"""Local Transformers model process; never imported into Lua workers.""" import json from typing import Any from .llm import MODEL_DEPENDENCIES, MODEL_LOAD_ERRORS, _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.""" stage = "import_torch" try: import torch stage = "import_transformers" 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"] stage = "load_tokenizer" tokenizer = AutoTokenizer.from_pretrained( model_path, **hub_options, ) stage = "load_model" 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, ) stage = "move_to_device" model.to(device) stage = "eval_model" model.eval() _send(connection, {"ok": True}) except Exception as exc: exception = type(exc).__name__ dependency = exc.name if isinstance(exc, ImportError) else None failure = { "ok": False, "error": "ModelLoadFailed", "stage": stage, "exception": exception if exception in MODEL_LOAD_ERRORS else "unknown", "dependency": dependency if dependency in MODEL_DEPENDENCIES else "unknown", } try: _send(connection, failure) 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()