NYCU-MLLab's picture
Release REDACT code, linear risk heads, and model card
926f1b3 verified
|
Raw History Blame Contribute Delete
15.4 kB
# REDACT — Risk-Evaluated Decoding At Commit-Time
**ITD-MD** is the research codebase behind *REDACT*: toxicity-controlled text
generation for masked diffusion language models — **LLaDA-8B-Base** (primary)
and **Dream-v0-Base-7B** (replication backbone). The deployed risk model is a
noise-conditioned **linear head** trained on the frozen backbone's pooled hidden
states; at decode time,
REDACT directly evaluates the frozen-mask risk change of the model's top-K
candidates at each *committed* position and keeps the safest — single
trajectory, no reward model, no backward pass, with a per-commit KL bound to
the base model.
## Paper ↔ CLI method map
| Paper name | `control.method` | Notes |
|---|---|---|
| REDACT | `redact` (alias for `gradient` + `exact_dr_topk=K exact_dr_unmask=true`) | paper's η→∞ rows: `control.eta=1e8`; K via `control.exact_dr_topk` |
| REDACT-FO | `redact_fo` (alias for plain `gradient`) | first-order surrogate — the paper's *diagnosed* baseline (coherence collapse) |
| REDACT+BoN | `redact_bon` (alias for `gradient_bon` + exact-ΔR flags) | reward-access max-safety regime |
| Best-of-N | `bon_toxicity` | `control.best_of_n` |
| FK-DLM | `fk_dlm` | our reproduction of [Fk-Diffusion-Steering](https://github.com/yuhsuan0212/Fk-Diffusion-Steering); `fk_steering.*` |
| SMC-Base / SMC-Grad / SMC-AMOT | `smc_base` / `smc_grad` / `smc_amot` | our reproduction of [smc_ddm](https://github.com/yuhsuan0212/smc_ddm); `smc_ddm.*`; needs `model.mode=base` |
| Baseline | `baseline` | uncontrolled decoding |
## Environment
Managed with `uv`; **`cu130` is the only supported extra** (H200/Hopper). A
bare `uv sync` deliberately installs no torch.
```bash
uv sync --extra cu130
source .venv/bin/activate
# flash-attn builds from source (slow); on the SLURM cluster use:
sbatch scripts/setup/build_env.sh
```
Slurm launchers contain no site-specific account or email; pass `sbatch -A`
when your cluster does not provide a default account.
## Quickstart
```bash
# Extract the registered LLaDA cache, then train the paper-deployed linear head
python main.py polytope.extract extract.cache_dir=output/polytope_rebuild/cache
python main.py linear
# Evaluate (generic compatibility config remains polytope-first)
python main.py safety_eval control.method=baseline
# Select the deployed linear head explicitly
python main.py safety_eval --config-name linear control.method=redact control.eta=1e8
python main.py safety_eval control.method=redact_fo control.eta=50 control.grad_every_k=3
# Multi-GPU (single node)
python main.py --launcher torchrun --nproc-per-node 8 safety_eval control.method=redact
# Dream deployed head: `python main.py linear --config-name dream`
python main.py safety_eval --config-name dream_linear control.method=redact
# Dream polytope compatibility config
python main.py safety_eval --config-name dream control.method=redact
```
Smoke-test a change without the heavy scorers (the post-hoc LLM judge defaults
**on** and loads 32B vLLM models — always disable it for smokes):
```bash
python main.py safety_eval control.method=baseline data.num_samples=4 \
eval.ppl=false eval.degeneracy=false eval.llm_judge.enabled=false \
eval.output_dir=output/_smoke
```
**Refactor gates**: `bash scripts/checks/test_cpu.sh` runs the portable regression
suite. `sbatch scripts/checks/golden_smoke.sh` then runs 4-prompt evals for all
nine method/backbone families twice each and byte-compares generations against
blessed references (all families are deterministic under per-prompt seeding) —
run it after any change that touches decode, steering, or eval plumbing.
## Reproducing the paper
- Test set: two baseline passes + union via `sbatch scripts/toxicity/build_testset.sh`
and feed the merged JSON into evals with `data.local_prompts=...`.
- Main sweeps: `scripts/toxicity/safety_eval_multinode_sweep*.sh`,
`scripts/toxicity/methods_all_multinode.sh`, `scripts/toxicity/dream_methods_multinode.sh`, and
`scripts/toxicity/dream_linear_multinode.sh`.
- Faithfulness audit (Table 4): `sbatch scripts/analysis/taylor_faithfulness.sh`.
- Coherence judging: `scripts/analysis/llm_judge.sh` (vLLM Nemotron-3-Nano-30B-A3B + Gemma-3-27B).
- Op-count/cost table: `scripts/analysis/opcount_sweep.sh`.
The `*_multinode.sh` launchers call `srun ... torchrun ... -m
safety_evaluation.eval` directly instead of through `main.py` (whose torchrun
mode is single-node `--standalone` only) and reproduce its env contract by
hand: frozen `RUN_TS_*` for every rank, no `module load cuda` at runtime, no
`CUBLAS_WORKSPACE_CONFIG` — on CUDA 13 a system cuBLAS shadowing the torch
wheel's copy crashes the first bf16 GEMM with `CUBLAS_STATUS_INVALID_VALUE`.
## Repo map
| Path | What |
|---|---|
| `generate.py` / `generate_dream.py` | LLaDA decode loop + FO/direct-ΔR steering; Dream counterpart via `diffusion_generate` hooks |
| `polytope/` | risk-model pipeline: extract hidden-state cache → train LLaDA/Dream toxicity or refusal-robustness polytopes |
| `linear_head/` | paper-deployed single-layer, noise-conditioned risk head and its LLaDA/Dream training configs |
| `mlp/` | MLP risk-head ablation (same cache/pooling/labels/split as the polytope) |
| `jailbreak_reward/` | prompt-conditioned usable-safety reward manifest, training, and differentiable hard/soft-token scorer for BoN/FK/SMC baselines |
| `safety_evaluation/` | eval runtime plus `cli/` modules for toxicity and refusal-robustness datasets, judging, and reports |
| `analysis/` | commit-ledger, runtime, risk-resolution, faithfulness, and quality analyses |
| `tools/` | deterministic release and static-demo maintenance commands |
| `utils/` | model loading, pooling, distributed + file-barrier helpers, op counters, logging |
| `scripts/` | maintained Slurm/reproduction launchers; see `scripts/README.md` |
| `demo/gradient-logits/` | self-contained HTML visualization of one steering trace (provenance in its README) |
## Refusal-robustness transfer
The paper's secondary transfer study freezes a linear-head REDACT operating
point on 616 StrongREJECT prompts. It is separate from the toxicity main table;
refusal-substring and Llama-Guard scores are diagnostic sensitivities, not the
reportable semantic ASR endpoint.
```bash
# Train and validate the 4,385-parameter instruct-model risk head.
sbatch scripts/jailbreak/linear_head_train.sh
# The same launcher supports a smoke (default) or the frozen 616-prompt run.
sbatch scripts/jailbreak/disjoint_confirmatory.sh
JB_CONFIRMATORY_MODE=full sbatch scripts/jailbreak/disjoint_confirmatory.sh
# Semantic safety, response-only coherence, structure, and cost report.
sbatch scripts/jailbreak/disjoint_audit.sh
```
`disjoint_confirmatory.sh` is the public entry point; `eval_multinode.sh` is
its shared distributed backend. Generation is
scored against the original harmful behavior stored in `metadata.base_prompt`,
not against the attack wrapper. The frozen 616-prompt contrast is confirmatory;
reward-controller arms designed after opening that set are diagnostic only.
Automatic, agent-adjudicated, and human-adjudicated endpoints must remain
separately labelled.
The jailbreak presets truncate the visible continuation before the tokenizer's
first EOS/EOT token. This matters for fixed-length diffusion decoding: merely
using `skip_special_tokens=True` hides the marker but concatenates the filled
post-EOT slots back into the scored response. Generic toxicity presets retain
their compatibility behavior unless `generation.truncate_at_stop_tokens=true`
is selected explicitly.
## Deployed linear risk head
```bash
python main.py linear
python main.py linear --config-name dream
python main.py safety_eval --config-name linear control.method=redact
python main.py safety_eval --config-name dream_linear control.method=redact
```
The generic `config` and `dream` safety-eval presets intentionally retain the
polytope compatibility default. Select `linear` / `dream_linear` explicitly for the
paper-deployed head. Existing `output/linear_headswap*/time_dependent_mlp_best.pt`
artifacts remain loadable with `control.risk_model_type=linear`.
## MLP risk-head ablation
```bash
python main.py mlp.train
python main.py safety_eval control.risk_model_type=mlp \
control.risk_checkpoint=output/mlp/time_dependent_mlp_best.pt
```
Direct frozen-mask steering (`exact_dr_topk>0`) is head-family agnostic and supports
`risk_model_type=polytope`, `linear`, and `mlp`.
### Direct-ΔR runtime
Each evaluated commit position uses one batched backbone pass over its top-K
candidate rows, not K separate launches. Because a diffusion backbone processes
the full prompt-plus-response sequence for every row, row count and sequence
length both matter; evaluation logs report launches, rows, and token-rows.
The compatibility-preserving optimizations are enabled by default through
`control.exact_dr_runtime_optimized=true`. Dream reuses the native decode hidden
state and bypasses unused candidate vocabulary projections; LLaDA retains only
the final hidden state and bypasses the unused K-row vocabulary projection.
The golden gate checks these paths against the unoptimized reference generations.
`control.exact_dr_reuse_selected_state=true` is a separate LLaDA-only fast path
that reuses the chosen candidate state as the next base state. It substantially
reduces backbone work, but changes floating-point batching and can therefore
change later token decisions. It is intentionally off by default and requires a
fresh end-to-end result run whenever enabled.
`scripts/jailbreak/disjoint_audit.sh` rebuilds the safety, response-only
coherence, structural-validity, and cost report from frozen generation
artifacts.
### Jailbreak reward model training
The dedicated JB-RM is separate from the REDACT risk head. It learns one
prompt-conditioned usable-safety log reward for the BoN, FK, SMC-base, and
SMC-grad comparator track. Candidate generation and Nemotron annotation happen
upstream; the preparation command validates the frozen labels, behavior-level
splits, decontamination marker, and optional confirmation-set denylist before
tokenizing anything:
```bash
python main.py jailbreak_reward.prepare \
data.inputs='[output/jailbreak_reward/candidates/train.jsonl]' \
data.forbidden_behavior_ids=output/jailbreak_reward/corpus/forbidden_confirmation_behaviors.json
JB_REWARD_INIT_CHECKPOINT=/path/to/llada_toxicity_distill/checkpoint-last \
python main.py jailbreak_reward.train
# Reproduce the public-data v3 annotation + training pipeline on Slurm.
sbatch scripts/jailbreak/reward_public_train.sh
# Build every valid unique pair, annotate in eight GPU shards, then fit.
bash scripts/jailbreak/reward_public_max_build.sh
annotation_job=$(sbatch --parsable scripts/jailbreak/reward_public_max_annotate.sh)
sbatch --dependency="afterok:${annotation_job}" \
scripts/jailbreak/reward_public_max_train.sh
# Fully offline tiny-data training, checkpoint reload, and SMC-grad gates.
python tests/cpu/test_jailbreak_reward_cpu.py
python tests/cpu/test_jailbreak_reward_public_candidates_cpu.py
```
Each labelled candidate needs `dataset_id`, `behavior_id`, `split`,
`decontamination_status=pass`, attacked-prompt/response token IDs (or text), and
the frozen Nemotron parsed record. The positive class requires non-harmful
`refusal|safe_alternative` with relevance/coherence at least 3. The maximal
recipe combines every valid unique, group-split BeaverTails and Aegis
prompt/response pair with JBB trajectory examples, re-labels every source with
that same rubric, and assigns
equal total loss mass to each source-domain x teacher-class cell. A pretraining
gate rejects corpora with too few safe alternatives, paired groups, or source
domains; checkpoint selection macro-averages top-1 and pairwise accuracy across
domains. The exported checkpoint covers
the full 126,464-entry LLaDA proposal vocabulary and bundles a differentiable
`[B,L,V]` path; a scorer/LLaDA vocab mismatch is rejected rather than silently
masking proposal logits. The opened 616-row confirmation set is forbidden from
training, calibration, or checkpoint choice.
The runtime methods are additive: `bon_jb_rm`, `fk_dlm_jb_rm`,
`smc_base_jb_rm`, and `smc_grad_jb_rm` live beside, rather than replace, the
toxicity comparator implementations. They all bind the same checkpoint hash and
persist candidate/particle rewards plus method-specific selection, ancestry,
ESS, resampling, operation-count, wall-time, and memory provenance. The current
public-max-v4 checkpoint passed discrete ranking gates but failed the frozen
held-out Taylor-correlation threshold, so it is accepted for BoN/FK/SMC-base
only; `smc_grad_jb_rm` fails closed until a separately qualified checkpoint is
provided. A development-only matched smoke can be launched with:
```bash
JB_REWARD_SMOKE_RECORDS=80 \
JB_REWARD_SMOKE_SELECTION=all_terminal_validation \
JB_REWARD_GEN_LENGTH=256 JB_REWARD_GEN_STEPS=256 \
JB_REWARD_PROPOSAL_TEMPERATURE=0.7 \
JB_REWARD_INCLUDE_FROZEN_BASELINE=1 \
sbatch scripts/jailbreak/reward_methods_smoke.sh
```
This validation split is for controller selection only. It must not replace a
newly frozen held-out confirmation evaluation; the earlier 616-row StrongREJECT
set is excluded from training but has already been opened for evaluation.
Benign over-refusal is evaluated on a separately frozen, decontaminated cache:
247 XSTest-safe prompts plus all 1,319 OR-Bench-Hard prompts. Report the two
strata separately—never as one pooled rate. The refusal classifier treats any
attempt at the requested task as a direct answer and requires an exact response
span for every refusal; labels without evidence remain unresolved. The CPU
schema gate is:
```bash
python tests/cpu/test_benign_overrefusal_cpu.py
```
Run `scripts/jailbreak/benign_overrefusal_multinode.sh` with the default
`JB_BENIGN_METHOD_SET=primary` before adding reward-method comparators; judge it
with `scripts/jailbreak/benign_overrefusal_judge.sh`. AlpacaEval remains an
optional, separately reported general-instruction sanity stratum and is not in
the primary over-refusal denominator.
### Best-of-N runtime
`control.bon_runtime_optimized=true` enables the LLaDA BoN active-row decoder.
It applies vocabulary projection, Gumbel sampling, and the confidence softmax
only to still-masked rows in the current block instead of the prompt, committed
tokens, and future blocks. This preserves the sampling law but changes the RNG
tensor shape, so fixed seeds produce different stochastic candidates;
the switch remains off until the affected result rows are regenerated.
`control.bon_bypass_inactive_lm_head=true` controls the projection bypass.
`control.bon_reuse_selection_scores=true` is an exact optimization enabled by
default: the score already computed for the selected candidate becomes its
final evaluation score instead of invoking the same scorer again. Use
`scripts/checks/bon_runtime_benchmark.sh` and `scripts/checks/bon_runtime_accept.sh` for the
paired GPU benchmark and deterministic smoke gate.