Upload folder using huggingface_hub
Browse files- .gitattributes +1 -0
- checksums.txt +2 -0
- config.json +109 -0
- configuration_smallthinker.py +127 -0
- generation_config.json +9 -0
- merges.txt +0 -0
- model-00001-of-00002.safetensors +3 -0
- model-00002-of-00002.safetensors +3 -0
- model.safetensors.index.json +0 -0
- model_lm_head.pt +3 -0
- modeling_smallthinker.py +287 -0
- modular_smallthinker.py +407 -0
- tokenizer.json +3 -0
- tokenizer_config.json +207 -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
|
checksums.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
20be6f7b5051c683b6e0de1e9794ee1c5ff9cc8380f74246463eb34870061cda ./model-00002-of-00002.safetensors
|
| 2 |
+
6cefd487ca75d8283cb2d3c28a6cd66527455ea926cc39a07816a5715ed87992 ./model-00001-of-00002.safetensors
|
config.json
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"SmallThinkerForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"attention_dropout": 0.0,
|
| 6 |
+
"auto_map": {
|
| 7 |
+
"AutoConfig": "configuration_smallthinker.SmallThinkerConfig",
|
| 8 |
+
"AutoModel": "modeling_smallthinker.SmallThinkerForCausalLM",
|
| 9 |
+
"AutoModelForCausalLM": "modeling_smallthinker.SmallThinkerForCausalLM"
|
| 10 |
+
},
|
| 11 |
+
"bos_token_id": 151643,
|
| 12 |
+
"eos_token_id": [151643,151645],
|
| 13 |
+
"head_dim": 128,
|
| 14 |
+
"hidden_size": 1536,
|
| 15 |
+
"initializer_range": 0.02,
|
| 16 |
+
"max_length": null,
|
| 17 |
+
"max_position_embeddings": 32768,
|
| 18 |
+
"model_name": "smallthinker_4b_instruct",
|
| 19 |
+
"model_type": "smallthinker",
|
| 20 |
+
"moe_ffn_hidden_size": 768,
|
| 21 |
+
"moe_num_active_primary_experts": 4,
|
| 22 |
+
"moe_num_primary_experts": 32,
|
| 23 |
+
"norm_topk_prob": true,
|
| 24 |
+
"num_attention_heads": 12,
|
| 25 |
+
"num_hidden_layers": 32,
|
| 26 |
+
"num_key_value_heads": 2,
|
| 27 |
+
"output_router_logits": false,
|
| 28 |
+
"repetition_penalty": null,
|
| 29 |
+
"rms_norm_eps": 1e-06,
|
| 30 |
+
"rope_layout": [
|
| 31 |
+
1,
|
| 32 |
+
1,
|
| 33 |
+
1,
|
| 34 |
+
1,
|
| 35 |
+
1,
|
| 36 |
+
1,
|
| 37 |
+
1,
|
| 38 |
+
1,
|
| 39 |
+
1,
|
| 40 |
+
1,
|
| 41 |
+
1,
|
| 42 |
+
1,
|
| 43 |
+
1,
|
| 44 |
+
1,
|
| 45 |
+
1,
|
| 46 |
+
1,
|
| 47 |
+
1,
|
| 48 |
+
1,
|
| 49 |
+
1,
|
| 50 |
+
1,
|
| 51 |
+
1,
|
| 52 |
+
1,
|
| 53 |
+
1,
|
| 54 |
+
1,
|
| 55 |
+
1,
|
| 56 |
+
1,
|
| 57 |
+
1,
|
| 58 |
+
1,
|
| 59 |
+
1,
|
| 60 |
+
1,
|
| 61 |
+
1,
|
| 62 |
+
1
|
| 63 |
+
],
|
| 64 |
+
"rope_scaling": null,
|
| 65 |
+
"rope_theta": 1.5e6,
|
| 66 |
+
"sliding_window_size": 4096,
|
| 67 |
+
"sliding_window_layout": [
|
| 68 |
+
0,
|
| 69 |
+
0,
|
| 70 |
+
0,
|
| 71 |
+
0,
|
| 72 |
+
0,
|
| 73 |
+
0,
|
| 74 |
+
0,
|
| 75 |
+
0,
|
| 76 |
+
0,
|
| 77 |
+
0,
|
| 78 |
+
0,
|
| 79 |
+
0,
|
| 80 |
+
0,
|
| 81 |
+
0,
|
| 82 |
+
0,
|
| 83 |
+
0,
|
| 84 |
+
0,
|
| 85 |
+
0,
|
| 86 |
+
0,
|
| 87 |
+
0,
|
| 88 |
+
0,
|
| 89 |
+
0,
|
| 90 |
+
0,
|
| 91 |
+
0,
|
| 92 |
+
0,
|
| 93 |
+
0,
|
| 94 |
+
0,
|
| 95 |
+
0,
|
| 96 |
+
0,
|
| 97 |
+
0,
|
| 98 |
+
0,
|
| 99 |
+
0
|
| 100 |
+
],
|
| 101 |
+
"temperature": null,
|
| 102 |
+
"tie_word_embeddings": true,
|
| 103 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
| 104 |
+
"top_p": null,
|
| 105 |
+
"torch_dtype": "bfloat16",
|
| 106 |
+
"transformers_version": "4.53.3",
|
| 107 |
+
"use_cache": false,
|
| 108 |
+
"vocab_size": 151936
|
| 109 |
+
}
|
configuration_smallthinker.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 3 |
+
|
| 4 |
+
class SmallThinkerConfig(PretrainedConfig):
|
| 5 |
+
"""
|
| 6 |
+
This is the configuration class to store the configuration of a [`SmallThinkerModel`].
|
| 7 |
+
It is used to instantiate a SmallThinker model according to the specified arguments, defining the model architecture.
|
| 8 |
+
The default values for each of the parameters are the same as the ones used in the original SmallThinker 4B model.
|
| 9 |
+
|
| 10 |
+
General configs:
|
| 11 |
+
- model_type: "smallthinker"
|
| 12 |
+
- model_name
|
| 13 |
+
- num_hidden_layers
|
| 14 |
+
- hidden_size
|
| 15 |
+
|
| 16 |
+
Tokenizer configs:
|
| 17 |
+
- pad_token_id
|
| 18 |
+
- bos_token_id
|
| 19 |
+
- eos_token_id
|
| 20 |
+
|
| 21 |
+
Embedding configs:
|
| 22 |
+
- vocab_size
|
| 23 |
+
|
| 24 |
+
RMSNorm configs:
|
| 25 |
+
- rms_norm_eps
|
| 26 |
+
|
| 27 |
+
Attention configs:
|
| 28 |
+
- num_attention_heads
|
| 29 |
+
- num_key_value_heads
|
| 30 |
+
- head_dim
|
| 31 |
+
- use_cache
|
| 32 |
+
- rope_layout: array of 0 or 1s, 0 for nope, 1 for rope
|
| 33 |
+
- rope_theta
|
| 34 |
+
- max_position_embeddings
|
| 35 |
+
- sliding_window_layout: array of 0 or 1s, 0 for normal attention, 1 for SWA
|
| 36 |
+
- sliding_window_size
|
| 37 |
+
|
| 38 |
+
MoE FFN configs:
|
| 39 |
+
- moe_num_primary_experts
|
| 40 |
+
- moe_ffn_hidden_size
|
| 41 |
+
- moe_primary_router_apply_softmax: Use topk-softmax in routing instead of topk-sigmoid-normalize
|
| 42 |
+
- moe_num_active_primary_experts
|
| 43 |
+
|
| 44 |
+
LM Head configs:
|
| 45 |
+
- tie_word_embeddings
|
| 46 |
+
|
| 47 |
+
Other configs:
|
| 48 |
+
- initializer_range
|
| 49 |
+
"""
|
| 50 |
+
def __init__(self,
|
| 51 |
+
model_type = "smallthinker",
|
| 52 |
+
model_name="smallthinker_4b_base",
|
| 53 |
+
num_hidden_layers=32,
|
| 54 |
+
hidden_size=1536,
|
| 55 |
+
pad_token_id=None,
|
| 56 |
+
bos_token_id=151643,
|
| 57 |
+
eos_token_id=[151643,151645],
|
| 58 |
+
vocab_size=151936,
|
| 59 |
+
rms_norm_eps=1e-6,
|
| 60 |
+
num_attention_heads=12,
|
| 61 |
+
num_key_value_heads=2,
|
| 62 |
+
head_dim=128,
|
| 63 |
+
use_cache=True,
|
| 64 |
+
rope_layout=[1]*32,
|
| 65 |
+
rope_theta=1e6,
|
| 66 |
+
max_position_embeddings=4096 * 32,
|
| 67 |
+
sliding_window_layout=[0]*32,
|
| 68 |
+
sliding_window_size=4096,
|
| 69 |
+
moe_num_primary_experts=32,
|
| 70 |
+
moe_ffn_hidden_size=768,
|
| 71 |
+
moe_primary_router_apply_softmax=False,
|
| 72 |
+
moe_num_active_primary_experts=4,
|
| 73 |
+
tie_word_embeddings=True,
|
| 74 |
+
initializer_range=0.02,
|
| 75 |
+
**kwargs,
|
| 76 |
+
):
|
| 77 |
+
# Configuration sanitizers
|
| 78 |
+
assert num_attention_heads % num_key_value_heads == 0, "[SmallThinker config sanitizer] num_attention_heads must be divisible by num_key_value_heads"
|
| 79 |
+
assert len(rope_layout) == num_hidden_layers, "[SmallThinker config sanitizer] rope_layout must have the same length as num_hidden_layers"
|
| 80 |
+
assert len(sliding_window_layout) == num_hidden_layers, "[SmallThinker config sanitizer] sliding_window_layout must have the same length as num_hidden_layers"
|
| 81 |
+
|
| 82 |
+
# General configs
|
| 83 |
+
self.model_type = model_type
|
| 84 |
+
self.model_name = model_name
|
| 85 |
+
self.num_hidden_layers = num_hidden_layers
|
| 86 |
+
self.hidden_size = hidden_size
|
| 87 |
+
|
| 88 |
+
# Tokenizer configs
|
| 89 |
+
self.pad_token_id = pad_token_id
|
| 90 |
+
self.bos_token_id = bos_token_id
|
| 91 |
+
self.eos_token_id = eos_token_id
|
| 92 |
+
|
| 93 |
+
# Embedding configs
|
| 94 |
+
self.vocab_size = vocab_size
|
| 95 |
+
|
| 96 |
+
# RMSNorm configs
|
| 97 |
+
self.rms_norm_eps = rms_norm_eps
|
| 98 |
+
|
| 99 |
+
# Attention configs
|
| 100 |
+
self.num_attention_heads = num_attention_heads
|
| 101 |
+
self.num_key_value_heads = num_key_value_heads
|
| 102 |
+
self.head_dim = head_dim
|
| 103 |
+
self.use_cache = use_cache
|
| 104 |
+
self.rope_layout = rope_layout
|
| 105 |
+
self.rope_theta = rope_theta
|
| 106 |
+
self.max_position_embeddings = max_position_embeddings
|
| 107 |
+
self.sliding_window_layout = sliding_window_layout
|
| 108 |
+
self.sliding_window_size = sliding_window_size
|
| 109 |
+
|
| 110 |
+
# MoE FFN configs
|
| 111 |
+
self.moe_num_primary_experts = moe_num_primary_experts
|
| 112 |
+
self.moe_ffn_hidden_size = moe_ffn_hidden_size
|
| 113 |
+
self.moe_primary_router_apply_softmax = moe_primary_router_apply_softmax
|
| 114 |
+
self.moe_num_active_primary_experts = moe_num_active_primary_experts
|
| 115 |
+
|
| 116 |
+
# Other configs
|
| 117 |
+
self.initializer_range = initializer_range
|
| 118 |
+
|
| 119 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs)
|
| 120 |
+
|
| 121 |
+
# VLLM config, not used in transformers, but VLLM requires these args to run correctly. DO NOT DELETE!
|
| 122 |
+
self.sliding_window = sliding_window_size
|
| 123 |
+
self.sliding_window_pattern = sliding_window_layout
|
| 124 |
+
|
| 125 |
+
self._attn_implementation = "sdpa"
|
| 126 |
+
|
| 127 |
+
__all__ = ["SmallThinkerConfig"]
|
generation_config.json
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 151643,
|
| 4 |
+
"eos_token_id": [
|
| 5 |
+
151643,
|
| 6 |
+
151645
|
| 7 |
+
],
|
| 8 |
+
"transformers_version": "4.53.3"
|
| 9 |
+
}
|
merges.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model-00001-of-00002.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6cefd487ca75d8283cb2d3c28a6cd66527455ea926cc39a07816a5715ed87992
|
| 3 |
+
size 4999721256
|
model-00002-of-00002.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:20be6f7b5051c683b6e0de1e9794ee1c5ff9cc8380f74246463eb34870061cda
|
| 3 |
+
size 3537628448
|
model.safetensors.index.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model_lm_head.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8d29461f8711ea6d76a1a2e73921fda360a07fd5004b910cb94d41f05322f3ce
|
| 3 |
+
size 78579669
|
modeling_smallthinker.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
from typing import List, Optional, Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from torch import nn
|
| 7 |
+
|
| 8 |
+
from transformers.cache_utils import HybridCache, StaticCache
|
| 9 |
+
from transformers.generation import GenerationMixin
|
| 10 |
+
from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
|
| 11 |
+
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
| 12 |
+
from transformers.modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
|
| 13 |
+
from transformers.processing_utils import Unpack
|
| 14 |
+
from transformers.utils import LossKwargs, can_return_tuple, logging
|
| 15 |
+
from .configuration_smallthinker import SmallThinkerConfig
|
| 16 |
+
from .modular_smallthinker import *
|
| 17 |
+
|
| 18 |
+
logger = logging.get_logger(__name__)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class SmallThinkerModel(SmallThinkerPreTrainedModel):
|
| 22 |
+
def __init__(self, config: SmallThinkerConfig):
|
| 23 |
+
super().__init__(config)
|
| 24 |
+
self.padding_idx = config.pad_token_id
|
| 25 |
+
self.vocab_size = config.vocab_size
|
| 26 |
+
|
| 27 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 28 |
+
self.layers = nn.ModuleList(
|
| 29 |
+
[SmallThinkerDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 30 |
+
)
|
| 31 |
+
self.norm = SmallThinkerRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 32 |
+
self.rotary_emb = SmallThinkerRotaryEmbedding(config=config)
|
| 33 |
+
self.gradient_checkpointing = False
|
| 34 |
+
self.rope_layout = config.rope_layout
|
| 35 |
+
self.config = config
|
| 36 |
+
|
| 37 |
+
# Initialize weights and apply final processing
|
| 38 |
+
self.post_init()
|
| 39 |
+
|
| 40 |
+
def get_input_embeddings(self):
|
| 41 |
+
return self.embed_tokens
|
| 42 |
+
|
| 43 |
+
def set_input_embeddings(self, value):
|
| 44 |
+
self.embed_tokens = value
|
| 45 |
+
|
| 46 |
+
@can_return_tuple
|
| 47 |
+
def forward(
|
| 48 |
+
self,
|
| 49 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 50 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 51 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 52 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 53 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 54 |
+
use_cache: Optional[bool] = None,
|
| 55 |
+
output_attentions: Optional[bool] = None,
|
| 56 |
+
output_hidden_states: Optional[bool] = None,
|
| 57 |
+
output_router_logits: Optional[bool] = None,
|
| 58 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 59 |
+
**flash_attn_kwargs: Unpack[FlashAttentionKwargs],
|
| 60 |
+
) -> MoeModelOutputWithPast:
|
| 61 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 62 |
+
output_router_logits = (
|
| 63 |
+
output_router_logits if output_router_logits is not None else self.config.output_router_logits
|
| 64 |
+
)
|
| 65 |
+
output_hidden_states = (
|
| 66 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 67 |
+
)
|
| 68 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 69 |
+
|
| 70 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 71 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 72 |
+
|
| 73 |
+
if inputs_embeds is None:
|
| 74 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 75 |
+
|
| 76 |
+
if use_cache and past_key_values is None:
|
| 77 |
+
batch_size, seq_len, _ = inputs_embeds.shape
|
| 78 |
+
# NOTE: ideally, `HybridCache` should be initialized outside the model with `layer_device_map`
|
| 79 |
+
if not hasattr(self.config, "sliding_window_layout") or self.config.sliding_window_layout is None or not any(self.config.sliding_window_layout):
|
| 80 |
+
past_key_values = StaticCache(
|
| 81 |
+
self.config,
|
| 82 |
+
max_batch_size=batch_size,
|
| 83 |
+
max_cache_len=seq_len,
|
| 84 |
+
dtype=inputs_embeds.dtype,
|
| 85 |
+
device=self.device,
|
| 86 |
+
)
|
| 87 |
+
else:
|
| 88 |
+
past_key_values = HybridCache(
|
| 89 |
+
self.config,
|
| 90 |
+
max_batch_size=batch_size,
|
| 91 |
+
max_cache_len=seq_len,
|
| 92 |
+
dtype=inputs_embeds.dtype,
|
| 93 |
+
device=self.device,
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
if cache_position is None:
|
| 97 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 98 |
+
cache_position = torch.arange(
|
| 99 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
if position_ids is None:
|
| 103 |
+
position_ids = cache_position.unsqueeze(0)
|
| 104 |
+
|
| 105 |
+
causal_mask = create_causal_mask(
|
| 106 |
+
config=self.config,
|
| 107 |
+
input_embeds=inputs_embeds,
|
| 108 |
+
attention_mask=attention_mask,
|
| 109 |
+
cache_position=cache_position,
|
| 110 |
+
past_key_values=past_key_values,
|
| 111 |
+
position_ids=position_ids,
|
| 112 |
+
)
|
| 113 |
+
if hasattr(self.config, "sliding_window_layout") and self.config.sliding_window_layout is not None and any(self.config.sliding_window_layout):
|
| 114 |
+
swa_mask = create_sliding_window_causal_mask(
|
| 115 |
+
config=self.config,
|
| 116 |
+
input_embeds=inputs_embeds,
|
| 117 |
+
attention_mask=attention_mask,
|
| 118 |
+
cache_position=cache_position,
|
| 119 |
+
past_key_values=past_key_values,
|
| 120 |
+
position_ids=position_ids,
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
hidden_states = inputs_embeds
|
| 124 |
+
# create position embeddings to be shared across the decoder layers
|
| 125 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 126 |
+
|
| 127 |
+
# decoder layers
|
| 128 |
+
all_hidden_states = () if output_hidden_states else None
|
| 129 |
+
all_self_attns = () if output_attentions else None
|
| 130 |
+
all_router_logits = () if output_router_logits else None
|
| 131 |
+
|
| 132 |
+
for layer_idx, decoder_layer in enumerate(self.layers):
|
| 133 |
+
if output_hidden_states:
|
| 134 |
+
all_hidden_states += (hidden_states,)
|
| 135 |
+
|
| 136 |
+
if hasattr(self.config, "sliding_window_layout") and self.config.sliding_window_layout is not None:
|
| 137 |
+
if self.config.sliding_window_layout[layer_idx] == 1:
|
| 138 |
+
layer_outputs = decoder_layer(
|
| 139 |
+
hidden_states,
|
| 140 |
+
attention_mask=swa_mask,
|
| 141 |
+
position_ids=position_ids,
|
| 142 |
+
past_key_value=past_key_values,
|
| 143 |
+
output_attentions=output_attentions,
|
| 144 |
+
output_router_logits=output_router_logits,
|
| 145 |
+
use_cache=use_cache,
|
| 146 |
+
cache_position=cache_position,
|
| 147 |
+
position_embeddings=position_embeddings if self.rope_layout[layer_idx] else None,
|
| 148 |
+
**flash_attn_kwargs,
|
| 149 |
+
)
|
| 150 |
+
else:
|
| 151 |
+
layer_outputs = decoder_layer(
|
| 152 |
+
hidden_states,
|
| 153 |
+
attention_mask=causal_mask,
|
| 154 |
+
position_ids=position_ids,
|
| 155 |
+
past_key_value=past_key_values,
|
| 156 |
+
output_attentions=output_attentions,
|
| 157 |
+
output_router_logits=output_router_logits,
|
| 158 |
+
use_cache=use_cache,
|
| 159 |
+
cache_position=cache_position,
|
| 160 |
+
position_embeddings=position_embeddings if self.rope_layout[layer_idx] else None,
|
| 161 |
+
**flash_attn_kwargs,
|
| 162 |
+
)
|
| 163 |
+
else:
|
| 164 |
+
layer_outputs = decoder_layer(
|
| 165 |
+
hidden_states,
|
| 166 |
+
attention_mask=causal_mask,
|
| 167 |
+
position_ids=position_ids,
|
| 168 |
+
past_key_value=past_key_values,
|
| 169 |
+
output_attentions=output_attentions,
|
| 170 |
+
output_router_logits=output_router_logits,
|
| 171 |
+
use_cache=use_cache,
|
| 172 |
+
cache_position=cache_position,
|
| 173 |
+
position_embeddings=position_embeddings if self.rope_layout[layer_idx] else None,
|
| 174 |
+
**flash_attn_kwargs,
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
hidden_states = layer_outputs[0]
|
| 178 |
+
|
| 179 |
+
if output_attentions:
|
| 180 |
+
all_self_attns += (layer_outputs[1],)
|
| 181 |
+
|
| 182 |
+
if output_router_logits:
|
| 183 |
+
all_router_logits += (layer_outputs[-1],)
|
| 184 |
+
|
| 185 |
+
hidden_states = self.norm(hidden_states)
|
| 186 |
+
|
| 187 |
+
# add hidden states from the last decoder layer
|
| 188 |
+
if output_hidden_states:
|
| 189 |
+
all_hidden_states += (hidden_states,)
|
| 190 |
+
|
| 191 |
+
return MoeModelOutputWithPast(
|
| 192 |
+
last_hidden_state=hidden_states,
|
| 193 |
+
past_key_values=past_key_values if use_cache else None,
|
| 194 |
+
hidden_states=all_hidden_states,
|
| 195 |
+
attentions=all_self_attns,
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
|
| 199 |
+
|
| 200 |
+
class SmallThinkerForCausalLM(SmallThinkerPreTrainedModel, GenerationMixin):
|
| 201 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 202 |
+
def __init__(self, config):
|
| 203 |
+
super().__init__(config)
|
| 204 |
+
self.model = SmallThinkerModel(config)
|
| 205 |
+
self.vocab_size = config.vocab_size
|
| 206 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 207 |
+
self.post_init()
|
| 208 |
+
|
| 209 |
+
def get_input_embeddings(self):
|
| 210 |
+
return self.model.embed_tokens
|
| 211 |
+
|
| 212 |
+
def set_input_embeddings(self, value):
|
| 213 |
+
self.model.embed_tokens = value
|
| 214 |
+
|
| 215 |
+
def get_output_embeddings(self):
|
| 216 |
+
return self.lm_head
|
| 217 |
+
|
| 218 |
+
def set_output_embeddings(self, new_embeddings):
|
| 219 |
+
self.lm_head = new_embeddings
|
| 220 |
+
|
| 221 |
+
def set_decoder(self, decoder):
|
| 222 |
+
self.model = decoder
|
| 223 |
+
|
| 224 |
+
def get_decoder(self):
|
| 225 |
+
return self.model
|
| 226 |
+
|
| 227 |
+
@can_return_tuple
|
| 228 |
+
def forward(
|
| 229 |
+
self,
|
| 230 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 231 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 232 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 233 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 234 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 235 |
+
use_cache: Optional[bool] = None,
|
| 236 |
+
output_attentions: Optional[bool] = None,
|
| 237 |
+
output_hidden_states: Optional[bool] = None,
|
| 238 |
+
output_router_logits: Optional[bool] = None,
|
| 239 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 240 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
| 241 |
+
**kwargs: Unpack[KwargsForCausalLM],
|
| 242 |
+
) -> MoeCausalLMOutputWithPast:
|
| 243 |
+
|
| 244 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 245 |
+
output_router_logits = (
|
| 246 |
+
output_router_logits if output_router_logits is not None else self.config.output_router_logits
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
output_hidden_states = (
|
| 250 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 254 |
+
outputs: MoeModelOutputWithPast = self.model(
|
| 255 |
+
input_ids=input_ids,
|
| 256 |
+
attention_mask=attention_mask,
|
| 257 |
+
position_ids=position_ids,
|
| 258 |
+
past_key_values=past_key_values,
|
| 259 |
+
inputs_embeds=inputs_embeds,
|
| 260 |
+
use_cache=use_cache,
|
| 261 |
+
output_attentions=output_attentions,
|
| 262 |
+
output_hidden_states=output_hidden_states,
|
| 263 |
+
output_router_logits=output_router_logits,
|
| 264 |
+
cache_position=cache_position,
|
| 265 |
+
**kwargs,
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
hidden_states = outputs.last_hidden_state
|
| 269 |
+
# Only compute necessary logits, and do not upcast them to float
|
| 270 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 271 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 272 |
+
|
| 273 |
+
return MoeCausalLMOutputWithPast(
|
| 274 |
+
loss=None,
|
| 275 |
+
aux_loss=None,
|
| 276 |
+
logits=logits,
|
| 277 |
+
past_key_values=outputs.past_key_values,
|
| 278 |
+
hidden_states=outputs.hidden_states,
|
| 279 |
+
attentions=outputs.attentions,
|
| 280 |
+
router_logits=outputs.router_logits,
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
__all__ = [
|
| 284 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Callable, Optional, Tuple
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from torch import nn
|
| 6 |
+
|
| 7 |
+
from transformers.cache_utils import Cache
|
| 8 |
+
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
| 9 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 10 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 11 |
+
from transformers.processing_utils import Unpack
|
| 12 |
+
from transformers.utils import logging
|
| 13 |
+
from .configuration_smallthinker import SmallThinkerConfig
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
logger = logging.get_logger(__name__)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@torch.jit.script
|
| 20 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 21 |
+
"""
|
| 22 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 23 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 24 |
+
"""
|
| 25 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 26 |
+
if n_rep == 1:
|
| 27 |
+
return hidden_states
|
| 28 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 29 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def rotate_half(x):
|
| 33 |
+
"""Rotates half the hidden dims of the input."""
|
| 34 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 35 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 36 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 40 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
q (`torch.Tensor`): The query tensor.
|
| 44 |
+
k (`torch.Tensor`): The key tensor.
|
| 45 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 46 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 47 |
+
position_ids (`torch.Tensor`, *optional*):
|
| 48 |
+
Deprecated and unused.
|
| 49 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 50 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 51 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 52 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 53 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 54 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 55 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 56 |
+
Returns:
|
| 57 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 58 |
+
"""
|
| 59 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 60 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 61 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 62 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 63 |
+
return q_embed, k_embed
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def check_is_swa_layer(config, layer_idx):
|
| 67 |
+
"""
|
| 68 |
+
Check if the current layer is a sliding window attention layer.
|
| 69 |
+
"""
|
| 70 |
+
if not hasattr(config, "sliding_window_layout"):
|
| 71 |
+
return False
|
| 72 |
+
elif config.sliding_window_layout is None:
|
| 73 |
+
return False
|
| 74 |
+
else:
|
| 75 |
+
return config.sliding_window_layout[layer_idx] == 1
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class SmallThinkerRMSNorm(nn.Module):
|
| 79 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 80 |
+
"""
|
| 81 |
+
SmallThinkerRMSNorm is equivalent to T5LayerNorm
|
| 82 |
+
"""
|
| 83 |
+
super().__init__()
|
| 84 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 85 |
+
self.variance_epsilon = eps
|
| 86 |
+
|
| 87 |
+
def forward(self, hidden_states):
|
| 88 |
+
input_dtype = hidden_states.dtype
|
| 89 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 90 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 91 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 92 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 93 |
+
|
| 94 |
+
def extra_repr(self):
|
| 95 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class SmallThinkerRotaryEmbedding(nn.Module):
|
| 99 |
+
def __init__(self, config: SmallThinkerConfig, device=None):
|
| 100 |
+
super().__init__()
|
| 101 |
+
if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
|
| 102 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
| 103 |
+
else:
|
| 104 |
+
self.rope_type = "default"
|
| 105 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 106 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 107 |
+
|
| 108 |
+
self.config = config
|
| 109 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 110 |
+
|
| 111 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
| 112 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 113 |
+
self.original_inv_freq = self.inv_freq
|
| 114 |
+
|
| 115 |
+
@torch.no_grad()
|
| 116 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
| 117 |
+
def forward(self, x, position_ids):
|
| 118 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
| 119 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 120 |
+
|
| 121 |
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
| 122 |
+
with torch.autocast(device_type=device_type, enabled=False): # Force float32
|
| 123 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 124 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 125 |
+
cos = emb.cos() * self.attention_scaling
|
| 126 |
+
sin = emb.sin() * self.attention_scaling
|
| 127 |
+
|
| 128 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class SmallThinkerExpert(nn.Module):
|
| 132 |
+
def __init__(self, config: SmallThinkerConfig):
|
| 133 |
+
super().__init__()
|
| 134 |
+
self.hidden_dim = config.hidden_size
|
| 135 |
+
self.ffn_dim = config.moe_ffn_hidden_size
|
| 136 |
+
|
| 137 |
+
self.up = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False)
|
| 138 |
+
self.gate = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False)
|
| 139 |
+
self.down = nn.Linear(self.ffn_dim, self.hidden_dim, bias=False)
|
| 140 |
+
|
| 141 |
+
def forward(self, hidden_states: torch.Tensor):
|
| 142 |
+
current_hidden_states = self.up(hidden_states) * F.relu(self.gate(hidden_states))
|
| 143 |
+
batch_size, _ = current_hidden_states.shape
|
| 144 |
+
current_hidden_states = current_hidden_states.view(batch_size, -1)
|
| 145 |
+
current_hidden_states = self.down(current_hidden_states)
|
| 146 |
+
return current_hidden_states
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class SmallThinkerMoeBlock(nn.Module):
|
| 150 |
+
def __init__(self, config: SmallThinkerConfig):
|
| 151 |
+
super().__init__()
|
| 152 |
+
self.hidden_dim = config.hidden_size
|
| 153 |
+
self.num_primary_experts = config.moe_num_primary_experts
|
| 154 |
+
self.moe_primary_router_apply_softmax = config.moe_primary_router_apply_softmax
|
| 155 |
+
self.num_active_primary_experts = config.moe_num_active_primary_experts
|
| 156 |
+
self.primary_router = nn.Linear(self.hidden_dim, self.num_primary_experts, bias=False)
|
| 157 |
+
self.experts = nn.ModuleList([SmallThinkerExpert(config) for _ in range(self.num_primary_experts)])
|
| 158 |
+
|
| 159 |
+
def forward(self, router_input: torch.Tensor, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 160 |
+
batch_size, sequence_length, hidden_dim = hidden_states.shape
|
| 161 |
+
# Flatten the tokens into (bs * sl, hidden_dim)
|
| 162 |
+
hidden_states = hidden_states.view(-1, hidden_dim)
|
| 163 |
+
router_input = router_input.view(-1, hidden_dim)
|
| 164 |
+
# Primary router logits: (bs * sl, n_experts)
|
| 165 |
+
router_logits = self.primary_router(router_input)
|
| 166 |
+
|
| 167 |
+
router_logits, selected_experts = torch.topk(router_logits, self.num_active_primary_experts, dim=-1)
|
| 168 |
+
|
| 169 |
+
if self.moe_primary_router_apply_softmax:
|
| 170 |
+
routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
|
| 171 |
+
else:
|
| 172 |
+
routing_weights = F.sigmoid(router_logits)
|
| 173 |
+
routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
|
| 174 |
+
|
| 175 |
+
routing_weights = routing_weights.to(hidden_states.dtype)
|
| 176 |
+
|
| 177 |
+
# Prepare the final tensor
|
| 178 |
+
final_hidden_states = torch.zeros(
|
| 179 |
+
(batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
# One hot encode the selected experts to create an expert mask
|
| 183 |
+
# this will be used to easily index which expert is going to be sollicitated
|
| 184 |
+
expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_primary_experts).permute(2, 1, 0)
|
| 185 |
+
expert_hitted = (expert_mask.sum(dim=(-1, -2)) > 0).nonzero(as_tuple=True)[0].tolist()
|
| 186 |
+
|
| 187 |
+
for expert_idx in expert_hitted:
|
| 188 |
+
expert_layer = self.experts[expert_idx]
|
| 189 |
+
idx, top_x = torch.where(expert_mask[expert_idx])
|
| 190 |
+
# Index the correct hidden states and compute the expert hidden state for
|
| 191 |
+
# the current expert. We need to make sure to multiply the output hidden
|
| 192 |
+
# states by `routing_weights` on the corresponding tokens (top-1 and top-2)
|
| 193 |
+
current_state = hidden_states[top_x].reshape(-1, hidden_dim)
|
| 194 |
+
current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
|
| 195 |
+
|
| 196 |
+
# However `index_add_` only support torch tensors for indexing so we'll use the `top_x` tensor here.
|
| 197 |
+
final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
|
| 198 |
+
final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
|
| 199 |
+
return final_hidden_states, router_logits
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def eager_attention_forward(
|
| 203 |
+
module: nn.Module,
|
| 204 |
+
query: torch.Tensor,
|
| 205 |
+
key: torch.Tensor,
|
| 206 |
+
value: torch.Tensor,
|
| 207 |
+
attention_mask: Optional[torch.Tensor],
|
| 208 |
+
scaling: float,
|
| 209 |
+
dropout: float = 0.0,
|
| 210 |
+
**kwargs,
|
| 211 |
+
):
|
| 212 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 213 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 214 |
+
|
| 215 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 216 |
+
if attention_mask is not None:
|
| 217 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 218 |
+
attn_weights = attn_weights + causal_mask
|
| 219 |
+
|
| 220 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 221 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 222 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 223 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 224 |
+
|
| 225 |
+
return attn_output, attn_weights
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
class SmallThinkerAttention(nn.Module):
|
| 229 |
+
def __init__(self, config: SmallThinkerConfig, layer_idx: int):
|
| 230 |
+
super().__init__()
|
| 231 |
+
self.config = config
|
| 232 |
+
self.layer_idx = layer_idx
|
| 233 |
+
self.head_dim = config.head_dim
|
| 234 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 235 |
+
self.scaling = self.head_dim**-0.5
|
| 236 |
+
self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
|
| 237 |
+
self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
|
| 238 |
+
self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
|
| 239 |
+
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
|
| 240 |
+
self.sliding_window = config.sliding_window_size if config.sliding_window_layout[layer_idx] else None
|
| 241 |
+
|
| 242 |
+
def forward(
|
| 243 |
+
self,
|
| 244 |
+
hidden_states: torch.Tensor,
|
| 245 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
| 246 |
+
attention_mask: Optional[torch.Tensor],
|
| 247 |
+
past_key_value: Optional[Cache] = None,
|
| 248 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 249 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 250 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 251 |
+
|
| 252 |
+
input_shape = hidden_states.shape[:-1]
|
| 253 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 254 |
+
|
| 255 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 256 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 257 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 258 |
+
|
| 259 |
+
if position_embeddings:
|
| 260 |
+
cos, sin = position_embeddings
|
| 261 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 262 |
+
else:
|
| 263 |
+
cos, sin = None, None
|
| 264 |
+
|
| 265 |
+
if past_key_value is not None:
|
| 266 |
+
cache_kwargs = {
|
| 267 |
+
"sin": sin,
|
| 268 |
+
"cos": cos,
|
| 269 |
+
"cache_position": cache_position,
|
| 270 |
+
"sliding_window": self.sliding_window,
|
| 271 |
+
}
|
| 272 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 273 |
+
|
| 274 |
+
attention_interface: Callable = eager_attention_forward
|
| 275 |
+
if self.config._attn_implementation != "eager":
|
| 276 |
+
if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
|
| 277 |
+
logger.warning_once(
|
| 278 |
+
"`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
|
| 279 |
+
'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
| 280 |
+
)
|
| 281 |
+
else:
|
| 282 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 283 |
+
|
| 284 |
+
attn_output, attn_weights = attention_interface(
|
| 285 |
+
self,
|
| 286 |
+
query_states,
|
| 287 |
+
key_states,
|
| 288 |
+
value_states,
|
| 289 |
+
attention_mask,
|
| 290 |
+
dropout=0.0,
|
| 291 |
+
scaling=self.scaling,
|
| 292 |
+
sliding_window=self.sliding_window,
|
| 293 |
+
**kwargs,
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 297 |
+
attn_output = self.o_proj(attn_output)
|
| 298 |
+
return attn_output, attn_weights
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
class SmallThinkerDecoderLayer(nn.Module):
|
| 302 |
+
def __init__(self, config: SmallThinkerConfig, layer_idx: int):
|
| 303 |
+
super().__init__()
|
| 304 |
+
self.hidden_size = config.hidden_size
|
| 305 |
+
self.self_attn = SmallThinkerAttention(config, layer_idx)
|
| 306 |
+
self.block_sparse_moe = SmallThinkerMoeBlock(config)
|
| 307 |
+
self.input_layernorm = SmallThinkerRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 308 |
+
self.post_attention_layernorm = SmallThinkerRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 309 |
+
self.is_swa = check_is_swa_layer(config, layer_idx)
|
| 310 |
+
|
| 311 |
+
if self.is_swa and config._attn_implementation == "sdpa":
|
| 312 |
+
logger.warning_once(
|
| 313 |
+
f"Sliding Window Attention is enabled but not optimized for `{config._attn_implementation}`; "
|
| 314 |
+
"unexpected results may be encountered."
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
def forward(
|
| 318 |
+
self,
|
| 319 |
+
hidden_states: torch.Tensor,
|
| 320 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 321 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 322 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 323 |
+
output_attentions: Optional[bool] = False,
|
| 324 |
+
output_router_logits: Optional[bool] = False,
|
| 325 |
+
use_cache: Optional[bool] = False,
|
| 326 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 327 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 328 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 329 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 330 |
+
"""
|
| 331 |
+
Args:
|
| 332 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 333 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
| 334 |
+
`(batch, sequence_length)` where padding elements are indicated by 0.
|
| 335 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
| 336 |
+
output_attentions (`bool`, *optional*):
|
| 337 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 338 |
+
returned tensors for more detail.
|
| 339 |
+
output_router_logits (`bool`, *optional*):
|
| 340 |
+
Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
|
| 341 |
+
should not be returned during inference.
|
| 342 |
+
use_cache (`bool`, *optional*):
|
| 343 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 344 |
+
(see `past_key_values`).
|
| 345 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
| 346 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
| 347 |
+
kwargs (`dict`, *optional*):
|
| 348 |
+
Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
|
| 349 |
+
into the model
|
| 350 |
+
"""
|
| 351 |
+
residual = hidden_states
|
| 352 |
+
router_input = hidden_states
|
| 353 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 354 |
+
# Self Attention
|
| 355 |
+
hidden_states, self_attn_weights = self.self_attn(
|
| 356 |
+
hidden_states=hidden_states,
|
| 357 |
+
position_embeddings=position_embeddings,
|
| 358 |
+
attention_mask=attention_mask,
|
| 359 |
+
position_ids=position_ids,
|
| 360 |
+
past_key_value=past_key_value,
|
| 361 |
+
output_attentions=output_attentions,
|
| 362 |
+
use_cache=use_cache,
|
| 363 |
+
cache_position=cache_position,
|
| 364 |
+
**kwargs,
|
| 365 |
+
)
|
| 366 |
+
hidden_states = residual + hidden_states
|
| 367 |
+
|
| 368 |
+
# Fully Connected
|
| 369 |
+
residual = hidden_states
|
| 370 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 371 |
+
hidden_states, router_logits = self.block_sparse_moe(router_input, hidden_states)
|
| 372 |
+
hidden_states = residual + hidden_states
|
| 373 |
+
|
| 374 |
+
outputs = (hidden_states,)
|
| 375 |
+
if output_attentions:
|
| 376 |
+
outputs += (self_attn_weights,)
|
| 377 |
+
if output_router_logits:
|
| 378 |
+
outputs += (router_logits,)
|
| 379 |
+
return outputs
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
class SmallThinkerPreTrainedModel(PreTrainedModel):
|
| 383 |
+
config_class = SmallThinkerConfig
|
| 384 |
+
base_model_prefix = "model"
|
| 385 |
+
supports_gradient_checkpointing = False
|
| 386 |
+
_no_split_modules = ["SmallThinkerDecoderLayer"]
|
| 387 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 388 |
+
_supports_flash_attn_2 = True
|
| 389 |
+
_supports_sdpa = True
|
| 390 |
+
_supports_flex_attn = False
|
| 391 |
+
_supports_cache_class = True
|
| 392 |
+
_supports_quantized_cache = True
|
| 393 |
+
_supports_static_cache = False
|
| 394 |
+
_supports_attention_backend = True
|
| 395 |
+
|
| 396 |
+
def _init_weights(self, module):
|
| 397 |
+
std = self.config.initializer_range
|
| 398 |
+
if isinstance(module, nn.Linear):
|
| 399 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 400 |
+
if module.bias is not None:
|
| 401 |
+
module.bias.data.zero_()
|
| 402 |
+
elif isinstance(module, nn.Embedding):
|
| 403 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 404 |
+
if module.padding_idx is not None:
|
| 405 |
+
module.weight.data[module.padding_idx].zero_()
|
| 406 |
+
elif isinstance(module, SmallThinkerRMSNorm):
|
| 407 |
+
module.weight.data.fill_(1.0)
|
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,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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"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 |
+
},
|
| 182 |
+
"additional_special_tokens": [
|
| 183 |
+
"<|im_start|>",
|
| 184 |
+
"<|im_end|>",
|
| 185 |
+
"<|object_ref_start|>",
|
| 186 |
+
"<|object_ref_end|>",
|
| 187 |
+
"<|box_start|>",
|
| 188 |
+
"<|box_end|>",
|
| 189 |
+
"<|quad_start|>",
|
| 190 |
+
"<|quad_end|>",
|
| 191 |
+
"<|vision_start|>",
|
| 192 |
+
"<|vision_end|>",
|
| 193 |
+
"<|vision_pad|>",
|
| 194 |
+
"<|image_pad|>",
|
| 195 |
+
"<|video_pad|>"
|
| 196 |
+
],
|
| 197 |
+
"bos_token": null,
|
| 198 |
+
"chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0]['role'] == 'system' %}\n {{- messages[0]['content'] }}\n {%- else %}\n {{- 'You are SmallThinker. You are a helpful assistant.' }}\n {%- endif %}\n {{- \"\\n\\n# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0]['role'] == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0]['content'] + '<|im_end|>\\n' }}\n {%- else %}\n {{- '<|im_start|>system\\nYou are SmallThinker. You are a helpful assistant.<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) or (message.role == \"assistant\" and not message.tool_calls) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role }}\n {%- if message.content %}\n {{- '\\n' + message.content }}\n {%- endif %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '\\n<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}\n",
|
| 199 |
+
"clean_up_tokenization_spaces": false,
|
| 200 |
+
"eos_token": "<|im_end|>",
|
| 201 |
+
"errors": "replace",
|
| 202 |
+
"model_max_length": 131072,
|
| 203 |
+
"pad_token": "<|endoftext|>",
|
| 204 |
+
"split_special_tokens": false,
|
| 205 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
| 206 |
+
"unk_token": null
|
| 207 |
+
}
|
vocab.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|