gqszhanshijin commited on
Commit
bd40e19
·
1 Parent(s): 6cc5618
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +6 -0
  2. steel-llm-step-1060000-ckpt/config.json +37 -0
  3. steel-llm-step-1060000-ckpt/configuration_steel.py +131 -0
  4. steel-llm-step-1060000-ckpt/generation_config.json +6 -0
  5. steel-llm-step-1060000-ckpt/merges.txt +0 -0
  6. steel-llm-step-1060000-ckpt/model.safetensors +3 -0
  7. steel-llm-step-1060000-ckpt/modeling_steel.py +1502 -0
  8. steel-llm-step-1060000-ckpt/softmoe_v3.py +112 -0
  9. steel-llm-step-1060000-ckpt/tokenizer.json +0 -0
  10. steel-llm-step-1060000-ckpt/tokenizer_config.json +41 -0
  11. steel-llm-step-1060000-ckpt/vocab.json +0 -0
  12. steel-llm-step-480000-ckpt/config.json +37 -0
  13. steel-llm-step-480000-ckpt/configuration_steel.py +131 -0
  14. steel-llm-step-480000-ckpt/generation_config.json +6 -0
  15. steel-llm-step-480000-ckpt/merges.txt +0 -0
  16. steel-llm-step-480000-ckpt/model.safetensors +3 -0
  17. steel-llm-step-480000-ckpt/modeling_steel.py +1499 -0
  18. steel-llm-step-480000-ckpt/softmoe_v3.py +112 -0
  19. steel-llm-step-480000-ckpt/tokenizer.json +0 -0
  20. steel-llm-step-480000-ckpt/tokenizer_config.json +41 -0
  21. steel-llm-step-480000-ckpt/vocab.json +0 -0
  22. steel-llm-step-660000-ckpt/config.json +37 -0
  23. steel-llm-step-660000-ckpt/configuration_steel.py +131 -0
  24. steel-llm-step-660000-ckpt/generation_config.json +6 -0
  25. steel-llm-step-660000-ckpt/merges.txt +0 -0
  26. steel-llm-step-660000-ckpt/model.safetensors +3 -0
  27. steel-llm-step-660000-ckpt/modeling_steel.py +1499 -0
  28. steel-llm-step-660000-ckpt/softmoe_v3.py +112 -0
  29. steel-llm-step-660000-ckpt/tokenizer.json +0 -0
  30. steel-llm-step-660000-ckpt/tokenizer_config.json +41 -0
  31. steel-llm-step-660000-ckpt/vocab.json +0 -0
  32. steel-llm-step-720000-ckpt/config.json +37 -0
  33. steel-llm-step-720000-ckpt/configuration_steel.py +131 -0
  34. steel-llm-step-720000-ckpt/generation_config.json +6 -0
  35. steel-llm-step-720000-ckpt/merges.txt +0 -0
  36. steel-llm-step-720000-ckpt/model.safetensors +3 -0
  37. steel-llm-step-720000-ckpt/modeling_steel.py +1499 -0
  38. steel-llm-step-720000-ckpt/softmoe_v3.py +112 -0
  39. steel-llm-step-720000-ckpt/tokenizer.json +0 -0
  40. steel-llm-step-720000-ckpt/tokenizer_config.json +41 -0
  41. steel-llm-step-720000-ckpt/vocab.json +0 -0
  42. steel-llm-step-980000-ckpt/config.json +37 -0
  43. steel-llm-step-980000-ckpt/configuration_steel.py +131 -0
  44. steel-llm-step-980000-ckpt/generation_config.json +6 -0
  45. steel-llm-step-980000-ckpt/merges.txt +0 -0
  46. steel-llm-step-980000-ckpt/model.safetensors +3 -0
  47. steel-llm-step-980000-ckpt/modeling_steel.py +1499 -0
  48. steel-llm-step-980000-ckpt/softmoe_v3.py +112 -0
  49. steel-llm-step-980000-ckpt/tokenizer.json +0 -0
  50. steel-llm-step-980000-ckpt/tokenizer_config.json +41 -0
