Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add LLaMA 2 example for DirectML #701

Merged
merged 63 commits into from
Nov 10, 2023
Merged
Show file tree
Hide file tree
Changes from 54 commits
Commits
Show all changes
63 commits
Select commit Hold shift + click to select a range
c5f57ff
Add a Llama 2 sample for DirectML
PatriceVignola Sep 18, 2023
bc4feb0
Remove cos/sin from float32 list
PatriceVignola Sep 18, 2023
4c7c191
Make Norm layer fp16
PatriceVignola Sep 18, 2023
7c927de
Make more RMSNorm float32
PatriceVignola Sep 18, 2023
78833b1
More fp32 conversions
PatriceVignola Sep 19, 2023
2fb953d
Provide max_gen_len
PatriceVignola Sep 19, 2023
50020d5
Improve ScatterND perf
PatriceVignola Sep 21, 2023
d28ecc4
Support any value for max_seq_len
PatriceVignola Sep 22, 2023
dadc77c
Split the cache in many parts
PatriceVignola Sep 26, 2023
8743604
Uncomment snippet
PatriceVignola Sep 26, 2023
b65d9f3
Remove unneeded gather
PatriceVignola Sep 27, 2023
5d03663
Slice cos/sin outside of the inner loop
PatriceVignola Sep 27, 2023
7b21092
Add dynamic sample
PatriceVignola Sep 30, 2023
0a71537
Enable dynamic graph fusion
PatriceVignola Oct 7, 2023
a08ce0f
Slightly improve UpdateCache perf
PatriceVignola Oct 8, 2023
b6d6cea
Remove float16 workaround
PatriceVignola Oct 9, 2023
b63184c
Set gpt2 as the model type in config
PatriceVignola Oct 9, 2023
6ea7319
Add MHA support
PatriceVignola Oct 10, 2023
49d1478
Add workaround for binding caches to same input/output
PatriceVignola Oct 10, 2023
5019038
Enable attention fusion
PatriceVignola Oct 10, 2023
bf16a3f
Add perf compute options
PatriceVignola Oct 10, 2023
e538b6c
Add LLaMA license and use guides
PatriceVignola Oct 11, 2023
b57c145
Add Chat app (WIP)
PatriceVignola Oct 12, 2023
148a314
Enable exposing chat app over local network
PatriceVignola Oct 12, 2023
3dc2a8c
Fix relative imports
PatriceVignola Oct 12, 2023
6e07b7d
Fix relative import issues
PatriceVignola Oct 23, 2023
14dc8f0
Add RotaryEmbedding support
PatriceVignola Oct 29, 2023
1b23bb7
Refactor code
PatriceVignola Oct 30, 2023
2d5acb8
WIP
PatriceVignola Oct 30, 2023
28bfc5e
Fix chat app
PatriceVignola Oct 30, 2023
60dc171
Add expand optimization
PatriceVignola Oct 30, 2023
66bb5da
Add expand optimization
PatriceVignola Oct 30, 2023
1f30f1e
Add seq_len_increment override
PatriceVignola Oct 30, 2023
ac576de
Simplify Expand node
PatriceVignola Oct 30, 2023
8dfa891
WIP
PatriceVignola Oct 30, 2023
f78f6d0
WIP
PatriceVignola Oct 30, 2023
3af2c35
Revert optimum merging changes
PatriceVignola Oct 31, 2023
631cf55
Add protobuf 3.20.3 dependency
PatriceVignola Oct 31, 2023
66b030e
Merge branch 'main' of https://github.com/microsoft/Olive into user/p…
PatriceVignola Oct 31, 2023
6b4b922
Refactoring
PatriceVignola Oct 31, 2023
34ba13d
Refactoring
PatriceVignola Oct 31, 2023
de53c2a
Merge branch 'main' of https://github.com/microsoft/Olive into user/p…
PatriceVignola Oct 31, 2023
ba75de7
Update README
PatriceVignola Oct 31, 2023
1ca895b
Remove wrong line
PatriceVignola Nov 1, 2023
23a14a0
Merge branch 'main' of https://github.com/microsoft/Olive into user/p…
PatriceVignola Nov 1, 2023
e6247ca
Add LayerNorm option
PatriceVignola Nov 6, 2023
cea6f07
Disable skip layer norm
PatriceVignola Nov 6, 2023
f427534
Simplify mask calculation
PatriceVignola Nov 6, 2023
6ab31b3
Clean chat app
PatriceVignola Nov 6, 2023
2c49da7
WIP
PatriceVignola Nov 7, 2023
f1b3bf8
WIP
PatriceVignola Nov 7, 2023
1364d84
Remove OptimumModel
PatriceVignola Nov 7, 2023
650f564
Merge branch 'main' of https://github.com/microsoft/Olive into user/p…
PatriceVignola Nov 7, 2023
6e61af9
Update requirement to onnxruntime-directml>=1.16.2
PatriceVignola Nov 7, 2023
f99b081
Apply lintrunner
PatriceVignola Nov 7, 2023
5dcc6c0
Revert CompositePytorchModel and OptimumModel merge
PatriceVignola Nov 7, 2023
d5aa5d0
Merge branch 'main' of https://github.com/microsoft/Olive into user/p…
PatriceVignola Nov 7, 2023
61514c9
Address PR comments
PatriceVignola Nov 7, 2023
aacad95
Ignore pylint for ChatApp
PatriceVignola Nov 7, 2023
1be509f
Revert unneeded change
PatriceVignola Nov 8, 2023
bad589e
Add COMPOSITE_MODEL
PatriceVignola Nov 9, 2023
83773ad
Add option to choose between 7b and 7b-chat
PatriceVignola Nov 9, 2023
94b3a63
Add LayerNorm and RMS option
PatriceVignola Nov 10, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/source/api/models.rst
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,9 @@ DistributedPyTorchModel Model
SNPE Model
----------
.. autoclass:: olive.model.SNPEModel

