diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index 428351ed0..000000000 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -name: Bug report -about: Create a report to help us reproduce and fix the issue -title: '' -labels: '' -assignees: '' - ---- - -**Before submitting a bug, please make sure the issue hasn't been already addressed by searching through the [FAQs](https://ai.meta.com/llama/faq/) and [existing/past issues](https://github.com/facebookresearch/llama/issues)** - -## Describe the bug - - -### Minimal reproducible example - - -```python -# sample code to repro the bug -``` - -### Output - - -``` - -``` - -## Runtime Environment -- Model: [eg: `llama-2-7b-chat`] -- Using via huggingface?: [yes/no] -- OS: [eg. Linux/Ubuntu, Windows] -- GPU VRAM: -- Number of GPUs: -- GPU Make: [eg: Nvidia, AMD, Intel] - -**Additional context** -Add any other context about the problem or environment here. diff --git a/.gitignore b/.gitignore index 6769e21d9..da2cdaa50 100755 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,7 @@ +llama-2-7b/ +tokenizer.model +tokenizer_checklist.chk + # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index cf9dc2448..000000000 --- a/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,80 +0,0 @@ -# Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to make participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, sex characteristics, gender identity and expression, -level of experience, education, socio-economic status, nationality, personal -appearance, race, religion, or sexual identity and orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or -advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic -address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a -professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies within all project spaces, and it also applies when -an individual is representing the project or its community in public spaces. -Examples of representing a project or community include using an official -project e-mail address, posting via an official social media account, or acting -as an appointed representative at an online or offline event. Representation of -a project may be further defined and clarified by project maintainers. - -This Code of Conduct also applies outside the project spaces when there is a -reasonable belief that an individual's behavior may have a negative impact on -the project or its community. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at . All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html - -[homepage]: https://www.contributor-covenant.org - -For answers to common questions about this code of conduct, see -https://www.contributor-covenant.org/faq \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 5eb507d67..000000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,31 +0,0 @@ -# Contributing to Llama -We want to make contributing to this project as easy and transparent as -possible. - -## Pull Requests -We actively welcome your pull requests. - -1. Fork the repo and create your branch from `main`. -2. If you've added code that should be tested, add tests. -3. If you've changed APIs, update the documentation. -4. Ensure the test suite passes. -5. Make sure your code lints. -6. If you haven't already, complete the Contributor License Agreement ("CLA"). - -## Contributor License Agreement ("CLA") -In order to accept your pull request, we need you to submit a CLA. You only need -to do this once to work on any of Meta's open source projects. - -Complete your CLA here: - -## Issues -We use GitHub issues to track public bugs. Please ensure your description is -clear and has sufficient instructions to be able to reproduce the issue. - -Meta has a [bounty program](https://www.facebook.com/whitehat/) for the safe -disclosure of security bugs. In those cases, please go through the process -outlined on that page and do not file a public issue. - -## License -By contributing to Llama, you agree that your contributions will be licensed -under the LICENSE file in the root directory of this source tree. \ No newline at end of file diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 28c98e84d..000000000 --- a/LICENSE +++ /dev/null @@ -1,126 +0,0 @@ -LLAMA 2 COMMUNITY LICENSE AGREEMENT -Llama 2 Version Release Date: July 18, 2023 - -"Agreement" means the terms and conditions for use, reproduction, distribution and -modification of the Llama Materials set forth herein. - -"Documentation" means the specifications, manuals and documentation -accompanying Llama 2 distributed by Meta at ai.meta.com/resources/models-and- -libraries/llama-downloads/. - -"Licensee" or "you" means you, or your employer or any other person or entity (if -you are entering into this Agreement on such person or entity's behalf), of the age -required under applicable laws, rules or regulations to provide legal consent and that -has legal authority to bind your employer or such other person or entity if you are -entering in this Agreement on their behalf. - -"Llama 2" means the foundational large language models and software and -algorithms, including machine-learning model code, trained model weights, -inference-enabling code, training-enabling code, fine-tuning enabling code and other -elements of the foregoing distributed by Meta at ai.meta.com/resources/models-and- -libraries/llama-downloads/. - -"Llama Materials" means, collectively, Meta's proprietary Llama 2 and -Documentation (and any portion thereof) made available under this Agreement. - -"Meta" or "we" means Meta Platforms Ireland Limited (if you are located in or, if you -are an entity, your principal place of business is in the EEA or Switzerland) and Meta -Platforms, Inc. (if you are located outside of the EEA or Switzerland). - -By clicking "I Accept" below or by using or distributing any portion or element of the -Llama Materials, you agree to be bound by this Agreement. - -1. License Rights and Redistribution. - - a. Grant of Rights. You are granted a non-exclusive, worldwide, non- -transferable and royalty-free limited license under Meta's intellectual property or -other rights owned by Meta embodied in the Llama Materials to use, reproduce, -distribute, copy, create derivative works of, and make modifications to the Llama -Materials. - - b. Redistribution and Use. - - i. If you distribute or make the Llama Materials, or any derivative works -thereof, available to a third party, you shall provide a copy of this Agreement to such -third party. - ii. If you receive Llama Materials, or any derivative works thereof, from -a Licensee as part of an integrated end user product, then Section 2 of this -Agreement will not apply to you. - - iii. You must retain in all copies of the Llama Materials that you -distribute the following attribution notice within a "Notice" text file distributed as a -part of such copies: "Llama 2 is licensed under the LLAMA 2 Community License, -Copyright (c) Meta Platforms, Inc. All Rights Reserved." - - iv. Your use of the Llama Materials must comply with applicable laws -and regulations (including trade compliance laws and regulations) and adhere to the -Acceptable Use Policy for the Llama Materials (available at -https://ai.meta.com/llama/use-policy), which is hereby incorporated by reference into -this Agreement. - - v. You will not use the Llama Materials or any output or results of the -Llama Materials to improve any other large language model (excluding Llama 2 or -derivative works thereof). - -2. Additional Commercial Terms. If, on the Llama 2 version release date, the -monthly active users of the products or services made available by or for Licensee, -or Licensee's affiliates, is greater than 700 million monthly active users in the -preceding calendar month, you must request a license from Meta, which Meta may -grant to you in its sole discretion, and you are not authorized to exercise any of the -rights under this Agreement unless or until Meta otherwise expressly grants you -such rights. - -3. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE -LLAMA MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE -PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY -WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR -FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE -FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING -THE LLAMA MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR -USE OF THE LLAMA MATERIALS AND ANY OUTPUT AND RESULTS. - -4. Limitation of Liability. IN NO EVENT WILL META OR ITS AFFILIATES BE -LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, -NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS -AGREEMENT, FOR ANY LOST PROFITS OR ANY INDIRECT, SPECIAL, -CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN -IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF -ANY OF THE FOREGOING. - -5. Intellectual Property. - - a. No trademark licenses are granted under this Agreement, and in -connection with the Llama Materials, neither Meta nor Licensee may use any name -or mark owned by or associated with the other or any of its affiliates, except as -required for reasonable and customary use in describing and redistributing the -Llama Materials. - - b. Subject to Meta's ownership of Llama Materials and derivatives made by or -for Meta, with respect to any derivative works and modifications of the Llama -Materials that are made by you, as between you and Meta, you are and will be the -owner of such derivative works and modifications. - - c. If you institute litigation or other proceedings against Meta or any entity -(including a cross-claim or counterclaim in a lawsuit) alleging that the Llama -Materials or Llama 2 outputs or results, or any portion of any of the foregoing, -constitutes an infringement of intellectual property or other rights owned or licensable -by you, then any licenses granted to you under this Agreement shall terminate as of -the date such litigation or claim is filed or instituted. You will indemnify and hold -harmless Meta from and against any claim by any third party arising out of or related -to your use or distribution of the Llama Materials. - -6. Term and Termination. The term of this Agreement will commence upon your -acceptance of this Agreement or access to the Llama Materials and will continue in -full force and effect until terminated in accordance with the terms and conditions -herein. Meta may terminate this Agreement if you are in breach of any term or -condition of this Agreement. Upon termination of this Agreement, you shall delete -and cease use of the Llama Materials. Sections 3, 4 and 7 shall survive the -termination of this Agreement. - -7. Governing Law and Jurisdiction. This Agreement will be governed and -construed under the laws of the State of California without regard to choice of law -principles, and the UN Convention on Contracts for the International Sale of Goods -does not apply to this Agreement. The courts of California shall have exclusive -jurisdiction of any dispute arising out of this Agreement. - diff --git a/MODEL_CARD.md b/MODEL_CARD.md deleted file mode 100644 index 370807880..000000000 --- a/MODEL_CARD.md +++ /dev/null @@ -1,100 +0,0 @@ -# **Model Details** - -Meta developed and released the Llama 2 family of large language models (LLMs), a collection of pretrained and fine-tuned generative text models ranging in scale from 7 billion to 70 billion parameters. Our fine-tuned LLMs, called Llama-2-Chat, are optimized for dialogue use cases. Llama-2-Chat models outperform open-source chat models on most benchmarks we tested, and in our human evaluations for helpfulness and safety, are on par with some popular closed-source models like ChatGPT and PaLM. - -**Model Developers** Meta - -**Variations** Llama 2 comes in a range of parameter sizes — 7B, 13B, and 70B — as well as pretrained and fine-tuned variations. - -**Input** Models input text only. - -**Output** Models generate text only. - -**Model Architecture** Llama 2 is an auto-regressive language model that uses an optimized transformer architecture. The tuned versions use supervised fine-tuning (SFT) and reinforcement learning with human feedback (RLHF) to align with human preferences for helpfulness and safety. - -||Training Data|Params|Context Length|GQA|Tokens|LR| -|---|---|---|---|---|---|---| -Llama 2|*A new mix of publicly available online data*|7B|4k|✗|2.0T|3.0 x 10-4 -Llama 2|*A new mix of publicly available online data*|13B|4k|✗|2.0T|3.0 x 10-4 -Llama 2|*A new mix of publicly available online data*|70B|4k|✔|2.0T|1.5 x 10-4 - -**Llama 2 family of models.** Token counts refer to pretraining data only. All models are trained with a global batch-size of 4M tokens. The 70B version uses Grouped-Query Attention (GQA) for improved inference scalability. - -**Model Dates** Llama 2 was trained between January 2023 and July 2023. - -**Status** This is a static model trained on an offline dataset. Future versions of the tuned models will be released as we improve model safety with community feedback. - -**License** A custom commercial license is available at: [https://ai.meta.com/resources/models-and-libraries/llama-downloads/](https://ai.meta.com/resources/models-and-libraries/llama-downloads/) - -**Research Paper** More information can be found in the paper "Llama-2: Open Foundation and Fine-tuned Chat Models", available at https://ai.meta.com/research/publications/llama-2-open-foundation-and-fine-tuned-chat-models/. - -**Where to send questions or comments about the model** Instructions on how to provide feedback or comments on the model can be found in the model [README](README.md). - -# **Intended Use** -**Intended Use Cases** Llama 2 is intended for commercial and research use in English. Tuned models are intended for assistant-like chat, whereas pretrained models can be adapted for a variety of natural language generation tasks. - -**Out-of-scope** Uses Use in any manner that violates applicable laws or regulations (including trade compliance laws). Use in any other way that is prohibited by the Acceptable Use Policy and Llama 2 Community License. Use in languages other than English**. - -**Note: Developers may fine-tune Llama 2 models for languages beyond English provided they comply with the Llama 2 Community License and the Acceptable Use Policy. - -# **Hardware and Software** -**Training Factors** We used custom training libraries, Meta's Research Super Cluster, and production clusters for pretraining. Fine-tuning, annotation, and evaluation were also performed on third-party cloud compute. - -**Carbon Footprint** Pretraining utilized a cumulative 3.3M GPU hours of computation on hardware of type A100-80GB (TDP of 350-400W). Estimated total emissions were 539 tCO2eq, 100% of which were offset by Meta’s sustainability program. - -||Time (GPU hours)|Power Consumption (W)|Carbon Emitted(tCO2eq)| -|---|---|---|---| -|Llama 2 7B|184320|400|31.22| -|Llama 2 13B|368640|400|62.44| -|Llama 2 70B|1720320|400|291.42| -|Total|3311616||539.00| - -**CO2 emissions during pretraining.** Time: total GPU time required for training each model. Power Consumption: peak power capacity per GPU device for the GPUs used adjusted for power usage efficiency. 100% of the emissions are directly offset by Meta's sustainability program, and because we are openly releasing these models, the pretraining costs do not need to be incurred by others. - -# **Training Data** -**Overview** Llama 2 was pretrained on 2 trillion tokens of data from publicly available sources. The fine-tuning data includes publicly available instruction datasets, as well as over one million new human-annotated examples. Neither the pretraining nor the fine-tuning datasets include Meta user data. - -**Data Freshness** The pretraining data has a cutoff of September 2022, but some tuning data is more recent, up to July 2023. - -# **Evaluation Results** - -In this section, we report the results for the Llama 1 and Llama 2 models on standard academic benchmarks. -For all the evaluations, we use our internal evaluations library. - -|Model|Size|Code|Commonsense Reasoning|World Knowledge|Reading Comprehension|Math|MMLU|BBH|AGI Eval| -|---|---|---|---|---|---|---|---|---|---| -|Llama 1|7B|14.1|60.8|46.2|58.5|6.95|35.1|30.3|23.9| -|Llama 1|13B|18.9|66.1|52.6|62.3|10.9|46.9|37.0|33.9| -|Llama 1|33B|26.0|70.0|58.4|67.6|21.4|57.8|39.8|41.7| -|Llama 1|65B|30.7|70.7|60.5|68.6|30.8|63.4|43.5|47.6| -|Llama 2|7B|16.8|63.9|48.9|61.3|14.6|45.3|32.6|29.3| -|Llama 2|13B|24.5|66.9|55.4|65.8|28.7|54.8|39.4|39.1| -|Llama 2|70B|**37.5**|**71.9**|**63.6**|**69.4**|**35.2**|**68.9**|**51.2**|**54.2**| - -**Overall performance on grouped academic benchmarks.** *Code:* We report the average pass@1 scores of our models on HumanEval and MBPP. *Commonsense Reasoning:* We report the average of PIQA, SIQA, HellaSwag, WinoGrande, ARC easy and challenge, OpenBookQA, and CommonsenseQA. We report 7-shot results for CommonSenseQA and 0-shot results for all other benchmarks. *World Knowledge:* We evaluate the 5-shot performance on NaturalQuestions and TriviaQA and report the average. *Reading Comprehension:* For reading comprehension, we report the 0-shot average on SQuAD, QuAC, and BoolQ. *MATH:* We report the average of the GSM8K (8 shot) and MATH (4 shot) benchmarks at the top 1. - -|||TruthfulQA|Toxigen| -|---|---|---|---| -|Llama 1|7B|27.42|23.00| -|Llama 1|13B|41.74|23.08| -|Llama 1|33B|44.19|22.57| -|Llama 1|65B|48.71|21.77| -|Llama 2|7B|33.29|**21.25**| -|Llama 2|13B|41.86|26.10| -|Llama 2|70B|**50.18**|24.60| - -**Evaluation of pretrained LLMs on automatic safety benchmarks.** For TruthfulQA, we present the percentage of generations that are both truthful and informative (the higher the better). For ToxiGen, we present the percentage of toxic generations (the smaller the better). - - -|||TruthfulQA|Toxigen| -|---|---|---|---| -|Llama-2-Chat|7B|57.04|**0.00**| -|Llama-2-Chat|13B|62.18|**0.00**| -|Llama-2-Chat|70B|**64.14**|0.01| - -**Evaluation of fine-tuned LLMs on different safety datasets.** Same metric definitions as above. - -# **Ethical Considerations and Limitations** -Llama 2 is a new technology that carries risks with use. Testing conducted to date has been in English, and has not covered, nor could it cover all scenarios. For these reasons, as with all LLMs, Llama 2’s potential outputs cannot be predicted in advance, and the model may in some instances produce inaccurate, biased or other objectionable responses to user prompts. Therefore, before deploying any applications of Llama 2, developers should perform safety testing and tuning tailored to their specific applications of the model. - -Please see the Responsible Use Guide available at [https://ai.meta.com/llama/responsible-use-guide/](https://ai.meta.com/llama/responsible-use-guide/) diff --git a/README.md b/README.md index 96ae58f01..22e8a7d8e 100755 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Llama 2 -We are unlocking the power of large language models. Our latest version of Llama is now accessible to individuals, creators, researchers and businesses of all sizes so that they can experiment, innovate and scale their ideas responsibly. +We are unlocking the power of large language models. Our latest version of Llama is now accessible to individuals, creators, researchers and businesses of all sizes so that they can experiment, innovate and scale their ideas responsibly. This release includes model weights and starting code for pretrained and fine-tuned Llama language models — ranging from 7B to 70B parameters. @@ -28,32 +28,36 @@ We are also providing downloads on [Hugging Face](https://huggingface.co/meta-ll ## Quick Start -You can follow the steps below to quickly get up and running with Llama 2 models. These steps will let you run quick inference locally. For more examples, see the [Llama 2 recipes repository](https://github.com/facebookresearch/llama-recipes). +You can follow the steps below to quickly get up and running with Llama 2 models. These steps will let you run quick inference locally. For more examples, see the [Llama 2 recipes repository](https://github.com/facebookresearch/llama-recipes). 1. In a conda env with PyTorch / CUDA available clone and download this repository. 2. In the top level directory run: - ```bash - pip install -e . - ``` + ```bash + pip install -e . + ``` 3. Visit the [Meta website](https://ai.meta.com/resources/models-and-libraries/llama-downloads/) and register to download the model/s. 4. Once registered, you will get an email with a URL to download the models. You will need this URL when you run the download.sh script. -5. Once you get the email, navigate to your downloaded llama repository and run the download.sh script. - - Make sure to grant execution permissions to the download.sh script - - During this process, you will be prompted to enter the URL from the email. - - Do not use the “Copy Link” option but rather make sure to manually copy the link from the email. +5. Once you get the email, navigate to your downloaded llama repository and run the download.sh script. + + - Make sure to grant execution permissions to the download.sh script + - During this process, you will be prompted to enter the URL from the email. + - Do not use the “Copy Link” option but rather make sure to manually copy the link from the email. 6. Once the model/s you want have been downloaded, you can run the model locally using the command below: + ```bash torchrun --nproc_per_node 1 example_chat_completion.py \ --ckpt_dir llama-2-7b-chat/ \ --tokenizer_path tokenizer.model \ --max_seq_len 512 --max_batch_size 6 ``` + **Note** -- Replace `llama-2-7b-chat/` with the path to your checkpoint directory and `tokenizer.model` with the path to your tokenizer model. + +- Replace `llama-2-7b-chat/` with the path to your checkpoint directory and `tokenizer.model` with the path to your tokenizer model. - The `–nproc_per_node` should be set to the [MP](#inference) value for the model you are using. - Adjust the `max_seq_len` and `max_batch_size` parameters as needed. - This example runs the [example_chat_completion.py](example_chat_completion.py) found in this repository but you can change that to a different .py file. @@ -62,11 +66,11 @@ torchrun --nproc_per_node 1 example_chat_completion.py \ Different models require different model-parallel (MP) values: -| Model | MP | -|--------|----| -| 7B | 1 | -| 13B | 2 | -| 70B | 8 | +| Model | MP | +| ----- | --- | +| 7B | 1 | +| 13B | 2 | +| 70B | 8 | All models support sequence length up to 4096 tokens, but we pre-allocate the cache according to `max_seq_len` and `max_batch_size` values. So set those according to your hardware. @@ -105,16 +109,18 @@ In order to help developers address these risks, we have created the [Responsibl ## Issues Please report any software “bug”, or other problems with the models through one of the following means: + - Reporting issues with the model: [github.com/facebookresearch/llama](http://github.com/facebookresearch/llama) - Reporting risky content generated by the model: [developers.facebook.com/llama_output_feedback](http://developers.facebook.com/llama_output_feedback) - Reporting bugs and security concerns: [facebook.com/whitehat/info](http://facebook.com/whitehat/info) ## Model Card + See [MODEL_CARD.md](MODEL_CARD.md). ## License -Our model and weights are licensed for both researchers and commercial entities, upholding the principles of openness. Our mission is to empower individuals, and industry through this opportunity, while fostering an environment of discovery and ethical AI advancements. +Our model and weights are licensed for both researchers and commercial entities, upholding the principles of openness. Our mission is to empower individuals, and industry through this opportunity, while fostering an environment of discovery and ethical AI advancements. See the [LICENSE](LICENSE) file, as well as our accompanying [Acceptable Use Policy](USE_POLICY.md) @@ -124,7 +130,8 @@ See the [LICENSE](LICENSE) file, as well as our accompanying [Acceptable Use Pol 2. [Llama 2 technical overview](https://ai.meta.com/resources/models-and-libraries/llama) 3. [Open Innovation AI Research Community](https://ai.meta.com/llama/open-innovation-ai-research-community/) -For common questions, the FAQ can be found [here](https://ai.meta.com/llama/faq/) which will be kept up to date over time as new questions arise. +For common questions, the FAQ can be found [here](https://ai.meta.com/llama/faq/) which will be kept up to date over time as new questions arise. ## Original LLaMA + The repo for the original llama release is in the [`llama_v1`](https://github.com/facebookresearch/llama/tree/llama_v1) branch. diff --git a/Responsible-Use-Guide.pdf b/Responsible-Use-Guide.pdf deleted file mode 100644 index e65e5d1c8..000000000 Binary files a/Responsible-Use-Guide.pdf and /dev/null differ diff --git a/UPDATES.md b/UPDATES.md deleted file mode 100644 index f3429d838..000000000 --- a/UPDATES.md +++ /dev/null @@ -1,21 +0,0 @@ -# 8/7/23 Updates - -## System Prompt Update - -### Observed Issue -We received feedback from the community on our prompt template and we are providing an update to reduce the false refusal rates seen. False refusals occur when the model incorrectly refuses to answer a question that it should, for example due to overly broad instructions to be cautious in how it provides responses. - -### Updated approach -Based on evaluation and analysis, we recommend the removal of the system prompt as the default setting. Pull request [#626](https://github.com/facebookresearch/llama/pull/626) removes the system prompt as the default option, but still provides an example to help enable experimentation for those using it. - -## Token Sanitization Update - -### Observed Issue -The PyTorch scripts currently provided for tokenization and model inference allow for direct prompt injection via string concatenation. Prompt injections allow for the addition of special system and instruction prompt strings from user-provided prompts. - -As noted in the documentation, these strings are required to use the fine-tuned chat models. However, prompt injections have also been used for manipulating or abusing models by bypassing their safeguards, allowing for the creation of content or behaviors otherwise outside the bounds of acceptable use. - -### Updated approach -We recommend sanitizing [these strings](https://github.com/facebookresearch/llama#fine-tuned-chat-models) from any user provided prompts. Sanitization of user prompts mitigates malicious or accidental abuse of these strings. The provided scripts have been updated to do this. - -Note: even with this update safety classifiers should still be applied to catch unsafe behaviors or content produced by the model. An [example](https://github.com/facebookresearch/llama-recipes/blob/main/inference/inference.py) of how to deploy such a classifier can be found in the llama-recipes repository. diff --git a/USE_POLICY.md b/USE_POLICY.md deleted file mode 100644 index abbcc199b..000000000 --- a/USE_POLICY.md +++ /dev/null @@ -1,50 +0,0 @@ -# Llama 2 Acceptable Use Policy - -Meta is committed to promoting safe and fair use of its tools and features, including Llama 2. If you access or use Llama 2, you agree to this Acceptable Use Policy (“Policy”). The most recent copy of this policy can be found at [ai.meta.com/llama/use-policy](http://ai.meta.com/llama/use-policy). - -## Prohibited Uses -We want everyone to use Llama 2 safely and responsibly. You agree you will not use, or allow others to use, Llama 2 to: - -1. Violate the law or others’ rights, including to: - 1. Engage in, promote, generate, contribute to, encourage, plan, incite, or further illegal or unlawful activity or content, such as: - 1. Violence or terrorism - 2. Exploitation or harm to children, including the solicitation, creation, acquisition, or dissemination of child exploitative content or failure to report Child Sexual Abuse Material - 3. Human trafficking, exploitation, and sexual violence - 4. The illegal distribution of information or materials to minors, including obscene materials, or failure to employ legally required age-gating in connection with such information or materials. - 5. Sexual solicitation - 6. Any other criminal activity - 2. Engage in, promote, incite, or facilitate the harassment, abuse, threatening, or bullying of individuals or groups of individuals - 3. Engage in, promote, incite, or facilitate discrimination or other unlawful or harmful conduct in the provision of employment, employment benefits, credit, housing, other economic benefits, or other essential goods and services - 4. Engage in the unauthorized or unlicensed practice of any profession including, but not limited to, financial, legal, medical/health, or related professional practices - 5. Collect, process, disclose, generate, or infer health, demographic, or other sensitive personal or private information about individuals without rights and consents required by applicable laws - 6. Engage in or facilitate any action or generate any content that infringes, misappropriates, or otherwise violates any third-party rights, including the outputs or results of any products or services using the Llama 2 Materials - 7. Create, generate, or facilitate the creation of malicious code, malware, computer viruses or do anything else that could disable, overburden, interfere with or impair the proper working, integrity, operation or appearance of a website or computer system - - - -2. Engage in, promote, incite, facilitate, or assist in the planning or development of activities that present a risk of death or bodily harm to individuals, including use of Llama 2 related to the following: - 1. Military, warfare, nuclear industries or applications, espionage, use for materials or activities that are subject to the International Traffic Arms Regulations (ITAR) maintained by the United States Department of State - 2. Guns and illegal weapons (including weapon development) - 3. Illegal drugs and regulated/controlled substances - 4. Operation of critical infrastructure, transportation technologies, or heavy machinery - 5. Self-harm or harm to others, including suicide, cutting, and eating disorders - 6. Any content intended to incite or promote violence, abuse, or any infliction of bodily harm to an individual - - - -3. Intentionally deceive or mislead others, including use of Llama 2 related to the following: - 1. Generating, promoting, or furthering fraud or the creation or promotion of disinformation - 2. Generating, promoting, or furthering defamatory content, including the creation of defamatory statements, images, or other content - 3. Generating, promoting, or further distributing spam - 4. Impersonating another individual without consent, authorization, or legal right - 5. Representing that the use of Llama 2 or outputs are human-generated - 6. Generating or facilitating false online engagement, including fake reviews and other means of fake online engagement -4. Fail to appropriately disclose to end users any known dangers of your AI system - -Please report any violation of this Policy, software “bug,” or other problems that could lead to a violation of this Policy through one of the following means: - -* Reporting issues with the model: [github.com/facebookresearch/llama](http://github.com/facebookresearch/llama) -* Reporting risky content generated by the model: [developers.facebook.com/llama_output_feedback](http://developers.facebook.com/llama_output_feedback) -* Reporting bugs and security concerns: [facebook.com/whitehat/info](http://facebook.com/whitehat/info) -* Reporting violations of the Acceptable Use Policy or unlicensed uses of Llama: [LlamaUseReport@meta.com](mailto:LlamaUseReport@meta.com) - diff --git a/benchmark_outputs/batch_size_1_num_workers_0.txt b/benchmark_outputs/batch_size_1_num_workers_0.txt new file mode 100644 index 000000000..b768df38b --- /dev/null +++ b/benchmark_outputs/batch_size_1_num_workers_0.txt @@ -0,0 +1,58 @@ +Starting up... +Building data loaders... +Initializing Model... +> initializing model parallel with size 1 +> initializing ddp with size 1 +> initializing pipeline with size 1 +Loaded in 12.05 seconds +Running inference benchmark... + +Working on device: cuda +Starting BATCH 1 of 5 +Finished Batch 1 of 5 +Batch load time: 0.0010531009902479127 +Batch inference time: 5.044861934002256 +Batch total time: 5.045921023993287 +Starting BATCH 2 of 5 +Finished Batch 2 of 5 +Batch load time: 0.000634292999166064 +Batch inference time: 4.504916821009829 +Batch total time: 4.505557062002481 +Starting BATCH 3 of 5 +Finished Batch 3 of 5 +Batch load time: 0.0007395810098387301 +Batch inference time: 4.533521624005516 +Batch total time: 4.534268278002855 +Starting BATCH 4 of 5 +Finished Batch 4 of 5 +Batch load time: 0.0006648830021731555 +Batch inference time: 4.495368515010341 +Batch total time: 4.496039069999824 +Starting BATCH 5 of 5 +Finished Batch 5 of 5 +Batch load time: 0.0006519919988932088 +Batch inference time: 4.496985145000508 +Batch total time: 4.497643199007143 + + + Manual Profile Results... +Data-loading times +> per epoch: tensor([0.0011, 0.0006, 0.0007, 0.0007, 0.0007]) +> average: tensor(0.0007) + +Inference time for each epoch +> per epoch tensor([5.0430, 4.5039, 4.5352, 4.4961, 4.4961]) +> average tensor(4.6133) + +Total time for each epoch +> per epoch tensor([5.0469, 4.5039, 4.5352, 4.4961, 4.4961]) +> average tensor(4.6172) + + + +Profiling sorted by CUDA time total +------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ + Name Self CPU % Self CPU CPU total % CPU total CPU time avg Self CUDA Self CUDA % CUDA total CUDA time avg CPU Mem Self CPU Mem CUDA Mem Self CUDA Mem # of Calls +------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ + run_benchmark 27.07% 6.249s 100.00% 23.083s 23.083s 0.000us 0.00% 15.070s 15.070s 0 b -2.66 Kb 8.13 Mb -4.18 Gb 1 +"benchmark_outputs/batch_size_1_num_workers_0.txt" 91L, 8729B 53,1 Top \ No newline at end of file diff --git a/benchmark_outputs/batch_size_1_num_workers_1.txt b/benchmark_outputs/batch_size_1_num_workers_1.txt new file mode 100644 index 000000000..92517ddd6 --- /dev/null +++ b/benchmark_outputs/batch_size_1_num_workers_1.txt @@ -0,0 +1,58 @@ +Starting up... +Building data loaders... +Initializing Model... +> initializing model parallel with size 1 +> initializing ddp with size 1 +> initializing pipeline with size 1 +Loaded in 65.44 seconds +Running inference benchmark... + +Working on device: cuda +Starting BATCH 1 of 5 +Finished Batch 1 of 5 +Batch load time: 0.17542113500530832 +Batch inference time: 5.1042240419919835 +Batch total time: 5.27965795599448 +Starting BATCH 2 of 5 +Finished Batch 2 of 5 +Batch load time: 0.11129688000073656 +Batch inference time: 4.523343688008026 +Batch total time: 4.634657599002821 +Starting BATCH 3 of 5 +Finished Batch 3 of 5 +Batch load time: 0.0730158430087613 +Batch inference time: 4.516634412007988 +Batch total time: 4.589664141007233 +Starting BATCH 4 of 5 +Finished Batch 4 of 5 +Batch load time: 0.07771697499265429 +Batch inference time: 4.432252533995779 +Batch total time: 4.509983689000364 +Starting BATCH 5 of 5 +Finished Batch 5 of 5 +Batch load time: 0.0820326890097931 +Batch inference time: 4.4701670890062815 +Batch total time: 4.552215193005395 + + + Manual Profile Results... +Data-loading times +> per epoch: tensor([0.1754, 0.1113, 0.0730, 0.0777, 0.0820]) +> average: tensor(0.1039) + +Inference time for each epoch +> per epoch tensor([5.1055, 4.5234, 4.5156, 4.4336, 4.4688]) +> average tensor(4.6094) + +Total time for each epoch +> per epoch tensor([5.2812, 4.6328, 4.5898, 4.5117, 4.5508]) +> average tensor(4.7148) + + + +Profiling sorted by CUDA time total +------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ + Name Self CPU % Self CPU CPU total % CPU total CPU time avg Self CUDA Self CUDA % CUDA total CUDA time avg CPU Mem Self CPU Mem CUDA Mem Self CUDA Mem # of Calls +------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ + run_benchmark 27.94% 6.585s 100.00% 23.570s 23.570s 0.000us 0.00% 15.065s 15.065s 0 b -2.66 Kb 8.13 Mb -4.16 Gb 1 +"benchmark_outputs/batch_size_1_num_workers_1.txt" 91L, 8719B 1,1 Top \ No newline at end of file diff --git a/benchmark_outputs/batch_size_2_num_workers_0.txt b/benchmark_outputs/batch_size_2_num_workers_0.txt new file mode 100644 index 000000000..7a9420d43 --- /dev/null +++ b/benchmark_outputs/batch_size_2_num_workers_0.txt @@ -0,0 +1,58 @@ +Starting up... +Building data loaders... +Initializing Model... +> initializing model parallel with size 1 +> initializing ddp with size 1 +> initializing pipeline with size 1 +Loaded in 67.71 seconds +Running inference benchmark... + +Working on device: cuda +Starting BATCH 1 of 5 +Finished Batch 1 of 5 +Batch load time: 0.0012337989901425317 +Batch inference time: 4.979560280000442 +Batch total time: 4.980800386008923 +Starting BATCH 2 of 5 +Finished Batch 2 of 5 +Batch load time: 0.0006314070051303133 +Batch inference time: 4.436402372986777 +Batch total time: 4.4370395870064385 +Starting BATCH 3 of 5 +Finished Batch 3 of 5 +Batch load time: 0.0006100949976826087 +Batch inference time: 4.489002016998711 +Batch total time: 4.489618256004178 +Starting BATCH 4 of 5 +Finished Batch 4 of 5 +Batch load time: 0.000657053999020718 +Batch inference time: 4.481591136995121 +Batch total time: 4.482254397997167 +Starting BATCH 5 of 5 +Finished Batch 5 of 5 +Batch load time: 0.0006241549999685958 +Batch inference time: 4.433049211991602 +Batch total time: 4.43367860399303 + + + Manual Profile Results... +Data-loading times +> per epoch: tensor([0.0012, 0.0006, 0.0006, 0.0007, 0.0006]) +> average: tensor(0.0008) + +Inference time for each epoch +> per epoch tensor([4.9805, 4.4375, 4.4883, 4.4805, 4.4336]) +> average tensor(4.5625) + +Total time for each epoch +> per epoch tensor([4.9805, 4.4375, 4.4883, 4.4805, 4.4336]) +> average tensor(4.5625) + + + +Profiling sorted by CUDA time total +------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ + Name Self CPU % Self CPU CPU total % CPU total CPU time avg Self CUDA Self CUDA % CUDA total CUDA time avg CPU Mem Self CPU Mem CUDA Mem Self CUDA Mem # of Calls +------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ + run_benchmark 26.66% 6.085s 100.00% 22.827s 22.827s 0.000us 0.00% 15.085s 15.085s 0 b -2.66 Kb 8.13 Mb -4.18 Gb 1 +"benchmark_outputs/batch_size_2_num_workers_0.txt" 91L, 8729B 52,0-1 Top \ No newline at end of file diff --git a/benchmark_outputs/batch_size_2_num_workers_1.txt b/benchmark_outputs/batch_size_2_num_workers_1.txt new file mode 100644 index 000000000..36a617ade --- /dev/null +++ b/benchmark_outputs/batch_size_2_num_workers_1.txt @@ -0,0 +1,58 @@ +Starting up... +Building data loaders... +Initializing Model... +> initializing model parallel with size 1 +> initializing ddp with size 1 +> initializing pipeline with size 1 +Loaded in 111.55 seconds +Running inference benchmark... + +Working on device: cuda +Starting BATCH 1 of 5 +Finished Batch 1 of 5 +Batch load time: 0.0553153660002863 +Batch inference time: 4.988452916993992 +Batch total time: 5.043779415995232 +Starting BATCH 2 of 5 +Finished Batch 2 of 5 +Batch load time: 0.06645661000220571 +Batch inference time: 4.431401344001642 +Batch total time: 4.49787032698805 +Starting BATCH 3 of 5 +Finished Batch 3 of 5 +Batch load time: 0.06894606399873737 +Batch inference time: 4.5093786460056435 +Batch total time: 4.5783342299982905 +Starting BATCH 4 of 5 +Finished Batch 4 of 5 +Batch load time: 0.10248679800133687 +Batch inference time: 4.488342932003434 +Batch total time: 4.590840438992018 +Starting BATCH 5 of 5 +Finished Batch 5 of 5 +Batch load time: 0.07949267400545068 +Batch inference time: 4.5397761540079955 +Batch total time: 4.619280054001138 + + + Manual Profile Results... +Data-loading times +> per epoch: tensor([0.0553, 0.0665, 0.0690, 0.1025, 0.0795]) +> average: tensor(0.0745) + +Inference time for each epoch +> per epoch tensor([4.9883, 4.4297, 4.5078, 4.4883, 4.5391]) +> average tensor(4.5898) + +Total time for each epoch +> per epoch tensor([5.0430, 4.4961, 4.5781, 4.5898, 4.6211]) +> average tensor(4.6641) + + + +Profiling sorted by CUDA time total +------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ + Name Self CPU % Self CPU CPU total % CPU total CPU time avg Self CUDA Self CUDA % CUDA total CUDA time avg CPU Mem Self CPU Mem CUDA Mem Self CUDA Mem # of Calls +------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ + run_benchmark 27.47% 6.410s 100.00% 23.334s 23.334s 0.000us 0.00% 15.079s 15.079s 0 b -2.66 Kb 8.13 Mb -4.18 Gb 1 +"benchmark_outputs/batch_size_2_num_workers_1.txt" 91L, 8722B 1,1 Top \ No newline at end of file diff --git a/benchmark_outputs/batch_size_4_num_workers_0.txt b/benchmark_outputs/batch_size_4_num_workers_0.txt new file mode 100644 index 000000000..1d7aa9616 --- /dev/null +++ b/benchmark_outputs/batch_size_4_num_workers_0.txt @@ -0,0 +1,58 @@ +Starting up... +Building data loaders... +Initializing Model... +> initializing model parallel with size 1 +> initializing ddp with size 1 +> initializing pipeline with size 1 +Loaded in 182.83 seconds +Running inference benchmark... + +Working on device: cuda +Starting BATCH 1 of 5 +Finished Batch 1 of 5 +Batch load time: 0.0010882980132009834 +Batch inference time: 5.046935585996835 +Batch total time: 5.048030566002126 +Starting BATCH 2 of 5 +Finished Batch 2 of 5 +Batch load time: 0.0006488210055977106 +Batch inference time: 4.47928033999051 +Batch total time: 4.479962162004085 +Starting BATCH 3 of 5 +Finished Batch 3 of 5 +Batch load time: 0.0006499989976873621 +Batch inference time: 4.4514494110044325 +Batch total time: 4.452105590986321 +Starting BATCH 4 of 5 +Finished Batch 4 of 5 +Batch load time: 0.0006679049984086305 +Batch inference time: 4.445740676994319 +Batch total time: 4.446414493009797 +Starting BATCH 5 of 5 +Finished Batch 5 of 5 +Batch load time: 0.0006229520076885819 +Batch inference time: 4.457714663003571 +Batch total time: 4.458343616002821 + + + Manual Profile Results... +Data-loading times +> per epoch: tensor([0.0011, 0.0006, 0.0006, 0.0007, 0.0006]) +> average: tensor(0.0007) + +Inference time for each epoch +> per epoch tensor([5.0469, 4.4805, 4.4531, 4.4453, 4.4570]) +> average tensor(4.5781) + +Total time for each epoch +> per epoch tensor([5.0469, 4.4805, 4.4531, 4.4453, 4.4570]) +> average tensor(4.5781) + + + +Profiling sorted by CUDA time total +------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ + Name Self CPU % Self CPU CPU total % CPU total CPU time avg Self CUDA Self CUDA % CUDA total CUDA time avg CPU Mem Self CPU Mem CUDA Mem Self CUDA Mem # of Calls +------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ + run_benchmark 26.98% 6.176s 100.00% 22.888s 22.888s 0.000us 0.00% 15.065s 15.065s 0 b -2.66 Kb 8.13 Mb -4.19 Gb 1 +"benchmark_outputs/batch_size_4_num_workers_0.txt" 91L, 8731B 1,1 Top \ No newline at end of file diff --git a/benchmark_outputs/batch_size_4_num_workers_1.txt b/benchmark_outputs/batch_size_4_num_workers_1.txt new file mode 100644 index 000000000..8178362f9 --- /dev/null +++ b/benchmark_outputs/batch_size_4_num_workers_1.txt @@ -0,0 +1,58 @@ +Starting up... +Building data loaders... +Initializing Model... +> initializing model parallel with size 1 +> initializing ddp with size 1 +> initializing pipeline with size 1 +Loaded in 100.42 seconds +Running inference benchmark... + +Working on device: cuda +Starting BATCH 1 of 5 +Finished Batch 1 of 5 +Batch load time: 0.1019776799948886 +Batch inference time: 5.030931850997149 +Batch total time: 5.132919580995804 +Starting BATCH 2 of 5 +Finished Batch 2 of 5 +Batch load time: 0.0671316090010805 +Batch inference time: 4.438084541005082 +Batch total time: 4.505228757989244 +Starting BATCH 3 of 5 +Finished Batch 3 of 5 +Batch load time: 0.06837264500791207 +Batch inference time: 4.474854444008088 +Batch total time: 4.543237587000476 +Starting BATCH 4 of 5 +Finished Batch 4 of 5 +Batch load time: 0.07436333999794442 +Batch inference time: 4.4623387989995535 +Batch total time: 4.53671289801423 +Starting BATCH 5 of 5 +Finished Batch 5 of 5 +Batch load time: 0.07757725499686785 +Batch inference time: 4.4232901810028125 +Batch total time: 4.500878610997461 + + + Manual Profile Results... +Data-loading times +> per epoch: tensor([0.1020, 0.0671, 0.0684, 0.0743, 0.0776]) +> average: tensor(0.0779) + +Inference time for each epoch +> per epoch tensor([5.0312, 4.4375, 4.4766, 4.4609, 4.4219]) +> average tensor(4.5664) + +Total time for each epoch +> per epoch tensor([5.1328, 4.5039, 4.5430, 4.5352, 4.5000]) +> average tensor(4.6445) + + + +Profiling sorted by CUDA time total +------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ + Name Self CPU % Self CPU CPU total % CPU total CPU time avg Self CUDA Self CUDA % CUDA total CUDA time avg CPU Mem Self CPU Mem CUDA Mem Self CUDA Mem # of Calls +------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ + run_benchmark 27.55% 6.399s 100.00% 23.222s 23.222s 0.000us 0.00% 15.063s 15.063s 0 b -3.18 Kb 8.13 Mb -4.17 Gb 1 +"benchmark_outputs/batch_size_4_num_workers_1.txt" 91L, 8720B 1,1 Top \ No newline at end of file diff --git a/benchmark_outputs/batch_size_8_num_workers_0.txt b/benchmark_outputs/batch_size_8_num_workers_0.txt new file mode 100644 index 000000000..a2a91117a --- /dev/null +++ b/benchmark_outputs/batch_size_8_num_workers_0.txt @@ -0,0 +1,58 @@ +Starting up... +Building data loaders... +Initializing Model... +> initializing model parallel with size 1 +> initializing ddp with size 1 +> initializing pipeline with size 1 +Loaded in 182.13 seconds +Running inference benchmark... + +Working on device: cuda +Starting BATCH 1 of 5 +Finished Batch 1 of 5 +Batch load time: 0.001075489999493584 +Batch inference time: 4.895436988997972 +Batch total time: 4.896518624998862 +Starting BATCH 2 of 5 +Finished Batch 2 of 5 +Batch load time: 0.0006358410028042272 +Batch inference time: 4.359566414990695 +Batch total time: 4.360208049998619 +Starting BATCH 3 of 5 +Finished Batch 3 of 5 +Batch load time: 0.0006404919986380264 +Batch inference time: 4.369482416004757 +Batch total time: 4.370128884998849 +Starting BATCH 4 of 5 +Finished Batch 4 of 5 +Batch load time: 0.0006534309941343963 +Batch inference time: 4.313248220991227 +Batch total time: 4.313907664007274 +Starting BATCH 5 of 5 +Finished Batch 5 of 5 +Batch load time: 0.0006494239933090284 +Batch inference time: 4.3910173189942725 +Batch total time: 4.391673523001373 + + + Manual Profile Results... +Data-loading times +> per epoch: tensor([0.0011, 0.0006, 0.0006, 0.0007, 0.0006]) +> average: tensor(0.0007) + +Inference time for each epoch +> per epoch tensor([4.8945, 4.3594, 4.3711, 4.3125, 4.3906]) +> average tensor(4.4648) + +Total time for each epoch +> per epoch tensor([4.8984, 4.3594, 4.3711, 4.3125, 4.3906]) +> average tensor(4.4648) + + + +Profiling sorted by CUDA time total +------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ + Name Self CPU % Self CPU CPU total % CPU total CPU time avg Self CUDA Self CUDA % CUDA total CUDA time avg CPU Mem Self CPU Mem CUDA Mem Self CUDA Mem # of Calls +------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ + run_benchmark 26.27% 5.868s 100.00% 22.336s 22.336s 0.000us 0.00% 15.074s 15.074s 0 b -2.66 Kb 8.13 Mb -4.21 Gb 1 +"benchmark_outputs/batch_size_8_num_workers_0.txt" 91L, 8731B 1,1 Top \ No newline at end of file diff --git a/benchmark_outputs/batch_size_8_num_workers_1.txt b/benchmark_outputs/batch_size_8_num_workers_1.txt new file mode 100644 index 000000000..fc77342a7 --- /dev/null +++ b/benchmark_outputs/batch_size_8_num_workers_1.txt @@ -0,0 +1,30 @@ + aten::copy_ 4.45% 1.043s 8.63% 2.024s 16.191us 416.322ms 2.99% 743.074ms 5.945us 0 b 0 b 0 b 0 b 124995 + aten::_to_copy 2.84% 666.198ms 12.83% 3.008s 29.012us 0.000us 0.00% 646.904ms 6.239us 2.58 Kb 0 b 1.06 Gb 0 b 103695 + aten::to 1.22% 286.543ms 13.80% 3.236s 22.222us 0.000us 0.00% 641.483ms 4.405us 2.58 Kb 0 b 1.06 Gb 25.83 Mb 145620 +------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ +Self CPU time total: 23.446s +Self CUDA time total: 13.901s + + + + +Profiling sorted by CUDA memory usage +------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ + Name Self CPU % Self CPU CPU total % CPU total CPU time avg Self CUDA Self CUDA % CUDA total CUDA time avg CPU Mem Self CPU Mem CUDA Mem Self CUDA Mem # of Calls +------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ + aten::empty_strided 3.32% 777.328ms 3.32% 777.328ms 7.473us 0.000us 0.00% 0.000us 0.000us 2.58 Kb 2.58 Kb 1.10 Gb 1.10 Gb 104015 + aten::mul 4.20% 983.674ms 6.09% 1.427s 19.729us 128.721ms 0.93% 311.740ms 4.311us 0 b 0 b 1.01 Gb 1.01 Gb 72320 + aten::mm 9.76% 2.288s 12.53% 2.937s 40.787us 12.947s 93.14% 13.155s 182.704us 0 b 0 b 870.93 Mb 870.93 Mb 72000 + aten::pow 1.51% 353.068ms 2.04% 477.868ms 22.974us 20.913ms 0.15% 79.482ms 3.821us 0 b 0 b 330.08 Mb 330.08 Mb 20800 + aten::silu 0.65% 151.408ms 0.96% 225.273ms 21.999us 26.142ms 0.19% 50.783ms 4.959us 0 b 0 b 218.36 Mb 218.36 Mb 10240 + aten::add 2.81% 657.946ms 4.07% 953.898ms 23.019us 62.703ms 0.45% 174.723ms 4.216us 0 b 0 b 172.73 Mb 172.73 Mb 41440 + aten::sort 0.10% 23.128ms 0.22% 51.926ms 161.763us 26.676ms 0.19% 48.079ms 149.779us 0 b 0 b 117.55 Mb 117.55 Mb 321 + aten::bmm 2.47% 579.866ms 3.22% 756.074ms 36.918us 82.598ms 0.59% 135.565ms 6.619us 0 b 0 b 104.38 Mb 104.38 Mb 20480 + aten::_softmax 0.60% 140.315ms 0.88% 206.046ms 19.512us 32.235ms 0.23% 60.789ms 5.757us 0 b 0 b 82.81 Mb 82.81 Mb 10560 + aten::div 0.85% 199.026ms 1.19% 279.037ms 25.647us 15.933ms 0.11% 42.943ms 3.947us 0 b 0 b 62.19 Mb 62.19 Mb 10880 +------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ +Self CPU time total: 23.446s +Self CUDA time total: 13.901s + +~ +"benchmark_outputs/batch_size_8_num_workers_1.txt" 91L, 8721B 91,0-1 Bot \ No newline at end of file diff --git a/gsmk_dataset.py b/gsmk_dataset.py new file mode 100644 index 000000000..4f25d5884 --- /dev/null +++ b/gsmk_dataset.py @@ -0,0 +1,18 @@ +from torch.utils.data import DataLoader +import time +from datasets import load_dataset + +# https://huggingface.co/datasets/gsm8k +HUGGING_FACE_GSMK_DATASET_ID = "gsm8k" + +# Manual seed for reproducatibility + +def get_data_loader(batch_size, num_workers): + dataset = load_dataset(HUGGING_FACE_GSMK_DATASET_ID, 'main')['train'] + dataloader = DataLoader( + dataset, + batch_size=batch_size, + shuffle=False, + num_workers=num_workers + ) + return dataloader diff --git a/inference_benchmark.py b/inference_benchmark.py new file mode 100644 index 000000000..2c7a6f726 --- /dev/null +++ b/inference_benchmark.py @@ -0,0 +1,160 @@ +import torch +from gsmk_dataset import get_data_loader +import time +import fire +from torch.profiler import profile, record_function, ProfilerActivity + + +from llama import Llama +from typing import List + +### Setup ### +BATCH_SIZE = 16 +BATCH_COUNT = 5 +NUM_WORKERS = 1 +PROFILE_MEMORY = True + +# https://huggingface.co/datasets/gsm8k +HUGGING_FACE_GSMK_DATASET_ID = "gsm8k" + +# Manual seed for reproducatibility +SEED = 42 +torch.manual_seed(SEED) +torch.cuda.manual_seed(SEED) + +DEVICE_CUDA = 'cuda' +DEVICE_CPU = 'cpu' + + +def get_device(): + return torch.device(DEVICE_CUDA if torch.cuda.is_available() else DEVICE_CPU) + +def get_model(ckpt_dir, tokenizer_path, max_seq_len, max_batch_size): + generator = Llama.build( + ckpt_dir=ckpt_dir, + tokenizer_path=tokenizer_path, + max_seq_len=max_seq_len, + max_batch_size=max_batch_size, + ) + return generator + + +def run_benchmark(dataloader, model): + load_time_per_batch = torch.zeros(BATCH_COUNT) + inference_time_per_batch = torch.zeros(BATCH_COUNT) + total_time_per_batch = torch.zeros(BATCH_COUNT) + + device = get_device() + # model.to(device) + print("Working on device: {}".format(device)) + + + for batch_idx in range(BATCH_COUNT): + print("Starting BATCH {} of {}".format(batch_idx + 1, BATCH_COUNT)) + (output, load_time, inference_time), batch_time = measure_runtime(run_batch_inference, + dataloader, + model) + load_time_per_batch[batch_idx] = load_time + inference_time_per_batch[batch_idx] = inference_time + total_time_per_batch[batch_idx] = batch_time + + print("Finished Batch {} of {}".format(batch_idx + 1, BATCH_COUNT)) + print("Batch load time: {}".format(load_time)) + print("Batch inference time: {}".format(inference_time)) + print("Batch total time: {}".format(batch_time)) + return model, load_time_per_batch, inference_time_per_batch, total_time_per_batch + + +def measure_runtime(func, *func_args): + start = time.perf_counter() + result = func(*func_args) + end = time.perf_counter() + elapsed = end - start + return result, elapsed + + +def run_batch_inference(dataloader, model): + (question, answer), load_time = measure_runtime( + __get_next_batch, dataloader) + + + # print("question: ", question, "\nanswer: ", answer) + # print("question type: ", type(question), "answer type", type(answer)) + # print("question shape: ", len(question), "answer shape", len(answer)) + # device = get_device() + # x = x.to(device) + # y = y.to(device) + + output, inference_time = measure_runtime( + inference, + model, + [question]) + + return output, load_time, inference_time + +def inference( + generator: Llama, + prompts: List[str], + temperature: float = 0.6, + top_p: float = 0.9, + max_gen_len: int = 64, +): + with torch.no_grad(): + results = generator.text_completion( + prompts, + max_gen_len=max_gen_len, + temperature=temperature, + top_p=top_p, + ) + return zip(prompts, results) + +def __get_next_batch(dataloader): + return next(iter(dataloader)) + + +def benchmark(ckpt_dir, + tokenizer_path, + max_seq_len, + max_batch_size, + batch_size=BATCH_SIZE, + num_workers=NUM_WORKERS): + print("Starting up...") + + print("Building data loaders...") + data_loader = get_data_loader(num_workers, batch_size) + + print("Initializing Model...") + net = get_model(ckpt_dir, tokenizer_path, max_seq_len, max_batch_size) + + print("Running inference benchmark...\n") + + with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], record_shapes=True, profile_memory=PROFILE_MEMORY) as prof: + with record_function("run_benchmark"): + # _, load, inference, total = run_benchmark(data_loader, net) + _, load, inference, total = run_benchmark(data_loader, net) + + print("\n\n Manual Profile Results...") + print("Data-loading times") + print("> per epoch: ", load) + print("> average: ", torch.mean(load)) + print("\nInference time for each epoch") + print("> per epoch", inference) + print("> average", torch.mean(inference)) + print("\nTotal time for each epoch") + print("> per epoch", total) + print("> average", torch.mean(total)) + + print("\n\n") + print("Profiling sorted by CUDA time total") + profile_cuda_time = prof.key_averages().table(sort_by="cuda_time_total", row_limit=10) + print(profile_cuda_time) + + print("\n\n") + print("Profiling sorted by CUDA memory usage") + profile_cuda_mem = prof.key_averages().table(sort_by="self_cuda_memory_usage", row_limit=10) + print(profile_cuda_mem) + + +if __name__ == "__main__": + # torch.cuda.empty_cache() + fire.Fire(benchmark) diff --git a/llama/generation.py b/llama/generation.py index 5f8faf9f3..a16d31f1a 100755 --- a/llama/generation.py +++ b/llama/generation.py @@ -116,7 +116,13 @@ def build( tokenizer = Tokenizer(model_path=tokenizer_path) model_args.vocab_size = tokenizer.n_words torch.set_default_tensor_type(torch.cuda.HalfTensor) - model = Transformer(model_args) + model = Transformer(model_args).eval() # quantization + #model.fuse_model() # quantization + + model.qconfig = torch.ao.quantization.default_qconfig # quantization + torch.ao.quantization.prepare(model, inplace=True) + torch.ao.quantization.convert(model, inplace=True) + model.load_state_dict(checkpoint, strict=False) print(f"Loaded in {time.time() - start_time:.2f} seconds") diff --git a/llama/model.py b/llama/model.py index c78570f68..c0c14aa96 100755 --- a/llama/model.py +++ b/llama/model.py @@ -381,6 +381,7 @@ def __init__(self, layer_id: int, args: ModelArgs): ) self.layer_id = layer_id self.attention_norm = RMSNorm(args.dim, eps=args.norm_eps) + self.attn_norm_w = self.attention_norm.weight self.ffn_norm = RMSNorm(args.dim, eps=args.norm_eps) def forward( @@ -430,6 +431,8 @@ def __init__(self, params: ModelArgs): """ super().__init__() + # quantization + # self.quant = torch.ao.quantization.QuantStub() self.params = params self.vocab_size = params.vocab_size self.n_layers = params.n_layers @@ -452,6 +455,9 @@ def __init__(self, params: ModelArgs): # Adding this multiplier instead of using 4096 directly allows for dynamism of token lengths while training or fine-tuning. self.params.dim // self.params.n_heads, self.params.max_seq_len * 2 ) + # quantization + # self.dequant = torch.ao.quantization.DeQuantStub() + @torch.inference_mode() def forward(self, tokens: torch.Tensor, start_pos: int): @@ -487,9 +493,13 @@ def forward(self, tokens: torch.Tensor, start_pos: int): torch.zeros((seqlen, start_pos), device=tokens.device), mask ]).type_as(h) - - for layer in self.layers: + + for layer_idx, layer in enumerate(self.layers): h = layer(h, start_pos, freqs_cis, mask) + """if layer_idx == 0: + h = self.quant(h)""" h = self.norm(h) output = self.output(h).float() + # quantization + # output = self.dequant(output) return output diff --git a/prune_model.py b/prune_model.py new file mode 100644 index 000000000..d78d57fdc --- /dev/null +++ b/prune_model.py @@ -0,0 +1,120 @@ +import os +import torch +from llama import Llama +import fire +from gsmk_dataset import get_data_loader +import torch +import torch.nn.utils.prune as prune + +backend = "qnnpack" + +def print_model_size(mdl): + torch.save(mdl.state_dict(), "tmp.pt") + print("%.2f MB" %(os.path.getsize("tmp.pt")/1e6)) + os.remove('tmp.pt') + + + +def get_model(ckpt_dir, tokenizer_path, max_seq_len, max_batch_size): + generator = Llama.build( + ckpt_dir=ckpt_dir, + tokenizer_path=tokenizer_path, + max_seq_len=max_seq_len, + max_batch_size=max_batch_size, + ) + return generator + +def prune_model(llama): + model = llama.model + + print(f'model type = {type(model)}') + + # set up pruning: + count = 0 + total_params = 0 + before_num_zeros = 0 + after_num_zeros = 0 + for layer in model.layers: # each layer is a TransformerBlock + # we only have nn.Parameter objects in RMSNorm class + #import torch.nn.utils.prune as prune + + # Assuming you have a TransformerBlock object named 'layer' + #num_zeros = torch.sum(layer.weight == 0).item() + #total_params = layer.weight.numel() + #sparsity = num_zeros / total_params + #print(f"Sparsity of the TransformerBlock (before pruning): {sparsity}") + before_total_weights = layer.attention.wq.weight + layer.attention.wk.weight + layer.attention.wv.weight + layer.attention_norm.weight + layer.ffn_norm.weight + #att_norm_w = layer.attention_norm.weight + #ffn_norm_w = layer.ffn_norm.weight + #total_weights = attention_w + att_norm_w + ffn_norm_w + before_num_zeros += torch.sum(before_total_weights == 0).item() + total_params += before_total_weights.numel() + #print(f'Sparsity of the TransformerBlock (before pruning): {sparsity}') + + + layer=prune.random_unstructured(layer, name="attn_norm_w", amount=0.3) # name is a torch.nn.Parameter + + after_total_weights = layer.attention.wq.weight + layer.attention.wk.weight + layer.attention.wv.weight + layer.attention_norm.weight + layer.ffn_norm.weight + after_num_zeros += torch.sum(after_total_weights == 0).item() + + #num_zeros = torch.sum(layer.weight == 0).item() + #sparsity = num_zeros / total_params + #print(f"Sparsity of the TransformerBlock (after pruning): {sparsity}") + # prune.l1_unstructured(layer, name="bias", amount=3) + count += 1 + if count % 10**6 == 0: + print(f'we are {count} layers in') + + print(f'Sparsity of the TransformerBlock (before pruning): {before_num_zeros/total_params}') + print(f'Sparsity of the TransformerBlock (after pruning): {after_num_zeros/total_params}') + + + + """for i in range(len(model.layers)): # each layer is a TransformerBlock + # we only have nn.Parameter objects in RMSNorm class + model.layers[i] = prune.random_unstructured(model.layers[i], name="attn_norm_w", amount=0.3) # name is a torch.nn.Parameter + # model.layer = prune.random_unstructured(layer, name="attn_norm_w", amount=0.3) # name is a torch.nn.Parameter + # prune.l1_unstructured(layer, name="bias", amount=3) + """ + + + + #enc = model.encoder + #dec = model.decoder + + # setup quantization + """model.eval() + model.qconfig = torch.ao.quantization.get_default_qconfig('x86') + torch.backends.quantized.engine = backend + torch.quantization.prepare(model, inplace=True) + """ + + # calibrate model to real world data + dataloader = get_data_loader(3, 0) + for _ in range(10): + batch = next(iter(dataloader)) + llama.text_completion( + batch, + max_gen_len=512, + temperature=0.6, + top_p=0.9, + ) + + # convert in place + # torch.quantization.convert(model, inplace=True) + + +def main(): + llama = get_model("/home/gyt2107/hpml_llama/llama-2-7b/", "tokenizer.model", 512, 6) + print("model size before in-place pruning") + print_model_size(llama.model) + + prune_model(llama) + print("model size after in-place pruning") + print_model_size(llama.model) + + # save the quantized model + torch.save(llama.model.state_dict(), "quantized_model.pt") + +if __name__ == "__main__": + fire.Fire(main) \ No newline at end of file diff --git a/quantize_model.py b/quantize_model.py new file mode 100644 index 000000000..d12bd556a --- /dev/null +++ b/quantize_model.py @@ -0,0 +1,61 @@ +import os +import torch +from llama import Llama +import fire +from gsmk_dataset import get_data_loader + +backend = "qnnpack" + +def print_model_size(mdl): + torch.save(mdl.state_dict(), "tmp.pt") + print("%.2f MB" %(os.path.getsize("tmp.pt")/1e6)) + os.remove('tmp.pt') + + + +def get_model(ckpt_dir, tokenizer_path, max_seq_len, max_batch_size): + generator = Llama.build( + ckpt_dir=ckpt_dir, + tokenizer_path=tokenizer_path, + max_seq_len=max_seq_len, + max_batch_size=max_batch_size, + ) + return generator + +def quantize_model(llama): + model = llama.model + # setup quantization + model.eval() + model.qconfig = torch.ao.quantization.get_default_qconfig('x86') + torch.backends.quantized.engine = backend + torch.quantization.prepare(model, inplace=True) + + # calibrate model to real world data + dataloader = get_data_loader(3, 0) + for _ in range(10): + batch = next(iter(dataloader)) + llama.text_completion( + batch, + max_gen_len=512, + temperature=0.6, + top_p=0.9, + ) + + # convert in place + torch.quantization.convert(model, inplace=True) + + +def main(): + llama = get_model("llama-2-7b/", "tokenizer.model", 512, 6) + print("model size before in-place quantization") + print_model_size(llama.model) + + quantize_model(llama) + print("model size after in-place quantization") + print_model_size(llama.model) + + # save the quantized model + torch.save(llama.model.state_dict(), "quantized_model.pt") + +if __name__ == "__main__": + fire.Fire(main) \ No newline at end of file diff --git a/run_inference_benchmarks.sh b/run_inference_benchmarks.sh new file mode 100644 index 000000000..a1763fb2c --- /dev/null +++ b/run_inference_benchmarks.sh @@ -0,0 +1,55 @@ +# TODO: parameterize. this works for now. + +echo "Running inference benchmarks" + +if [ ! -d "benchmark_outputs" ]; then + echo "Creating benchmark_outputs directory" + mkdir benchmark_outputs +fi + +echo "Batch size 1, num workers 0" +torchrun inference_benchmark.py --ckpt_dir llama-2-7b/ --tokenizer_path tokenizer.model --max_seq_len 512 --max_batch_size 8 --batch_size 1 --num_workers 0 > benchmark_outputs/batch_size_1_num_workers_0.txt +echo "Batch size 2, num workers 0" +torchrun inference_benchmark.py --ckpt_dir llama-2-7b/ --tokenizer_path tokenizer.model --max_seq_len 512 --max_batch_size 8 --batch_size 2 --num_workers 0 > benchmark_outputs/batch_size_2_num_workers_0.txt +echo "Batch size 4, num workers 0" +torchrun inference_benchmark.py --ckpt_dir llama-2-7b/ --tokenizer_path tokenizer.model --max_seq_len 512 --max_batch_size 8 --batch_size 4 --num_workers 0 > benchmark_outputs/batch_size_4_num_workers_0.txt +echo "Batch size 8, num workers 0" +torchrun inference_benchmark.py --ckpt_dir llama-2-7b/ --tokenizer_path tokenizer.model --max_seq_len 512 --max_batch_size 8 --batch_size 8 --num_workers 0 > benchmark_outputs/batch_size_8_num_workers_0.txt + +echo "Batch size 1, num workers 1" +torchrun inference_benchmark.py --ckpt_dir llama-2-7b/ --tokenizer_path tokenizer.model --max_seq_len 512 --max_batch_size 8 --batch_size 1 --num_workers 1 > benchmark_outputs/batch_size_1_num_workers_1.txt +echo "Batch size 2, num workers 1" +torchrun inference_benchmark.py --ckpt_dir llama-2-7b/ --tokenizer_path tokenizer.model --max_seq_len 512 --max_batch_size 8 --batch_size 2 --num_workers 1 > benchmark_outputs/batch_size_2_num_workers_1.txt +echo "Batch size 4, num workers 1" +torchrun inference_benchmark.py --ckpt_dir llama-2-7b/ --tokenizer_path tokenizer.model --max_seq_len 512 --max_batch_size 8 --batch_size 4 --num_workers 1 > benchmark_outputs/batch_size_4_num_workers_1.txt +echo "Batch size 8, num workers 1" +torchrun inference_benchmark.py --ckpt_dir llama-2-7b/ --tokenizer_path tokenizer.model --max_seq_len 512 --max_batch_size 8 --batch_size 8 --num_workers 1 > benchmark_outputs/batch_size_8_num_workers_1.txt + +echo "Batch size 1, num workers 2" +torchrun inference_benchmark.py --ckpt_dir llama-2-7b/ --tokenizer_path tokenizer.model --max_seq_len 512 --max_batch_size 8 --batch_size 1 --num_workers 2 > benchmark_outputs/batch_size_1_num_workers_2.txt +echo "Batch size 2, num workers 2" +torchrun inference_benchmark.py --ckpt_dir llama-2-7b/ --tokenizer_path tokenizer.model --max_seq_len 512 --max_batch_size 8 --batch_size 2 --num_workers 2 > benchmark_outputs/batch_size_2_num_workers_2.txt +echo "Batch size 4, num workers 2" +torchrun inference_benchmark.py --ckpt_dir llama-2-7b/ --tokenizer_path tokenizer.model --max_seq_len 512 --max_batch_size 8 --batch_size 4 --num_workers 2 > benchmark_outputs/batch_size_4_num_workers_2.txt +echo "Batch size 8, num workers 2" +torchrun inference_benchmark.py --ckpt_dir llama-2-7b/ --tokenizer_path tokenizer.model --max_seq_len 512 --max_batch_size 8 --batch_size 8 --num_workers 2 > benchmark_outputs/batch_size_8_num_workers_2.txt + +echo "Batch size 1, num workers 4" +torchrun inference_benchmark.py --ckpt_dir llama-2-7b/ --tokenizer_path tokenizer.model --max_seq_len 512 --max_batch_size 8 --batch_size 1 --num_workers 4 > benchmark_outputs/batch_size_1_num_workers_4.txt +echo "Batch size 2, num workers 4" +torchrun inference_benchmark.py --ckpt_dir llama-2-7b/ --tokenizer_path tokenizer.model --max_seq_len 512 --max_batch_size 8 --batch_size 2 --num_workers 4 > benchmark_outputs/batch_size_2_num_workers_4.txt +echo "Batch size 4, num workers 4" +torchrun inference_benchmark.py --ckpt_dir llama-2-7b/ --tokenizer_path tokenizer.model --max_seq_len 512 --max_batch_size 8 --batch_size 4 --num_workers 4 > benchmark_outputs/batch_size_4_num_workers_4.txt +echo "Batch size 8, num workers 4" +torchrun inference_benchmark.py --ckpt_dir llama-2-7b/ --tokenizer_path tokenizer.model --max_seq_len 512 --max_batch_size 8 --batch_size 8 --num_workers 4 > benchmark_outputs/batch_size_8_num_workers_4.txt + +echo "Batch size 1, num workers 8" +torchrun inference_benchmark.py --ckpt_dir llama-2-7b/ --tokenizer_path tokenizer.model --max_seq_len 512 --max_batch_size 8 --batch_size 1 --num_workers 8 > benchmark_outputs/batch_size_1_num_workers_8.txt +echo "Batch size 2, num workers 8" +torchrun inference_benchmark.py --ckpt_dir llama-2-7b/ --tokenizer_path tokenizer.model --max_seq_len 512 --max_batch_size 8 --batch_size 2 --num_workers 8 > benchmark_outputs/batch_size_2_num_workers_8.txt +echo "Batch size 4, num workers 8" +torchrun inference_benchmark.py --ckpt_dir llama-2-7b/ --tokenizer_path tokenizer.model --max_seq_len 512 --max_batch_size 8 --batch_size 4 --num_workers 8 > benchmark_outputs/batch_size_4_num_workers_8.txt +echo "Batch size 8, num workers 8" +torchrun inference_benchmark.py --ckpt_dir llama-2-7b/ --tokenizer_path tokenizer.model --max_seq_len 512 --max_batch_size 8 --batch_size 8 --num_workers 8 > benchmark_outputs/batch_size_8_num_workers_8.txt + +echo "DONE. Exiting." \ No newline at end of file diff --git a/script_model.py b/script_model.py new file mode 100644 index 000000000..ba89e000b --- /dev/null +++ b/script_model.py @@ -0,0 +1,74 @@ +import torch +from torch.utils.data import DataLoader +import time +from datasets import load_dataset +import fire +from torch.profiler import profile, record_function, ProfilerActivity + +### Setup ### +BATCH_SIZE = 1 +BATCH_COUNT = 5 +NUM_WORKERS = 1 +PROFILE_MEMORY = True + +# https://huggingface.co/datasets/gsm8k +HUGGING_FACE_GSMK_DATASET_ID = "gsm8k" + +# Manual seed for reproducatibility +SEED = 42 +torch.manual_seed(SEED) +torch.cuda.manual_seed(SEED) + +DEVICE_CUDA = 'cuda' +DEVICE_CPU = 'cpu' + +from llama import Llama +from typing import List + +def get_model(ckpt_dir, tokenizer_path, max_seq_len, max_batch_size): + generator = Llama.build( + ckpt_dir=ckpt_dir, + tokenizer_path=tokenizer_path, + max_seq_len=max_seq_len, + max_batch_size=max_batch_size, + ) + return generator + +def inference( + generator: Llama, + prompts: List[str], + temperature: float = 0.6, + top_p: float = 0.9, + max_gen_len: int = 64, +): + with torch.no_grad(): + results = generator.text_completion( + prompts, + max_gen_len=max_gen_len, + temperature=temperature, + top_p=top_p, + ) + return zip(prompts, results) + + + +def script_model(ckpt_dir, + tokenizer_path, + max_seq_len, + max_batch_size): + print("Starting up...") + # torch.cuda.reset() + torch.cuda.empty_cache() + print("Initializing Model...") + llama = get_model(ckpt_dir, tokenizer_path, max_seq_len, max_batch_size) + + print("Attempting to script model...") + scripted_llama = torch.jit.script(llama) + print("Successfully scripted model!") + + print("Saving scripted model...") + scripted_llama.save("scripted_llama.pt") + + +if __name__ == "__main__": + fire.Fire(script_model)