fix ollama context size for non-latin text and the real system prompt size
(cherry picked from commit 0eb9ba2dfa)
This commit is contained in:
1 parent
59b01dcd3a
commit
360056a98a
3 files changed
+158
-6
No files matched your search
+23
-6
@@ -61,6 +61,21 @@ def _get_tokenizer():
|
||||
# Cached at import time. None if tiktoken is unavailable; consumers must handle.
|
||||
_TOKENIZER = _get_tokenizer()
|
||||
|
||||
# Anything past Latin Extended (CJK, Devanagari, Cyrillic, Arabic, ...).
|
||||
_NON_LATIN_RE = re.compile(r"[^\u0000-ɏ]")
|
||||
|
||||
|
||||
def _estimate_prompt_tokens(text: str) -> int:
|
||||
"""Rough token count for sizing a local model's context window.
|
||||
|
||||
chars/4 holds for English and code but not other scripts: on qwen2.5 a
|
||||
Chinese doc came out 2.8x larger than chars/4 and a Hindi one 3.7x, so
|
||||
num_ctx was too small and Ollama cut the prompt. Count non-Latin
|
||||
characters as one token each, which errs on the safe side for both.
|
||||
"""
|
||||
non_latin = len(_NON_LATIN_RE.findall(text))
|
||||
return (len(text) - non_latin) // _CHARS_PER_TOKEN + non_latin
|
||||
|
||||
|
||||
def _resolve_ollama_base_url(default: str) -> str:
|
||||
"""Resolve the Ollama base URL. Honors an explicit OLLAMA_BASE_URL first
|
||||
@@ -1408,7 +1423,8 @@ def _backend_pkg_hint(pkg: str, extra: str) -> str:
|
||||
)
|
||||
|
||||
|
||||
def _ollama_request_extras(user_message: str, max_completion_tokens: int) -> dict:
|
||||
def _ollama_request_extras(user_message: str, max_completion_tokens: int,
|
||||
system_prompt: str = "") -> dict:
|
||||
"""num_ctx/keep_alive for an Ollama request, sized to the prompt."""
|
||||
# Ollama defaults num_ctx to 2048 and silently truncates prompts larger
|
||||
# than that — the symptom is hollow 200 OK responses after the first few
|
||||
@@ -1416,12 +1432,14 @@ def _ollama_request_extras(user_message: str, max_completion_tokens: int) -> dic
|
||||
# over-allocate KV-cache VRAM. Over-allocation (e.g. 128k slots for an 8k
|
||||
# prompt on a 31B model) exhausts VRAM by chunk 4 and produces the same
|
||||
# hollow-200 symptom — just from a different direction (#798 follow-up).
|
||||
# Formula: actual input tokens + output cap + system prompt headroom.
|
||||
# Formula: input tokens (user message + system prompt) + output cap + margin.
|
||||
# Capped at 131072 (enough for the default 60k token_budget); env var wins.
|
||||
num_ctx_raw = os.environ.get("GRAPHIFY_OLLAMA_NUM_CTX", "").strip()
|
||||
# Auto-derive num_ctx from actual chunk size regardless — used as the
|
||||
# fallback and for the mismatch check below.
|
||||
estimated_input = len(user_message) // _CHARS_PER_TOKEN + 400
|
||||
# The system prompt is measured rather than assumed: a flat 400 was short
|
||||
# of the ~760 tokens the extraction prompt really takes.
|
||||
estimated_input = _estimate_prompt_tokens(user_message) + _estimate_prompt_tokens(system_prompt)
|
||||
auto_num_ctx = min(estimated_input + max_completion_tokens + 2000, 131072)
|
||||
auto_num_ctx = max(auto_num_ctx, 8192)
|
||||
if num_ctx_raw:
|
||||
@@ -1448,8 +1466,6 @@ def _ollama_request_extras(user_message: str, max_completion_tokens: int) -> dic
|
||||
file=sys.stderr,
|
||||
)
|
||||
else:
|
||||
# Estimate input tokens: user_message chars / 4 (standard BPE
|
||||
# heuristic) + 400 for the system prompt, then add output headroom.
|
||||
num_ctx = auto_num_ctx
|
||||
keep_alive = os.environ.get("GRAPHIFY_OLLAMA_KEEP_ALIVE", "30m")
|
||||
return {"options": {"num_ctx": num_ctx}, "keep_alive": keep_alive}
|
||||
@@ -1599,7 +1615,8 @@ def _call_openai_compat(
|
||||
# above, and replacing it here made the flag silently inert on ollama (#3988).
|
||||
kwargs["extra_body"] = {
|
||||
**kwargs.get("extra_body", {}),
|
||||
**_ollama_request_extras(user_message, max_completion_tokens),
|
||||
**_ollama_request_extras(user_message, max_completion_tokens,
|
||||
kwargs["messages"][0]["content"]),
|
||||
}
|
||||
native = None
|
||||
if backend == "ollama" and extra_body is None:
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
"""num_ctx sizing for Ollama. Once num_ctx actually reached Ollama (#4413) the
|
||||
estimate behind it mattered: chars/4 undercounts non-Latin scripts (2.8x for
|
||||
Chinese, 3.7x for Hindi on qwen2.5) and the flat 400 tokens left for the
|
||||
system prompt was short of the ~760 the extraction prompt takes.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from graphify import llm
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_env_override(monkeypatch):
|
||||
monkeypatch.delenv("GRAPHIFY_OLLAMA_NUM_CTX", raising=False)
|
||||
|
||||
|
||||
def test_estimate_unchanged_for_english_and_code():
|
||||
text = "def handler(request):\n return Response(status=200)\n" * 200
|
||||
assert llm._estimate_prompt_tokens(text) == len(text) // llm._CHARS_PER_TOKEN
|
||||
|
||||
|
||||
def test_estimate_unchanged_for_accented_latin():
|
||||
text = "Größenänderung für Café und Façade " * 100
|
||||
assert llm._estimate_prompt_tokens(text) == len(text) // llm._CHARS_PER_TOKEN
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", [
|
||||
"知识图谱把代码和文档连接起来" * 500, # Chinese
|
||||
"ज्ञान ग्राफ कोड और दस्तावेज़ों को जोड़ता है" * 300, # Hindi
|
||||
"Граф знаний связывает код и документы" * 300, # Russian
|
||||
], ids=["chinese", "hindi", "russian"])
|
||||
def test_estimate_counts_non_latin_chars_as_tokens(text):
|
||||
non_latin = sum(1 for c in text if ord(c) > 0x24F)
|
||||
assert llm._estimate_prompt_tokens(text) >= non_latin
|
||||
assert llm._estimate_prompt_tokens(text) > len(text) // llm._CHARS_PER_TOKEN
|
||||
|
||||
|
||||
def test_chinese_chunk_gets_room_for_its_tokens():
|
||||
# 20k Chinese chars is ~14k tokens on qwen2.5. chars/4 sized this at the
|
||||
# 8192 floor, so Ollama cut the prompt.
|
||||
msg = "知识图谱把代码和文档连接起来" * 1500
|
||||
extras = llm._ollama_request_extras(msg, 4096)
|
||||
assert extras["options"]["num_ctx"] >= len(msg) + 4096
|
||||
|
||||
|
||||
def test_system_prompt_is_counted():
|
||||
msg = "x" * 40_000
|
||||
system = llm._extraction_system(deep=False)
|
||||
without = llm._ollama_request_extras(msg, 8192)["options"]["num_ctx"]
|
||||
with_sys = llm._ollama_request_extras(msg, 8192, system)["options"]["num_ctx"]
|
||||
assert with_sys - without == llm._estimate_prompt_tokens(system)
|
||||
|
||||
|
||||
def test_extraction_call_sizes_for_its_system_prompt(monkeypatch):
|
||||
import sys
|
||||
import types
|
||||
|
||||
sent = {}
|
||||
|
||||
class _FakeOpenAI:
|
||||
def __init__(self, *_, **__):
|
||||
pass
|
||||
|
||||
def post(self, path, *, body, **__):
|
||||
sent.update(body)
|
||||
return {"message": {"content": '{"nodes":[],"edges":[],"hyperedges":[]}'},
|
||||
"done_reason": "stop", "prompt_eval_count": 1, "eval_count": 100}
|
||||
|
||||
fake = types.ModuleType("openai")
|
||||
fake.OpenAI = _FakeOpenAI
|
||||
fake.APIStatusError = type("APIStatusError", (Exception,), {})
|
||||
monkeypatch.setitem(sys.modules, "openai", fake)
|
||||
monkeypatch.setattr(llm, "_OLLAMA_NO_NATIVE", set())
|
||||
|
||||
msg = "x" * 40_000
|
||||
llm._call_openai_compat("http://localhost:11434/v1", "ollama", "m", msg,
|
||||
max_completion_tokens=8192, backend="ollama", deep_mode=True)
|
||||
|
||||
system = llm._extraction_system(deep=True)
|
||||
assert sent["options"]["num_ctx"] == (
|
||||
llm._estimate_prompt_tokens(msg) + llm._estimate_prompt_tokens(system) + 8192 + 2000
|
||||
)
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Opt-in check against a real Ollama server: the whole prompt must reach the
|
||||
model, not just as much as fits Ollama's default context (#4413). Every other
|
||||
Ollama test fakes the openai client, so this is the one that exercises the
|
||||
real `client.post` call and Ollama's own truncation.
|
||||
|
||||
GRAPHIFY_TEST_OLLAMA_MODEL=qwen2.5:14b pytest tests/test_ollama_live.py
|
||||
|
||||
GRAPHIFY_TEST_OLLAMA_URL defaults to http://localhost:11434.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import urllib.request
|
||||
|
||||
import pytest
|
||||
|
||||
from graphify import llm
|
||||
|
||||
MODEL = os.environ.get("GRAPHIFY_TEST_OLLAMA_MODEL", "").strip()
|
||||
URL = os.environ.get("GRAPHIFY_TEST_OLLAMA_URL", "http://localhost:11434").rstrip("/")
|
||||
|
||||
pytestmark = pytest.mark.skipif(not MODEL, reason="set GRAPHIFY_TEST_OLLAMA_MODEL to run")
|
||||
pytest.importorskip("openai")
|
||||
|
||||
|
||||
def _real_prompt_tokens(system: str, user: str) -> int:
|
||||
# Same messages with a context far bigger than the prompt, so nothing is cut.
|
||||
body = {
|
||||
"model": MODEL,
|
||||
"messages": [{"role": "system", "content": system}, {"role": "user", "content": user}],
|
||||
"stream": False,
|
||||
"options": {"num_ctx": 65536, "num_predict": 1},
|
||||
}
|
||||
req = urllib.request.Request(f"{URL}/api/chat", json.dumps(body).encode(),
|
||||
{"Content-Type": "application/json"})
|
||||
with urllib.request.urlopen(req, timeout=900) as resp:
|
||||
return json.load(resp)["prompt_eval_count"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("user", [
|
||||
"The parser hands each token to the resolver, which looks it up in the symbol table. " * 400,
|
||||
"知识图谱把代码和文档连接起来,解析器把每个标记交给解析程序。" * 600,
|
||||
], ids=["english", "chinese"])
|
||||
def test_whole_prompt_reaches_the_model(monkeypatch, user):
|
||||
monkeypatch.delenv("GRAPHIFY_OLLAMA_NUM_CTX", raising=False)
|
||||
monkeypatch.setattr(llm, "_OLLAMA_NO_NATIVE", set())
|
||||
result = llm._call_openai_compat(f"{URL}/v1", "ollama", MODEL, user,
|
||||
max_completion_tokens=64, backend="ollama")
|
||||
expected = _real_prompt_tokens(llm._extraction_system(deep=False), user)
|
||||
assert expected > 4096, "prompt must be bigger than Ollama's default context"
|
||||
assert result["input_tokens"] == expected
|
||||
Reference in new issue
Block a user