Datasets:
Upload 17 files
Browse files- README.md +67 -3
- ToxiCN_1.0.csv +0 -0
- ToxiCN_ex/ToxiCN/data/test.json +0 -0
- ToxiCN_ex/ToxiCN/data/train.json +0 -0
- ToxiCN_ex/ToxiCN/lexicon/LGBT.json +1 -0
- ToxiCN_ex/ToxiCN/lexicon/general.json +1 -0
- ToxiCN_ex/ToxiCN/lexicon/racism.json +1 -0
- ToxiCN_ex/ToxiCN/lexicon/region.json +1 -0
- ToxiCN_ex/ToxiCN/lexicon/sexism.json +1 -0
- ToxiCN_ex/model/Config_base.py +70 -0
- ToxiCN_ex/requirements.txt +10 -0
- ToxiCN_ex/run.py +123 -0
- ToxiCN_ex/src/BERT.py +507 -0
- ToxiCN_ex/src/Models.py +69 -0
- ToxiCN_ex/src/datasets.py +238 -0
- ToxiCN_ex/train_eval.py +202 -0
- modeling_bert.py +1635 -0
README.md
CHANGED
@@ -1,3 +1,67 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Facilitating Fine-grained Detection of Chinese Toxic Language: Hierarchical Taxonomy, Resources, and Benchmark
|
2 |
+
|
3 |
+
🎉**2024.9 Our related study, titled "Towards Comprehensive Detection of Chinese Harmful Meme", has been accepted to NeurIPS 2024! In this paper, we present ToxiCN_MM, the first Chinese harmful meme dataset. Here is the link: [https://github.com/DUT-lujunyu/ToxiCN_MM](https://github.com/DUT-lujunyu/ToxiCN_MM). Welcome to star or fork it!**
|
4 |
+
|
5 |
+
🎉**2024.9 Our related study, titled "PclGPT: A Large Language Model for Patronizing and Condescending Language Detection", has been accepted to EMNLP 2024! In this paper, we focus on a specific type of implicit toxicity, patronizing, and condescending language. [link](https://github.com/dut-laowang/emnlp24-PclGPT/tree/main) [paper](https://arxiv.org/abs/2410.00361)**
|
6 |
+
|
7 |
+
🎉**2024.5 Our proposed dataset, ToxiCN, has been adopted by the international evaluation [CLEF 2024: Multilingual Text Detoxification](https://pan.webis.de/clef24/pan24-web/text-detoxification.html) as the sole Chinese data source. [Report](https://ceur-ws.org/Vol-3740/paper-223.pdf)**
|
8 |
+
___
|
9 |
+
|
10 |
+
|
11 |
+
|
12 |
+
**The paper has been accepted in ACL 2023 (main conference, long paper).** [Paper](https://aclanthology.org/2023.acl-long.898/)
|
13 |
+
|
14 |
+
☠️ ***Warning: The samples presented by this paper may be considered offensive or vulgar.***
|
15 |
+
|
16 |
+
## ❗️ Ethics Statement
|
17 |
+
The opinions and findings contained in the samples of our presented dataset should not be interpreted as representing the views expressed or implied by the authors. We acknowledge the risk of malicious actors attempting to reverse-engineer comments. **We sincerely hope that users will employ the dataset responsibly and appropriately, avoiding misuse or abuse.** We believe the benefits of our proposed resources outweigh the associated risks. **All resources are intended solely for scientific research and are prohibited from commercial use.**
|
18 |
+
|
19 |
+
|
20 |
+
## 📜 Monitor Toxic Frame
|
21 |
+
we introduce a hierarchical taxonomy **Monitor Toxic Frame**. Based on the taxonomy, the posts are progressively divided into diverse granularities as follows: **_(I) Whether Toxic_**, ***(II) Toxic Type*** (general offensive language or hate speech), ***(III) Targeted Group***, ***(IV) Expression Category*** (explicitness, implicitness, or reporting).
|
22 |
+
|
23 |
+
## 📜 ToxiCN
|
24 |
+
We conduct a fine-grained annotation of posts crawled from _Zhihu_ and _Tieba_, including both direct and indirect toxic samples. And ToxiCN dataset is presented, which has 12k comments containing **_Sexism_**, **_Racism_**, **_Regional Bias_**, **_Anti-LGBTQ_**, and **_Others_**. The dataset is presented in ***ToxiCN_1.0.csv***. Here we simply describe each fine-grain label.
|
25 |
+
|
26 |
+
| Label | Description |
|
27 |
+
| ----------------- | ------------------------------------------------------------ |
|
28 |
+
| toxic | Identify if a comment is toxic (1) or non-toxic (0). |
|
29 |
+
| toxic_type | non-toxic: 0, general offensive language: 1, hate speech: 2 |
|
30 |
+
| expression | non-hate: 0, explicit hate speech: 1, implicit hate speech: 2, reporting: 3|
|
31 |
+
| target (a list) | LGBTQ: Index 0, Region: Index 1, Sexism: Index 2, Racism: Index 3, others: Index 4, non-hate: Index 5 |
|
32 |
+
|
33 |
+
## 📜 Insult Lexicon
|
34 |
+
See https://github.com/DUT-lujunyu/ToxiCN/tree/main/ToxiCN_ex/ToxiCN/lexicon
|
35 |
+
## 📜 Benchmark
|
36 |
+
We present a migratable benchmark of **Toxic Knowledge Enhancement** (**TKE**), enriching the text representation. The code is shown in **_modeling_bert.py_**, which is based on **transformers 3.1.0**.
|
37 |
+
|
38 |
+
|
39 |
+
## ❗️ Licenses
|
40 |
+
This work is licensed under a Creative Commons Attribution- NonCommercial-NoDerivatives 4.0 International License (CC BY-NC-ND 4.0).
|
41 |
+
|
42 |
+
## Poster
|
43 |
+

|
44 |
+
|
45 |
+
|
46 |
+
|
47 |
+
## Cite
|
48 |
+
If you want to use the resources, please cite the following paper:
|
49 |
+
~~~
|
50 |
+
@inproceedings{lu-etal-2023-facilitating,
|
51 |
+
title = "Facilitating Fine-grained Detection of {C}hinese Toxic Language: Hierarchical Taxonomy, Resources, and Benchmarks",
|
52 |
+
author = "Lu, Junyu and
|
53 |
+
Xu, Bo and
|
54 |
+
Zhang, Xiaokun and
|
55 |
+
Min, Changrong and
|
56 |
+
Yang, Liang and
|
57 |
+
Lin, Hongfei",
|
58 |
+
booktitle = "Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)",
|
59 |
+
month = jul,
|
60 |
+
year = "2023",
|
61 |
+
address = "Toronto, Canada",
|
62 |
+
publisher = "Association for Computational Linguistics",
|
63 |
+
url = "https://aclanthology.org/2023.acl-long.898",
|
64 |
+
doi = "10.18653/v1/2023.acl-long.898",
|
65 |
+
pages = "16235--16250",
|
66 |
+
}
|
67 |
+
~~~
|
ToxiCN_1.0.csv
ADDED
The diff for this file is too large to render.
See raw diff
|
|
ToxiCN_ex/ToxiCN/data/test.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
ToxiCN_ex/ToxiCN/data/train.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
ToxiCN_ex/ToxiCN/lexicon/LGBT.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"基佬": [1825, 878], "炼铜": [4159, 7198], "txl": [162, 8206, 8178], "基蛆": [1825, 6025], "男同": [4511, 1398], "反同": [1353, 1398], "恐同": [2607, 1398], "同志": [1398, 2562], "gay": [149, 143, 167], "通讯录": [6858, 6380, 2497], "撑同": [3053, 1398], "鸡老": [7883, 5439], "直佬": [4684, 878], "反铜": [1353, 7198], "艾基": [5687, 1825], "艾兹佬": [5687, 1074, 878], "男铜": [4511, 7198], "鸡佬": [7883, 878], "ltp": [10413, 8187], "屠同": [2248, 1398], "繁殖批": [5246, 3658, 2821], "染艾": [3381, 5687], "同杏恋": [1398, 3331, 2605], "断袖": [3171, 6153], "龙阳之好": [7987, 7345, 722, 1962], "击佬": [1140, 878], "男童": [4511, 4997]}
|
ToxiCN_ex/ToxiCN/lexicon/general.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"神经": [4868, 5307], "神经病": [4868, 5307, 4567], "垃圾": [1796, 1769], "艹": [5685], "草": [5770], "辣鸡": [6793, 7883], "傻逼": [1004, 6873], "萨比": [5855, 3683], "煞笔": [4208, 5011], "沙软": [3763, 6763], "沙軟": [3763, 6727], "法西斯": [3791, 6205, 3172], "几把": [1126, 2828], "肥猪": [5503, 4343], "尼玛": [2225, 4377], "傻X": [1004, 166], "舔狗": [5654, 4318], "狗": [4318], "猪": [4343], "废物": [2426, 4289], "儒猴": [1027, 4347], "他妈": [800, 1968], "鬼话": [7787, 6413], "脑瘫": [5554, 4611], "巨婴": [2342, 2048], "驴": [7723], "蠢驴": [6111, 7723], "特么": [4294, 720], "捏麻麻的": [2934, 7937, 7937, 4638], "绿毛龟": [5344, 3688, 7991], "不得house": [679, 2533, 150, 157, 163, 161, 147], "你妈妈的": [872, 1968, 1968, 4638], "捏妈妈的": [2934, 1968, 1968, 4638], "小屁孩": [2207, 2230, 2111], "弱智": [2483, 3255], "批": [2821], "贵物": [6586, 4289], "畜生": [4523, 4495], "蛆": [6025], "屎": [2241], "货色": [6573, 5682], "勾八": [1256, 1061], "妈的": [1968, 4638], "傻卵": [1004, 1317], "啥卵": [1567, 1317], "放屁": [3123, 2230], "牛鬼蛇神": [4281, 7787, 6026, 4868], "精神病": [5125, 4868, 4567], "狗屁": [4318, 2230], "猪精": [4343, 5125], "沸物": [3778, 4289], "伞兵": [835, 1070], "乞丐": [737, 681], "疯狗": [4556, 4318], "嘴炮": [1673, 4152], "鬼母": [7787, 3678], "智障": [3255, 7397], "变态": [1359, 2578], "他妈的": [800, 1968, 4638], "你妈的": [872, 1968, 4638], "你他妈的": [872, 800, 1968, 4638], "鸟事": [7881, 752], "活该": [3833, 6421], "操蛋": [3082, 6028], "烂裤裆": [4162, 6175, 6164], "孝子": [2105, 2094], "奴隶": [1958, 7405], "死一死": [3647, 671, 3647], "傻B": [1004, 144], "爆杀": [4255, 3324], "下头": [678, 1928], "鲨bee": [7835, 8815, 8154], "牲口": [4291, 1366], "吸血虫": [1429, 6117, 6001], "吸血鬼": [1429, 6117, 7787], "吊": [1396], "网曝": [5381, 3284], "网暴": [5381, 3274], "畜牲": [4523, 4291], "孽": [2121], "寄生虫": [2164, 4495, 6001], "弱指": [2483, 2900], "坦克": [1788, 1046], "鲨鼻": [7835, 7965], "捧杀": [2942, 3324], "寄吧": [2164, 1416], "p事": [158, 752], "贱": [6583], "蠢": [6111], "傻子": [1004, 2094], "粪": [5116], "崽子": [2312, 2094], "苟": [5732], "穷b": [4956, 144], "魔怔": [7795, 2585], "牛头人": [4281, 1928, 782], "牛马": [4281, 7716], "乐子人": [727, 2094, 782], "鸵鸟": [7893, 7881], "呆子": [1438, 2094], "歪皮": [3639, 4649], "憨憨": [2736, 2736], "矮子": [4765, 2094], "蒻痣": [5894, 4582], "撒币": [3054, 2355], "小丑": [2207, 682], "你妈": [872, 1968], "菊花": [5825, 5709], "喷子": [1613, 2094], "傻*": [1004, 115], "给爷爬": [5314, 4267, 4260], "狗腿子": [4318, 5597, 2094], "÷剩": [193, 1197], "恶熏": [2626, 4221], "鼠鼠": [7962, 7962], "僵尸": [1018, 2221], "暴毙": [3274, 3687], "孙杂": [2101, 3325], "杂皮": [3325, 4649], "有大病": [3300, 1920, 4567], "你是个什么东西": [872, 3221, 702, 784, 720, 691, 6205], "沙币": [3763, 2355], "白莲": [4635, 5813], "沙峦": [3763, 2287], "熊孩子": [4220, 2111, 2094], "嘿涩蕙": [1678, 3886, 5936], "瘪三": [4610, 676], "老鼠": [5439, 7962], "二极管": [753, 3353, 5052], "恶心": [2626, 2552], "下三滥": [678, 676, 4010], "双标": [1352, 3403], "口区": [1366, 1277], "蛀虫": [6024, 6001], "搅屎棍": [3009, 2241, 3471], "蛆丝": [6025, 692], "傻呗": [1004, 1446], "强奸犯": [2487, 1960, 4306], "吃枣药丸": [1391, 3365, 5790, 709], "呸": [1459], "这b": [6821, 144], "铁花生": [7188, 5709, 4495], "牠": [4284], "吉拔": [1395, 2869], "屌逼": [2239, 6873], "冲爆": [1103, 4255], "孽畜": [2121, 4523], "眼瞎": [4706, 4735], "小鬼": [2207, 7787], "淦死": [3911, 3647], "淦": [3911], "瘠薄": [4603, 5946], "跪舔": [6661, 5654], "塌马": [1847, 7716], "跪族": [6661, 3184], "粪蛋": [5116, 6028], "乐色": [727, 5682], "渣子": [3942, 2094], "杂毛": [3325, 3688], "色狼": [5682, 4331], "杂碎": [3325, 4810], "杂种": [3325, 4905], "沙口": [3763, 1366], "瞎": [4735], "鬼子": [7787, 2094], "奴才": [1958, 2798], "走狗": [6624, 4318], "爪牙": [4259, 4280], "败类": [6571, 5102], "憨批": [2736, 2821], "狗东西": [4318, 691, 6205], "街溜子": [6125, 3977, 2094], "诡雷": [6417, 7440], "烂裤子": [4162, 6175, 2094], "色胚": [5682, 5524], "狗贼": [4318, 6592], "丁丁": [672, 672], "强奸": [2487, 1960], "造孽": [6863, 2121], "pussy": [11227, 8565, 8179], "一棒子打死": [671, 3472, 2094, 2802, 3647], "杠精": [3339, 5125], "tm": [9908], "jb": [13063], "sj": [161, 8334], "sb": [12359], "nm": [156, 8175], "der": [9157], "nt": [8495], "tmd": [9908, 8168], "qj": [159, 8334], "md": [11399], "fw": [148, 8220], "j8": [152, 8156], "ntr": [8495, 8180], "zz": [168, 8253], "lkd": [154, 8197, 8168], "ex": [9577], "pua": [11227, 8139], "qs": [11974], "loser": [12264, 9520]}
|
ToxiCN_ex/ToxiCN/lexicon/racism.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"黑叔叔": [7946, 1356, 1356], "原": [1333], "洋大人": [3817, 1920, 782], "洋爹": [3817, 4269], "默": [7949], "白楠": [4635, 3507], "n哥": [156, 1520], "ni哥": [10560, 1520], "歪果仁": [3639, 3362, 785], "歪果": [3639, 3362], "泥娃娃": [3799, 2015, 2015], "尼哥": [2225, 1520], "泥哥": [3799, 1520], "尼葛": [2225, 5867], "黒鬼": [7946, 7787], "昆仑奴": [3204, 796, 1958], "泥鸽": [3799, 7894], "嘿鬼": [1678, 7787], "黑蛆": [7946, 6025], "跪虫族": [6661, 6001, 3184], "虫族": [6001, 3184], "黒杂": [7947, 3325], "黑杂种": [7946, 3325, 4905], "黑混": [7946, 3921], "黑砸": [7946, 4790], "混黑": [3921, 7946], "嘿砸": [1678, 4790], "黑泥鳅": [7946, 3799, 7844], "嘿蛆": [1678, 6025], "嘿爹": [1678, 4269], "黑爹": [7946, 4269], "黑哥": [7946, 1520], "嘿哥": [1678, 1520], "猩猩": [4342, 4342], "命贵": [1462, 6586], "黑命贵": [7946, 1462, 6586], "nigger": [10560, 9949, 8196], "黑狗": [7946, 4318], "泥革": [3799, 7484], "嘿狗": [1678, 4318], "倪格": [960, 3419], "嘿虫": [1678, 6001], "黑虫": [7946, 6001], "嗨人": [1635, 782], "黑比": [7946, 3683], "嘿比": [1678, 3683], "黑逼": [7946, 6873], "嘿逼": [1678, 6873], "嘿砸肿": [1678, 4790, 5514], "犹太狗": [4310, 1922, 4318], "黑杂碎": [7946, 3325, 4810], "黑犬": [7946, 4305], "嘿嘿": [1678, 1678], "黑黑": [7946, 7946], "倪哥": [960, 1520], "反三非": [1353, 676, 7478], "三非": [676, 7478], "反黑": [1353, 7946], "小黑": [2207, 7946], "黑枸": [7946, 3375], "嘿枸": [1678, 3375], "黑猴子": [7946, 4347, 2094], "洋垃圾": [3817, 1796, 1769], "黑吹": [7946, 1430], "黑小子": [7946, 2207, 2094], "黑玩意": [7946, 4381, 2692], "嘿玩意": [1678, 4381, 2692], "嘿杂碎": [1678, 3325, 4810], "嘿杂种": [1678, 3325, 4905], "人妖": [782, 1973], "白皮猪": [4635, 4649, 4343], "串串": [706, 706], "嘿畜": [1678, 4523], "黑畜": [7946, 4523], "小二黑": [2207, 753, 7946], "小二嘿": [2207, 753, 1678], "黑贵": [7946, 6586], "嘿贵": [1678, 6586], "黑粪": [7946, 5116], "类人猿": [5102, 782, 4351], "人猿": [782, 4351], "舔黑": [5654, 7946], "黑皮": [7946, 4649], "嘿皮": [1678, 4649], "黑乐色": [7946, 727, 5682], "嘿乐色": [1678, 727, 5682], "黑沙口": [7946, 3763, 1366], "嘿沙口": [1678, 3763, 1366], "墨": [1874], "默人": [7949, 782], "墨人": [1874, 782], "黑醋": [7946, 7005], "黑杂": [7946, 3325], "默妖": [7949, 1973], "黑猩猩": [7946, 4342, 4342], "嘿猩猩": [1678, 4342, 4342], "媚黑": [2055, 7946], "飞周人": [7607, 1453, 782], "鬼子虫类": [7787, 2094, 6001, 5102], "虫混": [6001, 3921], "黑非洲": [7946, 7478, 3828], "媚白": [2055, 4635], "非洲佬": [7478, 3828, 878], "嘿硅": [1678, 4795], "黑硅": [7946, 4795], "黑不溜秋": [7946, 679, 3977, 4904], "黑子哥": [7946, 2094, 1520], "灭默": [4127, 7949], "屠默": [2248, 7949], "猎默": [4333, 7949], "杀默": [3324, 7949], "反默": [1353, 7949], "虫类": [6001, 5102], "国际鬼子虫类": [1744, 7354, 7787, 2094, 6001, 5102], "屠嘿": [2248, 1678], "屠黑": [2248, 7946], "媚嘿": [2055, 1678], "凯乐奇": [1132, 727, 1936], "hr": [8967], "凯乐奇计划": [1132, 727, 1936, 6369, 1153], "凯勒奇": [1132, 1239, 1936], "凯勒奇计划": [1132, 1239, 1936, 6369, 1153], "红毛鬼子": [5273, 3688, 7787, 2094], "煤精": [4209, 5125], "类人": [5102, 782], "黑哥哥": [7946, 1520, 1520], "黑妹妹": [7946, 1987, 1987], "黑族": [7946, 3184], "黑娃娃": [7946, 2015, 2015], "反白": [1353, 4635], "跪洋": [6661, 3817], "白皮": [4635, 4649], "哥布林": [1520, 2357, 3360], "肖万": [5494, 674], "h人": [150, 782], "黑北鼻": [7946, 1266, 7965], "羊大人": [5399, 1920, 782], "泥搁": [3799, 3007], "魄": [7790], "白腩": [4635, 5583], "黑男": [7946, 4511], "黑女": [7946, 1957], "崇洋媚外": [2300, 3817, 2055, 1912], "黑淫": [7946, 3915]}
|
ToxiCN_ex/ToxiCN/lexicon/region.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"南满": [1298, 4007], "南蛮": [1298, 6037], "蛮子": [6037, 2094], "棒子": [3472, 2094], "小日本": [2207, 3189, 3315], "漂亮国": [4023, 778, 1744], "南大人": [1298, 1920, 782], "弯弯": [2482, 2482], "湾湾": [3968, 3968], "西八": [6205, 1061], "棒男": [3472, 4511], "棒女": [3472, 1957], "山东葱": [2255, 691, 5876], "蛮": [6037], "满子": [4007, 2094], "蛮夷": [6037, 1929], "喃蛮": [1586, 6037], "南宋人": [1298, 2129, 782], "西戎": [6205, 2766], "北狄": [1266, 4313], "东夷": [691, 1929], "北佬": [1266, 878], "偷井盖": [982, 759, 4667], "山越猴": [2255, 6632, 4347], "京巴": [776, 2349], "九头鸟": [736, 1928, 7881], "东百": [691, 4636], "白完": [4635, 2130], "胡建": [5529, 2456], "陕蛋蛋": [7362, 6028, 6028], "百越": [4636, 6632], "狗日的": [4318, 3189, 4638], "红脖子": [5273, 5556, 2094], "巴铁": [2349, 7188], "三哥": [676, 1520], "阿三": [7350, 676], "小鬼子": [2207, 7787, 2094], "小日子": [2207, 3189, 2094], "倭狗": [963, 4318], "倭": [963], "倭寇": [963, 2167], "日杂": [3189, 3325], "飞周": [7607, 1453], "飞舟": [7607, 5660], "高卢乌鸡": [7770, 1306, 723, 7883], "美国佬": [5401, 1744, 878], "乡巴佬": [740, 2349, 878]}
|
ToxiCN_ex/ToxiCN/lexicon/sexism.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"婊": [2040], "婊子": [2040, 2094], "拳师": [2891, 2360], "开苞": [2458, 5731], "骚": [7746], "绝育": [5318, 5509], "奇趣蛋": [1936, 6637, 6028], "母狗": [3678, 4318], "牧狗": [4288, 4318], "幕刃": [2391, 1145], "慕刃": [2710, 1145], "亩人": [774, 782], "鸡": [7883], "龟男": [7991, 4511], "龟楠": [7991, 3507], "普信男": [3249, 928, 4511], "普信": [3249, 928], "女拳": [1957, 2891], "男拳": [4511, 2891], "仙女": [803, 1957], "小仙女": [2207, 803, 1957], "小藓女": [2207, 5968, 1957], "女厕所": [1957, 1329, 2792], "幕人": [2391, 782], "慕人": [2710, 782], "幕勾": [2391, 1256], "慕勾": [2710, 1256], "国铝": [1744, 7199], "亩狗": [774, 4318], "亩勾": [774, 1256], "亩篝": [774, 5068], "亩刃": [774, 1145], "亩": [774], "龟仙人": [7991, 803, 782], "姆蛆": [1990, 6025], "阿娜": [7350, 2025], "easygirl": [9935, 9375], "eg": [147, 8181], "÷女": [193, 1957], "姆搐": [1990, 3012], "蝈女": [6067, 1957], "木勾": [3312, 1256], "鲍鱼": [7828, 7824], "妓女": [1972, 1957], "母拳": [3678, 2891], "普信女": [3249, 928, 1957], "绿帽": [5344, 2384], "穆狗": [4946, 4318], "母猪": [3678, 4343], "厌女": [1328, 1957], "硅南": [4795, 1298], "粿": [5126], "公狗": [1062, 4318], "犬男": [4305, 4511], "沐勾": [3759, 1256], "拳畜": [2891, 4523], "母畜": [3678, 4523], "牧人": [4288, 782], "钼刃": [7184, 1145], "娘炮": [2023, 4152], "慕√": [2710, 380], "烧鸡": [4173, 7883], "女醛": [1957, 7010], "姆坦": [1990, 1788], "墓垢": [1867, 1803], "薇安妇": [5948, 2128, 1967], "慰安妇": [2720, 2128, 1967], "女犬": [1957, 4305], "妈宝女": [1968, 2140, 1957], "妈宝男": [1968, 2140, 4511], "腐女": [5576, 1957], "母坦": [3678, 1788], "肉便器": [5489, 912, 1690], "直男癌": [4684, 4511, 4617], "郭女": [6958, 1957], "田园女拳": [4506, 1736, 1957, 2891], "田园女权": [4506, 1736, 1957, 3326], "绿茶": [5344, 5763], "绿茶婊": [5344, 5763, 2040], "男淫": [4511, 3915], "烂货": [4162, 6573], "腩人": [5583, 782], "蝈腩": [6067, 5583], "女贼": [1957, 6592], "七尺大儒": [673, 2223, 1920, 1027], "拳虱": [2891, 6003], "圣母": [1760, 3678], "织女": [5302, 1957], "母朱": [3678, 3319], "腐癌": [5576, 4617], "站街女": [4991, 6125, 1957], "龟奴": [7991, 1958], "乌龟精": [723, 7991, 5125], "娘们": [2023, 812], "脑残女": [5554, 3655, 1957], "窑姐": [4965, 1995], "郭南": [6958, 1298], "ezg": [147, 8253, 8181], "田园表": [4506, 1736, 6134], "田园婊": [4506, 1736, 2040], "表子": [6134, 2094], "xdz": [8444, 8253], "小吊子": [2207, 1396, 2094], "金针菇": [7032, 7151, 5823], "田园女": [4506, 1736, 1957], "中华田园犬": [704, 1290, 4506, 1736, 4305], "国楠": [1744, 3507], "子宫战": [2094, 2151, 2773], "人造子宫": [782, 6863, 2094, 2151], "母沟": [3678, 3765], "锅女": [7222, 1957], "打拳": [2802, 2891], "姆的": [1990, 4638], "八婆": [1061, 2038], "sao": [3221, 12053], "骚女": [7746, 1957], "sao女": [3221, 12053, 1957], "幕√": [2391, 380]}
|
ToxiCN_ex/model/Config_base.py
ADDED
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding: UTF-8
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
import torch.nn.functional as F
|
5 |
+
import numpy as np
|
6 |
+
|
7 |
+
import os
|
8 |
+
from os import path
|
9 |
+
|
10 |
+
|
11 |
+
# 2022.7.27 config基类
|
12 |
+
|
13 |
+
class Config_base(object):
|
14 |
+
|
15 |
+
"""配置参数"""
|
16 |
+
def __init__(self, model_name, dataset):
|
17 |
+
# path
|
18 |
+
self.model_name = model_name
|
19 |
+
self.train_path = path.dirname(path.dirname(__file__))+'/'+ dataset + '/data/train.json' # 训练集
|
20 |
+
self.dev_path = path.dirname(path.dirname(__file__))+'/'+ dataset + '/data/test.json' # 验证集
|
21 |
+
self.test_path = path.dirname(path.dirname(__file__))+'/'+ dataset + '/data/test.json' # 测试集
|
22 |
+
|
23 |
+
self.vocab_path = path.dirname(path.dirname(__file__))+'/'+ dataset + '/data/vocab.pkl'
|
24 |
+
self.lexicon_path = path.dirname(path.dirname(__file__))+'/'+ dataset + '/lexicon/' # 数据集、模型训练结果 # 词表
|
25 |
+
self.result_path = path.dirname(path.dirname(__file__))+'/' + dataset + '/result'
|
26 |
+
self.checkpoint_path = path.dirname(path.dirname(__file__))+'/'+ dataset + '/saved_dict' # 数据集、模型训练结果
|
27 |
+
self.data_path = self.checkpoint_path + '/data.tar'
|
28 |
+
# self.log_path = path.dirname(path.dirname(__file__))+'/'+ dataset + '/log/' + self.model_name
|
29 |
+
# self.embedding_pretrained = torch.tensor(
|
30 |
+
# np.load(path.dirname(path.dirname(__file__))+'/'+ 'THUCNews' + '/data/' + embedding)["embeddings"].astype('float32'))\
|
31 |
+
# if embedding != 'random' else None # 预训练词向量
|
32 |
+
self.word2vec_path = path.dirname(path.dirname(path.dirname(__file__)))+"/glove/source/glove.6B.300d.bin"
|
33 |
+
# self.plm = "roberta-base" # 预训练模型
|
34 |
+
# self.plm = "bert-base-chinese"
|
35 |
+
|
36 |
+
# dataset
|
37 |
+
self.seed = 1
|
38 |
+
# self.require_improvement = 1000 # 若超过1000batch效果还没提升,则提前结束训练 transformer:2000
|
39 |
+
self.num_classes = 2 # 类别数
|
40 |
+
# self.n_vocab = 0 # 词表大小,在运行时赋值
|
41 |
+
self.pad_size = 80 # 每句话处理成的长度(短填长切)
|
42 |
+
|
43 |
+
# model
|
44 |
+
self.dropout = 0.5 # 随机失活
|
45 |
+
self.vocab_dim = 768
|
46 |
+
self.fc_hidden_dim = 256
|
47 |
+
|
48 |
+
# train
|
49 |
+
self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') # 设备
|
50 |
+
self.learning_rate = 1e-5 # 学习率 transformer:5e-4
|
51 |
+
self.scheduler = False # 是否学习率衰减
|
52 |
+
self.adversarial = False # 是否对抗训练
|
53 |
+
self.num_warm = 0 # 开始验证的epoch数
|
54 |
+
self.num_epochs = 5 # epoch数
|
55 |
+
self.batch_size = 32 # mini-batch大小
|
56 |
+
|
57 |
+
# loss
|
58 |
+
self.alpha1 = 0.5
|
59 |
+
self.gamma1 = 4
|
60 |
+
|
61 |
+
# evaluate
|
62 |
+
self.threshold = 0.5 # 二分类阈值
|
63 |
+
self.score_key = "F1" # 评价指标
|
64 |
+
|
65 |
+
if __name__ == '__main__':
|
66 |
+
config = Config_base("BERT", "SWSR")
|
67 |
+
print(config.vocab_path)
|
68 |
+
print(config.word2vec_path)
|
69 |
+
print(path.dirname(__file__))
|
70 |
+
print(path.dirname(path.dirname(__file__)))
|
ToxiCN_ex/requirements.txt
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
gensim==3.8.3
|
2 |
+
jieba==0.42.1
|
3 |
+
nltk==3.7
|
4 |
+
numpy==1.21.2
|
5 |
+
ray==1.13.0
|
6 |
+
scikit_learn==1.1.2
|
7 |
+
tensorboardX==2.5.1
|
8 |
+
torch==1.7.0
|
9 |
+
tqdm==4.64.0
|
10 |
+
transformers==3.4.0
|
ToxiCN_ex/run.py
ADDED
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from importlib import import_module
|
2 |
+
from src.datasets import *
|
3 |
+
import os
|
4 |
+
from os import path
|
5 |
+
import numpy as np
|
6 |
+
from train_eval import train, eval
|
7 |
+
import argparse
|
8 |
+
from src.Models import *
|
9 |
+
|
10 |
+
from ray import tune
|
11 |
+
from ray.tune.schedulers import ASHAScheduler
|
12 |
+
|
13 |
+
parser = argparse.ArgumentParser(description='Chinese Toxic Classification')
|
14 |
+
parser.add_argument('--mode', default="train", type=str, help='train/test')
|
15 |
+
# 是否微调超参数
|
16 |
+
parser.add_argument('--tune_param', default=False, type=bool, help='True for param tuning')
|
17 |
+
parser.add_argument('--tune_samples', default=1, type=int, help='Number of tuning experiments to run')
|
18 |
+
parser.add_argument('--tune_asha', default=False, type=bool, help='If use ASHA scheduler for early stopping')
|
19 |
+
parser.add_argument('--tune_file', default='RoBERTa', type=str, help='Suffix of filename for parameter tuning results')
|
20 |
+
parser.add_argument('--tune_gpu', default=True, type=bool, help='Use GPU to tune parameters')
|
21 |
+
args = parser.parse_args()
|
22 |
+
|
23 |
+
# TOC
|
24 |
+
# search_space = {
|
25 |
+
# 'learning_rate': tune.choice([1e-5, 5e-5]),
|
26 |
+
# 'num_epochs': tune.choice([5]),
|
27 |
+
# 'batch_size': tune.choice([32, 64]),
|
28 |
+
# 'dropout': tune.choice([0.2, 0.5]),
|
29 |
+
# 'seed': tune.choice([1]),
|
30 |
+
# "pad_size" : tune.choice([50, 100])
|
31 |
+
# }
|
32 |
+
|
33 |
+
# THUCnews
|
34 |
+
search_space = {
|
35 |
+
'learning_rate': tune.choice([1e-5]),
|
36 |
+
'num_epochs': tune.choice([5]),
|
37 |
+
'batch_size': tune.choice([32]),
|
38 |
+
# 'dropout': tune.choice([0.2, 0.3, 0.5]),
|
39 |
+
'seed': tune.choice([1]),
|
40 |
+
"pad_size" : tune.choice([80]),
|
41 |
+
"alpha1" : tune.choice([0.5])
|
42 |
+
}
|
43 |
+
|
44 |
+
def convert_label(preds):
|
45 |
+
final_pred = []
|
46 |
+
for pred in preds:
|
47 |
+
if pred == [1, 0]:
|
48 |
+
final_pred.append("offensive")
|
49 |
+
else:
|
50 |
+
final_pred.append("non-offensive")
|
51 |
+
return final_pred
|
52 |
+
|
53 |
+
if __name__ == '__main__':
|
54 |
+
# dataset = 'TOC' # 数据集
|
55 |
+
dataset = "ToxiCN"
|
56 |
+
# model_name = "bert-base-chinese"
|
57 |
+
model_name = "hfl/chinese-roberta-wwm-ext"
|
58 |
+
# model_name = "junnyu/ChineseBERT-base"
|
59 |
+
|
60 |
+
np.random.seed(1)
|
61 |
+
torch.manual_seed(1)
|
62 |
+
torch.cuda.manual_seed_all(1)
|
63 |
+
torch.backends.cudnn.deterministic = True # 保证每次结果一样
|
64 |
+
|
65 |
+
start_time = time.time()
|
66 |
+
print("Loading data...")
|
67 |
+
|
68 |
+
x = import_module('model.' + "Config_base")
|
69 |
+
config = x.Config_base(model_name, dataset) # 引入Config参数,包括Config_base和各私有Config
|
70 |
+
|
71 |
+
if not os.path.exists(config.data_path):
|
72 |
+
trn_data = Datasets(config, config.train_path)
|
73 |
+
dev_data = Datasets(config, config.dev_path)
|
74 |
+
test_data = Datasets(config, config.test_path)
|
75 |
+
torch.save({
|
76 |
+
'trn_data' : trn_data,
|
77 |
+
'dev_data' : dev_data,
|
78 |
+
'test_data' : test_data,
|
79 |
+
}, config.data_path)
|
80 |
+
else:
|
81 |
+
checkpoint = torch.load(config.data_path)
|
82 |
+
trn_data = checkpoint['trn_data']
|
83 |
+
dev_data = checkpoint['dev_data']
|
84 |
+
test_data = checkpoint['test_data']
|
85 |
+
print('The size of the Training dataset: {}'.format(len(trn_data)))
|
86 |
+
print('The size of the Validation dataset: {}'.format(len(dev_data)))
|
87 |
+
print('The size of the Test dataset: {}'.format(len(test_data)))
|
88 |
+
train_iter = Dataloader(trn_data, batch_size=int(config.batch_size), SEED=config.seed)
|
89 |
+
dev_iter = Dataloader(dev_data, batch_size=int(config.batch_size), shuffle=False)
|
90 |
+
test_iter = Dataloader(test_data, batch_size=int(config.batch_size), shuffle=False)
|
91 |
+
|
92 |
+
time_dif = get_time_dif(start_time)
|
93 |
+
print("Time usage:", time_dif)
|
94 |
+
|
95 |
+
def experiment(tune_config):
|
96 |
+
if tune_config:
|
97 |
+
for param in tune_config:
|
98 |
+
setattr(config, param, tune_config[param])
|
99 |
+
train(config, train_iter, dev_iter, test_iter)
|
100 |
+
|
101 |
+
if args.mode == "train":
|
102 |
+
if args.tune_param:
|
103 |
+
scheduler = ASHAScheduler(metric='metric', mode="max") if args.tune_asha else None
|
104 |
+
analysis = tune.run(experiment, num_samples=args.tune_samples, config=search_space, resources_per_trial={'gpu':int(args.tune_gpu)},
|
105 |
+
scheduler=scheduler,
|
106 |
+
verbose=3)
|
107 |
+
analysis.results_df.to_csv('tune_results_'+args.tune_file+'.csv')
|
108 |
+
# if not tune parameters
|
109 |
+
else:
|
110 |
+
experiment(tune_config=None)
|
111 |
+
|
112 |
+
else:
|
113 |
+
embed_model = Bert_Layer(config).to(config.device)
|
114 |
+
model = TwoLayerFFNNLayer(config).to(config.device)
|
115 |
+
# model_name = "ckp-bert-base-chinese-NN_ML-100_D-0.2_B-64_E-5_Lr-1e-05-BEST.tar"
|
116 |
+
model_name = "ckp-bert-base-chinese-NN_ML-150_D-0.5_B-32_E-2_Lr-1e-05-BEST.tar"
|
117 |
+
path = '{}/{}'.format(config.checkpoint_path, model_name)
|
118 |
+
checkpoint = torch.load(path)
|
119 |
+
embed_model.load_state_dict(checkpoint['embed_model_state_dict'])
|
120 |
+
model.load_state_dict(checkpoint['model_state_dict'])
|
121 |
+
loss_fn = nn.BCEWithLogitsLoss()
|
122 |
+
dev_scores, preds = eval(config, embed_model, model, loss_fn, dev_iter, data_name='TEST')
|
123 |
+
print(convert_label(preds))
|
ToxiCN_ex/src/BERT.py
ADDED
@@ -0,0 +1,507 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""PyTorch BERT model. """
|
2 |
+
|
3 |
+
|
4 |
+
import logging
|
5 |
+
import math
|
6 |
+
import os
|
7 |
+
import warnings
|
8 |
+
|
9 |
+
import torch
|
10 |
+
import torch.utils.checkpoint
|
11 |
+
from torch import nn
|
12 |
+
from torch.nn import CrossEntropyLoss, MSELoss
|
13 |
+
|
14 |
+
from transformers.activations import gelu, gelu_new, swish
|
15 |
+
from transformers.configuration_bert import BertConfig
|
16 |
+
from transformers.file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_callable
|
17 |
+
from transformers.modeling_utils import PreTrainedModel, find_pruneable_heads_and_indices, prune_linear_layer
|
18 |
+
|
19 |
+
|
20 |
+
logger = logging.getLogger(__name__)
|
21 |
+
|
22 |
+
BERT_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
23 |
+
"bert-base-uncased",
|
24 |
+
"bert-large-uncased",
|
25 |
+
"bert-base-cased",
|
26 |
+
"bert-large-cased",
|
27 |
+
"bert-base-multilingual-uncased",
|
28 |
+
"bert-base-multilingual-cased",
|
29 |
+
"bert-base-chinese",
|
30 |
+
"bert-base-german-cased",
|
31 |
+
"bert-large-uncased-whole-word-masking",
|
32 |
+
"bert-large-cased-whole-word-masking",
|
33 |
+
"bert-large-uncased-whole-word-masking-finetuned-squad",
|
34 |
+
"bert-large-cased-whole-word-masking-finetuned-squad",
|
35 |
+
"bert-base-cased-finetuned-mrpc",
|
36 |
+
"bert-base-german-dbmdz-cased",
|
37 |
+
"bert-base-german-dbmdz-uncased",
|
38 |
+
"cl-tohoku/bert-base-japanese",
|
39 |
+
"cl-tohoku/bert-base-japanese-whole-word-masking",
|
40 |
+
"cl-tohoku/bert-base-japanese-char",
|
41 |
+
"cl-tohoku/bert-base-japanese-char-whole-word-masking",
|
42 |
+
"TurkuNLP/bert-base-finnish-cased-v1",
|
43 |
+
"TurkuNLP/bert-base-finnish-uncased-v1",
|
44 |
+
"wietsedv/bert-base-dutch-cased",
|
45 |
+
# See all BERT models at https://huggingface.co/models?filter=bert
|
46 |
+
]
|
47 |
+
|
48 |
+
|
49 |
+
def mish(x):
|
50 |
+
return x * torch.tanh(nn.functional.softplus(x))
|
51 |
+
|
52 |
+
|
53 |
+
ACT2FN = {"gelu": gelu, "relu": torch.nn.functional.relu, "swish": swish, "gelu_new": gelu_new, "mish": mish}
|
54 |
+
|
55 |
+
|
56 |
+
BertLayerNorm = torch.nn.LayerNorm
|
57 |
+
|
58 |
+
|
59 |
+
class BertEmbeddings(nn.Module):
|
60 |
+
"""Construct the embeddings from word, position and token_type embeddings.
|
61 |
+
"""
|
62 |
+
|
63 |
+
def __init__(self, config):
|
64 |
+
super().__init__()
|
65 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
66 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
67 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
68 |
+
|
69 |
+
# 2022.10.8 toxic_embeddings: non-toxic + 5 kinds of toxic
|
70 |
+
self.toxic_embeddings = nn.Embedding(6, config.hidden_size)
|
71 |
+
|
72 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
73 |
+
# any TensorFlow checkpoint file
|
74 |
+
self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
75 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
76 |
+
|
77 |
+
# 2022.05.02 test token_tags
|
78 |
+
def forward(self, input_ids=None, token_type_ids=None, position_ids=None, token_tags=None, toxic_ids=None, inputs_embeds=None):
|
79 |
+
if input_ids is not None:
|
80 |
+
input_shape = input_ids.size()
|
81 |
+
else:
|
82 |
+
input_shape = inputs_embeds.size()[:-1]
|
83 |
+
|
84 |
+
seq_length = input_shape[1]
|
85 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
86 |
+
if position_ids is None:
|
87 |
+
position_ids = torch.arange(seq_length, dtype=torch.long, device=device)
|
88 |
+
position_ids = position_ids.unsqueeze(0).expand(input_shape)
|
89 |
+
if token_type_ids is None:
|
90 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
91 |
+
|
92 |
+
if inputs_embeds is None:
|
93 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
94 |
+
position_embeddings = self.position_embeddings(position_ids)
|
95 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
96 |
+
|
97 |
+
embeddings = inputs_embeds + position_embeddings + token_type_embeddings
|
98 |
+
# 2022.10.8 toxic_embeddings
|
99 |
+
if toxic_ids is not None:
|
100 |
+
toxic_embeddings = self.toxic_embeddings(toxic_ids)
|
101 |
+
embeddings += toxic_embeddings
|
102 |
+
|
103 |
+
embeddings = self.LayerNorm(embeddings)
|
104 |
+
embeddings = self.dropout(embeddings)
|
105 |
+
return embeddings
|
106 |
+
|
107 |
+
|
108 |
+
class BertSelfAttention(nn.Module):
|
109 |
+
def __init__(self, config):
|
110 |
+
super().__init__()
|
111 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
112 |
+
raise ValueError(
|
113 |
+
"The hidden size (%d) is not a multiple of the number of attention "
|
114 |
+
"heads (%d)" % (config.hidden_size, config.num_attention_heads)
|
115 |
+
)
|
116 |
+
|
117 |
+
self.num_attention_heads = config.num_attention_heads
|
118 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
119 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
120 |
+
|
121 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
122 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
123 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
124 |
+
|
125 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
126 |
+
|
127 |
+
def transpose_for_scores(self, x):
|
128 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
129 |
+
x = x.view(*new_x_shape)
|
130 |
+
return x.permute(0, 2, 1, 3)
|
131 |
+
|
132 |
+
def forward(
|
133 |
+
self,
|
134 |
+
hidden_states,
|
135 |
+
attention_mask=None,
|
136 |
+
head_mask=None,
|
137 |
+
encoder_hidden_states=None,
|
138 |
+
encoder_attention_mask=None,
|
139 |
+
output_attentions=False,
|
140 |
+
):
|
141 |
+
mixed_query_layer = self.query(hidden_states)
|
142 |
+
|
143 |
+
# If this is instantiated as a cross-attention module, the keys
|
144 |
+
# and values come from an encoder; the attention mask needs to be
|
145 |
+
# such that the encoder's padding tokens are not attended to.
|
146 |
+
if encoder_hidden_states is not None:
|
147 |
+
mixed_key_layer = self.key(encoder_hidden_states)
|
148 |
+
mixed_value_layer = self.value(encoder_hidden_states)
|
149 |
+
attention_mask = encoder_attention_mask
|
150 |
+
else:
|
151 |
+
mixed_key_layer = self.key(hidden_states)
|
152 |
+
mixed_value_layer = self.value(hidden_states)
|
153 |
+
|
154 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
155 |
+
key_layer = self.transpose_for_scores(mixed_key_layer)
|
156 |
+
value_layer = self.transpose_for_scores(mixed_value_layer)
|
157 |
+
|
158 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
159 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
160 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
161 |
+
if attention_mask is not None:
|
162 |
+
# Apply the attention mask is (precomputed for all layers in BertModel forward() function)
|
163 |
+
attention_scores = attention_scores + attention_mask
|
164 |
+
|
165 |
+
# Normalize the attention scores to probabilities.
|
166 |
+
attention_probs = nn.Softmax(dim=-1)(attention_scores)
|
167 |
+
|
168 |
+
# This is actually dropping out entire tokens to attend to, which might
|
169 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
170 |
+
attention_probs = self.dropout(attention_probs)
|
171 |
+
|
172 |
+
# Mask heads if we want to
|
173 |
+
if head_mask is not None:
|
174 |
+
attention_probs = attention_probs * head_mask
|
175 |
+
|
176 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
177 |
+
|
178 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
179 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
180 |
+
context_layer = context_layer.view(*new_context_layer_shape)
|
181 |
+
|
182 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
183 |
+
return outputs
|
184 |
+
|
185 |
+
|
186 |
+
class BertSelfOutput(nn.Module):
|
187 |
+
def __init__(self, config):
|
188 |
+
super().__init__()
|
189 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
190 |
+
self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
191 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
192 |
+
|
193 |
+
def forward(self, hidden_states, input_tensor):
|
194 |
+
hidden_states = self.dense(hidden_states)
|
195 |
+
hidden_states = self.dropout(hidden_states)
|
196 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
197 |
+
return hidden_states
|
198 |
+
|
199 |
+
|
200 |
+
class BertAttention(nn.Module):
|
201 |
+
def __init__(self, config):
|
202 |
+
super().__init__()
|
203 |
+
self.self = BertSelfAttention(config)
|
204 |
+
self.output = BertSelfOutput(config)
|
205 |
+
self.pruned_heads = set()
|
206 |
+
|
207 |
+
def prune_heads(self, heads):
|
208 |
+
if len(heads) == 0:
|
209 |
+
return
|
210 |
+
heads, index = find_pruneable_heads_and_indices(
|
211 |
+
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
|
212 |
+
)
|
213 |
+
|
214 |
+
# Prune linear layers
|
215 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
216 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
217 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
218 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
219 |
+
|
220 |
+
# Update hyper params and store pruned heads
|
221 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
222 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
223 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
224 |
+
|
225 |
+
def forward(
|
226 |
+
self,
|
227 |
+
hidden_states,
|
228 |
+
attention_mask=None,
|
229 |
+
head_mask=None,
|
230 |
+
encoder_hidden_states=None,
|
231 |
+
encoder_attention_mask=None,
|
232 |
+
output_attentions=False,
|
233 |
+
):
|
234 |
+
self_outputs = self.self(
|
235 |
+
hidden_states, attention_mask, head_mask, encoder_hidden_states, encoder_attention_mask, output_attentions,
|
236 |
+
)
|
237 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
238 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
239 |
+
return outputs
|
240 |
+
|
241 |
+
|
242 |
+
class BertIntermediate(nn.Module):
|
243 |
+
def __init__(self, config):
|
244 |
+
super().__init__()
|
245 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
246 |
+
if isinstance(config.hidden_act, str):
|
247 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
248 |
+
else:
|
249 |
+
self.intermediate_act_fn = config.hidden_act
|
250 |
+
|
251 |
+
def forward(self, hidden_states):
|
252 |
+
hidden_states = self.dense(hidden_states)
|
253 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
254 |
+
return hidden_states
|
255 |
+
|
256 |
+
|
257 |
+
class BertOutput(nn.Module):
|
258 |
+
def __init__(self, config):
|
259 |
+
super().__init__()
|
260 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
261 |
+
self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
262 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
263 |
+
|
264 |
+
def forward(self, hidden_states, input_tensor):
|
265 |
+
hidden_states = self.dense(hidden_states)
|
266 |
+
hidden_states = self.dropout(hidden_states)
|
267 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
268 |
+
return hidden_states
|
269 |
+
|
270 |
+
|
271 |
+
class BertLayer(nn.Module):
|
272 |
+
def __init__(self, config):
|
273 |
+
super().__init__()
|
274 |
+
self.attention = BertAttention(config)
|
275 |
+
self.is_decoder = config.is_decoder
|
276 |
+
if self.is_decoder:
|
277 |
+
self.crossattention = BertAttention(config)
|
278 |
+
self.intermediate = BertIntermediate(config)
|
279 |
+
self.output = BertOutput(config)
|
280 |
+
|
281 |
+
def forward(
|
282 |
+
self,
|
283 |
+
hidden_states,
|
284 |
+
attention_mask=None,
|
285 |
+
head_mask=None,
|
286 |
+
encoder_hidden_states=None,
|
287 |
+
encoder_attention_mask=None,
|
288 |
+
output_attentions=False,
|
289 |
+
):
|
290 |
+
self_attention_outputs = self.attention(
|
291 |
+
hidden_states, attention_mask, head_mask, output_attentions=output_attentions,
|
292 |
+
)
|
293 |
+
attention_output = self_attention_outputs[0]
|
294 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
295 |
+
|
296 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
297 |
+
cross_attention_outputs = self.crossattention(
|
298 |
+
attention_output,
|
299 |
+
attention_mask,
|
300 |
+
head_mask,
|
301 |
+
encoder_hidden_states,
|
302 |
+
encoder_attention_mask,
|
303 |
+
output_attentions,
|
304 |
+
)
|
305 |
+
attention_output = cross_attention_outputs[0]
|
306 |
+
outputs = outputs + cross_attention_outputs[1:] # add cross attentions if we output attention weights
|
307 |
+
|
308 |
+
intermediate_output = self.intermediate(attention_output)
|
309 |
+
layer_output = self.output(intermediate_output, attention_output)
|
310 |
+
outputs = (layer_output,) + outputs
|
311 |
+
return outputs
|
312 |
+
|
313 |
+
|
314 |
+
class BertEncoder(nn.Module):
|
315 |
+
def __init__(self, config):
|
316 |
+
super().__init__()
|
317 |
+
self.config = config
|
318 |
+
self.layer = nn.ModuleList([BertLayer(config) for _ in range(config.num_hidden_layers)])
|
319 |
+
|
320 |
+
def forward(
|
321 |
+
self,
|
322 |
+
hidden_states,
|
323 |
+
attention_mask=None,
|
324 |
+
head_mask=None,
|
325 |
+
encoder_hidden_states=None,
|
326 |
+
encoder_attention_mask=None,
|
327 |
+
output_attentions=False,
|
328 |
+
output_hidden_states=False,
|
329 |
+
):
|
330 |
+
all_hidden_states = ()
|
331 |
+
all_attentions = ()
|
332 |
+
for i, layer_module in enumerate(self.layer):
|
333 |
+
if output_hidden_states:
|
334 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
335 |
+
|
336 |
+
if getattr(self.config, "gradient_checkpointing", False):
|
337 |
+
|
338 |
+
def create_custom_forward(module):
|
339 |
+
def custom_forward(*inputs):
|
340 |
+
return module(*inputs, output_attentions)
|
341 |
+
|
342 |
+
return custom_forward
|
343 |
+
|
344 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
345 |
+
create_custom_forward(layer_module),
|
346 |
+
hidden_states,
|
347 |
+
attention_mask,
|
348 |
+
head_mask[i],
|
349 |
+
encoder_hidden_states,
|
350 |
+
encoder_attention_mask,
|
351 |
+
)
|
352 |
+
else:
|
353 |
+
layer_outputs = layer_module(
|
354 |
+
hidden_states,
|
355 |
+
attention_mask,
|
356 |
+
head_mask[i],
|
357 |
+
encoder_hidden_states,
|
358 |
+
encoder_attention_mask,
|
359 |
+
output_attentions,
|
360 |
+
)
|
361 |
+
hidden_states = layer_outputs[0]
|
362 |
+
|
363 |
+
if output_attentions:
|
364 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
365 |
+
|
366 |
+
# Add last layer
|
367 |
+
if output_hidden_states:
|
368 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
369 |
+
|
370 |
+
outputs = (hidden_states,)
|
371 |
+
if output_hidden_states:
|
372 |
+
outputs = outputs + (all_hidden_states,)
|
373 |
+
if output_attentions:
|
374 |
+
outputs = outputs + (all_attentions,)
|
375 |
+
return outputs # last-layer hidden state, (all hidden states), (all attentions)
|
376 |
+
|
377 |
+
|
378 |
+
class BertPooler(nn.Module):
|
379 |
+
def __init__(self, config):
|
380 |
+
super().__init__()
|
381 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
382 |
+
self.activation = nn.Tanh()
|
383 |
+
|
384 |
+
def forward(self, hidden_states):
|
385 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
386 |
+
# to the first token.
|
387 |
+
first_token_tensor = hidden_states[:, 0]
|
388 |
+
pooled_output = self.dense(first_token_tensor)
|
389 |
+
pooled_output = self.activation(pooled_output)
|
390 |
+
return pooled_output
|
391 |
+
|
392 |
+
|
393 |
+
class BertPreTrainedModel(PreTrainedModel):
|
394 |
+
config_class = BertConfig
|
395 |
+
base_model_prefix = "bert"
|
396 |
+
|
397 |
+
def _init_weights(self, module):
|
398 |
+
""" Initialize the weights """
|
399 |
+
if isinstance(module, (nn.Linear, nn.Embedding)):
|
400 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
401 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
402 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
403 |
+
elif isinstance(module, BertLayerNorm):
|
404 |
+
module.bias.data.zero_()
|
405 |
+
module.weight.data.fill_(1.0)
|
406 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
407 |
+
module.bias.data.zero_()
|
408 |
+
|
409 |
+
|
410 |
+
class BertModel(BertPreTrainedModel):
|
411 |
+
|
412 |
+
def __init__(self, config):
|
413 |
+
super().__init__(config)
|
414 |
+
self.config = config
|
415 |
+
|
416 |
+
self.embeddings = BertEmbeddings(config)
|
417 |
+
self.encoder = BertEncoder(config)
|
418 |
+
self.pooler = BertPooler(config)
|
419 |
+
|
420 |
+
self.init_weights()
|
421 |
+
|
422 |
+
def get_input_embeddings(self):
|
423 |
+
return self.embeddings.word_embeddings
|
424 |
+
|
425 |
+
def set_input_embeddings(self, value):
|
426 |
+
self.embeddings.word_embeddings = value
|
427 |
+
|
428 |
+
def _prune_heads(self, heads_to_prune):
|
429 |
+
for layer, heads in heads_to_prune.items():
|
430 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
431 |
+
|
432 |
+
def forward(
|
433 |
+
self,
|
434 |
+
input_ids=None,
|
435 |
+
attention_mask=None,
|
436 |
+
token_type_ids=None,
|
437 |
+
position_ids=None,
|
438 |
+
head_mask=None,
|
439 |
+
inputs_embeds=None,
|
440 |
+
encoder_hidden_states=None,
|
441 |
+
encoder_attention_mask=None,
|
442 |
+
output_attentions=None,
|
443 |
+
output_hidden_states=None,
|
444 |
+
toxic_ids=None,
|
445 |
+
):
|
446 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
447 |
+
output_hidden_states = (
|
448 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
449 |
+
)
|
450 |
+
|
451 |
+
if input_ids is not None and inputs_embeds is not None:
|
452 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
453 |
+
elif input_ids is not None:
|
454 |
+
input_shape = input_ids.size()
|
455 |
+
elif inputs_embeds is not None:
|
456 |
+
input_shape = inputs_embeds.size()[:-1]
|
457 |
+
else:
|
458 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
459 |
+
|
460 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
461 |
+
|
462 |
+
if attention_mask is None:
|
463 |
+
attention_mask = torch.ones(input_shape, device=device)
|
464 |
+
if token_type_ids is None:
|
465 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
466 |
+
|
467 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
468 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
469 |
+
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape, device)
|
470 |
+
|
471 |
+
# If a 2D ou 3D attention mask is provided for the cross-attention
|
472 |
+
# we need to make broadcastabe to [batch_size, num_heads, seq_length, seq_length]
|
473 |
+
if self.config.is_decoder and encoder_hidden_states is not None:
|
474 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
|
475 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
476 |
+
if encoder_attention_mask is None:
|
477 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
478 |
+
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
479 |
+
else:
|
480 |
+
encoder_extended_attention_mask = None
|
481 |
+
|
482 |
+
# Prepare head mask if needed
|
483 |
+
# 1.0 in head_mask indicate we keep the head
|
484 |
+
# attention_probs has shape bsz x n_heads x N x N
|
485 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
486 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
487 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
488 |
+
|
489 |
+
embedding_output = self.embeddings(
|
490 |
+
input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds
|
491 |
+
)
|
492 |
+
encoder_outputs = self.encoder(
|
493 |
+
embedding_output,
|
494 |
+
attention_mask=extended_attention_mask,
|
495 |
+
head_mask=head_mask,
|
496 |
+
encoder_hidden_states=encoder_hidden_states,
|
497 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
498 |
+
output_attentions=output_attentions,
|
499 |
+
output_hidden_states=output_hidden_states,
|
500 |
+
)
|
501 |
+
sequence_output = encoder_outputs[0]
|
502 |
+
pooled_output = self.pooler(sequence_output)
|
503 |
+
|
504 |
+
outputs = (sequence_output, pooled_output,) + encoder_outputs[
|
505 |
+
1:
|
506 |
+
] # add hidden_states and attentions if they are here
|
507 |
+
return outputs # sequence_output, pooled_output, (hidden_states), (attentions)
|
ToxiCN_ex/src/Models.py
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import BertModel
|
2 |
+
# from chinesebert import ChineseBertForMaskedLM, ChineseBertTokenizerFast, ChineseBertConfig
|
3 |
+
from src.BERT import BertModel
|
4 |
+
import torch
|
5 |
+
import torch.nn as nn
|
6 |
+
from torch.autograd import Variable
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
# 2022.4.28 Glove + LSTM
|
10 |
+
class BiLSTM(nn.Module):
|
11 |
+
def __init__(self, config, embedding_weight):
|
12 |
+
super(BiLSTM, self).__init__()
|
13 |
+
self.device = config.device
|
14 |
+
self.vocab_size = embedding_weight.shape[0]
|
15 |
+
self.embed_dim = embedding_weight.shape[1]
|
16 |
+
# Embedding Layer
|
17 |
+
embedding_weight = torch.from_numpy(embedding_weight).float()
|
18 |
+
embedding_weight = Variable(embedding_weight, requires_grad=config.if_grad)
|
19 |
+
self.embedding = nn.Embedding(self.vocab_size, self.embed_dim, _weight=embedding_weight)
|
20 |
+
# Encoder layer
|
21 |
+
self.bi_lstm = nn.LSTM(self.embed_dim, config.lstm_hidden_dim, bidirectional=True, batch_first=True)
|
22 |
+
|
23 |
+
def forward(self, **kwargs):
|
24 |
+
emb = self.embedding(kwargs["title_text_token_ids"].to(self.device)) # [batch, len] --> [batch, len, embed_dim]
|
25 |
+
lstm_out, _ = self.bi_lstm(emb) # [batch, len, embed_dim] --> [batch, len, lstm_hidden_dim*2]
|
26 |
+
lstm_out_pool = torch.mean(lstm_out, dim=1) # [batch, lstm_hidden_dim*2]
|
27 |
+
return lstm_out, lstm_out_pool
|
28 |
+
|
29 |
+
|
30 |
+
class Bert_Layer(torch.nn.Module):
|
31 |
+
def __init__(self, config):
|
32 |
+
super(Bert_Layer, self).__init__()
|
33 |
+
# self.use_cuda = kwargs['use_cuda']
|
34 |
+
self.device = config.device
|
35 |
+
# BERT/Roberta
|
36 |
+
self.bert_layer = BertModel.from_pretrained(config.model_name)
|
37 |
+
# ChineseBERT
|
38 |
+
# self.config = ChineseBertConfig.from_pretrained(config.model_name)
|
39 |
+
# self.bert_layer = ChineseBertForMaskedLM.from_pretrained("ShannonAI/ChineseBERT-base", config=self.config)
|
40 |
+
self.dim = config.vocab_dim
|
41 |
+
|
42 |
+
def forward(self, **kwargs):
|
43 |
+
bert_output = self.bert_layer(input_ids=kwargs['text_idx'].to(self.device),
|
44 |
+
token_type_ids=kwargs['text_ids'].to(self.device),
|
45 |
+
attention_mask=kwargs['text_mask'].to(self.device),
|
46 |
+
toxic_ids=kwargs["toxic_ids"].to(self.device))
|
47 |
+
return bert_output[0], bert_output[1]
|
48 |
+
|
49 |
+
|
50 |
+
class TwoLayerFFNNLayer(torch.nn.Module):
|
51 |
+
'''
|
52 |
+
2-layer FFNN with specified nonlinear function
|
53 |
+
must be followed with some kind of prediction layer for actual prediction
|
54 |
+
'''
|
55 |
+
def __init__(self, config):
|
56 |
+
super(TwoLayerFFNNLayer, self).__init__()
|
57 |
+
self.output = config.dropout
|
58 |
+
self.input_dim = config.vocab_dim
|
59 |
+
self.hidden_dim = config.fc_hidden_dim
|
60 |
+
self.out_dim = config.num_classes
|
61 |
+
self.dropout = nn.Dropout(config.dropout)
|
62 |
+
self.model = nn.Sequential(nn.Linear(self.input_dim, self.hidden_dim),
|
63 |
+
nn.Tanh(),
|
64 |
+
nn.Linear(self.hidden_dim, self.out_dim))
|
65 |
+
|
66 |
+
def forward(self, att_input, pooled_emb):
|
67 |
+
att_input = self.dropout(att_input)
|
68 |
+
pooled_emb = self.dropout(pooled_emb)
|
69 |
+
return self.model(pooled_emb)
|
ToxiCN_ex/src/datasets.py
ADDED
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
import json, time, random, torch
|
3 |
+
from torch.utils.data import Dataset, DataLoader
|
4 |
+
from transformers import BertTokenizer, AutoTokenizer
|
5 |
+
# from chinesebert import ChineseBertForMaskedLM, ChineseBertTokenizerFast, ChineseBertConfig
|
6 |
+
from tqdm import tqdm
|
7 |
+
|
8 |
+
import jieba
|
9 |
+
# from nltk.corpus import stopwords
|
10 |
+
# from src.helper import *
|
11 |
+
from importlib import import_module
|
12 |
+
import pickle as pkl
|
13 |
+
import time
|
14 |
+
from datetime import timedelta
|
15 |
+
|
16 |
+
|
17 |
+
MAX_VOCAB_SIZE = 10000
|
18 |
+
UNK, PAD = '<UNK>', '<PAD>'
|
19 |
+
|
20 |
+
def token_to_index(token, config):
|
21 |
+
vocab = pkl.load(open(config.vocab_path, 'rb'))
|
22 |
+
# print(f"Vocab size: {len(vocab)}")
|
23 |
+
|
24 |
+
words_line = []
|
25 |
+
if len(token) < config.pad_size:
|
26 |
+
token.extend([PAD] * (config.pad_size - len(token)))
|
27 |
+
else:
|
28 |
+
token = token[:config.pad_size]
|
29 |
+
|
30 |
+
# word to id
|
31 |
+
for word in token:
|
32 |
+
words_line.append(vocab.get(word, vocab.get(UNK)))
|
33 |
+
return words_line
|
34 |
+
|
35 |
+
# 获取dirty_word的索引
|
36 |
+
def get_dirty_words(path):
|
37 |
+
with open(path, 'r') as f:
|
38 |
+
data = json.load(f)
|
39 |
+
dirty_words = list(data.values())
|
40 |
+
return dirty_words
|
41 |
+
|
42 |
+
def get_all_dirty_words(base_path):
|
43 |
+
all_dirty_words = []
|
44 |
+
paths = ["general.json", "LGBT.json", "region.json", "sexism.json", "racism.json"]
|
45 |
+
for i in paths:
|
46 |
+
all_dirty_words.append(get_dirty_words(base_path + i))
|
47 |
+
return all_dirty_words
|
48 |
+
|
49 |
+
def get_toxic_id(text_idx, toxic_ids, dirty_words, toxic_index):
|
50 |
+
for dirty_word in dirty_words:
|
51 |
+
for index, token in enumerate(text_idx):
|
52 |
+
if token == 0:
|
53 |
+
break
|
54 |
+
if token != dirty_word[0]: # 第一个字符不是dirty_word的词首
|
55 |
+
continue
|
56 |
+
else:
|
57 |
+
flag = 1
|
58 |
+
start_index = index
|
59 |
+
end_index = index+1
|
60 |
+
for i in range(len(dirty_word[1:])):
|
61 |
+
if end_index >= len(text_idx): # 越界
|
62 |
+
flag = 0
|
63 |
+
break
|
64 |
+
if text_idx[end_index] != dirty_word[1+i]: # 后续单词非dirty词
|
65 |
+
flag = 0
|
66 |
+
break
|
67 |
+
end_index += 1
|
68 |
+
if flag:
|
69 |
+
for dirty_index in range(start_index, end_index): # 对含脏词的span打上类别label
|
70 |
+
toxic_ids[dirty_index] = toxic_index
|
71 |
+
# print(toxic_ids)
|
72 |
+
return toxic_ids
|
73 |
+
|
74 |
+
def get_all_toxic_id(pad_size, text_idx, all_dirty_words):
|
75 |
+
toxic_ids = [0 for i in range(pad_size)]
|
76 |
+
for toxic_index, dirty_words in enumerate(all_dirty_words):
|
77 |
+
toxic_ids = get_toxic_id(text_idx, toxic_ids, dirty_words, toxic_index+1)
|
78 |
+
return toxic_ids
|
79 |
+
|
80 |
+
class Datasets(Dataset):
|
81 |
+
'''
|
82 |
+
The dataset based on Bert.
|
83 |
+
'''
|
84 |
+
def __init__(self, kwargs, data_name, add_special_tokens=True, not_test=True):
|
85 |
+
self.kwargs = kwargs
|
86 |
+
self.not_test = not_test
|
87 |
+
self.data_name = data_name
|
88 |
+
self.lexicon_base_path = kwargs.lexicon_path
|
89 |
+
self.max_tok_len = kwargs.pad_size
|
90 |
+
self.add_special_tokens = add_special_tokens
|
91 |
+
# self.tokenizer = BertTokenizer.from_pretrained('resources/scibert_scivocab_cased')
|
92 |
+
# self.tokenizer = BertTokenizer.from_pretrained(kwargs.model_name)
|
93 |
+
# BERT/Roberta
|
94 |
+
self.tokenizer = AutoTokenizer.from_pretrained(kwargs.model_name)
|
95 |
+
# ChineseBERT
|
96 |
+
# self.tokenizer = ChineseBertTokenizerFast.from_pretrained(kwargs.model_name)
|
97 |
+
# self.word2vec_path = kwargs.word2vec_path
|
98 |
+
with open(data_name, 'r') as f:
|
99 |
+
self.data_file = json.load(f)
|
100 |
+
self.preprocess_data()
|
101 |
+
|
102 |
+
def preprocess_data(self):
|
103 |
+
print('Preprocessing Data {} ...'.format(self.data_name))
|
104 |
+
# word2idx, embedding_matrix = load_word2vec_matrix(self.word2vec_path)
|
105 |
+
data_time_start=time.time()
|
106 |
+
all_dirty_words = get_all_dirty_words(self.lexicon_base_path)
|
107 |
+
|
108 |
+
for row in tqdm(self.data_file):
|
109 |
+
ori_text = row['content']
|
110 |
+
text = self.tokenizer(ori_text, add_special_tokens=self.add_special_tokens,
|
111 |
+
max_length=int(self.max_tok_len), padding='max_length', truncation=True)
|
112 |
+
# For BERT
|
113 |
+
row['text_idx'] = text['input_ids']
|
114 |
+
row['text_ids'] = text['token_type_ids']
|
115 |
+
row['text_mask'] = text['attention_mask']
|
116 |
+
row['toxic_ids'] = get_all_toxic_id(self.max_tok_len, row['text_idx'], all_dirty_words)
|
117 |
+
|
118 |
+
# for glove
|
119 |
+
# sub_text = re.sub(u"([^\u0030-\u0039\u0041-\u005a\u0061-\u007a])"," ",ori_text)
|
120 |
+
# text_token = [w for w in ori_text]
|
121 |
+
# row["text_token_ids"] = token_to_index(text_token, self.kwargs)
|
122 |
+
# row["text_token_len"] = len(row["text_token_ids"])
|
123 |
+
# row["text_token_ids"] = pad_token_seq(row["text_token_ids"], self.max_tok_len)
|
124 |
+
|
125 |
+
data_time_end = time.time()
|
126 |
+
print("... finished preprocessing cost {} ".format(data_time_end-data_time_start))
|
127 |
+
|
128 |
+
# def get_key(self, index):
|
129 |
+
# path = "data/label/level_" + str(index) + '.json'
|
130 |
+
# with open(path, 'r+') as file:
|
131 |
+
# content=file.read()
|
132 |
+
# key = json.loads(content)
|
133 |
+
# return key
|
134 |
+
|
135 |
+
# def convert_one_hot(self, data, one_hot, length):
|
136 |
+
# data_ = [0 for i in range(length)]
|
137 |
+
# for i in data:
|
138 |
+
# data_[one_hot[i]] = 1
|
139 |
+
# return data_
|
140 |
+
|
141 |
+
def __len__(self):
|
142 |
+
return len(self.data_file)
|
143 |
+
|
144 |
+
def __getitem__(self, idx, corpus=None):
|
145 |
+
row = self.data_file[idx]
|
146 |
+
sample = {
|
147 |
+
# For BERT
|
148 |
+
'text_idx': row['text_idx'], 'text_ids': row['text_ids'], 'text_mask': row['text_mask'], 'toxic_ids': row['toxic_ids'],
|
149 |
+
# For GloVe
|
150 |
+
# 'text_token_ids': row["text_token_ids"]
|
151 |
+
'toxic': row["toxic_one_hot"], 'toxic_type': row["toxic_type_one_hot"], 'expression': row["expression_one_hot"], 'target': row["target"]
|
152 |
+
}
|
153 |
+
# For label
|
154 |
+
# sample['label'] = row['label']
|
155 |
+
return sample
|
156 |
+
|
157 |
+
|
158 |
+
class Dataloader(DataLoader):
|
159 |
+
'''
|
160 |
+
A batch sampler of a dataset.
|
161 |
+
'''
|
162 |
+
def __init__(self, data, batch_size, shuffle=True, SEED=0):
|
163 |
+
self.data = data
|
164 |
+
self.batch_size = batch_size
|
165 |
+
self.shuffle = shuffle
|
166 |
+
self.SEED = SEED
|
167 |
+
random.seed(self.SEED)
|
168 |
+
|
169 |
+
self.indices = list(range(len(data)))
|
170 |
+
if shuffle:
|
171 |
+
random.shuffle(self.indices)
|
172 |
+
self.batch_num = 0
|
173 |
+
|
174 |
+
def __len__(self):
|
175 |
+
return int(len(self.data) / float(self.batch_size))
|
176 |
+
|
177 |
+
def num_batches(self):
|
178 |
+
return len(self.data) / float(self.batch_size)
|
179 |
+
|
180 |
+
def __iter__(self):
|
181 |
+
self.indices = list(range(len(self.data)))
|
182 |
+
if self.shuffle:
|
183 |
+
random.shuffle(self.indices)
|
184 |
+
return self
|
185 |
+
|
186 |
+
def __next__(self):
|
187 |
+
if self.indices != []:
|
188 |
+
idxs = self.indices[:self.batch_size]
|
189 |
+
batch = [self.data.__getitem__(i) for i in idxs]
|
190 |
+
self.indices = self.indices[self.batch_size:]
|
191 |
+
return batch
|
192 |
+
else:
|
193 |
+
raise StopIteration
|
194 |
+
|
195 |
+
def get(self):
|
196 |
+
self.reset()
|
197 |
+
return self.__next__()
|
198 |
+
|
199 |
+
def reset(self):
|
200 |
+
self.indices = list(range(len(self.data)))
|
201 |
+
if self.shuffle: random.shuffle(self.indices)
|
202 |
+
|
203 |
+
def to_tensor(batch):
|
204 |
+
'''
|
205 |
+
Convert a batch data into tensor
|
206 |
+
'''
|
207 |
+
args = {}
|
208 |
+
# For label
|
209 |
+
# args["label"] = torch.tensor([b['label'] for b in batch])
|
210 |
+
|
211 |
+
# For BERT
|
212 |
+
args['text_idx'] = torch.tensor([b['text_idx'] for b in batch])
|
213 |
+
args['text_ids'] = torch.tensor([b['text_ids'] for b in batch])
|
214 |
+
args['text_mask'] = torch.tensor([b['text_mask'] for b in batch])
|
215 |
+
args['toxic_ids'] = torch.tensor([b['toxic_ids'] for b in batch])
|
216 |
+
|
217 |
+
# For GloVe
|
218 |
+
# args['text_token_len'] = torch.tensor([b['text_token_len'] for b in batch])
|
219 |
+
# args['text_token_ids'] = torch.tensor([b['text_token_ids'] for b in batch])
|
220 |
+
args['toxic'] = torch.tensor([b['toxic'] for b in batch])
|
221 |
+
args['toxic_type'] = torch.tensor([b['toxic_type'] for b in batch])
|
222 |
+
args['expression'] = torch.tensor([b['expression'] for b in batch])
|
223 |
+
args['target'] = torch.tensor([b['target'] for b in batch])
|
224 |
+
|
225 |
+
return args
|
226 |
+
|
227 |
+
def get_time_dif(start_time):
|
228 |
+
"""获取已使用时间"""
|
229 |
+
end_time = time.time()
|
230 |
+
time_dif = end_time - start_time
|
231 |
+
return timedelta(seconds=int(round(time_dif)))
|
232 |
+
|
233 |
+
def convert_onehot(config, label):
|
234 |
+
onehot_label = [0 for i in range(config.num_classes)]
|
235 |
+
onehot_label[int(label)] = 1
|
236 |
+
return onehot_label
|
237 |
+
|
238 |
+
|
ToxiCN_ex/train_eval.py
ADDED
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from sklearn import metrics
|
3 |
+
from sklearn.metrics import f1_score, precision_score, recall_score, accuracy_score
|
4 |
+
|
5 |
+
import torch
|
6 |
+
import torch.nn as nn
|
7 |
+
import torch.nn.functional as F
|
8 |
+
import torch.optim as optim
|
9 |
+
from tqdm import tqdm
|
10 |
+
|
11 |
+
import time
|
12 |
+
import json
|
13 |
+
import copy
|
14 |
+
from src.datasets import get_time_dif, to_tensor, convert_onehot
|
15 |
+
from src.Models import *
|
16 |
+
# from src.losses import *
|
17 |
+
|
18 |
+
# from tensorboardX import SummaryWriter
|
19 |
+
from ray import tune
|
20 |
+
|
21 |
+
|
22 |
+
def train(config, train_iter, dev_iter, test_iter, task=1):
|
23 |
+
embed_model = Bert_Layer(config).to(config.device)
|
24 |
+
model = TwoLayerFFNNLayer(config).to(config.device)
|
25 |
+
model_name = '{}-NN_ML-{}_D-{}_B-{}_E-{}_Lr-{}_aplha-{}'.format(config.model_name, config.pad_size, config.dropout,
|
26 |
+
config.batch_size, config.num_epochs, config.learning_rate, config.alpha1)
|
27 |
+
embed_optimizer = optim.AdamW(embed_model.parameters(), lr=config.learning_rate)
|
28 |
+
model_optimizer = optim.AdamW(model.parameters(), lr=config.learning_rate)
|
29 |
+
# fgm = FGM(embed_model, epsilon=1, emb_name='word_embeddings.')
|
30 |
+
loss_fn = nn.BCEWithLogitsLoss()
|
31 |
+
# loss_fn = get_loss_func("FL", [0.4, 0.6], config.num_classes, config.alpha1)
|
32 |
+
max_score = 0
|
33 |
+
|
34 |
+
for epoch in range(config.num_epochs):
|
35 |
+
embed_model.train()
|
36 |
+
model.train()
|
37 |
+
start_time = time.time()
|
38 |
+
print("Model is training in epoch {}".format(epoch))
|
39 |
+
loss_all = 0.
|
40 |
+
preds = []
|
41 |
+
labels = []
|
42 |
+
|
43 |
+
for batch in tqdm(train_iter, desc='Training', colour = 'MAGENTA'):
|
44 |
+
embed_model.zero_grad()
|
45 |
+
model.zero_grad()
|
46 |
+
args = to_tensor(batch)
|
47 |
+
att_input, pooled_emb = embed_model(**args)
|
48 |
+
|
49 |
+
logit = model(att_input, pooled_emb).cpu()
|
50 |
+
|
51 |
+
label = args['toxic']
|
52 |
+
# label = args['toxic_type']
|
53 |
+
# label = args['expression']
|
54 |
+
# label = args['target']
|
55 |
+
loss = loss_fn(logit, label.float())
|
56 |
+
pred = get_preds(config, logit)
|
57 |
+
# pred = get_preds_task2_4(config, logit)
|
58 |
+
# pred = get_preds_task3(config, logit)
|
59 |
+
preds.extend(pred)
|
60 |
+
labels.extend(label.detach().numpy())
|
61 |
+
|
62 |
+
loss_all += loss.item()
|
63 |
+
embed_optimizer.zero_grad()
|
64 |
+
model_optimizer.zero_grad()
|
65 |
+
loss.backward()
|
66 |
+
|
67 |
+
embed_optimizer.step()
|
68 |
+
model_optimizer.step()
|
69 |
+
|
70 |
+
end_time = time.time()
|
71 |
+
print(" took: {:.1f} min".format((end_time - start_time)/60.))
|
72 |
+
print("TRAINED for {} epochs".format(epoch))
|
73 |
+
|
74 |
+
# 验证
|
75 |
+
if epoch >= config.num_warm:
|
76 |
+
# print("training loss: loss={}".format(loss_all/len(data)))
|
77 |
+
trn_scores = get_scores(preds, labels, loss_all, len(train_iter), data_name="TRAIN")
|
78 |
+
dev_scores, _ = eval(config, embed_model, model, loss_fn, dev_iter, data_name='DEV')
|
79 |
+
f = open('{}/{}.all_scores.txt'.format(config.result_path, model_name), 'a')
|
80 |
+
f.write(' ================================================== Epoch: {} ==================================================\n'.format(epoch))
|
81 |
+
f.write('TrainScore: \n{}\nEvalScore: \n{}\n'.format(json.dumps(trn_scores), json.dumps(dev_scores)))
|
82 |
+
max_score = save_best(config, epoch, model_name, embed_model, model, dev_scores, max_score)
|
83 |
+
print("ALLTRAINED for {} epochs".format(epoch))
|
84 |
+
|
85 |
+
path = '{}/ckp-{}-{}.tar'.format(config.checkpoint_path, model_name, 'BEST')
|
86 |
+
checkpoint = torch.load(path)
|
87 |
+
embed_model.load_state_dict(checkpoint['embed_model_state_dict'])
|
88 |
+
model.load_state_dict(checkpoint['model_state_dict'])
|
89 |
+
test_scores, _ = eval(config, embed_model, model, loss_fn, test_iter, data_name='DEV')
|
90 |
+
f = open('{}/{}.all_scores.txt'.format(config.result_path, model_name), 'a')
|
91 |
+
f.write('Test: \n{}\n'.format(json.dumps(test_scores)))
|
92 |
+
|
93 |
+
|
94 |
+
def eval(config, embed_model, model, loss_fn, dev_iter, data_name='DEV'):
|
95 |
+
loss_all = 0.
|
96 |
+
preds = []
|
97 |
+
labels = []
|
98 |
+
for batch in tqdm(dev_iter, desc='Evaling', colour = 'CYAN'):
|
99 |
+
with torch.no_grad():
|
100 |
+
args = to_tensor(batch)
|
101 |
+
att_input, pooled_emb = embed_model(**args)
|
102 |
+
logit = model(att_input, pooled_emb)
|
103 |
+
|
104 |
+
logit = logit.cpu()
|
105 |
+
label = args['toxic']
|
106 |
+
# label = args['toxic_type']
|
107 |
+
# label = args['expression']
|
108 |
+
# label = args['target']
|
109 |
+
loss = loss_fn(logit, label.float())
|
110 |
+
pred = get_preds(config, logit)
|
111 |
+
# pred = get_preds_task2_4(config, logit)
|
112 |
+
# pred = get_preds_task3(config, logit)
|
113 |
+
preds.extend(pred)
|
114 |
+
labels.extend(label.detach().numpy())
|
115 |
+
loss_all += loss.item()
|
116 |
+
|
117 |
+
dev_scores = get_scores(preds, labels, loss_all, len(dev_iter), data_name=data_name)
|
118 |
+
# if data_name != "TEST": # 2022.9.20 命令行输入为test模式时,不调用tune
|
119 |
+
# tune.report(metric=dev_scores)
|
120 |
+
|
121 |
+
return dev_scores, preds
|
122 |
+
|
123 |
+
|
124 |
+
# For Multi Classfication
|
125 |
+
def get_preds(config, logit):
|
126 |
+
results = torch.max(logit.data, 1)[1].cpu().numpy()
|
127 |
+
new_results = []
|
128 |
+
for result in results:
|
129 |
+
result = convert_onehot(config, result)
|
130 |
+
new_results.append(result)
|
131 |
+
return new_results
|
132 |
+
|
133 |
+
# Task 2 and 4: 多分类 Toxic Type Discrimination and d Expression Type Detection
|
134 |
+
def get_preds_task2_4(config, logit):
|
135 |
+
all_results = []
|
136 |
+
logit_ = torch.sigmoid(logit)
|
137 |
+
results_pred = torch.max(logit_.data, 1)[0].cpu().numpy()
|
138 |
+
results = torch.max(logit_.data, 1)[1].cpu().numpy() # index for maximum probability
|
139 |
+
for i in range(len(results)):
|
140 |
+
if results_pred[i] < 0.5:
|
141 |
+
result = [0 for i in range(config.num_classes)]
|
142 |
+
else:
|
143 |
+
result = convert_onehot(config, results[i])
|
144 |
+
all_results.append(result)
|
145 |
+
return all_results
|
146 |
+
|
147 |
+
# Task 3: 多标签分类 Targeted Group Detection
|
148 |
+
def get_preds_task3(config, logit):
|
149 |
+
all_results = []
|
150 |
+
logit_ = torch.sigmoid(logit)
|
151 |
+
results_pred = torch.max(logit_.data, 1)[0].cpu().numpy()
|
152 |
+
results = torch.max(logit_.data, 1)[1].cpu().numpy()
|
153 |
+
logit_ = logit_.detach().cpu().numpy()
|
154 |
+
for i in range(len(results)):
|
155 |
+
if results_pred[i] < 0.5:
|
156 |
+
result = [0 for i in range(config.num_classes)]
|
157 |
+
else:
|
158 |
+
result = get_pred_task3(logit_[i])
|
159 |
+
all_results.append(result)
|
160 |
+
return all_results
|
161 |
+
|
162 |
+
def get_pred_task3(logit):
|
163 |
+
result = [0 for i in range(len(logit))]
|
164 |
+
for i in range(len(logit)):
|
165 |
+
if logit[i] >= 0.5:
|
166 |
+
result[i] = 1
|
167 |
+
return result
|
168 |
+
|
169 |
+
def get_scores(all_preds, all_lebels, loss_all, len, data_name):
|
170 |
+
score_dict = dict()
|
171 |
+
f1 = f1_score(all_preds, all_lebels, average='weighted')
|
172 |
+
# acc = accuracy_score(all_preds, all_lebels)
|
173 |
+
all_f1 = f1_score(all_preds, all_lebels, average=None)
|
174 |
+
pre = precision_score(all_preds, all_lebels, average='weighted')
|
175 |
+
recall = recall_score(all_preds, all_lebels, average='weighted')
|
176 |
+
|
177 |
+
score_dict['F1'] = f1
|
178 |
+
# score_dict['accuracy'] = acc
|
179 |
+
score_dict['all_f1'] = all_f1.tolist()
|
180 |
+
score_dict['precision'] = pre
|
181 |
+
score_dict['recall'] = recall
|
182 |
+
|
183 |
+
score_dict['all_loss'] = loss_all/len
|
184 |
+
print("Evaling on \"{}\" data".format(data_name))
|
185 |
+
for s_name, s_val in score_dict.items():
|
186 |
+
print("{}: {}".format(s_name, s_val))
|
187 |
+
return score_dict
|
188 |
+
|
189 |
+
def save_best(config, epoch, model_name, embed_model, model, score, max_score):
|
190 |
+
score_key = config.score_key
|
191 |
+
curr_score = score[score_key]
|
192 |
+
print('The epoch_{} {}: {}\nCurrent max {}: {}'.format(epoch, score_key, curr_score, score_key, max_score))
|
193 |
+
|
194 |
+
if curr_score > max_score or epoch == 0:
|
195 |
+
torch.save({
|
196 |
+
'epoch': config.num_epochs,
|
197 |
+
'embed_model_state_dict': embed_model.state_dict(),
|
198 |
+
'model_state_dict': model.state_dict(),
|
199 |
+
}, '{}/ckp-{}-{}.tar'.format(config.checkpoint_path, model_name, 'BEST'))
|
200 |
+
return curr_score
|
201 |
+
else:
|
202 |
+
return max_score
|
modeling_bert.py
ADDED
@@ -0,0 +1,1635 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
4 |
+
#
|
5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
6 |
+
# you may not use this file except in compliance with the License.
|
7 |
+
# You may obtain a copy of the License at
|
8 |
+
#
|
9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
10 |
+
#
|
11 |
+
# Unless required by applicable law or agreed to in writing, software
|
12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
14 |
+
# See the License for the specific language governing permissions and
|
15 |
+
# limitations under the License.
|
16 |
+
"""PyTorch BERT model. """
|
17 |
+
|
18 |
+
|
19 |
+
import math
|
20 |
+
import os
|
21 |
+
import warnings
|
22 |
+
from dataclasses import dataclass
|
23 |
+
from typing import Optional, Tuple
|
24 |
+
|
25 |
+
import torch
|
26 |
+
import torch.utils.checkpoint
|
27 |
+
from torch import nn
|
28 |
+
from torch.nn import CrossEntropyLoss, MSELoss
|
29 |
+
|
30 |
+
from .activations import gelu, gelu_new, swish
|
31 |
+
from .configuration_bert import BertConfig
|
32 |
+
from .file_utils import (
|
33 |
+
ModelOutput,
|
34 |
+
add_code_sample_docstrings,
|
35 |
+
add_start_docstrings,
|
36 |
+
add_start_docstrings_to_callable,
|
37 |
+
replace_return_docstrings,
|
38 |
+
)
|
39 |
+
from .modeling_outputs import (
|
40 |
+
BaseModelOutput,
|
41 |
+
BaseModelOutputWithPooling,
|
42 |
+
CausalLMOutput,
|
43 |
+
MaskedLMOutput,
|
44 |
+
MultipleChoiceModelOutput,
|
45 |
+
NextSentencePredictorOutput,
|
46 |
+
QuestionAnsweringModelOutput,
|
47 |
+
SequenceClassifierOutput,
|
48 |
+
TokenClassifierOutput,
|
49 |
+
)
|
50 |
+
from .modeling_utils import (
|
51 |
+
PreTrainedModel,
|
52 |
+
apply_chunking_to_forward,
|
53 |
+
find_pruneable_heads_and_indices,
|
54 |
+
prune_linear_layer,
|
55 |
+
)
|
56 |
+
from .utils import logging
|
57 |
+
|
58 |
+
|
59 |
+
logger = logging.get_logger(__name__)
|
60 |
+
|
61 |
+
_CONFIG_FOR_DOC = "BertConfig"
|
62 |
+
_TOKENIZER_FOR_DOC = "BertTokenizer"
|
63 |
+
|
64 |
+
BERT_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
65 |
+
"bert-base-uncased",
|
66 |
+
"bert-large-uncased",
|
67 |
+
"bert-base-cased",
|
68 |
+
"bert-large-cased",
|
69 |
+
"bert-base-multilingual-uncased",
|
70 |
+
"bert-base-multilingual-cased",
|
71 |
+
"bert-base-chinese",
|
72 |
+
"bert-base-german-cased",
|
73 |
+
"bert-large-uncased-whole-word-masking",
|
74 |
+
"bert-large-cased-whole-word-masking",
|
75 |
+
"bert-large-uncased-whole-word-masking-finetuned-squad",
|
76 |
+
"bert-large-cased-whole-word-masking-finetuned-squad",
|
77 |
+
"bert-base-cased-finetuned-mrpc",
|
78 |
+
"bert-base-german-dbmdz-cased",
|
79 |
+
"bert-base-german-dbmdz-uncased",
|
80 |
+
"cl-tohoku/bert-base-japanese",
|
81 |
+
"cl-tohoku/bert-base-japanese-whole-word-masking",
|
82 |
+
"cl-tohoku/bert-base-japanese-char",
|
83 |
+
"cl-tohoku/bert-base-japanese-char-whole-word-masking",
|
84 |
+
"TurkuNLP/bert-base-finnish-cased-v1",
|
85 |
+
"TurkuNLP/bert-base-finnish-uncased-v1",
|
86 |
+
"wietsedv/bert-base-dutch-cased",
|
87 |
+
# See all BERT models at https://huggingface.co/models?filter=bert
|
88 |
+
]
|
89 |
+
|
90 |
+
|
91 |
+
def load_tf_weights_in_bert(model, config, tf_checkpoint_path):
|
92 |
+
"""Load tf checkpoints in a pytorch model."""
|
93 |
+
try:
|
94 |
+
import re
|
95 |
+
|
96 |
+
import numpy as np
|
97 |
+
import tensorflow as tf
|
98 |
+
except ImportError:
|
99 |
+
logger.error(
|
100 |
+
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
|
101 |
+
"https://www.tensorflow.org/install/ for installation instructions."
|
102 |
+
)
|
103 |
+
raise
|
104 |
+
tf_path = os.path.abspath(tf_checkpoint_path)
|
105 |
+
logger.info("Converting TensorFlow checkpoint from {}".format(tf_path))
|
106 |
+
# Load weights from TF model
|
107 |
+
init_vars = tf.train.list_variables(tf_path)
|
108 |
+
names = []
|
109 |
+
arrays = []
|
110 |
+
for name, shape in init_vars:
|
111 |
+
logger.info("Loading TF weight {} with shape {}".format(name, shape))
|
112 |
+
array = tf.train.load_variable(tf_path, name)
|
113 |
+
names.append(name)
|
114 |
+
arrays.append(array)
|
115 |
+
|
116 |
+
for name, array in zip(names, arrays):
|
117 |
+
name = name.split("/")
|
118 |
+
# adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
|
119 |
+
# which are not required for using pretrained model
|
120 |
+
if any(
|
121 |
+
n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
|
122 |
+
for n in name
|
123 |
+
):
|
124 |
+
logger.info("Skipping {}".format("/".join(name)))
|
125 |
+
continue
|
126 |
+
pointer = model
|
127 |
+
for m_name in name:
|
128 |
+
if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
|
129 |
+
scope_names = re.split(r"_(\d+)", m_name)
|
130 |
+
else:
|
131 |
+
scope_names = [m_name]
|
132 |
+
if scope_names[0] == "kernel" or scope_names[0] == "gamma":
|
133 |
+
pointer = getattr(pointer, "weight")
|
134 |
+
elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
|
135 |
+
pointer = getattr(pointer, "bias")
|
136 |
+
elif scope_names[0] == "output_weights":
|
137 |
+
pointer = getattr(pointer, "weight")
|
138 |
+
elif scope_names[0] == "squad":
|
139 |
+
pointer = getattr(pointer, "classifier")
|
140 |
+
else:
|
141 |
+
try:
|
142 |
+
pointer = getattr(pointer, scope_names[0])
|
143 |
+
except AttributeError:
|
144 |
+
logger.info("Skipping {}".format("/".join(name)))
|
145 |
+
continue
|
146 |
+
if len(scope_names) >= 2:
|
147 |
+
num = int(scope_names[1])
|
148 |
+
pointer = pointer[num]
|
149 |
+
if m_name[-11:] == "_embeddings":
|
150 |
+
pointer = getattr(pointer, "weight")
|
151 |
+
elif m_name == "kernel":
|
152 |
+
array = np.transpose(array)
|
153 |
+
try:
|
154 |
+
assert (
|
155 |
+
pointer.shape == array.shape
|
156 |
+
), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
|
157 |
+
except AssertionError as e:
|
158 |
+
e.args += (pointer.shape, array.shape)
|
159 |
+
raise
|
160 |
+
logger.info("Initialize PyTorch weight {}".format(name))
|
161 |
+
pointer.data = torch.from_numpy(array)
|
162 |
+
return model
|
163 |
+
|
164 |
+
|
165 |
+
def mish(x):
|
166 |
+
return x * torch.tanh(nn.functional.softplus(x))
|
167 |
+
|
168 |
+
|
169 |
+
ACT2FN = {"gelu": gelu, "relu": torch.nn.functional.relu, "swish": swish, "gelu_new": gelu_new, "mish": mish}
|
170 |
+
|
171 |
+
|
172 |
+
BertLayerNorm = torch.nn.LayerNorm
|
173 |
+
|
174 |
+
|
175 |
+
class BertEmbeddings(nn.Module):
|
176 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
177 |
+
|
178 |
+
def __init__(self, config):
|
179 |
+
super().__init__()
|
180 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
181 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
182 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
183 |
+
|
184 |
+
# 2022.10.8 toxic_embeddings: non-toxic + 5 kinds of toxic
|
185 |
+
self.toxic_embeddings = nn.Embedding(6, config.hidden_size)
|
186 |
+
|
187 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
188 |
+
# any TensorFlow checkpoint file
|
189 |
+
self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
190 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
191 |
+
|
192 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
193 |
+
self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
|
194 |
+
|
195 |
+
def forward(self, input_ids=None, token_type_ids=None, position_ids=None, toxic_ids=None, inputs_embeds=None):
|
196 |
+
if input_ids is not None:
|
197 |
+
input_shape = input_ids.size()
|
198 |
+
else:
|
199 |
+
input_shape = inputs_embeds.size()[:-1]
|
200 |
+
|
201 |
+
seq_length = input_shape[1]
|
202 |
+
|
203 |
+
if position_ids is None:
|
204 |
+
position_ids = self.position_ids[:, :seq_length]
|
205 |
+
|
206 |
+
if token_type_ids is None:
|
207 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
208 |
+
|
209 |
+
if inputs_embeds is None:
|
210 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
211 |
+
position_embeddings = self.position_embeddings(position_ids)
|
212 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
213 |
+
|
214 |
+
embeddings = inputs_embeds + position_embeddings + token_type_embeddings
|
215 |
+
|
216 |
+
# 2022.10.8 toxic_embeddings
|
217 |
+
if toxic_ids is not None:
|
218 |
+
toxic_embeddings = self.toxic_embeddings(toxic_ids)
|
219 |
+
embeddings += toxic_embeddings
|
220 |
+
|
221 |
+
embeddings = self.LayerNorm(embeddings)
|
222 |
+
embeddings = self.dropout(embeddings)
|
223 |
+
return embeddings
|
224 |
+
|
225 |
+
|
226 |
+
class BertSelfAttention(nn.Module):
|
227 |
+
def __init__(self, config):
|
228 |
+
super().__init__()
|
229 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
230 |
+
raise ValueError(
|
231 |
+
"The hidden size (%d) is not a multiple of the number of attention "
|
232 |
+
"heads (%d)" % (config.hidden_size, config.num_attention_heads)
|
233 |
+
)
|
234 |
+
|
235 |
+
self.num_attention_heads = config.num_attention_heads
|
236 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
237 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
238 |
+
|
239 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
240 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
241 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
242 |
+
|
243 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
244 |
+
|
245 |
+
def transpose_for_scores(self, x):
|
246 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
247 |
+
x = x.view(*new_x_shape)
|
248 |
+
return x.permute(0, 2, 1, 3)
|
249 |
+
|
250 |
+
def forward(
|
251 |
+
self,
|
252 |
+
hidden_states,
|
253 |
+
attention_mask=None,
|
254 |
+
head_mask=None,
|
255 |
+
encoder_hidden_states=None,
|
256 |
+
encoder_attention_mask=None,
|
257 |
+
output_attentions=False,
|
258 |
+
):
|
259 |
+
mixed_query_layer = self.query(hidden_states)
|
260 |
+
|
261 |
+
# If this is instantiated as a cross-attention module, the keys
|
262 |
+
# and values come from an encoder; the attention mask needs to be
|
263 |
+
# such that the encoder's padding tokens are not attended to.
|
264 |
+
if encoder_hidden_states is not None:
|
265 |
+
mixed_key_layer = self.key(encoder_hidden_states)
|
266 |
+
mixed_value_layer = self.value(encoder_hidden_states)
|
267 |
+
attention_mask = encoder_attention_mask
|
268 |
+
else:
|
269 |
+
mixed_key_layer = self.key(hidden_states)
|
270 |
+
mixed_value_layer = self.value(hidden_states)
|
271 |
+
|
272 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
273 |
+
key_layer = self.transpose_for_scores(mixed_key_layer)
|
274 |
+
value_layer = self.transpose_for_scores(mixed_value_layer)
|
275 |
+
|
276 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
277 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
278 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
279 |
+
if attention_mask is not None:
|
280 |
+
# Apply the attention mask is (precomputed for all layers in BertModel forward() function)
|
281 |
+
attention_scores = attention_scores + attention_mask
|
282 |
+
|
283 |
+
# Normalize the attention scores to probabilities.
|
284 |
+
attention_probs = nn.Softmax(dim=-1)(attention_scores)
|
285 |
+
|
286 |
+
# This is actually dropping out entire tokens to attend to, which might
|
287 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
288 |
+
attention_probs = self.dropout(attention_probs)
|
289 |
+
|
290 |
+
# Mask heads if we want to
|
291 |
+
if head_mask is not None:
|
292 |
+
attention_probs = attention_probs * head_mask
|
293 |
+
|
294 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
295 |
+
|
296 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
297 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
298 |
+
context_layer = context_layer.view(*new_context_layer_shape)
|
299 |
+
|
300 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
301 |
+
return outputs
|
302 |
+
|
303 |
+
|
304 |
+
class BertSelfOutput(nn.Module):
|
305 |
+
def __init__(self, config):
|
306 |
+
super().__init__()
|
307 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
308 |
+
self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
309 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
310 |
+
|
311 |
+
def forward(self, hidden_states, input_tensor):
|
312 |
+
hidden_states = self.dense(hidden_states)
|
313 |
+
hidden_states = self.dropout(hidden_states)
|
314 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
315 |
+
return hidden_states
|
316 |
+
|
317 |
+
|
318 |
+
class BertAttention(nn.Module):
|
319 |
+
def __init__(self, config):
|
320 |
+
super().__init__()
|
321 |
+
self.self = BertSelfAttention(config)
|
322 |
+
self.output = BertSelfOutput(config)
|
323 |
+
self.pruned_heads = set()
|
324 |
+
|
325 |
+
def prune_heads(self, heads):
|
326 |
+
if len(heads) == 0:
|
327 |
+
return
|
328 |
+
heads, index = find_pruneable_heads_and_indices(
|
329 |
+
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
|
330 |
+
)
|
331 |
+
|
332 |
+
# Prune linear layers
|
333 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
334 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
335 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
336 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
337 |
+
|
338 |
+
# Update hyper params and store pruned heads
|
339 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
340 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
341 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
342 |
+
|
343 |
+
def forward(
|
344 |
+
self,
|
345 |
+
hidden_states,
|
346 |
+
attention_mask=None,
|
347 |
+
head_mask=None,
|
348 |
+
encoder_hidden_states=None,
|
349 |
+
encoder_attention_mask=None,
|
350 |
+
output_attentions=False,
|
351 |
+
):
|
352 |
+
self_outputs = self.self(
|
353 |
+
hidden_states,
|
354 |
+
attention_mask,
|
355 |
+
head_mask,
|
356 |
+
encoder_hidden_states,
|
357 |
+
encoder_attention_mask,
|
358 |
+
output_attentions,
|
359 |
+
)
|
360 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
361 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
362 |
+
return outputs
|
363 |
+
|
364 |
+
|
365 |
+
class BertIntermediate(nn.Module):
|
366 |
+
def __init__(self, config):
|
367 |
+
super().__init__()
|
368 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
369 |
+
if isinstance(config.hidden_act, str):
|
370 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
371 |
+
else:
|
372 |
+
self.intermediate_act_fn = config.hidden_act
|
373 |
+
|
374 |
+
def forward(self, hidden_states):
|
375 |
+
hidden_states = self.dense(hidden_states)
|
376 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
377 |
+
return hidden_states
|
378 |
+
|
379 |
+
|
380 |
+
class BertOutput(nn.Module):
|
381 |
+
def __init__(self, config):
|
382 |
+
super().__init__()
|
383 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
384 |
+
self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
385 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
386 |
+
|
387 |
+
def forward(self, hidden_states, input_tensor):
|
388 |
+
hidden_states = self.dense(hidden_states)
|
389 |
+
hidden_states = self.dropout(hidden_states)
|
390 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
391 |
+
return hidden_states
|
392 |
+
|
393 |
+
|
394 |
+
class BertLayer(nn.Module):
|
395 |
+
def __init__(self, config):
|
396 |
+
super().__init__()
|
397 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
398 |
+
self.seq_len_dim = 1
|
399 |
+
self.attention = BertAttention(config)
|
400 |
+
self.is_decoder = config.is_decoder
|
401 |
+
self.add_cross_attention = config.add_cross_attention
|
402 |
+
if self.add_cross_attention:
|
403 |
+
assert self.is_decoder, f"{self} should be used as a decoder model if cross attention is added"
|
404 |
+
self.crossattention = BertAttention(config)
|
405 |
+
self.intermediate = BertIntermediate(config)
|
406 |
+
self.output = BertOutput(config)
|
407 |
+
|
408 |
+
def forward(
|
409 |
+
self,
|
410 |
+
hidden_states,
|
411 |
+
attention_mask=None,
|
412 |
+
head_mask=None,
|
413 |
+
encoder_hidden_states=None,
|
414 |
+
encoder_attention_mask=None,
|
415 |
+
output_attentions=False,
|
416 |
+
):
|
417 |
+
self_attention_outputs = self.attention(
|
418 |
+
hidden_states,
|
419 |
+
attention_mask,
|
420 |
+
head_mask,
|
421 |
+
output_attentions=output_attentions,
|
422 |
+
)
|
423 |
+
attention_output = self_attention_outputs[0]
|
424 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
425 |
+
|
426 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
427 |
+
assert hasattr(
|
428 |
+
self, "crossattention"
|
429 |
+
), f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`"
|
430 |
+
cross_attention_outputs = self.crossattention(
|
431 |
+
attention_output,
|
432 |
+
attention_mask,
|
433 |
+
head_mask,
|
434 |
+
encoder_hidden_states,
|
435 |
+
encoder_attention_mask,
|
436 |
+
output_attentions,
|
437 |
+
)
|
438 |
+
attention_output = cross_attention_outputs[0]
|
439 |
+
outputs = outputs + cross_attention_outputs[1:] # add cross attentions if we output attention weights
|
440 |
+
|
441 |
+
layer_output = apply_chunking_to_forward(
|
442 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
443 |
+
)
|
444 |
+
outputs = (layer_output,) + outputs
|
445 |
+
return outputs
|
446 |
+
|
447 |
+
def feed_forward_chunk(self, attention_output):
|
448 |
+
intermediate_output = self.intermediate(attention_output)
|
449 |
+
layer_output = self.output(intermediate_output, attention_output)
|
450 |
+
return layer_output
|
451 |
+
|
452 |
+
|
453 |
+
class BertEncoder(nn.Module):
|
454 |
+
def __init__(self, config):
|
455 |
+
super().__init__()
|
456 |
+
self.config = config
|
457 |
+
self.layer = nn.ModuleList([BertLayer(config) for _ in range(config.num_hidden_layers)])
|
458 |
+
|
459 |
+
def forward(
|
460 |
+
self,
|
461 |
+
hidden_states,
|
462 |
+
attention_mask=None,
|
463 |
+
head_mask=None,
|
464 |
+
encoder_hidden_states=None,
|
465 |
+
encoder_attention_mask=None,
|
466 |
+
output_attentions=False,
|
467 |
+
output_hidden_states=False,
|
468 |
+
return_dict=False,
|
469 |
+
):
|
470 |
+
all_hidden_states = () if output_hidden_states else None
|
471 |
+
all_attentions = () if output_attentions else None
|
472 |
+
for i, layer_module in enumerate(self.layer):
|
473 |
+
if output_hidden_states:
|
474 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
475 |
+
|
476 |
+
if getattr(self.config, "gradient_checkpointing", False):
|
477 |
+
|
478 |
+
def create_custom_forward(module):
|
479 |
+
def custom_forward(*inputs):
|
480 |
+
return module(*inputs, output_attentions)
|
481 |
+
|
482 |
+
return custom_forward
|
483 |
+
|
484 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
485 |
+
create_custom_forward(layer_module),
|
486 |
+
hidden_states,
|
487 |
+
attention_mask,
|
488 |
+
head_mask[i],
|
489 |
+
encoder_hidden_states,
|
490 |
+
encoder_attention_mask,
|
491 |
+
)
|
492 |
+
else:
|
493 |
+
layer_outputs = layer_module(
|
494 |
+
hidden_states,
|
495 |
+
attention_mask,
|
496 |
+
head_mask[i],
|
497 |
+
encoder_hidden_states,
|
498 |
+
encoder_attention_mask,
|
499 |
+
output_attentions,
|
500 |
+
)
|
501 |
+
hidden_states = layer_outputs[0]
|
502 |
+
if output_attentions:
|
503 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
504 |
+
|
505 |
+
if output_hidden_states:
|
506 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
507 |
+
|
508 |
+
if not return_dict:
|
509 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
|
510 |
+
return BaseModelOutput(
|
511 |
+
last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
|
512 |
+
)
|
513 |
+
|
514 |
+
|
515 |
+
class BertPooler(nn.Module):
|
516 |
+
def __init__(self, config):
|
517 |
+
super().__init__()
|
518 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
519 |
+
self.activation = nn.Tanh()
|
520 |
+
|
521 |
+
def forward(self, hidden_states):
|
522 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
523 |
+
# to the first token.
|
524 |
+
first_token_tensor = hidden_states[:, 0]
|
525 |
+
pooled_output = self.dense(first_token_tensor)
|
526 |
+
pooled_output = self.activation(pooled_output)
|
527 |
+
return pooled_output
|
528 |
+
|
529 |
+
|
530 |
+
class BertPredictionHeadTransform(nn.Module):
|
531 |
+
def __init__(self, config):
|
532 |
+
super().__init__()
|
533 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
534 |
+
if isinstance(config.hidden_act, str):
|
535 |
+
self.transform_act_fn = ACT2FN[config.hidden_act]
|
536 |
+
else:
|
537 |
+
self.transform_act_fn = config.hidden_act
|
538 |
+
self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
539 |
+
|
540 |
+
def forward(self, hidden_states):
|
541 |
+
hidden_states = self.dense(hidden_states)
|
542 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
543 |
+
hidden_states = self.LayerNorm(hidden_states)
|
544 |
+
return hidden_states
|
545 |
+
|
546 |
+
|
547 |
+
class BertLMPredictionHead(nn.Module):
|
548 |
+
def __init__(self, config):
|
549 |
+
super().__init__()
|
550 |
+
self.transform = BertPredictionHeadTransform(config)
|
551 |
+
|
552 |
+
# The output weights are the same as the input embeddings, but there is
|
553 |
+
# an output-only bias for each token.
|
554 |
+
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
555 |
+
|
556 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
557 |
+
|
558 |
+
# Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
|
559 |
+
self.decoder.bias = self.bias
|
560 |
+
|
561 |
+
def forward(self, hidden_states):
|
562 |
+
hidden_states = self.transform(hidden_states)
|
563 |
+
hidden_states = self.decoder(hidden_states)
|
564 |
+
return hidden_states
|
565 |
+
|
566 |
+
|
567 |
+
class BertOnlyMLMHead(nn.Module):
|
568 |
+
def __init__(self, config):
|
569 |
+
super().__init__()
|
570 |
+
self.predictions = BertLMPredictionHead(config)
|
571 |
+
|
572 |
+
def forward(self, sequence_output):
|
573 |
+
prediction_scores = self.predictions(sequence_output)
|
574 |
+
return prediction_scores
|
575 |
+
|
576 |
+
|
577 |
+
class BertOnlyNSPHead(nn.Module):
|
578 |
+
def __init__(self, config):
|
579 |
+
super().__init__()
|
580 |
+
self.seq_relationship = nn.Linear(config.hidden_size, 2)
|
581 |
+
|
582 |
+
def forward(self, pooled_output):
|
583 |
+
seq_relationship_score = self.seq_relationship(pooled_output)
|
584 |
+
return seq_relationship_score
|
585 |
+
|
586 |
+
|
587 |
+
class BertPreTrainingHeads(nn.Module):
|
588 |
+
def __init__(self, config):
|
589 |
+
super().__init__()
|
590 |
+
self.predictions = BertLMPredictionHead(config)
|
591 |
+
self.seq_relationship = nn.Linear(config.hidden_size, 2)
|
592 |
+
|
593 |
+
def forward(self, sequence_output, pooled_output):
|
594 |
+
prediction_scores = self.predictions(sequence_output)
|
595 |
+
seq_relationship_score = self.seq_relationship(pooled_output)
|
596 |
+
return prediction_scores, seq_relationship_score
|
597 |
+
|
598 |
+
|
599 |
+
class BertPreTrainedModel(PreTrainedModel):
|
600 |
+
"""An abstract class to handle weights initialization and
|
601 |
+
a simple interface for downloading and loading pretrained models.
|
602 |
+
"""
|
603 |
+
|
604 |
+
config_class = BertConfig
|
605 |
+
load_tf_weights = load_tf_weights_in_bert
|
606 |
+
base_model_prefix = "bert"
|
607 |
+
authorized_missing_keys = [r"position_ids"]
|
608 |
+
|
609 |
+
def _init_weights(self, module):
|
610 |
+
""" Initialize the weights """
|
611 |
+
if isinstance(module, (nn.Linear, nn.Embedding)):
|
612 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
613 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
614 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
615 |
+
elif isinstance(module, BertLayerNorm):
|
616 |
+
module.bias.data.zero_()
|
617 |
+
module.weight.data.fill_(1.0)
|
618 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
619 |
+
module.bias.data.zero_()
|
620 |
+
|
621 |
+
|
622 |
+
@dataclass
|
623 |
+
class BertForPreTrainingOutput(ModelOutput):
|
624 |
+
"""
|
625 |
+
Output type of :class:`~transformers.BertForPreTrainingModel`.
|
626 |
+
|
627 |
+
Args:
|
628 |
+
loss (`optional`, returned when ``labels`` is provided, ``torch.FloatTensor`` of shape :obj:`(1,)`):
|
629 |
+
Total loss as the sum of the masked language modeling loss and the next sequence prediction (classification) loss.
|
630 |
+
prediction_logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.vocab_size)`):
|
631 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
632 |
+
seq_relationship_logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, 2)`):
|
633 |
+
Prediction scores of the next sequence prediction (classification) head (scores of True/False
|
634 |
+
continuation before SoftMax).
|
635 |
+
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
|
636 |
+
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
|
637 |
+
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
|
638 |
+
|
639 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
640 |
+
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
|
641 |
+
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
|
642 |
+
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
|
643 |
+
|
644 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
645 |
+
heads.
|
646 |
+
"""
|
647 |
+
|
648 |
+
loss: Optional[torch.FloatTensor] = None
|
649 |
+
prediction_logits: torch.FloatTensor = None
|
650 |
+
seq_relationship_logits: torch.FloatTensor = None
|
651 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
652 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
653 |
+
|
654 |
+
|
655 |
+
BERT_START_DOCSTRING = r"""
|
656 |
+
This model is a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`_ sub-class.
|
657 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general
|
658 |
+
usage and behavior.
|
659 |
+
|
660 |
+
Parameters:
|
661 |
+
config (:class:`~transformers.BertConfig`): Model configuration class with all the parameters of the model.
|
662 |
+
Initializing with a config file does not load the weights associated with the model, only the configuration.
|
663 |
+
Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model weights.
|
664 |
+
"""
|
665 |
+
|
666 |
+
BERT_INPUTS_DOCSTRING = r"""
|
667 |
+
Args:
|
668 |
+
input_ids (:obj:`torch.LongTensor` of shape :obj:`{0}`):
|
669 |
+
Indices of input sequence tokens in the vocabulary.
|
670 |
+
|
671 |
+
Indices can be obtained using :class:`transformers.BertTokenizer`.
|
672 |
+
See :func:`transformers.PreTrainedTokenizer.encode` and
|
673 |
+
:func:`transformers.PreTrainedTokenizer.__call__` for details.
|
674 |
+
|
675 |
+
`What are input IDs? <../glossary.html#input-ids>`__
|
676 |
+
attention_mask (:obj:`torch.FloatTensor` of shape :obj:`{0}`, `optional`, defaults to :obj:`None`):
|
677 |
+
Mask to avoid performing attention on padding token indices.
|
678 |
+
Mask values selected in ``[0, 1]``:
|
679 |
+
``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.
|
680 |
+
|
681 |
+
`What are attention masks? <../glossary.html#attention-mask>`__
|
682 |
+
token_type_ids (:obj:`torch.LongTensor` of shape :obj:`{0}`, `optional`, defaults to :obj:`None`):
|
683 |
+
Segment token indices to indicate first and second portions of the inputs.
|
684 |
+
Indices are selected in ``[0, 1]``: ``0`` corresponds to a `sentence A` token, ``1``
|
685 |
+
corresponds to a `sentence B` token
|
686 |
+
|
687 |
+
`What are token type IDs? <../glossary.html#token-type-ids>`_
|
688 |
+
position_ids (:obj:`torch.LongTensor` of shape :obj:`{0}`, `optional`, defaults to :obj:`None`):
|
689 |
+
Indices of positions of each input sequence tokens in the position embeddings.
|
690 |
+
Selected in the range ``[0, config.max_position_embeddings - 1]``.
|
691 |
+
|
692 |
+
`What are position IDs? <../glossary.html#position-ids>`_
|
693 |
+
head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`, defaults to :obj:`None`):
|
694 |
+
Mask to nullify selected heads of the self-attention modules.
|
695 |
+
Mask values selected in ``[0, 1]``:
|
696 |
+
:obj:`1` indicates the head is **not masked**, :obj:`0` indicates the head is **masked**.
|
697 |
+
inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`, defaults to :obj:`None`):
|
698 |
+
Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation.
|
699 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
700 |
+
than the model's internal embedding lookup matrix.
|
701 |
+
output_attentions (:obj:`bool`, `optional`, defaults to :obj:`None`):
|
702 |
+
If set to ``True``, the attentions tensors of all attention layers are returned. See ``attentions`` under returned tensors for more detail.
|
703 |
+
output_hidden_states (:obj:`bool`, `optional`, defaults to :obj:`None`):
|
704 |
+
If set to ``True``, the hidden states of all layers are returned. See ``hidden_states`` under returned tensors for more detail.
|
705 |
+
return_dict (:obj:`bool`, `optional`, defaults to :obj:`None`):
|
706 |
+
If set to ``True``, the model will return a :class:`~transformers.file_utils.ModelOutput` instead of a
|
707 |
+
plain tuple.
|
708 |
+
"""
|
709 |
+
|
710 |
+
|
711 |
+
@add_start_docstrings(
|
712 |
+
"The bare Bert Model transformer outputting raw hidden-states without any specific head on top.",
|
713 |
+
BERT_START_DOCSTRING,
|
714 |
+
)
|
715 |
+
class BertModel(BertPreTrainedModel):
|
716 |
+
"""
|
717 |
+
|
718 |
+
The model can behave as an encoder (with only self-attention) as well
|
719 |
+
as a decoder, in which case a layer of cross-attention is added between
|
720 |
+
the self-attention layers, following the architecture described in `Attention is all you need`_ by Ashish Vaswani,
|
721 |
+
Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
|
722 |
+
|
723 |
+
To behave as an decoder the model needs to be initialized with the
|
724 |
+
:obj:`is_decoder` argument of the configuration set to :obj:`True`.
|
725 |
+
To be used in a Seq2Seq model, the model needs to initialized with both :obj:`is_decoder`
|
726 |
+
argument and :obj:`add_cross_attention` set to :obj:`True`; an
|
727 |
+
:obj:`encoder_hidden_states` is then expected as an input to the forward pass.
|
728 |
+
|
729 |
+
.. _`Attention is all you need`:
|
730 |
+
https://arxiv.org/abs/1706.03762
|
731 |
+
|
732 |
+
"""
|
733 |
+
|
734 |
+
def __init__(self, config):
|
735 |
+
super().__init__(config)
|
736 |
+
self.config = config
|
737 |
+
|
738 |
+
self.embeddings = BertEmbeddings(config)
|
739 |
+
self.encoder = BertEncoder(config)
|
740 |
+
self.pooler = BertPooler(config)
|
741 |
+
|
742 |
+
self.init_weights()
|
743 |
+
|
744 |
+
def get_input_embeddings(self):
|
745 |
+
return self.embeddings.word_embeddings
|
746 |
+
|
747 |
+
def set_input_embeddings(self, value):
|
748 |
+
self.embeddings.word_embeddings = value
|
749 |
+
|
750 |
+
def _prune_heads(self, heads_to_prune):
|
751 |
+
"""Prunes heads of the model.
|
752 |
+
heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
|
753 |
+
See base class PreTrainedModel
|
754 |
+
"""
|
755 |
+
for layer, heads in heads_to_prune.items():
|
756 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
757 |
+
|
758 |
+
@add_start_docstrings_to_callable(BERT_INPUTS_DOCSTRING.format("(batch_size, sequence_length)"))
|
759 |
+
@add_code_sample_docstrings(
|
760 |
+
tokenizer_class=_TOKENIZER_FOR_DOC,
|
761 |
+
checkpoint="bert-base-uncased",
|
762 |
+
output_type=BaseModelOutputWithPooling,
|
763 |
+
config_class=_CONFIG_FOR_DOC,
|
764 |
+
)
|
765 |
+
def forward(
|
766 |
+
self,
|
767 |
+
input_ids=None,
|
768 |
+
attention_mask=None,
|
769 |
+
token_type_ids=None,
|
770 |
+
position_ids=None,
|
771 |
+
head_mask=None,
|
772 |
+
inputs_embeds=None,
|
773 |
+
encoder_hidden_states=None,
|
774 |
+
encoder_attention_mask=None,
|
775 |
+
output_attentions=None,
|
776 |
+
output_hidden_states=None,
|
777 |
+
return_dict=None,
|
778 |
+
toxic_ids=None
|
779 |
+
):
|
780 |
+
r"""
|
781 |
+
encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`, defaults to :obj:`None`):
|
782 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
783 |
+
if the model is configured as a decoder.
|
784 |
+
encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
|
785 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask
|
786 |
+
is used in the cross-attention if the model is configured as a decoder.
|
787 |
+
Mask values selected in ``[0, 1]``:
|
788 |
+
``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.
|
789 |
+
"""
|
790 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
791 |
+
output_hidden_states = (
|
792 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
793 |
+
)
|
794 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
795 |
+
|
796 |
+
if input_ids is not None and inputs_embeds is not None:
|
797 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
798 |
+
elif input_ids is not None:
|
799 |
+
input_shape = input_ids.size()
|
800 |
+
elif inputs_embeds is not None:
|
801 |
+
input_shape = inputs_embeds.size()[:-1]
|
802 |
+
else:
|
803 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
804 |
+
|
805 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
806 |
+
|
807 |
+
if attention_mask is None:
|
808 |
+
attention_mask = torch.ones(input_shape, device=device)
|
809 |
+
if token_type_ids is None:
|
810 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
811 |
+
|
812 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
813 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
814 |
+
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape, device)
|
815 |
+
|
816 |
+
# If a 2D ou 3D attention mask is provided for the cross-attention
|
817 |
+
# we need to make broadcastabe to [batch_size, num_heads, seq_length, seq_length]
|
818 |
+
if self.config.is_decoder and encoder_hidden_states is not None:
|
819 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
|
820 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
821 |
+
if encoder_attention_mask is None:
|
822 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
823 |
+
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
824 |
+
else:
|
825 |
+
encoder_extended_attention_mask = None
|
826 |
+
|
827 |
+
# Prepare head mask if needed
|
828 |
+
# 1.0 in head_mask indicate we keep the head
|
829 |
+
# attention_probs has shape bsz x n_heads x N x N
|
830 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
831 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
832 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
833 |
+
|
834 |
+
embedding_output = self.embeddings(
|
835 |
+
input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, toxic_ids=toxic_ids, inputs_embeds=inputs_embeds
|
836 |
+
)
|
837 |
+
encoder_outputs = self.encoder(
|
838 |
+
embedding_output,
|
839 |
+
attention_mask=extended_attention_mask,
|
840 |
+
head_mask=head_mask,
|
841 |
+
encoder_hidden_states=encoder_hidden_states,
|
842 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
843 |
+
output_attentions=output_attentions,
|
844 |
+
output_hidden_states=output_hidden_states,
|
845 |
+
return_dict=return_dict,
|
846 |
+
)
|
847 |
+
sequence_output = encoder_outputs[0]
|
848 |
+
pooled_output = self.pooler(sequence_output)
|
849 |
+
|
850 |
+
if not return_dict:
|
851 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
852 |
+
|
853 |
+
return BaseModelOutputWithPooling(
|
854 |
+
last_hidden_state=sequence_output,
|
855 |
+
pooler_output=pooled_output,
|
856 |
+
hidden_states=encoder_outputs.hidden_states,
|
857 |
+
attentions=encoder_outputs.attentions,
|
858 |
+
)
|
859 |
+
|
860 |
+
|
861 |
+
@add_start_docstrings(
|
862 |
+
"""Bert Model with two heads on top as done during the pre-training: a `masked language modeling` head and
|
863 |
+
a `next sentence prediction (classification)` head. """,
|
864 |
+
BERT_START_DOCSTRING,
|
865 |
+
)
|
866 |
+
class BertForPreTraining(BertPreTrainedModel):
|
867 |
+
def __init__(self, config):
|
868 |
+
super().__init__(config)
|
869 |
+
|
870 |
+
self.bert = BertModel(config)
|
871 |
+
self.cls = BertPreTrainingHeads(config)
|
872 |
+
|
873 |
+
self.init_weights()
|
874 |
+
|
875 |
+
def get_output_embeddings(self):
|
876 |
+
return self.cls.predictions.decoder
|
877 |
+
|
878 |
+
@add_start_docstrings_to_callable(BERT_INPUTS_DOCSTRING.format("(batch_size, sequence_length)"))
|
879 |
+
@replace_return_docstrings(output_type=BertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
|
880 |
+
def forward(
|
881 |
+
self,
|
882 |
+
input_ids=None,
|
883 |
+
attention_mask=None,
|
884 |
+
token_type_ids=None,
|
885 |
+
position_ids=None,
|
886 |
+
head_mask=None,
|
887 |
+
inputs_embeds=None,
|
888 |
+
labels=None,
|
889 |
+
next_sentence_label=None,
|
890 |
+
output_attentions=None,
|
891 |
+
output_hidden_states=None,
|
892 |
+
return_dict=None,
|
893 |
+
**kwargs
|
894 |
+
):
|
895 |
+
r"""
|
896 |
+
labels (``torch.LongTensor`` of shape ``(batch_size, sequence_length)``, `optional`, defaults to :obj:`None`):
|
897 |
+
Labels for computing the masked language modeling loss.
|
898 |
+
Indices should be in ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring)
|
899 |
+
Tokens with indices set to ``-100`` are ignored (masked), the loss is only computed for the tokens with labels
|
900 |
+
in ``[0, ..., config.vocab_size]``
|
901 |
+
next_sentence_label (``torch.LongTensor`` of shape ``(batch_size,)``, `optional`, defaults to :obj:`None`):
|
902 |
+
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair (see :obj:`input_ids` docstring)
|
903 |
+
Indices should be in ``[0, 1]``.
|
904 |
+
``0`` indicates sequence B is a continuation of sequence A,
|
905 |
+
``1`` indicates sequence B is a random sequence.
|
906 |
+
kwargs (:obj:`Dict[str, any]`, optional, defaults to `{}`):
|
907 |
+
Used to hide legacy arguments that have been deprecated.
|
908 |
+
|
909 |
+
Returns:
|
910 |
+
|
911 |
+
Examples::
|
912 |
+
|
913 |
+
>>> from transformers import BertTokenizer, BertForPreTraining
|
914 |
+
>>> import torch
|
915 |
+
|
916 |
+
>>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
|
917 |
+
>>> model = BertForPreTraining.from_pretrained('bert-base-uncased', return_dict=True)
|
918 |
+
|
919 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
|
920 |
+
>>> outputs = model(**inputs)
|
921 |
+
|
922 |
+
>>> prediction_logits = outptus.prediction_logits
|
923 |
+
>>> seq_relationship_logits = outputs.seq_relationship_logits
|
924 |
+
"""
|
925 |
+
if "masked_lm_labels" in kwargs:
|
926 |
+
warnings.warn(
|
927 |
+
"The `masked_lm_labels` argument is deprecated and will be removed in a future version, use `labels` instead.",
|
928 |
+
FutureWarning,
|
929 |
+
)
|
930 |
+
labels = kwargs.pop("masked_lm_labels")
|
931 |
+
assert kwargs == {}, f"Unexpected keyword arguments: {list(kwargs.keys())}."
|
932 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
933 |
+
|
934 |
+
outputs = self.bert(
|
935 |
+
input_ids,
|
936 |
+
attention_mask=attention_mask,
|
937 |
+
token_type_ids=token_type_ids,
|
938 |
+
position_ids=position_ids,
|
939 |
+
head_mask=head_mask,
|
940 |
+
inputs_embeds=inputs_embeds,
|
941 |
+
output_attentions=output_attentions,
|
942 |
+
output_hidden_states=output_hidden_states,
|
943 |
+
return_dict=return_dict,
|
944 |
+
)
|
945 |
+
|
946 |
+
sequence_output, pooled_output = outputs[:2]
|
947 |
+
prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
|
948 |
+
|
949 |
+
total_loss = None
|
950 |
+
if labels is not None and next_sentence_label is not None:
|
951 |
+
loss_fct = CrossEntropyLoss()
|
952 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
953 |
+
next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
|
954 |
+
total_loss = masked_lm_loss + next_sentence_loss
|
955 |
+
|
956 |
+
if not return_dict:
|
957 |
+
output = (prediction_scores, seq_relationship_score) + outputs[2:]
|
958 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
959 |
+
|
960 |
+
return BertForPreTrainingOutput(
|
961 |
+
loss=total_loss,
|
962 |
+
prediction_logits=prediction_scores,
|
963 |
+
seq_relationship_logits=seq_relationship_score,
|
964 |
+
hidden_states=outputs.hidden_states,
|
965 |
+
attentions=outputs.attentions,
|
966 |
+
)
|
967 |
+
|
968 |
+
|
969 |
+
@add_start_docstrings(
|
970 |
+
"""Bert Model with a `language modeling` head on top for CLM fine-tuning. """, BERT_START_DOCSTRING
|
971 |
+
)
|
972 |
+
class BertLMHeadModel(BertPreTrainedModel):
|
973 |
+
def __init__(self, config):
|
974 |
+
super().__init__(config)
|
975 |
+
|
976 |
+
if not config.is_decoder:
|
977 |
+
logger.warning("If you want to use `BertLMHeadModel` as a standalone, add `is_decoder=True.`")
|
978 |
+
|
979 |
+
self.bert = BertModel(config)
|
980 |
+
self.cls = BertOnlyMLMHead(config)
|
981 |
+
|
982 |
+
self.init_weights()
|
983 |
+
|
984 |
+
def get_output_embeddings(self):
|
985 |
+
return self.cls.predictions.decoder
|
986 |
+
|
987 |
+
@add_start_docstrings_to_callable(BERT_INPUTS_DOCSTRING.format("(batch_size, sequence_length)"))
|
988 |
+
@replace_return_docstrings(output_type=CausalLMOutput, config_class=_CONFIG_FOR_DOC)
|
989 |
+
def forward(
|
990 |
+
self,
|
991 |
+
input_ids=None,
|
992 |
+
attention_mask=None,
|
993 |
+
token_type_ids=None,
|
994 |
+
position_ids=None,
|
995 |
+
head_mask=None,
|
996 |
+
inputs_embeds=None,
|
997 |
+
encoder_hidden_states=None,
|
998 |
+
encoder_attention_mask=None,
|
999 |
+
labels=None,
|
1000 |
+
output_attentions=None,
|
1001 |
+
output_hidden_states=None,
|
1002 |
+
return_dict=None,
|
1003 |
+
):
|
1004 |
+
r"""
|
1005 |
+
encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`, defaults to :obj:`None`):
|
1006 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
1007 |
+
if the model is configured as a decoder.
|
1008 |
+
encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
|
1009 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask
|
1010 |
+
is used in the cross-attention if the model is configured as a decoder.
|
1011 |
+
Mask values selected in ``[0, 1]``:
|
1012 |
+
``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.
|
1013 |
+
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
|
1014 |
+
Labels for computing the left-to-right language modeling loss (next word prediction).
|
1015 |
+
Indices should be in ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring)
|
1016 |
+
Tokens with indices set to ``-100`` are ignored (masked), the loss is only computed for the tokens with labels
|
1017 |
+
in ``[0, ..., config.vocab_size]``
|
1018 |
+
|
1019 |
+
Returns:
|
1020 |
+
|
1021 |
+
Example::
|
1022 |
+
|
1023 |
+
>>> from transformers import BertTokenizer, BertLMHeadModel, BertConfig
|
1024 |
+
>>> import torch
|
1025 |
+
|
1026 |
+
>>> tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
|
1027 |
+
>>> config = BertConfig.from_pretrained("bert-base-cased")
|
1028 |
+
>>> config.is_decoder = True
|
1029 |
+
>>> model = BertLMHeadModel.from_pretrained('bert-base-cased', config=config, return_dict=True)
|
1030 |
+
|
1031 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
|
1032 |
+
>>> outputs = model(**inputs)
|
1033 |
+
|
1034 |
+
>>> prediction_logits = outputs.logits
|
1035 |
+
"""
|
1036 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1037 |
+
|
1038 |
+
outputs = self.bert(
|
1039 |
+
input_ids,
|
1040 |
+
attention_mask=attention_mask,
|
1041 |
+
token_type_ids=token_type_ids,
|
1042 |
+
position_ids=position_ids,
|
1043 |
+
head_mask=head_mask,
|
1044 |
+
inputs_embeds=inputs_embeds,
|
1045 |
+
encoder_hidden_states=encoder_hidden_states,
|
1046 |
+
encoder_attention_mask=encoder_attention_mask,
|
1047 |
+
output_attentions=output_attentions,
|
1048 |
+
output_hidden_states=output_hidden_states,
|
1049 |
+
return_dict=return_dict,
|
1050 |
+
)
|
1051 |
+
|
1052 |
+
sequence_output = outputs[0]
|
1053 |
+
prediction_scores = self.cls(sequence_output)
|
1054 |
+
|
1055 |
+
lm_loss = None
|
1056 |
+
if labels is not None:
|
1057 |
+
# we are doing next-token prediction; shift prediction scores and input ids by one
|
1058 |
+
shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
|
1059 |
+
labels = labels[:, 1:].contiguous()
|
1060 |
+
loss_fct = CrossEntropyLoss()
|
1061 |
+
lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
1062 |
+
|
1063 |
+
if not return_dict:
|
1064 |
+
output = (prediction_scores,) + outputs[2:]
|
1065 |
+
return ((lm_loss,) + output) if lm_loss is not None else output
|
1066 |
+
|
1067 |
+
return CausalLMOutput(
|
1068 |
+
loss=lm_loss,
|
1069 |
+
logits=prediction_scores,
|
1070 |
+
hidden_states=outputs.hidden_states,
|
1071 |
+
attentions=outputs.attentions,
|
1072 |
+
)
|
1073 |
+
|
1074 |
+
def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_kwargs):
|
1075 |
+
input_shape = input_ids.shape
|
1076 |
+
|
1077 |
+
# if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
|
1078 |
+
if attention_mask is None:
|
1079 |
+
attention_mask = input_ids.new_ones(input_shape)
|
1080 |
+
|
1081 |
+
return {"input_ids": input_ids, "attention_mask": attention_mask}
|
1082 |
+
|
1083 |
+
|
1084 |
+
@add_start_docstrings("""Bert Model with a `language modeling` head on top. """, BERT_START_DOCSTRING)
|
1085 |
+
class BertForMaskedLM(BertPreTrainedModel):
|
1086 |
+
def __init__(self, config):
|
1087 |
+
super().__init__(config)
|
1088 |
+
|
1089 |
+
if config.is_decoder:
|
1090 |
+
logger.warning(
|
1091 |
+
"If you want to use `BertForMaskedLM` make sure `config.is_decoder=False` for "
|
1092 |
+
"bi-directional self-attention."
|
1093 |
+
)
|
1094 |
+
|
1095 |
+
self.bert = BertModel(config)
|
1096 |
+
self.cls = BertOnlyMLMHead(config)
|
1097 |
+
|
1098 |
+
self.init_weights()
|
1099 |
+
|
1100 |
+
def get_output_embeddings(self):
|
1101 |
+
return self.cls.predictions.decoder
|
1102 |
+
|
1103 |
+
@add_start_docstrings_to_callable(BERT_INPUTS_DOCSTRING.format("(batch_size, sequence_length)"))
|
1104 |
+
@add_code_sample_docstrings(
|
1105 |
+
tokenizer_class=_TOKENIZER_FOR_DOC,
|
1106 |
+
checkpoint="bert-base-uncased",
|
1107 |
+
output_type=MaskedLMOutput,
|
1108 |
+
config_class=_CONFIG_FOR_DOC,
|
1109 |
+
)
|
1110 |
+
def forward(
|
1111 |
+
self,
|
1112 |
+
input_ids=None,
|
1113 |
+
attention_mask=None,
|
1114 |
+
token_type_ids=None,
|
1115 |
+
position_ids=None,
|
1116 |
+
head_mask=None,
|
1117 |
+
inputs_embeds=None,
|
1118 |
+
encoder_hidden_states=None,
|
1119 |
+
encoder_attention_mask=None,
|
1120 |
+
labels=None,
|
1121 |
+
output_attentions=None,
|
1122 |
+
output_hidden_states=None,
|
1123 |
+
return_dict=None,
|
1124 |
+
**kwargs
|
1125 |
+
):
|
1126 |
+
r"""
|
1127 |
+
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
|
1128 |
+
Labels for computing the masked language modeling loss.
|
1129 |
+
Indices should be in ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring)
|
1130 |
+
Tokens with indices set to ``-100`` are ignored (masked), the loss is only computed for the tokens with labels
|
1131 |
+
in ``[0, ..., config.vocab_size]``
|
1132 |
+
kwargs (:obj:`Dict[str, any]`, optional, defaults to `{}`):
|
1133 |
+
Used to hide legacy arguments that have been deprecated.
|
1134 |
+
"""
|
1135 |
+
if "masked_lm_labels" in kwargs:
|
1136 |
+
warnings.warn(
|
1137 |
+
"The `masked_lm_labels` argument is deprecated and will be removed in a future version, use `labels` instead.",
|
1138 |
+
FutureWarning,
|
1139 |
+
)
|
1140 |
+
labels = kwargs.pop("masked_lm_labels")
|
1141 |
+
assert "lm_labels" not in kwargs, "Use `BertWithLMHead` for autoregressive language modeling task."
|
1142 |
+
assert kwargs == {}, f"Unexpected keyword arguments: {list(kwargs.keys())}."
|
1143 |
+
|
1144 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1145 |
+
|
1146 |
+
outputs = self.bert(
|
1147 |
+
input_ids,
|
1148 |
+
attention_mask=attention_mask,
|
1149 |
+
token_type_ids=token_type_ids,
|
1150 |
+
position_ids=position_ids,
|
1151 |
+
head_mask=head_mask,
|
1152 |
+
inputs_embeds=inputs_embeds,
|
1153 |
+
encoder_hidden_states=encoder_hidden_states,
|
1154 |
+
encoder_attention_mask=encoder_attention_mask,
|
1155 |
+
output_attentions=output_attentions,
|
1156 |
+
output_hidden_states=output_hidden_states,
|
1157 |
+
return_dict=return_dict,
|
1158 |
+
)
|
1159 |
+
|
1160 |
+
sequence_output = outputs[0]
|
1161 |
+
prediction_scores = self.cls(sequence_output)
|
1162 |
+
|
1163 |
+
masked_lm_loss = None
|
1164 |
+
if labels is not None:
|
1165 |
+
loss_fct = CrossEntropyLoss() # -100 index = padding token
|
1166 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
1167 |
+
|
1168 |
+
if not return_dict:
|
1169 |
+
output = (prediction_scores,) + outputs[2:]
|
1170 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
1171 |
+
|
1172 |
+
return MaskedLMOutput(
|
1173 |
+
loss=masked_lm_loss,
|
1174 |
+
logits=prediction_scores,
|
1175 |
+
hidden_states=outputs.hidden_states,
|
1176 |
+
attentions=outputs.attentions,
|
1177 |
+
)
|
1178 |
+
|
1179 |
+
def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_kwargs):
|
1180 |
+
input_shape = input_ids.shape
|
1181 |
+
effective_batch_size = input_shape[0]
|
1182 |
+
|
1183 |
+
# add a dummy token
|
1184 |
+
assert self.config.pad_token_id is not None, "The PAD token should be defined for generation"
|
1185 |
+
attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1)
|
1186 |
+
dummy_token = torch.full(
|
1187 |
+
(effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device
|
1188 |
+
)
|
1189 |
+
input_ids = torch.cat([input_ids, dummy_token], dim=1)
|
1190 |
+
|
1191 |
+
return {"input_ids": input_ids, "attention_mask": attention_mask}
|
1192 |
+
|
1193 |
+
|
1194 |
+
@add_start_docstrings(
|
1195 |
+
"""Bert Model with a `next sentence prediction (classification)` head on top. """,
|
1196 |
+
BERT_START_DOCSTRING,
|
1197 |
+
)
|
1198 |
+
class BertForNextSentencePrediction(BertPreTrainedModel):
|
1199 |
+
def __init__(self, config):
|
1200 |
+
super().__init__(config)
|
1201 |
+
|
1202 |
+
self.bert = BertModel(config)
|
1203 |
+
self.cls = BertOnlyNSPHead(config)
|
1204 |
+
|
1205 |
+
self.init_weights()
|
1206 |
+
|
1207 |
+
@add_start_docstrings_to_callable(BERT_INPUTS_DOCSTRING.format("(batch_size, sequence_length)"))
|
1208 |
+
@replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
|
1209 |
+
def forward(
|
1210 |
+
self,
|
1211 |
+
input_ids=None,
|
1212 |
+
attention_mask=None,
|
1213 |
+
token_type_ids=None,
|
1214 |
+
position_ids=None,
|
1215 |
+
head_mask=None,
|
1216 |
+
inputs_embeds=None,
|
1217 |
+
next_sentence_label=None,
|
1218 |
+
output_attentions=None,
|
1219 |
+
output_hidden_states=None,
|
1220 |
+
return_dict=None,
|
1221 |
+
):
|
1222 |
+
r"""
|
1223 |
+
next_sentence_label (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):
|
1224 |
+
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair (see ``input_ids`` docstring)
|
1225 |
+
Indices should be in ``[0, 1]``.
|
1226 |
+
``0`` indicates sequence B is a continuation of sequence A,
|
1227 |
+
``1`` indicates sequence B is a random sequence.
|
1228 |
+
|
1229 |
+
Returns:
|
1230 |
+
|
1231 |
+
Example::
|
1232 |
+
|
1233 |
+
>>> from transformers import BertTokenizer, BertForNextSentencePrediction
|
1234 |
+
>>> import torch
|
1235 |
+
|
1236 |
+
>>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
|
1237 |
+
>>> model = BertForNextSentencePrediction.from_pretrained('bert-base-uncased', return_dict=True)
|
1238 |
+
|
1239 |
+
>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
|
1240 |
+
>>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
|
1241 |
+
>>> encoding = tokenizer(prompt, next_sentence, return_tensors='pt')
|
1242 |
+
|
1243 |
+
>>> outputs = model(**encoding, next_sentence_label=torch.LongTensor([1]))
|
1244 |
+
>>> logits = outputs.logits
|
1245 |
+
>>> assert logits[0, 0] < logits[0, 1] # next sentence was random
|
1246 |
+
"""
|
1247 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1248 |
+
|
1249 |
+
outputs = self.bert(
|
1250 |
+
input_ids,
|
1251 |
+
attention_mask=attention_mask,
|
1252 |
+
token_type_ids=token_type_ids,
|
1253 |
+
position_ids=position_ids,
|
1254 |
+
head_mask=head_mask,
|
1255 |
+
inputs_embeds=inputs_embeds,
|
1256 |
+
output_attentions=output_attentions,
|
1257 |
+
output_hidden_states=output_hidden_states,
|
1258 |
+
return_dict=return_dict,
|
1259 |
+
)
|
1260 |
+
|
1261 |
+
pooled_output = outputs[1]
|
1262 |
+
|
1263 |
+
seq_relationship_scores = self.cls(pooled_output)
|
1264 |
+
|
1265 |
+
next_sentence_loss = None
|
1266 |
+
if next_sentence_label is not None:
|
1267 |
+
loss_fct = CrossEntropyLoss()
|
1268 |
+
next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), next_sentence_label.view(-1))
|
1269 |
+
|
1270 |
+
if not return_dict:
|
1271 |
+
output = (seq_relationship_scores,) + outputs[2:]
|
1272 |
+
return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
|
1273 |
+
|
1274 |
+
return NextSentencePredictorOutput(
|
1275 |
+
loss=next_sentence_loss,
|
1276 |
+
logits=seq_relationship_scores,
|
1277 |
+
hidden_states=outputs.hidden_states,
|
1278 |
+
attentions=outputs.attentions,
|
1279 |
+
)
|
1280 |
+
|
1281 |
+
|
1282 |
+
@add_start_docstrings(
|
1283 |
+
"""Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of
|
1284 |
+
the pooled output) e.g. for GLUE tasks. """,
|
1285 |
+
BERT_START_DOCSTRING,
|
1286 |
+
)
|
1287 |
+
class BertForSequenceClassification(BertPreTrainedModel):
|
1288 |
+
def __init__(self, config):
|
1289 |
+
super().__init__(config)
|
1290 |
+
self.num_labels = config.num_labels
|
1291 |
+
|
1292 |
+
self.bert = BertModel(config)
|
1293 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
1294 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
1295 |
+
|
1296 |
+
self.init_weights()
|
1297 |
+
|
1298 |
+
@add_start_docstrings_to_callable(BERT_INPUTS_DOCSTRING.format("(batch_size, sequence_length)"))
|
1299 |
+
@add_code_sample_docstrings(
|
1300 |
+
tokenizer_class=_TOKENIZER_FOR_DOC,
|
1301 |
+
checkpoint="bert-base-uncased",
|
1302 |
+
output_type=SequenceClassifierOutput,
|
1303 |
+
config_class=_CONFIG_FOR_DOC,
|
1304 |
+
)
|
1305 |
+
def forward(
|
1306 |
+
self,
|
1307 |
+
input_ids=None,
|
1308 |
+
attention_mask=None,
|
1309 |
+
token_type_ids=None,
|
1310 |
+
position_ids=None,
|
1311 |
+
head_mask=None,
|
1312 |
+
inputs_embeds=None,
|
1313 |
+
labels=None,
|
1314 |
+
output_attentions=None,
|
1315 |
+
output_hidden_states=None,
|
1316 |
+
return_dict=None,
|
1317 |
+
):
|
1318 |
+
r"""
|
1319 |
+
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):
|
1320 |
+
Labels for computing the sequence classification/regression loss.
|
1321 |
+
Indices should be in :obj:`[0, ..., config.num_labels - 1]`.
|
1322 |
+
If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss),
|
1323 |
+
If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1324 |
+
"""
|
1325 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1326 |
+
|
1327 |
+
outputs = self.bert(
|
1328 |
+
input_ids,
|
1329 |
+
attention_mask=attention_mask,
|
1330 |
+
token_type_ids=token_type_ids,
|
1331 |
+
position_ids=position_ids,
|
1332 |
+
head_mask=head_mask,
|
1333 |
+
inputs_embeds=inputs_embeds,
|
1334 |
+
output_attentions=output_attentions,
|
1335 |
+
output_hidden_states=output_hidden_states,
|
1336 |
+
return_dict=return_dict,
|
1337 |
+
)
|
1338 |
+
|
1339 |
+
pooled_output = outputs[1]
|
1340 |
+
|
1341 |
+
pooled_output = self.dropout(pooled_output)
|
1342 |
+
logits = self.classifier(pooled_output)
|
1343 |
+
|
1344 |
+
loss = None
|
1345 |
+
if labels is not None:
|
1346 |
+
if self.num_labels == 1:
|
1347 |
+
# We are doing regression
|
1348 |
+
loss_fct = MSELoss()
|
1349 |
+
loss = loss_fct(logits.view(-1), labels.view(-1))
|
1350 |
+
else:
|
1351 |
+
loss_fct = CrossEntropyLoss()
|
1352 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
1353 |
+
|
1354 |
+
if not return_dict:
|
1355 |
+
output = (logits,) + outputs[2:]
|
1356 |
+
return ((loss,) + output) if loss is not None else output
|
1357 |
+
|
1358 |
+
return SequenceClassifierOutput(
|
1359 |
+
loss=loss,
|
1360 |
+
logits=logits,
|
1361 |
+
hidden_states=outputs.hidden_states,
|
1362 |
+
attentions=outputs.attentions,
|
1363 |
+
)
|
1364 |
+
|
1365 |
+
|
1366 |
+
@add_start_docstrings(
|
1367 |
+
"""Bert Model with a multiple choice classification head on top (a linear layer on top of
|
1368 |
+
the pooled output and a softmax) e.g. for RocStories/SWAG tasks. """,
|
1369 |
+
BERT_START_DOCSTRING,
|
1370 |
+
)
|
1371 |
+
class BertForMultipleChoice(BertPreTrainedModel):
|
1372 |
+
def __init__(self, config):
|
1373 |
+
super().__init__(config)
|
1374 |
+
|
1375 |
+
self.bert = BertModel(config)
|
1376 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
1377 |
+
self.classifier = nn.Linear(config.hidden_size, 1)
|
1378 |
+
|
1379 |
+
self.init_weights()
|
1380 |
+
|
1381 |
+
@add_start_docstrings_to_callable(BERT_INPUTS_DOCSTRING.format("(batch_size, num_choices, sequence_length)"))
|
1382 |
+
@add_code_sample_docstrings(
|
1383 |
+
tokenizer_class=_TOKENIZER_FOR_DOC,
|
1384 |
+
checkpoint="bert-base-uncased",
|
1385 |
+
output_type=MultipleChoiceModelOutput,
|
1386 |
+
config_class=_CONFIG_FOR_DOC,
|
1387 |
+
)
|
1388 |
+
def forward(
|
1389 |
+
self,
|
1390 |
+
input_ids=None,
|
1391 |
+
attention_mask=None,
|
1392 |
+
token_type_ids=None,
|
1393 |
+
position_ids=None,
|
1394 |
+
head_mask=None,
|
1395 |
+
inputs_embeds=None,
|
1396 |
+
labels=None,
|
1397 |
+
output_attentions=None,
|
1398 |
+
output_hidden_states=None,
|
1399 |
+
return_dict=None,
|
1400 |
+
):
|
1401 |
+
r"""
|
1402 |
+
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):
|
1403 |
+
Labels for computing the multiple choice classification loss.
|
1404 |
+
Indices should be in ``[0, ..., num_choices-1]`` where `num_choices` is the size of the second dimension
|
1405 |
+
of the input tensors. (see `input_ids` above)
|
1406 |
+
"""
|
1407 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1408 |
+
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
|
1409 |
+
|
1410 |
+
input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
|
1411 |
+
attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
|
1412 |
+
token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
|
1413 |
+
position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
|
1414 |
+
inputs_embeds = (
|
1415 |
+
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
|
1416 |
+
if inputs_embeds is not None
|
1417 |
+
else None
|
1418 |
+
)
|
1419 |
+
|
1420 |
+
outputs = self.bert(
|
1421 |
+
input_ids,
|
1422 |
+
attention_mask=attention_mask,
|
1423 |
+
token_type_ids=token_type_ids,
|
1424 |
+
position_ids=position_ids,
|
1425 |
+
head_mask=head_mask,
|
1426 |
+
inputs_embeds=inputs_embeds,
|
1427 |
+
output_attentions=output_attentions,
|
1428 |
+
output_hidden_states=output_hidden_states,
|
1429 |
+
return_dict=return_dict,
|
1430 |
+
)
|
1431 |
+
|
1432 |
+
pooled_output = outputs[1]
|
1433 |
+
|
1434 |
+
pooled_output = self.dropout(pooled_output)
|
1435 |
+
logits = self.classifier(pooled_output)
|
1436 |
+
reshaped_logits = logits.view(-1, num_choices)
|
1437 |
+
|
1438 |
+
loss = None
|
1439 |
+
if labels is not None:
|
1440 |
+
loss_fct = CrossEntropyLoss()
|
1441 |
+
loss = loss_fct(reshaped_logits, labels)
|
1442 |
+
|
1443 |
+
if not return_dict:
|
1444 |
+
output = (reshaped_logits,) + outputs[2:]
|
1445 |
+
return ((loss,) + output) if loss is not None else output
|
1446 |
+
|
1447 |
+
return MultipleChoiceModelOutput(
|
1448 |
+
loss=loss,
|
1449 |
+
logits=reshaped_logits,
|
1450 |
+
hidden_states=outputs.hidden_states,
|
1451 |
+
attentions=outputs.attentions,
|
1452 |
+
)
|
1453 |
+
|
1454 |
+
|
1455 |
+
@add_start_docstrings(
|
1456 |
+
"""Bert Model with a token classification head on top (a linear layer on top of
|
1457 |
+
the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. """,
|
1458 |
+
BERT_START_DOCSTRING,
|
1459 |
+
)
|
1460 |
+
class BertForTokenClassification(BertPreTrainedModel):
|
1461 |
+
def __init__(self, config):
|
1462 |
+
super().__init__(config)
|
1463 |
+
self.num_labels = config.num_labels
|
1464 |
+
|
1465 |
+
self.bert = BertModel(config)
|
1466 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
1467 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
1468 |
+
|
1469 |
+
self.init_weights()
|
1470 |
+
|
1471 |
+
@add_start_docstrings_to_callable(BERT_INPUTS_DOCSTRING.format("(batch_size, sequence_length)"))
|
1472 |
+
@add_code_sample_docstrings(
|
1473 |
+
tokenizer_class=_TOKENIZER_FOR_DOC,
|
1474 |
+
checkpoint="bert-base-uncased",
|
1475 |
+
output_type=TokenClassifierOutput,
|
1476 |
+
config_class=_CONFIG_FOR_DOC,
|
1477 |
+
)
|
1478 |
+
def forward(
|
1479 |
+
self,
|
1480 |
+
input_ids=None,
|
1481 |
+
attention_mask=None,
|
1482 |
+
token_type_ids=None,
|
1483 |
+
position_ids=None,
|
1484 |
+
head_mask=None,
|
1485 |
+
inputs_embeds=None,
|
1486 |
+
labels=None,
|
1487 |
+
output_attentions=None,
|
1488 |
+
output_hidden_states=None,
|
1489 |
+
return_dict=None,
|
1490 |
+
):
|
1491 |
+
r"""
|
1492 |
+
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
|
1493 |
+
Labels for computing the token classification loss.
|
1494 |
+
Indices should be in ``[0, ..., config.num_labels - 1]``.
|
1495 |
+
"""
|
1496 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1497 |
+
|
1498 |
+
outputs = self.bert(
|
1499 |
+
input_ids,
|
1500 |
+
attention_mask=attention_mask,
|
1501 |
+
token_type_ids=token_type_ids,
|
1502 |
+
position_ids=position_ids,
|
1503 |
+
head_mask=head_mask,
|
1504 |
+
inputs_embeds=inputs_embeds,
|
1505 |
+
output_attentions=output_attentions,
|
1506 |
+
output_hidden_states=output_hidden_states,
|
1507 |
+
return_dict=return_dict,
|
1508 |
+
)
|
1509 |
+
|
1510 |
+
sequence_output = outputs[0]
|
1511 |
+
|
1512 |
+
sequence_output = self.dropout(sequence_output)
|
1513 |
+
logits = self.classifier(sequence_output)
|
1514 |
+
|
1515 |
+
loss = None
|
1516 |
+
if labels is not None:
|
1517 |
+
loss_fct = CrossEntropyLoss()
|
1518 |
+
# Only keep active parts of the loss
|
1519 |
+
if attention_mask is not None:
|
1520 |
+
active_loss = attention_mask.view(-1) == 1
|
1521 |
+
active_logits = logits.view(-1, self.num_labels)
|
1522 |
+
active_labels = torch.where(
|
1523 |
+
active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels)
|
1524 |
+
)
|
1525 |
+
loss = loss_fct(active_logits, active_labels)
|
1526 |
+
else:
|
1527 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
1528 |
+
|
1529 |
+
if not return_dict:
|
1530 |
+
output = (logits,) + outputs[2:]
|
1531 |
+
return ((loss,) + output) if loss is not None else output
|
1532 |
+
|
1533 |
+
return TokenClassifierOutput(
|
1534 |
+
loss=loss,
|
1535 |
+
logits=logits,
|
1536 |
+
hidden_states=outputs.hidden_states,
|
1537 |
+
attentions=outputs.attentions,
|
1538 |
+
)
|
1539 |
+
|
1540 |
+
|
1541 |
+
@add_start_docstrings(
|
1542 |
+
"""Bert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
|
1543 |
+
layers on top of the hidden-states output to compute `span start logits` and `span end logits`). """,
|
1544 |
+
BERT_START_DOCSTRING,
|
1545 |
+
)
|
1546 |
+
class BertForQuestionAnswering(BertPreTrainedModel):
|
1547 |
+
def __init__(self, config):
|
1548 |
+
super().__init__(config)
|
1549 |
+
self.num_labels = config.num_labels
|
1550 |
+
|
1551 |
+
self.bert = BertModel(config)
|
1552 |
+
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
|
1553 |
+
|
1554 |
+
self.init_weights()
|
1555 |
+
|
1556 |
+
@add_start_docstrings_to_callable(BERT_INPUTS_DOCSTRING.format("(batch_size, sequence_length)"))
|
1557 |
+
@add_code_sample_docstrings(
|
1558 |
+
tokenizer_class=_TOKENIZER_FOR_DOC,
|
1559 |
+
checkpoint="bert-base-uncased",
|
1560 |
+
output_type=QuestionAnsweringModelOutput,
|
1561 |
+
config_class=_CONFIG_FOR_DOC,
|
1562 |
+
)
|
1563 |
+
def forward(
|
1564 |
+
self,
|
1565 |
+
input_ids=None,
|
1566 |
+
attention_mask=None,
|
1567 |
+
token_type_ids=None,
|
1568 |
+
position_ids=None,
|
1569 |
+
head_mask=None,
|
1570 |
+
inputs_embeds=None,
|
1571 |
+
start_positions=None,
|
1572 |
+
end_positions=None,
|
1573 |
+
output_attentions=None,
|
1574 |
+
output_hidden_states=None,
|
1575 |
+
return_dict=None,
|
1576 |
+
):
|
1577 |
+
r"""
|
1578 |
+
start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):
|
1579 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
1580 |
+
Positions are clamped to the length of the sequence (`sequence_length`).
|
1581 |
+
Position outside of the sequence are not taken into account for computing the loss.
|
1582 |
+
end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):
|
1583 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
1584 |
+
Positions are clamped to the length of the sequence (`sequence_length`).
|
1585 |
+
Position outside of the sequence are not taken into account for computing the loss.
|
1586 |
+
"""
|
1587 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1588 |
+
|
1589 |
+
outputs = self.bert(
|
1590 |
+
input_ids,
|
1591 |
+
attention_mask=attention_mask,
|
1592 |
+
token_type_ids=token_type_ids,
|
1593 |
+
position_ids=position_ids,
|
1594 |
+
head_mask=head_mask,
|
1595 |
+
inputs_embeds=inputs_embeds,
|
1596 |
+
output_attentions=output_attentions,
|
1597 |
+
output_hidden_states=output_hidden_states,
|
1598 |
+
return_dict=return_dict,
|
1599 |
+
)
|
1600 |
+
|
1601 |
+
sequence_output = outputs[0]
|
1602 |
+
|
1603 |
+
logits = self.qa_outputs(sequence_output)
|
1604 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
1605 |
+
start_logits = start_logits.squeeze(-1)
|
1606 |
+
end_logits = end_logits.squeeze(-1)
|
1607 |
+
|
1608 |
+
total_loss = None
|
1609 |
+
if start_positions is not None and end_positions is not None:
|
1610 |
+
# If we are on multi-GPU, split add a dimension
|
1611 |
+
if len(start_positions.size()) > 1:
|
1612 |
+
start_positions = start_positions.squeeze(-1)
|
1613 |
+
if len(end_positions.size()) > 1:
|
1614 |
+
end_positions = end_positions.squeeze(-1)
|
1615 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
1616 |
+
ignored_index = start_logits.size(1)
|
1617 |
+
start_positions.clamp_(0, ignored_index)
|
1618 |
+
end_positions.clamp_(0, ignored_index)
|
1619 |
+
|
1620 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
1621 |
+
start_loss = loss_fct(start_logits, start_positions)
|
1622 |
+
end_loss = loss_fct(end_logits, end_positions)
|
1623 |
+
total_loss = (start_loss + end_loss) / 2
|
1624 |
+
|
1625 |
+
if not return_dict:
|
1626 |
+
output = (start_logits, end_logits) + outputs[2:]
|
1627 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
1628 |
+
|
1629 |
+
return QuestionAnsweringModelOutput(
|
1630 |
+
loss=total_loss,
|
1631 |
+
start_logits=start_logits,
|
1632 |
+
end_logits=end_logits,
|
1633 |
+
hidden_states=outputs.hidden_states,
|
1634 |
+
attentions=outputs.attentions,
|
1635 |
+
)
|