Code Monkey home page Code Monkey logo

conversationalqa's Introduction

Controlling the Risk of Conversational Search via Reinforcement Learning

&

Simulating and Modeling the Risk of Conversational Search

A risk-aware conversational search system consisting of pretrained answer and question rerankers and a decision maker trained by reinforcement learning.

Package requirements (recommended versions).

  1. torch==1.4.0
  2. transformers==3.4.0

How to use

  1. Preprocess data.(alternatively, the processed datasets can be downloaded from datasets) Here we use MSDialog dataset as example. You can also set dataset_name to be 'UDC' for Ubuntu Dialog Corpus or 'opendialkg' for Opendialkg. First, download MSDialog-Complete.json into /data.

    $ cd data
    $ python3 data_processing.py --dataset_name MSDialog
    

    This will process and filter the data. All conversations that meet the filtering criterion are saved in MSDialog-Complete and will be automatically split into training and testing set. The others are save in MSDialog-Incomplete. The former is used for the main experiments and the latter is used for fine-tuning the rerankers only. The data processing code uses random.seed(2020) to fix the result of data generation.

  2. Fine-tune pretrained reranker checkpoints on both the answer reranking and question reranking training samples (MSDialog as example). The training of the rerankers are based on ParlAI

    $ cd ParlAI
    $ python3 -u examples/train_model.py \
        --init-model zoo:pretrained_transformers/poly_model_huge_reddit/model \
        -t fromfile:parlaiformat --fromfile_datapath ../data/MSDialog-parlai-answer \
        --model transformer/polyencoder --batchsize 4 --eval-batchsize 100 \
        --warmup_updates 100 --lr-scheduler-patience 0 --lr-scheduler-decay 0.4 \
        -lr 5e-05 --data-parallel True --history-size 20 --label-truncate 72 \
        --text-truncate 360 --num-epochs 12.0 --max_train_time 200000 -veps 0.5 \
        -vme 8000 --validation-metric accuracy --validation-metric-mode max \
        --save-after-valid True --log_every_n_secs 20 --candidates batch --fp16 True \
        --dict-tokenizer bpe --dict-lower True --optimizer adamax --output-scaling 0.06 \
        --variant xlm --reduction-type mean --share-encoders False \
        --learn-positional-embeddings True --n-layers 12 --n-heads 12 --ffn-size 3072 \
        --attention-dropout 0.1 --relu-dropout 0.0 --dropout 0.1 --n-positions 1024 \
        --embedding-size 768 --activation gelu --embeddings-scale False --n-segments 2 \
        --learn-embeddings True --polyencoder-type codes --poly-n-codes 64 \
        --poly-attention-type basic --dict-endtoken __start__ \
        --model-file zoo:pretrained_transformers/model_poly/answer \
        --ignore-bad-candidates True  --eval-candidates batch
    
    $ python3 -u examples/train_model.py \
        --init-model zoo:pretrained_transformers/poly_model_huge_reddit/model \
        -t fromfile:parlaiformat --fromfile_datapath ../data/MSDialog-parlai-question \
        --model transformer/polyencoder --batchsize 4 --eval-batchsize 100 \
        --warmup_updates 100 --lr-scheduler-patience 0 --lr-scheduler-decay 0.4 \
        -lr 5e-05 --data-parallel True --history-size 20 --label-truncate 72 \
        --text-truncate 360 --num-epochs 12.0 --max_train_time 200000 -veps 0.5 \
        -vme 8000 --validation-metric accuracy --validation-metric-mode max \
        --save-after-valid True --log_every_n_secs 20 --candidates batch --fp16 True \
        --dict-tokenizer bpe --dict-lower True --optimizer adamax --output-scaling 0.06 \
        --variant xlm --reduction-type mean --share-encoders False \
        --learn-positional-embeddings True --n-layers 12 --n-heads 12 --ffn-size 3072 \
        --attention-dropout 0.1 --relu-dropout 0.0 --dropout 0.1 --n-positions 1024 \
        --embedding-size 768 --activation gelu --embeddings-scale False --n-segments 2 \
        --learn-embeddings True --polyencoder-type codes --poly-n-codes 64 \
        --poly-attention-type basic --dict-endtoken __start__ \
        --model-file zoo:pretrained_transformers/model_poly/question \
        --ignore-bad-candidates True  --eval-candidates batch
    

    This will download the poly-encoder checkpoints pretrained on reddit and fine-tune it on our preprocessed dataset. The fine-tuned model is save in ParlAI/data/models/pretrained_transformers/model_poly/.

    If you get an error of dictionary size mismatching, this is because that the pretrained model checkpoints has a dictionary that's larger than the fine-tune dataset. To solve this problem, before running the fine-tuning script, copy the downloaded pretrained dict file ParlAI/data/models/pretrained_transformers/poly_model_huge_reddit/model.dict to ParlAI/data/models/pretrained_transformers/model_poly/ and rename them to answer.dict. Then run the above fine-tuning script. Similar for the bi-encoder experiments.

    For bi-encoder fine-tuning, use the following command. When getting the dictionary size error, copy ParlAI/data/models/pretrained_transformers/bi_model_huge_reddit/model.dict to ParlAI/data/models/pretrained_transformers/model_bi/ and rename them to answer.dict.:

    $ cd ParlAI
    $ python3 -u examples/train_model.py \
        --init-model zoo:pretrained_transformers/bi_model_huge_reddit/model \
        -t fromfile:parlaiformat --fromfile_datapath ../data/MSDialog-parlai-answer \
        --model transformer/biencoder --batchsize 4 --eval-batchsize 100 \
        --warmup_updates 100 --lr-scheduler-patience 0 \
        --lr-scheduler-decay 0.4 -lr 5e-05 --data-parallel True \
        --history-size 20 --label-truncate 72 --text-truncate 360 \
        --num-epochs 12.0 --max_train_time 200000 -veps 0.5 -vme 8000 \
        --validation-metric accuracy --validation-metric-mode max \
        --save-after-valid True --log_every_n_secs 20 --candidates batch \
        --dict-tokenizer bpe --dict-lower True --optimizer adamax \
        --output-scaling 0.06 \
        --variant xlm --reduction-type mean --share-encoders False \
        --learn-positional-embeddings True --n-layers 12 --n-heads 12 \
        --ffn-size 3072 --attention-dropout 0.1 --relu-dropout 0.0 --dropout 0.1 \
        --n-positions 1024 --embedding-size 768 --activation gelu \
        --embeddings-scale False --n-segments 2 --learn-embeddings True \
        --share-word-embeddings False --dict-endtoken __start__ --fp16 True \
        --model-file zoo:pretrained_transformers/model_bi/answer\
        --ignore-bad-candidates True  --eval-candidates batch
    
    $ python3 -u examples/train_model.py \
        --init-model zoo:pretrained_transformers/bi_model_huge_reddit/model \
        -t fromfile:parlaiformat --fromfile_datapath ../data/MSDialog-parlai-question \
        --model transformer/biencoder --batchsize 4 --eval-batchsize 100 \
        --warmup_updates 100 --lr-scheduler-patience 0 \
        --lr-scheduler-decay 0.4 -lr 5e-05 --data-parallel True \
        --history-size 20 --label-truncate 72 --text-truncate 360 \
        --num-epochs 12.0 --max_train_time 200000 -veps 0.5 -vme 8000 \
        --validation-metric accuracy --validation-metric-mode max \
        --save-after-valid True --log_every_n_secs 20 --candidates batch \
        --dict-tokenizer bpe --dict-lower True --optimizer adamax \
        --output-scaling 0.06 \
        --variant xlm --reduction-type mean --share-encoders False \
        --learn-positional-embeddings True --n-layers 12 --n-heads 12 \
        --ffn-size 3072 --attention-dropout 0.1 --relu-dropout 0.0 --dropout 0.1 \
        --n-positions 1024 --embedding-size 768 --activation gelu \
        --embeddings-scale False --n-segments 2 --learn-embeddings True \
        --share-word-embeddings False --dict-endtoken __start__ --fp16 True \
        --model-file zoo:pretrained_transformers/model_bi/question\
        --ignore-bad-candidates True  --eval-candidates batch
    

    The fine-tuning code is based on ParlAI poly-encoder, but we modify several scripts for our needs. We do not recommended downloading the original ParlAI code and replace the ParlAI folder in this program. The original training of the encoders are done on 8 x GPU 32GB. We decrease the batch size and is able to run it on 4 x GPU 11GB (GeForce RTX 2080Ti).

  3. Run the main experiments. To run the experiments, use the following code:

    $ python3  run_sampling.py --dataset_name MSDialog --reranker_name Poly --topn 1 --cv 0 > your_log_file
    

    --dataset_name can be 'MSDialog', 'UDC', or 'Opendialkg' currently. --reranker_name can be 'Poly' or 'Bi' currently. --topn means the top n reranked candidates are considered correct, i.e. --topn computes recall@1. The MSDialog dataset is too small, so it's recommended to run it using cross validation. When the dataset size is big enough or there is no need to run cross validation, simply use --cv -1 to turn off cross validation. The experiment would take a couple of hours to one day. So, it's recommended to save the results to a log file.