.gitattributes CHANGED
@@ -33,3 +33,9 @@ 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
+ steel-llm-step-1060000-ckpt filter=lfs diff=lfs merge=lfs -text
37
+ steel-llm-step-220000-ckpt filter=lfs diff=lfs merge=lfs -text
38
+ steel-llm-step-480000-ckpt filter=lfs diff=lfs merge=lfs -text
39
+ steel-llm-step-660000-ckpt filter=lfs diff=lfs merge=lfs -text
40
+ steel-llm-step-720000-ckpt filter=lfs diff=lfs merge=lfs -text
41
+ steel-llm-step-980000-ckpt filter=lfs diff=lfs merge=lfs -text
steel-llm-step-1060000-ckpt/config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "FFN_type": "softmoe_v3",
3
+ "_name_or_path": "./steel_modify_from_qwen_1_5",
4
+ "architectures": [
5
+ "SteelForCausalLM"
6
+ ],
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_steel.SteelConfig",
10
+ "AutoModelForCausalLM": "modeling_steel.SteelForCausalLM"
11
+ },
12
+ "bos_token_id": 151643,
13
+ "eos_token_id": 151645,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 1792,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 1792,
18
+ "max_position_embeddings": 32768,
19
+ "max_window_layers": 21,
20
+ "mlp_div_ratio": 4,
21
+ "mlp_type": "senet",
22
+ "model_type": "qwen2",
23
+ "n_experts": 6,
24
+ "num_attention_heads": 32,
25
+ "num_hidden_layers": 18,
26
+ "num_key_value_heads": 32,
27
+ "rms_norm_eps": 1e-06,
28
+ "rope_theta": 1000000.0,
29
+ "sliding_window": 32768,
30
+ "slots_per_expert": 1,
31
+ "tie_word_embeddings": false,
32
+ "torch_dtype": "float32",
33
+ "transformers_version": "4.41.1",
34
+ "use_cache": true,
35
+ "use_sliding_window": false,
36
+ "vocab_size": 151936
37
+ }
steel-llm-step-1060000-ckpt/configuration_steel.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 zhanshijin and lishu. All rights reserved.
3
+ #
4
+ # This project copy from qwen1.5
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ Steel model configuration"""
17
+
18
+ from transformers.configuration_utils import PretrainedConfig
19
+ from transformers.utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+
26
+
27
+ class SteelConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`Qwen2Model`]. It is used to instantiate a
30
+ Qwen2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
31
+ with the defaults will yield a similar configuration to that of
32
+ Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PretrainedConfig`] for more information.
36
+
37
+
38
+ Args:
39
+ vocab_size (`int`, *optional*, defaults to 151936):
40
+ Vocabulary size of the Qwen2 model. Defines the number of different tokens that can be represented by the
41
+ `inputs_ids` passed when calling [`Qwen2Model`]
42
+ hidden_size (`int`, *optional*, defaults to 4096):
43
+ Dimension of the hidden representations.
44
+ intermediate_size (`int`, *optional*, defaults to 22016):
45
+ Dimension of the MLP representations.
46
+ num_hidden_layers (`int`, *optional*, defaults to 32):
47
+ Number of hidden layers in the Transformer encoder.
48
+ num_attention_heads (`int`, *optional*, defaults to 32):
49
+ Number of attention heads for each attention layer in the Transformer encoder.
50
+ num_key_value_heads (`int`, *optional*, defaults to 32):
51
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
52
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
53
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
54
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
55
+ by meanpooling all the original heads within that group. For more details checkout [this
56
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
57
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
58
+ The non-linear activation function (function or string) in the decoder.
59
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
60
+ The maximum sequence length that this model might ever be used with.
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
64
+ The epsilon used by the rms normalization layers.
65
+ use_cache (`bool`, *optional*, defaults to `True`):
66
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
67
+ relevant if `config.is_decoder=True`.
68
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
69
+ Whether the model's input and output word embeddings should be tied.
70
+ rope_theta (`float`, *optional*, defaults to 10000.0):
71
+ The base period of the RoPE embeddings.
72
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
73
+ Whether to use sliding window attention.
74
+ sliding_window (`int`, *optional*, defaults to 4096):
75
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
76
+ max_window_layers (`int`, *optional*, defaults to 28):
77
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
78
+ attention_dropout (`float`, *optional*, defaults to 0.0):
79
+ The dropout ratio for the attention probabilities.
80
+ """
81
+
82
+ model_type = "qwen2"
83
+ keys_to_ignore_at_inference = ["past_key_values"]
84
+
85
+ def __init__(
86
+ self,
87
+ vocab_size=151936,
88
+ hidden_size=4096,
89
+ intermediate_size=22016,
90
+ num_hidden_layers=32,
91
+ num_attention_heads=32,
92
+ num_key_value_heads=32,
93
+ hidden_act="silu",
94
+ max_position_embeddings=32768,
95
+ initializer_range=0.02,
96
+ rms_norm_eps=1e-6,
97
+ use_cache=True,
98
+ tie_word_embeddings=False,
99
+ rope_theta=10000.0,
100
+ use_sliding_window=False,
101
+ sliding_window=4096,
102
+ max_window_layers=28,
103
+ attention_dropout=0.0,
104
+ **kwargs,
105
+ ):
106
+ self.vocab_size = vocab_size
107
+ self.max_position_embeddings = max_position_embeddings
108
+ self.hidden_size = hidden_size
109
+ self.intermediate_size = intermediate_size
110
+ self.num_hidden_layers = num_hidden_layers
111
+ self.num_attention_heads = num_attention_heads
112
+ self.use_sliding_window = use_sliding_window
113
+ self.sliding_window = sliding_window
114
+ self.max_window_layers = max_window_layers
115
+
116
+ # for backward compatibility
117
+ if num_key_value_heads is None:
118
+ num_key_value_heads = num_attention_heads
119
+
120
+ self.num_key_value_heads = num_key_value_heads
121
+ self.hidden_act = hidden_act
122
+ self.initializer_range = initializer_range
123
+ self.rms_norm_eps = rms_norm_eps
124
+ self.use_cache = use_cache
125
+ self.rope_theta = rope_theta
126
+ self.attention_dropout = attention_dropout
127
+
128
+ super().__init__(
129
+ tie_word_embeddings=tie_word_embeddings,
130
+ **kwargs,
131
+ )
steel-llm-step-1060000-ckpt/generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 151643,
4
+ "eos_token_id": 151645,
5
+ "transformers_version": "4.41.1"
6
+ }
steel-llm-step-1060000-ckpt/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
steel-llm-step-1060000-ckpt/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:634cc607bf8cf464180dbf9d2945caacf81e5afcb57a0daa7d124738fc2242c5
3
+ size 4491766872
steel-llm-step-1060000-ckpt/modeling_steel.py ADDED
@@ -0,0 +1,1502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The zhanshijin and lishu. All rights reserved.
3
+ #
4
+ #
5
+ #This model copy from qwen1.5.
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+ """ PyTorch Steel model."""
19
+ import inspect
20
+ import math
21
+ import warnings
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.nn.functional as F
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+
30
+ from transformers.activations import ACT2FN
31
+ from transformers.cache_utils import Cache, DynamicCache
32
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
33
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
34
+ from transformers.modeling_utils import PreTrainedModel
35
+ from transformers.utils import (
36
+ add_start_docstrings,
37
+ add_start_docstrings_to_model_forward,
38
+ is_flash_attn_2_available,
39
+ is_flash_attn_greater_or_equal_2_10,
40
+ logging,
41
+ replace_return_docstrings,
42
+ )
43
+ import os
44
+ import sys
45
+ sys.path.append(os.path.abspath(os.path.dirname(__file__)))
46
+ from .configuration_steel import SteelConfig
47
+ from .softmoe_v3 import SteelSoftMoEV3
48
+
49
+ if is_flash_attn_2_available():
50
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
51
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
52
+
53
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
54
+ print("zhanshijin: surrport flash_attn_2")
55
+ print(f"zhanshijin: if flash attn surrport window:{_flash_supports_window_size}")
56
+ else:
57
+ print("zhanshijin: not surrport flash_attn_2")
58
+
59
+ logger = logging.get_logger(__name__)
60
+
61
+ rms_norm = None
62
+ def _import_cuda_rmsnorm():
63
+ global rms_norm
64
+ try:
65
+ from flash_attn.ops.rms_norm import rms_norm as __rms_norm
66
+ rms_norm = __rms_norm
67
+ print("zhanshijin: success import cuda __rms_norm")
68
+ except ImportError:
69
+ logger.warn(
70
+ "Warning: import flash_attn rms_norm fail, please install FlashAttention layer_norm to get higher efficiency "
71
+ "https://github.com/Dao-AILab/flash-attention/tree/main/csrc/layer_norm"
72
+ )
73
+
74
+ _CONFIG_FOR_DOC = "SteelConfig"
75
+
76
+
77
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
78
+ def _get_unpad_data(attention_mask):
79
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
80
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
81
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
82
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
83
+ return (
84
+ indices,
85
+ cu_seqlens,
86
+ max_seqlen_in_batch,
87
+ )
88
+
89
+
90
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Steel
91
+ class SteelRMSNorm(nn.Module):
92
+ def __init__(self, hidden_size, eps=1e-6):
93
+ """
94
+ SteelRMSNorm is equivalent to T5LayerNorm
95
+ """
96
+ super().__init__()
97
+ self.weight = nn.Parameter(torch.ones(hidden_size))
98
+ self.variance_epsilon = eps
99
+
100
+ def forward(self, hidden_states):
101
+ if rms_norm is not None and hidden_states.is_cuda:
102
+ return rms_norm(hidden_states, self.weight, self.variance_epsilon)
103
+ else:
104
+ input_dtype = hidden_states.dtype
105
+ hidden_states = hidden_states.to(torch.float32)
106
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
107
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
108
+ # test precision consistency
109
+ # from flash_attn.ops.rms_norm import rms_norm as _rms_norm
110
+ # print(_rms_norm(hidden_states, self.weight, self.variance_epsilon)[0,0,:10])
111
+ # print((self.weight * hidden_states.to(input_dtype))[0,0,:10])
112
+ return self.weight * hidden_states.to(input_dtype)
113
+
114
+
115
+ # Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Steel
116
+ class SteelRotaryEmbedding(nn.Module):
117
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
118
+ super().__init__()
119
+
120
+ self.dim = dim
121
+ self.max_position_embeddings = max_position_embeddings
122
+ self.base = base
123
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
124
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
125
+
126
+ # Build here to make `torch.jit.trace` work.
127
+ self._set_cos_sin_cache(
128
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
129
+ )
130
+
131
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
132
+ self.max_seq_len_cached = seq_len
133
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
134
+
135
+ freqs = torch.outer(t, self.inv_freq)
136
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
137
+ emb = torch.cat((freqs, freqs), dim=-1)
138
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
139
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
140
+
141
+ def forward(self, x, seq_len=None):
142
+ # x: [bs, num_attention_heads, seq_len, head_size]
143
+ if seq_len > self.max_seq_len_cached:
144
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
145
+
146
+ return (
147
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
148
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
149
+ )
150
+
151
+
152
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
153
+ def rotate_half(x):
154
+ """Rotates half the hidden dims of the input."""
155
+ x1 = x[..., : x.shape[-1] // 2]
156
+ x2 = x[..., x.shape[-1] // 2 :]
157
+ return torch.cat((-x2, x1), dim=-1)
158
+
159
+
160
+ # Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
161
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
162
+ """Applies Rotary Position Embedding to the query and key tensors.
163
+
164
+ Args:
165
+ q (`torch.Tensor`): The query tensor.
166
+ k (`torch.Tensor`): The key tensor.
167
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
168
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
169
+ position_ids (`torch.Tensor`):
170
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
171
+ used to pass offsetted position ids when working with a KV-cache.
172
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
173
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
174
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
175
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
176
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
177
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
178
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
179
+ Returns:
180
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
181
+ """
182
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
183
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
184
+ q_embed = (q * cos) + (rotate_half(q) * sin)
185
+ k_embed = (k * cos) + (rotate_half(k) * sin)
186
+ return q_embed, k_embed
187
+
188
+
189
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Steel->Steel
190
+ class SteelMLP(nn.Module):
191
+ def __init__(self, config):
192
+ super().__init__()
193
+ self.config = config
194
+ self.hidden_size = config.hidden_size
195
+ self.intermediate_size = config.intermediate_size //config.mlp_div_ratio
196
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
197
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
198
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
199
+ self.act_fn = ACT2FN[config.hidden_act]
200
+
201
+ def forward(self, x):
202
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
203
+
204
+ class SteelSENet(nn.Module):
205
+ def __init__(self, config):
206
+ super().__init__()
207
+ self.config = config
208
+ self.hidden_size = config.hidden_size
209
+ self.intermediate_size = config.intermediate_size //config.mlp_div_ratio
210
+ self.gate_up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
211
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
212
+ self.gate_down_proj = nn.Linear(self.intermediate_size,self.hidden_size, bias=False)
213
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
214
+ self.act_fn1 = ACT2FN[config.hidden_act]
215
+ self.act_fn2 = ACT2FN[config.hidden_act]
216
+
217
+ def forward(self, x):
218
+ x = self.act_fn1(self.gate_up_proj(x)) * self.up_proj(x)
219
+ return self.act_fn2(self.gate_down_proj(x)) * self.down_proj(x)
220
+
221
+
222
+ class SteelSoftMoeV1(nn.Module):
223
+ def __init__(self, config, layer=None):
224
+ super().__init__()
225
+ self.config = config
226
+ self.experts = nn.ModuleList([layer(config) for _ in range(config.n_experts)])
227
+ self.gating = nn.Linear(config.hidden_size, config.n_experts)
228
+ def forward(self, x):
229
+ weights = self.gating(x)
230
+ weights = nn.functional.softmax(weights, dim=-1, dtype=torch.float32).to(x.dtype)
231
+ outputs = torch.stack(
232
+ [expert(x) for expert in self.experts], dim=2)
233
+ weights = weights.unsqueeze(-1)
234
+ return torch.sum(outputs * weights, dim=2)
235
+
236
+ class SteelSoftMoeV2(nn.Module):
237
+ def __init__(self, config, layer):
238
+ super().__init__()
239
+ self.config = config
240
+ self.experts = nn.ModuleList([layer(config) for _ in range(config.n_experts)])
241
+ self.score = nn.Parameter(torch.randn(config.hidden_size, config.n_experts * config.slots_per_expert))
242
+
243
+ def forward(self, x):
244
+ logits = torch.matmul(x, self.score) # (batch_size, seq_len, slots)
245
+ dispatch_weights = F.softmax(logits, dim=-1,dtype=torch.float32).to(x.dtype)
246
+ combine_weights = F.softmax(logits, dim=1,dtype=torch.float32).to(x.dtype)
247
+ xs = torch.bmm(dispatch_weights.transpose(1, 2), x)
248
+ ys = torch.cat(
249
+ [expert(xs[:, i * self.config.slots_per_expert : (i + 1) * self.config.slots_per_expert, :])
250
+ for i, expert in enumerate(self.experts)],
251
+ dim=1
252
+ )
253
+ y = torch.bmm(combine_weights, ys)
254
+ return y
255
+
256
+
257
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
258
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
259
+ """
260
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
261
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
262
+ """
263
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
264
+ if n_rep == 1:
265
+ return hidden_states
266
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
267
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
268
+
269
+
270
+ class SteelAttention(nn.Module):
271
+ """
272
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
273
+ and "Generating Long Sequences with Sparse Transformers".
274
+ """
275
+
276
+ def __init__(self, config: SteelConfig, layer_idx: Optional[int] = None):
277
+ super().__init__()
278
+ self.config = config
279
+ self.layer_idx = layer_idx
280
+ if layer_idx is None:
281
+ logger.warning_once(
282
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
283
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
284
+ "when creating this class."
285
+ )
286
+
287
+ self.hidden_size = config.hidden_size
288
+ self.num_heads = config.num_attention_heads
289
+ self.head_dim = self.hidden_size // self.num_heads
290
+ self.num_key_value_heads = config.num_key_value_heads
291
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
292
+ self.max_position_embeddings = config.max_position_embeddings
293
+ self.rope_theta = config.rope_theta
294
+ self.is_causal = True
295
+ self.attention_dropout = config.attention_dropout
296
+
297
+ if (self.head_dim * self.num_heads) != self.hidden_size:
298
+ raise ValueError(
299
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
300
+ f" and `num_heads`: {self.num_heads})."
301
+ )
302
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
303
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
304
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
305
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
306
+
307
+ self.rotary_emb = SteelRotaryEmbedding(
308
+ self.head_dim,
309
+ max_position_embeddings=self.max_position_embeddings,
310
+ base=self.rope_theta,
311
+ )
312
+
313
+ def forward(
314
+ self,
315
+ hidden_states: torch.Tensor,
316
+ attention_mask: Optional[torch.Tensor] = None,
317
+ position_ids: Optional[torch.LongTensor] = None,
318
+ past_key_value: Optional[Cache] = None,
319
+ output_attentions: bool = False,
320
+ use_cache: bool = False,
321
+ **kwargs,
322
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
323
+ if "padding_mask" in kwargs:
324
+ warnings.warn(
325
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
326
+ )
327
+ bsz, q_len, _ = hidden_states.size()
328
+
329
+ query_states = self.q_proj(hidden_states)
330
+ key_states = self.k_proj(hidden_states)
331
+ value_states = self.v_proj(hidden_states)
332
+
333
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
334
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
335
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
336
+
337
+ kv_seq_len = key_states.shape[-2]
338
+ if past_key_value is not None:
339
+ if self.layer_idx is None:
340
+ raise ValueError(
341
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
342
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
343
+ "with a layer index."
344
+ )
345
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
346
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
347
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
348
+
349
+
350
+ if past_key_value is not None:
351
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
352
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
353
+
354
+ # repeat k/v heads if n_kv_heads < n_heads
355
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
356
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
357
+
358
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
359
+
360
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
361
+ raise ValueError(
362
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
363
+ f" {attn_weights.size()}"
364
+ )
365
+
366
+ if attention_mask is not None:
367
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
368
+ raise ValueError(
369
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
370
+ )
371
+
372
+ attn_weights = attn_weights + attention_mask
373
+
374
+ # upcast attention to fp32
375
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
376
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
377
+ attn_output = torch.matmul(attn_weights, value_states)
378
+
379
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
380
+ raise ValueError(
381
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
382
+ f" {attn_output.size()}"
383
+ )
384
+
385
+ attn_output = attn_output.transpose(1, 2).contiguous()
386
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
387
+
388
+ attn_output = self.o_proj(attn_output)
389
+
390
+ if not output_attentions:
391
+ attn_weights = None
392
+
393
+ return attn_output, attn_weights, past_key_value
394
+
395
+
396
+ class SteelFlashAttention2(SteelAttention):
397
+ """
398
+ Steel flash attention module, following Steel attention module. This module inherits from `SteelAttention`
399
+ as the weights of the module stays untouched. The only required change would be on the forward pass
400
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
401
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
402
+ config.max_window_layers layers.
403
+ """
404
+
405
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
406
+ def __init__(self, *args, **kwargs):
407
+ super().__init__(*args, **kwargs)
408
+
409
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
410
+ # 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.
411
+ # 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).
412
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
413
+
414
+ def forward(
415
+ self,
416
+ hidden_states: torch.Tensor,
417
+ attention_mask: Optional[torch.Tensor] = None,
418
+ position_ids: Optional[torch.LongTensor] = None,
419
+ past_key_value: Optional[Cache] = None,
420
+ output_attentions: bool = False,
421
+ use_cache: bool = False,
422
+ **kwargs,
423
+ ):
424
+ if "padding_mask" in kwargs:
425
+ warnings.warn(
426
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
427
+ )
428
+
429
+ # overwrite attention_mask with padding_mask
430
+ attention_mask = kwargs.pop("padding_mask")
431
+ bsz, q_len, _ = hidden_states.size()
432
+
433
+ query_states = self.q_proj(hidden_states)
434
+ key_states = self.k_proj(hidden_states)
435
+ value_states = self.v_proj(hidden_states)
436
+
437
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
438
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
439
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
440
+
441
+ kv_seq_len = key_states.shape[-2]
442
+ if past_key_value is not None:
443
+ if self.layer_idx is None:
444
+ raise ValueError(
445
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
446
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
447
+ "with a layer index."
448
+ )
449
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
450
+
451
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
452
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
453
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
454
+
455
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
456
+
457
+ use_sliding_windows = (
458
+ _flash_supports_window_size
459
+ and getattr(self.config, "sliding_window", None) is not None
460
+ and kv_seq_len > self.config.sliding_window
461
+ and self.config.use_sliding_window
462
+ )
463
+
464
+ if not _flash_supports_window_size:
465
+ logger.warning_once(
466
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
467
+ " make sure to upgrade flash-attn library."
468
+ )
469
+
470
+ if past_key_value is not None:
471
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
472
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
473
+ if (
474
+ getattr(self.config, "sliding_window", None) is not None
475
+ and kv_seq_len > self.config.sliding_window
476
+ and cache_has_contents
477
+ ):
478
+ slicing_tokens = 1 - self.config.sliding_window
479
+
480
+ past_key = past_key_value[self.layer_idx][0]
481
+ past_value = past_key_value[self.layer_idx][1]
482
+
483
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
484
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
485
+
486
+ if past_key.shape[-2] != self.config.sliding_window - 1:
487
+ raise ValueError(
488
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
489
+ f" {past_key.shape}"
490
+ )
491
+
492
+ if attention_mask is not None:
493
+ attention_mask = attention_mask[:, slicing_tokens:]
494
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
495
+
496
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
497
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
498
+
499
+ # repeat k/v heads if n_kv_heads < n_heads
500
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
501
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
502
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
503
+
504
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
505
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
506
+ # cast them back in float16 just to be sure everything works as expected.
507
+ input_dtype = query_states.dtype
508
+ if input_dtype == torch.float32:
509
+ if torch.is_autocast_enabled():
510
+ target_dtype = torch.get_autocast_gpu_dtype()
511
+ # Handle the case where the model is quantized
512
+ elif hasattr(self.config, "_pre_quantization_dtype"):
513
+ target_dtype = self.config._pre_quantization_dtype
514
+ else:
515
+ target_dtype = self.q_proj.weight.dtype
516
+
517
+ logger.warning_once(
518
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
519
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
520
+ f" {target_dtype}."
521
+ )
522
+
523
+ query_states = query_states.to(target_dtype)
524
+ key_states = key_states.to(target_dtype)
525
+ value_states = value_states.to(target_dtype)
526
+
527
+ # Reashape to the expected shape for Flash Attention
528
+ query_states = query_states.transpose(1, 2)
529
+ key_states = key_states.transpose(1, 2)
530
+ value_states = value_states.transpose(1, 2)
531
+
532
+ attn_output = self._flash_attention_forward(
533
+ query_states,
534
+ key_states,
535
+ value_states,
536
+ attention_mask,
537
+ q_len,
538
+ dropout=dropout_rate,
539
+ use_sliding_windows=use_sliding_windows,
540
+ )
541
+
542
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
543
+ attn_output = self.o_proj(attn_output)
544
+
545
+ if not output_attentions:
546
+ attn_weights = None
547
+
548
+ return attn_output, attn_weights, past_key_value
549
+
550
+ def _flash_attention_forward(
551
+ self,
552
+ query_states,
553
+ key_states,
554
+ value_states,
555
+ attention_mask,
556
+ query_length,
557
+ dropout=0.0,
558
+ softmax_scale=None,
559
+ use_sliding_windows=False,
560
+ ):
561
+ """
562
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
563
+ first unpad the input, then computes the attention scores and pad the final attention scores.
564
+
565
+ Args:
566
+ query_states (`torch.Tensor`):
567
+ Input query states to be passed to Flash Attention API
568
+ key_states (`torch.Tensor`):
569
+ Input key states to be passed to Flash Attention API
570
+ value_states (`torch.Tensor`):
571
+ Input value states to be passed to Flash Attention API
572
+ attention_mask (`torch.Tensor`):
573
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
574
+ position of padding tokens and 1 for the position of non-padding tokens.
575
+ dropout (`float`):
576
+ Attention dropout
577
+ softmax_scale (`float`, *optional*):
578
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
579
+ use_sliding_windows (`bool`, *optional*):
580
+ Whether to activate sliding window attention.
581
+ """
582
+ if not self._flash_attn_uses_top_left_mask:
583
+ causal = self.is_causal
584
+ else:
585
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
586
+ causal = self.is_causal and query_length != 1
587
+
588
+ # Decide whether to use SWA or not by layer index.
589
+ if use_sliding_windows and self.layer_idx >= self.config.max_window_layers:
590
+ use_sliding_windows = False
591
+
592
+ # Contains at least one padding token in the sequence
593
+ if attention_mask is not None:
594
+ batch_size = query_states.shape[0]
595
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
596
+ query_states, key_states, value_states, attention_mask, query_length
597
+ )
598
+
599
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
600
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
601
+
602
+ if not use_sliding_windows:
603
+ attn_output_unpad = flash_attn_varlen_func(
604
+ query_states,
605
+ key_states,
606
+ value_states,
607
+ cu_seqlens_q=cu_seqlens_q,
608
+ cu_seqlens_k=cu_seqlens_k,
609
+ max_seqlen_q=max_seqlen_in_batch_q,
610
+ max_seqlen_k=max_seqlen_in_batch_k,
611
+ dropout_p=dropout,
612
+ softmax_scale=softmax_scale,
613
+ causal=causal,
614
+ )
615
+ else:
616
+ attn_output_unpad = flash_attn_varlen_func(
617
+ query_states,
618
+ key_states,
619
+ value_states,
620
+ cu_seqlens_q=cu_seqlens_q,
621
+ cu_seqlens_k=cu_seqlens_k,
622
+ max_seqlen_q=max_seqlen_in_batch_q,
623
+ max_seqlen_k=max_seqlen_in_batch_k,
624
+ dropout_p=dropout,
625
+ softmax_scale=softmax_scale,
626
+ causal=causal,
627
+ window_size=(self.config.sliding_window, self.config.sliding_window),
628
+ )
629
+
630
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
631
+ else:
632
+ if not use_sliding_windows:
633
+ attn_output = flash_attn_func(
634
+ query_states,
635
+ key_states,
636
+ value_states,
637
+ dropout,
638
+ softmax_scale=softmax_scale,
639
+ causal=causal,
640
+ )
641
+ else:
642
+ attn_output = flash_attn_func(
643
+ query_states,
644
+ key_states,
645
+ value_states,
646
+ dropout,
647
+ softmax_scale=softmax_scale,
648
+ causal=causal,
649
+ window_size=(self.config.sliding_window, self.config.sliding_window),
650
+ )
651
+
652
+ return attn_output
653
+
654
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
655
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
656
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
657
+
658
+ # On the first iteration we need to properly re-create the padding mask
659
+ # by slicing it on the proper place
660
+ if kv_seq_len != attention_mask.shape[-1]:
661
+ attention_mask_num_tokens = attention_mask.shape[-1]
662
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
663
+
664
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
665
+
666
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
667
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
668
+
669
+ if query_length == kv_seq_len:
670
+ query_layer = index_first_axis(
671
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
672
+ )
673
+ cu_seqlens_q = cu_seqlens_k
674
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
675
+ indices_q = indices_k
676
+ elif query_length == 1:
677
+ max_seqlen_in_batch_q = 1
678
+ cu_seqlens_q = torch.arange(
679
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
680
+ ) # There is a memcpy here, that is very bad.
681
+ indices_q = cu_seqlens_q[:-1]
682
+ query_layer = query_layer.squeeze(1)
683
+ else:
684
+ # The -q_len: slice assumes left padding.
685
+ attention_mask = attention_mask[:, -query_length:]
686
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
687
+
688
+ return (
689
+ query_layer,
690
+ key_layer,
691
+ value_layer,
692
+ indices_q,
693
+ (cu_seqlens_q, cu_seqlens_k),
694
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
695
+ )
696
+
697
+
698
+ # Copied from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Steel
699
+ class SteelSdpaAttention(SteelAttention):
700
+ """
701
+ Steel attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
702
+ `SteelAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
703
+ SDPA API.
704
+ """
705
+
706
+ # Adapted from SteelAttention.forward
707
+ def forward(
708
+ self,
709
+ hidden_states: torch.Tensor,
710
+ attention_mask: Optional[torch.Tensor] = None,
711
+ position_ids: Optional[torch.LongTensor] = None,
712
+ past_key_value: Optional[Cache] = None,
713
+ output_attentions: bool = False,
714
+ use_cache: bool = False,
715
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
716
+ if output_attentions:
717
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
718
+ logger.warning_once(
719
+ "SteelModel is using SteelSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
720
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
721
+ )
722
+ return super().forward(
723
+ hidden_states=hidden_states,
724
+ attention_mask=attention_mask,
725
+ position_ids=position_ids,
726
+ past_key_value=past_key_value,
727
+ output_attentions=output_attentions,
728
+ use_cache=use_cache,
729
+ )
730
+
731
+ bsz, q_len, _ = hidden_states.size()
732
+
733
+ query_states = self.q_proj(hidden_states)
734
+ key_states = self.k_proj(hidden_states)
735
+ value_states = self.v_proj(hidden_states)
736
+
737
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
738
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
739
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
740
+
741
+ kv_seq_len = key_states.shape[-2]
742
+ if past_key_value is not None:
743
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
744
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
745
+
746
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
747
+
748
+ if past_key_value is not None:
749
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
750
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
751
+
752
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
753
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
754
+
755
+ if attention_mask is not None:
756
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
757
+ raise ValueError(
758
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
759
+ )
760
+
761
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
762
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
763
+ if query_states.device.type == "cuda" and attention_mask is not None:
764
+ query_states = query_states.contiguous()
765
+ key_states = key_states.contiguous()
766
+ value_states = value_states.contiguous()
767
+
768
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
769
+ query_states,
770
+ key_states,
771
+ value_states,
772
+ attn_mask=attention_mask,
773
+ dropout_p=self.attention_dropout if self.training else 0.0,
774
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
775
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
776
+ )
777
+
778
+ attn_output = attn_output.transpose(1, 2).contiguous()
779
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
780
+
781
+ attn_output = self.o_proj(attn_output)
782
+
783
+ return attn_output, None, past_key_value
784
+
785
+
786
+ Steel_ATTENTION_CLASSES = {
787
+ "eager": SteelAttention,
788
+ "flash_attention_2": SteelFlashAttention2,
789
+ "sdpa": SteelSdpaAttention,
790
+ }
791
+
792
+
793
+ class SteelDecoderLayer(nn.Module):
794
+ def __init__(self, config: SteelConfig, layer_idx: int):
795
+ super().__init__()
796
+ self.hidden_size = config.hidden_size
797
+
798
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
799
+ logger.warning_once(
800
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
801
+ "unexpected results may be encountered."
802
+ )
803
+ self.self_attn = Steel_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
804
+ if config.mlp_type == "raw":
805
+ mlp_class = SteelMLP
806
+ logger.warning_once(f"mlp_class: SteelMLP")
807
+ elif config.mlp_type == "senet":
808
+ mlp_class = SteelSENet
809
+ logger.warning_once(f"mlp_class: SteelSENet")
810
+ else:
811
+ raise NameError(f"No this mlp type: {config.mlp_type}")
812
+
813
+ if config.FFN_type == "raw":
814
+ self.mlp = mlp_class(config)
815
+ logger.warning_once(f"FFN: {mlp_class}")
816
+ elif config.FFN_type == "softmoe_v1":
817
+ self.mlp = SteelSoftMoeV1(config, layer=mlp_class)
818
+ logger.warning_once(f"FFN: SteelSoftMoeV1")
819
+ elif config.FFN_type == "softmoe_v2":
820
+ self.mlp = SteelSoftMoeV2(config, layer=mlp_class)
821
+ logger.warning_once(f"FFN: SteelSoftMoeV2")
822
+ elif config.FFN_type == "softmoe_v3":
823
+ self.mlp = SteelSoftMoEV3(config=config, layer=mlp_class)
824
+ logger.warning_once(f"FFN: SteelSoftMoeV3")
825
+ else:
826
+ raise NameError(f"No this FFN type: {config.FFN_type}")
827
+
828
+ self.input_layernorm = SteelRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
829
+ self.post_attention_layernorm = SteelRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
830
+
831
+ def forward(
832
+ self,
833
+ hidden_states: torch.Tensor,
834
+ attention_mask: Optional[torch.Tensor] = None,
835
+ position_ids: Optional[torch.LongTensor] = None,
836
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
837
+ output_attentions: Optional[bool] = False,
838
+ use_cache: Optional[bool] = False,
839
+ **kwargs,
840
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
841
+ if "padding_mask" in kwargs:
842
+ warnings.warn(
843
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
844
+ "Please make sure use `attention_mask` instead.`"
845
+ )
846
+ """
847
+ Args:
848
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
849
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
850
+ `(batch, sequence_length)` where padding elements are indicated by 0.
851
+ output_attentions (`bool`, *optional*):
852
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
853
+ returned tensors for more detail.
854
+ use_cache (`bool`, *optional*):
855
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
856
+ (see `past_key_values`).
857
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
858
+ """
859
+
860
+ residual = hidden_states
861
+
862
+ hidden_states = self.input_layernorm(hidden_states)
863
+
864
+ # Self Attention
865
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
866
+ hidden_states=hidden_states,
867
+ attention_mask=attention_mask,
868
+ position_ids=position_ids,
869
+ past_key_value=past_key_value,
870
+ output_attentions=output_attentions,
871
+ use_cache=use_cache,
872
+ )
873
+ hidden_states = residual + hidden_states
874
+
875
+ # Fully Connected
876
+ residual = hidden_states
877
+ hidden_states = self.post_attention_layernorm(hidden_states)
878
+ hidden_states = self.mlp(hidden_states)
879
+ hidden_states = residual + hidden_states
880
+
881
+ outputs = (hidden_states,)
882
+
883
+ if output_attentions:
884
+ outputs += (self_attn_weights,)
885
+
886
+ if use_cache:
887
+ outputs += (present_key_value,)
888
+
889
+ return outputs
890
+
891
+
892
+ Steel_START_DOCSTRING = r"""
893
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
894
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
895
+ etc.)
896
+
897
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
898
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
899
+ and behavior.
900
+
901
+ Parameters:
902
+ config ([`SteelConfig`]):
903
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
904
+ load the weights associated with the model, only the configuration. Check out the
905
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
906
+ """
907
+
908
+
909
+ @add_start_docstrings(
910
+ "The bare Steel Model outputting raw hidden-states without any specific head on top.",
911
+ Steel_START_DOCSTRING,
912
+ )
913
+ class SteelPreTrainedModel(PreTrainedModel):
914
+ config_class = SteelConfig
915
+ base_model_prefix = "model"
916
+ supports_gradient_checkpointing = True
917
+ _no_split_modules = ["SteelDecoderLayer"]
918
+ _skip_keys_device_placement = "past_key_values"
919
+ _supports_flash_attn_2 = True
920
+ _supports_sdpa = True
921
+ _supports_cache_class = True
922
+
923
+ def _init_weights(self, module):
924
+ std = self.config.initializer_range
925
+ if isinstance(module, nn.Linear):
926
+ module.weight.data.normal_(mean=0.0, std=std)
927
+ if module.bias is not None:
928
+ module.bias.data.zero_()
929
+ elif isinstance(module, nn.Embedding):
930
+ module.weight.data.normal_(mean=0.0, std=std)
931
+ if module.padding_idx is not None:
932
+ module.weight.data[module.padding_idx].zero_()
933
+
934
+
935
+ Steel_INPUTS_DOCSTRING = r"""
936
+ Args:
937
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
938
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
939
+ it.
940
+
941
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
942
+ [`PreTrainedTokenizer.__call__`] for details.
943
+
944
+ [What are input IDs?](../glossary#input-ids)
945
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
946
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
947
+
948
+ - 1 for tokens that are **not masked**,
949
+ - 0 for tokens that are **masked**.
950
+
951
+ [What are attention masks?](../glossary#attention-mask)
952
+
953
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
954
+ [`PreTrainedTokenizer.__call__`] for details.
955
+
956
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
957
+ `past_key_values`).
958
+
959
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
960
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
961
+ information on the default strategy.
962
+
963
+ - 1 indicates the head is **not masked**,
964
+ - 0 indicates the head is **masked**.
965
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
966
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
967
+ config.n_positions - 1]`.
968
+
969
+ [What are position IDs?](../glossary#position-ids)
970
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
971
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
972
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
973
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
974
+
975
+ Two formats are allowed:
976
+ - a [`~cache_utils.Cache`] instance;
977
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
978
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
979
+ cache format.
980
+
981
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
982
+ legacy cache format will be returned.
983
+
984
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
985
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
986
+ of shape `(batch_size, sequence_length)`.
987
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
988
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
989
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
990
+ model's internal embedding lookup matrix.
991
+ use_cache (`bool`, *optional*):
992
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
993
+ `past_key_values`).
994
+ output_attentions (`bool`, *optional*):
995
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
996
+ tensors for more detail.
997
+ output_hidden_states (`bool`, *optional*):
998
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
999
+ more detail.
1000
+ return_dict (`bool`, *optional*):
1001
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1002
+ """
1003
+
1004
+
1005
+ @add_start_docstrings(
1006
+ "The bare Steel Model outputting raw hidden-states without any specific head on top.",
1007
+ Steel_START_DOCSTRING,
1008
+ )
1009
+ class SteelModel(SteelPreTrainedModel):
1010
+ """
1011
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`SteelDecoderLayer`]
1012
+
1013
+ Args:
1014
+ config: SteelConfig
1015
+ """
1016
+
1017
+ def __init__(self, config: SteelConfig):
1018
+ super().__init__(config)
1019
+ self.padding_idx = config.pad_token_id
1020
+ self.vocab_size = config.vocab_size
1021
+
1022
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1023
+ self.layers = nn.ModuleList(
1024
+ [SteelDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1025
+ )
1026
+ self._attn_implementation = config._attn_implementation
1027
+ logger.warning_once(
1028
+ f"zhanshijin: now use _attn_implementation is {config._attn_implementation}, you can choose from {Steel_ATTENTION_CLASSES.keys()}"
1029
+ )
1030
+ self.norm = SteelRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1031
+
1032
+ self.gradient_checkpointing = False
1033
+ # Initialize weights and apply final processing
1034
+ self.post_init()
1035
+
1036
+ if hasattr(config, "use_cuda_rmsnorm") and config.use_cuda_rmsnorm:
1037
+ _import_cuda_rmsnorm()
1038
+ else:
1039
+ print("zhanshijin: use torch rmsnorm")
1040
+
1041
+ def get_input_embeddings(self):
1042
+ return self.embed_tokens
1043
+
1044
+ def set_input_embeddings(self, value):
1045
+ self.embed_tokens = value
1046
+
1047
+ @add_start_docstrings_to_model_forward(Steel_INPUTS_DOCSTRING)
1048
+ def forward(
1049
+ self,
1050
+ input_ids: torch.LongTensor = None,
1051
+ attention_mask: Optional[torch.Tensor] = None,
1052
+ position_ids: Optional[torch.LongTensor] = None,
1053
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1054
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1055
+ use_cache: Optional[bool] = None,
1056
+ output_attentions: Optional[bool] = None,
1057
+ output_hidden_states: Optional[bool] = None,
1058
+ return_dict: Optional[bool] = None,
1059
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1060
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1061
+ output_hidden_states = (
1062
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1063
+ )
1064
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1065
+
1066
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1067
+
1068
+ # retrieve input_ids and inputs_embeds
1069
+ if input_ids is not None and inputs_embeds is not None:
1070
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1071
+ elif input_ids is not None:
1072
+ batch_size, seq_length = input_ids.shape
1073
+ elif inputs_embeds is not None:
1074
+ batch_size, seq_length, _ = inputs_embeds.shape
1075
+ else:
1076
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
1077
+
1078
+ if self.gradient_checkpointing and self.training:
1079
+ if use_cache:
1080
+ logger.warning_once(
1081
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1082
+ )
1083
+ use_cache = False
1084
+
1085
+ past_key_values_length = 0
1086
+
1087
+ if use_cache:
1088
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1089
+ if use_legacy_cache:
1090
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1091
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1092
+
1093
+ if position_ids is None:
1094
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1095
+ position_ids = torch.arange(
1096
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1097
+ )
1098
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1099
+ else:
1100
+ position_ids = position_ids.view(-1, seq_length).long()
1101
+
1102
+ if inputs_embeds is None:
1103
+ inputs_embeds = self.embed_tokens(input_ids)
1104
+
1105
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1106
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1107
+ if is_padding_right:
1108
+ raise ValueError(
1109
+ "You are attempting to perform batched generation with padding_side='right'"
1110
+ " this may lead to unexpected behaviour for Flash Attention version of Steel. Make sure to "
1111
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1112
+ )
1113
+
1114
+ if self._attn_implementation == "flash_attention_2":
1115
+ # 2d mask is passed through the layers
1116
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1117
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1118
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1119
+ # the manual implementation that requires a 4D causal mask in all cases.
1120
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1121
+ attention_mask,
1122
+ (batch_size, seq_length),
1123
+ inputs_embeds,
1124
+ past_key_values_length,
1125
+ sliding_window=self.config.sliding_window,
1126
+ )
1127
+ else:
1128
+ # 4d mask is passed through the layers
1129
+ attention_mask = _prepare_4d_causal_attention_mask(
1130
+ attention_mask,
1131
+ (batch_size, seq_length),
1132
+ inputs_embeds,
1133
+ past_key_values_length,
1134
+ sliding_window=self.config.sliding_window,
1135
+ )
1136
+
1137
+ hidden_states = inputs_embeds
1138
+
1139
+ # decoder layers
1140
+ all_hidden_states = () if output_hidden_states else None
1141
+ all_self_attns = () if output_attentions else None
1142
+ next_decoder_cache = None
1143
+
1144
+ for decoder_layer in self.layers:
1145
+ if output_hidden_states:
1146
+ all_hidden_states += (hidden_states,)
1147
+
1148
+ if self.gradient_checkpointing and self.training:
1149
+ layer_outputs = self._gradient_checkpointing_func(
1150
+ decoder_layer.__call__,
1151
+ hidden_states,
1152
+ attention_mask,
1153
+ position_ids,
1154
+ past_key_values,
1155
+ output_attentions,
1156
+ use_cache,
1157
+ )
1158
+ else:
1159
+ layer_outputs = decoder_layer(
1160
+ hidden_states,
1161
+ attention_mask=attention_mask,
1162
+ position_ids=position_ids,
1163
+ past_key_value=past_key_values,
1164
+ output_attentions=output_attentions,
1165
+ use_cache=use_cache,
1166
+ )
1167
+
1168
+ hidden_states = layer_outputs[0]
1169
+
1170
+ if use_cache:
1171
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1172
+
1173
+ if output_attentions:
1174
+ all_self_attns += (layer_outputs[1],)
1175
+
1176
+ hidden_states = self.norm(hidden_states)
1177
+
1178
+ # add hidden states from the last decoder layer
1179
+ if output_hidden_states:
1180
+ all_hidden_states += (hidden_states,)
1181
+
1182
+ next_cache = None
1183
+ if use_cache:
1184
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1185
+
1186
+ if not return_dict:
1187
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1188
+ return BaseModelOutputWithPast(
1189
+ last_hidden_state=hidden_states,
1190
+ past_key_values=next_cache,
1191
+ hidden_states=all_hidden_states,
1192
+ attentions=all_self_attns,
1193
+ )
1194
+
1195
+
1196
+ class SteelForCausalLM(SteelPreTrainedModel):
1197
+ _tied_weights_keys = ["lm_head.weight"]
1198
+
1199
+ def __init__(self, config):
1200
+ super().__init__(config)
1201
+ self.model = SteelModel(config)
1202
+ self.vocab_size = config.vocab_size
1203
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1204
+
1205
+ # Initialize weights and apply final processing
1206
+ self.post_init()
1207
+
1208
+ def get_input_embeddings(self):
1209
+ return self.model.embed_tokens
1210
+
1211
+ def set_input_embeddings(self, value):
1212
+ self.model.embed_tokens = value
1213
+
1214
+ def get_output_embeddings(self):
1215
+ return self.lm_head
1216
+
1217
+ def set_output_embeddings(self, new_embeddings):
1218
+ self.lm_head = new_embeddings
1219
+
1220
+ def set_decoder(self, decoder):
1221
+ self.model = decoder
1222
+
1223
+ def get_decoder(self):
1224
+ return self.model
1225
+
1226
+ @add_start_docstrings_to_model_forward(Steel_INPUTS_DOCSTRING)
1227
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1228
+ def forward(
1229
+ self,
1230
+ input_ids: torch.LongTensor = None,
1231
+ attention_mask: Optional[torch.Tensor] = None,
1232
+ position_ids: Optional[torch.LongTensor] = None,
1233
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1234
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1235
+ labels: Optional[torch.LongTensor] = None,
1236
+ use_cache: Optional[bool] = None,
1237
+ output_attentions: Optional[bool] = None,
1238
+ output_hidden_states: Optional[bool] = None,
1239
+ return_dict: Optional[bool] = None,
1240
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1241
+ r"""
1242
+ Args:
1243
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1244
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1245
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1246
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1247
+
1248
+ Returns:
1249
+
1250
+ Example:
1251
+
1252
+ ```python
1253
+ >>> from transformers import AutoTokenizer, SteelForCausalLM
1254
+
1255
+ >>> model = SteelForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1256
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1257
+
1258
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1259
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1260
+
1261
+ >>> # Generate
1262
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1263
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1264
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1265
+ ```"""
1266
+
1267
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1268
+ output_hidden_states = (
1269
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1270
+ )
1271
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1272
+
1273
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1274
+ outputs = self.model(
1275
+ input_ids=input_ids,
1276
+ attention_mask=attention_mask,
1277
+ position_ids=position_ids,
1278
+ past_key_values=past_key_values,
1279
+ inputs_embeds=inputs_embeds,
1280
+ use_cache=use_cache,
1281
+ output_attentions=output_attentions,
1282
+ output_hidden_states=output_hidden_states,
1283
+ return_dict=return_dict,
1284
+ )
1285
+
1286
+ hidden_states = outputs[0]
1287
+ logits = self.lm_head(hidden_states)
1288
+ logits = logits.float()
1289
+
1290
+ loss = None
1291
+ if labels is not None:
1292
+ # Shift so that tokens < n predict n
1293
+ shift_logits = logits[..., :-1, :].contiguous()
1294
+ shift_labels = labels[..., 1:].contiguous()
1295
+ # Flatten the tokens
1296
+ loss_fct = CrossEntropyLoss()
1297
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1298
+ shift_labels = shift_labels.view(-1)
1299
+ # Enable model parallelism
1300
+ shift_labels = shift_labels.to(shift_logits.device)
1301
+ loss = loss_fct(shift_logits, shift_labels)
1302
+
1303
+ if not return_dict:
1304
+ output = (logits,) + outputs[1:]
1305
+ return (loss,) + output if loss is not None else output
1306
+
1307
+ return CausalLMOutputWithPast(
1308
+ loss=loss,
1309
+ logits=logits,
1310
+ past_key_values=outputs.past_key_values,
1311
+ hidden_states=outputs.hidden_states,
1312
+ attentions=outputs.attentions,
1313
+ )
1314
+
1315
+ def prepare_inputs_for_generation(
1316
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1317
+ ):
1318
+ # Omit tokens covered by past_key_values
1319
+ if past_key_values is not None:
1320
+ if isinstance(past_key_values, Cache):
1321
+ cache_length = past_key_values.get_seq_length()
1322
+ past_length = past_key_values.seen_tokens
1323
+ max_cache_length = past_key_values.get_max_length()
1324
+ else:
1325
+ cache_length = past_length = past_key_values[0][0].shape[2]
1326
+ max_cache_length = None
1327
+
1328
+ # Keep only the unprocessed tokens:
1329
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1330
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1331
+ # input)
1332
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1333
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1334
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1335
+ # input_ids based on the past_length.
1336
+ elif past_length < input_ids.shape[1]:
1337
+ input_ids = input_ids[:, past_length:]
1338
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1339
+
1340
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1341
+ if (
1342
+ max_cache_length is not None
1343
+ and attention_mask is not None
1344
+ and cache_length + input_ids.shape[1] > max_cache_length
1345
+ ):
1346
+ attention_mask = attention_mask[:, -max_cache_length:]
1347
+
1348
+ position_ids = kwargs.get("position_ids", None)
1349
+ if attention_mask is not None and position_ids is None:
1350
+ # create position_ids on the fly for batch generation
1351
+ position_ids = attention_mask.long().cumsum(-1) - 1
1352
+ position_ids.masked_fill_(attention_mask == 0, 1)
1353
+ if past_key_values:
1354
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1355
+
1356
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1357
+ if inputs_embeds is not None and past_key_values is None:
1358
+ model_inputs = {"inputs_embeds": inputs_embeds}
1359
+ else:
1360
+ model_inputs = {"input_ids": input_ids}
1361
+
1362
+ model_inputs.update(
1363
+ {
1364
+ "position_ids": position_ids,
1365
+ "past_key_values": past_key_values,
1366
+ "use_cache": kwargs.get("use_cache"),
1367
+ "attention_mask": attention_mask,
1368
+ }
1369
+ )
1370
+ return model_inputs
1371
+
1372
+ @staticmethod
1373
+ def _reorder_cache(past_key_values, beam_idx):
1374
+ reordered_past = ()
1375
+ for layer_past in past_key_values:
1376
+ reordered_past += (
1377
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1378
+ )
1379
+ return reordered_past
1380
+
1381
+
1382
+ @add_start_docstrings(
1383
+ """
1384
+ The Steel Model transformer with a sequence classification head on top (linear layer).
1385
+
1386
+ [`SteelForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1387
+ (e.g. GPT-2) do.
1388
+
1389
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1390
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1391
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1392
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1393
+ each row of the batch).
1394
+ """,
1395
+ Steel_START_DOCSTRING,
1396
+ )
1397
+ class SteelForSequenceClassification(SteelPreTrainedModel):
1398
+ def __init__(self, config):
1399
+ super().__init__(config)
1400
+ self.num_labels = config.num_labels
1401
+ self.model = SteelModel(config)
1402
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1403
+
1404
+ # Initialize weights and apply final processing
1405
+ self.post_init()
1406
+
1407
+ def get_input_embeddings(self):
1408
+ return self.model.embed_tokens
1409
+
1410
+ def set_input_embeddings(self, value):
1411
+ self.model.embed_tokens = value
1412
+
1413
+ @add_start_docstrings_to_model_forward(Steel_INPUTS_DOCSTRING)
1414
+ def forward(
1415
+ self,
1416
+ input_ids: torch.LongTensor = None,
1417
+ attention_mask: Optional[torch.Tensor] = None,
1418
+ position_ids: Optional[torch.LongTensor] = None,
1419
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1420
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1421
+ labels: Optional[torch.LongTensor] = None,
1422
+ use_cache: Optional[bool] = None,
1423
+ output_attentions: Optional[bool] = None,
1424
+ output_hidden_states: Optional[bool] = None,
1425
+ return_dict: Optional[bool] = None,
1426
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1427
+ r"""
1428
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1429
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1430
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1431
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1432
+ """
1433
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1434
+
1435
+ transformer_outputs = self.model(
1436
+ input_ids,
1437
+ attention_mask=attention_mask,
1438
+ position_ids=position_ids,
1439
+ past_key_values=past_key_values,
1440
+ inputs_embeds=inputs_embeds,
1441
+ use_cache=use_cache,
1442
+ output_attentions=output_attentions,
1443
+ output_hidden_states=output_hidden_states,
1444
+ return_dict=return_dict,
1445
+ )
1446
+ hidden_states = transformer_outputs[0]
1447
+ logits = self.score(hidden_states)
1448
+
1449
+ if input_ids is not None:
1450
+ batch_size = input_ids.shape[0]
1451
+ else:
1452
+ batch_size = inputs_embeds.shape[0]
1453
+
1454
+ if self.config.pad_token_id is None and batch_size != 1:
1455
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1456
+ if self.config.pad_token_id is None:
1457
+ sequence_lengths = -1
1458
+ else:
1459
+ if input_ids is not None:
1460
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1461
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1462
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1463
+ sequence_lengths = sequence_lengths.to(logits.device)
1464
+ else:
1465
+ sequence_lengths = -1
1466
+
1467
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1468
+
1469
+ loss = None
1470
+ if labels is not None:
1471
+ labels = labels.to(logits.device)
1472
+ if self.config.problem_type is None:
1473
+ if self.num_labels == 1:
1474
+ self.config.problem_type = "regression"
1475
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1476
+ self.config.problem_type = "single_label_classification"
1477
+ else:
1478
+ self.config.problem_type = "multi_label_classification"
1479
+
1480
+ if self.config.problem_type == "regression":
1481
+ loss_fct = MSELoss()
1482
+ if self.num_labels == 1:
1483
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1484
+ else:
1485
+ loss = loss_fct(pooled_logits, labels)
1486
+ elif self.config.problem_type == "single_label_classification":
1487
+ loss_fct = CrossEntropyLoss()
1488
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1489
+ elif self.config.problem_type == "multi_label_classification":
1490
+ loss_fct = BCEWithLogitsLoss()
1491
+ loss = loss_fct(pooled_logits, labels)
1492
+ if not return_dict:
1493
+ output = (pooled_logits,) + transformer_outputs[1:]
1494
+ return ((loss,) + output) if loss is not None else output
1495
+
1496
+ return SequenceClassifierOutputWithPast(
1497
+ loss=loss,
1498
+ logits=pooled_logits,
1499
+ past_key_values=transformer_outputs.past_key_values,
1500
+ hidden_states=transformer_outputs.hidden_states,
1501
+ attentions=transformer_outputs.attentions,
1502
+ )
steel-llm-step-1060000-ckpt/softmoe_v3.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+
8
+ def softmax(x: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
9
+ """
10
+ Compute the softmax along the specified dimensions.
11
+ This function adds the option to specify multiple dimensions
12
+
13
+ Args:
14
+ x (torch.Tensor): Input tensor.
15
+ dims (int or tuple[int]): The dimension or list of dimensions along which the softmax probabilities are computed.
16
+
17
+ Returns:
18
+ torch.Tensor: Output tensor containing softmax probabilities along the specified dimensions.
19
+ """
20
+ dtype = x.dtype
21
+ x = x.to(torch.float32)
22
+ max_vals = torch.amax(x, dim=dim, keepdim=True)
23
+ e_x = torch.exp(x - max_vals)
24
+ sum_exp = e_x.sum(dim=dim, keepdim=True)
25
+ return (e_x / sum_exp).to(dtype)
26
+
27
+ # copy from https://github.com/bwconrad/soft-moe
28
+ class SteelSoftMoEV3(nn.Module):
29
+ """
30
+ A wrapper class to create a Soft Mixture of Experts layer.
31
+
32
+ From "From Sparse to Soft Mixtures of Experts"
33
+ https://arxiv.org/pdf/2308.00951.pdf
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ config,
39
+ layer: Callable,
40
+ ) -> None:
41
+ """
42
+ Args:
43
+ dim (int): Dimensionality of input features.
44
+ num_experts (int): Number of experts.
45
+ slots_per_expert (int): Number of token slots per expert.
46
+ layer (Callable): Network layer of the experts.
47
+ normalize (bool): Normalize input and phi (sec. 2.3 from paper)
48
+ **layer_kwargs: Additional keyword arguments for the layer class.
49
+ """
50
+ super().__init__()
51
+
52
+ self.dim = config.hidden_size
53
+ self.num_experts = config.n_experts
54
+ self.slots_per_expert = config.slots_per_expert if hasattr(config, "slots_per_expert") else 1
55
+ self.normalize = True
56
+
57
+ # Initialize phi and normalization scaling factor
58
+ self.phi = nn.Parameter(torch.zeros(self.dim, self.num_experts, self.slots_per_expert))
59
+ if self.normalize:
60
+ self.scale = nn.Parameter(torch.ones(1))
61
+
62
+ # Initialize phi using LeCun normal initialization
63
+ # https://github.com/google-research/vmoe/blob/662341d007650d5bbb7c6a2bef7f3c759a20cc7e/vmoe/projects/soft_moe/router.py#L49C1-L49C1
64
+ nn.init.normal_(self.phi, mean=0, std=1 / self.dim**0.5)
65
+
66
+ # Create a list of expert networks
67
+ self.experts = nn.ModuleList(
68
+ [layer(config) for _ in range(self.num_experts)]
69
+ )
70
+
71
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
72
+ """
73
+ Forward pass through the Soft-MoE layer (algorithm 1 from paper).
74
+
75
+ Args:
76
+ x (torch.Tensor): Input tensor of shape [batch_size, seq_len, input_dim].
77
+
78
+ Returns:
79
+ torch.Tensor: Output tensor of shape [batch_size, seq_len, input_dim].
80
+ """
81
+ assert (
82
+ x.shape[-1] == self.dim
83
+ ), f"Input feature dim of {x.shape[-1]} does not match layer dim of {self.dim}"
84
+ assert (
85
+ len(x.shape) == 3
86
+ ), f"Input expected to have 3 dimensions but has {len(x.shape)}"
87
+
88
+ phi = self.phi
89
+
90
+ # Normalize input and phi
91
+ if self.normalize:
92
+ x = F.normalize(x, dim=2) # [b, m, d]
93
+ phi = self.scale * F.normalize(phi, dim=0) # [d, n, p]
94
+
95
+ # Compute dispatch and combine weights
96
+ logits = torch.einsum("bmd,dnp->bmnp", x, phi)
97
+ d = softmax(logits, dim=1)
98
+ c = softmax(logits, dim=(2, 3))
99
+ # tmp = c[0,:,:,0].reshape([c.shape[1],-1])
100
+ # print("num:",tmp, "shape:",tmp.shape, "sum:",tmp.sum(dim=1))
101
+ # Compute input slots as weighted average of input tokens using dispatch weights
102
+ xs = torch.einsum("bmd,bmnp->bnpd", x, d)
103
+
104
+ # Apply expert to corresponding slots
105
+ ys = torch.stack(
106
+ [f_i(xs[:, i, :, :]) for i, f_i in enumerate(self.experts)], dim=1
107
+ )
108
+
109
+ # Compute output tokens as weighted average of output slots using combine weights
110
+ y = torch.einsum("bnpd,bmnp->bmd", ys, c)
111
+
112
+ return y
steel-llm-step-1060000-ckpt/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
steel-llm-step-1060000-ckpt/tokenizer_config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": ["<|im_start|>", "<|im_end|>"],
30
+ "bos_token": null,
31
+ "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 %}",
32
+ "clean_up_tokenization_spaces": false,
33
+ "eos_token": "<|im_end|>",
34
+ "errors": "replace",
35
+ "model_max_length": 32768,
36
+ "pad_token": "<|endoftext|>",
37
+ "split_special_tokens": false,
38
+ "tokenizer_class": "Qwen2Tokenizer",
39
+ "unk_token": null
40
+ }
41
+
steel-llm-step-1060000-ckpt/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
steel-llm-step-480000-ckpt/config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "FFN_type": "softmoe_v3",
3
+ "_name_or_path": "./steel_modify_from_qwen_1_5",
4
+ "architectures": [
5
+ "SteelForCausalLM"
6
+ ],
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_steel.SteelConfig",
10
+ "AutoModelForCausalLM": "modeling_steel.SteelForCausalLM"
11
+ },
12
+ "bos_token_id": 151643,
13
+ "eos_token_id": 151645,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 1792,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 1792,
18
+ "max_position_embeddings": 32768,
19
+ "max_window_layers": 21,
20
+ "mlp_div_ratio": 4,
21
+ "mlp_type": "senet",
22
+ "model_type": "qwen2",
23
+ "n_experts": 6,
24
+ "num_attention_heads": 32,
25
+ "num_hidden_layers": 18,
26
+ "num_key_value_heads": 32,
27
+ "rms_norm_eps": 1e-06,
28
+ "rope_theta": 1000000.0,
29
+ "sliding_window": 32768,
30
+ "slots_per_expert": 1,
31
+ "tie_word_embeddings": false,
32
+ "torch_dtype": "float32",
33
+ "transformers_version": "4.41.1",
34
+ "use_cache": true,
35
+ "use_sliding_window": false,
36
+ "vocab_size": 151936
37
+ }
steel-llm-step-480000-ckpt/configuration_steel.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 zhanshijin and lishu. All rights reserved.
3
+ #
4
+ # This project copy from qwen1.5
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ Steel model configuration"""
17
+
18
+ from transformers.configuration_utils import PretrainedConfig
19
+ from transformers.utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+
26
+
27
+ class SteelConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`Qwen2Model`]. It is used to instantiate a
30
+ Qwen2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
31
+ with the defaults will yield a similar configuration to that of
32
+ Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PretrainedConfig`] for more information.
36
+
37
+
38
+ Args:
39
+ vocab_size (`int`, *optional*, defaults to 151936):
40
+ Vocabulary size of the Qwen2 model. Defines the number of different tokens that can be represented by the
41
+ `inputs_ids` passed when calling [`Qwen2Model`]
42
+ hidden_size (`int`, *optional*, defaults to 4096):
43
+ Dimension of the hidden representations.
44
+ intermediate_size (`int`, *optional*, defaults to 22016):
45
+ Dimension of the MLP representations.
46
+ num_hidden_layers (`int`, *optional*, defaults to 32):
47
+ Number of hidden layers in the Transformer encoder.
48
+ num_attention_heads (`int`, *optional*, defaults to 32):
49
+ Number of attention heads for each attention layer in the Transformer encoder.
50
+ num_key_value_heads (`int`, *optional*, defaults to 32):
51
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
52
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
53
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
54
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
55
+ by meanpooling all the original heads within that group. For more details checkout [this
56
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
57
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
58
+ The non-linear activation function (function or string) in the decoder.
59
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
60
+ The maximum sequence length that this model might ever be used with.
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
64
+ The epsilon used by the rms normalization layers.
65
+ use_cache (`bool`, *optional*, defaults to `True`):
66
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
67
+ relevant if `config.is_decoder=True`.
68
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
69
+ Whether the model's input and output word embeddings should be tied.
70
+ rope_theta (`float`, *optional*, defaults to 10000.0):
71
+ The base period of the RoPE embeddings.
72
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
73
+ Whether to use sliding window attention.
74
+ sliding_window (`int`, *optional*, defaults to 4096):
75
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
76
+ max_window_layers (`int`, *optional*, defaults to 28):
77
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
78
+ attention_dropout (`float`, *optional*, defaults to 0.0):
79
+ The dropout ratio for the attention probabilities.
80
+ """
81
+
82
+ model_type = "qwen2"
83
+ keys_to_ignore_at_inference = ["past_key_values"]
84
+
85
+ def __init__(
86
+ self,
87
+ vocab_size=151936,
88
+ hidden_size=4096,
89
+ intermediate_size=22016,
90
+ num_hidden_layers=32,
91
+ num_attention_heads=32,
92
+ num_key_value_heads=32,
93
+ hidden_act="silu",
94
+ max_position_embeddings=32768,
95
+ initializer_range=0.02,
96
+ rms_norm_eps=1e-6,
97
+ use_cache=True,
98
+ tie_word_embeddings=False,
99
+ rope_theta=10000.0,
100
+ use_sliding_window=False,
101
+ sliding_window=4096,
102
+ max_window_layers=28,
103
+ attention_dropout=0.0,
104
+ **kwargs,
105
+ ):
106
+ self.vocab_size = vocab_size
107
+ self.max_position_embeddings = max_position_embeddings
108
+ self.hidden_size = hidden_size
109
+ self.intermediate_size = intermediate_size
110
+ self.num_hidden_layers = num_hidden_layers
111
+ self.num_attention_heads = num_attention_heads
112
+ self.use_sliding_window = use_sliding_window
113
+ self.sliding_window = sliding_window
114
+ self.max_window_layers = max_window_layers
115
+
116
+ # for backward compatibility
117
+ if num_key_value_heads is None:
118
+ num_key_value_heads = num_attention_heads
119
+
120
+ self.num_key_value_heads = num_key_value_heads
121
+ self.hidden_act = hidden_act
122
+ self.initializer_range = initializer_range
123
+ self.rms_norm_eps = rms_norm_eps
124
+ self.use_cache = use_cache
125
+ self.rope_theta = rope_theta
126
+ self.attention_dropout = attention_dropout
127
+
128
+ super().__init__(
129
+ tie_word_embeddings=tie_word_embeddings,
130
+ **kwargs,
131
+ )
steel-llm-step-480000-ckpt/generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 151643,
4
+ "eos_token_id": 151645,
5
+ "transformers_version": "4.41.1"
6
+ }
steel-llm-step-480000-ckpt/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
steel-llm-step-480000-ckpt/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a74bc70abbfb585eb98971db725598c85942b90859f9bfa63842a0d58b528607
3
+ size 4491766872
steel-llm-step-480000-ckpt/modeling_steel.py ADDED
@@ -0,0 +1,1499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The zhanshijin and lishu. All rights reserved.
3
+ #
4
+ #
5
+ #This model copy from qwen1.5.
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+ """ PyTorch Steel model."""
19
+ import inspect
20
+ import math
21
+ import warnings
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.nn.functional as F
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+
30
+ from transformers.activations import ACT2FN
31
+ from transformers.cache_utils import Cache, DynamicCache
32
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
33
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
34
+ from transformers.modeling_utils import PreTrainedModel
35
+ from transformers.utils import (
36
+ add_start_docstrings,
37
+ add_start_docstrings_to_model_forward,
38
+ is_flash_attn_2_available,
39
+ is_flash_attn_greater_or_equal_2_10,
40
+ logging,
41
+ replace_return_docstrings,
42
+ )
43
+ from configuration_steel import SteelConfig
44
+ from softmoe_v3 import SteelSoftMoEV3
45
+
46
+ if is_flash_attn_2_available():
47
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
48
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
49
+
50
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
51
+ print("zhanshijin: surrport flash_attn_2")
52
+ print(f"zhanshijin: if flash attn surrport window:{_flash_supports_window_size}")
53
+ else:
54
+ print("zhanshijin: not surrport flash_attn_2")
55
+
56
+ logger = logging.get_logger(__name__)
57
+
58
+ rms_norm = None
59
+ def _import_cuda_rmsnorm():
60
+ global rms_norm
61
+ try:
62
+ from flash_attn.ops.rms_norm import rms_norm as __rms_norm
63
+ rms_norm = __rms_norm
64
+ print("zhanshijin: success import cuda __rms_norm")
65
+ except ImportError:
66
+ logger.warn(
67
+ "Warning: import flash_attn rms_norm fail, please install FlashAttention layer_norm to get higher efficiency "
68
+ "https://github.com/Dao-AILab/flash-attention/tree/main/csrc/layer_norm"
69
+ )
70
+
71
+ _CONFIG_FOR_DOC = "SteelConfig"
72
+
73
+
74
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
75
+ def _get_unpad_data(attention_mask):
76
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
77
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
78
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
79
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
80
+ return (
81
+ indices,
82
+ cu_seqlens,
83
+ max_seqlen_in_batch,
84
+ )
85
+
86
+
87
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Steel
88
+ class SteelRMSNorm(nn.Module):
89
+ def __init__(self, hidden_size, eps=1e-6):
90
+ """
91
+ SteelRMSNorm is equivalent to T5LayerNorm
92
+ """
93
+ super().__init__()
94
+ self.weight = nn.Parameter(torch.ones(hidden_size))
95
+ self.variance_epsilon = eps
96
+
97
+ def forward(self, hidden_states):
98
+ if rms_norm is not None and hidden_states.is_cuda:
99
+ return rms_norm(hidden_states, self.weight, self.variance_epsilon)
100
+ else:
101
+ input_dtype = hidden_states.dtype
102
+ hidden_states = hidden_states.to(torch.float32)
103
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
104
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
105
+ # test precision consistency
106
+ # from flash_attn.ops.rms_norm import rms_norm as _rms_norm
107
+ # print(_rms_norm(hidden_states, self.weight, self.variance_epsilon)[0,0,:10])
108
+ # print((self.weight * hidden_states.to(input_dtype))[0,0,:10])
109
+ return self.weight * hidden_states.to(input_dtype)
110
+
111
+
112
+ # Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Steel
113
+ class SteelRotaryEmbedding(nn.Module):
114
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
115
+ super().__init__()
116
+
117
+ self.dim = dim
118
+ self.max_position_embeddings = max_position_embeddings
119
+ self.base = base
120
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
121
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
122
+
123
+ # Build here to make `torch.jit.trace` work.
124
+ self._set_cos_sin_cache(
125
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
126
+ )
127
+
128
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
129
+ self.max_seq_len_cached = seq_len
130
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
131
+
132
+ freqs = torch.outer(t, self.inv_freq)
133
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
134
+ emb = torch.cat((freqs, freqs), dim=-1)
135
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
136
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
137
+
138
+ def forward(self, x, seq_len=None):
139
+ # x: [bs, num_attention_heads, seq_len, head_size]
140
+ if seq_len > self.max_seq_len_cached:
141
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
142
+
143
+ return (
144
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
145
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
146
+ )
147
+
148
+
149
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
150
+ def rotate_half(x):
151
+ """Rotates half the hidden dims of the input."""
152
+ x1 = x[..., : x.shape[-1] // 2]
153
+ x2 = x[..., x.shape[-1] // 2 :]
154
+ return torch.cat((-x2, x1), dim=-1)
155
+
156
+
157
+ # Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
158
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
159
+ """Applies Rotary Position Embedding to the query and key tensors.
160
+
161
+ Args:
162
+ q (`torch.Tensor`): The query tensor.
163
+ k (`torch.Tensor`): The key tensor.
164
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
165
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
166
+ position_ids (`torch.Tensor`):
167
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
168
+ used to pass offsetted position ids when working with a KV-cache.
169
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
170
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
171
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
172
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
173
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
174
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
175
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
176
+ Returns:
177
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
178
+ """
179
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
180
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
181
+ q_embed = (q * cos) + (rotate_half(q) * sin)
182
+ k_embed = (k * cos) + (rotate_half(k) * sin)
183
+ return q_embed, k_embed
184
+
185
+
186
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Steel->Steel
187
+ class SteelMLP(nn.Module):
188
+ def __init__(self, config):
189
+ super().__init__()
190
+ self.config = config
191
+ self.hidden_size = config.hidden_size
192
+ self.intermediate_size = config.intermediate_size //config.mlp_div_ratio
193
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
194
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
195
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
196
+ self.act_fn = ACT2FN[config.hidden_act]
197
+
198
+ def forward(self, x):
199
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
200
+
201
+ class SteelSENet(nn.Module):
202
+ def __init__(self, config):
203
+ super().__init__()
204
+ self.config = config
205
+ self.hidden_size = config.hidden_size
206
+ self.intermediate_size = config.intermediate_size //config.mlp_div_ratio
207
+ self.gate_up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
208
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
209
+ self.gate_down_proj = nn.Linear(self.intermediate_size,self.hidden_size, bias=False)
210
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
211
+ self.act_fn1 = ACT2FN[config.hidden_act]
212
+ self.act_fn2 = ACT2FN[config.hidden_act]
213
+
214
+ def forward(self, x):
215
+ x = self.act_fn1(self.gate_up_proj(x)) * self.up_proj(x)
216
+ return self.act_fn2(self.gate_down_proj(x)) * self.down_proj(x)
217
+
218
+
219
+ class SteelSoftMoeV1(nn.Module):
220
+ def __init__(self, config, layer=None):
221
+ super().__init__()
222
+ self.config = config
223
+ self.experts = nn.ModuleList([layer(config) for _ in range(config.n_experts)])
224
+ self.gating = nn.Linear(config.hidden_size, config.n_experts)
225
+ def forward(self, x):
226
+ weights = self.gating(x)
227
+ weights = nn.functional.softmax(weights, dim=-1, dtype=torch.float32).to(x.dtype)
228
+ outputs = torch.stack(
229
+ [expert(x) for expert in self.experts], dim=2)
230
+ weights = weights.unsqueeze(-1)
231
+ return torch.sum(outputs * weights, dim=2)
232
+
233
+ class SteelSoftMoeV2(nn.Module):
234
+ def __init__(self, config, layer):
235
+ super().__init__()
236
+ self.config = config
237
+ self.experts = nn.ModuleList([layer(config) for _ in range(config.n_experts)])
238
+ self.score = nn.Parameter(torch.randn(config.hidden_size, config.n_experts * config.slots_per_expert))
239
+
240
+ def forward(self, x):
241
+ logits = torch.matmul(x, self.score) # (batch_size, seq_len, slots)
242
+ dispatch_weights = F.softmax(logits, dim=-1,dtype=torch.float32).to(x.dtype)
243
+ combine_weights = F.softmax(logits, dim=1,dtype=torch.float32).to(x.dtype)
244
+ xs = torch.bmm(dispatch_weights.transpose(1, 2), x)
245
+ ys = torch.cat(
246
+ [expert(xs[:, i * self.config.slots_per_expert : (i + 1) * self.config.slots_per_expert, :])
247
+ for i, expert in enumerate(self.experts)],
248
+ dim=1
249
+ )
250
+ y = torch.bmm(combine_weights, ys)
251
+ return y
252
+
253
+
254
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
255
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
256
+ """
257
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
258
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
259
+ """
260
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
261
+ if n_rep == 1:
262
+ return hidden_states
263
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
264
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
265
+
266
+
267
+ class SteelAttention(nn.Module):
268
+ """
269
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
270
+ and "Generating Long Sequences with Sparse Transformers".
271
+ """
272
+
273
+ def __init__(self, config: SteelConfig, layer_idx: Optional[int] = None):
274
+ super().__init__()
275
+ self.config = config
276
+ self.layer_idx = layer_idx
277
+ if layer_idx is None:
278
+ logger.warning_once(
279
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
280
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
281
+ "when creating this class."
282
+ )
283
+
284
+ self.hidden_size = config.hidden_size
285
+ self.num_heads = config.num_attention_heads
286
+ self.head_dim = self.hidden_size // self.num_heads
287
+ self.num_key_value_heads = config.num_key_value_heads
288
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
289
+ self.max_position_embeddings = config.max_position_embeddings
290
+ self.rope_theta = config.rope_theta
291
+ self.is_causal = True
292
+ self.attention_dropout = config.attention_dropout
293
+
294
+ if (self.head_dim * self.num_heads) != self.hidden_size:
295
+ raise ValueError(
296
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
297
+ f" and `num_heads`: {self.num_heads})."
298
+ )
299
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
300
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
301
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
302
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
303
+
304
+ self.rotary_emb = SteelRotaryEmbedding(
305
+ self.head_dim,
306
+ max_position_embeddings=self.max_position_embeddings,
307
+ base=self.rope_theta,
308
+ )
309
+
310
+ def forward(
311
+ self,
312
+ hidden_states: torch.Tensor,
313
+ attention_mask: Optional[torch.Tensor] = None,
314
+ position_ids: Optional[torch.LongTensor] = None,
315
+ past_key_value: Optional[Cache] = None,
316
+ output_attentions: bool = False,
317
+ use_cache: bool = False,
318
+ **kwargs,
319
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
320
+ if "padding_mask" in kwargs:
321
+ warnings.warn(
322
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
323
+ )
324
+ bsz, q_len, _ = hidden_states.size()
325
+
326
+ query_states = self.q_proj(hidden_states)
327
+ key_states = self.k_proj(hidden_states)
328
+ value_states = self.v_proj(hidden_states)
329
+
330
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
331
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
332
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
333
+
334
+ kv_seq_len = key_states.shape[-2]
335
+ if past_key_value is not None:
336
+ if self.layer_idx is None:
337
+ raise ValueError(
338
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
339
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
340
+ "with a layer index."
341
+ )
342
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
343
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
344
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
345
+
346
+
347
+ if past_key_value is not None:
348
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
349
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
350
+
351
+ # repeat k/v heads if n_kv_heads < n_heads
352
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
353
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
354
+
355
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
356
+
357
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
358
+ raise ValueError(
359
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
360
+ f" {attn_weights.size()}"
361
+ )
362
+
363
+ if attention_mask is not None:
364
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
365
+ raise ValueError(
366
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
367
+ )
368
+
369
+ attn_weights = attn_weights + attention_mask
370
+
371
+ # upcast attention to fp32
372
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
373
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
374
+ attn_output = torch.matmul(attn_weights, value_states)
375
+
376
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
377
+ raise ValueError(
378
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
379
+ f" {attn_output.size()}"
380
+ )
381
+
382
+ attn_output = attn_output.transpose(1, 2).contiguous()
383
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
384
+
385
+ attn_output = self.o_proj(attn_output)
386
+
387
+ if not output_attentions:
388
+ attn_weights = None
389
+
390
+ return attn_output, attn_weights, past_key_value
391
+
392
+
393
+ class SteelFlashAttention2(SteelAttention):
394
+ """
395
+ Steel flash attention module, following Steel attention module. This module inherits from `SteelAttention`
396
+ as the weights of the module stays untouched. The only required change would be on the forward pass
397
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
398
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
399
+ config.max_window_layers layers.
400
+ """
401
+
402
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
403
+ def __init__(self, *args, **kwargs):
404
+ super().__init__(*args, **kwargs)
405
+
406
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
407
+ # 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.
408
+ # 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).
409
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
410
+
411
+ def forward(
412
+ self,
413
+ hidden_states: torch.Tensor,
414
+ attention_mask: Optional[torch.Tensor] = None,
415
+ position_ids: Optional[torch.LongTensor] = None,
416
+ past_key_value: Optional[Cache] = None,
417
+ output_attentions: bool = False,
418
+ use_cache: bool = False,
419
+ **kwargs,
420
+ ):
421
+ if "padding_mask" in kwargs:
422
+ warnings.warn(
423
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
424
+ )
425
+
426
+ # overwrite attention_mask with padding_mask
427
+ attention_mask = kwargs.pop("padding_mask")
428
+ bsz, q_len, _ = hidden_states.size()
429
+
430
+ query_states = self.q_proj(hidden_states)
431
+ key_states = self.k_proj(hidden_states)
432
+ value_states = self.v_proj(hidden_states)
433
+
434
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
435
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
436
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
437
+
438
+ kv_seq_len = key_states.shape[-2]
439
+ if past_key_value is not None:
440
+ if self.layer_idx is None:
441
+ raise ValueError(
442
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
443
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
444
+ "with a layer index."
445
+ )
446
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
447
+
448
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
449
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
450
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
451
+
452
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
453
+
454
+ use_sliding_windows = (
455
+ _flash_supports_window_size
456
+ and getattr(self.config, "sliding_window", None) is not None
457
+ and kv_seq_len > self.config.sliding_window
458
+ and self.config.use_sliding_window
459
+ )
460
+
461
+ if not _flash_supports_window_size:
462
+ logger.warning_once(
463
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
464
+ " make sure to upgrade flash-attn library."
465
+ )
466
+
467
+ if past_key_value is not None:
468
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
469
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
470
+ if (
471
+ getattr(self.config, "sliding_window", None) is not None
472
+ and kv_seq_len > self.config.sliding_window
473
+ and cache_has_contents
474
+ ):
475
+ slicing_tokens = 1 - self.config.sliding_window
476
+
477
+ past_key = past_key_value[self.layer_idx][0]
478
+ past_value = past_key_value[self.layer_idx][1]
479
+
480
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
481
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
482
+
483
+ if past_key.shape[-2] != self.config.sliding_window - 1:
484
+ raise ValueError(
485
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
486
+ f" {past_key.shape}"
487
+ )
488
+
489
+ if attention_mask is not None:
490
+ attention_mask = attention_mask[:, slicing_tokens:]
491
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
492
+
493
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
494
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
495
+
496
+ # repeat k/v heads if n_kv_heads < n_heads
497
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
498
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
499
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
500
+
501
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
502
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
503
+ # cast them back in float16 just to be sure everything works as expected.
504
+ input_dtype = query_states.dtype
505
+ if input_dtype == torch.float32:
506
+ if torch.is_autocast_enabled():
507
+ target_dtype = torch.get_autocast_gpu_dtype()
508
+ # Handle the case where the model is quantized
509
+ elif hasattr(self.config, "_pre_quantization_dtype"):
510
+ target_dtype = self.config._pre_quantization_dtype
511
+ else:
512
+ target_dtype = self.q_proj.weight.dtype
513
+
514
+ logger.warning_once(
515
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
516
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
517
+ f" {target_dtype}."
518
+ )
519
+
520
+ query_states = query_states.to(target_dtype)
521
+ key_states = key_states.to(target_dtype)
522
+ value_states = value_states.to(target_dtype)
523
+
524
+ # Reashape to the expected shape for Flash Attention
525
+ query_states = query_states.transpose(1, 2)
526
+ key_states = key_states.transpose(1, 2)
527
+ value_states = value_states.transpose(1, 2)
528
+
529
+ attn_output = self._flash_attention_forward(
530
+ query_states,
531
+ key_states,
532
+ value_states,
533
+ attention_mask,
534
+ q_len,
535
+ dropout=dropout_rate,
536
+ use_sliding_windows=use_sliding_windows,
537
+ )
538
+
539
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
540
+ attn_output = self.o_proj(attn_output)
541
+
542
+ if not output_attentions:
543
+ attn_weights = None
544
+
545
+ return attn_output, attn_weights, past_key_value
546
+
547
+ def _flash_attention_forward(
548
+ self,
549
+ query_states,
550
+ key_states,
551
+ value_states,
552
+ attention_mask,
553
+ query_length,
554
+ dropout=0.0,
555
+ softmax_scale=None,
556
+ use_sliding_windows=False,
557
+ ):
558
+ """
559
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
560
+ first unpad the input, then computes the attention scores and pad the final attention scores.
561
+
562
+ Args:
563
+ query_states (`torch.Tensor`):
564
+ Input query states to be passed to Flash Attention API
565
+ key_states (`torch.Tensor`):
566
+ Input key states to be passed to Flash Attention API
567
+ value_states (`torch.Tensor`):
568
+ Input value states to be passed to Flash Attention API
569
+ attention_mask (`torch.Tensor`):
570
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
571
+ position of padding tokens and 1 for the position of non-padding tokens.
572
+ dropout (`float`):
573
+ Attention dropout
574
+ softmax_scale (`float`, *optional*):
575
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
576
+ use_sliding_windows (`bool`, *optional*):
577
+ Whether to activate sliding window attention.
578
+ """
579
+ if not self._flash_attn_uses_top_left_mask:
580
+ causal = self.is_causal
581
+ else:
582
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
583
+ causal = self.is_causal and query_length != 1
584
+
585
+ # Decide whether to use SWA or not by layer index.
586
+ if use_sliding_windows and self.layer_idx >= self.config.max_window_layers:
587
+ use_sliding_windows = False
588
+
589
+ # Contains at least one padding token in the sequence
590
+ if attention_mask is not None:
591
+ batch_size = query_states.shape[0]
592
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
593
+ query_states, key_states, value_states, attention_mask, query_length
594
+ )
595
+
596
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
597
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
598
+
599
+ if not use_sliding_windows:
600
+ attn_output_unpad = flash_attn_varlen_func(
601
+ query_states,
602
+ key_states,
603
+ value_states,
604
+ cu_seqlens_q=cu_seqlens_q,
605
+ cu_seqlens_k=cu_seqlens_k,
606
+ max_seqlen_q=max_seqlen_in_batch_q,
607
+ max_seqlen_k=max_seqlen_in_batch_k,
608
+ dropout_p=dropout,
609
+ softmax_scale=softmax_scale,
610
+ causal=causal,
611
+ )
612
+ else:
613
+ attn_output_unpad = flash_attn_varlen_func(
614
+ query_states,
615
+ key_states,
616
+ value_states,
617
+ cu_seqlens_q=cu_seqlens_q,
618
+ cu_seqlens_k=cu_seqlens_k,
619
+ max_seqlen_q=max_seqlen_in_batch_q,
620
+ max_seqlen_k=max_seqlen_in_batch_k,
621
+ dropout_p=dropout,
622
+ softmax_scale=softmax_scale,
623
+ causal=causal,
624
+ window_size=(self.config.sliding_window, self.config.sliding_window),
625
+ )
626
+
627
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
628
+ else:
629
+ if not use_sliding_windows:
630
+ attn_output = flash_attn_func(
631
+ query_states,
632
+ key_states,
633
+ value_states,
634
+ dropout,
635
+ softmax_scale=softmax_scale,
636
+ causal=causal,
637
+ )
638
+ else:
639
+ attn_output = flash_attn_func(
640
+ query_states,
641
+ key_states,
642
+ value_states,
643
+ dropout,
644
+ softmax_scale=softmax_scale,
645
+ causal=causal,
646
+ window_size=(self.config.sliding_window, self.config.sliding_window),
647
+ )
648
+
649
+ return attn_output
650
+
651
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
652
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
653
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
654
+
655
+ # On the first iteration we need to properly re-create the padding mask
656
+ # by slicing it on the proper place
657
+ if kv_seq_len != attention_mask.shape[-1]:
658
+ attention_mask_num_tokens = attention_mask.shape[-1]
659
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
660
+
661
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
662
+
663
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
664
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
665
+
666
+ if query_length == kv_seq_len:
667
+ query_layer = index_first_axis(
668
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
669
+ )
670
+ cu_seqlens_q = cu_seqlens_k
671
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
672
+ indices_q = indices_k
673
+ elif query_length == 1:
674
+ max_seqlen_in_batch_q = 1
675
+ cu_seqlens_q = torch.arange(
676
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
677
+ ) # There is a memcpy here, that is very bad.
678
+ indices_q = cu_seqlens_q[:-1]
679
+ query_layer = query_layer.squeeze(1)
680
+ else:
681
+ # The -q_len: slice assumes left padding.
682
+ attention_mask = attention_mask[:, -query_length:]
683
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
684
+
685
+ return (
686
+ query_layer,
687
+ key_layer,
688
+ value_layer,
689
+ indices_q,
690
+ (cu_seqlens_q, cu_seqlens_k),
691
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
692
+ )
693
+
694
+
695
+ # Copied from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Steel
696
+ class SteelSdpaAttention(SteelAttention):
697
+ """
698
+ Steel attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
699
+ `SteelAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
700
+ SDPA API.
701
+ """
702
+
703
+ # Adapted from SteelAttention.forward
704
+ def forward(
705
+ self,
706
+ hidden_states: torch.Tensor,
707
+ attention_mask: Optional[torch.Tensor] = None,
708
+ position_ids: Optional[torch.LongTensor] = None,
709
+ past_key_value: Optional[Cache] = None,
710
+ output_attentions: bool = False,
711
+ use_cache: bool = False,
712
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
713
+ if output_attentions:
714
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
715
+ logger.warning_once(
716
+ "SteelModel is using SteelSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
717
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
718
+ )
719
+ return super().forward(
720
+ hidden_states=hidden_states,
721
+ attention_mask=attention_mask,
722
+ position_ids=position_ids,
723
+ past_key_value=past_key_value,
724
+ output_attentions=output_attentions,
725
+ use_cache=use_cache,
726
+ )
727
+
728
+ bsz, q_len, _ = hidden_states.size()
729
+
730
+ query_states = self.q_proj(hidden_states)
731
+ key_states = self.k_proj(hidden_states)
732
+ value_states = self.v_proj(hidden_states)
733
+
734
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
735
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
736
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
737
+
738
+ kv_seq_len = key_states.shape[-2]
739
+ if past_key_value is not None:
740
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
741
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
742
+
743
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
744
+
745
+ if past_key_value is not None:
746
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
747
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
748
+
749
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
750
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
751
+
752
+ if attention_mask is not None:
753
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
754
+ raise ValueError(
755
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
756
+ )
757
+
758
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
759
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
760
+ if query_states.device.type == "cuda" and attention_mask is not None:
761
+ query_states = query_states.contiguous()
762
+ key_states = key_states.contiguous()
763
+ value_states = value_states.contiguous()
764
+
765
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
766
+ query_states,
767
+ key_states,
768
+ value_states,
769
+ attn_mask=attention_mask,
770
+ dropout_p=self.attention_dropout if self.training else 0.0,
771
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
772
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
773
+ )
774
+
775
+ attn_output = attn_output.transpose(1, 2).contiguous()
776
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
777
+
778
+ attn_output = self.o_proj(attn_output)
779
+
780
+ return attn_output, None, past_key_value
781
+
782
+
783
+ Steel_ATTENTION_CLASSES = {
784
+ "eager": SteelAttention,
785
+ "flash_attention_2": SteelFlashAttention2,
786
+ "sdpa": SteelSdpaAttention,
787
+ }
788
+
789
+
790
+ class SteelDecoderLayer(nn.Module):
791
+ def __init__(self, config: SteelConfig, layer_idx: int):
792
+ super().__init__()
793
+ self.hidden_size = config.hidden_size
794
+
795
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
796
+ logger.warning_once(
797
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
798
+ "unexpected results may be encountered."
799
+ )
800
+ self.self_attn = Steel_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
801
+ if config.mlp_type == "raw":
802
+ mlp_class = SteelMLP
803
+ logger.warning_once(f"mlp_class: SteelMLP")
804
+ elif config.mlp_type == "senet":
805
+ mlp_class = SteelSENet
806
+ logger.warning_once(f"mlp_class: SteelSENet")
807
+ else:
808
+ raise NameError(f"No this mlp type: {config.mlp_type}")
809
+
810
+ if config.FFN_type == "raw":
811
+ self.mlp = mlp_class(config)
812
+ logger.warning_once(f"FFN: {mlp_class}")
813
+ elif config.FFN_type == "softmoe_v1":
814
+ self.mlp = SteelSoftMoeV1(config, layer=mlp_class)
815
+ logger.warning_once(f"FFN: SteelSoftMoeV1")
816
+ elif config.FFN_type == "softmoe_v2":
817
+ self.mlp = SteelSoftMoeV2(config, layer=mlp_class)
818
+ logger.warning_once(f"FFN: SteelSoftMoeV2")
819
+ elif config.FFN_type == "softmoe_v3":
820
+ self.mlp = SteelSoftMoEV3(config=config, layer=mlp_class)
821
+ logger.warning_once(f"FFN: SteelSoftMoeV3")
822
+ else:
823
+ raise NameError(f"No this FFN type: {config.FFN_type}")
824
+
825
+ self.input_layernorm = SteelRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
826
+ self.post_attention_layernorm = SteelRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
827
+
828
+ def forward(
829
+ self,
830
+ hidden_states: torch.Tensor,
831
+ attention_mask: Optional[torch.Tensor] = None,
832
+ position_ids: Optional[torch.LongTensor] = None,
833
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
834
+ output_attentions: Optional[bool] = False,
835
+ use_cache: Optional[bool] = False,
836
+ **kwargs,
837
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
838
+ if "padding_mask" in kwargs:
839
+ warnings.warn(
840
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
841
+ "Please make sure use `attention_mask` instead.`"
842
+ )
843
+ """
844
+ Args:
845
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
846
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
847
+ `(batch, sequence_length)` where padding elements are indicated by 0.
848
+ output_attentions (`bool`, *optional*):
849
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
850
+ returned tensors for more detail.
851
+ use_cache (`bool`, *optional*):
852
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
853
+ (see `past_key_values`).
854
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
855
+ """
856
+
857
+ residual = hidden_states
858
+
859
+ hidden_states = self.input_layernorm(hidden_states)
860
+
861
+ # Self Attention
862
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
863
+ hidden_states=hidden_states,
864
+ attention_mask=attention_mask,
865
+ position_ids=position_ids,
866
+ past_key_value=past_key_value,
867
+ output_attentions=output_attentions,
868
+ use_cache=use_cache,
869
+ )
870
+ hidden_states = residual + hidden_states
871
+
872
+ # Fully Connected
873
+ residual = hidden_states
874
+ hidden_states = self.post_attention_layernorm(hidden_states)
875
+ hidden_states = self.mlp(hidden_states)
876
+ hidden_states = residual + hidden_states
877
+
878
+ outputs = (hidden_states,)
879
+
880
+ if output_attentions:
881
+ outputs += (self_attn_weights,)
882
+
883
+ if use_cache:
884
+ outputs += (present_key_value,)
885
+
886
+ return outputs
887
+
888
+
889
+ Steel_START_DOCSTRING = r"""
890
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
891
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
892
+ etc.)
893
+
894
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
895
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
896
+ and behavior.
897
+
898
+ Parameters:
899
+ config ([`SteelConfig`]):
900
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
901
+ load the weights associated with the model, only the configuration. Check out the
902
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
903
+ """
904
+
905
+
906
+ @add_start_docstrings(
907
+ "The bare Steel Model outputting raw hidden-states without any specific head on top.",
908
+ Steel_START_DOCSTRING,
909
+ )
910
+ class SteelPreTrainedModel(PreTrainedModel):
911
+ config_class = SteelConfig
912
+ base_model_prefix = "model"
913
+ supports_gradient_checkpointing = True
914
+ _no_split_modules = ["SteelDecoderLayer"]
915
+ _skip_keys_device_placement = "past_key_values"
916
+ _supports_flash_attn_2 = True
917
+ _supports_sdpa = True
918
+ _supports_cache_class = True
919
+
920
+ def _init_weights(self, module):
921
+ std = self.config.initializer_range
922
+ if isinstance(module, nn.Linear):
923
+ module.weight.data.normal_(mean=0.0, std=std)
924
+ if module.bias is not None:
925
+ module.bias.data.zero_()
926
+ elif isinstance(module, nn.Embedding):
927
+ module.weight.data.normal_(mean=0.0, std=std)
928
+ if module.padding_idx is not None:
929
+ module.weight.data[module.padding_idx].zero_()
930
+
931
+
932
+ Steel_INPUTS_DOCSTRING = r"""
933
+ Args:
934
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
935
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
936
+ it.
937
+
938
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
939
+ [`PreTrainedTokenizer.__call__`] for details.
940
+
941
+ [What are input IDs?](../glossary#input-ids)
942
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
943
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
944
+
945
+ - 1 for tokens that are **not masked**,
946
+ - 0 for tokens that are **masked**.
947
+
948
+ [What are attention masks?](../glossary#attention-mask)
949
+
950
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
951
+ [`PreTrainedTokenizer.__call__`] for details.
952
+
953
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
954
+ `past_key_values`).
955
+
956
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
957
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
958
+ information on the default strategy.
959
+
960
+ - 1 indicates the head is **not masked**,
961
+ - 0 indicates the head is **masked**.
962
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
963
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
964
+ config.n_positions - 1]`.
965
+
966
+ [What are position IDs?](../glossary#position-ids)
967
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
968
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
969
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
970
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
971
+
972
+ Two formats are allowed:
973
+ - a [`~cache_utils.Cache`] instance;
974
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
975
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
976
+ cache format.
977
+
978
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
979
+ legacy cache format will be returned.
980
+
981
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
982
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
983
+ of shape `(batch_size, sequence_length)`.
984
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
985
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
986
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
987
+ model's internal embedding lookup matrix.
988
+ use_cache (`bool`, *optional*):
989
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
990
+ `past_key_values`).
991
+ output_attentions (`bool`, *optional*):
992
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
993
+ tensors for more detail.
994
+ output_hidden_states (`bool`, *optional*):
995
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
996
+ more detail.
997
+ return_dict (`bool`, *optional*):
998
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
999
+ """
1000
+
1001
+
1002
+ @add_start_docstrings(
1003
+ "The bare Steel Model outputting raw hidden-states without any specific head on top.",
1004
+ Steel_START_DOCSTRING,
1005
+ )
1006
+ class SteelModel(SteelPreTrainedModel):
1007
+ """
1008
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`SteelDecoderLayer`]
1009
+
1010
+ Args:
1011
+ config: SteelConfig
1012
+ """
1013
+
1014
+ def __init__(self, config: SteelConfig):
1015
+ super().__init__(config)
1016
+ self.padding_idx = config.pad_token_id
1017
+ self.vocab_size = config.vocab_size
1018
+
1019
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1020
+ self.layers = nn.ModuleList(
1021
+ [SteelDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1022
+ )
1023
+ self._attn_implementation = config._attn_implementation
1024
+ logger.warning_once(
1025
+ f"zhanshijin: now use _attn_implementation is {config._attn_implementation}, you can choose from {Steel_ATTENTION_CLASSES.keys()}"
1026
+ )
1027
+ self.norm = SteelRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1028
+
1029
+ self.gradient_checkpointing = False
1030
+ # Initialize weights and apply final processing
1031
+ self.post_init()
1032
+
1033
+ if hasattr(config, "use_cuda_rmsnorm") and config.use_cuda_rmsnorm:
1034
+ _import_cuda_rmsnorm()
1035
+ else:
1036
+ print("zhanshijin: use torch rmsnorm")
1037
+
1038
+ def get_input_embeddings(self):
1039
+ return self.embed_tokens
1040
+
1041
+ def set_input_embeddings(self, value):
1042
+ self.embed_tokens = value
1043
+
1044
+ @add_start_docstrings_to_model_forward(Steel_INPUTS_DOCSTRING)
1045
+ def forward(
1046
+ self,
1047
+ input_ids: torch.LongTensor = None,
1048
+ attention_mask: Optional[torch.Tensor] = None,
1049
+ position_ids: Optional[torch.LongTensor] = None,
1050
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1051
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1052
+ use_cache: Optional[bool] = None,
1053
+ output_attentions: Optional[bool] = None,
1054
+ output_hidden_states: Optional[bool] = None,
1055
+ return_dict: Optional[bool] = None,
1056
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1057
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1058
+ output_hidden_states = (
1059
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1060
+ )
1061
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1062
+
1063
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1064
+
1065
+ # retrieve input_ids and inputs_embeds
1066
+ if input_ids is not None and inputs_embeds is not None:
1067
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1068
+ elif input_ids is not None:
1069
+ batch_size, seq_length = input_ids.shape
1070
+ elif inputs_embeds is not None:
1071
+ batch_size, seq_length, _ = inputs_embeds.shape
1072
+ else:
1073
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
1074
+
1075
+ if self.gradient_checkpointing and self.training:
1076
+ if use_cache:
1077
+ logger.warning_once(
1078
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1079
+ )
1080
+ use_cache = False
1081
+
1082
+ past_key_values_length = 0
1083
+
1084
+ if use_cache:
1085
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1086
+ if use_legacy_cache:
1087
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1088
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1089
+
1090
+ if position_ids is None:
1091
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1092
+ position_ids = torch.arange(
1093
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1094
+ )
1095
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1096
+ else:
1097
+ position_ids = position_ids.view(-1, seq_length).long()
1098
+
1099
+ if inputs_embeds is None:
1100
+ inputs_embeds = self.embed_tokens(input_ids)
1101
+
1102
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1103
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1104
+ if is_padding_right:
1105
+ raise ValueError(
1106
+ "You are attempting to perform batched generation with padding_side='right'"
1107
+ " this may lead to unexpected behaviour for Flash Attention version of Steel. Make sure to "
1108
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1109
+ )
1110
+
1111
+ if self._attn_implementation == "flash_attention_2":
1112
+ # 2d mask is passed through the layers
1113
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1114
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1115
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1116
+ # the manual implementation that requires a 4D causal mask in all cases.
1117
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1118
+ attention_mask,
1119
+ (batch_size, seq_length),
1120
+ inputs_embeds,
1121
+ past_key_values_length,
1122
+ sliding_window=self.config.sliding_window,
1123
+ )
1124
+ else:
1125
+ # 4d mask is passed through the layers
1126
+ attention_mask = _prepare_4d_causal_attention_mask(
1127
+ attention_mask,
1128
+ (batch_size, seq_length),
1129
+ inputs_embeds,
1130
+ past_key_values_length,
1131
+ sliding_window=self.config.sliding_window,
1132
+ )
1133
+
1134
+ hidden_states = inputs_embeds
1135
+
1136
+ # decoder layers
1137
+ all_hidden_states = () if output_hidden_states else None
1138
+ all_self_attns = () if output_attentions else None
1139
+ next_decoder_cache = None
1140
+
1141
+ for decoder_layer in self.layers:
1142
+ if output_hidden_states:
1143
+ all_hidden_states += (hidden_states,)
1144
+
1145
+ if self.gradient_checkpointing and self.training:
1146
+ layer_outputs = self._gradient_checkpointing_func(
1147
+ decoder_layer.__call__,
1148
+ hidden_states,
1149
+ attention_mask,
1150
+ position_ids,
1151
+ past_key_values,
1152
+ output_attentions,
1153
+ use_cache,
1154
+ )
1155
+ else:
1156
+ layer_outputs = decoder_layer(
1157
+ hidden_states,
1158
+ attention_mask=attention_mask,
1159
+ position_ids=position_ids,
1160
+ past_key_value=past_key_values,
1161
+ output_attentions=output_attentions,
1162
+ use_cache=use_cache,
1163
+ )
1164
+
1165
+ hidden_states = layer_outputs[0]
1166
+
1167
+ if use_cache:
1168
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1169
+
1170
+ if output_attentions:
1171
+ all_self_attns += (layer_outputs[1],)
1172
+
1173
+ hidden_states = self.norm(hidden_states)
1174
+
1175
+ # add hidden states from the last decoder layer
1176
+ if output_hidden_states:
1177
+ all_hidden_states += (hidden_states,)
1178
+
1179
+ next_cache = None
1180
+ if use_cache:
1181
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1182
+
1183
+ if not return_dict:
1184
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1185
+ return BaseModelOutputWithPast(
1186
+ last_hidden_state=hidden_states,
1187
+ past_key_values=next_cache,
1188
+ hidden_states=all_hidden_states,
1189
+ attentions=all_self_attns,
1190
+ )
1191
+
1192
+
1193
+ class SteelForCausalLM(SteelPreTrainedModel):
1194
+ _tied_weights_keys = ["lm_head.weight"]
1195
+
1196
+ def __init__(self, config):
1197
+ super().__init__(config)
1198
+ self.model = SteelModel(config)
1199
+ self.vocab_size = config.vocab_size
1200
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1201
+
1202
+ # Initialize weights and apply final processing
1203
+ self.post_init()
1204
+
1205
+ def get_input_embeddings(self):
1206
+ return self.model.embed_tokens
1207
+
1208
+ def set_input_embeddings(self, value):
1209
+ self.model.embed_tokens = value
1210
+
1211
+ def get_output_embeddings(self):
1212
+ return self.lm_head
1213
+
1214
+ def set_output_embeddings(self, new_embeddings):
1215
+ self.lm_head = new_embeddings
1216
+
1217
+ def set_decoder(self, decoder):
1218
+ self.model = decoder
1219
+
1220
+ def get_decoder(self):
1221
+ return self.model
1222
+
1223
+ @add_start_docstrings_to_model_forward(Steel_INPUTS_DOCSTRING)
1224
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1225
+ def forward(
1226
+ self,
1227
+ input_ids: torch.LongTensor = None,
1228
+ attention_mask: Optional[torch.Tensor] = None,
1229
+ position_ids: Optional[torch.LongTensor] = None,
1230
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1231
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1232
+ labels: Optional[torch.LongTensor] = None,
1233
+ use_cache: Optional[bool] = None,
1234
+ output_attentions: Optional[bool] = None,
1235
+ output_hidden_states: Optional[bool] = None,
1236
+ return_dict: Optional[bool] = None,
1237
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1238
+ r"""
1239
+ Args:
1240
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1241
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1242
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1243
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1244
+
1245
+ Returns:
1246
+
1247
+ Example:
1248
+
1249
+ ```python
1250
+ >>> from transformers import AutoTokenizer, SteelForCausalLM
1251
+
1252
+ >>> model = SteelForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1253
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1254
+
1255
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1256
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1257
+
1258
+ >>> # Generate
1259
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1260
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1261
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1262
+ ```"""
1263
+
1264
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1265
+ output_hidden_states = (
1266
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1267
+ )
1268
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1269
+
1270
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1271
+ outputs = self.model(
1272
+ input_ids=input_ids,
1273
+ attention_mask=attention_mask,
1274
+ position_ids=position_ids,
1275
+ past_key_values=past_key_values,
1276
+ inputs_embeds=inputs_embeds,
1277
+ use_cache=use_cache,
1278
+ output_attentions=output_attentions,
1279
+ output_hidden_states=output_hidden_states,
1280
+ return_dict=return_dict,
1281
+ )
1282
+
1283
+ hidden_states = outputs[0]
1284
+ logits = self.lm_head(hidden_states)
1285
+ logits = logits.float()
1286
+
1287
+ loss = None
1288
+ if labels is not None:
1289
+ # Shift so that tokens < n predict n
1290
+ shift_logits = logits[..., :-1, :].contiguous()
1291
+ shift_labels = labels[..., 1:].contiguous()
1292
+ # Flatten the tokens
1293
+ loss_fct = CrossEntropyLoss()
1294
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1295
+ shift_labels = shift_labels.view(-1)
1296
+ # Enable model parallelism
1297
+ shift_labels = shift_labels.to(shift_logits.device)
1298
+ loss = loss_fct(shift_logits, shift_labels)
1299
+
1300
+ if not return_dict:
1301
+ output = (logits,) + outputs[1:]
1302
+ return (loss,) + output if loss is not None else output
1303
+
1304
+ return CausalLMOutputWithPast(
1305
+ loss=loss,
1306
+ logits=logits,
1307
+ past_key_values=outputs.past_key_values,
1308
+ hidden_states=outputs.hidden_states,
1309
+ attentions=outputs.attentions,
1310
+ )
1311
+
1312
+ def prepare_inputs_for_generation(
1313
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1314
+ ):
1315
+ # Omit tokens covered by past_key_values
1316
+ if past_key_values is not None:
1317
+ if isinstance(past_key_values, Cache):
1318
+ cache_length = past_key_values.get_seq_length()
1319
+ past_length = past_key_values.seen_tokens
1320
+ max_cache_length = past_key_values.get_max_length()
1321
+ else:
1322
+ cache_length = past_length = past_key_values[0][0].shape[2]
1323
+ max_cache_length = None
1324
+
1325
+ # Keep only the unprocessed tokens:
1326
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1327
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1328
+ # input)
1329
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1330
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1331
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1332
+ # input_ids based on the past_length.
1333
+ elif past_length < input_ids.shape[1]:
1334
+ input_ids = input_ids[:, past_length:]
1335
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1336
+
1337
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1338
+ if (
1339
+ max_cache_length is not None
1340
+ and attention_mask is not None
1341
+ and cache_length + input_ids.shape[1] > max_cache_length
1342
+ ):
1343
+ attention_mask = attention_mask[:, -max_cache_length:]
1344
+
1345
+ position_ids = kwargs.get("position_ids", None)
1346
+ if attention_mask is not None and position_ids is None:
1347
+ # create position_ids on the fly for batch generation
1348
+ position_ids = attention_mask.long().cumsum(-1) - 1
1349
+ position_ids.masked_fill_(attention_mask == 0, 1)
1350
+ if past_key_values:
1351
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1352
+
1353
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1354
+ if inputs_embeds is not None and past_key_values is None:
1355
+ model_inputs = {"inputs_embeds": inputs_embeds}
1356
+ else:
1357
+ model_inputs = {"input_ids": input_ids}
1358
+
1359
+ model_inputs.update(
1360
+ {
1361
+ "position_ids": position_ids,
1362
+ "past_key_values": past_key_values,
1363
+ "use_cache": kwargs.get("use_cache"),
1364
+ "attention_mask": attention_mask,
1365
+ }
1366
+ )
1367
+ return model_inputs
1368
+
1369
+ @staticmethod
1370
+ def _reorder_cache(past_key_values, beam_idx):
1371
+ reordered_past = ()
1372
+ for layer_past in past_key_values:
1373
+ reordered_past += (
1374
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1375
+ )
1376
+ return reordered_past
1377
+
1378
+
1379
+ @add_start_docstrings(
1380
+ """
1381
+ The Steel Model transformer with a sequence classification head on top (linear layer).
1382
+
1383
+ [`SteelForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1384
+ (e.g. GPT-2) do.
1385
+
1386
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1387
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1388
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1389
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1390
+ each row of the batch).
1391
+ """,
1392
+ Steel_START_DOCSTRING,
1393
+ )
1394
+ class SteelForSequenceClassification(SteelPreTrainedModel):
1395
+ def __init__(self, config):
1396
+ super().__init__(config)
1397
+ self.num_labels = config.num_labels
1398
+ self.model = SteelModel(config)
1399
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1400
+
1401
+ # Initialize weights and apply final processing
1402
+ self.post_init()
1403
+
1404
+ def get_input_embeddings(self):
1405
+ return self.model.embed_tokens
1406
+
1407
+ def set_input_embeddings(self, value):
1408
+ self.model.embed_tokens = value
1409
+
1410
+ @add_start_docstrings_to_model_forward(Steel_INPUTS_DOCSTRING)
1411
+ def forward(
1412
+ self,
1413
+ input_ids: torch.LongTensor = None,
1414
+ attention_mask: Optional[torch.Tensor] = None,
1415
+ position_ids: Optional[torch.LongTensor] = None,
1416
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1417
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1418
+ labels: Optional[torch.LongTensor] = None,
1419
+ use_cache: Optional[bool] = None,
1420
+ output_attentions: Optional[bool] = None,
1421
+ output_hidden_states: Optional[bool] = None,
1422
+ return_dict: Optional[bool] = None,
1423
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1424
+ r"""
1425
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1426
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1427
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1428
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1429
+ """
1430
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1431
+
1432
+ transformer_outputs = self.model(
1433
+ input_ids,
1434
+ attention_mask=attention_mask,
1435
+ position_ids=position_ids,
1436
+ past_key_values=past_key_values,
1437
+ inputs_embeds=inputs_embeds,
1438
+ use_cache=use_cache,
1439
+ output_attentions=output_attentions,
1440
+ output_hidden_states=output_hidden_states,
1441
+ return_dict=return_dict,
1442
+ )
1443
+ hidden_states = transformer_outputs[0]
1444
+ logits = self.score(hidden_states)
1445
+
1446
+ if input_ids is not None:
1447
+ batch_size = input_ids.shape[0]
1448
+ else:
1449
+ batch_size = inputs_embeds.shape[0]
1450
+
1451
+ if self.config.pad_token_id is None and batch_size != 1:
1452
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1453
+ if self.config.pad_token_id is None:
1454
+ sequence_lengths = -1
1455
+ else:
1456
+ if input_ids is not None:
1457
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1458
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1459
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1460
+ sequence_lengths = sequence_lengths.to(logits.device)
1461
+ else:
1462
+ sequence_lengths = -1
1463
+
1464
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1465
+
1466
+ loss = None
1467
+ if labels is not None:
1468
+ labels = labels.to(logits.device)
1469
+ if self.config.problem_type is None:
1470
+ if self.num_labels == 1:
1471
+ self.config.problem_type = "regression"
1472
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1473
+ self.config.problem_type = "single_label_classification"
1474
+ else:
1475
+ self.config.problem_type = "multi_label_classification"
1476
+
1477
+ if self.config.problem_type == "regression":
1478
+ loss_fct = MSELoss()
1479
+ if self.num_labels == 1:
1480
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1481
+ else:
1482
+ loss = loss_fct(pooled_logits, labels)
1483
+ elif self.config.problem_type == "single_label_classification":
1484
+ loss_fct = CrossEntropyLoss()
1485
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1486
+ elif self.config.problem_type == "multi_label_classification":
1487
+ loss_fct = BCEWithLogitsLoss()
1488
+ loss = loss_fct(pooled_logits, labels)
1489
+ if not return_dict:
1490
+ output = (pooled_logits,) + transformer_outputs[1:]
1491
+ return ((loss,) + output) if loss is not None else output
1492
+
1493
+ return SequenceClassifierOutputWithPast(
1494
+ loss=loss,
1495
+ logits=pooled_logits,
1496
+ past_key_values=transformer_outputs.past_key_values,
1497
+ hidden_states=transformer_outputs.hidden_states,
1498
+ attentions=transformer_outputs.attentions,
1499
+ )
steel-llm-step-480000-ckpt/softmoe_v3.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+
8
+ def softmax(x: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
9
+ """
10
+ Compute the softmax along the specified dimensions.
11
+ This function adds the option to specify multiple dimensions
12
+
13
+ Args:
14
+ x (torch.Tensor): Input tensor.
15
+ dims (int or tuple[int]): The dimension or list of dimensions along which the softmax probabilities are computed.
16
+
17
+ Returns:
18
+ torch.Tensor: Output tensor containing softmax probabilities along the specified dimensions.
19
+ """
20
+ dtype = x.dtype
21
+ x = x.to(torch.float32)
22
+ max_vals = torch.amax(x, dim=dim, keepdim=True)
23
+ e_x = torch.exp(x - max_vals)
24
+ sum_exp = e_x.sum(dim=dim, keepdim=True)
25
+ return (e_x / sum_exp).to(dtype)
26
+
27
+ # copy from https://github.com/bwconrad/soft-moe
28
+ class SteelSoftMoEV3(nn.Module):
29
+ """
30
+ A wrapper class to create a Soft Mixture of Experts layer.
31
+
32
+ From "From Sparse to Soft Mixtures of Experts"
33
+ https://arxiv.org/pdf/2308.00951.pdf
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ config,
39
+ layer: Callable,
40
+ ) -> None:
41
+ """
42
+ Args:
43
+ dim (int): Dimensionality of input features.
44
+ num_experts (int): Number of experts.
45
+ slots_per_expert (int): Number of token slots per expert.
46
+ layer (Callable): Network layer of the experts.
47
+ normalize (bool): Normalize input and phi (sec. 2.3 from paper)
48
+ **layer_kwargs: Additional keyword arguments for the layer class.
49
+ """
50
+ super().__init__()
51
+
52
+ self.dim = config.hidden_size
53
+ self.num_experts = config.n_experts
54
+ self.slots_per_expert = config.slots_per_expert if hasattr(config, "slots_per_expert") else 1
55
+ self.normalize = True
56
+
57
+ # Initialize phi and normalization scaling factor
58
+ self.phi = nn.Parameter(torch.zeros(self.dim, self.num_experts, self.slots_per_expert))
59
+ if self.normalize:
60
+ self.scale = nn.Parameter(torch.ones(1))
61
+
62
+ # Initialize phi using LeCun normal initialization
63
+ # https://github.com/google-research/vmoe/blob/662341d007650d5bbb7c6a2bef7f3c759a20cc7e/vmoe/projects/soft_moe/router.py#L49C1-L49C1
64
+ nn.init.normal_(self.phi, mean=0, std=1 / self.dim**0.5)
65
+
66
+ # Create a list of expert networks
67
+ self.experts = nn.ModuleList(
68
+ [layer(config) for _ in range(self.num_experts)]
69
+ )
70
+
71
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
72
+ """
73
+ Forward pass through the Soft-MoE layer (algorithm 1 from paper).
74
+
75
+ Args:
76
+ x (torch.Tensor): Input tensor of shape [batch_size, seq_len, input_dim].
77
+
78
+ Returns:
79
+ torch.Tensor: Output tensor of shape [batch_size, seq_len, input_dim].
80
+ """
81
+ assert (
82
+ x.shape[-1] == self.dim
83
+ ), f"Input feature dim of {x.shape[-1]} does not match layer dim of {self.dim}"
84
+ assert (
85
+ len(x.shape) == 3
86
+ ), f"Input expected to have 3 dimensions but has {len(x.shape)}"
87
+
88
+ phi = self.phi
89
+
90
+ # Normalize input and phi
91
+ if self.normalize:
92
+ x = F.normalize(x, dim=2) # [b, m, d]
93
+ phi = self.scale * F.normalize(phi, dim=0) # [d, n, p]
94
+
95
+ # Compute dispatch and combine weights
96
+ logits = torch.einsum("bmd,dnp->bmnp", x, phi)
97
+ d = softmax(logits, dim=1)
98
+ c = softmax(logits, dim=(2, 3))
99
+ # tmp = c[0,:,:,0].reshape([c.shape[1],-1])
100
+ # print("num:",tmp, "shape:",tmp.shape, "sum:",tmp.sum(dim=1))
101
+ # Compute input slots as weighted average of input tokens using dispatch weights
102
+ xs = torch.einsum("bmd,bmnp->bnpd", x, d)
103
+
104
+ # Apply expert to corresponding slots
105
+ ys = torch.stack(
106
+ [f_i(xs[:, i, :, :]) for i, f_i in enumerate(self.experts)], dim=1
107
+ )
108
+
109
+ # Compute output tokens as weighted average of output slots using combine weights
110
+ y = torch.einsum("bnpd,bmnp->bmd", ys, c)
111
+
112
+ return y
steel-llm-step-480000-ckpt/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
steel-llm-step-480000-ckpt/tokenizer_config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": ["<|im_start|>", "<|im_end|>"],
30
+ "bos_token": null,
31
+ "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 %}",
32
+ "clean_up_tokenization_spaces": false,
33
+ "eos_token": "<|im_end|>",
34
+ "errors": "replace",
35
+ "model_max_length": 32768,
36
+ "pad_token": "<|endoftext|>",
37
+ "split_special_tokens": false,
38
+ "tokenizer_class": "Qwen2Tokenizer",
39
+ "unk_token": null
40
+ }
41
+
steel-llm-step-480000-ckpt/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
steel-llm-step-660000-ckpt/config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "FFN_type": "softmoe_v3",
3
+ "_name_or_path": "./steel_modify_from_qwen_1_5",
4
+ "architectures": [
5
+ "SteelForCausalLM"
6
+ ],
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_steel.SteelConfig",
10
+ "AutoModelForCausalLM": "modeling_steel.SteelForCausalLM"
11
+ },
12
+ "bos_token_id": 151643,
13
+ "eos_token_id": 151645,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 1792,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 1792,
18
+ "max_position_embeddings": 32768,
19
+ "max_window_layers": 21,
20
+ "mlp_div_ratio": 4,
21
+ "mlp_type": "senet",
22
+ "model_type": "qwen2",
23
+ "n_experts": 6,
24
+ "num_attention_heads": 32,
25
+ "num_hidden_layers": 18,
26
+ "num_key_value_heads": 32,
27
+ "rms_norm_eps": 1e-06,
28
+ "rope_theta": 1000000.0,
29
+ "sliding_window": 32768,
30
+ "slots_per_expert": 1,
31
+ "tie_word_embeddings": false,
32
+ "torch_dtype": "float32",
33
+ "transformers_version": "4.41.1",
34
+ "use_cache": true,
35
+ "use_sliding_window": false,
36
+ "vocab_size": 151936
37
+ }
steel-llm-step-660000-ckpt/configuration_steel.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 zhanshijin and lishu. All rights reserved.
3
+ #
4
+ # This project copy from qwen1.5
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ Steel model configuration"""
17
+
18
+ from transformers.configuration_utils import PretrainedConfig
19
+ from transformers.utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+
26
+
27
+ class SteelConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`Qwen2Model`]. It is used to instantiate a
30
+ Qwen2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
31
+ with the defaults will yield a similar configuration to that of
32
+ Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PretrainedConfig`] for more information.
36
+
37
+
38
+ Args:
39
+ vocab_size (`int`, *optional*, defaults to 151936):
40
+ Vocabulary size of the Qwen2 model. Defines the number of different tokens that can be represented by the
41
+ `inputs_ids` passed when calling [`Qwen2Model`]
42
+ hidden_size (`int`, *optional*, defaults to 4096):
43
+ Dimension of the hidden representations.
44
+ intermediate_size (`int`, *optional*, defaults to 22016):
45
+ Dimension of the MLP representations.
46
+ num_hidden_layers (`int`, *optional*, defaults to 32):
47
+ Number of hidden layers in the Transformer encoder.
48
+ num_attention_heads (`int`, *optional*, defaults to 32):
49
+ Number of attention heads for each attention layer in the Transformer encoder.
50
+ num_key_value_heads (`int`, *optional*, defaults to 32):
51
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
52
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
53
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
54
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
55
+ by meanpooling all the original heads within that group. For more details checkout [this
56
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
57
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
58
+ The non-linear activation function (function or string) in the decoder.
59
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
60
+ The maximum sequence length that this model might ever be used with.
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
64
+ The epsilon used by the rms normalization layers.
65
+ use_cache (`bool`, *optional*, defaults to `True`):
66
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
67
+ relevant if `config.is_decoder=True`.
68
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
69
+ Whether the model's input and output word embeddings should be tied.
70
+ rope_theta (`float`, *optional*, defaults to 10000.0):
71
+ The base period of the RoPE embeddings.
72
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
73
+ Whether to use sliding window attention.
74
+ sliding_window (`int`, *optional*, defaults to 4096):
75
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
76
+ max_window_layers (`int`, *optional*, defaults to 28):
77
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
78
+ attention_dropout (`float`, *optional*, defaults to 0.0):
79
+ The dropout ratio for the attention probabilities.
80
+ """
81
+
82
+ model_type = "qwen2"
83
+ keys_to_ignore_at_inference = ["past_key_values"]
84
+
85
+ def __init__(
86
+ self,
87
+ vocab_size=151936,
88
+ hidden_size=4096,
89
+ intermediate_size=22016,
90
+ num_hidden_layers=32,
91
+ num_attention_heads=32,
92
+ num_key_value_heads=32,
93
+ hidden_act="silu",
94
+ max_position_embeddings=32768,
95
+ initializer_range=0.02,
96
+ rms_norm_eps=1e-6,
97
+ use_cache=True,
98
+ tie_word_embeddings=False,
99
+ rope_theta=10000.0,
100
+ use_sliding_window=False,
101
+ sliding_window=4096,
102
+ max_window_layers=28,
103
+ attention_dropout=0.0,
104
+ **kwargs,
105
+ ):
106
+ self.vocab_size = vocab_size
107
+ self.max_position_embeddings = max_position_embeddings
108
+ self.hidden_size = hidden_size
109
+ self.intermediate_size = intermediate_size
110
+ self.num_hidden_layers = num_hidden_layers
111
+ self.num_attention_heads = num_attention_heads
112
+ self.use_sliding_window = use_sliding_window
113
+ self.sliding_window = sliding_window
114
+ self.max_window_layers = max_window_layers
115
+
116
+ # for backward compatibility
117
+ if num_key_value_heads is None:
118
+ num_key_value_heads = num_attention_heads
119
+
120
+ self.num_key_value_heads = num_key_value_heads
121
+ self.hidden_act = hidden_act
122
+ self.initializer_range = initializer_range
123
+ self.rms_norm_eps = rms_norm_eps
124
+ self.use_cache = use_cache
125
+ self.rope_theta = rope_theta
126
+ self.attention_dropout = attention_dropout
127
+
128
+ super().__init__(
129
+ tie_word_embeddings=tie_word_embeddings,
130
+ **kwargs,
131
+ )
steel-llm-step-660000-ckpt/generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 151643,
4
+ "eos_token_id": 151645,
5
+ "transformers_version": "4.41.1"
6
+ }
steel-llm-step-660000-ckpt/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
steel-llm-step-660000-ckpt/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f2c087902fdfbd1aaa57c882baea44205d2525800ce9e82ab261cdfd758688f0
3
+ size 4491766872
steel-llm-step-660000-ckpt/modeling_steel.py ADDED
@@ -0,0 +1,1499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The zhanshijin and lishu. All rights reserved.
3
+ #
4
+ #
5
+ #This model copy from qwen1.5.
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+ """ PyTorch Steel model."""
19
+ import inspect
20
+ import math
21
+ import warnings
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.nn.functional as F
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+
30
+ from transformers.activations import ACT2FN
31
+ from transformers.cache_utils import Cache, DynamicCache
32
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
33
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
34
+ from transformers.modeling_utils import PreTrainedModel
35
+ from transformers.utils import (
36
+ add_start_docstrings,
37
+ add_start_docstrings_to_model_forward,
38
+ is_flash_attn_2_available,
39
+ is_flash_attn_greater_or_equal_2_10,
40
+ logging,
41
+ replace_return_docstrings,
42
+ )
43
+ from configuration_steel import SteelConfig
44
+ from softmoe_v3 import SteelSoftMoEV3
45
+
46
+ if is_flash_attn_2_available():
47
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
48
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
49
+
50
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
51
+ print("zhanshijin: surrport flash_attn_2")
52
+ print(f"zhanshijin: if flash attn surrport window:{_flash_supports_window_size}")
53
+ else:
54
+ print("zhanshijin: not surrport flash_attn_2")
55
+
56
+ logger = logging.get_logger(__name__)
57
+
58
+ rms_norm = None
59
+ def _import_cuda_rmsnorm():
60
+ global rms_norm
61
+ try:
62
+ from flash_attn.ops.rms_norm import rms_norm as __rms_norm
63
+ rms_norm = __rms_norm
64
+ print("zhanshijin: success import cuda __rms_norm")
65
+ except ImportError:
66
+ logger.warn(
67
+ "Warning: import flash_attn rms_norm fail, please install FlashAttention layer_norm to get higher efficiency "
68
+ "https://github.com/Dao-AILab/flash-attention/tree/main/csrc/layer_norm"
69
+ )
70
+
71
+ _CONFIG_FOR_DOC = "SteelConfig"
72
+
73
+
74
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
75
+ def _get_unpad_data(attention_mask):
76
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
77
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
78
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
79
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
80
+ return (
81
+ indices,
82
+ cu_seqlens,
83
+ max_seqlen_in_batch,
84
+ )
85
+
86
+
87
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Steel
88
+ class SteelRMSNorm(nn.Module):
89
+ def __init__(self, hidden_size, eps=1e-6):
90
+ """
91
+ SteelRMSNorm is equivalent to T5LayerNorm
92
+ """
93
+ super().__init__()
94
+ self.weight = nn.Parameter(torch.ones(hidden_size))
95
+ self.variance_epsilon = eps
96
+
97
+ def forward(self, hidden_states):
98
+ if rms_norm is not None and hidden_states.is_cuda:
99
+ return rms_norm(hidden_states, self.weight, self.variance_epsilon)
100
+ else:
101
+ input_dtype = hidden_states.dtype
102
+ hidden_states = hidden_states.to(torch.float32)
103
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
104
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
105
+ # test precision consistency
106
+ # from flash_attn.ops.rms_norm import rms_norm as _rms_norm
107
+ # print(_rms_norm(hidden_states, self.weight, self.variance_epsilon)[0,0,:10])
108
+ # print((self.weight * hidden_states.to(input_dtype))[0,0,:10])
109
+ return self.weight * hidden_states.to(input_dtype)
110
+
111
+
112
+ # Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Steel
113
+ class SteelRotaryEmbedding(nn.Module):
114
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
115
+ super().__init__()
116
+
117
+ self.dim = dim
118
+ self.max_position_embeddings = max_position_embeddings
119
+ self.base = base
120
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
121
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
122
+
123
+ # Build here to make `torch.jit.trace` work.
124
+ self._set_cos_sin_cache(
125
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
126
+ )
127
+
128
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
129
+ self.max_seq_len_cached = seq_len
130
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
131
+
132
+ freqs = torch.outer(t, self.inv_freq)
133
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
134
+ emb = torch.cat((freqs, freqs), dim=-1)
135
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
136
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
137
+
138
+ def forward(self, x, seq_len=None):
139
+ # x: [bs, num_attention_heads, seq_len, head_size]
140
+ if seq_len > self.max_seq_len_cached:
141
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
142
+
143
+ return (
144
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
145
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
146
+ )
147
+
148
+
149
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
150
+ def rotate_half(x):
151
+ """Rotates half the hidden dims of the input."""
152
+ x1 = x[..., : x.shape[-1] // 2]
153
+ x2 = x[..., x.shape[-1] // 2 :]
154
+ return torch.cat((-x2, x1), dim=-1)
155
+
156
+
157
+ # Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
158
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
159
+ """Applies Rotary Position Embedding to the query and key tensors.
160
+
161
+ Args:
162
+ q (`torch.Tensor`): The query tensor.
163
+ k (`torch.Tensor`): The key tensor.
164
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
165
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
166
+ position_ids (`torch.Tensor`):
167
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
168
+ used to pass offsetted position ids when working with a KV-cache.
169
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
170
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
171
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
172
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
173
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
174
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
175
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
176
+ Returns:
177
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
178
+ """
179
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
180
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
181
+ q_embed = (q * cos) + (rotate_half(q) * sin)
182
+ k_embed = (k * cos) + (rotate_half(k) * sin)
183
+ return q_embed, k_embed
184
+
185
+
186
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Steel->Steel
187
+ class SteelMLP(nn.Module):
188
+ def __init__(self, config):
189
+ super().__init__()
190
+ self.config = config
191
+ self.hidden_size = config.hidden_size
192
+ self.intermediate_size = config.intermediate_size //config.mlp_div_ratio
193
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
194
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
195
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
196
+ self.act_fn = ACT2FN[config.hidden_act]
197
+
198
+ def forward(self, x):
199
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
200
+
201
+ class SteelSENet(nn.Module):
202
+ def __init__(self, config):
203
+ super().__init__()
204
+ self.config = config
205
+ self.hidden_size = config.hidden_size
206
+ self.intermediate_size = config.intermediate_size //config.mlp_div_ratio
207
+ self.gate_up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
208
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
209
+ self.gate_down_proj = nn.Linear(self.intermediate_size,self.hidden_size, bias=False)
210
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
211
+ self.act_fn1 = ACT2FN[config.hidden_act]
212
+ self.act_fn2 = ACT2FN[config.hidden_act]
213
+
214
+ def forward(self, x):
215
+ x = self.act_fn1(self.gate_up_proj(x)) * self.up_proj(x)
216
+ return self.act_fn2(self.gate_down_proj(x)) * self.down_proj(x)
217
+
218
+
219
+ class SteelSoftMoeV1(nn.Module):
220
+ def __init__(self, config, layer=None):
221
+ super().__init__()
222
+ self.config = config
223
+ self.experts = nn.ModuleList([layer(config) for _ in range(config.n_experts)])
224
+ self.gating = nn.Linear(config.hidden_size, config.n_experts)
225
+ def forward(self, x):
226
+ weights = self.gating(x)
227
+ weights = nn.functional.softmax(weights, dim=-1, dtype=torch.float32).to(x.dtype)
228
+ outputs = torch.stack(
229
+ [expert(x) for expert in self.experts], dim=2)
230
+ weights = weights.unsqueeze(-1)
231
+ return torch.sum(outputs * weights, dim=2)
232
+
233
+ class SteelSoftMoeV2(nn.Module):
234
+ def __init__(self, config, layer):
235
+ super().__init__()
236
+ self.config = config
237
+ self.experts = nn.ModuleList([layer(config) for _ in range(config.n_experts)])
238
+ self.score = nn.Parameter(torch.randn(config.hidden_size, config.n_experts * config.slots_per_expert))
239
+
240
+ def forward(self, x):
241
+ logits = torch.matmul(x, self.score) # (batch_size, seq_len, slots)
242
+ dispatch_weights = F.softmax(logits, dim=-1,dtype=torch.float32).to(x.dtype)
243
+ combine_weights = F.softmax(logits, dim=1,dtype=torch.float32).to(x.dtype)
244
+ xs = torch.bmm(dispatch_weights.transpose(1, 2), x)
245
+ ys = torch.cat(
246
+ [expert(xs[:, i * self.config.slots_per_expert : (i + 1) * self.config.slots_per_expert, :])
247
+ for i, expert in enumerate(self.experts)],
248
+ dim=1
249
+ )
250
+ y = torch.bmm(combine_weights, ys)
251
+ return y
252
+
253
+
254
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
255
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
256
+ """
257
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
258
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
259
+ """
260
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
261
+ if n_rep == 1:
262
+ return hidden_states
263
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
264
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
265
+
266
+
267
+ class SteelAttention(nn.Module):
268
+ """
269
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
270
+ and "Generating Long Sequences with Sparse Transformers".
271
+ """
272
+
273
+ def __init__(self, config: SteelConfig, layer_idx: Optional[int] = None):
274
+ super().__init__()
275
+ self.config = config
276
+ self.layer_idx = layer_idx
277
+ if layer_idx is None:
278
+ logger.warning_once(
279
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
280
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
281
+ "when creating this class."
282
+ )
283
+
284
+ self.hidden_size = config.hidden_size
285
+ self.num_heads = config.num_attention_heads
286
+ self.head_dim = self.hidden_size // self.num_heads
287
+ self.num_key_value_heads = config.num_key_value_heads
288
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
289
+ self.max_position_embeddings = config.max_position_embeddings
290
+ self.rope_theta = config.rope_theta
291
+ self.is_causal = True
292
+ self.attention_dropout = config.attention_dropout
293
+
294
+ if (self.head_dim * self.num_heads) != self.hidden_size:
295
+ raise ValueError(
296
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
297
+ f" and `num_heads`: {self.num_heads})."
298
+ )
299
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
300
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
301
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
302
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
303
+
304
+ self.rotary_emb = SteelRotaryEmbedding(
305
+ self.head_dim,
306
+ max_position_embeddings=self.max_position_embeddings,
307
+ base=self.rope_theta,
308
+ )
309
+
310
+ def forward(
311
+ self,
312
+ hidden_states: torch.Tensor,
313
+ attention_mask: Optional[torch.Tensor] = None,
314
+ position_ids: Optional[torch.LongTensor] = None,
315
+ past_key_value: Optional[Cache] = None,
316
+ output_attentions: bool = False,
317
+ use_cache: bool = False,
318
+ **kwargs,
319
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
320
+ if "padding_mask" in kwargs:
321
+ warnings.warn(
322
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
323
+ )
324
+ bsz, q_len, _ = hidden_states.size()
325
+
326
+ query_states = self.q_proj(hidden_states)
327
+ key_states = self.k_proj(hidden_states)
328
+ value_states = self.v_proj(hidden_states)
329
+
330
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
331
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
332
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
333
+
334
+ kv_seq_len = key_states.shape[-2]
335
+ if past_key_value is not None:
336
+ if self.layer_idx is None:
337
+ raise ValueError(
338
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
339
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
340
+ "with a layer index."
341
+ )
342
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
343
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
344
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
345
+
346
+
347
+ if past_key_value is not None:
348
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
349
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
350
+
351
+ # repeat k/v heads if n_kv_heads < n_heads
352
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
353
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
354
+
355
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
356
+
357
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
358
+ raise ValueError(
359
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
360
+ f" {attn_weights.size()}"
361
+ )
362
+
363
+ if attention_mask is not None:
364
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
365
+ raise ValueError(
366
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
367
+ )
368
+
369
+ attn_weights = attn_weights + attention_mask
370
+
371
+ # upcast attention to fp32
372
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
373
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
374
+ attn_output = torch.matmul(attn_weights, value_states)
375
+
376
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
377
+ raise ValueError(
378
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
379
+ f" {attn_output.size()}"
380
+ )
381
+
382
+ attn_output = attn_output.transpose(1, 2).contiguous()
383
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
384
+
385
+ attn_output = self.o_proj(attn_output)
386
+
387
+ if not output_attentions:
388
+ attn_weights = None
389
+
390
+ return attn_output, attn_weights, past_key_value
391
+
392
+
393
+ class SteelFlashAttention2(SteelAttention):
394
+ """
395
+ Steel flash attention module, following Steel attention module. This module inherits from `SteelAttention`
396
+ as the weights of the module stays untouched. The only required change would be on the forward pass
397
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
398
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
399
+ config.max_window_layers layers.
400
+ """
401
+
402
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
403
+ def __init__(self, *args, **kwargs):
404
+ super().__init__(*args, **kwargs)
405
+
406
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
407
+ # 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.
408
+ # 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).
409
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
410
+
411
+ def forward(
412
+ self,
413
+ hidden_states: torch.Tensor,
414
+ attention_mask: Optional[torch.Tensor] = None,
415
+ position_ids: Optional[torch.LongTensor] = None,
416
+ past_key_value: Optional[Cache] = None,
417
+ output_attentions: bool = False,
418
+ use_cache: bool = False,
419
+ **kwargs,
420
+ ):
421
+ if "padding_mask" in kwargs:
422
+ warnings.warn(
423
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
424
+ )
425
+
426
+ # overwrite attention_mask with padding_mask
427
+ attention_mask = kwargs.pop("padding_mask")
428
+ bsz, q_len, _ = hidden_states.size()
429
+
430
+ query_states = self.q_proj(hidden_states)
431
+ key_states = self.k_proj(hidden_states)
432
+ value_states = self.v_proj(hidden_states)
433
+
434
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
435
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
436
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
437
+
438
+ kv_seq_len = key_states.shape[-2]
439
+ if past_key_value is not None:
440
+ if self.layer_idx is None:
441
+ raise ValueError(
442
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
443
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
444
+ "with a layer index."
445
+ )
446
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
447
+
448
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
449
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
450
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
451
+
452
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
453
+
454
+ use_sliding_windows = (
455
+ _flash_supports_window_size
456
+ and getattr(self.config, "sliding_window", None) is not None
457
+ and kv_seq_len > self.config.sliding_window
458
+ and self.config.use_sliding_window
459
+ )
460
+
461
+ if not _flash_supports_window_size:
462
+ logger.warning_once(
463
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
464
+ " make sure to upgrade flash-attn library."
465
+ )
466
+
467
+ if past_key_value is not None:
468
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
469
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
470
+ if (
471
+ getattr(self.config, "sliding_window", None) is not None
472
+ and kv_seq_len > self.config.sliding_window
473
+ and cache_has_contents
474
+ ):
475
+ slicing_tokens = 1 - self.config.sliding_window
476
+
477
+ past_key = past_key_value[self.layer_idx][0]
478
+ past_value = past_key_value[self.layer_idx][1]
479
+
480
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
481
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
482
+
483
+ if past_key.shape[-2] != self.config.sliding_window - 1:
484
+ raise ValueError(
485
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
486
+ f" {past_key.shape}"
487
+ )
488
+
489
+ if attention_mask is not None:
490
+ attention_mask = attention_mask[:, slicing_tokens:]
491
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
492
+
493
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
494
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
495
+
496
+ # repeat k/v heads if n_kv_heads < n_heads
497
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
498
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
499
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
500
+
501
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
502
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
503
+ # cast them back in float16 just to be sure everything works as expected.
504
+ input_dtype = query_states.dtype
505
+ if input_dtype == torch.float32:
506
+ if torch.is_autocast_enabled():
507
+ target_dtype = torch.get_autocast_gpu_dtype()
508
+ # Handle the case where the model is quantized
509
+ elif hasattr(self.config, "_pre_quantization_dtype"):
510
+ target_dtype = self.config._pre_quantization_dtype
511
+ else:
512
+ target_dtype = self.q_proj.weight.dtype
513
+
514
+ logger.warning_once(
515
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
516
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
517
+ f" {target_dtype}."
518
+ )
519
+
520
+ query_states = query_states.to(target_dtype)
521
+ key_states = key_states.to(target_dtype)
522
+ value_states = value_states.to(target_dtype)
523
+
524
+ # Reashape to the expected shape for Flash Attention
525
+ query_states = query_states.transpose(1, 2)
526
+ key_states = key_states.transpose(1, 2)
527
+ value_states = value_states.transpose(1, 2)
528
+
529
+ attn_output = self._flash_attention_forward(
530
+ query_states,
531
+ key_states,
532
+ value_states,
533
+ attention_mask,
534
+ q_len,
535
+ dropout=dropout_rate,
536
+ use_sliding_windows=use_sliding_windows,
537
+ )
538
+
539
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
540
+ attn_output = self.o_proj(attn_output)
541
+
542
+ if not output_attentions:
543
+ attn_weights = None
544
+
545
+ return attn_output, attn_weights, past_key_value
546
+
547
+ def _flash_attention_forward(
548
+ self,
549
+ query_states,
550
+ key_states,
551
+ value_states,
552
+ attention_mask,
553
+ query_length,
554
+ dropout=0.0,
555
+ softmax_scale=None,
556
+ use_sliding_windows=False,
557
+ ):
558
+ """
559
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
560
+ first unpad the input, then computes the attention scores and pad the final attention scores.
561
+
562
+ Args:
563
+ query_states (`torch.Tensor`):
564
+ Input query states to be passed to Flash Attention API
565
+ key_states (`torch.Tensor`):
566
+ Input key states to be passed to Flash Attention API
567
+ value_states (`torch.Tensor`):
568
+ Input value states to be passed to Flash Attention API
569
+ attention_mask (`torch.Tensor`):
570
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
571
+ position of padding tokens and 1 for the position of non-padding tokens.
572
+ dropout (`float`):
573
+ Attention dropout
574
+ softmax_scale (`float`, *optional*):
575
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
576
+ use_sliding_windows (`bool`, *optional*):
577
+ Whether to activate sliding window attention.
578
+ """
579
+ if not self._flash_attn_uses_top_left_mask:
580
+ causal = self.is_causal
581
+ else:
582
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
583
+ causal = self.is_causal and query_length != 1
584
+
585
+ # Decide whether to use SWA or not by layer index.
586
+ if use_sliding_windows and self.layer_idx >= self.config.max_window_layers:
587
+ use_sliding_windows = False
588
+
589
+ # Contains at least one padding token in the sequence
590
+ if attention_mask is not None:
591
+ batch_size = query_states.shape[0]
592
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
593
+ query_states, key_states, value_states, attention_mask, query_length
594
+ )
595
+
596
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
597
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
598
+
599
+ if not use_sliding_windows:
600
+ attn_output_unpad = flash_attn_varlen_func(
601
+ query_states,
602
+ key_states,
603
+ value_states,
604
+ cu_seqlens_q=cu_seqlens_q,
605
+ cu_seqlens_k=cu_seqlens_k,
606
+ max_seqlen_q=max_seqlen_in_batch_q,
607
+ max_seqlen_k=max_seqlen_in_batch_k,
608
+ dropout_p=dropout,
609
+ softmax_scale=softmax_scale,
610
+ causal=causal,
611
+ )
612
+ else:
613
+ attn_output_unpad = flash_attn_varlen_func(
614
+ query_states,
615
+ key_states,
616
+ value_states,
617
+ cu_seqlens_q=cu_seqlens_q,
618
+ cu_seqlens_k=cu_seqlens_k,
619
+ max_seqlen_q=max_seqlen_in_batch_q,
620
+ max_seqlen_k=max_seqlen_in_batch_k,
621
+ dropout_p=dropout,
622
+ softmax_scale=softmax_scale,
623
+ causal=causal,
624
+ window_size=(self.config.sliding_window, self.config.sliding_window),
625
+ )
626
+
627
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
628
+ else:
629
+ if not use_sliding_windows:
630
+ attn_output = flash_attn_func(
631
+ query_states,
632
+ key_states,
633
+ value_states,
634
+ dropout,
635
+ softmax_scale=softmax_scale,
636
+ causal=causal,
637
+ )
638
+ else:
639
+ attn_output = flash_attn_func(
640
+ query_states,
641
+ key_states,
642
+ value_states,
643
+ dropout,
644
+ softmax_scale=softmax_scale,
645
+ causal=causal,
646
+ window_size=(self.config.sliding_window, self.config.sliding_window),
647
+ )
648
+
649
+ return attn_output
650
+
651
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
652
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
653
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
654
+
655
+ # On the first iteration we need to properly re-create the padding mask
656
+ # by slicing it on the proper place
657
+ if kv_seq_len != attention_mask.shape[-1]:
658
+ attention_mask_num_tokens = attention_mask.shape[-1]
659
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
660
+
661
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
662
+
663
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
664
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
665
+
666
+ if query_length == kv_seq_len:
667
+ query_layer = index_first_axis(
668
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
669
+ )
670
+ cu_seqlens_q = cu_seqlens_k
671
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
672
+ indices_q = indices_k
673
+ elif query_length == 1:
674
+ max_seqlen_in_batch_q = 1
675
+ cu_seqlens_q = torch.arange(
676
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
677
+ ) # There is a memcpy here, that is very bad.
678
+ indices_q = cu_seqlens_q[:-1]
679
+ query_layer = query_layer.squeeze(1)
680
+ else:
681
+ # The -q_len: slice assumes left padding.
682
+ attention_mask = attention_mask[:, -query_length:]
683
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
684
+
685
+ return (
686
+ query_layer,
687
+ key_layer,
688
+ value_layer,
689
+ indices_q,
690
+ (cu_seqlens_q, cu_seqlens_k),
691
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
692
+ )
693
+
694
+
695
+ # Copied from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Steel
696
+ class SteelSdpaAttention(SteelAttention):
697
+ """
698
+ Steel attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
699
+ `SteelAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
700
+ SDPA API.
701
+ """
702
+
703
+ # Adapted from SteelAttention.forward
704
+ def forward(
705
+ self,
706
+ hidden_states: torch.Tensor,
707
+ attention_mask: Optional[torch.Tensor] = None,
708
+ position_ids: Optional[torch.LongTensor] = None,
709
+ past_key_value: Optional[Cache] = None,
710
+ output_attentions: bool = False,
711
+ use_cache: bool = False,
712
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
713
+ if output_attentions:
714
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
715
+ logger.warning_once(
716
+ "SteelModel is using SteelSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
717
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
718
+ )
719
+ return super().forward(
720
+ hidden_states=hidden_states,
721
+ attention_mask=attention_mask,
722
+ position_ids=position_ids,
723
+ past_key_value=past_key_value,
724
+ output_attentions=output_attentions,
725
+ use_cache=use_cache,
726
+ )
727
+
728
+ bsz, q_len, _ = hidden_states.size()
729
+
730
+ query_states = self.q_proj(hidden_states)
731
+ key_states = self.k_proj(hidden_states)
732
+ value_states = self.v_proj(hidden_states)
733
+
734
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
735
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
736
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
737
+
738
+ kv_seq_len = key_states.shape[-2]
739
+ if past_key_value is not None:
740
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
741
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
742
+
743
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
744
+
745
+ if past_key_value is not None:
746
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
747
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
748
+
749
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
750
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
751
+
752
+ if attention_mask is not None:
753
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
754
+ raise ValueError(
755
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
756
+ )
757
+
758
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
759
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
760
+ if query_states.device.type == "cuda" and attention_mask is not None:
761
+ query_states = query_states.contiguous()
762
+ key_states = key_states.contiguous()
763
+ value_states = value_states.contiguous()
764
+
765
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
766
+ query_states,
767
+ key_states,
768
+ value_states,
769
+ attn_mask=attention_mask,
770
+ dropout_p=self.attention_dropout if self.training else 0.0,
771
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
772
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
773
+ )
774
+
775
+ attn_output = attn_output.transpose(1, 2).contiguous()
776
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
777
+
778
+ attn_output = self.o_proj(attn_output)
779
+
780
+ return attn_output, None, past_key_value
781
+
782
+
783
+ Steel_ATTENTION_CLASSES = {
784
+ "eager": SteelAttention,
785
+ "flash_attention_2": SteelFlashAttention2,
786
+ "sdpa": SteelSdpaAttention,
787
+ }
788
+
789
+
790
+ class SteelDecoderLayer(nn.Module):
791
+ def __init__(self, config: SteelConfig, layer_idx: int):
792
+ super().__init__()
793
+ self.hidden_size = config.hidden_size
794
+
795
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
796
+ logger.warning_once(
797
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
798
+ "unexpected results may be encountered."
799
+ )
800
+ self.self_attn = Steel_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
801
+ if config.mlp_type == "raw":
802
+ mlp_class = SteelMLP
803
+ logger.warning_once(f"mlp_class: SteelMLP")
804
+ elif config.mlp_type == "senet":
805
+ mlp_class = SteelSENet
806
+ logger.warning_once(f"mlp_class: SteelSENet")
807
+ else:
808
+ raise NameError(f"No this mlp type: {config.mlp_type}")
809
+
810
+ if config.FFN_type == "raw":
811
+ self.mlp = mlp_class(config)
812
+ logger.warning_once(f"FFN: {mlp_class}")
813
+ elif config.FFN_type == "softmoe_v1":
814
+ self.mlp = SteelSoftMoeV1(config, layer=mlp_class)
815
+ logger.warning_once(f"FFN: SteelSoftMoeV1")
816
+ elif config.FFN_type == "softmoe_v2":
817
+ self.mlp = SteelSoftMoeV2(config, layer=mlp_class)
818
+ logger.warning_once(f"FFN: SteelSoftMoeV2")
819
+ elif config.FFN_type == "softmoe_v3":
820
+ self.mlp = SteelSoftMoEV3(config=config, layer=mlp_class)
821
+ logger.warning_once(f"FFN: SteelSoftMoeV3")
822
+ else:
823
+ raise NameError(f"No this FFN type: {config.FFN_type}")
824
+
825
+ self.input_layernorm = SteelRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
826
+ self.post_attention_layernorm = SteelRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
827
+
828
+ def forward(
829
+ self,
830
+ hidden_states: torch.Tensor,
831
+ attention_mask: Optional[torch.Tensor] = None,
832
+ position_ids: Optional[torch.LongTensor] = None,
833
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
834
+ output_attentions: Optional[bool] = False,
835
+ use_cache: Optional[bool] = False,
836
+ **kwargs,
837
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
838
+ if "padding_mask" in kwargs:
839
+ warnings.warn(
840
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
841
+ "Please make sure use `attention_mask` instead.`"
842
+ )
843
+ """
844
+ Args:
845
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
846
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
847
+ `(batch, sequence_length)` where padding elements are indicated by 0.
848
+ output_attentions (`bool`, *optional*):
849
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
850
+ returned tensors for more detail.
851
+ use_cache (`bool`, *optional*):
852
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
853
+ (see `past_key_values`).
854
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
855
+ """
856
+
857
+ residual = hidden_states
858
+
859
+ hidden_states = self.input_layernorm(hidden_states)
860
+
861
+ # Self Attention
862
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
863
+ hidden_states=hidden_states,
864
+ attention_mask=attention_mask,
865
+ position_ids=position_ids,
866
+ past_key_value=past_key_value,
867
+ output_attentions=output_attentions,
868
+ use_cache=use_cache,
869
+ )
870
+ hidden_states = residual + hidden_states
871
+
872
+ # Fully Connected
873
+ residual = hidden_states
874
+ hidden_states = self.post_attention_layernorm(hidden_states)
875
+ hidden_states = self.mlp(hidden_states)
876
+ hidden_states = residual + hidden_states
877
+
878
+ outputs = (hidden_states,)
879
+
880
+ if output_attentions:
881
+ outputs += (self_attn_weights,)
882
+
883
+ if use_cache:
884
+ outputs += (present_key_value,)
885
+
886
+ return outputs
887
+
888
+
889
+ Steel_START_DOCSTRING = r"""
890
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
891
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
892
+ etc.)
893
+
894
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
895
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
896
+ and behavior.
897
+
898
+ Parameters:
899
+ config ([`SteelConfig`]):
900
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
901
+ load the weights associated with the model, only the configuration. Check out the
902
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
903
+ """
904
+
905
+
906
+ @add_start_docstrings(
907
+ "The bare Steel Model outputting raw hidden-states without any specific head on top.",
908
+ Steel_START_DOCSTRING,
909
+ )
910
+ class SteelPreTrainedModel(PreTrainedModel):
911
+ config_class = SteelConfig
912
+ base_model_prefix = "model"
913
+ supports_gradient_checkpointing = True
914
+ _no_split_modules = ["SteelDecoderLayer"]
915
+ _skip_keys_device_placement = "past_key_values"
916
+ _supports_flash_attn_2 = True
917
+ _supports_sdpa = True
918
+ _supports_cache_class = True
919
+
920
+ def _init_weights(self, module):
921
+ std = self.config.initializer_range
922
+ if isinstance(module, nn.Linear):
923
+ module.weight.data.normal_(mean=0.0, std=std)
924
+ if module.bias is not None:
925
+ module.bias.data.zero_()
926
+ elif isinstance(module, nn.Embedding):
927
+ module.weight.data.normal_(mean=0.0, std=std)
928
+ if module.padding_idx is not None:
929
+ module.weight.data[module.padding_idx].zero_()
930
+
931
+
932
+ Steel_INPUTS_DOCSTRING = r"""
933
+ Args:
934
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
935
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
936
+ it.
937
+
938
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
939
+ [`PreTrainedTokenizer.__call__`] for details.
940
+
941
+ [What are input IDs?](../glossary#input-ids)
942
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
943
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
944
+
945
+ - 1 for tokens that are **not masked**,
946
+ - 0 for tokens that are **masked**.
947
+
948
+ [What are attention masks?](../glossary#attention-mask)
949
+
950
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
951
+ [`PreTrainedTokenizer.__call__`] for details.
952
+
953
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
954
+ `past_key_values`).
955
+
956
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
957
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
958
+ information on the default strategy.
959
+
960
+ - 1 indicates the head is **not masked**,
961
+ - 0 indicates the head is **masked**.
962
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
963
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
964
+ config.n_positions - 1]`.
965
+
966
+ [What are position IDs?](../glossary#position-ids)
967
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
968
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
969
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
970
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
971
+
972
+ Two formats are allowed:
973
+ - a [`~cache_utils.Cache`] instance;
974
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
975
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
976
+ cache format.
977
+
978
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
979
+ legacy cache format will be returned.
980
+
981
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
982
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
983
+ of shape `(batch_size, sequence_length)`.
984
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
985
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
986
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
987
+ model's internal embedding lookup matrix.
988
+ use_cache (`bool`, *optional*):
989
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
990
+ `past_key_values`).
991
+ output_attentions (`bool`, *optional*):
992
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
993
+ tensors for more detail.
994
+ output_hidden_states (`bool`, *optional*):
995
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
996
+ more detail.
997
+ return_dict (`bool`, *optional*):
998
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
999
+ """
1000
+
1001
+
1002
+ @add_start_docstrings(
1003
+ "The bare Steel Model outputting raw hidden-states without any specific head on top.",
1004
+ Steel_START_DOCSTRING,
1005
+ )
1006
+ class SteelModel(SteelPreTrainedModel):
1007
+ """
1008
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`SteelDecoderLayer`]
1009
+
1010
+ Args:
1011
+ config: SteelConfig
1012
+ """
1013
+
1014
+ def __init__(self, config: SteelConfig):
1015
+ super().__init__(config)
1016
+ self.padding_idx = config.pad_token_id
1017
+ self.vocab_size = config.vocab_size
1018
+
1019
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1020
+ self.layers = nn.ModuleList(
1021
+ [SteelDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1022
+ )
1023
+ self._attn_implementation = config._attn_implementation
1024
+ logger.warning_once(
1025
+ f"zhanshijin: now use _attn_implementation is {config._attn_implementation}, you can choose from {Steel_ATTENTION_CLASSES.keys()}"
1026
+ )
1027
+ self.norm = SteelRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1028
+
1029
+ self.gradient_checkpointing = False
1030
+ # Initialize weights and apply final processing
1031
+ self.post_init()
1032
+
1033
+ if hasattr(config, "use_cuda_rmsnorm") and config.use_cuda_rmsnorm:
1034
+ _import_cuda_rmsnorm()
1035
+ else:
1036
+ print("zhanshijin: use torch rmsnorm")
1037
+
1038
+ def get_input_embeddings(self):
1039
+ return self.embed_tokens
1040
+
1041
+ def set_input_embeddings(self, value):
1042
+ self.embed_tokens = value
1043
+
1044
+ @add_start_docstrings_to_model_forward(Steel_INPUTS_DOCSTRING)
1045
+ def forward(
1046
+ self,
1047
+ input_ids: torch.LongTensor = None,
1048
+ attention_mask: Optional[torch.Tensor] = None,
1049
+ position_ids: Optional[torch.LongTensor] = None,
1050
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1051
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1052
+ use_cache: Optional[bool] = None,
1053
+ output_attentions: Optional[bool] = None,
1054
+ output_hidden_states: Optional[bool] = None,
1055
+ return_dict: Optional[bool] = None,
1056
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1057
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1058
+ output_hidden_states = (
1059
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1060
+ )
1061
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1062
+
1063
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1064
+
1065
+ # retrieve input_ids and inputs_embeds
1066
+ if input_ids is not None and inputs_embeds is not None:
1067
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1068
+ elif input_ids is not None:
1069
+ batch_size, seq_length = input_ids.shape
1070
+ elif inputs_embeds is not None:
1071
+ batch_size, seq_length, _ = inputs_embeds.shape
1072
+ else:
1073
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
1074
+
1075
+ if self.gradient_checkpointing and self.training:
1076
+ if use_cache:
1077
+ logger.warning_once(
1078
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1079
+ )
1080
+ use_cache = False
1081
+
1082
+ past_key_values_length = 0
1083
+
1084
+ if use_cache:
1085
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1086
+ if use_legacy_cache:
1087
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1088
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1089
+
1090
+ if position_ids is None:
1091
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1092
+ position_ids = torch.arange(
1093
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1094
+ )
1095
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1096
+ else:
1097
+ position_ids = position_ids.view(-1, seq_length).long()
1098
+
1099
+ if inputs_embeds is None:
1100
+ inputs_embeds = self.embed_tokens(input_ids)
1101
+
1102
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1103
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1104
+ if is_padding_right:
1105
+ raise ValueError(
1106
+ "You are attempting to perform batched generation with padding_side='right'"
1107
+ " this may lead to unexpected behaviour for Flash Attention version of Steel. Make sure to "
1108
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1109
+ )
1110
+
1111
+ if self._attn_implementation == "flash_attention_2":
1112
+ # 2d mask is passed through the layers
1113
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1114
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1115
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1116
+ # the manual implementation that requires a 4D causal mask in all cases.
1117
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1118
+ attention_mask,
1119
+ (batch_size, seq_length),
1120
+ inputs_embeds,
1121
+ past_key_values_length,
1122
+ sliding_window=self.config.sliding_window,
1123
+ )
1124
+ else:
1125
+ # 4d mask is passed through the layers
1126
+ attention_mask = _prepare_4d_causal_attention_mask(
1127
+ attention_mask,
1128
+ (batch_size, seq_length),
1129
+ inputs_embeds,
1130
+ past_key_values_length,
1131
+ sliding_window=self.config.sliding_window,
1132
+ )
1133
+
1134
+ hidden_states = inputs_embeds
1135
+
1136
+ # decoder layers
1137
+ all_hidden_states = () if output_hidden_states else None
1138
+ all_self_attns = () if output_attentions else None
1139
+ next_decoder_cache = None
1140
+
1141
+ for decoder_layer in self.layers:
1142
+ if output_hidden_states:
1143
+ all_hidden_states += (hidden_states,)
1144
+
1145
+ if self.gradient_checkpointing and self.training:
1146
+ layer_outputs = self._gradient_checkpointing_func(
1147
+ decoder_layer.__call__,
1148
+ hidden_states,
1149
+ attention_mask,
1150
+ position_ids,
1151
+ past_key_values,
1152
+ output_attentions,
1153
+ use_cache,
1154
+ )
1155
+ else:
1156
+ layer_outputs = decoder_layer(
1157
+ hidden_states,
1158
+ attention_mask=attention_mask,
1159
+ position_ids=position_ids,
1160
+ past_key_value=past_key_values,
1161
+ output_attentions=output_attentions,
1162
+ use_cache=use_cache,
1163
+ )
1164
+
1165
+ hidden_states = layer_outputs[0]
1166
+
1167
+ if use_cache:
1168
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1169
+
1170
+ if output_attentions:
1171
+ all_self_attns += (layer_outputs[1],)
1172
+
1173
+ hidden_states = self.norm(hidden_states)
1174
+
1175
+ # add hidden states from the last decoder layer
1176
+ if output_hidden_states:
1177
+ all_hidden_states += (hidden_states,)
1178
+
1179
+ next_cache = None
1180
+ if use_cache:
1181
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1182
+
1183
+ if not return_dict:
1184
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1185
+ return BaseModelOutputWithPast(
1186
+ last_hidden_state=hidden_states,
1187
+ past_key_values=next_cache,
1188
+ hidden_states=all_hidden_states,
1189
+ attentions=all_self_attns,
1190
+ )
1191
+
1192
+
1193
+ class SteelForCausalLM(SteelPreTrainedModel):
1194
+ _tied_weights_keys = ["lm_head.weight"]
1195
+
1196
+ def __init__(self, config):
1197
+ super().__init__(config)
1198
+ self.model = SteelModel(config)
1199
+ self.vocab_size = config.vocab_size
1200
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1201
+
1202
+ # Initialize weights and apply final processing
1203
+ self.post_init()
1204
+
1205
+ def get_input_embeddings(self):
1206
+ return self.model.embed_tokens
1207
+
1208
+ def set_input_embeddings(self, value):
1209
+ self.model.embed_tokens = value
1210
+
1211
+ def get_output_embeddings(self):
1212
+ return self.lm_head
1213
+
1214
+ def set_output_embeddings(self, new_embeddings):
1215
+ self.lm_head = new_embeddings
1216
+
1217
+ def set_decoder(self, decoder):
1218
+ self.model = decoder
1219
+
1220
+ def get_decoder(self):
1221
+ return self.model
1222
+
1223
+ @add_start_docstrings_to_model_forward(Steel_INPUTS_DOCSTRING)
1224
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1225
+ def forward(
1226
+ self,
1227
+ input_ids: torch.LongTensor = None,
1228
+ attention_mask: Optional[torch.Tensor] = None,
1229
+ position_ids: Optional[torch.LongTensor] = None,
1230
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1231
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1232
+ labels: Optional[torch.LongTensor] = None,
1233
+ use_cache: Optional[bool] = None,
1234
+ output_attentions: Optional[bool] = None,
1235
+ output_hidden_states: Optional[bool] = None,
1236
+ return_dict: Optional[bool] = None,
1237
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1238
+ r"""
1239
+ Args:
1240
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1241
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1242
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1243
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1244
+
1245
+ Returns:
1246
+
1247
+ Example:
1248
+
1249
+ ```python
1250
+ >>> from transformers import AutoTokenizer, SteelForCausalLM
1251
+
1252
+ >>> model = SteelForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1253
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1254
+
1255
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1256
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1257
+
1258
+ >>> # Generate
1259
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1260
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1261
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1262
+ ```"""
1263
+
1264
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1265
+ output_hidden_states = (
1266
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1267
+ )
1268
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1269
+
1270
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1271
+ outputs = self.model(
1272
+ input_ids=input_ids,
1273
+ attention_mask=attention_mask,
1274
+ position_ids=position_ids,
1275
+ past_key_values=past_key_values,
1276
+ inputs_embeds=inputs_embeds,
1277
+ use_cache=use_cache,
1278
+ output_attentions=output_attentions,
1279
+ output_hidden_states=output_hidden_states,
1280
+ return_dict=return_dict,
1281
+ )
1282
+
1283
+ hidden_states = outputs[0]
1284
+ logits = self.lm_head(hidden_states)
1285
+ logits = logits.float()
1286
+
1287
+ loss = None
1288
+ if labels is not None:
1289
+ # Shift so that tokens < n predict n
1290
+ shift_logits = logits[..., :-1, :].contiguous()
1291
+ shift_labels = labels[..., 1:].contiguous()
1292
+ # Flatten the tokens
1293
+ loss_fct = CrossEntropyLoss()
1294
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1295
+ shift_labels = shift_labels.view(-1)
1296
+ # Enable model parallelism
1297
+ shift_labels = shift_labels.to(shift_logits.device)
1298
+ loss = loss_fct(shift_logits, shift_labels)
1299
+
1300
+ if not return_dict:
1301
+ output = (logits,) + outputs[1:]
1302
+ return (loss,) + output if loss is not None else output
1303
+
1304
+ return CausalLMOutputWithPast(
1305
+ loss=loss,
1306
+ logits=logits,
1307
+ past_key_values=outputs.past_key_values,
1308
+ hidden_states=outputs.hidden_states,
1309
+ attentions=outputs.attentions,
1310
+ )
1311
+
1312
+ def prepare_inputs_for_generation(
1313
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1314
+ ):
1315
+ # Omit tokens covered by past_key_values
1316
+ if past_key_values is not None:
1317
+ if isinstance(past_key_values, Cache):
1318
+ cache_length = past_key_values.get_seq_length()
1319
+ past_length = past_key_values.seen_tokens
1320
+ max_cache_length = past_key_values.get_max_length()
1321
+ else:
1322
+ cache_length = past_length = past_key_values[0][0].shape[2]
1323
+ max_cache_length = None
1324
+
1325
+ # Keep only the unprocessed tokens:
1326
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1327
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1328
+ # input)
1329
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1330
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1331
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1332
+ # input_ids based on the past_length.
1333
+ elif past_length < input_ids.shape[1]:
1334
+ input_ids = input_ids[:, past_length:]
1335
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1336
+
1337
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1338
+ if (
1339
+ max_cache_length is not None
1340
+ and attention_mask is not None
1341
+ and cache_length + input_ids.shape[1] > max_cache_length
1342
+ ):
1343
+ attention_mask = attention_mask[:, -max_cache_length:]
1344
+
1345
+ position_ids = kwargs.get("position_ids", None)
1346
+ if attention_mask is not None and position_ids is None:
1347
+ # create position_ids on the fly for batch generation
1348
+ position_ids = attention_mask.long().cumsum(-1) - 1
1349
+ position_ids.masked_fill_(attention_mask == 0, 1)
1350
+ if past_key_values:
1351
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1352
+
1353
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1354
+ if inputs_embeds is not None and past_key_values is None:
1355
+ model_inputs = {"inputs_embeds": inputs_embeds}
1356
+ else:
1357
+ model_inputs = {"input_ids": input_ids}
1358
+
1359
+ model_inputs.update(
1360
+ {
1361
+ "position_ids": position_ids,
1362
+ "past_key_values": past_key_values,
1363
+ "use_cache": kwargs.get("use_cache"),
1364
+ "attention_mask": attention_mask,
1365
+ }
1366
+ )
1367
+ return model_inputs
1368
+
1369
+ @staticmethod
1370
+ def _reorder_cache(past_key_values, beam_idx):
1371
+ reordered_past = ()
1372
+ for layer_past in past_key_values:
1373
+ reordered_past += (
1374
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1375
+ )
1376
+ return reordered_past
1377
+
1378
+
1379
+ @add_start_docstrings(
1380
+ """
1381
+ The Steel Model transformer with a sequence classification head on top (linear layer).
1382
+
1383
+ [`SteelForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1384
+ (e.g. GPT-2) do.
1385
+
1386
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1387
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1388
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1389
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1390
+ each row of the batch).
1391
+ """,
1392
+ Steel_START_DOCSTRING,
1393
+ )
1394
+ class SteelForSequenceClassification(SteelPreTrainedModel):
1395
+ def __init__(self, config):
1396
+ super().__init__(config)
1397
+ self.num_labels = config.num_labels
1398
+ self.model = SteelModel(config)
1399
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1400
+
1401
+ # Initialize weights and apply final processing
1402
+ self.post_init()
1403
+
1404
+ def get_input_embeddings(self):
1405
+ return self.model.embed_tokens
1406
+
1407
+ def set_input_embeddings(self, value):
1408
+ self.model.embed_tokens = value
1409
+
1410
+ @add_start_docstrings_to_model_forward(Steel_INPUTS_DOCSTRING)
1411
+ def forward(
1412
+ self,
1413
+ input_ids: torch.LongTensor = None,
1414
+ attention_mask: Optional[torch.Tensor] = None,
1415
+ position_ids: Optional[torch.LongTensor] = None,
1416
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1417
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1418
+ labels: Optional[torch.LongTensor] = None,
1419
+ use_cache: Optional[bool] = None,
1420
+ output_attentions: Optional[bool] = None,
1421
+ output_hidden_states: Optional[bool] = None,
1422
+ return_dict: Optional[bool] = None,
1423
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1424
+ r"""
1425
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1426
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1427
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1428
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1429
+ """
1430
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1431
+
1432
+ transformer_outputs = self.model(
1433
+ input_ids,
1434
+ attention_mask=attention_mask,
1435
+ position_ids=position_ids,
1436
+ past_key_values=past_key_values,
1437
+ inputs_embeds=inputs_embeds,
1438
+ use_cache=use_cache,
1439
+ output_attentions=output_attentions,
1440
+ output_hidden_states=output_hidden_states,
1441
+ return_dict=return_dict,
1442
+ )
1443
+ hidden_states = transformer_outputs[0]
1444
+ logits = self.score(hidden_states)
1445
+
1446
+ if input_ids is not None:
1447
+ batch_size = input_ids.shape[0]
1448
+ else:
1449
+ batch_size = inputs_embeds.shape[0]
1450
+
1451
+ if self.config.pad_token_id is None and batch_size != 1:
1452
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1453
+ if self.config.pad_token_id is None:
1454
+ sequence_lengths = -1
1455
+ else:
1456
+ if input_ids is not None:
1457
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1458
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1459
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1460
+ sequence_lengths = sequence_lengths.to(logits.device)
1461
+ else:
1462
+ sequence_lengths = -1
1463
+
1464
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1465
+
1466
+ loss = None
1467
+ if labels is not None:
1468
+ labels = labels.to(logits.device)
1469
+ if self.config.problem_type is None:
1470
+ if self.num_labels == 1:
1471
+ self.config.problem_type = "regression"
1472
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1473
+ self.config.problem_type = "single_label_classification"
1474
+ else:
1475
+ self.config.problem_type = "multi_label_classification"
1476
+
1477
+ if self.config.problem_type == "regression":
1478
+ loss_fct = MSELoss()
1479
+ if self.num_labels == 1:
1480
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1481
+ else:
1482
+ loss = loss_fct(pooled_logits, labels)
1483
+ elif self.config.problem_type == "single_label_classification":
1484
+ loss_fct = CrossEntropyLoss()
1485
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1486
+ elif self.config.problem_type == "multi_label_classification":
1487
+ loss_fct = BCEWithLogitsLoss()
1488
+ loss = loss_fct(pooled_logits, labels)
1489
+ if not return_dict:
1490
+ output = (pooled_logits,) + transformer_outputs[1:]
1491
+ return ((loss,) + output) if loss is not None else output
1492
+
1493
+ return SequenceClassifierOutputWithPast(
1494
+ loss=loss,
1495
+ logits=pooled_logits,
1496
+ past_key_values=transformer_outputs.past_key_values,
1497
+ hidden_states=transformer_outputs.hidden_states,
1498
+ attentions=transformer_outputs.attentions,
1499
+ )
steel-llm-step-660000-ckpt/softmoe_v3.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+
8
+ def softmax(x: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
9
+ """
10
+ Compute the softmax along the specified dimensions.
11
+ This function adds the option to specify multiple dimensions
12
+
13
+ Args:
14
+ x (torch.Tensor): Input tensor.
15
+ dims (int or tuple[int]): The dimension or list of dimensions along which the softmax probabilities are computed.
16
+
17
+ Returns:
18
+ torch.Tensor: Output tensor containing softmax probabilities along the specified dimensions.
19
+ """
20
+ dtype = x.dtype
21
+ x = x.to(torch.float32)
22
+ max_vals = torch.amax(x, dim=dim, keepdim=True)
23
+ e_x = torch.exp(x - max_vals)
24
+ sum_exp = e_x.sum(dim=dim, keepdim=True)
25
+ return (e_x / sum_exp).to(dtype)
26
+
27
+ # copy from https://github.com/bwconrad/soft-moe
28
+ class SteelSoftMoEV3(nn.Module):
29
+ """
30
+ A wrapper class to create a Soft Mixture of Experts layer.
31
+
32
+ From "From Sparse to Soft Mixtures of Experts"
33
+ https://arxiv.org/pdf/2308.00951.pdf
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ config,
39
+ layer: Callable,
40
+ ) -> None:
41
+ """
42
+ Args:
43
+ dim (int): Dimensionality of input features.
44
+ num_experts (int): Number of experts.
45
+ slots_per_expert (int): Number of token slots per expert.
46
+ layer (Callable): Network layer of the experts.
47
+ normalize (bool): Normalize input and phi (sec. 2.3 from paper)
48
+ **layer_kwargs: Additional keyword arguments for the layer class.
49
+ """
50
+ super().__init__()
51
+
52
+ self.dim = config.hidden_size
53
+ self.num_experts = config.n_experts
54
+ self.slots_per_expert = config.slots_per_expert if hasattr(config, "slots_per_expert") else 1
55
+ self.normalize = True
56
+
57
+ # Initialize phi and normalization scaling factor
58
+ self.phi = nn.Parameter(torch.zeros(self.dim, self.num_experts, self.slots_per_expert))
59
+ if self.normalize:
60
+ self.scale = nn.Parameter(torch.ones(1))
61
+
62
+ # Initialize phi using LeCun normal initialization
63
+ # https://github.com/google-research/vmoe/blob/662341d007650d5bbb7c6a2bef7f3c759a20cc7e/vmoe/projects/soft_moe/router.py#L49C1-L49C1
64
+ nn.init.normal_(self.phi, mean=0, std=1 / self.dim**0.5)
65
+
66
+ # Create a list of expert networks
67
+ self.experts = nn.ModuleList(
68
+ [layer(config) for _ in range(self.num_experts)]
69
+ )
70
+
71
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
72
+ """
73
+ Forward pass through the Soft-MoE layer (algorithm 1 from paper).
74
+
75
+ Args:
76
+ x (torch.Tensor): Input tensor of shape [batch_size, seq_len, input_dim].
77
+
78
+ Returns:
79
+ torch.Tensor: Output tensor of shape [batch_size, seq_len, input_dim].
80
+ """
81
+ assert (
82
+ x.shape[-1] == self.dim
83
+ ), f"Input feature dim of {x.shape[-1]} does not match layer dim of {self.dim}"
84
+ assert (
85
+ len(x.shape) == 3
86
+ ), f"Input expected to have 3 dimensions but has {len(x.shape)}"
87
+
88
+ phi = self.phi
89
+
90
+ # Normalize input and phi
91
+ if self.normalize:
92
+ x = F.normalize(x, dim=2) # [b, m, d]
93
+ phi = self.scale * F.normalize(phi, dim=0) # [d, n, p]
94
+
95
+ # Compute dispatch and combine weights
96
+ logits = torch.einsum("bmd,dnp->bmnp", x, phi)
97
+ d = softmax(logits, dim=1)
98
+ c = softmax(logits, dim=(2, 3))
99
+ # tmp = c[0,:,:,0].reshape([c.shape[1],-1])
100
+ # print("num:",tmp, "shape:",tmp.shape, "sum:",tmp.sum(dim=1))
101
+ # Compute input slots as weighted average of input tokens using dispatch weights
102
+ xs = torch.einsum("bmd,bmnp->bnpd", x, d)
103
+
104
+ # Apply expert to corresponding slots
105
+ ys = torch.stack(
106
+ [f_i(xs[:, i, :, :]) for i, f_i in enumerate(self.experts)], dim=1
107
+ )
108
+
109
+ # Compute output tokens as weighted average of output slots using combine weights
110
+ y = torch.einsum("bnpd,bmnp->bmd", ys, c)
111
+
112
+ return y
steel-llm-step-660000-ckpt/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
steel-llm-step-660000-ckpt/tokenizer_config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": ["<|im_start|>", "<|im_end|>"],
30
+ "bos_token": null,
31
+ "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 %}",
32
+ "clean_up_tokenization_spaces": false,
33
+ "eos_token": "<|im_end|>",
34
+ "errors": "replace",
35
+ "model_max_length": 32768,
36
+ "pad_token": "<|endoftext|>",
37
+ "split_special_tokens": false,
38
+ "tokenizer_class": "Qwen2Tokenizer",
39
+ "unk_token": null
40
+ }
41
+
steel-llm-step-660000-ckpt/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
steel-llm-step-720000-ckpt/config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "FFN_type": "softmoe_v3",
3
+ "_name_or_path": "./steel_modify_from_qwen_1_5",
4
+ "architectures": [
5
+ "SteelForCausalLM"
6
+ ],
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_steel.SteelConfig",
10
+ "AutoModelForCausalLM": "modeling_steel.SteelForCausalLM"
11
+ },
12
+ "bos_token_id": 151643,
13
+ "eos_token_id": 151645,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 1792,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 1792,
18
+ "max_position_embeddings": 32768,
19
+ "max_window_layers": 21,
20
+ "mlp_div_ratio": 4,
21
+ "mlp_type": "senet",
22
+ "model_type": "qwen2",
23
+ "n_experts": 6,
24
+ "num_attention_heads": 32,
25
+ "num_hidden_layers": 18,
26
+ "num_key_value_heads": 32,
27
+ "rms_norm_eps": 1e-06,
28
+ "rope_theta": 1000000.0,
29
+ "sliding_window": 32768,
30
+ "slots_per_expert": 1,
31
+ "tie_word_embeddings": false,
32
+ "torch_dtype": "float32",
33
+ "transformers_version": "4.41.1",
34
+ "use_cache": true,
35
+ "use_sliding_window": false,
36
+ "vocab_size": 151936
37
+ }
steel-llm-step-720000-ckpt/configuration_steel.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 zhanshijin and lishu. All rights reserved.
3
+ #
4
+ # This project copy from qwen1.5
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ Steel model configuration"""
17
+
18
+ from transformers.configuration_utils import PretrainedConfig
19
+ from transformers.utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+
26
+
27
+ class SteelConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`Qwen2Model`]. It is used to instantiate a
30
+ Qwen2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
31
+ with the defaults will yield a similar configuration to that of
32
+ Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PretrainedConfig`] for more information.
36
+
37
+
38
+ Args:
39
+ vocab_size (`int`, *optional*, defaults to 151936):
40
+ Vocabulary size of the Qwen2 model. Defines the number of different tokens that can be represented by the
41
+ `inputs_ids` passed when calling [`Qwen2Model`]
42
+ hidden_size (`int`, *optional*, defaults to 4096):
43
+ Dimension of the hidden representations.
44
+ intermediate_size (`int`, *optional*, defaults to 22016):
45
+ Dimension of the MLP representations.
46
+ num_hidden_layers (`int`, *optional*, defaults to 32):
47
+ Number of hidden layers in the Transformer encoder.
48
+ num_attention_heads (`int`, *optional*, defaults to 32):
49
+ Number of attention heads for each attention layer in the Transformer encoder.
50
+ num_key_value_heads (`int`, *optional*, defaults to 32):
51
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
52
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
53
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
54
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
55
+ by meanpooling all the original heads within that group. For more details checkout [this
56
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
57
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
58
+ The non-linear activation function (function or string) in the decoder.
59
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
60
+ The maximum sequence length that this model might ever be used with.
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
64
+ The epsilon used by the rms normalization layers.
65
+ use_cache (`bool`, *optional*, defaults to `True`):
66
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
67
+ relevant if `config.is_decoder=True`.
68
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
69
+ Whether the model's input and output word embeddings should be tied.
70
+ rope_theta (`float`, *optional*, defaults to 10000.0):
71
+ The base period of the RoPE embeddings.
72
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
73
+ Whether to use sliding window attention.
74
+ sliding_window (`int`, *optional*, defaults to 4096):
75
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
76
+ max_window_layers (`int`, *optional*, defaults to 28):
77
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
78
+ attention_dropout (`float`, *optional*, defaults to 0.0):
79
+ The dropout ratio for the attention probabilities.
80
+ """
81
+
82
+ model_type = "qwen2"
83
+ keys_to_ignore_at_inference = ["past_key_values"]
84
+
85
+ def __init__(
86
+ self,
87
+ vocab_size=151936,
88
+ hidden_size=4096,
89
+ intermediate_size=22016,
90
+ num_hidden_layers=32,
91
+ num_attention_heads=32,
92
+ num_key_value_heads=32,
93
+ hidden_act="silu",
94
+ max_position_embeddings=32768,
95
+ initializer_range=0.02,
96
+ rms_norm_eps=1e-6,
97
+ use_cache=True,
98
+ tie_word_embeddings=False,
99
+ rope_theta=10000.0,
100
+ use_sliding_window=False,
101
+ sliding_window=4096,
102
+ max_window_layers=28,
103
+ attention_dropout=0.0,
104
+ **kwargs,
105
+ ):
106
+ self.vocab_size = vocab_size
107
+ self.max_position_embeddings = max_position_embeddings
108
+ self.hidden_size = hidden_size
109
+ self.intermediate_size = intermediate_size
110
+ self.num_hidden_layers = num_hidden_layers
111
+ self.num_attention_heads = num_attention_heads
112
+ self.use_sliding_window = use_sliding_window
113
+ self.sliding_window = sliding_window
114
+ self.max_window_layers = max_window_layers
115
+
116
+ # for backward compatibility
117
+ if num_key_value_heads is None:
118
+ num_key_value_heads = num_attention_heads
119
+
120
+ self.num_key_value_heads = num_key_value_heads
121
+ self.hidden_act = hidden_act
122
+ self.initializer_range = initializer_range
123
+ self.rms_norm_eps = rms_norm_eps
124
+ self.use_cache = use_cache
125
+ self.rope_theta = rope_theta
126
+ self.attention_dropout = attention_dropout
127
+
128
+ super().__init__(
129
+ tie_word_embeddings=tie_word_embeddings,
130
+ **kwargs,
131
+ )
steel-llm-step-720000-ckpt/generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 151643,
4
+ "eos_token_id": 151645,
5
+ "transformers_version": "4.41.1"
6
+ }
steel-llm-step-720000-ckpt/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
steel-llm-step-720000-ckpt/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6db7c29544fae9845c12b83925a1b09e9a64f68e63c5da52e7c7104fb4ab8dfd
3
+ size 4491766872
steel-llm-step-720000-ckpt/modeling_steel.py ADDED
@@ -0,0 +1,1499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The zhanshijin and lishu. All rights reserved.
3
+ #
4
+ #
5
+ #This model copy from qwen1.5.
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+ """ PyTorch Steel model."""
19
+ import inspect
20
+ import math
21
+ import warnings
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.nn.functional as F
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+
30
+ from transformers.activations import ACT2FN
31
+ from transformers.cache_utils import Cache, DynamicCache
32
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
33
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
34
+ from transformers.modeling_utils import PreTrainedModel
35
+ from transformers.utils import (
36
+ add_start_docstrings,
37
+ add_start_docstrings_to_model_forward,
38
+ is_flash_attn_2_available,
39
+ is_flash_attn_greater_or_equal_2_10,
40
+ logging,
41
+ replace_return_docstrings,
42
+ )
43
+ from configuration_steel import SteelConfig
44
+ from softmoe_v3 import SteelSoftMoEV3
45
+
46
+ if is_flash_attn_2_available():
47
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
48
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
49
+
50
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
51
+ print("zhanshijin: surrport flash_attn_2")
52
+ print(f"zhanshijin: if flash attn surrport window:{_flash_supports_window_size}")
53
+ else:
54
+ print("zhanshijin: not surrport flash_attn_2")
55
+
56
+ logger = logging.get_logger(__name__)
57
+
58
+ rms_norm = None
59
+ def _import_cuda_rmsnorm():
60
+ global rms_norm
61
+ try:
62
+ from flash_attn.ops.rms_norm import rms_norm as __rms_norm
63
+ rms_norm = __rms_norm
64
+ print("zhanshijin: success import cuda __rms_norm")
65
+ except ImportError:
66
+ logger.warn(
67
+ "Warning: import flash_attn rms_norm fail, please install FlashAttention layer_norm to get higher efficiency "
68
+ "https://github.com/Dao-AILab/flash-attention/tree/main/csrc/layer_norm"
69
+ )
70
+
71
+ _CONFIG_FOR_DOC = "SteelConfig"
72
+
73
+
74
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
75
+ def _get_unpad_data(attention_mask):
76
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
77
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
78
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
79
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
80
+ return (
81
+ indices,
82
+ cu_seqlens,
83
+ max_seqlen_in_batch,
84
+ )
85
+
86
+
87
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Steel
88
+ class SteelRMSNorm(nn.Module):
89
+ def __init__(self, hidden_size, eps=1e-6):
90
+ """
91
+ SteelRMSNorm is equivalent to T5LayerNorm
92
+ """
93
+ super().__init__()
94
+ self.weight = nn.Parameter(torch.ones(hidden_size))
95
+ self.variance_epsilon = eps
96
+
97
+ def forward(self, hidden_states):
98
+ if rms_norm is not None and hidden_states.is_cuda:
99
+ return rms_norm(hidden_states, self.weight, self.variance_epsilon)
100
+ else:
101
+ input_dtype = hidden_states.dtype
102
+ hidden_states = hidden_states.to(torch.float32)
103
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
104
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
105
+ # test precision consistency
106
+ # from flash_attn.ops.rms_norm import rms_norm as _rms_norm
107
+ # print(_rms_norm(hidden_states, self.weight, self.variance_epsilon)[0,0,:10])
108
+ # print((self.weight * hidden_states.to(input_dtype))[0,0,:10])
109
+ return self.weight * hidden_states.to(input_dtype)
110
+
111
+
112
+ # Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Steel
113
+ class SteelRotaryEmbedding(nn.Module):
114
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
115
+ super().__init__()
116
+
117
+ self.dim = dim
118
+ self.max_position_embeddings = max_position_embeddings
119
+ self.base = base
120
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
121
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
122
+
123
+ # Build here to make `torch.jit.trace` work.
124
+ self._set_cos_sin_cache(
125
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
126
+ )
127
+
128
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
129
+ self.max_seq_len_cached = seq_len
130
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
131
+
132
+ freqs = torch.outer(t, self.inv_freq)
133
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
134
+ emb = torch.cat((freqs, freqs), dim=-1)
135
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
136
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
137
+
138
+ def forward(self, x, seq_len=None):
139
+ # x: [bs, num_attention_heads, seq_len, head_size]
140
+ if seq_len > self.max_seq_len_cached:
141
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
142
+
143
+ return (
144
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
145
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
146
+ )
147
+
148
+
149
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
150
+ def rotate_half(x):
151
+ """Rotates half the hidden dims of the input."""
152
+ x1 = x[..., : x.shape[-1] // 2]
153
+ x2 = x[..., x.shape[-1] // 2 :]
154
+ return torch.cat((-x2, x1), dim=-1)
155
+
156
+
157
+ # Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
158
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
159
+ """Applies Rotary Position Embedding to the query and key tensors.
160
+
161
+ Args:
162
+ q (`torch.Tensor`): The query tensor.
163
+ k (`torch.Tensor`): The key tensor.
164
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
165
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
166
+ position_ids (`torch.Tensor`):
167
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
168
+ used to pass offsetted position ids when working with a KV-cache.
169
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
170
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
171
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
172
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
173
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
174
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
175
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
176
+ Returns:
177
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
178
+ """
179
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
180
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
181
+ q_embed = (q * cos) + (rotate_half(q) * sin)
182
+ k_embed = (k * cos) + (rotate_half(k) * sin)
183
+ return q_embed, k_embed
184
+
185
+
186
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Steel->Steel
187
+ class SteelMLP(nn.Module):
188
+ def __init__(self, config):
189
+ super().__init__()
190
+ self.config = config
191
+ self.hidden_size = config.hidden_size
192
+ self.intermediate_size = config.intermediate_size //config.mlp_div_ratio
193
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
194
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
195
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
196
+ self.act_fn = ACT2FN[config.hidden_act]
197
+
198
+ def forward(self, x):
199
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
200
+
201
+ class SteelSENet(nn.Module):
202
+ def __init__(self, config):
203
+ super().__init__()
204
+ self.config = config
205
+ self.hidden_size = config.hidden_size
206
+ self.intermediate_size = config.intermediate_size //config.mlp_div_ratio
207
+ self.gate_up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
208
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
209
+ self.gate_down_proj = nn.Linear(self.intermediate_size,self.hidden_size, bias=False)
210
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
211
+ self.act_fn1 = ACT2FN[config.hidden_act]
212
+ self.act_fn2 = ACT2FN[config.hidden_act]
213
+
214
+ def forward(self, x):
215
+ x = self.act_fn1(self.gate_up_proj(x)) * self.up_proj(x)
216
+ return self.act_fn2(self.gate_down_proj(x)) * self.down_proj(x)
217
+
218
+
219
+ class SteelSoftMoeV1(nn.Module):
220
+ def __init__(self, config, layer=None):
221
+ super().__init__()
222
+ self.config = config
223
+ self.experts = nn.ModuleList([layer(config) for _ in range(config.n_experts)])
224
+ self.gating = nn.Linear(config.hidden_size, config.n_experts)
225
+ def forward(self, x):
226
+ weights = self.gating(x)
227
+ weights = nn.functional.softmax(weights, dim=-1, dtype=torch.float32).to(x.dtype)
228
+ outputs = torch.stack(
229
+ [expert(x) for expert in self.experts], dim=2)
230
+ weights = weights.unsqueeze(-1)
231
+ return torch.sum(outputs * weights, dim=2)
232
+
233
+ class SteelSoftMoeV2(nn.Module):
234
+ def __init__(self, config, layer):
235
+ super().__init__()
236
+ self.config = config
237
+ self.experts = nn.ModuleList([layer(config) for _ in range(config.n_experts)])
238
+ self.score = nn.Parameter(torch.randn(config.hidden_size, config.n_experts * config.slots_per_expert))
239
+
240
+ def forward(self, x):
241
+ logits = torch.matmul(x, self.score) # (batch_size, seq_len, slots)
242
+ dispatch_weights = F.softmax(logits, dim=-1,dtype=torch.float32).to(x.dtype)
243
+ combine_weights = F.softmax(logits, dim=1,dtype=torch.float32).to(x.dtype)
244
+ xs = torch.bmm(dispatch_weights.transpose(1, 2), x)
245
+ ys = torch.cat(
246
+ [expert(xs[:, i * self.config.slots_per_expert : (i + 1) * self.config.slots_per_expert, :])
247
+ for i, expert in enumerate(self.experts)],
248
+ dim=1
249
+ )
250
+ y = torch.bmm(combine_weights, ys)
251
+ return y
252
+
253
+
254
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
255
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
256
+ """
257
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
258
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
259
+ """
260
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
261
+ if n_rep == 1:
262
+ return hidden_states
263
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
264
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
265
+
266
+
267
+ class SteelAttention(nn.Module):
268
+ """
269
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
270
+ and "Generating Long Sequences with Sparse Transformers".
271
+ """
272
+
273
+ def __init__(self, config: SteelConfig, layer_idx: Optional[int] = None):
274
+ super().__init__()
275
+ self.config = config
276
+ self.layer_idx = layer_idx
277
+ if layer_idx is None:
278
+ logger.warning_once(
279
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
280
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
281
+ "when creating this class."
282
+ )
283
+
284
+ self.hidden_size = config.hidden_size
285
+ self.num_heads = config.num_attention_heads
286
+ self.head_dim = self.hidden_size // self.num_heads
287
+ self.num_key_value_heads = config.num_key_value_heads
288
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
289
+ self.max_position_embeddings = config.max_position_embeddings
290
+ self.rope_theta = config.rope_theta
291
+ self.is_causal = True
292
+ self.attention_dropout = config.attention_dropout
293
+
294
+ if (self.head_dim * self.num_heads) != self.hidden_size:
295
+ raise ValueError(
296
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
297
+ f" and `num_heads`: {self.num_heads})."
298
+ )
299
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
300
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
301
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
302
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
303
+
304
+ self.rotary_emb = SteelRotaryEmbedding(
305
+ self.head_dim,
306
+ max_position_embeddings=self.max_position_embeddings,
307
+ base=self.rope_theta,
308
+ )
309
+
310
+ def forward(
311
+ self,
312
+ hidden_states: torch.Tensor,
313
+ attention_mask: Optional[torch.Tensor] = None,
314
+ position_ids: Optional[torch.LongTensor] = None,
315
+ past_key_value: Optional[Cache] = None,
316
+ output_attentions: bool = False,
317
+ use_cache: bool = False,
318
+ **kwargs,
319
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
320
+ if "padding_mask" in kwargs:
321
+ warnings.warn(
322
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
323
+ )
324
+ bsz, q_len, _ = hidden_states.size()
325
+
326
+ query_states = self.q_proj(hidden_states)
327
+ key_states = self.k_proj(hidden_states)
328
+ value_states = self.v_proj(hidden_states)
329
+
330
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
331
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
332
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
333
+
334
+ kv_seq_len = key_states.shape[-2]
335
+ if past_key_value is not None:
336
+ if self.layer_idx is None:
337
+ raise ValueError(
338
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
339
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
340
+ "with a layer index."
341
+ )
342
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
343
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
344
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
345
+
346
+
347
+ if past_key_value is not None:
348
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
349
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
350
+
351
+ # repeat k/v heads if n_kv_heads < n_heads
352
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
353
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
354
+
355
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
356
+
357
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
358
+ raise ValueError(
359
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
360
+ f" {attn_weights.size()}"
361
+ )
362
+
363
+ if attention_mask is not None:
364
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
365
+ raise ValueError(
366
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
367
+ )
368
+
369
+ attn_weights = attn_weights + attention_mask
370
+
371
+ # upcast attention to fp32
372
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
373
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
374
+ attn_output = torch.matmul(attn_weights, value_states)
375
+
376
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
377
+ raise ValueError(
378
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
379
+ f" {attn_output.size()}"
380
+ )
381
+
382
+ attn_output = attn_output.transpose(1, 2).contiguous()
383
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
384
+
385
+ attn_output = self.o_proj(attn_output)
386
+
387
+ if not output_attentions:
388
+ attn_weights = None
389
+
390
+ return attn_output, attn_weights, past_key_value
391
+
392
+
393
+ class SteelFlashAttention2(SteelAttention):
394
+ """
395
+ Steel flash attention module, following Steel attention module. This module inherits from `SteelAttention`
396
+ as the weights of the module stays untouched. The only required change would be on the forward pass
397
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
398
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
399
+ config.max_window_layers layers.
400
+ """
401
+
402
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
403
+ def __init__(self, *args, **kwargs):
404
+ super().__init__(*args, **kwargs)
405
+
406
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
407
+ # 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.
408
+ # 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).
409
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
410
+
411
+ def forward(
412
+ self,
413
+ hidden_states: torch.Tensor,
414
+ attention_mask: Optional[torch.Tensor] = None,
415
+ position_ids: Optional[torch.LongTensor] = None,
416
+ past_key_value: Optional[Cache] = None,
417
+ output_attentions: bool = False,
418
+ use_cache: bool = False,
419
+ **kwargs,
420
+ ):
421
+ if "padding_mask" in kwargs:
422
+ warnings.warn(
423
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
424
+ )
425
+
426
+ # overwrite attention_mask with padding_mask
427
+ attention_mask = kwargs.pop("padding_mask")
428
+ bsz, q_len, _ = hidden_states.size()
429
+
430
+ query_states = self.q_proj(hidden_states)
431
+ key_states = self.k_proj(hidden_states)
432
+ value_states = self.v_proj(hidden_states)
433
+
434
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
435
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
436
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
437
+
438
+ kv_seq_len = key_states.shape[-2]
439
+ if past_key_value is not None:
440
+ if self.layer_idx is None:
441
+ raise ValueError(
442
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
443
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
444
+ "with a layer index."
445
+ )
446
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
447
+
448
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
449
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
450
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
451
+
452
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
453
+
454
+ use_sliding_windows = (
455
+ _flash_supports_window_size
456
+ and getattr(self.config, "sliding_window", None) is not None
457
+ and kv_seq_len > self.config.sliding_window
458
+ and self.config.use_sliding_window
459
+ )
460
+
461
+ if not _flash_supports_window_size:
462
+ logger.warning_once(
463
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
464
+ " make sure to upgrade flash-attn library."
465
+ )
466
+
467
+ if past_key_value is not None:
468
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
469
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
470
+ if (
471
+ getattr(self.config, "sliding_window", None) is not None
472
+ and kv_seq_len > self.config.sliding_window
473
+ and cache_has_contents
474
+ ):
475
+ slicing_tokens = 1 - self.config.sliding_window
476
+
477
+ past_key = past_key_value[self.layer_idx][0]
478
+ past_value = past_key_value[self.layer_idx][1]
479
+
480
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
481
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
482
+
483
+ if past_key.shape[-2] != self.config.sliding_window - 1:
484
+ raise ValueError(
485
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
486
+ f" {past_key.shape}"
487
+ )
488
+
489
+ if attention_mask is not None:
490
+ attention_mask = attention_mask[:, slicing_tokens:]
491
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
492
+
493
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
494
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
495
+
496
+ # repeat k/v heads if n_kv_heads < n_heads
497
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
498
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
499
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
500
+
501
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
502
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
503
+ # cast them back in float16 just to be sure everything works as expected.
504
+ input_dtype = query_states.dtype
505
+ if input_dtype == torch.float32:
506
+ if torch.is_autocast_enabled():
507
+ target_dtype = torch.get_autocast_gpu_dtype()
508
+ # Handle the case where the model is quantized
509
+ elif hasattr(self.config, "_pre_quantization_dtype"):
510
+ target_dtype = self.config._pre_quantization_dtype
511
+ else:
512
+ target_dtype = self.q_proj.weight.dtype
513
+
514
+ logger.warning_once(
515
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
516
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
517
+ f" {target_dtype}."
518
+ )
519
+
520
+ query_states = query_states.to(target_dtype)
521
+ key_states = key_states.to(target_dtype)
522
+ value_states = value_states.to(target_dtype)
523
+
524
+ # Reashape to the expected shape for Flash Attention
525
+ query_states = query_states.transpose(1, 2)
526
+ key_states = key_states.transpose(1, 2)
527
+ value_states = value_states.transpose(1, 2)
528
+
529
+ attn_output = self._flash_attention_forward(
530
+ query_states,
531
+ key_states,
532
+ value_states,
533
+ attention_mask,
534
+ q_len,
535
+ dropout=dropout_rate,
536
+ use_sliding_windows=use_sliding_windows,
537
+ )
538
+
539
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
540
+ attn_output = self.o_proj(attn_output)
541
+
542
+ if not output_attentions:
543
+ attn_weights = None
544
+
545
+ return attn_output, attn_weights, past_key_value
546
+
547
+ def _flash_attention_forward(
548
+ self,
549
+ query_states,
550
+ key_states,
551
+ value_states,
552
+ attention_mask,
553
+ query_length,
554
+ dropout=0.0,
555
+ softmax_scale=None,
556
+ use_sliding_windows=False,
557
+ ):
558
+ """
559
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
560
+ first unpad the input, then computes the attention scores and pad the final attention scores.
561
+
562
+ Args:
563
+ query_states (`torch.Tensor`):
564
+ Input query states to be passed to Flash Attention API
565
+ key_states (`torch.Tensor`):
566
+ Input key states to be passed to Flash Attention API
567
+ value_states (`torch.Tensor`):
568
+ Input value states to be passed to Flash Attention API
569
+ attention_mask (`torch.Tensor`):
570
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
571
+ position of padding tokens and 1 for the position of non-padding tokens.
572
+ dropout (`float`):
573
+ Attention dropout
574
+ softmax_scale (`float`, *optional*):
575
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
576
+ use_sliding_windows (`bool`, *optional*):
577
+ Whether to activate sliding window attention.
578
+ """
579
+ if not self._flash_attn_uses_top_left_mask:
580
+ causal = self.is_causal
581
+ else:
582
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
583
+ causal = self.is_causal and query_length != 1
584
+
585
+ # Decide whether to use SWA or not by layer index.
586
+ if use_sliding_windows and self.layer_idx >= self.config.max_window_layers:
587
+ use_sliding_windows = False
588
+
589
+ # Contains at least one padding token in the sequence
590
+ if attention_mask is not None:
591
+ batch_size = query_states.shape[0]
592
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
593
+ query_states, key_states, value_states, attention_mask, query_length
594
+ )
595
+
596
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
597
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
598
+
599
+ if not use_sliding_windows:
600
+ attn_output_unpad = flash_attn_varlen_func(
601
+ query_states,
602
+ key_states,
603
+ value_states,
604
+ cu_seqlens_q=cu_seqlens_q,
605
+ cu_seqlens_k=cu_seqlens_k,
606
+ max_seqlen_q=max_seqlen_in_batch_q,
607
+ max_seqlen_k=max_seqlen_in_batch_k,
608
+ dropout_p=dropout,
609
+ softmax_scale=softmax_scale,
610
+ causal=causal,
611
+ )
612
+ else:
613
+ attn_output_unpad = flash_attn_varlen_func(
614
+ query_states,
615
+ key_states,
616
+ value_states,
617
+ cu_seqlens_q=cu_seqlens_q,
618
+ cu_seqlens_k=cu_seqlens_k,
619
+ max_seqlen_q=max_seqlen_in_batch_q,
620
+ max_seqlen_k=max_seqlen_in_batch_k,
621
+ dropout_p=dropout,
622
+ softmax_scale=softmax_scale,
623
+ causal=causal,
624
+ window_size=(self.config.sliding_window, self.config.sliding_window),
625
+ )
626
+
627
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
628
+ else:
629
+ if not use_sliding_windows:
630
+ attn_output = flash_attn_func(
631
+ query_states,
632
+ key_states,
633
+ value_states,
634
+ dropout,
635
+ softmax_scale=softmax_scale,
636
+ causal=causal,
637
+ )
638
+ else:
639
+ attn_output = flash_attn_func(
640
+ query_states,
641
+ key_states,
642
+ value_states,
643
+ dropout,
644
+ softmax_scale=softmax_scale,
645
+ causal=causal,
646
+ window_size=(self.config.sliding_window, self.config.sliding_window),
647
+ )
648
+
649
+ return attn_output
650
+
651
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
652
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
653
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
654
+
655
+ # On the first iteration we need to properly re-create the padding mask
656
+ # by slicing it on the proper place
657
+ if kv_seq_len != attention_mask.shape[-1]:
658
+ attention_mask_num_tokens = attention_mask.shape[-1]
659
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
660
+
661
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
662
+
663
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
664
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
665
+
666
+ if query_length == kv_seq_len:
667
+ query_layer = index_first_axis(
668
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
669
+ )
670
+ cu_seqlens_q = cu_seqlens_k
671
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
672
+ indices_q = indices_k
673
+ elif query_length == 1:
674
+ max_seqlen_in_batch_q = 1
675
+ cu_seqlens_q = torch.arange(
676
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
677
+ ) # There is a memcpy here, that is very bad.
678
+ indices_q = cu_seqlens_q[:-1]
679
+ query_layer = query_layer.squeeze(1)
680
+ else:
681
+ # The -q_len: slice assumes left padding.
682
+ attention_mask = attention_mask[:, -query_length:]
683
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
684
+
685
+ return (
686
+ query_layer,
687
+ key_layer,
688
+ value_layer,
689
+ indices_q,
690
+ (cu_seqlens_q, cu_seqlens_k),
691
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
692
+ )
693
+
694
+
695
+ # Copied from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Steel
696
+ class SteelSdpaAttention(SteelAttention):
697
+ """
698
+ Steel attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
699
+ `SteelAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
700
+ SDPA API.
701
+ """
702
+
703
+ # Adapted from SteelAttention.forward
704
+ def forward(
705
+ self,
706
+ hidden_states: torch.Tensor,
707
+ attention_mask: Optional[torch.Tensor] = None,
708
+ position_ids: Optional[torch.LongTensor] = None,
709
+ past_key_value: Optional[Cache] = None,
710
+ output_attentions: bool = False,
711
+ use_cache: bool = False,
712
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
713
+ if output_attentions:
714
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
715
+ logger.warning_once(
716
+ "SteelModel is using SteelSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
717
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
718
+ )
719
+ return super().forward(
720
+ hidden_states=hidden_states,
721
+ attention_mask=attention_mask,
722
+ position_ids=position_ids,
723
+ past_key_value=past_key_value,
724
+ output_attentions=output_attentions,
725
+ use_cache=use_cache,
726
+ )
727
+
728
+ bsz, q_len, _ = hidden_states.size()
729
+
730
+ query_states = self.q_proj(hidden_states)
731
+ key_states = self.k_proj(hidden_states)
732
+ value_states = self.v_proj(hidden_states)
733
+
734
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
735
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
736
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
737
+
738
+ kv_seq_len = key_states.shape[-2]
739
+ if past_key_value is not None:
740
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
741
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
742
+
743
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
744
+
745
+ if past_key_value is not None:
746
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
747
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
748
+
749
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
750
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
751
+
752
+ if attention_mask is not None:
753
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
754
+ raise ValueError(
755
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
756
+ )
757
+
758
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
759
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
760
+ if query_states.device.type == "cuda" and attention_mask is not None:
761
+ query_states = query_states.contiguous()
762
+ key_states = key_states.contiguous()
763
+ value_states = value_states.contiguous()
764
+
765
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
766
+ query_states,
767
+ key_states,
768
+ value_states,
769
+ attn_mask=attention_mask,
770
+ dropout_p=self.attention_dropout if self.training else 0.0,
771
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
772
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
773
+ )
774
+
775
+ attn_output = attn_output.transpose(1, 2).contiguous()
776
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
777
+
778
+ attn_output = self.o_proj(attn_output)
779
+
780
+ return attn_output, None, past_key_value
781
+
782
+
783
+ Steel_ATTENTION_CLASSES = {
784
+ "eager": SteelAttention,
785
+ "flash_attention_2": SteelFlashAttention2,
786
+ "sdpa": SteelSdpaAttention,
787
+ }
788
+
789
+
790
+ class SteelDecoderLayer(nn.Module):
791
+ def __init__(self, config: SteelConfig, layer_idx: int):
792
+ super().__init__()
793
+ self.hidden_size = config.hidden_size
794
+
795
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
796
+ logger.warning_once(
797
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
798
+ "unexpected results may be encountered."
799
+ )
800
+ self.self_attn = Steel_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
801
+ if config.mlp_type == "raw":
802
+ mlp_class = SteelMLP
803
+ logger.warning_once(f"mlp_class: SteelMLP")
804
+ elif config.mlp_type == "senet":
805
+ mlp_class = SteelSENet
806
+ logger.warning_once(f"mlp_class: SteelSENet")
807
+ else:
808
+ raise NameError(f"No this mlp type: {config.mlp_type}")
809
+
810
+ if config.FFN_type == "raw":
811
+ self.mlp = mlp_class(config)
812
+ logger.warning_once(f"FFN: {mlp_class}")
813
+ elif config.FFN_type == "softmoe_v1":
814
+ self.mlp = SteelSoftMoeV1(config, layer=mlp_class)
815
+ logger.warning_once(f"FFN: SteelSoftMoeV1")
816
+ elif config.FFN_type == "softmoe_v2":
817
+ self.mlp = SteelSoftMoeV2(config, layer=mlp_class)
818
+ logger.warning_once(f"FFN: SteelSoftMoeV2")
819
+ elif config.FFN_type == "softmoe_v3":
820
+ self.mlp = SteelSoftMoEV3(config=config, layer=mlp_class)
821
+ logger.warning_once(f"FFN: SteelSoftMoeV3")
822
+ else:
823
+ raise NameError(f"No this FFN type: {config.FFN_type}")
824
+
825
+ self.input_layernorm = SteelRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
826
+ self.post_attention_layernorm = SteelRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
827
+
828
+ def forward(
829
+ self,
830
+ hidden_states: torch.Tensor,
831
+ attention_mask: Optional[torch.Tensor] = None,
832
+ position_ids: Optional[torch.LongTensor] = None,
833
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
834
+ output_attentions: Optional[bool] = False,
835
+ use_cache: Optional[bool] = False,
836
+ **kwargs,
837
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
838
+ if "padding_mask" in kwargs:
839
+ warnings.warn(
840
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
841
+ "Please make sure use `attention_mask` instead.`"
842
+ )
843
+ """
844
+ Args:
845
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
846
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
847
+ `(batch, sequence_length)` where padding elements are indicated by 0.
848
+ output_attentions (`bool`, *optional*):
849
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
850
+ returned tensors for more detail.
851
+ use_cache (`bool`, *optional*):
852
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
853
+ (see `past_key_values`).
854
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
855
+ """
856
+
857
+ residual = hidden_states
858
+
859
+ hidden_states = self.input_layernorm(hidden_states)
860
+
861
+ # Self Attention
862
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
863
+ hidden_states=hidden_states,
864
+ attention_mask=attention_mask,
865
+ position_ids=position_ids,
866
+ past_key_value=past_key_value,
867
+ output_attentions=output_attentions,
868
+ use_cache=use_cache,
869
+ )
870
+ hidden_states = residual + hidden_states
871
+
872
+ # Fully Connected
873
+ residual = hidden_states
874
+ hidden_states = self.post_attention_layernorm(hidden_states)
875
+ hidden_states = self.mlp(hidden_states)
876
+ hidden_states = residual + hidden_states
877
+
878
+ outputs = (hidden_states,)
879
+
880
+ if output_attentions:
881
+ outputs += (self_attn_weights,)
882
+
883
+ if use_cache:
884
+ outputs += (present_key_value,)
885
+
886
+ return outputs
887
+
888
+
889
+ Steel_START_DOCSTRING = r"""
890
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
891
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
892
+ etc.)
893
+
894
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
895
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
896
+ and behavior.
897
+
898
+ Parameters:
899
+ config ([`SteelConfig`]):
900
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
901
+ load the weights associated with the model, only the configuration. Check out the
902
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
903
+ """
904
+
905
+
906
+ @add_start_docstrings(
907
+ "The bare Steel Model outputting raw hidden-states without any specific head on top.",
908
+ Steel_START_DOCSTRING,
909
+ )
910
+ class SteelPreTrainedModel(PreTrainedModel):
911
+ config_class = SteelConfig
912
+ base_model_prefix = "model"
913
+ supports_gradient_checkpointing = True
914
+ _no_split_modules = ["SteelDecoderLayer"]
915
+ _skip_keys_device_placement = "past_key_values"
916
+ _supports_flash_attn_2 = True
917
+ _supports_sdpa = True
918
+ _supports_cache_class = True
919
+
920
+ def _init_weights(self, module):
921
+ std = self.config.initializer_range
922
+ if isinstance(module, nn.Linear):
923
+ module.weight.data.normal_(mean=0.0, std=std)
924
+ if module.bias is not None:
925
+ module.bias.data.zero_()
926
+ elif isinstance(module, nn.Embedding):
927
+ module.weight.data.normal_(mean=0.0, std=std)
928
+ if module.padding_idx is not None:
929
+ module.weight.data[module.padding_idx].zero_()
930
+
931
+
932
+ Steel_INPUTS_DOCSTRING = r"""
933
+ Args:
934
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
935
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
936
+ it.
937
+
938
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
939
+ [`PreTrainedTokenizer.__call__`] for details.
940
+
941
+ [What are input IDs?](../glossary#input-ids)
942
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
943
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
944
+
945
+ - 1 for tokens that are **not masked**,
946
+ - 0 for tokens that are **masked**.
947
+
948
+ [What are attention masks?](../glossary#attention-mask)
949
+
950
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
951
+ [`PreTrainedTokenizer.__call__`] for details.
952
+
953
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
954
+ `past_key_values`).
955
+
956
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
957
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
958
+ information on the default strategy.
959
+
960
+ - 1 indicates the head is **not masked**,
961
+ - 0 indicates the head is **masked**.
962
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
963
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
964
+ config.n_positions - 1]`.
965
+
966
+ [What are position IDs?](../glossary#position-ids)
967
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
968
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
969
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
970
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
971
+
972
+ Two formats are allowed:
973
+ - a [`~cache_utils.Cache`] instance;
974
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
975
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
976
+ cache format.
977
+
978
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
979
+ legacy cache format will be returned.
980
+
981
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
982
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
983
+ of shape `(batch_size, sequence_length)`.
984
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
985
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
986
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
987
+ model's internal embedding lookup matrix.
988
+ use_cache (`bool`, *optional*):
989
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
990
+ `past_key_values`).
991
+ output_attentions (`bool`, *optional*):
992
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
993
+ tensors for more detail.
994
+ output_hidden_states (`bool`, *optional*):
995
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
996
+ more detail.
997
+ return_dict (`bool`, *optional*):
998
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
999
+ """
1000
+
1001
+
1002
+ @add_start_docstrings(
1003
+ "The bare Steel Model outputting raw hidden-states without any specific head on top.",
1004
+ Steel_START_DOCSTRING,
1005
+ )
1006
+ class SteelModel(SteelPreTrainedModel):
1007
+ """
1008
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`SteelDecoderLayer`]
1009
+
1010
+ Args:
1011
+ config: SteelConfig
1012
+ """
1013
+
1014
+ def __init__(self, config: SteelConfig):
1015
+ super().__init__(config)
1016
+ self.padding_idx = config.pad_token_id
1017
+ self.vocab_size = config.vocab_size
1018
+
1019
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1020
+ self.layers = nn.ModuleList(
1021
+ [SteelDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1022
+ )
1023
+ self._attn_implementation = config._attn_implementation
1024
+ logger.warning_once(
1025
+ f"zhanshijin: now use _attn_implementation is {config._attn_implementation}, you can choose from {Steel_ATTENTION_CLASSES.keys()}"
1026
+ )
1027
+ self.norm = SteelRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1028
+
1029
+ self.gradient_checkpointing = False
1030
+ # Initialize weights and apply final processing
1031
+ self.post_init()
1032
+
1033
+ if hasattr(config, "use_cuda_rmsnorm") and config.use_cuda_rmsnorm:
1034
+ _import_cuda_rmsnorm()
1035
+ else:
1036
+ print("zhanshijin: use torch rmsnorm")
1037
+
1038
+ def get_input_embeddings(self):
1039
+ return self.embed_tokens
1040
+
1041
+ def set_input_embeddings(self, value):
1042
+ self.embed_tokens = value
1043
+
1044
+ @add_start_docstrings_to_model_forward(Steel_INPUTS_DOCSTRING)
1045
+ def forward(
1046
+ self,
1047
+ input_ids: torch.LongTensor = None,
1048
+ attention_mask: Optional[torch.Tensor] = None,
1049
+ position_ids: Optional[torch.LongTensor] = None,
1050
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1051
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1052
+ use_cache: Optional[bool] = None,
1053
+ output_attentions: Optional[bool] = None,
1054
+ output_hidden_states: Optional[bool] = None,
1055
+ return_dict: Optional[bool] = None,
1056
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1057
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1058
+ output_hidden_states = (
1059
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1060
+ )
1061
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1062
+
1063
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1064
+
1065
+ # retrieve input_ids and inputs_embeds
1066
+ if input_ids is not None and inputs_embeds is not None:
1067
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1068
+ elif input_ids is not None:
1069
+ batch_size, seq_length = input_ids.shape
1070
+ elif inputs_embeds is not None:
1071
+ batch_size, seq_length, _ = inputs_embeds.shape
1072
+ else:
1073
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
1074
+
1075
+ if self.gradient_checkpointing and self.training:
1076
+ if use_cache:
1077
+ logger.warning_once(
1078
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1079
+ )
1080
+ use_cache = False
1081
+
1082
+ past_key_values_length = 0
1083
+
1084
+ if use_cache:
1085
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1086
+ if use_legacy_cache:
1087
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1088
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1089
+
1090
+ if position_ids is None:
1091
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1092
+ position_ids = torch.arange(
1093
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1094
+ )
1095
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1096
+ else:
1097
+ position_ids = position_ids.view(-1, seq_length).long()
1098
+
1099
+ if inputs_embeds is None:
1100
+ inputs_embeds = self.embed_tokens(input_ids)
1101
+
1102
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1103
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1104
+ if is_padding_right:
1105
+ raise ValueError(
1106
+ "You are attempting to perform batched generation with padding_side='right'"
1107
+ " this may lead to unexpected behaviour for Flash Attention version of Steel. Make sure to "
1108
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1109
+ )
1110
+
1111
+ if self._attn_implementation == "flash_attention_2":
1112
+ # 2d mask is passed through the layers
1113
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1114
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1115
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1116
+ # the manual implementation that requires a 4D causal mask in all cases.
1117
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1118
+ attention_mask,
1119
+ (batch_size, seq_length),
1120
+ inputs_embeds,
1121
+ past_key_values_length,
1122
+ sliding_window=self.config.sliding_window,
1123
+ )
1124
+ else:
1125
+ # 4d mask is passed through the layers
1126
+ attention_mask = _prepare_4d_causal_attention_mask(
1127
+ attention_mask,
1128
+ (batch_size, seq_length),
1129
+ inputs_embeds,
1130
+ past_key_values_length,
1131
+ sliding_window=self.config.sliding_window,
1132
+ )
1133
+
1134
+ hidden_states = inputs_embeds
1135
+
1136
+ # decoder layers
1137
+ all_hidden_states = () if output_hidden_states else None
1138
+ all_self_attns = () if output_attentions else None
1139
+ next_decoder_cache = None
1140
+
1141
+ for decoder_layer in self.layers:
1142
+ if output_hidden_states:
1143
+ all_hidden_states += (hidden_states,)
1144
+
1145
+ if self.gradient_checkpointing and self.training:
1146
+ layer_outputs = self._gradient_checkpointing_func(
1147
+ decoder_layer.__call__,
1148
+ hidden_states,
1149
+ attention_mask,
1150
+ position_ids,
1151
+ past_key_values,
1152
+ output_attentions,
1153
+ use_cache,
1154
+ )
1155
+ else:
1156
+ layer_outputs = decoder_layer(
1157
+ hidden_states,
1158
+ attention_mask=attention_mask,
1159
+ position_ids=position_ids,
1160
+ past_key_value=past_key_values,
1161
+ output_attentions=output_attentions,
1162
+ use_cache=use_cache,
1163
+ )
1164
+
1165
+ hidden_states = layer_outputs[0]
1166
+
1167
+ if use_cache:
1168
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1169
+
1170
+ if output_attentions:
1171
+ all_self_attns += (layer_outputs[1],)
1172
+
1173
+ hidden_states = self.norm(hidden_states)
1174
+
1175
+ # add hidden states from the last decoder layer
1176
+ if output_hidden_states:
1177
+ all_hidden_states += (hidden_states,)
1178
+
1179
+ next_cache = None
1180
+ if use_cache:
1181
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1182
+
1183
+ if not return_dict:
1184
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1185
+ return BaseModelOutputWithPast(
1186
+ last_hidden_state=hidden_states,
1187
+ past_key_values=next_cache,
1188
+ hidden_states=all_hidden_states,
1189
+ attentions=all_self_attns,
1190
+ )
1191
+
1192
+
1193
+ class SteelForCausalLM(SteelPreTrainedModel):
1194
+ _tied_weights_keys = ["lm_head.weight"]
1195
+
1196
+ def __init__(self, config):
1197
+ super().__init__(config)
1198
+ self.model = SteelModel(config)
1199
+ self.vocab_size = config.vocab_size
1200
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1201
+
1202
+ # Initialize weights and apply final processing
1203
+ self.post_init()
1204
+
1205
+ def get_input_embeddings(self):
1206
+ return self.model.embed_tokens
1207
+
1208
+ def set_input_embeddings(self, value):
1209
+ self.model.embed_tokens = value
1210
+
1211
+ def get_output_embeddings(self):
1212
+ return self.lm_head
1213
+
1214
+ def set_output_embeddings(self, new_embeddings):
1215
+ self.lm_head = new_embeddings
1216
+
1217
+ def set_decoder(self, decoder):
1218
+ self.model = decoder
1219
+
1220
+ def get_decoder(self):
1221
+ return self.model
1222
+
1223
+ @add_start_docstrings_to_model_forward(Steel_INPUTS_DOCSTRING)
1224
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1225
+ def forward(
1226
+ self,
1227
+ input_ids: torch.LongTensor = None,
1228
+ attention_mask: Optional[torch.Tensor] = None,
1229
+ position_ids: Optional[torch.LongTensor] = None,
1230
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1231
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1232
+ labels: Optional[torch.LongTensor] = None,
1233
+ use_cache: Optional[bool] = None,
1234
+ output_attentions: Optional[bool] = None,
1235
+ output_hidden_states: Optional[bool] = None,
1236
+ return_dict: Optional[bool] = None,
1237
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1238
+ r"""
1239
+ Args:
1240
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1241
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1242
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1243
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1244
+
1245
+ Returns:
1246
+
1247
+ Example:
1248
+
1249
+ ```python
1250
+ >>> from transformers import AutoTokenizer, SteelForCausalLM
1251
+
1252
+ >>> model = SteelForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1253
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1254
+
1255
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1256
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1257
+
1258
+ >>> # Generate
1259
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1260
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1261
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1262
+ ```"""
1263
+
1264
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1265
+ output_hidden_states = (
1266
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1267
+ )
1268
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1269
+
1270
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1271
+ outputs = self.model(
1272
+ input_ids=input_ids,
1273
+ attention_mask=attention_mask,
1274
+ position_ids=position_ids,
1275
+ past_key_values=past_key_values,
1276
+ inputs_embeds=inputs_embeds,
1277
+ use_cache=use_cache,
1278
+ output_attentions=output_attentions,
1279
+ output_hidden_states=output_hidden_states,
1280
+ return_dict=return_dict,
1281
+ )
1282
+
1283
+ hidden_states = outputs[0]
1284
+ logits = self.lm_head(hidden_states)
1285
+ logits = logits.float()
1286
+
1287
+ loss = None
1288
+ if labels is not None:
1289
+ # Shift so that tokens < n predict n
1290
+ shift_logits = logits[..., :-1, :].contiguous()
1291
+ shift_labels = labels[..., 1:].contiguous()
1292
+ # Flatten the tokens
1293
+ loss_fct = CrossEntropyLoss()
1294
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1295
+ shift_labels = shift_labels.view(-1)
1296
+ # Enable model parallelism
1297
+ shift_labels = shift_labels.to(shift_logits.device)
1298
+ loss = loss_fct(shift_logits, shift_labels)
1299
+
1300
+ if not return_dict:
1301
+ output = (logits,) + outputs[1:]
1302
+ return (loss,) + output if loss is not None else output
1303
+
1304
+ return CausalLMOutputWithPast(
1305
+ loss=loss,
1306
+ logits=logits,
1307
+ past_key_values=outputs.past_key_values,
1308
+ hidden_states=outputs.hidden_states,
1309
+ attentions=outputs.attentions,
1310
+ )
1311
+
1312
+ def prepare_inputs_for_generation(
1313
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1314
+ ):
1315
+ # Omit tokens covered by past_key_values
1316
+ if past_key_values is not None:
1317
+ if isinstance(past_key_values, Cache):
1318
+ cache_length = past_key_values.get_seq_length()
1319
+ past_length = past_key_values.seen_tokens
1320
+ max_cache_length = past_key_values.get_max_length()
1321
+ else:
1322
+ cache_length = past_length = past_key_values[0][0].shape[2]
1323
+ max_cache_length = None
1324
+
1325
+ # Keep only the unprocessed tokens:
1326
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1327
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1328
+ # input)
1329
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1330
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1331
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1332
+ # input_ids based on the past_length.
1333
+ elif past_length < input_ids.shape[1]:
1334
+ input_ids = input_ids[:, past_length:]
1335
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1336
+
1337
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1338
+ if (
1339
+ max_cache_length is not None
1340
+ and attention_mask is not None
1341
+ and cache_length + input_ids.shape[1] > max_cache_length
1342
+ ):
1343
+ attention_mask = attention_mask[:, -max_cache_length:]
1344
+
1345
+ position_ids = kwargs.get("position_ids", None)
1346
+ if attention_mask is not None and position_ids is None:
1347
+ # create position_ids on the fly for batch generation
1348
+ position_ids = attention_mask.long().cumsum(-1) - 1
1349
+ position_ids.masked_fill_(attention_mask == 0, 1)
1350
+ if past_key_values:
1351
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1352
+
1353
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1354
+ if inputs_embeds is not None and past_key_values is None:
1355
+ model_inputs = {"inputs_embeds": inputs_embeds}
1356
+ else:
1357
+ model_inputs = {"input_ids": input_ids}
1358
+
1359
+ model_inputs.update(
1360
+ {
1361
+ "position_ids": position_ids,
1362
+ "past_key_values": past_key_values,
1363
+ "use_cache": kwargs.get("use_cache"),
1364
+ "attention_mask": attention_mask,
1365
+ }
1366
+ )
1367
+ return model_inputs
1368
+
1369
+ @staticmethod
1370
+ def _reorder_cache(past_key_values, beam_idx):
1371
+ reordered_past = ()
1372
+ for layer_past in past_key_values:
1373
+ reordered_past += (
1374
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1375
+ )
1376
+ return reordered_past
1377
+
1378
+
1379
+ @add_start_docstrings(
1380
+ """
1381
+ The Steel Model transformer with a sequence classification head on top (linear layer).
1382
+
1383
+ [`SteelForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1384
+ (e.g. GPT-2) do.
1385
+
1386
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1387
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1388
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1389
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1390
+ each row of the batch).
1391
+ """,
1392
+ Steel_START_DOCSTRING,
1393
+ )
1394
+ class SteelForSequenceClassification(SteelPreTrainedModel):
1395
+ def __init__(self, config):
1396
+ super().__init__(config)
1397
+ self.num_labels = config.num_labels
1398
+ self.model = SteelModel(config)
1399
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1400
+
1401
+ # Initialize weights and apply final processing
1402
+ self.post_init()
1403
+
1404
+ def get_input_embeddings(self):
1405
+ return self.model.embed_tokens
1406
+
1407
+ def set_input_embeddings(self, value):
1408
+ self.model.embed_tokens = value
1409
+
1410
+ @add_start_docstrings_to_model_forward(Steel_INPUTS_DOCSTRING)
1411
+ def forward(
1412
+ self,
1413
+ input_ids: torch.LongTensor = None,
1414
+ attention_mask: Optional[torch.Tensor] = None,
1415
+ position_ids: Optional[torch.LongTensor] = None,
1416
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1417
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1418
+ labels: Optional[torch.LongTensor] = None,
1419
+ use_cache: Optional[bool] = None,
1420
+ output_attentions: Optional[bool] = None,
1421
+ output_hidden_states: Optional[bool] = None,
1422
+ return_dict: Optional[bool] = None,
1423
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1424
+ r"""
1425
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1426
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1427
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1428
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1429
+ """
1430
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1431
+
1432
+ transformer_outputs = self.model(
1433
+ input_ids,
1434
+ attention_mask=attention_mask,
1435
+ position_ids=position_ids,
1436
+ past_key_values=past_key_values,
1437
+ inputs_embeds=inputs_embeds,
1438
+ use_cache=use_cache,
1439
+ output_attentions=output_attentions,
1440
+ output_hidden_states=output_hidden_states,
1441
+ return_dict=return_dict,
1442
+ )
1443
+ hidden_states = transformer_outputs[0]
1444
+ logits = self.score(hidden_states)
1445
+
1446
+ if input_ids is not None:
1447
+ batch_size = input_ids.shape[0]
1448
+ else:
1449
+ batch_size = inputs_embeds.shape[0]
1450
+
1451
+ if self.config.pad_token_id is None and batch_size != 1:
1452
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1453
+ if self.config.pad_token_id is None:
1454
+ sequence_lengths = -1
1455
+ else:
1456
+ if input_ids is not None:
1457
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1458
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1459
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1460
+ sequence_lengths = sequence_lengths.to(logits.device)
1461
+ else:
1462
+ sequence_lengths = -1
1463
+
1464
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1465
+
1466
+ loss = None
1467
+ if labels is not None:
1468
+ labels = labels.to(logits.device)
1469
+ if self.config.problem_type is None:
1470
+ if self.num_labels == 1:
1471
+ self.config.problem_type = "regression"
1472
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1473
+ self.config.problem_type = "single_label_classification"
1474
+ else:
1475
+ self.config.problem_type = "multi_label_classification"
1476
+
1477
+ if self.config.problem_type == "regression":
1478
+ loss_fct = MSELoss()
1479
+ if self.num_labels == 1:
1480
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1481
+ else:
1482
+ loss = loss_fct(pooled_logits, labels)
1483
+ elif self.config.problem_type == "single_label_classification":
1484
+ loss_fct = CrossEntropyLoss()
1485
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1486
+ elif self.config.problem_type == "multi_label_classification":
1487
+ loss_fct = BCEWithLogitsLoss()
1488
+ loss = loss_fct(pooled_logits, labels)
1489
+ if not return_dict:
1490
+ output = (pooled_logits,) + transformer_outputs[1:]
1491
+ return ((loss,) + output) if loss is not None else output
1492
+
1493
+ return SequenceClassifierOutputWithPast(
1494
+ loss=loss,
1495
+ logits=pooled_logits,
1496
+ past_key_values=transformer_outputs.past_key_values,
1497
+ hidden_states=transformer_outputs.hidden_states,
1498
+ attentions=transformer_outputs.attentions,
1499
+ )
steel-llm-step-720000-ckpt/softmoe_v3.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+
8
+ def softmax(x: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
9
+ """
10
+ Compute the softmax along the specified dimensions.
11
+ This function adds the option to specify multiple dimensions
12
+
13
+ Args:
14
+ x (torch.Tensor): Input tensor.
15
+ dims (int or tuple[int]): The dimension or list of dimensions along which the softmax probabilities are computed.
16
+
17
+ Returns:
18
+ torch.Tensor: Output tensor containing softmax probabilities along the specified dimensions.
19
+ """
20
+ dtype = x.dtype
21
+ x = x.to(torch.float32)
22
+ max_vals = torch.amax(x, dim=dim, keepdim=True)
23
+ e_x = torch.exp(x - max_vals)
24
+ sum_exp = e_x.sum(dim=dim, keepdim=True)
25
+ return (e_x / sum_exp).to(dtype)
26
+
27
+ # copy from https://github.com/bwconrad/soft-moe
28
+ class SteelSoftMoEV3(nn.Module):
29
+ """
30
+ A wrapper class to create a Soft Mixture of Experts layer.
31
+
32
+ From "From Sparse to Soft Mixtures of Experts"
33
+ https://arxiv.org/pdf/2308.00951.pdf
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ config,
39
+ layer: Callable,
40
+ ) -> None:
41
+ """
42
+ Args:
43
+ dim (int): Dimensionality of input features.
44
+ num_experts (int): Number of experts.
45
+ slots_per_expert (int): Number of token slots per expert.
46
+ layer (Callable): Network layer of the experts.
47
+ normalize (bool): Normalize input and phi (sec. 2.3 from paper)
48
+ **layer_kwargs: Additional keyword arguments for the layer class.
49
+ """
50
+ super().__init__()
51
+
52
+ self.dim = config.hidden_size
53
+ self.num_experts = config.n_experts
54
+ self.slots_per_expert = config.slots_per_expert if hasattr(config, "slots_per_expert") else 1
55
+ self.normalize = True
56
+
57
+ # Initialize phi and normalization scaling factor
58
+ self.phi = nn.Parameter(torch.zeros(self.dim, self.num_experts, self.slots_per_expert))
59
+ if self.normalize:
60
+ self.scale = nn.Parameter(torch.ones(1))
61
+
62
+ # Initialize phi using LeCun normal initialization
63
+ # https://github.com/google-research/vmoe/blob/662341d007650d5bbb7c6a2bef7f3c759a20cc7e/vmoe/projects/soft_moe/router.py#L49C1-L49C1
64
+ nn.init.normal_(self.phi, mean=0, std=1 / self.dim**0.5)
65
+
66
+ # Create a list of expert networks
67
+ self.experts = nn.ModuleList(
68
+ [layer(config) for _ in range(self.num_experts)]
69
+ )
70
+
71
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
72
+ """
73
+ Forward pass through the Soft-MoE layer (algorithm 1 from paper).
74
+
75
+ Args:
76
+ x (torch.Tensor): Input tensor of shape [batch_size, seq_len, input_dim].
77
+
78
+ Returns:
79
+ torch.Tensor: Output tensor of shape [batch_size, seq_len, input_dim].
80
+ """
81
+ assert (
82
+ x.shape[-1] == self.dim
83
+ ), f"Input feature dim of {x.shape[-1]} does not match layer dim of {self.dim}"
84
+ assert (
85
+ len(x.shape) == 3
86
+ ), f"Input expected to have 3 dimensions but has {len(x.shape)}"
87
+
88
+ phi = self.phi
89
+
90
+ # Normalize input and phi
91
+ if self.normalize:
92
+ x = F.normalize(x, dim=2) # [b, m, d]
93
+ phi = self.scale * F.normalize(phi, dim=0) # [d, n, p]
94
+
95
+ # Compute dispatch and combine weights
96
+ logits = torch.einsum("bmd,dnp->bmnp", x, phi)
97
+ d = softmax(logits, dim=1)
98
+ c = softmax(logits, dim=(2, 3))
99
+ # tmp = c[0,:,:,0].reshape([c.shape[1],-1])
100
+ # print("num:",tmp, "shape:",tmp.shape, "sum:",tmp.sum(dim=1))
101
+ # Compute input slots as weighted average of input tokens using dispatch weights
102
+ xs = torch.einsum("bmd,bmnp->bnpd", x, d)
103
+
104
+ # Apply expert to corresponding slots
105
+ ys = torch.stack(
106
+ [f_i(xs[:, i, :, :]) for i, f_i in enumerate(self.experts)], dim=1
107
+ )
108
+
109
+ # Compute output tokens as weighted average of output slots using combine weights
110
+ y = torch.einsum("bnpd,bmnp->bmd", ys, c)
111
+
112
+ return y
steel-llm-step-720000-ckpt/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
steel-llm-step-720000-ckpt/tokenizer_config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": ["<|im_start|>", "<|im_end|>"],
30
+ "bos_token": null,
31
+ "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 %}",
32
+ "clean_up_tokenization_spaces": false,
33
+ "eos_token": "<|im_end|>",
34
+ "errors": "replace",
35
+ "model_max_length": 32768,
36
+ "pad_token": "<|endoftext|>",
37
+ "split_special_tokens": false,
38
+ "tokenizer_class": "Qwen2Tokenizer",
39
+ "unk_token": null
40
+ }
41
+
steel-llm-step-720000-ckpt/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
steel-llm-step-980000-ckpt/config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "FFN_type": "softmoe_v3",
3
+ "_name_or_path": "./steel_modify_from_qwen_1_5",
4
+ "architectures": [
5
+ "SteelForCausalLM"
6
+ ],
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_steel.SteelConfig",
10
+ "AutoModelForCausalLM": "modeling_steel.SteelForCausalLM"
11
+ },
12
+ "bos_token_id": 151643,
13
+ "eos_token_id": 151645,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 1792,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 1792,
18
+ "max_position_embeddings": 32768,
19
+ "max_window_layers": 21,
20
+ "mlp_div_ratio": 4,
21
+ "mlp_type": "senet",
22
+ "model_type": "qwen2",
23
+ "n_experts": 6,
24
+ "num_attention_heads": 32,
25
+ "num_hidden_layers": 18,
26
+ "num_key_value_heads": 32,
27
+ "rms_norm_eps": 1e-06,
28
+ "rope_theta": 1000000.0,
29
+ "sliding_window": 32768,
30
+ "slots_per_expert": 1,
31
+ "tie_word_embeddings": false,
32
+ "torch_dtype": "float32",
33
+ "transformers_version": "4.41.1",
34
+ "use_cache": true,
35
+ "use_sliding_window": false,
36
+ "vocab_size": 151936
37
+ }
steel-llm-step-980000-ckpt/configuration_steel.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 zhanshijin and lishu. All rights reserved.
3
+ #
4
+ # This project copy from qwen1.5
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ Steel model configuration"""
17
+
18
+ from transformers.configuration_utils import PretrainedConfig
19
+ from transformers.utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+
26
+
27
+ class SteelConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`Qwen2Model`]. It is used to instantiate a
30
+ Qwen2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
31
+ with the defaults will yield a similar configuration to that of
32
+ Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PretrainedConfig`] for more information.
36
+
37
+
38
+ Args:
39
+ vocab_size (`int`, *optional*, defaults to 151936):
40
+ Vocabulary size of the Qwen2 model. Defines the number of different tokens that can be represented by the
41
+ `inputs_ids` passed when calling [`Qwen2Model`]
42
+ hidden_size (`int`, *optional*, defaults to 4096):
43
+ Dimension of the hidden representations.
44
+ intermediate_size (`int`, *optional*, defaults to 22016):
45
+ Dimension of the MLP representations.
46
+ num_hidden_layers (`int`, *optional*, defaults to 32):
47
+ Number of hidden layers in the Transformer encoder.
48
+ num_attention_heads (`int`, *optional*, defaults to 32):
49
+ Number of attention heads for each attention layer in the Transformer encoder.
50
+ num_key_value_heads (`int`, *optional*, defaults to 32):
51
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
52
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
53
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
54
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
55
+ by meanpooling all the original heads within that group. For more details checkout [this
56
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
57
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
58
+ The non-linear activation function (function or string) in the decoder.
59
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
60
+ The maximum sequence length that this model might ever be used with.
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
64
+ The epsilon used by the rms normalization layers.
65
+ use_cache (`bool`, *optional*, defaults to `True`):
66
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
67
+ relevant if `config.is_decoder=True`.
68
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
69
+ Whether the model's input and output word embeddings should be tied.
70
+ rope_theta (`float`, *optional*, defaults to 10000.0):
71
+ The base period of the RoPE embeddings.
72
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
73
+ Whether to use sliding window attention.
74
+ sliding_window (`int`, *optional*, defaults to 4096):
75
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
76
+ max_window_layers (`int`, *optional*, defaults to 28):
77
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
78
+ attention_dropout (`float`, *optional*, defaults to 0.0):
79
+ The dropout ratio for the attention probabilities.
80
+ """
81
+
82
+ model_type = "qwen2"
83
+ keys_to_ignore_at_inference = ["past_key_values"]
84
+
85
+ def __init__(
86
+ self,
87
+ vocab_size=151936,
88
+ hidden_size=4096,
89
+ intermediate_size=22016,
90
+ num_hidden_layers=32,
91
+ num_attention_heads=32,
92
+ num_key_value_heads=32,
93
+ hidden_act="silu",
94
+ max_position_embeddings=32768,
95
+ initializer_range=0.02,
96
+ rms_norm_eps=1e-6,
97
+ use_cache=True,
98
+ tie_word_embeddings=False,
99
+ rope_theta=10000.0,
100
+ use_sliding_window=False,
101
+ sliding_window=4096,
102
+ max_window_layers=28,
103
+ attention_dropout=0.0,
104
+ **kwargs,
105
+ ):
106
+ self.vocab_size = vocab_size
107
+ self.max_position_embeddings = max_position_embeddings
108
+ self.hidden_size = hidden_size
109
+ self.intermediate_size = intermediate_size
110
+ self.num_hidden_layers = num_hidden_layers
111
+ self.num_attention_heads = num_attention_heads
112
+ self.use_sliding_window = use_sliding_window
113
+ self.sliding_window = sliding_window
114
+ self.max_window_layers = max_window_layers
115
+
116
+ # for backward compatibility
117
+ if num_key_value_heads is None:
118
+ num_key_value_heads = num_attention_heads
119
+
120
+ self.num_key_value_heads = num_key_value_heads
121
+ self.hidden_act = hidden_act
122
+ self.initializer_range = initializer_range
123
+ self.rms_norm_eps = rms_norm_eps
124
+ self.use_cache = use_cache
125
+ self.rope_theta = rope_theta
126
+ self.attention_dropout = attention_dropout
127
+
128
+ super().__init__(
129
+ tie_word_embeddings=tie_word_embeddings,
130
+ **kwargs,
131
+ )
steel-llm-step-980000-ckpt/generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 151643,
4
+ "eos_token_id": 151645,
5
+ "transformers_version": "4.41.1"
6
+ }
steel-llm-step-980000-ckpt/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
steel-llm-step-980000-ckpt/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a637c4440b49f410ecd3006e585146e44f0d6c124973383628c4618f56c24fe8
3
+ size 4491766872
steel-llm-step-980000-ckpt/modeling_steel.py ADDED
@@ -0,0 +1,1499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The zhanshijin and lishu. All rights reserved.
3
+ #
4
+ #
5
+ #This model copy from qwen1.5.
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+ """ PyTorch Steel model."""
19
+ import inspect
20
+ import math
21
+ import warnings
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.nn.functional as F
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+
30
+ from transformers.activations import ACT2FN
31
+ from transformers.cache_utils import Cache, DynamicCache
32
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
33
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
34
+ from transformers.modeling_utils import PreTrainedModel
35
+ from transformers.utils import (
36
+ add_start_docstrings,
37
+ add_start_docstrings_to_model_forward,
38
+ is_flash_attn_2_available,
39
+ is_flash_attn_greater_or_equal_2_10,
40
+ logging,
41
+ replace_return_docstrings,
42
+ )
43
+ from configuration_steel import SteelConfig
44
+ from softmoe_v3 import SteelSoftMoEV3
45
+
46
+ if is_flash_attn_2_available():
47
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
48
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
49
+
50
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
51
+ print("zhanshijin: surrport flash_attn_2")
52
+ print(f"zhanshijin: if flash attn surrport window:{_flash_supports_window_size}")
53
+ else:
54
+ print("zhanshijin: not surrport flash_attn_2")
55
+
56
+ logger = logging.get_logger(__name__)
57
+
58
+ rms_norm = None
59
+ def _import_cuda_rmsnorm():
60
+ global rms_norm
61
+ try:
62
+ from flash_attn.ops.rms_norm import rms_norm as __rms_norm
63
+ rms_norm = __rms_norm
64
+ print("zhanshijin: success import cuda __rms_norm")
65
+ except ImportError:
66
+ logger.warn(
67
+ "Warning: import flash_attn rms_norm fail, please install FlashAttention layer_norm to get higher efficiency "
68
+ "https://github.com/Dao-AILab/flash-attention/tree/main/csrc/layer_norm"
69
+ )
70
+
71
+ _CONFIG_FOR_DOC = "SteelConfig"
72
+
73
+
74
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
75
+ def _get_unpad_data(attention_mask):
76
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
77
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
78
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
79
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
80
+ return (
81
+ indices,
82
+ cu_seqlens,
83
+ max_seqlen_in_batch,
84
+ )
85
+
86
+
87
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Steel
88
+ class SteelRMSNorm(nn.Module):
89
+ def __init__(self, hidden_size, eps=1e-6):
90
+ """
91
+ SteelRMSNorm is equivalent to T5LayerNorm
92
+ """
93
+ super().__init__()
94
+ self.weight = nn.Parameter(torch.ones(hidden_size))
95
+ self.variance_epsilon = eps
96
+
97
+ def forward(self, hidden_states):
98
+ if rms_norm is not None and hidden_states.is_cuda:
99
+ return rms_norm(hidden_states, self.weight, self.variance_epsilon)
100
+ else:
101
+ input_dtype = hidden_states.dtype
102
+ hidden_states = hidden_states.to(torch.float32)
103
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
104
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
105
+ # test precision consistency
106
+ # from flash_attn.ops.rms_norm import rms_norm as _rms_norm
107
+ # print(_rms_norm(hidden_states, self.weight, self.variance_epsilon)[0,0,:10])
108
+ # print((self.weight * hidden_states.to(input_dtype))[0,0,:10])
109
+ return self.weight * hidden_states.to(input_dtype)
110
+
111
+
112
+ # Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Steel
113
+ class SteelRotaryEmbedding(nn.Module):
114
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
115
+ super().__init__()
116
+
117
+ self.dim = dim
118
+ self.max_position_embeddings = max_position_embeddings
119
+ self.base = base
120
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
121
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
122
+
123
+ # Build here to make `torch.jit.trace` work.
124
+ self._set_cos_sin_cache(
125
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
126
+ )
127
+
128
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
129
+ self.max_seq_len_cached = seq_len
130
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
131
+
132
+ freqs = torch.outer(t, self.inv_freq)
133
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
134
+ emb = torch.cat((freqs, freqs), dim=-1)
135
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
136
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
137
+
138
+ def forward(self, x, seq_len=None):
139
+ # x: [bs, num_attention_heads, seq_len, head_size]
140
+ if seq_len > self.max_seq_len_cached:
141
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
142
+
143
+ return (
144
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
145
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
146
+ )
147
+
148
+
149
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
150
+ def rotate_half(x):
151
+ """Rotates half the hidden dims of the input."""
152
+ x1 = x[..., : x.shape[-1] // 2]
153
+ x2 = x[..., x.shape[-1] // 2 :]
154
+ return torch.cat((-x2, x1), dim=-1)
155
+
156
+
157
+ # Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
158
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
159
+ """Applies Rotary Position Embedding to the query and key tensors.
160
+
161
+ Args:
162
+ q (`torch.Tensor`): The query tensor.
163
+ k (`torch.Tensor`): The key tensor.
164
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
165
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
166
+ position_ids (`torch.Tensor`):
167
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
168
+ used to pass offsetted position ids when working with a KV-cache.
169
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
170
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
171
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
172
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
173
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
174
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
175
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
176
+ Returns:
177
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
178
+ """
179
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
180
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
181
+ q_embed = (q * cos) + (rotate_half(q) * sin)
182
+ k_embed = (k * cos) + (rotate_half(k) * sin)
183
+ return q_embed, k_embed
184
+
185
+
186
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Steel->Steel
187
+ class SteelMLP(nn.Module):
188
+ def __init__(self, config):
189
+ super().__init__()
190
+ self.config = config
191
+ self.hidden_size = config.hidden_size
192
+ self.intermediate_size = config.intermediate_size //config.mlp_div_ratio
193
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
194
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
195
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
196
+ self.act_fn = ACT2FN[config.hidden_act]
197
+
198
+ def forward(self, x):
199
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
200
+
201
+ class SteelSENet(nn.Module):
202
+ def __init__(self, config):
203
+ super().__init__()
204
+ self.config = config
205
+ self.hidden_size = config.hidden_size
206
+ self.intermediate_size = config.intermediate_size //config.mlp_div_ratio
207
+ self.gate_up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
208
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
209
+ self.gate_down_proj = nn.Linear(self.intermediate_size,self.hidden_size, bias=False)
210
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
211
+ self.act_fn1 = ACT2FN[config.hidden_act]
212
+ self.act_fn2 = ACT2FN[config.hidden_act]
213
+
214
+ def forward(self, x):
215
+ x = self.act_fn1(self.gate_up_proj(x)) * self.up_proj(x)
216
+ return self.act_fn2(self.gate_down_proj(x)) * self.down_proj(x)
217
+
218
+
219
+ class SteelSoftMoeV1(nn.Module):
220
+ def __init__(self, config, layer=None):
221
+ super().__init__()
222
+ self.config = config
223
+ self.experts = nn.ModuleList([layer(config) for _ in range(config.n_experts)])
224
+ self.gating = nn.Linear(config.hidden_size, config.n_experts)
225
+ def forward(self, x):
226
+ weights = self.gating(x)
227
+ weights = nn.functional.softmax(weights, dim=-1, dtype=torch.float32).to(x.dtype)
228
+ outputs = torch.stack(
229
+ [expert(x) for expert in self.experts], dim=2)
230
+ weights = weights.unsqueeze(-1)
231
+ return torch.sum(outputs * weights, dim=2)
232
+
233
+ class SteelSoftMoeV2(nn.Module):
234
+ def __init__(self, config, layer):
235
+ super().__init__()
236
+ self.config = config
237
+ self.experts = nn.ModuleList([layer(config) for _ in range(config.n_experts)])
238
+ self.score = nn.Parameter(torch.randn(config.hidden_size, config.n_experts * config.slots_per_expert))
239
+
240
+ def forward(self, x):
241
+ logits = torch.matmul(x, self.score) # (batch_size, seq_len, slots)
242
+ dispatch_weights = F.softmax(logits, dim=-1,dtype=torch.float32).to(x.dtype)
243
+ combine_weights = F.softmax(logits, dim=1,dtype=torch.float32).to(x.dtype)
244
+ xs = torch.bmm(dispatch_weights.transpose(1, 2), x)
245
+ ys = torch.cat(
246
+ [expert(xs[:, i * self.config.slots_per_expert : (i + 1) * self.config.slots_per_expert, :])
247
+ for i, expert in enumerate(self.experts)],
248
+ dim=1
249
+ )
250
+ y = torch.bmm(combine_weights, ys)
251
+ return y
252
+
253
+
254
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
255
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
256
+ """
257
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
258
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
259
+ """
260
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
261
+ if n_rep == 1:
262
+ return hidden_states
263
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
264
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
265
+
266
+
267
+ class SteelAttention(nn.Module):
268
+ """
269
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
270
+ and "Generating Long Sequences with Sparse Transformers".
271
+ """
272
+
273
+ def __init__(self, config: SteelConfig, layer_idx: Optional[int] = None):
274
+ super().__init__()
275
+ self.config = config
276
+ self.layer_idx = layer_idx
277
+ if layer_idx is None:
278
+ logger.warning_once(
279
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
280
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
281
+ "when creating this class."
282
+ )
283
+
284
+ self.hidden_size = config.hidden_size
285
+ self.num_heads = config.num_attention_heads
286
+ self.head_dim = self.hidden_size // self.num_heads
287
+ self.num_key_value_heads = config.num_key_value_heads
288
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
289
+ self.max_position_embeddings = config.max_position_embeddings
290
+ self.rope_theta = config.rope_theta
291
+ self.is_causal = True
292
+ self.attention_dropout = config.attention_dropout
293
+
294
+ if (self.head_dim * self.num_heads) != self.hidden_size:
295
+ raise ValueError(
296
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
297
+ f" and `num_heads`: {self.num_heads})."
298
+ )
299
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
300
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
301
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
302
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
303
+
304
+ self.rotary_emb = SteelRotaryEmbedding(
305
+ self.head_dim,
306
+ max_position_embeddings=self.max_position_embeddings,
307
+ base=self.rope_theta,
308
+ )
309
+
310
+ def forward(
311
+ self,
312
+ hidden_states: torch.Tensor,
313
+ attention_mask: Optional[torch.Tensor] = None,
314
+ position_ids: Optional[torch.LongTensor] = None,
315
+ past_key_value: Optional[Cache] = None,
316
+ output_attentions: bool = False,
317
+ use_cache: bool = False,
318
+ **kwargs,
319
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
320
+ if "padding_mask" in kwargs:
321
+ warnings.warn(
322
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
323
+ )
324
+ bsz, q_len, _ = hidden_states.size()
325
+
326
+ query_states = self.q_proj(hidden_states)
327
+ key_states = self.k_proj(hidden_states)
328
+ value_states = self.v_proj(hidden_states)
329
+
330
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
331
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
332
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
333
+
334
+ kv_seq_len = key_states.shape[-2]
335
+ if past_key_value is not None:
336
+ if self.layer_idx is None:
337
+ raise ValueError(
338
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
339
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
340
+ "with a layer index."
341
+ )
342
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
343
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
344
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
345
+
346
+
347
+ if past_key_value is not None:
348
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
349
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
350
+
351
+ # repeat k/v heads if n_kv_heads < n_heads
352
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
353
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
354
+
355
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
356
+
357
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
358
+ raise ValueError(
359
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
360
+ f" {attn_weights.size()}"
361
+ )
362
+
363
+ if attention_mask is not None:
364
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
365
+ raise ValueError(
366
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
367
+ )
368
+
369
+ attn_weights = attn_weights + attention_mask
370
+
371
+ # upcast attention to fp32
372
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
373
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
374
+ attn_output = torch.matmul(attn_weights, value_states)
375
+
376
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
377
+ raise ValueError(
378
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
379
+ f" {attn_output.size()}"
380
+ )
381
+
382
+ attn_output = attn_output.transpose(1, 2).contiguous()
383
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
384
+
385
+ attn_output = self.o_proj(attn_output)
386
+
387
+ if not output_attentions:
388
+ attn_weights = None
389
+
390
+ return attn_output, attn_weights, past_key_value
391
+
392
+
393
+ class SteelFlashAttention2(SteelAttention):
394
+ """
395
+ Steel flash attention module, following Steel attention module. This module inherits from `SteelAttention`
396
+ as the weights of the module stays untouched. The only required change would be on the forward pass
397
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
398
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
399
+ config.max_window_layers layers.
400
+ """
401
+
402
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
403
+ def __init__(self, *args, **kwargs):
404
+ super().__init__(*args, **kwargs)
405
+
406
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
407
+ # 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.
408
+ # 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).
409
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
410
+
411
+ def forward(
412
+ self,
413
+ hidden_states: torch.Tensor,
414
+ attention_mask: Optional[torch.Tensor] = None,
415
+ position_ids: Optional[torch.LongTensor] = None,
416
+ past_key_value: Optional[Cache] = None,
417
+ output_attentions: bool = False,
418
+ use_cache: bool = False,
419
+ **kwargs,
420
+ ):
421
+ if "padding_mask" in kwargs:
422
+ warnings.warn(
423
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
424
+ )
425
+
426
+ # overwrite attention_mask with padding_mask
427
+ attention_mask = kwargs.pop("padding_mask")
428
+ bsz, q_len, _ = hidden_states.size()
429
+
430
+ query_states = self.q_proj(hidden_states)
431
+ key_states = self.k_proj(hidden_states)
432
+ value_states = self.v_proj(hidden_states)
433
+
434
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
435
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
436
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
437
+
438
+ kv_seq_len = key_states.shape[-2]
439
+ if past_key_value is not None:
440
+ if self.layer_idx is None:
441
+ raise ValueError(
442
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
443
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
444
+ "with a layer index."
445
+ )
446
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
447
+
448
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
449
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
450
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
451
+
452
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
453
+
454
+ use_sliding_windows = (
455
+ _flash_supports_window_size
456
+ and getattr(self.config, "sliding_window", None) is not None
457
+ and kv_seq_len > self.config.sliding_window
458
+ and self.config.use_sliding_window
459
+ )
460
+
461
+ if not _flash_supports_window_size:
462
+ logger.warning_once(
463
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
464
+ " make sure to upgrade flash-attn library."
465
+ )
466
+
467
+ if past_key_value is not None:
468
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
469
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
470
+ if (
471
+ getattr(self.config, "sliding_window", None) is not None
472
+ and kv_seq_len > self.config.sliding_window
473
+ and cache_has_contents
474
+ ):
475
+ slicing_tokens = 1 - self.config.sliding_window
476
+
477
+ past_key = past_key_value[self.layer_idx][0]
478
+ past_value = past_key_value[self.layer_idx][1]
479
+
480
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
481
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
482
+
483
+ if past_key.shape[-2] != self.config.sliding_window - 1:
484
+ raise ValueError(
485
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
486
+ f" {past_key.shape}"
487
+ )
488
+
489
+ if attention_mask is not None:
490
+ attention_mask = attention_mask[:, slicing_tokens:]
491
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
492
+
493
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
494
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
495
+
496
+ # repeat k/v heads if n_kv_heads < n_heads
497
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
498
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
499
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
500
+
501
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
502
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
503
+ # cast them back in float16 just to be sure everything works as expected.
504
+ input_dtype = query_states.dtype
505
+ if input_dtype == torch.float32:
506
+ if torch.is_autocast_enabled():
507
+ target_dtype = torch.get_autocast_gpu_dtype()
508
+ # Handle the case where the model is quantized
509
+ elif hasattr(self.config, "_pre_quantization_dtype"):
510
+ target_dtype = self.config._pre_quantization_dtype
511
+ else:
512
+ target_dtype = self.q_proj.weight.dtype
513
+
514
+ logger.warning_once(
515
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
516
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
517
+ f" {target_dtype}."
518
+ )
519
+
520
+ query_states = query_states.to(target_dtype)
521
+ key_states = key_states.to(target_dtype)
522
+ value_states = value_states.to(target_dtype)
523
+
524
+ # Reashape to the expected shape for Flash Attention
525
+ query_states = query_states.transpose(1, 2)
526
+ key_states = key_states.transpose(1, 2)
527
+ value_states = value_states.transpose(1, 2)
528
+
529
+ attn_output = self._flash_attention_forward(
530
+ query_states,
531
+ key_states,
532
+ value_states,
533
+ attention_mask,
534
+ q_len,
535
+ dropout=dropout_rate,
536
+ use_sliding_windows=use_sliding_windows,
537
+ )
538
+
539
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
540
+ attn_output = self.o_proj(attn_output)
541
+
542
+ if not output_attentions:
543
+ attn_weights = None
544
+
545
+ return attn_output, attn_weights, past_key_value
546
+
547
+ def _flash_attention_forward(
548
+ self,
549
+ query_states,
550
+ key_states,
551
+ value_states,
552
+ attention_mask,
553
+ query_length,
554
+ dropout=0.0,
555
+ softmax_scale=None,
556
+ use_sliding_windows=False,
557
+ ):
558
+ """
559
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
560
+ first unpad the input, then computes the attention scores and pad the final attention scores.
561
+
562
+ Args:
563
+ query_states (`torch.Tensor`):
564
+ Input query states to be passed to Flash Attention API
565
+ key_states (`torch.Tensor`):
566
+ Input key states to be passed to Flash Attention API
567
+ value_states (`torch.Tensor`):
568
+ Input value states to be passed to Flash Attention API
569
+ attention_mask (`torch.Tensor`):
570
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
571
+ position of padding tokens and 1 for the position of non-padding tokens.
572
+ dropout (`float`):
573
+ Attention dropout
574
+ softmax_scale (`float`, *optional*):
575
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
576
+ use_sliding_windows (`bool`, *optional*):
577
+ Whether to activate sliding window attention.
578
+ """
579
+ if not self._flash_attn_uses_top_left_mask:
580
+ causal = self.is_causal
581
+ else:
582
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
583
+ causal = self.is_causal and query_length != 1
584
+
585
+ # Decide whether to use SWA or not by layer index.
586
+ if use_sliding_windows and self.layer_idx >= self.config.max_window_layers:
587
+ use_sliding_windows = False
588
+
589
+ # Contains at least one padding token in the sequence
590
+ if attention_mask is not None:
591
+ batch_size = query_states.shape[0]
592
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
593
+ query_states, key_states, value_states, attention_mask, query_length
594
+ )
595
+
596
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
597
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
598
+
599
+ if not use_sliding_windows:
600
+ attn_output_unpad = flash_attn_varlen_func(
601
+ query_states,
602
+ key_states,
603
+ value_states,
604
+ cu_seqlens_q=cu_seqlens_q,
605
+ cu_seqlens_k=cu_seqlens_k,
606
+ max_seqlen_q=max_seqlen_in_batch_q,
607
+ max_seqlen_k=max_seqlen_in_batch_k,
608
+ dropout_p=dropout,
609
+ softmax_scale=softmax_scale,
610
+ causal=causal,
611
+ )
612
+ else:
613
+ attn_output_unpad = flash_attn_varlen_func(
614
+ query_states,
615
+ key_states,
616
+ value_states,
617
+ cu_seqlens_q=cu_seqlens_q,
618
+ cu_seqlens_k=cu_seqlens_k,
619
+ max_seqlen_q=max_seqlen_in_batch_q,
620
+ max_seqlen_k=max_seqlen_in_batch_k,
621
+ dropout_p=dropout,
622
+ softmax_scale=softmax_scale,
623
+ causal=causal,
624
+ window_size=(self.config.sliding_window, self.config.sliding_window),
625
+ )
626
+
627
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
628
+ else:
629
+ if not use_sliding_windows:
630
+ attn_output = flash_attn_func(
631
+ query_states,
632
+ key_states,
633
+ value_states,
634
+ dropout,
635
+ softmax_scale=softmax_scale,
636
+ causal=causal,
637
+ )
638
+ else:
639
+ attn_output = flash_attn_func(
640
+ query_states,
641
+ key_states,
642
+ value_states,
643
+ dropout,
644
+ softmax_scale=softmax_scale,
645
+ causal=causal,
646
+ window_size=(self.config.sliding_window, self.config.sliding_window),
647
+ )
648
+
649
+ return attn_output
650
+
651
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
652
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
653
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
654
+
655
+ # On the first iteration we need to properly re-create the padding mask
656
+ # by slicing it on the proper place
657
+ if kv_seq_len != attention_mask.shape[-1]:
658
+ attention_mask_num_tokens = attention_mask.shape[-1]
659
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
660
+
661
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
662
+
663
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
664
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
665
+
666
+ if query_length == kv_seq_len:
667
+ query_layer = index_first_axis(
668
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
669
+ )
670
+ cu_seqlens_q = cu_seqlens_k
671
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
672
+ indices_q = indices_k
673
+ elif query_length == 1:
674
+ max_seqlen_in_batch_q = 1
675
+ cu_seqlens_q = torch.arange(
676
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
677
+ ) # There is a memcpy here, that is very bad.
678
+ indices_q = cu_seqlens_q[:-1]
679
+ query_layer = query_layer.squeeze(1)
680
+ else:
681
+ # The -q_len: slice assumes left padding.
682
+ attention_mask = attention_mask[:, -query_length:]
683
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
684
+
685
+ return (
686
+ query_layer,
687
+ key_layer,
688
+ value_layer,
689
+ indices_q,
690
+ (cu_seqlens_q, cu_seqlens_k),
691
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
692
+ )
693
+
694
+
695
+ # Copied from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Steel
696
+ class SteelSdpaAttention(SteelAttention):
697
+ """
698
+ Steel attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
699
+ `SteelAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
700
+ SDPA API.
701
+ """
702
+
703
+ # Adapted from SteelAttention.forward
704
+ def forward(
705
+ self,
706
+ hidden_states: torch.Tensor,
707
+ attention_mask: Optional[torch.Tensor] = None,
708
+ position_ids: Optional[torch.LongTensor] = None,
709
+ past_key_value: Optional[Cache] = None,
710
+ output_attentions: bool = False,
711
+ use_cache: bool = False,
712
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
713
+ if output_attentions:
714
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
715
+ logger.warning_once(
716
+ "SteelModel is using SteelSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
717
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
718
+ )
719
+ return super().forward(
720
+ hidden_states=hidden_states,
721
+ attention_mask=attention_mask,
722
+ position_ids=position_ids,
723
+ past_key_value=past_key_value,
724
+ output_attentions=output_attentions,
725
+ use_cache=use_cache,
726
+ )
727
+
728
+ bsz, q_len, _ = hidden_states.size()
729
+
730
+ query_states = self.q_proj(hidden_states)
731
+ key_states = self.k_proj(hidden_states)
732
+ value_states = self.v_proj(hidden_states)
733
+
734
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
735
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
736
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
737
+
738
+ kv_seq_len = key_states.shape[-2]
739
+ if past_key_value is not None:
740
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
741
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
742
+
743
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
744
+
745
+ if past_key_value is not None:
746
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
747
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
748
+
749
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
750
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
751
+
752
+ if attention_mask is not None:
753
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
754
+ raise ValueError(
755
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
756
+ )
757
+
758
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
759
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
760
+ if query_states.device.type == "cuda" and attention_mask is not None:
761
+ query_states = query_states.contiguous()
762
+ key_states = key_states.contiguous()
763
+ value_states = value_states.contiguous()
764
+
765
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
766
+ query_states,
767
+ key_states,
768
+ value_states,
769
+ attn_mask=attention_mask,
770
+ dropout_p=self.attention_dropout if self.training else 0.0,
771
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
772
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
773
+ )
774
+
775
+ attn_output = attn_output.transpose(1, 2).contiguous()
776
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
777
+
778
+ attn_output = self.o_proj(attn_output)
779
+
780
+ return attn_output, None, past_key_value
781
+
782
+
783
+ Steel_ATTENTION_CLASSES = {
784
+ "eager": SteelAttention,
785
+ "flash_attention_2": SteelFlashAttention2,
786
+ "sdpa": SteelSdpaAttention,
787
+ }
788
+
789
+
790
+ class SteelDecoderLayer(nn.Module):
791
+ def __init__(self, config: SteelConfig, layer_idx: int):
792
+ super().__init__()
793
+ self.hidden_size = config.hidden_size
794
+
795
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
796
+ logger.warning_once(
797
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
798
+ "unexpected results may be encountered."
799
+ )
800
+ self.self_attn = Steel_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
801
+ if config.mlp_type == "raw":
802
+ mlp_class = SteelMLP
803
+ logger.warning_once(f"mlp_class: SteelMLP")
804
+ elif config.mlp_type == "senet":
805
+ mlp_class = SteelSENet
806
+ logger.warning_once(f"mlp_class: SteelSENet")
807
+ else:
808
+ raise NameError(f"No this mlp type: {config.mlp_type}")
809
+
810
+ if config.FFN_type == "raw":
811
+ self.mlp = mlp_class(config)
812
+ logger.warning_once(f"FFN: {mlp_class}")
813
+ elif config.FFN_type == "softmoe_v1":
814
+ self.mlp = SteelSoftMoeV1(config, layer=mlp_class)
815
+ logger.warning_once(f"FFN: SteelSoftMoeV1")
816
+ elif config.FFN_type == "softmoe_v2":
817
+ self.mlp = SteelSoftMoeV2(config, layer=mlp_class)
818
+ logger.warning_once(f"FFN: SteelSoftMoeV2")
819
+ elif config.FFN_type == "softmoe_v3":
820
+ self.mlp = SteelSoftMoEV3(config=config, layer=mlp_class)
821
+ logger.warning_once(f"FFN: SteelSoftMoeV3")
822
+ else:
823
+ raise NameError(f"No this FFN type: {config.FFN_type}")
824
+
825
+ self.input_layernorm = SteelRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
826
+ self.post_attention_layernorm = SteelRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
827
+
828
+ def forward(
829
+ self,
830
+ hidden_states: torch.Tensor,
831
+ attention_mask: Optional[torch.Tensor] = None,
832
+ position_ids: Optional[torch.LongTensor] = None,
833
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
834
+ output_attentions: Optional[bool] = False,
835
+ use_cache: Optional[bool] = False,
836
+ **kwargs,
837
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
838
+ if "padding_mask" in kwargs:
839
+ warnings.warn(
840
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
841
+ "Please make sure use `attention_mask` instead.`"
842
+ )
843
+ """
844
+ Args:
845
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
846
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
847
+ `(batch, sequence_length)` where padding elements are indicated by 0.
848
+ output_attentions (`bool`, *optional*):
849
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
850
+ returned tensors for more detail.
851
+ use_cache (`bool`, *optional*):
852
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
853
+ (see `past_key_values`).
854
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
855
+ """
856
+
857
+ residual = hidden_states
858
+
859
+ hidden_states = self.input_layernorm(hidden_states)
860
+
861
+ # Self Attention
862
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
863
+ hidden_states=hidden_states,
864
+ attention_mask=attention_mask,
865
+ position_ids=position_ids,
866
+ past_key_value=past_key_value,
867
+ output_attentions=output_attentions,
868
+ use_cache=use_cache,
869
+ )
870
+ hidden_states = residual + hidden_states
871
+
872
+ # Fully Connected
873
+ residual = hidden_states
874
+ hidden_states = self.post_attention_layernorm(hidden_states)
875
+ hidden_states = self.mlp(hidden_states)
876
+ hidden_states = residual + hidden_states
877
+
878
+ outputs = (hidden_states,)
879
+
880
+ if output_attentions:
881
+ outputs += (self_attn_weights,)
882
+
883
+ if use_cache:
884
+ outputs += (present_key_value,)
885
+
886
+ return outputs
887
+
888
+
889
+ Steel_START_DOCSTRING = r"""
890
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
891
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
892
+ etc.)
893
+
894
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
895
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
896
+ and behavior.
897
+
898
+ Parameters:
899
+ config ([`SteelConfig`]):
900
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
901
+ load the weights associated with the model, only the configuration. Check out the
902
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
903
+ """
904
+
905
+
906
+ @add_start_docstrings(
907
+ "The bare Steel Model outputting raw hidden-states without any specific head on top.",
908
+ Steel_START_DOCSTRING,
909
+ )
910
+ class SteelPreTrainedModel(PreTrainedModel):
911
+ config_class = SteelConfig
912
+ base_model_prefix = "model"
913
+ supports_gradient_checkpointing = True
914
+ _no_split_modules = ["SteelDecoderLayer"]
915
+ _skip_keys_device_placement = "past_key_values"
916
+ _supports_flash_attn_2 = True
917
+ _supports_sdpa = True
918
+ _supports_cache_class = True
919
+
920
+ def _init_weights(self, module):
921
+ std = self.config.initializer_range
922
+ if isinstance(module, nn.Linear):
923
+ module.weight.data.normal_(mean=0.0, std=std)
924
+ if module.bias is not None:
925
+ module.bias.data.zero_()
926
+ elif isinstance(module, nn.Embedding):
927
+ module.weight.data.normal_(mean=0.0, std=std)
928
+ if module.padding_idx is not None:
929
+ module.weight.data[module.padding_idx].zero_()
930
+
931
+
932
+ Steel_INPUTS_DOCSTRING = r"""
933
+ Args:
934
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
935
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
936
+ it.
937
+
938
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
939
+ [`PreTrainedTokenizer.__call__`] for details.
940
+
941
+ [What are input IDs?](../glossary#input-ids)
942
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
943
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
944
+
945
+ - 1 for tokens that are **not masked**,
946
+ - 0 for tokens that are **masked**.
947
+
948
+ [What are attention masks?](../glossary#attention-mask)
949
+
950
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
951
+ [`PreTrainedTokenizer.__call__`] for details.
952
+
953
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
954
+ `past_key_values`).
955
+
956
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
957
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
958
+ information on the default strategy.
959
+
960
+ - 1 indicates the head is **not masked**,
961
+ - 0 indicates the head is **masked**.
962
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
963
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
964
+ config.n_positions - 1]`.
965
+
966
+ [What are position IDs?](../glossary#position-ids)
967
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
968
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
969
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
970
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
971
+
972
+ Two formats are allowed:
973
+ - a [`~cache_utils.Cache`] instance;
974
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
975
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
976
+ cache format.
977
+
978
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
979
+ legacy cache format will be returned.
980
+
981
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
982
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
983
+ of shape `(batch_size, sequence_length)`.
984
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
985
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
986
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
987
+ model's internal embedding lookup matrix.
988
+ use_cache (`bool`, *optional*):
989
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
990
+ `past_key_values`).
991
+ output_attentions (`bool`, *optional*):
992
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
993
+ tensors for more detail.
994
+ output_hidden_states (`bool`, *optional*):
995
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
996
+ more detail.
997
+ return_dict (`bool`, *optional*):
998
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
999
+ """
1000
+
1001
+
1002
+ @add_start_docstrings(
1003
+ "The bare Steel Model outputting raw hidden-states without any specific head on top.",
1004
+ Steel_START_DOCSTRING,
1005
+ )
1006
+ class SteelModel(SteelPreTrainedModel):
1007
+ """
1008
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`SteelDecoderLayer`]
1009
+
1010
+ Args:
1011
+ config: SteelConfig
1012
+ """
1013
+
1014
+ def __init__(self, config: SteelConfig):
1015
+ super().__init__(config)
1016
+ self.padding_idx = config.pad_token_id
1017
+ self.vocab_size = config.vocab_size
1018
+
1019
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1020
+ self.layers = nn.ModuleList(
1021
+ [SteelDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1022
+ )
1023
+ self._attn_implementation = config._attn_implementation
1024
+ logger.warning_once(
1025
+ f"zhanshijin: now use _attn_implementation is {config._attn_implementation}, you can choose from {Steel_ATTENTION_CLASSES.keys()}"
1026
+ )
1027
+ self.norm = SteelRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1028
+
1029
+ self.gradient_checkpointing = False
1030
+ # Initialize weights and apply final processing
1031
+ self.post_init()
1032
+
1033
+ if hasattr(config, "use_cuda_rmsnorm") and config.use_cuda_rmsnorm:
1034
+ _import_cuda_rmsnorm()
1035
+ else:
1036
+ print("zhanshijin: use torch rmsnorm")
1037
+
1038
+ def get_input_embeddings(self):
1039
+ return self.embed_tokens
1040
+
1041
+ def set_input_embeddings(self, value):
1042
+ self.embed_tokens = value
1043
+
1044
+ @add_start_docstrings_to_model_forward(Steel_INPUTS_DOCSTRING)
1045
+ def forward(
1046
+ self,
1047
+ input_ids: torch.LongTensor = None,
1048
+ attention_mask: Optional[torch.Tensor] = None,
1049
+ position_ids: Optional[torch.LongTensor] = None,
1050
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1051
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1052
+ use_cache: Optional[bool] = None,
1053
+ output_attentions: Optional[bool] = None,
1054
+ output_hidden_states: Optional[bool] = None,
1055
+ return_dict: Optional[bool] = None,
1056
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1057
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1058
+ output_hidden_states = (
1059
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1060
+ )
1061
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1062
+
1063
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1064
+
1065
+ # retrieve input_ids and inputs_embeds
1066
+ if input_ids is not None and inputs_embeds is not None:
1067
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1068
+ elif input_ids is not None:
1069
+ batch_size, seq_length = input_ids.shape
1070
+ elif inputs_embeds is not None:
1071
+ batch_size, seq_length, _ = inputs_embeds.shape
1072
+ else:
1073
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
1074
+
1075
+ if self.gradient_checkpointing and self.training:
1076
+ if use_cache:
1077
+ logger.warning_once(
1078
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1079
+ )
1080
+ use_cache = False
1081
+
1082
+ past_key_values_length = 0
1083
+
1084
+ if use_cache:
1085
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1086
+ if use_legacy_cache:
1087
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1088
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1089
+
1090
+ if position_ids is None:
1091
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1092
+ position_ids = torch.arange(
1093
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1094
+ )
1095
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1096
+ else:
1097
+ position_ids = position_ids.view(-1, seq_length).long()
1098
+
1099
+ if inputs_embeds is None:
1100
+ inputs_embeds = self.embed_tokens(input_ids)
1101
+
1102
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1103
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1104
+ if is_padding_right:
1105
+ raise ValueError(
1106
+ "You are attempting to perform batched generation with padding_side='right'"
1107
+ " this may lead to unexpected behaviour for Flash Attention version of Steel. Make sure to "
1108
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1109
+ )
1110
+
1111
+ if self._attn_implementation == "flash_attention_2":
1112
+ # 2d mask is passed through the layers
1113
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1114
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1115
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1116
+ # the manual implementation that requires a 4D causal mask in all cases.
1117
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1118
+ attention_mask,
1119
+ (batch_size, seq_length),
1120
+ inputs_embeds,
1121
+ past_key_values_length,
1122
+ sliding_window=self.config.sliding_window,
1123
+ )
1124
+ else:
1125
+ # 4d mask is passed through the layers
1126
+ attention_mask = _prepare_4d_causal_attention_mask(
1127
+ attention_mask,
1128
+ (batch_size, seq_length),
1129
+ inputs_embeds,
1130
+ past_key_values_length,
1131
+ sliding_window=self.config.sliding_window,
1132
+ )
1133
+
1134
+ hidden_states = inputs_embeds
1135
+
1136
+ # decoder layers
1137
+ all_hidden_states = () if output_hidden_states else None
1138
+ all_self_attns = () if output_attentions else None
1139
+ next_decoder_cache = None
1140
+
1141
+ for decoder_layer in self.layers:
1142
+ if output_hidden_states:
1143
+ all_hidden_states += (hidden_states,)
1144
+
1145
+ if self.gradient_checkpointing and self.training:
1146
+ layer_outputs = self._gradient_checkpointing_func(
1147
+ decoder_layer.__call__,
1148
+ hidden_states,
1149
+ attention_mask,
1150
+ position_ids,
1151
+ past_key_values,
1152
+ output_attentions,
1153
+ use_cache,
1154
+ )
1155
+ else:
1156
+ layer_outputs = decoder_layer(
1157
+ hidden_states,
1158
+ attention_mask=attention_mask,
1159
+ position_ids=position_ids,
1160
+ past_key_value=past_key_values,
1161
+ output_attentions=output_attentions,
1162
+ use_cache=use_cache,
1163
+ )
1164
+
1165
+ hidden_states = layer_outputs[0]
1166
+
1167
+ if use_cache:
1168
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1169
+
1170
+ if output_attentions:
1171
+ all_self_attns += (layer_outputs[1],)
1172
+
1173
+ hidden_states = self.norm(hidden_states)
1174
+
1175
+ # add hidden states from the last decoder layer
1176
+ if output_hidden_states:
1177
+ all_hidden_states += (hidden_states,)
1178
+
1179
+ next_cache = None
1180
+ if use_cache:
1181
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1182
+
1183
+ if not return_dict:
1184
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1185
+ return BaseModelOutputWithPast(
1186
+ last_hidden_state=hidden_states,
1187
+ past_key_values=next_cache,
1188
+ hidden_states=all_hidden_states,
1189
+ attentions=all_self_attns,
1190
+ )
1191
+
1192
+
1193
+ class SteelForCausalLM(SteelPreTrainedModel):
1194
+ _tied_weights_keys = ["lm_head.weight"]
1195
+
1196
+ def __init__(self, config):
1197
+ super().__init__(config)
1198
+ self.model = SteelModel(config)
1199
+ self.vocab_size = config.vocab_size
1200
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1201
+
1202
+ # Initialize weights and apply final processing
1203
+ self.post_init()
1204
+
1205
+ def get_input_embeddings(self):
1206
+ return self.model.embed_tokens
1207
+
1208
+ def set_input_embeddings(self, value):
1209
+ self.model.embed_tokens = value
1210
+
1211
+ def get_output_embeddings(self):
1212
+ return self.lm_head
1213
+
1214
+ def set_output_embeddings(self, new_embeddings):
1215
+ self.lm_head = new_embeddings
1216
+
1217
+ def set_decoder(self, decoder):
1218
+ self.model = decoder
1219
+
1220
+ def get_decoder(self):
1221
+ return self.model
1222
+
1223
+ @add_start_docstrings_to_model_forward(Steel_INPUTS_DOCSTRING)
1224
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1225
+ def forward(
1226
+ self,
1227
+ input_ids: torch.LongTensor = None,
1228
+ attention_mask: Optional[torch.Tensor] = None,
1229
+ position_ids: Optional[torch.LongTensor] = None,
1230
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1231
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1232
+ labels: Optional[torch.LongTensor] = None,
1233
+ use_cache: Optional[bool] = None,
1234
+ output_attentions: Optional[bool] = None,
1235
+ output_hidden_states: Optional[bool] = None,
1236
+ return_dict: Optional[bool] = None,
1237
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1238
+ r"""
1239
+ Args:
1240
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1241
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1242
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1243
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1244
+
1245
+ Returns:
1246
+
1247
+ Example:
1248
+
1249
+ ```python
1250
+ >>> from transformers import AutoTokenizer, SteelForCausalLM
1251
+
1252
+ >>> model = SteelForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1253
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1254
+
1255
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1256
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1257
+
1258
+ >>> # Generate
1259
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1260
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1261
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1262
+ ```"""
1263
+
1264
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1265
+ output_hidden_states = (
1266
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1267
+ )
1268
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1269
+
1270
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1271
+ outputs = self.model(
1272
+ input_ids=input_ids,
1273
+ attention_mask=attention_mask,
1274
+ position_ids=position_ids,
1275
+ past_key_values=past_key_values,
1276
+ inputs_embeds=inputs_embeds,
1277
+ use_cache=use_cache,
1278
+ output_attentions=output_attentions,
1279
+ output_hidden_states=output_hidden_states,
1280
+ return_dict=return_dict,
1281
+ )
1282
+
1283
+ hidden_states = outputs[0]
1284
+ logits = self.lm_head(hidden_states)
1285
+ logits = logits.float()
1286
+
1287
+ loss = None
1288
+ if labels is not None:
1289
+ # Shift so that tokens < n predict n
1290
+ shift_logits = logits[..., :-1, :].contiguous()
1291
+ shift_labels = labels[..., 1:].contiguous()
1292
+ # Flatten the tokens
1293
+ loss_fct = CrossEntropyLoss()
1294
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1295
+ shift_labels = shift_labels.view(-1)
1296
+ # Enable model parallelism
1297
+ shift_labels = shift_labels.to(shift_logits.device)
1298
+ loss = loss_fct(shift_logits, shift_labels)
1299
+
1300
+ if not return_dict:
1301
+ output = (logits,) + outputs[1:]
1302
+ return (loss,) + output if loss is not None else output
1303
+
1304
+ return CausalLMOutputWithPast(
1305
+ loss=loss,
1306
+ logits=logits,
1307
+ past_key_values=outputs.past_key_values,
1308
+ hidden_states=outputs.hidden_states,
1309
+ attentions=outputs.attentions,
1310
+ )
1311
+
1312
+ def prepare_inputs_for_generation(
1313
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1314
+ ):
1315
+ # Omit tokens covered by past_key_values
1316
+ if past_key_values is not None:
1317
+ if isinstance(past_key_values, Cache):
1318
+ cache_length = past_key_values.get_seq_length()
1319
+ past_length = past_key_values.seen_tokens
1320
+ max_cache_length = past_key_values.get_max_length()
1321
+ else:
1322
+ cache_length = past_length = past_key_values[0][0].shape[2]
1323
+ max_cache_length = None
1324
+
1325
+ # Keep only the unprocessed tokens:
1326
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1327
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1328
+ # input)
1329
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1330
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1331
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1332
+ # input_ids based on the past_length.
1333
+ elif past_length < input_ids.shape[1]:
1334
+ input_ids = input_ids[:, past_length:]
1335
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1336
+
1337
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1338
+ if (
1339
+ max_cache_length is not None
1340
+ and attention_mask is not None
1341
+ and cache_length + input_ids.shape[1] > max_cache_length
1342
+ ):
1343
+ attention_mask = attention_mask[:, -max_cache_length:]
1344
+
1345
+ position_ids = kwargs.get("position_ids", None)
1346
+ if attention_mask is not None and position_ids is None:
1347
+ # create position_ids on the fly for batch generation
1348
+ position_ids = attention_mask.long().cumsum(-1) - 1
1349
+ position_ids.masked_fill_(attention_mask == 0, 1)
1350
+ if past_key_values:
1351
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1352
+
1353
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1354
+ if inputs_embeds is not None and past_key_values is None:
1355
+ model_inputs = {"inputs_embeds": inputs_embeds}
1356
+ else:
1357
+ model_inputs = {"input_ids": input_ids}
1358
+
1359
+ model_inputs.update(
1360
+ {
1361
+ "position_ids": position_ids,
1362
+ "past_key_values": past_key_values,
1363
+ "use_cache": kwargs.get("use_cache"),
1364
+ "attention_mask": attention_mask,
1365
+ }
1366
+ )
1367
+ return model_inputs
1368
+
1369
+ @staticmethod
1370
+ def _reorder_cache(past_key_values, beam_idx):
1371
+ reordered_past = ()
1372
+ for layer_past in past_key_values:
1373
+ reordered_past += (
1374
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1375
+ )
1376
+ return reordered_past
1377
+
1378
+
1379
+ @add_start_docstrings(
1380
+ """
1381
+ The Steel Model transformer with a sequence classification head on top (linear layer).
1382
+
1383
+ [`SteelForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1384
+ (e.g. GPT-2) do.
1385
+
1386
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1387
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1388
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1389
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1390
+ each row of the batch).
1391
+ """,
1392
+ Steel_START_DOCSTRING,
1393
+ )
1394
+ class SteelForSequenceClassification(SteelPreTrainedModel):
1395
+ def __init__(self, config):
1396
+ super().__init__(config)
1397
+ self.num_labels = config.num_labels
1398
+ self.model = SteelModel(config)
1399
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1400
+
1401
+ # Initialize weights and apply final processing
1402
+ self.post_init()
1403
+
1404
+ def get_input_embeddings(self):
1405
+ return self.model.embed_tokens
1406
+
1407
+ def set_input_embeddings(self, value):
1408
+ self.model.embed_tokens = value
1409
+
1410
+ @add_start_docstrings_to_model_forward(Steel_INPUTS_DOCSTRING)
1411
+ def forward(
1412
+ self,
1413
+ input_ids: torch.LongTensor = None,
1414
+ attention_mask: Optional[torch.Tensor] = None,
1415
+ position_ids: Optional[torch.LongTensor] = None,
1416
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1417
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1418
+ labels: Optional[torch.LongTensor] = None,
1419
+ use_cache: Optional[bool] = None,
1420
+ output_attentions: Optional[bool] = None,
1421
+ output_hidden_states: Optional[bool] = None,
1422
+ return_dict: Optional[bool] = None,
1423
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1424
+ r"""
1425
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1426
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1427
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1428
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1429
+ """
1430
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1431
+
1432
+ transformer_outputs = self.model(
1433
+ input_ids,
1434
+ attention_mask=attention_mask,
1435
+ position_ids=position_ids,
1436
+ past_key_values=past_key_values,
1437
+ inputs_embeds=inputs_embeds,
1438
+ use_cache=use_cache,
1439
+ output_attentions=output_attentions,
1440
+ output_hidden_states=output_hidden_states,
1441
+ return_dict=return_dict,
1442
+ )
1443
+ hidden_states = transformer_outputs[0]
1444
+ logits = self.score(hidden_states)
1445
+
1446
+ if input_ids is not None:
1447
+ batch_size = input_ids.shape[0]
1448
+ else:
1449
+ batch_size = inputs_embeds.shape[0]
1450
+
1451
+ if self.config.pad_token_id is None and batch_size != 1:
1452
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1453
+ if self.config.pad_token_id is None:
1454
+ sequence_lengths = -1
1455
+ else:
1456
+ if input_ids is not None:
1457
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1458
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1459
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1460
+ sequence_lengths = sequence_lengths.to(logits.device)
1461
+ else:
1462
+ sequence_lengths = -1
1463
+
1464
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1465
+
1466
+ loss = None
1467
+ if labels is not None:
1468
+ labels = labels.to(logits.device)
1469
+ if self.config.problem_type is None:
1470
+ if self.num_labels == 1:
1471
+ self.config.problem_type = "regression"
1472
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1473
+ self.config.problem_type = "single_label_classification"
1474
+ else:
1475
+ self.config.problem_type = "multi_label_classification"
1476
+
1477
+ if self.config.problem_type == "regression":
1478
+ loss_fct = MSELoss()
1479
+ if self.num_labels == 1:
1480
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1481
+ else:
1482
+ loss = loss_fct(pooled_logits, labels)
1483
+ elif self.config.problem_type == "single_label_classification":
1484
+ loss_fct = CrossEntropyLoss()
1485
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1486
+ elif self.config.problem_type == "multi_label_classification":
1487
+ loss_fct = BCEWithLogitsLoss()
1488
+ loss = loss_fct(pooled_logits, labels)
1489
+ if not return_dict:
1490
+ output = (pooled_logits,) + transformer_outputs[1:]
1491
+ return ((loss,) + output) if loss is not None else output
1492
+
1493
+ return SequenceClassifierOutputWithPast(
1494
+ loss=loss,
1495
+ logits=pooled_logits,
1496
+ past_key_values=transformer_outputs.past_key_values,
1497
+ hidden_states=transformer_outputs.hidden_states,
1498
+ attentions=transformer_outputs.attentions,
1499
+ )
steel-llm-step-980000-ckpt/softmoe_v3.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+
8
+ def softmax(x: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
9
+ """
10
+ Compute the softmax along the specified dimensions.
11
+ This function adds the option to specify multiple dimensions
12
+
13
+ Args:
14
+ x (torch.Tensor): Input tensor.
15
+ dims (int or tuple[int]): The dimension or list of dimensions along which the softmax probabilities are computed.
16
+
17
+ Returns:
18
+ torch.Tensor: Output tensor containing softmax probabilities along the specified dimensions.
19
+ """
20
+ dtype = x.dtype
21
+ x = x.to(torch.float32)
22
+ max_vals = torch.amax(x, dim=dim, keepdim=True)
23
+ e_x = torch.exp(x - max_vals)
24
+ sum_exp = e_x.sum(dim=dim, keepdim=True)
25
+ return (e_x / sum_exp).to(dtype)
26
+
27
+ # copy from https://github.com/bwconrad/soft-moe
28
+ class SteelSoftMoEV3(nn.Module):
29
+ """
30
+ A wrapper class to create a Soft Mixture of Experts layer.
31
+
32
+ From "From Sparse to Soft Mixtures of Experts"
33
+ https://arxiv.org/pdf/2308.00951.pdf
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ config,
39
+ layer: Callable,
40
+ ) -> None:
41
+ """
42
+ Args:
43
+ dim (int): Dimensionality of input features.
44
+ num_experts (int): Number of experts.
45
+ slots_per_expert (int): Number of token slots per expert.
46
+ layer (Callable): Network layer of the experts.
47
+ normalize (bool): Normalize input and phi (sec. 2.3 from paper)
48
+ **layer_kwargs: Additional keyword arguments for the layer class.
49
+ """
50
+ super().__init__()
51
+
52
+ self.dim = config.hidden_size
53
+ self.num_experts = config.n_experts
54
+ self.slots_per_expert = config.slots_per_expert if hasattr(config, "slots_per_expert") else 1
55
+ self.normalize = True
56
+
57
+ # Initialize phi and normalization scaling factor
58
+ self.phi = nn.Parameter(torch.zeros(self.dim, self.num_experts, self.slots_per_expert))
59
+ if self.normalize:
60
+ self.scale = nn.Parameter(torch.ones(1))
61
+
62
+ # Initialize phi using LeCun normal initialization
63
+ # https://github.com/google-research/vmoe/blob/662341d007650d5bbb7c6a2bef7f3c759a20cc7e/vmoe/projects/soft_moe/router.py#L49C1-L49C1
64
+ nn.init.normal_(self.phi, mean=0, std=1 / self.dim**0.5)
65
+
66
+ # Create a list of expert networks
67
+ self.experts = nn.ModuleList(
68
+ [layer(config) for _ in range(self.num_experts)]
69
+ )
70
+
71
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
72
+ """
73
+ Forward pass through the Soft-MoE layer (algorithm 1 from paper).
74
+
75
+ Args:
76
+ x (torch.Tensor): Input tensor of shape [batch_size, seq_len, input_dim].
77
+
78
+ Returns:
79
+ torch.Tensor: Output tensor of shape [batch_size, seq_len, input_dim].
80
+ """
81
+ assert (
82
+ x.shape[-1] == self.dim
83
+ ), f"Input feature dim of {x.shape[-1]} does not match layer dim of {self.dim}"
84
+ assert (
85
+ len(x.shape) == 3
86
+ ), f"Input expected to have 3 dimensions but has {len(x.shape)}"
87
+
88
+ phi = self.phi
89
+
90
+ # Normalize input and phi
91
+ if self.normalize:
92
+ x = F.normalize(x, dim=2) # [b, m, d]
93
+ phi = self.scale * F.normalize(phi, dim=0) # [d, n, p]
94
+
95
+ # Compute dispatch and combine weights
96
+ logits = torch.einsum("bmd,dnp->bmnp", x, phi)
97
+ d = softmax(logits, dim=1)
98
+ c = softmax(logits, dim=(2, 3))
99
+ # tmp = c[0,:,:,0].reshape([c.shape[1],-1])
100
+ # print("num:",tmp, "shape:",tmp.shape, "sum:",tmp.sum(dim=1))
101
+ # Compute input slots as weighted average of input tokens using dispatch weights
102
+ xs = torch.einsum("bmd,bmnp->bnpd", x, d)
103
+
104
+ # Apply expert to corresponding slots
105
+ ys = torch.stack(
106
+ [f_i(xs[:, i, :, :]) for i, f_i in enumerate(self.experts)], dim=1
107
+ )
108
+
109
+ # Compute output tokens as weighted average of output slots using combine weights
110
+ y = torch.einsum("bnpd,bmnp->bmd", ys, c)
111
+
112
+ return y
steel-llm-step-980000-ckpt/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
steel-llm-step-980000-ckpt/tokenizer_config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": ["<|im_start|>", "<|im_end|>"],
30
+ "bos_token": null,
31
+ "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 %}",
32
+ "clean_up_tokenization_spaces": false,
33
+ "eos_token": "<|im_end|>",
34
+ "errors": "replace",
35
+ "model_max_length": 32768,
36
+ "pad_token": "<|endoftext|>",
37
+ "split_special_tokens": false,
38
+ "tokenizer_class": "Qwen2Tokenizer",
39
+ "unk_token": null
40
+ }
41
+