{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Maxime Labonne",
  "title_listed": "Fine-tune a Mistral-7b model with Direct Preference Optimization",
  "keywords": "DPO,偏好对齐,Mistral",
  "domain": "大模型算法",
  "content_type": "深度技术解析",
  "is_paid_flag": "部分免费/会员墙",
  "url": "https://towardsdatascience.com/fine-tune-a-mistral-7b-model-with-direct-preference-optimization-708042745aac/",
  "publish_date": "2024-01",
  "corpus_stage": "预训练/SFT",
  "notes": "",
  "id": "c0dbf6c13a15",
  "collected_at": "2026-10-01T21:53:53",
  "title": "Fine-tune a Mistral-7b model with Direct Preference Optimization | Towards Data Science",
  "body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\n# Fine-tune a Mistral-7b model with Direct Preference Optimization\nBoost the performance of your supervised fine-tuned models\n[Maxime Labonne](https://towardsdatascience.com/author/mlabonne/)\nJanuary 1, 202410 min read\n![Image by author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/0SklfpfBm5zX07hrP.png)\nImage by author\nPre-trained Large Language Models (LLMs) can only perform next-token prediction, making them unable to answer questions. This is why these base models are then fine-tuned on pairs of instructions and answers to act as helpful assistants. However, this process can still be flawed: fine-tuned LLMs can be biased, toxic, harmful, etc. This is where Reinforcement Learning from Human Feedback (RLHF) comes into play.\nRLHF provides different answers to the LLM, which are ranked according to a desired behavior (helpfulness, toxicity, etc.). The model learns to output the best answer among these candidates, hence mimicking the behavior we want to instill. Often seen as a way to censor models, this process has recently become popular for improving performance, as shown in [neural-chat-7b-v3–1](https://huggingface.co/Intel/neural-chat-7b-v3-1).\nIn this article, we will create [NeuralHermes-2.5](https://huggingface.co/mlabonne/NeuralHermes-2.5-Mistral-7B), by fine-tuning [OpenHermes-2.5](https://huggingface.co/teknium/OpenHermes-2.5-Mistral-7B) using a RLHF-like technique: Direct Preference Optimization (DPO). For this purpose, we will introduce a preference dataset, describe how the DPO algorithm works, and apply it to our model. We'll see that it significantly improves the performance of the base model on the Open LLM Leaderboard.\nAs per usual, the code is available on [GitHub](https://github.com/mlabonne/llm-course/blob/main/Fine_tune_a_Mistral_7b_model_with_DPO.ipynb) and [Google Colab](https://colab.research.google.com/drive/15iFBr1xWgztXvhrj5I9fBv20c7CFOPBE?usp=sharing).\nLearn this step by step with the interactive [AI Engineer](https://roadmap.sh/ai-engineer), [AI and Data Scientist](https://roadmap.sh/ai-data-scientist) and [Computer Science](https://roadmap.sh/computer-science) roadmaps.\n_**Update**_ _:_[_Jessie Davids_](https://www.linkedin.com/in/jesse-th-davids/) _, a reader who used this article and code, managed to create the best-performing model on the Open LLM Leaderboard ~7B param. Congrats to him! 🎉_\n![Image by author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/0ZtUkSHacdDNhNmol.jpg)\nImage by author\n## 🥇 Preference datasets\nPreference datasets are not standardized, but they typically consist of a collection of answers that are ranked by humans. This ranking is essential, as the RLHF process fine-tunes LLMs to output the preferred answer. Here is an example of [Anthropic/hh-rlhf](https://huggingface.co/datasets/Anthropic/hh-rlhf/viewer/default/train), a popular preference dataset:\n![Image by author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/0tNKdGVsJEDmocJoP.png)\nImage by author\nThe structure of the dataset is straightforward: for each row, there is one chosen (preferred) answer, and one rejected answer. The goal of RLHF is to guide the model to output the preferred answer.\nPreference datasets are notoriously costly and difficult to make, as they require collecting manual feedback from humans. This feedback is also subjective and can easily be biased toward confident (but wrong) answers or contradict itself (different annotators have different values). Over time, several solutions have been proposed to tackle these issues, such as replacing human feedback with AI feedback ([RLAIF](https://arxiv.org/abs/2212.08073)).\nThese datasets also tend to be a lot smaller than fine-tuning datasets. To illustrate this, the excellent [neural-chat-7b-v3–1](https://huggingface.co/Intel/neural-chat-7b-v3-1) (best 7B LLM on the [Open LLM Leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard) when it was released) uses 518k samples for fine-tuning ([Open-Orca/SlimOrca](https://huggingface.co/datasets/Open-Orca/SlimOrca)) but only 12.9k samples for RLHF ([Intel/orca_dpo_pairs](https://huggingface.co/datasets/Intel/orca_dpo_pairs)). In this case, the authors generated answers with GPT-4/3.5 to create the preferred answers, and with [Llama 2 13b chat](https://huggingface.co/meta-llama/Llama-2-13b-chat-hf) to create the rejected responses. It's a smart way to bypass human feedback and only rely on models with different levels of performance.\n## 🎓 Direct Preference Optimization\nWhile the concept of RLHF has been used in robotics for a long time, it was popularized for LLMs in OpenAI's paper [Fine-Tuning Language Models from Human Preferences](https://arxiv.org/pdf/1909.08593.pdf). In this paper, the authors present a framework where a reward model is trained to approximate human feedback. This reward model is then used to optimize the fine-tuned model's policy using the [Proximal Policy Optimization](https://arxiv.org/abs/1707.06347) (PPO) algorithm.\n![Image by author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/0-Spul1NZGwNs5N8t.png)\nImage by author\nThe core concept of PPO revolves around making smaller, incremental updates to the policy, as larger updates can lead to instability or suboptimal solutions. From experience, this technique is unfortunately still unstable (loss diverges), difficult to reproduce (numerous hyperparameters, sensitive to random seeds), and computationally expensive.\nThis is where Direct Preference Optimization (DPO) comes into play. DPO simplifies control by treating the task as a classification problem. Concretely, it uses two models: the **trained model** (or policy model) and a copy of it called the **reference model**. During training, the goal is to make sure the trained model outputs higher probabilities for preferred answers than the reference model. Conversely, we also want it to output lower probabilities for rejected answers. It means we're penalizing the LLM for bad answers and rewarding it for good ones.\n![Image by author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/0YZB41c8c0FVuUrmb.png)\nImage by author\nBy using the LLM itself as a reward model and employing binary cross-entropy objectives, DPO efficiently aligns the model's outputs with human preferences without the need for extensive sampling, reward model fitting, or intricate hyperparameter adjustments. It results in a more stable, more efficient, and computationally less demanding process.\n## 💾 Formatting the data\nIn this example, we'll fine-tune the excellent [OpenHermes-2.5-Mistral-7B](https://huggingface.co/teknium/OpenHermes-2.5-Mistral-7B), which is a Mistral-7b model that was only supervised fine-tuned. To this end, we'll use the [Intel/orca_dpo_pairs](https://huggingface.co/datasets/Intel/orca_dpo_pairs) dataset to align our model and improve its performance. We call this new model NeuralHermes-2.5-Mistral-7B.\nThe first step consists of installing the required libraries as follows.\nbash\n\n```\npip install -q datasets trl peft bitsandbytes sentencepiece wandb\n```\n\nOnce it's done, we can import the libraries. I'm also using the secrets tab in Google Colab to store my Hugging Face token.\npython\n\n```\nimport os\nimport gc\nimport torch\n\nimport transformers\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments, BitsAndBytesConfig\nfrom datasets import load_dataset\nfrom peft import LoraConfig, PeftModel, get_peft_model, prepare_model_for_kbit_training\nfrom trl import DPOTrainer\nimport bitsandbytes as bnb\nfrom google.colab import userdata\nimport wandb\n\n# Defined in the secrets tab in Google Colab\nhf_token = userdata.get('huggingface')\nwb_token = userdata.get('wandb')\nwandb.login(key=wb_token)\n\nmodel_name = \"teknium/OpenHermes-2.5-Mistral-7B\"\nnew_model = \"NeuralHermes-2.5-Mistral-7B\"\n```\n\nOpenHermes-2.5-Mistral-7B uses a specific chat template, called [ChatML](https://huggingface.co/docs/transformers/chat_templating). Here is an example of a conversation formatted with this template:\nsql\n\n```\n<|im_start|>system\nYou are a helpful chatbot assistant.<|im_end|>\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\nHi, how can I help you?<|im_end|>\n```\n\nAs you can see, ChatML defines different roles (system, user, assistant) and appends special tokens (`<|im_start|>` and `<|im_end|>`) to separate them. Moreover, `[DPOTrainer](https://huggingface.co/docs/trl/main/en/dpo_trainer)` also requires a specific format with three columns: prompt, chosen, and rejected.\nOur dataset contains four columns: system, question, chatgpt, and llama2–13b-chat. We'll simply concatenate the system and question columns to the prompt column. We'll also map the chatgpt column to \"chosen\" and llama2–13b-chat to \"rejected\". To format the dataset in a reliable way, we'll use the tokenizer's `apply_chat_template()` function, which already uses ChatML.\npython\n\n```\ndef chatml_format(example):\n    # Format system\n    if len(example['system']) > 0:\n        message = {\"role\": \"system\", \"content\": example['system']}\n        system = tokenizer.apply_chat_template([message], tokenize=False)\n    else:\n        system = \"\"\n\n    # Format instruction\n    message = {\"role\": \"user\", \"content\": example['question']}\n    prompt = tokenizer.apply_chat_template([message], tokenize=False, add_generation_prompt=True)\n\n    # Format chosen answer\n    chosen = example['chosen'] + \"<|im_end|>n\"\n\n    # Format rejected answer\n    rejected = example['rejected'] + \"<|im_end|>n\"\n\n    return {\n        \"prompt\": system + prompt,\n        \"chosen\": chosen,\n        \"rejected\": rejected,\n    }\n\n# Load dataset\ndataset = load_dataset(\"Intel/orca_dpo_pairs\")['train']\n\n# Save columns\noriginal_columns = dataset.column_names\n\n# Tokenizer\ntokenizer = AutoTokenizer.from_pretrained(model_name)\ntokenizer.pad_token = tokenizer.eos_token\ntokenizer.padding_side = \"left\"\n\n# Format dataset\ndataset = dataset.map(\n    chatml_format,\n    remove_columns=original_columns\n)\n```\n\nLet's print a sample of the formatted dataset to confirm that everything works as expected:\nbash\n\n```\n{'prompt': '<|im_start|>systemnYou are an AI assistant. You will be given a task. You must generate a detailed and long answer.<|im_end|>n<|im_start|>usernGenerate an approximately fifteen-word sentence that describes all this data: Midsummer House eatType restaurant; Midsummer House food Chinese; Midsummer House priceRange moderate; Midsummer House customer rating 3 out of 5; Midsummer House near All Bar One<|im_end|>n<|im_start|>assistantn',\n'chosen': 'Midsummer House is a moderately priced Chinese restaurant with a 3/5 customer rating, located near All Bar One.<|im_end|>n',\n'rejected': ' Sure! Here's a sentence that describes all the data you provided:nn\"Midsummer House is a moderately priced Chinese restaurant with a customer rating of 3 out of 5, located near All Bar One, offering a variety of delicious dishes.\"<|im_end|>n'}\n```\n\nWe can see that the prompt combines system and user instructions. Thanks to the `add_generation_prompt=True` argument, it also appends the beginning of the assistant's answer. If you want to skip this step, you can directly used the preprocessed dataset as [mlabonne/chatml_dpo_pairs](https://huggingface.co/datasets/mlabonne/chatml_dpo_pairs).\n## ⚙️ Training the model with DPO\nNext, we define the LoRA configurations to train the model. As described in [Intel's blog post](https://medium.com/intel-analytics-software/the-practice-of-supervised-finetuning-and-direct-preference-optimization-on-habana-gaudi2-a1197d8a3cd3), we set the rank value to be equal to the `lora_alpha`, which is unusual (2 * `r` as a rule of thumb). We also target all the linear modules with adapters.\npython\n\n```\n# LoRA configuration\npeft_config = LoraConfig(\n    r=16,\n    lora_alpha=16,\n    lora_dropout=0.05,\n    bias=\"none\",\n    task_type=\"CAUSAL_LM\",\n    target_modules=['k_proj', 'gate_proj', 'v_proj', 'up_proj', 'q_proj', 'o_proj', 'down_proj']\n)\n```\n\nWe're now ready to load the model we want to fine-tune with DPO. In this case, two models are required: the model to fine-tune as well as the reference model. This is mostly for the sake of readability, as the `DPOTrainer` object automatically creates a reference model if none is provided.\npython\n\n```\n# Model to fine-tune\nmodel = AutoModelForCausalLM.from_pretrained(\n    model_name,\n    torch_dtype=torch.float16,\n    load_in_4bit=True\n)\nmodel.config.use_cache = False\n\n# Reference model\nref_model = AutoModelForCausalLM.from_pretrained(\n    model_name,\n    torch_dtype=torch.float16,\n    load_in_4bit=True\n)\n```\n\nThe final step consists of providing all the hyperparameters to `TrainingArguments` and `DPOTrainer`:\n  * Among them, the `beta` parameter is unique to DPO since it controls the divergence from the initial policy (0.1 is a typical value for it).\n  * Compared to the values described in [Intel's blog post](https://medium.com/intel-analytics-software/the-practice-of-supervised-finetuning-and-direct-preference-optimization-on-habana-gaudi2-a1197d8a3cd3), we lower the learning rate (from 5e-4 to 5e-5) and the number of steps (from 1,000 to 200). I manually optimized these values after a few runs to stabilize training and achieve the best results.\n\n\nWe can now start training the model. Note that it requires an A100 GPU and takes between 1 hour to complete the training.\npython\n\n```\n# Training arguments\ntraining_args = TrainingArguments(\n    per_device_train_batch_size=4,\n    gradient_accumulation_steps=4,\n    gradient_checkpointing=True,\n    learning_rate=5e-5,\n    lr_scheduler_type=\"cosine\",\n    max_steps=200,\n    save_strategy=\"no\",\n    logging_steps=1,\n    output_dir=new_model,\n    optim=\"paged_adamw_32bit\",\n    warmup_steps=100,\n    bf16=True,\n    report_to=\"wandb\",\n)\n\n# Create DPO trainer\ndpo_trainer = DPOTrainer(\n    model,\n    ref_model,\n    args=training_args,\n    train_dataset=dataset,\n    tokenizer=tokenizer,\n    peft_config=peft_config,\n    beta=0.1,\n    max_prompt_length=1024,\n    max_length=1536,\n)\n\n# Fine-tune model with DPO\ndpo_trainer.train()\n```\n\nOur model is now fine-tuned. You can check the project on Weights & Biases [at this address](https://wandb.ai/mlabonne/NeuralHermes-2-5-Mistral-7B/runs/axe71gr0?workspace=user-mlabonne). Here are some interesting metrics to analyze:\n![Image by author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/0po4OaIs9EY_c4Rcu.png)\nImage by author\nInterestingly, the training loss quickly drops to zero (before 50 steps), despite 100 warmup steps. Meanwhile, the other metrics keep evolving.\nThe train/rewards/chosen and train/rewards/rejected plots correspond to the mean difference between the log probabilities output by the trained and reference models. It makes sense that, over time, they diverge as our trained model learns the preferred answers. The train/rewards/margins plot also shows the difference between these two plots. Finally, the train/reward/accuracies plot shows the frequency of choosing the preferred answer. The trained model quickly reaches a perfect accuracy score, which is a good sign but could also mean that the difference between preferred and rejected answers is too obvious.\nNow that it's trained, we can merge the adapter with the original model. Next, we save the merged model and the tokenizer before pushing it to the Hugging Face Hub.\npython\n\n```\n# Save artifacts\ndpo_trainer.model.save_pretrained(\"final_checkpoint\")\ntokenizer.save_pretrained(\"final_checkpoint\")\n\n# Flush memory\ndel dpo_trainer, model, ref_model\ngc.collect()\ntorch.cuda.empty_cache()\n\n# Reload model in FP16 (instead of NF4)\nbase_model = AutoModelForCausalLM.from_pretrained(\n    model_name,\n    return_dict=True,\n    torch_dtype=torch.float16,\n)\ntokenizer = AutoTokenizer.from_pretrained(model_name)\n\n# Merge base model with the adapter\nmodel = PeftModel.from_pretrained(base_model, \"final_checkpoint\")\nmodel = model.merge_and_unload()\n\n# Save model and tokenizer\nmodel.save_pretrained(new_model)\ntokenizer.save_pretrained(new_model)\n\n# Push them to the HF Hub\nmodel.push_to_hub(new_model, use_temp_dir=False, token=hf_token)\ntokenizer.push_to_hub(new_model, use_temp_dir=False, token=hf_token)\n```\n\nLet's see how our model performs in a real test. We'll format the prompt to ask a basic question: \"What is a Large Language Model?\"\npython\n\n```\n# Format prompt\nmessage = [\n    {\"role\": \"system\", \"content\": \"You are a helpful assistant chatbot.\"},\n    {\"role\": \"user\", \"content\": \"What is a Large Language Model?\"}\n]\ntokenizer = AutoTokenizer.from_pretrained(new_model)\nprompt = tokenizer.apply_chat_template(message, add_generation_prompt=True, tokenize=False)\n\n# Create pipeline\npipeline = transformers.pipeline(\n    \"text-generation\",\n    model=new_model,\n    tokenizer=tokenizer\n)\n\n# Generate text\nsequences = pipeline(\n    prompt,\n    do_sample=True,\n    temperature=0.7,\n    top_p=0.9,\n    num_return_sequences=1,\n    max_length=200,\n)\nprint(sequences[0]['generated_text'])\n```\n\nHere's the answer from the model:\nsql\n\n```\nA large language model is a type of artificial intelligence (AI) system that has been trained on vast amounts of text data. These models are designed to understand and generate human language, allowing them to perform various natural language processing tasks, such as text generation, language translation, and question answering. Large language models typically use deep learning techniques, like recurrent neural networks (RNNs) or transformers, to learn patterns and relationships in the data, enabling them to generate coherent and contextually relevant responses. The size of these models, in terms of the number of parameters and the volume of data they are trained on, plays a significant role in their ability to comprehend and produce complex language structures.\n```\n\nEverything seems to be working, we can now evaluate the merged model. As this is a general-purpose model, we can leverage the [lm-evaluation-harness](https://github.com/EleutherAI/lm-evaluation-harness) to evaluate it. As the process is quite resource-intensive, we can also directly submit it for evaluation on the [Open LLM Leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard). It took a few days, but here are the results compared to other OpenHermes models:\n![Image by author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/0ELtGoA3Hrs7BfvRs.png)\nImage by author\nCompared to the original model, NeuralHermes-2–5-Mistral-7B model improved the average score by 6.7 points (particularly on GSM8K). This is an unexpectedly large improvement, which showcases the power of Direct Preference Optimization.\n## Conclusion\nIn this article, we fine-tuned an already supervised fine-tuned model using DPO and created our own [NeuralHermes-2.5](https://huggingface.co/mlabonne/NeuralHermes-2.5-Mistral-7B) model. By leveraging a high-quality preference dataset, we created a sample-efficient fine-tuning pipeline that produced a significant improvement on the Open LLM Leaderboard. If you want to give it a try, you can find quantized variants of this model or use this [Hugging Face Space](https://huggingface.co/spaces/zhangtao103239/NeuralHermes-2.5-Mistral-7B-GGUF-Chat).\nNote that our fine-tuning pipeline can still be improved in different ways. For example, the preference dataset is still quite raw and could be improved with more filtering and by using different models. In addition, numerous hyperparameters can still be tweaked to achieve better results. In particular, the learning rate can still be lowered to train the model on more steps and inject more preference data.\n## References\n  * [Fine-tune Llama 2 with DPO](https://huggingface.co/blog/dpo-trl) by Kashif Rasul, Younes Belkada, and Leandro von Werra.\n  * [Supervised Fine-Tuning and Direct Preference Optimization on Intel Gaudi2](https://medium.com/intel-analytics-software/the-practice-of-supervised-finetuning-and-direct-preference-optimization-on-habana-gaudi2-a1197d8a3cd3) by Kaokao Lv, Wenxin Zhang, and Haihao Shen.\n  * [llama2-fine-tune](https://github.com/mzbac/llama2-fine-tune) by mzbac.\n\n\n* * *\n_Learn more about machine learning and support my work with one click - become a Medium member here:_\n> [**Join Medium with my referral link - Maxime Labonne**](https://medium.com/@mlabonne/membership)\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657499317_sxy3ci.png)\nWritten By\n## [Maxime Labonne](https://towardsdatascience.com/author/mlabonne/)\n[See all from Maxime Labonne](https://towardsdatascience.com/author/mlabonne/)\n[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Artificial Intelligence](https://towardsdatascience.com/tag/artificial-intelligence/)[Data Science](https://towardsdatascience.com/tag/data-science/)[Large Language Models](https://towardsdatascience.com/tag/large-language-models/)[Programming](https://towardsdatascience.com/tag/programming/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Ffine-tune-a-mistral-7b-model-with-direct-preference-optimization-708042745aac%2F&title=Fine-tune%20a%20Mistral-7b%20model%20with%20Direct%20Preference%20Optimization)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Ffine-tune-a-mistral-7b-model-with-direct-preference-optimization-708042745aac%2F&title=Fine-tune%20a%20Mistral-7b%20model%20with%20Direct%20Preference%20Optimization)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Ffine-tune-a-mistral-7b-model-with-direct-preference-optimization-708042745aac%2F&text=Fine-tune%20a%20Mistral-7b%20model%20with%20Direct%20Preference%20Optimization)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/01/0HXXyDFWGhV7pvo8E-scaled.jpg)](https://towardsdatascience.com/implementing-linear-regression-with-gradient-descent-from-scratch-f6d088ec1219/)\n## [Implementing Linear Regression with Gradient Descent From Scratch](https://towardsdatascience.com/implementing-linear-regression-with-gradient-descent-from-scratch-f6d088ec1219/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nBuild a strong machine learning foundation by fully understanding and deriving gradient descent\n[Marvin Lanhenke](https://towardsdatascience.com/author/marvinlanhenke/)\nJanuary 16, 20226 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/02/1XsFcyoLXNdAkbSfNGnxhEg.png)](https://towardsdatascience.com/confusion-matrix-un-confused-1ba98dee0d7f/)\n## [Confusion Matrix \"Un-confused\"](https://towardsdatascience.com/confusion-matrix-un-confused-1ba98dee0d7f/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nBreaking down the confusion matrix\n[Kurtis Pykes](https://towardsdatascience.com/author/kurtispykes/)\nFebruary 16, 20207 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/09/1JBUbbzy_HnFt6q4OPlPplw.png)](https://towardsdatascience.com/overcoming-data-visualization-imposter-syndrome-5c22ec1bca3d/)\n## [Overcoming Data Visualization Impostor Syndrome](https://towardsdatascience.com/overcoming-data-visualization-imposter-syndrome-5c22ec1bca3d/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nShared data visualizations on social media are at an alarmingly high level - this leaves many people discouraged and afraid to share...\n[Adam Mico](https://towardsdatascience.com/author/adammico/)\nSeptember 26, 20217 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1kKgc3CEhUSmKi0971S7zfA.jpeg)](https://towardsdatascience.com/how-to-onboard-new-data-analysts-45605f904ef9/)\n## [How to Onboard New Data Analysts](https://towardsdatascience.com/how-to-onboard-new-data-analysts-45605f904ef9/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nTips to add value faster\n[Vicky Yu](https://towardsdatascience.com/author/madfordata/)\nApril 11, 20213 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/11/0vU_Or7A3jt0bbWhT.jpg)](https://towardsdatascience.com/understanding-apache-hive-llap-fa6d93f73032/)\n## [Understanding Apache Hive LLAP](https://towardsdatascience.com/understanding-apache-hive-llap-fa6d93f73032/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nIn this post, I try to explain what LLAP is for Apache Hive and how it can help us in reducing query latency.\n[Sunny Srinidhi](https://towardsdatascience.com/author/contactsunny/)\nNovember 18, 20218 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/11/0HJ1_XJdWanbG0ktD-scaled.jpg)](https://towardsdatascience.com/in-the-8-key-mlops-roles-where-do-you-fit-in-251272ca5488/)\n## [In the 8 Key MLOps Roles, Where Do You Fit In?](https://towardsdatascience.com/in-the-8-key-mlops-roles-where-do-you-fit-in-251272ca5488/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nLarge-scale data science teams can have several distinct roles & responsibilities to manage machine learning operations.\n[Thuwarakesh Murallie](https://towardsdatascience.com/author/thuwarakesh/)\nNovember 9, 20217 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/02/1qLx0ZFV-yL_lOJZ5J1gqQ.jpeg)](https://towardsdatascience.com/how-to-deliver-a-successful-data-presentation-bfd23684197d/)\n## [How to Deliver a Successful Data Presentation](https://towardsdatascience.com/how-to-deliver-a-successful-data-presentation-bfd23684197d/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nLessons I've learned from presenting to senior leadership\n[Vicky Yu](https://towardsdatascience.com/author/madfordata/)\nFebruary 9, 20214 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2019/05/1qYrPvxRwUeZAc7UmjH158Q-scaled.jpeg)](https://towardsdatascience.com/image-manipulation-tools-for-python-6eb0908ed61f/)\n## [10 Python image manipulation tools](https://towardsdatascience.com/image-manipulation-tools-for-python-6eb0908ed61f/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nAn overview of some of the commonly used Python libraries that provide an easy and intuitive way to transform images.\n[Parul Pandey](https://towardsdatascience.com/author/pandeyparul/)\nMay 26, 20197 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/11/1DK4seQk4sTK1ZMzj_b6ifQ.png)](https://towardsdatascience.com/probabilistic-deep-learning-for-wind-turbines-b8ea00fabe30/)\n## [Probabilistic Deep Learning for Wind Turbines](https://towardsdatascience.com/probabilistic-deep-learning-for-wind-turbines-b8ea00fabe30/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nHow to apply Gaussian Processes on big data\n[Michael Berk](https://towardsdatascience.com/author/michaelberk/)\nNovember 1, 20216 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3642/image?etag=1780830904480&width=500&height=500) Check Your Biases ](https://towardsdatascience.com/check-your-biases-ba2685a7f799/ \"Check Your Biases\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4973/image?etag=1782232567105&width=500&height=500) Machine Learning Tricks, Learning with ChatGPT, and Other Recent Must-Reads ](https://towardsdatascience.com/machine-learning-tricks-learning-with-chatgpt-and-other-recent-must-reads-f277648a1921/ \"Machine Learning Tricks, Learning with ChatGPT, and Other Recent Must-Reads\")\n\n\nword word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word\n  \nmmMwWLliI0fiflO&1  \nmmMwWLliI0fiflO&1  \nmmMwWLliI0fiflO&1  \nmmMwWLliI0fiflO&1  \nmmMwWLliI0fiflO&1  \nmmMwWLliI0fiflO&1  \nmmMwWLliI0fiflO&1\n",
  "metadata": {
    "title": "Fine-tune a Mistral-7b model with Direct Preference Optimization | Towards Data Science",
    "description": "Boost the performance of your supervised fine-tuned models",
    "keywords": null,
    "author": "Maxime Labonne",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Fine-tune a Mistral-7b model with Direct Preference Optimization",
    "og:description": "Boost the performance of your supervised fine-tuned models",
    "og:url": "https://towardsdatascience.com/fine-tune-a-mistral-7b-model-with-direct-preference-optimization-708042745aac/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/0SklfpfBm5zX07hrP.png",
    "og:image:width": "1792",
    "og:image:height": "1024",
    "og:image:type": "image/png",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Maxime Labonne",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "10 min read",
    "article:published_time": "2024-01-01T18:09:45.000Z",
    "article:modified_time": "2024-01-01T18:09:45.000Z",
    "article:author": "https://towardsdatascience.com/author/mlabonne/"
  },
  "paywall": {
    "listed_paid": true,
    "detected": false,
    "marker": "",
    "public_only": true,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": "",
    "retried": true
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/c0dbf6c13a15/code/block_000.txt",
      "chars": 66
    },
    {
      "language": "txt",
      "file": "attachments/c0dbf6c13a15/code/block_001.txt",
      "chars": 613
    },
    {
      "language": "txt",
      "file": "attachments/c0dbf6c13a15/code/block_002.txt",
      "chars": 152
    },
    {
      "language": "txt",
      "file": "attachments/c0dbf6c13a15/code/block_003.txt",
      "chars": 1075
    },
    {
      "language": "txt",
      "file": "attachments/c0dbf6c13a15/code/block_004.txt",
      "chars": 842
    },
    {
      "language": "txt",
      "file": "attachments/c0dbf6c13a15/code/block_005.txt",
      "chars": 242
    },
    {
      "language": "txt",
      "file": "attachments/c0dbf6c13a15/code/block_006.txt",
      "chars": 309
    },
    {
      "language": "txt",
      "file": "attachments/c0dbf6c13a15/code/block_007.txt",
      "chars": 690
    },
    {
      "language": "txt",
      "file": "attachments/c0dbf6c13a15/code/block_008.txt",
      "chars": 817
    },
    {
      "language": "txt",
      "file": "attachments/c0dbf6c13a15/code/block_009.txt",
      "chars": 635
    },
    {
      "language": "txt",
      "file": "attachments/c0dbf6c13a15/code/block_010.txt",
      "chars": 774
    }
  ],
  "images": [
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/0SklfpfBm5zX07hrP.png",
      "alt": "Image by author",
      "local_path": "attachments/c0dbf6c13a15/images/000.png",
      "bytes": 3381203,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/0ZtUkSHacdDNhNmol.jpg",
      "alt": "Image by author",
      "local_path": "attachments/c0dbf6c13a15/images/001.jpg",
      "bytes": 72109,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/0tNKdGVsJEDmocJoP.png",
      "alt": "Image by author",
      "local_path": "attachments/c0dbf6c13a15/images/002.png",
      "bytes": 80361,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/0-Spul1NZGwNs5N8t.png",
      "alt": "Image by author",
      "local_path": "attachments/c0dbf6c13a15/images/003.png",
      "bytes": 583868,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/0YZB41c8c0FVuUrmb.png",
      "alt": "Image by author",
      "local_path": "attachments/c0dbf6c13a15/images/004.png",
      "bytes": 591337,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/0po4OaIs9EY_c4Rcu.png",
      "alt": "Image by author",
      "local_path": "attachments/c0dbf6c13a15/images/005.png",
      "bytes": 167956,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/0ELtGoA3Hrs7BfvRs.png",
      "alt": "Image by author",
      "local_path": "attachments/c0dbf6c13a15/images/006.png",
      "bytes": 85288,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2022/01/0HXXyDFWGhV7pvo8E-scaled.jpg",
      "alt": "",
      "local_path": "attachments/c0dbf6c13a15/images/007.jpg",
      "bytes": 352953,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2020/02/1XsFcyoLXNdAkbSfNGnxhEg.png",
      "alt": "",
      "local_path": "attachments/c0dbf6c13a15/images/008.png",
      "bytes": 10137,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/09/1JBUbbzy_HnFt6q4OPlPplw.png",
      "alt": "",
      "local_path": "attachments/c0dbf6c13a15/images/009.png",
      "bytes": 2131226,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1kKgc3CEhUSmKi0971S7zfA.jpeg",
      "alt": "",
      "local_path": "attachments/c0dbf6c13a15/images/010.jpeg",
      "bytes": 100888,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/11/0vU_Or7A3jt0bbWhT.jpg",
      "alt": "",
      "local_path": "attachments/c0dbf6c13a15/images/011.jpg",
      "bytes": 505888,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/11/0HJ1_XJdWanbG0ktD-scaled.jpg",
      "alt": "",
      "local_path": "attachments/c0dbf6c13a15/images/012.jpg",
      "bytes": 416417,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/02/1qLx0ZFV-yL_lOJZ5J1gqQ.jpeg",
      "alt": "",
      "local_path": "attachments/c0dbf6c13a15/images/013.jpeg",
      "bytes": 116317,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2019/05/1qYrPvxRwUeZAc7UmjH158Q-scaled.jpeg",
      "alt": "",
      "local_path": "attachments/c0dbf6c13a15/images/014.jpeg",
      "bytes": 283060,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/11/1DK4seQk4sTK1ZMzj_b6ifQ.png",
      "alt": "",
      "local_path": "attachments/c0dbf6c13a15/images/015.png",
      "bytes": 342587,
      "downloaded": true
    }
  ],
  "audio": [],
  "videos": [],
  "links": [],
  "retry_at": "2026-10-03T07:59:09",
  "repair_version": 2,
  "repaired_at": "2026-10-14T11:11:48Z",
  "source_url": "https://towardsdatascience.com/fine-tune-a-mistral-7b-model-with-direct-preference-optimization-708042745aac/",
  "delivery_status": "excluded_paid",
  "discovery_status": "excluded_paid",
  "missing_reason": "按原约定排除付费/会员全文"
}