diff --git a/data/draft_vocab_fr.bin b/data/draft_vocab_fr.bin new file mode 100644 index 00000000..21fff5d0 Binary files /dev/null and b/data/draft_vocab_fr.bin differ diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index e2b63fc9..f7732835 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -46,7 +46,9 @@ the kernel's amdgpu driver (no ROCm install needed): architectures above; the engine is compiled for each of them (cards of two families, e.g. gfx1100 + gfx1201, need a system ROCm 7: AMD's wheels hold one family). A split pays only when no single card holds the model's experts (see RDNA4 below). -- **Limits for now:** images only through the CPU encoder (`--vision cpu`, 0.1.32), no calibration. The Monitor +- **Limits for now:** images only through the CPU encoder (`--vision cpu`, 0.1.32). Setup does not offer the tuning + (calibration) on AMD yet: its controls are being checked on HIP one at a time (#566). Since 0.1.39 a tuning run by + hand (`./setup.sh --calibrate`) is saved for the AMD card it ran on and reused when setup runs again. The Monitor shows the card's load, VRAM, temperature and power from Linux sysfs (0.1.32). The rest of setup is the same as on NVIDIA: the model download, the start script, the server. diff --git a/docs/DETAILS.md b/docs/DETAILS.md index dd44dbef..876e6406 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -107,6 +107,11 @@ English/code subset from before (40,525 ids, ~110 MiB less VRAM, English answers almost no drafts). `--draft-vocab cyrillic` takes the English/code subset plus the whole Cyrillic script (58,963 ids): the shipped subsets hold 142 of the vocabulary's 18,580 Cyrillic tokens, so Ukrainian or Russian answers got 1.4 tokens a round; with it 2.1, and 83 -> 109 tokens/s (RTX 5090, the NVFP4 fork), English unchanged. +`--draft-vocab fr` (0.1.39, #597) takes the English/code subset plus the 5,686 tokens that cover 99% of a French +Wikipedia corpus (46,211 ids, `tools/draft_vocab.py --corpus`): 23.6% of French text's tokens were outside the +English/code subset, 0.7% are outside this one. Drafts accepted in French answers 0.51 -> 0.60 (IQ3_XXS, RTX 5070, +8 prompts x 2 passes; English 0.61 -> 0.63 and code 0.77 -> 0.78, no loss), and 141 -> 158 tok/s in French on an +RTX 5090 (IQ3_S, the reporter's measurement). `tools/draft_vocab.py` builds and inspects subsets. When the start stops with "the draft head does not fit" (a 12 GB card with a long context, #474), the engine says how much the head needs, how much VRAM is free and which smaller subset fits, and the server's start error repeats it; setup suggests `--draft-vocab en` on cards under @@ -145,6 +150,13 @@ other ~18 GB), a 32 GB PC with a 12-16 GB GPU the Coder; IQ3_XXS on a 32 GB PC s with `--resident-experts` started with `--gpus` switches to `--mmap-experts` with a note, and the engine runs that pair as `--mmap-experts` with a warning instead of refusing it. +**A mapped arena for small RAM (Linux, opt-in, 0.1.39, PR #640):** `STRATA_ARENA_MMAP=1` maps a native pack's expert +arena read-only from the pack's `experts.bin` instead of reading it into locked RAM, for a PC whose GPUs hold most +experts but whose RAM is small (2x 16 GB GPUs with 32 GB of RAM: ~1 GB -> 25 GB available while serving). The first +start writes `experts.bin` (when the drive has room for it), later starts map it; the pages of the experts a GPU holds +are handed back to the OS. Run it with `--pcie-frac 0` (the GPUs get no mapped alias). Without the variable nothing +changes. + **Low-RAM mode without `experts.bin` (engine 0.1.31):** for the native packs (IQ2_XS, IQ3_XXS, IQ3_S, the Coder, Swift, Q2_0 packed by `tools/iq_pack.py`; not the canonical Q2_0 pack setup makes for AVX-512 CPUs) the mapped mode no longer needs the pack's `experts.bin`: when the pack has none, the engine @@ -221,7 +233,9 @@ card gains depends on its PCIe link (the experts stream over it), so they are st More VRAM matters more than a faster GPU: every extra GB holds ~700 more experts, and every expert on the GPU is one the CPU does not have to compute. A 3090's 24 GB takes most of the CPU work away. (Since 0.1.14 the expert profile ranks all 24,576 experts; before, the cache stopped at 8,000, about 10-14 GB. `tools/make_profile.py` builds a profile from -your own prompts: run the engine once with `--dump-routing trace.bin`, see the tool's help.) +your own prompts: run the engine once with `--dump-routing trace.bin`, see the tool's help. The shipped profile already +ranks every pair, so a trace only changes the order with `--reorder` (0.1.39, #587): your trace's pairs first, then the +base's, then the rest.) ## Which model? diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 2e9d975f..5925214e 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -80,6 +80,14 @@ The engine flags behind it: `--layer-split K1[,K2..]|auto` and `--split-device D devices; default the next visible ones). `--layer-split K --split-device 0` runs both stages on one card sharing everything - the bit-exact check of the hand-off, not a speed mode. +**Each card loads only its own layers' dense weights** (0.1.39, PR #639) with explicit split points (`--layer-split +27`, not `auto`): every card used to keep a full copy (~3.4 GB for the Coder) though its stage reads only its own +layers, and the VRAM it frees goes to that card's expert cache (2x MI50 16 GB, Coder: 8,819 -> 10,626 experts in +VRAM, decode 39.2 -> 41.7 tok/s). On by default in the AMD (HIP) builds, `STRATA_STAGE_TRIM=0` keeps the full copies; +on NVIDIA it is opt-in with `STRATA_STAGE_TRIM=1` until it has been run on NVIDIA cards (please report how it goes). +A card holding more experts can change which experts run on the GPU, so the output can differ slightly from a run +without it. + **auto** tries every placement (all of them for two or three cards; proportional to the free VRAM beyond that) and keeps the one whose caches would hold the most of the expert profile, hottest pairs weighted most; ties go to the placement that leaves the fullest card the most room. The startup log prints the choice: diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index beaa5aa3..8fbc4a58 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -138,6 +138,11 @@ public: virtual void begin_layer(int64_t layer, const int32_t* ids, int64_t k) { (void) layer; (void) ids; (void) k; } /// Plan v0.3 P6: the DEVICE address of a pinned, mapped blob (the GPU can read it over PCIe), or null. virtual const uint8_t* device_alias(int64_t layer, int64_t expert) const { (void) layer; (void) expert; return nullptr; } + /// A file-backed source: start reading this expert's pages now (it will be needed by the CPU); no-op elsewhere. + virtual void prefetch(int64_t layer, int64_t expert) { (void) layer; (void) expert; } + /// A file-backed source: this expert lives in VRAM, so its pages need not stay in RAM - hand them back to the + /// kernel (a later read re-reads the file; no result depends on it). Returns the bytes released; 0 elsewhere. + virtual uint64_t release(int64_t layer, int64_t expert) { (void) layer; (void) expert; return 0; } /// Whether the verify window may give the GPU a PCIe share of this layer's misses at all (each expert is still /// checked with `pinned`). The arena answers per layer through its expert 0; the resident RAM mode's compact /// copy has no expert 0 when the GPU cache holds it, so it answers for the whole copy. @@ -667,6 +672,8 @@ public: int64_t reads() const { return reads_; } bool pinned(int64_t layer, int64_t expert) const override; const uint8_t* device_alias(int64_t layer, int64_t expert) const override; + void prefetch(int64_t layer, int64_t expert) override; + uint64_t release(int64_t layer, int64_t expert) override; /// What backing was obtained and why, for the startup print. "The engine adapts to the machine it is on" is /// only true if the engine says what it got. @@ -683,6 +690,8 @@ public: private: void* arena_ = nullptr; ///< the PinnedArena, owned + void* map_ = nullptr; ///< STRATA_ARENA_MMAP: the arena file, mapped read-only (not the PinnedArena) + uint64_t map_bytes_ = 0; std::vector dev_slice_; ///< device alias of each registered slice (or of the whole range) uint64_t slice_bytes_ = 0; const uint8_t* base_ = nullptr; diff --git a/include/strata/core/native_dense.hpp b/include/strata/core/native_dense.hpp index 8330fac5..911b31b6 100644 --- a/include/strata/core/native_dense.hpp +++ b/include/strata/core/native_dense.hpp @@ -25,6 +25,9 @@ public: /// supported type, 2-D), read from the GGUF headers only - so the canonical arena can skip them. static bool served_names(const std::vector& shards, bool include_ple_key, std::set& out, std::string& err); + /// Layer split: load only blocks [lb, le) (every other `blk.N.` projection belongs to another GPU's stage; the + /// PLE tensors are loaded everywhere). Process-wide, read by the next `load`; (-1, -1) = all layers. + static void set_layer_range(int lb, int le); /// #326: a native pack whose `blk.1.ple_key.weight` row is unquantized (iq_pack --compat-bf16 of a GGUF key /// the native kernel also reads, e.g. OrcaRouter's IQ3_XXS) serves the PLE from that row, so it is taken out /// of `skip` and `load` does not upload the GGUF key over it. A quantized row leaves `skip` unchanged. diff --git a/include/strata/hip_compat/cuda_runtime.h b/include/strata/hip_compat/cuda_runtime.h index da2c4f4c..ccf9a913 100644 --- a/include/strata/hip_compat/cuda_runtime.h +++ b/include/strata/hip_compat/cuda_runtime.h @@ -61,6 +61,7 @@ #define cudaHostRegister hipHostRegister #define cudaHostRegisterMapped hipHostRegisterMapped #define cudaHostRegisterPortable hipHostRegisterPortable +#define cudaHostRegisterReadOnly hipHostRegisterReadOnly #define cudaHostUnregister hipHostUnregister #define cudaLaunchHostFunc hipLaunchHostFunc #define cudaMalloc hipMalloc diff --git a/serve/server.py b/serve/server.py index 179975bf..78022ba6 100644 --- a/serve/server.py +++ b/serve/server.py @@ -446,6 +446,7 @@ class StrataEngine: pass raise RuntimeError("the engine exited before it was ready" + (f" (see {log})" if log else "") + start_failure_hint(log, log_start) + start_log_tail(log, log_start)) + self.known_ctx = self.max_context # survives a failed restart: requests keep their limit and restart it # (from PR #41, midhatn) a locally built engine can sit next to another release's BUILD.json: engines that # report their own version (INFO engine=, 0.1.8+) win, the manifest stays the fallback for older ones if self.info.get("engine"): @@ -505,15 +506,37 @@ class StrataEngine: self.close() self.unloaded = True - def restart(self): - """Start the engine again (the same command) after it died; the new process has its own line queue.""" + RESTART_RETRY_S = 15.0 # between the tries of restart(): a dying engine's VRAM may take a while to come back + + def restart(self, tries: int = 3): + """Start the engine again (the same command) after it died; the new process has its own line queue. + close() ends and waits for the old process first (EngineStuck when it cannot be ended). A start that still + exits before READY - a dead engine's VRAM can take a while to come back, notably on ROCm - is retried + (PR #637).""" self.close() info = dict(self.info) - # #344: not alive until READY - __init__ sets max_context to 0 and blocks until the engine says READY, and a - # request that saw alive() in that window skipped load() and failed with "context (0)". __init__ clears - # `ended` itself once READY (before its pump thread can set it again). - self.ended = True - self.__init__(*self.spawn) + self.starting = True # prepare() answers 503 "starting" meanwhile (#344) + try: + for i in range(tries): + # #344: not alive until READY - __init__ sets max_context to 0 and blocks until the engine says + # READY, and a request that saw alive() in that window skipped load() and failed with "context + # (0)". __init__ clears `ended` itself once READY (before its pump thread can set it again). + self.ended = True + try: + self.__init__(*self.spawn) + break + except RuntimeError: + try: + self.proc.wait(timeout=60) + except (subprocess.TimeoutExpired, OSError): + pass + if i == tries - 1: + raise + print(f"[strata] the engine did not start (try {i + 1} of {tries}); again in " + f"{self.RESTART_RETRY_S:g} s", flush=True) + time.sleep(self.RESTART_RETRY_S) + finally: + self.starting = False self.info = {**info, **self.info} def _parse_done(self, line): @@ -1559,18 +1582,25 @@ class Service: for path, _ in encoded: f.write(path.read_bytes()) self.embeddings.path = combined - if self.engine.max_context <= 0: # #344: (re)starting, not a prompt that is too long - raise EngineStarting("the engine is starting (a minute or two); try again shortly") - room = self.engine.max_context - CTX_SLACK - len(ids) + ctx = self.engine.max_context + if ctx <= 0: + if getattr(self.engine, "starting", False): # #344: (re)starting, not a prompt that is too long + raise EngineStarting("the engine is starting (a minute or two); try again shortly") + # a failed restart leaves max_context 0: check against the last known context, so the request reaches + # run() - which starts the engine again - instead of failing with "exceeds the context (0)" forever + ctx = getattr(self.engine, "known_ctx", 0) + if ctx <= 0: + raise EngineStarting("the engine is starting (a minute or two); try again shortly") + room = ctx - CTX_SLACK - len(ids) if max_new is None or max_new <= 0 or (self.fit_max_tokens and room < 1): if room < 1: raise ValueError(f"prompt ({len(ids)} tokens) leaves no room to answer in the context " - f"({self.engine.max_context}); requests are never truncated") + f"({ctx}); requests are never truncated") max_new = room elif max_new > room: if not self.fit_max_tokens: raise ValueError(f"prompt ({len(ids)} tokens) + max tokens ({max_new}) exceeds the context " - f"({self.engine.max_context}); requests are never truncated. Send a smaller " + f"({ctx}); requests are never truncated. Send a smaller " f"max_tokens (at most {max(0, room)} here), or add \"fit_max_tokens\": true to the " "model's strata-.json to shorten it to the room left (#545)") max_new = max(1, room) # --fit-max-tokens: a shorter completion beats a 400 diff --git a/serve/test_server.py b/serve/test_server.py index acf99ed6..0ffe2f6c 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -2252,6 +2252,13 @@ for line in sys.stdin: break ''' +FAKE_STRATA_FAIL_ONCE = '''import pathlib, sys, time +fail = pathlib.Path(sys.argv[sys.argv.index("--fail") + 1]) +if fail.exists(): # this start fails before READY (as one next to a dying engine did) + fail.unlink() + sys.exit(1) +''' + FAKE_STRATA.split("\n", 1)[1] + class RestartWindow(unittest.TestCase): """#344: while the engine restarts it is not alive (a request waits for the restart instead of reading @@ -2303,6 +2310,54 @@ class RestartWindow(unittest.TestCase): gate.touch() eng.unload() + def test_restart_retries_a_start_that_fails(self): + """A dead engine's VRAM is freed only when its process is gone, so a new engine started at once can exit + before READY; restart() tries again (3 times) instead of leaving the server with max_context 0.""" + from unittest import mock + import serve.server as server + with tempfile.TemporaryDirectory() as d: + script, gate, fail = Path(d) / "fake_strata.py", Path(d) / "ready", Path(d) / "fail_once" + script.write_text(FAKE_STRATA_FAIL_ONCE, encoding="utf-8") + real = server.subprocess.Popen + with mock.patch.object(server.subprocess, "Popen", + lambda cmd, **kw: real([sys.executable, str(script), *cmd[1:]], **kw)), \ + mock.patch.object(StrataEngine, "RESTART_RETRY_S", 0.0): + gate.touch() + eng = StrataEngine("strata", ["--gate", str(gate), "--fail", str(fail)]) + try: + self.assertEqual(eng.max_context, 4096) + self.assertEqual(eng.known_ctx, 4096) + fail.touch() # the next start exits before READY, the one after works + eng.proc.kill() + eng.proc.wait(10) + eng.restart() + self.assertFalse(fail.exists(), "the failing start never ran") + self.assertTrue(eng.alive()) + self.assertEqual(eng.max_context, 4096) + self.assertFalse(eng.starting) + finally: + gate.touch() + eng.unload() + + def test_failed_restart_keeps_the_known_context(self): + """After a restart that failed, max_context is 0 but the engine is not starting: a request is checked against + the last known context and reaches run() (which starts the engine again), not a 400 about context 0.""" + tok = ByteTokenizer() + eng = MockEngine(tok, "\n\nok", max_context=0) + eng.known_ctx, eng.starting = 4096, False + svc = Service(eng, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + try: + req = urllib.request.Request(base + "/v1/chat/completions", + data=json.dumps({"model": "m", "max_tokens": 16, + "messages": [{"role": "user", "content": "hi"}]}).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=30) as r: + self.assertEqual(r.status, 200) + finally: + httpd.shutdown() + def test_context_zero_is_503(self): tok = ByteTokenizer() svc = Service(MockEngine(tok, "\n\nok", max_context=0), tok, diff --git a/setup.py b/setup.py index 6a4c18d9..05dda6aa 100644 --- a/setup.py +++ b/setup.py @@ -2628,11 +2628,37 @@ def rotational_disk(path) -> str | None: return None +def hip_config_cards(sel) -> list[dict]: + """#566: the AMD cards a HIP config runs on - its "gpu" (one index or a list) in HIP's numbering, as amd_gpus + lists them; no "gpu": the supported card with the most VRAM, as setup picks it. Each card's name carries its + architecture (an RX 7900 XTX and an RX 7900 XT are both gfx1100; a card without a product name in sysfs is known + by its arch only). A card that is not found is {} (the key then says "?").""" + amd = amd_gpus() + if sel is None: + usable = [g for g in amd if amd_problem(g) is None] + sel = max(usable, key=lambda x: (round(x["vram_gb"]), -x["index"]))["index"] if usable else None + byid = {g["index"]: g for g in amd} + cards = [] + for i in (sel if isinstance(sel, list) else [sel]): + g = byid.get(i) + if g is None: + cards.append({}) + continue + arch = g.get("arch") or "" + name = g.get("name") or "?" + cards.append({**g, "name": name if not arch or arch in name else f"{name} ({arch})"}) + return cards + + def hardware_key(cfg: dict) -> str: """What a calibration is valid for: this GPU, CPU and RAM, and the model with its context and images setting - (the context's KV cache and the image encoder take VRAM from the expert cache).""" + (the context's KV cache and the image encoder take VRAM from the expert cache). #566: a HIP config's cards are + AMD's (hip_config_cards) - nvidia-smi's list named them "?" (or another card with that number) before.""" sel = cfg.get("gpu") - gl = [gpu_info(i) or {} for i in sel] if isinstance(sel, list) else [gpu_info(sel) or {}] + if cfg.get("backend") == "hip": + gl = hip_config_cards(sel) + else: + gl = [gpu_info(i) or {} for i in sel] if isinstance(sel, list) else [gpu_info(sel) or {}] g = {"name": " + ".join(x.get("name", "?") for x in gl), "vram_gb": sum(x.get("vram_gb", 0) for x in gl)} a = cfg.get("args", []) ctx = a[a.index("--max-context") + 1] if "--max-context" in a else "?" @@ -2681,6 +2707,16 @@ def saved_calibration(cfg: dict) -> dict | None: return (load_settings().get("calibration") or {}).get(hardware_key(cfg)) +def setup_calibration(cfg: dict, hip: bool) -> dict | None: + """The calibration a (re-)install applies to its new config: the one saved for this PC and model. #566: on Linux + HIP too - hardware_key now names the AMD cards, so a `./setup.sh --calibrate` run is matched to its card and + model. Windows HIP keeps the defaults for now (not tried there). Setup still offers the tuning itself on NVIDIA + only: each control is verified on HIP first.""" + if hip and WIN: + return None + return saved_calibration(cfg) + + def upgrade_config(cfg_path: Path, cfg: dict) -> dict: """Configs written before v0.1.13 read prompts in fixed 2048-token chunks; the engine now picks the chunk itself (`--prefill auto`: up to 8192, as the free VRAM allows - about 2x faster on long prompts). Under WSL, @@ -2891,7 +2927,8 @@ def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_ OLD_DRAFT_VOCABS = {"369151522226a5edaa5f12cfd1e2ae7db8f4fbdbd222f3dcf327dced9597fb25"} # to 0.1.26: 27 Han tokens -DRAFT_VOCABS = {"cjk": "draft_vocab.bin", "en": "draft_vocab_en.bin", "cyrillic": "draft_vocab_cyrillic.bin"} +DRAFT_VOCABS = {"cjk": "draft_vocab.bin", "en": "draft_vocab_en.bin", "cyrillic": "draft_vocab_cyrillic.bin", + "fr": "draft_vocab_fr.bin"} def saved_draft_vocab(cfg_path: Path) -> str | None: @@ -2929,7 +2966,7 @@ def vision_tokens(asked: int | None, vision: str, earlier: Path | None) -> int: return asked -DRAFT_VOCAB_MIB = {"cjk": 348, "cyrillic": 193, "en": 133} # the draft head's VRAM per subset (IQ3_S: the largest) +DRAFT_VOCAB_MIB = {"cjk": 348, "cyrillic": 193, "fr": 151, "en": 133} # the draft head's VRAM per subset (IQ3_S: the largest) SMALL_DRAFT_VRAM_GB = 14 # #474: below this the default subset's head can be what does not fit @@ -3004,7 +3041,7 @@ def refresh_draft_vocab(rt: Path, choice: str = "cjk") -> None: """The draft layer's token subset in the MTP folder: `cjk` (data/draft_vocab.bin, since 0.1.27, #137), `en` (data/draft_vocab_en.bin, the English/code subset before it: ~110 MiB less VRAM, English answers 1-2% faster) or `cyrillic` (data/draft_vocab_cyrillic.bin: English/code and the whole Cyrillic script, for Ukrainian, Russian, - Bulgarian, Serbian... answers). + Bulgarian, Serbian... answers) or `fr` (data/draft_vocab_fr.bin: English/code and the tokens of French text, #597). Copied when missing or when a shipped subset other than the chosen one is there; a subset made by hand is kept.""" new, dst = ROOT / "data" / DRAFT_VOCABS.get(choice, "draft_vocab.bin"), rt / "draft_vocab.bin" if not new.exists() or not rt.is_dir(): @@ -3016,7 +3053,8 @@ def refresh_draft_vocab(rt: Path, choice: str = "cjk") -> None: if old not in shipped or old == hashlib.sha256(new.read_bytes()).hexdigest(): return ok("draft layer: the token subset " + {"cjk": "with Chinese, Japanese and Korean", - "cyrillic": "with the Cyrillic script"}.get(choice, + "cyrillic": "with the Cyrillic script", + "fr": "for French"}.get(choice, "for English and code (less VRAM)")) shutil.copyfile(new, dst) @@ -3158,7 +3196,8 @@ def main() -> int: ap.add_argument("--draft-vocab", choices=list(DRAFT_VOCABS), help="the draft layer's tokens: cjk = with Chinese, Japanese and Korean (default), en = English " "and code only (~110 MiB less VRAM, English answers 1-2%% faster), cyrillic = English, code " - "and the Cyrillic script (Ukrainian, Russian... answers decode ~30%% faster)") + "and the Cyrillic script (Ukrainian, Russian... answers decode ~30%% faster), fr = English, " + "code and French (French answers: 18%% more drafts accepted)") ap.add_argument("--low-ram", choices=["auto", "on", "off", "resident", "mmap"], default="auto", help="read the model's experts from one file in its folder instead of copying them all into RAM " "(for a PC with a big GPU and little RAM); auto: when the experts would not fit the RAM. In " @@ -3728,7 +3767,7 @@ def main() -> int: "--out", str(mtp / "mtp-q2_0.gguf")], env=env) run([sys.executable, str(ROOT / "tools" / "mtp_rt.py"), "--gguf", str(mtp / "mtp-q2_0.gguf"), "--out", str(rt)], env=env) - # a setup run again without --draft-vocab keeps the subset this model's config chose before (cyrillic, en) + # a setup run again without --draft-vocab keeps the subset this model's config chose before (cyrillic, fr, en) draft_vocab = a.draft_vocab or saved_draft_vocab(ROOT / f"strata-{tag.lower()}.json") refresh_draft_vocab(rt, draft_vocab or "cjk") ok(f"MTP draft layer: {rt}") @@ -3877,7 +3916,7 @@ def main() -> int: elif a.vision_tokens is not None: warn("--vision-tokens: images are off for this model, so it is not used") cfg_path = ROOT / f"strata-{tag.lower()}.json" - cal = None if hip else saved_calibration(cfg) # tools/calibrate.py is NVIDIA-only for now + cal = setup_calibration(cfg, hip) # #566: Linux HIP too; the tuning is offered on NVIDIA only if cal is not None: sys.path.insert(0, str(ROOT / "tools")) import calibrate as CAL diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index 08edd46b..e2154941 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -2669,7 +2669,7 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6 std::ifstream f(path, std::ios::binary | std::ios::ate); if (!f) { err = "ArenaExpertSource: cannot open " + path; return false; } const uint64_t got = (uint64_t) f.tellg(); - if (got != want) { + if (got != want && got != want + (uint64_t) blob) { // + one blob: STRATA_ARENA_MMAP's padded file char buf[400]; std::snprintf(buf, sizeof buf, "ArenaExpertSource: %s is %llu B but %lld layers x %lld experts (blobs up to %lld B) " @@ -2681,6 +2681,45 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6 } } + // STRATA_ARENA_MMAP=1 (a small-RAM machine whose GPUs hold most experts): the arena is the pack's experts.bin + // mapped READ-ONLY - not locked, not pinned. The page cache keeps what the CPU pool and the prompt path + // actually read (the experts no VRAM cache holds) and gives back the rest under memory pressure; a page + // dropped is re-read from the file, so a result never depends on what is resident. The GPUs then get no + // mapped alias: run with --pcie-frac 0. The first start writes experts.bin (arena layout, padded by one blob + // so a whole-slot copy may start at any expert), later ones map it. +#if defined(_WIN32) + static const bool arena_mmap = false; // POSIX mmap/madvise: Linux only for now +#else + static const bool arena_mmap = [] { const char* v = std::getenv("STRATA_ARENA_MMAP"); return v && v[0] == '1'; }(); + if (arena_mmap) { + const uint64_t file_bytes = want + (uint64_t) blob; + uint64_t have = 0; + { + std::ifstream f(path, std::ios::binary | std::ios::ate); + if (f) have = (uint64_t) f.tellg(); + } + if (have == file_bytes) { + const int fd = ::open(path.c_str(), O_RDONLY); + void* v = fd >= 0 ? mmap(nullptr, (size_t) file_bytes, PROT_READ, MAP_SHARED, fd, 0) : MAP_FAILED; + if (fd >= 0) ::close(fd); + if (v == MAP_FAILED) { err = "ArenaExpertSource: mmap of " + path + " failed"; return false; } + map_ = v; + map_bytes_ = file_bytes; + base_ = (const uint8_t*) v; + pinned_bytes_ = 0; + dev_slice_.clear(); + slice_bytes_ = 0; + blobs_ = n_layers * n_expert; + n_expert_ = n_expert; + reads_ = 0; + note_ = "mapped read-only from " + path + " (STRATA_ARENA_MMAP: not locked, not pinned)"; + gib_per_s_ = 0.0; + load_seconds_ = load_read_s_ = load_copy_s_ = 0.0; + return true; + } + } +#endif + // #633: THE RAM BEFORE THE ALLOCATION. On Linux the arena is an anonymous mapping that succeeds whatever the host // has; its pages are committed as the load writes them, so a container whose memory limit is below the arena was // killed by the OOM killer part-way through the load, without a message. A hard cgroup limit below it is @@ -2770,6 +2809,30 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6 err = "ArenaExpertSource: the load read " + std::to_string(st.bytes) + " B of " + std::to_string(want); return false; } + // the first start: write experts.bin for the mapped starts after this one - only when the drive has room for it + // and 2 GiB more (a full drive fails other writes too); otherwise this start says so and runs pinned as before + std::error_code space_ec; + const uint64_t free_disk = arena_mmap && from_gguf ? (uint64_t) std::filesystem::space( + std::filesystem::path(path).parent_path(), space_ec).available : 0; + const bool room = !space_ec && free_disk >= want + (uint64_t) blob + (2ull << 30); + if (arena_mmap && from_gguf && !room) + std::fprintf(stderr, "strata generate: STRATA_ARENA_MMAP: NOT writing %s - %.1f GiB free on that drive, it needs " + "%.1f GiB plus 2 GiB to spare; this start keeps the arena in RAM\n", path.c_str(), + (double) free_disk / 1073741824.0, (double) (want + (uint64_t) blob) / 1073741824.0); + if (arena_mmap && from_gguf && room) { + const std::string tmp = path + ".tmp"; + std::FILE* f = std::fopen(tmp.c_str(), "wb"); + bool ok = f != nullptr && std::fwrite(a->data(), 1, (size_t) want, f) == (size_t) want; + if (ok) { + std::vector pad((size_t) blob, 0); + ok = std::fwrite(pad.data(), 1, pad.size(), f) == pad.size(); + } + if (f) ok = std::fclose(f) == 0 && ok; + if (ok) ok = std::rename(tmp.c_str(), path.c_str()) == 0; + if (!ok) std::remove(tmp.c_str()); + std::fprintf(stderr, "strata generate: STRATA_ARENA_MMAP: %s %s (the next start maps it)\n", + ok ? "wrote" : "could NOT write", path.c_str()); + } arena_ = a; base_ = a->data(); pinned_bytes_ = a->registered_bytes; @@ -2800,6 +2863,11 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6 } void ArenaExpertSource::close() { +#if !defined(_WIN32) + if (map_ != nullptr) munmap(map_, (size_t) map_bytes_); +#endif + map_ = nullptr; + map_bytes_ = 0; if (arena_ != nullptr) { delete (PinnedArena*) arena_; arena_ = nullptr; @@ -2809,6 +2877,39 @@ void ArenaExpertSource::close() { n_expert_ = 0; } +void ArenaExpertSource::prefetch(int64_t layer, int64_t expert) { +#if defined(_WIN32) + (void) layer; (void) expert; +#else + if (map_ == nullptr || layer < 0 || expert < 0 || expert >= n_expert_) return; + const auto& lay = strata::kernels::cpu::expert_layout(); + const uint64_t off = lay.blob_offset(layer, expert) & ~(uint64_t) 4095; + const uint64_t end = lay.blob_offset(layer, expert) + lay.blob_bytes(layer); + madvise((uint8_t*) map_ + off, (size_t) (end - off), MADV_WILLNEED); +#endif +} + +// Only the pages wholly inside the blob: a page shared with a neighbour the CPU may still read stays. MADV_DONTNEED +// unmaps them from this process; they stay in the page cache as clean, unmapped pages - the first the kernel takes +// back under pressure, and a minor fault away when the CPU needs the expert again (an adaptive swap evicts it). +// Dropping them from the cache too (POSIX_FADV_DONTNEED) made every eviction a re-read from the disk: ~200 major +// faults a second in decode, +8 ms a window. The memory the arena used to hold was never the cache itself but +// ROCclr's pin-in-place locks on it (see main) - locked pages are the ones the kernel cannot take back. +uint64_t ArenaExpertSource::release(int64_t layer, int64_t expert) { +#if defined(_WIN32) + (void) layer; (void) expert; + return 0; +#else + if (map_ == nullptr || layer < 0 || expert < 0 || expert >= n_expert_) return 0; + const auto& lay = strata::kernels::cpu::expert_layout(); + const uint64_t off = (lay.blob_offset(layer, expert) + 4095) & ~(uint64_t) 4095; + const uint64_t end = (lay.blob_offset(layer, expert) + lay.blob_bytes(layer)) & ~(uint64_t) 4095; + if (end <= off) return 0; + if (madvise((uint8_t*) map_ + off, (size_t) (end - off), MADV_DONTNEED) != 0) return 0; + return end - off; +#endif +} + bool ArenaExpertSource::pinned(int64_t layer, int64_t expert) const { if (base_ == nullptr || layer < 0 || expert < 0 || expert >= n_expert_) return false; const auto& lay = strata::kernels::cpu::expert_layout(); diff --git a/src/core/native_dense.cpp b/src/core/native_dense.cpp index 4a86d48c..86d70fb8 100644 --- a/src/core/native_dense.cpp +++ b/src/core/native_dense.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -13,6 +14,12 @@ namespace strata::core { namespace { +int g_layer_lb = -1, g_layer_le = -1; // set_layer_range; -1: every layer +bool in_range(const std::string& name) { + if (g_layer_lb < 0 || name.rfind("blk.", 0) != 0) return true; + const int l = std::atoi(name.c_str() + 4); + return l >= g_layer_lb && l < g_layer_le; +} bool eligible(const strata::TensorInfo& tensor, bool include_ple_key) { const auto& name = tensor.name; if (name.rfind("blk.", 0) != 0) return false; @@ -53,6 +60,7 @@ bool NativeDense::served_names(const std::vector& shards, bool incl } } +void NativeDense::set_layer_range(int lb, int le) { g_layer_lb = lb; g_layer_le = le; } bool NativeDense::keep_unquantized_ple_key(const std::string& pack_dir, std::set& skip, std::string& err) { const std::string key = "blk.1.ple_key.weight"; @@ -139,6 +147,7 @@ bool NativeDense::load(const std::vector& shards, WeightTable& tabl } for (const auto& tensor : gguf.tensors()) { if (!eligible(tensor, include_ple_key)) continue; + if (!in_range(tensor.name) && tensor.name.find("ple") == std::string::npos) continue; if (!seen.insert(tensor.name).second) { err = "native dense: duplicate tensor " + tensor.name; return false; } diff --git a/src/program/generate.cpp b/src/program/generate.cpp index bb9037e8..1b6ed60e 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -130,6 +130,70 @@ std::string vram_free_note() { } // perf-review D-4: the lent slots are refilled with queued copies and one wait; STRATA_REFILL_BLOCKING=1 waits on each +// A file-backed arena on AMD (STRATA_ARENA_MMAP; the engine raises ROCclr's pin-in-place threshold, see main): an +// adaptive swap copies one expert straight from the mapped file. Through ROCclr's staging that copy blocks the host +// (decode windows of 150+ ms); instead the batch's pages are locked here for the async copies and unlocked when they +// have landed (unpin_blobs), so the release that follows can hand them back. Neighbouring experts share a page and +// a copy from a range only PART of which is registered fails ("invalid argument"), so the page ranges are merged +// first and each merged span is registered once. A span that does not register is copied through the staging +// path. Portable: a layer split copies to either card. +// Whether pin_blobs locks anything (AMD on Linux with STRATA_ARENA_MMAP=1): the callers only gather the swaps' spans +// then - `blob()` is not free (it counts reads, and the file tier may assemble the blob), so the default runs skip it. +bool pin_blobs_on() { +#if (defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)) && !defined(_WIN32) + static const bool on = std::getenv("STRATA_ARENA_MMAP") && std::getenv("STRATA_ARENA_MMAP")[0] == '1'; + return on; +#else + return false; +#endif +} +int pin_blobs(std::vector> r, std::vector& live) { + int failed = 0; // ranges left pageable (a copy from them still works, through the driver's staging) +#if (defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)) && !defined(_WIN32) + if (!pin_blobs_on() || r.empty()) return 0; + for (auto& [a, e] : r) { a &= ~(uintptr_t) 4095; e = (e + 4095) & ~(uintptr_t) 4095; } + std::sort(r.begin(), r.end()); + size_t k = 0; + for (size_t i = 1; i < r.size(); ++i) { + if (r[i].first <= r[k].second) r[k].second = std::max(r[k].second, r[i].second); + else r[++k] = r[i]; + } + r.resize(k + 1); + for (const auto& [a, e] : r) { + if (cudaHostRegister((void*) a, (size_t) (e - a), cudaHostRegisterReadOnly | cudaHostRegisterPortable) == + cudaSuccess) + live.push_back((void*) a); + else { + (void) cudaGetLastError(); + ++failed; + } + } +#else + (void) r; (void) live; +#endif + return failed; +} +void unpin_blobs(std::vector& v) { + for (void* p : v) (void) cudaHostUnregister(p); + (void) cudaGetLastError(); + v.clear(); +} + +// STRATA_RSS_TRACE=1: the process's mapped file pages (the arena) at a startup step - who reads the arena back +void rss_probe(const char* where) { + static const bool on = std::getenv("STRATA_RSS_TRACE") != nullptr; + if (!on) return; + FILE* f = std::fopen("/proc/self/status", "r"); + if (!f) return; + char line[256]; + long long kb = -1; + while (std::fgets(line, sizeof line, f)) + if (std::strncmp(line, "RssFile:", 8) == 0) { kb = std::atoll(line + 8); break; } + std::fclose(f); + std::fprintf(stderr, "strata rss: %s: RssFile %.2f GiB\n", where, (double) kb / (1024.0 * 1024.0)); + std::fflush(stderr); +} + bool refill_blocking() { static const bool v = std::getenv("STRATA_REFILL_BLOCKING") != nullptr; return v; @@ -1141,6 +1205,15 @@ int main(int argc, char** argv) { // pipe or a file is block-buffered, so a program that dies loses every line it had already printed - which // turns "it crashed at step 7" into "it crashed somewhere", and the difference is a debugging session. std::setvbuf(stdout, nullptr, _IONBF, 0); +#if (defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)) && !defined(_WIN32) + // AMD, a file-backed arena (STRATA_ARENA_MMAP): ROCclr copies a pageable source of 1 MiB or more by locking its + // pages in place (a GPU userptr), and keeps them - so every expert the VRAM fill copied from the mapped + // experts.bin stayed resident, the release of the VRAM-held ones was undone by the driver at once, and a + // 32 GB PC ran with ~0.3 GB free: the kernel swapped, and a turn's checkpoint took 25-80 s. Above this size + // ROCclr stages through its own pinned buffers instead; decode is unchanged (49.06 vs 49.16 ms/window). + if (std::getenv("STRATA_ARENA_MMAP") && std::getenv("STRATA_ARENA_MMAP")[0] == '1') + setenv("GPU_PINNED_MIN_XFER_SIZE", "1000000", 0); // MiB; an explicit setting wins +#endif // Load every CUDA kernel when the context is created, before the expert cache takes the free VRAM. With the // default lazy loading, a kernel first used mid-prompt (MMQ for IQ3_XXS at 64K+ on a 12 GB card) found no VRAM // left for its code and the engine ended ("out of memory: cudaFuncSetAttribute"). Costs ~30 MB of VRAM. @@ -2062,6 +2135,44 @@ int main(int argc, char** argv) { } if (native_pack) skip.insert("token_embd.weight"); } + // Layer split with explicit split points: every GPU holds only the dense weights of ITS layers (the PLE tensors + // stay everywhere). Without this each card keeps a full copy (~3.4 GB for the Coder) that its stage never + // reads - VRAM the expert cache wants. On by default in the AMD (HIP) builds, where it was measured (PR #639, + // 2x MI50); STRATA_STAGE_TRIM=0 keeps the full copies there. The CUDA build keeps the full copies unless + // STRATA_STAGE_TRIM=1, until it has run on NVIDIA cards. + const std::set skip_base = skip; + const bool stage_trim = multi_gpu && !split_auto && !split_at.empty() && [] { + const char* v = std::getenv("STRATA_STAGE_TRIM"); + if (v != nullptr && v[0] != 0) return std::string(v) != "0"; +#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) + return true; +#else + return false; +#endif + }(); + // keep_routers: CUDA0 with --mmap-experts keeps every layer's router (ffn_gate_inp, ~2.5 MiB a layer) - the file + // tier's routing-aware prefetch (RouterLookahead, below) copies all of them from CUDA0's arena, and would + // otherwise turn itself off + auto add_foreign = [&](int64_t lb, int64_t le, std::set& out, bool keep_routers) { + std::FILE* f = std::fopen((o.pack + "/index.txt").c_str(), "rb"); + if (!f) return; + char line[1024], name[256]; + while (std::fgets(line, sizeof line, f)) { + if (line[0] == '#' || std::sscanf(line, "%255s", name) != 1) continue; + const std::string n = name; + if (n.rfind("blk.", 0) != 0 || n.find("ple") != std::string::npos) continue; + if (keep_routers && n.ends_with(".ffn_gate_inp.weight")) continue; + const int64_t l = std::atoll(name + 4); + if (l < lb || l >= le) out.insert(n); + } + std::fclose(f); + }; + if (stage_trim) { + add_foreign(0, split_at[0], skip, o.mmap_experts); + strata::core::NativeDense::set_layer_range(0, (int) split_at[0]); + std::fprintf(stderr, "strata generate: layer split: CUDA0 loads the dense weights of layers 0-%lld only\n", + (long long) split_at[0] - 1); + } uint64_t pool_bytes = 0; if (!strata::core::WeightTable::pool_bytes(o.pack, pool_bytes, err, skip.empty() ? nullptr : &skip)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); @@ -2393,16 +2504,31 @@ int main(int argc, char** argv) { return 1; } const strata::core::OnDevice on(st.dev); + std::set skip_s = skip_base; + uint64_t pool_s = pool_bytes; + if (stage_trim) { + const int64_t lb = split_at[i], le = i + 1 < split_at.size() ? split_at[i + 1] : g.n_layers; + add_foreign(lb, le, skip_s, false); + strata::core::NativeDense::set_layer_range((int) lb, (int) le); + if (!strata::core::WeightTable::pool_bytes(o.pack, pool_s, err, &skip_s)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + std::fprintf(stderr, "strata generate: layer split: CUDA%d loads the dense weights of layers %lld-%lld only\n", + st.dev, (long long) lb, (long long) le - 1); + } else { + skip_s = skip; + } void* arena_s = nullptr; - if (cudaMalloc(&arena_s, pool_bytes) != cudaSuccess || - !st.wt.load(o.pack, arena_s, pool_bytes, err, skip.empty() ? nullptr : &skip)) { + if (cudaMalloc(&arena_s, pool_s) != cudaSuccess || + !st.wt.load(o.pack, arena_s, pool_s, err, skip_s.empty() ? nullptr : &skip_s)) { cudaGetLastError(); size_t free_b = 0, total_b = 0; // #486: what that card had free cudaMemGetInfo(&free_b, &total_b); std::fprintf(stderr, "strata generate: layer split, CUDA%d weights: %s (%llu MiB needed, %llu MiB of %llu " "MiB free on that card)\n", st.dev, err.empty() ? "the weight arena does not fit" : err.c_str(), - (unsigned long long) (pool_bytes >> 20), (unsigned long long) (free_b >> 20), + (unsigned long long) (pool_s >> 20), (unsigned long long) (free_b >> 20), (unsigned long long) (total_b >> 20)); return 1; } @@ -3221,6 +3347,12 @@ int main(int argc, char** argv) { // to hold back is the windows - and `free_b` has already lost the drafter. const int64_t room = stage_room(st.dev, true, false); const strata::core::OnDevice on(st.dev); + { + size_t fb = 0, tb = 0; + cudaMemGetInfo(&fb, &tb); + std::fprintf(stderr, "strata generate: layer split, CUDA%d: %.2f GiB free of %.2f, room for experts %.2f GiB\n", + st.dev, (double) fb / 1073741824.0, (double) tb / 1073741824.0, (double) room / 1073741824.0); + } std::vector sized; int64_t used = 0; for (const auto& pr : st.profile) { @@ -3990,6 +4122,31 @@ int main(int argc, char** argv) { } thits.d_res = d_res; thits.n_expert = g.n_expert; + // a file-backed arena (STRATA_ARENA_MMAP): the experts no GPU holds are the ones the CPU pool and the + // prompt path will read - start reading them now instead of faulting them in 4 KB at a time mid-request + // ... and the ones a GPU holds are handed back first (STRATA_ARENA_RELEASE=0 keeps them): the fill read the + // whole arena, and left mapped and referenced it crowds every other allocation into swap + { + static const bool keep = std::getenv("STRATA_ARENA_RELEASE") && std::getenv("STRATA_ARENA_RELEASE")[0] == '0'; + rss_probe("before the release"); + uint64_t released = 0; + if (!keep) + for (size_t i = 0; i < host_res.size(); ++i) + if (host_res[i] != strata::core::kNotResident) + released += srcp->release((int64_t) i / g.n_expert, (int64_t) i % g.n_expert); + if (released > 0) + std::fprintf(stderr, "strata generate: expert arena: %.2f GiB of VRAM-held experts handed back to the OS\n", + (double) released / (1024.0 * 1024.0 * 1024.0)); + rss_probe("after the release"); + int64_t pf = 0; + for (size_t i = 0; i < host_res.size(); ++i) + if (host_res[i] == strata::core::kNotResident) { + srcp->prefetch((int64_t) i / g.n_expert, (int64_t) i % g.n_expert); + ++pf; + } + (void) pf; + rss_probe("after the prefetch hints"); + } for (auto& st : stages) { // layer split across GPUs: the same table on every device const strata::core::OnDevice on(st->dev); if (cudaMalloc((void**) &st->d_res, host_res.size() * sizeof(int32_t)) != cudaSuccess || @@ -4404,6 +4561,7 @@ int main(int argc, char** argv) { } else { std::fprintf(stderr, "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)\n"); } + rss_probe("the prompt path set up"); // layer split across GPUs: a prompt path per stage, each handing its chunk's rows to the next. // THE CHUNK STEPS DOWN INSTEAD OF EXITING. A split's stage caches are sized after the arena is registered, and // the prompt path's own buffers (no loan) are not priced into them: with the whole arena pinned (#253) a @@ -4878,6 +5036,7 @@ int main(int argc, char** argv) { } // plan v0.3 P6: swaps in flight - (residency index, slot) admitted when adapt_ev has completed std::vector> pending; + std::vector pin_live; // the swaps' locked arena pages (pin_blob), unlocked once they have landed cudaEvent_t adapt_ev = nullptr; cudaEventCreateWithFlags(&adapt_ev, cudaEventDisableTiming); // a layer split's later stages keep a copy of the residency table on their devices, and swap on their own @@ -4900,8 +5059,12 @@ int main(int argc, char** argv) { else if (cudaEventQuery(st->adapt_ev) != cudaSuccess) return; } for (auto& st : stages) st->adapt_live = false; + unpin_blobs(pin_live); src.commit_exchanges(); // the resident RAM mode: the evicted experts take their places in RAM - for (const auto& [i, slot] : pending) host_res[(size_t) i] = slot; + for (const auto& [i, slot] : pending) { + host_res[(size_t) i] = slot; + srcp->release((int64_t) i / g.n_expert, (int64_t) i % g.n_expert); // in VRAM now: RAM not needed + } pending.clear(); res_upload(); }; @@ -4933,6 +5096,14 @@ int main(int argc, char** argv) { std::sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.gain > b.gain; }); if ((int) swaps.size() > o.adapt_swaps) swaps.resize((size_t) o.adapt_swaps); if (!resident_stage_swaps(src, xcache, host_res, g.n_expert, swaps, adapt_stream)) return false; + if (pin_blobs_on()) { // lock the batch's source pages (a file-backed arena on AMD; see pin_blobs) + std::vector> spans; + for (const Swap& s : swaps) + if (const uint8_t* b = srcp->blob(s.layer, s.in)) + spans.emplace_back((uintptr_t) b, + (uintptr_t) b + strata::kernels::cpu::expert_layout().blob_bytes(s.layer)); + pin_blobs(std::move(spans), pin_live); + } bool main_live = false; for (const Swap& s : swaps) { const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out; @@ -4944,11 +5115,15 @@ int main(int argc, char** argv) { if (slot < 0 || b == nullptr || cudaMemcpyAsync(gs ? gs->cache.device_slot(slot) : xcache.device_slot(slot), b, (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer), - cudaMemcpyHostToDevice, gs ? gs->adapt_stream : adapt_stream) != cudaSuccess) + cudaMemcpyHostToDevice, gs ? gs->adapt_stream : adapt_stream) != cudaSuccess) { + std::fprintf(stderr, "strata serve: adaptive swap copy failed (layer %d, slot %d, pinned %d): %s\n", + (int) s.layer, (int) slot, pin_live.empty() ? 0 : 1, cudaGetErrorString(cudaGetLastError())); return false; + } if (gs) gs->adapt_live = true; else main_live = true; host_res[out] = strata::core::kNotResident; // evicted now: the CPU computes it meanwhile + srcp->prefetch(s.layer, s.out); // a file-backed arena released its pages: read them back ahead pending.emplace_back((int32_t) in, slot); // resident once the copy has landed } if (!swaps.empty()) cudaEventRecord(adapt_ev, adapt_stream); @@ -5065,6 +5240,7 @@ int main(int argc, char** argv) { const int64_t free_mib = (int64_t) (free_b >> 20); if (free_mib >= 256) { std::fprintf(stderr, "strata serve: %lld MiB of VRAM free with everything loaded\n", (long long) free_mib); + rss_probe("serving"); } else if (reserve_adapted) { // #496: the reserve was already lowered to make the cache fit - a bigger one would leave it no room std::fprintf(stderr, "strata serve: WARNING: %lld MiB of VRAM free with everything loaded - this card " @@ -6568,6 +6744,7 @@ int main(int argc, char** argv) { } // plan v0.3 P6: swaps in flight - (residency index, slot) admitted when adapt_ev has completed std::vector> pending; + std::vector pin_live; // the swaps' locked arena pages (pin_blob), unlocked once they have landed cudaEvent_t adapt_ev = nullptr; cudaEventCreateWithFlags(&adapt_ev, cudaEventDisableTiming); int64_t adapt_rounds = 0; // counted here: `rounds` is declared below the adapt lambda @@ -6584,8 +6761,12 @@ int main(int argc, char** argv) { } if (trace_pending) std::fprintf(stderr, "strata: PENDING landed, %zu experts become resident\n", pending.size()); + unpin_blobs(pin_live); src.commit_exchanges(); // the resident RAM mode: the evicted experts take their places in RAM - for (const auto& [i, slot] : pending) host_res[(size_t) i] = slot; + for (const auto& [i, slot] : pending) { + host_res[(size_t) i] = slot; + srcp->release((int64_t) i / g.n_expert, (int64_t) i % g.n_expert); // in VRAM now: RAM not needed + } pending.clear(); if (d_res != nullptr) cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); @@ -6635,6 +6816,14 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: an adaptive refill failed (copying evicted experts back)\n"); return false; } + if (pin_blobs_on()) { // lock the batch's source pages (a file-backed arena on AMD; see pin_blobs) + std::vector> spans; + for (const Swap& s : swaps) + if (const uint8_t* b = srcp->blob(s.layer, s.in)) + spans.emplace_back((uintptr_t) b, + (uintptr_t) b + strata::kernels::cpu::expert_layout().blob_bytes(s.layer)); + pin_blobs(std::move(spans), pin_live); + } for (const Swap& s : swaps) { const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out; const int32_t slot = host_res[out]; @@ -6647,6 +6836,7 @@ int main(int argc, char** argv) { return false; } host_res[out] = strata::core::kNotResident; // evicted now: the CPU computes it meanwhile + srcp->prefetch(s.layer, s.out); // a file-backed arena released its pages: read them back ahead pending.emplace_back((int32_t) in, slot); // resident once the copy has landed } if (!swaps.empty()) cudaEventRecord(adapt_ev, adapt_stream); diff --git a/tools/draft_vocab.py b/tools/draft_vocab.py index 77fa6b98..b3cc9fc5 100644 --- a/tools/draft_vocab.py +++ b/tools/draft_vocab.py @@ -10,12 +10,23 @@ Chinese drafted almost nothing (#137). This adds whole scripts to a subset: --add takes han, kana, hangul, cjk_punct, cjk (those four) or cyrillic. The base ids keep their order; the added ones follow in id order. --stats prints what a subset holds. + +A language written in a script the base already holds (French, Spanish, German... in Latin letters) needs specific +words and word pieces, not a whole script. --corpus adds the tokens of a text corpus in that language: the most +frequent ones that together cover --coverage (default 0.99) of the corpus's token occurrences (#597): + + python tools/draft_vocab.py --gguf -00001-of-0000N.gguf --base data/draft_vocab_en.bin \ + --corpus fr1.txt fr2.txt ... --coverage 0.99 --out data/draft_vocab_fr.bin + +It prints the share of the corpus's occurrences outside the base and outside the new subset. --add and --corpus +can be combined. """ from __future__ import annotations import argparse import sys from array import array +from collections import Counter from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) @@ -50,11 +61,41 @@ def token_text(tok, i: int) -> str | None: return None +def corpus_counts(tok, paths) -> Counter: + """Token occurrences over the corpus files (UTF-8 text, tokenized as plain text: no special tokens).""" + counts: Counter = Counter() + for path in paths: + counts.update(tok.encode(Path(path).read_text(encoding="utf-8"))) + return counts + + +def covering(counts: Counter, coverage: float) -> list[int]: + """The most frequent ids (ties: the lower id first) that together cover `coverage` of the occurrences.""" + total = sum(counts.values()) + picked, covered = [], 0 + for i, c in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])): + if covered >= coverage * total: + break + picked.append(i) + covered += c + return picked + + +def outside(counts: Counter, ids) -> float: + """The share of the occurrences whose token is not in `ids`.""" + total = sum(counts.values()) + have = set(ids) + return sum(c for i, c in counts.items() if i not in have) / total if total else 0.0 + + def main() -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--gguf", required=True, help="the model's (first) GGUF file: its vocabulary") ap.add_argument("--base", help="the subset to extend (int32 ids)") ap.add_argument("--add", default="", help="comma list: han, kana, hangul, cjk_punct, cjk, cyrillic") + ap.add_argument("--corpus", nargs="+", default=[], help="UTF-8 text files in the language to add (#597)") + ap.add_argument("--coverage", type=float, default=0.99, + help="with --corpus: the share of its token occurrences the added tokens cover (default 0.99)") ap.add_argument("--out", help="where to write the new subset") ap.add_argument("--stats", action="store_true", help="print what the base (and the new) subset holds") a = ap.parse_args() @@ -72,8 +113,12 @@ def main() -> int: if any(nm not in SCRIPTS for nm in names): sys.exit(f"--add {x}: expected one of {', '.join([*SCRIPTS, *GROUPS])}") want.update(names) + if not 0 < a.coverage <= 1: + sys.exit("--coverage: expected a share in (0, 1]") + counts = corpus_counts(tok, a.corpus) if a.corpus else Counter() + from_corpus = set(covering(counts, a.coverage)) if counts else set() have = set(base) - added = [i for i in range(n) if i not in have and kinds[i] & want] + added = [i for i in range(n) if i not in have and (kinds[i] & want or i in from_corpus)] ids = base + added def stats(label, sel): @@ -86,6 +131,11 @@ def main() -> int: stats("base", base) if added: stats("new", ids) + if counts: + print(f"corpus: {sum(counts.values())} token occurrences, {len(counts)} distinct; " + f"{len(from_corpus)} tokens cover {a.coverage:g}, {len(from_corpus - have)} of them not in the base") + print(f"corpus occurrences outside the base: {outside(counts, base):.2%}, outside the new subset: " + f"{outside(counts, ids):.2%}") if a.out: Path(a.out).write_bytes(array("i", ids).tobytes()) print(f"wrote {a.out}: {len(ids)} ids ({len(added)} added)") diff --git a/tools/make_profile.py b/tools/make_profile.py index 0f023848..9916cf10 100644 --- a/tools/make_profile.py +++ b/tools/make_profile.py @@ -6,9 +6,12 @@ ranks fewer pairs than a card can hold caps the cache (issue #46: a 32 GB card s writes one that ranks all 24,576. The order: the base profile's ranking (default: the shipped data/expert-profile.bin), then the pairs your routing -traces used, most frequent first, then every pair still missing, interleaved across the layers. +traces used, most frequent first, then every pair still missing, interleaved across the layers. The base is only +*appended to*, never reordered - and the shipped profile already ranks all 24,576 pairs, so with it a trace is a +no-op. `--reorder` ranks the traces first and lets the base fill the rest, which is how a workload's trace decides +the top; `--no-base` drops the base entirely. - python tools/make_profile.py [TRACE ...] [--base data/expert-profile.bin | --no-base] [--out PATH] + python tools/make_profile.py [TRACE ...] [--base data/expert-profile.bin | --no-base] [--reorder] [--out PATH] [--n-expert 256] (a pruned model: GSQ-RCO Coder keeps 256 of 512) A routing trace comes from a one-shot engine run with `--dump-routing FILE` (a prompt typical of your use; the @@ -60,39 +63,56 @@ def write_profile(path, ranked, n_expert=N_EXPERT): f.write(struct.pack("<%di" % n_expert, *table[layer])) -def main(): - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("traces", nargs="*", help="routing traces from --dump-routing") - ap.add_argument("--base", default=str(ROOT / "data" / "expert-profile.bin"), help="ranking to keep first") - ap.add_argument("--no-base", action="store_true", help="rank by the traces only") - ap.add_argument("--out", default=str(ROOT / "data" / "expert-profile.bin")) - ap.add_argument("--n-expert", type=int, default=N_EXPERT, help="experts per layer (default 512)") - a = ap.parse_args() +def rank_profile(base_pairs, trace_freq, n_expert=N_EXPERT, no_base=False, reorder=False): + """The ranked (layer, expert) list and the counts it was built from (`base`, `trace`, `fill`). - ranked, seen = [], set() + Default: the base's order, then the traces' pairs most frequent first, then the fill. With `reorder` (or + `no_base`) the traces' pairs come first, so a base that already ranks every pair no longer hides them; the base + (unless `no_base`) and then the fill follow. A base is never reordered against itself - it only ever fills.""" + ranked, seen, counts = [], set(), defaultdict(int) - def take(pairs): + def take(pairs, key): for p in pairs: p = (int(p[0]), int(p[1])) if p not in seen: seen.add(p) ranked.append(p) + counts[key] += 1 + + trace_pairs = [p for p, _ in sorted(trace_freq.items(), key=lambda kv: (-kv[1], kv[0]))] + if no_base or reorder: + take(trace_pairs, "trace") + if not no_base: + take(base_pairs, "base") + if not (no_base or reorder): + take(trace_pairs, "trace") + take(((layer, e) for e in range(n_expert) for layer in range(N_LAYER)), "fill") + return ranked, counts + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("traces", nargs="*", help="routing traces from --dump-routing") + ap.add_argument("--base", default=str(ROOT / "data" / "expert-profile.bin"), help="ranking to keep first") + ap.add_argument("--no-base", action="store_true", help="rank by the traces only") + ap.add_argument("--reorder", action="store_true", + help="rank the traces' pairs before the base's (the base, then the fill, follow); needed with a " + "base that already ranks every pair, where --base alone cannot change the order") + ap.add_argument("--out", default=str(ROOT / "data" / "expert-profile.bin")) + ap.add_argument("--n-expert", type=int, default=N_EXPERT, help="experts per layer (default 512)") + a = ap.parse_args() ne = a.n_expert - if not a.no_base: - take(read_profile(a.base, ne)) - n_base = len(ranked) freq = defaultdict(int) for t in a.traces: for p, c in read_trace(t, ne).items(): freq[p] += c - take(p for p, _ in sorted(freq.items(), key=lambda kv: (-kv[1], kv[0]))) - n_trace = len(ranked) - n_base - take((layer, e) for e in range(ne) for layer in range(N_LAYER)) # the rest, across the layers + base_pairs = [] if a.no_base else read_profile(a.base, ne) + ranked, counts = rank_profile(base_pairs, freq, ne, no_base=a.no_base, reorder=a.reorder) write_profile(a.out, ranked, ne) assert read_profile(a.out, ne) == ranked, "the profile did not survive the round trip" - print(f"wrote {a.out}: {len(ranked)} ranked pairs ({n_base} from the base, {n_trace} from the traces, " - f"{len(ranked) - n_base - n_trace} filled in)") + print(f"wrote {a.out}: {len(ranked)} ranked pairs ({counts['base']} from the base, {counts['trace']} from the " + f"traces, {counts['fill']} filled in)") if __name__ == "__main__": diff --git a/tools/test_draft_vocab.py b/tools/test_draft_vocab.py new file mode 100644 index 00000000..2375a223 --- /dev/null +++ b/tools/test_draft_vocab.py @@ -0,0 +1,47 @@ +"""Tests for tools/draft_vocab.py's corpus coverage mode (#597): the most frequent tokens of a corpus that together cover +a given share of its occurrences. No model, no GPU. + + python -m unittest tools.test_draft_vocab +""" +from __future__ import annotations + +import sys +import tempfile +import unittest +from collections import Counter +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import draft_vocab as DV # noqa: E402 + + +class Coverage(unittest.TestCase): + def test_most_frequent_first_until_the_share_is_covered(self): + c = Counter({7: 50, 3: 30, 9: 15, 4: 5}) # 100 occurrences + self.assertEqual(DV.covering(c, 0.5), [7]) + self.assertEqual(DV.covering(c, 0.8), [7, 3]) + self.assertEqual(DV.covering(c, 0.81), [7, 3, 9]) + self.assertEqual(DV.covering(c, 1.0), [7, 3, 9, 4]) + + def test_ties_take_the_lower_id_first(self): + self.assertEqual(DV.covering(Counter({5: 10, 2: 10, 8: 10}), 0.5), [2, 5]) + + def test_share_outside_a_subset(self): + c = Counter({1: 60, 2: 30, 3: 10}) + self.assertAlmostEqual(DV.outside(c, [1]), 0.4) + self.assertAlmostEqual(DV.outside(c, [1, 2, 3]), 0.0) + self.assertEqual(DV.outside(Counter(), [1]), 0.0) + + def test_corpus_counts_reads_every_file(self): + class Tok: # one id per character + def encode(self, text): + return [ord(ch) for ch in text] + with tempfile.TemporaryDirectory() as d: + a, b = Path(d) / "a.txt", Path(d) / "b.txt" + a.write_text("été", encoding="utf-8") + b.write_text("eté", encoding="utf-8") + self.assertEqual(DV.corpus_counts(Tok(), [a, b]), Counter({ord("é"): 3, ord("t"): 2, ord("e"): 1})) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_make_profile.py b/tools/test_make_profile.py new file mode 100644 index 00000000..f9c36202 --- /dev/null +++ b/tools/test_make_profile.py @@ -0,0 +1,104 @@ +"""Tests for tools/make_profile.py, without a model: synthetic profiles and routing traces. + + python -m unittest tools.test_make_profile +""" +from __future__ import annotations + +import struct +import sys +import tempfile +import unittest +from collections import defaultdict +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +import make_profile as MP # noqa: E402 + +NE = 4 # a tiny "experts per layer"; the layer count is fixed at MP.N_LAYER + + +def write_trace(path, records): + """One record per (layer, [expert ids]); the reader skips k weights after the k ids.""" + with open(path, "wb") as f: + for layer, experts in records: + f.write(struct.pack(" the smaller pair first + self.assertEqual(ranked[:3], [(2, 0), (3, 0), (1, 0)]) + + def test_default_appends_only(self): + base = [(0, 0), (0, 1)] + freq = defaultdict(int, {(0, 0): 5, (1, 3): 9}) + ranked, _ = MP.rank_profile(base, freq, NE) + self.assertEqual(ranked[:3], [(0, 0), (0, 1), (1, 3)]) # base first; (0,0) already there, not moved + + def test_no_base_uses_the_traces_then_the_fill(self): + base = [(0, 0), (0, 1)] + freq = defaultdict(int, {(1, 3): 9, (0, 0): 5}) + ranked, counts = MP.rank_profile(base, freq, NE, no_base=True) + self.assertEqual(ranked[:2], [(1, 3), (0, 0)]) + self.assertEqual(counts["base"], 0) + self.assertEqual(len(ranked), MP.N_LAYER * NE) + + def test_reorder_without_traces_is_the_default(self): + base = full_base() + self.assertEqual(MP.rank_profile(base, defaultdict(int), NE, reorder=True)[0], base) + + +class Main(unittest.TestCase): + def run_main(self, argv): + old, sys.argv = sys.argv, ["make_profile.py"] + argv + try: + MP.main() + finally: + sys.argv = old + + def test_end_to_end_reorder_over_a_complete_base(self): + with tempfile.TemporaryDirectory() as d: + base = Path(d) / "base.bin" + out = Path(d) / "out.bin" + trace = Path(d) / "t.bin" + MP.write_profile(str(base), full_base(), NE) + write_trace(str(trace), [(5, [1]), (6, [2]), (6, [2]), (6, [2])]) + self.run_main([str(trace), "--base", str(base), "--reorder", "--n-expert", str(NE), "--out", str(out)]) + ranked = MP.read_profile(str(out), NE) + self.assertEqual(ranked[:2], [(6, 2), (5, 1)]) # most frequent first + self.assertEqual(set(ranked), set(full_base())) + # and without --reorder it is the base's order, untouched + self.run_main([str(trace), "--base", str(base), "--n-expert", str(NE), "--out", str(out)]) + self.assertEqual(MP.read_profile(str(out), NE), full_base()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_setup_amd.py b/tools/test_setup_amd.py index a00a6502..f98f657b 100644 --- a/tools/test_setup_amd.py +++ b/tools/test_setup_amd.py @@ -336,6 +336,81 @@ def setup_hip(text): return _HIP_DEVICES(text=text) +class CalibrationKey(unittest.TestCase): + """#566: a calibration is saved and found again per PC and model (hardware_key). A HIP config's cards are AMD's, + in HIP's numbering - nvidia-smi named them "?" (or another card with that number) before - and setup reuses a + saved calibration on Linux HIP. The NVIDIA key and the settings file's format are unchanged.""" + AMD = [{"index": 0, "name": "AMD Radeon RX 7900 XTX", "vram_gb": 23.98, "arch": "gfx1100"}, + {"index": 1, "name": "AMD Radeon RX 7900 XT", "vram_gb": 19.98, "arch": "gfx1100"}, + {"index": 2, "name": "AMD Radeon (gfx1201)", "vram_gb": 15.92, "arch": "gfx1201"}, + {"index": 3, "name": "AMD Radeon (gfx1036)", "vram_gb": 0.5, "arch": "gfx1036"}] + + def setUp(self): + self.patches = [mock.patch.object(setup, "amd_gpus", lambda *a, **k: [dict(g) for g in self.AMD]), + mock.patch.object(setup, "cpu_info", lambda: ("AMD Ryzen 9 7950X", 16)), + mock.patch.object(setup, "ram_gb", lambda: 63.6)] + for p in self.patches: + p.start() + + def tearDown(self): + for p in self.patches: + p.stop() + + @staticmethod + def cfg(gpu, backend="hip", ctx="32768"): + c = {"model_name": "qwen3.8-flash-next-iq3_xxs", "args": ["--max-context", ctx, "--kv", "int8"], "gpu": gpu} + if backend: + c["backend"] = backend + return c + + def test_hip_key_names_the_amd_card_and_its_arch(self): + def no_nvidia(*a, **k): # a HIP config never asks nvidia-smi (a PC with both kinds) + raise AssertionError("gpu_info called for a HIP config") + with mock.patch.object(setup, "gpu_info", no_nvidia): + self.assertEqual(setup.hardware_key(self.cfg(0)), + "AMD Radeon RX 7900 XTX (gfx1100)|24GB|AMD Ryzen 9 7950X|64GB|qwen3.8-flash-next-iq3_xxs|" + "32768|text") + # the arch is not repeated when the name already holds it (no product name in sysfs) + self.assertTrue(setup.hardware_key(self.cfg(2)).startswith("AMD Radeon (gfx1201)|16GB|")) + + def test_two_cards_of_one_arch_are_two_keys(self): + keys = {setup.hardware_key(self.cfg(i)) for i in (0, 1, 2)} + self.assertEqual(len(keys), 3) + + def test_a_split_names_every_card(self): + self.assertTrue(setup.hardware_key(self.cfg([1, 0])).startswith( + "AMD Radeon RX 7900 XT (gfx1100) + AMD Radeon RX 7900 XTX (gfx1100)|44GB|")) + + def test_no_gpu_in_the_config_is_the_supported_card_with_the_most_vram(self): + self.assertTrue(setup.hardware_key(self.cfg(None)).startswith("AMD Radeon RX 7900 XTX (gfx1100)|24GB|")) + + def test_a_card_that_is_gone_is_unknown(self): + self.assertTrue(setup.hardware_key(self.cfg(7)).startswith("?|0GB|")) + + def test_nvidia_key_unchanged(self): + def amd(*a, **k): + raise AssertionError("amd_gpus called for an NVIDIA config") + with mock.patch.object(setup, "amd_gpus", amd), \ + mock.patch.object(setup, "gpu_info", lambda i=None: {"name": "NVIDIA GeForce RTX 5070", "vram_gb": 11.94}): + self.assertEqual(setup.hardware_key(self.cfg(0, backend=None)), + "NVIDIA GeForce RTX 5070|12GB|AMD Ryzen 9 7950X|64GB|qwen3.8-flash-next-iq3_xxs|32768|text") + self.assertEqual(setup.hardware_key(self.cfg([0, 1], backend="cuda")), + "NVIDIA GeForce RTX 5070 + NVIDIA GeForce RTX 5070|24GB|AMD Ryzen 9 7950X|64GB|" + "qwen3.8-flash-next-iq3_xxs|32768|text") + + def test_setup_reuses_a_saved_calibration_on_linux_hip(self): + cfg = self.cfg(1) + saved = {"settings": {"pcie_frac": 0.0}, "tok_s": 40.1, "date": "2026-10-03"} + other = {"settings": {"pcie_frac": 0.5}, "tok_s": 50.0, "date": "2026-10-02"} + store = {"calibration": {setup.hardware_key(cfg): saved, setup.hardware_key(self.cfg(0)): other}} + with mock.patch.object(setup, "load_settings", lambda: store): + with mock.patch.object(setup, "WIN", False): + self.assertEqual(setup.setup_calibration(cfg, hip=True), saved) # its own card's, not the XTX's + self.assertIsNone(setup.setup_calibration(self.cfg(2), hip=True)) # never tuned on that card + with mock.patch.object(setup, "WIN", True): + self.assertIsNone(setup.setup_calibration(cfg, hip=True)) # Windows HIP: defaults for now + + class WindowsHipVision(unittest.TestCase): def test_no_cpu_encoder_on_windows(self): with mock.patch.object(setup, "WIN", True), mock.patch.object(setup, "warn", lambda *a: None): diff --git a/tools/test_setup_draft_vocab.py b/tools/test_setup_draft_vocab.py index 6fedb4a8..09cac429 100644 --- a/tools/test_setup_draft_vocab.py +++ b/tools/test_setup_draft_vocab.py @@ -1,5 +1,5 @@ """Tests for setup.py's draft-vocabulary choice (#287): a setup run again without --draft-vocab keeps the subset the -model's config chose before (cyrillic, en), and refresh_draft_vocab copies the chosen shipped subset. Pure file work +model's config chose before (cyrillic, fr, en), and refresh_draft_vocab copies the chosen shipped subset. Pure file work in a temporary folder - no GPU, no downloads, no prompts. python -m unittest tools.test_setup_draft_vocab @@ -49,6 +49,37 @@ class Refresh(unittest.TestCase): self.assertEqual(hashlib.sha256((rt / "draft_vocab.bin").read_bytes()).hexdigest(), want) + def test_fr_replaces_a_shipped_subset_and_back(self): + # #597: the French subset is a shipped one too - a later --draft-vocab cjk (or en) replaces it again, while a + # subset made by hand stays + data = ROOT / "data" + if not (data / setup.DRAFT_VOCABS["fr"]).exists(): + self.skipTest("data/draft_vocab_fr.bin is not in this checkout") + sha = lambda p: hashlib.sha256(p.read_bytes()).hexdigest() # noqa: E731 + with tempfile.TemporaryDirectory() as d: + rt = Path(d) + (rt / "draft_vocab.bin").write_bytes((data / setup.DRAFT_VOCABS["en"]).read_bytes()) + setup.refresh_draft_vocab(rt, "fr") + self.assertEqual(sha(rt / "draft_vocab.bin"), sha(data / setup.DRAFT_VOCABS["fr"])) + setup.refresh_draft_vocab(rt, "cjk") + self.assertEqual(sha(rt / "draft_vocab.bin"), sha(data / setup.DRAFT_VOCABS["cjk"])) + (rt / "draft_vocab.bin").write_bytes(bytes([1, 0, 0, 0])) # made by hand: kept + setup.refresh_draft_vocab(rt, "fr") + self.assertEqual((rt / "draft_vocab.bin").read_bytes(), bytes([1, 0, 0, 0])) + + def test_fr_holds_the_en_subset_in_its_order(self): + # built with tools/draft_vocab.py --base data/draft_vocab_en.bin --corpus ...: the base first, unchanged + from array import array + data = ROOT / "data" + if not (data / setup.DRAFT_VOCABS["fr"]).exists(): + self.skipTest("data/draft_vocab_fr.bin is not in this checkout") + en = list(array("i", (data / setup.DRAFT_VOCABS["en"]).read_bytes())) + fr = list(array("i", (data / setup.DRAFT_VOCABS["fr"]).read_bytes())) + self.assertEqual(fr[:len(en)], en) + self.assertEqual(len(set(fr)), len(fr)) + self.assertEqual(fr[len(en):], sorted(fr[len(en):])) + + class SmallCardNote(unittest.TestCase): """#474: a card under 14 GB is told about a smaller draft subset - a note only, and not when one was chosen.""" @@ -57,7 +88,8 @@ class SmallCardNote(unittest.TestCase): self.assertTrue(note) self.assertIn("--draft-vocab en", " ".join(note)) self.assertIn("the draft head does not fit", " ".join(note)) - for vram, chosen in ((16.0, None), (24.0, None), (12.0, "en"), (12.0, "cyrillic"), (12.0, "cjk"), (0.0, None)): + for vram, chosen in ((16.0, None), (24.0, None), (12.0, "en"), (12.0, "cyrillic"), (12.0, "fr"), (12.0, "cjk"), + (0.0, None)): self.assertEqual(setup.draft_vocab_note(vram, chosen), [], (vram, chosen)) def test_sizes_follow_the_shipped_subsets(self): @@ -68,7 +100,7 @@ class SmallCardNote(unittest.TestCase): if not p.exists(): self.skipTest(f"data/{name} is not in this checkout") sizes[choice] = p.stat().st_size // 4 - for choice in ("en", "cyrillic"): + for choice in ("en", "cyrillic", "fr"): want = setup.DRAFT_VOCAB_MIB["cjk"] * sizes[choice] / sizes["cjk"] self.assertAlmostEqual(setup.DRAFT_VOCAB_MIB[choice], want, delta=3)