iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📖

re:Invent 2024: Fine-tuning Methods and Benefits with Amazon Bedrock

に公開
2024/12/10

Introduction

By transcribing various overseas lectures into Japanese articles, we make hidden, high-quality information more accessible. In this project, which operates under that concept, the presentation we will cover this time is:

📖 AWS re:Invent 2024 - Customizing models for enhanced results: Fine-tuning in Amazon Bedrock (AIM357)

This video provides a detailed explanation of Fine-tuning to improve the performance of Foundation Models and Small Language Models. It introduces the features of the Fine-tuning function in Amazon Bedrock, how to set Hyperparameters, and the Custom Model Import function. In particular, regarding the Fine-tuning of Anthropic's Claude 3 Haiku, it shows a concrete example where an experiment using the TAT-QA dataset achieved a 25% improvement in accuracy and a 35% reduction in token usage compared to the base model. Furthermore, for Meta's Llama 3 models, the effects are explained in detail through practical demos of distillation and fine-tuning from a 405B model to an 8B model.
https://www.youtube.com/watch?v=G3r09u_aA9o

  • This article was automatically generated from the video. As there may be typos or incorrect information, please refer to the original video for accurate information.
  • Clicking on the image will take you to the corresponding scene in the video.

Information regarding the transcription articles for re:Invent 2024 is summarized in this Spreadsheet. Please check it out as well!

Main Content

Basics of Fine-tuning and Overview of Amazon Bedrock Features

Thumbnail 0

Thumbnail 30

This is a very hot topic that many of you may already know. There are numerous techniques for extracting performance from Foundation Models and Small Language Models. One of the technologies garnering significant attention in both the research field and from customers is Fine-tuning and model customization. Today, we will start with the basics and look at two interesting application examples using Anthropic's models and Meta's models. Let's explore what Fine-tuning actually means, what the lifecycle of these models is like, and what features are available in Amazon Bedrock related to Fine-tuning customization.

Thumbnail 50

Fine-tuning is essentially the process of taking a pre-trained model and customizing it with your own data. The journey to obtaining that pre-trained model begins with a large collection of unlabeled data. Large organizations with abundant resources typically perform pre-training of models to achieve basic capabilities, from which we can then perform Fine-tuning on task-specific datasets. This results in a Foundation Model that can be used generally across multiple tasks, languages, and domains. We then use labeled, task-specific examples—Prompt-Completion pairs that indicate input and expected output—as training data to fine-tune the base model into a model for a specific use case.

Thumbnail 140

We have seen many customers implement this in specific domains. If you are in financial services or healthcare, the vocabulary and types of tasks are significantly different. The more you perform Fine-tuning with high-quality, relevant data, the more the final results for that specific task will improve. Looking at the general lifecycle of Fine-tuning, it typically begins with a use case. For example, let's consider the case of summarizing a document into two lines. While it might seem simple, accurately capturing the details of a document in two lines is a difficult task for many LLMs today. Another example is text-to-SQL conversion, where a text query is converted into SQL, and that SQL is executed against an analytics or warehousing backend to retrieve data for plotting or BI visualization.

The use case suggests what data is actually needed. This is where data preparation becomes crucial. You need to clean and augment the data, remove duplicates, and ensure you aren't training on the same data twice. What we have observed in both research and actual operations is that high-quality data is the greatest differentiator in pre-training. High-quality data undoubtedly produces a higher-quality model for that specific task type. Even today, many organizations invest time, resources, and expensive human labelers to label data for Fine-tuning.

Once this data is ready, various frameworks and services can be used. At AWS, we have services like Amazon SageMaker and Amazon Bedrock, which you can use to execute model Fine-tuning and customize based on the prepared data. When performing this customization, it is advisable to set up monitoring to track the Fine-tuning progress and allow for pausing the job if necessary to resume with different hyperparameters, which we will discuss in later slides. Once model training is complete, the validation metrics are good, and you have confirmed that the training produced results different from the base model, you should evaluate it with a completely blind test set. For tasks like document summarization or text-to-SQL, you can prepare a set of blind tasks as a test set for evaluation. Many customers using Retrieval Augmented Generation have their own evaluation metrics, and Amazon Bedrock also provides management features to easily evaluate customized models.