CompositePyTorchModel Model
--------------------------
.. autoclass:: olive.model.CompositePyTorchModel

.. _distributed_onnx_model:
3 changes: 2 additions & 1 deletion examples/directml/dolly_v2/config_dolly_v2.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
{
"input_model":{
"type": "OptimumModel",
"type": "CompositePyTorchModel",
"config": {
"model_type": "Optimum",
"model_path": "databricks/dolly-v2-7b",
"model_components": ["decoder_model.onnx", "decoder_with_past_model.onnx"]
}
Expand Down
2 changes: 2 additions & 0 deletions examples/directml/llama_v2/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/raw_model_data/
/footprints/
125 changes: 125 additions & 0 deletions examples/directml/llama_v2/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
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 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.
61 changes: 61 additions & 0 deletions examples/directml/llama_v2/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Llama 2 Optimization with DirectML <!-- omit in toc -->

This sample shows how to optimize [Llama 2](https://github.com/facebookresearch/llama) to run with ONNX Runtime and DirectML.

This implementation of Llama 2 is slightly different from what can be found in HuggingFace or other Llama repositories in order to make it run fast on ONNX Runtime and DirectML. One of the optimizations is having has a fixed size of `max_seq_len` that should be overridden when the session is loaded in order to make sure that DirectML is able to compile all operators into a single graph that can be reused for each token.

Also, the model is comprised of 2 subgraphs joined by an `If` node: `decoder_with_past` and `decoder`. This allows us to use a model with a variable sequence length for the first token, but then usethe model with a fixed sequence length of 1 for subsequent inferences. Again, this is necessary to allow DirectML to re-used compiled kernels as much as possible.

Finally, the model doesn't just output the logits but also the modified attention mask and rotary embeddings. This is to avoid having to update them outside of onnxruntime, which would require us to download the data to the CPU and use torch or numpy to update them.

**Contents**:
- [Setup](#setup)
- [Conversion to ONNX and Latency Optimization](#conversion-to-onnx-and-latency-optimization)

# Setup

Olive is currently under pre-release, with constant updates and improvements to the functions and usage. This sample code will be frequently updated as Olive evolves, so it is important to install Olive from source when checking out this code from the main branch. See the [README for examples](https://github.com/microsoft/Olive/blob/main/examples/README.md#important) for detailed instructions on how to do this.

1. Install Olive

```
pip install -e .
```

2. Install the requirements

```
cd olive/examples/directml/llama_v2
pip install -r requirements.txt
```

3. [Request access](https://ai.meta.com/resources/models-and-libraries/llama-downloads/) to the Llama 2 weights from Meta


# Conversion to ONNX and Latency Optimization

The easiest way to optimize the pipeline is with the `llama_v2.py` helper script:

```
python llama_v2.py
```

The first time this script is invoked can take some time since it will need to download the Llama 2 weights from Meta. When requested, paste the URL that was sent to your e-mail address by Meta (the link is valid for 24 hours).

The Llama V2 model is very large, and the optimization process is resource intensive. The optimization process can easily take more than 128GB of memory. You can still optimize the model on a machine with less memory, but you'd have to increase your paging file size accordingly and the conversion process will take significantly longer to complete (many hours).

Once the script successfully completes, the optimized ONNX pipeline will be stored under `models/optimized/llama_v2`.

Re-running the script with `--optimize` will delete the output models, but it will *not* delete the Olive cache. Subsequent runs will complete much faster since it will simply be copying previously optimized models; you may use the `--clean_cache` option to start from scratch (not typically used unless you are modifying the scripts, for example).

If you only want to run the inference sample (possible after the model has been optimized), run the `run_llama_v2_io_binding.py` helper script:

```
python run_llama_v2_io_binding.py --prompt=<any_prompt_you_choose>
```

The previous script works pretty well if you know in advance how long you want the output to be or if you want to limit the user to a maximum number of tokens. If you want to allow conversations of any length, use the following script instead:

```
python run_llama_v2_dynamic_io_binding.py --prompt=<any_prompt_you_choose>
```
Binary file not shown.
49 changes: 49 additions & 0 deletions examples/directml/llama_v2/USE-POLICY-META-LLAMA-2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# 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)
11 changes: 11 additions & 0 deletions examples/directml/llama_v2/argmax_sampling_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------

import torch


class ArgmaxSampling(torch.nn.Module):
def forward(self, logits):
return torch.argmax(logits, dim=-1, keepdim=True)
4 changes: 4 additions & 0 deletions examples/directml/llama_v2/chat_app/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import os
import sys

sys.path.append(os.path.dirname(os.path.realpath(__file__)))
Loading
Loading