• Stars
    star
    359
  • Rank 114,232 (Top 3 %)
  • Language
    Python
  • License
    Apache License 2.0
  • Created over 4 years ago
  • Updated almost 4 years ago

Reviews

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

Repository Details

KnowBert -- Knowledge Enhanced Contextual Word Representations

KnowBert

KnowBert is a general method to embed multiple knowledge bases into BERT. This repository contains pretrained models, evaluation and training scripts for KnowBert with Wikipedia and WordNet.

Citation:

@inproceedings{Peters2019KnowledgeEC,
  author={Matthew E. Peters and Mark Neumann and Robert L Logan and Roy Schwartz and Vidur Joshi and Sameer Singh and Noah A. Smith},
  title={Knowledge Enhanced Contextual Word Representations},
  booktitle={EMNLP},
  year={2019}
}

Getting started

git clone [email protected]:allenai/kb.git
cd kb
conda create -n knowbert python=3.6.7
source activate knowbert
pip install torch==1.2.0
pip install -r requirements.txt
python -c "import nltk; nltk.download('wordnet')"
python -m spacy download en_core_web_sm
pip install --editable .

Then make sure the tests pass:

pytest -v tests

Pretrained Models

How to embed sentences or sentence pairs programmatically

from kb.include_all import ModelArchiveFromParams
from kb.knowbert_utils import KnowBertBatchifier
from allennlp.common import Params

import torch

# a pretrained model, e.g. for Wordnet+Wikipedia
archive_file = 'https://allennlp.s3-us-west-2.amazonaws.com/knowbert/models/knowbert_wiki_wordnet_model.tar.gz'

# load model and batcher
params = Params({"archive_file": archive_file})
model = ModelArchiveFromParams.from_params(params=params)
batcher = KnowBertBatchifier(archive_file)

sentences = ["Paris is located in France.", "KnowBert is a knowledge enhanced BERT"]

# batcher takes raw untokenized sentences
# and yields batches of tensors needed to run KnowBert
for batch in batcher.iter_batches(sentences, verbose=True):
    # model_output['contextual_embeddings'] is (batch_size, seq_len, embed_dim) tensor of top layer activations
    model_output = model(**batch)

How to run intrinisic evaluation

First download one of the pretrained models from the previous section.

Heldout perplexity (Table 1)

Download the heldout data. Then run:

MODEL_ARCHIVE=..location of model
HELDOUT_FILE=wikipedia_bookscorpus_knowbert_heldout.txt
python bin/evaluate_perplexity.py -m $MODEL_ARCHIVE -e $HELDOUT_FILE

The heldout perplexity is key exp(lm_loss_wgt).

Wikidata KG probe (Table 1)

Run:

MODEL_ARCHIVE=..location of model

mkdir -p kg_probe
cd kg_probe
curl https://allennlp.s3-us-west-2.amazonaws.com/knowbert/data/kg_probe.zip > kg_probe.zip
unzip kg_probe.zip

cd ..
python bin/evaluate_mrr.py \
    --model_archive $MODEL_ARCHIVE \
    --datadir kg_probe \
    --cuda_device 0

The results are in key 'mrr'.

Word-sense disambiguation

To evaluate the internal WordNet linker on the ALL task evaluation from Raganato et al. (2017) follow these steps (Table 2). First download the Java scorer and evaluation file.

Then run this command to generate predictions from KnowBert:

EVALUATION_FILE=semeval2007_semeval2013_semeval2015_senseval2_senseval3_all.json
KNOWBERT_PREDICTIONS=knowbert_wordnet_predicted.txt
MODEL_ARCHIVE=..location of model

python bin/evaluate_wsd_official.py \
    --evaluation_file $EVALUATION_FILE \
    --output_file $KNOWBERT_PREDICTIONS \
    --model_archive $MODEL_ARCHIVE \
    --cuda_device 0

To evaluate predictions, decompress the Java scorer, navigate to the directory WSD_Evaluation_Framework/Evaluation_Datasets and run

java Scorer ALL/ALL.gold.key.txt $KNOWBERT_PREDICTIONS