Reference

Please cite the following work if you use this code repository in your work:

@inproceedings{10.1145/3442381.3449893,
author = {Wang, Zhenduo and Ai, Qingyao},
title = {Controlling the Risk of Conversational Search via Reinforcement Learning},
year = {2021},
isbn = {9781450383127},
publisher = {Association for Computing Machinery},
address = {New York, NY, USA},
url = {https://doi.org/10.1145/3442381.3449893},
doi = {10.1145/3442381.3449893},
pages = {1968โ€“1977},
numpages = {10},
keywords = {conversational search, reinforcement learning},
location = {Ljubljana, Slovenia},
series = {WWW '21}
}
@article{10.1145/3507357,
author = {Wang, Zhenduo and Ai, Qingyao},
title = {Simulating and Modeling the Risk of Conversational Search},
year = {2022},
issue_date = {October 2022},
publisher = {Association for Computing Machinery},
address = {New York, NY, USA},
volume = {40},
number = {4},
issn = {1046-8188},
url = {https://doi.org/10.1145/3507357},
doi = {10.1145/3507357},
month = {mar},
articleno = {85},
numpages = {33},
keywords = {risk control, reinforcement learning, Conversational search}
}

conversationalqa's People

Contributors

zhenduow avatar dependabot[bot] avatar

Stargazers

 avatar Yaxiong Wu avatar Jiho Noh avatar Brutus Xu avatar magicye avatar Phenix avatar luhua avatar Martin Uray avatar Shashank Gupta avatar

Watchers

 avatar

Forkers

leeensub

conversationalqa's Issues

Not able to fine-tune reranker

Hi,

I am having issues running the fine-tunning with your instructions.

  1. the instructions are missing to change the path to ParlAI in ParlAI/examples/train_model.py (minor thing)
  2. when starting to fine-tune the reranker I get an exception in ParlAI/parlai/core/metrics.py, stating that (line 607) a None can not be concatenated with None. Resolved that by checking on None.
  3. when training more than 26h, fine-tuning crashes for the following reason (with both, poly- and bi endocer):
CUDA_VISIBLE_DEVICES=1,4,5,7 python3 -u examples/train_model.py     --init-model zoo:pretrained_transformers/bi_model_hu
ge_reddit/model     -t fromfile:parlaiformat --fromfile_datapath ../data/MSDialog-parlai-question     --model transformer/biencoder --batchsize 4 --eval-batchsize 100     --warmup_updates 100 --lr-scheduler-pati
ence 0     --lr-scheduler-decay 0.4 -lr 5e-05 --data-parallel True     --history-size 20 --label-truncate 72 --text-truncate 360     --num-epochs 12.0 --max_train_time 200000 -veps 0.5 -vme 8000     --validation
-metric accuracy --validation-metric-mode max     --save-after-valid True --log_every_n_secs 20 --candidates batch     --dict-tokenizer bpe --dict-lower True --optimizer adamax     --output-scaling 0.06     --va
riant xlm --reduction-type mean --share-encoders False     --learn-positional-embeddings True --n-layers 12 --n-heads 12     --ffn-size 3072 --attention-dropout 0.1 --relu-dropout 0.0 --dropout 0.1     --n-posit
ions 1024 --embedding-size 768 --activation gelu     --embeddings-scale False --n-segments 2 --learn-embeddings True     --share-word-embeddings False --dict-endtoken __start__ --fp16 True  --fp16-impl apex --fo
rce-fp16-tokens true  --model-file zoo:pretrained_transformers/model_bi/question    --ignore-bad-candidates True  --eval-candidates batch
[ building dictionary first... ]
[ dictionary already built .]

***************************************************************************
[ WARNING ] : your model is being loaded with opts that do not exist in the model you are initializing the weights with: dynamic_batching: None,evaltask: None,eval_batchsize: 100,display_examples: False,num_epoc
hs: 12.0,max_train_time: 200000.0,validation_every_n_secs: -1,save_every_n_secs: -1,save_after_valid: True,validation_every_n_epochs: 0.5,validation_max_exs: 8000,short_final_eval: False,validation_patience: 10,
validation_metric: accuracy,validation_metric_mode: max,validation_cutoff: 1.0,load_from_checkpoint: False,validation_share_agent: False,metrics: default,aggregate_micro: False,tensorboard_log: False,dict_maxexs
: -1,dict_include_valid: False,dict_include_test: False,log_every_n_secs: 20.0,fromfile_datapath: ../data/MSDialog-parlai-question,fromfile_datatype_extension: False,fp16_impl: apex,force_fp16_tokens: True,adam_
eps: 1e-08,adafactor_eps: 1e-30,0.001,history_add_global_end_token: None,max_lr_steps: -1,invsqrt_lr_decay_gamma: -1,interactive_candidates: fixed,encode_candidate_vecs_batchsize: 256,rank_top_k: -1,inference: m
ax,topk: 5,return_cand_scores: False,n_encoder_layers: -1,n_decoder_layers: -1,model_parallel: False,bpe_vocab: None,bpe_merge: None,bpe_add_prefix_space: None,dict_loaded: True,download_path: project/ParlAI/downloads,datapath: project/ParlAI/data,interactive_mode: False

***************************************************************************
[ WARNING ] : your model is being loaded with opts that differ from the model you are initializing the weights with. Add the following args to your run command to change this:

--task convai2 --batchsize 512 --single-turn False --candidates inline --eval-candidates inline --encode-candidate-vecs False --cap-num-predictions 100 --ignore-bad-candidates False --parlai-home /private/home/e
dinan/ParlAI
***************************************************************************
project/ParlAI/parlai/utils/fp16.py:144: UserWarning: You set --fp16 true with --fp16-impl apex, but fp16 with apex is unavailable. To use apex fp
16, please install APEX from https://github.com/NVIDIA/apex.
  'You set --fp16 true with --fp16-impl apex, but fp16 '
Traceback (most recent call last):
  File "project/ParlAI/parlai/core/torch_agent.py", line 1805, in load_state_dict
    self.model.load_state_dict(state_dict)
  File "project/.venv/lib/python3.6/site-packages/torch/nn/modules/module.py", line 830, in load_state_dict
    self.__class__.__name__, "\n\t".join(error_msgs)))
RuntimeError: Error(s) in loading state_dict for TransformerMemNetModel:
        size mismatch for embeddings.weight: copying a param with shape torch.Size([54944, 768]) from checkpoint, the shape in current model is torch.Size([29920, 768]).
        size mismatch for cand_embeddings.weight: copying a param with shape torch.Size([54944, 768]) from checkpoint, the shape in current model is torch.Size([29920, 768]).
        size mismatch for context_encoder.embeddings.weight: copying a param with shape torch.Size([54944, 768]) from checkpoint, the shape in current model is torch.Size([29920, 768]).
        size mismatch for cand_encoder.embeddings.weight: copying a param with shape torch.Size([54944, 768]) from checkpoint, the shape in current model is torch.Size([29920, 768]).
        size mismatch for memory_transformer.embeddings.weight: copying a param with shape torch.Size([54944, 768]) from checkpoint, the shape in current model is torch.Size([29920, 768]).

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "examples/train_model.py", line 16, in <module>
    TrainModel.main()
  File "project/ParlAI/parlai/scripts/script.py", line 81, in main
    return cls._run_args(None)
  File "project/ParlAI/parlai/scripts/script.py", line 68, in _run_args
    return script.run()
  File "project/ParlAI/parlai/scripts/train_model.py", line 759, in run
    return TrainLoop(self.opt).train()
  File "project/ParlAI/parlai/scripts/train_model.py", line 276, in __init__
    self.agent = create_agent(opt)
  File "project/ParlAI/parlai/core/agents.py", line 407, in create_agent
    model = create_agent_from_opt_file(opt)
  File "project/ParlAI/parlai/core/agents.py", line 362, in create_agent_from_opt_file
    return model_class(new_opt)
  File "project/ParlAI/parlai/core/torch_ranker_agent.py", line 207, in __init__
    states = self.load(init_model)
  File "project/ParlAI/parlai/core/torch_agent.py", line 1832, in load
    self.load_state_dict(states['model'])
  File "project/ParlAI/parlai/core/torch_agent.py", line 1810, in load_state_dict
    f'{msg_}\n'
RuntimeError: Error(s) in loading state_dict for TransformerMemNetModel:
        size mismatch for embeddings.weight: copying a param with shape torch.Size([54944, 768]) from checkpoint, the shape in current model is torch.Size([29920, 768]).
        size mismatch for cand_embeddings.weight: copying a param with shape torch.Size([54944, 768]) from checkpoint, the shape in current model is torch.Size([29920, 768]).
        size mismatch for context_encoder.embeddings.weight: copying a param with shape torch.Size([54944, 768]) from checkpoint, the shape in current model is torch.Size([29920, 768]).
        size mismatch for cand_encoder.embeddings.weight: copying a param with shape torch.Size([54944, 768]) from checkpoint, the shape in current model is torch.Size([29920, 768]).
        size mismatch for memory_transformer.embeddings.weight: copying a param with shape torch.Size([54944, 768]) from checkpoint, the shape in current model is torch.Size([29920, 768])

Best

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.