• Stars
    star
    4,145
  • Rank 10,001 (Top 0.3 %)
  • Language
    Python
  • License
    Apache License 2.0
  • Created over 2 years ago
  • Updated 4 months ago

Reviews

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

Repository Details

An Open-Source Framework for Prompt-Learning.

An Open-Source Framework for Prompt-learning.


OverviewInstallationHow To UseDocsPaperCitationPerformance

version

What's New?

  • ❗️ April 2023: $\color{red}{\normalsize{\textbf{Want to build your Chat AI?}}}$ We are releasing UltraChat, use OpenPrompt and UltraChat to conduct supervised instruction tuning, see ./tutorial/9_UltraChat.py.
  • Aug 2022: Thanks to contributor zhiyongLiu1114, OpenPrompt now supports ERNIE 1.0 in PaddlePaddle.
  • July 2022: OpenPrompt supports OPT now.
  • June 2022: OpenPrompt wins ACL 2022 Best Demo Paper Award.
  • Mar 2022: We add a tutorial as the response to issue 124, which uses a customized tokenizer_wrapper to perform tasks that are not in the default configuration of OpenPrompt (e.g., Bert tokenizer+T5 model).
  • Feb 2022: Check out our sister repo OpenDelta!
  • Dec 2021: pip install openprompt
  • Dec 2021: SuperGLUE performance are added
  • Dec 2021: We support generation paradigm for all tasks by adding a new verbalizer:GenerationVerbalizer and a tutorial: 4.1_all_tasks_are_generation.py
  • Nov 2021: Now we have released a paper OpenPrompt: An Open-source Framework for Prompt-learning.
  • Nov 2021 PrefixTuning supports t5 now.
  • Nov 2021: We made some major changes from the last version, where a flexible template language is newly introduced! Part of the docs is outdated and we will fix it soon.

Overview

Prompt-learning is the latest paradigm to adapt pre-trained language models (PLMs) to downstream NLP tasks, which modifies the input text with a textual template and directly uses PLMs to conduct pre-trained tasks. This library provides a standard, flexible and extensible framework to deploy the prompt-learning pipeline. OpenPrompt supports loading PLMs directly from huggingface transformers. In the future, we will also support PLMs implemented by other libraries. For more resources about prompt-learning, please check our paper list.

What Can You Do via OpenPrompt?

demo

  • Use the implementations of current prompt-learning approaches.* We have implemented various of prompting methods, including templating, verbalizing and optimization strategies under a unified standard. You can easily call and understand these methods.
  • Design your own prompt-learning work. With the extensibility of OpenPrompt, you can quickly practice your prompt-learning ideas.

Installation

Note: Please use Python 3.8+ for OpenPrompt

Using Pip

Our repo is tested on Python 3.8+ and PyTorch 1.8.1+, install OpenPrompt using pip as follows:

pip install openprompt

To play with the latest features, you can also install OpenPrompt from the source.

Using Git

Clone the repository from github:

git clone https://github.com/thunlp/OpenPrompt.git
cd OpenPrompt
pip install -r requirements.txt
python setup.py install

Modify the code

python setup.py develop

Use OpenPrompt

Base Concepts

A PromptModel object contains a PLM, a (or multiple) Template and a (or multiple) Verbalizer, where the Template class is defined to wrap the original input with templates, and the Verbalizer class is to construct a projection between labels and target words in the current vocabulary. And a PromptModel object practically participates in training and inference.

Introduction by a Simple Example

With the modularity and flexibility of OpenPrompt, you can easily develop a prompt-learning pipeline.

Step 1: Define a task

The first step is to determine the current NLP task, think about what’s your data looks like and what do you want from the data! That is, the essence of this step is to determine the classes and the InputExample of the task. For simplicity, we use Sentiment Analysis as an example. tutorial_task.

from openprompt.data_utils import InputExample
classes = [ # There are two classes in Sentiment Analysis, one for negative and one for positive
    "negative",
    "positive"
]
dataset = [ # For simplicity, there's only two examples
    # text_a is the input text of the data, some other datasets may have multiple input sentences in one example.
    InputExample(
        guid = 0,
        text_a = "Albert Einstein was one of the greatest intellects of his time.",
    ),
    InputExample(
        guid = 1,
        text_a = "The film was badly made.",
    ),
]

Step 2: Define a Pre-trained Language Models (PLMs) as backbone.

Choose a PLM to support your task. Different models have different attributes, we encourge you to use OpenPrompt to explore the potential of various PLMs. OpenPrompt is compatible with models on huggingface.

from openprompt.plms import load_plm
plm, tokenizer, model_config, WrapperClass = load_plm("bert", "bert-base-cased")