AIDA Entity linking

To reproduce the results in Table 3 for KnowBert-W+W:

# or aida_test.txt
EVALUATION_FILE=aida_dev.txt
MODEL_ARCHIVE=..location of model

curl https://allennlp.s3-us-west-2.amazonaws.com/knowbert/wiki_entity_linking/$EVALUATION_FILE > $EVALUATION_FILE

python bin/evaluate_wiki_linking.py \
    --model_archive $MODEL_ARCHIVE \
    --evaluation_file $EVALUATION_FILE \
    --wiki_and_wordnet

Results are in key wiki_el_f1.

Fine tuning KnowBert for downstream tasks

Fine tuning KnowBert is similar to fine tuning BERT for a downstream task. We provide configuration and model files for the following tasks:

  • Relation extraction: TACRED and SemEval 2010 Task 8
  • Entity typing (Choi et al 2018)
  • Binary sentence classification: Words-in-Context

To reproduce our results for the following tasks, find the appropriate config file in training_config/downstream/, edit the location of the training and dev data files, then run (example provided for TACRED):

allennlp train --file-friendly-logging --include-package kb.include_all \
        training_config/downstream/tacred.jsonnet -s OUTPUT_DIRECTORY

Similar to BERT, for some tasks performance can vary significantly with hyperparameter choices and the random seed. We used the script bin/run_hyperparameter_seeds.sh to perform a small grid search over learning rate, number of epochs and the random seed, choosing the best model based on the validation set.

Evaluating fine tuned models

Fine-tuned KnowBert-Wiki+Wordnet models are available.

To evaluate a model first download the model archive and run:

allennlp evaluate --include-package kb.include_all \
    --cuda-device 0 \
    model_archive_here \
    dev_or_test_filename_here

TACRED

To evaluate a model with the official scorer, run:

python bin/write_tacred_for_official_scorer.py \
    --model_archive model_archive_here \
    --evaluation_file tacred_dev_or_test.json \
    --output_file knowbert_predictions_tacred_dev_or_test.txt

python bin/tacred_scorer.py tacred_dev_or_test.gold knowbert_predictions_tacred_dev_or_test.txt

SemEval 2010 Task 8

To evaluate a model with the official scorer, first download the testing gold keys and run:

curl https://allennlp.s3-us-west-2.amazonaws.com/knowbert/data/semeval2010_task8/test.json > semeval2010_task8_test.json

python bin/write_semeval2010_task8_for_official_eval.py \
    --model_archive model_archive_here \
    --evaluation_file semeval2010_task8_test.json \
    --output_file knowbert_predictions_semeval2010_task8_test.txt

perl -w bin/semeval2010_task8_scorer-v1.2.pl knowbert_predictions_semeval2010_task8_test.txt semeval2010_task8_testing_keys.txt

WiC

Use bin/write_wic_for_codalab.py to write a file for submission to the CodaLab evaluation server.

How to pretrain KnowBert

Roughly speaking, the process to fine tune BERT into KnowBert is:

  1. Prepare your corpus.
  2. Prepare the knowledge bases (not necessary if you are using Wikipedia or WordNet as we have already prepared these).
  3. For each knowledge base:
    1. Pretrain the entity linker while freezing everything else.
    2. Fine tune all parameters (except entity embeddings).

Prepare your corpus.

  1. Sentence tokenize your training corpus using spacy, and prepare input files for next-sentence-prediction sampling. Each file contains one sentence per line with consecutive sentences on subsequent lines and blank lines separating documents.
  2. Run bin/create_pretraining_data_for_bert.py to group the sentences by length, do the NSP sampling, and write out files for training.
  3. Reserve one or more of the training files for heldout evaluation.

