Sign inSign up

sapienzanlp/relik

By sapienzanlp

Updated about 2 years ago

Retrieve, Read and LinK: Fast and Accurate IE on an Academic Budget

Image
Machine learning & AI
0

1.3K

sapienzanlp/relik repository overview

Conference Paper arXiv

Hugging Face Collection Hugging Face Spaces

Lightning PyTorch Code style: black PyPi Version Release Version

A blazing fast and lightweight Information Extraction model for Entity Linking and Relation Extraction.

🛠️ Installation

Installation from PyPI

pip install relik
Other installation options
Install with optional dependencies

Install with all the optional dependencies.

pip install relik[all]

Install with optional dependencies for training and evaluation.

pip install relik[train]

Install with optional dependencies for FAISS

FAISS PyPI package is only available for CPU. For GPU, install it from source or use the conda package.

For CPU:

pip install relik[faiss]

For GPU:

conda create -n relik python=3.10
conda activate relik

# install pytorch
conda install -y pytorch=2.1.0 pytorch-cuda=12.1 -c pytorch -c nvidia

# GPU
conda install -y -c pytorch -c nvidia faiss-gpu=1.8.0
# or GPU with NVIDIA RAFT
conda install -y -c pytorch -c nvidia -c rapidsai -c conda-forge faiss-gpu-raft=1.8.0

pip install relik

Install with optional dependencies for serving the models with FastAPI and Ray.

pip install relik[serve]
Installation from source
git clone https://github.com/SapienzaNLP/relik.git
cd relik
pip install -e .[all]

🤖 Models

New models:

Models from the paper:

A full list of models can be found on 🤗 Hugging Face.

Other models sizes will be available in the future 👀.

🚀 Quick Start

ReLiK is a lightweight and fast model for Entity Linking and Relation Extraction. It is composed of two main components: a retriever and a reader. The retriever is responsible for retrieving relevant documents from a large collection, while the reader is responsible for extracting entities and relations from the retrieved documents. ReLiK can be used with the from_pretrained method to load a pre-trained pipeline.

Here is an example of how to use ReLiK for Entity Linking:

from relik import Relik
from relik.inference.data.objects import RelikOutput

relik = Relik.from_pretrained("sapienzanlp/relik-entity-linking-large")
relik_out: RelikOutput = relik("Michael Jordan was one of the best players in the NBA.")

Output:

RelikOutput(
  text="Michael Jordan was one of the best players in the NBA.",
  tokens=['Michael', 'Jordan', 'was', 'one', 'of', 'the', 'best', 'players', 'in', 'the', 'NBA', '.'],
  id=0,
  spans=[
      Span(start=0, end=14, label="Michael Jordan", text="Michael Jordan"),
      Span(start=50, end=53, label="National Basketball Association", text="NBA"),
  ],
  triples=[],
  candidates=Candidates(
      span=[
          [
              [
                  {"text": "Michael Jordan", "id": 4484083},
                  {"text": "National Basketball Association", "id": 5209815},
                  {"text": "Walter Jordan", "id": 2340190},
                  {"text": "Jordan", "id": 3486773},
                  {"text": "50 Greatest Players in NBA History", "id": 1742909},
                  ...
              ]
          ]
      ]
  ),
)

and for Relation Extraction:

from relik import Relik
from relik.inference.data.objects import RelikOutput

relik = Relik.from_pretrained("sapienzanlp/relik-relation-extraction-nyt-large")
relik_out: RelikOutput = relik("Michael Jordan was one of the best players in the NBA.")

Output:

RelikOutput(
  text='Michael Jordan was one of the best players in the NBA.', 
  tokens=Michael Jordan was one of the best players in the NBA., 
  id=0, 
  spans=[
    Span(start=0, end=14, label='--NME--', text='Michael Jordan'), 
    Span(start=50, end=53, label='--NME--', text='NBA')
  ], 
  triplets=[
    Triplets(
      subject=Span(start=0, end=14, label='--NME--', text='Michael Jordan'), 
      label='company', 
      object=Span(start=50, end=53, label='--NME--', text='NBA'), 
      confidence=1.0
      )
  ], 
  candidates=Candidates(
    span=[], 
    triplet=[
              [
                [
                  {"text": "company", "id": 4, "metadata": {"definition": "company of this person"}}, 
                  {"text": "nationality", "id": 10, "metadata": {"definition": "nationality of this person or entity"}}, 
                  {"text": "child", "id": 17, "metadata": {"definition": "child of this person"}}, 
                  {"text": "founded by", "id": 0, "metadata": {"definition": "founder or co-founder of this organization, religion or place"}}, 
                  {"text": "residence", "id": 18, "metadata": {"definition": "place where this person has lived"}},
                  ...
              ]
          ]
      ]
  ),
)
Docker Images

Docker images for ReLiK are available on Docker Hub. You can pull the latest image with:

docker pull sapienzanlp/relik:latest

and run the image with:

docker run -p 12345:8000 sapienzanlp/relik:latest --config relik-ie/relik-cie-small

sapienzanlp/relik:latest points to the latest CUDA version of the model. To run with GPU support:

docker run -p 12345:8000 --gpus all sapienzanlp/relik:latest --config relik-ie/relik-cie-small --device cuda

If instead a GPU is not available, a CPU version of the image can be used:

docker run -p 12345:8000 sapienzanlp/relik:1.0.5-cpu-fastapi --config relik-ie/relik-cie-small

Tip: you can mount your .cache/huggingface folder to the docker container to avoid downloading the model weights every time you run the container.

docker run -p 12345:8000 -v ~/.cache/huggingface:/home/relik-user/.cache/huggingface sapienzanlp/relik:latest --config relik-ie/relik-cie-small

