(Personalized) Page-Rank computation using PyTorch

Overview

torch-ppr

Tests PyPI PyPI - Python Version PyPI - License Documentation Status Codecov status Cookiecutter template from @cthoyt Code style: black Contributor Covenant

This package allows calculating page-rank and personalized page-rank via power iteration with PyTorch, which also supports calculation on GPU (or other accelerators).

πŸ’ͺ Getting Started

As a simple example, consider this simple graph with five nodes.

Its edge list is given as

>>> import torch
>>> edge_index = torch.as_tensor(data=[(0, 1), (1, 2), (1, 3), (2, 4)]).t()

We can use

>>> from torch_ppr import page_rank
>>> page_rank(edge_index=edge_index)
tensor([0.1269, 0.3694, 0.2486, 0.1269, 0.1281])

to calculate the page rank, i.e., a measure of global importance. We notice that the central node receives the largest importance score, while all other nodes have lower importance. Moreover, the two indistinguishable nodes 0 and 3 receive the same page rank.

We can also calculate personalized page rank which measures importance from the perspective of a single node. For instance, for node 2, we have

>>> from torch_ppr import personalized_page_rank
>>> personalized_page_rank(edge_index=edge_index, indices=[2])
tensor([[0.1103, 0.3484, 0.2922, 0.1103, 0.1388]])

Thus, the most important node is the central node 1, nodes 0 and 3 receive the same importance value which is below the value of the direct neighbor 4.

By the virtue of using PyTorch, the code seamlessly works on GPUs, too, and supports auto-grad differentiation. Moreover, the calculation of personalized page rank supports automatic batch size optimization via torch_max_mem.

πŸš€ Installation

The most recent release can be installed from PyPI with:

$ pip install torch_ppr

The most recent code and data can be installed directly from GitHub with:

$ pip install git+https://github.com/mberr/torch-ppr.git

πŸ‘ Contributing

Contributions, whether filing an issue, making a pull request, or forking, are appreciated. See CONTRIBUTING.md for more information on getting involved.

πŸ‘‹ Attribution

βš–οΈ License

The code in this package is licensed under the MIT License.

πŸͺ Cookiecutter

This package was created with @audreyfeldroy's cookiecutter package using @cthoyt's cookiecutter-snekpack template.

πŸ› οΈ For Developers

See developer instructions

The final section of the README is for if you want to get involved by making a code contribution.

Development Installation

To install in development mode, use the following:

$ git clone git+https://github.com/mberr/torch-ppr.git
$ cd torch-ppr
$ pip install -e .

πŸ₯Ό Testing

After cloning the repository and installing tox with pip install tox, the unit tests in the tests/ folder can be run reproducibly with:

$ tox

Additionally, these tests are automatically re-run with each commit in a GitHub Action.

πŸ“– Building the Documentation

The documentation can be built locally using the following:

$ git clone git+https://github.com/mberr/torch-ppr.git
$ cd torch-ppr
$ tox -e docs
$ open docs/build/html/index.html

The documentation automatically installs the package as well as the docs extra specified in the setup.cfg. sphinx plugins like texext can be added there. Additionally, they need to be added to the extensions list in docs/source/conf.py.

πŸ“¦ Making a Release

After installing the package in development mode and installing tox with pip install tox, the commands for making a new release are contained within the finish environment in tox.ini. Run the following from the shell:

$ tox -e finish

This script does the following:

  1. Uses Bump2Version to switch the version number in the setup.cfg, src/torch_ppr/version.py, and docs/source/conf.py to not have the -dev suffix
  2. Packages the code in both a tar archive and a wheel using build
  3. Uploads to PyPI using twine. Be sure to have a .pypirc file configured to avoid the need for manual input at this step
  4. Push to GitHub. You'll need to make a release going with the commit where the version was bumped.
  5. Bump the version to the next patch. If you made big changes and want to bump the version by minor, you can use tox -e bumpversion minor after.
