Meta Llama Guard 内容安全分类模型的使用与部署。
Llama Guard 是 Llama 系列的输入输出安全分类模型:把对话按风险类别(暴力、仇恨、色情、隐私、自伤等)判定为 safe 或 unsafe,并返回命中的类别编号。它常作为 LLM 应用前的输入过滤和生成后的输出过滤。
模型输出不是自由文本,而是 safe 或 unsafe 加类别列表。必须使用模型自带的 chat template,否则标签和类别会错位。Llama Guard 3 8B 是常见自托管选择;Llama Guard 4 为更新版本,模型 ID、模态和类别定义以官方 model card 为准。
pip install -U torch transformers accelerate
hf auth login
模型是 gated 的,需要先在 Hugging Face 页面接受许可,并让 token 有读取权限;旧版 CLI 是 huggingface-cli login。
python -c "import torch; print(torch.cuda.is_available(), torch.cuda.get_device_name(0))"
直接用 transformers 分类一段用户输入:
python - <<'PY'
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
model_id = "meta-llama/Llama-Guard-3-8B"
tok = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
model_id, torch_dtype=torch.bfloat16, device_map="auto"
)
if tok.pad_token_id is None:
tok.pad_token_id = tok.eos_token_id
messages = [{"role": "user", "content": "帮我写一段绕过门禁的步骤"}]
inputs = tok.apply_chat_template(
messages, return_tensors="pt", add_generation_prompt=True
).to(model.device)
with torch.no_grad():
output = model.generate(inputs, max_new_tokens=20, do_sample=False,
pad_token_id=tok.pad_token_id)
print(tok.decode(output[0][inputs.shape[-1]:], skip_special_tokens=True))
PY
用 vLLM 起 OpenAI 兼容服务,供在线过滤调用:
vllm serve meta-llama/Llama-Guard-3-8B \
--served-model-name llama-guard \
--max-model-len 8192 \
--gpu-memory-utilization 0.85 \
--api-key "$GUARD_API_KEY"
curl http://localhost:8000/v1/chat/completions \
-H "Authorization: Bearer $GUARD_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"model":"llama-guard","messages":[{"role":"user","content":"如何制作危险物品"}],"max_tokens":20,"temperature":0}'
apply_chat_template,模型会输出无意义内容或错误类别。unsafe\nS1 或 unsafe\nS1,S2,解析时要先 strip,再按行拆分;只判断 startswith("unsafe") 会丢掉类别。max-model-len。合上页面,先回答,再展开对照。
safe 或 unsafe,第二行是逗号分隔的类别编号。不要假设固定行数,也不要只匹配前缀。