Practical Approaches to Fine-tuning and Advanced Amazon Bedrock Features

Thumbnail 310

Now, a key question is: when should you actually perform Fine-tuning? You have likely tried various techniques, such as prompt engineering, RAG (Retrieval Augmented Generation) which improves responses by retrieving context from a knowledge base, and Fine-tuning. Typically, people try these in order of increasing complexity.

First, you should try prompt engineering; using optimized, high-quality prompts can yield about half the desired results. Recently, Amazon released a feature that automatically optimizes prompts for specific use cases. Also, using RAG allows you to leverage internal knowledge bases stored in various formats, such as vector embedding indexes or graph formats. When a user asks a question, RAG retrieves relevant document or source fragments and combines them with the question to get a better answer.

Let's look at today's Fine-tuning, from low to high complexity. For example, if you want to mimic a specific tone in the customer service industry, you can achieve a high success rate even with prompting or prompting plus RAG. However, using Fine-tuning can achieve even higher success rates for low-complexity tasks. Also, if you want to teach the model a completely new skill, such as making a model that wasn't good at Text-to-SQL become proficient at it, Fine-tuning is extremely effective.

Considering this Text-to-SQL example, a Fine-tuned model demonstrates excellent performance on a specific task set, but it doesn't generalize well to other multiple tasks, such as slightly different types of SQL or GraphQL. In other words, while Fine-tuning provides excellent performance for the specific task you taught it, it tends to be difficult to generalize to similar multiple task sets. As a final case, if you want to teach a model new knowledge and have it use that knowledge to solve tasks, Fine-tuning is even less likely to work.

Thumbnail 520

Think of Fine-tuning as something performed for a specific task where you can achieve excellent performance and verify that it works reliably. However, this is a double-edged sword. If you aim for generalization, using a base model, prompting, or RAG is better. So, what are the important considerations when performing Fine-tuning? Unfortunately, the best answer right now is "it depends." There is no clear answer yet. If you want to learn new concepts that the base model already understands through small-scale Fine-tuning, it is a very good use case.

As I mentioned earlier, some of these use cases involve wanting the model to perform specific tasks or specific processing, and if you get promising results with few-shots, you can expect Fine-tuning to produce excellent results. Few-shots are basically inline examples that can be attached to instructions or prompts. These few-shots help the model respond in a specific way, and providing these examples can improve task accuracy and adjust the tone. If few-shots work well, you can consider that performing Fine-tuning using many similar examples might yield even better results.

Also, with prompt engineering, you usually start simple and gradually expand the prompt, which can eventually lead to very complex, large prompts. Therefore, you need to verify if the model is actually following your instructions, solving the challenges, and properly adhering to the constraints set in the prompt.

In that process, you might end up with a large set of system instructions, prompts, and examples that work well. However, you will be fighting a token budget because you will be sending more input tokens. You might get the required answer, but it will cost more for the input tokens. Fine-tuning is one way to avoid this complex prompting. Some customers include hundreds of examples in the prompt itself, but you can perform Fine-tuning on those examples and use a Fine-tuned model with a shorter prompt. As long as you use the same interface, you will pay roughly the same cost for the output prompt, but the cost for the input prompt will be lower.

Concrete Implementation and Effects of Fine-tuning in Amazon Bedrock

Thumbnail 660

Thumbnail 670

Now that you understand a bit about Fine-tuning, I'd like to talk about some features of Amazon Bedrock. There is a feature called Bedrock Fine-tuning, which allows you to use simple datasets. You can upload datasets in JSONL format, using the prompt-completion pairs explained in the first diagram, to S3 and start a model customization job to Fine-tune the base model through the console or the provided API set. This generates model artifacts specialized for specific use cases or task types, which you can use through Provisioned Throughput (essentially a standalone endpoint available as an API). You can integrate this with your final application.

When performing Fine-tuning, Amazon Bedrock provides the most important parameters that allow you to control the results of the Fine-tuning. These are called Hyperparameters. These high-level ways to control Fine-tuning include the Learning Rate, the number of Epochs indicating how long to run training, and Warmup Steps. These are all explained in detail in the documentation. The key point is that Bedrock's Fine-tuning feature is very simple. You don't have to worry about framework setup, instance setup, sign-in, cluster management, and so on.

Thumbnail 770

This is a very rare case, but Continued Pre-training is also one of the management features of Amazon Bedrock. The reason it is rare is that it usually requires a large amount of high-quality data, as well as time and resources for training. For example, you may know about scaling laws, which show the relationship between the optimal model and the amount of resources required for Fine-tuning. If you do the math, if you try to train a trillion-parameter model from scratch, it would cost about $20 million for Pre-training, assuming you have a trillion tokens of high-quality data. If you have $20 million in spare funds, please let me know.

There are also cases where you adopt a smaller architecture for Pre-training. The smaller models like Nova Micro and Nova Light that we released earlier this week are Pre-trained with a similar process in mind. The life cycle consists of Pre-training the model using a large amount of unlabeled data, followed by Fine-tuning and alignment. In Continued Pre-training, as long as the dataset is saved in S3 in the correct format, you can select the base model architecture. This is no longer a base Pre-trained model. You can train a model completely from scratch, and there are good reasons to do so. That said, it is a rare case, and in most cases, Fine-tuning should yield sufficient results.

Thumbnail 880

One important feature released a few months ago is Custom Model Import. For example, consider a case where you use one of the common model architectures and perform Fine-tuning somewhere other than Bedrock, such as SageMaker, Hugging Face Auto Train, or on your own laptop. If it is a Llama model, a Flan-T5 model, or another supported model, you can import it into Amazon Bedrock along with supported model architectures like Mistral, and access your model directly using Bedrock's model invocation API. This enables highly flexible operations, allowing you to invoke a model you have Fine-tuned yourself in Bedrock without using Amazon Bedrock's Fine-tuning feature. You can use Custom Model Import to import it into Amazon Bedrock and use it directly there. One of the attractive features of Amazon Bedrock is that you only pay for the input/output tokens used in the model marketplace. Even with Custom Model Import, you can use your own model with token-based costs. This allows you to test the model first, and once it is ready for integration with your application, you can obtain a dedicated endpoint for that specific model through Provisioned Throughput.

Thumbnail 970

Finally, as a recently released feature, there is Amazon Bedrock Model Distillation. My co-author Yan has already published a great guide that you can take a look at. The idea of this feature is to use a larger, more advanced model to generate prompt and completion pairs, and utilize them as a labeled dataset for a smaller model. For example, you can generate a dataset using a large general-purpose model like Llama 405B, and use that to train smaller Llama models like 1B or 8B. With Amazon Bedrock Model Distillation, you simply select a Teacher model and a Student model, and provide the dataset as an S3 file. Particularly interesting is that if you have a production application using Amazon Bedrock's Invocation API, invocation logs of input/output pairs are recorded in CloudWatch logs, and you can directly parse those logs and use them for training. You can use Bedrock's simple wizard to utilize relevant APIs.

At the end of the process, you get a distillation model that has been precisely tuned for a specific task. The only difference is that you start with almost no or no data at all, and the Teacher Model uses them as examples to generate even higher-quality examples for downstream Fine-tuning of smaller models. Please try these features. Documentation, APIs, and related blogs are all available. This concludes the explanation of Amazon Bedrock features. Next, I will explain the customization of Anthropic Claude 3 Haiku in particular, and then talk about ESA and Meta.

Fine-tuning Anthropic Claude 3 Haiku: Best Practices and Experimental Results

Thumbnail 1130