Comments
  • `torch.sparse.mm` breaking API changes

    `torch.sparse.mm` breaking API changes

    Suddenly, everything stopped working 😱 presumably because of the changes to torch.sparse. Particularly, I am on PyTorch 1.10, master branch of PyKEEN and torch-ppr 0.0.5.

    Problem 1: the allclose() check does not pass now: https://github.com/mberr/torch-ppr/blob/921898f1a4b7770e6cdd1931e935262e456eb3c9/src/torch_ppr/utils.py#L221-L222

    MWE:

    import torch
    from torch_ppr import page_rank
    
    from pykeen.datasets import FB15k237
    
    dataset = FB15k237(create_inverse_triples=False)
    edges = dataset.training.mapped_triples[:, [0, 2]].t()
    pr = page_rank(edge_index=torch.cat([edges, edges.flip(0)], dim=-1), num_nodes=dataset.num_entities)
    
    >> ValueError: Invalid column sum: tensor([1.0000, 1.0000, 1.0000,  ..., 1.0000, 1.0000, 1.0000]). expected 1.0
    

    Looking into the debugger:

    • adj_sum does sum up to the number of nodes
    • the default tolerance fails the check, but if I reduce rtol=1e-4 or atol=1e-4 - the check passes

    Problem 2: the signature of torch.sparse.addmm has changed from the one used in power_iteration so the API call fails with the unknown kwarg error.

    https://github.com/mberr/torch-ppr/blob/921898f1a4b7770e6cdd1931e935262e456eb3c9/src/torch_ppr/utils.py#L310

    In fact, I can't find where those kwargs input, sparse, dense come from because the current signature has less readable mat, mat1, mat2. I traced to the very Torch 1.3.0 and still can't find where those originated from. Where does this signature come from? πŸ˜…

    My test env

    torch                 1.10.0
    torch-ppr             0.0.5
    
    opened by migalkin 7
  • Incorporating edge weights

    Incorporating edge weights

    Hello,

    Thank you for this great repository; it is a great, handy package that performs very well! I was wondering however; is it possible to incorporate edge weights into the personalized pagerank method?

    Best Filip

    opened by Filco306 5
  • RuntimeError torch.sparse.addmm different torch tensor shape

    RuntimeError torch.sparse.addmm different torch tensor shape

    Dear torch-ppr

    I installed torch-ppr on my Mac with python 3.9 and run the example code

    >>> import torch
    >>> edge_index = torch.as_tensor(data=[(0, 1), (1, 2), (1, 3), (2, 4)]).t()
    >>> from torch_ppr import page_rank
    >>> page_rank(edge_index)
    

    I got a runtimeerror as

    x = torch.sparse.addmm(input=x0, sparse=adj, dense=x, beta=alpha, alpha=beta)
    RuntimeError: mat1 and mat2 shapes cannot be multiplied (2x4 and 2x1)
    

    I printed the shape of x0, adj and x

    torch.Size([2, 1])
    torch.Size([2, 4])
    torch.Size([2, 1])
    

    I believe that the shape of adj should be 2x2 or I might be wrong. I find the define process of adj.

    # convert to sparse matrix, shape: (n, n)
    adj = edge_index_to_sparse_matrix(edge_index=edge_index, num_nodes=num_nodes)
    adj = adj + adj.t()
    

    The adj is symmect.

    I wonder how to fix the runtimeError or any suggestions? Thanks in advanced meatball1982 12-May-2022 09:54:50

    opened by meatball1982 4
  • Expose API functions from top-level

    Expose API functions from top-level

    Also update cookiecutter package in https://github.com/cthoyt/cookiecutter-snekpack/commit/fa032ffc3c718c208d3a03e212aaa299c193de94 to have this be a part by default

    opened by cthoyt 2
  • Formulate page-rank as a torch.nn Layer

    Formulate page-rank as a torch.nn Layer

    Thank you for this repo!

    The reason to request a 'layer' fomulation is to convert the function page_rank to an onnx graph with torch.onnx (only accepts models).

    Once I have the onnx model, I can compile it different hardware (other than cuda).

    Maybe need just the forward pass, no need for a backward pass although I think the compute will be differentiable.

    Thanks.

    opened by LM-AuroTripathy 8
