• Stars
    star
    290
  • Rank 142,135 (Top 3 %)
  • Language
    Python
  • License
    MIT License
  • Created over 2 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Code for the NAACL 2022 long paper "DiffCSE: Difference-based Contrastive Learning for Sentence Embeddings"

DiffCSE: Difference-based Contrastive Learning for Sentence Embeddings

Version License: MIT Arxiv Hugging Face Models Hugging Face Transformers Tweet GitHub Stars

Open In Colab

arXiv link: https://arxiv.org/abs/2204.10298
To be published in NAACL 2022

Authors: Yung-Sung Chuang, Rumen Dangovski, Hongyin Luo, Yang Zhang, Shiyu Chang, Marin Soljačić, Shang-Wen Li, Scott Wen-tau Yih, Yoon Kim, James Glass

Our code is mainly based on the code of SimCSE. Please refer to their repository for more detailed information.

Overview

DiffCSE

We propose DiffCSE, an unsupervised contrastive learning framework for learning sentence embeddings. DiffCSE learns sentence embeddings that are sensitive to the difference between the original sentence and an edited sentence, where the edited sentence is obtained by stochastically masking out the original sentence and then sampling from a masked language model. We show that DiffSCE is an instance of equivariant contrastive learning (Dangovski et al., 2021), which generalizes contrastive learning and learns representations that are insensitive to certain types of augmentations and sensitive to other "harmful" types of augmentations. Our experiments show that DiffCSE achieves state-of-the-art results among unsupervised sentence representation learning methods, outperforming unsupervised SimCSE by 2.3 absolute points on semantic textual similarity tasks.

Setups

Python Pytorch

Requirements

  • Python 3.9.5

Install our customized Transformers package

cd transformers-4.2.1
pip install .

Install other packages

pip install -r requirements.txt

Download the pretraining dataset

cd data
bash download_wiki.sh

Download the downstream dataset

cd SentEval/data/downstream/
bash download_dataset.sh

Training

(The same as run_diffcse.sh.)

python train.py \
    --model_name_or_path bert-base-uncased \
    --generator_name distilbert-base-uncased \
    --train_file data/wiki1m_for_simcse.txt \
    --output_dir <your_output_model_dir> \
    --num_train_epochs 2 \
    --per_device_train_batch_size 64 \
    --learning_rate 7e-6 \
    --max_seq_length 32 \
    --evaluation_strategy steps \
    --metric_for_best_model stsb_spearman \
    --load_best_model_at_end \
    --eval_steps 125 \
    --pooler_type cls \
    --mlp_only_train \
    --overwrite_output_dir \
    --logging_first_step \
    --logging_dir <your_logging_dir> \
    --temp 0.05 \
    --do_train \
    --do_eval \
    --batchnorm \
    --lambda_weight 0.005 \
    --fp16 --masking_ratio 0.30

Our new arguments:

  • --lambda_weight: the lambda coefficient mentioned in Section 3 of our paper.
  • --masking_ratio: the masking ratio for MLM generator to randomly replace tokens.
  • --generator_name: the model name of generator. For bert-base-uncased, we use distilbert-base-uncased. For roberta-base, we use distilroberta-base.

Arguments from SimCSE:

  • --train_file: Training file path (data/wiki1m_for_simcse.txt).
  • --model_name_or_path: Pre-trained checkpoints to start with such as BERT-based models (bert-base-uncased, bert-large-uncased, etc.) and RoBERTa-based models (RoBERTa-base, RoBERTa-large).
  • --temp: Temperature for the contrastive loss. We always use 0.05.
  • --pooler_type: Pooling method.
  • --mlp_only_train: For unsupervised SimCSE or DiffCSE, it works better to train the model with MLP layer but test the model without it. You should use this argument when training unsupervised SimCSE/DiffCSE models.

For the results in our paper, we use a NVidia 2080Ti GPU with CUDA 11.2. Using different types of devices or different versions of CUDA/Python/PyTorch may lead to slightly different performance.

Evaluation

Open In Colab
We provide a simple colab notebook to reproduce our results easily. We can also run the commands below for evaluation:

python evaluation.py \
    --model_name_or_path <your_output_model_dir> \
    --pooler cls_before_pooler \
    --task_set <sts|transfer|full> \
    --mode test

To evaluate our pretrained DiffCSE checkpoints, we can use the following scripts:

BERT

STS

python evaluation.py \
    --model_name_or_path voidism/diffcse-bert-base-uncased-sts \
    --pooler cls_before_pooler \
    --task_set sts \
    --mode test

Transfer Tasks

python evaluation.py \
    --model_name_or_path voidism/diffcse-bert-base-uncased-trans \
    --pooler cls_before_pooler \
    --task_set transfer \
    --mode test

RoBERTa

STS

python evaluation.py \
    --model_name_or_path voidism/diffcse-roberta-base-sts \
    --pooler cls_before_pooler \
    --task_set sts \
    --mode test

