{
  "@context": "https://schema.org",
  "@id": "https://aggr.aymericbeaumet.com/items/philschmid-de/2025-01-23-how-to-align-open-llms-in-2025-with-dpo-and-and-synthetic/#webpage",
  "@type": [
    "WebPage",
    "ArchiveComponent"
  ],
  "articleBody": "Large Language Models (LLMs) continued their important role in 2024, with several major developments completely outperforming previous models. The focus continued to more smaller, more powerful models from companies like Meta, Qwen, or Google. These models not only became more powerful, but also more efficient.\n\nPart of the reason is the continued scaling of post-training methods and datasets. Post-training methods like [Direct Preference Optimization (DPO)](https://huggingface.co/papers/2305.18290), [Proximal Policy Optimization (PPO)](https://huggingface.co/papers/2203.02155), and [Group Preference Optimization (GRPO)](https://huggingface.co/papers/2310.11523) have been used to align models with human preferences and improve performance.\n\nContinuing from [How to fine-tune open LLMs in 2025 with Hugging Face](https://www.philschmid.de/fine-tune-llms-in-2025), this guide focuses on aligning models using Direct Preference Optimization (DPO). We'll build upon our previously fine-tuned model from the [Fine-Tune LLMs in 2025](https://www.philschmid.de/fine-tune-llms-in-2025) guide and improve it further through preference learning.\n\nBefore we start, let's take a look at the [Direct Preference Optimization (DPO)](https://huggingface.co/papers/2305.18290) paper and understand how it works.\n\n**What is Direct Preference Optimization (DPO)?**\n\n[Direct Preference Optimization (DPO)](https://huggingface.co/papers/2305.18290) is a simplified approach to align language models with human preferences. Unlike traditional RLHF methods that require training a separate reward model and using complex PPO optimization, DPO treats the alignment problem as a classification task on preference data. This makes it more stable, efficient, and computationally lightweight compared to alternatives.\n\n- **Simplicity**: DPO eliminates the need for a separate reward model and complex RL optimization, making it easier to implement and debug\n- **Stability**: By avoiding the instabilities of PPO training, DPO provides more reliable convergence\n- **Efficiency**: The direct optimization approach requires less compute and fewer hyperparameters than traditional RLHF\n- **Performance**: Despite its simplicity, DPO achieves comparable results\n\n**Overview**\n\nIn this guide, we'll use offline DPO with on-Policy data. Offline DPO is the more compute-efficient, meaning we don't need a Reward model during training in memory. However, we will be staying on-policy. We'll first generate samples from the Supervised Fine-Tuned (SFT) model we trained in the previous guide and score them with a rule-based reward model that checks answer correctness. These scores will then be used to create preference pairs (a \"preferred\" and a \"rejected\" response) for DPO training.\n\nIf you are going to adjust the example to your own use case, which cannot be verified with a rule-based reward model, you can use a generic reward model like [nicolinho/QRM-Llama3.1-8B-v2](https://huggingface.co/nicolinho/QRM-Llama3.1-8B-v2), which ranks in the top 10 on reward bench or LLM as judge based on your own criteria.\n\nYou will learn how to:\n\n1. [Setup the development environment](https://www.philschmid.de/rl-with-llms-in-2025-dpo#1-setup-development-environment)\n2. [Create on-policy preference dataset from model outputs](https://www.philschmid.de/rl-with-llms-in-2025-dpo#2-create-on-policy-preference-dataset-from-model-outputs)\n3. [Align the model using DPO and the Hugging Face `DPOTrainer`](https://www.philschmid.de/rl-with-llms-in-2025-dpo#3-align-the-model-using-dpo-and-the-hugging-face-dpotrainer)\n4. [Test and evaluate the aligned model](https://www.philschmid.de/rl-with-llms-in-2025-dpo#4-test-and-evaluate-the-aligned-model)\n\n*Note: This guide is designed for consumer GPUs (24GB+) like the NVIDIA RTX 4090/5090 or A10G, but can be adapted for larger systems.*\n\n## 1\\. Setup development environment\n\nOur first step is to install Hugging Face Libraries and Pytorch, vllm, and trl, transformers and datasets. If you haven't heard of trl yet, don't worry. It is a new library on top of transformers and datasets, which makes it easier to fine-tune, rlhf, align open LLMs.\n\nPython\n\n```python\n# Install Pytorch & other libraries, make sure to match your GPU driver version\n%pip install \"torch==2.5.1\" vllm tensorboard  \"setuptools<71.0.0\" openai \"lm-eval[api]==0.4.5\"  --index-url https://download.pytorch.org/whl/cu121\n \n# Install flash-attn\n%pip install flash-attn \n \n# Install Hugging Face libraries\n%pip install  --upgrade \\\n  \"transformers==4.48.1\" \\\n  \"datasets==3.1.0\" \\\n  \"accelerate==1.3.0\" \\\n  \"bitsandbytes==0.45.0\" \\\n  \"peft==0.14.0\" \\\n  \"hf-transfer==0.1.9\" \\\n  \"trl==0.13.0\"\n```\n\n*Note: you may need to restart the kernel to use updated packages.*\n\nWe will use the [Hugging Face Hub](https://huggingface.co/models) as a remote model versioning service. This means we will automatically push our model, logs and information to the Hub during training. You must register on the [Hugging Face](https://huggingface.co/join) for this. After you have an account, we will use the `login` util from the `huggingface_hub` package to log into our account and store our token (access key) on the disk.\n\nPython\n\n```python\nfrom huggingface_hub import login\n \nlogin(token=\"\", add_to_git_credential=True) # ADD YOUR TOKEN HERE\n```\n\n## 2\\. Create on-policy preference dataset from model outputs\n\nWe are going to generate a preference dataset from our SFT model rather than using a different model and off-policy data. On-policy data is generated from the model being trained, which means the preference pairs directly reflect the model's current capabilities and output distribution. This makes the training more relevant and effective.\n\nStudies have shown that leveraging on-policy preference data leads to better performance compared to off-policy approaches. [REF 1](https://arxiv.org/abs/2404.14367), [REF 2](https://arxiv.org/abs/2403.10160).\n\nAs we are building on our previous fine-tuned model we want to furhter improve the performance on MATH related tasks. We will use the prompts from [philschmid/DMath](https://huggingface.co/datasets/philschmid/DMath). DMath (Diverse Math Word Problems) is a collection of 10K high-quality grade school-level math word problems for the paper [\"It Ain't Over: A Multi-aspect Diverse Math Word Problem Dataset\"](https://aclanthology.org/2023.emnlp-main.927.pdf). Each solution will be scored by a rule-based reward model that checks answer correctness using a regex. (Thats a very simple and naive approach, better would to additionally use specific format extraction, e.g. \"The Answer is: \\[ANSWER\\]\" or additional LLM Judge). If the solution is correct, it will be labeled as preferred, otherwise as rejected. Based on the score we will create difference preference pairs.\n\nI prepared [create\\_preference\\_dataset.py](https://github.com/philschmid/deep-learning-pytorch-huggingface/blob/main/training/scripts/dpo/create_preference_dataset.py) script to generate the dataset. The dataset will be saved to the Hugging Face Hub. We are going to generate 4 solutions for each input hoping to have at least one correct solution and one incorrect solution. If we don't have a pair we will skip the input.\n\nPython\n\n```python\npython scripts/dpo/create_preference_dataset.py --dataset_id philschmid/DMath --sample_size 5000 --generation_model_name_or_path philschmid/llama-3-1-8b-math-orca-spectrum-10k-ep1 --num_solutions 4 --batch_size 16 \n```\n\n*Note: You can skip this step and used the generated preference dataset from me [philschmid/philschmid-llama-3-1-8b-math-orca-spectr-philschmid-DMath-candidates](https://huggingface.co/philschmid/philschmid-llama-3-1-8b-math-orca-spectr-philschmid-DMath-candidates). It includes 1.9k prefence pairs.*\n\n## 3\\. Align the model using DPO and the Hugging Face DPOTrainer\n\nTRL supports the DPO through a dedicated [DPOTrainer](https://huggingface.co/docs/trl/dpo_trainer) for aligning LLMs from preference data, as described in [Direct Preference Optimization: Your Language Model is Secretly a Reward Model](https://huggingface.co/papers/2305.18290). The `DPOTrainer` is a subclass of the `Trainer` from the `transformers` library and supports all the same features, including logging, checkpointing, distributed training, and parameter efficient fine-tuning (PEFT). [Direct Preference Optimization (DPO)](https://huggingface.co/papers/2305.18290) aligns LLMs with human preferences using 'prompt', 'chosen', and 'rejected' columns, where each 'prompt' is paired with a 'chosen' response that aligns with human preferences and a 'rejected' response that does not.\n\nWe prepared a [run\\_dpo.py](https://github.com/philschmid/deep-learning-pytorch-huggingface/blob/main/training/scripts/dpo/run_dpo.py) scripts, which supports providing a yaml configuration file. This allows you to easily change the model, dataset, hyperparameters, and other settings. This is done by using the `TrlParser`, which parses the yaml file and converts it into the `TrainingArguments` arguments.\n\nBased on the [Alignment Handbook](https://github.com/huggingface/alignment-handbook) we know that we need to use a ~10-100x smaller learning rate for DPO compared to SFT. In our example we reduce the learning rate from 2e-4 (SFT) to 5e-6 (DPO). Another important parameter is the `beta` parameter, which is used to control the strength of the alignment, typically something in the range of 0.1 to 0.5. A higher beta means less divergence from the initial reference model or the text generations are very similar in terms of their probability distributions.\n\nThe script is kept very simple and is easy to understand. This should help you understand, customize and extend the script for your own use case. We define `dataclasses` for our arguments. Every argument can then be provided either via the command line or by providing a yaml configuration file. That way we have better type safety and intellisense support.\n\nPython\n\n```python\n# ....\n \n@dataclass\nclass ScriptArguments:\n    dataset_id_or_path: str\n    ...\n# ....\n```\n\nThe training script is separated by `#######` blocks for the different parts of the script. The main training function:\n\n1. Logs all hyperperparameters\n2. Loads the dataset and Tokenizer from Hugging Face Hub or local disk\n3. Prepares the DPO dataset correctly using the `prompt`, `chosen` and `rejected` column\n4. Loads the policy model and/or reference model\n5. Instantiate DPO trainer and starts the training loop (optionally continue training from a checkpoint)\n6. Saves the model and optionally pushes it to the Hugging Face Hub\n\nBelow is an example recipe of how we train [Llama 8B model with DPO and Q-LoRA](https://github.com/philschmid/deep-learning-pytorch-huggingface/blob/main/training/receipes/dpo-llama-3-1-8b-qlora.yaml).\n\nYAML\n\n```yaml\n# Model arguments\nmodel_name_or_path: philschmid/llama-3-1-8b-math-orca-spectrum-10k-ep1\ntokenizer_name_or_path: philschmid/llama-3-1-8b-math-orca-spectrum-10k-ep1\nmodel_revision: main\ntorch_dtype: bfloat16\nattn_implementation: flash_attention_2\nuse_liger: false\nbf16: true\ntf32: true\noutput_dir: runs/dpo-llama-3-1-8b-math-ep3\n \n# Dataset arguments\ndataset_id_or_path: philschmid/philschmid-llama-3-1-8b-math-orca-spectr-philschmid-DMath-candidates\n \n# LoRA arguments\nuse_peft: true\nload_in_4bit: true\nlora_target_modules: \"all-linear\"\n# important as we need to train the special tokens for the chat template of llama \nlora_modules_to_save: [\"lm_head\", \"embed_tokens\"] # you might need to change this for qwen or other models\nlora_r: 16\nlora_alpha: 16\n \n# Training arguments\nbeta: 0.1\nmax_length: 1536\nmax_prompt_length: 768\nloss_type: sigmoid # default loss, alternatives: https://huggingface.co/docs/trl/dpo_trainer#loss-functions\nnum_train_epochs: 3\nper_device_train_batch_size: 1 \ngradient_accumulation_steps: 8\ngradient_checkpointing: true\ngradient_checkpointing_kwargs:\n  use_reentrant: false\nlearning_rate: 5.0e-6 \nlr_scheduler_type: constant\nwarmup_ratio: 0.03\n \n# Logging arguments\nlogging_strategy: steps\nlogging_steps: 5\nreport_to:\n- tensorboard\nsave_strategy: \"epoch\"\nseed: 42\n \n# Hugging Face Hub \npush_to_hub: true\n  # hub_model_id: llama-3-1-8b-math-orca-qlora-10k-ep1 # if not defined same as output_dir\nhub_strategy: every_save\n```\n\nThis config can be used for single-GPU training (~24GB GPU Memory), if you have more memory available you can increase the `per_device_train_batch_size` and for multi-GPU training with DeepSpeed (see Appendix for full\n\n\\_Note: I ran the script on 1x H100 with a batch size of 8 and 8 gradient accumulation steps. This took ~1 hours to complete.\\_command).\n\nPython\n\n```python\n!python scripts/dpo/run_dpo.py --config receipes/dpo-llama-3-1-8b-qlora.yaml\n```\n\n*Note: During the training we want to minimize loss and grow reward/margins metrics. Keep an eye on the reward/margins metrics, if they are not growing you might need to increase the beta parameter or adjust the learning\\_rate.*\n\nUsing Q-LoRA only saves the trained adapter weights. If you want to use the model as standalone model, e.g. for inference you might want to merge the adapter and base model. This can be done using the following command:\n\nPython\n\n```python\n!python scripts/merge_adapter_weights.py --peft_model_id runs/dpo-llama-3-1-8b-math-ep3 --push_to_hub True --repository_id dpo-llama-3-1-8b-math-ep3-merged\n```\n\n## 4\\. Test and evaluate the aligned model\n\nAfter the training is done we want to evaluate and test our model. Similar to our SFT model, we will evaluate the model on [GSM8K](https://huggingface.co/datasets/openai/gsm8k) dataset to see if it improved performance. GSM8K (Grade School Math 8K) is a dataset of 8.5K high quality linguistically diverse grade school math word problems. The dataset was created to support the task of question answering on basic mathematical problems that require multi-step reasoning.\n\nEvaluating Generative AI models is not a trivial task since 1 input can have multiple correct outputs. If you want to learn more about evaluating generative models, check out:\n\n- [Evaluate LLMs and RAG a practical example using Langchain and Hugging Face](https://www.philschmid.de/evaluate-llm).\n- [Evaluate LLMs using Evaluation Harness and Hugging Face TGI/vLLM](https://www.philschmid.de/evaluate-llms-with-lm-eval-and-tgi-vllm)\n- [LLM Evaluation doesn't need to be complicated](https://www.philschmid.de/llm-evaluation)\n- [Evaluating Open LLMs with MixEval: The Closest Benchmark to LMSYS Chatbot Arena](https://www.philschmid.de/evaluate-llm-mixeval)\n\nWe are going to use [Evaluation Harness](https://github.com/EleutherAI/lm-evaluation-harness) an open-source framework to evaluate language models on a wide range of tasks and benchmarks. The frameworks support evaluating models behind OpenAI compatible API endpoints, those can be locally or remotely. This super helpful as we can evaluate our model in the same environment we will use for production.\n\nWe are going to use [Text Generation Inference (TGI)](https://github.com/huggingface/text-generation-inference) for testing and deploying our model. TGI is a purpose-built solution for deploying and serving Large Language Models (LLMs). TGI enables high-performance text generation using Tensor Parallelism and continous batching. If you are or want to use vLLM you can check the Appendix on how to start the inference server.\n\n*Note: Make sure that you have enough GPU memory to run the container. Restart kernel to remove all allocated GPU memory from the notebook.*\n\nWe will start the on 1 GPU detached. Meaning we can can continue to use the notebook while the container is running. If you have more GPUs you can change the `--gpus` and `--num-shard` flags to the number of GPUs.\n\nBash\n\n```bash\n%%bash\n \nnum_gpus=1\nmodel_id=philschmid/dpo-llama-3-1-8b-math-ep3-merged # replace with your model id\n \ndocker run --name tgi --gpus ${num_gpus} -d -ti -p 8080:80 --shm-size=2GB \\\n  -e HF_TOKEN=$(cat ~/.cache/huggingface/token) \\\n  ghcr.io/huggingface/text-generation-inference:3.0.1 \\\n  --model-id ${model_id} \\\n  --num-shard ${num_gpus}\n \n```\n\nOur container will now start in the background and download the model from Hugging Face Hub. We can check the logs to see the progress with `docker logs -f tgi`.\n\nOnce our container is running we can send requests using the `openai` or `huggingface_hub` sdk. Here we ll use the `openai` sdk to send a request to our inference server. If you don't have the `openai` sdk installed you can install it using `pip install openai`.\n\nPython\n\n```python\nfrom openai import OpenAI\n \n# create client \nclient = OpenAI(base_url=\"http://localhost:8080/v1\",api_key=\"-\")\n \nsystem_message = \"\"\"Solve the given high school math problem by providing a clear explanation of each step leading to the final solution.\n \nProvide a detailed breakdown of your calculations, beginning with an explanation of the problem and describing how you derive each formula, value, or conclusion. Use logical steps that build upon one another, to arrive at the final answer in a systematic manner.\n \n# Steps\n \n1. **Understand the Problem**: Restate the given math problem and clearly identify the main question and any important given values.\n2. **Set Up**: Identify the key formulas or concepts that could help solve the problem (e.g., algebraic manipulation, geometry formulas, trigonometric identities).\n3. **Solve Step-by-Step**: Iteratively progress through each step of the math problem, justifying why each consecutive operation brings you closer to the solution.\n4. **Double Check**: If applicable, double check the work for accuracy and sense, and mention potential alternative approaches if any.\n5. **Final Answer**: Provide the numerical or algebraic solution clearly, accompanied by appropriate units if relevant.\n \n# Notes\n \n- Always clearly define any variable or term used.\n- Wherever applicable, include unit conversions or context to explain why each formula or step has been chosen.\n- Assume the level of mathematics is suitable for high school, and avoid overly advanced math techniques unless they are common at that level.\n- Return the final in an extra line. Staring with \"The Answer is: [ANSWER]\"\n \n# Examples\n\"\"\"\n \nmessages = [\n    {\"role\": \"system\", \"content\": system_message},\n    # {\"role\": \"user\", \"content\": \"If you converted $140 to 158760 Korean Won, how much is $1 in Korean Won?\"},\n    {\"role\": \"user\", \"content\": \"Q: Henry and 3 of his friends order 7 pizzas for lunch. Each pizza is cut into 8 slices. If Henry and his friends want to share the pizzas equally, how many slices can each of them have?\\nA:\"},\n    # {\"role\": \"user\", \"content\": \"The rectangular-shaped cell phone is 9 centimeters (cm) wide and 46 centimeters (cm) in circumference. Find the vertical length of the cell phone?\"},\n]\nexpected_answer = \"14\"\n \n \n# Take a random sample from the dataset and remove the last message and send it to the model\n \nresponse = client.chat.completions.create(\n    model=\"philschmid/dpo-llama-3-1-8b-math-ep3-merged\",\n    messages=messages,\n    stream=False, # no streaming\n    max_tokens=1024,\n    temperature=1.0)\nresponse = response.choices[0].message.content\n \n# Print results\nprint(f\"Query:\\n{messages[1]['content']}\")\nprint(f\"Original Answer:\\n{expected_answer}\")\nprint(f\"Generated Answer:\\n{response}\")\n \n```\n\nAwesome that looks great! Now we can evaluate our model with the [Evaluation Harness](https://github.com/EleutherAI/lm-evaluation-harness).\n\n*Note: Make sure to change the model id to your fine-tuned model.*\n\nPython\n\n```python\n!lm_eval --model local-chat-completions \\\n  --tasks gsm8k_cot \\\n  --model_args model=philschmid/dpo-llama-3-1-8b-math-ep3-merged,base_url=http://localhost:8080/v1/chat/completions,num_concurrent=8,max_retries=10,tokenized_requests=False,timeout=180,max_length=4096 \\\n  --apply_chat_template \\\n  --fewshot_as_multiturn\n```\n\nWow, 59% accuracy, thats a 5% improvement from our SFT model, using only ~2k preference pairs for 3 epochs. That shows that our script and config is working correctly.\n\n*Note: You might be able to achieve better results with more data, more epochs or tuning the hyperparameters (beta, learning rate, batch size, etc.). I ran some ablations on multi-gpu training and full training with DeepSpeed (see Appendix for full command) and the best results was 62% accuracy.*\n\nPython\n\n```python\n!docker stop tgi\n!docker rm tgi\n```\n\n## Conclusion\n\nIn this guide, we successfully aligned a Llama 3.1 8B model using Direct Preference Optimization (DPO) and achieved a 5% improvement on GSM8K compared to our SFT baseline. Instead of using off-policy preference data (like existing human preference datasets), we generated our own preference pairs using the SFT model we wanted to align. This approach has several advantages:\n\n- The preference pairs directly reflect the model's current capabilities and output distribution\n- We could automatically evaluate responses using a rule-based reward model for math problems\n- The training becomes more focused and effective since we're optimizing for the specific behaviors we want to improve\n\nWe also learned that even with a relatively small dataset (~2k preference pairs) and just 3 epochs of training, DPO can produce meaningful improvements in model performance. **The** combination of on-policy data generation and DPO provides a practical and efficient approach to aligning language models with specific objectives. This method could be adapted for various domains beyond math problems by using different reward models or evaluation criteria to generate preference pairs.\n\n## Appendix\n\n*Note: Make sure to install deepspeed and accelerate before running the commands. `pip install deepspeed==0.15.4`*\n\n### Distributed Training\n\nBash\n\n```bash\nACCELERATE_LOG_LEVEL=info accelerate launch --num_processes 4 --config_file configs/accelerate_configs/deepspeed_zero3.yaml scripts/dpo/run_dpo.py --config receipes/dpo-llama-3-1-8b.yaml\n```\n",
  "authors": [],
  "captured_at": "2026-09-27T19:29:15.293681927+00:00",
  "category": "programming",
  "content_html": "<p>Large Language Models (LLMs) continued their important role in 2024, with several major developments completely outperforming previous models. The focus continued to more smaller, more powerful models from companies like Meta, Qwen, or Google. These models not only became more powerful, but also more efficient.</p>\n<p>Part of the reason is the continued scaling of post-training methods and datasets. Post-training methods like <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/papers/2305.18290\">Direct Preference Optimization (DPO)</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/papers/2203.02155\">Proximal Policy Optimization (PPO)</a>, and <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/papers/2310.11523\">Group Preference Optimization (GRPO)</a> have been used to align models with human preferences and improve performance.</p>\n<p>Continuing from <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.philschmid.de/fine-tune-llms-in-2025\">How to fine-tune open LLMs in 2025 with Hugging Face</a>, this guide focuses on aligning models using Direct Preference Optimization (DPO). We'll build upon our previously fine-tuned model from the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.philschmid.de/fine-tune-llms-in-2025\">Fine-Tune LLMs in 2025</a> guide and improve it further through preference learning.</p>\n<p>Before we start, let's take a look at the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/papers/2305.18290\">Direct Preference Optimization (DPO)</a> paper and understand how it works.</p>\n<p><strong>What is Direct Preference Optimization (DPO)?</strong></p>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/papers/2305.18290\">Direct Preference Optimization (DPO)</a> is a simplified approach to align language models with human preferences. Unlike traditional RLHF methods that require training a separate reward model and using complex PPO optimization, DPO treats the alignment problem as a classification task on preference data. This makes it more stable, efficient, and computationally lightweight compared to alternatives.</p>\n<ul>\n<li><strong>Simplicity</strong>: DPO eliminates the need for a separate reward model and complex RL optimization, making it easier to implement and debug</li>\n<li><strong>Stability</strong>: By avoiding the instabilities of PPO training, DPO provides more reliable convergence</li>\n<li><strong>Efficiency</strong>: The direct optimization approach requires less compute and fewer hyperparameters than traditional RLHF</li>\n<li><strong>Performance</strong>: Despite its simplicity, DPO achieves comparable results</li>\n</ul>\n<p><strong>Overview</strong></p>\n<p>In this guide, we'll use offline DPO with on-Policy data. Offline DPO is the more compute-efficient, meaning we don't need a Reward model during training in memory. However, we will be staying on-policy. We'll first generate samples from the Supervised Fine-Tuned (SFT) model we trained in the previous guide and score them with a rule-based reward model that checks answer correctness. These scores will then be used to create preference pairs (a &quot;preferred&quot; and a &quot;rejected&quot; response) for DPO training.</p>\n<p>If you are going to adjust the example to your own use case, which cannot be verified with a rule-based reward model, you can use a generic reward model like <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/nicolinho/QRM-Llama3.1-8B-v2\">nicolinho/QRM-Llama3.1-8B-v2</a>, which ranks in the top 10 on reward bench or LLM as judge based on your own criteria.</p>\n<p>You will learn how to:</p>\n<ol>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.philschmid.de/rl-with-llms-in-2025-dpo#1-setup-development-environment\">Setup the development environment</a></li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.philschmid.de/rl-with-llms-in-2025-dpo#2-create-on-policy-preference-dataset-from-model-outputs\">Create on-policy preference dataset from model outputs</a></li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.philschmid.de/rl-with-llms-in-2025-dpo#3-align-the-model-using-dpo-and-the-hugging-face-dpotrainer\">Align the model using DPO and the Hugging Face <code>DPOTrainer</code></a></li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.philschmid.de/rl-with-llms-in-2025-dpo#4-test-and-evaluate-the-aligned-model\">Test and evaluate the aligned model</a></li>\n</ol>\n<p><em>Note: This guide is designed for consumer GPUs (24GB+) like the NVIDIA RTX 4090/5090 or A10G, but can be adapted for larger systems.</em></p>\n<h2>1. Setup development environment</h2>\n<p>Our first step is to install Hugging Face Libraries and Pytorch, vllm, and trl, transformers and datasets. If you haven't heard of trl yet, don't worry. It is a new library on top of transformers and datasets, which makes it easier to fine-tune, rlhf, align open LLMs.</p>\n<p>Python</p>\n<pre><code class=\"language-python\"><span class=\"code-snippet\" data-language=\"Python\"><span class=\"syntax-source syntax-python\"><span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span> Install Pytorch &amp; other libraries, make sure to match your GPU driver version\n</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">%</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">pip</span></span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">install</span></span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">torch==2.5.1<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">vllm</span></span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">tensorboard</span></span>  <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">setuptools&lt;71.0.0<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">openai</span></span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">lm-eval[api]==0.4.5<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span>  <span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">index</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">url</span></span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">https</span></span><span class=\"syntax-punctuation syntax-separator syntax-annotation syntax-variable syntax-python\">:</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">/</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">/</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">download</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span><span class=\"syntax-meta syntax-generic-name syntax-python\">pytorch</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span><span class=\"syntax-meta syntax-generic-name syntax-python\">org</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">/</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">whl</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">/</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">cu121</span></span>\n \n<span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span> Install flash-attn\n</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">%</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">pip</span></span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">install</span></span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">flash</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">attn</span></span> \n \n<span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span> Install Hugging Face libraries\n</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">%</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">pip</span></span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">install</span></span>  <span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">upgrade</span></span> <span class=\"syntax-punctuation syntax-separator syntax-continuation syntax-line syntax-python\">\\</span>\n  <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">transformers==4.48.1<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span> <span class=\"syntax-punctuation syntax-separator syntax-continuation syntax-line syntax-python\">\\</span>\n  <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">datasets==3.1.0<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span> <span class=\"syntax-punctuation syntax-separator syntax-continuation syntax-line syntax-python\">\\</span>\n  <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">accelerate==1.3.0<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span> <span class=\"syntax-punctuation syntax-separator syntax-continuation syntax-line syntax-python\">\\</span>\n  <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">bitsandbytes==0.45.0<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span> <span class=\"syntax-punctuation syntax-separator syntax-continuation syntax-line syntax-python\">\\</span>\n  <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">peft==0.14.0<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span> <span class=\"syntax-punctuation syntax-separator syntax-continuation syntax-line syntax-python\">\\</span>\n  <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">hf-transfer==0.1.9<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span> <span class=\"syntax-punctuation syntax-separator syntax-continuation syntax-line syntax-python\">\\</span>\n  <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">trl==0.13.0<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span>\n</span></span></code></pre>\n<p><em>Note: you may need to restart the kernel to use updated packages.</em></p>\n<p>We will use the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/models\">Hugging Face Hub</a> as a remote model versioning service. This means we will automatically push our model, logs and information to the Hub during training. You must register on the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/join\">Hugging Face</a> for this. After you have an account, we will use the <code>login</code> util from the <code>huggingface_hub</code> package to log into our account and store our token (access key) on the disk.</p>\n<p>Python</p>\n<pre><code class=\"language-python\"><span class=\"code-snippet\" data-language=\"Python\"><span class=\"syntax-source syntax-python\"><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-keyword syntax-control syntax-import syntax-from syntax-python\">from</span></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-meta syntax-import-source syntax-python\"> <span class=\"syntax-meta syntax-import-path syntax-python\"><span class=\"syntax-meta syntax-import-name syntax-python\">huggingface_hub</span></span> <span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-keyword syntax-control syntax-import syntax-python\">import</span></span></span></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"> <span class=\"syntax-meta syntax-generic-name syntax-python\">login</span></span>\n \n<span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">login</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-variable syntax-parameter syntax-python\">token</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span> <span class=\"syntax-variable syntax-parameter syntax-python\">add_to_git_credential</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-constant syntax-language syntax-python\">True</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span> <span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span> ADD YOUR TOKEN HERE\n</span></span></span></code></pre>\n<h2>2. Create on-policy preference dataset from model outputs</h2>\n<p>We are going to generate a preference dataset from our SFT model rather than using a different model and off-policy data. On-policy data is generated from the model being trained, which means the preference pairs directly reflect the model's current capabilities and output distribution. This makes the training more relevant and effective.</p>\n<p>Studies have shown that leveraging on-policy preference data leads to better performance compared to off-policy approaches. <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2404.14367\">REF 1</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://arxiv.org/abs/2403.10160\">REF 2</a>.</p>\n<p>As we are building on our previous fine-tuned model we want to furhter improve the performance on MATH related tasks. We will use the prompts from <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/datasets/philschmid/DMath\">philschmid/DMath</a>. DMath (Diverse Math Word Problems) is a collection of 10K high-quality grade school-level math word problems for the paper <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://aclanthology.org/2023.emnlp-main.927.pdf\">&quot;It Ain't Over: A Multi-aspect Diverse Math Word Problem Dataset&quot;</a>. Each solution will be scored by a rule-based reward model that checks answer correctness using a regex. (Thats a very simple and naive approach, better would to additionally use specific format extraction, e.g. &quot;The Answer is: [ANSWER]&quot; or additional LLM Judge). If the solution is correct, it will be labeled as preferred, otherwise as rejected. Based on the score we will create difference preference pairs.</p>\n<p>I prepared <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/philschmid/deep-learning-pytorch-huggingface/blob/main/training/scripts/dpo/create_preference_dataset.py\">create_preference_dataset.py</a> script to generate the dataset. The dataset will be saved to the Hugging Face Hub. We are going to generate 4 solutions for each input hoping to have at least one correct solution and one incorrect solution. If we don't have a pair we will skip the input.</p>\n<p>Python</p>\n<pre><code class=\"language-python\"><span class=\"code-snippet\" data-language=\"Python\"><span class=\"syntax-source syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">python</span></span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">scripts</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">/</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">dpo</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">/</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">create_preference_dataset</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span><span class=\"syntax-meta syntax-generic-name syntax-python\">py</span></span> <span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">dataset_id</span></span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">philschmid</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">/</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">DMath</span></span> <span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">sample_size</span></span> <span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">5000</span> <span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">generation_model_name_or_path</span></span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">philschmid</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">/</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">llama</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">3</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">1</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span>8b<span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">math</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">orca</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">spectrum</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span>10k<span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">ep1</span></span> <span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">num_solutions</span></span> <span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">4</span> <span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">batch_size</span></span> <span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">16</span> \n</span></span></code></pre>\n<p><em>Note: You can skip this step and used the generated preference dataset from me <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/philschmid/philschmid-llama-3-1-8b-math-orca-spectr-philschmid-DMath-candidates\">philschmid/philschmid-llama-3-1-8b-math-orca-spectr-philschmid-DMath-candidates</a>. It includes 1.9k prefence pairs.</em></p>\n<h2>3. Align the model using DPO and the Hugging Face DPOTrainer</h2>\n<p>TRL supports the DPO through a dedicated <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/docs/trl/dpo_trainer\">DPOTrainer</a> for aligning LLMs from preference data, as described in <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/papers/2305.18290\">Direct Preference Optimization: Your Language Model is Secretly a Reward Model</a>. The <code>DPOTrainer</code> is a subclass of the <code>Trainer</code> from the <code>transformers</code> library and supports all the same features, including logging, checkpointing, distributed training, and parameter efficient fine-tuning (PEFT). <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/papers/2305.18290\">Direct Preference Optimization (DPO)</a> aligns LLMs with human preferences using 'prompt', 'chosen', and 'rejected' columns, where each 'prompt' is paired with a 'chosen' response that aligns with human preferences and a 'rejected' response that does not.</p>\n<p>We prepared a <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/philschmid/deep-learning-pytorch-huggingface/blob/main/training/scripts/dpo/run_dpo.py\">run_dpo.py</a> scripts, which supports providing a yaml configuration file. This allows you to easily change the model, dataset, hyperparameters, and other settings. This is done by using the <code>TrlParser</code>, which parses the yaml file and converts it into the <code>TrainingArguments</code> arguments.</p>\n<p>Based on the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/huggingface/alignment-handbook\">Alignment Handbook</a> we know that we need to use a ~10-100x smaller learning rate for DPO compared to SFT. In our example we reduce the learning rate from 2e-4 (SFT) to 5e-6 (DPO). Another important parameter is the <code>beta</code> parameter, which is used to control the strength of the alignment, typically something in the range of 0.1 to 0.5. A higher beta means less divergence from the initial reference model or the text generations are very similar in terms of their probability distributions.</p>\n<p>The script is kept very simple and is easy to understand. This should help you understand, customize and extend the script for your own use case. We define <code>dataclasses</code> for our arguments. Every argument can then be provided either via the command line or by providing a yaml configuration file. That way we have better type safety and intellisense support.</p>\n<p>Python</p>\n<pre><code class=\"language-python\"><span class=\"code-snippet\" data-language=\"Python\"><span class=\"syntax-source syntax-python\"><span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span> ....\n</span> \n<span class=\"syntax-meta syntax-annotation syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-annotation syntax-python\">@</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-annotation syntax-python\">dataclass</span></span></span>\n<span class=\"syntax-meta syntax-class syntax-python\"><span class=\"syntax-storage syntax-type syntax-class syntax-python\">class</span> <span class=\"syntax-entity syntax-name syntax-class syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">ScriptArguments</span></span><span class=\"syntax-punctuation syntax-section syntax-class syntax-begin syntax-python\">:</span></span>\n    <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">dataset_id_or_path</span></span><span class=\"syntax-punctuation syntax-separator syntax-annotation syntax-variable syntax-python\">:</span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-support syntax-type syntax-python\">str</span></span>\n    <span class=\"syntax-constant syntax-language syntax-python\">...</span>\n<span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span> ....\n</span></span></span></code></pre>\n<p>The training script is separated by <code>#######</code> blocks for the different parts of the script. The main training function:</p>\n<ol>\n<li>Logs all hyperperparameters</li>\n<li>Loads the dataset and Tokenizer from Hugging Face Hub or local disk</li>\n<li>Prepares the DPO dataset correctly using the <code>prompt</code>, <code>chosen</code> and <code>rejected</code> column</li>\n<li>Loads the policy model and/or reference model</li>\n<li>Instantiate DPO trainer and starts the training loop (optionally continue training from a checkpoint)</li>\n<li>Saves the model and optionally pushes it to the Hugging Face Hub</li>\n</ol>\n<p>Below is an example recipe of how we train <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/philschmid/deep-learning-pytorch-huggingface/blob/main/training/receipes/dpo-llama-3-1-8b-qlora.yaml\">Llama 8B model with DPO and Q-LoRA</a>.</p>\n<p>YAML</p>\n<pre><code class=\"language-yaml\"><span class=\"code-snippet\" data-language=\"YAML\"><span class=\"syntax-source syntax-yaml\"><span class=\"syntax-comment syntax-line syntax-number-sign syntax-yaml\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-line syntax-number-sign syntax-yaml\">#</span> Model arguments\n</span><span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">model_name_or_path</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\">philschmid/llama-3-1-8b-math-orca-spectrum-10k-ep1</span>\n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">tokenizer_name_or_path</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\">philschmid/llama-3-1-8b-math-orca-spectrum-10k-ep1</span>\n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">model_revision</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\">main</span>\n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">torch_dtype</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\">bfloat16</span>\n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">attn_implementation</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\">flash_attention_2</span>\n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">use_liger</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-constant syntax-language syntax-boolean syntax-yaml\">false</span>\n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">bf16</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-constant syntax-language syntax-boolean syntax-yaml\">true</span>\n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">tf32</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-constant syntax-language syntax-boolean syntax-yaml\">true</span>\n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">output_dir</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\">runs/dpo-llama-3-1-8b-math-ep3</span>\n \n<span class=\"syntax-comment syntax-line syntax-number-sign syntax-yaml\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-line syntax-number-sign syntax-yaml\">#</span> Dataset arguments\n</span><span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">dataset_id_or_path</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\">philschmid/philschmid-llama-3-1-8b-math-orca-spectr-philschmid-DMath-candidates</span>\n \n<span class=\"syntax-comment syntax-line syntax-number-sign syntax-yaml\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-line syntax-number-sign syntax-yaml\">#</span> LoRA arguments\n</span><span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">use_peft</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-constant syntax-language syntax-boolean syntax-yaml\">true</span>\n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">load_in_4bit</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-constant syntax-language syntax-boolean syntax-yaml\">true</span>\n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">lora_target_modules</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-string syntax-quoted syntax-double syntax-yaml\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-yaml\">&quot;</span>all-linear<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-yaml\">&quot;</span></span>\n<span class=\"syntax-comment syntax-line syntax-number-sign syntax-yaml\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-line syntax-number-sign syntax-yaml\">#</span> important as we need to train the special tokens for the chat template of llama \n</span><span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">lora_modules_to_save</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-meta syntax-flow-sequence syntax-yaml\"><span class=\"syntax-punctuation syntax-definition syntax-sequence syntax-begin syntax-yaml\">[</span><span class=\"syntax-string syntax-quoted syntax-double syntax-yaml\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-yaml\">&quot;</span>lm_head<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-yaml\">&quot;</span></span><span class=\"syntax-punctuation syntax-separator syntax-sequence syntax-yaml\">,</span> <span class=\"syntax-string syntax-quoted syntax-double syntax-yaml\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-yaml\">&quot;</span>embed_tokens<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-yaml\">&quot;</span></span><span class=\"syntax-punctuation syntax-definition syntax-sequence syntax-end syntax-yaml\">]</span></span> <span class=\"syntax-comment syntax-line syntax-number-sign syntax-yaml\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-line syntax-number-sign syntax-yaml\">#</span> you might need to change this for qwen or other models\n</span><span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">lora_r</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-constant syntax-numeric syntax-integer syntax-yaml\">16</span>\n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">lora_alpha</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-constant syntax-numeric syntax-integer syntax-yaml\">16</span>\n \n<span class=\"syntax-comment syntax-line syntax-number-sign syntax-yaml\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-line syntax-number-sign syntax-yaml\">#</span> Training arguments\n</span><span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">beta</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-constant syntax-numeric syntax-float syntax-yaml\">0.1</span>\n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">max_length</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-constant syntax-numeric syntax-integer syntax-yaml\">1536</span>\n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">max_prompt_length</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-constant syntax-numeric syntax-integer syntax-yaml\">768</span>\n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">loss_type</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\">sigmoid</span> <span class=\"syntax-comment syntax-line syntax-number-sign syntax-yaml\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-line syntax-number-sign syntax-yaml\">#</span> default loss, alternatives: https://huggingface.co/docs/trl/dpo_trainer#loss-functions\n</span><span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">num_train_epochs</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-constant syntax-numeric syntax-integer syntax-yaml\">3</span>\n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">per_device_train_batch_size</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-constant syntax-numeric syntax-integer syntax-yaml\">1</span> \n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">gradient_accumulation_steps</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-constant syntax-numeric syntax-integer syntax-yaml\">8</span>\n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">gradient_checkpointing</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-constant syntax-language syntax-boolean syntax-yaml\">true</span>\n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">gradient_checkpointing_kwargs</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span>\n  <span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">use_reentrant</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-constant syntax-language syntax-boolean syntax-yaml\">false</span>\n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">learning_rate</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-constant syntax-numeric syntax-float syntax-yaml\">5.0e-6</span> \n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">lr_scheduler_type</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\">constant</span>\n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">warmup_ratio</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-constant syntax-numeric syntax-float syntax-yaml\">0.03</span>\n \n<span class=\"syntax-comment syntax-line syntax-number-sign syntax-yaml\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-line syntax-number-sign syntax-yaml\">#</span> Logging arguments\n</span><span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">logging_strategy</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\">steps</span>\n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">logging_steps</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-constant syntax-numeric syntax-integer syntax-yaml\">5</span>\n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">report_to</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span>\n<span class=\"syntax-punctuation syntax-definition syntax-block syntax-sequence syntax-item syntax-yaml\">-</span> <span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\">tensorboard</span>\n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">save_strategy</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-string syntax-quoted syntax-double syntax-yaml\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-yaml\">&quot;</span>epoch<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-yaml\">&quot;</span></span>\n<span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">seed</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-constant syntax-numeric syntax-integer syntax-yaml\">42</span>\n \n<span class=\"syntax-comment syntax-line syntax-number-sign syntax-yaml\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-line syntax-number-sign syntax-yaml\">#</span> Hugging Face Hub \n</span><span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">push_to_hub</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-constant syntax-language syntax-boolean syntax-yaml\">true</span>\n  <span class=\"syntax-comment syntax-line syntax-number-sign syntax-yaml\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-line syntax-number-sign syntax-yaml\">#</span> hub_model_id: llama-3-1-8b-math-orca-qlora-10k-ep1 # if not defined same as output_dir\n</span><span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\"><span class=\"syntax-entity syntax-name syntax-tag syntax-yaml\">hub_strategy</span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-mapping syntax-yaml\">:</span> <span class=\"syntax-string syntax-unquoted syntax-plain syntax-out syntax-yaml\">every_save</span>\n</span></span></code></pre>\n<p>This config can be used for single-GPU training (~24GB GPU Memory), if you have more memory available you can increase the <code>per_device_train_batch_size</code> and for multi-GPU training with DeepSpeed (see Appendix for full</p>\n<p>_Note: I ran the script on 1x H100 with a batch size of 8 and 8 gradient accumulation steps. This took ~1 hours to complete._command).</p>\n<p>Python</p>\n<pre><code class=\"language-python\"><span class=\"code-snippet\" data-language=\"Python\"><span class=\"syntax-source syntax-python\">!<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">python</span></span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">scripts</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">/</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">dpo</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">/</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">run_dpo</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span><span class=\"syntax-meta syntax-generic-name syntax-python\">py</span></span> <span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">config</span></span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">receipes</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">/</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">dpo</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">llama</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">3</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">1</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span>8b<span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">qlora</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span><span class=\"syntax-meta syntax-generic-name syntax-python\">yaml</span></span>\n</span></span></code></pre>\n<p><em>Note: During the training we want to minimize loss and grow reward/margins metrics. Keep an eye on the reward/margins metrics, if they are not growing you might need to increase the beta parameter or adjust the learning_rate.</em></p>\n<p>Using Q-LoRA only saves the trained adapter weights. If you want to use the model as standalone model, e.g. for inference you might want to merge the adapter and base model. This can be done using the following command:</p>\n<p>Python</p>\n<pre><code class=\"language-python\"><span class=\"code-snippet\" data-language=\"Python\"><span class=\"syntax-source syntax-python\">!<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">python</span></span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">scripts</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">/</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">merge_adapter_weights</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span><span class=\"syntax-meta syntax-generic-name syntax-python\">py</span></span> <span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">peft_model_id</span></span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">runs</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">/</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">dpo</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">llama</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">3</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">1</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span>8b<span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">math</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">ep3</span></span> <span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">push_to_hub</span></span> <span class=\"syntax-constant syntax-language syntax-python\">True</span> <span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">repository_id</span></span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">dpo</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">llama</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">3</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">1</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span>8b<span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">math</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">ep3</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">merged</span></span>\n</span></span></code></pre>\n<h2>4. Test and evaluate the aligned model</h2>\n<p>After the training is done we want to evaluate and test our model. Similar to our SFT model, we will evaluate the model on <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/datasets/openai/gsm8k\">GSM8K</a> dataset to see if it improved performance. GSM8K (Grade School Math 8K) is a dataset of 8.5K high quality linguistically diverse grade school math word problems. The dataset was created to support the task of question answering on basic mathematical problems that require multi-step reasoning.</p>\n<p>Evaluating Generative AI models is not a trivial task since 1 input can have multiple correct outputs. If you want to learn more about evaluating generative models, check out:</p>\n<ul>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.philschmid.de/evaluate-llm\">Evaluate LLMs and RAG a practical example using Langchain and Hugging Face</a>.</li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.philschmid.de/evaluate-llms-with-lm-eval-and-tgi-vllm\">Evaluate LLMs using Evaluation Harness and Hugging Face TGI/vLLM</a></li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.philschmid.de/llm-evaluation\">LLM Evaluation doesn't need to be complicated</a></li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.philschmid.de/evaluate-llm-mixeval\">Evaluating Open LLMs with MixEval: The Closest Benchmark to LMSYS Chatbot Arena</a></li>\n</ul>\n<p>We are going to use <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/EleutherAI/lm-evaluation-harness\">Evaluation Harness</a> an open-source framework to evaluate language models on a wide range of tasks and benchmarks. The frameworks support evaluating models behind OpenAI compatible API endpoints, those can be locally or remotely. This super helpful as we can evaluate our model in the same environment we will use for production.</p>\n<p>We are going to use <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/huggingface/text-generation-inference\">Text Generation Inference (TGI)</a> for testing and deploying our model. TGI is a purpose-built solution for deploying and serving Large Language Models (LLMs). TGI enables high-performance text generation using Tensor Parallelism and continous batching. If you are or want to use vLLM you can check the Appendix on how to start the inference server.</p>\n<p><em>Note: Make sure that you have enough GPU memory to run the container. Restart kernel to remove all allocated GPU memory from the notebook.</em></p>\n<p>We will start the on 1 GPU detached. Meaning we can can continue to use the notebook while the container is running. If you have more GPUs you can change the <code>--gpus</code> and <code>--num-shard</code> flags to the number of GPUs.</p>\n<p>Bash</p>\n<pre><code class=\"language-bash\"><span class=\"code-snippet\" data-language=\"Shell\"><span class=\"syntax-source syntax-shell syntax-bash\"><span class=\"syntax-meta syntax-function-call syntax-shell\"><span class=\"syntax-variable syntax-function syntax-shell\"><span class=\"syntax-meta syntax-group syntax-expansion syntax-job syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-variable syntax-job syntax-shell\">%</span><span class=\"syntax-variable syntax-language syntax-job syntax-shell\">%</span></span>bash</span></span>\n \n<span class=\"syntax-variable syntax-other syntax-readwrite syntax-assignment syntax-shell\">num_gpus</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-shell\">=</span><span class=\"syntax-string syntax-unquoted syntax-shell\">1</span>\n<span class=\"syntax-variable syntax-other syntax-readwrite syntax-assignment syntax-shell\">model_id</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-shell\">=</span><span class=\"syntax-string syntax-unquoted syntax-shell\">philschmid/dpo-llama-3-1-8b-math-ep3-merged</span> <span class=\"syntax-comment syntax-line syntax-number-sign syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-begin syntax-shell\">#</span></span><span class=\"syntax-comment syntax-line syntax-number-sign syntax-shell\"> replace with your model id</span><span class=\"syntax-comment syntax-line syntax-number-sign syntax-shell\">\n</span> \n<span class=\"syntax-meta syntax-function-call syntax-shell\"><span class=\"syntax-variable syntax-function syntax-shell\">docker</span></span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-shell\"> run<span class=\"syntax-variable syntax-parameter syntax-option syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-parameter syntax-shell\"> --</span>name</span> tgi<span class=\"syntax-variable syntax-parameter syntax-option syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-parameter syntax-shell\"> --</span>gpus</span> <span class=\"syntax-meta syntax-group syntax-expansion syntax-parameter syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-variable syntax-shell\">$</span><span class=\"syntax-punctuation syntax-section syntax-expansion syntax-parameter syntax-begin syntax-shell\">{</span></span><span class=\"syntax-meta syntax-group syntax-expansion syntax-parameter syntax-shell\"><span class=\"syntax-variable syntax-other syntax-readwrite syntax-shell\">num_gpus</span></span><span class=\"syntax-meta syntax-group syntax-expansion syntax-parameter syntax-shell\"><span class=\"syntax-punctuation syntax-section syntax-expansion syntax-parameter syntax-end syntax-shell\">}</span></span><span class=\"syntax-variable syntax-parameter syntax-option syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-parameter syntax-shell\"> -</span>d</span><span class=\"syntax-variable syntax-parameter syntax-option syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-parameter syntax-shell\"> -</span>ti</span><span class=\"syntax-variable syntax-parameter syntax-option syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-parameter syntax-shell\"> -</span>p</span> 8080:80<span class=\"syntax-variable syntax-parameter syntax-option syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-parameter syntax-shell\"> --</span>shm-size</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-option syntax-shell\">=</span>2GB <span class=\"syntax-punctuation syntax-separator syntax-continuation syntax-line syntax-shell\">\\\n</span><span class=\"syntax-variable syntax-parameter syntax-option syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-parameter syntax-shell\">  -</span>e</span> HF_TOKEN=<span class=\"syntax-meta syntax-group syntax-expansion syntax-command syntax-parens syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-variable syntax-shell\">$</span><span class=\"syntax-punctuation syntax-section syntax-parens syntax-begin syntax-shell\">(</span><span class=\"syntax-meta syntax-function-call syntax-shell\"><span class=\"syntax-variable syntax-function syntax-shell\">cat</span></span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-shell\"> <span class=\"syntax-meta syntax-group syntax-expansion syntax-tilde\"><span class=\"syntax-variable syntax-language syntax-tilde syntax-shell\">~</span></span>/.cache/huggingface/token</span><span class=\"syntax-punctuation syntax-section syntax-parens syntax-end syntax-shell\">)</span></span> <span class=\"syntax-punctuation syntax-separator syntax-continuation syntax-line syntax-shell\">\\\n</span>  ghcr.io/huggingface/text-generation-inference:3.0.1 <span class=\"syntax-punctuation syntax-separator syntax-continuation syntax-line syntax-shell\">\\\n</span><span class=\"syntax-variable syntax-parameter syntax-option syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-parameter syntax-shell\">  --</span>model-id</span> <span class=\"syntax-meta syntax-group syntax-expansion syntax-parameter syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-variable syntax-shell\">$</span><span class=\"syntax-punctuation syntax-section syntax-expansion syntax-parameter syntax-begin syntax-shell\">{</span></span><span class=\"syntax-meta syntax-group syntax-expansion syntax-parameter syntax-shell\"><span class=\"syntax-variable syntax-other syntax-readwrite syntax-shell\">model_id</span></span><span class=\"syntax-meta syntax-group syntax-expansion syntax-parameter syntax-shell\"><span class=\"syntax-punctuation syntax-section syntax-expansion syntax-parameter syntax-end syntax-shell\">}</span></span> <span class=\"syntax-punctuation syntax-separator syntax-continuation syntax-line syntax-shell\">\\\n</span><span class=\"syntax-variable syntax-parameter syntax-option syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-parameter syntax-shell\">  --</span>num-shard</span> <span class=\"syntax-meta syntax-group syntax-expansion syntax-parameter syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-variable syntax-shell\">$</span><span class=\"syntax-punctuation syntax-section syntax-expansion syntax-parameter syntax-begin syntax-shell\">{</span></span><span class=\"syntax-meta syntax-group syntax-expansion syntax-parameter syntax-shell\"><span class=\"syntax-variable syntax-other syntax-readwrite syntax-shell\">num_gpus</span></span><span class=\"syntax-meta syntax-group syntax-expansion syntax-parameter syntax-shell\"><span class=\"syntax-punctuation syntax-section syntax-expansion syntax-parameter syntax-end syntax-shell\">}</span></span></span>\n \n</span></span></code></pre>\n<p>Our container will now start in the background and download the model from Hugging Face Hub. We can check the logs to see the progress with <code>docker logs -f tgi</code>.</p>\n<p>Once our container is running we can send requests using the <code>openai</code> or <code>huggingface_hub</code> sdk. Here we ll use the <code>openai</code> sdk to send a request to our inference server. If you don't have the <code>openai</code> sdk installed you can install it using <code>pip install openai</code>.</p>\n<p>Python</p>\n<pre><code class=\"language-python\"><span class=\"code-snippet\" data-language=\"Python\"><span class=\"syntax-source syntax-python\"><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-keyword syntax-control syntax-import syntax-from syntax-python\">from</span></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-meta syntax-import-source syntax-python\"> <span class=\"syntax-meta syntax-import-path syntax-python\"><span class=\"syntax-meta syntax-import-name syntax-python\">openai</span></span> <span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-keyword syntax-control syntax-import syntax-python\">import</span></span></span></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"> <span class=\"syntax-meta syntax-generic-name syntax-python\">OpenAI</span></span>\n \n<span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span> create client \n</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">client</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">OpenAI</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-variable syntax-parameter syntax-python\">base_url</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">http://localhost:8080/v1<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span><span class=\"syntax-variable syntax-parameter syntax-python\">api_key</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">-<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n \n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">system_message</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-block syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;&quot;&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-block syntax-python\"><span class=\"syntax-meta syntax-string syntax-python\"></span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-block syntax-python\">Solve the given high school math problem by providing a clear explanation of each step leading to the final solution.\n \nProvide a detailed breakdown of your calculations, beginning with an explanation of the problem and describing how you derive each formula, value, or conclusion. Use logical steps that build upon one another, to arrive at the final answer in a systematic manner.\n \n# Steps\n \n1. **Understand the Problem**: Restate the given math problem and clearly identify the main question and any important given values.\n2. **Set Up**: Identify the key formulas or concepts that could help solve the problem (e.g., algebraic manipulation, geometry formulas, trigonometric identities).\n3. **Solve Step-by-Step**: Iteratively progress through each step of the math problem, justifying why each consecutive operation brings you closer to the solution.\n4. **Double Check**: If applicable, double check the work for accuracy and sense, and mention potential alternative approaches if any.\n5. **Final Answer**: Provide the numerical or algebraic solution clearly, accompanied by appropriate units if relevant.\n \n# Notes\n \n- Always clearly define any variable or term used.\n- Wherever applicable, include unit conversions or context to explain why each formula or step has been chosen.\n- Assume the level of mathematics is suitable for high school, and avoid overly advanced math techniques unless they are common at that level.\n- Return the final in an extra line. Staring with &quot;The Answer is: [ANSWER]&quot;\n \n# Examples\n<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;&quot;&quot;</span></span></span>\n \n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">messages</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-structure syntax-list syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-list syntax-begin syntax-python\">[</span>\n    <span class=\"syntax-meta syntax-structure syntax-dictionary-or-set syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-dictionary-or-set syntax-begin syntax-python\">{</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">role<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-python\">:</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">system<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-dictionary-or-set syntax-python\">,</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">content<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-python\">:</span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">system_message</span></span><span class=\"syntax-punctuation syntax-section syntax-dictionary-or-set syntax-end syntax-python\">}</span></span><span class=\"syntax-punctuation syntax-separator syntax-list syntax-python\">,</span>\n    <span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span> {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;If you converted $140 to 158760 Korean Won, how much is $1 in Korean Won?&quot;},\n</span>    <span class=\"syntax-meta syntax-structure syntax-dictionary-or-set syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-dictionary-or-set syntax-begin syntax-python\">{</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">role<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-python\">:</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">user<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-dictionary-or-set syntax-python\">,</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">content<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-python\">:</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">Q: Henry and 3 of his friends order 7 pizzas for lunch. Each pizza is cut into 8 slices. If Henry and his friends want to share the pizzas equally, how many slices can each of them have?<span class=\"syntax-constant syntax-character syntax-escape syntax-python\">\\n</span>A:<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-section syntax-dictionary-or-set syntax-end syntax-python\">}</span></span><span class=\"syntax-punctuation syntax-separator syntax-list syntax-python\">,</span>\n    <span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span> {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;The rectangular-shaped cell phone is 9 centimeters (cm) wide and 46 centimeters (cm) in circumference. Find the vertical length of the cell phone?&quot;},\n</span><span class=\"syntax-punctuation syntax-section syntax-list syntax-end syntax-python\">]</span></span>\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">expected_answer</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">14<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span>\n \n \n<span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span> Take a random sample from the dataset and remove the last message and send it to the model\n</span> \n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">response</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">client</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span><span class=\"syntax-meta syntax-generic-name syntax-python\">chat</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span><span class=\"syntax-meta syntax-generic-name syntax-python\">completions</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">create</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\">\n    <span class=\"syntax-variable syntax-parameter syntax-python\">model</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">philschmid/dpo-llama-3-1-8b-math-ep3-merged<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">messages</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">messages</span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">stream</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-constant syntax-language syntax-python\">False</span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span> <span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span> no streaming\n</span>    <span class=\"syntax-variable syntax-parameter syntax-python\">max_tokens</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">1024</span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">temperature</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-constant syntax-numeric syntax-float syntax-python\">1<span class=\"syntax-punctuation syntax-separator syntax-decimal syntax-python\">.</span>0</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">response</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">response</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span><span class=\"syntax-meta syntax-generic-name syntax-python\">choices</span></span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-begin syntax-python\">[</span></span><span class=\"syntax-meta syntax-item-access syntax-arguments syntax-python\"><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">0</span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-end syntax-python\">]</span></span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span><span class=\"syntax-meta syntax-generic-name syntax-python\">message</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span><span class=\"syntax-meta syntax-generic-name syntax-python\">content</span>\n \n<span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span> Print results\n</span><span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-support syntax-function syntax-builtin syntax-python\">print</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-storage syntax-type syntax-string syntax-python\">f</span><span class=\"syntax-meta syntax-string syntax-interpolated syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-interpolated syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">Query:<span class=\"syntax-constant syntax-character syntax-escape syntax-python\">\\n</span></span><span class=\"syntax-meta syntax-interpolation syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-interpolation syntax-begin syntax-python\">{</span><span class=\"syntax-source syntax-python syntax-embedded\"><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">messages</span></span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-begin syntax-python\">[</span></span><span class=\"syntax-meta syntax-item-access syntax-arguments syntax-python\"><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">1</span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-end syntax-python\">]</span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-begin syntax-python\">[</span></span><span class=\"syntax-meta syntax-item-access syntax-arguments syntax-python\"><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-single syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&#39;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-single syntax-python\">content<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&#39;</span></span></span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-end syntax-python\">]</span></span></span></span><span class=\"syntax-meta syntax-interpolation syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-interpolation syntax-end syntax-python\">}</span></span><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n<span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-support syntax-function syntax-builtin syntax-python\">print</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-storage syntax-type syntax-string syntax-python\">f</span><span class=\"syntax-meta syntax-string syntax-interpolated syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-interpolated syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">Original Answer:<span class=\"syntax-constant syntax-character syntax-escape syntax-python\">\\n</span></span><span class=\"syntax-meta syntax-interpolation syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-interpolation syntax-begin syntax-python\">{</span><span class=\"syntax-source syntax-python syntax-embedded\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">expected_answer</span></span></span></span><span class=\"syntax-meta syntax-interpolation syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-interpolation syntax-end syntax-python\">}</span></span><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n<span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-support syntax-function syntax-builtin syntax-python\">print</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-storage syntax-type syntax-string syntax-python\">f</span><span class=\"syntax-meta syntax-string syntax-interpolated syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-interpolated syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">Generated Answer:<span class=\"syntax-constant syntax-character syntax-escape syntax-python\">\\n</span></span><span class=\"syntax-meta syntax-interpolation syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-interpolation syntax-begin syntax-python\">{</span><span class=\"syntax-source syntax-python syntax-embedded\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">response</span></span></span></span><span class=\"syntax-meta syntax-interpolation syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-interpolation syntax-end syntax-python\">}</span></span><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n \n</span></span></code></pre>\n<p>Awesome that looks great! Now we can evaluate our model with the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/EleutherAI/lm-evaluation-harness\">Evaluation Harness</a>.</p>\n<p><em>Note: Make sure to change the model id to your fine-tuned model.</em></p>\n<p>Python</p>\n<pre><code class=\"language-python\"><span class=\"code-snippet\" data-language=\"Python\"><span class=\"syntax-source syntax-python\">!<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">lm_eval</span></span> <span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model</span></span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">local</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">chat</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">completions</span></span> <span class=\"syntax-punctuation syntax-separator syntax-continuation syntax-line syntax-python\">\\</span>\n  <span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">tasks</span></span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">gsm8k_cot</span></span> <span class=\"syntax-punctuation syntax-separator syntax-continuation syntax-line syntax-python\">\\</span>\n  <span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model_args</span></span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model</span></span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">philschmid</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">/</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">dpo</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">llama</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">3</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">1</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span>8b<span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">math</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">ep3</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">merged</span></span>,<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">base_url</span></span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">http</span></span><span class=\"syntax-punctuation syntax-separator syntax-annotation syntax-variable syntax-python\">:</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">/</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">/</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">localhost</span></span><span class=\"syntax-punctuation syntax-separator syntax-annotation syntax-variable syntax-python\">:</span><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">8080</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">/</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">v1</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">/</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">chat</span></span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">/</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">completions</span></span>,<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">num_concurrent</span></span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">8</span>,<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">max_retries</span></span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">10</span>,<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">tokenized_requests</span></span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-constant syntax-language syntax-python\">False</span>,<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">timeout</span></span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">180</span>,<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">max_length</span></span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">4096</span> <span class=\"syntax-punctuation syntax-separator syntax-continuation syntax-line syntax-python\">\\</span>\n  <span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">apply_chat_template</span></span> <span class=\"syntax-punctuation syntax-separator syntax-continuation syntax-line syntax-python\">\\</span>\n  <span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">fewshot_as_multiturn</span></span>\n</span></span></code></pre>\n<p>Wow, 59% accuracy, thats a 5% improvement from our SFT model, using only ~2k preference pairs for 3 epochs. That shows that our script and config is working correctly.</p>\n<p><em>Note: You might be able to achieve better results with more data, more epochs or tuning the hyperparameters (beta, learning rate, batch size, etc.). I ran some ablations on multi-gpu training and full training with DeepSpeed (see Appendix for full command) and the best results was 62% accuracy.</em></p>\n<p>Python</p>\n<pre><code class=\"language-python\"><span class=\"code-snippet\" data-language=\"Python\"><span class=\"syntax-source syntax-python\">!<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">docker</span></span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">stop</span></span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">tgi</span></span>\n!<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">docker</span></span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">rm</span></span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">tgi</span></span>\n</span></span></code></pre>\n<h2>Conclusion</h2>\n<p>In this guide, we successfully aligned a Llama 3.1 8B model using Direct Preference Optimization (DPO) and achieved a 5% improvement on GSM8K compared to our SFT baseline. Instead of using off-policy preference data (like existing human preference datasets), we generated our own preference pairs using the SFT model we wanted to align. This approach has several advantages:</p>\n<ul>\n<li>The preference pairs directly reflect the model's current capabilities and output distribution</li>\n<li>We could automatically evaluate responses using a rule-based reward model for math problems</li>\n<li>The training becomes more focused and effective since we're optimizing for the specific behaviors we want to improve</li>\n</ul>\n<p>We also learned that even with a relatively small dataset (~2k preference pairs) and just 3 epochs of training, DPO can produce meaningful improvements in model performance. <strong>The</strong> combination of on-policy data generation and DPO provides a practical and efficient approach to aligning language models with specific objectives. This method could be adapted for various domains beyond math problems by using different reward models or evaluation criteria to generate preference pairs.</p>\n<h2>Appendix</h2>\n<p><em>Note: Make sure to install deepspeed and accelerate before running the commands. <code>pip install deepspeed==0.15.4</code></em></p>\n<h3>Distributed Training</h3>\n<p>Bash</p>\n<pre><code class=\"language-bash\"><span class=\"code-snippet\" data-language=\"Shell\"><span class=\"syntax-source syntax-shell syntax-bash\"><span class=\"syntax-variable syntax-other syntax-readwrite syntax-assignment syntax-shell\">ACCELERATE_LOG_LEVEL</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-shell\">=</span><span class=\"syntax-string syntax-unquoted syntax-shell\">info</span> <span class=\"syntax-meta syntax-function-call syntax-shell\"><span class=\"syntax-variable syntax-function syntax-shell\">accelerate</span></span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-shell\"> launch<span class=\"syntax-variable syntax-parameter syntax-option syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-parameter syntax-shell\"> --</span>num_processes</span> 4<span class=\"syntax-variable syntax-parameter syntax-option syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-parameter syntax-shell\"> --</span>config_file</span> configs/accelerate_configs/deepspeed_zero3.yaml scripts/dpo/run_dpo.py<span class=\"syntax-variable syntax-parameter syntax-option syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-parameter syntax-shell\"> --</span>config</span> receipes/dpo-llama-3-1-8b.yaml</span>\n</span></span></code></pre>\n",
  "content_markdown": "Large Language Models (LLMs) continued their important role in 2024, with several major developments completely outperforming previous models. The focus continued to more smaller, more powerful models from companies like Meta, Qwen, or Google. These models not only became more powerful, but also more efficient.\n\nPart of the reason is the continued scaling of post-training methods and datasets. Post-training methods like [Direct Preference Optimization (DPO)](https://huggingface.co/papers/2305.18290), [Proximal Policy Optimization (PPO)](https://huggingface.co/papers/2203.02155), and [Group Preference Optimization (GRPO)](https://huggingface.co/papers/2310.11523) have been used to align models with human preferences and improve performance.\n\nContinuing from [How to fine-tune open LLMs in 2025 with Hugging Face](https://www.philschmid.de/fine-tune-llms-in-2025), this guide focuses on aligning models using Direct Preference Optimization (DPO). We'll build upon our previously fine-tuned model from the [Fine-Tune LLMs in 2025](https://www.philschmid.de/fine-tune-llms-in-2025) guide and improve it further through preference learning.\n\nBefore we start, let's take a look at the [Direct Preference Optimization (DPO)](https://huggingface.co/papers/2305.18290) paper and understand how it works.\n\n**What is Direct Preference Optimization (DPO)?**\n\n[Direct Preference Optimization (DPO)](https://huggingface.co/papers/2305.18290) is a simplified approach to align language models with human preferences. Unlike traditional RLHF methods that require training a separate reward model and using complex PPO optimization, DPO treats the alignment problem as a classification task on preference data. This makes it more stable, efficient, and computationally lightweight compared to alternatives.\n\n- **Simplicity**: DPO eliminates the need for a separate reward model and complex RL optimization, making it easier to implement and debug\n- **Stability**: By avoiding the instabilities of PPO training, DPO provides more reliable convergence\n- **Efficiency**: The direct optimization approach requires less compute and fewer hyperparameters than traditional RLHF\n- **Performance**: Despite its simplicity, DPO achieves comparable results\n\n**Overview**\n\nIn this guide, we'll use offline DPO with on-Policy data. Offline DPO is the more compute-efficient, meaning we don't need a Reward model during training in memory. However, we will be staying on-policy. We'll first generate samples from the Supervised Fine-Tuned (SFT) model we trained in the previous guide and score them with a rule-based reward model that checks answer correctness. These scores will then be used to create preference pairs (a \"preferred\" and a \"rejected\" response) for DPO training.\n\nIf you are going to adjust the example to your own use case, which cannot be verified with a rule-based reward model, you can use a generic reward model like [nicolinho/QRM-Llama3.1-8B-v2](https://huggingface.co/nicolinho/QRM-Llama3.1-8B-v2), which ranks in the top 10 on reward bench or LLM as judge based on your own criteria.\n\nYou will learn how to:\n\n1. [Setup the development environment](https://www.philschmid.de/rl-with-llms-in-2025-dpo#1-setup-development-environment)\n2. [Create on-policy preference dataset from model outputs](https://www.philschmid.de/rl-with-llms-in-2025-dpo#2-create-on-policy-preference-dataset-from-model-outputs)\n3. [Align the model using DPO and the Hugging Face `DPOTrainer`](https://www.philschmid.de/rl-with-llms-in-2025-dpo#3-align-the-model-using-dpo-and-the-hugging-face-dpotrainer)\n4. [Test and evaluate the aligned model](https://www.philschmid.de/rl-with-llms-in-2025-dpo#4-test-and-evaluate-the-aligned-model)\n\n*Note: This guide is designed for consumer GPUs (24GB+) like the NVIDIA RTX 4090/5090 or A10G, but can be adapted for larger systems.*\n\n## 1\\. Setup development environment\n\nOur first step is to install Hugging Face Libraries and Pytorch, vllm, and trl, transformers and datasets. If you haven't heard of trl yet, don't worry. It is a new library on top of transformers and datasets, which makes it easier to fine-tune, rlhf, align open LLMs.\n\nPython\n\n```python\n# Install Pytorch & other libraries, make sure to match your GPU driver version\n%pip install \"torch==2.5.1\" vllm tensorboard  \"setuptools<71.0.0\" openai \"lm-eval[api]==0.4.5\"  --index-url https://download.pytorch.org/whl/cu121\n \n# Install flash-attn\n%pip install flash-attn \n \n# Install Hugging Face libraries\n%pip install  --upgrade \\\n  \"transformers==4.48.1\" \\\n  \"datasets==3.1.0\" \\\n  \"accelerate==1.3.0\" \\\n  \"bitsandbytes==0.45.0\" \\\n  \"peft==0.14.0\" \\\n  \"hf-transfer==0.1.9\" \\\n  \"trl==0.13.0\"\n```\n\n*Note: you may need to restart the kernel to use updated packages.*\n\nWe will use the [Hugging Face Hub](https://huggingface.co/models) as a remote model versioning service. This means we will automatically push our model, logs and information to the Hub during training. You must register on the [Hugging Face](https://huggingface.co/join) for this. After you have an account, we will use the `login` util from the `huggingface_hub` package to log into our account and store our token (access key) on the disk.\n\nPython\n\n```python\nfrom huggingface_hub import login\n \nlogin(token=\"\", add_to_git_credential=True) # ADD YOUR TOKEN HERE\n```\n\n## 2\\. Create on-policy preference dataset from model outputs\n\nWe are going to generate a preference dataset from our SFT model rather than using a different model and off-policy data. On-policy data is generated from the model being trained, which means the preference pairs directly reflect the model's current capabilities and output distribution. This makes the training more relevant and effective.\n\nStudies have shown that leveraging on-policy preference data leads to better performance compared to off-policy approaches. [REF 1](https://arxiv.org/abs/2404.14367), [REF 2](https://arxiv.org/abs/2403.10160).\n\nAs we are building on our previous fine-tuned model we want to furhter improve the performance on MATH related tasks. We will use the prompts from [philschmid/DMath](https://huggingface.co/datasets/philschmid/DMath). DMath (Diverse Math Word Problems) is a collection of 10K high-quality grade school-level math word problems for the paper [\"It Ain't Over: A Multi-aspect Diverse Math Word Problem Dataset\"](https://aclanthology.org/2023.emnlp-main.927.pdf). Each solution will be scored by a rule-based reward model that checks answer correctness using a regex. (Thats a very simple and naive approach, better would to additionally use specific format extraction, e.g. \"The Answer is: \\[ANSWER\\]\" or additional LLM Judge). If the solution is correct, it will be labeled as preferred, otherwise as rejected. Based on the score we will create difference preference pairs.\n\nI prepared [create\\_preference\\_dataset.py](https://github.com/philschmid/deep-learning-pytorch-huggingface/blob/main/training/scripts/dpo/create_preference_dataset.py) script to generate the dataset. The dataset will be saved to the Hugging Face Hub. We are going to generate 4 solutions for each input hoping to have at least one correct solution and one incorrect solution. If we don't have a pair we will skip the input.\n\nPython\n\n```python\npython scripts/dpo/create_preference_dataset.py --dataset_id philschmid/DMath --sample_size 5000 --generation_model_name_or_path philschmid/llama-3-1-8b-math-orca-spectrum-10k-ep1 --num_solutions 4 --batch_size 16 \n```\n\n*Note: You can skip this step and used the generated preference dataset from me [philschmid/philschmid-llama-3-1-8b-math-orca-spectr-philschmid-DMath-candidates](https://huggingface.co/philschmid/philschmid-llama-3-1-8b-math-orca-spectr-philschmid-DMath-candidates). It includes 1.9k prefence pairs.*\n\n## 3\\. Align the model using DPO and the Hugging Face DPOTrainer\n\nTRL supports the DPO through a dedicated [DPOTrainer](https://huggingface.co/docs/trl/dpo_trainer) for aligning LLMs from preference data, as described in [Direct Preference Optimization: Your Language Model is Secretly a Reward Model](https://huggingface.co/papers/2305.18290). The `DPOTrainer` is a subclass of the `Trainer` from the `transformers` library and supports all the same features, including logging, checkpointing, distributed training, and parameter efficient fine-tuning (PEFT). [Direct Preference Optimization (DPO)](https://huggingface.co/papers/2305.18290) aligns LLMs with human preferences using 'prompt', 'chosen', and 'rejected' columns, where each 'prompt' is paired with a 'chosen' response that aligns with human preferences and a 'rejected' response that does not.\n\nWe prepared a [run\\_dpo.py](https://github.com/philschmid/deep-learning-pytorch-huggingface/blob/main/training/scripts/dpo/run_dpo.py) scripts, which supports providing a yaml configuration file. This allows you to easily change the model, dataset, hyperparameters, and other settings. This is done by using the `TrlParser`, which parses the yaml file and converts it into the `TrainingArguments` arguments.\n\nBased on the [Alignment Handbook](https://github.com/huggingface/alignment-handbook) we know that we need to use a ~10-100x smaller learning rate for DPO compared to SFT. In our example we reduce the learning rate from 2e-4 (SFT) to 5e-6 (DPO). Another important parameter is the `beta` parameter, which is used to control the strength of the alignment, typically something in the range of 0.1 to 0.5. A higher beta means less divergence from the initial reference model or the text generations are very similar in terms of their probability distributions.\n\nThe script is kept very simple and is easy to understand. This should help you understand, customize and extend the script for your own use case. We define `dataclasses` for our arguments. Every argument can then be provided either via the command line or by providing a yaml configuration file. That way we have better type safety and intellisense support.\n\nPython\n\n```python\n# ....\n \n@dataclass\nclass ScriptArguments:\n    dataset_id_or_path: str\n    ...\n# ....\n```\n\nThe training script is separated by `#######` blocks for the different parts of the script. The main training function:\n\n1. Logs all hyperperparameters\n2. Loads the dataset and Tokenizer from Hugging Face Hub or local disk\n3. Prepares the DPO dataset correctly using the `prompt`, `chosen` and `rejected` column\n4. Loads the policy model and/or reference model\n5. Instantiate DPO trainer and starts the training loop (optionally continue training from a checkpoint)\n6. Saves the model and optionally pushes it to the Hugging Face Hub\n\nBelow is an example recipe of how we train [Llama 8B model with DPO and Q-LoRA](https://github.com/philschmid/deep-learning-pytorch-huggingface/blob/main/training/receipes/dpo-llama-3-1-8b-qlora.yaml).\n\nYAML\n\n```yaml\n# Model arguments\nmodel_name_or_path: philschmid/llama-3-1-8b-math-orca-spectrum-10k-ep1\ntokenizer_name_or_path: philschmid/llama-3-1-8b-math-orca-spectrum-10k-ep1\nmodel_revision: main\ntorch_dtype: bfloat16\nattn_implementation: flash_attention_2\nuse_liger: false\nbf16: true\ntf32: true\noutput_dir: runs/dpo-llama-3-1-8b-math-ep3\n \n# Dataset arguments\ndataset_id_or_path: philschmid/philschmid-llama-3-1-8b-math-orca-spectr-philschmid-DMath-candidates\n \n# LoRA arguments\nuse_peft: true\nload_in_4bit: true\nlora_target_modules: \"all-linear\"\n# important as we need to train the special tokens for the chat template of llama \nlora_modules_to_save: [\"lm_head\", \"embed_tokens\"] # you might need to change this for qwen or other models\nlora_r: 16\nlora_alpha: 16\n \n# Training arguments\nbeta: 0.1\nmax_length: 1536\nmax_prompt_length: 768\nloss_type: sigmoid # default loss, alternatives: https://huggingface.co/docs/trl/dpo_trainer#loss-functions\nnum_train_epochs: 3\nper_device_train_batch_size: 1 \ngradient_accumulation_steps: 8\ngradient_checkpointing: true\ngradient_checkpointing_kwargs:\n  use_reentrant: false\nlearning_rate: 5.0e-6 \nlr_scheduler_type: constant\nwarmup_ratio: 0.03\n \n# Logging arguments\nlogging_strategy: steps\nlogging_steps: 5\nreport_to:\n- tensorboard\nsave_strategy: \"epoch\"\nseed: 42\n \n# Hugging Face Hub \npush_to_hub: true\n  # hub_model_id: llama-3-1-8b-math-orca-qlora-10k-ep1 # if not defined same as output_dir\nhub_strategy: every_save\n```\n\nThis config can be used for single-GPU training (~24GB GPU Memory), if you have more memory available you can increase the `per_device_train_batch_size` and for multi-GPU training with DeepSpeed (see Appendix for full\n\n\\_Note: I ran the script on 1x H100 with a batch size of 8 and 8 gradient accumulation steps. This took ~1 hours to complete.\\_command).\n\nPython\n\n```python\n!python scripts/dpo/run_dpo.py --config receipes/dpo-llama-3-1-8b-qlora.yaml\n```\n\n*Note: During the training we want to minimize loss and grow reward/margins metrics. Keep an eye on the reward/margins metrics, if they are not growing you might need to increase the beta parameter or adjust the learning\\_rate.*\n\nUsing Q-LoRA only saves the trained adapter weights. If you want to use the model as standalone model, e.g. for inference you might want to merge the adapter and base model. This can be done using the following command:\n\nPython\n\n```python\n!python scripts/merge_adapter_weights.py --peft_model_id runs/dpo-llama-3-1-8b-math-ep3 --push_to_hub True --repository_id dpo-llama-3-1-8b-math-ep3-merged\n```\n\n## 4\\. Test and evaluate the aligned model\n\nAfter the training is done we want to evaluate and test our model. Similar to our SFT model, we will evaluate the model on [GSM8K](https://huggingface.co/datasets/openai/gsm8k) dataset to see if it improved performance. GSM8K (Grade School Math 8K) is a dataset of 8.5K high quality linguistically diverse grade school math word problems. The dataset was created to support the task of question answering on basic mathematical problems that require multi-step reasoning.\n\nEvaluating Generative AI models is not a trivial task since 1 input can have multiple correct outputs. If you want to learn more about evaluating generative models, check out:\n\n- [Evaluate LLMs and RAG a practical example using Langchain and Hugging Face](https://www.philschmid.de/evaluate-llm).\n- [Evaluate LLMs using Evaluation Harness and Hugging Face TGI/vLLM](https://www.philschmid.de/evaluate-llms-with-lm-eval-and-tgi-vllm)\n- [LLM Evaluation doesn't need to be complicated](https://www.philschmid.de/llm-evaluation)\n- [Evaluating Open LLMs with MixEval: The Closest Benchmark to LMSYS Chatbot Arena](https://www.philschmid.de/evaluate-llm-mixeval)\n\nWe are going to use [Evaluation Harness](https://github.com/EleutherAI/lm-evaluation-harness) an open-source framework to evaluate language models on a wide range of tasks and benchmarks. The frameworks support evaluating models behind OpenAI compatible API endpoints, those can be locally or remotely. This super helpful as we can evaluate our model in the same environment we will use for production.\n\nWe are going to use [Text Generation Inference (TGI)](https://github.com/huggingface/text-generation-inference) for testing and deploying our model. TGI is a purpose-built solution for deploying and serving Large Language Models (LLMs). TGI enables high-performance text generation using Tensor Parallelism and continous batching. If you are or want to use vLLM you can check the Appendix on how to start the inference server.\n\n*Note: Make sure that you have enough GPU memory to run the container. Restart kernel to remove all allocated GPU memory from the notebook.*\n\nWe will start the on 1 GPU detached. Meaning we can can continue to use the notebook while the container is running. If you have more GPUs you can change the `--gpus` and `--num-shard` flags to the number of GPUs.\n\nBash\n\n```bash\n%%bash\n \nnum_gpus=1\nmodel_id=philschmid/dpo-llama-3-1-8b-math-ep3-merged # replace with your model id\n \ndocker run --name tgi --gpus ${num_gpus} -d -ti -p 8080:80 --shm-size=2GB \\\n  -e HF_TOKEN=$(cat ~/.cache/huggingface/token) \\\n  ghcr.io/huggingface/text-generation-inference:3.0.1 \\\n  --model-id ${model_id} \\\n  --num-shard ${num_gpus}\n \n```\n\nOur container will now start in the background and download the model from Hugging Face Hub. We can check the logs to see the progress with `docker logs -f tgi`.\n\nOnce our container is running we can send requests using the `openai` or `huggingface_hub` sdk. Here we ll use the `openai` sdk to send a request to our inference server. If you don't have the `openai` sdk installed you can install it using `pip install openai`.\n\nPython\n\n```python\nfrom openai import OpenAI\n \n# create client \nclient = OpenAI(base_url=\"http://localhost:8080/v1\",api_key=\"-\")\n \nsystem_message = \"\"\"Solve the given high school math problem by providing a clear explanation of each step leading to the final solution.\n \nProvide a detailed breakdown of your calculations, beginning with an explanation of the problem and describing how you derive each formula, value, or conclusion. Use logical steps that build upon one another, to arrive at the final answer in a systematic manner.\n \n# Steps\n \n1. **Understand the Problem**: Restate the given math problem and clearly identify the main question and any important given values.\n2. **Set Up**: Identify the key formulas or concepts that could help solve the problem (e.g., algebraic manipulation, geometry formulas, trigonometric identities).\n3. **Solve Step-by-Step**: Iteratively progress through each step of the math problem, justifying why each consecutive operation brings you closer to the solution.\n4. **Double Check**: If applicable, double check the work for accuracy and sense, and mention potential alternative approaches if any.\n5. **Final Answer**: Provide the numerical or algebraic solution clearly, accompanied by appropriate units if relevant.\n \n# Notes\n \n- Always clearly define any variable or term used.\n- Wherever applicable, include unit conversions or context to explain why each formula or step has been chosen.\n- Assume the level of mathematics is suitable for high school, and avoid overly advanced math techniques unless they are common at that level.\n- Return the final in an extra line. Staring with \"The Answer is: [ANSWER]\"\n \n# Examples\n\"\"\"\n \nmessages = [\n    {\"role\": \"system\", \"content\": system_message},\n    # {\"role\": \"user\", \"content\": \"If you converted $140 to 158760 Korean Won, how much is $1 in Korean Won?\"},\n    {\"role\": \"user\", \"content\": \"Q: Henry and 3 of his friends order 7 pizzas for lunch. Each pizza is cut into 8 slices. If Henry and his friends want to share the pizzas equally, how many slices can each of them have?\\nA:\"},\n    # {\"role\": \"user\", \"content\": \"The rectangular-shaped cell phone is 9 centimeters (cm) wide and 46 centimeters (cm) in circumference. Find the vertical length of the cell phone?\"},\n]\nexpected_answer = \"14\"\n \n \n# Take a random sample from the dataset and remove the last message and send it to the model\n \nresponse = client.chat.completions.create(\n    model=\"philschmid/dpo-llama-3-1-8b-math-ep3-merged\",\n    messages=messages,\n    stream=False, # no streaming\n    max_tokens=1024,\n    temperature=1.0)\nresponse = response.choices[0].message.content\n \n# Print results\nprint(f\"Query:\\n{messages[1]['content']}\")\nprint(f\"Original Answer:\\n{expected_answer}\")\nprint(f\"Generated Answer:\\n{response}\")\n \n```\n\nAwesome that looks great! Now we can evaluate our model with the [Evaluation Harness](https://github.com/EleutherAI/lm-evaluation-harness).\n\n*Note: Make sure to change the model id to your fine-tuned model.*\n\nPython\n\n```python\n!lm_eval --model local-chat-completions \\\n  --tasks gsm8k_cot \\\n  --model_args model=philschmid/dpo-llama-3-1-8b-math-ep3-merged,base_url=http://localhost:8080/v1/chat/completions,num_concurrent=8,max_retries=10,tokenized_requests=False,timeout=180,max_length=4096 \\\n  --apply_chat_template \\\n  --fewshot_as_multiturn\n```\n\nWow, 59% accuracy, thats a 5% improvement from our SFT model, using only ~2k preference pairs for 3 epochs. That shows that our script and config is working correctly.\n\n*Note: You might be able to achieve better results with more data, more epochs or tuning the hyperparameters (beta, learning rate, batch size, etc.). I ran some ablations on multi-gpu training and full training with DeepSpeed (see Appendix for full command) and the best results was 62% accuracy.*\n\nPython\n\n```python\n!docker stop tgi\n!docker rm tgi\n```\n\n## Conclusion\n\nIn this guide, we successfully aligned a Llama 3.1 8B model using Direct Preference Optimization (DPO) and achieved a 5% improvement on GSM8K compared to our SFT baseline. Instead of using off-policy preference data (like existing human preference datasets), we generated our own preference pairs using the SFT model we wanted to align. This approach has several advantages:\n\n- The preference pairs directly reflect the model's current capabilities and output distribution\n- We could automatically evaluate responses using a rule-based reward model for math problems\n- The training becomes more focused and effective since we're optimizing for the specific behaviors we want to improve\n\nWe also learned that even with a relatively small dataset (~2k preference pairs) and just 3 epochs of training, DPO can produce meaningful improvements in model performance. **The** combination of on-policy data generation and DPO provides a practical and efficient approach to aligning language models with specific objectives. This method could be adapted for various domains beyond math problems by using different reward models or evaluation criteria to generate preference pairs.\n\n## Appendix\n\n*Note: Make sure to install deepspeed and accelerate before running the commands. `pip install deepspeed==0.15.4`*\n\n### Distributed Training\n\nBash\n\n```bash\nACCELERATE_LOG_LEVEL=info accelerate launch --num_processes 4 --config_file configs/accelerate_configs/deepspeed_zero3.yaml scripts/dpo/run_dpo.py --config receipes/dpo-llama-3-1-8b.yaml\n```\n",
  "dateCreated": "2026-09-27T19:29:15.293681927+00:00",
  "date_created": "2025-01-23T00:00:00+00:00",
  "date_modified": "2025-01-23T00:00:00+00:00",
  "date_published": "2025-01-23T00:00:00+00:00",
  "description": "Learn how to align LLMs using Hugging Face TRL and RLHF through Direct Preference Optimization (DPO) and on-policy synthetic data.",
  "external_url": "https://www.philschmid.de/rl-with-llms-in-2025-dpo",
  "git": {
    "commit": "ebb0941c5c06a2ab2377342d607535262a3e969e",
    "path": "items/philschmid-de/2025/01/2025-01-23-how-to-align-open-llms-in-2025-with-dpo-and-and-synthetic.md",
    "permalink": "https://github.com/aymericbeaumet/aggr-instance/blob/ebb0941c5c06a2ab2377342d607535262a3e969e/items/philschmid-de/2025/01/2025-01-23-how-to-align-open-llms-in-2025-with-dpo-and-and-synthetic.md"
  },
  "id": "urn:aggr:item:891a59bfbb8d6973c2528cb25e6713bbc9e700b3",
  "isBasedOn": {
    "@id": "https://www.philschmid.de/rl-with-llms-in-2025-dpo"
  },
  "mainEntity": {
    "@id": "https://www.philschmid.de/rl-with-llms-in-2025-dpo",
    "@type": "CreativeWork",
    "archivedAt": {
      "@id": "https://aggr.aymericbeaumet.com/items/philschmid-de/2025-01-23-how-to-align-open-llms-in-2025-with-dpo-and-and-synthetic/#webpage"
    },
    "dateModified": "2025-01-23T00:00:00+00:00",
    "datePublished": "2025-01-23T00:00:00+00:00",
    "headline": "How to align open LLMs in 2025 with DPO and and synthetic data",
    "timeRequired": "PT14M",
    "url": "https://www.philschmid.de/rl-with-llms-in-2025-dpo",
    "wordCount": 2972
  },
  "name": "Archived snapshot: How to align open LLMs in 2025 with DPO and and synthetic data",
  "preview": null,
  "reading_minutes": 14,
  "replicated_at": null,
  "source": "philschmid-de",
  "source_name": "philschmid.de - RSS feed",
  "summary": "Learn how to align LLMs using Hugging Face TRL and RLHF through Direct Preference Optimization (DPO) and on-policy synthetic data.",
  "tags": [],
  "temporalCoverage": "2026-09-27T19:29:15.293681927+00:00",
  "title": "How to align open LLMs in 2025 with DPO and and synthetic data",
  "url": "https://aggr.aymericbeaumet.com/items/philschmid-de/2025-01-23-how-to-align-open-llms-in-2025-with-dpo-and-and-synthetic/",
  "word_count": 2972
}