"""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=False, ) 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()