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