fix(模型): 显示加载失败阶段和依赖诊断
模型子进程返回固定的加载阶段、异常类型和已知依赖名称,主进程在启动日志及异常中展示诊断信息,不输出原始异常文本。保留加载失败时阻止就绪与子进程清理行为。 新增六个加载阶段、异常信息过滤与进程清理测试;相关测试共 28 项通过,Ruff 检查通过。
This commit is contained in:
1 parent
5d71803b02
commit
eab1af6c5f
4 files changed
+150
-5
No files matched your search
+28
-2
@@ -14,6 +14,30 @@ from .config import LLMConfig, Settings
|
||||
|
||||
logger = logging.getLogger("middleware.audit")
|
||||
|
||||
# Only fixed diagnostic labels may cross the startup IPC boundary or enter logs.
|
||||
MODEL_LOAD_STAGES = {
|
||||
"import_torch", "import_transformers", "load_tokenizer", "load_model",
|
||||
"move_to_device", "eval_model",
|
||||
}
|
||||
MODEL_LOAD_ERRORS = {
|
||||
"ModuleNotFoundError", "ImportError", "FileNotFoundError", "PermissionError",
|
||||
"OSError", "ValueError", "TypeError", "RuntimeError", "MemoryError",
|
||||
"SafetensorError", "OutOfMemoryError",
|
||||
}
|
||||
MODEL_DEPENDENCIES = {"torch", "transformers", "tokenizers", "safetensors", "numpy", "accelerate"}
|
||||
|
||||
|
||||
def model_load_diagnostic(result: dict[str, Any]) -> str:
|
||||
labels = []
|
||||
for key, allowed in (
|
||||
("stage", MODEL_LOAD_STAGES),
|
||||
("exception", MODEL_LOAD_ERRORS),
|
||||
("dependency", MODEL_DEPENDENCIES),
|
||||
):
|
||||
value = result.get(key)
|
||||
labels.append(f"{key}={value if isinstance(value, str) and value in allowed else 'unknown'}")
|
||||
return " ".join(labels)
|
||||
|
||||
|
||||
class LLMFailure(Exception):
|
||||
"""A deliberately non-sensitive LLM capability failure."""
|
||||
@@ -149,7 +173,7 @@ class GuardAdapter:
|
||||
from .llm_worker import guard_worker_main
|
||||
|
||||
if not self.spec.file.is_dir():
|
||||
raise LLMUnavailable()
|
||||
raise LLMUnavailable("ModelDirectoryMissing")
|
||||
parent, child = self.context.Pipe(duplex=True)
|
||||
process = self.context.Process(
|
||||
target=guard_worker_main,
|
||||
@@ -177,7 +201,9 @@ class GuardAdapter:
|
||||
)
|
||||
result = json.loads(response)
|
||||
if not result.get("ok"):
|
||||
raise LLMUnavailable()
|
||||
diagnostic = model_load_diagnostic(result)
|
||||
logger.error("model_load_failed model=%s %s", self.spec.id, diagnostic)
|
||||
raise LLMUnavailable(f"ModelLoadFailed {diagnostic}")
|
||||
except BaseException as exc:
|
||||
await self.stop()
|
||||
if isinstance(exc, (LLMFailure, asyncio.CancelledError)):
|
||||
|
||||
@@ -3,24 +3,29 @@
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from .llm import _send, guard_messages, parse_guard_output
|
||||
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")
|
||||
@@ -29,12 +34,23 @@ def guard_worker_main(
|
||||
torch_dtype=torch_dtype,
|
||||
**hub_options,
|
||||
)
|
||||
stage = "move_to_device"
|
||||
model.to(device)
|
||||
stage = "eval_model"
|
||||
model.eval()
|
||||
_send(connection, {"ok": True})
|
||||
except Exception:
|
||||
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, {"ok": False, "error": "ModelLoadFailed"})
|
||||
_send(connection, failure)
|
||||
finally:
|
||||
connection.close()
|
||||
return
|
||||
|
||||
Reference in new issue
Block a user