CDial-GPT: Chinese GPT Models for Dialogue Generation

CDial-GPT

This project provides a large-scale cleaned Chinese conversation dataset and a Chinese GPT model pre-trained on this dataset. Please refer to our paper for more details.

Our code used for the pre-training is adapted from the TransferTransfo model based on the Transformers library. The codes used for both pre-training and fine-tuning are provided in this repository.

Dataset

We present a Large-scale Cleaned Chinese Conversation corpus (LCCC) containing: LCCC-base (Baidu Netdisk, Google Drive) and LCCC-large (Baidu Netdisk, Google Drive). A rigorous data cleaning pipeline is designed to ensure the quality of the corpus. This pipeline involves a set of rules and several classifier-based filters. Noises such as offensive or sensitive words, special symbols, emojis, grammatically incorrect sentences, and incoherent conversations are filtered.

The statistic of our corpus is presented below. Dialogues with only two utterances are regarded as "Single-turn", and dialogues with more than three utterances are regarded as "Multi-turn". The vocabulary size is calculated in word-level, and Jieba is used to tokenize each utterance to words.

LCCC-base 
(Baidu Netdisk, Google Drive)
Single-turnMulti-turn
Sessions3,354,3823,466,607
Utterances6,708,55413,365,268
Characters68,559,727163,690,614
Vocabulary372,063666,931
Avg. words per utterance6.798.32
Avg. utterances per session23.86

Note that LCCC-base is cleaned using more strict rules compared to LCCC-large.

LCCC-large 
(Baidu Netdisk, Google Drive)
Single-turnMulti-turn
Sessions7,273,8044,733,955
Utterances14,547,60818,341,167
Characters162,301,556217,776,649
Vocabulary662,514690,027
Avg. words per utterance7.458.14
Avg. utterances per session23.87

The raw dialogues for LCCC-base originate from a Weibo Corpus that we crawled from Weibo, and the raw dialogues for LCCC-large is built by combining several conversation datasets in addition to the Weibo Corpus:

DatasetSessionsSample
Weibo Corpus79MQ:火锅我在重庆成都吃了七八顿火锅 A: 哈哈哈哈!那我的嘴巴 可能要烂掉!
PTT Gossiping Corpus0.4MQ:为什么乡民总是欺负国高中生呢QQ A:如果以为选好科系就会变成比尔盖兹那不如退学吧
Subtitle Corpus2.74MQ:京戏里头的人都是不自由的 A:他们让人拿笼子给套起来了了
Xiaohuangji Corpus0.45MQ:你谈过恋爱么 A:谈过,哎,别提了,伤心..
Tieba Corpus2.32MQ:前排,鲁迷们都起床了吧 A:标题说助攻,但是看了那球,真是活生生的讽刺了
Qingyun Corpus0.1MQ:看来你很爱钱 A:噢是吗?那么你也差不多了
Douban Conversation Corpus0.5MQ:看原版英文电影学纯正英语 A:大爱老友记反复看了好多次 了 Q:一样光盘都快被我看花了 A:那你现在的英语应该不错了
E-commerical Conversation Corpus0.5MQ:这个会不会聚划算 A:暂时没有哦 Q:后期会不会有 A:不一定哦亲多多关注我们哦
Chinese Chat Corpus0.5MQ: 我今天腿都废了,你们过节,我搬砖 A: 辛苦啊,圣诞节还去赚大钱了加油 Q: 毕竟是没男朋友的人,什么节都是一样的

Pre-training

Models

We also present a series of Chinese GPT model that are first pre-trained on a Chinese novel dataset and then post-trained on our LCCC dataset.

Similar to TransferTransfo, we concatenate all dialogue histories into one context sentence, and use this sentence to predict the response. The input of our model consists of word embedding, speaker embedding, and positional embedding of each word.

Input representation

ModelsParameter SizePre-training DatasetDescription
GPTNovel95.5MChinese NovelA GPT model pre-trained on Chinese Novel dataset (1.3B words, note that we do not provide the detail of this model)
CDial-GPTLCCC-base95.5MLCCC-baseA GPT model post-trained on LCCC-base dataset from GPTNovel
CDial-GPT2LCCC-base95.5MLCCC-baseA GPT2 model post-trained on LCCC-base dataset from GPTNovel
CDial-GPTLCCC-large95.5MLCCC-largeA GPT model post-trained on LCCC-large dataset from GPTNovel

