• Stars
    star
    3,238
  • Rank 13,856 (Top 0.3 %)
  • Language
    Python
  • License
    Other
  • Created about 6 years ago
  • Updated over 1 year ago

Reviews

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

Repository Details

Generate embeddings from large-scale graph-structured data.

PyTorch-BigGraph

Support Ukraine CircleCI Status Documentation Status

PyTorch-BigGraph (PBG) is a distributed system for learning graph embeddings for large graphs, particularly big web interaction graphs with up to billions of entities and trillions of edges.

PBG was introduced in the PyTorch-BigGraph: A Large-scale Graph Embedding Framework paper, presented at the SysML conference in 2019.

Update: PBG now supports GPU training. Check out the GPU Training section below!

Overview

PBG trains on an input graph by ingesting its list of edges, each identified by its source and target entities and, possibly, a relation type. It outputs a feature vector (embedding) for each entity, trying to place adjacent entities close to each other in the vector space, while pushing unconnected entities apart. Therefore, entities that have a similar distribution of neighbors will end up being nearby.

It is possible to configure each relation type to calculate this "proximity score" in a different way, with the parameters (if any) learned during training. This allows the same underlying entity embeddings to be shared among multiple relation types.

The generality and extensibility of its model allows PBG to train a number of models from the knowledge graph embedding literature, including TransE, RESCAL, DistMult and ComplEx.

PBG is designed with scale in mind, and achieves it through:

  • graph partitioning, so that the model does not have to be fully loaded into memory
  • multi-threaded computation on each machine
  • distributed execution across multiple machines (optional), all simultaneously operating on disjoint parts of the graph
  • batched negative sampling, allowing for processing >1 million edges/sec/machine with 100 negatives per edge

PBG is not optimized for small graphs. If your graph has fewer than 100,000 nodes, consider using KBC with the ComplEx model and N3 regularizer. KBC produces state-of-the-art embeddings for graphs that can fit on a single GPU. Compared to KBC, PyTorch-BigGraph enables learning on very large graphs whose embeddings wouldn't fit in a single GPU or a single machine, but may not produce high-quality embeddings for small graphs without careful tuning.

Requirements

PBG is written in Python (version 3.6 or later) and relies on PyTorch (at least version 1.0) and a few other libraries.

All computations are performed on the CPU, therefore a large number of cores is advisable. No GPU is necessary.

When running on multiple machines, they need to be able to communicate to each other at high bandwidth (10 Gbps or higher recommended) and have access to a shared filesystem (for checkpointing). PBG uses torch.distributed, which uses the Gloo package which runs on top of TCP or MPI.

Installation

Clone the repository (or download it as an archive) and, inside the top-level directory, run:

pip install .

PyTorch-BigGraph includes some C++ kernels that are only used for the experimental GPU mode. If you want to use GPU mode, compile the C++ code as follows:

PBG_INSTALL_CPP=1 pip install .

Everything will work identically except that you will be able to run GPU training (torchbiggraph_train_gpu).

The results of the paper can easily be reproduced by running the following command (which executes this script):

torchbiggraph_example_fb15k

This will download the Freebase 15k knowledge base dataset, put it into the right format, train on it using the ComplEx model and finally perform an evaluation of the learned embeddings that calculates the MRR and other metrics that should match the paper. Another command, torchbiggraph_example_livejournal, does the same for the LiveJournal interaction graph dataset.

To learn how to use PBG, let us walk through what the FB15k script does.

Getting started

Downloading the data

First, it retrieves the dataset and unpacks it, obtaining a directory with three edge sets as TSV files, for training, validation and testing.

wget https://dl.fbaipublicfiles.com/starspace/fb15k.tgz -P data
tar xf data/fb15k.tgz -C data

Each line of these files contains information about one edge. Using tabs as separators, the lines are divided into columns which contain the identifiers of the source entities, the relation types and the target entities. For example:

/m/027rn	/location/country/form_of_government	/m/06cx9
/m/017dcd	/tv/tv_program/regular_cast./tv/regular_tv_appearance/actor	/m/06v8s0
/m/07s9rl0	/media_common/netflix_genre/titles	/m/0170z3
/m/01sl1q	/award/award_winner/awards_won./award/award_honor/award_winner	/m/044mz_
/m/0cnk2q	/soccer/football_team/current_roster./sports/sports_team_roster/position	/m/02nzb8