Thank you everyone. As she explained quite thoroughly about the Bedrock Model customization features earlier, I would like to dive deeper into customizing Anthropic Claude 3 Haiku here. I will use this time to share best practices and experimental results, and provide you with insights on how to make this feature successful. As explained in the Fine-tuning life cycle, you must first have a clear use case. Once the use case is defined, you enter the data preparation stage. For Claude 3 Haiku Fine-tuning, you need to prepare data in JSONL format, and each line must represent a training record using the Message API. Looking at each line in detail, you can optionally set a System Prompt, which is highly recommended. This is because assigning a role to the model often leads to better performance. Next, as a required field, you need a Message field, which must contain two roles: the User role containing the prompt input when interacting with the Fine-tuned model, and the Assistant role carrying the desired output.

These two roles must be placed alternately, and multi-turn conversations are also supported. This means that each JSONL file can contain multiple User and Assistant conversations, but they must be placed alternately and follow the Message API format. Once the data is prepared, you can proceed to the Fine-tuning parameter settings.

Thumbnail 1240

These are the five parameters supported for Claude 3 Haiku Fine-tuning on Amazon Bedrock. The first three are mandatory, while the bottom two are optional but highly recommended. The first parameter is EpochCount, the maximum number of times to repeat the entire training dataset. This can be set up to 10, but in Haiku Fine-tuning, early stopping is possible if you provide a validation dataset. If you use a validation dataset, you may not need to complete the Fine-tuning job within the specified count. This is simply the maximum number to set.

The second parameter is Batch Size, the number of samples processed before updating model parameters. This Batch Size is closely related to the number of training records. The third parameter is Learning Rate Multiplier, which affects the learning rate. It is set to 1 by default, and as our science team's extensive experiments have shown this value to be most effective, we recommend customers start with this value. Early Stopping Threshold and Early Stopping Patience are optional parameters that you can enable if you provide a validation dataset. Early Stopping is a technique to prevent overfitting by stopping the training job if the validation loss does not decrease sufficiently within the specified threshold and patience parameters.

Thumbnail 1400

Now that you understand these parameters, let's explain how to set them appropriately. For the Learning rate multiplier, our researchers' experimental results suggest starting with 1.0. You can then adjust it based on evaluation results. The optimal value for Batch size depends on the size of the dataset. For training data exceeding 1,000 records, we recommend a larger Batch size of 32-64. For medium-sized datasets of 500 to 1,000 records, consider a Batch size of 16 to 32. For small datasets of less than 500 records, try a smaller Batch size of 4 to 16. Our experiments have shown that in large-scale data scenarios of 1,000 to 10,000, the influence of Learning rate is significant, while for small datasets of less than 100, Batch size is a major factor that determines Fine-tuning performance.

Thumbnail 1480

Let's look at performance evaluation using the TAT-QA dataset as a target use case. This dataset is publicly available and focuses on question-answering tasks related to financial text and tabular content. We trained the model using 10,000 records from this TAT-QA dataset and evaluated it using approximately 3,500 records. Here, we used the F1 score of word matching for evaluation.

After conducting experiments and trying various settings, the best performance obtained from the Fine-tuned Claude 3 Haiku was approximately 91.2% accuracy. This is actually better than the base Haiku, Claude 3 Sonnet, and even the latest Claude 3.5 Sonnet model. Looking at the model's performance improvement, we saw an approximately 25% improvement compared to the base Haiku, outperformed Claude 3 Sonnet by about 20%, and even outperformed Claude 3.5 Sonnet by about 10%.

I want to emphasize In-context learning here as well. Customers often ask, "I've already Fine-tuned the model, should I still use In-context learning?" The answer is "yes". In-context learning helps improve performance for both base models and Fine-tuned models, so you should continue to consider using it. If you want to push your model's performance to the maximum, consider using Fine-tuning in combination with In-context learning.

Thumbnail 1590

The final slide I want to explain is another advantage of using a Fine-tuned model: reduction in Token usage. It is well known that higher output Tokens usually lead to higher latency and costs. Fine-tuning allows you to increase the efficiency of model output Token usage. Taking the TAT-QA dataset as an example, while the base Haiku has an average output of about 34 Tokens, the Fine-tuned model has an average output of about 22 Tokens, showing a 35% improvement. Looking at this histogram, the Fine-tuned Haiku shows a very dense distribution, meaning the output is very concise. On the other hand, the base Haiku tends to generate unnecessary information.

