Text Generation
Safetensors
English
Chinese
plm
conversational
custom_code
daven3 commited on
Commit
6759397
·
verified ·
1 Parent(s): 7687d96

Upload 11 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
added_tokens.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "<|endoftext|>": 151643,
3
+ "<|im_end|>": 151645,
4
+ "<|im_start|>": 151644
5
+ }
config.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "EdgellmForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_edgellm.EdgellmConfig",
7
+ "AutoModel": "modeling_edgellm.EdgellmModel",
8
+ "AutoModelForCausalLM": "modeling_edgellm.EdgellmForCausalLM"
9
+ },
10
+ "attention_bias": false,
11
+ "attention_dropout": 0.0,
12
+ "bos_token_id": 151643,
13
+ "eos_token_id": 151643,
14
+ "hidden_act": "relu2",
15
+ "hidden_size": 2048,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 8192,
18
+ "kv_lora_rank": 512,
19
+ "max_position_embeddings": 4096,
20
+ "model_type": "edgellm",
21
+ "num_attention_heads": 16,
22
+ "num_key_value_heads": 16,
23
+ "num_hidden_layers": 32,
24
+ "q_lora_rank": null,
25
+ "qk_nope_head_dim": 128,
26
+ "qk_rope_head_dim": 64,
27
+ "rms_norm_eps": 1e-06,
28
+ "rope_scaling": null,
29
+ "pretraining_tp": 1,
30
+ "rope_theta": 100000.0,
31
+ "sliding_window": 4096,
32
+ "tie_word_embeddings": true,
33
+ "torch_dtype": "bfloat16",
34
+ "transformers_version": "4.40.1",
35
+ "use_cache": true,
36
+ "use_sliding_window": false,
37
+ "v_head_dim": 128,
38
+ "vocab_size": 151936
39
+ }
configuration_edgellm.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The EdgeLLM team and The HuggingFace Inc. 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
+ """EdgeLLM model configuration"""
16
+ # Test test
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class EdgellmConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`Qwen2Model`]. It is used to instantiate a
27
+ Qwen2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
28
+ with the defaults will yield a similar configuration to that of
29
+ Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 151936):
37
+ Vocabulary size of the Qwen2 model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`Qwen2Model`]
39
+ hidden_size (`int`, *optional*, defaults to 4096):
40
+ Dimension of the hidden representations.
41
+ intermediate_size (`int`, *optional*, defaults to 22016):
42
+ Dimension of the MLP representations.
43
+ num_hidden_layers (`int`, *optional*, defaults to 32):
44
+ Number of hidden layers in the Transformer encoder.
45
+ num_attention_heads (`int`, *optional*, defaults to 32):
46
+ Number of attention heads for each attention layer in the Transformer encoder.
47
+ num_key_value_heads (`int`, *optional*, defaults to 32):
48
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
49
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
50
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
51
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
52
+ by meanpooling all the original heads within that group. For more details checkout [this
53
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
54
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
55
+ The non-linear activation function (function or string) in the decoder.
56
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
57
+ The maximum sequence length that this model might ever be used with.
58
+ initializer_range (`float`, *optional*, defaults to 0.02):
59
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
60
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
61
+ The epsilon used by the rms normalization layers.
62
+ use_cache (`bool`, *optional*, defaults to `True`):
63
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
64
+ relevant if `config.is_decoder=True`.
65
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
66
+ Whether the model's input and output word embeddings should be tied.
67
+ rope_theta (`float`, *optional*, defaults to 10000.0):
68
+ The base period of the RoPE embeddings.
69
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
70
+ Whether to use sliding window attention.
71
+ sliding_window (`int`, *optional*, defaults to 4096):
72
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
73
+ max_window_layers (`int`, *optional*, defaults to 28):
74
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
75
+ attention_dropout (`float`, *optional*, defaults to 0.0):
76
+ The dropout ratio for the attention probabilities.
77
+
78
+ ```python
79
+ >>> from transformers import Qwen2Model, Qwen2Config
80
+
81
+ >>> # Initializing a Qwen2 style configuration
82
+ >>> configuration = Qwen2Config()
83
+
84
+ >>> # Initializing a model from the Qwen2-7B style configuration
85
+ >>> model = Qwen2Model(configuration)
86
+
87
+ >>> # Accessing the model configuration
88
+ >>> configuration = model.config
89
+ ```"""
90
+
91
+ model_type = "edgellm"
92
+ keys_to_ignore_at_inference = ["past_key_values"]
93
+
94
+ def __init__(
95
+ self,
96
+ vocab_size=151936,
97
+ hidden_size=2048,
98
+ intermediate_size=8192,
99
+ num_hidden_layers=32,
100
+ num_attention_heads=16,
101
+ num_key_value_heads=16,
102
+ kv_lora_rank = 512,
103
+ q_lora_rank = None,
104
+ qk_rope_head_dim = 64,
105
+ v_head_dim = 128,
106
+ qk_nope_head_dim = 128,
107
+ hidden_act="relu2",
108
+ max_position_embeddings=4096,
109
+ initializer_range=0.02,
110
+ rms_norm_eps=1e-6,
111
+ use_cache=True,
112
+ pretraining_tp=1,
113
+ tie_word_embeddings=True,
114
+ rope_theta=10000.0,
115
+ rope_scaling=None,
116
+ attention_bias=False,
117
+ attention_dropout=0.0,
118
+ use_sliding_window=False,
119
+ sliding_window=4096,
120
+ **kwargs,
121
+ ):
122
+ self.vocab_size = vocab_size
123
+ self.max_position_embeddings = max_position_embeddings
124
+ self.hidden_size = hidden_size
125
+ self.intermediate_size = intermediate_size
126
+ self.num_hidden_layers = num_hidden_layers
127
+ self.num_attention_heads = num_attention_heads
128
+ self.kv_lora_rank = kv_lora_rank
129
+ self.q_lora_rank = q_lora_rank
130
+ self.qk_rope_head_dim = qk_rope_head_dim
131
+ self.v_head_dim = v_head_dim
132
+ self.qk_nope_head_dim = qk_nope_head_dim
133
+ # for backward compatibility
134
+ if num_key_value_heads is None:
135
+ num_key_value_heads = num_attention_heads
136
+
137
+ self.num_key_value_heads = num_key_value_heads
138
+ self.hidden_act = hidden_act
139
+ self.initializer_range = initializer_range
140
+ self.rms_norm_eps = rms_norm_eps
141
+ self.pretraining_tp = pretraining_tp
142
+ self.use_cache = use_cache
143
+ self.rope_theta = rope_theta
144
+ self.rope_scaling = rope_scaling
145
+ self.attention_bias = attention_bias
146
+ self.attention_dropout = attention_dropout
147
+
148
+ self.use_sliding_window = use_sliding_window
149
+ self.sliding_window = sliding_window
150
+
151
+ # for backward compatibility
152
+ if num_key_value_heads is None:
153
+ num_key_value_heads = num_attention_heads
154
+ self.attn_implementation = "flash_attention_2"
155
+
156
+ super().__init__(
157
+ tie_word_embeddings=tie_word_embeddings,
158
+ **kwargs,
159
+ )
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 151643,
4
+ "eos_token_id": 151643,
5
+ "transformers_version": "4.46.1",
6
+ "use_cache": false
7
+ }
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:57e2148e5abfb7ac5a3c442895d73fbb8b234e0f0f088f0c84fb1c85ef31ff83
3
+ size 3650950536
modeling_edgellm.py ADDED
@@ -0,0 +1,1701 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The EdgeLLM team and The HuggingFace Inc. All rights reserved.
3
+ #
4
+ # This code is based on Alibaba's Qwen2 library, DeepSeek-AI's deepseekv2
5
+ # libraryEleutherAI's GPT-NeoX library and the GPT-NeoX and OPT implementations
6
+ # in this library. It has been modified from its original forms to accommodate
7
+ # minor architectural differences compared to GPT-NeoX and OPT used by the Meta
8
+ # AI team that trained the model.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+ """PyTorch EdgeLLM model."""
22
+
23
+ import inspect
24
+ import math
25
+ import warnings
26
+ from typing import List, Optional, Tuple, Union
27
+
28
+ import torch
29
+ import torch.nn.functional as F
30
+ import torch.utils.checkpoint
31
+ from torch import nn
32
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
33
+
34
+ from transformers.activations import ACT2FN
35
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
36
+ from transformers.modeling_attn_mask_utils import (
37
+ AttentionMaskConverter,
38
+ _prepare_4d_attention_mask,
39
+ _prepare_4d_causal_attention_mask
40
+ )
41
+ from transformers.modeling_outputs import (
42
+ BaseModelOutputWithPast,
43
+ CausalLMOutputWithPast,
44
+ SequenceClassifierOutputWithPast,
45
+ TokenClassifierOutput,
46
+ )
47
+ from transformers.modeling_utils import PreTrainedModel
48
+ from transformers.utils import (
49
+ add_start_docstrings,
50
+ add_start_docstrings_to_model_forward,
51
+ is_flash_attn_2_available,
52
+ is_flash_attn_greater_or_equal_2_10,
53
+ logging,
54
+ replace_return_docstrings,
55
+ )
56
+ from .configuration_edgellm import EdgellmConfig
57
+
58
+
59
+ if is_flash_attn_2_available():
60
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
61
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
62
+
63
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
64
+
65
+
66
+ logger = logging.get_logger(__name__)
67
+
68
+
69
+ _CHECKPOINT_FOR_DOC = "Edgellm/Edgellm-7B-beta"
70
+ _CONFIG_FOR_DOC = "EdgellmConfig"
71
+
72
+
73
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
74
+ def _get_unpad_data(attention_mask):
75
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
76
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
77
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
78
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
79
+ return (
80
+ indices,
81
+ cu_seqlens,
82
+ max_seqlen_in_batch,
83
+ )
84
+
85
+ class IdentityOperation(nn.Module):
86
+ def __init__(self):
87
+ super(IdentityOperation, self).__init__()
88
+
89
+ def forward(self, x):
90
+ return x
91
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Edgellm
92
+ class EdgellmRMSNorm(nn.Module):
93
+ def __init__(self, hidden_size, eps=1e-6):
94
+ """
95
+ EdgellmRMSNorm is equivalent to T5LayerNorm
96
+ """
97
+ super().__init__()
98
+ self.weight = nn.Parameter(torch.ones(hidden_size))
99
+ self.variance_epsilon = eps
100
+
101
+ def forward(self, hidden_states):
102
+ input_dtype = hidden_states.dtype
103
+ hidden_states = hidden_states.to(torch.float32)
104
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
105
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
106
+ # return self.weight * hidden_states.to(input_dtype)
107
+ return (self.weight.to(torch.float32) * hidden_states).to(input_dtype)
108
+
109
+
110
+ # Copied from transformers.models.mixtral.modeling_mixtral.MixtralRotaryEmbedding with Mixtral->Edgellm
111
+ class EdgellmRotaryEmbedding(nn.Module):
112
+ def __init__(self, dim, max_position_embeddings=4096, base=100000, device=None):
113
+ super().__init__()
114
+ self.dim = dim
115
+ self.max_position_embeddings = max_position_embeddings
116
+ self.base = base
117
+ inv_freq = 1.0 / (
118
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
119
+ )
120
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
121
+
122
+ # Build here to make `torch.jit.trace` work.
123
+ self._set_cos_sin_cache(
124
+ seq_len=max_position_embeddings,
125
+ device=self.inv_freq.device,
126
+ dtype=torch.get_default_dtype(),
127
+ )
128
+ self.max_seq_len_cached = None
129
+
130
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
131
+ self.max_seq_len_cached = seq_len
132
+ t = torch.arange(
133
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
134
+ )
135
+
136
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
137
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
138
+ emb = torch.cat((freqs, freqs), dim=-1)
139
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
140
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
141
+
142
+ def forward(self, x, seq_len=None):
143
+ # x: [bs, num_attention_heads, seq_len, head_size]
144
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
145
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
146
+
147
+ return (
148
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
149
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
150
+ )
151
+
152
+
153
+ class EdgellmLinearScalingRotaryEmbedding(EdgellmRotaryEmbedding):
154
+ """EdgellmRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
155
+
156
+ def __init__(
157
+ self,
158
+ dim,
159
+ max_position_embeddings=2048,
160
+ base=10000,
161
+ device=None,
162
+ scaling_factor=1.0,
163
+ ):
164
+ self.scaling_factor = scaling_factor
165
+ super().__init__(dim, max_position_embeddings, base, device)
166
+
167
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
168
+ self.max_seq_len_cached = seq_len
169
+ t = torch.arange(
170
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
171
+ )
172
+ t = t / self.scaling_factor
173
+
174
+ freqs = torch.outer(t, self.inv_freq)
175
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
176
+ emb = torch.cat((freqs, freqs), dim=-1)
177
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
178
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
179
+
180
+
181
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->Edgellm
182
+ class EdgellmDynamicNTKScalingRotaryEmbedding(EdgellmRotaryEmbedding):
183
+ """EdgellmRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
184
+
185
+ def __init__(
186
+ self,
187
+ dim,
188
+ max_position_embeddings=2048,
189
+ base=10000,
190
+ device=None,
191
+ scaling_factor=1.0,
192
+ ):
193
+ self.scaling_factor = scaling_factor
194
+ super().__init__(dim, max_position_embeddings, base, device)
195
+
196
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
197
+ self.max_seq_len_cached = seq_len
198
+
199
+ if seq_len > self.max_position_embeddings:
200
+ base = self.base * (
201
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
202
+ - (self.scaling_factor - 1)
203
+ ) ** (self.dim / (self.dim - 2))
204
+ inv_freq = 1.0 / (
205
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
206
+ )
207
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
208
+
209
+ t = torch.arange(
210
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
211
+ )
212
+
213
+ freqs = torch.outer(t, self.inv_freq)
214
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
215
+ emb = torch.cat((freqs, freqs), dim=-1)
216
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
217
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
218
+
219
+
220
+ # Inverse dim formula to find dim based on number of rotations
221
+ def yarn_find_correction_dim(
222
+ num_rotations, dim, base=10000, max_position_embeddings=2048
223
+ ):
224
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
225
+ 2 * math.log(base)
226
+ )
227
+
228
+
229
+ # Find dim range bounds based on rotations
230
+ def yarn_find_correction_range(
231
+ low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
232
+ ):
233
+ low = math.floor(
234
+ yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
235
+ )
236
+ high = math.ceil(
237
+ yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
238
+ )
239
+ return max(low, 0), min(high, dim - 1) # Clamp values just in case
240
+
241
+
242
+ def yarn_get_mscale(scale=1, mscale=1):
243
+ if scale <= 1:
244
+ return 1.0
245
+ return 0.1 * mscale * math.log(scale) + 1.0
246
+
247
+
248
+ def yarn_linear_ramp_mask(min, max, dim):
249
+ if min == max:
250
+ max += 0.001 # Prevent singularity
251
+
252
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
253
+ ramp_func = torch.clamp(linear_func, 0, 1)
254
+ return ramp_func
255
+
256
+
257
+ class EdgellmYarnRotaryEmbedding(EdgellmRotaryEmbedding):
258
+
259
+ def __init__(
260
+ self,
261
+ dim,
262
+ max_position_embeddings=2048,
263
+ base=10000,
264
+ device=None,
265
+ scaling_factor=1.0,
266
+ original_max_position_embeddings=4096,
267
+ beta_fast=32,
268
+ beta_slow=1,
269
+ mscale=1,
270
+ mscale_all_dim=0,
271
+ ):
272
+ self.scaling_factor = scaling_factor
273
+ self.original_max_position_embeddings = original_max_position_embeddings
274
+ self.beta_fast = beta_fast
275
+ self.beta_slow = beta_slow
276
+ self.mscale = mscale
277
+ self.mscale_all_dim = mscale_all_dim
278
+ super().__init__(dim, max_position_embeddings, base, device)
279
+
280
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
281
+ self.max_seq_len_cached = seq_len
282
+ dim = self.dim
283
+
284
+ freq_extra = 1.0 / (
285
+ self.base
286
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
287
+ )
288
+ freq_inter = 1.0 / (
289
+ self.scaling_factor
290
+ * self.base
291
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
292
+ )
293
+
294
+ low, high = yarn_find_correction_range(
295
+ self.beta_fast,
296
+ self.beta_slow,
297
+ dim,
298
+ self.base,
299
+ self.original_max_position_embeddings,
300
+ )
301
+ inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
302
+ device=device, dtype=torch.float32
303
+ )
304
+ inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
305
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
306
+
307
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
308
+
309
+ freqs = torch.outer(t, inv_freq)
310
+
311
+ _mscale = float(
312
+ yarn_get_mscale(self.scaling_factor, self.mscale)
313
+ / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
314
+ )
315
+
316
+ emb = torch.cat((freqs, freqs), dim=-1)
317
+ self.register_buffer(
318
+ "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
319
+ )
320
+ self.register_buffer(
321
+ "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
322
+ )
323
+
324
+
325
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
326
+ def rotate_half(x):
327
+ """Rotates half the hidden dims of the input."""
328
+ x1 = x[..., : x.shape[-1] // 2]
329
+ x2 = x[..., x.shape[-1] // 2 :]
330
+ return torch.cat((-x2, x1), dim=-1)
331
+
332
+
333
+ # Copied from transformers.models.mixtral.modeling_mixtral.apply_rotary_pos_emb
334
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
335
+ """Applies Rotary Position Embedding to the query and key tensors.
336
+
337
+ Args:
338
+ q (`torch.Tensor`): The query tensor.
339
+ k (`torch.Tensor`): The key tensor.
340
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
341
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
342
+ position_ids (`torch.Tensor`):
343
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
344
+ used to pass offsetted position ids when working with a KV-cache.
345
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
346
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
347
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
348
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
349
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
350
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
351
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
352
+ Returns:
353
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
354
+ """
355
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
356
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
357
+
358
+ b, h, s, d = q.shape
359
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
360
+
361
+ b, h, s, d = k.shape
362
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
363
+
364
+ q_embed = (q * cos) + (rotate_half(q) * sin)
365
+ k_embed = (k * cos) + (rotate_half(k) * sin)
366
+ return q_embed, k_embed
367
+
368
+
369
+ class EdgellmMLP(nn.Module):
370
+ def __init__(self, config):
371
+ super().__init__()
372
+ self.hidden_size = config.hidden_size
373
+ self.intermediate_size = config.intermediate_size
374
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
375
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
376
+ self.act_fn = ACT2FN[config.hidden_act]
377
+
378
+ def forward(self, hidden_state):
379
+ h = self.up_proj(hidden_state)
380
+ h = self.act_fn(h)
381
+ h = self.down_proj(h)
382
+ return h
383
+
384
+
385
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
386
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
387
+ """
388
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
389
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
390
+ """
391
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
392
+ if n_rep == 1:
393
+ return hidden_states
394
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
395
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
396
+
397
+
398
+ # Copied from https://huggingface.co/deepseek-ai/DeepSeek-V2-Lite/blob/main/modeling_deepseek.py
399
+ # DeepseekV2Attention with DeepseekV2->Edgellm
400
+
401
+ class EdgellmAttention(nn.Module):
402
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
403
+
404
+ def __init__(self, config, layer_idx: Optional[int] = None):
405
+ super().__init__()
406
+ self.config = config
407
+ self.layer_idx = layer_idx
408
+ if layer_idx is None:
409
+ logger.warning_once(
410
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
411
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
412
+ "when creating this class."
413
+ )
414
+
415
+ self.attention_dropout = config.attention_dropout
416
+ self.hidden_size = config.hidden_size
417
+ self.num_heads = config.num_attention_heads
418
+
419
+ self.max_position_embeddings = config.max_position_embeddings
420
+ self.rope_theta = config.rope_theta
421
+ self.q_lora_rank = config.q_lora_rank
422
+ self.qk_rope_head_dim = config.qk_rope_head_dim
423
+ self.kv_lora_rank = config.kv_lora_rank
424
+ self.v_head_dim = config.v_head_dim
425
+ self.qk_nope_head_dim = config.qk_nope_head_dim
426
+ self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
427
+ self.attn_in = IdentityOperation()
428
+ self.attn_out = IdentityOperation()
429
+
430
+ self.is_causal = True
431
+
432
+ if self.q_lora_rank is None:
433
+ self.q_proj = nn.Linear(
434
+ self.hidden_size, self.num_heads * self.q_head_dim, bias=False
435
+ ) # 2048 16 192
436
+ else:
437
+ self.q_a_proj = nn.Linear(
438
+ self.hidden_size, config.q_lora_rank, bias=config.attention_bias
439
+ )
440
+ self.q_a_layernorm = EdgellmRMSNorm(config.q_lora_rank)
441
+ self.q_b_proj = nn.Linear(
442
+ config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
443
+ )
444
+
445
+ self.kv_a_proj_with_mqa = nn.Linear(
446
+ self.hidden_size,
447
+ config.kv_lora_rank + config.qk_rope_head_dim,
448
+ bias=config.attention_bias,
449
+ ) # 2048 512 64
450
+ self.kv_a_layernorm = EdgellmRMSNorm(config.kv_lora_rank)
451
+ self.kv_b_proj = nn.Linear(
452
+ config.kv_lora_rank,
453
+ self.num_heads
454
+ * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
455
+ bias=False,
456
+ ) #512
457
+ # breakpoint()
458
+ self.o_proj = nn.Linear(
459
+ self.num_heads * self.v_head_dim,
460
+ self.hidden_size,
461
+ bias=config.attention_bias,
462
+ ) # 16 128 2048
463
+ self._init_rope()
464
+
465
+ self.softmax_scale = self.q_head_dim ** (-0.5) # sqrt 1/192
466
+
467
+
468
+ def _init_rope(self):
469
+ if self.config.rope_scaling is None:
470
+ self.rotary_emb = EdgellmRotaryEmbedding(
471
+ self.qk_rope_head_dim,
472
+ max_position_embeddings=self.max_position_embeddings,
473
+ base=self.rope_theta,
474
+ )
475
+ else:
476
+ scaling_type = self.config.rope_scaling["type"]
477
+ scaling_factor = self.config.rope_scaling["factor"]
478
+ if scaling_type == "linear":
479
+ self.rotary_emb = DeepseekV2LinearScalingRotaryEmbedding(
480
+ self.qk_rope_head_dim,
481
+ max_position_embeddings=self.max_position_embeddings,
482
+ scaling_factor=scaling_factor,
483
+ base=self.rope_theta,
484
+ )
485
+ elif scaling_type == "dynamic":
486
+ self.rotary_emb = DeepseekV2DynamicNTKScalingRotaryEmbedding(
487
+ self.qk_rope_head_dim,
488
+ max_position_embeddings=self.max_position_embeddings,
489
+ scaling_factor=scaling_factor,
490
+ base=self.rope_theta,
491
+ )
492
+ elif scaling_type == "yarn":
493
+ kwargs = {
494
+ key: self.config.rope_scaling[key]
495
+ for key in [
496
+ "original_max_position_embeddings",
497
+ "beta_fast",
498
+ "beta_slow",
499
+ "mscale",
500
+ "mscale_all_dim",
501
+ ]
502
+ if key in self.config.rope_scaling
503
+ }
504
+ self.rotary_emb = DeepseekV2YarnRotaryEmbedding(
505
+ self.qk_rope_head_dim,
506
+ max_position_embeddings=self.max_position_embeddings,
507
+ scaling_factor=scaling_factor,
508
+ base=self.rope_theta,
509
+ **kwargs,
510
+ )
511
+ else:
512
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
513
+
514
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
515
+ return (
516
+ tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
517
+ .transpose(1, 2)
518
+ .contiguous()
519
+ )
520
+
521
+ def forward(
522
+ self,
523
+ hidden_states: torch.Tensor,
524
+ attention_mask: Optional[torch.Tensor] = None,
525
+ position_ids: Optional[torch.LongTensor] = None,
526
+ past_key_value: Optional[Cache] = None,
527
+ output_attentions: bool = False,
528
+ use_cache: bool = False,
529
+ **kwargs,
530
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
531
+ if "padding_mask" in kwargs:
532
+ warnings.warn(
533
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
534
+ )
535
+ bsz, q_len, _ = hidden_states.size()
536
+
537
+ if self.q_lora_rank is None:
538
+ q = self.q_proj(hidden_states) # 9,2048 -> 3072, 16 * 192
539
+ else:
540
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
541
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)#[1, 16, 9, 192])
542
+ q_nope, q_pe = torch.split(
543
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
544
+ )# [1, 16, 9, 128] [1, 16, 9, 64]
545
+
546
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states) # 1 9 576
547
+ compressed_kv, k_pe = torch.split(
548
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
549
+ )# 512 64
550
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)# [1, 1, 9, 64])
551
+ kv = (
552
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
553
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
554
+ .transpose(1, 2)
555
+ )
556
+ # 1 16 9 256
557
+ k_nope, value_states = torch.split(
558
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
559
+ ) # 1 16 9 128, 1 16 9 128
560
+ kv_seq_len = value_states.shape[-2]
561
+ if past_key_value is not None:
562
+ if self.layer_idx is None:
563
+ raise ValueError(
564
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
565
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
566
+ "with a layer index."
567
+ )
568
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
569
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
570
+
571
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
572
+
573
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)# ([1, 16, 9, 192])
574
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
575
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
576
+
577
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
578
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
579
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
580
+ if past_key_value is not None:
581
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
582
+ key_states, value_states = past_key_value.update(
583
+ key_states, value_states, self.layer_idx, cache_kwargs
584
+ )
585
+
586
+ attn_weights = (
587
+ torch.matmul(query_states, key_states.transpose(2, 3)) * self.softmax_scale
588
+ )
589
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
590
+ raise ValueError(
591
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
592
+ f" {attn_weights.size()}"
593
+ )
594
+ if attention_mask is not None:
595
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
596
+ raise ValueError(
597
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
598
+ )
599
+
600
+ attn_weights = attn_weights + attention_mask
601
+ attn_weights = nn.functional.softmax(
602
+ attn_weights, dim=-1, dtype=torch.float32
603
+ ).to(query_states.dtype)
604
+ attn_weights = nn.functional.dropout(
605
+ attn_weights, p=self.attention_dropout, training=self.training
606
+ )
607
+ attn_output = torch.matmul(attn_weights, value_states)
608
+
609
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
610
+ raise ValueError(
611
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
612
+ f" {attn_output.size()}"
613
+ )
614
+ attn_output = attn_output.transpose(1, 2).contiguous()
615
+
616
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
617
+
618
+ attn_output = self.o_proj(attn_output)
619
+
620
+ if not output_attentions:
621
+ attn_weights = None
622
+
623
+ return attn_output, attn_weights, past_key_value
624
+
625
+
626
+ class EdgellmFlashAttention2(EdgellmAttention):
627
+ """
628
+ DeepseekV2 flash attention module. This module inherits from `DeepseekV2Attention` as the weights of the module stays
629
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
630
+ flash attention and deal with padding tokens in case the input contains any of them.
631
+ """
632
+
633
+ def __init__(self, *args, **kwargs):
634
+ super().__init__(*args, **kwargs)
635
+
636
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
637
+ # 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.
638
+ # 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).
639
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
640
+
641
+ def forward(
642
+ self,
643
+ hidden_states: torch.Tensor,
644
+ attention_mask: Optional[torch.LongTensor] = None,
645
+ position_ids: Optional[torch.LongTensor] = None,
646
+ past_key_value: Optional[Cache] = None,
647
+ output_attentions: bool = False,
648
+ use_cache: bool = False,
649
+ **kwargs,
650
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
651
+ # DeepseekV2FlashAttention2 attention does not support output_attentions
652
+
653
+ if "padding_mask" in kwargs:
654
+ warnings.warn(
655
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
656
+ )
657
+
658
+ # overwrite attention_mask with padding_mask
659
+ attention_mask = kwargs.pop("padding_mask")
660
+
661
+ output_attentions = False
662
+
663
+ bsz, q_len, _ = hidden_states.size()
664
+
665
+ if self.q_lora_rank is None:
666
+ q = self.q_proj(hidden_states)
667
+ else:
668
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
669
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
670
+ q_nope, q_pe = torch.split(
671
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
672
+ )
673
+
674
+ # Flash attention requires the input to have the shape
675
+ # batch_size x seq_length x head_dim x hidden_dim
676
+ # therefore we just need to keep the original shape
677
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
678
+ compressed_kv, k_pe = torch.split(
679
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
680
+ )
681
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
682
+ kv = (
683
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
684
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
685
+ .transpose(1, 2)
686
+ )
687
+
688
+ k_nope, value_states = torch.split(
689
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
690
+ )
691
+ kv_seq_len = value_states.shape[-2]
692
+
693
+ kv_seq_len = value_states.shape[-2]
694
+ if past_key_value is not None:
695
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
696
+
697
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
698
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
699
+
700
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
701
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
702
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
703
+
704
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
705
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
706
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
707
+
708
+ if self.q_head_dim != self.v_head_dim:
709
+ value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
710
+
711
+ if past_key_value is not None:
712
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
713
+ key_states, value_states = past_key_value.update(
714
+ key_states, value_states, self.layer_idx, cache_kwargs
715
+ )
716
+
717
+ # 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
718
+ # to be able to avoid many of these transpose/reshape/view.
719
+ query_states = query_states.transpose(1, 2)
720
+ key_states = key_states.transpose(1, 2)
721
+ value_states = value_states.transpose(1, 2)
722
+
723
+ dropout_rate = self.attention_dropout if self.training else 0.0
724
+
725
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
726
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
727
+ # cast them back in the correct dtype just to be sure everything works as expected.
728
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
729
+ # in fp32. (DeepseekV2RMSNorm handles it correctly)
730
+
731
+ input_dtype = query_states.dtype
732
+ if input_dtype == torch.float32:
733
+ # Handle the case where the model is quantized
734
+ if hasattr(self.config, "_pre_quantization_dtype"):
735
+ target_dtype = self.config._pre_quantization_dtype
736
+ elif torch.is_autocast_enabled():
737
+ target_dtype = torch.get_autocast_gpu_dtype()
738
+ else:
739
+ target_dtype = self.q_proj.weight.dtype if self.q_lora_rank is None else self.q_a_proj.weight.dtype
740
+
741
+ logger.warning_once(
742
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
743
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
744
+ f" {target_dtype}."
745
+ )
746
+
747
+ query_states = query_states.to(target_dtype)
748
+ key_states = key_states.to(target_dtype)
749
+ value_states = value_states.to(target_dtype)
750
+ # breakpoint()
751
+ attn_output = self._flash_attention_forward(
752
+ query_states,
753
+ key_states,
754
+ value_states,
755
+ attention_mask,
756
+ q_len,
757
+ dropout=dropout_rate,
758
+ softmax_scale=self.softmax_scale,
759
+ )
760
+ if self.q_head_dim != self.v_head_dim:
761
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
762
+
763
+ attn_output = attn_output.reshape(
764
+ bsz, q_len, self.num_heads * self.v_head_dim
765
+ ).contiguous()
766
+ # torch.save(attn_output, "./hf-attn_output_b_821.pt")
767
+ # breakpoint()
768
+ attn_output = self.o_proj(attn_output)
769
+ # torch.save(attn_output, "./hf-attn_output_821.pt")
770
+ # breakpoint()
771
+ if not output_attentions:
772
+ attn_weights = None
773
+
774
+ return attn_output, attn_weights, past_key_value
775
+
776
+ def _flash_attention_forward(
777
+ self,
778
+ query_states,
779
+ key_states,
780
+ value_states,
781
+ attention_mask,
782
+ query_length,
783
+ dropout=0.0,
784
+ softmax_scale=None,
785
+ ):
786
+ """
787
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
788
+ first unpad the input, then computes the attention scores and pad the final attention scores.
789
+
790
+ Args:
791
+ query_states (`torch.Tensor`):
792
+ Input query states to be passed to Flash Attention API
793
+ key_states (`torch.Tensor`):
794
+ Input key states to be passed to Flash Attention API
795
+ value_states (`torch.Tensor`):
796
+ Input value states to be passed to Flash Attention API
797
+ attention_mask (`torch.Tensor`):
798
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
799
+ position of padding tokens and 1 for the position of non-padding tokens.
800
+ dropout (`int`, *optional*):
801
+ Attention dropout
802
+ softmax_scale (`float`, *optional*):
803
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
804
+ """
805
+
806
+ if not self._flash_attn_uses_top_left_mask:
807
+ causal = self.is_causal
808
+ else:
809
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in DeepseekV2FlashAttention2 __init__.
810
+ causal = self.is_causal and query_length != 1
811
+
812
+ # Contains at least one padding token in the sequence
813
+ if attention_mask is not None:
814
+ batch_size = query_states.shape[0]
815
+ (
816
+ query_states,
817
+ key_states,
818
+ value_states,
819
+ indices_q,
820
+ cu_seq_lens,
821
+ max_seq_lens,
822
+ ) = self._upad_input(
823
+ query_states, key_states, value_states, attention_mask, query_length
824
+ )
825
+
826
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
827
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
828
+
829
+ attn_output_unpad = flash_attn_varlen_func(
830
+ query_states,
831
+ key_states,
832
+ value_states,
833
+ cu_seqlens_q=cu_seqlens_q,
834
+ cu_seqlens_k=cu_seqlens_k,
835
+ max_seqlen_q=max_seqlen_in_batch_q,
836
+ max_seqlen_k=max_seqlen_in_batch_k,
837
+ dropout_p=dropout,
838
+ softmax_scale=softmax_scale,
839
+ causal=causal,
840
+ )
841
+
842
+ attn_output = pad_input(
843
+ attn_output_unpad, indices_q, batch_size, query_length
844
+ )
845
+ else:
846
+ attn_output = flash_attn_func(
847
+ query_states,
848
+ key_states,
849
+ value_states,
850
+ dropout,
851
+ softmax_scale=softmax_scale,
852
+ causal=causal,
853
+ )
854
+
855
+ return attn_output
856
+
857
+ def _upad_input(
858
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
859
+ ):
860
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
861
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
862
+
863
+ key_layer = index_first_axis(
864
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
865
+ indices_k,
866
+ )
867
+ value_layer = index_first_axis(
868
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
869
+ indices_k,
870
+ )
871
+ if query_length == kv_seq_len:
872
+ query_layer = index_first_axis(
873
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
874
+ indices_k,
875
+ )
876
+ cu_seqlens_q = cu_seqlens_k
877
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
878
+ indices_q = indices_k
879
+ elif query_length == 1:
880
+ max_seqlen_in_batch_q = 1
881
+ cu_seqlens_q = torch.arange(
882
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
883
+ ) # There is a memcpy here, that is very bad.
884
+ indices_q = cu_seqlens_q[:-1]
885
+ query_layer = query_layer.squeeze(1)
886
+ else:
887
+ # The -q_len: slice assumes left padding.
888
+ attention_mask = attention_mask[:, -query_length:]
889
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
890
+ query_layer, attention_mask
891
+ )
892
+
893
+ return (
894
+ query_layer,
895
+ key_layer,
896
+ value_layer,
897
+ indices_q,
898
+ (cu_seqlens_q, cu_seqlens_k),
899
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
900
+ )
901
+ Edgellm_ATTENTION_CLASSES = {
902
+ "eager": EdgellmAttention,
903
+ "flash_attention_2": EdgellmFlashAttention2,
904
+ }
905
+
906
+
907
+ class EdgellmDecoderLayer(nn.Module):
908
+ def __init__(self, config: EdgellmConfig, layer_idx: int):
909
+ super().__init__()
910
+ self.hidden_size = config.hidden_size
911
+
912
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
913
+ logger.warning_once(
914
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
915
+ "unexpected results may be encountered."
916
+ )
917
+ self.self_attn = Edgellm_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
918
+ self.mlp = EdgellmMLP(config)
919
+ self.input_layernorm = EdgellmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
920
+ self.post_attention_layernorm = EdgellmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
921
+
922
+ def forward(
923
+ self,
924
+ hidden_states: torch.Tensor,
925
+ attention_mask: Optional[torch.Tensor] = None,
926
+ position_ids: Optional[torch.LongTensor] = None,
927
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
928
+ output_attentions: Optional[bool] = False,
929
+ use_cache: Optional[bool] = False,
930
+ cache_position: Optional[torch.LongTensor] = None,
931
+ **kwargs,
932
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
933
+ """
934
+ Args:
935
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
936
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
937
+ `(batch, sequence_length)` where padding elements are indicated by 0.
938
+ output_attentions (`bool`, *optional*):
939
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
940
+ returned tensors for more detail.
941
+ use_cache (`bool`, *optional*):
942
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
943
+ (see `past_key_values`).
944
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
945
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
946
+ Indices depicting the position of the input sequence tokens in the sequence.
947
+ kwargs (`dict`, *optional*):
948
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
949
+ into the model
950
+ """
951
+
952
+ residual = hidden_states
953
+
954
+ hidden_states = self.input_layernorm(hidden_states)
955
+
956
+ # Self Attention
957
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
958
+ hidden_states=hidden_states,
959
+ attention_mask=attention_mask,
960
+ position_ids=position_ids,
961
+ past_key_value=past_key_value,
962
+ output_attentions=output_attentions,
963
+ use_cache=use_cache,
964
+ cache_position=cache_position,
965
+ )
966
+ hidden_states = residual + hidden_states
967
+
968
+ # Fully Connected
969
+ residual = hidden_states
970
+ hidden_states = self.post_attention_layernorm(hidden_states)
971
+ hidden_states = self.mlp(hidden_states)
972
+ hidden_states = residual + hidden_states
973
+
974
+ outputs = (hidden_states,)
975
+
976
+ if output_attentions:
977
+ outputs += (self_attn_weights,)
978
+
979
+ if use_cache:
980
+ outputs += (present_key_value,)
981
+
982
+ return outputs
983
+
984
+
985
+ Edgellm_START_DOCSTRING = r"""
986
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
987
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
988
+ etc.)
989
+
990
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
991
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
992
+ and behavior.
993
+
994
+ Parameters:
995
+ config ([`EdgellmConfig`]):
996
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
997
+ load the weights associated with the model, only the configuration. Check out the
998
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
999
+ """
1000
+
1001
+
1002
+ @add_start_docstrings(
1003
+ "The bare Edgellm Model outputting raw hidden-states without any specific head on top.",
1004
+ Edgellm_START_DOCSTRING,
1005
+ )
1006
+ class EdgellmPreTrainedModel(PreTrainedModel):
1007
+ config_class = EdgellmConfig
1008
+ base_model_prefix = "model"
1009
+ supports_gradient_checkpointing = True
1010
+ _no_split_modules = ["EdgellmDecoderLayer"]
1011
+ _skip_keys_device_placement = "past_key_values"
1012
+ _supports_flash_attn_2 = True
1013
+ _supports_cache_class = True
1014
+
1015
+ def _init_weights(self, module):
1016
+ std = self.config.initializer_range
1017
+ if isinstance(module, nn.Linear):
1018
+ module.weight.data.normal_(mean=0.0, std=std)
1019
+ if module.bias is not None:
1020
+ module.bias.data.zero_()
1021
+ elif isinstance(module, nn.Embedding):
1022
+ module.weight.data.normal_(mean=0.0, std=std)
1023
+ if module.padding_idx is not None:
1024
+ module.weight.data[module.padding_idx].zero_()
1025
+
1026
+
1027
+ Edgellm_INPUTS_DOCSTRING = r"""
1028
+ Args:
1029
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1030
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1031
+ it.
1032
+
1033
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1034
+ [`PreTrainedTokenizer.__call__`] for details.
1035
+
1036
+ [What are input IDs?](../glossary#input-ids)
1037
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1038
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1039
+
1040
+ - 1 for tokens that are **not masked**,
1041
+ - 0 for tokens that are **masked**.
1042
+
1043
+ [What are attention masks?](../glossary#attention-mask)
1044
+
1045
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1046
+ [`PreTrainedTokenizer.__call__`] for details.
1047
+
1048
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
1049
+ `past_key_values`).
1050
+
1051
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1052
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1053
+ information on the default strategy.
1054
+
1055
+ - 1 indicates the head is **not masked**,
1056
+ - 0 indicates the head is **masked**.
1057
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1058
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1059
+ config.n_positions - 1]`.
1060
+
1061
+ [What are position IDs?](../glossary#position-ids)
1062
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1063
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1064
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1065
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1066
+
1067
+ Two formats are allowed:
1068
+ - a [`~cache_utils.Cache`] instance;
1069
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1070
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1071
+ cache format.
1072
+
1073
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1074
+ legacy cache format will be returned.
1075
+
1076
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1077
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1078
+ of shape `(batch_size, sequence_length)`.
1079
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1080
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1081
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1082
+ model's internal embedding lookup matrix.
1083
+ use_cache (`bool`, *optional*):
1084
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1085
+ `past_key_values`).
1086
+ output_attentions (`bool`, *optional*):
1087
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1088
+ tensors for more detail.
1089
+ output_hidden_states (`bool`, *optional*):
1090
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1091
+ more detail.
1092
+ return_dict (`bool`, *optional*):
1093
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1094
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
1095
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
1096
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
1097
+ the complete sequence length.
1098
+ """
1099
+
1100
+
1101
+ @add_start_docstrings(
1102
+ "The bare Edgellm Model outputting raw hidden-states without any specific head on top.",
1103
+ Edgellm_START_DOCSTRING,
1104
+ )
1105
+ class EdgellmModel(EdgellmPreTrainedModel):
1106
+ """
1107
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`EdgellmDecoderLayer`]
1108
+
1109
+ Args:
1110
+ config: EdgellmConfig
1111
+ """
1112
+
1113
+ def __init__(self, config: EdgellmConfig):
1114
+ super().__init__(config)
1115
+ self.padding_idx = config.pad_token_id
1116
+ self.vocab_size = config.vocab_size
1117
+
1118
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1119
+ self.layers = nn.ModuleList(
1120
+ [EdgellmDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1121
+ )
1122
+ self._attn_implementation = config._attn_implementation
1123
+ self.norm = EdgellmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1124
+
1125
+ self.gradient_checkpointing = False
1126
+ # Initialize weights and apply final processing
1127
+ self.post_init()
1128
+
1129
+ def get_input_embeddings(self):
1130
+ return self.embed_tokens
1131
+
1132
+ def set_input_embeddings(self, value):
1133
+ self.embed_tokens = value
1134
+
1135
+ @add_start_docstrings_to_model_forward(Edgellm_INPUTS_DOCSTRING)
1136
+ def forward(
1137
+ self,
1138
+ input_ids: torch.LongTensor = None,
1139
+ attention_mask: Optional[torch.Tensor] = None,
1140
+ position_ids: Optional[torch.LongTensor] = None,
1141
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1142
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1143
+ use_cache: Optional[bool] = None,
1144
+ output_attentions: Optional[bool] = None,
1145
+ output_hidden_states: Optional[bool] = None,
1146
+ return_dict: Optional[bool] = None,
1147
+ cache_position: Optional[torch.LongTensor] = None,
1148
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1149
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1150
+ output_hidden_states = (
1151
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1152
+ )
1153
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1154
+
1155
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1156
+
1157
+ # retrieve input_ids and inputs_embeds
1158
+ if (input_ids is None) ^ (inputs_embeds is not None):
1159
+ raise ValueError(
1160
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
1161
+ )
1162
+ elif input_ids is not None:
1163
+ batch_size, seq_length = input_ids.shape[:2]
1164
+ elif inputs_embeds is not None:
1165
+ batch_size, seq_length = inputs_embeds.shape[:2]
1166
+ else:
1167
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1168
+
1169
+ if self.gradient_checkpointing and self.training:
1170
+ if use_cache:
1171
+ logger.warning_once(
1172
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1173
+ )
1174
+ use_cache = False
1175
+
1176
+ past_key_values_length = 0
1177
+ if use_cache:
1178
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1179
+ if use_legacy_cache:
1180
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1181
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1182
+
1183
+ if inputs_embeds is None:
1184
+ inputs_embeds = self.embed_tokens(input_ids)
1185
+
1186
+ if cache_position is None:
1187
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1188
+ cache_position = torch.arange(
1189
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1190
+ )
1191
+ if position_ids is None:
1192
+ position_ids = cache_position.unsqueeze(0)
1193
+ if self.config._attn_implementation == "flash_attention_2":
1194
+ # 2d mask is passed through the layers
1195
+ attention_mask = (
1196
+ attention_mask
1197
+ if (attention_mask is not None and 0 in attention_mask)
1198
+ else None
1199
+ )
1200
+ else:
1201
+ # 4d mask is passed through the layers
1202
+ attention_mask = _prepare_4d_causal_attention_mask(
1203
+ attention_mask,
1204
+ (batch_size, seq_length),
1205
+ inputs_embeds,
1206
+ past_key_values_length,
1207
+ )
1208
+
1209
+ hidden_states = inputs_embeds
1210
+
1211
+ # decoder layers
1212
+ all_hidden_states = () if output_hidden_states else None
1213
+ all_self_attns = () if output_attentions else None
1214
+ next_decoder_cache = None
1215
+
1216
+ for decoder_layer in self.layers:
1217
+ if output_hidden_states:
1218
+ all_hidden_states += (hidden_states,)
1219
+
1220
+ if self.gradient_checkpointing and self.training:
1221
+ layer_outputs = self._gradient_checkpointing_func(
1222
+ decoder_layer.__call__,
1223
+ hidden_states,
1224
+ attention_mask,
1225
+ position_ids,
1226
+ past_key_values,
1227
+ output_attentions,
1228
+ use_cache,
1229
+ cache_position,
1230
+ )
1231
+ else:
1232
+ layer_outputs = decoder_layer(
1233
+ hidden_states,
1234
+ attention_mask=attention_mask,
1235
+ position_ids=position_ids,
1236
+ past_key_value=past_key_values,
1237
+ output_attentions=output_attentions,
1238
+ use_cache=use_cache,
1239
+ cache_position=cache_position,
1240
+ )
1241
+
1242
+ hidden_states = layer_outputs[0]
1243
+
1244
+ if use_cache:
1245
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1246
+
1247
+ if output_attentions:
1248
+ all_self_attns += (layer_outputs[1],)
1249
+
1250
+ hidden_states = self.norm(hidden_states)
1251
+
1252
+ # add hidden states from the last decoder layer
1253
+ if output_hidden_states:
1254
+ all_hidden_states += (hidden_states,)
1255
+
1256
+ next_cache = None
1257
+ if use_cache:
1258
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1259
+
1260
+ if not return_dict:
1261
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1262
+ return BaseModelOutputWithPast(
1263
+ last_hidden_state=hidden_states,
1264
+ past_key_values=next_cache,
1265
+ hidden_states=all_hidden_states,
1266
+ attentions=all_self_attns,
1267
+ )
1268
+
1269
+
1270
+ class EdgellmForCausalLM(EdgellmPreTrainedModel):
1271
+ _tied_weights_keys = ["lm_head.weight"]
1272
+
1273
+ def __init__(self, config):
1274
+ super().__init__(config)
1275
+ self.model = EdgellmModel(config)
1276
+ self.vocab_size = config.vocab_size
1277
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1278
+
1279
+ # Initialize weights and apply final processing
1280
+ self.post_init()
1281
+
1282
+ def get_input_embeddings(self):
1283
+ return self.model.embed_tokens
1284
+
1285
+ def set_input_embeddings(self, value):
1286
+ self.model.embed_tokens = value
1287
+
1288
+ def get_output_embeddings(self):
1289
+ return self.lm_head
1290
+
1291
+ def set_output_embeddings(self, new_embeddings):
1292
+ self.lm_head = new_embeddings
1293
+
1294
+ def set_decoder(self, decoder):
1295
+ self.model = decoder
1296
+
1297
+ def get_decoder(self):
1298
+ return self.model
1299
+
1300
+ @add_start_docstrings_to_model_forward(Edgellm_INPUTS_DOCSTRING)
1301
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1302
+ def forward(
1303
+ self,
1304
+ input_ids: torch.LongTensor = None,
1305
+ attention_mask: Optional[torch.Tensor] = None,
1306
+ position_ids: Optional[torch.LongTensor] = None,
1307
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1308
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1309
+ labels: Optional[torch.LongTensor] = None,
1310
+ use_cache: Optional[bool] = None,
1311
+ output_attentions: Optional[bool] = None,
1312
+ output_hidden_states: Optional[bool] = None,
1313
+ return_dict: Optional[bool] = None,
1314
+ cache_position: Optional[torch.LongTensor] = None,
1315
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1316
+ r"""
1317
+ Args:
1318
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1319
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1320
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1321
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1322
+
1323
+ Returns:
1324
+
1325
+ Example:
1326
+
1327
+ ```python
1328
+ >>> from transformers import AutoTokenizer, EdgellmForCausalLM
1329
+
1330
+ >>> model = EdgellmForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1331
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1332
+
1333
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1334
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1335
+
1336
+ >>> # Generate
1337
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1338
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1339
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1340
+ ```"""
1341
+
1342
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1343
+ output_hidden_states = (
1344
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1345
+ )
1346
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1347
+
1348
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1349
+ outputs = self.model(
1350
+ input_ids=input_ids,
1351
+ attention_mask=attention_mask,
1352
+ position_ids=position_ids,
1353
+ past_key_values=past_key_values,
1354
+ inputs_embeds=inputs_embeds,
1355
+ use_cache=use_cache,
1356
+ output_attentions=output_attentions,
1357
+ output_hidden_states=output_hidden_states,
1358
+ return_dict=return_dict,
1359
+ cache_position=cache_position,
1360
+ )
1361
+
1362
+ hidden_states = outputs[0]
1363
+ logits = self.lm_head(hidden_states)
1364
+ logits = logits.float()
1365
+
1366
+ loss = None
1367
+ if labels is not None:
1368
+ # Shift so that tokens < n predict n
1369
+ shift_logits = logits[..., :-1, :].contiguous()
1370
+ shift_labels = labels[..., 1:].contiguous()
1371
+ # Flatten the tokens
1372
+ loss_fct = CrossEntropyLoss()
1373
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1374
+ shift_labels = shift_labels.view(-1)
1375
+ # Enable model parallelism
1376
+ shift_labels = shift_labels.to(shift_logits.device)
1377
+ loss = loss_fct(shift_logits, shift_labels)
1378
+
1379
+ if not return_dict:
1380
+ output = (logits,) + outputs[1:]
1381
+ return (loss,) + output if loss is not None else output
1382
+
1383
+ return CausalLMOutputWithPast(
1384
+ loss=loss,
1385
+ logits=logits,
1386
+ past_key_values=outputs.past_key_values,
1387
+ hidden_states=outputs.hidden_states,
1388
+ attentions=outputs.attentions,
1389
+ )
1390
+
1391
+ def prepare_inputs_for_generation(
1392
+ self,
1393
+ input_ids,
1394
+ past_key_values=None,
1395
+ attention_mask=None,
1396
+ inputs_embeds=None,
1397
+ cache_position=None,
1398
+ use_cache=True,
1399
+ **kwargs,
1400
+ ):
1401
+ past_length = 0
1402
+ # Omit tokens covered by past_key_values
1403
+ if past_key_values is not None:
1404
+ # Past key values are always initialized with a `Cache` object -> no need for if-else anymore
1405
+ past_length = cache_position[0] if cache_position is not None else past_key_values.get_seq_length()
1406
+ max_cache_length = (
1407
+ torch.tensor(past_key_values.get_max_length(), device=input_ids.device)
1408
+ if past_key_values.get_max_length() is not None
1409
+ else None
1410
+ )
1411
+ cache_length = past_length if max_cache_length is None else torch.min(max_cache_length, past_length)
1412
+
1413
+ # Keep only the unprocessed tokens:
1414
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1415
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1416
+ # input)
1417
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1418
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1419
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1420
+ # input_ids based on the past_length.
1421
+ elif past_length < input_ids.shape[1]:
1422
+ input_ids = input_ids[:, past_length:]
1423
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1424
+
1425
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1426
+ if (
1427
+ max_cache_length is not None
1428
+ and attention_mask is not None
1429
+ and cache_length + input_ids.shape[1] > max_cache_length
1430
+ ):
1431
+ attention_mask = attention_mask[:, -max_cache_length:]
1432
+
1433
+ position_ids = kwargs.get("position_ids", None)
1434
+ if attention_mask is not None and position_ids is None:
1435
+ # create position_ids on the fly for batch generation
1436
+ position_ids = attention_mask.long().cumsum(-1) - 1
1437
+ position_ids.masked_fill_(attention_mask == 0, 1)
1438
+ if past_key_values:
1439
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1440
+
1441
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1442
+ if inputs_embeds is not None and past_length == 0:
1443
+ model_inputs = {"inputs_embeds": inputs_embeds}
1444
+ else:
1445
+ model_inputs = {"input_ids": input_ids}
1446
+
1447
+ input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
1448
+ if cache_position is None:
1449
+ cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device)
1450
+ elif use_cache:
1451
+ cache_position = cache_position[-input_length:]
1452
+
1453
+ model_inputs.update(
1454
+ {
1455
+ "position_ids": position_ids,
1456
+ "past_key_values": past_key_values,
1457
+ "use_cache": use_cache,
1458
+ "attention_mask": attention_mask,
1459
+ "cache_position": cache_position,
1460
+ }
1461
+ )
1462
+ return model_inputs
1463
+
1464
+ @staticmethod
1465
+ def _reorder_cache(past_key_values, beam_idx):
1466
+ reordered_past = ()
1467
+ for layer_past in past_key_values:
1468
+ reordered_past += (
1469
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1470
+ )
1471
+ return reordered_past
1472
+
1473
+
1474
+ @add_start_docstrings(
1475
+ """
1476
+ The Edgellm Model transformer with a sequence classification head on top (linear layer).
1477
+
1478
+ [`EdgellmForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1479
+ (e.g. GPT-2) do.
1480
+
1481
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1482
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1483
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1484
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1485
+ each row of the batch).
1486
+ """,
1487
+ Edgellm_START_DOCSTRING,
1488
+ )
1489
+ class EdgellmForSequenceClassification(EdgellmPreTrainedModel):
1490
+ def __init__(self, config):
1491
+ super().__init__(config)
1492
+ self.num_labels = config.num_labels
1493
+ self.model = EdgellmModel(config)
1494
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1495
+
1496
+ # Initialize weights and apply final processing
1497
+ self.post_init()
1498
+
1499
+ def get_input_embeddings(self):
1500
+ return self.model.embed_tokens
1501
+
1502
+ def set_input_embeddings(self, value):
1503
+ self.model.embed_tokens = value
1504
+
1505
+ @add_start_docstrings_to_model_forward(Edgellm_INPUTS_DOCSTRING)
1506
+ def forward(
1507
+ self,
1508
+ input_ids: torch.LongTensor = None,
1509
+ attention_mask: Optional[torch.Tensor] = None,
1510
+ position_ids: Optional[torch.LongTensor] = None,
1511
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1512
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1513
+ labels: Optional[torch.LongTensor] = None,
1514
+ use_cache: Optional[bool] = None,
1515
+ output_attentions: Optional[bool] = None,
1516
+ output_hidden_states: Optional[bool] = None,
1517
+ return_dict: Optional[bool] = None,
1518
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1519
+ r"""
1520
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1521
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1522
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1523
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1524
+ """
1525
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1526
+
1527
+ transformer_outputs = self.model(
1528
+ input_ids,
1529
+ attention_mask=attention_mask,
1530
+ position_ids=position_ids,
1531
+ past_key_values=past_key_values,
1532
+ inputs_embeds=inputs_embeds,
1533
+ use_cache=use_cache,
1534
+ output_attentions=output_attentions,
1535
+ output_hidden_states=output_hidden_states,
1536
+ return_dict=return_dict,
1537
+ )
1538
+ hidden_states = transformer_outputs[0]
1539
+ logits = self.score(hidden_states)
1540
+
1541
+ if input_ids is not None:
1542
+ batch_size = input_ids.shape[0]
1543
+ else:
1544
+ batch_size = inputs_embeds.shape[0]
1545
+
1546
+ if self.config.pad_token_id is None and batch_size != 1:
1547
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1548
+ if self.config.pad_token_id is None:
1549
+ sequence_lengths = -1
1550
+ else:
1551
+ if input_ids is not None:
1552
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1553
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1554
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1555
+ sequence_lengths = sequence_lengths.to(logits.device)
1556
+ else:
1557
+ sequence_lengths = -1
1558
+
1559
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1560
+
1561
+ loss = None
1562
+ if labels is not None:
1563
+ labels = labels.to(logits.device)
1564
+ if self.config.problem_type is None:
1565
+ if self.num_labels == 1:
1566
+ self.config.problem_type = "regression"
1567
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1568
+ self.config.problem_type = "single_label_classification"
1569
+ else:
1570
+ self.config.problem_type = "multi_label_classification"
1571
+
1572
+ if self.config.problem_type == "regression":
1573
+ loss_fct = MSELoss()
1574
+ if self.num_labels == 1:
1575
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1576
+ else:
1577
+ loss = loss_fct(pooled_logits, labels)
1578
+ elif self.config.problem_type == "single_label_classification":
1579
+ loss_fct = CrossEntropyLoss()
1580
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1581
+ elif self.config.problem_type == "multi_label_classification":
1582
+ loss_fct = BCEWithLogitsLoss()
1583
+ loss = loss_fct(pooled_logits, labels)
1584
+ if not return_dict:
1585
+ output = (pooled_logits,) + transformer_outputs[1:]
1586
+ return ((loss,) + output) if loss is not None else output
1587
+
1588
+ return SequenceClassifierOutputWithPast(
1589
+ loss=loss,
1590
+ logits=pooled_logits,
1591
+ past_key_values=transformer_outputs.past_key_values,
1592
+ hidden_states=transformer_outputs.hidden_states,
1593
+ attentions=transformer_outputs.attentions,
1594
+ )
1595
+
1596
+
1597
+ @add_start_docstrings(
1598
+ """
1599
+ The Edgellm Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1600
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1601
+ """,
1602
+ Edgellm_START_DOCSTRING,
1603
+ )
1604
+ # Copied from transformers.models.llama.modeling_llama.LlamaForTokenClassification with Llama->Edgellm, LLAMA->Edgellm
1605
+ class EdgellmForTokenClassification(EdgellmPreTrainedModel):
1606
+ def __init__(self, config):
1607
+ super().__init__(config)
1608
+ self.num_labels = config.num_labels
1609
+ self.model = EdgellmModel(config)
1610
+ if getattr(config, "classifier_dropout", None) is not None:
1611
+ classifier_dropout = config.classifier_dropout
1612
+ elif getattr(config, "hidden_dropout", None) is not None:
1613
+ classifier_dropout = config.hidden_dropout
1614
+ else:
1615
+ classifier_dropout = 0.1
1616
+ self.dropout = nn.Dropout(classifier_dropout)
1617
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1618
+
1619
+ # Initialize weights and apply final processing
1620
+ self.post_init()
1621
+
1622
+ def get_input_embeddings(self):
1623
+ return self.model.embed_tokens
1624
+
1625
+ def set_input_embeddings(self, value):
1626
+ self.model.embed_tokens = value
1627
+
1628
+ @add_start_docstrings_to_model_forward(Edgellm_INPUTS_DOCSTRING)
1629
+ def forward(
1630
+ self,
1631
+ input_ids: Optional[torch.LongTensor] = None,
1632
+ attention_mask: Optional[torch.Tensor] = None,
1633
+ position_ids: Optional[torch.LongTensor] = None,
1634
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1635
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1636
+ labels: Optional[torch.LongTensor] = None,
1637
+ use_cache: Optional[bool] = None,
1638
+ output_attentions: Optional[bool] = None,
1639
+ output_hidden_states: Optional[bool] = None,
1640
+ return_dict: Optional[bool] = None,
1641
+ ) -> Union[Tuple, TokenClassifierOutput]:
1642
+ r"""
1643
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1644
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1645
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1646
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1647
+ """
1648
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1649
+
1650
+ outputs = self.model(
1651
+ input_ids,
1652
+ attention_mask=attention_mask,
1653
+ position_ids=position_ids,
1654
+ past_key_values=past_key_values,
1655
+ inputs_embeds=inputs_embeds,
1656
+ use_cache=use_cache,
1657
+ output_attentions=output_attentions,
1658
+ output_hidden_states=output_hidden_states,
1659
+ return_dict=return_dict,
1660
+ )
1661
+ sequence_output = outputs[0]
1662
+ sequence_output = self.dropout(sequence_output)
1663
+ logits = self.score(sequence_output)
1664
+
1665
+ loss = None
1666
+ if labels is not None:
1667
+ loss_fct = CrossEntropyLoss()
1668
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1669
+
1670
+ if not return_dict:
1671
+ output = (logits,) + outputs[2:]
1672
+ return ((loss,) + output) if loss is not None else output
1673
+
1674
+ return TokenClassifierOutput(
1675
+ loss=loss,
1676
+ logits=logits,
1677
+ hidden_states=outputs.hidden_states,
1678
+ attentions=outputs.attentions,
1679
+ )
1680
+
1681
+
1682
+ # if __name__=="__main__":
1683
+ # from IPython import embed
1684
+ # from transformers import Qwen2Tokenizer
1685
+ # import light_hf_proxy
1686
+ # tokenizer = Qwen2Tokenizer.from_pretrained("Qwen/Qwen2-1.5B")
1687
+ # config = EdgellmConfig.from_pretrained("/data/daven/edge/edgellm/edgellm/config.json" ,attn_implementation="flash_attention_2", torch_dtype=torch.bfloat16)
1688
+ # model = EdgellmForCausalLM(config).to(torch.bfloat16).to("cuda:7")
1689
+ # input_ids = tokenizer(
1690
+ # "Thanks to the generous support from SIGMOD EC, we will provide scholarship awards to selected students attending the WSDM 2024 conference. For awardees attending in-person, the grant will cover the cost of registration + some travel expenses. The awards will be competitive in the sense that not every student will receive a Travel Award. Each awardee will receive a bursary to partially cover the expense to attend the conference in-person. Awardees are expected to register for the main conference using a free-registration code provided with the award notification email and will have to make their own arrangements for travel and accommodation.Awardees are expected to register for the main conference and will have to make their own arrangements for travel and accommodation."
1691
+ # )
1692
+ # sample = torch.tensor([input_ids["input_ids"]]).to("cuda:7") # (1,L)
1693
+
1694
+ # # Step 4: Forward pass through the model
1695
+ # with torch.no_grad():
1696
+ # outputs = model(sample)
1697
+
1698
+ # # Optionally, inspect the outputs
1699
+ # print(outputs)
1700
+
1701
+ # embed()
special_tokens_map.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>"
5
+ ],
6
+ "eos_token": {
7
+ "content": "<|endoftext|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false
12
+ },
13
+ "pad_token": {
14
+ "content": "<|endoftext|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false
19
+ }
20
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bcfe42da0a4497e8b2b172c1f9f4ec423a46dc12907f4349c55025f670422ba9
3
+ size 11418266
tokenizer_config.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "151643": {
5
+ "content": "<|endoftext|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "151644": {
13
+ "content": "<|im_start|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "151645": {
21
+ "content": "<|im_end|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ }
28
+ },
29
+ "additional_special_tokens": [
30
+ "<|im_start|>",
31
+ "<|im_end|>"
32
+ ],
33
+ "bos_token": null,
34
+ "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 %}",
35
+ "clean_up_tokenization_spaces": false,
36
+ "eos_token": "<|endoftext|>",
37
+ "errors": "replace",
38
+ "model_max_length": 4096,
39
+ "pad_token": "<|endoftext|>",
40
+ "padding_side": "right",
41
+ "split_special_tokens": false,
42
+ "tokenizer_class": "Qwen2Tokenizer",
43
+ "unk_token": null
44
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff