├── code ├── .gitkeep ├── chat_template │ └── llama-3-instruct.jinja └── llama3_finetune_inference.ipynb ├── data ├── .gitkeep └── scratch │ └── .gitkeep ├── models └── .gitkeep ├── apt.txt ├── .gitattributes ├── requirements.txt ├── postBuild.bash ├── preBuild.bash ├── .project ├── configpacks └── spec.yaml ├── variables.env ├── .gitignore ├── README.md └── LICENSE.txt /code/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /models/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data/scratch/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /apt.txt: -------------------------------------------------------------------------------- 1 | # apt packages to install should be listed one per line 2 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | models/** filter=lfs diff=lfs merge=lfs -text 2 | data/** filter=lfs diff=lfs merge=lfs -text 3 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | jupyterlab>3.0 2 | datasets==2.19.1 3 | bitsandbytes==0.43.1 4 | transformers==4.41.1 5 | peft==0.11.1 6 | accelerate==0.30.1 7 | trl==0.8.6 8 | ipywidgets==8.1.3 9 | wandb==0.17.0 10 | -------------------------------------------------------------------------------- /postBuild.bash: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # This file contains bash commands that will be executed at the end of the container build process, 3 | # after all system packages and programming language specific package have been installed. 4 | # 5 | # Note: This file may be removed if you don't need to use it 6 | -------------------------------------------------------------------------------- /preBuild.bash: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # This file contains bash commands that will be executed at the beginning of the container build process, 3 | # before any system packages or programming language specific package have been installed. 4 | # 5 | # Note: This file may be removed if you don't need to use it 6 | -------------------------------------------------------------------------------- /.project/configpacks: -------------------------------------------------------------------------------- 1 | *defaults.ContainerUser 2 | *bash.PreBuild 3 | *cuda.CUDA 4 | *defaults.EnvVars 5 | *defaults.Readme 6 | *defaults.Entrypoint 7 | *apt.PackageManager 8 | *bash.PreLanguage 9 | *python.PipPackageManager 10 | *bash.PostBuild 11 | *jupyterlab.JupyterLab 12 | *tensorboard.Tensorboard -------------------------------------------------------------------------------- /variables.env: -------------------------------------------------------------------------------- 1 | # Set environment variables in the format KEY=VALUE, 1 per line 2 | # This file will be sourced inside the project container when started. 3 | # NOTE: If you change this file while the project is running, you must restart the project container for changes to take effect. 4 | 5 | TENSORBOARD_LOGS_DIRECTORY=/data/tensorboard/logs/ 6 | -------------------------------------------------------------------------------- /code/chat_template/llama-3-instruct.jinja: -------------------------------------------------------------------------------- 1 | {% if messages[0]['role'] == 'system' %} 2 | {% set offset = 1 %} 3 | {% else %} 4 | {% set offset = 0 %} 5 | {% endif %} 6 | 7 | {{ bos_token }} 8 | {% for message in messages %} 9 | {% if (message['role'] == 'user') != (loop.index0 % 2 == offset) %} 10 | {{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }} 11 | {% endif %} 12 | 13 | {{ '<|start_header_id|>' + message['role'] + '<|end_header_id|>\n\n' + message['content'] | trim + '<|eot_id|>' }} 14 | {% endfor %} 15 | 16 | {% if add_generation_prompt %} 17 | {{ '<|start_header_id|>' + 'assistant' + '<|end_header_id|>\n\n' }} 18 | {% endif %} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore generated or temporary files managed by the Workbench 2 | .project/* 3 | !.project/spec.yaml 4 | !.project/configpacks 5 | 6 | # General ignores 7 | .DS_Store 8 | 9 | # Byte-compiled / optimized / DLL files 10 | __pycache__/ 11 | *.py[cod] 12 | *$py.class 13 | 14 | # Temp directories, notebooks created by jupyterlab 15 | .ipynb_checkpoints 16 | .Trash-*/ 17 | .jupyter/ 18 | .local/ 19 | 20 | # Python distribution / packaging 21 | .Python 22 | build/ 23 | develop-eggs/ 24 | dist/ 25 | downloads/ 26 | eggs/ 27 | .eggs/ 28 | lib/ 29 | lib64/ 30 | parts/ 31 | sdist/ 32 | var/ 33 | wheels/ 34 | share/python-wheels/ 35 | *.egg-info/ 36 | .installed.cfg 37 | *.egg 38 | MANIFEST 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | cover/ 54 | 55 | # Workbench Project Layout 56 | data/scratch/* 57 | !data/scratch/.gitkeep -------------------------------------------------------------------------------- /.project/spec.yaml: -------------------------------------------------------------------------------- 1 | specVersion: v2 2 | specMinorVersion: 2 3 | meta: 4 | name: llama3-finetune 5 | image: project-llama3-finetune 6 | description: An example project for finetuning a Llama3 model 7 | labels: [] 8 | createdOn: "2024-07-09T22:56:06Z" 9 | defaultBranch: main 10 | layout: 11 | - path: code/ 12 | type: code 13 | storage: git 14 | - path: models/ 15 | type: models 16 | storage: gitlfs 17 | - path: data/ 18 | type: data 19 | storage: gitlfs 20 | - path: data/scratch/ 21 | type: data 22 | storage: gitignore 23 | environment: 24 | base: 25 | registry: nvcr.io 26 | image: nvidia/ai-workbench/pytorch:1.0.2 27 | build_timestamp: "20231102150513" 28 | name: PyTorch 29 | supported_architectures: [] 30 | cuda_version: "12.2" 31 | description: A Pytorch 2.1 Base with CUDA 12.2 32 | entrypoint_script: "" 33 | labels: 34 | - cuda12.2 35 | - pytorch2.1 36 | apps: 37 | - name: jupyterlab 38 | type: jupyterlab 39 | class: webapp 40 | start_command: jupyter lab --allow-root --port 8888 --ip 0.0.0.0 --no-browser 41 | --NotebookApp.base_url=\$PROXY_PREFIX --NotebookApp.default_url=/lab --NotebookApp.allow_origin='*' 42 | health_check_command: '[ \$(echo url=\$(jupyter lab list | head -n 2 | tail 43 | -n 1 | cut -f1 -d'' '' | grep -v ''Currently'' | sed "s@/?@/lab?@g") | curl 44 | -o /dev/null -s -w ''%{http_code}'' --config -) == ''200'' ]' 45 | stop_command: jupyter lab stop 8888 46 | user_msg: "" 47 | logfile_path: "" 48 | timeout_seconds: 60 49 | icon_url: "" 50 | webapp_options: 51 | autolaunch: true 52 | port: "8888" 53 | proxy: 54 | trim_prefix: false 55 | url_command: jupyter lab list | head -n 2 | tail -n 1 | cut -f1 -d' ' | grep 56 | -v 'Currently' 57 | - name: tensorboard 58 | type: tensorboard 59 | class: webapp 60 | start_command: tensorboard --logdir \$TENSORBOARD_LOGS_DIRECTORY --path_prefix=\$PROXY_PREFIX 61 | --bind_all 62 | health_check_command: '[ \$(curl -o /dev/null -s -w ''%{http_code}'' http://localhost:\$TENSORBOARD_PORT\$PROXY_PREFIX/) 63 | == ''200'' ]' 64 | stop_command: pkill tensorboard 65 | user_msg: "" 66 | logfile_path: "" 67 | timeout_seconds: 60 68 | icon_url: "" 69 | webapp_options: 70 | autolaunch: true 71 | port: "6006" 72 | proxy: 73 | trim_prefix: false 74 | url: http://localhost:6006 75 | programming_languages: 76 | - python3 77 | icon_url: "" 78 | image_version: 1.0.2 79 | os: linux 80 | os_distro: ubuntu 81 | os_distro_release: "22.04" 82 | schema_version: v2 83 | user_info: 84 | uid: "" 85 | gid: "" 86 | username: "" 87 | package_managers: 88 | - name: apt 89 | binary_path: /usr/bin/apt 90 | installed_packages: 91 | - curl 92 | - git 93 | - git-lfs 94 | - vim 95 | - name: pip 96 | binary_path: /usr/local/bin/pip 97 | installed_packages: 98 | - jupyterlab==4.0.7 99 | package_manager_environment: 100 | name: "" 101 | target: "" 102 | execution: 103 | apps: [] 104 | resources: 105 | gpu: 106 | requested: 1 107 | sharedMemoryMB: 1024 108 | secrets: 109 | - variable: HF_KEY 110 | description: Hugging Face Hub Token 111 | mounts: 112 | - type: project 113 | target: /project/ 114 | description: Project directory 115 | options: rw 116 | - type: volume 117 | target: /data/tensorboard/logs/ 118 | description: Tensorboard Log Files 119 | options: volumeName=tensorboard-logs-volume 120 | - type: host 121 | target: /project/models/ 122 | description: Where to save the finetuned Llama3 model on the underlying *host* machine, ie. for home path, enter /home/[user] or /mnt/C/Users/[user] (Windows) 123 | options: "" 124 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Table of Contents 2 | * [Introduction](#nvidia-ai-workbench-introduction) 3 | * [Project Description](#project-description) 4 | * [Sizing Guide](#sizing-guide) 5 | * [Quickstart](#quickstart) 6 | * [Prerequisites](#prerequisites) 7 | * [Tutorial (Desktop App)](#tutorial-desktop-app) 8 | * [Tutorial (CLI-Only)](#tutorial-cli-only) 9 | * [License](#license) 10 | 11 | # NVIDIA AI Workbench: Introduction [![Open In AI Workbench](https://img.shields.io/badge/Open_In-AI_Workbench-76B900)](https://ngc.nvidia.com/open-ai-workbench/aHR0cHM6Ly9naXRodWIuY29tL05WSURJQS93b3JrYmVuY2gtZXhhbXBsZS1sbGFtYTMtZmluZXR1bmU=) 12 | 13 | 14 | 15 | 16 | 17 |

