[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-115049":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":9,"language":10,"languages":9,"totalLinesOfCode":9,"stars":11,"forks":12,"watchers":13,"openIssues":12,"contributorsCount":12,"subscribersCount":12,"size":12,"stars1d":12,"stars7d":14,"stars30d":14,"stars90d":12,"forks30d":12,"starsTrendScore":15,"compositeScore":16,"rankGlobal":9,"rankLanguage":9,"license":17,"archived":18,"fork":18,"defaultBranch":19,"hasWiki":20,"hasPages":18,"topics":21,"createdAt":9,"pushedAt":22,"updatedAt":23,"readmeContent":24,"aiSummary":25,"trendingCount":12,"starSnapshotCount":12,"syncStatus":26,"lastSyncTime":27,"discoverSource":28},115049,"Cat-DPO","RaymondY\u002FCat-DPO","RaymondY","Code for the NeurIPS 2026 paper \"Cat-DPO: Category-Adaptive Safety Alignment\"",null,"Python",101,0,59,40,9,64,"Apache License 2.0",false,"main",true,[],"2026-11-07 07:26:58","2026-11-21 13:36:11","\u003Ch1 align=\"center\">\n  \u003Cimg src=\"assets\u002Flogo.png\" height=\"36\" align=\"absmiddle\">&nbsp;Cat-DPO: Category-Adaptive Safety Alignment\n\u003C\u002Fh1>\n\n\u003Cp align=\"center\">\n  \u003Ca href=\"https:\u002F\u002Farxiv.org\u002Fabs\u002F2604.17299\">\u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FPaper-arXiv-B31B1B?logo=arxiv&logoColor=white\" alt=\"arXiv\">\u003C\u002Fa>\n  \u003Ca href=\"https:\u002F\u002Fneurips.cc\u002Fvirtual\u002F2026\u002Floc\u002Fatlanta\u002Fposter\u002F151048\">\u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FNeurIPS-2026-68448B?logo=data:image\u002Fpng;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM%2FrhtAAAEwklEQVR42t2YeahVVRTGf%2Bve65SWPjElTIvMelZqF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RKurKlJWTU4THZIdH1dmlN4qdvHWtvHgqsr7uvFd3tbAIh1CfAj6NiLvzxgpgLdAGVIHBEXF%2FiW7rgruaAR3Zf3u6JMvn9cnTWUIV85QvjEznO159Lb3dcPUO9QV1kDq0g4c0RQdHqr8lzSvVa7KabFIPLyXSYnWCenQz17414Pc0ku%2Fm%2FwBgTlKzQe0HvJxJ8yjwYkSsTfBt3Q3%2B7h5l9e6XBvVD4HVgSgrnfOD8BL4qTebNwEJgaERs6UmWNnpU0qVUgXuBc4DDUnL%2BTAf9fvq2BcDxuVCqAGcWjnqPfsWSOE5V70lJuVL9WO2b967LGF1e2kUYq%2FbZFXHuKeDRue61lCTT0o61luyZ6qxGbPsuUVwCVkvRHQbsAzwDtGVt3gTMA0Zk9y%2BBNzNxAHr3dGHe06%2FYmpVgQm5tbMzdg8Vq77q%2B%2FdW31Ocznpu3%2FabOKe2xDM0tjMJYXJzUD80%2BfxdivsdBluroIHWeul9afXPNMibbGzM0Fql37dUNzDQTP2alGZ0A19RT3mxQUbfFO7LUnlFyPrW9um5pWnbuTpBN3YP%2BLx%2F%2FADSkjr3XGqz9AAAAAElFTkSuQmCC\" alt=\"NeurIPS 2026\">\u003C\u002Fa>\n  \u003Ca href=\"LICENSE\">\u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FLicense-Apache%202.0-34A853\" alt=\"License\">\u003C\u002Fa>\n\u003C\u002Fp>\n\n\u003Cp align=\"center\">\n  \u003Ca href=\"assets\u002Fmethod_overview.png\">\n    \u003Cimg src=\"assets\u002Fmethod_overview.png\" alt=\"Left: standard DPO trains one LLM policy on preference data, each prompt carrying a preferred and an unpreferred response, under a single objective. Right: Cat-DPO reads the same preference data as K harm categories such as Public Health, Cybercrime, Privacy, and Violence. It trains the policy, adapts one margin lambda_k per category from quantities the training step already produces, and feeds those margins back into the next step.\" width=\"100%\">\n  \u003C\u002Fa>\n\u003C\u002Fp>\n\n## Overview\n\nDPO-based safety alignment is uneven across harm categories: a model can be safe on\naverage while leaving particular categories underprotected. Cat-DPO casts safety alignment\nas a *per-category* constrained problem and turns the Lagrangian dual variable of each\ncategory's constraint into an adaptive margin on the DPO loss, updated online from the\ntraining signal itself.\n\n```\nL = -log sigma(beta * delta_i - lambda_k)              lambda_k is the margin for category k\nlambda_k \u003C- max(0, lambda_k + eta * (V_i - epsilon))   V_i = 1 - sigma(beta * delta_i)\n```\n\nOn Alpaca-7B, against a matched run with the margin disabled, this lifts the three weakest\nharm categories from 85.5% to 94.3% safe and cuts cross-category variance by about 80%,\nat the same training cost. Details are in the [paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F2604.17299).\n\n\u003Cp align=\"center\">\n  \u003Ca href=\"assets\u002Fper_category.png\">\n    \u003Cimg src=\"assets\u002Fper_category.png\" alt=\"Per-category harmlessness on PKU-SafeRLHF for four methods trained on Alpaca-7B, shown on the eight harm categories where vanilla DPO scores lowest, with each method's overall average marked. Every method drops below its own average on these categories, and Cat-DPO is the highest of the four on all eight.\" width=\"92%\">\n  \u003C\u002Fa>\n\u003C\u002Fp>\n\n## Features\n\n- **Safety as `K` constraints, not one scalar.** Prior direct methods attach a single\n  safety signal to the loss, a cost budget, a fixed margin, or a separate safety stage,\n  and it reaches every training pair identically. Cat-DPO imposes one constraint per harm\n  category, so the optimization knows which categories are still lagging.\n- **Each category's margin adapts itself during training.** It rises while that category\n  is still unsafe and relaxes once it is not, driven by `V_i`, a quantity the DPO step\n  already computes that says how thin the chosen-rejected separation still is. Nothing is\n  tuned per category by hand, and there is no cost model and no on-policy sampling, so a\n  run costs what a DPO run costs. (Formally, each margin is the Lagrangian dual variable\n  of that category's constraint, which is where the update rule comes from.)\n- **Per category, not per pair.** Adaptive-margin DPO variants derive a margin from\n  pair-level features. Cat-DPO derives it per category, and charges a multi-label example\n  to the category it violates most.\n- **A thicker separation is what transfers.** A pair keeps contributing gradient until\n  `beta * delta_i` clears the margin, so a growing margin keeps pushing a lagging category\n  apart after a plain DPO loss would have released it, and that extra room is what holds\n  on prompts the model has not seen.\n- **Not tied to an annotated taxonomy.** The categories are only a grouping of the\n  training prompts, never read for what they mean. Annotated harm labels give the best\n  result, and clustering the prompts with no labels and no model recovers most of that\n  gain, so a dataset that ships no taxonomy is still workable.\n\n## Install\n\n```bash\npip install -r requirements.txt\n```\n\nOne GPU with enough memory for a 7B policy. On the first run the trainer caches the\nreference model's log-probabilities to `outputs\u002Fref_logps\u002F`, so later runs with the same\nmodel and dataset never load the reference model, which saves about 14 GB of VRAM.\n\n## Train\n\n```bash\n# Default: Alpaca-7B (LLaMA-2), eta=0.5, epsilon=0.02\nCUDA_VISIBLE_DEVICES=0 bash scripts\u002Frun_train.sh\n\n# Override any hyperparameter through the environment\nETA_DUAL=1.0 EPSILON=0.05 CUDA_VISIBLE_DEVICES=0 bash scripts\u002Frun_train.sh\n\n# A different backbone\nMODEL=Qwen\u002FQwen3-4B-Base CUDA_VISIBLE_DEVICES=0 bash scripts\u002Frun_train.sh\n\n# Several seeds\nfor s in 1 2 42; do SEED=$s CUDA_VISIBLE_DEVICES=0 bash scripts\u002Frun_train.sh; done\n```\n\nTraining uses the `alpaca2-7b` subset of\n[PKU-SafeRLHF](https:\u002F\u002Fhuggingface.co\u002Fdatasets\u002FPKU-Alignment\u002FPKU-SafeRLHF) in `bettersafe`\nmode, the preference pairs on which the helpfulness and safety annotations agree. The\ndataset carries 19 harm categories with multi-label annotations, so a prompt is charged to\nevery category it touches.\n\n## Hyperparameters\n\nSet through the environment before the script call. See `scripts\u002Frun_train.sh` for the\nfull list.\n\n| Parameter | Default | Description |\n|-----------|---------|-------------|\n| `ETA_DUAL` | `0.5` | Dual ascent step size for the lambda updates; `0` disables the margin |\n| `EPSILON` | `0.02` | Per-category safety tolerance |\n| `MARGIN_AGG` | `max` | How lambda is aggregated over a multi-label example: `max` or `sum` |\n| `LAMBDA_CAP` | `0` | Clip every lambda_k to this ceiling; `0` leaves it uncapped |\n| `CATEGORY_MAP` | — | JSON from `make_cluster_categories.py`, to train on label-free categories |\n| `SEED` | `42` | Random seed |\n| `LR` | `1e-5` | Learning rate |\n| `EPOCHS` | `2` | Number of training epochs |\n| `BATCH_SIZE` | `8` | Per-device batch size |\n| `GRAD_ACCUM` | `1` | Gradient accumulation steps (effective batch = `BATCH_SIZE` x `GRAD_ACCUM`) |\n| `BETA` | `0.1` | DPO KL penalty coefficient |\n\n## Categories without a harm taxonomy\n\nThe method does not require the category assignment `C(x)` to come from a curated\ntaxonomy. This script discards the 19 PKU harm labels and derives categories by\nunsupervised clustering of the training prompts: TF-IDF features over the prompt and its\nrejected response, truncated SVD, then k-means with `K = 19` so the number of dual\nvariables is unchanged. No model and no label is consulted.\n\n```bash\ncd src\npython make_cluster_categories.py --k 19 --out ..\u002Foutputs\u002Fcluster_categories_k19.json\ncd ..\nCATEGORY_MAP=outputs\u002Fcluster_categories_k19.json RUN_NAME=catdpo_clustered \\\n  CUDA_VISIBLE_DEVICES=0 bash scripts\u002Frun_train.sh\n```\n\nEvaluation still reports the original PKU 19 categories.\n\n## Evaluate\n\nGenerates responses on the PKU-SafeRLHF test split and scores them with two reward models:\n`beaver-7b-unified-cost` for safety (cost \u003C= 0 means safe) and `beaver-7b-unified-reward`\nfor helpfulness.\n\n```bash\nCUDA_VISIBLE_DEVICES=0 bash scripts\u002Frun_eval.sh outputs\u002Fcatdpo_eta0.5_eps0.02_seed42\u002Ffinal\n```\n\n| Metric | Definition |\n|--------|-----------|\n| Safety Rate | Fraction of safe responses (cost \u003C= 0) |\n| Macro Safety | Mean of the per-category safety rates |\n| Worst-3 Avg | Mean safety rate of the three worst categories |\n| Gap | Max minus min per-category safety rate |\n| Variance | Variance across the per-category safety rates |\n\nThe last four are the ones that move when the margin is per-category: they read the shape\nof the distribution rather than its mean.\n\n## Outputs\n\nAfter training, the run directory holds\n\n| File | Contents |\n|---|---|\n| `final\u002F` | Trained model checkpoint |\n| `catdpo_lambdas.csv` | Per-category lambda trajectories over training |\n| `category_metrics.csv` | Per-category margins, losses, preference probabilities |\n| `final_lambdas.json` | Final lambda value for every category |\n\n## Repository layout\n\n```\nsrc\u002F\n  data.py                      PKU-SafeRLHF loading and agreement filtering\n  ref_logps.py                 Precompute and cache reference model log-probs\n  category_logger.py           Per-category training metrics (wandb + CSV)\n  train_catdpo.py              Cat-DPO trainer, and the margin ablations\n  make_cluster_categories.py   Label-free category construction\n  evaluate.py                  Generation + beaver cost\u002Freward scoring\nscripts\u002F\n  run_train.sh                 Training launcher\n  run_eval.sh                  Evaluation launcher\n```\n\n## Citation\n\n```bibtex\n@inproceedings{yang2026catdpo,\n  title     = {Cat-DPO: Category-Adaptive Safety Alignment},\n  author    = {Yang, Tiankai and Nian, Yi and Li, Xinyuan and Xu, Ruiyao and Zou, Henry Peng\n               and Ding, Kaize and Hu, Xiyang and Liu, Yan and Zhao, Yue},\n  booktitle = {Advances in Neural Information Processing Systems (NeurIPS)},\n  year      = {2026}\n}\n```\n\n## License\n\nSee [LICENSE](LICENSE).\n","Cat-DPO 是一种面向多类别安全风险的偏好对齐方法，用于提升大语言模型在不同危害类型下的安全响应能力。其核心是扩展标准DPO（Direct Preference Optimization），为公共卫生、网络犯罪、隐私泄露、暴力等K类安全风险分别自适应学习类别特定的边界调节参数λₖ，无需额外标注或模型结构修改，仅基于原始偏好数据即可实现细粒度安全对齐。该方法适用于需要按危害类型差异化控制模型输出的场景，如内容审核系统、企业级AI助手安全加固及合规性敏感的垂直领域部署。",2,"2026-11-24 04:50:10","CREATED_QUERY"]