Nagase-Kotono
commited on
Commit
•
9f29267
1
Parent(s):
417a7da
Upload model
Browse files- config.json +43 -0
- configuration_midm.py +21 -0
- generation_config.json +7 -0
- model-00001-of-00004.safetensors +3 -0
- model-00002-of-00004.safetensors +3 -0
- model-00003-of-00004.safetensors +3 -0
- model-00004-of-00004.safetensors +3 -0
- model.safetensors.index.json +332 -0
- modeling_midm.py +1469 -0
- rotary_position_embedding.py +97 -0
config.json
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "/workspace/midm-bitext-S-7B-inst-v1",
|
3 |
+
"activation_function": "silu",
|
4 |
+
"architectures": [
|
5 |
+
"MidmLMHeadModel"
|
6 |
+
],
|
7 |
+
"attn_pdrop": 0.0,
|
8 |
+
"auto_map": {
|
9 |
+
"AutoConfig": "configuration_midm.MidmBitextConfig",
|
10 |
+
"AutoModelForCausalLM": "modeling_midm.MidmLMHeadModel"
|
11 |
+
},
|
12 |
+
"bos_token_id": 2,
|
13 |
+
"embd_pdrop": 0.0,
|
14 |
+
"eos_token_id": 3,
|
15 |
+
"initializer_range": 0.02,
|
16 |
+
"layer_norm_epsilon": 1e-05,
|
17 |
+
"model_type": "midm-bitext-S",
|
18 |
+
"n_embd": 4096,
|
19 |
+
"n_head": 32,
|
20 |
+
"n_inner": 10880,
|
21 |
+
"n_layer": 32,
|
22 |
+
"n_positions": 8192,
|
23 |
+
"normalization_type": "layernorm1p",
|
24 |
+
"pad_token_id": 1,
|
25 |
+
"reorder_and_upcast_attn": false,
|
26 |
+
"resid_pdrop": 0.0,
|
27 |
+
"rotary_percentage": 0.5,
|
28 |
+
"scale_attn_by_inverse_layer_idx": false,
|
29 |
+
"scale_attn_weights": true,
|
30 |
+
"scale_qk_by_inverse_layer_idx": true,
|
31 |
+
"summary_activation": null,
|
32 |
+
"summary_first_dropout": 0.1,
|
33 |
+
"summary_proj_to_labels": true,
|
34 |
+
"summary_type": "cls_index",
|
35 |
+
"summary_use_proj": true,
|
36 |
+
"tie_word_embeddings": false,
|
37 |
+
"torch_dtype": "float16",
|
38 |
+
"transformers_version": "4.36.0.dev0",
|
39 |
+
"use_absolute_position_embedding": false,
|
40 |
+
"use_cache": true,
|
41 |
+
"use_rotary_position_embedding": true,
|
42 |
+
"vocab_size": 72192
|
43 |
+
}
|
configuration_midm.py
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers.models.gpt2.configuration_gpt2 import GPT2Config
|
2 |
+
|
3 |
+
class MidmBitextConfig(GPT2Config):
|
4 |
+
model_type = "midm-bitext-S"
|
5 |
+
|
6 |
+
def __init__(
|
7 |
+
self,
|
8 |
+
use_absolute_position_embedding: bool = True,
|
9 |
+
use_rotary_position_embedding: bool = False,
|
10 |
+
rotary_percentage: float = 1.0,
|
11 |
+
normalization_type: str = 'layernorm',
|
12 |
+
scale_qk_by_inverse_layer_idx: bool = False,
|
13 |
+
*args,
|
14 |
+
**kwargs
|
15 |
+
):
|
16 |
+
super().__init__(*args, **kwargs)
|
17 |
+
self.use_absolute_position_embedding = use_absolute_position_embedding
|
18 |
+
self.use_rotary_position_embedding = use_rotary_position_embedding
|
19 |
+
self.rotary_percentage = rotary_percentage
|
20 |
+
self.normalization_type = normalization_type
|
21 |
+
self.scale_qk_by_inverse_layer_idx = scale_qk_by_inverse_layer_idx
|
generation_config.json
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"bos_token_id": 2,
|
4 |
+
"eos_token_id": 3,
|
5 |
+
"pad_token_id": 1,
|
6 |
+
"transformers_version": "4.36.0.dev0"
|
7 |
+
}
|
model-00001-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a7424a19a4a23562817d01b3d531e8cc01a3f49b28a2fd3c10e8dbec7d1b08a2
|
3 |
+
size 4977911860
|
model-00002-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a8772d9f8fca279d12de2ca525de702a09540d817abb2871fc30d3bcfb4f76a5
|
3 |
+
size 4988447820
|
model-00003-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6a43507ceffdee2b812335306f51620de80fa6eb4a6ba3c300f4afb58f3665af
|
3 |
+
size 4888816622
|
model-00004-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c6964f603e6c8148393e1bbb66ef588af1ecddcbfaf11d0b1d15a51456671e40
|
3 |
+
size 1327547954
|
model.safetensors.index.json
ADDED
@@ -0,0 +1,332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"metadata": {
|
3 |
+
"total_size": 16182689984
|
4 |
+
},
|
5 |
+
"weight_map": {
|
6 |
+
"lm_head.weight": "model-00004-of-00004.safetensors",
|
7 |
+
"transformer.h.0.attn.bias": "model-00001-of-00004.safetensors",
|
8 |
+
"transformer.h.0.attn.c_attn.weight": "model-00001-of-00004.safetensors",
|
9 |
+
"transformer.h.0.attn.c_proj.weight": "model-00001-of-00004.safetensors",
|
10 |
+
"transformer.h.0.attn.masked_bias": "model-00001-of-00004.safetensors",
|
11 |
+
"transformer.h.0.ln_1.bias": "model-00001-of-00004.safetensors",
|
12 |
+
"transformer.h.0.ln_1.weight": "model-00001-of-00004.safetensors",
|
13 |
+
"transformer.h.0.ln_2.bias": "model-00001-of-00004.safetensors",
|
14 |
+
"transformer.h.0.ln_2.weight": "model-00001-of-00004.safetensors",
|
15 |
+
"transformer.h.0.mlp.c_fc.weight": "model-00001-of-00004.safetensors",
|
16 |
+
"transformer.h.0.mlp.c_proj.weight": "model-00001-of-00004.safetensors",
|
17 |
+
"transformer.h.1.attn.bias": "model-00001-of-00004.safetensors",
|
18 |
+
"transformer.h.1.attn.c_attn.weight": "model-00001-of-00004.safetensors",
|
19 |
+
"transformer.h.1.attn.c_proj.weight": "model-00001-of-00004.safetensors",
|
20 |
+
"transformer.h.1.attn.masked_bias": "model-00001-of-00004.safetensors",
|
21 |
+
"transformer.h.1.ln_1.bias": "model-00001-of-00004.safetensors",
|
22 |
+
"transformer.h.1.ln_1.weight": "model-00001-of-00004.safetensors",
|
23 |
+
"transformer.h.1.ln_2.bias": "model-00001-of-00004.safetensors",
|
24 |
+
"transformer.h.1.ln_2.weight": "model-00001-of-00004.safetensors",
|
25 |
+
"transformer.h.1.mlp.c_fc.weight": "model-00001-of-00004.safetensors",
|
26 |
+
"transformer.h.1.mlp.c_proj.weight": "model-00001-of-00004.safetensors",
|
27 |
+
"transformer.h.10.attn.bias": "model-00002-of-00004.safetensors",
|
28 |
+
"transformer.h.10.attn.c_attn.weight": "model-00002-of-00004.safetensors",
|
29 |
+
"transformer.h.10.attn.c_proj.weight": "model-00002-of-00004.safetensors",
|
30 |
+
"transformer.h.10.attn.masked_bias": "model-00002-of-00004.safetensors",
|
31 |
+
"transformer.h.10.ln_1.bias": "model-00002-of-00004.safetensors",
|
32 |
+
"transformer.h.10.ln_1.weight": "model-00002-of-00004.safetensors",
|
33 |
+
"transformer.h.10.ln_2.bias": "model-00002-of-00004.safetensors",
|
34 |
+
"transformer.h.10.ln_2.weight": "model-00002-of-00004.safetensors",
|
35 |
+
"transformer.h.10.mlp.c_fc.weight": "model-00002-of-00004.safetensors",
|
36 |
+
"transformer.h.10.mlp.c_proj.weight": "model-00002-of-00004.safetensors",
|
37 |
+
"transformer.h.11.attn.bias": "model-00002-of-00004.safetensors",
|
38 |
+
"transformer.h.11.attn.c_attn.weight": "model-00002-of-00004.safetensors",
|
39 |
+
"transformer.h.11.attn.c_proj.weight": "model-00002-of-00004.safetensors",
|
40 |
+
"transformer.h.11.attn.masked_bias": "model-00002-of-00004.safetensors",
|
41 |
+
"transformer.h.11.ln_1.bias": "model-00002-of-00004.safetensors",
|
42 |
+
"transformer.h.11.ln_1.weight": "model-00002-of-00004.safetensors",
|
43 |
+
"transformer.h.11.ln_2.bias": "model-00002-of-00004.safetensors",
|
44 |
+
"transformer.h.11.ln_2.weight": "model-00002-of-00004.safetensors",
|
45 |
+
"transformer.h.11.mlp.c_fc.weight": "model-00002-of-00004.safetensors",
|
46 |
+
"transformer.h.11.mlp.c_proj.weight": "model-00002-of-00004.safetensors",
|
47 |
+
"transformer.h.12.attn.bias": "model-00002-of-00004.safetensors",
|
48 |
+
"transformer.h.12.attn.c_attn.weight": "model-00002-of-00004.safetensors",
|
49 |
+
"transformer.h.12.attn.c_proj.weight": "model-00002-of-00004.safetensors",
|
50 |
+
"transformer.h.12.attn.masked_bias": "model-00002-of-00004.safetensors",
|
51 |
+
"transformer.h.12.ln_1.bias": "model-00002-of-00004.safetensors",
|
52 |
+
"transformer.h.12.ln_1.weight": "model-00002-of-00004.safetensors",
|
53 |
+
"transformer.h.12.ln_2.bias": "model-00002-of-00004.safetensors",
|
54 |
+
"transformer.h.12.ln_2.weight": "model-00002-of-00004.safetensors",
|
55 |
+
"transformer.h.12.mlp.c_fc.weight": "model-00002-of-00004.safetensors",
|
56 |
+
"transformer.h.12.mlp.c_proj.weight": "model-00002-of-00004.safetensors",
|
57 |
+
"transformer.h.13.attn.bias": "model-00002-of-00004.safetensors",
|
58 |
+
"transformer.h.13.attn.c_attn.weight": "model-00002-of-00004.safetensors",
|
59 |
+
"transformer.h.13.attn.c_proj.weight": "model-00002-of-00004.safetensors",
|
60 |
+
"transformer.h.13.attn.masked_bias": "model-00002-of-00004.safetensors",
|
61 |
+
"transformer.h.13.ln_1.bias": "model-00002-of-00004.safetensors",
|
62 |
+
"transformer.h.13.ln_1.weight": "model-00002-of-00004.safetensors",
|
63 |
+
"transformer.h.13.ln_2.bias": "model-00002-of-00004.safetensors",
|
64 |
+
"transformer.h.13.ln_2.weight": "model-00002-of-00004.safetensors",
|
65 |
+
"transformer.h.13.mlp.c_fc.weight": "model-00002-of-00004.safetensors",
|
66 |
+
"transformer.h.13.mlp.c_proj.weight": "model-00002-of-00004.safetensors",
|
67 |
+
"transformer.h.14.attn.bias": "model-00002-of-00004.safetensors",
|
68 |
+
"transformer.h.14.attn.c_attn.weight": "model-00002-of-00004.safetensors",
|
69 |
+
"transformer.h.14.attn.c_proj.weight": "model-00002-of-00004.safetensors",
|
70 |
+
"transformer.h.14.attn.masked_bias": "model-00002-of-00004.safetensors",
|
71 |
+
"transformer.h.14.ln_1.bias": "model-00002-of-00004.safetensors",
|
72 |
+
"transformer.h.14.ln_1.weight": "model-00002-of-00004.safetensors",
|
73 |
+
"transformer.h.14.ln_2.bias": "model-00002-of-00004.safetensors",
|
74 |
+
"transformer.h.14.ln_2.weight": "model-00002-of-00004.safetensors",
|
75 |
+
"transformer.h.14.mlp.c_fc.weight": "model-00002-of-00004.safetensors",
|
76 |
+
"transformer.h.14.mlp.c_proj.weight": "model-00002-of-00004.safetensors",
|
77 |
+
"transformer.h.15.attn.bias": "model-00002-of-00004.safetensors",
|
78 |
+
"transformer.h.15.attn.c_attn.weight": "model-00002-of-00004.safetensors",
|
79 |
+
"transformer.h.15.attn.c_proj.weight": "model-00002-of-00004.safetensors",
|
80 |
+
"transformer.h.15.attn.masked_bias": "model-00002-of-00004.safetensors",
|
81 |
+
"transformer.h.15.ln_1.bias": "model-00002-of-00004.safetensors",
|
82 |
+
"transformer.h.15.ln_1.weight": "model-00002-of-00004.safetensors",
|
83 |
+
"transformer.h.15.ln_2.bias": "model-00002-of-00004.safetensors",
|
84 |
+
"transformer.h.15.ln_2.weight": "model-00002-of-00004.safetensors",
|
85 |
+
"transformer.h.15.mlp.c_fc.weight": "model-00002-of-00004.safetensors",
|
86 |
+
"transformer.h.15.mlp.c_proj.weight": "model-00002-of-00004.safetensors",
|
87 |
+
"transformer.h.16.attn.bias": "model-00002-of-00004.safetensors",
|
88 |
+
"transformer.h.16.attn.c_attn.weight": "model-00002-of-00004.safetensors",
|
89 |
+
"transformer.h.16.attn.c_proj.weight": "model-00002-of-00004.safetensors",
|
90 |
+
"transformer.h.16.attn.masked_bias": "model-00002-of-00004.safetensors",
|
91 |
+
"transformer.h.16.ln_1.bias": "model-00002-of-00004.safetensors",
|
92 |
+
"transformer.h.16.ln_1.weight": "model-00002-of-00004.safetensors",
|
93 |
+
"transformer.h.16.ln_2.bias": "model-00002-of-00004.safetensors",
|
94 |
+
"transformer.h.16.ln_2.weight": "model-00002-of-00004.safetensors",
|
95 |
+
"transformer.h.16.mlp.c_fc.weight": "model-00002-of-00004.safetensors",
|
96 |
+
"transformer.h.16.mlp.c_proj.weight": "model-00002-of-00004.safetensors",
|
97 |
+
"transformer.h.17.attn.bias": "model-00002-of-00004.safetensors",
|
98 |
+
"transformer.h.17.attn.c_attn.weight": "model-00002-of-00004.safetensors",
|
99 |
+
"transformer.h.17.attn.c_proj.weight": "model-00002-of-00004.safetensors",
|
100 |
+
"transformer.h.17.attn.masked_bias": "model-00002-of-00004.safetensors",
|
101 |
+
"transformer.h.17.ln_1.bias": "model-00002-of-00004.safetensors",
|
102 |
+
"transformer.h.17.ln_1.weight": "model-00002-of-00004.safetensors",
|
103 |
+
"transformer.h.17.ln_2.bias": "model-00002-of-00004.safetensors",
|
104 |
+
"transformer.h.17.ln_2.weight": "model-00002-of-00004.safetensors",
|
105 |
+
"transformer.h.17.mlp.c_fc.weight": "model-00002-of-00004.safetensors",
|
106 |
+
"transformer.h.17.mlp.c_proj.weight": "model-00002-of-00004.safetensors",
|
107 |
+
"transformer.h.18.attn.bias": "model-00002-of-00004.safetensors",
|
108 |
+
"transformer.h.18.attn.c_attn.weight": "model-00002-of-00004.safetensors",
|
109 |
+
"transformer.h.18.attn.c_proj.weight": "model-00002-of-00004.safetensors",
|
110 |
+
"transformer.h.18.attn.masked_bias": "model-00002-of-00004.safetensors",
|
111 |
+
"transformer.h.18.ln_1.bias": "model-00002-of-00004.safetensors",
|
112 |
+
"transformer.h.18.ln_1.weight": "model-00002-of-00004.safetensors",
|
113 |
+
"transformer.h.18.ln_2.bias": "model-00002-of-00004.safetensors",
|
114 |
+
"transformer.h.18.ln_2.weight": "model-00002-of-00004.safetensors",
|
115 |
+
"transformer.h.18.mlp.c_fc.weight": "model-00002-of-00004.safetensors",
|
116 |
+
"transformer.h.18.mlp.c_proj.weight": "model-00002-of-00004.safetensors",
|
117 |
+
"transformer.h.19.attn.bias": "model-00002-of-00004.safetensors",
|
118 |
+
"transformer.h.19.attn.c_attn.weight": "model-00002-of-00004.safetensors",
|
119 |
+
"transformer.h.19.attn.c_proj.weight": "model-00002-of-00004.safetensors",
|
120 |
+
"transformer.h.19.attn.masked_bias": "model-00002-of-00004.safetensors",
|
121 |
+
"transformer.h.19.ln_1.bias": "model-00002-of-00004.safetensors",
|
122 |
+
"transformer.h.19.ln_1.weight": "model-00002-of-00004.safetensors",
|
123 |
+
"transformer.h.19.ln_2.bias": "model-00002-of-00004.safetensors",
|
124 |
+
"transformer.h.19.ln_2.weight": "model-00002-of-00004.safetensors",
|
125 |
+
"transformer.h.19.mlp.c_fc.weight": "model-00002-of-00004.safetensors",
|
126 |
+
"transformer.h.19.mlp.c_proj.weight": "model-00002-of-00004.safetensors",
|
127 |
+
"transformer.h.2.attn.bias": "model-00001-of-00004.safetensors",
|
128 |
+
"transformer.h.2.attn.c_attn.weight": "model-00001-of-00004.safetensors",
|
129 |
+
"transformer.h.2.attn.c_proj.weight": "model-00001-of-00004.safetensors",
|
130 |
+
"transformer.h.2.attn.masked_bias": "model-00001-of-00004.safetensors",
|
131 |
+
"transformer.h.2.ln_1.bias": "model-00001-of-00004.safetensors",
|
132 |
+
"transformer.h.2.ln_1.weight": "model-00001-of-00004.safetensors",
|
133 |
+
"transformer.h.2.ln_2.bias": "model-00001-of-00004.safetensors",
|
134 |
+
"transformer.h.2.ln_2.weight": "model-00001-of-00004.safetensors",
|
135 |
+
"transformer.h.2.mlp.c_fc.weight": "model-00001-of-00004.safetensors",
|
136 |
+
"transformer.h.2.mlp.c_proj.weight": "model-00001-of-00004.safetensors",
|
137 |
+
"transformer.h.20.attn.bias": "model-00003-of-00004.safetensors",
|
138 |
+
"transformer.h.20.attn.c_attn.weight": "model-00003-of-00004.safetensors",
|
139 |
+
"transformer.h.20.attn.c_proj.weight": "model-00003-of-00004.safetensors",
|
140 |
+
"transformer.h.20.attn.masked_bias": "model-00003-of-00004.safetensors",
|
141 |
+
"transformer.h.20.ln_1.bias": "model-00002-of-00004.safetensors",
|
142 |
+
"transformer.h.20.ln_1.weight": "model-00002-of-00004.safetensors",
|
143 |
+
"transformer.h.20.ln_2.bias": "model-00003-of-00004.safetensors",
|
144 |
+
"transformer.h.20.ln_2.weight": "model-00003-of-00004.safetensors",
|
145 |
+
"transformer.h.20.mlp.c_fc.weight": "model-00003-of-00004.safetensors",
|
146 |
+
"transformer.h.20.mlp.c_proj.weight": "model-00003-of-00004.safetensors",
|
147 |
+
"transformer.h.21.attn.bias": "model-00003-of-00004.safetensors",
|
148 |
+
"transformer.h.21.attn.c_attn.weight": "model-00003-of-00004.safetensors",
|
149 |
+
"transformer.h.21.attn.c_proj.weight": "model-00003-of-00004.safetensors",
|
150 |
+
"transformer.h.21.attn.masked_bias": "model-00003-of-00004.safetensors",
|
151 |
+
"transformer.h.21.ln_1.bias": "model-00003-of-00004.safetensors",
|
152 |
+
"transformer.h.21.ln_1.weight": "model-00003-of-00004.safetensors",
|
153 |
+
"transformer.h.21.ln_2.bias": "model-00003-of-00004.safetensors",
|
154 |
+
"transformer.h.21.ln_2.weight": "model-00003-of-00004.safetensors",
|
155 |
+
"transformer.h.21.mlp.c_fc.weight": "model-00003-of-00004.safetensors",
|
156 |
+
"transformer.h.21.mlp.c_proj.weight": "model-00003-of-00004.safetensors",
|
157 |
+
"transformer.h.22.attn.bias": "model-00003-of-00004.safetensors",
|
158 |
+
"transformer.h.22.attn.c_attn.weight": "model-00003-of-00004.safetensors",
|
159 |
+
"transformer.h.22.attn.c_proj.weight": "model-00003-of-00004.safetensors",
|
160 |
+
"transformer.h.22.attn.masked_bias": "model-00003-of-00004.safetensors",
|
161 |
+
"transformer.h.22.ln_1.bias": "model-00003-of-00004.safetensors",
|
162 |
+
"transformer.h.22.ln_1.weight": "model-00003-of-00004.safetensors",
|
163 |
+
"transformer.h.22.ln_2.bias": "model-00003-of-00004.safetensors",
|
164 |
+
"transformer.h.22.ln_2.weight": "model-00003-of-00004.safetensors",
|
165 |
+
"transformer.h.22.mlp.c_fc.weight": "model-00003-of-00004.safetensors",
|
166 |
+
"transformer.h.22.mlp.c_proj.weight": "model-00003-of-00004.safetensors",
|
167 |
+
"transformer.h.23.attn.bias": "model-00003-of-00004.safetensors",
|
168 |
+
"transformer.h.23.attn.c_attn.weight": "model-00003-of-00004.safetensors",
|
169 |
+
"transformer.h.23.attn.c_proj.weight": "model-00003-of-00004.safetensors",
|
170 |
+
"transformer.h.23.attn.masked_bias": "model-00003-of-00004.safetensors",
|
171 |
+
"transformer.h.23.ln_1.bias": "model-00003-of-00004.safetensors",
|
172 |
+
"transformer.h.23.ln_1.weight": "model-00003-of-00004.safetensors",
|
173 |
+
"transformer.h.23.ln_2.bias": "model-00003-of-00004.safetensors",
|
174 |
+
"transformer.h.23.ln_2.weight": "model-00003-of-00004.safetensors",
|
175 |
+
"transformer.h.23.mlp.c_fc.weight": "model-00003-of-00004.safetensors",
|
176 |
+
"transformer.h.23.mlp.c_proj.weight": "model-00003-of-00004.safetensors",
|
177 |
+
"transformer.h.24.attn.bias": "model-00003-of-00004.safetensors",
|
178 |
+
"transformer.h.24.attn.c_attn.weight": "model-00003-of-00004.safetensors",
|
179 |
+
"transformer.h.24.attn.c_proj.weight": "model-00003-of-00004.safetensors",
|
180 |
+
"transformer.h.24.attn.masked_bias": "model-00003-of-00004.safetensors",
|
181 |
+
"transformer.h.24.ln_1.bias": "model-00003-of-00004.safetensors",
|
182 |
+
"transformer.h.24.ln_1.weight": "model-00003-of-00004.safetensors",
|
183 |
+
"transformer.h.24.ln_2.bias": "model-00003-of-00004.safetensors",
|
184 |
+
"transformer.h.24.ln_2.weight": "model-00003-of-00004.safetensors",
|
185 |
+
"transformer.h.24.mlp.c_fc.weight": "model-00003-of-00004.safetensors",
|
186 |
+
"transformer.h.24.mlp.c_proj.weight": "model-00003-of-00004.safetensors",
|
187 |
+
"transformer.h.25.attn.bias": "model-00003-of-00004.safetensors",
|
188 |
+
"transformer.h.25.attn.c_attn.weight": "model-00003-of-00004.safetensors",
|
189 |
+
"transformer.h.25.attn.c_proj.weight": "model-00003-of-00004.safetensors",
|
190 |
+
"transformer.h.25.attn.masked_bias": "model-00003-of-00004.safetensors",
|
191 |
+
"transformer.h.25.ln_1.bias": "model-00003-of-00004.safetensors",
|
192 |
+
"transformer.h.25.ln_1.weight": "model-00003-of-00004.safetensors",
|
193 |
+
"transformer.h.25.ln_2.bias": "model-00003-of-00004.safetensors",
|
194 |
+
"transformer.h.25.ln_2.weight": "model-00003-of-00004.safetensors",
|
195 |
+
"transformer.h.25.mlp.c_fc.weight": "model-00003-of-00004.safetensors",
|
196 |
+
"transformer.h.25.mlp.c_proj.weight": "model-00003-of-00004.safetensors",
|
197 |
+
"transformer.h.26.attn.bias": "model-00003-of-00004.safetensors",
|
198 |
+
"transformer.h.26.attn.c_attn.weight": "model-00003-of-00004.safetensors",
|
199 |
+
"transformer.h.26.attn.c_proj.weight": "model-00003-of-00004.safetensors",
|
200 |
+
"transformer.h.26.attn.masked_bias": "model-00003-of-00004.safetensors",
|
201 |
+
"transformer.h.26.ln_1.bias": "model-00003-of-00004.safetensors",
|
202 |
+
"transformer.h.26.ln_1.weight": "model-00003-of-00004.safetensors",
|
203 |
+
"transformer.h.26.ln_2.bias": "model-00003-of-00004.safetensors",
|
204 |
+
"transformer.h.26.ln_2.weight": "model-00003-of-00004.safetensors",
|
205 |
+
"transformer.h.26.mlp.c_fc.weight": "model-00003-of-00004.safetensors",
|
206 |
+
"transformer.h.26.mlp.c_proj.weight": "model-00003-of-00004.safetensors",
|
207 |
+
"transformer.h.27.attn.bias": "model-00003-of-00004.safetensors",
|
208 |
+
"transformer.h.27.attn.c_attn.weight": "model-00003-of-00004.safetensors",
|
209 |
+
"transformer.h.27.attn.c_proj.weight": "model-00003-of-00004.safetensors",
|
210 |
+
"transformer.h.27.attn.masked_bias": "model-00003-of-00004.safetensors",
|
211 |
+
"transformer.h.27.ln_1.bias": "model-00003-of-00004.safetensors",
|
212 |
+
"transformer.h.27.ln_1.weight": "model-00003-of-00004.safetensors",
|
213 |
+
"transformer.h.27.ln_2.bias": "model-00003-of-00004.safetensors",
|
214 |
+
"transformer.h.27.ln_2.weight": "model-00003-of-00004.safetensors",
|
215 |
+
"transformer.h.27.mlp.c_fc.weight": "model-00003-of-00004.safetensors",
|
216 |
+
"transformer.h.27.mlp.c_proj.weight": "model-00003-of-00004.safetensors",
|
217 |
+
"transformer.h.28.attn.bias": "model-00003-of-00004.safetensors",
|
218 |
+
"transformer.h.28.attn.c_attn.weight": "model-00003-of-00004.safetensors",
|
219 |
+
"transformer.h.28.attn.c_proj.weight": "model-00003-of-00004.safetensors",
|
220 |
+
"transformer.h.28.attn.masked_bias": "model-00003-of-00004.safetensors",
|
221 |
+
"transformer.h.28.ln_1.bias": "model-00003-of-00004.safetensors",
|
222 |
+
"transformer.h.28.ln_1.weight": "model-00003-of-00004.safetensors",
|
223 |
+
"transformer.h.28.ln_2.bias": "model-00003-of-00004.safetensors",
|
224 |
+
"transformer.h.28.ln_2.weight": "model-00003-of-00004.safetensors",
|
225 |
+
"transformer.h.28.mlp.c_fc.weight": "model-00003-of-00004.safetensors",
|
226 |
+
"transformer.h.28.mlp.c_proj.weight": "model-00003-of-00004.safetensors",
|
227 |
+
"transformer.h.29.attn.bias": "model-00003-of-00004.safetensors",
|
228 |
+
"transformer.h.29.attn.c_attn.weight": "model-00003-of-00004.safetensors",
|
229 |
+
"transformer.h.29.attn.c_proj.weight": "model-00003-of-00004.safetensors",
|
230 |
+
"transformer.h.29.attn.masked_bias": "model-00003-of-00004.safetensors",
|
231 |
+
"transformer.h.29.ln_1.bias": "model-00003-of-00004.safetensors",
|
232 |
+
"transformer.h.29.ln_1.weight": "model-00003-of-00004.safetensors",
|
233 |
+
"transformer.h.29.ln_2.bias": "model-00003-of-00004.safetensors",
|
234 |
+
"transformer.h.29.ln_2.weight": "model-00003-of-00004.safetensors",
|
235 |
+
"transformer.h.29.mlp.c_fc.weight": "model-00003-of-00004.safetensors",
|
236 |
+
"transformer.h.29.mlp.c_proj.weight": "model-00003-of-00004.safetensors",
|
237 |
+
"transformer.h.3.attn.bias": "model-00001-of-00004.safetensors",
|
238 |
+
"transformer.h.3.attn.c_attn.weight": "model-00001-of-00004.safetensors",
|
239 |
+
"transformer.h.3.attn.c_proj.weight": "model-00001-of-00004.safetensors",
|
240 |
+
"transformer.h.3.attn.masked_bias": "model-00001-of-00004.safetensors",
|
241 |
+
"transformer.h.3.ln_1.bias": "model-00001-of-00004.safetensors",
|
242 |
+
"transformer.h.3.ln_1.weight": "model-00001-of-00004.safetensors",
|
243 |
+
"transformer.h.3.ln_2.bias": "model-00001-of-00004.safetensors",
|
244 |
+
"transformer.h.3.ln_2.weight": "model-00001-of-00004.safetensors",
|
245 |
+
"transformer.h.3.mlp.c_fc.weight": "model-00001-of-00004.safetensors",
|
246 |
+
"transformer.h.3.mlp.c_proj.weight": "model-00001-of-00004.safetensors",
|
247 |
+
"transformer.h.30.attn.bias": "model-00003-of-00004.safetensors",
|
248 |
+
"transformer.h.30.attn.c_attn.weight": "model-00003-of-00004.safetensors",
|
249 |
+
"transformer.h.30.attn.c_proj.weight": "model-00003-of-00004.safetensors",
|
250 |
+
"transformer.h.30.attn.masked_bias": "model-00003-of-00004.safetensors",
|
251 |
+
"transformer.h.30.ln_1.bias": "model-00003-of-00004.safetensors",
|
252 |
+
"transformer.h.30.ln_1.weight": "model-00003-of-00004.safetensors",
|
253 |
+
"transformer.h.30.ln_2.bias": "model-00003-of-00004.safetensors",
|
254 |
+
"transformer.h.30.ln_2.weight": "model-00003-of-00004.safetensors",
|
255 |
+
"transformer.h.30.mlp.c_fc.weight": "model-00004-of-00004.safetensors",
|
256 |
+
"transformer.h.30.mlp.c_proj.weight": "model-00004-of-00004.safetensors",
|
257 |
+
"transformer.h.31.attn.bias": "model-00004-of-00004.safetensors",
|
258 |
+
"transformer.h.31.attn.c_attn.weight": "model-00004-of-00004.safetensors",
|
259 |
+
"transformer.h.31.attn.c_proj.weight": "model-00004-of-00004.safetensors",
|
260 |
+
"transformer.h.31.attn.masked_bias": "model-00004-of-00004.safetensors",
|
261 |
+
"transformer.h.31.ln_1.bias": "model-00004-of-00004.safetensors",
|
262 |
+
"transformer.h.31.ln_1.weight": "model-00004-of-00004.safetensors",
|
263 |
+
"transformer.h.31.ln_2.bias": "model-00004-of-00004.safetensors",
|
264 |
+
"transformer.h.31.ln_2.weight": "model-00004-of-00004.safetensors",
|
265 |
+
"transformer.h.31.mlp.c_fc.weight": "model-00004-of-00004.safetensors",
|
266 |
+
"transformer.h.31.mlp.c_proj.weight": "model-00004-of-00004.safetensors",
|
267 |
+
"transformer.h.4.attn.bias": "model-00001-of-00004.safetensors",
|
268 |
+
"transformer.h.4.attn.c_attn.weight": "model-00001-of-00004.safetensors",
|
269 |
+
"transformer.h.4.attn.c_proj.weight": "model-00001-of-00004.safetensors",
|
270 |
+
"transformer.h.4.attn.masked_bias": "model-00001-of-00004.safetensors",
|
271 |
+
"transformer.h.4.ln_1.bias": "model-00001-of-00004.safetensors",
|
272 |
+
"transformer.h.4.ln_1.weight": "model-00001-of-00004.safetensors",
|
273 |
+
"transformer.h.4.ln_2.bias": "model-00001-of-00004.safetensors",
|
274 |
+
"transformer.h.4.ln_2.weight": "model-00001-of-00004.safetensors",
|
275 |
+
"transformer.h.4.mlp.c_fc.weight": "model-00001-of-00004.safetensors",
|
276 |
+
"transformer.h.4.mlp.c_proj.weight": "model-00001-of-00004.safetensors",
|
277 |
+
"transformer.h.5.attn.bias": "model-00001-of-00004.safetensors",
|
278 |
+
"transformer.h.5.attn.c_attn.weight": "model-00001-of-00004.safetensors",
|
279 |
+
"transformer.h.5.attn.c_proj.weight": "model-00001-of-00004.safetensors",
|
280 |
+
"transformer.h.5.attn.masked_bias": "model-00001-of-00004.safetensors",
|
281 |
+
"transformer.h.5.ln_1.bias": "model-00001-of-00004.safetensors",
|
282 |
+
"transformer.h.5.ln_1.weight": "model-00001-of-00004.safetensors",
|
283 |
+
"transformer.h.5.ln_2.bias": "model-00001-of-00004.safetensors",
|
284 |
+
"transformer.h.5.ln_2.weight": "model-00001-of-00004.safetensors",
|
285 |
+
"transformer.h.5.mlp.c_fc.weight": "model-00001-of-00004.safetensors",
|
286 |
+
"transformer.h.5.mlp.c_proj.weight": "model-00001-of-00004.safetensors",
|
287 |
+
"transformer.h.6.attn.bias": "model-00001-of-00004.safetensors",
|
288 |
+
"transformer.h.6.attn.c_attn.weight": "model-00001-of-00004.safetensors",
|
289 |
+
"transformer.h.6.attn.c_proj.weight": "model-00001-of-00004.safetensors",
|
290 |
+
"transformer.h.6.attn.masked_bias": "model-00001-of-00004.safetensors",
|
291 |
+
"transformer.h.6.ln_1.bias": "model-00001-of-00004.safetensors",
|
292 |
+
"transformer.h.6.ln_1.weight": "model-00001-of-00004.safetensors",
|
293 |
+
"transformer.h.6.ln_2.bias": "model-00001-of-00004.safetensors",
|
294 |
+
"transformer.h.6.ln_2.weight": "model-00001-of-00004.safetensors",
|
295 |
+
"transformer.h.6.mlp.c_fc.weight": "model-00001-of-00004.safetensors",
|
296 |
+
"transformer.h.6.mlp.c_proj.weight": "model-00001-of-00004.safetensors",
|
297 |
+
"transformer.h.7.attn.bias": "model-00001-of-00004.safetensors",
|
298 |
+
"transformer.h.7.attn.c_attn.weight": "model-00001-of-00004.safetensors",
|
299 |
+
"transformer.h.7.attn.c_proj.weight": "model-00001-of-00004.safetensors",
|
300 |
+
"transformer.h.7.attn.masked_bias": "model-00001-of-00004.safetensors",
|
301 |
+
"transformer.h.7.ln_1.bias": "model-00001-of-00004.safetensors",
|
302 |
+
"transformer.h.7.ln_1.weight": "model-00001-of-00004.safetensors",
|
303 |
+
"transformer.h.7.ln_2.bias": "model-00001-of-00004.safetensors",
|
304 |
+
"transformer.h.7.ln_2.weight": "model-00001-of-00004.safetensors",
|
305 |
+
"transformer.h.7.mlp.c_fc.weight": "model-00001-of-00004.safetensors",
|
306 |
+
"transformer.h.7.mlp.c_proj.weight": "model-00001-of-00004.safetensors",
|
307 |
+
"transformer.h.8.attn.bias": "model-00001-of-00004.safetensors",
|
308 |
+
"transformer.h.8.attn.c_attn.weight": "model-00001-of-00004.safetensors",
|
309 |
+
"transformer.h.8.attn.c_proj.weight": "model-00001-of-00004.safetensors",
|
310 |
+
"transformer.h.8.attn.masked_bias": "model-00001-of-00004.safetensors",
|
311 |
+
"transformer.h.8.ln_1.bias": "model-00001-of-00004.safetensors",
|
312 |
+
"transformer.h.8.ln_1.weight": "model-00001-of-00004.safetensors",
|
313 |
+
"transformer.h.8.ln_2.bias": "model-00001-of-00004.safetensors",
|
314 |
+
"transformer.h.8.ln_2.weight": "model-00001-of-00004.safetensors",
|
315 |
+
"transformer.h.8.mlp.c_fc.weight": "model-00001-of-00004.safetensors",
|
316 |
+
"transformer.h.8.mlp.c_proj.weight": "model-00001-of-00004.safetensors",
|
317 |
+
"transformer.h.9.attn.bias": "model-00001-of-00004.safetensors",
|
318 |
+
"transformer.h.9.attn.c_attn.weight": "model-00001-of-00004.safetensors",
|
319 |
+
"transformer.h.9.attn.c_proj.weight": "model-00002-of-00004.safetensors",
|
320 |
+
"transformer.h.9.attn.masked_bias": "model-00001-of-00004.safetensors",
|
321 |
+
"transformer.h.9.ln_1.bias": "model-00001-of-00004.safetensors",
|
322 |
+
"transformer.h.9.ln_1.weight": "model-00001-of-00004.safetensors",
|
323 |
+
"transformer.h.9.ln_2.bias": "model-00002-of-00004.safetensors",
|
324 |
+
"transformer.h.9.ln_2.weight": "model-00002-of-00004.safetensors",
|
325 |
+
"transformer.h.9.mlp.c_fc.weight": "model-00002-of-00004.safetensors",
|
326 |
+
"transformer.h.9.mlp.c_proj.weight": "model-00002-of-00004.safetensors",
|
327 |
+
"transformer.ln_f.bias": "model-00004-of-00004.safetensors",
|
328 |
+
"transformer.ln_f.weight": "model-00004-of-00004.safetensors",
|
329 |
+
"transformer.rotary_pos_emb.inv_freq": "model-00001-of-00004.safetensors",
|
330 |
+
"transformer.wte.weight": "model-00001-of-00004.safetensors"
|
331 |
+
}
|
332 |
+
}
|
modeling_midm.py
ADDED
@@ -0,0 +1,1469 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
"""PyTorch Midm model."""
|
16 |
+
|
17 |
+
import math
|
18 |
+
import os
|
19 |
+
from dataclasses import dataclass
|
20 |
+
from typing import Optional, Tuple
|
21 |
+
|
22 |
+
import torch
|
23 |
+
import torch.utils.checkpoint
|
24 |
+
from packaging import version
|
25 |
+
from torch import nn
|
26 |
+
from torch.nn import CrossEntropyLoss, MSELoss
|
27 |
+
from types import SimpleNamespace
|
28 |
+
from .rotary_position_embedding import RotaryEmbedding, apply_rotary_pos_emb
|
29 |
+
|
30 |
+
if version.parse(torch.__version__) >= version.parse("1.6"):
|
31 |
+
is_amp_available = True
|
32 |
+
from torch.cuda.amp import autocast
|
33 |
+
else:
|
34 |
+
is_amp_available = False
|
35 |
+
|
36 |
+
from transformers.activations import ACT2FN
|
37 |
+
from transformers.file_utils import (
|
38 |
+
ModelOutput,
|
39 |
+
add_code_sample_docstrings,
|
40 |
+
add_start_docstrings,
|
41 |
+
add_start_docstrings_to_model_forward,
|
42 |
+
replace_return_docstrings,
|
43 |
+
)
|
44 |
+
from transformers.modeling_outputs import (
|
45 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
46 |
+
CausalLMOutputWithCrossAttentions,
|
47 |
+
SequenceClassifierOutputWithPast,
|
48 |
+
TokenClassifierOutput,
|
49 |
+
)
|
50 |
+
from transformers.modeling_utils import (
|
51 |
+
Conv1D,
|
52 |
+
PreTrainedModel,
|
53 |
+
SequenceSummary,
|
54 |
+
find_pruneable_heads_and_indices,
|
55 |
+
prune_conv1d_layer,
|
56 |
+
)
|
57 |
+
from transformers.utils import logging
|
58 |
+
from transformers.utils.model_parallel_utils import assert_device_map, get_device_map
|
59 |
+
from .configuration_midm import MidmBitextConfig
|
60 |
+
|
61 |
+
|
62 |
+
logger = logging.get_logger(__name__)
|
63 |
+
|
64 |
+
_CHECKPOINT_FOR_DOC = "Midm"
|
65 |
+
_CONFIG_FOR_DOC = "MidmBitextConfig"
|
66 |
+
_TOKENIZER_FOR_DOC = "Midm_bitext_Tokenizer"
|
67 |
+
|
68 |
+
MIDM_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
69 |
+
"Midm-bitext-S",
|
70 |
+
]
|
71 |
+
|
72 |
+
def layernorm1p(module, input):
|
73 |
+
return torch.nn.functional.layer_norm(
|
74 |
+
input, module.normalized_shape, module.weight + 1, module.bias, module.eps)
|
75 |
+
|
76 |
+
class MidmAttention(nn.Module):
|
77 |
+
def __init__(self, config, is_cross_attention=False, layer_idx=None):
|
78 |
+
super().__init__()
|
79 |
+
|
80 |
+
max_positions = config.max_position_embeddings
|
81 |
+
self.register_buffer(
|
82 |
+
"bias",
|
83 |
+
torch.tril(torch.ones((max_positions, max_positions), dtype=torch.uint8)).view(
|
84 |
+
1, 1, max_positions, max_positions
|
85 |
+
),
|
86 |
+
)
|
87 |
+
self.register_buffer("masked_bias", torch.tensor(-1e4))
|
88 |
+
|
89 |
+
self.embed_dim = config.hidden_size
|
90 |
+
self.num_heads = config.num_attention_heads
|
91 |
+
self.head_dim = self.embed_dim // self.num_heads
|
92 |
+
self.split_size = self.embed_dim
|
93 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
94 |
+
raise ValueError(
|
95 |
+
f"`embed_dim` must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {self.num_heads})."
|
96 |
+
)
|
97 |
+
|
98 |
+
self.scale_attn_weights = config.scale_attn_weights
|
99 |
+
self.is_cross_attention = is_cross_attention
|
100 |
+
|
101 |
+
# Layer-wise attention scaling, reordering, and upcasting
|
102 |
+
self.scale_attn_by_inverse_layer_idx = config.scale_attn_by_inverse_layer_idx
|
103 |
+
self.layer_idx = layer_idx
|
104 |
+
self.reorder_and_upcast_attn = config.reorder_and_upcast_attn
|
105 |
+
self.scale_qk_by_inverse_layer_idx = config.scale_qk_by_inverse_layer_idx
|
106 |
+
assert self.scale_attn_by_inverse_layer_idx != self.scale_qk_by_inverse_layer_idx
|
107 |
+
|
108 |
+
if self.is_cross_attention:
|
109 |
+
self.c_attn = nn.Linear(self.embed_dim, 2 * self.embed_dim, bias=False)
|
110 |
+
nn.init.normal_(self.c_attn.weight, std=0.02)
|
111 |
+
self.q_attn = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
|
112 |
+
nn.init.normal_(self.q_attn.weight, std=0.02)
|
113 |
+
else:
|
114 |
+
self.c_attn = nn.Linear(self.embed_dim, 3 * self.embed_dim, bias=False)
|
115 |
+
nn.init.normal_(self.c_attn.weight, std=0.02)
|
116 |
+
self.c_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
|
117 |
+
nn.init.normal_(self.c_proj.weight, std=0.02)
|
118 |
+
|
119 |
+
self.attn_dropout = nn.Dropout(config.attn_pdrop)
|
120 |
+
self.resid_dropout = nn.Dropout(config.resid_pdrop)
|
121 |
+
|
122 |
+
self.pruned_heads = set()
|
123 |
+
|
124 |
+
def prune_heads(self, heads):
|
125 |
+
if len(heads) == 0:
|
126 |
+
return
|
127 |
+
heads, index = find_pruneable_heads_and_indices(heads, self.num_heads, self.head_dim, self.pruned_heads)
|
128 |
+
index_attn = torch.cat([index, index + self.split_size, index + (2 * self.split_size)])
|
129 |
+
|
130 |
+
# Prune conv1d layers
|
131 |
+
self.c_attn = prune_conv1d_layer(self.c_attn, index_attn, dim=1)
|
132 |
+
self.c_proj = prune_conv1d_layer(self.c_proj, index, dim=0)
|
133 |
+
|
134 |
+
# Update hyper params
|
135 |
+
self.split_size = (self.split_size // self.num_heads) * (self.num_heads - len(heads))
|
136 |
+
self.num_heads = self.num_heads - len(heads)
|
137 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
138 |
+
|
139 |
+
def _attn(self, query, key, value, attention_mask=None, head_mask=None):
|
140 |
+
attn_weights = torch.matmul(query, key.transpose(-1, -2))
|
141 |
+
|
142 |
+
if self.scale_attn_weights:
|
143 |
+
attn_weights = attn_weights / (float(value.size(-1)) ** 0.5)
|
144 |
+
|
145 |
+
# Layer-wise attention scaling
|
146 |
+
if self.scale_attn_by_inverse_layer_idx or self.scale_qk_by_inverse_layer_idx:
|
147 |
+
attn_weights = attn_weights / float(self.layer_idx + 1)
|
148 |
+
|
149 |
+
if not self.is_cross_attention:
|
150 |
+
# if only "normal" attention layer implements causal mask
|
151 |
+
query_length, key_length = query.size(-2), key.size(-2)
|
152 |
+
causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length].bool()
|
153 |
+
attn_weights = torch.where(causal_mask, attn_weights, self.masked_bias.to(attn_weights.dtype))
|
154 |
+
|
155 |
+
if attention_mask is not None:
|
156 |
+
# Apply the attention mask
|
157 |
+
attn_weights = attn_weights + attention_mask
|
158 |
+
|
159 |
+
if self.scale_qk_by_inverse_layer_idx:
|
160 |
+
attn_weights = attn_weights * float(self.layer_idx + 1)
|
161 |
+
|
162 |
+
attn_weights = nn.Softmax(dim=-1)(attn_weights)
|
163 |
+
|
164 |
+
# Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op otherwise
|
165 |
+
attn_weights = attn_weights.type(value.dtype)
|
166 |
+
attn_weights = self.attn_dropout(attn_weights)
|
167 |
+
|
168 |
+
# Mask heads if we want to
|
169 |
+
if head_mask is not None:
|
170 |
+
attn_weights = attn_weights * head_mask
|
171 |
+
|
172 |
+
attn_output = torch.matmul(attn_weights, value)
|
173 |
+
|
174 |
+
return attn_output, attn_weights
|
175 |
+
|
176 |
+
def _upcast_and_reordered_attn(self, query, key, value, attention_mask=None, head_mask=None):
|
177 |
+
# Use `torch.baddbmm` (a bit more efficient w/ alpha param for scaling -- from Megatron-LM)
|
178 |
+
bsz, num_heads, q_seq_len, dk = query.size()
|
179 |
+
_, _, k_seq_len, _ = key.size()
|
180 |
+
|
181 |
+
# Preallocate attn_weights for `baddbmm`
|
182 |
+
attn_weights = torch.empty(bsz * num_heads, q_seq_len, k_seq_len, dtype=torch.float32, device=query.device)
|
183 |
+
|
184 |
+
# Compute Scale Factor
|
185 |
+
scale_factor = 1.0
|
186 |
+
if self.scale_attn_weights:
|
187 |
+
scale_factor /= float(value.size(-1)) ** 0.5
|
188 |
+
|
189 |
+
if self.scale_attn_by_inverse_layer_idx:
|
190 |
+
scale_factor /= float(self.layer_idx + 1)
|
191 |
+
|
192 |
+
# Upcast (turn off autocast) and reorder (Scale K by 1 / root(dk))
|
193 |
+
if is_amp_available:
|
194 |
+
with autocast(enabled=False):
|
195 |
+
q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(-1, dk, k_seq_len)
|
196 |
+
attn_weights = torch.baddbmm(attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor)
|
197 |
+
attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
|
198 |
+
else:
|
199 |
+
q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(-1, dk, k_seq_len)
|
200 |
+
attn_weights = torch.baddbmm(attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor)
|
201 |
+
attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
|
202 |
+
|
203 |
+
if not self.is_cross_attention:
|
204 |
+
# if only "normal" attention layer implements causal mask
|
205 |
+
query_length, key_length = query.size(-2), key.size(-2)
|
206 |
+
causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length].bool()
|
207 |
+
attn_weights = torch.where(causal_mask, attn_weights, self.masked_bias.to(attn_weights.dtype))
|
208 |
+
|
209 |
+
if attention_mask is not None:
|
210 |
+
# Apply the attention mask
|
211 |
+
attn_weights = attn_weights + attention_mask
|
212 |
+
|
213 |
+
attn_weights = nn.Softmax(dim=-1)(attn_weights)
|
214 |
+
|
215 |
+
# Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op if otherwise
|
216 |
+
if attn_weights.dtype != torch.float32:
|
217 |
+
raise RuntimeError("Error with upcasting, attn_weights does not have dtype torch.float32")
|
218 |
+
attn_weights = attn_weights.type(value.dtype)
|
219 |
+
attn_weights = self.attn_dropout(attn_weights)
|
220 |
+
|
221 |
+
# Mask heads if we want to
|
222 |
+
if head_mask is not None:
|
223 |
+
attn_weights = attn_weights * head_mask
|
224 |
+
|
225 |
+
attn_output = torch.matmul(attn_weights, value)
|
226 |
+
|
227 |
+
return attn_output, attn_weights
|
228 |
+
|
229 |
+
def _split_heads(self, tensor, num_heads, attn_head_size):
|
230 |
+
"""
|
231 |
+
Splits hidden_size dim into attn_head_size and num_heads
|
232 |
+
"""
|
233 |
+
new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
|
234 |
+
tensor = tensor.view(*new_shape)
|
235 |
+
return tensor.permute(0, 2, 1, 3) # (batch, head, seq_length, head_features)
|
236 |
+
|
237 |
+
def _merge_heads(self, tensor, num_heads, attn_head_size):
|
238 |
+
"""
|
239 |
+
Merges attn_head_size dim and num_attn_heads dim into hidden_size
|
240 |
+
"""
|
241 |
+
tensor = tensor.permute(0, 2, 1, 3).contiguous()
|
242 |
+
new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
|
243 |
+
return tensor.view(new_shape)
|
244 |
+
|
245 |
+
def forward(
|
246 |
+
self,
|
247 |
+
hidden_states,
|
248 |
+
layer_past=None,
|
249 |
+
attention_mask=None,
|
250 |
+
head_mask=None,
|
251 |
+
encoder_hidden_states=None,
|
252 |
+
encoder_attention_mask=None,
|
253 |
+
use_cache=False,
|
254 |
+
output_attentions=False,
|
255 |
+
rotary_pos_emb=None,
|
256 |
+
):
|
257 |
+
if encoder_hidden_states is not None:
|
258 |
+
if not hasattr(self, "q_attn"):
|
259 |
+
raise ValueError(
|
260 |
+
"If class is used as cross attention, the weights `q_attn` have to be defined. "
|
261 |
+
"Please make sure to instantiate class with `MidmAttention(..., is_cross_attention=True)`."
|
262 |
+
)
|
263 |
+
|
264 |
+
query = self.q_attn(hidden_states)
|
265 |
+
key, value = self.c_attn(encoder_hidden_states).split(self.split_size, dim=2)
|
266 |
+
attention_mask = encoder_attention_mask
|
267 |
+
else:
|
268 |
+
query, key, value = self.c_attn(hidden_states).split(self.split_size, dim=2)
|
269 |
+
|
270 |
+
query = self._split_heads(query, self.num_heads, self.head_dim)
|
271 |
+
key = self._split_heads(key, self.num_heads, self.head_dim)
|
272 |
+
value = self._split_heads(value, self.num_heads, self.head_dim)
|
273 |
+
|
274 |
+
if layer_past is not None:
|
275 |
+
past_key, past_value = layer_past
|
276 |
+
key = torch.cat((past_key, key), dim=-2)
|
277 |
+
value = torch.cat((past_value, value), dim=-2)
|
278 |
+
|
279 |
+
if use_cache is True:
|
280 |
+
present = (key, value)
|
281 |
+
else:
|
282 |
+
present = None
|
283 |
+
|
284 |
+
if rotary_pos_emb is not None:
|
285 |
+
query = apply_rotary_pos_emb(query, rotary_pos_emb)
|
286 |
+
key = apply_rotary_pos_emb(key, rotary_pos_emb)
|
287 |
+
|
288 |
+
if self.reorder_and_upcast_attn:
|
289 |
+
attn_output, attn_weights = self._upcast_and_reordered_attn(query, key, value, attention_mask, head_mask)
|
290 |
+
else:
|
291 |
+
attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask)
|
292 |
+
|
293 |
+
attn_output = self._merge_heads(attn_output, self.num_heads, self.head_dim)
|
294 |
+
attn_output = self.c_proj(attn_output)
|
295 |
+
attn_output = self.resid_dropout(attn_output)
|
296 |
+
|
297 |
+
outputs = (attn_output, present)
|
298 |
+
if output_attentions:
|
299 |
+
outputs += (attn_weights,)
|
300 |
+
|
301 |
+
return outputs # a, present, (attentions)
|
302 |
+
|
303 |
+
|
304 |
+
class MidmMLP(nn.Module):
|
305 |
+
def __init__(self, intermediate_size, config):
|
306 |
+
super().__init__()
|
307 |
+
embed_dim = config.hidden_size
|
308 |
+
self.kt_glu = config.activation_function in ['silu']
|
309 |
+
if self.kt_glu:
|
310 |
+
self.c_fc = nn.Linear(embed_dim, intermediate_size * 2, bias=False)
|
311 |
+
else:
|
312 |
+
self.c_fc = nn.Linear(embed_dim, intermediate_size, bias=False)
|
313 |
+
nn.init.normal_(self.c_fc.weight, std=0.02)
|
314 |
+
self.c_proj = nn.Linear(intermediate_size, embed_dim, bias=False)
|
315 |
+
nn.init.normal_(self.c_proj.weight, std=0.02)
|
316 |
+
|
317 |
+
if config.activation_function == 'silu':
|
318 |
+
self.act = torch.nn.functional.silu
|
319 |
+
else:
|
320 |
+
self.act = ACT2FN[config.activation_function]
|
321 |
+
self.dropout = nn.Dropout(config.resid_pdrop)
|
322 |
+
|
323 |
+
def forward(self, hidden_states):
|
324 |
+
hidden_states = self.c_fc(hidden_states)
|
325 |
+
if self.kt_glu:
|
326 |
+
hidden_states1, hidden_states2 = torch.chunk(hidden_states, 2, dim=-1)
|
327 |
+
hidden_states = self.act(hidden_states1) * hidden_states2
|
328 |
+
else:
|
329 |
+
hidden_states = self.act(hidden_states)
|
330 |
+
hidden_states = self.c_proj(hidden_states)
|
331 |
+
hidden_states = self.dropout(hidden_states)
|
332 |
+
return hidden_states
|
333 |
+
|
334 |
+
|
335 |
+
class MidmBlock(nn.Module):
|
336 |
+
def __init__(self, config, layer_idx=None):
|
337 |
+
super().__init__()
|
338 |
+
hidden_size = config.hidden_size
|
339 |
+
inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
|
340 |
+
|
341 |
+
self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
|
342 |
+
self.attn = MidmAttention(config, layer_idx=layer_idx)
|
343 |
+
self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
|
344 |
+
self.use_layernorm1p = config.normalization_type == 'layernorm1p'
|
345 |
+
|
346 |
+
if config.add_cross_attention:
|
347 |
+
self.crossattention = MidmAttention(config, is_cross_attention=True)
|
348 |
+
self.ln_cross_attn = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
|
349 |
+
|
350 |
+
self.mlp = MidmMLP(inner_dim, config)
|
351 |
+
|
352 |
+
def forward(
|
353 |
+
self,
|
354 |
+
hidden_states,
|
355 |
+
layer_past=None,
|
356 |
+
attention_mask=None,
|
357 |
+
head_mask=None,
|
358 |
+
encoder_hidden_states=None,
|
359 |
+
encoder_attention_mask=None,
|
360 |
+
use_cache=False,
|
361 |
+
output_attentions=False,
|
362 |
+
rotary_pos_emb=None,
|
363 |
+
):
|
364 |
+
residual = hidden_states
|
365 |
+
if self.use_layernorm1p:
|
366 |
+
hidden_states = layernorm1p(self.ln_1, hidden_states)
|
367 |
+
else:
|
368 |
+
hidden_states = self.ln_1(hidden_states)
|
369 |
+
attn_outputs = self.attn(
|
370 |
+
hidden_states,
|
371 |
+
layer_past=layer_past,
|
372 |
+
attention_mask=attention_mask,
|
373 |
+
head_mask=head_mask,
|
374 |
+
use_cache=use_cache,
|
375 |
+
output_attentions=output_attentions,
|
376 |
+
rotary_pos_emb=rotary_pos_emb,
|
377 |
+
)
|
378 |
+
attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
|
379 |
+
outputs = attn_outputs[1:]
|
380 |
+
# residual connection
|
381 |
+
hidden_states = attn_output + residual
|
382 |
+
|
383 |
+
if encoder_hidden_states is not None:
|
384 |
+
# add one self-attention block for cross-attention
|
385 |
+
if not hasattr(self, "crossattention"):
|
386 |
+
raise ValueError(
|
387 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with "
|
388 |
+
"cross-attention layers by setting `config.add_cross_attention=True`"
|
389 |
+
)
|
390 |
+
residual = hidden_states
|
391 |
+
if self.use_layernorm1p:
|
392 |
+
hidden_states = layernorm1p(self.ln_cross_attn, hidden_states)
|
393 |
+
else:
|
394 |
+
hidden_states = self.ln_cross_attn(hidden_states)
|
395 |
+
cross_attn_outputs = self.crossattention(
|
396 |
+
hidden_states,
|
397 |
+
attention_mask=attention_mask,
|
398 |
+
head_mask=head_mask,
|
399 |
+
encoder_hidden_states=encoder_hidden_states,
|
400 |
+
encoder_attention_mask=encoder_attention_mask,
|
401 |
+
output_attentions=output_attentions,
|
402 |
+
)
|
403 |
+
attn_output = cross_attn_outputs[0]
|
404 |
+
# residual connection
|
405 |
+
hidden_states = residual + attn_output
|
406 |
+
outputs = outputs + cross_attn_outputs[2:] # add cross attentions if we output attention weights
|
407 |
+
|
408 |
+
residual = hidden_states
|
409 |
+
if self.use_layernorm1p:
|
410 |
+
hidden_states = layernorm1p(self.ln_2, hidden_states)
|
411 |
+
else:
|
412 |
+
hidden_states = self.ln_2(hidden_states)
|
413 |
+
feed_forward_hidden_states = self.mlp(hidden_states)
|
414 |
+
# residual connection
|
415 |
+
hidden_states = residual + feed_forward_hidden_states
|
416 |
+
|
417 |
+
if use_cache:
|
418 |
+
outputs = (hidden_states,) + outputs
|
419 |
+
else:
|
420 |
+
outputs = (hidden_states,) + outputs[1:]
|
421 |
+
|
422 |
+
return outputs # hidden_states, present, (attentions, cross_attentions)
|
423 |
+
|
424 |
+
|
425 |
+
class MidmPreTrainedModel(PreTrainedModel):
|
426 |
+
"""
|
427 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
428 |
+
models.
|
429 |
+
"""
|
430 |
+
|
431 |
+
config_class = MidmBitextConfig
|
432 |
+
base_model_prefix = "transformer"
|
433 |
+
is_parallelizable = True
|
434 |
+
supports_gradient_checkpointing = True
|
435 |
+
_no_split_modules = ["MidmBlock"]
|
436 |
+
|
437 |
+
def __init__(self, *inputs, **kwargs):
|
438 |
+
super().__init__(*inputs, **kwargs)
|
439 |
+
|
440 |
+
def _init_weights(self, module):
|
441 |
+
"""Initialize the weights."""
|
442 |
+
if isinstance(module, (nn.Linear, Conv1D)):
|
443 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
444 |
+
if module.bias is not None:
|
445 |
+
module.bias.data.zero_()
|
446 |
+
elif isinstance(module, nn.Embedding):
|
447 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
448 |
+
if module.padding_idx is not None:
|
449 |
+
module.weight.data[module.padding_idx].zero_()
|
450 |
+
elif isinstance(module, nn.LayerNorm):
|
451 |
+
module.bias.data.zero_()
|
452 |
+
module.weight.data.fill_(1.0)
|
453 |
+
|
454 |
+
for name, p in module.named_parameters():
|
455 |
+
if "c_proj" in name and "weight" in name:
|
456 |
+
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
|
457 |
+
p.data.normal_(mean=0.0, std=(self.config.initializer_range / math.sqrt(2 * self.config.n_layer)))
|
458 |
+
|
459 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
460 |
+
if isinstance(module, MidmModel):
|
461 |
+
module.gradient_checkpointing = value
|
462 |
+
|
463 |
+
def make_tensors_contiguous(self):
|
464 |
+
for name, param in self.named_parameters():
|
465 |
+
if not param.is_contiguous():
|
466 |
+
param.data = param.data.contiguous()
|
467 |
+
|
468 |
+
def save_pretrained(self, save_directory, **kwargs):
|
469 |
+
# Make tensors contiguous
|
470 |
+
self.make_tensors_contiguous()
|
471 |
+
|
472 |
+
# Call the original save_pretrained method
|
473 |
+
super().save_pretrained(save_directory, **kwargs)
|
474 |
+
|
475 |
+
@dataclass
|
476 |
+
class MidmDoubleHeadsModelOutput(ModelOutput):
|
477 |
+
loss: Optional[torch.FloatTensor] = None
|
478 |
+
mc_loss: Optional[torch.FloatTensor] = None
|
479 |
+
logits: torch.FloatTensor = None
|
480 |
+
mc_logits: torch.FloatTensor = None
|
481 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
|
482 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
483 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
484 |
+
|
485 |
+
|
486 |
+
MIDM_START_DOCSTRING = r"""
|
487 |
+
|
488 |
+
This model inherits from :class:`~transformers.PreTrainedModel`. Check the superclass documentation for the generic
|
489 |
+
methods the library implements for all its model (such as downloading or saving, resizing the input embeddings,
|
490 |
+
pruning heads etc.)
|
491 |
+
|
492 |
+
This model is also a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`__
|
493 |
+
subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to
|
494 |
+
general usage and behavior.
|
495 |
+
|
496 |
+
Parameters:
|
497 |
+
config (:class:`~transformers.MidmBitextConfig`): Model configuration class with all the parameters of the model.
|
498 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
499 |
+
configuration. Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model
|
500 |
+
weights.
|
501 |
+
"""
|
502 |
+
|
503 |
+
MIDM_INPUTS_DOCSTRING = r"""
|
504 |
+
Args:
|
505 |
+
input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, input_ids_length)`):
|
506 |
+
:obj:`input_ids_length` = ``sequence_length`` if :obj:`past_key_values` is ``None`` else
|
507 |
+
``past_key_values[0][0].shape[-2]`` (``sequence_length`` of input past key value states). Indices of input
|
508 |
+
sequence tokens in the vocabulary.
|
509 |
+
|
510 |
+
If :obj:`past_key_values` is used, only ``input_ids`` that do not have their past calculated should be
|
511 |
+
passed as ``input_ids``.
|
512 |
+
|
513 |
+
Indices can be obtained using :class:`~transformers.Midm_bitext_Tokenizer`. See
|
514 |
+
:meth:`transformers.PreTrainedTokenizer.encode` and :meth:`transformers.PreTrainedTokenizer.__call__` for
|
515 |
+
details.
|
516 |
+
|
517 |
+
`What are input IDs? <../glossary.html#input-ids>`__
|
518 |
+
past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers`):
|
519 |
+
Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
|
520 |
+
:obj:`past_key_values` output below). Can be used to speed up sequential decoding. The ``input_ids`` which
|
521 |
+
have their past given to this model should not be passed as ``input_ids`` as they have already been
|
522 |
+
computed.
|
523 |
+
attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
|
524 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``:
|
525 |
+
|
526 |
+
- 1 for tokens that are **not masked**,
|
527 |
+
- 0 for tokens that are **masked**.
|
528 |
+
|
529 |
+
`What are attention masks? <../glossary.html#attention-mask>`__
|
530 |
+
token_type_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, input_ids_length)`, `optional`):
|
531 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in ``[0,
|
532 |
+
1]``:
|
533 |
+
|
534 |
+
- 0 corresponds to a `sentence A` token,
|
535 |
+
- 1 corresponds to a `sentence B` token.
|
536 |
+
|
537 |
+
`What are token type IDs? <../glossary.html#token-type-ids>`_
|
538 |
+
position_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
|
539 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range ``[0,
|
540 |
+
config.max_position_embeddings - 1]``.
|
541 |
+
|
542 |
+
`What are position IDs? <../glossary.html#position-ids>`_
|
543 |
+
head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`):
|
544 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in ``[0, 1]``:
|
545 |
+
|
546 |
+
- 1 indicates the head is **not masked**,
|
547 |
+
- 0 indicates the head is **masked**.
|
548 |
+
|
549 |
+
inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
|
550 |
+
Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation.
|
551 |
+
This is useful if you want more control over how to convert :obj:`input_ids` indices into associated
|
552 |
+
vectors than the model's internal embedding lookup matrix.
|
553 |
+
|
554 |
+
If :obj:`past_key_values` is used, optionally only the last :obj:`inputs_embeds` have to be input (see
|
555 |
+
:obj:`past_key_values`).
|
556 |
+
use_cache (:obj:`bool`, `optional`):
|
557 |
+
If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
|
558 |
+
decoding (see :obj:`past_key_values`).
|
559 |
+
output_attentions (:obj:`bool`, `optional`):
|
560 |
+
Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under returned
|
561 |
+
tensors for more detail.
|
562 |
+
output_hidden_states (:obj:`bool`, `optional`):
|
563 |
+
Whether or not to return the hidden states of all layers. See ``hidden_states`` under returned tensors for
|
564 |
+
more detail.
|
565 |
+
return_dict (:obj:`bool`, `optional`):
|
566 |
+
Whether or not to return a :class:`~transformers.file_utils.ModelOutput` instead of a plain tuple.
|
567 |
+
"""
|
568 |
+
PARALLELIZE_DOCSTRING = r"""
|
569 |
+
This is an experimental feature and is a subject to change at a moment's notice.
|
570 |
+
|
571 |
+
Uses a device map to distribute attention modules of the model across several devices. If no device map is given,
|
572 |
+
it will evenly distribute blocks across all devices.
|
573 |
+
|
574 |
+
Args:
|
575 |
+
device_map (:obj:`Dict[int, list]`, optional, defaults to None):
|
576 |
+
A dictionary that maps attention modules to devices. Note that the embedding module and LMHead are always
|
577 |
+
automatically mapped to the first device (for esoteric reasons). That means that the first device should
|
578 |
+
have fewer attention modules mapped to it than other devices. For reference, the Midm models have the
|
579 |
+
following number of attention modules:
|
580 |
+
|
581 |
+
- midm-bitext-S: 32
|
582 |
+
|
583 |
+
Example::
|
584 |
+
|
585 |
+
# Here is an example of a device map on a machine with 4 GPUs using midm-bitext-S, which has a total of 48 attention modules:
|
586 |
+
model = MidmLMHeadModel.from_pretrained('midm-bitext-S')
|
587 |
+
device_map = {0: [0, 1, 2, 3, 4, 5, 6, 7, 8],
|
588 |
+
1: [9, 10, 11, 12, 13, 14, 15, 16],
|
589 |
+
2: [17, 18, 19, 20, 21, 22, 23, 24],
|
590 |
+
3: [25, 26, 27, 28, 29, 30, 31, 32]}
|
591 |
+
model.parallelize(device_map)
|
592 |
+
"""
|
593 |
+
DEPARALLELIZE_DOCSTRING = r"""
|
594 |
+
Moves the model to cpu from a model parallel state.
|
595 |
+
|
596 |
+
Example::
|
597 |
+
|
598 |
+
# On a 4 GPU machine with midm-bitext-S:
|
599 |
+
model = MidmLMHeadModel.from_pretrained('midm-bitext-S')
|
600 |
+
device_map = {0: [0, 1, 2, 3, 4, 5, 6, 7, 8],
|
601 |
+
1: [9, 10, 11, 12, 13, 14, 15, 16],
|
602 |
+
2: [17, 18, 19, 20, 21, 22, 23, 24],
|
603 |
+
3: [25, 26, 27, 28, 29, 30, 31, 32]}
|
604 |
+
model.parallelize(device_map) # Splits the model across several devices
|
605 |
+
model.deparallelize() # Put the model back on cpu and cleans memory by calling torch.cuda.empty_cache()
|
606 |
+
"""
|
607 |
+
|
608 |
+
|
609 |
+
@add_start_docstrings(
|
610 |
+
"The bare Midm Model transformer outputting raw hidden-states without any specific head on top.",
|
611 |
+
MIDM_START_DOCSTRING,
|
612 |
+
)
|
613 |
+
class MidmModel(MidmPreTrainedModel):
|
614 |
+
_keys_to_ignore_on_load_missing = ["attn.masked_bias"]
|
615 |
+
|
616 |
+
def __init__(self, config):
|
617 |
+
super().__init__(config)
|
618 |
+
|
619 |
+
self.embed_dim = config.hidden_size
|
620 |
+
|
621 |
+
self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
|
622 |
+
self.use_absolute_position_embedding = config.use_absolute_position_embedding
|
623 |
+
if self.use_absolute_position_embedding:
|
624 |
+
self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim)
|
625 |
+
|
626 |
+
self.use_rotary_position_embedding = config.use_rotary_position_embedding
|
627 |
+
if self.use_rotary_position_embedding:
|
628 |
+
rotary_dim = config.hidden_size // config.num_attention_heads
|
629 |
+
assert 0 < config.rotary_percentage <= 1
|
630 |
+
if config.rotary_percentage < 1:
|
631 |
+
rotary_dim = int(rotary_dim * config.rotary_percentage)
|
632 |
+
self.rotary_pos_emb = RotaryEmbedding(
|
633 |
+
rotary_dim,
|
634 |
+
seq_len_interpolation_factor=None,
|
635 |
+
pretrained_max_position_embeddings=config.max_position_embeddings)
|
636 |
+
|
637 |
+
self.drop = nn.Dropout(config.embd_pdrop)
|
638 |
+
self.h = nn.ModuleList([MidmBlock(config, layer_idx=i) for i in range(config.num_hidden_layers)])
|
639 |
+
self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
|
640 |
+
self.use_layernorm1p = config.normalization_type == 'layernorm1p'
|
641 |
+
|
642 |
+
self.init_weights()
|
643 |
+
|
644 |
+
# Model parallel
|
645 |
+
self.model_parallel = False
|
646 |
+
self.device_map = None
|
647 |
+
self.gradient_checkpointing = False
|
648 |
+
|
649 |
+
@add_start_docstrings(PARALLELIZE_DOCSTRING)
|
650 |
+
def parallelize(self, device_map=None):
|
651 |
+
# Check validity of device_map
|
652 |
+
self.device_map = (
|
653 |
+
get_device_map(len(self.h), range(torch.cuda.device_count())) if device_map is None else device_map
|
654 |
+
)
|
655 |
+
assert_device_map(self.device_map, len(self.h))
|
656 |
+
self.model_parallel = True
|
657 |
+
self.first_device = "cpu" if "cpu" in self.device_map.keys() else "cuda:" + str(min(self.device_map.keys()))
|
658 |
+
self.last_device = "cuda:" + str(max(self.device_map.keys()))
|
659 |
+
self.wte = self.wte.to(self.first_device)
|
660 |
+
if self.use_absolute_position_embedding:
|
661 |
+
self.wpe = self.wpe.to(self.first_device)
|
662 |
+
# Load onto devices
|
663 |
+
for k, v in self.device_map.items():
|
664 |
+
for block in v:
|
665 |
+
cuda_device = "cuda:" + str(k)
|
666 |
+
self.h[block] = self.h[block].to(cuda_device)
|
667 |
+
# ln_f to last
|
668 |
+
self.ln_f = self.ln_f.to(self.last_device)
|
669 |
+
|
670 |
+
@add_start_docstrings(DEPARALLELIZE_DOCSTRING)
|
671 |
+
def deparallelize(self):
|
672 |
+
self.model_parallel = False
|
673 |
+
self.device_map = None
|
674 |
+
self.first_device = "cpu"
|
675 |
+
self.last_device = "cpu"
|
676 |
+
self.wte = self.wte.to("cpu")
|
677 |
+
if self.use_absolute_position_embedding:
|
678 |
+
self.wpe = self.wpe.to("cpu")
|
679 |
+
for index in range(len(self.h)):
|
680 |
+
self.h[index] = self.h[index].to("cpu")
|
681 |
+
self.ln_f = self.ln_f.to("cpu")
|
682 |
+
torch.cuda.empty_cache()
|
683 |
+
|
684 |
+
def get_input_embeddings(self):
|
685 |
+
return self.wte
|
686 |
+
|
687 |
+
def set_input_embeddings(self, new_embeddings):
|
688 |
+
self.wte = new_embeddings
|
689 |
+
|
690 |
+
def _prune_heads(self, heads_to_prune):
|
691 |
+
"""
|
692 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
|
693 |
+
"""
|
694 |
+
for layer, heads in heads_to_prune.items():
|
695 |
+
self.h[layer].attn.prune_heads(heads)
|
696 |
+
|
697 |
+
@add_start_docstrings_to_model_forward(MIDM_INPUTS_DOCSTRING)
|
698 |
+
@add_code_sample_docstrings(
|
699 |
+
processor_class=_TOKENIZER_FOR_DOC,
|
700 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
701 |
+
output_type=BaseModelOutputWithPastAndCrossAttentions,
|
702 |
+
config_class=_CONFIG_FOR_DOC,
|
703 |
+
)
|
704 |
+
def forward(
|
705 |
+
self,
|
706 |
+
input_ids=None,
|
707 |
+
past_key_values=None,
|
708 |
+
attention_mask=None,
|
709 |
+
token_type_ids=None,
|
710 |
+
position_ids=None,
|
711 |
+
head_mask=None,
|
712 |
+
inputs_embeds=None,
|
713 |
+
encoder_hidden_states=None,
|
714 |
+
encoder_attention_mask=None,
|
715 |
+
use_cache=None,
|
716 |
+
output_attentions=None,
|
717 |
+
output_hidden_states=None,
|
718 |
+
return_dict=None,
|
719 |
+
):
|
720 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
721 |
+
output_hidden_states = (
|
722 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
723 |
+
)
|
724 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
725 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
726 |
+
|
727 |
+
if input_ids is not None and inputs_embeds is not None:
|
728 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
729 |
+
elif input_ids is not None:
|
730 |
+
input_shape = input_ids.size()
|
731 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
732 |
+
batch_size = input_ids.shape[0]
|
733 |
+
elif inputs_embeds is not None:
|
734 |
+
input_shape = inputs_embeds.size()[:-1]
|
735 |
+
batch_size = inputs_embeds.shape[0]
|
736 |
+
else:
|
737 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
738 |
+
|
739 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
740 |
+
|
741 |
+
if token_type_ids is not None:
|
742 |
+
token_type_ids = token_type_ids.view(-1, input_shape[-1])
|
743 |
+
if position_ids is not None:
|
744 |
+
position_ids = position_ids.view(-1, input_shape[-1])
|
745 |
+
|
746 |
+
if past_key_values is None:
|
747 |
+
past_length = 0
|
748 |
+
past_key_values = tuple([None] * len(self.h))
|
749 |
+
else:
|
750 |
+
past_length = past_key_values[0][0].size(-2)
|
751 |
+
if position_ids is None:
|
752 |
+
position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
|
753 |
+
position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
|
754 |
+
|
755 |
+
# MidmAttention mask.
|
756 |
+
if attention_mask is not None:
|
757 |
+
if batch_size <= 0:
|
758 |
+
raise ValueError("batch_size has to be defined and > 0")
|
759 |
+
attention_mask = attention_mask.view(batch_size, -1)
|
760 |
+
# We create a 3D attention mask from a 2D tensor mask.
|
761 |
+
# Sizes are [batch_size, 1, 1, to_seq_length]
|
762 |
+
# So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
|
763 |
+
# this attention mask is more simple than the triangular masking of causal attention
|
764 |
+
# used in KT Midm, we just need to prepare the broadcast dimension here.
|
765 |
+
attention_mask = attention_mask[:, None, None, :]
|
766 |
+
|
767 |
+
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
|
768 |
+
# masked positions, this operation will create a tensor which is 0.0 for
|
769 |
+
# positions we want to attend and -10000.0 for masked positions.
|
770 |
+
# Since we are adding it to the raw scores before the softmax, this is
|
771 |
+
# effectively the same as removing these entirely.
|
772 |
+
attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
|
773 |
+
attention_mask = (1.0 - attention_mask) * -10000.0
|
774 |
+
|
775 |
+
# If a 2D or 3D attention mask is provided for the cross-attention
|
776 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
777 |
+
if self.config.add_cross_attention and encoder_hidden_states is not None:
|
778 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
|
779 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
780 |
+
if encoder_attention_mask is None:
|
781 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
782 |
+
encoder_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
783 |
+
else:
|
784 |
+
encoder_attention_mask = None
|
785 |
+
|
786 |
+
rotary_pos_emb = None
|
787 |
+
if self.use_rotary_position_embedding:
|
788 |
+
rotary_pos_emb = self.rotary_pos_emb(past_length + input_shape[-1])
|
789 |
+
|
790 |
+
# Prepare head mask if needed
|
791 |
+
# 1.0 in head_mask indicate we keep the head
|
792 |
+
# attention_probs has shape bsz x n_heads x N x N
|
793 |
+
# head_mask has shape n_layer x batch x n_heads x N x N
|
794 |
+
head_mask = self.get_head_mask(head_mask, self.config.n_layer)
|
795 |
+
|
796 |
+
if inputs_embeds is None:
|
797 |
+
inputs_embeds = self.wte(input_ids)
|
798 |
+
if self.use_absolute_position_embedding:
|
799 |
+
position_embeds = self.wpe(position_ids)
|
800 |
+
hidden_states = inputs_embeds + position_embeds
|
801 |
+
else:
|
802 |
+
hidden_states = inputs_embeds
|
803 |
+
|
804 |
+
if token_type_ids is not None:
|
805 |
+
token_type_embeds = self.wte(token_type_ids)
|
806 |
+
hidden_states = hidden_states + token_type_embeds
|
807 |
+
|
808 |
+
hidden_states = self.drop(hidden_states)
|
809 |
+
|
810 |
+
output_shape = input_shape + (hidden_states.size(-1),)
|
811 |
+
|
812 |
+
presents = () if use_cache else None
|
813 |
+
all_self_attentions = () if output_attentions else None
|
814 |
+
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
|
815 |
+
all_hidden_states = () if output_hidden_states else None
|
816 |
+
for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
|
817 |
+
|
818 |
+
# Model parallel
|
819 |
+
if self.model_parallel:
|
820 |
+
torch.cuda.set_device(hidden_states.device)
|
821 |
+
# Ensure layer_past is on same device as hidden_states (might not be correct)
|
822 |
+
if layer_past is not None:
|
823 |
+
layer_past = tuple(past_state.to(hidden_states.device) for past_state in layer_past)
|
824 |
+
# Ensure that attention_mask is always on the same device as hidden_states
|
825 |
+
if attention_mask is not None:
|
826 |
+
attention_mask = attention_mask.to(hidden_states.device)
|
827 |
+
if isinstance(head_mask, torch.Tensor):
|
828 |
+
head_mask = head_mask.to(hidden_states.device)
|
829 |
+
if output_hidden_states:
|
830 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
831 |
+
|
832 |
+
if self.gradient_checkpointing and self.training:
|
833 |
+
|
834 |
+
if use_cache:
|
835 |
+
logger.warning(
|
836 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
837 |
+
)
|
838 |
+
use_cache = False
|
839 |
+
|
840 |
+
def create_custom_forward(module):
|
841 |
+
def custom_forward(*inputs):
|
842 |
+
# None for past_key_value
|
843 |
+
return module(*inputs, use_cache, output_attentions)
|
844 |
+
|
845 |
+
return custom_forward
|
846 |
+
|
847 |
+
outputs = torch.utils.checkpoint.checkpoint(
|
848 |
+
create_custom_forward(block),
|
849 |
+
hidden_states,
|
850 |
+
None,
|
851 |
+
attention_mask,
|
852 |
+
head_mask[i],
|
853 |
+
encoder_hidden_states,
|
854 |
+
encoder_attention_mask,
|
855 |
+
rotary_pos_emb=rotary_pos_emb,
|
856 |
+
)
|
857 |
+
else:
|
858 |
+
outputs = block(
|
859 |
+
hidden_states,
|
860 |
+
layer_past=layer_past,
|
861 |
+
attention_mask=attention_mask,
|
862 |
+
head_mask=head_mask[i],
|
863 |
+
encoder_hidden_states=encoder_hidden_states,
|
864 |
+
encoder_attention_mask=encoder_attention_mask,
|
865 |
+
use_cache=use_cache,
|
866 |
+
output_attentions=output_attentions,
|
867 |
+
rotary_pos_emb=rotary_pos_emb,
|
868 |
+
)
|
869 |
+
|
870 |
+
hidden_states = outputs[0]
|
871 |
+
if use_cache is True:
|
872 |
+
presents = presents + (outputs[1],)
|
873 |
+
|
874 |
+
if output_attentions:
|
875 |
+
all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
|
876 |
+
if self.config.add_cross_attention:
|
877 |
+
all_cross_attentions = all_cross_attentions + (outputs[3 if use_cache else 2],)
|
878 |
+
|
879 |
+
# Model Parallel: If it's the last layer for that device, put things on the next device
|
880 |
+
if self.model_parallel:
|
881 |
+
for k, v in self.device_map.items():
|
882 |
+
if i == v[-1] and "cuda:" + str(k) != self.last_device:
|
883 |
+
hidden_states = hidden_states.to("cuda:" + str(k + 1))
|
884 |
+
|
885 |
+
if self.use_layernorm1p:
|
886 |
+
hidden_states = layernorm1p(self.ln_f, hidden_states)
|
887 |
+
else:
|
888 |
+
hidden_states = self.ln_f(hidden_states)
|
889 |
+
|
890 |
+
hidden_states = hidden_states.view(*output_shape)
|
891 |
+
# Add last hidden state
|
892 |
+
if output_hidden_states:
|
893 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
894 |
+
|
895 |
+
if not return_dict:
|
896 |
+
return tuple(
|
897 |
+
v
|
898 |
+
for v in [hidden_states, presents, all_hidden_states, all_self_attentions, all_cross_attentions]
|
899 |
+
if v is not None
|
900 |
+
)
|
901 |
+
|
902 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
903 |
+
last_hidden_state=hidden_states,
|
904 |
+
past_key_values=presents,
|
905 |
+
hidden_states=all_hidden_states,
|
906 |
+
attentions=all_self_attentions,
|
907 |
+
cross_attentions=all_cross_attentions,
|
908 |
+
)
|
909 |
+
|
910 |
+
|
911 |
+
@add_start_docstrings(
|
912 |
+
"""
|
913 |
+
The Midm Model transformer with a language modeling head on top (linear layer with weights tied to the input
|
914 |
+
embeddings).
|
915 |
+
""",
|
916 |
+
MIDM_START_DOCSTRING,
|
917 |
+
)
|
918 |
+
class MidmLMHeadModel(MidmPreTrainedModel):
|
919 |
+
_keys_to_ignore_on_load_missing = [r"attn.masked_bias", r"attn.bias", r"lm_head.weight"]
|
920 |
+
|
921 |
+
def __init__(self, config):
|
922 |
+
super().__init__(config)
|
923 |
+
self.transformer = MidmModel(config)
|
924 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
925 |
+
|
926 |
+
self.init_weights()
|
927 |
+
|
928 |
+
# Model parallel
|
929 |
+
self.model_parallel = False
|
930 |
+
self.device_map = None
|
931 |
+
|
932 |
+
@add_start_docstrings(PARALLELIZE_DOCSTRING)
|
933 |
+
def parallelize(self, device_map=None):
|
934 |
+
self.device_map = (
|
935 |
+
get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
|
936 |
+
if device_map is None
|
937 |
+
else device_map
|
938 |
+
)
|
939 |
+
assert_device_map(self.device_map, len(self.transformer.h))
|
940 |
+
self.transformer.parallelize(self.device_map)
|
941 |
+
self.lm_head = self.lm_head.to(self.transformer.first_device)
|
942 |
+
self.model_parallel = True
|
943 |
+
|
944 |
+
@add_start_docstrings(DEPARALLELIZE_DOCSTRING)
|
945 |
+
def deparallelize(self):
|
946 |
+
self.transformer.deparallelize()
|
947 |
+
self.transformer = self.transformer.to("cpu")
|
948 |
+
self.lm_head = self.lm_head.to("cpu")
|
949 |
+
self.model_parallel = False
|
950 |
+
torch.cuda.empty_cache()
|
951 |
+
|
952 |
+
def get_output_embeddings(self):
|
953 |
+
return self.lm_head
|
954 |
+
|
955 |
+
def set_output_embeddings(self, new_embeddings):
|
956 |
+
self.lm_head = new_embeddings
|
957 |
+
|
958 |
+
def prepare_inputs_for_generation(self, input_ids, past=None, **kwargs):
|
959 |
+
token_type_ids = kwargs.get("token_type_ids", None)
|
960 |
+
# only last token for inputs_ids if past is defined in kwargs
|
961 |
+
if past:
|
962 |
+
input_ids = input_ids[:, -1].unsqueeze(-1)
|
963 |
+
if token_type_ids is not None:
|
964 |
+
token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
|
965 |
+
|
966 |
+
attention_mask = kwargs.get("attention_mask", None)
|
967 |
+
position_ids = kwargs.get("position_ids", None)
|
968 |
+
|
969 |
+
if attention_mask is not None and position_ids is None:
|
970 |
+
# create position_ids on the fly for batch generation
|
971 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
972 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
973 |
+
if past:
|
974 |
+
position_ids = position_ids[:, -1].unsqueeze(-1)
|
975 |
+
else:
|
976 |
+
position_ids = None
|
977 |
+
return {
|
978 |
+
"input_ids": input_ids,
|
979 |
+
"past_key_values": past,
|
980 |
+
"use_cache": kwargs.get("use_cache"),
|
981 |
+
"position_ids": position_ids,
|
982 |
+
"attention_mask": attention_mask,
|
983 |
+
"token_type_ids": token_type_ids,
|
984 |
+
}
|
985 |
+
|
986 |
+
@add_start_docstrings_to_model_forward(MIDM_INPUTS_DOCSTRING)
|
987 |
+
@add_code_sample_docstrings(
|
988 |
+
processor_class=_TOKENIZER_FOR_DOC,
|
989 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
990 |
+
output_type=CausalLMOutputWithCrossAttentions,
|
991 |
+
config_class=_CONFIG_FOR_DOC,
|
992 |
+
)
|
993 |
+
def forward(
|
994 |
+
self,
|
995 |
+
input_ids=None,
|
996 |
+
past_key_values=None,
|
997 |
+
attention_mask=None,
|
998 |
+
token_type_ids=None,
|
999 |
+
position_ids=None,
|
1000 |
+
head_mask=None,
|
1001 |
+
inputs_embeds=None,
|
1002 |
+
encoder_hidden_states=None,
|
1003 |
+
encoder_attention_mask=None,
|
1004 |
+
labels=None,
|
1005 |
+
use_cache=None,
|
1006 |
+
output_attentions=None,
|
1007 |
+
output_hidden_states=None,
|
1008 |
+
return_dict=None,
|
1009 |
+
):
|
1010 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1011 |
+
|
1012 |
+
transformer_outputs = self.transformer(
|
1013 |
+
input_ids,
|
1014 |
+
past_key_values=past_key_values,
|
1015 |
+
attention_mask=attention_mask,
|
1016 |
+
token_type_ids=token_type_ids,
|
1017 |
+
position_ids=position_ids,
|
1018 |
+
head_mask=head_mask,
|
1019 |
+
inputs_embeds=inputs_embeds,
|
1020 |
+
encoder_hidden_states=encoder_hidden_states,
|
1021 |
+
encoder_attention_mask=encoder_attention_mask,
|
1022 |
+
use_cache=use_cache,
|
1023 |
+
output_attentions=output_attentions,
|
1024 |
+
output_hidden_states=output_hidden_states,
|
1025 |
+
return_dict=return_dict,
|
1026 |
+
)
|
1027 |
+
hidden_states = transformer_outputs[0]
|
1028 |
+
|
1029 |
+
# Set device for model parallelism
|
1030 |
+
if self.model_parallel:
|
1031 |
+
torch.cuda.set_device(self.transformer.first_device)
|
1032 |
+
hidden_states = hidden_states.to(self.lm_head.weight.device)
|
1033 |
+
|
1034 |
+
lm_logits = self.lm_head(hidden_states)
|
1035 |
+
|
1036 |
+
loss = None
|
1037 |
+
if labels is not None:
|
1038 |
+
# Shift so that tokens < n predict n
|
1039 |
+
shift_logits = lm_logits[..., :-1, :].contiguous()
|
1040 |
+
shift_labels = labels[..., 1:].contiguous()
|
1041 |
+
# Flatten the tokens
|
1042 |
+
loss_fct = CrossEntropyLoss()
|
1043 |
+
loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
|
1044 |
+
|
1045 |
+
if not return_dict:
|
1046 |
+
output = (lm_logits,) + transformer_outputs[1:]
|
1047 |
+
return ((loss,) + output) if loss is not None else output
|
1048 |
+
|
1049 |
+
return CausalLMOutputWithCrossAttentions(
|
1050 |
+
loss=loss,
|
1051 |
+
logits=lm_logits,
|
1052 |
+
past_key_values=transformer_outputs.past_key_values,
|
1053 |
+
hidden_states=transformer_outputs.hidden_states,
|
1054 |
+
attentions=transformer_outputs.attentions,
|
1055 |
+
cross_attentions=transformer_outputs.cross_attentions,
|
1056 |
+
)
|
1057 |
+
|
1058 |
+
@staticmethod
|
1059 |
+
def _reorder_cache(past: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor) -> Tuple[Tuple[torch.Tensor]]:
|
1060 |
+
"""
|
1061 |
+
This function is used to re-order the :obj:`past_key_values` cache if
|
1062 |
+
:meth:`~transformers.PreTrainedModel.beam_search` or :meth:`~transformers.PreTrainedModel.beam_sample` is
|
1063 |
+
called. This is required to match :obj:`past_key_values` with the correct beam_idx at every generation step.
|
1064 |
+
"""
|
1065 |
+
return tuple(
|
1066 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
|
1067 |
+
for layer_past in past
|
1068 |
+
)
|
1069 |
+
|
1070 |
+
|
1071 |
+
@add_start_docstrings(
|
1072 |
+
"""
|
1073 |
+
The Midm Model transformer with a language modeling and a multiple-choice classification head on top e.g. for
|
1074 |
+
RocStories/SWAG tasks. The two heads are two linear layers. The language modeling head has its weights tied to the
|
1075 |
+
input embeddings, the classification head takes as input the input of a specified classification token index in the
|
1076 |
+
input sequence).
|
1077 |
+
""",
|
1078 |
+
MIDM_START_DOCSTRING,
|
1079 |
+
)
|
1080 |
+
class MidmDoubleHeadsModel(MidmPreTrainedModel):
|
1081 |
+
_keys_to_ignore_on_load_missing = [r"attn.masked_bias", r"attn.bias", r"lm_head.weight"]
|
1082 |
+
|
1083 |
+
def __init__(self, config):
|
1084 |
+
super().__init__(config)
|
1085 |
+
config.num_labels = 1
|
1086 |
+
self.transformer = MidmModel(config)
|
1087 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
1088 |
+
self.multiple_choice_head = SequenceSummary(config)
|
1089 |
+
|
1090 |
+
self.init_weights()
|
1091 |
+
|
1092 |
+
# Model parallel
|
1093 |
+
self.model_parallel = False
|
1094 |
+
self.device_map = None
|
1095 |
+
|
1096 |
+
@add_start_docstrings(PARALLELIZE_DOCSTRING)
|
1097 |
+
def parallelize(self, device_map=None):
|
1098 |
+
self.device_map = (
|
1099 |
+
get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
|
1100 |
+
if device_map is None
|
1101 |
+
else device_map
|
1102 |
+
)
|
1103 |
+
assert_device_map(self.device_map, len(self.transformer.h))
|
1104 |
+
self.transformer.parallelize(self.device_map)
|
1105 |
+
self.lm_head = self.lm_head.to(self.transformer.first_device)
|
1106 |
+
self.multiple_choice_head = self.multiple_choice_head.to(self.transformer.first_device)
|
1107 |
+
self.model_parallel = True
|
1108 |
+
|
1109 |
+
@add_start_docstrings(DEPARALLELIZE_DOCSTRING)
|
1110 |
+
def deparallelize(self):
|
1111 |
+
self.transformer.deparallelize()
|
1112 |
+
self.transformer = self.transformer.to("cpu")
|
1113 |
+
self.lm_head = self.lm_head.to("cpu")
|
1114 |
+
self.multiple_choice_head = self.multiple_choice_head.to("cpu")
|
1115 |
+
self.model_parallel = False
|
1116 |
+
torch.cuda.empty_cache()
|
1117 |
+
|
1118 |
+
def get_output_embeddings(self):
|
1119 |
+
return self.lm_head
|
1120 |
+
|
1121 |
+
def set_output_embeddings(self, new_embeddings):
|
1122 |
+
self.lm_head = new_embeddings
|
1123 |
+
|
1124 |
+
def prepare_inputs_for_generation(self, input_ids, past=None, **kwargs):
|
1125 |
+
token_type_ids = kwargs.get("token_type_ids", None)
|
1126 |
+
# only last token for inputs_ids if past is defined in kwargs
|
1127 |
+
if past:
|
1128 |
+
input_ids = input_ids[:, -1].unsqueeze(-1)
|
1129 |
+
if token_type_ids is not None:
|
1130 |
+
token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
|
1131 |
+
|
1132 |
+
attention_mask = kwargs.get("attention_mask", None)
|
1133 |
+
position_ids = kwargs.get("position_ids", None)
|
1134 |
+
|
1135 |
+
if attention_mask is not None and position_ids is None:
|
1136 |
+
# create position_ids on the fly for batch generation
|
1137 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1138 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1139 |
+
if past:
|
1140 |
+
position_ids = position_ids[:, -1].unsqueeze(-1)
|
1141 |
+
else:
|
1142 |
+
position_ids = None
|
1143 |
+
|
1144 |
+
return {
|
1145 |
+
"input_ids": input_ids,
|
1146 |
+
"past_key_values": past,
|
1147 |
+
"use_cache": kwargs.get("use_cache"),
|
1148 |
+
"position_ids": position_ids,
|
1149 |
+
"attention_mask": attention_mask,
|
1150 |
+
"token_type_ids": token_type_ids,
|
1151 |
+
}
|
1152 |
+
|
1153 |
+
@add_start_docstrings_to_model_forward(MIDM_INPUTS_DOCSTRING)
|
1154 |
+
def forward(
|
1155 |
+
self,
|
1156 |
+
input_ids=None,
|
1157 |
+
past_key_values=None,
|
1158 |
+
attention_mask=None,
|
1159 |
+
token_type_ids=None,
|
1160 |
+
position_ids=None,
|
1161 |
+
head_mask=None,
|
1162 |
+
inputs_embeds=None,
|
1163 |
+
mc_token_ids=None,
|
1164 |
+
labels=None,
|
1165 |
+
mc_labels=None,
|
1166 |
+
use_cache=None,
|
1167 |
+
output_attentions=None,
|
1168 |
+
output_hidden_states=None,
|
1169 |
+
return_dict=None,
|
1170 |
+
**kwargs,
|
1171 |
+
):
|
1172 |
+
|
1173 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1174 |
+
|
1175 |
+
transformer_outputs = self.transformer(
|
1176 |
+
input_ids,
|
1177 |
+
past_key_values=past_key_values,
|
1178 |
+
attention_mask=attention_mask,
|
1179 |
+
token_type_ids=token_type_ids,
|
1180 |
+
position_ids=position_ids,
|
1181 |
+
head_mask=head_mask,
|
1182 |
+
inputs_embeds=inputs_embeds,
|
1183 |
+
use_cache=use_cache,
|
1184 |
+
output_attentions=output_attentions,
|
1185 |
+
output_hidden_states=output_hidden_states,
|
1186 |
+
return_dict=return_dict,
|
1187 |
+
)
|
1188 |
+
|
1189 |
+
hidden_states = transformer_outputs[0]
|
1190 |
+
|
1191 |
+
# Set device for model parallelism
|
1192 |
+
if self.model_parallel:
|
1193 |
+
torch.cuda.set_device(self.transformer.first_device)
|
1194 |
+
hidden_states = hidden_states.to(self.lm_head.weight.device)
|
1195 |
+
|
1196 |
+
lm_logits = self.lm_head(hidden_states)
|
1197 |
+
mc_logits = self.multiple_choice_head(hidden_states, mc_token_ids).squeeze(-1)
|
1198 |
+
|
1199 |
+
mc_loss = None
|
1200 |
+
if mc_labels is not None:
|
1201 |
+
loss_fct = CrossEntropyLoss()
|
1202 |
+
mc_loss = loss_fct(mc_logits.view(-1, mc_logits.size(-1)), mc_labels.view(-1))
|
1203 |
+
lm_loss = None
|
1204 |
+
if labels is not None:
|
1205 |
+
shift_logits = lm_logits[..., :-1, :].contiguous()
|
1206 |
+
shift_labels = labels[..., 1:].contiguous()
|
1207 |
+
loss_fct = CrossEntropyLoss()
|
1208 |
+
lm_loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
|
1209 |
+
|
1210 |
+
if not return_dict:
|
1211 |
+
output = (lm_logits, mc_logits) + transformer_outputs[1:]
|
1212 |
+
if mc_loss is not None:
|
1213 |
+
output = (mc_loss,) + output
|
1214 |
+
return ((lm_loss,) + output) if lm_loss is not None else output
|
1215 |
+
|
1216 |
+
return MidmDoubleHeadsModelOutput(
|
1217 |
+
loss=lm_loss,
|
1218 |
+
mc_loss=mc_loss,
|
1219 |
+
logits=lm_logits,
|
1220 |
+
mc_logits=mc_logits,
|
1221 |
+
past_key_values=transformer_outputs.past_key_values,
|
1222 |
+
hidden_states=transformer_outputs.hidden_states,
|
1223 |
+
attentions=transformer_outputs.attentions,
|
1224 |
+
)
|
1225 |
+
|
1226 |
+
@staticmethod
|
1227 |
+
def _reorder_cache(past: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor) -> Tuple[Tuple[torch.Tensor]]:
|
1228 |
+
return tuple(
|
1229 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
|
1230 |
+
for layer_past in past
|
1231 |
+
)
|
1232 |
+
|
1233 |
+
|
1234 |
+
@add_start_docstrings(
|
1235 |
+
"""
|
1236 |
+
The Midm Model transformer with a sequence classification head on top (linear layer).
|
1237 |
+
|
1238 |
+
:class:`~transformers.MidmForSequenceClassification` uses the last token in order to do the classification, as
|
1239 |
+
other causal models do.
|
1240 |
+
|
1241 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
1242 |
+
:obj:`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each
|
1243 |
+
row. If no :obj:`pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot
|
1244 |
+
guess the padding tokens when :obj:`inputs_embeds` are passed instead of :obj:`input_ids`, it does the same (take
|
1245 |
+
the last value in each row of the batch).
|
1246 |
+
""",
|
1247 |
+
MIDM_START_DOCSTRING,
|
1248 |
+
)
|
1249 |
+
class MidmForSequenceClassification(MidmPreTrainedModel):
|
1250 |
+
_keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"lm_head\.weight"]
|
1251 |
+
|
1252 |
+
def __init__(self, config):
|
1253 |
+
super().__init__(config)
|
1254 |
+
self.num_labels = config.num_labels
|
1255 |
+
self.transformer = MidmModel(config)
|
1256 |
+
self.score = nn.Linear(config.n_embd, self.num_labels, bias=False)
|
1257 |
+
|
1258 |
+
self.init_weights()
|
1259 |
+
|
1260 |
+
# Model parallel
|
1261 |
+
self.model_parallel = False
|
1262 |
+
self.device_map = None
|
1263 |
+
|
1264 |
+
@add_start_docstrings_to_model_forward(MIDM_INPUTS_DOCSTRING)
|
1265 |
+
def forward(
|
1266 |
+
self,
|
1267 |
+
input_ids=None,
|
1268 |
+
past_key_values=None,
|
1269 |
+
attention_mask=None,
|
1270 |
+
token_type_ids=None,
|
1271 |
+
position_ids=None,
|
1272 |
+
head_mask=None,
|
1273 |
+
inputs_embeds=None,
|
1274 |
+
labels=None,
|
1275 |
+
use_cache=None,
|
1276 |
+
output_attentions=None,
|
1277 |
+
output_hidden_states=None,
|
1278 |
+
return_dict=None,
|
1279 |
+
):
|
1280 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1281 |
+
|
1282 |
+
transformer_outputs = self.transformer(
|
1283 |
+
input_ids,
|
1284 |
+
past_key_values=past_key_values,
|
1285 |
+
attention_mask=attention_mask,
|
1286 |
+
token_type_ids=token_type_ids,
|
1287 |
+
position_ids=position_ids,
|
1288 |
+
head_mask=head_mask,
|
1289 |
+
inputs_embeds=inputs_embeds,
|
1290 |
+
use_cache=use_cache,
|
1291 |
+
output_attentions=output_attentions,
|
1292 |
+
output_hidden_states=output_hidden_states,
|
1293 |
+
return_dict=return_dict,
|
1294 |
+
)
|
1295 |
+
hidden_states = transformer_outputs[0]
|
1296 |
+
logits = self.score(hidden_states)
|
1297 |
+
|
1298 |
+
if input_ids is not None:
|
1299 |
+
batch_size, sequence_length = input_ids.shape[:2]
|
1300 |
+
else:
|
1301 |
+
batch_size, sequence_length = inputs_embeds.shape[:2]
|
1302 |
+
|
1303 |
+
assert (
|
1304 |
+
self.config.pad_token_id is not None or batch_size == 1
|
1305 |
+
), "Cannot handle batch sizes > 1 if no padding token is defined."
|
1306 |
+
if self.config.pad_token_id is None:
|
1307 |
+
sequence_lengths = -1
|
1308 |
+
else:
|
1309 |
+
if input_ids is not None:
|
1310 |
+
sequence_lengths = torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1
|
1311 |
+
else:
|
1312 |
+
sequence_lengths = -1
|
1313 |
+
logger.warning(
|
1314 |
+
f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
|
1315 |
+
f"unexpected if using padding tokens in conjunction with `inputs_embeds.`"
|
1316 |
+
)
|
1317 |
+
|
1318 |
+
pooled_logits = logits[range(batch_size), sequence_lengths]
|
1319 |
+
|
1320 |
+
loss = None
|
1321 |
+
if labels is not None:
|
1322 |
+
if self.num_labels == 1:
|
1323 |
+
# We are doing regression
|
1324 |
+
loss_fct = MSELoss()
|
1325 |
+
loss = loss_fct(pooled_logits.view(-1), labels.to(self.dtype).view(-1))
|
1326 |
+
else:
|
1327 |
+
loss_fct = CrossEntropyLoss()
|
1328 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
1329 |
+
|
1330 |
+
if not return_dict:
|
1331 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
1332 |
+
return ((loss,) + output) if loss is not None else output
|
1333 |
+
|
1334 |
+
return SequenceClassifierOutputWithPast(
|
1335 |
+
loss=loss,
|
1336 |
+
logits=pooled_logits,
|
1337 |
+
past_key_values=transformer_outputs.past_key_values,
|
1338 |
+
hidden_states=transformer_outputs.hidden_states,
|
1339 |
+
attentions=transformer_outputs.attentions,
|
1340 |
+
)
|
1341 |
+
|
1342 |
+
|
1343 |
+
@add_start_docstrings(
|
1344 |
+
"""
|
1345 |
+
Midm Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
|
1346 |
+
Named-Entity-Recognition (NER) tasks.
|
1347 |
+
""",
|
1348 |
+
MIDM_START_DOCSTRING,
|
1349 |
+
)
|
1350 |
+
class MidmForTokenClassification(MidmPreTrainedModel):
|
1351 |
+
def __init__(self, config):
|
1352 |
+
super().__init__(config)
|
1353 |
+
self.num_labels = config.num_labels
|
1354 |
+
|
1355 |
+
self.transformer = MidmModel(config)
|
1356 |
+
if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
|
1357 |
+
classifier_dropout = config.classifier_dropout
|
1358 |
+
elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
|
1359 |
+
classifier_dropout = config.hidden_dropout
|
1360 |
+
else:
|
1361 |
+
classifier_dropout = 0.1
|
1362 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
1363 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
1364 |
+
|
1365 |
+
self.init_weights()
|
1366 |
+
|
1367 |
+
# Model parallel
|
1368 |
+
self.model_parallel = False
|
1369 |
+
self.device_map = None
|
1370 |
+
|
1371 |
+
@add_start_docstrings_to_model_forward(MIDM_INPUTS_DOCSTRING)
|
1372 |
+
def forward(
|
1373 |
+
self,
|
1374 |
+
input_ids=None,
|
1375 |
+
past_key_values=None,
|
1376 |
+
attention_mask=None,
|
1377 |
+
token_type_ids=None,
|
1378 |
+
position_ids=None,
|
1379 |
+
head_mask=None,
|
1380 |
+
inputs_embeds=None,
|
1381 |
+
labels=None,
|
1382 |
+
use_cache=None,
|
1383 |
+
output_attentions=None,
|
1384 |
+
output_hidden_states=None,
|
1385 |
+
return_dict=None,
|
1386 |
+
):
|
1387 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1388 |
+
|
1389 |
+
transformer_outputs = self.transformer(
|
1390 |
+
input_ids,
|
1391 |
+
past_key_values=past_key_values,
|
1392 |
+
attention_mask=attention_mask,
|
1393 |
+
token_type_ids=token_type_ids,
|
1394 |
+
position_ids=position_ids,
|
1395 |
+
head_mask=head_mask,
|
1396 |
+
inputs_embeds=inputs_embeds,
|
1397 |
+
use_cache=use_cache,
|
1398 |
+
output_attentions=output_attentions,
|
1399 |
+
output_hidden_states=output_hidden_states,
|
1400 |
+
return_dict=return_dict,
|
1401 |
+
)
|
1402 |
+
|
1403 |
+
hidden_states = transformer_outputs[0]
|
1404 |
+
hidden_states = self.dropout(hidden_states)
|
1405 |
+
logits = self.classifier(hidden_states)
|
1406 |
+
|
1407 |
+
loss = None
|
1408 |
+
if labels is not None:
|
1409 |
+
loss_fct = CrossEntropyLoss()
|
1410 |
+
# Only keep active parts of the loss
|
1411 |
+
if attention_mask is not None:
|
1412 |
+
active_loss = attention_mask.view(-1) == 1
|
1413 |
+
active_logits = logits.view(-1, self.num_labels)
|
1414 |
+
active_labels = torch.where(
|
1415 |
+
active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels)
|
1416 |
+
)
|
1417 |
+
loss = loss_fct(active_logits, active_labels)
|
1418 |
+
else:
|
1419 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
1420 |
+
|
1421 |
+
if not return_dict:
|
1422 |
+
output = (logits,) + transformer_outputs[2:]
|
1423 |
+
return ((loss,) + output) if loss is not None else output
|
1424 |
+
|
1425 |
+
return TokenClassifierOutput(
|
1426 |
+
loss=loss,
|
1427 |
+
logits=logits,
|
1428 |
+
hidden_states=transformer_outputs.hidden_states,
|
1429 |
+
attentions=transformer_outputs.attentions,
|
1430 |
+
)
|
1431 |
+
|
1432 |
+
def get_submodule(module, target: str) -> "Module":
|
1433 |
+
if target == "":
|
1434 |
+
return module
|
1435 |
+
|
1436 |
+
atoms: List[str] = target.split(".")
|
1437 |
+
mod: torch.nn.Module = module
|
1438 |
+
|
1439 |
+
for item in atoms:
|
1440 |
+
|
1441 |
+
if not hasattr(mod, item):
|
1442 |
+
raise AttributeError(mod._get_name() + " has no "
|
1443 |
+
"attribute `" + item + "`")
|
1444 |
+
|
1445 |
+
mod = getattr(mod, item)
|
1446 |
+
|
1447 |
+
if not isinstance(mod, torch.nn.Module):
|
1448 |
+
raise AttributeError("`" + item + "` is not "
|
1449 |
+
"an nn.Module")
|
1450 |
+
|
1451 |
+
return mod
|
1452 |
+
|
1453 |
+
|
1454 |
+
def get_parameter(module, target: str) -> "Parameter":
|
1455 |
+
module_path, _, param_name = target.rpartition(".")
|
1456 |
+
|
1457 |
+
mod: torch.nn.Module = get_submodule(module, module_path)
|
1458 |
+
|
1459 |
+
if not hasattr(mod, param_name):
|
1460 |
+
raise AttributeError(mod._get_name() + " has no attribute `"
|
1461 |
+
+ param_name + "`")
|
1462 |
+
|
1463 |
+
param: torch.nn.Parameter = getattr(mod, param_name)
|
1464 |
+
|
1465 |
+
if not isinstance(param, torch.nn.Parameter):
|
1466 |
+
raise AttributeError("`" + param_name + "` is not an "
|
1467 |
+
"nn.Parameter")
|
1468 |
+
|
1469 |
+
return param
|
rotary_position_embedding.py
ADDED
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
|
16 |
+
import torch
|
17 |
+
from einops import rearrange
|
18 |
+
from torch import einsum, nn
|
19 |
+
|
20 |
+
__all__ = ['RotaryEmbedding', 'apply_rotary_pos_emb']
|
21 |
+
|
22 |
+
|
23 |
+
class RotaryEmbedding(nn.Module):
|
24 |
+
"""
|
25 |
+
Implements Rotary Position Embedding from https://arxiv.org/abs/2104.09864.
|
26 |
+
"""
|
27 |
+
|
28 |
+
def __init__(
|
29 |
+
self, dim: int, seq_len_interpolation_factor: int = None, pretrained_max_position_embeddings: int = None
|
30 |
+
):
|
31 |
+
"""
|
32 |
+
Args:
|
33 |
+
|
34 |
+
dim (int): rotary embedding dimension
|
35 |
+
seq_len_interpolation_factor (int): if not None, discrete positions will be interpolated
|
36 |
+
by this factor via the trick in https://arxiv.org/abs/2306.15595.
|
37 |
+
pretrained_max_position_embeddings (int): pre-trained max_position_embeddings before position interpolation.
|
38 |
+
"""
|
39 |
+
super().__init__()
|
40 |
+
self.seq_len_interpolation_factor = seq_len_interpolation_factor
|
41 |
+
inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2).float() / dim))
|
42 |
+
self.register_buffer('inv_freq', inv_freq)
|
43 |
+
self.pretrained_max_position_embeddings = pretrained_max_position_embeddings
|
44 |
+
|
45 |
+
def forward(self, max_seq_len, offset=0):
|
46 |
+
seq = torch.arange(max_seq_len, device=self.inv_freq.device) + offset
|
47 |
+
seq = seq.type_as(self.inv_freq)
|
48 |
+
|
49 |
+
if self.pretrained_max_position_embeddings is not None and self.seq_len_interpolation_factor is not None:
|
50 |
+
if max_seq_len > self.pretrained_max_position_embeddings * self.seq_len_interpolation_factor:
|
51 |
+
# dynamic linear scaling (length > position we have learned)
|
52 |
+
seq *= 1 / (max_seq_len / self.pretrained_max_position_embeddings)
|
53 |
+
else:
|
54 |
+
# fixed linear scaling
|
55 |
+
seq *= 1 / self.seq_len_interpolation_factor
|
56 |
+
|
57 |
+
freqs = einsum('i , j -> i j', seq, self.inv_freq)
|
58 |
+
# first part even vector components, second part odd vector components,
|
59 |
+
# 2 * dim in dimension size
|
60 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
61 |
+
# emb [seq_length, .., dim]
|
62 |
+
return rearrange(emb, 'n d -> n 1 1 d')
|
63 |
+
|
64 |
+
|
65 |
+
def _rotate_half(x):
|
66 |
+
"""
|
67 |
+
change sign so the last dimension
|
68 |
+
[A, B, C, D] -> [-C, -D, A, B]
|
69 |
+
"""
|
70 |
+
x = rearrange(x, '... (j d) -> ... j d', j=2)
|
71 |
+
x1, x2 = x.unbind(dim=-2)
|
72 |
+
return torch.cat((-x2, x1), dim=-1)
|
73 |
+
|
74 |
+
|
75 |
+
def apply_rotary_pos_emb(t, freqs):
|
76 |
+
"""
|
77 |
+
input tensor t is of shape [seq_length, ..., dim]
|
78 |
+
rotary positional embeding tensor freqs is of shape [seq_length, ..., dim]
|
79 |
+
check https://kexue.fm/archives/8265 for detailed formulas
|
80 |
+
"""
|
81 |
+
# Changes from the original RoPE implementation
|
82 |
+
# 1. The original NeMo implementation assumes the input tensor of shape
|
83 |
+
# [seq_length, ..., dim], but the HF layout is [..., seq_length, dim].
|
84 |
+
# Thus freqs needs to be viewed as [..., seq_length, dim].
|
85 |
+
freqs = freqs.permute(1, 2, 0, 3)
|
86 |
+
# 2. Support for queries which past tokens are truncated
|
87 |
+
assert freqs.shape[-2] >= t.shape[-2]
|
88 |
+
if freqs.shape[-2] != t.shape[-2]:
|
89 |
+
freqs = freqs[:, :, -t.shape[-2]:, :]
|
90 |
+
|
91 |
+
rot_dim = freqs.shape[-1]
|
92 |
+
# ideally t_pass is empty so rotary pos embedding is applied to all tensor t
|
93 |
+
t, t_pass = t[..., :rot_dim], t[..., rot_dim:]
|
94 |
+
# first part is cosine component
|
95 |
+
# second part is sine component, need to change signs with _rotate_half method
|
96 |
+
t = (t * freqs.cos()) + (_rotate_half(t) * freqs.sin())
|
97 |
+
return torch.cat((t, t_pass), dim=-1)
|