18 | :arrow_down: Download AI Workbench • 19 | :book: Read the Docs • 20 | :open_file_folder: Explore Example Projects • 21 | :rotating_light: Facing Issues? Let Us Know! 22 |

23 | 24 | ## Project Description 25 | The Llama3-8B model is an advanced LLM developed by Meta that demonstrates SOTA performance on reasoning, code generation, and contextual understanding tasks. In this project, we will focus on finetuning this base model in two ways: 26 | 27 | 1. ```llama3_finetune_inference.ipynb```: Supervised Full Finetuning (SFT) 28 | 29 | This notebook provides a sample workflow for fine-tuning a full precision Llama3-8B base model using SFT on a subset of the OpenAssistant Guanaco dataset with the intention of improving the model's conversational and instruction following capabilities. Then, you can deploy and test your finetuned model on a vLLM API server. 30 | 31 | 2. ```llama3dpo.ipynb```: Direct Preference Optimization (DPO) 32 | 33 | This notebook provides a sample workflow for fine-tuning a 4-bit quantized Llama3-8B model using Direct Preference Optimization (DPO). 34 | 35 | ### What is Direct Preference Optimization (DPO)? 36 | 37 | Traditionally, developers can add reinforcement learning from human feedback (RLHF) to SFT to evaluate, reward, and improve finetuning results. However these algorithms require more data, are less stable, and are computationally expensive! 38 | 39 | Direct Preference Optimization improves on a lot of the shortcomings of RLHF. Essentially, DPO treats a task as a classification problem. It uses 2 models: the trained model and a copy called the reference model. During DPO training, the goal is to make sure the trained model outputs higher probabilities for preferred answers and lower probabilities for rejected answers when compared to the reference model. 40 | 41 | Because the LLM uses itself as a reward model, it is able to align itself without need for a reward model or extensive sampling and hyperparameter tuning, resulting in a more stable and less computationally intensive process. 42 | 43 | | :memo: Remember | 44 | | :---------------------------| 45 | | This project is meant as an example workflow and a starting point; you are free to swap out the dataset, choose a different task, and edit the training prompts as you see fit for your particular use case! | 46 | 47 | ## Sizing Guide 48 | 49 | | GPU VRAM | Example Hardware | Compatible? | 50 | | -------- | ------- | ------- | 51 | | <16 GB | RTX 3080, RTX 3500 Ada | N | 52 | | 16 GB | RTX 4080 16GB, RTX A4000 | Y (DPO only) | 53 | | 24 GB | RTX 3090/4090, RTX A5000/5500, A10/30 | Y (DPO only) | 54 | | 32 GB | RTX 5000 Ada | Y (DPO only) | 55 | | 40 GB | A100-40GB | Y (DPO only) | 56 | | 48 GB | RTX 6000 Ada, L40/L40S, A40 | Y (DPO only) | 57 | | 80 GB | A100-80GB | Y | 58 | | >80 GB | 8x A100-80GB | Y | 59 | 60 | # Quickstart 61 | 62 | ## Prerequisites 63 | AI Workbench will prompt you to provide a few pieces of information before running any apps in this project. Ensure you have this information ready. 64 | 65 | * The location where you would like the Llama3-8B models to live on the underlying **host** system. 66 | * The Hugging Face API Key w/ Llama3-8B access (see below). 67 | 68 | | :exclamation: Important | 69 | | :---------------------------| 70 | | Verify you can see a "You have been granted access to this model." message on the Hugging Face model cards [here](https://huggingface.co/meta-llama/Meta-Llama-3-8B) and [here](https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct); if not, you may need to accept the terms to grant access for your HF token. | 71 | 72 | ## Tutorial (Desktop App) 73 | 74 | If you do not NVIDIA AI Workbench installed, first complete the installation for AI Workbench [here](https://www.nvidia.com/en-us/deep-learning-ai/solutions/data-science/workbench/). Then, 75 | 76 | 1. Fork this Project to your own GitHub namespace and copy the link 77 | 78 | ``` 79 | https://github.com/[your_namespace]/ 80 | ``` 81 | 82 | 2. Open NVIDIA AI Workbench. Select a location to work in. 83 | 84 | 3. Clone this Project onto your desired machine by selecting **Clone Project** and providing the GitHub link. 85 | 86 | 4. Wait for the project to build. You can expand the bottom **Building** indicator to view real-time build logs. 87 | 88 | 5. When the build completes, set the following configurations. 89 | 90 | * `Environment` → `Mounts` → `Configure`. Specify the file path of the mount, eg. where the Llama3-8B models will live on your **host** machine. 91 | 92 | eg. if you would like your finetuned model to be saved in your home path, enter ```/home/[user]``` or ```/mnt/C/Users/[user]``` (Windows) 93 | 94 | * `Environment` → `Secrets` → `Configure`. Specify the Hugging Face Token as a project secret. 95 | 96 | 6. On the top right of the window, select **Jupyterlab**. 97 | 98 | 7. Navigate to the `code` directory of the project. Then, open your fine-tuning notebook of choice and get started. Happy coding! 99 | 100 | ## Tutorial (CLI-Only) 101 | Some users may choose to use the **CLI tool only** instead of the Desktop App. If you do not NVIDIA AI Workbench installed, first complete the installation for AI Workbench [here](https://www.nvidia.com/en-us/deep-learning-ai/solutions/data-science/workbench/). Then, 102 | 1. Fork this Project to your own GitHub namespace and copying the link 103 | 104 | ``` 105 | https://github.com/[your_namespace]/ 106 | ``` 107 | 108 | 2. Open a shell and activating the Context you want to clone into by 109 | 110 | ``` 111 | $ nvwb list contexts 112 | 113 | $ nvwb activate 114 | ``` 115 | 116 | | :bulb: Tip | 117 | | :---------------------------| 118 | | Use ```nvwb help``` to see a full list of AI Workbench commands. | 119 | 120 | 3. Clone this Project onto your desired machine by running 121 | 122 | ``` 123 | $ nvwb clone project 124 | ``` 125 | 126 | 4. Open the Project by 127 | 128 | ``` 129 | $ nvwb list projects 130 | 131 | $ nvwb open 132 | ``` 133 | 134 | 5. Start **Jupyterlab** by 135 | 136 | ``` 137 | $ nvwb start jupyterlab 138 | ``` 139 | 140 | * Specify the file path of the mount, eg. where the Llama3-8B models will live on your **host** machine. 141 | 142 | eg. if you would like your finetuned model to be saved in your home path, enter ```/home/[user]``` or ```/mnt/C/Users/[user]``` (Windows) 143 | 144 | * Specify the Hugging Face Token as a project secret. 145 | 146 | 6. Navigate to the `code` directory of the project. Then, open your fine-tuning notebook of choice and get started. Happy coding! 147 | 148 | # License 149 | This NVIDIA AI Workbench example project is under the [Apache 2.0 License](https://github.com/NVIDIA/workbench-example-llama3-finetune/blob/main/LICENSE.txt) 150 | 151 | This project may utilize additional third-party open source software projects. Review the license terms of these open source projects before use. Third party components used as part of this project are subject to their separate legal notices or terms that accompany the components. You are responsible for confirming compliance with third-party component license terms and requirements. 152 | 153 | | :question: Have Questions? | 154 | | :---------------------------| 155 | | Please direct any issues, fixes, suggestions, and discussion on this project to the DevZone Members Only Forum thread [here](https://forums.developer.nvidia.com/t/support-workbench-example-project-llama-3-finetune/303411) | 156 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2023 NVIDIA Corporation 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /code/llama3_finetune_inference.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "attachments": {}, 5 | "cell_type": "markdown", 6 | "id": "e0dd4a63-5f87-43e9-a67f-ca9e00b48ede", 7 | "metadata": {}, 8 | "source": [ 9 | "\n", 10 | "
\n", 11 | " \n", 12 | "
\n", 13 | "\n", 14 | "\n", 15 | "
\n", 16 | " NVIDIA AI Workbench •\n", 17 | " User Documentation •\n", 18 | " Example Projects Catalog •\n", 19 | " Problem? Submit a ticket here! \n", 20 | "
\n", 21 | "\n", 22 | "# Finetune and deploy the Llama3-8b model using SFT and VLLM \n", 23 | "\n", 24 | "Welcome!\n", 25 | "\n", 26 | "In this notebook, we're going to walk through the flow of using supervised finetuning (SFT) on the Llama3-8B model from scratch using the base model and then deploying it using VLLM. Ensure you have requested and have been approved access to this model via [HuggingFace](https://huggingface.co/meta-llama/Meta-Llama-3-8B). \n", 27 | "\n", 28 | "Llama-3 was has an 8k context length which is pretty small compared to some of the newer models that have been released and is was pretrained with 15 trillion tokens on a 24k GPU cluster. Luckily for finetuning, we only need a fraction of that compute power.\n", 29 | "\n", 30 | "Note that we will be using the base model in this notebook and not the instruct model. Additionally, we will be running through a full finetune with no quantization. This notebook was originally built for 2 A100-80GB GPUs, but the default hyperparameters have since been adjusted to run on 1x A100-80GB. If you're looking for a lighter Llama3-finetune, checkout out the other Llama3 finetuning notebook which uses Direct Preference Optimization.\n", 31 | "\n", 32 | "#### Help us make this tutorial better! Please provide feedback on the [NVIDIA Developer Forum](https://forums.developer.nvidia.com/c/ai-data-science/nvidia-ai-workbench/671).\n", 33 | "\n", 34 | "A note about running Jupyter Notebooks: Press Shift + Enter to run a cell. A * in the left-hand cell box means the cell is running. A number means it has completed. If your Notebook is acting weird, you can interrupt a too-long process by interrupting the kernel (Kernel tab -> Interrupt Kernel) or even restarting the kernel (Kernel tab -> Restart Kernel). Note restarting the kernel will require you to run everything from the beginning." 35 | ] 36 | }, 37 | { 38 | "cell_type": "markdown", 39 | "id": "01a7bfcf-0552-433f-8afb-145e661ab34a", 40 | "metadata": {}, 41 | "source": [ 42 | "## Table of Contents\n", 43 | "1. Import libraries\n", 44 | "2. Download model\n", 45 | "3. Fintuning flow\n", 46 | "4. Deploy as an OpenAI compatible endpoint" 47 | ] 48 | }, 49 | { 50 | "cell_type": "markdown", 51 | "id": "b2fab017-7a3d-4322-8ec7-bc20eabe7e9a", 52 | "metadata": {}, 53 | "source": [ 54 | "## 1. Imports libraries" 55 | ] 56 | }, 57 | { 58 | "cell_type": "code", 59 | "execution_count": null, 60 | "id": "2be21a74-407f-49a9-83e9-771cf90d29b1", 61 | "metadata": {}, 62 | "outputs": [], 63 | "source": [ 64 | "# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n", 65 | "# SPDX-License-Identifier: Apache-2.0\n", 66 | "#\n", 67 | "# Licensed under the Apache License, Version 2.0 (the \"License\");\n", 68 | "# you may not use this file except in compliance with the License.\n", 69 | "# You may obtain a copy of the License at\n", 70 | "#\n", 71 | "# http://www.apache.org/licenses/LICENSE-2.0\n", 72 | "#\n", 73 | "# Unless required by applicable law or agreed to in writing, software\n", 74 | "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", 75 | "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", 76 | "# See the License for the specific language governing permissions and\n", 77 | "# limitations under the License.\n", 78 | "\n", 79 | "import os\n", 80 | "import torch\n", 81 | "from datasets import load_dataset\n", 82 | "from transformers import (\n", 83 | " AutoModelForCausalLM,\n", 84 | " AutoTokenizer,\n", 85 | " BitsAndBytesConfig,\n", 86 | " HfArgumentParser,\n", 87 | " TrainingArguments,\n", 88 | " pipeline,\n", 89 | " logging,\n", 90 | ")\n", 91 | "from peft import LoraConfig, PeftModel\n", 92 | "from trl import SFTTrainer" 93 | ] 94 | }, 95 | { 96 | "cell_type": "markdown", 97 | "id": "a3fc909e-efb6-4b4b-8c10-e0ed72477600", 98 | "metadata": {}, 99 | "source": [ 100 | "## 2. Load in Llama 3 and our dataset\n", 101 | "\n", 102 | "Because we are using the base model, there is not an exact prompt template we have to follow. The dataset we are using follows LLama3's template format so it should be fine for downstream tasks that use the Llama3 chat format. If you're bringing your own data, you can format it however you want as long as you use the same formatting downstream. \n", 103 | "\n", 104 | "Here's the official [Llama3 chat template](https://huggingface.co/blog/llama3#how-to-prompt-llama-3)" 105 | ] 106 | }, 107 | { 108 | "cell_type": "code", 109 | "execution_count": null, 110 | "id": "b422e214-977a-4c45-9d66-b6a698c546eb", 111 | "metadata": {}, 112 | "outputs": [], 113 | "source": [ 114 | "base_model_id = \"meta-llama/Meta-Llama-3-8B\"\n", 115 | "dataset_name = \"scooterman/guanaco-llama3-1k\"\n", 116 | "new_model = \"/project/models/NV-llama3-8b-SFT\"" 117 | ] 118 | }, 119 | { 120 | "cell_type": "code", 121 | "execution_count": null, 122 | "id": "c3a03b3f-5398-455e-880c-f503cba51821", 123 | "metadata": {}, 124 | "outputs": [], 125 | "source": [ 126 | "from datasets import load_dataset\n", 127 | "\n", 128 | "dataset = load_dataset(dataset_name, split=\"train\")" 129 | ] 130 | }, 131 | { 132 | "cell_type": "code", 133 | "execution_count": null, 134 | "id": "5081c400-f9c0-403b-b145-0e75e5a9982e", 135 | "metadata": {}, 136 | "outputs": [], 137 | "source": [ 138 | "import torch\n", 139 | "from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig\n", 140 | "\n", 141 | "model = AutoModelForCausalLM.from_pretrained(base_model_id, \n", 142 | " token=os.environ[\"HF_KEY\"], \n", 143 | " cache_dir=\"/project/models\",\n", 144 | " device_map=\"auto\")\n", 145 | "tokenizer = AutoTokenizer.from_pretrained(\n", 146 | " base_model_id,\n", 147 | " token=os.environ[\"HF_KEY\"], \n", 148 | " add_eos_token=True,\n", 149 | " add_bos_token=True, \n", 150 | ")\n", 151 | "tokenizer.pad_token = tokenizer.eos_token" 152 | ] 153 | }, 154 | { 155 | "cell_type": "markdown", 156 | "id": "77919e07-7495-4a50-82c7-99459ba815c2", 157 | "metadata": {}, 158 | "source": [ 159 | "## 3. Set our Training Arguments\n", 160 | "\n", 161 | "A lot of tutorials simply paste a list of arguments leaving it up to the reader to figure out what each argument does. Below, annotations have been added to explain what each argument does." 162 | ] 163 | }, 164 | { 165 | "cell_type": "code", 166 | "execution_count": null, 167 | "id": "614e0a54-2740-438d-a72c-f3c0215c6558", 168 | "metadata": {}, 169 | "outputs": [], 170 | "source": [ 171 | "# Output directory where the results and checkpoint are stored\n", 172 | "output_dir = \"./results\"\n", 173 | "\n", 174 | "# Number of training epochs - how many times does the model see the whole dataset\n", 175 | "num_train_epochs = 1 #Increase this for a larger finetune\n", 176 | "\n", 177 | "# Enable fp16/bf16 training. This is the type of each weight. Since we are on an A100\n", 178 | "# we can set bf16 to true because it can handle that type of computation\n", 179 | "bf16 = True\n", 180 | "\n", 181 | "# Batch size is the number of training examples used to train a single forward and backward pass. \n", 182 | "per_device_train_batch_size = 1\n", 183 | "\n", 184 | "# Gradients are accumulated over multiple mini-batches before updating the model weights. \n", 185 | "# This allows for effectively training with a larger batch size on hardware with limited memory\n", 186 | "gradient_accumulation_steps = 8\n", 187 | "\n", 188 | "# memory optimization technique that reduces RAM usage during training by intermittently storing \n", 189 | "# intermediate activations instead of retaining them throughout the entire forward pass, trading \n", 190 | "# computational time for lower memory consumption.\n", 191 | "gradient_checkpointing = True\n", 192 | "\n", 193 | "# Maximum gradient normal (gradient clipping)\n", 194 | "max_grad_norm = 0.3\n", 195 | "\n", 196 | "# Initial learning rate (AdamW optimizer)\n", 197 | "learning_rate = 2e-4\n", 198 | "\n", 199 | "# Weight decay to apply to all layers except bias/LayerNorm weights\n", 200 | "weight_decay = 0.001\n", 201 | "\n", 202 | "# Optimizer to use\n", 203 | "optim = \"paged_adamw_32bit\"\n", 204 | "\n", 205 | "# Number of training steps (overrides num_train_epochs)\n", 206 | "max_steps = 500\n", 207 | "\n", 208 | "# Ratio of steps for a linear warmup (from 0 to learning rate)\n", 209 | "warmup_ratio = 0.03\n", 210 | "\n", 211 | "# Group sequences into batches with same length\n", 212 | "# Saves memory and speeds up training considerably\n", 213 | "group_by_length = True\n", 214 | "\n", 215 | "# Save checkpoint every X updates steps\n", 216 | "save_steps = 100\n", 217 | "\n", 218 | "# Log every X updates steps\n", 219 | "logging_steps = 5" 220 | ] 221 | }, 222 | { 223 | "cell_type": "markdown", 224 | "id": "7bec1455-c08d-4671-bb3c-48cf07ec86a8", 225 | "metadata": {}, 226 | "source": [ 227 | "## (Optional) Run the training using WandB for logging\n", 228 | "\n", 229 | "Weights and Biases is industry standard for monitoring and evaluating your training job. If you have an account and API key, you can monitor this run." 230 | ] 231 | }, 232 | { 233 | "cell_type": "code", 234 | "execution_count": null, 235 | "id": "f57e00a2-a90a-4e43-a79d-2fe98dda58f6", 236 | "metadata": {}, 237 | "outputs": [], 238 | "source": [ 239 | "### Uncomment to use Weights and Biases ###\n", 240 | "\n", 241 | "# import wandb\n", 242 | "\n", 243 | "# wandb.login()" 244 | ] 245 | }, 246 | { 247 | "cell_type": "code", 248 | "execution_count": null, 249 | "id": "c93b0c17-77af-4328-889a-d418d0814101", 250 | "metadata": {}, 251 | "outputs": [], 252 | "source": [ 253 | "training_arguments = TrainingArguments(\n", 254 | " output_dir=output_dir,\n", 255 | " num_train_epochs=num_train_epochs,\n", 256 | " per_device_train_batch_size=per_device_train_batch_size,\n", 257 | " gradient_accumulation_steps=gradient_accumulation_steps,\n", 258 | " optim=optim,\n", 259 | " save_steps=save_steps,\n", 260 | " logging_steps=logging_steps,\n", 261 | " learning_rate=learning_rate,\n", 262 | " weight_decay=weight_decay,\n", 263 | " bf16=bf16,\n", 264 | " max_grad_norm=max_grad_norm,\n", 265 | " max_steps=max_steps,\n", 266 | " warmup_ratio=warmup_ratio,\n", 267 | " group_by_length=group_by_length,\n", 268 | " gradient_checkpointing=gradient_checkpointing,\n", 269 | " report_to=\"none\" # can replace with \"wandb\"\n", 270 | ")" 271 | ] 272 | }, 273 | { 274 | "cell_type": "code", 275 | "execution_count": null, 276 | "id": "3c6ad908-f10e-4605-bff3-efdfbe722a5c", 277 | "metadata": {}, 278 | "outputs": [], 279 | "source": [ 280 | "trainer = SFTTrainer(\n", 281 | " model=model,\n", 282 | " train_dataset=dataset,\n", 283 | " dataset_text_field=\"text\",\n", 284 | " tokenizer=tokenizer,\n", 285 | " args=training_arguments,\n", 286 | ")" 287 | ] 288 | }, 289 | { 290 | "cell_type": "code", 291 | "execution_count": null, 292 | "id": "1ef576ca-fa8d-4045-8a75-3e74116d4abf", 293 | "metadata": {}, 294 | "outputs": [], 295 | "source": [ 296 | "trainer.train()\n", 297 | "\n", 298 | "# Save trained model\n", 299 | "trainer.model.save_pretrained(new_model)" 300 | ] 301 | }, 302 | { 303 | "cell_type": "markdown", 304 | "id": "11b2e768-2b8c-4028-a385-37304eead298", 305 | "metadata": {}, 306 | "source": [ 307 | "## 4. Run the model for inference!\n", 308 | "\n", 309 | "To deploy this model for extremely quick inference, we use VLLM and host an OpenAI compatible endpoint. You might have to **restart the kernel** to flush the GPU memory and then just run the cells below. \n", 310 | "\n", 311 | "First, uncomment and install the vLLM pip package. You may need to restart the kernel for the package to take effect. Then, run the command to start the API server. Once running, you can open a new tab in Jupyterlab, select Terminal, and run the curl command to send a request to the server. \n", 312 | "\n", 313 | "**Note:** We install the latest version of vLLM in the following cell. This may upgrade your transformers package version, which can cause issues if you re-run the notebook from the beginning. If you would like to re-run the entire notebook for another finetuning flow, restart the project environment from inside AI Workbench to get a fresh environment to work in." 314 | ] 315 | }, 316 | { 317 | "cell_type": "code", 318 | "execution_count": null, 319 | "id": "16b71f88-25e7-4e52-8e06-b64b2da1208d", 320 | "metadata": {}, 321 | "outputs": [], 322 | "source": [ 323 | "# Uncomment to install the latest version of vLLM. \n", 324 | "# !pip install vllm" 325 | ] 326 | }, 327 | { 328 | "cell_type": "code", 329 | "execution_count": null, 330 | "id": "4862b83e-ec92-43bc-b7f6-d7aa7712430f", 331 | "metadata": { 332 | "scrolled": true 333 | }, 334 | "outputs": [], 335 | "source": [ 336 | "!python -O -u -m vllm.entrypoints.openai.api_server \\\n", 337 | " --host=0.0.0.0 \\\n", 338 | " --port=8000 \\\n", 339 | " --model=/project/models/NV-llama3-8b-SFT \\\n", 340 | " --tokenizer=meta-llama/Meta-Llama-3-8B \\\n", 341 | " --tensor-parallel-size=1 # set to number of GPUs\n", 342 | "\n", 343 | "# Open up a terminal and run\n", 344 | "# curl http://localhost:8000/v1/completions \\\n", 345 | "# -H \"Content-Type: application/json\" \\\n", 346 | "# -d '{\n", 347 | "# \"model\": \"/project/models/NV-llama3-8b-SFT\",\n", 348 | "# \"prompt\": \"What is San Francisco\",\n", 349 | "# \"max_tokens\": 30,\n", 350 | "# \"temperature\": 0\n", 351 | "# }'" 352 | ] 353 | }, 354 | { 355 | "cell_type": "code", 356 | "execution_count": null, 357 | "id": "58e340e5-be8c-4662-8b86-91041e4db2f6", 358 | "metadata": {}, 359 | "outputs": [], 360 | "source": [] 361 | } 362 | ], 363 | "metadata": { 364 | "kernelspec": { 365 | "display_name": "Python 3 (ipykernel)", 366 | "language": "python", 367 | "name": "python3" 368 | }, 369 | "language_info": { 370 | "codemirror_mode": { 371 | "name": "ipython", 372 | "version": 3 373 | }, 374 | "file_extension": ".py", 375 | "mimetype": "text/x-python", 376 | "name": "python", 377 | "nbconvert_exporter": "python", 378 | "pygments_lexer": "ipython3", 379 | "version": "3.10.12" 380 | } 381 | }, 382 | "nbformat": 4, 383 | "nbformat_minor": 5 384 | } 385 | --------------------------------------------------------------------------------