zhouliang
commited on
Commit
•
a7eeac5
1
Parent(s):
db333d6
Upload 86 files
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- config.json +30 -0
- configuration_yi.py +121 -0
- generation_config.json +7 -0
- modeling_yi.py +1030 -0
- pytorch_model-00001-of-00077.bin +3 -0
- pytorch_model-00002-of-00077.bin +3 -0
- pytorch_model-00003-of-00077.bin +3 -0
- pytorch_model-00004-of-00077.bin +3 -0
- pytorch_model-00005-of-00077.bin +3 -0
- pytorch_model-00006-of-00077.bin +3 -0
- pytorch_model-00007-of-00077.bin +3 -0
- pytorch_model-00008-of-00077.bin +3 -0
- pytorch_model-00009-of-00077.bin +3 -0
- pytorch_model-00010-of-00077.bin +3 -0
- pytorch_model-00011-of-00077.bin +3 -0
- pytorch_model-00012-of-00077.bin +3 -0
- pytorch_model-00013-of-00077.bin +3 -0
- pytorch_model-00014-of-00077.bin +3 -0
- pytorch_model-00015-of-00077.bin +3 -0
- pytorch_model-00016-of-00077.bin +3 -0
- pytorch_model-00017-of-00077.bin +3 -0
- pytorch_model-00018-of-00077.bin +3 -0
- pytorch_model-00019-of-00077.bin +3 -0
- pytorch_model-00020-of-00077.bin +3 -0
- pytorch_model-00021-of-00077.bin +3 -0
- pytorch_model-00022-of-00077.bin +3 -0
- pytorch_model-00023-of-00077.bin +3 -0
- pytorch_model-00024-of-00077.bin +3 -0
- pytorch_model-00025-of-00077.bin +3 -0
- pytorch_model-00026-of-00077.bin +3 -0
- pytorch_model-00027-of-00077.bin +3 -0
- pytorch_model-00028-of-00077.bin +3 -0
- pytorch_model-00029-of-00077.bin +3 -0
- pytorch_model-00030-of-00077.bin +3 -0
- pytorch_model-00031-of-00077.bin +3 -0
- pytorch_model-00032-of-00077.bin +3 -0
- pytorch_model-00033-of-00077.bin +3 -0
- pytorch_model-00034-of-00077.bin +3 -0
- pytorch_model-00035-of-00077.bin +3 -0
- pytorch_model-00036-of-00077.bin +3 -0
- pytorch_model-00037-of-00077.bin +3 -0
- pytorch_model-00038-of-00077.bin +3 -0
- pytorch_model-00039-of-00077.bin +3 -0
- pytorch_model-00040-of-00077.bin +3 -0
- pytorch_model-00041-of-00077.bin +3 -0
- pytorch_model-00042-of-00077.bin +3 -0
- pytorch_model-00043-of-00077.bin +3 -0
- pytorch_model-00044-of-00077.bin +3 -0
- pytorch_model-00045-of-00077.bin +3 -0
- pytorch_model-00046-of-00077.bin +3 -0
config.json
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "/DATA4T/text-generation-webui/models/yi-sex",
|
3 |
+
"architectures": [
|
4 |
+
"YiForCausalLM"
|
5 |
+
],
|
6 |
+
"auto_map": {
|
7 |
+
"AutoConfig": "configuration_yi.YiConfig",
|
8 |
+
"AutoModel": "modeling_yi.YiForCausalLM",
|
9 |
+
"AutoModelForCausalLM": "modeling_yi.YiForCausalLM"
|
10 |
+
},
|
11 |
+
"bos_token_id": 1,
|
12 |
+
"eos_token_id": 2,
|
13 |
+
"hidden_act": "silu",
|
14 |
+
"hidden_size": 7168,
|
15 |
+
"initializer_range": 0.02,
|
16 |
+
"intermediate_size": 20480,
|
17 |
+
"max_position_embeddings": 4096,
|
18 |
+
"model_type": "Yi",
|
19 |
+
"num_attention_heads": 56,
|
20 |
+
"num_hidden_layers": 60,
|
21 |
+
"num_key_value_heads": 8,
|
22 |
+
"pad_token_id": 0,
|
23 |
+
"rms_norm_eps": 1e-05,
|
24 |
+
"rope_theta": 5000000.0,
|
25 |
+
"tie_word_embeddings": false,
|
26 |
+
"torch_dtype": "bfloat16",
|
27 |
+
"transformers_version": "4.34.1",
|
28 |
+
"use_cache": true,
|
29 |
+
"vocab_size": 64000
|
30 |
+
}
|
configuration_yi.py
ADDED
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" Yi model configuration"""
|
2 |
+
from transformers.configuration_utils import PretrainedConfig
|
3 |
+
from transformers.utils import logging
|
4 |
+
|
5 |
+
logger = logging.get_logger(__name__)
|
6 |
+
|
7 |
+
Yi_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
8 |
+
|
9 |
+
|
10 |
+
class YiConfig(PretrainedConfig):
|
11 |
+
r"""
|
12 |
+
This is the configuration class to store the configuration of a [`YiModel`]. It is used to instantiate an Yi
|
13 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
14 |
+
defaults will yield a similar configuration to that of the Yi model.
|
15 |
+
|
16 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
17 |
+
documentation from [`PretrainedConfig`] for more information.
|
18 |
+
|
19 |
+
|
20 |
+
Args:
|
21 |
+
vocab_size (`int`, *optional*, defaults to 64000):
|
22 |
+
Vocabulary size of the Yi model. Defines the number of different tokens that can be represented by the
|
23 |
+
`inputs_ids` passed when calling [`YiModel`]
|
24 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
25 |
+
Dimension of the hidden representations.
|
26 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
27 |
+
Dimension of the MLP representations.
|
28 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
29 |
+
Number of hidden layers in the Transformer encoder.
|
30 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
31 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
32 |
+
num_key_value_heads (`int`, *optional*):
|
33 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
34 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
35 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
36 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
37 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
38 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
39 |
+
`num_attention_heads`.
|
40 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
41 |
+
The non-linear activation function (function or string) in the decoder.
|
42 |
+
max_position_embeddings (`int`, *optional*, defaults to 4096):
|
43 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
44 |
+
just in case (e.g., 512 or 1024 or 2048 or 4096).
|
45 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
46 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
47 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-5):
|
48 |
+
The epsilon used by the rms normalization layers.
|
49 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
50 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
51 |
+
relevant if `config.is_decoder=True`.
|
52 |
+
tie_word_embeddings(`bool`, *optional*, defaults to `False`):
|
53 |
+
Whether to tie weight embeddings
|
54 |
+
output_attentions (`bool`, *optional*, defaults to `False`):
|
55 |
+
Whether or not to output attentions.
|
56 |
+
rope_theta (`float`, *optional*, defaults to 5000000.0):
|
57 |
+
The base period of the RoPE embeddings.
|
58 |
+
Example:
|
59 |
+
|
60 |
+
```python
|
61 |
+
>>> from transformers import YiModel, YiConfig
|
62 |
+
|
63 |
+
>>> # Initializing a Yi style configuration
|
64 |
+
>>> configuration = YiConfig()
|
65 |
+
|
66 |
+
>>> # Initializing a model from the Yi style configuration
|
67 |
+
>>> model = YiModel(configuration)
|
68 |
+
|
69 |
+
>>> # Accessing the model configuration
|
70 |
+
>>> configuration = model.config
|
71 |
+
```"""
|
72 |
+
model_type = "Yi"
|
73 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
74 |
+
|
75 |
+
def __init__(
|
76 |
+
self,
|
77 |
+
vocab_size=64000,
|
78 |
+
hidden_size=4096,
|
79 |
+
intermediate_size=11008,
|
80 |
+
num_hidden_layers=32,
|
81 |
+
num_attention_heads=32,
|
82 |
+
num_key_value_heads=4,
|
83 |
+
hidden_act="silu",
|
84 |
+
max_position_embeddings=4096,
|
85 |
+
initializer_range=0.02,
|
86 |
+
rms_norm_eps=1e-5,
|
87 |
+
use_cache=True,
|
88 |
+
pad_token_id=0,
|
89 |
+
bos_token_id=1,
|
90 |
+
eos_token_id=2,
|
91 |
+
tie_word_embeddings=False,
|
92 |
+
output_attentions=False,
|
93 |
+
rope_theta=5000000.0,
|
94 |
+
**kwargs,
|
95 |
+
):
|
96 |
+
self.vocab_size = vocab_size
|
97 |
+
self.max_position_embeddings = max_position_embeddings
|
98 |
+
self.hidden_size = hidden_size
|
99 |
+
self.intermediate_size = intermediate_size
|
100 |
+
self.num_hidden_layers = num_hidden_layers
|
101 |
+
self.num_attention_heads = num_attention_heads
|
102 |
+
|
103 |
+
# for backward compatibility
|
104 |
+
if num_key_value_heads is None:
|
105 |
+
num_key_value_heads = num_attention_heads
|
106 |
+
|
107 |
+
self.num_key_value_heads = num_key_value_heads
|
108 |
+
self.hidden_act = hidden_act
|
109 |
+
self.initializer_range = initializer_range
|
110 |
+
self.rms_norm_eps = rms_norm_eps
|
111 |
+
self.use_cache = use_cache
|
112 |
+
self.output_attentions = output_attentions
|
113 |
+
self.rope_theta = rope_theta
|
114 |
+
|
115 |
+
super().__init__(
|
116 |
+
pad_token_id=pad_token_id,
|
117 |
+
bos_token_id=bos_token_id,
|
118 |
+
eos_token_id=eos_token_id,
|
119 |
+
tie_word_embeddings=tie_word_embeddings,
|
120 |
+
**kwargs,
|
121 |
+
)
|
generation_config.json
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"bos_token_id": 1,
|
4 |
+
"eos_token_id": 2,
|
5 |
+
"pad_token_id": 0,
|
6 |
+
"transformers_version": "4.34.1"
|
7 |
+
}
|
modeling_yi.py
ADDED
@@ -0,0 +1,1030 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" PyTorch Yi model."""
|
2 |
+
import math
|
3 |
+
from typing import List, Optional, Tuple, Union
|
4 |
+
|
5 |
+
import torch.utils.checkpoint
|
6 |
+
from einops import repeat
|
7 |
+
from torch import nn
|
8 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
9 |
+
|
10 |
+
from transformers.activations import ACT2FN
|
11 |
+
from transformers.modeling_outputs import (
|
12 |
+
BaseModelOutputWithPast,
|
13 |
+
CausalLMOutputWithPast,
|
14 |
+
SequenceClassifierOutputWithPast,
|
15 |
+
)
|
16 |
+
from transformers.modeling_utils import PreTrainedModel
|
17 |
+
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
|
18 |
+
from transformers.utils import (
|
19 |
+
add_start_docstrings,
|
20 |
+
add_start_docstrings_to_model_forward,
|
21 |
+
is_flash_attn_available,
|
22 |
+
logging,
|
23 |
+
replace_return_docstrings,
|
24 |
+
)
|
25 |
+
|
26 |
+
from .configuration_yi import YiConfig
|
27 |
+
|
28 |
+
|
29 |
+
if is_flash_attn_available():
|
30 |
+
from flash_attn import flash_attn_func
|
31 |
+
|
32 |
+
|
33 |
+
logger = logging.get_logger(__name__)
|
34 |
+
|
35 |
+
_CONFIG_FOR_DOC = "YiConfig"
|
36 |
+
|
37 |
+
|
38 |
+
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
39 |
+
def _make_causal_mask(
|
40 |
+
input_ids_shape: torch.Size,
|
41 |
+
dtype: torch.dtype,
|
42 |
+
device: torch.device,
|
43 |
+
past_key_values_length: int = 0,
|
44 |
+
):
|
45 |
+
"""
|
46 |
+
Make causal mask used for bi-directional self-attention.
|
47 |
+
"""
|
48 |
+
bsz, tgt_len = input_ids_shape
|
49 |
+
mask = torch.full(
|
50 |
+
(tgt_len, tgt_len),
|
51 |
+
torch.tensor(torch.finfo(dtype).min, device=device),
|
52 |
+
device=device,
|
53 |
+
)
|
54 |
+
mask_cond = torch.arange(mask.size(-1), device=device)
|
55 |
+
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
56 |
+
mask = mask.to(dtype)
|
57 |
+
|
58 |
+
if past_key_values_length > 0:
|
59 |
+
mask = torch.cat(
|
60 |
+
[
|
61 |
+
torch.zeros(
|
62 |
+
tgt_len, past_key_values_length, dtype=dtype, device=device
|
63 |
+
),
|
64 |
+
mask,
|
65 |
+
],
|
66 |
+
dim=-1,
|
67 |
+
)
|
68 |
+
return mask[None, None, :, :].expand(
|
69 |
+
bsz, 1, tgt_len, tgt_len + past_key_values_length
|
70 |
+
)
|
71 |
+
|
72 |
+
|
73 |
+
# Copied from transformers.models.bart.modeling_bart._expand_mask
|
74 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
75 |
+
"""
|
76 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
77 |
+
"""
|
78 |
+
bsz, src_len = mask.size()
|
79 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
80 |
+
|
81 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
82 |
+
|
83 |
+
inverted_mask = 1.0 - expanded_mask
|
84 |
+
|
85 |
+
return inverted_mask.masked_fill(
|
86 |
+
inverted_mask.to(torch.bool), torch.finfo(dtype).min
|
87 |
+
)
|
88 |
+
|
89 |
+
|
90 |
+
class YiRMSNorm(nn.Module):
|
91 |
+
def __init__(self, hidden_size, eps=1e-5):
|
92 |
+
"""
|
93 |
+
YiRMSNorm is equivalent to T5LayerNorm
|
94 |
+
"""
|
95 |
+
super().__init__()
|
96 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
97 |
+
self.variance_epsilon = eps
|
98 |
+
|
99 |
+
def forward(self, hidden_states):
|
100 |
+
input_dtype = hidden_states.dtype
|
101 |
+
hidden_states = hidden_states.to(torch.float32)
|
102 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
103 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
104 |
+
|
105 |
+
return self.weight * hidden_states.to(input_dtype)
|
106 |
+
|
107 |
+
|
108 |
+
ALL_LAYERNORM_LAYERS.append(YiRMSNorm)
|
109 |
+
|
110 |
+
|
111 |
+
class YiRotaryEmbedding(torch.nn.Module):
|
112 |
+
def __init__(self, dim, max_position_embeddings=4096, base=5000000, device=None):
|
113 |
+
super().__init__()
|
114 |
+
|
115 |
+
self.dim = dim
|
116 |
+
self.max_position_embeddings = max_position_embeddings
|
117 |
+
self.base = base
|
118 |
+
|
119 |
+
# Build here to make `torch.jit.trace` work.
|
120 |
+
self._set_cos_sin_cache(seq_len=max_position_embeddings, device=device)
|
121 |
+
|
122 |
+
def _set_cos_sin_cache(self, seq_len, device):
|
123 |
+
self.max_seq_len_cached = seq_len
|
124 |
+
inv_freq = 1.0 / (
|
125 |
+
self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
|
126 |
+
)
|
127 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.float32)
|
128 |
+
freqs = torch.einsum("i,j->ij", t, inv_freq)
|
129 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
130 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
131 |
+
self.register_buffer(
|
132 |
+
"cos_cached", emb.cos()[None, None, :, :], persistent=False
|
133 |
+
)
|
134 |
+
self.register_buffer(
|
135 |
+
"sin_cached", emb.sin()[None, None, :, :], persistent=False
|
136 |
+
)
|
137 |
+
|
138 |
+
def forward(self, x, seq_len=None):
|
139 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
140 |
+
if seq_len > self.max_seq_len_cached:
|
141 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device)
|
142 |
+
|
143 |
+
return (
|
144 |
+
self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
145 |
+
self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
146 |
+
)
|
147 |
+
|
148 |
+
|
149 |
+
def rotate_half(x):
|
150 |
+
"""Rotates half the hidden dims of the input."""
|
151 |
+
x1 = x[..., : x.shape[-1] // 2]
|
152 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
153 |
+
return torch.cat((-x2, x1), dim=-1)
|
154 |
+
|
155 |
+
|
156 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, flash_attn_available):
|
157 |
+
# The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
|
158 |
+
cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
|
159 |
+
sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
|
160 |
+
expand_dim = 2 if flash_attn_available else 1
|
161 |
+
cos = cos[position_ids].unsqueeze(expand_dim) # [bs, seq_len, dim]
|
162 |
+
sin = sin[position_ids].unsqueeze(expand_dim) # [bs, seq_len, dim]
|
163 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
164 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
165 |
+
return q_embed, k_embed
|
166 |
+
|
167 |
+
|
168 |
+
class YiMLP(nn.Module):
|
169 |
+
def __init__(self, hidden_size: int, intermediate_size: int, hidden_act: str):
|
170 |
+
super().__init__()
|
171 |
+
self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
172 |
+
self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
|
173 |
+
self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
174 |
+
self.act_fn = ACT2FN[hidden_act]
|
175 |
+
|
176 |
+
def forward(self, x):
|
177 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
178 |
+
|
179 |
+
|
180 |
+
class YiAttention(nn.Module):
|
181 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
182 |
+
|
183 |
+
def __init__(self, config: YiConfig):
|
184 |
+
super().__init__()
|
185 |
+
self.config = config
|
186 |
+
self.hidden_size = config.hidden_size
|
187 |
+
self.num_heads = config.num_attention_heads
|
188 |
+
self.head_dim = self.hidden_size // self.num_heads
|
189 |
+
self.num_key_value_heads = config.num_key_value_heads
|
190 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
191 |
+
self.max_position_embeddings = config.max_position_embeddings
|
192 |
+
|
193 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
194 |
+
raise ValueError(
|
195 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
196 |
+
f" and `num_heads`: {self.num_heads})."
|
197 |
+
)
|
198 |
+
self.q_proj = nn.Linear(
|
199 |
+
self.hidden_size, self.num_heads * self.head_dim, bias=False
|
200 |
+
)
|
201 |
+
self.k_proj = nn.Linear(
|
202 |
+
self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
|
203 |
+
)
|
204 |
+
self.v_proj = nn.Linear(
|
205 |
+
self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
|
206 |
+
)
|
207 |
+
self.o_proj = nn.Linear(
|
208 |
+
self.num_heads * self.head_dim, self.hidden_size, bias=False
|
209 |
+
)
|
210 |
+
|
211 |
+
self.rotary_emb = YiRotaryEmbedding(
|
212 |
+
self.head_dim,
|
213 |
+
max_position_embeddings=self.max_position_embeddings,
|
214 |
+
base=self.config.rope_theta,
|
215 |
+
)
|
216 |
+
|
217 |
+
def forward(
|
218 |
+
self,
|
219 |
+
hidden_states: torch.Tensor,
|
220 |
+
attention_mask: Optional[torch.Tensor] = None,
|
221 |
+
position_ids: Optional[torch.LongTensor] = None,
|
222 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
223 |
+
output_attentions: bool = False,
|
224 |
+
use_cache: bool = False,
|
225 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
226 |
+
bsz, q_len, _ = hidden_states.size()
|
227 |
+
flash_attn_available = is_flash_attn_available()
|
228 |
+
|
229 |
+
query_states = self.q_proj(hidden_states).view(
|
230 |
+
bsz, q_len, self.num_heads, self.head_dim
|
231 |
+
)
|
232 |
+
|
233 |
+
key_states = self.k_proj(hidden_states).view(
|
234 |
+
bsz, q_len, self.num_key_value_heads, self.head_dim
|
235 |
+
)
|
236 |
+
value_states = self.v_proj(hidden_states).view(
|
237 |
+
bsz, q_len, self.num_key_value_heads, self.head_dim
|
238 |
+
)
|
239 |
+
|
240 |
+
if not flash_attn_available:
|
241 |
+
if self.num_key_value_groups > 1:
|
242 |
+
key_states = repeat(
|
243 |
+
key_states, f"b n h d -> b n (h {self.num_key_value_groups}) d"
|
244 |
+
)
|
245 |
+
value_states = repeat(
|
246 |
+
value_states, f"b n h d -> b n (h {self.num_key_value_groups}) d"
|
247 |
+
)
|
248 |
+
|
249 |
+
# b n h d -> b h n d
|
250 |
+
query_states = query_states.transpose(1, 2)
|
251 |
+
key_states = key_states.transpose(1, 2)
|
252 |
+
value_states = value_states.transpose(1, 2)
|
253 |
+
|
254 |
+
seq_dim = 1 if flash_attn_available else 2
|
255 |
+
kv_seq_len = key_states.shape[seq_dim]
|
256 |
+
if past_key_value is not None:
|
257 |
+
kv_seq_len += past_key_value[0].shape[seq_dim]
|
258 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
259 |
+
query_states, key_states = apply_rotary_pos_emb(
|
260 |
+
query_states, key_states, cos, sin, position_ids, flash_attn_available
|
261 |
+
)
|
262 |
+
|
263 |
+
if past_key_value is not None:
|
264 |
+
# reuse k, v, self_attention
|
265 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=seq_dim)
|
266 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=seq_dim)
|
267 |
+
|
268 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
269 |
+
|
270 |
+
if flash_attn_available:
|
271 |
+
attn_output = flash_attn_func(
|
272 |
+
query_states, key_states, value_states, dropout_p=0.0, causal=True
|
273 |
+
)
|
274 |
+
else:
|
275 |
+
attn_weights = torch.matmul(
|
276 |
+
query_states, key_states.transpose(2, 3)
|
277 |
+
) / math.sqrt(self.head_dim)
|
278 |
+
|
279 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
280 |
+
raise ValueError(
|
281 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
282 |
+
f" {attn_weights.size()}"
|
283 |
+
)
|
284 |
+
|
285 |
+
if attention_mask is not None:
|
286 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
287 |
+
raise ValueError(
|
288 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is"
|
289 |
+
f"{attention_mask.size()}"
|
290 |
+
)
|
291 |
+
attn_weights = attn_weights + attention_mask
|
292 |
+
dtype_min = torch.tensor(
|
293 |
+
torch.finfo(attn_weights.dtype).min,
|
294 |
+
device=attn_weights.device,
|
295 |
+
dtype=attn_weights.dtype,
|
296 |
+
)
|
297 |
+
attn_weights = torch.max(attn_weights, dtype_min)
|
298 |
+
|
299 |
+
# upcast attention to fp32
|
300 |
+
attn_weights = nn.functional.softmax(
|
301 |
+
attn_weights, dim=-1, dtype=torch.float32
|
302 |
+
).to(query_states.dtype)
|
303 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
304 |
+
|
305 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
306 |
+
raise ValueError(
|
307 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
308 |
+
f" {attn_output.size()}"
|
309 |
+
)
|
310 |
+
|
311 |
+
if not flash_attn_available:
|
312 |
+
attn_output = attn_output.transpose(1, 2)
|
313 |
+
|
314 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
315 |
+
|
316 |
+
attn_output = self.o_proj(attn_output)
|
317 |
+
|
318 |
+
if not output_attentions:
|
319 |
+
attn_weights = None
|
320 |
+
|
321 |
+
return attn_output, attn_weights, past_key_value
|
322 |
+
|
323 |
+
|
324 |
+
class YiDecoderLayer(nn.Module):
|
325 |
+
def __init__(self, config: YiConfig):
|
326 |
+
super().__init__()
|
327 |
+
|
328 |
+
self.hidden_size = config.hidden_size
|
329 |
+
self.self_attn = YiAttention(config=config)
|
330 |
+
self.mlp = YiMLP(
|
331 |
+
hidden_size=self.hidden_size,
|
332 |
+
intermediate_size=config.intermediate_size,
|
333 |
+
hidden_act=config.hidden_act,
|
334 |
+
)
|
335 |
+
|
336 |
+
self.ln1 = YiRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
337 |
+
self.ln2 = YiRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
338 |
+
|
339 |
+
def forward(
|
340 |
+
self,
|
341 |
+
hidden_states: torch.Tensor,
|
342 |
+
attention_mask: Optional[torch.Tensor] = None,
|
343 |
+
position_ids: Optional[torch.LongTensor] = None,
|
344 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
345 |
+
output_attentions: Optional[bool] = False,
|
346 |
+
use_cache: Optional[bool] = False,
|
347 |
+
) -> Tuple[
|
348 |
+
torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
|
349 |
+
]:
|
350 |
+
"""
|
351 |
+
Args:
|
352 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
353 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
354 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
355 |
+
output_attentions (`bool`, *optional*):
|
356 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
357 |
+
returned tensors for more detail.
|
358 |
+
use_cache (`bool`, *optional*):
|
359 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
360 |
+
(see `past_key_values`).
|
361 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
362 |
+
"""
|
363 |
+
|
364 |
+
residual = hidden_states
|
365 |
+
|
366 |
+
hidden_states = self.ln1(hidden_states)
|
367 |
+
|
368 |
+
# Self Attention
|
369 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
370 |
+
hidden_states=hidden_states,
|
371 |
+
attention_mask=attention_mask,
|
372 |
+
position_ids=position_ids,
|
373 |
+
past_key_value=past_key_value,
|
374 |
+
output_attentions=output_attentions,
|
375 |
+
use_cache=use_cache,
|
376 |
+
)
|
377 |
+
hidden_states = residual + hidden_states
|
378 |
+
|
379 |
+
# Fully Connected
|
380 |
+
residual = hidden_states
|
381 |
+
hidden_states = self.ln2(hidden_states)
|
382 |
+
hidden_states = self.mlp(hidden_states)
|
383 |
+
hidden_states = residual + hidden_states
|
384 |
+
|
385 |
+
outputs = (hidden_states,)
|
386 |
+
|
387 |
+
if output_attentions:
|
388 |
+
outputs += (self_attn_weights,)
|
389 |
+
|
390 |
+
if use_cache:
|
391 |
+
outputs += (present_key_value,)
|
392 |
+
|
393 |
+
return outputs
|
394 |
+
|
395 |
+
|
396 |
+
Yi_START_DOCSTRING = r"""
|
397 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
398 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
399 |
+
etc.)
|
400 |
+
|
401 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
402 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
403 |
+
and behavior.
|
404 |
+
|
405 |
+
Parameters:
|
406 |
+
config ([`YiConfig`]):
|
407 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
408 |
+
load the weights associated with the model, only the configuration. Check out the
|
409 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
410 |
+
"""
|
411 |
+
|
412 |
+
|
413 |
+
@add_start_docstrings(
|
414 |
+
"The bare Yi Model outputting raw hidden-states without any specific head on top.",
|
415 |
+
Yi_START_DOCSTRING,
|
416 |
+
)
|
417 |
+
class YiPreTrainedModel(PreTrainedModel):
|
418 |
+
config_class = YiConfig
|
419 |
+
base_model_prefix = "model"
|
420 |
+
supports_gradient_checkpointing = True
|
421 |
+
_no_split_modules = ["YiDecoderLayer"]
|
422 |
+
_skip_keys_device_placement = "past_key_values"
|
423 |
+
|
424 |
+
def _init_weights(self, module):
|
425 |
+
std = self.config.initializer_range
|
426 |
+
if isinstance(module, nn.Linear):
|
427 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
428 |
+
if module.bias is not None:
|
429 |
+
module.bias.data.zero_()
|
430 |
+
elif isinstance(module, nn.Embedding):
|
431 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
432 |
+
if module.padding_idx is not None:
|
433 |
+
module.weight.data[module.padding_idx].zero_()
|
434 |
+
|
435 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
436 |
+
if isinstance(module, YiModel):
|
437 |
+
module.gradient_checkpointing = value
|
438 |
+
|
439 |
+
|
440 |
+
Yi_INPUTS_DOCSTRING = r"""
|
441 |
+
Args:
|
442 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
443 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
444 |
+
it.
|
445 |
+
|
446 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
447 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
448 |
+
|
449 |
+
[What are input IDs?](../glossary#input-ids)
|
450 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
451 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
452 |
+
|
453 |
+
- 1 for tokens that are **not masked**,
|
454 |
+
- 0 for tokens that are **masked**.
|
455 |
+
|
456 |
+
[What are attention masks?](../glossary#attention-mask)
|
457 |
+
|
458 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
459 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
460 |
+
|
461 |
+
If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
462 |
+
`past_key_values`).
|
463 |
+
|
464 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
465 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
466 |
+
information on the default strategy.
|
467 |
+
|
468 |
+
- 1 indicates the head is **not masked**,
|
469 |
+
- 0 indicates the head is **masked**.
|
470 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
471 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
472 |
+
config.n_positions - 1]`.
|
473 |
+
|
474 |
+
[What are position IDs?](../glossary#position-ids)
|
475 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
476 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
477 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
|
478 |
+
`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
|
479 |
+
|
480 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
481 |
+
blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
482 |
+
|
483 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
484 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
485 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
486 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
487 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
488 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
489 |
+
model's internal embedding lookup matrix.
|
490 |
+
use_cache (`bool`, *optional*):
|
491 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
492 |
+
`past_key_values`).
|
493 |
+
output_attentions (`bool`, *optional*):
|
494 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
495 |
+
tensors for more detail.
|
496 |
+
output_hidden_states (`bool`, *optional*):
|
497 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
498 |
+
more detail.
|
499 |
+
return_dict (`bool`, *optional*):
|
500 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
501 |
+
"""
|
502 |
+
|
503 |
+
|
504 |
+
@add_start_docstrings(
|
505 |
+
"The bare Yi Model outputting raw hidden-states without any specific head on top.",
|
506 |
+
Yi_START_DOCSTRING,
|
507 |
+
)
|
508 |
+
class YiModel(YiPreTrainedModel):
|
509 |
+
"""
|
510 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`YiDecoderLayer`]
|
511 |
+
|
512 |
+
Args:
|
513 |
+
config: YiConfig
|
514 |
+
"""
|
515 |
+
|
516 |
+
def __init__(self, config: YiConfig):
|
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(
|
522 |
+
config.vocab_size, config.hidden_size, self.padding_idx
|
523 |
+
)
|
524 |
+
self.layers = nn.ModuleList(
|
525 |
+
[YiDecoderLayer(config) for _ in range(config.num_hidden_layers)]
|
526 |
+
)
|
527 |
+
|
528 |
+
self.norm = YiRMSNorm(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 |
+
# Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
|
541 |
+
def _prepare_decoder_attention_mask(
|
542 |
+
self, attention_mask, input_ids, inputs_embeds, past_key_values_length
|
543 |
+
):
|
544 |
+
input_shape = input_ids.shape
|
545 |
+
# create causal mask
|
546 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
547 |
+
combined_attention_mask = None
|
548 |
+
if input_shape[-1] > 1:
|
549 |
+
combined_attention_mask = _make_causal_mask(
|
550 |
+
input_shape,
|
551 |
+
inputs_embeds.dtype,
|
552 |
+
device=inputs_embeds.device,
|
553 |
+
past_key_values_length=past_key_values_length,
|
554 |
+
)
|
555 |
+
|
556 |
+
if attention_mask is not None:
|
557 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
558 |
+
expanded_attn_mask = _expand_mask(
|
559 |
+
attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
|
560 |
+
).to(inputs_embeds.device)
|
561 |
+
combined_attention_mask = (
|
562 |
+
expanded_attn_mask
|
563 |
+
if combined_attention_mask is None
|
564 |
+
else expanded_attn_mask + combined_attention_mask
|
565 |
+
)
|
566 |
+
|
567 |
+
return combined_attention_mask
|
568 |
+
|
569 |
+
@add_start_docstrings_to_model_forward(Yi_INPUTS_DOCSTRING)
|
570 |
+
def forward(
|
571 |
+
self,
|
572 |
+
input_ids: torch.LongTensor = None,
|
573 |
+
attention_mask: Optional[torch.Tensor] = None,
|
574 |
+
position_ids: Optional[torch.LongTensor] = None,
|
575 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
576 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
577 |
+
use_cache: Optional[bool] = None,
|
578 |
+
output_attentions: Optional[bool] = None,
|
579 |
+
output_hidden_states: Optional[bool] = None,
|
580 |
+
return_dict: Optional[bool] = None,
|
581 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
582 |
+
output_attentions = (
|
583 |
+
output_attentions
|
584 |
+
if output_attentions is not None
|
585 |
+
else self.config.output_attentions
|
586 |
+
)
|
587 |
+
output_hidden_states = (
|
588 |
+
output_hidden_states
|
589 |
+
if output_hidden_states is not None
|
590 |
+
else self.config.output_hidden_states
|
591 |
+
)
|
592 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
593 |
+
|
594 |
+
return_dict = (
|
595 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
596 |
+
)
|
597 |
+
|
598 |
+
# retrieve input_ids and inputs_embeds
|
599 |
+
if input_ids is not None and inputs_embeds is not None:
|
600 |
+
raise ValueError(
|
601 |
+
"You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time"
|
602 |
+
)
|
603 |
+
elif input_ids is not None:
|
604 |
+
batch_size, seq_length = input_ids.shape
|
605 |
+
elif inputs_embeds is not None:
|
606 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
607 |
+
else:
|
608 |
+
raise ValueError(
|
609 |
+
"You have to specify either decoder_input_ids or decoder_inputs_embeds"
|
610 |
+
)
|
611 |
+
|
612 |
+
seq_length_with_past = seq_length
|
613 |
+
past_key_values_length = 0
|
614 |
+
|
615 |
+
if past_key_values is not None:
|
616 |
+
past_key_values_length = past_key_values[0][0].shape[2]
|
617 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
618 |
+
|
619 |
+
if position_ids is None:
|
620 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
621 |
+
position_ids = torch.arange(
|
622 |
+
past_key_values_length,
|
623 |
+
seq_length + past_key_values_length,
|
624 |
+
dtype=torch.long,
|
625 |
+
device=device,
|
626 |
+
)
|
627 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
628 |
+
else:
|
629 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
630 |
+
|
631 |
+
if inputs_embeds is None:
|
632 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
633 |
+
|
634 |
+
if not is_flash_attn_available():
|
635 |
+
# embed positions
|
636 |
+
if attention_mask is None:
|
637 |
+
attention_mask = torch.ones(
|
638 |
+
(batch_size, seq_length_with_past),
|
639 |
+
dtype=torch.bool,
|
640 |
+
device=inputs_embeds.device,
|
641 |
+
)
|
642 |
+
attention_mask = self._prepare_decoder_attention_mask(
|
643 |
+
attention_mask,
|
644 |
+
input_ids,
|
645 |
+
inputs_embeds,
|
646 |
+
past_key_values_length,
|
647 |
+
)
|
648 |
+
else:
|
649 |
+
attention_mask = None
|
650 |
+
|
651 |
+
hidden_states = inputs_embeds
|
652 |
+
if self.gradient_checkpointing and self.training:
|
653 |
+
if use_cache:
|
654 |
+
logger.warning_once(
|
655 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
656 |
+
)
|
657 |
+
use_cache = False
|
658 |
+
|
659 |
+
# decoder layers
|
660 |
+
all_hidden_states = () if output_hidden_states else None
|
661 |
+
all_self_attns = () if output_attentions else None
|
662 |
+
next_decoder_cache = () if use_cache else None
|
663 |
+
|
664 |
+
for idx, decoder_layer in enumerate(self.layers):
|
665 |
+
if output_hidden_states:
|
666 |
+
all_hidden_states += (hidden_states,)
|
667 |
+
|
668 |
+
past_key_value = (
|
669 |
+
past_key_values[idx] if past_key_values is not None else None
|
670 |
+
)
|
671 |
+
|
672 |
+
if self.gradient_checkpointing and self.training:
|
673 |
+
|
674 |
+
def create_custom_forward(module):
|
675 |
+
def custom_forward(*inputs):
|
676 |
+
# None for past_key_value
|
677 |
+
return module(*inputs, past_key_value, output_attentions)
|
678 |
+
|
679 |
+
return custom_forward
|
680 |
+
|
681 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
682 |
+
create_custom_forward(decoder_layer),
|
683 |
+
hidden_states,
|
684 |
+
attention_mask,
|
685 |
+
position_ids,
|
686 |
+
)
|
687 |
+
else:
|
688 |
+
layer_outputs = decoder_layer(
|
689 |
+
hidden_states,
|
690 |
+
attention_mask=attention_mask,
|
691 |
+
position_ids=position_ids,
|
692 |
+
past_key_value=past_key_value,
|
693 |
+
output_attentions=output_attentions,
|
694 |
+
use_cache=use_cache,
|
695 |
+
)
|
696 |
+
|
697 |
+
hidden_states = layer_outputs[0]
|
698 |
+
|
699 |
+
if use_cache:
|
700 |
+
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
|
701 |
+
|
702 |
+
if output_attentions:
|
703 |
+
all_self_attns += (layer_outputs[1],)
|
704 |
+
|
705 |
+
hidden_states = self.norm(hidden_states)
|
706 |
+
# add hidden states from the last decoder layer
|
707 |
+
if output_hidden_states:
|
708 |
+
all_hidden_states += (hidden_states,)
|
709 |
+
|
710 |
+
next_cache = next_decoder_cache if use_cache else None
|
711 |
+
if not return_dict:
|
712 |
+
return tuple(
|
713 |
+
v
|
714 |
+
for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
|
715 |
+
if v is not None
|
716 |
+
)
|
717 |
+
return BaseModelOutputWithPast(
|
718 |
+
last_hidden_state=hidden_states,
|
719 |
+
past_key_values=next_cache,
|
720 |
+
hidden_states=all_hidden_states,
|
721 |
+
attentions=all_self_attns,
|
722 |
+
)
|
723 |
+
|
724 |
+
|
725 |
+
class YiForCausalLM(YiPreTrainedModel):
|
726 |
+
_tied_weights_keys = ["lm_head.weight"]
|
727 |
+
|
728 |
+
def __init__(self, config):
|
729 |
+
super().__init__(config)
|
730 |
+
self.model = YiModel(config)
|
731 |
+
|
732 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
733 |
+
|
734 |
+
# Initialize weights and apply final processing
|
735 |
+
self.post_init()
|
736 |
+
|
737 |
+
def get_input_embeddings(self):
|
738 |
+
return self.model.embed_tokens
|
739 |
+
|
740 |
+
def set_input_embeddings(self, value):
|
741 |
+
self.model.embed_tokens = value
|
742 |
+
|
743 |
+
def get_output_embeddings(self):
|
744 |
+
return self.lm_head
|
745 |
+
|
746 |
+
def set_output_embeddings(self, new_embeddings):
|
747 |
+
self.lm_head = new_embeddings
|
748 |
+
|
749 |
+
def set_decoder(self, decoder):
|
750 |
+
self.model = decoder
|
751 |
+
|
752 |
+
def get_decoder(self):
|
753 |
+
return self.model
|
754 |
+
|
755 |
+
@add_start_docstrings_to_model_forward(Yi_INPUTS_DOCSTRING)
|
756 |
+
@replace_return_docstrings(
|
757 |
+
output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
|
758 |
+
)
|
759 |
+
def forward(
|
760 |
+
self,
|
761 |
+
input_ids: torch.LongTensor = None,
|
762 |
+
attention_mask: Optional[torch.Tensor] = None,
|
763 |
+
position_ids: Optional[torch.LongTensor] = None,
|
764 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
765 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
766 |
+
labels: Optional[torch.LongTensor] = None,
|
767 |
+
use_cache: Optional[bool] = None,
|
768 |
+
output_attentions: Optional[bool] = None,
|
769 |
+
output_hidden_states: Optional[bool] = None,
|
770 |
+
return_dict: Optional[bool] = None,
|
771 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
772 |
+
r"""
|
773 |
+
Args:
|
774 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
775 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
776 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
777 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
778 |
+
|
779 |
+
Returns:
|
780 |
+
|
781 |
+
Example:
|
782 |
+
|
783 |
+
```python
|
784 |
+
>>> from transformers import AutoTokenizer, YiForCausalLM
|
785 |
+
|
786 |
+
>>> model = YiForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
|
787 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
|
788 |
+
|
789 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
790 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
791 |
+
|
792 |
+
>>> # Generate
|
793 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
794 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
795 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
796 |
+
```"""
|
797 |
+
|
798 |
+
output_attentions = (
|
799 |
+
output_attentions
|
800 |
+
if output_attentions is not None
|
801 |
+
else self.config.output_attentions
|
802 |
+
)
|
803 |
+
output_hidden_states = (
|
804 |
+
output_hidden_states
|
805 |
+
if output_hidden_states is not None
|
806 |
+
else self.config.output_hidden_states
|
807 |
+
)
|
808 |
+
return_dict = (
|
809 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
810 |
+
)
|
811 |
+
|
812 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
813 |
+
outputs = self.model(
|
814 |
+
input_ids=input_ids,
|
815 |
+
attention_mask=attention_mask,
|
816 |
+
position_ids=position_ids,
|
817 |
+
past_key_values=past_key_values,
|
818 |
+
inputs_embeds=inputs_embeds,
|
819 |
+
use_cache=use_cache,
|
820 |
+
output_attentions=output_attentions,
|
821 |
+
output_hidden_states=output_hidden_states,
|
822 |
+
return_dict=return_dict,
|
823 |
+
)
|
824 |
+
|
825 |
+
hidden_states = outputs[0]
|
826 |
+
logits = self.lm_head(hidden_states)
|
827 |
+
|
828 |
+
loss = None
|
829 |
+
if labels is not None:
|
830 |
+
# Shift so that tokens < n predict n
|
831 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
832 |
+
shift_labels = labels[..., 1:].contiguous()
|
833 |
+
# Flatten the tokens
|
834 |
+
loss_fct = CrossEntropyLoss()
|
835 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
836 |
+
shift_labels = shift_labels.view(-1)
|
837 |
+
# Enable model parallelism
|
838 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
839 |
+
loss = loss_fct(shift_logits, shift_labels)
|
840 |
+
|
841 |
+
if not return_dict:
|
842 |
+
output = (logits,) + outputs[1:]
|
843 |
+
return (loss,) + output if loss is not None else output
|
844 |
+
|
845 |
+
return CausalLMOutputWithPast(
|
846 |
+
loss=loss,
|
847 |
+
logits=logits,
|
848 |
+
past_key_values=outputs.past_key_values,
|
849 |
+
hidden_states=outputs.hidden_states,
|
850 |
+
attentions=outputs.attentions,
|
851 |
+
)
|
852 |
+
|
853 |
+
def prepare_inputs_for_generation(
|
854 |
+
self,
|
855 |
+
input_ids,
|
856 |
+
past_key_values=None,
|
857 |
+
attention_mask=None,
|
858 |
+
inputs_embeds=None,
|
859 |
+
**kwargs,
|
860 |
+
):
|
861 |
+
if past_key_values:
|
862 |
+
input_ids = input_ids[:, -1:]
|
863 |
+
|
864 |
+
position_ids = kwargs.get("position_ids", None)
|
865 |
+
if attention_mask is not None and position_ids is None:
|
866 |
+
# create position_ids on the fly for batch generation
|
867 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
868 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
869 |
+
if past_key_values:
|
870 |
+
position_ids = position_ids[:, -1].unsqueeze(-1)
|
871 |
+
|
872 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
873 |
+
if inputs_embeds is not None and past_key_values is None:
|
874 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
875 |
+
else:
|
876 |
+
model_inputs = {"input_ids": input_ids}
|
877 |
+
|
878 |
+
model_inputs.update(
|
879 |
+
{
|
880 |
+
"position_ids": position_ids,
|
881 |
+
"past_key_values": past_key_values,
|
882 |
+
"use_cache": kwargs.get("use_cache"),
|
883 |
+
"attention_mask": attention_mask,
|
884 |
+
}
|
885 |
+
)
|
886 |
+
return model_inputs
|
887 |
+
|
888 |
+
@staticmethod
|
889 |
+
def _reorder_cache(past_key_values, beam_idx):
|
890 |
+
reordered_past = ()
|
891 |
+
for layer_past in past_key_values:
|
892 |
+
reordered_past += (
|
893 |
+
tuple(
|
894 |
+
past_state.index_select(0, beam_idx.to(past_state.device))
|
895 |
+
for past_state in layer_past
|
896 |
+
),
|
897 |
+
)
|
898 |
+
return reordered_past
|
899 |
+
|
900 |
+
|
901 |
+
@add_start_docstrings(
|
902 |
+
"""
|
903 |
+
The Yi Model transformer with a sequence classification head on top (linear layer).
|
904 |
+
|
905 |
+
[`YiForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
906 |
+
(e.g. GPT-2) do.
|
907 |
+
|
908 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
909 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
910 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
911 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
912 |
+
each row of the batch).
|
913 |
+
""",
|
914 |
+
Yi_START_DOCSTRING,
|
915 |
+
)
|
916 |
+
class YiForSequenceClassification(YiPreTrainedModel):
|
917 |
+
def __init__(self, config):
|
918 |
+
super().__init__(config)
|
919 |
+
self.num_labels = config.num_labels
|
920 |
+
self.model = YiModel(config)
|
921 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
922 |
+
|
923 |
+
# Initialize weights and apply final processing
|
924 |
+
self.post_init()
|
925 |
+
|
926 |
+
def get_input_embeddings(self):
|
927 |
+
return self.model.embed_tokens
|
928 |
+
|
929 |
+
def set_input_embeddings(self, value):
|
930 |
+
self.model.embed_tokens = value
|
931 |
+
|
932 |
+
@add_start_docstrings_to_model_forward(Yi_INPUTS_DOCSTRING)
|
933 |
+
def forward(
|
934 |
+
self,
|
935 |
+
input_ids: torch.LongTensor = None,
|
936 |
+
attention_mask: Optional[torch.Tensor] = None,
|
937 |
+
position_ids: Optional[torch.LongTensor] = None,
|
938 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
939 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
940 |
+
labels: Optional[torch.LongTensor] = None,
|
941 |
+
use_cache: Optional[bool] = None,
|
942 |
+
output_attentions: Optional[bool] = None,
|
943 |
+
output_hidden_states: Optional[bool] = None,
|
944 |
+
return_dict: Optional[bool] = None,
|
945 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
946 |
+
r"""
|
947 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
948 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
949 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
950 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
951 |
+
"""
|
952 |
+
return_dict = (
|
953 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
954 |
+
)
|
955 |
+
|
956 |
+
transformer_outputs = self.model(
|
957 |
+
input_ids,
|
958 |
+
attention_mask=attention_mask,
|
959 |
+
position_ids=position_ids,
|
960 |
+
past_key_values=past_key_values,
|
961 |
+
inputs_embeds=inputs_embeds,
|
962 |
+
use_cache=use_cache,
|
963 |
+
output_attentions=output_attentions,
|
964 |
+
output_hidden_states=output_hidden_states,
|
965 |
+
return_dict=return_dict,
|
966 |
+
)
|
967 |
+
hidden_states = transformer_outputs[0]
|
968 |
+
logits = self.score(hidden_states)
|
969 |
+
|
970 |
+
if input_ids is not None:
|
971 |
+
batch_size = input_ids.shape[0]
|
972 |
+
else:
|
973 |
+
batch_size = inputs_embeds.shape[0]
|
974 |
+
|
975 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
976 |
+
raise ValueError(
|
977 |
+
"Cannot handle batch sizes > 1 if no padding token is defined."
|
978 |
+
)
|
979 |
+
if self.config.pad_token_id is None:
|
980 |
+
sequence_lengths = -1
|
981 |
+
else:
|
982 |
+
if input_ids is not None:
|
983 |
+
sequence_lengths = (
|
984 |
+
torch.eq(input_ids, self.config.pad_token_id).long().argmax(-1) - 1
|
985 |
+
).to(logits.device)
|
986 |
+
else:
|
987 |
+
sequence_lengths = -1
|
988 |
+
|
989 |
+
pooled_logits = logits[
|
990 |
+
torch.arange(batch_size, device=logits.device), sequence_lengths
|
991 |
+
]
|
992 |
+
|
993 |
+
loss = None
|
994 |
+
if labels is not None:
|
995 |
+
labels = labels.to(logits.device)
|
996 |
+
if self.config.problem_type is None:
|
997 |
+
if self.num_labels == 1:
|
998 |
+
self.config.problem_type = "regression"
|
999 |
+
elif self.num_labels > 1 and (
|
1000 |
+
labels.dtype == torch.long or labels.dtype == torch.int
|
1001 |
+
):
|
1002 |
+
self.config.problem_type = "single_label_classification"
|
1003 |
+
else:
|
1004 |
+
self.config.problem_type = "multi_label_classification"
|
1005 |
+
|
1006 |
+
if self.config.problem_type == "regression":
|
1007 |
+
loss_fct = MSELoss()
|
1008 |
+
if self.num_labels == 1:
|
1009 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
1010 |
+
else:
|
1011 |
+
loss = loss_fct(pooled_logits, labels)
|
1012 |
+
elif self.config.problem_type == "single_label_classification":
|
1013 |
+
loss_fct = CrossEntropyLoss()
|
1014 |
+
loss = loss_fct(
|
1015 |
+
pooled_logits.view(-1, self.num_labels), labels.view(-1)
|
1016 |
+
)
|
1017 |
+
elif self.config.problem_type == "multi_label_classification":
|
1018 |
+
loss_fct = BCEWithLogitsLoss()
|
1019 |
+
loss = loss_fct(pooled_logits, labels)
|
1020 |
+
if not return_dict:
|
1021 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
1022 |
+
return ((loss,) + output) if loss is not None else output
|
1023 |
+
|
1024 |
+
return SequenceClassifierOutputWithPast(
|
1025 |
+
loss=loss,
|
1026 |
+
logits=pooled_logits,
|
1027 |
+
past_key_values=transformer_outputs.past_key_values,
|
1028 |
+
hidden_states=transformer_outputs.hidden_states,
|
1029 |
+
attentions=transformer_outputs.attentions,
|
1030 |
+
)
|
pytorch_model-00001-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:7f008b55313ea3b48074112fbeffbdf9d948e62f1eec231d1ec702e8342fda1b
|
3 |
+
size 917505413
|
pytorch_model-00002-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d1d5958a01c26b1820365bee324a4c5e2e9c2e3316aaf09665ffc0d4b48a1305
|
3 |
+
size 822086554
|
pytorch_model-00003-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d85448e97ba75a31b2541f1ab0d66cbb886cbae65bdc8be458be03a16f0be0b8
|
3 |
+
size 822115836
|
pytorch_model-00004-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c7e498889f74e14dd7a92627567474a1cfc8753b38016f4e019656dadb743d39
|
3 |
+
size 822115836
|
pytorch_model-00005-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:427ed70ecfe0bd45b3d50c37466592b561ef784f5595edcd9a7f2383f9231ca6
|
3 |
+
size 998276267
|
pytorch_model-00006-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c3661d7ae3fabd493d971141797dca656282238e5ba1a4453ed93be193234c07
|
3 |
+
size 998276267
|
pytorch_model-00007-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d6ea746408de553092b8692ed3500dbef3d42001ede84b2678baa74ab0cc4a78
|
3 |
+
size 822086554
|
pytorch_model-00008-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e2d7e1ce5a185916d05dae8e41c0fcc3009d0b8baca442494c313af0e012f740
|
3 |
+
size 822115836
|
pytorch_model-00009-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d8dde5951a9aa6cf0d0723df2cc66740564830f92fbeb308ac2f6a640aaf8b6a
|
3 |
+
size 822115836
|
pytorch_model-00010-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:bf011a401f02cc324d3d196e17781f41ea24ed7c24340d7572a3c6dfd7ee9923
|
3 |
+
size 998276267
|
pytorch_model-00011-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b64d4a714ae756d373b2965b4d1d907d7c52df995c4d25e23b8795a2f7c60a80
|
3 |
+
size 998276267
|
pytorch_model-00012-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:7ce8891f2e1119a35760455f8c7ef639810af52c521611fc7ff3a00fb13411df
|
3 |
+
size 822086554
|
pytorch_model-00013-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:632277bd09e7cb9f8011e98803e22e73790767f52591488b9ded51f7ebcc8ab2
|
3 |
+
size 822115836
|
pytorch_model-00014-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5129cb47226623d984a47af84a827911571b76bc3a624a27baa6487cef1ea2a6
|
3 |
+
size 822115836
|
pytorch_model-00015-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5c59fc995b4c6b191db065abd754dc69515c41fbb838045b6e195c226087e1b6
|
3 |
+
size 998276267
|
pytorch_model-00016-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6c6ecbf912cc7fccadd4eaf6cbfe7f42e9265b29660fa14ce748eecd74e0669f
|
3 |
+
size 998276267
|
pytorch_model-00017-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:577ad5fa496a1034241ce4aef978e326737ff41e30351dacb0bd9143d26e6a44
|
3 |
+
size 822086554
|
pytorch_model-00018-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:091383a2d940d65c731c293696d6751795506e300bcab0c4cb557082235d1699
|
3 |
+
size 822115836
|
pytorch_model-00019-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f6cee5bac09e019e40de352a15b07eabd4b20cd712dc67624a215c546a83d596
|
3 |
+
size 822115836
|
pytorch_model-00020-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d7fc14c3764aa051c4ce8c9246d367cc096d65825b309bc3a4b4f151fb7b2551
|
3 |
+
size 998276267
|
pytorch_model-00021-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d4aca8fb901bcd54868adcb56463d45f92d70ca93fc7adcbc1a81309599b6203
|
3 |
+
size 998276267
|
pytorch_model-00022-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c09fb0ac57a401e069660daacce9c5f3e37ffaca9798ee17cf19a9736b1fd04e
|
3 |
+
size 822086554
|
pytorch_model-00023-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:65060f8bd8a92f503a12716ba53d821bc260e0e7586373e439598adf3a4eeece
|
3 |
+
size 822115836
|
pytorch_model-00024-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3657a48d08843947796618bfdb85d64e93a3a50d79c1418c24d0bd56ba634497
|
3 |
+
size 822115836
|
pytorch_model-00025-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6a69557c8acd7a21e2b8dff8c0af8b55a4200f1b13cdace4d6ca340ca1a18b64
|
3 |
+
size 998276267
|
pytorch_model-00026-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a752ac70b883821eca590a01b922f394453a7de636ea4142e71cdf0dac6d9123
|
3 |
+
size 998276267
|
pytorch_model-00027-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f795f1f4229860229a3937540cf317a2eb49975362c9e7aea2393552fb27ba02
|
3 |
+
size 822086554
|
pytorch_model-00028-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0bb4c67261fe159a71d87472482c517e3c36526897417385c9dcc2a616690120
|
3 |
+
size 822115836
|
pytorch_model-00029-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9ec3a2fde5adf32e862770e5e8edc3a917b3774f46dd5be3cffd04cf5b4b2f8e
|
3 |
+
size 822115836
|
pytorch_model-00030-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4b46b3a57d749692914249523bbe60845cc0f0cae57283a2cd8bcce5b1aff4f9
|
3 |
+
size 998276267
|
pytorch_model-00031-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:79c30b89464c2e3a02c1f508327902e3f3606c72bde2858920b0608415ec3c6a
|
3 |
+
size 998276267
|
pytorch_model-00032-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:20fa61c860fe59da46cb0223dfb938369ffd35702dee7170b86af6a79f2945a8
|
3 |
+
size 822086554
|
pytorch_model-00033-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:174b587a621052f4debf764127e514ae9f9a604a468bf793a8f45be9832abfdf
|
3 |
+
size 822115836
|
pytorch_model-00034-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3c12b266a1a6b6570a6279dd79f756d44850946e3270805a71e12f26cbbe3e95
|
3 |
+
size 822115836
|
pytorch_model-00035-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b32abd9c5a34eba20bc8faa401c45186535830b22668119c3cd3f36cffbd6764
|
3 |
+
size 998276267
|
pytorch_model-00036-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b947853d3d1a96f075030708eedc0bb833759f3903d7d5ee1173fc9787765483
|
3 |
+
size 998276267
|
pytorch_model-00037-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:99292b9bd1c4c22d493953d81f6c30c780f54e1ba015cda5326da5071321bda5
|
3 |
+
size 822086554
|
pytorch_model-00038-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d017a39e08f8224a4318c24af3df96d5a711c4855eb6ed1a35e7d50ad48a9607
|
3 |
+
size 822115836
|
pytorch_model-00039-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:89a3f91da56a76427563ea5af3d8145e3270d9a8c5f5fc9ee7c00c616c2c17c6
|
3 |
+
size 822115836
|
pytorch_model-00040-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a4745381c69850027bbfcfac1bdb6b77e33b9497dd8a6ad13df9020162156d41
|
3 |
+
size 998276267
|
pytorch_model-00041-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8611ec684ceeed728433ae9b051ab2293a00f4f5489f8794d440dbe7770fff99
|
3 |
+
size 998276267
|
pytorch_model-00042-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:928ebebdae9638a94561cf34f2a8d500719e6f80be8f5cb6f7edef64f1245c47
|
3 |
+
size 822086554
|
pytorch_model-00043-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d1f1338d53c4d430221c1cb38dce255596250033b67bdded95391dfbd9337dc2
|
3 |
+
size 822115836
|
pytorch_model-00044-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:87e392be7a0b8b80aeb49f2fcc70c090749f0c9074c2cf78acf764032fcc5017
|
3 |
+
size 822115836
|
pytorch_model-00045-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:49353c7423c270f1b8fa29f4ce720609737eeedf24fd78d9b8e2930db4da5233
|
3 |
+
size 998276267
|
pytorch_model-00046-of-00077.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:77c94f5cd4229bda2cfef666c2d241f664835cd7e59f815b4907095e1ff1e9e8
|
3 |
+
size 998276267
|