qicao-apple commited on
Commit
1900662
0 Parent(s):

add OpenELM

Browse files
Files changed (4) hide show
  1. .gitattributes +35 -0
  2. LICENSE +47 -0
  3. README.md +191 -0
  4. generate_openelm.py +240 -0
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (C) 2024 Apple Inc. All Rights Reserved.
2
+
3
+ Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple
4
+ Inc. ("Apple") in consideration of your agreement to the following
5
+ terms, and your use, installation, modification or redistribution of
6
+ this Apple software constitutes acceptance of these terms. If you do
7
+ not agree with these terms, please do not use, install, modify or
8
+ redistribute this Apple software.
9
+
10
+ In consideration of your agreement to abide by the following terms, and
11
+ subject to these terms, Apple grants you a personal, non-exclusive
12
+ license, under Apple's copyrights in this original Apple software (the
13
+ "Apple Software"), to use, reproduce, modify and redistribute the Apple
14
+ Software, with or without modifications, in source and/or binary forms;
15
+ provided that if you redistribute the Apple Software in its entirety and
16
+ without modifications, you must retain this notice and the following
17
+ text and disclaimers in all such redistributions of the Apple Software.
18
+ Neither the name, trademarks, service marks or logos of Apple Inc. may
19
+ be used to endorse or promote products derived from the Apple Software
20
+ without specific prior written permission from Apple. Except as
21
+ expressly stated in this notice, no other rights or licenses, express or
22
+ implied, are granted by Apple herein, including but not limited to any
23
+ patent rights that may be infringed by your derivative works or by other
24
+ works in which the Apple Software may be incorporated.
25
+
26
+ The Apple Software is provided by Apple on an "AS IS" basis. APPLE
27
+ MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
28
+ THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
29
+ FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
30
+ OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
31
+
32
+ IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
33
+ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
34
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
35
+ INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
36
+ MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
37
+ AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
38
+ STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
39
+ POSSIBILITY OF SUCH DAMAGE.
40
+
41
+
42
+ -------------------------------------------------------------------------------
43
+ SOFTWARE DISTRIBUTED IN THIS REPOSITORY:
44
+
45
+ This software includes a number of subcomponents with separate
46
+ copyright notices and license terms - please see the file ACKNOWLEDGEMENTS.
47
+ -------------------------------------------------------------------------------
README.md ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ license_name: apple-sample-code-license
4
+ license_link: LICENSE
5
+ ---
6
+
7
+ # OpenELM
8
+
9
+ *Sachin Mehta, Mohammad Hossein Sekhavat, Qingqing Cao, Maxwell Horton, Yanzi Jin, Chenfan Sun, Iman Mirzadeh, Mahyar Najibi, Dmitry Belenko, Peter Zatloukal, Mohammad Rastegari*
10
+
11
+ We introduce **OpenELM**, a family of **Open**-source **E**fficient **L**anguage **M**odels. OpenELM uses a layer-wise scaling strategy to efficiently allocate parameters within each layer of the transformer model, leading to enhanced accuracy. We pretrained OpenELM models using the [CoreNet](https://github.com/apple/corenet) library. We release both pretrained and instruction tuned models with 270M, 450M, 1.1B and 3B parameters.
12
+
13
+ Our pre-training dataset contains RefinedWeb, deduplicated PILE, a subset of RedPajama, and a subset of Dolma v1.6, totaling approximately 1.8 trillion tokens. Please check license agreements and terms of these datasets before using them.
14
+
15
+ See the list below for the details of each model:
16
+
17
+ - [OpenELM-270M](https://huggingface.co/apple/OpenELM-270M)
18
+ - [OpenELM-450M](https://huggingface.co/apple/OpenELM-450M)
19
+ - [OpenELM-1_1B](https://huggingface.co/apple/OpenELM-1_1B)
20
+ - [OpenELM-3B](https://huggingface.co/apple/OpenELM-3B)
21
+ - [OpenELM-270M-Instruct](https://huggingface.co/apple/OpenELM-270M-Instruct)
22
+ - [OpenELM-450M-Instruct](https://huggingface.co/apple/OpenELM-450M-Instruct)
23
+ - [OpenELM-1_1B-Instruct](https://huggingface.co/apple/OpenELM-1_1B-Instruct)
24
+ - [OpenELM-3B-Instruct](https://huggingface.co/apple/OpenELM-3B-Instruct)
25
+
26
+
27
+ ```python
28
+
29
+ from transformers import AutoModelForCausalLM
30
+
31
+ openelm_270m = AutoModelForCausalLM.from_pretrained("apple/OpenELM-270M", trust_remote_code=True)
32
+ openelm_450m = AutoModelForCausalLM.from_pretrained("apple/OpenELM-450M", trust_remote_code=True)
33
+ openelm_1b = AutoModelForCausalLM.from_pretrained("apple/OpenELM-1_1B", trust_remote_code=True)
34
+ openelm_3b = AutoModelForCausalLM.from_pretrained("apple/OpenELM-3B", trust_remote_code=True)
35
+
36
+ openelm_270m_instruct = AutoModelForCausalLM.from_pretrained("apple/OpenELM-270M-Instruct", trust_remote_code=True)
37
+ openelm_450m_instruct = AutoModelForCausalLM.from_pretrained("apple/OpenELM-450M-Instruct", trust_remote_code=True)
38
+ openelm_1b_instruct = AutoModelForCausalLM.from_pretrained("apple/OpenELM-1_1B-Instruct", trust_remote_code=True)
39
+ openelm_3b_instruct = AutoModelForCausalLM.from_pretrained("apple/OpenELM-3B-Instruct", trust_remote_code=True)
40
+
41
+ ```
42
+
43
+ ## Usage
44
+
45
+ We have provided an example function to generate output from OpenELM models loaded via [HuggingFace Hub](https://huggingface.co/docs/hub/) in `generate_openelm.py`.
46
+
47
+ You can try the model by running the following command:
48
+ ```
49
+ python generate_openelm.py --model [MODEL_NAME] --hf_access_token [HF_ACCESS_TOKEN] --prompt 'Once upon a time there was' --generate_kwargs repetition_penalty=1.2
50
+ ```
51
+ Please refer to [this link](https://huggingface.co/docs/hub/security-tokens) to obtain your hugging face access token.
52
+
53
+ Additional arguments to the hugging face generate function can be passed via `generate_kwargs`. As an example, to speedup the inference, you can try [lookup token speculative generation](https://huggingface.co/docs/transformers/generation_strategies) by passing the `prompt_lookup_num_tokens` argument as follows:
54
+ ```
55
+ python generate_openelm.py --model [MODEL_NAME] --hf_access_token [HF_ACCESS_TOKEN] --prompt 'Once upon a time there was' --generate_kwargs repetition_penalty=1.2 prompt_lookup_num_tokens=10
56
+ ```
57
+ Alternatively, try model-wise speculative generation with an [assistive model](https://huggingface.co/blog/assisted-generation) by passing a smaller model through the `assistant_model` argument, for example:
58
+ ```
59
+ python generate_openelm.py --model [MODEL_NAME] --hf_access_token [HF_ACCESS_TOKEN] --prompt 'Once upon a time there was' --generate_kwargs repetition_penalty=1.2 --assistant_model [SMALLER_MODEL_NAME]
60
+ ```
61
+
62
+
63
+ ## Main Results
64
+
65
+ ### Zero-Shot
66
+
67
+ | **Model Size** | **ARC-c** | **ARC-e** | **BoolQ** | **HellaSwag** | **PIQA** | **SciQ** | **WinoGrande** | **Average** |
68
+ |-----------------------------------------------------------------------------|-----------|-----------|-----------|---------------|-----------|-----------|----------------|-------------|
69
+ | [OpenELM-270M](https://huggingface.co/apple/OpenELM-270M) | 26.45 | 45.08 | **53.98** | 46.71 | 69.75 | **84.70** | **53.91** | 54.37 |
70
+ | [OpenELM-270M-Instruct](https://huggingface.co/apple/OpenELM-270M-Instruct) | **30.55** | **46.68** | 48.56 | **52.07** | **70.78** | 84.40 | 52.72 | **55.11** |
71
+ | [OpenELM-450M](https://huggingface.co/apple/OpenELM-450M) | 27.56 | 48.06 | 55.78 | 53.97 | 72.31 | 87.20 | 58.01 | 57.56 |
72
+ | [OpenELM-450M-Instruct](https://huggingface.co/apple/OpenELM-450M-Instruct) | **30.38** | **50.00** | **60.37** | **59.34** | **72.63** | **88.00** | **58.96** | **59.95** |
73
+ | [OpenELM-1_1B](https://huggingface.co/apple/OpenELM-1_1B) | 32.34 | **55.43** | 63.58 | 64.81 | **75.57** | **90.60** | 61.72 | 63.44 |
74
+ | [OpenELM-1_1B-Instruct](https://huggingface.co/apple/OpenELM-1_1B-Instruct) | **37.97** | 52.23 | **70.00** | **71.20** | 75.03 | 89.30 | **62.75** | **65.50** |
75
+ | [OpenELM-3B](https://huggingface.co/apple/OpenELM-3B) | 35.58 | 59.89 | 67.40 | 72.44 | 78.24 | **92.70** | 65.51 | 67.39 |
76
+ | [OpenELM-3B-Instruct](https://huggingface.co/apple/OpenELM-3B-Instruct) | **39.42** | **61.74** | **68.17** | **76.36** | **79.00** | 92.50 | **66.85** | **69.15** |
77
+
78
+ ### LLM360
79
+
80
+ | **Model Size** | **ARC-c** | **HellaSwag** | **MMLU** | **TruthfulQA** | **WinoGrande** | **Average** |
81
+ |-----------------------------------------------------------------------------|-----------|---------------|-----------|----------------|----------------|-------------|
82
+ | [OpenELM-270M](https://huggingface.co/apple/OpenELM-270M) | 27.65 | 47.15 | 25.72 | **39.24** | **53.83** | 38.72 |
83
+ | [OpenELM-270M-Instruct](https://huggingface.co/apple/OpenELM-270M-Instruct) | **32.51** | **51.58** | **26.70** | 38.72 | 53.20 | **40.54** |
84
+ | [OpenELM-450M](https://huggingface.co/apple/OpenELM-450M) | 30.20 | 53.86 | **26.01** | 40.18 | 57.22 | 41.50 |
85
+ | [OpenELM-450M-Instruct](https://huggingface.co/apple/OpenELM-450M-Instruct) | **33.53** | **59.31** | 25.41 | **40.48** | **58.33** | **43.41** |
86
+ | [OpenELM-1_1B](https://huggingface.co/apple/OpenELM-1_1B) | 36.69 | 65.71 | **27.05** | 36.98 | 63.22 | 45.93 |
87
+ | [OpenELM-1_1B-Instruct](https://huggingface.co/apple/OpenELM-1_1B-Instruct) | **41.55** | **71.83** | 25.65 | **45.95** | **64.72** | **49.94** |
88
+ | [OpenELM-3B](https://huggingface.co/apple/OpenELM-3B) | 42.24 | 73.28 | **26.76** | 34.98 | 67.25 | 48.90 |
89
+ | [OpenELM-3B-Instruct](https://huggingface.co/apple/OpenELM-3B-Instruct) | **47.70** | **76.87** | 24.80 | **38.76** | **67.96** | **51.22** |
90
+
91
+
92
+ ### OpenLLM Leaderboard
93
+
94
+ | **Model Size** | **ARC-c** | **CrowS-Pairs** | **HellaSwag** | **MMLU** | **PIQA** | **RACE** | **TruthfulQA** | **WinoGrande** | **Average** |
95
+ |-----------------------------------------------------------------------------|-----------|-----------------|---------------|-----------|-----------|-----------|----------------|----------------|-------------|
96
+ | [OpenELM-270M](https://huggingface.co/apple/OpenELM-270M) | 27.65 | **66.79** | 47.15 | 25.72 | 69.75 | 30.91 | **39.24** | **53.83** | 45.13 |
97
+ | [OpenELM-270M-Instruct](https://huggingface.co/apple/OpenELM-270M-Instruct) | **32.51** | 66.01 | **51.58** | **26.70** | **70.78** | 33.78 | 38.72 | 53.20 | **46.66** |
98
+ | [OpenELM-450M](https://huggingface.co/apple/OpenELM-450M) | 30.20 | **68.63** | 53.86 | **26.01** | 72.31 | 33.11 | 40.18 | 57.22 | 47.69 |
99
+ | [OpenELM-450M-Instruct](https://huggingface.co/apple/OpenELM-450M-Instruct) | **33.53** | 67.44 | **59.31** | 25.41 | **72.63** | **36.84** | **40.48** | **58.33** | **49.25** |
100
+ | [OpenELM-1_1B](https://huggingface.co/apple/OpenELM-1_1B) | 36.69 | **71.74** | 65.71 | **27.05** | **75.57** | 36.46 | 36.98 | 63.22 | 51.68 |
101
+ | [OpenELM-1_1B-Instruct](https://huggingface.co/apple/OpenELM-1_1B-Instruct) | **41.55** | 71.02 | **71.83** | 25.65 | 75.03 | **39.43** | **45.95** | **64.72** | **54.40** |
102
+ | [OpenELM-3B](https://huggingface.co/apple/OpenELM-3B) | 42.24 | **73.29** | 73.28 | **26.76** | 78.24 | **38.76** | 34.98 | 67.25 | 54.35 |
103
+ | [OpenELM-3B-Instruct](https://huggingface.co/apple/OpenELM-3B-Instruct) | **47.70** | 72.33 | **76.87** | 24.80 | **79.00** | 38.47 | **38.76** | **67.96** | **55.73** |
104
+
105
+ See the technical report for more results and comparison.
106
+
107
+ ## Evaluation
108
+
109
+ ### Setup
110
+
111
+ Install the following dependencies:
112
+
113
+ ```bash
114
+
115
+ # install public lm-eval-harness
116
+
117
+ harness_repo="public-lm-eval-harness"
118
+ git clone https://github.com/EleutherAI/lm-evaluation-harness ${harness_repo}
119
+ cd ${harness_repo}
120
+ # use main branch on 03-15-2024, SHA is dc90fec
121
+ git checkout dc90fec
122
+ pip install -e .
123
+ cd ..
124
+
125
+ # 66d6242 is the main branch on 2024-04-01
126
+ pip install datasets@git+https://github.com/huggingface/datasets.git@66d6242
127
+ pip install tokenizers>=0.15.2 transformers>=4.38.2 sentencepiece>=0.2.0
128
+
129
+ ```
130
+
131
+ ### Evaluate OpenELM
132
+
133
+ ```bash
134
+
135
+ # OpenELM-270M
136
+ hf_model=OpenELM-270M
137
+
138
+
139
+ # this flag is needed because lm-eval-harness set add_bos_token to False by default, but OpenELM uses LLaMA tokenizer which requires add_bos_token to be True
140
+ tokenizer=meta-llama/Llama-2-7b-hf
141
+ add_bos_token=True
142
+ batch_size=1
143
+
144
+ mkdir lm_eval_output
145
+
146
+ shot=0
147
+ task=arc_challenge,arc_easy,boolq,hellaswag,piqa,race,winogrande,sciq,truthfulqa_mc2
148
+ lm_eval --model hf \
149
+ --model_args pretrained=${hf_model},trust_remote_code=True,add_bos_token=${add_bos_token},tokenizer=${tokenizer} \
150
+ --tasks ${task} \
151
+ --device cuda:0 \
152
+ --num_fewshot ${shot} \
153
+ --output_path ./lm_eval_output/${hf_model//\//_}_${task//,/_}-${shot}shot \
154
+ --batch_size ${batch_size} 2>&1 | tee ./lm_eval_output/eval-${hf_model//\//_}_${task//,/_}-${shot}shot.log
155
+
156
+ shot=5
157
+ task=mmlu,winogrande
158
+ lm_eval --model hf \
159
+ --model_args pretrained=${hf_model},trust_remote_code=True,add_bos_token=${add_bos_token},tokenizer=${tokenizer} \
160
+ --tasks ${task} \
161
+ --device cuda:0 \
162
+ --num_fewshot ${shot} \
163
+ --output_path ./lm_eval_output/${hf_model//\//_}_${task//,/_}-${shot}shot \
164
+ --batch_size ${batch_size} 2>&1 | tee ./lm_eval_output/eval-${hf_model//\//_}_${task//,/_}-${shot}shot.log
165
+
166
+ shot=25
167
+ task=arc_challenge,crows_pairs_english
168
+ lm_eval --model hf \
169
+ --model_args pretrained=${hf_model},trust_remote_code=True,add_bos_token=${add_bos_token},tokenizer=${tokenizer} \
170
+ --tasks ${task} \
171
+ --device cuda:0 \
172
+ --num_fewshot ${shot} \
173
+ --output_path ./lm_eval_output/${hf_model//\//_}_${task//,/_}-${shot}shot \
174
+ --batch_size ${batch_size} 2>&1 | tee ./lm_eval_output/eval-${hf_model//\//_}_${task//,/_}-${shot}shot.log
175
+
176
+ shot=10
177
+ task=hellaswag
178
+ lm_eval --model hf \
179
+ --model_args pretrained=${hf_model},trust_remote_code=True,add_bos_token=${add_bos_token},tokenizer=${tokenizer} \
180
+ --tasks ${task} \
181
+ --device cuda:0 \
182
+ --num_fewshot ${shot} \
183
+ --output_path ./lm_eval_output/${hf_model//\//_}_${task//,/_}-${shot}shot \
184
+ --batch_size ${batch_size} 2>&1 | tee ./lm_eval_output/eval-${hf_model//\//_}_${task//,/_}-${shot}shot.log
185
+
186
+ ```
187
+
188
+
189
+ ## Bias, Risks, and Limitations
190
+
191
+ The release of OpenELM models aims to empower and enrich the open research community by providing access to state-of-the-art language models. Trained on publicly available datasets, these models are made available without any safety guarantees. Consequently, there exists the possibility of these models producing outputs that are inaccurate, harmful, biased, or objectionable in response to user prompts. Thus, it is imperative for users and developers to undertake thorough safety testing and implement appropriate filtering mechanisms tailored to their specific requirements.
generate_openelm.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # For licensing see accompanying LICENSE file.
3
+ # Copyright (C) 2024 Apple Inc. All Rights Reserved.
4
+ #
5
+
6
+ """Module to generate OpenELM output given a model and an input prompt."""
7
+ import os
8
+ import logging
9
+ import time
10
+ import argparse
11
+ from typing import Optional, Union
12
+ import torch
13
+
14
+ from transformers import AutoTokenizer, AutoModelForCausalLM
15
+
16
+
17
+ def generate(
18
+ prompt: str,
19
+ model: Union[str, AutoModelForCausalLM],
20
+ hf_access_token: str = None,
21
+ tokenizer: Union[str, AutoTokenizer] = 'meta-llama/Llama-2-7b-hf',
22
+ device: Optional[str] = None,
23
+ max_length: int = 1024,
24
+ assistant_model: Optional[Union[str, AutoModelForCausalLM]] = None,
25
+ generate_kwargs: Optional[dict] = None,
26
+ ) -> str:
27
+ """ Generates output given a prompt.
28
+
29
+ Args:
30
+ prompt: The string prompt.
31
+ model: The LLM Model. If a string is passed, it should be the path to
32
+ the hf converted checkpoint.
33
+ hf_access_token: Hugging face access token.
34
+ tokenizer: Tokenizer instance. If model is set as a string path,
35
+ the tokenizer will be loaded from the checkpoint.
36
+ device: String representation of device to run the model on. If None
37
+ and cuda available it would be set to cuda:0 else cpu.
38
+ max_length: Maximum length of tokens, input prompt + generated tokens.
39
+ assistant_model: If set, this model will be used for
40
+ speculative generation. If a string is passed, it should be the
41
+ path to the hf converted checkpoint.
42
+ generate_kwargs: Extra kwargs passed to the hf generate function.
43
+
44
+ Returns:
45
+ output_text: output generated as a string.
46
+ generation_time: generation time in seconds.
47
+
48
+ Raises:
49
+ ValueError: If device is set to CUDA but no CUDA device is detected.
50
+ ValueError: If tokenizer is not set.
51
+ ValueError: If hf_access_token is not specified.
52
+ """
53
+ if not device:
54
+ if torch.cuda.is_available() and torch.cuda.device_count():
55
+ device = "cuda:0"
56
+ logging.warning(
57
+ 'inference device is not set, using cuda:0, %s',
58
+ torch.cuda.get_device_name(0)
59
+ )
60
+ else:
61
+ device = 'cpu'
62
+ logging.warning(
63
+ (
64
+ 'No CUDA device detected, using cpu, '
65
+ 'expect slower speeds.'
66
+ )
67
+ )
68
+
69
+ if 'cuda' in device and not torch.cuda.is_available():
70
+ raise ValueError('CUDA device requested but no CUDA device detected.')
71
+
72
+ if not tokenizer:
73
+ raise ValueError('Tokenizer is not set in the generate function.')
74
+
75
+ if not hf_access_token:
76
+ raise ValueError((
77
+ 'Hugging face access token needs to be specified. '
78
+ 'Please refer to https://huggingface.co/docs/hub/security-tokens'
79
+ ' to obtain one.'
80
+ )
81
+ )
82
+
83
+ if isinstance(model, str):
84
+ checkpoint_path = model
85
+ model = AutoModelForCausalLM.from_pretrained(
86
+ checkpoint_path,
87
+ trust_remote_code=True
88
+ )
89
+ model.to(device).eval()
90
+ if isinstance(tokenizer, str):
91
+ tokenizer = AutoTokenizer.from_pretrained(
92
+ tokenizer,
93
+ token=hf_access_token,
94
+ )
95
+
96
+ # Speculative mode
97
+ draft_model = None
98
+ if assistant_model:
99
+ draft_model = assistant_model
100
+ if isinstance(assistant_model, str):
101
+ draft_model = AutoModelForCausalLM.from_pretrained(
102
+ assistant_model,
103
+ trust_remote_code=True
104
+ )
105
+ draft_model.to(device).eval()
106
+
107
+ # Prepare the prompt
108
+ tokenized_prompt = tokenizer(prompt)
109
+ tokenized_prompt = torch.tensor(
110
+ tokenized_prompt['input_ids'],
111
+ device=device
112
+ )
113
+
114
+ tokenized_prompt = tokenized_prompt.unsqueeze(0)
115
+
116
+ # Generate
117
+ stime = time.time()
118
+ output_ids = model.generate(
119
+ tokenized_prompt,
120
+ max_length=max_length,
121
+ pad_token_id=0,
122
+ assistant_model=draft_model,
123
+ **(generate_kwargs if generate_kwargs else {}),
124
+ )
125
+ generation_time = time.time() - stime
126
+
127
+ output_text = tokenizer.decode(
128
+ output_ids[0].tolist(),
129
+ skip_special_tokens=True
130
+ )
131
+
132
+ return output_text, generation_time
133
+
134
+
135
+ def openelm_generate_parser():
136
+ """Argument Parser"""
137
+
138
+ class KwargsParser(argparse.Action):
139
+ """Parser action class to parse kwargs of form key=value"""
140
+ def __call__(self, parser, namespace, values, option_string=None):
141
+ setattr(namespace, self.dest, dict())
142
+ for val in values:
143
+ if '=' not in val:
144
+ raise ValueError(
145
+ (
146
+ 'Argument parsing error, kwargs are expected in'
147
+ ' the form of key=value.'
148
+ )
149
+ )
150
+ kwarg_k, kwarg_v = val.split('=')
151
+ try:
152
+ converted_v = int(kwarg_v)
153
+ except ValueError:
154
+ try:
155
+ converted_v = float(kwarg_v)
156
+ except ValueError:
157
+ converted_v = kwarg_v
158
+ getattr(namespace, self.dest)[kwarg_k] = converted_v
159
+
160
+ parser = argparse.ArgumentParser('OpenELM Generate Module')
161
+ parser.add_argument(
162
+ '--model',
163
+ dest='model',
164
+ help='Path to the hf converted model.',
165
+ required=True,
166
+ type=str,
167
+ )
168
+ parser.add_argument(
169
+ '--hf_access_token',
170
+ dest='hf_access_token',
171
+ help='Hugging face access token, starting with "hf_".',
172
+ type=str,
173
+ )
174
+ parser.add_argument(
175
+ '--prompt',
176
+ dest='prompt',
177
+ help='Prompt for LLM call.',
178
+ default='',
179
+ type=str,
180
+ )
181
+ parser.add_argument(
182
+ '--device',
183
+ dest='device',
184
+ help='Device used for inference.',
185
+ type=str,
186
+ )
187
+ parser.add_argument(
188
+ '--max_length',
189
+ dest='max_length',
190
+ help='Maximum length of tokens.',
191
+ default=256,
192
+ type=int,
193
+ )
194
+ parser.add_argument(
195
+ '--assistant_model',
196
+ dest='assistant_model',
197
+ help=(
198
+ (
199
+ 'If set, this is used as a draft model '
200
+ 'for assisted speculative generation.'
201
+ )
202
+ ),
203
+ type=str,
204
+ )
205
+ parser.add_argument(
206
+ '--generate_kwargs',
207
+ dest='generate_kwargs',
208
+ help='Additional kwargs passed to the HF generate function.',
209
+ type=str,
210
+ nargs='*',
211
+ action=KwargsParser,
212
+ )
213
+ return parser.parse_args()
214
+
215
+
216
+ if __name__ == '__main__':
217
+ args = openelm_generate_parser()
218
+ prompt = args.prompt
219
+
220
+ output_text, genertaion_time = generate(
221
+ prompt=prompt,
222
+ model=args.model,
223
+ device=args.device,
224
+ max_length=args.max_length,
225
+ assistant_model=args.assistant_model,
226
+ generate_kwargs=args.generate_kwargs,
227
+ hf_access_token=args.hf_access_token,
228
+ )
229
+
230
+ print_txt = (
231
+ f'\r\n{"=" * os.get_terminal_size().columns}\r\n'
232
+ '\033[1m Prompt + Generated Output\033[0m\r\n'
233
+ f'{"-" * os.get_terminal_size().columns}\r\n'
234
+ f'{output_text}\r\n'
235
+ f'{"-" * os.get_terminal_size().columns}\r\n'
236
+ '\r\nGeneration took'
237
+ f'\033[1m\033[92m {round(genertaion_time, 2)} \033[0m'
238
+ 'seconds.\r\n'
239
+ )
240
+ print(print_txt)