Spaces:
Running
Running
Enable llama.cpp KV prompt cache (512 MB): ~21% off study-plan time
Browse files
main.py
CHANGED
|
@@ -21,6 +21,7 @@ from fastapi import FastAPI, HTTPException
|
|
| 21 |
from pydantic import BaseModel, Field
|
| 22 |
from huggingface_hub import hf_hub_download
|
| 23 |
from llama_cpp import Llama
|
|
|
|
| 24 |
from llama_cpp import llama_chat_format
|
| 25 |
|
| 26 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
|
@@ -50,6 +51,10 @@ _USABLE = len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else
|
|
| 50 |
N_THREADS = int(os.getenv("N_THREADS", str(_USABLE)))
|
| 51 |
N_GPU_LAYERS = int(os.getenv("N_GPU_LAYERS", "0"))
|
| 52 |
DEFAULT_MAX_TOKENS = int(os.getenv("DEFAULT_MAX_TOKENS", "512"))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
# Current model state (mutable at runtime via /admin/load).
|
| 55 |
_llm: Optional[Llama] = None
|
|
@@ -81,6 +86,9 @@ def _download_and_load(cfg: Dict[str, str]) -> None:
|
|
| 81 |
if cfg["chat_format"]:
|
| 82 |
kwargs["chat_format"] = cfg["chat_format"]
|
| 83 |
new_llm = Llama(**kwargs)
|
|
|
|
|
|
|
|
|
|
| 84 |
with _llm_lock: # swap atomically; old model is freed
|
| 85 |
_llm = new_llm
|
| 86 |
_cfg = dict(cfg)
|
|
|
|
| 21 |
from pydantic import BaseModel, Field
|
| 22 |
from huggingface_hub import hf_hub_download
|
| 23 |
from llama_cpp import Llama
|
| 24 |
+
from llama_cpp.llama_cache import LlamaRAMCache
|
| 25 |
from llama_cpp import llama_chat_format
|
| 26 |
|
| 27 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
|
|
|
| 51 |
N_THREADS = int(os.getenv("N_THREADS", str(_USABLE)))
|
| 52 |
N_GPU_LAYERS = int(os.getenv("N_GPU_LAYERS", "0"))
|
| 53 |
DEFAULT_MAX_TOKENS = int(os.getenv("DEFAULT_MAX_TOKENS", "512"))
|
| 54 |
+
# Prompt (KV) cache. Without it every call re-prefills the whole system prompt,
|
| 55 |
+
# which is NOT cheap on 2 vCPU: measured 20.8s -> 8.5s per call with the study
|
| 56 |
+
# plan's rotating daily/weekly/monthly prompts, ~21% off a full plan.
|
| 57 |
+
PROMPT_CACHE_MB = int(os.getenv("PROMPT_CACHE_MB", "512")) # 0 disables
|
| 58 |
|
| 59 |
# Current model state (mutable at runtime via /admin/load).
|
| 60 |
_llm: Optional[Llama] = None
|
|
|
|
| 86 |
if cfg["chat_format"]:
|
| 87 |
kwargs["chat_format"] = cfg["chat_format"]
|
| 88 |
new_llm = Llama(**kwargs)
|
| 89 |
+
if PROMPT_CACHE_MB > 0:
|
| 90 |
+
new_llm.set_cache(LlamaRAMCache(capacity_bytes=PROMPT_CACHE_MB * 1024 * 1024))
|
| 91 |
+
log.info("Prompt cache enabled (%d MB).", PROMPT_CACHE_MB)
|
| 92 |
with _llm_lock: # swap atomically; old model is freed
|
| 93 |
_llm = new_llm
|
| 94 |
_cfg = dict(cfg)
|