Files
agent-safe-middleware/middleware/llm_worker.py
T
starrrLight 45e45948bd fix(LLM): 限制模型输入分词内存
模型 worker 在 token 化阶段最多处理配置上限加一个 token,超限请求直接失败,避免先完整构造超长输入张量再拒绝。
2026-10-11 17:42:11 +08:00

85 lines
3.2 KiB
Python

"""Local Transformers model process; never imported into Lua workers."""
import json
from typing import Any
from .llm import _send, guard_messages, parse_guard_output
def guard_worker_main(
connection, model_path: str, load: dict[str, Any], limits: dict[str, Any]
) -> None:
"""Load one model and serve serialized requests until stopped."""
try:
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
hub_options = {"local_files_only": True, "trust_remote_code": False}
if load.get("revision") is not None:
hub_options["revision"] = load["revision"]
tokenizer = AutoTokenizer.from_pretrained(
model_path,
**hub_options,
)
dtype_name = load.get("dtype", "auto")
torch_dtype = "auto" if dtype_name == "auto" else getattr(torch, dtype_name)
device = load.get("device", "cpu")
model = AutoModelForCausalLM.from_pretrained(
model_path,
torch_dtype=torch_dtype,
**hub_options,
)
model.to(device)
model.eval()
_send(connection, {"ok": True})
except Exception:
try:
_send(connection, {"ok": False, "error": "ModelLoadFailed"})
finally:
connection.close()
return
try:
while True:
command = json.loads(connection.recv_bytes(1024 * 1024).decode())
if command.get("op") == "stop":
return
if command.get("op") != "call":
_send(connection, {"ok": False, "error": "InvalidRequest"})
continue
try:
request = command["request"]
messages = guard_messages(request)
text = tokenizer.apply_chat_template(messages, tokenize=False)
inputs = tokenizer(
[text],
return_tensors="pt",
truncation=True,
max_length=limits["max_input_tokens"] + 1,
)
if inputs["input_ids"].shape[1] > limits["max_input_tokens"]:
_send(connection, {"ok": False, "error": "ModelInputTooLong"})
continue
device = next(model.parameters()).device
inputs = {key: value.to(device) for key, value in inputs.items()}
with torch.inference_mode():
generated = model.generate(
**inputs,
max_new_tokens=limits["max_new_tokens"],
do_sample=False,
)
output_ids = generated[0][inputs["input_ids"].shape[1] :].tolist()
output = tokenizer.decode(output_ids, skip_special_tokens=True)
value = parse_guard_output(output)
from .llm import validate_guard_result
_send(
connection, {"ok": True, "value": validate_guard_result(value, request["task"])}
)
except Exception:
_send(connection, {"ok": False, "error": "ModelFailure"})
except (EOFError, OSError, ValueError, json.JSONDecodeError):
pass
finally:
connection.close()