Installation

Install from the source codes:

git clone https://github.com/thu-coai/CDial-GPT.git
cd CDial-GPT
pip install -r requirements.txt 

Quick Start

Step 1: Prepare the data for fine-tuning (E.g., STC dataset or "data/toy_data.json" in our respository) and the pre-trianed model:

# Download the STC dataset and unzip into "data_path" dir (fine-tuning on STC)
git lfs install
git clone https://huggingface.co/thu-coai/CDial-GPT_LCCC-large  # or OpenAIGPTLMHeadModel.from_pretrained("thu-coai/CDial-GPT_LCCC-large")

ps: You can download the train and valid split of STC from the following links: (Baidu Netdisk, Google Drive)

Step 2: Train the model

python train.py --pretrained --model_checkpoint thu-coai/CDial-GPT_LCCC-large --data_path data/STC.json --scheduler linear  # Single GPU training

or

python -m torch.distributed.launch --nproc_per_node=8 train.py --pretrained --model_checkpoint thu-coai/CDial-GPT_LCCC-large --data_path data/STC.json --scheduler linear  # Training on 8 GPUs

Note: We have also provided train_path argument in the training script to read dataset in plain text, which will be sliced and handled distributionally. You can consider to use this argument if the dataset is too large for your system's memory. (also, remember to leave the data_path argument empty if you are using train_path).

Step 3: Inference mode

# YOUR_MODEL_PATH: the model path used for generation
python infer.py --model_checkpoint YOUR_MODEL_PATH --datapath data/STC_test.json --out_path STC_result.txt  # Do Inference on a corpus
python interact.py --model_checkpoint YOUR_MODEL_PATH  # Interact on the terminal

ps: You can download the test split of STC from the following links: (Baidu Netdisk, Google Drive)

Training Arguments

ArgumentsTypeDefault valueDescription
model_checkpointstr""Path or URL of model files (Directory of pre-training model and config/vocab files)
pretrainedboolFalseIf False, then train the model from scratch
data_pathstr""Path of the dataset
dataset_cachestrdefault="dataset_cache"Path or url of the dataset cache
train_pathstr""Path of the training set for distributed dataset
valid_pathstr""Path of the validation set for distributed dataset
log_filestr""Output logs to a file under this path
num_workersint1Number of subprocesses for data loading
n_epochsint70Number of training epochs
train_batch_sizeint8Batch size for training
valid_batch_sizeint8Batch size for validation
max_historyint15Number of previous exchanges to keep in history
schedulerstr"noam"Method of optimizer
n_emdint768Number of n_emd in config file (for noam)
eval_before_startboolFalseIf true, start evaluation before training
warmup_stepsint5000Warm up steps
valid_stepsint0Perform validation every X steps, if is not 0
gradient_accumulation_stepsint64Accumulate gradients on several steps
max_normfloat1.0Clipping gradient norm
devicestr"cuda" if torch.cuda.is_available() else "cpu"Device (cuda or cpu)
fp16str""Set to O0, O1, O2 or O3 for fp16 training (see apex documentation)
local_rankint-1Local rank for distributed training (-1: not distributed)

Evaluation

Evaluation is performed on results generated by models fine-tuned on

STC dataset (Train/Valid split (Baidu Netdisk, Google Drive), Test split (Baidu Netdisk, Google Drive)). All responses are generated using the Nucleus Sampling scheme with a threshold 0.9 and temperature 0.7.

Automatic Evaluation

ModelsModel SizePPLBLEU-2BLEU-4Dist-1Dist-2Greedy MatchingEmbedding Average
Attn-Seq2seq73M34.203.930.908.511.9165.8483.38
Transformer113M22.106.723.148.813.9766.0683.55
GPT2-chitchat88M-2.280.5410.316.2561.5478.94
GPTNovel95.5M21.275.962.718.011.7266.1283.34
GPTLCCC-base95.5M18.386.483.088.312.6866.2183.54
GPT2LCCC-base95.5M22.765.692.507.710.8766.2483.46
GPTLCCC-large95.5M18.236.633.208.312.7166.2583.63

