okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-142d-numa into f-1421bccef1cf8

main
2.6 KiB70 linesraw
1"""Opt-in: give the model files' page cache back when the server stops (STRATA_DROP_CACHE_ON_EXIT=1).
2
3Linux keeps a stopped model's GGUF/pack files in the page cache (MemAvailable counts it, `free` shows it as used), which
4helps a restart of the SAME model.  On a host that then starts a different, large model (a dual-socket server whose second
5NUMA node holds the old model's cache) some owners prefer the pages back at once.  Off by default.  Only this server's own
6model files are advised, and only after the engine process has ended (its mappings are gone, so the pages can go).
7"""
8from __future__ import annotations
9
10import os
11from pathlib import Path
12
13
14def enabled(env=None) -> bool:
15    env = os.environ if env is None else env
16    return os.name != "nt" and env.get("STRATA_DROP_CACHE_ON_EXIT", "").strip().lower() in ("1", "true", "yes", "on")
17
18
19def model_files(paths) -> list[str]:
20    """The regular files named by `paths` (a file, or a directory walked recursively); missing ones are skipped."""
21    out: list[str] = []
22    for p in paths:
23        if not p:
24            continue
25        q = Path(p)
26        try:
27            if q.is_file():
28                out.append(str(q))
29            elif q.is_dir():
30                out.extend(str(f) for f in sorted(q.rglob("*")) if f.is_file())
31        except OSError:
32            continue
33    return out
34
35
36def drop(paths, advise=None) -> int:
37    """posix_fadvise(DONTNEED) on every file of `paths`; returns how many files were advised.  Never raises."""
38    advise = advise or getattr(os, "posix_fadvise", None)
39    if advise is None:
40        return 0
41    n = 0
42    for f in model_files(paths):
43        try:
44            fd = os.open(f, os.O_RDONLY)
45        except OSError:
46            continue
47        try:
48            advise(fd, 0, 0, getattr(os, "POSIX_FADV_DONTNEED", 4))
49            n += 1
50        except OSError:
51            pass
52        finally:
53            os.close(fd)
54    return n
55
56
57def drop_after_exit(engine, env=None, advise=None) -> int:
58    """Called once the engine has been closed.  0 when not opted in or the engine still runs."""
59    if not enabled(env):
60        return 0
61    proc = getattr(engine, "proc", None)
62    if proc is not None and proc.poll() is None:
63        return 0
64    spawn = getattr(engine, "spawn", None)
65    args = list(spawn[1]) if spawn else []
66    wanted = {"--native", "--pack", "--mmproj", "--model"}
67    paths = [v for k, v in zip(args, args[1:]) if k in wanted]
68    n = drop(paths or [getattr(engine, "model_path", None)], advise)
69    print(f"[strata] STRATA_DROP_CACHE_ON_EXIT: released the page cache of {n} model files", flush=True)
70    return n