Step 3: Define a Template.

Template is a modifier of the original input text, which is also one of the most important modules in prompt-learning.  We have defined text_a in Step 1.

from openprompt.prompts import ManualTemplate
promptTemplate = ManualTemplate(
    text = '{"placeholder":"text_a"} It was {"mask"}',
    tokenizer = tokenizer,
)

Step 4: Define a Verbalizer

Verbalizer is another important (but not necessary) in prompt-learning,which projects the original labels (we have defined them as classes, remember?) to a set of label words. Here is an example that we project the negative class to the word bad, and project the positive class to the words good, wonderful, great.

from openprompt.prompts import ManualVerbalizer
promptVerbalizer = ManualVerbalizer(
    classes = classes,
    label_words = {
        "negative": ["bad"],
        "positive": ["good", "wonderful", "great"],
    },
    tokenizer = tokenizer,
)

Step 5: Combine them into a PromptModel

Given the task, now we have a PLM, a Template and a Verbalizer, we combine them into a PromptModel. Note that although the example naively combine the three modules, you can actually define some complicated interactions among them.

from openprompt import PromptForClassification
promptModel = PromptForClassification(
    template = promptTemplate,
    plm = plm,
    verbalizer = promptVerbalizer,
)

Step 6: Define a DataLoader

A PromptDataLoader is basically a prompt version of pytorch Dataloader, which also includes a Tokenizer, a Template and a TokenizerWrapper.

from openprompt import PromptDataLoader
data_loader = PromptDataLoader(
    dataset = dataset,
    tokenizer = tokenizer,
    template = promptTemplate,
    tokenizer_wrapper_class=WrapperClass,
)

Step 7: Train and inference

Done! We can conduct training and inference the same as other processes in Pytorch.

import torch

# making zero-shot inference using pretrained MLM with prompt
promptModel.eval()
with torch.no_grad():
    for batch in data_loader:
        logits = promptModel(batch)
        preds = torch.argmax(logits, dim = -1)
        print(classes[preds])
# predictions would be 1, 0 for classes 'positive', 'negative'

Please refer to our tutorial scripts, and documentation for more details.

Datasets

We provide a series of download scripts in the dataset/ folder, feel free to use them to download benchmarks.

Performance Report

There are too many possible combinations powered by OpenPrompt. We are trying our best to test the performance of different methods as soon as possible. The performance will be constantly updated into the Tables. We also encourage the users to find the best hyper-parameters for their own tasks and report the results by making pull request.

Known Issues

Major improvement/enhancement in future.

  • We made some major changes from the last version, so part of the docs is outdated. We will fix it soon.

Citation

Please cite our paper if you use OpenPrompt in your work

@article{ding2021openprompt,
  title={OpenPrompt: An Open-source Framework for Prompt-learning},
  author={Ding, Ning and Hu, Shengding and Zhao, Weilin and Chen, Yulin and Liu, Zhiyuan and Zheng, Hai-Tao and Sun, Maosong},
  journal={arXiv preprint arXiv:2111.01998},
  year={2021}
}

Contributors

We thank all the contributors to this project, more contributors are welcome!

More Repositories

1

GNNPapers

Must-read papers on graph neural networks (GNN)
15,490
star
2

WantWords

An open-source online reverse dictionary.
JavaScript
6,933
star
3

OpenNRE

An Open-Source Package for Neural Relation Extraction (NRE)
Python
4,232
star
4

PromptPapers

Must-read papers on prompt-based tuning for pre-trained language models.
3,912
star
5

OpenKE

An Open-Source Package for Knowledge Embedding (KE)
Python
3,709
star
6

PLMpapers

Must-read Papers on pre-trained language models.
3,161
star
7

NRLPapers

Must-read papers on network representation learning (NRL) / network embedding (NE)
TeX
2,520
star
8

UltraChat

Large-scale, Informative, and Diverse Multi-round Chat Data (and Models)
Python
2,118
star
9

THULAC-Python

An Efficient Lexical Analyzer for Chinese
Python
1,937
star
10

OpenNE

An Open-Source Package for Network Embedding (NE)
Python
1,672
star
11

KRLPapers

Must-read papers on knowledge representation learning (KRL) / knowledge embedding (KE)
TeX
1,527
star
12

TAADpapers

Must-read Papers on Textual Adversarial Attack and Defense
Python
1,455
star
13

ERNIE

Source code and dataset for ACL 2019 paper "ERNIE: Enhanced Language Representation with Informative Entities"
Python
1,396
star
14

KB2E

Knowledge Graph Embeddings including TransE, TransH, TransR and PTransE
C++
1,360
star
15

NREPapers

Must-read papers on neural relation extraction (NRE)
TeX
1,023
star
16

