superdocker commited on
Commit
0e6f5af
1 Parent(s): 7950536

Upload model

Browse files
config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/hub/midm-7b-w4a16cw-dpo",
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": "float32",
38
+ "transformers_version": "4.36.2",
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.2"
7
+ }
model-00001-of-00007.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:db7e762258171ba93f5e56b83ad2c33d5df28d2af098da4d92110295a47ddd3b
3
+ size 4999943444
model-00002-of-00007.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2f05d97883c66d43eaf8e152e3eaf102f611d0d93f9dc7e5db30381a834e5db8
3
+ size 4953839352
model-00003-of-00007.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:411615585aa2957b9d5d663677c92e0cd2b9a776c99431a0da3cd2e1cbd68e98
3
+ size 4976908028
model-00004-of-00007.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cdb70deef35efe7509ae842d015651768dc46c18152336c8ec874d5678853551
3
+ size 4865792144
model-00005-of-00007.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:219a17a132340196f0a9843d2ef1b36a8fbdf023c6689576bc6c46df85451261
3
+ size 4953839448
model-00006-of-00007.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:54c69789d2e970a2bbf1ac63104e4897fd89b6be36b6fdfeb9f5329f0efbfb6f
3
+ size 4284814336
model-00007-of-00007.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4d212678e7c3e47956cc59f4af169b85373f79ca118365f5712919e038f13f52
3
+ size 1182793856
model.safetensors.index.json ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 30217896192
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00007-of-00007.safetensors",
7
+ "transformer.h.0.attn.bias": "model-00001-of-00007.safetensors",
8
+ "transformer.h.0.attn.c_attn.weight": "model-00001-of-00007.safetensors",
9
+ "transformer.h.0.attn.c_proj.weight": "model-00001-of-00007.safetensors",
10
+ "transformer.h.0.attn.masked_bias": "model-00001-of-00007.safetensors",
11
+ "transformer.h.0.ln_1.bias": "model-00001-of-00007.safetensors",
12
+ "transformer.h.0.ln_1.weight": "model-00001-of-00007.safetensors",
13
+ "transformer.h.0.ln_2.bias": "model-00001-of-00007.safetensors",
14
+ "transformer.h.0.ln_2.weight": "model-00001-of-00007.safetensors",
15
+ "transformer.h.0.mlp.c_fc.weight": "model-00001-of-00007.safetensors",
16
+ "transformer.h.0.mlp.c_proj.weight": "model-00001-of-00007.safetensors",
17
+ "transformer.h.1.attn.bias": "model-00001-of-00007.safetensors",
18
+ "transformer.h.1.attn.c_attn.weight": "model-00001-of-00007.safetensors",
19
+ "transformer.h.1.attn.c_proj.weight": "model-00001-of-00007.safetensors",
20
+ "transformer.h.1.attn.masked_bias": "model-00001-of-00007.safetensors",
21
+ "transformer.h.1.ln_1.bias": "model-00001-of-00007.safetensors",
22
+ "transformer.h.1.ln_1.weight": "model-00001-of-00007.safetensors",
23
+ "transformer.h.1.ln_2.bias": "model-00001-of-00007.safetensors",
24
+ "transformer.h.1.ln_2.weight": "model-00001-of-00007.safetensors",
25
+ "transformer.h.1.mlp.c_fc.weight": "model-00001-of-00007.safetensors",
26
+ "transformer.h.1.mlp.c_proj.weight": "model-00001-of-00007.safetensors",
27
+ "transformer.h.10.attn.bias": "model-00002-of-00007.safetensors",
28
+ "transformer.h.10.attn.c_attn.weight": "model-00003-of-00007.safetensors",
29
+ "transformer.h.10.attn.c_proj.weight": "model-00003-of-00007.safetensors",
30
+ "transformer.h.10.attn.masked_bias": "model-00002-of-00007.safetensors",
31
+ "transformer.h.10.ln_1.bias": "model-00002-of-00007.safetensors",
32
+ "transformer.h.10.ln_1.weight": "model-00002-of-00007.safetensors",
33
+ "transformer.h.10.ln_2.bias": "model-00003-of-00007.safetensors",
34
+ "transformer.h.10.ln_2.weight": "model-00003-of-00007.safetensors",
35
+ "transformer.h.10.mlp.c_fc.weight": "model-00003-of-00007.safetensors",
36
+ "transformer.h.10.mlp.c_proj.weight": "model-00003-of-00007.safetensors",
37
+ "transformer.h.11.attn.bias": "model-00003-of-00007.safetensors",
38
+ "transformer.h.11.attn.c_attn.weight": "model-00003-of-00007.safetensors",
39
+ "transformer.h.11.attn.c_proj.weight": "model-00003-of-00007.safetensors",
40
+ "transformer.h.11.attn.masked_bias": "model-00003-of-00007.safetensors",
41
+ "transformer.h.11.ln_1.bias": "model-00003-of-00007.safetensors",
42
+ "transformer.h.11.ln_1.weight": "model-00003-of-00007.safetensors",
43
+ "transformer.h.11.ln_2.bias": "model-00003-of-00007.safetensors",
44
+ "transformer.h.11.ln_2.weight": "model-00003-of-00007.safetensors",
45
+ "transformer.h.11.mlp.c_fc.weight": "model-00003-of-00007.safetensors",
46
+ "transformer.h.11.mlp.c_proj.weight": "model-00003-of-00007.safetensors",
47
+ "transformer.h.12.attn.bias": "model-00003-of-00007.safetensors",
48
+ "transformer.h.12.attn.c_attn.weight": "model-00003-of-00007.safetensors",
49
+ "transformer.h.12.attn.c_proj.weight": "model-00003-of-00007.safetensors",
50
+ "transformer.h.12.attn.masked_bias": "model-00003-of-00007.safetensors",
51
+ "transformer.h.12.ln_1.bias": "model-00003-of-00007.safetensors",
52
+ "transformer.h.12.ln_1.weight": "model-00003-of-00007.safetensors",
53
+ "transformer.h.12.ln_2.bias": "model-00003-of-00007.safetensors",
54
+ "transformer.h.12.ln_2.weight": "model-00003-of-00007.safetensors",
55
+ "transformer.h.12.mlp.c_fc.weight": "model-00003-of-00007.safetensors",
56
+ "transformer.h.12.mlp.c_proj.weight": "model-00003-of-00007.safetensors",
57
+ "transformer.h.13.attn.bias": "model-00003-of-00007.safetensors",
58
+ "transformer.h.13.attn.c_attn.weight": "model-00003-of-00007.safetensors",
59
+ "transformer.h.13.attn.c_proj.weight": "model-00003-of-00007.safetensors",
60
+ "transformer.h.13.attn.masked_bias": "model-00003-of-00007.safetensors",
61
+ "transformer.h.13.ln_1.bias": "model-00003-of-00007.safetensors",
62
+ "transformer.h.13.ln_1.weight": "model-00003-of-00007.safetensors",
63
+ "transformer.h.13.ln_2.bias": "model-00003-of-00007.safetensors",
64
+ "transformer.h.13.ln_2.weight": "model-00003-of-00007.safetensors",
65
+ "transformer.h.13.mlp.c_fc.weight": "model-00003-of-00007.safetensors",
66
+ "transformer.h.13.mlp.c_proj.weight": "model-00003-of-00007.safetensors",
67
+ "transformer.h.14.attn.bias": "model-00003-of-00007.safetensors",
68
+ "transformer.h.14.attn.c_attn.weight": "model-00003-of-00007.safetensors",
69
+ "transformer.h.14.attn.c_proj.weight": "model-00003-of-00007.safetensors",
70
+ "transformer.h.14.attn.masked_bias": "model-00003-of-00007.safetensors",
71
+ "transformer.h.14.ln_1.bias": "model-00003-of-00007.safetensors",
72
+ "transformer.h.14.ln_1.weight": "model-00003-of-00007.safetensors",
73
+ "transformer.h.14.ln_2.bias": "model-00003-of-00007.safetensors",
74
+ "transformer.h.14.ln_2.weight": "model-00003-of-00007.safetensors",
75
+ "transformer.h.14.mlp.c_fc.weight": "model-00003-of-00007.safetensors",
76
+ "transformer.h.14.mlp.c_proj.weight": "model-00003-of-00007.safetensors",
77
+ "transformer.h.15.attn.bias": "model-00003-of-00007.safetensors",
78
+ "transformer.h.15.attn.c_attn.weight": "model-00003-of-00007.safetensors",
79
+ "transformer.h.15.attn.c_proj.weight": "model-00003-of-00007.safetensors",
80
+ "transformer.h.15.attn.masked_bias": "model-00003-of-00007.safetensors",
81
+ "transformer.h.15.ln_1.bias": "model-00003-of-00007.safetensors",
82
+ "transformer.h.15.ln_1.weight": "model-00003-of-00007.safetensors",
83
+ "transformer.h.15.ln_2.bias": "model-00003-of-00007.safetensors",
84
+ "transformer.h.15.ln_2.weight": "model-00003-of-00007.safetensors",
85
+ "transformer.h.15.mlp.c_fc.weight": "model-00003-of-00007.safetensors",
86
+ "transformer.h.15.mlp.c_proj.weight": "model-00004-of-00007.safetensors",
87
+ "transformer.h.16.attn.bias": "model-00004-of-00007.safetensors",
88
+ "transformer.h.16.attn.c_attn.weight": "model-00004-of-00007.safetensors",
89
+ "transformer.h.16.attn.c_proj.weight": "model-00004-of-00007.safetensors",
90
+ "transformer.h.16.attn.masked_bias": "model-00004-of-00007.safetensors",
91
+ "transformer.h.16.ln_1.bias": "model-00004-of-00007.safetensors",
92
+ "transformer.h.16.ln_1.weight": "model-00004-of-00007.safetensors",
93
+ "transformer.h.16.ln_2.bias": "model-00004-of-00007.safetensors",
94
+ "transformer.h.16.ln_2.weight": "model-00004-of-00007.safetensors",
95
+ "transformer.h.16.mlp.c_fc.weight": "model-00004-of-00007.safetensors",
96
+ "transformer.h.16.mlp.c_proj.weight": "model-00004-of-00007.safetensors",
97
+ "transformer.h.17.attn.bias": "model-00004-of-00007.safetensors",
98
+ "transformer.h.17.attn.c_attn.weight": "model-00004-of-00007.safetensors",
99
+ "transformer.h.17.attn.c_proj.weight": "model-00004-of-00007.safetensors",
100
+ "transformer.h.17.attn.masked_bias": "model-00004-of-00007.safetensors",
101
+ "transformer.h.17.ln_1.bias": "model-00004-of-00007.safetensors",
102
+ "transformer.h.17.ln_1.weight": "model-00004-of-00007.safetensors",
103
+ "transformer.h.17.ln_2.bias": "model-00004-of-00007.safetensors",
104
+ "transformer.h.17.ln_2.weight": "model-00004-of-00007.safetensors",
105
+ "transformer.h.17.mlp.c_fc.weight": "model-00004-of-00007.safetensors",
106
+ "transformer.h.17.mlp.c_proj.weight": "model-00004-of-00007.safetensors",
107
+ "transformer.h.18.attn.bias": "model-00004-of-00007.safetensors",
108
+ "transformer.h.18.attn.c_attn.weight": "model-00004-of-00007.safetensors",
109
+ "transformer.h.18.attn.c_proj.weight": "model-00004-of-00007.safetensors",
110
+ "transformer.h.18.attn.masked_bias": "model-00004-of-00007.safetensors",
111
+ "transformer.h.18.ln_1.bias": "model-00004-of-00007.safetensors",
112
+ "transformer.h.18.ln_1.weight": "model-00004-of-00007.safetensors",
113
+ "transformer.h.18.ln_2.bias": "model-00004-of-00007.safetensors",
114
+ "transformer.h.18.ln_2.weight": "model-00004-of-00007.safetensors",
115
+ "transformer.h.18.mlp.c_fc.weight": "model-00004-of-00007.safetensors",
116
+ "transformer.h.18.mlp.c_proj.weight": "model-00004-of-00007.safetensors",
117
+ "transformer.h.19.attn.bias": "model-00004-of-00007.safetensors",
118
+ "transformer.h.19.attn.c_attn.weight": "model-00004-of-00007.safetensors",
119
+ "transformer.h.19.attn.c_proj.weight": "model-00004-of-00007.safetensors",
120
+ "transformer.h.19.attn.masked_bias": "model-00004-of-00007.safetensors",
121
+ "transformer.h.19.ln_1.bias": "model-00004-of-00007.safetensors",
122
+ "transformer.h.19.ln_1.weight": "model-00004-of-00007.safetensors",
123
+ "transformer.h.19.ln_2.bias": "model-00004-of-00007.safetensors",
124
+ "transformer.h.19.ln_2.weight": "model-00004-of-00007.safetensors",
125
+ "transformer.h.19.mlp.c_fc.weight": "model-00004-of-00007.safetensors",
126
+ "transformer.h.19.mlp.c_proj.weight": "model-00004-of-00007.safetensors",
127
+ "transformer.h.2.attn.bias": "model-00001-of-00007.safetensors",
128
+ "transformer.h.2.attn.c_attn.weight": "model-00001-of-00007.safetensors",
129
+ "transformer.h.2.attn.c_proj.weight": "model-00001-of-00007.safetensors",
130
+ "transformer.h.2.attn.masked_bias": "model-00001-of-00007.safetensors",
131
+ "transformer.h.2.ln_1.bias": "model-00001-of-00007.safetensors",
132
+ "transformer.h.2.ln_1.weight": "model-00001-of-00007.safetensors",
133
+ "transformer.h.2.ln_2.bias": "model-00001-of-00007.safetensors",
134
+ "transformer.h.2.ln_2.weight": "model-00001-of-00007.safetensors",
135
+ "transformer.h.2.mlp.c_fc.weight": "model-00001-of-00007.safetensors",
136
+ "transformer.h.2.mlp.c_proj.weight": "model-00001-of-00007.safetensors",
137
+ "transformer.h.20.attn.bias": "model-00004-of-00007.safetensors",
138
+ "transformer.h.20.attn.c_attn.weight": "model-00004-of-00007.safetensors",
139
+ "transformer.h.20.attn.c_proj.weight": "model-00004-of-00007.safetensors",
140
+ "transformer.h.20.attn.masked_bias": "model-00004-of-00007.safetensors",
141
+ "transformer.h.20.ln_1.bias": "model-00004-of-00007.safetensors",
142
+ "transformer.h.20.ln_1.weight": "model-00004-of-00007.safetensors",
143
+ "transformer.h.20.ln_2.bias": "model-00004-of-00007.safetensors",
144
+ "transformer.h.20.ln_2.weight": "model-00004-of-00007.safetensors",
145
+ "transformer.h.20.mlp.c_fc.weight": "model-00004-of-00007.safetensors",
146
+ "transformer.h.20.mlp.c_proj.weight": "model-00004-of-00007.safetensors",
147
+ "transformer.h.21.attn.bias": "model-00004-of-00007.safetensors",
148
+ "transformer.h.21.attn.c_attn.weight": "model-00004-of-00007.safetensors",
149
+ "transformer.h.21.attn.c_proj.weight": "model-00004-of-00007.safetensors",
150
+ "transformer.h.21.attn.masked_bias": "model-00004-of-00007.safetensors",
151
+ "transformer.h.21.ln_1.bias": "model-00004-of-00007.safetensors",
152
+ "transformer.h.21.ln_1.weight": "model-00004-of-00007.safetensors",
153
+ "transformer.h.21.ln_2.bias": "model-00004-of-00007.safetensors",
154
+ "transformer.h.21.ln_2.weight": "model-00004-of-00007.safetensors",
155
+ "transformer.h.21.mlp.c_fc.weight": "model-00005-of-00007.safetensors",
156
+ "transformer.h.21.mlp.c_proj.weight": "model-00005-of-00007.safetensors",
157
+ "transformer.h.22.attn.bias": "model-00005-of-00007.safetensors",
158
+ "transformer.h.22.attn.c_attn.weight": "model-00005-of-00007.safetensors",
159
+ "transformer.h.22.attn.c_proj.weight": "model-00005-of-00007.safetensors",
160
+ "transformer.h.22.attn.masked_bias": "model-00005-of-00007.safetensors",
161
+ "transformer.h.22.ln_1.bias": "model-00005-of-00007.safetensors",
162
+ "transformer.h.22.ln_1.weight": "model-00005-of-00007.safetensors",
163
+ "transformer.h.22.ln_2.bias": "model-00005-of-00007.safetensors",
164
+ "transformer.h.22.ln_2.weight": "model-00005-of-00007.safetensors",
165
+ "transformer.h.22.mlp.c_fc.weight": "model-00005-of-00007.safetensors",
166
+ "transformer.h.22.mlp.c_proj.weight": "model-00005-of-00007.safetensors",
167
+ "transformer.h.23.attn.bias": "model-00005-of-00007.safetensors",
168
+ "transformer.h.23.attn.c_attn.weight": "model-00005-of-00007.safetensors",
169
+ "transformer.h.23.attn.c_proj.weight": "model-00005-of-00007.safetensors",
170
+ "transformer.h.23.attn.masked_bias": "model-00005-of-00007.safetensors",
171
+ "transformer.h.23.ln_1.bias": "model-00005-of-00007.safetensors",
172
+ "transformer.h.23.ln_1.weight": "model-00005-of-00007.safetensors",
173
+ "transformer.h.23.ln_2.bias": "model-00005-of-00007.safetensors",
174
+ "transformer.h.23.ln_2.weight": "model-00005-of-00007.safetensors",
175
+ "transformer.h.23.mlp.c_fc.weight": "model-00005-of-00007.safetensors",
176
+ "transformer.h.23.mlp.c_proj.weight": "model-00005-of-00007.safetensors",
177
+ "transformer.h.24.attn.bias": "model-00005-of-00007.safetensors",
178
+ "transformer.h.24.attn.c_attn.weight": "model-00005-of-00007.safetensors",
179
+ "transformer.h.24.attn.c_proj.weight": "model-00005-of-00007.safetensors",
180
+ "transformer.h.24.attn.masked_bias": "model-00005-of-00007.safetensors",
181
+ "transformer.h.24.ln_1.bias": "model-00005-of-00007.safetensors",
182
+ "transformer.h.24.ln_1.weight": "model-00005-of-00007.safetensors",
183
+ "transformer.h.24.ln_2.bias": "model-00005-of-00007.safetensors",
184
+ "transformer.h.24.ln_2.weight": "model-00005-of-00007.safetensors",
185
+ "transformer.h.24.mlp.c_fc.weight": "model-00005-of-00007.safetensors",
186
+ "transformer.h.24.mlp.c_proj.weight": "model-00005-of-00007.safetensors",
187
+ "transformer.h.25.attn.bias": "model-00005-of-00007.safetensors",
188
+ "transformer.h.25.attn.c_attn.weight": "model-00005-of-00007.safetensors",
189
+ "transformer.h.25.attn.c_proj.weight": "model-00005-of-00007.safetensors",
190
+ "transformer.h.25.attn.masked_bias": "model-00005-of-00007.safetensors",
191
+ "transformer.h.25.ln_1.bias": "model-00005-of-00007.safetensors",
192
+ "transformer.h.25.ln_1.weight": "model-00005-of-00007.safetensors",
193
+ "transformer.h.25.ln_2.bias": "model-00005-of-00007.safetensors",
194
+ "transformer.h.25.ln_2.weight": "model-00005-of-00007.safetensors",
195
+ "transformer.h.25.mlp.c_fc.weight": "model-00005-of-00007.safetensors",
196
+ "transformer.h.25.mlp.c_proj.weight": "model-00005-of-00007.safetensors",
197
+ "transformer.h.26.attn.bias": "model-00005-of-00007.safetensors",
198
+ "transformer.h.26.attn.c_attn.weight": "model-00005-of-00007.safetensors",
199
+ "transformer.h.26.attn.c_proj.weight": "model-00005-of-00007.safetensors",
200
+ "transformer.h.26.attn.masked_bias": "model-00005-of-00007.safetensors",
201
+ "transformer.h.26.ln_1.bias": "model-00005-of-00007.safetensors",
202
+ "transformer.h.26.ln_1.weight": "model-00005-of-00007.safetensors",
203
+ "transformer.h.26.ln_2.bias": "model-00005-of-00007.safetensors",
204
+ "transformer.h.26.ln_2.weight": "model-00005-of-00007.safetensors",
205
+ "transformer.h.26.mlp.c_fc.weight": "model-00005-of-00007.safetensors",
206
+ "transformer.h.26.mlp.c_proj.weight": "model-00005-of-00007.safetensors",
207
+ "transformer.h.27.attn.bias": "model-00005-of-00007.safetensors",
208
+ "transformer.h.27.attn.c_attn.weight": "model-00006-of-00007.safetensors",
209
+ "transformer.h.27.attn.c_proj.weight": "model-00006-of-00007.safetensors",
210
+ "transformer.h.27.attn.masked_bias": "model-00005-of-00007.safetensors",
211
+ "transformer.h.27.ln_1.bias": "model-00005-of-00007.safetensors",
212
+ "transformer.h.27.ln_1.weight": "model-00005-of-00007.safetensors",
213
+ "transformer.h.27.ln_2.bias": "model-00006-of-00007.safetensors",
214
+ "transformer.h.27.ln_2.weight": "model-00006-of-00007.safetensors",
215
+ "transformer.h.27.mlp.c_fc.weight": "model-00006-of-00007.safetensors",
216
+ "transformer.h.27.mlp.c_proj.weight": "model-00006-of-00007.safetensors",
217
+ "transformer.h.28.attn.bias": "model-00006-of-00007.safetensors",
218
+ "transformer.h.28.attn.c_attn.weight": "model-00006-of-00007.safetensors",
219
+ "transformer.h.28.attn.c_proj.weight": "model-00006-of-00007.safetensors",
220
+ "transformer.h.28.attn.masked_bias": "model-00006-of-00007.safetensors",
221
+ "transformer.h.28.ln_1.bias": "model-00006-of-00007.safetensors",
222
+ "transformer.h.28.ln_1.weight": "model-00006-of-00007.safetensors",
223
+ "transformer.h.28.ln_2.bias": "model-00006-of-00007.safetensors",
224
+ "transformer.h.28.ln_2.weight": "model-00006-of-00007.safetensors",
225
+ "transformer.h.28.mlp.c_fc.weight": "model-00006-of-00007.safetensors",
226
+ "transformer.h.28.mlp.c_proj.weight": "model-00006-of-00007.safetensors",
227
+ "transformer.h.29.attn.bias": "model-00006-of-00007.safetensors",
228
+ "transformer.h.29.attn.c_attn.weight": "model-00006-of-00007.safetensors",
229
+ "transformer.h.29.attn.c_proj.weight": "model-00006-of-00007.safetensors",
230
+ "transformer.h.29.attn.masked_bias": "model-00006-of-00007.safetensors",
231
+ "transformer.h.29.ln_1.bias": "model-00006-of-00007.safetensors",
232
+ "transformer.h.29.ln_1.weight": "model-00006-of-00007.safetensors",
233
+ "transformer.h.29.ln_2.bias": "model-00006-of-00007.safetensors",
234
+ "transformer.h.29.ln_2.weight": "model-00006-of-00007.safetensors",
235
+ "transformer.h.29.mlp.c_fc.weight": "model-00006-of-00007.safetensors",
236
+ "transformer.h.29.mlp.c_proj.weight": "model-00006-of-00007.safetensors",
237
+ "transformer.h.3.attn.bias": "model-00001-of-00007.safetensors",
238
+ "transformer.h.3.attn.c_attn.weight": "model-00001-of-00007.safetensors",
239
+ "transformer.h.3.attn.c_proj.weight": "model-00001-of-00007.safetensors",
240
+ "transformer.h.3.attn.masked_bias": "model-00001-of-00007.safetensors",
241
+ "transformer.h.3.ln_1.bias": "model-00001-of-00007.safetensors",
242
+ "transformer.h.3.ln_1.weight": "model-00001-of-00007.safetensors",
243
+ "transformer.h.3.ln_2.bias": "model-00001-of-00007.safetensors",
244
+ "transformer.h.3.ln_2.weight": "model-00001-of-00007.safetensors",
245
+ "transformer.h.3.mlp.c_fc.weight": "model-00001-of-00007.safetensors",
246
+ "transformer.h.3.mlp.c_proj.weight": "model-00001-of-00007.safetensors",
247
+ "transformer.h.30.attn.bias": "model-00006-of-00007.safetensors",
248
+ "transformer.h.30.attn.c_attn.weight": "model-00006-of-00007.safetensors",
249
+ "transformer.h.30.attn.c_proj.weight": "model-00006-of-00007.safetensors",
250
+ "transformer.h.30.attn.masked_bias": "model-00006-of-00007.safetensors",
251
+ "transformer.h.30.ln_1.bias": "model-00006-of-00007.safetensors",
252
+ "transformer.h.30.ln_1.weight": "model-00006-of-00007.safetensors",
253
+ "transformer.h.30.ln_2.bias": "model-00006-of-00007.safetensors",
254
+ "transformer.h.30.ln_2.weight": "model-00006-of-00007.safetensors",
255
+ "transformer.h.30.mlp.c_fc.weight": "model-00006-of-00007.safetensors",
256
+ "transformer.h.30.mlp.c_proj.weight": "model-00006-of-00007.safetensors",
257
+ "transformer.h.31.attn.bias": "model-00006-of-00007.safetensors",
258
+ "transformer.h.31.attn.c_attn.weight": "model-00006-of-00007.safetensors",
259
+ "transformer.h.31.attn.c_proj.weight": "model-00006-of-00007.safetensors",
260
+ "transformer.h.31.attn.masked_bias": "model-00006-of-00007.safetensors",
261
+ "transformer.h.31.ln_1.bias": "model-00006-of-00007.safetensors",
262
+ "transformer.h.31.ln_1.weight": "model-00006-of-00007.safetensors",
263
+ "transformer.h.31.ln_2.bias": "model-00006-of-00007.safetensors",
264
+ "transformer.h.31.ln_2.weight": "model-00006-of-00007.safetensors",
265
+ "transformer.h.31.mlp.c_fc.weight": "model-00006-of-00007.safetensors",
266
+ "transformer.h.31.mlp.c_proj.weight": "model-00006-of-00007.safetensors",
267
+ "transformer.h.4.attn.bias": "model-00001-of-00007.safetensors",
268
+ "transformer.h.4.attn.c_attn.weight": "model-00001-of-00007.safetensors",
269
+ "transformer.h.4.attn.c_proj.weight": "model-00001-of-00007.safetensors",
270
+ "transformer.h.4.attn.masked_bias": "model-00001-of-00007.safetensors",
271
+ "transformer.h.4.ln_1.bias": "model-00001-of-00007.safetensors",
272
+ "transformer.h.4.ln_1.weight": "model-00001-of-00007.safetensors",
273
+ "transformer.h.4.ln_2.bias": "model-00001-of-00007.safetensors",
274
+ "transformer.h.4.ln_2.weight": "model-00001-of-00007.safetensors",
275
+ "transformer.h.4.mlp.c_fc.weight": "model-00002-of-00007.safetensors",
276
+ "transformer.h.4.mlp.c_proj.weight": "model-00002-of-00007.safetensors",
277
+ "transformer.h.5.attn.bias": "model-00002-of-00007.safetensors",
278
+ "transformer.h.5.attn.c_attn.weight": "model-00002-of-00007.safetensors",
279
+ "transformer.h.5.attn.c_proj.weight": "model-00002-of-00007.safetensors",
280
+ "transformer.h.5.attn.masked_bias": "model-00002-of-00007.safetensors",
281
+ "transformer.h.5.ln_1.bias": "model-00002-of-00007.safetensors",
282
+ "transformer.h.5.ln_1.weight": "model-00002-of-00007.safetensors",
283
+ "transformer.h.5.ln_2.bias": "model-00002-of-00007.safetensors",
284
+ "transformer.h.5.ln_2.weight": "model-00002-of-00007.safetensors",
285
+ "transformer.h.5.mlp.c_fc.weight": "model-00002-of-00007.safetensors",
286
+ "transformer.h.5.mlp.c_proj.weight": "model-00002-of-00007.safetensors",
287
+ "transformer.h.6.attn.bias": "model-00002-of-00007.safetensors",
288
+ "transformer.h.6.attn.c_attn.weight": "model-00002-of-00007.safetensors",
289
+ "transformer.h.6.attn.c_proj.weight": "model-00002-of-00007.safetensors",
290
+ "transformer.h.6.attn.masked_bias": "model-00002-of-00007.safetensors",
291
+ "transformer.h.6.ln_1.bias": "model-00002-of-00007.safetensors",
292
+ "transformer.h.6.ln_1.weight": "model-00002-of-00007.safetensors",
293
+ "transformer.h.6.ln_2.bias": "model-00002-of-00007.safetensors",
294
+ "transformer.h.6.ln_2.weight": "model-00002-of-00007.safetensors",
295
+ "transformer.h.6.mlp.c_fc.weight": "model-00002-of-00007.safetensors",
296
+ "transformer.h.6.mlp.c_proj.weight": "model-00002-of-00007.safetensors",
297
+ "transformer.h.7.attn.bias": "model-00002-of-00007.safetensors",
298
+ "transformer.h.7.attn.c_attn.weight": "model-00002-of-00007.safetensors",
299
+ "transformer.h.7.attn.c_proj.weight": "model-00002-of-00007.safetensors",
300
+ "transformer.h.7.attn.masked_bias": "model-00002-of-00007.safetensors",
301
+ "transformer.h.7.ln_1.bias": "model-00002-of-00007.safetensors",
302
+ "transformer.h.7.ln_1.weight": "model-00002-of-00007.safetensors",
303
+ "transformer.h.7.ln_2.bias": "model-00002-of-00007.safetensors",
304
+ "transformer.h.7.ln_2.weight": "model-00002-of-00007.safetensors",
305
+ "transformer.h.7.mlp.c_fc.weight": "model-00002-of-00007.safetensors",
306
+ "transformer.h.7.mlp.c_proj.weight": "model-00002-of-00007.safetensors",
307
+ "transformer.h.8.attn.bias": "model-00002-of-00007.safetensors",
308
+ "transformer.h.8.attn.c_attn.weight": "model-00002-of-00007.safetensors",
309
+ "transformer.h.8.attn.c_proj.weight": "model-00002-of-00007.safetensors",
310
+ "transformer.h.8.attn.masked_bias": "model-00002-of-00007.safetensors",
311
+ "transformer.h.8.ln_1.bias": "model-00002-of-00007.safetensors",
312
+ "transformer.h.8.ln_1.weight": "model-00002-of-00007.safetensors",
313
+ "transformer.h.8.ln_2.bias": "model-00002-of-00007.safetensors",
314
+ "transformer.h.8.ln_2.weight": "model-00002-of-00007.safetensors",
315
+ "transformer.h.8.mlp.c_fc.weight": "model-00002-of-00007.safetensors",
316
+ "transformer.h.8.mlp.c_proj.weight": "model-00002-of-00007.safetensors",
317
+ "transformer.h.9.attn.bias": "model-00002-of-00007.safetensors",
318
+ "transformer.h.9.attn.c_attn.weight": "model-00002-of-00007.safetensors",
319
+ "transformer.h.9.attn.c_proj.weight": "model-00002-of-00007.safetensors",
320
+ "transformer.h.9.attn.masked_bias": "model-00002-of-00007.safetensors",
321
+ "transformer.h.9.ln_1.bias": "model-00002-of-00007.safetensors",
322
+ "transformer.h.9.ln_1.weight": "model-00002-of-00007.safetensors",
323
+ "transformer.h.9.ln_2.bias": "model-00002-of-00007.safetensors",
324
+ "transformer.h.9.ln_2.weight": "model-00002-of-00007.safetensors",
325
+ "transformer.h.9.mlp.c_fc.weight": "model-00002-of-00007.safetensors",
326
+ "transformer.h.9.mlp.c_proj.weight": "model-00002-of-00007.safetensors",
327
+ "transformer.ln_f.bias": "model-00006-of-00007.safetensors",
328
+ "transformer.ln_f.weight": "model-00006-of-00007.safetensors",
329
+ "transformer.rotary_pos_emb.inv_freq": "model-00001-of-00007.safetensors",
330
+ "transformer.wte.weight": "model-00001-of-00007.safetensors"
331
+ }
332
+ }
modeling_midm.py ADDED
@@ -0,0 +1,1458 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
464
+ @dataclass
465
+ class MidmDoubleHeadsModelOutput(ModelOutput):
466
+ loss: Optional[torch.FloatTensor] = None
467
+ mc_loss: Optional[torch.FloatTensor] = None
468
+ logits: torch.FloatTensor = None
469
+ mc_logits: torch.FloatTensor = None
470
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
471
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
472
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
473
+
474
+
475
+ MIDM_START_DOCSTRING = r"""
476
+
477
+ This model inherits from :class:`~transformers.PreTrainedModel`. Check the superclass documentation for the generic
478
+ methods the library implements for all its model (such as downloading or saving, resizing the input embeddings,
479
+ pruning heads etc.)
480
+
481
+ This model is also a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`__
482
+ subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to
483
+ general usage and behavior.
484
+
485
+ Parameters:
486
+ config (:class:`~transformers.MidmBitextConfig`): Model configuration class with all the parameters of the model.
487
+ Initializing with a config file does not load the weights associated with the model, only the
488
+ configuration. Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model
489
+ weights.
490
+ """
491
+
492
+ MIDM_INPUTS_DOCSTRING = r"""
493
+ Args:
494
+ input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, input_ids_length)`):
495
+ :obj:`input_ids_length` = ``sequence_length`` if :obj:`past_key_values` is ``None`` else
496
+ ``past_key_values[0][0].shape[-2]`` (``sequence_length`` of input past key value states). Indices of input
497
+ sequence tokens in the vocabulary.
498
+
499
+ If :obj:`past_key_values` is used, only ``input_ids`` that do not have their past calculated should be
500
+ passed as ``input_ids``.
501
+
502
+ Indices can be obtained using :class:`~transformers.Midm_bitext_Tokenizer`. See
503
+ :meth:`transformers.PreTrainedTokenizer.encode` and :meth:`transformers.PreTrainedTokenizer.__call__` for
504
+ details.
505
+
506
+ `What are input IDs? <../glossary.html#input-ids>`__
507
+ past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers`):
508
+ Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
509
+ :obj:`past_key_values` output below). Can be used to speed up sequential decoding. The ``input_ids`` which
510
+ have their past given to this model should not be passed as ``input_ids`` as they have already been
511
+ computed.
512
+ attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
513
+ Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``:
514
+
515
+ - 1 for tokens that are **not masked**,
516
+ - 0 for tokens that are **masked**.
517
+
518
+ `What are attention masks? <../glossary.html#attention-mask>`__
519
+ token_type_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, input_ids_length)`, `optional`):
520
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in ``[0,
521
+ 1]``:
522
+
523
+ - 0 corresponds to a `sentence A` token,
524
+ - 1 corresponds to a `sentence B` token.
525
+
526
+ `What are token type IDs? <../glossary.html#token-type-ids>`_
527
+ position_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
528
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range ``[0,
529
+ config.max_position_embeddings - 1]``.
530
+
531
+ `What are position IDs? <../glossary.html#position-ids>`_
532
+ head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`):
533
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in ``[0, 1]``:
534
+
535
+ - 1 indicates the head is **not masked**,
536
+ - 0 indicates the head is **masked**.
537
+
538
+ inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
539
+ Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation.
540
+ This is useful if you want more control over how to convert :obj:`input_ids` indices into associated
541
+ vectors than the model's internal embedding lookup matrix.
542
+
543
+ If :obj:`past_key_values` is used, optionally only the last :obj:`inputs_embeds` have to be input (see
544
+ :obj:`past_key_values`).
545
+ use_cache (:obj:`bool`, `optional`):
546
+ If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
547
+ decoding (see :obj:`past_key_values`).
548
+ output_attentions (:obj:`bool`, `optional`):
549
+ Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under returned
550
+ tensors for more detail.
551
+ output_hidden_states (:obj:`bool`, `optional`):
552
+ Whether or not to return the hidden states of all layers. See ``hidden_states`` under returned tensors for
553
+ more detail.
554
+ return_dict (:obj:`bool`, `optional`):
555
+ Whether or not to return a :class:`~transformers.file_utils.ModelOutput` instead of a plain tuple.
556
+ """
557
+ PARALLELIZE_DOCSTRING = r"""
558
+ This is an experimental feature and is a subject to change at a moment's notice.
559
+
560
+ Uses a device map to distribute attention modules of the model across several devices. If no device map is given,
561
+ it will evenly distribute blocks across all devices.
562
+
563
+ Args:
564
+ device_map (:obj:`Dict[int, list]`, optional, defaults to None):
565
+ A dictionary that maps attention modules to devices. Note that the embedding module and LMHead are always
566
+ automatically mapped to the first device (for esoteric reasons). That means that the first device should
567
+ have fewer attention modules mapped to it than other devices. For reference, the Midm models have the
568
+ following number of attention modules:
569
+
570
+ - midm-bitext-S: 32
571
+
572
+ Example::
573
+
574
+ # 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:
575
+ model = MidmLMHeadModel.from_pretrained('midm-bitext-S')
576
+ device_map = {0: [0, 1, 2, 3, 4, 5, 6, 7, 8],
577
+ 1: [9, 10, 11, 12, 13, 14, 15, 16],
578
+ 2: [17, 18, 19, 20, 21, 22, 23, 24],
579
+ 3: [25, 26, 27, 28, 29, 30, 31, 32]}
580
+ model.parallelize(device_map)
581
+ """
582
+ DEPARALLELIZE_DOCSTRING = r"""
583
+ Moves the model to cpu from a model parallel state.
584
+
585
+ Example::
586
+
587
+ # On a 4 GPU machine with midm-bitext-S:
588
+ model = MidmLMHeadModel.from_pretrained('midm-bitext-S')
589
+ device_map = {0: [0, 1, 2, 3, 4, 5, 6, 7, 8],
590
+ 1: [9, 10, 11, 12, 13, 14, 15, 16],
591
+ 2: [17, 18, 19, 20, 21, 22, 23, 24],
592
+ 3: [25, 26, 27, 28, 29, 30, 31, 32]}
593
+ model.parallelize(device_map) # Splits the model across several devices
594
+ model.deparallelize() # Put the model back on cpu and cleans memory by calling torch.cuda.empty_cache()
595
+ """
596
+
597
+
598
+ @add_start_docstrings(
599
+ "The bare Midm Model transformer outputting raw hidden-states without any specific head on top.",
600
+ MIDM_START_DOCSTRING,
601
+ )
602
+ class MidmModel(MidmPreTrainedModel):
603
+ _keys_to_ignore_on_load_missing = ["attn.masked_bias"]
604
+
605
+ def __init__(self, config):
606
+ super().__init__(config)
607
+
608
+ self.embed_dim = config.hidden_size
609
+
610
+ self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
611
+ self.use_absolute_position_embedding = config.use_absolute_position_embedding
612
+ if self.use_absolute_position_embedding:
613
+ self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim)
614
+
615
+ self.use_rotary_position_embedding = config.use_rotary_position_embedding
616
+ if self.use_rotary_position_embedding:
617
+ rotary_dim = config.hidden_size // config.num_attention_heads
618
+ assert 0 < config.rotary_percentage <= 1
619
+ if config.rotary_percentage < 1:
620
+ rotary_dim = int(rotary_dim * config.rotary_percentage)
621
+ self.rotary_pos_emb = RotaryEmbedding(
622
+ rotary_dim,
623
+ seq_len_interpolation_factor=None,
624
+ pretrained_max_position_embeddings=config.max_position_embeddings)
625
+
626
+ self.drop = nn.Dropout(config.embd_pdrop)
627
+ self.h = nn.ModuleList([MidmBlock(config, layer_idx=i) for i in range(config.num_hidden_layers)])
628
+ self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
629
+ self.use_layernorm1p = config.normalization_type == 'layernorm1p'
630
+
631
+ self.init_weights()
632
+
633
+ # Model parallel
634
+ self.model_parallel = False
635
+ self.device_map = None
636
+ self.gradient_checkpointing = False
637
+
638
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
639
+ def parallelize(self, device_map=None):
640
+ # Check validity of device_map
641
+ self.device_map = (
642
+ get_device_map(len(self.h), range(torch.cuda.device_count())) if device_map is None else device_map
643
+ )
644
+ assert_device_map(self.device_map, len(self.h))
645
+ self.model_parallel = True
646
+ self.first_device = "cpu" if "cpu" in self.device_map.keys() else "cuda:" + str(min(self.device_map.keys()))
647
+ self.last_device = "cuda:" + str(max(self.device_map.keys()))
648
+ self.wte = self.wte.to(self.first_device)
649
+ if self.use_absolute_position_embedding:
650
+ self.wpe = self.wpe.to(self.first_device)
651
+ # Load onto devices
652
+ for k, v in self.device_map.items():
653
+ for block in v:
654
+ cuda_device = "cuda:" + str(k)
655
+ self.h[block] = self.h[block].to(cuda_device)
656
+ # ln_f to last
657
+ self.ln_f = self.ln_f.to(self.last_device)
658
+
659
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
660
+ def deparallelize(self):
661
+ self.model_parallel = False
662
+ self.device_map = None
663
+ self.first_device = "cpu"
664
+ self.last_device = "cpu"
665
+ self.wte = self.wte.to("cpu")
666
+ if self.use_absolute_position_embedding:
667
+ self.wpe = self.wpe.to("cpu")
668
+ for index in range(len(self.h)):
669
+ self.h[index] = self.h[index].to("cpu")
670
+ self.ln_f = self.ln_f.to("cpu")
671
+ torch.cuda.empty_cache()
672
+
673
+ def get_input_embeddings(self):
674
+ return self.wte
675
+
676
+ def set_input_embeddings(self, new_embeddings):
677
+ self.wte = new_embeddings
678
+
679
+ def _prune_heads(self, heads_to_prune):
680
+ """
681
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
682
+ """
683
+ for layer, heads in heads_to_prune.items():
684
+ self.h[layer].attn.prune_heads(heads)
685
+
686
+ @add_start_docstrings_to_model_forward(MIDM_INPUTS_DOCSTRING)
687
+ @add_code_sample_docstrings(
688
+ processor_class=_TOKENIZER_FOR_DOC,
689
+ checkpoint=_CHECKPOINT_FOR_DOC,
690
+ output_type=BaseModelOutputWithPastAndCrossAttentions,
691
+ config_class=_CONFIG_FOR_DOC,
692
+ )
693
+ def forward(
694
+ self,
695
+ input_ids=None,
696
+ past_key_values=None,
697
+ attention_mask=None,
698
+ token_type_ids=None,
699
+ position_ids=None,
700
+ head_mask=None,
701
+ inputs_embeds=None,
702
+ encoder_hidden_states=None,
703
+ encoder_attention_mask=None,
704
+ use_cache=None,
705
+ output_attentions=None,
706
+ output_hidden_states=None,
707
+ return_dict=None,
708
+ ):
709
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
710
+ output_hidden_states = (
711
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
712
+ )
713
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
714
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
715
+
716
+ if input_ids is not None and inputs_embeds is not None:
717
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
718
+ elif input_ids is not None:
719
+ input_shape = input_ids.size()
720
+ input_ids = input_ids.view(-1, input_shape[-1])
721
+ batch_size = input_ids.shape[0]
722
+ elif inputs_embeds is not None:
723
+ input_shape = inputs_embeds.size()[:-1]
724
+ batch_size = inputs_embeds.shape[0]
725
+ else:
726
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
727
+
728
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
729
+
730
+ if token_type_ids is not None:
731
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
732
+ if position_ids is not None:
733
+ position_ids = position_ids.view(-1, input_shape[-1])
734
+
735
+ if past_key_values is None:
736
+ past_length = 0
737
+ past_key_values = tuple([None] * len(self.h))
738
+ else:
739
+ past_length = past_key_values[0][0].size(-2)
740
+ if position_ids is None:
741
+ position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
742
+ position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
743
+
744
+ # MidmAttention mask.
745
+ if attention_mask is not None:
746
+ if batch_size <= 0:
747
+ raise ValueError("batch_size has to be defined and > 0")
748
+ attention_mask = attention_mask.view(batch_size, -1)
749
+ # We create a 3D attention mask from a 2D tensor mask.
750
+ # Sizes are [batch_size, 1, 1, to_seq_length]
751
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
752
+ # this attention mask is more simple than the triangular masking of causal attention
753
+ # used in KT Midm, we just need to prepare the broadcast dimension here.
754
+ attention_mask = attention_mask[:, None, None, :]
755
+
756
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
757
+ # masked positions, this operation will create a tensor which is 0.0 for
758
+ # positions we want to attend and -10000.0 for masked positions.
759
+ # Since we are adding it to the raw scores before the softmax, this is
760
+ # effectively the same as removing these entirely.
761
+ attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
762
+ attention_mask = (1.0 - attention_mask) * -10000.0
763
+
764
+ # If a 2D or 3D attention mask is provided for the cross-attention
765
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
766
+ if self.config.add_cross_attention and encoder_hidden_states is not None:
767
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
768
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
769
+ if encoder_attention_mask is None:
770
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
771
+ encoder_attention_mask = self.invert_attention_mask(encoder_attention_mask)
772
+ else:
773
+ encoder_attention_mask = None
774
+
775
+ rotary_pos_emb = None
776
+ if self.use_rotary_position_embedding:
777
+ rotary_pos_emb = self.rotary_pos_emb(past_length + input_shape[-1])
778
+
779
+ # Prepare head mask if needed
780
+ # 1.0 in head_mask indicate we keep the head
781
+ # attention_probs has shape bsz x n_heads x N x N
782
+ # head_mask has shape n_layer x batch x n_heads x N x N
783
+ head_mask = self.get_head_mask(head_mask, self.config.n_layer)
784
+
785
+ if inputs_embeds is None:
786
+ inputs_embeds = self.wte(input_ids)
787
+ if self.use_absolute_position_embedding:
788
+ position_embeds = self.wpe(position_ids)
789
+ hidden_states = inputs_embeds + position_embeds
790
+ else:
791
+ hidden_states = inputs_embeds
792
+
793
+ if token_type_ids is not None:
794
+ token_type_embeds = self.wte(token_type_ids)
795
+ hidden_states = hidden_states + token_type_embeds
796
+
797
+ hidden_states = self.drop(hidden_states)
798
+
799
+ output_shape = input_shape + (hidden_states.size(-1),)
800
+
801
+ presents = () if use_cache else None
802
+ all_self_attentions = () if output_attentions else None
803
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
804
+ all_hidden_states = () if output_hidden_states else None
805
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
806
+
807
+ # Model parallel
808
+ if self.model_parallel:
809
+ torch.cuda.set_device(hidden_states.device)
810
+ # Ensure layer_past is on same device as hidden_states (might not be correct)
811
+ if layer_past is not None:
812
+ layer_past = tuple(past_state.to(hidden_states.device) for past_state in layer_past)
813
+ # Ensure that attention_mask is always on the same device as hidden_states
814
+ if attention_mask is not None:
815
+ attention_mask = attention_mask.to(hidden_states.device)
816
+ if isinstance(head_mask, torch.Tensor):
817
+ head_mask = head_mask.to(hidden_states.device)
818
+ if output_hidden_states:
819
+ all_hidden_states = all_hidden_states + (hidden_states,)
820
+
821
+ if self.gradient_checkpointing and self.training:
822
+
823
+ if use_cache:
824
+ logger.warning(
825
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
826
+ )
827
+ use_cache = False
828
+
829
+ def create_custom_forward(module):
830
+ def custom_forward(*inputs):
831
+ # None for past_key_value
832
+ return module(*inputs, use_cache, output_attentions)
833
+
834
+ return custom_forward
835
+
836
+ outputs = torch.utils.checkpoint.checkpoint(
837
+ create_custom_forward(block),
838
+ hidden_states,
839
+ None,
840
+ attention_mask,
841
+ head_mask[i],
842
+ encoder_hidden_states,
843
+ encoder_attention_mask,
844
+ rotary_pos_emb=rotary_pos_emb,
845
+ )
846
+ else:
847
+ outputs = block(
848
+ hidden_states,
849
+ layer_past=layer_past,
850
+ attention_mask=attention_mask,
851
+ head_mask=head_mask[i],
852
+ encoder_hidden_states=encoder_hidden_states,
853
+ encoder_attention_mask=encoder_attention_mask,
854
+ use_cache=use_cache,
855
+ output_attentions=output_attentions,
856
+ rotary_pos_emb=rotary_pos_emb,
857
+ )
858
+
859
+ hidden_states = outputs[0]
860
+ if use_cache is True:
861
+ presents = presents + (outputs[1],)
862
+
863
+ if output_attentions:
864
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
865
+ if self.config.add_cross_attention:
866
+ all_cross_attentions = all_cross_attentions + (outputs[3 if use_cache else 2],)
867
+
868
+ # Model Parallel: If it's the last layer for that device, put things on the next device
869
+ if self.model_parallel:
870
+ for k, v in self.device_map.items():
871
+ if i == v[-1] and "cuda:" + str(k) != self.last_device:
872
+ hidden_states = hidden_states.to("cuda:" + str(k + 1))
873
+
874
+ if self.use_layernorm1p:
875
+ hidden_states = layernorm1p(self.ln_f, hidden_states)
876
+ else:
877
+ hidden_states = self.ln_f(hidden_states)
878
+
879
+ hidden_states = hidden_states.view(*output_shape)
880
+ # Add last hidden state
881
+ if output_hidden_states:
882
+ all_hidden_states = all_hidden_states + (hidden_states,)
883
+
884
+ if not return_dict:
885
+ return tuple(
886
+ v
887
+ for v in [hidden_states, presents, all_hidden_states, all_self_attentions, all_cross_attentions]
888
+ if v is not None
889
+ )
890
+
891
+ return BaseModelOutputWithPastAndCrossAttentions(
892
+ last_hidden_state=hidden_states,
893
+ past_key_values=presents,
894
+ hidden_states=all_hidden_states,
895
+ attentions=all_self_attentions,
896
+ cross_attentions=all_cross_attentions,
897
+ )
898
+
899
+
900
+ @add_start_docstrings(
901
+ """
902
+ The Midm Model transformer with a language modeling head on top (linear layer with weights tied to the input
903
+ embeddings).
904
+ """,
905
+ MIDM_START_DOCSTRING,
906
+ )
907
+ class MidmLMHeadModel(MidmPreTrainedModel):
908
+ _keys_to_ignore_on_load_missing = [r"attn.masked_bias", r"attn.bias", r"lm_head.weight"]
909
+
910
+ def __init__(self, config):
911
+ super().__init__(config)
912
+ self.transformer = MidmModel(config)
913
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
914
+
915
+ self.init_weights()
916
+
917
+ # Model parallel
918
+ self.model_parallel = False
919
+ self.device_map = None
920
+
921
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
922
+ def parallelize(self, device_map=None):
923
+ self.device_map = (
924
+ get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
925
+ if device_map is None
926
+ else device_map
927
+ )
928
+ assert_device_map(self.device_map, len(self.transformer.h))
929
+ self.transformer.parallelize(self.device_map)
930
+ self.lm_head = self.lm_head.to(self.transformer.first_device)
931
+ self.model_parallel = True
932
+
933
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
934
+ def deparallelize(self):
935
+ self.transformer.deparallelize()
936
+ self.transformer = self.transformer.to("cpu")
937
+ self.lm_head = self.lm_head.to("cpu")
938
+ self.model_parallel = False
939
+ torch.cuda.empty_cache()
940
+
941
+ def get_output_embeddings(self):
942
+ return self.lm_head
943
+
944
+ def set_output_embeddings(self, new_embeddings):
945
+ self.lm_head = new_embeddings
946
+
947
+ def prepare_inputs_for_generation(self, input_ids, past=None, **kwargs):
948
+ token_type_ids = kwargs.get("token_type_ids", None)
949
+ # only last token for inputs_ids if past is defined in kwargs
950
+ if past:
951
+ input_ids = input_ids[:, -1].unsqueeze(-1)
952
+ if token_type_ids is not None:
953
+ token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
954
+
955
+ attention_mask = kwargs.get("attention_mask", None)
956
+ position_ids = kwargs.get("position_ids", None)
957
+
958
+ if attention_mask is not None and position_ids is None:
959
+ # create position_ids on the fly for batch generation
960
+ position_ids = attention_mask.long().cumsum(-1) - 1
961
+ position_ids.masked_fill_(attention_mask == 0, 1)
962
+ if past:
963
+ position_ids = position_ids[:, -1].unsqueeze(-1)
964
+ else:
965
+ position_ids = None
966
+ return {
967
+ "input_ids": input_ids,
968
+ "past_key_values": past,
969
+ "use_cache": kwargs.get("use_cache"),
970
+ "position_ids": position_ids,
971
+ "attention_mask": attention_mask,
972
+ "token_type_ids": token_type_ids,
973
+ }
974
+
975
+ @add_start_docstrings_to_model_forward(MIDM_INPUTS_DOCSTRING)
976
+ @add_code_sample_docstrings(
977
+ processor_class=_TOKENIZER_FOR_DOC,
978
+ checkpoint=_CHECKPOINT_FOR_DOC,
979
+ output_type=CausalLMOutputWithCrossAttentions,
980
+ config_class=_CONFIG_FOR_DOC,
981
+ )
982
+ def forward(
983
+ self,
984
+ input_ids=None,
985
+ past_key_values=None,
986
+ attention_mask=None,
987
+ token_type_ids=None,
988
+ position_ids=None,
989
+ head_mask=None,
990
+ inputs_embeds=None,
991
+ encoder_hidden_states=None,
992
+ encoder_attention_mask=None,
993
+ labels=None,
994
+ use_cache=None,
995
+ output_attentions=None,
996
+ output_hidden_states=None,
997
+ return_dict=None,
998
+ ):
999
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1000
+
1001
+ transformer_outputs = self.transformer(
1002
+ input_ids,
1003
+ past_key_values=past_key_values,
1004
+ attention_mask=attention_mask,
1005
+ token_type_ids=token_type_ids,
1006
+ position_ids=position_ids,
1007
+ head_mask=head_mask,
1008
+ inputs_embeds=inputs_embeds,
1009
+ encoder_hidden_states=encoder_hidden_states,
1010
+ encoder_attention_mask=encoder_attention_mask,
1011
+ use_cache=use_cache,
1012
+ output_attentions=output_attentions,
1013
+ output_hidden_states=output_hidden_states,
1014
+ return_dict=return_dict,
1015
+ )
1016
+ hidden_states = transformer_outputs[0]
1017
+
1018
+ # Set device for model parallelism
1019
+ if self.model_parallel:
1020
+ torch.cuda.set_device(self.transformer.first_device)
1021
+ hidden_states = hidden_states.to(self.lm_head.weight.device)
1022
+
1023
+ lm_logits = self.lm_head(hidden_states)
1024
+
1025
+ loss = None
1026
+ if labels is not None:
1027
+ # Shift so that tokens < n predict n
1028
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1029
+ shift_labels = labels[..., 1:].contiguous()
1030
+ # Flatten the tokens
1031
+ loss_fct = CrossEntropyLoss()
1032
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1033
+
1034
+ if not return_dict:
1035
+ output = (lm_logits,) + transformer_outputs[1:]
1036
+ return ((loss,) + output) if loss is not None else output
1037
+
1038
+ return CausalLMOutputWithCrossAttentions(
1039
+ loss=loss,
1040
+ logits=lm_logits,
1041
+ past_key_values=transformer_outputs.past_key_values,
1042
+ hidden_states=transformer_outputs.hidden_states,
1043
+ attentions=transformer_outputs.attentions,
1044
+ cross_attentions=transformer_outputs.cross_attentions,
1045
+ )
1046
+
1047
+ @staticmethod
1048
+ def _reorder_cache(past: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor) -> Tuple[Tuple[torch.Tensor]]:
1049
+ """
1050
+ This function is used to re-order the :obj:`past_key_values` cache if
1051
+ :meth:`~transformers.PreTrainedModel.beam_search` or :meth:`~transformers.PreTrainedModel.beam_sample` is
1052
+ called. This is required to match :obj:`past_key_values` with the correct beam_idx at every generation step.
1053
+ """
1054
+ return tuple(
1055
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
1056
+ for layer_past in past
1057
+ )
1058
+
1059
+
1060
+ @add_start_docstrings(
1061
+ """
1062
+ The Midm Model transformer with a language modeling and a multiple-choice classification head on top e.g. for
1063
+ RocStories/SWAG tasks. The two heads are two linear layers. The language modeling head has its weights tied to the
1064
+ input embeddings, the classification head takes as input the input of a specified classification token index in the
1065
+ input sequence).
1066
+ """,
1067
+ MIDM_START_DOCSTRING,
1068
+ )
1069
+ class MidmDoubleHeadsModel(MidmPreTrainedModel):
1070
+ _keys_to_ignore_on_load_missing = [r"attn.masked_bias", r"attn.bias", r"lm_head.weight"]
1071
+
1072
+ def __init__(self, config):
1073
+ super().__init__(config)
1074
+ config.num_labels = 1
1075
+ self.transformer = MidmModel(config)
1076
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
1077
+ self.multiple_choice_head = SequenceSummary(config)
1078
+
1079
+ self.init_weights()
1080
+
1081
+ # Model parallel
1082
+ self.model_parallel = False
1083
+ self.device_map = None
1084
+
1085
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
1086
+ def parallelize(self, device_map=None):
1087
+ self.device_map = (
1088
+ get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
1089
+ if device_map is None
1090
+ else device_map
1091
+ )
1092
+ assert_device_map(self.device_map, len(self.transformer.h))
1093
+ self.transformer.parallelize(self.device_map)
1094
+ self.lm_head = self.lm_head.to(self.transformer.first_device)
1095
+ self.multiple_choice_head = self.multiple_choice_head.to(self.transformer.first_device)
1096
+ self.model_parallel = True
1097
+
1098
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
1099
+ def deparallelize(self):
1100
+ self.transformer.deparallelize()
1101
+ self.transformer = self.transformer.to("cpu")
1102
+ self.lm_head = self.lm_head.to("cpu")
1103
+ self.multiple_choice_head = self.multiple_choice_head.to("cpu")
1104
+ self.model_parallel = False
1105
+ torch.cuda.empty_cache()
1106
+
1107
+ def get_output_embeddings(self):
1108
+ return self.lm_head
1109
+
1110
+ def set_output_embeddings(self, new_embeddings):
1111
+ self.lm_head = new_embeddings
1112
+
1113
+ def prepare_inputs_for_generation(self, input_ids, past=None, **kwargs):
1114
+ token_type_ids = kwargs.get("token_type_ids", None)
1115
+ # only last token for inputs_ids if past is defined in kwargs
1116
+ if past:
1117
+ input_ids = input_ids[:, -1].unsqueeze(-1)
1118
+ if token_type_ids is not None:
1119
+ token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
1120
+
1121
+ attention_mask = kwargs.get("attention_mask", None)
1122
+ position_ids = kwargs.get("position_ids", None)
1123
+
1124
+ if attention_mask is not None and position_ids is None:
1125
+ # create position_ids on the fly for batch generation
1126
+ position_ids = attention_mask.long().cumsum(-1) - 1
1127
+ position_ids.masked_fill_(attention_mask == 0, 1)
1128
+ if past:
1129
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1130
+ else:
1131
+ position_ids = None
1132
+
1133
+ return {
1134
+ "input_ids": input_ids,
1135
+ "past_key_values": past,
1136
+ "use_cache": kwargs.get("use_cache"),
1137
+ "position_ids": position_ids,
1138
+ "attention_mask": attention_mask,
1139
+ "token_type_ids": token_type_ids,
1140
+ }
1141
+
1142
+ @add_start_docstrings_to_model_forward(MIDM_INPUTS_DOCSTRING)
1143
+ def forward(
1144
+ self,
1145
+ input_ids=None,
1146
+ past_key_values=None,
1147
+ attention_mask=None,
1148
+ token_type_ids=None,
1149
+ position_ids=None,
1150
+ head_mask=None,
1151
+ inputs_embeds=None,
1152
+ mc_token_ids=None,
1153
+ labels=None,
1154
+ mc_labels=None,
1155
+ use_cache=None,
1156
+ output_attentions=None,
1157
+ output_hidden_states=None,
1158
+ return_dict=None,
1159
+ **kwargs,
1160
+ ):
1161
+
1162
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1163
+
1164
+ transformer_outputs = self.transformer(
1165
+ input_ids,
1166
+ past_key_values=past_key_values,
1167
+ attention_mask=attention_mask,
1168
+ token_type_ids=token_type_ids,
1169
+ position_ids=position_ids,
1170
+ head_mask=head_mask,
1171
+ inputs_embeds=inputs_embeds,
1172
+ use_cache=use_cache,
1173
+ output_attentions=output_attentions,
1174
+ output_hidden_states=output_hidden_states,
1175
+ return_dict=return_dict,
1176
+ )
1177
+
1178
+ hidden_states = transformer_outputs[0]
1179
+
1180
+ # Set device for model parallelism
1181
+ if self.model_parallel:
1182
+ torch.cuda.set_device(self.transformer.first_device)
1183
+ hidden_states = hidden_states.to(self.lm_head.weight.device)
1184
+
1185
+ lm_logits = self.lm_head(hidden_states)
1186
+ mc_logits = self.multiple_choice_head(hidden_states, mc_token_ids).squeeze(-1)
1187
+
1188
+ mc_loss = None
1189
+ if mc_labels is not None:
1190
+ loss_fct = CrossEntropyLoss()
1191
+ mc_loss = loss_fct(mc_logits.view(-1, mc_logits.size(-1)), mc_labels.view(-1))
1192
+ lm_loss = None
1193
+ if labels is not None:
1194
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1195
+ shift_labels = labels[..., 1:].contiguous()
1196
+ loss_fct = CrossEntropyLoss()
1197
+ lm_loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1198
+
1199
+ if not return_dict:
1200
+ output = (lm_logits, mc_logits) + transformer_outputs[1:]
1201
+ if mc_loss is not None:
1202
+ output = (mc_loss,) + output
1203
+ return ((lm_loss,) + output) if lm_loss is not None else output
1204
+
1205
+ return MidmDoubleHeadsModelOutput(
1206
+ loss=lm_loss,
1207
+ mc_loss=mc_loss,
1208
+ logits=lm_logits,
1209
+ mc_logits=mc_logits,
1210
+ past_key_values=transformer_outputs.past_key_values,
1211
+ hidden_states=transformer_outputs.hidden_states,
1212
+ attentions=transformer_outputs.attentions,
1213
+ )
1214
+
1215
+ @staticmethod
1216
+ def _reorder_cache(past: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor) -> Tuple[Tuple[torch.Tensor]]:
1217
+ return tuple(
1218
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
1219
+ for layer_past in past
1220
+ )
1221
+
1222
+
1223
+ @add_start_docstrings(
1224
+ """
1225
+ The Midm Model transformer with a sequence classification head on top (linear layer).
1226
+
1227
+ :class:`~transformers.MidmForSequenceClassification` uses the last token in order to do the classification, as
1228
+ other causal models do.
1229
+
1230
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1231
+ :obj:`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each
1232
+ row. If no :obj:`pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot
1233
+ guess the padding tokens when :obj:`inputs_embeds` are passed instead of :obj:`input_ids`, it does the same (take
1234
+ the last value in each row of the batch).
1235
+ """,
1236
+ MIDM_START_DOCSTRING,
1237
+ )
1238
+ class MidmForSequenceClassification(MidmPreTrainedModel):
1239
+ _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"lm_head\.weight"]
1240
+
1241
+ def __init__(self, config):
1242
+ super().__init__(config)
1243
+ self.num_labels = config.num_labels
1244
+ self.transformer = MidmModel(config)
1245
+ self.score = nn.Linear(config.n_embd, self.num_labels, bias=False)
1246
+
1247
+ self.init_weights()
1248
+
1249
+ # Model parallel
1250
+ self.model_parallel = False
1251
+ self.device_map = None
1252
+
1253
+ @add_start_docstrings_to_model_forward(MIDM_INPUTS_DOCSTRING)
1254
+ def forward(
1255
+ self,
1256
+ input_ids=None,
1257
+ past_key_values=None,
1258
+ attention_mask=None,
1259
+ token_type_ids=None,
1260
+ position_ids=None,
1261
+ head_mask=None,
1262
+ inputs_embeds=None,
1263
+ labels=None,
1264
+ use_cache=None,
1265
+ output_attentions=None,
1266
+ output_hidden_states=None,
1267
+ return_dict=None,
1268
+ ):
1269
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1270
+
1271
+ transformer_outputs = self.transformer(
1272
+ input_ids,
1273
+ past_key_values=past_key_values,
1274
+ attention_mask=attention_mask,
1275
+ token_type_ids=token_type_ids,
1276
+ position_ids=position_ids,
1277
+ head_mask=head_mask,
1278
+ inputs_embeds=inputs_embeds,
1279
+ use_cache=use_cache,
1280
+ output_attentions=output_attentions,
1281
+ output_hidden_states=output_hidden_states,
1282
+ return_dict=return_dict,
1283
+ )
1284
+ hidden_states = transformer_outputs[0]
1285
+ logits = self.score(hidden_states)
1286
+
1287
+ if input_ids is not None:
1288
+ batch_size, sequence_length = input_ids.shape[:2]
1289
+ else:
1290
+ batch_size, sequence_length = inputs_embeds.shape[:2]
1291
+
1292
+ assert (
1293
+ self.config.pad_token_id is not None or batch_size == 1
1294
+ ), "Cannot handle batch sizes > 1 if no padding token is defined."
1295
+ if self.config.pad_token_id is None:
1296
+ sequence_lengths = -1
1297
+ else:
1298
+ if input_ids is not None:
1299
+ sequence_lengths = torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1
1300
+ else:
1301
+ sequence_lengths = -1
1302
+ logger.warning(
1303
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1304
+ f"unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1305
+ )
1306
+
1307
+ pooled_logits = logits[range(batch_size), sequence_lengths]
1308
+
1309
+ loss = None
1310
+ if labels is not None:
1311
+ if self.num_labels == 1:
1312
+ # We are doing regression
1313
+ loss_fct = MSELoss()
1314
+ loss = loss_fct(pooled_logits.view(-1), labels.to(self.dtype).view(-1))
1315
+ else:
1316
+ loss_fct = CrossEntropyLoss()
1317
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1318
+
1319
+ if not return_dict:
1320
+ output = (pooled_logits,) + transformer_outputs[1:]
1321
+ return ((loss,) + output) if loss is not None else output
1322
+
1323
+ return SequenceClassifierOutputWithPast(
1324
+ loss=loss,
1325
+ logits=pooled_logits,
1326
+ past_key_values=transformer_outputs.past_key_values,
1327
+ hidden_states=transformer_outputs.hidden_states,
1328
+ attentions=transformer_outputs.attentions,
1329
+ )
1330
+
1331
+
1332
+ @add_start_docstrings(
1333
+ """
1334
+ Midm Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1335
+ Named-Entity-Recognition (NER) tasks.
1336
+ """,
1337
+ MIDM_START_DOCSTRING,
1338
+ )
1339
+ class MidmForTokenClassification(MidmPreTrainedModel):
1340
+ def __init__(self, config):
1341
+ super().__init__(config)
1342
+ self.num_labels = config.num_labels
1343
+
1344
+ self.transformer = MidmModel(config)
1345
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1346
+ classifier_dropout = config.classifier_dropout
1347
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1348
+ classifier_dropout = config.hidden_dropout
1349
+ else:
1350
+ classifier_dropout = 0.1
1351
+ self.dropout = nn.Dropout(classifier_dropout)
1352
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1353
+
1354
+ self.init_weights()
1355
+
1356
+ # Model parallel
1357
+ self.model_parallel = False
1358
+ self.device_map = None
1359
+
1360
+ @add_start_docstrings_to_model_forward(MIDM_INPUTS_DOCSTRING)
1361
+ def forward(
1362
+ self,
1363
+ input_ids=None,
1364
+ past_key_values=None,
1365
+ attention_mask=None,
1366
+ token_type_ids=None,
1367
+ position_ids=None,
1368
+ head_mask=None,
1369
+ inputs_embeds=None,
1370
+ labels=None,
1371
+ use_cache=None,
1372
+ output_attentions=None,
1373
+ output_hidden_states=None,
1374
+ return_dict=None,
1375
+ ):
1376
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1377
+
1378
+ transformer_outputs = self.transformer(
1379
+ input_ids,
1380
+ past_key_values=past_key_values,
1381
+ attention_mask=attention_mask,
1382
+ token_type_ids=token_type_ids,
1383
+ position_ids=position_ids,
1384
+ head_mask=head_mask,
1385
+ inputs_embeds=inputs_embeds,
1386
+ use_cache=use_cache,
1387
+ output_attentions=output_attentions,
1388
+ output_hidden_states=output_hidden_states,
1389
+ return_dict=return_dict,
1390
+ )
1391
+
1392
+ hidden_states = transformer_outputs[0]
1393
+ hidden_states = self.dropout(hidden_states)
1394
+ logits = self.classifier(hidden_states)
1395
+
1396
+ loss = None
1397
+ if labels is not None:
1398
+ loss_fct = CrossEntropyLoss()
1399
+ # Only keep active parts of the loss
1400
+ if attention_mask is not None:
1401
+ active_loss = attention_mask.view(-1) == 1
1402
+ active_logits = logits.view(-1, self.num_labels)
1403
+ active_labels = torch.where(
1404
+ active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels)
1405
+ )
1406
+ loss = loss_fct(active_logits, active_labels)
1407
+ else:
1408
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1409
+
1410
+ if not return_dict:
1411
+ output = (logits,) + transformer_outputs[2:]
1412
+ return ((loss,) + output) if loss is not None else output
1413
+
1414
+ return TokenClassifierOutput(
1415
+ loss=loss,
1416
+ logits=logits,
1417
+ hidden_states=transformer_outputs.hidden_states,
1418
+ attentions=transformer_outputs.attentions,
1419
+ )
1420
+
1421
+ def get_submodule(module, target: str) -> "Module":
1422
+ if target == "":
1423
+ return module
1424
+
1425
+ atoms: List[str] = target.split(".")
1426
+ mod: torch.nn.Module = module
1427
+
1428
+ for item in atoms:
1429
+
1430
+ if not hasattr(mod, item):
1431
+ raise AttributeError(mod._get_name() + " has no "
1432
+ "attribute `" + item + "`")
1433
+
1434
+ mod = getattr(mod, item)
1435
+
1436
+ if not isinstance(mod, torch.nn.Module):
1437
+ raise AttributeError("`" + item + "` is not "
1438
+ "an nn.Module")
1439
+
1440
+ return mod
1441
+
1442
+
1443
+ def get_parameter(module, target: str) -> "Parameter":
1444
+ module_path, _, param_name = target.rpartition(".")
1445
+
1446
+ mod: torch.nn.Module = get_submodule(module, module_path)
1447
+
1448
+ if not hasattr(mod, param_name):
1449
+ raise AttributeError(mod._get_name() + " has no attribute `"
1450
+ + param_name + "`")
1451
+
1452
+ param: torch.nn.Parameter = getattr(mod, param_name)
1453
+
1454
+ if not isinstance(param, torch.nn.Parameter):
1455
+ raise AttributeError("`" + param_name + "` is not an "
1456
+ "nn.Parameter")
1457
+
1458
+ 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)