Prepare the input knowledge bases.

  1. We have already prepared the knowledge bases for Wikipedia and WordNet. The necessary files will be automatically downloaded as needed when running evaluations or fine tuning KnowBert.

  2. If you would like to add an additional knowledge source to KnowBert, these are roughly the steps to follow:

    1. Compute entity embeddings for each entity in your knowledge base.
    2. Write a candidate generator for the entity linkers. Use the existing WordNet or Wikipedia generators as templates.
  3. Our Wikipedia candidate dictionary list and embeddings were extracted from End-to-End Neural Entity Linking, Kolitsas et al 2018 via a manual process.

  4. Our WordNet candidate generator is rule based (see code). The embeddings were computed via a multistep process that combines TuckER and GenSen embeddings. The prepared files contain everything needed to run KnowBert and include:

    1. entities.jsonl - metadata about WordNet synsets.
    2. wordnet_synsets_mask_null_vocab.txt and wordnet_synsets_mask_null_vocab_embeddings_tucker_gensen.hdf5 - vocabulary file and embedding file for WordNet synsets.
    3. semcor_and_wordnet_examples.json annotated training data combining SemCor and WordNet examples for supervising the WordNet linker.
  5. If you would like to generate these files yourself from scratch, follow these steps.

    1. Extract the WordNet metadata and relationship graph.
      python bin/extract_wordnet.py --extract_graph --entity_file $WORKDIR/entities.jsonl --relationship_file $WORKDIR/relations.txt
      
    2. Download the Words-in-Context dataset to exclude from the extracted WordNet example usages.
      WORKDIR=.
      cd $WORKDIR
      wget https://pilehvar.github.io/wic/package/WiC_dataset.zip
      unzip WiC_dataset.zip
      
    3. Download the word sense diambiguation data:
      cd $WORKDIR
      wget http://lcl.uniroma1.it/wsdeval/data/WSD_Evaluation_Framework.zip
      unzip WSD_Evaluation_Framework.zip
      
    4. Convert the WSD data from XML to jsonl, and concatenate all evaluation files for easy evaluation:
      mkdir $WORKDIR/wsd_jsonl
      python bin/preprocess_wsd.py --wsd_framework_root $WORKDIR/WSD_Evaluation_Framework  --outdir $WORKDIR/wsd_jsonl
      cat $WORKDIR/wsd_jsonl/semeval* $WORKDIR/wsd_jsonl/senseval* > $WORKDIR/semeval2007_semeval2013_semeval2015_senseval2_senseval3.json
      
    5. Extract all the synset example usages from WordNet (after removing sentences from WiC heldout sets):
      python bin/extract_wordnet.py --extract_examples_wordnet --entity_file $WORKDIR/entities.jsonl --wic_root_dir $WORKDIR --wordnet_example_file $WORKDIR/wordnet_examples_remove_wic_devtest.json
      
    6. Combine WordNet examples and definitions with SemCor for training KnowBert:
      cat $WORKDIR/wordnet_examples_remove_wic_devtest.json $WORKDIR/wsd_jsonl/semcor.json > $WORKDIR/semcor_and_wordnet_examples.json
      
    7. Create training and test splits of the relationship graph.
      python bin/extract_wordnet.py --split_wordnet --relationship_file $WORKDIR/relations.txt --relationship_train_file $WORKDIR/relations_train99.txt --relationship_dev_file $WORKDIR/relations_dev01.txt
      
    8. Train TuckER embeddings on the extracted graph. The configuration files uses relationship graph files on S3, although you can substitute them for the files generated in the previous step by modifying the configuration file.
      allennlp train -s $WORKDIR/wordnet_tucker --include-package kb.kg_embedding --file-friendly-logging training_config/wordnet_tucker.json
      
    9. Generate a vocabulary file useful for WordNet synsets with special tokens
      python bin/combine_wordnet_embeddings.py --generate_wordnet_synset_vocab --entity_file $WORKDIR/entities.jsonl --vocab_file $WORKDIR/wordnet_synsets_mask_null_vocab.txt
      
    10. Get the GenSen embeddings from each synset definition. First install the code from this link. Then run
      python bin/combine_wordnet_embeddings.py --generate_gensen_embeddings --entity_file $WORKDIR/entities.jsonl --vocab_file $WORKDIR/wordnet_synsets_mask_null_vocab.txt --gensen_file $WORKDIR/gensen_synsets.hdf5
      
    11. Extract the TuckER embeddings for the synsets from the trained model
      python bin/combine_wordnet_embeddings.py --extract_tucker --tucker_archive_file $WORKDIR/wordnet_tucker/model.tar.gz --vocab_file $WORKDIR/wordnet_synsets_mask_null_vocab.txt --tucker_hdf5_file $WORKDIR/tucker_embeddings.hdf5
      
    12. Finally combine the TuckER and GenSen embeddings into one file
      python bin/combine_wordnet_embeddings.py --combine_tucker_gensen --tucker_hdf5_file $WORKDIR/tucker_embeddings.hdf5 --gensen_file $WORKDIR/gensen_synsets.hdf5 --all_embeddings_file $WORKDIR/wordnet_synsets_mask_null_vocab_embeddings_tucker_gensen.hdf5
      

