okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
bccef1cf8
main
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 : 15env = os .environ if env is None else env 16return 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.""" 21out :list [str ]= [] 22for p in paths : 23if not p : 24continue 25q = Path (p ) 26try : 27if q .is_file (): 28out .append (str (q )) 29elif q .is_dir (): 30out .extend (str (f )for f in sorted (q .rglob ("*" ))if f .is_file ()) 31except OSError : 32continue 33return 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.""" 38advise = advise or getattr (os ,"posix_fadvise" ,None ) 39if advise is None : 40return 0 41n = 0 42for f in model_files (paths ): 43try : 44fd = os .open (f ,os .O_RDONLY ) 45except OSError : 46continue 47try : 48advise (fd ,0 ,0 ,getattr (os ,"POSIX_FADV_DONTNEED" ,4 )) 49n += 1 50except OSError : 51pass 52finally : 53os .close (fd ) 54return 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.""" 59if not enabled (env ): 60return 0 61proc = getattr (engine ,"proc" ,None ) 62if proc is not None and proc .poll ()is None : 63return 0 64spawn = getattr (engine ,"spawn" ,None ) 65args = list (spawn [1 ])if spawn else [] 66wanted = {"--native" ,"--pack" ,"--mmproj" ,"--model" } 67paths = [v for k ,v in zip (args ,args [1 :])if k in wanted ] 68n = drop (paths or [getattr (engine ,"model_path" ,None )],advise ) 69f"[strata] STRATA_DROP_CACHE_ON_EXIT: released the page cache of { n } model files" ,flush = True ) 70return n