OpenCLaP

Open Chinese Language Pre-trained Model Zoo
971
star
17

WebCPM

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

OpenDelta

A plug-and-play library for parameter-efficient-tuning (Delta Tuning)
Python
938
star
19

RCPapers

Must-read papers on Machine Reading Comprehension
890
star
20

NRE

Neural Relation Extraction, including CNN, PCNN, CNN+ATT, PCNN+ATT
C++
812
star
21

ToolLearningPapers

777
star
22

THULAC

An Efficient Lexical Analyzer for Chinese
C++
770
star
23

FewRel

A Large-Scale Few-Shot Relation Extraction Dataset
Python
716
star
24

THUOCL

THUOCL(THU Open Chinese Lexicon)中文词库
697
star
25

Chinese_Rumor_Dataset

中文谣言数据
672
star
26

OpenAttack

An Open-Source Package for Textual Adversarial Attack.
Python
651
star
27

DocRED

Dataset and codes for ACL 2019 DocRED: A Large-Scale Document-Level Relation Extraction Dataset.
Python
605
star
28

OpenHowNet

Core Data of HowNet and OpenHowNet Python API
Python
592
star
29

TensorFlow-TransX

An implementation of TransE and its extended models for Knowledge Representation Learning on TensorFlow
Python
511
star
30

LegalPapers

Must-read Papers on Legal Intelligence
450
star
31

OpenMatch

An Open-Source Package for Information Retrieval.
Python
444
star
32

CAIL

Chinese AI & Law Challenge
439
star
33

BERT-KPE

Python
437
star
34

Fast-TransX

An Efficient implementation of TransE and its extended models for Knowledge Representation Learning
C++
396
star
35

TensorFlow-Summarization

Python
390
star
36

Few-NERD

Code and data of ACL 2021 paper "Few-NERD: A Few-shot Named Entity Recognition Dataset"
Python
376
star
37

SOS4NLP

Survey of Surveys for Natural Language Processing (SOS4NLP)
327
star
38

THULAC-Java

An Efficient Lexical Analyzer for Chinese
Java
322
star
39

NSC

Neural Sentiment Classification
Python
287
star
40

BMCourse

The repo for Tsinghua summer course: Interdisciplinary Seminar on Big Models
Python
269
star
41

Chinese_NRE

Source code for ACL 2019 paper "Chinese Relation Extraction with Multi-Grained Information and External Linguistic Knowledge"
Python
264
star
42

DeltaPapers

Must-read Papers of Parameter-Efficient Tuning (Delta Tuning) Methods on Pre-trained Models.
259
star
43

PL-Marker

Source code for "Packed Levitated Marker for Entity and Relation Extraction"
Python
239
star
44

SE-WRL

Improved Word Representation Learning with Sememes
C
197
star
45

THUCTC

An Efficient Chinese Text Classifier
Java
196
star
46

InfLLM

The code of our paper "InfLLM: Unveiling the Intrinsic Capacity of LLMs for Understanding Extremely Long Sequences with Training-Free Memory"
Python
196
star
47

SCPapers

Must-read Papers on Sememe Computation
192
star
48

KnowledgeablePromptTuning

kpt code
Python
192
star
49

CANE

Source code and datasets of "CANE: Context-Aware Network Embedding for Relation Modeling"
Python
190
star
50

JointNRE

Joint Neural Relation Extraction with Text and KGs
Python
185
star
51

HATT-Proto

Code and dataset of AAAI2019 paper Hybrid Attention-Based Prototypical Networks for Noisy Few-Shot Relation Classification
Python
180
star
52

LLaVA-UHD

LLaVA-UHD: an LMM Perceiving Any Aspect Ratio and High-Resolution Images
Python
169
star
53

NLP-THU

NLP Course Material & QA
162
star
54

KernelGAT

The source codes for Fine-grained Fact Verification with Kernel Graph Attention Network.
Python
161
star
55

LegalPLMs

Source code and checkpoints for legal pre-trained language models.
Python
158
star
56

EntityDuetNeuralRanking

Entity-Duet Neural Ranking Model
Python
153
star
57

PTR

Prompt Tuning with Rules
Python
151
star
58

OOP-THU

OOP Course Material & QA
148
star
59

Auto_CLIWC

Code for Chinese LIWC Lexicon Expansion via Hierarchical Classification of Word Embeddings with Sememe Attention (AAAI18)
Python
136
star
60

OpenBackdoor

An open-source toolkit for textual backdoor attack and defense (NeurIPS 2022 D&B, Spotlight)
Python
135
star
61

attribute_charge

The source code of our COLING'18 paper "Few-Shot Charge Prediction with Discriminative Legal Attributes".
Python
126
star
62

