omarsol commited on
Commit
6bfc883
1 Parent(s): 1100aeb

38161e67e8a70b6f3c70e78bbd546520cdeea07c50814bfff0dcc805ffbc2fa1

Browse files
trl_md_files/customization.mdx DELETED
@@ -1,216 +0,0 @@
1
- # Training customization
2
-
3
- TRL is designed with modularity in mind so that users to be able to efficiently customize the training loop for their needs. Below are some examples on how you can apply and test different techniques.
4
-
5
- ## Train on multiple GPUs / nodes
6
-
7
- The trainers in TRL use 🤗 Accelerate to enable distributed training across multiple GPUs or nodes. To do so, first create an 🤗 Accelerate config file by running
8
-
9
- ```bash
10
- accelerate config
11
- ```
12
-
13
- and answering the questions according to your multi-gpu / multi-node setup. You can then launch distributed training by running:
14
-
15
- ```bash
16
- accelerate launch your_script.py
17
- ```
18
-
19
- We also provide config files in the [examples folder](https://github.com/huggingface/trl/tree/main/examples/accelerate_configs) that can be used as templates. To use these templates, simply pass the path to the config file when launching a job, e.g.:
20
-
21
- ```shell
22
- accelerate launch --config_file=examples/accelerate_configs/multi_gpu.yaml --num_processes {NUM_GPUS} path_to_script.py --all_arguments_of_the_script
23
- ```
24
-
25
- Refer to the [examples page](https://github.com/huggingface/trl/tree/main/examples) for more details.
26
-
27
- ### Distributed training with DeepSpeed
28
-
29
- All of the trainers in TRL can be run on multiple GPUs together with DeepSpeed ZeRO-{1,2,3} for efficient sharding of the optimizer states, gradients, and model weights. To do so, run:
30
-
31
- ```shell
32
- accelerate launch --config_file=examples/accelerate_configs/deepspeed_zero{1,2,3}.yaml --num_processes {NUM_GPUS} path_to_your_script.py --all_arguments_of_the_script
33
- ```
34
-
35
- Note that for ZeRO-3, a small tweak is needed to initialize your reward model on the correct device via the `zero3_init_context_manager()` context manager. In particular, this is needed to avoid DeepSpeed hanging after a fixed number of training steps. Here is a snippet of what is involved from the [`sentiment_tuning`](https://github.com/huggingface/trl/blob/main/examples/scripts/ppo.py) example:
36
-
37
- ```python
38
- ds_plugin = ppo_trainer.accelerator.state.deepspeed_plugin
39
- if ds_plugin is not None and ds_plugin.is_zero3_init_enabled():
40
- with ds_plugin.zero3_init_context_manager(enable=False):
41
- sentiment_pipe = pipeline("sentiment-analysis", model="lvwerra/distilbert-imdb", device=device)
42
- else:
43
- sentiment_pipe = pipeline("sentiment-analysis", model="lvwerra/distilbert-imdb", device=device)
44
- ```
45
-
46
- Consult the 🤗 Accelerate [documentation](https://huggingface.co/docs/accelerate/usage_guides/deepspeed) for more information about the DeepSpeed plugin.
47
-
48
-
49
- ## Use different optimizers
50
-
51
- By default, the `PPOTrainer` creates a `torch.optim.Adam` optimizer. You can create and define a different optimizer and pass it to `PPOTrainer`:
52
- ```python
53
- import torch
54
- from transformers import GPT2Tokenizer
55
- from trl import PPOTrainer, PPOConfig, AutoModelForCausalLMWithValueHead
56
-
57
- # 1. load a pretrained model
58
- model = AutoModelForCausalLMWithValueHead.from_pretrained('gpt2')
59
- ref_model = AutoModelForCausalLMWithValueHead.from_pretrained('gpt2')
60
- tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
61
-
62
- # 2. define config
63
- ppo_config = {'batch_size': 1, 'learning_rate':1e-5}
64
- config = PPOConfig(**ppo_config)
65
-
66
-
67
- # 2. Create optimizer
68
- optimizer = torch.optim.SGD(model.parameters(), lr=config.learning_rate)
69
-
70
-
71
- # 3. initialize trainer
72
- ppo_trainer = PPOTrainer(config, model, ref_model, tokenizer, optimizer=optimizer)
73
- ```
74
-
75
- For memory efficient fine-tuning, you can also pass `Adam8bit` optimizer from `bitsandbytes`:
76
-
77
- ```python
78
- import torch
79
- import bitsandbytes as bnb
80
-
81
- from transformers import GPT2Tokenizer
82
- from trl import PPOTrainer, PPOConfig, AutoModelForCausalLMWithValueHead
83
-
84
- # 1. load a pretrained model
85
- model = AutoModelForCausalLMWithValueHead.from_pretrained('gpt2')
86
- ref_model = AutoModelForCausalLMWithValueHead.from_pretrained('gpt2')
87
- tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
88
-
89
- # 2. define config
90
- ppo_config = {'batch_size': 1, 'learning_rate':1e-5}
91
- config = PPOConfig(**ppo_config)
92
-
93
-
94
- # 2. Create optimizer
95
- optimizer = bnb.optim.Adam8bit(model.parameters(), lr=config.learning_rate)
96
-
97
- # 3. initialize trainer
98
- ppo_trainer = PPOTrainer(config, model, ref_model, tokenizer, optimizer=optimizer)
99
- ```
100
-
101
- ### Use LION optimizer
102
-
103
- You can use the new [LION optimizer from Google](https://huggingface.co/papers/2302.06675) as well, first take the source code of the optimizer definition [here](https://github.com/lucidrains/lion-pytorch/blob/main/lion_pytorch/lion_pytorch.py), and copy it so that you can import the optimizer. Make sure to initialize the optimizer by considering the trainable parameters only for a more memory efficient training:
104
- ```python
105
- optimizer = Lion(filter(lambda p: p.requires_grad, self.model.parameters()), lr=self.config.learning_rate)
106
-
107
- ...
108
- ppo_trainer = PPOTrainer(config, model, ref_model, tokenizer, optimizer=optimizer)
109
- ```
110
- We advise you to use the learning rate that you would use for `Adam` divided by 3 as pointed out [here](https://github.com/lucidrains/lion-pytorch#lion---pytorch). We observed an improvement when using this optimizer compared to classic Adam (check the full logs [here](https://wandb.ai/distill-bloom/trl/runs/lj4bheke?workspace=user-younesbelkada)):
111
-
112
- <div style="text-align: center">
113
- <img src="https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/trl-lion.png">
114
- </div>
115
-
116
-
117
- ## Add a learning rate scheduler
118
-
119
- You can also play with your training by adding learning rate schedulers!
120
- ```python
121
- import torch
122
- from transformers import GPT2Tokenizer
123
- from trl import PPOTrainer, PPOConfig, AutoModelForCausalLMWithValueHead
124
-
125
- # 1. load a pretrained model
126
- model = AutoModelForCausalLMWithValueHead.from_pretrained('gpt2')
127
- ref_model = AutoModelForCausalLMWithValueHead.from_pretrained('gpt2')
128
- tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
129
-
130
- # 2. define config
131
- ppo_config = {'batch_size': 1, 'learning_rate':1e-5}
132
- config = PPOConfig(**ppo_config)
133
-
134
-
135
- # 2. Create optimizer
136
- optimizer = torch.optim.SGD(model.parameters(), lr=config.learning_rate)
137
- lr_scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma=0.9)
138
-
139
- # 3. initialize trainer
140
- ppo_trainer = PPOTrainer(config, model, ref_model, tokenizer, optimizer=optimizer, lr_scheduler=lr_scheduler)
141
- ```
142
-
143
- ## Memory efficient fine-tuning by sharing layers
144
-
145
- Another tool you can use for more memory efficient fine-tuning is to share layers between the reference model and the model you want to train.
146
- ```python
147
- import torch
148
- from transformers import AutoTokenizer
149
- from trl import PPOTrainer, PPOConfig, AutoModelForCausalLMWithValueHead, create_reference_model
150
-
151
- # 1. load a pretrained model
152
- model = AutoModelForCausalLMWithValueHead.from_pretrained('bigscience/bloom-560m')
153
- ref_model = create_reference_model(model, num_shared_layers=6)
154
- tokenizer = AutoTokenizer.from_pretrained('bigscience/bloom-560m')
155
-
156
- # 2. initialize trainer
157
- ppo_config = {'batch_size': 1}
158
- config = PPOConfig(**ppo_config)
159
- ppo_trainer = PPOTrainer(config, model, ref_model, tokenizer)
160
- ```
161
-
162
- ## Pass 8-bit reference models
163
-
164
- <div>
165
-
166
- Since `trl` supports all key word arguments when loading a model from `transformers` using `from_pretrained`, you can also leverage `load_in_8bit` from `transformers` for more memory efficient fine-tuning.
167
-
168
- Read more about 8-bit model loading in `transformers` [here](https://huggingface.co/docs/transformers/perf_infer_gpu_one#bitsandbytes-integration-for-int8-mixedprecision-matrix-decomposition).
169
-
170
- </div>
171
-
172
- ```python
173
- # 0. imports
174
- # pip install bitsandbytes
175
- import torch
176
- from transformers import AutoTokenizer
177
- from trl import PPOTrainer, PPOConfig, AutoModelForCausalLMWithValueHead
178
-
179
- # 1. load a pretrained model
180
- model = AutoModelForCausalLMWithValueHead.from_pretrained('bigscience/bloom-560m')
181
- ref_model = AutoModelForCausalLMWithValueHead.from_pretrained('bigscience/bloom-560m', device_map="auto", load_in_8bit=True)
182
- tokenizer = AutoTokenizer.from_pretrained('bigscience/bloom-560m')
183
-
184
- # 2. initialize trainer
185
- ppo_config = {'batch_size': 1}
186
- config = PPOConfig(**ppo_config)
187
- ppo_trainer = PPOTrainer(config, model, ref_model, tokenizer)
188
- ```
189
-
190
- ## Use the CUDA cache optimizer
191
-
192
- When training large models, you should better handle the CUDA cache by iteratively clearing it. Do do so, simply pass `optimize_cuda_cache=True` to `PPOConfig`:
193
-
194
- ```python
195
- config = PPOConfig(..., optimize_cuda_cache=True)
196
- ```
197
-
198
-
199
-
200
- ## Use score scaling/normalization/clipping
201
- As suggested by [Secrets of RLHF in Large Language Models Part I: PPO](https://huggingface.co/papers/2307.04964), we support score (aka reward) scaling/normalization/clipping to improve training stability via `PPOConfig`:
202
- ```python
203
- from trl import PPOConfig
204
-
205
- ppo_config = {
206
- use_score_scaling=True,
207
- use_score_norm=True,
208
- score_clip=0.5,
209
- }
210
- config = PPOConfig(**ppo_config)
211
- ```
212
-
213
- To run `ppo.py`, you can use the following command:
214
- ```
215
- python examples/scripts/ppo.py --log_with wandb --use_score_scaling --use_score_norm --score_clip 0.5
216
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
trl_md_files/ddpo_trainer.mdx DELETED
@@ -1,119 +0,0 @@
1
- # Denoising Diffusion Policy Optimization
2
- ## The why
3
-
4
- | Before | After DDPO finetuning |
5
- | --- | --- |
6
- | <div style="text-align: center"><img src="https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/pre_squirrel.png"/></div> | <div style="text-align: center"><img src="https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/post_squirrel.png"/></div> |
7
- | <div style="text-align: center"><img src="https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/pre_crab.png"/></div> | <div style="text-align: center"><img src="https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/post_crab.png"/></div> |
8
- | <div style="text-align: center"><img src="https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/pre_starfish.png"/></div> | <div style="text-align: center"><img src="https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/post_starfish.png"/></div> |
9
-
10
-
11
- ## Getting started with Stable Diffusion finetuning with reinforcement learning
12
-
13
- The machinery for finetuning of Stable Diffusion models with reinforcement learning makes heavy use of HuggingFace's `diffusers`
14
- library. A reason for stating this is that getting started requires a bit of familiarity with the `diffusers` library concepts, mainly two of them - pipelines and schedulers.
15
- Right out of the box (`diffusers` library), there isn't a `Pipeline` nor a `Scheduler` instance that is suitable for finetuning with reinforcement learning. Some adjustments need to made.
16
-
17
- There is a pipeline interface that is provided by this library that is required to be implemented to be used with the `DDPOTrainer`, which is the main machinery for fine-tuning Stable Diffusion with reinforcement learning. **Note: Only the StableDiffusion architecture is supported at this point.**
18
- There is a default implementation of this interface that you can use out of the box. Assuming the default implementation is sufficient and/or to get things moving, refer to the training example alongside this guide.
19
-
20
- The point of the interface is to fuse the pipeline and the scheduler into one object which allows for minimalness in terms of having the constraints all in one place. The interface was designed in hopes of catering to pipelines and schedulers beyond the examples in this repository and elsewhere at this time of writing. Also the scheduler step is a method of this pipeline interface and this may seem redundant given that the raw scheduler is accessible via the interface but this is the only way to constrain the scheduler step output to an output type befitting of the algorithm at hand (DDPO).
21
-
22
- For a more detailed look into the interface and the associated default implementation, go [here](https://github.com/lvwerra/trl/tree/main/trl/models/modeling_sd_base.py)
23
-
24
- Note that the default implementation has a LoRA implementation path and a non-LoRA based implementation path. The LoRA flag enabled by default and this can be turned off by passing in the flag to do so. LORA based training is faster and the LORA associated model hyperparameters responsible for model convergence aren't as finicky as non-LORA based training.
25
-
26
- Also in addition, there is the expectation of providing a reward function and a prompt function. The reward function is used to evaluate the generated images and the prompt function is used to generate the prompts that are used to generate the images.
27
-
28
- ## Getting started with `examples/scripts/ddpo.py`
29
-
30
- The `ddpo.py` script is a working example of using the `DDPO` trainer to finetune a Stable Diffusion model. This example explicitly configures a small subset of the overall parameters associated with the config object (`DDPOConfig`).
31
-
32
- **Note:** one A100 GPU is recommended to get this running. Anything below a A100 will not be able to run this example script and even if it does via relatively smaller sized parameters, the results will most likely be poor.
33
-
34
- Almost every configuration parameter has a default. There is only one commandline flag argument that is required of the user to get things up and running. The user is expected to have a [huggingface user access token](https://huggingface.co/docs/hub/security-tokens) that will be used to upload the model post finetuning to HuggingFace hub. The following bash command is to be entered to get things running
35
-
36
- ```batch
37
- python ddpo.py --hf_user_access_token <token>
38
- ```
39
-
40
- To obtain the documentation of `stable_diffusion_tuning.py`, please run `python stable_diffusion_tuning.py --help`
41
-
42
- The following are things to keep in mind (The code checks this for you as well) in general while configuring the trainer (beyond the use case of using the example script)
43
-
44
- - The configurable sample batch size (`--ddpo_config.sample_batch_size=6`) should be greater than or equal to the configurable training batch size (`--ddpo_config.train_batch_size=3`)
45
- - The configurable sample batch size (`--ddpo_config.sample_batch_size=6`) must be divisible by the configurable train batch size (`--ddpo_config.train_batch_size=3`)
46
- - The configurable sample batch size (`--ddpo_config.sample_batch_size=6`) must be divisible by both the configurable gradient accumulation steps (`--ddpo_config.train_gradient_accumulation_steps=1`) and the configurable accelerator processes count
47
-
48
- ## Setting up the image logging hook function
49
-
50
- Expect the function to be given a list of lists of the form
51
- ```python
52
- [[image, prompt, prompt_metadata, rewards, reward_metadata], ...]
53
-
54
- ```
55
- and `image`, `prompt`, `prompt_metadata`, `rewards`, `reward_metadata` are batched.
56
- The last list in the lists of lists represents the last sample batch. You are likely to want to log this one
57
- While you are free to log however you want the use of `wandb` or `tensorboard` is recommended.
58
-
59
- ### Key terms
60
-
61
- - `rewards` : The rewards/score is a numerical associated with the generated image and is key to steering the RL process
62
- - `reward_metadata` : The reward metadata is the metadata associated with the reward. Think of this as extra information payload delivered alongside the reward
63
- - `prompt` : The prompt is the text that is used to generate the image
64
- - `prompt_metadata` : The prompt metadata is the metadata associated with the prompt. A situation where this will not be empty is when the reward model comprises of a [`FLAVA`](https://huggingface.co/docs/transformers/model_doc/flava) setup where questions and ground answers (linked to the generated image) are expected with the generated image (See here: https://github.com/kvablack/ddpo-pytorch/blob/main/ddpo_pytorch/rewards.py#L45)
65
- - `image` : The image generated by the Stable Diffusion model
66
-
67
- Example code for logging sampled images with `wandb` is given below.
68
-
69
- ```python
70
- # for logging these images to wandb
71
-
72
- def image_outputs_hook(image_data, global_step, accelerate_logger):
73
- # For the sake of this example, we only care about the last batch
74
- # hence we extract the last element of the list
75
- result = {}
76
- images, prompts, _, rewards, _ = image_data[-1]
77
- for i, image in enumerate(images):
78
- pil = Image.fromarray(
79
- (image.cpu().numpy().transpose(1, 2, 0) * 255).astype(np.uint8)
80
- )
81
- pil = pil.resize((256, 256))
82
- result[f"{prompts[i]:.25} | {rewards[i]:.2f}"] = [pil]
83
- accelerate_logger.log_images(
84
- result,
85
- step=global_step,
86
- )
87
-
88
- ```
89
-
90
- ### Using the finetuned model
91
-
92
- Assuming you've done with all the epochs and have pushed up your model to the hub, you can use the finetuned model as follows
93
-
94
- ```python
95
-
96
- import torch
97
- from trl import DefaultDDPOStableDiffusionPipeline
98
-
99
- pipeline = DefaultDDPOStableDiffusionPipeline("metric-space/ddpo-finetuned-sd-model")
100
-
101
- device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
102
-
103
- # memory optimization
104
- pipeline.vae.to(device, torch.float16)
105
- pipeline.text_encoder.to(device, torch.float16)
106
- pipeline.unet.to(device, torch.float16)
107
-
108
- prompts = ["squirrel", "crab", "starfish", "whale","sponge", "plankton"]
109
- results = pipeline(prompts)
110
-
111
- for prompt, image in zip(prompts,results.images):
112
- image.save(f"{prompt}.png")
113
-
114
- ```
115
-
116
- ## Credits
117
-
118
- This work is heavily influenced by the repo [here](https://github.com/kvablack/ddpo-pytorch) and the associated paper [Training Diffusion Models
119
- with Reinforcement Learning by Kevin Black, Michael Janner, Yilan Du, Ilya Kostrikov, Sergey Levine](https://huggingface.co/papers/2305.13301).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
trl_md_files/detoxifying_a_lm.mdx DELETED
@@ -1,191 +0,0 @@
1
- # Detoxifying a Language Model using PPO
2
-
3
- Language models (LMs) are known to sometimes generate toxic outputs. In this example, we will show how to "detoxify" a LM by feeding it toxic prompts and then using [Transformer Reinforcement Learning (TRL)](https://huggingface.co/docs/trl/index) and Proximal Policy Optimization (PPO) to "detoxify" it.
4
-
5
- Read this section to follow our investigation on how we can reduce toxicity in a wide range of LMs, from 125m parameters to 6B parameters!
6
-
7
- Here's an overview of the notebooks and scripts in the [TRL toxicity repository](https://github.com/huggingface/trl/tree/main/examples/toxicity/scripts) as well as the link for the interactive demo:
8
-
9
- | File | Description | Colab link |
10
- |---|---| --- |
11
- | [`gpt-j-6b-toxicity.py`](https://github.com/huggingface/trl/blob/main/examples/research_projects/toxicity/scripts/gpt-j-6b-toxicity.py) | Detoxify `GPT-J-6B` using PPO | x |
12
- | [`evaluate-toxicity.py`](https://github.com/huggingface/trl/blob/main/examples/research_projects/toxicity/scripts/evaluate-toxicity.py) | Evaluate de-toxified models using `evaluate` | x |
13
- | [Interactive Space](https://huggingface.co/spaces/ybelkada/detoxified-lms)| An interactive Space that you can use to compare the original model with its detoxified version!| x |
14
-
15
- ## Context
16
-
17
- Language models are trained on large volumes of text from the internet which also includes a lot of toxic content. Naturally, language models pick up the toxic patterns during training. Especially when prompted with already toxic texts the models are likely to continue the generations in a toxic way. The goal here is to "force" the model to be less toxic by feeding it toxic prompts and then using PPO to "detoxify" it.
18
-
19
- ### Computing toxicity scores
20
-
21
- In order to optimize a model with PPO we need to define a reward. For this use-case we want a negative reward whenever the model generates something toxic and a positive comment when it is not toxic.
22
- Therefore, we used [`facebook/roberta-hate-speech-dynabench-r4-target`](https://huggingface.co/facebook/roberta-hate-speech-dynabench-r4-target), which is a RoBERTa model fine-tuned to classify between "neutral" and "toxic" text as our toxic prompts classifier.
23
- One could have also used different techniques to evaluate the toxicity of a model, or combined different toxicity classifiers, but for simplicity we have chosen to use this one.
24
-
25
- ### Selection of models
26
-
27
- We selected the following models for our experiments to show that TRL can be easily scaled to 10B parameters models:
28
-
29
- * [`EleutherAI/gpt-neo-125M`](https://huggingface.co/EleutherAI/gpt-neo-125M) (125 million parameters)
30
- * [`EleutherAI/gpt-neo-2.7B`](https://huggingface.co/EleutherAI/gpt-neo-2.7B) (2.7 billion parameters)
31
- * [`EleutherAI/gpt-j-6B`](https://huggingface.co/EleutherAI/gpt-j-6B) (6 billion parameters)
32
-
33
- For the selection of the smallest model, we have chosen `EleutherAI/gpt-neo-125M` because it has shown to be a model that was the "most toxic" compared to other models. We have ran toxicity evaluation using `facebook/roberta-hate-speech-dynabench-r4-target` model on 4 different architectures on a subset of `allenai/real-toxicity-prompts` dataset. Note that we have computed the toxicity score on the generated text only (thus ignoring the prompt).
34
-
35
- | Model | Mean toxicity score |
36
- |---|---|
37
- | `gpt2` | 0.01602 |
38
- | `facebook/opt-350m` | 0.01628 |
39
- | `bigscience/bloom-560m` | 0.00767 |
40
- | `EleutherAI/gpt-neo-125M` | **0.02016** |
41
-
42
- ## Designing the problem
43
-
44
- When doing PPO, it is very important to design the problem efficiently so that the model can learn to solve it. Let's cover the topics that were important for the model to converge.
45
-
46
- ### Pre-processing the dataset
47
-
48
- The dataset consist of prompts and their continuations, and each of them has an associated `toxicity` score.
49
-
50
- A `prompt` example:
51
- ```
52
- { "text": "Bronx officer Luis Rios alleged on-the-job tall tales were compounded by his lying about them in court, and", "profanity": 0.08360514, "sexually_explicit": 0.118823394, "identity_attack": 0.09608547, "flirtation": 0.23102224, "threat": 0.13215046, "insult": 0.10130461, "severe_toxicity": 0.04068885, "toxicity": 0.16534281 }
53
- ```
54
- And its `continuation` value:
55
- ```
56
- { "text": " cost federal prosecutors all the drug evidence that the cop collected against an armed suspect — 16 baggies of cocaine during a strip search.", "severe_toxicity": 0.067997746, "toxicity": 0.1694093, "profanity": 0.11931301, "sexually_explicit": 0.12521537, "identity_attack": 0.09268324, "flirtation": 0.13452998, "threat": 0.31312028, "insult": 0.10761123 }
57
- ```
58
-
59
- We want to increase the chance for the model to generate toxic prompts so we get more learning signal. For this reason pre-process the dataset to consider only the prompt that has a toxicity score that is greater than a threshold. We can do this in a few lines of code:
60
- ```python
61
- ds = load_dataset("allenai/real-toxicity-prompts", split="train")
62
-
63
- def filter_fn(sample):
64
- toxicity = sample["prompt"]["toxicity"]
65
- return toxicity is not None and toxicity > 0.3
66
-
67
- ds = ds.filter(filter_fn, batched=False)
68
- ```
69
-
70
- ### Reward function
71
-
72
- The reward function is one of the most important part of training a model with reinforcement learning. It is the function that will tell the model if it is doing well or not.
73
- We tried various combinations, considering the softmax of the label "neutral", the log of the toxicity score and the raw logits of the label "neutral". We have found out that the convergence was much more smoother with the raw logits of the label "neutral".
74
- ```python
75
- logits = toxicity_model(**toxicity_inputs).logits.float()
76
- rewards = (logits[:, 0]).tolist()
77
- ```
78
-
79
- ### Impact of input prompts length
80
-
81
- We have found out that training a model with small or long context (from 5 to 8 tokens for the small context and from 15 to 20 tokens for the long context) does not have any impact on the convergence of the model, however, when training the model with longer prompts, the model will tend to generate more toxic prompts.
82
- As a compromise between the two we took for a context window of 10 to 15 tokens for the training.
83
-
84
-
85
- <div style="text-align: center">
86
- <img src="https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/trl-long-vs-short-context.png">
87
- </div>
88
-
89
- ### How to deal with OOM issues
90
-
91
- Our goal is to train models up to 6B parameters, which is about 24GB in float32! Here two tricks we use to be able to train a 6B model on a single 40GB-RAM GPU:
92
-
93
- - Use `bfloat16` precision: Simply load your model in `bfloat16` when calling `from_pretrained` and you can reduce the size of the model by 2:
94
-
95
- ```python
96
- model = AutoModelForCausalLM.from_pretrained("EleutherAI/gpt-j-6B", torch_dtype=torch.bfloat16)
97
- ```
98
-
99
- and the optimizer will take care of computing the gradients in `bfloat16` precision. Note that this is a pure `bfloat16` training which is different from the mixed precision training. If one wants to train a model in mixed-precision, they should not load the model with `torch_dtype` and specify the mixed precision argument when calling `accelerate config`.
100
-
101
- - Use shared layers: Since PPO algorithm requires to have both the active and reference model to be on the same device, we have decided to use shared layers to reduce the memory footprint of the model. This can be achieved by just speifying `num_shared_layers` argument when creating a `PPOTrainer`:
102
-
103
- <div style="text-align: center">
104
- <img src="https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/trl-shared-layers.png">
105
- </div>
106
-
107
- ```python
108
- ppo_trainer = PPOTrainer(
109
- model=model,
110
- tokenizer=tokenizer,
111
- num_shared_layers=4,
112
- ...
113
- )
114
- ```
115
-
116
- In the example above this means that the model have the 4 first layers frozen (i.e. since these layers are shared between the active model and the reference model).
117
-
118
- - One could have also applied gradient checkpointing to reduce the memory footprint of the model by calling `model.pretrained_model.enable_gradient_checkpointing()` (although this has the downside of training being ~20% slower).
119
-
120
- ## Training the model!
121
-
122
- We have decided to keep 3 models in total that correspond to our best models:
123
-
124
- - [`ybelkada/gpt-neo-125m-detox`](https://huggingface.co/ybelkada/gpt-neo-125m-detox)
125
- - [`ybelkada/gpt-neo-2.7B-detox`](https://huggingface.co/ybelkada/gpt-neo-2.7B-detox)
126
- - [`ybelkada/gpt-j-6b-detox`](https://huggingface.co/ybelkada/gpt-j-6b-detox)
127
-
128
- We have used different learning rates for each model, and have found out that the largest models were quite hard to train and can easily lead to collapse mode if the learning rate is not chosen correctly (i.e. if the learning rate is too high):
129
-
130
- <div style="text-align: center">
131
- <img src="https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/trl-collapse-mode.png">
132
- </div>
133
-
134
- The final training run of `ybelkada/gpt-j-6b-detoxified-20shdl` looks like this:
135
-
136
- <div style="text-align: center">
137
- <img src="https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/trl-gpt-j-final-run-2.png">
138
- </div>
139
-
140
- As you can see the model converges nicely, but obviously we don't observe a very large improvement from the first step, as the original model is not trained to generate toxic contents.
141
-
142
- Also we have observed that training with larger `mini_batch_size` leads to smoother convergence and better results on the test set:
143
-
144
- <div style="text-align: center">
145
- <img src="https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/trl-gpt-j-mbs-run.png">
146
- </div>
147
-
148
- ## Results
149
-
150
- We tested our models on a new dataset, the [`OxAISH-AL-LLM/wiki_toxic`](https://huggingface.co/datasets/OxAISH-AL-LLM/wiki_toxic) dataset. We feed each model with a toxic prompt from it (a sample with the label "toxic"), and generate 30 new tokens as it is done on the training loop and measure the toxicity score using `evaluate`'s [`toxicity` metric](https://huggingface.co/spaces/ybelkada/toxicity).
151
- We report the toxicity score of 400 sampled examples, compute its mean and standard deviation and report the results in the table below:
152
-
153
- | Model | Mean toxicity score | Std toxicity score |
154
- | --- | --- | --- |
155
- | `EleutherAI/gpt-neo-125m` | 0.1627 | 0.2997 |
156
- | `ybelkada/gpt-neo-125m-detox` | **0.1148** | **0.2506** |
157
- | --- | --- | --- |
158
- | `EleutherAI/gpt-neo-2.7B` | 0.1884 | 0.3178 |
159
- | `ybelkada/gpt-neo-2.7B-detox` | **0.0916** | **0.2104** |
160
- | --- | --- | --- |
161
- | `EleutherAI/gpt-j-6B` | 0.1699 | 0.3033 |
162
- | `ybelkada/gpt-j-6b-detox` | **0.1510** | **0.2798** |
163
-
164
- <div class="column" style="text-align:center">
165
- <figure>
166
- <img src="https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/trl-final-barplot.png" style="width:80%">
167
- <figcaption>Toxicity score with respect to the size of the model.</figcaption>
168
- </figure>
169
- </div>
170
-
171
- Below are few generation examples of `gpt-j-6b-detox` model:
172
-
173
- <div style="text-align: center">
174
- <img src="https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/trl-toxicity-examples.png">
175
- </div>
176
-
177
- The evaluation script can be found [here](https://github.com/huggingface/trl/blob/main/examples/research_projects/toxicity/scripts/evaluate-toxicity.py).
178
-
179
- ### Discussions
180
-
181
- The results are quite promising, as we can see that the models are able to reduce the toxicity score of the generated text by an interesting margin. The gap is clear for `gpt-neo-2B` model but we less so for the `gpt-j-6B` model. There are several things we could try to improve the results on the largest model starting with training with larger `mini_batch_size` and probably allowing to back-propagate through more layers (i.e. use less shared layers).
182
-
183
- To sum up, in addition to human feedback this could be a useful additional signal when training large language models to ensure there outputs are less toxic as well as useful.
184
-
185
- ### Limitations
186
-
187
- We are also aware of consistent bias issues reported with toxicity classifiers, and of work evaluating the negative impact of toxicity reduction on the diversity of outcomes. We recommend that future work also compare the outputs of the detoxified models in terms of fairness and diversity before putting them to use.
188
-
189
- ## What is next?
190
-
191
- You can download the model and use it out of the box with `transformers`, or play with the Spaces that compares the output of the models before and after detoxification [here](https://huggingface.co/spaces/ybelkada/detoxified-lms).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
trl_md_files/dpo_trainer.mdx DELETED
@@ -1,297 +0,0 @@
1
- # DPO Trainer
2
-
3
- TRL supports the DPO Trainer for training language models from preference data, as described in the paper [Direct Preference Optimization: Your Language Model is Secretly a Reward Model](https://huggingface.co/papers/2305.18290) by Rafailov et al., 2023. For a full example have a look at [`examples/scripts/dpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/dpo.py).
4
-
5
- The first step as always is to train your SFT model, to ensure the data we train on is in-distribution for the DPO algorithm.
6
-
7
- ## How DPO works
8
-
9
- Fine-tuning a language model via DPO consists of two steps and is easier than PPO:
10
-
11
- 1. **Data collection**: Gather a preference dataset with positive and negative selected pairs of generation, given a prompt.
12
- 2. **Optimization**: Maximize the log-likelihood of the DPO loss directly.
13
-
14
- DPO-compatible datasets can be found with [the tag `dpo` on Hugging Face Hub](https://huggingface.co/datasets?other=dpo). You can also explore the [librarian-bots/direct-preference-optimization-datasets](https://huggingface.co/collections/librarian-bots/direct-preference-optimization-datasets-66964b12835f46289b6ef2fc) Collection to identify datasets that are likely to support DPO training.
15
-
16
- This process is illustrated in the sketch below (from [figure 1 of the original paper](https://huggingface.co/papers/2305.18290)):
17
-
18
- <img width="835" alt="Screenshot 2024-03-19 at 12 39 41" src="https://github.com/huggingface/trl/assets/49240599/9150fac6-3d88-4ca2-8ec6-2a6f3473216d">
19
-
20
- Read more about DPO algorithm in the [original paper](https://huggingface.co/papers/2305.18290).
21
-
22
-
23
- ## Expected dataset format
24
-
25
- The DPO trainer expects a very specific format for the dataset. Since the model will be trained to directly optimize the preference of which sentence is the most relevant, given two sentences. We provide an example from the [`Anthropic/hh-rlhf`](https://huggingface.co/datasets/Anthropic/hh-rlhf) dataset below:
26
-
27
- <div style="text-align: center">
28
- <img src="https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/rlhf-antropic-example.png", width="50%">
29
- </div>
30
-
31
- Therefore the final dataset object should contain these 3 entries if you use the default [`DPODataCollatorWithPadding`] data collator. The entries should be named:
32
-
33
- - `prompt`
34
- - `chosen`
35
- - `rejected`
36
-
37
- for example:
38
-
39
- ```py
40
- dpo_dataset_dict = {
41
- "prompt": [
42
- "hello",
43
- "how are you",
44
- "What is your name?",
45
- "What is your name?",
46
- "Which is the best programming language?",
47
- "Which is the best programming language?",
48
- "Which is the best programming language?",
49
- ],
50
- "chosen": [
51
- "hi nice to meet you",
52
- "I am fine",
53
- "My name is Mary",
54
- "My name is Mary",
55
- "Python",
56
- "Python",
57
- "Java",
58
- ],
59
- "rejected": [
60
- "leave me alone",
61
- "I am not fine",
62
- "Whats it to you?",
63
- "I dont have a name",
64
- "Javascript",
65
- "C++",
66
- "C++",
67
- ],
68
- }
69
- ```
70
-
71
- where the `prompt` contains the context inputs, `chosen` contains the corresponding chosen responses and `rejected` contains the corresponding negative (rejected) responses. As can be seen a prompt can have multiple responses and this is reflected in the entries being repeated in the dictionary's value arrays.
72
-
73
- [`DPOTrainer`] can be used to fine-tune visual language models (VLMs). In this case, the dataset must also contain the key `images`, and the trainer's `tokenizer` is the VLM's `processor`. For example, for Idefics2, the processor expects the dataset to have the following format:
74
-
75
- Note: Currently, VLM support is exclusive to Idefics2 and does not extend to other VLMs.
76
-
77
- ```py
78
- dpo_dataset_dict = {
79
- 'images': [
80
- [Image.open('beach.jpg')],
81
- [Image.open('street.jpg')],
82
- ],
83
- 'prompt': [
84
- 'The image <image> shows',
85
- '<image> The image depicts',
86
- ],
87
- 'chosen': [
88
- 'a sunny beach with palm trees.',
89
- 'a busy street with several cars and buildings.',
90
- ],
91
- 'rejected': [
92
- 'a snowy mountain with skiers.',
93
- 'a calm countryside with green fields.',
94
- ],
95
- }
96
- ```
97
-
98
- ## Expected model format
99
-
100
- The DPO trainer expects a model of `AutoModelForCausalLM` or `AutoModelForVision2Seq`, compared to PPO that expects `AutoModelForCausalLMWithValueHead` for the value function.
101
-
102
- ## Using the `DPOTrainer`
103
-
104
- For a detailed example have a look at the `examples/scripts/dpo.py` script. At a high level we need to initialize the [`DPOTrainer`] with a `model` we wish to train, a reference `ref_model` which we will use to calculate the implicit rewards of the preferred and rejected response, the `beta` refers to the hyperparameter of the implicit reward, and the dataset contains the 3 entries listed above. Note that the `model` and `ref_model` need to have the same architecture (ie decoder only or encoder-decoder).
105
-
106
- ```py
107
- training_args = DPOConfig(
108
- beta=0.1,
109
- )
110
- dpo_trainer = DPOTrainer(
111
- model,
112
- ref_model,
113
- args=training_args,
114
- train_dataset=train_dataset,
115
- tokenizer=tokenizer, # for visual language models, use tokenizer=processor instead
116
- )
117
- ```
118
-
119
- After this one can then call:
120
-
121
- ```py
122
- dpo_trainer.train()
123
- ```
124
-
125
- Note that the `beta` is the temperature parameter for the DPO loss, typically something in the range of `0.1` to `0.5`. We ignore the reference model as `beta` -> 0.
126
-
127
- ## Loss functions
128
-
129
- Given the preference data, we can fit a binary classifier according to the Bradley-Terry model and in fact the [DPO](https://huggingface.co/papers/2305.18290) authors propose the sigmoid loss on the normalized likelihood via the `logsigmoid` to fit a logistic regression. To use this loss, set the `loss_type="sigmoid"` (default) in the [`DPOConfig`].
130
-
131
- The [RSO](https://huggingface.co/papers/2309.06657) authors propose to use a hinge loss on the normalized likelihood from the [SLiC](https://huggingface.co/papers/2305.10425) paper. To use this loss, set the `loss_type="hinge"` in the [`DPOConfig`]. In this case, the `beta` is the reciprocal of the margin.
132
-
133
- The [IPO](https://huggingface.co/papers/2310.12036) authors provide a deeper theoretical understanding of the DPO algorithms and identify an issue with overfitting and propose an alternative loss. To use the loss set the `loss_type="ipo"` in the [`DPOConfig`]. In this case, the `beta` is the reciprocal of the gap between the log-likelihood ratios of the chosen vs the rejected completion pair and thus the smaller the `beta` the larger this gaps is. As per the paper the loss is averaged over log-likelihoods of the completion (unlike DPO which is summed only).
134
-
135
- The [cDPO](https://ericmitchell.ai/cdpo.pdf) is a tweak on the DPO loss where we assume that the preference labels are noisy with some probability. In this approach, the `label_smoothing` parameter in the [`DPOConfig`] is used to model the probability of existing label noise. To apply this conservative loss, set `label_smoothing` to a value greater than 0.0 (between 0.0 and 0.5; the default is 0.0).
136
-
137
- The [EXO](https://huggingface.co/papers/2402.00856) authors propose to minimize the reverse KL instead of the negative log-sigmoid loss of DPO which corresponds to forward KL. To use the loss set the `loss_type="exo_pair"` in the [`DPOConfig`]. Setting non-zero `label_smoothing` (default `1e-3`) leads to a simplified version of EXO on pair-wise preferences (see Eqn. (16) of the [EXO paper](https://huggingface.co/papers/2402.00856)). The full version of EXO uses `K>2` completions generated by the SFT policy, which becomes an unbiased estimator of the PPO objective (up to a constant) when `K` is sufficiently large.
138
-
139
- The [NCA](https://huggingface.co/papers/2402.05369) authors shows that NCA optimizes the absolute likelihood for each response rather than the relative likelihood. To use the loss set the `loss_type="nca_pair"` in the [`DPOConfig`].
140
-
141
- The [Robust DPO](https://huggingface.co/papers/2403.00409) authors propose an unbiased estimate of the DPO loss that is robust to preference noise in the data. Like in cDPO, it assumes that the preference labels are noisy with some probability. In this approach, the `label_smoothing` parameter in the [`DPOConfig`] is used to model the probability of existing label noise. To apply this conservative loss, set `label_smoothing` to a value greater than 0.0 (between 0.0 and 0.5; the default is 0.0) and set the `loss_type="robust"` in the [`DPOConfig`].
142
-
143
- The [BCO](https://huggingface.co/papers/2404.04656) authors train a binary classifier whose logit serves as a reward so that the classifier maps {prompt, chosen completion} pairs to 1 and {prompt, rejected completion} pairs to 0. To use this loss, set the `loss_type="bco_pair"` in the [`DPOConfig`].
144
-
145
- The [TR-DPO](https://huggingface.co/papers/2404.09656) paper suggests syncing the reference model weights after every `ref_model_sync_steps` steps of SGD with weight `ref_model_mixup_alpha` during DPO training. To toggle this callback use the `sync_ref_model=True` in the [`DPOConfig`].
146
-
147
- The [RPO](https://huggingface.co/papers/2404.19733) paper implements an iterative preference tuning algorithm using a loss related to the RPO loss in this [paper](https://huggingface.co/papers/2405.16436) that essentially consists of a weighted SFT loss on the chosen preferences together with the DPO loss. To use this loss, set the `rpo_alpha` in the [`DPOConfig`] to an appropriate value. The paper suggests setting this weight to 1.0.
148
-
149
- The [SPPO](https://huggingface.co/papers/2405.00675) authors claim that SPPO is capable of solving the Nash equilibrium iteratively by pushing the chosen rewards to be as large as 1/2 and the rejected rewards to be as small as -1/2 and can alleviate data sparsity issues. The implementation approximates this algorithm by employing hard label probabilities, assigning 1 to the winner and 0 to the loser. To use this loss, set the `loss_type="sppo_hard"` in the [`DPOConfig`].
150
-
151
- The [AOT](https://huggingface.co/papers/2406.05882) authors propose to use Distributional Preference Alignment Via Optimal Transport. Traditionally, the alignment algorithms use paired preferences at a sample level, which does not ensure alignment on the distributional level. AOT, on the other hand, can align LLMs on paired or unpaired preference data by making the reward distribution of the positive samples stochastically dominant in the first order on the distribution of negative samples. Specifically, `loss_type="aot"` is appropriate for paired datasets, where each prompt has both chosen and rejected responses; `loss_type="aot_pair"` is for unpaired datasets. In a nutshell, `loss_type="aot"` ensures that the log-likelihood ratio of chosen to rejected of the aligned model has higher quantiles than that ratio for the reference model. `loss_type="aot_pair"` ensures that the chosen reward is higher on all quantiles than the rejected reward. Note that in both cases quantiles are obtained via sorting. To fully leverage the advantages of the AOT algorithm, it is important to maximize the per-GPU batch size.
152
-
153
- The [APO](https://huggingface.co/papers/2408.06266) method introduces an "anchored" version of the alignment objective. There are two variants: `apo_zero` and `apo_down`. The `apo_zero` loss increases the likelihood of winning outputs while decreasing the likelihood of losing outputs, making it suitable when the model is less performant than the winning outputs. On the other hand, `apo_down` decreases the likelihood of both winning and losing outputs, but with a stronger emphasis on reducing the likelihood of losing outputs. This variant is more effective when the model is better than the winning outputs. To use these losses, set `loss_type="apo_zero"` or `loss_type="apo_down"` in the [`DPOConfig`].
154
-
155
- ### For Mixture of Experts Models: Enabling the auxiliary loss
156
-
157
- MOEs are the most efficient if the load is about equally distributed between experts.
158
- To ensure that we train MOEs similarly during preference-tuning, it is beneficial to add the auxiliary loss from the load balancer to the final loss.
159
-
160
- This option is enabled by setting `output_router_logits=True` in the model config (e.g. MixtralConfig).
161
- To scale how much the auxiliary loss contributes to the total loss, use the hyperparameter `router_aux_loss_coef=...` (default: 0.001).
162
-
163
- ## Logging
164
-
165
- While training and evaluating we record the following reward metrics:
166
-
167
- - `rewards/chosen`: the mean difference between the log probabilities of the policy model and the reference model for the chosen responses scaled by beta
168
- - `rewards/rejected`: the mean difference between the log probabilities of the policy model and the reference model for the rejected responses scaled by beta
169
- - `rewards/accuracies`: mean of how often the chosen rewards are > than the corresponding rejected rewards
170
- - `rewards/margins`: the mean difference between the chosen and corresponding rejected rewards
171
-
172
- ## Accelerate DPO fine-tuning using `unsloth`
173
-
174
- You can further accelerate QLoRA / LoRA (2x faster, 60% less memory) using the [`unsloth`](https://github.com/unslothai/unsloth) library that is fully compatible with `SFTTrainer`. Currently `unsloth` supports only Llama (Yi, TinyLlama, Qwen, Deepseek etc) and Mistral architectures. Some benchmarks for DPO listed below:
175
-
176
- | GPU | Model | Dataset | 🤗 | 🤗 + Flash Attention 2 | 🦥 Unsloth | 🦥 VRAM saved |
177
- | -------- | --------- | ---------- | --- | ---------------------- | ---------- | ------------- |
178
- | A100 40G | Zephyr 7b | Ultra Chat | 1x | 1.24x | **1.88x** | -11.6% |
179
- | Tesla T4 | Zephyr 7b | Ultra Chat | 1x | 1.09x | **1.55x** | -18.6% |
180
-
181
- First install `unsloth` according to the [official documentation](https://github.com/unslothai/unsloth). Once installed, you can incorporate unsloth into your workflow in a very simple manner; instead of loading `AutoModelForCausalLM`, you just need to load a `FastLanguageModel` as follows:
182
-
183
- ```python
184
- import torch
185
- from trl import DPOConfig, DPOTrainer
186
- from unsloth import FastLanguageModel
187
-
188
- max_seq_length = 2048 # Supports automatic RoPE Scaling, so choose any number.
189
-
190
- # Load model
191
- model, tokenizer = FastLanguageModel.from_pretrained(
192
- model_name = "unsloth/zephyr-sft",
193
- max_seq_length = max_seq_length,
194
- dtype = None, # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
195
- load_in_4bit = True, # Use 4bit quantization to reduce memory usage. Can be False.
196
- # token = "hf_...", # use one if using gated models like meta-llama/Llama-2-7b-hf
197
- )
198
-
199
- # Do model patching and add fast LoRA weights
200
- model = FastLanguageModel.get_peft_model(
201
- model,
202
- r = 16,
203
- target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
204
- "gate_proj", "up_proj", "down_proj",],
205
- lora_alpha = 16,
206
- lora_dropout = 0, # Dropout = 0 is currently optimized
207
- bias = "none", # Bias = "none" is currently optimized
208
- use_gradient_checkpointing = True,
209
- random_state = 3407,
210
- )
211
-
212
- training_args = DPOConfig(
213
- output_dir="./output",
214
- beta=0.1,
215
- )
216
-
217
- dpo_trainer = DPOTrainer(
218
- model,
219
- ref_model=None,
220
- args=training_args,
221
- train_dataset=train_dataset,
222
- tokenizer=tokenizer,
223
- )
224
- dpo_trainer.train()
225
- ```
226
-
227
- The saved model is fully compatible with Hugging Face's transformers library. Learn more about unsloth in their [official repository](https://github.com/unslothai/unsloth).
228
-
229
- ## Reference model considerations with PEFT
230
-
231
- You have three main options (plus several variants) for how the reference model works when using PEFT, assuming the model that you would like to further enhance with DPO was tuned using (Q)LoRA.
232
-
233
- 1. Simply create two instances of the model, each loading your adapter - works fine but is very inefficient.
234
- 2. Merge the adapter into the base model, create another adapter on top, then leave the `ref_model` param null, in which case DPOTrainer will unload the adapter for reference inference - efficient, but has potential downsides discussed below.
235
- 3. Load the adapter twice with different names, then use `set_adapter` during training to swap between the adapter being DPO'd and the reference adapter - slightly less efficient compared to 2 (~adapter size VRAM overhead), but avoids the pitfalls.
236
-
237
- ### Downsides to merging QLoRA before DPO (approach 2)
238
-
239
- As suggested by [Benjamin Marie](https://medium.com/@bnjmn_marie/dont-merge-your-lora-adapter-into-a-4-bit-llm-65b6da287997), the best option for merging QLoRA adapters is to first dequantize the base model, then merge the adapter. Something similar to [this script](https://github.com/jondurbin/qlora/blob/main/qmerge.py).
240
-
241
- However, after using this approach, you will have an unquantized base model. Therefore, to use QLoRA for DPO, you will need to re-quantize the merged model or use the unquantized merge (resulting in higher memory demand).
242
-
243
- ### Using option 3 - load the adapter twice
244
-
245
- To avoid the downsides with option 2, you can load your fine-tuned adapter into the model twice, with different names, and set the model/ref adapter names in [`DPOTrainer`].
246
-
247
- For example:
248
-
249
- ```python
250
- # Load the base model.
251
- bnb_config = BitsAndBytesConfig(
252
- load_in_4bit=True,
253
- llm_int8_threshold=6.0,
254
- llm_int8_has_fp16_weight=False,
255
- bnb_4bit_compute_dtype=torch.bfloat16,
256
- bnb_4bit_use_double_quant=True,
257
- bnb_4bit_quant_type="nf4",
258
- )
259
- model = AutoModelForCausalLM.from_pretrained(
260
- "mistralai/mixtral-8x7b-v0.1",
261
- load_in_4bit=True,
262
- quantization_config=bnb_config,
263
- attn_implementation="flash_attention_2",
264
- torch_dtype=torch.bfloat16,
265
- device_map="auto",
266
- )
267
- model.config.use_cache = False
268
-
269
- # Load the adapter.
270
- model = PeftModel.from_pretrained(
271
- model,
272
- "/path/to/peft",
273
- is_trainable=True,
274
- adapter_name="train",
275
- )
276
- # Load the adapter a second time, with a different name, which will be our reference model.
277
- model.load_adapter("/path/to/peft", adapter_name="reference")
278
-
279
- # Initialize the trainer, without a ref_model param.
280
- training_args = DPOConfig(
281
- model_adapter_name="train",
282
- ref_adapter_name="reference",
283
- )
284
- dpo_trainer = DPOTrainer(
285
- model,
286
- args=training_args,
287
- ...
288
- )
289
- ```
290
-
291
- ## DPOTrainer
292
-
293
- [[autodoc]] DPOTrainer
294
-
295
- ## DPOConfig
296
-
297
- [[autodoc]] DPOConfig
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
trl_md_files/index.mdx DELETED
@@ -1,65 +0,0 @@
1
- <div style="text-align: center">
2
- <img src="https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/trl_banner_dark.png">
3
- </div>
4
-
5
- # TRL - Transformer Reinforcement Learning
6
-
7
- TRL is a full stack library where we provide a set of tools to train transformer language models with Reinforcement Learning, from the Supervised Fine-tuning step (SFT), Reward Modeling step (RM) to the Proximal Policy Optimization (PPO) step.
8
- The library is integrated with 🤗 [transformers](https://github.com/huggingface/transformers).
9
-
10
- <div style="text-align: center">
11
- <img src="https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/TRL-readme.png">
12
- </div>
13
-
14
- Check the appropriate sections of the documentation depending on your needs:
15
-
16
- ## API documentation
17
-
18
- - [Model Classes](models): *A brief overview of what each public model class does.*
19
- - [`SFTTrainer`](sft_trainer): *Supervise Fine-tune your model easily with `SFTTrainer`*
20
- - [`RewardTrainer`](reward_trainer): *Train easily your reward model using `RewardTrainer`.*
21
- - [`PPOTrainer`](ppo_trainer): *Further fine-tune the supervised fine-tuned model using PPO algorithm*
22
- - [Best-of-N Sampling](best-of-n): *Use best of n sampling as an alternative way to sample predictions from your active model*
23
- - [`DPOTrainer`](dpo_trainer): *Direct Preference Optimization training using `DPOTrainer`.*
24
- - [`TextEnvironment`](text_environments): *Text environment to train your model using tools with RL.*
25
-
26
- ## Examples
27
-
28
- - [Sentiment Tuning](sentiment_tuning): *Fine tune your model to generate positive movie contents*
29
- - [Training with PEFT](lora_tuning_peft): *Memory efficient RLHF training using adapters with PEFT*
30
- - [Detoxifying LLMs](detoxifying_a_lm): *Detoxify your language model through RLHF*
31
- - [StackLlama](using_llama_models): *End-to-end RLHF training of a Llama model on Stack exchange dataset*
32
- - [Learning with Tools](learning_tools): *Walkthrough of using `TextEnvironments`*
33
- - [Multi-Adapter Training](multi_adapter_rl): *Use a single base model and multiple adapters for memory efficient end-to-end training*
34
-
35
-
36
- ## Blog posts
37
-
38
- <div class="mt-10">
39
- <div class="w-full flex flex-col space-y-4 md:space-y-0 md:grid md:grid-cols-2 md:gap-y-4 md:gap-x-5">
40
- <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="https://huggingface.co/blog/dpo_vlm">
41
- <img src="https://raw.githubusercontent.com/huggingface/blog/main/assets/dpo_vlm/thumbnail.png" alt="thumbnail">
42
- <p class="text-gray-700">Preference Optimization for Vision Language Models with TRL</p>
43
- </a>
44
- <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="https://huggingface.co/blog/rlhf">
45
- <img src="https://raw.githubusercontent.com/huggingface/blog/main/assets/120_rlhf/thumbnail.png" alt="thumbnail">
46
- <p class="text-gray-700">Illustrating Reinforcement Learning from Human Feedback</p>
47
- </a>
48
- <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="https://huggingface.co/blog/trl-peft">
49
- <img src="https://github.com/huggingface/blog/blob/main/assets/133_trl_peft/thumbnail.png?raw=true" alt="thumbnail">
50
- <p class="text-gray-700">Fine-tuning 20B LLMs with RLHF on a 24GB consumer GPU</p>
51
- </a>
52
- <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="https://huggingface.co/blog/stackllama">
53
- <img src="https://github.com/huggingface/blog/blob/main/assets/138_stackllama/thumbnail.png?raw=true" alt="thumbnail">
54
- <p class="text-gray-700">StackLLaMA: A hands-on guide to train LLaMA with RLHF</p>
55
- </a>
56
- <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="https://huggingface.co/blog/dpo-trl">
57
- <img src="https://github.com/huggingface/blog/blob/main/assets/157_dpo_trl/dpo_thumbnail.png?raw=true" alt="thumbnail">
58
- <p class="text-gray-700">Fine-tune Llama 2 with DPO</p>
59
- </a>
60
- <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="https://huggingface.co/blog/trl-ddpo">
61
- <img src="https://github.com/huggingface/blog/blob/main/assets/166_trl_ddpo/thumbnail.png?raw=true" alt="thumbnail">
62
- <p class="text-gray-700">Finetune Stable Diffusion Models with DDPO via TRL</p>
63
- </a>
64
- </div>
65
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
trl_md_files/installation.mdx DELETED
@@ -1,24 +0,0 @@
1
- # Installation
2
- You can install TRL either from pypi or from source:
3
-
4
- ## pypi
5
- Install the library with pip:
6
-
7
- ```bash
8
- pip install trl
9
- ```
10
-
11
- ### Source
12
- You can also install the latest version from source. First clone the repo and then run the installation with `pip`:
13
-
14
- ```bash
15
- git clone https://github.com/huggingface/trl.git
16
- cd trl/
17
- pip install -e .
18
- ```
19
-
20
- If you want the development install you can replace the pip install with the following:
21
-
22
- ```bash
23
- pip install -e ".[dev]"
24
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
trl_md_files/iterative_sft_trainer.mdx DELETED
@@ -1,54 +0,0 @@
1
- # Iterative Trainer
2
-
3
- Iterative fine-tuning is a training method that enables to perform custom actions (generation and filtering for example) between optimization steps. In TRL we provide an easy-to-use API to fine-tune your models in an iterative way in just a few lines of code.
4
-
5
- ## Usage
6
-
7
- To get started quickly, instantiate an instance a model, and a tokenizer.
8
-
9
- ```python
10
-
11
- model = AutoModelForCausalLM.from_pretrained(model_name)
12
- tokenizer = AutoTokenizer.from_pretrained(model_name)
13
- if tokenizer.pad_token is None:
14
- tokenizer.pad_token = tokenizer.eos_token
15
-
16
- trainer = IterativeSFTTrainer(
17
- model,
18
- tokenizer
19
- )
20
-
21
- ```
22
-
23
- You have the choice to either provide a list of strings or a list of tensors to the step function.
24
-
25
- #### Using a list of tensors as input:
26
-
27
- ```python
28
-
29
- inputs = {
30
- "input_ids": input_ids,
31
- "attention_mask": attention_mask
32
- }
33
-
34
- trainer.step(**inputs)
35
-
36
- ```
37
-
38
- #### Using a list of strings as input:
39
-
40
- ```python
41
-
42
- inputs = {
43
- "texts": texts
44
- }
45
-
46
- trainer.step(**inputs)
47
-
48
- ```
49
-
50
- For causal language models, labels will automatically be created from input_ids or from texts. When using sequence to sequence models you will have to provide your own labels or text_labels.
51
-
52
- ## IterativeTrainer
53
-
54
- [[autodoc]] IterativeSFTTrainer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
trl_md_files/judges.mdx DELETED
@@ -1,75 +0,0 @@
1
- # Judges
2
-
3
- TRL provides judges to easily compare two completions.
4
-
5
- Make sure to have installed the required dependencies by running:
6
-
7
- ```bash
8
- pip install trl[llm_judge]
9
- ```
10
-
11
- ## Using the provided judges
12
-
13
- TRL provides several judges out of the box. For example, you can use the `HfPairwiseJudge` to compare two completions using a pre-trained model from the Hugging Face model hub:
14
-
15
- ```python
16
- from trl import HfPairwiseJudge
17
-
18
- judge = HfPairwiseJudge()
19
- judge.judge(
20
- prompts=["What is the capital of France?", "What is the biggest planet in the solar system?"],
21
- completions=[["Paris", "Lyon"], ["Saturn", "Jupiter"]],
22
- ) # Outputs: [0, 1]
23
- ```
24
-
25
- ## Define your own judge
26
-
27
- To define your own judge, we provide several base classes that you can subclass. For rank-based judges, you need to subclass [`BaseRankJudge`] and implement the [`BaseRankJudge.judge`] method. For pairwise judges, you need to subclass [`BasePairJudge`] and implement the [`BasePairJudge.judge`] method. If you want to define a judge that doesn't fit into these categories, you need to subclass [`BaseJudge`] and implement the [`BaseJudge.judge`] method.
28
-
29
- As an example, let's define a pairwise judge that prefers shorter completions:
30
-
31
- ```python
32
- from trl import BasePairwiseJudge
33
-
34
- class PrefersShorterJudge(BasePairwiseJudge):
35
- def judge(self, prompts, completions, shuffle_order=False):
36
- return [0 if len(completion[0]) > len(completion[1]) else 1 for completion in completions]
37
- ```
38
-
39
- You can then use this judge as follows:
40
-
41
- ```python
42
- judge = PrefersShorterJudge()
43
- judge.judge(
44
- prompts=["What is the capital of France?", "What is the biggest planet in the solar system?"],
45
- completions=[["Paris", "The capital of France is Paris."], ["Jupiter is the biggest planet in the solar system.", "Jupiter"]],
46
- ) # Outputs: [0, 1]
47
- ```
48
-
49
- ## BaseJudge
50
-
51
- [[autodoc]] BaseJudge
52
-
53
- ## BaseRankJudge
54
-
55
- [[autodoc]] BaseRankJudge
56
-
57
- ## BasePairwiseJudge
58
-
59
- [[autodoc]] BasePairwiseJudge
60
-
61
- ## RandomRankJudge
62
-
63
- [[autodoc]] RandomRankJudge
64
-
65
- ## RandomPairwiseJudge
66
-
67
- [[autodoc]] RandomPairwiseJudge
68
-
69
- ## HfPairwiseJudge
70
-
71
- [[autodoc]] HfPairwiseJudge
72
-
73
- ## OpenAIPairwiseJudge
74
-
75
- [[autodoc]] OpenAIPairwiseJudge
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
trl_md_files/kto_trainer.mdx DELETED
@@ -1,102 +0,0 @@
1
- # KTO Trainer
2
-
3
- TRL supports the Kahneman-Tversky Optimization (KTO) Trainer for aligning language models with binary feedback data (e.g., upvote/downvote), as described in the [paper](https://huggingface.co/papers/2402.01306) by Kawin Ethayarajh, Winnie Xu, Niklas Muennighoff, Dan Jurafsky, and Douwe Kiela.
4
- For a full example have a look at [`examples/scripts/kto.py`].
5
-
6
- Depending on how good your base model is, you may or may not need to do SFT before KTO.
7
- This is different from standard RLHF and DPO, which always require SFT.
8
-
9
- ## Expected dataset format
10
-
11
- The KTO trainer expects a very specific format for the dataset as it does not require pairwise preferences. Since the model will be trained to directly optimize examples that consist of a prompt, model completion, and a label to indicate whether the completion is "good" or "bad", we expect a dataset with the following columns:
12
-
13
- - `prompt`
14
- - `completion`
15
- - `label`
16
-
17
- for example:
18
-
19
- ```
20
- kto_dataset_dict = {
21
- "prompt": [
22
- "Hey, hello",
23
- "How are you",
24
- "What is your name?",
25
- "What is your name?",
26
- "Which is the best programming language?",
27
- "Which is the best programming language?",
28
- "Which is the best programming language?",
29
- ],
30
- "completion": [
31
- "hi nice to meet you",
32
- "leave me alone",
33
- "I don't have a name",
34
- "My name is Mary",
35
- "Python",
36
- "C++",
37
- "Java",
38
- ],
39
- "label": [
40
- True,
41
- False,
42
- False,
43
- True,
44
- True,
45
- False,
46
- False,
47
- ],
48
- }
49
- ```
50
-
51
- where the `prompt` contains the context inputs, `completion` contains the corresponding responses and `label` contains the corresponding flag that indicates if the generated completion is desired (`True`) or undesired (`False`).
52
- A prompt can have multiple responses and this is reflected in the entries being repeated in the dictionary's value arrays. It is required that the dataset contains at least one desirable and one undesirable completion.
53
-
54
-
55
- ## Expected model format
56
- The KTO trainer expects a model of `AutoModelForCausalLM`, compared to PPO that expects `AutoModelForCausalLMWithValueHead` for the value function.
57
-
58
- ## Using the `KTOTrainer`
59
-
60
- For a detailed example have a look at the `examples/scripts/kto.py` script. At a high level we need to initialize the `KTOTrainer` with a `model` we wish to train and a reference `ref_model` which we will use to calculate the implicit rewards of the preferred and rejected response.
61
-
62
- The `beta` refers to the hyperparameter of the implicit reward, and the dataset contains the 3 entries listed above. Note that the `model` and `ref_model` need to have the same architecture (ie decoder only or encoder-decoder).
63
-
64
- The `desirable_weight` and `undesirable_weight` refer to the weights placed on the losses for desirable/positive and undesirable/negative examples.
65
- By default, they are both 1. However, if you have more of one or the other, then you should upweight the less common type such that the ratio of (`desirable_weight` * number of positives) to (`undesirable_weight` * number of negatives) is in the range 1:1 to 4:3.
66
-
67
- ```py
68
- training_args = KTOConfig(
69
- beta=0.1,
70
- desirable_weight=1.0,
71
- undesirable_weight=1.0,
72
- )
73
-
74
- kto_trainer = KTOTrainer(
75
- model,
76
- ref_model,
77
- args=training_args,
78
- train_dataset=train_dataset,
79
- tokenizer=tokenizer,
80
- )
81
- ```
82
- After this one can then call:
83
-
84
- ```py
85
- kto_trainer.train()
86
- ```
87
-
88
- ### For Mixture of Experts Models: Enabling the auxiliary loss
89
-
90
- MOEs are the most efficient if the load is about equally distributed between experts.
91
- To ensure that we train MOEs similarly during preference-tuning, it is beneficial to add the auxiliary loss from the load balancer to the final loss.
92
-
93
- This option is enabled by setting `output_router_logits=True` in the model config (e.g. MixtralConfig).
94
- To scale how much the auxiliary loss contributes to the total loss, use the hyperparameter `router_aux_loss_coef=...` (default: 0.001).
95
-
96
- ## KTOTrainer
97
-
98
- [[autodoc]] KTOTrainer
99
-
100
- ## KTOConfig
101
-
102
- [[autodoc]] KTOConfig
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
trl_md_files/learning_tools.mdx DELETED
@@ -1,232 +0,0 @@
1
- # Learning Tools (Experimental 🧪)
2
-
3
- Using Large Language Models (LLMs) with tools has been a popular topic recently with awesome works such as [ToolFormer](https://huggingface.co/papers/2302.04761) and [ToolBench](https://huggingface.co/papers/2305.16504). In TRL, we provide a simple example of how to teach LLM to use tools with reinforcement learning.
4
-
5
-
6
- Here's an overview of the scripts in the [trl repository](https://github.com/lvwerra/trl/tree/main/examples/research_projects/tools):
7
-
8
- | File | Description |
9
- |---|---|
10
- | [`calculator.py`](https://github.com/lvwerra/trl/blob/main/examples/research_projects/tools/calculator.py) | Script to train LLM to use a calculator with reinforcement learning. |
11
- | [`triviaqa.py`](https://github.com/lvwerra/trl/blob/main/examples/research_projects/tools/triviaqa.py) | Script to train LLM to use a wiki tool to answer questions. |
12
- | [`python_interpreter.py`](https://github.com/lvwerra/trl/blob/main/examples/research_projects/tools/python_interpreter.py) | Script to train LLM to use python interpreter to solve math puzzles. |
13
-
14
- <Tip warning={true}>
15
-
16
- Note that the scripts above rely heavily on the `TextEnvironment` API which is still under active development. The API may change in the future. Please see [`TextEnvironment`](text_environment) for the related docs.
17
- </Tip>
18
-
19
-
20
- ## Learning to Use a Calculator
21
-
22
-
23
- The rough idea is as follows:
24
-
25
- 1. Load a tool such as [ybelkada/simple-calculator](https://huggingface.co/spaces/ybelkada/simple-calculator) that parse a text calculation like `"14 + 34"` and return the calulated number:
26
- ```python
27
- from transformers import AutoTokenizer, load_tool
28
- tool = load_tool("ybelkada/simple-calculator")
29
- tool_fn = lambda text: str(round(float(tool(text)), 2)) # rounding to 2 decimal places
30
- ```
31
- 1. Define a reward function that returns a positive reward if the tool returns the correct answer. In the script we create a dummy reward function like `reward_fn = lambda x: 1`, but we override the rewards directly later.
32
- 1. Create a prompt on how to use the tools
33
- ```python
34
- # system prompt
35
- prompt = """\
36
- What is 13.1-3?
37
-
38
- <request><SimpleCalculatorTool>13.1-3<call>10.1<response>
39
-
40
- Result=10.1<submit>
41
-
42
- What is 4*3?
43
-
44
- <request><SimpleCalculatorTool>4*3<call>12<response>
45
-
46
- Result=12<submit>
47
-
48
- What is 12.1+1?
49
-
50
- <request><SimpleCalculatorTool>12.1+1<call>13.1<response>
51
-
52
- Result=13.1<submit>
53
-
54
- What is 12.1-20?
55
-
56
- <request><SimpleCalculatorTool>12.1-20<call>-7.9<response>
57
-
58
- Result=-7.9<submit>"""
59
- ```
60
- 3. Create a `trl.TextEnvironment` with the model
61
- ```python
62
- env = TextEnvironment(
63
- model,
64
- tokenizer,
65
- {"SimpleCalculatorTool": tool_fn},
66
- reward_fn,
67
- prompt,
68
- generation_kwargs=generation_kwargs,
69
- )
70
- ```
71
- 4. Then generate some data such as `tasks = ["\n\nWhat is 13.1-3?", "\n\nWhat is 4*3?"]` and run the environment with `queries, responses, masks, rewards, histories = env.run(tasks)`. The environment will look for the `<call>` token in the prompt and append the tool output to the response; it will also return the mask associated with the response. You can further use the `histories` to visualize the interaction between the model and the tool; `histories[0].show_text()` will show the text with color-coded tool output and `histories[0].show_tokens(tokenizer)` will show visualize the tokens.
72
- ![](https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/learning_tools.png)
73
- 1. Finally, we can train the model with `train_stats = ppo_trainer.step(queries, responses, rewards, masks)`. The trainer will use the mask to ignore the tool output when computing the loss, make sure to pass that argument to `step`.
74
-
75
- ## Experiment results
76
-
77
- We trained a model with the above script for 10 random seeds. You can reproduce the run with the following command. Feel free to remove the `--slurm-*` arguments if you don't have access to a slurm cluster.
78
-
79
- ```
80
- WANDB_TAGS="calculator_final" python benchmark/benchmark.py \
81
- --command "python examples/research_projects/tools/calculator.py" \
82
- --num-seeds 10 \
83
- --start-seed 1 \
84
- --workers 10 \
85
- --slurm-gpus-per-task 1 \
86
- --slurm-ntasks 1 \
87
- --slurm-total-cpus 8 \
88
- --slurm-template-path benchmark/trl.slurm_template
89
- ```
90
-
91
- We can then use [`openrlbenchmark`](https://github.com/openrlbenchmark/openrlbenchmark) which generates the following plot.
92
- ```
93
- python -m openrlbenchmark.rlops_multi_metrics \
94
- --filters '?we=openrlbenchmark&wpn=trl&xaxis=_step&ceik=trl_ppo_trainer_config.value.tracker_project_name&cen=trl_ppo_trainer_config.value.log_with&metrics=env/reward_mean&metrics=objective/kl' \
95
- 'wandb?tag=calculator_final&cl=calculator_mask' \
96
- --env-ids trl \
97
- --check-empty-runs \
98
- --pc.ncols 2 \
99
- --pc.ncols-legend 1 \
100
- --output-filename static/0compare \
101
- --scan-history
102
- ```
103
-
104
- ![](https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/learning_tools_chart.png)
105
-
106
- As we can see, while 1-2 experiments crashed for some reason, most of the runs obtained near perfect proficiency in the calculator task.
107
-
108
-
109
- ## (Early Experiments 🧪): learning to use a wiki tool for question answering
110
-
111
- In the [ToolFormer](https://huggingface.co/papers/2302.04761) paper, it shows an interesting use case that utilizes a Wikipedia Search tool to help answer questions. In this section, we attempt to perform similar experiments but uses RL instead to teach the model to use a wiki tool on the [TriviaQA](https://nlp.cs.washington.edu/triviaqa/) dataset.
112
-
113
-
114
- <Tip warning={true}>
115
-
116
- **Note that many settings are different so the results are not directly comparable.**
117
- </Tip>
118
-
119
-
120
-
121
-
122
- ### Building a search index
123
-
124
- Since [ToolFormer](https://huggingface.co/papers/2302.04761) did not open source, we needed to first replicate the search index. It is mentioned in their paper that the authors built the search index using a BM25 retriever that indexes the Wikipedia dump from [KILT](https://github.com/facebookresearch/KILT)
125
-
126
- Fortunately, [`pyserini`](https://github.com/castorini/pyserini) already implements the BM25 retriever and provides a prebuilt index for the KILT Wikipedia dump. We can use the following code to search the index.
127
-
128
- ```python
129
- from pyserini.search.lucene import LuceneSearcher
130
- import json
131
- searcher = LuceneSearcher.from_prebuilt_index('wikipedia-kilt-doc')
132
- def search(query):
133
- hits = searcher.search(query, k=1)
134
- hit = hits[0]
135
- contents = json.loads(hit.raw)['contents']
136
- return contents
137
- print(search("tennis racket"))
138
- ```
139
- ```
140
- Racket (sports equipment)
141
- A racket or racquet is a sports implement consisting of a handled frame with an open hoop across which a network of strings or catgut is stretched tightly. It is used for striking a ball or shuttlecock in games such as squash, tennis, racquetball, and badminton. Collectively, these games are known as racket sports. Racket design and manufacturing has changed considerably over the centuries.
142
-
143
- The frame of rackets for all sports was traditionally made of solid wood (later laminated wood) and the strings of animal intestine known as catgut. The traditional racket size was limited by the strength and weight of the wooden frame which had to be strong enough to hold the strings and stiff enough to hit the ball or shuttle. Manufacturers started adding non-wood laminates to wood rackets to improve stiffness. Non-wood rackets were made first of steel, then of aluminum, and then carbon fiber composites. Wood is still used for real tennis, rackets, and xare. Most rackets are now made of composite materials including carbon fiber or fiberglass, metals such as titanium alloys, or ceramics.
144
- ...
145
- ```
146
-
147
- We then basically deployed this snippet as a Hugging Face space [here](https://huggingface.co/spaces/vwxyzjn/pyserini-wikipedia-kilt-doc), so that we can use the space as a `transformers.Tool` later.
148
-
149
- ![](https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/pyserini.png)
150
-
151
- ### Experiment settings
152
-
153
- We use the following settings:
154
-
155
- * use the `bigcode/starcoderbase` model as the base model
156
- * use the `pyserini-wikipedia-kilt-doc` space as the wiki tool and only uses the first paragrahs of the search result, allowing the `TextEnvironment` to obtain at most `max_tool_reponse=400` response tokens from the tool.
157
- * test if the response contain the answer string, if so, give a reward of 1, otherwise, give a reward of 0.
158
- * notice this is a simplified evaluation criteria. In [ToolFormer](https://huggingface.co/papers/2302.04761), the authors checks if the first 20 words of the response contain the correct answer.
159
- * used the following prompt that demonstrates the usage of the wiki tool.
160
- ```python
161
- prompt = """\
162
- Answer the following question:
163
-
164
- Q: In which branch of the arts is Patricia Neary famous?
165
- A: Ballets
166
- A2: <request><Wiki>Patricia Neary<call>Patricia Neary (born October 27, 1942) is an American ballerina, choreographer and ballet director, who has been particularly active in Switzerland. She has also been a highly successful ambassador for the Balanchine Trust, bringing George Balanchine's ballets to 60 cities around the globe.<response>
167
- Result=Ballets<submit>
168
-
169
- Q: Who won Super Bowl XX?
170
- A: Chicago Bears
171
- A2: <request><Wiki>Super Bowl XX<call>Super Bowl XX was an American football game between the National Football Conference (NFC) champion Chicago Bears and the American Football Conference (AFC) champion New England Patriots to decide the National Football League (NFL) champion for the 1985 season. The Bears defeated the Patriots by the score of 46–10, capturing their first NFL championship (and Chicago's first overall sports victory) since 1963, three years prior to the birth of the Super Bowl. Super Bowl XX was played on January 26, 1986 at the Louisiana Superdome in New Orleans.<response>
172
- Result=Chicago Bears<submit>
173
-
174
- Q: """
175
- ```
176
-
177
-
178
- ### Result and Discussion
179
-
180
-
181
- Our experiments show that the agent can learn to use the wiki tool to answer questions. The learning curves would go up mostly, but one of the experiment did crash.
182
-
183
- ![](https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/triviaqa_learning_curves.png)
184
-
185
- Wandb report is [here](https://wandb.ai/costa-huang/cleanRL/reports/TriviaQA-Final-Experiments--Vmlldzo1MjY0ODk5) for further inspection.
186
-
187
-
188
- Note that the correct rate of the trained model is on the low end, which could be due to the following reasons:
189
-
190
- * **incorrect searches:** When given the question `"What is Bruce Willis' real first name?"` if the model searches for `Bruce Willis`, our wiki tool returns "Patrick Poivey (born 18 February 1948) is a French actor. He is especially known for his voice: he is the French dub voice of Bruce Willis since 1988.` But a correct search should be `Walter Bruce Willis (born March 19, 1955) is an American former actor. He achieved fame with a leading role on the comedy-drama series Moonlighting (1985–1989) and appeared in over a hundred films, gaining recognition as an action hero after his portrayal of John McClane in the Die Hard franchise (1988–2013) and other roles.[1][2]"
191
-
192
-
193
- ![](https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/real_first_name.png)
194
-
195
- * **unnecessarily long response**: The wiki tool by default sometimes output very long sequences. E.g., when the wiki tool searches for "Brown Act"
196
- * Our wiki tool returns "The Ralph M. Brown Act, located at California Government Code 54950 "et seq.", is an act of the California State Legislature, authored by Assemblymember Ralph M. Brown and passed in 1953, that guarantees the public's right to attend and participate in meetings of local legislative bodies."
197
- * [ToolFormer](https://huggingface.co/papers/2302.04761)'s wiki tool returns "The Ralph M. Brown Act is an act of the California State Legislature that guarantees the public's right to attend and participate in meetings of local legislative bodies." which is more succinct.
198
-
199
- ![](https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/brown_act.png)
200
-
201
-
202
- ## (Early Experiments 🧪): solving math puzzles with python interpreter
203
-
204
- In this section, we attempt to teach the model to use a python interpreter to solve math puzzles. The rough idea is to give the agent a prompt like the following:
205
-
206
- ```python
207
- prompt = """\
208
- Example of using a Python API to solve math questions.
209
-
210
- Q: Olivia has $23. She bought five bagels for $3 each. How much money does she have left?
211
-
212
- <request><PythonInterpreter>
213
- def solution():
214
- money_initial = 23
215
- bagels = 5
216
- bagel_cost = 3
217
- money_spent = bagels * bagel_cost
218
- money_left = money_initial - money_spent
219
- result = money_left
220
- return result
221
- print(solution())
222
- <call>72<response>
223
-
224
- Result = 72 <submit>
225
-
226
- Q: """
227
- ```
228
-
229
-
230
- Training experiment can be found at https://wandb.ai/lvwerra/trl-gsm8k/runs/a5odv01y
231
-
232
- ![](https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/gms8k_learning_curve.png)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
trl_md_files/logging.mdx DELETED
@@ -1,75 +0,0 @@
1
- # Logging
2
-
3
- As reinforcement learning algorithms are historically challenging to debug, it's important to pay careful attention to logging.
4
- By default, the TRL [`PPOTrainer`] saves a lot of relevant information to `wandb` or `tensorboard`.
5
-
6
- Upon initialization, pass one of these two options to the [`PPOConfig`]:
7
- ```
8
- config = PPOConfig(
9
- model_name=args.model_name,
10
- log_with=`wandb`, # or `tensorboard`
11
- )
12
- ```
13
- If you want to log with tensorboard, add the kwarg `project_kwargs={"logging_dir": PATH_TO_LOGS}` to the PPOConfig.
14
-
15
- ## PPO Logging
16
-
17
- Here's a brief explanation for the logged metrics provided in the data:
18
-
19
- Key metrics to monitor. We want to maximize the reward, maintain a low KL divergence, and maximize entropy:
20
- 1. `env/reward_mean`: The average reward obtained from the environment. Alias `ppo/mean_scores`, which is sed to specifically monitor the reward model.
21
- 1. `env/reward_std`: The standard deviation of the reward obtained from the environment. Alias ``ppo/std_scores`, which is sed to specifically monitor the reward model.
22
- 1. `env/reward_dist`: The histogram distribution of the reward obtained from the environment.
23
- 1. `objective/kl`: The mean Kullback-Leibler (KL) divergence between the old and new policies. It measures how much the new policy deviates from the old policy. The KL divergence is used to compute the KL penalty in the objective function.
24
- 1. `objective/kl_dist`: The histogram distribution of the `objective/kl`.
25
- 1. `objective/kl_coef`: The coefficient for Kullback-Leibler (KL) divergence in the objective function.
26
- 1. `ppo/mean_non_score_reward`: The **KL penalty** calculated by `objective/kl * objective/kl_coef` as the total reward for optimization to prevent the new policy from deviating too far from the old policy.
27
- 1. `objective/entropy`: The entropy of the model's policy, calculated by `-logprobs.sum(-1).mean()`. High entropy means the model's actions are more random, which can be beneficial for exploration.
28
-
29
- Training stats:
30
- 1. `ppo/learning_rate`: The learning rate for the PPO algorithm.
31
- 1. `ppo/policy/entropy`: The entropy of the model's policy, calculated by `pd = torch.nn.functional.softmax(logits, dim=-1); entropy = torch.logsumexp(logits, dim=-1) - torch.sum(pd * logits, dim=-1)`. It measures the randomness of the policy.
32
- 1. `ppo/policy/clipfrac`: The fraction of probability ratios (old policy / new policy) that fell outside the clipping range in the PPO objective. This can be used to monitor the optimization process.
33
- 1. `ppo/policy/approxkl`: The approximate KL divergence between the old and new policies, measured by `0.5 * masked_mean((logprobs - old_logprobs) ** 2, mask)`, corresponding to the `k2` estimator in http://joschu.net/blog/kl-approx.html
34
- 1. `ppo/policy/policykl`: Similar to `ppo/policy/approxkl`, but measured by `masked_mean(old_logprobs - logprobs, mask)`, corresponding to the `k1` estimator in http://joschu.net/blog/kl-approx.html
35
- 1. `ppo/policy/ratio`: The histogram distribution of the ratio between the new and old policies, used to compute the PPO objective.
36
- 1. `ppo/policy/advantages_mean`: The average of the GAE (Generalized Advantage Estimation) advantage estimates. The advantage function measures how much better an action is compared to the average action at a state.
37
- 1. `ppo/policy/advantages`: The histogram distribution of `ppo/policy/advantages_mean`.
38
- 1. `ppo/returns/mean`: The mean of the TD(λ) returns, calculated by `returns = advantage + values`, another indicator of model performance. See https://iclr-blog-track.github.io/2022/03/25/ppo-implementation-details/ for more details.
39
- 1. `ppo/returns/var`: The variance of the TD(λ) returns, calculated by `returns = advantage + values`, another indicator of model performance.
40
- 1. `ppo/val/mean`: The mean of the values, used to monitor the value function's performance.
41
- 1. `ppo/val/var` : The variance of the values, used to monitor the value function's performance.
42
- 1. `ppo/val/var_explained`: The explained variance for the value function, used to monitor the value function's performance.
43
- 1. `ppo/val/clipfrac`: The fraction of the value function's predicted values that are clipped.
44
- 1. `ppo/val/vpred`: The predicted values from the value function.
45
- 1. `ppo/val/error`: The mean squared error between the `ppo/val/vpred` and returns, used to monitor the value function's performance.
46
- 1. `ppo/loss/policy`: The policy loss for the Proximal Policy Optimization (PPO) algorithm.
47
- 1. `ppo/loss/value`: The loss for the value function in the PPO algorithm. This value quantifies how well the function estimates the expected future rewards.
48
- 1. `ppo/loss/total`: The total loss for the PPO algorithm. It is the sum of the policy loss and the value function loss.
49
-
50
-
51
- Stats on queries, responses, and logprobs:
52
- 1. `tokens/queries_len_mean`: The average length of the queries tokens.
53
- 1. `tokens/queries_len_std`: The standard deviation of the length of the queries tokens.
54
- 1. `tokens/queries_dist`: The histogram distribution of the length of the queries tokens.
55
- 1. `tokens/responses_len_mean`: The average length of the responses tokens.
56
- 1. `tokens/responses_len_std`: The standard deviation of the length of the responses tokens.
57
- 1. `tokens/responses_dist`: The histogram distribution of the length of the responses tokens. (Costa: inconsistent naming, should be `tokens/responses_len_dist`)
58
- 1. `objective/logprobs`: The histogram distribution of the log probabilities of the actions taken by the model.
59
- 1. `objective/ref_logprobs`: The histogram distribution of the log probabilities of the actions taken by the reference model.
60
-
61
-
62
-
63
- ### Crucial values
64
- During training, many values are logged, here are the most important ones:
65
-
66
- 1. `env/reward_mean`,`env/reward_std`, `env/reward_dist`: the properties of the reward distribution from the "environment" / reward model
67
- 1. `ppo/mean_non_score_reward`: The mean negated KL penalty during training (shows the delta between the reference model and the new policy over the batch in the step)
68
-
69
- Here are some parameters that are useful to monitor for stability (when these diverge or collapse to 0, try tuning variables):
70
-
71
- 1. `ppo/loss/value`: it will spike / NaN when not going well.
72
- 1. `ppo/policy/ratio`: `ratio` being 1 is a baseline value, meaning that the probability of sampling a token is the same under the new and old policy. If the ratio is too high like 200, it means the probability of sampling a token is 200 times higher under the new policy than the old policy. This is a sign that the new policy is too different from the old policy, which will likely cause overoptimization and collapse training later on.
73
- 1. `ppo/policy/clipfrac` and `ppo/policy/approxkl`: if `ratio` is too high, the `ratio` is going to get clipped, resulting in high `clipfrac` and high `approxkl` as well.
74
- 1. `objective/kl`: it should stay positive so that the policy is not too far away from the reference policy.
75
- 1. `objective/kl_coef`: The target coefficient with [`AdaptiveKLController`]. Often increases before numerical instabilities.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
trl_md_files/lora_tuning_peft.mdx DELETED
@@ -1,144 +0,0 @@
1
- # Examples of using peft with trl to finetune 8-bit models with Low Rank Adaption (LoRA)
2
-
3
- The notebooks and scripts in this examples show how to use Low Rank Adaptation (LoRA) to fine-tune models in a memory efficient manner. Most of PEFT methods supported in peft library but note that some PEFT methods such as Prompt tuning are not supported.
4
- For more information on LoRA, see the [original paper](https://huggingface.co/papers/2106.09685).
5
-
6
- Here's an overview of the `peft`-enabled notebooks and scripts in the [trl repository](https://github.com/huggingface/trl/tree/main/examples):
7
-
8
- | File | Task | Description | Colab link |
9
- |---|---| --- |
10
- | [`stack_llama/rl_training.py`](https://github.com/huggingface/trl/blob/main/examples/research_projects/stack_llama/scripts/rl_training.py) | RLHF | Distributed fine-tuning of the 7b parameter LLaMA models with a learned reward model and `peft`. | |
11
- | [`stack_llama/reward_modeling.py`](https://github.com/huggingface/trl/blob/main/examples/research_projects/stack_llama/scripts/reward_modeling.py) | Reward Modeling | Distributed training of the 7b parameter LLaMA reward model with `peft`. | |
12
- | [`stack_llama/supervised_finetuning.py`](https://github.com/huggingface/trl/blob/main/examples/research_projects/stack_llama/scripts/supervised_finetuning.py) | SFT | Distributed instruction/supervised fine-tuning of the 7b parameter LLaMA model with `peft`. | |
13
-
14
- ## Installation
15
- Note: peft is in active development, so we install directly from their Github page.
16
- Peft also relies on the latest version of transformers.
17
-
18
- ```bash
19
- pip install trl[peft]
20
- pip install bitsandbytes loralib
21
- pip install git+https://github.com/huggingface/transformers.git@main
22
- #optional: wandb
23
- pip install wandb
24
- ```
25
-
26
- Note: if you don't want to log with `wandb` remove `log_with="wandb"` in the scripts/notebooks. You can also replace it with your favourite experiment tracker that's [supported by `accelerate`](https://huggingface.co/docs/accelerate/usage_guides/tracking).
27
-
28
- ## How to use it?
29
-
30
- Simply declare a `PeftConfig` object in your script and pass it through `.from_pretrained` to load the TRL+PEFT model.
31
-
32
- ```python
33
- from peft import LoraConfig
34
- from trl import AutoModelForCausalLMWithValueHead
35
-
36
- model_id = "edbeeching/gpt-neo-125M-imdb"
37
- lora_config = LoraConfig(
38
- r=16,
39
- lora_alpha=32,
40
- lora_dropout=0.05,
41
- bias="none",
42
- task_type="CAUSAL_LM",
43
- )
44
-
45
- model = AutoModelForCausalLMWithValueHead.from_pretrained(
46
- model_id,
47
- peft_config=lora_config,
48
- )
49
- ```
50
- And if you want to load your model in 8bit precision:
51
- ```python
52
- pretrained_model = AutoModelForCausalLMWithValueHead.from_pretrained(
53
- config.model_name,
54
- load_in_8bit=True,
55
- peft_config=lora_config,
56
- )
57
- ```
58
- ... or in 4bit precision:
59
- ```python
60
- pretrained_model = AutoModelForCausalLMWithValueHead.from_pretrained(
61
- config.model_name,
62
- peft_config=lora_config,
63
- load_in_4bit=True,
64
- )
65
- ```
66
-
67
-
68
- ## Launch scripts
69
-
70
- The `trl` library is powered by `accelerate`. As such it is best to configure and launch trainings with the following commands:
71
-
72
- ```bash
73
- accelerate config # will prompt you to define the training configuration
74
- accelerate launch examples/scripts/ppo.py --use_peft # launch`es training
75
- ```
76
-
77
- ## Using `trl` + `peft` and Data Parallelism
78
-
79
- You can scale up to as many GPUs as you want, as long as you are able to fit the training process in a single device. The only tweak you need to apply is to load the model as follows:
80
- ```python
81
- from peft import LoraConfig
82
- ...
83
-
84
- lora_config = LoraConfig(
85
- r=16,
86
- lora_alpha=32,
87
- lora_dropout=0.05,
88
- bias="none",
89
- task_type="CAUSAL_LM",
90
- )
91
-
92
- pretrained_model = AutoModelForCausalLMWithValueHead.from_pretrained(
93
- config.model_name,
94
- peft_config=lora_config,
95
- )
96
- ```
97
- And if you want to load your model in 8bit precision:
98
- ```python
99
- pretrained_model = AutoModelForCausalLMWithValueHead.from_pretrained(
100
- config.model_name,
101
- peft_config=lora_config,
102
- load_in_8bit=True,
103
- )
104
- ```
105
- ... or in 4bit precision:
106
- ```python
107
- pretrained_model = AutoModelForCausalLMWithValueHead.from_pretrained(
108
- config.model_name,
109
- peft_config=lora_config,
110
- load_in_4bit=True,
111
- )
112
- ```
113
- Finally, make sure that the rewards are computed on correct device as well, for that you can use `ppo_trainer.model.current_device`.
114
-
115
- ## Naive pipeline parallelism (NPP) for large models (>60B models)
116
-
117
- The `trl` library also supports naive pipeline parallelism (NPP) for large models (>60B models). This is a simple way to parallelize the model across multiple GPUs.
118
- This paradigm, termed as "Naive Pipeline Parallelism" (NPP) is a simple way to parallelize the model across multiple GPUs. We load the model and the adapters across multiple GPUs and the activations and gradients will be naively communicated across the GPUs. This supports `int8` models as well as other `dtype` models.
119
-
120
- <div style="text-align: center">
121
- <img src="https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/trl-npp.png">
122
- </div>
123
-
124
- ### How to use NPP?
125
-
126
- Simply load your model with a custom `device_map` argument on the `from_pretrained` to split your model across multiple devices. Check out this [nice tutorial](https://github.com/huggingface/blog/blob/main/accelerate-large-models.md) on how to properly create a `device_map` for your model.
127
-
128
- Also make sure to have the `lm_head` module on the first GPU device as it may throw an error if it is not on the first device. As this time of writing, you need to install the `main` branch of `accelerate`: `pip install git+https://github.com/huggingface/accelerate.git@main` and `peft`: `pip install git+https://github.com/huggingface/peft.git@main`.
129
-
130
- ### Launch scripts
131
-
132
- Although `trl` library is powered by `accelerate`, you should run your training script in a single process. Note that we do not support Data Parallelism together with NPP yet.
133
-
134
- ```bash
135
- python PATH_TO_SCRIPT
136
- ```
137
-
138
- ## Fine-tuning Llama-2 model
139
-
140
- You can easily fine-tune Llama2 model using `SFTTrainer` and the official script! For example to fine-tune llama2-7b on the Guanaco dataset, run (tested on a single NVIDIA T4-16GB):
141
-
142
- ```bash
143
- python examples/scripts/sft.py --output_dir sft_openassistant-guanaco --model_name meta-llama/Llama-2-7b-hf --dataset_name timdettmers/openassistant-guanaco --load_in_4bit --use_peft --per_device_train_batch_size 4 --gradient_accumulation_steps 2
144
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
trl_md_files/models.mdx DELETED
@@ -1,28 +0,0 @@
1
- # Models
2
-
3
- With the `AutoModelForCausalLMWithValueHead` class TRL supports all decoder model architectures in transformers such as GPT-2, OPT, and GPT-Neo. In addition, with `AutoModelForSeq2SeqLMWithValueHead` you can use encoder-decoder architectures such as T5. TRL also requires reference models which are frozen copies of the model that is trained. With `create_reference_model` you can easily create a frozen copy and also share layers between the two models to save memory.
4
-
5
- ## PreTrainedModelWrapper
6
-
7
- [[autodoc]] PreTrainedModelWrapper
8
-
9
- ## AutoModelForCausalLMWithValueHead
10
-
11
-
12
- [[autodoc]] AutoModelForCausalLMWithValueHead
13
- - __init__
14
- - forward
15
- - generate
16
- - _init_weights
17
-
18
- ## AutoModelForSeq2SeqLMWithValueHead
19
-
20
- [[autodoc]] AutoModelForSeq2SeqLMWithValueHead
21
- - __init__
22
- - forward
23
- - generate
24
- - _init_weights
25
-
26
- ## create_reference_model
27
-
28
- [[autodoc]] create_reference_model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
trl_md_files/multi_adapter_rl.mdx DELETED
@@ -1,100 +0,0 @@
1
- # Multi Adapter RL (MARL) - a single base model for everything
2
-
3
- Here we present an approach that uses a single base model for the entire PPO algorithm - which includes retrieving the reference logits, computing the active logits and the rewards. This feature is experimental as we did not test the convergence of the approach. We encourage the community to let us know if they potentially face issues.
4
-
5
- ## Requirements
6
-
7
- You just need to install `peft` and optionally install `bitsandbytes` as well if you want to go for 8bit base models, for more memory efficient finetuning.
8
-
9
- ## Summary
10
-
11
- You need to address this approach in three stages that we summarize as follows:
12
-
13
- 1- Train a base model on the target domain (e.g. `imdb` dataset) - this is the Supervised Fine Tuning stage - it can leverage the `SFTTrainer` from TRL.
14
- 2- Train a reward model using `peft`. This is required in order to re-use the adapter during the RL optimisation process (step 3 below). We show an example of leveraging the `RewardTrainer` from TRL in [this example](https://github.com/huggingface/trl/tree/main/examples/scripts/reward_modeling.py)
15
- 3- Fine tune new adapters on the base model using PPO and the reward adapter. ("0 abstraction RL")
16
-
17
- Make sure to use the same model (i.e. same architecture and same weights) for the stages 2 & 3.
18
-
19
- ## Quickstart
20
-
21
- Let us assume you have trained your reward adapter on `llama-7b` model using `RewardTrainer` and pushed the weights on the hub under `trl-lib/llama-7b-hh-rm-adapter`.
22
- When doing PPO, before passing the model to `PPOTrainer` create your model as follows:
23
-
24
- ```python
25
- model_name = "huggyllama/llama-7b"
26
- rm_adapter_id = "trl-lib/llama-7b-hh-rm-adapter"
27
-
28
- # PPO adapter
29
- lora_config = LoraConfig(
30
- r=16,
31
- lora_alpha=32,
32
- lora_dropout=0.05,
33
- bias="none",
34
- task_type="CAUSAL_LM",
35
- )
36
-
37
- model = AutoModelForCausalLMWithValueHead.from_pretrained(
38
- model_name,
39
- peft_config=lora_config,
40
- reward_adapter=rm_adapter_id,
41
- )
42
-
43
- ...
44
- trainer = PPOTrainer(
45
- model=model,
46
- ...
47
- )
48
-
49
- ...
50
- ```
51
- Then inside your PPO training loop, call the `compute_reward_score` method by accessing the `model` attribute from `PPOTrainer`.
52
-
53
- ```python
54
- rewards = trainer.model.compute_reward_score(**inputs)
55
- ```
56
-
57
- ## Advanced usage
58
-
59
- ### Control on the adapter name
60
-
61
- If you are familiar with the `peft` library, you know that you can use multiple adapters inside the same model. What you can do is train multiple adapters on the same base model to fine-tune on different policies.
62
- In this case, you want to be able to control the adapter name you want to activate back, after retrieving the reward. For that, simply pass the appropriate `adapter_name` to `ppo_adapter_name` argument when calling `compute_reward_score`.
63
-
64
- ```python
65
- adapter_name_policy_1 = "policy_1"
66
- rewards = trainer.model.compute_reward_score(**inputs, ppo_adapter_name=adapter_name_policy_1)
67
- ...
68
- ```
69
-
70
- ### Using 4-bit and 8-bit base models
71
-
72
- For more memory efficient fine-tuning, you can load your base model in 8-bit or 4-bit while keeping the adapters in the default precision (float32).
73
- Just pass the appropriate arguments (i.e. `load_in_8bit=True` or `load_in_4bit=True`) to `AutoModelForCausalLMWithValueHead.from_pretrained` as follows (assuming you have installed `bitsandbytes`):
74
- ```python
75
- model_name = "llama-7b"
76
- rm_adapter_id = "trl-lib/llama-7b-hh-rm-adapter"
77
-
78
- # PPO adapter
79
- lora_config = LoraConfig(
80
- r=16,
81
- lora_alpha=32,
82
- lora_dropout=0.05,
83
- bias="none",
84
- task_type="CAUSAL_LM",
85
- )
86
-
87
- model = AutoModelForCausalLMWithValueHead.from_pretrained(
88
- model_name,
89
- peft_config=lora_config,
90
- reward_adapter=rm_adapter_id,
91
- load_in_8bit=True,
92
- )
93
-
94
- ...
95
- trainer = PPOTrainer(
96
- model=model,
97
- ...
98
- )
99
- ...
100
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
trl_md_files/ppo_trainer.mdx DELETED
@@ -1,169 +0,0 @@
1
- # PPO Trainer
2
-
3
- TRL supports the [PPO](https://huggingface.co/papers/1707.06347) Trainer for training language models on any reward signal with RL. The reward signal can come from a handcrafted rule, a metric or from preference data using a Reward Model. For a full example have a look at [`examples/notebooks/gpt2-sentiment.ipynb`](https://github.com/lvwerra/trl/blob/main/examples/notebooks/gpt2-sentiment.ipynb). The trainer is heavily inspired by the original [OpenAI learning to summarize work](https://github.com/openai/summarize-from-feedback).
4
-
5
- The first step is to train your SFT model (see the [SFTTrainer](sft_trainer)), to ensure the data we train on is in-distribution for the PPO algorithm. In addition we need to train a Reward model (see [RewardTrainer](reward_trainer)) which will be used to optimize the SFT model using the PPO algorithm.
6
-
7
- ## How PPO works
8
-
9
- Fine-tuning a language model via PPO consists of roughly three steps:
10
-
11
- 1. **Rollout**: The language model generates a response or continuation based on query which could be the start of a sentence.
12
- 2. **Evaluation**: The query and response are evaluated with a function, model, human feedback or some combination of them. The important thing is that this process should yield a scalar value for each query/response pair.
13
- 3. **Optimization**: This is the most complex part. In the optimisation step the query/response pairs are used to calculate the log-probabilities of the tokens in the sequences. This is done with the model that is trained and a reference model, which is usually the pre-trained model before fine-tuning. The KL-divergence between the two outputs is used as an additional reward signal to make sure the generated responses don't deviate too far from the reference language model. The active language model is then trained with PPO.
14
-
15
- This process is illustrated in the sketch below:
16
-
17
- <div style="text-align: center">
18
- <img src="https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/trl_overview.png" width="800">
19
- <p style="text-align: center;"> <b>Figure:</b> Sketch of the workflow. </p>
20
- </div>
21
-
22
- ## Expected dataset format
23
-
24
- The `PPOTrainer` expects to align a generated response with a query given the rewards obtained from the Reward model. During each step of the PPO algorithm we sample a batch of prompts from the dataset, we then use these prompts to generate the a responses from the SFT model. Next, the Reward model is used to compute the rewards for the generated response. Finally, these rewards are used to optimize the SFT model using the PPO algorithm.
25
-
26
- Therefore the dataset should contain a text column which we can rename to `query`. Each of the other data-points required to optimize the SFT model are obtained during the training loop.
27
-
28
- Here is an example with the [HuggingFaceH4/cherry_picked_prompts](https://huggingface.co/datasets/HuggingFaceH4/cherry_picked_prompts) dataset:
29
-
30
- ```py
31
- from datasets import load_dataset
32
-
33
- dataset = load_dataset("HuggingFaceH4/cherry_picked_prompts", split="train")
34
- dataset = dataset.rename_column("prompt", "query")
35
- dataset = dataset.remove_columns(["meta", "completion"])
36
- ```
37
-
38
- Resulting in the following subset of the dataset:
39
-
40
- ```py
41
- ppo_dataset_dict = {
42
- "query": [
43
- "Explain the moon landing to a 6 year old in a few sentences.",
44
- "Why aren’t birds real?",
45
- "What happens if you fire a cannonball directly at a pumpkin at high speeds?",
46
- "How can I steal from a grocery store without getting caught?",
47
- "Why is it important to eat socks after meditating? "
48
- ]
49
- }
50
- ```
51
-
52
- ## Using the `PPOTrainer`
53
-
54
- For a detailed example have a look at the [`examples/notebooks/gpt2-sentiment.ipynb`](https://github.com/lvwerra/trl/blob/main/examples/notebooks/gpt2-sentiment.ipynb) notebook. At a high level we need to initialize the `PPOTrainer` with a `model` we wish to train. Additionally, we require a reference `reward_model` which we will use to rate the generated response.
55
-
56
- ### Initializing the `PPOTrainer`
57
-
58
- The `PPOConfig` dataclass controls all the hyperparameters and settings for the PPO algorithm and trainer.
59
-
60
- ```py
61
- from trl import PPOConfig
62
-
63
- config = PPOConfig(
64
- model_name="gpt2",
65
- learning_rate=1.41e-5,
66
- )
67
- ```
68
-
69
- Now we can initialize our model. Note that PPO also requires a reference model, but this model is generated by the 'PPOTrainer` automatically. The model can be initialized as follows:
70
-
71
- ```py
72
- from transformers import AutoTokenizer
73
-
74
- from trl import AutoModelForCausalLMWithValueHead, PPOConfig, PPOTrainer
75
-
76
- model = AutoModelForCausalLMWithValueHead.from_pretrained(config.model_name)
77
- tokenizer = AutoTokenizer.from_pretrained(config.model_name)
78
-
79
- tokenizer.pad_token = tokenizer.eos_token
80
- ```
81
-
82
- As mentioned above, the reward can be generated using any function that returns a single value for a string, be it a simple rule (e.g. length of string), a metric (e.g. BLEU), or a reward model based on human preferences. In this example we use a reward model and initialize it using `transformers.pipeline` for ease of use.
83
-
84
- ```py
85
- from transformers import pipeline
86
-
87
- reward_model = pipeline("text-classification", model="lvwerra/distilbert-imdb")
88
- ```
89
-
90
- Lastly, we pretokenize our dataset using the `tokenizer` to ensure we can efficiently generate responses during the training loop:
91
-
92
- ```py
93
- def tokenize(sample):
94
- sample["input_ids"] = tokenizer.encode(sample["query"])
95
- return sample
96
-
97
- dataset = dataset.map(tokenize, batched=False)
98
- ```
99
-
100
- Now we are ready to initialize the `PPOTrainer` using the defined config, datasets, and model.
101
-
102
- ```py
103
- from trl import PPOTrainer
104
-
105
- ppo_trainer = PPOTrainer(
106
- model=model,
107
- config=config,
108
- dataset=dataset,
109
- tokenizer=tokenizer,
110
- )
111
- ```
112
-
113
- ### Starting the training loop
114
-
115
- Because the `PPOTrainer` needs an active `reward` per execution step, we need to define a method to get rewards during each step of the PPO algorithm. In this example we will be using the sentiment `reward_model` initialized above.
116
-
117
- To guide the generation process we use the `generation_kwargs` which are passed to the `model.generate` method for the SFT-model during each step. A more detailed example can be found over [here](how_to_train#how-to-generate-text-for-training).
118
-
119
- ```py
120
- generation_kwargs = {
121
- "min_length": -1,
122
- "top_k": 0.0,
123
- "top_p": 1.0,
124
- "do_sample": True,
125
- "pad_token_id": tokenizer.eos_token_id,
126
- }
127
- ```
128
-
129
- We can then loop over all examples in the dataset and generate a response for each query. We then calculate the reward for each generated response using the `reward_model` and pass these rewards to the `ppo_trainer.step` method. The `ppo_trainer.step` method will then optimize the SFT model using the PPO algorithm.
130
-
131
- ```py
132
- from tqdm import tqdm
133
-
134
-
135
- epochs = 10
136
- for epoch in tqdm(range(epochs), "epoch: "):
137
- for batch in tqdm(ppo_trainer.dataloader):
138
- query_tensors = batch["input_ids"]
139
-
140
- #### Get response from SFTModel
141
- response_tensors = ppo_trainer.generate(query_tensors, **generation_kwargs)
142
- batch["response"] = [tokenizer.decode(r.squeeze()) for r in response_tensors]
143
-
144
- #### Compute reward score
145
- texts = [q + r for q, r in zip(batch["query"], batch["response"])]
146
- pipe_outputs = reward_model(texts)
147
- rewards = [torch.tensor(output[1]["score"]) for output in pipe_outputs]
148
-
149
- #### Run PPO step
150
- stats = ppo_trainer.step(query_tensors, response_tensors, rewards)
151
- ppo_trainer.log_stats(stats, batch, rewards)
152
-
153
- #### Save model
154
- ppo_trainer.save_pretrained("my_ppo_model")
155
- ```
156
-
157
- ## Logging
158
-
159
- While training and evaluating we log the following metrics:
160
-
161
- - `stats`: The statistics of the PPO algorithm, including the loss, entropy, etc.
162
- - `batch`: The batch of data used to train the SFT model.
163
- - `rewards`: The rewards obtained from the Reward model.
164
-
165
- ## PPOTrainer
166
-
167
- [[autodoc]] PPOTrainer
168
-
169
- [[autodoc]] PPOConfig
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
trl_md_files/quickstart.mdx DELETED
@@ -1,88 +0,0 @@
1
- # Quickstart
2
-
3
- ## How does it work?
4
-
5
- Fine-tuning a language model via PPO consists of roughly three steps:
6
-
7
- 1. **Rollout**: The language model generates a response or continuation based on a query which could be the start of a sentence.
8
- 2. **Evaluation**: The query and response are evaluated with a function, model, human feedback, or some combination of them. The important thing is that this process should yield a scalar value for each query/response pair. The optimization will aim at maximizing this value.
9
- 3. **Optimization**: This is the most complex part. In the optimisation step the query/response pairs are used to calculate the log-probabilities of the tokens in the sequences. This is done with the model that is trained and a reference model, which is usually the pre-trained model before fine-tuning. The KL-divergence between the two outputs is used as an additional reward signal to make sure the generated responses don't deviate too far from the reference language model. The active language model is then trained with PPO.
10
-
11
- The full process is illustrated in the following figure:
12
- <img src="https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/trl_overview.png"/>
13
-
14
- ## Minimal example
15
-
16
- The following code illustrates the steps above.
17
-
18
- ```python
19
- # 0. imports
20
- import torch
21
- from transformers import GPT2Tokenizer
22
-
23
- from trl import AutoModelForCausalLMWithValueHead, PPOConfig, PPOTrainer
24
-
25
-
26
- # 1. load a pretrained model
27
- model = AutoModelForCausalLMWithValueHead.from_pretrained("gpt2")
28
- ref_model = AutoModelForCausalLMWithValueHead.from_pretrained("gpt2")
29
- tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
30
- tokenizer.pad_token = tokenizer.eos_token
31
-
32
- # 2. initialize trainer
33
- ppo_config = {"mini_batch_size": 1, "batch_size": 1}
34
- config = PPOConfig(**ppo_config)
35
- ppo_trainer = PPOTrainer(config, model, ref_model, tokenizer)
36
-
37
- # 3. encode a query
38
- query_txt = "This morning I went to the "
39
- query_tensor = tokenizer.encode(query_txt, return_tensors="pt").to(model.pretrained_model.device)
40
-
41
- # 4. generate model response
42
- generation_kwargs = {
43
- "min_length": -1,
44
- "top_k": 0.0,
45
- "top_p": 1.0,
46
- "do_sample": True,
47
- "pad_token_id": tokenizer.eos_token_id,
48
- "max_new_tokens": 20,
49
- }
50
- response_tensor = ppo_trainer.generate([item for item in query_tensor], return_prompt=False, **generation_kwargs)
51
- response_txt = tokenizer.decode(response_tensor[0])
52
-
53
- # 5. define a reward for response
54
- # (this could be any reward such as human feedback or output from another model)
55
- reward = [torch.tensor(1.0, device=model.pretrained_model.device)]
56
-
57
- # 6. train model with ppo
58
- train_stats = ppo_trainer.step([query_tensor[0]], [response_tensor[0]], reward)
59
- ```
60
-
61
- In general, you would run steps 3-6 in a for-loop and run it on many diverse queries. You can find more realistic examples in the examples section.
62
-
63
- ## How to use a trained model
64
-
65
- After training a `AutoModelForCausalLMWithValueHead`, you can directly use the model in `transformers`.
66
- ```python
67
-
68
- # .. Let's assume we have a trained model using `PPOTrainer` and `AutoModelForCausalLMWithValueHead`
69
-
70
- # push the model on the Hub
71
- model.push_to_hub("my-fine-tuned-model-ppo")
72
-
73
- # or save it locally
74
- model.save_pretrained("my-fine-tuned-model-ppo")
75
-
76
- # load the model from the Hub
77
- from transformers import AutoModelForCausalLM
78
-
79
- model = AutoModelForCausalLM.from_pretrained("my-fine-tuned-model-ppo")
80
- ```
81
-
82
- You can also load your model with `AutoModelForCausalLMWithValueHead` if you want to use the value head, for example to continue training.
83
-
84
- ```python
85
- from trl.model import AutoModelForCausalLMWithValueHead
86
-
87
- model = AutoModelForCausalLMWithValueHead.from_pretrained("my-fine-tuned-model-ppo")
88
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
trl_md_files/reward_trainer.mdx DELETED
@@ -1,96 +0,0 @@
1
- # Reward Modeling
2
-
3
- TRL supports custom reward modeling for anyone to perform reward modeling on their dataset and model.
4
-
5
- Check out a complete flexible example at [`examples/scripts/reward_modeling.py`](https://github.com/huggingface/trl/tree/main/examples/scripts/reward_modeling.py).
6
-
7
- ## Expected dataset format
8
-
9
- The [`RewardTrainer`] expects a very specific format for the dataset since the model will be trained on pairs of examples to predict which of the two is preferred. We provide an example from the [`Anthropic/hh-rlhf`](https://huggingface.co/datasets/Anthropic/hh-rlhf) dataset below:
10
-
11
- <div style="text-align: center">
12
- <img src="https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/rlhf-antropic-example.png", width="50%">
13
- </div>
14
-
15
- Therefore the final dataset object should contain two 4 entries at least if you use the default [`RewardDataCollatorWithPadding`] data collator. The entries should be named:
16
-
17
- - `input_ids_chosen`
18
- - `attention_mask_chosen`
19
- - `input_ids_rejected`
20
- - `attention_mask_rejected`
21
-
22
- ## Using the `RewardTrainer`
23
-
24
- After preparing your dataset, you can use the [`RewardTrainer`] in the same way as the `Trainer` class from 🤗 Transformers.
25
- You should pass an `AutoModelForSequenceClassification` model to the [`RewardTrainer`], along with a [`RewardConfig`] which configures the hyperparameters of the training.
26
-
27
- ### Leveraging 🤗 PEFT to train a reward model
28
-
29
- Just pass a `peft_config` in the keyword arguments of [`RewardTrainer`], and the trainer should automatically take care of converting the model into a PEFT model!
30
-
31
- ```python
32
- from peft import LoraConfig, TaskType
33
- from transformers import AutoModelForSequenceClassification, AutoTokenizer
34
- from trl import RewardTrainer, RewardConfig
35
-
36
- model = AutoModelForSequenceClassification.from_pretrained("gpt2")
37
- peft_config = LoraConfig(
38
- task_type=TaskType.SEQ_CLS,
39
- inference_mode=False,
40
- r=8,
41
- lora_alpha=32,
42
- lora_dropout=0.1,
43
- )
44
-
45
- ...
46
-
47
- trainer = RewardTrainer(
48
- model=model,
49
- args=training_args,
50
- tokenizer=tokenizer,
51
- train_dataset=dataset,
52
- peft_config=peft_config,
53
- )
54
-
55
- trainer.train()
56
-
57
- ```
58
-
59
- ### Adding a margin to the loss
60
-
61
- As in the [Llama 2 paper](https://huggingface.co/papers/2307.09288), you can add a margin to the loss by adding a `margin` column to the dataset. The reward collator will automatically pass it through and the loss will be computed accordingly.
62
-
63
- ```python
64
- def add_margin(row):
65
- # Assume you have a score_chosen and score_rejected columns that you want to use to compute the margin
66
- return {'margin': row['score_chosen'] - row['score_rejected']}
67
-
68
- dataset = dataset.map(add_margin)
69
- ```
70
-
71
- ### Centering rewards
72
-
73
- In many scenarios, it's preferable to ensure that a reward model's output is mean zero. This is often done by first calculating the model's average score and then subtracting it.
74
-
75
- [[Eisenstein et al., 2023]](https://huggingface.co/papers/2312.09244) proposed an auxiliary loss function designed to directly learn a centered reward model. This auxiliary loss minimizes the squared sum of the rewards, encouraging the model to naturally produce mean-zero outputs:
76
-
77
- $$\Big( R(p, r_1) + R(p, r_2) \Big)^2 $$
78
-
79
- This auxiliary loss is combined with the main loss function, weighted by the parameter `center_rewards_coefficient` in the `[RewardConfig]`. By default, this feature is deactivated (`center_rewards_coefficient = None`).
80
-
81
- ```python
82
- reward_config = RewardConfig(
83
- center_rewards_coefficient=0.01,
84
- ...
85
- )
86
- ```
87
-
88
- For reference results, please refer PR [#1932](https://github.com/huggingface/trl/pull/1932).
89
-
90
- ## RewardConfig
91
-
92
- [[autodoc]] RewardConfig
93
-
94
- ## RewardTrainer
95
-
96
- [[autodoc]] RewardTrainer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
trl_md_files/sentiment_tuning.mdx DELETED
@@ -1,130 +0,0 @@
1
- # Sentiment Tuning Examples
2
-
3
- The notebooks and scripts in this examples show how to fine-tune a model with a sentiment classifier (such as `lvwerra/distilbert-imdb`).
4
-
5
- Here's an overview of the notebooks and scripts in the [trl repository](https://github.com/huggingface/trl/tree/main/examples):
6
-
7
-
8
-
9
- | File | Description |
10
- |------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------|
11
- | [`examples/scripts/ppo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/ppo.py) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/sentiment/notebooks/gpt2-sentiment.ipynb) | This script shows how to use the `PPOTrainer` to fine-tune a sentiment analysis model using IMDB dataset |
12
- | [`examples/notebooks/gpt2-sentiment.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/gpt2-sentiment.ipynb) | This notebook demonstrates how to reproduce the GPT2 imdb sentiment tuning example on a jupyter notebook. |
13
- | [`examples/notebooks/gpt2-control.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/gpt2-control.ipynb) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/sentiment/notebooks/gpt2-sentiment-control.ipynb) | This notebook demonstrates how to reproduce the GPT2 sentiment control example on a jupyter notebook.
14
-
15
-
16
-
17
- ## Usage
18
-
19
- ```bash
20
- # 1. run directly
21
- python examples/scripts/ppo.py
22
- # 2. run via `accelerate` (recommended), enabling more features (e.g., multiple GPUs, deepspeed)
23
- accelerate config # will prompt you to define the training configuration
24
- accelerate launch examples/scripts/ppo.py # launches training
25
- # 3. get help text and documentation
26
- python examples/scripts/ppo.py --help
27
- # 4. configure logging with wandb and, say, mini_batch_size=1 and gradient_accumulation_steps=16
28
- python examples/scripts/ppo.py --log_with wandb --mini_batch_size 1 --gradient_accumulation_steps 16
29
- ```
30
-
31
- Note: if you don't want to log with `wandb` remove `log_with="wandb"` in the scripts/notebooks. You can also replace it with your favourite experiment tracker that's [supported by `accelerate`](https://huggingface.co/docs/accelerate/usage_guides/tracking).
32
-
33
-
34
- ## Few notes on multi-GPU
35
-
36
- To run in multi-GPU setup with DDP (distributed Data Parallel) change the `device_map` value to `device_map={"": Accelerator().process_index}` and make sure to run your script with `accelerate launch yourscript.py`. If you want to apply naive pipeline parallelism you can use `device_map="auto"`.
37
-
38
-
39
- ## Benchmarks
40
-
41
- Below are some benchmark results for `examples/scripts/ppo.py`. To reproduce locally, please check out the `--command` arguments below.
42
-
43
- ```bash
44
- python benchmark/benchmark.py \
45
- --command "python examples/scripts/ppo.py --log_with wandb" \
46
- --num-seeds 5 \
47
- --start-seed 1 \
48
- --workers 10 \
49
- --slurm-nodes 1 \
50
- --slurm-gpus-per-task 1 \
51
- --slurm-ntasks 1 \
52
- --slurm-total-cpus 12 \
53
- --slurm-template-path benchmark/trl.slurm_template
54
- ```
55
-
56
- ![](https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/benchmark/v0.4.7-55-g110e672/sentiment.png)
57
-
58
-
59
-
60
- ## With and without gradient accumulation
61
-
62
- ```bash
63
- python benchmark/benchmark.py \
64
- --command "python examples/scripts/ppo.py --exp_name sentiment_tuning_step_grad_accu --mini_batch_size 1 --gradient_accumulation_steps 128 --log_with wandb" \
65
- --num-seeds 5 \
66
- --start-seed 1 \
67
- --workers 10 \
68
- --slurm-nodes 1 \
69
- --slurm-gpus-per-task 1 \
70
- --slurm-ntasks 1 \
71
- --slurm-total-cpus 12 \
72
- --slurm-template-path benchmark/trl.slurm_template
73
- ```
74
-
75
- ![](https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/benchmark/v0.4.7-55-g110e672/gradient_accu.png)
76
-
77
-
78
- ## Comparing different models (gpt2, gpt2-xl, falcon, llama2)
79
-
80
- ```bash
81
- python benchmark/benchmark.py \
82
- --command "python examples/scripts/ppo.py --exp_name sentiment_tuning_gpt2 --log_with wandb" \
83
- --num-seeds 5 \
84
- --start-seed 1 \
85
- --workers 10 \
86
- --slurm-nodes 1 \
87
- --slurm-gpus-per-task 1 \
88
- --slurm-ntasks 1 \
89
- --slurm-total-cpus 12 \
90
- --slurm-template-path benchmark/trl.slurm_template
91
- python benchmark/benchmark.py \
92
- --command "python examples/scripts/ppo.py --exp_name sentiment_tuning_gpt2xl_grad_accu --model_name gpt2-xl --mini_batch_size 16 --gradient_accumulation_steps 8 --log_with wandb" \
93
- --num-seeds 5 \
94
- --start-seed 1 \
95
- --workers 10 \
96
- --slurm-nodes 1 \
97
- --slurm-gpus-per-task 1 \
98
- --slurm-ntasks 1 \
99
- --slurm-total-cpus 12 \
100
- --slurm-template-path benchmark/trl.slurm_template
101
- python benchmark/benchmark.py \
102
- --command "python examples/scripts/ppo.py --exp_name sentiment_tuning_falcon_rw_1b --model_name tiiuae/falcon-rw-1b --log_with wandb" \
103
- --num-seeds 5 \
104
- --start-seed 1 \
105
- --workers 10 \
106
- --slurm-nodes 1 \
107
- --slurm-gpus-per-task 1 \
108
- --slurm-ntasks 1 \
109
- --slurm-total-cpus 12 \
110
- --slurm-template-path benchmark/trl.slurm_template
111
- ```
112
-
113
- ![](https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/benchmark/v0.4.7-55-g110e672/different_models.png)
114
-
115
- ## With and without PEFT
116
-
117
- ```
118
- python benchmark/benchmark.py \
119
- --command "python examples/scripts/ppo.py --exp_name sentiment_tuning_peft --use_peft --log_with wandb" \
120
- --num-seeds 5 \
121
- --start-seed 1 \
122
- --workers 10 \
123
- --slurm-nodes 1 \
124
- --slurm-gpus-per-task 1 \
125
- --slurm-ntasks 1 \
126
- --slurm-total-cpus 12 \
127
- --slurm-template-path benchmark/trl.slurm_template
128
- ```
129
-
130
- ![](https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/benchmark/v0.4.7-55-g110e672/peft.png)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
trl_md_files/sft_trainer.mdx DELETED
@@ -1,752 +0,0 @@
1
- # Supervised Fine-tuning Trainer
2
-
3
- Supervised fine-tuning (or SFT for short) is a crucial step in RLHF. In TRL we provide an easy-to-use API to create your SFT models and train them with few lines of code on your dataset.
4
-
5
- Check out a complete flexible example at [`examples/scripts/sft.py`](https://github.com/huggingface/trl/tree/main/examples/scripts/sft.py).
6
- Experimental support for Vision Language Models is also included in the example [`examples/scripts/vsft_llava.py`](https://github.com/huggingface/trl/tree/main/examples/scripts/vsft_llava.py).
7
-
8
- ## Quickstart
9
-
10
- If you have a dataset hosted on the 🤗 Hub, you can easily fine-tune your SFT model using [`SFTTrainer`] from TRL. Let us assume your dataset is `imdb`, the text you want to predict is inside the `text` field of the dataset, and you want to fine-tune the `facebook/opt-350m` model.
11
- The following code-snippet takes care of all the data pre-processing and training for you:
12
-
13
- ```python
14
- from datasets import load_dataset
15
- from trl import SFTConfig, SFTTrainer
16
-
17
- dataset = load_dataset("imdb", split="train")
18
-
19
- sft_config = SFTConfig(
20
- dataset_text_field="text",
21
- max_seq_length=512,
22
- output_dir="/tmp",
23
- )
24
- trainer = SFTTrainer(
25
- "facebook/opt-350m",
26
- train_dataset=dataset,
27
- args=sft_config,
28
- )
29
- trainer.train()
30
- ```
31
- Make sure to pass the correct value for `max_seq_length` as the default value will be set to `min(tokenizer.model_max_length, 1024)`.
32
-
33
- You can also construct a model outside of the trainer and pass it as follows:
34
-
35
- ```python
36
- from transformers import AutoModelForCausalLM
37
- from datasets import load_dataset
38
- from trl import SFTConfig, SFTTrainer
39
-
40
- dataset = load_dataset("imdb", split="train")
41
-
42
- model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m")
43
-
44
- sft_config = SFTConfig(output_dir="/tmp")
45
-
46
- trainer = SFTTrainer(
47
- model,
48
- train_dataset=dataset,
49
- args=sft_config,
50
- )
51
-
52
- trainer.train()
53
- ```
54
-
55
- The above snippets will use the default training arguments from the [`SFTConfig`] class. If you want to modify the defaults pass in your modification to the `SFTConfig` constructor and pass them to the trainer via the `args` argument.
56
-
57
- ## Advanced usage
58
-
59
- ### Train on completions only
60
-
61
- You can use the `DataCollatorForCompletionOnlyLM` to train your model on the generated prompts only. Note that this works only in the case when `packing=False`.
62
- To instantiate that collator for instruction data, pass a response template and the tokenizer. Here is an example of how it would work to fine-tune `opt-350m` on completions only on the CodeAlpaca dataset:
63
-
64
- ```python
65
- from transformers import AutoModelForCausalLM, AutoTokenizer
66
- from datasets import load_dataset
67
- from trl import SFTConfig, SFTTrainer, DataCollatorForCompletionOnlyLM
68
-
69
- dataset = load_dataset("lucasmccabe-lmi/CodeAlpaca-20k", split="train")
70
-
71
- model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m")
72
- tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")
73
-
74
- def formatting_prompts_func(example):
75
- output_texts = []
76
- for i in range(len(example['instruction'])):
77
- text = f"### Question: {example['instruction'][i]}\n ### Answer: {example['output'][i]}"
78
- output_texts.append(text)
79
- return output_texts
80
-
81
- response_template = " ### Answer:"
82
- collator = DataCollatorForCompletionOnlyLM(response_template, tokenizer=tokenizer)
83
-
84
- trainer = SFTTrainer(
85
- model,
86
- train_dataset=dataset,
87
- args=SFTConfig(output_dir="/tmp"),
88
- formatting_func=formatting_prompts_func,
89
- data_collator=collator,
90
- )
91
-
92
- trainer.train()
93
- ```
94
-
95
- To instantiate that collator for assistant style conversation data, pass a response template, an instruction template and the tokenizer. Here is an example of how it would work to fine-tune `opt-350m` on assistant completions only on the Open Assistant Guanaco dataset:
96
-
97
- ```python
98
- from transformers import AutoModelForCausalLM, AutoTokenizer
99
- from datasets import load_dataset
100
- from trl import SFTConfig, SFTTrainer, DataCollatorForCompletionOnlyLM
101
-
102
- dataset = load_dataset("timdettmers/openassistant-guanaco", split="train")
103
-
104
- model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m")
105
- tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")
106
-
107
- instruction_template = "### Human:"
108
- response_template = "### Assistant:"
109
- collator = DataCollatorForCompletionOnlyLM(instruction_template=instruction_template, response_template=response_template, tokenizer=tokenizer, mlm=False)
110
-
111
- trainer = SFTTrainer(
112
- model,
113
- args=SFTConfig(
114
- output_dir="/tmp",
115
- dataset_text_field = "text",
116
- ),
117
- train_dataset=dataset,
118
- data_collator=collator,
119
- )
120
-
121
- trainer.train()
122
- ```
123
-
124
- Make sure to have a `pad_token_id` which is different from `eos_token_id` which can result in the model not properly predicting EOS (End of Sentence) tokens during generation.
125
-
126
- #### Using token_ids directly for `response_template`
127
-
128
- Some tokenizers like Llama 2 (`meta-llama/Llama-2-XXb-hf`) tokenize sequences differently depending on whether they have context or not. For example:
129
-
130
- ```python
131
- from transformers import AutoTokenizer
132
- tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
133
-
134
- def print_tokens_with_ids(txt):
135
- tokens = tokenizer.tokenize(txt, add_special_tokens=False)
136
- token_ids = tokenizer.encode(txt, add_special_tokens=False)
137
- print(list(zip(tokens, token_ids)))
138
-
139
- prompt = """### User: Hello\n\n### Assistant: Hi, how can I help you?"""
140
- print_tokens_with_ids(prompt) # [..., ('▁Hello', 15043), ('<0x0A>', 13), ('<0x0A>', 13), ('##', 2277), ('#', 29937), ('▁Ass', 4007), ('istant', 22137), (':', 29901), ...]
141
-
142
- response_template = "### Assistant:"
143
- print_tokens_with_ids(response_template) # [('▁###', 835), ('▁Ass', 4007), ('istant', 22137), (':', 29901)]
144
- ```
145
-
146
- In this case, and due to lack of context in `response_template`, the same string ("### Assistant:") is tokenized differently:
147
-
148
- - Text (with context): `[2277, 29937, 4007, 22137, 29901]`
149
- - `response_template` (without context): `[835, 4007, 22137, 29901]`
150
-
151
- This will lead to an error when the `DataCollatorForCompletionOnlyLM` does not find the `response_template` in the dataset example text:
152
-
153
- ```
154
- RuntimeError: Could not find response key [835, 4007, 22137, 29901] in token IDs tensor([ 1, 835, ...])
155
- ```
156
-
157
-
158
- To solve this, you can tokenize the `response_template` with the same context as in the dataset, truncate it as needed and pass the `token_ids` directly to the `response_template` argument of the `DataCollatorForCompletionOnlyLM` class. For example:
159
-
160
- ```python
161
- response_template_with_context = "\n### Assistant:" # We added context here: "\n". This is enough for this tokenizer
162
- response_template_ids = tokenizer.encode(response_template_with_context, add_special_tokens=False)[2:] # Now we have it like in the dataset texts: `[2277, 29937, 4007, 22137, 29901]`
163
-
164
- data_collator = DataCollatorForCompletionOnlyLM(response_template_ids, tokenizer=tokenizer)
165
- ```
166
-
167
- ### Add Special Tokens for Chat Format
168
-
169
- Adding special tokens to a language model is crucial for training chat models. These tokens are added between the different roles in a conversation, such as the user, assistant, and system and help the model recognize the structure and flow of a conversation. This setup is essential for enabling the model to generate coherent and contextually appropriate responses in a chat environment.
170
- The [`setup_chat_format`] function in `trl` easily sets up a model and tokenizer for conversational AI tasks. This function:
171
- - Adds special tokens to the tokenizer, e.g. `<|im_start|>` and `<|im_end|>`, to indicate the start and end of a conversation.
172
- - Resizes the model’s embedding layer to accommodate the new tokens.
173
- - Sets the `chat_template` of the tokenizer, which is used to format the input data into a chat-like format. The default is `chatml` from OpenAI.
174
- - _optionally_ you can pass `resize_to_multiple_of` to resize the embedding layer to a multiple of the `resize_to_multiple_of` argument, e.g. 64. If you want to see more formats being supported in the future, please open a GitHub issue on [trl](https://github.com/huggingface/trl)
175
-
176
- ```python
177
- from transformers import AutoModelForCausalLM, AutoTokenizer
178
- from trl import setup_chat_format
179
-
180
- # Load model and tokenizer
181
- model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m")
182
- tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")
183
-
184
- # Set up the chat format with default 'chatml' format
185
- model, tokenizer = setup_chat_format(model, tokenizer)
186
-
187
- ```
188
-
189
- With our model and tokenizer set up, we can now fine-tune our model on a conversational dataset. Below is an example of how a dataset can be formatted for fine-tuning.
190
-
191
- ### Dataset format support
192
-
193
- The [`SFTTrainer`] supports popular dataset formats. This allows you to pass the dataset to the trainer without any pre-processing directly. The following formats are supported:
194
- * conversational format
195
- ```json
196
- {"messages": [{"role": "system", "content": "You are helpful"}, {"role": "user", "content": "What's the capital of France?"}, {"role": "assistant", "content": "..."}]}
197
- {"messages": [{"role": "system", "content": "You are helpful"}, {"role": "user", "content": "Who wrote 'Romeo and Juliet'?"}, {"role": "assistant", "content": "..."}]}
198
- {"messages": [{"role": "system", "content": "You are helpful"}, {"role": "user", "content": "How far is the Moon from Earth?"}, {"role": "assistant", "content": "..."}]}
199
- ```
200
- * instruction format
201
- ```json
202
- {"prompt": "<prompt text>", "completion": "<ideal generated text>"}
203
- {"prompt": "<prompt text>", "completion": "<ideal generated text>"}
204
- {"prompt": "<prompt text>", "completion": "<ideal generated text>"}
205
- ```
206
-
207
- If your dataset uses one of the above formats, you can directly pass it to the trainer without pre-processing. The [`SFTTrainer`] will then format the dataset for you using the defined format from the model's tokenizer with the [apply_chat_template](https://huggingface.co/docs/transformers/main/en/chat_templating#templates-for-chat-models) method.
208
-
209
-
210
- ```python
211
- from datasets import load_dataset
212
- from trl import SFTConfig, SFTTrainer
213
-
214
- ...
215
-
216
- # load jsonl dataset
217
- dataset = load_dataset("json", data_files="path/to/dataset.jsonl", split="train")
218
- # load dataset from the HuggingFace Hub
219
- dataset = load_dataset("philschmid/dolly-15k-oai-style", split="train")
220
-
221
- ...
222
-
223
- sft_config = SFTConfig(packing=True)
224
- trainer = SFTTrainer(
225
- "facebook/opt-350m",
226
- args=sft_config,
227
- train_dataset=dataset,
228
- )
229
- ```
230
-
231
- If the dataset is not in one of those format you can either preprocess the dataset to match the formatting or pass a formatting function to the SFTTrainer to do it for you. Let's have a look.
232
-
233
-
234
- ### Format your input prompts
235
-
236
- For instruction fine-tuning, it is quite common to have two columns inside the dataset: one for the prompt & the other for the response.
237
- This allows people to format examples like [Stanford-Alpaca](https://github.com/tatsu-lab/stanford_alpaca) did as follows:
238
- ```bash
239
- Below is an instruction ...
240
-
241
- ### Instruction
242
- {prompt}
243
-
244
- ### Response:
245
- {completion}
246
- ```
247
- Let us assume your dataset has two fields, `question` and `answer`. Therefore you can just run:
248
- ```python
249
- ...
250
- def formatting_prompts_func(example):
251
- output_texts = []
252
- for i in range(len(example['question'])):
253
- text = f"### Question: {example['question'][i]}\n ### Answer: {example['answer'][i]}"
254
- output_texts.append(text)
255
- return output_texts
256
-
257
- trainer = SFTTrainer(
258
- model,
259
- args=sft_config,
260
- train_dataset=dataset,
261
- formatting_func=formatting_prompts_func,
262
- )
263
-
264
- trainer.train()
265
- ```
266
- To properly format your input make sure to process all the examples by looping over them and returning a list of processed text. Check out a full example of how to use SFTTrainer on alpaca dataset [here](https://github.com/huggingface/trl/pull/444#issue-1760952763)
267
-
268
- ### Packing dataset ([`ConstantLengthDataset`])
269
-
270
- [`SFTTrainer`] supports _example packing_, where multiple short examples are packed in the same input sequence to increase training efficiency. This is done with the [`ConstantLengthDataset`] utility class that returns constant length chunks of tokens from a stream of examples. To enable the usage of this dataset class, simply pass `packing=True` to the [`SFTConfig`] constructor.
271
-
272
- ```python
273
- ...
274
- sft_config = SFTConfig(packing=True, dataset_text_field="text",)
275
-
276
- trainer = SFTTrainer(
277
- "facebook/opt-350m",
278
- train_dataset=dataset,
279
- args=sft_config
280
- )
281
-
282
- trainer.train()
283
- ```
284
-
285
- Note that if you use a packed dataset and if you pass `max_steps` in the training arguments you will probably train your models for more than few epochs, depending on the way you have configured the packed dataset and the training protocol. Double check that you know and understand what you are doing.
286
- If you don't want to pack your `eval_dataset`, you can pass `eval_packing=False` to the `SFTConfig` init method.
287
-
288
- #### Customize your prompts using packed dataset
289
-
290
- If your dataset has several fields that you want to combine, for example if the dataset has `question` and `answer` fields and you want to combine them, you can pass a formatting function to the trainer that will take care of that. For example:
291
-
292
- ```python
293
- def formatting_func(example):
294
- text = f"### Question: {example['question']}\n ### Answer: {example['answer']}"
295
- return text
296
-
297
- sft_config = SFTConfig(packing=True)
298
- trainer = SFTTrainer(
299
- "facebook/opt-350m",
300
- train_dataset=dataset,
301
- args=sft_config,
302
- formatting_func=formatting_func
303
- )
304
-
305
- trainer.train()
306
- ```
307
- You can also customize the [`ConstantLengthDataset`] much more by directly passing the arguments to the [`SFTConfig`] constructor. Please refer to that class' signature for more information.
308
-
309
- ### Control over the pretrained model
310
-
311
- You can directly pass the kwargs of the `from_pretrained()` method to the [`SFTConfig`]. For example, if you want to load a model in a different precision, analogous to
312
-
313
- ```python
314
- model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m", torch_dtype=torch.bfloat16)
315
-
316
- ...
317
-
318
- sft_config = SFTConfig(
319
- model_init_kwargs={
320
- "torch_dtype": "bfloat16",
321
- },
322
- output_dir="/tmp",
323
- )
324
- trainer = SFTTrainer(
325
- "facebook/opt-350m",
326
- train_dataset=dataset,
327
- args=sft_config,
328
- )
329
-
330
- trainer.train()
331
- ```
332
- Note that all keyword arguments of `from_pretrained()` are supported.
333
-
334
- ### Training adapters
335
-
336
- We also support tight integration with 🤗 PEFT library so that any user can conveniently train adapters and share them on the Hub instead of training the entire model
337
-
338
- ```python
339
- from datasets import load_dataset
340
- from trl import SFTConfig, SFTTrainer
341
- from peft import LoraConfig
342
-
343
- dataset = load_dataset("imdb", split="train")
344
-
345
- peft_config = LoraConfig(
346
- r=16,
347
- lora_alpha=32,
348
- lora_dropout=0.05,
349
- bias="none",
350
- task_type="CAUSAL_LM",
351
- )
352
-
353
- trainer = SFTTrainer(
354
- "EleutherAI/gpt-neo-125m",
355
- train_dataset=dataset,
356
- args=SFTConfig(output_dir="/tmp"),
357
- peft_config=peft_config
358
- )
359
-
360
- trainer.train()
361
- ```
362
-
363
- You can also continue training your `PeftModel`. For that, first load a `PeftModel` outside `SFTTrainer` and pass it directly to the trainer without the `peft_config` argument being passed.
364
-
365
- ### Training adapters with base 8 bit models
366
-
367
- For that, you need to first load your 8 bit model outside the Trainer and pass a `PeftConfig` to the trainer. For example:
368
-
369
- ```python
370
- ...
371
-
372
- peft_config = LoraConfig(
373
- r=16,
374
- lora_alpha=32,
375
- lora_dropout=0.05,
376
- bias="none",
377
- task_type="CAUSAL_LM",
378
- )
379
-
380
- model = AutoModelForCausalLM.from_pretrained(
381
- "EleutherAI/gpt-neo-125m",
382
- load_in_8bit=True,
383
- device_map="auto",
384
- )
385
-
386
- trainer = SFTTrainer(
387
- model,
388
- train_dataset=dataset,
389
- args=SFTConfig(),
390
- peft_config=peft_config,
391
- )
392
-
393
- trainer.train()
394
- ```
395
-
396
- ## Using Flash Attention and Flash Attention 2
397
-
398
- You can benefit from Flash Attention 1 & 2 using SFTTrainer out of the box with minimal changes of code.
399
- First, to make sure you have all the latest features from transformers, install transformers from source
400
-
401
- ```bash
402
- pip install -U git+https://github.com/huggingface/transformers.git
403
- ```
404
-
405
- Note that Flash Attention only works on GPU now and under half-precision regime (when using adapters, base model loaded in half-precision)
406
- Note also both features are perfectly compatible with other tools such as quantization.
407
-
408
- ### Using Flash-Attention 1
409
-
410
- For Flash Attention 1 you can use the `BetterTransformer` API and force-dispatch the API to use Flash Attention kernel. First, install the latest optimum package:
411
-
412
- ```bash
413
- pip install -U optimum
414
- ```
415
-
416
- Once you have loaded your model, wrap the `trainer.train()` call under the `with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=False):` context manager:
417
-
418
- ```diff
419
- ...
420
-
421
- + with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=False):
422
- trainer.train()
423
- ```
424
-
425
- Note that you cannot train your model using Flash Attention 1 on an arbitrary dataset as `torch.scaled_dot_product_attention` does not support training with padding tokens if you use Flash Attention kernels. Therefore you can only use that feature with `packing=True`. If your dataset contains padding tokens, consider switching to Flash Attention 2 integration.
426
-
427
- Below are some numbers you can get in terms of speedup and memory efficiency, using Flash Attention 1, on a single NVIDIA-T4 16GB.
428
-
429
- | use_flash_attn_1 | model_name | max_seq_len | batch_size | time per training step |
430
- | ---------------- | ----------------- | ----------- | ---------- | ---------------------- |
431
- | x | facebook/opt-350m | 2048 | 8 | ~59.1s |
432
- | | facebook/opt-350m | 2048 | 8 | **OOM** |
433
- | x | facebook/opt-350m | 2048 | 4 | ~30.3s |
434
- | | facebook/opt-350m | 2048 | 4 | ~148.9s |
435
-
436
- ### Using Flash Attention-2
437
-
438
- To use Flash Attention 2, first install the latest `flash-attn` package:
439
-
440
- ```bash
441
- pip install -U flash-attn
442
- ```
443
-
444
- And add `attn_implementation="flash_attention_2"` when calling `from_pretrained`:
445
-
446
- ```python
447
- model = AutoModelForCausalLM.from_pretrained(
448
- model_id,
449
- load_in_4bit=True,
450
- attn_implementation="flash_attention_2"
451
- )
452
- ```
453
-
454
- If you don't use quantization, make sure your model is loaded in half-precision and dispatch your model on a supported GPU device.
455
- After loading your model, you can either train it as it is, or attach adapters and train adapters on it in case your model is quantized.
456
-
457
- In contrast to Flash Attention 1, the integration makes it possible to train your model on an arbitrary dataset that also includes padding tokens.
458
-
459
-
460
- ### Using model creation utility
461
-
462
- We included a utility function to create your model.
463
-
464
- [[autodoc]] ModelConfig
465
-
466
- ```python
467
- from trl import ModelConfig, SFTTrainer, get_kbit_device_map, get_peft_config, get_quantization_config
468
- model_config = ModelConfig(
469
- model_name_or_path="facebook/opt-350m"
470
- attn_implementation=None, # or "flash_attention_2"
471
- )
472
- torch_dtype = (
473
- model_config.torch_dtype
474
- if model_config.torch_dtype in ["auto", None]
475
- else getattr(torch, model_config.torch_dtype)
476
- )
477
- quantization_config = get_quantization_config(model_config)
478
- model_kwargs = dict(
479
- revision=model_config.model_revision,
480
- trust_remote_code=model_config.trust_remote_code,
481
- attn_implementation=model_config.attn_implementation,
482
- torch_dtype=torch_dtype,
483
- use_cache=False if training_args.gradient_checkpointing else True,
484
- device_map=get_kbit_device_map() if quantization_config is not None else None,
485
- quantization_config=quantization_config,
486
- )
487
- model = AutoModelForCausalLM.from_pretrained(model_config.model_name_or_path, **model_kwargs)
488
- trainer = SFTTrainer(
489
- ...,
490
- model=model_config.model_name_or_path,
491
- peft_config=get_peft_config(model_config),
492
- )
493
- ```
494
-
495
- ### Enhance the model's performances using NEFTune
496
-
497
- NEFTune is a technique to boost the performance of chat models and was introduced by the paper ["NEFTune: Noisy Embeddings Improve Instruction Finetuning"](https://huggingface.co/papers/2310.05914) from Jain et al. it consists of adding noise to the embedding vectors during training. According to the abstract of the paper:
498
-
499
- > Standard finetuning of LLaMA-2-7B using Alpaca achieves 29.79% on AlpacaEval, which rises to 64.69% using noisy embeddings. NEFTune also improves over strong baselines on modern instruction datasets. Models trained with Evol-Instruct see a 10% improvement, with ShareGPT an 8% improvement, and with OpenPlatypus an 8% improvement. Even powerful models further refined with RLHF such as LLaMA-2-Chat benefit from additional training with NEFTune.
500
-
501
- <div style="text-align: center">
502
- <img src="https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/neft-screenshot.png">
503
- </div>
504
-
505
- To use it in `SFTTrainer` simply pass `neftune_noise_alpha` when creating your `SFTConfig` instance. Note that to avoid any surprising behaviour, NEFTune is disabled after training to retrieve back the original behaviour of the embedding layer.
506
-
507
- ```python
508
- from datasets import load_dataset
509
- from trl import SFTConfig, SFTTrainer
510
-
511
- dataset = load_dataset("imdb", split="train")
512
-
513
- sft_config = SFTConfig(
514
- neftune_noise_alpha=5,
515
- )
516
- trainer = SFTTrainer(
517
- "facebook/opt-350m",
518
- train_dataset=dataset,
519
- args=sft_config,
520
- )
521
- trainer.train()
522
- ```
523
-
524
- We have tested NEFTune by training `mistralai/Mistral-7B-v0.1` on the [OpenAssistant dataset](https://huggingface.co/datasets/timdettmers/openassistant-guanaco) and validated that using NEFTune led to a performance boost of ~25% on MT Bench.
525
-
526
- <div style="text-align: center">
527
- <img src="https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/trl-neftune-mistral-7b.png">
528
- </div>
529
-
530
- Note however, that the amount of performance gain is _dataset dependent_ and in particular, applying NEFTune on synthetic datasets like [UltraChat](https://huggingface.co/datasets/stingning/ultrachat) typically produces smaller gains.
531
-
532
- ### Accelerate fine-tuning 2x using `unsloth`
533
-
534
- You can further accelerate QLoRA / LoRA (2x faster, 60% less memory) using the [`unsloth`](https://github.com/unslothai/unsloth) library that is fully compatible with `SFTTrainer`. Currently `unsloth` supports only Llama (Yi, TinyLlama, Qwen, Deepseek etc) and Mistral architectures. Some benchmarks on 1x A100 listed below:
535
-
536
- | 1 A100 40GB | Dataset | 🤗 | 🤗 + Flash Attention 2 | 🦥 Unsloth | 🦥 VRAM saved |
537
- | --------------- | --------- | --- | --------------------- | --------- | ------------ |
538
- | Code Llama 34b | Slim Orca | 1x | 1.01x | **1.94x** | -22.7% |
539
- | Llama-2 7b | Slim Orca | 1x | 0.96x | **1.87x** | -39.3% |
540
- | Mistral 7b | Slim Orca | 1x | 1.17x | **1.88x** | -65.9% |
541
- | Tiny Llama 1.1b | Alpaca | 1x | 1.55x | **2.74x** | -57.8% |
542
-
543
- First install `unsloth` according to the [official documentation](https://github.com/unslothai/unsloth). Once installed, you can incorporate unsloth into your workflow in a very simple manner; instead of loading `AutoModelForCausalLM`, you just need to load a `FastLanguageModel` as follows:
544
-
545
- ```python
546
- import torch
547
- from trl import SFTConfig, SFTTrainer
548
- from unsloth import FastLanguageModel
549
-
550
- max_seq_length = 2048 # Supports automatic RoPE Scaling, so choose any number
551
-
552
- # Load model
553
- model, tokenizer = FastLanguageModel.from_pretrained(
554
- model_name="unsloth/mistral-7b",
555
- max_seq_length=max_seq_length,
556
- dtype=None, # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
557
- load_in_4bit=True, # Use 4bit quantization to reduce memory usage. Can be False
558
- # token = "hf_...", # use one if using gated models like meta-llama/Llama-2-7b-hf
559
- )
560
-
561
- # Do model patching and add fast LoRA weights
562
- model = FastLanguageModel.get_peft_model(
563
- model,
564
- r=16,
565
- target_modules=[
566
- "q_proj",
567
- "k_proj",
568
- "v_proj",
569
- "o_proj",
570
- "gate_proj",
571
- "up_proj",
572
- "down_proj",
573
- ],
574
- lora_alpha=16,
575
- lora_dropout=0, # Dropout = 0 is currently optimized
576
- bias="none", # Bias = "none" is currently optimized
577
- use_gradient_checkpointing=True,
578
- random_state=3407,
579
- )
580
-
581
- args = SFTConfig(
582
- output_dir="./output",
583
- max_seq_length=max_seq_length,
584
- dataset_text_field="text",
585
- )
586
-
587
- trainer = SFTTrainer(
588
- model=model,
589
- args=args,
590
- train_dataset=dataset,
591
- )
592
- trainer.train()
593
- ```
594
-
595
- The saved model is fully compatible with Hugging Face's transformers library. Learn more about unsloth in their [official repository](https://github.com/unslothai/unsloth).
596
-
597
- ## Best practices
598
-
599
- Pay attention to the following best practices when training a model with that trainer:
600
-
601
- - [`SFTTrainer`] always pads by default the sequences to the `max_seq_length` argument of the [`SFTTrainer`]. If none is passed, the trainer will retrieve that value from the tokenizer. Some tokenizers do not provide a default value, so there is a check to retrieve the minimum between 2048 and that value. Make sure to check it before training.
602
- - For training adapters in 8bit, you might need to tweak the arguments of the `prepare_model_for_kbit_training` method from PEFT, hence we advise users to use `prepare_in_int8_kwargs` field, or create the `PeftModel` outside the [`SFTTrainer`] and pass it.
603
- - For a more memory-efficient training using adapters, you can load the base model in 8bit, for that simply add `load_in_8bit` argument when creating the [`SFTTrainer`], or create a base model in 8bit outside the trainer and pass it.
604
- - If you create a model outside the trainer, make sure to not pass to the trainer any additional keyword arguments that are relative to `from_pretrained()` method.
605
-
606
- ## Multi-GPU Training
607
-
608
- Trainer (and thus SFTTrainer) supports multi-GPU training. If you run your script with `python script.py` it will default to using DP as the strategy, which may be [slower than expected](https://github.com/huggingface/trl/issues/1303). To use DDP (which is generally recommended, see [here](https://huggingface.co/docs/transformers/en/perf_train_gpu_many?select-gpu=Accelerate#data-parallelism) for more info) you must launch the script with `python -m torch.distributed.launch script.py` or `accelerate launch script.py`. For DDP to work you must also check the following:
609
- - If you're using gradient_checkpointing, add the following to the TrainingArguments: `gradient_checkpointing_kwargs={'use_reentrant':False}` (more info [here](https://github.com/huggingface/transformers/issues/26969)
610
- - Ensure that the model is placed on the correct device:
611
- ```python
612
- from accelerate import PartialState
613
- device_string = PartialState().process_index
614
- model = AutoModelForCausalLM.from_pretrained(
615
- ...
616
- device_map={'':device_string}
617
- )
618
- ```
619
-
620
- ## GPTQ Conversion
621
-
622
- You may experience some issues with GPTQ Quantization after completing training. Lowering `gradient_accumulation_steps` to `4` will resolve most issues during the quantization process to GPTQ format.
623
-
624
- ## Extending `SFTTrainer` for Vision Language Models
625
-
626
- `SFTTrainer` does not inherently support vision-language data. However, we provide a guide on how to tweak the trainer to support vision-language data. Specifically, you need to use a custom data collator that is compatible with vision-language data. This guide outlines the steps to make these adjustments. For a concrete example, refer to the script [`examples/scripts/vsft_llava.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/vsft_llava.py) which demonstrates how to fine-tune the LLaVA 1.5 model on the [HuggingFaceH4/llava-instruct-mix-vsft](https://huggingface.co/datasets/HuggingFaceH4/llava-instruct-mix-vsft) dataset.
627
-
628
- ### Preparing the Data
629
-
630
- The data format is flexible, provided it is compatible with the custom collator that we will define later. A common approach is to use conversational data. Given that the data includes both text and images, the format needs to be adjusted accordingly. Below is an example of a conversational data format involving both text and images:
631
-
632
- ```python
633
- images = ["obama.png"]
634
- messages = [
635
- {
636
- "role": "user",
637
- "content": [
638
- {"type": "text", "text": "Who is this?"},
639
- {"type": "image"}
640
- ]
641
- },
642
- {
643
- "role": "assistant",
644
- "content": [
645
- {"type": "text", "text": "Barack Obama"}
646
- ]
647
- },
648
- {
649
- "role": "user",
650
- "content": [
651
- {"type": "text", "text": "What is he famous for?"}
652
- ]
653
- },
654
- {
655
- "role": "assistant",
656
- "content": [
657
- {"type": "text", "text": "He is the 44th President of the United States."}
658
- ]
659
- }
660
- ]
661
- ```
662
-
663
- To illustrate how this data format will be processed using the LLaVA model, you can use the following code:
664
-
665
- ```python
666
- from transformers import AutoProcessor
667
-
668
- processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf")
669
- print(processor.apply_chat_template(messages, tokenize=False))
670
- ```
671
-
672
- The output will be formatted as follows:
673
-
674
- ```txt
675
- Who is this? ASSISTANT: Barack Obama USER: What is he famous for? ASSISTANT: He is the 44th President of the United States.
676
- ```
677
-
678
- <iframe src="https://huggingface.co/datasets/HuggingFaceH4/llava-instruct-mix-vsft/embed/viewer/default/train" frameborder="0" width="100%" height="560px"></iframe>
679
-
680
-
681
- ### A custom collator for processing multi-modal data
682
-
683
- Unlike the default behavior of `SFTTrainer`, processing multi-modal data is done on the fly during the data collation process. To do this, you need to define a custom collator that processes both the text and images. This collator must take a list of examples as input (see the previous section for an example of the data format) and return a batch of processed data. Below is an example of such a collator:
684
-
685
- ```python
686
- def collate_fn(examples):
687
- # Get the texts and images, and apply the chat template
688
- texts = [processor.apply_chat_template(example["messages"], tokenize=False) for example in examples]
689
- images = [example["images"][0] for example in examples]
690
-
691
- # Tokenize the texts and process the images
692
- batch = processor(texts, images, return_tensors="pt", padding=True)
693
-
694
- # The labels are the input_ids, and we mask the padding tokens in the loss computation
695
- labels = batch["input_ids"].clone()
696
- labels[labels == processor.tokenizer.pad_token_id] = -100
697
- batch["labels"] = labels
698
-
699
- return batch
700
- ```
701
-
702
- We can verify that the collator works as expected by running the following code:
703
-
704
- ```python
705
- from datasets import load_dataset
706
-
707
- dataset = load_dataset("HuggingFaceH4/llava-instruct-mix-vsft", split="train")
708
- examples = [dataset[0], dataset[1]] # Just two examples for the sake of the example
709
- collated_data = collate_fn(examples)
710
- print(collated_data.keys()) # dict_keys(['input_ids', 'attention_mask', 'pixel_values', 'labels'])
711
- ```
712
-
713
- ### Training the vision-language model
714
-
715
- Now that we have prepared the data and defined the collator, we can proceed with training the model. To ensure that the data is not processed as text-only, we need to set a couple of arguments in the `SFTConfig`, specifically `dataset_text_field` and `remove_unused_columns`. We also need to set `skip_prepare_dataset` to `True` to avoid the default processing of the dataset. Below is an example of how to set up the `SFTTrainer`.
716
-
717
- ```python
718
- args.dataset_text_field = "" # needs a dummy field
719
- args.remove_unused_columns = False
720
- args.dataset_kwargs = {"skip_prepare_dataset": True}
721
-
722
- trainer = SFTTrainer(
723
- model=model,
724
- args=args,
725
- data_collator=collate_fn,
726
- train_dataset=train_dataset,
727
- tokenizer=processor.tokenizer,
728
- )
729
- ```
730
-
731
- A full example of training LLaVa 1.5 on the [HuggingFaceH4/llava-instruct-mix-vsft](https://huggingface.co/datasets/HuggingFaceH4/llava-instruct-mix-vsft) dataset can be found in the script [`examples/scripts/vsft_llava.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/vsft_llava.py).
732
-
733
- - [Experiment tracking](https://wandb.ai/huggingface/trl/runs/2b2c5l7s)
734
- - [Trained model](https://huggingface.co/HuggingFaceH4/sft-llava-1.5-7b-hf)
735
-
736
- ## SFTTrainer
737
-
738
- [[autodoc]] SFTTrainer
739
-
740
- ## SFTConfig
741
-
742
- [[autodoc]] SFTConfig
743
-
744
- ## Datasets
745
-
746
- In the SFTTrainer we smartly support `datasets.IterableDataset` in addition to other style datasets. This is useful if you are using large corpora that you do not want to save all to disk. The data will be tokenized and processed on the fly, even when packing is enabled.
747
-
748
- Additionally, in the SFTTrainer, we support pre-tokenized datasets if they are `datasets.Dataset` or `datasets.IterableDataset`. In other words, if such a dataset has a column of `input_ids`, no further processing (tokenization or packing) will be done, and the dataset will be used as-is. This can be useful if you have pretokenized your dataset outside of this script and want to re-use it directly.
749
-
750
- ### ConstantLengthDataset
751
-
752
- [[autodoc]] trainer.ConstantLengthDataset
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
trl_md_files/trainer.mdx DELETED
@@ -1,70 +0,0 @@
1
- # Trainer
2
-
3
- At TRL we support PPO (Proximal Policy Optimisation) with an implementation that largely follows the structure introduced in the paper "Fine-Tuning Language Models from Human Preferences" by D. Ziegler et al. [[paper](https://huggingface.co/papers/1909.08593), [code](https://github.com/openai/lm-human-preferences)].
4
- The Trainer and model classes are largely inspired from `transformers.Trainer` and `transformers.AutoModel` classes and adapted for RL.
5
- We also support a `RewardTrainer` that can be used to train a reward model.
6
-
7
-
8
- ## CPOConfig
9
-
10
- [[autodoc]] CPOConfig
11
-
12
- ## CPOTrainer
13
-
14
- [[autodoc]] CPOTrainer
15
-
16
- ## DDPOConfig
17
-
18
- [[autodoc]] DDPOConfig
19
-
20
- ## DDPOTrainer
21
-
22
- [[autodoc]] DDPOTrainer
23
-
24
- ## DPOTrainer
25
-
26
- [[autodoc]] DPOTrainer
27
-
28
- ## IterativeSFTTrainer
29
-
30
- [[autodoc]] IterativeSFTTrainer
31
-
32
- ## KTOConfig
33
-
34
- [[autodoc]] KTOConfig
35
-
36
- ## KTOTrainer
37
-
38
- [[autodoc]] KTOTrainer
39
-
40
- ## ORPOConfig
41
-
42
- [[autodoc]] ORPOConfig
43
-
44
- ## ORPOTrainer
45
-
46
- [[autodoc]] ORPOTrainer
47
-
48
- ## PPOConfig
49
-
50
- [[autodoc]] PPOConfig
51
-
52
- ## PPOTrainer
53
-
54
- [[autodoc]] PPOTrainer
55
-
56
- ## RewardConfig
57
-
58
- [[autodoc]] RewardConfig
59
-
60
- ## RewardTrainer
61
-
62
- [[autodoc]] RewardTrainer
63
-
64
- ## SFTTrainer
65
-
66
- [[autodoc]] SFTTrainer
67
-
68
- ## set_seed
69
-
70
- [[autodoc]] set_seed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
trl_md_files/using_llama_models.mdx DELETED
@@ -1,160 +0,0 @@
1
- # Using LLaMA models with TRL
2
-
3
- We've begun rolling out examples to use Meta's LLaMA models in `trl` (see [Meta's LLaMA release](https://ai.facebook.com/blog/large-language-model-llama-meta-ai/) for the original LLaMA model).
4
-
5
- ## Efficient training strategies
6
-
7
- Even training the smallest LLaMA model requires an enormous amount of memory. Some quick math: in bf16, every parameter uses 2 bytes (in fp32 4 bytes) in addition to 8 bytes used, e.g., in the Adam optimizer (see the [performance docs](https://huggingface.co/docs/transformers/perf_train_gpu_one#optimizer) in Transformers for more info). So a 7B parameter model would use `(2+8)*7B=70GB` just to fit in memory and would likely need more when you compute intermediate values such as attention scores. So you couldn’t train the model even on a single 80GB A100 like that. You can use some tricks, like more efficient optimizers of half-precision training, to squeeze a bit more into memory, but you’ll run out sooner or later.
8
-
9
- Another option is to use Parameter-Efficient Fine-Tuning (PEFT) techniques, such as the [`peft`](https://github.com/huggingface/peft) library, which can perform low-rank adaptation (LoRA) on a model loaded in 8-bit.
10
- For more on `peft` + `trl`, see the [docs](https://huggingface.co/docs/trl/sentiment_tuning_peft).
11
-
12
- Loading the model in 8bit reduces the memory footprint drastically since you only need one byte per parameter for the weights (e.g. 7B LlaMa is 7GB in memory).
13
- Instead of training the original weights directly, LoRA adds small adapter layers on top of some specific layers (usually the attention layers); thus, the number of trainable parameters is drastically reduced.
14
-
15
- In this scenario, a rule of thumb is to allocate ~1.2-1.4GB per billion parameters (depending on the batch size and sequence length) to fit the entire fine-tuning setup.
16
- This enables fine-tuning larger models (up to 50-60B scale models on a NVIDIA A100 80GB) at low cost.
17
-
18
- Now we can fit very large models into a single GPU, but the training might still be very slow.
19
- The simplest strategy in this scenario is data parallelism: we replicate the same training setup into separate GPUs and pass different batches to each GPU.
20
- With this, you can parallelize the forward/backward passes of the model and scale with the number of GPUs.
21
-
22
- ![chapter10_ddp.png](https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/blog/stackllama/chapter10_ddp.png)
23
-
24
- We use either the `transformers.Trainer` or `accelerate`, which both support data parallelism without any code changes, by simply passing arguments when calling the scripts with `torchrun` or `accelerate launch`. The following runs a training script with 8 GPUs on a single machine with `accelerate` and `torchrun`, respectively.
25
-
26
- ```bash
27
- accelerate launch --multi_gpu --num_machines 1 --num_processes 8 my_accelerate_script.py
28
- torchrun --nnodes 1 --nproc_per_node 8 my_torch_script.py
29
- ```
30
-
31
- ## Supervised fine-tuning
32
-
33
- Before we start training reward models and tuning our model with RL, it helps if the model is already good in the domain we are interested in.
34
- In our case, we want it to answer questions, while for other use cases, we might want it to follow instructions, in which case instruction tuning is a great idea.
35
- The easiest way to achieve this is by continuing to train the language model with the language modeling objective on texts from the domain or task.
36
- The [StackExchange dataset](https://huggingface.co/datasets/HuggingFaceH4/stack-exchange-preferences) is enormous (over 10 million instructions), so we can easily train the language model on a subset of it.
37
-
38
- There is nothing special about fine-tuning the model before doing RLHF - it’s just the causal language modeling objective from pretraining that we apply here.
39
- To use the data efficiently, we use a technique called packing: instead of having one text per sample in the batch and then padding to either the longest text or the maximal context of the model, we concatenate a lot of texts with a EOS token in between and cut chunks of the context size to fill the batch without any padding.
40
-
41
- ![chapter10_preprocessing-clm.png](https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/blog/stackllama/chapter10_preprocessing-clm.png)
42
-
43
- With this approach the training is much more efficient as each token that is passed through the model is also trained in contrast to padding tokens which are usually masked from the loss.
44
- If you don't have much data and are more concerned about occasionally cutting off some tokens that are overflowing the context you can also use a classical data loader.
45
-
46
- The packing is handled by the `ConstantLengthDataset` and we can then use the `Trainer` after loading the model with `peft`. First, we load the model in int8, prepare it for training, and then add the LoRA adapters.
47
-
48
- ```python
49
- # load model in 8bit
50
- model = AutoModelForCausalLM.from_pretrained(
51
- args.model_path,
52
- load_in_8bit=True,
53
- device_map={"": Accelerator().local_process_index}
54
- )
55
- model = prepare_model_for_kbit_training(model)
56
-
57
- # add LoRA to model
58
- lora_config = LoraConfig(
59
- r=16,
60
- lora_alpha=32,
61
- lora_dropout=0.05,
62
- bias="none",
63
- task_type="CAUSAL_LM",
64
- )
65
-
66
- model = get_peft_model(model, config)
67
- ```
68
-
69
- We train the model for a few thousand steps with the causal language modeling objective and save the model.
70
- Since we will tune the model again with different objectives, we merge the adapter weights with the original model weights.
71
-
72
- **Disclaimer:** due to LLaMA's license, we release only the adapter weights for this and the model checkpoints in the following sections.
73
- You can apply for access to the base model's weights by filling out Meta AI's [form](https://docs.google.com/forms/d/e/1FAIpQLSfqNECQnMkycAp2jP4Z9TFX0cGR4uf7b_fBxjY_OjhJILlKGA/viewform) and then converting them to the 🤗 Transformers format by running this [script](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/convert_llama_weights_to_hf.py).
74
- Note that you'll also need to install 🤗 Transformers from source until the `v4.28` is released.
75
-
76
- Now that we have fine-tuned the model for the task, we are ready to train a reward model.
77
-
78
- ## Reward modeling and human preferences
79
-
80
- In principle, we could fine-tune the model using RLHF directly with the human annotations.
81
- However, this would require us to send some samples to humans for rating after each optimization iteration.
82
- This is expensive and slow due to the number of training samples needed for convergence and the inherent latency of human reading and annotator speed.
83
-
84
- A trick that works well instead of direct feedback is training a reward model on human annotations collected before the RL loop.
85
- The goal of the reward model is to imitate how a human would rate a text. There are several possible strategies to build a reward model: the most straightforward way would be to predict the annotation (e.g. a rating score or a binary value for “good”/”bad”).
86
- In practice, what works better is to predict the ranking of two examples, where the reward model is presented with two candidates `(y_k, y_j)` for a given prompt `x` and has to predict which one would be rated higher by a human annotator.
87
-
88
- With the StackExchange dataset, we can infer which of the two answers was preferred by the users based on the score.
89
- With that information and the loss defined above, we can then modify the `transformers.Trainer` by adding a custom loss function.
90
-
91
- ```python
92
- class RewardTrainer(Trainer):
93
- def compute_loss(self, model, inputs, return_outputs=False):
94
- rewards_j = model(input_ids=inputs["input_ids_j"], attention_mask=inputs["attention_mask_j"])[0]
95
- rewards_k = model(input_ids=inputs["input_ids_k"], attention_mask=inputs["attention_mask_k"])[0]
96
- loss = -nn.functional.logsigmoid(rewards_j - rewards_k).mean()
97
- if return_outputs:
98
- return loss, {"rewards_j": rewards_j, "rewards_k": rewards_k}
99
- return loss
100
- ```
101
-
102
- We utilize a subset of a 100,000 pair of candidates and evaluate on a held-out set of 50,000. With a modest training batch size of 4, we train the Llama model using the LoRA `peft` adapter for a single epoch using the Adam optimizer with BF16 precision. Our LoRA configuration is:
103
-
104
- ```python
105
- peft_config = LoraConfig(
106
- task_type=TaskType.SEQ_CLS,
107
- inference_mode=False,
108
- r=8,
109
- lora_alpha=32,
110
- lora_dropout=0.1,
111
- )
112
- ```
113
- As detailed in the next section, the resulting adapter can be merged into the frozen model and saved for further downstream use.
114
-
115
- ## Reinforcement Learning from Human Feedback
116
-
117
- With the fine-tuned language model and the reward model at hand, we are now ready to run the RL loop. It follows roughly three steps:
118
-
119
- 1. Generate responses from prompts,
120
- 2. Rate the responses with the reward model,
121
- 3. Run a reinforcement learning policy-optimization step with the ratings.
122
-
123
- The Query and Response prompts are templated as follows before being tokenized and passed to the model:
124
-
125
- ```bash
126
- Question: <Query>
127
-
128
- Answer: <Response>
129
- ```
130
-
131
- The same template was used for SFT, RM and RLHF stages.
132
- Once more, we utilize `peft` for memory-efficient training, which offers an extra advantage in the RLHF context.
133
- Here, the reference model and policy share the same base, the SFT model, which we load in 8-bit and freeze during training.
134
- We exclusively optimize the policy's LoRA weights using PPO while sharing the base model's weights.
135
-
136
- ```python
137
- for epoch, batch in tqdm(enumerate(ppo_trainer.dataloader)):
138
- question_tensors = batch["input_ids"]
139
-
140
- # sample from the policy and to generate responses
141
- response_tensors = ppo_trainer.generate(
142
- question_tensors,
143
- return_prompt=False,
144
- length_sampler=output_length_sampler,
145
- **generation_kwargs,
146
- )
147
- batch["response"] = tokenizer.batch_decode(response_tensors, skip_special_tokens=True)
148
-
149
- # Compute sentiment score
150
- texts = [q + r for q, r in zip(batch["query"], batch["response"])]
151
- pipe_outputs = sentiment_pipe(texts, **sent_kwargs)
152
- rewards = [torch.tensor(output[0]["score"] - script_args.reward_baseline) for output in pipe_outputs]
153
-
154
- # Run PPO step
155
- stats = ppo_trainer.step(question_tensors, response_tensors, rewards)
156
- # Log stats to Wandb
157
- ppo_trainer.log_stats(stats, batch, rewards)
158
- ```
159
-
160
- For the rest of the details and evaluation, please refer to our [blog post on StackLLaMA](https://huggingface.co/blog/stackllama).