Giter Site home page Giter Site logo

thunlp / webcpm Goto Github PK

View Code? Open in Web Editor NEW
962.0 24.0 80.0 4.11 MB

Official codes for ACL 2023 paper "WebCPM: Interactive Web Search for Chinese Long-form Question Answering"

License: Apache License 2.0

JavaScript 1.33% HTML 71.82% Vue 0.49% TypeScript 1.91% Less 0.06% Python 24.21% Shell 0.18%

webcpm's Introduction

WebCPM

✨ This is the implementation of ACL 2023 paper Interactive Web Search for Chinese Long-form Question Answering

paper

Read this in 中文.


Quick links

Overview

platform

In this work we present WebCPM, a project for interactive Web search using Chinese Pre-trained Models. We develop a web search interface which both humans and collect human web search behaviors. Then we fine-tune PLMs with up to 10B parameters to imitate human behaviors of web search and to generate answers based on the collected facts. We open source the web search interface, dataset, implementation, and model parameters.

Requirements

To run our code, please install all the dependency packages by using the following command:

pip install -r requirements.txt

NOTE: Different versions of packages (e.g., pytorch) may lead to different results from the paper. However, the trend should still hold no matter what versions of packages you use.

Preparation

Prepare the Data

First download the data from Google Drive, and put the files interactive_data and pipeline_data to ./data, or run the following commands:

The downloaded files contain the following:

interactive_data/data.json is the dataset used in the experiments of the paper (5500 instances in total). interactive_data/data_zhihu.json is additional dataset collected alongside this paper (~900 instances), with the question sourcing from Zhihu, you can use this for data augmentation.

Please use the following codes to split the above data into train, dev, and test set (setting --add_zhihu will add data_zhihu.json).

cd data/interactive_data
python split.py --add_zhihu

In addition to the interactive web search data, we also provide the dataset needed for training the pipeline-based web search: pipeline_data (110k instances in total). All the data is created by prompting text-davinci-003 (Bing search engine is also involved) and then manually filtered by human annotators. (Note This part is not included in the paper, and you don't need to split it into train / dev / test.)

Prepare the model

WebCPM is based on CPM-bee with up to 10 billion parameters, which is one of the largest Chinese pre-trained language model in the community. We use an early version of CPM-bee, which is denoted as cpm_10b_webcpm_exp.pt. The latest version of CPM-bee is hosted at New-CPM-bee. You may need to replace the cpm-live package for the new version. Note the model checkpoint has not been fine-tuned towards any downstream task. To access cpm_10b_webcpm_exp.pt, you can download the model parameters at Tsinghua Cloud, or run the following script:

cd models
bash download_model_initial_model.sh

The above codes will download the 10B (non-finetuned) model at models, for the finetuned pipeline model, please refer to download_model_pipeline_finetuned.sh, or download it manually from Tsinghua Cloud.

Train WebCPM

platform

We provide two versions of WebCPM: (1) interactive web search (the method proposed in the ACL paper) and (2) pipeline-based web search, which is easier to deploy (this method is not reported in the paper). Both versions use different scripts for training data generation and the same codes for model training.

A brief Introduction of Pipeline-based Web Search

The workflow follows four stages: (1) first, generate possible search queries based on the original question; (2) then for each search query, call Bing search and visit top-K web pages; (3) for each web page, extract the important information; (4) based on all the recorded information, generate a coherent and nuanced answer. All these things are trained in a multi-task way, please refer to run_web_browsing/run_pipeline.py. For details of the interactive web search, please refer to our original paper.

Data Preprocessing

Before you start, run the following codes:

export PYTHONPATH=/**your-base-path**/webcpm

The training data generation is as follows (we differentiate between interactive web search and pipeline-based method). The following codes will generate train_data, dev_data, and test_data in the corresponding folder, which will be loaded during training.

Training Data Generation of Interactive Web Search

First, construct the data for the synthesis model using the following codes:

cd dataset_interactive
python make_data_synthesis_model.py --data_path ../../data/interactive_data  --augment_qa_data --augment_data_path ../../data/pipeline_data

We explain some of the arguments as follows:

  • data_path: The source data path.
  • augment_qa_data: Whether to augment the training data with qa data automatically generated by text-davinci. (To replicate the results in our paper, do not add this argument)
  • augment_data_path: The data path to the augmented training data.

The training data generation of the search model is as follows:

python make_data_search_model.py --add_query --add_action --add_abstract --abstract_all_tokens

We explain some of the arguments as follows:

  • data_path: The source data path.
  • add_query: If True, will add the query generation data.
  • add_abstract: If True, will add the generate supporting fact extraction data.
  • abstract_all_tokens: If True, supporting fact extraction module will generate all the tokens, instead of only the first / last few tokens.
  • add_action: If True, will add the action prediction data.
  • add_synthesis: If True, will load local data for the synthesis model. Note You must first run python make_data_synthesis_model.py to obtain the synthesis data then add this argument here.

If you want to train all sub-tasks in a multi-task way, just add all the above arguments; otherwise only add one argument (e.g., --add_query) for single-task testing.

Training Data Generation of Pipeline-based Web Search

Please run the following codes:

cd dataset_pipeline
python make_data.py

Training

To train WebCPM, run the following codes:

cd training
export PYTHONPATH=/**your-base-path**/webcpm
export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
GPUS_PER_NODE=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l | xargs)
echo "Number of visible devices: $GPUS_PER_NODE, should be the same as visible devices"

