mllmTeam commited on
Commit
f8fe721
1 Parent(s): 9214e3a

Upload folder using huggingface_hub

Browse files
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ PhoneLM-0.5B-Instruct is a 0.5 billion parameter decoder-only language model.
2
+
3
+ ## Usage
4
+ ```python
5
+ from transformers import AutoTokenizer, AutoModelForCausalLM
6
+
7
+ model_name = 'mllmTeam/PhoneLM-0.5B-Instruct'
8
+ question = "Hello, who are you?"
9
+ prompt = [{"role": "user", "content": question}]
10
+
11
+ model = AutoModelForCausalLM.from_pretrained(model_name, device_map='cuda', trust_remote_code=True)
12
+
13
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
14
+ input_text = tokenizer.apply_chat_template(prompt, tokenize=False, add_generation_prompt=True)
15
+
16
+ inp = tokenizer(input_text, return_tensors="pt")
17
+ inp = {k: v.to('cuda') for k, v in inp.items()}
18
+ out = model.generate(**inp,
19
+ max_length=256,
20
+ do_sample=True,
21
+ temperature=0.7,
22
+ top_p=0.7
23
+ )
24
+ text = tokenizer.decode(out[0], skip_special_tokens=True)
25
+ print(text)
26
+ ```
27
+
28
+
29
+ ## Model Details
30
+
31
+ * **Developed by**: mllmTeam
32
+ * **Model type**: `PhoneLM 0.5B` models are auto-regressive language models based on the transformer decoder architecture.
33
+ * **Language(s)**: English
34
+ * **Paper**: [PhoneLM Technical Report]()
35
+ * **Library**: [PhoneLM](https://github.com/UbiquitousLearning/PhoneLM)
36
+
37
+ ### Model Architecture
38
+
39
+ The model is a decoder-only transformer architecture with the following modifications:
40
+
41
+ | Hidden Size | Layers | Heads | Sequence Length |
42
+ |-------------|--------|-------|-----------------|
43
+ | 1024 | 24 | 16 | 2048 |
44
+
45
+ * **Position Embeddings**: Rotary Position Embeddings ([Su et al., 2021](https://arxiv.org/abs/2104.09864)) applied to the first 25% of head embedding dimensions for improved throughput following [Black et al. (2022)](https://arxiv.org/pdf/2204.06745.pdf). PhoneLM quantized the sin and cos values in Rotary Position Embeddings to 8-bit integers.
46
+ * **Normalization**: LayerNorm ([Ba et al., 2016](https://arxiv.org/abs/1607.06450)) with learned bias terms as opposed to RMSNorm ([Zhang & Sennrich, 2019](https://arxiv.org/abs/1910.07467)).
47
+ * **Biases**: We remove all bias terms from the feed-forward networks and multi-head self-attention layers, except for the biases of the query, key, and value projections ([Bai et al., 2023](https://arxiv.org/abs/2309.16609)).
48
+ * **ReLU Activation Function**: ReLU([Glorot et al., 2011](https://proceedings.mlr.press/v15/glorot11a/glorot11a.pdf)) activation functions are adopted in feed-forward networks.
49
+ * **Tokenizer**: We use the SmolLM([Allal et al., 2024](https://huggingface.co/blog/smollm))'s tokenizer with a vocabulary size of 49,152.
50
+
51
+ ## LICENSE
52
+ * This repository is released under the [Apache-2.0](https://huggingface.co/mllmTeam/PhoneLM-0.5B-Instruct/blob/main/LICENSE) License.
config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "./",
3
+ "architectures": [
4
+ "PhoneLMForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_phonelm.PhoneLMConfig",
10
+ "AutoModelForCausalLM": "modeling_phonelm.PhoneLMForCausalLM"
11
+ },
12
+ "bos_token_id": 1,
13
+ "eos_token_id": 2,
14
+ "hidden_act": "relu",
15
+ "hidden_size": 2560,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 6816,
18
+ "max_position_embeddings": 2048,
19
+ "model_type": "phonelm",
20
+ "num_attention_heads": 16,
21
+ "num_hidden_layers": 19,
22
+ "num_key_value_heads": 16,
23
+ "pretraining_tp": 1,
24
+ "rms_norm_eps": 1e-06,
25
+ "rope_scaling": null,
26
+ "rope_theta": 10000.0,
27
+ "tie_word_embeddings": true,
28
+ "torch_dtype": "bfloat16",
29
+ "transformers_version": "4.42.4",
30
+ "use_cache": true,
31
+ "vocab_size": 49152
32
+ }
configuration_phonelm.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 mllmTeam and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on mllmTeam's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PhoneLM model configuration"""
21
+
22
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.utils import logging
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ class PhoneLMConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`PhoneLMModel`]. It is used to instantiate an PhoneLM
30
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
31
+ defaults will yield a similar configuration to that of the PhoneLM-7B.
32
+
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PretrainedConfig`] for more information.
35
+
36
+
37
+ Args:
38
+ vocab_size (`int`, *optional*, defaults to 32000):
39
+ Vocabulary size of the PhoneLM model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`PhoneLMModel`]
41
+ hidden_size (`int`, *optional*, defaults to 4096):
42
+ Dimension of the hidden representations.
43
+ intermediate_size (`int`, *optional*, defaults to 11008):
44
+ Dimension of the MLP representations.
45
+ num_hidden_layers (`int`, *optional*, defaults to 32):
46
+ Number of hidden layers in the Transformer decoder.
47
+ num_attention_heads (`int`, *optional*, defaults to 32):
48
+ Number of attention heads for each attention layer in the Transformer decoder.
49
+ num_key_value_heads (`int`, *optional*):
50
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
51
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
52
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
53
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
54
+ by meanpooling all the original heads within that group. For more details checkout [this
55
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
56
+ `num_attention_heads`.
57
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
58
+ The non-linear activation function (function or string) in the decoder.
59
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
60
+ The maximum sequence length that this model might ever be used with. PhoneLM 1 supports up to 2048 tokens,
61
+ PhoneLM 2 up to 4096, CodePhoneLM up to 16384.
62
+ initializer_range (`float`, *optional*, defaults to 0.02):
63
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
64
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
65
+ The epsilon used by the rms normalization layers.
66
+ use_cache (`bool`, *optional*, defaults to `True`):
67
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
68
+ relevant if `config.is_decoder=True`.
69
+ pad_token_id (`int`, *optional*):
70
+ Padding token id.
71
+ bos_token_id (`int`, *optional*, defaults to 1):
72
+ Beginning of stream token id.
73
+ eos_token_id (`int`, *optional*, defaults to 2):
74
+ End of stream token id.
75
+ pretraining_tp (`int`, *optional*, defaults to 1):
76
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
77
+ document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to understand more about it. This value is
78
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
79
+ issue](https://github.com/pytorch/pytorch/issues/76232).
80
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
81
+ Whether to tie weight embeddings
82
+ rope_theta (`float`, *optional*, defaults to 10000.0):
83
+ The base period of the RoPE embeddings.
84
+ rope_scaling (`Dict`, *optional*):
85
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
86
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
87
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
88
+ `max_position_embeddings` to the expected new maximum. This is an
89
+ experimental feature, subject to breaking API changes in future versions.
90
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
91
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
92
+ attention_dropout (`float`, *optional*, defaults to 0.0):
93
+ The dropout ratio for the attention probabilities.
94
+
95
+ ```python
96
+ >>> from transformers import PhoneLMModel, PhoneLMConfig
97
+
98
+ >>> # Initializing a PhoneLM style configuration
99
+ >>> configuration = PhoneLMConfig()
100
+
101
+ >>> # Initializing a model from the PhoneLM style configuration
102
+ >>> model = PhoneLMModel(configuration)
103
+
104
+ >>> # Accessing the model configuration
105
+ >>> configuration = model.config
106
+ ```"""
107
+
108
+ model_type = "phonelm"
109
+ keys_to_ignore_at_inference = ["past_key_values"]
110
+
111
+ def __init__(
112
+ self,
113
+ vocab_size=32000,
114
+ hidden_size=4096,
115
+ intermediate_size=11008,
116
+ num_hidden_layers=32,
117
+ num_attention_heads=32,
118
+ num_key_value_heads=None,
119
+ hidden_act="silu",
120
+ max_position_embeddings=2048,
121
+ initializer_range=0.02,
122
+ rms_norm_eps=1e-6,
123
+ use_cache=True,
124
+ pad_token_id=None,
125
+ bos_token_id=1,
126
+ eos_token_id=2,
127
+ pretraining_tp=1,
128
+ tie_word_embeddings=False,
129
+ rope_theta=10000.0,
130
+ rope_scaling=None,
131
+ attention_bias=False,
132
+ attention_dropout=0.0,
133
+ **kwargs,
134
+ ):
135
+ self.vocab_size = vocab_size
136
+ self.max_position_embeddings = max_position_embeddings
137
+ self.hidden_size = hidden_size
138
+ self.intermediate_size = intermediate_size
139
+ self.num_hidden_layers = num_hidden_layers
140
+ self.num_attention_heads = num_attention_heads
141
+
142
+ # for backward compatibility
143
+ if num_key_value_heads is None:
144
+ num_key_value_heads = num_attention_heads
145
+
146
+ self.num_key_value_heads = num_key_value_heads
147
+ self.hidden_act = hidden_act
148
+ self.initializer_range = initializer_range
149
+ self.rms_norm_eps = rms_norm_eps
150
+ self.pretraining_tp = pretraining_tp
151
+ self.use_cache = use_cache
152
+ self.rope_theta = rope_theta
153
+ self.rope_scaling = rope_scaling
154
+ self._rope_scaling_validation()
155
+ self.attention_bias = attention_bias
156
+ self.attention_dropout = attention_dropout
157
+ super().__init__(
158
+ pad_token_id=pad_token_id,
159
+ bos_token_id=bos_token_id,
160
+ eos_token_id=eos_token_id,
161
+ tie_word_embeddings=tie_word_embeddings,
162
+ **kwargs,
163
+ )
164
+
165
+ def _rope_scaling_validation(self):
166
+ """
167
+ Validate the `rope_scaling` configuration.
168
+ """
169
+ if self.rope_scaling is None:
170
+ return
171
+
172
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
173
+ raise ValueError(
174
+ "`rope_scaling` must be a dictionary with two fields, `type` and `factor`, " f"got {self.rope_scaling}"
175
+ )
176
+ rope_scaling_type = self.rope_scaling.get("type", None)
177
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
178
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
179
+ raise ValueError(
180
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
181
+ )
182
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
183
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "transformers_version": "4.42.4"
6
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:19a52b2374a1bb577ea45c7cf8feec615d1c03455cf48675a376b02e05f255db
3
+ size 3237206528
modeling_phonelm.py ADDED
@@ -0,0 +1,1629 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 mllmTeam and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on mllmTeam's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """PyTorch PhoneLM model."""
21
+
22
+ import math
23
+ import warnings
24
+ from typing import List, Optional, Tuple, Union
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+ import torch.utils.checkpoint
29
+ from torch import nn
30
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
31
+
32
+ from transformers.activations import ACT2FN
33
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
34
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
35
+ from transformers.modeling_outputs import (
36
+ BaseModelOutputWithPast,
37
+ CausalLMOutputWithPast,
38
+ QuestionAnsweringModelOutput,
39
+ SequenceClassifierOutputWithPast,
40
+ )
41
+ from transformers.modeling_utils import PreTrainedModel
42
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
43
+ from transformers.utils import (
44
+ add_start_docstrings,
45
+ add_start_docstrings_to_model_forward,
46
+ is_flash_attn_2_available,
47
+ is_flash_attn_greater_or_equal_2_10,
48
+ logging,
49
+ replace_return_docstrings,
50
+ )
51
+ from configuration_phonelm import PhoneLMConfig
52
+
53
+ if is_flash_attn_2_available():
54
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
55
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
56
+
57
+
58
+
59
+ from transformers.pytorch_utils import (
60
+ ALL_LAYERNORM_LAYERS,
61
+ is_torch_greater_or_equal_than_1_13,
62
+ )
63
+
64
+ from transformers.modeling_attn_mask_utils import (
65
+ AttentionMaskConverter,
66
+ _prepare_4d_attention_mask,
67
+ _prepare_4d_causal_attention_mask,
68
+ )
69
+ from transformers.utils.import_utils import is_torch_fx_available
70
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
71
+ # It means that the function will not be traced through and simply appear as a node in the graph.
72
+ if is_torch_fx_available():
73
+ if not is_torch_greater_or_equal_than_1_13:
74
+ import torch.fx
75
+
76
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
77
+
78
+
79
+ logger = logging.get_logger(__name__)
80
+
81
+ _CONFIG_FOR_DOC = "PhoneLMConfig"
82
+
83
+
84
+ def _get_unpad_data(attention_mask):
85
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
86
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
87
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
88
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
89
+ return (
90
+ indices,
91
+ cu_seqlens,
92
+ max_seqlen_in_batch,
93
+ )
94
+
95
+
96
+ class PhoneLMRMSNorm(nn.Module):
97
+ def __init__(self, hidden_size, eps=1e-6):
98
+ """
99
+ PhoneLMRMSNorm is equivalent to T5LayerNorm
100
+ """
101
+ super().__init__()
102
+ self.weight = nn.Parameter(torch.ones(hidden_size))
103
+ self.variance_epsilon = eps
104
+
105
+ def forward(self, hidden_states):
106
+ input_dtype = hidden_states.dtype
107
+ hidden_states = hidden_states.to(torch.float32)
108
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
109
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
110
+ return self.weight * hidden_states.to(input_dtype)
111
+
112
+
113
+ ALL_LAYERNORM_LAYERS.append(PhoneLMRMSNorm)
114
+
115
+
116
+
117
+
118
+ class PhoneLMRotaryEmbedding(nn.Module):
119
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
120
+ super().__init__()
121
+ self.scaling_factor = scaling_factor
122
+ self.dim = dim
123
+ self.max_position_embeddings = max_position_embeddings
124
+ self.base = base
125
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
126
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
127
+ # For BC we register cos and sin cached
128
+ self.max_seq_len_cached = max_position_embeddings
129
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
130
+ t = t / self.scaling_factor
131
+ freqs = torch.outer(t, self.inv_freq)
132
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
133
+ emb = torch.cat((freqs, freqs), dim=-1)
134
+ self.register_buffer("_cos_cached", emb.cos().to(torch.get_default_dtype()), persistent=False)
135
+ self.register_buffer("_sin_cached", emb.sin().to(torch.get_default_dtype()), persistent=False)
136
+
137
+ @property
138
+ def sin_cached(self):
139
+ logger.warning_once(
140
+ "The sin_cached attribute will be removed in 4.39. Bear in mind that its contents changed in v4.38. Use "
141
+ "the forward method of RoPE from now on instead. It is not used in the `PhoneLMAttention` class"
142
+ )
143
+ return self._sin_cached
144
+
145
+ @property
146
+ def cos_cached(self):
147
+ logger.warning_once(
148
+ "The cos_cached attribute will be removed in 4.39. Bear in mind that its contents changed in v4.38. Use "
149
+ "the forward method of RoPE from now on instead. It is not used in the `PhoneLMAttention` class"
150
+ )
151
+ return self._cos_cached
152
+
153
+ @torch.no_grad()
154
+ def forward(self, x, position_ids):
155
+ # x: [bs, num_attention_heads, seq_len, head_size]
156
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
157
+ position_ids_expanded = position_ids[:, None, :].float()
158
+ # Force float32 since bfloat16 loses precision on long contexts
159
+ # See https://github.com/huggingface/transformers/pull/29285
160
+ device_type = x.device.type
161
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
162
+ with torch.autocast(device_type=device_type, enabled=False):
163
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
164
+ emb = torch.cat((freqs, freqs), dim=-1)
165
+ cos = emb.cos()
166
+ sin = emb.sin()
167
+ cos_max = cos.abs().max()
168
+ sin_max = sin.abs().max()
169
+ cos_quant = (cos / cos_max * 127).round().to(torch.int8)
170
+ sin_quant = (sin / sin_max * 127).round().to(torch.int8)
171
+ return cos_quant, sin_quant, cos_max, sin_max
172
+
173
+
174
+ class PhoneLMLinearScalingRotaryEmbedding(PhoneLMRotaryEmbedding):
175
+ """PhoneLMRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
176
+
177
+ def forward(self, x, position_ids):
178
+ # difference to the original RoPE: a scaling factor is aplied to the position ids
179
+ position_ids = position_ids.float() / self.scaling_factor
180
+ cos, sin = super().forward(x, position_ids)
181
+ # return cos, sin
182
+ cos_max = cos.abs().max()
183
+ sin_max = sin.abs().max()
184
+ cos_quant = (cos / cos_max * 127).round().to(torch.int8)
185
+ sin_quant = (sin / sin_max * 127).round().to(torch.int8)
186
+ return cos_quant, sin_quant, cos_max, sin_max
187
+
188
+
189
+ class PhoneLMDynamicNTKScalingRotaryEmbedding(PhoneLMRotaryEmbedding):
190
+ """PhoneLMRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
191
+
192
+ def forward(self, x, position_ids):
193
+ # difference to the original RoPE: inv_freq is recomputed when the sequence length > original length
194
+ seq_len = torch.max(position_ids) + 1
195
+ if seq_len > self.max_position_embeddings:
196
+ base = self.base * (
197
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
198
+ ) ** (self.dim / (self.dim - 2))
199
+ inv_freq = 1.0 / (
200
+ base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(x.device) / self.dim)
201
+ )
202
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: this may break with compilation
203
+
204
+ cos, sin = super().forward(x, position_ids)
205
+ cos_max = cos.abs().max()
206
+ sin_max = sin.abs().max()
207
+ cos_quant = (cos / cos_max * 127).round().to(torch.int8)
208
+ sin_quant = (sin / sin_max * 127).round().to(torch.int8)
209
+ return cos_quant, sin_quant, cos_max, sin_max
210
+
211
+
212
+ def rotate_half(x):
213
+ """Rotates half the hidden dims of the input."""
214
+ x1 = x[..., : x.shape[-1] // 2]
215
+ x2 = x[..., x.shape[-1] // 2 :]
216
+ return torch.cat((-x2, x1), dim=-1)
217
+
218
+ def apply_rotary_pos_emb_i8(q, k, cos_quant, sin_quant, cos_max, sin_max, position_ids=None, unsqueeze_dim=1):
219
+ """Applies Rotary Position Embedding to the query and key tensors, using quantized INT8 representations for cos and sin."""
220
+ o_dtype = q.dtype
221
+ cos = cos_quant.float() / 127 * cos_max
222
+ sin = sin_quant.float() / 127 * sin_max
223
+ cos = cos.unsqueeze(unsqueeze_dim)
224
+ sin = sin.unsqueeze(unsqueeze_dim)
225
+ q_embed = (q * cos) + (rotate_half(q) * sin)
226
+ k_embed = (k * cos) + (rotate_half(k) * sin)
227
+ q_embed = q_embed.to(o_dtype)
228
+ k_embed = k_embed.to(o_dtype)
229
+ return q_embed, k_embed
230
+
231
+
232
+
233
+ class PhoneLMMLP(nn.Module):
234
+ def __init__(self, config, layer_idx: Optional[int] = None):
235
+ super().__init__()
236
+ self.config = config
237
+ self.hidden_size = config.hidden_size
238
+ self.intermediate_size = config.intermediate_size
239
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
240
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
241
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
242
+ self.act_fn = ACT2FN[config.hidden_act]
243
+
244
+ def forward(self, x):
245
+ if self.config.pretraining_tp > 1:
246
+ slice = self.intermediate_size // self.config.pretraining_tp
247
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
248
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
249
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
250
+
251
+ gate_proj = torch.cat(
252
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
253
+ )
254
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
255
+
256
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
257
+ down_proj = [
258
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
259
+ ]
260
+ down_proj = sum(down_proj)
261
+ else:
262
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
263
+
264
+ return down_proj
265
+
266
+
267
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
268
+ """
269
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
270
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
271
+ """
272
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
273
+ if n_rep == 1:
274
+ return hidden_states
275
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
276
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
277
+
278
+
279
+ class PhoneLMAttention(nn.Module):
280
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
281
+
282
+ def __init__(self, config: PhoneLMConfig, layer_idx: Optional[int] = None):
283
+ super().__init__()
284
+ self.config = config
285
+ self.layer_idx = layer_idx
286
+ if layer_idx is None:
287
+ logger.warning_once(
288
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
289
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
290
+ "when creating this class."
291
+ )
292
+
293
+ self.attention_dropout = config.attention_dropout
294
+ self.hidden_size = config.hidden_size
295
+ self.num_heads = config.num_attention_heads
296
+ self.head_dim = self.hidden_size // self.num_heads
297
+ self.num_key_value_heads = config.num_key_value_heads
298
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
299
+ self.max_position_embeddings = config.max_position_embeddings
300
+ self.rope_theta = config.rope_theta
301
+ self.is_causal = True
302
+
303
+ if (self.head_dim * self.num_heads) != self.hidden_size:
304
+ raise ValueError(
305
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
306
+ f" and `num_heads`: {self.num_heads})."
307
+ )
308
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
309
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
310
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
311
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
312
+ self._init_rope()
313
+
314
+ def _init_rope(self):
315
+ if self.config.rope_scaling is None:
316
+ self.rotary_emb = PhoneLMRotaryEmbedding(
317
+ self.head_dim,
318
+ max_position_embeddings=self.max_position_embeddings,
319
+ base=self.rope_theta,
320
+ )
321
+ else:
322
+ scaling_type = self.config.rope_scaling["type"]
323
+ scaling_factor = self.config.rope_scaling["factor"]
324
+ if scaling_type == "linear":
325
+ self.rotary_emb = PhoneLMLinearScalingRotaryEmbedding(
326
+ self.head_dim,
327
+ max_position_embeddings=self.max_position_embeddings,
328
+ scaling_factor=scaling_factor,
329
+ base=self.rope_theta,
330
+ )
331
+ elif scaling_type == "dynamic":
332
+ self.rotary_emb = PhoneLMDynamicNTKScalingRotaryEmbedding(
333
+ self.head_dim,
334
+ max_position_embeddings=self.max_position_embeddings,
335
+ scaling_factor=scaling_factor,
336
+ base=self.rope_theta,
337
+ )
338
+ else:
339
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
340
+
341
+ def forward(
342
+ self,
343
+ hidden_states: torch.Tensor,
344
+ attention_mask: Optional[torch.Tensor] = None,
345
+ position_ids: Optional[torch.LongTensor] = None,
346
+ past_key_value: Optional[Cache] = None,
347
+ output_attentions: bool = False,
348
+ use_cache: bool = False,
349
+ cache_position: Optional[torch.LongTensor] = None,
350
+ **kwargs,
351
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
352
+ bsz, q_len, _ = hidden_states.size()
353
+
354
+ if self.config.pretraining_tp > 1:
355
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
356
+ query_slices = self.q_proj.weight.split(
357
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
358
+ )
359
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
360
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
361
+
362
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
363
+ query_states = torch.cat(query_states, dim=-1)
364
+
365
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
366
+ key_states = torch.cat(key_states, dim=-1)
367
+
368
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
369
+ value_states = torch.cat(value_states, dim=-1)
370
+
371
+ else:
372
+ query_states = self.q_proj(hidden_states )
373
+ key_states = self.k_proj(hidden_states )
374
+ value_states = self.v_proj(hidden_states )
375
+
376
+ query_states = query_states.view(bsz, q_len, self.num_heads, int(self.head_dim)).transpose(1, 2)
377
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, int(self.head_dim)).transpose(1, 2)
378
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, int(self.head_dim)).transpose(1, 2)
379
+
380
+ past_key_value = getattr(self, "past_key_value", past_key_value)
381
+ cos, sin, cos_max, sin_max = self.rotary_emb(value_states, position_ids)
382
+ query_states, key_states = apply_rotary_pos_emb_i8(query_states, key_states, cos, sin, cos_max, sin_max)
383
+
384
+ if past_key_value is not None:
385
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
386
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
387
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
388
+
389
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
390
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
391
+
392
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
393
+
394
+ if attention_mask is not None: # no matter the length, we just slice it
395
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
396
+ attn_weights = attn_weights + causal_mask
397
+
398
+ # upcast attention to fp32
399
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
400
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
401
+ attn_output = torch.matmul(attn_weights, value_states)
402
+
403
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
404
+ raise ValueError(
405
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
406
+ f" {attn_output.size()}"
407
+ )
408
+
409
+ attn_output = attn_output.transpose(1, 2).contiguous()
410
+
411
+ attn_output = attn_output.reshape(bsz, q_len, int(self.hidden_size))
412
+
413
+ if self.config.pretraining_tp > 1:
414
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
415
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
416
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
417
+ else:
418
+ attn_output = self.o_proj(attn_output)
419
+
420
+ if not output_attentions:
421
+ attn_weights = None
422
+
423
+ return attn_output, attn_weights, past_key_value
424
+
425
+
426
+ class PhoneLMFlashAttention2(PhoneLMAttention):
427
+ """
428
+ PhoneLM flash attention module. This module inherits from `PhoneLMAttention` as the weights of the module stays
429
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
430
+ flash attention and deal with padding tokens in case the input contains any of them.
431
+ """
432
+
433
+ def __init__(self, *args, **kwargs):
434
+ super().__init__(*args, **kwargs)
435
+
436
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
437
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
438
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
439
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
440
+
441
+ def forward(
442
+ self,
443
+ hidden_states: torch.Tensor,
444
+ attention_mask: Optional[torch.LongTensor] = None,
445
+ position_ids: Optional[torch.LongTensor] = None,
446
+ past_key_value: Optional[Cache] = None,
447
+ output_attentions: bool = False,
448
+ use_cache: bool = False,
449
+ cache_position: Optional[torch.LongTensor] = None,
450
+ **kwargs,
451
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
452
+ output_attentions = False
453
+
454
+ bsz, q_len, _ = hidden_states.size()
455
+
456
+ query_states = self.q_proj(hidden_states)
457
+ key_states = self.k_proj(hidden_states)
458
+ value_states = self.v_proj(hidden_states)
459
+
460
+ # Flash attention requires the input to have the shape
461
+ # batch_size x seq_length x head_dim x hidden_dim
462
+ # therefore we just need to keep the original shape
463
+ query_states = query_states.view(bsz, q_len, self.num_heads, int(self.head_dim)).transpose(1, 2)
464
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, int(self.head_dim)).transpose(1, 2)
465
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, int(self.head_dim)).transpose(1, 2)
466
+
467
+ cos, sin, cos_max, sin_max = self.rotary_emb(value_states, position_ids)
468
+ query_states, key_states = apply_rotary_pos_emb_i8(query_states, key_states, cos, sin, cos_max, sin_max)
469
+
470
+ past_key_value = getattr(self, "past_key_value", past_key_value)
471
+
472
+ if past_key_value is not None:
473
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
474
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
475
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
476
+
477
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
478
+ # to be able to avoid many of these transpose/reshape/view.
479
+ query_states = query_states.transpose(1, 2)
480
+ key_states = key_states.transpose(1, 2)
481
+ value_states = value_states.transpose(1, 2)
482
+
483
+ dropout_rate = self.attention_dropout if self.training else 0.0
484
+
485
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
486
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
487
+ # cast them back in the correct dtype just to be sure everything works as expected.
488
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
489
+ # in fp32. (PhoneLMRMSNorm handles it correctly)
490
+
491
+ input_dtype = query_states.dtype
492
+ if input_dtype == torch.float32:
493
+ if torch.is_autocast_enabled():
494
+ target_dtype = torch.get_autocast_gpu_dtype()
495
+ # Handle the case where the model is quantized
496
+ elif hasattr(self.config, "_pre_quantization_dtype"):
497
+ target_dtype = self.config._pre_quantization_dtype
498
+ else:
499
+ target_dtype = self.q_proj.weight.dtype
500
+
501
+ logger.warning_once(
502
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
503
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
504
+ f" {target_dtype}."
505
+ )
506
+
507
+ query_states = query_states.to(target_dtype)
508
+ key_states = key_states.to(target_dtype)
509
+ value_states = value_states.to(target_dtype)
510
+
511
+ attn_output = self._flash_attention_forward(
512
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
513
+ )
514
+
515
+ attn_output = attn_output.reshape(bsz, q_len, int(self.hidden_size)).contiguous()
516
+ attn_output = self.o_proj(attn_output)
517
+
518
+ if not output_attentions:
519
+ attn_weights = None
520
+
521
+ return attn_output, attn_weights, past_key_value
522
+
523
+ def _flash_attention_forward(
524
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
525
+ ):
526
+ """
527
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
528
+ first unpad the input, then computes the attention scores and pad the final attention scores.
529
+
530
+ Args:
531
+ query_states (`torch.Tensor`):
532
+ Input query states to be passed to Flash Attention API
533
+ key_states (`torch.Tensor`):
534
+ Input key states to be passed to Flash Attention API
535
+ value_states (`torch.Tensor`):
536
+ Input value states to be passed to Flash Attention API
537
+ attention_mask (`torch.Tensor`):
538
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
539
+ position of padding tokens and 1 for the position of non-padding tokens.
540
+ dropout (`float`):
541
+ Attention dropout
542
+ softmax_scale (`float`, *optional*):
543
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
544
+ """
545
+ if not self._flash_attn_uses_top_left_mask:
546
+ causal = self.is_causal
547
+ else:
548
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in PhoneLMFlashAttention2 __init__.
549
+ causal = self.is_causal and query_length != 1
550
+
551
+ # Contains at least one padding token in the sequence
552
+ if attention_mask is not None:
553
+ batch_size = query_states.shape[0]
554
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
555
+ query_states, key_states, value_states, attention_mask, query_length
556
+ )
557
+
558
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
559
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
560
+
561
+ attn_output_unpad = flash_attn_varlen_func(
562
+ query_states,
563
+ key_states,
564
+ value_states,
565
+ cu_seqlens_q=cu_seqlens_q,
566
+ cu_seqlens_k=cu_seqlens_k,
567
+ max_seqlen_q=max_seqlen_in_batch_q,
568
+ max_seqlen_k=max_seqlen_in_batch_k,
569
+ dropout_p=dropout,
570
+ softmax_scale=softmax_scale,
571
+ causal=causal,
572
+ )
573
+
574
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
575
+ else:
576
+ attn_output = flash_attn_func(
577
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
578
+ )
579
+
580
+ return attn_output
581
+
582
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
583
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
584
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
585
+
586
+ key_layer = index_first_axis(
587
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
588
+ )
589
+ value_layer = index_first_axis(
590
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
591
+ )
592
+ if query_length == kv_seq_len:
593
+ query_layer = index_first_axis(
594
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
595
+ )
596
+ cu_seqlens_q = cu_seqlens_k
597
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
598
+ indices_q = indices_k
599
+ elif query_length == 1:
600
+ max_seqlen_in_batch_q = 1
601
+ cu_seqlens_q = torch.arange(
602
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
603
+ ) # There is a memcpy here, that is very bad.
604
+ indices_q = cu_seqlens_q[:-1]
605
+ query_layer = query_layer.squeeze(1)
606
+ else:
607
+ # The -q_len: slice assumes left padding.
608
+ attention_mask = attention_mask[:, -query_length:]
609
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
610
+
611
+ return (
612
+ query_layer,
613
+ key_layer,
614
+ value_layer,
615
+ indices_q,
616
+ (cu_seqlens_q, cu_seqlens_k),
617
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
618
+ )
619
+
620
+
621
+ class PhoneLMSdpaAttention(PhoneLMAttention):
622
+ """
623
+ PhoneLM attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
624
+ `PhoneLMAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
625
+ SDPA API.
626
+ """
627
+
628
+ # Adapted from PhoneLMAttention.forward
629
+ def forward(
630
+ self,
631
+ hidden_states: torch.Tensor,
632
+ attention_mask: Optional[torch.Tensor] = None,
633
+ position_ids: Optional[torch.LongTensor] = None,
634
+ past_key_value: Optional[Cache] = None,
635
+ output_attentions: bool = False,
636
+ use_cache: bool = False,
637
+ cache_position: Optional[torch.LongTensor] = None,
638
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
639
+ if output_attentions:
640
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
641
+ logger.warning_once(
642
+ "PhoneLMModel is using PhoneLMSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
643
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
644
+ )
645
+ return super().forward(
646
+ hidden_states=hidden_states,
647
+ attention_mask=attention_mask,
648
+ position_ids=position_ids,
649
+ past_key_value=past_key_value,
650
+ output_attentions=output_attentions,
651
+ use_cache=use_cache,
652
+ cache_position=cache_position,
653
+ )
654
+
655
+ bsz, q_len, _ = hidden_states.size()
656
+
657
+ query_states = self.q_proj(hidden_states)
658
+ key_states = self.k_proj(hidden_states)
659
+ value_states = self.v_proj(hidden_states)
660
+
661
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
662
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
663
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
664
+
665
+ cos, sin, cos_max, sin_max = self.rotary_emb(value_states, position_ids)
666
+ query_states, key_states = apply_rotary_pos_emb_i8(query_states, key_states, cos, sin, cos_max, sin_max)
667
+
668
+ # In case static cache is used, it is an instance attribute.
669
+ past_key_value = getattr(self, "past_key_value", past_key_value)
670
+
671
+ if past_key_value is not None:
672
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
673
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
674
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
675
+
676
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
677
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
678
+
679
+ causal_mask = attention_mask
680
+ if attention_mask is not None:
681
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
682
+
683
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
684
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
685
+ if query_states.device.type == "cuda" and causal_mask is not None:
686
+ query_states = query_states.contiguous()
687
+ key_states = key_states.contiguous()
688
+ value_states = value_states.contiguous()
689
+
690
+ # In case we are not compiling, we may set `causal_mask` to None, which is required to dispatch to SDPA's Flash Attention 2 backend, rather
691
+ # relying on the `is_causal` argument.
692
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
693
+ query_states,
694
+ key_states,
695
+ value_states,
696
+ attn_mask=causal_mask,
697
+ dropout_p=self.attention_dropout if self.training else 0.0,
698
+ is_causal=causal_mask is None and q_len > 1,
699
+ )
700
+
701
+ attn_output = attn_output.transpose(1, 2).contiguous()
702
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
703
+
704
+ attn_output = self.o_proj(attn_output)
705
+
706
+ return attn_output, None, past_key_value
707
+
708
+
709
+ PhoneLM_ATTENTION_CLASSES = {
710
+ "eager": PhoneLMAttention,
711
+ "flash_attention_2": PhoneLMFlashAttention2,
712
+ "sdpa": PhoneLMSdpaAttention,
713
+ }
714
+
715
+ class PhoneLMDecoderLayer(nn.Module):
716
+ def __init__(self, config: PhoneLMConfig, layer_idx: int):
717
+ super().__init__()
718
+ self.hidden_size = config.hidden_size
719
+
720
+ self.self_attn = PhoneLM_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
721
+
722
+
723
+ self.mlp = PhoneLMMLP(config=config, layer_idx=layer_idx)
724
+
725
+ self.input_layernorm = PhoneLMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
726
+ self.post_attention_layernorm = PhoneLMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
727
+
728
+ def forward(
729
+ self,
730
+ hidden_states: torch.Tensor,
731
+ attention_mask: Optional[torch.Tensor] = None,
732
+ position_ids: Optional[torch.LongTensor] = None,
733
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
734
+ output_attentions: Optional[bool] = False,
735
+ use_cache: Optional[bool] = False,
736
+ cache_position: Optional[torch.LongTensor] = None,
737
+ **kwargs,
738
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
739
+ """
740
+ Args:
741
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
742
+ attention_mask (`torch.FloatTensor`, *optional*):
743
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
744
+ query_sequence_length, key_sequence_length)` if default attention is used.
745
+ output_attentions (`bool`, *optional*):
746
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
747
+ returned tensors for more detail.
748
+ use_cache (`bool`, *optional*):
749
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
750
+ (see `past_key_values`).
751
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
752
+ """
753
+ if "padding_mask" in kwargs:
754
+ warnings.warn(
755
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
756
+ )
757
+
758
+ residual = hidden_states
759
+
760
+ hidden_states = self.input_layernorm(hidden_states)
761
+
762
+ # Self Attention
763
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
764
+ hidden_states=hidden_states,
765
+ attention_mask=attention_mask,
766
+ position_ids=position_ids,
767
+ past_key_value=past_key_value,
768
+ output_attentions=output_attentions,
769
+ use_cache=use_cache,
770
+ cache_position=cache_position,
771
+ **kwargs,
772
+ )
773
+ hidden_states = residual + hidden_states
774
+
775
+ # Fully Connected
776
+ residual = hidden_states
777
+ hidden_states = self.post_attention_layernorm(hidden_states)
778
+ hidden_states = self.mlp(hidden_states)
779
+ hidden_states = residual + hidden_states
780
+
781
+ outputs = (hidden_states,)
782
+
783
+ if output_attentions:
784
+ outputs += (self_attn_weights,)
785
+
786
+ if use_cache:
787
+ outputs += (present_key_value,)
788
+
789
+ return outputs
790
+
791
+
792
+ PhoneLM_START_DOCSTRING = r"""
793
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
794
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
795
+ etc.)
796
+
797
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
798
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
799
+ and behavior.
800
+
801
+ Parameters:
802
+ config ([`PhoneLMConfig`]):
803
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
804
+ load the weights associated with the model, only the configuration. Check out the
805
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
806
+ """
807
+
808
+
809
+ @add_start_docstrings(
810
+ "The bare PhoneLM Model outputting raw hidden-states without any specific head on top.",
811
+ PhoneLM_START_DOCSTRING,
812
+ )
813
+ class PhoneLMPreTrainedModel(PreTrainedModel):
814
+ config_class = PhoneLMConfig
815
+ base_model_prefix = "model"
816
+ supports_gradient_checkpointing = True
817
+ _no_split_modules = ["PhoneLMDecoderLayer"]
818
+ _skip_keys_device_placement = ["past_key_values"]
819
+ _supports_flash_attn_2 = True
820
+ _supports_sdpa = True
821
+ _supports_cache_class = True
822
+
823
+ def _init_weights(self, module):
824
+ std = self.config.initializer_range
825
+ if isinstance(module, nn.Linear):
826
+ module.weight.data.normal_(mean=0.0, std=std)
827
+ if module.bias is not None:
828
+ module.bias.data.zero_()
829
+ elif isinstance(module, nn.Embedding):
830
+ module.weight.data.normal_(mean=0.0, std=std)
831
+ if module.padding_idx is not None:
832
+ module.weight.data[module.padding_idx].zero_()
833
+
834
+ def _setup_cache(self, cache_cls, max_batch_size, max_cache_len: Optional[int] = None):
835
+ if self.config._attn_implementation == "flash_attention_2" and cache_cls == StaticCache:
836
+ raise ValueError(
837
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
838
+ "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
839
+ )
840
+
841
+ for layer in self.model.layers:
842
+ device = layer.input_layernorm.weight.device
843
+ if hasattr(self.config, "_pre_quantization_dtype"):
844
+ dtype = self.config._pre_quantization_dtype
845
+ else:
846
+ dtype = layer.self_attn.o_proj.weight.dtype
847
+ layer.self_attn.past_key_value = cache_cls(
848
+ self.config, max_batch_size, max_cache_len, device=device, dtype=dtype
849
+ )
850
+
851
+ def _reset_cache(self):
852
+ for layer in self.model.layers:
853
+ layer.self_attn.past_key_value = None
854
+
855
+
856
+ PhoneLM_INPUTS_DOCSTRING = r"""
857
+ Args:
858
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
859
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
860
+ it.
861
+
862
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
863
+ [`PreTrainedTokenizer.__call__`] for details.
864
+
865
+ [What are input IDs?](../glossary#input-ids)
866
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
867
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
868
+
869
+ - 1 for tokens that are **not masked**,
870
+ - 0 for tokens that are **masked**.
871
+
872
+ [What are attention masks?](../glossary#attention-mask)
873
+
874
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
875
+ [`PreTrainedTokenizer.__call__`] for details.
876
+
877
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
878
+ `past_key_values`).
879
+
880
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
881
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
882
+ information on the default strategy.
883
+
884
+ - 1 indicates the head is **not masked**,
885
+ - 0 indicates the head is **masked**.
886
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
887
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
888
+ config.n_positions - 1]`.
889
+
890
+ [What are position IDs?](../glossary#position-ids)
891
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
892
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
893
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
894
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
895
+
896
+ Two formats are allowed:
897
+ - a [`~cache_utils.Cache`] instance;
898
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
899
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
900
+ cache format.
901
+
902
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
903
+ legacy cache format will be returned.
904
+
905
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
906
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
907
+ of shape `(batch_size, sequence_length)`.
908
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
909
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
910
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
911
+ model's internal embedding lookup matrix.
912
+ use_cache (`bool`, *optional*):
913
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
914
+ `past_key_values`).
915
+ output_attentions (`bool`, *optional*):
916
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
917
+ tensors for more detail.
918
+ output_hidden_states (`bool`, *optional*):
919
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
920
+ more detail.
921
+ return_dict (`bool`, *optional*):
922
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
923
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
924
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
925
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
926
+ the complete sequence length.
927
+ """
928
+
929
+
930
+ @add_start_docstrings(
931
+ "The bare PhoneLM Model outputting raw hidden-states without any specific head on top.",
932
+ PhoneLM_START_DOCSTRING,
933
+ )
934
+ class PhoneLMModel(PhoneLMPreTrainedModel):
935
+ """
936
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PhoneLMDecoderLayer`]
937
+
938
+ Args:
939
+ config: PhoneLMConfig
940
+ """
941
+
942
+ def __init__(self, config: PhoneLMConfig):
943
+ super().__init__(config)
944
+ self.padding_idx = config.pad_token_id
945
+ self.vocab_size = config.vocab_size
946
+
947
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
948
+ self.norm = PhoneLMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
949
+ self.layers = nn.ModuleList(
950
+ [PhoneLMDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
951
+ )
952
+ self.gradient_checkpointing = False
953
+
954
+ # Initialize weights and apply final processing
955
+ self.post_init()
956
+
957
+ def get_input_embeddings(self):
958
+ return self.embed_tokens
959
+
960
+ def set_input_embeddings(self, value):
961
+ self.embed_tokens = value
962
+
963
+ @add_start_docstrings_to_model_forward(PhoneLM_INPUTS_DOCSTRING)
964
+ def forward(
965
+ self,
966
+ input_ids: torch.LongTensor = None,
967
+ attention_mask: Optional[torch.Tensor] = None,
968
+ position_ids: Optional[torch.LongTensor] = None,
969
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
970
+ inputs_embeds: Optional[torch.FloatTensor] = None,
971
+ use_cache: Optional[bool] = None,
972
+ output_attentions: Optional[bool] = None,
973
+ output_hidden_states: Optional[bool] = None,
974
+ return_dict: Optional[bool] = None,
975
+ cache_position: Optional[torch.LongTensor] = None,
976
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
977
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
978
+ output_hidden_states = (
979
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
980
+ )
981
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
982
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
983
+
984
+ if (input_ids is None) ^ (inputs_embeds is not None):
985
+ raise ValueError(
986
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
987
+ )
988
+
989
+ if self.gradient_checkpointing and self.training and use_cache:
990
+ logger.warning_once(
991
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
992
+ )
993
+ use_cache = False
994
+
995
+ # retrieve input_ids and inputs_embeds
996
+ if input_ids is not None and inputs_embeds is not None:
997
+ raise ValueError(
998
+ "You cannot specify both input_ids and inputs_embeds at the same time"
999
+ )
1000
+ elif input_ids is not None:
1001
+ batch_size, seq_length = input_ids.shape[:2]
1002
+ elif inputs_embeds is not None:
1003
+ batch_size, seq_length = inputs_embeds.shape[:2]
1004
+ else:
1005
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1006
+
1007
+ if inputs_embeds is None:
1008
+ inputs_embeds = self.embed_tokens(input_ids)
1009
+
1010
+ past_seen_tokens = 0
1011
+ past_key_values_length = 0
1012
+ if use_cache: # kept for BC (cache positions)
1013
+ if not isinstance(past_key_values, StaticCache):
1014
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1015
+ past_seen_tokens = past_key_values.get_seq_length()
1016
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1017
+
1018
+ if cache_position is None:
1019
+ if isinstance(past_key_values, StaticCache):
1020
+ raise ValueError("cache_position is a required argument when using StaticCache.")
1021
+ cache_position = torch.arange(
1022
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1023
+ )
1024
+
1025
+ if position_ids is None:
1026
+ position_ids = cache_position.unsqueeze(0)
1027
+
1028
+ causal_mask = self._update_causal_mask(attention_mask, inputs_embeds, cache_position, past_seen_tokens)
1029
+
1030
+ # embed positions
1031
+ hidden_states = inputs_embeds
1032
+
1033
+ # decoder layers
1034
+ all_hidden_states = () if output_hidden_states else None
1035
+ all_self_attns = () if output_attentions else None
1036
+ next_decoder_cache = None
1037
+
1038
+ for i, decoder_layer in enumerate(self.layers):
1039
+
1040
+ if output_hidden_states:
1041
+ all_hidden_states += (hidden_states,)
1042
+
1043
+ if self.gradient_checkpointing and self.training:
1044
+ layer_outputs = self._gradient_checkpointing_func(
1045
+ decoder_layer.__call__,
1046
+ hidden_states,
1047
+ causal_mask,
1048
+ position_ids,
1049
+ past_key_values,
1050
+ output_attentions,
1051
+ use_cache,
1052
+ cache_position,
1053
+ )
1054
+ else:
1055
+ layer_outputs = decoder_layer(
1056
+ hidden_states,
1057
+ attention_mask=causal_mask,
1058
+ position_ids=position_ids,
1059
+ past_key_value=past_key_values,
1060
+ output_attentions=output_attentions,
1061
+ use_cache=use_cache,
1062
+ cache_position=cache_position,
1063
+ )
1064
+
1065
+ hidden_states = layer_outputs[0]
1066
+
1067
+ if use_cache:
1068
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1069
+
1070
+ if output_attentions:
1071
+ all_self_attns += (layer_outputs[1],)
1072
+
1073
+ hidden_states = self.norm(hidden_states)
1074
+
1075
+ # add hidden states from the last decoder layer
1076
+ if output_hidden_states:
1077
+ all_hidden_states += (hidden_states,)
1078
+
1079
+ next_cache = None
1080
+ if use_cache:
1081
+ next_cache = (
1082
+ next_decoder_cache.to_legacy_cache() if isinstance(next_decoder_cache, Cache) else next_decoder_cache
1083
+ )
1084
+ if not return_dict:
1085
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1086
+ return BaseModelOutputWithPast(
1087
+ last_hidden_state=hidden_states,
1088
+ past_key_values=next_cache,
1089
+ hidden_states=all_hidden_states,
1090
+ attentions=all_self_attns,
1091
+ )
1092
+
1093
+ def _update_causak_mask_mla(
1094
+ self,
1095
+ attention_mask: torch.Tensor,
1096
+ batch_size: int,
1097
+ seq_length: int,
1098
+ inputs_embeds,
1099
+ past_key_values_length
1100
+ ):
1101
+ if self.config._attn_implementation == "flash_attention_2":
1102
+ # 2d mask is passed through the layers
1103
+ attention_mask = (
1104
+ attention_mask
1105
+ if (attention_mask is not None and 0 in attention_mask)
1106
+ else None
1107
+ )
1108
+ else:
1109
+ # 4d mask is passed through the layers
1110
+ attention_mask = _prepare_4d_causal_attention_mask(
1111
+ attention_mask,
1112
+ (batch_size, seq_length),
1113
+ inputs_embeds,
1114
+ past_key_values_length,
1115
+ )
1116
+ return attention_mask
1117
+
1118
+ def _update_causal_mask(
1119
+ self,
1120
+ attention_mask: torch.Tensor,
1121
+ input_tensor: torch.Tensor,
1122
+ cache_position: torch.Tensor,
1123
+ past_seen_tokens: int,
1124
+ ):
1125
+ # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
1126
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
1127
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
1128
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
1129
+
1130
+ if self.config._attn_implementation == "flash_attention_2":
1131
+ if attention_mask is not None and 0.0 in attention_mask:
1132
+ return attention_mask
1133
+ return None
1134
+
1135
+ if self.config._attn_implementation == "sdpa":
1136
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument,
1137
+ # in order to dispatch on Flash Attention 2.
1138
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1139
+ attention_mask, inputs_embeds=input_tensor, past_key_values_length=past_seen_tokens
1140
+ ):
1141
+ return None
1142
+
1143
+ dtype, device = input_tensor.dtype, input_tensor.device
1144
+ min_dtype = torch.finfo(dtype).min
1145
+ sequence_length = input_tensor.shape[1]
1146
+ if hasattr(getattr(self.layers[0], "self_attn", {}), "past_key_value"): # static cache
1147
+ target_length = self.config.max_position_embeddings
1148
+ else: # dynamic cache
1149
+ target_length = (
1150
+ attention_mask.shape[-1]
1151
+ if isinstance(attention_mask, torch.Tensor)
1152
+ else past_seen_tokens + sequence_length + 1
1153
+ )
1154
+
1155
+ causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
1156
+ if sequence_length != 1:
1157
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1158
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1159
+ causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
1160
+ if attention_mask is not None:
1161
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1162
+ if attention_mask.dim() == 2:
1163
+ mask_length = attention_mask.shape[-1]
1164
+ padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[:, None, None, :].eq(0.0)
1165
+ causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(padding_mask, min_dtype)
1166
+ elif attention_mask.dim() == 4:
1167
+ # backwards compatibility: we allow passing a 4D attention mask shorter than the input length with
1168
+ # cache. In that case, the 4D attention mask attends to the newest tokens only.
1169
+ if attention_mask.shape[-2] < cache_position[0] + sequence_length:
1170
+ offset = cache_position[0]
1171
+ else:
1172
+ offset = 0
1173
+ mask_shape = attention_mask.shape
1174
+ mask_slice = (attention_mask.eq(0.0)).to(dtype=dtype) * min_dtype
1175
+ causal_mask[
1176
+ : mask_shape[0], : mask_shape[1], offset : mask_shape[2] + offset, : mask_shape[3]
1177
+ ] = mask_slice
1178
+
1179
+ if (
1180
+ self.config._attn_implementation == "sdpa"
1181
+ and attention_mask is not None
1182
+ and attention_mask.device.type == "cuda"
1183
+ ):
1184
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1185
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1186
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1187
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1188
+
1189
+ return causal_mask
1190
+
1191
+
1192
+ class PhoneLMForCausalLM(PhoneLMPreTrainedModel):
1193
+ _tied_weights_keys = ["lm_head.weight"]
1194
+
1195
+ def __init__(self, config):
1196
+ super().__init__(config)
1197
+ self.model = PhoneLMModel(config)
1198
+ self.vocab_size = config.vocab_size
1199
+
1200
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1201
+
1202
+ # Initialize weights and apply final processing
1203
+ self.post_init()
1204
+
1205
+ def get_input_embeddings(self):
1206
+ return self.model.embed_tokens
1207
+
1208
+ def set_input_embeddings(self, value):
1209
+ self.model.embed_tokens = value
1210
+
1211
+ def get_output_embeddings(self):
1212
+ return self.lm_head
1213
+
1214
+ def set_output_embeddings(self, new_embeddings):
1215
+ self.lm_head = new_embeddings
1216
+
1217
+ def set_decoder(self, decoder):
1218
+ self.model = decoder
1219
+
1220
+ def get_decoder(self):
1221
+ return self.model
1222
+
1223
+ @add_start_docstrings_to_model_forward(PhoneLM_INPUTS_DOCSTRING)
1224
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1225
+ def forward(
1226
+ self,
1227
+ input_ids: torch.LongTensor = None,
1228
+ attention_mask: Optional[torch.Tensor] = None,
1229
+ position_ids: Optional[torch.LongTensor] = None,
1230
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1231
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1232
+ labels: Optional[torch.LongTensor] = None,
1233
+ use_cache: Optional[bool] = None,
1234
+ output_attentions: Optional[bool] = None,
1235
+ output_hidden_states: Optional[bool] = None,
1236
+ return_dict: Optional[bool] = None,
1237
+ cache_position: Optional[torch.LongTensor] = None,
1238
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1239
+ r"""
1240
+ Args:
1241
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1242
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1243
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1244
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1245
+
1246
+ Returns:
1247
+
1248
+ Example:
1249
+
1250
+ ```python
1251
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
1252
+
1253
+ >>> model = AutoModelForCausalLM.from_pretrained("mllmTeam/PhoneLM-1.5B")
1254
+ >>> tokenizer = AutoTokenizer.from_pretrained("mllmTeam/PhoneLM-1.5B", trust_remote_code=True)
1255
+
1256
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1257
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1258
+
1259
+ >>> # Generate
1260
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1261
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1262
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1263
+ ```"""
1264
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1265
+ output_hidden_states = (
1266
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1267
+ )
1268
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1269
+
1270
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1271
+ outputs = self.model(
1272
+ input_ids=input_ids,
1273
+ attention_mask=attention_mask,
1274
+ position_ids=position_ids,
1275
+ past_key_values=past_key_values,
1276
+ inputs_embeds=inputs_embeds,
1277
+ use_cache=use_cache,
1278
+ output_attentions=output_attentions,
1279
+ output_hidden_states=output_hidden_states,
1280
+ return_dict=return_dict,
1281
+ cache_position=cache_position,
1282
+ )
1283
+
1284
+ hidden_states = outputs[0]
1285
+ if self.config.pretraining_tp > 1:
1286
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1287
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1288
+ logits = torch.cat(logits, dim=-1)
1289
+ else:
1290
+ logits = self.lm_head(hidden_states)
1291
+ # logits = logits.float()
1292
+
1293
+ loss = None
1294
+ if labels is not None:
1295
+ # Shift so that tokens < n predict n
1296
+ shift_logits = logits[..., :-1, :].contiguous()
1297
+ shift_labels = labels[..., 1:].contiguous()
1298
+ # Flatten the tokens
1299
+ loss_fct = CrossEntropyLoss()
1300
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1301
+ shift_labels = shift_labels.view(-1)
1302
+ # Enable model parallelism
1303
+ shift_labels = shift_labels.to(shift_logits.device)
1304
+ loss = loss_fct(shift_logits, shift_labels)
1305
+
1306
+ if not return_dict:
1307
+ output = (logits,) + outputs[1:]
1308
+ return (loss,) + output if loss is not None else output
1309
+
1310
+ return CausalLMOutputWithPast(
1311
+ loss=loss,
1312
+ logits=logits,
1313
+ past_key_values=outputs.past_key_values,
1314
+ hidden_states=outputs.hidden_states,
1315
+ attentions=outputs.attentions,
1316
+ )
1317
+
1318
+ def prepare_inputs_for_generation(
1319
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, cache_position=None, **kwargs
1320
+ ):
1321
+ # With static cache, the `past_key_values` is None
1322
+ # TODO joao: standardize interface for the different Cache classes and remove of this if
1323
+ has_static_cache = False
1324
+ if past_key_values is None:
1325
+ past_key_values = getattr(getattr(self.model.layers[0], "self_attn", {}), "past_key_value", None)
1326
+ has_static_cache = past_key_values is not None
1327
+
1328
+ past_length = 0
1329
+ if past_key_values is not None:
1330
+ if isinstance(past_key_values, Cache):
1331
+ past_length = cache_position[0] if cache_position is not None else past_key_values.get_seq_length()
1332
+ max_cache_length = (
1333
+ torch.tensor(past_key_values.get_max_length(), device=input_ids.device)
1334
+ if past_key_values.get_max_length() is not None
1335
+ else None
1336
+ )
1337
+ cache_length = past_length if max_cache_length is None else torch.min(max_cache_length, past_length)
1338
+ # TODO joao: remove this `else` after `generate` prioritizes `Cache` objects
1339
+ else:
1340
+ cache_length = past_length = past_key_values[0][0].shape[2]
1341
+ max_cache_length = None
1342
+
1343
+ # Keep only the unprocessed tokens:
1344
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1345
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1346
+ # input)
1347
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1348
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1349
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1350
+ # input_ids based on the past_length.
1351
+ elif past_length < input_ids.shape[1]:
1352
+ input_ids = input_ids[:, past_length:]
1353
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1354
+
1355
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1356
+ if (
1357
+ max_cache_length is not None
1358
+ and attention_mask is not None
1359
+ and cache_length + input_ids.shape[1] > max_cache_length
1360
+ ):
1361
+ attention_mask = attention_mask[:, -max_cache_length:]
1362
+
1363
+ position_ids = kwargs.get("position_ids", None)
1364
+ if attention_mask is not None and position_ids is None:
1365
+ # create position_ids on the fly for batch generation
1366
+ position_ids = attention_mask.long().cumsum(-1) - 1
1367
+ position_ids.masked_fill_(attention_mask == 0, 1)
1368
+ if past_key_values:
1369
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1370
+
1371
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1372
+ if inputs_embeds is not None and past_key_values is None:
1373
+ model_inputs = {"inputs_embeds": inputs_embeds}
1374
+ else:
1375
+ # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
1376
+ # recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
1377
+ # TODO: use `next_tokens` directly instead.
1378
+ model_inputs = {"input_ids": input_ids.contiguous()}
1379
+
1380
+ input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
1381
+ if cache_position is None:
1382
+ cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device)
1383
+ else:
1384
+ cache_position = cache_position[-input_length:]
1385
+
1386
+ if has_static_cache:
1387
+ past_key_values = None
1388
+
1389
+ model_inputs.update(
1390
+ {
1391
+ "position_ids": position_ids,
1392
+ "cache_position": cache_position,
1393
+ "past_key_values": past_key_values,
1394
+ "use_cache": kwargs.get("use_cache"),
1395
+ "attention_mask": attention_mask,
1396
+ }
1397
+ )
1398
+ return model_inputs
1399
+
1400
+ @staticmethod
1401
+ def _reorder_cache(past_key_values, beam_idx):
1402
+ reordered_past = ()
1403
+ for layer_past in past_key_values:
1404
+ reordered_past += (
1405
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1406
+ )
1407
+ return reordered_past
1408
+
1409
+
1410
+ @add_start_docstrings(
1411
+ """
1412
+ The PhoneLM Model transformer with a sequence classification head on top (linear layer).
1413
+
1414
+ [`PhoneLMForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1415
+ (e.g. GPT-2) do.
1416
+
1417
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1418
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1419
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1420
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1421
+ each row of the batch).
1422
+ """,
1423
+ PhoneLM_START_DOCSTRING,
1424
+ )
1425
+ class PhoneLMForSequenceClassification(PhoneLMPreTrainedModel):
1426
+ def __init__(self, config):
1427
+ super().__init__(config)
1428
+ self.num_labels = config.num_labels
1429
+ self.model = PhoneLMModel(config)
1430
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1431
+
1432
+ # Initialize weights and apply final processing
1433
+ self.post_init()
1434
+
1435
+ def get_input_embeddings(self):
1436
+ return self.model.embed_tokens
1437
+
1438
+ def set_input_embeddings(self, value):
1439
+ self.model.embed_tokens = value
1440
+
1441
+ @add_start_docstrings_to_model_forward(PhoneLM_INPUTS_DOCSTRING)
1442
+ def forward(
1443
+ self,
1444
+ input_ids: torch.LongTensor = None,
1445
+ attention_mask: Optional[torch.Tensor] = None,
1446
+ position_ids: Optional[torch.LongTensor] = None,
1447
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1448
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1449
+ labels: Optional[torch.LongTensor] = None,
1450
+ use_cache: Optional[bool] = None,
1451
+ output_attentions: Optional[bool] = None,
1452
+ output_hidden_states: Optional[bool] = None,
1453
+ return_dict: Optional[bool] = None,
1454
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1455
+ r"""
1456
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1457
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1458
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1459
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1460
+ """
1461
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1462
+
1463
+ transformer_outputs = self.model(
1464
+ input_ids,
1465
+ attention_mask=attention_mask,
1466
+ position_ids=position_ids,
1467
+ past_key_values=past_key_values,
1468
+ inputs_embeds=inputs_embeds,
1469
+ use_cache=use_cache,
1470
+ output_attentions=output_attentions,
1471
+ output_hidden_states=output_hidden_states,
1472
+ return_dict=return_dict,
1473
+ )
1474
+ hidden_states = transformer_outputs[0]
1475
+ logits = self.score(hidden_states)
1476
+
1477
+ if input_ids is not None:
1478
+ batch_size = input_ids.shape[0]
1479
+ else:
1480
+ batch_size = inputs_embeds.shape[0]
1481
+
1482
+ if self.config.pad_token_id is None and batch_size != 1:
1483
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1484
+ if self.config.pad_token_id is None:
1485
+ sequence_lengths = -1
1486
+ else:
1487
+ if input_ids is not None:
1488
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1489
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1490
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1491
+ sequence_lengths = sequence_lengths.to(logits.device)
1492
+ else:
1493
+ sequence_lengths = -1
1494
+
1495
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1496
+
1497
+ loss = None
1498
+ if labels is not None:
1499
+ labels = labels.to(logits.device)
1500
+ if self.config.problem_type is None:
1501
+ if self.num_labels == 1:
1502
+ self.config.problem_type = "regression"
1503
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1504
+ self.config.problem_type = "single_label_classification"
1505
+ else:
1506
+ self.config.problem_type = "multi_label_classification"
1507
+
1508
+ if self.config.problem_type == "regression":
1509
+ loss_fct = MSELoss()
1510
+ if self.num_labels == 1:
1511
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1512
+ else:
1513
+ loss = loss_fct(pooled_logits, labels)
1514
+ elif self.config.problem_type == "single_label_classification":
1515
+ loss_fct = CrossEntropyLoss()
1516
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1517
+ elif self.config.problem_type == "multi_label_classification":
1518
+ loss_fct = BCEWithLogitsLoss()
1519
+ loss = loss_fct(pooled_logits, labels)
1520
+ if not return_dict:
1521
+ output = (pooled_logits,) + transformer_outputs[1:]
1522
+ return ((loss,) + output) if loss is not None else output
1523
+
1524
+ return SequenceClassifierOutputWithPast(
1525
+ loss=loss,
1526
+ logits=pooled_logits,
1527
+ past_key_values=transformer_outputs.past_key_values,
1528
+ hidden_states=transformer_outputs.hidden_states,
1529
+ attentions=transformer_outputs.attentions,
1530
+ )
1531
+
1532
+
1533
+ @add_start_docstrings(
1534
+ """
1535
+ The PhoneLM Model transformer with a span classification head on top for extractive question-answering tasks like
1536
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1537
+ """,
1538
+ PhoneLM_START_DOCSTRING,
1539
+ )
1540
+ class PhoneLMForQuestionAnswering(PhoneLMPreTrainedModel):
1541
+ base_model_prefix = "transformer"
1542
+
1543
+ # Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->PhoneLM
1544
+ def __init__(self, config):
1545
+ super().__init__(config)
1546
+ self.transformer = PhoneLMModel(config)
1547
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1548
+
1549
+ # Initialize weights and apply final processing
1550
+ self.post_init()
1551
+
1552
+ def get_input_embeddings(self):
1553
+ return self.transformer.embed_tokens
1554
+
1555
+ def set_input_embeddings(self, value):
1556
+ self.transformer.embed_tokens = value
1557
+
1558
+ @add_start_docstrings_to_model_forward(PhoneLM_INPUTS_DOCSTRING)
1559
+ def forward(
1560
+ self,
1561
+ input_ids: Optional[torch.LongTensor] = None,
1562
+ attention_mask: Optional[torch.FloatTensor] = None,
1563
+ position_ids: Optional[torch.LongTensor] = None,
1564
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1565
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1566
+ start_positions: Optional[torch.LongTensor] = None,
1567
+ end_positions: Optional[torch.LongTensor] = None,
1568
+ output_attentions: Optional[bool] = None,
1569
+ output_hidden_states: Optional[bool] = None,
1570
+ return_dict: Optional[bool] = None,
1571
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1572
+ r"""
1573
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1574
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1575
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1576
+ are not taken into account for computing the loss.
1577
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1578
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1579
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1580
+ are not taken into account for computing the loss.
1581
+ """
1582
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1583
+
1584
+ outputs = self.transformer(
1585
+ input_ids,
1586
+ attention_mask=attention_mask,
1587
+ position_ids=position_ids,
1588
+ past_key_values=past_key_values,
1589
+ inputs_embeds=inputs_embeds,
1590
+ output_attentions=output_attentions,
1591
+ output_hidden_states=output_hidden_states,
1592
+ return_dict=return_dict,
1593
+ )
1594
+
1595
+ sequence_output = outputs[0]
1596
+
1597
+ logits = self.qa_outputs(sequence_output)
1598
+ start_logits, end_logits = logits.split(1, dim=-1)
1599
+ start_logits = start_logits.squeeze(-1).contiguous()
1600
+ end_logits = end_logits.squeeze(-1).contiguous()
1601
+
1602
+ total_loss = None
1603
+ if start_positions is not None and end_positions is not None:
1604
+ # If we are on multi-GPU, split add a dimension
1605
+ if len(start_positions.size()) > 1:
1606
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1607
+ if len(end_positions.size()) > 1:
1608
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1609
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1610
+ ignored_index = start_logits.size(1)
1611
+ start_positions = start_positions.clamp(0, ignored_index)
1612
+ end_positions = end_positions.clamp(0, ignored_index)
1613
+
1614
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1615
+ start_loss = loss_fct(start_logits, start_positions)
1616
+ end_loss = loss_fct(end_logits, end_positions)
1617
+ total_loss = (start_loss + end_loss) / 2
1618
+
1619
+ if not return_dict:
1620
+ output = (start_logits, end_logits) + outputs[2:]
1621
+ return ((total_loss,) + output) if total_loss is not None else output
1622
+
1623
+ return QuestionAnsweringModelOutput(
1624
+ loss=total_loss,
1625
+ start_logits=start_logits,
1626
+ end_logits=end_logits,
1627
+ hidden_states=outputs.hidden_states,
1628
+ attentions=outputs.attentions,
1629
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|endoftext|>",
4
+ "<|im_start|>",
5
+ "<|im_end|>",
6
+ "<repo_name>",
7
+ "<reponame>",
8
+ "<file_sep>",
9
+ "<filename>",
10
+ "<gh_stars>",
11
+ "<issue_start>",
12
+ "<issue_comment>",
13
+ "<issue_closed>",
14
+ "<jupyter_start>",
15
+ "<jupyter_text>",
16
+ "<jupyter_code>",
17
+ "<jupyter_output>",
18
+ "<jupyter_script>",
19
+ "<empty_output>"
20
+ ],
21
+ "bos_token": {
22
+ "content": "<|endoftext|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false
27
+ },
28
+ "eos_token": {
29
+ "content": "<|endoftext|>",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false
34
+ },
35
+ "pad_token": {
36
+ "content": "<|endoftext|>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false
41
+ },
42
+ "unk_token": {
43
+ "content": "<|endoftext|>",
44
+ "lstrip": false,
45
+ "normalized": false,
46
+ "rstrip": false,
47
+ "single_word": false
48
+ }
49
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "0": {
5
+ "content": "<|endoftext|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "1": {
13
+ "content": "<|im_start|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "2": {
21
+ "content": "<|im_end|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ },
28
+ "3": {
29
+ "content": "<repo_name>",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": true
35
+ },
36
+ "4": {
37
+ "content": "<reponame>",
38
+ "lstrip": false,
39
+ "normalized": false,
40
+ "rstrip": false,
41
+ "single_word": false,
42
+ "special": true
43
+ },
44
+ "5": {
45
+ "content": "<file_sep>",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false,
50
+ "special": true
51
+ },
52
+ "6": {
53
+ "content": "<filename>",
54
+ "lstrip": false,
55
+ "normalized": false,
56
+ "rstrip": false,
57
+ "single_word": false,
58
+ "special": true
59
+ },
60
+ "7": {
61
+ "content": "<gh_stars>",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": false,
65
+ "single_word": false,
66
+ "special": true
67
+ },
68
+ "8": {
69
+ "content": "<issue_start>",
70
+ "lstrip": false,
71
+ "normalized": false,
72
+ "rstrip": false,
73
+ "single_word": false,
74
+ "special": true
75
+ },
76
+ "9": {
77
+ "content": "<issue_comment>",
78
+ "lstrip": false,
79
+ "normalized": false,
80
+ "rstrip": false,
81
+ "single_word": false,
82
+ "special": true
83
+ },
84
+ "10": {
85
+ "content": "<issue_closed>",
86
+ "lstrip": false,
87
+ "normalized": false,
88
+ "rstrip": false,
89
+ "single_word": false,
90
+ "special": true
91
+ },
92
+ "11": {
93
+ "content": "<jupyter_start>",
94
+ "lstrip": false,
95
+ "normalized": false,
96
+ "rstrip": false,
97
+ "single_word": false,
98
+ "special": true
99
+ },
100
+ "12": {
101
+ "content": "<jupyter_text>",
102
+ "lstrip": false,
103
+ "normalized": false,
104
+ "rstrip": false,
105
+ "single_word": false,
106
+ "special": true
107
+ },
108
+ "13": {
109
+ "content": "<jupyter_code>",
110
+ "lstrip": false,
111
+ "normalized": false,
112
+ "rstrip": false,
113
+ "single_word": false,
114
+ "special": true
115
+ },
116
+ "14": {
117
+ "content": "<jupyter_output>",
118
+ "lstrip": false,
119
+ "normalized": false,
120
+ "rstrip": false,
121
+ "single_word": false,
122
+ "special": true
123
+ },
124
+ "15": {
125
+ "content": "<jupyter_script>",
126
+ "lstrip": false,
127
+ "normalized": false,
128
+ "rstrip": false,
129
+ "single_word": false,
130
+ "special": true
131
+ },
132
+ "16": {
133
+ "content": "<empty_output>",
134
+ "lstrip": false,
135
+ "normalized": false,
136
+ "rstrip": false,
137
+ "single_word": false,
138
+ "special": true
139
+ }
140
+ },
141
+ "additional_special_tokens": [
142
+ "<|endoftext|>",
143
+ "<|im_start|>",
144
+ "<|im_end|>",
145
+ "<repo_name>",
146
+ "<reponame>",
147
+ "<file_sep>",
148
+ "<filename>",
149
+ "<gh_stars>",
150
+ "<issue_start>",
151
+ "<issue_comment>",
152
+ "<issue_closed>",
153
+ "<jupyter_start>",
154
+ "<jupyter_text>",
155
+ "<jupyter_code>",
156
+ "<jupyter_output>",
157
+ "<jupyter_script>",
158
+ "<empty_output>"
159
+ ],
160
+ "bos_token": "<|endoftext|>",
161
+ "chat_template": "{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n' }}{% endif %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
162
+ "clean_up_tokenization_spaces": false,
163
+ "eos_token": "<|endoftext|>",
164
+ "model_max_length": 1000000000000000019884624838656,
165
+ "pad_token": "<|endoftext|>",
166
+ "tokenizer_class": "GPT2Tokenizer",
167
+ "unk_token": "<|endoftext|>",
168
+ "vocab_size": 49152
169
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff