页面简介
Execute end-to-end LLM workflows to develop & productionize LLMs at scale.
正文摘录
HomeBlogBlog DetailEnd-to-end LLM Workflows GuideBy Goku Mohandas | June 17, 2024[ Anyscale template | GitHub | Notebook ] · 25 min. read In this guide, we'll learn how to execute the end-to-end LLM workflows to develop & productionize LLMs at scale.Data preprocessing: prepare our dataset for fine-tuning with batch data processing.Fine-tuning: tune our LLM (LoRA / full param) with key optimizations with distributed training.Evaluation: apply batch inference with our tuned LLMs to generate outputs and perform evaluation.Serving: serve our LLMs as a production application that can autoscale, swap between LoRA adapters, etc.Throughout these workloads we'll be using Ray, a framework for distributing ML, used by OpenAI, Netflix, Uber, etc. And Anyscale, a platform to scale your ML workloads from development to production.💵 Cost: $0 (using free Anyscale credits)🕑 Total time: 90 mins (including fine-tuning)🔄 REPLACE indicates to replace with your unique values💡 INSIGHT indicates infrastructure insightJoin Slack community to share issues / questionsLinkSet upWe can execute this notebook entirely for free (no credit card needed) by creating an Anyscale account. Once you log in, you'll be directed to the main console where you'll see a collection of notebook templates. Click on the "End-to-end LLM Workflows" to open up the workspace and click on the README.ipynb to get started. Workspaces are a fully managed development environment which allow us to use our favorite tools (VSCode, notebooks, terminal, etc.) on top of infinite compute (when we need it). In fact, by clicking on the compute at the top right (✅ 1 node, 8 CPU), we can see the cluster information:Head node (Workspace node): manages the cluster, distributes tasks, and hosts development tools.Worker nodes: machines that execute work orchestrated by the head node and can scale back to 0.setup-compute💡 INSIGHT : Because we have Auto-select worker nodesenabled, that means that the required worker nodes (ex. GPU workers) will automagically be provisioned based on our workload's needs! They'll spin up, run the workload and then scale back to zero. This allows us to maintain a lean workspace environment (and only pay for compute when we need it) and completely remove the need to manage any infrastructure.auto-workersNote: we can explore all the metrics (ex. hardware util), logs, dashboards, manage dependencies (ex. images, pip packages, etc.) on the menu bar above.1import os 2import ray 3import warnings 4warnings.filterwarnings("ignore") 5%load_ext autoreload 6%autoreload 2We'll need a free Hugging Face token to load our base LLMs and tokenizers, etc. And since we are using Llama models, we need to login and accept the terms and conditions here.🔄 REPLACE : Place your unique HF token below. If you accidentally ran this code block before pasting your HF token, then click the Restart button up top to restart the notebook kernel.1# Initialize HF token 2os.environ['HF_TOKEN'] = '' # <-- replace with your token 3ray.init(runtime_env={'env_vars': {'HF_TOKEN': os.environ['HF_TOKEN']}})LinkData PreprocessingWe'll start by preprocessing our data in preparation for fine-tuning our LLM. We'll use batch processing to apply our preprocessing across our dataset at scale.data-overviewLinkDatasetFor our task, we'll be using the Viggo dataset dataset, where the input (meaning_representation) is a structured collection of the overall intent (ex. inform) and entities (ex. release_year) and the output (target) is an unstructured sentence that incorporates all the structured input information. But for our task, we'll reverse this task where the input will be the unstructured sentence and the output will be the structured information.1Input (unstructured sentence): 2"Dirt: Showdown from 2012 is a sport racing game for the PlayStation, Xbox, PC rated E 10+ (for Everyone 10 and Older). It's not available on Steam, Linux, or Mac." 3 4Output (intent + entities): 5"inform(name[Dirt: Showdown], release_year[2012], esrb[E 10+ (for Everyone 10 and Older)], genres[driving/racing, sport], platforms[PlayStation, Xbox, PC], available_on_steam[no], has_linux_release[no], has_mac_release[no])"1from datasets import load_dataset 2ray.data.set_progress_bars(enabled=False)1# Load the VIGGO dataset 2dataset = load_dataset("GEM/viggo", trust_remote_code=True)1# Data splits 2train_set = dataset['train'] 3val_set = dataset['validation'] 4test_set = dataset['test'] 5print (f"train: {len(train_set)}") 6print (f"val: {len(val_set)}") 7print (f"test: {len(test_set)}")1train: 5103 2val: 714 3test: 10831# Sample 2train_set[0]1{'gem_id': 'viggo-train-0', 2 'meaning_representation': 'inform(name[Dirt: Showdown], release_year[2012], esrb[E 10+ (for Everyone 10 and Older)], genres[driving/racing, sport], platforms[PlayStation, Xbox, PC], available_on_steam[no], has_linux_release[no], has_mac_release[no])', 3 'target': "Dirt: Showdown from 2012 is a sport racing game for the PlayStation, Xbox, PC rated E 10+ (for Everyone 10 and Older). It's not available on Steam, Linux, or Mac.", 4 'references': ["Dirt: Showdown from 2012 is a sport racing game for the PlayStation, Xbox, PC rated E 10+ (for Everyone 10 and Older). It's not available on Steam, Linux, or Mac."]}LinkData PreprocessingWe'll use Ray to load our dataset and apply preprocessing to batches of our data at scale.1import re1# Load as a Ray Dataset 2train_ds = ray.data.from_items(train_set) 3train_ds.take(1)1[{'gem_id': 'viggo-train-0', 2 'meaning_representation': 'inform(name[Dirt: Showdown], release_year[2012], esrb[E 10+ (for Everyone 10 and Older)], genres[driving/racing, sport], platforms[PlayStation, Xbox, PC], available_on_steam[no], has_linux_release[no], has_mac_release[no])', 3 'target': "Dirt: Showdown from 2012 is a sport racing game for the PlayStation, Xbox, PC rated E 10+ (for Everyone 10 and Older). It's not available on Steam, Linux, or Mac.", 4 'references': ["Dirt: Showdown from 2012 is a sport racing game for the PlayStation, Xbox, PC rated E 10+ (for Everyone 10 and Older). It's not available on Steam, Linux, or Mac."]}]The preprocessing we'll do involves formatting our dataset into the schema required for fine-tuning (system, user, assistant) conversations.system: description of the behavior or personality of the model. As a best practice, this should be the same for all examples in the fine-tuning dataset, and should remain the same system prompt when moved to production.user: user message, or "prompt," that provides a request for the model to respond to.assistant: stores previous responses but can also contain examples of intended responses for the LLM to return.1conversations = [ 2 {"messages": [ 3 {'role': 'system', 'content': system_content}, 4 {'role': 'user', 'content': item['target']}, 5 {'role': 'assistant', 'content': item['meaning_representation']}]}, 6 {"messages": [...],} 7 ... 8]1def to_schema(item, system_content): 2 messages = [ 3 {'role': 'system', 'content': system_content}, 4 {'role': 'user', 'content': item['target']}, 5 {'role': 'assistant', 'content': item['meaning_representation']}] 6 return {'messages': messages}Our system_content will guide the LLM on how to behave. Our specific directions involve specifying the list of possible intents and entities to extract.1# System content 2system_content = ( 3 "Given a target sentence construct the underlying meaning representation of the input " 4 "sentence as a single function with attributes and attribute values. This function " 5 "should describe the target string accurately and the function must be one of the " 6 "following ['inform', 'request', 'give_opinion', 'confirm', 'verify_attribute', " 7 "'suggest', 'request_explanation', 'recommend', 'request_attribute']. The attributes " 8 "must be one of the following: ['name', 'exp_release_date', 'release_year', 'developer', " 9 "'esrb', 'rating', 'genres', 'player_perspective', 'has_multiplayer', 'platforms', " 10 "'available_on_steam', 'has_linux_release', 'has_mac_release', 'specifier']")To apply our function on our dataset at scale, we can pass it to ray.data.Dataset.map. Here, we can specify the function to apply to each sample in our data, what compute to use, etc. The diagram below shows how we can read from various data sources (ex. cloud storage) and apply operations at scale across different hardware (CPU, GPU). For our workload, we'll just use the default compute strategy which will use CPUs to scale out our workload.Note: If we want to distribute a workload across batches of our data instead of individual samples, we can use ray.data.Dataset.map_batches. We'll see this in action when we perform batch inference in our evaluation template. There are also many other distributed operations we can perform on our dataset.data-detailed1# Distributed preprocessing 2ft_train_ds = train_ds.map(to_schema, fn_kwargs={'system_content': system_content}) 3ft_train_ds.take(1)1[{'messages': [{'content': "Given a target sentence construct the underlying meaning representation of the input sentence as a single function with attributes and attribute values. This function should describe the target string accurately and the function must be one of the following ['inform', 'request', 'give_opinion', 'confirm', 'verify_attribute', 'suggest', 'request_explanation', 'recommend', 'request_attribute']. The attributes must be one of the following: ['name', 'exp_release_date', 'release_year', 'developer', 'esrb', 'rating', 'genres', 'player_perspective', 'has_multiplayer', 'platforms', 'available_on_steam', 'has_linux_release', 'has_mac_release', 'specifier']", 2 'role': 'system'}, 3 {'content': "Dirt: Showdown from 2012 is a sport racing game for the PlayStation, Xbox, PC rated E 10+ (for Everyone 10 and Older). It's not available on Steam, Linux, or Mac.", 4 'role': 'user'}, 5 {'content': 'inform(name[Dirt: Showdown], release_year[2012], esrb[E 10+ (for Everyone 10 and Older)], genres[driving/racing, sport], platforms[PlayStation, Xbox, PC], a