TAP

TAP 复现 — Tree of Attacks with Pruning

English →

忠实、自包含地复现越狱方法:Mehrotra et al., “Tree of Attacks: Jailbreaking Black-Box LLMs Automatically”(NeurIPS 2024)。

系统提示词逐字复现自论文 Table 5/6/7。本配置使用开源模型作攻击者/目标,用 Qwen3Guard 作评估器。

仅供研究使用。 本代码用于安全/红队研究与复现已发表的基线,请勿用于生产或传播有害内容。

算法流程(论文 Algorithm 1)

每轮迭代(最多 depth 轮):

  1. Branch(分支):攻击者 LLM 对每个叶节点生成 branching_factor 个变体提示。
  2. Prune-1(剪枝·偏题):评估器判断 Off-Topic 并剪枝(Qwen3Guard 模式跳过,与论文 Appendix C.4 的 guard 评估器一致)。
  3. Attack & Assess(攻击+打分):用每个提示查询目标 LLM,评估器打分;判为越狱即成功并返回。
  4. Prune-2(剪枝·保优):保留分数最高的 width 个叶节点进入下一轮。

论文默认超参:branching_factor=4width=10depth=10

评估器(Qwen3Guard)

默认 --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

思考模式(给目标 2 张卡更稳)

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 约定(每个模型用自己的卡,互不挤占)

常用参数

| 参数 | 默认 | 说明 | |——|——|——| | --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(原子写,运行中可随时查看/续跑):

final_prompt 是 TAP 最终收敛出的对抗提示词(成功时为触发越狱那条,否则为得分最高那条)。

断点续跑

中断后用同样命令加 --resume--input/--output 保持一致)。已完成的 goal 会被跳过,汇总指标基于全部结果重算。

文件说明

引用

@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}
}