Metadata-Version: 2.4
Name: rill-gnn
Version: 0.1.0
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Rust
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Dist: torch>=2.0
Requires-Dist: numpy>=1.22
Requires-Dist: ogb>=1.3.6 ; extra == 'benchmark'
Requires-Dist: pytest>=7.0 ; extra == 'dev'
Requires-Dist: torch-geometric>=2.4 ; extra == 'dev'
Requires-Dist: certifi>=2023.7 ; extra == 'dev'
Requires-Dist: scipy>=1.8 ; extra == 'dev'
Provides-Extra: benchmark
Provides-Extra: dev
License-File: LICENSE-APACHE
License-File: LICENSE-MIT
Summary: Rust-backed neighbor sampling for PyTorch with zero-copy DLPack batch handoff
License: MIT OR Apache-2.0
Requires-Python: >=3.8
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM

# Rill

**Rust-backed neighbor sampling for PyTorch.**

[![CI](https://github.com/Joy-Majumder/Rill/actions/workflows/ci.yml/badge.svg)](https://github.com/Joy-Majumder/Rill/actions/workflows/ci.yml)
[![License: MIT OR Apache-2.0](https://img.shields.io/badge/license-MIT%20%2F%20Apache--2.0-blue.svg)](./LICENSE-MIT)
[![Python 3.8+](https://img.shields.io/badge/python-3.8%2B-blue.svg)](https://www.python.org/downloads/)

Rill accelerates mini-batch GNN data loading by moving graph storage, multi-hop neighbor sampling, feature gathering, and batch assembly into a native Rust core. The Python GIL is released during all native work, and batches are handed to PyTorch via zero-copy DLPack tensors.

On `ogbn-products` (2.4M nodes, 124M edges) with a 2-layer GraphSAGE model, Rill delivers:

- **8.1–8.7× faster** batch loading than PyG `NeighborLoader`
- **3.6–4.5× faster** end-to-end training epochs (loader + transfer + model)
- **2.86 GB (30%) lower** peak host memory
- **1.000× equivalent** subgraph sizes and identical tensor layouts (`float32` / `int64`, contiguous)

> [!NOTE]
> Rill is not a full replacement for PyTorch Geometric. You still use PyG or PyTorch for your GNN layers (`SAGEConv`, `GCNConv`, etc.); Rill replaces `NeighborLoader` for in-memory homogeneous node-level graphs.

---

## Benchmarks

All timings are medians over 10 timed repeats after 3 warmup epochs on `ogbn-products` (`2,449,029` nodes, `123,718,280` edges), `20,000` training seeds, fanout `[10, 10]`, batch size `256`.
Reproduce with [`examples/benchmark_full.py`](./examples/benchmark_full.py).

### Controlled comparison

Both loaders sample the same workload and emit identical tensor formats (medians across all 79 batches):

| Loader | Median nodes / batch | Median edges / batch | `x` dtype / contiguous | `edge_index` dtype / contiguous |
| --- | ---: | ---: | --- | --- |
| **Rill** | 24,659 | 27,591 | `float32` / `True` | `int64` / `True` |
| **PyG (`pyg_lib`)** | 24,673 | 27,582 | `float32` / `True` | `int64` / `True` |
| **Ratio (Rill / PyG)** | **0.999×** | **1.000×** | **Match** | **Match** |

### Loader and end-to-end epoch timing

| Threads | Rill loader | PyG loader | Loader speedup | Rill E2E | PyG E2E | E2E speedup |
| ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| 1 | 670 ms | 5,402 ms | **8.06×** | 1,389 ms | 6,293 ms | **4.53×** |
| 4 | 408 ms | 3,546 ms | **8.68×** | 1,100 ms | 3,902 ms | **3.55×** |
| 8\* | 441 ms | 5,093 ms | 11.56× | 1,131 ms | 5,368 ms | 4.75× |

*\*Oversubscribed: 8 workers on a 4-core CPU; included to illustrate contention behavior rather than as a scaling point.*

`E2E` measures the full training epoch: batch loading + host-to-device transfer + 2-layer GraphSAGE (`hidden=256`) forward, loss, backward, and optimizer step. Only E2E totals are compared head-to-head; PyG's multi-worker IPC and background CPU contention affect both transfer (`543 ms` vs `180 ms` at 4 threads) and model execution.

### Peak host memory & one-time construction

| Metric | Threads | Rill | PyG | Delta |
| --- | ---: | ---: | ---: | ---: |
| **Peak RSS** (baseline ~3,770 MB) | 1 | 6,604 MB | 9,465 MB | **-2.86 GB (-30%)** |
| **Peak RSS** (baseline ~3,770 MB) | 4 | 6,678 MB | 9,559 MB | **-2.88 GB (-30%)** |
| **Loader construction** (one-time) | 1 | 18.86 s | 11.04 s | +7.82 s |
| **Loader construction** (one-time) | 4 | 11.80 s | 6.99 s | +4.81 s |

Rill eagerly builds CSR/CSC indexes in parallel and copies node features into Rust-managed memory, whereas PyG defers part of its setup to the first iteration. At 4 threads, Rill's extra `~4.8 s` construction cost is recovered in **~2 epochs**.

<details>
<summary><strong>Test environment</strong></summary>

- **CPU:** Intel Xeon @ 2.00 GHz, 4 vCPUs
- **RAM:** 31 GB
- **GPU:** 2× Tesla T4 (15 GB each)
- **OS:** Linux 6.18.55+ (`x86_64`, `glibc` 2.39)
- **Stack:** Python 3.13, PyTorch `2.11.0+cu130`, PyG `2.8.1`, `pyg_lib`, CUDA `13.0`
- **Host:** Kaggle Notebook (GPU T4 ×2)

</details>

---

## Installation

```bash
pip install rill-gnn
```

To build from source (requires a stable Rust toolchain):

```bash
python -m pip install .
```

**Requirements:** Python 3.8+, PyTorch 2.0+, NumPy 1.22+.

---

## Quick Start

`RillLoader` accepts any mapping or object (such as a PyG `Data` object) with `edge_index`, `x`, and optional `y`:

```python
import torch.nn.functional as F
from torch_geometric.nn import SAGEConv
from rill import RillLoader

loader = RillLoader(
    data,
    num_neighbors=[10, 10],
    batch_size=1024,
    input_nodes=data.train_mask,
    shuffle=True,
    seed=42,
)

for batch in loader:
    x = batch["x"].to(device)
    edge_index = batch["edge_index"].to(device)
    y = batch["y"].to(device)

    out = model(x, edge_index)
    loss = F.cross_entropy(out[: batch["batch_size"]], y)
    loss.backward()
```

### Batch schema

| Key | Shape / Type | Description |
| --- | --- | --- |
| `x` | `(num_sampled_nodes, num_features)` `float32` | Node features for the sampled subgraph. |
| `edge_index` | `(2, num_sampled_edges)` `int64` | Local `[source, target]` inbound edges (`source -> target`). |
| `n_id` | `(num_sampled_nodes,)` `int64` | Original graph node IDs. |
| `batch_size` | `int` | Number of unique seed nodes at the start of the batch. |
| `y` | `(batch_size, ...)` `int64` *(optional)* | Labels for the seed nodes only. |

---

## Scope & Limitations

**Supported today:**
- In-memory homogeneous graphs (`edge_index` + dense `float32` node features `x` + optional integer labels `y`)
- Inbound multi-hop neighbor sampling (`num_neighbors` list per hop)
- Seed selection via node IDs or boolean mask (`input_nodes`)
- Deterministic per-epoch shuffling and sampling (`seed`)

**Not yet supported:**
- Heterogeneous graphs (`HeteroData`), edge features (`edge_attr`), or link prediction (`LinkNeighborLoader`)
- `num_neighbors=[-1]` (all-neighbor fanout) or sampling with replacement in `RillLoader`
- Out-of-core / disk-backed graphs (e.g., `ogbn-papers100M`)
- Attribute-style batch access (`batch.x` — currently returns a `dict`)

---

## Reproducing Benchmarks

Install the development and OGB benchmark extras (plus a compatible `pyg_lib` or `torch_sparse` build):

```bash
python -m pip install ".[dev,benchmark]"
```

Run the full multi-thread sweep with end-to-end GraphSAGE timing:

```bash
python -m examples.benchmark_full \
  --dataset ogbn-products \
  --num-seeds 20000 \
  --warmup 3 \
  --repeats 10 \
  --sweep \
  --e2e
```

For a quick single-thread check on Cora:

```bash
python -m examples.benchmark_cora --dataset cora --warmup 3 --repeats 10 --threads 1
```

See [CONTRIBUTING.md](./CONTRIBUTING.md) for development setup, Rust/Python test commands, and benchmark methodology.

---

## Roadmap

- Drop-in `batch.x` / `batch.edge_index` attribute access alongside dict access
- CSC-only index construction for `RillLoader` and zero-copy feature buffer borrowing
- `num_neighbors=[-1]` (all-neighbor) and `edge_attr` support

---

## AI Disclosure

Rill was built with significant assistance from AI coding tools. Architecture, design decisions, and research direction are human-driven; implementation, tests, benchmarks, and documentation were developed collaboratively with AI pair-programming. All code has been reviewed and tested by the author.

## License

Dual-licensed under either the [MIT License](./LICENSE-MIT) or the [Apache License, Version 2.0](./LICENSE-APACHE), at your option.