I'd like to show you a concrete example to wrap up my part. In the live corner, there is a question from the TAT-QA dataset: "How did the company adopt Topic 606?" The correct answer is very concise, perhaps about 4 words long. Base Haiku tends to add unnecessary explanation here. The base model's answer was factually accurate, but not very efficient. On the other hand, the Fine-tuned Haiku matched the correct answer 100%. It provides very concise output while generating factually based results.

Customizing and Demonstrating Meta's Llama Models

Now, I'd like to ask Isa to talk about customizing Meta models on Amazon Bedrock. I am Isa, an AI Partner Engineering Engineer at Meta. I will explain the customization of Meta's Llama model. I will introduce some use cases where Fine-tuning is truly effective, show you one or two examples, and then demonstrate the distillation and Fine-tuning of the 8B model.

Thumbnail 1740

Regarding Llama 3 Fine-tuning use cases. What is shown here are some of the use cases where Fine-tuning is truly effective. The reason I introduce this here is to answer frequently asked questions: "Why is Fine-tuning necessary?" "Why doesn't the Llama model perform as expected if I'm only using prompt engineering and RAG without Fine-tuning?" I have listed five examples here, but this is just a fraction, and there are many other use cases. Customer service chatbots can benefit from Fine-tuning by understanding inquiries from a company's customers and having the company's internal knowledge or product context. Content generation can be tailored to the brand's tone and style. In addition, compliance and regulatory analysis, financial chart analysis, etc., are also possible - all of which can become very specific to the requirements of the organization or company. In the case of finance, it could become very specific to that company's metrics or the specific analysis being executed. These are just a few examples.

Thumbnail 1830

Let's delve a little deeper into Fine-tuning, building on what Shreyas and YNN provided. One of the most important parts of Fine-tuning is dataset analysis and processing. It is important to ensure a dataset that is sufficiently diverse and generalized, yet specialized, suitable for your intended purpose. As you can see in this slide, we emphasize that a properly curated dataset is crucial for gaining the benefits of Fine-tuning. If the dataset is not sufficiently diverse or generalized, you might not be able to obtain the performance and accuracy improvements worth the effort and resources invested. The second point is that diverse datasets really help with data generalization. Regarding domain-specific datasets and custom datasets, domain naturally refers to the industry domain you want to adjust the dataset for. For specific tasks or projects, you will consider a custom dataset designed to provide highly relevant and accurate results in the Fine-tuning path with that model.

Thumbnail 1920

As a rough overview, we have published Llama and general default settings regarding Fine-tuning for all examples. If you look at the GitHub resources, Llama is open source, and we have our open-source repositories, Llama Recipes and Llama Stack. These contain many examples regarding inference, Fine-tuning, and safety assurance using Llama Guard. All Fine-tuning examples such as Full Parameter, LoRA, and Q-LoRA are available there. We usually publish recommended parameters, but you might need to change them depending on the specific case. This depends on the nature and scale of the dataset, needs, and whether you have sufficient validation data. We have also included links to end-to-end RAG examples using deployable and modifiable chatbots, and recipes for multimodal models released a few months ago. Llama 3.2 possesses multimodal capabilities capable of text output from text and image inputs.

Thumbnail 2020

I want to highlight how Fine-tuning helps here. In this example, I'm explaining it abstractly, but I'm showing an example of running a simple analysis solving a math problem with the Llama Base 8B model and its Fine-tuned version. Looking at the output of the Llama 3 8B model, it doesn't make much sense, and the calculations are a bit off. On the other hand, looking at the Fine-tuned version, it understands the problem instructions, explains them in concise language, and can perform the calculations correctly. This shows an example where Fine-tuning makes a huge difference in generating plausible and accurate output.

Thumbnail 2080

Now, let's move on to the demo. In this demo, I will show you a notebook available on GitHub. This was created in collaboration with AWS and is published in the Llama repository on AWS, and linked from Llama Recipes as well. In this notebook, we show the steps for running 405B models on SageMaker or Bedrock.