ConceptFlow

Python
119
star
63

THUCKE

THU Chinese Keyphrase Extraction Toolkit
C++
118
star
64

CAIL2018

Python
111
star
65

KR-EAR

Knowledge Representation Learning with Entities, Attributes and Relations
C++
111
star
66

Neural-Snowball

Code and dataset of AAAI2020 Paper Neural Snowball for Few-Shot Relation Learning
Python
111
star
67

ChatEval

Codes for our paper "ChatEval: Towards Better LLM-based Evaluators through Multi-Agent Debate"
Python
109
star
68

MultiRD

Code and data of the AAAI-20 paper "Multi-channel Reverse Dictionary Model"
Python
106
star
69

TransNet

Source code and datasets of IJCAI2017 paper "TransNet: Translation-Based Network Representation Learning for Social Relation Extraction".
Jupyter Notebook
103
star
70

RE-Context-or-Names

Bert-based models(BERT, MTB, CP) for relation extraction.
Python
100
star
71

AGE

Source code and dataset for KDD 2020 paper "Adaptive Graph Encoder for Attributed Graph Embedding"
Python
99
star
72

GEAR

Source code for ACL 2019 paper "GEAR: Graph-based Evidence Aggregating and Reasoning for Fact Verification"
Python
95
star
73

HNRE

Hierarchical Neural Relation Extraction
Python
95
star
74

LEVEN

Source code and dataset for ACL2022 Findings Paper "LEVEN: A Large-Scale Chinese Legal Event Detection dataset"
Python
94
star
75

TopJudge

Python
93
star
76

Prompt-Transferability

On Transferability of Prompt Tuning for Natural Language Processing
Python
85
star
77

SememePSO-Attack

Code and data of the ACL 2020 paper "Word-level Textual Adversarial Attacking as Combinatorial Optimization"
Python
85
star
78

XQA

Dataset and baseline for ACL 2019 paper "XQA: A Cross-lingual Open-domain Question Answering Dataset"
Python
84
star
79

HMEAE

Source code for EMNLP-IJCNLP 2019 paper "HMEAE: Hierarchical Modular Event Argument Extraction".
Python
84
star
80

ERICA

Source code for ACL 2021 paper "ERICA: Improving Entity and Relation Understanding for Pre-trained Language Models via Contrastive Learning"
Python
82
star
81

CLAIM

77
star
82

TKRL

Representation Learning of Knowledge Graphs with Hierarchical Types (IJCAI-2016)
C++
76
star
83

TLNN

Source code for EMNLP-IJCNLP 2019 paper "Event Detection with Trigger-Aware Lattice Neural Network".
Python
75
star
84

MMDW

Max-margin DeepWalk
Java
71
star
85

KV-PLM

Source code for "A Deep-learning System Bridging Molecule Structure and Biomedical Text with Comprehension Comparable to Human Professionals"
Python
71
star
86

KNET

Neural Entity Typing with Knowledge Attention
Python
69
star
87

SelectiveMasking

Source code for "Train No Evil: Selective Masking for Task-Guided Pre-Training"
Python
68
star
88

NeuIRPapers

Must-read Papers on Neural Information Retrieval
68
star
89

MoEfication

Python
66
star
90

Adv-ED

Source code and dataset for NAACL 2019 paper "Adversarial Training for Weakly Supervised Event Detection".
Python
66
star
91

CorefBERT

Source code for EMNLP 2020 paper "Coreferential Reasoning Learning for Language Representation"
Python
64
star
92

ConversationQueryRewriter

Code and Data for SIGIR 2020 Paper "Few-Shot Generative Conversational Query Rewriting"
Roff
63
star
93

MuGNN

Source code for ACL2019 paper "Multi-Channel Graph Neural Network for Entity Alignment".
Python
62
star
94

sememe_prediction

Codes for Lexical Sememe Prediction via Word Embeddings and Matrix Factorization (IJCAI 2017).
Python
60
star
95

DIAG-NRE

Source code for ACL 2019 paper "DIAG-NRE: A Neural Pattern Diagnosis Framework for Distantly Supervised Neural Relation Extraction".
Python
59
star
96

topical_word_embeddings

Topical Word Embeddings
Python
57
star
97

QuoteR

Official code and data of the ACL 2022 paper "QuoteR: A Benchmark of Quote Recommendation for Writing"
Python
57
star
98

paragraph2vec

Paragraph Vector Implementation
Python
56
star
99

DKRL

Representation Learning of Knowledge Graphs with Entity Descriptions (AAAI-2016)
C++
54
star
100

Ouroboros

Ouroboros: Speculative Decoding with Large Model Enhanced Drafting
Python
51
star