diff --git a/CMakeLists.txt b/CMakeLists.txt index 69dc0253..ab399104 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -391,6 +391,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(expert_cache_per_layer_test PRIVATE strata_engine) add_test(NAME expert_cache_per_layer_test COMMAND expert_cache_per_layer_test) set_tests_properties(expert_cache_per_layer_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_executable(expert_cache_segmented_test tests/core/expert_cache_segmented_test.cpp) + target_link_libraries(expert_cache_segmented_test PRIVATE strata_engine) + add_test(NAME expert_cache_segmented_test COMMAND expert_cache_segmented_test) + set_tests_properties(expert_cache_segmented_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) endif() if(STRATA_BUILD_CONVERSATION_TESTS) add_executable(conversation_snapshot_test src/core/conversation_snapshot_test.cpp) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 876e6406..dc64a554 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -441,6 +441,18 @@ the OS file cache, so loading again takes seconds while that RAM is not needed e 16 GB with Q2_0 in the low-RAM mode: unloading takes ~0.3 s, and a request to an unloaded model answered after 4.6 s (text) or 14.7 s (a picture, image encoder on the CPU). +**Giving part of the VRAM back while it keeps serving (#533, opt-in, one NVIDIA GPU).** With `"vram_elastic": true` +in the config (the engine flag `--vram-elastic`), the expert cache is allocated in 512 MiB segments +(`"vram_segment_mib"`), and `POST /v1/vram` with `{"reserve_mib": 8000}` shrinks it between requests until that much +VRAM is free for another program; `{"reserve_mib": null}` grows it back towards its full size, keeping the reserve +the engine started with (`--vram-reserve-mib`), and `{"reserve_mib": 0}` takes all of it back. A request that is +running finishes first. The experts of the segments given back are computed on the CPU, like any expert outside the +cache, so answers keep coming, slower; growing back puts the same experts in the same slots. Nothing resizes on its +own. Not with a layer split, the helper caches, `--peer-device` or the resident low-RAM mode. Measured on an RTX 5070 +12 GB with Q2_0 (4.8 GiB cache): `{"reserve_mib": 6000}` took 78 ms and freed 4.3 GiB (the cache keeps 0.5 GiB for +the prompt path), decode 44 -> 33 tok/s; growing back took 92 ms and the answers were token for token the ones before +the shrink. Without the flag nothing changes (the same answers as without it). + **Keep what the expert cache learned across restarts (opt-in, engine 0.1.36, #477):** a start fills the GPU's expert cache from the shipped profile, and the adaptive tier (`--adapt-every`) then moves in the experts your requests use. With `"expert_profile_save": "expert-profile-learned.bin"` in `strata-.json` the engine saves that as a diff --git a/include/strata/core/expert_cache.hpp b/include/strata/core/expert_cache.hpp index a5061bf0..2730a03d 100644 --- a/include/strata/core/expert_cache.hpp +++ b/include/strata/core/expert_cache.hpp @@ -89,13 +89,44 @@ public: void close(); bool valid() const { return base_ != nullptr; } - int64_t slots() const { return slots_; } + /// The slots usable now: all of them, unless `shrink` gave the tail's VRAM back (#533) - then the ones wholly + /// inside the VRAM still backed, always a prefix. The prompt path's loan (the last slots) and every report + /// follow this; `full_slots()` is what `open` allocated. + int64_t slots() const { return live_slots_; } + int64_t full_slots() const { return slots_; } /// Slots actually claimed. Not the same as `slots()` - the cache does not evict, so a run that routes /// fewer distinct experts than there are slots leaves the rest empty. int64_t resident() const { return per_layer_ ? admitted_ : next_free_; } - int64_t bytes() const { return off_.empty() ? slots_ * blob_ : (int64_t) off_.back(); } + /// The bytes of `slots()` (all of the arena unless shrunk); `full_bytes()`: of every slot. + int64_t bytes() const { return slot_end(live_slots_); } + int64_t full_bytes() const { return slot_end(slots_); } double gib() const { return (double) bytes() / 1073741824.0; } + /// **#533: HOT VRAM RESIZE, OPT-IN (--vram-elastic).** With a segment size set before `open`/`open_sized`, the + /// arena is one reserved address range backed by physical segments of that size (CUDA virtual memory + /// management) instead of one cudaMalloc, so `shrink` can give the tail's VRAM back to the driver - for another + /// program - and `grow` can take it again, while every slot keeps its address (the captured graphs, the verify + /// plan's pointers and the prompt path's loan all hold addresses into it). 0 (the default): one cudaMalloc, as + /// always. CUDA only: a HIP build refuses it at open. The slots past `slots()` after a shrink must hold no + /// resident expert and no loan: the CALLER evicts them first (they become CPU misses). + void set_segment_bytes(int64_t seg_bytes) { seg_req_ = seg_bytes > 0 ? seg_bytes : 0; } + bool segmented() const { return !segs_.empty(); } + int64_t segment_bytes() const { return seg_; } + /// Bytes of the arena backed by VRAM now (a whole number of segments; the arena when not segmented). + int64_t mapped_bytes() const; + /// Unmaps every segment past the first `keep_bytes` (rounded UP to a segment boundary): `slots()` becomes the + /// slots wholly inside what stays. Waits for the device first. False with `err` when not segmented or a driver + /// call failed. + bool shrink(int64_t keep_bytes, std::string& err); + /// Maps segments again up to `want_bytes` (rounded DOWN to a segment, at most the arena; the last, shorter + /// segment only when `want_bytes` covers the arena). Stops at the first segment the driver cannot back (false, + /// `err`: what was mapped by then stays). The new slots are empty until the caller fills them. + bool grow(int64_t want_bytes, std::string& err); + /// The number of leading slots that fit wholly inside the first `bytes` bytes. + int64_t slots_within(int64_t bytes) const; + /// The bytes the first `n` slots span. + int64_t bytes_of(int64_t n) const { return slot_end(n < 0 ? 0 : n > slots_ ? slots_ : n); } + /// `(layer, expert)` -> slot index, or `kNotResident`. Bounds-checked: a bad layer or expert returns /// `kNotResident` rather than reading whatever is adjacent in the table. int32_t slot_of(int64_t layer, int64_t expert) const; @@ -160,7 +191,17 @@ private: uint8_t* blocking_staging_ = nullptr; std::size_t blocking_staging_bytes_ = 0; #endif + int64_t slot_end(int64_t n) const { return off_.empty() ? n * blob_ : (int64_t) off_[(size_t) n]; } + bool open_segmented(uint64_t want, std::string& err); + void release_segmented(); uint8_t* base_ = nullptr; + int64_t live_slots_ = 0; ///< #533: slots() - all of them unless shrunk + int64_t seg_req_ = 0; ///< #533: the segment size asked for (0: one cudaMalloc) + int64_t seg_ = 0; ///< #533: the segment size used (a multiple of the driver's granularity) + uint64_t reserved_ = 0; ///< #533: the reserved address range's size + std::vector segs_; ///< #533: each segment's physical handle (0: unmapped) + std::vector seg_size_; ///< #533: each segment's size (the last one may be shorter) + int64_t mapped_segs_ = 0; ///< #533: segments [0, mapped_segs_) are backed std::vector residency_; ///< [n_layers * n_expert] -> slot or kNotResident int64_t slots_ = 0; int64_t n_layers_ = 0; diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index b80d10bd..f146046d 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -60,6 +60,9 @@ public: /// The watchdog's view of the window in flight (issue #31): the layer, the GPU's sequence, the flags. void diag(std::FILE* f) const; + /// #649 (STRATA_VERIFY_TRACE=1, opt-in): the last windows' host-side handshake events and the GPU's breadcrumbs + /// (in mapped memory, so they read while the GPU hangs). Nothing when the trace is off. + void trace_dump(std::FILE* f) const; /// #267: raise every flag the window's spin kernels wait on past any ring (UINT32_MAX), so a window the GPU /// cannot finish drains instead of staying resident, then wait up to `timeout_ms` for its streams. For the @@ -184,6 +187,12 @@ private: bool ple_stage() const { return lb_ <= 1 && 1 < le_; } ///< holds layer 1, where the PLE block runs bool capture_commit(std::string& err); bool record_window(int T, cudaStream_t cs, std::string& err); + // #649: STRATA_VERIFY_TRACE=1 - a host event ring (trace_ev) and GPU breadcrumbs: the profiler's stamp points, + // per layer and token group, written to mapped memory (null when the trace is off) + void trace_ev(const char* what, int64_t step, int64_t layer, int64_t aux) const; + unsigned long long* trace_h_ = nullptr; + unsigned long long* trace_m_ = nullptr; + size_t trace_n_ = 0; static constexpr int kProfPer = 33; // stamps per layer (32 left the hc-read second // half's up-stamp at slot 32 = the next layer's slot 0: D8) bool prof_on_ = false; diff --git a/include/strata/kernels/elementwise.hpp b/include/strata/kernels/elementwise.hpp index 02501beb..543d75dc 100644 --- a/include/strata/kernels/elementwise.hpp +++ b/include/strata/kernels/elementwise.hpp @@ -114,6 +114,10 @@ void copy_rows_from_mapped(float* dst, const float* src, int64_t rows, int64_t w /// device-to-host memcpy nodes (copy-engine operations in the middle of the layer chain) and the ring kernel. void doorbell_publish(const float* x, const int32_t* ids, const float* weights, int64_t n, int64_t k, float* x_out, int32_t* ids_out, float* weights_out, uint32_t* d_seq, void* stream); +/// #649 (HIP, STRATA_DOORBELL_STORE=1): the ring stored as `value` instead of incremented over PCIe. +void doorbell_publish_value(const float* x, const int32_t* ids, const float* weights, int64_t n, int64_t k, + float* x_out, int32_t* ids_out, float* weights_out, uint32_t* d_seq, uint32_t value, + void* stream); /// Plan v0.3 P3: copy `n` int32 from mapped pinned host memory into device memory with a kernel (the QSA /// per-token step and positions), instead of a host-to-device memcpy node in the middle of a layer. diff --git a/include/strata/kernels/kv_stream.hpp b/include/strata/kernels/kv_stream.hpp index b3ebee34..514474b1 100644 --- a/include/strata/kernels/kv_stream.hpp +++ b/include/strata/kernels/kv_stream.hpp @@ -85,6 +85,12 @@ void kv_ring_restore(const QsaAttnPools& slots, const KvHostPools& host, int fmt void kv_stage_from_host(const QsaAttnPools& stage, const KvHostPools& host, int fmt, int64_t n_blocks, const QsaShapes& s, void* stream); +/// #579 #613 (HIP A/B, STRATA_KV_HOST_DMA=1): the reverse of kv_stage_from_host for blocks [b0, b1) - the staging +/// pool's blocks into the host copy, by DMA, so the prompt path's append need not write host memory from a kernel. +/// Not capturable. +void kv_unstage_to_host(const QsaAttnPools& stage, const KvHostPools& host, int fmt, int64_t b0, int64_t b1, + const QsaShapes& s, void* stream); + struct KvStreamCounters { uint64_t misses = 0, lookups = 0, calls = 0; bool overflow = false; diff --git a/serve/server.py b/serve/server.py index 78022ba6..cdf0cceb 100644 --- a/serve/server.py +++ b/serve/server.py @@ -554,6 +554,37 @@ class StrataEngine: if len(f) >= 16: # #588 (engine 0.1.39+): routed experts read over PCIe self.last.update(offloaded=int(f[15])) + def vram(self, reserve_mib: int | None, timeout: float = 120.0) -> dict: + """#533: `VRAM ` between requests (the caller holds the service's FIFO): the engine shrinks its + expert cache until that much VRAM is free, or grows it back when more is free; None: back to the reserve it + started with. -> the engine's figures (expert_slots, expert_cache_mib, vram_free_mib, ...); raises ValueError + with the engine's reason (e.g. it was not started with --vram-elastic), EngineDied when it ended.""" + if not self.alive(): + raise EngineDied("the engine is not running") + self.proc.stdin.write("VRAM" + ("" if reserve_mib is None else f" {int(reserve_mib)}") + "\n") + self.proc.stdin.flush() + deadline = time.time() + timeout + while True: + try: + line = self.lines.get(timeout=max(0.1, deadline - time.time())) + except queue.Empty: + raise EngineDied("the engine did not answer the VRAM command") from None + if line is None: + raise EngineDied("the engine ended") + line = line.strip() + if line.startswith("ERR"): + raise ValueError(line[4:].strip() or "the engine refused the VRAM command") + if line.startswith("VRAM "): + out = {} + for kv in line.split()[1:]: + k, _, v = kv.partition("=") + out[k] = int(v) if v.lstrip("-").isdigit() else v + self.info.update({k: out[k] for k in ("expert_slots", "vram_free_mib") if k in out}) + self.info["vram"] = out + return out + if time.time() > deadline: + raise EngineDied("the engine did not answer the VRAM command") + @staticmethod def sampling_keys(sampling: dict) -> str: keys = "" @@ -967,6 +998,13 @@ def engine_args(cfg: dict) -> list[str]: # opt-in: an auto split runs on the first card alone when it holds every profiled expert and the KV if len(gpu_list(cfg)) > 1 and cfg.get("split_skip_if_fits") and "--split-skip-if-fits" not in args: args.append("--split-skip-if-fits") + # #533 (opt-in): "vram_elastic": true - the expert cache in segments, so POST /v1/vram can give VRAM back to other + # programs and take it back; "vram_segment_mib" sets the segment size (the engine's default: 512) + if cfg.get("vram_elastic") is True and "--vram-elastic" not in args: + args.append("--vram-elastic") + seg = cfg.get("vram_segment_mib") + if isinstance(seg, int) and not isinstance(seg, bool) and seg > 0 and "--vram-segment-mib" not in args: + args += ["--vram-segment-mib", str(seg)] return learned_profile_args(cfg, args) @@ -1166,6 +1204,7 @@ class Service: self.idle_unload_s = 0 self.min_free_vram_mib = 0 self.before_load = None + self.vram_reserve = None # #533: the last POST /v1/vram reserve (None: the start's) self.reasoning_budget_tokens = 0 # #123: the config's default thinking budget (0: none) self.repeat_stop_tokens = REPEAT_STOP_TOKENS # #606: one token this many times in a row ends a reply (0: off) self.anthropic_think_unasked = True # #278: "anthropic_thinking": "on_request" -> False @@ -1267,6 +1306,35 @@ class Service: "(a minute or two) ...", flush=True) self.engine.restart() print("[strata] the engine is running again", flush=True) + if self.vram_reserve is not None and hasattr(self.engine, "vram"): # #533: the reserve asked for last + try: + self.engine.vram(self.vram_reserve) + except (ValueError, EngineDied) as e: + print(f"[strata] the VRAM reserve ({self.vram_reserve} MiB) was not applied: {e}", flush=True) + + vram_wait_s = 300.0 # #533: how long POST /v1/vram waits for a running request + + def vram(self, reserve_mib: int | None) -> dict: + """#533, POST /v1/vram: keep `reserve_mib` of VRAM free for other programs (None: the reserve the engine + started with), applied between requests - a request that is running finishes first (up to wait_s). Only an + engine started with --vram-elastic (the config's "vram_elastic": true) can do it; it never resizes on its own. + An unloaded engine applies it when it loads. -> {"status": ..., and the engine's figures}.""" + if not hasattr(self.engine, "vram"): + raise ValueError("this engine cannot resize its VRAM use") + if not self.fifo.acquire(timeout=self.vram_wait_s): + raise ModelBusy("a request is still running; try again when it has finished") + try: + if not self.loaded(): + self.vram_reserve = reserve_mib + return {"status": "not loaded", "reserve_mib": reserve_mib, + "note": "applied when the model loads"} + out = self.engine.vram(reserve_mib) + self.vram_reserve = reserve_mib + print(f"[strata] VRAM: {out.get('vram_free_mib')} MiB free, expert cache {out.get('expert_cache_mib')} of " + f"{out.get('expert_cache_full_mib')} MiB ({out.get('expert_slots')} experts)", flush=True) + return {"status": "ok", **out} + finally: + self.fifo.release() def _say_died(self, e: Exception) -> None: """The server window's line for an engine that died (or was ended, #481) in the middle of a request.""" @@ -1507,6 +1575,8 @@ class Service: "activity": {"requests": totals["requests"] + int(busy), "in_flight": int(busy) + int(s.get("queued") or 0), "last_request_at": int(last_at) if last_at else None}, "last_timings": last_t, + "vram": dict((getattr(self.engine, "info", {}) or {}).get("vram") or {}, + elastic=bool((getattr(self.engine, "info", {}) or {}).get("vram_elastic"))), "machine": { "at": int(time.time()), "gpu": {"name": static.get("gpu_name"), "used_mib": scaled(hw.get("gpu_mem_used"), 2 ** 20), @@ -2521,6 +2591,17 @@ def make_handler(svc: Service): result = "loaded" self._json(200, {"status": result, **svc.v1_status()}) return + if path == "/v1/vram": # #533: give VRAM back to other programs, or take it + if not self._own_page("the VRAM reserve can be changed"): + return + r = req.get("reserve_mib") + if r is not None and (isinstance(r, bool) or not isinstance(r, int) or r < 0): + raise ValueError("reserve_mib: a whole number of MiB (0 or more), or null for the start's") + try: + self._json(200, svc.vram(r)) + except EngineDied as e: + self._json(503, {"error": {"type": "server_error", "message": str(e)}}) + return if path in ("/v1/chat/completions", "/v1/messages", "/v1/responses"): self.record = svc.begin_request(path, req) if path == "/v1/responses": diff --git a/serve/test_vram.py b/serve/test_vram.py new file mode 100644 index 00000000..e1abe0b6 --- /dev/null +++ b/serve/test_vram.py @@ -0,0 +1,136 @@ +"""#533: POST /v1/vram (opt-in hot VRAM resize) - the engine command, the route, the config key, a reserve kept for +an unloaded engine and applied when it loads again.""" +import io +import json +import queue +import unittest +import urllib.error +import urllib.request +from pathlib import Path +from unittest import mock + +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, EngineDied, Service, StrataEngine, engine_args, serve +from serve.test_lifecycle import ResidentEngine + + +class VramEngine(ResidentEngine): + """The resident test engine with an elastic cache: VRAM n frees what the reserve asks for, None takes the + start's (700 MiB).""" + def __init__(self, tok, elastic=True): + super().__init__(tok) + self.elastic, self.calls = elastic, [] + + def vram(self, reserve_mib, timeout=120.0): + self.calls.append(reserve_mib) + if not self.elastic: + raise ValueError("VRAM needs an engine started with --vram-elastic (one NVIDIA GPU, --serve)") + r = 700 if reserve_mib is None else reserve_mib + out = {"reserve_mib": r, "expert_slots": max(100, 4000 - r), "expert_cache_mib": max(500, 6000 - r), + "expert_cache_full_mib": 6000, "vram_free_mib": r, "prompt_chunk": 4096} + self.info["vram"] = out + return out + + +class EngineCommand(unittest.TestCase): + def engine(self, replies): + e = StrataEngine("missing-executable", [], lazy=True) + e.proc = mock.Mock() + e.proc.poll.return_value = None + e.proc.stdin = io.StringIO() + e.ended = False + e.lines = queue.Queue() + for r in replies: + e.lines.put(r) + return e + + def test_the_line_and_the_answer(self): + e = self.engine(["strata serve: something else\n", + "VRAM reserve_mib=6000 expert_slots=1200 expert_slots_full=3700 expert_cache_mib=1536 " + "expert_cache_full_mib=4900 vram_free_mib=6100 prompt_chunk=2048\n"]) + out = e.vram(6000) + self.assertEqual(e.proc.stdin.getvalue(), "VRAM 6000\n") + self.assertEqual(out["expert_slots"], 1200) + self.assertEqual(out["prompt_chunk"], 2048) + self.assertEqual(e.info["expert_slots"], 1200) + e = self.engine(["VRAM reserve_mib=700 expert_slots=3700\n"]) + e.vram(None) + self.assertEqual(e.proc.stdin.getvalue(), "VRAM\n") + + def test_refused_and_died(self): + e = self.engine(["ERR VRAM needs an engine started with --vram-elastic\n"]) + with self.assertRaisesRegex(ValueError, "--vram-elastic"): + e.vram(100) + e = self.engine([None]) + with self.assertRaises(EngineDied): + e.vram(100) + + def test_config_key(self): + cfg = {"args": ["--max-context", "8192"]} + self.assertEqual(engine_args(cfg), ["--max-context", "8192"]) # off unless asked + self.assertEqual(engine_args({**cfg, "vram_elastic": True, "vram_segment_mib": 256}), + ["--max-context", "8192", "--vram-elastic", "--vram-segment-mib", "256"]) + self.assertEqual(engine_args({**cfg, "vram_elastic": "yes"}), ["--max-context", "8192"]) + + +class Route(unittest.TestCase): + def setUp(self): + tok = ByteTokenizer() + self.engine = VramEngine(tok) + self.svc = Service(self.engine, tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def request(self, path, body=None, headers=None): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode() if body is not None else None, + headers={"Content-Type": "application/json", **(headers or {})}) + try: + response = urllib.request.urlopen(req, timeout=10) + except urllib.error.HTTPError as error: + response = error + with response: + return response.status, json.loads(response.read().decode()) + + def test_resize_and_status(self): + self.engine.loaded = True + code, body = self.request("/v1/vram", {"reserve_mib": 4000}) + self.assertEqual(code, 200, body) + self.assertEqual(body["status"], "ok") + self.assertEqual(body["expert_cache_mib"], 2000) + self.assertEqual(self.request("/v1/status")[1]["vram"]["expert_cache_mib"], 2000) + code, body = self.request("/v1/vram", {"reserve_mib": None}) # back to the start's reserve + self.assertEqual(code, 200) + self.assertEqual(self.engine.calls, [4000, None]) + + def test_bad_input_busy_and_foreign_pages(self): + self.engine.loaded = True + for bad in ({"reserve_mib": -1}, {"reserve_mib": "8 GiB"}, {"reserve_mib": True}, {"reserve_mib": 1.5}): + self.assertEqual(self.request("/v1/vram", bad)[0], 400, bad) + self.assertEqual(self.request("/v1/vram", {"reserve_mib": 1}, {"Origin": "https://other.example"})[0], 403) + self.assertEqual(self.request("/v1/vram", {"reserve_mib": 1}, {"Content-Type": "text/plain"})[0], 415) + self.svc.vram_wait_s = 0.2 + with self.svc.fifo: # a request is running + self.assertEqual(self.request("/v1/vram", {"reserve_mib": 1})[0], 409) + self.assertEqual(self.engine.calls, []) + + def test_an_engine_without_the_flag_says_so(self): + self.engine.loaded, self.engine.elastic = True, False + code, body = self.request("/v1/vram", {"reserve_mib": 3000}) + self.assertEqual(code, 400) + self.assertIn("--vram-elastic", body["error"]["message"]) + + def test_unloaded_keeps_the_reserve_for_the_next_load(self): + code, body = self.request("/v1/vram", {"reserve_mib": 5000}) + self.assertEqual(code, 200) + self.assertEqual(body["status"], "not loaded") + self.assertEqual(self.engine.calls, []) + self.assertEqual(self.request("/v1/load", {})[0], 200) + self.assertEqual(self.engine.calls, [5000]) + + +if __name__ == "__main__": + unittest.main() diff --git a/setup.py b/setup.py index 05dda6aa..acd99f68 100644 --- a/setup.py +++ b/setup.py @@ -316,6 +316,74 @@ def page_file_gb(): return max(0.0, (m.ullTotalPageFile - m.ullTotalPhys) / 2**30) +def cpu_cores(): + """#642: (performance cores, efficiency cores) of a hybrid CPU (Intel 12th gen+, AMD Zen 5 + Zen 5c), counted + as the engine's pool counts them (detect_cpu_topology: physical cores, by Windows' EfficiencyClass or Linux's + cpu_capacity); None on a CPU whose cores are all alike, or when the OS does not say.""" + classes = [] # one entry per physical core: its efficiency/capacity class + try: + if WIN: + k32 = ctypes.windll.kernel32 + n = ctypes.c_ulong(0) + k32.GetLogicalProcessorInformationEx(0, None, ctypes.byref(n)) # RelationProcessorCore: the size + if not n.value: + return None + buf = ctypes.create_string_buffer(n.value) + if not k32.GetLogicalProcessorInformationEx(0, buf, ctypes.byref(n)): + return None + raw, at = buf.raw[:n.value], 0 + while at + 10 <= len(raw): # SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX: Relationship, Size, then + rel, size = struct.unpack_from(" int | None: + """#642 (Hardin22's measurement): on a hybrid CPU the expert pool runs best on the P-cores but the host loop's one + plus HALF of the E-cores - an E-core runs the expert kernels ~2.2x slower and each layer waits for its slowest + part (i9-14900KF, 8P + 16E: 15 workers decoded 165 / 116 tok/s against 106 / 84 with all 23). Only on a CPU with + more E-cores than P-cores: on an i7-13700KF (8P + 8E, docs/AMD_HIP.md's gfx1030 report) all 15 workers decoded + 38-42 tok/s against 36 with 8, so there the engine's own count stays. None: the engine's own default (one worker + per physical core but the host's) stays.""" + if not cores: + return None + p, e = cores + if e <= p: + return None + return max(1, p - 1 + e // 2) + + +def recommend_pool_workers(args: list) -> list: + """`args` with setup's recommended `--pool-workers` for a hybrid CPU, unless they set one already (a calibration's + measured count, or the user's own). A recommendation: the config line can be edited or removed.""" + n = hybrid_pool_workers(cpu_cores()) + if n is None or "--pool-workers" in args: + return args + p, e = cpu_cores() + ok(f"hybrid CPU ({p} performance + {e} efficiency cores): {n} CPU expert workers - the performance cores and half " + "of the efficiency cores (--pool-workers in the config; START-HERE --calibrate measures it on this PC)") + return [*args, "--pool-workers", str(n)] + + def cpu_info(): """(name, avx2, avx512): avx512 means everything Strata's fast AVX-512 kernels use (F, BW, VL, VNNI, VBMI), the same test the engine makes (cpu_avx512_ok), not just AVX-512F.""" @@ -3922,6 +3990,8 @@ def main() -> int: import calibrate as CAL cfg["args"] = CAL.apply(cfg["args"], cal.get("settings") or {}) ok("the settings tuned for this PC earlier are used" + (f" ({cal['date']})" if cal.get("date") else "")) + else: # #642: measured counts (a calibration) win over the rule + cfg["args"] = recommend_pool_workers(cfg["args"]) write_setup_config(cfg_path, cfg, adopted if adopted is not None and adopted.name == cfg_path.name else None) script = write_run_script(tag, cfg_path, port, cfg.get("open_browser") is not False) # offered only when someone answers: --yes installs and adopted earlier installs are not held up by it diff --git a/src/core/expert_cache.cpp b/src/core/expert_cache.cpp index dc644436..e25f60e9 100644 --- a/src/core/expert_cache.cpp +++ b/src/core/expert_cache.cpp @@ -2,6 +2,9 @@ #include "strata/core/expert_cache.hpp" #include +#if !defined(STRATA_USE_HIP) +#include // #533: the virtual memory management types (the functions come through the runtime's entry points) +#endif #include #include @@ -142,6 +145,239 @@ bool write_expert_profile(const std::string& path, int64_t n_layers, int64_t n_e ExpertCache::~ExpertCache() { close(); } +// ---- #533: the segmented arena (--vram-elastic). The driver API's virtual memory functions, looked up through the +// runtime (no link against the driver library): one address range for the whole arena, backed by physical segments, +// and the tail's segments unmapped / mapped again later. Nothing here runs unless a segment size was set. +#if !defined(STRATA_USE_HIP) +namespace { +struct Vmm { + CUresult (CUDAAPI* device_get)(CUdevice*, int) = nullptr; + CUresult (CUDAAPI* attribute)(int*, CUdevice_attribute, CUdevice) = nullptr; + CUresult (CUDAAPI* granularity)(size_t*, const CUmemAllocationProp*, CUmemAllocationGranularity_flags) = nullptr; + CUresult (CUDAAPI* reserve)(CUdeviceptr*, size_t, size_t, CUdeviceptr, unsigned long long) = nullptr; + CUresult (CUDAAPI* address_free)(CUdeviceptr, size_t) = nullptr; + CUresult (CUDAAPI* create)(CUmemGenericAllocationHandle*, size_t, const CUmemAllocationProp*, + unsigned long long) = nullptr; + CUresult (CUDAAPI* release)(CUmemGenericAllocationHandle) = nullptr; + CUresult (CUDAAPI* map)(CUdeviceptr, size_t, size_t, CUmemGenericAllocationHandle, unsigned long long) = nullptr; + CUresult (CUDAAPI* unmap)(CUdeviceptr, size_t) = nullptr; + CUresult (CUDAAPI* set_access)(CUdeviceptr, size_t, const CUmemAccessDesc*, size_t) = nullptr; + bool ok = false; +}; + +template bool entry(const char* name, F& f) { + void* p = nullptr; + cudaDriverEntryPointQueryResult q{}; +#if CUDART_VERSION >= 12050 + const cudaError_t e = cudaGetDriverEntryPointByVersion(name, &p, 12000, cudaEnableDefault, &q); +#else + const cudaError_t e = cudaGetDriverEntryPoint(name, &p, cudaEnableDefault, &q); +#endif + if (e != cudaSuccess || q != cudaDriverEntryPointSuccess || p == nullptr) { + (void) cudaGetLastError(); + return false; + } + f = reinterpret_cast(p); + return true; +} + +const Vmm& vmm() { + static const Vmm v = [] { + Vmm x; + x.ok = entry("cuDeviceGet", x.device_get) && entry("cuDeviceGetAttribute", x.attribute) && + entry("cuMemGetAllocationGranularity", x.granularity) && entry("cuMemAddressReserve", x.reserve) && + entry("cuMemAddressFree", x.address_free) && entry("cuMemCreate", x.create) && + entry("cuMemRelease", x.release) && entry("cuMemMap", x.map) && entry("cuMemUnmap", x.unmap) && + entry("cuMemSetAccess", x.set_access); + return x; + }(); + return v; +} + +CUmemAllocationProp device_prop(int dev) { + CUmemAllocationProp prop{}; + prop.type = CU_MEM_ALLOCATION_TYPE_PINNED; + prop.location.type = CU_MEM_LOCATION_TYPE_DEVICE; + prop.location.id = dev; + return prop; +} + +// one segment: a physical allocation mapped at `va`, readable and writable by this device +bool map_segment(const Vmm& v, int dev, CUdeviceptr va, size_t bytes, unsigned long long& handle) { + const CUmemAllocationProp prop = device_prop(dev); + CUmemGenericAllocationHandle h = 0; + if (v.create(&h, bytes, &prop, 0) != CUDA_SUCCESS) return false; + if (v.map(va, bytes, 0, h, 0) != CUDA_SUCCESS) { + v.release(h); + return false; + } + CUmemAccessDesc access{}; + access.location.type = CU_MEM_LOCATION_TYPE_DEVICE; + access.location.id = dev; + access.flags = CU_MEM_ACCESS_FLAGS_PROT_READWRITE; + if (v.set_access(va, bytes, &access, 1) != CUDA_SUCCESS) { + v.unmap(va, bytes); + v.release(h); + return false; + } + handle = (unsigned long long) h; + return true; +} +} // namespace +#endif + +bool ExpertCache::open_segmented(uint64_t want, std::string& err) { +#if defined(STRATA_USE_HIP) + (void) want; + err = "ExpertCache: --vram-elastic (a segmented expert cache) is CUDA-only for now"; + return false; +#else + const Vmm& v = vmm(); + int dev = 0, supported = 0; + CUdevice cu = 0; + if (!v.ok || cudaGetDevice(&dev) != cudaSuccess || v.device_get(&cu, dev) != CUDA_SUCCESS || + v.attribute(&supported, CU_DEVICE_ATTRIBUTE_VIRTUAL_MEMORY_MANAGEMENT_SUPPORTED, cu) != CUDA_SUCCESS || + !supported) { + err = "ExpertCache: --vram-elastic needs the driver's virtual memory management, which this GPU or driver " + "does not offer"; + return false; + } + const CUmemAllocationProp prop = device_prop(dev); + size_t gran = 0; + if (v.granularity(&gran, &prop, CU_MEM_ALLOC_GRANULARITY_RECOMMENDED) != CUDA_SUCCESS || gran == 0) { + err = "ExpertCache: cannot read the driver's allocation granularity"; + return false; + } + const uint64_t g = (uint64_t) gran; + const uint64_t total = (want + g - 1) / g * g; + seg_ = (int64_t) (((uint64_t) seg_req_ + g - 1) / g * g); + CUdeviceptr va = 0; + if (v.reserve(&va, (size_t) total, 0, 0, 0) != CUDA_SUCCESS) { + err = "ExpertCache: cannot reserve the address range of the segmented expert cache"; + return false; + } + base_ = reinterpret_cast(va); + reserved_ = total; + for (uint64_t at = 0; at < total; at += (uint64_t) seg_) { + segs_.push_back(0); + seg_size_.push_back((int64_t) std::min((uint64_t) seg_, total - at)); + } + for (size_t i = 0; i < segs_.size(); ++i) { + if (!map_segment(v, dev, va + (CUdeviceptr) ((uint64_t) i * (uint64_t) seg_), (size_t) seg_size_[i], + segs_[i])) { + char buf[200]; + std::snprintf(buf, sizeof buf, "ExpertCache: cudaMalloc failed: segment %zu of %zu (%.2f GiB) of the " + "segmented cache could not be allocated", i + 1, segs_.size(), + (double) seg_size_[i] / 1073741824.0); + err = buf; // "cudaMalloc failed": the auto cache's smaller-retry path reads it as an allocation failure + release_segmented(); + return false; + } + mapped_segs_ = (int64_t) i + 1; + } + return true; +#endif +} + +void ExpertCache::release_segmented() { +#if !defined(STRATA_USE_HIP) + const Vmm& v = vmm(); + if (base_ != nullptr) cudaDeviceSynchronize(); + const CUdeviceptr va = reinterpret_cast(base_); + for (size_t i = 0; i < segs_.size(); ++i) + if (segs_[i] != 0) { + v.unmap(va + (CUdeviceptr) ((uint64_t) i * (uint64_t) seg_), (size_t) seg_size_[i]); + v.release((CUmemGenericAllocationHandle) segs_[i]); + } + if (base_ != nullptr && reserved_ > 0) v.address_free(va, (size_t) reserved_); +#endif + segs_.clear(); + seg_size_.clear(); + mapped_segs_ = 0; + reserved_ = 0; + base_ = nullptr; +} + +int64_t ExpertCache::mapped_bytes() const { + if (segs_.empty()) return base_ != nullptr ? full_bytes() : 0; + int64_t b = 0; + for (int64_t i = 0; i < mapped_segs_; ++i) b += seg_size_[(size_t) i]; + return b; +} + +int64_t ExpertCache::slots_within(int64_t bytes) const { + if (bytes >= full_bytes()) return slots_; + if (bytes <= 0) return 0; + if (off_.empty()) return blob_ > 0 ? bytes / blob_ : 0; + // off_[i + 1] is slot i's end: count the slots whose end is at most `bytes` + return (int64_t) (std::upper_bound(off_.begin() + 1, off_.end(), (uint64_t) bytes) - (off_.begin() + 1)); +} + +bool ExpertCache::shrink(int64_t keep_bytes, std::string& err) { + if (segs_.empty()) { + err = "the expert cache is not segmented (the engine needs --vram-elastic)"; + return false; + } +#if defined(STRATA_USE_HIP) + (void) keep_bytes; + return false; +#else + const Vmm& v = vmm(); + int64_t keep = 0, at = 0; // the segments [0, keep) hold the first keep_bytes + while (keep < (int64_t) segs_.size() && at < keep_bytes) at += seg_size_[(size_t) keep++]; + if (keep >= mapped_segs_) return true; + if (cudaDeviceSynchronize() != cudaSuccess) { + err = std::string("the device failed before the cache shrank: ") + cudaGetErrorString(cudaGetLastError()); + return false; + } + const CUdeviceptr va = reinterpret_cast(base_); + for (int64_t i = mapped_segs_ - 1; i >= keep; --i) { + const CUdeviceptr p = va + (CUdeviceptr) ((uint64_t) i * (uint64_t) seg_); + if (v.unmap(p, (size_t) seg_size_[(size_t) i]) != CUDA_SUCCESS || + v.release((CUmemGenericAllocationHandle) segs_[(size_t) i]) != CUDA_SUCCESS) { + err = "the driver refused to release an expert-cache segment"; + live_slots_ = slots_within(mapped_bytes()); + return false; + } + segs_[(size_t) i] = 0; + mapped_segs_ = i; + } + live_slots_ = slots_within(mapped_bytes()); + return true; +#endif +} + +bool ExpertCache::grow(int64_t want_bytes, std::string& err) { + if (segs_.empty()) { + err = "the expert cache is not segmented (the engine needs --vram-elastic)"; + return false; + } +#if defined(STRATA_USE_HIP) + (void) want_bytes; + return false; +#else + const Vmm& v = vmm(); + int dev = 0; + cudaGetDevice(&dev); + const CUdeviceptr va = reinterpret_cast(base_); + int64_t at = mapped_bytes(); + while (mapped_segs_ < (int64_t) segs_.size() && at + seg_size_[(size_t) mapped_segs_] <= want_bytes) { + const size_t i = (size_t) mapped_segs_; + if (!map_segment(v, dev, va + (CUdeviceptr) ((uint64_t) i * (uint64_t) seg_), (size_t) seg_size_[i], + segs_[i])) { + (void) cudaGetLastError(); + err = "the driver has no VRAM for another expert-cache segment"; + live_slots_ = slots_within(mapped_bytes()); + return false; + } + at += seg_size_[i]; + ++mapped_segs_; + } + live_slots_ = slots_within(mapped_bytes()); + return true; +#endif +} + #if defined(STRATA_USE_HIP) bool ExpertCache::ensure_blocking_staging(std::size_t bytes, std::string& err) { if (bytes <= blocking_staging_bytes_) return true; @@ -193,7 +429,9 @@ bool ExpertCache::open(int64_t n_slots, int64_t n_layers, int64_t n_expert, int6 } } - if (cudaMalloc((void**) &base_, (size_t) want) != cudaSuccess) { + if (seg_req_ > 0) { // #533: --vram-elastic: physical segments behind one address range (zeroed below) + if (!open_segmented(want, err)) return false; + } else if (cudaMalloc((void**) &base_, (size_t) want) != cudaSuccess) { base_ = nullptr; char buf[256]; std::snprintf(buf, sizeof buf, "ExpertCache: cudaMalloc(%.2f GiB) failed: %s", @@ -211,6 +449,7 @@ bool ExpertCache::open(int64_t n_slots, int64_t n_layers, int64_t n_expert, int6 residency_.assign((size_t) (n_layers * n_expert), kNotResident); slots_ = n_slots; + live_slots_ = n_slots; n_layers_ = n_layers; n_expert_ = n_expert; blob_ = blob_bytes; @@ -247,6 +486,7 @@ bool ExpertCache::open_sized(const std::vector& slot_bytes, int64_t n_l // one allocation of the summed size, through the uniform path's checks: n "slots" of 1 byte if (!open((int64_t) off.back(), n_layers, n_expert, 1, err)) return false; slots_ = (int64_t) slot_bytes.size(); + live_slots_ = slots_; blob_ = mx; off_ = std::move(off); #if defined(STRATA_USE_HIP) @@ -273,12 +513,15 @@ void ExpertCache::close() { blocking_staging_bytes_ = 0; #endif off_.clear(); - if (base_ != nullptr) { + if (!segs_.empty()) { + release_segmented(); + } else if (base_ != nullptr) { cudaFree(base_); base_ = nullptr; } residency_.clear(); slots_ = 0; + live_slots_ = 0; n_layers_ = 0; n_expert_ = 0; blob_ = 0; diff --git a/src/core/verify.cpp b/src/core/verify.cpp index f956d731..8a8b69bc 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -69,7 +69,29 @@ struct Bump { } }; +// #649 (HIP, opt-in A/Bs for the gfx1030 verify timeouts; CUDA never reads them) +// STRATA_VERIFY_COHERENT=1 the handshake words and rows in explicitly coherent (fine-grained) host memory +// STRATA_DOORBELL_STORE=1 the GPU stores each step's ring instead of read-modify-writing it over PCIe +bool env_on(const char* name) { + const char* e = std::getenv(name); + return e != nullptr && e[0] != 0 && e[0] != '0'; +} +#if defined(STRATA_USE_HIP) +const bool g_coherent = env_on("STRATA_VERIFY_COHERENT"); +const bool g_doorbell_store = env_on("STRATA_DOORBELL_STORE"); +#endif +const bool g_trace = env_on("STRATA_VERIFY_TRACE"); + bool mapped(size_t bytes, void** h, void** d) { +#if defined(STRATA_USE_HIP) + if (g_coherent) { + if (hipHostMalloc(h, bytes, hipHostMallocMapped | hipHostMallocCoherent | + (peer_portable() ? hipHostMallocPortable : 0)) != hipSuccess) + return false; + std::memset(*h, 0, bytes); + return cudaHostGetDevicePointer(d, *h, 0) == cudaSuccess; + } +#endif if (cudaHostAlloc(h, bytes, cudaHostAllocMapped | (peer_portable() ? cudaHostAllocPortable : 0)) != cudaSuccess) return false; // multi-GPU: portable only with a peer - the peer card writes its rows into them std::memset(*h, 0, bytes); return cudaHostGetDevicePointer(d, *h, 0) == cudaSuccess; @@ -122,6 +144,20 @@ void release_live_verifiers(std::FILE* f) { } if (f != nullptr) std::fflush(f); } +// #649: the host side of STRATA_VERIFY_TRACE - a ring of the last kTraceN handshake events of every verifier +struct TraceEv { + int64_t t_ns; + const void* who; + int64_t window, step, layer, aux; + uint32_t seq, flag, a, b; + const char* what; +}; +constexpr uint64_t kTraceN = 4096; +TraceEv g_trace_ring[kTraceN]; +std::atomic g_trace_next{0}; +int64_t trace_now_ns() { + return std::chrono::duration_cast(Clock::now().time_since_epoch()).count(); +} std::string released_note(bool drained) { return drained ? "; its GPU waits were released and the GPU finished (#267)" : "; its GPU waits were released but the GPU did not finish within 5 s (#267)"; @@ -136,6 +172,7 @@ const int64_t g_test_stall = [] { bool Verifier::release_gpu_waits(int timeout_ms) { released_.store(true); + trace_ev("RELEASE", -1, -1, timeout_ms); // the words the spin kernels read (wait_flag_ge, wait_flag_ge_or) are mapped host memory, so a store here // reaches them with no API call; UINT32_MAX is past every ring. (E-6's skip words are device memory, but // wait_flag_ge_or also returns on its flag.) A host function raising flag B later only raises. @@ -148,13 +185,76 @@ bool Verifier::release_gpu_waits(int timeout_ms) { for (cudaStream_t s : {cs_, copy_}) { if (s == nullptr) continue; while (cudaStreamQuery(s) == cudaErrorNotReady) { - if (ms_since(t0) > timeout_ms) return false; + if (ms_since(t0) > timeout_ms) { + trace_ev("RELEASE-NOT-DRAINED", -1, -1, (int64_t) ms_since(t0)); + return false; + } std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } + trace_ev("RELEASE-DRAINED", -1, -1, (int64_t) ms_since(t0)); // aux: ms the GPU took to finish once released return true; } +void Verifier::trace_ev(const char* what, int64_t step, int64_t layer, int64_t aux) const { + if (!g_trace) return; + auto rd = [](const uint32_t* p) { return p ? *(const volatile uint32_t*) p : 0u; }; + TraceEv& e = g_trace_ring[g_trace_next.fetch_add(1) % kTraceN]; + e = {trace_now_ns(), this, windows, step, layer, aux, rd(h_seq_), rd(h_flag_), rd(h_flagA_), rd(h_flagB_), what}; +} + +void Verifier::trace_dump(std::FILE* f) const { + if (!g_trace || f == nullptr) return; + static const char* names[kProfPer] = {"pre", "hc-read0", "qkv gemv", "conv", "ab", "z", "rec", "kv-idx", + "k/v rope", "kv append", "q", "scores+topk", "kv-resolve", "attention", + "gate", "", "out-proj", "router+ring", "shared", "waitA", "VRAM hits", "waitB", + "PCIe grp", "waitCPU", "combine", "", "head", "", "", "", "", "", ""}; + const uint64_t end = g_trace_next.load(); + const uint64_t n = end < 160 ? end : 160; + std::fprintf(f, "strata verify trace (#649): the last %llu handshake events (host clock, us before the last; " + "words: seq = GPU rang, flag = CPU served, A = plan, B = copies)\n", (unsigned long long) n); + const int64_t t_last = n ? g_trace_ring[(end - 1) % kTraceN].t_ns : 0; + for (uint64_t i = end - n; i < end; ++i) { + const TraceEv& e = g_trace_ring[i % kTraceN]; + if (e.what == nullptr) continue; + std::fprintf(f, " %10.1f %-20s v%p window %lld step %lld layer %lld aux %lld | seq %u flag %u A %u B %u\n", + (double) (t_last - e.t_ns) / 1000.0, e.what, e.who, (long long) e.window, (long long) e.step, + (long long) e.layer, (long long) e.aux, e.seq, e.flag, e.a, e.b); + } + if (trace_h_ == nullptr || g_ == nullptr) return; + // the breadcrumbs: every stamp point the GPU passed in this window (ns of the GPU clock after the window's first) + unsigned long long t0 = ~0ull; + for (size_t i = 0; i < trace_n_; ++i) { + const unsigned long long t = *(const volatile unsigned long long*) (trace_h_ + i); + if (t != 0 && t < t0) t0 = t; + } + if (t0 == ~0ull) { + std::fprintf(f, "strata verify trace: no GPU breadcrumb in this window (the GPU never started it)\n"); + return; + } + int64_t last_l = -1; + for (int64_t l = 0; l <= g_->n_layers; ++l) + for (int i = 0; i < kProfPer; ++i) + for (int grp = 0; grp < 2; ++grp) + if (trace_h_[(size_t) ((l * kProfPer + i) * 2 + grp)] != 0) last_l = l; + std::fprintf(f, "strata verify trace: GPU breadcrumbs (us after the window's first), the GPU got as far as layer " + "%lld:\n", (long long) last_l); + for (int64_t l = std::max(0, last_l - 2); l <= std::min(g_->n_layers, last_l + 1); ++l) + for (int grp = 0; grp < 2; ++grp) { + std::string line; + char b[64]; + for (int i = 0; i < kProfPer; ++i) { + const unsigned long long t = trace_h_[(size_t) ((l * kProfPer + i) * 2 + grp)]; + if (t == 0) continue; + std::snprintf(b, sizeof b, " %s(%d)=%.1f", names[i], i, (double) (t - t0) / 1000.0); + line += b; + } + if (!line.empty()) + std::fprintf(f, " layer %lld group %d:%s\n", (long long) l, grp, line.c_str()); + } + std::fflush(f); +} + void Verifier::diag(std::FILE* f) const { auto rd = [](const uint32_t* p) { return p ? *(const volatile uint32_t*) p : 0u; }; // #251: outside a verify stage these are the LAST window's numbers (it finished), not the stalled work's @@ -163,6 +263,7 @@ void Verifier::diag(std::FILE* f) const { std::fprintf(f, " verify window%s: %d tokens at position %lld, host at layer step %u; the GPU rang %u; flags: " "served %u, plan (A) %u, copies (B) %u\n", current ? "" : " (last window, not the current stage)", last_t_, (long long) last_pos0_, cur_layer_ + 1, rd(h_seq_), rd(h_flag_), rd(h_flagA_), rd(h_flagB_)); + trace_dump(f); // #649: STRATA_VERIFY_TRACE=1 only } Verifier::~Verifier() { @@ -331,6 +432,23 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& return false; } cudaMemset(arena_, 0, count.used); + if (g_trace && trace_h_ == nullptr) { // #649: the breadcrumbs, mapped so they read while the GPU hangs + trace_n_ = (size_t) (g.n_layers + 1) * kProfPer * 2; + if (!mapped(trace_n_ * 8, (void**) &trace_h_, (void**) &trace_m_)) { + (void) cudaGetLastError(); + trace_h_ = trace_m_ = nullptr; + trace_n_ = 0; + } +#if defined(STRATA_USE_HIP) + std::fprintf(stderr, "strata verify trace (#649): on; coherent words %s, doorbell %s, HIP_HOST_COHERENT=%s " + "HSA_ENABLE_SDMA=%s GPU_MAX_HW_QUEUES=%s\n", g_coherent ? "explicit" : "default", + g_doorbell_store ? "stored" : "incremented", std::getenv("HIP_HOST_COHERENT") ? std::getenv("HIP_HOST_COHERENT") : "-", + std::getenv("HSA_ENABLE_SDMA") ? std::getenv("HSA_ENABLE_SDMA") : "-", + std::getenv("GPU_MAX_HW_QUEUES") ? std::getenv("GPU_MAX_HW_QUEUES") : "-"); +#else + std::fprintf(stderr, "strata verify trace (#649): on\n"); +#endif + } prof_on_ = std::getenv("STRATA_VERIFY_PROFILE") != nullptr; if (prof_on_) { const size_t np = (size_t) g.n_layers * kProfPer + 4; @@ -405,7 +523,10 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { auto Rt = [&](int t) { return R_ + (size_t) t * HC * N; }; const int G = (split_ && T >= 2) ? 2 : 1; static const bool dec_batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }(); - auto stamp = [&](int64_t l, int i, int grp) { if (prof_on_ && grp == 0) gpu_stamp(prof_, (int) (l * kProfPer + i), cs); }; + auto stamp = [&](int64_t l, int i, int grp) { + if (prof_on_ && grp == 0) gpu_stamp(prof_, (int) (l * kProfPer + i), cs); + if (trace_m_ != nullptr) gpu_stamp(trace_m_, (int) ((l * kProfPer + i) * 2 + grp), cs); // #649 + }; const int tb_[2] = {0, (T + 1) / 2}, te_[2] = {G == 2 ? (T + 1) / 2 : T, T}; groups_[T] = G; @@ -691,6 +812,12 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { hits_.cache_base, slot_off_d_, (long long) hits_.blob, plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, skip_ + grp, (uint32_t) ((l - lb_) * G + grp + 1), cs); +#if defined(STRATA_USE_HIP) + if (g_doorbell_store) // #649 A/B: the step's ring stored, not incremented over PCIe + doorbell_publish_value(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N, + m_ids_ + tb * K, m_w_ + tb * K, m_seq_, (uint32_t) ((l - lb_) * G + grp + 1), cs); + else +#endif doorbell_publish(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N, m_ids_ + tb * K, m_w_ + tb * K, m_seq_, cs); stamp(l, 17, grp); @@ -1055,13 +1182,16 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, *(volatile uint32_t*) h_flag_ = 0; *(volatile uint32_t*) h_flagA_ = 0; *(volatile uint32_t*) h_flagB_ = 0; + if (trace_h_ != nullptr) std::memset(trace_h_, 0, trace_n_ * 8); // #649: this window's breadcrumbs only std::atomic_thread_fence(std::memory_order_seq_cst); + trace_ev("WINDOW", -1, -1, pos0 * 16 + T); last_t_ = T; last_pos0_ = pos0; for (int t = 0; t < T; ++t) last_tokens_[t] = tokens[t]; ms_host += ms_since(t0); VDBG("staged; launching\n"); const cudaError_t le = cudaGraphLaunch(exec_[T], cs_); + trace_ev("LAUNCHED", -1, -1, (int64_t) le); if (le != cudaSuccess) { err = std::string("verify: launch: ") + cudaGetErrorString(le); return false; } (void) cudaStreamQuery(cs_); VDBG("launched\n"); @@ -1087,6 +1217,8 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, last_flush = now; const cudaError_t q = cudaStreamQuery(cs_); if (q != cudaErrorNotReady && *seq < want) { + trace_ev("NEVER-RANG", k, l, (int64_t) q); + trace_dump(stderr); err = "verify: layer " + std::to_string(l) + " never rang (" + (q == cudaSuccess ? std::string("graph finished") : std::string(cudaGetErrorString(q))) + ")"; return false; @@ -1094,11 +1226,20 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, } if (now - a > std::chrono::seconds(20)) { // #267: the caller ends the engine; no spin kernel may outlive it + trace_ev("TIMEOUT", k, l, (int64_t) cudaStreamQuery(cs_)); + if (g_trace) { + diag(stderr); // the words and the breadcrumbs before the release ... + const bool drained = release_gpu_waits(5000); + trace_dump(stderr); // ... and after it: did the GPU move once its waits were raised? + err = "verify: timed out at layer " + std::to_string(l) + released_note(drained); + return false; + } err = "verify: timed out at layer " + std::to_string(l) + released_note(release_gpu_waits(5000)); return false; } } const Clock::time_point b = Clock::now(); + if (g_trace) trace_ev("RANG", k, l, (int64_t) std::chrono::duration_cast(b - a).count()); VDBG("layer %lld rang\n", (long long) l); cur_layer_ = want - 1; set_plan_slot(grp); @@ -1108,6 +1249,8 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, pool(user, h_x_ + (size_t) tb * g.n_embd, h_ids_ + (size_t) tb * ss.k, n, ss.k, h_ymiss_ + (size_t) tb * ss.k * g.n_embd, l); VDBG("layer %lld served\n", (long long) l); + if (g_trace) trace_ev(*(volatile uint32_t*) h_flagA_ == want ? "SERVED" : "SERVED-NO-PLAN-YET", k, l, + (int64_t) ms_since(b)); // aux: ms the CPU experts took progress_tick(); std::atomic_thread_fence(std::memory_order_seq_cst); _mm_sfence(); @@ -1131,7 +1274,9 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, // spin kernel outlives the process - the case that left Windows GPUs "lost" until a power cycle. The wait // itself stays a blocking sync: a cudaStreamQuery poll here cost IQ3_S ~3% decode (a core calling the driver // beside the expert workers). + trace_ev("SYNC", -1, -1, 0); const cudaError_t se = cudaStreamSynchronize(cs_); + trace_ev("SYNCED", -1, -1, (int64_t) se); if (se != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(se); return false; } progress_at("verify window: waiting for the expert copies", (int64_t) T); cudaStreamSynchronize(copy_); // no host function of this window may raise flag B in the next one diff --git a/src/kernels/cpu/pool.cpp b/src/kernels/cpu/pool.cpp index 45e43470..1919d2e9 100644 --- a/src/kernels/cpu/pool.cpp +++ b/src/kernels/cpu/pool.cpp @@ -95,6 +95,12 @@ CpuTopology detect_cpu_topology(bool skip_first, PoolAffinity affinity) { } if (affinity == PoolAffinity::All || !topo.is_hybrid) { + // #642 (from Hardin22's fork): on a hybrid CPU the P-cores first (the host takes the first of them), so a + // pool smaller than the core count (setup's --pool-workers for a hybrid CPU) runs on the P-cores and the + // first E-cores rather than on whatever the OS numbered first. All cores alike: the order is unchanged. + if (topo.is_hybrid) + std::stable_sort(descs.begin(), descs.end(), + [](const CoreDesc& x, const CoreDesc& y) { return x.efficiency > y.efficiency; }); for (const auto& c : descs) topo.worker_cores.push_back(c.lps[0]); if (skip_first && !topo.worker_cores.empty()) { topo.host_core = topo.worker_cores.front(); @@ -219,6 +225,9 @@ CpuTopology detect_cpu_topology(bool skip_first, PoolAffinity affinity) { } if (affinity == PoolAffinity::All || !topo.is_hybrid) { + if (topo.is_hybrid) // #642: the P-cores first (see the Windows branch) + std::stable_sort(all_cpus.begin(), all_cpus.end(), + [](const CoreLinux& x, const CoreLinux& y) { return x.cap > y.cap; }); for (const auto& cl : all_cpus) { if (!cl.is_sibling) topo.worker_cores.push_back(cl.cpu); } diff --git a/src/kernels/cuda/elementwise.cu b/src/kernels/cuda/elementwise.cu index 26cf66fa..4d670e99 100644 --- a/src/kernels/cuda/elementwise.cu +++ b/src/kernels/cuda/elementwise.cu @@ -303,6 +303,30 @@ __global__ void doorbell_publish_kernel(const float* __restrict__ x, const int32 } } +// #649 (HIP, STRATA_DOORBELL_STORE=1): the same publish, but the ring is STORED (the step's own number, known at +// capture) instead of read-modify-written over PCIe - one store, no read of host memory from the GPU. +__global__ void doorbell_publish_value_kernel(const float* __restrict__ x, const int32_t* __restrict__ ids, + const float* __restrict__ w, int n, int k, float* x_out, int32_t* ids_out, + float* w_out, uint32_t* seq, uint32_t value) { + for (int i = threadIdx.x; i < n; i += blockDim.x) x_out[i] = x[i]; + if ((int) threadIdx.x < k) { ids_out[threadIdx.x] = ids[threadIdx.x]; w_out[threadIdx.x] = w[threadIdx.x]; } + __threadfence_system(); + __syncthreads(); + if (threadIdx.x == 0) { + __threadfence_system(); + *(volatile uint32_t*) seq = value; + __threadfence_system(); + } +} + +void doorbell_publish_value(const float* x, const int32_t* ids, const float* weights, int64_t n, int64_t k, + float* x_out, int32_t* ids_out, float* weights_out, uint32_t* d_seq, uint32_t value, + void* stream) { + if (k > 1024) { std::fprintf(stderr, "doorbell_publish: k too large\n"); std::exit(1); } + doorbell_publish_value_kernel<<<1, 1024, 0, (cudaStream_t) stream>>>(x, ids, weights, (int) n, (int) k, x_out, + ids_out, weights_out, d_seq, value); +} + void doorbell_publish(const float* x, const int32_t* ids, const float* weights, int64_t n, int64_t k, float* x_out, int32_t* ids_out, float* weights_out, uint32_t* d_seq, void* stream) { if (k > 1024) { std::fprintf(stderr, "doorbell_publish: k too large\n"); std::exit(1); } diff --git a/src/kernels/cuda/kv_stream.cu b/src/kernels/cuda/kv_stream.cu index ec01ff22..914a836e 100644 --- a/src/kernels/cuda/kv_stream.cu +++ b/src/kernels/cuda/kv_stream.cu @@ -251,6 +251,16 @@ void kv_stage_from_host(const QsaAttnPools& stage, const KvHostPools& host, int check("stage"); } +void kv_unstage_to_host(const QsaAttnPools& stage, const KvHostPools& host, int fmt, int64_t b0, int64_t b1, + const QsaShapes& s, void* stream) { + if (b1 <= b0) return; + const Runs r = runs_of(stage, host, fmt, s); // src: the host copy, dst: the staging pool (identity layout both) + for (int a = 0; a < r.n; ++a) + if (cudaMemcpyAsync((void*) (r.src[a] + b0 * r.len[a]), r.dst[a] + b0 * r.len[a], (size_t) ((b1 - b0) * r.len[a]), + cudaMemcpyDefault, (cudaStream_t) stream) != cudaSuccess) + check("unstage"); +} + KvStreamCounters kv_stream_counters(const KvStreamMap& m) { int32_t c[kKvCtlInts] = {}; KvStreamCounters r; diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 5d46e4bf..37d8f83c 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -1642,8 +1642,23 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e } host_setup_ms += ms_since(tsetup); bool normed = false; // F-2: the previous half's write already normed R for this half (grs, xn16) + // #579 #613 (opt-in diagnosis, STRATA_PF_STEP_SYNC=1): the compute and copy streams are waited for after each + // step named below, a step that took over 250 ms is logged, and a stall's report names the step it is in. + // Slower (a sync per step); the bytes are the same. + static const bool step_sync = [] { const char* e = std::getenv("STRATA_PF_STEP_SYNC"); return e && e[0] == '1'; }(); + auto pf_step = [&](const char* what, int64_t layer) { + if (!step_sync) return; + core::progress_at(what, layer, p0); + const auto ts = Clock::now(); + const cudaError_t a = cudaStreamSynchronize(m.cs), b = cudaStreamSynchronize(m.copy); + const double ms = ms_since(ts); + if (ms > 250.0 || a != cudaSuccess || b != cudaSuccess) + std::fprintf(stderr, "strata pf-step: chunk from token %lld, layer %lld: %s took %.0f ms (%s / %s)\n", + (long long) p0, (long long) layer, what, ms, cudaGetErrorString(a), cudaGetErrorString(b)); + }; for (int64_t l = LB; l < LE; ++l) { core::progress_beat(); // the serve watchdog: a prompt chunk of 8192 tokens is still moving + if (l > LB) pf_step("reading the prompt (batched, step sync): the experts and the rest of layer", l - 1); core::progress_at("reading the prompt (batched): layer", l, p0); // #251: a stall names layer and chunk const core::LayerView v(*m.wt, l); if (l == std::max(LB, 1) && !ple_land()) return false; // the PLE rows, read from layer 1 on @@ -1773,7 +1788,20 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e core::qsa_kv_format(st), (p0 + s.page_size - 1) / s.page_size, s, m.cs); pt.mark(kPfQsa, cs); + pf_step("reading the prompt (batched, step sync): the K/V staged from RAM at layer", l); } + // #579 #613 (HIP, opt-in A/B, STRATA_KV_HOST_DMA=1): the append writes the staging pool and the + // resident slots only, and one DMA copies the chunk's blocks from the staging pool to the host copy + // - no kernel writes host memory over PCIe. The bytes every reader sees are the same (the staged + // first block is complete; past the chunk's last cell nothing is read until a later append writes + // it). CUDA: never. +#if defined(STRATA_USE_HIP) + static const bool kv_host_dma = [] { const char* e = std::getenv("STRATA_KV_HOST_DMA"); return e && e[0] == '1'; }(); +#else + constexpr bool kv_host_dma = false; +#endif + const bool host_by_dma = staged && kv_host_dma; + const strata::kernels::KvHostPools* host_w = host_by_dma ? nullptr : &st.host; if (st.kv_hybrid) { // K8V4: K INT8 unrotated, V rotated Q4_0 (only V and the output rotate) strata::kernels::fwht256_inplace_cuda(m.Vc, T * 2, m.cs); kv_append(m.Kc, m.Kc, T, p0, st.page_table, s.page_size, nullptr, nullptr, @@ -1788,12 +1816,17 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e } if (st.kv_q4) strata::kernels::kv_append_q4(st.k_q4, st.v_q4, st.page_table, p0, T, m.Kc, m.Vc, s, m.cs, - &st.host, staged ? &m.stage : nullptr); + host_w, staged ? &m.stage : nullptr); else kv_append(m.Kc, m.Vc, T, p0, st.page_table, s.page_size, st.kv_int8 ? nullptr : st.k_pool, st.kv_int8 ? nullptr : st.v_pool, st.k_q, st.v_q, st.k_scale, st.v_scale, m.cs, - &st.host, staged ? &m.stage : nullptr); + host_w, staged ? &m.stage : nullptr); + if (host_by_dma) + strata::kernels::kv_unstage_to_host(pools_of(m.stage, m.ident_table), st.host, + core::qsa_kv_format(st), p0 / s.page_size, + (p0 + T + s.page_size - 1) / s.page_size, s, m.cs); } + if (staged) pf_step("reading the prompt (batched, step sync): the K/V append at layer", l); split_q(m.Qf, m.q, T, m.cs); rms_rows(m.q, (const float*) wqn->data, T * 24, 256, 256, EPS, m.cs); rope(m.q, T, 24, 256, 6144, p0, strata::kernels::rope_scaling(), m.cs); @@ -2049,7 +2082,12 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e int32_t* src_h = grp_mapped ? m.grp_host + 2 * m.grp_tk : m.src_host.data(); if (grp_mapped) copy_i32(m.grp_dev, m.ids, T * K, m.cs); else cudaMemcpyAsync(m.ids_host.data(), m.ids, (size_t) T * K * 4, cudaMemcpyDeviceToHost, m.cs); + // #579: a stall here is the GPU (this layer's attention and router, or the previous layer's + // work), not the host: the watchdog's report says so (only its text changes) + core::progress_at("reading the prompt (batched): waiting for the GPU (attention, router) at layer", + l, p0); cudaStreamSynchronize(m.cs); + core::progress_at("reading the prompt (batched): layer", l, p0); pt.fold(); if (pe.on) { // the peer's marks so far are done: the primary waited for its last rows int pd = 0; cudaGetDevice(&pd); cudaSetDevice(pe.dev); cudaStreamSynchronize(m.pp->s); pe.fold(); cudaSetDevice(pd); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 1b6ed60e..f6d98b96 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -420,6 +420,10 @@ struct Options { /// and the KV state, minus this reserve for the graphs, the hit scratch and the head. int vram_reserve_mib = 700; bool vram_reserve_given = false; ///< --vram-reserve-mib on the command line (#496: no smaller automatic reserve) + /// #533 (opt-in): the expert cache in physical segments (CUDA virtual memory management), so the serve loop's + /// `VRAM ` command can give part of it back to other programs and take it again. Off: one cudaMalloc. + bool vram_elastic = false; + int64_t vram_segment_mib = 512; /// Plan v0.3 P5: batched prompt processing in chunks of this many tokens (0 = the token path). int64_t prefill_chunk = 0; /// `--prefill auto`: the largest chunk (up to 8192) whose buffers the expert cache can lend. Every expert a chunk @@ -600,6 +604,9 @@ void usage() { " --conversation-cache-mib N --serve: RAM budget for parked conversations (default 0 = off)\n" " --conversation-cache-slots N --serve: at most N parked conversations (default 4)\n" " --conversation-cache-min-free-mib N --serve: physical RAM floor when parking (default 2560)\n" + " --vram-elastic --serve (#533, opt-in, NVIDIA): the expert cache in segments (--vram-segment-mib,\n" + " default 512), so the command `VRAM ` (the server's POST /v1/vram) can\n" + " give VRAM back to other programs between requests and take it back later\n" " --prompt-cache-every N --serve: also checkpoint every N fresh prompt tokens (default 16384, 0 = off)\n" " --turn-token ID --serve: the token that opens a chat turn (default 248045, <|im_start|>)\n" " --tail-role-token ID --serve: a turn of this role right before the last turn is left out of\n" @@ -1359,6 +1366,8 @@ int main(int argc, char** argv) { } else if (a == "--no-split-rows") o.no_split_rows = true; else if (a == "--no-prefill-borrow") o.no_prefill_borrow = true; + else if (a == "--vram-elastic") o.vram_elastic = true; + else if (a == "--vram-segment-mib") o.vram_segment_mib = std::atoll(next("--vram-segment-mib")); else if (a == "--prefill-until") o.prefill_until = std::atoll(next("--prefill-until")); else if (a == "--dump-final-r") o.dump_final_r = next("--dump-final-r"); else if (a == "--spec") o.spec = std::atoi(next("--spec")); @@ -3175,6 +3184,24 @@ int main(int argc, char** argv) { } o.expert_cache = (int) sized_slots.size(); } + // #533: --vram-elastic: the cache in physical segments (the VRAM command resizes it between requests). One GPU, + // no helper caches, serve mode: anything else keeps the one cudaMalloc, said once. + if (o.vram_elastic) { + const char* why = !o.serve ? "it works between requests of --serve" + : multi_gpu ? "a layer split has a cache per GPU" + : std::any_of(o.expert_cache_remote.begin(), o.expert_cache_remote.end(), + [](int n) { return n > 0; }) ? "the helper caches on other GPUs" + : o.vram_segment_mib < 64 ? "--vram-segment-mib is below 64" : nullptr; +#if defined(STRATA_USE_HIP) + if (why == nullptr) why = "it is NVIDIA-only for now"; +#endif + if (why != nullptr) { + std::fprintf(stderr, "strata generate: --vram-elastic is off: %s\n", why); + o.vram_elastic = false; + } else { + xcache.set_segment_bytes(o.vram_segment_mib << 20); + } + } if (o.expert_cache > 0) { // keep the first `keep_bytes` of the cache (the profile's hottest experts first); false when nothing is left auto shrink_to = [&](int64_t keep_bytes) -> bool { @@ -4919,7 +4946,18 @@ int main(int argc, char** argv) { std::vector part_next(stages.size() + 1, INT64_MAX); // a checkpoint of the state after `cur[0, L)`; false only when the copy itself failed. `parts`: the stages' // states saved at L (a split's mid-prompt checkpoint); without, they are read now (everything is at L) + // #613: why the last checkpoint_at failed - a failed device sync is the GPU itself (a hang Windows then resets), + // not the checkpoint, and the error says so + std::string ckpt_why; + auto gpu_sync_ok = [&]() -> bool { + const cudaError_t e = cudaDeviceSynchronize(); + if (e == cudaSuccess) return true; + ckpt_why = std::string(": the GPU stopped responding before it (") + cudaGetErrorString(e) + + ") - a GPU hang; on Windows the driver is then reset"; + return false; + }; auto checkpoint_at = [&](int64_t L, std::vector* parts = nullptr) -> bool { + ckpt_why.clear(); if (o.prompt_cache <= 0 || L < 1) return true; for (ConvCheckpoint& c : checks) if ((int64_t) c.ids.size() == L) { c.used = ++check_clock; return true; } @@ -4935,12 +4973,12 @@ int main(int argc, char** argv) { c.block_pos = std::move((*parts)[0].block_pos); for (size_t i = 1; i < parts->size(); ++i) c.stage_parts.push_back(std::move((*parts)[i])); } else { - if (cudaDeviceSynchronize() != cudaSuccess || !checkpoint_save(c, ss, g)) return false; + if (!gpu_sync_ok() || !checkpoint_save(c, ss, g)) return false; for (auto& st : stages) { // a layer split's later stages: their sessions' part const strata::core::OnDevice on(st->dev); ConvCheckpoint part; part.ids = c.ids; - if (cudaDeviceSynchronize() != cudaSuccess || !checkpoint_save(part, st->ss, g)) return false; + if (!gpu_sync_ok() || !checkpoint_save(part, st->ss, g)) return false; c.stage_parts.push_back(std::move(part)); } } @@ -4990,7 +5028,7 @@ int main(int argc, char** argv) { } else { saved = checkpoint_at(done); } - if (!saved) { e = "saving a conversation checkpoint failed"; return false; } + if (!saved) { e = "saving a conversation checkpoint failed" + ckpt_why; return false; } pp_next_check = done + o.prompt_cache_every; } return true; @@ -5277,7 +5315,7 @@ int main(int argc, char** argv) { "expert_slots_primary=%lld expert_cache_primary_mib=%lld spec=%d " "mtp_max=%d lookup=%d vram_free_mib=%lld cvec=%s arena_mib=%lld pool_workers=%d pcie_frac=%.2f " "spec_min_p=%.2f conversation_cache_mib=%lld conversation_cache_slots=%d " - "conversation_cache_min_free_mib=%lld tail_role_token=%lld engine=" STRATA_VERSION "\n", + "conversation_cache_min_free_mib=%lld tail_role_token=%lld vram_elastic=%d engine=" STRATA_VERSION "\n", (long long) o.max_context, o.kv.c_str(), (long long) (g.n_qsa_layers() > 0 && ss.qsa_states[ss.qsa_primary()].kv_mode == 1 ? ss.qsa_states[ss.qsa_primary()].n_slots * 4 : 0), @@ -5288,7 +5326,7 @@ int main(int argc, char** argv) { (long long) ((o.mmap_experts ? src.resident_bytes() : strata::kernels::cpu::expert_layout().total) >> 20), pool.workers(), o.pcie_frac, o.spec_min_p, (long long) o.conversation_cache_mib, o.conversation_cache_slots, - (long long) o.conversation_cache_min_free_mib, (long long) o.tail_role_token); + (long long) o.conversation_cache_min_free_mib, (long long) o.tail_role_token, xcache.segmented() ? 1 : 0); } // issue #29: a request whose heartbeat (tokens, prompt chunks, verify windows) stops for this long is stuck on // a flag nobody will raise - end the engine with where it was, so the server starts it again instead of the @@ -5335,7 +5373,132 @@ int main(int argc, char** argv) { bool mrope_identity = true; std::vector img_rows; std::vector row_ptr; + // ---- #533: VRAM , between requests, only with --vram-elastic. It shrinks the expert cache + // until that much VRAM is free for other programs (a game, a CAD session), or grows it back towards its full + // size when more than that is free. Never on its own: only this command (the server's POST /v1/vram) moves + // it. A shrink gives back the cache's LAST segments: the experts in their slots become CPU misses, as any + // expert outside the cache is (no output changes beyond what a smaller cache decodes), the prompt path's + // loan moves down to the end of what is left (a smaller chunk when it no longer fits). A grow maps them + // again and puts each slot's expert back (or, when the adaptive tier already brought that one back, the + // most-routed missing expert of the same layer); the adaptive tier carries on from there. + std::vector> vram_evicted; // (residency index, slot) the shrinks took + const int64_t chunk_full = o.prefill_chunk; // the loan's chunk with the whole cache + auto relend = [&]() { // the prompt path's loan: the end of the slots left, its chunk as large as fits + if (pf_parts.empty() || pf_parts[0].first < 0) return; + PfPart& p = pf_parts[0]; + const int64_t live = xcache.slots(); + auto fits = [&](int64_t c) { + const int64_t k = part_slots(p, c); + return k > 0 && k + 128 <= live && !(o.prefill_auto && k * 100 > kAutoLendPct * live); + }; + int64_t c = chunk_full; + while (c > 256 && !fits(c)) c = std::max(256, c / 2 / 256 * 256); + o.prefill_chunk = c; + p.first = (int32_t) std::max(0, live - part_slots(p, c)); + p.first_now = -1; // laid out again at the next loan + }; + auto vram_command = [&](const std::string& cmd, std::string& e) -> bool { + // `VRAM` alone: the reserve the engine started with (--vram-reserve-mib) + char* end = nullptr; + const bool bare = cmd.find_first_not_of(' ', 4) == std::string::npos; + const long long reserve = bare ? (long long) o.vram_reserve_mib : std::strtoll(cmd.c_str() + 4, &end, 10); + if (!bare && (end == cmd.c_str() + 4 || reserve < 0)) { e = "expected: VRAM [reserve_mib]"; return false; } + if (!xcache.segmented()) { + e = "VRAM needs an engine started with --vram-elastic (one NVIDIA GPU, --serve)"; + return false; + } + if (src.complement_ready()) { + e = "VRAM: not with the resident low-RAM mode (the cache holds experts RAM does not)"; + return false; + } + if (peer.valid()) { e = "VRAM: not with --peer-device"; return false; } + for (const PfPart& p : pf_parts) + if (!p.lent.empty()) { e = "VRAM: a prompt's loan is still out"; return false; } + if (!ver.wait_commit(e)) return false; + apply_pending(true); // the adaptive tier's swaps in flight land first + if (cudaDeviceSynchronize() != cudaSuccess) { + e = std::string("VRAM: ") + cudaGetErrorString(cudaGetLastError()); + return false; + } + const auto t0 = Clock::now(); + size_t free_b = 0, total_b = 0; + cudaMemGetInfo(&free_b, &total_b); + const int64_t want_free = (int64_t) reserve << 20, mapped = xcache.mapped_bytes(); + const int64_t before = xcache.slots(); + // what stays at least: the prompt path's smallest loan (256 tokens) and the 128 slots it must leave + const int64_t floor_slots = std::min(xcache.full_slots(), + 128 + (pf_parts.empty() || pf_parts[0].first < 0 ? 0 : part_slots(pf_parts[0], 256))); + std::string note; + if ((int64_t) free_b < want_free) { + const int64_t floor_b = xcache.bytes_of(floor_slots); + int64_t keep = mapped - (want_free - (int64_t) free_b); + if (keep < floor_b) { + keep = floor_b; + note = " (the cache keeps its smallest size: the prompt path's buffers)"; + } + if (!xcache.shrink(keep, e)) return false; + const int64_t live = xcache.slots(); + for (size_t i = 0; i < host_res.size(); ++i) + if (host_res[i] >= live) { + vram_evicted.emplace_back((int32_t) i, host_res[i]); + host_res[i] = strata::core::kNotResident; + } + res_upload(); + } else if (mapped < xcache.full_bytes()) { + std::string gerr; + if (!xcache.grow(mapped + ((int64_t) free_b - want_free), gerr)) note = " (" + gerr + ")"; + const int64_t live = xcache.slots(); + std::string ferr; + std::vector> keep_out; + for (const auto& [i, slot] : vram_evicted) { + if (slot >= live) { keep_out.emplace_back(i, slot); continue; } + const int64_t layer = i / g.n_expert; + int64_t pick = i; + if (host_res[(size_t) i] >= 0) { // back already (the adaptive tier): the layer's most-routed miss + pick = -1; + float best = -1.0f; + for (int64_t ex = 0; ex < g.n_expert; ++ex) { + const size_t j = (size_t) (layer * g.n_expert + ex); + if (host_res[j] >= 0) continue; + const float u = drive.d.usage.empty() ? 0.0f : drive.d.usage[j]; + if (u > best) { best = u; pick = (int64_t) j; } + } + } + if (pick < 0) continue; + const uint8_t* b = srcp->blob(layer, pick % g.n_expert); + if (b == nullptr || !xcache.fill_slot_queued(slot, b, ferr, + (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(layer))) { + e = "VRAM: refilling the cache failed: " + ferr; + return false; + } + host_res[(size_t) pick] = slot; + } + vram_evicted.swap(keep_out); + if (!xcache.sync_queued(ferr)) { e = "VRAM: " + ferr; return false; } + res_upload(); + } + relend(); + cudaMemGetInfo(&free_b, &total_b); + std::fprintf(stderr, "strata serve: VRAM %lld MiB kept free: the expert cache %lld -> %lld of %lld slots " + "(%.2f of %.2f GiB), %lld MiB free now, prompt chunk %lld, in %.0f ms%s\n", + reserve, (long long) before, (long long) xcache.slots(), (long long) xcache.full_slots(), + (double) xcache.mapped_bytes() / 1073741824.0, (double) xcache.full_bytes() / 1073741824.0, + (long long) (free_b >> 20), (long long) o.prefill_chunk, + std::chrono::duration(Clock::now() - t0).count(), note.c_str()); + std::printf("VRAM reserve_mib=%lld expert_slots=%lld expert_slots_full=%lld expert_cache_mib=%lld " + "expert_cache_full_mib=%lld vram_free_mib=%lld prompt_chunk=%lld\n", reserve, + (long long) xcache.slots(), (long long) xcache.full_slots(), + (long long) (xcache.mapped_bytes() >> 20), (long long) (xcache.full_bytes() >> 20), + (long long) (free_b >> 20), (long long) o.prefill_chunk); + return true; + }; while (next_line(line)) { + if (line.rfind("VRAM", 0) == 0) { // #533 (above): between requests, not a request + std::string verr; + if (!vram_command(line, verr)) std::printf("ERR %s\n", verr.c_str()); + std::fflush(stdout); + continue; + } // #477: every --expert-profile-save-every minutes, before the next request (at QUIT: after the loop) if (!heat.empty() && line != "QUIT" && o.expert_profile_save_min > 0 && Clock::now() - profile_saved_at >= std::chrono::duration(o.expert_profile_save_min * 60.0)) @@ -5948,7 +6111,7 @@ int main(int argc, char** argv) { } at = to; if ((to == turn_at || to == root_at) && !checkpoint_at(to)) { - std::printf("ERR saving a conversation checkpoint failed\n"); + std::printf("ERR saving a conversation checkpoint failed%s\n", ckpt_why.c_str()); return 1; } } diff --git a/tests/core/expert_cache_segmented_test.cpp b/tests/core/expert_cache_segmented_test.cpp new file mode 100644 index 00000000..cabf24a4 --- /dev/null +++ b/tests/core/expert_cache_segmented_test.cpp @@ -0,0 +1,99 @@ +// #533: the segmented expert cache (--vram-elastic). A shrink gives the last segments' VRAM back to the driver and +// keeps every slot left exactly as it was (same address, same bytes); a grow maps them again at the same addresses. +// Uniform and sized slots. Needs a CUDA device with virtual memory management (exits 77 without one). +#include "strata/core/expert_cache.hpp" + +#include + +#include +#include +#include + +namespace { +int fail(const char* what, const std::string& err = "") { + std::fprintf(stderr, "FAIL %s %s\n", what, err.c_str()); + return 1; +} + +size_t free_vram() { + size_t f = 0, t = 0; + cudaMemGetInfo(&f, &t); + return f; +} + +// slot i holds the byte (i * 7 + 1) everywhere +bool fill(strata::core::ExpertCache& c, int64_t from, int64_t to, int64_t blob) { + std::vector b((size_t) blob); + for (int64_t i = from; i < to; ++i) { + std::fill(b.begin(), b.end(), (uint8_t) (i * 7 + 1)); + if (cudaMemcpy(c.device_slot((int32_t) i), b.data(), (size_t) blob, cudaMemcpyHostToDevice) != cudaSuccess) + return false; + } + return true; +} + +bool check(const strata::core::ExpertCache& c, int64_t to, int64_t blob) { + std::vector b((size_t) blob); + for (int64_t i = 0; i < to; ++i) { + if (cudaMemcpy(b.data(), c.device_slot((int32_t) i), (size_t) blob, cudaMemcpyDeviceToHost) != cudaSuccess) + return false; + for (const uint8_t x : b) + if (x != (uint8_t) (i * 7 + 1)) return false; + } + return true; +} +} // namespace + +int main() { + int n = 0; + if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) { + std::puts("no CUDA device: skipped"); + return 77; + } + constexpr int64_t kBlob = 1 << 20, kSlots = 96, kSeg = 8ll << 20; + for (int sized = 0; sized < 2; ++sized) { + strata::core::ExpertCache c; + c.set_segment_bytes(kSeg); + std::string err; + const bool ok = sized ? c.open_sized(std::vector(kSlots, kBlob), 4, 64, err) + : c.open(kSlots, 4, 64, kBlob, err); + if (!ok) { + if (err.find("virtual memory management") != std::string::npos) { + std::printf("%s: skipped\n", err.c_str()); + return 77; + } + return fail("open", err); + } + if (!c.segmented() || c.slots() != kSlots || c.mapped_bytes() < kSlots * kBlob) return fail("open sizes"); + uint8_t* const first = c.device_slot(0); + if (!fill(c, 0, kSlots, kBlob)) return fail("fill"); + const size_t before = free_vram(); + // keep 30 MiB: rounded up to whole 8 MiB segments = 32 MiB = 32 slots + if (!c.shrink(30ll << 20, err)) return fail("shrink", err); + if (c.slots() != 32 || c.mapped_bytes() != 32ll << 20 || c.bytes() != 32ll << 20) + return fail("shrunk sizes"); + if (c.full_slots() != kSlots || c.full_bytes() != kSlots * kBlob) return fail("full sizes"); + const size_t freed = free_vram() - before; + if (freed + (8u << 20) < (size_t) (64ll << 20)) { // ~64 MiB back to the driver (WDDM rounds a little) + std::fprintf(stderr, "freed %zu bytes\n", freed); + return fail("VRAM not given back"); + } + if (c.device_slot(0) != first || !check(c, 32, kBlob)) return fail("slots kept after the shrink"); + // grow to 70 MiB: whole segments only, 64 MiB = 64 slots + if (!c.grow(70ll << 20, err) || c.slots() != 64) return fail("grow part", err); + if (!c.grow(1ll << 40, err) || c.slots() != kSlots || c.mapped_bytes() < kSlots * kBlob) + return fail("grow all", err); + if (c.device_slot(0) != first || !check(c, 32, kBlob)) return fail("slots kept after the grow"); + if (!fill(c, 32, kSlots, kBlob) || !check(c, kSlots, kBlob)) return fail("the grown slots"); + if (c.slots_within(0) != 0 || c.slots_within(kBlob * 3 + 5) != 3 || c.bytes_of(5) != 5 * kBlob) + return fail("slots_within / bytes_of"); + c.close(); + if (c.valid() || c.slots() != 0) return fail("close"); + } + // the default (no segment size): one allocation, shrink refused + strata::core::ExpertCache d; + std::string err; + if (!d.open(8, 2, 4, kBlob, err) || d.segmented() || d.shrink(0, err)) return fail("unsegmented", err); + std::puts("expert cache segments: shrink gives VRAM back and keeps the slots, grow maps them again"); + return 0; +} diff --git a/tools/conversation_restore_speed.py b/tools/conversation_restore_speed.py new file mode 100644 index 00000000..980c4b7e --- /dev/null +++ b/tools/conversation_restore_speed.py @@ -0,0 +1,182 @@ +"""#528: decode speed after a conversation-cache restore, against the same turns kept live. + +Two private engines run one after the other (never an existing server): + baseline --conversation-cache-mib 0: conversation A, turn after turn, continues live + candidate --conversation-cache-mib N: between A's turns an unrelated conversation B parks A, so every later + turn of A is restored from its parked snapshot +Each A turn's greedy output must be the same token for token in both, and its decode speed should be too (a +restored conversation decodes like a live one). --mode same: one conversation whose client re-renders each reply +(no parking needed); --mode pair: two long conversations take turns (a snapshot restored every turn). On a PC with +little RAM the cache's physical-RAM floor may refuse to park (the log says "skip parking"): that turn reads its +prompt again and is reported as not restored. Dry-run by default; --run needs the GPU (and its lock). + +Measured on the RTX 5070 (0.1.38, #528): Q2_0 37K tokens --kv-resident 16384, IQ3_XXS 50-75K tokens +--kv-resident 32768 (switch, same and pair modes): restored turns decode at the live turns' speed, same tokens. + + python tools/conversation_restore_speed.py --config cfg.json --engine build-release/strata.exe \ + --output out-dir --tokens 40000 --set=--max-context=65536 --set=--kv-resident=16384 --run +""" +import argparse +import json +from pathlib import Path +import sys +import threading + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT), str(ROOT / 'tools')] + + +def override(args, pairs): + """cfg args with each `--flag value` of pairs replacing the config's own (or appended).""" + out = list(args) + for flag, value in pairs: + if flag in out: + i = out.index(flag) + if value is None: + del out[i:i + 2] + else: + out[i + 1] = value + elif value is not None: + out += [flag, value] + return out + + +def parse_sets(items): + pairs = [] + for item in items or []: + flag, _, value = item.partition('=') + pairs.append((flag, value if value != '' else None)) + return pairs + + +def summarize(records): + rows = [] + for r in records: + tok_s = r['generated'] / (r['decode_ms'] / 1000) if r.get('decode_ms') else 0.0 + acc = f"{r.get('drafts_accepted', 0)}/{r.get('drafts_offered', 0)}" + rows.append(f" {r['name']:<8} reused={r.get('reused', 0):>6} gen={r['generated']:>4} " + f"decode={tok_s:6.1f} tok/s drafts={acc:<9} hits={r.get('hits', 0)}/{r.get('lookups', 0)}") + return '\n'.join(rows) + + +def compare(results, tolerance): + """The A turns: identical ids, restored (reused > 0) in the candidate, and decode within `tolerance`.""" + base = {r['name']: r for r in results['baseline']} + problems = [] + for r in results['candidate']: + if not r['name'].startswith('A'): + continue + b = base.get(r['name']) + if b is None: + problems.append(f"{r['name']}: no baseline turn") + continue + if r['ids'] != b['ids']: + problems.append(f"{r['name']}: output differs from the live baseline") + if r['name'] != 'A1' and not r.get('reused'): + problems.append(f"{r['name']}: not restored (reused=0)") + speed = lambda x: x['generated'] / (x['decode_ms'] / 1000) if x.get('decode_ms') else 0.0 + if r['name'] != 'A1' and speed(r) < (1 - tolerance) * speed(b): + problems.append(f"{r['name']}: restored decode {speed(r):.1f} tok/s vs live {speed(b):.1f}") + return problems + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument('--config', type=Path, required=True) + ap.add_argument('--engine', type=Path, required=True) + ap.add_argument('--output', type=Path, required=True, help='new directory; an existing path is refused') + ap.add_argument('--tokens', type=int, default=20000, help='about this many prompt tokens in A') + ap.add_argument('--gen', type=int, default=160, help='tokens generated per A turn') + ap.add_argument('--turns', type=int, default=3, help='A turns (the first is read fresh)') + ap.add_argument('--cache-mib', type=int, default=8192) + ap.add_argument('--set', action='append', metavar='FLAG=VALUE', + help='override an engine flag of the config (FLAG= drops it); repeatable') + ap.add_argument('--tolerance', type=float, default=0.15, help='allowed decode shortfall of a restored turn') + ap.add_argument('--only', choices=('baseline', 'candidate'), help='run one side only (no comparison)') + ap.add_argument('--mode', choices=('switch', 'same', 'pair'), default='switch', + help='switch: B parks A between turns; same: one conversation whose client drops the last ' + '--trim tokens of each reply (re-rendered history), as agent clients do; pair: two long ' + 'conversations A and C take turns (each turn restores a big snapshot, the cache holds two)') + ap.add_argument('--trim', type=int, default=8) + ap.add_argument('--run', action='store_true') + a = ap.parse_args() + if not a.run: + print('Dry run: baseline (live turns) vs candidate (every turn after the first restored from a parked ' + 'snapshot); greedy, fixed residency. Use --run with the GPU free.') + return + from serve.server import StrataEngine, child_env + from serve.frontend import ChatTemplate + from conversation_cache_parity import load_tokenizer + cfg = json.loads(a.config.read_text(encoding='utf-8')) + p = Path(cfg['tokenizer']) + tok = load_tokenizer(p) + tpl = ChatTemplate(p / 'chat_template.jinja') + enc = lambda text: tok.encode(text, parse_special=True) + colors = ('blue', 'green', 'red', 'amber', 'violet', 'teal', 'grey', 'white') + shapes = ('square', 'triangle', 'circle', 'hexagon', 'star', 'ring') + + def doc(label, n): + lines = [f'{label}: here is an inventory list to remember.'] + i = 0 + while len(lines) * 15 < n: + lines.append(f'Record {i}: a {colors[i % 8]} {shapes[(i * 7) % 6]} stored in bin {(i * 37) % 997}.') + i += 1 + return '\n'.join(lines) + + ask = 'Write a long, detailed story that uses as many of the records above as you can.' + A = enc(tpl.render([{'role': 'user', 'content': doc('Conversation A', a.tokens) + '\n' + ask}], + enable_thinking=False)) + B = enc(tpl.render([{'role': 'user', 'content': doc('Unrelated conversation B', 2000) + '\nName one bin.'}], + enable_thinking=False)) + follow = [enc('<|im_end|>\n<|im_start|>user\nContinue the story, with new records.<|im_end|>\n' + '<|im_start|>assistant\n\n\n\n\n')] + a.output.mkdir(parents=False, exist_ok=False) + env = child_env(cfg) + base_args = override(cfg['args'], parse_sets(a.set) + [('--adapt-swaps', '0'), ('--prompt-cache', '6')]) + results = {'prompt_tokens': len(A), 'args': base_args} + sides = [('baseline', 0), ('candidate', a.cache_mib)] + if a.only: + sides = [s for s in sides if s[0] == a.only] + for label, budget in sides: + args = base_args + ['--conversation-cache-mib', str(budget), '--conversation-cache-slots', '4'] + engine = StrataEngine(str(a.engine.resolve()), args, cwd=cfg.get('cwd'), log=str(a.output / f'{label}.log'), + env=env) + records = [] + + def generate(ids, count, name): + out = [t for t in engine.generate(ids, count, {'temperature': 0}, threading.Event()) if t is not None] + records.append({'name': name, 'ids': out, **engine.last}) + print(f'{label} {summarize(records[-1:]).strip()}', flush=True) + return out + + try: + convo = list(A) + other = enc(tpl.render([{'role': 'user', 'content': doc('Second long conversation C', a.tokens) + '\n' + + ask}], enable_thinking=False)) if a.mode == 'pair' else None + for turn in range(1, a.turns + 1): + if other is not None and budget: # C's turn first: A comes back from its snapshot after it + out_c = generate(other, a.gen if turn == 1 else 32, f'C{turn}') + other = other + out_c + follow[0] + if turn > 1: + if budget and a.mode == 'switch': + generate(B, 1, f'B{turn}') # parks A: this turn of A comes back from the snapshot + convo += follow[0] + out = generate(convo, a.gen, f'A{turn}') + convo += out[:-a.trim] if a.mode == 'same' and len(out) > a.trim else out + finally: + engine.close() + results[label] = records + (a.output / 'results.json').write_text(json.dumps(results, indent=1) + '\n') + for label, _ in sides: + print(f'{label}:\n{summarize(results[label])}') + if a.only: + return + problems = compare(results, a.tolerance) + for line in problems: + print('FAIL ' + line) + print('PASS: restored turns decode like live ones, same output' if not problems else 'FAILED') + sys.exit(1 if problems else 0) + + +if __name__ == '__main__': + main() diff --git a/tools/test_conversation_restore_speed.py b/tools/test_conversation_restore_speed.py new file mode 100644 index 00000000..d5a14892 --- /dev/null +++ b/tools/test_conversation_restore_speed.py @@ -0,0 +1,34 @@ +"""#528: the restore-speed bench's own logic (no GPU): flag overrides and the pass/fail rule.""" +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import conversation_restore_speed as R # noqa: E402 + + +def turn(name, ids, ms, reused=1): + return {'name': name, 'ids': ids, 'generated': len(ids), 'decode_ms': ms, 'reused': reused} + + +class Bench(unittest.TestCase): + def test_override(self): + args = ['--max-context', '32768', '--kv', 'int8'] + self.assertEqual(R.override(args, R.parse_sets(['--max-context=65536', '--kv-resident=16384', '--kv='])), + ['--max-context', '65536', '--kv-resident', '16384']) + + def test_compare(self): + base = [turn('A1', [1, 2], 100, 0), turn('A2', [3, 4], 100)] + ok = {'baseline': base, 'candidate': [turn('A1', [1, 2], 100, 0), turn('B2', [9], 10), + turn('A2', [3, 4], 110)]} + self.assertEqual(R.compare(ok, 0.15), []) + slow = {'baseline': base, 'candidate': [turn('A1', [1, 2], 100, 0), turn('A2', [3, 4], 400)]} + self.assertTrue(any('restored decode' in p for p in R.compare(slow, 0.15))) + differ = {'baseline': base, 'candidate': [turn('A1', [1, 2], 100, 0), turn('A2', [3, 5], 100)]} + self.assertTrue(any('output differs' in p for p in R.compare(differ, 0.15))) + unrestored = {'baseline': base, 'candidate': [turn('A1', [1, 2], 100, 0), turn('A2', [3, 4], 100, 0)]} + self.assertTrue(any('not restored' in p for p in R.compare(unrestored, 0.15))) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/test_setup_golden.py b/tools/test_setup_golden.py index a3c0a2d8..2f2513a4 100644 --- a/tools/test_setup_golden.py +++ b/tools/test_setup_golden.py @@ -100,6 +100,7 @@ def install(ram, found, argv, answers=None, extra=(), avx512=False, configs=()): mock.patch.object(setup, "amd_gpus", lambda: []), mock.patch.object(setup, "ram_gb", lambda: ram), mock.patch.object(setup, "cpu_info", lambda: ("Test CPU", True, avx512)), + mock.patch.object(setup, "cpu_cores", lambda: None), # #642: not a hybrid CPU mock.patch.object(setup, "page_file_gb", lambda: 16.0), mock.patch.object(setup, "is_wsl", lambda: False), mock.patch.object(setup, "rotational_disk", lambda p: None), # #605: the test PC's own disk diff --git a/tools/test_setup_hybrid.py b/tools/test_setup_hybrid.py new file mode 100644 index 00000000..a5b9a164 --- /dev/null +++ b/tools/test_setup_hybrid.py @@ -0,0 +1,65 @@ +"""#642: setup recommends the expert pool's worker count on a hybrid CPU (the P-cores but the host loop's one, plus +half of the E-cores) and writes nothing new anywhere else; a calibration's measured count wins over the rule. + + python -m unittest tools.test_setup_hybrid +""" +from __future__ import annotations + +import sys +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "tools")) +import setup # noqa: E402 +from test_setup_golden import PROFILES, install # noqa: E402 + + +class HybridWorkers(unittest.TestCase): + def test_rule(self): + self.assertIsNone(setup.hybrid_pool_workers(None)) + self.assertEqual(setup.hybrid_pool_workers((8, 16)), 15) # i9-14900K: the fork's measured 15 + self.assertEqual(setup.hybrid_pool_workers((6, 8)), 9) # i5-13600K + self.assertEqual(setup.hybrid_pool_workers((4, 8)), 7) # Ryzen AI 9 HX 370 (Zen 5 + Zen 5c) + self.assertIsNone(setup.hybrid_pool_workers((8, 8))) # i7-13700K: all cores measured faster (AMD_HIP.md) + self.assertIsNone(setup.hybrid_pool_workers((8, 4))) + + def test_recommend_keeps_a_given_count(self): + with mock.patch.object(setup, "cpu_cores", lambda: (8, 16)), mock.patch.object(setup, "ok", lambda *a: None): + self.assertEqual(setup.recommend_pool_workers(["--spec", "4"]), ["--spec", "4", "--pool-workers", "15"]) + given = ["--pool-workers", "12"] + self.assertEqual(setup.recommend_pool_workers(given), given) + with mock.patch.object(setup, "cpu_cores", lambda: None): + self.assertEqual(setup.recommend_pool_workers(["--spec", "4"]), ["--spec", "4"]) + + def test_install_on_a_hybrid_cpu(self): + ram, found = PROFILES["96GB-1x16GB"] + hybrid = [mock.patch.object(setup, "cpu_cores", lambda: (8, 16))] + code, text, cfg, _ = install(ram, found, ["--family", "qwen", "--no-start", "--model", "Q2_0"], extra=hybrid) + self.assertEqual(code, 0, text) + a = cfg["args"] + self.assertEqual(a[a.index("--pool-workers") + 1], "15") + self.assertIn("hybrid CPU (8 performance + 16 efficiency cores)", text) + # the same PC without the hybrid CPU: the config is the one it always was (no --pool-workers) + code, text, plain, _ = install(ram, found, ["--family", "qwen", "--no-start", "--model", "Q2_0"]) + self.assertEqual(code, 0, text) + self.assertNotIn("--pool-workers", plain["args"]) + i = a.index("--pool-workers") + self.assertEqual(a[:i] + a[i + 2:], plain["args"]) + + def test_calibration_wins(self): + ram, found = PROFILES["96GB-1x16GB"] + cal = {"settings": {"--pool-workers": "11"}, "date": "2026-10-03"} + extra = [mock.patch.object(setup, "cpu_cores", lambda: (8, 16)), + mock.patch.object(setup, "saved_calibration", lambda cfg: cal)] + code, text, cfg, _ = install(ram, found, ["--family", "qwen", "--no-start", "--model", "Q2_0"], extra=extra) + self.assertEqual(code, 0, text) + a = cfg["args"] + self.assertEqual(a[a.index("--pool-workers") + 1], "11") + self.assertEqual(a.count("--pool-workers"), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_setup_unsloth.py b/tools/test_setup_unsloth.py index 38caa4e6..3cd0c998 100644 --- a/tools/test_setup_unsloth.py +++ b/tools/test_setup_unsloth.py @@ -164,6 +164,7 @@ class Base(unittest.TestCase): mock.patch.object(setup, "amd_gpus", lambda *a: list(amd)), mock.patch.object(setup, "ram_gb", lambda: ram), mock.patch.object(setup, "cpu_info", lambda: ("Test CPU", True, True)), + mock.patch.object(setup, "cpu_cores", lambda: None), # #642: not a hybrid CPU mock.patch.object(setup, "page_file_gb", lambda: 16.0), mock.patch.object(setup, "free_gb", lambda p: free), mock.patch.object(setup, "rotational_disk", lambda p: None), # #605: not the test PC's disk