HALOs 仓库支持多种大模型对齐训练方法

该仓库提供 DPO、KTO 和离线 PPO 等大模型对齐方法,并已扩展支持 LoRA、参考 logit 缓存与便捷评估,同时给出多节点 Slurm 训练启动脚本。

# **H**垛**a**以非为中心 **乐**ss 函数( HALOs) : 无效 : 此 repo 允许您将 LLMs 与各种方法对齐, 如 DPO , KTO, 以及 PPO 的离线版本 . 它最初是随KTO纸一同发行的,但后来进行了重大修改,以支持LoRAs,参考日志缓存,以及轻松的评价(原始代码参见: `legacy` 仓库的分支)。 与TRL或Axlotl等替代品相比,HALOs为: - 模块化:数据加载,培训和采样都是分开的. - 扩展性:您可以快速写入自己的数据加载器或执行新的对齐损失. - 简单: 重播量小到可以黑入. 它从1B到30B LLMS经过了规模测试;早期的版本被用于在Huggingface上训练Archangel套装模型. 配置由下列人员处理: [海德拉语Name](https://hydra.cc/),并同时启动工作 [加速](https://huggingface.co/docs/accelerate/en/index),并且所有培训默认使用 FSDP 完成。首先使用 Hugginface repo 的 SFT 模式 `meta-llama/Meta-Llama-3-8B`,运行命令像 ```accelerate launch --config_file accelerate_config/fsdp_8gpu.yaml --main_process_port 29500 launch.py loss=sft model=llama datasets=[ultrabin] exp_name=llama3-8b_sft ++cache_dir=/data/models ++model.name_or_path=meta-llama/Meta-Llama-3-8B``` which will save a model to `/data/models/llama3-8b_sft/FINAL/`. To then align the SFT model with KTO, run a command like ```accelerate launch --config_file accelerate_config/fsdp_8gpu.yaml --main_process_port 29500 launch.py loss=kto model=llama datasets=[ultrabin] exp_name=llama3-8b_sft_kto ++cache_dir=/data/models ++model.name_or_path=meta-llama/Meta-Llama-3-8B ++model.load_from=/data/models/llama3-8b_sft/FINAL/``` which will save a model to `/data/models/llama3-8b_sft_kto/FINAL`. ## Quickstart 1. First, clone the repo and install the dependencies. This might take a while. The package versions are important---if you change them, there is no guarantee the code will run. ```console . install.sh ``` 2. 确定您是否需要新的数据集。如果您有您想要引用的数据集 `foo` 当您启动任务时, 添加一个名为 `get_foo` 输入 `dataloader.py` 将返回一个 `Dataset` 实例。此函数应当有下列签名: `split` 应该是 `train` 或 时 间 `test`: ```def get_foo(split: str, *args, **kwargs) -> Dataset:``` Alternatively, you can have a dataset as a JSON file, where each object has the fields in `examples/binary_feedback` or `examples/pairwise_feedback`. You would pass the path to the dataset (e.g., `examples/binary_feedback`) instead of its name. Determine whether you need a new dataloader. Each loss in `config/loss/` has one corresponding dataloader; for KTO, it is `dataloader.UnpairedPreferenceDataLoader`. You will probably not need to write a new dataloader unless you are doing something creative, like turning score-based data into preferences or binary feedback. 3. Determine whether you need a new trainer. In most cases, this will subclass either `UnpairedPreferenceTrainer` (i.e., KTO-style) or `PairedPreferenceTrainer` (i.e., DPO-style). If you need highly custom behavior that is not in either, then you can subclass `BasicTrainer` directly. We can implement a dummy version of KTO as follows (not that this is different from the proper version of KTO in `KTOTrainer`). To make DummyKTOTrainer, we just subclass `trainers.UnpairedPreferenceTrainer` as `trainers.DummyKTOTrainer` and overwrite the loss function definition. ```python class DummyKTOTrainer(UnpairedPreferenceTrainer): """A fake version of KTO (not the actual one!) meant to introduce you to the HALOs repo.""" def loss(self, policy_chosen_logps: torch.FloatTensor, policy_rejected_logps: torch.FloatTensor, reference_chosen_logps: torch.FloatTensor, reference_rejected_logps: torch.FloatTensor) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: chosen_KL = (policy_chosen_logps - reference_chosen_logps).mean().clamp(min=0) rejected_KL = (policy_rejected_logps - reference_rejected_logps).mean().clamp(min=0) chosen_logratios = (policy_chosen_logps - reference_chosen_logps) rejected_logratios = (policy_rejected_logps - reference_rejected_logps) losses = torch.cat((1 - F.sigmoid(self.config.loss.beta * (chosen_logratios - chosen_KL)), 1 - F.sigmoid(self.config.loss.beta * (rejected_KL - rejected_logratios))), 0) chosen_rewards = self.config.loss.beta * (policy_chosen_logps - reference_chosen_logps).detach() rejected_rewards = self.config.loss.beta * (policy_rejected_logps - reference_rejected_logps).detach() return losses, chosen_rewards, rejected_rewards ``` 4. 如果我们想要的话,我们可以增加一个文件到 `config/loss` 指定 Dummy KTO 损失细节的文件夹 : ```yaml name: dummy-kto beta: 0.1 # the temperature parameter for dummy KTO; lower values mean we care less about the reference model trainer: DummyKTOTrainer # implemented in trainers.py dataloader: UnpairedPreferenceDataLoader # already exists in dataloaders.py ``` 同样,为了支持新一类的模型,我们将增加一个Yaml文件。 `config/model` 继承自 `config/model/base_model.yaml`. 5. 现在我们可以开始训练一个模型了! 让我们在Ultrafeedback和SHP数据集上调整一个Llama3-8B模型。 `wandb login` 运行 `wandb offline` 如果您的 GPU 没有连接到互联网。 然后启动任务 : ```console accelerate launch \ --config_file accelerate_config/fsdp_8gpu.yaml \ # accelerate config for 8-gpu allocation --main_process_port 29500 \ # port for gpu communication launch.py \ # main file for launching job loss=dummy-kto \ # must be a file name in config/loss model=llama \ # must be a file name in config/model datasets=[ultrabin,examples/binary_feedback.json] \ # ultrabin is a Huggingface dataset; binary_feedback.json is a local file exp_name=llama3-8b_sft_dummy-kto \ # experiment name, also the subfolder in cache dir for saving the model ++cache_dir=/data/models \ # set the cache directory ++model.name_or_path=meta-llama/Meta-Llama-3-8B \ # HF (or local) repo containing model configs, vocab, etc. ++model.load_from=/data/models/llama3-8b_sft/FINAL/ \ # load existing model as starting point; if empty, use model.name_or_path ++lr=5e-6 \ # set the learning rate ++loss.beta=0.1 # set a KTO-specific hyperparameter (see config/loss/kto.yaml for details) ``` 就是这样,你的模特儿会被救出来 `/data/models/llama3-8b_sft_dummy-kto/FINAL`. 6. 我们现在可以评价对齐模型。 首先,要评价AlpacaEval(需要为此设置OPENAI_API_KEY才能工作): ```console python -m train.sample /data/models/llama3-8b_sft_dummy-kto/FINAL --gpu_count 1 --output_file outputs/llama3-8b_sft_dummy-kto.json --datasets alpacaeval alpaca_eval evaluate --is_overwrite_leaderboard=True --model_outputs=outputs/llama3-8b_sft_dummy-kto.json ``` 然后,我们可以从LMEval运行各种基准的模型,在安装过程中下载到: ```console export MODEL_PATH=/data/models/llama3-8b_sft_dummy-kto/FINAL lm_eval --model hf \ --model_args pretrained="$MODEL_PATH",tokenizer="$MODEL_PATH",parallelize=True \ --tasks arc_easy,arc_challenge,winogrande,bbh_cot_fewshot,gsm8k_cot \ # can add any task in LMEval --batch_size 4 # bug if you use 'auto' with gsm8k_cot ``` 7. 如果我们想把这个抽样数据 变成一个新的反馈数据集 做另一轮对齐, 我们可以做 ```console accelerate launch --config_file accelerate_config/fsdp_4gpu.yaml --main_process_port 29500 label.py \ /data/models/llama3-8B-bt/FINAL outputs/llama3-8b_sft_dummy-kto.json \ pairwise_feedback_dataset.json --feedback_type pairwise ``` 地点 `/data/models/llama3-8B-bt/FINAL` 来自训练一个奖励模型 顶端的LLM使用 `BradleyTerryTrainer`. ## 问题 1. 您支持多节点训练吗 ? 是的,见 `scripts/launch_multinode_batch.sh` 财务报告和财务报告 `scripts/launch_multinode_interactive.sh` 在批量或交互式 Slurm 任务中如何在两个节点上启动任务。您可能需要一个自定义的加速配置, 取决于您有多少节点。 请使用 2 - 节点 示例 。 `accelerate_config` 作为模板。 2. 我该怎么拯救中间检查站? 设定 `intermediate_checkpoints` 到正数 `config/config.yaml` 或命令行上使用 `++config.intermediate_checkpoints=true`. 每一个 `config.eval_every` 步骤,在实验目录中将保存一个检查点(cache_dir /$ exp_name ). 3. 我在哪里找到所有阿奇尔模型? 他们都上 [拥抱脸枢纽](https://huggingface.co/collections/ContextualAI/archangel-65bd45029fa020161b052430). 4. 你支持LoRA训练吗? 是的,设置 `use_peft` 到正数 `config/model/base_model.yaml` 或命令行上使用 `++model.use_peft=true`。您可以使用默认的 LoRA 超参数。 `config/model/base_model.yaml` 或在命令行上覆盖它们(例如, `++model.peft.lora_r=128`),注意LoRA训练期间的中间检查站将只是LoRA模块,但LoRA重量在最终保存前将与模型合并. 5. 你支持FlashAttention吗? 是的,只是过关 `attn_implementation` 改为: `flash_attention_2` 输入 `model/base_model.yaml`,在命令行上,或者在任何继承文件上, `model/base_model.yaml`。默认情况下,某些模范类将这样做。 6. 我可以预先计算参考模型的日志概率来保存内存吗? 是的,简单设定 `++cache_reference_logprobs=true` 从参考模型中预先计算日志概率,这将大大降低内存。如果您在多个工作中使用相同的参考模型,这很常见,那么您可以覆盖 `++reference model=PATH` 到从先前任务中缓存到腌制文件中的日志概率。 7. 我得到一个错误 看起来像 [军衔1]: `torch.distributed.DistBackendError: [1] is setting up NCCL communicator and retrieving ncclUniqueId from [0] via c10d key-value store by key '0', but store->get('0') got error: Socket Timeout`. 这是因为您没有设置魔杖, 所以机器 0 正在等待您的输入来设置魔杖, 而其余的机器被屏蔽 。 `wandb login` 然后运行 `wandb offline` 如果您的机器没有连接到互联网上。 ## 引用 如果你觉得这回款有用,请随意引用: ``` @inproceedings{ethayarajhmodel, title={Model Alignment as Prospect Theoretic Optimization}, author={Ethayarajh, Kawin and Xu, Winnie and Muennighoff, Niklas and Jurafsky, Dan and Kiela, Douwe}, booktitle={Forty-first International Conference on Machine Learning} } ```

查看原始来源