Releases(v0.0.8)
  • v0.0.8(Jul 20, 2022)

    What's Changed

    • Update error message of validate_adjacency by @mberr in https://github.com/mberr/torch-ppr/pull/18
    • Add option to add identity matrix by @mberr in https://github.com/mberr/torch-ppr/pull/20

    Full Changelog: https://github.com/mberr/torch-ppr/compare/v0.0.7...v0.0.8

    Source code(tar.gz)
    Source code(zip)
  • v0.0.7(Jun 29, 2022)

    What's Changed

    • Fix torch 1.12 compat by @mberr in https://github.com/mberr/torch-ppr/pull/17

    Full Changelog: https://github.com/mberr/torch-ppr/compare/v0.0.6...v0.0.7

    Source code(tar.gz)
    Source code(zip)
  • v0.0.6(Jun 29, 2022)

    What's Changed

    • Fix language tag in docs by @cthoyt in https://github.com/mberr/torch-ppr/pull/13
    • Fix torch.sparse.addmm use by @mberr in https://github.com/mberr/torch-ppr/pull/12
    • Enable CI on multiple versions of pytorch by @cthoyt in https://github.com/mberr/torch-ppr/pull/14
    • Improve sparse CSR support by @mberr in https://github.com/mberr/torch-ppr/pull/15
    • Increase numerical tolerance by @mberr in https://github.com/mberr/torch-ppr/pull/16

    Full Changelog: https://github.com/mberr/torch-ppr/compare/v0.0.5...v0.0.6

    Source code(tar.gz)
    Source code(zip)
  • v0.0.5(May 12, 2022)

    What's Changed

    • Improve input validation by @mberr in https://github.com/mberr/torch-ppr/pull/10

    Full Changelog: https://github.com/mberr/torch-ppr/compare/v0.0.4...v0.0.5

    Source code(tar.gz)
    Source code(zip)
  • v0.0.4(May 10, 2022)

    What's Changed

    • Expose num_nodes parameter by @mberr in https://github.com/mberr/torch-ppr/pull/8

    Full Changelog: https://github.com/mberr/torch-ppr/compare/v0.0.3...v0.0.4

    Source code(tar.gz)
    Source code(zip)
  • v0.0.3(May 10, 2022)

    What's Changed

    • Add imports to code examples in README by @cthoyt in https://github.com/mberr/torch-ppr/pull/6
    • Expose API functions from top-level by @cthoyt in https://github.com/mberr/torch-ppr/pull/7

    New Contributors

    • @cthoyt made their first contribution in https://github.com/mberr/torch-ppr/pull/6

    Full Changelog: https://github.com/mberr/torch-ppr/compare/v0.0.2...v0.0.3

    Source code(tar.gz)
    Source code(zip)
  • v0.0.2(May 9, 2022)

    What's Changed

    • Fix device resolution order by @mberr in https://github.com/mberr/torch-ppr/pull/5

    Full Changelog: https://github.com/mberr/torch-ppr/compare/v0.0.1...v0.0.2

    Source code(tar.gz)
    Source code(zip)
  • v0.0.1(May 6, 2022)

Owner
Max Berrendorf
Max Berrendorf
Automatic Data-Regularized Actor-Critic (Auto-DrAC)

Auto-DrAC: Automatic Data-Regularized Actor-Critic This is a PyTorch implementation of the methods proposed in Automatic Data Augmentation for General

89 Dec 13, 2022
A model that attempts to learn and benefit from data collected on card counting.

A model that attempts to learn and benefit from data collected on card counting. A decision tree like model is built to win more often than loose and increase the bet of the player appropriately to c

1 Dec 17, 2021
Spectral Temporal Graph Neural Network (StemGNN in short) for Multivariate Time-series Forecasting

Spectral Temporal Graph Neural Network for Multivariate Time-series Forecasting This repository is the official implementation of Spectral Temporal Gr

Microsoft 306 Dec 29, 2022
MINOS: Multimodal Indoor Simulator

MINOS Simulator MINOS is a simulator designed to support the development of multisensory models for goal-directed navigation in complex indoor environ

194 Dec 27, 2022
Code for "My(o) Armband Leaks Passwords: An EMG and IMU Based Keylogging Side-Channel Attack" paper

Myo Keylogging This is the source code for our paper My(o) Armband Leaks Passwords: An EMG and IMU Based Keylogging Side-Channel Attack by Matthias Ga

Secure Mobile Networking Lab 7 Jan 03, 2023
Fast SHAP value computation for interpreting tree-based models

