update
Browse files- config.json +26 -0
- configuration_tinyllm.py +61 -0
- generation_config.json +12 -0
- modeling_tinyllm.py +1057 -0
- pytorch_model.bin +3 -0
- tokenization_chatglm.py +389 -0
- tokenizer.model +3 -0
- tokenizer_config.json +52 -0
- vocab.txt +0 -0
config.json
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"TinyllmForCausalLM"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoConfig": "configuration_tinyllm.TinyllmConfig",
|
7 |
+
"AutoModelForCausalLM": "modeling_tinyllm.TinyllmForCausalLM"
|
8 |
+
},
|
9 |
+
"attention_dropout": 0.0,
|
10 |
+
"hidden_act": "silu",
|
11 |
+
"hidden_size": 512,
|
12 |
+
"initializer_range": 0.02,
|
13 |
+
"intermediate_size": 1408,
|
14 |
+
"max_position_embeddings": 1024,
|
15 |
+
"model_type": "tinyllm",
|
16 |
+
"num_attention_heads": 8,
|
17 |
+
"num_hidden_layers": 8,
|
18 |
+
"num_key_value_heads": 8,
|
19 |
+
"rms_norm_eps": 1e-06,
|
20 |
+
"rope_theta": 10000.0,
|
21 |
+
"tie_word_embeddings": false,
|
22 |
+
"torch_dtype": "float16",
|
23 |
+
"transformers_version": "4.38.2",
|
24 |
+
"use_cache": true,
|
25 |
+
"vocab_size": 64798
|
26 |
+
}
|
configuration_tinyllm.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers.configuration_utils import PretrainedConfig
|
2 |
+
from transformers.utils import logging
|
3 |
+
|
4 |
+
|
5 |
+
logger = logging.get_logger(__name__)
|
6 |
+
|
7 |
+
|
8 |
+
class TinyllmConfig(PretrainedConfig):
|
9 |
+
""" TinyLLM 配置文件
|
10 |
+
"""
|
11 |
+
|
12 |
+
model_type = "tinyllm"
|
13 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
14 |
+
|
15 |
+
def __init__(
|
16 |
+
self,
|
17 |
+
vocab_size=64797,
|
18 |
+
hidden_size=4096,
|
19 |
+
intermediate_size=11008,
|
20 |
+
num_hidden_layers=32,
|
21 |
+
num_attention_heads=32,
|
22 |
+
num_key_value_heads=None,
|
23 |
+
hidden_act="silu",
|
24 |
+
max_position_embeddings=2048,
|
25 |
+
initializer_range=0.02,
|
26 |
+
rms_norm_eps=1e-6,
|
27 |
+
use_cache=True,
|
28 |
+
pad_token_id=None,
|
29 |
+
bos_token_id=None,
|
30 |
+
eos_token_id=None,
|
31 |
+
tie_word_embeddings=False,
|
32 |
+
rope_theta=10000.0,
|
33 |
+
attention_dropout=0.0,
|
34 |
+
**kwargs
|
35 |
+
):
|
36 |
+
self.vocab_size = vocab_size
|
37 |
+
self.max_position_embeddings = max_position_embeddings
|
38 |
+
self.hidden_size = hidden_size
|
39 |
+
self.intermediate_size = intermediate_size
|
40 |
+
self.num_hidden_layers = num_hidden_layers
|
41 |
+
self.num_attention_heads = num_attention_heads
|
42 |
+
|
43 |
+
# for backward compatibility
|
44 |
+
if num_key_value_heads is None:
|
45 |
+
num_key_value_heads = num_attention_heads
|
46 |
+
|
47 |
+
self.num_key_value_heads = num_key_value_heads
|
48 |
+
self.hidden_act = hidden_act
|
49 |
+
self.initializer_range = initializer_range
|
50 |
+
self.rms_norm_eps = rms_norm_eps
|
51 |
+
self.use_cache = use_cache
|
52 |
+
self.rope_theta = rope_theta
|
53 |
+
self.attention_dropout = attention_dropout
|
54 |
+
|
55 |
+
super().__init__(
|
56 |
+
pad_token_id=pad_token_id,
|
57 |
+
bos_token_id=bos_token_id,
|
58 |
+
eos_token_id=eos_token_id,
|
59 |
+
tie_word_embeddings=tie_word_embeddings,
|
60 |
+
**kwargs
|
61 |
+
)
|
generation_config.json
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token_id": 1,
|
3 |
+
"do_sample": true,
|
4 |
+
"eos_token_id": 2,
|
5 |
+
"pad_token_id": 0,
|
6 |
+
"top_k":30,
|
7 |
+
"top_p":0.8,
|
8 |
+
"temperature":0.8,
|
9 |
+
"repetition_penalty": 1.1,
|
10 |
+
"_from_model_config": true,
|
11 |
+
"transformers_version": "4.38.2"
|
12 |
+
}
|
modeling_tinyllm.py
ADDED
@@ -0,0 +1,1057 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Tiny LLM 模型架构
|
3 |
+
|
4 |
+
到处抄,整体还是Llama2的模型架构
|
5 |
+
"""
|
6 |
+
|
7 |
+
import math
|
8 |
+
import warnings
|
9 |
+
from threading import Thread
|
10 |
+
from typing import List, Optional, Tuple, Union
|
11 |
+
|
12 |
+
import torch
|
13 |
+
import torch.nn.functional as F
|
14 |
+
import torch.utils.checkpoint
|
15 |
+
from torch import nn
|
16 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
17 |
+
|
18 |
+
from transformers.activations import ACT2FN
|
19 |
+
from transformers.cache_utils import Cache, DynamicCache
|
20 |
+
from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
|
21 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
|
22 |
+
from transformers.modeling_utils import PreTrainedModel
|
23 |
+
from transformers.utils import logging
|
24 |
+
from transformers.generation.utils import GenerationConfig
|
25 |
+
|
26 |
+
from .configuration_tinyllm import TinyllmConfig
|
27 |
+
|
28 |
+
logger = logging.get_logger(__name__)
|
29 |
+
|
30 |
+
def debug(key, value):
|
31 |
+
"""
|
32 |
+
"""
|
33 |
+
try:
|
34 |
+
res = {"var": torch.var(value).item(), "mean": torch.mean(value).item(),
|
35 |
+
"max":torch.max(value).item(), "size": value.size(), "dtype": value.dtype}
|
36 |
+
except:
|
37 |
+
res = value
|
38 |
+
print("debug", key, res, sep="\t")
|
39 |
+
|
40 |
+
|
41 |
+
def report_memory(name):
|
42 |
+
"""Simple GPU memory report."""
|
43 |
+
mega_bytes = 1024.0 * 1024.0
|
44 |
+
string = name + ' memory (MB)'
|
45 |
+
# 变量分配显存
|
46 |
+
string += ' | allocated: {}'.format(
|
47 |
+
torch.cuda.memory_allocated() / mega_bytes)
|
48 |
+
string += ' | max allocated: {}'.format(
|
49 |
+
torch.cuda.max_memory_allocated() / mega_bytes)
|
50 |
+
# 缓存和变量分配显存,实际显存还需要+pytorch context
|
51 |
+
string += ' | reserved: {}'.format(
|
52 |
+
torch.cuda.memory_reserved() / mega_bytes)
|
53 |
+
string += ' | max reserved: {}'.format(
|
54 |
+
torch.cuda.max_memory_reserved() / mega_bytes)
|
55 |
+
try:
|
56 |
+
if torch.distributed.get_rank() == 0:
|
57 |
+
print("[Rank {}] {}".format(torch.distributed.get_rank(), string),
|
58 |
+
flush=True)
|
59 |
+
pass
|
60 |
+
except:
|
61 |
+
pass
|
62 |
+
|
63 |
+
class TinyllmRMSNorm(nn.Module):
|
64 |
+
def __init__(self, hidden_size, eps=1e-6):
|
65 |
+
""" TinyllmRMSNorm
|
66 |
+
"""
|
67 |
+
super().__init__()
|
68 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
69 |
+
self.variance_epsilon = eps
|
70 |
+
|
71 |
+
def forward(self, hidden_states):
|
72 |
+
input_dtype = hidden_states.dtype
|
73 |
+
hidden_states = hidden_states.to(torch.float32)
|
74 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
75 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
76 |
+
return self.weight * hidden_states.to(input_dtype)
|
77 |
+
|
78 |
+
class TinyllmRotaryEmbedding(nn.Module):
|
79 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
80 |
+
""" 旋转位置编码
|
81 |
+
- dim (int): 旋转嵌入的维度大小。
|
82 |
+
- max_position_embeddings (int): 预计算的最大位置嵌入数,默认为2048。
|
83 |
+
- base (int): 用于计算逆频率的基本频率,默认为10000。
|
84 |
+
"""
|
85 |
+
super().__init__()
|
86 |
+
|
87 |
+
self.dim = dim
|
88 |
+
self.max_position_embeddings = max_position_embeddings
|
89 |
+
self.base = base
|
90 |
+
# 计算逆频率值,并将其注册为模型的缓冲区
|
91 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
|
92 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
93 |
+
|
94 |
+
# 为了支持`torch.jit.trace`功能,立即计算预存储的余弦和正弦缓存
|
95 |
+
self._set_cos_sin_cache(
|
96 |
+
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
|
97 |
+
)
|
98 |
+
|
99 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
100 |
+
""" 预计算的余弦和正弦缓存
|
101 |
+
"""
|
102 |
+
self.max_seq_len_cached = seq_len
|
103 |
+
# 创建一个从0到最大序列长度-1的整数张量,与 inv_freq 具有相同的设备和数据类型
|
104 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
|
105 |
+
|
106 |
+
# 计算每个位置与每个维度的频率,形成频谱矩阵
|
107 |
+
freqs = torch.outer(t, self.inv_freq)
|
108 |
+
|
109 |
+
# 不同于论文中的实现,这里采用了不同的排列方式以获得相同的计算结果
|
110 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
111 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
112 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
113 |
+
|
114 |
+
def forward(self, x, seq_len=None):
|
115 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
116 |
+
if seq_len > self.max_seq_len_cached:
|
117 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
118 |
+
|
119 |
+
return (
|
120 |
+
self.cos_cached[:seq_len].to(dtype=x.dtype),
|
121 |
+
self.sin_cached[:seq_len].to(dtype=x.dtype),
|
122 |
+
)
|
123 |
+
|
124 |
+
def rotate_half(x):
|
125 |
+
""" 旋转输入一半的 hidden dim
|
126 |
+
"""
|
127 |
+
x1 = x[..., : x.shape[-1] // 2]
|
128 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
129 |
+
return torch.cat((-x2, x1), dim=-1)
|
130 |
+
|
131 |
+
|
132 |
+
# Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
|
133 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
|
134 |
+
""" 在 qk 应用旋转位置编码
|
135 |
+
|
136 |
+
Args:
|
137 |
+
q (`torch.Tensor`): q
|
138 |
+
k (`torch.Tensor`): k
|
139 |
+
cos (`torch.Tensor`): 旋转位置嵌入的余弦部分
|
140 |
+
sin (`torch.Tensor`): 旋转位置嵌入的正弦部分
|
141 |
+
position_ids (`torch.Tensor`): 与q和k对应位置的标记索引。例如,在处理KV缓存时,可以使用偏移过的位置ID。
|
142 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1): 'unsqueeze_dim' 参数指定了沿哪个维度对 cos[position_ids]
|
143 |
+
和 sin[position_ids] 进行扩展,以便它们能够适当地广播到 q 和 k 的维度上。
|
144 |
+
例如,注意 cos[position_ids] 和 sin[position_ids] 具有形状 [batch_size, seq_len, head_dim]。
|
145 |
+
那么,如果 q 和 k 的形状分别为 [batch_size, heads, seq_len, head_dim],
|
146 |
+
则设置 unsqueeze_dim=1 可使 cos[position_ids] 和 sin[position_ids] 可以广播到 q 和 k 的形状上。
|
147 |
+
同样地,如果 q 和 k 的形状为 [batch_size, seq_len, heads, head_dim],则应将 unsqueeze_dim 设置为 2
|
148 |
+
Returns:
|
149 |
+
包含使用旋转位置嵌入变换后的q和k张量的 `tuple(torch.Tensor)`。
|
150 |
+
"""
|
151 |
+
# print("ori cos: ", cos.shape)
|
152 |
+
cos = cos[position_ids].unsqueeze(unsqueeze_dim)
|
153 |
+
sin = sin[position_ids].unsqueeze(unsqueeze_dim)
|
154 |
+
|
155 |
+
# print("q: ", q.shape)
|
156 |
+
# print("cos: ", cos.shape)
|
157 |
+
# print("sin: ", sin.shape)
|
158 |
+
# print("rotate_half: ", rotate_half(q).shape)
|
159 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
160 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
161 |
+
return q_embed, k_embed
|
162 |
+
|
163 |
+
|
164 |
+
class TinyllmMLP(nn.Module):
|
165 |
+
def __init__(self, config):
|
166 |
+
super().__init__()
|
167 |
+
self.config = config
|
168 |
+
self.hidden_size = config.hidden_size
|
169 |
+
self.intermediate_size = config.intermediate_size
|
170 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
171 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
172 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
173 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
174 |
+
|
175 |
+
def forward(self, x):
|
176 |
+
intermediate = self.act_fn(self.gate_proj(x)) * self.up_proj(x)
|
177 |
+
down_proj = self.down_proj(intermediate)
|
178 |
+
return down_proj
|
179 |
+
|
180 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
181 |
+
"""
|
182 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
183 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
184 |
+
"""
|
185 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
186 |
+
if n_rep == 1:
|
187 |
+
return hidden_states
|
188 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
189 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
190 |
+
|
191 |
+
class TinyllmAttention(nn.Module):
|
192 |
+
""" 多头注意力
|
193 |
+
"""
|
194 |
+
|
195 |
+
def __init__(self, config: TinyllmConfig, layer_idx: Optional[int] = None):
|
196 |
+
super().__init__()
|
197 |
+
self.config = config
|
198 |
+
self.layer_idx = layer_idx
|
199 |
+
if layer_idx is None:
|
200 |
+
logger.warning_once(
|
201 |
+
f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
202 |
+
"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
203 |
+
"when creating this class."
|
204 |
+
)
|
205 |
+
|
206 |
+
self.hidden_size = config.hidden_size
|
207 |
+
self.num_heads = config.num_attention_heads
|
208 |
+
self.head_dim = self.hidden_size // self.num_heads
|
209 |
+
self.num_key_value_heads = config.num_key_value_heads
|
210 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
211 |
+
self.max_position_embeddings = config.max_position_embeddings
|
212 |
+
self.rope_theta = config.rope_theta
|
213 |
+
# 因果自回归模式
|
214 |
+
self.is_causal = True
|
215 |
+
self.attention_dropout = config.attention_dropout
|
216 |
+
|
217 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
218 |
+
raise ValueError(
|
219 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
220 |
+
f" and `num_heads`: {self.num_heads})."
|
221 |
+
)
|
222 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
|
223 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
|
224 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
|
225 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
226 |
+
|
227 |
+
self.rotary_emb = TinyllmRotaryEmbedding(
|
228 |
+
self.head_dim,
|
229 |
+
max_position_embeddings=self.max_position_embeddings,
|
230 |
+
base=self.rope_theta,
|
231 |
+
)
|
232 |
+
|
233 |
+
def forward(
|
234 |
+
self,
|
235 |
+
hidden_states: torch.Tensor,
|
236 |
+
attention_mask: Optional[torch.Tensor] = None,
|
237 |
+
position_ids: Optional[torch.LongTensor] = None,
|
238 |
+
past_key_value: Optional[Cache] = None,
|
239 |
+
output_attentions: bool = False,
|
240 |
+
use_cache: bool = False,
|
241 |
+
**kwargs,
|
242 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
243 |
+
if "padding_mask" in kwargs:
|
244 |
+
warnings.warn(
|
245 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
246 |
+
)
|
247 |
+
bsz, q_len, _ = hidden_states.size()
|
248 |
+
|
249 |
+
query_states = self.q_proj(hidden_states)
|
250 |
+
key_states = self.k_proj(hidden_states)
|
251 |
+
value_states = self.v_proj(hidden_states)
|
252 |
+
|
253 |
+
# 重新投影,变成多头注意力结构
|
254 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
255 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
256 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
257 |
+
|
258 |
+
kv_seq_len = key_states.shape[-2]
|
259 |
+
if past_key_value is not None:
|
260 |
+
if self.layer_idx is None:
|
261 |
+
raise ValueError(
|
262 |
+
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
263 |
+
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
264 |
+
"with a layer index."
|
265 |
+
)
|
266 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
267 |
+
# 应用旋转位置编码到 qk 向量
|
268 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
269 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
270 |
+
|
271 |
+
# 如果存在缓存,则更新 kv
|
272 |
+
if past_key_value is not None:
|
273 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
274 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
275 |
+
|
276 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
277 |
+
# 如果 num_key_value_heads 小于 num_heads,则重复key和value向量以匹配头数量
|
278 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
279 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
280 |
+
|
281 |
+
# 计算注意力权重
|
282 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
283 |
+
|
284 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
285 |
+
raise ValueError(
|
286 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
287 |
+
f" {attn_weights.size()}"
|
288 |
+
)
|
289 |
+
|
290 |
+
if attention_mask is not None:
|
291 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
292 |
+
raise ValueError(
|
293 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
294 |
+
)
|
295 |
+
|
296 |
+
attn_weights = attn_weights + attention_mask
|
297 |
+
|
298 |
+
# softmax归一化注意力权重,并转换至float32类型以防止数值溢出
|
299 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
300 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
301 |
+
# 注意力输出
|
302 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
303 |
+
|
304 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
305 |
+
raise ValueError(
|
306 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
307 |
+
f" {attn_output.size()}"
|
308 |
+
)
|
309 |
+
|
310 |
+
# 还原注意力输出的形状以与后续层对接
|
311 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
312 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
313 |
+
|
314 |
+
# 通过o_proj层进一步处理注意力输出
|
315 |
+
attn_output = self.o_proj(attn_output)
|
316 |
+
|
317 |
+
if not output_attentions:
|
318 |
+
attn_weights = None
|
319 |
+
|
320 |
+
return attn_output, attn_weights, past_key_value
|
321 |
+
|
322 |
+
class TinyllmSdpaAttention(TinyllmAttention):
|
323 |
+
""" 使用 torch.nn.functional.scaled_dot_product_attention 实现的注意力模块。
|
324 |
+
该模块继承自 `TinyllmAttention`,因为模块的权重保持不变。唯一的变化在于前向传播过程中适应 SDPA API。
|
325 |
+
Scaled Dot Product Attention (SDPA)
|
326 |
+
"""
|
327 |
+
|
328 |
+
def forward(
|
329 |
+
self,
|
330 |
+
hidden_states: torch.Tensor,
|
331 |
+
attention_mask: Optional[torch.Tensor] = None,
|
332 |
+
position_ids: Optional[torch.LongTensor] = None,
|
333 |
+
past_key_value: Optional[Cache] = None,
|
334 |
+
output_attentions: bool = False,
|
335 |
+
use_cache: bool = False,
|
336 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
337 |
+
# 当设置output_attentions=True时,由于torch.nn.functional.scaled_dot_product_attention不支持直接返回注意力权重
|
338 |
+
# 因此暂时降级回用父类的手动实现方式,并发出警告提示用户未来版本的更改要求
|
339 |
+
if output_attentions:
|
340 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
341 |
+
logger.warning_once(
|
342 |
+
"Model is using SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
|
343 |
+
'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
344 |
+
)
|
345 |
+
return super().forward(
|
346 |
+
hidden_states=hidden_states,
|
347 |
+
attention_mask=attention_mask,
|
348 |
+
position_ids=position_ids,
|
349 |
+
past_key_value=past_key_value,
|
350 |
+
output_attentions=output_attentions,
|
351 |
+
use_cache=use_cache,
|
352 |
+
)
|
353 |
+
# 获取输入维度信息
|
354 |
+
bsz, q_len, _ = hidden_states.size()
|
355 |
+
|
356 |
+
# 对输入进行线性映射得到query、key、value向量
|
357 |
+
query_states = self.q_proj(hidden_states)
|
358 |
+
key_states = self.k_proj(hidden_states)
|
359 |
+
value_states = self.v_proj(hidden_states)
|
360 |
+
|
361 |
+
# 将映射后的向量调整为多头注意力所需格式
|
362 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
363 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
364 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
365 |
+
|
366 |
+
# 计算有效的 kv 序列长度(考虑缓存的情况)
|
367 |
+
kv_seq_len = key_states.shape[-2]
|
368 |
+
if past_key_value is not None:
|
369 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
370 |
+
|
371 |
+
# 应用旋转位置嵌入(RoPE)
|
372 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
373 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
374 |
+
|
375 |
+
# 如果有缓存,更新key和value状态
|
376 |
+
if past_key_value is not None:
|
377 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
378 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
379 |
+
|
380 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
381 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
382 |
+
|
383 |
+
if attention_mask is not None:
|
384 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
385 |
+
raise ValueError(
|
386 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
387 |
+
)
|
388 |
+
|
389 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
390 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
391 |
+
if query_states.device.type == "cuda" and attention_mask is not None:
|
392 |
+
query_states = query_states.contiguous()
|
393 |
+
key_states = key_states.contiguous()
|
394 |
+
value_states = value_states.contiguous()
|
395 |
+
|
396 |
+
# 使用scaled_dot_product_attention进行计算
|
397 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
398 |
+
query_states,
|
399 |
+
key_states,
|
400 |
+
value_states,
|
401 |
+
attn_mask=attention_mask,
|
402 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
403 |
+
# The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
|
404 |
+
is_causal=self.is_causal and attention_mask is None and q_len > 1,
|
405 |
+
)
|
406 |
+
|
407 |
+
# 还原注意力输出的形状
|
408 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
409 |
+
attn_output = attn_output.view(bsz, q_len, self.hidden_size)
|
410 |
+
|
411 |
+
# 将注意力输出通过最终的线性层(o_proj层)
|
412 |
+
attn_output = self.o_proj(attn_output)
|
413 |
+
|
414 |
+
return attn_output, None, past_key_value
|
415 |
+
|
416 |
+
TINYLLM_ATTENTION_CLASSES = {
|
417 |
+
"eager": TinyllmAttention,
|
418 |
+
"sdpa": TinyllmSdpaAttention,
|
419 |
+
}
|
420 |
+
|
421 |
+
class TinyllmDecoderLayer(nn.Module):
|
422 |
+
def __init__(self, config: TinyllmConfig, layer_idx: int):
|
423 |
+
super().__init__()
|
424 |
+
self.hidden_size = config.hidden_size
|
425 |
+
|
426 |
+
self.self_attn = TINYLLM_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
|
427 |
+
self.mlp = TinyllmMLP(config)
|
428 |
+
self.input_layernorm = TinyllmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
429 |
+
self.post_attention_layernorm = TinyllmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
430 |
+
|
431 |
+
def forward(
|
432 |
+
self,
|
433 |
+
hidden_states: torch.Tensor,
|
434 |
+
attention_mask: Optional[torch.Tensor] = None,
|
435 |
+
position_ids: Optional[torch.LongTensor] = None,
|
436 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
437 |
+
output_attentions: Optional[bool] = False,
|
438 |
+
use_cache: Optional[bool] = False,
|
439 |
+
**kwargs,
|
440 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
441 |
+
"""
|
442 |
+
Args:
|
443 |
+
hidden_states (`torch.FloatTensor`): 输入形状 `(batch, seq_len, embed_dim)`
|
444 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask 形状`(batch, sequence_length)`,
|
445 |
+
填充使用0表示
|
446 |
+
output_attentions (`bool`, *optional*): 是否返回所有注意力层的注意力张量。
|
447 |
+
use_cache (`bool`, *optional*): 如果设置为 `True`,则返回 `past_key_values` 关键值状态,可用于加速解码
|
448 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): 缓存的之前kv状态
|
449 |
+
"""
|
450 |
+
|
451 |
+
residual = hidden_states
|
452 |
+
|
453 |
+
hidden_states = self.input_layernorm(hidden_states)
|
454 |
+
|
455 |
+
# Self Attention
|
456 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
457 |
+
hidden_states=hidden_states,
|
458 |
+
attention_mask=attention_mask,
|
459 |
+
position_ids=position_ids,
|
460 |
+
past_key_value=past_key_value,
|
461 |
+
output_attentions=output_attentions,
|
462 |
+
use_cache=use_cache,
|
463 |
+
)
|
464 |
+
hidden_states = residual + hidden_states
|
465 |
+
|
466 |
+
# Fully Connected
|
467 |
+
residual = hidden_states
|
468 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
469 |
+
hidden_states = self.mlp(hidden_states)
|
470 |
+
hidden_states = residual + hidden_states
|
471 |
+
|
472 |
+
outputs = (hidden_states,)
|
473 |
+
|
474 |
+
if output_attentions:
|
475 |
+
outputs += (self_attn_weights,)
|
476 |
+
|
477 |
+
if use_cache:
|
478 |
+
outputs += (present_key_value,)
|
479 |
+
|
480 |
+
return outputs
|
481 |
+
|
482 |
+
|
483 |
+
class TinyllmPreTrainedModel(PreTrainedModel):
|
484 |
+
config_class = TinyllmConfig
|
485 |
+
# 定义了模型内部子模块命名的基础前缀,当加载或保存模型时,这个前缀将用于识别模型主体部分。
|
486 |
+
base_model_prefix = "model"
|
487 |
+
# 表明该模型支持梯度检查点技术,这是一种内存优化策略,可减少模型训练时所需的显存
|
488 |
+
supports_gradient_checkpointing = True
|
489 |
+
# 指定了在序列化过程中不应被拆分的模块列表,即在模型保存与加载时保持这些模块作为一个整体。
|
490 |
+
_no_split_modules = ["TinyllmDecoderLayer"]
|
491 |
+
# 在跨设备数据移动时,指示哪些关键字(key)对应的数据应该跳过设备放置步骤。
|
492 |
+
_skip_keys_device_placement = "past_key_values"
|
493 |
+
# Scaled Dot Product Attention (SDPA)
|
494 |
+
_supports_sdpa = True
|
495 |
+
# 表示模型支持缓存机制,这在自回归模型(如Transformer解码器)中很常见,
|
496 |
+
# 用于存储先前计算的结果以加快后续时间步长的计算速度。
|
497 |
+
_supports_cache_class = True
|
498 |
+
|
499 |
+
def _init_weights(self, module):
|
500 |
+
std = self.config.initializer_range
|
501 |
+
if isinstance(module, nn.Linear):
|
502 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
503 |
+
if module.bias is not None:
|
504 |
+
module.bias.data.zero_()
|
505 |
+
elif isinstance(module, nn.Embedding):
|
506 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
507 |
+
if module.padding_idx is not None:
|
508 |
+
module.weight.data[module.padding_idx].zero_()
|
509 |
+
|
510 |
+
class TinyllmModel(TinyllmPreTrainedModel):
|
511 |
+
""" 根据配置文件堆叠 TinyllmDecoderLayer
|
512 |
+
Args:
|
513 |
+
config: TinyllmConfig
|
514 |
+
"""
|
515 |
+
|
516 |
+
def __init__(self, config: TinyllmConfig):
|
517 |
+
super().__init__(config)
|
518 |
+
self.padding_idx = config.pad_token_id
|
519 |
+
self.vocab_size = config.vocab_size
|
520 |
+
|
521 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
522 |
+
self.layers = nn.ModuleList(
|
523 |
+
[TinyllmDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
524 |
+
)
|
525 |
+
self._attn_implementation = config._attn_implementation
|
526 |
+
self.norm = TinyllmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
527 |
+
|
528 |
+
self.gradient_checkpointing = False
|
529 |
+
# Initialize weights and apply final processing
|
530 |
+
self.post_init()
|
531 |
+
|
532 |
+
def get_input_embeddings(self):
|
533 |
+
return self.embed_tokens
|
534 |
+
|
535 |
+
def set_input_embeddings(self, value):
|
536 |
+
self.embed_tokens = value
|
537 |
+
|
538 |
+
def forward(
|
539 |
+
self,
|
540 |
+
input_ids: torch.LongTensor = None,
|
541 |
+
attention_mask: Optional[torch.Tensor] = None,
|
542 |
+
position_ids: Optional[torch.LongTensor] = None, # 每个输入序列词元在位置嵌入中的位置索引
|
543 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None, # 可用于加速序列解码预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值)
|
544 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
545 |
+
use_cache: Optional[bool] = None,
|
546 |
+
output_attentions: Optional[bool] = None,
|
547 |
+
output_hidden_states: Optional[bool] = None,
|
548 |
+
return_dict: Optional[bool] = None,
|
549 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
550 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
551 |
+
output_hidden_states = (
|
552 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
553 |
+
)
|
554 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
555 |
+
|
556 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
557 |
+
|
558 |
+
# retrieve input_ids and inputs_embeds
|
559 |
+
if input_ids is not None and inputs_embeds is not None:
|
560 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
561 |
+
elif input_ids is not None:
|
562 |
+
batch_size, seq_length = input_ids.shape
|
563 |
+
elif inputs_embeds is not None:
|
564 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
565 |
+
else:
|
566 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
567 |
+
|
568 |
+
if self.gradient_checkpointing and self.training:
|
569 |
+
if use_cache:
|
570 |
+
logger.warning_once(
|
571 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
572 |
+
)
|
573 |
+
use_cache = False
|
574 |
+
|
575 |
+
past_key_values_length = 0
|
576 |
+
|
577 |
+
if use_cache:
|
578 |
+
use_legacy_cache = not isinstance(past_key_values, Cache)
|
579 |
+
if use_legacy_cache:
|
580 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
581 |
+
past_key_values_length = past_key_values.get_usable_length(seq_length)
|
582 |
+
|
583 |
+
if position_ids is None:
|
584 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
585 |
+
# 生成一个从past_key_values_length到seq_length + past_key_values_length的整数序列
|
586 |
+
position_ids = torch.arange(
|
587 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
588 |
+
)
|
589 |
+
# 将生成的序列重塑为形状为(1, seq_length)的张量,然后展平为形状为(-1, seq_length)的张量
|
590 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
591 |
+
else:
|
592 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
593 |
+
|
594 |
+
if inputs_embeds is None:
|
595 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
596 |
+
|
597 |
+
# 适应不同注意力机制对注意力掩码的不同要求而设计的
|
598 |
+
if self._attn_implementation == "sdpa" and not output_attentions:
|
599 |
+
# output_attentions=True can not be supported when using SDPA, and we fall back on
|
600 |
+
# the manual implementation that requires a 4D causal mask in all cases.
|
601 |
+
attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
|
602 |
+
attention_mask,
|
603 |
+
(batch_size, seq_length),
|
604 |
+
inputs_embeds,
|
605 |
+
past_key_values_length,
|
606 |
+
)
|
607 |
+
else:
|
608 |
+
# 4d mask is passed through the layers
|
609 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
610 |
+
attention_mask,
|
611 |
+
(batch_size, seq_length),
|
612 |
+
inputs_embeds,
|
613 |
+
past_key_values_length,
|
614 |
+
sliding_window=self.config.sliding_window,
|
615 |
+
)
|
616 |
+
|
617 |
+
hidden_states = inputs_embeds
|
618 |
+
|
619 |
+
# decoder layers
|
620 |
+
all_hidden_states = () if output_hidden_states else None
|
621 |
+
all_self_attns = () if output_attentions else None
|
622 |
+
next_decoder_cache = None
|
623 |
+
|
624 |
+
for decoder_layer in self.layers:
|
625 |
+
# 1.隐藏状态保存
|
626 |
+
if output_hidden_states:
|
627 |
+
all_hidden_states += (hidden_states,)
|
628 |
+
# 2.梯度检查,方便在反向传播时只激活部分层,节省内存资源
|
629 |
+
# 3.解码层:
|
630 |
+
if self.gradient_checkpointing and self.training:
|
631 |
+
layer_outputs = self._gradient_checkpointing_func(
|
632 |
+
decoder_layer.__call__,
|
633 |
+
hidden_states,
|
634 |
+
attention_mask,
|
635 |
+
position_ids,
|
636 |
+
past_key_values,
|
637 |
+
output_attentions,
|
638 |
+
use_cache,
|
639 |
+
)
|
640 |
+
else:
|
641 |
+
layer_outputs = decoder_layer(
|
642 |
+
hidden_states,
|
643 |
+
attention_mask=attention_mask,
|
644 |
+
position_ids=position_ids,
|
645 |
+
past_key_value=past_key_values,
|
646 |
+
output_attentions=output_attentions,
|
647 |
+
use_cache=use_cache,
|
648 |
+
)
|
649 |
+
# 4.更新隐藏状态
|
650 |
+
hidden_states = layer_outputs[0]
|
651 |
+
# 5.更新缓存
|
652 |
+
if use_cache:
|
653 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
654 |
+
# 6.注意力输出保存
|
655 |
+
if output_attentions:
|
656 |
+
all_self_attns += (layer_outputs[1],)
|
657 |
+
|
658 |
+
hidden_states = self.norm(hidden_states)
|
659 |
+
|
660 |
+
# add hidden states from the last decoder layer
|
661 |
+
if output_hidden_states:
|
662 |
+
all_hidden_states += (hidden_states,)
|
663 |
+
|
664 |
+
next_cache = None
|
665 |
+
if use_cache:
|
666 |
+
next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
|
667 |
+
|
668 |
+
if not return_dict:
|
669 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
670 |
+
return BaseModelOutputWithPast(
|
671 |
+
last_hidden_state=hidden_states,
|
672 |
+
past_key_values=next_cache,
|
673 |
+
hidden_states=all_hidden_states,
|
674 |
+
attentions=all_self_attns,
|
675 |
+
)
|
676 |
+
|
677 |
+
class TinyllmForCausalLM(TinyllmPreTrainedModel):
|
678 |
+
_tied_weights_keys = ["lm_head.weight"]
|
679 |
+
|
680 |
+
def __init__(self, config):
|
681 |
+
super().__init__(config)
|
682 |
+
self.model = TinyllmModel(config)
|
683 |
+
self.vocab_size = config.vocab_size
|
684 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
685 |
+
|
686 |
+
# Initialize weights and apply final processing
|
687 |
+
self.post_init()
|
688 |
+
|
689 |
+
def get_input_embeddings(self):
|
690 |
+
return self.model.embed_tokens
|
691 |
+
|
692 |
+
def set_input_embeddings(self, value):
|
693 |
+
self.model.embed_tokens = value
|
694 |
+
|
695 |
+
def get_output_embeddings(self):
|
696 |
+
return self.lm_head
|
697 |
+
|
698 |
+
def set_output_embeddings(self, new_embeddings):
|
699 |
+
self.lm_head = new_embeddings
|
700 |
+
|
701 |
+
def set_decoder(self, decoder):
|
702 |
+
self.model = decoder
|
703 |
+
|
704 |
+
def get_decoder(self):
|
705 |
+
return self.model
|
706 |
+
|
707 |
+
def forward(
|
708 |
+
self,
|
709 |
+
input_ids: torch.LongTensor = None,
|
710 |
+
attention_mask: Optional[torch.Tensor] = None,
|
711 |
+
position_ids: Optional[torch.LongTensor] = None,
|
712 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
713 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
714 |
+
labels: Optional[torch.LongTensor] = None,
|
715 |
+
use_cache: Optional[bool] = None,
|
716 |
+
output_attentions: Optional[bool] = None,
|
717 |
+
output_hidden_states: Optional[bool] = None,
|
718 |
+
return_dict: Optional[bool] = None,
|
719 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
720 |
+
|
721 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
722 |
+
output_hidden_states = (
|
723 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
724 |
+
)
|
725 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
726 |
+
|
727 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
728 |
+
outputs = self.model(
|
729 |
+
input_ids=input_ids,
|
730 |
+
attention_mask=attention_mask,
|
731 |
+
position_ids=position_ids,
|
732 |
+
past_key_values=past_key_values,
|
733 |
+
inputs_embeds=inputs_embeds,
|
734 |
+
use_cache=use_cache,
|
735 |
+
output_attentions=output_attentions,
|
736 |
+
output_hidden_states=output_hidden_states,
|
737 |
+
return_dict=return_dict,
|
738 |
+
)
|
739 |
+
|
740 |
+
hidden_states = outputs[0]
|
741 |
+
logits = self.lm_head(hidden_states)
|
742 |
+
logits = logits.float()
|
743 |
+
|
744 |
+
loss = None
|
745 |
+
if labels is not None:
|
746 |
+
# Shift so that tokens < n predict n
|
747 |
+
# 对于自回归模型(如GPT系列),我们需要将模型输出的logits向前移动一位,
|
748 |
+
# 这样使得模型预测的是当前时刻 t 的下一个词,而非当前词本身
|
749 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
750 |
+
# 同时,也需要将真实标签(labels)向前移动一位以与调整后的logits对齐
|
751 |
+
shift_labels = labels[..., 1:].contiguous()
|
752 |
+
# Flatten the tokens
|
753 |
+
loss_fct = CrossEntropyLoss(ignore_index=-100)
|
754 |
+
|
755 |
+
# 将移位后的 logits 和 labels 扁平化,即将它们展平为一维张量
|
756 |
+
# 其中shift_logits变成 (batch_size * sequence_length, vocab_size) 的形式
|
757 |
+
# shift_labels变为 (batch_size * sequence_length) 的形式
|
758 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
759 |
+
shift_labels = shift_labels.view(-1)
|
760 |
+
|
761 |
+
# Enable model parallelism
|
762 |
+
# 确保模型并行计算时,labels的数据存储位置与logits一致
|
763 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
764 |
+
loss = loss_fct(shift_logits, shift_labels)
|
765 |
+
|
766 |
+
if not return_dict:
|
767 |
+
output = (logits,) + outputs[1:]
|
768 |
+
return (loss,) + output if loss is not None else output
|
769 |
+
|
770 |
+
return CausalLMOutputWithPast(
|
771 |
+
loss=loss,
|
772 |
+
logits=logits,
|
773 |
+
past_key_values=outputs.past_key_values,
|
774 |
+
hidden_states=outputs.hidden_states,
|
775 |
+
attentions=outputs.attentions,
|
776 |
+
)
|
777 |
+
|
778 |
+
def prepare_inputs_for_generation(
|
779 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
780 |
+
):
|
781 |
+
""" 准备模型的输入参数
|
782 |
+
包括处理input_ids、past_key_values(历史隐藏状态缓存)、attention_mask以及可选的inputs_embeds。
|
783 |
+
"""
|
784 |
+
# Omit tokens covered by past_key_values
|
785 |
+
if past_key_values is not None:
|
786 |
+
if isinstance(past_key_values, Cache):
|
787 |
+
cache_length = past_key_values.get_seq_length()
|
788 |
+
past_length = past_key_values.seen_tokens
|
789 |
+
max_cache_length = past_key_values.get_max_length()
|
790 |
+
else:
|
791 |
+
cache_length = past_length = past_key_values[0][0].shape[2]
|
792 |
+
max_cache_length = None
|
793 |
+
|
794 |
+
# 根据缓存情况裁剪input_ids,只保留未处理的token:
|
795 |
+
# # 1. 如果 attention_mask 比 input_ids 更长,说明部分输入已通过缓存传递(如仅传入inputs_embeds)
|
796 |
+
if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
|
797 |
+
# 取最后未处理的部分
|
798 |
+
input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
|
799 |
+
# 2. 若已处理的 token 数小于input_ids中的总数,表明input_ids包含全部输入,从中去掉已处理的部分
|
800 |
+
elif past_length < input_ids.shape[1]:
|
801 |
+
input_ids = input_ids[:, past_length:]
|
802 |
+
# 3. 否则,认为input_ids中只有待处理的新token
|
803 |
+
|
804 |
+
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
|
805 |
+
if (
|
806 |
+
max_cache_length is not None
|
807 |
+
and attention_mask is not None
|
808 |
+
and cache_length + input_ids.shape[1] > max_cache_length
|
809 |
+
):
|
810 |
+
attention_mask = attention_mask[:, -max_cache_length:]
|
811 |
+
|
812 |
+
# 初始化或处理position_ids
|
813 |
+
position_ids = kwargs.get("position_ids", None)
|
814 |
+
# 如果attention_mask存在但position_ids不存在,则基于attention_mask动态创建position_ids
|
815 |
+
if attention_mask is not None and position_ids is None:
|
816 |
+
# create position_ids on the fly for batch generation
|
817 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
818 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
819 |
+
if past_key_values:
|
820 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
821 |
+
|
822 |
+
# 根据inputs_embeds和past_key_values的存在与否来决定模型输入
|
823 |
+
# 如果提供了inputs_embeds且没有past_key_values(首次生成步骤),则直接使用inputs_embeds作为模型输入
|
824 |
+
if inputs_embeds is not None and past_key_values is None:
|
825 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
826 |
+
else:
|
827 |
+
model_inputs = {"input_ids": input_ids}
|
828 |
+
|
829 |
+
model_inputs.update(
|
830 |
+
{
|
831 |
+
"position_ids": position_ids,
|
832 |
+
"past_key_values": past_key_values,
|
833 |
+
"use_cache": kwargs.get("use_cache"),
|
834 |
+
"attention_mask": attention_mask,
|
835 |
+
}
|
836 |
+
)
|
837 |
+
return model_inputs
|
838 |
+
|
839 |
+
@staticmethod
|
840 |
+
def _reorder_cache(past_key_values, beam_idx):
|
841 |
+
""" 用于重新排序缓存中的历史隐藏状态,以适应束搜索(beam search)算法
|
842 |
+
"""
|
843 |
+
reordered_past = ()
|
844 |
+
# 遍历每一层的隐藏状态
|
845 |
+
for layer_past in past_key_values:
|
846 |
+
# 对于每一层的每个隐藏状态向量,执行索引选择操作
|
847 |
+
reordered_past += (
|
848 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
849 |
+
)
|
850 |
+
return reordered_past
|
851 |
+
|
852 |
+
def chat(self, tokenizer, messages: List[dict], stream=False, generation_config: Optional[GenerationConfig]=None):
|
853 |
+
pass
|
854 |
+
|
855 |
+
class TinyllmForSequenceClassification(TinyllmPreTrainedModel):
|
856 |
+
def __init__(self, config):
|
857 |
+
super().__init__(config)
|
858 |
+
self.num_labels = config.num_labels
|
859 |
+
self.model = TinyllmModel(config)
|
860 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
861 |
+
|
862 |
+
# Initialize weights and apply final processing
|
863 |
+
self.post_init()
|
864 |
+
|
865 |
+
def get_input_embeddings(self):
|
866 |
+
return self.model.embed_tokens
|
867 |
+
|
868 |
+
def set_input_embeddings(self, value):
|
869 |
+
self.model.embed_tokens = value
|
870 |
+
|
871 |
+
def forward(
|
872 |
+
self,
|
873 |
+
input_ids: torch.LongTensor = None,
|
874 |
+
attention_mask: Optional[torch.Tensor] = None,
|
875 |
+
position_ids: Optional[torch.LongTensor] = None,
|
876 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
877 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
878 |
+
labels: Optional[torch.LongTensor] = None,
|
879 |
+
use_cache: Optional[bool] = None,
|
880 |
+
output_attentions: Optional[bool] = None,
|
881 |
+
output_hidden_states: Optional[bool] = None,
|
882 |
+
return_dict: Optional[bool] = None,
|
883 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
884 |
+
|
885 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
886 |
+
|
887 |
+
transformer_outputs = self.model(
|
888 |
+
input_ids,
|
889 |
+
attention_mask=attention_mask,
|
890 |
+
position_ids=position_ids,
|
891 |
+
past_key_values=past_key_values,
|
892 |
+
inputs_embeds=inputs_embeds,
|
893 |
+
use_cache=use_cache,
|
894 |
+
output_attentions=output_attentions,
|
895 |
+
output_hidden_states=output_hidden_states,
|
896 |
+
return_dict=return_dict,
|
897 |
+
)
|
898 |
+
hidden_states = transformer_outputs[0]
|
899 |
+
logits = self.score(hidden_states)
|
900 |
+
|
901 |
+
if input_ids is not None:
|
902 |
+
batch_size = input_ids.shape[0]
|
903 |
+
else:
|
904 |
+
batch_size = inputs_embeds.shape[0]
|
905 |
+
|
906 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
907 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
908 |
+
# 确定输入序列的有效长度,即从起始到第一个填充符出现之前的所有非填充字符的数量
|
909 |
+
if self.config.pad_token_id is None:
|
910 |
+
# 无法计算有效长度
|
911 |
+
sequence_lengths = -1
|
912 |
+
else:
|
913 |
+
if input_ids is not None:
|
914 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
915 |
+
# 对于给定的输入IDs(input_ids),查找其中等于填充符ID的位置
|
916 |
+
# argmax(-1)作用在最后一个维度上,找到每个序列中填充符首次出现的最大索引位置
|
917 |
+
# 因为索引是从0开始的,减去1可得到每个序列的有效字符数(不含填充符)
|
918 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
919 |
+
# 为了保证与ONNX兼容以及防止越界,当序列尾部被完全填充时,采用模运算来保持有效长度
|
920 |
+
# 即使索引超过了输入序列的实际长度,也会自动对应回到有效的范围之内
|
921 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
922 |
+
# 确保计算出的序列长度在与logits相同的设备上,便于后续操作
|
923 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
924 |
+
else:
|
925 |
+
sequence_lengths = -1
|
926 |
+
|
927 |
+
# 提取实际标签对应的logits
|
928 |
+
# 使用arange函数生成一个从0到batch_size-1的索引,并与sequence_lengths结合,
|
929 |
+
# 选取每个样本的有效logit
|
930 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
931 |
+
|
932 |
+
loss = None
|
933 |
+
if labels is not None:
|
934 |
+
labels = labels.to(logits.device)
|
935 |
+
# 若模型配置没有明确指定 problem_type ,则根据num_labels和labels的数据类型推断 problem_type
|
936 |
+
if self.config.problem_type is None:
|
937 |
+
if self.num_labels == 1:
|
938 |
+
self.config.problem_type = "regression"
|
939 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
940 |
+
self.config.problem_type = "single_label_classification"
|
941 |
+
else:
|
942 |
+
self.config.problem_type = "multi_label_classification"
|
943 |
+
|
944 |
+
if self.config.problem_type == "regression":
|
945 |
+
# 使用均方误差损失函数
|
946 |
+
loss_fct = MSELoss()
|
947 |
+
# 如果num_labels为1,则直接计算单输出的损失;否则,按列计算所有输出的损失
|
948 |
+
if self.num_labels == 1:
|
949 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
950 |
+
else:
|
951 |
+
loss = loss_fct(pooled_logits, labels)
|
952 |
+
elif self.config.problem_type == "single_label_classification":
|
953 |
+
# 单标签分类任务,使用交叉熵损失函数
|
954 |
+
loss_fct = CrossEntropyLoss()
|
955 |
+
# 将pooled_logits展平为(batch_size * num_labels)的形式,与同样展平后的labels进行比较
|
956 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
957 |
+
elif self.config.problem_type == "multi_label_classification":
|
958 |
+
# 多标签分类任务,使用带Sigmoid激活的二元交叉熵损失函数
|
959 |
+
loss_fct = BCEWithLogitsLoss()
|
960 |
+
# 直接计算sigmoid之前的logits与标签之间的损失
|
961 |
+
loss = loss_fct(pooled_logits, labels)
|
962 |
+
|
963 |
+
if not return_dict:
|
964 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
965 |
+
return ((loss,) + output) if loss is not None else output
|
966 |
+
|
967 |
+
return SequenceClassifierOutputWithPast(
|
968 |
+
loss=loss,
|
969 |
+
logits=pooled_logits,
|
970 |
+
past_key_values=transformer_outputs.past_key_values,
|
971 |
+
hidden_states=transformer_outputs.hidden_states,
|
972 |
+
attentions=transformer_outputs.attentions,
|
973 |
+
)
|
974 |
+
|
975 |
+
def print_model_parameters(model):
|
976 |
+
""" 打印模型各个层参数
|
977 |
+
"""
|
978 |
+
param_sum = 0
|
979 |
+
for name, param in model.named_parameters():
|
980 |
+
if param.requires_grad:
|
981 |
+
param_sum += param.numel()
|
982 |
+
print(f"Layer: {name}, Parameters: {param.numel()}")
|
983 |
+
print(f"Total of parameters: {param_sum}")
|
984 |
+
|
985 |
+
if __name__ == "__main__":
|
986 |
+
# vocav size https://github.com/THUDM/ChatGLM3/issues/634
|
987 |
+
args_1480m = TinyllmConfig(
|
988 |
+
hidden_size=2048,
|
989 |
+
num_hidden_layers=24,
|
990 |
+
num_attention_heads=16,
|
991 |
+
intermediate_size=5504,
|
992 |
+
rope_theta=10000.0,
|
993 |
+
max_position_embeddings=1024,
|
994 |
+
vocab_size=64798,
|
995 |
+
)
|
996 |
+
|
997 |
+
args_440m = TinyllmConfig(
|
998 |
+
hidden_size=1024,
|
999 |
+
num_hidden_layers=24,
|
1000 |
+
num_attention_heads=16,
|
1001 |
+
intermediate_size=2816,
|
1002 |
+
rope_theta=10000.0,
|
1003 |
+
max_position_embeddings=1024,
|
1004 |
+
vocab_size=64798,
|
1005 |
+
)
|
1006 |
+
|
1007 |
+
args_210m = TinyllmConfig(
|
1008 |
+
hidden_size=768,
|
1009 |
+
num_hidden_layers=16,
|
1010 |
+
num_attention_heads=12,
|
1011 |
+
intermediate_size=2048,
|
1012 |
+
rope_theta=10000.0,
|
1013 |
+
max_position_embeddings=1024,
|
1014 |
+
vocab_size=64798,
|
1015 |
+
)
|
1016 |
+
|
1017 |
+
args_92m = TinyllmConfig(
|
1018 |
+
hidden_size=512,
|
1019 |
+
num_hidden_layers=8,
|
1020 |
+
num_attention_heads=8,
|
1021 |
+
intermediate_size=1408,
|
1022 |
+
rope_theta=10000.0,
|
1023 |
+
max_position_embeddings=1024,
|
1024 |
+
vocab_size=64798,
|
1025 |
+
)
|
1026 |
+
|
1027 |
+
args_42m = TinyllmConfig(
|
1028 |
+
hidden_size=288,
|
1029 |
+
num_hidden_layers=6,
|
1030 |
+
num_attention_heads=6,
|
1031 |
+
intermediate_size=768,
|
1032 |
+
rope_theta=10000.0,
|
1033 |
+
max_position_embeddings=512,
|
1034 |
+
vocab_size=64798,
|
1035 |
+
)
|
1036 |
+
|
1037 |
+
args_16m = TinyllmConfig(
|
1038 |
+
hidden_size=120,
|
1039 |
+
num_hidden_layers=6,
|
1040 |
+
num_attention_heads=6,
|
1041 |
+
intermediate_size=384,
|
1042 |
+
rope_theta=10000.0,
|
1043 |
+
max_position_embeddings=512,
|
1044 |
+
vocab_size=64798,
|
1045 |
+
)
|
1046 |
+
|
1047 |
+
model = TinyllmForCausalLM(args_210m)
|
1048 |
+
|
1049 |
+
inputs_ids = torch.tensor([[1,2,4],[4,3,2]])
|
1050 |
+
labels = torch.tensor([[1,4,3],[2,3,1]])
|
1051 |
+
print(inputs_ids.shape)
|
1052 |
+
outputs = model(input_ids=inputs_ids, labels=labels)
|
1053 |
+
print(outputs.logits)
|
1054 |
+
print(outputs.loss)
|
1055 |
+
|
1056 |
+
# print_model_parameters(model)
|
1057 |
+
|
pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:27541cad46d5000b5012b23c410cc966a3ec03ff7f070ecfe86ba6c49bfb326a
|
3 |
+
size 184142076
|
tokenization_chatglm.py
ADDED
@@ -0,0 +1,389 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import os
|
3 |
+
import re
|
4 |
+
from typing import List, Optional, Union, Dict
|
5 |
+
from sentencepiece import SentencePieceProcessor
|
6 |
+
from transformers import PreTrainedTokenizer
|
7 |
+
from transformers.utils import logging, PaddingStrategy
|
8 |
+
from transformers.tokenization_utils_base import EncodedInput, BatchEncoding
|
9 |
+
|
10 |
+
|
11 |
+
logger = logging.get_logger(__name__)
|
12 |
+
|
13 |
+
|
14 |
+
class SPTokenizer:
|
15 |
+
def __init__(self, model_path: str):
|
16 |
+
# reload tokenizer
|
17 |
+
assert os.path.isfile(model_path), model_path
|
18 |
+
self.sp_model = SentencePieceProcessor(model_file=model_path)
|
19 |
+
|
20 |
+
# BOS / EOS token IDs
|
21 |
+
self.n_words: int = self.sp_model.vocab_size()
|
22 |
+
self.bos_id: int = self.sp_model.bos_id()
|
23 |
+
self.eos_id: int = self.sp_model.eos_id()
|
24 |
+
self.pad_id: int = self.sp_model.unk_id()
|
25 |
+
# 确保vocab_size与piece数量一致
|
26 |
+
assert self.sp_model.vocab_size() == self.sp_model.get_piece_size()
|
27 |
+
|
28 |
+
# 定义聊天角色相关的特殊token
|
29 |
+
role_special_tokens = ["<|system|>", "<|user|>", "<|assistant|>", "<|observation|>"]
|
30 |
+
# 添加额外的通用特殊token
|
31 |
+
special_tokens = ["[MASK]", "[gMASK]", "[sMASK]", "sop", "eop"] + role_special_tokens
|
32 |
+
# 创建特殊token与ID之间的映射关系
|
33 |
+
self.special_tokens = {}
|
34 |
+
self.index_special_tokens = {}
|
35 |
+
for token in special_tokens:
|
36 |
+
# 分配新的词汇表ID给特殊token
|
37 |
+
self.special_tokens[token] = self.n_words
|
38 |
+
self.index_special_tokens[self.n_words] = token
|
39 |
+
self.n_words += 1
|
40 |
+
# 生成正则表达式,用于在apply_chat_template方法中查找特殊token
|
41 |
+
self.role_special_token_expression = "|".join([re.escape(token) for token in special_tokens]) # for apply_chat_template
|
42 |
+
|
43 |
+
def tokenize(self, s: str, encode_special_tokens=False):
|
44 |
+
""" 对输入字符串进行分词操作,可选择是否编码特殊token
|
45 |
+
"""
|
46 |
+
if encode_special_tokens:
|
47 |
+
# 对特殊字符进行处理
|
48 |
+
last_index = 0
|
49 |
+
t = []
|
50 |
+
for match in re.finditer(self.role_special_token_expression, s):
|
51 |
+
# 查找并保留非特殊token部分的分词结果
|
52 |
+
if last_index < match.start():
|
53 |
+
t.extend(self.sp_model.EncodeAsPieces(s[last_index:match.start()]))
|
54 |
+
# 直接添加特殊token
|
55 |
+
t.append(s[match.start():match.end()])
|
56 |
+
last_index = match.end()
|
57 |
+
# 处理剩余非特殊token部分
|
58 |
+
if last_index < len(s):
|
59 |
+
t.extend(self.sp_model.EncodeAsPieces(s[last_index:]))
|
60 |
+
return t
|
61 |
+
else:
|
62 |
+
# 当encode_special_tokens为False时,直接调用SentencePiece模型进行分词
|
63 |
+
return self.sp_model.EncodeAsPieces(s)
|
64 |
+
|
65 |
+
def encode(self, s: str, bos: bool = False, eos: bool = False) -> List[int]:
|
66 |
+
""" 将字符串转化为ID列表,可选择是否添加BOS/EOS token
|
67 |
+
"""
|
68 |
+
assert type(s) is str
|
69 |
+
t = self.sp_model.encode(s)
|
70 |
+
if bos:
|
71 |
+
t = [self.bos_id] + t
|
72 |
+
if eos:
|
73 |
+
t = t + [self.eos_id]
|
74 |
+
return t
|
75 |
+
|
76 |
+
def decode(self, t: List[int]) -> str:
|
77 |
+
""" 将ID列表解码为字符串
|
78 |
+
"""
|
79 |
+
text, buffer = "", []
|
80 |
+
for token in t:
|
81 |
+
# 处理特殊tokenID转字符串
|
82 |
+
if token in self.index_special_tokens:
|
83 |
+
if buffer:
|
84 |
+
text += self.sp_model.decode(buffer)
|
85 |
+
buffer = []
|
86 |
+
text += self.index_special_tokens[token]
|
87 |
+
else:
|
88 |
+
buffer.append(token)
|
89 |
+
# 解码剩余普通tokenID
|
90 |
+
if buffer:
|
91 |
+
text += self.sp_model.decode(buffer)
|
92 |
+
return text
|
93 |
+
|
94 |
+
def decode_tokens(self, tokens: List[str]) -> str:
|
95 |
+
""" 将分词结果(List[str])解码为字符串
|
96 |
+
"""
|
97 |
+
text = self.sp_model.DecodePieces(tokens)
|
98 |
+
return text
|
99 |
+
|
100 |
+
def convert_token_to_id(self, token):
|
101 |
+
""" 将给定的token字符串转化为对应的ID
|
102 |
+
"""
|
103 |
+
if token in self.special_tokens:
|
104 |
+
return self.special_tokens[token]
|
105 |
+
return self.sp_model.PieceToId(token)
|
106 |
+
|
107 |
+
def convert_id_to_token(self, index):
|
108 |
+
""" 将给定的ID转化为对应的token字符串
|
109 |
+
"""
|
110 |
+
# 处理特殊tokenID
|
111 |
+
if index in self.index_special_tokens:
|
112 |
+
return self.index_special_tokens[index]
|
113 |
+
# 处理边界情况和其他特殊ID
|
114 |
+
if index in [self.eos_id, self.bos_id, self.pad_id] or index < 0 or index > self.sp_model.vocab_size():
|
115 |
+
return ""
|
116 |
+
# 将普通ID转换为token
|
117 |
+
return self.sp_model.IdToPiece(index)
|
118 |
+
|
119 |
+
|
120 |
+
class ChatGLMTokenizer(PreTrainedTokenizer):
|
121 |
+
# 预训练模型所需的文件名配置,这里指向tokenizer的model文件
|
122 |
+
vocab_files_names = {"vocab_file": "tokenizer.model"}
|
123 |
+
# 模型输入的特征名称列表
|
124 |
+
model_input_names = ["input_ids", "attention_mask", "position_ids"]
|
125 |
+
|
126 |
+
def __init__(
|
127 |
+
self,
|
128 |
+
vocab_file,
|
129 |
+
padding_side="left",
|
130 |
+
clean_up_tokenization_spaces=False,
|
131 |
+
encode_special_tokens=False,
|
132 |
+
**kwargs
|
133 |
+
):
|
134 |
+
# 设置tokenizer的名称
|
135 |
+
self.name = "GLMTokenizer"
|
136 |
+
# 存储vocab文件路径
|
137 |
+
self.vocab_file = vocab_file
|
138 |
+
# 使用SPTokenizer作为基础分词器
|
139 |
+
self.tokenizer = SPTokenizer(vocab_file)
|
140 |
+
# 定义特殊token及其对应的ID
|
141 |
+
self.special_tokens = {
|
142 |
+
"<bos>": self.tokenizer.bos_id,
|
143 |
+
"<eos>": self.tokenizer.eos_id,
|
144 |
+
"<unk>": self.tokenizer.pad_id,
|
145 |
+
"<pad>": self.tokenizer.pad_id
|
146 |
+
}
|
147 |
+
self.encode_special_tokens = encode_special_tokens
|
148 |
+
|
149 |
+
super().__init__(
|
150 |
+
padding_side=padding_side,
|
151 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
152 |
+
**kwargs
|
153 |
+
)
|
154 |
+
|
155 |
+
def get_command(self, token):
|
156 |
+
""" 获取指定特殊 token 对应的 id
|
157 |
+
"""
|
158 |
+
if token in self.special_tokens:
|
159 |
+
return self.special_tokens[token]
|
160 |
+
# 如果不在自定义特殊 token 中,则从基础SPTokenizer的特殊 token 中查找
|
161 |
+
assert token in self.tokenizer.special_tokens, f"{token} is not a special token for {self.name}"
|
162 |
+
return self.tokenizer.special_tokens[token]
|
163 |
+
|
164 |
+
@property
|
165 |
+
def unk_token(self) -> str:
|
166 |
+
""" 通过ID获取未登录词、填充符和结束符的字符串形式
|
167 |
+
"""
|
168 |
+
return self.tokenizer.sp_model.IdToPiece(self.get_command("<unk>"))
|
169 |
+
|
170 |
+
@property
|
171 |
+
def pad_token(self) -> str:
|
172 |
+
return self.tokenizer.sp_model.IdToPiece(self.get_command("<pad>"))
|
173 |
+
|
174 |
+
@property
|
175 |
+
def eos_token(self) -> str:
|
176 |
+
return self.tokenizer.sp_model.IdToPiece(self.get_command("<eos>"))
|
177 |
+
|
178 |
+
@property
|
179 |
+
def unk_token_id(self) -> int:
|
180 |
+
""" 获取未登录词、填充符和结束符的ID形式
|
181 |
+
"""
|
182 |
+
return self.get_command("<unk>")
|
183 |
+
|
184 |
+
@property
|
185 |
+
def pad_token_id(self) -> int:
|
186 |
+
return self.get_command("<pad>")
|
187 |
+
|
188 |
+
@property
|
189 |
+
def eos_token_id(self):
|
190 |
+
return self.get_command("<eos>")
|
191 |
+
|
192 |
+
@unk_token.setter
|
193 |
+
def unk_token(self, value):
|
194 |
+
""" 不支持设置未登录词、填充符和结束符,输出警告信息
|
195 |
+
"""
|
196 |
+
logger.warning("Setting unk_token is not supported, use the default one.")
|
197 |
+
|
198 |
+
@pad_token.setter
|
199 |
+
def pad_token(self, value):
|
200 |
+
logger.warning("Setting pad_token is not supported, use the default one.")
|
201 |
+
|
202 |
+
@eos_token.setter
|
203 |
+
def eos_token(self, value):
|
204 |
+
logger.warning("Setting eos_token is not supported, use the default one.")
|
205 |
+
|
206 |
+
@property
|
207 |
+
def vocab_size(self):
|
208 |
+
""" 返回整个词汇表的大小
|
209 |
+
"""
|
210 |
+
return self.tokenizer.n_words
|
211 |
+
|
212 |
+
def get_vocab(self):
|
213 |
+
""" 获取词汇表字典,其中键是token,值是其对应的ID
|
214 |
+
"""
|
215 |
+
vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
|
216 |
+
vocab.update(self.added_tokens_encoder)
|
217 |
+
return vocab
|
218 |
+
|
219 |
+
def _tokenize(self, text, **kwargs):
|
220 |
+
""" 实现分词功能,利用SPTokenizer进行分词操作
|
221 |
+
"""
|
222 |
+
return self.tokenizer.tokenize(text, encode_special_tokens=self.encode_special_tokens)
|
223 |
+
|
224 |
+
def _convert_token_to_id(self, token):
|
225 |
+
""" 将token字符串转化为ID
|
226 |
+
"""
|
227 |
+
return self.tokenizer.convert_token_to_id(token)
|
228 |
+
|
229 |
+
def _convert_id_to_token(self, index):
|
230 |
+
""" 将ID转化为token字符串
|
231 |
+
"""
|
232 |
+
return self.tokenizer.convert_id_to_token(index)
|
233 |
+
|
234 |
+
def convert_tokens_to_string(self, tokens: List[str]) -> str:
|
235 |
+
""" 将分词结果的tokens列表还原为字符串
|
236 |
+
"""
|
237 |
+
return self.tokenizer.decode_tokens(tokens)
|
238 |
+
|
239 |
+
def save_vocabulary(self, save_directory, filename_prefix=None):
|
240 |
+
""" 将词汇表和特殊令牌token保存到指定目录。
|
241 |
+
|
242 |
+
Args:
|
243 |
+
save_directory (`str`): 将词汇表和特殊令牌文件保存到指定目录。
|
244 |
+
filename_prefix (`str`, *optional*): 可选添加到保存文件名前的前缀。
|
245 |
+
|
246 |
+
Returns:
|
247 |
+
`Tuple(str)`: 保存文件的路径
|
248 |
+
"""
|
249 |
+
if os.path.isdir(save_directory):
|
250 |
+
vocab_file = os.path.join(
|
251 |
+
save_directory, self.vocab_files_names["vocab_file"]
|
252 |
+
)
|
253 |
+
else:
|
254 |
+
vocab_file = save_directory
|
255 |
+
|
256 |
+
with open(self.vocab_file, 'rb') as fin:
|
257 |
+
proto_str = fin.read()
|
258 |
+
|
259 |
+
with open(vocab_file, "wb") as writer:
|
260 |
+
writer.write(proto_str)
|
261 |
+
|
262 |
+
return (vocab_file,)
|
263 |
+
|
264 |
+
def get_prefix_tokens(self):
|
265 |
+
""" 获取用于模型输入的前缀 token
|
266 |
+
"""
|
267 |
+
prefix_tokens = [self.get_command("[gMASK]"), self.get_command("sop")]
|
268 |
+
return prefix_tokens
|
269 |
+
|
270 |
+
def build_single_message(self, role, metadata, message):
|
271 |
+
""" 构建单条消息的 token 序列
|
272 |
+
"""
|
273 |
+
assert role in ["system", "user", "assistant", "observation"], role
|
274 |
+
# 构建角色标识Token序列
|
275 |
+
role_tokens = [self.get_command(f"<|{role}|>")] + self.tokenizer.encode(f"{metadata}\n")
|
276 |
+
# 构建消息正文Token序列
|
277 |
+
message_tokens = self.tokenizer.encode(message)
|
278 |
+
# 合并角色标识Token与消息正文Token
|
279 |
+
tokens = role_tokens + message_tokens
|
280 |
+
return tokens
|
281 |
+
|
282 |
+
def build_chat_input(self, query, history=None, role="user"):
|
283 |
+
""" 根据对话历史及当前query构建模型输入
|
284 |
+
"""
|
285 |
+
if history is None:
|
286 |
+
history = []
|
287 |
+
input_ids = []
|
288 |
+
# 遍历对话历史
|
289 |
+
for item in history:
|
290 |
+
# 获取内容
|
291 |
+
content = item["content"]
|
292 |
+
# 若为系统消息且包含工具信息,将其加入内容
|
293 |
+
if item["role"] == "system" and "tools" in item:
|
294 |
+
content = content + "\n" + json.dumps(item["tools"], indent=4, ensure_ascii=False)
|
295 |
+
# 构建单条历史消息的Token序列并加入到模型输入ID列表
|
296 |
+
input_ids.extend(self.build_single_message(item["role"], item.get("metadata", ""), content))
|
297 |
+
# 构建当前query的Token序列并加入到模型输入ID列表
|
298 |
+
input_ids.extend(self.build_single_message(role, "", query))
|
299 |
+
# 添加表示回复的assistant标记
|
300 |
+
input_ids.extend([self.get_command("<|assistant|>")])
|
301 |
+
# 调用tokenizer批量编码方法,返回PyTorch张量形式的模型输入
|
302 |
+
return self.batch_encode_plus([input_ids], return_tensors="pt", is_split_into_words=True)
|
303 |
+
|
304 |
+
def build_inputs_with_special_tokens(
|
305 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
306 |
+
) -> List[int]:
|
307 |
+
""" 通过拼接和添加特殊标记,从一个或两个序列构建用于序列分类任务的模型输入。
|
308 |
+
|
309 |
+
BERT序列格式如下:
|
310 |
+
- 单一序列:`[CLS] X [SEP]`
|
311 |
+
- 序列对:`[CLS] A [SEP] B [SEP]`
|
312 |
+
|
313 |
+
Args:
|
314 |
+
token_ids_0 (`List[int]`): 将添加特殊token的IDs列表
|
315 |
+
token_ids_1 (`List[int]`, *optional*): 可选的第二个序列的IDs列表,用于序列对。
|
316 |
+
|
317 |
+
Returns:
|
318 |
+
`List[int]`: 包含适当特殊标记的[输入IDs](../glossary#input-ids)列表。
|
319 |
+
"""
|
320 |
+
# 获取前缀标记
|
321 |
+
prefix_tokens = self.get_prefix_tokens()
|
322 |
+
# 在token_ids_0前添加前缀标记
|
323 |
+
token_ids_0 = prefix_tokens + token_ids_0
|
324 |
+
# 若存在token_ids_1,将token_ids_0、token_ids_1连接,并添加结束标记,然后返回
|
325 |
+
if token_ids_1 is not None:
|
326 |
+
token_ids_0 = token_ids_0 + token_ids_1 + [self.get_command("<eos>")]
|
327 |
+
return token_ids_0
|
328 |
+
|
329 |
+
def _pad(
|
330 |
+
self,
|
331 |
+
encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
|
332 |
+
max_length: Optional[int] = None,
|
333 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
334 |
+
pad_to_multiple_of: Optional[int] = None,
|
335 |
+
return_attention_mask: Optional[bool] = None,
|
336 |
+
) -> dict:
|
337 |
+
""" 此方法用于对编码后的输入进行填充(左右两侧填充,直至达到预设长度或批次中的最大长度)
|
338 |
+
|
339 |
+
Args:
|
340 |
+
encoded_inputs: 字典形式的编码后输入,键为特征名称,值为整数列表(例如,`List[int]`),或者一批编码后的输入(例如,`List[List[int]]`)。
|
341 |
+
max_length: 返回列表的最大长度,也可作为填充长度
|
342 |
+
padding_strategy: 填充策略,有以下选项:
|
343 |
+
- PaddingStrategy.LONGEST : 根据批次中最长序列进行填充
|
344 |
+
- PaddingStrategy.MAX_LENGTH: 默认策略,填充至最大长度
|
345 |
+
- PaddingStrategy.DO_NOT_PAD: 不进行填充
|
346 |
+
本tokenizer的填充方向由self.padding_side属性决定:
|
347 |
+
- 'left': 在序列左侧填充
|
348 |
+
- 'right': 在序列右侧填充
|
349 |
+
pad_to_multiple_of: (可选)若设置,则将序列填充至给定值的倍数。这对于在NVIDIA硬件上启用具有计算能力`>= 7.5`(Volta及以上)的Tensor Core非常有用。
|
350 |
+
return_attention_mask:(可选)若设置为False,则避免返回注意力掩码(默认:根据模型特性设置
|
351 |
+
"""
|
352 |
+
# 从模型默认设置中加载填充侧信息
|
353 |
+
assert self.padding_side == "left"
|
354 |
+
|
355 |
+
# 获取必要的输入特征,这里假设第一个特征为主要输入特征
|
356 |
+
required_input = encoded_inputs[self.model_input_names[0]]
|
357 |
+
seq_length = len(required_input)
|
358 |
+
|
359 |
+
# 如果填充策略为最长序列,则将最大长度设置为当前序列长度
|
360 |
+
if padding_strategy == PaddingStrategy.LONGEST:
|
361 |
+
max_length = len(required_input)
|
362 |
+
|
363 |
+
# 计算实际最大长度,确保满足pad_to_multiple_of的要求
|
364 |
+
if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
|
365 |
+
max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
|
366 |
+
|
367 |
+
# 判断是否需要填充
|
368 |
+
needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
|
369 |
+
|
370 |
+
# 若不存在注意力掩码,则初始化
|
371 |
+
if "attention_mask" not in encoded_inputs:
|
372 |
+
encoded_inputs["attention_mask"] = [1] * seq_length
|
373 |
+
|
374 |
+
if "position_ids" not in encoded_inputs:
|
375 |
+
encoded_inputs["position_ids"] = list(range(seq_length))
|
376 |
+
|
377 |
+
# 若需要填充,则执行填充操作
|
378 |
+
if needs_to_be_padded:
|
379 |
+
difference = max_length - len(required_input)
|
380 |
+
# 对注意力掩码进行填充
|
381 |
+
if "attention_mask" in encoded_inputs:
|
382 |
+
encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
|
383 |
+
# 对位置标识进行填充
|
384 |
+
if "position_ids" in encoded_inputs:
|
385 |
+
encoded_inputs["position_ids"] = [0] * difference + encoded_inputs["position_ids"]
|
386 |
+
# 对主要输入特征进行填充
|
387 |
+
encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
|
388 |
+
|
389 |
+
return encoded_inputs
|
tokenizer.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e7dc4c393423b76e4373e5157ddc34803a0189ba96b21ddbb40269d31468a6f2
|
3 |
+
size 1018370
|
tokenizer_config.json
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"added_tokens_decoder": {
|
3 |
+
"64790": {
|
4 |
+
"content": "[gMASK]",
|
5 |
+
"lstrip": false,
|
6 |
+
"normalized": true,
|
7 |
+
"rstrip": false,
|
8 |
+
"single_word": false,
|
9 |
+
"special": false
|
10 |
+
},
|
11 |
+
"64792": {
|
12 |
+
"content": "sop",
|
13 |
+
"lstrip": false,
|
14 |
+
"normalized": true,
|
15 |
+
"rstrip": false,
|
16 |
+
"single_word": false,
|
17 |
+
"special": false
|
18 |
+
},
|
19 |
+
"64795": {
|
20 |
+
"content": "<|user|>",
|
21 |
+
"lstrip": false,
|
22 |
+
"normalized": true,
|
23 |
+
"rstrip": false,
|
24 |
+
"single_word": false,
|
25 |
+
"special": false
|
26 |
+
},
|
27 |
+
"64796": {
|
28 |
+
"content": "<|assistant|>",
|
29 |
+
"lstrip": false,
|
30 |
+
"normalized": true,
|
31 |
+
"rstrip": false,
|
32 |
+
"single_word": false,
|
33 |
+
"special": false
|
34 |
+
}
|
35 |
+
},
|
36 |
+
"auto_map": {
|
37 |
+
"AutoTokenizer": [
|
38 |
+
"tokenization_chatglm.ChatGLMTokenizer",
|
39 |
+
null
|
40 |
+
]
|
41 |
+
},
|
42 |
+
"chat_template": "{% for message in messages %}{% if loop.first %}[gMASK]sop<|{{ message['role'] }}|>\n {{ message['content'] }}{% else %}<|{{ message['role'] }}|>\n {{ message['content'] }}{% endif %}{% endfor %}{% if add_generation_prompt %}<|assistant|>{% endif %}",
|
43 |
+
"clean_up_tokenization_spaces": false,
|
44 |
+
"do_lower_case": false,
|
45 |
+
"eos_token": "</s>",
|
46 |
+
"model_max_length": 1000000000000000019884624838656,
|
47 |
+
"pad_token": "<unk>",
|
48 |
+
"padding_side": "left",
|
49 |
+
"remove_space": false,
|
50 |
+
"tokenizer_class": "ChatGLMTokenizer",
|
51 |
+
"unk_token": "<unk>"
|
52 |
+
}
|
vocab.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|