set -ex

MASTER_ADDR=localhost
MASTER_PORT=3239
NNODES=1
NODE_RANK=0

OPTS=""
OPTS+=" --model-config config/cpm-bee-10b.json"
OPTS+=" --dataset ../data/dataset_interactive/train_data"
OPTS+=" --dataseteval ../data/dataset_interactive/dev_data"
OPTS+=" --epoch 5"
OPTS+=" --batch-size 8"
OPTS+=" --train-iters 100"
OPTS+=" --save-name webcpm_finetuned"
OPTS+=" --max-length 2560"
OPTS+=" --save ../models/"
OPTS+=" --lr 0.0001"
OPTS+=" --inspect-iters 100"
OPTS+=" --warmup-iters 1"
OPTS+=" --save-epochs 1"
OPTS+=" --lr-decay-style noam"
OPTS+=" --weight-decay 0.01"
OPTS+=" --clip-grad 1.0"
OPTS+=" --loss-scale 32768"
OPTS+=" --start-step 0"
OPTS+=" --load ../models/cpm_10b_webcpm_exp.pt"

CMD="torchrun --nnodes=${NNODES} --nproc_per_node=${GPUS_PER_NODE} --rdzv_id=1 --rdzv_backend=c10d --rdzv_endpoint=${MASTER_ADDR}:${MASTER_PORT} finetune_cpm_bee.py ${OPTS}"

echo ${CMD}
$CMD

We explain some of the arguments as follows:

  • dataset and dataseteval: The path to the processed file. For interactive web search, it is dataset_interactive, while for pipeline-based method, it is dataset_pipeline.
  • batch-size: The batch size of a single GPU, the real batch size will be #GPUs x batch-size per GPU.
  • max-length: The maximum sequence length of the data (not the model), those longer training instances will be dropped.
  • save-name and save: The path to save the fine-tuned model and the name of the saved model checkpoint.
  • epoch: The number of training epochs.
  • load: The path to the pre-trained model checkpoint (cpmb in this case).

Note no matter which module you are training (or the multi-task setting), you can use the above codes. We are training on 8x80G A100, you can change the batch size according to your GPU devices, the performance is not sensitive to the hyper-parameters.

Single-task Evaluation

To evaluate different sub-tasks, you can first run the following codes to get the prediction of your fine-tuned model on the test data:

cd inference
python inference.py --test_file ../training/dataset_interactive/test.txt --output_file output/test_predictions.json --ckpt_path **your_finetuned_checkpoint.pt