Human Evaluation

We also employed 3 crowd-sourced annotators to evaluate 200 samples of each model about fluency, relevance, and diversity based on a 2/1/0 score schema. Refer to our paper for more details.

Models+2+1+0Kappa
Attn-Seq2Seq27.1%21.4%51.4%0.4544
Transformer42.4%23.6%34.0%0.4429
GPT2-chitchat24.3%19,1%56.6%0.3941
GPTLCCC-base46.7%21.8%31.5%0.3954
GPTLCCC-large48.6%24.5%27.0%0.4203

Toxic Generation Statistics

We randomly select 1000 generated samples, and make a statistic of toxic generation:

RepetitionDirty wordOther Bad Cases
2392

Case study of GPTLCCC-large

Single-turn generated examples from STC dataset (fine-tuned on STC):

PostResponse
这 居 然 是 北 京 不 是 哈 尔 滨 。哈 尔 滨 的 天 气 好 像 比 北 京 好 点 , 我 这 里 就 是 小 雨 , 白 天 都 是 大 风
运 营 商 校 园 广 告 大 P K , 太 欢 乐 了 ! 哈 哈 哈 。我 以 为 是 马 云 的 广 告 。
D e l s a S p o s a 糖 果 色 系 列 婚 纱 , 粉 蓝 红 紫 , 俏 皮 又 清 新 , 你 喜 欢 吗 ?最 后 一 件 太 美 了 , 美 的 不 像 话 !

Multi-turn generated examples using the interactive script:

RoelResponse
User别爱我没结果
Bot没 结 果 的 爱 是 多 么 的 痛 。
User但是爱过就可以了
Bot有 时 候 ,爱 情 就 是 一 场 游 戏 。
User输的总是我
Bot我 爱 你 , 就 像 我 爱 你 一 样 。
User你可拉到吧
Bot你 可 拉 到 吧 。
User别学我说话
Bot我 说 话 就 是 你 不 行 。
User逼我动手是吧
Bot不 , 是 逼 你 动 口 是 吧

Authors

Yida Wang, Pei Ke, Yinhe Zheng, Kaili Huang, Yong Jiang, Xiaoyan Zhu, Minlie Huang

Acknowledgement

Zuoxian Ye, Yao Wang, Yifan Pan

Disclaimer

The LCCC dataset and the pre-trained models aim to facilitate the research for conversation generation. The LCCC dataset provided in this repository originates from various sources. Although a rigorous cleaning process has been carried out, there is no guarantee that all the inappropriate contents have been completely filtered out. All the contents contained in this dataset does not represent the authors' opinion. This repository contains only part of the modeling machinery needed to actually produce a dialogue model. The decoding script provided in this repository is only for the research purpose. We are not responsible for any contents generated using our model.

Citation

Please kindly cite our paper if you use the datasets or models in your research:

