├── .gitignore ├── eval.txt ├── README.md ├── train.txt ├── run_language_model_bert.py ├── run_language_model_ernie.py └── run_language_model_roberta.py /.gitignore: -------------------------------------------------------------------------------- 1 | cached* 2 | ernie 3 | hflroberta 4 | runs 5 | wandb 6 | output 7 | -------------------------------------------------------------------------------- /eval.txt: -------------------------------------------------------------------------------- 1 | 所以注定我这辈子是做不了商人妈蛋 2 | 3 | 无论是心情多么低沉的夜晚,天光大亮后都是崭新的开始。 4 | 5 | 帽子怎么就变绿色幸好只是试一下 6 | 7 | 不想当个好人,好人的背后有多少的心酸害怕喝醉酒的人,害怕他们做出无法挽回的事情是真的会醉么?还是找个机会发泄出平时不敢说的话,不敢做的事呢,这样失控的人,真的很可怕2016.10.1晚上八点二十八分 8 | 9 | 一种爱是你可以为她去死;还有一种爱是得为你爱的人好好活着。 10 | 11 | 考了两次普通话,每次都离目标差一点点,就一点点!!要被气死了!! 12 | 13 | 尼玛吓死我了,人家剪个头发回来跟劳改犯一样短的可怕,后面什么鬼[黑线][黑线][黑线][白眼][白眼] 14 | 15 | 活在阴影里这么久,还不是出来的时候 16 | 17 | 小紧张~不过美美羊和圆圆媛要去看我表演,好开森啊! 18 | 19 | 感觉自己被一杯红茶玛奇朵给收买了不开心 20 | 21 | 你以为你是谁啊。就你这样的,,,,我也是醉了! 22 | 23 | 是安徽省规模较大的科技中介机构之一。 24 | 25 | 本标准由第七分会“书刊号标准化工作组负责起草。 26 | 27 | 这样折磨我真的好吗?为什么我背的题一道都不考,伐开心 28 | 29 | 一个人真无聊,美食都没味了,你要在就好了…唉……… 30 | 31 | 早上和妈妈生气,居然说,找个新妈妈 32 | 33 | 把孩子的涂鸦做成长毛绒玩具!一切来自一个真实的灵感:一位母亲把她四岁儿子的涂鸦做成长毛绒玩具。(via风过山) 34 | 35 | 这个村的年轻人大多数都出外打工。 36 | 37 | #linther说#以前,他从来不对我说晚安,就算每次我发了晚安,他只会回“拜”。今天,他主动说了“晚安”,我心里一惊,又觉得是不是自己想多了。 38 | 39 | 除此之外比较让我恐惧的就是,自己的智商是有限的,有的东西我可能一辈子都理解不了,但是却有人能够轻易的理解。就像看着自己怎么伸手都够不着的果实被别人轻易的摘去了一样。而且那里明明还有很多果实,我能看得到但是一辈子都够不着。想想真是让人害怕啊。不甘心也没有用,为什么我不是天才呢。 40 | 41 | 手机买了12天就降了300,摩托你的手机情怀呢? 42 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 基于pytorch的中文语言模型预训练 2 | ACL2020 Best Paper有一篇论文提名奖,《Don’t Stop Pretraining: Adapt Language Models to Domains and Tasks》。这篇论文做了很多语言模型预训练的实验,系统的分析了语言模型预训练对子任务的效果提升情况。有几个主要结论: 3 | * 在目标领域的数据集上继续预训练(DAPT)可以提升效果;目标领域的语料与RoBERTa的原始预训练语料越不相关,DAPT效果则提升更明显。 4 | 5 | * 在具体任务的数据集上继续预训练(TAPT)可以十分“廉价”地提升效果。 6 | 7 | * 结合二者(先进行DAPT,再进行TAPT)可以进一步提升效果。 8 | 9 | * 如果能获取更多的、任务相关的无标注数据继续预训练(Curated-TAPT),效果则最佳。 10 | 11 | * 如果无法获取更多的、任务相关的无标注数据,采取一种十分轻量化的简单数据选择策略,效果也会提升。 12 | 13 | 14 | 15 | 虽然在bert上语言模型预训练在算法比赛中已经是一个稳定的上分操作。但是上面这篇文章难能可贵的是对这个操作进行了系统分析。大部分中文语言模型都是在tensorflow上训练的,一个常见例子是中文roberta项目。可以参考 16 | https://github.com/brightmart/roberta_zh 17 | 18 | 19 | 使用pytorch进行中文bert语言模型预训练的例子比较少。在huggingface的Transformers中,有一部分代码支持语言模型预训练(不是很丰富,很多功能都不支持比如wwm)。为了用最少的代码成本完成bert语言模型预训练,本文借鉴了里面的一些现成代码。也尝试分享一下使用pytorch进行语言模型预训练的一些经验。主要有三个常见的中文语言模型 20 | * bert-base-chinese 21 | * roberta-wwm-ext 22 | * ernie 23 | 24 | ## bert-base-chinese 25 | 26 | (https://huggingface.co/bert-base-chinese) 27 | ​ 28 | 29 | 这是最常见的中文bert语言模型,基于中文维基百科相关语料进行预训练。把它作为baseline,在领域内无监督数据进行语言模型预训练很简单。只需要使用官方给的例子就好。 30 | 31 | https://github.com/huggingface/transformers/tree/master/examples/language-modeling 32 | (本文使用的transformers更新到3.0.2) 33 | ``` 34 | python run_language_model_bert.py --output_dir=output --model_type=bert --model_name_or_path=bert-base-chinese --do_train --train_data_file=train.txt --do_eval --eval_data_file=eval.txt --mlm --per_device_train_batch_size=4 35 | 36 | ``` 37 | 38 | ## roberta-wwm-ext 39 | 40 | (https://github.com/ymcui/Chinese-BERT-wwm) 41 | 42 | 43 | 哈工大讯飞联合实验室发布的预训练语言模型。预训练的方式是采用roberta类似的方法,比如动态mask,更多的训练数据等等。在很多任务中,该模型效果要优于bert-base-chinese。 44 | 因为中文roberta类的配置文件比如vocab.txt,都是采用bert的方法设计的。英文roberta模型读取配置文件的格式默认是vocab.json。对于一些英文roberta模型,倒是可以通过AutoModel自动读取。这就解释了huggingface的模型库的中文roberta示例代码为什么跑不通。https://huggingface.co/models? 45 | 46 | 47 | 如果要基于上面的代码run_language_modeling.py继续预训练roberta。还需要做两个改动。 48 | * 下载roberta-wwm-ext到本地目录hflroberta,在config.json中修改“model_type”:"roberta"为"model_type":"bert"。 49 | * 对上面的run_language_modeling.py中的AutoModel和AutoTokenizer都进行替换为BertModel和BertTokenizer。 50 | 51 | 假设config.json已经改好,可以运行如下命令。 52 | ``` 53 | python run_language_model_roberta.py --output_dir=output --model_type=bert --model_name_or_path=hflroberta --do_train --train_data_file=train.txt --do_eval --eval_data_file=eval.txt --mlm --per_device_train_batch_size=4 54 | ``` 55 | 56 | ### ernie 57 | https://github.com/nghuyong/ERNIE-Pytorch) 58 | 59 | ernie是百度发布的基于百度知道贴吧等中文语料结合实体预测等任务生成的预训练模型。这个模型的准确率在某些任务上要优于bert-base-chinese和roberta。如果基于ernie1.0模型做领域数据预训练的话只需要一步修改。 60 | 61 | * 下载ernie1.0到本地目录ernie,在config.json中增加字段"model_type":"bert"。 62 | 运行 63 | ``` 64 | python run_language_model_ernie.py --output_dir=output --model_type=bert --model_name_or_path=ernie --do_train --train_data_file=train.txt --do_eval --eval_data_file=eval.txt --mlm --per_device_train_batch_size=4 65 | 66 | ``` 67 | -------------------------------------------------------------------------------- /train.txt: -------------------------------------------------------------------------------- 1 | 所以注定我这辈子是做不了商人妈蛋 2 | 3 | 无论是心情多么低沉的夜晚,天光大亮后都是崭新的开始。 4 | 5 | 帽子怎么就变绿色幸好只是试一下 6 | 7 | 不想当个好人,好人的背后有多少的心酸害怕喝醉酒的人,害怕他们做出无法挽回的事情是真的会醉么?还是找个机会发泄出平时不敢说的话,不敢做的事呢,这样失控的人,真的很可怕2016.10.1晚上八点二十八分 8 | 9 | 一种爱是你可以为她去死;还有一种爱是得为你爱的人好好活着。 10 | 11 | 考了两次普通话,每次都离目标差一点点,就一点点!!要被气死了!! 12 | 13 | 尼玛吓死我了,人家剪个头发回来跟劳改犯一样短的可怕,后面什么鬼[黑线][黑线][黑线][白眼][白眼] 14 | 15 | 活在阴影里这么久,还不是出来的时候 16 | 17 | 小紧张~不过美美羊和圆圆媛要去看我表演,好开森啊! 18 | 19 | 感觉自己被一杯红茶玛奇朵给收买了不开心 20 | 21 | 你以为你是谁啊。就你这样的,,,,我也是醉了! 22 | 23 | 是安徽省规模较大的科技中介机构之一。 24 | 25 | 本标准由第七分会“书刊号标准化工作组负责起草。 26 | 27 | 这样折磨我真的好吗?为什么我背的题一道都不考,伐开心 28 | 29 | 一个人真无聊,美食都没味了,你要在就好了…唉……… 30 | 31 | 早上和妈妈生气,居然说,找个新妈妈 32 | 33 | 把孩子的涂鸦做成长毛绒玩具!一切来自一个真实的灵感:一位母亲把她四岁儿子的涂鸦做成长毛绒玩具。(via风过山) 34 | 35 | 这个村的年轻人大多数都出外打工。 36 | 37 | #linther说#以前,他从来不对我说晚安,就算每次我发了晚安,他只会回“拜”。今天,他主动说了“晚安”,我心里一惊,又觉得是不是自己想多了。 38 | 39 | 除此之外比较让我恐惧的就是,自己的智商是有限的,有的东西我可能一辈子都理解不了,但是却有人能够轻易的理解。就像看着自己怎么伸手都够不着的果实被别人轻易的摘去了一样。而且那里明明还有很多果实,我能看得到但是一辈子都够不着。想想真是让人害怕啊。不甘心也没有用,为什么我不是天才呢。 40 | 41 | 手机买了12天就降了300,摩托你的手机情怀呢? 42 | 43 | 形成的土壤为潮沙泥和潮沙泥田。 44 | 45 | 卧槽!!!!!!禽兽!!!!!!!! 46 | 47 | 为什么老师看见我的桌面会问我:“你平时是不是打游戏?” 48 | 49 | 棉花一枝独秀?难道看不见服装业的形势? 50 | 51 | 前身为始建于1892年的“宽仁医院。 52 | 53 | 最近追三国演义,曹操要刺杀董卓,关键时刻吕布突然进来,曹操转势跪献宝刀,吓一头脑袋汗,这个演技我给后来刺杀收留他的吕伯奢一家看的心惊 54 | 55 | 【女生健康睡眠】女生一旦晚睡早起,生活作息就会严重违背生物钟,易成为慢性失眠。有睡眠问题的女生是男生的1.5倍,有慢性失眠问题的女生是男生的1.3倍。睡不好的女生常有脑中风心血管疾病的患病风险。女生每天最好睡足8小时,不要少于6小时。中午最好休息半小时到1小时。晚上最好10时左右睡觉。 56 | 57 | 从听《callmemabye》到现在,今天第一次看歌曲的MV,拍的很唯美,女主很小清新,男主很阳光很帅气,but,最后的结局却是:那么迷人好看的男主,他callmemabye的对象竟然是乐队的吉他手,他喜欢的是男的。 58 | 59 | 过了太久安逸的生活了,被最近一系列的国际大事惊呆了,这是什么节奏 60 | 61 | 5月22日上午9:00——10:30,申报高中、中职、实习指导教师资格人员教育教学能力测试笔试; 62 | 63 | 想自己装个软件,咋这难呢??想骂人 64 | 65 | 加州最有名的意面,披萨,居然也要排队,蒜香虾球面,宫爆虾球面,好吃 66 | 67 | 真是火大做了一遍乱码白做重做又乱码破系统能不能不闹 68 | 69 | 似乎又被禁言了渣浪你想怎样,我的vip是白开的吗? 70 | 71 | 心里好烦好烦好烦好烦你们不熟你妹啊那你上课的干嘛跟她讲话卧槽靠靠靠!烦死了还笑那么开心我去你大爷你怎么跟她不熟了我靠 72 | 73 | 我没有你们那种与生俱来的自信…也或许曾经有过…? 74 | 75 | 到海关办了退运,花了286,肉疼 76 | 77 | 看完恐怖片才意思到自己是一个人睡旅馆,楼道隔音不好能听到脚步声,楼下还有那种服务,害怕到没有困意 78 | 79 | 谢谢honey们帮我庆祝生日!!!谢谢你们的祝福,谢谢身边的所有人!爱你们 80 | 81 | 一到下雨天就莫名的惆怆,下一秒情绪就完全奔溃,闭着眼睛忍不住的流眼泪,这种情绪陪伴自己已经有一年半了。我想哪种心酸,委屈,无力辩解,和深深的遗憾只有这淅淅沥沥的雨声知道 82 | 83 | 熬到了天亮,好神奇一点睡意都没有 84 | 85 | 终于………以前都是在上面的😂👆柔板跟催眠曲似的,豆说他弹的速度比她数钱还快 86 | 87 | 感觉很不好,需要音乐平复我躁动的内心!😖😖😖 88 | 89 | 2011.11.24,11:58分,《垫底辣妹》里最后因为一向被自己忽视小看的女儿考试了梦想中的大学,爸爸背起女儿....我竟然想大喊一声:你如果此刻冲到我面前来找我我就原谅你.....呵呵... 90 | 91 | 全场比赛结束,阿森纳3:0战胜萨格纳布迪纳摩,桑切斯闪耀全场,接下来欧冠最后一场生死战,让我们去希腊赢两球或者3:2的比分 92 | 93 | 一觉醒来你发现你梦到的人身边不是你你的未来也不会有他心里的一阵失落感和难受就会升起 94 | 95 | 而起关键是在燃油的精确配置和废气的后置处理,各多的电子新科技将运用到新一带柴油机上。 96 | 97 | 纯君也在玩touken的节奏? 98 | 99 | 只想说,有些人完全不懂什么叫人情味,既然你不懂人情味,也枉费做一个人,那么我也就不用把你当人看,尼玛,心塞,是很塞 100 | 101 | 1986年在遗传病研究中,张乃赓新发现了6种8例遗传病,获黑龙江省计划生育委员会遗传病研究一等奖,并获黑龙江省科技进步三等奖。 102 | 103 | 为啥子都喜欢赶在中午饭点过来啊啊啊,你们午休能不能也让我们歇会 104 | 105 | 字迹潦草却不失内涵,宿舍不拔插线板写的检讨大二的我们身不由己呀,真心不知道怎么写 106 | 107 | 更年期的女boss真的让人受不了,烦躁 108 | 109 | 今天晚上给别人写推优的什么东西,还有选修课,明天晚上要交的物理实验数据还没处理,周六要考综合交通,没复习,还正好是物理演示实验的那天,还有一个月考四级,没怎么背英语,听课听不进去,跑步停了半个月了,锻炼虽然一直在做着,但是晚上开始吃了,负能量爆棚,真糟糕 110 | 111 | 第二十一条??严禁弃婴、溺婴、非法收养子女。 112 | 113 | 空闲时间太多,就会胡思乱想,以至于唤醒了心中的彷徨。 114 | 115 | 老舍《黑白李》:“黑李是我的好友,因为常到他家去,所以对白李的事儿我也略知一二。 116 | 117 | 阳气就是阳清之气,阴阳二气混杂从而化育了万物。 118 | 119 | 永远在变的计划,你什么时候能让我追上你!!!! 120 | 121 | 吃个宵夜而已嘛你就开始痛痛痛了.6点还要起床.我只想安安静静睡个觉.乖!不要折磨我了呵. 122 | 123 | 听得太多命中注定,看来得准备自己一个人好好过了……一切是好是坏我都欣然面对! 124 | 125 | 这支DirtySouth名团组建于1991年,全部团员来自佐治亚州首府亚特兰大市,成员分别为Cee-Lo、Khujo、T-Mo和BigGipp等四人。 126 | 127 | 梦见某国发现某病毒强化人体,收集了一批志愿者和选中的军人来试验,不行的会被淘汰。病毒感染的人对宿主会天然有好感,但是满足宿主条件的很少,好容易集齐了所有条件找到了一个人,但要很残酷的全部打碎重组,然后经过强化宿主和被病毒感染的人的关系就可以组建一支绝对服从的强大军队。 128 | 129 | 换季降温也想美美的?一条围巾就足够啦!小法为大家普及几种冬天最常用的厚围巾的系法,赶快叫着小伙伴,一起get√起来吧! 130 | 131 | 我竟然才知道我有一个富二代加官二代加红二代的朋友 132 | 133 | 画个圈圈诅咒你!(臭老头)脏鬼! 134 | 135 | 一早起来陪伴自己3年的那根笔居然不见了真心是找不到了 136 | 137 | 全村辖1个村民小组,其中从事第一产业人数110人。 138 | 139 | 一首摇篮曲搞定一个吃货,那也是神了 140 | 141 | 小区取缔垃圾桶,以后没有大爷来每天收拾两次垃圾桶了,我好怀念收垃圾的大爷,有大爷的日子垃圾想扔就扔 142 | 143 | 两个班的差别怎么辣么大一天给你们上课焦死人 144 | 145 | @新浪微博你个碧池,设置的什么破功能,不是说好的仅自己可见吗?tellmewhy?你个碧池! 146 | 147 | 天阴下雨,浑身酸疼的赶脚,不喜欢 148 | 149 | 开会开到现在,饿成🐶了,我想妈妈 150 | 151 | 总是忙忙叨叨到现在,但是泡过脚之后睡觉真的很舒服。昨天晚上梦见二肥,我很想你,陪我一起长大的你,在那边要好好的。 152 | 153 | 我也不太懂为啥要保持最坏的打算,担惊受怕过三年,并且担忧越来越强烈。希望结果出现的时候,不会影响正常的生活。 154 | 155 | 不是抱怨。而是根本想去拿着所有东西摔他脸上告诉他你妈逼啊!卧槽! 156 | 157 | 今天又拔出这么多白发,我还年轻离我远点 158 | 159 | 每一个管理者都可以对照拉伯福所说的这十种错误,举一反三,验照一下自己是不是犯过类似的错误。 160 | 161 | 现在的警察都是这样办事的么?! 162 | 163 | 看了多篇报道,有植入广告嫌疑,西方人能干得出来? 164 | 165 | 胖了胖了胖了,怎么才可以不受美食的诱惑。真的胖了 166 | 167 | 改变命运的时候来了,可惜不够分,有点失落 168 | 169 | 今天是宝小姐第一次,参加学校举行的“万圣节”…看来玩的好开心 170 | 171 | 真的很后悔以前的微博都删了好多东西都找不回来仅剩一些残余的记忆 172 | 173 | [婴儿]#Day98#第一次摔下床,现在还心有余悸。并没有一直哭,哄一会吃完奶就睡着了。看着满脸蚊子包熟睡的你,真是后悔,心疼!这是第一次一定也是最后一次。 174 | 175 | 我的神哦,还好我不但不泡脚,而且从来不洗脚赶紧泡会压压惊 176 | 177 | 今天是个倒霉的日子………………… 178 | 179 | 如果把信息发给接受不到的对方,可以很直接,不用这么纠结 180 | 181 | 外国学者称它为“中国17世纪的工艺百科全书。 182 | 183 | 月华寒子夜,更漏待天明。梦中忽觉醒,回寰一息中。 184 | 185 | 典型的外在报酬为经济薪酬,即货币薪酬。 186 | 187 | 做这道菜的心里过程:在菜场看的时候,它们一个个喷着水撒欢,买回家清洗的时候它们都害怕地紧闭着盔甲,由于泥太多,我用力清洗时发现把一个壳弄碎了,觉得它们好可怜~炒的时候很纠结,把它们一个个炒死了~他们有没有神经系统啊?但熟的时候闻到香味我就忘了它们生前的所有,人类好可怕 188 | 189 | 看了几日的视频教程终于狠下心安静的去织了感觉还挺不错的妈妈老公都说还不错心里挺开心 190 | 191 | 做过的选择极少给你回过头更改的机会,又没勇气抛下所有另辟一蹊径,只得努力奋斗,使最初的选择变成正确。 192 | 193 | 如果哪位有幸考中了第一名状元,不仅能得到高官厚禄,还可以名扬天下。 194 | 195 | 1906年转入镇平县立第一高等小学堂,次年,考入县立师范传习所。 196 | 197 | 特么即participation后,reflectivewriting成为了我最恶心的体裁1000的反思花了我四天天天检讨才憋完…… 198 | 199 | 万历十七年受封世子,天启元年,袭封周王。 200 | 201 | 自己买的东西冒着雨也要拿回来,要走那么远内心是崩溃的 202 | 203 | 我就想问一下@杭州市民卡你们是怎么做到过去一周不管什么时候打你们客服电话都是“服务代表正忙”的忙音。 204 | 205 | 刚刚上床,肩膀ba了一声,感觉整个左肩都不好了疼 206 | 207 | 从以前到现在都是这样,会恐惧将来发生的事,会恐惧将来对那个时间的否定。会害怕自己的麻木。即使回过头去想以前的事,并没有什么。但是现在当前的时间点上,让我去想将来会冷漠的看这样的自己,让我害怕不已。 208 | 209 | 想吃什么的时候正好能吃到这一定是世界上最幸福的事情之一 210 | 211 | 在他们喜闻乐见的环境中引导他们!鼓舞他们向那些真善美学习、这样我们的国家!我们的民族,我们这一代的大学生才是有希望的! 212 | 213 | 看完后,怎么会有这么大胆女孩,恐怖[惊恐]!这个个社会,真的什么人都有。不能随便发定位这些了!好恐怖! 214 | 215 | 网又没了,又在挂流量,要崩溃。 216 | 217 | 妈蛋的TB坑爹的无良商家!挣黑心钱也不怕遭雷劈!怎么说都不理人!给我气不行了! 218 | 219 | 就这样,我三个月来的纠结和痛苦就这么过去了。回头看的时候,依然还是心有余悸。一路艰辛,终得其所,虽不是如愿以偿,但已尽力,自己努力无愧于心,但深得教训。此事为今后之参照,愿再接再厉! 220 | 221 | 耳边听着“不要告别”,又想起了五六月的武汉,空气是潮湿的,也是人心惶惶的,太多人要离开,要告别,我也在惴惴不安和不舍中离开,现在想来在武汉的两年是最自由的,又想到了璐璐和黑学霸…… 222 | 223 | 说好的起来看书,一觉过午。饥肠辘辘煮面,发现没盐了,等了半天面还没熟,原来跳闸了,重新来过等,还没熟,奥,原来插头掉了…我顶!老子他妈不吃了 224 | 225 | 安静的可怕,这个时候应该看个恐怖片[惊恐] 226 | 227 | 又停电fuck有多少事都我不能干了 228 | 229 | 事实证明,十一过后我就拆蚊帐是多么的错误!这几天没一天睡好的,平均每晚都要三四个蚊子,谁家像我们这么多啊?家里会不会有蚊子窝?我认输了,明天重新把蚊帐装上今晚这个我还没找到,关灯就嗡嗡,抓狂死了 230 | 231 | 你看到是世界都是被包装过的,就像纳尼亚传奇里白皇后变出热奶茶和巧克力,最后都化作一团冰凉的白雪。大家说着言不由衷的话,口是心非的说他们爱你,支持你。却又在心里偷偷地埋怨你。就是这样的吧。 232 | 233 | 每次回忆起来都是满满的温暖和感动 234 | 235 | @苑洛fover婧祺说:“你是弯的!”我没反应过来:“啊?”然后顺着她指得方向一看,原来是月亮 236 | 237 | 10月才刚刚开始,已经给2017年预约了三件大事。在日本似乎习惯了一切提前安排,似乎计划让我们的生活丰富多彩并井井有条,但有时也会有些小迟疑想想它是不是真的好,拖拉时间向前的同时,不免也有种惧怕被时间碾轧的小恐惧。 238 | 239 | 快速化解愤怒的是与愤怒不相干的工作。工作,没有感情色彩,客观存在,可以集中注意力,也可以消耗体力…… 240 | 241 | 一回到寝室就开始做ppt!我真是要崩溃了!脑袋里的想法那么好,为什么就是做不出来呢!先是一个技术问题,搞了三四个小时解决后,又找不到合适的图!我真的心好累!痘痘都长一脸了明天我就是不吃不喝不睡也要把ppt做出来!再求有没有人有眼睛鼻子嘴巴耳朵头发特征明显的卡通图🙏 242 | 243 | 12月乌鲁木齐市环保局和市教育局命名乌鲁木齐市第二十三中学为“市级绿色学校。 244 | 245 | 圆通快递,暴力运送!都成这样了,竟然说没有当面验收,完全在推脱责任! 246 | 247 | 《小萝莉的猴神大叔》国界之门打开那一刻什么宗教国家矛盾统统靠边站感情不分国界特别感人的电影好看就是了👉 248 | 249 | 物流显示已经签收。可我没有收到阿。去小区物管也没看到。打电话没人接。几个意思。 250 | 251 | 人间土味好可怕恐怖看到这种东西就不想结婚但是根据什么垃圾配什么垃圾桶的原则我觉得我也不可能和这种人结婚但是我还是很震撼我要去看钱困困微博缓解一下 252 | 253 | 白天鹅(海盗旗)出击…下一次不会把伊斯坎德尔甚至白杨搞出来吧… 254 | 255 | 我大概1月9、10号左右回家,越来越近了。老公,好爱你啊 256 | 257 | 1公司位置??公司logo??单开纱窗主要产品:I、隐形纱窗、纱门。 258 | 259 | 现在出去都没脸跟别人说我是火箭球迷了!!!。。。😞 260 | 261 | 14、洛那类风湿性关节炎、骨性关节炎、腰痛、肩周炎、颈肩腕综合症,以及手术后、外伤后及拔牙后的镇痛消炎,急性上呼吸道炎症的解热镇痛。 262 | 263 |   商业票据出票人(DRAWER)出票人是签发票据并将票据交付给他人的人。 264 | 265 | 广东人热冬伤不起,求2000块买台空调 266 | 267 | 今晚只能在厕所度过了?闹肚子闹肚子闹肚子大晚上的 268 | 269 | 这一定是exo专供烤肉店,一次两次广告都不用了,😭一点都不羡慕 270 | 271 | 裴娜从孙培处得知自己的体检结果里居然有孕检一项,大惊,认定是丑女们故意要出她的丑,假装要跟吴庸坦白,从马莎莎手里骗回了体检单。 272 | 273 | 饭上金菠萝后的第一个生日开心!碎觉啦!鸟宝宝们晚安 274 | 275 | 昨晚上那只很大的蜘蛛吓坏我了,一时手软没打着不知藏到那去了,现在睡觉都有阴影了,床和边边都翻了几遍,应该走了吧 276 | 277 | 柳如烟只好找些助孕的偏方来吃,果然象怀上了。 278 | 279 | 昨晚和老妈生气,今早接到学生电话说错过了考试时间一直担心中午赶车摔倒水坑里脚崴了我的玫瑰金屏幕也碎了我想知道我还能承受多少。 280 | 281 | 看得多了,心也大了,好的不珍惜,差的舍不得放弃,矛盾纠结,感觉什么也感动不了我,怎么会变得那么狠心😔对自己好失望,再也回不到原来的我了 282 | 283 | 初见台北~国父纪念馆、台北101、诚品书店的一天~结果,就在刚刚半小时前,就地震了!可吓死姐了…躺在酒店床上好好的,顿时感觉怎么晃的那么厉害!长那么大第一次感受这么可怕的晃动,可怕!谁能报道出台湾的地震问题…我看看这是几级地震?|台湾 284 | 285 | 晒晒儿子照片,第一次发,多多关照 286 | 287 | 减肥,,,减肥,?(不能再吃了,死胖子) 288 | 289 | [喵喵][喵喵][喵喵]最后一个最可怕[泪]吓哭了太吓人了 290 | 291 | 【旅途日志】人在旅途,真理往往是简捷明了的,只是由于心灵受到尘埃的蒙蔽,使得简单的道理变得复杂起来,一旦想通了,明白了,人生之旅就不会左顾右盼、茫然不知所措了。屈原在《离骚》中感叹到:路漫漫其修远兮,吾将上下而求索。世界太大,生命太短,如果不导演好自己,怎能悟透人生的意义? 292 | 293 | 晚上八点睡着,感觉睡了一个世纪,她妈的一睁眼才12点,睡不着了 294 | 295 | 我去~骗子的手段太高明了,你跟我谈法律,你还不知道我是干嘛的吧,小心点,我警告你,别惹火了我(大家小心点,千万别上当) 296 | 297 | 工作太认真了竟然忘了吃饭时间,现在肚子咕咕叫,只能出来觅食了 298 | 299 | 最近净遇到点sb真是日了tm了 300 | 301 | 正所谓“十指痛归心”,谁能感受这N+1只草泥马在奔腾的感觉? 302 | 303 | 土都吃不起的少女只想要1500块钱把花呗还上-.- 304 | 305 | 老公说只要我每天过的开心快乐就好,他养我,听了心里好感动,当他把工资卡给我的时候说,宝贝你想买什么就买,我的心里美美哒 306 | 307 | 憋屈的事情,劳心劳力的你以为我很愿意? 308 | 309 | 复制另一个人,复制所有的性格却没有情感和记忆,轻蔑地看着过去的自己,还有我 310 | 311 | 人若看清和明白自己的处境,就只能承担的,即使心里有一种畏惧,对着萧瑟的,对黑暗与幽闭的恐惧,也要承担着它,回到自己的使命中。有骨骼的哀伤,那等同于一种自我克制。 312 | 313 | 它们分泌一种液体给蚁吃,而蚁餵养它们作为回报。 314 | 315 | 弘光时监生,隆武帝赐姓朱、号“国姓爷。 316 | 317 | 各部门职能明确,在相对独立基础上通力合作,以促进本协会健康向上发展,统一管理协会事务,受会员监督。 318 | 319 | 你真正喜欢想要的,没有一样,是可以轻易得到的。这就是努力的理由。 320 | 321 | 烦,今天路上怎么这么堵,动都不动!!! 322 | 323 | HCG即人绒毛膜促性腺激素,是受孕妇女妊娠期由胎盘产生的一种糖蛋白,可通过肾小球从尿液中排出。 324 | 325 | 最霉的一天!换班换班!有本事你去买辆车啊!每次我跑腿!还是绕远路!每次一换班心情就不爽!弄的好像我理所当然一样! 326 | 327 | 感觉很惶恐害怕自己控制不住想从窗口跳下去无牵无挂一了百了 328 | 329 | 大半夜的为什么要看家乡小吃...现在又饿又想家 330 | 331 | 为什么出门不带钥匙为什么出门不带钥匙为什么出门不带钥匙 332 | 333 | 话说原来楼下装修不是入住而是要出售 334 | 335 | 这是同一只脚么,怎么变化这么大? 336 | 337 | 我靠我该怎么做才能解气贱人年年有今年特别多真的是够了 338 | 339 | 医院现有在职职工1300人,其中医技人员占80%,高级专业技术人员110多人,中级专业技术人员近500人。 340 | 341 | 今天老妈回家去参加她老同学的婚礼回来跟我说看看人家都结婚了你还天天赖在家我说这催婚吗不急不急妈该找了呀我说我怎么找啊大街上随便抓一个能行吗妈能抓就抓吧(亲妈呀你好开明)妈呀这个急不得要不然你问问你女婿杨洋 342 | 343 | 起床真的是无比艰难的一件事本来,考翻译也没什么好复习的,可是这次偏偏要考中外翻译史中的人物。整本书那么多人物,其实我也不知道会考哪三个,但是我真的是不会甘心放弃掉那30分呢继续背书去了,说不定就押到了呢… 344 | 345 | 刚才写了篇长篇日志,内容非常精彩,点发送的时候,麻痹手欠了...点错了...没啦就。 346 | 347 | 你要走就走得再远一点吧。我不怕你从别人那里获得新的快乐了,可是我怕你再回一回头。 348 | 349 | 负能量爆棚了感觉要炸了..怎么他妈的还在原地踏步 350 | 351 | 大概是我妈get的拍照新技能。我还以为是我从162奔向了165 352 | 353 | 陌陌号被禁言,是有人举报我了么,谁能告诉我 354 | 355 | 骗子的技俩,你信一成你都会倾家荡产这是绝对真实的实例发生在我身上有一天有一个自称是外国的将军加了我有一天他说他儿子在非洲旅行说他儿子没有零用钱了他那边也没法去银行会账给他儿子叫我寄钱给他儿子请大家警惕 356 | 357 | 人生如戏,如今场景已经布置好了,主角却已不在了 358 | 359 | 火大~火大~奇葩一枚。自己态度不好,还需要别人对你态度好吗? 360 | 361 | 王弼注:“阳气始剥尽至来复,时凡七日。 362 | 363 | 不刮风不下雨运动会为什么要延期,狗逼学校收钱怎么不延期 364 | 365 | 血糖低导致体质下降,体重也直速的下降 366 | 367 | 我原本计划好好的调时差贱洋又他妈来把我弄醒催我起床吃东西然后我吃完他就呼呼大睡了 368 | 369 | 我做过最疯狂的事就是勇敢和你在一起 370 | 371 | 跟我说句话跟我说句话跟我说句话能死吗 372 | 373 | 下雨打不到车挤不上公交提N多东西边走边掉妈蛋都去死 374 | 375 | 我没救了,纸媒老大,自打进门起就一直无视他,一直无视,一直无视,跟我说话也爱理不理,今天才知道他是老大,他是老大,他是老大 376 | 377 | 此刻让我最抓狂的事是有人在你身边吃东西吃的那个吧唧吧唧吧唧吧唧吧唧吧唧吧唧吧唧吧唧吧唧吧唧吧唧吧唧吧唧吧唧吧唧啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊受不了了想揍人😣😲✊✊✊抓狂的要死这种声音真心的听着难受,抓狂,想扁人 378 | 379 | 和真爱在一起各种搞怪,怎么舒服怎么来! 380 | 381 | 看你躺在怀里,不由想起你刚来我身边时的场景,未满两个月的你巴掌大的你好小好小,第一次养小奶狗什么都不懂,带着你去宠物店让你在地上走着一边叫着你怕你跑丢一边跟着你怕你有事,就那样跟了你一路笑了一路就感觉真的好搞笑,走哪都特别吸引目光,到宠物店了才知道你太小不能出门…有你真好 382 | 383 | 晋陶潜《杂诗》之三:“严霜结野草,枯悴未遽央。 384 | 385 | 记得小时候,爸妈总是在八九点钟,电视剧还没看完的时候,就催促我们去准备上床睡觉,然后小时候的我们,因为害怕还不能违抗父母,哪怕心里一百万个不愿意也会乖乖上床,把眼睛闭上。这一觉啊,没有噩梦,没有思念的人,没有被眼泪弄湿的枕头,可是,那样的日子,再也回不去了。 386 | 387 | 傻逼啊,我是惯着你,还是直接呼你脸啊 388 | 389 | 想剪短发又想留长发,女人真是个矛盾的生物体😔😔 390 | 391 | 嗅出了一丝东的寒意所以童鞋一定要把自己弄得暖和一点LoveYou!MH 392 | 393 | 这其中,以巴巴多斯进入发达国家行列的意义最为重大,因为它成为拉丁美洲第一个发达国家,也是第一个以黑人为主体的发达国家。 394 | 395 | 这课上的要疯了wuliaohehe 396 | 397 | 我今天才知道,原来我家是卖牙膏的 398 | 399 | 困得蒙瞪的,一下子就气清醒了,what'sthefuck! 400 | 401 | 尝新,我说的是杯子。设计感和质感都超级好。贵,但有它的价值。 402 | 403 | SR型具有出色的错误消除能力,可以直接安装在飞机地板上,简化了组装工作。 404 | 405 | 一个月内剪两次发!只因上次的垃圾所谓总监把发剪得太难睇了! 406 | 407 | 我是69年的,69年的,69年的。说三遍。领导们又把我师弟说成师兄,把我搞成青年委员……说好的青年委员起码70后好不好……长的年轻居然有这样的劣势!无语…… 408 | -------------------------------------------------------------------------------- /run_language_model_bert.py: -------------------------------------------------------------------------------- 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 | """ 17 | Fine-tuning the library models for language modeling on a text file (GPT, GPT-2, CTRL, BERT, RoBERTa, XLNet). 18 | GPT, GPT-2 and CTRL are fine-tuned using a causal language modeling (CLM) loss. BERT and RoBERTa are fine-tuned 19 | using a masked language modeling (MLM) loss. XLNet is fine-tuned using a permutation language modeling (PLM) loss. 20 | """ 21 | 22 | 23 | import logging 24 | import math 25 | import os 26 | from dataclasses import dataclass, field 27 | from typing import Optional 28 | 29 | from transformers import ( 30 | CONFIG_MAPPING, 31 | MODEL_WITH_LM_HEAD_MAPPING, 32 | AutoConfig, 33 | AutoModelWithLMHead, 34 | AutoTokenizer, 35 | DataCollatorForLanguageModeling, 36 | HfArgumentParser, 37 | LineByLineTextDataset, 38 | PreTrainedTokenizer, 39 | TextDataset, 40 | Trainer, 41 | TrainingArguments, 42 | set_seed, 43 | ) 44 | 45 | 46 | logger = logging.getLogger(__name__) 47 | 48 | 49 | MODEL_CONFIG_CLASSES = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) 50 | MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) 51 | 52 | 53 | @dataclass 54 | class ModelArguments: 55 | """ 56 | Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch. 57 | """ 58 | 59 | model_name_or_path: Optional[str] = field( 60 | default=None, 61 | metadata={ 62 | "help": "The model checkpoint for weights initialization. Leave None if you want to train a model from scratch." 63 | }, 64 | ) 65 | model_type: Optional[str] = field( 66 | default=None, 67 | metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)}, 68 | ) 69 | config_name: Optional[str] = field( 70 | default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"} 71 | ) 72 | tokenizer_name: Optional[str] = field( 73 | default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} 74 | ) 75 | cache_dir: Optional[str] = field( 76 | default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"} 77 | ) 78 | 79 | 80 | @dataclass 81 | class DataTrainingArguments: 82 | """ 83 | Arguments pertaining to what data we are going to input our model for training and eval. 84 | """ 85 | 86 | train_data_file: Optional[str] = field( 87 | default=None, metadata={"help": "The input training data file (a text file)."} 88 | ) 89 | eval_data_file: Optional[str] = field( 90 | default=None, 91 | metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."}, 92 | ) 93 | line_by_line: bool = field( 94 | default=False, 95 | metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."}, 96 | ) 97 | 98 | mlm: bool = field( 99 | default=False, metadata={"help": "Train with masked-language modeling loss instead of language modeling."} 100 | ) 101 | mlm_probability: float = field( 102 | default=0.15, metadata={"help": "Ratio of tokens to mask for masked language modeling loss"} 103 | ) 104 | plm_probability: float = field( 105 | default=1 / 6, 106 | metadata={ 107 | "help": "Ratio of length of a span of masked tokens to surrounding context length for permutation language modeling." 108 | }, 109 | ) 110 | max_span_length: int = field( 111 | default=5, metadata={"help": "Maximum length of a span of masked tokens for permutation language modeling."} 112 | ) 113 | 114 | block_size: int = field( 115 | default=-1, 116 | metadata={ 117 | "help": "Optional input sequence length after tokenization." 118 | "The training dataset will be truncated in block of this size for training." 119 | "Default to the model max input length for single sentence inputs (take into account special tokens)." 120 | }, 121 | ) 122 | overwrite_cache: bool = field( 123 | default=False, metadata={"help": "Overwrite the cached training and evaluation sets"} 124 | ) 125 | 126 | 127 | def get_dataset(args: DataTrainingArguments, tokenizer: PreTrainedTokenizer, evaluate=False): 128 | file_path = args.eval_data_file if evaluate else args.train_data_file 129 | if args.line_by_line: 130 | return LineByLineTextDataset(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size) 131 | else: 132 | return TextDataset( 133 | tokenizer=tokenizer, file_path=file_path, block_size=args.block_size, overwrite_cache=args.overwrite_cache 134 | ) 135 | 136 | 137 | def main(): 138 | # See all possible arguments in src/transformers/training_args.py 139 | # or by passing the --help flag to this script. 140 | # We now keep distinct sets of args, for a cleaner separation of concerns. 141 | 142 | parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) 143 | model_args, data_args, training_args = parser.parse_args_into_dataclasses() 144 | 145 | if data_args.eval_data_file is None and training_args.do_eval: 146 | raise ValueError( 147 | "Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file " 148 | "or remove the --do_eval argument." 149 | ) 150 | 151 | if ( 152 | os.path.exists(training_args.output_dir) 153 | and os.listdir(training_args.output_dir) 154 | and training_args.do_train 155 | and not training_args.overwrite_output_dir 156 | ): 157 | raise ValueError( 158 | f"Output directory ({training_args.output_dir}) already exists and is not empty. Use --overwrite_output_dir to overcome." 159 | ) 160 | 161 | # Setup logging 162 | logging.basicConfig( 163 | format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", 164 | datefmt="%m/%d/%Y %H:%M:%S", 165 | level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, 166 | ) 167 | logger.warning( 168 | "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s", 169 | training_args.local_rank, 170 | training_args.device, 171 | training_args.n_gpu, 172 | bool(training_args.local_rank != -1), 173 | training_args.fp16, 174 | ) 175 | logger.info("Training/evaluation parameters %s", training_args) 176 | 177 | # Set seed 178 | set_seed(training_args.seed) 179 | 180 | # Load pretrained model and tokenizer 181 | # 182 | # Distributed training: 183 | # The .from_pretrained methods guarantee that only one local process can concurrently 184 | # download model & vocab. 185 | 186 | if model_args.config_name: 187 | config = AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir) 188 | elif model_args.model_name_or_path: 189 | config = AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) 190 | else: 191 | config = CONFIG_MAPPING[model_args.model_type]() 192 | logger.warning("You are instantiating a new config instance from scratch.") 193 | 194 | if model_args.tokenizer_name: 195 | tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, cache_dir=model_args.cache_dir) 196 | elif model_args.model_name_or_path: 197 | tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) 198 | else: 199 | raise ValueError( 200 | "You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another script, save it," 201 | "and load it from here, using --tokenizer_name" 202 | ) 203 | 204 | if model_args.model_name_or_path: 205 | model = AutoModelWithLMHead.from_pretrained( 206 | model_args.model_name_or_path, 207 | from_tf=bool(".ckpt" in model_args.model_name_or_path), 208 | config=config, 209 | cache_dir=model_args.cache_dir, 210 | ) 211 | else: 212 | logger.info("Training new model from scratch") 213 | model = AutoModelWithLMHead.from_config(config) 214 | 215 | model.resize_token_embeddings(len(tokenizer)) 216 | 217 | if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm: 218 | raise ValueError( 219 | "BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the" 220 | "--mlm flag (masked language modeling)." 221 | ) 222 | 223 | if data_args.block_size <= 0: 224 | data_args.block_size = tokenizer.max_len 225 | # Our input block size will be the max possible for the model 226 | else: 227 | data_args.block_size = min(data_args.block_size, tokenizer.max_len) 228 | 229 | # Get datasets 230 | 231 | train_dataset = get_dataset(data_args, tokenizer=tokenizer) if training_args.do_train else None 232 | eval_dataset = get_dataset(data_args, tokenizer=tokenizer, evaluate=True) if training_args.do_eval else None 233 | 234 | data_collator = DataCollatorForLanguageModeling( 235 | tokenizer=tokenizer, mlm=data_args.mlm, mlm_probability=data_args.mlm_probability 236 | ) 237 | 238 | # Initialize our Trainer 239 | trainer = Trainer( 240 | model=model, 241 | args=training_args, 242 | data_collator=data_collator, 243 | train_dataset=train_dataset, 244 | eval_dataset=eval_dataset, 245 | prediction_loss_only=True, 246 | ) 247 | 248 | # Training 249 | if training_args.do_train: 250 | model_path = ( 251 | model_args.model_name_or_path 252 | if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path) 253 | else None 254 | ) 255 | trainer.train(model_path=model_path) 256 | trainer.save_model() 257 | # For convenience, we also re-save the tokenizer to the same directory, 258 | # so that you can share your model easily on huggingface.co/models =) 259 | if trainer.is_world_master(): 260 | tokenizer.save_pretrained(training_args.output_dir) 261 | 262 | # Evaluation 263 | results = {} 264 | if training_args.do_eval: 265 | logger.info("*** Evaluate ***") 266 | 267 | eval_output = trainer.evaluate() 268 | 269 | perplexity = math.exp(eval_output["eval_loss"]) 270 | result = {"perplexity": perplexity} 271 | 272 | output_eval_file = os.path.join(training_args.output_dir, "eval_results_lm.txt") 273 | if trainer.is_world_master(): 274 | with open(output_eval_file, "w") as writer: 275 | logger.info("***** Eval results *****") 276 | for key in sorted(result.keys()): 277 | logger.info(" %s = %s", key, str(result[key])) 278 | writer.write("%s = %s\n" % (key, str(result[key]))) 279 | 280 | results.update(result) 281 | 282 | return results 283 | 284 | 285 | def _mp_fn(index): 286 | # For xla_spawn (TPUs) 287 | main() 288 | 289 | 290 | if __name__ == "__main__": 291 | main() -------------------------------------------------------------------------------- /run_language_model_ernie.py: -------------------------------------------------------------------------------- 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 | """ 17 | Fine-tuning the library models for language modeling on a text file (GPT, GPT-2, CTRL, BERT, RoBERTa, XLNet). 18 | GPT, GPT-2 and CTRL are fine-tuned using a causal language modeling (CLM) loss. BERT and RoBERTa are fine-tuned 19 | using a masked language modeling (MLM) loss. XLNet is fine-tuned using a permutation language modeling (PLM) loss. 20 | """ 21 | 22 | 23 | import logging 24 | import math 25 | import os 26 | from dataclasses import dataclass, field 27 | from typing import Optional 28 | 29 | from transformers import ( 30 | CONFIG_MAPPING, 31 | MODEL_WITH_LM_HEAD_MAPPING, 32 | AutoConfig, 33 | AutoModelWithLMHead, 34 | AutoTokenizer, 35 | DataCollatorForLanguageModeling, 36 | HfArgumentParser, 37 | LineByLineTextDataset, 38 | PreTrainedTokenizer, 39 | TextDataset, 40 | Trainer, 41 | TrainingArguments, 42 | set_seed, 43 | ) 44 | 45 | 46 | logger = logging.getLogger(__name__) 47 | 48 | 49 | MODEL_CONFIG_CLASSES = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) 50 | MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) 51 | 52 | 53 | @dataclass 54 | class ModelArguments: 55 | """ 56 | Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch. 57 | """ 58 | 59 | model_name_or_path: Optional[str] = field( 60 | default=None, 61 | metadata={ 62 | "help": "The model checkpoint for weights initialization. Leave None if you want to train a model from scratch." 63 | }, 64 | ) 65 | model_type: Optional[str] = field( 66 | default=None, 67 | metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)}, 68 | ) 69 | config_name: Optional[str] = field( 70 | default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"} 71 | ) 72 | tokenizer_name: Optional[str] = field( 73 | default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} 74 | ) 75 | cache_dir: Optional[str] = field( 76 | default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"} 77 | ) 78 | 79 | 80 | @dataclass 81 | class DataTrainingArguments: 82 | """ 83 | Arguments pertaining to what data we are going to input our model for training and eval. 84 | """ 85 | 86 | train_data_file: Optional[str] = field( 87 | default=None, metadata={"help": "The input training data file (a text file)."} 88 | ) 89 | eval_data_file: Optional[str] = field( 90 | default=None, 91 | metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."}, 92 | ) 93 | line_by_line: bool = field( 94 | default=True, 95 | metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."}, 96 | ) 97 | 98 | mlm: bool = field( 99 | default=False, metadata={"help": "Train with masked-language modeling loss instead of language modeling."} 100 | ) 101 | mlm_probability: float = field( 102 | default=0.15, metadata={"help": "Ratio of tokens to mask for masked language modeling loss"} 103 | ) 104 | plm_probability: float = field( 105 | default=1 / 6, 106 | metadata={ 107 | "help": "Ratio of length of a span of masked tokens to surrounding context length for permutation language modeling." 108 | }, 109 | ) 110 | max_span_length: int = field( 111 | default=5, metadata={"help": "Maximum length of a span of masked tokens for permutation language modeling."} 112 | ) 113 | 114 | block_size: int = field( 115 | default=512, 116 | metadata={ 117 | "help": "Optional input sequence length after tokenization." 118 | "The training dataset will be truncated in block of this size for training." 119 | "Default to the model max input length for single sentence inputs (take into account special tokens)." 120 | }, 121 | ) 122 | overwrite_cache: bool = field( 123 | default=False, metadata={"help": "Overwrite the cached training and evaluation sets"} 124 | ) 125 | 126 | 127 | def get_dataset(args: DataTrainingArguments, tokenizer: PreTrainedTokenizer, evaluate=False): 128 | file_path = args.eval_data_file if evaluate else args.train_data_file 129 | if args.line_by_line: 130 | return LineByLineTextDataset(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size) 131 | else: 132 | return TextDataset( 133 | tokenizer=tokenizer, file_path=file_path, block_size=args.block_size, overwrite_cache=args.overwrite_cache 134 | ) 135 | 136 | 137 | def main(): 138 | # See all possible arguments in src/transformers/training_args.py 139 | # or by passing the --help flag to this script. 140 | # We now keep distinct sets of args, for a cleaner separation of concerns. 141 | 142 | parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) 143 | model_args, data_args, training_args = parser.parse_args_into_dataclasses() 144 | 145 | if data_args.eval_data_file is None and training_args.do_eval: 146 | raise ValueError( 147 | "Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file " 148 | "or remove the --do_eval argument." 149 | ) 150 | 151 | if ( 152 | os.path.exists(training_args.output_dir) 153 | and os.listdir(training_args.output_dir) 154 | and training_args.do_train 155 | and not training_args.overwrite_output_dir 156 | ): 157 | raise ValueError( 158 | f"Output directory ({training_args.output_dir}) already exists and is not empty. Use --overwrite_output_dir to overcome." 159 | ) 160 | 161 | # Setup logging 162 | logging.basicConfig( 163 | format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", 164 | datefmt="%m/%d/%Y %H:%M:%S", 165 | level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, 166 | ) 167 | logger.warning( 168 | "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s", 169 | training_args.local_rank, 170 | training_args.device, 171 | training_args.n_gpu, 172 | bool(training_args.local_rank != -1), 173 | training_args.fp16, 174 | ) 175 | logger.info("Training/evaluation parameters %s", training_args) 176 | 177 | # Set seed 178 | set_seed(training_args.seed) 179 | 180 | # Load pretrained model and tokenizer 181 | # 182 | # Distributed training: 183 | # The .from_pretrained methods guarantee that only one local process can concurrently 184 | # download model & vocab. 185 | 186 | if model_args.config_name: 187 | config = AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir) 188 | elif model_args.model_name_or_path: 189 | config = AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) 190 | else: 191 | config = CONFIG_MAPPING[model_args.model_type]() 192 | logger.warning("You are instantiating a new config instance from scratch.") 193 | 194 | if model_args.tokenizer_name: 195 | tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, cache_dir=model_args.cache_dir) 196 | elif model_args.model_name_or_path: 197 | tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) 198 | else: 199 | raise ValueError( 200 | "You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another script, save it," 201 | "and load it from here, using --tokenizer_name" 202 | ) 203 | 204 | if model_args.model_name_or_path: 205 | model = AutoModelWithLMHead.from_pretrained( 206 | model_args.model_name_or_path, 207 | from_tf=bool(".ckpt" in model_args.model_name_or_path), 208 | config=config, 209 | cache_dir=model_args.cache_dir, 210 | ) 211 | else: 212 | logger.info("Training new model from scratch") 213 | model = AutoModelWithLMHead.from_config(config) 214 | 215 | model.resize_token_embeddings(len(tokenizer)) 216 | 217 | if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm: 218 | raise ValueError( 219 | "BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the" 220 | "--mlm flag (masked language modeling)." 221 | ) 222 | 223 | if data_args.block_size <= 0: 224 | data_args.block_size = tokenizer.max_len 225 | # Our input block size will be the max possible for the model 226 | else: 227 | data_args.block_size = min(data_args.block_size, tokenizer.max_len) 228 | 229 | # Get datasets 230 | 231 | train_dataset = get_dataset(data_args, tokenizer=tokenizer) if training_args.do_train else None 232 | eval_dataset = get_dataset(data_args, tokenizer=tokenizer, evaluate=True) if training_args.do_eval else None 233 | 234 | data_collator = DataCollatorForLanguageModeling( 235 | tokenizer=tokenizer, mlm=data_args.mlm, mlm_probability=data_args.mlm_probability 236 | ) 237 | 238 | # Initialize our Trainer 239 | trainer = Trainer( 240 | model=model, 241 | args=training_args, 242 | data_collator=data_collator, 243 | train_dataset=train_dataset, 244 | eval_dataset=eval_dataset, 245 | prediction_loss_only=True, 246 | ) 247 | 248 | # Training 249 | if training_args.do_train: 250 | model_path = ( 251 | model_args.model_name_or_path 252 | if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path) 253 | else None 254 | ) 255 | trainer.train(model_path=model_path) 256 | trainer.save_model() 257 | # For convenience, we also re-save the tokenizer to the same directory, 258 | # so that you can share your model easily on huggingface.co/models =) 259 | if trainer.is_world_master(): 260 | tokenizer.save_pretrained(training_args.output_dir) 261 | 262 | # Evaluation 263 | results = {} 264 | if training_args.do_eval: 265 | logger.info("*** Evaluate ***") 266 | 267 | eval_output = trainer.evaluate() 268 | 269 | perplexity = math.exp(eval_output["eval_loss"]) 270 | result = {"perplexity": perplexity} 271 | 272 | output_eval_file = os.path.join(training_args.output_dir, "eval_results_lm.txt") 273 | if trainer.is_world_master(): 274 | with open(output_eval_file, "w") as writer: 275 | logger.info("***** Eval results *****") 276 | for key in sorted(result.keys()): 277 | logger.info(" %s = %s", key, str(result[key])) 278 | writer.write("%s = %s\n" % (key, str(result[key]))) 279 | 280 | results.update(result) 281 | 282 | return results 283 | 284 | 285 | def _mp_fn(index): 286 | # For xla_spawn (TPUs) 287 | main() 288 | 289 | 290 | if __name__ == "__main__": 291 | main() -------------------------------------------------------------------------------- /run_language_model_roberta.py: -------------------------------------------------------------------------------- 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 | """ 17 | Fine-tuning the library models for language modeling on a text file (GPT, GPT-2, CTRL, BERT, RoBERTa, XLNet). 18 | GPT, GPT-2 and CTRL are fine-tuned using a causal language modeling (CLM) loss. BERT and RoBERTa are fine-tuned 19 | using a masked language modeling (MLM) loss. XLNet is fine-tuned using a permutation language modeling (PLM) loss. 20 | """ 21 | 22 | 23 | import logging 24 | import math 25 | import os 26 | from dataclasses import dataclass, field 27 | from typing import Optional 28 | from transformers import BertTokenizer, BertForMaskedLM, BertConfig, BertLMHeadModel 29 | 30 | from transformers import ( 31 | CONFIG_MAPPING, 32 | MODEL_WITH_LM_HEAD_MAPPING, 33 | AutoConfig, 34 | AutoModelWithLMHead, 35 | AutoTokenizer, 36 | DataCollatorForLanguageModeling, 37 | HfArgumentParser, 38 | LineByLineTextDataset, 39 | PreTrainedTokenizer, 40 | TextDataset, 41 | Trainer, 42 | TrainingArguments, 43 | set_seed, 44 | ) 45 | 46 | 47 | logger = logging.getLogger(__name__) 48 | 49 | 50 | MODEL_CONFIG_CLASSES = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) 51 | MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) 52 | 53 | 54 | @dataclass 55 | class ModelArguments: 56 | """ 57 | Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch. 58 | """ 59 | 60 | model_name_or_path: Optional[str] = field( 61 | default=None, 62 | metadata={ 63 | "help": "The model checkpoint for weights initialization. Leave None if you want to train a model from scratch." 64 | }, 65 | ) 66 | model_type: Optional[str] = field( 67 | default=None, 68 | metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)}, 69 | ) 70 | config_name: Optional[str] = field( 71 | default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"} 72 | ) 73 | tokenizer_name: Optional[str] = field( 74 | default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} 75 | ) 76 | cache_dir: Optional[str] = field( 77 | default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"} 78 | ) 79 | 80 | 81 | @dataclass 82 | class DataTrainingArguments: 83 | """ 84 | Arguments pertaining to what data we are going to input our model for training and eval. 85 | """ 86 | 87 | train_data_file: Optional[str] = field( 88 | default=None, metadata={"help": "The input training data file (a text file)."} 89 | ) 90 | eval_data_file: Optional[str] = field( 91 | default=None, 92 | metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."}, 93 | ) 94 | line_by_line: bool = field( 95 | default=True, 96 | metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."}, 97 | ) 98 | 99 | mlm: bool = field( 100 | default=False, metadata={"help": "Train with masked-language modeling loss instead of language modeling."} 101 | ) 102 | mlm_probability: float = field( 103 | default=0.15, metadata={"help": "Ratio of tokens to mask for masked language modeling loss"} 104 | ) 105 | plm_probability: float = field( 106 | default=1 / 6, 107 | metadata={ 108 | "help": "Ratio of length of a span of masked tokens to surrounding context length for permutation language modeling." 109 | }, 110 | ) 111 | max_span_length: int = field( 112 | default=5, metadata={"help": "Maximum length of a span of masked tokens for permutation language modeling."} 113 | ) 114 | 115 | block_size: int = field( 116 | default=512, 117 | metadata={ 118 | "help": "Optional input sequence length after tokenization." 119 | "The training dataset will be truncated in block of this size for training." 120 | "Default to the model max input length for single sentence inputs (take into account special tokens)." 121 | }, 122 | ) 123 | overwrite_cache: bool = field( 124 | default=False, metadata={"help": "Overwrite the cached training and evaluation sets"} 125 | ) 126 | 127 | 128 | def get_dataset(args: DataTrainingArguments, tokenizer: PreTrainedTokenizer, evaluate=False): 129 | file_path = args.eval_data_file if evaluate else args.train_data_file 130 | if args.line_by_line: 131 | return LineByLineTextDataset(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size) 132 | else: 133 | return TextDataset( 134 | tokenizer=tokenizer, file_path=file_path, block_size=args.block_size, overwrite_cache=args.overwrite_cache 135 | ) 136 | 137 | 138 | def main(): 139 | # See all possible arguments in src/transformers/training_args.py 140 | # or by passing the --help flag to this script. 141 | # We now keep distinct sets of args, for a cleaner separation of concerns. 142 | 143 | parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) 144 | model_args, data_args, training_args = parser.parse_args_into_dataclasses() 145 | # model_args.config_name = 146 | if data_args.eval_data_file is None and training_args.do_eval: 147 | raise ValueError( 148 | "Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file " 149 | "or remove the --do_eval argument." 150 | ) 151 | 152 | if ( 153 | os.path.exists(training_args.output_dir) 154 | and os.listdir(training_args.output_dir) 155 | and training_args.do_train 156 | and not training_args.overwrite_output_dir 157 | ): 158 | raise ValueError( 159 | f"Output directory ({training_args.output_dir}) already exists and is not empty. Use --overwrite_output_dir to overcome." 160 | ) 161 | 162 | # Setup logging 163 | logging.basicConfig( 164 | format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", 165 | datefmt="%m/%d/%Y %H:%M:%S", 166 | level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, 167 | ) 168 | logger.warning( 169 | "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s", 170 | training_args.local_rank, 171 | training_args.device, 172 | training_args.n_gpu, 173 | bool(training_args.local_rank != -1), 174 | training_args.fp16, 175 | ) 176 | logger.info("Training/evaluation parameters %s", training_args) 177 | 178 | # Set seed 179 | set_seed(training_args.seed) 180 | 181 | # Load pretrained model and tokenizer 182 | # 183 | # Distributed training: 184 | # The .from_pretrained methods guarantee that only one local process can concurrently 185 | # download model & vocab. 186 | 187 | if model_args.config_name: 188 | config = AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir) 189 | elif model_args.model_name_or_path: 190 | config = BertConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) 191 | # config = AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) 192 | else: 193 | config = CONFIG_MAPPING[model_args.model_type]() 194 | logger.warning("You are instantiating a new config instance from scratch.") 195 | 196 | if model_args.tokenizer_name: 197 | tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, cache_dir=model_args.cache_dir) 198 | elif model_args.model_name_or_path: 199 | tokenizer = BertTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) 200 | # tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) 201 | else: 202 | raise ValueError( 203 | "You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another script, save it," 204 | "and load it from here, using --tokenizer_name" 205 | ) 206 | 207 | if model_args.model_name_or_path: 208 | # model = AutoModelWithLMHead.from_pretrained( 209 | # model_args.model_name_or_path, 210 | # from_tf=bool(".ckpt" in model_args.model_name_or_path), 211 | # config=config, 212 | # cache_dir=model_args.cache_dir, 213 | # ) 214 | model = BertForMaskedLM.from_pretrained( 215 | model_args.model_name_or_path, 216 | from_tf=bool(".ckpt" in model_args.model_name_or_path), 217 | config=config, 218 | cache_dir=model_args.cache_dir, 219 | ) 220 | else: 221 | logger.info("Training new model from scratch") 222 | model = AutoModelWithLMHead.from_config(config) 223 | 224 | model.resize_token_embeddings(len(tokenizer)) 225 | 226 | if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm: 227 | raise ValueError( 228 | "BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the" 229 | "--mlm flag (masked language modeling)." 230 | ) 231 | 232 | if data_args.block_size <= 0: 233 | data_args.block_size = tokenizer.max_len 234 | # Our input block size will be the max possible for the model 235 | else: 236 | data_args.block_size = min(data_args.block_size, tokenizer.max_len) 237 | 238 | # Get datasets 239 | print('data args--------------------', data_args) 240 | train_dataset = get_dataset(data_args, tokenizer=tokenizer) if training_args.do_train else None 241 | eval_dataset = get_dataset(data_args, tokenizer=tokenizer, evaluate=True) if training_args.do_eval else None 242 | # print('examples----------------', train_dataset.examples) 243 | data_collator = DataCollatorForLanguageModeling( 244 | tokenizer=tokenizer, mlm=data_args.mlm, mlm_probability=data_args.mlm_probability 245 | ) 246 | 247 | # Initialize our Trainer 248 | trainer = Trainer( 249 | model=model, 250 | args=training_args, 251 | data_collator=data_collator, 252 | train_dataset=train_dataset, 253 | eval_dataset=eval_dataset, 254 | prediction_loss_only=True, 255 | ) 256 | 257 | # Training 258 | if training_args.do_train: 259 | model_path = ( 260 | model_args.model_name_or_path 261 | if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path) 262 | else None 263 | ) 264 | trainer.train(model_path=model_path) 265 | trainer.save_model() 266 | # For convenience, we also re-save the tokenizer to the same directory, 267 | # so that you can share your model easily on huggingface.co/models =) 268 | if trainer.is_world_master(): 269 | tokenizer.save_pretrained(training_args.output_dir) 270 | 271 | # Evaluation 272 | results = {} 273 | if training_args.do_eval: 274 | logger.info("*** Evaluate ***") 275 | 276 | eval_output = trainer.evaluate() 277 | 278 | perplexity = math.exp(eval_output["eval_loss"]) 279 | result = {"perplexity": perplexity} 280 | 281 | output_eval_file = os.path.join(training_args.output_dir, "eval_results_lm.txt") 282 | if trainer.is_world_master(): 283 | with open(output_eval_file, "w") as writer: 284 | logger.info("***** Eval results *****") 285 | for key in sorted(result.keys()): 286 | logger.info(" %s = %s", key, str(result[key])) 287 | writer.write("%s = %s\n" % (key, str(result[key]))) 288 | 289 | results.update(result) 290 | 291 | return results 292 | 293 | 294 | def _mp_fn(index): 295 | # For xla_spawn (TPUs) 296 | main() 297 | 298 | 299 | if __name__ == "__main__": 300 | main() --------------------------------------------------------------------------------