We explain some of the arguments as follows:

  • test_file: The path to the test file, it should have been generated during data preprocessing.
  • output_file: The path you want to write your predictions.
  • ckpt_path: The path to your fine-tuned model.

After obtaining the predictions on the test file, you can run the following codes for single-task evaluation:

python evaluate.py --input_file output/test_predictions.txt --evaluate_action

We explain some of the arguments as follows:

  • input_file: The path you write your predictions of the test file.
  • evaluate_action: Whether you want to evaluate the action prediction task (F1).
  • evaluate_query: Whether you want to evaluate the search query generation task (Rougel-L).
  • evaluate_abstract: Whether you want to evaluate the supporting fact extraction task (Rougel-L).
  • abstract_all_tokens: Which mode do you train your model for supporting fact extraction, if you generate all the tokens, add this argument (Rougel-L).
  • evaluate_answer: Whether you want to evaluate the answer synthesis task (Rougel-L).
  • beam_size: Setting beam size to 1 would significantly accelerate inference, but hurt the performance a little bit.

Run WebCPM for New Questions

This is the implementation for the whole pipeline evaluation. You can use the following codes to generate answers for new questions. Note this requires you to first get a Bing search API key from here and run the following codes:

cd run_web_browsing
export PYTHONPATH=/**base-path**/webcpm
export BING_SEARCH_KEY="**Your Bing Search API Key**"

Interactive Web Search

python run_interactive.py --data_path predictions/test_interactive.json --ckpt_path **your-checkpoint**

Pipeline-based Web Search

python run_pipeline.py --data_path predictions/test.json --ckpt_path **your-checkpoint**

We explain some of the arguments as follows:

  • data_path: The path you write your predictions.
  • ckpt_path: The path to the checkpoint where you have trained using the pipeline-based method.

Platform Building for Data Annotation

platform

We open source our web search interface, you can use it for data annotation. Please refer to Annotation. The codes are a bit messy currently, we will soon upload a cleaner version.

Bugs or questions?

If you have any questions related to the codes or the paper, please contact Yujia ([email protected]) or open an issue.

Resources of Tool Learning

With the powerful capabilities of foundation models, we are eager to see their applications in manipulating various tools. WebCPM is one typical research attempts. For more resources, please refer to the following:

Citation

If you find our WebCPM useful, please use the following citation:

@inproceedings{qin2023webcpm,
    title = "WebCPM: Interactive Web Search for Chinese Long-form Question Answering",
    author={Yujia Qin and Zihan Cai and Dian Jin and Lan Yan and Shihao Liang and Kunlun Zhu and Yankai Lin and Xu Han and Ning Ding and Huadong Wang and Ruobing Xie and Fanchao Qi and Zhiyuan Liu and Maosong Sun and Jie Zhou},
    booktitle = "Proceedings of ACL 2023",
    year = "2023",
    publisher = "Association for Computational Linguistics",
    url = "https://arxiv.org/abs/2305.06849",
}

webcpm's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

webcpm's Issues

为什么去掉引用?

你好,请问下你们在interactive方式下,把cite去掉了是吧?

我看make_data_synthesis_model.py 会去掉引用,这个是为什么呢?

模型加速

您好,目前应用部署在V100s上,1s约生成10个字左右,请问下是否可以提供模型推理加速的一些方案,谢谢

How to try using T5

Great job, but CPM is too big for me. How can I use a small model like T5 or ChatGLM6B

关于模型模仿人类搜索行为的一些问题

简单了解了下WebCPM和WebGPT,应该都是训练LLM学会使用Search Engine,通过搜索结果来总结生成答案。都有人类behavior clone过程,对这个过程有两个疑问:
1.模型是否有必要模仿学习人类行为?
对于人类来说对搜索结果经常会翻页,返回,筛选,是因为受人类阅读速度和时间影响,耐性有限,从而会快速挑选其中的搜索结果进行阅读总结。但对于机器来说不存在这样的问题,机器应该是阅读尽量多的相关页面来进行信息摘要和事实提取,最后总结生成答案,这样答案才更完整和真实吧。

