gqszhanshijin commited on
Commit
01be556
·
1 Parent(s): bb74b6c
steel-llm-step-220000-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-220000-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-220000-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-220000-ckpt/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
steel-llm-step-220000-ckpt/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e804620850544541ba5b07ef6cc5775b17c534d5842171e4ee61908a57e60053
3
+ size 4491766872
steel-llm-step-220000-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-220000-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-220000-ckpt/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
steel-llm-step-220000-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-220000-ckpt/vocab.json ADDED
The diff for this file is too large to render. See raw diff