Add files using upload-large-folder tool
Browse files- .gitattributes +1 -0
- README.md +39 -0
- added_tokens.json +28 -0
- chat_template.jinja +6 -0
- config.json +52 -0
- configuration_klear.py +224 -0
- generation_config.json +12 -0
- merges.txt +0 -0
- model-00001-of-00004.safetensors +3 -0
- model-00002-of-00004.safetensors +3 -0
- model-00003-of-00004.safetensors +3 -0
- model-00004-of-00004.safetensors +3 -0
- model.safetensors.index.json +0 -0
- modeling_klear.py +682 -0
- special_tokens_map.json +31 -0
- tokenizer.json +3 -0
- tokenizer_config.json +239 -0
- vocab.json +0 -0
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
license: apache-2.0
|
3 |
+
language:
|
4 |
+
- zh
|
5 |
+
- en
|
6 |
+
base_model: Kwai-Klear/Klear-46B-A2.5B-Instruct
|
7 |
+
pipeline_tag: text-generation
|
8 |
+
library_name: mlx
|
9 |
+
tags:
|
10 |
+
- mlx
|
11 |
+
---
|
12 |
+
|
13 |
+
# mlx-community/Klear-46B-A2.5B-Instruct-3bit
|
14 |
+
|
15 |
+
This model [mlx-community/Klear-46B-A2.5B-Instruct-3bit](https://huggingface.co/mlx-community/Klear-46B-A2.5B-Instruct-3bit) was
|
16 |
+
converted to MLX format from [Kwai-Klear/Klear-46B-A2.5B-Instruct](https://huggingface.co/Kwai-Klear/Klear-46B-A2.5B-Instruct)
|
17 |
+
using mlx-lm version **0.27.1**.
|
18 |
+
|
19 |
+
## Use with mlx
|
20 |
+
|
21 |
+
```bash
|
22 |
+
pip install mlx-lm
|
23 |
+
```
|
24 |
+
|
25 |
+
```python
|
26 |
+
from mlx_lm import load, generate
|
27 |
+
|
28 |
+
model, tokenizer = load("mlx-community/Klear-46B-A2.5B-Instruct-3bit")
|
29 |
+
|
30 |
+
prompt = "hello"
|
31 |
+
|
32 |
+
if tokenizer.chat_template is not None:
|
33 |
+
messages = [{"role": "user", "content": prompt}]
|
34 |
+
prompt = tokenizer.apply_chat_template(
|
35 |
+
messages, add_generation_prompt=True
|
36 |
+
)
|
37 |
+
|
38 |
+
response = generate(model, tokenizer, prompt=prompt, verbose=True)
|
39 |
+
```
|
added_tokens.json
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"</think>": 151668,
|
3 |
+
"</tool_call>": 151658,
|
4 |
+
"</tool_response>": 151666,
|
5 |
+
"<think>": 151667,
|
6 |
+
"<tool_call>": 151657,
|
7 |
+
"<tool_response>": 151665,
|
8 |
+
"<|box_end|>": 151649,
|
9 |
+
"<|box_start|>": 151648,
|
10 |
+
"<|endoftext|>": 151643,
|
11 |
+
"<|file_sep|>": 151664,
|
12 |
+
"<|fim_middle|>": 151660,
|
13 |
+
"<|fim_pad|>": 151662,
|
14 |
+
"<|fim_prefix|>": 151659,
|
15 |
+
"<|fim_suffix|>": 151661,
|
16 |
+
"<|im_end|>": 151645,
|
17 |
+
"<|im_start|>": 151644,
|
18 |
+
"<|image_pad|>": 151655,
|
19 |
+
"<|object_ref_end|>": 151647,
|
20 |
+
"<|object_ref_start|>": 151646,
|
21 |
+
"<|quad_end|>": 151651,
|
22 |
+
"<|quad_start|>": 151650,
|
23 |
+
"<|repo_name|>": 151663,
|
24 |
+
"<|video_pad|>": 151656,
|
25 |
+
"<|vision_end|>": 151653,
|
26 |
+
"<|vision_pad|>": 151654,
|
27 |
+
"<|vision_start|>": 151652
|
28 |
+
}
|
chat_template.jinja
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|im_start|>system
|
2 |
+
You are a helpful AI assistant, skilled at solving various problems.<|im_end|>
|
3 |
+
' }}{% endif %}{{'<|im_start|>' + message['role'] + '
|
4 |
+
' + message['content'] + '<|im_end|>' + '
|
5 |
+
'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant
|
6 |
+
' }}{% endif %}
|
config.json
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"KlearMoeForCausalLM"
|
4 |
+
],
|
5 |
+
"attention_bias": false,
|
6 |
+
"attention_dropout": 0.0,
|
7 |
+
"auto_map": {
|
8 |
+
"AutoConfig": "configuration_klear.KlearConfig",
|
9 |
+
"AutoModel": "modeling_klear.KlearModel",
|
10 |
+
"AutoModelForCausalLM": "modeling_klear.KlearMoeForCausalLM"
|
11 |
+
},
|
12 |
+
"decoder_sparse_step": 1,
|
13 |
+
"dtype": "bfloat16",
|
14 |
+
"hidden_act": "silu",
|
15 |
+
"hidden_size": 2048,
|
16 |
+
"initializer_range": 0.02,
|
17 |
+
"intermediate_size": 8064,
|
18 |
+
"max_position_embeddings": 65536,
|
19 |
+
"mlp_only_layers": [],
|
20 |
+
"model_type": "Klear",
|
21 |
+
"moe_aux_loss_coeff": 0.0001,
|
22 |
+
"moe_intermediate_size": 896,
|
23 |
+
"n_shared_experts": 1,
|
24 |
+
"norm_topk_prob": true,
|
25 |
+
"num_attention_heads": 32,
|
26 |
+
"num_experts": 256,
|
27 |
+
"num_experts_per_tok": 8,
|
28 |
+
"num_hidden_layers": 32,
|
29 |
+
"num_key_value_heads": 4,
|
30 |
+
"output_router_logits": false,
|
31 |
+
"quantization": {
|
32 |
+
"group_size": 64,
|
33 |
+
"bits": 3,
|
34 |
+
"mode": "affine"
|
35 |
+
},
|
36 |
+
"quantization_config": {
|
37 |
+
"group_size": 64,
|
38 |
+
"bits": 3,
|
39 |
+
"mode": "affine"
|
40 |
+
},
|
41 |
+
"rms_norm_eps": 1e-05,
|
42 |
+
"rope_scaling": null,
|
43 |
+
"rope_theta": 500000.0,
|
44 |
+
"routed_scaling_factor": 2.5,
|
45 |
+
"router_aux_loss_coef": 0.001,
|
46 |
+
"sliding_window": null,
|
47 |
+
"tie_word_embeddings": false,
|
48 |
+
"transformers_version": "4.56.0",
|
49 |
+
"use_cache": true,
|
50 |
+
"use_sliding_window": false,
|
51 |
+
"vocab_size": 151936
|
52 |
+
}
|
configuration_klear.py
ADDED
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
2 |
+
# This file was automatically generated from src/transformers/models/Klear/modular_klear.py.
|
3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
5 |
+
# modular_klear.py file directly. One of our CI enforces this.
|
6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
7 |
+
|
8 |
+
|
9 |
+
from transformers.configuration_utils import PretrainedConfig
|
10 |
+
from transformers.modeling_rope_utils import rope_config_validation
|
11 |
+
|
12 |
+
|
13 |
+
class KlearConfig(PretrainedConfig):
|
14 |
+
r"""
|
15 |
+
This is the configuration class to store the configuration of a [`KlearModel`]. It is used to instantiate a
|
16 |
+
Klear model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
17 |
+
with the defaults will yield a similar configuration to that of [Klear-kwaii/Klear-MoE](https://huggingface.co/Klear/Klear-MoE).
|
18 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
19 |
+
documentation from [`PretrainedConfig`] for more information.
|
20 |
+
Args:
|
21 |
+
vocab_size (`int`, *optional*, defaults to 151936):
|
22 |
+
Vocabulary size of the Klear model. Defines the number of different tokens that can be represented by the
|
23 |
+
`inputs_ids` passed when calling [`KlearModel`]
|
24 |
+
hidden_size (`int`, *optional*, defaults to 2048):
|
25 |
+
Dimension of the hidden representations.
|
26 |
+
intermediate_size (`int`, *optional*, defaults to 6144):
|
27 |
+
Dimension of the MLP representations.
|
28 |
+
num_hidden_layers (`int`, *optional*, defaults to 24):
|
29 |
+
Number of hidden layers in the Transformer encoder.
|
30 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
31 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
32 |
+
num_key_value_heads (`int`, *optional*, defaults to 4):
|
33 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
34 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
35 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
36 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
37 |
+
by meanpooling all the original heads within that group. For more details, check out [this
|
38 |
+
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
|
39 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
40 |
+
The non-linear activation function (function or string) in the decoder.
|
41 |
+
max_position_embeddings (`int`, *optional*, defaults to 32768):
|
42 |
+
The maximum sequence length that this model might ever be used with.
|
43 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
44 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
45 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
46 |
+
The epsilon used by the rms normalization layers.
|
47 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
48 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
49 |
+
relevant if `config.is_decoder=True`.
|
50 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
51 |
+
Whether the model's input and output word embeddings should be tied.
|
52 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
53 |
+
The base period of the RoPE embeddings.
|
54 |
+
rope_scaling (`Dict`, *optional*):
|
55 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
|
56 |
+
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
|
57 |
+
accordingly.
|
58 |
+
Expected contents:
|
59 |
+
`rope_type` (`str`):
|
60 |
+
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
|
61 |
+
'llama3'], with 'default' being the original RoPE implementation.
|
62 |
+
`factor` (`float`, *optional*):
|
63 |
+
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
|
64 |
+
most scaling types, a `factor` of x will enable the model to handle sequences of length x *
|
65 |
+
original maximum pre-trained length.
|
66 |
+
`original_max_position_embeddings` (`int`, *optional*):
|
67 |
+
Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
|
68 |
+
pretraining.
|
69 |
+
`attention_factor` (`float`, *optional*):
|
70 |
+
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
71 |
+
computation. If unspecified, it defaults to value recommended by the implementation, using the
|
72 |
+
`factor` field to infer the suggested value.
|
73 |
+
`beta_fast` (`float`, *optional*):
|
74 |
+
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
75 |
+
ramp function. If unspecified, it defaults to 32.
|
76 |
+
`beta_slow` (`float`, *optional*):
|
77 |
+
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
78 |
+
ramp function. If unspecified, it defaults to 1.
|
79 |
+
`short_factor` (`list[float]`, *optional*):
|
80 |
+
Only used with 'longrope'. The scaling factor to be applied to short contexts (<
|
81 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
82 |
+
size divided by the number of attention heads divided by 2
|
83 |
+
`long_factor` (`list[float]`, *optional*):
|
84 |
+
Only used with 'longrope'. The scaling factor to be applied to long contexts (<
|
85 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
86 |
+
size divided by the number of attention heads divided by 2
|
87 |
+
`low_freq_factor` (`float`, *optional*):
|
88 |
+
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
89 |
+
`high_freq_factor` (`float`, *optional*):
|
90 |
+
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
91 |
+
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
|
92 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
93 |
+
use_sliding_window (`bool`, *optional*, defaults to `False`):
|
94 |
+
Whether to use sliding window attention.
|
95 |
+
sliding_window (`int`, *optional*, defaults to 4096):
|
96 |
+
Sliding window attention (SWA) window size. If not specified, will default to `4096`.
|
97 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
98 |
+
The dropout ratio for the attention probabilities.
|
99 |
+
decoder_sparse_step (`int`, *optional*, defaults to 1):
|
100 |
+
The frequency of the MoE layer.
|
101 |
+
moe_intermediate_size (`int`, *optional*, defaults to 768):
|
102 |
+
Intermediate size of the routed expert.
|
103 |
+
num_experts_per_tok (`int`, *optional*, defaults to 8):
|
104 |
+
Number of selected experts.
|
105 |
+
num_experts (`int`, *optional*, defaults to 128):
|
106 |
+
Number of routed experts.
|
107 |
+
norm_topk_prob (`bool`, *optional*, defaults to `False`):
|
108 |
+
Whether to normalize the topk probabilities.
|
109 |
+
output_router_logits (`bool`, *optional*, defaults to `False`):
|
110 |
+
Whether or not the router logits should be returned by the model. Enabling this will also
|
111 |
+
allow the model to output the auxiliary loss, including load balancing loss and router z-loss.
|
112 |
+
router_aux_loss_coef (`float`, *optional*, defaults to 0.001):
|
113 |
+
The aux loss factor for the total loss.
|
114 |
+
mlp_only_layers (`list[int]`, *optional*, defaults to `[]`):
|
115 |
+
Indicate which layers use KlearMLP rather than KlearSparseMoeBlock
|
116 |
+
The list contains layer index, from 0 to num_layers-1 if we have num_layers layers
|
117 |
+
If `mlp_only_layers` is empty, `decoder_sparse_step` is used to determine the sparsity.
|
118 |
+
```python
|
119 |
+
>>> from transformers import KlearModel, KlearConfig
|
120 |
+
>>> # Initializing a Klear style configuration
|
121 |
+
>>> configuration = KlearConfig()
|
122 |
+
>>> # Initializing a model from the Klear-MoE" style configuration
|
123 |
+
>>> model = KlearModel(configuration)
|
124 |
+
>>> # Accessing the model configuration
|
125 |
+
>>> configuration = model.config
|
126 |
+
```"""
|
127 |
+
|
128 |
+
model_type = "Klear"
|
129 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
130 |
+
|
131 |
+
# Default tensor parallel plan for base model `Klear`
|
132 |
+
base_model_tp_plan = {
|
133 |
+
"layers.*.self_attn.q_proj": "colwise",
|
134 |
+
"layers.*.self_attn.k_proj": "colwise",
|
135 |
+
"layers.*.self_attn.v_proj": "colwise",
|
136 |
+
"layers.*.self_attn.o_proj": "rowwise",
|
137 |
+
"layers.*.mlp.experts.*.gate_proj": "colwise",
|
138 |
+
"layers.*.mlp.experts.*.up_proj": "colwise",
|
139 |
+
"layers.*.mlp.experts.*.down_proj": "rowwise",
|
140 |
+
"layers.*.mlp.gate_proj": "colwise",
|
141 |
+
"layers.*.mlp.up_proj": "colwise",
|
142 |
+
"layers.*.mlp.down_proj": "rowwise",
|
143 |
+
}
|
144 |
+
base_model_pp_plan = {
|
145 |
+
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
146 |
+
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
147 |
+
"norm": (["hidden_states"], ["hidden_states"]),
|
148 |
+
}
|
149 |
+
|
150 |
+
def __init__(
|
151 |
+
self,
|
152 |
+
vocab_size=151936,
|
153 |
+
hidden_size=2048,
|
154 |
+
intermediate_size=6144,
|
155 |
+
num_hidden_layers=24,
|
156 |
+
num_attention_heads=32,
|
157 |
+
num_key_value_heads=4,
|
158 |
+
hidden_act="silu",
|
159 |
+
max_position_embeddings=32768,
|
160 |
+
initializer_range=0.02,
|
161 |
+
rms_norm_eps=1e-6,
|
162 |
+
use_cache=True,
|
163 |
+
tie_word_embeddings=False,
|
164 |
+
rope_theta=10000.0,
|
165 |
+
rope_scaling=None,
|
166 |
+
attention_bias=False,
|
167 |
+
use_sliding_window=False,
|
168 |
+
sliding_window=4096,
|
169 |
+
attention_dropout=0.0,
|
170 |
+
decoder_sparse_step=1,
|
171 |
+
moe_intermediate_size=768,
|
172 |
+
num_experts_per_tok=8,
|
173 |
+
num_experts=128,
|
174 |
+
norm_topk_prob=True,
|
175 |
+
output_router_logits=False,
|
176 |
+
router_aux_loss_coef=0.001,
|
177 |
+
mlp_only_layers=None,
|
178 |
+
routed_scaling_factor=2.5,
|
179 |
+
n_shared_experts=1,
|
180 |
+
**kwargs,
|
181 |
+
):
|
182 |
+
super().__init__(
|
183 |
+
tie_word_embeddings=tie_word_embeddings,
|
184 |
+
**kwargs,
|
185 |
+
)
|
186 |
+
self.vocab_size = vocab_size
|
187 |
+
self.max_position_embeddings = max_position_embeddings
|
188 |
+
self.hidden_size = hidden_size
|
189 |
+
self.intermediate_size = intermediate_size
|
190 |
+
self.num_hidden_layers = num_hidden_layers
|
191 |
+
self.num_attention_heads = num_attention_heads
|
192 |
+
self.use_sliding_window = use_sliding_window
|
193 |
+
self.sliding_window = sliding_window if use_sliding_window else None
|
194 |
+
|
195 |
+
self.num_key_value_heads = num_key_value_heads
|
196 |
+
self.hidden_act = hidden_act
|
197 |
+
self.initializer_range = initializer_range
|
198 |
+
self.rms_norm_eps = rms_norm_eps
|
199 |
+
self.use_cache = use_cache
|
200 |
+
self.rope_theta = rope_theta
|
201 |
+
self.rope_scaling = rope_scaling
|
202 |
+
self.attention_bias = attention_bias
|
203 |
+
self.attention_dropout = attention_dropout
|
204 |
+
# Validate the correctness of rotary position embeddings parameters
|
205 |
+
# BC: if there is a 'type' field, move it to 'rope_type'.
|
206 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
207 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
208 |
+
rope_config_validation(self)
|
209 |
+
|
210 |
+
# MoE arguments
|
211 |
+
self.decoder_sparse_step = decoder_sparse_step
|
212 |
+
self.moe_intermediate_size = moe_intermediate_size
|
213 |
+
self.num_experts_per_tok = num_experts_per_tok
|
214 |
+
self.num_experts = num_experts
|
215 |
+
self.norm_topk_prob = norm_topk_prob
|
216 |
+
self.output_router_logits = output_router_logits
|
217 |
+
self.router_aux_loss_coef = router_aux_loss_coef
|
218 |
+
self.mlp_only_layers = [] if mlp_only_layers is None else mlp_only_layers
|
219 |
+
|
220 |
+
self.routed_scaling_factor = routed_scaling_factor
|
221 |
+
self.n_shared_experts = n_shared_experts
|
222 |
+
|
223 |
+
|
224 |
+
__all__ = ["KlearConfig"]
|
generation_config.json
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"pad_token_id": 151643,
|
3 |
+
"do_sample": true,
|
4 |
+
"eos_token_id": [
|
5 |
+
151645,
|
6 |
+
151643
|
7 |
+
],
|
8 |
+
"repetition_penalty": 1.05,
|
9 |
+
"temperature": 0.6,
|
10 |
+
"top_p": 0.95,
|
11 |
+
"top_k": 40
|
12 |
+
}
|
merges.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
model-00001-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:856a3de4812c47d3221116955aa0f79108641489700b9acab5ccc82ba0c99a44
|
3 |
+
size 5332780155
|
model-00002-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:23ced0040b18d089bf7eceb6a703e9cf4a0d77a1288b76a9e7de2c7937ed197d
|
3 |
+
size 5368445970
|
model-00003-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:22329084265f7a129387b7b31cc3e1534c92b7f1eb90056e7a4f778ff0f8a452
|
3 |
+
size 5228427347
|
model-00004-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0ad97708e7cdd808af82d17f5d92923ba72722ce5b717ed941e9a25ae311834f
|
3 |
+
size 4289675902
|
model.safetensors.index.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
modeling_klear.py
ADDED
@@ -0,0 +1,682 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
2 |
+
# This file was automatically generated from src/transformers/models/klear/modular_klear.py.
|
3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
5 |
+
# modular_klear.py file directly. One of our CI enforces this.
|
6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
7 |
+
|
8 |
+
from typing import Callable, Optional, Union
|
9 |
+
|
10 |
+
import torch
|
11 |
+
import torch.nn.functional as F
|
12 |
+
from torch import nn
|
13 |
+
|
14 |
+
from transformers.activations import ACT2FN
|
15 |
+
from transformers.cache_utils import Cache, DynamicCache
|
16 |
+
from transformers.generation import GenerationMixin
|
17 |
+
from transformers.integrations import use_kernel_forward_from_hub
|
18 |
+
from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
|
19 |
+
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
20 |
+
from transformers.modeling_layers import (
|
21 |
+
GenericForQuestionAnswering,
|
22 |
+
GenericForSequenceClassification,
|
23 |
+
GenericForTokenClassification,
|
24 |
+
GradientCheckpointingLayer,
|
25 |
+
)
|
26 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
27 |
+
from transformers.modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
|
28 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
29 |
+
from transformers.processing_utils import Unpack
|
30 |
+
from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
|
31 |
+
from transformers.utils.generic import OutputRecorder, check_model_inputs
|
32 |
+
from .configuration_klear import KlearConfig
|
33 |
+
|
34 |
+
|
35 |
+
def rotate_half(x):
|
36 |
+
"""Rotates half the hidden dims of the input."""
|
37 |
+
x1 = x[..., : x.shape[-1] // 2]
|
38 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
39 |
+
return torch.cat((-x2, x1), dim=-1)
|
40 |
+
|
41 |
+
|
42 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
43 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
44 |
+
Args:
|
45 |
+
q (`torch.Tensor`): The query tensor.
|
46 |
+
k (`torch.Tensor`): The key tensor.
|
47 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
48 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
49 |
+
position_ids (`torch.Tensor`, *optional*):
|
50 |
+
Deprecated and unused.
|
51 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
52 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
53 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
54 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
55 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
56 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
57 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
58 |
+
Returns:
|
59 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
60 |
+
"""
|
61 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
62 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
63 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
64 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
65 |
+
return q_embed, k_embed
|
66 |
+
|
67 |
+
|
68 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
69 |
+
"""
|
70 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
71 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
72 |
+
"""
|
73 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
74 |
+
if n_rep == 1:
|
75 |
+
return hidden_states
|
76 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
77 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
78 |
+
|
79 |
+
|
80 |
+
def eager_attention_forward(
|
81 |
+
module: nn.Module,
|
82 |
+
query: torch.Tensor,
|
83 |
+
key: torch.Tensor,
|
84 |
+
value: torch.Tensor,
|
85 |
+
attention_mask: Optional[torch.Tensor],
|
86 |
+
scaling: float,
|
87 |
+
dropout: float = 0.0,
|
88 |
+
**kwargs: Unpack[TransformersKwargs],
|
89 |
+
):
|
90 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
91 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
92 |
+
|
93 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
94 |
+
if attention_mask is not None:
|
95 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
96 |
+
attn_weights = attn_weights + causal_mask
|
97 |
+
|
98 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
99 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
100 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
101 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
102 |
+
|
103 |
+
return attn_output, attn_weights
|
104 |
+
|
105 |
+
|
106 |
+
class KlearAttention(nn.Module):
|
107 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
108 |
+
|
109 |
+
def __init__(self, config: KlearConfig, layer_idx: int):
|
110 |
+
super().__init__()
|
111 |
+
self.config = config
|
112 |
+
self.layer_idx = layer_idx
|
113 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
114 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
115 |
+
self.scaling = self.head_dim**-0.5
|
116 |
+
self.attention_dropout = config.attention_dropout
|
117 |
+
self.is_causal = True
|
118 |
+
|
119 |
+
self.q_proj = nn.Linear(
|
120 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
121 |
+
)
|
122 |
+
self.k_proj = nn.Linear(
|
123 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
124 |
+
)
|
125 |
+
self.v_proj = nn.Linear(
|
126 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
127 |
+
)
|
128 |
+
self.o_proj = nn.Linear(
|
129 |
+
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
|
130 |
+
)
|
131 |
+
self.q_norm = KlearRMSNorm(self.head_dim, eps=config.rms_norm_eps) # unlike olmo, only on the head dim!
|
132 |
+
self.k_norm = KlearRMSNorm(self.head_dim, eps=config.rms_norm_eps) # thus post q_norm does not need reshape
|
133 |
+
self.sliding_window = getattr(config, "sliding_window", None)
|
134 |
+
|
135 |
+
def forward(
|
136 |
+
self,
|
137 |
+
hidden_states: torch.Tensor,
|
138 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
139 |
+
attention_mask: Optional[torch.Tensor],
|
140 |
+
past_key_value: Optional[Cache] = None,
|
141 |
+
cache_position: Optional[torch.LongTensor] = None,
|
142 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
143 |
+
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
|
144 |
+
input_shape = hidden_states.shape[:-1]
|
145 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
146 |
+
|
147 |
+
query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
148 |
+
key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
149 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
150 |
+
|
151 |
+
cos, sin = position_embeddings
|
152 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
153 |
+
|
154 |
+
if past_key_value is not None:
|
155 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
156 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
157 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
158 |
+
|
159 |
+
attention_interface: Callable = eager_attention_forward
|
160 |
+
if self.config._attn_implementation != "eager":
|
161 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
162 |
+
|
163 |
+
attn_output, attn_weights = attention_interface(
|
164 |
+
self,
|
165 |
+
query_states,
|
166 |
+
key_states,
|
167 |
+
value_states,
|
168 |
+
attention_mask,
|
169 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
170 |
+
scaling=self.scaling,
|
171 |
+
sliding_window=self.sliding_window, # diff with Llama
|
172 |
+
**kwargs,
|
173 |
+
)
|
174 |
+
|
175 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
176 |
+
attn_output = self.o_proj(attn_output)
|
177 |
+
return attn_output, attn_weights
|
178 |
+
|
179 |
+
|
180 |
+
class KlearMLP(nn.Module):
|
181 |
+
def __init__(self, config, intermediate_size=None):
|
182 |
+
super().__init__()
|
183 |
+
self.config = config
|
184 |
+
self.hidden_size = config.hidden_size
|
185 |
+
self.intermediate_size = intermediate_size if intermediate_size is not None else config.intermediate_size
|
186 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
187 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
188 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
189 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
190 |
+
|
191 |
+
def forward(self, x):
|
192 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
193 |
+
return down_proj
|
194 |
+
|
195 |
+
|
196 |
+
class KlearSparseMoeBlock(nn.Module):
|
197 |
+
def __init__(self, config):
|
198 |
+
super().__init__()
|
199 |
+
self.config = config
|
200 |
+
self.num_experts = config.num_experts
|
201 |
+
self.top_k = config.num_experts_per_tok
|
202 |
+
self.norm_topk_prob = config.norm_topk_prob
|
203 |
+
|
204 |
+
# router
|
205 |
+
self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
|
206 |
+
self.experts = nn.ModuleList(
|
207 |
+
[KlearMLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(config.num_experts)]
|
208 |
+
)
|
209 |
+
self.shared_experts = KlearMLP(
|
210 |
+
config=config, intermediate_size=config.moe_intermediate_size * config.n_shared_experts
|
211 |
+
)
|
212 |
+
|
213 |
+
self.coefficient = nn.Linear(config.hidden_size, 2)
|
214 |
+
self.register_buffer("expert_bias", torch.zeros(self.num_experts, dtype=torch.float32))
|
215 |
+
|
216 |
+
def forward(self, hidden_states):
|
217 |
+
residuals = hidden_states
|
218 |
+
batch_size, sequence_length, hidden_dim = hidden_states.shape
|
219 |
+
hidden_states = hidden_states.view(-1, hidden_dim)
|
220 |
+
# router_logits: (batch * sequence_length, n_experts)
|
221 |
+
router_logits = nn.functional.linear(hidden_states.to(torch.float32), self.gate.weight.to(torch.float32))
|
222 |
+
|
223 |
+
routing_weights = F.sigmoid(router_logits)
|
224 |
+
ori_routing_weights = routing_weights
|
225 |
+
|
226 |
+
# using bias
|
227 |
+
biasd_routing_weights = routing_weights + self.expert_bias.unsqueeze(0)
|
228 |
+
_, selected_experts = torch.topk(biasd_routing_weights, self.top_k, dim=-1)
|
229 |
+
|
230 |
+
# Extract corresponding original probabilities
|
231 |
+
ori_routing_weights = torch.gather(ori_routing_weights, dim=-1, index=selected_experts)
|
232 |
+
|
233 |
+
if self.norm_topk_prob: # only diff with mixtral sparse moe block!
|
234 |
+
ori_routing_weights /= ori_routing_weights.sum(dim=-1, keepdim=True)
|
235 |
+
# we cast back to the input dtype
|
236 |
+
ori_routing_weights = ori_routing_weights.to(hidden_states.dtype)
|
237 |
+
|
238 |
+
final_hidden_states = torch.zeros(
|
239 |
+
(batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
|
240 |
+
)
|
241 |
+
|
242 |
+
# One hot encode the selected experts to create an expert mask
|
243 |
+
# this will be used to easily index which expert is going to be sollicitated
|
244 |
+
expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
|
245 |
+
|
246 |
+
# Loop over all available experts in the model and perform the computation on each expert
|
247 |
+
expert_hitted = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
|
248 |
+
for expert_idx in expert_hitted:
|
249 |
+
expert_layer = self.experts[expert_idx]
|
250 |
+
idx, top_x = torch.where(expert_mask[expert_idx].squeeze(0))
|
251 |
+
|
252 |
+
# Index the correct hidden states and compute the expert hidden state for
|
253 |
+
# the current expert. We need to make sure to multiply the output hidden
|
254 |
+
# states by `ori_routing_weights` on the corresponding tokens (top-1 and top-2)
|
255 |
+
current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
|
256 |
+
current_hidden_states = expert_layer(current_state) * ori_routing_weights[top_x, idx, None]
|
257 |
+
|
258 |
+
# However `index_add_` only support torch tensors for indexing so we'll use
|
259 |
+
# the `top_x` tensor here.
|
260 |
+
final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
|
261 |
+
final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
|
262 |
+
|
263 |
+
coef = self.coefficient(residuals).softmax(dim=-1)
|
264 |
+
final_hidden_states = final_hidden_states * coef[..., :1] + self.shared_experts(residuals) * coef[..., 1:]
|
265 |
+
|
266 |
+
return final_hidden_states, router_logits
|
267 |
+
|
268 |
+
|
269 |
+
@use_kernel_forward_from_hub("RMSNorm")
|
270 |
+
class KlearRMSNorm(nn.Module):
|
271 |
+
def __init__(self, hidden_size, eps=1e-6):
|
272 |
+
"""
|
273 |
+
KlearRMSNorm is equivalent to T5LayerNorm
|
274 |
+
"""
|
275 |
+
super().__init__()
|
276 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
277 |
+
self.variance_epsilon = eps
|
278 |
+
|
279 |
+
def forward(self, hidden_states):
|
280 |
+
input_dtype = hidden_states.dtype
|
281 |
+
hidden_states = hidden_states.to(torch.float32)
|
282 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
283 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
284 |
+
return self.weight * hidden_states.to(input_dtype)
|
285 |
+
|
286 |
+
def extra_repr(self):
|
287 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
288 |
+
|
289 |
+
|
290 |
+
class KlearDecoderLayer(GradientCheckpointingLayer):
|
291 |
+
def __init__(self, config: KlearConfig, layer_idx: int):
|
292 |
+
super().__init__()
|
293 |
+
self.hidden_size = config.hidden_size
|
294 |
+
|
295 |
+
self.self_attn = KlearAttention(config, layer_idx)
|
296 |
+
|
297 |
+
if (layer_idx not in config.mlp_only_layers) and (
|
298 |
+
config.num_experts > 0 and (layer_idx + 1) % config.decoder_sparse_step == 0
|
299 |
+
):
|
300 |
+
self.mlp = KlearSparseMoeBlock(config)
|
301 |
+
else:
|
302 |
+
self.mlp = KlearMLP(config, intermediate_size=config.intermediate_size)
|
303 |
+
|
304 |
+
self.input_layernorm = KlearRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
305 |
+
self.post_attention_layernorm = KlearRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
306 |
+
|
307 |
+
def forward(
|
308 |
+
self,
|
309 |
+
hidden_states: torch.Tensor,
|
310 |
+
attention_mask: Optional[torch.Tensor] = None,
|
311 |
+
position_ids: Optional[torch.LongTensor] = None,
|
312 |
+
past_key_value: Optional[tuple[torch.Tensor]] = None,
|
313 |
+
output_attentions: Optional[bool] = False,
|
314 |
+
output_router_logits: Optional[bool] = False,
|
315 |
+
use_cache: Optional[bool] = False,
|
316 |
+
cache_position: Optional[torch.LongTensor] = None,
|
317 |
+
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
318 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
319 |
+
) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
320 |
+
"""
|
321 |
+
Args:
|
322 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
323 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
324 |
+
`(batch, sequence_length)` where padding elements are indicated by 0.
|
325 |
+
output_attentions (`bool`, *optional*):
|
326 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
327 |
+
returned tensors for more detail.
|
328 |
+
output_router_logits (`bool`, *optional*):
|
329 |
+
Whether or not to return the logits of all the routers. They are useful for computing the router loss,
|
330 |
+
and should not be returned during inference.
|
331 |
+
use_cache (`bool`, *optional*):
|
332 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
333 |
+
(see `past_key_values`).
|
334 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
335 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
336 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
337 |
+
position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
|
338 |
+
Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
|
339 |
+
with `head_dim` being the embedding dimension of each attention head.
|
340 |
+
kwargs (`dict`, *optional*):
|
341 |
+
Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
|
342 |
+
into the model
|
343 |
+
"""
|
344 |
+
|
345 |
+
residual = hidden_states
|
346 |
+
hidden_states = self.input_layernorm(hidden_states)
|
347 |
+
|
348 |
+
# Self Attention
|
349 |
+
hidden_states, self_attn_weights = self.self_attn(
|
350 |
+
hidden_states=hidden_states,
|
351 |
+
attention_mask=attention_mask,
|
352 |
+
position_ids=position_ids,
|
353 |
+
past_key_value=past_key_value,
|
354 |
+
output_attentions=output_attentions,
|
355 |
+
use_cache=use_cache,
|
356 |
+
cache_position=cache_position,
|
357 |
+
position_embeddings=position_embeddings,
|
358 |
+
**kwargs,
|
359 |
+
)
|
360 |
+
hidden_states = residual + hidden_states
|
361 |
+
|
362 |
+
# Fully Connected
|
363 |
+
residual = hidden_states
|
364 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
365 |
+
|
366 |
+
hidden_states = self.mlp(hidden_states)
|
367 |
+
if isinstance(hidden_states, tuple):
|
368 |
+
hidden_states, router_logits = hidden_states
|
369 |
+
else:
|
370 |
+
router_logits = None
|
371 |
+
|
372 |
+
hidden_states = residual + hidden_states
|
373 |
+
|
374 |
+
outputs = (hidden_states,)
|
375 |
+
|
376 |
+
if output_attentions:
|
377 |
+
outputs += (self_attn_weights,)
|
378 |
+
|
379 |
+
if output_router_logits:
|
380 |
+
outputs += (router_logits,)
|
381 |
+
|
382 |
+
return outputs
|
383 |
+
|
384 |
+
|
385 |
+
class KlearRotaryEmbedding(nn.Module):
|
386 |
+
def __init__(self, config: KlearConfig, device=None):
|
387 |
+
super().__init__()
|
388 |
+
# BC: "rope_type" was originally "type"
|
389 |
+
if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
|
390 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
391 |
+
else:
|
392 |
+
self.rope_type = "default"
|
393 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
394 |
+
self.original_max_seq_len = config.max_position_embeddings
|
395 |
+
|
396 |
+
self.config = config
|
397 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
398 |
+
|
399 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
400 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
401 |
+
self.original_inv_freq = self.inv_freq
|
402 |
+
|
403 |
+
@torch.no_grad()
|
404 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
405 |
+
def forward(self, x, position_ids):
|
406 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
407 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
408 |
+
|
409 |
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
410 |
+
with torch.autocast(device_type=device_type, enabled=False): # Force float32
|
411 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
412 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
413 |
+
cos = emb.cos() * self.attention_scaling
|
414 |
+
sin = emb.sin() * self.attention_scaling
|
415 |
+
|
416 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
417 |
+
|
418 |
+
|
419 |
+
@auto_docstring
|
420 |
+
class KlearPreTrainedModel(PreTrainedModel):
|
421 |
+
config: KlearConfig
|
422 |
+
base_model_prefix = "model"
|
423 |
+
supports_gradient_checkpointing = True
|
424 |
+
_no_split_modules = ["KlearDecoderLayer"]
|
425 |
+
_skip_keys_device_placement = ["past_key_values"]
|
426 |
+
_supports_flash_attn = True
|
427 |
+
_supports_sdpa = True
|
428 |
+
_supports_flex_attn = True
|
429 |
+
_can_compile_fullgraph = False # MoE models don't work with torch.compile (`torch.where(condition)` not supported)
|
430 |
+
_supports_attention_backend = True
|
431 |
+
_can_record_outputs = {
|
432 |
+
"router_logits": OutputRecorder(KlearSparseMoeBlock, index=1),
|
433 |
+
"hidden_states": KlearDecoderLayer,
|
434 |
+
"attentions": KlearAttention,
|
435 |
+
}
|
436 |
+
|
437 |
+
|
438 |
+
@auto_docstring
|
439 |
+
class KlearModel(KlearPreTrainedModel):
|
440 |
+
def __init__(self, config: KlearConfig):
|
441 |
+
super().__init__(config)
|
442 |
+
self.padding_idx = config.pad_token_id
|
443 |
+
self.vocab_size = config.vocab_size
|
444 |
+
|
445 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
446 |
+
self.layers = nn.ModuleList(
|
447 |
+
[KlearDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
448 |
+
)
|
449 |
+
self.norm = KlearRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
450 |
+
self.rotary_emb = KlearRotaryEmbedding(config=config)
|
451 |
+
self.gradient_checkpointing = False
|
452 |
+
|
453 |
+
# Initialize weights and apply final processing
|
454 |
+
self.post_init()
|
455 |
+
|
456 |
+
@check_model_inputs
|
457 |
+
@auto_docstring
|
458 |
+
def forward(
|
459 |
+
self,
|
460 |
+
input_ids: Optional[torch.LongTensor] = None,
|
461 |
+
attention_mask: Optional[torch.Tensor] = None,
|
462 |
+
position_ids: Optional[torch.LongTensor] = None,
|
463 |
+
past_key_values: Optional[list[torch.FloatTensor]] = None,
|
464 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
465 |
+
use_cache: Optional[bool] = None,
|
466 |
+
output_attentions: Optional[bool] = None,
|
467 |
+
output_hidden_states: Optional[bool] = None,
|
468 |
+
output_router_logits: Optional[bool] = None,
|
469 |
+
cache_position: Optional[torch.LongTensor] = None,
|
470 |
+
**kwargs: Unpack[TransformersKwargs],
|
471 |
+
) -> MoeModelOutputWithPast:
|
472 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
473 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
474 |
+
|
475 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
476 |
+
output_router_logits = (
|
477 |
+
output_router_logits if output_router_logits is not None else self.config.output_router_logits
|
478 |
+
)
|
479 |
+
output_hidden_states = (
|
480 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
481 |
+
)
|
482 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
483 |
+
|
484 |
+
if use_cache and past_key_values is None:
|
485 |
+
past_key_values = DynamicCache()
|
486 |
+
|
487 |
+
if inputs_embeds is None:
|
488 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
489 |
+
|
490 |
+
if cache_position is None:
|
491 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
492 |
+
cache_position = torch.arange(
|
493 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
494 |
+
)
|
495 |
+
if position_ids is None:
|
496 |
+
position_ids = cache_position.unsqueeze(0)
|
497 |
+
|
498 |
+
mask_function = create_causal_mask if self.config.sliding_window is None else create_sliding_window_causal_mask
|
499 |
+
causal_mask = mask_function(
|
500 |
+
config=self.config,
|
501 |
+
input_embeds=inputs_embeds,
|
502 |
+
attention_mask=attention_mask,
|
503 |
+
cache_position=cache_position,
|
504 |
+
past_key_values=past_key_values,
|
505 |
+
position_ids=position_ids,
|
506 |
+
)
|
507 |
+
|
508 |
+
hidden_states = inputs_embeds
|
509 |
+
|
510 |
+
# create position embeddings to be shared across the decoder layers
|
511 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
512 |
+
|
513 |
+
# decoder layers
|
514 |
+
all_hidden_states = () if output_hidden_states else None
|
515 |
+
all_self_attns = () if output_attentions else None
|
516 |
+
all_router_logits = () if output_router_logits else None
|
517 |
+
|
518 |
+
for decoder_layer in self.layers:
|
519 |
+
if output_hidden_states:
|
520 |
+
all_hidden_states += (hidden_states,)
|
521 |
+
|
522 |
+
layer_outputs = decoder_layer(
|
523 |
+
hidden_states,
|
524 |
+
attention_mask=causal_mask,
|
525 |
+
position_ids=position_ids,
|
526 |
+
past_key_value=past_key_values,
|
527 |
+
output_attentions=output_attentions,
|
528 |
+
output_router_logits=output_router_logits,
|
529 |
+
use_cache=use_cache,
|
530 |
+
cache_position=cache_position,
|
531 |
+
position_embeddings=position_embeddings,
|
532 |
+
**kwargs,
|
533 |
+
)
|
534 |
+
|
535 |
+
hidden_states = layer_outputs[0]
|
536 |
+
|
537 |
+
if output_attentions:
|
538 |
+
all_self_attns += (layer_outputs[1],)
|
539 |
+
|
540 |
+
if output_router_logits:
|
541 |
+
all_router_logits += (layer_outputs[-1],)
|
542 |
+
|
543 |
+
hidden_states = self.norm(hidden_states)
|
544 |
+
|
545 |
+
return MoeModelOutputWithPast(
|
546 |
+
last_hidden_state=hidden_states,
|
547 |
+
past_key_values=past_key_values,
|
548 |
+
hidden_states=all_hidden_states,
|
549 |
+
attentions=all_self_attns,
|
550 |
+
router_logits=all_router_logits,
|
551 |
+
)
|
552 |
+
|
553 |
+
|
554 |
+
@auto_docstring
|
555 |
+
class KlearMoeForCausalLM(KlearPreTrainedModel, GenerationMixin):
|
556 |
+
_tied_weights_keys = ["lm_head.weight"]
|
557 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
558 |
+
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
559 |
+
|
560 |
+
def __init__(self, config):
|
561 |
+
super().__init__(config)
|
562 |
+
self.model = KlearModel(config)
|
563 |
+
self.vocab_size = config.vocab_size
|
564 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
565 |
+
self.router_aux_loss_coef = config.router_aux_loss_coef
|
566 |
+
self.num_experts = config.num_experts
|
567 |
+
self.num_experts_per_tok = config.num_experts_per_tok
|
568 |
+
self.moe_aux_loss_coeff = getattr(config, "moe_aux_loss_coeff", 1.0)
|
569 |
+
|
570 |
+
# Initialize weights and apply final processing
|
571 |
+
self.post_init()
|
572 |
+
|
573 |
+
def set_decoder(self, decoder):
|
574 |
+
self.model = decoder
|
575 |
+
|
576 |
+
def get_decoder(self):
|
577 |
+
return self.model
|
578 |
+
|
579 |
+
@can_return_tuple
|
580 |
+
@auto_docstring
|
581 |
+
def forward(
|
582 |
+
self,
|
583 |
+
input_ids: Optional[torch.LongTensor] = None,
|
584 |
+
attention_mask: Optional[torch.Tensor] = None,
|
585 |
+
position_ids: Optional[torch.LongTensor] = None,
|
586 |
+
past_key_values: Optional[list[torch.FloatTensor]] = None,
|
587 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
588 |
+
labels: Optional[torch.LongTensor] = None,
|
589 |
+
use_cache: Optional[bool] = None,
|
590 |
+
output_attentions: Optional[bool] = None,
|
591 |
+
output_hidden_states: Optional[bool] = None,
|
592 |
+
output_router_logits: Optional[bool] = None,
|
593 |
+
cache_position: Optional[torch.LongTensor] = None,
|
594 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
595 |
+
**kwargs: Unpack[TransformersKwargs],
|
596 |
+
) -> MoeCausalLMOutputWithPast:
|
597 |
+
r"""
|
598 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
599 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
600 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
601 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
602 |
+
Example:
|
603 |
+
```python
|
604 |
+
>>> from transformers import AutoTokenizer, KlearMoeForCausalLM
|
605 |
+
>>> model = KlearMoeForCausalLM.from_pretrained("Klear-kwaii/Klear-MoE")
|
606 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("Klear-kwaii/Klear-MoE")
|
607 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
608 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
609 |
+
>>> # Generate
|
610 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
611 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
612 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
613 |
+
```"""
|
614 |
+
|
615 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
616 |
+
output_router_logits = (
|
617 |
+
output_router_logits if output_router_logits is not None else self.config.output_router_logits
|
618 |
+
)
|
619 |
+
|
620 |
+
output_hidden_states = (
|
621 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
622 |
+
)
|
623 |
+
|
624 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
625 |
+
outputs: MoeModelOutputWithPast = self.model(
|
626 |
+
input_ids=input_ids,
|
627 |
+
attention_mask=attention_mask,
|
628 |
+
position_ids=position_ids,
|
629 |
+
past_key_values=past_key_values,
|
630 |
+
inputs_embeds=inputs_embeds,
|
631 |
+
use_cache=use_cache,
|
632 |
+
output_attentions=output_attentions,
|
633 |
+
output_hidden_states=output_hidden_states,
|
634 |
+
output_router_logits=output_router_logits,
|
635 |
+
cache_position=cache_position,
|
636 |
+
**kwargs,
|
637 |
+
)
|
638 |
+
|
639 |
+
hidden_states = outputs.last_hidden_state
|
640 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
641 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
642 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
643 |
+
|
644 |
+
loss = None
|
645 |
+
if labels is not None:
|
646 |
+
loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
|
647 |
+
|
648 |
+
aux_loss = None
|
649 |
+
if output_router_logits:
|
650 |
+
pass
|
651 |
+
|
652 |
+
return MoeCausalLMOutputWithPast(
|
653 |
+
loss=loss,
|
654 |
+
aux_loss=aux_loss,
|
655 |
+
logits=logits,
|
656 |
+
past_key_values=outputs.past_key_values,
|
657 |
+
hidden_states=outputs.hidden_states,
|
658 |
+
attentions=outputs.attentions,
|
659 |
+
router_logits=outputs.router_logits,
|
660 |
+
)
|
661 |
+
|
662 |
+
|
663 |
+
class KlearForSequenceClassification(GenericForSequenceClassification, KlearPreTrainedModel):
|
664 |
+
pass
|
665 |
+
|
666 |
+
|
667 |
+
class KlearForTokenClassification(GenericForTokenClassification, KlearPreTrainedModel):
|
668 |
+
pass
|
669 |
+
|
670 |
+
|
671 |
+
class KlearForQuestionAnswering(GenericForQuestionAnswering, KlearPreTrainedModel):
|
672 |
+
base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model`
|
673 |
+
|
674 |
+
|
675 |
+
__all__ = [
|
676 |
+
"KlearMoeForCausalLM",
|
677 |
+
"KlearForQuestionAnswering",
|
678 |
+
"KlearModel",
|
679 |
+
"KlearPreTrainedModel",
|
680 |
+
"KlearForSequenceClassification",
|
681 |
+
"KlearForTokenClassification",
|
682 |
+
]
|
special_tokens_map.json
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"additional_special_tokens": [
|
3 |
+
"<|im_start|>",
|
4 |
+
"<|im_end|>",
|
5 |
+
"<|object_ref_start|>",
|
6 |
+
"<|object_ref_end|>",
|
7 |
+
"<|box_start|>",
|
8 |
+
"<|box_end|>",
|
9 |
+
"<|quad_start|>",
|
10 |
+
"<|quad_end|>",
|
11 |
+
"<|vision_start|>",
|
12 |
+
"<|vision_end|>",
|
13 |
+
"<|vision_pad|>",
|
14 |
+
"<|image_pad|>",
|
15 |
+
"<|video_pad|>"
|
16 |
+
],
|
17 |
+
"eos_token": {
|
18 |
+
"content": "<|im_end|>",
|
19 |
+
"lstrip": false,
|
20 |
+
"normalized": false,
|
21 |
+
"rstrip": false,
|
22 |
+
"single_word": false
|
23 |
+
},
|
24 |
+
"pad_token": {
|
25 |
+
"content": "<|endoftext|>",
|
26 |
+
"lstrip": false,
|
27 |
+
"normalized": false,
|
28 |
+
"rstrip": false,
|
29 |
+
"single_word": false
|
30 |
+
}
|
31 |
+
}
|
tokenizer.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4
|
3 |
+
size 11422654
|
tokenizer_config.json
ADDED
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_bos_token": false,
|
3 |
+
"add_prefix_space": false,
|
4 |
+
"added_tokens_decoder": {
|
5 |
+
"151643": {
|
6 |
+
"content": "<|endoftext|>",
|
7 |
+
"lstrip": false,
|
8 |
+
"normalized": false,
|
9 |
+
"rstrip": false,
|
10 |
+
"single_word": false,
|
11 |
+
"special": true
|
12 |
+
},
|
13 |
+
"151644": {
|
14 |
+
"content": "<|im_start|>",
|
15 |
+
"lstrip": false,
|
16 |
+
"normalized": false,
|
17 |
+
"rstrip": false,
|
18 |
+
"single_word": false,
|
19 |
+
"special": true
|
20 |
+
},
|
21 |
+
"151645": {
|
22 |
+
"content": "<|im_end|>",
|
23 |
+
"lstrip": false,
|
24 |
+
"normalized": false,
|
25 |
+
"rstrip": false,
|
26 |
+
"single_word": false,
|
27 |
+
"special": true
|
28 |
+
},
|
29 |
+
"151646": {
|
30 |
+
"content": "<|object_ref_start|>",
|
31 |
+
"lstrip": false,
|
32 |
+
"normalized": false,
|
33 |
+
"rstrip": false,
|
34 |
+
"single_word": false,
|
35 |
+
"special": true
|
36 |
+
},
|
37 |
+
"151647": {
|
38 |
+
"content": "<|object_ref_end|>",
|
39 |
+
"lstrip": false,
|
40 |
+
"normalized": false,
|
41 |
+
"rstrip": false,
|
42 |
+
"single_word": false,
|
43 |
+
"special": true
|
44 |
+
},
|
45 |
+
"151648": {
|
46 |
+
"content": "<|box_start|>",
|
47 |
+
"lstrip": false,
|
48 |
+
"normalized": false,
|
49 |
+
"rstrip": false,
|
50 |
+
"single_word": false,
|
51 |
+
"special": true
|
52 |
+
},
|
53 |
+
"151649": {
|
54 |
+
"content": "<|box_end|>",
|
55 |
+
"lstrip": false,
|
56 |
+
"normalized": false,
|
57 |
+
"rstrip": false,
|
58 |
+
"single_word": false,
|
59 |
+
"special": true
|
60 |
+
},
|
61 |
+
"151650": {
|
62 |
+
"content": "<|quad_start|>",
|
63 |
+
"lstrip": false,
|
64 |
+
"normalized": false,
|
65 |
+
"rstrip": false,
|
66 |
+
"single_word": false,
|
67 |
+
"special": true
|
68 |
+
},
|
69 |
+
"151651": {
|
70 |
+
"content": "<|quad_end|>",
|
71 |
+
"lstrip": false,
|
72 |
+
"normalized": false,
|
73 |
+
"rstrip": false,
|
74 |
+
"single_word": false,
|
75 |
+
"special": true
|
76 |
+
},
|
77 |
+
"151652": {
|
78 |
+
"content": "<|vision_start|>",
|
79 |
+
"lstrip": false,
|
80 |
+
"normalized": false,
|
81 |
+
"rstrip": false,
|
82 |
+
"single_word": false,
|
83 |
+
"special": true
|
84 |
+
},
|
85 |
+
"151653": {
|
86 |
+
"content": "<|vision_end|>",
|
87 |
+
"lstrip": false,
|
88 |
+
"normalized": false,
|
89 |
+
"rstrip": false,
|
90 |
+
"single_word": false,
|
91 |
+
"special": true
|
92 |
+
},
|
93 |
+
"151654": {
|
94 |
+
"content": "<|vision_pad|>",
|
95 |
+
"lstrip": false,
|
96 |
+
"normalized": false,
|
97 |
+
"rstrip": false,
|
98 |
+
"single_word": false,
|
99 |
+
"special": true
|
100 |
+
},
|
101 |
+
"151655": {
|
102 |
+
"content": "<|image_pad|>",
|
103 |
+
"lstrip": false,
|
104 |
+
"normalized": false,
|
105 |
+
"rstrip": false,
|
106 |
+
"single_word": false,
|
107 |
+
"special": true
|
108 |
+
},
|
109 |
+
"151656": {
|
110 |
+
"content": "<|video_pad|>",
|
111 |
+
"lstrip": false,
|
112 |
+
"normalized": false,
|
113 |
+
"rstrip": false,
|
114 |
+
"single_word": false,
|
115 |
+
"special": true
|
116 |
+
},
|
117 |
+
"151657": {
|
118 |
+
"content": "<tool_call>",
|
119 |
+
"lstrip": false,
|
120 |
+
"normalized": false,
|
121 |
+
"rstrip": false,
|
122 |
+
"single_word": false,
|
123 |
+
"special": false
|
124 |
+
},
|
125 |
+
"151658": {
|
126 |
+
"content": "</tool_call>",
|
127 |
+
"lstrip": false,
|
128 |
+
"normalized": false,
|
129 |
+
"rstrip": false,
|
130 |
+
"single_word": false,
|
131 |
+
"special": false
|
132 |
+
},
|
133 |
+
"151659": {
|
134 |
+
"content": "<|fim_prefix|>",
|
135 |
+
"lstrip": false,
|
136 |
+
"normalized": false,
|
137 |
+
"rstrip": false,
|
138 |
+
"single_word": false,
|
139 |
+
"special": false
|
140 |
+
},
|
141 |
+
"151660": {
|
142 |
+
"content": "<|fim_middle|>",
|
143 |
+
"lstrip": false,
|
144 |
+
"normalized": false,
|
145 |
+
"rstrip": false,
|
146 |
+
"single_word": false,
|
147 |
+
"special": false
|
148 |
+
},
|
149 |
+
"151661": {
|
150 |
+
"content": "<|fim_suffix|>",
|
151 |
+
"lstrip": false,
|
152 |
+
"normalized": false,
|
153 |
+
"rstrip": false,
|
154 |
+
"single_word": false,
|
155 |
+
"special": false
|
156 |
+
},
|
157 |
+
"151662": {
|
158 |
+
"content": "<|fim_pad|>",
|
159 |
+
"lstrip": false,
|
160 |
+
"normalized": false,
|
161 |
+
"rstrip": false,
|
162 |
+
"single_word": false,
|
163 |
+
"special": false
|
164 |
+
},
|
165 |
+
"151663": {
|
166 |
+
"content": "<|repo_name|>",
|
167 |
+
"lstrip": false,
|
168 |
+
"normalized": false,
|
169 |
+
"rstrip": false,
|
170 |
+
"single_word": false,
|
171 |
+
"special": false
|
172 |
+
},
|
173 |
+
"151664": {
|
174 |
+
"content": "<|file_sep|>",
|
175 |
+
"lstrip": false,
|
176 |
+
"normalized": false,
|
177 |
+
"rstrip": false,
|
178 |
+
"single_word": false,
|
179 |
+
"special": false
|
180 |
+
},
|
181 |
+
"151665": {
|
182 |
+
"content": "<tool_response>",
|
183 |
+
"lstrip": false,
|
184 |
+
"normalized": false,
|
185 |
+
"rstrip": false,
|
186 |
+
"single_word": false,
|
187 |
+
"special": false
|
188 |
+
},
|
189 |
+
"151666": {
|
190 |
+
"content": "</tool_response>",
|
191 |
+
"lstrip": false,
|
192 |
+
"normalized": false,
|
193 |
+
"rstrip": false,
|
194 |
+
"single_word": false,
|
195 |
+
"special": false
|
196 |
+
},
|
197 |
+
"151667": {
|
198 |
+
"content": "<think>",
|
199 |
+
"lstrip": false,
|
200 |
+
"normalized": false,
|
201 |
+
"rstrip": false,
|
202 |
+
"single_word": false,
|
203 |
+
"special": false
|
204 |
+
},
|
205 |
+
"151668": {
|
206 |
+
"content": "</think>",
|
207 |
+
"lstrip": false,
|
208 |
+
"normalized": false,
|
209 |
+
"rstrip": false,
|
210 |
+
"single_word": false,
|
211 |
+
"special": false
|
212 |
+
}
|
213 |
+
},
|
214 |
+
"additional_special_tokens": [
|
215 |
+
"<|im_start|>",
|
216 |
+
"<|im_end|>",
|
217 |
+
"<|object_ref_start|>",
|
218 |
+
"<|object_ref_end|>",
|
219 |
+
"<|box_start|>",
|
220 |
+
"<|box_end|>",
|
221 |
+
"<|quad_start|>",
|
222 |
+
"<|quad_end|>",
|
223 |
+
"<|vision_start|>",
|
224 |
+
"<|vision_end|>",
|
225 |
+
"<|vision_pad|>",
|
226 |
+
"<|image_pad|>",
|
227 |
+
"<|video_pad|>"
|
228 |
+
],
|
229 |
+
"bos_token": null,
|
230 |
+
"clean_up_tokenization_spaces": false,
|
231 |
+
"eos_token": "<|im_end|>",
|
232 |
+
"errors": "replace",
|
233 |
+
"extra_special_tokens": {},
|
234 |
+
"model_max_length": 1048576,
|
235 |
+
"pad_token": "<|endoftext|>",
|
236 |
+
"split_special_tokens": false,
|
237 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
238 |
+
"unk_token": null
|
239 |
+
}
|
vocab.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|