2.搜索引擎排序算法的变动或更换搜索引擎是否都会对模型的性能产生影响?
目前模型是通过bing search来训练的,如果bing search对排序算法进行了变动,搜索结果的排序变了,或者使用其他引擎。是不是对整个搜索行为学习都有影响,需要重新训练。

代码问题make_data_synthesis_model.py

make_syn

line201: rouge.get_scores(cc_new, ' '.join(ans.split()), avg=True)["rouge-l"]["f"] > threshold:

其中split() 在python3下是不生效的,建议改成list(ans)

bmtrain import错误

你好,python3.10安装bmtrain,显示安装成功,但是import bmtrain时,报这个错误:/bmtrain/nccl/_C.cpython-310-x86_64-linux-gnu.so: undefined symbol: ncclBroadcast。torch版本是2.0.0

运行流水线式网页搜索出错

Traceback (most recent call last):
File "/content/WebCPM/run_web_browsing/run_pipeline.py", line 182, in
pred_dict = model_predict_cpmb(modelcpmb, tokenizer_cpmb, question, max_abstract_num=5, whether_corrupt_abstract=False)
File "/content/WebCPM/run_web_browsing/run_pipeline.py", line 57, in model_predict_cpmb
searched_results = op.search(query)
File "/content/WebCPM/run_web_browsing/interaction/platformctrl_pipeline.py", line 48, in search
return self.content[-1].data["webPages"]["value"]
KeyError: 'webPages'
Traceback (most recent call last):
File "/content/WebCPM/run_web_browsing/run_pipeline.py", line 185, in
dump_list.append(pred_dict)
NameError: name 'pred_dict' is not defined

search返回结果json中可能没有webPages字段,需要处理下

os.environ.keys()没有‘MASTER_PORT’

您好,最近调研到您的工作,感觉这个工作非常有价值,填补了国内的空白!

我在复现您的代码的时候,遇到了一个小bug,尝试了许多方法仍然没有解决,所以想问一下您。错误如下:

File "finetune_cpm_bee.py", line 78, in initialize
os.environ["MASTER_PORT"] = str(int(os.environ["MASTER_PORT"]) + 12)
File "/usr/local/lib/python3.8/os.py", line 673, in getitem
raise KeyError(key) from None
KeyError: 'MASTER_PORT

我对我服务器的os.environ.keys()进行了输出,发现确实没有'MASTER_PORT'这个key,也没有分布式需要的其他key,例如WORLD_SIZE,RANK等,我想问一下这是什么原因导致的?是需要安装一些特有库吗?

能提供下baidu网盘的下载地址吗

interactive_data/data.json is the dataset used in the experiments of the paper (5500 instances in total). interactive_data/data_zhihu.json is additional dataset collected alongside this paper (~900 instances), with the question sourcing from Zhihu, you can use this for data augmentation.

t5模型疑问和复现问题

使用数据make_data的数据,然后source:2048 ,target:1024, 测试任务Fact 生成
1.使用mengzi-t5 设置2048的话,大于512的长度都会失去位置信息吧?这个有特殊的处理和优化?
2. 我使用seq2seq 实现的代码,跑出来的结果rouge-l 与论文的61.9差距比较大,代码参考:https://colab.research.google.com/drive/1gXcjGRQHtPU4So4EIktrUBUo4EStp89-?usp=sharing ,请问参数什么的是否不对?或者是有其他的地方需要注意。

迭代两步后内存爆炸