Transfer Tasks

python evaluation.py \
    --model_name_or_path voidism/diffcse-roberta-base-trans \
    --pooler cls_before_pooler \
    --task_set transfer \
    --mode test

For more detailed information, please check SimCSE's GitHub repo.

Pretrained models

Hugging Face Models

We can load the models using the API provided by SimCSE. See Getting Started for more information.

from diffcse import DiffCSE
model_bert_sts = DiffCSE("voidism/diffcse-bert-base-uncased-sts")
model_bert_trans = DiffCSE("voidism/diffcse-bert-base-uncased-trans")
model_roberta_sts = DiffCSE("voidism/diffcse-roberta-base-sts")
model_roberta_trans = DiffCSE("voidism/diffcse-roberta-base-trans")

Citations

DOI

Please cite our paper and the SimCSE paper if they are helpful to your work!

@inproceedings{chuang2022diffcse,
   title={{DiffCSE}: Difference-based Contrastive Learning for Sentence Embeddings},
   author={Chuang, Yung-Sung and Dangovski, Rumen and Luo, Hongyin and Zhang, Yang and Chang, Shiyu and Soljacic, Marin and Li, Shang-Wen and Yih, Wen-tau and Kim, Yoon and Glass, James},
   booktitle={Annual Conference of the North American Chapter of the Association for Computational Linguistics (NAACL)},
   year={2022}
}

@inproceedings{gao2021simcse,
   title={{SimCSE}: Simple Contrastive Learning of Sentence Embeddings},
   author={Gao, Tianyu and Yao, Xingcheng and Chen, Danqi},
   booktitle={Empirical Methods in Natural Language Processing (EMNLP)},
   year={2021}
}

More Repositories

1

DoLa

Official implementation for the paper "DoLa: Decoding by Contrasting Layers Improves Factuality in Large Language Models"
Python
398
star
2

Lookback-Lens

Official implementation for the paper "Detecting and Mitigating Contextual Hallucinations in Large Language Models Using Only Attention Maps"
Python
93
star
3

pywordseg

Open Source State-of-the-art Chinese Word Segmentation System with BiLSTM and ELMo. https://arxiv.org/abs/1901.05816
Python
39
star
4

EAR

Code for the ACL 2023 long paper - Expand, Rerank, and Retrieve: Query Reranking for Open-Domain Question Answering
Python
34
star
5

Transformer_CycleGAN_Text_Style_Transfer-pytorch

Implementation of CycleGAN for Text style transfer with PyTorch.
Python
29
star
6

L2KD

Code for the EMNLP2020 long paper "Lifelong Language Knowledge Distillation" https://arxiv.org/abs/2010.02123
Python
12
star
7

ML2018SPRING

NTUEE 2018 spring course - Machine Learning (Pei-Yuan Wu, Hung-Yi Lee, Tsungnan Lin)
Python
11
star
8

NAR-ST

Code for the ACL-IJCNLP 2021 Findings paper "Investigating the Reordering Capability in CTC-based Non-Autoregressive End-to-End Speech Translation"
Python
10
star
9

BiLSTM_Collocation_Parser

BiLSTM+ELMo 搭建的中文 Collocation Parser
Python
9
star
10

Input_Method_auto-Modifier

Windows 自動切換輸入法程式 Chinese computer user always annoyed with modifying input types between Chinese and English every now and then. Sometimes you type in a lot of words but finally find it was under wrong input type. It is a kind of tolerant. So I write this tiny Python code to solve this problem. With this program, we almost no need to press "Shift" to change our input type. It will modify you input type automatically according to the words you type in.
AutoHotkey
6
star
11

MakeNTU2019_workshop

MakeNTU 2019 workshop tutorial for Face Lock with RPi, Azure, OpenCV.
Python
5
star
12

invrat_debias

Code for "Mitigating Biases in Toxic Language Detection through Invariant Rationalization"
Python
4
star
13

AWS_synthesis

Python
2
star
14

LiTy

LiTy: Listen & Type - Efficient Dictation Training Tool for English Learners.
Python
2
star
15

Chinese_Sentence_Dependency_Analyzer

Using Word2vec's center vector and context vector to analysis the collocation relations between Chinese words, and greedily want to extract some dependency relations in sentence (but not so successful).
Python
2
star
16

mfcc_extractor

Simple one-line scripts to extract reliable MFCC features with librosa and store in HDF5 format file.
Python
2
star
17

blockchain

A simple implementation of blockchain (UTXO)
Python
2
star
18

DSnP_fraig

Functionally Reduced And-Inverter Graph (FRAIG) - NTUEE Course DSnP Final Project
C++
1
star
19

coffee_beans_recognize

Python
1
star
20

Multiple_clipboard

A tiny tool that can keep each item you copy(up to 100 items). Select one of them to paste by taping "up" and "down" key just like you are keying in commands on the terminal.
Python
1
star