-
Notifications
You must be signed in to change notification settings - Fork 88
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit f5985ac
Showing
26 changed files
with
2,231 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
*.json | ||
*.DS_Store | ||
*.pyc | ||
*.egg-info | ||
dist |
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
# Code of Conduct | ||
|
||
## Our Pledge | ||
|
||
In the interest of fostering an open and welcoming environment, we as | ||
contributors and maintainers pledge to making 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. | ||
|
||
## Enforcement | ||
|
||
Instances of abusive, harassing, or otherwise unacceptable behavior may be | ||
reported by contacting the open source team at [[email protected]](mailto:[email protected]). 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](https://www.contributor-covenant.org), version 1.4, | ||
available at [https://www.contributor-covenant.org/version/1/4/code-of-conduct.html](https://www.contributor-covenant.org/version/1/4/code-of-conduct.html) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
# Contribution Guide | ||
|
||
Thanks for your interest in contributing. This project was released to provide a reference implementation, and beyond its publication there are limited plans for future development of the repository. | ||
|
||
While we welcome new pull requests and issues please note that our response may be limited. Forks and out-of-tree improvements are strongly encouraged. | ||
|
||
## Before you get started | ||
|
||
By submitting a pull request, you represent that you have the right to license your contribution to Apple and the community, and agree by submitting the patch that your contributions are licensed under the [LICENSE](LICENSE). | ||
|
||
We ask that all community members read and observe our [Code of Conduct](CODE_OF_CONDUCT.md). |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
Copyright (C) 2022 Apple Inc. All Rights Reserved. | ||
|
||
IMPORTANT: This Apple software is supplied to you by Apple | ||
Inc. ("Apple") in consideration of your agreement to the following | ||
terms, and your use, installation, modification or redistribution of | ||
this Apple software constitutes acceptance of these terms. If you do | ||
not agree with these terms, please do not use, install, modify or | ||
redistribute this Apple software. | ||
|
||
In consideration of your agreement to abide by the following terms, and | ||
subject to these terms, Apple grants you a personal, non-exclusive | ||
license, under Apple's copyrights in this original Apple software (the | ||
"Apple Software"), to use, reproduce, modify and redistribute the Apple | ||
Software, with or without modifications, in source and/or binary forms; | ||
provided that if you redistribute the Apple Software in its entirety and | ||
without modifications, you must retain this notice and the following | ||
text and disclaimers in all such redistributions of the Apple Software. | ||
Neither the name, trademarks, service marks or logos of Apple Inc. may | ||
be used to endorse or promote products derived from the Apple Software | ||
without specific prior written permission from Apple. Except as | ||
expressly stated in this notice, no other rights or licenses, express or | ||
implied, are granted by Apple herein, including but not limited to any | ||
patent rights that may be infringed by your derivative works or by other | ||
works in which the Apple Software may be incorporated. | ||
|
||
The Apple Software is provided by Apple on an "AS IS" basis. APPLE | ||
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION | ||
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS | ||
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND | ||
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. | ||
|
||
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL | ||
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF | ||
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS | ||
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, | ||
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED | ||
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), | ||
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE | ||
POSSIBILITY OF SUCH DAMAGE. | ||
|
||
------------------------------------------------------------------------------- | ||
SOFTWARE DISTRIBUTED WITH ane_transformers: | ||
|
||
The ane_transformers software includes a number of subcomponents with separate | ||
copyright notices and license terms - please see the file ACKNOWLEDGEMENTS. | ||
------------------------------------------------------------------------------- |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
test: | ||
python ane_transformers/reference/test_transformer.py | ||
python ane_transformers/huggingface/test_distilbert.py | ||
|
||
style: | ||
yapf -rip --verify ane_transformers |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
# Apple Neural Engine (ANE) Transformers | ||
Use `ane_transformers` as a reference PyTorch implementation if you are considering deploying your Transformer models on Apple devices with an A14 or newer and M1 or newer chip to achieve up to **10 times faster** and **14 times** lower peak memory consumption compared to baseline implementations. | ||
|
||
`ane_transformers.reference` comprises a standalone reference implementation and `ane_transformers.huggingface` comprises optimized versions of [Hugging Face](https://huggingface.co/models) model classes such as `distilbert` to demonstrate the application of the optimization principles laid out in our research article on existing third-party implementations. | ||
|
||
Please check out our [research article](https://machinelearning.apple.com/research/apple-neural-engine) for a detailed explanation of the optimizations as well as interactive figures to explore latency and peak memory consumption data from our case study: [Hugging Face distilbert](https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english) model deployment on various devices and operating system versions. Below figures are non-interactive snapshots from the research article for iPhone 13 with iOS16.0 installed: | ||
|
||
<img src="assets/iPhone13_iOS16_latency_comparison.png"> | ||
|
||
<img src="assets/iPhone13_iOS16_memory_comparison.png"> | ||
|
||
## Tutorial: Optimized Deployment of Hugging Face distilbert | ||
|
||
This tutorial is a step-by-step guide to the model deployment process from the case study in our research article. The same code is used to generate the Hugging Face distilbert performance data in the figures above. | ||
|
||
In order to begin the optimizations, we initialize the baseline model as follows: | ||
|
||
```python | ||
import transformers | ||
model_name = "distilbert-base-uncased-finetuned-sst-2-english" | ||
baseline_model = transformers.AutoModelForSequenceClassification.from_pretrained( | ||
model_name, | ||
return_dict=False, | ||
torchscript=True, | ||
).eval() | ||
``` | ||
|
||
Then we initialize the mathematically equivalent but optimized model, and we restore its parameters using that of the baseline model: | ||
|
||
```python | ||
from ane_transformers.huggingface import distilbert as ane_distilbert | ||
optimized_model = ane_distilbert.DistilBertForSequenceClassification( | ||
baseline_model.config).eval() | ||
optimized_model.load_state_dict(baseline_model.state_dict()) | ||
``` | ||
|
||
Next we create sample inputs for the model: | ||
|
||
```python | ||
tokenizer = transformers.AutoTokenizer.from_pretrained(model_name) | ||
tokenized = tokenizer( | ||
["Sample input text to trace the model"], | ||
return_tensors="pt", | ||
max_length=128, # token sequence length | ||
padding="max_length", | ||
) | ||
``` | ||
|
||
We then trace the optimized model to obtain the expected input format (Torchscript) for the coremltools conversion tool. | ||
|
||
```python | ||
import torch | ||
traced_optimized_model = torch.jit.trace( | ||
optimized_model, | ||
(tokenized["input_ids"], tokenized["attention_mask"]) | ||
) | ||
``` | ||
|
||
Finally, we use coremltools to generate the Core ML model package file and save it. | ||
|
||
```python | ||
import coremltools as ct | ||
import numpy as np | ||
ane_mlpackage_obj = ct.convert( | ||
traced_optimized_model, | ||
convert_to="mlprogram", | ||
inputs=[ | ||
ct.TensorType( | ||
f"input_{name}", | ||
shape=tensor.shape, | ||
dtype=np.int32, | ||
) for name, tensor in tokenized.items() | ||
], | ||
compute_units=ct.ComputeUnit.ALL, | ||
) | ||
out_path = "HuggingFace_ane_transformers_distilbert_seqLen128_batchSize1.mlpackage" | ||
ane_mlpackage_obj.save(out_path) | ||
``` | ||
|
||
To verify performance, developers can now launch Xcode and simply add this model package file as a resource in their projects. After clicking on the Performance tab, the developer can generate a performance report on locally available devices, for example, on the Mac that is running Xcode or another Apple device that is connected to that Mac. The figure below shows a performance report generated for this model on an iPhone 13 Pro Max with iOS 16.0 installed. | ||
|
||
<img src="assets/xcode_performance_report_comparison.png"> | ||
|
||
|
||
Based on the figure above, the latency is improved by a factor of 2.84 times for the sequence length of 128 and batch size of 1 that were chosen for the tutorial. Higher sequence lengths, such as 512, and batch sizes, such as 8, will yield up to **10 times lower latency** and **14 times lower peak memory consumption**. Please refer to Figure 2 from our [research article](https://machinelearning.apple.com/research/apple-neural-engine) for detailed and interactive performance data. | ||
|
||
Note that the load and compilation times increase due to the number of operations increasing in the optimized model but these are one-time costs and user experience will not be affected if the model is loaded asynchronously. | ||
|
||
Note that 4 of the 606 operations in the optimized model are executed on the CPU. These are the embedding lookup related operations and they are more efficient to do on the CPU for this particular model configuration. | ||
|
||
## A Note on Unit Tests | ||
The unit tests measure, among other things, the ANE speed-up factor. Since the device spec for this reference implementation is M1 or newer chips for the Mac and A14 and newer chips for the iPhone and iPad, the speed-up unit tests will print a warning message if executed on devices outside of this spec. Even if the model is generated using an out of spec Mac, the model should work as expected on in-spec devices. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
from . import _version |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
__version__ = "0.1.0" |
Empty file.
Oops, something went wrong.