Metadata-Version: 2.4
Name: graphpfn
Version: 0.1.1
Summary: GraphPFN
Project-URL: Repository, https://github.com/eremeev-d/graphpfn-package
Author: Dmitry Eremeev, Oleg Platonov, Gleb Bazhenov, Artem Babenko, Liudmila Prokhorenkova
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright 2026 Yandex LLC
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
License-File: LICENSE
License-File: NOTICE
Requires-Python: <4,>=3.11
Requires-Dist: delu
Requires-Dist: dgl<2.5,>=2.4
Requires-Dist: einops
Requires-Dist: huggingface-hub
Requires-Dist: numpy>=2.0
Requires-Dist: optuna>=3.1.0
Requires-Dist: pandas
Requires-Dist: pyyaml
Requires-Dist: scikit-learn>=1.4
Requires-Dist: torch-geometric
Requires-Dist: torch<2.5,>=2.1
Requires-Dist: tqdm
Description-Content-Type: text/markdown

# GraphPFN

**GraphPFN** is a graph foundation model for node-level tasks, built on the [prior-data fitted networks (PFN)](https://arxiv.org/abs/2112.10510) framework and accepted at ICML 2026 ([arXiv](https://arxiv.org/abs/2509.21489), [poster](https://icml.cc/virtual/2026/poster/66511)). It is pretrained on a novel synthetic prior that combines multi-level stochastic block models with graph-aware structured causal models to generate millions of diverse attributed graphs, and extends the PFN-based tabular foundation model [LimiX](https://github.com/limix-ldm/LimiX) with attention-based graph neighborhood aggregation (message passing) modules. This lets GraphPFN generalize across diverse real-world graph domains, supporting both in-context learning and finetuning regimes. Pretrained weights are available on [HuggingFace](https://huggingface.co/eremeev-d/graphpfn-1.3).

> [!NOTE]
> This repository provides both the `graphpfn` **Python package** for using pretrained GraphPFN on your own graphs, and the **paper code** used to reproduce all experiments from the paper, including model pretraining and synthetic dataset generation. See the [Paper Code](#paper-code) section and `paper` directory for details.

## News

- 2026-07-03: `graphpfn` Python package released on [PyPI](https://pypi.org/project/graphpfn/), offering convenient interfaces for using pretrained GraphPFN on your own graphs!
- 2026-06-22: GraphPFN-1.3 released, featuring a refactored graph prior, native ECOC support, extended evaluation, and various other improvements!
- 2026-04-30: GraphPFN [accepted](https://icml.cc/virtual/2026/poster/66511) to ICML 2026!
- 2026-02-13: GraphPFN-1.2 released, featuring improved ICL performance, end-to-end dataset generation and more!
- 2025-09-25: GraphPFN-1.0 released!

## Installation

**Prerequisites:** Python 3.11+ and a CUDA-capable GPU (CUDA 11.8 or newer).

There are two ways to use the `graphpfn` package. You can install it via `pip` into your own environment, handling PyTorch and DGL dependencies yourself. Alternatively, you can clone the repo and write your scripts inside it — [`uv`](https://github.com/astral-sh/uv) will manage the entire environment for you, including PyTorch and DGL, with no manual installation steps.

### Install as a package

**1. Install [PyTorch](https://pytorch.org/) and [DGL](https://www.dgl.ai)**

The commands below use CUDA 11.8 and PyTorch 2.4. For other combinations, check the [DGL getting started page](https://www.dgl.ai/pages/start.html). Please note that DGL does not officially support more modern PyTorch versions, so `graphpfn` pins `torch<2.5`.

```bash
pip install "torch==2.4" --index-url https://download.pytorch.org/whl/cu118
pip install dgl -f https://data.dgl.ai/wheels/torch-2.4/cu118/repo.html
```

**2. Install `graphpfn`**

From PyPI:
```bash
pip install graphpfn
```

Or from a local clone:
```bash
git clone https://github.com/yandex-research/graphpfn
cd graphpfn
pip install -e .
```

### Work within the repo

Clone the repo, place your script anywhere inside it (e.g. `examples/`), and run it with `uv run`. The full environment — including PyTorch and DGL — is defined in `uv.lock` and set up automatically on first run, with no manual `pip install` needed.

```bash
# Install uv
curl -LsSf https://astral.sh/uv/install.sh | sh

# Clone the repo
git clone https://github.com/yandex-research/graphpfn
cd graphpfn

# Run a script
uv run examples/basic.py
```

## Usage

### Quick Start

The snippet below runs ICL inference on an [amazon-ratings](https://arxiv.org/abs/2302.11640) dataset using pretrained GraphPFN weights downloaded automatically from HuggingFace:

```python
from torch_geometric.datasets import HeterophilousGraphDataset
from graphpfn import GraphDataset, predict_icl
from graphpfn.inference.util import compute_metrics

pyg_data = HeterophilousGraphDataset("data", "amazon-ratings")[0]
dataset = GraphDataset.from_pyg(pyg_data, task_type="multiclass", name="amazon-ratings")

preds = predict_icl(dataset=dataset, device="cuda:0")

test_mask = dataset.masks["test"]
metrics = compute_metrics(
    y_true=dataset.targets[test_mask],
    y_pred=preds[test_mask],
    task_type=dataset.task_type,
)
print(metrics)  # {"accuracy": ...}
```

See [`examples/basic.py`](examples/basic.py) and [`examples/finetune.py`](examples/finetune.py) for full runnable examples.

---

### GraphDataset

`GraphDataset` is a simple dataclass that holds everything needed for inference: the graph, node features, targets, train/val/test masks, and the task type.

```python
@dataclass
class GraphDataset:
    name: str
    graph: dgl.DGLGraph
    features: FeatureArrays   # TypedDict with keys: "num", "frac", "cat", "other"
    targets: np.ndarray       # shape [n_nodes]; NaN for unlabeled nodes
    masks: MaskArrays         # TypedDict with keys: "train", "val", "test"
    task_type: TaskType       # "binclass" | "multiclass" | "regression"
```

Features are split by type so the preprocessing pipeline can apply the right transform to each:
- **`"num"`** — general numerical features
- **`"frac"`** — fractional features in [0, 1]
- **`"cat"`** — categorical features as integer codes
- **`"other"`** — anything else, e.g. neural or sparse embeddings

Only the keys present in the dict are processed, you don't need to provide all four types.

**From PyTorch Geometric:**

```python
from graphpfn import GraphDataset

dataset = GraphDataset.from_pyg(
    pyg_data,               # torch_geometric.data.Data
    task_type="multiclass",
    name="my-dataset",
    split_index=0,          # which column of *_mask to use (default: 0)
)
```

PyG node features (`pyg_data.x`) are loaded as `"other"` features. If they are high-dimensional neural embeddings, consider setting `d_pca=64` in `preprocessing_kwargs` (see [ICL Inference](#icl-inference)).

You can also replace masks after construction (e.g. to use custom splits):

```python
custom_splits = dict(np.load("split.npz"))
dataset.masks = custom_splits
```

**From GraphLand:**

[GraphLand](https://arxiv.org/abs/2409.14500) is a benchmark collection of real-world industrial graph datasets with pre-defined splits.

```python
dataset = GraphDataset.from_graphland(
    "tolokers-2",
    split="RL",          # "RL" (default) | "RH" | "TH"
    root_dir="data",     # path where datasets are stored
)
```

This loader automatically separates numerical, fractional, and categorical features based on dataset metadata.

**From custom data:**

You can build a `GraphDataset` directly from any DGL graph and NumPy arrays:

```python
import dgl, numpy as np, torch
from graphpfn import GraphDataset

graph = dgl.graph((src_nodes, dst_nodes), num_nodes=N)
features = {"num": numerical_array, "cat": categorical_array}
targets = np.array(...)   # shape [N], float32; NaN for unlabeled nodes
masks = {"train": train_bool_array, "val": val_bool_array, "test": test_bool_array}

dataset = GraphDataset(
    name="my-dataset",
    graph=graph,
    features=features,
    targets=targets,
    masks=masks,
    task_type="binclass",
)
```

---

### ICL Inference

In-context learning (ICL) runs the pretrained model **without any weight updates**. Training nodes are passed as context and the model predicts all other nodes in a single forward pass. This is the fastest mode and works well out of the box.

```python
from graphpfn import predict_icl

preds = predict_icl(
    dataset=dataset,
    preprocessing_kwargs={"d_pca": 64},  # recommended for neural-embedding features
    amp=True,       # bfloat16 autocast (default: True)
    device="cuda:0",
)
```

`predict_icl` returns a NumPy array of predictions for **all nodes**: shape `[n_nodes]` for binary classification and regression, or `[n_nodes, n_classes]` for multiclass. Index with a mask to get per-split results.

**Key parameters:**

| Parameter | Default | Description |
|---|---|---|
| `model_kwargs` | `{}` | Passed to `GraphPFN.from_pretrained`. Use `"checkpoint"` key to specify a local path or HuggingFace URI. |
| `preprocessing_kwargs` | `{}` | Feature preprocessing options; see the table below. |
| `amp` | `True` | Enables bfloat16 autocast for faster inference on supported GPUs. |
| `device` | — | Required. Target CUDA device, e.g. `"cuda:0"`. |

**Preprocessing options** (via `preprocessing_kwargs`):

| Parameter | Default | Description |
|---|---|---|
| `num_transform` | `"quantile-normal"` | Transform for `"num"` features. One of `"standard"`, `"quantile-normal"`, `"quantile-uniform"`, or `None`. |
| `frac_transform` | `"quantile-uniform"` | Transform for `"frac"` features. Same options as `num_transform`. |
| `cat_transform` | `"ordinal"` | Transform for `"cat"` features. One of `"ordinal"`, `"one-hot"`, or `None`. |
| `other_transform` | `"standard"` | Transform for `"other"` features. Same options as `num_transform`. |
| `d_pca` | `None` | If set, all features are concatenated and reduced to `d_pca` dimensions with PCA. Recommended (e.g. `64`) when features are high-dimensional neural embeddings. |

See [`examples/basic.py`](examples/basic.py) for a full runnable example.

---

### Finetuning

Finetuning updates the model weights on training nodes of the target graph. This typically improves performance over ICL at the cost of more compute. **We recommend** `tune_and_predict_ft`, which performs a grid search over learning rates and returns predictions from the best trial.

```python
from functools import partial
from graphpfn import tune_and_predict_ft
from graphpfn.inference.util import compute_score, compute_loss

preds, best_hparams = tune_and_predict_ft(
    dataset=dataset,
    score_fn=partial(compute_score, task_type=dataset.task_type),
    loss_fn=partial(compute_loss, task_type=dataset.task_type),
    device="cuda:0",
)
print(best_hparams)  # {"lr": 0.0005}
```

`tune_and_predict_ft` returns `(predictions, best_hyperparams)`. Predictions have the same shape as in `predict_icl`.

`score_fn` **and** `loss_fn`**:**

The library provides ready-to-use implementations in `graphpfn.inference.util`:

```python
from graphpfn.inference.util import compute_score, compute_loss, compute_metrics

# compute_score: single scalar, higher is always better (used for early stopping)
# Defaults: average_precision (binclass), accuracy (multiclass), R^2 (regression)
score = compute_score(y_true=..., y_pred=..., task_type="multiclass")

# compute_loss: differentiable Tensor loss (cross-entropy or MSE)
loss = compute_loss(y_true=..., y_pred=..., task_type="multiclass")

# compute_metrics: dict of all relevant metrics
metrics = compute_metrics(y_true=..., y_pred=..., task_type="binclass")
# {"average_precision": ..., "roc_auc": ...}
```

You can also pass any custom callables matching the `ScoreFn` / `LossFn` protocols from `graphpfn.inference`.

**Key parameters** (shared between `tune_and_predict_ft` and `predict_ft`):

| Parameter | Default | Description |
|---|---|---|
| `score_fn` | — | Required. Scalar metric used for validation and early stopping (higher = better). |
| `loss_fn` | — | Required. Differentiable loss used for gradient updates. |
| `n_steps` | `-1` | Total training steps. `-1` means run until early stopping triggers. |
| `steps_per_epoch` | `10` | Steps between validation evaluations. |
| `patience` | `4` | Early stopping patience in epochs. |
| `train_batch_size` | `1024` | Number of training nodes predicted per gradient step. |
| `model_kwargs` | `{}` | Same as in `predict_icl`. |
| `preprocessing_kwargs` | `{}` | Same as in `predict_icl`. |
| `amp` | `True` | Same as in `predict_icl`. |
| `device` | — | Required. |
| `verbose` | `True` | Print validation scores during training. |

**Learning rate:** `predict_ft` takes a single `lr: float` (required), while `tune_and_predict_ft` takes `lr_grid: list[float]` — it runs one `predict_ft` trial per value and returns predictions from the best-scoring trial.

| Parameter | Function | Default | Description |
|---|---|---|---|
| `lr` | `predict_ft` | — | Learning rate for the Adam optimizer. |
| `lr_grid` | `tune_and_predict_ft` | 10 log-spaced values 5e-6 to 5e-4 | List of learning rates to try; the trial with the best validation score wins. |

See [`examples/finetune.py`](examples/finetune.py) for a full runnable example.

---

### Model API

`GraphPFN` and `GraphPFNLight` are standard `torch.nn.Module` subclasses, useful when you need more control than the high-level inference functions provide.

`GraphPFN` wraps `GraphPFNLight` with an ensemble of feature/target permutations. It is used internally by all inference functions and is the recommended way to interact with the model directly:

```python
from graphpfn import GraphPFN

model = GraphPFN.from_pretrained(
    n_features=64,
    n_classes=5,           # None for regression
    device="cuda:0",
    checkpoint="hf://eremeev-d/graphpfn-1.3/graphpfn-adapters-1_3.pt",  # default
    ensemble_kwargs={"n_members": 10},  # default
)

preds = model(
    graph=graph,                  # DGL Graph
    features=features,            # Tensor [n_nodes, n_features]
    y_train=y_train,              # Tensor [n_train]
    train_mask=train_mask,        # BoolTensor [n_nodes]
    task_type="multiclass",
)  # → Tensor [n_nodes, n_classes]
```

Each of the `n_members` ensemble runs uses a different random permutation of features and (for multiclass) class labels, and the outputs are aggregated before returning.

For **custom finetuning loops**, use `GraphPFN.train_step_forward` instead of `forward` — it samples a single random ensemble member and returns `(query_preds, query_targets)` in the transformed target space, ready for a loss and `.backward()`. Running one member per step keeps gradient steps as cheap as a single ICL forward pass while still covering the ensemble's permutation space over many steps. See [`src/graphpfn/model/graphpfn.py`](src/graphpfn/model/graphpfn.py) for the method and [`src/graphpfn/inference/finetune.py`](src/graphpfn/inference/finetune.py) for a reference implementation.

`GraphPFNLight` is the bare backbone without ensembling — a single forward pass with no permutations. Its `forward` signature is identical to `GraphPFN`. It is intended for advanced use cases where you manage ensembling yourself. For standard inference, prefer `GraphPFN`.

## Paper Code

The [`paper/`](paper/) directory contains the code used to reproduce all paper experiments, including model pretraining, synthetic dataset generation, and evaluation. See [`paper/README.md`](paper/README.md) for setup instructions and full details.

## Licenses

GraphPFN code and weights are released under the [Apache License 2.0](LICENSE). The vendored LimiX component is also distributed under Apache 2.0 — see [`LICENSES/LimiX.txt`](LICENSES/LimiX.txt). Note that **LimiX pretrained weights** are distributed under a separate license, users are responsible for complying with it — see the [LimiX repository](https://github.com/limix-ldm/LimiX) for details. All vendored third-party components are listed in the [`NOTICE`](NOTICE) file and [`LICENSES/`](LICENSES/) directory.

## Citation

If you use GraphPFN in your research, please cite our paper:

```bibtex
@inproceedings{eremeev2026graphpfn,
  title={{GraphPFN}: A Prior-Data Fitted Graph Foundation Model},
  author={Eremeev, Dmitry and Platonov, Oleg and Bazhenov, Gleb and Babenko, Artem and Prokhorenkova, Liudmila},
  booktitle={International Conference on Machine Learning},
  year={2026}
}
```
