gqszhanshijin commited on
Commit
63b2963
·
1 Parent(s): b970276

update chat v2

Browse files
README.md CHANGED
@@ -15,6 +15,8 @@ Steel-LLM是个人发起的利用业余时间从零开始预训练中文大模
15
 
16
  "Steel(钢)"取名灵感来源于华北平原一只优秀的乐队“万能青年旅店(万青)”。乐队在做一专的时候条件有限,自称是在“土法炼钢”,但却是一张神专。我们训练LLM的条件同样有限,但也希望能炼出好“钢”来。
17
 
 
 
18
  ## 📖 预训练数据
19
  预训练数据方面,Steel-LLM主要使用了wanjuan1.0、Skywork/Skypile-150B数据集、starcoder的python/java/c++数据。另外也加入了中文维基百科、百度百科、知乎问答等数据,转换为token id后占用1.7T硬盘空间。Steel-LLM也对问答数据以及代码数据使用data-juicer进行了数据清洗,数据收集及数据处理的具体细节见我的博客:
20
  https://mp.weixin.qq.com/s/yqmtHLuuNV9075qHgzhcPw
@@ -40,7 +42,7 @@ Steel-LLM在CEVAL和CMMLU上进行了测试。Steel-LLM旨在训练一个中文L
40
 
41
  | | CEVAL | CMMLU |
42
  |-----------------|-------|-------|
43
- | Steel-LLM | 38.57 | 33.48 |
44
  | ChatGPT | 51.0 | - |
45
  | GPT4 | 66.4 | - |
46
  | ChatGLM-6B | 38.9 | - |
 
15
 
16
  "Steel(钢)"取名灵感来源于华北平原一只优秀的乐队“万能青年旅店(万青)”。乐队在做一专的时候条件有限,自称是在“土法炼钢”,但却是一张神专。我们训练LLM的条件同样有限,但也希望能炼出好“钢”来。
17
 
18
+ ## 🔥更新
19
+ 2025.1.17 更新steel-LLM-chat-v2,微调时加入了英文数据,中英文数据比例和预训练保持一致,最终在ceval上由38分提高到了41.9分,cmmlu从33分提高到了36分。
20
  ## 📖 预训练数据
21
  预训练数据方面,Steel-LLM主要使用了wanjuan1.0、Skywork/Skypile-150B数据集、starcoder的python/java/c++数据。另外也加入了中文维基百科、百度百科、知乎问答等数据,转换为token id后占用1.7T硬盘空间。Steel-LLM也对问答数据以及代码数据使用data-juicer进行了数据清洗,数据收集及数据处理的具体细节见我的博客:
22
  https://mp.weixin.qq.com/s/yqmtHLuuNV9075qHgzhcPw
 
42
 
43
  | | CEVAL | CMMLU |
44
  |-----------------|-------|-------|
45
+ | Steel-LLM(chat v2) | 41.9 | 36.08 |
46
  | ChatGPT | 51.0 | - |
47
  | GPT4 | 66.4 | - |
48
  | ChatGLM-6B | 38.9 | - |
steel-llm-chat-v2/added_tokens.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "<|endoftext|>": 151643,
3
+ "<|im_end|>": 151645,
4
+ "<|im_start|>": 151644
5
+ }
steel-llm-chat-v2/config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "FFN_type": "softmoe_v3",
3
+ "_name_or_path": "/data/model/llm/Steel-LLM/steel-llm-step-1060000-ckpt",
4
+ "architectures": [
5
+ "SteelForCausalLM"
6
+ ],
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_steel.SteelConfig",
10
+ "AutoModel": "modeling_steel.SteelForCausalLM",
11
+ "AutoModelForCausalLM": "modeling_steel.SteelForCausalLM"
12
+ },
13
+ "bos_token_id": 151643,
14
+ "eos_token_id": 151645,
15
+ "hidden_act": "silu",
16
+ "hidden_size": 1792,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 1792,
19
+ "max_position_embeddings": 32768,
20
+ "max_window_layers": 21,
21
+ "mlp_div_ratio": 4,
22
+ "mlp_type": "senet",
23
+ "model_type": "qwen2",
24
+ "n_experts": 6,
25
+ "num_attention_heads": 32,
26
+ "num_hidden_layers": 18,
27
+ "num_key_value_heads": 32,
28
+ "rms_norm_eps": 1e-06,
29
+ "rope_theta": 1000000.0,
30
+ "sliding_window": 32768,
31
+ "slots_per_expert": 1,
32
+ "tie_word_embeddings": false,
33
+ "torch_dtype": "float32",
34
+ "transformers_version": "4.43.4",
35
+ "use_cache": false,
36
+ "use_sliding_window": false,
37
+ "vocab_size": 151936
38
+ }
steel-llm-chat-v2/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-chat-v2/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.43.4"
6
+ }
steel-llm-chat-v2/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
steel-llm-chat-v2/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f8b08168d3e1b93cd60db3e9127ed11f49ad50110c6eb9482f49272461dd4614
3
+ size 4491766872
steel-llm-chat-v2/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-chat-v2/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-chat-v2/special_tokens_map.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>"
5
+ ],
6
+ "eos_token": {
7
+ "content": "<|im_end|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false
12
+ },
13
+ "pad_token": {
14
+ "content": "<|endoftext|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false
19
+ }
20
+ }
steel-llm-chat-v2/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
steel-llm-chat-v2/tokenizer_config.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "151643": {
5
+ "content": "<|endoftext|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "151644": {
13
+ "content": "<|im_start|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "151645": {
21
+ "content": "<|im_end|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ }
28
+ },
29
+ "additional_special_tokens": [
30
+ "<|im_start|>",
31
+ "<|im_end|>"
32
+ ],
33
+ "bos_token": null,
34
+ "chat_template": "{% set system_message = 'You are a helpful assistant.' %}{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% else %}{% set loop_messages = messages %}{% endif %}{% if system_message is defined %}{{ '<|im_start|>system\n' + system_message + '<|im_end|>\n' }}{% endif %}{% for message in loop_messages %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{{ '<|im_start|>user\n' + content + '<|im_end|>\n<|im_start|>assistant\n' }}{% elif message['role'] == 'assistant' %}{{ content + '<|im_end|>' + '\n' }}{% endif %}{% endfor %}",
35
+ "clean_up_tokenization_spaces": false,
36
+ "eos_token": "<|im_end|>",
37
+ "errors": "replace",
38
+ "model_max_length": 32768,
39
+ "pad_token": "<|endoftext|>",
40
+ "padding_side": "right",
41
+ "split_special_tokens": false,
42
+ "tokenizer_class": "Qwen2Tokenizer",
43
+ "unk_token": null
44
+ }
steel-llm-chat-v2/trainer_state.json ADDED
The diff for this file is too large to render. See raw diff
 
steel-llm-chat-v2/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:184d48b5036c92838901a0a8a37d6e74829e0741d309af32d72cd034f8f4719c
3
+ size 5496
steel-llm-chat-v2/vocab.json ADDED
The diff for this file is too large to render. See raw diff