FastTreeSHAP FastTreeSHAP package is built based on the paper Fast TreeSHAP: Accelerating SHAP Value Computation for Trees published in NeurIPS 2021 X

LinkedIn 369 Jan 04, 2023
Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth [Paper]

Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth [Paper] Downloads [Downloads] Trained ckpt files for NYU Depth V2 and

98 Jan 01, 2023
Learning from History: Modeling Temporal Knowledge Graphs with Sequential Copy-Generation Networks

CyGNet This repository reproduces the AAAI'21 paper β€œLearning from History: Modeling Temporal Knowledge Graphs with Sequential Copy-Generation Network

CunchaoZ 89 Jan 03, 2023
Hyperparameters tuning and features selection are two common steps in every machine learning pipeline.

shap-hypetune A python package for simultaneous Hyperparameters Tuning and Features Selection for Gradient Boosting Models. Overview Hyperparameters t

Marco Cerliani 422 Jan 08, 2023
Source code of our BMVC 2021 paper: AniFormer: Data-driven 3D Animation with Transformer

AniFormer This is the PyTorch implementation of our BMVC 2021 paper AniFormer: Data-driven 3D Animation with Transformer. Haoyu Chen, Hao Tang, Nicu S

24 Nov 02, 2022
Captcha-tensorflow - Image Captcha Solving Using TensorFlow and CNN Model. Accuracy 90%+

Captcha Solving Using TensorFlow Introduction Solve captcha using TensorFlow. Learn CNN and TensorFlow by a practical project. Follow the steps, run t

Jackon Yang 869 Jan 06, 2023
RuDOLPH: One Hyper-Modal Transformer can be creative as DALL-E and smart as CLIP

[Paper] [Π₯Π°Π±Ρ€] [Model Card] [Colab] [Kaggle] RuDOLPH 🦌 πŸŽ„ β˜ƒοΈ One Hyper-Modal Transformer can be creative as DALL-E and smart as CLIP Russian Diffusio

AI Forever 232 Jan 04, 2023
This is a template for the Non-autoregressive Deep Learning-Based TTS model (in PyTorch).

Non-autoregressive Deep Learning-Based TTS Template This is a template for the Non-autoregressive TTS model. It contains Data Preprocessing Pipeline D

Keon Lee 13 Dec 05, 2022
ICLR 2021 i-Mix: A Domain-Agnostic Strategy for Contrastive Representation Learning

Introduction PyTorch code for the ICLR 2021 paper [i-Mix: A Domain-Agnostic Strategy for Contrastive Representation Learning]. @inproceedings{lee2021i

Kibok Lee 68 Nov 27, 2022
Example repository for custom C++/CUDA operators for TorchScript

Custom TorchScript Operators Example This repository contains examples for writing, compiling and using custom TorchScript operators. See here for the

106 Dec 14, 2022
Deep metric learning methods implemented in Chainer

Deep Metric Learning Implementation of several methods for deep metric learning in Chainer v4.2.0. Proxy-NCA: No Fuss Distance Metric Learning using P

ronekko 156 Nov 28, 2022
Code for our EMNLP 2021 paper "Learning Kernel-Smoothed Machine Translation with Retrieved Examples"

KSTER Code for our EMNLP 2021 paper "Learning Kernel-Smoothed Machine Translation with Retrieved Examples" [paper]. Usage Download the processed datas

jiangqn 23 Nov 24, 2022
A PyTorch implementation of a Factorization Machine module in cython.

fmpytorch A library for factorization machines in pytorch. A factorization machine is like a linear model, except multiplicative interaction terms bet

Jack Hessel 167 Jul 06, 2022
Real-CUGAN - Real Cascade U-Nets for Anime Image Super Resolution

Real Cascade U-Nets for Anime Image Super Resolution δΈ­ζ–‡ | English πŸ”₯ Real-CUGAN

tarsin 111 Dec 28, 2022
Functional TensorFlow Implementation of Singular Value Decomposition for paper Fast Graph Learning

tf-fsvd TensorFlow Implementation of Functional Singular Value Decomposition for paper Fast Graph Learning with Unique Optimal Solutions Cite If you f

Sami Abu-El-Haija 14 Nov 25, 2021