Thumbnail 2130

As demonstrated here, we take that dataset and teach it to the 8B model using Distillation. We will fine-tune the 8B model to improve its performance. I'm going to skip a lot of the text here and move on to the code portion.

Thumbnail 2150

As prerequisites, you need an AWS account, access to SageMaker, access to Bedrock, and IAM settings. I won't go into detail about these, but let's proceed to the actual content. What we'll actually do here is deploy the Llama 3 8B Instruct model and use the deepmind/aqua_rat dataset. This is a large-scale dataset collecting about 100,000 algebraic word problems. This dataset is very suitable for training and evaluating the model, and can truly measure the ability to reason about algebraic problems in natural language.

Thumbnail 2200

Thumbnail 2220

First, there are basic imports, and we'll start configuring the dataset. Here, we'll read the dataset and actually display it. By running this notebook, you can see what this dataset actually looks like. As you can see by looking at the code, we've applied restrictions in these lines so as not to display all 100,000+ examples. We've also split it appropriately, and that is the output here. You can confirm what you are dealing with.

Thumbnail 2240

In the next step of this notebook, we deploy the 8B Instruct model, run the problem, and confirm that the output before Fine-tuning or learning is not 100% accurate and does not perfectly match the results we desire. Running the same prompt in 405B shows that you get much better output. In other words, if you get a good response using 405B, it means you can potentially use that 405B output to create synthetic data or data for training smaller models.

Thumbnail 2280

Thumbnail 2290

Thumbnail 2300

In the next section, we deploy the 405B model. There are two formats for this code. We are deploying in SageMaker, but it's also executable in Bedrock, and there is an example at the bottom for running it in Bedrock. In this way, code for creating synthetic data using Bedrock is provided as an option. This is very advantageous; while SageMaker abstracts away a lot, the need to understand DevOps or how to spin up resources is removed, making things simpler.

Thumbnail 2340

Here too, when deploying in SageMaker, we deploy that instance. After that, we generate synthetic data, and that is the role of this code. Then we save that data, and basically output it in JSON format. The same process is carried out on the Bedrock side. These all use the Bedrock Converse API, which is very useful in cases like this.

Thumbnail 2390

Thumbnail 2400

Next, naturally, you need to upload the data generated from 405B to S3 for the training job. In this notebook, we used SageMaker to perform training, but that's no longer necessary. You can perform training of Llama 8B or 7B in Bedrock, which is also very advantageous. Again, you don't need to secure resources or spin them up yourself, nor do you need to worry about resource cost consumption after the job is complete. Now, let's start the actual Fine-tuning of the 8B model. In this case, since we are executing directly, very detailed output is displayed, not Bedrock output. Every Epoch has been executed here, and that output is displayed. Let's scroll a bit to move forward. This is complete.

Thumbnail 2410

Thumbnail 2420

Thumbnail 2430

Now, this is complete. Having finished training the 8B model and completed the Fine-tuning, I'd like to proceed to deploying the model in this section. At this point, we have deployed the 8B Fine-tuned model trained by the output of the 405B model. And now, we have an easy-to-read table clearly showing the effects of Fine-tuning. As you can see, questions are defined in the left column, the output of the Fine-tuned model is displayed in the third column, and the output of the non-Fine-tuned model is displayed in the last column.

I'll briefly summarize the conclusion here. Reus touched on much of this, but Fine-tuning can clearly improve model performance and accuracy, and it can be adapted to any use case. Furthermore, there are many advantages in terms of computational resources as well. A reduction in Token usage, meaning benefits in cost, is one of them. My part ends here. This concludes the presentation. We will all remain in this room for a while, so if anyone has any questions, please feel free to reach out and talk to us. Thank you very much.


  • This article is created entirely automatically by utilizing Amazon Bedrock.
  • Considering concerns about internet contamination by generative AI articles, in this article, we hope to maintain the value of the original content itself as much as possible by converting session videos into text and images without almost changing the amount of information, while enhancing accessibility and googlability in multiple languages.

Discussion