{
  "source_file": "0930",
  "source_platform": "个人博客",
  "author": "Philipp Schmid",
  "title_listed": "Fine-tune LLMs in 2024 with TRL",
  "keywords": "TRL,微调,RLHF",
  "domain": "大模型算法",
  "content_type": "教程",
  "is_paid_flag": "否",
  "url": "https://www.philschmid.de/fine-tune-llms-in-2024-with-trl",
  "publish_date": "2024-01",
  "corpus_stage": "强化学习/对齐",
  "notes": "2024年用TRL微调LLM",
  "id": "3135846076ac",
  "collected_at": "2026-10-02T14:29:08",
  "title": "How to Fine-Tune LLMs in 2024 with Hugging Face",
  "body_markdown": "How to Fine-Tune LLMs in 2024 with Hugging Face\nJanuary 23, 2024\n17\nminute read\nView Code\nLarge Language Models or LLMs have seen a lot of progress in the last year. We went from no ChatGPT competitor to a whole zoo of LLMs, including Meta AI's\nLlama 2\n, Mistrals\nMistral\n&\nMixtral\nmodels, TII\nFalcon\n, and many more.\nThose LLMs can be used for a variety of tasks, including chatbots, question answering, summarization without any additional training. However, if you want to customize a model for your application. You may need to fine-tune the model on your data to achieve higher quality results than prompting or saving cost by training smaller models more efficient model.\nThis blog post walks you thorugh how to fine-tune open LLMs using Hugging Face\nTRL\n,\nTransformers\n&\ndatasets\nin 2024. In the blog, we are going to:\nDefine our use case\nSetup development environment\nCreate and prepare the dataset\nFine-tune LLM using\ntrl\nand the\nSFTTrainer\nTest and evaluate the LLM\nDeploy the LLM for Production\nNote: This blog was created to run on consumer size GPUs (24GB), e.g. NVIDIA A10G or RTX 4090/3090, but can be easily adapted to run on bigger GPUs.\n1. Define our use case\nWhen fine-tuning LLMs, it is important you know your use case and the task you want to solve. This will help you to choose the right model or help you to create a dataset to fine-tune your model. If you haven't defined your use case yet. You might want to go back to the drawing board.\nI want to mention that not all use cases require fine-tuning and it is always recommended to evaluate and try out already fine-tuned models or API-based models before fine-tuning your own model.\nAs an example, we are going to use the following use case:\nWe want to fine-tune a model, which can generate SQL queries based on a natural language instruction, which can then be integrated into our BI tool. The goal is to reduce the time it takes to create a SQL query and make it easier for non-technical users to create SQL queries.\nText to SQL can be a good use case for fine-tuning LLMs, as it is a complex task that requires a lot of (internal) knowledge about the data and the SQL language.\n2. Setup development environment\nOur first step is to install Hugging Face Libraries and Pytorch, including 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.\nPython\n# Install Pytorch & other libraries\n!\npip install\n\"torch==2.1.2\"\ntensorboard\n# Install Hugging Face libraries\n!\npip install\n--\nupgrade \\\n\"transformers==4.36.2\"\n\\\n\"datasets==2.16.1\"\n\\\n\"accelerate==0.26.1\"\n\\\n\"evaluate==0.4.1\"\n\\\n\"bitsandbytes==0.42.0\"\n\\\n# \"trl==0.7.10\" # \\\n# \"peft==0.7.1\" \\\n# install peft & trl from github\n!\npip install git+https://github.com/huggingface/trl@a3c5b7178ac4f65569975efadc97db2f3749c65e\n--\nupgrade\n!\npip install git+https://github.com/huggingface/peft@\n4a1559582281fc3c9283892caea8ccef1d6f5a4f\n--\nupgrade\nIf you are using a GPU with Ampere architecture (e.g. NVIDIA A10G or RTX 4090/3090) or newer you can use Flash attention. Flash Attention is a an method that reorders the attention computation and leverages classical techniques (tiling, recomputation) to significantly speed it up and reduce memory usage from quadratic to linear in sequence length. The TL;DR; accelerates training up to 3x. Learn more at\nFlashAttention\n.\nNote: If your machine has less than 96GB of RAM and lots of CPU cores, reduce the number of\nMAX_JOBS\n. On the\ng5.2xlarge\nwe used\n4\n.\nPython\nimport\ntorch;\nassert\ntorch.cuda.\nget_device_capability\n()[\n0\n] >=\n8\n,\n'Hardware not supported for Flash Attention'\n# install flash-attn\n!\npip install ninja packaging\n!\nMAX_JOBS\n=\n4\npip install flash-attn\n--\nno-build-isolation\nInstalling flash attention can take quite a bit of time (10-45 minutes).\nWe will use the\nHugging Face Hub\nas 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\nHugging Face\nfor this. After you have an account, we will use the\nlogin\nutil from the\nhuggingface_hub\npackage to log into our account and store our token (access key) on the disk.\nPython\nfrom\nhuggingface_hub\nimport\nlogin\nlogin\n(\ntoken\n=\n\"\"\n,\n# ADD YOUR TOKEN HERE\nadd_to_git_credential\n=\nTrue\n)\n3. Create and prepare the dataset\nOnce you have determined that fine-tuning is the right solution we need to create a dataset to fine-tune our model. The dataset should be a diverse set of demonstrations of the task you want to solve. There are several ways to create such a dataset, including:\nUsing existing open-source datasets, e.g.,\nSpider\nUsing LLMs to create synthetically datasets, e.g.,\nAlpaca\nUsing Humans to create datasets, e.g.,\nDolly\n.\nUsing a combination of the above methods, e.g.,\nOrca\nEach of the methods has its own advantages and disadvantages and depends on the budget, time, and quality requirements. For example, using an existing dataset is the easiest but might not be tailored to your specific use case, while using humans might be the most accurate but can be time-consuming and expensive. It is also possible to combine several methods to create an instruction dataset, as shown in\nOrca: Progressive Learning from Complex Explanation Traces of GPT-4.\nIn our example we will use an already existing dataset called\nsql-create-context\n, which contains samples of natural language instructions, schema definitions and the corresponding SQL query.\nWith the latest release of\ntrl\nwe now support popular instruction and conversation dataset formats. This means we only need to convert our dataset to one of the supported formats and\ntrl\nwill take care of the rest. Those formats include:\nconversational format\nJSON\n{\n\"messages\"\n: [{\n\"role\"\n:\n\"system\"\n,\n\"content\"\n:\n\"You are...\"\n}, {\n\"role\"\n:\n\"user\"\n,\n\"content\"\n:\n\"...\"\n}, {\n\"role\"\n:\n\"assistant\"\n,\n\"content\"\n:\n\"...\"\n}]}\n{\n\"messages\"\n: [{\n\"role\"\n:\n\"system\"\n,\n\"content\"\n:\n\"You are...\"\n}, {\n\"role\"\n:\n\"user\"\n,\n\"content\"\n:\n\"...\"\n}, {\n\"role\"\n:\n\"assistant\"\n,\n\"content\"\n:\n\"...\"\n}]}\n{\n\"messages\"\n: [{\n\"role\"\n:\n\"system\"\n,\n\"content\"\n:\n\"You are...\"\n}, {\n\"role\"\n:\n\"user\"\n,\n\"content\"\n:\n\"...\"\n}, {\n\"role\"\n:\n\"assistant\"\n,\n\"content\"\n:\n\"...\"\n}]}\ninstruction format\nJSON\n{\n\"prompt\"\n:\n\"<prompt text>\"\n,\n\"completion\"\n:\n\"<ideal generated text>\"\n}\n{\n\"prompt\"\n:\n\"<prompt text>\"\n,\n\"completion\"\n:\n\"<ideal generated text>\"\n}\n{\n\"prompt\"\n:\n\"<prompt text>\"\n,\n\"completion\"\n:\n\"<ideal generated text>\"\n}\nIn our example we are going to load our open-source dataset using the 🤗 Datasets library and then convert it into the the conversational format, where we include the schema definition in the system message for our assistant. We'll then save the dataset as jsonl file, which we can then use to fine-tune our model. We are randomly downsampling the dataset to only 10,000 samples.\nNote: This step can be different for your use case. For example, if you have already a dataset from, e.g. working with OpenAI, you can skip this step and go directly to the fine-tuning step.\nPython\nfrom\ndatasets\nimport\nload_dataset\n# Convert dataset to OAI messages\nsystem_message =\n\"\"\"You are an text to SQL query translator. Users will ask you questions in English and you will generate a SQL query based on the provided SCHEMA.\nSCHEMA:\n{schema}\"\"\"\ndef\ncreate_conversation\n(\nsample\n):\nreturn\n{\n\"messages\"\n: [\n{\n\"role\"\n:\n\"system\"\n,\n\"content\"\n: system_message.\nformat\n(\nschema\n=sample[\n\"context\"\n])},\n{\n\"role\"\n:\n\"user\"\n,\n\"content\"\n: sample[\n\"question\"\n]},\n{\n\"role\"\n:\n\"assistant\"\n,\n\"content\"\n: sample[\n\"answer\"\n]}\n]\n}\n# Load dataset from the hub\ndataset =\nload_dataset\n(\n\"b-mc2/sql-create-context\"\n,\nsplit\n=\n\"train\"\n)\ndataset = dataset.\nshuffle\n().\nselect\n(range(\n12500\n))\n# Convert dataset to OAI messages\ndataset = dataset.\nmap\n(create_conversation,\nremove_columns\n=dataset.features,\nbatched\n=\nFalse\n)\n# split dataset into 10,000 training samples and 2,500 test samples\ndataset = dataset.\ntrain_test_split\n(\ntest_size\n=\n2500\n/\n12500\n)\nprint(dataset[\n\"train\"\n][\n345\n][\n\"messages\"\n])\n# save datasets to disk\ndataset[\n\"train\"\n].\nto_json\n(\n\"train_dataset.json\"\n,\norient\n=\n\"records\"\n)\ndataset[\n\"test\"\n].\nto_json\n(\n\"test_dataset.json\"\n,\norient\n=\n\"records\"\n)\n4. Fine-tune LLM using\ntrl\nand the\nSFTTrainer\nWe are now ready to fine-tune our model. We will use the\nSFTTrainer\nfrom\ntrl\nto fine-tune our model. The\nSFTTrainer\nmakes it straightfoward to supervise fine-tune open LLMs. The\nSFTTrainer\nis a subclass of the\nTrainer\nfrom the\ntransformers\nlibrary and supports all the same features, including logging, evaluation, and checkpointing, but adds additiional quality of life features, including:\nDataset formatting, including conversational and instruction format\nTraining on completions only, ignoring prompts\nPacking datasets for more efficient training\nPEFT (parameter-efficient fine-tuning) support including Q-LoRA\nPreparing the model and tokenizer for conversational fine-tuning (e.g. adding special tokens)\nWe will use the dataset formatting, packing and PEFT features in our example. As peft method we will use\nQLoRA\na technique to reduce the memory footprint of large language models during finetuning, without sacrificing performance by using quantization. If you want to learn more about QLoRA and how it works, check out\nMaking LLMs even more accessible with bitsandbytes, 4-bit quantization and QLoRA\nblog post.\nNow, lets get started! 🚀 Let's load our json dataset from disk.\nPython\nfrom\ndatasets\nimport\nload_dataset\n# Load jsonl data from disk\ndataset =\nload_dataset\n(\n\"json\"\n,\ndata_files\n=\n\"train_dataset.json\"\n,\nsplit\n=\n\"train\"\n)\nNext, we will load our LLM. For our use case we are going to use CodeLlama 7B. CodeLlama is a Llama model trained for general code synthesis and understanding.\nBut we can easily swap out the model for another model, e.g.\nMistral\nor\nMixtral\nmodels, TII\nFalcon\n, or any other LLMs by changing our\nmodel_id\nvariable. We will use bitsandbytes to quantize our model to 4-bit.\nNote: Be aware the bigger the model the more memory it will require. In our example we will use the 7B version, which can be tuned on 24GB GPUs. If you have a smaller GPU.\nCorrectly, preparing the model and tokenizer for training chat/conversational models is crucial. We need to add new special tokens to the tokenizer and model to teach them the different roles in a conversation. In\ntrl\nwe have a convenient method with\nsetup_chat_format\n, which:\nAdds special tokens to the tokenizer, e.g.\n<|im_start|>\nand\n<|im_end|>\n, to indicate the start and end of a conversation.\nResizes the model’s embedding layer to accommodate the new tokens.\nSets the\nchat_template\nof the tokenizer, which is used to format the input data into a chat-like format. The default is\nchatml\nfrom OpenAI.\nPython\nimport\ntorch\nfrom\ntransformers\nimport\nAutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig\nfrom\ntrl\nimport\nsetup_chat_format\n# Hugging Face model id\nmodel_id =\n\"codellama/CodeLlama-7b-hf\"\n# or `mistralai/Mistral-7B-v0.1`\n# BitsAndBytesConfig int-4 config\nbnb_config =\nBitsAndBytesConfig\n(\nload_in_4bit\n=\nTrue\n,\nbnb_4bit_use_double_quant\n=\nTrue\n,\nbnb_4bit_quant_type\n=\n\"nf4\"\n,\nbnb_4bit_compute_dtype\n=torch.bfloat16\n)\n# Load model and tokenizer\nmodel = AutoModelForCausalLM.\nfrom_pretrained\n(\nmodel_id,\ndevice_map\n=\n\"auto\"\n,\nattn_implementation\n=\n\"flash_attention_2\"\n,\ntorch_dtype\n=torch.bfloat16,\nquantization_config\n=bnb_config\n)\ntokenizer = AutoTokenizer.\nfrom_pretrained\n(model_id)\ntokenizer.padding_side =\n'right'\n# to prevent warnings\n# # set chat template to OAI chatML, remove if you start from a fine-tuned model\nmodel, tokenizer =\nsetup_chat_format\n(model, tokenizer)\nThe\nSFTTrainer\nsupports a native integration with\npeft\n, which makes it super easy to efficiently tune LLMs using, e.g. QLoRA. We only need to create our\nLoraConfig\nand provide it to the trainer. Our\nLoraConfig\nparameters are defined based on the\nqlora paper\nand sebastian's\nblog post\n.\nPython\nfrom\npeft\nimport\nLoraConfig\n# LoRA config based on QLoRA paper & Sebastian Raschka experiment\npeft_config =\nLoraConfig\n(\nlora_alpha\n=\n128\n,\nlora_dropout\n=\n0.05\n,\nr\n=\n256\n,\nbias\n=\n\"none\"\n,\ntarget_modules\n=\n\"all-linear\"\n,\ntask_type\n=\n\"CAUSAL_LM\"\n,\n)\nBefore we can start our training we need to define the hyperparameters (\nTrainingArguments\n) we want to use.\nPython\nfrom\ntransformers\nimport\nTrainingArguments\nargs =\nTrainingArguments\n(\noutput_dir\n=\n\"code-llama-7b-text-to-sql\"\n,\n# directory to save and repository id\nnum_train_epochs\n=\n3\n,\n# number of training epochs\nper_device_train_batch_size\n=\n3\n,\n# batch size per device during training\ngradient_accumulation_steps\n=\n2\n,\n# number of steps before performing a backward/update pass\ngradient_checkpointing\n=\nTrue\n,\n# use gradient checkpointing to save memory\noptim\n=\n\"adamw_torch_fused\"\n,\n# use fused adamw optimizer\nlogging_steps\n=\n10\n,\n# log every 10 steps\nsave_strategy\n=\n\"epoch\"\n,\n# save checkpoint every epoch\nlearning_rate\n=\n2e-4\n,\n# learning rate, based on QLoRA paper\nbf16\n=\nTrue\n,\n# use bfloat16 precision\ntf32\n=\nTrue\n,\n# use tf32 precision\nmax_grad_norm\n=\n0.3\n,\n# max gradient norm based on QLoRA paper\nwarmup_ratio\n=\n0.03\n,\n# warmup ratio based on QLoRA paper\nlr_scheduler_type\n=\n\"constant\"\n,\n# use constant learning rate scheduler\npush_to_hub\n=\nTrue\n,\n# push model to hub\nreport_to\n=\n\"tensorboard\"\n,\n# report metrics to tensorboard\n)\nWe now have every building block to create our\nSFTTrainer\nand start training our model.\nPython\nfrom\ntrl\nimport\nSFTTrainer\nmax_seq_length =\n3072\n# max sequence length for model and packing of the dataset\ntrainer =\nSFTTrainer\n(\nmodel\n=model,\nargs\n=args,\ntrain_dataset\n=dataset,\npeft_config\n=peft_config,\nmax_seq_length\n=max_seq_length,\ntokenizer\n=tokenizer,\npacking\n=\nTrue\n,\ndataset_kwargs\n={\n\"add_special_tokens\"\n:\nFalse\n,\n# We template with special tokens\n\"append_concat_token\"\n:\nFalse\n,\n# No need to add additional separator token\n}\n)\nWe can start training our model by calling the\ntrain()\nmethod on our\nTrainer\ninstance. This will start the training loop and train our model for 3 epochs. Since we are using a PEFT method, we will only save the adapted model weights and not the full model.\nPython\n# start training, the model will be automatically saved to the hub and the output directory\ntrainer.\ntrain\n()\n# save model\ntrainer.\nsave_model\n()\nThe training with Flash Attention for 3 epochs with a dataset of 10k samples took 01:29:58 on a\ng5.2xlarge\n. The instance costs\n1,212$/h\nwhich brings us to a total cost of only\n1.8$\n.\nPython\n# free the memory again\ndel\nmodel\ndel\ntrainer\ntorch.cuda.\nempty_cache\n()\nOptional: Merge LoRA adapter in to the original model\nWhen using QLoRA, we only train adapters and not the full model. This means when saving the model during training we only save the adapter weights and not the full model. If you want to save the full model, which makes it easier to use with Text Generation Inference you can merge the adapter weights into the model weights using the\nmerge_and_unload\nmethod and then save the model with the\nsave_pretrained\nmethod. This will save a default model, which can be used for inference.\nNote: You might require > 30GB CPU Memory.\nPython\n#### COMMENT IN TO MERGE PEFT AND BASE MODEL ####\n# from peft import AutoPeftModelForCausalLM\n# # Load PEFT model on CPU\n# model = AutoPeftModelForCausalLM.from_pretrained(\n#     args.output_dir,\n#     torch_dtype=torch.float16,\n#     low_cpu_mem_usage=True,\n# )\n# # Merge LoRA and base model and save\n# merged_model = model.merge_and_unload()\n# merged_model.save_pretrained(args.output_dir,safe_serialization=True, max_shard_size=\"2GB\")\n5. Test and evaluate the LLM\nAfter the training is done we want to evaluate and test our model. We will load different samples from the original dataset and evaluate the model on those samples, using a simple loop and accuracy as our metric.\nNote: 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\nEvaluate LLMs and RAG a practical example using Langchain and Hugging Face\nblog post.\nPython\nimport\ntorch\nfrom\npeft\nimport\nAutoPeftModelForCausalLM\nfrom\ntransformers\nimport\nAutoTokenizer, pipeline\npeft_model_id =\n\"./code-llama-7b-text-to-sql\"\n# peft_model_id = args.output_dir\n# Load Model with PEFT adapter\nmodel = AutoPeftModelForCausalLM.\nfrom_pretrained\n(\npeft_model_id,\ndevice_map\n=\n\"auto\"\n,\ntorch_dtype\n=torch.float16\n)\ntokenizer = AutoTokenizer.\nfrom_pretrained\n(peft_model_id)\n# load into pipeline\npipe =\npipeline\n(\n\"text-generation\"\n,\nmodel\n=model,\ntokenizer\n=tokenizer)\nLet’s load our test dataset try to generate an instruction.\nPython\nfrom\ndatasets\nimport\nload_dataset\nfrom\nrandom\nimport\nrandint\n# Load our test dataset\neval_dataset =\nload_dataset\n(\n\"json\"\n,\ndata_files\n=\n\"test_dataset.json\"\n,\nsplit\n=\n\"train\"\n)\nrand_idx =\nrandint\n(\n0\n, len(eval_dataset))\n# Test on sample\nprompt = pipe.tokenizer.\napply_chat_template\n(eval_dataset[rand_idx][\n\"messages\"\n][:\n2\n],\ntokenize\n=\nFalse\n,\nadd_generation_prompt\n=\nTrue\n)\noutputs =\npipe\n(prompt,\nmax_new_tokens\n=\n256\n,\ndo_sample\n=\nFalse\n,\ntemperature\n=\n0.1\n,\ntop_k\n=\n50\n,\ntop_p\n=\n0.1\n,\neos_token_id\n=pipe.tokenizer.eos_token_id,\npad_token_id\n=pipe.tokenizer.pad_token_id)\nprint(\nf\n\"Query:\n\\n\n{\neval_dataset[rand_idx][\n'messages'\n][\n1\n][\n'content'\n]\n}\n\"\n)\nprint(\nf\n\"Original Answer:\n\\n\n{\neval_dataset[rand_idx][\n'messages'\n][\n2\n][\n'content'\n]\n}\n\"\n)\nprint(\nf\n\"Generated Answer:\n\\n\n{\noutputs[\n0\n][\n'generated_text'\n][len(prompt):].\nstrip\n()\n}\n\"\n)\nNice! Our model was able to generate a SQL query based on the natural language instruction. Lets evaluate our model on the full 2,500 samples of our test dataset.\nNote: As mentioned above, evaluating generative models is not a trivial task. In our example we used the accuracy of the generated SQL based on the ground truth SQL query as our metric. An alternative way could be to automatically execute the generated SQL query and compare the results with the ground truth. This would be a more accurate metric but requires more work to setup.\nPython\nfrom\ntqdm\nimport\ntqdm\ndef\nevaluate\n(\nsample\n):\nprompt = pipe.tokenizer.\napply_chat_template\n(sample[\n\"messages\"\n][:\n2\n],\ntokenize\n=\nFalse\n,\nadd_generation_prompt\n=\nTrue\n)\noutputs =\npipe\n(prompt,\nmax_new_tokens\n=\n256\n,\ndo_sample\n=\nTrue\n,\ntemperature\n=\n0.7\n,\ntop_k\n=\n50\n,\ntop_p\n=\n0.95\n,\neos_token_id\n=pipe.tokenizer.eos_token_id,\npad_token_id\n=pipe.tokenizer.pad_token_id)\npredicted_answer = outputs[\n0\n][\n'generated_text'\n][len(prompt):].\nstrip\n()\nif\npredicted_answer == sample[\n\"messages\"\n][\n2\n][\n\"content\"\n]:\nreturn\n1\nelse\n:\nreturn\n0\nsuccess_rate = []\nnumber_of_eval_samples =\n1000\n# iterate over eval dataset and predict\nfor\ns\nin\ntqdm\n(eval_dataset.\nshuffle\n().\nselect\n(range(number_of_eval_samples))):\nsuccess_rate.\nappend\n(\nevaluate\n(s))\n# compute accuracy\naccuracy = sum(success_rate)/len(success_rate)\nprint(\nf\n\"Accuracy:\n{\naccuracy*\n100\n:.2f\n}\n%\"\n)\nWe evaluated our model on 1000 samples from the evaluation dataset and got an accuracy of\n79.50%\n, which took ~25 minutes.\nThis is quite good, but as mentioned you need to take this metric with a grain of salt. It would be better if we could evaluate our model by running the qureies against a real database and compare the results. Since there might be different \"correct\" SQL queries for the same instruction. There are also several ways on how we could improve the performance by using few-shot learning, using RAG, Self-healing to generate the SQL query.\n6. Deploy the LLM for Production\nYou can now deploy your model to production. For deploying open LLMs into production we recommend using\nText Generation Inference (TGI)\n. 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 for the most popular open LLMs, including Llama, Mistral, Mixtral, StarCoder, T5 and more. Text Generation Inference is used by companies as IBM, Grammarly, Uber, Deutsche Telekom, and many more. There are several ways to deploy your model, including:\nDeploy LLMs with Hugging Face Inference Endpoints\nHugging Face LLM Inference Container for Amazon SageMaker\nDIY\nIf you have docker installed you can use the following command to start the inference server.\nNote: Make sure that you have enough GPU memory to run the container. Restart kernel to remove all allocated GPU memory from the notebook.\nBash\n%%bash\n# model=$PWD/{args.output_dir} # path to model\nmodel\n=$(pwd)\n/code-llama-7b-text-to-sql\n# path to model\nnum_shard\n=\n1\n# number of shards\nmax_input_length\n=\n1024\n# max input length\nmax_total_tokens\n=\n2048\n# max total tokens\ndocker\nrun\n-d\n--name\ntgi\n--gpus\nall\n-ti\n-p\n8080:80\n\\\n-e\nMODEL_ID=/workspace\n\\\n-e\nNUM_SHARD=\n$num_shard\n\\\n-e\nMAX_INPUT_LENGTH=\n$max_input_length\n\\\n-e\nMAX_TOTAL_TOKENS=\n$max_total_tokens\n\\\n-v\n$model\n:/workspace\n\\\nghcr.io/huggingface/text-generation-inference:latest\nOnce your container is running you can send requests.\nPython\nimport\nrequests\nas\nr\nfrom\ntransformers\nimport\nAutoTokenizer\nfrom\ndatasets\nimport\nload_dataset\nfrom\nrandom\nimport\nrandint\n# Load our test dataset and Tokenizer again\ntokenizer = AutoTokenizer.\nfrom_pretrained\n(\n\"code-llama-7b-text-to-sql\"\n)\neval_dataset =\nload_dataset\n(\n\"json\"\n,\ndata_files\n=\n\"test_dataset.json\"\n,\nsplit\n=\n\"train\"\n)\nrand_idx =\nrandint\n(\n0\n, len(eval_dataset))\n# generate the same prompt as for the first local test\nprompt = tokenizer.\napply_chat_template\n(eval_dataset[rand_idx][\n\"messages\"\n][:\n2\n],\ntokenize\n=\nFalse\n,\nadd_generation_prompt\n=\nTrue\n)\nrequest= {\n\"inputs\"\n:prompt,\n\"parameters\"\n:{\n\"temperature\"\n:\n0.2\n,\n\"top_p\"\n:\n0.95\n,\n\"max_new_tokens\"\n:\n256\n}}\n# send request to inference server\nresp = r.\npost\n(\n\"http://127.0.0.1:8080/generate\"\n,\njson\n=request)\noutput = resp.\njson\n()[\n\"generated_text\"\n].\nstrip\n()\ntime_per_token = resp.headers.\nget\n(\n\"x-time-per-token\"\n)\ntime_prompt_tokens = resp.headers.\nget\n(\n\"x-prompt-tokens\"\n)\n# Print results\nprint(\nf\n\"Query:\n\\n\n{\neval_dataset[rand_idx][\n'messages'\n][\n1\n][\n'content'\n]\n}\n\"\n)\nprint(\nf\n\"Original Answer:\n\\n\n{\neval_dataset[rand_idx][\n'messages'\n][\n2\n][\n'content'\n]\n}\n\"\n)\nprint(\nf\n\"Generated Answer:\n\\n\n{\noutput\n}\n\"\n)\nprint(\nf\n\"Latency per token:\n{\ntime_per_token\n}\nms\"\n)\nprint(\nf\n\"Latency prompt encoding:\n{\ntime_prompt_tokens\n}\nms\"\n)\nAwesome, Don't forget to stop your container once you are done.\nPython\n!\ndocker stop tgi\nConclusion\nLarge Language Models and the availability of tools TRL make it an ideal time for companies to invest in open LLM technology. Fine-tuning open LLMs for specific tasks can significantly enhance efficiency and open new opportunities for innovation and improved services. With the increasing accessibility and cost-effectiveness, there has never been a better time to start using open LLMs.\nThanks for reading! If you have any questions, feel free to contact me on\nTwitter\nor\nLinkedIn\n.",
  "metadata": {
    "title": "How to Fine-Tune LLMs in 2024 with Hugging Face",
    "description": "In this blog post you will learn how to fine-tune LLMs using Hugging Face TRL, Transformers and Datasets in 2024. We will fine-tune a LLM on a text to SQL dataset.",
    "keywords": null,
    "author": "Philipp Schmid",
    "og:title": "How to Fine-Tune LLMs in 2024 with Hugging Face",
    "og:description": "In this blog post you will learn how to fine-tune LLMs using Hugging Face TRL, Transformers and Datasets in 2024. We will fine-tune a LLM on a text to SQL dataset.",
    "og:url": "https://www.philschmid.de/fine-tune-llms-in-2024-with-trl",
    "og:image": "https://www.philschmid.de/static/blog/fine-tune-llms-in-2024-with-trl/thumbnail.jpg",
    "og:image:width": "1200",
    "og:image:height": "630",
    "og:image:alt": "How to Fine-Tune LLMs in 2024 with Hugging Face",
    "og:type": "article",
    "twitter:card": "summary_large_image",
    "twitter:title": "How to Fine-Tune LLMs in 2024 with Hugging Face",
    "twitter:description": "In this blog post you will learn how to fine-tune LLMs using Hugging Face TRL, Transformers and Datasets in 2024. We will fine-tune a LLM on a text to SQL dataset.",
    "twitter:image": "https://www.philschmid.de/static/blog/fine-tune-llms-in-2024-with-trl/thumbnail.jpg",
    "article:published_time": "2024-01-23"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": ""
  },
  "code_blocks": [
    {
      "file": "attachments/3135846076ac/code/body-000.txt",
      "chars": 544,
      "language": "text"
    },
    {
      "file": "attachments/3135846076ac/code/body-001.txt",
      "chars": 215,
      "language": "text"
    },
    {
      "file": "attachments/3135846076ac/code/body-002.txt",
      "chars": 109,
      "language": "text"
    },
    {
      "file": "attachments/3135846076ac/code/body-003.txt",
      "chars": 410,
      "language": "text"
    },
    {
      "file": "attachments/3135846076ac/code/body-004.txt",
      "chars": 203,
      "language": "text"
    },
    {
      "file": "attachments/3135846076ac/code/body-005.txt",
      "chars": 1119,
      "language": "text"
    },
    {
      "file": "attachments/3135846076ac/code/body-006.txt",
      "chars": 142,
      "language": "text"
    },
    {
      "file": "attachments/3135846076ac/code/body-007.txt",
      "chars": 887,
      "language": "text"
    },
    {
      "file": "attachments/3135846076ac/code/body-008.txt",
      "chars": 278,
      "language": "text"
    },
    {
      "file": "attachments/3135846076ac/code/body-009.txt",
      "chars": 1316,
      "language": "text"
    },
    {
      "file": "attachments/3135846076ac/code/body-010.txt",
      "chars": 482,
      "language": "text"
    },
    {
      "file": "attachments/3135846076ac/code/body-011.txt",
      "chars": 143,
      "language": "text"
    },
    {
      "file": "attachments/3135846076ac/code/body-012.txt",
      "chars": 70,
      "language": "text"
    },
    {
      "file": "attachments/3135846076ac/code/body-013.txt",
      "chars": 441,
      "language": "text"
    },
    {
      "file": "attachments/3135846076ac/code/body-014.txt",
      "chars": 483,
      "language": "text"
    },
    {
      "file": "attachments/3135846076ac/code/body-015.txt",
      "chars": 773,
      "language": "text"
    },
    {
      "file": "attachments/3135846076ac/code/body-016.txt",
      "chars": 844,
      "language": "text"
    },
    {
      "file": "attachments/3135846076ac/code/body-017.txt",
      "chars": 511,
      "language": "text"
    },
    {
      "file": "attachments/3135846076ac/code/body-018.txt",
      "chars": 1208,
      "language": "text"
    },
    {
      "file": "attachments/3135846076ac/code/body-019.txt",
      "chars": 16,
      "language": "text"
    }
  ],
  "images": [],
  "audio": [],
  "videos": [],
  "links": [
    {
      "href": "https://github.com/philschmid/deep-learning-pytorch-huggingface/blob/main/training/fine-tune-llms-in-2024-with-trl.ipynb",
      "label": "View Code",
      "type": "a"
    },
    {
      "href": "https://huggingface.co/meta-llama/Llama-2-70b-chat-hf",
      "label": "Llama 2",
      "type": "a"
    },
    {
      "href": "https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2",
      "label": "Mistral",
      "type": "a"
    },
    {
      "href": "https://huggingface.co/mistralai/Mixtral-8x7B-Instruct-v0.1",
      "label": "Mixtral",
      "type": "a"
    },
    {
      "href": "https://huggingface.co/tiiuae/falcon-40b",
      "label": "Falcon",
      "type": "a"
    },
    {
      "href": "https://huggingface.co/docs/trl/index",
      "label": "TRL",
      "type": "a"
    },
    {
      "href": "https://huggingface.co/docs/transformers/index",
      "label": "Transformers",
      "type": "a"
    },
    {
      "href": "https://huggingface.co/docs/datasets/index",
      "label": "datasets",
      "type": "a"
    },
    {
      "href": "https://github.com/Dao-AILab/flash-attention/tree/main",
      "label": "FlashAttention",
      "type": "a"
    },
    {
      "href": "https://huggingface.co/models",
      "label": "Hugging Face Hub",
      "type": "a"
    },
    {
      "href": "https://huggingface.co/join",
      "label": "Hugging Face",
      "type": "a"
    },
    {
      "href": "https://huggingface.co/datasets/spider",
      "label": "Spider",
      "type": "a"
    },
    {
      "href": "https://huggingface.co/datasets/tatsu-lab/alpaca",
      "label": "Alpaca",
      "type": "a"
    },
    {
      "href": "https://huggingface.co/datasets/databricks/databricks-dolly-15k",
      "label": "Dolly",
      "type": "a"
    },
    {
      "href": "https://huggingface.co/datasets/Open-Orca/OpenOrca",
      "label": "Orca",
      "type": "a"
    },
    {
      "href": "https://arxiv.org/abs/2306.02707",
      "label": "Orca: Progressive Learning from Complex Explanation Traces of GPT-4.",
      "type": "a"
    },
    {
      "href": "https://huggingface.co/datasets/b-mc2/sql-create-context",
      "label": "sql-create-context",
      "type": "a"
    },
    {
      "href": "https://huggingface.co/docs/trl/sft_trainer",
      "label": "SFTTrainer",
      "type": "a"
    },
    {
      "href": "https://arxiv.org/abs/2305.14314",
      "label": "QLoRA",
      "type": "a"
    },
    {
      "href": "https://huggingface.co/blog/4bit-transformers-bitsandbytes",
      "label": "Making LLMs even more accessible with bitsandbytes, 4-bit quantization and QLoRA",
      "type": "a"
    },
    {
      "href": "https://huggingface.co/docs/trl/main/en/sft_trainer",
      "label": "setup_chat_format",
      "type": "a"
    },
    {
      "href": "https://arxiv.org/pdf/2305.14314.pdf",
      "label": "qlora paper",
      "type": "a"
    },
    {
      "href": "https://magazine.sebastianraschka.com/p/practical-tips-for-finetuning-llms",
      "label": "blog post",
      "type": "a"
    },
    {
      "href": "https://www.philschmid.de/evaluate-llm",
      "label": "Evaluate LLMs and RAG a practical example using Langchain and Hugging Face",
      "type": "a"
    },
    {
      "href": "https://github.com/huggingface/text-generation-inference",
      "label": "Text Generation Inference (TGI)",
      "type": "a"
    },
    {
      "href": "https://huggingface.co/blog/inference-endpoints-llm",
      "label": "Deploy LLMs with Hugging Face Inference Endpoints",
      "type": "a"
    },
    {
      "href": "https://huggingface.co/blog/sagemaker-huggingface-llm",
      "label": "Hugging Face LLM Inference Container for Amazon SageMaker",
      "type": "a"
    },
    {
      "href": "https://twitter.com/_philschmid",
      "label": "Twitter",
      "type": "a"
    },
    {
      "href": "https://www.linkedin.com/in/philipp-schmid-a6a2bb196/",
      "label": "LinkedIn",
      "type": "a"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-14T10:52:46Z",
  "source_url": "https://www.philschmid.de/fine-tune-llms-in-2024-with-trl",
  "papers": [
    {
      "status": "ok",
      "url": "https://arxiv.org/pdf/2306.02707",
      "bytes": 1458242,
      "reused": true,
      "local_path": "papers/repair/67a6a1e952ff4b98f65e.pdf"
    },
    {
      "status": "ok",
      "url": "https://arxiv.org/pdf/2305.14314",
      "bytes": 1065470,
      "reused": true,
      "local_path": "papers/repair/df2f754581ddf63a5d62.pdf"
    },
    {
      "status": "ok",
      "url": "https://arxiv.org/pdf/2305.14314.pdf",
      "bytes": 1065470,
      "reused": false,
      "local_path": "papers/repair/42f75ee4f85fbba6ba8a.pdf"
    }
  ],
  "actual_video_files": [],
  "body_chars": 22854,
  "expected_body_images": 0,
  "discovery_status": "ok",
  "delivery_status": "ok",
  "missing_reason": "",
  "raw_html": "attachments/3135846076ac/pages/source.html",
  "local_html": "attachments/3135846076ac/pages/article.html",
  "body_base_path": "attachments/3135846076ac/pages/",
  "body_markdown_path": "attachments/3135846076ac/pages/article.md"
}