The API will be available at http://localhost:12345. It exposes a single endpoint /relik with several parameters that can be passed to the model. A quick documentation of the API can be found at http://localhost:12345/docs. Here is a simple example of how to query the API:

curl -X 'GET' \
  'http://127.0.0.1:12345/api/relik?text=Michael%20Jordan%20was%20one%20of%20the%20best%20players%20in%20the%20NBA.&is_split_into_words=false&retriever_batch_size=32&reader_batch_size=32&return_windows=false&use_doc_topic=false&annotation_type=char&relation_threshold=0.5' \
  -H 'accept: application/json'

Here the full list of parameters that can be passed to the docker image:

docker run sapienzanlp/relik:latest -h

Usage: relik [-h --help] [-c --config] [-p --precision] [-d --device] [--retriever] [--retriever-device] 
[--retriever-precision] [--index-device] [--index-precision] [--reader] [--reader-device] [--reader-precision] 
[--annotation-type] [--frontend] [--workers] -- start the FastAPI server for the RElik model

where:
    -h --help               Show this help text
    -c --config             Pretrained ReLiK config name (from HuggingFace) or path
    -p --precision          Precision, default '32'.
    -d --device             Device to use, default 'cpu'.
    --retriever             Override retriever model name.
    --retriever-device      Override retriever device.
    --retriever-precision   Override retriever precision.
    --index-device          Override index device.
    --index-precision       Override index precision.
    --reader                Override reader model name.
    --reader-device         Override reader device.
    --reader-precision      Override reader precision.
    --annotation-type       Annotation type ('char', 'word'), default 'char'.
    --frontend              Whether to start the frontend server.
    --workers               Number of workers to use.

📊 Performance

Entity Linking

We evaluate the performance of ReLiK on Entity Linking using GERBIL. The following table shows the results (InKB Micro F1) of ReLiK Large and Base:

ModelAIDAMSNBCDerK50R128R500O15O16TotOODAIT (m:s)
GENRE83.773.754.160.746.740.356.150.058.254.538:00
EntQA85.872.152.964.554.141.961.151.360.556.420:00
ReLiKsmall82.272.755.668.348.042.362.753.660.757.600:29
ReLiKBase85.372.355.668.048.141.662.552.360.757.200:29
ReLiKLarge86.475.056.372.851.743.065.157.263.460.201:46

Comparison systems' evaluation (InKB Micro F1) on the in-domain AIDA test set and out-of-domain MSNBC (MSN), Derczynski (Der), KORE50 (K50), N3-Reuters-128 (R128), N3-RSS-500 (R500), OKE-15 (O15), and OKE-16 (O16) test sets. Bold indicates the best model. GENRE uses mention dictionaries. The AIT column shows the time in minutes and seconds (m:s) that the systems need to process the whole AIDA test set using an NVIDIA RTX 4090, except for EntQA which does not fit in 24GB of RAM and for which an A100 is used.

To evaluate ReLiK we use the following steps:

  1. Download the GERBIL server from here.

  2. Start the GERBIL server:

cd gerbil && ./start.sh
  1. Start the following services:
cd gerbil-SpotWrapNifWS4Test && mvn clean -Dmaven.tomcat.port=1235 tomcat:run
  1. Start the ReLiK server for GERBIL providing the model name as an argument (e.g. sapienzanlp/relik-entity-linking-large):
python relik/reader/utils/gerbil.py --relik-model-name sapienzanlp/relik-entity-linking-large
  1. Open the URL http://localhost:1234/gerbil and:
    • Select A2KB as experiment type
    • Select "Ma - strong annotation match"
    • In the Name field write the name you want to give to the experiment
    • In the URI field write: http://localhost:1235/gerbil-spotWrapNifWS4Test/myalgorithm
    • Select the datasets (We use AIDA-B, MSNBC, Der, K50, R128, R500, OKE15, OKE16)
    • Finally, run experiment
Relation Extraction

The following table shows the results (Micro F1) of ReLiK Large on the NYT dataset:

ModelNYTNYT (Pretr)AIT (m:s)
REBEL93.193.401:45
UiE93.5----
USM94.094.1--
ReLiKLarge95.094.900:30

To evaluate Relation Extraction we can directly use the reader with the script relik/reader/trainer/predict_re.py, pointing at the file with already retrieved candidates. If you want to use our trained Reader:

python relik/reader/trainer/predict_re.py --model_path sapienzanlp/relik-reader-deberta-v3-large-nyt --data_path /Users/perelluis/Documents/relik/data/debug/test.window.candidates.jsonl --is-eval

Be aware that we compute the threshold for predicting relations based on the development set. To compute it while evaluating you can run the following:

python relik/reader/trainer/predict_re.py --model_path sapienzanlp/relik-reader-deberta-v3-large-nyt --data_path /Users/perelluis/Documents/relik/data/debug/dev.window.candidates.jsonl --is-eval --compute-threshold

💽 Cite this work

If you use any part of this work, please consider citing the paper as follows:

@inproceedings{orlando-etal-2024-relik,
    title     = "Retrieve, Read and LinK: Fast and Accurate Entity Linking and Relation Extraction on an Academic Budget",
    author    = "Orlando, Riccardo and Huguet Cabot, Pere-Llu{\'\i}s and Barba, Edoardo and Navigli, Roberto",
    booktitle = "Findings of the Association for Computational Linguistics: ACL 2024",
    month     = aug,
    year      = "2024",
    address   = "Bangkok, Thailand",
    publisher = "Association for Computational Linguistics",
}

🪪 License

The data and software are licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0.

Tag summary

Content type

Image

Digest

sha256:b40e87885

Size

3.1 GB

Last updated

about 2 years ago

docker pull sapienzanlp/relik