@inproceedings{wang2020chinese,
  title={A Large-Scale Chinese Short-Text Conversation Dataset},
  author={Wang, Yida and Ke, Pei and Zheng, Yinhe and Huang, Kaili and Jiang, Yong and Zhu, Xiaoyan and Huang, Minlie},
  booktitle={NLPCC},
  year={2020},
  url={https://arxiv.org/abs/2008.03946}
}

CDial-GPT

本项目提供了一个大规模中文对话数据集,并提供了在此数据集上的中文对话预训练模型(中文GPT模型),更多信息可参考我们的论文

本项目代码修改自TransferTransfo,使用了HuggingFace Pytorch版的Transformers库, 可用于预训练与微调。

News

  • 2022-06-09: LCCC数据集现在可以通过huggingface的datasets库加载:
from datasets import load_dataset

dataset = load_dataset("lccc", "base")  # or "large"
  • 2022-04-26: 一个新的多模态对话数据集MMChat,欢迎大家使用。
  • 2021-02-28: 一个对话数据清洗框架,欢迎大家提bug和加速优化算法,以及新的清洗功能等等。
  • 2021-01-09: 实验室出版新书《现代自然语言生成》,欢迎大家阅读购买。
  • 2020-11-20: 预训练模型新工作SentiLARE。本工作将词级别的语言学知识(包括词性和词的情感极性)引入预训练语言模型中,提出了一种适用于情感分析任务的语言表示模型SentiLARE,欢迎大家使用。
  • 2020-10-18: 我们的论文《A Large-Scale Chinese Short-Text Conversation Dataset》获得了NLPCC2020 Best Student Paper Award。 🎉 🎉 🎉
  • 2020-09-08: 感谢@xiejiachen所提供的可视化Web界面
  • 2020-09-02: 可用bert4keras加载TF版本的CDial-GPT模型,感谢苏剑林@bojone提供代码。

数据集概况

我们所提供的数据集LCCC(Large-scale Cleaned Chinese Conversation)主要包含两部分: LCCC-base (百度网盘, Google Drive) 和 LCCC-large (百度网盘, Google Drive). 我们设计了一套严格的数据过滤流程来确保该数据集中对话数据的质量。 这一数据过滤流程中包括一系列手工规则以及若干基于机器学习算法所构建的分类器。 我们所过滤掉的噪声包括:脏字脏词、特殊字符、颜表情、语法不通的语句、上下文不相关的对话等。

该数据集的统计信息如下表所示。 其中,我们将仅包含两个语句的对话称为“单轮对话”,我们将包含两个以上语句的对话称为“多轮对话”。 统计词表大小时使用 Jieba 分词。

LCCC-base 
(百度网盘, Google Drive)
单轮对话多轮对话
总对话轮次3,354,2323,466,274
总对话语句6,708,46413,365,256
总字符数68,559,367163,690,569
词表大小372,063666,931
对话语句的平均词数6.798.32
每轮对话的平均语句数23.86

请注意, LCCC-base 数据集的清洗过程比 LCCC-large 更为严格,因此其规模也更小。

LCCC-large 
(百度网盘, Google Drive)
单轮对话多轮对话
总对话轮次7,273,8044,733,955
总对话语句14,547,60818,341,167
总字符数162,301,556217,776,649
词表大小662,514690,027
对话语句的评价词数7.458.14
每轮对话的平均语句数23.87

LCCC-base 数据集中的原始对话数据来自于微博对话,LCCC-large 数据集中的原始对话数据在这些微博对话的基础上融合了其他开源对话数据集:

数据集总对话轮次对话示例
Weibo Corpus79MQ:火锅我在重庆成都吃了七八顿火锅 A: 哈哈哈哈!那我的嘴巴 可能要烂掉!
PTT Gossiping Corpus0.4MQ:为什么乡民总是欺负国高中生呢QQ A:如果以为选好科系就会变成比尔盖兹那不如退学吧
Subtitle Corpus2.74MQ:京戏里头的人都是不自由的 A:他们让人拿笼子给套起来了了
Xiaohuangji Corpus0.45MQ:你谈过恋爱么 A:谈过,哎,别提了,伤心..
Tieba Corpus2.32MQ:前排,鲁迷们都起床了吧 A:标题说助攻,但是看了那球,真是活生生的讽刺了
Qingyun Corpus0.1MQ:看来你很爱钱 A:噢是吗?那么你也差不多了
Douban Conversation Corpus0.5MQ:看原版英文电影学纯正英语 A:大爱老友记反复看了好多次 了 Q:一样光盘都快被我看花了 A:那你现在的英语应该不错了
E-commerical Conversation Corpus0.5MQ:这个会不会聚划算 A:暂时没有哦 Q:后期会不会有 A:不一定哦亲多多关注我们哦
Chinese Chat Corpus0.5MQ: 我今天腿都废了,你们过节,我搬砖 A: 辛苦啊,圣诞节还去赚大钱了加油 Q: 毕竟是没男朋友的人,什么节都是一样的

预训练模型概况

模型

我们同时提供了一系列中文预训练模型(中文GPT模型),这些模型的预训练过程分为两步,首先在一个中文小说数据上预训练,然后在LCCC数据集上预训练。

我们沿用了 TransferTransfo 中的数据预处理设定,既将所有的对话历史拼接为一个句子,然后使用这个句子作为模型的输入,预测对话回复。我们模型的输入除了各个词的向量表示外,还包括发话人向量表示和位置向量表示。

模型输入

预训练模型参数数量预训练所使用数据描述
GPTNovel95.5M中文小说数据基于中文小说数据所构建中文预训练GPT模型 (该小说数据中共包括1.3B个字)
CDial-GPTLCCC-base95.5MLCCC-base在GPTNovel的基础上,使用 LCCC-base 训练得到的中文预训练GPT模型
CDial-GPT2LCCC-base95.5MLCCC-base在GPTNovel的基础上,使用 LCCC-base 训练得到的中文预训练GPT2模型
CDial-GPTLCCC-large95.5MLCCC-large在GPTNovel的基础上,使用 LCCC-large 训练得到的中文预训练GPT模型

安装

从源代码直接安装:

git clone https://github.com/thu-coai/CDial-GPT.git
cd CDial-GPT
pip install -r requirements.txt 

快速开始

Step 1: 准备预训练模型和 fine-tuning 所需使用的数据集(如 STC dataset 或该项目目录中的toy数据 "data/toy_data.json", 请注意如数据中包含英文需按字母分割如:h e l l o)

# 下载 STC 数据集 中的训练集和验证集 并将其解压至 "data_path" 目录 (如果微调所使用的数据集为 STC)
git lfs install
git clone https://huggingface.co/thu-coai/CDial-GPT_LCCC-large  # 您可自行下载模型或者OpenAIGPTLMHeadModel.from_pretrained("thu-coai/CDial-GPT_LCCC-large")

ps:可以使用如下链接下载STC的训练集和验证集 (百度网盘, Google Drive)

Step 2: 训练模型

python train.py --pretrained --model_checkpoint thu-coai/CDial-GPT_LCCC-large --data_path data/STC.json --scheduler linear  # 使用单个GPU进行训练

或者

python -m torch.distributed.launch --nproc_per_node=8 train.py --pretrained --model_checkpoint thu-coai/CDial-GPT_LCCC-large --data_path data/STC.json --scheduler linear  # 以分布式的方式在8块GPU上训练

我们的训练脚本中还提供了 train_path 参数,用户可使用该参数以切片地形式读取纯文本文件。如果您所使用的的系统中内存有限,可以考虑使用该参数读入训练数据。 如果您使用 train_path 则需要将 data_path 置空。

Step 3: 生成文本

# YOUR_MODEL_PATH: 你要使用的模型的路径,每次微调后的模型目录保存在./runs/中
python infer.py --model_checkpoint YOUR_MODEL_PATH --datapath data/STC_test.json --out_path STC_result.txt  # 在测试数据上生成回复
python interact.py --model_checkpoint YOUR_MODEL_PATH  # 在命令行中与模型进行交互

ps:可以使用如下链接下载STC的测试集 (百度网盘, Google Drive)

训练脚本参数

参数类型默认值描述
model_checkpointstr""Path or URL of model files (Directory of pre-training model and config/vocab files)
pretrainedboolFalseIf False, then train the model from scratch
data_pathstr""Path of the dataset
dataset_cachestrdefault="dataset_cache"Path or url of the dataset cache
train_pathstr""Path of the training set for distributed dataset
valid_pathstr""Path of the validation set for distributed dataset
log_filestr""Output logs to a file under this path
num_workersint1Number of subprocesses for data loading
n_epochsint70Number of training epochs
train_batch_sizeint8Batch size for training
valid_batch_sizeint8Batch size for validation
max_historyint15Number of previous exchanges to keep in history
schedulerstr"noam"Method of optimizer
n_emdint768Number of n_emd in config file (for noam)
eval_before_startboolFalseIf true, start evaluation before training
warmup_stepsint5000Warm up steps
valid_stepsint0Perform validation every X steps, if is not 0
gradient_accumulation_stepsint64Accumulate gradients on several steps
max_normfloat1.0Clipping gradient norm
devicestr"cuda" if torch.cuda.is_available() else "cpu"Device (cuda or cpu)
fp16str""Set to O0, O1, O2 or O3 for fp16 training (see apex documentation)
local_rankint-1Local rank for distributed training (-1: not distributed)

评测结果

我们评测了使用 STC数据集 (训练集/验证集 (百度网盘, Google Drive), 测试集 (百度网盘, Google Drive)) 微调后的对话预训练模型。 所有的回复均使用 Nucleus Sampling 的方法采样得到 (p=0.9, temperature=0.7)。

自动评价指标

模型模型大小PPLBLEU-2BLEU-4Dist-1Dist-2Greedy MatchingEmbedding Average
Attn-Seq2seq73M34.203.930.908.511.9165.8483.38
Transformer113M22.106.723.148.813.9766.0683.55
GPT2-chitchat88M-2.280.5410.316.2561.5478.94
GPTNovel95.5M21.275.962.718.011.7266.1283.34
GPTLCCC-base95.5M18.386.483.088.312.6866.2183.54
GPT2LCCC-base95.5M22.765.692.507.710.8766.2483.46
GPTLCCC-large95.5M18.236.633.208.312.7166.2583.63

人工评价指标

我们为每个模型采样了200个回复,并在外包平台上邀请了3位标注员对这些回复进行人工评测,评测维度为对话流畅性、上下文相关性和回复多样性。每个维度的打分范围为 2/1/0。更多细节请参考我们的 论文

模型+2+1+0Kappa
Attn-Seq2Seq27.1%21.4%51.4%0.4544
Transformer42.4%23.6%34.0%0.4429
GPT2-chitchat24.3%19,1%56.6%0.3941
GPTLCCC-base46.7%21.8%31.5%0.3954
GPTLCCC-large48.6%24.5%27.0%0.4203

不良回复统计

我们随机采样了1000个对话回复,并统计了这些回复中的不良回复:

包含重复语句包含脏字其他不良回复
2392

GPTLCCC-large模型的生成示例

我们在STC数据集上微调了GPTLCCC-large模型的参数,并使用这一微调后的模型生成了如下对话示例:

PostResponse
这 居 然 是 北 京 不 是 哈 尔 滨 。哈 尔 滨 的 天 气 好 像 比 北 京 好 点 , 我 这 里 就 是 小 雨 , 白 天 都 是 大 风
运 营 商 校 园 广 告 大 P K , 太 欢 乐 了 ! 哈 哈 哈 。我 以 为 是 马 云 的 广 告 。
D e l s a S p o s a 糖 果 色 系 列 婚 纱 , 粉 蓝 红 紫 , 俏 皮 又 清 新 , 你 喜 欢 吗 ?最 后 一 件 太 美 了 , 美 的 不 像 话 !

我们还使用上述微调后的模型得到了如下交互结果:

RoelResponse
User别爱我没结果
Bot没 结 果 的 爱 是 多 么 的 痛 。
User但是爱过就可以了
Bot有 时 候 ,爱 情 就 是 一 场 游 戏 。
User输的总是我
Bot我 爱 你 , 就 像 我 爱 你 一 样 。
User你可拉到吧
Bot你 可 拉 到 吧 。
User别学我说话
Bot我 说 话 就 是 你 不 行 。
User逼我动手是吧
Bot不 , 是 逼 你 动 口 是 吧

作者

Yida Wang, Pei Ke, Yinhe Zheng, Kaili Huang, Yong Jiang, Xiaoyan Zhu, Minlie Huang

致谢

Zuoxian Ye, Yao Wang, Yifan Pan

免责声明

本项目所提供的 LCCC 数据集和预训练对话模型仅限科研用途。LCCC数据集中的对话收集自不同的来源,虽然我们设计了一套严格的数据清洗流程,但是我们并不保证所有不当内容均已被过滤。该数据中所包含的所有内容和意见与本项目作者无关。 本项目所提供的模型和代码仅为完整对话系统的一个组成部分,我们所提供的解码脚本仅限科研用途,使用本项目中的模型和脚本所生成的一切对话内容与本项目作者无关。

引用

如果您觉得我们的项目对您有帮助,请引用我们的论文

@inproceedings{wang2020chinese,
  title={A Large-Scale Chinese Short-Text Conversation Dataset},
  author={Wang, Yida and Ke, Pei and Zheng, Yinhe and Huang, Kaili and Jiang, Yong and Zhu, Xiaoyan and Huang, Minlie},
  booktitle={NLPCC},
  year={2020},
  url={https://arxiv.org/abs/2008.03946}
}

Download Details:

Author: thu-coai
Source Code: https://github.com/thu-coai/CDial-GPT 
License: MIT license

#gpt #text #generator #pytorch 

CDial-GPT: Chinese GPT Models for Dialogue Generation
1.05 GEEK