(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
Personalized Federated Learning using Pytorch (pFedMe)

Personalized Federated Learning with Moreau Envelopes (NeurIPS 2020) This repository implements all experiments in the paper Personalized Federated Le

Charlie Dinh 226 Dec 30, 2022
Pytorch based library to rank predicted bounding boxes using text/image user's prompts.

pytorch_clip_bbox: Implementation of the CLIP guided bbox ranking for Object Detection. Pytorch based library to rank predicted bounding boxes using t

Sergei Belousov 50 Nov 27, 2022
A PyTorch implementation of "Predict then Propagate: Graph Neural Networks meet Personalized PageRank" (ICLR 2019).

APPNP ⠀ A PyTorch implementation of Predict then Propagate: Graph Neural Networks meet Personalized PageRank (ICLR 2019). Abstract Neural message pass

Benedek Rozemberczki 329 Dec 30, 2022
Official code implementation for "Personalized Federated Learning using Hypernetworks"

Personalized Federated Learning using Hypernetworks This is an official implementation of Personalized Federated Learning using Hypernetworks paper. [

Aviv Shamsian 121 Dec 25, 2022
JudeasRx - graphical app for doing personalized causal medicine using the methods invented by Judea Pearl et al.

JudeasRX Instructions Read the references given in the Theory and Notation section below Fire up the Jupyter Notebook judeas-rx.ipynb The notebook dra

Robert R. Tucci 19 Nov 7, 2022
Official PyTorch Implementation of Rank & Sort Loss [ICCV2021]

Rank & Sort Loss for Object Detection and Instance Segmentation The official implementation of Rank & Sort Loss. Our implementation is based on mmdete

Kemal Oksuz 229 Dec 20, 2022
This is the pytorch implementation for the paper: Generalizable Mixed-Precision Quantization via Attribution Rank Preservation, which is accepted to ICCV2021.

GMPQ: Generalizable Mixed-Precision Quantization via Attribution Rank Preservation This is the pytorch implementation for the paper: Generalizable Mix

null 18 Sep 2, 2022
A PyTorch implementation of "SimGNN: A Neural Network Approach to Fast Graph Similarity Computation" (WSDM 2019).

SimGNN ⠀⠀⠀ A PyTorch implementation of SimGNN: A Neural Network Approach to Fast Graph Similarity Computation (WSDM 2019). Abstract Graph similarity s

Benedek Rozemberczki 534 Dec 25, 2022
A pure PyTorch batched computation implementation of "CIF: Continuous Integrate-and-Fire for End-to-End Speech Recognition"

A pure PyTorch batched computation implementation of "CIF: Continuous Integrate-and-Fire for End-to-End Speech Recognition"

張致強 14 Dec 2, 2022
The source codes for ACL 2021 paper 'BoB: BERT Over BERT for Training Persona-based Dialogue Models from Limited Personalized Data'

BoB: BERT Over BERT for Training Persona-based Dialogue Models from Limited Personalized Data This repository provides the implementation details for

null 124 Dec 27, 2022
Personalized Transfer of User Preferences for Cross-domain Recommendation (PTUPCDR)

This is the official implementation of our paper Personalized Transfer of User Preferences for Cross-domain Recommendation (PTUPCDR), which has been accepted by WSDM2022.

Yongchun Zhu 81 Dec 29, 2022
Listing arxiv - Personalized list of today's articles from ArXiv

Personalized list of today's articles from ArXiv Print and/or send to your gmail

Lilianne Nakazono 5 Jun 17, 2022
Regulatory Instruments for Fair Personalized Pricing.

Fair pricing Source code for WWW 2022 paper Regulatory Instruments for Fair Personalized Pricing. Installation Requirements Linux with Python >= 3.6 p

Renzhe Xu 6 Oct 26, 2022
[ICLR 2021] Rank the Episodes: A Simple Approach for Exploration in Procedurally-Generated Environments.

[ICLR 2021] RAPID: A Simple Approach for Exploration in Reinforcement Learning This is the Tensorflow implementation of ICLR 2021 paper Rank the Episo

Daochen Zha 48 Nov 21, 2022
An efficient and effective learning to rank algorithm by mining information across ranking candidates. This repository contains the tensorflow implementation of SERank model. The code is developed based on TF-Ranking.

SERank An efficient and effective learning to rank algorithm by mining information across ranking candidates. This repository contains the tensorflow

Zhihu 44 Oct 20, 2022
Source Code for DialogBERT: Discourse-Aware Response Generation via Learning to Recover and Rank Utterances (https://arxiv.org/pdf/2012.01775.pdf)

DialogBERT This is a PyTorch implementation of the DialogBERT model described in DialogBERT: Neural Response Generation via Hierarchical BERT with Dis

Xiaodong Gu 67 Jan 6, 2023
Rank 1st in the public leaderboard of ScanRefer (2021-03-18)

InstanceRefer InstanceRefer: Cooperative Holistic Understanding for Visual Grounding on Point Clouds through Instance Multi-level Contextual Referring

null 63 Dec 7, 2022
Code for "LoRA: Low-Rank Adaptation of Large Language Models"

LoRA: Low-Rank Adaptation of Large Language Models This repo contains the implementation of LoRA in GPT-2 and steps to replicate the results in our re

Microsoft 394 Jan 8, 2023
TensorFlow Ranking is a library for Learning-to-Rank (LTR) techniques on the TensorFlow platform

TensorFlow Ranking is a library for Learning-to-Rank (LTR) techniques on the TensorFlow platform

null 2.6k Jan 4, 2023