fix(llm): _hf_gen_kwargs, truncated-JSON repair, ModalLLM warmup, debug-gated logs
Browse files- Add _hf_gen_kwargs to map complete() kwargs to transformers generate() correctly
(greedy vs sampled) so temperature/top_p actually apply.
- Repair max_tokens-truncated JSON in LlamaCppLLM.complete_json via close_truncated_json.
- Add ModalLLM.warmup() to pre-heat the GPU container before the first player turn.
- Gate complete/complete_json trace logs behind config.DEBUG to reduce noise.
- Remove duplicated helpers now living in utils.py.
- visualnovel/llm.py +46 -40
visualnovel/llm.py
CHANGED
|
@@ -14,44 +14,29 @@ Heavy imports are done lazily inside each real backend so a MOCK checkout needs
|
|
| 14 |
|
| 15 |
from __future__ import annotations
|
| 16 |
|
| 17 |
-
import contextlib
|
| 18 |
-
import os
|
| 19 |
-
import sys
|
| 20 |
-
from collections.abc import Generator
|
| 21 |
from typing import Any, Protocol
|
| 22 |
|
| 23 |
-
|
| 24 |
-
def _safe_print(msg: str) -> None:
|
| 25 |
-
"""Print to stdout, replacing unencodable chars (cp1252 on Windows terminals)."""
|
| 26 |
-
print(
|
| 27 |
-
msg.encode(sys.stdout.encoding or "utf-8", errors="replace").decode(
|
| 28 |
-
sys.stdout.encoding or "utf-8", errors="replace"
|
| 29 |
-
)
|
| 30 |
-
)
|
| 31 |
-
|
| 32 |
-
|
| 33 |
from . import config
|
|
|
|
| 34 |
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
"""Redirect the C-level stderr fd to /dev/null for the duration of the block.
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
"""
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
os.close(devnull_fd)
|
| 55 |
|
| 56 |
|
| 57 |
class LLMBackend(Protocol):
|
|
@@ -103,8 +88,15 @@ class LlamaCppLLM:
|
|
| 103 |
temperature=kw.get("temperature", 0.7),
|
| 104 |
top_p=kw.get("top_p", 0.9),
|
| 105 |
max_tokens=kw.get("max_tokens", 512),
|
|
|
|
| 106 |
)
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
|
| 110 |
# --------------------------------------------------------------------------- #
|
|
@@ -114,7 +106,9 @@ class TransformersLLM:
|
|
| 114 |
def __init__(self) -> None:
|
| 115 |
import torch # noqa: PLC0415
|
| 116 |
from transformers import AutoModelForCausalLM, AutoTokenizer # noqa: PLC0415
|
|
|
|
| 117 |
|
|
|
|
| 118 |
print(f"[llm] Loading {config.LLM_REPO}…")
|
| 119 |
self.tok = AutoTokenizer.from_pretrained(config.LLM_REPO)
|
| 120 |
self.model = AutoModelForCausalLM.from_pretrained(
|
|
@@ -139,10 +133,13 @@ class TransformersLLM:
|
|
| 139 |
)
|
| 140 |
|
| 141 |
def complete(self, messages: list[dict[str, str]], **kw: Any) -> str:
|
| 142 |
-
text
|
|
|
|
|
|
|
| 143 |
ids = self.tok(text, return_tensors="pt").to(self.model.device)
|
| 144 |
-
out = self.model.generate(**ids,
|
| 145 |
-
|
|
|
|
| 146 |
|
| 147 |
def complete_json(self, messages: list[dict[str, str]], schema: dict, **kw: Any) -> dict:
|
| 148 |
import json # noqa: PLC0415
|
|
@@ -181,8 +178,7 @@ class TransformersLLM:
|
|
| 181 |
# Disable Qwen3 thinking mode: <think> blocks waste tokens and can truncate the JSON
|
| 182 |
text = self._apply_template(augmented, enable_thinking=False)
|
| 183 |
ids = self.tok(text, return_tensors="pt").to(self.model.device)
|
| 184 |
-
|
| 185 |
-
out = self.model.generate(**ids, max_new_tokens=max_new)
|
| 186 |
raw = self.tok.decode(out[0][ids.input_ids.shape[1] :], skip_special_tokens=True)
|
| 187 |
|
| 188 |
# Prefer text AFTER </think>, fall back to text INSIDE <think>.
|
|
@@ -226,15 +222,25 @@ class ModalLLM:
|
|
| 226 |
self._cls = modal.Cls.from_name("vn-app", "ModalLLMBackend")
|
| 227 |
self._backend = self._cls()
|
| 228 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
def complete(self, messages: list[dict[str, str]], **kw: Any) -> str:
|
| 230 |
result = self._backend.complete.remote(messages, **kw)
|
| 231 |
-
|
|
|
|
| 232 |
return result
|
| 233 |
|
| 234 |
def complete_json(self, messages: list[dict[str, str]], schema: dict, **kw: Any) -> dict:
|
| 235 |
-
|
|
|
|
| 236 |
result = self._backend.complete_json.remote(messages, schema, **kw)
|
| 237 |
-
|
|
|
|
| 238 |
return result
|
| 239 |
|
| 240 |
|
|
|
|
| 14 |
|
| 15 |
from __future__ import annotations
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
from typing import Any, Protocol
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
from . import config
|
| 20 |
+
from .utils import _quiet_stderr, _safe_print, close_truncated_json, strip_think
|
| 21 |
|
| 22 |
|
| 23 |
+
def _hf_gen_kwargs(kw: dict[str, Any]) -> dict[str, Any]:
|
| 24 |
+
"""Map our complete()/complete_json() kwargs to transformers generate() kwargs.
|
|
|
|
| 25 |
|
| 26 |
+
Greedy decode when temperature is absent or 0; otherwise enable sampling so
|
| 27 |
+
temperature/top_p actually apply (generate() silently ignores them without
|
| 28 |
+
do_sample=True) and retries produce different outputs.
|
| 29 |
"""
|
| 30 |
+
out: dict[str, Any] = {"max_new_tokens": kw.get("max_tokens", 512)}
|
| 31 |
+
temperature = kw.get("temperature")
|
| 32 |
+
if temperature:
|
| 33 |
+
out["do_sample"] = True
|
| 34 |
+
out["temperature"] = temperature
|
| 35 |
+
if "top_p" in kw:
|
| 36 |
+
out["top_p"] = kw["top_p"]
|
| 37 |
+
else:
|
| 38 |
+
out["do_sample"] = False
|
| 39 |
+
return out
|
|
|
|
| 40 |
|
| 41 |
|
| 42 |
class LLMBackend(Protocol):
|
|
|
|
| 88 |
temperature=kw.get("temperature", 0.7),
|
| 89 |
top_p=kw.get("top_p", 0.9),
|
| 90 |
max_tokens=kw.get("max_tokens", 512),
|
| 91 |
+
presence_penalty=kw.get("presence_penalty", 0.0),
|
| 92 |
)
|
| 93 |
+
content = out["choices"][0]["message"]["content"]
|
| 94 |
+
try:
|
| 95 |
+
return json.loads(content)
|
| 96 |
+
except json.JSONDecodeError:
|
| 97 |
+
# max_tokens hit mid-object — the grammar can't close it, so we do.
|
| 98 |
+
print(f"[llm] truncated JSON ({len(content)} chars), repairing")
|
| 99 |
+
return json.loads(close_truncated_json(content))
|
| 100 |
|
| 101 |
|
| 102 |
# --------------------------------------------------------------------------- #
|
|
|
|
| 106 |
def __init__(self) -> None:
|
| 107 |
import torch # noqa: PLC0415
|
| 108 |
from transformers import AutoModelForCausalLM, AutoTokenizer # noqa: PLC0415
|
| 109 |
+
from transformers.utils import logging as hf_logging # noqa: PLC0415
|
| 110 |
|
| 111 |
+
hf_logging.set_verbosity_error() # advisories bypass stdlib logging config
|
| 112 |
print(f"[llm] Loading {config.LLM_REPO}…")
|
| 113 |
self.tok = AutoTokenizer.from_pretrained(config.LLM_REPO)
|
| 114 |
self.model = AutoModelForCausalLM.from_pretrained(
|
|
|
|
| 133 |
)
|
| 134 |
|
| 135 |
def complete(self, messages: list[dict[str, str]], **kw: Any) -> str:
|
| 136 |
+
# Thinking off: the only free-text consumer is compact_memory, where a 256-token
|
| 137 |
+
# budget would be eaten by the <think> block. strip_think() catches leftovers.
|
| 138 |
+
text = self._apply_template(messages, enable_thinking=False)
|
| 139 |
ids = self.tok(text, return_tensors="pt").to(self.model.device)
|
| 140 |
+
out = self.model.generate(**ids, **_hf_gen_kwargs(kw))
|
| 141 |
+
raw = self.tok.decode(out[0][ids.input_ids.shape[1] :], skip_special_tokens=True)
|
| 142 |
+
return strip_think(raw)
|
| 143 |
|
| 144 |
def complete_json(self, messages: list[dict[str, str]], schema: dict, **kw: Any) -> dict:
|
| 145 |
import json # noqa: PLC0415
|
|
|
|
| 178 |
# Disable Qwen3 thinking mode: <think> blocks waste tokens and can truncate the JSON
|
| 179 |
text = self._apply_template(augmented, enable_thinking=False)
|
| 180 |
ids = self.tok(text, return_tensors="pt").to(self.model.device)
|
| 181 |
+
out = self.model.generate(**ids, **_hf_gen_kwargs(kw))
|
|
|
|
| 182 |
raw = self.tok.decode(out[0][ids.input_ids.shape[1] :], skip_special_tokens=True)
|
| 183 |
|
| 184 |
# Prefer text AFTER </think>, fall back to text INSIDE <think>.
|
|
|
|
| 222 |
self._cls = modal.Cls.from_name("vn-app", "ModalLLMBackend")
|
| 223 |
self._backend = self._cls()
|
| 224 |
|
| 225 |
+
def warmup(self) -> None:
|
| 226 |
+
"""Fire-and-forget ping so the GPU container is warm before the first turn."""
|
| 227 |
+
try:
|
| 228 |
+
self._backend.complete.spawn([{"role": "user", "content": "hi"}], max_tokens=1)
|
| 229 |
+
except Exception as exc: # missing deployment must not kill server start
|
| 230 |
+
_safe_print(f"[ModalLLM] warmup skipped: {exc}")
|
| 231 |
+
|
| 232 |
def complete(self, messages: list[dict[str, str]], **kw: Any) -> str:
|
| 233 |
result = self._backend.complete.remote(messages, **kw)
|
| 234 |
+
if config.DEBUG:
|
| 235 |
+
_safe_print(f"[ModalLLM] complete -> {result[:120]!r}")
|
| 236 |
return result
|
| 237 |
|
| 238 |
def complete_json(self, messages: list[dict[str, str]], schema: dict, **kw: Any) -> dict:
|
| 239 |
+
if config.DEBUG:
|
| 240 |
+
_safe_print(f"[ModalLLM] complete_json input messages:\n{messages}\n")
|
| 241 |
result = self._backend.complete_json.remote(messages, schema, **kw)
|
| 242 |
+
if config.DEBUG:
|
| 243 |
+
_safe_print(f"[ModalLLM] complete_json -> {result}")
|
| 244 |
return result
|
| 245 |
|
| 246 |
|