finetune_cpm_bee.py迭代两步后,服务器内存(不是显存)占用急剧增加,直到占满报错,问题出在更新参数的时候:
File "/home/adax/projects/WebCPM/training/scripts/../finetune_cpm_bee.py", line 210, in finetune
optim_manager.step()
File "/home/adax/anaconda3/lib/python3.9/site-packages/bmtrain-0.2.2-py3.9-linux-x86_64.egg/bmtrain/optim/optim_manager.py", line 131, in step
optimizer.step(scale=self.loss_scale)
File "/home/adax/anaconda3/lib/python3.9/site-packages/torch/optim/optimizer.py", line 140, in wrapper
out = func(*args, **kwargs)
File "/home/adax/anaconda3/lib/python3.9/site-packages/torch/autograd/grad_mode.py", line 27, in decorate_context
Traceback (most recent call last):
File "/home/adax/projects/WebCPM/training/scripts/../finetune_cpm_bee.py", line 402, in
main()
File "/home/adax/projects/WebCPM/training/scripts/../finetune_cpm_bee.py", line 398, in main
return func(*args, **kwargs)
File "/home/adax/anaconda3/lib/python3.9/site-packages/bmtrain-0.2.2-py3.9-linux-x86_64.egg/bmtrain/optim/adam_offload.py", line 72, in step
finetune(args, tokenizer, model, optimizer, lr_scheduler)
File "/home/adax/projects/WebCPM/training/scripts/../finetune_cpm_bee.py", line 210, in finetune
optim_manager.step()
File "/home/adax/anaconda3/lib/python3.9/site-packages/bmtrain-0.2.2-py3.9-linux-x86_64.egg/bmtrain/optim/optim_manager.py", line 131, in step
state['_param_fp32'] = torch.empty(p.size(), dtype=torch.float32, device="cpu") # on host
optimizer.step(scale=self.loss_scale)
File "/home/adax/anaconda3/lib/python3.9/site-packages/torch/optim/optimizer.py", line 140, in wrapper
RuntimeError out = func(*args, **kwargs)
File "/home/adax/anaconda3/lib/python3.9/site-packages/torch/autograd/grad_mode.py", line 27, in decorate_context
return func(*args, **kwargs)
File "/home/adax/anaconda3/lib/python3.9/site-packages/bmtrain-0.2.2-py3.9-linux-x86_64.egg/bmtrain/optim/adam_offload.py", line 67, in step
state['exp_avg'] = torch.zeros(p.size(), dtype=torch.float32, device="cpu") # on host
RuntimeError: [enforce fail at alloc_cpu.cpp:75] err == 0. DefaultCPUAllocator: can't allocate memory: you tried to allocate 167772160 bytes. Error code 12 (Cannot allocate memory):
[enforce fail at alloc_cpu.cpp:75] err == 0. DefaultCPUAllocator: can't allocate memory: you tried to allocate 167772160 bytes. Error code 12 (Cannot allocate memory)

引用问题

您好,请问一下,模型是根据摘要+文本输入大模型中的吗,我看模型输出并没有具体的引用结果啊,比如xxxxxxxxxxxxxxxxx[1],xxxxxxxxxxxxxxxxxxxx[2]。每一个话有一个引用,但是这个功能是没有吗

pipeline方式模型

你好,我看到interactive网页搜索方法是训练两个模型检索模型和合成模型,pipeline的方式没有提及,是只训练了一个整体模型嘛?还是也训练两个,如果训练了两个的话,合成模型是使用那儿的数据,pipeline_data的数据看起来像是只训练检索用的?

关于流水线网页搜索工作流程

README中提到流水线网页工作流程包括四个阶段:

(1)首先,根据原始问题生成可能的搜索查询;(2)然后,对每个搜索查询,调用Bing搜索并访问前K个网页;(3)对于每个网页,提取重要信息;(4)基于所有记录的信息,生成连贯且细致的答案。

关于阶段2)只是简单的调用Bing搜索的前k个页面吗?你们的论文中提到这里应该是有个action prediction模块进行动作预测来选择一个页面的吧,不是简单的只取排在前面的k个页面吧

模型是否支持fmoe切分?

作者,您好!
我想问一下,训练或者推理过程中,如果单卡装不下模型的话,支持模型切分吗?例如fmoe框架

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.