Pretraining the entity linkers

This step pretrains the entity linker while freezing the rest of the network using only supervised data.

Config files are in training_config/pretraining/knowbert_wiki_linker.jsonnet and training_config/pretraining/knowbert_wordnet_linker.jsonnet.

To train the Wikipedia linker for KnowBert-Wiki run:

allennlp train -s OUTPUT_DIRECTORY --file-friendly-logging --include-package kb.include_all training_config/pretraining/knowbert_wiki_linker.jsonnet

The command is similar for WordNet.

Fine tuning BERT

After pre-training the entity linkers from the step above, fine tune BERT. The pretrained models in our paper were trained on a single GPU with 24GB of RAM. For multiple GPU training, change cuda_device to a list of device IDs.

Config files are in training_config/pretraining/knowbert_wiki.jsonnet and training_config/pretraining/knowbert_wordnet.jsonnet.

Before training, modify the following keys in the config file (or use --overrides flag to allennlp train):

  • "language_modeling"
  • "model_archive" to point to the model.tar.gz from the previous linker pretraining step.

KnowBert Wordnet + Wiki

First train KnowBert-Wiki. Then pretrain the WordNet linker and finally fine tune the entire network.

Config file to pretrain the WordNet linker from KnowBert-Wiki is in training_config/pretraining/knowbert_wordnet_wiki_linker.jsonnet and config to train KnowBert-W+W is in training_config/pretraining/knowbert_wordnet_wiki.jsonnet.

More Repositories

1

allennlp

An open-source NLP research library, built on PyTorch.
Python
11,691
star
2

OLMo

Modeling, training, eval, and inference code for OLMo
Python
3,949
star
3

RL4LMs

A modular RL library to fine-tune language models to human preferences
Python
2,020
star
4

longformer

Longformer: The Long-Document Transformer
Python
1,955
star
5

bilm-tf

Tensorflow implementation of contextualized word representations from bi-directional language models
Python
1,621
star
6

scispacy

A full spaCy pipeline and models for scientific/biomedical documents.
Python
1,566
star
7

bi-att-flow

Bi-directional Attention Flow (BiDAF) network is a multi-stage hierarchical process that represents context at different levels of granularity and uses a bi-directional attention flow mechanism to achieve a query-aware context representation without early summarization.
Python
1,524
star
8

scibert

A BERT model for scientific text.
Python
1,432
star
9

ai2thor

An open-source platform for Visual AI.
C#
1,010
star
10

open-instruct

Python
932
star
11

XNOR-Net

ImageNet classification using binary Convolutional Neural Networks
Lua
839
star
12

mmc4

MultimodalC4 is a multimodal extension of c4 that interleaves millions of images with text.
Python
793
star
13

s2orc

S2ORC: The Semantic Scholar Open Research Corpus: https://www.aclweb.org/anthology/2020.acl-main.447/
Python
745
star
14

scitldr

Python
734
star
15

natural-instructions

Expanding natural instructions
Python
690
star
16

dolma

Data and tools for generating and inspecting OLMo pre-training data.
Python
678
star
17

visprog

Official code for VisProg (CVPR 2023 Best Paper!)
Python
642
star
18

papermage

library supporting NLP and CV research on scientific papers
Python
605
star
19

science-parse

Science Parse parses scientific papers (in PDF form) and returns them in structured form.
Java
566
star
20

