忠实、自包含地复现越狱方法:Mehrotra et al., “Tree of Attacks: Jailbreaking Black-Box LLMs Automatically”(NeurIPS 2024)。
系统提示词逐字复现自论文 Table 5/6/7。本配置使用开源模型作攻击者/目标,用 Qwen3Guard 作评估器。
仅供研究使用。 本代码用于安全/红队研究与复现已发表的基线,请勿用于生产或传播有害内容。
每轮迭代(最多 depth 轮):
branching_factor 个变体提示。width 个叶节点进入下一轮。论文默认超参:branching_factor=4、width=10、depth=10。
默认 --evaluator-type guard,Qwen3Guard 对目标回复输出三类标签 Safe / Unsafe / Controversial:
只要某分支被判越狱,立即记为成功并返回。
也可切换为论文原始的分级 LLM judge:
--evaluator-type llm --evaluator-model gpt-4(需 OpenAI key,或填本地模型名)。此模式启用 1–10 打分与 Off-Topic(Phase-1)剪枝。
pip install -r requirements.txt
模型加载默认走 modelscope(无则自动回退 transformers)。
数据集在 ./Dataset/(Adv.csv / Harm.csv / JBB.csv)。从第二行开始读(跳过表头),取第一列作 goal;第二列(若有)作目标起始串(Sure, here is ...),否则自动合成。输入/输出路径都用参数传入。
python tap_main.py \
--input ./Dataset/Adv.csv \
--output ./results/adv_nothink.json \
--GPU 1,2,4 \
--attack-model-path /path/to/models/Qwen/Qwen3-8B \
--target-model-path /path/to/models/Qwen/Qwen3-8B \
--guard-path /path/to/models/Qwen/Qwen3Guard-Gen-8B
python tap_main.py \
--input ./Dataset/Adv.csv \
--output ./results/adv_think.json \
--attack-gpu 1 --target-gpu 2,5 --guard-gpu 4 \
--target-model-path /path/to/models/Qwen/Qwen3-8B \
--guard-path /path/to/models/Qwen/Qwen3Guard-Gen-4B \
--enable-thinking
--GPU 1,2,4:攻击者→1 号、目标→2 号、评估器→4 号,每个模型独占一张卡(非思考够用)。--attack-gpu / --target-gpu / --guard-gpu。
思考模式(32768 token,KV 缓存大)建议给目标 2 张卡(--target-gpu 2,5)。--max-batch(默认 8)自动拆成小批,OOM 就调小到 4/2/1。| 参数 | 默认 | 说明 |
|——|——|——|
| --resume | 关 | 断点续跑:读已有 --output,跳过已完成的 goal 继续 |
| --limit | 0 | >0 时只跑前 N 条(快速验证) |
| --branching-factor | 4 | 分支因子 b |
| --width | 10 | 每轮保留的最大叶节点数 w |
| --depth | 10 | 最大迭代深度 d |
| --enable-thinking | 关 | 开启目标的思考模式(Qwen3) |
| --target-max-tokens | 32768 | 目标生成长度(思考模式留足空间) |
| --max-batch | 8 | 单次前向最多几条序列(OOM 就调小) |
| --evaluator-type | guard | guard=Qwen3Guard;llm=分级判分 |
完整参数见 python tap_main.py --help。更详细的中文操作手册见 技术操作.md。
边跑边写的 JSON(原子写,运行中可随时查看/续跑):
config:本次运行的模型与超参。summary:attack_success_rate(ASR)、mean_queries、mean_iterations、mean_time_sec。results:每条 goal 的 success / final_score / final_prompt / final_response / final_thinking / num_queries / iterations / elapsed_sec。final_prompt 是 TAP 最终收敛出的对抗提示词(成功时为触发越狱那条,否则为得分最高那条)。
中断后用同样命令加 --resume(--input/--output 保持一致)。已完成的 goal 会被跳过,汇总指标基于全部结果重算。
tap_main.py:主程序(参数、数据 IO、TAP 树搜索、写结果)。conversers.py:三个角色 AttackLM / TargetLM / GuardEvaluator(+LLMEvaluator)。language_models.py:HuggingFaceChat(本地,一模型一卡)/ OpenAIModel(可选 gpt-*)。system_prompts.py:论文 Table 5/6/7,逐字复现。common.py:JSON/评分解析、对话拼接。tap_animation.html:攻击流程的独立动画讲解(浏览器打开)。@inproceedings{mehrotra2024tree,
title={Tree of Attacks: Jailbreaking Black-Box LLMs Automatically},
author={Mehrotra, Anay and Zampetakis, Manolis and Kassianik, Paul and Nelson, Blaine and Anderson, Hyrum and Singer, Yaron and Karbasi, Amin},
booktitle={NeurIPS},
year={2024}
}