Preparing the data

Then, the script converts the edge lists to PBG's input format. This amounts to assigning a numerical identifier to all entities and relation types, shuffling and partitioning the entities and edges and writing all down in the right format.

Luckily, there is a command that does all of this:

torchbiggraph_import_from_tsv \
  --lhs-col=0 --rel-col=1 --rhs-col=2 \
  torchbiggraph/examples/configs/fb15k_config_cpu.py \
  data/FB15k/freebase_mtr100_mte100-train.txt \
  data/FB15k/freebase_mtr100_mte100-valid.txt \
  data/FB15k/freebase_mtr100_mte100-test.txt

The outputs will be stored next to the inputs in the data/FB15k directory.

This simple utility is only suitable for small graphs that fit entirely in memory. To handle larger data one will have to implement their own custom preprocessor.

Training

The torchbiggraph_train command is used to launch training. The training parameters are tucked away in a configuration file, whose path is given to the command. They can however be overridden from the command line with the --param flag. The sample config is used for both training and evaluation, so we will have to use the override to specify the edge set to use.

torchbiggraph_train \
  torchbiggraph/examples/configs/fb15k_config_cpu.py \
  -p edge_paths=data/FB15k/freebase_mtr100_mte100-train_partitioned

This will read data from the entity_path directory specified in the configuration and the edge_paths directory given on the command line. It will write checkpoints (which also double as the output data) to the checkpoint_path directory also defined in the configuration, which in this case is model/fb15k.

Training will proceed for 50 epochs in total, with the progress and some statistics logged to the console, for example:

Starting epoch 1 / 50, edge path 1 / 1, edge chunk 1 / 1
Edge path: data/FB15k/freebase_mtr100_mte100-train_partitioned
still in queue: 0
Swapping partitioned embeddings None ( 0 , 0 )
( 0 , 0 ): Loading entities
( 0 , 0 ): bucket 1 / 1 : Processed 483142 edges in 17.36 s ( 0.028 M/sec ); io: 0.02 s ( 542.52 MB/sec )
( 0 , 0 ): loss:  309.695 , violators_lhs:  171.846 , violators_rhs:  165.525 , count:  483142
Swapping partitioned embeddings ( 0 , 0 ) None
Writing partitioned embeddings
Finished epoch 1 / 50, edge path 1 / 1, edge chunk 1 / 1
Writing the metadata
Writing the checkpoint
Switching to the new checkpoint version

GPU Training

Warning: GPU Training is still experimental; expect sharp corners and lack of documentation.

torchbiggraph_example_fb15k will automatically detect if a GPU is available and run with the GPU training config. For your own training runs, you will need to change a few parameters to enable GPU training. Lets see how the two FB15k configs differ:

$ diff torchbiggraph/examples/configs/fb15k_config_cpu.py torchbiggraph/examples/configs/fb15k_config_gpu.py
37a38
>         batch_size=10000,
42a44,45
>         # GPU
>         num_gpus=1,

The most important difference is of course num_gpus=1, which says to run on 1 GPU. If num_gpus=N>1, PBG will recursively shard the embeddings within each partition into N subpartitions to run on multiple GPUs. The subpartitions need to fit in GPU memory, so if you get CUDA out-of-memory errors, you'll need to increase num_partitions or num_gpus.

The next most important difference for GPU training is that batch_size must be much larger. Since training is being performed on a single GPU instead of 40 cores, the batch size can be increased by about that factor as well. We suggest batch size of around 100,000 in order to achieve good speeds for GPU training.