writing-code-for-nlp-research-emnlp2018

A companion repository for the "Writing code for NLP Research" Tutorial at EMNLP 2018
Python
558
star
21

pdffigures2

Given a scholarly PDF, extract figures, tables, captions, and section titles.
Scala
514
star
22

allennlp-models

Officially supported AllenNLP models
Python
512
star
23

tango

Organize your experiments into discrete steps that can be cached and reused throughout the lifetime of your research project.
Python
507
star
24

objaverse-xl

🪐 Objaverse-XL is a Universe of 10M+ 3D Objects. Contains API Scripts for Downloading and Processing!
Python
490
star
25

dont-stop-pretraining

Code associated with the Don't Stop Pretraining ACL 2020 paper
Python
488
star
26

specter

SPECTER: Document-level Representation Learning using Citation-informed Transformers
Python
485
star
27

unified-io-2

Python
471
star
28

macaw

Multi-angle c(q)uestion answering
Python
451
star
29

document-qa

Python
420
star
30

scholarphi

An interactive PDF reader.
Python
410
star
31

deep_qa

A deep NLP library, based on Keras / tf, focused on question answering (but useful for other NLP too)
Python
405
star
32

acl2018-semantic-parsing-tutorial

Materials from the ACL 2018 tutorial on neural semantic parsing
402
star
33

unifiedqa

UnifiedQA: Crossing Format Boundaries With a Single QA System
Python
384
star
34

pawls

Software that makes labeling PDFs easy.
Python
356
star
35

PeerRead

Data and code for Kang et al., NAACL 2018's paper titled "A Dataset of Peer Reviews (PeerRead): Collection, Insights and NLP Applications"
Python
354
star
36

naacl2021-longdoc-tutorial

Python
343
star
37

openie-standalone

Quality information extraction at web scale. Edit
Scala
329
star
38

python-package-template

A template repo for Python packages
Python
318
star
39

acl2022-zerofewshot-tutorial

293
star
40

allenact

An open source framework for research in Embodied-AI from AI2.
Python
293
star
41

ir_datasets

Provides a common interface to many IR ranking datasets.
Python
291
star
42

s2orc-doc2json

Parsers for scientific papers (PDF2JSON, TEX2JSON, JATS2JSON)
Python
290
star
43

beaker-cli

A collaborative platform for rapid and reproducible research.
Go
230
star
44

Holodeck

CVPR 2024: Language Guided Generation of 3D Embodied AI Environments.
Python
220
star
45

procthor

🏘️ Scaling Embodied AI by Procedurally Generating Interactive 3D Houses
Python
214
star
46

comet-atomic-2020

Python
212
star
47

FineGrainedRLHF

Python
209
star
48

fm-cheatsheet

Website for hosting the Open Foundation Models Cheat Sheet.
Python
207
star
49

spv2

Science-parse version 2
Python
206
star
50

scifact

Data and models for the SciFact verification task.
Python
206
star
51

OLMo-Eval

Evaluation suite for LLMs
Python
200
star
52

unified-io-inference

Jupyter Notebook
196
star
53

allennlp-demo

Code for the AllenNLP demo.
TypeScript
191
star
54

lumos

Code and data for "Lumos: Learning Agents with Unified Data, Modular Design, and Open-Source LLMs"
Python
190
star
55

citeomatic

A citation recommendation system that allows users to find relevant citations for their paper drafts. The tool is backed by Semantic Scholar's OpenCorpus dataset.
Jupyter Notebook
182
star
56

cartography

Dataset Cartography: Mapping and Diagnosing Datasets with Training Dynamics
Jupyter Notebook
180
star
57

savn

