yangheng commited on
Commit
28be5b3
·
verified ·
1 Parent(s): 20504c7

Upload 9 files

Browse files
config.json ADDED
@@ -0,0 +1,1882 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "OmniGenomefold_config": null,
3
+ "architectures": [
4
+ "OmniGenomeModel"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_omnigenome.OmniGenomeConfig",
9
+ "AutoModel": "modeling_omnigenome.OmniGenomeModel",
10
+ "AutoModelForMaskedLM": "modeling_omnigenome.OmniGenomeForMaskedLM",
11
+ "AutoModelForSeq2SeqLM": "modeling_omnigenome.OmniGenomeForSeq2SeqLM",
12
+ "AutoModelForSequenceClassification": "modeling_omnigenome.OmniGenomeForSequenceClassification",
13
+ "AutoModelForTokenClassification": "modeling_omnigenome.OmniGenomeForTokenClassification"
14
+ },
15
+ "classifier_dropout": null,
16
+ "dtype": "float16",
17
+ "emb_layer_norm_before": false,
18
+ "hidden_act": "gelu",
19
+ "hidden_dropout_prob": 0,
20
+ "hidden_size": 480,
21
+ "id2label": {
22
+ "0": "0",
23
+ "1": "1",
24
+ "2": "2",
25
+ "3": "3",
26
+ "4": "4",
27
+ "5": "5",
28
+ "6": "6",
29
+ "7": "7",
30
+ "8": "8",
31
+ "9": "9",
32
+ "10": "10",
33
+ "11": "11",
34
+ "12": "12",
35
+ "13": "13",
36
+ "14": "14",
37
+ "15": "15",
38
+ "16": "16",
39
+ "17": "17",
40
+ "18": "18",
41
+ "19": "19",
42
+ "20": "20",
43
+ "21": "21",
44
+ "22": "22",
45
+ "23": "23",
46
+ "24": "24",
47
+ "25": "25",
48
+ "26": "26",
49
+ "27": "27",
50
+ "28": "28",
51
+ "29": "29",
52
+ "30": "30",
53
+ "31": "31",
54
+ "32": "32",
55
+ "33": "33",
56
+ "34": "34",
57
+ "35": "35",
58
+ "36": "36",
59
+ "37": "37",
60
+ "38": "38",
61
+ "39": "39",
62
+ "40": "40",
63
+ "41": "41",
64
+ "42": "42",
65
+ "43": "43",
66
+ "44": "44",
67
+ "45": "45",
68
+ "46": "46",
69
+ "47": "47",
70
+ "48": "48",
71
+ "49": "49",
72
+ "50": "50",
73
+ "51": "51",
74
+ "52": "52",
75
+ "53": "53",
76
+ "54": "54",
77
+ "55": "55",
78
+ "56": "56",
79
+ "57": "57",
80
+ "58": "58",
81
+ "59": "59",
82
+ "60": "60",
83
+ "61": "61",
84
+ "62": "62",
85
+ "63": "63",
86
+ "64": "64",
87
+ "65": "65",
88
+ "66": "66",
89
+ "67": "67",
90
+ "68": "68",
91
+ "69": "69",
92
+ "70": "70",
93
+ "71": "71",
94
+ "72": "72",
95
+ "73": "73",
96
+ "74": "74",
97
+ "75": "75",
98
+ "76": "76",
99
+ "77": "77",
100
+ "78": "78",
101
+ "79": "79",
102
+ "80": "80",
103
+ "81": "81",
104
+ "82": "82",
105
+ "83": "83",
106
+ "84": "84",
107
+ "85": "85",
108
+ "86": "86",
109
+ "87": "87",
110
+ "88": "88",
111
+ "89": "89",
112
+ "90": "90",
113
+ "91": "91",
114
+ "92": "92",
115
+ "93": "93",
116
+ "94": "94",
117
+ "95": "95",
118
+ "96": "96",
119
+ "97": "97",
120
+ "98": "98",
121
+ "99": "99",
122
+ "100": "100",
123
+ "101": "101",
124
+ "102": "102",
125
+ "103": "103",
126
+ "104": "104",
127
+ "105": "105",
128
+ "106": "106",
129
+ "107": "107",
130
+ "108": "108",
131
+ "109": "109",
132
+ "110": "110",
133
+ "111": "111",
134
+ "112": "112",
135
+ "113": "113",
136
+ "114": "114",
137
+ "115": "115",
138
+ "116": "116",
139
+ "117": "117",
140
+ "118": "118",
141
+ "119": "119",
142
+ "120": "120",
143
+ "121": "121",
144
+ "122": "122",
145
+ "123": "123",
146
+ "124": "124",
147
+ "125": "125",
148
+ "126": "126",
149
+ "127": "127",
150
+ "128": "128",
151
+ "129": "129",
152
+ "130": "130",
153
+ "131": "131",
154
+ "132": "132",
155
+ "133": "133",
156
+ "134": "134",
157
+ "135": "135",
158
+ "136": "136",
159
+ "137": "137",
160
+ "138": "138",
161
+ "139": "139",
162
+ "140": "140",
163
+ "141": "141",
164
+ "142": "142",
165
+ "143": "143",
166
+ "144": "144",
167
+ "145": "145",
168
+ "146": "146",
169
+ "147": "147",
170
+ "148": "148",
171
+ "149": "149",
172
+ "150": "150",
173
+ "151": "151",
174
+ "152": "152",
175
+ "153": "153",
176
+ "154": "154",
177
+ "155": "155",
178
+ "156": "156",
179
+ "157": "157",
180
+ "158": "158",
181
+ "159": "159",
182
+ "160": "160",
183
+ "161": "161",
184
+ "162": "162",
185
+ "163": "163",
186
+ "164": "164",
187
+ "165": "165",
188
+ "166": "166",
189
+ "167": "167",
190
+ "168": "168",
191
+ "169": "169",
192
+ "170": "170",
193
+ "171": "171",
194
+ "172": "172",
195
+ "173": "173",
196
+ "174": "174",
197
+ "175": "175",
198
+ "176": "176",
199
+ "177": "177",
200
+ "178": "178",
201
+ "179": "179",
202
+ "180": "180",
203
+ "181": "181",
204
+ "182": "182",
205
+ "183": "183",
206
+ "184": "184",
207
+ "185": "185",
208
+ "186": "186",
209
+ "187": "187",
210
+ "188": "188",
211
+ "189": "189",
212
+ "190": "190",
213
+ "191": "191",
214
+ "192": "192",
215
+ "193": "193",
216
+ "194": "194",
217
+ "195": "195",
218
+ "196": "196",
219
+ "197": "197",
220
+ "198": "198",
221
+ "199": "199",
222
+ "200": "200",
223
+ "201": "201",
224
+ "202": "202",
225
+ "203": "203",
226
+ "204": "204",
227
+ "205": "205",
228
+ "206": "206",
229
+ "207": "207",
230
+ "208": "208",
231
+ "209": "209",
232
+ "210": "210",
233
+ "211": "211",
234
+ "212": "212",
235
+ "213": "213",
236
+ "214": "214",
237
+ "215": "215",
238
+ "216": "216",
239
+ "217": "217",
240
+ "218": "218",
241
+ "219": "219",
242
+ "220": "220",
243
+ "221": "221",
244
+ "222": "222",
245
+ "223": "223",
246
+ "224": "224",
247
+ "225": "225",
248
+ "226": "226",
249
+ "227": "227",
250
+ "228": "228",
251
+ "229": "229",
252
+ "230": "230",
253
+ "231": "231",
254
+ "232": "232",
255
+ "233": "233",
256
+ "234": "234",
257
+ "235": "235",
258
+ "236": "236",
259
+ "237": "237",
260
+ "238": "238",
261
+ "239": "239",
262
+ "240": "240",
263
+ "241": "241",
264
+ "242": "242",
265
+ "243": "243",
266
+ "244": "244",
267
+ "245": "245",
268
+ "246": "246",
269
+ "247": "247",
270
+ "248": "248",
271
+ "249": "249",
272
+ "250": "250",
273
+ "251": "251",
274
+ "252": "252",
275
+ "253": "253",
276
+ "254": "254",
277
+ "255": "255",
278
+ "256": "256",
279
+ "257": "257",
280
+ "258": "258",
281
+ "259": "259",
282
+ "260": "260",
283
+ "261": "261",
284
+ "262": "262",
285
+ "263": "263",
286
+ "264": "264",
287
+ "265": "265",
288
+ "266": "266",
289
+ "267": "267",
290
+ "268": "268",
291
+ "269": "269",
292
+ "270": "270",
293
+ "271": "271",
294
+ "272": "272",
295
+ "273": "273",
296
+ "274": "274",
297
+ "275": "275",
298
+ "276": "276",
299
+ "277": "277",
300
+ "278": "278",
301
+ "279": "279",
302
+ "280": "280",
303
+ "281": "281",
304
+ "282": "282",
305
+ "283": "283",
306
+ "284": "284",
307
+ "285": "285",
308
+ "286": "286",
309
+ "287": "287",
310
+ "288": "288",
311
+ "289": "289",
312
+ "290": "290",
313
+ "291": "291",
314
+ "292": "292",
315
+ "293": "293",
316
+ "294": "294",
317
+ "295": "295",
318
+ "296": "296",
319
+ "297": "297",
320
+ "298": "298",
321
+ "299": "299",
322
+ "300": "300",
323
+ "301": "301",
324
+ "302": "302",
325
+ "303": "303",
326
+ "304": "304",
327
+ "305": "305",
328
+ "306": "306",
329
+ "307": "307",
330
+ "308": "308",
331
+ "309": "309",
332
+ "310": "310",
333
+ "311": "311",
334
+ "312": "312",
335
+ "313": "313",
336
+ "314": "314",
337
+ "315": "315",
338
+ "316": "316",
339
+ "317": "317",
340
+ "318": "318",
341
+ "319": "319",
342
+ "320": "320",
343
+ "321": "321",
344
+ "322": "322",
345
+ "323": "323",
346
+ "324": "324",
347
+ "325": "325",
348
+ "326": "326",
349
+ "327": "327",
350
+ "328": "328",
351
+ "329": "329",
352
+ "330": "330",
353
+ "331": "331",
354
+ "332": "332",
355
+ "333": "333",
356
+ "334": "334",
357
+ "335": "335",
358
+ "336": "336",
359
+ "337": "337",
360
+ "338": "338",
361
+ "339": "339",
362
+ "340": "340",
363
+ "341": "341",
364
+ "342": "342",
365
+ "343": "343",
366
+ "344": "344",
367
+ "345": "345",
368
+ "346": "346",
369
+ "347": "347",
370
+ "348": "348",
371
+ "349": "349",
372
+ "350": "350",
373
+ "351": "351",
374
+ "352": "352",
375
+ "353": "353",
376
+ "354": "354",
377
+ "355": "355",
378
+ "356": "356",
379
+ "357": "357",
380
+ "358": "358",
381
+ "359": "359",
382
+ "360": "360",
383
+ "361": "361",
384
+ "362": "362",
385
+ "363": "363",
386
+ "364": "364",
387
+ "365": "365",
388
+ "366": "366",
389
+ "367": "367",
390
+ "368": "368",
391
+ "369": "369",
392
+ "370": "370",
393
+ "371": "371",
394
+ "372": "372",
395
+ "373": "373",
396
+ "374": "374",
397
+ "375": "375",
398
+ "376": "376",
399
+ "377": "377",
400
+ "378": "378",
401
+ "379": "379",
402
+ "380": "380",
403
+ "381": "381",
404
+ "382": "382",
405
+ "383": "383",
406
+ "384": "384",
407
+ "385": "385",
408
+ "386": "386",
409
+ "387": "387",
410
+ "388": "388",
411
+ "389": "389",
412
+ "390": "390",
413
+ "391": "391",
414
+ "392": "392",
415
+ "393": "393",
416
+ "394": "394",
417
+ "395": "395",
418
+ "396": "396",
419
+ "397": "397",
420
+ "398": "398",
421
+ "399": "399",
422
+ "400": "400",
423
+ "401": "401",
424
+ "402": "402",
425
+ "403": "403",
426
+ "404": "404",
427
+ "405": "405",
428
+ "406": "406",
429
+ "407": "407",
430
+ "408": "408",
431
+ "409": "409",
432
+ "410": "410",
433
+ "411": "411",
434
+ "412": "412",
435
+ "413": "413",
436
+ "414": "414",
437
+ "415": "415",
438
+ "416": "416",
439
+ "417": "417",
440
+ "418": "418",
441
+ "419": "419",
442
+ "420": "420",
443
+ "421": "421",
444
+ "422": "422",
445
+ "423": "423",
446
+ "424": "424",
447
+ "425": "425",
448
+ "426": "426",
449
+ "427": "427",
450
+ "428": "428",
451
+ "429": "429",
452
+ "430": "430",
453
+ "431": "431",
454
+ "432": "432",
455
+ "433": "433",
456
+ "434": "434",
457
+ "435": "435",
458
+ "436": "436",
459
+ "437": "437",
460
+ "438": "438",
461
+ "439": "439",
462
+ "440": "440",
463
+ "441": "441",
464
+ "442": "442",
465
+ "443": "443",
466
+ "444": "444",
467
+ "445": "445",
468
+ "446": "446",
469
+ "447": "447",
470
+ "448": "448",
471
+ "449": "449",
472
+ "450": "450",
473
+ "451": "451",
474
+ "452": "452",
475
+ "453": "453",
476
+ "454": "454",
477
+ "455": "455",
478
+ "456": "456",
479
+ "457": "457",
480
+ "458": "458",
481
+ "459": "459",
482
+ "460": "460",
483
+ "461": "461",
484
+ "462": "462",
485
+ "463": "463",
486
+ "464": "464",
487
+ "465": "465",
488
+ "466": "466",
489
+ "467": "467",
490
+ "468": "468",
491
+ "469": "469",
492
+ "470": "470",
493
+ "471": "471",
494
+ "472": "472",
495
+ "473": "473",
496
+ "474": "474",
497
+ "475": "475",
498
+ "476": "476",
499
+ "477": "477",
500
+ "478": "478",
501
+ "479": "479",
502
+ "480": "480",
503
+ "481": "481",
504
+ "482": "482",
505
+ "483": "483",
506
+ "484": "484",
507
+ "485": "485",
508
+ "486": "486",
509
+ "487": "487",
510
+ "488": "488",
511
+ "489": "489",
512
+ "490": "490",
513
+ "491": "491",
514
+ "492": "492",
515
+ "493": "493",
516
+ "494": "494",
517
+ "495": "495",
518
+ "496": "496",
519
+ "497": "497",
520
+ "498": "498",
521
+ "499": "499",
522
+ "500": "500",
523
+ "501": "501",
524
+ "502": "502",
525
+ "503": "503",
526
+ "504": "504",
527
+ "505": "505",
528
+ "506": "506",
529
+ "507": "507",
530
+ "508": "508",
531
+ "509": "509",
532
+ "510": "510",
533
+ "511": "511",
534
+ "512": "512",
535
+ "513": "513",
536
+ "514": "514",
537
+ "515": "515",
538
+ "516": "516",
539
+ "517": "517",
540
+ "518": "518",
541
+ "519": "519",
542
+ "520": "520",
543
+ "521": "521",
544
+ "522": "522",
545
+ "523": "523",
546
+ "524": "524",
547
+ "525": "525",
548
+ "526": "526",
549
+ "527": "527",
550
+ "528": "528",
551
+ "529": "529",
552
+ "530": "530",
553
+ "531": "531",
554
+ "532": "532",
555
+ "533": "533",
556
+ "534": "534",
557
+ "535": "535",
558
+ "536": "536",
559
+ "537": "537",
560
+ "538": "538",
561
+ "539": "539",
562
+ "540": "540",
563
+ "541": "541",
564
+ "542": "542",
565
+ "543": "543",
566
+ "544": "544",
567
+ "545": "545",
568
+ "546": "546",
569
+ "547": "547",
570
+ "548": "548",
571
+ "549": "549",
572
+ "550": "550",
573
+ "551": "551",
574
+ "552": "552",
575
+ "553": "553",
576
+ "554": "554",
577
+ "555": "555",
578
+ "556": "556",
579
+ "557": "557",
580
+ "558": "558",
581
+ "559": "559",
582
+ "560": "560",
583
+ "561": "561",
584
+ "562": "562",
585
+ "563": "563",
586
+ "564": "564",
587
+ "565": "565",
588
+ "566": "566",
589
+ "567": "567",
590
+ "568": "568",
591
+ "569": "569",
592
+ "570": "570",
593
+ "571": "571",
594
+ "572": "572",
595
+ "573": "573",
596
+ "574": "574",
597
+ "575": "575",
598
+ "576": "576",
599
+ "577": "577",
600
+ "578": "578",
601
+ "579": "579",
602
+ "580": "580",
603
+ "581": "581",
604
+ "582": "582",
605
+ "583": "583",
606
+ "584": "584",
607
+ "585": "585",
608
+ "586": "586",
609
+ "587": "587",
610
+ "588": "588",
611
+ "589": "589",
612
+ "590": "590",
613
+ "591": "591",
614
+ "592": "592",
615
+ "593": "593",
616
+ "594": "594",
617
+ "595": "595",
618
+ "596": "596",
619
+ "597": "597",
620
+ "598": "598",
621
+ "599": "599",
622
+ "600": "600",
623
+ "601": "601",
624
+ "602": "602",
625
+ "603": "603",
626
+ "604": "604",
627
+ "605": "605",
628
+ "606": "606",
629
+ "607": "607",
630
+ "608": "608",
631
+ "609": "609",
632
+ "610": "610",
633
+ "611": "611",
634
+ "612": "612",
635
+ "613": "613",
636
+ "614": "614",
637
+ "615": "615",
638
+ "616": "616",
639
+ "617": "617",
640
+ "618": "618",
641
+ "619": "619",
642
+ "620": "620",
643
+ "621": "621",
644
+ "622": "622",
645
+ "623": "623",
646
+ "624": "624",
647
+ "625": "625",
648
+ "626": "626",
649
+ "627": "627",
650
+ "628": "628",
651
+ "629": "629",
652
+ "630": "630",
653
+ "631": "631",
654
+ "632": "632",
655
+ "633": "633",
656
+ "634": "634",
657
+ "635": "635",
658
+ "636": "636",
659
+ "637": "637",
660
+ "638": "638",
661
+ "639": "639",
662
+ "640": "640",
663
+ "641": "641",
664
+ "642": "642",
665
+ "643": "643",
666
+ "644": "644",
667
+ "645": "645",
668
+ "646": "646",
669
+ "647": "647",
670
+ "648": "648",
671
+ "649": "649",
672
+ "650": "650",
673
+ "651": "651",
674
+ "652": "652",
675
+ "653": "653",
676
+ "654": "654",
677
+ "655": "655",
678
+ "656": "656",
679
+ "657": "657",
680
+ "658": "658",
681
+ "659": "659",
682
+ "660": "660",
683
+ "661": "661",
684
+ "662": "662",
685
+ "663": "663",
686
+ "664": "664",
687
+ "665": "665",
688
+ "666": "666",
689
+ "667": "667",
690
+ "668": "668",
691
+ "669": "669",
692
+ "670": "670",
693
+ "671": "671",
694
+ "672": "672",
695
+ "673": "673",
696
+ "674": "674",
697
+ "675": "675",
698
+ "676": "676",
699
+ "677": "677",
700
+ "678": "678",
701
+ "679": "679",
702
+ "680": "680",
703
+ "681": "681",
704
+ "682": "682",
705
+ "683": "683",
706
+ "684": "684",
707
+ "685": "685",
708
+ "686": "686",
709
+ "687": "687",
710
+ "688": "688",
711
+ "689": "689",
712
+ "690": "690",
713
+ "691": "691",
714
+ "692": "692",
715
+ "693": "693",
716
+ "694": "694",
717
+ "695": "695",
718
+ "696": "696",
719
+ "697": "697",
720
+ "698": "698",
721
+ "699": "699",
722
+ "700": "700",
723
+ "701": "701",
724
+ "702": "702",
725
+ "703": "703",
726
+ "704": "704",
727
+ "705": "705",
728
+ "706": "706",
729
+ "707": "707",
730
+ "708": "708",
731
+ "709": "709",
732
+ "710": "710",
733
+ "711": "711",
734
+ "712": "712",
735
+ "713": "713",
736
+ "714": "714",
737
+ "715": "715",
738
+ "716": "716",
739
+ "717": "717",
740
+ "718": "718",
741
+ "719": "719",
742
+ "720": "720",
743
+ "721": "721",
744
+ "722": "722",
745
+ "723": "723",
746
+ "724": "724",
747
+ "725": "725",
748
+ "726": "726",
749
+ "727": "727",
750
+ "728": "728",
751
+ "729": "729",
752
+ "730": "730",
753
+ "731": "731",
754
+ "732": "732",
755
+ "733": "733",
756
+ "734": "734",
757
+ "735": "735",
758
+ "736": "736",
759
+ "737": "737",
760
+ "738": "738",
761
+ "739": "739",
762
+ "740": "740",
763
+ "741": "741",
764
+ "742": "742",
765
+ "743": "743",
766
+ "744": "744",
767
+ "745": "745",
768
+ "746": "746",
769
+ "747": "747",
770
+ "748": "748",
771
+ "749": "749",
772
+ "750": "750",
773
+ "751": "751",
774
+ "752": "752",
775
+ "753": "753",
776
+ "754": "754",
777
+ "755": "755",
778
+ "756": "756",
779
+ "757": "757",
780
+ "758": "758",
781
+ "759": "759",
782
+ "760": "760",
783
+ "761": "761",
784
+ "762": "762",
785
+ "763": "763",
786
+ "764": "764",
787
+ "765": "765",
788
+ "766": "766",
789
+ "767": "767",
790
+ "768": "768",
791
+ "769": "769",
792
+ "770": "770",
793
+ "771": "771",
794
+ "772": "772",
795
+ "773": "773",
796
+ "774": "774",
797
+ "775": "775",
798
+ "776": "776",
799
+ "777": "777",
800
+ "778": "778",
801
+ "779": "779",
802
+ "780": "780",
803
+ "781": "781",
804
+ "782": "782",
805
+ "783": "783",
806
+ "784": "784",
807
+ "785": "785",
808
+ "786": "786",
809
+ "787": "787",
810
+ "788": "788",
811
+ "789": "789",
812
+ "790": "790",
813
+ "791": "791",
814
+ "792": "792",
815
+ "793": "793",
816
+ "794": "794",
817
+ "795": "795",
818
+ "796": "796",
819
+ "797": "797",
820
+ "798": "798",
821
+ "799": "799",
822
+ "800": "800",
823
+ "801": "801",
824
+ "802": "802",
825
+ "803": "803",
826
+ "804": "804",
827
+ "805": "805",
828
+ "806": "806",
829
+ "807": "807",
830
+ "808": "808",
831
+ "809": "809",
832
+ "810": "810",
833
+ "811": "811",
834
+ "812": "812",
835
+ "813": "813",
836
+ "814": "814",
837
+ "815": "815",
838
+ "816": "816",
839
+ "817": "817",
840
+ "818": "818",
841
+ "819": "819",
842
+ "820": "820",
843
+ "821": "821",
844
+ "822": "822",
845
+ "823": "823",
846
+ "824": "824",
847
+ "825": "825",
848
+ "826": "826",
849
+ "827": "827",
850
+ "828": "828",
851
+ "829": "829",
852
+ "830": "830",
853
+ "831": "831",
854
+ "832": "832",
855
+ "833": "833",
856
+ "834": "834",
857
+ "835": "835",
858
+ "836": "836",
859
+ "837": "837",
860
+ "838": "838",
861
+ "839": "839",
862
+ "840": "840",
863
+ "841": "841",
864
+ "842": "842",
865
+ "843": "843",
866
+ "844": "844",
867
+ "845": "845",
868
+ "846": "846",
869
+ "847": "847",
870
+ "848": "848",
871
+ "849": "849",
872
+ "850": "850",
873
+ "851": "851",
874
+ "852": "852",
875
+ "853": "853",
876
+ "854": "854",
877
+ "855": "855",
878
+ "856": "856",
879
+ "857": "857",
880
+ "858": "858",
881
+ "859": "859",
882
+ "860": "860",
883
+ "861": "861",
884
+ "862": "862",
885
+ "863": "863",
886
+ "864": "864",
887
+ "865": "865",
888
+ "866": "866",
889
+ "867": "867",
890
+ "868": "868",
891
+ "869": "869",
892
+ "870": "870",
893
+ "871": "871",
894
+ "872": "872",
895
+ "873": "873",
896
+ "874": "874",
897
+ "875": "875",
898
+ "876": "876",
899
+ "877": "877",
900
+ "878": "878",
901
+ "879": "879",
902
+ "880": "880",
903
+ "881": "881",
904
+ "882": "882",
905
+ "883": "883",
906
+ "884": "884",
907
+ "885": "885",
908
+ "886": "886",
909
+ "887": "887",
910
+ "888": "888",
911
+ "889": "889",
912
+ "890": "890",
913
+ "891": "891",
914
+ "892": "892",
915
+ "893": "893",
916
+ "894": "894",
917
+ "895": "895",
918
+ "896": "896",
919
+ "897": "897",
920
+ "898": "898",
921
+ "899": "899",
922
+ "900": "900",
923
+ "901": "901",
924
+ "902": "902",
925
+ "903": "903",
926
+ "904": "904",
927
+ "905": "905",
928
+ "906": "906",
929
+ "907": "907",
930
+ "908": "908",
931
+ "909": "909",
932
+ "910": "910",
933
+ "911": "911",
934
+ "912": "912",
935
+ "913": "913",
936
+ "914": "914",
937
+ "915": "915",
938
+ "916": "916",
939
+ "917": "917",
940
+ "918": "918"
941
+ },
942
+ "initializer_range": 0.02,
943
+ "intermediate_size": 2400,
944
+ "is_folding_model": false,
945
+ "label2id": {
946
+ "0": 0,
947
+ "1": 1,
948
+ "10": 10,
949
+ "100": 100,
950
+ "101": 101,
951
+ "102": 102,
952
+ "103": 103,
953
+ "104": 104,
954
+ "105": 105,
955
+ "106": 106,
956
+ "107": 107,
957
+ "108": 108,
958
+ "109": 109,
959
+ "11": 11,
960
+ "110": 110,
961
+ "111": 111,
962
+ "112": 112,
963
+ "113": 113,
964
+ "114": 114,
965
+ "115": 115,
966
+ "116": 116,
967
+ "117": 117,
968
+ "118": 118,
969
+ "119": 119,
970
+ "12": 12,
971
+ "120": 120,
972
+ "121": 121,
973
+ "122": 122,
974
+ "123": 123,
975
+ "124": 124,
976
+ "125": 125,
977
+ "126": 126,
978
+ "127": 127,
979
+ "128": 128,
980
+ "129": 129,
981
+ "13": 13,
982
+ "130": 130,
983
+ "131": 131,
984
+ "132": 132,
985
+ "133": 133,
986
+ "134": 134,
987
+ "135": 135,
988
+ "136": 136,
989
+ "137": 137,
990
+ "138": 138,
991
+ "139": 139,
992
+ "14": 14,
993
+ "140": 140,
994
+ "141": 141,
995
+ "142": 142,
996
+ "143": 143,
997
+ "144": 144,
998
+ "145": 145,
999
+ "146": 146,
1000
+ "147": 147,
1001
+ "148": 148,
1002
+ "149": 149,
1003
+ "15": 15,
1004
+ "150": 150,
1005
+ "151": 151,
1006
+ "152": 152,
1007
+ "153": 153,
1008
+ "154": 154,
1009
+ "155": 155,
1010
+ "156": 156,
1011
+ "157": 157,
1012
+ "158": 158,
1013
+ "159": 159,
1014
+ "16": 16,
1015
+ "160": 160,
1016
+ "161": 161,
1017
+ "162": 162,
1018
+ "163": 163,
1019
+ "164": 164,
1020
+ "165": 165,
1021
+ "166": 166,
1022
+ "167": 167,
1023
+ "168": 168,
1024
+ "169": 169,
1025
+ "17": 17,
1026
+ "170": 170,
1027
+ "171": 171,
1028
+ "172": 172,
1029
+ "173": 173,
1030
+ "174": 174,
1031
+ "175": 175,
1032
+ "176": 176,
1033
+ "177": 177,
1034
+ "178": 178,
1035
+ "179": 179,
1036
+ "18": 18,
1037
+ "180": 180,
1038
+ "181": 181,
1039
+ "182": 182,
1040
+ "183": 183,
1041
+ "184": 184,
1042
+ "185": 185,
1043
+ "186": 186,
1044
+ "187": 187,
1045
+ "188": 188,
1046
+ "189": 189,
1047
+ "19": 19,
1048
+ "190": 190,
1049
+ "191": 191,
1050
+ "192": 192,
1051
+ "193": 193,
1052
+ "194": 194,
1053
+ "195": 195,
1054
+ "196": 196,
1055
+ "197": 197,
1056
+ "198": 198,
1057
+ "199": 199,
1058
+ "2": 2,
1059
+ "20": 20,
1060
+ "200": 200,
1061
+ "201": 201,
1062
+ "202": 202,
1063
+ "203": 203,
1064
+ "204": 204,
1065
+ "205": 205,
1066
+ "206": 206,
1067
+ "207": 207,
1068
+ "208": 208,
1069
+ "209": 209,
1070
+ "21": 21,
1071
+ "210": 210,
1072
+ "211": 211,
1073
+ "212": 212,
1074
+ "213": 213,
1075
+ "214": 214,
1076
+ "215": 215,
1077
+ "216": 216,
1078
+ "217": 217,
1079
+ "218": 218,
1080
+ "219": 219,
1081
+ "22": 22,
1082
+ "220": 220,
1083
+ "221": 221,
1084
+ "222": 222,
1085
+ "223": 223,
1086
+ "224": 224,
1087
+ "225": 225,
1088
+ "226": 226,
1089
+ "227": 227,
1090
+ "228": 228,
1091
+ "229": 229,
1092
+ "23": 23,
1093
+ "230": 230,
1094
+ "231": 231,
1095
+ "232": 232,
1096
+ "233": 233,
1097
+ "234": 234,
1098
+ "235": 235,
1099
+ "236": 236,
1100
+ "237": 237,
1101
+ "238": 238,
1102
+ "239": 239,
1103
+ "24": 24,
1104
+ "240": 240,
1105
+ "241": 241,
1106
+ "242": 242,
1107
+ "243": 243,
1108
+ "244": 244,
1109
+ "245": 245,
1110
+ "246": 246,
1111
+ "247": 247,
1112
+ "248": 248,
1113
+ "249": 249,
1114
+ "25": 25,
1115
+ "250": 250,
1116
+ "251": 251,
1117
+ "252": 252,
1118
+ "253": 253,
1119
+ "254": 254,
1120
+ "255": 255,
1121
+ "256": 256,
1122
+ "257": 257,
1123
+ "258": 258,
1124
+ "259": 259,
1125
+ "26": 26,
1126
+ "260": 260,
1127
+ "261": 261,
1128
+ "262": 262,
1129
+ "263": 263,
1130
+ "264": 264,
1131
+ "265": 265,
1132
+ "266": 266,
1133
+ "267": 267,
1134
+ "268": 268,
1135
+ "269": 269,
1136
+ "27": 27,
1137
+ "270": 270,
1138
+ "271": 271,
1139
+ "272": 272,
1140
+ "273": 273,
1141
+ "274": 274,
1142
+ "275": 275,
1143
+ "276": 276,
1144
+ "277": 277,
1145
+ "278": 278,
1146
+ "279": 279,
1147
+ "28": 28,
1148
+ "280": 280,
1149
+ "281": 281,
1150
+ "282": 282,
1151
+ "283": 283,
1152
+ "284": 284,
1153
+ "285": 285,
1154
+ "286": 286,
1155
+ "287": 287,
1156
+ "288": 288,
1157
+ "289": 289,
1158
+ "29": 29,
1159
+ "290": 290,
1160
+ "291": 291,
1161
+ "292": 292,
1162
+ "293": 293,
1163
+ "294": 294,
1164
+ "295": 295,
1165
+ "296": 296,
1166
+ "297": 297,
1167
+ "298": 298,
1168
+ "299": 299,
1169
+ "3": 3,
1170
+ "30": 30,
1171
+ "300": 300,
1172
+ "301": 301,
1173
+ "302": 302,
1174
+ "303": 303,
1175
+ "304": 304,
1176
+ "305": 305,
1177
+ "306": 306,
1178
+ "307": 307,
1179
+ "308": 308,
1180
+ "309": 309,
1181
+ "31": 31,
1182
+ "310": 310,
1183
+ "311": 311,
1184
+ "312": 312,
1185
+ "313": 313,
1186
+ "314": 314,
1187
+ "315": 315,
1188
+ "316": 316,
1189
+ "317": 317,
1190
+ "318": 318,
1191
+ "319": 319,
1192
+ "32": 32,
1193
+ "320": 320,
1194
+ "321": 321,
1195
+ "322": 322,
1196
+ "323": 323,
1197
+ "324": 324,
1198
+ "325": 325,
1199
+ "326": 326,
1200
+ "327": 327,
1201
+ "328": 328,
1202
+ "329": 329,
1203
+ "33": 33,
1204
+ "330": 330,
1205
+ "331": 331,
1206
+ "332": 332,
1207
+ "333": 333,
1208
+ "334": 334,
1209
+ "335": 335,
1210
+ "336": 336,
1211
+ "337": 337,
1212
+ "338": 338,
1213
+ "339": 339,
1214
+ "34": 34,
1215
+ "340": 340,
1216
+ "341": 341,
1217
+ "342": 342,
1218
+ "343": 343,
1219
+ "344": 344,
1220
+ "345": 345,
1221
+ "346": 346,
1222
+ "347": 347,
1223
+ "348": 348,
1224
+ "349": 349,
1225
+ "35": 35,
1226
+ "350": 350,
1227
+ "351": 351,
1228
+ "352": 352,
1229
+ "353": 353,
1230
+ "354": 354,
1231
+ "355": 355,
1232
+ "356": 356,
1233
+ "357": 357,
1234
+ "358": 358,
1235
+ "359": 359,
1236
+ "36": 36,
1237
+ "360": 360,
1238
+ "361": 361,
1239
+ "362": 362,
1240
+ "363": 363,
1241
+ "364": 364,
1242
+ "365": 365,
1243
+ "366": 366,
1244
+ "367": 367,
1245
+ "368": 368,
1246
+ "369": 369,
1247
+ "37": 37,
1248
+ "370": 370,
1249
+ "371": 371,
1250
+ "372": 372,
1251
+ "373": 373,
1252
+ "374": 374,
1253
+ "375": 375,
1254
+ "376": 376,
1255
+ "377": 377,
1256
+ "378": 378,
1257
+ "379": 379,
1258
+ "38": 38,
1259
+ "380": 380,
1260
+ "381": 381,
1261
+ "382": 382,
1262
+ "383": 383,
1263
+ "384": 384,
1264
+ "385": 385,
1265
+ "386": 386,
1266
+ "387": 387,
1267
+ "388": 388,
1268
+ "389": 389,
1269
+ "39": 39,
1270
+ "390": 390,
1271
+ "391": 391,
1272
+ "392": 392,
1273
+ "393": 393,
1274
+ "394": 394,
1275
+ "395": 395,
1276
+ "396": 396,
1277
+ "397": 397,
1278
+ "398": 398,
1279
+ "399": 399,
1280
+ "4": 4,
1281
+ "40": 40,
1282
+ "400": 400,
1283
+ "401": 401,
1284
+ "402": 402,
1285
+ "403": 403,
1286
+ "404": 404,
1287
+ "405": 405,
1288
+ "406": 406,
1289
+ "407": 407,
1290
+ "408": 408,
1291
+ "409": 409,
1292
+ "41": 41,
1293
+ "410": 410,
1294
+ "411": 411,
1295
+ "412": 412,
1296
+ "413": 413,
1297
+ "414": 414,
1298
+ "415": 415,
1299
+ "416": 416,
1300
+ "417": 417,
1301
+ "418": 418,
1302
+ "419": 419,
1303
+ "42": 42,
1304
+ "420": 420,
1305
+ "421": 421,
1306
+ "422": 422,
1307
+ "423": 423,
1308
+ "424": 424,
1309
+ "425": 425,
1310
+ "426": 426,
1311
+ "427": 427,
1312
+ "428": 428,
1313
+ "429": 429,
1314
+ "43": 43,
1315
+ "430": 430,
1316
+ "431": 431,
1317
+ "432": 432,
1318
+ "433": 433,
1319
+ "434": 434,
1320
+ "435": 435,
1321
+ "436": 436,
1322
+ "437": 437,
1323
+ "438": 438,
1324
+ "439": 439,
1325
+ "44": 44,
1326
+ "440": 440,
1327
+ "441": 441,
1328
+ "442": 442,
1329
+ "443": 443,
1330
+ "444": 444,
1331
+ "445": 445,
1332
+ "446": 446,
1333
+ "447": 447,
1334
+ "448": 448,
1335
+ "449": 449,
1336
+ "45": 45,
1337
+ "450": 450,
1338
+ "451": 451,
1339
+ "452": 452,
1340
+ "453": 453,
1341
+ "454": 454,
1342
+ "455": 455,
1343
+ "456": 456,
1344
+ "457": 457,
1345
+ "458": 458,
1346
+ "459": 459,
1347
+ "46": 46,
1348
+ "460": 460,
1349
+ "461": 461,
1350
+ "462": 462,
1351
+ "463": 463,
1352
+ "464": 464,
1353
+ "465": 465,
1354
+ "466": 466,
1355
+ "467": 467,
1356
+ "468": 468,
1357
+ "469": 469,
1358
+ "47": 47,
1359
+ "470": 470,
1360
+ "471": 471,
1361
+ "472": 472,
1362
+ "473": 473,
1363
+ "474": 474,
1364
+ "475": 475,
1365
+ "476": 476,
1366
+ "477": 477,
1367
+ "478": 478,
1368
+ "479": 479,
1369
+ "48": 48,
1370
+ "480": 480,
1371
+ "481": 481,
1372
+ "482": 482,
1373
+ "483": 483,
1374
+ "484": 484,
1375
+ "485": 485,
1376
+ "486": 486,
1377
+ "487": 487,
1378
+ "488": 488,
1379
+ "489": 489,
1380
+ "49": 49,
1381
+ "490": 490,
1382
+ "491": 491,
1383
+ "492": 492,
1384
+ "493": 493,
1385
+ "494": 494,
1386
+ "495": 495,
1387
+ "496": 496,
1388
+ "497": 497,
1389
+ "498": 498,
1390
+ "499": 499,
1391
+ "5": 5,
1392
+ "50": 50,
1393
+ "500": 500,
1394
+ "501": 501,
1395
+ "502": 502,
1396
+ "503": 503,
1397
+ "504": 504,
1398
+ "505": 505,
1399
+ "506": 506,
1400
+ "507": 507,
1401
+ "508": 508,
1402
+ "509": 509,
1403
+ "51": 51,
1404
+ "510": 510,
1405
+ "511": 511,
1406
+ "512": 512,
1407
+ "513": 513,
1408
+ "514": 514,
1409
+ "515": 515,
1410
+ "516": 516,
1411
+ "517": 517,
1412
+ "518": 518,
1413
+ "519": 519,
1414
+ "52": 52,
1415
+ "520": 520,
1416
+ "521": 521,
1417
+ "522": 522,
1418
+ "523": 523,
1419
+ "524": 524,
1420
+ "525": 525,
1421
+ "526": 526,
1422
+ "527": 527,
1423
+ "528": 528,
1424
+ "529": 529,
1425
+ "53": 53,
1426
+ "530": 530,
1427
+ "531": 531,
1428
+ "532": 532,
1429
+ "533": 533,
1430
+ "534": 534,
1431
+ "535": 535,
1432
+ "536": 536,
1433
+ "537": 537,
1434
+ "538": 538,
1435
+ "539": 539,
1436
+ "54": 54,
1437
+ "540": 540,
1438
+ "541": 541,
1439
+ "542": 542,
1440
+ "543": 543,
1441
+ "544": 544,
1442
+ "545": 545,
1443
+ "546": 546,
1444
+ "547": 547,
1445
+ "548": 548,
1446
+ "549": 549,
1447
+ "55": 55,
1448
+ "550": 550,
1449
+ "551": 551,
1450
+ "552": 552,
1451
+ "553": 553,
1452
+ "554": 554,
1453
+ "555": 555,
1454
+ "556": 556,
1455
+ "557": 557,
1456
+ "558": 558,
1457
+ "559": 559,
1458
+ "56": 56,
1459
+ "560": 560,
1460
+ "561": 561,
1461
+ "562": 562,
1462
+ "563": 563,
1463
+ "564": 564,
1464
+ "565": 565,
1465
+ "566": 566,
1466
+ "567": 567,
1467
+ "568": 568,
1468
+ "569": 569,
1469
+ "57": 57,
1470
+ "570": 570,
1471
+ "571": 571,
1472
+ "572": 572,
1473
+ "573": 573,
1474
+ "574": 574,
1475
+ "575": 575,
1476
+ "576": 576,
1477
+ "577": 577,
1478
+ "578": 578,
1479
+ "579": 579,
1480
+ "58": 58,
1481
+ "580": 580,
1482
+ "581": 581,
1483
+ "582": 582,
1484
+ "583": 583,
1485
+ "584": 584,
1486
+ "585": 585,
1487
+ "586": 586,
1488
+ "587": 587,
1489
+ "588": 588,
1490
+ "589": 589,
1491
+ "59": 59,
1492
+ "590": 590,
1493
+ "591": 591,
1494
+ "592": 592,
1495
+ "593": 593,
1496
+ "594": 594,
1497
+ "595": 595,
1498
+ "596": 596,
1499
+ "597": 597,
1500
+ "598": 598,
1501
+ "599": 599,
1502
+ "6": 6,
1503
+ "60": 60,
1504
+ "600": 600,
1505
+ "601": 601,
1506
+ "602": 602,
1507
+ "603": 603,
1508
+ "604": 604,
1509
+ "605": 605,
1510
+ "606": 606,
1511
+ "607": 607,
1512
+ "608": 608,
1513
+ "609": 609,
1514
+ "61": 61,
1515
+ "610": 610,
1516
+ "611": 611,
1517
+ "612": 612,
1518
+ "613": 613,
1519
+ "614": 614,
1520
+ "615": 615,
1521
+ "616": 616,
1522
+ "617": 617,
1523
+ "618": 618,
1524
+ "619": 619,
1525
+ "62": 62,
1526
+ "620": 620,
1527
+ "621": 621,
1528
+ "622": 622,
1529
+ "623": 623,
1530
+ "624": 624,
1531
+ "625": 625,
1532
+ "626": 626,
1533
+ "627": 627,
1534
+ "628": 628,
1535
+ "629": 629,
1536
+ "63": 63,
1537
+ "630": 630,
1538
+ "631": 631,
1539
+ "632": 632,
1540
+ "633": 633,
1541
+ "634": 634,
1542
+ "635": 635,
1543
+ "636": 636,
1544
+ "637": 637,
1545
+ "638": 638,
1546
+ "639": 639,
1547
+ "64": 64,
1548
+ "640": 640,
1549
+ "641": 641,
1550
+ "642": 642,
1551
+ "643": 643,
1552
+ "644": 644,
1553
+ "645": 645,
1554
+ "646": 646,
1555
+ "647": 647,
1556
+ "648": 648,
1557
+ "649": 649,
1558
+ "65": 65,
1559
+ "650": 650,
1560
+ "651": 651,
1561
+ "652": 652,
1562
+ "653": 653,
1563
+ "654": 654,
1564
+ "655": 655,
1565
+ "656": 656,
1566
+ "657": 657,
1567
+ "658": 658,
1568
+ "659": 659,
1569
+ "66": 66,
1570
+ "660": 660,
1571
+ "661": 661,
1572
+ "662": 662,
1573
+ "663": 663,
1574
+ "664": 664,
1575
+ "665": 665,
1576
+ "666": 666,
1577
+ "667": 667,
1578
+ "668": 668,
1579
+ "669": 669,
1580
+ "67": 67,
1581
+ "670": 670,
1582
+ "671": 671,
1583
+ "672": 672,
1584
+ "673": 673,
1585
+ "674": 674,
1586
+ "675": 675,
1587
+ "676": 676,
1588
+ "677": 677,
1589
+ "678": 678,
1590
+ "679": 679,
1591
+ "68": 68,
1592
+ "680": 680,
1593
+ "681": 681,
1594
+ "682": 682,
1595
+ "683": 683,
1596
+ "684": 684,
1597
+ "685": 685,
1598
+ "686": 686,
1599
+ "687": 687,
1600
+ "688": 688,
1601
+ "689": 689,
1602
+ "69": 69,
1603
+ "690": 690,
1604
+ "691": 691,
1605
+ "692": 692,
1606
+ "693": 693,
1607
+ "694": 694,
1608
+ "695": 695,
1609
+ "696": 696,
1610
+ "697": 697,
1611
+ "698": 698,
1612
+ "699": 699,
1613
+ "7": 7,
1614
+ "70": 70,
1615
+ "700": 700,
1616
+ "701": 701,
1617
+ "702": 702,
1618
+ "703": 703,
1619
+ "704": 704,
1620
+ "705": 705,
1621
+ "706": 706,
1622
+ "707": 707,
1623
+ "708": 708,
1624
+ "709": 709,
1625
+ "71": 71,
1626
+ "710": 710,
1627
+ "711": 711,
1628
+ "712": 712,
1629
+ "713": 713,
1630
+ "714": 714,
1631
+ "715": 715,
1632
+ "716": 716,
1633
+ "717": 717,
1634
+ "718": 718,
1635
+ "719": 719,
1636
+ "72": 72,
1637
+ "720": 720,
1638
+ "721": 721,
1639
+ "722": 722,
1640
+ "723": 723,
1641
+ "724": 724,
1642
+ "725": 725,
1643
+ "726": 726,
1644
+ "727": 727,
1645
+ "728": 728,
1646
+ "729": 729,
1647
+ "73": 73,
1648
+ "730": 730,
1649
+ "731": 731,
1650
+ "732": 732,
1651
+ "733": 733,
1652
+ "734": 734,
1653
+ "735": 735,
1654
+ "736": 736,
1655
+ "737": 737,
1656
+ "738": 738,
1657
+ "739": 739,
1658
+ "74": 74,
1659
+ "740": 740,
1660
+ "741": 741,
1661
+ "742": 742,
1662
+ "743": 743,
1663
+ "744": 744,
1664
+ "745": 745,
1665
+ "746": 746,
1666
+ "747": 747,
1667
+ "748": 748,
1668
+ "749": 749,
1669
+ "75": 75,
1670
+ "750": 750,
1671
+ "751": 751,
1672
+ "752": 752,
1673
+ "753": 753,
1674
+ "754": 754,
1675
+ "755": 755,
1676
+ "756": 756,
1677
+ "757": 757,
1678
+ "758": 758,
1679
+ "759": 759,
1680
+ "76": 76,
1681
+ "760": 760,
1682
+ "761": 761,
1683
+ "762": 762,
1684
+ "763": 763,
1685
+ "764": 764,
1686
+ "765": 765,
1687
+ "766": 766,
1688
+ "767": 767,
1689
+ "768": 768,
1690
+ "769": 769,
1691
+ "77": 77,
1692
+ "770": 770,
1693
+ "771": 771,
1694
+ "772": 772,
1695
+ "773": 773,
1696
+ "774": 774,
1697
+ "775": 775,
1698
+ "776": 776,
1699
+ "777": 777,
1700
+ "778": 778,
1701
+ "779": 779,
1702
+ "78": 78,
1703
+ "780": 780,
1704
+ "781": 781,
1705
+ "782": 782,
1706
+ "783": 783,
1707
+ "784": 784,
1708
+ "785": 785,
1709
+ "786": 786,
1710
+ "787": 787,
1711
+ "788": 788,
1712
+ "789": 789,
1713
+ "79": 79,
1714
+ "790": 790,
1715
+ "791": 791,
1716
+ "792": 792,
1717
+ "793": 793,
1718
+ "794": 794,
1719
+ "795": 795,
1720
+ "796": 796,
1721
+ "797": 797,
1722
+ "798": 798,
1723
+ "799": 799,
1724
+ "8": 8,
1725
+ "80": 80,
1726
+ "800": 800,
1727
+ "801": 801,
1728
+ "802": 802,
1729
+ "803": 803,
1730
+ "804": 804,
1731
+ "805": 805,
1732
+ "806": 806,
1733
+ "807": 807,
1734
+ "808": 808,
1735
+ "809": 809,
1736
+ "81": 81,
1737
+ "810": 810,
1738
+ "811": 811,
1739
+ "812": 812,
1740
+ "813": 813,
1741
+ "814": 814,
1742
+ "815": 815,
1743
+ "816": 816,
1744
+ "817": 817,
1745
+ "818": 818,
1746
+ "819": 819,
1747
+ "82": 82,
1748
+ "820": 820,
1749
+ "821": 821,
1750
+ "822": 822,
1751
+ "823": 823,
1752
+ "824": 824,
1753
+ "825": 825,
1754
+ "826": 826,
1755
+ "827": 827,
1756
+ "828": 828,
1757
+ "829": 829,
1758
+ "83": 83,
1759
+ "830": 830,
1760
+ "831": 831,
1761
+ "832": 832,
1762
+ "833": 833,
1763
+ "834": 834,
1764
+ "835": 835,
1765
+ "836": 836,
1766
+ "837": 837,
1767
+ "838": 838,
1768
+ "839": 839,
1769
+ "84": 84,
1770
+ "840": 840,
1771
+ "841": 841,
1772
+ "842": 842,
1773
+ "843": 843,
1774
+ "844": 844,
1775
+ "845": 845,
1776
+ "846": 846,
1777
+ "847": 847,
1778
+ "848": 848,
1779
+ "849": 849,
1780
+ "85": 85,
1781
+ "850": 850,
1782
+ "851": 851,
1783
+ "852": 852,
1784
+ "853": 853,
1785
+ "854": 854,
1786
+ "855": 855,
1787
+ "856": 856,
1788
+ "857": 857,
1789
+ "858": 858,
1790
+ "859": 859,
1791
+ "86": 86,
1792
+ "860": 860,
1793
+ "861": 861,
1794
+ "862": 862,
1795
+ "863": 863,
1796
+ "864": 864,
1797
+ "865": 865,
1798
+ "866": 866,
1799
+ "867": 867,
1800
+ "868": 868,
1801
+ "869": 869,
1802
+ "87": 87,
1803
+ "870": 870,
1804
+ "871": 871,
1805
+ "872": 872,
1806
+ "873": 873,
1807
+ "874": 874,
1808
+ "875": 875,
1809
+ "876": 876,
1810
+ "877": 877,
1811
+ "878": 878,
1812
+ "879": 879,
1813
+ "88": 88,
1814
+ "880": 880,
1815
+ "881": 881,
1816
+ "882": 882,
1817
+ "883": 883,
1818
+ "884": 884,
1819
+ "885": 885,
1820
+ "886": 886,
1821
+ "887": 887,
1822
+ "888": 888,
1823
+ "889": 889,
1824
+ "89": 89,
1825
+ "890": 890,
1826
+ "891": 891,
1827
+ "892": 892,
1828
+ "893": 893,
1829
+ "894": 894,
1830
+ "895": 895,
1831
+ "896": 896,
1832
+ "897": 897,
1833
+ "898": 898,
1834
+ "899": 899,
1835
+ "9": 9,
1836
+ "90": 90,
1837
+ "900": 900,
1838
+ "901": 901,
1839
+ "902": 902,
1840
+ "903": 903,
1841
+ "904": 904,
1842
+ "905": 905,
1843
+ "906": 906,
1844
+ "907": 907,
1845
+ "908": 908,
1846
+ "909": 909,
1847
+ "91": 91,
1848
+ "910": 910,
1849
+ "911": 911,
1850
+ "912": 912,
1851
+ "913": 913,
1852
+ "914": 914,
1853
+ "915": 915,
1854
+ "916": 916,
1855
+ "917": 917,
1856
+ "918": 918,
1857
+ "92": 92,
1858
+ "93": 93,
1859
+ "94": 94,
1860
+ "95": 95,
1861
+ "96": 96,
1862
+ "97": 97,
1863
+ "98": 98,
1864
+ "99": 99
1865
+ },
1866
+ "layer_norm_eps": 1e-05,
1867
+ "mask_token_id": 23,
1868
+ "max_position_embeddings": 1026,
1869
+ "model_type": "omnigenome",
1870
+ "num_attention_heads": 24,
1871
+ "num_generation": 50,
1872
+ "num_hidden_layers": 16,
1873
+ "num_population": 100,
1874
+ "pad_token_id": 1,
1875
+ "position_embedding_type": "rotary",
1876
+ "token_dropout": true,
1877
+ "transformers_version": "4.57.1",
1878
+ "use_cache": true,
1879
+ "verify_ss": true,
1880
+ "vocab_list": null,
1881
+ "vocab_size": 24
1882
+ }
configuration_omnigenome.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Meta and The HuggingFace Inc. team. 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
+ """ OmniGenome model configuration"""
16
+
17
+ from dataclasses import asdict, dataclass
18
+ from typing import Optional
19
+
20
+ from transformers import PretrainedConfig
21
+
22
+ from transformers.utils import logging
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+ # TODO Update this
27
+ OmniGenome_PRETRAINED_CONFIG_ARCHIVE_MAP = {
28
+ "yangheng/OmniGenome-52M": "https://huggingface.co/yangheng/OmniGenome-52M/resolve/main/config.json",
29
+ "yangheng/OmniGenome-186M": "https://huggingface.co/yangheng/OmniGenome-186M/resolve/main/config.json",
30
+ # See all OmniGenome models at https://huggingface.co/models?filter=OmniGenome
31
+ }
32
+
33
+
34
+ class OmniGenomeConfig(PretrainedConfig):
35
+ r"""
36
+ This is the configuration class to store the configuration of a [`OmniGenomeModel`]. It is used to instantiate a OmniGenome model
37
+ according to the specified arguments, defining the model architecture. Instantiating a configuration with the
38
+ defaults will yield a similar configuration to that of the OmniGenome
39
+ [yangheng/OmniGenome-52M](https://huggingface.co/yangheng/OmniGenome-52M) architecture.
40
+
41
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
42
+ documentation from [`PretrainedConfig`] for more information.
43
+
44
+
45
+ Args:
46
+ vocab_size (`int`, *optional*):
47
+ Vocabulary size of the OmniGenome model. Defines the number of different tokens that can be represented by the
48
+ `inputs_ids` passed when calling [`OmniGenomeModel`].
49
+ mask_token_id (`int`, *optional*):
50
+ The index of the mask token in the vocabulary. This must be included in the config because of the
51
+ "mask-dropout" scaling trick, which will scale the inputs depending on the number of masked tokens.
52
+ pad_token_id (`int`, *optional*):
53
+ The index of the padding token in the vocabulary. This must be included in the config because certain parts
54
+ of the OmniGenome code use this instead of the attention mask.
55
+ hidden_size (`int`, *optional*, defaults to 768):
56
+ Dimensionality of the encoder layers and the pooler layer.
57
+ num_hidden_layers (`int`, *optional*, defaults to 12):
58
+ Number of hidden layers in the Transformer encoder.
59
+ num_attention_heads (`int`, *optional*, defaults to 12):
60
+ Number of attention heads for each attention layer in the Transformer encoder.
61
+ intermediate_size (`int`, *optional*, defaults to 3072):
62
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
63
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
64
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
65
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
66
+ The dropout ratio for the attention probabilities.
67
+ max_position_embeddings (`int`, *optional*, defaults to 1026):
68
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
69
+ just in case (e.g., 512 or 1024 or 2048).
70
+ initializer_range (`float`, *optional*, defaults to 0.02):
71
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
72
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
73
+ The epsilon used by the layer normalization layers.
74
+ position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
75
+ Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query", "rotary"`.
76
+ For positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
77
+ [Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
78
+ For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
79
+ with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
80
+ is_decoder (`bool`, *optional*, defaults to `False`):
81
+ Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
82
+ use_cache (`bool`, *optional*, defaults to `True`):
83
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
84
+ relevant if `config.is_decoder=True`.
85
+ emb_layer_norm_before (`bool`, *optional*):
86
+ Whether to apply layer normalization after embeddings but before the main stem of the network.
87
+ token_dropout (`bool`, defaults to `False`):
88
+ When this is enabled, masked tokens are treated as if they had been dropped out by input dropout.
89
+
90
+ Examples:
91
+
92
+ ```python
93
+ # >>> from transformers import OmniGenomeModel, OmniGenomeConfig
94
+ #
95
+ # >>> # Initializing a OmniGenome yangheng/OmniGenome-52M style configuration >>> configuration = OmniGenomeConfig()
96
+ #
97
+ # >>> # Initializing a model from the configuration >>> model = OmniGenomeModel(configuration)
98
+ #
99
+ # >>> # Accessing the model configuration >>> configuration = model.config
100
+ ```"""
101
+
102
+ model_type = "omnigenome"
103
+
104
+ def __init__(
105
+ self,
106
+ vocab_size=None,
107
+ mask_token_id=None,
108
+ pad_token_id=None,
109
+ hidden_size=768,
110
+ num_hidden_layers=12,
111
+ num_attention_heads=12,
112
+ intermediate_size=3072,
113
+ hidden_dropout_prob=0.1,
114
+ attention_probs_dropout_prob=0.1,
115
+ max_position_embeddings=1026,
116
+ initializer_range=0.02,
117
+ layer_norm_eps=1e-12,
118
+ position_embedding_type="absolute",
119
+ use_cache=True,
120
+ emb_layer_norm_before=None,
121
+ token_dropout=False,
122
+ is_folding_model=False,
123
+ OmniGenomefold_config=None,
124
+ vocab_list=None,
125
+ **kwargs,
126
+ ):
127
+ super().__init__(
128
+ pad_token_id=pad_token_id, mask_token_id=mask_token_id, **kwargs
129
+ )
130
+
131
+ self.vocab_size = vocab_size
132
+ self.hidden_size = hidden_size
133
+ self.num_hidden_layers = num_hidden_layers
134
+ self.num_attention_heads = num_attention_heads
135
+ self.intermediate_size = intermediate_size
136
+ self.hidden_dropout_prob = hidden_dropout_prob
137
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
138
+ self.max_position_embeddings = max_position_embeddings
139
+ self.initializer_range = initializer_range
140
+ self.layer_norm_eps = layer_norm_eps
141
+ self.position_embedding_type = position_embedding_type
142
+ self.use_cache = use_cache
143
+ self.emb_layer_norm_before = emb_layer_norm_before
144
+ self.token_dropout = token_dropout
145
+ self.is_folding_model = is_folding_model
146
+ self.OmniGenomefold_config = None
147
+ self.vocab_list = None
148
+ if self.OmniGenomefold_config is not None and getattr(
149
+ self.OmniGenomefold_config, "use_OmniGenome_attn_map", False
150
+ ):
151
+ raise ValueError(
152
+ "The HuggingFace port of OmniGenomeFold does not support use_OmniGenome_attn_map at this time!"
153
+ )
154
+
155
+ def to_dict(self):
156
+ """
157
+ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
158
+
159
+ Returns:
160
+ `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
161
+ """
162
+ output = super().to_dict()
163
+ return output
164
+
165
+
166
+ @dataclass
167
+ class TrunkConfig:
168
+ num_blocks: int = 48
169
+ sequence_state_dim: int = 1024
170
+ pairwise_state_dim: int = 128
171
+ sequence_head_width: int = 32
172
+ pairwise_head_width: int = 32
173
+ position_bins: int = 32
174
+ dropout: float = 0
175
+ layer_drop: float = 0
176
+ cpu_grad_checkpoint: bool = False
177
+ max_recycles: int = 4
178
+ chunk_size: Optional[int] = 128
179
+ structure_module: "StructureModuleConfig" = None
180
+
181
+ def __post_init__(self):
182
+ if self.structure_module is None:
183
+ self.structure_module = StructureModuleConfig()
184
+ elif isinstance(self.structure_module, dict):
185
+ self.structure_module = StructureModuleConfig(**self.structure_module)
186
+
187
+ if self.max_recycles <= 0:
188
+ raise ValueError(
189
+ f"`max_recycles` should be positive, got {self.max_recycles}."
190
+ )
191
+ if self.sequence_state_dim % self.sequence_state_dim != 0:
192
+ raise ValueError(
193
+ "`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got"
194
+ f" {self.sequence_state_dim} and {self.sequence_state_dim}."
195
+ )
196
+ if self.pairwise_state_dim % self.pairwise_state_dim != 0:
197
+ raise ValueError(
198
+ "`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got"
199
+ f" {self.pairwise_state_dim} and {self.pairwise_state_dim}."
200
+ )
201
+
202
+ sequence_num_heads = self.sequence_state_dim // self.sequence_head_width
203
+ pairwise_num_heads = self.pairwise_state_dim // self.pairwise_head_width
204
+
205
+ if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width:
206
+ raise ValueError(
207
+ "`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got"
208
+ f" {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}."
209
+ )
210
+ if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width:
211
+ raise ValueError(
212
+ "`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got"
213
+ f" {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}."
214
+ )
215
+ if self.pairwise_state_dim % 2 != 0:
216
+ raise ValueError(
217
+ f"`pairwise_state_dim` should be even, got {self.pairwise_state_dim}."
218
+ )
219
+
220
+ if self.dropout >= 0.4:
221
+ raise ValueError(
222
+ f"`dropout` should not be greater than 0.4, got {self.dropout}."
223
+ )
224
+
225
+ def to_dict(self):
226
+ """
227
+ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
228
+
229
+ Returns:
230
+ `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
231
+ """
232
+ output = asdict(self)
233
+ output["structure_module"] = self.structure_module.to_dict()
234
+ return output
235
+
236
+
237
+ @dataclass
238
+ class StructureModuleConfig:
239
+ """
240
+ Args:
241
+ sequence_dim:
242
+ Single representation channel dimension
243
+ pairwise_dim:
244
+ Pair representation channel dimension
245
+ ipa_dim:
246
+ IPA hidden channel dimension
247
+ resnet_dim:
248
+ Angle resnet (Alg. 23 lines 11-14) hidden channel dimension
249
+ num_heads_ipa:
250
+ Number of IPA heads
251
+ num_qk_points:
252
+ Number of query/key points to generate during IPA
253
+ num_v_points:
254
+ Number of value points to generate during IPA
255
+ dropout_rate:
256
+ Dropout rate used throughout the layer
257
+ num_blocks:
258
+ Number of structure module blocks
259
+ num_transition_layers:
260
+ Number of layers in the single representation transition (Alg. 23 lines 8-9)
261
+ num_resnet_blocks:
262
+ Number of blocks in the angle resnet
263
+ num_angles:
264
+ Number of angles to generate in the angle resnet
265
+ trans_scale_factor:
266
+ Scale of single representation transition hidden dimension
267
+ epsilon:
268
+ Small number used in angle resnet normalization
269
+ inf:
270
+ Large number used for attention masking
271
+ """
272
+
273
+ sequence_dim: int = 384
274
+ pairwise_dim: int = 128
275
+ ipa_dim: int = 16
276
+ resnet_dim: int = 128
277
+ num_heads_ipa: int = 12
278
+ num_qk_points: int = 4
279
+ num_v_points: int = 8
280
+ dropout_rate: float = 0.1
281
+ num_blocks: int = 8
282
+ num_transition_layers: int = 1
283
+ num_resnet_blocks: int = 2
284
+ num_angles: int = 7
285
+ trans_scale_factor: int = 10
286
+ epsilon: float = 1e-8
287
+ inf: float = 1e5
288
+
289
+ def to_dict(self):
290
+ return asdict(self)
291
+
292
+
293
+ def get_default_vocab_list():
294
+ return (
295
+ "<cls>",
296
+ "<pad>",
297
+ "<eos>",
298
+ "<unk>",
299
+ "A",
300
+ "C",
301
+ "G",
302
+ "T",
303
+ "U",
304
+ "N",
305
+ " ",
306
+ "<mask>",
307
+ )
metadata.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "library_name": "omnigenbench",
3
+ "omnigenbench_version": "0.3.27alpha",
4
+ "torch_version": "2.8.0+cu128+cu12.8+gita1cb3cc05d46d198467bebbb6e8fba50a325d4e7",
5
+ "transformers_version": "4.57.1",
6
+ "model_cls": "OmniModelForMultiLabelSequenceClassification",
7
+ "dataset_cls": null,
8
+ "dataset_module": null,
9
+ "tokenizer_cls": "EsmTokenizer",
10
+ "model_name": "OmniModelForMultiLabelSequenceClassification",
11
+ "loss_fn_class": "BCELoss",
12
+ "loss_fn_module": "torch.nn.modules.loss",
13
+ "model_module": "omnigenbench.src.model.classification.model",
14
+ "custom_attrs": {
15
+ "threshold": 0.5
16
+ }
17
+ }
modeling_omnigenome.py ADDED
@@ -0,0 +1,1912 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 ColaLab-UoE (https://colalab.ai/), Meta and The HuggingFace Inc. team. 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 OmniGenome model."""
16
+ import copy
17
+ import math
18
+ import os
19
+ import random
20
+ import warnings
21
+ from dataclasses import dataclass
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import numpy as np
25
+ import torch
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+ from transformers import add_start_docstrings, PreTrainedModel
30
+
31
+ from transformers.modeling_outputs import (
32
+ BaseModelOutputWithPastAndCrossAttentions,
33
+ BaseModelOutputWithPoolingAndCrossAttentions,
34
+ MaskedLMOutput,
35
+ SequenceClassifierOutput,
36
+ TokenClassifierOutput,
37
+ )
38
+
39
+ from transformers.pytorch_utils import (
40
+ find_pruneable_heads_and_indices,
41
+ prune_linear_layer,
42
+ )
43
+
44
+ from transformers.utils import (
45
+ logging,
46
+ add_code_sample_docstrings,
47
+ add_start_docstrings_to_model_forward, ModelOutput,
48
+ )
49
+
50
+ from .configuration_omnigenome import OmniGenomeConfig
51
+
52
+ try:
53
+ from flash_attn import flash_attn_func
54
+ except ImportError:
55
+ flash_attn_func = None
56
+
57
+ logger = logging.get_logger(__name__)
58
+
59
+ _CHECKPOINT_FOR_DOC = "yangheng/OmniGenome-52M"
60
+ _CONFIG_FOR_DOC = "OmniGenomeConfig"
61
+
62
+ OmniGenome_PRETRAINED_MODEL_ARCHIVE_LIST = [
63
+ "yangheng/OmniGenome-52M",
64
+ # This is not a complete list of all OmniGenome models!
65
+ # See all OmniGenome models at https://huggingface.co/models?filter=OmniGenome
66
+ ]
67
+
68
+
69
+ def rotate_half(x):
70
+ x1, x2 = x.chunk(2, dim=-1)
71
+ return torch.cat((-x2, x1), dim=-1)
72
+
73
+
74
+ def apply_rotary_pos_emb(x, cos, sin):
75
+ cos = cos[:, :, : x.shape[-2], :]
76
+ sin = sin[:, :, : x.shape[-2], :]
77
+
78
+ return (x * cos) + (rotate_half(x) * sin)
79
+
80
+
81
+ def gelu(x):
82
+ """
83
+ This is the gelu implementation from the original OmniGenome repo. Using F.gelu yields subtly wrong results.
84
+ """
85
+ return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
86
+
87
+
88
+ def symmetrize(x):
89
+ "Make layer symmetric in final two dimensions, used for contact prediction."
90
+ return x + x.transpose(-1, -2)
91
+
92
+
93
+ def average_product_correct(x):
94
+ "Perform average product correct, used for contact prediction."
95
+ a1 = x.sum(-1, keepdims=True)
96
+ a2 = x.sum(-2, keepdims=True)
97
+ a12 = x.sum((-1, -2), keepdims=True)
98
+
99
+ avg = a1 * a2
100
+ avg.div_(a12) # in-place to reduce memory
101
+ normalized = x - avg
102
+ return normalized
103
+
104
+
105
+ # Copied from transformers.models.esm.modeling_esm.RotaryEmbedding
106
+ class RotaryEmbedding(torch.nn.Module):
107
+ """
108
+ Rotary position embeddings based on those in
109
+ [RoFormer](https://huggingface.co/docs/transformers/model_doc/roformer). Query and keys are transformed by rotation
110
+ matrices which depend on their relative positions.
111
+ """
112
+
113
+ def __init__(self, dim: int):
114
+ super().__init__()
115
+ # Generate and save the inverse frequency buffer (non trainable)
116
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2).float() / dim))
117
+ inv_freq = inv_freq
118
+ self.register_buffer("inv_freq", inv_freq)
119
+
120
+ self._seq_len_cached = None
121
+ self._cos_cached = None
122
+ self._sin_cached = None
123
+
124
+ def _update_cos_sin_tables(self, x, seq_dimension=2):
125
+ seq_len = x.shape[seq_dimension]
126
+
127
+ # Reset the tables if the sequence length has changed,
128
+ # or if we're on a new device (possibly due to tracing for instance)
129
+ if seq_len != self._seq_len_cached or self._cos_cached.device != x.device:
130
+ self._seq_len_cached = seq_len
131
+ t = torch.arange(x.shape[seq_dimension], device=x.device).type_as(
132
+ self.inv_freq
133
+ )
134
+ freqs = torch.outer(t, self.inv_freq)
135
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
136
+
137
+ self._cos_cached = emb.cos()[None, None, :, :]
138
+ self._sin_cached = emb.sin()[None, None, :, :]
139
+
140
+ return self._cos_cached, self._sin_cached
141
+
142
+ def forward(
143
+ self, q: torch.Tensor, k: torch.Tensor
144
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
145
+ self._cos_cached, self._sin_cached = self._update_cos_sin_tables(
146
+ k, seq_dimension=-2
147
+ )
148
+
149
+ return (
150
+ apply_rotary_pos_emb(q, self._cos_cached, self._sin_cached),
151
+ apply_rotary_pos_emb(k, self._cos_cached, self._sin_cached),
152
+ )
153
+
154
+
155
+ # Copied from transformers.models.esm.modeling_esm.EsmContactPredictionHead with Esm->OmniGenome
156
+ class OmniGenomeContactPredictionHead(nn.Module):
157
+ """Performs symmetrization, apc, and computes a logistic regression on the output features"""
158
+
159
+ def __init__(
160
+ self,
161
+ in_features: int,
162
+ bias=True,
163
+ eos_idx: int = 2,
164
+ ):
165
+ super().__init__()
166
+ self.in_features = in_features
167
+ self.eos_idx = eos_idx
168
+ self.regression = nn.Linear(in_features, 1, bias)
169
+ self.activation = nn.Sigmoid()
170
+
171
+ def forward(self, tokens, attentions):
172
+ # remove eos token attentions
173
+ eos_mask = tokens.ne(self.eos_idx).to(attentions)
174
+ eos_mask = eos_mask.unsqueeze(1) * eos_mask.unsqueeze(2)
175
+ attentions = attentions * eos_mask[:, None, None, :, :]
176
+ attentions = attentions[..., :-1, :-1]
177
+ # remove cls token attentions
178
+ attentions = attentions[..., 1:, 1:]
179
+ batch_size, layers, heads, seqlen, _ = attentions.size()
180
+ attentions = attentions.view(batch_size, layers * heads, seqlen, seqlen)
181
+
182
+ # features: batch x channels x tokens x tokens (symmetric)
183
+ attentions = attentions.to(
184
+ self.regression.weight.device
185
+ ) # attentions always float32, may need to convert to float16
186
+ attentions = average_product_correct(symmetrize(attentions))
187
+ attentions = attentions.permute(0, 2, 3, 1)
188
+ return self.activation(self.regression(attentions).squeeze(3))
189
+
190
+
191
+ # Copied from transformers.models.esm.modeling_esm.EsmEmbeddings with Esm->OmniGenome
192
+ class OmniGenomeEmbeddings(nn.Module):
193
+ """
194
+ Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
195
+ """
196
+
197
+ def __init__(self, config):
198
+ super().__init__()
199
+ self.word_embeddings = nn.Embedding(
200
+ config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id
201
+ )
202
+
203
+ if config.emb_layer_norm_before:
204
+ self.layer_norm = nn.LayerNorm(
205
+ config.hidden_size, eps=config.layer_norm_eps
206
+ )
207
+ else:
208
+ self.layer_norm = None
209
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
210
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
211
+ self.position_embedding_type = getattr(
212
+ config, "position_embedding_type", "absolute"
213
+ )
214
+ self.register_buffer(
215
+ "position_ids",
216
+ torch.arange(config.max_position_embeddings).expand((1, -1)),
217
+ persistent=False,
218
+ )
219
+
220
+ self.padding_idx = config.pad_token_id
221
+ self.position_embeddings = nn.Embedding(
222
+ config.max_position_embeddings,
223
+ config.hidden_size,
224
+ padding_idx=self.padding_idx,
225
+ )
226
+ self.token_dropout = config.token_dropout
227
+ self.mask_token_id = config.mask_token_id
228
+
229
+ def forward(
230
+ self,
231
+ input_ids=None,
232
+ attention_mask=None,
233
+ position_ids=None,
234
+ inputs_embeds=None,
235
+ past_key_values_length=0,
236
+ ):
237
+ if position_ids is None:
238
+ if input_ids is not None:
239
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
240
+ position_ids = create_position_ids_from_input_ids(
241
+ input_ids, self.padding_idx, past_key_values_length
242
+ )
243
+ else:
244
+ position_ids = self.create_position_ids_from_inputs_embeds(
245
+ inputs_embeds
246
+ )
247
+
248
+ if inputs_embeds is None:
249
+ inputs_embeds = self.word_embeddings(input_ids)
250
+
251
+ # Note that if we want to support OmniGenome-1 (not 1b!) in future then we need to support an
252
+ # embedding_scale factor here.
253
+ embeddings = inputs_embeds
254
+
255
+ # Matt: OmniGenome has the option to handle masking in MLM in a slightly unusual way. If the token_dropout
256
+ # flag is False then it is handled in the same was as BERT/RoBERTa. If it is set to True, however,
257
+ # masked tokens are treated as if they were selected for input dropout and zeroed out.
258
+ # This "mask-dropout" is compensated for when masked tokens are not present, by scaling embeddings by
259
+ # a factor of (fraction of unmasked tokens during training) / (fraction of unmasked tokens in sample).
260
+ # This is analogous to the way that dropout layers scale down outputs during evaluation when not
261
+ # actually dropping out values (or, equivalently, scale up their un-dropped outputs in training).
262
+ if self.token_dropout:
263
+ embeddings = embeddings.masked_fill(
264
+ (input_ids == self.mask_token_id).unsqueeze(-1), 0.0
265
+ )
266
+ mask_ratio_train = (
267
+ 0.15 * 0.8
268
+ ) # Hardcoded as the ratio used in all OmniGenome model training runs
269
+ src_lengths = attention_mask.sum(-1)
270
+ mask_ratio_observed = (input_ids == self.mask_token_id).sum(
271
+ -1
272
+ ).float() / src_lengths
273
+ embeddings = (
274
+ embeddings
275
+ * (1 - mask_ratio_train)
276
+ / (1 - mask_ratio_observed)[:, None, None]
277
+ ).to(embeddings.dtype)
278
+
279
+ if self.position_embedding_type == "absolute":
280
+ position_embeddings = self.position_embeddings(position_ids)
281
+ embeddings = embeddings + position_embeddings
282
+
283
+ if self.layer_norm is not None:
284
+ embeddings = self.layer_norm(embeddings)
285
+ if attention_mask is not None:
286
+ embeddings = (embeddings * attention_mask.unsqueeze(-1)).to(
287
+ embeddings.dtype
288
+ )
289
+ # Matt: I think this line was copied incorrectly from BERT, disabling it for now.
290
+ # embeddings = self.dropout(embeddings)
291
+ return embeddings
292
+
293
+ def create_position_ids_from_inputs_embeds(self, inputs_embeds):
294
+ """
295
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
296
+ Args:
297
+ inputs_embeds: torch.Tensor
298
+ Returns: torch.Tensor
299
+ """
300
+ input_shape = inputs_embeds.size()[:-1]
301
+ sequence_length = input_shape[1]
302
+
303
+ position_ids = torch.arange(
304
+ self.padding_idx + 1,
305
+ sequence_length + self.padding_idx + 1,
306
+ dtype=torch.long,
307
+ device=inputs_embeds.device,
308
+ )
309
+ return position_ids.unsqueeze(0).expand(input_shape)
310
+
311
+ #
312
+ # # Copied from transformers.models.esm.modeling_esm.EsmSelfAttention with Esm->OmniGenome
313
+ # class OmniGenomeSelfAttention(nn.Module):
314
+ # def __init__(self, config, position_embedding_type=None):
315
+ # super().__init__()
316
+ # if config.hidden_size % config.num_attention_heads != 0 and not hasattr(
317
+ # config, "embedding_size"
318
+ # ):
319
+ # raise ValueError(
320
+ # f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
321
+ # f"heads ({config.num_attention_heads})"
322
+ # )
323
+ #
324
+ # self.num_attention_heads = config.num_attention_heads
325
+ # self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
326
+ # self.all_head_size = self.num_attention_heads * self.attention_head_size
327
+ #
328
+ # self.query = nn.Linear(config.hidden_size, self.all_head_size)
329
+ # self.key = nn.Linear(config.hidden_size, self.all_head_size)
330
+ # self.value = nn.Linear(config.hidden_size, self.all_head_size)
331
+ #
332
+ # self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
333
+ # self.position_embedding_type = position_embedding_type or getattr(
334
+ # config, "position_embedding_type", "absolute"
335
+ # )
336
+ # self.rotary_embeddings = None
337
+ # if (
338
+ # self.position_embedding_type == "relative_key"
339
+ # or self.position_embedding_type == "relative_key_query"
340
+ # ):
341
+ # self.max_position_embeddings = config.max_position_embeddings
342
+ # self.distance_embedding = nn.Embedding(
343
+ # 2 * config.max_position_embeddings - 1, self.attention_head_size
344
+ # )
345
+ # elif self.position_embedding_type == "rotary":
346
+ # self.rotary_embeddings = RotaryEmbedding(dim=self.attention_head_size)
347
+ #
348
+ # self.is_decoder = config.is_decoder
349
+ #
350
+ # def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
351
+ # new_x_shape = x.size()[:-1] + (
352
+ # self.num_attention_heads,
353
+ # self.attention_head_size,
354
+ # )
355
+ # x = x.view(new_x_shape)
356
+ # return x.permute(0, 2, 1, 3)
357
+ #
358
+ # def forward(
359
+ # self,
360
+ # hidden_states: torch.Tensor,
361
+ # attention_mask: Optional[torch.FloatTensor] = None,
362
+ # head_mask: Optional[torch.FloatTensor] = None,
363
+ # encoder_hidden_states: Optional[torch.FloatTensor] = None,
364
+ # encoder_attention_mask: Optional[torch.FloatTensor] = None,
365
+ # past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
366
+ # output_attentions: Optional[bool] = False,
367
+ # ) -> Tuple[torch.Tensor]:
368
+ # mixed_query_layer = self.query(hidden_states)
369
+ #
370
+ # # If this is instantiated as a cross-attention module, the keys
371
+ # # and values come from an encoder; the attention mask needs to be
372
+ # # such that the encoder's padding tokens are not attended to.
373
+ # is_cross_attention = encoder_hidden_states is not None
374
+ #
375
+ # if is_cross_attention and past_key_value is not None:
376
+ # # reuse k,v, cross_attentions
377
+ # key_layer = past_key_value[0]
378
+ # value_layer = past_key_value[1]
379
+ # attention_mask = encoder_attention_mask
380
+ # elif is_cross_attention:
381
+ # key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
382
+ # value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
383
+ # attention_mask = encoder_attention_mask
384
+ # elif past_key_value is not None:
385
+ # key_layer = self.transpose_for_scores(self.key(hidden_states))
386
+ # value_layer = self.transpose_for_scores(self.value(hidden_states))
387
+ # key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
388
+ # value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
389
+ # else:
390
+ # key_layer = self.transpose_for_scores(self.key(hidden_states))
391
+ # value_layer = self.transpose_for_scores(self.value(hidden_states))
392
+ #
393
+ # query_layer = self.transpose_for_scores(mixed_query_layer)
394
+ #
395
+ # # Matt: Our BERT model (which this code was derived from) scales attention logits down by sqrt(head_dim).
396
+ # # OmniGenome scales the query down by the same factor instead. Modulo numerical stability these are equivalent,
397
+ # # but not when rotary embeddings get involved. Therefore, we scale the query here to match the original
398
+ # # OmniGenome code and fix rotary embeddings.
399
+ # query_layer = query_layer * self.attention_head_size ** -0.5
400
+ #
401
+ # if self.is_decoder:
402
+ # # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
403
+ # # Further calls to cross_attention layer can then reuse all cross-attention
404
+ # # key/value_states (first "if" case)
405
+ # # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
406
+ # # all previous decoder key/value_states. Further calls to uni-directional self-attention
407
+ # # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
408
+ # # if encoder bi-directional self-attention `past_key_value` is always `None`
409
+ # past_key_value = (key_layer, value_layer)
410
+ #
411
+ # if self.position_embedding_type == "rotary":
412
+ # query_layer, key_layer = self.rotary_embeddings(query_layer, key_layer)
413
+ #
414
+ # # Take the dot product between "query" and "key" to get the raw attention scores.
415
+ # attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
416
+ #
417
+ # if (
418
+ # self.position_embedding_type == "relative_key"
419
+ # or self.position_embedding_type == "relative_key_query"
420
+ # ):
421
+ # seq_length = hidden_states.size()[1]
422
+ # position_ids_l = torch.arange(
423
+ # seq_length, dtype=torch.long, device=hidden_states.device
424
+ # ).view(-1, 1)
425
+ # position_ids_r = torch.arange(
426
+ # seq_length, dtype=torch.long, device=hidden_states.device
427
+ # ).view(1, -1)
428
+ # distance = position_ids_l - position_ids_r
429
+ # positional_embedding = self.distance_embedding(
430
+ # distance + self.max_position_embeddings - 1
431
+ # )
432
+ # positional_embedding = positional_embedding.to(
433
+ # dtype=query_layer.dtype
434
+ # ) # fp16 compatibility
435
+ #
436
+ # if self.position_embedding_type == "relative_key":
437
+ # relative_position_scores = torch.einsum(
438
+ # "bhld,lrd->bhlr", query_layer, positional_embedding
439
+ # )
440
+ # attention_scores = attention_scores + relative_position_scores
441
+ # elif self.position_embedding_type == "relative_key_query":
442
+ # relative_position_scores_query = torch.einsum(
443
+ # "bhld,lrd->bhlr", query_layer, positional_embedding
444
+ # )
445
+ # relative_position_scores_key = torch.einsum(
446
+ # "bhrd,lrd->bhlr", key_layer, positional_embedding
447
+ # )
448
+ # attention_scores = (
449
+ # attention_scores
450
+ # + relative_position_scores_query
451
+ # + relative_position_scores_key
452
+ # )
453
+ #
454
+ # if attention_mask is not None:
455
+ # # Apply the attention mask is (precomputed for all layers in OmniGenomeModel forward() function)
456
+ # attention_scores = attention_scores + attention_mask
457
+ #
458
+ # # Normalize the attention scores to probabilities.
459
+ # attention_probs = nn.functional.softmax(attention_scores, dim=-1)
460
+ #
461
+ # # This is actually dropping out entire tokens to attend to, which might
462
+ # # seem a bit unusual, but is taken from the original Transformer paper.
463
+ # attention_probs = self.dropout(attention_probs)
464
+ #
465
+ # # Mask heads if we want to
466
+ # if head_mask is not None:
467
+ # attention_probs = attention_probs * head_mask
468
+ #
469
+ # context_layer = torch.matmul(attention_probs, value_layer)
470
+ #
471
+ # context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
472
+ # new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
473
+ # context_layer = context_layer.view(new_context_layer_shape)
474
+ #
475
+ # outputs = (
476
+ # (context_layer, attention_probs) if output_attentions else (context_layer,)
477
+ # )
478
+ #
479
+ # if self.is_decoder:
480
+ # outputs = outputs + (past_key_value,)
481
+ # return outputs
482
+
483
+
484
+ # Copied from transformers.models.esm.modeling_esm.EsmSelfAttention with Esm->OmniGenome
485
+ class OmniGenomeSelfAttention(nn.Module):
486
+ def __init__(self, config, position_embedding_type=None):
487
+ super().__init__()
488
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(
489
+ config, "embedding_size"
490
+ ):
491
+ raise ValueError(
492
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
493
+ f"heads ({config.num_attention_heads})"
494
+ )
495
+
496
+ self.num_attention_heads = config.num_attention_heads
497
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
498
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
499
+
500
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
501
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
502
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
503
+
504
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
505
+ self.position_embedding_type = position_embedding_type or getattr(
506
+ config, "position_embedding_type", "absolute"
507
+ )
508
+ self.rotary_embeddings = None
509
+ if (
510
+ self.position_embedding_type == "relative_key"
511
+ or self.position_embedding_type == "relative_key_query"
512
+ ):
513
+ self.max_position_embeddings = config.max_position_embeddings
514
+ self.distance_embedding = nn.Embedding(
515
+ 2 * config.max_position_embeddings - 1, self.attention_head_size
516
+ )
517
+ elif self.position_embedding_type == "rotary":
518
+ self.rotary_embeddings = RotaryEmbedding(dim=self.attention_head_size)
519
+
520
+ self.is_decoder = config.is_decoder
521
+
522
+ if flash_attn_func:
523
+ self.flash_attn_func = flash_attn_func
524
+ else:
525
+ self.flash_attn_func = None
526
+
527
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
528
+ new_x_shape = x.size()[:-1] + (
529
+ self.num_attention_heads,
530
+ self.attention_head_size,
531
+ )
532
+ x = x.view(new_x_shape)
533
+ return x.permute(0, 2, 1, 3)
534
+
535
+ def forward(
536
+ self,
537
+ hidden_states: torch.Tensor,
538
+ attention_mask: Optional[torch.FloatTensor] = None,
539
+ head_mask: Optional[torch.FloatTensor] = None,
540
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
541
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
542
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
543
+ output_attentions: Optional[bool] = False,
544
+ ) -> Tuple[torch.Tensor]:
545
+ mixed_query_layer = self.query(hidden_states)
546
+
547
+ is_cross_attention = encoder_hidden_states is not None
548
+
549
+ if is_cross_attention and past_key_value is not None:
550
+ key_layer = past_key_value[0]
551
+ value_layer = past_key_value[1]
552
+ attention_mask = encoder_attention_mask
553
+ elif is_cross_attention:
554
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
555
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
556
+ attention_mask = encoder_attention_mask
557
+ elif past_key_value is not None:
558
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
559
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
560
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
561
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
562
+ else:
563
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
564
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
565
+
566
+ query_layer = self.transpose_for_scores(mixed_query_layer)
567
+
568
+ if self.is_decoder:
569
+ past_key_value = (key_layer, value_layer)
570
+
571
+ if self.flash_attn_func is not None:
572
+ # 应用旋转位置编码
573
+ query_layer, key_layer = self.rotary_embeddings(query_layer, key_layer)
574
+
575
+ # 调整维度顺序为 [batch_size, seq_len, num_heads, head_dim]
576
+ q = query_layer.transpose(1, 2).to(torch.float16)
577
+ k = key_layer.transpose(1, 2).to(torch.float16)
578
+ v = value_layer.transpose(1, 2).to(torch.float16)
579
+
580
+ # 使用FlashAttention计算
581
+ context_layer = self.flash_attn_func(
582
+ q, k, v,
583
+ dropout_p=self.dropout.p if self.training else 0.0,
584
+ softmax_scale=self.attention_head_size ** -0.5,
585
+ causal=self.is_decoder
586
+ )
587
+
588
+ # 恢复维度顺序 [batch_size, num_heads, seq_len, head_dim]
589
+ context_layer = context_layer.transpose(1, 2).to(hidden_states.dtype)
590
+ else:
591
+ # 原始实现
592
+ query_layer = query_layer * self.attention_head_size ** -0.5
593
+
594
+ if self.position_embedding_type == "rotary":
595
+ query_layer, key_layer = self.rotary_embeddings(query_layer, key_layer)
596
+
597
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
598
+
599
+ if self.position_embedding_type in ["relative_key", "relative_key_query"]:
600
+ seq_length = hidden_states.size()[1]
601
+ position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
602
+ position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
603
+ distance = position_ids_l - position_ids_r
604
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
605
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype)
606
+
607
+ if self.position_embedding_type == "relative_key":
608
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
609
+ attention_scores = attention_scores + relative_position_scores
610
+ elif self.position_embedding_type == "relative_key_query":
611
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
612
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
613
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
614
+
615
+ if attention_mask is not None:
616
+ attention_scores = attention_scores + attention_mask
617
+
618
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
619
+ attention_probs = self.dropout(attention_probs)
620
+
621
+ if head_mask is not None:
622
+ attention_probs = attention_probs * head_mask
623
+
624
+ context_layer = torch.matmul(attention_probs, value_layer)
625
+
626
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
627
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
628
+ context_layer = context_layer.view(new_context_layer_shape)
629
+
630
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
631
+ if self.is_decoder:
632
+ outputs = outputs + (past_key_value,)
633
+ return outputs
634
+
635
+ # Copied from transformers.models.esm.modeling_esm.EsmSelfOutput with Esm->OmniGenome
636
+ class OmniGenomeSelfOutput(nn.Module):
637
+ def __init__(self, config):
638
+ super().__init__()
639
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
640
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
641
+
642
+ def forward(self, hidden_states, input_tensor):
643
+ hidden_states = self.dense(hidden_states)
644
+ hidden_states = self.dropout(hidden_states)
645
+ hidden_states = hidden_states + input_tensor
646
+ return hidden_states
647
+
648
+
649
+ # Copied from transformers.models.esm.modeling_esm.EsmAttention with Esm->OmniGenome
650
+ class OmniGenomeAttention(nn.Module):
651
+ def __init__(self, config):
652
+ super().__init__()
653
+ self.self = OmniGenomeSelfAttention(config)
654
+ self.output = OmniGenomeSelfOutput(config)
655
+ self.pruned_heads = set()
656
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
657
+
658
+ def prune_heads(self, heads):
659
+ if len(heads) == 0:
660
+ return
661
+ heads, index = find_pruneable_heads_and_indices(
662
+ heads,
663
+ self.self.num_attention_heads,
664
+ self.self.attention_head_size,
665
+ self.pruned_heads,
666
+ )
667
+
668
+ # Prune linear layers
669
+ self.self.query = prune_linear_layer(self.self.query, index)
670
+ self.self.key = prune_linear_layer(self.self.key, index)
671
+ self.self.value = prune_linear_layer(self.self.value, index)
672
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
673
+
674
+ # Update hyper params and store pruned heads
675
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
676
+ self.self.all_head_size = (
677
+ self.self.attention_head_size * self.self.num_attention_heads
678
+ )
679
+ self.pruned_heads = self.pruned_heads.union(heads)
680
+
681
+ def forward(
682
+ self,
683
+ hidden_states,
684
+ attention_mask=None,
685
+ head_mask=None,
686
+ encoder_hidden_states=None,
687
+ encoder_attention_mask=None,
688
+ past_key_value=None,
689
+ output_attentions=False,
690
+ ):
691
+ hidden_states_ln = self.LayerNorm(hidden_states)
692
+ hidden_states_ln = hidden_states_ln.to(hidden_states.dtype)
693
+ self_outputs = self.self(
694
+ hidden_states_ln,
695
+ attention_mask,
696
+ head_mask,
697
+ encoder_hidden_states,
698
+ encoder_attention_mask,
699
+ past_key_value,
700
+ output_attentions,
701
+ )
702
+ attention_output = self.output(self_outputs[0], hidden_states)
703
+ outputs = (attention_output,) + self_outputs[
704
+ 1:
705
+ ] # add attentions if we output them
706
+ return outputs
707
+
708
+
709
+ # Copied from transformers.models.esm.modeling_esm.EsmIntermediate with Esm->OmniGenome
710
+ class OmniGenomeIntermediate(nn.Module):
711
+ def __init__(self, config):
712
+ super().__init__()
713
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
714
+
715
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
716
+ hidden_states = self.dense(hidden_states)
717
+ hidden_states = gelu(hidden_states)
718
+ return hidden_states
719
+
720
+
721
+ # Copied from transformers.models.esm.modeling_esm.EsmOutput with Esm->OmniGenome
722
+ class OmniGenomeOutput(nn.Module):
723
+ def __init__(self, config):
724
+ super().__init__()
725
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
726
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
727
+
728
+ def forward(self, hidden_states, input_tensor):
729
+ hidden_states = self.dense(hidden_states)
730
+ hidden_states = self.dropout(hidden_states)
731
+ hidden_states = hidden_states + input_tensor
732
+ return hidden_states
733
+
734
+
735
+ # Copied from transformers.models.esm.modeling_esm.EsmLayer with Esm->OmniGenome
736
+ class OmniGenomeLayer(nn.Module):
737
+ def __init__(self, config):
738
+ super().__init__()
739
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
740
+ self.seq_len_dim = 1
741
+ self.attention = OmniGenomeAttention(config)
742
+ self.is_decoder = config.is_decoder
743
+ self.add_cross_attention = config.add_cross_attention
744
+ if self.add_cross_attention:
745
+ if not self.is_decoder:
746
+ raise RuntimeError(
747
+ f"{self} should be used as a decoder model if cross attention is added"
748
+ )
749
+ self.crossattention = OmniGenomeAttention(config)
750
+ self.intermediate = OmniGenomeIntermediate(config)
751
+ self.output = OmniGenomeOutput(config)
752
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
753
+
754
+ def forward(
755
+ self,
756
+ hidden_states,
757
+ attention_mask=None,
758
+ head_mask=None,
759
+ encoder_hidden_states=None,
760
+ encoder_attention_mask=None,
761
+ past_key_value=None,
762
+ output_attentions=False,
763
+ ):
764
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
765
+ self_attn_past_key_value = (
766
+ past_key_value[:2] if past_key_value is not None else None
767
+ )
768
+ self_attention_outputs = self.attention(
769
+ hidden_states,
770
+ attention_mask,
771
+ head_mask,
772
+ output_attentions=output_attentions,
773
+ past_key_value=self_attn_past_key_value,
774
+ )
775
+ attention_output = self_attention_outputs[0]
776
+
777
+ # if decoder, the last output is tuple of self-attn cache
778
+ if self.is_decoder:
779
+ outputs = self_attention_outputs[1:-1]
780
+ present_key_value = self_attention_outputs[-1]
781
+ else:
782
+ outputs = self_attention_outputs[
783
+ 1:
784
+ ] # add self attentions if we output attention weights
785
+
786
+ cross_attn_present_key_value = None
787
+ if self.is_decoder and encoder_hidden_states is not None:
788
+ if not hasattr(self, "crossattention"):
789
+ raise AttributeError(
790
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated"
791
+ " with cross-attention layers by setting `config.add_cross_attention=True`"
792
+ )
793
+
794
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
795
+ cross_attn_past_key_value = (
796
+ past_key_value[-2:] if past_key_value is not None else None
797
+ )
798
+ cross_attention_outputs = self.crossattention(
799
+ attention_output,
800
+ attention_mask,
801
+ head_mask,
802
+ encoder_hidden_states,
803
+ encoder_attention_mask,
804
+ cross_attn_past_key_value,
805
+ output_attentions,
806
+ )
807
+ attention_output = cross_attention_outputs[0]
808
+ outputs = (
809
+ outputs + cross_attention_outputs[1:-1]
810
+ ) # add cross attentions if we output attention weights
811
+
812
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
813
+ cross_attn_present_key_value = cross_attention_outputs[-1]
814
+ present_key_value = present_key_value + cross_attn_present_key_value
815
+
816
+ layer_output = self.feed_forward_chunk(attention_output)
817
+
818
+ outputs = (layer_output,) + outputs
819
+
820
+ # if decoder, return the attn key/values as the last output
821
+ if self.is_decoder:
822
+ outputs = outputs + (present_key_value,)
823
+ return outputs
824
+
825
+ def feed_forward_chunk(self, attention_output):
826
+ attention_output_ln = self.LayerNorm(attention_output)
827
+ intermediate_output = self.intermediate(attention_output_ln)
828
+ layer_output = self.output(intermediate_output, attention_output)
829
+ return layer_output
830
+
831
+
832
+ # Copied from transformers.models.esm.modeling_esm.EsmEncoder with Esm->OmniGenome
833
+ class OmniGenomeEncoder(nn.Module):
834
+ def __init__(self, config):
835
+ super().__init__()
836
+ self.config = config
837
+ self.layer = nn.ModuleList(
838
+ [OmniGenomeLayer(config) for _ in range(config.num_hidden_layers)]
839
+ )
840
+ self.emb_layer_norm_after = nn.LayerNorm(
841
+ config.hidden_size, eps=config.layer_norm_eps
842
+ )
843
+ self.gradient_checkpointing = False
844
+
845
+ def forward(
846
+ self,
847
+ hidden_states,
848
+ attention_mask=None,
849
+ head_mask=None,
850
+ encoder_hidden_states=None,
851
+ encoder_attention_mask=None,
852
+ past_key_values=None,
853
+ use_cache=None,
854
+ output_attentions=False,
855
+ output_hidden_states=False,
856
+ return_dict=True,
857
+ ):
858
+ if self.gradient_checkpointing and self.training:
859
+ if use_cache:
860
+ logger.warning_once(
861
+ "`use_cache=True` is incompatible with `config.gradient_checkpointing=True`. Setting "
862
+ "`use_cache=False`..."
863
+ )
864
+ use_cache = False
865
+ all_hidden_states = () if output_hidden_states else None
866
+ all_self_attentions = () if output_attentions else None
867
+ all_cross_attentions = (
868
+ () if output_attentions and self.config.add_cross_attention else None
869
+ )
870
+
871
+ next_decoder_cache = () if use_cache else None
872
+ for i, layer_module in enumerate(self.layer):
873
+ if output_hidden_states:
874
+ all_hidden_states = all_hidden_states + (hidden_states,)
875
+
876
+ layer_head_mask = head_mask[i] if head_mask is not None else None
877
+ past_key_value = past_key_values[i] if past_key_values is not None else None
878
+
879
+ if self.gradient_checkpointing and self.training:
880
+ layer_outputs = self._gradient_checkpointing_func(
881
+ layer_module.__call__,
882
+ hidden_states,
883
+ attention_mask,
884
+ layer_head_mask,
885
+ encoder_hidden_states,
886
+ encoder_attention_mask,
887
+ past_key_value,
888
+ output_attentions,
889
+ )
890
+ else:
891
+ layer_outputs = layer_module(
892
+ hidden_states,
893
+ attention_mask,
894
+ layer_head_mask,
895
+ encoder_hidden_states,
896
+ encoder_attention_mask,
897
+ past_key_value,
898
+ output_attentions,
899
+ )
900
+
901
+ hidden_states = layer_outputs[0]
902
+ if use_cache:
903
+ next_decoder_cache = next_decoder_cache + (layer_outputs[-1],)
904
+ if output_attentions:
905
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
906
+ if self.config.add_cross_attention:
907
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
908
+
909
+ if self.emb_layer_norm_after:
910
+ hidden_states = self.emb_layer_norm_after(hidden_states)
911
+
912
+ if output_hidden_states:
913
+ all_hidden_states = all_hidden_states + (hidden_states,)
914
+
915
+ if not return_dict:
916
+ return tuple(
917
+ v
918
+ for v in [
919
+ hidden_states,
920
+ next_decoder_cache,
921
+ all_hidden_states,
922
+ all_self_attentions,
923
+ all_cross_attentions,
924
+ ]
925
+ if v is not None
926
+ )
927
+ return BaseModelOutputWithPastAndCrossAttentions(
928
+ last_hidden_state=hidden_states,
929
+ past_key_values=next_decoder_cache,
930
+ hidden_states=all_hidden_states,
931
+ attentions=all_self_attentions,
932
+ cross_attentions=all_cross_attentions,
933
+ )
934
+
935
+
936
+ # Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->OmniGenome
937
+ class OmniGenomePooler(nn.Module):
938
+ def __init__(self, config):
939
+ super().__init__()
940
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
941
+ self.activation = nn.Tanh()
942
+
943
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
944
+ # We "pool" the model by simply taking the hidden state corresponding
945
+ # to the first token.
946
+ first_token_tensor = hidden_states[:, 0]
947
+ pooled_output = self.dense(first_token_tensor)
948
+ pooled_output = self.activation(pooled_output)
949
+ return pooled_output
950
+
951
+
952
+ # Copied from transformers.models.esm.modeling_esm.EsmPreTrainedModel with Esm->OmniGenome
953
+ class OmniGenomePreTrainedModel(PreTrainedModel):
954
+ """
955
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
956
+ models.
957
+ """
958
+
959
+ config_class = OmniGenomeConfig
960
+ base_model_prefix = "OmniGenome"
961
+ supports_gradient_checkpointing = True
962
+ _no_split_modules = [
963
+ "OmniGenomeLayer",
964
+ "OmniGenomeFoldTriangularSelfAttentionBlock",
965
+ "OmniGenomeEmbeddings",
966
+ ]
967
+
968
+ # Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weights
969
+ def _init_weights(self, module):
970
+ """Initialize the weights"""
971
+ if isinstance(module, nn.Linear):
972
+ # Slightly different from the TF version which uses truncated_normal for initialization
973
+ # cf https://github.com/pytorch/pytorch/pull/5617
974
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
975
+ if module.bias is not None:
976
+ module.bias.data.zero_()
977
+ elif isinstance(module, nn.Embedding):
978
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
979
+ if module.padding_idx is not None:
980
+ module.weight.data[module.padding_idx].zero_()
981
+ elif isinstance(module, nn.LayerNorm):
982
+ module.bias.data.zero_()
983
+ module.weight.data.fill_(1.0)
984
+
985
+
986
+ OmniGenome_START_DOCSTRING = r"""
987
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
988
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
989
+ etc.)
990
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
991
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
992
+ and behavior.
993
+ Parameters:
994
+ config ([`OmniGenomeConfig`]): Model configuration class with all the parameters of the
995
+ model. Initializing with a config file does not load the weights associated with the model, only the
996
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
997
+ """
998
+
999
+ OmniGenome_INPUTS_DOCSTRING = r"""
1000
+ Args:
1001
+ input_ids (`torch.LongTensor` of shape `({0})`):
1002
+ Indices of input sequence tokens in the vocabulary.
1003
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1004
+ [`PreTrainedTokenizer.__call__`] for details.
1005
+ [What are input IDs?](../glossary#input-ids)
1006
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
1007
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1008
+ - 1 for tokens that are **not masked**,
1009
+ - 0 for tokens that are **masked**.
1010
+ [What are attention masks?](../glossary#attention-mask)
1011
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
1012
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1013
+ config.max_position_embeddings - 1]`.
1014
+ [What are position IDs?](../glossary#position-ids)
1015
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1016
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
1017
+ - 1 indicates the head is **not masked**,
1018
+ - 0 indicates the head is **masked**.
1019
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
1020
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1021
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1022
+ model's internal embedding lookup matrix.
1023
+ output_attentions (`bool`, *optional*):
1024
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1025
+ tensors for more detail.
1026
+ output_hidden_states (`bool`, *optional*):
1027
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1028
+ more detail.
1029
+ return_dict (`bool`, *optional*):
1030
+ Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
1031
+ """
1032
+
1033
+
1034
+ @add_start_docstrings(
1035
+ "The bare OmniGenome Model transformer outputting raw hidden-states without any specific head on top.",
1036
+ OmniGenome_START_DOCSTRING,
1037
+ )
1038
+ # Copied from transformers.models.esm.modeling_esm.EsmModel with Esm->OmniGenome
1039
+ class OmniGenomeModel(OmniGenomePreTrainedModel):
1040
+ """
1041
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
1042
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
1043
+ all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
1044
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
1045
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
1046
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
1047
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
1048
+ """
1049
+
1050
+ def __init__(self, config, add_pooling_layer=True):
1051
+ super().__init__(config)
1052
+ self.config = config
1053
+
1054
+ self.embeddings = OmniGenomeEmbeddings(config)
1055
+ self.encoder = OmniGenomeEncoder(config)
1056
+
1057
+ self.pooler = OmniGenomePooler(config) if add_pooling_layer else None
1058
+
1059
+ self.contact_head = OmniGenomeContactPredictionHead(
1060
+ in_features=config.num_hidden_layers * config.num_attention_heads, bias=True
1061
+ )
1062
+
1063
+ # Initialize weights and apply final processing
1064
+ self.post_init()
1065
+
1066
+ def get_input_embeddings(self):
1067
+ return self.embeddings.word_embeddings
1068
+
1069
+ def set_input_embeddings(self, value):
1070
+ self.embeddings.word_embeddings = value
1071
+
1072
+ def _prune_heads(self, heads_to_prune):
1073
+ """
1074
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
1075
+ class PreTrainedModel
1076
+ """
1077
+ for layer, heads in heads_to_prune.items():
1078
+ self.encoder.layer[layer].attention.prune_heads(heads)
1079
+
1080
+ @add_start_docstrings_to_model_forward(
1081
+ OmniGenome_INPUTS_DOCSTRING.format("(batch_size, sequence_length)")
1082
+ )
1083
+ @add_code_sample_docstrings(
1084
+ checkpoint=_CHECKPOINT_FOR_DOC,
1085
+ output_type=BaseModelOutputWithPoolingAndCrossAttentions,
1086
+ config_class=_CONFIG_FOR_DOC,
1087
+ )
1088
+ def forward(
1089
+ self,
1090
+ input_ids: Optional[torch.Tensor] = None,
1091
+ attention_mask: Optional[torch.Tensor] = None,
1092
+ position_ids: Optional[torch.Tensor] = None,
1093
+ head_mask: Optional[torch.Tensor] = None,
1094
+ inputs_embeds: Optional[torch.Tensor] = None,
1095
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1096
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1097
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1098
+ use_cache: Optional[bool] = None,
1099
+ output_attentions: Optional[bool] = None,
1100
+ output_hidden_states: Optional[bool] = None,
1101
+ return_dict: Optional[bool] = None,
1102
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
1103
+ r"""
1104
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1105
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
1106
+ the model is configured as a decoder.
1107
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1108
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1109
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1110
+ - 1 for tokens that are **not masked**,
1111
+ - 0 for tokens that are **masked**.
1112
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
1113
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1114
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1115
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1116
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1117
+ use_cache (`bool`, *optional*):
1118
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1119
+ `past_key_values`).
1120
+ """
1121
+ output_attentions = (
1122
+ output_attentions
1123
+ if output_attentions is not None
1124
+ else self.config.output_attentions
1125
+ )
1126
+ output_hidden_states = (
1127
+ output_hidden_states
1128
+ if output_hidden_states is not None
1129
+ else self.config.output_hidden_states
1130
+ )
1131
+ return_dict = (
1132
+ return_dict if return_dict is not None else self.config.use_return_dict
1133
+ )
1134
+
1135
+ if self.config.is_decoder:
1136
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1137
+ else:
1138
+ use_cache = False
1139
+
1140
+ if input_ids is not None and inputs_embeds is not None:
1141
+ raise ValueError(
1142
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1143
+ )
1144
+ elif input_ids is not None:
1145
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
1146
+ input_shape = input_ids.size()
1147
+ elif inputs_embeds is not None:
1148
+ input_shape = inputs_embeds.size()[:-1]
1149
+ else:
1150
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1151
+
1152
+ batch_size, seq_length = input_shape
1153
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1154
+
1155
+ # past_key_values_length
1156
+ past_key_values_length = (
1157
+ past_key_values[0][0].shape[2] if past_key_values is not None else 0
1158
+ )
1159
+
1160
+ if attention_mask is None:
1161
+ attention_mask = torch.ones(
1162
+ ((batch_size, seq_length + past_key_values_length)), device=device
1163
+ )
1164
+
1165
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
1166
+ # ourselves in which case we just need to make it broadcastable to all heads.
1167
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(
1168
+ attention_mask, input_shape
1169
+ )
1170
+
1171
+ # If a 2D or 3D attention mask is provided for the cross-attention
1172
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
1173
+ if self.config.is_decoder and encoder_hidden_states is not None:
1174
+ (
1175
+ encoder_batch_size,
1176
+ encoder_sequence_length,
1177
+ _,
1178
+ ) = encoder_hidden_states.size()
1179
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
1180
+ if encoder_attention_mask is None:
1181
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
1182
+ encoder_extended_attention_mask = self.invert_attention_mask(
1183
+ encoder_attention_mask
1184
+ )
1185
+ else:
1186
+ encoder_extended_attention_mask = None
1187
+
1188
+ # Prepare head mask if needed
1189
+ # 1.0 in head_mask indicate we keep the head
1190
+ # attention_probs has shape bsz x n_heads x N x N
1191
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
1192
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
1193
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
1194
+
1195
+ embedding_output = self.embeddings(
1196
+ input_ids=input_ids,
1197
+ position_ids=position_ids,
1198
+ attention_mask=attention_mask,
1199
+ inputs_embeds=inputs_embeds,
1200
+ past_key_values_length=past_key_values_length,
1201
+ )
1202
+ encoder_outputs = self.encoder(
1203
+ embedding_output,
1204
+ attention_mask=extended_attention_mask,
1205
+ head_mask=head_mask,
1206
+ encoder_hidden_states=encoder_hidden_states,
1207
+ encoder_attention_mask=encoder_extended_attention_mask,
1208
+ past_key_values=past_key_values,
1209
+ use_cache=use_cache,
1210
+ output_attentions=output_attentions,
1211
+ output_hidden_states=output_hidden_states,
1212
+ return_dict=return_dict,
1213
+ )
1214
+ sequence_output = encoder_outputs[0]
1215
+ pooled_output = (
1216
+ self.pooler(sequence_output) if self.pooler is not None else None
1217
+ )
1218
+
1219
+ if not return_dict:
1220
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
1221
+
1222
+ return BaseModelOutputWithPoolingAndCrossAttentions(
1223
+ last_hidden_state=sequence_output,
1224
+ pooler_output=pooled_output,
1225
+ past_key_values=encoder_outputs.past_key_values,
1226
+ hidden_states=encoder_outputs.hidden_states,
1227
+ attentions=encoder_outputs.attentions,
1228
+ cross_attentions=encoder_outputs.cross_attentions,
1229
+ )
1230
+
1231
+ def predict_contacts(self, tokens, attention_mask):
1232
+ attns = self(
1233
+ tokens,
1234
+ attention_mask=attention_mask,
1235
+ return_dict=True,
1236
+ output_attentions=True,
1237
+ ).attentions
1238
+ attns = torch.stack(attns, dim=1) # Matches the original model layout
1239
+ # In the original model, attentions for padding tokens are completely zeroed out.
1240
+ # This makes no difference most of the time because the other tokens won't attend to them,
1241
+ # but it does for the contact prediction task, which takes attentions as input,
1242
+ # so we have to mimic that here.
1243
+ attns *= attention_mask.unsqueeze(1).unsqueeze(2).unsqueeze(3)
1244
+ attns *= attention_mask.unsqueeze(1).unsqueeze(2).unsqueeze(4)
1245
+ return self.contact_head(tokens, attns)
1246
+
1247
+
1248
+ @add_start_docstrings(
1249
+ """OmniGenome Model with a `language modeling` head on top.""", OmniGenome_START_DOCSTRING
1250
+ )
1251
+ # Copied from transformers.models.esm.modeling_esm.EsmForMaskedLM with Esm->OmniGenome
1252
+ class OmniGenomeForMaskedLM(OmniGenomePreTrainedModel):
1253
+ _tied_weights_keys = ["lm_head.decoder.weight"]
1254
+
1255
+ def __init__(self, config):
1256
+ super().__init__(config)
1257
+
1258
+ if config.is_decoder:
1259
+ logger.warning(
1260
+ "If you want to use `OmniGenomeForMaskedLM` make sure `config.is_decoder=False` for "
1261
+ "bi-directional self-attention."
1262
+ )
1263
+
1264
+ self.OmniGenome = OmniGenomeModel(config, add_pooling_layer=False)
1265
+ self.lm_head = OmniGenomeLMHead(config)
1266
+ self.init_weights()
1267
+
1268
+ def get_output_embeddings(self):
1269
+ return self.lm_head.decoder
1270
+
1271
+ def set_output_embeddings(self, new_embeddings):
1272
+ self.lm_head.decoder = new_embeddings
1273
+
1274
+ @add_start_docstrings_to_model_forward(
1275
+ OmniGenome_INPUTS_DOCSTRING.format("batch_size, sequence_length")
1276
+ )
1277
+ @add_code_sample_docstrings(
1278
+ checkpoint=_CHECKPOINT_FOR_DOC,
1279
+ output_type=MaskedLMOutput,
1280
+ config_class=_CONFIG_FOR_DOC,
1281
+ mask="<mask>",
1282
+ )
1283
+ def forward(
1284
+ self,
1285
+ input_ids: Optional[torch.LongTensor] = None,
1286
+ attention_mask: Optional[torch.Tensor] = None,
1287
+ position_ids: Optional[torch.LongTensor] = None,
1288
+ head_mask: Optional[torch.Tensor] = None,
1289
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1290
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
1291
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1292
+ labels: Optional[torch.LongTensor] = None,
1293
+ output_attentions: Optional[bool] = None,
1294
+ output_hidden_states: Optional[bool] = None,
1295
+ return_dict: Optional[bool] = None,
1296
+ ) -> Union[Tuple, MaskedLMOutput]:
1297
+ r"""
1298
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1299
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1300
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1301
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1302
+ kwargs (`Dict[str, any]`, optional, defaults to *{}*):
1303
+ Used to hide legacy arguments that have been deprecated.
1304
+ """
1305
+ return_dict = (
1306
+ return_dict if return_dict is not None else self.config.use_return_dict
1307
+ )
1308
+
1309
+ outputs = self.OmniGenome(
1310
+ input_ids,
1311
+ attention_mask=attention_mask,
1312
+ position_ids=position_ids,
1313
+ head_mask=head_mask,
1314
+ inputs_embeds=inputs_embeds,
1315
+ encoder_hidden_states=encoder_hidden_states,
1316
+ encoder_attention_mask=encoder_attention_mask,
1317
+ output_attentions=output_attentions,
1318
+ output_hidden_states=output_hidden_states,
1319
+ return_dict=return_dict,
1320
+ )
1321
+ sequence_output = outputs[0]
1322
+ prediction_scores = self.lm_head(sequence_output)
1323
+
1324
+ masked_lm_loss = None
1325
+ if labels is not None:
1326
+ loss_fct = CrossEntropyLoss()
1327
+
1328
+ labels = labels.to(prediction_scores.device)
1329
+ masked_lm_loss = loss_fct(
1330
+ prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)
1331
+ )
1332
+
1333
+ if not return_dict:
1334
+ output = (prediction_scores,) + outputs[2:]
1335
+ return (
1336
+ ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1337
+ )
1338
+
1339
+ return MaskedLMOutput(
1340
+ loss=masked_lm_loss,
1341
+ logits=prediction_scores,
1342
+ hidden_states=outputs.hidden_states,
1343
+ attentions=outputs.attentions,
1344
+ )
1345
+
1346
+ def predict_contacts(self, tokens, attention_mask):
1347
+ return self.OmniGenome.predict_contacts(tokens, attention_mask=attention_mask)
1348
+
1349
+
1350
+ # Copied from transformers.models.esm.modeling_esm.EsmLMHead with Esm->OmniGenome
1351
+ class OmniGenomeLMHead(nn.Module):
1352
+ """OmniGenome Head for masked language modeling."""
1353
+
1354
+ def __init__(self, config):
1355
+ super().__init__()
1356
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
1357
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
1358
+
1359
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1360
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
1361
+
1362
+ def forward(self, features, **kwargs):
1363
+ x = self.dense(features)
1364
+ x = gelu(x)
1365
+ x = self.layer_norm(x)
1366
+
1367
+ # project back to size of vocabulary with bias
1368
+ x = self.decoder(x) + self.bias
1369
+ return x
1370
+
1371
+
1372
+ @add_start_docstrings(
1373
+ """
1374
+ OmniGenome Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
1375
+ output) e.g. for GLUE tasks.
1376
+ """,
1377
+ OmniGenome_START_DOCSTRING,
1378
+ )
1379
+ class OmniGenomeForSequenceClassification(OmniGenomePreTrainedModel):
1380
+ def __init__(self, config):
1381
+ super().__init__(config)
1382
+ self.num_labels = config.num_labels
1383
+ self.config = config
1384
+ self.OmniGenome = OmniGenomeModel(config, add_pooling_layer=False)
1385
+ self.classifier = OmniGenomeClassificationHead(config)
1386
+ self.init_weights()
1387
+
1388
+ @add_start_docstrings_to_model_forward(
1389
+ OmniGenome_INPUTS_DOCSTRING.format("batch_size, sequence_length")
1390
+ )
1391
+ @add_code_sample_docstrings(
1392
+ checkpoint=_CHECKPOINT_FOR_DOC,
1393
+ output_type=SequenceClassifierOutput,
1394
+ config_class=_CONFIG_FOR_DOC,
1395
+ )
1396
+ def forward(
1397
+ self,
1398
+ input_ids: Optional[torch.LongTensor] = None,
1399
+ attention_mask: Optional[torch.Tensor] = None,
1400
+ position_ids: Optional[torch.LongTensor] = None,
1401
+ head_mask: Optional[torch.Tensor] = None,
1402
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1403
+ labels: Optional[torch.LongTensor] = None,
1404
+ output_attentions: Optional[bool] = None,
1405
+ output_hidden_states: Optional[bool] = None,
1406
+ return_dict: Optional[bool] = None,
1407
+ ) -> Union[Tuple, SequenceClassifierOutput]:
1408
+ r"""
1409
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1410
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1411
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1412
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1413
+ """
1414
+ return_dict = (
1415
+ return_dict if return_dict is not None else self.config.use_return_dict
1416
+ )
1417
+
1418
+ outputs = self.OmniGenome(
1419
+ input_ids,
1420
+ attention_mask=attention_mask,
1421
+ position_ids=position_ids,
1422
+ head_mask=head_mask,
1423
+ inputs_embeds=inputs_embeds,
1424
+ output_attentions=output_attentions,
1425
+ output_hidden_states=output_hidden_states,
1426
+ return_dict=return_dict,
1427
+ )
1428
+ last_hidden_state = outputs[0]
1429
+ logits = self.classifier(last_hidden_state)
1430
+
1431
+ loss = None
1432
+ if labels is not None:
1433
+ labels = labels.to(logits.device)
1434
+
1435
+ if self.config.problem_type is None:
1436
+ if self.num_labels == 1:
1437
+ self.config.problem_type = "regression"
1438
+ elif self.num_labels > 1 and (
1439
+ labels.dtype == torch.long or labels.dtype == torch.int
1440
+ ):
1441
+ self.config.problem_type = "single_label_classification"
1442
+ else:
1443
+ self.config.problem_type = "multi_label_classification"
1444
+
1445
+ if self.config.problem_type == "regression":
1446
+ loss_fct = MSELoss()
1447
+ if self.num_labels == 1:
1448
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1449
+ else:
1450
+ loss = loss_fct(logits, labels)
1451
+ elif self.config.problem_type == "single_label_classification":
1452
+ loss_fct = CrossEntropyLoss()
1453
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1454
+ elif self.config.problem_type == "multi_label_classification":
1455
+ loss_fct = BCEWithLogitsLoss()
1456
+ loss = loss_fct(logits, labels)
1457
+
1458
+ if not return_dict:
1459
+ output = (logits,) + outputs[2:]
1460
+ return ((loss,) + output) if loss is not None else output
1461
+
1462
+ return SequenceClassifierOutput(
1463
+ loss=loss,
1464
+ logits=logits,
1465
+ hidden_states=outputs.hidden_states,
1466
+ attentions=outputs.attentions,
1467
+ )
1468
+
1469
+
1470
+ @add_start_docstrings(
1471
+ """
1472
+ OmniGenome Model with a token classification head on top (a linear layer on top of the hidden-states output)
1473
+ Note that this model is pre-trained for RNA secondary structure prediction and can be used for zero-shot RNA
1474
+ secondary structure prediction. Please find more advanced usages at https://github.com/yangheng95/OmniGenome
1475
+ This model can be fine-tuned for other token classification tasks.
1476
+ """,
1477
+ OmniGenome_START_DOCSTRING,
1478
+ )
1479
+ # Copied from transformers.models.esm.modeling_esm.EsmForTokenClassification with Esm->OmniGenome
1480
+ class OmniGenomeForTokenClassification(OmniGenomePreTrainedModel):
1481
+ def __init__(self, config):
1482
+ super().__init__(config)
1483
+ self.num_labels = config.num_labels
1484
+ self.OmniGenome = OmniGenomeModel(config, add_pooling_layer=False)
1485
+ self.dense = torch.nn.Linear(config.hidden_size, config.hidden_size)
1486
+ self.classifier = torch.nn.Linear(self.config.hidden_size, self.num_labels)
1487
+ self.softmax = nn.Softmax(dim=-1)
1488
+ self.init_weights()
1489
+
1490
+ @add_start_docstrings_to_model_forward(
1491
+ OmniGenome_INPUTS_DOCSTRING.format("batch_size, sequence_length")
1492
+ )
1493
+ @add_code_sample_docstrings(
1494
+ checkpoint=_CHECKPOINT_FOR_DOC,
1495
+ output_type=TokenClassifierOutput,
1496
+ config_class=_CONFIG_FOR_DOC,
1497
+ )
1498
+ def forward(
1499
+ self,
1500
+ input_ids: Optional[torch.LongTensor] = None,
1501
+ attention_mask: Optional[torch.Tensor] = None,
1502
+ position_ids: Optional[torch.LongTensor] = None,
1503
+ head_mask: Optional[torch.Tensor] = None,
1504
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1505
+ labels: Optional[torch.LongTensor] = None,
1506
+ output_attentions: Optional[bool] = None,
1507
+ output_hidden_states: Optional[bool] = None,
1508
+ return_dict: Optional[bool] = None,
1509
+ ) -> Union[Tuple, TokenClassifierOutput]:
1510
+ r"""
1511
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1512
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1513
+ """
1514
+
1515
+ return_dict = (
1516
+ return_dict if return_dict is not None else self.config.use_return_dict
1517
+ )
1518
+
1519
+ outputs = self.OmniGenome(
1520
+ input_ids,
1521
+ attention_mask=attention_mask,
1522
+ position_ids=position_ids,
1523
+ head_mask=head_mask,
1524
+ inputs_embeds=inputs_embeds,
1525
+ output_attentions=output_attentions,
1526
+ output_hidden_states=output_hidden_states,
1527
+ return_dict=return_dict,
1528
+ )
1529
+
1530
+ last_hidden_state = outputs[0]
1531
+ last_hidden_state = self.dense(last_hidden_state)
1532
+ logits = self.classifier(last_hidden_state)
1533
+ logits = self.softmax(logits)
1534
+
1535
+ loss = None
1536
+ if labels is not None:
1537
+ loss_fct = CrossEntropyLoss()
1538
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1539
+
1540
+ if not return_dict:
1541
+ output = (logits,) + outputs[2:]
1542
+ return ((loss,) + output) if loss is not None else output
1543
+
1544
+ return TokenClassifierOutput(
1545
+ loss=loss,
1546
+ logits=logits,
1547
+ hidden_states=outputs.hidden_states,
1548
+ attentions=outputs.attentions,
1549
+ )
1550
+
1551
+ @staticmethod
1552
+ def verify_secondary_structure(structure):
1553
+ structure = list(structure)
1554
+ left_brackets = []
1555
+ right_brackets = []
1556
+ for i, char in enumerate(structure):
1557
+ if char == "(":
1558
+ left_brackets.append(i)
1559
+ elif char == ")":
1560
+ if left_brackets:
1561
+ left_brackets.pop()
1562
+ else:
1563
+ right_brackets.append(i)
1564
+
1565
+ for i in left_brackets:
1566
+ structure[i] = "."
1567
+ for i in right_brackets:
1568
+ structure[i] = "."
1569
+
1570
+ structure = "".join(structure)
1571
+
1572
+ return structure
1573
+
1574
+ def predict_rna_structure(
1575
+ self,
1576
+ sequence: str,
1577
+ **kwargs
1578
+ ) -> List[str]:
1579
+ r"""
1580
+ Load the pretrained OmniGenome Model to do zero-shot prediction of the secondary structure
1581
+ of a sequence given the sequence
1582
+ """
1583
+ if self.tokenizer is None:
1584
+ tokenizer = kwargs.get("tokenizer", None)
1585
+ if tokenizer is None:
1586
+ from transformers import AutoTokenizer
1587
+ self.tokenizer = AutoTokenizer.from_pretrained(self.config.name_or_path)
1588
+ else:
1589
+ self.tokenizer = tokenizer
1590
+
1591
+ inputs = self.tokenizer(sequence, return_tensors="pt", padding="max_length", truncation=True)
1592
+ input_ids = inputs["input_ids"]
1593
+ attention_mask = inputs["attention_mask"]
1594
+ outputs = self.forward(input_ids, attention_mask, **kwargs)
1595
+
1596
+ logits = torch.argmax(outputs.logits, dim=-1)
1597
+ lengths = torch.sum(torch.ne(torch.tensor(0), attention_mask), dim=-1)
1598
+ structures = []
1599
+ for i, length in enumerate(lengths):
1600
+ structure = logits[i, :length].cpu().numpy()
1601
+ structure = "".join(self.config.id2label[label] for label in structure)
1602
+ if self.config.verify_ss:
1603
+ structure = self.verify_secondary_structure(structure)
1604
+ structures.append(structure)
1605
+ return structures
1606
+
1607
+
1608
+ @dataclass
1609
+ class Seq2SeqLMWithValueOutput(ModelOutput):
1610
+ """
1611
+ Base class for sequence-to-sequence language models with a value head.
1612
+
1613
+ Args:
1614
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
1615
+ Language modeling loss.
1616
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
1617
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
1618
+ value (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
1619
+ Value estimation scores from the value head.
1620
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1621
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
1622
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
1623
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
1624
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and cross-attention
1625
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
1626
+ decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
1627
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
1628
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
1629
+ Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
1630
+ decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
1631
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
1632
+ sequence_length)`.
1633
+ Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in
1634
+ the self-attention heads.
1635
+ cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
1636
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
1637
+ sequence_length)`.
1638
+ Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute
1639
+ the weighted average in the cross-attention heads.
1640
+ encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1641
+ Sequence of hidden-states at the output of the last layer of the encoder of the model.
1642
+ encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
1643
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
1644
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
1645
+ Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
1646
+ encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
1647
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
1648
+ sequence_length)`.
1649
+ Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in
1650
+ the self-attention heads.
1651
+ """
1652
+ loss: Optional[torch.FloatTensor] = None
1653
+ logits: torch.FloatTensor = None
1654
+ value: torch.FloatTensor = None
1655
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None
1656
+ decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
1657
+ decoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
1658
+ cross_attentions: Optional[Tuple[torch.FloatTensor]] = None
1659
+ encoder_last_hidden_state: Optional[torch.FloatTensor] = None
1660
+ encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
1661
+ encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
1662
+
1663
+
1664
+ #
1665
+ # 2. Define the Value Head module
1666
+ #
1667
+
1668
+ class ValueHead(nn.Module):
1669
+ """Head for predicting a scalar value for each token in a sequence."""
1670
+
1671
+ def __init__(self, config: OmniGenomeConfig):
1672
+ super().__init__()
1673
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1674
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
1675
+ self.out_proj = nn.Linear(config.hidden_size, 1)
1676
+ self.activation = nn.Tanh()
1677
+
1678
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
1679
+ """
1680
+ Args:
1681
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
1682
+ The hidden states from the decoder.
1683
+ Returns:
1684
+ `torch.FloatTensor` of shape `(batch_size, seq_len, 1)`: The predicted value for each token.
1685
+ """
1686
+ hidden_states = self.dropout(hidden_states)
1687
+ hidden_states = self.dense(hidden_states)
1688
+ hidden_states = self.activation(hidden_states)
1689
+ hidden_states = self.dropout(hidden_states)
1690
+ value = self.out_proj(hidden_states)
1691
+ return value
1692
+
1693
+
1694
+ #
1695
+ # 3. Define the main Seq2Seq model class with a Value Head
1696
+ #
1697
+
1698
+
1699
+ @add_start_docstrings(
1700
+ """
1701
+ OmniGenome Model with a sequence-to-sequence language modeling head and a value head on top.
1702
+ This model is designed for reinforcement learning-based fine-tuning algorithms like GRPO.
1703
+ It comprises an OmniGenome-based encoder and decoder.
1704
+ """,
1705
+ OmniGenome_START_DOCSTRING,
1706
+ )
1707
+ class OmniGenomeForSeq2SeqWithValueHead(OmniGenomePreTrainedModel):
1708
+ _tied_weights_keys = ["lm_head.decoder.weight"]
1709
+
1710
+ def __init__(self, config: OmniGenomeConfig):
1711
+ super().__init__(config)
1712
+
1713
+ # The model architecture follows the standard Encoder-Decoder pattern.
1714
+ # self.encoder = OmniGenomeModel(config, add_pooling_layer=False)
1715
+ self.encoder = OmniGenomeModel.from_pretrained(f"{os.path.dirname(__file__)}")
1716
+ # The decoder requires a modified configuration to enable cross-attention.
1717
+ decoder_config = copy.deepcopy(config)
1718
+ decoder_config.is_decoder = True
1719
+ decoder_config.add_cross_attention = True
1720
+ decoder_config.num_hidden_layers = 3 # Reduce the number of layers for the decoder to speed up training
1721
+ self.decoder = OmniGenomeModel(decoder_config, add_pooling_layer=False)
1722
+ self.decoder.embeddings = copy.deepcopy(self.encoder.embeddings) # Share embeddings between encoder and decoder
1723
+ self.decoder.embeddings.token_dropout = False
1724
+ self.lm_head = OmniGenomeLMHead(config)
1725
+ self.value_head = ValueHead(config)
1726
+
1727
+ # Initialize weights and apply final processing
1728
+ self.post_init()
1729
+
1730
+ def get_encoder(self):
1731
+ return self.encoder
1732
+
1733
+ def get_decoder(self):
1734
+ return self.decoder
1735
+
1736
+ def get_input_embeddings(self):
1737
+ return self.encoder.get_input_embeddings()
1738
+
1739
+ def set_input_embeddings(self, value):
1740
+ self.encoder.set_input_embeddings(value)
1741
+ self.decoder.set_input_embeddings(value)
1742
+
1743
+ def get_output_embeddings(self):
1744
+ return self.lm_head.decoder
1745
+
1746
+ def set_output_embeddings(self, new_embeddings):
1747
+ self.lm_head.decoder = new_embeddings
1748
+
1749
+ @add_start_docstrings_to_model_forward(
1750
+ # ... (docstring)
1751
+ )
1752
+ def forward(
1753
+ self,
1754
+ input_ids: Optional[torch.LongTensor] = None,
1755
+ attention_mask: Optional[torch.FloatTensor] = None,
1756
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1757
+ decoder_attention_mask: Optional[torch.BoolTensor] = None,
1758
+ head_mask: Optional[torch.FloatTensor] = None,
1759
+ decoder_head_mask: Optional[torch.FloatTensor] = None,
1760
+ # cross_attn_head_mask: Optional[torch.Tensor] = None, # <<< FIX: REMOVE THIS LINE
1761
+ encoder_outputs: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1762
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1763
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1764
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1765
+ labels: Optional[torch.LongTensor] = None,
1766
+ use_cache: Optional[bool] = None,
1767
+ output_attentions: Optional[bool] = None,
1768
+ output_hidden_states: Optional[bool] = None,
1769
+ return_dict: Optional[bool] = None,
1770
+ ) -> Union[Tuple, Seq2SeqLMWithValueOutput]:
1771
+ r"""
1772
+ Returns:
1773
+ A [`Seq2SeqLMWithValueOutput`] containing the language modeling logits, the value prediction, and other standard model outputs.
1774
+ """
1775
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1776
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1777
+
1778
+ # Step 1: Encode the input sequence if not already provided
1779
+ if encoder_outputs is None:
1780
+ encoder_outputs = self.encoder(
1781
+ input_ids=input_ids,
1782
+ attention_mask=attention_mask,
1783
+ inputs_embeds=inputs_embeds,
1784
+ head_mask=head_mask,
1785
+ output_attentions=output_attentions,
1786
+ output_hidden_states=output_hidden_states,
1787
+ return_dict=return_dict,
1788
+ )
1789
+
1790
+ encoder_hidden_states = encoder_outputs[0] if not return_dict else encoder_outputs.last_hidden_state
1791
+
1792
+ # Step 2: Decode the sequence using the encoder's output as context
1793
+ decoder_outputs = self.decoder(
1794
+ input_ids=decoder_input_ids,
1795
+ attention_mask=decoder_attention_mask,
1796
+ encoder_hidden_states=encoder_hidden_states,
1797
+ encoder_attention_mask=attention_mask,
1798
+ head_mask=decoder_head_mask,
1799
+ # cross_attn_head_mask=cross_attn_head_mask, # <<< FIX: REMOVE THIS LINE
1800
+ past_key_values=past_key_values,
1801
+ inputs_embeds=decoder_inputs_embeds,
1802
+ use_cache=use_cache,
1803
+ output_attentions=output_attentions,
1804
+ output_hidden_states=output_hidden_states,
1805
+ return_dict=return_dict,
1806
+ )
1807
+
1808
+ sequence_output = decoder_outputs[0] if not return_dict else decoder_outputs.last_hidden_state
1809
+
1810
+ # Step 3: Compute logits and value from the decoder's final hidden state
1811
+ lm_logits = self.lm_head(sequence_output)
1812
+ value = self.value_head(sequence_output).squeeze(-1)
1813
+
1814
+ # Step 4: Compute loss if labels are provided
1815
+ loss = None
1816
+ if labels is not None:
1817
+ loss_fct = CrossEntropyLoss()
1818
+ labels = labels.to(lm_logits.device)
1819
+ loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
1820
+
1821
+ if not return_dict:
1822
+ # Reconstruct the output tuple
1823
+ output = (lm_logits, value) + decoder_outputs[1:] + encoder_outputs
1824
+ return ((loss,) + output) if loss is not None else output
1825
+
1826
+ return Seq2SeqLMWithValueOutput(
1827
+ loss=loss,
1828
+ logits=lm_logits,
1829
+ value=value,
1830
+ past_key_values=decoder_outputs.past_key_values,
1831
+ decoder_hidden_states=decoder_outputs.hidden_states,
1832
+ decoder_attentions=decoder_outputs.attentions,
1833
+ cross_attentions=decoder_outputs.cross_attentions,
1834
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1835
+ encoder_hidden_states=encoder_outputs.hidden_states,
1836
+ encoder_attentions=encoder_outputs.attentions,
1837
+ )
1838
+
1839
+ def prepare_inputs_for_generation(
1840
+ self,
1841
+ decoder_input_ids,
1842
+ past_key_values=None,
1843
+ attention_mask=None,
1844
+ head_mask=None,
1845
+ decoder_head_mask=None,
1846
+ cross_attn_head_mask=None,
1847
+ use_cache=None,
1848
+ encoder_outputs=None,
1849
+ **kwargs,
1850
+ ):
1851
+ # Cut decoder_input_ids if past is used
1852
+ if past_key_values is not None:
1853
+ decoder_input_ids = decoder_input_ids[:, -1:]
1854
+
1855
+ return {
1856
+ "input_ids": None, # encoder_outputs is provided, so no need for input_ids
1857
+ "encoder_outputs": encoder_outputs,
1858
+ "past_key_values": past_key_values,
1859
+ "decoder_input_ids": decoder_input_ids,
1860
+ "attention_mask": attention_mask,
1861
+ "head_mask": head_mask,
1862
+ "decoder_head_mask": decoder_head_mask,
1863
+ "cross_attn_head_mask": cross_attn_head_mask,
1864
+ "use_cache": use_cache,
1865
+ }
1866
+
1867
+ @staticmethod
1868
+ def _reorder_cache(past_key_values, beam_idx):
1869
+ reordered_past = ()
1870
+ for layer_past in past_key_values:
1871
+ reordered_past += (
1872
+ tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),
1873
+ )
1874
+ return reordered_past
1875
+
1876
+
1877
+ # Copied from transformers.models.esm.modeling_esm.EsmClassificationHead with Esm->OmniGenome
1878
+ class OmniGenomeClassificationHead(nn.Module):
1879
+ """Head for sentence-level classification tasks."""
1880
+
1881
+ def __init__(self, config):
1882
+ super().__init__()
1883
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
1884
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1885
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
1886
+
1887
+ def forward(self, features, **kwargs):
1888
+ x = features[:, 0, :] # take <s> token (equiv. to [CLS])
1889
+ x = self.dropout(x)
1890
+ x = self.dense(x)
1891
+ x = torch.tanh(x)
1892
+ x = self.dropout(x)
1893
+ x = self.out_proj(x)
1894
+ return x
1895
+
1896
+
1897
+ def create_position_ids_from_input_ids(
1898
+ input_ids, padding_idx, past_key_values_length=0
1899
+ ):
1900
+ """
1901
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
1902
+ are ignored. This is modified from fairseq's `utils.make_positions`.
1903
+ Args:
1904
+ x: torch.Tensor x:
1905
+ Returns: torch.Tensor
1906
+ """
1907
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
1908
+ mask = input_ids.ne(padding_idx).int()
1909
+ incremental_indices = (
1910
+ torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length
1911
+ ) * mask
1912
+ return incremental_indices.long() + padding_idx
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:16c060eef0bc0cfed017b1a182b1dc518c8eb321a7ca93a06889b81b91cb57d6
3
+ size 107708935
special_tokens_map.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": {
3
+ "content": "<cls>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<eos>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "mask_token": {
17
+ "content": "<mask>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "pad_token": {
24
+ "content": "<pad>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "unk_token": {
31
+ "content": "<unk>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ }
37
+ }
tokenizer.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bb3c164260010c8bb2639cf081d188a44d74b1f975966efb9ec9c4ef04775e22
3
+ size 2788
tokenizer_config.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<cls>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "<pad>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "<eos>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "<unk>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "23": {
36
+ "content": "<mask>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": true,
45
+ "cls_token": "<cls>",
46
+ "eos_token": "<eos>",
47
+ "extra_special_tokens": {},
48
+ "mask_token": "<mask>",
49
+ "model_max_length": 1000000000000000019884624838656,
50
+ "pad_token": "<pad>",
51
+ "tokenizer_class": "EsmTokenizer",
52
+ "unk_token": "<unk>"
53
+ }
vocab.txt ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <cls>
2
+ <pad>
3
+ <eos>
4
+ <unk>
5
+ A
6
+ C
7
+ G
8
+ T
9
+ N
10
+ U
11
+ a
12
+ c
13
+ g
14
+ t
15
+ n
16
+ u
17
+ (
18
+ )
19
+ .
20
+ *
21
+ 1
22
+ 2
23
+ 3
24
+ <mask>