Since evaluation still occurs on CPU, we suggest turning down eval_fraction to at most 0.01 so that evaluation does not become a bottleneck (not relevant for FB15k which doesn't do eval during training).

Finally, to take advantage of GPU speed, we suggest turning up num_uniform_negatives and/or num_batch_negatives to about 1000 rather than their default values of 50 (FB15k already uses 1000 uniform negatives).

Evaluation

Once training is complete, the entity embeddings it produced can be evaluated against a held-out edge set. The torchbiggraph_example_fb15k command performs a filtered evaluation, which calculates the ranks of the edges in the evaluation set by comparing them against all other edges except the ones that are true positives in any of the training, validation or test set. Filtered evaluation is used in the literature for FB15k, but does not scale beyond small graphs.

The final results should match the values of mrr (Mean Reciprocal Rank, MRR) and r10 (Hits@10) reported in the paper:

Stats: pos_rank:  65.4821 , mrr:  0.789921 , r1:  0.738501 , r10:  0.876894 , r50:  0.92647 , auc:  0.989868 , count:  59071

Evaluation can also be run directly from the command line as follows:

torchbiggraph_eval \
  torchbiggraph/examples/configs/fb15k_config_cpu.py \
  -p edge_paths=data/FB15k/freebase_mtr100_mte100-test_partitioned \
  -p relations.0.all_negs=true \
  -p num_uniform_negs=0

However, filtered evaluation cannot be performed on the command line, so the reported results will not match the paper. They will be something like:

Stats: pos_rank:  234.136 , mrr:  0.239957 , r1:  0.131757 , r10:  0.485382 , r50:  0.712693 , auc:  0.989648 , count:  59071

Converting the output

During preprocessing, the entities and relation types had their identifiers converted from strings to ordinals. In order to map the output embeddings back onto the original names, one can do:

torchbiggraph_export_to_tsv \
  torchbiggraph/examples/configs/fb15k_config.py \
  --entities-output entity_embeddings.tsv \
  --relation-types-output relation_types_parameters.tsv

This will create the entity_embeddings.tsv file, which is a text file where each line contains the identifier of an entity followed respectively by the components of its embedding, each in a different column, all separated by tabs. For example, with each line shortened for brevity:

/m/0fphf3v	-0.524391472	-0.016430536	-0.461346656	-0.394277513	0.125605106	...
/m/01bns_	-0.122734159	-0.091636233	0.506501377	-0.503864646	0.215775326	...
/m/02ryvsw	-0.107151665	0.002058491	-0.094485454	-0.129078045	-0.123694092	...
/m/04y6_qr	-0.577532947	-0.215747222	-0.022358289	-0.352154016	-0.051905245	...
/m/02wrhj	-0.593656778	-0.557167351	0.042525314	-0.104738958	-0.265990764	...

It will also create a relation_types_parameters.tsv file which contains the parameters of the operators for the relation types. The format is similar to the above, but each line starts with more key columns containing, respectively, the name of a relation type, a side (lhs or rhs), the name of the operator which is used by that relation type on that side, the name of a parameter of that operator and the shape of the parameter (integers separated by x). These columns are followed by the values of the flattened parameter. For example, for two relation types, foo and bar, respectively using operators linear and complex_diagonal, with an embedding dimension of 200 and dynamic relations enabled, this file could look like:

foo	lhs	linear	linear_transformation	200x200	-0.683401227	0.209822774	-0.047136042	...
foo	rhs	linear	linear_transformation	200x200	-0.695254087	0.502532542	-0.131654695	...
bar	lhs	complex_diagonal	real	200	0.263731539	1.350529909	1.217602968	...
bar	lhs	complex_diagonal	imag	200	-0.089371338	-0.092713356	0.025076168	...
bar	rhs	complex_diagonal	real	200	-2.350617170	0.529571176	0.521403074	...
bar	rhs	complex_diagonal	imag	200	0.692483306	0.446569800	0.235914066	...

Pre-trained embeddings

We trained a PBG model on the full Wikidata graph, using a translation operator to represent relations. It can be downloaded here (36GiB, gzip-compressed). We used the truthy version of data from here to train our model. The model file is in TSV format as described in the above section. Note that the first line of the file contains the number of entities, the number of relations and the dimension of the embeddings, separated by tabs. The model contains 78 million entities, 4,131 relations and the dimension of the embeddings is 200.

Documentation

More information can be found in the full documentation.

Communication

  • GitHub Issues: Bug reports, feature requests, install issues, etc.
  • The PyTorch-BigGraph Slack is a forum for online discussion between developers and users, discussing features, collaboration, etc.

Citation

To cite this work please use:

@inproceedings{pbg,
  title={{PyTorch-BigGraph: A Large-scale Graph Embedding System}},
  author={Lerer, Adam and Wu, Ledell and Shen, Jiajun and Lacroix, Timothee and Wehrstedt, Luca and Bose, Abhijit and Peysakhovich, Alex},
  booktitle={Proceedings of the 2nd SysML Conference},
  year={2019},
  address={Palo Alto, CA, USA}
}

License

PyTorch-BigGraph is BSD licensed, as found in the LICENSE.txt file.

More Repositories

1

llama

Inference code for LLaMA models
Python
44,989
star
2

segment-anything

The repository provides code for running inference with the SegmentAnything Model (SAM), links for downloading the trained model checkpoints, and example notebooks that show how to use the model.
Jupyter Notebook
42,134
star
3

Detectron

FAIR's research platform for object detection research, implementing popular algorithms like Mask R-CNN and RetinaNet.
Python
25,771
star
4

fairseq

Facebook AI Research Sequence-to-Sequence Toolkit written in Python.
Python
25,718
star
5

detectron2

Detectron2 is a platform for object detection, segmentation and other visual recognition tasks.
Python
25,567
star
6

fastText

Library for fast text representation and classification.
HTML
24,973
star
7

faiss

A library for efficient similarity search and clustering of dense vectors.
C++
24,035
star
8

audiocraft

Audiocraft is a library for audio processing and generation with deep learning. It features the state-of-the-art EnCodec audio compressor / tokenizer, along with MusicGen, a simple and controllable music generation LM with textual and melodic conditioning.
Python
19,691
star
9

codellama

Inference code for CodeLlama models
Python
13,303
star
10

sam2

The repository provides code for running inference with the Meta Segment Anything Model 2 (SAM 2), links for downloading the trained model checkpoints, and example notebooks that show how to use the model.
Jupyter Notebook
11,906
star
11

detr

End-to-End Object Detection with Transformers
Python
11,076
star
12

seamless_communication

Foundational Models for State-of-the-Art Speech and Text Translation
Jupyter Notebook
10,584
star
13

ParlAI

A framework for training and evaluating AI models on a variety of openly available dialogue datasets.
Python
10,085
star
14

maskrcnn-benchmark

Fast, modular reference implementation of Instance Segmentation and Object Detection algorithms in PyTorch.
Python
9,104
star
15

pifuhd

High-Resolution 3D Human Digitization from A Single Image.
Python
8,923
star
16

hydra

Hydra is a framework for elegantly configuring complex applications
Python
8,550
star
17

nougat

Implementation of Nougat Neural Optical Understanding for Academic Documents
Python
8,088
star
18

AnimatedDrawings

Code to accompany "A Method for Animating Children's Drawings of the Human Figure"
Python
8,032
star
19

ImageBind

ImageBind One Embedding Space to Bind Them All
Python
7,630
star
20

llama-recipes

Scripts for fine-tuning Llama2 with composable FSDP & PEFT methods to cover single/multi-node GPUs. Supports default & custom datasets for applications such as summarization & question answering. Supporting a number of candid inference solutions such as HF TGI, VLLM for local or cloud deployment.Demo apps to showcase Llama2 for WhatsApp & Messenger
Jupyter Notebook
7,402
star
21

pytorch3d

PyTorch3D is FAIR's library of reusable components for deep learning with 3D data
Python
7,322
star
22

dinov2

PyTorch code and models for the DINOv2 self-supervised learning method.
Jupyter Notebook
7,278
star
23

DensePose

A real-time approach for mapping all human pixels of 2D RGB images to a 3D surface-based model of the body
Jupyter Notebook
6,547
star
24

pytext

A natural language modeling framework based on PyTorch
Python
6,357
star
25

DiT

Official PyTorch Implementation of "Scalable Diffusion Models with Transformers"
Python
5,995
star
26

metaseq

Repo for external large-scale work
Python
5,947
star
27

demucs

Code for the paper Hybrid Spectrogram and Waveform Source Separation
Python
5,886
star
28

SlowFast

PySlowFast: video understanding codebase from FAIR for reproducing state-of-the-art video models.
Python
5,678
star
29

mae

PyTorch implementation of MAE https//arxiv.org/abs/2111.06377
Python
5,495
star
30

mmf

A modular framework for vision & language multimodal research from Facebook AI Research (FAIR)
Python
5,235
star
31

ConvNeXt

Code release for ConvNeXt model
Python
4,971
star
32

dino

PyTorch code for Vision Transformers training with the Self-Supervised learning method DINO
Python
4,830
star
33

AugLy

A data augmentations library for audio, image, text, and video.
Python
4,739
star
34

Kats

Kats, a kit to analyze time series data, a lightweight, easy-to-use, generalizable, and extendable framework to perform time series analysis, from understanding the key statistics and characteristics, detecting change points and anomalies, to forecasting future trends.
Python
4,387
star
35

DrQA

Reading Wikipedia to Answer Open-Domain Questions
Python
4,374
star
36

sapiens

High-resolution models for human tasks.
Python
4,340
star
37

xformers

Hackable and optimized Transformers building blocks, supporting a composable construction.
Python
4,191
star
38

moco

PyTorch implementation of MoCo: https://arxiv.org/abs/1911.05722
Python
4,035
star
39

StarSpace

Learning embeddings for classification, retrieval and ranking.
C++
3,856
star
40

lingua

Meta Lingua: a lean, efficient, and easy-to-hack codebase to research LLMs.
Python
3,829
star
41

fairseq-lua

Facebook AI Research Sequence-to-Sequence Toolkit
Lua
3,765
star
42

nevergrad

A Python toolbox for performing gradient-free optimization
Python
3,446
star
43

deit

Official DeiT repository
Python
3,425
star
44

dlrm

An implementation of a deep learning recommendation model (DLRM)
Python
3,417
star
45

ReAgent

A platform for Reasoning systems (Reinforcement Learning, Contextual Bandits, etc.)
Python
3,395
star
46

LASER

Language-Agnostic SEntence Representations
Python
3,308
star
47

VideoPose3D

Efficient 3D human pose estimation in video using 2D keypoint trajectories
Python
3,294
star
48

deepmask

Torch implementation of DeepMask and SharpMask
Lua
3,113
star
49

MUSE

A library for Multilingual Unsupervised or Supervised word Embeddings
Python
3,094
star
50

vissl

VISSL is FAIR's library of extensible, modular and scalable components for SOTA Self-Supervised Learning with images.
Jupyter Notebook
3,038
star
51

pytorchvideo

A deep learning library for video understanding research.
Python
2,885
star
52

XLM

PyTorch original implementation of Cross-lingual Language Model Pretraining.
Python
2,763
star
53

audio2photoreal

Code and dataset for photorealistic Codec Avatars driven from audio
Python
2,696
star
54

ijepa

Official codebase for I-JEPA, the Image-based Joint-Embedding Predictive Architecture. First outlined in the CVPR paper, "Self-supervised learning from images with a joint-embedding predictive architecture."
Python
2,670
star
55

jepa

PyTorch code and models for V-JEPA self-supervised learning from video.
Python
2,646
star
56

habitat-sim

A flexible, high-performance 3D simulator for Embodied AI research.
C++
2,621
star
57

co-tracker

CoTracker is a model for tracking any point (pixel) on a video.
Jupyter Notebook
2,564
star
58

hiplot

HiPlot makes understanding high dimensional data easy
TypeScript
2,481
star
59

fairscale

PyTorch extensions for high performance and large scale training.
Python
2,319
star
60

encodec

State-of-the-art deep learning based audio codec supporting both mono 24 kHz audio and stereo 48 kHz audio.
Python
2,313
star
61

InferSent

InferSent sentence embeddings
Jupyter Notebook
2,264
star
62

Pearl

A Production-ready Reinforcement Learning AI Agent Library brought by the Applied Reinforcement Learning team at Meta.
Python
2,193
star
63

pyrobot

PyRobot: An Open Source Robotics Research Platform
Python
2,109
star
64

darkforestGo

DarkForest, the Facebook Go engine.
C
2,108
star
65

ELF

An End-To-End, Lightweight and Flexible Platform for Game Research
C++
2,089
star
66

pycls

Codebase for Image Classification Research, written in PyTorch.
Python
2,053
star
67

esm

Evolutionary Scale Modeling (esm): Pretrained language models for proteins
Python
2,026
star
68

frankmocap

A Strong and Easy-to-use Single View 3D Hand+Body Pose Estimator
Python
1,972
star
69

video-nonlocal-net

Non-local Neural Networks for Video Classification
Python
1,931
star
70

SentEval

A python tool for evaluating the quality of sentence embeddings.
Python
1,930
star
71

habitat-lab

A modular high-level library to train embodied AI agents across a variety of tasks and environments.
Python
1,867
star
72

ResNeXt

Implementation of a classification framework from the paper Aggregated Residual Transformations for Deep Neural Networks
Lua
1,863
star
73

SparseConvNet

Submanifold sparse convolutional networks
C++
1,847
star
74

schedule_free

Schedule-Free Optimization in PyTorch
Python
1,842
star
75

chameleon

Repository for Meta Chameleon, a mixed-modal early-fusion foundation model from FAIR.
Python
1,811
star
76

swav

PyTorch implementation of SwAV https//arxiv.org/abs/2006.09882
Python
1,790
star
77

TensorComprehensions

A domain specific language to express machine learning workloads.
C++
1,747
star
78

Mask2Former

Code release for "Masked-attention Mask Transformer for Universal Image Segmentation"
Python
1,638
star
79

fvcore

Collection of common code that's shared among different research projects in FAIR computer vision team.
Python
1,623
star
80

TransCoder

Public release of the TransCoder research project https://arxiv.org/pdf/2006.03511.pdf
Python
1,611
star
81

poincare-embeddings

PyTorch implementation of the NIPS-17 paper "Poincarรฉ Embeddings for Learning Hierarchical Representations"
Python
1,587
star
82

votenet

Deep Hough Voting for 3D Object Detection in Point Clouds
Python
1,563
star
83

pytorch_GAN_zoo

A mix of GAN implementations including progressive growing
Python
1,554
star
84

ClassyVision

An end-to-end PyTorch framework for image and video classification
Python
1,552
star
85

deepcluster

Deep Clustering for Unsupervised Learning of Visual Features
Python
1,544
star
86

higher

higher is a pytorch library allowing users to obtain higher order gradients over losses spanning training loops rather than individual training steps.
Python
1,524
star
87

UnsupervisedMT

Phrase-Based & Neural Unsupervised Machine Translation
Python
1,496
star
88

consistent_depth

We estimate dense, flicker-free, geometrically consistent depth from monocular video, for example hand-held cell phone video.
Python
1,479
star
89

ConvNeXt-V2

Code release for ConvNeXt V2 model
Python
1,454
star
90

Detic

Code release for "Detecting Twenty-thousand Classes using Image-level Supervision".
Python
1,446
star
91

end-to-end-negotiator

Deal or No Deal? End-to-End Learning for Negotiation Dialogues
Python
1,368
star
92

DomainBed

DomainBed is a suite to test domain generalization algorithms
Python
1,355
star
93

multipathnet

A Torch implementation of the object detection network from "A MultiPath Network for Object Detection" (https://arxiv.org/abs/1604.02135)
Lua
1,349
star
94

CommAI-env

A platform for developing AI systems as described in A Roadmap towards Machine Intelligence - http://arxiv.org/abs/1511.08130
1,324
star
95

theseus

A library for differentiable nonlinear optimization
Python
1,306
star
96

DPR

Dense Passage Retriever - is a set of tools and models for open domain Q&A task.
Python
1,292
star
97

CrypTen

A framework for Privacy Preserving Machine Learning
Python
1,283
star
98

denoiser

Real Time Speech Enhancement in the Waveform Domain (Interspeech 2020)We provide a PyTorch implementation of the paper Real Time Speech Enhancement in the Waveform Domain. In which, we present a causal speech enhancement model working on the raw waveform that runs in real-time on a laptop CPU. The proposed model is based on an encoder-decoder architecture with skip-connections. It is optimized on both time and frequency domains, using multiple loss functions. Empirical evidence shows that it is capable of removing various kinds of background noise including stationary and non-stationary noises, as well as room reverb. Additionally, we suggest a set of data augmentation techniques applied directly on the raw waveform which further improve model performance and its generalization abilities.
Python
1,272
star
99

DeepSDF

Learning Continuous Signed Distance Functions for Shape Representation
Python
1,191
star
100

TimeSformer

The official pytorch implementation of our paper "Is Space-Time Attention All You Need for Video Understanding?"
Python
1,172
star