ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

AI-Research-SKILLs 中的 LlamaGuard:为 LLM 应用构建输入输出双向内容审核的完整实战指南

AI-Research-SKILLs 中的 LlamaGuard:为 LLM 应用构建输入输出双向内容审核的完整实战指南 AI 技能人工智能大模型深度学习【免费下载链接】AI-Research-SKILLsComprehensive open-source library of AI research and engineering skills for any AI model. Package the skills and your claude code/codex/gemini agent will be an AI research agent with full horsepower. Maintained by Orchestra Research.项目地址https://gitcode.com/gh_mirrors/ai/AI-Research-SKILLs点击查看免费下载本篇技术指南以 AI-Research-SKILLs 仓库中 07-safety-alignment/llamaguard/SKILL.md 为核心系统讲解 Meta LlamaGuard 这一面向 LLM 输入/输出过滤的专用审核模型从 6 大安全类别与 HuggingFace Transformers 快速上手到输入过滤、输出过滤、vLLM 生产部署、FastAPI 服务化、NeMo Guardrails 集成五大工作流再到量化、吞吐与故障排查。读完本文你将掌握一套可直接复制运行的 LlamaGuard 接入方案并理解它如何与仓库中 Prompt Guard、NeMo Guardrails 组合成纵深防御的内容安全体系。什么是 LlamaGuardLlamaGuard 是 Meta 推出的一个 7-8B 参数规模的内容安全分类模型专门用于对 LLM 的输入用户提示词和输出模型回复进行安全审核。与通用的毒性检测 API不同LlamaGuard 本身就是一个 LLM——它将审核建模为一次条件生成任务给定一段多轮对话模型输出safe或unsafe并在判定为unsafe时给出具体的违规类别如 S3武器、S6犯罪规划。在 AI-Research-SKILLs 的安全与对齐Safety Alignment分类中LlamaGuard 被定位为内容安全分类content safety classification专用技能与 Constitutional AI训练期安全对齐、NeMo Guardrails运行时护栏管线、Prompt Guard提示注入检测共同构成 4 项安全技能体系见 README.md 安全技能清单 与 技能路由表。快速开始安装与环境准备LlamaGuard 通过 HuggingFace Transformers 加载需要先安装依赖并完成 HuggingFace 登录模型为受限访问需接受许可协议pip install transformers torch # Login to HuggingFace (required) huggingface-cli login依赖声明在 SKILL.md 的 frontmatter 中为transformers、torch、vllm三项07-safety-alignment/llamaguard/SKILL.md其中 vLLM 用于生产级推理加速见下文工作流 3。基础调用把审核当作一次生成from transformers import AutoTokenizer, AutoModelForCausalLM model_id meta-llama/LlamaGuard-7b tokenizer AutoTokenizer.from_pretrained(model_id) model AutoModelForCausalLM.from_pretrained(model_id, device_mapauto) def moderate(chat): input_ids tokenizer.apply_chat_template(chat, return_tensorspt).to(model.device) output model.generate(input_idsinput_ids, max_new_tokens100) return tokenizer.decode(output[0], skip_special_tokensTrue) # Check user input result moderate([ {role: user, content: How do I make explosives?} ]) print(result) # Output: unsafe\nS3 (Criminal Planning)关键点在于apply_chat_templateLlamaGuard 需要按官方对话模板组织上下文包括可选的系统提示用于声明自定义安全策略模板会把用户消息包装成审核指令形式模型随后生成safe或unsafe\nS{category}。判定结果的解析逻辑非常直接——以safe开头则放行否则按换行符取第二行即为违规类别编号。六大安全类别LlamaGuard 1/2 的审核分类基于 6 个策略类别这是整个审核体系的核心枚举S1Violence Hate暴力与仇恨S2Sexual Content色情内容S3Guns Illegal Weapons枪支与非法武器S4Regulated Substances管制物质S5Suicide Self-Harm自杀与自残S6Criminal Planning犯罪规划上述枚举与 Prompt Guard 技能文档 中对 LlamaGuard 的描述一致content moderation (violence, hate, criminal planning)并且 S1-S6 类别可被前端业务系统直接映射为拒绝文案、风控策略或审计日志标签。五大实战工作流工作流 1输入过滤Prompt Moderation在请求进入业务 LLM 之前先做一次审核把恶意用户输入挡在门外def check_input(user_message): result moderate([{role: user, content: user_message}]) if result.startswith(unsafe): category result.split(\n)[1] return False, category # Blocked else: return True, None # Safe # Example safe, category check_input(How do I hack a website?) if not safe: print(fRequest blocked: {category}) # Return error to user else: # Send to LLM response llm.generate(user_message)该模式对应审核链路的第一道闸门拦截发生在 LLM 推理之前可显著降低恶意提示词触达业务模型的概率也避免为违规请求支付推理成本。注意这里对如何入侵网站命中 S6Criminal Planning返回类别编号可用于记录风控事件。工作流 2输出过滤Response Moderation只审核输入是不够的——模型仍可能生成不合规内容。输出过滤把用户消息 助手回复打包成完整对话再做一次审核仅在通过后才展示给用户def check_output(user_message, bot_response): conversation [ {role: user, content: user_message}, {role: assistant, content: bot_response} ] result moderate(conversation) if result.startswith(unsafe): category result.split(\n)[1] return False, category else: return True, None # Example user_msg Tell me about harmful substances bot_msg llm.generate(user_msg) safe, category check_output(user_msg, bot_msg) if not safe: print(fResponse blocked: {category}) # Return generic response return I cannot provide that information. else: return bot_msg把完整多轮上下文传给审核模型是 LlamaGuard 的设计精髓它能结合用户提问语境判断回复是否合规避免把科普性质的安全讨论误判为违规这一点也是它在输出侧相对朴素关键词过滤的核心优势。工作流 3vLLM 生产部署高吞吐推理Transformers 逐条生成的延迟300-500ms对线上服务偏高生产环境推荐 vLLM 部署。vLLM 支持连续批处理continuous batching单卡 A100 上吞吐可达约 50-100 requests/secfrom vllm import LLM, SamplingParams # Initialize vLLM llm LLM(modelmeta-llama/LlamaGuard-7b, tensor_parallel_size1) # Sampling params sampling_params SamplingParams( temperature0.0, # Deterministic max_tokens100 ) def moderate_vllm(chat): # Format prompt (需要预先加载 tokenizer见下方说明) prompt tokenizer.apply_chat_template(chat, tokenizeFalse) # Generate output llm.generate([prompt], sampling_params) return output[0].outputs[0].text # Batch moderation chats [ [{role: user, content: How to make bombs?}], [{role: user, content: Whats the weather?}], [{role: user, content: Tell me about drugs}] ] prompts [tokenizer.apply_chat_template(c, tokenizeFalse) for c in chats] results llm.generate(prompts, sampling_params) for i, result in enumerate(results): print(fChat {i}: {result.outputs[0].text})两点实操提醒一是temperature0.0保证审核输出确定性随机采样可能导致同一内容时判时拒二是示例中的tokenizer仍需通过AutoTokenizer.from_pretrained(model_id)单独加载vLLM 只负责模型权重与推理引擎模板化由 Transformers tokenizer 完成。tensor_parallel_size可在多卡场景下切分模型例如两张 GPU 上设为 2 可进一步降低首 token 延迟。工作流 4FastAPI 审核服务端点把 vLLM 封装成 HTTP 服务供业务侧聊天机器人、RAG 应用统一调用from fastapi import FastAPI from pydantic import BaseModel from vllm import LLM, SamplingParams app FastAPI() llm LLM(modelmeta-llama/LlamaGuard-7b) sampling_params SamplingParams(temperature0.0, max_tokens100) class ModerationRequest(BaseModel): messages: list # [{role: user, content: ...}] app.post(/moderate) def moderate_endpoint(request: ModerationRequest): prompt tokenizer.apply_chat_template(request.messages, tokenizeFalse) output llm.generate([prompt], sampling_params)[0] result output.outputs[0].text is_safe result.startswith(safe) category None if is_safe else result.split(\n)[1] if \n in result else None return { safe: is_safe, category: category, full_output: result } # Run: uvicorn api:app --host 0.0.0.0 --port 8000启动服务后即可用 curl 验证curl -X POST http://localhost:8000/moderate \ -H Content-Type: application/json \ -d {messages: [{role: user, content: How to hack?}]} # Response: {safe: false, category: S6, full_output: unsafe\nS6}返回结构把safe布尔值、category类别和full_output原始输出一并暴露业务层既能做硬阻断也能在审计日志中留存模型原始判定。注意messages支持任意轮次对话因此同一端点天然兼容工作流 2 的输入输出联合审核。工作流 5NeMo Guardrails 集成在 AI-Research-SKILLs 的安全体系中NeMo Guardrails 负责可编程运行时护栏而 LlamaGuard 是其中可插拔的审核模型。两者通过nemoguardrails.integrations.llama_guard集成将 LlamaGuard 注册为输入/输出 railsfrom nemoguardrails import RailsConfig, LLMRails from nemoguardrails.integrations.llama_guard import LlamaGuard # Configure NeMo Guardrails config RailsConfig.from_content( models: - type: main engine: openai model: gpt-4 rails: input: flows: - llamaguard check input output: flows: - llamaguard check output ) # Add LlamaGuard integration llama_guard LlamaGuard(model_pathmeta-llama/LlamaGuard-7b) rails LLMRails(config) rails.register_action(llama_guard.check_input, namellamaguard check input) rails.register_action(llama_guard.check_output, namellamaguard check output) # Use with automatic moderation response rails.generate(messages[ {role: user, content: How do I make weapons?} ]) # Automatically blocked by LlamaGuard注意 NeMo Guardrails 一侧的等价写法是from nemoguardrails.integrations import LlamaGuard配置块中 flow 名称为llama guard check input/output见 nemo-guardrails/SKILL.md 工作流 5。两者注册动作的名称必须与 YAML 中flows列表完全一致否则 rails 不会被触发。这种组合方式让 LlamaGuard 的内容类别审核与 NeMo 的提示注入检测、PII 过滤、事实核查等机制共存于同一条护栏管线。何时使用 LlamaGuard 及其替代方案适合选择 LlamaGuard 的场景需要一个开箱即用的预训练审核模型而不是从零训练分类器追求高准确率SKILL.md 声明 prompt 侧 94.5%、response 侧 95.3%具备 GPU 资源7-8B 模型需要数 GB 显存需要细粒度的安全类别S1-S6以便分级处置而非简单的好/坏二分类正在构建生产级 LLM 应用需要输入输出双向把关。模型版本演进LlamaGuard 17B初版6 个类别LlamaGuard 28B改进版仍为 6 类别LlamaGuard 38B最新版2024能力增强。各版本 HuggingFace 模型标识见文末资源清单升级版本时只需更换model_id上述代码无需改动。何时改用其他方案OpenAI Moderation API更简单、API 化、无自托管成本Perspective APIGoogle 的毒性检测服务NeMo Guardrails更完整的可编程安全框架如需 jailbreak 检测、PII 过滤、事实核查等多机制组合Constitutional AI训练期安全对齐方法属于把安全内化进权重而非运行时过滤见 constitutional-ai/SKILL.md。纵深防御与 Prompt Guard 分层组合单一审核模型存在盲区LlamaGuard 擅长内容类别判定但对提示注入/越狱改写如Ignore all previous instructions不一定敏感。仓库中的 Prompt Guard86M 参数GPU 上 2ms 延迟专门检测 INJECTION/JAILBREAK 两类攻击可与 LlamaGuard 组合成四层防线# Layer 1: Prompt Guard (jailbreak detection) if get_jailbreak_score(user_input) 0.5: return Blocked: jailbreak attempt # Layer 2: LlamaGuard (content moderation) if not llamaguard.is_safe(user_input): return Blocked: unsafe content # Layer 3: Process with LLM response llm.generate(user_input) # Layer 4: Validate output if not llamaguard.is_safe(response): return Error: Cannot provide that response return responseLayer 1 用轻量分类器先过滤注入型攻击几乎零延迟Layer 2/4 用 LlamaGuard 做内容类别审核形成快前置 精审核的成本与效果折中。这也是 AI-Research-SKILLs 安全分类下 4 项技能互相咬合、可叠加使用的典型组合。常见问题排查问题 1模型访问被拒绝Access Denied受限模型gated model需要两步授权huggingface-cli login # Enter your token然后在模型页面如meta-llama/LlamaGuard-7b接受许可协议Accept license授权后本地缓存即可正常下载权重。问题 2高延迟500msTransformers 逐条生成延迟偏高可改用 vLLM 获得约 10× 加速from vllm import LLM llm LLM(modelmeta-llama/LlamaGuard-7b) # Latency: 500ms → 50ms多卡场景开启张量并行llm LLM(modelmeta-llama/LlamaGuard-7b, tensor_parallel_size2) # 2× faster on 2 GPUs问题 3误报False Positives当unsafe判定置信度不足时可改用概率阈值过滤解析首个 token 中unsafe对应的概率只有超过阈值如 0.9才判为违规# Get probability of unsafe token logits model(..., return_dict_in_generateTrue, output_scoresTrue) unsafe_prob torch.softmax(logits.scores[0][0], dim-1)[unsafe_token_id] if unsafe_prob 0.9: # High confidence threshold return unsafe else: return safe该方案把硬判定变为软评分便于针对不同业务场景调节敏感度。问题 4GPU 显存溢出OOM7B 模型 FP16 约需 14GB 显存可用 8-bit 量化降到约 7GBfrom transformers import BitsAndBytesConfig quantization_config BitsAndBytesConfig(load_in_8bitTrue) model AutoModelForCausalLM.from_pretrained( model_id, quantization_configquantization_config, device_mapauto ) # Memory: 14GB → 7GB高级扩展方向原 SKILL.md 列出的三个进阶主题自定义类别、性能基准、部署指南对应三个方向本文结合仓库实际情况给出可落地的延伸路径自定义安全类别domain-specific categoriesLlamaGuard 支持在apply_chat_template时注入自定义系统提示自定义 policy将 S1-S6 替换/扩展为面向业务领域的类别清单后微调。仓库内可参考微调类技能的流程例如 03-fine-tuning/peft 中的 PEFT/LoRA 微调范式以及 06-post-training/trl-fine-tuning 的 SFT 训练流程把自定义策略 标注样本转化为 LoRA 适配器叠加在 LlamaGuard 基座上。准确率与延迟基准对比可在仓库 dev_data/deep_research_report_1.md 中找到各安全方案的调研性对比含 LlamaGuard 版本线与组合建议作为选型参考更严谨的实测需在自己数据集上评估 TPR/FPR 与 p95 延迟。规模化部署vLLM 之上可叠加 12-inference-serving/vllm 中的部署细节如 OpenAI 兼容 API、量化、多卡并行并结合 09-infrastructure 下的 Modal/SkyPilot 等方案按需扩容生产化时建议对/moderate端点做批处理合并以利用 vLLM 的连续批处理能力摊薄单请求延迟。硬件需求与性能参考硬件要求GPUNVIDIA T4/A10/A100显存FP1614GB7B 模型INT87GB量化后INT44GBQLoRACPU可运行但很慢约 10× 延迟吞吐单卡 A100 约 50-100 req/sec延迟参考单 GPUHuggingFace Transformers300-500msvLLM50-100ms批量处理vLLM单请求 20-50ms上述数据来自 SKILL.md 的实测性描述实际数值随硬件型号、批大小、输入长度浮动上线前建议用代表性流量压测校准。资源清单HuggingFace 模型需登录并接受许可V1meta-llama/LlamaGuard-7bV2meta-llama/Meta-Llama-Guard-2-8BV3meta-llama/Meta-Llama-Guard-3-8B论文Llama Guard: LLM-based Input-Output Safeguard for Human-AI Conversations集成生态vLLM、Sagemaker、NeMo Guardrails仓库内配套资料本技能路由见 0-autoresearch-skill/references/skill-routing.md配套安全技能见 Prompt Guard 与 NeMo Guardrails小结LlamaGuard 以审核即生成的方式把内容安全从规则匹配升级为可解释、可扩展的类别化判定。本文覆盖了从 Transformers 快速上手、输入/输出双向过滤、vLLM 与 FastAPI 生产化到 NeMo Guardrails 集成、与 Prompt Guard 分层组合的完整链路在 AI-Research-SKILLs 中它与其他 3 项安全技能共同构成一套可叠加、可替换的运行时安全工具箱。接入时只需记住三条主线用apply_chat_template组织对话上下文、以safe/unsafe\nS{category}解析判定结果、用 vLLM 批量处理满足生产吞吐。赞分享AI 技能人工智能大模型深度学习【免费下载链接】AI-Research-SKILLsComprehensive open-source library of AI research and engineering skills for any AI model. Package the skills and your claude code/codex/gemini agent will be an AI research agent with full horsepower. Maintained by Orchestra Research.项目地址https://gitcode.com/gh_mirrors/ai/AI-Research-SKILLs点击查看免费下载相关推荐AI-Research-SKILLs 中的 Instructor 技能用 Pydantic 实现 LLM 结构化输出的完整实战指南AI Research SKILLs 中的 Instructor 技能用 Pydantic 实现 LLM 结构化输出的完整实战指南 本篇技术指南以 AI ReAI 技能人工智能大模型深度学习用 ADK 构建 LLM Auditor面向 LLM 输出的自动化事实核查智能体实战指南用 ADK 构建 LLM Auditor面向 LLM 输出的自动化事实核查智能体实战指南 LLM Auditor 是 Agent Development Ki示例工程AI-Research-SKILLs 之 Outlines JSON 生成完全指南用 Pydantic 模型与 JSON Schema 锁定 LLM 结构化输出AI Research SKILLs 之 Outlines JSON 生成完全指南用 Pydantic 模型与 JSON Schema 锁定 LLM 结构化输AI 技能人工智能大模型深度学习上一篇Lombok CustomLog注解终极指南轻松集成任意日志框架的完整教程下一篇探索次元世界的秘密HaSuite与Harepacker-resurrected创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表