Learning to Learn how to Learn: Self-Adaptive Visual Navigation using Meta-Learning (https://arxiv.org/abs/1812.00971)
Python
175
star
58

vampire

Variational Methods for Pretraining in Resource-limited Environments
Python
173
star
59

objaverse-rendering

📷 Scripts for rendering Objaverse
Python
169
star
60

hidden-networks

Python
164
star
61

ScienceWorld

ScienceWorld is a text-based virtual environment centered around accomplishing tasks from the standardized elementary science curriculum.
Scala
156
star
62

vila

Incorporating VIsual LAyout Structures for Scientific Text Classification
Python
155
star
63

mmda

multimodal document analysis
Jupyter Notebook
154
star
64

cord19

Get started with CORD-19
149
star
65

PRIMER

The official code for PRIMERA: Pyramid-based Masked Sentence Pre-training for Multi-document Summarization
Python
145
star
66

dnw

Discovering Neural Wirings (https://arxiv.org/abs/1906.00586)
Python
139
star
67

tpu_pretrain

LM Pretraining with PyTorch/TPU
Python
129
star
68

deepfigures-open

Companion code to the paper "Extracting Scientific Figures with Distantly Supervised Neural Networks" 🤖
Python
129
star
69

catwalk

This project studies the performance and robustness of language models and task-adaptation methods.
Python
129
star
70

allentune

Hyperparameter Search for AllenNLP
Python
128
star
71

lm-explorer

interactive explorer for language models
Python
127
star
72

pdffigures

Command line tool to extract figures, tables, and captions from scholarly documents in PDF form.
C++
125
star
73

SciREX

Data/Code Repository for https://api.semanticscholar.org/CorpusID:218470122
Python
125
star
74

s2-folks

Public space for the user community of Semantic Scholar APIs to share scripts, report issues, and make suggestions.
125
star
75

scidocs

Dataset accompanying the SPECTER model
Python
124
star
76

gooaq

Question-answers, collected from Google
Python
116
star
77

OpenBookQA

Code for experiments on OpenBookQA from the EMNLP 2018 paper "Can a Suit of Armor Conduct Electricity? A New Dataset for Open Book Question Answering"
Python
113
star
78

allennlp-as-a-library-example

A simple example for how to build your own model using AllenNLP as a dependency.
Python
113
star
79

alexafsm

With alexafsm, developers can model dialog agents with first-class concepts such as states, attributes, transition, and actions. alexafsm also provides visualization and other tools to help understand, test, debug, and maintain complex FSM conversations.
Python
108
star
80

allennlp-semparse

A framework for building semantic parsers (including neural module networks) with AllenNLP, built by the authors of AllenNLP
Python
107
star
81

scicite

Repository for NAACL 2019 paper on Citation Intent prediction
Python
106
star
82

peS2o

Pretraining Efficiently on S2ORC!
105
star
83

multimodalqa

Python
102
star
84

commonsense-kg-completion

Python
102
star
85

real-toxicity-prompts

Jupyter Notebook
101
star
86

ai2thor-rearrangement

🔀 Visual Room Rearrangement
Python
97
star
87

embodied-clip

Official codebase for EmbCLIP
Python
97
star
88

aristo-mini

Aristo mini is a light-weight question answering system that can quickly evaluate Aristo science questions with an evaluation web server and the provided baseline solvers.
Python
96
star
89

s2search

The Semantic Scholar Search Reranker
Python
93
star
90

elastic

Python
91
star
91

reward-bench

RewardBench: the first evaluation tool for reward models.
Python
90
star
92

flex

Few-shot NLP benchmark for unified, rigorous eval
Python
89
star
93

gpv-1

A task-agnostic vision-language architecture as a step towards General Purpose Vision
Jupyter Notebook
89
star
94

manipulathor

ManipulaTHOR, a framework that facilitates visual manipulation of objects using a robotic arm
Jupyter Notebook
86
star
95

medicat

Dataset of medical images, captions, subfigure-subcaption annotations, and inline textual references
Python
85
star
96

propara

ProPara (Process Paragraph Comprehension) dataset and models
Python
82
star
97

allennlp-guide

Code and material for the AllenNLP Guide
Python
81
star
98

hierplane

A tool for visualizing trees, tailored specifically to the analysis of parse trees.
JavaScript
81
star
99

S2AND

Semantic Scholar's Author Disambiguation Algorithm & Evaluation Suite
Python
78
star
100

ARC-Solvers

ARC Question Solvers
Python
78
star