HighCWu commited on
Commit
3bc6e89
·
verified ·
1 Parent(s): 2941978

Upload 9 files

Browse files
chat_template.jinja ADDED
@@ -0,0 +1 @@
 
 
1
+ {% if messages[0]['role'] == 'system' %}{% set system_message = messages[0]['content'] %}{{ '<|im_start|>system\n' + system_message + '<|im_end|>\n' }}{% else %}{{ '<|im_start|>system\nYou are a helpful assistant<|im_end|>\n' }}{% endif %}{% for message in messages %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{{ '<|im_start|>user\n' + content + '<|im_end|>\n<|im_start|>assistant\n' }}{% elif message['role'] == 'assistant' %}{{ content + '<|im_end|>' + '\n' }}{% endif %}{% endfor %}
config.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "EmbformerForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_embformer.EmbformerConfig",
9
+ "AutoModelForCausalLM": "modeling_embformer.EmbformerForCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "eos_token_id": 2,
13
+ "head_dim": 96,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 768,
16
+ "initializer_range": 0.02,
17
+ "layer_types": [
18
+ "full_attention",
19
+ "full_attention",
20
+ "full_attention",
21
+ "full_attention",
22
+ "full_attention",
23
+ "full_attention",
24
+ "full_attention",
25
+ "full_attention",
26
+ "full_attention",
27
+ "full_attention",
28
+ "full_attention",
29
+ "full_attention",
30
+ "full_attention",
31
+ "full_attention",
32
+ "full_attention",
33
+ "full_attention"
34
+ ],
35
+ "max_position_embeddings": 32768,
36
+ "max_seq_len": 8192,
37
+ "max_window_layers": 28,
38
+ "model_type": "embformer",
39
+ "num_attention_heads": 8,
40
+ "num_hidden_layers": 16,
41
+ "num_key_value_heads": 2,
42
+ "rms_norm_eps": 1e-06,
43
+ "rope_scaling": null,
44
+ "rope_theta": 10000.0,
45
+ "sliding_window": null,
46
+ "tie_word_embeddings": true,
47
+ "torch_dtype": "bfloat16",
48
+ "transformers_version": "4.53.0.dev0",
49
+ "use_cache": true,
50
+ "use_channel_shift": true,
51
+ "use_sliding_window": false,
52
+ "vocab_size": 6400
53
+ }
configuration_embformer.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 Wu Hecong and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Embformer model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig, layer_type_validation
18
+ from transformers.modeling_rope_utils import rope_config_validation
19
+ from transformers.utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class EmbformerConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`EmbformerModel`]. It is used to instantiate a
28
+ Embformer model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
+ with the defaults will yield a similar configuration to that of
30
+ Embformer-8B [HighCWu/Embformer-8B](https://huggingface.co/HighCWu/Embformer-8B).
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+
36
+ Args:
37
+ vocab_size (`int`, *optional*, defaults to 151936):
38
+ Vocabulary size of the Embformer model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`EmbformerModel`]
40
+ hidden_size (`int`, *optional*, defaults to 4096):
41
+ Dimension of the hidden representations.
42
+ num_hidden_layers (`int`, *optional*, defaults to 32):
43
+ Number of hidden layers in the Transformer encoder.
44
+ num_attention_heads (`int`, *optional*, defaults to 32):
45
+ Number of attention heads for each attention layer in the Transformer encoder.
46
+ num_key_value_heads (`int`, *optional*, defaults to 32):
47
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
48
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
49
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
50
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
51
+ by meanpooling all the original heads within that group. For more details, check out [this
52
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
53
+ head_dim (`int`, *optional*, defaults to 128):
54
+ The attention head dimension.
55
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
56
+ The non-linear activation function (function or string) in the decoder.
57
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
58
+ The maximum sequence length that this model might ever be used with.
59
+ initializer_range (`float`, *optional*, defaults to 0.02):
60
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
61
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
62
+ The epsilon used by the rms normalization layers.
63
+ use_cache (`bool`, *optional*, defaults to `True`):
64
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
65
+ relevant if `config.is_decoder=True`.
66
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
67
+ Whether the model's input and output word embeddings should be tied.
68
+ rope_theta (`float`, *optional*, defaults to 10000.0):
69
+ The base period of the RoPE embeddings.
70
+ rope_scaling (`Dict`, *optional*):
71
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
72
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
73
+ accordingly.
74
+ Expected contents:
75
+ `rope_type` (`str`):
76
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
77
+ 'llama3'], with 'default' being the original RoPE implementation.
78
+ `factor` (`float`, *optional*):
79
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
80
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
81
+ original maximum pre-trained length.
82
+ `original_max_position_embeddings` (`int`, *optional*):
83
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
84
+ pretraining.
85
+ `attention_factor` (`float`, *optional*):
86
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
87
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
88
+ `factor` field to infer the suggested value.
89
+ `beta_fast` (`float`, *optional*):
90
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
91
+ ramp function. If unspecified, it defaults to 32.
92
+ `beta_slow` (`float`, *optional*):
93
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
94
+ ramp function. If unspecified, it defaults to 1.
95
+ `short_factor` (`List[float]`, *optional*):
96
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
97
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
98
+ size divided by the number of attention heads divided by 2
99
+ `long_factor` (`List[float]`, *optional*):
100
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
101
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
102
+ size divided by the number of attention heads divided by 2
103
+ `low_freq_factor` (`float`, *optional*):
104
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
105
+ `high_freq_factor` (`float`, *optional*):
106
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
107
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
108
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
109
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
110
+ Whether to use sliding window attention.
111
+ sliding_window (`int`, *optional*, defaults to 4096):
112
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
113
+ max_window_layers (`int`, *optional*, defaults to 28):
114
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
115
+ layer_types (`list`, *optional*):
116
+ Attention pattern for each layer.
117
+ attention_dropout (`float`, *optional*, defaults to 0.0):
118
+ The dropout ratio for the attention probabilities.
119
+
120
+ ```python
121
+ >>> from transformers import EmbformerModel, EmbformerConfig
122
+
123
+ >>> # Initializing a Embformer style configuration
124
+ >>> configuration = EmbformerConfig()
125
+
126
+ >>> # Initializing a model from the Embformer-8B style configuration
127
+ >>> model = EmbformerModel(configuration)
128
+
129
+ >>> # Accessing the model configuration
130
+ >>> configuration = model.config
131
+ ```"""
132
+
133
+ model_type = "embformer"
134
+ keys_to_ignore_at_inference = ["past_key_values"]
135
+
136
+ # Default tensor parallel plan for base model `Embformer`
137
+ base_model_tp_plan = {
138
+ "layers.*.self_attn.k_embed": "colwise",
139
+ "layers.*.self_attn.v_embed": "colwise",
140
+ "layers.*.ffn.gate_embed": "colwise",
141
+ }
142
+ base_model_pp_plan = {
143
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
144
+ "layers": (["hidden_states", "input_ids", "attention_mask"], ["hidden_states"]),
145
+ "norm": (["hidden_states"], ["hidden_states"]),
146
+ }
147
+
148
+ def __init__(
149
+ self,
150
+ vocab_size=151936,
151
+ hidden_size=4096,
152
+ num_hidden_layers=32,
153
+ num_attention_heads=32,
154
+ num_key_value_heads=32,
155
+ head_dim=128,
156
+ hidden_act="silu",
157
+ max_position_embeddings=32768,
158
+ initializer_range=0.02,
159
+ rms_norm_eps=1e-6,
160
+ use_cache=True,
161
+ tie_word_embeddings=False,
162
+ rope_theta=10000.0,
163
+ rope_scaling=None,
164
+ attention_bias=False,
165
+ use_sliding_window=False,
166
+ sliding_window=4096,
167
+ max_window_layers=28,
168
+ layer_types=None,
169
+ attention_dropout=0.0,
170
+ use_channel_shift=True,
171
+ **kwargs,
172
+ ):
173
+ self.vocab_size = vocab_size
174
+ self.max_position_embeddings = max_position_embeddings
175
+ self.hidden_size = hidden_size
176
+ self.num_hidden_layers = num_hidden_layers
177
+ self.num_attention_heads = num_attention_heads
178
+ self.use_sliding_window = use_sliding_window
179
+ self.sliding_window = sliding_window if self.use_sliding_window else None
180
+ self.max_window_layers = max_window_layers
181
+
182
+ # for backward compatibility
183
+ if num_key_value_heads is None:
184
+ num_key_value_heads = num_attention_heads
185
+
186
+ self.num_key_value_heads = num_key_value_heads
187
+ self.head_dim = head_dim
188
+ self.hidden_act = hidden_act
189
+ self.initializer_range = initializer_range
190
+ self.rms_norm_eps = rms_norm_eps
191
+ self.use_cache = use_cache
192
+ self.rope_theta = rope_theta
193
+ self.rope_scaling = rope_scaling
194
+ self.attention_bias = attention_bias
195
+ self.attention_dropout = attention_dropout
196
+ self.use_channel_shift = use_channel_shift
197
+ # Validate the correctness of rotary position embeddings parameters
198
+ # BC: if there is a 'type' field, move it to 'rope_type'.
199
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
200
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
201
+ rope_config_validation(self)
202
+
203
+ self.layer_types = layer_types
204
+ if self.layer_types is None:
205
+ self.layer_types = [
206
+ "sliding_attention"
207
+ if self.sliding_window is not None and i >= self.max_window_layers
208
+ else "full_attention"
209
+ for i in range(self.num_hidden_layers)
210
+ ]
211
+ layer_type_validation(self.layer_types)
212
+
213
+ super().__init__(
214
+ tie_word_embeddings=tie_word_embeddings,
215
+ **kwargs,
216
+ )
217
+
218
+
219
+ __all__ = ["EmbformerConfig"]
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.53.0.dev0"
6
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ce3a40d6e3ef023ef106c01cc20f70b83b04ce479ce11bf65806b24dabdda87a
3
+ size 245765584
modeling_embformer.py ADDED
@@ -0,0 +1,818 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 Wu Hecong and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Callable, Optional, Tuple, Union
17
+
18
+ import torch
19
+ from torch import nn
20
+
21
+ from transformers.activations import ACT2FN
22
+ from transformers.cache_utils import Cache, DynamicCache
23
+ from transformers.generation import GenerationMixin
24
+ from transformers.integrations import use_kernel_forward_from_hub
25
+ from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
26
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
27
+ from transformers.modeling_layers import GradientCheckpointingLayer
28
+ from transformers.modeling_outputs import (
29
+ BaseModelOutputWithPast,
30
+ CausalLMOutputWithPast,
31
+ QuestionAnsweringModelOutput,
32
+ SequenceClassifierOutputWithPast,
33
+ TokenClassifierOutput,
34
+ )
35
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
36
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
37
+ from transformers.processing_utils import Unpack
38
+ from transformers.utils import LossKwargs, auto_docstring, can_return_tuple, logging
39
+ from .configuration_embformer import EmbformerConfig
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+
45
+ @use_kernel_forward_from_hub("RMSNorm")
46
+ class EmbformerRMSNorm(nn.Module):
47
+ def __init__(self, hidden_size, eps=1e-6):
48
+ """
49
+ EmbformerRMSNorm uses a fixed scale weight (1.0).
50
+ """
51
+ super().__init__()
52
+ self.register_buffer("weight", torch.ones(hidden_size), persistent=False)
53
+ self.variance_epsilon = eps
54
+
55
+ def forward(self, hidden_states):
56
+ input_dtype = hidden_states.dtype
57
+ hidden_states = hidden_states.to(torch.float32)
58
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
59
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
60
+ return self.weight * hidden_states.to(input_dtype)
61
+
62
+ def extra_repr(self):
63
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
64
+
65
+
66
+ class EmbformerFeedForward(nn.Module):
67
+ def __init__(self, config):
68
+ super().__init__()
69
+ self.padding_idx = config.pad_token_id
70
+ self.gate_embed = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
71
+ self.act_fn = ACT2FN[config.hidden_act]
72
+
73
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
74
+ channel_shift = torch.arange(config.hidden_size).view(-1, self.head_dim)
75
+ if config.use_channel_shift:
76
+ channel_shift_ori = channel_shift.clone()
77
+ num_heads = config.num_attention_heads
78
+ for i in range(num_heads):
79
+ for j in range(self.head_dim):
80
+ k = (i + j) % num_heads
81
+ channel_shift[i, j] = channel_shift_ori[k, j]
82
+ channel_shift = channel_shift.flatten()
83
+ self.register_buffer("channel_shift", channel_shift, persistent=False)
84
+
85
+ def forward(self, x, input_ids):
86
+ return torch.index_select(self.act_fn(x) * self.gate_embed(input_ids), -1, index=self.channel_shift)
87
+
88
+
89
+ def rotate_half(x):
90
+ """Rotates half the hidden dims of the input."""
91
+ x1 = x[..., : x.shape[-1] // 2]
92
+ x2 = x[..., x.shape[-1] // 2 :]
93
+ return torch.cat((-x2, x1), dim=-1)
94
+
95
+
96
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
97
+ """Applies Rotary Position Embedding to the query and key tensors.
98
+
99
+ Args:
100
+ q (`torch.Tensor`): The query tensor.
101
+ k (`torch.Tensor`): The key tensor.
102
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
103
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
104
+ position_ids (`torch.Tensor`, *optional*):
105
+ Deprecated and unused.
106
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
107
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
108
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
109
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
110
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
111
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
112
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
113
+ Returns:
114
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
115
+ """
116
+ cos = cos.unsqueeze(unsqueeze_dim)
117
+ sin = sin.unsqueeze(unsqueeze_dim)
118
+ q_embed = (q * cos) + (rotate_half(q) * sin)
119
+ k_embed = (k * cos) + (rotate_half(k) * sin)
120
+ return q_embed, k_embed
121
+
122
+
123
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
124
+ """
125
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
126
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
127
+ """
128
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
129
+ if n_rep == 1:
130
+ return hidden_states
131
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
132
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
133
+
134
+
135
+ def eager_attention_forward(
136
+ module: nn.Module,
137
+ query: torch.Tensor,
138
+ key: torch.Tensor,
139
+ value: torch.Tensor,
140
+ attention_mask: Optional[torch.Tensor],
141
+ scaling: float,
142
+ dropout: float = 0.0,
143
+ **kwargs,
144
+ ):
145
+ key_states = repeat_kv(key, module.num_key_value_groups)
146
+ value_states = repeat_kv(value, module.num_key_value_groups)
147
+
148
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
149
+ if attention_mask is not None:
150
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
151
+ attn_weights = attn_weights + causal_mask
152
+
153
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
154
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
155
+ attn_output = torch.matmul(attn_weights, value_states)
156
+ attn_output = attn_output.transpose(1, 2).contiguous()
157
+
158
+ return attn_output, attn_weights
159
+
160
+
161
+ class EmbformerAttention(nn.Module):
162
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
163
+
164
+ def __init__(self, config: EmbformerConfig, layer_idx: int):
165
+ super().__init__()
166
+ self.config = config
167
+ self.layer_idx = layer_idx
168
+ self.padding_idx = config.pad_token_id
169
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
170
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
171
+ self.scaling = self.head_dim**-0.5
172
+ self.attention_dropout = config.attention_dropout
173
+ self.is_causal = True
174
+
175
+ self.k_embed = nn.Embedding(
176
+ config.vocab_size, config.num_key_value_heads * self.head_dim, self.padding_idx
177
+ )
178
+ self.v_embed = nn.Embedding(
179
+ config.vocab_size, config.num_key_value_heads * self.head_dim, self.padding_idx
180
+ )
181
+ self.q_norm = EmbformerRMSNorm(self.head_dim, eps=config.rms_norm_eps) # unlike olmo, only on the head dim!
182
+ self.k_norm = EmbformerRMSNorm(self.head_dim, eps=config.rms_norm_eps) # thus post q_norm does not need reshape
183
+ self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
184
+
185
+ def forward(
186
+ self,
187
+ hidden_states: torch.Tensor,
188
+ input_ids: torch.Tensor,
189
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
190
+ attention_mask: Optional[torch.Tensor],
191
+ past_key_value: Optional[DynamicCache] = None,
192
+ cache_position: Optional[torch.LongTensor] = None,
193
+ **kwargs: Unpack[FlashAttentionKwargs],
194
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
195
+ input_shape = hidden_states.shape[:-1]
196
+ hidden_shape = (*input_shape, -1, self.head_dim)
197
+
198
+ query_states = self.q_norm(hidden_states.view(hidden_shape)).transpose(1, 2)
199
+ key_states = self.k_norm(self.k_embed(input_ids).view(hidden_shape)).transpose(1, 2)
200
+ value_states = self.v_embed(input_ids).view(hidden_shape).transpose(1, 2)
201
+
202
+ cos, sin = position_embeddings
203
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
204
+
205
+ if past_key_value is not None:
206
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
207
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
208
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
209
+
210
+ attention_interface: Callable = eager_attention_forward
211
+ if self.config._attn_implementation != "eager":
212
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
213
+
214
+ attn_output, attn_weights = attention_interface(
215
+ self,
216
+ query_states,
217
+ key_states,
218
+ value_states,
219
+ attention_mask,
220
+ dropout=0.0 if not self.training else self.attention_dropout,
221
+ scaling=self.scaling,
222
+ sliding_window=self.sliding_window, # diff with Llama
223
+ **kwargs,
224
+ )
225
+
226
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
227
+ return attn_output, attn_weights
228
+
229
+
230
+ class EmbformerDecoderLayer(GradientCheckpointingLayer):
231
+ def __init__(self, config: EmbformerConfig, layer_idx: int):
232
+ super().__init__()
233
+ self.hidden_size = config.hidden_size
234
+
235
+ self.self_attn = EmbformerAttention(config=config, layer_idx=layer_idx)
236
+
237
+ self.ffn = EmbformerFeedForward(config)
238
+ self.input_layernorm = EmbformerRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
239
+ self.post_attention_layernorm = EmbformerRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
240
+ self.attention_type = config.layer_types[layer_idx]
241
+
242
+ def forward(
243
+ self,
244
+ hidden_states: torch.Tensor,
245
+ input_ids: torch.Tensor,
246
+ attention_mask: Optional[torch.Tensor] = None,
247
+ position_ids: Optional[torch.LongTensor] = None,
248
+ past_key_value: Optional[Cache] = None,
249
+ output_attentions: Optional[bool] = False,
250
+ use_cache: Optional[bool] = False,
251
+ cache_position: Optional[torch.LongTensor] = None,
252
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
253
+ **kwargs: Unpack[FlashAttentionKwargs],
254
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
255
+ residual = hidden_states
256
+ hidden_states = self.input_layernorm(hidden_states)
257
+
258
+ # Self Attention
259
+ hidden_states, self_attn_weights = self.self_attn(
260
+ hidden_states=hidden_states,
261
+ input_ids=input_ids,
262
+ attention_mask=attention_mask,
263
+ position_ids=position_ids,
264
+ past_key_value=past_key_value,
265
+ output_attentions=output_attentions,
266
+ use_cache=use_cache,
267
+ cache_position=cache_position,
268
+ position_embeddings=position_embeddings,
269
+ **kwargs,
270
+ )
271
+ hidden_states = residual + hidden_states
272
+
273
+ # Fully Connected
274
+ residual = hidden_states
275
+ hidden_states = self.post_attention_layernorm(hidden_states)
276
+ hidden_states = self.ffn(hidden_states, input_ids)
277
+ hidden_states = residual + hidden_states
278
+
279
+ outputs = (hidden_states,)
280
+ if output_attentions:
281
+ outputs += (self_attn_weights,)
282
+
283
+ return outputs
284
+
285
+
286
+ @auto_docstring
287
+ class EmbformerPreTrainedModel(PreTrainedModel):
288
+ config_class = EmbformerConfig
289
+ base_model_prefix = "model"
290
+ supports_gradient_checkpointing = True
291
+ _no_split_modules = ["EmbformerDecoderLayer"]
292
+ _skip_keys_device_placement = ["past_key_values"]
293
+ _supports_flash_attn_2 = True
294
+ _supports_sdpa = True
295
+ _supports_flex_attn = True
296
+ _supports_cache_class = True
297
+ _supports_quantized_cache = True
298
+ _supports_static_cache = True
299
+ _supports_attention_backend = True
300
+
301
+ def _init_weights(self, module):
302
+ std = self.config.initializer_range
303
+ if isinstance(module, nn.Linear):
304
+ module.weight.data.normal_(mean=0.0, std=std)
305
+ if module.bias is not None:
306
+ module.bias.data.zero_()
307
+ elif isinstance(module, nn.Embedding):
308
+ module.weight.data.normal_(mean=0.0, std=std)
309
+ if module.padding_idx is not None:
310
+ module.weight.data[module.padding_idx].zero_()
311
+ elif isinstance(module, EmbformerRMSNorm):
312
+ module.weight.data.fill_(1.0)
313
+
314
+
315
+ class EmbformerRotaryEmbedding(nn.Module):
316
+ def __init__(self, config: EmbformerConfig, device=None):
317
+ super().__init__()
318
+ # BC: "rope_type" was originally "type"
319
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
320
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
321
+ else:
322
+ self.rope_type = "default"
323
+ self.max_seq_len_cached = config.max_position_embeddings
324
+ self.original_max_seq_len = config.max_position_embeddings
325
+
326
+ self.config = config
327
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
328
+
329
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
330
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
331
+ self.original_inv_freq = self.inv_freq
332
+
333
+ @torch.no_grad()
334
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
335
+ def forward(self, x, position_ids):
336
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
337
+ position_ids_expanded = position_ids[:, None, :].float()
338
+
339
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
340
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
341
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
342
+ emb = torch.cat((freqs, freqs), dim=-1)
343
+ cos = emb.cos() * self.attention_scaling
344
+ sin = emb.sin() * self.attention_scaling
345
+
346
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
347
+
348
+
349
+ @auto_docstring
350
+ class EmbformerModel(EmbformerPreTrainedModel):
351
+ def __init__(self, config: EmbformerConfig):
352
+ super().__init__(config)
353
+ self.padding_idx = config.pad_token_id
354
+ self.vocab_size = config.vocab_size
355
+
356
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
357
+ self.layers = nn.ModuleList(
358
+ [EmbformerDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
359
+ )
360
+ self.norm = EmbformerRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
361
+ self.rotary_emb = EmbformerRotaryEmbedding(config=config)
362
+ self.gradient_checkpointing = False
363
+ self.has_sliding_layers = "sliding_attention" in self.config.layer_types
364
+
365
+ # Initialize weights and apply final processing
366
+ self.post_init()
367
+
368
+ def get_input_embeddings(self):
369
+ return self.embed_tokens
370
+
371
+ def set_input_embeddings(self, value):
372
+ self.embed_tokens = value
373
+
374
+ @can_return_tuple
375
+ @auto_docstring
376
+ def forward(
377
+ self,
378
+ input_ids: torch.LongTensor,
379
+ attention_mask: Optional[torch.Tensor] = None,
380
+ position_ids: Optional[torch.LongTensor] = None,
381
+ past_key_values: Optional[Cache] = None,
382
+ use_cache: Optional[bool] = None,
383
+ output_attentions: Optional[bool] = None,
384
+ output_hidden_states: Optional[bool] = None,
385
+ cache_position: Optional[torch.LongTensor] = None,
386
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
387
+ ) -> BaseModelOutputWithPast:
388
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
389
+ output_hidden_states = (
390
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
391
+ )
392
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
393
+
394
+ if input_ids is None:
395
+ raise ValueError("You must specify exactly input_ids")
396
+
397
+ if self.gradient_checkpointing and self.training and use_cache:
398
+ logger.warning_once(
399
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
400
+ )
401
+ use_cache = False
402
+
403
+ # TODO (joao): remove this exception in v4.56 -- it exists for users that try to pass a legacy cache
404
+ if not isinstance(past_key_values, (type(None), Cache)):
405
+ raise ValueError("The `past_key_values` should be either a `Cache` object or `None`.")
406
+
407
+ inputs_embeds = self.embed_tokens(input_ids)
408
+
409
+ if use_cache and past_key_values is None:
410
+ past_key_values = DynamicCache()
411
+
412
+ if cache_position is None:
413
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
414
+ cache_position = torch.arange(
415
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
416
+ )
417
+
418
+ if position_ids is None:
419
+ position_ids = cache_position.unsqueeze(0)
420
+
421
+ # It may already have been prepared by e.g. `generate`
422
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
423
+ # Prepare mask arguments
424
+ mask_kwargs = {
425
+ "config": self.config,
426
+ "input_embeds": inputs_embeds,
427
+ "attention_mask": attention_mask,
428
+ "cache_position": cache_position,
429
+ "past_key_values": past_key_values,
430
+ }
431
+ # Create the masks
432
+ causal_mask_mapping = {
433
+ "full_attention": create_causal_mask(**mask_kwargs),
434
+ }
435
+ # The sliding window alternating layers are not always activated depending on the config
436
+ if self.has_sliding_layers:
437
+ causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
438
+
439
+ hidden_states = inputs_embeds
440
+
441
+ # create position embeddings to be shared across the decoder layers
442
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
443
+
444
+ # decoder layers
445
+ all_hidden_states = () if output_hidden_states else None
446
+ all_self_attns = () if output_attentions else None
447
+
448
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
449
+ if output_hidden_states:
450
+ all_hidden_states += (hidden_states,)
451
+
452
+ layer_outputs = decoder_layer(
453
+ hidden_states,
454
+ input_ids=input_ids,
455
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
456
+ position_ids=position_ids,
457
+ past_key_value=past_key_values,
458
+ output_attentions=output_attentions,
459
+ use_cache=use_cache,
460
+ cache_position=cache_position,
461
+ position_embeddings=position_embeddings,
462
+ **flash_attn_kwargs,
463
+ )
464
+
465
+ hidden_states = layer_outputs[0]
466
+
467
+ if output_attentions:
468
+ all_self_attns += (layer_outputs[1],)
469
+
470
+ hidden_states = self.norm(hidden_states)
471
+
472
+ # add hidden states from the last decoder layer
473
+ if output_hidden_states:
474
+ all_hidden_states += (hidden_states,)
475
+
476
+ return BaseModelOutputWithPast(
477
+ last_hidden_state=hidden_states,
478
+ past_key_values=past_key_values if use_cache else None,
479
+ hidden_states=all_hidden_states,
480
+ attentions=all_self_attns,
481
+ )
482
+
483
+
484
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
485
+
486
+
487
+ @auto_docstring
488
+ class EmbformerForCausalLM(EmbformerPreTrainedModel, GenerationMixin):
489
+ _tied_weights_keys = ["lm_head.weight"]
490
+ _tp_plan = {"lm_head": "colwise_rep"}
491
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
492
+
493
+ def __init__(self, config):
494
+ super().__init__(config)
495
+ self.model = EmbformerModel(config)
496
+ self.vocab_size = config.vocab_size
497
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
498
+
499
+ # Initialize weights and apply final processing
500
+ self.post_init()
501
+
502
+ def get_input_embeddings(self):
503
+ return self.model.embed_tokens
504
+
505
+ def set_input_embeddings(self, value):
506
+ self.model.embed_tokens = value
507
+
508
+ def get_output_embeddings(self):
509
+ return self.lm_head
510
+
511
+ def set_output_embeddings(self, new_embeddings):
512
+ self.lm_head = new_embeddings
513
+
514
+ def set_decoder(self, decoder):
515
+ self.model = decoder
516
+
517
+ def get_decoder(self):
518
+ return self.model
519
+
520
+ @can_return_tuple
521
+ @auto_docstring
522
+ def forward(
523
+ self,
524
+ input_ids: torch.LongTensor,
525
+ attention_mask: Optional[torch.Tensor] = None,
526
+ position_ids: Optional[torch.LongTensor] = None,
527
+ past_key_values: Optional[Cache] = None,
528
+ labels: Optional[torch.LongTensor] = None,
529
+ use_cache: Optional[bool] = None,
530
+ output_attentions: Optional[bool] = None,
531
+ output_hidden_states: Optional[bool] = None,
532
+ cache_position: Optional[torch.LongTensor] = None,
533
+ logits_to_keep: Union[int, torch.Tensor] = 0,
534
+ **kwargs: Unpack[KwargsForCausalLM],
535
+ ) -> CausalLMOutputWithPast:
536
+ r"""
537
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
538
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
539
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
540
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
541
+
542
+ Example:
543
+
544
+ ```python
545
+ >>> from transformers import AutoTokenizer, EmbformerForCausalLM
546
+
547
+ >>> model = EmbformerForCausalLM.from_pretrained("HighCWu/Embformer-8B")
548
+ >>> tokenizer = AutoTokenizer.from_pretrained("HighCWu/Embformer-8B")
549
+
550
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
551
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
552
+
553
+ >>> # Generate
554
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
555
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
556
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
557
+ ```"""
558
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
559
+ output_hidden_states = (
560
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
561
+ )
562
+
563
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
564
+ outputs: BaseModelOutputWithPast = self.model(
565
+ input_ids=input_ids,
566
+ attention_mask=attention_mask,
567
+ position_ids=position_ids,
568
+ past_key_values=past_key_values,
569
+ use_cache=use_cache,
570
+ output_attentions=output_attentions,
571
+ output_hidden_states=output_hidden_states,
572
+ cache_position=cache_position,
573
+ **kwargs,
574
+ )
575
+
576
+ hidden_states = outputs.last_hidden_state
577
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
578
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
579
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
580
+
581
+ loss = None
582
+ if labels is not None:
583
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
584
+
585
+ return CausalLMOutputWithPast(
586
+ loss=loss,
587
+ logits=logits,
588
+ past_key_values=outputs.past_key_values,
589
+ hidden_states=outputs.hidden_states,
590
+ attentions=outputs.attentions,
591
+ )
592
+
593
+
594
+ @auto_docstring(
595
+ custom_intro="""
596
+ The Embformer Model transformer with a sequence classification head on top (linear layer).
597
+
598
+ [`EmbformerForSequenceClassification`] uses the last token in order to do the classification, as other causal models
599
+ (e.g. GPT-2) do.
600
+
601
+ Since it does classification on the last token, it requires to know the position of the last token. If a
602
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
603
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch.
604
+ """
605
+ )
606
+ class EmbformerForSequenceClassification(EmbformerPreTrainedModel):
607
+ def __init__(self, config):
608
+ super().__init__(config)
609
+ self.num_labels = config.num_labels
610
+ self.model = EmbformerModel(config)
611
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
612
+
613
+ # Initialize weights and apply final processing
614
+ self.post_init()
615
+
616
+ def get_input_embeddings(self):
617
+ return self.model.embed_tokens
618
+
619
+ def set_input_embeddings(self, value):
620
+ self.model.embed_tokens = value
621
+
622
+ @can_return_tuple
623
+ @auto_docstring
624
+ def forward(
625
+ self,
626
+ input_ids: torch.LongTensor,
627
+ attention_mask: Optional[torch.Tensor] = None,
628
+ position_ids: Optional[torch.LongTensor] = None,
629
+ past_key_values: Optional[Cache] = None,
630
+ labels: Optional[torch.LongTensor] = None,
631
+ use_cache: Optional[bool] = None,
632
+ output_attentions: Optional[bool] = None,
633
+ output_hidden_states: Optional[bool] = None,
634
+ ) -> SequenceClassifierOutputWithPast:
635
+ r"""
636
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
637
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
638
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
639
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
640
+ """
641
+
642
+ transformer_outputs: BaseModelOutputWithPast = self.model(
643
+ input_ids,
644
+ attention_mask=attention_mask,
645
+ position_ids=position_ids,
646
+ past_key_values=past_key_values,
647
+ use_cache=use_cache,
648
+ output_attentions=output_attentions,
649
+ output_hidden_states=output_hidden_states,
650
+ )
651
+ hidden_states = transformer_outputs.last_hidden_state
652
+ logits = self.score(hidden_states)
653
+
654
+ batch_size = input_ids.shape[0]
655
+
656
+ if self.config.pad_token_id is None and batch_size != 1:
657
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
658
+ if self.config.pad_token_id is None:
659
+ last_non_pad_token = -1
660
+ else:
661
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
662
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
663
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
664
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
665
+
666
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
667
+
668
+ loss = None
669
+ if labels is not None:
670
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
671
+
672
+ return SequenceClassifierOutputWithPast(
673
+ loss=loss,
674
+ logits=pooled_logits,
675
+ past_key_values=transformer_outputs.past_key_values,
676
+ hidden_states=transformer_outputs.hidden_states,
677
+ attentions=transformer_outputs.attentions,
678
+ )
679
+
680
+
681
+ @auto_docstring
682
+ class EmbformerForTokenClassification(EmbformerPreTrainedModel):
683
+ def __init__(self, config):
684
+ super().__init__(config)
685
+ self.num_labels = config.num_labels
686
+ self.model = EmbformerModel(config)
687
+ if getattr(config, "classifier_dropout", None) is not None:
688
+ classifier_dropout = config.classifier_dropout
689
+ elif getattr(config, "hidden_dropout", None) is not None:
690
+ classifier_dropout = config.hidden_dropout
691
+ else:
692
+ classifier_dropout = 0.1
693
+ self.dropout = nn.Dropout(classifier_dropout)
694
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
695
+
696
+ # Initialize weights and apply final processing
697
+ self.post_init()
698
+
699
+ def get_input_embeddings(self):
700
+ return self.model.embed_tokens
701
+
702
+ def set_input_embeddings(self, value):
703
+ self.model.embed_tokens = value
704
+
705
+ @can_return_tuple
706
+ @auto_docstring
707
+ def forward(
708
+ self,
709
+ input_ids: torch.LongTensor,
710
+ attention_mask: Optional[torch.Tensor] = None,
711
+ position_ids: Optional[torch.LongTensor] = None,
712
+ past_key_values: Optional[Cache] = None,
713
+ labels: Optional[torch.LongTensor] = None,
714
+ use_cache: Optional[bool] = None,
715
+ output_attentions: Optional[bool] = None,
716
+ output_hidden_states: Optional[bool] = None,
717
+ ) -> TokenClassifierOutput:
718
+ r"""
719
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
720
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
721
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
722
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
723
+ """
724
+
725
+ outputs: BaseModelOutputWithPast = self.model(
726
+ input_ids,
727
+ attention_mask=attention_mask,
728
+ position_ids=position_ids,
729
+ past_key_values=past_key_values,
730
+ use_cache=use_cache,
731
+ output_attentions=output_attentions,
732
+ output_hidden_states=output_hidden_states,
733
+ )
734
+ sequence_output = outputs.last_hidden_state
735
+ sequence_output = self.dropout(sequence_output)
736
+ logits = self.score(sequence_output)
737
+
738
+ loss = None
739
+ if labels is not None:
740
+ loss = self.loss_function(logits, labels, self.config)
741
+
742
+ return TokenClassifierOutput(
743
+ loss=loss,
744
+ logits=logits,
745
+ hidden_states=outputs.hidden_states,
746
+ attentions=outputs.attentions,
747
+ )
748
+
749
+
750
+ @auto_docstring
751
+ class EmbformerForQuestionAnswering(EmbformerPreTrainedModel):
752
+ base_model_prefix = "transformer"
753
+
754
+ def __init__(self, config):
755
+ super().__init__(config)
756
+ self.transformer = EmbformerModel(config)
757
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
758
+
759
+ # Initialize weights and apply final processing
760
+ self.post_init()
761
+
762
+ def get_input_embeddings(self):
763
+ return self.transformer.embed_tokens
764
+
765
+ def set_input_embeddings(self, value):
766
+ self.transformer.embed_tokens = value
767
+
768
+ @can_return_tuple
769
+ @auto_docstring
770
+ def forward(
771
+ self,
772
+ input_ids: torch.LongTensor,
773
+ attention_mask: Optional[torch.Tensor] = None,
774
+ position_ids: Optional[torch.LongTensor] = None,
775
+ past_key_values: Optional[Cache] = None,
776
+ start_positions: Optional[torch.LongTensor] = None,
777
+ end_positions: Optional[torch.LongTensor] = None,
778
+ output_attentions: Optional[bool] = None,
779
+ output_hidden_states: Optional[bool] = None,
780
+ **kwargs,
781
+ ) -> QuestionAnsweringModelOutput:
782
+ outputs: BaseModelOutputWithPast = self.transformer(
783
+ input_ids,
784
+ attention_mask=attention_mask,
785
+ position_ids=position_ids,
786
+ past_key_values=past_key_values,
787
+ output_attentions=output_attentions,
788
+ output_hidden_states=output_hidden_states,
789
+ )
790
+
791
+ sequence_output = outputs.last_hidden_state
792
+
793
+ logits = self.qa_outputs(sequence_output)
794
+ start_logits, end_logits = logits.split(1, dim=-1)
795
+ start_logits = start_logits.squeeze(-1).contiguous()
796
+ end_logits = end_logits.squeeze(-1).contiguous()
797
+
798
+ loss = None
799
+ if start_positions is not None and end_positions is not None:
800
+ loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
801
+
802
+ return QuestionAnsweringModelOutput(
803
+ loss=loss,
804
+ start_logits=start_logits,
805
+ end_logits=end_logits,
806
+ hidden_states=outputs.hidden_states,
807
+ attentions=outputs.attentions,
808
+ )
809
+
810
+
811
+ __all__ = [
812
+ "EmbformerForCausalLM",
813
+ "EmbformerForQuestionAnswering",
814
+ "EmbformerModel",
815
+ "EmbformerPreTrainedModel",
816
+ "EmbformerForSequenceClassification",
817
+ "EmbformerForTokenClassification",
818
+ ]
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|im_start|>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|im_end|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<|endoftext|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<|endoftext|>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": false,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<|endoftext|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<|im_start|>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "<|im_end|>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ }
30
+ },
31
+ "additional_special_tokens": [],
32
+ "bos_token": "<|im_start|>",
33
+ "clean_up_tokenization_spaces": false,
34
+ "eos_token": "<|im_end|>",
35
+ "extra_special_tokens": {},
36
+ "legacy": true,
37
+ "model_max_length": 32768,
38
+ "pad_token": "<|endoftext|>",
39
+ "sp_model_kwargs": {},
40
+ "spaces_between_special_tokens": false,
41
+ "tokenizer_class": "PreTrainedTokenizerFast",
42
+ "unk_token": "<|endoftext|>"
43
+ }