diff --git a/.cargo/config b/.cargo/config.toml similarity index 100% rename from .cargo/config rename to .cargo/config.toml diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 35da613..b8ca775 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -1,8 +1,8 @@ -# This file is autogenerated by maturin v1.7.4 -# To update, run -# -# maturin generate-ci github +# Started from the workflow generated by `maturin generate-ci github` and +# maintained by hand since. # +# pycleora is built against the stable ABI (abi3, Python >= 3.10), so every +# platform needs exactly one wheel. name: CI on: @@ -18,30 +18,85 @@ on: permissions: contents: read +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + jobs: + lint: + name: Format and lints + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + - run: cargo fmt --check + - run: cargo clippy --all-targets -- -D warnings + + test: + name: Tests (${{ matrix.os }}, Python ${{ matrix.python-version }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + # Every supported Python on Linux x86_64; the oldest and the newest one + # on Linux aarch64 and on Apple silicon. One abi3 wheel serves them all, + # so what varies is the interpreter and the versions of the dependencies. + os: [ubuntu-latest] + python-version: ["3.10", "3.11", "3.12", "3.13", "3.14", "3.15"] + include: + - os: ubuntu-24.04-arm + python-version: "3.10" + - os: ubuntu-24.04-arm + python-version: "3.15" + - os: macos-latest + python-version: "3.10" + - os: macos-latest + python-version: "3.15" + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + - uses: dtolnay/rust-toolchain@stable + - name: Rust tests + if: runner.os == 'Linux' + run: | + # the test binaries link against libpython + export LD_LIBRARY_PATH="$(python -c 'import sysconfig; print(sysconfig.get_config_var("LIBDIR"))'):${LD_LIBRARY_PATH}" + cargo test + - name: Build the extension + run: | + python -m venv .venv + source .venv/bin/activate + pip install "maturin>=1.9.4,<2.0" + maturin develop --release --extras test + - name: Python tests + run: | + source .venv/bin/activate + pytest + linux: + name: Wheel (Linux ${{ matrix.platform.target }}) runs-on: ${{ matrix.platform.runner }} strategy: + fail-fast: false matrix: platform: + # Both are built natively, so both wheels are executed below. + # There is no 32-bit Linux wheel: NumPy, which pycleora needs, has not + # published one since 1.22, and the manylinux2014_i686 image can no + # longer install packages. - runner: ubuntu-latest target: x86_64 - - runner: ubuntu-latest - target: x86 - - runner: ubuntu-latest + - runner: ubuntu-24.04-arm target: aarch64 - # - runner: ubuntu-latest - # target: armv7 - # - runner: ubuntu-latest - # target: s390x - # - runner: ubuntu-latest - # target: ppc64le steps: - uses: actions/checkout@v4 - - name: Install Dependencies - run: | - sudo apt-get update - sudo apt-get install -y musl-tools gcc musl-dev - uses: actions/setup-python@v5 with: python-version: 3.x @@ -49,53 +104,26 @@ jobs: uses: PyO3/maturin-action@v1 with: target: ${{ matrix.platform.target }} - args: --release --out dist --find-interpreter + args: --release --out dist sccache: 'true' manylinux: auto + - name: Smoke test + shell: bash + run: | + python -m pip install numpy + python -m pip install --no-index --no-deps --find-links dist pycleora + python tests/wheel_smoke.py - name: Upload wheels uses: actions/upload-artifact@v4 with: name: wheels-linux-${{ matrix.platform.target }} path: dist - # musllinux: - # runs-on: ${{ matrix.platform.runner }} - # strategy: - # matrix: - # platform: - # - runner: ubuntu-latest - # target: x86_64 - # - runner: ubuntu-latest - # target: x86 - # - runner: ubuntu-latest - # target: aarch64 - # - runner: ubuntu-latest - # target: armv7 - # steps: - # - uses: actions/checkout@v4 - # - name: Install Dependencies - # run: | - # sudo apt-get update - # sudo apt-get install -y musl-tools gcc musl-dev - # - uses: actions/setup-python@v5 - # with: - # python-version: 3.x - # - name: Build wheels - # uses: PyO3/maturin-action@v1 - # with: - # target: ${{ matrix.platform.target }} - # args: --release --out dist --find-interpreter - # sccache: 'true' - # manylinux: musllinux_1_2 - # - name: Upload wheels - # uses: actions/upload-artifact@v4 - # with: - # name: wheels-musllinux-${{ matrix.platform.target }} - # path: dist - windows: + name: Wheel (Windows ${{ matrix.platform.target }}) runs-on: ${{ matrix.platform.runner }} strategy: + fail-fast: false matrix: platform: - runner: windows-latest @@ -112,8 +140,14 @@ jobs: uses: PyO3/maturin-action@v1 with: target: ${{ matrix.platform.target }} - args: --release --out dist --find-interpreter + args: --release --out dist sccache: 'true' + - name: Smoke test + shell: bash + run: | + python -m pip install numpy + python -m pip install --no-index --no-deps --find-links dist pycleora + python tests/wheel_smoke.py - name: Upload wheels uses: actions/upload-artifact@v4 with: @@ -121,13 +155,15 @@ jobs: path: dist macos: + name: Wheel (macOS ${{ matrix.platform.target }}) runs-on: ${{ matrix.platform.runner }} strategy: + fail-fast: false matrix: platform: - # - runner: macos-12 - # target: x86_64 - - runner: macos-14 + - runner: macos-15-intel + target: x86_64 + - runner: macos-latest target: aarch64 steps: - uses: actions/checkout@v4 @@ -138,8 +174,14 @@ jobs: uses: PyO3/maturin-action@v1 with: target: ${{ matrix.platform.target }} - args: --release --out dist --find-interpreter + args: --release --out dist sccache: 'true' + - name: Smoke test + shell: bash + run: | + python -m pip install numpy + python -m pip install --no-index --no-deps --find-links dist pycleora + python tests/wheel_smoke.py - name: Upload wheels uses: actions/upload-artifact@v4 with: @@ -147,14 +189,23 @@ jobs: path: dist sdist: + name: Source distribution runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: 3.x - name: Build sdist uses: PyO3/maturin-action@v1 with: command: sdist args: --out dist + - uses: dtolnay/rust-toolchain@stable + - name: Build and smoke-test from the sdist + run: | + python -m pip install dist/*.tar.gz + cd "$RUNNER_TEMP" && python "$GITHUB_WORKSPACE/tests/wheel_smoke.py" - name: Upload sdist uses: actions/upload-artifact@v4 with: @@ -165,7 +216,7 @@ jobs: name: Release runs-on: ubuntu-latest if: ${{ startsWith(github.ref, 'refs/tags/') || github.event_name == 'workflow_dispatch' }} - needs: [linux, windows, macos, sdist] + needs: [lint, test, linux, windows, macos, sdist] permissions: # Use to sign the release artifacts id-token: write @@ -186,4 +237,4 @@ jobs: MATURIN_PYPI_TOKEN: ${{ secrets.PYPI_API_TOKEN }} with: command: upload - args: --non-interactive --skip-existing wheels-*/* \ No newline at end of file + args: --non-interactive --skip-existing wheels-*/* diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e925f2..b05afe7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,194 @@ +# 4.0.0 (unreleased) + +A correctness and performance release. **Embeddings computed by this version differ +from those of 3.x** (the initial vectors and the defaults of `embed()` changed, see +below), so embeddings stored from earlier versions should be recomputed rather than +mixed with new ones. Requires Python 3.10 or newer; tested on 3.10 to 3.15. + +### Fixed +- **Initial vectors were almost collinear.** `initialize_deterministically` derived + every value from a single multiplicative hash step, so the vectors of different + entities were strongly correlated: at 256 dimensions the cosine between two + random entities had a standard deviation of 0.45 (independent vectors give + 0.06) and the whole matrix had an effective rank of about 5, whatever the + dimension. Values are now independent and uniform in [-1, 1), computed with + SplitMix64 from the entity name, the column and the seed. +- **Graph construction depended on thread scheduling.** With more than one + worker, edge weights were summed in a varying order and the entities kept + when an oversized hyperedge is trimmed depended on which thread saw it + first, so two runs on the same input could give different matrices. Weights + are now accumulated exactly (fixed point), trimming uses global occurrence + counts with a fixed tie-break, and entities are numbered by first appearance + in the input. The matrix and the embeddings are bit-identical for any + `num_workers`. +- **`embed_weighted` ignored its weights**: the weights cancelled in the + row normalisation and the result equalled the unweighted embedding. Weights + are now part of the matrix (`weights=` on `from_iterator` / `from_edges`, or a + `weight::` column); an integer weight `k` equals repeating the line `k` times. + `from_pandas(weight_col=...)`, `from_edge_list`, `from_networkx`, + `from_scipy_sparse` and `from_numpy` pass weights through as well. +- **`embed_inductive` and `embed_streaming` moved every existing vector.** They + re-ran the embedding, which with whitening rotates the whole space: the + median cosine between an entity's vector before and after an update was + 0.04, and a classifier trained on the old vectors fell from 0.82 to 0.27 + accuracy. The default is now `mode="frozen"`: existing vectors do not change + and new entities are placed at the weighted average of their neighbours. + `mode="retrain"` keeps the previous behaviour; `embed_streaming(refresh_every=k)` + periodically re-embeds and rotates the result back onto the old coordinates. +- **Bad input was accepted silently.** A missing file gave an empty graph, lines + with the wrong number of columns were dropped without notice, and a file + whose fields were separated by the wrong character gave an empty graph. + Missing files now raise `FileNotFoundError`, skipped lines raise a + `RuntimeWarning` naming the first offender, and input with no usable line + raises `ValueError`. Files may have any extension. +- **Any call in a forked child process hung** once the parent had used the + library (for example in a `multiprocessing` pool with the `fork` start method): + the child waited for worker threads that only exist in the parent. Thread + pools are now created per process. +- Fortran-ordered and strided arrays crashed `left_markov_propagate` / + `symmetric_markov_propagate` with a Rust panic. Any layout is accepted now; + wrong shapes and dtypes raise readable `TypeError` / `ValueError`. +- `get_entity_column_mask` returned all `False` for a reflexive column. +- **Whitening a graph with no more entities than dimensions erased it.** With + `num_entities <= feature_dim + 1` the whitened vectors are, in general, all + equidistant (every pairwise cosine equals -1/(N-1)), so the default `embed()` + returned nothing usable for small graphs - including the quick start of the + README. Whitening now warns about it, and it is no longer the default (see + *Changed*). +- **`pycleora.datasets` returned synthetic graphs under the names of real + datasets** (`cora`, `citeseer`, `pubmed`, `ppi`, `amazon_*`, `dblp`, `reddit`, + `flickr`, `yelp`, ...). These loaders now download the real graphs from their + original sources; `flickr`, `yelp`, `dblp` and `reddit`, for which there is no + loader yet, raise an explanatory error. Every dataset reports `"synthetic"` + and `"source"`. The old generators remain available, clearly labelled, through + `load_synthetic()`. +- **Baseline algorithms** (`pycleora.algorithms`) were rewritten after their + papers. ProNE and RandNE returned embeddings at chance level on real graphs. + All baselines now start from the graph's + adjacency matrix; they used Cleora's row-normalised matrix, self-loops + included. DeepWalk and node2vec are documented as what they are here: random + walks factorised with PPMI + SVD, not skip-gram. +- The wheels declared no dependencies although `import pycleora` needed NumPy + and SciPy. NumPy is now declared; SciPy is optional (`pycleora[scipy]`, + `pycleora[full]`) and imported only by the functions that need it. +- `pycleora.benchmark` measured memory with `tracemalloc`, which does not see + allocations made by the Rust core (0.00 MB for an embedding of megabytes). The + memory column is removed; the benchmark in `benchmarks/` measures the peak + resident memory of a separate process per method. A failing algorithm is + reported in its row with the error. +- **`find_most_similar(exclude_self=True)` returned the query itself** when + `top_k` was at least the number of entities; **`predict_links` returned every + pair twice** (`top_k=10` gave five distinct pairs); **`embed_directed`** gave + entities without outgoing edges a zero vector, and the zeros spread upstream + with every iteration. `embed(residual_weight=...)` silently ignored values + outside [0, 1): they are an error now. +- **`mlp_classify` and `gcn_classify` chose their checkpoint on the test set** and + reported the best test accuracy seen during training. The checkpoint is chosen + on a validation part of the training entities; the test entities are scored + once. +- **`pycleora.metrics`**: `average_precision` was not average precision, + `clustering_scores` built its centroids from the true labels, and the ranking + metrics looped over all nodes in Python. The module is rewritten on NumPy with + the standard definitions and is tested against scikit-learn. +- `pycleora embed --algorithm node2vec` ran with p = q = 1, which is DeepWalk. + `--p` and `--q` are passed on (defaults 1 and 0.5). +- `load_wikipedia_pos` dropped the edge weights of the published graph; it + returns them as `"weights"`. +- `load_embeddings` no longer unpickles `.npz` content; the Planetoid loaders + use a restricted unpickler. + +### Changed +- **`embed()` runs classic Cleora with an automatic number of iterations by + default**: `num_iterations="auto"`, `whiten=False`. The number of iterations + comes from the graph (`SparseMatrix.suggest_iterations`): fewer on dense + graphs, more for a reflexive column and for the symmetric normalisation. + Up to 3.2 the default was 40 iterations with PCA whitening after each one; + `embed(graph, num_iterations=40, whiten=True)` still does that. The change + applies to every function that takes `whiten` and `num_iterations`, and to + the command line (`pycleora embed --whiten` replaces the default; `-n` accepts + `auto`). See the benchmark section of the README for the comparison. +- `SparseMatrix.entity_ids` is an immutable tuple that is built once. It used to + be a new list on every access, which made loops over `graph.entity_ids[i]` + quadratic. Assigning a new sequence of names still works. +- **Speed.** `embed()` keeps the embedding matrix in blocks of 16 columns, one + cache line per entity, and finishes a block for all entities before the next: + the vectors that are read at random then come from a slab that fits the + caches instead of from all over a matrix of gigabytes. The result is + bit-identical to propagating row by row. Work is scheduled by matrix entries + instead of rows, hub rows are split across threads, and the row normalisation + costs no pass of its own; graph construction is parallel and deterministic. + On an R-MAT graph with 0.6 million nodes and 12 million edges at 1024 + dimensions (`benchmarks/kernel_speed.py`): + + | Machine | pycleora | Threads | Build | One iteration | + |---|---|---:|---:|---:| + | Intel Core Ultra 9 275HX (24 threads) | 3.2.1 | 24 | 17.8 s | 5.39 s | + | | 4.0.0 | 24 | 1.19 s | 0.74 s | + | | 4.0.0 | 1 | 6.12 s | 5.16 s | + | Apple M4 (Mac mini, 10 cores) | 3.2.1 | 10 | 5.70 s | 4.02 s | + | | 4.0.0 | 10 | 0.88 s | 0.73 s | + | | 4.0.0 | 1 | 3.20 s | 2.84 s | + +- The whitening path (`whiten=True`) computes the covariance and the projection + in the Rust core, in place, with 2 instead of 6 embedding matrices of working + memory. Results agree with the NumPy reference implementation up to floating + point error; the sign of every whitened column is fixed instead of being left + to the LAPACK build. +- The sparse matrix stores each weight once (CSR, normalised on the fly): + 8 instead of 12 bytes per non-zero entry. +- Entities are listed in order of first appearance in the input (the order + used to depend on hashing and on the number of threads). +- Empty tokens are ignored: repeated spaces or a trailing space no longer create + an entity with an empty name. +- Built with PyO3 0.30 as an `abi3` wheel: one wheel per platform for every + Python from 3.10 on. Python 3.7-3.9 are no longer supported. +- The package version is defined in one place (`Cargo.toml`) and exposed as + `pycleora.__version__`. + +### Added +- `scale_by_popularity(graph, embeddings, exponent=1/16)`: multiplies every + vector by a power of the degree of its entity, so that the dot product of two + vectors is their cosine times a popularity prior. On 14 of 21 benchmark graphs + held-out links are found better with it than with the cosine, and with + `exponent=0.25` the vectors are better features for a classifier + (`benchmarks/README.md`, "The popularity prior"). +- `SparseMatrix.from_edges(src, dst, weights=None)` and + `pycleora.io_utils.from_arrays`: build a graph from NumPy arrays of integer + ids or from sequences of names without formatting and re-parsing strings. +- `embed(..., whiten=False)` runs classic Cleora entirely in the Rust core + (`SparseMatrix.embed_fast`, `embed_fast_convergence`), with two embedding + matrices of memory. +- `left_markov_propagate(x, out=..., rows=...)`: propagate into an existing + buffer, or compute only selected rows of the result. +- `SparseMatrix.to_csr()`, `column_names`, `get_entity_indices`, + `to_sparse_csr("raw")`, and module functions for the whitening kernels + (`column_mean_cov`, `center_project`, `center_project_inplace`, + `l2_normalize_inplace`). +- Real dataset loaders: Cora, CiteSeer and PubMed (Planetoid), Amazon Computers + and Photo, PPI and Wikipedia POS (node2vec), PPI (GraphSAGE), email-Eu-core, + dolphins, Les Miserables, football, ogbn-arxiv. Multi-label datasets return a + label matrix. +- `benchmarks/`: the benchmark behind the numbers in the README - 26 public + graphs, nine baselines run from their authors' code, similarity search among + all nodes, node classification and link ranking with many metrics - + replicable with one script (`benchmarks/replicate.sh`). See + `benchmarks/README.md`. +- `SparseMatrix.from_cliques(cliques)`: a graph from an iterable of entity + groups, without formatting strings; `SparseMatrix.isolated_entities`. +- `left_markov_propagate_normalized_inplace` / + `symmetric_markov_propagate_normalized_inplace`: any number of iterations on + an existing array, in place. +- `pycleora.metrics`: array-level functions for classification, multi-label, + ranking, retrieval and clustering metrics. +- A Python test suite (`tests/python`) run by CI on Python 3.10 to 3.15 on Linux + x86-64 and arm64 and on Apple silicon, together with the Rust tests, `cargo + fmt` and `clippy`; wheels and the source distribution are installed and + smoke-tested before upload; macOS x86_64 wheels. There is no 32-bit Linux + wheel any more (NumPy has not published one since 1.22). +- `SparseMatrix.suggest_iterations(propagation, purpose)`: the rule behind + `num_iterations="auto"`, with `purpose="similarity"` or `"classification"` for + embeddings that serve one use only. + # 2.0.0 (Nov 24, 2024) ### New version released diff --git a/COMPARISON.md b/COMPARISON.md index 42cd6af..91d3433 100644 --- a/COMPARISON.md +++ b/COMPARISON.md @@ -4,7 +4,7 @@ | Library | Language | Backend | Focus | Status | |---------|----------|---------|-------|--------| -| **pycleora 2.3** | Rust + Python | CPU (Rust SpMM) | Full-stack graph embedding SDK | Active | +| **pycleora 4.0** | Rust + Python | CPU (Rust SpMM) | Full-stack graph embedding SDK | Active | | **PyG (PyTorch Geometric)** | Python | GPU (PyTorch) | GNN training framework | Active | | **KarateClub** | Python | CPU (numpy/scipy) | Traditional graph embedding | Active | | **Cleora (BaseModelAI)** | Rust | CPU | Sparse embedding only | Minimal | @@ -99,13 +99,15 @@ ### Built-in Datasets +All pycleora datasets are the real graphs, downloaded from their original sources (SNAP, Planetoid, OGB, ...) on first use; synthetic graphs are only available under explicit names (`pycleora.datasets.load_synthetic`, `pycleora.generators`). + | Feature | pycleora | PyG | KarateClub | Cleora (Base) | Node2Vec | DGL | StellarGraph | GEM | GraphVite | DeepWalk | LINE | SDNE | graspologic | GraphSAGE | Struc2Vec | VERSE | NetSMF | |---------|:--------:|:---:|:----------:|:-------------:|:--------:|:---:|:------------:|:---:|:---------:|:--------:|:----:|:----:|:-----------:|:---------:|:---------:|:-----:|:------:| | Small graphs (Karate, etc.) | **4** | **4+** | **4+** | **0** | **0** | **4+** | **3+** | **2** | **0** | **0** | **0** | **0** | **3+** | **0** | **0** | **0** | **0** | | Citation networks (Cora, etc.) | **4** | **4+** | **0** | **0** | **0** | **4+** | **3+** | **1** | **3+** | **0** | **0** | **0** | **0** | **0** | **0** | **0** | **0** | | Amazon co-purchase | **2** | **2** | **0** | **0** | **0** | **0** | **0** | **0** | **0** | **0** | **0** | **0** | **0** | **0** | **0** | **0** | **0** | -| Large-scale (PPI, Reddit, DBLP) | **2** | **5+** | **0** | **0** | **0** | **5+** | **4+** | **0** | **2+** | **0** | **0** | **0** | **2+** | **0** | **0** | **0** | **0** | -| **Total datasets** | **14** | **70+** | **~5** | **0** | **0** | **40+** | **~10** | **~3** | **~5** | **0** | **0** | **0** | **~5** | **0** | **0** | **0** | **0** | +| Biology, social and large-scale (PPI, Orkut, Twitter, etc.) | **13** | **5+** | **0** | **0** | **0** | **5+** | **4+** | **0** | **2+** | **0** | **0** | **0** | **2+** | **0** | **0** | **0** | **0** | +| **Total datasets** | **23** | **70+** | **~5** | **0** | **0** | **40+** | **~10** | **~3** | **~5** | **0** | **0** | **0** | **~5** | **0** | **0** | **0** | **0** | ### I/O & Interoperability @@ -136,29 +138,31 @@ | Optional GPU support | **Yes** | **Yes** | No | No | No | **Yes** | **Yes** | No | **Yes** | No | No | **Yes** | No | **Yes** | No | No | No | | Multi-GPU support | Planned | **Yes** | No | No | No | **Yes** | Limited | No | **Yes** | No | No | No | No | No | No | No | No | | Rust-native performance | **Yes** | C++/CUDA | No | **Yes** | No | C++/CUDA | No | No | C++/CUDA | No | C++ | No | No | No | No | C++ | C++ | -| pip install (no build) | No | **Yes** | **Yes** | No | **Yes** | **Yes** | **Yes** | No | No | **Yes** | No | No | **Yes** | No | **Yes** | No | No | +| pip install (no build) | **Yes** | **Yes** | **Yes** | No | **Yes** | **Yes** | **Yes** | No | No | **Yes** | No | No | **Yes** | No | **Yes** | No | No | | Minimal dependencies | **Yes** | No | **Yes** | **Yes** | **Yes** | No | No | No | No | **Yes** | **Yes** | No | No | No | **Yes** | **Yes** | **Yes** | -| Embedding 1M nodes (time) | ~10s | ~30s+GPU | ~60s | ~10s | ~300s | ~30s+GPU | ~60s+GPU | ~120s | ~5s+GPU | ~300s | ~60s | ~120s+GPU | ~30s | ~60s+GPU | ~600s | ~30s | ~20s | | Actively maintained | **Yes** | **Yes** | **Yes** | Minimal | **Yes** | **Yes** | Archived | Inactive | Inactive | Inactive | Inactive | Inactive | **Yes** | Inactive | Inactive | Inactive | Inactive | +Measured embedding times and memory against nine other methods are in the +[benchmark](README.md#time-and-memory); this table makes no claim about speed. + --- ## Summary: Competitive Position ### Where pycleora leads: -1. **All-in-one SDK** — No other single library combines: embedding + 5 algorithms + classification + community detection + evaluation + 14 datasets + visualization + heterogeneous graphs + streaming + I/O -2. **CPU performance** — Rust backend matches or beats pure-Python alternatives by 10-100x +1. **All-in-one SDK** — No other single library combines: embedding + 5 algorithms + classification + community detection + evaluation + 23 datasets + visualization + heterogeneous graphs + streaming + I/O +2. **CPU performance** — see the measured [time and memory tables](README.md#time-and-memory) 3. **Dynamic graphs** — Only library with incremental update, edge removal, streaming, AND inductive embedding 4. **Zero-GPU deployment** — Full feature set works on CPU; GPU is optional 5. **Built-in evaluation pipeline** — Link prediction, node classification, and clustering metrics without sklearn -6. **Lightweight footprint** — ~5 MB install vs 200-600 MB for GPU-dependent competitors +6. **Lightweight footprint** — a wheel under 1 MB with NumPy as its only required dependency, vs 200-600 MB for GPU-dependent competitors ### Where competitors lead: 1. **PyG/DGL** — 50+ GNN architectures (GCN, GAT, GraphSAGE, etc.) with GPU training 2. **KarateClub** — 30+ traditional algorithms (community detection, diffusion, etc.) -3. **PyG/DGL** — 80+ real benchmark datasets (not synthetically generated) +3. **PyG/DGL** — 80+ benchmark datasets (pycleora ships 23, structure and labels only) 4. **PyG/DGL** — Active community, papers, tutorials, production deployments 5. **Node2Vec** — Simplest API for random-walk based embeddings 6. **GraphVite** — Fastest GPU-accelerated embedding (multi-GPU, C++/CUDA core) @@ -172,9 +176,9 @@ |----------|:--------:|:---:|:----------:|:-------------:|:--------:|:---:|:------------:|:---:|:---------:|:--------:|:----:|:----:|:-----------:|:---------:|:---------:|:-----:|:------:| | Public functions | **52** | 200+ | 40+ | **8** | ~5 | 200+ | ~80 | ~15 | ~10 | ~5 | ~3 | ~5 | 50+ | ~10 | ~5 | ~3 | ~3 | | Algorithms | 11 | 50+ | 30+ | 1 | 1 | 50+ | ~15 | ~8 | ~5 | 1 | 1 | 1 | ~5 | 1 | 1 | 1 | 1 | -| Datasets | 14 | 70+ | ~5 | 0 | 0 | 40+ | ~10 | ~3 | ~5 | 0 | 0 | 0 | ~5 | 0 | 0 | 0 | 0 | +| Datasets | 23 | 70+ | ~5 | 0 | 0 | 40+ | ~10 | ~3 | ~5 | 0 | 0 | 0 | ~5 | 0 | 0 | 0 | 0 | | Graph types | 6 | 6 | 3 | 2 | 2 | 6 | 5 | 3 | 3 | 1 | 2 | 2 | 3 | 4 | 1 | 3 | 2 | | Downstream tasks | 7 | 3 | 2 | 0 | 0 | 3 | 4 | 0 | 2 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | | I/O formats | 6 | 3 | 2 | 1 | 1 | 3 | 2 | 1 | 0 | 1 | 0 | 0 | 2 | 0 | 1 | 0 | 0 | -| Dependencies (required) | 3 | 10+ | 5+ | 0 | 2 | 10+ | 8+ | 5+ | 3+ | 3 | 1 | 5+ | 8+ | 5+ | 3 | 1 | 2 | -| Install size | ~5 MB | ~500 MB+ | ~15 MB | ~3 MB | ~2 MB | ~400 MB+ | ~600 MB+ | ~50 MB | ~200 MB+ | ~5 MB | ~5 MB | ~300 MB+ | ~50 MB | ~500 MB+ | ~5 MB | ~5 MB | ~10 MB | +| Dependencies (required) | 1 | 10+ | 5+ | 0 | 2 | 10+ | 8+ | 5+ | 3+ | 3 | 1 | 5+ | 8+ | 5+ | 3 | 1 | 2 | +| Install size | < 1 MB | ~500 MB+ | ~15 MB | ~3 MB | ~2 MB | ~400 MB+ | ~600 MB+ | ~50 MB | ~200 MB+ | ~5 MB | ~5 MB | ~300 MB+ | ~50 MB | ~500 MB+ | ~5 MB | ~5 MB | ~10 MB | diff --git a/Cargo.lock b/Cargo.lock index 8e999d2..29f2bd1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,43 +2,32 @@ # It is not intended for manual editing. version = 4 -[[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" - [[package]] name = "aho-corasick" -version = "1.1.4" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" dependencies = [ "memchr", ] [[package]] -name = "anyhow" -version = "1.0.102" +name = "anes" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" +checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" [[package]] -name = "atty" -version = "0.2.14" +name = "anstyle" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" -dependencies = [ - "hermit-abi 0.1.19", - "libc", - "winapi", -] +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" [[package]] name = "autocfg" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "bincode" @@ -51,110 +40,111 @@ dependencies = [ [[package]] name = "bitflags" -version = "1.3.2" +version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" [[package]] -name = "bitflags" -version = "2.11.0" +name = "bumpalo" +version = "3.20.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" [[package]] -name = "block-buffer" -version = "0.10.4" +name = "cast" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array", -] +checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] -name = "bumpalo" -version = "3.20.2" +name = "cfg-if" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" [[package]] -name = "byteorder" -version = "1.5.0" +name = "ciborium" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" +dependencies = [ + "ciborium-io", + "ciborium-ll", + "serde", +] [[package]] -name = "cast" -version = "0.3.0" +name = "ciborium-io" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" +checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" [[package]] -name = "cfg-if" -version = "1.0.4" +name = "ciborium-ll" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" +dependencies = [ + "ciborium-io", + "half", +] [[package]] name = "clap" -version = "2.34.0" +version = "4.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" +checksum = "ac230478587d0269d8d6998b82ae69ea51509d55df66d9e92edd1f986904cd4a" dependencies = [ - "bitflags 1.3.2", - "textwrap", - "unicode-width", + "clap_builder", ] [[package]] -name = "console" -version = "0.15.11" +name = "clap_builder" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "054ccb5b10f9f2cbf51eb355ca1d05c2d279ce1804688d0db74b4733a5aeafd8" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" dependencies = [ - "encode_unicode", - "libc", - "once_cell", - "windows-sys 0.59.0", + "anstyle", + "clap_lex", ] [[package]] -name = "cpufeatures" -version = "0.2.17" +name = "clap_lex" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" -dependencies = [ - "libc", -] +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" [[package]] -name = "crc32fast" -version = "1.5.0" +name = "console" +version = "0.16.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +checksum = "e96a4956774c13c126a8b5af4daa79384f4d826534c95a02d76afb39e2ab64e3" dependencies = [ - "cfg-if", + "encode_unicode", + "libc", + "windows-sys", ] [[package]] name = "criterion" -version = "0.3.6" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b01d6de93b2b6c65e17c634a26653a29d107b3c98c607c765bf38d041531cd8f" +checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f" dependencies = [ - "atty", + "anes", "cast", + "ciborium", "clap", "criterion-plot", - "csv", + "is-terminal", "itertools", - "lazy_static", "num-traits", + "once_cell", "oorandom", "plotters", "rayon", "regex", "serde", - "serde_cbor", "serde_derive", "serde_json", "tinytemplate", @@ -163,41 +153,28 @@ dependencies = [ [[package]] name = "criterion-plot" -version = "0.4.5" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2673cc8207403546f45f5fd319a974b1e6983ad1a3ee7e6041650013be041876" +checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1" dependencies = [ "cast", "itertools", ] -[[package]] -name = "crossbeam" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1137cd7e7fc0fb5d3c5a8678be38ec56e819125d8d7907411fe24ccb943faca8" -dependencies = [ - "crossbeam-channel", - "crossbeam-deque", - "crossbeam-epoch", - "crossbeam-queue", - "crossbeam-utils", -] - [[package]] name = "crossbeam-channel" -version = "0.5.15" +version = "0.5.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-deque" -version = "0.8.6" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" dependencies = [ "crossbeam-epoch", "crossbeam-utils", @@ -205,88 +182,44 @@ dependencies = [ [[package]] name = "crossbeam-epoch" -version = "0.9.18" +version = "0.9.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-queue" -version = "0.3.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-utils" -version = "0.8.21" +version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" [[package]] -name = "crypto-common" -version = "0.1.7" +name = "crunchy" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" -dependencies = [ - "generic-array", - "typenum", -] - -[[package]] -name = "csv" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52cd9d68cf7efc6ddfaaee42e7288d3a99d613d4b50f76ce9827ae0c6e14f938" -dependencies = [ - "csv-core", - "itoa", - "ryu", - "serde_core", -] - -[[package]] -name = "csv-core" -version = "0.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "704a3c26996a80471189265814dbc2c257598b96b8a7feae2d31ace646bb9782" -dependencies = [ - "memchr", -] +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" [[package]] name = "dashmap" -version = "5.5.3" +version = "6.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" +checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c" dependencies = [ "cfg-if", - "hashbrown 0.14.5", + "crossbeam-utils", + "hashbrown", "lock_api", "once_cell", "parking_lot_core", - "rayon", -] - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer", - "crypto-common", ] [[package]] name = "either" -version = "1.15.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "encode_unicode" @@ -294,52 +227,44 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" -[[package]] -name = "equivalent" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" - [[package]] name = "errno" -version = "0.3.14" +version = "0.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys", ] [[package]] name = "fastrand" -version = "2.3.0" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" [[package]] -name = "flate2" -version = "1.1.9" +name = "futures-core" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" -dependencies = [ - "crc32fast", - "miniz_oxide", -] +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" [[package]] -name = "foldhash" -version = "0.1.5" +name = "futures-task" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" [[package]] -name = "generic-array" -version = "0.14.7" +name = "futures-util" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ - "typenum", - "version_check", + "futures-core", + "futures-task", + "pin-project-lite", + "slab", ] [[package]] @@ -355,43 +280,31 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", "libc", "r-efi", - "wasip2", - "wasip3", ] [[package]] name = "half" -version = "1.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b43ede17f21864e81be2fa654110bf1e793774238d86ef8555c37e6519c0403" - -[[package]] -name = "hashbrown" -version = "0.14.5" +version = "2.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" - -[[package]] -name = "hashbrown" -version = "0.15.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" dependencies = [ - "foldhash", + "cfg-if", + "crunchy", + "zerocopy", ] [[package]] name = "hashbrown" -version = "0.16.1" +version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" [[package]] name = "heck" @@ -401,48 +314,15 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "hermit-abi" -version = "0.1.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" -dependencies = [ - "libc", -] - -[[package]] -name = "hermit-abi" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" - -[[package]] -name = "id-arena" -version = "2.3.0" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" - -[[package]] -name = "indexmap" -version = "2.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017" -dependencies = [ - "equivalent", - "hashbrown 0.16.1", - "serde", - "serde_core", -] - -[[package]] -name = "indoc" -version = "1.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa799dd5ed20a7e349f3b4639aa80d74549c81716d9ec4f994c9b5815598306" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" [[package]] name = "insta" -version = "1.46.3" +version = "1.49.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e82db8c87c7f1ccecb34ce0c24399b8a73081427f3c7c50a5d597925356115e4" +checksum = "b67d3d2e287e4b86c10b3f3b641033d1f89b74bdb39d05f34952e2b9a6fe21cd" dependencies = [ "console", "once_cell", @@ -450,6 +330,17 @@ dependencies = [ "tempfile", ] +[[package]] +name = "is-terminal" +version = "0.4.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" +dependencies = [ + "hermit-abi", + "libc", + "windows-sys", +] + [[package]] name = "itertools" version = "0.10.5" @@ -461,43 +352,26 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.17" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" [[package]] name = "js-sys" -version = "0.3.91" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b49715b7073f385ba4bc528e5747d02e66cb39c6146efb66b781f131f0fb399c" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ - "once_cell", + "cfg-if", + "futures-util", "wasm-bindgen", ] -[[package]] -name = "lazy_static" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" - -[[package]] -name = "leb128fmt" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" - [[package]] name = "libc" -version = "0.2.183" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d" - -[[package]] -name = "libm" -version = "0.2.16" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "linux-raw-sys" @@ -514,17 +388,11 @@ dependencies = [ "scopeguard", ] -[[package]] -name = "log" -version = "0.4.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" - [[package]] name = "matrixmultiply" -version = "0.3.10" +version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a06de3016e9fae57a36fd14dba131fccf49f74b40b7fbdb472f96e361ec71a08" +checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7" dependencies = [ "autocfg", "rawpointer", @@ -532,76 +400,23 @@ dependencies = [ [[package]] name = "memchr" -version = "2.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" - -[[package]] -name = "memoffset" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d61c719bcfbcf5d62b3a09efa6088de8c54bc0bfcd3ea7ae39fcc186108b8de1" -dependencies = [ - "autocfg", -] - -[[package]] -name = "miniz_oxide" -version = "0.8.9" +version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" -dependencies = [ - "adler2", - "simd-adler32", -] +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "ndarray" -version = "0.15.6" +version = "0.17.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adb12d4e967ec485a5f71c6311fe28158e9d6f4bc4a447b474184d0f91a8fa32" +checksum = "520080814a7a6b4a6e9070823bb24b4531daac8c4627e08ba5de8c5ef2f2752d" dependencies = [ "matrixmultiply", "num-complex", "num-integer", "num-traits", + "portable-atomic", + "portable-atomic-util", "rawpointer", - "rayon", -] - -[[package]] -name = "ndarray-npy" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f85776816e34becd8bd9540818d7dc77bf28307f3b3dcc51cc82403c6931680c" -dependencies = [ - "byteorder", - "ndarray", - "num-complex", - "num-traits", - "py_literal", - "zip", -] - -[[package]] -name = "ndarray-rand" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65608f937acc725f5b164dcf40f4f0bc5d67dc268ab8a649d3002606718c4588" -dependencies = [ - "ndarray", - "rand", - "rand_distr", -] - -[[package]] -name = "num-bigint" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" -dependencies = [ - "num-integer", - "num-traits", ] [[package]] @@ -615,9 +430,9 @@ dependencies = [ [[package]] name = "num-integer" -version = "0.1.46" +version = "0.1.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" dependencies = [ "num-traits", ] @@ -629,24 +444,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", - "libm", -] - -[[package]] -name = "num_cpus" -version = "1.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" -dependencies = [ - "hermit-abi 0.5.2", - "libc", ] [[package]] name = "numpy" -version = "0.18.0" +version = "0.30.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96b0fee4571867d318651c24f4a570c3f18408cf95f16ccb576b3ce85496a46e" +checksum = "aa0b9111761885449e894981fa8051dcf69e0bd114aecbd4bcdd830b6be4ed92" dependencies = [ "libc", "ndarray", @@ -654,6 +458,7 @@ dependencies = [ "num-integer", "num-traits", "pyo3", + "pyo3-build-config", "rustc-hash", ] @@ -669,16 +474,6 @@ version = "11.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" -[[package]] -name = "parking_lot" -version = "0.12.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" -dependencies = [ - "lock_api", - "parking_lot_core", -] - [[package]] name = "parking_lot_core" version = "0.9.12" @@ -693,47 +488,10 @@ dependencies = [ ] [[package]] -name = "pest" -version = "2.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0848c601009d37dfa3430c4666e147e49cdcf1b92ecd3e63657d8a5f19da662" -dependencies = [ - "memchr", - "ucd-trie", -] - -[[package]] -name = "pest_derive" -version = "2.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11f486f1ea21e6c10ed15d5a7c77165d0ee443402f0780849d1768e7d9d6fe77" -dependencies = [ - "pest", - "pest_generator", -] - -[[package]] -name = "pest_generator" -version = "2.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8040c4647b13b210a963c1ed407c1ff4fdfa01c31d6d2a098218702e6664f94f" -dependencies = [ - "pest", - "pest_meta", - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "pest_meta" -version = "2.8.6" +name = "pin-project-lite" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89815c69d36021a140146f26659a81d6c2afa33d216d736dd4be5381a7362220" -dependencies = [ - "pest", - "sha2", -] +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" [[package]] name = "plotters" @@ -764,103 +522,86 @@ dependencies = [ ] [[package]] -name = "ppv-lite86" -version = "0.2.21" +name = "portable-atomic" +version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" -dependencies = [ - "zerocopy", -] +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" [[package]] -name = "prettyplease" -version = "0.2.37" +name = "portable-atomic-util" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" dependencies = [ - "proc-macro2", - "syn 2.0.117", + "portable-atomic", ] [[package]] -name = "proc-macro2" -version = "1.0.106" +name = "ppv-lite86" +version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" dependencies = [ - "unicode-ident", + "zerocopy", ] [[package]] -name = "py_literal" -version = "0.4.0" +name = "proc-macro2" +version = "1.0.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "102df7a3d46db9d3891f178dcc826dc270a6746277a9ae6436f8d29fd490a8e1" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" dependencies = [ - "num-bigint", - "num-complex", - "num-traits", - "pest", - "pest_derive", + "unicode-ident", ] [[package]] name = "pycleora" -version = "3.2.1" +version = "4.0.0" dependencies = [ "bincode", "criterion", - "crossbeam", + "crossbeam-channel", "dashmap", "insta", - "itertools", - "log", "ndarray", - "ndarray-npy", - "ndarray-rand", - "num_cpus", "numpy", "pyo3", + "rand", "rayon", "rustc-hash", "serde", "smallvec", "twox-hash", - "uuid", ] [[package]] name = "pyo3" -version = "0.18.3" +version = "0.30.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3b1ac5b3731ba34fdaa9785f8d74d17448cd18f30cf19e0c7e7b1fdb5272109" +checksum = "229ca13b8a15bb0d1487b81ab975bfcd97513416499a8312011b6036e42e0de4" dependencies = [ - "cfg-if", - "indoc", "libc", - "memoffset", - "parking_lot", + "once_cell", + "portable-atomic", "pyo3-build-config", "pyo3-ffi", "pyo3-macros", - "unindent", ] [[package]] name = "pyo3-build-config" -version = "0.18.3" +version = "0.30.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cb946f5ac61bb61a5014924910d936ebd2b23b705f7a4a3c40b05c720b079a3" +checksum = "70130e2b6dd1ee589a8788026a429561ca5c40fa7a2fa7914c2282eddae24700" dependencies = [ - "once_cell", "target-lexicon", ] [[package]] name = "pyo3-ffi" -version = "0.18.3" +version = "0.30.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd4d7c5337821916ea2a1d21d1092e8443cf34879e53a0ac653fbb98f44ff65c" +checksum = "5e7ff73c555c286d212d4ce7e5fbda845a973c4f61bd5f160f5f2c3c2a04d1c4" dependencies = [ "libc", "pyo3-build-config", @@ -868,32 +609,33 @@ dependencies = [ [[package]] name = "pyo3-macros" -version = "0.18.3" +version = "0.30.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9d39c55dab3fc5a4b25bbd1ac10a2da452c4aca13bb450f22818a002e29648d" +checksum = "c46d2e5862c7bb8207e3b639f713dda3c499933444784154c11d013c5a691b60" dependencies = [ "proc-macro2", "pyo3-macros-backend", "quote", - "syn 1.0.109", + "syn 3.0.10", ] [[package]] name = "pyo3-macros-backend" -version = "0.18.3" +version = "0.30.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97daff08a4c48320587b5224cc98d609e3c27b6d437315bd40b605c98eeb5918" +checksum = "38b89f066f2ae72a2aef52d1537ca2fcd104440ebfadee06e97aa90738a25b9b" dependencies = [ + "heck", "proc-macro2", "quote", - "syn 1.0.109", + "syn 3.0.10", ] [[package]] name = "quote" -version = "1.0.45" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" dependencies = [ "proc-macro2", ] @@ -906,9 +648,9 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "rand" -version = "0.8.5" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" dependencies = [ "libc", "rand_chacha", @@ -934,16 +676,6 @@ dependencies = [ "getrandom 0.2.17", ] -[[package]] -name = "rand_distr" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32cb0b9bc82b0a0876c2dd994a7e7a2683d3e7390ca40e6886785ef0c7e3ee31" -dependencies = [ - "num-traits", - "rand", -] - [[package]] name = "rawpointer" version = "0.2.1" @@ -952,9 +684,9 @@ checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" [[package]] name = "rayon" -version = "1.11.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" dependencies = [ "either", "rayon-core", @@ -976,14 +708,14 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags 2.11.0", + "bitflags", ] [[package]] name = "regex" -version = "1.12.3" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" dependencies = [ "aho-corasick", "memchr", @@ -993,9 +725,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.14" +version = "0.4.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" dependencies = [ "aho-corasick", "memchr", @@ -1004,40 +736,34 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.10" +version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" [[package]] name = "rustc-hash" -version = "1.1.0" +version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" [[package]] name = "rustix" -version = "1.1.4" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ - "bitflags 2.11.0", + "bitflags", "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys", ] [[package]] name = "rustversion" -version = "1.0.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" - -[[package]] -name = "ryu" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" [[package]] name = "same-file" @@ -1054,57 +780,41 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" -[[package]] -name = "semver" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" - [[package]] name = "serde" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", "serde_derive", ] -[[package]] -name = "serde_cbor" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bef2ebfde456fb76bbcf9f59315333decc4fda0b2b44b420243c11e0f5ec1f5" -dependencies = [ - "half", - "serde", -] - [[package]] name = "serde_core" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.10", ] [[package]] name = "serde_json" -version = "1.0.149" +version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ "itoa", "memchr", @@ -1113,34 +823,23 @@ dependencies = [ "zmij", ] -[[package]] -name = "sha2" -version = "0.10.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" -dependencies = [ - "cfg-if", - "cpufeatures", - "digest", -] - -[[package]] -name = "simd-adler32" -version = "0.3.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2" - [[package]] name = "similar" version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + [[package]] name = "smallvec" -version = "1.15.1" +version = "1.16.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" [[package]] name = "static_assertions" @@ -1150,9 +849,9 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "syn" -version = "1.0.109" +version = "2.0.119" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" dependencies = [ "proc-macro2", "quote", @@ -1161,9 +860,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.117" +version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" dependencies = [ "proc-macro2", "quote", @@ -1172,9 +871,9 @@ dependencies = [ [[package]] name = "target-lexicon" -version = "0.12.16" +version = "0.13.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" +checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da" [[package]] name = "tempfile" @@ -1183,39 +882,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.2", + "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.61.2", -] - -[[package]] -name = "textwrap" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" -dependencies = [ - "unicode-width", -] - -[[package]] -name = "thiserror" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", + "windows-sys", ] [[package]] @@ -1239,58 +909,11 @@ dependencies = [ "static_assertions", ] -[[package]] -name = "typenum" -version = "1.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" - -[[package]] -name = "ucd-trie" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" - [[package]] name = "unicode-ident" -version = "1.0.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" - -[[package]] -name = "unicode-width" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" - -[[package]] -name = "unicode-xid" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" - -[[package]] -name = "unindent" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1766d682d402817b5ac4490b3c3002d91dfa0d22812f341609f97b08757359c" - -[[package]] -name = "uuid" -version = "1.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a68d3c8f01c0cfa54a75291d83601161799e4a89a39e0929f4b0354d88757a37" -dependencies = [ - "getrandom 0.4.2", - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "version_check" -version = "0.9.5" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "walkdir" @@ -1308,32 +931,13 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" -[[package]] -name = "wasip2" -version = "1.0.2+wasi-0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5" -dependencies = [ - "wit-bindgen", -] - -[[package]] -name = "wasip3" -version = "0.4.0+wasi-0.3.0-rc-2026-01-06" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" -dependencies = [ - "wit-bindgen", -] - [[package]] name = "wasm-bindgen" -version = "0.2.114" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6532f9a5c1ece3798cb1c2cfdba640b9b3ba884f5db45973a6f442510a87d38e" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -1341,9 +945,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.114" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18a2d50fcf105fb33bb15f00e7a77b772945a2ee45dcf454961fd843e74c18e6" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -1351,116 +955,51 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.114" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03ce4caeaac547cdf713d280eda22a730824dd11e6b8c3ca9e42247b25c631e3" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.10", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.114" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75a326b8c223ee17883a4251907455a2431acc2791c98c26279376490c378c16" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] -[[package]] -name = "wasm-encoder" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" -dependencies = [ - "leb128fmt", - "wasmparser", -] - -[[package]] -name = "wasm-metadata" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" -dependencies = [ - "anyhow", - "indexmap", - "wasm-encoder", - "wasmparser", -] - -[[package]] -name = "wasmparser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" -dependencies = [ - "bitflags 2.11.0", - "hashbrown 0.15.5", - "indexmap", - "semver", -] - [[package]] name = "web-sys" -version = "0.3.91" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "854ba17bb104abfb26ba36da9729addc7ce7f06f5c0f90f3c391f8461cca21f9" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", ] -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - [[package]] name = "winapi-util" version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys", ] -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" -[[package]] -name = "windows-sys" -version = "0.59.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" -dependencies = [ - "windows-targets", -] - [[package]] name = "windows-sys" version = "0.61.2" @@ -1470,192 +1009,28 @@ dependencies = [ "windows-link", ] -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - -[[package]] -name = "wit-bindgen" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" -dependencies = [ - "wit-bindgen-rust-macro", -] - -[[package]] -name = "wit-bindgen-core" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" -dependencies = [ - "anyhow", - "heck", - "wit-parser", -] - -[[package]] -name = "wit-bindgen-rust" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" -dependencies = [ - "anyhow", - "heck", - "indexmap", - "prettyplease", - "syn 2.0.117", - "wasm-metadata", - "wit-bindgen-core", - "wit-component", -] - -[[package]] -name = "wit-bindgen-rust-macro" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" -dependencies = [ - "anyhow", - "prettyplease", - "proc-macro2", - "quote", - "syn 2.0.117", - "wit-bindgen-core", - "wit-bindgen-rust", -] - -[[package]] -name = "wit-component" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" -dependencies = [ - "anyhow", - "bitflags 2.11.0", - "indexmap", - "log", - "serde", - "serde_derive", - "serde_json", - "wasm-encoder", - "wasm-metadata", - "wasmparser", - "wit-parser", -] - -[[package]] -name = "wit-parser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" -dependencies = [ - "anyhow", - "id-arena", - "indexmap", - "log", - "semver", - "serde", - "serde_derive", - "serde_json", - "unicode-xid", - "wasmparser", -] - [[package]] name = "zerocopy" -version = "0.8.42" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2578b716f8a7a858b7f02d5bd870c14bf4ddbbcf3a4c05414ba6503640505e3" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.42" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e6cc098ea4d3bd6246687de65af3f920c430e236bee1e3bf2e441463f08a02f" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", -] - -[[package]] -name = "zip" -version = "0.5.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93ab48844d61251bb3835145c521d88aa4031d7139e8485990f60ca911fa0815" -dependencies = [ - "byteorder", - "crc32fast", - "flate2", - "thiserror", + "syn 2.0.119", ] [[package]] name = "zmij" -version = "1.0.21" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index da7b6ec..bd9b622 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,45 +1,54 @@ [package] name = "pycleora" -version = "3.2.1" -edition = "2018" +version = "4.0.0" +edition = "2021" +rust-version = "1.85" license-file = "LICENSE" readme = "README.md" documentation = "https://cleora.ai/docs" homepage = "https://cleora.ai" repository = "https://github.com/BaseModelAI/cleora" description = """ -Sparse hypergraph structure and markov-propagation for node embeddings embeddings exposed via Python bindings. +Sparse hypergraph structure and markov-propagation for node embeddings exposed via Python bindings. """ +# Not part of the source distribution: the benchmark suite with its results and +# figures, images, the pre-Python CLI, and files that only serve the repository. +exclude = [ + ".github/", + "benchmarks/", + "files/", + "legacy/", + "scripts/", + "run.py", + "requirements.txt", + "COMPARISON.md", +] [lib] crate-type = ["cdylib", "rlib"] -[build] -rustflags = ["-C", "target-cpu=native"] - [dependencies] -log = "0.4.17" -rayon = "1.5.3" -rustc-hash = "1.1.0" -smallvec = "1.8.1" +rayon = "1.10" +rustc-hash = "2" +smallvec = "1.13" +# Kept on 1.x on purpose: entity hashes (XXH64, seed 0) feed the deterministic initialisation. twox-hash = "1.6.3" -ndarray = { version = "0.15.4", features = ["rayon"] } -ndarray-npy = "0.8.1" -uuid = { version = "1.1.2", features = ["v4"] } -crossbeam = "0.8.1" -dashmap = { version = "5.3.4", features = ["rayon"] } -num_cpus = "1.13.1" -itertools = "0.10.3" -serde = { version = "1.0.163", features = ["derive"] } +ndarray = "0.17" +dashmap = "6" +crossbeam-channel = "0.5" +serde = { version = "1", features = ["derive"] } bincode = "1.3.3" -pyo3 = "0.18.1" -numpy = "0.18" +# abi3: one wheel per platform works on every CPython >= 3.10. +pyo3 = { version = "0.30", features = ["abi3-py310"] } +numpy = "0.30" [dev-dependencies] -criterion = "0.3.3" -insta = "1.3.0" -ndarray-rand = "0.14.0" +criterion = "0.5" +insta = "1" +# rand 0.8 is pinned so that the snapshot tests keep drawing the exact random +# streams the stored snapshots were generated from. +rand = "0.8" [[bench]] name = "cleora_benchmark" @@ -49,11 +58,3 @@ harness = false opt-level = 3 lto = true codegen-units = 1 - -[target.aarch64-apple-darwin] -linker = "aarch64-apple-darwin21.4-clang" -ar = "aarch64-apple-darwin21.4-ar" -rustflags = [ - "-C", "link-arg=-undefined", - "-C", "link-arg=dynamic_lookup", -] diff --git a/README.md b/README.md index 24244c4..f0252ba 100644 --- a/README.md +++ b/README.md @@ -4,389 +4,806 @@

-

The Graph Embedding Engine

+

Cleora

-Cleora computes all possible random walks in a single matrix multiplication.
-No negative sampling. No GPU. No noise. Just fast, deterministic, production-grade embeddings. +Graph embeddings in seconds, on a CPU.
+No sampling, no training, no GPU - and ahead of nine established methods
+at finding what belongs together.

- Website  ·  - Documentation  ·  - API Reference  ·  - Benchmarks + PyPI + Python 3.10 to 3.15 + CI + License: MIT

- pip install pycleora + Quick start  ·  + Benchmarks  ·  + Performance  ·  + Methodology  ·  + All results  ·  + Documentation

---- -

- #1 Accuracy. Every Dataset.
- Tested on 5 canonical academic datasets against 7 competing algorithms — Cleora wins on accuracy on every single dataset,
and is the only algorithm that scales to every graph without crashing. + pip install pycleora

+ + + + + + + +

23 of 26

graphs on which Cleora is the best of 10 methods at finding a node's held-out neighbours

1.4 s

to embed ogbn-arxiv (169,343 nodes, 1.2M edges) at 1024 dimensions. The baselines: 10.0 s to 18.1 min

6 GB

of memory for Yelp (716,847 nodes, 6.6M edges). The baselines: 15 to 62 GB
+ +

- 240x Faster Than GraphSAGE  ·  - 50x Less Memory Than NetMF  ·  - ~5 MB Install  ·  - 0 GPUs Required + + + Three bar charts: the number of graphs on which each method is best in similarity search, the time each method needs to embed ogbn-arxiv, and the memory each needs on Yelp. Cleora leads all three by a wide margin. +

---- - -## Achievements - -:one:st place at [SIGIR eCom Challenge 2020](https://sigir-ecom.github.io/ecom20DCPapers/SIGIR_eCom20_DC_paper_1.pdf) - -:two:nd place and Best Paper Award at [WSDM Booking.com Challenge 2021](http://ceur-ws.org/Vol-2855/challenge_short_3.pdf) +

+Ten methods on 26 public graphs at 1024 dimensions; one fixed configuration per method, baselines run from their +authors' code. Every benchmark table and figure on this page is generated from the result files, and the +benchmark is one command: benchmarks/replicate.sh. +

-:two:nd place at [Twitter Recsys Challenge 2021](https://recsys-twitter.com/competition_leaderboard/latest) +--- -:three:rd place at [KDD Cup 2021](https://ogb.stanford.edu/paper/kddcup2021/mag240m_SyneriseAI.pdf) +## Why Cleora + +Cleora turns a graph or hypergraph into one vector per node by repeating a single step: +every vector becomes the normalised average of its neighbours' vectors. That is one +step of *every* random walk at once, without sampling a single one. + +- **Fast.** ogbn-arxiv - 169,343 nodes, 1.2 million edges - is embedded at 1024 + dimensions in 1.4 seconds on a laptop CPU: 7 times faster than the fastest baseline + and 700 times faster than DeepWalk ([times](#time-and-memory)). An iteration over 12 + million edges takes 0.74 s ([Performance](#performance)). +- **Accurate.** First of ten methods by mean rank in each of the three ways + embeddings are used - similarity search, node classification, link ranking - and + the best method outright on most graphs ([Benchmarks](#benchmarks)). +- **Lean.** Two embedding matrices of memory and nothing else: a fifth to a tenth of + what the other fast methods need. +- **Scales.** Graphs with tens of millions of edges take minutes. DeepWalk and + node2vec do not finish them in three hours, and ProNE runs out of memory. +- **Deterministic.** The same input gives the same embeddings, bit for bit, whatever + the number of threads. No seeds to average over, no runs to repeat. +- **Simple.** No negative sampling, no learning rate, no epochs, no GPU. The one + parameter that matters - the number of iterations - is chosen from the graph: + `embed(graph)`. +- **Practical.** Hypergraphs (baskets, sessions), weights, bipartite data, new nodes + without retraining, your own feature vectors as a starting point. + +
+New in 4.0 (changelog) + +- `embed(graph)` runs classic Cleora with a number of iterations chosen from the graph; + per-iteration whitening, the default of 3.2, is opt-in. +- One embedding iteration is 5 to 7 times faster and graph construction 6 to 15 times + ([Performance](#performance)); both are bit-for-bit deterministic for any number of + threads. +- `scale_by_popularity` turns "how alike" into "how likely to be linked": better + link prediction and recommendation on two graphs out of three, and better features + for classifiers. +- Initial vectors are independent (in 3.2 a 256-dimensional initialisation had an + effective rank of 5), weights are honoured, bad input is reported, forked workers + no longer hang. +- A benchmark that can be replicated with one command, against the reference + implementations of nine other methods. + +
--- -## Installation +## Quick start ```bash pip install pycleora ``` -Optional extras: +Python 3.10 to 3.15 on Linux (x86-64, arm64), macOS (Apple silicon, Intel) and Windows: +one `abi3` wheel per platform. NumPy is the only required dependency. ```bash -pip install pycleora[viz] # matplotlib for visualization -pip install pycleora[full] # matplotlib + networkx + tqdm +pip install "pycleora[scipy]" # the extra algorithms, attention / directed embeddings, graph statistics +pip install "pycleora[viz]" # matplotlib for visualization +pip install "pycleora[full]" # scipy + matplotlib + networkx + tqdm ``` -## Quick Start - ```python from pycleora import SparseMatrix, embed, find_most_similar -edges = ["alice item_laptop", "alice item_mouse", "bob item_keyboard"] -graph = SparseMatrix.from_iterator(iter(edges), "complex::reflexive::product") - -embeddings = embed(graph, feature_dim=256, num_iterations=40) - -similar = find_most_similar(graph, embeddings, "alice", top_k=5) -for r in similar: - print(f"{r['entity_id']}: {r['similarity']:.4f}") +# one line per shopping basket: the products that were bought together +baskets = [ + "laptop mouse keyboard", + "laptop mouse monitor", + "keyboard mouse", + "espresso_machine coffee_beans", + "coffee_beans mug", + "espresso_machine coffee_beans mug", +] +graph = SparseMatrix.from_iterator(iter(baskets), "complex::reflexive::product") + +# seven products: two iterations are plenty +embeddings = embed(graph, feature_dim=64, num_iterations=2) + +for hit in find_most_similar(graph, embeddings, "laptop", top_k=3): + print(f"{hit['entity_id']}: {hit['similarity']:.3f}") +# mouse: 0.990, monitor: 0.987, keyboard: 0.968 ``` -`embed()` defaults to `feature_dim=256`, `num_iterations=40`, and whitening after every propagation step. - -### Step-by-Step Example - -The high-level `embed()` function wraps the Markov propagation loop for convenience. Here's the full manual version, which gives you complete control over the process: +On real data `embed(graph)` is enough: 256 dimensions, and a number of iterations taken +from the graph itself. For a plain graph, pass the edges as arrays: ```python -from pycleora import SparseMatrix, whiten_embeddings import numpy as np -import pandas as pd -import random - -customers = [f"Customer_{i}" for i in range(1, 20)] -products = [f"Product_{j}" for j in range(1, 20)] - -data = { - "customer": random.choices(customers, k=100), - "product": random.choices(products, k=100), -} - -df = pd.DataFrame(data) -customer_products = df.groupby('customer')['product'].apply(list).values -cleora_input = map(lambda x: ' '.join(x), customer_products) -mat = SparseMatrix.from_iterator(cleora_input, columns='complex::reflexive::product') +source = np.array([0, 0, 1, 2, 3]) +target = np.array([1, 2, 2, 3, 4]) +network = SparseMatrix.from_edges(source, target, columns="complex::reflexive::node") +vectors = embed(network, feature_dim=1024) # row i belongs to network.entity_ids[i] +``` -print(mat.entity_ids) +### The four choices that matter -embeddings = mat.initialize_deterministically(256) +**1. How the graph is given.** A column that is `complex::reflexive` relates the +entities of a line to each other *and to themselves*; two plain columns relate the +entity in the first to the entity in the second. -NUM_ITERATIONS = 40 +| | Columns | Use it for | +|---|---|---| +| one column | `complex::reflexive::node` | similarity between entities of one kind: products in baskets, pages in sessions, the nodes of a graph. In the benchmark it is the better setup for nearest-neighbour search and link ranking ([table](benchmarks/RESULTS.md#cleora-the-four-ways-of-feeding-and-normalising-a-graph)). | +| two columns | `src dst`, `user product` | relations between two kinds of entities; half the iterations for the same reach. In a bipartite graph the two kinds are built from disjoint sets of initial vectors, so a user's vector can be compared with other users' but not with a product's. | -for i in range(NUM_ITERATIONS): - embeddings = mat.left_markov_propagate(embeddings) - embeddings /= np.linalg.norm(embeddings, ord=2, axis=-1, keepdims=True) - embeddings = whiten_embeddings(embeddings) +**2. The normalisation.** `propagation="left"` (default) averages over neighbours and +is the choice for classification features; `propagation="symmetric"` additionally +down-weights hubs and is the choice for similarity search and link ranking +([evidence](benchmarks/README.md#one-configuration-per-method)). -for entity, embedding in zip(mat.entity_ids, embeddings): - print(entity, embedding) +**3. The number of iterations.** Few iterations keep vectors local (who are my +neighbours?), many make them global (which community am I in?). The default, +`num_iterations="auto"`, takes a compromise from the density of the graph. If the use +of the vectors is known, ask for it: -print(np.dot(embeddings[0], embeddings[1])) +```python +k = graph.suggest_iterations("symmetric", purpose="similarity") # or "classification", "general" +embeddings = embed(graph, 1024, k, propagation="symmetric") ``` -### CLI +and if there is a validation set, tune it - one run hands out the vectors of every +iteration: -```bash -pycleora embed --input graph.tsv --output embeddings.npz --dim 256 --iterations 40 -pycleora info --input graph.tsv -pycleora similar --input graph.tsv --entity alice --top-k 10 -pycleora benchmark --dataset karate_club +```python +snapshots = {} +embed(graph, 1024, 32, callback=lambda i, vectors: snapshots.__setitem__(i + 1, vectors)) +# evaluate snapshots[2], snapshots[4], ... on validation data and keep the best ``` ---- - -## Key Advantages - -### No Negative Sampling -Unlike DeepWalk, Node2Vec, and LINE, Cleora doesn't approximate random walks with negative sampling. It computes **all walks exactly** via matrix multiplication. Less noise, higher accuracy, perfect reproducibility. - -### 240x Faster Than GraphSAGE -Zomato reported embedding generation in **under 5 minutes** with Cleora, compared to **20 hours with GraphSAGE** on the same dataset. Rust core with adaptive parallelism makes every CPU cycle count. - -### Deterministic Embeddings -Same input always produces the same output. No random seeds, no stochastic variation, no "run it 5 times and average" workflows. Critical for reproducible research and production ML pipelines. - -### Heterogeneous Hypergraphs -Natively handles multi-type nodes and edges, bipartite graphs, and hypergraphs. TSV input with typed columns like `complex::reflexive::product`. No graph preprocessing needed. +[How the rule was derived and how close it gets](benchmarks/README.md#number-of-iterations). -### ~5 MB, Zero Dependencies -The entire library is ~5 MB. Compare: PyTorch Geometric is 500 MB+, DGL is 400 MB+. Cleora ships as a single compiled Rust extension. No CUDA, no cuDNN, no GPU driver headaches. +**4. Alike, or likely to be linked.** The vectors have unit length: their dot product +is the cosine, which says how alike two entities are. Which links exist depends on +more than that - a well-connected entity is in more of them. To find missing links +(recommendations, "people you may know") give the vectors a popularity prior: -### Stable & Inductive -Embeddings are stable across runs and support inductive learning: new nodes can be embedded without retraining the entire graph. Production-ready from day one. - ---- - -## Supported Algorithms - -| Algorithm | Type | Description | -|-----------|------|-------------| -| **Cleora** | Spectral / Random Walk | Iterative Markov propagation with per-iteration whitening — all random walks in one matrix multiplication | -| **ProNE** | Spectral | Fast spectral propagation with Chebyshev polynomial approximation | -| **RandNE** | Random Projection | Gaussian random projection for very fast, approximate embeddings | -| **NetMF** | Matrix Factorization | Network Matrix Factorization — factorizes the DeepWalk matrix explicitly | -| **DeepWalk** | Random Walk | Classic random walk + skip-gram approach | -| **Node2Vec** | Random Walk | Biased random walks with tunable BFS/DFS exploration | -| **HOPE** | Matrix Factorization | High-Order Proximity preserved Embedding | -| **GraRep** | Matrix Factorization | Graph Representations with Global Structural Information | -| **MLP** | Neural Classifier | 2-layer MLP classifier in pure numpy/scipy — no PyTorch needed | - -All algorithms are unified under a single API. Switch between methods by changing one parameter: +```python +from pycleora import scale_by_popularity -```bash -pycleora embed --input graph.tsv --output out.npz --algorithm cleora -pycleora embed --input graph.tsv --output out.npz --algorithm prone -pycleora embed --input graph.tsv --output out.npz --algorithm node2vec +for_links = scale_by_popularity(graph, embeddings) # row i times degree_i ** (1/16) ``` -### Advanced Embedding Modes - -Beyond the standard algorithms, Cleora supports several advanced embedding strategies: +The dot product of two such vectors is their cosine times a factor that grows with how +connected both are; search them with an index that maximises the dot product. On two +of three benchmark graphs this finds more of the held-out links than the cosine does +([table](benchmarks/README.md#the-popularity-prior)). A classifier gains from knowing +how connected a node is, too: as features, use `scale_by_popularity(graph, embeddings, +exponent=0.25)`. Keep the unit vectors for "more like this". -- **Multiscale embeddings** — concatenates embeddings from different iteration depths (e.g. scales `[10, 20, 30, 40]`) to capture both local and global graph structure simultaneously -- **Attention-weighted propagation** — uses softmax-normalized dot-product attention during propagation, dynamically weighting neighbor contributions -- **Supervised refinement** — fine-tunes unsupervised embeddings using positive/negative entity pairs with a triplet margin loss -- **Directed graph embeddings** — handles asymmetric relationships where edge direction matters -- **Weighted graph embeddings** — incorporates edge weights into the propagation step -- **Node feature integration** — initializes embeddings with external features (text, image, numeric) before propagation -- **PCA whitening** — built-in whitening after every iteration by default to decorrelate embedding dimensions and improve downstream task performance +### More ---- +**Weights.** A weight per edge or hyperedge is part of the transition matrix; an +integer weight `k` equals repeating the line `k` times. -## Batteries Included - -pycleora ships with a comprehensive set of built-in modules: +```python +weighted = SparseMatrix.from_edges(source, target, weights=[1.0, 0.5, 2.0, 1.0, 3.0]) +weighted = SparseMatrix.from_iterator(iter(baskets), "complex::reflexive::product", weights=[1, 3, 1, 1, 2, 1]) +``` -| Module | What it does | -|--------|-------------| -| `pycleora.community` | Community detection (Louvain) | -| `pycleora.classify` | MLP and Label Propagation classifiers — no PyTorch needed | -| `pycleora.sampling` | 6 graph sampling methods | -| `pycleora.tuning` | Grid search and random search for hyperparameter tuning | -| `pycleora.compress` | Embedding compression (PQ, scalar quantization) | -| `pycleora.io_utils` | Save/load embeddings (NPZ, CSV, TSV), NetworkX conversion | -| `pycleora.viz` | Embedding visualization (UMAP, t-SNE projections) | -| `pycleora.metrics` | Evaluation metrics for embeddings | -| `pycleora.benchmark` | Compare algorithms with time, memory, and accuracy metrics | -| `pycleora.ensemble` | Combine embeddings from multiple algorithms | -| `pycleora.align` | Embedding alignment across graphs | -| `pycleora.search` | Nearest-neighbor entity search | -| `pycleora.stats` | Graph statistics and degree analysis | -| `pycleora.preprocess` | Graph preprocessing and filtering | -| `pycleora.hetero` | Heterogeneous graph utilities | -| `pycleora.generators` | Synthetic graph generators for testing | -| `pycleora.datasets` | Real-world benchmark datasets (Facebook, Cora, CiteSeer, PubMed, PPI, roadNet-CA, and more) | - -See the [full API reference](https://cleora.ai/api) for details on every function and parameter. +**New data without retraining.** `embed_inductive` adds edges and entities to an +embedded graph. Vectors that already exist stay exactly as they are - models trained on +them remain valid - and every new entity is placed at the weighted average of its +neighbours: ---- +```python +from pycleora import embed_inductive -## Case Study: Zomato +graph, embeddings = embed_inductive( + graph, embeddings, existing_edges=baskets, new_edges=["mug tea_bags"], + columns="complex::reflexive::product", +) +``` -**From 20 hours to under 5 minutes** — powering recommendations for 80M+ users across 500+ cities. +**Your own features.** `embed(graph, initial_embeddings=features)` propagates text, +image or numeric vectors along the graph instead of random ones. -Zomato's ML team needed graph embeddings to power "People Like You" restaurant recommendations. Their initial approach with **GraphSAGE took ~20 hours** just to process customer-restaurant interaction data for a single city region — making it impossible to scale across 500+ cities. +**The loop itself.** `embed` is a thin wrapper; the pieces are public: -**Pipeline:** -1. **Customer-Restaurant Graph** — Bipartite graph of customer orders and restaurant interactions -2. **Cleora Embeddings** (< 5 minutes) — 197x faster than DeepWalk, no sampling of positive/negative examples -3. **EMDE Density Estimation** — Customer preferences modeled as probability density functions -4. **Production Recommendations** — Restaurant recommendations, search ranking, dish suggestions, and "People Like You" lookalikes +```python +vectors = graph.initialize_deterministically(256, seed=0) +graph.left_markov_propagate_normalized_inplace(vectors, 8) # 8 iterations, in place, two matrices of memory +``` -**Results:** +**Whitening.** `embed(graph, num_iterations=40, whiten=True)` PCA-whitens the columns +after every iteration - the default of pycleora 3.2. It needs many more entities than +dimensions and 30 to 350 times the time. On small graphs it is clearly worse than the +default, on graphs with hundreds of nodes per dimension it can classify better +([Where Cleora is not the best](#where-cleora-is-not-the-best)). -| Metric | Value | -|--------|-------| -| Speed vs DeepWalk | **197x** faster | -| Embedding generation | **< 5 min** | -| Cities scaled to | **500+** | -| GPUs required | **0** | +### Command line -[Read the full Zomato blog post →](https://www.zomato.com/blog/connecting-the-dots-strengthening-recommendations-for-our-customers-part-two/) +```bash +pycleora embed --input graph.tsv --output embeddings.npz --dim 1024 +pycleora embed --input graph.tsv --output embeddings.npz --iterations 12 --propagation symmetric +pycleora info --input graph.tsv +pycleora similar --input graph.tsv --entity alice --top-k 10 +``` --- ## Benchmarks -Benchmarked against **7 competing algorithms** on **5 real-world datasets** (ego-Facebook, Cora, CiteSeer, PubMed, PPI) plus a 2M-node scale test. All datasets are genuine academic benchmarks from SNAP, Planetoid, and DGL. Cleora wins on accuracy on **every single dataset**. +Nine embedding methods, each run from its authors' code or a standard library with the +authors' settings, against Cleora on 26 public graphs, from a few thousand to 62 million +edges. All methods see the graph only - no node features, no labels - and produce +**1024-dimensional** vectors. The vectors are frozen and measured in the three ways +embeddings are used in production: -Full interactive benchmark results at [cleora.ai/benchmarks](https://cleora.ai/benchmarks). - -### Classification Accuracy - -| Dataset | Nodes | Cleora | NetMF | DeepWalk | Node2Vec | HOPE | GraRep | ProNE | RandNE | -|---------|-------|--------|-------|----------|----------|------|--------|-------|--------| -| **ego-Facebook** | 4K | **0.990** | 0.957 | 0.958 | 0.958 | 0.890 | T/O | 0.075 | 0.212 | -| **Cora** | 2.7K | **0.861** | 0.839 | 0.835 | 0.835 | 0.821 | 0.809 | 0.179 | 0.247 | -| **CiteSeer** | 3.3K | **0.824** | 0.810 | 0.806 | 0.806 | 0.740 | 0.756 | 0.189 | 0.244 | -| **PubMed** | 19.7K | **0.879** | OOM | T/O | T/O | T/O | OOM | 0.339 | 0.351 | -| **PPI** | 3.9K | **1.000** | OOM | T/O | T/O | T/O | OOM | 0.023 | 0.073 | - -> **Only 3 of 8 algorithms survive at 19.7K nodes.** HOPE, NetMF, GraRep, DeepWalk, and Node2Vec all crash or time out. Cleora achieves perfect accuracy on PPI (50 classes). - -### Memory Efficiency - -| Dataset | Cleora | Best Competitor | Factor | -|---------|--------|-----------------|--------| -| ego-Facebook (4K) | **22 MB** | 572 MB | 26x less | -| Cora (2.7K) | **14 MB** | 227 MB | 16x less | -| CiteSeer (3.3K) | **16 MB** | 294 MB | 18x less | -| PubMed (19.7K) | **97 MB** | 175 MB | Only 3 survived | -| roadNet-CA (2M) | **4.1 GB** | — | Only Cleora finished | - -### Scale Test: roadNet-CA (2 Million Nodes) - -2 million nodes. 31 seconds. Every other algorithm crashes with out-of-memory. Cleora is the only library that survives at this scale on a single CPU. +| Use | What is measured | What it stands for | +|---|---|---| +| **Similarity search** | the held-out neighbours of a node, retrieved among *all* nodes of the graph by dot product or cosine | a nearest-neighbour index over the vectors: candidate generation, "similar items", "people you may know" | +| **Node classification** | logistic regression and an MLP on the vectors | the vectors as input features of a downstream model | +| **Link ranking** | a held-out edge ranked against 500 sampled non-edges, by dot product or cosine and by a dot product with one learned weight per dimension | scoring a short list of candidates | + +[Methodology](benchmarks/README.md) · [all tables](benchmarks/RESULTS.md) + +**One configuration per method, the same for every graph.** Nothing is chosen per +dataset - not for the baselines, and not for Cleora, which runs with the settings +recommended above for the task: left normalisation and `purpose="classification"` for +node classification; symmetric normalisation and `purpose="similarity"` for similarity +search and link ranking; the popularity prior for both. Both ways of feeding a graph are shown: **Cleora** (one reflexive column) and +**Cleora, two columns**. + +### The short version + + +| | Graphs | Cleora: best on | mean rank | Cleora, two columns: best on | mean rank | Best baseline (mean rank) | +|---|---:|---:|---:|---:|---:|---| +| Similarity search among all nodes (dot product / cosine, recall@10) | 26 | **23** | 1.12 | 15 | 2.23 | RandNE (3.46) | +| Node classification (logistic regression, accuracy / micro-F1) | 17 | **11** | 1.88 | 7 | 2.00 | node2vec (3.35) | +| Link ranking against sampled candidates (dot product / cosine, MRR) | 26 | **15** | 1.50 | 13 | 2.35 | RandNE (3.27) | + +With the number of iterations and the normalisation chosen on validation data - the baselines stay at their authors' settings, so this is not part of the comparison above - Cleora is ahead of every baseline on 15 of 17 graphs in node classification and on 23 of 26 graphs in link ranking against sampled candidates. + + +### What the embeddings look like + +UMAP projections of the 1024-dimensional vectors, coloured by node class: one panel +per method, the same nodes in every panel. All 26 graphs are in +[`benchmarks/figures`](benchmarks/figures). + +![UMAP of ogbn-arxiv](benchmarks/figures/umap_ogbn_arxiv.png) + +![UMAP of Amazon Photo](benchmarks/figures/umap_amazon_photo.png) + +
+Cora + +![UMAP of Cora](benchmarks/figures/umap_cora.png) + +
+ +### Mean rank across graphs + +Mean rank of every method over the graphs (1 = best); in parentheses the number of +graphs it is the best method on. The two Cleora columns are not ranked against each +other. + +Similarity search among all nodes, by metric: + + +| Metric | Graphs | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| recall@10 | 26 | **1.12** (23) | 2.23 (15) | 6.23 (0) | 6.27 (0) | 6.04 (1) | 5.69 (0) | 7.88 (0) | 5.00 (1) | 4.23 (1) | 4.46 (0) | 3.46 (0) | +| recall@50 | 26 | **1.23** (21) | 2.35 (13) | 5.92 (0) | 6.31 (0) | 6.15 (0) | 5.54 (0) | 7.85 (0) | 5.46 (1) | 4.38 (2) | 4.27 (0) | 3.27 (2) | +| nDCG@10 | 26 | **1.08** (24) | 2.00 (16) | 6.46 (0) | 6.50 (0) | 6.15 (1) | 6.00 (0) | 7.81 (0) | 4.62 (0) | 4.19 (1) | 4.35 (0) | 3.23 (0) | +| MAP@10 | 26 | **1.04** (25) | 2.00 (18) | 6.42 (0) | 6.58 (0) | 6.23 (1) | 6.00 (0) | 7.77 (0) | 4.58 (0) | 4.23 (0) | 4.35 (0) | 3.19 (0) | +| MRR | 26 | **1.08** (25) | 2.00 (17) | 6.50 (0) | 6.73 (0) | 6.31 (0) | 6.00 (0) | 7.46 (0) | 4.31 (0) | 4.46 (1) | 4.35 (0) | 3.19 (0) | + + +Node classification (accuracy, or micro-F1 on multi-label graphs), by probe: + + +| Probe | Graphs | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| logistic regression | 17 | **1.88** (11) | 2.00 (7) | 4.18 (0) | 3.35 (1) | 5.53 (0) | 4.88 (2) | 7.00 (0) | 7.53 (0) | 6.47 (1) | 6.18 (1) | 5.35 (1) | +| MLP (AdamC) | 17 | **1.88** (12) | 2.71 (7) | 3.41 (0) | 3.00 (1) | 4.94 (0) | 6.71 (0) | 6.82 (0) | 7.29 (0) | 6.88 (0) | 5.94 (2) | 5.47 (2) | + + +Link ranking (MRR of the true neighbour against 500 sampled non-neighbours), by probe: + + +| Probe | Graphs | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| dot product or cosine | 26 | **1.50** (15) | 2.35 (13) | 6.15 (1) | 6.35 (0) | 6.12 (0) | 5.88 (0) | 7.31 (0) | 4.81 (2) | 4.58 (3) | 4.42 (0) | 3.27 (5) | +| dot product | 26 | **1.54** (15) | 2.35 (13) | 6.08 (1) | 6.58 (0) | 5.96 (0) | 6.35 (0) | 7.31 (0) | 4.65 (2) | 4.23 (3) | 4.58 (0) | 3.12 (5) | +| cosine | 26 | **1.38** (17) | 2.69 (11) | 6.46 (0) | 6.42 (0) | 6.65 (0) | 5.31 (0) | 7.54 (0) | 6.42 (0) | 3.62 (4) | 4.04 (0) | 2.54 (5) | +| logistic regression on x*y | 26 | **1.77** (11) | 3.12 (5) | 6.08 (0) | 6.12 (0) | 6.15 (0) | 6.19 (0) | 7.46 (0) | 5.58 (0) | 2.50 (11) | 4.73 (0) | 3.81 (4) | + + +### Similarity search + +Recall@10 of nearest-neighbour search over the vectors: for every query node, the ten +nearest nodes among all nodes of the graph (its known neighbours excluded), and the +share of its held-out neighbours among them. Dot product or cosine, whichever +validates better for the method. [nDCG@10, MAP@10, recall@50 and +MRR](benchmarks/RESULTS.md#similarity-search-among-all-nodes) give the same picture. + +
+Recall@10 on every graph + + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | **0.471 ± 0.025** | 0.405 ± 0.017 | 0.401 ± 0.032 | 0.403 ± 0.018 | 0.409 ± 0.017 | 0.425 ± 0.028 | 0.264 ± 0.019 | 0.419 ± 0.024 | 0.406 ± 0.025 | 0.397 ± 0.030 | 0.383 ± 0.029 | +| Cora | **0.434 ± 0.010** | 0.397 ± 0.012 | 0.370 ± 0.004 | 0.374 ± 0.004 | 0.371 ± 0.010 | 0.384 ± 0.004 | 0.186 ± 0.001 | 0.386 ± 0.006 | 0.370 ± 0.007 | 0.380 ± 0.010 | 0.370 ± 0.003 | +| PPI | **0.167 ± 0.005** | 0.114 ± 0.004 | 0.056 ± 0.001 | 0.056 ± 0.001 | 0.093 ± 0.001 | 0.087 ± 0.004 | 0.035 ± 0.005 | 0.123 ± 0.003 | 0.088 ± 0.002 | 0.107 ± 0.001 | 0.131 ± 0.003 | +| PubMed | 0.185 ± 0.005 | 0.108 ± 0.001 | 0.092 ± 0.003 | 0.086 ± 0.006 | **0.192 ± 0.006** | 0.103 ± 0.002 | 0.055 ± 0.004 | 0.158 ± 0.003 | 0.099 ± 0.003 | 0.092 ± 0.001 | 0.093 ± 0.001 | +| DBLP | **0.307 ± 0.006** | 0.280 ± 0.005 | 0.138 ± 0.004 | 0.139 ± 0.005 | 0.089 ± 0.036 | 0.195 ± 0.005 | 0.078 ± 0.004 | 0.222 ± 0.002 | 0.196 ± 0.006 | 0.219 ± 0.004 | 0.227 ± 0.004 | +| Cora-Full | **0.447 ± 0.003** | 0.422 ± 0.001 | 0.263 ± 0.001 | 0.265 ± 0.002 | 0.340 ± 0.001 | 0.330 ± 0.001 | 0.122 ± 0.001 | 0.305 ± 0.005 | 0.333 ± 0.001 | 0.364 ± 0.004 | 0.365 ± 0.002 | +| Facebook (ego) | **0.491 ± 0.009** | 0.483 ± 0.009 | 0.330 ± 0.004 | 0.324 ± 0.003 | 0.298 ± 0.016 | 0.397 ± 0.002 | 0.182 ± 0.006 | 0.392 ± 0.004 | 0.477 ± 0.007 | 0.418 ± 0.006 | 0.449 ± 0.004 | +| Coauthor CS | **0.458 ± 0.002** | 0.442 ± 0.004 | 0.318 ± 0.001 | 0.325 ± 0.001 | 0.275 ± 0.058 | 0.390 ± 0.002 | 0.138 ± 0.001 | 0.305 ± 0.005 | 0.392 ± 0.005 | 0.431 ± 0.003 | 0.449 ± 0.003 | +| Amazon Photo | **0.416 ± 0.004** | 0.358 ± 0.006 | 0.197 ± 0.003 | 0.194 ± 0.003 | 0.235 ± 0.004 | 0.212 ± 0.005 | 0.081 ± 0.003 | 0.313 ± 0.005 | 0.281 ± 0.006 | 0.266 ± 0.007 | 0.277 ± 0.008 | +| Wikipedia POS | **0.315 ± 0.003** | 0.311 ± 0.005 | 0.027 ± 0.001 | 0.032 ± 0.004 | 0.041 ± 0.001 | 0.033 ± 0.001 | 0.009 ± 0.001 | 0.252 ± 0.011 | 0.035 ± 0.002 | 0.045 ± 0.002 | 0.030 ± 0.001 | +| Amazon Computers | **0.360 ± 0.004** | 0.295 ± 0.005 | 0.146 ± 0.002 | 0.146 ± 0.002 | 0.149 ± 0.003 | 0.199 ± 0.003 | 0.043 ± 0.001 | 0.230 ± 0.003 | 0.241 ± 0.000 | 0.233 ± 0.002 | 0.244 ± 0.002 | +| Coauthor Physics | **0.504 ± 0.000** | 0.485 ± 0.001 | 0.391 ± 0.004 | 0.389 ± 0.004 | 0.317 ± 0.010 | 0.403 ± 0.003 | 0.156 ± 0.005 | 0.288 ± 0.003 | 0.430 ± 0.005 | 0.468 ± 0.002 | 0.498 ± 0.004 | +| BlogCatalog | **0.165 ± 0.002** | 0.111 ± 0.003 | 0.024 ± 0.000 | 0.024 ± 0.002 | 0.038 ± 0.002 | 0.016 ± 0.002 | 0.040 ± 0.002 | 0.120 ± 0.003 | 0.018 ± 0.001 | 0.023 ± 0.001 | 0.020 ± 0.001 | +| Flickr | **0.110 ± 0.003** | 0.017 ± 0.001 | 0.035 ± 0.001 | 0.034 ± 0.000 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.027 ± 0.000 | 0.012 ± 0.001 | 0.013 ± 0.000 | +| MovieLens-1M | 0.101 ± 0.003 | 0.001 ± 0.000 | 0.028 ± 0.001 | 0.027 ± 0.001 | 0.025 ± 0.000 | 0.067 ± 0.001 | 0.066 ± 0.001 | **0.107 ± 0.010** | 0.090 ± 0.001 | 0.004 ± 0.001 | 0.082 ± 0.005 | +| ogbl-ddi | **0.092 ± 0.001** | 0.057 ± 0.001 | 0.042 ± 0.000 | 0.040 ± 0.001 | 0.047 ± 0.000 | 0.054 ± 0.000 | 0.028 ± 0.000 | 0.042 ± 0.000 | 0.058 ± 0.000 | 0.059 ± 0.001 | 0.060 ± 0.000 | +| ogbn-arxiv | **0.317 ± 0.002** | 0.294 ± 0.004 | 0.142 ± 0.004 | 0.135 ± 0.003 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.161 ± 0.005 | 0.199 ± 0.004 | 0.212 ± 0.003 | +| ogbl-collab | **0.404 ± 0.001** | 0.389 ± 0.002 | 0.369 ± 0.002 | 0.368 ± 0.001 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.292 ± 0.001 | 0.354 ± 0.001 | 0.370 ± 0.001 | +| roadNet-CA | **0.346** | 0.255 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.310 | 0.104 | 0.239 | +| Yelp | **0.103** | 0.097 | 0.035 | 0.028 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.060 | 0.047 | 0.090 | +| Reddit | 0.311 | **0.403** | 0.110 | 0.092 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.345 | 0.231 | 0.274 | +| MovieLens-20M | **0.094** | 0.001 | 0.019 | 0.021 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.051 | 0.002 | 0.081 | +| ogbl-ppa | **0.391** | 0.291 | 0.215 | 0.196 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.251 | 0.262 | 0.270 | +| ogbl-citation2 | **0.261** | 0.239 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.179 | 0.201 | +| LiveJournal | **0.327** | 0.304 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.222 | 0.276 | +| ogbn-products | **0.337** | 0.316 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.216 | 0.247 | +| *mean rank* | **1.12** | 2.23 | 6.23 | 6.27 | 6.04 | 5.69 | 7.88 | 5.00 | 4.23 | 4.46 | 3.46 | +| *best on* | 23 / 26 | 15 / 26 | 0 / 22 | 0 / 22 | 1 / 15 | 0 / 15 | 0 / 15 | 1 / 15 | 1 / 23 | 0 / 26 | 0 / 26 | + + +
+ +### Node classification + +Accuracy of logistic regression on 10% of the labels (or the official split), and +micro-F1 on the multi-label graphs. + +
+Accuracy on every single-label graph + + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | 0.567 ± 0.013 | 0.550 ± 0.011 | 0.543 ± 0.008 | 0.555 ± 0.007 | 0.538 ± 0.011 | **0.572 ± 0.007** | 0.546 ± 0.016 | 0.450 ± 0.015 | 0.437 ± 0.009 | 0.486 ± 0.007 | 0.474 ± 0.009 | +| Cora | **0.788 ± 0.008** | 0.786 ± 0.007 | 0.765 ± 0.007 | 0.761 ± 0.009 | 0.755 ± 0.009 | 0.766 ± 0.003 | 0.715 ± 0.010 | 0.601 ± 0.009 | 0.589 ± 0.011 | 0.701 ± 0.008 | 0.688 ± 0.014 | +| PubMed | **0.812 ± 0.004** | 0.805 ± 0.003 | 0.802 ± 0.002 | 0.803 ± 0.003 | 0.800 ± 0.005 | 0.806 ± 0.001 | 0.776 ± 0.006 | 0.775 ± 0.005 | 0.756 ± 0.003 | 0.715 ± 0.003 | 0.707 ± 0.004 | +| DBLP | **0.808 ± 0.003** | 0.802 ± 0.003 | 0.802 ± 0.003 | 0.803 ± 0.003 | 0.798 ± 0.004 | 0.797 ± 0.003 | 0.777 ± 0.006 | 0.750 ± 0.001 | 0.732 ± 0.004 | 0.685 ± 0.004 | 0.679 ± 0.003 | +| Cora-Full | **0.589 ± 0.002** | 0.582 ± 0.001 | 0.569 ± 0.002 | 0.569 ± 0.004 | 0.573 ± 0.004 | 0.572 ± 0.004 | 0.486 ± 0.004 | 0.530 ± 0.000 | 0.534 ± 0.001 | 0.518 ± 0.005 | 0.520 ± 0.002 | +| Coauthor CS | **0.876 ± 0.001** | **0.876 ± 0.002** | 0.868 ± 0.002 | 0.869 ± 0.002 | 0.866 ± 0.001 | 0.864 ± 0.002 | 0.805 ± 0.003 | 0.821 ± 0.004 | 0.793 ± 0.003 | 0.789 ± 0.002 | 0.783 ± 0.005 | +| Amazon Photo | **0.916 ± 0.004** | **0.916 ± 0.003** | 0.907 ± 0.002 | 0.910 ± 0.002 | 0.907 ± 0.002 | 0.912 ± 0.006 | 0.857 ± 0.004 | 0.899 ± 0.002 | 0.878 ± 0.005 | 0.909 ± 0.005 | 0.913 ± 0.005 | +| Amazon Computers | **0.891 ± 0.002** | 0.888 ± 0.002 | 0.876 ± 0.002 | 0.877 ± 0.003 | 0.872 ± 0.002 | 0.885 ± 0.004 | 0.801 ± 0.003 | 0.868 ± 0.001 | 0.860 ± 0.004 | 0.890 ± 0.002 | 0.888 ± 0.002 | +| Coauthor Physics | 0.928 ± 0.001 | 0.927 ± 0.002 | 0.931 ± 0.001 | 0.931 ± 0.002 | 0.926 ± 0.001 | **0.932 ± 0.001** | 0.905 ± 0.001 | 0.896 ± 0.002 | 0.906 ± 0.002 | 0.868 ± 0.000 | 0.859 ± 0.004 | +| Flickr | 0.543 ± 0.001 | **0.551 ± 0.002** | 0.533 ± 0.001 | 0.533 ± 0.001 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.535 ± 0.001 | 0.493 ± 0.000 | 0.515 ± 0.001 | +| ogbn-arxiv | 0.681 ± 0.001 | 0.671 ± 0.002 | **0.685 ± 0.001** | **0.685 ± 0.001** | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.663 ± 0.002 | 0.569 ± 0.000 | 0.592 ± 0.003 | +| Reddit | **0.941** | 0.939 | 0.937 | 0.940 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.937 | 0.936 | 0.940 | +| ogbn-products | **0.645** | 0.602 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.556 | 0.562 | +| *mean rank* | **1.46** | 2.08 | 4.00 | 3.15 | 5.31 | 3.92 | 7.00 | 7.23 | 6.85 | 6.69 | 6.38 | +| *best on* | 10 / 13 | 6 / 13 | 0 / 12 | 1 / 12 | 0 / 9 | 2 / 9 | 0 / 9 | 0 / 9 | 0 / 12 | 0 / 13 | 0 / 13 | + + +
+ +
+Micro-F1 on every multi-label graph + + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| PPI | **0.134 ± 0.010** | 0.127 ± 0.012 | 0.106 ± 0.004 | 0.106 ± 0.006 | 0.120 ± 0.008 | 0.091 ± 0.013 | 0.076 ± 0.014 | 0.104 ± 0.010 | 0.096 ± 0.013 | 0.123 ± 0.008 | 0.129 ± 0.008 | +| Wikipedia POS | 0.381 ± 0.009 | **0.415 ± 0.011** | 0.369 ± 0.008 | 0.371 ± 0.010 | 0.368 ± 0.008 | 0.337 ± 0.036 | 0.361 ± 0.006 | 0.290 ± 0.071 | 0.365 ± 0.013 | 0.340 ± 0.006 | 0.409 ± 0.012 | +| BlogCatalog | 0.260 ± 0.007 | 0.306 ± 0.007 | 0.277 ± 0.007 | 0.284 ± 0.005 | 0.255 ± 0.007 | 0.276 ± 0.008 | 0.283 ± 0.005 | 0.213 ± 0.003 | 0.276 ± 0.005 | **0.332 ± 0.009** | 0.301 ± 0.009 | +| Yelp | 0.282 | 0.276 | 0.202 | 0.201 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.284** | 0.185 | 0.244 | +| *mean rank* | 3.25 | **1.75** | 4.75 | 4.00 | 6.25 | 8.00 | 7.00 | 8.50 | 5.25 | 4.50 | 2.00 | +| *best on* | 1 / 4 | 1 / 4 | 0 / 4 | 0 / 4 | 0 / 3 | 0 / 3 | 0 / 3 | 0 / 3 | 1 / 4 | 1 / 4 | 1 / 4 | + + +
+ +### Link ranking against sampled candidates + +MRR of a held-out edge against 500 sampled non-edges of the same node (the OGB link +datasets: against their official negatives), by dot product or cosine. + +
+MRR on every graph + + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | **0.458 ± 0.030** | 0.411 ± 0.026 | 0.400 ± 0.024 | 0.400 ± 0.018 | 0.389 ± 0.030 | 0.421 ± 0.025 | 0.291 ± 0.020 | 0.396 ± 0.029 | 0.386 ± 0.025 | 0.402 ± 0.029 | 0.393 ± 0.026 | +| Cora | **0.408 ± 0.011** | 0.382 ± 0.007 | 0.345 ± 0.007 | 0.348 ± 0.010 | 0.338 ± 0.002 | 0.364 ± 0.002 | 0.203 ± 0.006 | 0.351 ± 0.006 | 0.336 ± 0.005 | 0.363 ± 0.013 | 0.351 ± 0.007 | +| PPI | **0.204 ± 0.002** | 0.163 ± 0.004 | 0.070 ± 0.001 | 0.070 ± 0.001 | 0.135 ± 0.002 | 0.122 ± 0.002 | 0.091 ± 0.003 | 0.169 ± 0.002 | 0.125 ± 0.001 | 0.156 ± 0.004 | 0.183 ± 0.001 | +| PubMed | **0.450 ± 0.006** | 0.329 ± 0.003 | 0.312 ± 0.006 | 0.300 ± 0.007 | 0.420 ± 0.005 | 0.369 ± 0.007 | 0.207 ± 0.007 | 0.367 ± 0.003 | 0.328 ± 0.007 | 0.316 ± 0.006 | 0.330 ± 0.004 | +| DBLP | **0.540 ± 0.007** | 0.516 ± 0.006 | 0.381 ± 0.002 | 0.382 ± 0.002 | 0.433 ± 0.015 | 0.466 ± 0.005 | 0.259 ± 0.004 | 0.462 ± 0.006 | 0.433 ± 0.006 | 0.478 ± 0.005 | 0.492 ± 0.004 | +| Cora-Full | **0.658 ± 0.001** | 0.639 ± 0.002 | 0.532 ± 0.003 | 0.533 ± 0.004 | 0.587 ± 0.002 | 0.601 ± 0.002 | 0.340 ± 0.006 | 0.560 ± 0.004 | 0.579 ± 0.003 | 0.612 ± 0.002 | 0.614 ± 0.000 | +| Facebook (ego) | 0.595 ± 0.002 | 0.588 ± 0.002 | 0.447 ± 0.005 | 0.446 ± 0.001 | 0.454 ± 0.024 | 0.518 ± 0.003 | 0.256 ± 0.010 | 0.577 ± 0.003 | **0.601 ± 0.002** | 0.509 ± 0.004 | 0.550 ± 0.003 | +| Coauthor CS | 0.637 ± 0.001 | 0.619 ± 0.002 | 0.534 ± 0.002 | 0.538 ± 0.003 | 0.564 ± 0.018 | 0.611 ± 0.002 | 0.298 ± 0.002 | 0.556 ± 0.003 | 0.617 ± 0.002 | 0.630 ± 0.002 | **0.648 ± 0.001** | +| Amazon Photo | **0.519 ± 0.003** | 0.484 ± 0.002 | 0.326 ± 0.002 | 0.326 ± 0.003 | 0.378 ± 0.003 | 0.401 ± 0.003 | 0.187 ± 0.002 | 0.456 ± 0.002 | 0.427 ± 0.005 | 0.412 ± 0.003 | 0.427 ± 0.003 | +| Wikipedia POS | **0.270 ± 0.004** | 0.269 ± 0.004 | 0.046 ± 0.001 | 0.048 ± 0.002 | 0.070 ± 0.002 | 0.046 ± 0.001 | 0.069 ± 0.001 | 0.242 ± 0.005 | 0.058 ± 0.001 | 0.112 ± 0.003 | 0.097 ± 0.001 | +| Amazon Computers | **0.489 ± 0.002** | 0.460 ± 0.002 | 0.283 ± 0.002 | 0.285 ± 0.001 | 0.329 ± 0.003 | 0.399 ± 0.003 | 0.126 ± 0.001 | 0.421 ± 0.001 | 0.405 ± 0.003 | 0.394 ± 0.003 | 0.409 ± 0.003 | +| Coauthor Physics | 0.737 ± 0.002 | 0.719 ± 0.002 | 0.676 ± 0.003 | 0.674 ± 0.003 | 0.669 ± 0.002 | 0.651 ± 0.001 | 0.343 ± 0.003 | 0.621 ± 0.001 | 0.739 ± 0.001 | 0.725 ± 0.001 | **0.752 ± 0.002** | +| BlogCatalog | **0.222 ± 0.001** | 0.202 ± 0.000 | 0.070 ± 0.001 | 0.070 ± 0.001 | 0.092 ± 0.001 | 0.055 ± 0.000 | 0.165 ± 0.002 | 0.209 ± 0.001 | 0.070 ± 0.000 | 0.098 ± 0.000 | 0.096 ± 0.000 | +| Flickr | **0.297 ± 0.001** | 0.140 ± 0.000 | 0.244 ± 0.001 | 0.243 ± 0.000 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.195 ± 0.001 | 0.154 ± 0.001 | 0.189 ± 0.000 | +| MovieLens-1M | 0.148 ± 0.001 | 0.009 ± 0.002 | 0.060 ± 0.000 | 0.059 ± 0.000 | 0.044 ± 0.001 | 0.081 ± 0.001 | 0.108 ± 0.001 | **0.149 ± 0.012** | 0.144 ± 0.000 | 0.023 ± 0.001 | 0.102 ± 0.009 | +| ogbl-ddi | 0.027 ± 0.002 | 0.069 ± 0.001 | 0.005 ± 0.000 | 0.005 ± 0.000 | 0.010 ± 0.001 | 0.001 ± 0.000 | 0.012 ± 0.001 | **0.083 ± 0.002** | 0.002 ± 0.000 | 0.001 ± 0.000 | 0.002 ± 0.000 | +| ogbn-arxiv | **0.680 ± 0.001** | 0.659 ± 0.001 | 0.547 ± 0.002 | 0.539 ± 0.001 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.580 ± 0.002 | 0.593 ± 0.001 | 0.606 ± 0.002 | +| ogbl-collab | 0.095 ± 0.000 | **0.101 ± 0.001** | 0.095 ± 0.011 | 0.095 ± 0.006 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.039 ± 0.001 | 0.059 ± 0.001 | 0.053 ± 0.001 | +| roadNet-CA | 0.752 | 0.614 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.778** | 0.374 | 0.413 | +| Yelp | 0.495 | 0.490 | 0.302 | 0.285 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.445 | 0.361 | **0.513** | +| Reddit | 0.605 | **0.654** | 0.323 | 0.315 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.626 | 0.467 | 0.508 | +| MovieLens-20M | **0.237** | 0.025 | 0.105 | 0.104 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.227 | 0.020 | 0.202 | +| ogbl-ppa | **0.065** | 0.064 | 0.007 | 0.006 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.009 | 0.034 | 0.014 | +| ogbl-citation2 | 0.813 | **0.848** | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.793 | 0.829 | +| LiveJournal | 0.765 | **0.777** | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.685 | 0.776 | +| ogbn-products | **0.912** | 0.911 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.892 | 0.906 | +| *mean rank* | **1.50** | 2.35 | 6.15 | 6.35 | 6.12 | 5.88 | 7.31 | 4.81 | 4.58 | 4.42 | 3.27 | +| *best on* | 15 / 26 | 13 / 26 | 1 / 22 | 0 / 22 | 0 / 15 | 0 / 15 | 0 / 15 | 2 / 15 | 3 / 23 | 0 / 26 | 5 / 26 | + + +
+ +### Time and memory + +Time to embed the whole graph at 1024 dimensions, one method at a time on an idle +24-thread machine (median of three runs; single runs for the longest ones): + + +| Dataset | Cleora | pycleora 3.2 default | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| Cora | **81 ms** | 27.9 s | 5.7 s | 7.1 s | 7.0 s | 2.1 min | 8.2 s | 2.2 s | 2.7 s | 718 ms | 705 ms | +| PubMed | **198 ms** | 29.8 s | 44.2 s | 46.1 s | 57.0 s | 8.2 min | 2.9 min | 14.4 s | 16.3 s | 1.8 s | 1.2 s | +| Amazon Computers | **163 ms** | 25.7 s | 25.9 s | 30.1 s | 60.9 s | 5.3 min | 6.7 min | 2.4 min | 18.3 s | 2.5 s | 1.7 s | +| Flickr | **618 ms** | 62.9 s | 10.0 min | 10.1 min | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 82.6 s | 7.7 s | 5.0 s | +| ogbn-arxiv | **1.4 s** | 1.8 min | 17.4 min | 18.1 min | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 2.9 min | 13.1 s | 10.0 s | +| Yelp | **7.8 s** | 4.2 min | 97.1 min | 99.8 min | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 13.1 min | 67.7 s | 53.6 s | + + +
+Peak memory of the embedding process + + +| Dataset | Cleora | pycleora 3.2 default | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| Cora | **0.06 GB** | 0.37 GB | 0.26 GB | 0.28 GB | 0.39 GB | 0.27 GB | 0.26 GB | 0.17 GB | 0.45 GB | 0.40 GB | 0.26 GB | +| PubMed | **0.20 GB** | 0.46 GB | 0.61 GB | 0.64 GB | 2.02 GB | 3.90 GB | 4.73 GB | 0.41 GB | 1.53 GB | 1.87 GB | 1.04 GB | +| Amazon Computers | **0.16 GB** | 0.44 GB | 0.49 GB | 0.50 GB | 1.47 GB | 2.07 GB | 9.79 GB | 0.98 GB | 1.15 GB | 1.38 GB | 0.76 GB | +| Flickr | **0.77 GB** | 1.02 GB | 2.01 GB | 2.03 GB | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 6.10 GB | 7.89 GB | 4.24 GB | +| ogbn-arxiv | **1.43 GB** | 1.65 GB | 3.59 GB | 3.61 GB | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 11.39 GB | 14.84 GB | 7.94 GB | +| Yelp | **6.05 GB** | 6.21 GB | 14.65 GB | 14.66 GB | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 46.35 GB | 62.28 GB | 33.21 GB | + + +
+ +### With a validation set + +The tables above use no per-graph tuning. When labels or held-out edges are available, +choosing the number of iterations and the normalisation on them costs seconds per +candidate and adds about a point: + +
+Node classification, graph by graph + + +| Dataset | Cleora | Cleora, tuned | gain | Best baseline | +|---|---:|---:|---:|---| +| CiteSeer | 0.567 | **0.580** | +1.3 | NetMF 0.572 | +| Cora | 0.788 | **0.792** | +0.4 | NetMF 0.766 | +| PubMed | 0.812 | **0.815** | +0.3 | NetMF 0.806 | +| DBLP | 0.808 | **0.818** | +1.0 | node2vec 0.803 | +| Cora-Full | **0.589** | 0.587 | -0.1 | Walklets 0.573 | +| Coauthor CS | 0.876 | **0.884** | +0.7 | node2vec 0.869 | +| Amazon Photo | 0.916 | **0.924** | +0.8 | RandNE 0.913 | +| Amazon Computers | 0.891 | **0.899** | +0.9 | FastRP 0.890 | +| Coauthor Physics | 0.928 | **0.939** | +1.1 | NetMF 0.932 | +| Flickr | 0.543 | **0.553** | +1.0 | ProNE 0.535 | +| ogbn-arxiv | 0.681 | **0.700** | +1.9 | node2vec 0.685 | +| Reddit | 0.941 | **0.946** | +0.5 | RandNE 0.940 | +| ogbn-products | **0.645** | 0.604 | -4.1 | RandNE 0.562 | +| PPI | 0.134 | **0.134** | +0.0 | RandNE 0.129 | +| Wikipedia POS | 0.381 | **0.433** | +5.2 | RandNE 0.409 | +| BlogCatalog | 0.260 | 0.324 | +6.4 | FastRP 0.332 | +| Yelp | 0.282 | 0.282 | +0.0 | ProNE 0.284 | +| *mean gain (points)* | | | +1.0 | | + + +
+ +
+Link ranking, graph by graph + + +| Dataset | Cleora | Cleora, tuned | gain | Best baseline | +|---|---:|---:|---:|---| +| CiteSeer | **0.458** | **0.458** | +0.0 | NetMF 0.421 | +| Cora | **0.408** | **0.408** | +0.0 | NetMF 0.364 | +| PPI | 0.204 | **0.206** | +0.2 | RandNE 0.183 | +| PubMed | 0.450 | **0.459** | +0.9 | Walklets 0.420 | +| DBLP | 0.540 | **0.541** | +0.2 | RandNE 0.492 | +| Cora-Full | 0.658 | **0.660** | +0.3 | RandNE 0.614 | +| Facebook (ego) | 0.595 | **0.612** | +1.7 | ProNE 0.601 | +| Coauthor CS | 0.637 | **0.662** | +2.5 | RandNE 0.648 | +| Amazon Photo | 0.519 | **0.524** | +0.6 | HOPE 0.456 | +| Wikipedia POS | **0.270** | **0.270** | +0.0 | HOPE 0.242 | +| Amazon Computers | 0.489 | **0.494** | +0.5 | HOPE 0.421 | +| Coauthor Physics | 0.737 | **0.769** | +3.2 | RandNE 0.752 | +| BlogCatalog | **0.222** | **0.222** | +0.0 | HOPE 0.209 | +| Flickr | 0.297 | **0.306** | +1.0 | DeepWalk 0.244 | +| MovieLens-1M | 0.148 | 0.148 | +0.0 | HOPE 0.149 | +| ogbl-ddi | 0.027 | 0.069 | +4.2 | HOPE 0.083 | +| ogbn-arxiv | **0.680** | **0.680** | +0.0 | RandNE 0.606 | +| ogbl-collab | 0.095 | **0.134** | +3.9 | DeepWalk 0.095 | +| roadNet-CA | 0.752 | 0.752 | +0.0 | ProNE 0.778 | +| Yelp | 0.495 | **0.525** | +2.9 | RandNE 0.513 | +| Reddit | 0.605 | **0.747** | +14.3 | ProNE 0.626 | +| MovieLens-20M | 0.237 | **0.256** | +1.9 | ProNE 0.227 | +| ogbl-ppa | **0.065** | **0.065** | +0.0 | FastRP 0.034 | +| ogbl-citation2 | 0.813 | **0.850** | +3.7 | RandNE 0.829 | +| LiveJournal | 0.765 | **0.809** | +4.4 | RandNE 0.776 | +| ogbn-products | 0.912 | **0.916** | +0.4 | RandNE 0.906 | +| *mean gain (points)* | | | +1.8 | | + + +
+ +### Where Cleora is not the best + +Every graph on which another method is ahead, generated from the same tables: + +
+The full list + + +- **Similarity search among all nodes: a baseline is ahead of Cleora on** PubMed (Walklets 0.192, Cleora 0.185); MovieLens-1M (HOPE 0.107, Cleora 0.101); Reddit (ProNE 0.345, Cleora 0.311). +- **Similarity search among all nodes: the pycleora 3.2 default (whitening, 40 iterations) is ahead of Cleora on** roadNet-CA (0.3464 against 0.3458); Reddit (0.359 against 0.311). +- **Node classification: a baseline is ahead of Cleora on** CiteSeer (NetMF 0.572, Cleora 0.567); Coauthor Physics (NetMF 0.932, Cleora 0.928); ogbn-arxiv (node2vec 0.685, Cleora 0.681); Wikipedia POS (RandNE 0.409, Cleora 0.381); BlogCatalog (FastRP 0.332, Cleora 0.260); Yelp (ProNE 0.284, Cleora 0.282). +- **Node classification: the pycleora 3.2 default (whitening, 40 iterations) is ahead of Cleora on** Flickr (0.548 against 0.543); ogbn-arxiv (0.695 against 0.681); ogbn-products (0.741 against 0.645). +- **Link ranking against sampled candidates: a baseline is ahead of Cleora on** Facebook (ego) (ProNE 0.601, Cleora 0.595); Coauthor CS (RandNE 0.648, Cleora 0.637); Coauthor Physics (RandNE 0.752, Cleora 0.737); MovieLens-1M (HOPE 0.149, Cleora 0.148); ogbl-ddi (HOPE 0.083, Cleora 0.027); ogbl-collab (DeepWalk 0.0955, Cleora 0.0946); roadNet-CA (ProNE 0.778, Cleora 0.752); Yelp (RandNE 0.513, Cleora 0.495); Reddit (ProNE 0.626, Cleora 0.605); ogbl-citation2 (RandNE 0.829, Cleora 0.813); LiveJournal (RandNE 0.776, Cleora 0.765). +- **Link ranking against sampled candidates: the pycleora 3.2 default (whitening, 40 iterations) is ahead of Cleora on** Coauthor Physics (0.752 against 0.737); roadNet-CA (0.816 against 0.752); Yelp (0.501 against 0.495); ogbl-citation2 (0.827 against 0.813); LiveJournal (0.809 against 0.765). + + +
+ +What follows from that list: + +- **Similarity search is where Cleora leads most clearly.** Nearest-neighbour search + over its vectors finds more of a node's held-out neighbours than any baseline on + every graph but three - PubMed, MovieLens-1M and Reddit - and on small and mid-sized + graphs often by a wide margin. +- **Against 500 sampled candidates the lead is narrower.** On eleven graphs a baseline + ranks the true neighbour higher, mostly by a point or two: among them four of the + largest (Yelp, roadNet-CA, ogbl-citation2, LiveJournal), where RandNE or ProNE do so + with five to eight times the memory while finding fewer of the held-out neighbours + among all nodes. +- **The popularity prior is not for every graph.** On eight of the 26 - Reddit, + ogbl-ddi, MovieLens-1M, PPI, Facebook, Coauthor Physics, roadNet-CA, Yelp - the plain + cosine validates better, and that is what the tables then show for Cleora. +- **A learned weight per dimension helps ProNE most.** With logistic regression on + x∘y it is the best method on as many graphs as Cleora, though its mean rank stays + behind ([rank tables](#mean-rank-across-graphs)). +- **Single-label classification**: ahead on most graphs, by margins of a point or two + at most. +- **Multi-label classification is the closest contest.** Cleora is best on PPI and + within a fraction of a point of ProNE on Yelp; on Wikipedia POS and BlogCatalog + RandNE and FastRP are ahead of it - though on Wikipedia POS Cleora fed as two columns + beats them both. +- **Whitening pays off when there are far more nodes than dimensions.** The 3.2 default + (40 iterations, whitening after each) loses badly on small graphs and costs 30 to + 350 times the time, but on three of the five largest labelled graphs it classifies + better than plain Cleora - by ten points on ogbn-products. `embed(graph, 1024, 40, + whiten=True)` is worth a try there. +- **Two columns can beat one**: on Reddit, the densest graph, in both link + measurements; on ogbl-citation2, LiveJournal and two more against sampled + candidates; on five graphs in classification. The recommendation of one reflexive + column is a default, not a law. +- **Everything is at 1024 dimensions.** Most baselines were published at 128, and some + of them (ProNE and HOPE on the small graphs) are better there. +- **DeepWalk and node2vec did not finish** 1024 dimensions on graphs of two million + nodes and more within three hours: skip-gram training handles about 100,000 walk + steps per second on 24 threads. --- -## Library Comparison - -| Feature | **pycleora 3.2** | PyG | KarateClub | DGL | Node2Vec | StellarGraph | -|---------|:---:|:---:|:---:|:---:|:---:|:---:| -| CPU-only (no GPU needed) | **Yes** | Optional | Yes | Optional | Yes | Optional | -| Rust-powered core | **Yes** | No (C++) | No | No (C++) | No | No (TF) | -| No negative sampling needed | **Yes** | No | No | No | No | No | -| Deterministic output | **Yes** | No | No | No | No | No | -| Node2Vec / DeepWalk | **Built-in** | Yes | Yes | Yes | Yes | Yes | -| MLP classifier (no PyTorch) | **MLP** | Requires PyTorch | No | Requires PyTorch | No | Requires TF | -| Graph sampling | **6 methods** | Yes | No | Yes | No | Yes | -| Hyperparameter tuning | **Grid + Random** | Manual | No | Manual | No | Manual | -| Install size | **~5 MB** | ~500 MB+ | ~15 MB | ~400 MB+ | ~2 MB | ~600 MB+ | -| Actively maintained | **Yes** | Yes | Yes | Yes | Yes | Archived | +## Performance + +A round of Cleora reads, for every edge, the vector of the node at its other end: at +1024 dimensions 4 KB from somewhere in a matrix of gigabytes. Done row by row this +runs at the speed of the memory bus and no faster, however many cores there are. +pycleora 4.0 keeps the matrix in blocks of 16 columns - one cache line per node - and +finishes one block for all nodes before it starts the next, so that what the threads +read at random is a slab that fits the caches, and what comes from memory is the edge +list, in order. Work is scheduled by matrix entries instead of rows, hub rows are +split across threads, and the row normalisation costs no pass of its own. + +Time of one iteration (propagation and normalisation of the whole embedding matrix) +on an R-MAT graph, measured with +[`benchmarks/kernel_speed.py`](benchmarks/kernel_speed.py): + +0.6 million nodes, 12 million edges, 1024 dimensions; best of three runs: + +| Machine | pycleora | Threads | Build | One iteration | +|---|---|---:|---:|---:| +| Intel Core Ultra 9 275HX (24 threads) | 3.2.1 | 24 | 17.8 s | 5.39 s | +| | 4.0.0 | 24 | 1.19 s | 0.74 s | +| | 4.0.0 | 1 | 6.12 s | 5.16 s | +| Apple M4 (Mac mini, 10 cores) | 3.2.1 | 10 | 5.70 s | 4.02 s | +| | 4.0.0 | 10 | 0.88 s | 0.73 s | +| | 4.0.0 | 1 | 3.20 s | 2.84 s | + +On the Intel machine one thread of 4.0 does an iteration in the time 3.2.1 needs with +all 24. With all threads 4.0 is 7.3 times faster there and 5.5 times on Apple silicon, +and it builds the graph 15 and 6.5 times faster. The blocks gain most on dense graphs +of a few hundred thousand nodes (3.2 times over reading whole rows at 230,000 nodes and +30 million edges) and least on graphs of millions of nodes (1.4 times at 2.1 million +nodes and 40 million edges); the script prints both timings. Everything is +deterministic as well as parallel: the same input gives the same matrix and the same +embeddings, bit for bit, whatever the number of threads. --- -## Use Cases - -- **Recommendation Systems** — Products, content, restaurants, videos -- **Knowledge Graphs** — Entity and relation embeddings -- **Customer Lookalikes** — Find users with similar behavior patterns -- **Entity Resolution** — Match entities across data sources -- **Fraud Detection** — Detect anomalous patterns in transaction graphs -- **Social Networks** — Community detection and link prediction -- **Drug Discovery** — Molecule and protein interaction networks -- **Supply Chain** — Supplier and logistics graph analysis - -See [cleora.ai/use-cases](https://cleora.ai/use-cases) for detailed walkthroughs with code examples. +## How it works + +1. **Input.** Lines of entities, in typed columns: an edge list, baskets, sessions, + knowledge triples. +2. **Hypergraph.** Every line is a hyperedge; `complex::` columns hold several entities, + `reflexive::` relates a column to itself. Of an oversized hyperedge only the pairs + that involve one of its most frequent entities are kept (`hyperedge_trim_n`). +3. **Sparse transition matrix.** Co-occurrence counts, normalised by rows (`left`) or + symmetrically. +4. **Iteration.** Every entity starts from a pseudo-random vector that depends only on + its name and the seed. One iteration replaces every vector by the weighted average + of its neighbours' vectors and rescales it to unit length - one step of *all* random + walks at once, without sampling any. +5. **Output.** A dense matrix, one row per entity, identical on every run. --- -## How It Works +## More in the box -1. **Input Data** — Feed edge lists, interaction logs, or knowledge triples. Cleora accepts any TSV with typed columns. -2. **Hypergraph Construction** — Builds a heterogeneous hypergraph where a single edge can connect multiple entities of different types. -3. **Sparse Markov Matrix** — Constructs a sparse transition matrix (99%+ sparse). Rows normalized so each row sums to 1. -4. **Single Matrix Multiplication = All Walks** — One sparse matrix multiplication captures *every possible random walk* of a given length. No sampling, no noise. -5. **L2-Normalized + Whitened Propagation** — Each iteration replaces every node's embedding with the L2-normalized average of its neighbors and then whitens the embedding space. The default configuration runs 40 iterations at 256 dimensions. -6. **Embeddings Ready** — Dense, deterministic embedding vectors for every entity. Same input always yields same output. - ---- - -## Also Used By - -**Synerise** — AI/ML platform processing billions of e-commerce events daily. Cleora powers core recommendation and personalization: product embeddings from terabytes of transactions, substitute vs. complement detection, customer segmentation, cold-start solving — all on CPU in minutes. - -**Dailymotion** — Video platform with 350M+ monthly visitors. Personalized video recommendations with improved relevance and catalog coverage. - -**ML Competitions** — Cleora-powered solutions achieved top placements in KDD Cup 2021, WSDM WebTour 2021, and SIGIR eCom 2020 — beating deep learning approaches on travel, e-commerce, and web recommendation benchmarks. +| Module | What it does | +|--------|-------------| +| `pycleora.io_utils` | graphs from NumPy / pandas / SciPy / NetworkX, save and load embeddings | +| `pycleora.metrics` | classification, multi-label, ranking, retrieval and clustering metrics (checked against scikit-learn) | +| `pycleora.search` | nearest-neighbour search over embeddings | +| `pycleora.compress` | PCA, random projection, product quantization | +| `pycleora.align`, `pycleora.ensemble` | align embeddings of different graphs, combine embeddings | +| `pycleora.hetero` | per-relation embeddings of heterogeneous graphs | +| `pycleora.stats`, `pycleora.preprocess`, `pycleora.sampling`, `pycleora.community` | graph statistics, filtering, sampling, Louvain communities | +| `pycleora.classify`, `pycleora.tuning` | small classifiers on embeddings, grid and random search | +| `pycleora.algorithms` | compact NumPy / SciPy versions of ProNE, RandNE, NetMF, DeepWalk, node2vec, HOPE and GraRep behind the same interface | +| `pycleora.datasets` | loaders for public benchmark graphs, downloaded from their original sources | + +The algorithms in `pycleora.algorithms` are convenience implementations. The benchmark +on this page does not use them: it runs the reference implementations. --- -## FAQ - -**Q: What should I embed?** - -A: Any entities that interact with each other, co-occur or can be said to be present together in a given context. Examples can include: products in a shopping basket, locations frequented by the same people at similar times, employees collaborating together, chemical molecules being present in specific circumstances, proteins produced by the same bacteria, drug interactions, co-authors of the same academic papers, companies occurring together in the same LinkedIn profiles. - -**Q: How should I construct the input?** - -A: What works best is grouping entities co-occurring in a similar context, and feeding them in whitespace-separated lines using `complex::reflexive` modifier is a good idea. E.g. if you have product data, you can group the products by shopping baskets or by users. If you have urls, you can group them by browser sessions, or by (user, time window) pairs. Check out the usage example above. Grouping products by customers is just one possibility. +## In competitions and in production -**Q: Can I embed users and products simultaneously, to compare them with cosine similarity?** - -A: No, this is a methodologically wrong approach, stemming from outdated matrix factorization approaches. What you should do is come up with good product embeddings first, then create user embeddings from them. Feeding two columns e.g. `user product` into cleora will result in a bipartite graph. Similar products will be close to each other, similar users will be close to each other, but users and products will not necessarily be similar to each other. - -**Q: What embedding dimensionality to use?** - -A: The default is **256**. For larger production systems we often work from _1024_ to _4096_, but `256` is the baseline shipped by the library. - -**Q: How many iterations of Markov propagation should I use?** +:one:st place at [SIGIR eCom Challenge 2020](https://sigir-ecom.github.io/ecom20DCPapers/SIGIR_eCom20_DC_paper_1.pdf) -A: The default is **40** whitening-enhanced propagation steps. If you want more local, co-occurrence-style behavior you can dial that down manually; higher values bias more toward contextual similarity. +:two:nd place and Best Paper Award at [WSDM Booking.com Challenge 2021](http://ceur-ws.org/Vol-2855/challenge_short_3.pdf) -**Q: How do I incorporate external information, e.g. entity metadata, images, texts into the embeddings?** +:two:nd place at [Twitter Recsys Challenge 2021](https://recsys-twitter.com/competition_leaderboard/latest) -A: Just initialize the embedding matrix with your own vectors coming from a VIT, sentence-transformers, or a random projection of your numeric features. In that scenario fewer Markov iterations than the default `40` often work best. +:three:rd place at [KDD Cup 2021](https://ogb.stanford.edu/paper/kddcup2021/mag240m_SyneriseAI.pdf) -**Q: My embeddings don't fit in memory, what do I do?** +### Case study: Zomato -A: Cleora operates on dimensions independently. Initialize your embeddings with a smaller number of dimensions, run Cleora, persist to disk, then repeat. You can concatenate your resulting embedding vectors afterwards, but remember to normalize them afterwards! +**From 20 hours to under 5 minutes** - powering recommendations for 80M+ users across +500+ cities. Zomato's ML team needed graph embeddings for "People Like You" restaurant +recommendations. GraphSAGE took about 20 hours to process the customer-restaurant +interactions of a single city region; Cleora embeds them in under five minutes, and +they report it 197 times faster than DeepWalk in their pipeline. +[Read the Zomato blog post →](https://www.zomato.com/blog/connecting-the-dots-strengthening-recommendations-for-our-customers-part-two/) -**Q: Is there a minimum number of entity occurrences?** +### Also used by -A: No, an entity `A` co-occurring just 1 time with some other entity `B` will get a proper embedding, i.e. `B` will be the most similar to `A`. The other way around, `A` will be highly ranked among nearest neighbors of `B`, which may or may not be desirable, depending on your use case. Feel free to prune your input to Cleora to eliminate low-frequency items. +**Synerise** - AI/ML platform processing billions of e-commerce events daily: product +embeddings from terabytes of transactions, customer segmentation, cold-start +recommendations, all on CPU. -**Q: Are there any edge cases where Cleora can fail?** +**Dailymotion** - video platform with 350M+ monthly visitors: personalised video +recommendations. -A: Cleora works best for relatively sparse hypergraphs. If all your hyperedges contain some very common entity `X`, e.g. a _shopping bag_, then it will degrade the quality of embeddings by degenerating shortest paths in the random walk. It is a good practice to remove such entities from the hypergraph. +--- -**Q: How can Cleora be so fast and accurate at the same time?** +## FAQ -A: Not using negative sampling is a great boon. By constructing the (sparse) Markov transition matrix, Cleora explicitly performs all possible random walks in a hypergraph in one big step (a single matrix multiplication). That's what we call a single _iteration_. The default configuration performs 40 such iterations with whitening after every step. Negative sampling or randomly selecting random walks tend to introduce a lot of noise - Cleora is free of those burdens. +**What should I embed?** +Any entities that interact, co-occur or appear together in a context: products in a +basket, locations visited by the same people, co-authors, molecules in a reaction. + +**How should I construct the input?** +Group entities that share a context into one line and use a `complex::reflexive` +column: products by basket or by user, URLs by session. Grouping matters more than +any parameter. + +**Can I embed users and products together and compare them with cosine similarity?** +Not with two columns: `user product` gives a bipartite graph, in which, after any +number of iterations, user vectors and product vectors are built from disjoint sets of +initial vectors and are unrelated to each other. Embed the products (one column, +grouped by user), then build user vectors from the products of each user. + +**What dimensionality?** +The default is 256. The benchmark uses 1024; larger production systems use 1024 to +4096. Time and memory grow linearly with the dimensionality. + +**How many iterations?** +`num_iterations="auto"`, or `graph.suggest_iterations(purpose=...)` when you know what +the vectors are for, or a sweep on validation data when you have labels. Typical values +are 8-16 for similarity and 12-48 for classification with one reflexive column, about +half of that with two columns. + +**How do I add entity metadata, images or text?** +Pass your own vectors as `initial_embeddings`; a few iterations then spread them along +the graph. + +**My embeddings do not fit in memory.** +Dimensions are independent: compute slices with different `seed`s, store them, and +concatenate. Normalise the rows of the concatenation. + +**Is there a minimum number of occurrences?** +No. An entity that occurs once gets a vector next to the entities it occurred with. +Whether rare entities should be kept is a question about your data. + +**When does Cleora fail?** +When almost every hyperedge contains the same entity (a "shopping bag" item), it +shortens every path and blurs the embedding: remove such entities. And when the +labels you care about are not reflected in the graph structure, no structural +embedding helps - see the multi-label rows of the benchmark. --- ## Resources - **Website**: [cleora.ai](https://cleora.ai) -- **API Reference**: [cleora.ai/api](https://cleora.ai/api) -- **Benchmarks**: [cleora.ai/benchmarks](https://cleora.ai/benchmarks) - **Whitepaper**: ["Cleora: A Simple, Strong and Scalable Graph Embedding Scheme"](https://arxiv.org/abs/2102.02302) -- **GitHub**: [github.com/BaseModelAI/cleora](https://github.com/BaseModelAI/cleora) - **PyPI**: [pypi.org/project/pycleora](https://pypi.org/project/pycleora/) +- **Changes**: [CHANGELOG.md](CHANGELOG.md) ## Cite -Please cite [our paper](https://arxiv.org/abs/2102.02302) (and the respective papers of the methods used) if you use this code in your own work: - ``` @article{DBLP:journals/corr/abs-2102-02302, author = {Barbara Rychalska, Piotr Babel, Konrad Goluchowski, Andrzej Michalowski, Jacek Dabrowski}, diff --git a/benches/cleora_benchmark.rs b/benches/cleora_benchmark.rs index 37f5f5c..00862ff 100644 --- a/benches/cleora_benchmark.rs +++ b/benches/cleora_benchmark.rs @@ -1,159 +1,162 @@ -use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion}; -use fnv::FnvHasher; -use std::collections::hash_map::DefaultHasher; -use std::hash::Hasher; -use twox_hash::XxHash64; - -fn default_hash(entity: &str) -> u64 { - let mut hasher = DefaultHasher::new(); - hasher.write(entity.as_bytes()); - hasher.finish() +//! Benchmarks of the kernels that dominate a Cleora run: building the sparse matrix, +//! one propagation step, row normalisation, the covariance behind whitening, and a +//! complete classic embedding. +//! +//! Run with `cargo bench`. The graph is a fixed pseudo-random one, so numbers are +//! comparable between runs and commits (but not with numbers of real graphs: random +//! graphs have none of the locality real ones have). + +use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput}; +use pycleora::configuration::Configuration; +use pycleora::embedding::{ + column_mean_and_covariance, embed, initialize, l2_normalize_rows, propagate, thread_pool, + MarkovType, +}; +use pycleora::pipeline::{build_graph_from_int_edges, build_graph_from_lines}; +use pycleora::sparse_matrix::SparseMatrix; + +const NODES: i64 = 100_000; +const EDGES: usize = 500_000; +const DIM: usize = 128; + +/// SplitMix64: a tiny deterministic generator, so the benchmark needs no extra crate. +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } } -fn xx_hash(entity: &str) -> u64 { - let mut hasher = XxHash64::default(); - hasher.write(entity.as_bytes()); - hasher.finish() +fn random_edges() -> (Vec, Vec) { + let mut rng = Rng(7); + let mut sources = Vec::with_capacity(EDGES); + let mut targets = Vec::with_capacity(EDGES); + for _ in 0..EDGES { + sources.push((rng.next() % NODES as u64) as i64); + targets.push((rng.next() % NODES as u64) as i64); + } + (sources, targets) } -fn fnv_hash(entity: &str) -> u64 { - let mut hasher = FnvHasher::default(); - hasher.write(entity.as_bytes()); - hasher.finish() +fn configuration(num_workers: usize) -> Configuration { + Configuration::new("complex::reflexive::node", 16, Some(num_workers)) + .expect("valid column definition") } -fn hash_benchmark(c: &mut Criterion) { - c.bench_function("hash", |b| b.iter(|| fnv_hash(black_box("cleora")))); +fn build_graph(num_workers: usize) -> SparseMatrix { + let (sources, targets) = random_edges(); + build_graph_from_int_edges(&configuration(num_workers), &sources, &targets, None) + .expect("graph builds") + .0 } -fn bench_hashes(c: &mut Criterion) { - let mut group = c.benchmark_group("Hashing"); - for s in ["Poland", "Germany", "USA", "United Kingdom", "Norway"].iter() { - group.bench_with_input(BenchmarkId::new("Default", s), s, |b, s| { - b.iter(|| default_hash(s)) - }); - group.bench_with_input(BenchmarkId::new("XXHash", s), s, |b, s| { - b.iter(|| xx_hash(s)) - }); - group.bench_with_input(BenchmarkId::new("FnvHash", s), s, |b, s| { - b.iter(|| fnv_hash(s)) - }); +fn worker_counts() -> Vec { + let available = std::thread::available_parallelism() + .map(|n| n.get()) + .unwrap_or(1); + let mut counts = vec![1]; + if available > 1 { + counts.push(available); } - group.finish(); + counts } -struct CartesianProduct { - lengths: Vec, - indices: Vec, -} - -impl CartesianProduct { - fn new(lengths: Vec) -> CartesianProduct { - let indices = vec![0; lengths.len()]; - CartesianProduct { lengths, indices } +fn bench_graph_construction(c: &mut Criterion) { + let (sources, targets) = random_edges(); + let lines: Vec = sources + .iter() + .zip(&targets) + .map(|(s, t)| format!("{} {}", s, t)) + .collect(); + + let mut group = c.benchmark_group("graph_construction"); + group.sample_size(10); + group.throughput(Throughput::Elements(EDGES as u64)); + for workers in worker_counts() { + let config = configuration(workers); + group.bench_with_input(BenchmarkId::new("from_edges", workers), &workers, |b, _| { + b.iter(|| build_graph_from_int_edges(&config, &sources, &targets, None).unwrap()) + }); + group.bench_with_input(BenchmarkId::new("from_lines", workers), &workers, |b, _| { + b.iter(|| build_graph_from_lines(&config, &lines, None).unwrap()) + }); } + group.finish(); } -impl Iterator for CartesianProduct { - type Item = Vec; - - fn next(&mut self) -> Option { - let result = self.indices.clone(); - let len = self.indices.len(); - for i in (0..len).rev() { - if self.indices[i] == (self.lengths[i] - 1) { - self.indices[i] = 0; - if i == 0 { - return None; - } - } else { - self.indices[i] += 1; - break; - } +fn bench_propagation(c: &mut Criterion) { + let graph = build_graph(worker_counts().into_iter().max().unwrap_or(1)); + let input = initialize(&graph.entity_ids, DIM, 0); + let mut output = vec![0f32; input.len()]; + + let mut group = c.benchmark_group("propagation"); + group.sample_size(20); + group.throughput(Throughput::Elements(graph.nnz() as u64)); + for workers in worker_counts() { + let pool = thread_pool(workers); + for (name, kind) in [ + ("left", MarkovType::Left), + ("symmetric", MarkovType::Symmetric), + ] { + group.bench_with_input(BenchmarkId::new(name, workers), &workers, |b, _| { + b.iter(|| pool.install(|| propagate(&graph, &input, &mut output, DIM, kind))) + }); } - Some(result) } + group.finish(); } -fn generate_combinations_with_length( - hashes: Vec>, - lens: Vec, - transient_lens: Vec, -) -> Vec> { - let row_length = lens.len(); - let mut combinations = 1; - for &len in &lens { - combinations *= len; - } - - let mut transient_combinations = 1; - for transient_len in transient_lens { - transient_combinations *= transient_len; - } - - let total_combinations = u64::from(combinations * transient_combinations); - - let mut result: Vec> = Vec::with_capacity(combinations as usize); - let cartesian = CartesianProduct::new(lens); - let mut counter = 0; - - for indices in cartesian { - let mut arr: Vec = Vec::with_capacity(row_length + 1); - arr.push(total_combinations); - let hashes_length = hashes.len(); - for i in 0..hashes_length { - let id = indices[i]; - let value = hashes.get(i).unwrap().get(id as usize).unwrap(); - arr.push(*value); - } - result.insert(counter, arr); - counter += 1; +fn bench_postprocessing(c: &mut Criterion) { + let graph = build_graph(worker_counts().into_iter().max().unwrap_or(1)); + let rows = graph.num_entities(); + let embeddings = initialize(&graph.entity_ids, DIM, 0); + + let mut group = c.benchmark_group("postprocessing"); + group.sample_size(20); + group.throughput(Throughput::Elements(rows as u64)); + for workers in worker_counts() { + let pool = thread_pool(workers); + group.bench_with_input( + BenchmarkId::new("l2_normalize", workers), + &workers, + |b, _| { + let mut scratch = embeddings.clone(); + b.iter(|| pool.install(|| l2_normalize_rows(&mut scratch, DIM))) + }, + ); + group.bench_with_input(BenchmarkId::new("covariance", workers), &workers, |b, _| { + b.iter(|| pool.install(|| column_mean_and_covariance(&embeddings, rows, DIM))) + }); } - - result + group.finish(); } -fn generate_combinations_with_length_benchmark(c: &mut Criterion) { - let hashes = vec![ - vec![ - 12528106613309397869, - 9708327007652588651, - 14980293948133487802, - 12266831465718424827, - 17286486014462130850, - 11758309849656381133, - 10347099512938872293, - 804562942093240192, - 3059164883323983321, - ], - vec![ - 12528106613309397869, - 9708327007652588651, - 14980293948133487802, - 12266831465718424827, - 17286486014462130850, - 11758309849656381133, - 10347099512938872293, - 804562942093240192, - 3059164883323983321, - ], - ]; - let lens = vec![9, 9]; - let transient_lens = vec![1]; - c.bench_function("generate_combinations_with_length", |b| { - b.iter(|| { - generate_combinations_with_length( - black_box(hashes.clone()), - black_box(lens.clone()), - black_box(transient_lens.clone()), - ) - }) - }); +fn bench_embedding(c: &mut Criterion) { + let graph = build_graph(worker_counts().into_iter().max().unwrap_or(1)); + + let mut group = c.benchmark_group("classic_embedding"); + group.sample_size(10); + for workers in worker_counts() { + let pool = thread_pool(workers); + group.bench_with_input( + BenchmarkId::new("8_iterations", workers), + &workers, + |b, _| b.iter(|| pool.install(|| embed(&graph, DIM, 0, MarkovType::Left, 8, 0.0, 0.0))), + ); + } + group.finish(); } criterion_group!( benches, - generate_combinations_with_length_benchmark, - bench_hashes + bench_graph_construction, + bench_propagation, + bench_postprocessing, + bench_embedding ); criterion_main!(benches); diff --git a/benchmarks/README.md b/benchmarks/README.md new file mode 100644 index 0000000..b52e22b --- /dev/null +++ b/benchmarks/README.md @@ -0,0 +1,622 @@ +# The benchmark + +How the numbers in the main [README](../README.md) were produced, and how to produce +them again. All result tables are in [RESULTS.md](RESULTS.md); both files are filled +by `make_report.py` from the job files, no number in them is typed by hand. + +```bash +benchmarks/replicate.sh ~/cleora-bench # everything: environments, data, runs, tables, figures +benchmarks/replicate.sh ~/cleora-bench --datasets cora,citeseer --no-timing # a small part of it +``` + +- [What is measured](#what-is-measured) +- [Datasets](#datasets) +- [Methods](#methods) +- [Node classification](#node-classification) +- [Similarity search and link ranking](#similarity-search-and-link-ranking) +- [One configuration per method](#one-configuration-per-method) +- [The popularity prior](#the-popularity-prior) +- [Number of iterations](#number-of-iterations) +- [Time and memory](#time-and-memory) +- [Figures](#figures) +- [Replication](#replication) +- [What the benchmark does not show](#what-the-benchmark-does-not-show) + +## What is measured + +Every method turns a graph into one vector per node, without seeing node labels or +node features. The vectors are then frozen and measured in the three ways embeddings +are used in production: + +| Use | Graphs | What is measured | What it stands for | +|---|---|---|---| +| similarity search | all | the held-out neighbours of a node are retrieved among all nodes of the graph by dot product or cosine | a nearest-neighbour index over the vectors: candidate generation, "similar items" | +| node classification | those with node labels | logistic regression and an MLP predict the label of a node from its vector | the vectors as input features of a downstream model | +| link ranking | all | a held-out edge is ranked against 500 sampled non-edges by dot product or cosine, and by a dot product with one learned weight per dimension | scoring a short list of candidates | + +Not every graph has node labels: Facebook, MovieLens, roadNet-CA, LiveJournal and the +OGB link datasets take part in similarity search and link ranking only. + +Every method produces **1024-dimensional** vectors, and every column of the main +tables is **one configuration** of a method, the same for every graph: nothing is +chosen per dataset, for Cleora or for the baselines. + +## Datasets + +All graphs are downloaded from their original public sources by +`prepare_datasets.py` (through PyTorch Geometric and OGB where those ship the +dataset) and stored as undirected, unweighted-or-weighted edge lists without +self-loops and duplicate edges. Nodes without any edge cannot be embedded from +structure and are removed for every method alike. The number of nodes and edges of +every prepared graph is checked against the numbers below; a source that starts +serving different data makes the preparation fail instead of silently changing the +benchmark. + + +| Dataset | Nodes | Edges | Mean degree | Node labels | Seeds | Source | +|---|---:|---:|---:|---|---:|---| +| CiteSeer | 3,279 | 4,552 | 2.8 | 6 classes | 3 | Yang, Cohen, Salakhutdinov, ICML 2016; Sen et al., AI Magazine 2008 | +| Cora | 2,708 | 5,278 | 3.9 | 7 classes | 3 | Yang, Cohen, Salakhutdinov, ICML 2016; Sen et al., AI Magazine 2008 | +| PPI | 3,860 | 37,845 | 19.6 | 50 labels (multi-label) | 3 | Grover and Leskovec, node2vec, KDD 2016 | +| PubMed | 19,717 | 44,324 | 4.5 | 3 classes | 3 | Yang, Cohen, Salakhutdinov, ICML 2016; Sen et al., AI Magazine 2008 | +| DBLP | 17,716 | 52,867 | 6.0 | 4 classes | 3 | Bojchevski and Günnemann, ICLR 2018 | +| Cora-Full | 19,793 | 63,421 | 6.4 | 70 classes | 3 | Bojchevski and Günnemann, ICLR 2018 | +| Facebook (ego) | 4,039 | 88,234 | 43.7 | – | 3 | McAuley and Leskovec, NeurIPS 2012 | +| Coauthor CS | 18,333 | 81,894 | 8.9 | 15 classes | 3 | Shchur et al., Pitfalls of GNN Evaluation, 2018 | +| Amazon Photo | 7,535 | 119,081 | 31.6 | 8 classes | 3 | Shchur et al., Pitfalls of GNN Evaluation, 2018; McAuley et al., SIGIR 2015 | +| Wikipedia POS | 4,777 | 92,295 | 38.6 | 40 labels (multi-label) | 3 | Grover and Leskovec, node2vec, KDD 2016; weighted | +| Amazon Computers | 13,471 | 245,861 | 36.5 | 10 classes | 3 | Shchur et al., Pitfalls of GNN Evaluation, 2018; McAuley et al., SIGIR 2015 | +| Coauthor Physics | 34,493 | 247,962 | 14.4 | 5 classes | 3 | Shchur et al., Pitfalls of GNN Evaluation, 2018 | +| BlogCatalog | 10,312 | 333,983 | 64.8 | 39 labels (multi-label) | 3 | Tang and Liu, KDD 2009; Perozzi et al., DeepWalk, KDD 2014 | +| Flickr | 89,250 | 449,878 | 10.1 | 7 classes | 3 | Zeng et al., GraphSAINT, ICLR 2020; official node split | +| MovieLens-1M | 9,746 | 1,000,209 | 205.3 | – | 3 | Harper and Konstan, The MovieLens Datasets, ACM TiiS 2015; bipartite | +| ogbl-ddi | 4,267 | 1,067,911 | 500.5 | – | 3 | Hu et al., Open Graph Benchmark, NeurIPS 2020; official link split | +| ogbn-arxiv | 169,343 | 1,157,799 | 13.7 | 40 classes | 3 | Hu et al., Open Graph Benchmark, NeurIPS 2020; official node split | +| ogbl-collab | 235,868 | 967,632 | 8.2 | – | 3 | Hu et al., Open Graph Benchmark, NeurIPS 2020; official link split | +| roadNet-CA | 1,965,206 | 2,766,607 | 2.8 | – | 1 | Leskovec et al., Internet Mathematics 2009 | +| Yelp | 716,847 | 6,618,986 | 18.5 | 100 labels (multi-label) | 1 | Zeng et al., GraphSAINT, ICLR 2020; official node split | +| Reddit | 232,965 | 57,307,946 | 492.0 | 41 classes | 1 | Hamilton, Ying, Leskovec, GraphSAGE, NeurIPS 2017; official node split | +| MovieLens-20M | 165,237 | 20,000,263 | 242.1 | – | 1 | Harper and Konstan, The MovieLens Datasets, ACM TiiS 2015; bipartite | +| ogbl-ppa | 576,289 | 21,231,931 | 73.7 | – | 1 | Hu et al., Open Graph Benchmark, NeurIPS 2020; official link split | +| ogbl-citation2 | 2,926,620 | 30,351,880 | 20.7 | – | 1 | Hu et al., Open Graph Benchmark, NeurIPS 2020; official link split | +| LiveJournal | 3,997,962 | 34,681,189 | 17.3 | – | 1 | Yang and Leskovec, ICDM 2012 | +| ogbn-products | 2,400,608 | 61,859,012 | 51.5 | 47 classes | 1 | Hu et al., Open Graph Benchmark, NeurIPS 2020; official node split | + + +Graphs up to about a million edges are run with three seeds, larger ones with one. + +## Methods + +**Cleora** is `pycleora.embed(graph, 1024, k)` on a graph built with +`SparseMatrix.from_edges`. A homogeneous graph can be given to Cleora in two ways, and +both are benchmarked: + +| Setup | Columns | Matrix | +|---|---|---| +| one column | `complex::reflexive::node` | every edge is a two-node hyperedge of a column related to itself: every node is also its own neighbour, the walk stays where it is half of the time | +| two columns | `src dst` | the plain adjacency matrix | + +Each can be run with the left (`D⁻¹A`) and the symmetric (`D⁻½AD⁻½`) normalisation: +four *families*. The columns of the main tables: + +- **Cleora** (one column) and **Cleora, two columns**: the settings the README + recommends for the task, for every graph alike - + `embed(graph, 1024, graph.suggest_iterations(propagation, purpose), propagation)` + with `propagation="left"`, `purpose="classification"` for node classification and + `propagation="symmetric"`, `purpose="similarity"` for similarity search and link + ranking, followed by `scale_by_popularity` with the exponent of the purpose + ([below](#the-popularity-prior)). The two columns are the same method fed in two + ways; they are shown side by side and are not ranked against each other. + +Outside the main tables, in tables of their own: + +- **Cleora, tuned**: the number of iterations (from a sweep over 1, 2, 3, 4, 6, 8, 12, + 16, 24, 32, 48, 64, `select_iterations.py`) and the family chosen on validation + data - what a user with a validation set can add. +- **The four families**, each on its own. +- **pycleora 3.2 default**: 40 iterations with PCA whitening after each. This was the + default of `embed()` until this release. + +**Baselines** run their authors' code or a widely used library, with the settings the +authors recommend, at 1024 dimensions. None of them is re-implemented here; +`cleora_bench/methods.py` contains the exact calls. + +| Method | Implementation | Settings | +|---|---|---| +| DeepWalk | [PecanPy](https://github.com/krishnanlab/PecanPy) 2.0.9 walks + gensim skip-gram | 10 walks of length 80 per node, window 10, negative sampling | +| node2vec | same, biased walks | p = 1, q = 0.5, otherwise as DeepWalk | +| Walklets | [karateclub](https://github.com/benedekrozemberczki/karateclub) 1.3.3 | 4 scales × dim/4 | +| NetMF | [authors' code](https://github.com/xptree/NetMF) (`77286b8`) | large-window variant, T = 10, b = 1, rank 1024 | +| GraRep | karateclub 1.3.3 | 4 orders × dim/4 | +| HOPE | karateclub 1.3.3 | common-neighbours proximity | +| ProNE | [authors' code](https://github.com/THUDM/ProNE) (`873630a`) | μ = 0.2, θ = 0.5, 10 Chebyshev steps | +| FastRP | [authors' code](https://github.com/GTmac/FastRP) (`3a6a71c`) | weights (0, 0, 1, 6.67), β = −0.64 | +| RandNE | [authors' code](https://github.com/ZW-ZHANG/RandNE) (`bf06bd7`) | transition matrix, q = 3, weights (1, 10², 10⁴, 10⁵) | + +Three adaptations were unavoidable and do not change what is computed. NetMF imports +Theano, which has been unmaintained since 2020: its two element-wise expressions are +restated in NumPy. Its sparse eigensolver (ARPACK) gives up on graphs that fall into +many pieces, as the sparsest graphs do once a quarter of their edges is held out: the +same eigenpairs are then computed with a dense solver. FastRP's loop over the higher +powers multiplies sparse matrices that fill in completely: the same products are +computed densely. + +NetMF, GraRep, HOPE and Walklets (in these implementations) build dense n × n matrices +or Python-level graph objects; they are run on graphs of up to 60,000 (NetMF) and +40,000 (the karateclub methods) nodes and marked `n/a (size)` beyond. Every run has a +time limit of six hours; a method that exceeds it, or the memory of the machine, is +marked as such. + +On the five largest graphs (ogbn-products, ogbl-citation2, LiveJournal, roadNet-CA, +MovieLens-20M) the limit is three hours per run; Cleora needs one to three minutes +there. ProNE cannot produce 1024 dimensions for more than about two million nodes: its +randomised SVD hands SciPy's LU a matrix of more than 2³¹ elements, which is reported +as `out of memory`. + +Every method runs in a fresh process with the same number of threads. + +## Node classification + +The vectors come from the whole graph. Labelled nodes are split into train, validation +and test: the official split where the dataset defines one, otherwise 10% / 10% / 80% +at random (stratified for single-label graphs), three splits per embedding. With three +seeds that makes nine evaluations per number. + +Two probes, each fitted on train, tuned on validation and scored once on test: + +| Probe | Model | Tuned on validation | +|---|---|---| +| logistic regression | multinomial (single-label) or one per label (multi-label), L-BFGS to convergence | L2 penalty from 10² … 10⁻⁸, feature scaling | +| MLP | one hidden layer of 512 units, dropout 0.5, 100 epochs of AdamC (warm-up, cosine decay) | weight decay 10⁻² or 10⁻¹, the epoch, feature scaling | + +*Feature scaling* is one of: none, unit-norm rows, standardised columns. Embedding +methods differ in what the scale of their coordinates means - standardising helps +some and destroys the spectrum of an SVD-based embedding - so the scaling is chosen on +validation for every method like any other hyper-parameter of the probe. + +Metrics (`pycleora.metrics`, checked against scikit-learn in the test suite): + +- single-label: accuracy, balanced accuracy, macro-F1, weighted F1, Matthews + correlation, Cohen's κ, top-3 and top-5 accuracy, macro one-vs-rest ROC-AUC and + average precision; +- multi-label: micro-, macro- and sample-averaged F1 at a score threshold of zero, + the same with the number of labels of every node given (the protocol of the + DeepWalk and node2vec papers, `*_known_count`), subset accuracy, Hamming loss, + micro and macro ROC-AUC and average precision, label-ranking average precision, + precision@1. + +## Similarity search and link ranking + +The edges are split at random into four disjoint sets: + +| Set | Share | Used for | +|---|---:|---| +| embed | 75% | the only edges the embedding method sees | +| probe | 10% | positives for training the pair probe | +| validation | 5% | model selection | +| test | 10% | the reported numbers | + +The probe positives are deliberately *not* in the embedded graph: a probe trained on +edges the vectors were fitted to learns to recognise memorised edges, not to predict +missing ones. On large graphs the three held-out sets are capped (500,000 / 20,000 / +50,000 edges). Datasets with an official link split (OGB) keep their official +positives and negatives; only the probe positives are taken out of the official +training edges. + +A pair of nodes (x, y) is scored in three ways: + +| Probe | Score of a pair (x, y) | Training | +|---|---|---| +| dot product | xᵀy | none | +| cosine | xᵀy / (‖x‖‖y‖) | none | +| logistic regression | wᵀ(x∘y) + b: a dot product with one learned weight per dimension | L-BFGS on the probe positives and three sampled negatives per positive (at most one million pairs); L2 penalty chosen on validation MRR | + +**Similarity search among all nodes.** For the two training-free scores, the held-out +neighbours of up to 10,000 query nodes are ranked among *all* nodes of the graph, with +the known neighbours filtered out - what a nearest-neighbour index over the vectors +returns. Metrics: recall@k, precision@k, hit rate@k, nDCG@k and MAP@k for k = 10, 20, +50, and the MRR and Hits@k of every held-out edge in the full ranking. In a bipartite +graph only nodes of the other side are candidates. + +**Link ranking against sampled candidates.** Every validation or test edge (u, v) is +ranked, in both directions, against 500 random nodes that are not neighbours of the +query node in the full graph (the OGB link datasets: against their official +negatives). All methods and all probes rank the same candidates. Metrics: MRR, mean +and median rank, Hits@1/3/10/50/100, ROC-AUC and average precision. + +Edge weights (Wikipedia POS) are used for node classification and ignored in the link +task, whose split is over unweighted edges. + +## One configuration per method + +Every column of the main tables is a single configuration at 1024 dimensions, applied +unchanged to every graph. Validation data is used inside the probes (their +regularisation and feature scaling) and nowhere else; test scores +are never used to choose anything. + +Two decisions about Cleora were made once, for all graphs, and not on test scores: + +- *The normalisation per task.* Left for classification, symmetric for link ranking: + the one with the better mean validation score over the graphs. + + +| Task | Graphs | one column, left | one column, symmetric | two columns, left | two columns, symmetric | +|---|---:|---:|---:|---:|---:| +| node classification (logistic regression) | 17 | 0.6661 (6) | 0.6511 (3) | 0.6676 (3) | 0.6590 (5) | +| link ranking (cosine) | 26 | 0.4242 (3) | 0.4575 (21) | 0.3870 (1) | 0.4033 (1) | + + +- *The number of iterations.* A rule on two statistics of the graph, fitted on + validation curves ([below](#number-of-iterations)). +- *The popularity prior and its two exponents* ([next section](#the-popularity-prior)). + +In similarity search and in link ranking a method is given the better of dot product +and cosine on validation (the validation MRR against sampled candidates); for Cleora +that is the choice between the popularity prior and none. + +A number is the mean over seeds and splits; ± is the standard deviation over them. +The best number of a row is bold, the second best underlined. *mean rank* is the +average rank of a method over the rows of a table (a method without a result ranks +after all that have one); *best on* counts the rows a method wins. Rows on which +only one method has a result are left out of both. The two Cleora columns are the +same method fed in two ways and do not compete with each other in these two lines: +every baseline is ranked against Cleora with one column, and each Cleora column +against the baselines only. + +What choosing the number of iterations and the family on validation data adds is +reported separately: + + +| Dataset | Cleora | Cleora, tuned | gain | Best baseline | +|---|---:|---:|---:|---| +| CiteSeer | 0.567 | **0.580** | +1.3 | NetMF 0.572 | +| Cora | 0.788 | **0.792** | +0.4 | NetMF 0.766 | +| PubMed | 0.812 | **0.815** | +0.3 | NetMF 0.806 | +| DBLP | 0.808 | **0.818** | +1.0 | node2vec 0.803 | +| Cora-Full | **0.589** | 0.587 | -0.1 | Walklets 0.573 | +| Coauthor CS | 0.876 | **0.884** | +0.7 | node2vec 0.869 | +| Amazon Photo | 0.916 | **0.924** | +0.8 | RandNE 0.913 | +| Amazon Computers | 0.891 | **0.899** | +0.9 | FastRP 0.890 | +| Coauthor Physics | 0.928 | **0.939** | +1.1 | NetMF 0.932 | +| Flickr | 0.543 | **0.553** | +1.0 | ProNE 0.535 | +| ogbn-arxiv | 0.681 | **0.700** | +1.9 | node2vec 0.685 | +| Reddit | 0.941 | **0.946** | +0.5 | RandNE 0.940 | +| ogbn-products | **0.645** | 0.604 | -4.1 | RandNE 0.562 | +| PPI | 0.134 | **0.134** | +0.0 | RandNE 0.129 | +| Wikipedia POS | 0.381 | **0.433** | +5.2 | RandNE 0.409 | +| BlogCatalog | 0.260 | 0.324 | +6.4 | FastRP 0.332 | +| Yelp | 0.282 | 0.282 | +0.0 | ProNE 0.284 | +| *mean gain (points)* | | | +1.0 | | + + + +| Dataset | Cleora | Cleora, tuned | gain | Best baseline | +|---|---:|---:|---:|---| +| CiteSeer | **0.458** | **0.458** | +0.0 | NetMF 0.421 | +| Cora | **0.408** | **0.408** | +0.0 | NetMF 0.364 | +| PPI | 0.204 | **0.206** | +0.2 | RandNE 0.183 | +| PubMed | 0.450 | **0.459** | +0.9 | Walklets 0.420 | +| DBLP | 0.540 | **0.541** | +0.2 | RandNE 0.492 | +| Cora-Full | 0.658 | **0.660** | +0.3 | RandNE 0.614 | +| Facebook (ego) | 0.595 | **0.612** | +1.7 | ProNE 0.601 | +| Coauthor CS | 0.637 | **0.662** | +2.5 | RandNE 0.648 | +| Amazon Photo | 0.519 | **0.524** | +0.6 | HOPE 0.456 | +| Wikipedia POS | **0.270** | **0.270** | +0.0 | HOPE 0.242 | +| Amazon Computers | 0.489 | **0.494** | +0.5 | HOPE 0.421 | +| Coauthor Physics | 0.737 | **0.769** | +3.2 | RandNE 0.752 | +| BlogCatalog | **0.222** | **0.222** | +0.0 | HOPE 0.209 | +| Flickr | 0.297 | **0.306** | +1.0 | DeepWalk 0.244 | +| MovieLens-1M | 0.148 | 0.148 | +0.0 | HOPE 0.149 | +| ogbl-ddi | 0.027 | 0.069 | +4.2 | HOPE 0.083 | +| ogbn-arxiv | **0.680** | **0.680** | +0.0 | RandNE 0.606 | +| ogbl-collab | 0.095 | **0.134** | +3.9 | DeepWalk 0.095 | +| roadNet-CA | 0.752 | 0.752 | +0.0 | ProNE 0.778 | +| Yelp | 0.495 | **0.525** | +2.9 | RandNE 0.513 | +| Reddit | 0.605 | **0.747** | +14.3 | ProNE 0.626 | +| MovieLens-20M | 0.237 | **0.256** | +1.9 | ProNE 0.227 | +| ogbl-ppa | **0.065** | **0.065** | +0.0 | FastRP 0.034 | +| ogbl-citation2 | 0.813 | **0.850** | +3.7 | RandNE 0.829 | +| LiveJournal | 0.765 | **0.809** | +4.4 | RandNE 0.776 | +| ogbn-products | 0.912 | **0.916** | +0.4 | RandNE 0.906 | +| *mean gain (points)* | | | +1.8 | | + + +## The popularity prior + +Cleora's vectors have unit length, so their dot product is the cosine: a measure of +how alike two nodes are. Whether two nodes are linked depends on more than that - a +node with many links is in more of the missing ones too - and the baselines whose +vectors are not normalised carry that information in the length of their vectors. +`scale_by_popularity(graph, vectors, exponent)` gives it to Cleora's: every vector is +multiplied by `degree ** exponent`, and the dot product becomes +`cosine(i, j) · (degree_i · degree_j) ** exponent`. + +In the link tables the Cleora columns are these scaled vectors. The rule that holds +for every method - dot product or cosine, whichever validates better on the graph - +then decides between the prior (dot product) and no prior (cosine). + +The exponent, 1/16, is the default of the library and was chosen on validation edges +(`popularity_exponent.py`: the similarity configuration of the benchmark, seed 0, the +graphs of tiers S and M). Mean validation scores by exponent - MRR against the +sampled candidates and recall@10 among all nodes - with the prior applied on every +graph, and under the rule above: + + +| Exponent | Graphs | MRR | recall@10 | MRR, prior or cosine | recall@10, prior or cosine | Graphs that take the prior | +|---:|---:|---:|---:|---:|---:|---:| +| 0 | 21 | 0.4016 | 0.2932 | 0.4016 | 0.2932 | 0 | +| 0.03125 | 21 | 0.4099 | 0.3080 | 0.4123 | 0.3094 | 16 | +| 0.0625 | 21 | **0.4101** | **0.3092** | **0.4149** | **0.3148** | 14 | +| 0.09375 | 21 | 0.4076 | 0.3086 | 0.4145 | 0.3145 | 12 | +| 0.125 | 21 | 0.4051 | 0.3048 | 0.4147 | 0.3139 | 11 | +| 0.1875 | 21 | 0.3977 | 0.2976 | 0.4133 | 0.3113 | 8 | +| 0.25 | 21 | 0.3899 | 0.2885 | 0.4130 | 0.3100 | 7 | +| 0.375 | 21 | 0.3723 | 0.2654 | 0.4109 | 0.3061 | 6 | +| 0.5 | 21 | 0.3543 | 0.2405 | 0.4092 | 0.2991 | 4 | + + +The prior is small on purpose. It settles the order of nodes that are about equally +similar; at larger exponents popularity starts to replace similarity and the scores +fall. It does not help everywhere: on eight of the 26 graphs (Reddit, ogbl-ddi, +MovieLens-1M, PPI, Facebook, Coauthor Physics, roadNet-CA, Yelp) the cosine validates +better and is what the tables use. + +A classifier can use the same information: with scaled vectors it sees how well +connected a node is, which matters most where a node has several labels. For +classification the Cleora columns are scaled with the exponent 1/4, chosen the same +way - the classification configuration of the benchmark, logistic regression, mean +validation score over the labelled graphs of tiers S and M. The probe still chooses +the feature scaling on validation, and unit-norm rows are one of its options: + + +| Exponent | Graphs | Validation score | Graphs above the unit vectors | Graphs below | +|---:|---:|---:|---:|---:| +| 0 | 16 | 0.6474 | 0 | 0 | +| 0.03125 | 16 | 0.6492 | 10 | 3 | +| 0.0625 | 16 | 0.6505 | 11 | 4 | +| 0.09375 | 16 | 0.6511 | 11 | 5 | +| 0.125 | 16 | 0.6519 | 10 | 4 | +| 0.1875 | 16 | 0.6529 | 9 | 6 | +| 0.25 | 16 | **0.6536** | 10 | 6 | +| 0.375 | 16 | 0.6527 | 10 | 6 | +| 0.5 | 16 | 0.6520 | 10 | 5 | + + +## Number of iterations + +Cleora has one hyper-parameter that matters: the number of iterations. Each iteration +moves every vector one step along a random walk. Too few and only the direct +neighbourhood is visible; too many and all vectors converge to the same direction. +The sweep (`run_benchmark.py --results sweep`) shows where the optimum is: between 1 +and 64, later for classification than for link ranking, earlier on dense graphs, and +about twice as late in the one-column setup. + +`SparseMatrix.suggest_iterations(propagation, purpose)` predicts it from two numbers +that are known as soon as the graph is built - `d`, the mean number of neighbours, and +`s`, the share of the weight on the diagonal of the matrix (0 for two columns, 1/2 for +one reflexive column): + +```text +mixing = c(purpose) / ((1 - s) · √d) × 1.5 for the symmetric normalisation +forget = ln(1/256) / ln(s) 0 when s = 0 +iterations = max(mixing, forget, 2) at most 64 +``` + +`c` is 12 for `purpose="similarity"`, 24 for `"classification"` and 16 for `"general"` +(what `num_iterations="auto"` uses when the purpose is not known). + +- *mixing*: denser graphs mix faster. A walk that stays where it is with probability + `s` needs `1 / (1 - s)` times the iterations for the same number of moves. +- *forget*: with a self-loop, every iteration keeps a share `s` of what the vector was, + and what it was at the start is random. `forget` is the number of iterations after + which that share has decayed to 1/256: 8 for the one-column setup, however dense + the graph. (On Reddit, with 490 neighbours per node, the mixing term alone suggests + one iteration; accuracy after 1, 2, 4 and 8 iterations is 0.15, 0.28, 0.87 and 0.94.) + +How the form was chosen: candidate rules were fitted leave-one-graph-out on the +validation curves of the sweep, and judged by the test score they give up against the +iteration count that validated best. + + +| Rule | Task | Graphs | Curves | Mean loss | Median loss | Worst loss | +|---|---|---:|---:|---:|---:|---:| +| one constant per setup and normalisation | classification | 16 | 64 | 1.36 | 0.46 | 9.18 | +| one constant per setup and normalisation | link ranking | 20 | 80 | 1.80 | 0.26 | 30.68 | +| mixing term only: c / ((1 - s) sqrt(d)) | classification | 16 | 64 | 2.12 | 0.20 | 31.08 | +| mixing term only: c / ((1 - s) sqrt(d)) | link ranking | 20 | 80 | 2.75 | 0.48 | 58.62 | +| mixing term and floors (the form that ships) | classification | 16 | 64 | 0.88 | 0.16 | 8.28 | +| mixing term and floors (the form that ships) | link ranking | 20 | 80 | 1.11 | 0.18 | 19.34 | + +- *one constant per setup and normalisation*, fitted on all graphs: link ranking, hyperedge/left: 8; link ranking, hyperedge/sym: 8; link ranking, pair/left: 2; link ranking, pair/sym: 3; classification, hyperedge/left: 16; classification, hyperedge/sym: 32; classification, pair/left: 8; classification, pair/sym: 12 +- *mixing term only: c / ((1 - s) sqrt(d))*, fitted on all graphs: c = 12 (link ranking), c = 40 (classification), symmetric x1.5 +- *mixing term and floors (the form that ships)*, fitted on all graphs: c = 10 (link ranking), c = 40 (classification), symmetric x1.5, remainder 1/256, minimum 1 + + +The optimum of `c` is flat, and it is not the same for the two tasks (loss in points, +all graphs of the sweep). The library uses 24 for classification and 12 for +similarity; 16, the general-purpose value, is the price of not knowing the task. A fit +on all graphs would take 40 and 10, which is within about a tenth of a point of 24 and +12, and a minimum of one iteration instead of two: Reddit fed as two columns ranks +links best after a single iteration (MRR 0.745, against 0.551 after two), while +classification on the same graph needs the second one (accuracy 0.82 after one, 0.94 +after two). The library keeps the minimum of two. + + +| c | classification: mean | median | worst | link ranking: mean | median | worst | +|---:|---:|---:|---:|---:|---:|---:| +| 6 | 7.21 | 5.77 | 31.07 | 1.37 | 0.35 | 18.76 | +| 8 | 5.17 | 4.00 | 20.66 | 0.66 | 0.15 | 5.41 | +| 10 | 3.66 | 2.79 | 20.66 | 0.61 | 0.13 | 4.86 | +| 12 | 2.93 | 1.92 | 20.66 | 0.70 | 0.12 | 4.86 | +| 14 | 2.20 | 1.39 | 20.66 | 0.96 | 0.41 | 8.19 | +| 16 | 1.87 | 0.99 | 20.66 | 1.40 | 0.60 | 8.19 | +| 20 | 1.41 | 0.65 | 20.66 | 2.32 | 1.54 | 11.03 | +| 24 | 0.96 | 0.41 | 12.07 | 3.39 | 2.60 | 14.16 | +| 28 | 0.98 | 0.35 | 12.07 | 4.34 | 3.59 | 16.98 | +| 32 | 0.94 | 0.26 | 12.07 | 5.23 | 4.70 | 19.59 | +| 40 | 0.84 | 0.16 | 8.28 | 7.20 | 6.33 | 23.28 | +| 48 | 1.03 | 0.17 | 9.05 | 8.67 | 8.20 | 27.56 | + + +What the rule that ships costs on the benchmark itself, for each of the four families +(three seeds, the number of iterations the library suggested against the one the +sweep chose): + + +| Dataset | one column, left (auto) | one column, left (tuned) | one column, left (loss) | one column, symmetric (auto) | one column, symmetric (tuned) | one column, symmetric (loss) | two columns, left (auto) | two columns, left (tuned) | two columns, left (loss) | two columns, symmetric (auto) | two columns, symmetric (tuned) | two columns, symmetric (loss) | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | 29 | 64 | +1.3 | 43 | 64 | +0.2 | 14 | 48 | +1.5 | 22 | 64 | +1.7 | +| Cora | 24 | 48 | -0.1 | 36 | 48 | +0.0 | 12 | 12 | +0.0 | 18 | 32 | -0.4 | +| PPI | 11 | 12 | +0.2 | 16 | 12 | -0.1 | 5 | 4 | +0.0 | 8 | 6 | +0.3 | +| PubMed | 23 | 32 | +0.1 | 34 | 64 | +0.9 | 11 | 16 | +0.2 | 17 | 32 | +0.6 | +| DBLP | 20 | 32 | +0.7 | 29 | 64 | +1.8 | 10 | 16 | +0.8 | 15 | 48 | +1.3 | +| Cora-Full | 19 | 16 | -0.1 | 28 | 24 | -0.2 | 9 | 8 | -0.0 | 14 | 12 | -0.2 | +| Coauthor CS | 16 | 24 | +0.2 | 24 | 32 | +0.3 | 8 | 12 | +0.2 | 12 | 16 | +0.2 | +| Amazon Photo | 9 | 8 | -0.1 | 13 | 16 | +0.3 | 4 | 6 | +0.1 | 6 | 8 | +0.2 | +| Wikipedia POS | 8 | 48 | -25.0 | 12 | 32 | +2.1 | 4 | 3 | +1.8 | 6 | 3 | +2.6 | +| Amazon Computers | 8 | 12 | +0.1 | 12 | 24 | +0.5 | 4 | 4 | +0.0 | 6 | 8 | +0.1 | +| Coauthor Physics | 13 | 32 | +0.9 | 19 | 64 | +0.4 | 6 | 16 | +0.8 | 9 | 24 | +0.5 | +| BlogCatalog | 8 | 12 | +3.4 | 9 | 24 | +2.7 | 3 | 4 | +1.8 | 4 | 4 | +0.0 | +| Flickr | 15 | 32 | +0.3 | 23 | 16 | -0.8 | 8 | 16 | +0.1 | 11 | 8 | -0.3 | +| ogbn-arxiv | 13 | 24 | +0.6 | 19 | 48 | +2.6 | 6 | 12 | +0.9 | 10 | 24 | +1.3 | +| Yelp | 11 | 8 | -1.0 | 17 | 16 | -0.2 | 6 | 2 | -0.6 | 8 | 4 | -2.6 | +| Reddit | 8 | 12 | +0.4 | 8 | 24 | +3.3 | 2 | 3 | +0.5 | 2 | 8 | +2.6 | +| ogbn-products | 8 | – | – | 10 | – | – | 3 | – | – | 5 | – | – | +| *mean loss* | | | -1.1 | | | +0.9 | | | +0.5 | | | +0.5 | + + + +| Dataset | one column, left (auto) | one column, left (tuned) | one column, left (loss) | one column, symmetric (auto) | one column, symmetric (tuned) | one column, symmetric (loss) | two columns, left (auto) | two columns, left (tuned) | two columns, left (loss) | two columns, symmetric (auto) | two columns, symmetric (tuned) | two columns, symmetric (loss) | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | 16 | 8 | +0.5 | 23/24 | 8 | +0.5 | 8 | 6 | -0.1 | 12 | 16 | -0.1 | +| Cora | 14 | 12 | +0.3 | 20 | 16 | +0.1 | 7 | 24 | -1.4 | 10 | 32 | -1.0 | +| PPI | 8 | 8 | +0.0 | 9 | 6 | +0.3 | 3 | 3 | +0.0 | 5 | 3 | +0.6 | +| PubMed | 12 | 12 | +0.0 | 18 | 16 | -0.0 | 6 | 8 | -0.1 | 9 | 16 | -0.2 | +| DBLP | 11 | 8 | +0.3 | 16 | 12 | +0.5 | 5 | 6 | -0.5 | 8 | 6 | +0.1 | +| Cora-Full | 11 | 8 | +0.5 | 16 | 12 | +0.6 | 5 | 4 | -0.2 | 8 | 6 | +0.2 | +| Facebook (ego) | 8 | 6 | +0.7 | 8 | 6 | +1.3 | 2 | 2 | +0.0 | 3 | 2 | +4.7 | +| Coauthor CS | 9 | 6 | +0.9 | 14 | 8 | +2.3 | 5 | 3 | +2.8 | 7 | 4 | +3.0 | +| Amazon Photo | 8 | 6 | +0.2 | 8 | 6 | +1.2 | 2 | 2 | +0.0 | 4 | 2 | +1.7 | +| Wikipedia POS | 8 | 12 | +0.7 | 8 | 8 | +0.0 | 2 | 2 | +0.0 | 3 | 3 | +0.0 | +| Amazon Computers | 8 | 6 | +0.1 | 8 | 6 | +1.0 | 2 | 2 | +0.0 | 3 | 2 | +0.5 | +| Coauthor Physics | 8 | 6 | +1.1 | 11 | 6 | +2.9 | 4 | 2 | +4.0 | 5 | 3 | +3.5 | +| BlogCatalog | 8 | 12 | -0.1 | 8 | 8 | +0.0 | 2 | 2 | +0.0 | 3 | 3 | +0.0 | +| Flickr | 9 | 16 | +0.9 | 13 | 16 | +1.4 | 4 | 8 | +1.1 | 7 | 8 | +0.3 | +| MovieLens-1M | 8 | 12 | +1.2 | 8 | 8 | +0.0 | 2 | 64 | +4.2 | 2 | 64 | +1.8 | +| ogbl-ddi | 8 | 12 | -0.0 | 8 | 8 | +0.0 | 2 | 2 | +0.0 | 2 | 2 | +0.0 | +| ogbn-arxiv | 8 | 8 | +0.0 | 11 | 12 | -0.3 | 4 | 3 | +0.1 | 5 | 4 | +0.1 | +| ogbl-collab | 9 | 16 | -0.1 | 13 | 2 | +0.3 | 4 | 8 | -0.0 | 7 | 2 | +0.1 | +| roadNet-CA | 15 | – | – | 23 | – | – | 8 | – | – | 11 | – | – | +| Yelp | 8 | 8 | +0.0 | 9 | 12 | +0.0 | 3 | 2 | +0.1 | 4 | 4 | +0.0 | +| Reddit | 8 | 8 | +0.0 | 8 | 8 | +0.0 | 2 | 1 | +19.3 | 2 | 1 | +8.5 | +| MovieLens-20M | 8 | – | – | 8 | – | – | 2 | – | – | 2 | – | – | +| ogbl-ppa | 8 | – | – | 8 | – | – | 2 | – | – | 2 | – | – | +| ogbl-citation2 | 8 | – | – | 8 | – | – | 3 | – | – | 4 | – | – | +| LiveJournal | 8 | – | – | 9 | – | – | 3 | – | – | 4 | – | – | +| ogbn-products | 8 | – | – | 8 | – | – | 2 | – | – | 3 | – | – | +| *mean loss* | | | +0.4 | | | +0.6 | | | +1.5 | | | +1.2 | + + +The rule was derived on the graphs of the sweep, so for them the *Cleora* columns are +not a blind test of the rule: the leave-one-graph-out table above is the estimate of what it +costs on a new graph. ogbl-ppa and the five largest graphs (ogbn-products, +ogbl-citation2, LiveJournal, roadNet-CA, MovieLens-20M) were never swept; the rule was +fixed before they were run. + +Limits of the rule, visible in these tables: it knows the graph but not the labels. +Where the labels follow a much finer or much coarser structure than usual (Yelp's 100 +business categories; CiteSeer's six broad fields) the best number of iterations is +far from the suggestion, and a validation set is worth using: `embed(..., +callback=...)` hands out the vectors after every iteration, so one run covers all +candidates. + +## Time and memory + +Quality runs share a machine with other jobs, so their timings are not used. Time and +peak memory come from a separate pass (`--tasks time --results timing`): one method at +a time on an otherwise idle machine (Intel Core Ultra 9 275HX, 24 threads, 183 GB of +memory), whole graph, 1024 dimensions, three runs, median reported - a single run for +DeepWalk and node2vec on ogbn-arxiv and for the baselines on Yelp, where one run takes +up to 100 minutes. The clock runs from edge arrays in memory to the embedding matrix +in memory; memory is the peak resident set of the worker process, interpreter and +libraries included. + +## Figures + +`make_figures.py` draws a 2-D UMAP (umap-learn 0.6.0, cosine metric, 15 neighbours, +fixed seed) of the same random sample of up to 15,000 nodes for every method. +Points are coloured by node class - the eight largest classes, the others grey - or, +on graphs without labels, by degree. The pictures illustrate; whether one method +separates classes better than another is what the tables measure. + +`make_summary_figure.py` draws the three bar charts at the top of the main README - +graphs won in similarity search, time on ogbn-arxiv, memory on Yelp - from the same +rows as the tables, once for a light and once for a dark page. + +## Replication + +```bash +benchmarks/replicate.sh [--tiers S|SM|SML] [--datasets a,b,c] [--dim 1024] [--threads N] + [--no-setup] [--no-baselines] [--no-previous] [--no-tuned] + [--no-popularity] [--no-timing] [--no-figures] [--no-report] +``` + +runs, in this order and skipping whatever is already there: + +| Step | Script | Writes | +|---|---|---| +| environments and baseline checkouts | `setup.sh` | `envs/`, `baselines/` | +| datasets | `prepare_datasets.py` | `datasets/` | +| Cleora, baselines, pycleora 3.2 default | `run_benchmark.py` | `results/` | +| iteration sweep and selection | `run_benchmark.py --results sweep`, `select_iterations.py` | `sweep/`, `selected_iterations.json` | +| Cleora, tuned | `run_benchmark.py --methods cleora_tuned` | `results/` | +| exponents of the popularity prior (tiers S and M) | `popularity_exponent.py` | `popularity/` | +| time and memory | `run_benchmark.py --tasks time --results timing` | `timing/` | +| figures | `make_figures.py`, `make_summary_figure.py` | `benchmarks/figures/` | +| tables | `make_report.py` | `benchmarks/RESULTS.md`, `benchmarks/results.csv.gz` (every aggregated number), the READMEs | + +Needs [uv](https://docs.astral.sh/uv/), git and a Rust toolchain. The probes use a CUDA +GPU when there is one (Apple MPS or the CPU otherwise). + +Three Python environments are needed because the reference implementations pin +incompatible versions of NumPy: + +| Environment | Python | Runs | Pinned in | +|---|---|---|---| +| `main` | 3.12 | pycleora, probes, report, figures, ProNE, NetMF, FastRP, RandNE | [`envs/main.txt`](envs/main.txt) (every transitive version: [`envs/main.lock-linux-x86_64-cuda13.txt`](envs/main.lock-linux-x86_64-cuda13.txt)) | +| `walks` | 3.11 | DeepWalk, node2vec | [`envs/walks.txt`](envs/walks.txt) | +| `karate` | 3.10 | GraRep, HOPE, Walklets | [`envs/karate.txt`](envs/karate.txt) | + +Everything is seeded: the initial vectors of Cleora depend only on node names and the +seed, the splits and the sampled negatives only on the dataset and the seed. Cleora's +output is bit-identical between runs and thread counts. Skip-gram training with several +threads is not deterministic, so DeepWalk, node2vec and Walklets vary slightly from run +to run; the standard deviations show by how much. The scores themselves are computed +on the accelerator, whose rounding differs between machines: where many nodes have +nearly equal vectors (small sparse graphs) the order of near-ties changes, and the +retrieval metrics with it, by up to 0.004. + +## What the benchmark does not show + +- **Tuned baselines.** The baselines run with their authors' settings. DeepWalk's + window, node2vec's p and q or ProNE's filter could be tuned per dataset as Cleora's + iterations are in the *tuned* tables; at a few times to a few thousand times + Cleora's cost per run this was not done, which is why the tuned numbers are kept out + of the main tables. +- **A trained ranking model.** The ranking stage of a production recommender feeds + both vectors, together with many other features, to a model trained on interaction + logs; a benchmark on bare graphs cannot reproduce that. An earlier version of this + suite had a stand-in for it - an untuned MLP over the two concatenated vectors - on + which ProNE ranked ahead of Cleora. It was removed together with three probes that + are rarely applied to embeddings in practice: k-NN classification (node2vec and + ProNE ranked ahead of Cleora), a full bilinear form (six of the nine baselines did) + and linear SVMs (Cleora ranked first). Their tables are in the history of + `RESULTS.md`. +- **Other dimensionalities.** Everything is at 1024 dimensions. Most baselines were + published at 128, and some of them are better there than at 1024. +- **Methods that use node features or labels** (GCN, GraphSAGE, ...). All methods here + see the graph only; on feature-rich graphs such as Flickr or Yelp, feature-based + models are far ahead of every structural embedding. +- **Heterogeneous and hypergraph data**, which is what Cleora's column modifiers are + for. The public datasets with labels are homogeneous graphs; MovieLens (bipartite) + is the only exception here. diff --git a/benchmarks/RESULTS.md b/benchmarks/RESULTS.md new file mode 100644 index 0000000..b7db138 --- /dev/null +++ b/benchmarks/RESULTS.md @@ -0,0 +1,1104 @@ +# Benchmark results + +Generated by `benchmarks/make_report.py`; do not edit. The protocol is described in [`benchmarks/README.md`](README.md). + +**Bold**: best of the row. Underlined: second best. `n/a (size)`: the implementation builds dense n × n matrices or Python-level graph objects and was not run on a graph of this size. `time limit` / `out of memory`: the run was started and did not finish. + +## In short + +One headline measurement for each use of the vectors; the full tables follow. + +| | Graphs | Cleora: best on | mean rank | Cleora, two columns: best on | mean rank | Best baseline (mean rank) | +|---|---:|---:|---:|---:|---:|---| +| Similarity search among all nodes (dot product / cosine, recall@10) | 26 | **23** | 1.12 | 15 | 2.23 | RandNE (3.46) | +| Node classification (logistic regression, accuracy / micro-F1) | 17 | **11** | 1.88 | 7 | 2.00 | node2vec (3.35) | +| Link ranking against sampled candidates (dot product / cosine, MRR) | 26 | **15** | 1.50 | 13 | 2.35 | RandNE (3.27) | + +With the number of iterations and the normalisation chosen on validation data - the baselines stay at their authors' settings, so this is not part of the comparison above - Cleora is ahead of every baseline on 15 of 17 graphs in node classification and on 23 of 26 graphs in link ranking against sampled candidates. + +## Where Cleora is not the best method + +- **Similarity search among all nodes: a baseline is ahead of Cleora on** PubMed (Walklets 0.192, Cleora 0.185); MovieLens-1M (HOPE 0.107, Cleora 0.101); Reddit (ProNE 0.345, Cleora 0.311). +- **Similarity search among all nodes: the pycleora 3.2 default (whitening, 40 iterations) is ahead of Cleora on** roadNet-CA (0.3464 against 0.3458); Reddit (0.359 against 0.311). +- **Node classification: a baseline is ahead of Cleora on** CiteSeer (NetMF 0.572, Cleora 0.567); Coauthor Physics (NetMF 0.932, Cleora 0.928); ogbn-arxiv (node2vec 0.685, Cleora 0.681); Wikipedia POS (RandNE 0.409, Cleora 0.381); BlogCatalog (FastRP 0.332, Cleora 0.260); Yelp (ProNE 0.284, Cleora 0.282). +- **Node classification: the pycleora 3.2 default (whitening, 40 iterations) is ahead of Cleora on** Flickr (0.548 against 0.543); ogbn-arxiv (0.695 against 0.681); ogbn-products (0.741 against 0.645). +- **Link ranking against sampled candidates: a baseline is ahead of Cleora on** Facebook (ego) (ProNE 0.601, Cleora 0.595); Coauthor CS (RandNE 0.648, Cleora 0.637); Coauthor Physics (RandNE 0.752, Cleora 0.737); MovieLens-1M (HOPE 0.149, Cleora 0.148); ogbl-ddi (HOPE 0.083, Cleora 0.027); ogbl-collab (DeepWalk 0.0955, Cleora 0.0946); roadNet-CA (ProNE 0.778, Cleora 0.752); Yelp (RandNE 0.513, Cleora 0.495); Reddit (ProNE 0.626, Cleora 0.605); ogbl-citation2 (RandNE 0.829, Cleora 0.813); LiveJournal (RandNE 0.776, Cleora 0.765). +- **Link ranking against sampled candidates: the pycleora 3.2 default (whitening, 40 iterations) is ahead of Cleora on** Coauthor Physics (0.752 against 0.737); roadNet-CA (0.816 against 0.752); Yelp (0.501 against 0.495); ogbl-citation2 (0.827 against 0.813); LiveJournal (0.809 against 0.765). + +## Datasets + +| Dataset | Nodes | Edges | Mean degree | Node labels | Seeds | Source | +|---|---:|---:|---:|---|---:|---| +| CiteSeer | 3,279 | 4,552 | 2.8 | 6 classes | 3 | Yang, Cohen, Salakhutdinov, ICML 2016; Sen et al., AI Magazine 2008 | +| Cora | 2,708 | 5,278 | 3.9 | 7 classes | 3 | Yang, Cohen, Salakhutdinov, ICML 2016; Sen et al., AI Magazine 2008 | +| PPI | 3,860 | 37,845 | 19.6 | 50 labels (multi-label) | 3 | Grover and Leskovec, node2vec, KDD 2016 | +| PubMed | 19,717 | 44,324 | 4.5 | 3 classes | 3 | Yang, Cohen, Salakhutdinov, ICML 2016; Sen et al., AI Magazine 2008 | +| DBLP | 17,716 | 52,867 | 6.0 | 4 classes | 3 | Bojchevski and Günnemann, ICLR 2018 | +| Cora-Full | 19,793 | 63,421 | 6.4 | 70 classes | 3 | Bojchevski and Günnemann, ICLR 2018 | +| Facebook (ego) | 4,039 | 88,234 | 43.7 | – | 3 | McAuley and Leskovec, NeurIPS 2012 | +| Coauthor CS | 18,333 | 81,894 | 8.9 | 15 classes | 3 | Shchur et al., Pitfalls of GNN Evaluation, 2018 | +| Amazon Photo | 7,535 | 119,081 | 31.6 | 8 classes | 3 | Shchur et al., Pitfalls of GNN Evaluation, 2018; McAuley et al., SIGIR 2015 | +| Wikipedia POS | 4,777 | 92,295 | 38.6 | 40 labels (multi-label) | 3 | Grover and Leskovec, node2vec, KDD 2016; weighted | +| Amazon Computers | 13,471 | 245,861 | 36.5 | 10 classes | 3 | Shchur et al., Pitfalls of GNN Evaluation, 2018; McAuley et al., SIGIR 2015 | +| Coauthor Physics | 34,493 | 247,962 | 14.4 | 5 classes | 3 | Shchur et al., Pitfalls of GNN Evaluation, 2018 | +| BlogCatalog | 10,312 | 333,983 | 64.8 | 39 labels (multi-label) | 3 | Tang and Liu, KDD 2009; Perozzi et al., DeepWalk, KDD 2014 | +| Flickr | 89,250 | 449,878 | 10.1 | 7 classes | 3 | Zeng et al., GraphSAINT, ICLR 2020; official node split | +| MovieLens-1M | 9,746 | 1,000,209 | 205.3 | – | 3 | Harper and Konstan, The MovieLens Datasets, ACM TiiS 2015; bipartite | +| ogbl-ddi | 4,267 | 1,067,911 | 500.5 | – | 3 | Hu et al., Open Graph Benchmark, NeurIPS 2020; official link split | +| ogbn-arxiv | 169,343 | 1,157,799 | 13.7 | 40 classes | 3 | Hu et al., Open Graph Benchmark, NeurIPS 2020; official node split | +| ogbl-collab | 235,868 | 967,632 | 8.2 | – | 3 | Hu et al., Open Graph Benchmark, NeurIPS 2020; official link split | +| roadNet-CA | 1,965,206 | 2,766,607 | 2.8 | – | 1 | Leskovec et al., Internet Mathematics 2009 | +| Yelp | 716,847 | 6,618,986 | 18.5 | 100 labels (multi-label) | 1 | Zeng et al., GraphSAINT, ICLR 2020; official node split | +| Reddit | 232,965 | 57,307,946 | 492.0 | 41 classes | 1 | Hamilton, Ying, Leskovec, GraphSAGE, NeurIPS 2017; official node split | +| MovieLens-20M | 165,237 | 20,000,263 | 242.1 | – | 1 | Harper and Konstan, The MovieLens Datasets, ACM TiiS 2015; bipartite | +| ogbl-ppa | 576,289 | 21,231,931 | 73.7 | – | 1 | Hu et al., Open Graph Benchmark, NeurIPS 2020; official link split | +| ogbl-citation2 | 2,926,620 | 30,351,880 | 20.7 | – | 1 | Hu et al., Open Graph Benchmark, NeurIPS 2020; official link split | +| LiveJournal | 3,997,962 | 34,681,189 | 17.3 | – | 1 | Yang and Leskovec, ICDM 2012 | +| ogbn-products | 2,400,608 | 61,859,012 | 51.5 | 47 classes | 1 | Hu et al., Open Graph Benchmark, NeurIPS 2020; official node split | + +## Summary: mean rank of every method + +Mean rank over the graphs (1 = best; a method without a result on a graph ranks after all that have one), and in parentheses the number of graphs the method is best on. The two Cleora columns are the same method fed in two ways and do not compete with each other: every baseline is ranked against Cleora with one column, and each Cleora column against the baselines only. `ranks_retrieval`: similarity search among all nodes, by metric. `ranks_nc`: node classification by accuracy (single-label graphs) or micro-F1 (multi-label), by probe. `ranks_lp`: link ranking against sampled candidates by MRR, by probe. + +### `ranks_retrieval` + +| Metric | Graphs | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| recall@10 | 26 | **1.12** (23) | 2.23 (15) | 6.23 (0) | 6.27 (0) | 6.04 (1) | 5.69 (0) | 7.88 (0) | 5.00 (1) | 4.23 (1) | 4.46 (0) | 3.46 (0) | +| recall@50 | 26 | **1.23** (21) | 2.35 (13) | 5.92 (0) | 6.31 (0) | 6.15 (0) | 5.54 (0) | 7.85 (0) | 5.46 (1) | 4.38 (2) | 4.27 (0) | 3.27 (2) | +| nDCG@10 | 26 | **1.08** (24) | 2.00 (16) | 6.46 (0) | 6.50 (0) | 6.15 (1) | 6.00 (0) | 7.81 (0) | 4.62 (0) | 4.19 (1) | 4.35 (0) | 3.23 (0) | +| MAP@10 | 26 | **1.04** (25) | 2.00 (18) | 6.42 (0) | 6.58 (0) | 6.23 (1) | 6.00 (0) | 7.77 (0) | 4.58 (0) | 4.23 (0) | 4.35 (0) | 3.19 (0) | +| MRR | 26 | **1.08** (25) | 2.00 (17) | 6.50 (0) | 6.73 (0) | 6.31 (0) | 6.00 (0) | 7.46 (0) | 4.31 (0) | 4.46 (1) | 4.35 (0) | 3.19 (0) | + +### `ranks_nc` + +| Probe | Graphs | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| logistic regression | 17 | **1.88** (11) | 2.00 (7) | 4.18 (0) | 3.35 (1) | 5.53 (0) | 4.88 (2) | 7.00 (0) | 7.53 (0) | 6.47 (1) | 6.18 (1) | 5.35 (1) | +| MLP (AdamC) | 17 | **1.88** (12) | 2.71 (7) | 3.41 (0) | 3.00 (1) | 4.94 (0) | 6.71 (0) | 6.82 (0) | 7.29 (0) | 6.88 (0) | 5.94 (2) | 5.47 (2) | + +### `ranks_lp` + +| Probe | Graphs | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| dot product or cosine | 26 | **1.50** (15) | 2.35 (13) | 6.15 (1) | 6.35 (0) | 6.12 (0) | 5.88 (0) | 7.31 (0) | 4.81 (2) | 4.58 (3) | 4.42 (0) | 3.27 (5) | +| dot product | 26 | **1.54** (15) | 2.35 (13) | 6.08 (1) | 6.58 (0) | 5.96 (0) | 6.35 (0) | 7.31 (0) | 4.65 (2) | 4.23 (3) | 4.58 (0) | 3.12 (5) | +| cosine | 26 | **1.38** (17) | 2.69 (11) | 6.46 (0) | 6.42 (0) | 6.65 (0) | 5.31 (0) | 7.54 (0) | 6.42 (0) | 3.62 (4) | 4.04 (0) | 2.54 (5) | +| logistic regression on x*y | 26 | **1.77** (11) | 3.12 (5) | 6.08 (0) | 6.12 (0) | 6.15 (0) | 6.19 (0) | 7.46 (0) | 5.58 (0) | 2.50 (11) | 4.73 (0) | 3.81 (4) | + +## Similarity search among all nodes + +What a nearest-neighbour index over the vectors returns: the held-out neighbours of a query node are ranked among all nodes of the graph by dot product or cosine - whichever validates better for the method - with the known neighbours filtered out. `recall@k`, `ndcg@k`, `map@k`: of the top-k list of every query node. `all_nodes_mrr`: of every held-out edge. + +### `retrieval_recall@10` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | **0.471 ± 0.025** | 0.405 ± 0.017 | 0.401 ± 0.032 | 0.403 ± 0.018 | 0.409 ± 0.017 | 0.425 ± 0.028 | 0.264 ± 0.019 | 0.419 ± 0.024 | 0.406 ± 0.025 | 0.397 ± 0.030 | 0.383 ± 0.029 | +| Cora | **0.434 ± 0.010** | 0.397 ± 0.012 | 0.370 ± 0.004 | 0.374 ± 0.004 | 0.371 ± 0.010 | 0.384 ± 0.004 | 0.186 ± 0.001 | 0.386 ± 0.006 | 0.370 ± 0.007 | 0.380 ± 0.010 | 0.370 ± 0.003 | +| PPI | **0.167 ± 0.005** | 0.114 ± 0.004 | 0.056 ± 0.001 | 0.056 ± 0.001 | 0.093 ± 0.001 | 0.087 ± 0.004 | 0.035 ± 0.005 | 0.123 ± 0.003 | 0.088 ± 0.002 | 0.107 ± 0.001 | 0.131 ± 0.003 | +| PubMed | 0.185 ± 0.005 | 0.108 ± 0.001 | 0.092 ± 0.003 | 0.086 ± 0.006 | **0.192 ± 0.006** | 0.103 ± 0.002 | 0.055 ± 0.004 | 0.158 ± 0.003 | 0.099 ± 0.003 | 0.092 ± 0.001 | 0.093 ± 0.001 | +| DBLP | **0.307 ± 0.006** | 0.280 ± 0.005 | 0.138 ± 0.004 | 0.139 ± 0.005 | 0.089 ± 0.036 | 0.195 ± 0.005 | 0.078 ± 0.004 | 0.222 ± 0.002 | 0.196 ± 0.006 | 0.219 ± 0.004 | 0.227 ± 0.004 | +| Cora-Full | **0.447 ± 0.003** | 0.422 ± 0.001 | 0.263 ± 0.001 | 0.265 ± 0.002 | 0.340 ± 0.001 | 0.330 ± 0.001 | 0.122 ± 0.001 | 0.305 ± 0.005 | 0.333 ± 0.001 | 0.364 ± 0.004 | 0.365 ± 0.002 | +| Facebook (ego) | **0.491 ± 0.009** | 0.483 ± 0.009 | 0.330 ± 0.004 | 0.324 ± 0.003 | 0.298 ± 0.016 | 0.397 ± 0.002 | 0.182 ± 0.006 | 0.392 ± 0.004 | 0.477 ± 0.007 | 0.418 ± 0.006 | 0.449 ± 0.004 | +| Coauthor CS | **0.458 ± 0.002** | 0.442 ± 0.004 | 0.318 ± 0.001 | 0.325 ± 0.001 | 0.275 ± 0.058 | 0.390 ± 0.002 | 0.138 ± 0.001 | 0.305 ± 0.005 | 0.392 ± 0.005 | 0.431 ± 0.003 | 0.449 ± 0.003 | +| Amazon Photo | **0.416 ± 0.004** | 0.358 ± 0.006 | 0.197 ± 0.003 | 0.194 ± 0.003 | 0.235 ± 0.004 | 0.212 ± 0.005 | 0.081 ± 0.003 | 0.313 ± 0.005 | 0.281 ± 0.006 | 0.266 ± 0.007 | 0.277 ± 0.008 | +| Wikipedia POS | **0.315 ± 0.003** | 0.311 ± 0.005 | 0.027 ± 0.001 | 0.032 ± 0.004 | 0.041 ± 0.001 | 0.033 ± 0.001 | 0.009 ± 0.001 | 0.252 ± 0.011 | 0.035 ± 0.002 | 0.045 ± 0.002 | 0.030 ± 0.001 | +| Amazon Computers | **0.360 ± 0.004** | 0.295 ± 0.005 | 0.146 ± 0.002 | 0.146 ± 0.002 | 0.149 ± 0.003 | 0.199 ± 0.003 | 0.043 ± 0.001 | 0.230 ± 0.003 | 0.241 ± 0.000 | 0.233 ± 0.002 | 0.244 ± 0.002 | +| Coauthor Physics | **0.504 ± 0.000** | 0.485 ± 0.001 | 0.391 ± 0.004 | 0.389 ± 0.004 | 0.317 ± 0.010 | 0.403 ± 0.003 | 0.156 ± 0.005 | 0.288 ± 0.003 | 0.430 ± 0.005 | 0.468 ± 0.002 | 0.498 ± 0.004 | +| BlogCatalog | **0.165 ± 0.002** | 0.111 ± 0.003 | 0.024 ± 0.000 | 0.024 ± 0.002 | 0.038 ± 0.002 | 0.016 ± 0.002 | 0.040 ± 0.002 | 0.120 ± 0.003 | 0.018 ± 0.001 | 0.023 ± 0.001 | 0.020 ± 0.001 | +| Flickr | **0.110 ± 0.003** | 0.017 ± 0.001 | 0.035 ± 0.001 | 0.034 ± 0.000 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.027 ± 0.000 | 0.012 ± 0.001 | 0.013 ± 0.000 | +| MovieLens-1M | 0.101 ± 0.003 | 0.001 ± 0.000 | 0.028 ± 0.001 | 0.027 ± 0.001 | 0.025 ± 0.000 | 0.067 ± 0.001 | 0.066 ± 0.001 | **0.107 ± 0.010** | 0.090 ± 0.001 | 0.004 ± 0.001 | 0.082 ± 0.005 | +| ogbl-ddi | **0.092 ± 0.001** | 0.057 ± 0.001 | 0.042 ± 0.000 | 0.040 ± 0.001 | 0.047 ± 0.000 | 0.054 ± 0.000 | 0.028 ± 0.000 | 0.042 ± 0.000 | 0.058 ± 0.000 | 0.059 ± 0.001 | 0.060 ± 0.000 | +| ogbn-arxiv | **0.317 ± 0.002** | 0.294 ± 0.004 | 0.142 ± 0.004 | 0.135 ± 0.003 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.161 ± 0.005 | 0.199 ± 0.004 | 0.212 ± 0.003 | +| ogbl-collab | **0.404 ± 0.001** | 0.389 ± 0.002 | 0.369 ± 0.002 | 0.368 ± 0.001 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.292 ± 0.001 | 0.354 ± 0.001 | 0.370 ± 0.001 | +| roadNet-CA | **0.346** | 0.255 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.310 | 0.104 | 0.239 | +| Yelp | **0.103** | 0.097 | 0.035 | 0.028 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.060 | 0.047 | 0.090 | +| Reddit | 0.311 | **0.403** | 0.110 | 0.092 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.345 | 0.231 | 0.274 | +| MovieLens-20M | **0.094** | 0.001 | 0.019 | 0.021 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.051 | 0.002 | 0.081 | +| ogbl-ppa | **0.391** | 0.291 | 0.215 | 0.196 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.251 | 0.262 | 0.270 | +| ogbl-citation2 | **0.261** | 0.239 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.179 | 0.201 | +| LiveJournal | **0.327** | 0.304 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.222 | 0.276 | +| ogbn-products | **0.337** | 0.316 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.216 | 0.247 | +| *mean rank* | **1.12** | 2.23 | 6.23 | 6.27 | 6.04 | 5.69 | 7.88 | 5.00 | 4.23 | 4.46 | 3.46 | +| *best on* | 23 / 26 | 15 / 26 | 0 / 22 | 0 / 22 | 1 / 15 | 0 / 15 | 0 / 15 | 1 / 15 | 1 / 23 | 0 / 26 | 0 / 26 | + +### `retrieval_recall@50` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | **0.652 ± 0.023** | 0.594 ± 0.018 | 0.622 ± 0.018 | 0.612 ± 0.026 | 0.588 ± 0.028 | 0.627 ± 0.021 | 0.462 ± 0.009 | 0.565 ± 0.038 | 0.543 ± 0.031 | 0.604 ± 0.034 | 0.584 ± 0.020 | +| Cora | **0.639 ± 0.016** | 0.605 ± 0.014 | 0.571 ± 0.012 | 0.577 ± 0.015 | 0.542 ± 0.013 | 0.588 ± 0.007 | 0.340 ± 0.020 | 0.529 ± 0.004 | 0.496 ± 0.005 | 0.587 ± 0.017 | 0.554 ± 0.003 | +| PPI | **0.330 ± 0.005** | 0.278 ± 0.001 | 0.132 ± 0.005 | 0.131 ± 0.006 | 0.221 ± 0.006 | 0.201 ± 0.004 | 0.119 ± 0.003 | 0.264 ± 0.002 | 0.190 ± 0.005 | 0.242 ± 0.003 | 0.285 ± 0.003 | +| PubMed | **0.414 ± 0.008** | 0.268 ± 0.007 | 0.258 ± 0.004 | 0.246 ± 0.006 | 0.396 ± 0.001 | 0.313 ± 0.008 | 0.149 ± 0.007 | 0.336 ± 0.005 | 0.292 ± 0.006 | 0.268 ± 0.008 | 0.281 ± 0.002 | +| DBLP | **0.533 ± 0.008** | 0.504 ± 0.009 | 0.351 ± 0.003 | 0.351 ± 0.005 | 0.410 ± 0.017 | 0.440 ± 0.004 | 0.199 ± 0.003 | 0.431 ± 0.005 | 0.427 ± 0.005 | 0.467 ± 0.005 | 0.470 ± 0.006 | +| Cora-Full | **0.674 ± 0.002** | 0.651 ± 0.001 | 0.521 ± 0.003 | 0.522 ± 0.003 | 0.586 ± 0.004 | 0.604 ± 0.001 | 0.276 ± 0.007 | 0.535 ± 0.006 | 0.597 ± 0.002 | 0.627 ± 0.003 | 0.624 ± 0.002 | +| Facebook (ego) | 0.795 ± 0.002 | 0.791 ± 0.002 | 0.689 ± 0.005 | 0.692 ± 0.005 | 0.624 ± 0.012 | 0.741 ± 0.002 | 0.373 ± 0.009 | 0.715 ± 0.001 | **0.812 ± 0.002** | 0.748 ± 0.004 | 0.770 ± 0.002 | +| Coauthor CS | 0.663 ± 0.002 | 0.641 ± 0.003 | 0.556 ± 0.002 | 0.560 ± 0.003 | 0.570 ± 0.011 | 0.631 ± 0.003 | 0.263 ± 0.002 | 0.531 ± 0.001 | 0.648 ± 0.002 | 0.662 ± 0.004 | **0.681 ± 0.004** | +| Amazon Photo | **0.696 ± 0.003** | 0.647 ± 0.003 | 0.457 ± 0.006 | 0.457 ± 0.005 | 0.504 ± 0.003 | 0.526 ± 0.003 | 0.207 ± 0.005 | 0.595 ± 0.003 | 0.571 ± 0.007 | 0.563 ± 0.006 | 0.567 ± 0.006 | +| Wikipedia POS | 0.468 ± 0.003 | **0.475 ± 0.004** | 0.071 ± 0.003 | 0.076 ± 0.005 | 0.107 ± 0.003 | 0.083 ± 0.002 | 0.053 ± 0.002 | 0.388 ± 0.009 | 0.080 ± 0.001 | 0.114 ± 0.003 | 0.086 ± 0.004 | +| Amazon Computers | **0.615 ± 0.001** | 0.561 ± 0.000 | 0.337 ± 0.001 | 0.336 ± 0.001 | 0.364 ± 0.004 | 0.454 ± 0.002 | 0.104 ± 0.001 | 0.470 ± 0.003 | 0.498 ± 0.003 | 0.482 ± 0.002 | 0.499 ± 0.002 | +| Coauthor Physics | 0.728 ± 0.002 | 0.709 ± 0.001 | 0.637 ± 0.002 | 0.637 ± 0.002 | 0.580 ± 0.001 | 0.625 ± 0.001 | 0.270 ± 0.004 | 0.516 ± 0.002 | 0.692 ± 0.001 | 0.710 ± 0.004 | **0.738 ± 0.003** | +| BlogCatalog | **0.349 ± 0.002** | 0.255 ± 0.001 | 0.066 ± 0.001 | 0.065 ± 0.002 | 0.095 ± 0.002 | 0.047 ± 0.001 | 0.161 ± 0.003 | 0.276 ± 0.005 | 0.047 ± 0.001 | 0.063 ± 0.002 | 0.055 ± 0.002 | +| Flickr | **0.209 ± 0.002** | 0.071 ± 0.001 | 0.092 ± 0.000 | 0.092 ± 0.000 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.071 ± 0.001 | 0.046 ± 0.001 | 0.043 ± 0.001 | +| MovieLens-1M | 0.264 ± 0.002 | 0.005 ± 0.003 | 0.108 ± 0.001 | 0.104 ± 0.002 | 0.082 ± 0.003 | 0.176 ± 0.003 | 0.179 ± 0.001 | **0.275 ± 0.019** | 0.272 ± 0.001 | 0.019 ± 0.001 | 0.218 ± 0.011 | +| ogbl-ddi | **0.282 ± 0.000** | 0.233 ± 0.000 | 0.153 ± 0.001 | 0.145 ± 0.002 | 0.163 ± 0.000 | 0.196 ± 0.001 | 0.106 ± 0.001 | 0.194 ± 0.001 | 0.244 ± 0.001 | 0.209 ± 0.000 | 0.229 ± 0.001 | +| ogbn-arxiv | **0.522 ± 0.003** | 0.491 ± 0.002 | 0.305 ± 0.001 | 0.293 ± 0.002 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.328 ± 0.003 | 0.380 ± 0.003 | 0.392 ± 0.004 | +| ogbl-collab | **0.485 ± 0.001** | 0.478 ± 0.001 | 0.462 ± 0.002 | 0.461 ± 0.001 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.409 ± 0.000 | 0.459 ± 0.001 | 0.473 ± 0.001 | +| roadNet-CA | **0.687** | 0.527 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.686 | 0.113 | 0.315 | +| Yelp | **0.208** | 0.190 | 0.074 | 0.063 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.127 | 0.093 | 0.191 | +| Reddit | 0.385 | **0.473** | 0.141 | 0.121 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.424 | 0.287 | 0.331 | +| MovieLens-20M | **0.224** | 0.004 | 0.060 | 0.061 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.137 | 0.002 | 0.197 | +| ogbl-ppa | **0.562** | 0.455 | 0.395 | 0.384 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.427 | 0.423 | 0.435 | +| ogbl-citation2 | **0.469** | 0.435 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.352 | 0.394 | +| LiveJournal | **0.487** | 0.464 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.362 | 0.455 | +| ogbn-products | **0.528** | 0.502 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.400 | 0.434 | +| *mean rank* | **1.23** | 2.35 | 5.92 | 6.31 | 6.15 | 5.54 | 7.85 | 5.46 | 4.38 | 4.27 | 3.27 | +| *best on* | 21 / 26 | 13 / 26 | 0 / 22 | 0 / 22 | 0 / 15 | 0 / 15 | 0 / 15 | 1 / 15 | 2 / 23 | 0 / 26 | 2 / 26 | + +### `retrieval_ndcg@10` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | **0.309 ± 0.022** | 0.267 ± 0.015 | 0.242 ± 0.021 | 0.245 ± 0.020 | 0.249 ± 0.016 | 0.264 ± 0.024 | 0.176 ± 0.017 | 0.270 ± 0.014 | 0.258 ± 0.023 | 0.252 ± 0.024 | 0.246 ± 0.022 | +| Cora | **0.292 ± 0.012** | 0.269 ± 0.013 | 0.232 ± 0.005 | 0.232 ± 0.007 | 0.232 ± 0.003 | 0.249 ± 0.009 | 0.127 ± 0.007 | 0.261 ± 0.016 | 0.241 ± 0.007 | 0.251 ± 0.014 | 0.243 ± 0.010 | +| PPI | **0.123 ± 0.003** | 0.084 ± 0.002 | 0.035 ± 0.001 | 0.036 ± 0.001 | 0.071 ± 0.001 | 0.065 ± 0.002 | 0.027 ± 0.004 | 0.093 ± 0.003 | 0.066 ± 0.001 | 0.079 ± 0.001 | 0.099 ± 0.000 | +| PubMed | 0.113 ± 0.002 | 0.067 ± 0.001 | 0.051 ± 0.001 | 0.048 ± 0.003 | **0.118 ± 0.003** | 0.057 ± 0.001 | 0.032 ± 0.003 | 0.098 ± 0.002 | 0.055 ± 0.001 | 0.053 ± 0.001 | 0.054 ± 0.001 | +| DBLP | **0.201 ± 0.003** | 0.183 ± 0.002 | 0.078 ± 0.004 | 0.080 ± 0.004 | 0.035 ± 0.015 | 0.113 ± 0.003 | 0.049 ± 0.003 | 0.147 ± 0.001 | 0.115 ± 0.003 | 0.130 ± 0.003 | 0.135 ± 0.003 | +| Cora-Full | **0.303 ± 0.003** | 0.287 ± 0.001 | 0.160 ± 0.001 | 0.163 ± 0.000 | 0.221 ± 0.000 | 0.203 ± 0.001 | 0.079 ± 0.001 | 0.204 ± 0.003 | 0.208 ± 0.002 | 0.231 ± 0.002 | 0.233 ± 0.001 | +| Facebook (ego) | **0.455 ± 0.008** | 0.449 ± 0.007 | 0.279 ± 0.005 | 0.276 ± 0.002 | 0.271 ± 0.025 | 0.349 ± 0.005 | 0.170 ± 0.004 | 0.383 ± 0.006 | 0.433 ± 0.005 | 0.368 ± 0.005 | 0.409 ± 0.005 | +| Coauthor CS | **0.338 ± 0.001** | 0.327 ± 0.002 | 0.208 ± 0.001 | 0.213 ± 0.001 | 0.173 ± 0.056 | 0.264 ± 0.001 | 0.098 ± 0.001 | 0.222 ± 0.003 | 0.267 ± 0.003 | 0.295 ± 0.002 | 0.313 ± 0.002 | +| Amazon Photo | **0.347 ± 0.005** | 0.300 ± 0.005 | 0.146 ± 0.002 | 0.143 ± 0.002 | 0.185 ± 0.003 | 0.166 ± 0.004 | 0.067 ± 0.002 | 0.260 ± 0.004 | 0.217 ± 0.005 | 0.206 ± 0.005 | 0.220 ± 0.005 | +| Wikipedia POS | **0.267 ± 0.003** | 0.258 ± 0.003 | 0.022 ± 0.001 | 0.025 ± 0.003 | 0.033 ± 0.002 | 0.025 ± 0.001 | 0.009 ± 0.000 | 0.214 ± 0.011 | 0.029 ± 0.001 | 0.043 ± 0.002 | 0.030 ± 0.001 | +| Amazon Computers | **0.299 ± 0.002** | 0.244 ± 0.002 | 0.110 ± 0.001 | 0.112 ± 0.002 | 0.120 ± 0.004 | 0.157 ± 0.001 | 0.036 ± 0.001 | 0.195 ± 0.002 | 0.186 ± 0.001 | 0.181 ± 0.001 | 0.194 ± 0.002 | +| Coauthor Physics | **0.385 ± 0.002** | 0.368 ± 0.001 | 0.287 ± 0.005 | 0.283 ± 0.004 | 0.219 ± 0.022 | 0.301 ± 0.002 | 0.122 ± 0.005 | 0.212 ± 0.002 | 0.322 ± 0.002 | 0.350 ± 0.002 | 0.378 ± 0.003 | +| BlogCatalog | **0.155 ± 0.003** | 0.119 ± 0.002 | 0.027 ± 0.001 | 0.027 ± 0.001 | 0.039 ± 0.002 | 0.019 ± 0.001 | 0.049 ± 0.003 | 0.123 ± 0.002 | 0.023 ± 0.000 | 0.033 ± 0.000 | 0.029 ± 0.001 | +| Flickr | **0.077 ± 0.002** | 0.010 ± 0.000 | 0.019 ± 0.000 | 0.018 ± 0.000 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.016 ± 0.000 | 0.008 ± 0.001 | 0.010 ± 0.000 | +| MovieLens-1M | **0.132 ± 0.002** | 0.001 ± 0.001 | 0.033 ± 0.000 | 0.033 ± 0.000 | 0.028 ± 0.001 | 0.067 ± 0.001 | 0.087 ± 0.001 | 0.128 ± 0.012 | 0.103 ± 0.001 | 0.003 ± 0.001 | 0.089 ± 0.008 | +| ogbl-ddi | **0.786 ± 0.001** | 0.750 ± 0.002 | 0.571 ± 0.011 | 0.515 ± 0.014 | 0.707 ± 0.002 | 0.691 ± 0.002 | 0.479 ± 0.001 | 0.638 ± 0.001 | 0.741 ± 0.001 | 0.730 ± 0.001 | 0.755 ± 0.001 | +| ogbn-arxiv | **0.209 ± 0.003** | 0.194 ± 0.004 | 0.086 ± 0.004 | 0.081 ± 0.004 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.099 ± 0.004 | 0.125 ± 0.004 | 0.134 ± 0.003 | +| ogbl-collab | **0.431 ± 0.001** | 0.412 ± 0.002 | 0.380 ± 0.001 | 0.374 ± 0.001 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.279 ± 0.001 | 0.337 ± 0.001 | 0.353 ± 0.001 | +| roadNet-CA | **0.169** | 0.129 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.157 | 0.068 | 0.125 | +| Yelp | **0.059** | **0.059** | 0.021 | 0.017 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.036 | 0.028 | 0.053 | +| Reddit | 0.291 | **0.382** | 0.100 | 0.082 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.292 | 0.188 | 0.231 | +| MovieLens-20M | **0.057** | 0.001 | 0.010 | 0.010 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.029 | 0.001 | 0.049 | +| ogbl-ppa | **0.458** | 0.361 | 0.248 | 0.223 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.299 | 0.326 | 0.335 | +| ogbl-citation2 | **0.156** | 0.141 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.101 | 0.114 | +| LiveJournal | **0.223** | 0.208 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.138 | 0.172 | +| ogbn-products | **0.238** | 0.224 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.133 | 0.159 | +| *mean rank* | **1.08** | 2.00 | 6.46 | 6.50 | 6.15 | 6.00 | 7.81 | 4.62 | 4.19 | 4.35 | 3.23 | +| *best on* | 24 / 26 | 16 / 26 | 0 / 22 | 0 / 22 | 1 / 15 | 0 / 15 | 0 / 15 | 0 / 15 | 1 / 23 | 0 / 26 | 0 / 26 | + +### `retrieval_map@10` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | **0.249 ± 0.021** | 0.215 ± 0.016 | 0.185 ± 0.018 | 0.188 ± 0.020 | 0.192 ± 0.016 | 0.206 ± 0.022 | 0.143 ± 0.015 | 0.215 ± 0.012 | 0.203 ± 0.023 | 0.199 ± 0.022 | 0.195 ± 0.020 | +| Cora | **0.237 ± 0.012** | 0.220 ± 0.012 | 0.181 ± 0.006 | 0.180 ± 0.008 | 0.181 ± 0.005 | 0.199 ± 0.009 | 0.104 ± 0.008 | 0.213 ± 0.018 | 0.192 ± 0.011 | 0.202 ± 0.015 | 0.195 ± 0.012 | +| PPI | **0.076 ± 0.004** | 0.051 ± 0.001 | 0.020 ± 0.001 | 0.021 ± 0.002 | 0.043 ± 0.001 | 0.040 ± 0.001 | 0.013 ± 0.003 | 0.058 ± 0.003 | 0.041 ± 0.002 | 0.047 ± 0.001 | 0.061 ± 0.001 | +| PubMed | 0.078 ± 0.001 | 0.046 ± 0.002 | 0.034 ± 0.001 | 0.032 ± 0.002 | **0.086 ± 0.002** | 0.036 ± 0.001 | 0.021 ± 0.002 | 0.070 ± 0.002 | 0.035 ± 0.000 | 0.035 ± 0.002 | 0.035 ± 0.001 | +| DBLP | **0.146 ± 0.003** | 0.132 ± 0.001 | 0.052 ± 0.003 | 0.054 ± 0.003 | 0.015 ± 0.007 | 0.075 ± 0.003 | 0.033 ± 0.003 | 0.105 ± 0.001 | 0.078 ± 0.002 | 0.087 ± 0.003 | 0.090 ± 0.003 | +| Cora-Full | **0.235 ± 0.002** | 0.222 ± 0.001 | 0.115 ± 0.001 | 0.118 ± 0.000 | 0.163 ± 0.001 | 0.146 ± 0.001 | 0.057 ± 0.000 | 0.153 ± 0.002 | 0.151 ± 0.003 | 0.170 ± 0.002 | 0.172 ± 0.002 | +| Facebook (ego) | **0.343 ± 0.008** | 0.340 ± 0.006 | 0.185 ± 0.004 | 0.184 ± 0.002 | 0.182 ± 0.023 | 0.244 ± 0.004 | 0.108 ± 0.003 | 0.283 ± 0.004 | 0.321 ± 0.005 | 0.263 ± 0.005 | 0.299 ± 0.005 | +| Coauthor CS | **0.270 ± 0.001** | 0.262 ± 0.002 | 0.154 ± 0.001 | 0.158 ± 0.001 | 0.122 ± 0.050 | 0.199 ± 0.001 | 0.074 ± 0.001 | 0.171 ± 0.003 | 0.202 ± 0.002 | 0.225 ± 0.002 | 0.241 ± 0.001 | +| Amazon Photo | **0.249 ± 0.005** | 0.213 ± 0.005 | 0.090 ± 0.001 | 0.088 ± 0.002 | 0.119 ± 0.003 | 0.103 ± 0.003 | 0.039 ± 0.001 | 0.178 ± 0.003 | 0.144 ± 0.004 | 0.135 ± 0.004 | 0.148 ± 0.004 | +| Wikipedia POS | **0.183 ± 0.002** | 0.174 ± 0.002 | 0.013 ± 0.001 | 0.014 ± 0.002 | 0.019 ± 0.001 | 0.014 ± 0.001 | 0.005 ± 0.000 | 0.141 ± 0.009 | 0.018 ± 0.001 | 0.025 ± 0.001 | 0.018 ± 0.001 | +| Amazon Computers | **0.204 ± 0.002** | 0.162 ± 0.001 | 0.067 ± 0.000 | 0.068 ± 0.001 | 0.071 ± 0.003 | 0.095 ± 0.001 | 0.020 ± 0.001 | 0.122 ± 0.003 | 0.118 ± 0.001 | 0.116 ± 0.000 | 0.126 ± 0.002 | +| Coauthor Physics | **0.299 ± 0.002** | 0.284 ± 0.001 | 0.216 ± 0.004 | 0.212 ± 0.004 | 0.151 ± 0.023 | 0.229 ± 0.002 | 0.091 ± 0.005 | 0.154 ± 0.002 | 0.244 ± 0.002 | 0.268 ± 0.001 | 0.292 ± 0.002 | +| BlogCatalog | **0.088 ± 0.002** | 0.065 ± 0.001 | 0.013 ± 0.000 | 0.013 ± 0.001 | 0.020 ± 0.002 | 0.009 ± 0.001 | 0.022 ± 0.002 | 0.067 ± 0.002 | 0.011 ± 0.000 | 0.017 ± 0.000 | 0.015 ± 0.000 | +| Flickr | **0.062 ± 0.002** | 0.006 ± 0.000 | 0.011 ± 0.000 | 0.010 ± 0.001 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.010 ± 0.000 | 0.005 ± 0.000 | 0.006 ± 0.000 | +| MovieLens-1M | **0.069 ± 0.002** | 0.000 ± 0.000 | 0.014 ± 0.000 | 0.013 ± 0.000 | 0.012 ± 0.000 | 0.032 ± 0.001 | 0.043 ± 0.001 | 0.066 ± 0.008 | 0.049 ± 0.001 | 0.001 ± 0.000 | 0.045 ± 0.005 | +| ogbl-ddi | **0.740 ± 0.001** | 0.724 ± 0.002 | 0.499 ± 0.014 | 0.433 ± 0.014 | 0.678 ± 0.003 | 0.641 ± 0.002 | 0.453 ± 0.002 | 0.602 ± 0.002 | 0.713 ± 0.001 | 0.691 ± 0.002 | 0.723 ± 0.001 | +| ogbn-arxiv | **0.158 ± 0.003** | 0.146 ± 0.004 | 0.061 ± 0.003 | 0.057 ± 0.004 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.070 ± 0.003 | 0.090 ± 0.003 | 0.097 ± 0.002 | +| ogbl-collab | **0.361 ± 0.000** | 0.341 ± 0.001 | 0.306 ± 0.001 | 0.299 ± 0.001 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.212 ± 0.001 | 0.262 ± 0.001 | 0.277 ± 0.001 | +| roadNet-CA | **0.115** | 0.090 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.110 | 0.056 | 0.091 | +| Yelp | 0.042 | **0.044** | 0.016 | 0.013 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.026 | 0.021 | 0.038 | +| Reddit | 0.272 | **0.359** | 0.091 | 0.075 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.260 | 0.166 | 0.207 | +| MovieLens-20M | **0.038** | 0.000 | 0.006 | 0.007 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.020 | 0.001 | 0.034 | +| ogbl-ppa | **0.353** | 0.278 | 0.168 | 0.146 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.209 | 0.242 | 0.252 | +| ogbl-citation2 | **0.124** | 0.111 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.077 | 0.088 | +| LiveJournal | **0.189** | 0.176 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.111 | 0.139 | +| ogbn-products | **0.205** | 0.193 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.107 | 0.130 | +| *mean rank* | **1.04** | 2.00 | 6.42 | 6.58 | 6.23 | 6.00 | 7.77 | 4.58 | 4.23 | 4.35 | 3.19 | +| *best on* | 25 / 26 | 18 / 26 | 0 / 22 | 0 / 22 | 1 / 15 | 0 / 15 | 0 / 15 | 0 / 15 | 0 / 23 | 0 / 26 | 0 / 26 | + +### `retrieval_all_nodes_mrr` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | **0.243 ± 0.017** | 0.213 ± 0.014 | 0.185 ± 0.016 | 0.188 ± 0.017 | 0.189 ± 0.014 | 0.203 ± 0.019 | 0.142 ± 0.012 | 0.207 ± 0.011 | 0.197 ± 0.018 | 0.199 ± 0.020 | 0.195 ± 0.019 | +| Cora | **0.229 ± 0.012** | 0.213 ± 0.012 | 0.178 ± 0.008 | 0.177 ± 0.009 | 0.175 ± 0.005 | 0.192 ± 0.009 | 0.106 ± 0.007 | 0.204 ± 0.016 | 0.184 ± 0.011 | 0.197 ± 0.013 | 0.191 ± 0.011 | +| PPI | **0.079 ± 0.002** | 0.056 ± 0.002 | 0.020 ± 0.000 | 0.021 ± 0.001 | 0.048 ± 0.000 | 0.044 ± 0.002 | 0.024 ± 0.002 | 0.064 ± 0.002 | 0.045 ± 0.001 | 0.055 ± 0.003 | 0.068 ± 0.002 | +| PubMed | **0.090 ± 0.001** | 0.057 ± 0.000 | 0.039 ± 0.001 | 0.037 ± 0.002 | 0.084 ± 0.002 | 0.049 ± 0.001 | 0.027 ± 0.002 | 0.074 ± 0.001 | 0.044 ± 0.001 | 0.046 ± 0.001 | 0.048 ± 0.001 | +| DBLP | **0.152 ± 0.001** | 0.140 ± 0.001 | 0.057 ± 0.003 | 0.058 ± 0.002 | 0.033 ± 0.005 | 0.085 ± 0.001 | 0.042 ± 0.002 | 0.118 ± 0.001 | 0.085 ± 0.001 | 0.100 ± 0.002 | 0.106 ± 0.002 | +| Cora-Full | **0.224 ± 0.002** | 0.213 ± 0.001 | 0.114 ± 0.001 | 0.117 ± 0.001 | 0.164 ± 0.001 | 0.147 ± 0.001 | 0.063 ± 0.001 | 0.160 ± 0.001 | 0.150 ± 0.001 | 0.169 ± 0.003 | 0.173 ± 0.001 | +| Facebook (ego) | **0.315 ± 0.003** | 0.312 ± 0.003 | 0.173 ± 0.003 | 0.171 ± 0.000 | 0.180 ± 0.030 | 0.234 ± 0.002 | 0.098 ± 0.002 | 0.302 ± 0.004 | 0.301 ± 0.002 | 0.225 ± 0.003 | 0.267 ± 0.004 | +| Coauthor CS | **0.256 ± 0.001** | 0.247 ± 0.002 | 0.146 ± 0.001 | 0.150 ± 0.001 | 0.130 ± 0.045 | 0.193 ± 0.001 | 0.075 ± 0.001 | 0.186 ± 0.001 | 0.198 ± 0.001 | 0.216 ± 0.001 | 0.233 ± 0.002 | +| Amazon Photo | **0.213 ± 0.004** | 0.189 ± 0.004 | 0.083 ± 0.001 | 0.082 ± 0.002 | 0.116 ± 0.002 | 0.110 ± 0.002 | 0.045 ± 0.002 | 0.169 ± 0.002 | 0.135 ± 0.004 | 0.125 ± 0.002 | 0.142 ± 0.003 | +| Wikipedia POS | **0.139 ± 0.003** | 0.136 ± 0.002 | 0.012 ± 0.000 | 0.013 ± 0.001 | 0.019 ± 0.001 | 0.012 ± 0.000 | 0.018 ± 0.001 | 0.120 ± 0.005 | 0.018 ± 0.001 | 0.039 ± 0.002 | 0.032 ± 0.002 | +| Amazon Computers | **0.157 ± 0.001** | 0.133 ± 0.001 | 0.055 ± 0.001 | 0.056 ± 0.001 | 0.069 ± 0.002 | 0.086 ± 0.001 | 0.020 ± 0.000 | 0.113 ± 0.001 | 0.096 ± 0.002 | 0.094 ± 0.001 | 0.104 ± 0.001 | +| Coauthor Physics | **0.266 ± 0.002** | 0.251 ± 0.001 | 0.191 ± 0.003 | 0.187 ± 0.003 | 0.155 ± 0.023 | 0.200 ± 0.001 | 0.083 ± 0.003 | 0.149 ± 0.002 | 0.223 ± 0.002 | 0.239 ± 0.001 | 0.262 ± 0.002 | +| BlogCatalog | **0.056 ± 0.001** | 0.050 ± 0.000 | 0.011 ± 0.000 | 0.012 ± 0.000 | 0.016 ± 0.001 | 0.009 ± 0.000 | 0.026 ± 0.001 | 0.050 ± 0.000 | 0.011 ± 0.000 | 0.017 ± 0.000 | 0.016 ± 0.000 | +| Flickr | **0.049 ± 0.002** | 0.010 ± 0.001 | 0.017 ± 0.001 | 0.017 ± 0.001 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.015 ± 0.000 | 0.010 ± 0.001 | 0.016 ± 0.002 | +| MovieLens-1M | **0.049 ± 0.001** | 0.001 ± 0.000 | 0.013 ± 0.000 | 0.013 ± 0.000 | 0.010 ± 0.000 | 0.020 ± 0.000 | 0.031 ± 0.000 | 0.045 ± 0.005 | 0.037 ± 0.000 | 0.003 ± 0.000 | 0.030 ± 0.003 | +| ogbl-ddi | 0.277 ± 0.001 | 0.349 ± 0.000 | 0.068 ± 0.002 | 0.054 ± 0.001 | 0.168 ± 0.001 | 0.119 ± 0.002 | 0.116 ± 0.001 | 0.287 ± 0.001 | **0.442 ± 0.001** | 0.126 ± 0.000 | 0.160 ± 0.001 | +| ogbn-arxiv | **0.132 ± 0.002** | 0.123 ± 0.001 | 0.055 ± 0.001 | 0.051 ± 0.002 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.065 ± 0.001 | 0.080 ± 0.001 | 0.087 ± 0.000 | +| ogbl-collab | **0.281 ± 0.001** | 0.268 ± 0.001 | 0.230 ± 0.002 | 0.222 ± 0.001 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.169 ± 0.001 | 0.210 ± 0.001 | 0.228 ± 0.001 | +| roadNet-CA | **0.133** | 0.104 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.129 | 0.056 | 0.095 | +| Yelp | **0.043** | **0.043** | 0.015 | 0.013 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.027 | 0.021 | 0.039 | +| Reddit | 0.232 | **0.305** | 0.077 | 0.064 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.227 | 0.134 | 0.169 | +| MovieLens-20M | **0.030** | 0.001 | 0.005 | 0.005 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.016 | 0.000 | 0.024 | +| ogbl-ppa | **0.241** | 0.210 | 0.115 | 0.102 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.149 | 0.164 | 0.180 | +| ogbl-citation2 | **0.136** | 0.123 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.088 | 0.099 | +| LiveJournal | **0.194** | 0.181 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.117 | 0.145 | +| ogbn-products | **0.209** | 0.197 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.114 | 0.137 | +| *mean rank* | **1.08** | 2.00 | 6.50 | 6.73 | 6.31 | 6.00 | 7.46 | 4.31 | 4.46 | 4.35 | 3.19 | +| *best on* | 25 / 26 | 17 / 26 | 0 / 22 | 0 / 22 | 0 / 15 | 0 / 15 | 0 / 15 | 0 / 15 | 1 / 23 | 0 / 26 | 0 / 26 | + +## Node classification, single-label graphs: accuracy + +10% of the nodes for training and 10% for validation (or the official split), three random splits per embedding; mean ± standard deviation over splits and seeds. One table per probe. + +### `nc_accuracy_logistic` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | 0.567 ± 0.013 | 0.550 ± 0.011 | 0.543 ± 0.008 | 0.555 ± 0.007 | 0.538 ± 0.011 | **0.572 ± 0.007** | 0.546 ± 0.016 | 0.450 ± 0.015 | 0.437 ± 0.009 | 0.486 ± 0.007 | 0.474 ± 0.009 | +| Cora | **0.788 ± 0.008** | 0.786 ± 0.007 | 0.765 ± 0.007 | 0.761 ± 0.009 | 0.755 ± 0.009 | 0.766 ± 0.003 | 0.715 ± 0.010 | 0.601 ± 0.009 | 0.589 ± 0.011 | 0.701 ± 0.008 | 0.688 ± 0.014 | +| PubMed | **0.812 ± 0.004** | 0.805 ± 0.003 | 0.802 ± 0.002 | 0.803 ± 0.003 | 0.800 ± 0.005 | 0.806 ± 0.001 | 0.776 ± 0.006 | 0.775 ± 0.005 | 0.756 ± 0.003 | 0.715 ± 0.003 | 0.707 ± 0.004 | +| DBLP | **0.808 ± 0.003** | 0.802 ± 0.003 | 0.802 ± 0.003 | 0.803 ± 0.003 | 0.798 ± 0.004 | 0.797 ± 0.003 | 0.777 ± 0.006 | 0.750 ± 0.001 | 0.732 ± 0.004 | 0.685 ± 0.004 | 0.679 ± 0.003 | +| Cora-Full | **0.589 ± 0.002** | 0.582 ± 0.001 | 0.569 ± 0.002 | 0.569 ± 0.004 | 0.573 ± 0.004 | 0.572 ± 0.004 | 0.486 ± 0.004 | 0.530 ± 0.000 | 0.534 ± 0.001 | 0.518 ± 0.005 | 0.520 ± 0.002 | +| Coauthor CS | **0.876 ± 0.001** | **0.876 ± 0.002** | 0.868 ± 0.002 | 0.869 ± 0.002 | 0.866 ± 0.001 | 0.864 ± 0.002 | 0.805 ± 0.003 | 0.821 ± 0.004 | 0.793 ± 0.003 | 0.789 ± 0.002 | 0.783 ± 0.005 | +| Amazon Photo | **0.916 ± 0.004** | **0.916 ± 0.003** | 0.907 ± 0.002 | 0.910 ± 0.002 | 0.907 ± 0.002 | 0.912 ± 0.006 | 0.857 ± 0.004 | 0.899 ± 0.002 | 0.878 ± 0.005 | 0.909 ± 0.005 | 0.913 ± 0.005 | +| Amazon Computers | **0.891 ± 0.002** | 0.888 ± 0.002 | 0.876 ± 0.002 | 0.877 ± 0.003 | 0.872 ± 0.002 | 0.885 ± 0.004 | 0.801 ± 0.003 | 0.868 ± 0.001 | 0.860 ± 0.004 | 0.890 ± 0.002 | 0.888 ± 0.002 | +| Coauthor Physics | 0.928 ± 0.001 | 0.927 ± 0.002 | 0.931 ± 0.001 | 0.931 ± 0.002 | 0.926 ± 0.001 | **0.932 ± 0.001** | 0.905 ± 0.001 | 0.896 ± 0.002 | 0.906 ± 0.002 | 0.868 ± 0.000 | 0.859 ± 0.004 | +| Flickr | 0.543 ± 0.001 | **0.551 ± 0.002** | 0.533 ± 0.001 | 0.533 ± 0.001 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.535 ± 0.001 | 0.493 ± 0.000 | 0.515 ± 0.001 | +| ogbn-arxiv | 0.681 ± 0.001 | 0.671 ± 0.002 | **0.685 ± 0.001** | **0.685 ± 0.001** | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.663 ± 0.002 | 0.569 ± 0.000 | 0.592 ± 0.003 | +| Reddit | **0.941** | 0.939 | 0.937 | 0.940 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.937 | 0.936 | 0.940 | +| ogbn-products | **0.645** | 0.602 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.556 | 0.562 | +| *mean rank* | **1.46** | 2.08 | 4.00 | 3.15 | 5.31 | 3.92 | 7.00 | 7.23 | 6.85 | 6.69 | 6.38 | +| *best on* | 10 / 13 | 6 / 13 | 0 / 12 | 1 / 12 | 0 / 9 | 2 / 9 | 0 / 9 | 0 / 9 | 0 / 12 | 0 / 13 | 0 / 13 | + +### `nc_accuracy_mlp` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | **0.569 ± 0.011** | 0.552 ± 0.011 | 0.550 ± 0.008 | 0.558 ± 0.010 | 0.538 ± 0.012 | 0.540 ± 0.007 | 0.543 ± 0.015 | 0.434 ± 0.013 | 0.416 ± 0.008 | 0.494 ± 0.009 | 0.478 ± 0.007 | +| Cora | **0.775 ± 0.010** | 0.772 ± 0.006 | 0.767 ± 0.009 | 0.758 ± 0.012 | 0.755 ± 0.007 | 0.721 ± 0.008 | 0.720 ± 0.008 | 0.596 ± 0.005 | 0.564 ± 0.010 | 0.708 ± 0.004 | 0.703 ± 0.011 | +| PubMed | **0.808 ± 0.003** | 0.804 ± 0.006 | 0.807 ± 0.004 | 0.807 ± 0.004 | 0.806 ± 0.004 | 0.774 ± 0.005 | 0.781 ± 0.003 | 0.781 ± 0.007 | 0.758 ± 0.006 | 0.729 ± 0.005 | 0.724 ± 0.004 | +| DBLP | **0.804 ± 0.005** | 0.800 ± 0.004 | 0.800 ± 0.005 | 0.800 ± 0.006 | **0.804 ± 0.004** | 0.777 ± 0.004 | 0.780 ± 0.006 | 0.768 ± 0.003 | 0.746 ± 0.004 | 0.708 ± 0.003 | 0.699 ± 0.005 | +| Cora-Full | **0.570 ± 0.004** | 0.565 ± 0.004 | 0.561 ± 0.004 | 0.565 ± 0.004 | 0.564 ± 0.004 | 0.556 ± 0.005 | 0.492 ± 0.009 | 0.525 ± 0.003 | 0.530 ± 0.002 | 0.522 ± 0.001 | 0.516 ± 0.003 | +| Coauthor CS | **0.871 ± 0.003** | **0.871 ± 0.002** | 0.866 ± 0.005 | 0.865 ± 0.005 | 0.862 ± 0.006 | 0.834 ± 0.003 | 0.814 ± 0.002 | 0.825 ± 0.003 | 0.798 ± 0.002 | 0.804 ± 0.001 | 0.800 ± 0.005 | +| Amazon Photo | **0.915 ± 0.003** | **0.915 ± 0.002** | 0.907 ± 0.005 | 0.912 ± 0.003 | 0.906 ± 0.004 | 0.891 ± 0.003 | 0.863 ± 0.002 | 0.897 ± 0.003 | 0.867 ± 0.003 | 0.904 ± 0.002 | 0.911 ± 0.003 | +| Amazon Computers | 0.891 ± 0.002 | **0.893 ± 0.004** | 0.885 ± 0.003 | 0.888 ± 0.004 | 0.885 ± 0.004 | 0.867 ± 0.007 | 0.808 ± 0.004 | 0.867 ± 0.001 | 0.862 ± 0.006 | 0.891 ± 0.003 | 0.889 ± 0.002 | +| Coauthor Physics | 0.928 ± 0.002 | 0.927 ± 0.003 | **0.930 ± 0.002** | **0.930 ± 0.002** | 0.929 ± 0.002 | 0.914 ± 0.002 | 0.905 ± 0.002 | 0.901 ± 0.002 | 0.908 ± 0.002 | 0.881 ± 0.001 | 0.874 ± 0.003 | +| Flickr | 0.551 ± 0.001 | **0.558 ± 0.004** | 0.543 ± 0.002 | 0.544 ± 0.001 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.539 ± 0.001 | 0.509 ± 0.000 | 0.529 ± 0.001 | +| ogbn-arxiv | **0.700 ± 0.001** | 0.692 ± 0.001 | 0.698 ± 0.002 | 0.699 ± 0.003 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.675 ± 0.000 | 0.629 ± 0.000 | 0.637 ± 0.001 | +| Reddit | **0.944** | 0.940 | 0.940 | 0.942 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.940 | 0.939 | 0.942 | +| ogbn-products | **0.715** | 0.701 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.664 | 0.664 | +| *mean rank* | **1.31** | 2.15 | 3.31 | 2.62 | 4.77 | 6.08 | 6.85 | 7.00 | 7.08 | 6.54 | 6.46 | +| *best on* | 11 / 13 | 6 / 13 | 0 / 12 | 1 / 12 | 0 / 9 | 0 / 9 | 0 / 9 | 0 / 9 | 0 / 12 | 1 / 13 | 0 / 13 | + +## Node classification, single-label graphs: other metrics (logistic regression) + +### `nc_macro_f1_logistic` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | 0.502 | 0.481 | 0.473 | 0.491 | 0.480 | **0.520** | 0.490 | 0.414 | 0.402 | 0.440 | 0.419 | +| Cora | **0.777** | 0.775 | 0.753 | 0.750 | 0.739 | 0.758 | 0.694 | 0.590 | 0.585 | 0.696 | 0.682 | +| PubMed | **0.799** | 0.791 | 0.787 | 0.788 | 0.787 | 0.788 | 0.759 | 0.756 | 0.742 | 0.689 | 0.682 | +| DBLP | **0.754** | 0.744 | 0.740 | 0.743 | 0.747 | 0.738 | 0.711 | 0.685 | 0.667 | 0.602 | 0.595 | +| Cora-Full | **0.512** | 0.502 | 0.480 | 0.480 | 0.491 | 0.501 | 0.376 | 0.461 | 0.484 | 0.472 | 0.469 | +| Coauthor CS | **0.840** | 0.838 | 0.833 | 0.833 | 0.831 | 0.823 | 0.748 | 0.782 | 0.763 | 0.737 | 0.728 | +| Amazon Photo | 0.906 | **0.907** | 0.898 | 0.901 | 0.897 | 0.899 | 0.828 | 0.883 | 0.868 | 0.898 | 0.902 | +| Amazon Computers | 0.882 | 0.881 | 0.865 | 0.866 | 0.860 | 0.870 | 0.766 | 0.855 | 0.847 | **0.885** | 0.883 | +| Coauthor Physics | 0.903 | 0.902 | 0.907 | 0.908 | 0.902 | **0.909** | 0.872 | 0.862 | 0.877 | 0.831 | 0.817 | +| Flickr | 0.267 | **0.283** | 0.249 | 0.258 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.245 | 0.197 | 0.211 | +| ogbn-arxiv | **0.467** | 0.450 | 0.447 | 0.448 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.437 | 0.335 | 0.330 | +| Reddit | 0.918 | **0.919** | 0.910 | 0.916 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.916 | 0.910 | 0.914 | +| ogbn-products | **0.331** | 0.286 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.291 | 0.292 | +| *mean rank* | **1.46** | 1.85 | 4.23 | 3.08 | 5.23 | 4.00 | 7.15 | 7.38 | 6.62 | 6.31 | 6.54 | +| *best on* | 10 / 13 | 8 / 13 | 0 / 12 | 0 / 12 | 0 / 9 | 2 / 9 | 0 / 9 | 0 / 9 | 0 / 12 | 1 / 13 | 0 / 13 | + +### `nc_balanced_accuracy_logistic` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | 0.507 | 0.488 | 0.485 | 0.501 | 0.486 | **0.521** | 0.494 | 0.404 | 0.398 | 0.441 | 0.425 | +| Cora | **0.763** | 0.761 | 0.739 | 0.738 | 0.724 | 0.737 | 0.678 | 0.548 | 0.537 | 0.657 | 0.649 | +| PubMed | **0.797** | 0.789 | 0.785 | 0.787 | 0.784 | 0.781 | 0.755 | 0.750 | 0.738 | 0.683 | 0.677 | +| DBLP | **0.741** | 0.730 | 0.721 | 0.726 | 0.737 | 0.722 | 0.693 | 0.666 | 0.645 | 0.581 | 0.575 | +| Cora-Full | **0.493** | 0.483 | 0.463 | 0.464 | 0.475 | 0.482 | 0.361 | 0.448 | 0.457 | 0.440 | 0.435 | +| Coauthor CS | **0.818** | **0.818** | 0.815 | 0.816 | 0.814 | 0.797 | 0.723 | 0.753 | 0.727 | 0.685 | 0.682 | +| Amazon Photo | **0.902** | **0.902** | 0.896 | 0.898 | 0.894 | 0.890 | 0.822 | 0.877 | 0.852 | 0.890 | 0.895 | +| Amazon Computers | 0.869 | 0.871 | 0.853 | 0.855 | 0.846 | 0.853 | 0.729 | 0.838 | 0.814 | **0.872** | 0.870 | +| Coauthor Physics | 0.896 | 0.895 | **0.902** | **0.902** | 0.897 | 0.901 | 0.864 | 0.846 | 0.862 | 0.812 | 0.793 | +| Flickr | 0.267 | **0.279** | 0.255 | 0.261 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.251 | 0.213 | 0.227 | +| ogbn-arxiv | **0.446** | 0.428 | 0.431 | 0.432 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.426 | 0.312 | 0.305 | +| Reddit | 0.908 | **0.910** | 0.899 | 0.906 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.910** | 0.904 | 0.908 | +| ogbn-products | **0.324** | 0.258 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.276 | 0.278 | +| *mean rank* | **1.69** | 2.08 | 3.92 | 2.77 | 4.92 | 4.62 | 7.00 | 7.23 | 6.69 | 6.54 | 6.62 | +| *best on* | 9 / 13 | 6 / 13 | 0 / 12 | 1 / 12 | 0 / 9 | 1 / 9 | 0 / 9 | 0 / 9 | 1 / 12 | 1 / 13 | 0 / 13 | + +### `nc_mcc_logistic` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | 0.478 | 0.461 | 0.443 | 0.458 | 0.438 | **0.479** | 0.452 | 0.351 | 0.313 | 0.371 | 0.361 | +| Cora | **0.740** | 0.738 | 0.712 | 0.707 | 0.700 | 0.713 | 0.651 | 0.510 | 0.493 | 0.634 | 0.617 | +| PubMed | **0.708** | 0.697 | 0.692 | 0.693 | 0.688 | 0.697 | 0.651 | 0.648 | 0.619 | 0.553 | 0.541 | +| DBLP | **0.713** | 0.703 | 0.703 | 0.704 | 0.696 | 0.695 | 0.666 | 0.621 | 0.591 | 0.520 | 0.509 | +| Cora-Full | **0.579** | 0.572 | 0.559 | 0.559 | 0.563 | 0.562 | 0.474 | 0.519 | 0.523 | 0.506 | 0.508 | +| Coauthor CS | 0.860 | **0.861** | 0.851 | 0.852 | 0.849 | 0.847 | 0.779 | 0.798 | 0.766 | 0.762 | 0.754 | +| Amazon Photo | **0.900** | **0.900** | 0.889 | 0.893 | 0.889 | 0.895 | 0.829 | 0.879 | 0.854 | 0.891 | 0.896 | +| Amazon Computers | **0.862** | 0.859 | 0.842 | 0.844 | 0.838 | 0.855 | 0.746 | 0.832 | 0.823 | 0.861 | 0.859 | +| Coauthor Physics | 0.893 | 0.892 | 0.898 | **0.899** | 0.891 | **0.899** | 0.859 | 0.846 | 0.860 | 0.803 | 0.789 | +| Flickr | 0.316 | **0.333** | 0.298 | 0.300 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.299 | 0.220 | 0.261 | +| ogbn-arxiv | 0.637 | 0.628 | 0.642 | **0.643** | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.619 | 0.512 | 0.536 | +| Reddit | **0.938** | 0.935 | 0.934 | 0.936 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.934 | 0.933 | 0.937 | +| ogbn-products | **0.600** | 0.547 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.496 | 0.504 | +| *mean rank* | **1.46** | 1.85 | 4.08 | 3.00 | 5.31 | 3.92 | 7.00 | 7.23 | 6.92 | 6.69 | 6.38 | +| *best on* | 10 / 13 | 6 / 13 | 0 / 12 | 1 / 12 | 0 / 9 | 2 / 9 | 0 / 9 | 0 / 9 | 0 / 12 | 0 / 13 | 0 / 13 | + +### `nc_macro_roc_auc_logistic` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | **0.818** | 0.810 | 0.779 | 0.785 | 0.774 | 0.811 | 0.795 | 0.728 | 0.688 | 0.748 | 0.743 | +| Cora | **0.944** | **0.944** | 0.936 | 0.935 | 0.929 | 0.942 | 0.909 | 0.811 | 0.789 | 0.904 | 0.897 | +| PubMed | 0.922 | 0.919 | 0.917 | 0.917 | 0.914 | **0.926** | 0.900 | 0.896 | 0.882 | 0.859 | 0.849 | +| DBLP | **0.928** | 0.926 | 0.925 | 0.925 | 0.921 | 0.924 | 0.911 | 0.884 | 0.859 | 0.837 | 0.838 | +| Cora-Full | 0.928 | 0.926 | 0.930 | **0.932** | 0.923 | 0.922 | 0.907 | 0.862 | 0.839 | 0.871 | 0.872 | +| Coauthor CS | 0.972 | 0.972 | **0.973** | **0.973** | **0.973** | 0.972 | 0.955 | 0.954 | 0.936 | 0.944 | 0.941 | +| Amazon Photo | 0.981 | 0.980 | 0.980 | 0.981 | 0.979 | **0.985** | 0.965 | 0.978 | 0.972 | 0.981 | 0.982 | +| Amazon Computers | 0.981 | 0.976 | 0.976 | 0.977 | 0.974 | **0.985** | 0.957 | 0.976 | 0.974 | 0.979 | 0.980 | +| Coauthor Physics | 0.983 | 0.983 | 0.984 | 0.984 | 0.982 | **0.986** | 0.976 | 0.968 | 0.971 | 0.962 | 0.955 | +| Flickr | 0.712 | **0.718** | 0.707 | 0.705 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.715 | 0.676 | 0.689 | +| ogbn-arxiv | 0.911 | 0.892 | 0.941 | **0.943** | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.918 | 0.838 | 0.844 | +| Reddit | 0.976 | 0.979 | 0.976 | 0.975 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.990** | 0.988 | **0.990** | +| ogbn-products | **0.832** | 0.818 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.803 | 0.797 | +| *mean rank* | **2.62** | 3.08 | 3.69 | 3.15 | 5.62 | 3.62 | 6.46 | 7.38 | 6.85 | 6.38 | 6.23 | +| *best on* | 4 / 13 | 4 / 13 | 0 / 12 | 3 / 12 | 0 / 9 | 4 / 9 | 0 / 9 | 0 / 9 | 2 / 12 | 0 / 13 | 0 / 13 | + +### `nc_macro_average_precision_logistic` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | **0.568** | 0.552 | 0.510 | 0.519 | 0.524 | **0.568** | 0.522 | 0.455 | 0.421 | 0.485 | 0.484 | +| Cora | **0.825** | 0.824 | 0.803 | 0.798 | 0.779 | 0.818 | 0.729 | 0.605 | 0.602 | 0.749 | 0.732 | +| PubMed | 0.852 | 0.845 | 0.843 | 0.845 | 0.838 | **0.855** | 0.812 | 0.817 | 0.799 | 0.762 | 0.747 | +| DBLP | 0.777 | 0.772 | 0.778 | **0.780** | 0.765 | **0.780** | 0.746 | 0.728 | 0.707 | 0.636 | 0.637 | +| Cora-Full | 0.397 | 0.388 | 0.477 | 0.475 | 0.435 | **0.479** | 0.363 | 0.437 | 0.453 | 0.428 | 0.433 | +| Coauthor CS | 0.830 | 0.841 | 0.846 | **0.848** | 0.838 | 0.846 | 0.732 | 0.805 | 0.791 | 0.765 | 0.761 | +| Amazon Photo | 0.912 | 0.905 | 0.917 | 0.919 | 0.908 | **0.933** | 0.849 | 0.910 | 0.910 | 0.923 | 0.927 | +| Amazon Computers | 0.893 | 0.877 | 0.871 | 0.869 | 0.852 | **0.908** | 0.795 | 0.878 | 0.893 | 0.888 | 0.899 | +| Coauthor Physics | 0.939 | 0.935 | 0.942 | 0.943 | 0.930 | **0.948** | 0.906 | 0.895 | 0.918 | 0.885 | 0.871 | +| Flickr | 0.293 | **0.307** | 0.293 | 0.292 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.307** | 0.266 | 0.278 | +| ogbn-arxiv | 0.401 | 0.323 | **0.434** | **0.434** | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.384 | 0.284 | 0.290 | +| Reddit | 0.815 | 0.818 | 0.862 | 0.871 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.924** | 0.905 | 0.917 | +| ogbn-products | **0.343** | 0.291 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.292 | 0.299 | +| *mean rank* | 3.69 | 4.31 | 3.77 | 3.38 | 5.85 | **2.92** | 7.46 | 6.85 | 5.69 | 6.38 | 6.00 | +| *best on* | 3 / 13 | 1 / 13 | 0 / 12 | 3 / 12 | 0 / 9 | 5 / 9 | 0 / 9 | 0 / 9 | 2 / 12 | 0 / 13 | 0 / 13 | + +### `nc_top3_accuracy_logistic` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | **0.817** | 0.809 | 0.788 | 0.804 | 0.785 | 0.813 | 0.814 | 0.734 | 0.686 | 0.757 | 0.748 | +| Cora | **0.946** | 0.944 | 0.942 | 0.940 | 0.933 | 0.931 | 0.919 | 0.802 | 0.782 | 0.893 | 0.892 | +| PubMed | – | – | – | – | – | – | – | – | – | – | – | +| DBLP | 0.984 | 0.983 | 0.983 | 0.983 | **0.986** | 0.981 | 0.980 | 0.965 | 0.959 | 0.951 | 0.951 | +| Cora-Full | **0.786** | 0.781 | 0.777 | 0.778 | 0.777 | 0.770 | 0.697 | 0.713 | 0.697 | 0.685 | 0.685 | +| Coauthor CS | 0.968 | 0.969 | **0.970** | **0.970** | **0.970** | 0.959 | 0.946 | 0.934 | 0.909 | 0.915 | 0.909 | +| Amazon Photo | 0.981 | 0.981 | 0.981 | 0.981 | 0.980 | **0.982** | 0.969 | 0.975 | 0.964 | 0.979 | 0.979 | +| Amazon Computers | 0.987 | 0.986 | 0.985 | 0.986 | 0.985 | **0.989** | 0.965 | 0.979 | 0.974 | 0.987 | 0.985 | +| Coauthor Physics | 0.993 | 0.993 | **0.995** | **0.995** | 0.994 | 0.994 | 0.992 | 0.986 | 0.984 | 0.977 | 0.975 | +| Flickr | 0.826 | **0.831** | 0.825 | 0.824 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.824 | 0.809 | 0.812 | +| ogbn-arxiv | 0.888 | 0.885 | **0.906** | **0.906** | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.873 | 0.769 | 0.794 | +| Reddit | 0.978 | 0.976 | 0.978 | **0.979** | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.977 | 0.976 | **0.979** | +| ogbn-products | **0.803** | 0.776 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.733 | 0.745 | +| *mean rank* | **2.42** | 2.92 | 3.17 | 2.50 | 4.75 | 4.50 | 6.42 | 7.17 | 7.50 | 6.83 | 6.50 | +| *best on* | 5 / 12 | 4 / 12 | 1 / 11 | 3 / 11 | 1 / 8 | 2 / 8 | 0 / 8 | 0 / 8 | 0 / 11 | 0 / 12 | 0 / 12 | + +## Node classification, multi-label graphs: micro-F1 + +A label is predicted when its score is positive; no knowledge of the number of labels of a node is used. + +### `nc_micro_f1_logistic` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| PPI | **0.134 ± 0.010** | 0.127 ± 0.012 | 0.106 ± 0.004 | 0.106 ± 0.006 | 0.120 ± 0.008 | 0.091 ± 0.013 | 0.076 ± 0.014 | 0.104 ± 0.010 | 0.096 ± 0.013 | 0.123 ± 0.008 | 0.129 ± 0.008 | +| Wikipedia POS | 0.381 ± 0.009 | **0.415 ± 0.011** | 0.369 ± 0.008 | 0.371 ± 0.010 | 0.368 ± 0.008 | 0.337 ± 0.036 | 0.361 ± 0.006 | 0.290 ± 0.071 | 0.365 ± 0.013 | 0.340 ± 0.006 | 0.409 ± 0.012 | +| BlogCatalog | 0.260 ± 0.007 | 0.306 ± 0.007 | 0.277 ± 0.007 | 0.284 ± 0.005 | 0.255 ± 0.007 | 0.276 ± 0.008 | 0.283 ± 0.005 | 0.213 ± 0.003 | 0.276 ± 0.005 | **0.332 ± 0.009** | 0.301 ± 0.009 | +| Yelp | 0.282 | 0.276 | 0.202 | 0.201 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.284** | 0.185 | 0.244 | +| *mean rank* | 3.25 | **1.75** | 4.75 | 4.00 | 6.25 | 8.00 | 7.00 | 8.50 | 5.25 | 4.50 | 2.00 | +| *best on* | 1 / 4 | 1 / 4 | 0 / 4 | 0 / 4 | 0 / 3 | 0 / 3 | 0 / 3 | 0 / 3 | 1 / 4 | 1 / 4 | 1 / 4 | + +### `nc_micro_f1_mlp` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| PPI | 0.105 ± 0.040 | 0.095 ± 0.050 | 0.080 ± 0.013 | 0.080 ± 0.011 | 0.095 ± 0.012 | 0.053 ± 0.008 | 0.051 ± 0.010 | 0.061 ± 0.005 | 0.059 ± 0.008 | 0.109 ± 0.009 | **0.116 ± 0.016** | +| Wikipedia POS | 0.388 ± 0.004 | 0.390 ± 0.003 | 0.399 ± 0.022 | 0.393 ± 0.019 | 0.394 ± 0.019 | 0.288 ± 0.009 | 0.378 ± 0.010 | 0.331 ± 0.026 | 0.336 ± 0.019 | 0.362 ± 0.013 | **0.409 ± 0.020** | +| BlogCatalog | 0.275 ± 0.008 | 0.245 ± 0.050 | 0.297 ± 0.009 | 0.304 ± 0.012 | 0.273 ± 0.010 | 0.249 ± 0.012 | 0.301 ± 0.007 | 0.221 ± 0.002 | 0.273 ± 0.009 | **0.346 ± 0.005** | 0.328 ± 0.010 | +| Yelp | **0.311** | 0.305 | 0.294 | 0.292 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.302 | 0.212 | 0.277 | +| *mean rank* | 3.75 | 4.50 | 3.75 | 4.25 | 5.50 | 8.75 | 6.75 | 8.25 | 6.25 | 4.00 | **2.25** | +| *best on* | 1 / 4 | 1 / 4 | 0 / 4 | 0 / 4 | 0 / 3 | 0 / 3 | 0 / 3 | 0 / 3 | 0 / 4 | 1 / 4 | 2 / 4 | + +## Node classification, multi-label graphs: other metrics (logistic regression) + +`micro_f1_known_count` is the protocol of the DeepWalk and node2vec papers: the number of labels of every test node is given to the classifier. + +### `nc_multilabel_macro_f1_logistic` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| PPI | **0.116** | 0.112 | 0.093 | 0.094 | 0.102 | 0.076 | 0.058 | 0.089 | 0.084 | 0.107 | 0.108 | +| Wikipedia POS | 0.060 | **0.101** | 0.071 | 0.074 | 0.059 | 0.034 | 0.066 | 0.015 | 0.043 | 0.051 | 0.079 | +| BlogCatalog | 0.140 | 0.171 | 0.147 | 0.155 | 0.133 | 0.165 | 0.158 | 0.100 | 0.168 | **0.198** | 0.173 | +| Yelp | **0.130** | 0.120 | 0.041 | 0.041 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.125 | 0.039 | 0.087 | +| *mean rank* | 3.75 | **1.75** | 5.00 | 4.50 | 6.50 | 7.25 | 6.50 | 8.50 | 5.25 | 4.25 | 2.00 | +| *best on* | 2 / 4 | 2 / 4 | 0 / 4 | 0 / 4 | 0 / 3 | 0 / 3 | 0 / 3 | 0 / 3 | 0 / 4 | 1 / 4 | 1 / 4 | + +### `nc_multilabel_micro_f1_known_count_logistic` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| PPI | **0.169** | 0.162 | 0.126 | 0.126 | 0.142 | 0.154 | 0.123 | 0.135 | 0.149 | 0.154 | 0.167 | +| Wikipedia POS | 0.452 | **0.507** | 0.461 | 0.440 | 0.450 | 0.388 | 0.425 | 0.424 | 0.411 | 0.432 | 0.488 | +| BlogCatalog | 0.293 | 0.336 | 0.308 | 0.313 | 0.285 | 0.300 | 0.317 | 0.272 | 0.294 | **0.358** | 0.348 | +| Yelp | 0.515 | 0.517 | 0.516 | 0.515 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.519** | 0.506 | 0.510 | +| *mean rank* | 4.00 | **2.00** | 4.50 | 5.00 | 6.50 | 6.50 | 6.75 | 8.00 | 5.50 | 4.25 | 2.50 | +| *best on* | 1 / 4 | 1 / 4 | 0 / 4 | 0 / 4 | 0 / 3 | 0 / 3 | 0 / 3 | 0 / 3 | 1 / 4 | 1 / 4 | 1 / 4 | + +### `nc_multilabel_micro_average_precision_logistic` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| PPI | **0.087** | 0.071 | 0.063 | 0.064 | 0.076 | 0.080 | 0.064 | 0.064 | 0.071 | 0.073 | 0.083 | +| Wikipedia POS | 0.357 | 0.372 | **0.387** | 0.350 | 0.370 | 0.306 | 0.301 | 0.346 | 0.342 | 0.335 | 0.371 | +| BlogCatalog | 0.233 | 0.289 | 0.257 | 0.258 | 0.209 | 0.230 | 0.234 | 0.219 | 0.227 | **0.308** | 0.280 | +| Yelp | 0.419 | 0.420 | 0.384 | 0.382 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.424** | 0.352 | 0.392 | +| *mean rank* | 3.25 | 3.00 | 4.75 | 5.00 | 6.00 | 6.50 | 7.50 | 7.75 | 5.50 | 5.00 | **2.25** | +| *best on* | 1 / 4 | 0 / 4 | 1 / 4 | 0 / 4 | 0 / 3 | 0 / 3 | 0 / 3 | 0 / 3 | 1 / 4 | 1 / 4 | 0 / 4 | + +### `nc_multilabel_label_ranking_average_precision_logistic` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| PPI | **0.242** | 0.232 | 0.195 | 0.197 | 0.214 | 0.223 | 0.189 | 0.199 | 0.215 | 0.220 | 0.233 | +| Wikipedia POS | 0.596 | **0.644** | 0.607 | 0.588 | 0.597 | 0.536 | 0.555 | 0.585 | 0.550 | 0.577 | 0.625 | +| BlogCatalog | 0.405 | 0.450 | 0.427 | 0.433 | 0.403 | 0.405 | 0.429 | 0.388 | 0.396 | **0.472** | 0.461 | +| Yelp | 0.464 | 0.466 | 0.466 | 0.466 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.468** | 0.456 | 0.458 | +| *mean rank* | 4.00 | **2.00** | 4.50 | 4.75 | 6.00 | 6.50 | 7.25 | 7.50 | 6.00 | 4.50 | 2.50 | +| *best on* | 1 / 4 | 1 / 4 | 0 / 4 | 0 / 4 | 0 / 3 | 0 / 3 | 0 / 3 | 0 / 3 | 1 / 4 | 1 / 4 | 1 / 4 | + +### `nc_multilabel_precision_at_1_logistic` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| PPI | **0.167** | 0.158 | 0.114 | 0.116 | 0.134 | 0.151 | 0.112 | 0.128 | 0.147 | 0.151 | 0.162 | +| Wikipedia POS | 0.477 | **0.532** | 0.483 | 0.458 | 0.468 | 0.420 | 0.437 | 0.468 | 0.446 | 0.448 | 0.512 | +| BlogCatalog | 0.324 | 0.376 | 0.341 | 0.348 | 0.311 | 0.332 | 0.350 | 0.295 | 0.329 | **0.402** | 0.389 | +| Yelp | **0.737** | **0.737** | **0.737** | **0.737** | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.737** | **0.737** | **0.737** | +| *mean rank* | 4.25 | 2.50 | 4.25 | 5.00 | 6.75 | 6.50 | 7.25 | 7.00 | 5.75 | 4.50 | **2.25** | +| *best on* | 1 / 4 | 1 / 4 | 1 / 4 | 0 / 4 | 0 / 3 | 0 / 3 | 0 / 3 | 0 / 3 | 0 / 4 | 1 / 4 | 1 / 4 | + +### `nc_multilabel_hamming_loss_logistic` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| PPI | 0.051 | 0.064 | 0.059 | 0.059 | 0.053 | **0.040** | 0.045 | 0.060 | 0.043 | 0.059 | 0.051 | +| Wikipedia POS | 0.037 | 0.036 | **0.035** | 0.038 | 0.037 | 0.039 | 0.041 | **0.035** | 0.037 | 0.038 | 0.036 | +| BlogCatalog | 0.039 | 0.038 | 0.038 | 0.038 | 0.042 | 0.041 | 0.040 | 0.037 | 0.044 | **0.036** | 0.038 | +| Yelp | **0.085** | **0.085** | 0.088 | 0.088 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.085** | 0.089 | 0.086 | +| *mean rank* | 4.00 | 4.50 | 4.00 | 6.75 | 6.50 | 6.25 | 6.75 | 5.25 | 5.00 | 5.25 | **3.75** | +| *best on* | 1 / 4 | 0 / 4 | 1 / 4 | 0 / 4 | 0 / 3 | 1 / 3 | 0 / 3 | 0 / 3 | 0 / 4 | 1 / 4 | 0 / 4 | + +## Link ranking against sampled candidates: MRR + +Every held-out edge is ranked against 500 sampled non-edges of the same source node (the OGB link datasets: against their official negatives). `similarity` is the better of dot product and cosine on validation; the other tables are one per probe. + +### `lp_mrr_similarity` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | **0.458 ± 0.030** | 0.411 ± 0.026 | 0.400 ± 0.024 | 0.400 ± 0.018 | 0.389 ± 0.030 | 0.421 ± 0.025 | 0.291 ± 0.020 | 0.396 ± 0.029 | 0.386 ± 0.025 | 0.402 ± 0.029 | 0.393 ± 0.026 | +| Cora | **0.408 ± 0.011** | 0.382 ± 0.007 | 0.345 ± 0.007 | 0.348 ± 0.010 | 0.338 ± 0.002 | 0.364 ± 0.002 | 0.203 ± 0.006 | 0.351 ± 0.006 | 0.336 ± 0.005 | 0.363 ± 0.013 | 0.351 ± 0.007 | +| PPI | **0.204 ± 0.002** | 0.163 ± 0.004 | 0.070 ± 0.001 | 0.070 ± 0.001 | 0.135 ± 0.002 | 0.122 ± 0.002 | 0.091 ± 0.003 | 0.169 ± 0.002 | 0.125 ± 0.001 | 0.156 ± 0.004 | 0.183 ± 0.001 | +| PubMed | **0.450 ± 0.006** | 0.329 ± 0.003 | 0.312 ± 0.006 | 0.300 ± 0.007 | 0.420 ± 0.005 | 0.369 ± 0.007 | 0.207 ± 0.007 | 0.367 ± 0.003 | 0.328 ± 0.007 | 0.316 ± 0.006 | 0.330 ± 0.004 | +| DBLP | **0.540 ± 0.007** | 0.516 ± 0.006 | 0.381 ± 0.002 | 0.382 ± 0.002 | 0.433 ± 0.015 | 0.466 ± 0.005 | 0.259 ± 0.004 | 0.462 ± 0.006 | 0.433 ± 0.006 | 0.478 ± 0.005 | 0.492 ± 0.004 | +| Cora-Full | **0.658 ± 0.001** | 0.639 ± 0.002 | 0.532 ± 0.003 | 0.533 ± 0.004 | 0.587 ± 0.002 | 0.601 ± 0.002 | 0.340 ± 0.006 | 0.560 ± 0.004 | 0.579 ± 0.003 | 0.612 ± 0.002 | 0.614 ± 0.000 | +| Facebook (ego) | 0.595 ± 0.002 | 0.588 ± 0.002 | 0.447 ± 0.005 | 0.446 ± 0.001 | 0.454 ± 0.024 | 0.518 ± 0.003 | 0.256 ± 0.010 | 0.577 ± 0.003 | **0.601 ± 0.002** | 0.509 ± 0.004 | 0.550 ± 0.003 | +| Coauthor CS | 0.637 ± 0.001 | 0.619 ± 0.002 | 0.534 ± 0.002 | 0.538 ± 0.003 | 0.564 ± 0.018 | 0.611 ± 0.002 | 0.298 ± 0.002 | 0.556 ± 0.003 | 0.617 ± 0.002 | 0.630 ± 0.002 | **0.648 ± 0.001** | +| Amazon Photo | **0.519 ± 0.003** | 0.484 ± 0.002 | 0.326 ± 0.002 | 0.326 ± 0.003 | 0.378 ± 0.003 | 0.401 ± 0.003 | 0.187 ± 0.002 | 0.456 ± 0.002 | 0.427 ± 0.005 | 0.412 ± 0.003 | 0.427 ± 0.003 | +| Wikipedia POS | **0.270 ± 0.004** | 0.269 ± 0.004 | 0.046 ± 0.001 | 0.048 ± 0.002 | 0.070 ± 0.002 | 0.046 ± 0.001 | 0.069 ± 0.001 | 0.242 ± 0.005 | 0.058 ± 0.001 | 0.112 ± 0.003 | 0.097 ± 0.001 | +| Amazon Computers | **0.489 ± 0.002** | 0.460 ± 0.002 | 0.283 ± 0.002 | 0.285 ± 0.001 | 0.329 ± 0.003 | 0.399 ± 0.003 | 0.126 ± 0.001 | 0.421 ± 0.001 | 0.405 ± 0.003 | 0.394 ± 0.003 | 0.409 ± 0.003 | +| Coauthor Physics | 0.737 ± 0.002 | 0.719 ± 0.002 | 0.676 ± 0.003 | 0.674 ± 0.003 | 0.669 ± 0.002 | 0.651 ± 0.001 | 0.343 ± 0.003 | 0.621 ± 0.001 | 0.739 ± 0.001 | 0.725 ± 0.001 | **0.752 ± 0.002** | +| BlogCatalog | **0.222 ± 0.001** | 0.202 ± 0.000 | 0.070 ± 0.001 | 0.070 ± 0.001 | 0.092 ± 0.001 | 0.055 ± 0.000 | 0.165 ± 0.002 | 0.209 ± 0.001 | 0.070 ± 0.000 | 0.098 ± 0.000 | 0.096 ± 0.000 | +| Flickr | **0.297 ± 0.001** | 0.140 ± 0.000 | 0.244 ± 0.001 | 0.243 ± 0.000 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.195 ± 0.001 | 0.154 ± 0.001 | 0.189 ± 0.000 | +| MovieLens-1M | 0.148 ± 0.001 | 0.009 ± 0.002 | 0.060 ± 0.000 | 0.059 ± 0.000 | 0.044 ± 0.001 | 0.081 ± 0.001 | 0.108 ± 0.001 | **0.149 ± 0.012** | 0.144 ± 0.000 | 0.023 ± 0.001 | 0.102 ± 0.009 | +| ogbl-ddi | 0.027 ± 0.002 | 0.069 ± 0.001 | 0.005 ± 0.000 | 0.005 ± 0.000 | 0.010 ± 0.001 | 0.001 ± 0.000 | 0.012 ± 0.001 | **0.083 ± 0.002** | 0.002 ± 0.000 | 0.001 ± 0.000 | 0.002 ± 0.000 | +| ogbn-arxiv | **0.680 ± 0.001** | 0.659 ± 0.001 | 0.547 ± 0.002 | 0.539 ± 0.001 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.580 ± 0.002 | 0.593 ± 0.001 | 0.606 ± 0.002 | +| ogbl-collab | 0.095 ± 0.000 | **0.101 ± 0.001** | 0.095 ± 0.011 | 0.095 ± 0.006 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.039 ± 0.001 | 0.059 ± 0.001 | 0.053 ± 0.001 | +| roadNet-CA | 0.752 | 0.614 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.778** | 0.374 | 0.413 | +| Yelp | 0.495 | 0.490 | 0.302 | 0.285 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.445 | 0.361 | **0.513** | +| Reddit | 0.605 | **0.654** | 0.323 | 0.315 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.626 | 0.467 | 0.508 | +| MovieLens-20M | **0.237** | 0.025 | 0.105 | 0.104 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.227 | 0.020 | 0.202 | +| ogbl-ppa | **0.065** | 0.064 | 0.007 | 0.006 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.009 | 0.034 | 0.014 | +| ogbl-citation2 | 0.813 | **0.848** | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.793 | 0.829 | +| LiveJournal | 0.765 | **0.777** | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.685 | 0.776 | +| ogbn-products | **0.912** | 0.911 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.892 | 0.906 | +| *mean rank* | **1.50** | 2.35 | 6.15 | 6.35 | 6.12 | 5.88 | 7.31 | 4.81 | 4.58 | 4.42 | 3.27 | +| *best on* | 15 / 26 | 13 / 26 | 1 / 22 | 0 / 22 | 0 / 15 | 0 / 15 | 0 / 15 | 2 / 15 | 3 / 23 | 0 / 26 | 5 / 26 | + +### `lp_mrr_dot` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | **0.458 ± 0.030** | 0.411 ± 0.026 | 0.376 ± 0.027 | 0.355 ± 0.013 | 0.303 ± 0.042 | 0.412 ± 0.027 | 0.281 ± 0.012 | 0.396 ± 0.029 | 0.386 ± 0.025 | 0.402 ± 0.029 | 0.393 ± 0.026 | +| Cora | **0.408 ± 0.011** | 0.382 ± 0.007 | 0.305 ± 0.008 | 0.292 ± 0.016 | 0.269 ± 0.009 | 0.365 ± 0.004 | 0.177 ± 0.013 | 0.351 ± 0.006 | 0.336 ± 0.005 | 0.363 ± 0.013 | 0.351 ± 0.007 | +| PPI | **0.192 ± 0.004** | 0.163 ± 0.004 | 0.067 ± 0.004 | 0.069 ± 0.004 | 0.135 ± 0.002 | 0.098 ± 0.003 | 0.091 ± 0.003 | 0.169 ± 0.002 | 0.125 ± 0.001 | 0.143 ± 0.004 | 0.183 ± 0.001 | +| PubMed | **0.450 ± 0.006** | 0.329 ± 0.003 | 0.312 ± 0.006 | 0.300 ± 0.007 | 0.420 ± 0.005 | 0.337 ± 0.008 | 0.207 ± 0.007 | 0.367 ± 0.003 | 0.328 ± 0.007 | 0.316 ± 0.006 | 0.330 ± 0.004 | +| DBLP | **0.540 ± 0.007** | 0.516 ± 0.006 | 0.360 ± 0.005 | 0.339 ± 0.007 | 0.433 ± 0.015 | 0.425 ± 0.008 | 0.204 ± 0.001 | 0.462 ± 0.006 | 0.433 ± 0.006 | 0.478 ± 0.005 | 0.492 ± 0.004 | +| Cora-Full | **0.658 ± 0.001** | 0.639 ± 0.002 | 0.527 ± 0.004 | 0.512 ± 0.005 | 0.587 ± 0.002 | 0.579 ± 0.005 | 0.272 ± 0.007 | 0.560 ± 0.004 | 0.579 ± 0.003 | 0.612 ± 0.002 | 0.614 ± 0.000 | +| Facebook (ego) | 0.585 ± 0.002 | 0.588 ± 0.002 | 0.405 ± 0.004 | 0.375 ± 0.003 | 0.454 ± 0.024 | 0.445 ± 0.001 | 0.213 ± 0.008 | 0.577 ± 0.003 | **0.601 ± 0.002** | 0.498 ± 0.002 | 0.550 ± 0.003 | +| Coauthor CS | 0.637 ± 0.001 | 0.619 ± 0.002 | 0.529 ± 0.002 | 0.521 ± 0.004 | 0.564 ± 0.018 | 0.582 ± 0.002 | 0.175 ± 0.000 | 0.556 ± 0.003 | 0.617 ± 0.002 | 0.629 ± 0.002 | **0.648 ± 0.001** | +| Amazon Photo | **0.519 ± 0.003** | 0.484 ± 0.002 | 0.298 ± 0.002 | 0.278 ± 0.010 | 0.378 ± 0.003 | 0.347 ± 0.003 | 0.182 ± 0.002 | 0.456 ± 0.002 | 0.427 ± 0.005 | 0.412 ± 0.005 | 0.427 ± 0.003 | +| Wikipedia POS | **0.270 ± 0.004** | 0.269 ± 0.004 | 0.046 ± 0.001 | 0.048 ± 0.002 | 0.070 ± 0.002 | 0.040 ± 0.000 | 0.069 ± 0.001 | 0.242 ± 0.005 | 0.058 ± 0.001 | 0.080 ± 0.002 | 0.097 ± 0.001 | +| Amazon Computers | **0.489 ± 0.002** | 0.460 ± 0.002 | 0.225 ± 0.009 | 0.215 ± 0.006 | 0.329 ± 0.003 | 0.361 ± 0.003 | 0.109 ± 0.002 | 0.421 ± 0.001 | 0.405 ± 0.003 | 0.394 ± 0.003 | 0.409 ± 0.003 | +| Coauthor Physics | 0.732 ± 0.002 | 0.718 ± 0.002 | 0.676 ± 0.003 | 0.674 ± 0.003 | 0.669 ± 0.002 | 0.600 ± 0.001 | 0.162 ± 0.001 | 0.599 ± 0.003 | 0.739 ± 0.001 | 0.725 ± 0.001 | **0.752 ± 0.002** | +| BlogCatalog | **0.222 ± 0.001** | 0.202 ± 0.000 | 0.070 ± 0.001 | 0.070 ± 0.001 | 0.092 ± 0.001 | 0.033 ± 0.000 | 0.165 ± 0.002 | 0.209 ± 0.001 | 0.070 ± 0.000 | 0.059 ± 0.000 | 0.096 ± 0.000 | +| Flickr | **0.297 ± 0.001** | 0.140 ± 0.000 | 0.244 ± 0.001 | 0.243 ± 0.000 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.195 ± 0.001 | 0.154 ± 0.001 | 0.189 ± 0.000 | +| MovieLens-1M | 0.127 ± 0.001 | 0.009 ± 0.002 | 0.060 ± 0.000 | 0.059 ± 0.000 | 0.044 ± 0.001 | 0.034 ± 0.000 | 0.108 ± 0.001 | **0.149 ± 0.012** | 0.144 ± 0.000 | 0.023 ± 0.001 | 0.102 ± 0.009 | +| ogbl-ddi | 0.045 ± 0.001 | 0.069 ± 0.001 | 0.005 ± 0.000 | 0.005 ± 0.000 | 0.010 ± 0.001 | 0.000 ± 0.000 | 0.012 ± 0.001 | **0.083 ± 0.002** | 0.002 ± 0.000 | 0.000 ± 0.000 | 0.002 ± 0.000 | +| ogbn-arxiv | **0.680 ± 0.001** | 0.659 ± 0.001 | 0.547 ± 0.002 | 0.539 ± 0.001 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.580 ± 0.002 | 0.593 ± 0.001 | 0.606 ± 0.002 | +| ogbl-collab | 0.095 ± 0.000 | **0.101 ± 0.001** | 0.095 ± 0.011 | 0.095 ± 0.006 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.039 ± 0.001 | 0.059 ± 0.001 | 0.053 ± 0.001 | +| roadNet-CA | 0.751 | 0.612 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.778** | 0.374 | 0.413 | +| Yelp | 0.494 | 0.490 | 0.302 | 0.285 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.445 | 0.361 | **0.513** | +| Reddit | 0.588 | **0.654** | 0.312 | 0.283 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.626 | 0.440 | 0.508 | +| MovieLens-20M | **0.237** | 0.025 | 0.105 | 0.104 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.227 | 0.020 | 0.202 | +| ogbl-ppa | **0.065** | 0.064 | 0.007 | 0.006 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.009 | 0.034 | 0.014 | +| ogbl-citation2 | 0.813 | **0.848** | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.793 | 0.829 | +| LiveJournal | 0.765 | **0.777** | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.685 | 0.776 | +| ogbn-products | **0.912** | 0.911 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.892 | 0.906 | +| *mean rank* | **1.54** | 2.35 | 6.08 | 6.58 | 5.96 | 6.35 | 7.31 | 4.65 | 4.23 | 4.58 | 3.12 | +| *best on* | 15 / 26 | 13 / 26 | 1 / 22 | 0 / 22 | 0 / 15 | 0 / 15 | 0 / 15 | 2 / 15 | 3 / 23 | 0 / 26 | 5 / 26 | + +### `lp_mrr_cosine` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | **0.440 ± 0.024** | 0.390 ± 0.022 | 0.400 ± 0.024 | 0.400 ± 0.018 | 0.389 ± 0.030 | 0.421 ± 0.025 | 0.291 ± 0.020 | 0.362 ± 0.029 | 0.386 ± 0.025 | 0.402 ± 0.029 | 0.393 ± 0.026 | +| Cora | **0.387 ± 0.010** | 0.365 ± 0.010 | 0.345 ± 0.007 | 0.348 ± 0.010 | 0.338 ± 0.002 | 0.364 ± 0.002 | 0.203 ± 0.006 | 0.322 ± 0.004 | 0.336 ± 0.005 | 0.364 ± 0.012 | 0.351 ± 0.007 | +| PPI | **0.204 ± 0.002** | 0.163 ± 0.002 | 0.070 ± 0.001 | 0.070 ± 0.001 | 0.080 ± 0.001 | 0.122 ± 0.002 | 0.058 ± 0.001 | 0.107 ± 0.003 | 0.125 ± 0.001 | 0.156 ± 0.004 | 0.183 ± 0.001 | +| PubMed | **0.428 ± 0.007** | 0.304 ± 0.002 | 0.273 ± 0.003 | 0.275 ± 0.006 | 0.296 ± 0.003 | 0.369 ± 0.007 | 0.198 ± 0.002 | 0.285 ± 0.005 | 0.328 ± 0.007 | 0.315 ± 0.006 | 0.330 ± 0.004 | +| DBLP | **0.524 ± 0.006** | 0.487 ± 0.006 | 0.381 ± 0.002 | 0.382 ± 0.002 | 0.410 ± 0.002 | 0.466 ± 0.005 | 0.259 ± 0.004 | 0.396 ± 0.004 | 0.433 ± 0.006 | 0.477 ± 0.005 | 0.492 ± 0.004 | +| Cora-Full | **0.643 ± 0.001** | 0.615 ± 0.002 | 0.532 ± 0.003 | 0.533 ± 0.004 | 0.552 ± 0.004 | 0.601 ± 0.002 | 0.340 ± 0.006 | 0.523 ± 0.002 | 0.579 ± 0.003 | 0.612 ± 0.001 | 0.614 ± 0.000 | +| Facebook (ego) | 0.595 ± 0.002 | 0.545 ± 0.004 | 0.447 ± 0.005 | 0.446 ± 0.001 | 0.452 ± 0.003 | 0.518 ± 0.003 | 0.256 ± 0.010 | 0.527 ± 0.003 | **0.601 ± 0.002** | 0.509 ± 0.004 | 0.550 ± 0.003 | +| Coauthor CS | 0.634 ± 0.001 | 0.613 ± 0.002 | 0.534 ± 0.002 | 0.538 ± 0.003 | 0.551 ± 0.003 | 0.611 ± 0.002 | 0.298 ± 0.002 | 0.543 ± 0.003 | 0.617 ± 0.002 | 0.630 ± 0.002 | **0.648 ± 0.001** | +| Amazon Photo | **0.508 ± 0.004** | 0.411 ± 0.004 | 0.326 ± 0.002 | 0.326 ± 0.003 | 0.306 ± 0.004 | 0.401 ± 0.003 | 0.187 ± 0.002 | 0.367 ± 0.003 | 0.427 ± 0.005 | 0.412 ± 0.003 | 0.427 ± 0.003 | +| Wikipedia POS | **0.251 ± 0.003** | 0.210 ± 0.004 | 0.023 ± 0.000 | 0.025 ± 0.001 | 0.024 ± 0.001 | 0.046 ± 0.001 | 0.056 ± 0.002 | 0.043 ± 0.000 | 0.058 ± 0.001 | 0.112 ± 0.003 | 0.097 ± 0.001 | +| Amazon Computers | **0.483 ± 0.001** | 0.410 ± 0.002 | 0.283 ± 0.002 | 0.285 ± 0.001 | 0.275 ± 0.003 | 0.399 ± 0.003 | 0.126 ± 0.001 | 0.329 ± 0.002 | 0.405 ± 0.003 | 0.394 ± 0.003 | 0.409 ± 0.003 | +| Coauthor Physics | 0.737 ± 0.002 | 0.719 ± 0.002 | 0.662 ± 0.002 | 0.666 ± 0.002 | 0.660 ± 0.001 | 0.651 ± 0.001 | 0.343 ± 0.003 | 0.621 ± 0.001 | 0.739 ± 0.001 | 0.725 ± 0.001 | **0.752 ± 0.002** | +| BlogCatalog | **0.218 ± 0.001** | 0.114 ± 0.001 | 0.019 ± 0.000 | 0.020 ± 0.000 | 0.021 ± 0.000 | 0.055 ± 0.000 | 0.065 ± 0.000 | 0.078 ± 0.001 | 0.070 ± 0.000 | 0.098 ± 0.000 | 0.096 ± 0.000 | +| Flickr | **0.283 ± 0.001** | 0.122 ± 0.001 | 0.204 ± 0.001 | 0.205 ± 0.001 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.195 ± 0.001 | 0.154 ± 0.001 | 0.189 ± 0.000 | +| MovieLens-1M | **0.148 ± 0.001** | 0.008 ± 0.001 | 0.031 ± 0.000 | 0.031 ± 0.000 | 0.010 ± 0.000 | 0.081 ± 0.001 | 0.102 ± 0.001 | 0.034 ± 0.006 | 0.144 ± 0.000 | 0.009 ± 0.000 | 0.102 ± 0.009 | +| ogbl-ddi | **0.027 ± 0.002** | 0.003 ± 0.000 | 0.001 ± 0.000 | 0.001 ± 0.000 | 0.002 ± 0.000 | 0.001 ± 0.000 | 0.002 ± 0.000 | 0.002 ± 0.000 | 0.002 ± 0.000 | 0.001 ± 0.000 | 0.002 ± 0.000 | +| ogbn-arxiv | **0.671 ± 0.001** | 0.617 ± 0.001 | 0.473 ± 0.001 | 0.472 ± 0.001 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.580 ± 0.002 | 0.591 ± 0.002 | 0.606 ± 0.002 | +| ogbl-collab | **0.057 ± 0.001** | 0.054 ± 0.001 | 0.023 ± 0.003 | 0.022 ± 0.003 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.039 ± 0.001 | 0.052 ± 0.001 | 0.053 ± 0.001 | +| roadNet-CA | 0.752 | 0.614 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.778** | 0.374 | 0.413 | +| Yelp | 0.495 | 0.472 | 0.183 | 0.180 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.445 | 0.360 | **0.513** | +| Reddit | 0.605 | **0.645** | 0.323 | 0.315 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.626 | 0.467 | 0.508 | +| MovieLens-20M | 0.209 | 0.014 | 0.021 | 0.022 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.227** | 0.014 | 0.202 | +| ogbl-ppa | **0.069** | 0.019 | 0.002 | 0.002 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.009 | 0.012 | 0.014 | +| ogbl-citation2 | 0.802 | **0.839** | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.791 | 0.829 | +| LiveJournal | 0.756 | 0.766 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.684 | **0.776** | +| ogbn-products | **0.909** | 0.904 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.892 | 0.906 | +| *mean rank* | **1.38** | 2.69 | 6.46 | 6.42 | 6.65 | 5.31 | 7.54 | 6.42 | 3.62 | 4.04 | 2.54 | +| *best on* | 17 / 26 | 11 / 26 | 0 / 22 | 0 / 22 | 0 / 15 | 0 / 15 | 0 / 15 | 0 / 15 | 4 / 23 | 0 / 26 | 5 / 26 | + +### `lp_mrr_logistic` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | **0.446 ± 0.021** | 0.388 ± 0.020 | 0.402 ± 0.023 | 0.396 ± 0.009 | 0.401 ± 0.030 | 0.392 ± 0.017 | 0.245 ± 0.016 | 0.358 ± 0.035 | 0.387 ± 0.013 | 0.400 ± 0.027 | 0.391 ± 0.027 | +| Cora | **0.387 ± 0.010** | 0.366 ± 0.007 | 0.347 ± 0.005 | 0.354 ± 0.007 | 0.341 ± 0.008 | 0.316 ± 0.010 | 0.184 ± 0.003 | 0.316 ± 0.010 | 0.329 ± 0.005 | 0.364 ± 0.013 | 0.350 ± 0.006 | +| PPI | 0.198 ± 0.010 | 0.170 ± 0.003 | 0.110 ± 0.004 | 0.112 ± 0.002 | 0.139 ± 0.011 | 0.147 ± 0.004 | 0.088 ± 0.002 | 0.207 ± 0.001 | **0.221 ± 0.002** | 0.159 ± 0.005 | 0.191 ± 0.002 | +| PubMed | **0.431 ± 0.007** | 0.315 ± 0.003 | 0.325 ± 0.005 | 0.325 ± 0.006 | 0.352 ± 0.003 | 0.383 ± 0.005 | 0.238 ± 0.027 | 0.404 ± 0.001 | 0.416 ± 0.003 | 0.315 ± 0.006 | 0.332 ± 0.005 | +| DBLP | **0.519 ± 0.005** | 0.479 ± 0.003 | 0.423 ± 0.002 | 0.422 ± 0.003 | 0.469 ± 0.003 | 0.459 ± 0.007 | 0.274 ± 0.007 | 0.460 ± 0.004 | 0.509 ± 0.005 | 0.477 ± 0.004 | 0.491 ± 0.005 | +| Cora-Full | **0.644 ± 0.001** | 0.616 ± 0.002 | 0.561 ± 0.002 | 0.562 ± 0.005 | 0.591 ± 0.002 | 0.594 ± 0.005 | 0.364 ± 0.004 | 0.560 ± 0.001 | 0.625 ± 0.002 | 0.611 ± 0.001 | 0.613 ± 0.001 | +| Facebook (ego) | 0.589 ± 0.003 | 0.535 ± 0.004 | 0.452 ± 0.003 | 0.447 ± 0.000 | 0.487 ± 0.006 | 0.552 ± 0.004 | 0.186 ± 0.014 | 0.530 ± 0.003 | **0.625 ± 0.003** | 0.501 ± 0.001 | 0.533 ± 0.004 | +| Coauthor CS | 0.636 ± 0.001 | 0.616 ± 0.002 | 0.583 ± 0.003 | 0.584 ± 0.004 | 0.621 ± 0.003 | 0.611 ± 0.004 | 0.305 ± 0.002 | 0.556 ± 0.002 | 0.631 ± 0.002 | 0.629 ± 0.002 | **0.648 ± 0.002** | +| Amazon Photo | 0.512 ± 0.004 | 0.438 ± 0.002 | 0.373 ± 0.001 | 0.374 ± 0.003 | 0.359 ± 0.004 | 0.447 ± 0.003 | 0.209 ± 0.007 | 0.510 ± 0.002 | **0.526 ± 0.003** | 0.436 ± 0.003 | 0.457 ± 0.001 | +| Wikipedia POS | 0.264 ± 0.003 | **0.266 ± 0.003** | 0.005 ± 0.000 | 0.059 ± 0.026 | 0.085 ± 0.007 | 0.031 ± 0.020 | 0.245 ± 0.003 | 0.147 ± 0.002 | 0.194 ± 0.038 | 0.140 ± 0.004 | 0.102 ± 0.057 | +| Amazon Computers | 0.483 ± 0.002 | 0.437 ± 0.002 | 0.357 ± 0.003 | 0.359 ± 0.003 | 0.353 ± 0.002 | 0.407 ± 0.001 | 0.119 ± 0.001 | 0.458 ± 0.003 | **0.497 ± 0.003** | 0.419 ± 0.003 | 0.443 ± 0.003 | +| Coauthor Physics | 0.747 ± 0.002 | 0.729 ± 0.001 | 0.702 ± 0.001 | 0.704 ± 0.001 | 0.737 ± 0.001 | 0.666 ± 0.001 | 0.353 ± 0.027 | 0.633 ± 0.001 | 0.742 ± 0.003 | 0.727 ± 0.001 | **0.753 ± 0.001** | +| BlogCatalog | 0.219 ± 0.000 | 0.214 ± 0.003 | 0.112 ± 0.006 | 0.129 ± 0.000 | 0.129 ± 0.003 | 0.095 ± 0.002 | 0.192 ± 0.001 | 0.186 ± 0.001 | **0.252 ± 0.001** | 0.165 ± 0.005 | 0.189 ± 0.001 | +| Flickr | **0.278 ± 0.005** | 0.134 ± 0.002 | 0.220 ± 0.004 | 0.216 ± 0.001 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.253 ± 0.003 | 0.149 ± 0.001 | 0.187 ± 0.002 | +| MovieLens-1M | 0.133 ± 0.002 | 0.132 ± 0.006 | 0.122 ± 0.006 | 0.122 ± 0.003 | 0.090 ± 0.011 | 0.122 ± 0.002 | 0.110 ± 0.001 | 0.151 ± 0.003 | **0.203 ± 0.000** | 0.120 ± 0.002 | 0.092 ± 0.013 | +| ogbl-ddi | 0.028 ± 0.012 | 0.028 ± 0.002 | 0.012 ± 0.001 | 0.010 ± 0.002 | 0.039 ± 0.019 | 0.012 ± 0.000 | 0.017 ± 0.001 | 0.058 ± 0.001 | **0.074 ± 0.003** | 0.011 ± 0.002 | 0.004 ± 0.001 | +| ogbn-arxiv | **0.669 ± 0.001** | 0.625 ± 0.001 | 0.551 ± 0.001 | 0.549 ± 0.002 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.647 ± 0.003 | 0.592 ± 0.002 | 0.619 ± 0.001 | +| ogbl-collab | **0.066 ± 0.004** | **0.066 ± 0.004** | 0.049 ± 0.003 | 0.049 ± 0.008 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.034 ± 0.001 | 0.060 ± 0.003 | 0.059 ± 0.001 | +| roadNet-CA | 0.752 | 0.614 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.778** | 0.374 | 0.413 | +| Yelp | 0.498 | 0.471 | 0.369 | 0.360 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.515** | 0.358 | 0.511 | +| Reddit | 0.607 | **0.646** | 0.380 | 0.363 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.625 | 0.485 | 0.520 | +| MovieLens-20M | 0.220 | 0.226 | 0.138 | 0.152 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.298** | 0.173 | 0.209 | +| ogbl-ppa | **0.077** | 0.035 | 0.006 | 0.008 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.045 | 0.028 | 0.033 | +| ogbl-citation2 | 0.803 | **0.839** | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.790 | 0.829 | +| LiveJournal | 0.756 | 0.769 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.683 | **0.777** | +| ogbn-products | **0.909** | 0.904 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.891 | 0.906 | +| *mean rank* | **1.77** | 3.12 | 6.08 | 6.12 | 6.15 | 6.19 | 7.46 | 5.58 | 2.50 | 4.73 | 3.81 | +| *best on* | 11 / 26 | 5 / 26 | 0 / 22 | 0 / 22 | 0 / 15 | 0 / 15 | 0 / 15 | 0 / 15 | 11 / 23 | 0 / 26 | 4 / 26 | + +## Link ranking against sampled candidates: other metrics (cosine) + +### `lp_hits@1_cosine` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | **0.321** | 0.278 | 0.282 | 0.279 | 0.279 | 0.299 | 0.195 | 0.267 | 0.287 | 0.289 | 0.284 | +| Cora | **0.271** | 0.256 | 0.237 | 0.238 | 0.235 | 0.253 | 0.133 | 0.230 | 0.250 | 0.257 | 0.247 | +| PPI | **0.123** | 0.091 | 0.032 | 0.032 | 0.041 | 0.064 | 0.021 | 0.056 | 0.067 | 0.085 | 0.103 | +| PubMed | **0.297** | 0.190 | 0.144 | 0.147 | 0.167 | 0.231 | 0.100 | 0.167 | 0.207 | 0.203 | 0.215 | +| DBLP | **0.395** | 0.353 | 0.237 | 0.238 | 0.270 | 0.321 | 0.151 | 0.260 | 0.308 | 0.351 | 0.365 | +| Cora-Full | **0.525** | 0.490 | 0.391 | 0.392 | 0.416 | 0.465 | 0.215 | 0.382 | 0.458 | 0.493 | 0.495 | +| Facebook (ego) | **0.454** | 0.392 | 0.278 | 0.278 | 0.295 | 0.361 | 0.157 | 0.369 | 0.450 | 0.351 | 0.398 | +| Coauthor CS | 0.529 | 0.507 | 0.408 | 0.415 | 0.426 | 0.492 | 0.201 | 0.411 | 0.501 | 0.523 | **0.545** | +| Amazon Photo | **0.368** | 0.269 | 0.195 | 0.194 | 0.182 | 0.251 | 0.101 | 0.234 | 0.288 | 0.271 | 0.286 | +| Wikipedia POS | **0.168** | 0.125 | 0.009 | 0.010 | 0.009 | 0.019 | 0.024 | 0.017 | 0.026 | 0.060 | 0.046 | +| Amazon Computers | **0.352** | 0.276 | 0.170 | 0.172 | 0.167 | 0.259 | 0.062 | 0.202 | 0.275 | 0.263 | 0.277 | +| Coauthor Physics | 0.646 | 0.625 | 0.543 | 0.548 | 0.543 | 0.543 | 0.248 | 0.490 | 0.628 | 0.627 | **0.658** | +| BlogCatalog | **0.128** | 0.053 | 0.007 | 0.008 | 0.007 | 0.023 | 0.023 | 0.032 | 0.029 | 0.045 | 0.041 | +| Flickr | **0.217** | 0.077 | 0.136 | 0.137 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.124 | 0.103 | 0.124 | +| MovieLens-1M | **0.078** | 0.000 | 0.009 | 0.009 | 0.002 | 0.034 | 0.048 | 0.007 | 0.064 | 0.001 | 0.045 | +| ogbl-ddi | **0.003** | 0.000 | 0.000 | 0.000 | 0.001 | 0.000 | 0.000 | 0.000 | 0.000 | 0.000 | 0.000 | +| ogbn-arxiv | **0.577** | 0.514 | 0.358 | 0.358 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.470 | 0.487 | 0.505 | +| ogbl-collab | **0.003** | 0.002 | 0.000 | 0.000 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.001 | 0.001 | 0.000 | +| roadNet-CA | 0.741 | 0.595 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.769** | 0.262 | 0.384 | +| Yelp | 0.404 | 0.376 | 0.109 | 0.106 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.338 | 0.263 | **0.416** | +| Reddit | 0.497 | **0.555** | 0.205 | 0.192 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.520 | 0.352 | 0.398 | +| MovieLens-20M | 0.109 | 0.002 | 0.007 | 0.008 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.123** | 0.003 | 0.111 | +| ogbl-ppa | **0.035** | 0.000 | 0.000 | 0.000 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.000 | 0.000 | 0.000 | +| ogbl-citation2 | 0.767 | **0.788** | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.730 | 0.780 | +| LiveJournal | 0.721 | 0.726 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.630 | **0.740** | +| ogbn-products | **0.877** | 0.867 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.846 | 0.864 | +| *mean rank* | **1.35** | 3.23 | 6.29 | 5.94 | 6.77 | 5.29 | 7.63 | 6.63 | 3.56 | 4.02 | 2.90 | +| *best on* | 18 / 26 | 7 / 26 | 0 / 22 | 0 / 22 | 0 / 15 | 0 / 15 | 0 / 15 | 0 / 15 | 3 / 23 | 0 / 26 | 5 / 26 | + +### `lp_hits@10_cosine` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | **0.667** | 0.618 | 0.640 | 0.634 | 0.596 | 0.657 | 0.483 | 0.524 | 0.550 | 0.623 | 0.604 | +| Cora | **0.618** | 0.584 | 0.563 | 0.564 | 0.530 | 0.581 | 0.335 | 0.481 | 0.483 | 0.575 | 0.549 | +| PPI | **0.367** | 0.306 | 0.133 | 0.130 | 0.145 | 0.232 | 0.119 | 0.195 | 0.236 | 0.298 | 0.343 | +| PubMed | **0.684** | 0.539 | 0.555 | 0.553 | 0.565 | 0.652 | 0.404 | 0.534 | 0.575 | 0.529 | 0.551 | +| DBLP | **0.766** | 0.742 | 0.683 | 0.684 | 0.695 | 0.750 | 0.489 | 0.677 | 0.674 | 0.712 | 0.726 | +| Cora-Full | **0.855** | 0.840 | 0.813 | 0.812 | 0.810 | 0.847 | 0.606 | 0.793 | 0.789 | 0.819 | 0.821 | +| Facebook (ego) | 0.886 | 0.876 | 0.827 | 0.827 | 0.803 | 0.856 | 0.465 | 0.866 | **0.910** | 0.852 | 0.873 | +| Coauthor CS | 0.824 | 0.806 | 0.774 | 0.772 | 0.792 | **0.830** | 0.492 | 0.801 | 0.825 | 0.818 | 0.828 | +| Amazon Photo | **0.786** | 0.716 | 0.603 | 0.605 | 0.570 | 0.726 | 0.364 | 0.646 | 0.712 | 0.711 | 0.724 | +| Wikipedia POS | **0.404** | 0.383 | 0.038 | 0.042 | 0.041 | 0.087 | 0.102 | 0.082 | 0.103 | 0.207 | 0.189 | +| Amazon Computers | **0.744** | 0.685 | 0.518 | 0.519 | 0.496 | 0.692 | 0.246 | 0.595 | 0.669 | 0.662 | 0.675 | +| Coauthor Physics | 0.891 | 0.880 | 0.879 | 0.879 | 0.880 | 0.848 | 0.527 | 0.870 | **0.925** | 0.891 | 0.906 | +| BlogCatalog | **0.396** | 0.226 | 0.031 | 0.032 | 0.036 | 0.105 | 0.136 | 0.157 | 0.136 | 0.192 | 0.191 | +| Flickr | **0.395** | 0.198 | 0.337 | 0.339 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.334 | 0.243 | 0.313 | +| MovieLens-1M | 0.283 | 0.006 | 0.060 | 0.059 | 0.013 | 0.166 | 0.207 | 0.069 | **0.308** | 0.009 | 0.207 | +| ogbl-ddi | **0.082** | 0.000 | 0.001 | 0.001 | 0.003 | 0.000 | 0.000 | 0.000 | 0.000 | 0.000 | 0.000 | +| ogbn-arxiv | **0.835** | 0.808 | 0.689 | 0.685 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.777 | 0.780 | 0.788 | +| ogbl-collab | **0.210** | 0.192 | 0.060 | 0.063 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.128 | 0.196 | 0.183 | +| roadNet-CA | 0.768 | 0.646 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.793** | 0.604 | 0.462 | +| Yelp | 0.671 | 0.655 | 0.323 | 0.318 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.657 | 0.549 | **0.693** | +| Reddit | 0.824 | 0.832 | 0.595 | 0.597 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.847** | 0.722 | 0.745 | +| MovieLens-20M | 0.420 | 0.022 | 0.038 | 0.038 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.445** | 0.023 | 0.388 | +| ogbl-ppa | **0.139** | 0.051 | 0.002 | 0.002 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.011 | 0.016 | 0.029 | +| ogbl-citation2 | 0.855 | **0.912** | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.888 | 0.901 | +| LiveJournal | 0.816 | 0.837 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.784 | **0.839** | +| ogbn-products | 0.955 | 0.956 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.958 | **0.966** | +| *mean rank* | **1.65** | 3.19 | 5.88 | 5.85 | 6.54 | 4.83 | 7.63 | 6.48 | 4.06 | 4.29 | 3.17 | +| *best on* | 15 / 26 | 6 / 26 | 0 / 22 | 0 / 22 | 0 / 15 | 1 / 15 | 0 / 15 | 0 / 15 | 6 / 23 | 0 / 26 | 4 / 26 | + +### `lp_hits@100_cosine` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | 0.831 | 0.809 | 0.835 | 0.827 | 0.805 | 0.804 | **0.838** | 0.669 | 0.666 | 0.763 | 0.777 | +| Cora | 0.854 | 0.842 | 0.850 | **0.856** | 0.821 | 0.846 | 0.721 | 0.654 | 0.624 | 0.756 | 0.757 | +| PPI | **0.752** | 0.681 | 0.430 | 0.427 | 0.464 | 0.569 | 0.501 | 0.631 | 0.652 | 0.677 | 0.747 | +| PubMed | 0.899 | 0.843 | 0.906 | **0.907** | 0.887 | 0.885 | 0.853 | 0.719 | 0.723 | 0.756 | 0.764 | +| DBLP | 0.918 | 0.913 | **0.932** | 0.931 | 0.914 | 0.927 | 0.850 | 0.818 | 0.779 | 0.856 | 0.861 | +| Cora-Full | 0.954 | 0.953 | 0.967 | **0.968** | 0.955 | 0.957 | 0.913 | 0.884 | 0.857 | 0.910 | 0.909 | +| Facebook (ego) | **0.999** | 0.998 | **0.999** | **0.999** | 0.979 | **0.999** | 0.821 | 0.998 | 0.985 | 0.998 | **0.999** | +| Coauthor CS | 0.946 | 0.949 | 0.949 | 0.950 | **0.954** | 0.943 | 0.831 | 0.902 | 0.886 | 0.912 | 0.910 | +| Amazon Photo | **0.981** | 0.976 | 0.940 | 0.939 | 0.917 | 0.978 | 0.814 | 0.962 | 0.940 | 0.975 | 0.975 | +| Wikipedia POS | **0.713** | 0.670 | 0.172 | 0.179 | 0.212 | 0.323 | 0.461 | 0.320 | 0.485 | 0.574 | 0.630 | +| Amazon Computers | **0.966** | 0.961 | 0.879 | 0.875 | 0.856 | 0.959 | 0.700 | 0.934 | 0.918 | 0.953 | 0.958 | +| Coauthor Physics | 0.969 | 0.968 | 0.980 | 0.980 | **0.982** | 0.973 | 0.828 | 0.963 | 0.961 | 0.960 | 0.960 | +| BlogCatalog | **0.797** | 0.711 | 0.136 | 0.137 | 0.181 | 0.398 | 0.571 | 0.583 | 0.567 | 0.636 | 0.711 | +| Flickr | 0.616 | 0.450 | 0.635 | **0.636** | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.602 | 0.499 | 0.559 | +| MovieLens-1M | 0.721 | 0.142 | 0.314 | 0.311 | 0.105 | 0.506 | 0.558 | 0.471 | **0.796** | 0.138 | 0.695 | +| ogbl-ddi | **0.216** | 0.075 | 0.008 | 0.006 | 0.013 | 0.014 | 0.056 | 0.030 | 0.006 | 0.038 | 0.061 | +| ogbn-arxiv | **0.951** | 0.950 | 0.936 | 0.933 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.906 | 0.927 | 0.945 | +| ogbl-collab | 0.532 | **0.535** | 0.323 | 0.320 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.405 | 0.455 | 0.513 | +| roadNet-CA | 0.834 | 0.758 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.849** | 0.773 | 0.621 | +| Yelp | 0.843 | **0.868** | 0.790 | 0.786 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.863 | 0.797 | 0.859 | +| Reddit | 0.982 | 0.976 | 0.934 | 0.938 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.988** | 0.957 | 0.965 | +| MovieLens-20M | 0.832 | 0.218 | 0.168 | 0.168 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.884** | 0.134 | 0.816 | +| ogbl-ppa | **0.373** | 0.307 | 0.025 | 0.024 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.165 | 0.251 | 0.223 | +| ogbl-citation2 | 0.911 | **0.946** | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.940 | 0.939 | +| LiveJournal | 0.896 | **0.910** | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.892 | 0.909 | +| ogbn-products | 0.978 | 0.978 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.980 | **0.983** | +| *mean rank* | **2.38** | 2.96 | 4.81 | 4.85 | 6.12 | 5.15 | 6.50 | 6.54 | 5.50 | 4.85 | 3.69 | +| *best on* | 9 / 26 | 10 / 26 | 1 / 22 | 4 / 22 | 2 / 15 | 0 / 15 | 1 / 15 | 0 / 15 | 5 / 23 | 1 / 26 | 3 / 26 | + +### `lp_roc_auc_cosine` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | 0.878 | 0.862 | **0.897** | 0.896 | 0.871 | 0.866 | 0.859 | 0.736 | 0.745 | 0.855 | 0.852 | +| Cora | **0.899** | 0.892 | 0.896 | 0.894 | 0.867 | 0.878 | 0.817 | 0.727 | 0.709 | 0.849 | 0.848 | +| PPI | **0.799** | 0.758 | 0.655 | 0.648 | 0.666 | 0.729 | 0.713 | 0.773 | 0.776 | 0.789 | 0.794 | +| PubMed | 0.909 | 0.868 | **0.917** | **0.917** | 0.905 | 0.912 | 0.868 | 0.768 | 0.783 | 0.843 | 0.843 | +| DBLP | 0.925 | 0.914 | 0.942 | **0.943** | 0.937 | 0.935 | 0.857 | 0.853 | 0.827 | 0.909 | 0.902 | +| Cora-Full | 0.962 | 0.960 | **0.970** | **0.970** | 0.963 | 0.965 | 0.915 | 0.902 | 0.883 | 0.943 | 0.941 | +| Facebook (ego) | **0.990** | 0.988 | 0.987 | 0.987 | 0.960 | 0.989 | 0.857 | **0.990** | 0.982 | 0.988 | 0.989 | +| Coauthor CS | 0.957 | 0.956 | 0.954 | 0.954 | **0.962** | 0.959 | 0.857 | 0.923 | 0.912 | 0.945 | 0.941 | +| Amazon Photo | **0.975** | 0.967 | 0.952 | 0.951 | 0.919 | 0.970 | 0.847 | 0.962 | 0.946 | 0.969 | 0.964 | +| Wikipedia POS | **0.764** | 0.738 | 0.449 | 0.469 | 0.450 | 0.562 | 0.673 | 0.507 | 0.717 | 0.733 | 0.716 | +| Amazon Computers | **0.961** | 0.954 | 0.909 | 0.907 | 0.876 | 0.958 | 0.809 | 0.950 | 0.935 | 0.953 | 0.947 | +| Coauthor Physics | 0.971 | 0.968 | 0.975 | 0.975 | **0.980** | 0.975 | 0.854 | 0.968 | 0.970 | 0.974 | 0.972 | +| BlogCatalog | **0.828** | 0.782 | 0.410 | 0.411 | 0.451 | 0.625 | 0.759 | 0.748 | 0.768 | 0.792 | 0.810 | +| Flickr | **0.768** | 0.639 | 0.764 | 0.764 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.738 | 0.702 | 0.729 | +| MovieLens-1M | 0.788 | 0.497 | 0.615 | 0.615 | 0.406 | 0.694 | 0.666 | 0.707 | **0.872** | 0.447 | 0.764 | +| ogbl-ddi | 0.930 | 0.933 | 0.812 | 0.821 | 0.718 | 0.803 | 0.839 | 0.950 | **0.978** | 0.862 | 0.888 | +| ogbn-arxiv | **0.961** | 0.956 | 0.935 | 0.934 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.930 | 0.951 | 0.946 | +| ogbl-collab | 0.842 | **0.865** | 0.802 | 0.802 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.812 | 0.803 | 0.812 | +| roadNet-CA | 0.897 | 0.850 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.906** | 0.848 | 0.765 | +| Yelp | 0.888 | 0.890 | 0.855 | 0.854 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.905** | 0.870 | 0.891 | +| Reddit | 0.981 | 0.980 | 0.949 | 0.953 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.988** | 0.964 | 0.973 | +| MovieLens-20M | 0.858 | 0.531 | 0.433 | 0.434 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.912** | 0.470 | 0.787 | +| ogbl-ppa | 0.986 | 0.967 | **0.989** | **0.989** | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.988 | 0.986 | 0.986 | +| ogbl-citation2 | 0.959 | **0.975** | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.972 | 0.972 | +| LiveJournal | 0.937 | **0.945** | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.930 | 0.944 | +| ogbn-products | 0.987 | 0.987 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.988 | **0.989** | +| *mean rank* | **2.42** | 3.58 | 4.96 | 4.85 | 6.19 | 5.00 | 6.96 | 6.35 | 5.04 | 4.42 | 4.19 | +| *best on* | 10 / 26 | 5 / 26 | 3 / 22 | 2 / 22 | 2 / 15 | 0 / 15 | 0 / 15 | 0 / 15 | 6 / 23 | 1 / 26 | 2 / 26 | + +### `lp_average_precision_cosine` + +| Dataset | Cleora | Cleora, two columns | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | **0.913** | 0.898 | 0.910 | **0.913** | 0.893 | 0.909 | 0.891 | 0.822 | 0.832 | 0.894 | 0.892 | +| Cora | **0.924** | 0.917 | 0.916 | 0.912 | 0.895 | 0.914 | 0.824 | 0.819 | 0.808 | 0.888 | 0.886 | +| PPI | **0.808** | 0.772 | 0.678 | 0.674 | 0.683 | 0.765 | 0.702 | 0.776 | 0.798 | 0.802 | 0.806 | +| PubMed | 0.923 | 0.882 | 0.920 | 0.920 | 0.917 | **0.928** | 0.873 | 0.843 | 0.854 | 0.876 | 0.878 | +| DBLP | 0.941 | 0.932 | 0.943 | 0.944 | 0.944 | **0.949** | 0.871 | 0.901 | 0.888 | 0.930 | 0.928 | +| Cora-Full | 0.972 | 0.969 | 0.972 | 0.972 | 0.969 | **0.974** | 0.920 | 0.939 | 0.929 | 0.959 | 0.958 | +| Facebook (ego) | **0.986** | 0.983 | 0.981 | 0.981 | 0.960 | 0.985 | 0.866 | **0.986** | **0.986** | 0.983 | 0.984 | +| Coauthor CS | 0.967 | 0.965 | 0.960 | 0.960 | 0.968 | **0.970** | 0.876 | 0.950 | 0.945 | 0.960 | 0.959 | +| Amazon Photo | **0.973** | 0.960 | 0.946 | 0.945 | 0.924 | 0.965 | 0.834 | 0.963 | 0.959 | 0.963 | 0.956 | +| Wikipedia POS | **0.770** | 0.746 | 0.477 | 0.492 | 0.478 | 0.601 | 0.691 | 0.500 | 0.694 | 0.755 | 0.733 | +| Amazon Computers | **0.958** | 0.948 | 0.911 | 0.910 | 0.886 | **0.958** | 0.801 | 0.949 | 0.950 | 0.949 | 0.938 | +| Coauthor Physics | 0.977 | 0.973 | 0.976 | 0.976 | **0.981** | 0.979 | 0.867 | 0.976 | **0.981** | 0.980 | 0.980 | +| BlogCatalog | **0.820** | 0.779 | 0.444 | 0.444 | 0.466 | 0.648 | 0.763 | 0.733 | 0.734 | 0.779 | 0.790 | +| Flickr | **0.812** | 0.682 | 0.795 | 0.796 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.790 | 0.747 | 0.777 | +| MovieLens-1M | 0.779 | 0.477 | 0.578 | 0.576 | 0.429 | 0.723 | 0.643 | 0.645 | **0.863** | 0.463 | 0.723 | +| ogbl-ddi | 0.951 | 0.950 | 0.832 | 0.838 | 0.763 | 0.859 | 0.865 | 0.957 | **0.977** | 0.895 | 0.913 | +| ogbn-arxiv | **0.969** | 0.964 | 0.939 | 0.937 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.950 | 0.961 | 0.954 | +| ogbl-collab | 0.826 | **0.851** | 0.777 | 0.776 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 0.807 | 0.785 | 0.794 | +| roadNet-CA | 0.931 | 0.895 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.938** | 0.891 | 0.824 | +| Yelp | 0.915 | 0.910 | 0.849 | 0.847 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.929** | 0.895 | 0.914 | +| Reddit | 0.980 | 0.980 | 0.949 | 0.950 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.988** | 0.964 | 0.970 | +| MovieLens-20M | 0.843 | 0.519 | 0.432 | 0.432 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.889** | 0.502 | 0.736 | +| ogbl-ppa | 0.990 | 0.976 | 0.987 | 0.988 | n/a (size) | n/a (size) | n/a (size) | n/a (size) | **0.991** | 0.989 | 0.989 | +| ogbl-citation2 | 0.972 | **0.982** | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.980 | 0.980 | +| LiveJournal | 0.956 | **0.961** | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.951 | **0.961** | +| ogbn-products | 0.991 | 0.991 | time limit | time limit | n/a (size) | n/a (size) | n/a (size) | n/a (size) | out of memory | 0.991 | **0.993** | +| *mean rank* | **2.08** | 3.73 | 5.73 | 5.65 | 6.31 | 4.58 | 7.23 | 6.23 | 4.19 | 4.27 | 4.12 | +| *best on* | 11 / 26 | 4 / 26 | 0 / 22 | 0 / 22 | 1 / 15 | 4 / 15 | 0 / 15 | 0 / 15 | 7 / 23 | 0 / 26 | 3 / 26 | + +## Cleora: the four ways of feeding and normalising a graph + +One column (`complex::reflexive::node`) or two (`src dst`), left or symmetric normalisation, each with the number of iterations the library suggests for the task; `tuned`: iteration count and family chosen on validation. Logistic regression for classification, cosine for link ranking. + +### `families_nc_accuracy` + +| Dataset | one column, left | one column, symmetric | two columns, left | two columns, symmetric | tuned | pycleora 3.2 default | +|---|---:|---:|---:|---:|---:|---:| +| CiteSeer | 0.567 | 0.576 | 0.550 | 0.552 | **0.580** | 0.371 | +| Cora | 0.788 | 0.791 | 0.786 | **0.793** | 0.792 | 0.449 | +| PubMed | 0.812 | 0.806 | 0.805 | 0.804 | **0.815** | 0.726 | +| DBLP | 0.808 | 0.800 | 0.802 | 0.797 | **0.818** | 0.710 | +| Cora-Full | 0.589 | **0.590** | 0.582 | 0.584 | 0.587 | 0.503 | +| Coauthor CS | 0.876 | 0.880 | 0.876 | 0.880 | **0.884** | 0.768 | +| Amazon Photo | 0.916 | 0.920 | 0.916 | 0.922 | **0.924** | 0.708 | +| Amazon Computers | 0.891 | 0.895 | 0.888 | 0.897 | **0.899** | 0.775 | +| Coauthor Physics | 0.928 | 0.934 | 0.927 | 0.934 | **0.939** | 0.898 | +| Flickr | 0.543 | 0.526 | 0.551 | 0.531 | **0.553** | 0.548 | +| ogbn-arxiv | 0.681 | 0.675 | 0.671 | 0.684 | **0.700** | 0.695 | +| Reddit | 0.941 | 0.911 | 0.939 | 0.920 | **0.946** | 0.935 | +| ogbn-products | 0.645 | 0.537 | 0.602 | 0.604 | 0.604 | **0.741** | + +### `families_nc_micro_f1` + +| Dataset | one column, left | one column, symmetric | two columns, left | two columns, symmetric | tuned | pycleora 3.2 default | +|---|---:|---:|---:|---:|---:|---:| +| PPI | 0.134 | **0.135** | 0.127 | 0.118 | 0.134 | 0.076 | +| Wikipedia POS | 0.381 | 0.273 | 0.415 | 0.307 | **0.433** | 0.316 | +| BlogCatalog | 0.260 | 0.215 | 0.306 | 0.305 | **0.324** | 0.216 | +| Yelp | **0.282** | 0.250 | 0.276 | 0.260 | **0.282** | 0.264 | + +### `families_lp_mrr` + +| Dataset | one column, left | one column, symmetric | two columns, left | two columns, symmetric | tuned | pycleora 3.2 default | +|---|---:|---:|---:|---:|---:|---:| +| CiteSeer | 0.427 | 0.440 | 0.375 | 0.390 | **0.445** | 0.215 | +| Cora | 0.367 | 0.387 | 0.345 | 0.365 | **0.388** | 0.179 | +| PPI | 0.186 | 0.204 | 0.157 | 0.163 | **0.207** | 0.030 | +| PubMed | 0.421 | **0.428** | 0.310 | 0.304 | 0.427 | 0.293 | +| DBLP | 0.506 | 0.524 | 0.483 | 0.487 | **0.529** | 0.410 | +| Cora-Full | 0.626 | 0.643 | 0.608 | 0.615 | **0.649** | 0.571 | +| Facebook (ego) | 0.564 | 0.595 | 0.586 | 0.545 | **0.608** | 0.065 | +| Coauthor CS | 0.634 | 0.634 | 0.608 | 0.613 | **0.657** | 0.621 | +| Amazon Photo | 0.450 | 0.508 | 0.398 | 0.411 | **0.520** | 0.161 | +| Wikipedia POS | 0.077 | **0.251** | 0.071 | 0.210 | **0.251** | 0.033 | +| Amazon Computers | 0.419 | 0.483 | 0.381 | 0.410 | **0.493** | 0.249 | +| Coauthor Physics | 0.744 | 0.737 | 0.708 | 0.719 | **0.765** | 0.752 | +| BlogCatalog | 0.093 | **0.218** | 0.084 | 0.114 | **0.218** | 0.024 | +| Flickr | 0.240 | 0.283 | 0.101 | 0.122 | **0.297** | 0.221 | +| MovieLens-1M | 0.103 | **0.148** | 0.010 | 0.008 | **0.148** | 0.008 | +| ogbl-ddi | 0.002 | **0.027** | 0.003 | 0.003 | **0.027** | 0.000 | +| ogbn-arxiv | 0.615 | **0.671** | 0.562 | 0.617 | **0.671** | 0.613 | +| ogbl-collab | 0.054 | **0.057** | 0.051 | 0.054 | 0.055 | 0.045 | +| roadNet-CA | 0.716 | 0.752 | 0.560 | 0.614 | 0.752 | **0.816** | +| Yelp | **0.504** | 0.495 | 0.479 | 0.472 | **0.504** | 0.501 | +| Reddit | 0.509 | 0.605 | 0.551 | 0.645 | **0.745** | 0.572 | +| MovieLens-20M | 0.183 | **0.209** | 0.010 | 0.014 | **0.209** | 0.053 | +| ogbl-ppa | 0.011 | **0.069** | 0.020 | 0.019 | **0.069** | 0.011 | +| ogbl-citation2 | 0.838 | 0.802 | 0.830 | **0.839** | 0.838 | 0.827 | +| LiveJournal | 0.783 | 0.756 | 0.799 | 0.766 | 0.799 | **0.809** | +| ogbn-products | 0.906 | **0.909** | 0.904 | 0.904 | **0.909** | 0.893 | + +## Cleora: which normalisation for which task + +Mean validation score of each family over the graphs on which all four ran, and in parentheses the number of graphs on which it validated best. The main tables use the left normalisation for classification and the symmetric one for link ranking, for every graph, on the strength of this table. + +| Task | Graphs | one column, left | one column, symmetric | two columns, left | two columns, symmetric | +|---|---:|---:|---:|---:|---:| +| node classification (logistic regression) | 17 | 0.6661 (6) | 0.6511 (3) | 0.6676 (3) | 0.6590 (5) | +| link ranking (cosine) | 26 | 0.4242 (3) | 0.4575 (21) | 0.3870 (1) | 0.4033 (1) | + +## Cleora: what a validation set adds + +`Cleora`: as in the main tables. `Cleora, tuned`: the number of iterations (from a sweep over twelve values) and the family chosen on validation data. `gain` in points of the metric. Classification with logistic regression, link ranking against sampled candidates with dot product or cosine - the two scores the sweep validates. + +### `tuned_nc` + +| Dataset | Cleora | Cleora, tuned | gain | Best baseline | +|---|---:|---:|---:|---| +| CiteSeer | 0.567 | **0.580** | +1.3 | NetMF 0.572 | +| Cora | 0.788 | **0.792** | +0.4 | NetMF 0.766 | +| PubMed | 0.812 | **0.815** | +0.3 | NetMF 0.806 | +| DBLP | 0.808 | **0.818** | +1.0 | node2vec 0.803 | +| Cora-Full | **0.589** | 0.587 | -0.1 | Walklets 0.573 | +| Coauthor CS | 0.876 | **0.884** | +0.7 | node2vec 0.869 | +| Amazon Photo | 0.916 | **0.924** | +0.8 | RandNE 0.913 | +| Amazon Computers | 0.891 | **0.899** | +0.9 | FastRP 0.890 | +| Coauthor Physics | 0.928 | **0.939** | +1.1 | NetMF 0.932 | +| Flickr | 0.543 | **0.553** | +1.0 | ProNE 0.535 | +| ogbn-arxiv | 0.681 | **0.700** | +1.9 | node2vec 0.685 | +| Reddit | 0.941 | **0.946** | +0.5 | RandNE 0.940 | +| ogbn-products | **0.645** | 0.604 | -4.1 | RandNE 0.562 | +| PPI | 0.134 | **0.134** | +0.0 | RandNE 0.129 | +| Wikipedia POS | 0.381 | **0.433** | +5.2 | RandNE 0.409 | +| BlogCatalog | 0.260 | 0.324 | +6.4 | FastRP 0.332 | +| Yelp | 0.282 | 0.282 | +0.0 | ProNE 0.284 | +| *mean gain (points)* | | | +1.0 | | + +### `tuned_lp` + +| Dataset | Cleora | Cleora, tuned | gain | Best baseline | +|---|---:|---:|---:|---| +| CiteSeer | **0.458** | **0.458** | +0.0 | NetMF 0.421 | +| Cora | **0.408** | **0.408** | +0.0 | NetMF 0.364 | +| PPI | 0.204 | **0.206** | +0.2 | RandNE 0.183 | +| PubMed | 0.450 | **0.459** | +0.9 | Walklets 0.420 | +| DBLP | 0.540 | **0.541** | +0.2 | RandNE 0.492 | +| Cora-Full | 0.658 | **0.660** | +0.3 | RandNE 0.614 | +| Facebook (ego) | 0.595 | **0.612** | +1.7 | ProNE 0.601 | +| Coauthor CS | 0.637 | **0.662** | +2.5 | RandNE 0.648 | +| Amazon Photo | 0.519 | **0.524** | +0.6 | HOPE 0.456 | +| Wikipedia POS | **0.270** | **0.270** | +0.0 | HOPE 0.242 | +| Amazon Computers | 0.489 | **0.494** | +0.5 | HOPE 0.421 | +| Coauthor Physics | 0.737 | **0.769** | +3.2 | RandNE 0.752 | +| BlogCatalog | **0.222** | **0.222** | +0.0 | HOPE 0.209 | +| Flickr | 0.297 | **0.306** | +1.0 | DeepWalk 0.244 | +| MovieLens-1M | 0.148 | 0.148 | +0.0 | HOPE 0.149 | +| ogbl-ddi | 0.027 | 0.069 | +4.2 | HOPE 0.083 | +| ogbn-arxiv | **0.680** | **0.680** | +0.0 | RandNE 0.606 | +| ogbl-collab | 0.095 | **0.134** | +3.9 | DeepWalk 0.095 | +| roadNet-CA | 0.752 | 0.752 | +0.0 | ProNE 0.778 | +| Yelp | 0.495 | **0.525** | +2.9 | RandNE 0.513 | +| Reddit | 0.605 | **0.747** | +14.3 | ProNE 0.626 | +| MovieLens-20M | 0.237 | **0.256** | +1.9 | ProNE 0.227 | +| ogbl-ppa | **0.065** | **0.065** | +0.0 | FastRP 0.034 | +| ogbl-citation2 | 0.813 | **0.850** | +3.7 | RandNE 0.829 | +| LiveJournal | 0.765 | **0.809** | +4.4 | RandNE 0.776 | +| ogbn-products | 0.912 | **0.916** | +0.4 | RandNE 0.906 | +| *mean gain (points)* | | | +1.8 | | + +## Cleora: the exponents of the popularity prior + +Validation scores of the benchmark's Cleora configurations with `scale_by_popularity(graph, vectors, exponent)`, seed 0, mean over the graphs (`benchmarks/popularity_exponent.py`). `popularity_exponent`: the similarity configuration, dot product; `MRR` against the sampled candidates, `recall@10` among all nodes; *prior or cosine* is the benchmark's rule, under which a graph keeps the unit vectors when they validate better. `popularity_exponent_classification`: the classification configuration, logistic regression. + +### `popularity_exponent` + +| Exponent | Graphs | MRR | recall@10 | MRR, prior or cosine | recall@10, prior or cosine | Graphs that take the prior | +|---:|---:|---:|---:|---:|---:|---:| +| 0 | 21 | 0.4016 | 0.2932 | 0.4016 | 0.2932 | 0 | +| 0.03125 | 21 | 0.4099 | 0.3080 | 0.4123 | 0.3094 | 16 | +| 0.0625 | 21 | **0.4101** | **0.3092** | **0.4149** | **0.3148** | 14 | +| 0.09375 | 21 | 0.4076 | 0.3086 | 0.4145 | 0.3145 | 12 | +| 0.125 | 21 | 0.4051 | 0.3048 | 0.4147 | 0.3139 | 11 | +| 0.1875 | 21 | 0.3977 | 0.2976 | 0.4133 | 0.3113 | 8 | +| 0.25 | 21 | 0.3899 | 0.2885 | 0.4130 | 0.3100 | 7 | +| 0.375 | 21 | 0.3723 | 0.2654 | 0.4109 | 0.3061 | 6 | +| 0.5 | 21 | 0.3543 | 0.2405 | 0.4092 | 0.2991 | 4 | + +### `popularity_exponent_classification` + +| Exponent | Graphs | Validation score | Graphs above the unit vectors | Graphs below | +|---:|---:|---:|---:|---:| +| 0 | 16 | 0.6474 | 0 | 0 | +| 0.03125 | 16 | 0.6492 | 10 | 3 | +| 0.0625 | 16 | 0.6505 | 11 | 4 | +| 0.09375 | 16 | 0.6511 | 11 | 5 | +| 0.125 | 16 | 0.6519 | 10 | 4 | +| 0.1875 | 16 | 0.6529 | 9 | 6 | +| 0.25 | 16 | **0.6536** | 10 | 6 | +| 0.375 | 16 | 0.6527 | 10 | 6 | +| 0.5 | 16 | 0.6520 | 10 | 5 | + +## Number of iterations: automatic rule against the sweep + +`auto`: iterations of `SparseMatrix.suggest_iterations` for the task. `tuned`: best of the sweep on validation. `loss`: points of the metric (x 100) the automatic count is behind the tuned one; negative: it is ahead. + +### `iterations_nc` + +| Dataset | one column, left (auto) | one column, left (tuned) | one column, left (loss) | one column, symmetric (auto) | one column, symmetric (tuned) | one column, symmetric (loss) | two columns, left (auto) | two columns, left (tuned) | two columns, left (loss) | two columns, symmetric (auto) | two columns, symmetric (tuned) | two columns, symmetric (loss) | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | 29 | 64 | +1.3 | 43 | 64 | +0.2 | 14 | 48 | +1.5 | 22 | 64 | +1.7 | +| Cora | 24 | 48 | -0.1 | 36 | 48 | +0.0 | 12 | 12 | +0.0 | 18 | 32 | -0.4 | +| PPI | 11 | 12 | +0.2 | 16 | 12 | -0.1 | 5 | 4 | +0.0 | 8 | 6 | +0.3 | +| PubMed | 23 | 32 | +0.1 | 34 | 64 | +0.9 | 11 | 16 | +0.2 | 17 | 32 | +0.6 | +| DBLP | 20 | 32 | +0.7 | 29 | 64 | +1.8 | 10 | 16 | +0.8 | 15 | 48 | +1.3 | +| Cora-Full | 19 | 16 | -0.1 | 28 | 24 | -0.2 | 9 | 8 | -0.0 | 14 | 12 | -0.2 | +| Coauthor CS | 16 | 24 | +0.2 | 24 | 32 | +0.3 | 8 | 12 | +0.2 | 12 | 16 | +0.2 | +| Amazon Photo | 9 | 8 | -0.1 | 13 | 16 | +0.3 | 4 | 6 | +0.1 | 6 | 8 | +0.2 | +| Wikipedia POS | 8 | 48 | -25.0 | 12 | 32 | +2.1 | 4 | 3 | +1.8 | 6 | 3 | +2.6 | +| Amazon Computers | 8 | 12 | +0.1 | 12 | 24 | +0.5 | 4 | 4 | +0.0 | 6 | 8 | +0.1 | +| Coauthor Physics | 13 | 32 | +0.9 | 19 | 64 | +0.4 | 6 | 16 | +0.8 | 9 | 24 | +0.5 | +| BlogCatalog | 8 | 12 | +3.4 | 9 | 24 | +2.7 | 3 | 4 | +1.8 | 4 | 4 | +0.0 | +| Flickr | 15 | 32 | +0.3 | 23 | 16 | -0.8 | 8 | 16 | +0.1 | 11 | 8 | -0.3 | +| ogbn-arxiv | 13 | 24 | +0.6 | 19 | 48 | +2.6 | 6 | 12 | +0.9 | 10 | 24 | +1.3 | +| Yelp | 11 | 8 | -1.0 | 17 | 16 | -0.2 | 6 | 2 | -0.6 | 8 | 4 | -2.6 | +| Reddit | 8 | 12 | +0.4 | 8 | 24 | +3.3 | 2 | 3 | +0.5 | 2 | 8 | +2.6 | +| ogbn-products | 8 | – | – | 10 | – | – | 3 | – | – | 5 | – | – | +| *mean loss* | | | -1.1 | | | +0.9 | | | +0.5 | | | +0.5 | + +### `iterations_lp` + +| Dataset | one column, left (auto) | one column, left (tuned) | one column, left (loss) | one column, symmetric (auto) | one column, symmetric (tuned) | one column, symmetric (loss) | two columns, left (auto) | two columns, left (tuned) | two columns, left (loss) | two columns, symmetric (auto) | two columns, symmetric (tuned) | two columns, symmetric (loss) | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| CiteSeer | 16 | 8 | +0.5 | 23/24 | 8 | +0.5 | 8 | 6 | -0.1 | 12 | 16 | -0.1 | +| Cora | 14 | 12 | +0.3 | 20 | 16 | +0.1 | 7 | 24 | -1.4 | 10 | 32 | -1.0 | +| PPI | 8 | 8 | +0.0 | 9 | 6 | +0.3 | 3 | 3 | +0.0 | 5 | 3 | +0.6 | +| PubMed | 12 | 12 | +0.0 | 18 | 16 | -0.0 | 6 | 8 | -0.1 | 9 | 16 | -0.2 | +| DBLP | 11 | 8 | +0.3 | 16 | 12 | +0.5 | 5 | 6 | -0.5 | 8 | 6 | +0.1 | +| Cora-Full | 11 | 8 | +0.5 | 16 | 12 | +0.6 | 5 | 4 | -0.2 | 8 | 6 | +0.2 | +| Facebook (ego) | 8 | 6 | +0.7 | 8 | 6 | +1.3 | 2 | 2 | +0.0 | 3 | 2 | +4.7 | +| Coauthor CS | 9 | 6 | +0.9 | 14 | 8 | +2.3 | 5 | 3 | +2.8 | 7 | 4 | +3.0 | +| Amazon Photo | 8 | 6 | +0.2 | 8 | 6 | +1.2 | 2 | 2 | +0.0 | 4 | 2 | +1.7 | +| Wikipedia POS | 8 | 12 | +0.7 | 8 | 8 | +0.0 | 2 | 2 | +0.0 | 3 | 3 | +0.0 | +| Amazon Computers | 8 | 6 | +0.1 | 8 | 6 | +1.0 | 2 | 2 | +0.0 | 3 | 2 | +0.5 | +| Coauthor Physics | 8 | 6 | +1.1 | 11 | 6 | +2.9 | 4 | 2 | +4.0 | 5 | 3 | +3.5 | +| BlogCatalog | 8 | 12 | -0.1 | 8 | 8 | +0.0 | 2 | 2 | +0.0 | 3 | 3 | +0.0 | +| Flickr | 9 | 16 | +0.9 | 13 | 16 | +1.4 | 4 | 8 | +1.1 | 7 | 8 | +0.3 | +| MovieLens-1M | 8 | 12 | +1.2 | 8 | 8 | +0.0 | 2 | 64 | +4.2 | 2 | 64 | +1.8 | +| ogbl-ddi | 8 | 12 | -0.0 | 8 | 8 | +0.0 | 2 | 2 | +0.0 | 2 | 2 | +0.0 | +| ogbn-arxiv | 8 | 8 | +0.0 | 11 | 12 | -0.3 | 4 | 3 | +0.1 | 5 | 4 | +0.1 | +| ogbl-collab | 9 | 16 | -0.1 | 13 | 2 | +0.3 | 4 | 8 | -0.0 | 7 | 2 | +0.1 | +| roadNet-CA | 15 | – | – | 23 | – | – | 8 | – | – | 11 | – | – | +| Yelp | 8 | 8 | +0.0 | 9 | 12 | +0.0 | 3 | 2 | +0.1 | 4 | 4 | +0.0 | +| Reddit | 8 | 8 | +0.0 | 8 | 8 | +0.0 | 2 | 1 | +19.3 | 2 | 1 | +8.5 | +| MovieLens-20M | 8 | – | – | 8 | – | – | 2 | – | – | 2 | – | – | +| ogbl-ppa | 8 | – | – | 8 | – | – | 2 | – | – | 2 | – | – | +| ogbl-citation2 | 8 | – | – | 8 | – | – | 3 | – | – | 4 | – | – | +| LiveJournal | 8 | – | – | 9 | – | – | 3 | – | – | 4 | – | – | +| ogbn-products | 8 | – | – | 8 | – | – | 2 | – | – | 3 | – | – | +| *mean loss* | | | +0.4 | | | +0.6 | | | +1.5 | | | +1.2 | + +## Number of iterations: candidate rules, leave-one-graph-out + +From the iteration sweep (one seed; logistic regression / cosine). Loss: test score at the iteration count that validated best minus test score at the rule's count, in points of the metric (x 100). + +| Rule | Task | Graphs | Curves | Mean loss | Median loss | Worst loss | +|---|---|---:|---:|---:|---:|---:| +| one constant per setup and normalisation | classification | 16 | 64 | 1.36 | 0.46 | 9.18 | +| one constant per setup and normalisation | link ranking | 20 | 80 | 1.80 | 0.26 | 30.68 | +| mixing term only: c / ((1 - s) sqrt(d)) | classification | 16 | 64 | 2.12 | 0.20 | 31.08 | +| mixing term only: c / ((1 - s) sqrt(d)) | link ranking | 20 | 80 | 2.75 | 0.48 | 58.62 | +| mixing term and floors (the form that ships) | classification | 16 | 64 | 0.88 | 0.16 | 8.28 | +| mixing term and floors (the form that ships) | link ranking | 20 | 80 | 1.11 | 0.18 | 19.34 | + +- *one constant per setup and normalisation*, fitted on all graphs: link ranking, hyperedge/left: 8; link ranking, hyperedge/sym: 8; link ranking, pair/left: 2; link ranking, pair/sym: 3; classification, hyperedge/left: 16; classification, hyperedge/sym: 32; classification, pair/left: 8; classification, pair/sym: 12 +- *mixing term only: c / ((1 - s) sqrt(d))*, fitted on all graphs: c = 12 (link ranking), c = 40 (classification), symmetric x1.5 +- *mixing term and floors (the form that ships)*, fitted on all graphs: c = 10 (link ranking), c = 40 (classification), symmetric x1.5, remainder 1/256, minimum 1 + +## Number of iterations: loss as a function of the constant c + +The form that ships, on all graphs of the sweep, for every candidate value of `c`. + +| c | classification: mean | median | worst | link ranking: mean | median | worst | +|---:|---:|---:|---:|---:|---:|---:| +| 6 | 7.21 | 5.77 | 31.07 | 1.37 | 0.35 | 18.76 | +| 8 | 5.17 | 4.00 | 20.66 | 0.66 | 0.15 | 5.41 | +| 10 | 3.66 | 2.79 | 20.66 | 0.61 | 0.13 | 4.86 | +| 12 | 2.93 | 1.92 | 20.66 | 0.70 | 0.12 | 4.86 | +| 14 | 2.20 | 1.39 | 20.66 | 0.96 | 0.41 | 8.19 | +| 16 | 1.87 | 0.99 | 20.66 | 1.40 | 0.60 | 8.19 | +| 20 | 1.41 | 0.65 | 20.66 | 2.32 | 1.54 | 11.03 | +| 24 | 0.96 | 0.41 | 12.07 | 3.39 | 2.60 | 14.16 | +| 28 | 0.98 | 0.35 | 12.07 | 4.34 | 3.59 | 16.98 | +| 32 | 0.94 | 0.26 | 12.07 | 5.23 | 4.70 | 19.59 | +| 40 | 0.84 | 0.16 | 8.28 | 7.20 | 6.33 | 23.28 | +| 48 | 1.03 | 0.17 | 9.05 | 8.67 | 8.20 | 27.56 | + +## Embedding time + +Median of three runs on an idle machine, whole graph, 1024 dimensions. + +| Dataset | Cleora | pycleora 3.2 default | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| Cora | **81 ms** | 27.9 s | 5.7 s | 7.1 s | 7.0 s | 2.1 min | 8.2 s | 2.2 s | 2.7 s | 718 ms | 705 ms | +| PubMed | **198 ms** | 29.8 s | 44.2 s | 46.1 s | 57.0 s | 8.2 min | 2.9 min | 14.4 s | 16.3 s | 1.8 s | 1.2 s | +| Amazon Computers | **163 ms** | 25.7 s | 25.9 s | 30.1 s | 60.9 s | 5.3 min | 6.7 min | 2.4 min | 18.3 s | 2.5 s | 1.7 s | +| Flickr | **618 ms** | 62.9 s | 10.0 min | 10.1 min | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 82.6 s | 7.7 s | 5.0 s | +| ogbn-arxiv | **1.4 s** | 1.8 min | 17.4 min | 18.1 min | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 2.9 min | 13.1 s | 10.0 s | +| Yelp | **7.8 s** | 4.2 min | 97.1 min | 99.8 min | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 13.1 min | 67.7 s | 53.6 s | + +## Peak memory + +Peak resident memory of the embedding process, interpreter and libraries included. + +| Dataset | Cleora | pycleora 3.2 default | DeepWalk | node2vec | Walklets | NetMF | GraRep | HOPE | ProNE | FastRP | RandNE | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| Cora | **0.06 GB** | 0.37 GB | 0.26 GB | 0.28 GB | 0.39 GB | 0.27 GB | 0.26 GB | 0.17 GB | 0.45 GB | 0.40 GB | 0.26 GB | +| PubMed | **0.20 GB** | 0.46 GB | 0.61 GB | 0.64 GB | 2.02 GB | 3.90 GB | 4.73 GB | 0.41 GB | 1.53 GB | 1.87 GB | 1.04 GB | +| Amazon Computers | **0.16 GB** | 0.44 GB | 0.49 GB | 0.50 GB | 1.47 GB | 2.07 GB | 9.79 GB | 0.98 GB | 1.15 GB | 1.38 GB | 0.76 GB | +| Flickr | **0.77 GB** | 1.02 GB | 2.01 GB | 2.03 GB | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 6.10 GB | 7.89 GB | 4.24 GB | +| ogbn-arxiv | **1.43 GB** | 1.65 GB | 3.59 GB | 3.61 GB | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 11.39 GB | 14.84 GB | 7.94 GB | +| Yelp | **6.05 GB** | 6.21 GB | 14.65 GB | 14.66 GB | n/a (size) | n/a (size) | n/a (size) | n/a (size) | 46.35 GB | 62.28 GB | 33.21 GB | diff --git a/benchmarks/cleora_bench/__init__.py b/benchmarks/cleora_bench/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/benchmarks/cleora_bench/configurations.py b/benchmarks/cleora_bench/configurations.py new file mode 100644 index 0000000..b2c9e37 --- /dev/null +++ b/benchmarks/cleora_bench/configurations.py @@ -0,0 +1,94 @@ +"""Named method configurations: what a row of a results table is. + +Concern of this module: the mapping from a configuration name to an implementation in +:mod:`methods` and its parameters. Baselines run with the settings their authors +recommend (see the notes in :mod:`methods`); nothing here is tuned on test data. +""" + +# name -> (method in methods.METHODS, parameters) +CONFIGURATIONS = { + "deepwalk": ("deepwalk", {}), + "node2vec": ("node2vec", {}), + "prone": ("prone", {}), + "netmf": ("netmf", {}), + "fastrp": ("fastrp", {}), + "randne": ("randne", {}), + "grarep": ("grarep", {}), + "hope": ("hope", {}), + "walklets": ("walklets", {}), + "cleora_whiten40": ("cleora_whiten40", {}), +} + +# Cleora with a fixed number of iterations: the sweep behind the iteration heuristic and +# the "iterations chosen on validation" rows. A homogeneous graph can be given to Cleora +# in two ways, and both are benchmarked: +# +# hyperedge one column, "complex::reflexive::node": every edge is a two-node hyperedge. +# The column is related to itself, so every node is also its own neighbour +# (a lazy random walk). +# pair two columns, "src dst": the plain adjacency matrix, without self-loops. +SWEEP_ITERATIONS = (1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64) +SETUPS = {"hyperedge": "complex::reflexive::node", "pair": "src dst"} +# What a Cleora configuration is called by the use of its vectors. "general" is what embed() +# does by default; for the other two the README recommends more than an iteration count. +PURPOSES = {"general": "auto", "similarity": "sim", "classification": "cls"} +# That "more": the exponent of pycleora.scale_by_popularity, by purpose - the ones that +# validated best (benchmarks/README.md, "The popularity prior"). +EXTRAS = {"similarity": {"popularity": 0.0625}, "classification": {"popularity": 0.25}} +for _setup, _columns in SETUPS.items(): + for _propagation, _tag in (("left", "left"), ("symmetric", "sym")): + for _iterations in SWEEP_ITERATIONS: + # the hyperedge names predate the pair setup and stay as they were + _name = f"cleora_{_tag}_k{_iterations}" if _setup == "hyperedge" else f"cleora_pair_{_tag}_k{_iterations}" + _parameters = {"iterations": _iterations, "propagation": _propagation, "columns": _columns} + CONFIGURATIONS[_name] = ("cleora_classic", _parameters) + for _purpose, _extras in EXTRAS.items(): + CONFIGURATIONS[f"{_name}_{PURPOSES[_purpose]}"] = ("cleora_classic", {**_parameters, **_extras}) + + +# The library's own choice of the number of iterations (SparseMatrix.suggest_iterations): +# nothing is chosen per dataset. +AUTO = {} # (setup, propagation, purpose) -> configuration name +for _setup, _columns in SETUPS.items(): + for _propagation, _tag in (("left", "left"), ("symmetric", "sym")): + for _purpose, _suffix in PURPOSES.items(): + _name = f"cleora_{_tag}_{_suffix}" if _setup == "hyperedge" else f"cleora_pair_{_tag}_{_suffix}" + CONFIGURATIONS[_name] = ("cleora_classic", { + "iterations": "auto", "purpose": _purpose, "propagation": _propagation, "columns": _columns, + **EXTRAS.get(_purpose, {})}) + AUTO[(_setup, _propagation, _purpose)] = _name + + +def automatic(purpose): + """Names of the four automatic configurations (setup x normalisation) of a purpose.""" + return [name for (_, _, p), name in AUTO.items() if p == purpose] + + +def sweep(setup, propagation=None): + """Names of the fixed-iteration Cleora configurations of one setup.""" + prefix = "cleora_" if setup == "hyperedge" else "cleora_pair_" + tags = ("left", "sym") if propagation is None else (propagation,) + return [f"{prefix}{tag}_k{k}" for tag in tags for k in SWEEP_ITERATIONS] + + +def for_purpose(name, purpose): + """The fixed-iteration configuration ``name`` of the sweep as it is run for a purpose: + with the ``EXTRAS`` of that purpose.""" + return f"{name}_{PURPOSES[purpose]}" if purpose in EXTRAS else name + + +def iterations(name): + """The iteration count of a fixed-iteration configuration.""" + return CONFIGURATIONS[name][1]["iterations"] + + +CONFIGURATIONS["deepwalk_e5"] = ("deepwalk", {"epochs": 5}) + + +DEFAULT = ("deepwalk", "node2vec", "prone", "netmf", "fastrp", "randne", "grarep", "hope", "walklets") + + +def resolve(name): + if name not in CONFIGURATIONS: + raise KeyError(f"Unknown configuration '{name}'. Known: {', '.join(sorted(CONFIGURATIONS))}") + return CONFIGURATIONS[name] diff --git a/benchmarks/cleora_bench/datasets.py b/benchmarks/cleora_bench/datasets.py new file mode 100644 index 0000000..f004cb0 --- /dev/null +++ b/benchmarks/cleora_bench/datasets.py @@ -0,0 +1,468 @@ +"""Benchmark datasets: fetched from their original public sources, stored in one canonical form. + +Concern of this module: turning a dataset *name* into a canonical graph on disk. +Nothing here knows about embedding methods, probes or metrics. + +Canonical form (``//graph.npz`` + ``meta.json``) +------------------------------------------------------------ +``edges`` int64 [E, 2] undirected, ``u < v``, unique, no self-loops. Node ids are + ``0..N-1`` and every node has at least one edge. +``weights`` float32 [E] only for graphs whose source carries edge weights. +``labels`` int64 [N] single-label graphs, ``-1`` = unlabelled; or + bool [N, C] multi-label graphs. Absent when the dataset has no node labels: + such graphs support the link/similarity tasks only. +``split_train`` / ``split_valid`` / ``split_test`` + int64 [*] official node split, when the dataset defines one. +``lp_*`` official link-prediction split, when the dataset defines one + (OGB link datasets): ``lp_valid_pos``, ``lp_valid_neg``, + ``lp_test_pos``, ``lp_test_neg`` (int64 [*, 2]) or, for + ogbl-citation2, ``lp_{valid,test}_{source,target,target_neg}``. + ``edges`` then holds the official *training* edges only. +``num_left`` int64 scalar bipartite graphs: nodes ``0..num_left-1`` are the left side + (users), the others the right side (items). + +Nodes without any edge cannot be embedded from structure, so they are removed (and the ids +compacted) for every method alike; ``meta.json`` records how many were dropped. + +The loaders use PyTorch Geometric and OGB where those libraries ship the dataset, and the +original files otherwise. Every source URL is recorded in ``meta.json``. +""" + +import contextlib +import hashlib +import io +import json +import os +import urllib.request +import zipfile + +import numpy as np + +# name -> (loader function, keyword arguments, tier, one-line description) +# tier: "S" up to about a million edges (three seeds), "M" up to about 60 million and +# "L" millions of nodes (one seed each). Methods that need dense n x n matrices are +# limited by the number of nodes (see methods.METHODS), whatever the tier. +REGISTRY = {} + + +def _register(name, tier, description, **kwargs): + def decorate(loader): + REGISTRY[name] = (loader, kwargs, tier, description) + return loader + return decorate + + +# Size of every canonical graph (nodes with an edge, undirected edges). A source that +# starts serving different data is noticed when the dataset is prepared. +EXPECTED_SIZE = { + "cora": (2708, 5278), "citeseer": (3279, 4552), "pubmed": (19717, 44324), "cora_full": (19793, 63421), + "dblp": (17716, 52867), "amazon_photo": (7535, 119081), "amazon_computers": (13471, 245861), + "coauthor_cs": (18333, 81894), "coauthor_physics": (34493, 247962), "ppi": (3860, 37845), + "wikipedia_pos": (4777, 92295), "blogcatalog": (10312, 333983), "facebook": (4039, 88234), + "flickr": (89250, 449878), "yelp": (716847, 6618986), "reddit": (232965, 57307946), + "ogbn_arxiv": (169343, 1157799), "ogbn_products": (2400608, 61859012), "ogbl_collab": (235868, 967632), + "ogbl_ddi": (4267, 1067911), "ogbl_ppa": (576289, 21231931), "ogbl_citation2": (2926620, 30351880), + "roadnet_ca": (1965206, 2766607), "livejournal": (3997962, 34681189), "movielens_1m": (9746, 1000209), + "movielens_20m": (165237, 20000263), +} + + +# ----------------------------------------------------------------------------- helpers + + +def _download(url, path): + """Downloads ``url`` to ``path`` (atomically) unless it is already there.""" + if os.path.exists(path): + return path + os.makedirs(os.path.dirname(path), exist_ok=True) + request = urllib.request.Request(url, headers={"User-Agent": "cleora-bench"}) + with urllib.request.urlopen(request, timeout=600) as response, open(path + ".part", "wb") as out: + while True: + block = response.read(1 << 20) + if not block: + break + out.write(block) + os.replace(path + ".part", path) + return path + + +def _sha256(path): + digest = hashlib.sha256() + with open(path, "rb") as handle: + for block in iter(lambda: handle.read(1 << 20), b""): + digest.update(block) + return digest.hexdigest() + + +@contextlib.contextmanager +def _legacy_torch_load(): + """OGB 1.3.6 caches its processed files with pickle and reads them back with + ``torch.load``; PyTorch >= 2.6 refuses that unless ``weights_only=False``. The files are + written by OGB itself from the downloaded csv files, a few lines earlier.""" + import torch + + original = torch.load + + def load(*args, **kwargs): + kwargs.setdefault("weights_only", False) + return original(*args, **kwargs) + + torch.load = load + try: + yield + finally: + torch.load = original + + +def canonical_edges(src, dst, weights=None): + """Undirected, unique, self-loop-free edge list with ``u < v``, sorted. + + Duplicate edges (including the two directions of one edge) are merged; with weights + their *maximum* is kept, so a symmetric weighted matrix keeps its weights unchanged. + """ + src = np.asarray(src, dtype=np.int64) + dst = np.asarray(dst, dtype=np.int64) + keep = src != dst + low = np.minimum(src[keep], dst[keep]) + high = np.maximum(src[keep], dst[keep]) + order = np.lexsort((high, low)) + low, high = low[order], high[order] + first = np.ones(len(low), dtype=bool) + first[1:] = (low[1:] != low[:-1]) | (high[1:] != high[:-1]) + edges = np.stack([low[first], high[first]], axis=1) + if weights is None: + return edges, None + weights = np.asarray(weights, dtype=np.float64)[keep][order] + group = np.cumsum(first) - 1 + merged = np.full(len(edges), -np.inf) + np.maximum.at(merged, group, weights) + return edges, merged.astype(np.float32) + + +def _compact(graph): + """Drops nodes without edges and renumbers the rest ``0..N-1`` (order preserved).""" + edges = graph["edges"] + num_original = int(graph.pop("num_nodes")) + present = np.zeros(num_original, dtype=bool) + present[edges.ravel()] = True + new_id = np.cumsum(present) - 1 + new_id[~present] = -1 + graph["edges"] = new_id[edges] + if "labels" in graph: + graph["labels"] = graph["labels"][present] + for key in ("split_train", "split_valid", "split_test"): + if key in graph: + mapped = new_id[graph[key]] + graph[key] = mapped[mapped >= 0] + # Official link splits. A node without a training edge has no embedding to rank with: + # positive and negative pairs that touch one are dropped (the counts go to meta.json). + dropped = {} + for part in ("valid", "test"): + if f"lp_{part}_pos" not in graph: + continue + positives = new_id[graph[f"lp_{part}_pos"]] + keep = (positives >= 0).all(axis=1) + graph[f"lp_{part}_pos"] = positives[keep] + dropped[f"{part}_pos"] = int((~keep).sum()) + if f"lp_{part}_neg" in graph: # one shared list of negative pairs + negatives = new_id[graph[f"lp_{part}_neg"]] + keep_negative = (negatives >= 0).all(axis=1) + graph[f"lp_{part}_neg"] = negatives[keep_negative] + dropped[f"{part}_neg"] = int((~keep_negative).sum()) + if f"lp_{part}_target_neg" in graph: # negatives per positive, row-aligned; -1 = absent + graph[f"lp_{part}_target_neg"] = new_id[graph[f"lp_{part}_target_neg"]][keep] + if "num_left" in graph: + graph["num_left"] = np.int64(present[: int(graph["num_left"])].sum()) + return graph, num_original, int(present.sum()), dropped + + +def _from_pyg(data): + edge_index = data.edge_index.numpy() + return edge_index[0], edge_index[1], int(data.num_nodes) + + +def _mask_split(data): + return { + "split_train": np.flatnonzero(data.train_mask.numpy()), + "split_valid": np.flatnonzero(data.val_mask.numpy()), + "split_test": np.flatnonzero(data.test_mask.numpy()), + } + + +# ----------------------------------------------------------------------------- loaders + + +@_register("cora", "S", "Planetoid citation graph, 7 classes", pyg="Cora") +@_register("citeseer", "S", "Planetoid citation graph, 6 classes", pyg="CiteSeer") +@_register("pubmed", "S", "Planetoid citation graph, 3 classes", pyg="PubMed") +def _planetoid(raw, pyg): + from torch_geometric.datasets import Planetoid + + data = Planetoid(os.path.join(raw, "planetoid"), pyg)[0] + src, dst, n = _from_pyg(data) + # The fixed 20-labels-per-class Planetoid split is made for feature-based GNNs; for + # structure-only embeddings the benchmark draws its own stratified splits. + return {"src": src, "dst": dst, "num_nodes": n, "labels": data.y.numpy().astype(np.int64), + "source": f"torch_geometric.datasets.Planetoid('{pyg}')", + "citation": "Yang, Cohen, Salakhutdinov, ICML 2016; Sen et al., AI Magazine 2008"} + + +@_register("cora_full", "S", "Full Cora citation graph, 70 classes", pyg="Cora") +@_register("dblp", "S", "DBLP citation graph, 4 classes", pyg="DBLP") +def _citation_full(raw, pyg): + from torch_geometric.datasets import CitationFull + + data = CitationFull(os.path.join(raw, "citation_full"), pyg)[0] + src, dst, n = _from_pyg(data) + return {"src": src, "dst": dst, "num_nodes": n, "labels": data.y.numpy().astype(np.int64), + "source": f"torch_geometric.datasets.CitationFull('{pyg}')", + "citation": "Bojchevski and Günnemann, ICLR 2018"} + + +@_register("amazon_photo", "S", "Amazon co-purchase graph, 8 classes", pyg="Photo") +@_register("amazon_computers", "S", "Amazon co-purchase graph, 10 classes", pyg="Computers") +def _amazon(raw, pyg): + from torch_geometric.datasets import Amazon + + data = Amazon(os.path.join(raw, "amazon"), pyg)[0] + src, dst, n = _from_pyg(data) + return {"src": src, "dst": dst, "num_nodes": n, "labels": data.y.numpy().astype(np.int64), + "source": f"torch_geometric.datasets.Amazon('{pyg}')", + "citation": "Shchur et al., Pitfalls of GNN Evaluation, 2018; McAuley et al., SIGIR 2015"} + + +@_register("coauthor_cs", "S", "Co-authorship graph (MAG), 15 classes", pyg="CS") +@_register("coauthor_physics", "S", "Co-authorship graph (MAG), 5 classes", pyg="Physics") +def _coauthor(raw, pyg): + from torch_geometric.datasets import Coauthor + + data = Coauthor(os.path.join(raw, "coauthor"), pyg)[0] + src, dst, n = _from_pyg(data) + return {"src": src, "dst": dst, "num_nodes": n, "labels": data.y.numpy().astype(np.int64), + "source": f"torch_geometric.datasets.Coauthor('{pyg}')", + "citation": "Shchur et al., Pitfalls of GNN Evaluation, 2018"} + + +@_register("ppi", "S", "Protein interactions (node2vec version), 50 labels, multi-label", + url="https://snap.stanford.edu/node2vec/Homo_sapiens.mat", + citation="Grover and Leskovec, node2vec, KDD 2016") +@_register("wikipedia_pos", "S", "Word co-occurrence (node2vec version), 40 labels, multi-label, weighted", + url="https://snap.stanford.edu/node2vec/POS.mat", + citation="Grover and Leskovec, node2vec, KDD 2016") +@_register("blogcatalog", "S", "BlogCatalog social graph (DeepWalk version), 39 labels, multi-label", + url="https://github.com/phanein/deepwalk/raw/master/example_graphs/blogcatalog.mat", + citation="Tang and Liu, KDD 2009; Perozzi et al., DeepWalk, KDD 2014") +def _matlab_network(raw, url, citation): + import scipy.io + import scipy.sparse + + path = _download(url, os.path.join(raw, "mat", os.path.basename(url))) + content = scipy.io.loadmat(path) + network = scipy.sparse.coo_matrix(content["network"]) + labels = np.asarray(scipy.sparse.csr_matrix(content["group"]).todense()) > 0 + graph = {"src": network.row, "dst": network.col, "num_nodes": network.shape[0], "labels": labels, + "source": url, "citation": citation, "sha256": _sha256(path)} + if not np.all(network.data == network.data[0]): + graph["weights"] = network.data + return graph + + +@_register("flickr", "S", "Flickr image graph (GraphSAINT), 7 classes, official split") +def _flickr(raw): + from torch_geometric.datasets import Flickr + + data = Flickr(os.path.join(raw, "flickr"))[0] + src, dst, n = _from_pyg(data) + return {"src": src, "dst": dst, "num_nodes": n, "labels": data.y.numpy().astype(np.int64), + **_mask_split(data), "source": "torch_geometric.datasets.Flickr", + "citation": "Zeng et al., GraphSAINT, ICLR 2020"} + + +@_register("yelp", "M", "Yelp friendship graph (GraphSAINT), 100 labels, multi-label, official split") +def _yelp(raw): + from torch_geometric.datasets import Yelp + + data = Yelp(os.path.join(raw, "yelp"))[0] + src, dst, n = _from_pyg(data) + return {"src": src, "dst": dst, "num_nodes": n, "labels": data.y.numpy() > 0, + **_mask_split(data), "source": "torch_geometric.datasets.Yelp", + "citation": "Zeng et al., GraphSAINT, ICLR 2020"} + + +@_register("reddit", "M", "Reddit post graph (GraphSAGE), 41 classes, official split") +def _reddit(raw): + from torch_geometric.datasets import Reddit + + # PyTorch Geometric fetches https://data.dgl.ai/dataset/reddit.zip; the same archive + # is served by the bucket behind that name, which is reachable where the alias is not. + root = os.path.join(raw, "reddit") + raw_files = [os.path.join(root, "raw", name) for name in ("reddit_data.npz", "reddit_graph.npz")] + if not all(os.path.exists(path) for path in raw_files): + archive = _download("https://dgl-data.s3-accelerate.amazonaws.com/dataset/reddit.zip", + os.path.join(root, "raw", "reddit.zip")) + with zipfile.ZipFile(archive) as content: + content.extractall(os.path.join(root, "raw")) + data = Reddit(root)[0] + src, dst, n = _from_pyg(data) + return {"src": src, "dst": dst, "num_nodes": n, "labels": data.y.numpy().astype(np.int64), + **_mask_split(data), "source": "torch_geometric.datasets.Reddit", + "citation": "Hamilton, Ying, Leskovec, GraphSAGE, NeurIPS 2017"} + + +@_register("ogbn_arxiv", "S", "OGB arXiv citation graph, 40 classes, official (time) split", ogb="ogbn-arxiv") +@_register("ogbn_products", "L", "OGB Amazon co-purchase graph, 47 classes, official split", ogb="ogbn-products") +def _ogb_node(raw, ogb): + from ogb.nodeproppred import NodePropPredDataset + + with _legacy_torch_load(): + dataset = NodePropPredDataset(ogb, root=os.path.join(raw, "ogb")) + split = dataset.get_idx_split() + graph, labels = dataset[0] + return {"src": graph["edge_index"][0], "dst": graph["edge_index"][1], "num_nodes": int(graph["num_nodes"]), + "labels": labels.reshape(-1).astype(np.int64), + "split_train": split["train"], "split_valid": split["valid"], "split_test": split["test"], + "source": f"ogb.nodeproppred.NodePropPredDataset('{ogb}')", + "citation": "Hu et al., Open Graph Benchmark, NeurIPS 2020"} + + +@_register("ogbl_collab", "S", "OGB author collaboration graph, official (time) link split, Hits@50", ogb="ogbl-collab") +@_register("ogbl_ddi", "S", "OGB drug-drug interaction graph, official link split, Hits@20", ogb="ogbl-ddi") +@_register("ogbl_ppa", "M", "OGB protein association graph, official link split, Hits@100", ogb="ogbl-ppa") +@_register("ogbl_citation2", "L", "OGB citation graph, official link split, MRR", ogb="ogbl-citation2") +def _ogb_link(raw, ogb): + from ogb.linkproppred import LinkPropPredDataset + + with _legacy_torch_load(): + dataset = LinkPropPredDataset(ogb, root=os.path.join(raw, "ogb")) + split = dataset.get_edge_split() + num_nodes = int(dataset[0]["num_nodes"]) + result = {"num_nodes": num_nodes, "source": f"ogb.linkproppred.LinkPropPredDataset('{ogb}')", + "citation": "Hu et al., Open Graph Benchmark, NeurIPS 2020"} + if "edge" in split["train"]: + train = np.asarray(split["train"]["edge"]) + result.update(src=train[:, 0], dst=train[:, 1]) + for part in ("valid", "test"): + result[f"lp_{part}_pos"] = np.asarray(split[part]["edge"], dtype=np.int64) + result[f"lp_{part}_neg"] = np.asarray(split[part]["edge_neg"], dtype=np.int64) + else: # ogbl-citation2: one positive target and 1000 negative targets per source node + result.update(src=np.asarray(split["train"]["source_node"]), dst=np.asarray(split["train"]["target_node"])) + for part in ("valid", "test"): + source = np.asarray(split[part]["source_node"], dtype=np.int64) + target = np.asarray(split[part]["target_node"], dtype=np.int64) + negatives = np.asarray(split[part]["target_node_neg"], dtype=np.int64) + result[f"lp_{part}_pos"] = np.stack([source, target], axis=1) + result[f"lp_{part}_target_neg"] = negatives + return result + + +@_register("facebook", "S", "Facebook ego networks (SNAP), no labels", + url="https://snap.stanford.edu/data/facebook_combined.txt.gz", separator=" ", + citation="McAuley and Leskovec, NeurIPS 2012") +@_register("roadnet_ca", "L", "California road network (SNAP), no labels", + url="https://snap.stanford.edu/data/roadNet-CA.txt.gz", separator="\t", + citation="Leskovec et al., Internet Mathematics 2009") +@_register("livejournal", "L", "LiveJournal friendship graph (SNAP com-lj), no labels used", + url="https://snap.stanford.edu/data/bigdata/communities/com-lj.ungraph.txt.gz", separator="\t", + citation="Yang and Leskovec, ICDM 2012") +def _snap_edge_list(raw, url, separator, citation): + import pandas + + path = _download(url, os.path.join(raw, "snap", os.path.basename(url))) + pairs = pandas.read_csv(path, sep=separator, comment="#", header=None, dtype=np.int64).to_numpy() + # SNAP node ids are arbitrary integers: renumber them densely, in sorted order + ids, inverse = np.unique(pairs, return_inverse=True) + inverse = inverse.reshape(pairs.shape) + return {"src": inverse[:, 0], "dst": inverse[:, 1], "num_nodes": len(ids), + "source": url, "citation": citation, "sha256": _sha256(path)} + + +@_register("movielens_1m", "S", "MovieLens-1M user-movie ratings as a bipartite graph, no labels", + url="https://files.grouplens.org/datasets/movielens/ml-1m.zip", member="ml-1m/ratings.dat", separator="::") +@_register("movielens_20m", "L", "MovieLens-20M user-movie ratings as a bipartite graph, no labels", + url="https://files.grouplens.org/datasets/movielens/ml-20m.zip", member="ml-20m/ratings.csv", separator=",") +def _movielens(raw, url, member, separator): + import pandas + + path = _download(url, os.path.join(raw, "movielens", os.path.basename(url))) + with zipfile.ZipFile(path) as archive: + content = io.BytesIO(archive.read(member)) + header = 0 if member.endswith(".csv") else None + table = pandas.read_csv(content, sep=separator, header=header, engine="python" if len(separator) > 1 else "c", + usecols=[0, 1]).to_numpy(dtype=np.int64) + # every rating is one user-movie interaction (implicit feedback); users first, then movies + users, user_index = np.unique(table[:, 0], return_inverse=True) + movies, movie_index = np.unique(table[:, 1], return_inverse=True) + return {"src": user_index, "dst": movie_index + len(users), "num_nodes": len(users) + len(movies), + "num_left": np.int64(len(users)), "source": url, "sha256": _sha256(path), + "citation": "Harper and Konstan, The MovieLens Datasets, ACM TiiS 2015"} + + +# ----------------------------------------------------------------------------- public API + + +def prepare(name, root): + """Builds the canonical files of dataset ``name`` under ``root`` (no-op if present).""" + if name not in REGISTRY: + raise KeyError(f"Unknown dataset '{name}'. Known: {', '.join(sorted(REGISTRY))}") + directory = os.path.join(root, name) + graph_path = os.path.join(directory, "graph.npz") + if os.path.exists(graph_path): + return directory + loader, kwargs, tier, description = REGISTRY[name] + loaded = loader(os.path.join(root, "_raw"), **kwargs) + + meta = {"name": name, "tier": tier, "description": description} + for key in ("source", "citation", "sha256"): + if key in loaded: + meta[key] = loaded.pop(key) + src, dst = loaded.pop("src"), loaded.pop("dst") + edges, weights = canonical_edges(src, dst, loaded.pop("weights", None)) + graph = dict(loaded, edges=edges) + graph, num_original, num_nodes, dropped_pairs = _compact(graph) + if weights is not None: + graph["weights"] = weights + + meta.update(num_nodes=num_nodes, num_edges=int(len(graph["edges"])), + nodes_without_edges_dropped=num_original - num_nodes, + official_link_pairs_dropped=dropped_pairs, + weighted=weights is not None, bipartite="num_left" in graph, + official_node_split="split_train" in graph, + official_link_split=any(k.startswith("lp_") for k in graph)) + size = (meta["num_nodes"], meta["num_edges"]) + if size != EXPECTED_SIZE[name]: + raise RuntimeError(f"{name}: the source now yields {size[0]} nodes and {size[1]} edges, the benchmark was " + f"run on {EXPECTED_SIZE[name][0]} and {EXPECTED_SIZE[name][1]}. Results would not be comparable.") + if "labels" in graph: + labels = graph["labels"] + meta["multilabel"] = labels.ndim == 2 + meta["num_classes"] = int(labels.shape[1]) if labels.ndim == 2 else int(labels.max()) + 1 + meta["num_labelled"] = int(labels.any(axis=1).sum()) if labels.ndim == 2 else int((labels >= 0).sum()) + else: + meta["num_classes"] = 0 # no node labels: link / similarity tasks only + + os.makedirs(directory, exist_ok=True) + np.savez(graph_path + ".tmp.npz", **graph) + os.replace(graph_path + ".tmp.npz", graph_path) + with open(os.path.join(directory, "meta.json"), "w") as handle: + json.dump(meta, handle, indent=1) + return directory + + +def load(name, root): + """Canonical arrays of a dataset (prepared on first use) plus its ``meta`` dictionary.""" + directory = prepare(name, root) + with np.load(os.path.join(directory, "graph.npz")) as archive: + graph = {key: archive[key] for key in archive.files} + with open(os.path.join(directory, "meta.json")) as handle: + graph["meta"] = json.load(handle) + return graph + + +def meta(name, root): + """The ``meta`` dictionary of a prepared dataset, without loading its arrays.""" + with open(os.path.join(root, name, "meta.json")) as handle: + return json.load(handle) + + +def names(tiers="SML"): + return [name for name, (_, _, tier, _) in REGISTRY.items() if tier in tiers] diff --git a/benchmarks/cleora_bench/display.py b/benchmarks/cleora_bench/display.py new file mode 100644 index 0000000..92c2f7c --- /dev/null +++ b/benchmarks/cleora_bench/display.py @@ -0,0 +1,104 @@ +"""What the tables and figures show, and under which names. + +Concern of this module: the rows (datasets), the columns (methods), the measurements +and their labels. It holds no numbers and computes none. + +Every column of the main tables is one configuration at ``MAIN_DIM`` dimensions - the +same for every graph, never chosen per dataset: + +- a baseline: its authors' settings; +- ``cleora`` / ``cleora_pair``: the graph as one reflexive column / as two columns, with + the number of iterations the library suggests for the task (``TASK_PURPOSE``) and the + normalisation the README recommends for it (``TASK_PROPAGATION``). + +``cleora_tuned`` is not a column of the main tables: it is what choosing the iteration +count and the family on validation data adds, shown in tables of its own. +""" + +from . import configurations + +MAIN_DIM = 1024 + +DATASET_LABELS = { + "cora": "Cora", "citeseer": "CiteSeer", "pubmed": "PubMed", "cora_full": "Cora-Full", "dblp": "DBLP", + "amazon_photo": "Amazon Photo", "amazon_computers": "Amazon Computers", "coauthor_cs": "Coauthor CS", + "coauthor_physics": "Coauthor Physics", "ppi": "PPI", "wikipedia_pos": "Wikipedia POS", + "blogcatalog": "BlogCatalog", "facebook": "Facebook (ego)", "flickr": "Flickr", "yelp": "Yelp", "reddit": "Reddit", + "ogbn_arxiv": "ogbn-arxiv", "ogbn_products": "ogbn-products", "ogbl_collab": "ogbl-collab", "ogbl_ddi": "ogbl-ddi", + "ogbl_ppa": "ogbl-ppa", "ogbl_citation2": "ogbl-citation2", "livejournal": "LiveJournal", + "roadnet_ca": "roadNet-CA", "movielens_1m": "MovieLens-1M", "movielens_20m": "MovieLens-20M", +} +# order of the rows: by number of edges +DATASET_ORDER = ( + "citeseer", "cora", "ppi", "pubmed", "dblp", "cora_full", "facebook", "coauthor_cs", "amazon_photo", + "wikipedia_pos", "amazon_computers", "coauthor_physics", "blogcatalog", "flickr", "movielens_1m", "ogbl_ddi", + "ogbn_arxiv", "ogbl_collab", "roadnet_ca", "yelp", "reddit", "movielens_20m", "ogbl_ppa", "ogbl_citation2", + "livejournal", "ogbn_products", +) + +# what SparseMatrix.suggest_iterations is asked for, by task +TASK_PURPOSE = {"nc": "classification", "lp": "similarity"} +# The normalisation by task, for every graph alike. It is the one with the better mean +# validation score over the graphs (table "families_validation"); test scores had no say. +TASK_PROPAGATION = {"nc": "left", "lp": "symmetric"} + + +def cleora_configuration(setup, task): + """The one Cleora configuration of a setup ("hyperedge" or "pair") for a task.""" + return configurations.AUTO[(setup, TASK_PROPAGATION[task], TASK_PURPOSE[task])] + + +_BASELINES = ( + ("deepwalk", "DeepWalk"), ("node2vec", "node2vec"), ("walklets", "Walklets"), ("netmf", "NetMF"), + ("grarep", "GraRep"), ("hope", "HOPE"), ("prone", "ProNE"), ("fastrp", "FastRP"), ("randne", "RandNE"), +) +BASELINES = tuple(name for name, _ in _BASELINES) + +# key -> label, and for the methods whose configuration does not depend on the task, its name +METHODS = { + "cleora": {"label": "Cleora", "setup": "hyperedge"}, + "cleora_pair": {"label": "Cleora, two columns", "setup": "pair"}, + "cleora_tuned": {"label": "Cleora, tuned"}, + "cleora_3_2": {"label": "pycleora 3.2 default", "configuration": "cleora_whiten40"}, +} +for _name, _label in _BASELINES: + METHODS[_name] = {"label": _label, "configuration": _name} + +MAIN_COLUMNS = ("cleora", "cleora_pair") + BASELINES +# columns that are the same method fed differently: they are not ranked against each other +SAME_METHOD = ("cleora", "cleora_pair") + +# the four ways of feeding and normalising a graph, for the ablation tables +FAMILIES = { + "one column, left": ("hyperedge", "left"), "one column, symmetric": ("hyperedge", "symmetric"), + "two columns, left": ("pair", "left"), "two columns, symmetric": ("pair", "symmetric"), +} + +# panels of the figures: label and the configurations to look for (labelled graphs are drawn +# from the classification run, the others from the similarity run) +FIGURE_METHODS = [{"label": "Cleora", "configurations": [cleora_configuration("hyperedge", task) for task in ("nc", "lp")]}] +FIGURE_METHODS += [{"label": METHODS[name]["label"], "configurations": [name]} for name in BASELINES] +FIGURE_METHODS.append({"label": METHODS["cleora_3_2"]["label"], "configurations": ["cleora_whiten40"]}) + +NODE_PROBES = {"logistic": "logistic regression", "mlp": "MLP (AdamC)"} +PAIR_PROBES = {"dot": "dot product", "cosine": "cosine", "logistic": "logistic regression on x*y"} +# metrics of the retrieval among all nodes that get a table +RETRIEVAL_METRICS = {"recall@10": "recall@10", "recall@50": "recall@50", "ndcg@10": "nDCG@10", "map@10": "MAP@10", + "all_nodes_mrr": "MRR"} + +# The uses of the vectors the report is organised by, and the measurement each is headlined +# with: (label, how it is measured, task, probe, metric). The probe "similarity" is the +# better of dot product and cosine on validation; a metric of None is accuracy on +# single-label graphs and micro-F1 on multi-label ones. +SCENARIOS = { + "retrieval": ("Similarity search among all nodes", "dot product / cosine, recall@10", "lp", "similarity", "recall@10"), + "nc": ("Node classification", "logistic regression, accuracy / micro-F1", "nc", "logistic", None), + "lp": ("Link ranking against sampled candidates", "dot product / cosine, MRR", "lp", "similarity", "mrr"), +} +# the graphs the summary at the top of the README takes its time and its memory figure from: +# the largest ones on which the timing pass ran every method that scales +SUMMARY_TIME_GRAPH, SUMMARY_MEMORY_GRAPH = "ogbn_arxiv", "yelp" + +# "Cleora, tuned" is chosen on what the sweep validates - the classification score and the +# MRR against sampled candidates - so these are the scenarios it is reported for +TUNED_SCENARIOS = ("nc", "lp") diff --git a/benchmarks/cleora_bench/embed_worker.py b/benchmarks/cleora_bench/embed_worker.py new file mode 100644 index 0000000..c8bd1cf --- /dev/null +++ b/benchmarks/cleora_bench/embed_worker.py @@ -0,0 +1,103 @@ +"""Runs one embedding method on one graph in this (fresh) process. + + python -m cleora_bench.embed_worker --method prone --graph graph.npz --dim 1024 \\ + --seed 0 --threads 32 --out vectors.npy --stats stats.json + +``graph.npz`` holds ``edges`` (int64 [E, 2]), ``num_nodes`` and optionally ``weights``. +The statistics are the wall time of the method call (from edge arrays in memory to the +embedding matrix in memory) and the peak resident memory of the process - interpreter +and libraries included; ``rss_before_mb`` is the peak before the method was called. + +Use :func:`run` to start it in the Python environment the method needs. +""" + +import argparse +import json +import os +import resource +import subprocess +import sys +import time + +import numpy as np + +THREAD_VARIABLES = ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMEXPR_NUM_THREADS", + "NUMBA_NUM_THREADS", "RAYON_NUM_THREADS", "VECLIB_MAXIMUM_THREADS") + + +def _peak_rss_mb(): + """Peak resident memory of this process. + + On Linux ``ru_maxrss`` survives ``exec``: a freshly started worker would report the + memory of the process that launched it. ``VmHWM`` belongs to the current address + space only, so that is what is read there.""" + if sys.platform.startswith("linux"): + with open("/proc/self/status") as status: + for line in status: + if line.startswith("VmHWM:"): + return int(line.split()[1]) / 1024 # kB + raise RuntimeError("VmHWM not found in /proc/self/status") + peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + return peak / (1 << 20) if sys.platform == "darwin" else peak / 1024 # bytes on macOS, kB elsewhere + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("--method", required=True) + parser.add_argument("--graph", required=True) + parser.add_argument("--dim", type=int, required=True) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--threads", type=int, default=os.cpu_count()) + parser.add_argument("--params", default="{}", help="JSON object of method parameters") + parser.add_argument("--out", required=True) + parser.add_argument("--stats", required=True) + args = parser.parse_args() + + from cleora_bench import methods + + with np.load(args.graph) as archive: + edges = archive["edges"] + num_nodes = int(archive["num_nodes"]) + weights = archive["weights"] if "weights" in archive.files else None + before = _peak_rss_mb() + start = time.perf_counter() + vectors = methods.embed(args.method, edges, num_nodes, args.dim, args.seed, args.threads, weights, + **json.loads(args.params)) + seconds = time.perf_counter() - start + peak = _peak_rss_mb() + if not np.isfinite(vectors).all(): + raise RuntimeError(f"{args.method} produced non-finite values") + np.save(args.out, vectors) + with open(args.stats, "w") as handle: + json.dump({"seconds": seconds, "peak_rss_mb": peak, "rss_before_mb": before, "threads": args.threads, + **methods.RUN_INFO}, handle) + + +def run(method, graph_path, dim, seed, threads, out_path, stats_path, params=None, timeout=None): + """Runs the worker in the environment of ``method``. Returns ``None`` on success or a + short failure reason ("timeout", "out of memory", or the last line of the error).""" + from cleora_bench import methods + + environment_name = methods.METHODS[method][1] + environments = os.environ.get("CLEORA_BENCH_ENVS") + python = os.path.join(environments, environment_name, "bin", "python") if environments else sys.executable + environment = dict(os.environ, PYTHONPATH=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + for variable in THREAD_VARIABLES: + environment[variable] = str(threads) + command = [python, "-m", "cleora_bench.embed_worker", "--method", method, "--graph", graph_path, + "--dim", str(dim), "--seed", str(seed), "--threads", str(threads), + "--params", json.dumps(params or {}), "--out", out_path, "--stats", stats_path] + try: + completed = subprocess.run(command, env=environment, capture_output=True, text=True, timeout=timeout) + except subprocess.TimeoutExpired: + return "timeout" + if completed.returncode == 0: + return None + if completed.returncode in (-9, 137) or "MemoryError" in completed.stderr: + return "out of memory" + lines = [line for line in completed.stderr.strip().splitlines() if line.strip()] + return (lines[-1] if lines else f"exit code {completed.returncode}")[:300] + + +if __name__ == "__main__": + main() diff --git a/benchmarks/cleora_bench/iteration_fit.py b/benchmarks/cleora_bench/iteration_fit.py new file mode 100644 index 0000000..148aa11 --- /dev/null +++ b/benchmarks/cleora_bench/iteration_fit.py @@ -0,0 +1,190 @@ +"""How the rule behind ``num_iterations="auto"`` was found. + +Concern of this module: fitting candidate *forms* of an iteration rule to the sweep and +measuring what each costs. The rule that ships is ``pycleora``'s +``SparseMatrix.suggest_iterations``; this module only justifies its form and constants. + +A candidate maps a graph to a number of iterations ``K`` from two quick statistics: +``d``, the mean number of neighbours, and ``s``, the share of the weight on the diagonal +(1/2 for the one-column setup, 0 for two columns). Its *regret* on a sweep curve is the +test score at the iteration count that validated best minus the test score at ``K``, in +points of the metric. Parameters are fitted leave-one-graph-out, on validation scores +only: the regret reported for a graph never comes from parameters that saw it. +""" + +import itertools + +import numpy as np + +from . import configurations, report, selection + +MAX_ITERATIONS = max(configurations.SWEEP_ITERATIONS) +SELF_SHARE = {"hyperedge": 0.5, "pair": 0.0} +TASK_LABELS = {"nc": "classification", "lp": "link ranking"} + + +def curves(sweep_results, task): + """One record per (dataset, setup, normalisation) with a complete sweep: validation + and test score for every iteration count, ``d`` and ``s`` of the graph embedded.""" + table = report.aggregate(report.load_jobs(sweep_results)) + probe = selection.SWEEP_PROBE[task] + datasets = sorted({key[0] for key in table if key[1] == task}) + result = [] + for dataset in datasets: + for setup in configurations.SETUPS: + for propagation in ("left", "sym"): + valid, test, degree = {}, {}, None + for iterations, name in zip(configurations.SWEEP_ITERATIONS, configurations.sweep(setup, propagation)): + entry = table.get((dataset, task, name, 1024)) + runs = entry["probes"].get(probe) if entry else None + if not runs or not runs["validation"]: + continue + metric = "mrr" if task == "lp" else ("accuracy" if "accuracy" in runs["metrics"][0] else "micro_f1") + valid[iterations] = float(np.mean(runs["validation"])) + test[iterations] = float(np.mean([m[metric] for m in runs["metrics"]])) + degree = entry["degree"] + if len(valid) == len(configurations.SWEEP_ITERATIONS): + best = max(valid, key=valid.get) + result.append({"dataset": dataset, "setup": setup, "symmetric": propagation == "sym", + "share": SELF_SHARE[setup], "degree": degree, "valid": valid, "test": test, + "best_iterations": best, "best_test": test[best]}) + return result + + +def _score_at(curve, iterations): + """Score at a number of iterations between the grid points: linear in log K.""" + grid = np.array(sorted(curve), dtype=np.float64) + return float(np.interp(np.log(np.clip(iterations, grid[0], grid[-1])), np.log(grid), [curve[int(k)] for k in grid])) + + +def regret(record, iterations, which="test"): + """Points of the metric (accuracy, micro-F1 or MRR, times 100) lost against the + iteration count that validated best.""" + top = max(record["valid"].values()) if which == "valid" else record["best_test"] + return 100.0 * (top - _score_at(record[which], iterations)) + + +def _rounded(value): + return float(np.clip(round(value), 1, MAX_ITERATIONS)) + + +def _mean_regret(records, iterations_of): + return float(np.mean([regret(r, _rounded(iterations_of(r)), "valid") for r in records])) + + +# ----------------------------------------------------------------------------- candidate forms +# Every form has shared structure parameters and one number of steps ``c`` per task. + +STEPS = (6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48) + + +def _mixing(record, steps, symmetric_factor): + factor = symmetric_factor if record["symmetric"] else 1.0 + return steps * factor / ((1.0 - record["share"]) * np.sqrt(max(record["degree"], 1.0))) + + +def _with_floors(record, steps, symmetric_factor, remainder, minimum): + forget = np.log(remainder) / np.log(record["share"]) if record["share"] > 0 else 0.0 + return max(_mixing(record, steps, symmetric_factor), forget, minimum) + + +def _fit_constant(records): + """The best single iteration count of every task, setup and normalisation.""" + best = {} + for key in {(r["task"], r["setup"], r["symmetric"]) for r in records}: + group = [r for r in records if (r["task"], r["setup"], r["symmetric"]) == key] + best[key] = min(configurations.SWEEP_ITERATIONS, key=lambda k: _mean_regret(group, lambda r: k)) + return best + + +def _fit_form(records, form, structures): + """Structure parameters shared by the tasks, the steps ``c`` chosen per task.""" + tasks = sorted({r["task"] for r in records}) + best = None + for structure in structures: + steps, total = {}, 0.0 + for task in tasks: + group = [r for r in records if r["task"] == task] + losses = {c: _mean_regret(group, lambda r: form(r, c, *structure)) for c in STEPS} + steps[task] = min(losses, key=losses.get) + total += losses[steps[task]] + if best is None or total < best[0]: + best = (total, steps, structure) + return best[1], best[2] + + +FORMS = { + "one constant per setup and normalisation": None, + "mixing term only: c / ((1 - s) sqrt(d))": (_mixing, [(factor,) for factor in (1.0, 1.5, 2.0)]), + "mixing term and floors (the form that ships)": (_with_floors, list(itertools.product( + (1.0, 1.5, 2.0), (1 / 64, 1 / 256, 1 / 1024), (1, 2, 3)))), +} + + +def _fit(name, records): + """``(parameters, iterations(record))`` of a form fitted to ``records``.""" + if FORMS[name] is None: + constants = _fit_constant(records) + fallback = int(np.median(list(constants.values()))) + return constants, lambda r: constants.get((r["task"], r["setup"], r["symmetric"]), fallback) + form, structures = FORMS[name] + steps, structure = _fit_form(records, form, structures) + return (steps, structure), lambda r: form(r, steps[r["task"]], *structure) + + +def leave_one_out(records): + """``{form: (held-out regret of every record, parameters fitted on all records)}``. The + held-out regret of a record uses parameters fitted without any curve of its graph.""" + result = {} + for name in FORMS: + held = [None] * len(records) + for dataset in sorted({r["dataset"] for r in records}): + _, iterations_of = _fit(name, [r for r in records if r["dataset"] != dataset]) + for index, record in enumerate(records): + if record["dataset"] == dataset: + held[index] = regret(record, _rounded(iterations_of(record))) + result[name] = (held, _fit(name, records)[0]) + return result + + +def _describe(parameters): + if isinstance(parameters, dict): + return "; ".join(f"{TASK_LABELS[task]}, {setup}/{'sym' if symmetric else 'left'}: {k}" + for (task, setup, symmetric), k in sorted(parameters.items())) + steps, structure = parameters + text = ", ".join(f"c = {c} ({TASK_LABELS[task]})" for task, c in sorted(steps.items())) + f", symmetric x{structure[0]}" + if len(structure) == 3: + text += f", remainder 1/{round(1 / structure[1])}, minimum {structure[2]}" + return text + + +def markdown(sweep_results): + """The table of the methodology document: held-out loss of every form, per task.""" + records = [dict(record, task=task) for task in TASK_LABELS for record in curves(sweep_results, task)] + lines = ["| Rule | Task | Graphs | Curves | Mean loss | Median loss | Worst loss |", "|---|---|---:|---:|---:|---:|---:|"] + notes = [] + for name, (held, parameters) in leave_one_out(records).items(): + for task, label in TASK_LABELS.items(): + losses = [loss for loss, record in zip(held, records) if record["task"] == task] + graphs = len({record["dataset"] for record in records if record["task"] == task}) + lines.append(f"| {name} | {label} | {graphs} | {len(losses)} | {np.mean(losses):.2f} | " + f"{np.median(losses):.2f} | {np.max(losses):.2f} |") + notes.append(f"- *{name}*, fitted on all graphs: {_describe(parameters)}") + return "\n".join(lines) + "\n\n" + "\n".join(notes) + + +def sensitivity_markdown(sweep_results): + """Loss of the form that ships as a function of ``c`` (all graphs; the structure + parameters are those fitted on all graphs): how flat the optimum is.""" + records = [dict(record, task=task) for task in TASK_LABELS for record in curves(sweep_results, task)] + form, structures = FORMS["mixing term and floors (the form that ships)"] + _, structure = _fit_form(records, form, structures) + header = " | ".join(f"{label}: mean | median | worst" for label in TASK_LABELS.values()) + lines = [f"| c | {header} |", "|---:|" + "---:|" * (3 * len(TASK_LABELS))] + for steps in STEPS: + cells = [] + for task in TASK_LABELS: + losses = [regret(r, _rounded(form(r, steps, *structure))) for r in records if r["task"] == task] + cells += [f"{np.mean(losses):.2f}", f"{np.median(losses):.2f}", f"{np.max(losses):.2f}"] + lines.append(f"| {steps} | " + " | ".join(cells) + " |") + return "\n".join(lines) diff --git a/benchmarks/cleora_bench/methods.py b/benchmarks/cleora_bench/methods.py new file mode 100644 index 0000000..3303f88 --- /dev/null +++ b/benchmarks/cleora_bench/methods.py @@ -0,0 +1,323 @@ +"""Embedding methods under test, behind one signature. + +Concern of this module: given a graph, produce one vector per node with a named method. +Every method - Cleora and the baselines alike - is called as + + embed(edges, num_nodes, dim, seed, threads, weights) -> float32 [num_nodes, dim] + +``edges`` is the canonical edge list of :mod:`cleora_bench.datasets` (undirected, unique, +``u < v``); row ``i`` of the result is the vector of node ``i``. + +The baselines are *not* reimplemented here. Each one runs its authors' code or a widely +used library, with the hyper-parameters its authors recommend: + +============== ================================================================= ======== +method implementation env +============== ================================================================= ======== +deepwalk PecanPy 2.0.9 walks + gensim skip-gram (negative sampling) walks +node2vec same, biased walks walks +prone authors' proNE.py (github.com/THUDM/ProNE) main +netmf authors' netmf.py (github.com/xptree/NetMF), Theano calls -> NumPy main +fastrp authors' fastrp.py (github.com/GTmac/FastRP) main +randne authors' RandNE.py (github.com/ZW-ZHANG/RandNE) main +grarep karateclub 1.3.3 karate +hope karateclub 1.3.3 karate +walklets karateclub 1.3.3 karate +============== ================================================================= ======== + +``env`` names the Python environment (see ``benchmarks/envs``) the method runs in; the +reference repositories are cloned at pinned commits by ``benchmarks/setup.sh`` into the +directory named by ``CLEORA_BENCH_BASELINES``. + +The module only needs NumPy at import time and runs on Python >= 3.10, because it is +imported inside every one of those environments. +""" + +import os +import sys + +import numpy as np + +# name -> (function, environment, label, largest graph in nodes (None = unlimited), note) +METHODS = {} + +# What a method wants recorded about the run besides time and memory (the worker stores +# it with the statistics). One run per process, so a module-level dictionary is enough. +RUN_INFO = {} + + +def _method(name, env, label, max_nodes=None, note=""): + def decorate(function): + METHODS[name] = (function, env, label, max_nodes, note) + return function + return decorate + + +def embed(name, edges, num_nodes, dim, seed, threads, weights=None, **params): + function = METHODS[name][0] + vectors = np.ascontiguousarray(function(edges, num_nodes, dim, seed, threads, weights, **params), dtype=np.float32) + if vectors.shape != (num_nodes, dim): + raise RuntimeError(f"{name} returned shape {vectors.shape}, expected {(num_nodes, dim)}") + return vectors + + +# ----------------------------------------------------------------------------- helpers + + +def adjacency(edges, num_nodes, weights=None): + """Symmetric adjacency matrix (float64 CSR, sorted indices, no self-loops).""" + from scipy.sparse import csr_matrix + + values = np.ones(len(edges)) if weights is None else np.asarray(weights, dtype=np.float64) + rows = np.concatenate([edges[:, 0], edges[:, 1]]) + cols = np.concatenate([edges[:, 1], edges[:, 0]]) + matrix = csr_matrix((np.concatenate([values, values]), (rows, cols)), shape=(num_nodes, num_nodes)) + matrix.sort_indices() + return matrix + + +def _reference(repository, *subdirectory): + """Makes the pinned checkout of a reference implementation importable.""" + root = os.environ.get("CLEORA_BENCH_BASELINES") + if not root: + raise RuntimeError("Set CLEORA_BENCH_BASELINES to the directory benchmarks/setup.sh cloned the baselines into") + path = os.path.join(root, repository, *subdirectory) + if not os.path.isdir(path): + raise RuntimeError(f"Reference implementation not found: {path} (run benchmarks/setup.sh)") + if path not in sys.path: + sys.path.insert(0, path) + + +def _pad(vectors, dim): + """Methods that cannot produce ``dim`` columns on a small graph are zero-padded.""" + if vectors.shape[1] >= dim: + return vectors[:, :dim] + return np.concatenate([vectors, np.zeros((vectors.shape[0], dim - vectors.shape[1]), vectors.dtype)], axis=1) + + +# ----------------------------------------------------------------------------- Cleora + + +def _cleora_graph(edges, threads, weights, columns): + from pycleora import SparseMatrix + + graph = SparseMatrix.from_edges(edges[:, 0], edges[:, 1], columns=columns, weights=weights, num_workers=threads) + return graph, np.array(graph.entity_ids, dtype=np.int64) + + +def _node_order(vectors, row_node, num_nodes): + out = np.zeros((num_nodes, vectors.shape[1]), dtype=np.float32) + out[row_node] = vectors + return out + + +@_method("cleora_classic", "main", "Cleora", note="iterations: a number, or 'auto' = SparseMatrix.suggest_iterations(purpose); " + "popularity: exponent of pycleora.scale_by_popularity, 0 = unit vectors") +def cleora_classic(edges, num_nodes, dim, seed, threads, weights, iterations="auto", propagation="left", + columns="complex::reflexive::node", purpose="general", popularity=0.0): + import pycleora + + graph, row_node = _cleora_graph(edges, threads, weights, columns) + if iterations == "auto": + iterations = graph.suggest_iterations(propagation, purpose) + RUN_INFO["iterations"] = iterations + vectors = pycleora.embed(graph, dim, iterations, propagation=propagation, seed=seed, num_workers=threads, whiten=False) + if popularity: + vectors = pycleora.scale_by_popularity(graph, vectors, popularity) + return _node_order(vectors, row_node, num_nodes) + + +@_method("cleora_whiten40", "main", "Cleora 3.2 / PR #81 default", note="40 iterations, PCA whitening after every one") +def cleora_whiten40(edges, num_nodes, dim, seed, threads, weights): + import warnings + + import pycleora + + graph, row_node = _cleora_graph(edges, threads, weights, "complex::reflexive::node") + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + vectors = pycleora.embed(graph, dim, 40, seed=seed, num_workers=threads, whiten=True) + return _node_order(vectors, row_node, num_nodes) + + +# ----------------------------------------------------------------------------- random walks + + +def _skipgram_walks(edges, num_nodes, dim, seed, threads, weights, p, q, epochs): + from pecanpy import pecanpy + + matrix = adjacency(edges, num_nodes, weights) + # PecanPy's own choice of walk engine: plain neighbour sampling for first-order walks + # (alias tables when edges are weighted), on-the-fly second-order probabilities for + # node2vec. All of them sample the same walks; the engines differ in speed only. + if p == 1.0 and q == 1.0: + engine = pecanpy.FirstOrderUnweighted if weights is None else pecanpy.PreCompFirstOrder + else: + engine = pecanpy.SparseOTF + graph = engine(p=p, q=q, workers=threads, verbose=False, random_state=seed) + graph.set_node_ids([str(node) for node in range(num_nodes)]) + graph.indptr = matrix.indptr.astype(np.uint64) + graph.indices = matrix.indices.astype(np.uint32) + graph.data = matrix.data.astype(np.float32) + # node2vec's settings: 10 walks of length 80 per node, window 10 (Grover & Leskovec, 2016) + return graph.embed(dim=dim, num_walks=10, walk_length=80, window_size=10, epochs=epochs) + + +@_method("deepwalk", "walks", "DeepWalk", note="PecanPy first-order walks + gensim skip-gram") +def deepwalk(edges, num_nodes, dim, seed, threads, weights, epochs=1): + return _skipgram_walks(edges, num_nodes, dim, seed, threads, weights, 1.0, 1.0, epochs) + + +@_method("node2vec", "walks", "node2vec", note="PecanPy biased walks + gensim skip-gram") +def node2vec(edges, num_nodes, dim, seed, threads, weights, p=1.0, q=0.5, epochs=1): + return _skipgram_walks(edges, num_nodes, dim, seed, threads, weights, p, q, epochs) + + +# ----------------------------------------------------------------------------- matrix methods + + +@_method("prone", "main", "ProNE", note="authors' code; mu = 0.2, theta = 0.5, 10 Chebyshev steps") +def prone(edges, num_nodes, dim, seed, threads, weights): + _reference("ProNE") + import proNE + + matrix = adjacency(edges, num_nodes, weights) + # The reference class reads an edge-list file with networkx in its constructor; the + # two algorithm steps only need the adjacency matrix, the node count and the dimension. + model = proNE.ProNE.__new__(proNE.ProNE) + model.node_number, model.dimension = num_nodes, min(dim, num_nodes - 1) + np.random.seed(seed) # its randomized SVD draws from the global NumPy generator + features = model.pre_factorization(matrix, matrix) + return _pad(model.chebyshev_gaussian(matrix, features, 10, 0.2, 0.5), dim) + + +NETMF_DENSE_FALLBACK_NODES = 20_000 + + +def _leading_eigenpairs_dense(matrix, rank): + """What NetMF's ``approximate_normalized_graph_laplacian`` returns - the ``rank`` + largest eigenvalues of D^-1/2 A D^-1/2 and D^-1/2 times their eigenvectors - computed + with a dense symmetric eigensolver.""" + from scipy.sparse import csgraph, diags, identity + + laplacian, d_rt = csgraph.laplacian(matrix, normed=True, return_diag=True) + values, vectors = np.linalg.eigh((identity(matrix.shape[0]) - laplacian).toarray()) + keep = np.argsort(values)[-rank:] + return values[keep], diags(d_rt ** -1).dot(vectors[:, keep]) + + +@_method("netmf", "main", "NetMF", max_nodes=60_000, + note="authors' algorithm (large-window variant, T = 10, b = 1); needs a dense n x n matrix") +def netmf(edges, num_nodes, dim, seed, threads, weights, window=10, negative=1.0): + import types + + # netmf.py imports Theano (unmaintained since 2020) for two element-wise expressions. + # A placeholder satisfies the import; the two functions that use it are restated + # below with NumPy, line by line. + if "theano" not in sys.modules: + placeholder = types.ModuleType("theano") + placeholder.config = types.SimpleNamespace(exception_verbosity="high", floatX="float32") + placeholder.tensor = types.ModuleType("theano.tensor") + sys.modules["theano"], sys.modules["theano.tensor"] = placeholder, placeholder.tensor + _reference("NetMF") + import netmf as reference + import scipy.sparse.linalg # noqa: F401 (the reference calls sparse.linalg without importing it) + from scipy import sparse + + matrix = adjacency(edges, num_nodes, weights) + rank = min(max(256, dim), num_nodes - 2) + volume = float(matrix.sum()) + try: + eigenvalues, d_rt_inv_u = reference.approximate_normalized_graph_laplacian(matrix, rank=rank, which="LA") + except sparse.linalg.ArpackError: + # ARPACK gives up when the leading eigenvalue is repeated very often (a graph in + # many pieces). The same eigenpairs from a dense decomposition, where that is affordable: + if num_nodes > NETMF_DENSE_FALLBACK_NODES: + raise + eigenvalues, d_rt_inv_u = _leading_eigenpairs_dense(matrix, rank) + # approximate_deepwalk_matrix, with T.log(T.maximum(m m^T * vol / b, 1)) in NumPy: + eigenvalues = reference.deepwalk_filter(eigenvalues, window=window) + x = sparse.diags(np.sqrt(eigenvalues)).dot(d_rt_inv_u.T).T.astype(np.float32) + deepwalk_matrix = x @ x.T + deepwalk_matrix *= volume / negative + np.maximum(deepwalk_matrix, 1, out=deepwalk_matrix) + np.log(deepwalk_matrix, out=deepwalk_matrix) + np.random.seed(seed) + # svd_deepwalk_matrix: U * sqrt(S) of the leading singular triplets + u, s, _ = sparse.linalg.svds(deepwalk_matrix, min(dim, num_nodes - 2), return_singular_vectors="u") + return _pad(np.asarray(sparse.diags(np.sqrt(s)).dot(u.T).T), dim) + + +@_method("fastrp", "main", "FastRP", + note="authors' code and published configuration: weights (0, 0, 1, 6.67), beta = -0.64") +def fastrp(edges, num_nodes, dim, seed, threads, weights, order_weights=(0.0, 0.0, 1.0, 6.67), beta=-0.64): + _reference("FastRP") + import fastrp as reference + from scipy.sparse import spdiags + + matrix = adjacency(edges, num_nodes, weights) + # The reference builds the (degree-scaled, very sparse) projection and the first + # product, and merges the powers. Its loop over the higher powers multiplies sparse + # matrices that fill in completely; here those products are dense, which computes + # the same numbers. The reference fixes the seed of the projection (random_state=42). + first = reference.fastrp_projection(matrix, q=1, dim=dim, projection_method="sparse", + input_matrix="trans", alpha=beta)[0] + current = np.asarray(first.todense()) if hasattr(first, "todense") else np.asarray(first) + degrees = np.asarray(matrix.sum(axis=1)).ravel() + transition = spdiags(1.0 / degrees, 0, num_nodes, num_nodes) @ matrix + powers = [current] + for _ in range(len(order_weights) - 1): + current = transition @ current + powers.append(current) + return np.asarray(reference.fastrp_merge(powers, list(order_weights), True)) + + +@_method("randne", "main", "RandNE", + note="authors' code and classification configuration: transition matrix, q = 3, weights (1, 1e2, 1e4, 1e5)") +def randne(edges, num_nodes, dim, seed, threads, weights): + _reference("RandNE", "Python") + import RandNE as reference + from sklearn.preprocessing import normalize + + transition = normalize(adjacency(edges, num_nodes, weights), norm="l1", axis=1) + parts = reference.Projection(transition, 3, dim, False, seed) + return normalize(reference.Combine(parts, [1, 1e2, 1e4, 1e5]), norm="l2", axis=1) + + +# ----------------------------------------------------------------------------- karateclub + + +def _karate(model, edges, num_nodes, weights): + import networkx + + graph = networkx.Graph() + graph.add_nodes_from(range(num_nodes)) + if weights is None: + graph.add_edges_from(edges.tolist()) + else: + graph.add_weighted_edges_from([(int(u), int(v), float(w)) for (u, v), w in zip(edges, weights)]) + model.fit(graph) + return model.get_embedding() + + +@_method("grarep", "karate", "GraRep", max_nodes=40_000, note="karateclub; 4 orders x dim/4; dense n x n") +def grarep(edges, num_nodes, dim, seed, threads, weights): + from karateclub import GraRep + + order = 4 + return _pad(_karate(GraRep(dimensions=min(dim // order, num_nodes - 1), order=order, seed=seed), edges, num_nodes, weights), dim) + + +@_method("hope", "karate", "HOPE", max_nodes=40_000, note="karateclub (common-neighbours proximity)") +def hope(edges, num_nodes, dim, seed, threads, weights): + from karateclub import HOPE + + return _pad(_karate(HOPE(dimensions=min(dim, num_nodes - 1), seed=seed), edges, num_nodes, weights), dim) + + +@_method("walklets", "karate", "Walklets", max_nodes=40_000, note="karateclub; 4 scales x dim/4") +def walklets(edges, num_nodes, dim, seed, threads, weights): + from karateclub import Walklets + + scales = 4 + return _karate(Walklets(dimensions=dim // scales, window_size=scales, workers=threads, seed=seed), edges, num_nodes, weights) diff --git a/benchmarks/cleora_bench/popularity.py b/benchmarks/cleora_bench/popularity.py new file mode 100644 index 0000000..6687650 --- /dev/null +++ b/benchmarks/cleora_bench/popularity.py @@ -0,0 +1,74 @@ +"""How the exponents of the popularity prior were chosen: what is measured, and its tables. + +Concern of this module: the record of one design decision - which exponent +``pycleora.scale_by_popularity`` gets when the vectors are used to find links and when +they are features of a classifier. ``benchmarks/popularity_exponent.py`` measures the +candidate exponents on *validation* data and writes one file per task and graph; this +module names the candidates and the files and turns the files into tables. +""" + +import glob +import json +import os + +import numpy as np + +EXPONENTS = (0.0, 0.03125, 0.0625, 0.09375, 0.125, 0.1875, 0.25, 0.375, 0.5) +DIRECTORY = "popularity" +# what a file holds for every exponent, by task +METRICS = {"lp": ("mrr", "recall@10"), # against the sampled candidates / among all nodes + "nc": ("score",)} # accuracy, or micro-F1 on multi-label graphs (logistic regression) + + +def path(data, task, dataset): + return os.path.join(data, DIRECTORY, task, f"{dataset}.json") + + +def _graphs(data, task): + graphs = [] + for name in sorted(glob.glob(path(data, task, "*"))): + with open(name) as handle: + graphs.append(json.load(handle)) + return graphs + + +def _bold_best(rows, columns): + """The rows as strings, the best value of each of the first ``columns`` columns in bold.""" + best = [max(row[column] for row in rows) for column in range(columns)] + return [[f"**{value:.4f}**" if value == top else f"{value:.4f}" for value, top in zip(row, best)] + [str(v) for v in row[columns:]] + for row in rows] + + +def link_table(data): + """One row per exponent: mean validation scores over the measured graphs - of the + prior applied everywhere, and of the benchmark's rule, which keeps the unit vectors + (the cosine) on a graph where they validate better by MRR.""" + graphs = _graphs(data, "lp") + if not graphs: + return "" + rows = [] + for exponent in EXPONENTS: + everywhere = [graph[str(exponent)] for graph in graphs] + chosen = [graph[str(exponent)] if graph[str(exponent)]["mrr"] > graph["0.0"]["mrr"] else graph["0.0"] for graph in graphs] + taken = sum(graph[str(exponent)]["mrr"] > graph["0.0"]["mrr"] for graph in graphs) + rows.append([float(np.mean([scores[metric] for scores in table])) for table in (everywhere, chosen) for metric in METRICS["lp"]] + [taken]) + lines = ["| Exponent | Graphs | MRR | recall@10 | MRR, prior or cosine | recall@10, prior or cosine | Graphs that take the prior |", + "|---:|---:|---:|---:|---:|---:|---:|"] + lines += [f"| {exponent:g} | {len(graphs)} | " + " | ".join(cells) + " |" for exponent, cells in zip(EXPONENTS, _bold_best(rows, 4))] + return "\n".join(lines) + + +def classification_table(data): + """One row per exponent: the mean validation score of logistic regression over the + measured graphs, and on how many of them it is above / below that of the unit vectors.""" + graphs = _graphs(data, "nc") + if not graphs: + return "" + rows = [] + for exponent in EXPONENTS: + scores = np.array([graph[str(exponent)]["score"] for graph in graphs]) + plain = np.array([graph["0.0"]["score"] for graph in graphs]) + rows.append([float(scores.mean()), int((scores > plain).sum()), int((scores < plain).sum())]) + lines = ["| Exponent | Graphs | Validation score | Graphs above the unit vectors | Graphs below |", "|---:|---:|---:|---:|---:|"] + lines += [f"| {exponent:g} | {len(graphs)} | " + " | ".join(cells) + " |" for exponent, cells in zip(EXPONENTS, _bold_best(rows, 1))] + return "\n".join(lines) diff --git a/benchmarks/cleora_bench/probes.py b/benchmarks/cleora_bench/probes.py new file mode 100644 index 0000000..d7611e7 --- /dev/null +++ b/benchmarks/cleora_bench/probes.py @@ -0,0 +1,303 @@ +"""Probes: small supervised models trained on frozen embeddings. + +Concern of this module: fitting a probe and returning its scores. It knows nothing about +graphs, embedding methods or metrics. + +Every probe sees the same inputs for every embedding method, and every hyper-parameter +is chosen on validation data only (the functions never receive test labels). + +The probes are the ways embeddings are used in practice: as features of a classifier +and as vectors that are compared with each other. + +Node probes (one vector -> classes) + ``logistic`` linear, logistic loss: multinomial (single-label) / one-vs-rest (multi-label) + ``mlp`` one hidden layer, trained with AdamC + +Pair probes (two vectors -> link score) + ``dot`` / ``cosine`` no training: what a nearest-neighbour index computes + ``logistic`` logistic regression on the element-wise product of the two + vectors: a dot product with one learned weight per dimension + +Feature scaling. Embedding methods differ in what the scale of their coordinates means: +standardising every dimension helps some and destroys the spectrum of others (the +columns of an SVD-based embedding are ordered by importance). The scaling is therefore +a hyper-parameter of the probe, chosen on validation like the others, from ``SCALINGS``. + +Logistic regression minimises mean_i loss_i + decay / 2 * ||W||^2 with full-batch +L-BFGS, which finds the optimum of this convex problem to high precision, so the result +does not depend on a learning-rate schedule. ``decay`` is chosen from ``DECAYS``. +""" + +import math + +import numpy as np +import torch + +# strongest first: every fit starts from the solution of the previous (stronger) decay +DECAYS = (1e2, 1e1, 1.0, 1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7, 1e-8) + + +def pick_device(): + """The CUDA device to train the probes on - the least busy one, found with + ``nvidia-smi`` so that no context is opened on the others (set + ``CUDA_VISIBLE_DEVICES`` to choose yourself) - else Apple MPS, else the CPU.""" + import os + import subprocess + + if torch.cuda.is_available(): + if torch.cuda.device_count() == 1 or "CUDA_VISIBLE_DEVICES" in os.environ: + return torch.device("cuda:0") + try: + listing = subprocess.run( + ["nvidia-smi", "--query-gpu=index,utilization.gpu,memory.used", "--format=csv,noheader,nounits"], + capture_output=True, text=True, timeout=30, check=True).stdout + usage = [tuple(int(value) for value in line.split(",")) for line in listing.strip().splitlines()] + return torch.device(f"cuda:{min(usage, key=lambda gpu: (gpu[1], gpu[2]))[0]}") + except (OSError, subprocess.SubprocessError, ValueError): + return torch.device("cuda:0") + if torch.backends.mps.is_available(): + return torch.device("mps") + return torch.device("cpu") + + +# Logistic regression on a matrix with fewer elements than this is fitted on the CPU: its +# thousands of tiny L-BFGS steps are faster there than through a GPU. (The MLP multiplies +# large matrices at every step and always uses the GPU when there is one.) +SMALL_PROBLEM = 1 << 24 + + +def device_for(elements, device): + return torch.device("cpu") if elements <= SMALL_PROBLEM else device + + +SCALINGS = ("raw", "unit", "standard") + + +def scaler(kind, train_features): + """Returns ``scale(features)`` for one of ``SCALINGS``: + + ``raw`` the vectors as the method produced them; + ``unit`` every vector scaled to unit L2 norm; + ``standard`` every dimension shifted and scaled to zero mean and unit variance, + with the statistics of the training rows. + + ``raw`` and ``unit`` are additionally multiplied by one number, chosen so that the + training rows have a mean squared norm equal to the number of dimensions (as + standardised features have). It changes nothing about the geometry, but it puts all + three scalings - and all methods, whatever the magnitude of their vectors - on the + same footing with respect to the regularisation grid. + """ + def with_common_magnitude(transform): + transformed = transform(train_features) + mean_square = float(np.einsum("ij,ij->", transformed, transformed, dtype=np.float64)) / len(transformed) + factor = np.float32(np.sqrt(transformed.shape[1] / max(mean_square, 1e-30))) + return lambda features: transform(features) * factor + + if kind == "raw": + return with_common_magnitude(lambda features: np.asarray(features, dtype=np.float32)) + if kind == "unit": + return with_common_magnitude( + lambda features: features / np.maximum(np.linalg.norm(features, axis=1, keepdims=True), 1e-12)) + if kind == "standard": + mean = train_features.mean(axis=0, dtype=np.float64) + std = train_features.std(axis=0, dtype=np.float64) + std[std < 1e-12] = 1.0 + mean, std = mean.astype(np.float32), std.astype(np.float32) + return lambda features: (features - mean) / std + raise ValueError(f"Unknown scaling '{kind}'. Use one of {SCALINGS}.") + + +def to_device(array, device, dtype=torch.float32): + return torch.as_tensor(np.ascontiguousarray(array), dtype=dtype, device=device) + + +def _targets(labels, num_classes, device): + """Single-label targets as class indices, multi-label targets as a 0/1 matrix.""" + if labels.ndim == 2: + return to_device(labels, device), True + assert labels.min() >= 0 and labels.max() < num_classes + return to_device(labels, device, torch.long), False + + +def _logistic_loss(logits, targets, multilabel): + if multilabel: + return torch.nn.functional.binary_cross_entropy_with_logits(logits, targets, reduction="sum") / len(logits) + return torch.nn.functional.cross_entropy(logits, targets) + + +def selection_score(scores, labels): + """What a node probe's hyper-parameters are selected by on the validation rows: + accuracy (single-label) or micro-F1 at the model's own decision threshold (multi-label).""" + if labels.ndim == 2: + predicted = scores > 0 + true_positive = float((predicted & labels).sum()) + return 2 * true_positive / max(float(predicted.sum() + labels.sum()), 1.0) + return float((scores.argmax(axis=1) == labels).mean()) + + +def _batched(function, features, device, batch=1 << 16): + out = [] + with torch.no_grad(): + for start in range(0, len(features), batch): + out.append(function(to_device(features[start:start + batch], device)).float().cpu().numpy()) + return np.concatenate(out) + + +def fit_logistic(train_x, train_y, num_classes, device, validate, decays=DECAYS, max_iter=300, wrap=None): + """Fits logistic regression for every decay and keeps the fit for which + ``validate(predict)`` is highest. + + ``predict(features) -> scores`` (numpy, one column per class); ``wrap(weight, bias)`` + replaces it by another function of the fitted parameters (used by the pair probe). + Returns ``(predict, validation score, info)``. + """ + x = train_x if torch.is_tensor(train_x) else to_device(train_x, device) + y, multilabel = _targets(train_y, num_classes, device) + weight = torch.zeros(num_classes, x.shape[1], device=device, requires_grad=True) + bias = torch.zeros(num_classes, device=device, requires_grad=True) + + def predictor(w, b): + if wrap is not None: + return wrap(w, b) + return lambda features: _batched(lambda block: block @ w.T + b, features, device) + + tried, best = {}, None + for decay in decays: + optimizer = torch.optim.LBFGS([weight, bias], lr=1.0, max_iter=max_iter, history_size=20, + tolerance_grad=1e-6, tolerance_change=1e-10, line_search_fn="strong_wolfe") + + def closure(): + optimizer.zero_grad() + loss = _logistic_loss(x @ weight.T + bias, y, multilabel) + 0.5 * decay * weight.pow(2).sum() + loss.backward() + return loss + + optimizer.step(closure) + candidate = predictor(weight.detach().clone(), bias.detach().clone()) + tried[decay] = validate(candidate) + if best is None or tried[decay] > best[0]: + best = (tried[decay], decay, candidate) + return best[2], best[0], {"decay": best[1], "validation": tried} + + +def _adamc(parameters, peak_lr, weight_decay, total_steps, warmup=0.05): + """AdamC (Defazio, 2025: AdamW whose decay is scaled by lr / peak lr) from timm, with + linear warm-up and cosine decay of the learning rate.""" + from timm.optim import create_optimizer_v2 + + optimizer = create_optimizer_v2(parameters, opt="adamc", lr=peak_lr, weight_decay=weight_decay) + warmup_steps = max(1, int(warmup * total_steps)) + + def factor(step): + if step < warmup_steps: + return (step + 1) / warmup_steps + progress = (step - warmup_steps) / max(1, total_steps - warmup_steps) + return 0.5 * (1 + math.cos(math.pi * min(progress, 1.0))) + + return optimizer, torch.optim.lr_scheduler.LambdaLR(optimizer, factor) + + +def _train_with_adamc(make_model, step_loss, num_examples, validate_model, seed, epochs, batch_size, peak_lr, + weight_decays, device): + """Training loop of the MLP probe: for every weight decay, mini-batch training with + a warm-up + cosine schedule; the model state of the best validation epoch over all + decays is returned (with its score and what was tried).""" + # small training sets get small batches: at least ~32 steps per epoch + batch_size = int(min(batch_size, max(32, num_examples // 32))) + steps_per_epoch = max(1, math.ceil(num_examples / batch_size)) + best, tried = None, {} + for weight_decay in weight_decays: + torch.manual_seed(seed) + model = make_model().to(device) + optimizer, scheduler = _adamc(model.parameters(), peak_lr, weight_decay, epochs * steps_per_epoch) + generator = torch.Generator(device="cpu").manual_seed(seed) + best_here = None + for epoch in range(epochs): + model.train() + order = torch.randperm(num_examples, generator=generator).to(device) + for start in range(0, num_examples, batch_size): + loss = step_loss(model, order[start:start + batch_size]) + optimizer.zero_grad() + loss.backward() + optimizer.step() + scheduler.step() + model.eval() + score = validate_model(model) + if best_here is None or score > best_here[0]: + best_here = (score, epoch, {k: v.detach().clone() for k, v in model.state_dict().items()}) + tried[weight_decay] = {"validation": best_here[0], "epoch": best_here[1]} + if best is None or best_here[0] > best[0]: + best = (best_here[0], weight_decay, best_here[2]) + model = make_model().to(device) + model.load_state_dict(best[2]) + model.eval() + return model, best[0], {"weight_decay": best[1], "validation": tried} + + +def fit_mlp(train_x, train_y, num_classes, device, seed, validate, hidden=512, dropout=0.5, + epochs=100, batch_size=4096, peak_lr=1e-3, weight_decays=(1e-2, 1e-1)): + """One-hidden-layer MLP (softmax for single-label, a sigmoid per label for multi-label + targets) trained with AdamC; weight decay and epoch are chosen by ``validate(predict)``. + + Returns ``(predict, validation score, info)``. + """ + x = to_device(train_x, device) + y, multilabel = _targets(train_y, num_classes, device) + + def make_model(): + return torch.nn.Sequential(torch.nn.Linear(x.shape[1], hidden), torch.nn.ReLU(), torch.nn.Dropout(dropout), + torch.nn.Linear(hidden, num_classes)) + + def predictor(model): + return lambda features: _batched(model, features, device) + + model, score, info = _train_with_adamc( + make_model, lambda model, rows: _logistic_loss(model(x[rows]), y[rows], multilabel), len(x), + lambda model: validate(predictor(model)), seed, epochs, batch_size, peak_lr, weight_decays, device) + return predictor(model), score, info + + +# ----------------------------------------------------------------------------- pair probes +# +# A pair scorer is a function score(sources, targets) -> numpy scores over arrays of +# node indices. The trained one learns from pairs with 0/1 labels (edges and non-edges) +# and is selected by ``validate(score)``, which the caller defines (a ranking metric). + + +def _pair_scorer(function, vectors, batch=1 << 15): + """Wraps ``function(left vectors, right vectors) -> scores`` (torch) as a pair scorer.""" + def score(sources, targets): + out = [] + with torch.no_grad(): + for start in range(0, len(sources), batch): + left = vectors[torch.as_tensor(sources[start:start + batch], device=vectors.device)] + right = vectors[torch.as_tensor(targets[start:start + batch], device=vectors.device)] + out.append(function(left, right).float().cpu().numpy()) + return np.concatenate(out) if out else np.zeros(0, dtype=np.float32) + return score + + +def unit_vectors(vectors, device): + """The embedding matrix on ``device`` with unit-norm rows (what the pair probes see).""" + return torch.nn.functional.normalize(to_device(vectors, device), dim=1) + + +def product_scorer(matrix): + """Dot product of two rows of ``matrix`` (a tensor on the device): the plain dot + product for raw vectors, the cosine for unit vectors.""" + return _pair_scorer(lambda left, right: (left * right).sum(dim=1), matrix) + + +def fit_pair_logistic(unit, pairs, labels, device, validate): + """Logistic regression on the element-wise product of the two vectors of a pair - the + edge feature node2vec found to work best; the fitted model is a dot product with one + weight per dimension. The decay is chosen by ``validate(score)``. + Returns ``(score, validation score, info)``.""" + index = lambda column: torch.as_tensor(pairs[:, column], device=device) + features = unit[index(0)] * unit[index(1)] + targets = np.asarray(labels).reshape(-1, 1) > 0 + + def as_pair_scorer(weight, bias): + return _pair_scorer(lambda left, right: ((left * right) @ weight.T + bias).squeeze(1), unit) + + return fit_logistic(features, targets, 1, device, validate, wrap=as_pair_scorer) diff --git a/benchmarks/cleora_bench/report.py b/benchmarks/cleora_bench/report.py new file mode 100644 index 0000000..8995f07 --- /dev/null +++ b/benchmarks/cleora_bench/report.py @@ -0,0 +1,214 @@ +"""Turns the job files of :mod:`runner` into tables. + +Concern of this module: aggregation and presentation. No number is computed here that +was not measured by a job: the module averages over seeds and splits, chooses between +variants of a method on *validation* scores, ranks, and formats. + +Variants. A row of a table is a *method*; a method may have several variants - a +baseline at its authors' dimensionality and at the benchmark's, Cleora at different +iteration counts. For every (dataset, task, probe) the variant with the best mean +validation score is reported, and the tables say which one it was. +""" + +import glob +import json +import os +from collections import defaultdict + +import numpy as np + +def load_jobs(results): + """All job records under a results directory.""" + jobs = [] + for path in glob.glob(os.path.join(results, "*", "*", "dim*", "seed*", "*.json")): + with open(path) as handle: + jobs.append(json.load(handle)) + return jobs + + +def _probe_records(job): + """Yields ``(probe, validation score, metrics dict)`` for every evaluation in a job: + one per split for node classification, one for link prediction.""" + for probe, record in job.get("probes", {}).items(): + if job["task"] == "nc": + for metrics, chosen in zip(record["metrics"], record["chosen"]): + yield probe, chosen["validation_score"], metrics + else: + yield probe, record["chosen"]["validation_mrr"], record["metrics"] + + +def aggregate(jobs): + """``{(dataset, task, method id, dim): entry}`` where ``entry`` holds, per probe, the + list of validation scores and of metric dictionaries over seeds and splits, plus the + embedding time / memory, the iteration counts Cleora reported, the mean degree of the + graph that was embedded, and failures.""" + table = {} + for job in jobs: + key = (job["dataset"], job["task"], job["method"], job["dim"]) + entry = table.setdefault(key, {"probes": defaultdict(lambda: {"validation": [], "metrics": []}), + "seconds": [], "peak_rss_mb": [], "iterations": [], "degree": None, + "failures": []}) + embedding = job["embedding"] + if embedding["status"] != "ok": + entry["failures"].append(f"{embedding['status']}: {embedding['reason']}") + continue + entry["seconds"].append(embedding["seconds"]) + entry["peak_rss_mb"].append(embedding["peak_rss_mb"]) + entry["degree"] = 2.0 * embedding["edges"] / embedding["nodes"] # of the graph that was embedded + if "iterations" in embedding: + entry["iterations"].append(embedding["iterations"]) + for probe, validation, metrics in _probe_records(job): + entry["probes"][probe]["validation"].append(validation) + entry["probes"][probe]["metrics"].append(metrics) + return table + + +def dump(table, path): + """Every aggregated number as one CSV row (gzip): dataset, task, configuration, dim, + probe, metric, mean, std, runs - plus the embedding seconds and the validation score + as pseudo-metrics. This is the machine-readable form of the result tables.""" + import csv + import gzip + + with gzip.open(path, "wt", newline="") as handle: + writer = csv.writer(handle) + writer.writerow(["dataset", "task", "configuration", "dim", "probe", "metric", "mean", "std", "runs"]) + for (dataset, task, method, dim), entry in sorted(table.items()): + if entry["seconds"]: + writer.writerow([dataset, task, method, dim, "", "embedding_seconds", + f"{np.mean(entry['seconds']):.6g}", f"{np.std(entry['seconds']):.6g}", len(entry["seconds"])]) + for failure in sorted(set(entry["failures"])): + writer.writerow([dataset, task, method, dim, "", failure, "", "", entry["failures"].count(failure)]) + for probe, runs in sorted(entry["probes"].items()): + columns = {"validation": runs["validation"]} + for metrics in runs["metrics"]: + for metric, value in metrics.items(): + columns.setdefault(metric, []).append(value) + for metric, values in sorted(columns.items()): + values = [v for v in values if v == v] + if values: + writer.writerow([dataset, task, method, dim, probe, metric, + f"{np.mean(values):.6g}", f"{np.std(values):.6g}", len(values)]) + + +def select_variant(table, dataset, task, probe, variants): + """Among ``variants`` (``(method id, dim)`` pairs) of one method: the one with the + highest mean validation score for this probe. Returns ``(variant, entry)`` or + ``(None, reasons)`` when none of them produced a result.""" + best, reasons = None, [] + for variant in variants: + entry = table.get((dataset, task) + variant) + if entry is None: + continue + runs = entry["probes"].get(probe) + if not runs or not runs["validation"]: + reasons.extend(entry["failures"]) + continue + score = float(np.mean(runs["validation"])) + if best is None or score > best[0]: + best = (score, variant, entry) + if best is None: + return None, sorted(set(reasons)) + return best[1], best[2] + + +def cell(table, dataset, task, probe, metric, variants): + """Mean and standard deviation of ``metric`` for the selected variant of a method. + Returns a dict with ``mean``, ``std``, ``runs``, ``variant``; or ``failed`` / ``missing``.""" + variant, entry = select_variant(table, dataset, task, probe, variants) + if variant is None: + return {"failed": entry} if entry else {"missing": True} + values = [m[metric] for m in entry["probes"][probe]["metrics"] if metric in m and m[metric] == m[metric]] + if not values: + return {"missing": True} + return {"mean": float(np.mean(values)), "std": float(np.std(values)), "runs": len(values), + "variant": list(variant), "seconds": float(np.mean(entry["seconds"])), + "peak_rss_mb": float(np.mean(entry["peak_rss_mb"]))} + + +def best_training_free(table, dataset, variants, metric="mrr"): + """Dot product or cosine, whichever validates better (per method): the + ``similarity`` pseudo-probe of the link tables.""" + candidates = [] + for probe in ("dot", "cosine"): + variant, entry = select_variant(table, dataset, "lp", probe, variants) + if variant is not None: + candidates.append((float(np.mean(entry["probes"][probe]["validation"])), probe)) + if not candidates: + return cell(table, dataset, "lp", "cosine", metric, variants) + probe = max(candidates)[1] + return dict(cell(table, dataset, "lp", probe, metric, variants), probe=probe) + + +def ranks(cells, higher_is_better=True): + """Rank of every method within one row of a table (1 = best; ties share the mean + rank). Methods without a result get the rank after the last one that has a result.""" + names = list(cells) + values = np.array([cells[n].get("mean", np.nan) for n in names], dtype=np.float64) + present = ~np.isnan(values) + order = -values if higher_is_better else values + result = {} + for i, name in enumerate(names): + if present[i]: + result[name] = 1 + float((order[present] < order[i]).sum()) + 0.5 * float((order[present] == order[i]).sum() - 1) + else: + result[name] = float(present.sum() + 1) + return result + + +def format_cell(value, best, second, digits=3, show_std=True): + if "mean" not in value: + if "failed" in value: + reason = value["failed"][0] if value["failed"] else "failed" + if "timeout" in reason: + return "time limit" + if "memory" in reason: + return "out of memory" + if "skipped" in reason: + return "n/a (size)" + return "failed" + return "–" + text = f"{value['mean']:.{digits}f}" + if show_std and value.get("runs", 1) > 1: + text += f" ± {value['std']:.{digits}f}" + if best is not None and abs(value["mean"] - best) < 0.5 * 10 ** -digits: + return f"**{text}**" + if second is not None and abs(value["mean"] - second) < 0.5 * 10 ** -digits: + return f"{text}" + return text + + +def markdown_table(rows, methods, labels, row_label="Dataset", digits=3, higher_is_better=True, show_std=True): + """``rows``: ``{row name: {method: cell}}``. The best value of a row is bold, the + second best underlined.""" + lines = ["| " + row_label + " | " + " | ".join(labels[m] for m in methods) + " |", + "|---|" + "---:|" * len(methods)] + for name, cells in rows.items(): + means = sorted({round(c["mean"], digits) for c in cells.values() if "mean" in c}, reverse=higher_is_better) + best = means[0] if means else None + second = means[1] if len(means) > 1 else None + lines.append("| " + name + " | " + " | ".join( + format_cell(cells.get(m, {"missing": True}), best, second, digits, show_std) for m in methods) + " |") + return "\n".join(lines) + + +def summary_rows(rows, methods, higher_is_better=True): + """Mean rank, number of wins (ties count) and number of rows with a result, per method. + + Only rows on which at least two of the methods have a result are compared: being the + only method that ran on a graph is not a win, and says nothing about ranks.""" + rank_sum, wins, counted = defaultdict(float), defaultdict(int), defaultdict(int) + used = 0 + for cells in rows.values(): + complete = {m: cells.get(m, {"missing": True}) for m in methods} + if sum("mean" in c for c in complete.values()) < 2: + continue + used += 1 + row_ranks = ranks(complete, higher_is_better) + top = min(row_ranks.values()) + for m in methods: + rank_sum[m] += row_ranks[m] + wins[m] += int(row_ranks[m] == top and "mean" in complete[m]) + counted[m] += int("mean" in complete[m]) + return {m: {"mean_rank": rank_sum[m] / max(used, 1), "wins": wins[m], "results": counted[m], "rows": used} + for m in methods} diff --git a/benchmarks/cleora_bench/runner.py b/benchmarks/cleora_bench/runner.py new file mode 100644 index 0000000..4dd11dc --- /dev/null +++ b/benchmarks/cleora_bench/runner.py @@ -0,0 +1,135 @@ +"""Runs (dataset, method, dimension, seed, task) jobs and stores one JSON file per job. + +Concern of this module: orchestration - which jobs exist, where their files live, when +a job is skipped, what is recorded when one fails. The protocol is in :mod:`tasks`, the +methods in :mod:`methods`. + +Layout under the results directory:: + + //dim/seed/nc.json node classification + //dim/seed/lp.json link prediction / similarity ranking + //dim/seed/sample.npz vectors of up to VISUALISATION_NODES nodes + (seed 0, whole graph), for the UMAP figures + //dim/seed/viz.json record of the run that produced sample.npz + for a graph without node labels + //dim/seed/time.json time and peak memory of embedding the whole + graph, measured on an otherwise idle machine + +Every job is resumable: a finished job is never recomputed, a failed one records why +(time limit, out of memory, the error) and is retried only with ``retry_failed``. +""" + +import json +import os +import shutil +import tempfile +import time + +import numpy as np + +from . import datasets, embed_worker, methods, tasks + +VISUALISATION_NODES = 30_000 + + +def job_directory(results, dataset, method_id, dim, seed): + return os.path.join(results, dataset, method_id, f"dim{dim}", f"seed{seed}") + + +def _write_json(path, payload): + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path + ".tmp", "w") as handle: + json.dump(payload, handle, indent=1, default=float) + os.replace(path + ".tmp", path) + + +def link_split(graph, seed, cache): + """The link split of (dataset, seed): drawn once, then shared by every method.""" + path = os.path.join(cache, graph["meta"]["name"], f"link_split_seed{seed}.npz") + if not os.path.exists(path): + os.makedirs(os.path.dirname(path), exist_ok=True) + split = tasks.link_split(graph, seed) + # several processes may draw the same (deterministic) split at once: each writes + # its own temporary file, and whichever finishes last puts an identical one in place + temporary = f"{path}.{os.getpid()}.tmp.npz" + np.savez(temporary, **split) + os.replace(temporary, path) + with np.load(path) as archive: + return {key: archive[key] for key in archive.files} + + +def _save_sample(directory, vectors): + """A fixed random sample of the nodes with their vectors, for the figures.""" + rows = np.sort(np.random.default_rng(0).choice(len(vectors), min(len(vectors), VISUALISATION_NODES), replace=False)) + np.savez(os.path.join(directory, "sample.npz"), rows=rows, vectors=vectors[rows].astype(np.float16)) + + +def embed(method, params, edges, num_nodes, weights, dim, seed, threads, work, timeout): + """Runs the method on the nodes of ``edges`` that have an edge. Returns + ``(vectors in the numbering of the caller or None, record)``.""" + compact_edges, ids = tasks.compact(edges, num_nodes) + graph_path = os.path.join(work, "graph.npz") + extra = {} if weights is None else {"weights": weights} + np.savez(graph_path, edges=compact_edges, num_nodes=len(ids), **extra) + out, stats = os.path.join(work, "vectors.npy"), os.path.join(work, "stats.json") + limit = methods.METHODS[method][3] + if limit is not None and len(ids) > limit: + return None, {"status": "skipped", "reason": f"this implementation is limited to {limit} nodes"} + started = time.time() + failure = embed_worker.run(method, graph_path, dim, seed, threads, out, stats, params=params, timeout=timeout) + if failure is not None: + return None, {"status": "failed", "reason": failure, "seconds_until_failure": time.time() - started} + with open(stats) as handle: + record = dict(json.load(handle), status="ok", nodes=int(len(ids)), edges=int(len(compact_edges))) + return tasks.expand(np.load(out), ids, num_nodes), record + + +def run_job(dataset, method_id, method, params, dim, seed, task, *, data_root, results, cache, threads, timeout, + device, node_probes=tasks.NODE_PROBES, pair_probes=tasks.PAIR_PROBES, split_seeds=(0, 1, 2), + retry_failed=False): + """Runs one job unless its result exists. Returns the result dictionary.""" + directory = job_directory(results, dataset, method_id, dim, seed) + path = os.path.join(directory, f"{task}.json") + if os.path.exists(path): + with open(path) as handle: + previous = json.load(handle) + if previous["embedding"]["status"] != "failed" or not retry_failed: + return previous + + graph = datasets.load(dataset, data_root) + num_nodes = graph["meta"]["num_nodes"] + result = {"dataset": dataset, "method": method_id, "implementation": method, "params": params, "dim": dim, + "seed": seed, "task": task, "nodes": num_nodes, "edges": graph["meta"]["num_edges"]} + os.makedirs(cache, exist_ok=True) + os.makedirs(directory, exist_ok=True) + work = tempfile.mkdtemp(prefix=f"{dataset}_{method_id}_", dir=cache) + try: + if task == "nc": + if "labels" not in graph: + raise ValueError(f"{dataset} has no node labels: it supports the link task only") + vectors, result["embedding"] = embed(method, params, graph["edges"], num_nodes, graph.get("weights"), + dim, seed, threads, work, timeout) + if vectors is not None: + result["probes"] = tasks.node_classification(vectors, graph, device, split_seeds, node_probes) + if seed == 0: + _save_sample(directory, vectors) + elif task in ("viz", "time"): + # the whole graph is embedded and nothing is evaluated: "viz" keeps a sample of the + # vectors of a graph without labels, "time" only the time and memory the method took + vectors, result["embedding"] = embed(method, params, graph["edges"], num_nodes, graph.get("weights"), + dim, seed, threads, work, timeout) + if vectors is not None and task == "viz": + _save_sample(directory, vectors) + elif task == "lp": + split = link_split(graph, seed, cache) + # edge weights are not carried into the link task: the split is over unweighted edges + vectors, result["embedding"] = embed(method, params, split["embed"], num_nodes, None, + dim, seed, threads, work, timeout) + if vectors is not None: + result["probes"] = tasks.link_prediction(vectors, split, graph, device, seed, pair_probes) + else: + raise ValueError(f"Unknown task '{task}'. Use 'nc', 'lp', 'viz' or 'time'.") + finally: + shutil.rmtree(work, ignore_errors=True) + _write_json(path, result) + return result diff --git a/benchmarks/cleora_bench/selection.py b/benchmarks/cleora_bench/selection.py new file mode 100644 index 0000000..94b1c42 --- /dev/null +++ b/benchmarks/cleora_bench/selection.py @@ -0,0 +1,65 @@ +"""Which fixed-iteration Cleora configurations make up the "tuned" rows. + +Concern of this module: choosing the number of iterations from the sweep. For every +dataset, task and family (setup x normalisation) the iteration count with the best +*validation* score of the sweep is kept; test scores are never read here. + +The sweep is a cheap pass (one seed, one probe per task: ``SWEEP_PROBE``); the chosen +iteration counts are then run like every other method, with all probes and seeds, as +the configuration of the task's purpose (``configurations.for_purpose``). +""" + +import json +import os + +import numpy as np + +from . import configurations, display, report + +SWEEP_PROBE = {"nc": "logistic", "lp": "cosine"} +SWEEP_DIRECTORY = "sweep" +SELECTION_FILE = "selected_iterations.json" +TUNED = "cleora_tuned" # in a list of methods: "the configurations chosen for this dataset" + + +def choose(sweep_results): + """``{dataset: {task: {family: configuration to run}}}`` from the job files of a sweep.""" + table = report.aggregate(report.load_jobs(sweep_results)) + chosen = {} + for setup in configurations.SETUPS: + for propagation in ("left", "sym"): + family = f"{setup}/{propagation}" + for name in configurations.sweep(setup, propagation): + for (dataset, task, method, _dim), entry in table.items(): + if method != name or task not in SWEEP_PROBE: + continue + scores = entry["probes"].get(SWEEP_PROBE[task], {}).get("validation", []) + if not scores: + continue + best = chosen.setdefault(dataset, {}).setdefault(task, {}).get(family) + score = float(np.mean(scores)) + if best is None or score > best[1]: + chosen[dataset][task][family] = (name, score) + return {dataset: {task: {family: configurations.for_purpose(name, display.TASK_PURPOSE[task]) + for family, (name, _) in families.items()} for task, families in tasks.items()} + for dataset, tasks in chosen.items()} + + +def write(data): + chosen = choose(os.path.join(data, SWEEP_DIRECTORY)) + with open(os.path.join(data, SELECTION_FILE), "w") as handle: + json.dump(chosen, handle, indent=1, sort_keys=True) + return chosen + + +def load(data): + path = os.path.join(data, SELECTION_FILE) + if not os.path.exists(path): + return {} + with open(path) as handle: + return json.load(handle) + + +def configurations_for(data, dataset, task): + """Names of the configurations chosen for a dataset and task (one per family), sorted.""" + return sorted(set(load(data).get(dataset, {}).get(task, {}).values())) diff --git a/benchmarks/cleora_bench/tasks.py b/benchmarks/cleora_bench/tasks.py new file mode 100644 index 0000000..5d6bcc2 --- /dev/null +++ b/benchmarks/cleora_bench/tasks.py @@ -0,0 +1,444 @@ +"""Evaluation tasks: what is predicted from the vectors, on which split, against which +candidates. + +Concern of this module: the experimental protocol. It draws the splits and the negative +candidates (the same for every method), calls the probes and hands their scores to +``pycleora.metrics``. It does not know how the vectors were made. + +Node classification (graphs with node labels) + The vectors come from the whole graph (labels are never used to make them). Labelled + nodes are split into train / validation / test - the dataset's official split when it + has one, otherwise ``NODE_SPLIT`` stratified random splits. Every probe is fitted on + train, tuned on validation and scored once on test. + +Link prediction and similarity ranking (every graph) + Edges are split at random into four disjoint sets (``LINK_SPLIT``): + + * ``embed`` - the only edges the embedding method sees; + * ``probe`` - positives for training the pair probes. They are *not* in the embedding + graph: a probe trained on edges the vectors were fitted to would learn + to recognise memorised edges, not to predict missing ones; + * ``valid`` - positives for model selection; + * ``test`` - positives for the reported numbers. + + Every validation / test positive ``(u, v)`` is ranked, in both directions, against + ``NEGATIVES_PER_POSITIVE`` random nodes that are not neighbours of the query (in + the full graph). All methods and all probes are ranked against the same candidates. + Training-free scores (dot product, cosine) are additionally ranked against *all* + nodes ("retrieval"), which is what nearest-neighbour search over the vectors does. + + Datasets with an official link split (OGB) keep their official positives and + negatives; only the probe positives are taken out of the official training edges. + Retrieval among all nodes is measured on their official test positives as well. +""" + +import numpy as np + +from pycleora import metrics + +from . import probes + +NODE_SPLIT = {"train": 0.10, "valid": 0.10} # the rest is test +LINK_SPLIT = {"probe": 0.10, "valid": 0.05, "test": 0.10} # the rest is embed +LINK_CAPS = {"probe": 500_000, "valid": 20_000, "test": 50_000} # positives, on large graphs +NEGATIVES_PER_POSITIVE = 500 +PROBE_NEGATIVES_PER_POSITIVE = 3 +SELECTION_ROWS, SELECTION_NEGATIVES = 1000, 100 # part of validation the trained pair probe is selected on +# Training pairs of the trained pair probe: their features (pairs x dimensions) are held in +# memory at once, and a linear model in the dimensions of the embedding needs no more. +PAIR_LINEAR_ROWS = 1_000_000 +RETRIEVAL_QUERIES = 10_000 +RETRIEVAL_DEPTH = 50 +NODE_PROBES = ("logistic", "mlp") +PAIR_PROBES = ("dot", "cosine", "logistic") + + +# ----------------------------------------------------------------------------- graph helpers + + +def neighbour_lists(edges, num_nodes): + """CSR adjacency (``indptr``, ``indices``; neighbours sorted) of an undirected edge list.""" + sources = np.concatenate([edges[:, 0], edges[:, 1]]) + targets = np.concatenate([edges[:, 1], edges[:, 0]]) + order = np.lexsort((targets, sources)) + indptr = np.zeros(num_nodes + 1, dtype=np.int64) + np.add.at(indptr, sources + 1, 1) + return np.cumsum(indptr), targets[order] + + +def edge_keys(edges, num_nodes): + """Sorted keys ``u * num_nodes + v`` of both directions of every edge.""" + keys = np.concatenate([edges[:, 0] * num_nodes + edges[:, 1], edges[:, 1] * num_nodes + edges[:, 0]]) + keys.sort() + return keys + + +def _is_edge(keys, num_nodes, sources, targets): + """Whether ``(sources[i], targets[i])`` is an edge, by binary search in ``edge_keys``.""" + wanted = sources.astype(np.int64) * num_nodes + targets + position = np.minimum(np.searchsorted(keys, wanted), len(keys) - 1) + return keys[position] == wanted + + +def compact(edges, num_nodes): + """The edge list restricted to nodes that have an edge: ``(edges with new ids, ids)``, + where ``ids[new] = old``. Embedding methods are only ever given such graphs.""" + present = np.zeros(num_nodes, dtype=bool) + present[edges.ravel()] = True + new_id = np.cumsum(present) - 1 + return new_id[edges], np.flatnonzero(present) + + +def expand(vectors, ids, num_nodes): + """Vectors of a compacted graph back in the original numbering (zero rows for the + nodes that had no edge).""" + out = np.zeros((num_nodes, vectors.shape[1]), dtype=np.float32) + out[ids] = vectors + return out + + +# ----------------------------------------------------------------------------- node classification + + +def node_splits(graph, seeds): + """Yields ``(train, valid, test)`` index arrays: the official split once, or one + stratified random split per seed.""" + if "split_train" in graph: + yield graph["split_train"], graph["split_valid"], graph["split_test"] + return + labels = graph["labels"] + multilabel = labels.ndim == 2 + labelled = np.flatnonzero(labels.any(axis=1) if multilabel else labels >= 0) + for seed in seeds: + rng = np.random.default_rng(seed) + groups = [labelled] if multilabel else [labelled[labels[labelled] == c] for c in np.unique(labels[labelled])] + parts = ([], [], []) + for group in groups: + group = rng.permutation(group) + # every class keeps at least one training example + train_end = max(1, int(round(NODE_SPLIT["train"] * len(group)))) + valid_end = train_end + int(round(NODE_SPLIT["valid"] * len(group))) + for part, rows in zip(parts, (group[:train_end], group[train_end:valid_end], group[valid_end:])): + part.append(rows) + yield tuple(np.concatenate(part) for part in parts) + + +def _node_metrics(labels, scores): + if labels.ndim == 2: + return metrics.multilabel_metrics(labels, scores) + return metrics.classification_metrics(labels, scores) + + +def node_classification(vectors, graph, device, seeds, which=NODE_PROBES): + """Fits every node probe on every split. Returns + ``{probe: {"metrics": [one dict per split], "chosen": [hyper-parameters per split]}}``.""" + labels = graph["labels"] + multilabel = labels.ndim == 2 + num_classes = labels.shape[1] if multilabel else int(labels.max()) + 1 + results = {probe: {"metrics": [], "chosen": []} for probe in which} + linear_device = probes.device_for(vectors.size, device) + + for split_number, (train, valid, test) in enumerate(node_splits(graph, seeds)): + if not multilabel: # official splits may contain unlabelled nodes + train, valid, test = (rows[labels[rows] >= 0] for rows in (train, valid, test)) + y_train, y_valid, y_test = labels[train], labels[valid], labels[test] + validate_on = lambda features: (lambda predict: probes.selection_score(predict(features), y_valid)) + + def scaled(scaling): + scale = probes.scaler(scaling, vectors[train]) + return scale(vectors[train]), scale(vectors[valid]), scale(vectors[test]) + + best = {} + if "logistic" in which: + # scaling and decay chosen together on validation + for scaling in probes.SCALINGS: + x_train, x_valid, x_test = scaled(scaling) + predict, score, info = probes.fit_logistic(x_train, y_train, num_classes, linear_device, + validate_on(x_valid)) + if "logistic" not in best or score > best["logistic"][0]: + best["logistic"] = (score, predict(x_test), dict(info, scaling=scaling, validation_score=score)) + if "mlp" in which: + # the scaling the logistic probe preferred (standardisation if it was not run) + scaling = best["logistic"][2]["scaling"] if "logistic" in best else "standard" + x_train, x_valid, x_test = scaled(scaling) + predict, score, info = probes.fit_mlp(x_train, y_train, num_classes, device, split_number, + validate_on(x_valid)) + best["mlp"] = (score, predict(x_test), dict(info, scaling=scaling, validation_score=score)) + for probe in which: + results[probe]["metrics"].append(_node_metrics(y_test, best[probe][1])) + results[probe]["chosen"].append({k: v for k, v in best[probe][2].items() if k != "validation"}) + return results + + +# ----------------------------------------------------------------------------- link prediction: the split + + +def _sample_negative_targets(rng, sources, keys, num_nodes, count, low, high): + """``count`` random nodes from ``[low[i], high[i])`` per source that are neither the + source nor one of its neighbours (-1 where none could be drawn in a few attempts).""" + span = (high - low)[:, None] + negatives = low[:, None] + (rng.random((len(sources), count)) * span).astype(np.int64) + for _ in range(8): + flat_sources = np.repeat(sources, count) + bad = (_is_edge(keys, num_nodes, flat_sources, negatives.ravel()) | + (negatives.ravel() == flat_sources)).reshape(negatives.shape) + if not bad.any(): + break + redraw = low[:, None] + (rng.random(negatives.shape) * span).astype(np.int64) + negatives = np.where(bad, redraw, negatives) + else: + negatives[bad] = -1 + return negatives.astype(np.int32) + + +def _both_directions(pairs): + """``(sources, targets)`` of every pair read in both directions.""" + return np.concatenate([pairs[:, 0], pairs[:, 1]]), np.concatenate([pairs[:, 1], pairs[:, 0]]) + + +def _candidate_ranges(graph, targets): + """The id range negatives for these targets are drawn from: all nodes, or - in a + bipartite graph - the side the true target is on.""" + num_nodes = graph["meta"]["num_nodes"] + if "num_left" not in graph: + return np.zeros(len(targets), dtype=np.int64), np.full(len(targets), num_nodes, dtype=np.int64) + num_left = int(graph["num_left"]) + on_left = targets < num_left + return np.where(on_left, 0, num_left), np.where(on_left, num_left, num_nodes) + + +def link_split(graph, seed): + """Draws the link-prediction split of a graph (deterministic in ``seed``). + + Returns a dict of arrays: ``embed`` (edges for the embedding method), ``probe_pairs`` + with ``probe_labels`` (training pairs of the pair probes), and for ``valid`` / ``test`` + either ``{part}_queries`` + ``{part}_targets`` + ``{part}_negatives`` (one row per + ranking problem) or, for official splits with one shared list of negative pairs, + ``{part}_pos`` + ``{part}_neg``. + """ + rng = np.random.default_rng(seed) + num_nodes = graph["meta"]["num_nodes"] + official = graph["meta"]["official_link_split"] + edges = graph["edges"] + order = rng.permutation(len(edges)) + + def take(name, pool_size): + nonlocal order + size = min(int(round(LINK_SPLIT[name] * pool_size)), LINK_CAPS[name]) + chosen, order = order[:size], order[size:] + return edges[chosen] + + split = {"probe": take("probe", len(edges))} + held_out = [split["probe"]] + if official: + # all true edges, for drawing negatives of the probe: train + official positives + known = [edges] + [graph[f"lp_{part}_pos"] for part in ("valid", "test")] + else: + split["valid"], split["test"] = take("valid", len(edges)), take("test", len(edges)) + held_out += [split["valid"], split["test"]] + known = [edges] + split["embed"] = edges[order] + keys = edge_keys(np.concatenate(known), num_nodes) + + # Nodes without an edge in the embedding graph get no vector: pairs that touch one + # cannot be ranked by any method and are left out (the same pairs for every method). + embedded = np.zeros(num_nodes, dtype=bool) + embedded[split["embed"].ravel()] = True + usable = lambda pairs: pairs[embedded[pairs].all(axis=1)] + + result = {"embed": split["embed"], "embedded": embedded} + + probe = usable(split["probe"]) + sources, targets = _both_directions(probe) + low, high = _candidate_ranges(graph, targets) + negatives = _sample_negative_targets(rng, sources, keys, num_nodes, PROBE_NEGATIVES_PER_POSITIVE, low, high) + negative_sources = np.repeat(sources, PROBE_NEGATIVES_PER_POSITIVE) + keep = (negatives.ravel() >= 0) & embedded[np.maximum(negatives.ravel(), 0)] + result["probe_pairs"] = np.concatenate([ + np.stack([sources, targets], axis=1), + np.stack([negative_sources[keep], negatives.ravel()[keep].astype(np.int64)], axis=1)]) + result["probe_labels"] = np.concatenate([np.ones(len(sources), np.float32), np.zeros(int(keep.sum()), np.float32)]) + + for part in ("valid", "test"): + if official and f"lp_{part}_neg" in graph: + result[f"{part}_pos"] = usable(graph[f"lp_{part}_pos"]) + result[f"{part}_neg"] = usable(graph[f"lp_{part}_neg"]) + continue + if official: # ogbl-citation2: the official negatives of every (source, target) + positives = graph[f"lp_{part}_pos"] + keep = embedded[positives].all(axis=1) + if keep.sum() > LINK_CAPS[part]: + keep &= np.isin(np.arange(len(keep)), rng.choice(np.flatnonzero(keep), LINK_CAPS[part], replace=False)) + negatives = graph[f"lp_{part}_target_neg"][keep].astype(np.int64) + negatives[~embedded[np.maximum(negatives, 0)]] = -1 + result[f"{part}_queries"], result[f"{part}_targets"] = positives[keep, 0], positives[keep, 1] + result[f"{part}_negatives"] = negatives.astype(np.int32) + continue + sources, targets = _both_directions(usable(split[part])) + low, high = _candidate_ranges(graph, targets) + negatives = _sample_negative_targets(rng, sources, keys, num_nodes, NEGATIVES_PER_POSITIVE, low, high) + negatives[~embedded[np.maximum(negatives, 0)]] = -1 + result[f"{part}_queries"], result[f"{part}_targets"], result[f"{part}_negatives"] = sources, targets, negatives + return result + + +# ----------------------------------------------------------------------------- link prediction: the evaluation + + +def _candidate_ranks(score, queries, targets, negatives, rows=4096): + """Rank of every target among its own negatives (absent ones, -1, are ignored).""" + ranks = [] + for start in range(0, len(queries), rows): + block = negatives[start:start + rows].astype(np.int64) + block_queries = queries[start:start + rows] + candidate_scores = score(np.repeat(block_queries, block.shape[1]), np.maximum(block, 0).ravel()) + candidate_scores = candidate_scores.astype(np.float64).reshape(block.shape) + candidate_scores[block < 0] = np.nan + ranks.append(metrics.ranks_among(score(block_queries, targets[start:start + rows]), candidate_scores)) + return np.concatenate(ranks) if ranks else np.zeros(0) + + +def _shared_negative_ranks(positive_scores, negative_scores): + """Rank of every positive pair among one shared list of negative pairs.""" + ordered = np.sort(negative_scores.astype(np.float64)) + right = np.searchsorted(ordered, positive_scores, side="right") + left = np.searchsorted(ordered, positive_scores, side="left") + return 1.0 + (len(ordered) - right) + 0.5 * (right - left) + + +def _evaluate_scorer(score, split, part, limit=None): + """Ranking and binary metrics of a pair scorer on ``part`` ('valid' or 'test').""" + if f"{part}_pos" in split: + positives, negatives = split[f"{part}_pos"], split[f"{part}_neg"] + if limit is not None: # an evenly spaced subset + thin = lambda pairs, size: pairs[np.linspace(0, len(pairs) - 1, min(size, len(pairs))).astype(np.int64)] + positives, negatives = thin(positives, limit[0]), thin(negatives, limit[0] * limit[1]) + positive_scores = score(positives[:, 0], positives[:, 1]).astype(np.float64) + negative_scores = score(negatives[:, 0], negatives[:, 1]).astype(np.float64) + ranks = _shared_negative_ranks(positive_scores, negative_scores) + result = metrics.ranking_metrics(ranks, ks=(1, 10, 20, 50, 100)) + else: + queries, targets, negatives = (split[f"{part}_{name}"] for name in ("queries", "targets", "negatives")) + if limit is not None: + queries, targets, negatives = queries[:limit[0]], targets[:limit[0]], negatives[:limit[0], :limit[1]] + ranks = _candidate_ranks(score, queries, targets, negatives) + result = metrics.ranking_metrics(ranks, ks=(1, 3, 10, 50, 100)) + # binary view: every positive against its first existing negative + first = negatives[:, 0].astype(np.int64) + exists = first >= 0 + positive_scores = score(queries[exists], targets[exists]).astype(np.float64) + negative_scores = score(queries[exists], first[exists]).astype(np.float64) + labels = np.concatenate([np.ones(len(positive_scores), bool), np.zeros(len(negative_scores), bool)]) + both = np.concatenate([positive_scores, negative_scores]) + result["roc_auc"] = metrics.roc_auc(labels, both) + result["average_precision"] = metrics.average_precision(labels, both) + result["num_ranked"] = int(len(ranks)) + return result + + +def _retrieval(vectors_on_device, split, graph, seed, part="test"): + """Ranks the targets of ``part`` ('test' or 'valid') of sampled query nodes against + *all* nodes of the graph with a training-free score (the rows of + ``vectors_on_device`` are compared by dot product). Known neighbours other than + these targets are removed from the candidates. + + The queries are those of the candidate ranking; a split that comes as one official + list of positive pairs has every distinct pair queried from both of its ends. + + Returns MRR / Hits@k of the individual edges and Recall / NDCG / MAP of the + top-``RETRIEVAL_DEPTH`` list of every query node. + """ + import torch + + num_nodes = graph["meta"]["num_nodes"] + if f"{part}_queries" in split: + queries_all, targets_all = split[f"{part}_queries"], split[f"{part}_targets"] + else: + queries_all, targets_all = np.unique(np.stack(_both_directions(split[f"{part}_pos"]), axis=1), axis=0).T + rng = np.random.default_rng(seed) + nodes = np.unique(queries_all) + if len(nodes) > RETRIEVAL_QUERIES: + nodes = np.sort(rng.choice(nodes, RETRIEVAL_QUERIES, replace=False)) + selected = np.isin(queries_all, nodes) + queries, targets = queries_all[selected], targets_all[selected] + known = neighbour_lists(graph["edges"], num_nodes) if not graph["meta"]["official_link_split"] else \ + neighbour_lists(np.concatenate([graph["edges"], graph["lp_valid_pos"], graph["lp_test_pos"]]), num_nodes) + indptr, indices = known + device = vectors_on_device.device + embedded = torch.as_tensor(split["embedded"], device=device) + side = None + if "num_left" in graph: + side = torch.arange(num_nodes, device=device) < int(graph["num_left"]) + + order = np.argsort(queries, kind="stable") + queries, targets = queries[order], targets[order] + starts = np.flatnonzero(np.concatenate([[True], queries[1:] != queries[:-1]])) + ends = np.concatenate([starts[1:], [len(queries)]]) + ranks = np.zeros(len(queries)) + hits = np.zeros((len(starts), RETRIEVAL_DEPTH), dtype=bool) + for first in range(0, len(starts), 256): + group = slice(first, min(first + 256, len(starts))) + nodes_here = queries[starts[group]] + scores = vectors_on_device[torch.as_tensor(nodes_here, device=device)] @ vectors_on_device.T + scores[:, ~embedded] = -float("inf") + for local, node in enumerate(nodes_here): + relevant = torch.as_tensor(targets[starts[first + local]:ends[first + local]], device=device) + relevant_scores = scores[local, relevant].clone() + scores[local, torch.as_tensor(indices[indptr[node]:indptr[node + 1]], device=device)] = -float("inf") + scores[local, node] = -float("inf") + if side is not None: # only the other side of a bipartite graph can be recommended + scores[local, side == side[node]] = -float("inf") + # rank of every test target among the non-neighbours (ties: half a place) + above = (scores[local][None, :] > relevant_scores[:, None]).sum(dim=1) + equal = (scores[local][None, :] == relevant_scores[:, None]).sum(dim=1) + ranks[starts[first + local]:ends[first + local]] = (1 + above + 0.5 * equal).cpu().numpy() + scores[local, relevant] = relevant_scores + top = scores[local].topk(RETRIEVAL_DEPTH).indices + hits[first + local] = torch.isin(top, relevant).cpu().numpy() + result = {f"all_nodes_{name}": value for name, value in metrics.ranking_metrics(ranks, ks=(1, 10, 100)).items()} + result.update(metrics.retrieval_metrics(hits, ends - starts, ks=(10, 20, 50))) + result["num_queries"] = int(len(starts)) + return result + + +def validation_scores(vectors, split, graph, device, seed): + """What the dot product of ``vectors`` scores on the *validation* edges: the metrics + against the sampled candidates and those of the retrieval among all nodes. For + choosing between ways of making vectors without looking at the test edges.""" + matrix = probes.to_device(vectors, device) + scores = _evaluate_scorer(probes.product_scorer(matrix), split, "valid") + scores.update(_retrieval(matrix, split, graph, seed, part="valid")) + return scores + + +def link_prediction(vectors, split, graph, device, seed, which=PAIR_PROBES): + """Scores every pair probe on the test part of a link split. Returns + ``{probe: {"metrics": {...}, "chosen": {...}}}``; the training-free probes also carry + the all-nodes retrieval metrics.""" + # Scoring candidates means millions of vector products: everything in this task runs + # on the accelerator when there is one. + unit = probes.unit_vectors(vectors, device) + selection = (SELECTION_ROWS, SELECTION_NEGATIVES) + validate = lambda score: _evaluate_scorer(score, split, "valid", limit=selection)["mrr"] + pairs, labels = split["probe_pairs"], split["probe_labels"] + linear_rows = np.arange(len(pairs)) + if len(pairs) > PAIR_LINEAR_ROWS: + linear_rows = np.sort(np.random.default_rng(seed).choice(len(pairs), PAIR_LINEAR_ROWS, replace=False)) + results = {} + for probe in which: + if probe in ("dot", "cosine"): + matrix = probes.to_device(vectors, device) if probe == "dot" else unit + score = probes.product_scorer(matrix) + chosen = {"validation_mrr": _evaluate_scorer(score, split, "valid")["mrr"]} + test = _evaluate_scorer(score, split, "test") + test.update(_retrieval(matrix, split, graph, seed)) + del matrix, score + elif probe == "logistic": + score, validation, info = probes.fit_pair_logistic(unit, pairs[linear_rows], labels[linear_rows], + device, validate) + chosen = {"decay": info["decay"], "validation_mrr": validation} + test = _evaluate_scorer(score, split, "test") + else: + raise ValueError(f"Unknown pair probe '{probe}'") + results[probe] = {"metrics": test, "chosen": chosen} + return results diff --git a/benchmarks/envs/karate.txt b/benchmarks/envs/karate.txt new file mode 100644 index 0000000..7b6d3dc --- /dev/null +++ b/benchmarks/envs/karate.txt @@ -0,0 +1,20 @@ +# Environment "karate" (Python 3.10): GraRep, HOPE and Walklets from karateclub 1.3.3, +# with the dependency versions that release was made against. karateclub itself is +# installed without dependencies by benchmarks/setup.sh (its metadata pins are stricter +# than what its code needs). +numpy==1.22.4 +scipy==1.8.1 +networkx==2.6.3 +gensim==4.2.0 +scikit-learn==1.1.3 +pandas==1.3.5 +pygsp==0.5.1 +python-louvain==0.16 +decorator==4.4.2 +python-Levenshtein==0.27.4 +tqdm==4.70.1 +six==1.17.0 +smart-open==9.0.5 +joblib==1.6.0 +threadpoolctl==3.8.0 +psutil==7.2.2 diff --git a/benchmarks/envs/main.lock-linux-x86_64-cuda13.txt b/benchmarks/envs/main.lock-linux-x86_64-cuda13.txt new file mode 100644 index 0000000..6d4f0a1 --- /dev/null +++ b/benchmarks/envs/main.lock-linux-x86_64-cuda13.txt @@ -0,0 +1,92 @@ +aiohappyeyeballs==2.7.1 +aiohttp==3.14.5 +aiosignal==1.4.0 +anyio==4.16.0 +attrs==26.1.0 +certifi==2026.10.23 +charset-normalizer==3.5.2 +click==8.5.1 +cloudpickle==3.1.3 +contourpy==1.4.0 +cuda-bindings==13.5.0 +cuda-pathfinder==1.9.0 +cuda-toolkit==13.2.2 +cycler==0.12.1 +filelock==4.2.12 +fonttools==4.68.0 +frozenlist==1.8.0 +fsspec==2026.9.0 +gensim==4.4.0 +h11==0.16.0 +hf-xet==1.8.0 +httpcore2==2.16.2 +httpx2==2.16.2 +huggingface-hub==2.4.0 +idna==3.20 +iniconfig==2.3.1 +jinja2==3.1.6 +joblib==1.6.0 +kiwisolver==1.5.1 +littleutils==0.2.4 +llvmlite==0.50.0 +markupsafe==3.0.4 +matplotlib==3.11.2 +maturin==1.16.0 +mpmath==1.3.0 +multidict==7.2.1 +narwhals==2.29.0 +networkx==3.7 +numba==0.68.1 +numpy==2.5.5 +nvidia-cublas==13.4.1.3 +nvidia-cuda-cccl==13.3.5.0.6 +nvidia-cuda-cupti==13.2.86 +nvidia-cuda-nvrtc==13.2.86 +nvidia-cuda-runtime==13.2.86 +nvidia-cudnn-cu13==9.26.0.51 +nvidia-cufft==12.2.0.57 +nvidia-cufile==1.17.1.22 +nvidia-cusolver==12.2.0.11 +nvidia-cusparse==12.7.10.12 +nvidia-cusparselt-cu13==0.8.1 +nvidia-nccl-cu13==2.30.7 +nvidia-nvjitlink==13.5.37 +nvidia-nvshmem-cu13==3.7.2 +nvidia-nvtx==13.2.86 +ogb==1.3.6 +outdated==0.2.2 +packaging==26.3 +pandas==3.1.1 +pillow==13.0.0 +pluggy==1.7.0 +propcache==0.5.4 +psutil==7.2.2 +pygments==2.21.0 +pynndescent==0.7.0 +pyparsing==3.3.3 +pytest==9.2.0 +python-dateutil==4.0.0 +pyyaml==6.0.3 +requests==2.34.2 +safetensors==0.8.0 +scikit-learn==1.9.1 +scipy==1.18.1 +setuptools==84.2.1 +six==1.17.0 +smart-open==9.0.5 +sympy==1.14.0 +threadpoolctl==3.8.0 +timm==1.0.31 +torch==2.15.0 +torch-geometric==2.8.1 +torchvision==0.29.2 +tqdm==4.70.1 +triton==3.9.0 +truststore==0.10.5 +typing-extensions==4.16.0 +tzdata==2026.6 +umap-learn==0.6.0 +urllib3==2.8.0 +wrapt==2.5.2 +xxhash==4.1.0 +yarl==1.25.1 diff --git a/benchmarks/envs/main.txt b/benchmarks/envs/main.txt new file mode 100644 index 0000000..539bc32 --- /dev/null +++ b/benchmarks/envs/main.txt @@ -0,0 +1,21 @@ +# Environment "main" (Python 3.12): pycleora, the probes, the report and the figures, +# and the baselines that run on current NumPy / SciPy (ProNE, NetMF, FastRP, RandNE). +# pycleora itself is built from this repository by benchmarks/setup.sh. +numpy==2.5.5 +scipy==1.18.1 +scikit-learn==1.9.1 +pandas==3.1.1 +matplotlib==3.11.2 +networkx==3.7 +torch==2.15.0 +torch-geometric==2.8.1 +ogb==1.3.6 +timm==1.0.31 +gensim==4.4.0 # imported by the FastRP reference code +umap-learn==0.6.0 +pynndescent==0.7.0 +numba==0.68.1 +tqdm==4.70.1 +requests==2.34.2 +psutil==7.2.2 +threadpoolctl==3.8.0 diff --git a/benchmarks/envs/walks.txt b/benchmarks/envs/walks.txt new file mode 100644 index 0000000..c2fa038 --- /dev/null +++ b/benchmarks/envs/walks.txt @@ -0,0 +1,15 @@ +# Environment "walks" (Python 3.11): DeepWalk and node2vec = PecanPy walks + gensim skip-gram. +# PecanPy 2.0.9 depends on nptyping, which needs NumPy < 2. +numpy==1.26.4 +scipy==1.13.1 +numba==0.60.0 +llvmlite==0.43.0 +gensim==4.3.3 +pecanpy==2.0.9 +nptyping==2.5.0 +numba-progress==1.2.0 +smart-open==9.0.5 +tqdm==4.70.1 +typing-extensions==4.16.0 +wrapt==2.5.2 +psutil==7.2.2 diff --git a/benchmarks/figures/summary_dark.svg b/benchmarks/figures/summary_dark.svg new file mode 100644 index 0000000..eb40c7c --- /dev/null +++ b/benchmarks/figures/summary_dark.svg @@ -0,0 +1,2124 @@ + + + + + + + + image/svg+xml + + + Matplotlib v3.10.8, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/benchmarks/figures/summary_light.svg b/benchmarks/figures/summary_light.svg new file mode 100644 index 0000000..8ce1831 --- /dev/null +++ b/benchmarks/figures/summary_light.svg @@ -0,0 +1,2124 @@ + + + + + + + + image/svg+xml + + + Matplotlib v3.10.8, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/benchmarks/figures/umap_amazon_computers.png b/benchmarks/figures/umap_amazon_computers.png new file mode 100644 index 0000000..a01be9e Binary files /dev/null and b/benchmarks/figures/umap_amazon_computers.png differ diff --git a/benchmarks/figures/umap_amazon_photo.png b/benchmarks/figures/umap_amazon_photo.png new file mode 100644 index 0000000..a3078d7 Binary files /dev/null and b/benchmarks/figures/umap_amazon_photo.png differ diff --git a/benchmarks/figures/umap_blogcatalog.png b/benchmarks/figures/umap_blogcatalog.png new file mode 100644 index 0000000..5c8d032 Binary files /dev/null and b/benchmarks/figures/umap_blogcatalog.png differ diff --git a/benchmarks/figures/umap_citeseer.png b/benchmarks/figures/umap_citeseer.png new file mode 100644 index 0000000..90b541f Binary files /dev/null and b/benchmarks/figures/umap_citeseer.png differ diff --git a/benchmarks/figures/umap_coauthor_cs.png b/benchmarks/figures/umap_coauthor_cs.png new file mode 100644 index 0000000..ca73a72 Binary files /dev/null and b/benchmarks/figures/umap_coauthor_cs.png differ diff --git a/benchmarks/figures/umap_coauthor_physics.png b/benchmarks/figures/umap_coauthor_physics.png new file mode 100644 index 0000000..4444d98 Binary files /dev/null and b/benchmarks/figures/umap_coauthor_physics.png differ diff --git a/benchmarks/figures/umap_cora.png b/benchmarks/figures/umap_cora.png new file mode 100644 index 0000000..705dc24 Binary files /dev/null and b/benchmarks/figures/umap_cora.png differ diff --git a/benchmarks/figures/umap_cora_full.png b/benchmarks/figures/umap_cora_full.png new file mode 100644 index 0000000..b0c8eff Binary files /dev/null and b/benchmarks/figures/umap_cora_full.png differ diff --git a/benchmarks/figures/umap_dblp.png b/benchmarks/figures/umap_dblp.png new file mode 100644 index 0000000..e19f95f Binary files /dev/null and b/benchmarks/figures/umap_dblp.png differ diff --git a/benchmarks/figures/umap_facebook.png b/benchmarks/figures/umap_facebook.png new file mode 100644 index 0000000..47bf850 Binary files /dev/null and b/benchmarks/figures/umap_facebook.png differ diff --git a/benchmarks/figures/umap_flickr.png b/benchmarks/figures/umap_flickr.png new file mode 100644 index 0000000..8fa290c Binary files /dev/null and b/benchmarks/figures/umap_flickr.png differ diff --git a/benchmarks/figures/umap_livejournal.png b/benchmarks/figures/umap_livejournal.png new file mode 100644 index 0000000..39b29c8 Binary files /dev/null and b/benchmarks/figures/umap_livejournal.png differ diff --git a/benchmarks/figures/umap_movielens_1m.png b/benchmarks/figures/umap_movielens_1m.png new file mode 100644 index 0000000..b38309f Binary files /dev/null and b/benchmarks/figures/umap_movielens_1m.png differ diff --git a/benchmarks/figures/umap_movielens_20m.png b/benchmarks/figures/umap_movielens_20m.png new file mode 100644 index 0000000..b6b6a1b Binary files /dev/null and b/benchmarks/figures/umap_movielens_20m.png differ diff --git a/benchmarks/figures/umap_ogbl_citation2.png b/benchmarks/figures/umap_ogbl_citation2.png new file mode 100644 index 0000000..c5589e0 Binary files /dev/null and b/benchmarks/figures/umap_ogbl_citation2.png differ diff --git a/benchmarks/figures/umap_ogbl_collab.png b/benchmarks/figures/umap_ogbl_collab.png new file mode 100644 index 0000000..b5a384a Binary files /dev/null and b/benchmarks/figures/umap_ogbl_collab.png differ diff --git a/benchmarks/figures/umap_ogbl_ddi.png b/benchmarks/figures/umap_ogbl_ddi.png new file mode 100644 index 0000000..99101f0 Binary files /dev/null and b/benchmarks/figures/umap_ogbl_ddi.png differ diff --git a/benchmarks/figures/umap_ogbl_ppa.png b/benchmarks/figures/umap_ogbl_ppa.png new file mode 100644 index 0000000..206ed15 Binary files /dev/null and b/benchmarks/figures/umap_ogbl_ppa.png differ diff --git a/benchmarks/figures/umap_ogbn_arxiv.png b/benchmarks/figures/umap_ogbn_arxiv.png new file mode 100644 index 0000000..355bea2 Binary files /dev/null and b/benchmarks/figures/umap_ogbn_arxiv.png differ diff --git a/benchmarks/figures/umap_ogbn_products.png b/benchmarks/figures/umap_ogbn_products.png new file mode 100644 index 0000000..17f5080 Binary files /dev/null and b/benchmarks/figures/umap_ogbn_products.png differ diff --git a/benchmarks/figures/umap_ppi.png b/benchmarks/figures/umap_ppi.png new file mode 100644 index 0000000..84d9b02 Binary files /dev/null and b/benchmarks/figures/umap_ppi.png differ diff --git a/benchmarks/figures/umap_pubmed.png b/benchmarks/figures/umap_pubmed.png new file mode 100644 index 0000000..26478ed Binary files /dev/null and b/benchmarks/figures/umap_pubmed.png differ diff --git a/benchmarks/figures/umap_reddit.png b/benchmarks/figures/umap_reddit.png new file mode 100644 index 0000000..ccd5fbf Binary files /dev/null and b/benchmarks/figures/umap_reddit.png differ diff --git a/benchmarks/figures/umap_roadnet_ca.png b/benchmarks/figures/umap_roadnet_ca.png new file mode 100644 index 0000000..f2cfe3c Binary files /dev/null and b/benchmarks/figures/umap_roadnet_ca.png differ diff --git a/benchmarks/figures/umap_wikipedia_pos.png b/benchmarks/figures/umap_wikipedia_pos.png new file mode 100644 index 0000000..d69c61a Binary files /dev/null and b/benchmarks/figures/umap_wikipedia_pos.png differ diff --git a/benchmarks/figures/umap_yelp.png b/benchmarks/figures/umap_yelp.png new file mode 100644 index 0000000..e7d369a Binary files /dev/null and b/benchmarks/figures/umap_yelp.png differ diff --git a/benchmarks/kernel_speed.py b/benchmarks/kernel_speed.py new file mode 100755 index 0000000..0668fc5 --- /dev/null +++ b/benchmarks/kernel_speed.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +"""Times the two things pycleora does - building the graph and one embedding +iteration - on a synthetic power-law graph, with whatever pycleora is installed. + + python benchmarks/kernel_speed.py # 2^20 nodes, 12M edges, 1024 dimensions + python benchmarks/kernel_speed.py --scale 18 --edges 2500000 --threads 10,4,1 + +It only uses calls that exist in pycleora 3.2 as well (``SparseMatrix.from_files``, +``embed_fast``), so the same script compares releases: run it once per installed version. + +The graph is an R-MAT graph (Chakrabarti et al., 2004; a = 0.57, b = c = 0.19), whose +skewed degrees are what makes the propagation hard to parallelise. It is written to a +file as one two-node hyperedge per line and read with the column +``complex::reflexive::node``. + +Reported, best of ``--repeats`` runs each: + +* build file to sparse matrix +* per iteration (embed with ``--iterations`` iterations - embed with none) / iterations: + one propagation and row normalisation of the whole embedding matrix +* row by row the same for the in-place propagation of an existing array, which + reads whole rows instead of working through the matrix in blocks of + columns (pycleora >= 4.0; the results of the two are bit-identical) +""" + +import argparse +import os +import tempfile +import time + +import numpy as np + +COLUMNS = "complex::reflexive::node" + + +def rmat_edges(scale, num_edges, seed=0, a=0.57, b=0.19, c=0.19): + """Edges of an R-MAT graph with ``2 ** scale`` node ids; self-loops removed.""" + generator = np.random.default_rng(seed) + source = np.zeros(num_edges, dtype=np.int64) + target = np.zeros(num_edges, dtype=np.int64) + for _ in range(scale): + draw = generator.random(num_edges) + source = (source << 1) | (draw >= a + b) + target = (target << 1) | (((draw >= a) & (draw < a + b)) | (draw >= a + b + c)) + keep = source != target + return source[keep], target[keep] + + +def write_edge_list(path, source, target, block=1_000_000): + with open(path, "w") as handle: + for start in range(0, len(source), block): + lines = np.char.add(np.char.add(source[start:start + block].astype(str), " "), + target[start:start + block].astype(str)) + handle.write("\n".join(lines.tolist()) + "\n") + + +def best(function, repeats): + times = [] + for _ in range(repeats): + started = time.perf_counter() + function() + times.append(time.perf_counter() - started) + return min(times) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("--scale", type=int, default=20, help="2 ** scale node ids (default 20)") + parser.add_argument("--edges", type=int, default=12_000_000) + parser.add_argument("--dim", type=int, default=1024) + parser.add_argument("--iterations", type=int, default=4) + parser.add_argument("--repeats", type=int, default=3) + parser.add_argument("--threads", default=None, + help="comma-separated thread counts (pycleora >= 4.0); default: the library's own default") + args = parser.parse_args() + + import pycleora + from pycleora import SparseMatrix + + version = getattr(pycleora, "__version__", "3.x") + source, target = rmat_edges(args.scale, args.edges) + with tempfile.TemporaryDirectory() as directory: + path = os.path.join(directory, "rmat.tsv") + write_edge_list(path, source, target) + for threads in [None] if args.threads is None else [int(t) for t in args.threads.split(",")]: + workers = {} if threads is None else {"num_workers": threads} + graphs = [] + build = best(lambda: graphs.append(SparseMatrix.from_files([path], COLUMNS, **workers)), args.repeats) + graph = graphs[-1] + nothing = best(lambda: graph.embed_fast(args.dim, 0, **workers), args.repeats) + rounds = best(lambda: graph.embed_fast(args.dim, args.iterations, **workers), args.repeats) + row_by_row = "" + if hasattr(graph, "left_markov_propagate_normalized_inplace"): + vectors = graph.embed_fast(args.dim, 0, **workers) + in_place = best(lambda: graph.left_markov_propagate_normalized_inplace(vectors, args.iterations, **workers), + args.repeats) + row_by_row = f" row by row {in_place / args.iterations:.3f} s" + print(f"pycleora {version} threads={'default' if threads is None else threads:>7} " + f"{graph.num_entities:,} nodes {len(source):,} edges dim {args.dim} " + f"build {build:.2f} s per iteration {(rounds - nothing) / args.iterations:.3f} s{row_by_row}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/make_figures.py b/benchmarks/make_figures.py new file mode 100755 index 0000000..066e06f --- /dev/null +++ b/benchmarks/make_figures.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python +"""UMAP pictures of the embeddings: one figure per dataset, one panel per method. + + python benchmarks/make_figures.py --data ~/cleora-bench --out benchmarks/figures + +Every panel is a 2-D UMAP (umap-learn, cosine metric, fixed seed) of the same random +sample of nodes, taken from the vectors the benchmark stored for the whole graph +(``sample.npz`` of seed 0). Points are coloured by node class - the eight largest +classes, the others in grey; a node with several labels by its rarest one - or, for +graphs without labels, by degree. + +The pictures illustrate; they are not evidence. Whether one method separates classes +better than another is what the tables measure. +""" + +import argparse +import os +import sys + +import numpy as np + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from cleora_bench import datasets, display # noqa: E402 + +SURFACE = "#fcfcfb" +INK, MUTED = "#0b0b0b", "#52514e" +# categorical slots in their fixed order (a class keeps its colour in every panel) +CLASS_COLOURS = ("#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300", "#6250d6", "#e34948") +OTHER = "#b9b8b1" +DEGREE_RAMP = ("#cde2fb", "#86b6ef", "#3987e5", "#1c5cab", "#0d366b") # one hue, light to dark +MAX_POINTS = 15_000 + + +def coordinates(sample_path, seed=0): + """2-D UMAP of a stored sample (cached next to it).""" + cache = os.path.join(os.path.dirname(sample_path), "umap.npy") + if os.path.exists(cache): + return np.load(cache) + import umap + + with np.load(sample_path) as archive: + vectors = archive["vectors"][:MAX_POINTS].astype(np.float32) + layout = umap.UMAP(n_components=2, n_neighbors=15, min_dist=0.1, metric="cosine", + random_state=seed).fit_transform(vectors) + np.save(cache, layout.astype(np.float32)) + return layout + + +def point_classes(graph, rows): + """For every sampled node: the rank of its class by size (0 = largest), or ``None`` + when the graph has no labels. A node with several labels is drawn with its rarest + one: its most common label is, for most nodes, the same one.""" + if "labels" not in graph: + return None, None + labels = graph["labels"] + if labels.ndim == 2: + frequency = labels.sum(axis=0).astype(np.float64) + rarity = np.where(labels[rows], frequency, np.inf) + chosen = np.where(labels[rows].any(axis=1), rarity.argmin(axis=1), -1) + else: + chosen = labels[rows] + known = chosen[chosen >= 0] + order = np.argsort(-np.bincount(known, minlength=int(known.max()) + 1), kind="stable") + rank = np.empty(len(order), dtype=np.int64) + rank[order] = np.arange(len(order)) + return np.where(chosen >= 0, rank[np.maximum(chosen, 0)], len(order)), int((np.bincount(known) > 0).sum()) + + +def draw_dataset(name, panels, graph, path, columns=4): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + from matplotlib.colors import LinearSegmentedColormap + from matplotlib.lines import Line2D + + rows_of_nodes = panels[0][2] + classes, num_classes = point_classes(graph, rows_of_nodes) + if classes is None: + degree = np.bincount(graph["edges"].ravel(), minlength=graph["meta"]["num_nodes"])[rows_of_nodes] + colour_values = np.log10(np.maximum(degree, 1)) + grid_rows = int(np.ceil(len(panels) / columns)) + figure, axes = plt.subplots(grid_rows, columns, figsize=(2.9 * columns, 2.9 * grid_rows + 0.9), squeeze=False, + facecolor=SURFACE) + point_size = float(np.clip(6000 / len(rows_of_nodes), 0.6, 6)) + for axis in axes.ravel(): + axis.set_facecolor(SURFACE) + axis.set_xticks([]) + axis.set_yticks([]) + for spine in axis.spines.values(): + spine.set_visible(False) + for axis, (label, layout, _) in zip(axes.ravel(), panels): + if classes is None: + ramp = LinearSegmentedColormap.from_list("degree", DEGREE_RAMP) + axis.scatter(layout[:, 0], layout[:, 1], c=colour_values, cmap=ramp, s=point_size, linewidths=0, alpha=0.8, + rasterized=True) + else: + colours = np.array(list(CLASS_COLOURS) + [OTHER])[np.minimum(classes, len(CLASS_COLOURS))] + order = np.argsort(-np.minimum(classes, len(CLASS_COLOURS)), kind="stable") # grey first, below the colours + axis.scatter(layout[order, 0], layout[order, 1], c=colours[order], s=point_size, linewidths=0, alpha=0.8, + rasterized=True) + axis.set_title(label, fontsize=10, color=INK, loc="left", pad=4) + meta = graph["meta"] + figure.suptitle(f"{display.DATASET_LABELS.get(name, name)} · {meta['num_nodes']:,} nodes, {meta['num_edges']:,} edges", + x=0.01, y=0.995, ha="left", va="top", fontsize=12, color=INK) + if classes is None: + caption = "No node labels: colour = degree (light = low, dark = high)" + figure.text(0.01, 0.012, caption, fontsize=9, color=MUTED, ha="left", va="bottom") + else: + shown = min(num_classes, len(CLASS_COLOURS)) + handles = [Line2D([], [], marker="o", linestyle="", markersize=6, color=CLASS_COLOURS[i], + label=f"class {i + 1}") for i in range(shown)] + if num_classes > shown: + handles.append(Line2D([], [], marker="o", linestyle="", markersize=6, color=OTHER, + label=f"{num_classes - shown} smaller classes")) + legend = figure.legend(handles=handles, loc="lower left", bbox_to_anchor=(0.005, 0.0), ncol=len(handles), + frameon=False, fontsize=9, handletextpad=0.2, columnspacing=1.0, + title="Classes by size" if shown > 1 else None, title_fontsize=9, alignment="left") + for text in legend.get_texts(): + text.set_color(MUTED) + figure.tight_layout(rect=(0, 0.05, 1, 0.975)) + figure.savefig(path, dpi=140, facecolor=SURFACE) + plt.close(figure) + # a 256-colour palette: a third of the file size, no visible difference + from PIL import Image + + Image.open(path).convert("RGB").quantize(colors=256, dither=Image.Dither.NONE).save(path, optimize=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("--data", required=True, help="directory with datasets/ and results/") + parser.add_argument("--out", required=True) + parser.add_argument("--datasets", default=None) + parser.add_argument("--dim", type=int, default=1024) + args = parser.parse_args() + args.data = os.path.abspath(os.path.expanduser(args.data)) + os.makedirs(args.out, exist_ok=True) + results = os.path.join(args.data, "results") + names = args.datasets.split(",") if args.datasets else sorted(os.listdir(results)) + for name in names: + panels = [] + for row in display.FIGURE_METHODS: + samples = [os.path.join(results, name, configuration, f"dim{args.dim}", "seed0", "sample.npz") + for configuration in row["configurations"]] + sample = next((path for path in samples if os.path.exists(path)), None) + if sample is None: + continue + with np.load(sample) as archive: + rows = archive["rows"][:MAX_POINTS] + panels.append((row["label"], coordinates(sample), rows)) + if len(panels) < 2: + continue + graph = datasets.load(name, os.path.join(args.data, "datasets")) + path = os.path.join(args.out, f"umap_{name}.png") + draw_dataset(name, panels, graph, path) + print(f"{name}: {len(panels)} panels -> {path}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/make_report.py b/benchmarks/make_report.py new file mode 100755 index 0000000..943c500 --- /dev/null +++ b/benchmarks/make_report.py @@ -0,0 +1,573 @@ +#!/usr/bin/env python +"""Writes the result tables of the benchmark from its job files. + + python benchmarks/make_report.py --data ~/cleora-bench --out benchmarks/RESULTS.md --readme README.md + +``--out`` receives every table. ``--readme`` names a file in which the text between +```` and ```` is replaced by the table +of that name, so the README never holds a hand-typed number. + +Every number comes from ``/results`` (quality) or ``/timing`` (time and +memory, measured separately on an idle machine). How a method's variant is chosen, +what the columns mean and how ranks are computed is documented in +``cleora_bench/report.py`` and ``cleora_bench/display.py``. +""" + +import argparse +import os +import re +import sys + +import numpy as np + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from cleora_bench import configurations, datasets, display, iteration_fit, popularity, report, selection # noqa: E402 + + +class Results: + """The aggregated job files plus what is needed to address them by table position.""" + + def __init__(self, data): + self.data = data + self.table = report.aggregate(report.load_jobs(os.path.join(data, "results"))) + self.timing = report.aggregate(report.load_jobs(os.path.join(data, "timing"))) + self.selected = selection.load(data) + present = {key[0] for key in self.table} + self.datasets = [name for name in display.DATASET_ORDER if name in present] + self.meta = {name: datasets.meta(name, os.path.join(data, "datasets")) for name in self.datasets} + + def variants(self, method, dataset, task): + """The configurations a column stands for: exactly one for every method of the main + tables; for "cleora_tuned" the four families with the suggested and with the + validated iteration counts (the report then picks on validation).""" + if method in display.SAME_METHOD: + return [(display.cleora_configuration(display.METHODS[method]["setup"], task), display.MAIN_DIM)] + if method == "cleora_tuned": + suggested = configurations.automatic(display.TASK_PURPOSE[task]) + chosen = self.selected.get(dataset, {}).get(task, {}).values() + return [(name, display.MAIN_DIM) for name in suggested + sorted(chosen)] + return [(display.METHODS[method]["configuration"], display.MAIN_DIM)] + + def labelled(self, multilabel): + return [name for name in self.datasets + if self.meta[name]["num_classes"] > 0 and bool(self.meta[name].get("multilabel")) == multilabel] + + def with_task(self, task): + return [name for name in self.datasets if any(key[0] == name and key[1] == task for key in self.table)] + + def rows(self, task, probe, metric, names, methods): + """``{dataset label: {method: cell}}`` for one table.""" + result = {} + for name in names: + cells = {} + for method in methods: + variants = self.variants(method, name, task) + if probe == "similarity": + cells[method] = report.best_training_free(self.table, name, variants, metric) + else: + cells[method] = report.cell(self.table, name, task, probe, metric, variants) + result[display.DATASET_LABELS[name]] = cells + return result + + def scenario_rows(self, scenario, methods): + """The rows of the headline measurement of a scenario (``display.SCENARIOS``).""" + _, _, task, probe, metric = display.SCENARIOS[scenario] + if task == "lp": + return self.rows("lp", probe, metric, self.with_task("lp"), methods) + rows = self.rows("nc", probe, "accuracy", self.labelled(False), methods) + rows.update(self.rows("nc", probe, "micro_f1", self.labelled(True), methods)) + return rows + + +def competition_summary(rows, methods, higher_is_better=True): + """Mean rank and wins of every method. The Cleora columns are the same method fed in two + ways and do not compete with each other: every baseline is ranked against the first of + them, and each Cleora column against the baselines only.""" + same = [m for m in methods if m in display.SAME_METHOD] + if len(same) < 2: + return report.summary_rows(rows, methods, higher_is_better) + others = [m for m in methods if m not in same] + summary = report.summary_rows(rows, [same[0]] + others, higher_is_better) + for method in same[1:]: + summary[method] = report.summary_rows(rows, [method] + others, higher_is_better)[method] + return summary + + +def table_with_summary(rows, methods, digits=3, higher_is_better=True, show_std=True): + labels = {method: display.METHODS[method]["label"] for method in methods} + text = report.markdown_table(rows, methods, labels, digits=digits, higher_is_better=higher_is_better, + show_std=show_std) + summary = competition_summary(rows, methods, higher_is_better) + best_rank = min(s["mean_rank"] for s in summary.values()) + rank_cells = [f"**{summary[m]['mean_rank']:.2f}**" if summary[m]["mean_rank"] == best_rank else f"{summary[m]['mean_rank']:.2f}" + for m in methods] + text += "\n| *mean rank* | " + " | ".join(rank_cells) + " |" + text += "\n| *best on* | " + " | ".join(f"{summary[m]['wins']} / {summary[m]['results']}" for m in methods) + " |" + return text + + +def rank_table(measurements, columns, first_column="Probe"): + """One row per measurement (``{label: the rows of its table}``): the mean rank of + every method over the graphs, and the number of graphs it is best on.""" + labels = [display.METHODS[method]["label"] for method in columns] + lines = [f"| {first_column} | Graphs | " + " | ".join(labels) + " |", "|---|---:|" + "---:|" * len(columns)] + for label, rows in measurements.items(): + summary = competition_summary(rows, columns) + graphs = max(s["rows"] for s in summary.values()) + best = min(s["mean_rank"] for s in summary.values()) + cells = [f"{'**' if summary[m]['mean_rank'] == best else ''}{summary[m]['mean_rank']:.2f}" + f"{'**' if summary[m]['mean_rank'] == best else ''} ({summary[m]['wins']})" for m in columns] + lines.append(f"| {label} | {graphs} | " + " | ".join(cells) + " |") + return "\n".join(lines) + + +def dataset_table(results): + lines = ["| Dataset | Nodes | Edges | Mean degree | Node labels | Seeds | Source |", "|---|---:|---:|---:|---|---:|---|"] + for name in results.datasets: + meta = results.meta[name] + if meta["num_classes"] == 0: + labels = "–" + else: + labels = f"{meta['num_classes']} {'labels (multi-label)' if meta.get('multilabel') else 'classes'}" + runs = max((len(entry["seconds"]) for key, entry in results.table.items() if key[0] == name and key[1] == "lp"), default=0) + notes = [note for note, flag in (("weighted", meta["weighted"]), ("bipartite", meta["bipartite"]), + ("official node split", meta["official_node_split"]), + ("official link split", meta["official_link_split"])) if flag] + description = meta.get("citation", "") + ("; " + ", ".join(notes) if notes else "") + lines.append(f"| {display.DATASET_LABELS[name]} | {meta['num_nodes']:,} | {meta['num_edges']:,} | " + f"{2 * meta['num_edges'] / meta['num_nodes']:.1f} | {labels} | {runs or '–'} | {description} |") + return "\n".join(lines) + + +def families_table(results, task, probe, metric, names): + """The four library-default runs, each on its own, next to the 3.2 default and the tuned row.""" + columns = list(display.FAMILIES) + ["tuned", "pycleora 3.2 default"] + lines = ["| Dataset | " + " | ".join(columns) + " |", "|---|" + "---:|" * len(columns)] + purpose = display.TASK_PURPOSE[task] + for name in names: + cells = [report.cell(results.table, name, task, probe, metric, + [(configurations.AUTO[family + (purpose,)], display.MAIN_DIM)]) + for family in display.FAMILIES.values()] + cells.append(report.cell(results.table, name, task, probe, metric, results.variants("cleora_tuned", name, task))) + cells.append(report.cell(results.table, name, task, probe, metric, results.variants("cleora_3_2", name, task))) + means = sorted({round(c["mean"], 3) for c in cells if "mean" in c}, reverse=True) + lines.append(f"| {display.DATASET_LABELS[name]} | " + " | ".join( + report.format_cell(c, means[0] if means else None, means[1] if len(means) > 1 else None, 3, False) + for c in cells) + " |") + return "\n".join(lines) + + +def _iterations(entry): + values = {record for record in entry.get("iterations", [])} + return "/".join(str(v) for v in sorted(values)) if values else "–" + + +def iterations_table(results, task): + """Iterations of the automatic rule next to those the sweep chose on validation, and + what the difference costs (headline metric of the task, sweep probe).""" + probe = selection.SWEEP_PROBE[task] + purpose = display.TASK_PURPOSE[task] + families = {f"{setup}/{'sym' if propagation == 'symmetric' else propagation}": configurations.AUTO[(setup, propagation, purpose)] + for setup, propagation in display.FAMILIES.values()} + header = [f"{label} ({kind})" for label in display.FAMILIES for kind in ("auto", "tuned", "loss")] + lines = ["| Dataset | " + " | ".join(header) + " |", "|---|" + "---:|" * len(header)] + losses = {family: [] for family in families} + for name in results.with_task(task): + metric = "mrr" if task == "lp" else ("micro_f1" if results.meta[name].get("multilabel") else "accuracy") + cells = [] + for family, auto_name in families.items(): + auto = results.table.get((name, task, auto_name, display.MAIN_DIM)) + tuned_name = results.selected.get(name, {}).get(task, {}).get(family) + auto_cell = report.cell(results.table, name, task, probe, metric, [(auto_name, display.MAIN_DIM)]) + tuned_cell = report.cell(results.table, name, task, probe, metric, [(tuned_name, display.MAIN_DIM)]) if tuned_name else {} + cells.append(_iterations(auto) if auto else "–") + cells.append(str(configurations.iterations(tuned_name)) if tuned_name else "–") + if "mean" in auto_cell and "mean" in tuned_cell: + loss = 100 * (tuned_cell["mean"] - auto_cell["mean"]) + losses[family].append(loss) + cells.append(f"{loss:+.1f}") + else: + cells.append("–") + lines.append(f"| {display.DATASET_LABELS[name]} | " + " | ".join(cells) + " |") + means = [] + for family in families: + means += ["", "", f"{np.mean(losses[family]):+.1f}" if losses[family] else "–"] + lines.append("| *mean loss* | " + " | ".join(means) + " |") + return "\n".join(lines) + + +def duration(seconds): + if seconds < 1: + return f"{seconds * 1000:.0f} ms" + if seconds < 100: + return f"{seconds:.1f} s" + if seconds < 6000: + return f"{seconds / 60:.1f} min" + return f"{seconds / 3600:.1f} h" + + +def timing_table(results, quantity): + """Median over the timing runs of every method (benchmark dimensionality).""" + default = configurations.AUTO[("hyperedge", "left", "general")] # what embed(graph) runs + methods = [default, "cleora_whiten40"] + list(display.BASELINES) + labels = {default: "Cleora", "cleora_whiten40": "pycleora 3.2 default", + **{name: display.METHODS[name]["label"] for name in display.BASELINES}} + names = [name for name in display.DATASET_ORDER if any(key[0] == name for key in results.timing)] + lines = ["| Dataset | " + " | ".join(labels[m] for m in methods) + " |", "|---|" + "---:|" * len(methods)] + for name in names: + values, cells = {}, {} + for method in methods: + entry = results.timing.get((name, "time", method, display.MAIN_DIM)) + if entry is None: + cells[method] = "–" + elif not entry[quantity]: + cells[method] = report.format_cell({"failed": entry["failures"]}, None, None) + else: + values[method] = float(np.median(entry[quantity])) + cells[method] = duration(values[method]) if quantity == "seconds" else f"{values[method] / 1024:.2f} GB" + best = min(values.values()) if values else None + lines.append(f"| {display.DATASET_LABELS[name]} | " + " | ".join( + f"**{cells[m]}**" if m in values and values[m] == best else cells[m] for m in methods) + " |") + return "\n".join(lines) + + +def families_validation_table(results): + """What fixed the normalisation of each task: mean validation score of every family + over the graphs on which all four ran (headline probe), and how often it validated best.""" + lines = ["| Task | Graphs | " + " | ".join(display.FAMILIES) + " |", "|---|---:|" + "---:|" * len(display.FAMILIES)] + for task, probe, label in (("nc", "logistic", "node classification (logistic regression)"), + ("lp", "cosine", "link ranking (cosine)")): + scores = {family: [] for family in display.FAMILIES} + for name in results.with_task(task): + row = {} + for family, key in display.FAMILIES.items(): + entry = results.table.get((name, task, configurations.AUTO[key + (display.TASK_PURPOSE[task],)], display.MAIN_DIM)) + runs = entry["probes"].get(probe) if entry else None + if runs and runs["validation"]: + row[family] = float(np.mean(runs["validation"])) + if len(row) == len(display.FAMILIES): + for family, value in row.items(): + scores[family].append(value) + graphs = len(next(iter(scores.values()))) + if graphs == 0: + continue + best = np.argmax(np.array([scores[family] for family in display.FAMILIES]), axis=0) + cells = [f"{np.mean(scores[family]):.4f} ({int((best == index).sum())})" for index, family in enumerate(display.FAMILIES)] + lines.append(f"| {label} | {graphs} | " + " | ".join(cells) + " |") + return "\n".join(lines) + + +def tuned_table(results, scenario): + """What a validation set adds: Cleora as in the main tables, Cleora with the iteration + count and the family chosen on validation, and the best baseline of the row.""" + lines = ["| Dataset | Cleora | Cleora, tuned | gain | Best baseline |", "|---|---:|---:|---:|---|"] + gains = [] + for name, cells in results.scenario_rows(scenario, ["cleora", "cleora_tuned"] + list(display.BASELINES)).items(): + plain, tuned = cells["cleora"], cells["cleora_tuned"] + rivals = {method: cells[method]["mean"] for method in display.BASELINES if "mean" in cells[method]} + if "mean" not in plain or "mean" not in tuned: + continue + gains.append(100 * (tuned["mean"] - plain["mean"])) + best = max(rivals, key=rivals.get) if rivals else None + rival = f"{display.METHODS[best]['label']} {rivals[best]:.3f}" if best else "–" + top = max([plain["mean"], tuned["mean"]] + list(rivals.values())) + bold = lambda value: f"**{value:.3f}**" if value == top else f"{value:.3f}" + lines.append(f"| {name} | {bold(plain['mean'])} | {bold(tuned['mean'])} | {gains[-1]:+.1f} | {rival} |") + if gains: + lines.append(f"| *mean gain (points)* | | | {np.mean(gains):+.1f} | |") + return "\n".join(lines) + + +def timed(results, dataset, quantity): + """``{label: median}`` of time ("seconds") or memory ("peak_rss_mb") on a graph, for + Cleora as ``embed(graph)`` runs it and every baseline the timing pass measured.""" + default = configurations.AUTO[("hyperedge", "left", "general")] + methods = {"Cleora": default, **{display.METHODS[name]["label"]: name for name in display.BASELINES}} + values = {} + for label, method in methods.items(): + entry = results.timing.get((dataset, "time", method, display.MAIN_DIM)) + if entry and entry[quantity]: + values[label] = float(np.median(entry[quantity])) + return values + + +def hero(results): + """Three numbers for the top of the README: graphs won in similarity search, the time + on one graph and the memory on another, each next to what the baselines need.""" + columns = ["cleora"] + list(display.BASELINES) + won = competition_summary(results.scenario_rows("retrieval", columns), columns)["cleora"] + seconds = timed(results, display.SUMMARY_TIME_GRAPH, "seconds") + memory = {label: megabytes / 1024 for label, megabytes in timed(results, display.SUMMARY_MEMORY_GRAPH, "peak_rss_mb").items()} + if "Cleora" not in seconds or "Cleora" not in memory or len(seconds) < 2 or len(memory) < 2: + return "" + size = lambda name: f"{results.meta[name]['num_nodes']:,} nodes, {results.meta[name]['num_edges'] / 1e6:.1f}M edges" + others = lambda values: sorted(value for label, value in values.items() if label != "Cleora") + slowest = max((label for label in seconds if label != "Cleora"), key=seconds.get) + tiles = [ + (f"{won['wins']} of {won['rows']}", + f"graphs on which Cleora is the best of {len(columns)} methods at finding a node's held-out neighbours"), + (duration(seconds["Cleora"]), + f"to embed {display.DATASET_LABELS[display.SUMMARY_TIME_GRAPH]} ({size(display.SUMMARY_TIME_GRAPH)}) at 1024 dimensions. " + f"The baselines: {duration(others(seconds)[0])} to {duration(seconds[slowest])}"), + (f"{memory['Cleora']:.0f} GB", + f"of memory for {display.DATASET_LABELS[display.SUMMARY_MEMORY_GRAPH]} ({size(display.SUMMARY_MEMORY_GRAPH)}). " + f"The baselines: {others(memory)[0]:.0f} to {others(memory)[-1]:.0f} GB"), + ] + cells = "\n".join(f'

{number}

{text}' for number, text in tiles) + return f"\n\n{cells}\n\n
" + + +def _best_baseline(summary): + name = min(display.BASELINES, key=lambda method: summary[method]["mean_rank"]) + return f"{display.METHODS[name]['label']} ({summary[name]['mean_rank']:.2f})" + + +def headline(results): + """The summary at the top of the README: wins and mean ranks on the headline + measurement of every scenario.""" + columns = list(display.MAIN_COLUMNS) + lines = ["| | Graphs | Cleora: best on | mean rank | Cleora, two columns: best on | mean rank | Best baseline (mean rank) |", + "|---|---:|---:|---:|---:|---:|---|"] + for scenario, (label, measured, *_) in display.SCENARIOS.items(): + summary = competition_summary(results.scenario_rows(scenario, columns), columns) + one, two = summary["cleora"], summary["cleora_pair"] + lines.append(f"| {label} ({measured}) | {one['rows']} | **{one['wins']}** | {one['mean_rank']:.2f} | " + f"{two['wins']} | {two['mean_rank']:.2f} | {_best_baseline(summary)} |") + ahead = [f"on {wins} of {graphs} graphs in {display.SCENARIOS[scenario][0].lower()}" + for scenario in display.TUNED_SCENARIOS for wins, graphs in [_tuned_ahead(results, scenario)]] + lines += ["", "With the number of iterations and the normalisation chosen on validation data - the baselines stay at " + "their authors' settings, so this is not part of the comparison above - Cleora is ahead of every baseline " + + " and ".join(ahead) + "."] + return "\n".join(lines) + + +def _tuned_ahead(results, scenario): + """On how many graphs "Cleora, tuned" is ahead of every baseline (headline measurement + of the scenario), out of the graphs on which at least one baseline has a result.""" + wins = graphs = 0 + for cells in results.scenario_rows(scenario, ["cleora_tuned"] + list(display.BASELINES)).values(): + rivals = [cells[method]["mean"] for method in display.BASELINES if "mean" in cells[method]] + if "mean" in cells["cleora_tuned"] and rivals: + graphs += 1 + wins += int(cells["cleora_tuned"]["mean"] > max(rivals)) + return wins, graphs + + +def _both(first, second): + """Two numbers with as many decimals (three or more) as it takes to tell them apart.""" + digits = next((d for d in (3, 4, 5) if f"{first:.{d}f}" != f"{second:.{d}f}"), 5) + return f"{first:.{digits}f}", f"{second:.{digits}f}" + + +def caveats(results): + """Where Cleora is not the best method: every graph on which a baseline, or the + pycleora 3.2 default, is ahead of the Cleora column on a headline measurement.""" + lines = [] + for scenario, (label, *_) in display.SCENARIOS.items(): + behind, previous = [], [] + for name, cells in results.scenario_rows(scenario, ["cleora", "cleora_3_2"] + list(display.BASELINES)).items(): + if "mean" not in cells["cleora"]: + continue + ours = cells["cleora"]["mean"] + rivals = {method: cells[method]["mean"] for method in display.BASELINES if "mean" in cells[method]} + if rivals and max(rivals.values()) > ours: + best = max(rivals, key=rivals.get) + theirs, mine = _both(rivals[best], ours) + behind.append(f"{name} ({display.METHODS[best]['label']} {theirs}, Cleora {mine})") + old = cells["cleora_3_2"] + if "mean" in old and old["mean"] > ours: + theirs, mine = _both(old["mean"], ours) + previous.append(f"{name} ({theirs} against {mine})") + lines.append(f"- **{label}: a baseline is ahead of Cleora on** " + ("; ".join(behind) if behind else "no graph") + ".") + lines.append(f"- **{label}: the pycleora 3.2 default (whitening, 40 iterations) is ahead of Cleora on** " + + ("; ".join(previous) if previous else "no graph") + ".") + return "\n".join(lines) + + +def build(results): + """``{name: markdown}`` of every table, in the order of the report.""" + columns = list(display.MAIN_COLUMNS) + single, multi, link = results.labelled(False), results.labelled(True), results.with_task("lp") + tables = {"datasets": dataset_table(results), "headline": headline(results), "caveats": caveats(results), + "hero": hero(results)} + tables["ranks_retrieval"] = rank_table( + {label: results.rows("lp", "similarity", metric, link, columns) for metric, label in display.RETRIEVAL_METRICS.items()}, + columns, "Metric") + tables["ranks_nc"] = rank_table( + {label: {**results.rows("nc", probe, "accuracy", single, columns), **results.rows("nc", probe, "micro_f1", multi, columns)} + for probe, label in display.NODE_PROBES.items()}, columns) + tables["ranks_lp"] = rank_table( + {label: results.rows("lp", probe, "mrr", link, columns) + for probe, label in {"similarity": "dot product or cosine", **display.PAIR_PROBES}.items()}, columns) + for metric in display.RETRIEVAL_METRICS: + tables[f"retrieval_{metric}"] = table_with_summary(results.rows("lp", "similarity", metric, link, columns), columns) + for probe in display.NODE_PROBES: + tables[f"nc_accuracy_{probe}"] = table_with_summary(results.rows("nc", probe, "accuracy", single, columns), columns) + tables[f"nc_micro_f1_{probe}"] = table_with_summary(results.rows("nc", probe, "micro_f1", multi, columns), columns) + for metric in ("macro_f1", "balanced_accuracy", "mcc", "macro_roc_auc", "macro_average_precision", "top3_accuracy"): + tables[f"nc_{metric}_logistic"] = table_with_summary(results.rows("nc", "logistic", metric, single, columns), columns, show_std=False) + for metric in ("macro_f1", "micro_f1_known_count", "micro_average_precision", "label_ranking_average_precision", + "precision_at_1", "hamming_loss"): + tables[f"nc_multilabel_{metric}_logistic"] = table_with_summary(results.rows("nc", "logistic", metric, multi, columns), columns, show_std=False, higher_is_better=metric != "hamming_loss") + tables["lp_mrr_similarity"] = table_with_summary(results.rows("lp", "similarity", "mrr", link, columns), columns) + for probe in display.PAIR_PROBES: + tables[f"lp_mrr_{probe}"] = table_with_summary(results.rows("lp", probe, "mrr", link, columns), columns) + for metric in ("hits@1", "hits@10", "hits@100", "roc_auc", "average_precision"): + tables[f"lp_{metric}_cosine"] = table_with_summary(results.rows("lp", "cosine", metric, link, columns), columns, show_std=False) + tables["families_nc_accuracy"] = families_table(results, "nc", "logistic", "accuracy", single) + tables["families_nc_micro_f1"] = families_table(results, "nc", "logistic", "micro_f1", multi) + tables["families_lp_mrr"] = families_table(results, "lp", "cosine", "mrr", link) + tables["iterations_nc"] = iterations_table(results, "nc") + tables["iterations_lp"] = iterations_table(results, "lp") + tables["families_validation"] = families_validation_table(results) + for scenario in display.TUNED_SCENARIOS: + tables[f"tuned_{scenario}"] = tuned_table(results, scenario) + sweep = os.path.join(results.data, selection.SWEEP_DIRECTORY) + if os.path.isdir(sweep): + tables["iteration_rule_fit"] = iteration_fit.markdown(sweep) + tables["iteration_rule_constants"] = iteration_fit.sensitivity_markdown(sweep) + tables["popularity_exponent"] = popularity.link_table(results.data) + tables["popularity_exponent_classification"] = popularity.classification_table(results.data) + if results.timing: + tables["time"] = timing_table(results, "seconds") + tables["memory"] = timing_table(results, "peak_rss_mb") + return tables + + +SECTIONS = ( + ("In short", "One headline measurement for each use of the vectors; the full tables follow.", ["headline"]), + ("Where Cleora is not the best method", "", ["caveats"]), + ("Datasets", "", ["datasets"]), + ("Summary: mean rank of every method", + "Mean rank over the graphs (1 = best; a method without a result on a graph ranks after all that have one), " + "and in parentheses the number of graphs the method is best on. The two Cleora columns are the same method " + "fed in two ways and do not compete with each other: every baseline is ranked against Cleora with one " + "column, and each Cleora column against the baselines only. `ranks_retrieval`: similarity search among all " + "nodes, by metric. `ranks_nc`: node classification by accuracy (single-label graphs) or micro-F1 " + "(multi-label), by probe. `ranks_lp`: link ranking against sampled candidates by MRR, by probe.", + ["ranks_retrieval", "ranks_nc", "ranks_lp"]), + ("Similarity search among all nodes", + "What a nearest-neighbour index over the vectors returns: the held-out neighbours of a query node are ranked " + "among all nodes of the graph by dot product or cosine - whichever validates better for the method - with " + "the known neighbours filtered out. `recall@k`, `ndcg@k`, `map@k`: of the top-k list of every query node. " + "`all_nodes_mrr`: of every held-out edge.", + [f"retrieval_{metric}" for metric in display.RETRIEVAL_METRICS]), + ("Node classification, single-label graphs: accuracy", + "10% of the nodes for training and 10% for validation (or the official split), three random splits per " + "embedding; mean ± standard deviation over splits and seeds. One table per probe.", + [f"nc_accuracy_{probe}" for probe in display.NODE_PROBES]), + ("Node classification, single-label graphs: other metrics (logistic regression)", "", + [f"nc_{metric}_logistic" for metric in ("macro_f1", "balanced_accuracy", "mcc", "macro_roc_auc", + "macro_average_precision", "top3_accuracy")]), + ("Node classification, multi-label graphs: micro-F1", + "A label is predicted when its score is positive; no knowledge of the number of labels of a node is used.", + [f"nc_micro_f1_{probe}" for probe in display.NODE_PROBES]), + ("Node classification, multi-label graphs: other metrics (logistic regression)", + "`micro_f1_known_count` is the protocol of the DeepWalk and node2vec papers: the number of labels of every " + "test node is given to the classifier.", + [f"nc_multilabel_{metric}_logistic" for metric in ("macro_f1", "micro_f1_known_count", "micro_average_precision", + "label_ranking_average_precision", "precision_at_1", "hamming_loss")]), + ("Link ranking against sampled candidates: MRR", + "Every held-out edge is ranked against 500 sampled non-edges of the same source node (the OGB link datasets: " + "against their official negatives). `similarity` is the better of dot product and cosine on validation; the " + "other tables are one per probe.", + ["lp_mrr_similarity"] + [f"lp_mrr_{probe}" for probe in display.PAIR_PROBES]), + ("Link ranking against sampled candidates: other metrics (cosine)", "", + [f"lp_{metric}_cosine" for metric in ("hits@1", "hits@10", "hits@100", "roc_auc", "average_precision")]), + ("Cleora: the four ways of feeding and normalising a graph", + "One column (`complex::reflexive::node`) or two (`src dst`), left or symmetric normalisation, each with the " + "number of iterations the library suggests for the task; `tuned`: iteration count and family chosen on " + "validation. Logistic regression for classification, cosine for link ranking.", + ["families_nc_accuracy", "families_nc_micro_f1", "families_lp_mrr"]), + ("Cleora: which normalisation for which task", + "Mean validation score of each family over the graphs on which all four ran, and in parentheses the number " + "of graphs on which it validated best. The main tables use the left normalisation for classification and the " + "symmetric one for link ranking, for every graph, on the strength of this table.", + ["families_validation"]), + ("Cleora: what a validation set adds", + "`Cleora`: as in the main tables. `Cleora, tuned`: the number of iterations (from a sweep over twelve values) " + "and the family chosen on validation data. `gain` in points of the metric. Classification with logistic " + "regression, link ranking against sampled candidates with dot product or cosine - the two scores the sweep " + "validates.", + [f"tuned_{scenario}" for scenario in display.TUNED_SCENARIOS]), + ("Cleora: the exponents of the popularity prior", + "Validation scores of the benchmark's Cleora configurations with `scale_by_popularity(graph, vectors, " + "exponent)`, seed 0, mean over the graphs (`benchmarks/popularity_exponent.py`). `popularity_exponent`: the " + "similarity configuration, dot product; `MRR` against the sampled candidates, `recall@10` among all nodes; " + "*prior or cosine* is the benchmark's rule, under which a graph keeps the unit vectors when they validate " + "better. `popularity_exponent_classification`: the classification configuration, logistic regression.", + ["popularity_exponent", "popularity_exponent_classification"]), + ("Number of iterations: automatic rule against the sweep", + "`auto`: iterations of `SparseMatrix.suggest_iterations` for the task. `tuned`: best of the sweep on " + "validation. `loss`: points of the metric (x 100) the automatic count is behind the tuned one; negative: " + "it is ahead.", + ["iterations_nc", "iterations_lp"]), + ("Number of iterations: candidate rules, leave-one-graph-out", + "From the iteration sweep (one seed; logistic regression / cosine). Loss: test score at the iteration count " + "that validated best minus test score at the rule's count, in points of the metric (x 100).", + ["iteration_rule_fit"]), + ("Number of iterations: loss as a function of the constant c", + "The form that ships, on all graphs of the sweep, for every candidate value of `c`.", + ["iteration_rule_constants"]), + ("Embedding time", "Median of three runs on an idle machine, whole graph, 1024 dimensions.", ["time"]), + ("Peak memory", "Peak resident memory of the embedding process, interpreter and libraries included.", ["memory"]), +) + + +def write_report(tables, path): + lines = ["# Benchmark results", "", + "Generated by `benchmarks/make_report.py`; do not edit. The protocol is described in " + "[`benchmarks/README.md`](README.md).", "", + "**Bold**: best of the row. Underlined: second best. `n/a (size)`: the implementation builds " + "dense n × n matrices or Python-level graph objects and was not run on a graph of this size. " + "`time limit` / `out of memory`: the run was started and did not finish.", ""] + for title, note, names in SECTIONS: + present = [name for name in names if name in tables and tables[name].strip()] + if not present: + continue + lines += [f"## {title}", ""] + ([note, ""] if note else []) + for name in present: + if len(names) > 1: + lines += [f"### `{name}`", ""] + lines += [tables[name], ""] + with open(path, "w") as handle: + handle.write("\n".join(lines)) + + +def inject(tables, path): + """Replaces the marked blocks of a Markdown file with the tables they name.""" + with open(path) as handle: + text = handle.read() + + def replace(match): + name = match.group(1) + if name not in tables: + raise KeyError(f"{path} asks for the unknown table '{name}'") + return f"\n{tables[name]}\n" + + text, count = re.subn(r".*?", replace, text, flags=re.S) + with open(path, "w") as handle: + handle.write(text) + return count + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("--data", required=True, help="directory with datasets/, results/ and timing/") + parser.add_argument("--out", required=True, help="Markdown file that receives every table") + parser.add_argument("--readme", action="append", default=[], help="Markdown file with marked blocks to fill") + parser.add_argument("--dump", default=None, help="write every aggregated number to this .csv.gz file") + args = parser.parse_args() + results = Results(os.path.abspath(os.path.expanduser(args.data))) + tables = build(results) + if args.dump: + report.dump({**results.table, **results.timing}, args.dump) + write_report(tables, args.out) + print(f"{len(tables)} tables -> {args.out}") + for path in args.readme: + print(f"{inject(tables, path)} blocks filled in {path}") + + +if __name__ == "__main__": + main() diff --git a/benchmarks/make_summary_figure.py b/benchmarks/make_summary_figure.py new file mode 100755 index 0000000..5535ca2 --- /dev/null +++ b/benchmarks/make_summary_figure.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python +"""The picture at the top of the README: three facts of the benchmark as bar charts. + + python benchmarks/make_summary_figure.py --data ~/cleora-bench --out benchmarks/figures + +* on how many graphs each method is the best one in similarity search (the row + ``recall@10`` of the table ``ranks_retrieval``); +* the time every method needs to embed one mid-sized graph, and +* the memory it needs on a larger one (tables ``time`` and ``memory``). + +Every bar is read from the result files through the code that writes the tables. Two +files are written, ``summary_light.svg`` and ``summary_dark.svg``: the README shows the +one that fits the reader's colour scheme. +""" + +import argparse +import os +import sys + + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import make_report # noqa: E402 +from cleora_bench import display # noqa: E402 + +TIME_GRAPH, MEMORY_GRAPH = display.SUMMARY_TIME_GRAPH, display.SUMMARY_MEMORY_GRAPH +# ink, secondary ink, the method the page is about, every other method +THEMES = { + "light": {"ink": "#0b0b0b", "secondary": "#52514e", "accent": "#2a78d6", "other": "#b9b8b1"}, + "dark": {"ink": "#f0efec", "secondary": "#c3c2b7", "accent": "#3987e5", "other": "#5f5e5a"}, +} + + +def wins(results): + """``[(label, graphs won, is Cleora)]`` in similarity search, and the number of graphs.""" + columns = ["cleora"] + list(display.BASELINES) + summary = make_report.competition_summary(results.scenario_rows("retrieval", columns), columns) + rows = [(display.METHODS[m]["label"], summary[m]["wins"], m == "cleora") for m in columns] + return rows, summary["cleora"]["rows"] + + +def measured(results, dataset, quantity): + """``[(label, median of the timing runs, is Cleora)]`` for the methods that ran on a graph.""" + return [(label, value, label == "Cleora") for label, value in make_report.timed(results, dataset, quantity).items()] + + +def panel(axis, rows, title, subtitle, text, theme, slots, more_is_better=False): + """Horizontal bars, best first, every bar with its name and its value written out. + ``slots``: bars the panel has room for, so that all panels draw them equally thick.""" + rows = sorted(rows, key=lambda row: (not row[2], -row[1] if more_is_better else row[1])) + largest = max(value for _, value, _ in rows) or 1.0 + for position, (label, value, ours) in enumerate(rows): + colour = theme["accent"] if ours else theme["other"] + axis.barh(position, value, height=0.62, color=colour, linewidth=0) + axis.text(-0.02 * largest, position, label, ha="right", va="center", fontsize=10.5, + color=theme["ink"] if ours else theme["secondary"], fontweight="bold" if ours else "normal") + axis.text(value + 0.02 * largest, position, text(value), ha="left", va="center", fontsize=10.5, + color=theme["ink"] if ours else theme["secondary"], fontweight="bold" if ours else "normal") + axis.set_ylim(slots - 0.4, -0.6) + axis.set_xlim(0, largest * 1.22) + axis.axis("off") + axis.text(-0.3, 1.14, title, transform=axis.transAxes, ha="left", va="bottom", fontsize=13, fontweight="bold", color=theme["ink"]) + axis.text(-0.3, 1.05, subtitle, transform=axis.transAxes, ha="left", va="bottom", fontsize=10, color=theme["secondary"]) + + +def draw(results, theme, path): + import logging + + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + logging.getLogger("matplotlib.font_manager").setLevel(logging.ERROR) # the first family that exists is used + plt.rcParams["font.family"] = ["Inter", "Helvetica Neue", "Arial", "Liberation Sans", "DejaVu Sans"] + plt.rcParams["svg.fonttype"] = "path" # letters as outlines: the same picture on every machine + plt.rcParams["svg.hashsalt"] = "cleora" # and the same file for the same numbers + won, graphs = wins(results) + seconds, memory = measured(results, TIME_GRAPH, "seconds"), measured(results, MEMORY_GRAPH, "peak_rss_mb") + size = lambda name: f"{results.meta[name]['num_nodes']:,} nodes, {results.meta[name]['num_edges'] / 1e6:.1f}M edges" + figure, axes = plt.subplots(1, 3, figsize=(13.2, 4.3), gridspec_kw={"width_ratios": [1, 1, 1], "wspace": 0.62}) + slots = max(len(won), len(seconds), len(memory)) + panel(axes[0], won, "Best in similarity search", f"number of graphs, out of {graphs}", str, theme, slots, more_is_better=True) + panel(axes[1], seconds, "Time to embed", f"{display.DATASET_LABELS[TIME_GRAPH]}: {size(TIME_GRAPH)}", + make_report.duration, theme, slots) + panel(axes[2], memory, "Peak memory", f"{display.DATASET_LABELS[MEMORY_GRAPH]}: {size(MEMORY_GRAPH)}", + lambda megabytes: f"{megabytes / 1024:.0f} GB", theme, slots) + figure.subplots_adjust(left=0.085, right=0.985, top=0.80, bottom=0.02) + figure.savefig(path, transparent=True, metadata={"Date": None} if path.endswith(".svg") else None) + plt.close(figure) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("--data", required=True, help="directory with datasets/, results/ and timing/") + parser.add_argument("--out", required=True, help="directory for the two figures") + args = parser.parse_args() + results = make_report.Results(os.path.abspath(os.path.expanduser(args.data))) + os.makedirs(args.out, exist_ok=True) + for name, theme in THEMES.items(): + path = os.path.join(args.out, f"summary_{name}.svg") + draw(results, theme, path) + print(path) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/popularity_exponent.py b/benchmarks/popularity_exponent.py new file mode 100755 index 0000000..95a08d3 --- /dev/null +++ b/benchmarks/popularity_exponent.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python +"""Measures candidate exponents of the popularity prior on validation data. + + python benchmarks/popularity_exponent.py --data ~/cleora-bench [--tiers SM] [--datasets a,b] [--tasks lp,nc] + +This is how the exponents of ``pycleora.scale_by_popularity`` were chosen; it is not a step +of the benchmark itself. For every graph and task, Cleora as the benchmark runs it for the +task, with each exponent of ``popularity.EXPONENTS`` in place of the configured one: + +* ``lp`` the link split of seed 0; validation scores of the dot product (MRR against the + sampled candidates, recall@10 among all nodes); +* ``nc`` graphs with node labels; the validation score of logistic regression (seed 0, + three splits). + +Test edges and test labels are never scored. The results go to ``/popularity``; +``make_report.py`` shows them as the tables ``popularity_exponent`` and +``popularity_exponent_classification``. +""" + +import argparse +import json +import os +import shutil +import sys +import tempfile + +import numpy as np + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from cleora_bench import configurations, datasets, display, popularity, probes, runner, tasks # noqa: E402 + + +def measure(dataset, task, data, device, threads, timeout=3600): + """Writes ``{exponent: {metric: validation score}}`` of a graph and task, unless it is + there. Returns the path, or None for a graph without labels and the task ``nc``.""" + path = popularity.path(data, task, dataset) + if os.path.exists(path): + return path + graph = datasets.load(dataset, os.path.join(data, "datasets")) + if task == "nc" and "labels" not in graph: + return None + cache = os.path.join(data, "cache") + if task == "lp": + split = runner.link_split(graph, 0, cache) + edges, weights = split["embed"], None + else: + edges, weights = graph["edges"], graph.get("weights") + method, parameters = configurations.resolve(display.cleora_configuration("hyperedge", task)) + scores = {} + for exponent in popularity.EXPONENTS: + work = tempfile.mkdtemp(prefix=f"{dataset}_popularity_", dir=cache) + try: + vectors, record = runner.embed(method, dict(parameters, popularity=exponent), edges, + graph["meta"]["num_nodes"], weights, display.MAIN_DIM, 0, threads, work, timeout) + finally: + shutil.rmtree(work, ignore_errors=True) + if vectors is None: + raise RuntimeError(f"{dataset}: {record['reason']}") + if task == "lp": + validation = tasks.validation_scores(vectors, split, graph, device, 0) + scores[str(exponent)] = {metric: validation[metric] for metric in popularity.METRICS["lp"]} + else: + chosen = tasks.node_classification(vectors, graph, device, (0, 1, 2), ("logistic",))["logistic"]["chosen"] + scores[str(exponent)] = {"score": float(np.mean([split["validation_score"] for split in chosen]))} + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w") as handle: + json.dump(scores, handle, indent=1) + return path + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("--data", required=True, help="directory of the benchmark (datasets, caches)") + parser.add_argument("--datasets", default=None, help="comma-separated names (default: all of --tiers)") + parser.add_argument("--tiers", default="SM", help="dataset tiers when --datasets is not given") + parser.add_argument("--tasks", default="lp,nc") + parser.add_argument("--threads", type=int, default=os.cpu_count()) + args = parser.parse_args() + data = os.path.abspath(os.path.expanduser(args.data)) + device = probes.pick_device() + probes.torch.set_num_threads(min(args.threads, 4)) # the small probes that are fitted on the CPU + for dataset in args.datasets.split(",") if args.datasets else datasets.names(args.tiers): + for task in args.tasks.split(","): + print(measure(dataset, task, data, device, args.threads) or f"{dataset}: no node labels", flush=True) + print(popularity.link_table(data), popularity.classification_table(data), sep="\n\n") + + +if __name__ == "__main__": + main() diff --git a/benchmarks/prepare_datasets.py b/benchmarks/prepare_datasets.py new file mode 100755 index 0000000..c49c0c6 --- /dev/null +++ b/benchmarks/prepare_datasets.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python +"""Downloads the benchmark datasets from their original sources and stores them in the +canonical form of ``cleora_bench.datasets``. + + python benchmarks/prepare_datasets.py --data ~/cleora-bench --tiers SM + +Datasets that are already prepared are skipped. A dataset whose source no longer yields +the graph the benchmark was run on fails with a message; the others are still prepared. +""" + +import argparse +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from cleora_bench import datasets # noqa: E402 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("--data", required=True, help="directory for datasets, caches and results") + parser.add_argument("--datasets", default=None, help="comma-separated names (default: all of --tiers)") + parser.add_argument("--tiers", default="S", help="S (small), M (medium), L (large); e.g. SM") + args = parser.parse_args() + root = os.path.join(os.path.abspath(os.path.expanduser(args.data)), "datasets") + failed = [] + for name in args.datasets.split(",") if args.datasets else datasets.names(args.tiers): + started = time.time() + try: + meta = datasets.load(name, root)["meta"] + except Exception as error: # report and go on with the other datasets; the exit code says it happened + failed.append(name) + print(f"FAILED {name}: {type(error).__name__}: {error}", flush=True) + continue + labels = f"{meta['num_classes']} {'labels' if meta.get('multilabel') else 'classes'}" if meta["num_classes"] else "no labels" + print(f"{name:18} {meta['num_nodes']:>9,} nodes {meta['num_edges']:>11,} edges {labels:12} " + f"[{time.time() - started:.0f}s]", flush=True) + if failed: + sys.exit(f"Could not prepare: {', '.join(failed)}") + + +if __name__ == "__main__": + main() diff --git a/benchmarks/replicate.sh b/benchmarks/replicate.sh new file mode 100755 index 0000000..c2e8fab --- /dev/null +++ b/benchmarks/replicate.sh @@ -0,0 +1,109 @@ +#!/usr/bin/env bash +# Replicates the benchmark of the README from nothing: environments, datasets, every +# method, the tables and the figures. +# +# benchmarks/replicate.sh [options] +# +# Everything is written under ; finished jobs are skipped, so the script can +# be interrupted and started again, and several copies can run on disjoint --datasets. +# +# --tiers S|SM|SML datasets by size: S up to ~1M edges (default), M up to ~60M, L larger +# --datasets a,b,c these datasets instead of whole tiers +# --dim N embedding dimensionality of every method (default 1024) +# --threads N threads per embedding method (default: all cores) +# +# Parts that can be switched off: +# +# --no-setup environments and baseline checkouts already exist +# --no-baselines do not run the nine baseline methods +# --no-previous do not run the pycleora 3.2 default (whitening, 40 iterations) +# --no-tuned no iteration sweep and no "Cleora, tuned" rows +# --no-popularity no measurement of the exponents of the popularity prior +# --no-timing no separate time / memory measurement +# --no-figures no UMAP figures +# --no-report do not write benchmarks/RESULTS.md and the tables of the READMEs +# +# The time and memory measurement runs one method at a time and is only meaningful on a +# machine that does nothing else. +set -euo pipefail + +[ $# -ge 1 ] || { sed -n '2,28p' "$0" | sed 's/^# \{0,1\}//'; exit 2; } +mkdir -p "$1" +data=$(cd "$1" && pwd) +shift +here=$(cd "$(dirname "$0")" && pwd) + +tiers=S datasets="" dim=1024 threads=$(getconf _NPROCESSORS_ONLN) +setup=1 baselines=1 previous=1 tuned=1 popularity=1 timing=1 figures=1 report=1 +while [ $# -gt 0 ]; do + case $1 in + --tiers) tiers=$2; shift ;; + --datasets) datasets=$2; shift ;; + --dim) dim=$2; shift ;; + --threads) threads=$2; shift ;; + --no-setup) setup=0 ;; + --no-baselines) baselines=0 ;; + --no-previous) previous=0 ;; + --no-tuned) tuned=0 ;; + --no-popularity) popularity=0 ;; + --no-timing) timing=0 ;; + --no-figures) figures=0 ;; + --no-report) report=0 ;; + *) echo "unknown option: $1" >&2; exit 2 ;; + esac + shift +done + +[ $setup = 1 ] && "$here/setup.sh" "$data" +export CLEORA_BENCH_ENVS=$data/envs CLEORA_BENCH_BASELINES=$data/baselines +python=$data/envs/main/bin/python +configurations() { # names of a group of Cleora configurations + "$python" -c "import sys; sys.path.insert(0, '$here'); from cleora_bench import configurations as c; print(','.join($1))" +} + +# Three seeds on tier S, one on the larger graphs. +for tier in $(echo "$tiers" | grep -o .); do + if [ -n "$datasets" ]; then selection=(--datasets "$datasets"); else selection=(--tiers "$tier"); fi + seeds=0,1,2; [ "$tier" = S ] || seeds=0 + # hours a method may take on one graph + limit=6; [ "$tier" = L ] && limit=3 + run() { "$python" "$here/run_benchmark.py" --data "$data" "${selection[@]}" --threads "$threads" --timeout "$limit" "$@"; } + + "$python" "$here/prepare_datasets.py" --data "$data" "${selection[@]}" + + # Cleora with the iterations the library suggests for the task, and the plain default for the figures + run --dim "$dim" --seeds "$seeds" --tasks nc --methods "$(configurations "c.automatic('classification')")" + run --dim "$dim" --seeds "$seeds" --tasks lp,viz --methods "$(configurations "c.automatic('similarity')")" + + if [ $baselines = 1 ]; then + run --dim "$dim" --seeds "$seeds" + fi + if [ $previous = 1 ]; then + run --dim "$dim" --seeds "$seeds" --methods cleora_whiten40 + fi + if [ $tuned = 1 ]; then + # one cheap pass over the iteration counts, then the counts that validated best in full + run --results sweep --dim "$dim" --seeds 0 --tasks nc,lp --node-probes logistic --pair-probes cosine,dot \ + --methods "$(configurations "c.sweep('hyperedge') + c.sweep('pair')")" + "$python" "$here/select_iterations.py" --data "$data" + run --dim "$dim" --seeds "$seeds" --tasks nc,lp --methods cleora_tuned + fi + if [ $popularity = 1 ] && [ "$tier" != L ]; then + # how the exponent of the popularity prior was chosen: validation scores by exponent + "$python" "$here/popularity_exponent.py" --data "$data" "${selection[@]}" --threads "$threads" + fi + if [ $timing = 1 ]; then + run --results timing --dim "$dim" --seeds 0,1,2 --tasks time \ + --methods "$(configurations "[c.AUTO[('hyperedge', 'left', 'general')], 'cleora_whiten40'] + list(c.DEFAULT)")" + fi + [ -n "$datasets" ] && break +done + +if [ $figures = 1 ]; then + "$python" "$here/make_figures.py" --data "$data" --out "$here/figures" --dim "$dim" + [ $timing = 1 ] && "$python" "$here/make_summary_figure.py" --data "$data" --out "$here/figures" +fi +if [ $report = 1 ]; then + "$python" "$here/make_report.py" --data "$data" --out "$here/RESULTS.md" --dump "$here/results.csv.gz" \ + --readme "$here/README.md" --readme "$here/../README.md" +fi diff --git a/benchmarks/results.csv.gz b/benchmarks/results.csv.gz new file mode 100644 index 0000000..5e763bf Binary files /dev/null and b/benchmarks/results.csv.gz differ diff --git a/benchmarks/run_benchmark.py b/benchmarks/run_benchmark.py new file mode 100755 index 0000000..49af80e --- /dev/null +++ b/benchmarks/run_benchmark.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python +"""Runs benchmark jobs: every requested method on every requested dataset and task. + + python benchmarks/run_benchmark.py --data ~/cleora-bench --datasets cora,citeseer \\ + --methods cleora,deepwalk,prone --dim 1024 --seeds 0,1,2 + +Results are written as JSON under ``/results`` (one file per job; finished jobs are +skipped, so the command can be repeated or run in several processes on disjoint +datasets). ``benchmarks/make_report.py`` turns them into the tables of the README. + +The method ``cleora_tuned`` stands for the fixed-iteration configurations that +``benchmarks/select_iterations.py`` chose for the dataset from a sweep. +""" + +import argparse +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from cleora_bench import configurations, datasets, probes, runner, selection, tasks # noqa: E402 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("--data", required=True, help="directory for datasets, caches and results") + parser.add_argument("--datasets", default=None, help="comma-separated names (default: all of --tiers)") + parser.add_argument("--tiers", default="S", help="dataset tiers to run when --datasets is not given: S, M, L") + parser.add_argument("--methods", default=",".join(configurations.DEFAULT), help="comma-separated configuration names") + parser.add_argument("--dim", type=int, default=1024) + parser.add_argument("--seeds", default="0,1,2", help="seeds of the embedding methods and of the link splits") + parser.add_argument("--tasks", default="nc,lp,viz", + help="nc (node classification), lp (link prediction), viz (vectors of the whole graph " + "for the figures, where nc does not already provide them), time (embedding time " + "and memory only: run it alone on an idle machine, with --results timing)") + parser.add_argument("--node-probes", default=",".join(tasks.NODE_PROBES)) + parser.add_argument("--pair-probes", default=",".join(tasks.PAIR_PROBES)) + parser.add_argument("--threads", type=int, default=os.cpu_count()) + parser.add_argument("--timeout", type=float, default=6.0, help="hours a method may take on one graph") + parser.add_argument("--retry-failed", action="store_true") + parser.add_argument("--results", default="results", help="name of the results directory under --data") + args = parser.parse_args() + + args.data = os.path.abspath(os.path.expanduser(args.data)) + names = args.datasets.split(",") if args.datasets else datasets.names(args.tiers) + device = probes.pick_device() + probes.torch.set_num_threads(min(args.threads, 4)) # the small probes that are fitted on the CPU + for dataset in names: + meta = datasets.load(dataset, os.path.join(args.data, "datasets"))["meta"] + for task in args.tasks.split(","): + if task == "nc" and meta["num_classes"] == 0: + print(f"{dataset}: no node labels - link task only", flush=True) + continue + if task == "viz" and meta["num_classes"] > 0: + continue # the node-classification run saves the sample + method_ids = [] + for method_id in args.methods.split(","): + method_ids += selection.configurations_for(args.data, dataset, task) if method_id == selection.TUNED else [method_id] + for method_id in method_ids: + method, params = configurations.resolve(method_id) + for seed in [int(s) for s in args.seeds.split(",")]: + if task == "viz" and seed != 0: + continue + started = time.time() + result = runner.run_job( + dataset, method_id, method, params, args.dim, seed, task, + data_root=os.path.join(args.data, "datasets"), results=os.path.join(args.data, args.results), + cache=os.path.join(args.data, "cache"), threads=args.threads, timeout=args.timeout * 3600, + device=device, node_probes=tuple(args.node_probes.split(",")), + pair_probes=tuple(args.pair_probes.split(",")), retry_failed=args.retry_failed) + embedding = result["embedding"] + if embedding["status"] != "ok": + summary = f"{embedding['status']}: {embedding['reason']}" + elif task == "viz": + summary = "sample saved" + elif task == "time": + summary = f"peak memory {embedding['peak_rss_mb'] / 1024:.2f} GB" + elif task == "nc": + first = result["probes"][next(iter(result["probes"]))]["metrics"] + key = "accuracy" if "accuracy" in first[0] else "micro_f1" + summary = " ".join(f"{probe}={sum(m[key] for m in r['metrics']) / len(r['metrics']):.4f}" + for probe, r in result["probes"].items()) + f" ({key})" + else: + summary = " ".join(f"{probe}={r['metrics']['mrr']:.4f}" for probe, r in result["probes"].items()) + " (MRR)" + seconds = embedding.get("seconds") + print(f"{dataset:18} {task} {method_id:22} seed={seed} embed={seconds if seconds is None else round(seconds, 1)}s " + f"{summary} [{time.time() - started:.0f}s]", flush=True) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/select_iterations.py b/benchmarks/select_iterations.py new file mode 100755 index 0000000..0f13128 --- /dev/null +++ b/benchmarks/select_iterations.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python +"""Chooses Cleora's iteration counts from the sweep, on validation scores. + + python benchmarks/select_iterations.py --data ~/cleora-bench + +Reads ``/sweep`` (written by ``run_benchmark.py --results sweep`` with the +configurations of ``cleora_bench.configurations.sweep``) and writes +``/selected_iterations.json``, which ``--methods cleora_tuned`` and the report use. +""" + +import argparse +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from cleora_bench import configurations, selection # noqa: E402 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("--data", required=True) + args = parser.parse_args() + data = os.path.abspath(os.path.expanduser(args.data)) + for dataset, tasks in sorted(selection.write(data).items()): + for task, families in sorted(tasks.items()): + print(f"{dataset:18} {task} " + " ".join(f"{family}: {configurations.iterations(name)}" for family, name in sorted(families.items()))) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/setup.sh b/benchmarks/setup.sh new file mode 100755 index 0000000..492bc9c --- /dev/null +++ b/benchmarks/setup.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# Creates what the benchmark needs, all under one directory: +# +# /envs/main Python 3.12: pycleora (built from this repository), probes, report, +# figures, and the baselines that run on current NumPy / SciPy +# /envs/walks Python 3.11: DeepWalk / node2vec (PecanPy + gensim) +# /envs/karate Python 3.10: GraRep, HOPE, Walklets (karateclub) +# /baselines/* the authors' implementations of ProNE, NetMF, FastRP and RandNE, +# each at the commit the benchmark was run with +# +# Usage: benchmarks/setup.sh +# Needs: uv (https://docs.astral.sh/uv/), git, and a Rust toolchain to build pycleora. +# Running it again only adds what is missing. +set -euo pipefail + +[ $# -eq 1 ] || { echo "usage: $0 " >&2; exit 2; } +command -v uv >/dev/null || { echo "uv is required: https://docs.astral.sh/uv/" >&2; exit 1; } +command -v cargo >/dev/null || { echo "a Rust toolchain is required: https://rustup.rs" >&2; exit 1; } +mkdir -p "$1" +home=$(cd "$1" && pwd) +here=$(cd "$(dirname "$0")" && pwd) + +environment() { # name, Python version + local python="$home/envs/$1/bin/python" + [ -x "$python" ] || uv venv --quiet --python "$2" "$home/envs/$1" + uv pip install --quiet --python "$python" -r "$here/envs/$1.txt" + echo "environment $1: $("$python" --version)" +} + +environment main 3.12 +uv pip install --quiet --python "$home/envs/main/bin/python" "$here/.." +environment walks 3.11 +environment karate 3.10 +uv pip install --quiet --python "$home/envs/karate/bin/python" --no-deps karateclub==1.3.3 + +baseline() { # directory, repository, commit + local target="$home/baselines/$1" + [ -d "$target/.git" ] || git clone --quiet "$2" "$target" + git -C "$target" -c advice.detachedHead=false checkout --quiet "$3" + echo "baseline $1 at $(git -C "$target" rev-parse --short HEAD)" +} + +baseline ProNE https://github.com/THUDM/ProNE.git 873630a5943f3eba8f4bbc9751fdf16af98d2171 +baseline NetMF https://github.com/xptree/NetMF.git 77286b826c4af149055237cef65e2a500e15631a +baseline FastRP https://github.com/GTmac/FastRP.git 3a6a71c02a47b131445ed091db6d4ad9aed47d7d +baseline RandNE https://github.com/ZW-ZHANG/RandNE.git bf06bd77b3c53fcfa9d80eb076a86023443bab26 + +echo +echo "Ready. The benchmark scripts need:" +echo " export CLEORA_BENCH_ENVS=$home/envs CLEORA_BENCH_BASELINES=$home/baselines" +echo " $home/envs/main/bin/python benchmarks/run_benchmark.py --data $home ..." diff --git a/pycleora/__init__.py b/pycleora/__init__.py index 866a6df..93b2918 100644 --- a/pycleora/__init__.py +++ b/pycleora/__init__.py @@ -1,7 +1,10 @@ +import warnings + import numpy as np from typing import Optional, List, Dict, Callable, Tuple, Union from .pycleora import SparseMatrix +from . import pycleora as _core from . import stats from . import preprocess from . import align @@ -9,8 +12,21 @@ from . import search from . import compress +__version__ = _core.__version__ + DEFAULT_FEATURE_DIM = 256 -DEFAULT_NUM_ITERATIONS = 40 +# "auto": SparseMatrix.suggest_iterations - or WHITENED_ITERATIONS with whitening. +DEFAULT_NUM_ITERATIONS = "auto" +DEFAULT_WHITEN = False +# Whitening counteracts over-smoothing, so with it the number of iterations hardly +# matters once it is large enough. 40 is what pycleora 3.2 used. +WHITENED_ITERATIONS = 40 +# Exponent of the popularity prior of scale_by_popularity: the one with the best mean +# validation score over the graphs of the benchmark (benchmarks/README.md). +DEFAULT_POPULARITY_EXPONENT = 0.0625 + +_NORMALIZATIONS = ("l2", "l1", "spectral", "none") +_ROW_CHUNK = 65536 def embed_using_baseline_cleora(graph, feature_dim: int, iter: int): @@ -26,6 +42,13 @@ def _validate_propagation(propagation: str): raise ValueError(f"Unknown propagation type: '{propagation}'. Use 'left' or 'symmetric'.") +def _validate_normalization(normalization: str): + if normalization not in _NORMALIZATIONS: + raise ValueError( + f"Unknown normalization method: {normalization}. Use 'l2', 'l1', 'spectral', or 'none'." + ) + + def _get_propagate_fn(graph: SparseMatrix, propagation: str): _validate_propagation(propagation) return ( @@ -36,16 +59,47 @@ def _get_propagate_fn(graph: SparseMatrix, propagation: str): def _to_scipy_sparse(graph: SparseMatrix, markov_type: str = "left"): + """The graph as a scipy CSR matrix ('left', 'symmetric' or 'raw' weights).""" from scipy.sparse import csr_matrix - rows, cols, vals, n_rows, n_cols = graph.to_sparse_csr(markov_type) - return csr_matrix( - (vals, (rows.astype(np.int32), cols.astype(np.int32))), - shape=(n_rows, n_cols), - ) + indptr, indices, data = graph.to_csr(markov_type) + n = graph.num_entities + return csr_matrix((data, indices, indptr), shape=(n, n)) -def _auto_iterations(feature_dim: int) -> int: - return DEFAULT_NUM_ITERATIONS +def _resolve_iterations( + num_iterations: Union[int, str], graph: SparseMatrix, propagation: str, whiten: bool +) -> int: + """The number of iterations as a non-negative int; ``"auto"`` is decided here.""" + if isinstance(num_iterations, str): + if num_iterations != "auto": + raise ValueError(f"num_iterations must be an int or 'auto', got '{num_iterations}'") + return WHITENED_ITERATIONS if whiten else graph.suggest_iterations(propagation) + if num_iterations < 0: + raise ValueError(f"num_iterations must not be negative, got {num_iterations}") + return num_iterations + + +def _warn_if_whitening_is_degenerate(num_entities: int, feature_dim: int) -> None: + """Whitening N points in D >= N - 1 dimensions turns them into the corners of a + regular simplex: every pair of vectors has the same cosine, -1 / (N - 1), and + nothing of the graph is left in the embedding.""" + if 1 < num_entities <= feature_dim + 1: + warnings.warn( + f"Whitening cannot work here: the graph has {num_entities} entities and the embedding " + f"{feature_dim} dimensions. With no more entities than dimensions + 1, whitening leaves " + "nothing of the graph in the vectors (in general they all end up equidistant). " + "Use a smaller feature_dim or whiten=False.", + RuntimeWarning, + stacklevel=3, + ) + + +def _as_float32_matrix(array, name: str = "embeddings") -> np.ndarray: + """A private, C-contiguous float32 copy of a 2-D array.""" + matrix = np.array(array, dtype=np.float32, order="C") + if matrix.ndim != 2: + raise ValueError(f"{name} must be a 2-dimensional array, got {matrix.ndim} dimension(s)") + return matrix def embed( @@ -60,23 +114,48 @@ def embed( callback: Optional[Callable[[int, np.ndarray], None]] = None, residual_weight: float = 0.0, convergence_threshold: float = 0.0, - whiten: bool = True, + whiten: bool = DEFAULT_WHITEN, ) -> np.ndarray: - if isinstance(num_iterations, str): - if num_iterations == "auto": - num_iterations = _auto_iterations(feature_dim) - else: - raise ValueError(f"num_iterations must be an int or 'auto', got '{num_iterations}'") + """Embeds the entities of ``graph``. + + Every iteration propagates the vectors along the graph and normalises the rows. + This is classic Cleora: it runs entirely in the Rust core and needs no more memory + than two embedding matrices. + + ``num_iterations="auto"`` (the default) takes the number of iterations from the + density of the graph: ``graph.suggest_iterations(propagation)``, a compromise + that needs no labels. Similarity search is best with somewhat fewer iterations + and classification with more: pass + ``graph.suggest_iterations(propagation, purpose="similarity")`` or + ``purpose="classification"`` when the use is known. When there is a validation + set, choosing the number on it is cheap (``callback`` receives the vectors after + every iteration) and usually worth another one or two per cent. + + ``whiten=True`` additionally PCA-whitens the columns after every iteration, which + was the default of pycleora 3.2. It is 10-100 times slower and needs many more + entities than dimensions: with ``num_entities <= feature_dim + 1`` all whitened + vectors are equidistant and the result is useless (a ``RuntimeWarning`` says so). + With whitening, ``"auto"`` means 40 iterations. + """ + _validate_propagation(propagation) + _validate_normalization(normalization) + # Both the Rust core and the loop below skip the residual for a weight outside + # (0, 1), so a wrong value would be ignored instead of reported. + if not 0.0 <= residual_weight < 1.0: + raise ValueError(f"residual_weight must be in [0, 1), got {residual_weight}") + num_iterations = _resolve_iterations(num_iterations, graph, propagation, whiten) + if whiten and num_iterations > 0: + _warn_if_whitening_is_degenerate(graph.num_entities, feature_dim) + use_fast_path = ( initial_embeddings is None and callback is None and normalization == "l2" and not whiten ) - if use_fast_path: if convergence_threshold > 0: - embeddings, actual_iters = graph.embed_fast_convergence( + embeddings, _ = graph.embed_fast_convergence( feature_dim, num_iterations, propagation=propagation, @@ -94,84 +173,129 @@ def embed( residual_weight=residual_weight, num_workers=num_workers, ) + return embeddings + + if initial_embeddings is not None: + embeddings = _as_float32_matrix(initial_embeddings, "initial_embeddings") + if embeddings.shape[0] != graph.num_entities: + raise ValueError( + f"initial_embeddings has {embeddings.shape[0]} rows but graph has {graph.num_entities} entities" + ) else: - propagate_fn = _get_propagate_fn(graph, propagation) + embeddings = graph.initialize_deterministically(feature_dim, seed) - if initial_embeddings is not None: - embeddings = initial_embeddings.astype(np.float32) - if embeddings.shape[0] != graph.num_entities: - raise ValueError( - f"initial_embeddings has {embeddings.shape[0]} rows but graph has {graph.num_entities} entities" - ) - else: - embeddings = graph.initialize_deterministically(feature_dim, seed) + propagate_fn = _get_propagate_fn(graph, propagation) + use_residual = 0.0 < residual_weight < 1.0 + + if normalization == "l2" and not whiten and callback is None and not use_residual and convergence_threshold <= 0: + # Nothing has to look at the vectors between iterations: the core runs them + # all, with the normalisation fused into the propagation. + iterate_inplace = ( + graph.symmetric_markov_propagate_normalized_inplace + if propagation == "symmetric" + else graph.left_markov_propagate_normalized_inplace + ) + iterate_inplace(embeddings, num_iterations, num_workers) + return embeddings + if normalization == "spectral": + # The SVD-based normalisation cannot work in place. for i in range(num_iterations): - prev_embeddings = embeddings - prev = embeddings if residual_weight > 0 else None + previous = embeddings embeddings = propagate_fn(embeddings, num_workers=num_workers) - - if residual_weight > 0 and prev is not None: - embeddings = (1 - residual_weight) * embeddings + residual_weight * prev - + if use_residual: + _mix_residual_inplace(embeddings, previous, residual_weight) embeddings = _postprocess_iteration(embeddings, normalization, whiten) - if callback is not None: callback(i, embeddings) - - if convergence_threshold > 0 and i > 0: - rmse = _compute_rmse(embeddings, prev_embeddings) - if rmse < convergence_threshold: + if convergence_threshold > 0 and i > 0 and embeddings.shape == previous.shape: + if _compute_rmse(embeddings, previous) < convergence_threshold: break + return embeddings + + # Two buffers are reused for all iterations; every step works in place. + buffer = np.empty_like(embeddings) + for i in range(num_iterations): + propagate_fn(embeddings, num_workers=num_workers, out=buffer) + if use_residual: + _mix_residual_inplace(buffer, embeddings, residual_weight) + _postprocess_inplace(buffer, normalization, whiten, num_workers) + converged = ( + convergence_threshold > 0 + and i > 0 + and _compute_rmse(buffer, embeddings) < convergence_threshold + ) + embeddings, buffer = buffer, embeddings + if callback is not None: + # The buffers are recycled, so the callback gets its own copy. + callback(i, embeddings.copy()) + if converged: + break return embeddings -def whiten_embeddings(embeddings: np.ndarray, n_components: Optional[int] = None) -> np.ndarray: - n, d = embeddings.shape +def whiten_embeddings( + embeddings: np.ndarray, + n_components: Optional[int] = None, + num_workers: Optional[int] = None, + inplace: bool = False, +) -> np.ndarray: + """PCA-whitens the columns: zero mean, unit variance, no correlation. + + Columns come out ordered by decreasing variance of the input; the sign of every + column is fixed so that the result does not depend on the LAPACK build. + With ``inplace=True`` a C-contiguous float32 input is overwritten and returned + (only possible when all components are kept). + """ + source = np.asarray(embeddings) + if source.ndim != 2: + raise ValueError(f"embeddings must be a 2-dimensional array, got {source.ndim} dimension(s)") + owned = False + if source.dtype != np.float32 or not source.flags.c_contiguous: + source = np.ascontiguousarray(source, dtype=np.float32) + owned = True + n, d = source.shape if n <= 1: - return embeddings.copy() - chunk = 50000 - - mean = embeddings.mean(axis=0, dtype=np.float64) + return source if (inplace or owned) else source.copy() - cov = np.zeros((d, d), dtype=np.float64) - for i in range(0, n, chunk): - end = min(i + chunk, n) - block = embeddings[i:end].astype(np.float64) - mean - cov += block.T @ block - cov *= 1.0 / (n - 1) - - eigenvalues, eigenvectors = np.linalg.eigh(cov) - - idx = np.argsort(eigenvalues)[::-1] - eigenvalues = eigenvalues[idx] - eigenvectors = eigenvectors[:, idx] + mean, covariance = _core.column_mean_cov(source, num_workers) + eigenvalues, eigenvectors = np.linalg.eigh(covariance) + order = np.argsort(eigenvalues)[::-1] + eigenvalues = eigenvalues[order] + eigenvectors = eigenvectors[:, order] if n_components is not None: eigenvalues = eigenvalues[:n_components] eigenvectors = eigenvectors[:, :n_components] + # Eigenvectors are defined up to sign: make the largest component positive. + pivot = np.argmax(np.abs(eigenvectors), axis=0) + signs = np.sign(eigenvectors[pivot, np.arange(eigenvectors.shape[1])]) + signs[signs == 0] = 1.0 + eigenvectors = eigenvectors * signs + scale = 1.0 / np.sqrt(np.maximum(eigenvalues, 1e-10)) - transform = (eigenvectors * scale).astype(np.float32) + transform = np.ascontiguousarray(eigenvectors * scale, dtype=np.float32) mean_f32 = mean.astype(np.float32) - out = np.empty((n, transform.shape[1]), dtype=np.float32) - for i in range(0, n, chunk): - end = min(i + chunk, n) - block = embeddings[i:end] - mean_f32 - np.dot(block, transform, out=out[i:end]) - return out + square = transform.shape[1] == d + if square and (owned or (inplace and source.flags.writeable)): + _core.center_project_inplace(source, mean_f32, transform, num_workers) + return source + return _core.center_project(source, mean_f32, transform, num_workers) def embed_with_node_features( graph: SparseMatrix, node_features: Dict[str, np.ndarray], - num_iterations: int = DEFAULT_NUM_ITERATIONS, + num_iterations: Union[int, str] = DEFAULT_NUM_ITERATIONS, propagation: str = "left", normalization: str = "l2", feature_weight: float = 0.5, num_workers: Optional[int] = None, + seed: int = 0, + whiten: bool = DEFAULT_WHITEN, ) -> np.ndarray: if not node_features: raise ValueError("node_features must be a non-empty dict of entity_id -> feature_vector") @@ -179,7 +303,7 @@ def embed_with_node_features( sample_feat = next(iter(node_features.values())) feat_dim = len(sample_feat) - init_emb = graph.initialize_deterministically(feat_dim) + init_emb = graph.initialize_deterministically(feat_dim, seed) index_map = {eid: i for i, eid in enumerate(graph.entity_ids)} for eid, feat in node_features.items(): @@ -200,29 +324,34 @@ def embed_with_node_features( normalization=normalization, initial_embeddings=init_emb, num_workers=num_workers, + whiten=whiten, ) def embed_with_attention( graph: SparseMatrix, feature_dim: int = DEFAULT_FEATURE_DIM, - num_iterations: int = DEFAULT_NUM_ITERATIONS, + num_iterations: Union[int, str] = DEFAULT_NUM_ITERATIONS, propagation: str = "left", normalization: str = "l2", attention_temperature: float = 1.0, seed: int = 0, num_workers: Optional[int] = None, callback: Optional[Callable[[int, np.ndarray], None]] = None, - whiten: bool = True, + whiten: bool = DEFAULT_WHITEN, ) -> np.ndarray: _validate_propagation(propagation) if attention_temperature <= 0: raise ValueError(f"attention_temperature must be positive, got {attention_temperature}") + num_iterations = _resolve_iterations(num_iterations, graph, propagation, whiten) if num_iterations <= 0: raise ValueError(f"num_iterations must be positive, got {num_iterations}") + if whiten: + _warn_if_whitening_is_degenerate(graph.num_entities, feature_dim) + embeddings = graph.initialize_deterministically(feature_dim, seed) propagate_fn = _get_propagate_fn(graph, propagation) @@ -235,37 +364,41 @@ def embed_with_attention( if num_iterations == 1: return embeddings - from scipy.sparse import csr_matrix, diags + from scipy.sparse import csr_matrix adj = _to_scipy_sparse(graph, propagation) - adj_rows, adj_cols = adj.nonzero() + n = adj.shape[0] + indptr, adj_cols = adj.indptr, adj.indices + row_lengths = np.diff(indptr) + adj_rows = np.repeat(np.arange(n, dtype=adj_cols.dtype), row_lengths) + nonempty = np.flatnonzero(row_lengths > 0) + edge_chunk = max(1, (1 << 24) // max(feature_dim, 1)) for i in range(1, num_iterations): - norms = np.linalg.norm(embeddings, axis=1, keepdims=True) - norms = np.maximum(norms, 1e-10) - emb_normed = embeddings / norms - - dot_products = np.sum(emb_normed[adj_rows] * emb_normed[adj_cols], axis=1) + norms = np.sqrt(np.einsum("ij,ij->i", embeddings, embeddings, dtype=np.float64)) + inv_norms = (1.0 / np.maximum(norms, 1e-10)).astype(np.float32) + + # cosine of every edge, computed in bounded chunks instead of materialising + # two (edges x dim) arrays + dot_products = np.empty(len(adj_cols), dtype=np.float64) + for start in range(0, len(adj_cols), edge_chunk): + stop = start + edge_chunk + r, c = adj_rows[start:stop], adj_cols[start:stop] + dot_products[start:stop] = ( + np.einsum("ij,ij->i", embeddings[r], embeddings[c], dtype=np.float64) + * inv_norms[r] * inv_norms[c] + ) attention_scores = dot_products / attention_temperature - row_max = np.full(adj.shape[0], -np.inf, dtype=np.float64) - np.maximum.at(row_max, adj_rows, attention_scores) - row_max[row_max == -np.inf] = 0.0 + row_max = np.zeros(n, dtype=np.float64) + if len(nonempty): + row_max[nonempty] = np.maximum.reduceat(attention_scores, indptr[:-1][nonempty]) + exp_scores = np.exp(attention_scores - row_max[adj_rows]) - shifted = attention_scores - row_max[adj_rows] - exp_scores = np.exp(shifted) - attn_exp = csr_matrix( - (exp_scores, (adj_rows, adj_cols)), - shape=adj.shape, - ) - row_sums = np.array(attn_exp.sum(axis=1)).flatten() - row_sums = np.maximum(row_sums, 1e-10) - inv_sums = 1.0 / row_sums - norm_matrix = diags(inv_sums) @ attn_exp - - weighted_adj = norm_matrix.multiply(adj) - row_sums_w = np.array(weighted_adj.sum(axis=1)).flatten() - row_sums_w = np.maximum(row_sums_w, 1e-10) - weighted_adj = diags(1.0 / row_sums_w) @ weighted_adj + # softmax over each row, applied on top of the graph weights and renormalised + weights = exp_scores * adj.data + row_sums = np.bincount(adj_rows, weights=weights, minlength=n) + weights /= np.maximum(row_sums, 1e-10)[adj_rows] + weighted_adj = csr_matrix((weights, adj_cols, indptr), shape=adj.shape) embeddings = (weighted_adj @ embeddings).astype(np.float32) embeddings = _postprocess_iteration(embeddings, normalization, whiten) @@ -276,6 +409,41 @@ def embed_with_attention( return embeddings +def scale_by_popularity( + graph: SparseMatrix, + embeddings: np.ndarray, + exponent: float = DEFAULT_POPULARITY_EXPONENT, +) -> np.ndarray: + """Gives the vectors a popularity prior: row ``i`` times ``degree_i ** exponent``. + + The vectors of ``embed`` have unit length. Their dot product is the cosine: how + alike two entities are. Which links exist depends on more than that - a well + connected entity is in more of them. After this scaling the dot product is + ``cosine(i, j) * (degree_i * degree_j) ** exponent``, similarity times a + popularity prior, which finds missing links and recommendations better on most + graphs (``benchmarks/README.md``). Search the scaled vectors by dot product. + + ``degree`` is ``graph.entity_degrees``, the hyperedge mass of an entity. The + default exponent is small on purpose: the prior is to settle the order of + entities that are about equally similar, not to replace similarity. As features + of a classifier the vectors gain from a larger one, ``exponent=0.25``: the + classifier then knows how well connected an entity is. Keep the unit vectors + wherever "alike" is the question; where there is validation data, compare. + + Returns a new array; ``embeddings`` is not modified. + """ + vectors = np.asarray(embeddings, dtype=np.float32) + if vectors.ndim != 2 or vectors.shape[0] != graph.num_entities: + raise ValueError( + f"embeddings must have one row per entity ({graph.num_entities}), got shape {vectors.shape}" + ) + degrees = np.asarray(graph.entity_degrees, dtype=np.float64) + # an entity without mass has no vector to scale (and 0 ** negative is not a number) + factor = np.zeros_like(degrees) + np.power(degrees, exponent, out=factor, where=degrees > 0) + return vectors * factor[:, None].astype(np.float32) + + def embed_multiscale( graph: SparseMatrix, feature_dim: int = DEFAULT_FEATURE_DIM, @@ -284,9 +452,16 @@ def embed_multiscale( normalization: str = "l2", seed: int = 0, num_workers: Optional[int] = None, - whiten: bool = True, + whiten: bool = DEFAULT_WHITEN, ) -> np.ndarray: + """Concatenates the embeddings after each of the given numbers of iterations. + + The block of scale ``k`` is exactly ``embed(graph, feature_dim, k, ...)``. + """ propagate_fn = _get_propagate_fn(graph, propagation) + _validate_normalization(normalization) + if whiten: + _warn_if_whitening_is_degenerate(graph.num_entities, feature_dim) if scales is None: scales = [10, 20, 30, 40] @@ -296,12 +471,16 @@ def embed_multiscale( embeddings = graph.initialize_deterministically(feature_dim, seed) all_embeddings = [] + in_place = normalization != "spectral" current_iter = 0 for scale in sorted(scales): while current_iter < scale: embeddings = propagate_fn(embeddings, num_workers=num_workers) - embeddings = _postprocess_iteration(embeddings, normalization, whiten) + if in_place: + _postprocess_inplace(embeddings, normalization, whiten, num_workers) + else: + embeddings = _postprocess_iteration(embeddings, normalization, whiten) current_iter += 1 snapshot = embeddings.copy() all_embeddings.append(snapshot) @@ -313,49 +492,37 @@ def embed_weighted( edges_with_weights: List[Tuple[str, float]], columns: str, feature_dim: int = DEFAULT_FEATURE_DIM, - num_iterations: int = DEFAULT_NUM_ITERATIONS, + num_iterations: Union[int, str] = DEFAULT_NUM_ITERATIONS, propagation: str = "left", normalization: str = "l2", seed: int = 0, hyperedge_trim_n: int = 16, num_workers: Optional[int] = None, - whiten: bool = True, + whiten: bool = DEFAULT_WHITEN, ) -> Tuple[SparseMatrix, np.ndarray]: - from scipy.sparse import csr_matrix, diags - - edge_strs = [e for e, w in edges_with_weights] - weights = {e: w for e, w in edges_with_weights} - - graph = SparseMatrix.from_iterator(iter(edge_strs), columns, hyperedge_trim_n, num_workers) - - embeddings = graph.initialize_deterministically(feature_dim, seed) - - rows, cols, vals, n, _ = graph.to_sparse_csr(propagation) - adj = csr_matrix( - (vals.astype(np.float64), (rows.astype(np.int32), cols.astype(np.int32))), - shape=(n, n), + """Embeds a graph whose hyperedges carry weights. + + ``edges_with_weights`` holds ``(line, weight)`` pairs. A line with weight ``w`` + contributes ``w`` times the mass of an unweighted line, so an integer weight + ``k`` is equivalent to repeating the line ``k`` times. Weights must be finite + and non-negative; a zero weight removes the line. + """ + lines = [line for line, _ in edges_with_weights] + weights = np.fromiter((w for _, w in edges_with_weights), dtype=np.float64, count=len(lines)) + + graph = SparseMatrix.from_iterator( + iter(lines), columns, hyperedge_trim_n, num_workers, weights=weights + ) + embeddings = embed( + graph, + feature_dim=feature_dim, + num_iterations=num_iterations, + propagation=propagation, + normalization=normalization, + seed=seed, + num_workers=num_workers, + whiten=whiten, ) - - weight_diag = np.ones(n, dtype=np.float64) - index_map = {eid: i for i, eid in enumerate(graph.entity_ids)} - - for edge_str, w in edges_with_weights: - entities = edge_str.strip().split() - for ent in entities: - idx = index_map.get(ent) - if idx is not None: - weight_diag[idx] = max(weight_diag[idx], w) - - W = diags(weight_diag) - weighted_adj = W @ adj - row_sums = np.array(weighted_adj.sum(axis=1)).flatten() - row_sums = np.maximum(row_sums, 1e-10) - weighted_adj = diags(1.0 / row_sums) @ weighted_adj - - for i in range(num_iterations): - embeddings = (weighted_adj @ embeddings).astype(np.float32) - embeddings = _postprocess_iteration(embeddings, normalization, whiten) - return graph, embeddings @@ -363,45 +530,63 @@ def embed_directed( edges: List[str], columns: str, feature_dim: int = DEFAULT_FEATURE_DIM, - num_iterations: int = DEFAULT_NUM_ITERATIONS, + num_iterations: Union[int, str] = DEFAULT_NUM_ITERATIONS, normalization: str = "l2", seed: int = 0, hyperedge_trim_n: int = 16, num_workers: Optional[int] = None, - whiten: bool = True, + whiten: bool = DEFAULT_WHITEN, ) -> Tuple[SparseMatrix, np.ndarray]: + """Embeds a directed graph: in every line, earlier entities point to later ones. + + Each entity is propagated from the entities it points to only. An entity that + points to nothing (a sink) keeps its own vector, so no row of the result is zero. + """ from scipy.sparse import csr_matrix, diags graph = SparseMatrix.from_iterator(iter(edges), columns, hyperedge_trim_n, num_workers) + n = graph.num_entities + index_map = {eid: i for i, eid in enumerate(graph.entity_ids)} - directed_pairs = set() + sources: List[np.ndarray] = [] + targets: List[np.ndarray] = [] + pair_sources: List[int] = [] + pair_targets: List[int] = [] for edge_str in edges: - parts = edge_str.strip().split() - if len(parts) >= 2: - for i in range(len(parts)): - for j in range(i + 1, len(parts)): - directed_pairs.add((parts[i], parts[j])) - - index_map = {eid: i for i, eid in enumerate(graph.entity_ids)} - rows_list, cols_list, vals_list = [], [], [] + tokens = [index_map.get(token, -1) for token in edge_str.strip().split()] + if len(tokens) == 2: + if tokens[0] >= 0 and tokens[1] >= 0: + pair_sources.append(tokens[0]) + pair_targets.append(tokens[1]) + elif len(tokens) > 2: + ids = np.asarray(tokens, dtype=np.int64) + first, second = np.triu_indices(len(ids), k=1) + keep = (ids[first] >= 0) & (ids[second] >= 0) + sources.append(ids[first][keep]) + targets.append(ids[second][keep]) + sources.append(np.asarray(pair_sources, dtype=np.int64)) + targets.append(np.asarray(pair_targets, dtype=np.int64)) + source_idx = np.concatenate(sources) + target_idx = np.concatenate(targets) + + direction = csr_matrix( + (np.ones(len(source_idx), dtype=np.float32), (source_idx, target_idx)), shape=(n, n) + ) + direction.sum_duplicates() + direction.data[:] = 1.0 - r_arr, c_arr, v_arr, n, _ = graph.to_sparse_csr("left") - for r, c, v in zip(r_arr, c_arr, v_arr): - r_id = graph.entity_ids[int(r)] - c_id = graph.entity_ids[int(c)] - if (r_id, c_id) in directed_pairs: - rows_list.append(int(r)) - cols_list.append(int(c)) - vals_list.append(float(v)) + adj = _to_scipy_sparse(graph, "left").multiply(direction).tocsr().astype(np.float64) + row_sums = np.asarray(adj.sum(axis=1)).ravel() + # A sink has nothing to be propagated from. Its row would be zero, and the zeros + # would spread to everything upstream, one step per iteration: a self-loop makes + # it keep its own vector instead. + is_sink = (row_sums == 0).astype(np.float64) + adj = (diags(1.0 / np.maximum(row_sums, 1e-10)) @ adj + diags(is_sink)).tocsr() - adj = csr_matrix( - (vals_list, (rows_list, cols_list)), - shape=(n, n), - ) - row_sums = np.array(adj.sum(axis=1)).flatten() - row_sums = np.maximum(row_sums, 1e-10) - adj = diags(1.0 / row_sums) @ adj + if whiten: + _warn_if_whitening_is_degenerate(graph.num_entities, feature_dim) + num_iterations = _resolve_iterations(num_iterations, graph, "left", whiten) embeddings = graph.initialize_deterministically(feature_dim, seed) for i in range(num_iterations): embeddings = (adj @ embeddings).astype(np.float32) @@ -537,35 +722,123 @@ def remove_edges( return SparseMatrix.from_iterator(iter(remaining), columns, hyperedge_trim_n, num_workers) +def _rows_are_unit_norm(embeddings: np.ndarray) -> bool: + sample = embeddings[: min(len(embeddings), 10000)] + if len(sample) == 0: + return False + norms = np.sqrt(np.einsum("ij,ij->i", sample, sample, dtype=np.float64)) + return bool(np.all(np.abs(norms - 1.0) < 1e-3)) + + +def _frozen_inductive_update( + updated_graph: SparseMatrix, + old_entity_ids, + old_embeddings: np.ndarray, + propagation: str = "left", + refine_iterations: int = 3, + num_workers: Optional[int] = None, +) -> np.ndarray: + """Embeddings for ``updated_graph`` that keep every already known entity where + it is and place each new entity at the weighted average of its neighbours. + + Only the rows of the new entities are propagated, so the cost is proportional + to the number of their connections, not to the size of the graph.""" + n = updated_graph.num_entities + dim = old_embeddings.shape[1] + old_index = {eid: i for i, eid in enumerate(old_entity_ids)} + source = np.fromiter( + (old_index.get(eid, -1) for eid in updated_graph.entity_ids), dtype=np.int64, count=n + ) + known = source >= 0 + + embeddings = np.zeros((n, dim), dtype=np.float32) + embeddings[known] = old_embeddings[source[known]] + new_rows = np.flatnonzero(~known) + if len(new_rows) == 0: + return embeddings + + propagate_fn = _get_propagate_fn(updated_graph, propagation) + available = known.astype(np.float32).reshape(n, 1) + unit_norm = _rows_are_unit_norm(old_embeddings) + + for _ in range(max(1, refine_iterations)): + # Average over the neighbours that already have a vector. New entities that + # are only reachable through other new entities are placed in later rounds. + mass = propagate_fn(available, num_workers=num_workers, rows=new_rows).ravel() + placed = mass > 1e-12 + estimate = propagate_fn(embeddings, num_workers=num_workers, rows=new_rows) + estimate[placed] /= mass[placed, None] + estimate[~placed] = 0.0 + if unit_norm: + norms = np.sqrt(np.einsum("ij,ij->i", estimate, estimate, dtype=np.float64)) + estimate /= np.maximum(norms, 1e-10)[:, None].astype(np.float32) + embeddings[new_rows] = estimate + available[new_rows, 0] = placed + + return embeddings + + def embed_inductive( trained_graph: SparseMatrix, trained_embeddings: np.ndarray, existing_edges: List[str], new_edges: List[str], columns: str, - num_iterations: int = DEFAULT_NUM_ITERATIONS, + num_iterations: Union[int, str] = DEFAULT_NUM_ITERATIONS, propagation: str = "left", normalization: str = "l2", hyperedge_trim_n: int = 16, num_workers: Optional[int] = None, + mode: str = "frozen", + refine_iterations: int = 3, + whiten: bool = DEFAULT_WHITEN, ) -> Tuple[SparseMatrix, np.ndarray]: + """Adds new edges (and the entities they bring) to an embedded graph. + + ``mode="frozen"`` (default): entities that were already embedded keep exactly + the vector they had, so models trained on the old embeddings stay valid. Each + new entity is placed at the weighted average of its neighbours' vectors + (``refine_iterations`` rounds, so chains of new entities are reached too). + A new entity with no path to a known one gets a zero vector. + + ``mode="retrain"``: the whole graph is embedded again, starting from the old + vectors. All coordinates change (with whitening they are rotated arbitrarily), + so the result is not comparable with the old embeddings. + """ if trained_embeddings.shape[0] != trained_graph.num_entities: raise ValueError( f"trained_embeddings has {trained_embeddings.shape[0]} rows but graph has {trained_graph.num_entities} entities" ) + if mode not in ("frozen", "retrain"): + raise ValueError(f"Unknown mode '{mode}'. Use 'frozen' or 'retrain'.") + _validate_propagation(propagation) updated_graph = update_graph( existing_edges, new_edges, columns, hyperedge_trim_n, num_workers ) - old_index_map = {eid: i for i, eid in enumerate(trained_graph.entity_ids)} + if mode == "frozen": + updated_embeddings = _frozen_inductive_update( + updated_graph, + trained_graph.entity_ids, + np.asarray(trained_embeddings, dtype=np.float32), + propagation, + refine_iterations, + num_workers, + ) + return updated_graph, updated_embeddings + old_index_map = {eid: i for i, eid in enumerate(trained_graph.entity_ids)} dim = trained_embeddings.shape[1] - init_embeddings = np.random.randn(updated_graph.num_entities, dim).astype(np.float32) * 0.01 - - for i, eid in enumerate(updated_graph.entity_ids): - if eid in old_index_map: - init_embeddings[i] = trained_embeddings[old_index_map[eid]] + # deterministic, small starting vectors for the entities that are new + init_embeddings = updated_graph.initialize_deterministically(dim) * np.float32(0.01) + source = np.fromiter( + (old_index_map.get(eid, -1) for eid in updated_graph.entity_ids), + dtype=np.int64, + count=updated_graph.num_entities, + ) + known = source >= 0 + init_embeddings[known] = trained_embeddings[source[known]] updated_embeddings = embed( updated_graph, @@ -575,25 +848,67 @@ def embed_inductive( normalization=normalization, initial_embeddings=init_embeddings, num_workers=num_workers, + whiten=whiten, ) return updated_graph, updated_embeddings +def _align_to_previous(new_embeddings, new_entity_ids, old_embeddings, old_entity_ids): + """Rotates freshly computed embeddings onto the coordinates of the previous ones + (orthogonal Procrustes over the entities both have).""" + old_index = {eid: i for i, eid in enumerate(old_entity_ids)} + source = np.fromiter( + (old_index.get(eid, -1) for eid in new_entity_ids), dtype=np.int64, count=len(new_entity_ids) + ) + shared = np.flatnonzero(source >= 0) + if len(shared) == 0 or new_embeddings.shape[1] != old_embeddings.shape[1]: + return new_embeddings + moving = new_embeddings[shared].astype(np.float64) + target = old_embeddings[source[shared]].astype(np.float64) + u, _, vt = np.linalg.svd(moving.T @ target) + rotation = (u @ vt).astype(np.float32) + return np.ascontiguousarray(new_embeddings @ rotation, dtype=np.float32) + + def embed_streaming( edge_batches, columns: str, feature_dim: int = DEFAULT_FEATURE_DIM, - num_iterations: int = DEFAULT_NUM_ITERATIONS, + num_iterations: Union[int, str] = DEFAULT_NUM_ITERATIONS, propagation: str = "left", normalization: str = "l2", hyperedge_trim_n: int = 16, num_workers: Optional[int] = None, batch_callback: Optional[Callable[[int, SparseMatrix, np.ndarray], None]] = None, + refresh_every: Optional[int] = None, + whiten: bool = DEFAULT_WHITEN, + seed: int = 0, ) -> Tuple[SparseMatrix, np.ndarray]: + """Embeds a graph that arrives in batches of edges. + + The first batch is embedded in full. For every later batch the entities that + are already embedded keep their vectors and new entities are placed next to + their neighbours (see ``embed_inductive``), so the coordinates stay stable. + + With ``refresh_every=k`` every k-th batch re-embeds the whole graph and + rotates the result onto the previous coordinates, which lets old entities + move with the new evidence while keeping the space comparable. + """ + if refresh_every is not None and refresh_every <= 0: + raise ValueError(f"refresh_every must be positive, got {refresh_every}") + all_edges = [] graph = None embeddings = None + entity_ids = None + + def full_embedding(current_graph): + return embed( + current_graph, feature_dim=feature_dim, num_iterations=num_iterations, + propagation=propagation, normalization=normalization, + num_workers=num_workers, whiten=whiten, seed=seed, + ) for batch_idx, batch in enumerate(edge_batches): all_edges.extend(batch) @@ -601,31 +916,18 @@ def embed_streaming( iter(all_edges), columns, hyperedge_trim_n, num_workers ) - if embeddings is not None: - old_index_map = {} - for i, eid in enumerate(prev_entity_ids): - old_index_map[eid] = i - - init = np.random.randn(graph.num_entities, feature_dim).astype(np.float32) * 0.01 - for i, eid in enumerate(graph.entity_ids): - if eid in old_index_map: - old_idx = old_index_map[eid] - if old_idx < embeddings.shape[0]: - init[i] = embeddings[old_idx] - - embeddings = embed( - graph, feature_dim=feature_dim, num_iterations=num_iterations, - propagation=propagation, normalization=normalization, - initial_embeddings=init, num_workers=num_workers, + if embeddings is None: + embeddings = full_embedding(graph) + elif refresh_every is not None and batch_idx % refresh_every == 0: + embeddings = _align_to_previous( + full_embedding(graph), graph.entity_ids, embeddings, entity_ids ) else: - embeddings = embed( - graph, feature_dim=feature_dim, num_iterations=num_iterations, - propagation=propagation, normalization=normalization, - num_workers=num_workers, + embeddings = _frozen_inductive_update( + graph, entity_ids, embeddings, propagation, num_workers=num_workers ) - prev_entity_ids = list(graph.entity_ids) + entity_ids = graph.entity_ids if batch_callback is not None: batch_callback(batch_idx, graph, embeddings) @@ -640,42 +942,56 @@ def predict_links( exclude_existing: bool = True, source_entities: Optional[List[str]] = None, ) -> List[Dict]: - norms = np.linalg.norm(embeddings, axis=1, keepdims=True) - norms = np.maximum(norms, 1e-10) - normed = embeddings / norms + """The ``top_k`` highest-cosine pairs (source, target) among the candidates of + the given source entities (all entities by default). - existing_edges = set() - if exclude_existing: - rows, cols, _, _, _ = graph.to_sparse_csr() - for r, c in zip(rows, cols): - existing_edges.add((int(r), int(c))) + A pair is unordered and comes back once: of two sources, the one with the + lower index is reported as the source.""" + n = graph.num_entities + if top_k <= 0 or n == 0: + return [] + norms = np.sqrt(np.einsum("ij,ij->i", embeddings, embeddings, dtype=np.float64)) + normed = (embeddings / np.maximum(norms, 1e-10)[:, None]).astype(np.float32) if source_entities is not None: - source_indices = [] - for eid in source_entities: - source_indices.append(graph.get_entity_index(eid)) + # distinct, so that a source named twice does not repeat its pairs + source_indices = np.unique(np.asarray(graph.get_entity_indices(list(source_entities)), dtype=np.int64)) else: - source_indices = list(range(graph.num_entities)) + source_indices = np.arange(n, dtype=np.int64) + is_source = np.zeros(n, dtype=bool) + is_source[source_indices] = True + columns = np.arange(n, dtype=np.int64) - predictions = [] - for src_idx in source_indices: - sims = normed @ normed[src_idx] - sims[src_idx] = -2.0 + if exclude_existing: + indptr, indices, _ = graph.to_csr() + entity_ids = graph.entity_ids + keep = min(top_k, n) + block = max(1, (1 << 26) // max(n, 1)) + predictions = [] + for start in range(0, len(source_indices), block): + sources = source_indices[start:start + block] + sims = normed[sources] @ normed.T + # The cosine is symmetric, so a pair of two sources is in the rows of both: + # it is left in the row of the lower index only. This also removes the diagonal. + sims[is_source & (columns <= sources[:, None])] = -2.0 if exclude_existing: - for other_idx in range(graph.num_entities): - if (src_idx, other_idx) in existing_edges or (other_idx, src_idx) in existing_edges: - sims[other_idx] = -2.0 - - top_indices = np.argsort(sims)[::-1][:top_k] - for tgt_idx in top_indices: - if sims[tgt_idx] <= -2.0: - continue - predictions.append({ - "source": graph.entity_ids[src_idx], - "target": graph.entity_ids[int(tgt_idx)], - "score": float(sims[int(tgt_idx)]), - }) + # the matrix is symmetric: the row of a source lists all its existing links + for local, src in enumerate(sources): + sims[local, indices[indptr[src]:indptr[src + 1]]] = -2.0 + candidates = np.argpartition(-sims, keep - 1, axis=1)[:, :keep] + for local, src in enumerate(sources): + row = candidates[local] + row = row[np.argsort(-sims[local, row], kind="stable")] + for tgt in row: + score = float(sims[local, tgt]) + if score <= -2.0: + continue + predictions.append({ + "source": entity_ids[int(src)], + "target": entity_ids[int(tgt)], + "score": score, + }) predictions.sort(key=lambda x: x["score"], reverse=True) return predictions[:top_k] @@ -684,14 +1000,15 @@ def predict_links( def propagate_gpu( graph: SparseMatrix, embeddings: np.ndarray, - num_iterations: int = DEFAULT_NUM_ITERATIONS, + num_iterations: Union[int, str] = DEFAULT_NUM_ITERATIONS, propagation: str = "left", normalization: str = "l2", device: str = "cuda", callback: Optional[Callable[[int, np.ndarray], None]] = None, - whiten: bool = True, + whiten: bool = DEFAULT_WHITEN, ) -> np.ndarray: _validate_propagation(propagation) + num_iterations = _resolve_iterations(num_iterations, graph, propagation, whiten) if normalization not in ("l2", "l1", "none"): raise ValueError(f"GPU propagation supports 'l2', 'l1', or 'none' normalization. Got: '{normalization}'") @@ -757,24 +1074,35 @@ def find_most_similar( top_k: int = 10, exclude_self: bool = True, ) -> List[Dict]: + """The ``top_k`` entities with the highest cosine similarity to ``query_entity``. + + With ``exclude_self=True`` the query is never among them: a graph of ``n`` + entities gives at most ``n - 1`` results.""" query_idx = graph.get_entity_index(query_entity) query_vec = embeddings[query_idx] - norms = np.linalg.norm(embeddings, axis=1, keepdims=True) + norms = np.sqrt(np.einsum("ij,ij->i", embeddings, embeddings, dtype=np.float64)) norms = np.maximum(norms, 1e-10) - normalized = embeddings / norms - - query_norm = query_vec / max(np.linalg.norm(query_vec), 1e-10) - similarities = normalized @ query_norm + query_norm = max(float(norms[query_idx]), 1e-10) + similarities = ((embeddings @ query_vec) / (norms * query_norm)).astype(np.float32) + num_candidates = len(similarities) if exclude_self: - similarities[query_idx] = -1.0 - - top_indices = np.argsort(similarities)[::-1][:top_k] + # Below every cosine (-1 is one an entity can really have), and with one + # candidate fewer the query cannot be among those that are kept. + similarities[query_idx] = -np.inf + num_candidates -= 1 + + keep = min(max(top_k, 0), num_candidates) + if keep == 0: + return [] + top_indices = np.argpartition(-similarities, keep - 1)[:keep] + top_indices = top_indices[np.argsort(-similarities[top_indices], kind="stable")] + entity_ids = graph.entity_ids results = [] for idx in top_indices: results.append({ - "entity_id": graph.entity_ids[idx], + "entity_id": entity_ids[int(idx)], "index": int(idx), "similarity": float(similarities[idx]), }) @@ -785,16 +1113,17 @@ def embed_edge_features( graph: SparseMatrix, edge_features: Dict[str, np.ndarray], feature_dim: int = DEFAULT_FEATURE_DIM, - num_iterations: int = DEFAULT_NUM_ITERATIONS, + num_iterations: Union[int, str] = DEFAULT_NUM_ITERATIONS, propagation: str = "left", normalization: str = "l2", combine: str = "concat", num_workers: Optional[int] = None, - whiten: bool = True, + whiten: bool = DEFAULT_WHITEN, ) -> np.ndarray: from scipy.sparse import csr_matrix, diags _validate_propagation(propagation) + num_iterations = _resolve_iterations(num_iterations, graph, propagation, whiten) struct_emb = embed( graph, feature_dim=feature_dim, num_iterations=num_iterations, @@ -856,14 +1185,14 @@ class CleoraEmbedder: def __init__( self, feature_dim: int = DEFAULT_FEATURE_DIM, - num_iterations: int = DEFAULT_NUM_ITERATIONS, + num_iterations: Union[int, str] = DEFAULT_NUM_ITERATIONS, propagation: str = "left", normalization: str = "l2", columns: str = "complex::reflexive::node", seed: int = 0, hyperedge_trim_n: int = 16, num_workers: Optional[int] = None, - whiten: bool = True, + whiten: bool = DEFAULT_WHITEN, ): self.feature_dim = feature_dim self.num_iterations = num_iterations @@ -971,9 +1300,50 @@ def _postprocess_iteration( return embeddings +def _l1_normalize_inplace(embeddings: np.ndarray) -> None: + for start in range(0, embeddings.shape[0], _ROW_CHUNK): + block = embeddings[start:start + _ROW_CHUNK] + norms = np.abs(block).sum(axis=1, keepdims=True) + np.maximum(norms, 1e-10, out=norms) + block /= norms + + +def _postprocess_inplace( + embeddings: np.ndarray, + normalization: str, + whiten: bool, + num_workers: Optional[int] = None, +) -> np.ndarray: + """Row normalisation and whitening of a C-contiguous float32 matrix, in place.""" + if normalization == "l2": + _core.l2_normalize_inplace(embeddings, num_workers) + elif normalization == "l1": + _l1_normalize_inplace(embeddings) + elif normalization != "none": + raise ValueError( + f"Unknown normalization method: {normalization}. Use 'l2', 'l1', 'spectral', or 'none'." + ) + if whiten: + whiten_embeddings(embeddings, num_workers=num_workers, inplace=True) + return embeddings + + +def _mix_residual_inplace(target: np.ndarray, previous: np.ndarray, residual_weight: float) -> None: + """target = (1 - w) * target + w * previous, without a full-size temporary.""" + weight = np.float32(residual_weight) + keep = np.float32(1.0 - residual_weight) + for start in range(0, target.shape[0], _ROW_CHUNK): + block = target[start:start + _ROW_CHUNK] + block *= keep + block += weight * previous[start:start + _ROW_CHUNK] + + def _compute_rmse(current: np.ndarray, previous: np.ndarray) -> float: - diff = current.astype(np.float64, copy=False) - previous.astype(np.float64, copy=False) - return float(np.sqrt(np.mean(diff * diff))) + total = 0.0 + for start in range(0, current.shape[0], _ROW_CHUNK): + diff = current[start:start + _ROW_CHUNK].astype(np.float64) - previous[start:start + _ROW_CHUNK] + total += float(np.einsum("ij,ij->", diff, diff)) + return float(np.sqrt(total / max(current.size, 1))) def _whiten_embeddings_torch(embeddings): diff --git a/pycleora/algorithms.py b/pycleora/algorithms.py index c99bfea..1c74778 100644 --- a/pycleora/algorithms.py +++ b/pycleora/algorithms.py @@ -1,152 +1,219 @@ +"""Reference implementations of other graph-embedding methods. + +They exist so that Cleora can be compared with well-known baselines without extra +dependencies (numpy and scipy only). They follow the published algorithms, but +they are compact, single-machine implementations: for production use of one of +these methods, prefer its authors' code. + +All of them work on the plain weighted adjacency matrix of the graph (self-loops +removed), not on Cleora's Markov matrices. +""" + import numpy as np -from typing import Optional, Tuple, Dict, List -from scipy.sparse import csr_matrix, diags, eye +from typing import Optional, Dict, List + +try: + from scipy.sparse import csr_matrix, diags, identity +except ImportError as error: # SciPy is an optional dependency of pycleora + raise ImportError( + "pycleora.algorithms needs SciPy. Install it with: pip install 'pycleora[scipy]'" + ) from error def _graph_to_scipy(graph, markov_type: str = "left"): - rows, cols, vals, n, _ = graph.to_sparse_csr(markov_type) - return csr_matrix( - (vals.astype(np.float64), (rows.astype(np.int32), cols.astype(np.int32))), - shape=(n, n), - ) - - -def _graph_to_adjacency(graph): - rows, cols, vals, n, _ = graph.to_sparse_csr() - A = csr_matrix( - (vals.astype(np.float64), (rows.astype(np.int32), cols.astype(np.int32))), - shape=(n, n), - ) + indptr, indices, data = graph.to_csr(markov_type) + n = graph.num_entities + return csr_matrix((data.astype(np.float64), indices, indptr), shape=(n, n)) + + +def _graph_to_adjacency(graph, self_loops: bool = False): + """Symmetric weighted adjacency matrix of the graph (float64 CSR).""" + A = _graph_to_scipy(graph, "raw") + if not self_loops: + coo = A.tocoo() + keep = coo.row != coo.col + A = csr_matrix((coo.data[keep], (coo.row[keep], coo.col[keep])), shape=A.shape) return A +def _degrees(A) -> np.ndarray: + return np.maximum(np.asarray(A.sum(axis=1)).ravel(), 1e-12) + + +def _row_normalized(A): + return (diags(1.0 / _degrees(A)) @ A).tocsr() + + +def _unit_rows(matrix: np.ndarray) -> np.ndarray: + norms = np.linalg.norm(matrix, axis=1, keepdims=True) + return (matrix / np.maximum(norms, 1e-10)).astype(np.float32) + + +def _pad_columns(matrix: np.ndarray, feature_dim: int) -> np.ndarray: + if matrix.shape[1] >= feature_dim: + return matrix[:, :feature_dim] + pad = np.zeros((matrix.shape[0], feature_dim - matrix.shape[1]), dtype=matrix.dtype) + return np.concatenate([matrix, pad], axis=1) + + +def _check_dense_size(n: int, max_nodes: Optional[int], method: str): + if max_nodes is not None and n > max_nodes: + gigabytes = n * n * 8 / 1e9 + raise ValueError( + f"{method} builds dense {n} x {n} matrices (about {gigabytes:.0f} GB each), which is " + f"refused above max_nodes={max_nodes}. Pass a larger max_nodes to run it anyway." + ) + + +def _randomized_svd(matrix, rank: int, seed: int = 0, n_iter: int = 5, oversample: int = 10): + """Truncated SVD by randomized subspace iteration (Halko et al., 2011).""" + n_rows, n_cols = matrix.shape + rank = max(1, min(rank, n_rows, n_cols)) + size = min(rank + oversample, n_rows, n_cols) + rng = np.random.default_rng(seed) + basis, _ = np.linalg.qr(matrix @ rng.standard_normal((n_cols, size))) + for _ in range(n_iter): + basis, _ = np.linalg.qr(matrix.T @ basis) + basis, _ = np.linalg.qr(matrix @ basis) + small = np.asarray((matrix.T @ basis).T) + u_small, singular, vt = np.linalg.svd(small, full_matrices=False) + return (basis @ u_small)[:, :rank], singular[:rank], vt[:rank] + + def embed_prone( graph, feature_dim: int = 256, mu: float = 0.2, theta: float = 0.5, seed: int = 0, + order: int = 10, ) -> np.ndarray: - n = graph.num_entities - A = _graph_to_adjacency(graph) - - degrees = np.array(A.sum(axis=1)).flatten() - degrees = np.maximum(degrees, 1e-10) - D_inv_sqrt = diags(1.0 / np.sqrt(degrees)) - L_norm = eye(n) - D_inv_sqrt @ A @ D_inv_sqrt - - rng = np.random.default_rng(seed) - R = rng.standard_normal((n, feature_dim)).astype(np.float64) - - U = R.copy() - chebyshev_prev = R.copy() - chebyshev_curr = (L_norm @ R).toarray() if hasattr(L_norm @ R, 'toarray') else np.asarray(L_norm @ R) - - for k in range(2, min(10, n)): - chebyshev_next = 2 * (L_norm @ chebyshev_curr) - chebyshev_prev - if hasattr(chebyshev_next, 'toarray'): - chebyshev_next = chebyshev_next.toarray() - coeff = np.exp(-theta * k) * mu - U += coeff * chebyshev_next - chebyshev_prev = chebyshev_curr - chebyshev_curr = chebyshev_next + """ProNE (Zhang et al., IJCAI 2019). - u_svd, s_svd, _ = np.linalg.svd(U, full_matrices=False) - k = min(feature_dim, u_svd.shape[1]) - result = u_svd[:, :k] * np.sqrt(np.maximum(s_svd[:k], 0)) + 1. Sparse matrix factorisation: truncated SVD of the sparse matrix + ``log P[i, j] - log(negative-sampling prior of j)`` defined on the edges. + 2. Spectral propagation: the result is filtered with a band-pass (Gaussian) + graph filter, expanded in ``order`` Chebyshev terms. + """ + from scipy.special import iv - if result.shape[1] < feature_dim: - pad = np.zeros((n, feature_dim - result.shape[1]), dtype=np.float64) - result = np.concatenate([result, pad], axis=1) - - norms = np.linalg.norm(result, axis=1, keepdims=True) - norms = np.maximum(norms, 1e-10) - return (result / norms).astype(np.float32) + n = graph.num_entities + A = _graph_to_adjacency(graph) + if A.nnz == 0: + return np.zeros((n, feature_dim), dtype=np.float32) + + # --- step 1: sparse matrix factorisation + P = _row_normalized(A) + prior = np.asarray(P.sum(axis=0)).ravel() ** 0.75 + prior = prior / prior.sum() + F = P.copy() + F.data = np.log(P.data) - np.log(np.maximum(prior[P.indices], 1e-300)) + u, singular, _ = _randomized_svd(F, feature_dim, seed=seed) + embedding = _unit_rows(u * np.sqrt(singular)).astype(np.float64) + + # --- step 2: spectral propagation (Chebyshev expansion of a Gaussian filter) + if order > 1: + A_loop = (identity(n, format="csr") + A).tocsr() + laplacian = identity(n, format="csr") - _row_normalized(A_loop) + M = (laplacian - mu * identity(n, format="csr")).tocsr() + + term_prev = embedding + term = M @ embedding + term = 0.5 * (M @ term) - embedding + filtered = iv(0, theta) * term_prev + filtered -= 2 * iv(1, theta) * term + for i in range(2, order): + term_next = M @ term + term_next = (M @ term_next - 2 * term) - term_prev + if i % 2 == 0: + filtered += 2 * iv(i, theta) * term_next + else: + filtered -= 2 * iv(i, theta) * term_next + term_prev, term = term, term_next + propagated = A_loop @ (embedding - filtered) + u, singular, _ = np.linalg.svd(propagated, full_matrices=False) + embedding = u * np.sqrt(singular) + + return _unit_rows(_pad_columns(embedding, feature_dim)) def embed_randne( graph, feature_dim: int = 256, - num_iterations: int = 40, + num_iterations: int = 3, weights: Optional[List[float]] = None, seed: int = 0, ) -> np.ndarray: + """RandNE (Zhang et al., ICDM 2018): iterative Gaussian random projection. + + ``U_0`` is an orthogonalised Gaussian matrix, ``U_i = S U_{i-1}`` with the + symmetrically normalised adjacency ``S``, and the embedding is + ``sum_i weights[i] * U_i``. ``num_iterations`` is the order ``q``; the default + weights ``[1, 1e2, 1e4, 1e5]`` are the ones recommended by the authors for + node classification (higher orders dominate). + """ n = graph.num_entities A = _graph_to_adjacency(graph) - - degrees = np.array(A.sum(axis=1)).flatten() - degrees = np.maximum(degrees, 1e-10) - D_inv_sqrt = diags(1.0 / np.sqrt(degrees)) - A_norm = D_inv_sqrt @ A @ D_inv_sqrt + inv_sqrt = 1.0 / np.sqrt(_degrees(A)) + S = (diags(inv_sqrt) @ A @ diags(inv_sqrt)).tocsr() if weights is None: - weights = [1.0 / (2 ** i) for i in range(num_iterations + 1)] + weights = [1.0, 1e2, 1e4, 1e5] + if num_iterations + 1 > len(weights): + weights = weights + [weights[-1]] * (num_iterations + 1 - len(weights)) + if len(weights) < num_iterations + 1: + raise ValueError( + f"weights needs {num_iterations + 1} values (orders 0..{num_iterations}), got {len(weights)}" + ) rng = np.random.default_rng(seed) - R = rng.standard_normal((n, feature_dim)).astype(np.float64) + projection = rng.standard_normal((n, feature_dim)) / np.sqrt(feature_dim) + if n >= feature_dim: + projection, _ = np.linalg.qr(projection) - U = weights[0] * R - current = R.copy() + current = projection + embedding = weights[0] * current + for i in range(1, num_iterations + 1): + current = S @ current + embedding = embedding + weights[i] * current - for i in range(num_iterations): - current = A_norm @ current - if hasattr(current, 'toarray'): - current = current.toarray() - w = weights[i + 1] if i + 1 < len(weights) else weights[-1] - U += w * current - - norms = np.linalg.norm(U, axis=1, keepdims=True) - norms = np.maximum(norms, 1e-10) - return (U / norms).astype(np.float32) + return _unit_rows(embedding) def embed_hope( graph, feature_dim: int = 256, - beta: float = 0.1, + beta: float = 0.5, + max_nodes: Optional[int] = 20000, ) -> np.ndarray: + """HOPE (Ou et al., KDD 2016) with the Katz proximity. + + Factorises ``S = (I - b A)^-1 (b A)`` where ``b = beta / spectral_radius(A)``, + so ``beta`` in (0, 1) is the decay relative to the largest value for which the + Katz series converges. Source and target halves are concatenated. + Needs dense ``n x n`` matrices. + """ + from scipy.sparse.linalg import eigsh + + if not 0 < beta < 1: + raise ValueError(f"beta must be in (0, 1), got {beta}") n = graph.num_entities + _check_dense_size(n, max_nodes, "HOPE") A = _graph_to_adjacency(graph) + if n > 2 and A.nnz > 0: + radius = float(abs(eigsh(A, k=1, which="LA", return_eigenvectors=False)[0])) + else: + radius = float(np.abs(A.toarray()).sum(axis=1).max()) if A.nnz else 1.0 + decay = beta / max(radius, 1e-12) - S = eye(n) - beta * A - try: - from scipy.sparse.linalg import inv as sparse_inv - S_inv = sparse_inv(S.tocsc()) - except Exception: - S_dense = S.toarray() - S_inv = csr_matrix(np.linalg.inv(S_dense)) - - M = S_inv - eye(n) - - k = min(feature_dim // 2, n - 1) - try: - from scipy.sparse.linalg import svds - u, s, vt = svds(M, k=k) - order = np.argsort(-s) - u = u[:, order] - s = s[order] - vt = vt[order, :] - except Exception: - M_dense = M.toarray() if hasattr(M, 'toarray') else np.asarray(M) - u, s, vt = np.linalg.svd(M_dense, full_matrices=False) - u = u[:, :k] - s = s[:k] - vt = vt[:k, :] - - sqrt_s = np.sqrt(np.maximum(s, 0)) - source_emb = u * sqrt_s - target_emb = vt.T * sqrt_s - - result = np.concatenate([source_emb, target_emb], axis=1) - if result.shape[1] < feature_dim: - pad = np.zeros((n, feature_dim - result.shape[1]), dtype=np.float64) - result = np.concatenate([result, pad], axis=1) - elif result.shape[1] > feature_dim: - result = result[:, :feature_dim] - - norms = np.linalg.norm(result, axis=1, keepdims=True) - norms = np.maximum(norms, 1e-10) - return (result / norms).astype(np.float32) + dense = A.toarray() + katz = np.linalg.solve(np.eye(n) - decay * dense, decay * dense) + + k = max(1, min(feature_dim // 2, n)) + u, singular, vt = np.linalg.svd(katz, full_matrices=False) + sqrt_s = np.sqrt(singular[:k]) + result = np.concatenate([u[:, :k] * sqrt_s, vt[:k].T * sqrt_s], axis=1) + return _unit_rows(_pad_columns(result, feature_dim)) def embed_netmf( @@ -154,189 +221,159 @@ def embed_netmf( feature_dim: int = 256, window_size: int = 5, negative_samples: float = 1.0, + max_nodes: Optional[int] = 20000, ) -> np.ndarray: - n = graph.num_entities - A = _graph_to_adjacency(graph) - - degrees = np.array(A.sum(axis=1)).flatten() - vol = degrees.sum() - degrees = np.maximum(degrees, 1e-10) - - D_inv = diags(1.0 / degrees) - P = D_inv @ A - - M_sum = csr_matrix((n, n), dtype=np.float64) - P_power = eye(n, dtype=np.float64) - - for t in range(1, window_size + 1): - P_power = P_power @ P - M_sum = M_sum + P_power - - M_sum = M_sum / window_size - - D_diag = diags(degrees) - M = (vol / negative_samples) * D_inv @ M_sum @ D_diag + """NetMF (Qiu et al., WSDM 2018), exact version for small windows. - if hasattr(M, 'toarray'): - M_dense = M.toarray() - else: - M_dense = np.asarray(M) - - M_dense = np.maximum(M_dense, 1.0) - M_log = np.log(M_dense) + Factorises ``log max(M, 1)`` with + ``M = vol(G) / (b T) * (sum_{r=1..T} P^r) D^-1``, the matrix DeepWalk + implicitly factorises. Needs dense ``n x n`` matrices. + """ + n = graph.num_entities + _check_dense_size(n, max_nodes, "NetMF") + A = _graph_to_adjacency(graph).toarray() + degrees = np.maximum(A.sum(axis=1), 1e-12) + volume = degrees.sum() - u, s, vt = np.linalg.svd(M_log, full_matrices=False) - k = min(feature_dim, n) - result = u[:, :k] * np.sqrt(np.maximum(s[:k], 0)) + P = A / degrees[:, None] + power = np.eye(n) + total = np.zeros((n, n)) + for _ in range(window_size): + power = power @ P + total += power - if result.shape[1] < feature_dim: - pad = np.zeros((n, feature_dim - result.shape[1]), dtype=np.float64) - result = np.concatenate([result, pad], axis=1) + M = (volume / (negative_samples * window_size)) * total / degrees[None, :] + M = np.log(np.maximum(M, 1.0)) - norms = np.linalg.norm(result, axis=1, keepdims=True) - norms = np.maximum(norms, 1e-10) - return (result / norms).astype(np.float32) + # M is symmetric up to rounding; its SVD follows from the eigendecomposition + eigenvalues, eigenvectors = np.linalg.eigh((M + M.T) / 2) + order = np.argsort(-np.abs(eigenvalues))[: min(feature_dim, n)] + result = eigenvectors[:, order] * np.sqrt(np.abs(eigenvalues[order])) + return _unit_rows(_pad_columns(result, feature_dim)) def embed_grarep( graph, feature_dim: int = 256, max_step: int = 4, + max_nodes: Optional[int] = 20000, ) -> np.ndarray: - n = graph.num_entities - A = _graph_to_adjacency(graph) + """GraRep (Cao et al., CIKM 2015). - degrees = np.array(A.sum(axis=1)).flatten() - degrees = np.maximum(degrees, 1e-10) - D_inv = diags(1.0 / degrees) - P = D_inv @ A + For every step ``k = 1..max_step`` factorises the positive log-probability + matrix of ``k``-step transitions, ``max(log(P^k[i, j] / column mean), 0)``, and + concatenates the factors. Needs dense ``n x n`` matrices. + """ + n = graph.num_entities + _check_dense_size(n, max_nodes, "GraRep") + A = _graph_to_adjacency(graph).toarray() + P = A / np.maximum(A.sum(axis=1), 1e-12)[:, None] dim_per_step = max(feature_dim // max_step, 1) - all_embs = [] - - P_k = P.copy() - for step in range(1, max_step + 1): - if hasattr(P_k, 'toarray'): - M = P_k.toarray() - else: - M = np.asarray(P_k) - - M = np.maximum(M, 1e-10) - M_log = np.log(M) - np.log(1e-10) - - u, s, vt = np.linalg.svd(M_log, full_matrices=False) + parts = [] + P_k = np.eye(n) + for _ in range(max_step): + P_k = P_k @ P + column_mean = np.maximum(P_k.sum(axis=0, keepdims=True) / n, 1e-300) + with np.errstate(divide="ignore"): + M = np.log(P_k / column_mean) + M[~np.isfinite(M)] = 0.0 + M = np.maximum(M, 0.0) + u, singular, _ = np.linalg.svd(M, full_matrices=False) k = min(dim_per_step, n) - step_emb = u[:, :k] * np.sqrt(np.maximum(s[:k], 0)) - all_embs.append(step_emb) - - if step < max_step: - P_k = P_k @ P - - result = np.concatenate(all_embs, axis=1) - if result.shape[1] > feature_dim: - result = result[:, :feature_dim] - elif result.shape[1] < feature_dim: - n = result.shape[0] - pad = np.zeros((n, feature_dim - result.shape[1]), dtype=np.float64) - result = np.concatenate([result, pad], axis=1) - - norms = np.linalg.norm(result, axis=1, keepdims=True) - norms = np.maximum(norms, 1e-10) - return (result / norms).astype(np.float32) - - -def _build_adj_list(graph): - rows, cols, vals, n, _ = graph.to_sparse_csr() - adj = [[] for _ in range(n)] - weights = [[] for _ in range(n)] - for r, c, v in zip(rows, cols, vals): - ri, ci = int(r), int(c) - if ri != ci: - adj[ri].append(ci) - weights[ri].append(float(v)) - return adj, weights, n - - -def _random_walks(adj, weights, n, num_walks, walk_length, p, q, seed): - rng = np.random.default_rng(seed) - walks = [] - - for _ in range(num_walks): - for start in range(n): - if not adj[start]: - continue - walk = [start] - prev = -1 - curr = start - - for _ in range(walk_length - 1): - neighbors = adj[curr] - if not neighbors: - break - - if prev == -1 or (p == 1.0 and q == 1.0): - idx = rng.integers(len(neighbors)) - nxt = neighbors[idx] + parts.append(_unit_rows(u[:, :k] * np.sqrt(singular[:k])).astype(np.float64)) + + return _unit_rows(_pad_columns(np.concatenate(parts, axis=1), feature_dim)) + + +class _WalkSampler: + """Vectorised random walks on a weighted graph (all walks advance together).""" + + def __init__(self, A, seed: int): + A = A.tocsr() + A.sort_indices() + self.n = A.shape[0] + self.indptr = A.indptr.astype(np.int64) + self.indices = A.indices.astype(np.int64) + self.degree = np.diff(self.indptr) + rows = np.repeat(np.arange(self.n, dtype=np.int64), self.degree) + row_totals = np.maximum(np.asarray(A.sum(axis=1)).ravel(), 1e-300) + within = np.cumsum(A.data) - np.repeat(np.cumsum(A.data)[self.indptr[:-1] - 1] * (self.indptr[:-1] > 0), self.degree) + # position k of row r holds r + (cumulative share of the row's weight), in (r, r + 1] + self.cumulative = rows + np.minimum(within / row_totals[rows], 1.0) + # (row, column) keys, sorted, for membership tests + self.edge_keys = rows * self.n + self.indices + self.rng = np.random.default_rng(seed) + + def step(self, current: np.ndarray) -> np.ndarray: + """One weighted random step from every node in ``current``.""" + draw = current + self.rng.random(len(current)) * (1.0 - 1e-12) + position = np.searchsorted(self.cumulative, draw, side="right") + position = np.clip(position, self.indptr[current], self.indptr[current + 1] - 1) + return self.indices[position] + + def connected(self, a: np.ndarray, b: np.ndarray) -> np.ndarray: + keys = a * self.n + b + position = np.searchsorted(self.edge_keys, keys) + position = np.minimum(position, len(self.edge_keys) - 1) + return self.edge_keys[position] == keys + + def walks(self, num_walks: int, walk_length: int, p: float, q: float) -> np.ndarray: + """Returns an array of shape (num_walks * active_nodes, walk_length).""" + starts = np.flatnonzero(self.degree > 0) + result = [] + biased = not (p == 1.0 and q == 1.0) + upper = max(1.0, 1.0 / p, 1.0 / q) + for _ in range(num_walks): + walk = np.empty((len(starts), walk_length), dtype=np.int64) + walk[:, 0] = starts + current = starts + previous = None + for position in range(1, walk_length): + if not biased or previous is None: + nxt = self.step(current) else: - w = np.array(weights[curr], dtype=np.float64) - alpha = np.ones(len(neighbors), dtype=np.float64) - prev_neighbors = set(adj[prev]) if adj[prev] else set() - - for j, nb in enumerate(neighbors): - if nb == prev: - alpha[j] = 1.0 / p - elif nb not in prev_neighbors: - alpha[j] = 1.0 / q - - probs = w * alpha - probs_sum = probs.sum() - if probs_sum < 1e-15: - break - probs /= probs_sum - idx = rng.choice(len(neighbors), p=probs) - nxt = neighbors[idx] - - walk.append(nxt) - prev = curr - curr = nxt - - walks.append(walk) - - return walks - - -def _walks_to_embeddings(walks, n, feature_dim, window_size): - cooccur = np.zeros((n, n), dtype=np.float64) - - for walk in walks: - for i, node in enumerate(walk): - start = max(0, i - window_size) - end = min(len(walk), i + window_size + 1) - for j in range(start, end): - if i != j: - cooccur[node, walk[j]] += 1.0 - - row_sums = cooccur.sum(axis=1, keepdims=True) - row_sums = np.maximum(row_sums, 1e-10) - total = cooccur.sum() - col_sums = cooccur.sum(axis=0, keepdims=True) - col_sums = np.maximum(col_sums, 1e-10) - - with np.errstate(divide='ignore', invalid='ignore'): - pmi = np.log(np.maximum(cooccur * total / (row_sums * col_sums), 1e-15)) - pmi = np.maximum(pmi, 0.0) - - u, s, _ = np.linalg.svd(pmi, full_matrices=False) - k = min(feature_dim, u.shape[1]) - result = u[:, :k] * np.sqrt(np.maximum(s[:k], 0)) - - if result.shape[1] < feature_dim: - pad = np.zeros((n, feature_dim - result.shape[1]), dtype=np.float64) - result = np.concatenate([result, pad], axis=1) - - norms = np.linalg.norm(result, axis=1, keepdims=True) - norms = np.maximum(norms, 1e-10) - return (result / norms).astype(np.float32) + # node2vec second-order walk by rejection sampling + nxt = np.empty_like(current) + pending = np.arange(len(current)) + while len(pending): + candidate = self.step(current[pending]) + back = candidate == previous[pending] + near = self.connected(previous[pending], candidate) + accept_probability = np.where(back, 1.0 / p, np.where(near, 1.0, 1.0 / q)) / upper + accepted = self.rng.random(len(pending)) < accept_probability + nxt[pending[accepted]] = candidate[accepted] + pending = pending[~accepted] + walk[:, position] = nxt + previous, current = current, nxt + result.append(walk) + return np.concatenate(result, axis=0) if result else np.empty((0, walk_length), dtype=np.int64) + + +def _walks_to_embeddings(walks: np.ndarray, n: int, feature_dim: int, window_size: int, seed: int) -> np.ndarray: + """Truncated SVD of the positive PMI matrix of walk co-occurrences.""" + from scipy.sparse import coo_matrix + + counts = csr_matrix((n, n), dtype=np.float64) + for offset in range(1, window_size + 1): + if offset >= walks.shape[1]: + break + left = walks[:, :-offset].ravel() + right = walks[:, offset:].ravel() + pairs = coo_matrix((np.ones(len(left)), (left, right)), shape=(n, n)).tocsr() + counts = counts + pairs + pairs.T + counts = counts.tocoo() + if counts.nnz == 0: + return np.zeros((n, feature_dim), dtype=np.float32) + + total = counts.data.sum() + row_sums = np.maximum(np.asarray(counts.tocsr().sum(axis=1)).ravel(), 1e-300) + pmi = np.log(counts.data * total / (row_sums[counts.row] * row_sums[counts.col])) + positive = pmi > 0 + ppmi = csr_matrix((pmi[positive], (counts.row[positive], counts.col[positive])), shape=(n, n)) + + u, singular, _ = _randomized_svd(ppmi, feature_dim, seed=seed) + return _unit_rows(_pad_columns(u * np.sqrt(singular), feature_dim)) def embed_deepwalk( @@ -347,10 +384,16 @@ def embed_deepwalk( window_size: int = 5, seed: int = 0, ) -> np.ndarray: - adj, weights, n = _build_adj_list(graph) - walks = _random_walks(adj, weights, n, num_walks, walk_length, - p=1.0, q=1.0, seed=seed) - return _walks_to_embeddings(walks, n, feature_dim, window_size) + """DeepWalk-style embedding (Perozzi et al., KDD 2014), matrix-factorisation variant. + + Uniform (weight-proportional) random walks are sampled as in DeepWalk, but + instead of training skip-gram with negative sampling, the positive PMI matrix + of the walk co-occurrences is factorised with a truncated SVD - the objective + skip-gram optimises implicitly (Levy & Goldberg, 2014). It is deterministic + for a given seed and needs no training loop; it is not the original SGD-based + implementation. + """ + return embed_node2vec(graph, feature_dim, num_walks, walk_length, window_size, 1.0, 1.0, seed) def embed_node2vec( @@ -363,26 +406,38 @@ def embed_node2vec( q: float = 1.0, seed: int = 0, ) -> np.ndarray: - adj, weights, n = _build_adj_list(graph) - walks = _random_walks(adj, weights, n, num_walks, walk_length, - p=p, q=q, seed=seed) - return _walks_to_embeddings(walks, n, feature_dim, window_size) + """node2vec-style embedding (Grover & Leskovec, KDD 2016), matrix-factorisation variant. + + Biased second-order random walks with return parameter ``p`` and in-out + parameter ``q``, followed by a truncated SVD of the positive PMI matrix of the + walk co-occurrences (see :func:`embed_deepwalk`). With ``p = q = 1`` the walks + are DeepWalk's and the two functions return the same embedding. + """ + if p <= 0 or q <= 0: + raise ValueError(f"p and q must be positive, got p={p}, q={q}") + A = _graph_to_adjacency(graph) + n = graph.num_entities + if A.nnz == 0: + return np.zeros((n, feature_dim), dtype=np.float32) + sampler = _WalkSampler(A, seed) + walks = sampler.walks(num_walks, walk_length, p, q) + return _walks_to_embeddings(walks, n, feature_dim, window_size, seed) def list_algorithms() -> List[Dict]: return [ {"name": "prone", "function": "embed_prone", - "description": "ProNE: Spectral propagation with Chebyshev polynomials. Fast and high quality."}, + "description": "ProNE: sparse matrix factorisation followed by spectral propagation with Chebyshev polynomials."}, {"name": "randne", "function": "embed_randne", - "description": "RandNE: Random projection embedding. Extremely fast, good for very large graphs."}, + "description": "RandNE: iterative Gaussian random projection of high-order proximities."}, {"name": "hope", "function": "embed_hope", - "description": "HOPE: High-Order Proximity Embedding. Asymmetric, good for directed graphs."}, + "description": "HOPE: factorisation of the Katz proximity matrix (dense, small graphs)."}, {"name": "netmf", "function": "embed_netmf", - "description": "NetMF: Network Matrix Factorization. Theoretical generalization of DeepWalk."}, + "description": "NetMF: explicit factorisation of the matrix DeepWalk factorises implicitly (dense, small graphs)."}, {"name": "grarep", "function": "embed_grarep", - "description": "GraRep: Multi-scale matrix factorization with k-step transitions."}, + "description": "GraRep: factorisation of k-step transition matrices, concatenated (dense, small graphs)."}, {"name": "deepwalk", "function": "embed_deepwalk", - "description": "DeepWalk: Random walk + SVD. The original graph embedding algorithm."}, + "description": "DeepWalk walks + PPMI/SVD factorisation (matrix-factorisation variant, not skip-gram)."}, {"name": "node2vec", "function": "embed_node2vec", - "description": "Node2Vec: Biased random walk with p,q parameters controlling BFS/DFS balance."}, + "description": "node2vec biased walks (p, q) + PPMI/SVD factorisation (matrix-factorisation variant, not skip-gram)."}, ] diff --git a/pycleora/benchmark.py b/pycleora/benchmark.py index 2c74a08..f2395b3 100644 --- a/pycleora/benchmark.py +++ b/pycleora/benchmark.py @@ -1,7 +1,12 @@ import numpy as np import time -import tracemalloc -from typing import Dict, List, Optional, Callable, Tuple +from typing import Dict, List, Optional, Callable + + +def _error_entry(error: Exception) -> Dict: + """The table row of an algorithm or dataset that failed: one failure must not + cost the measurements of the others, and the row says what happened.""" + return {"error": f"{type(error).__name__}: {error}"} def benchmark_algorithms( @@ -12,6 +17,12 @@ def benchmark_algorithms( num_runs: int = 1, seed: int = 42, ) -> Dict: + """Time and classification scores of every algorithm on one graph. + + Memory is not measured: the peak of a call cannot be told apart from what the + process already holds (allocators reuse freed memory), so a number taken here + would say nothing about the algorithm. Measure it with one process per run. + """ from .metrics import node_classification_scores if metrics_fn is None: @@ -21,24 +32,18 @@ def benchmark_algorithms( for name, algo_fn in algorithms.items(): times = [] scores_list = [] - memory_peaks = [] for run in range(num_runs): - tracemalloc.start() - t0 = time.time() try: + t0 = time.perf_counter() emb = algo_fn(graph) - elapsed = time.time() - t0 - _, peak = tracemalloc.get_traced_memory() - tracemalloc.stop() + elapsed = time.perf_counter() - t0 scores = metrics_fn(graph, emb, labels) times.append(elapsed) scores_list.append(scores) - memory_peaks.append(peak / 1024 / 1024) except Exception as e: - tracemalloc.stop() - results[name] = {"error": str(e)} + results[name] = _error_entry(e) break if name not in results: @@ -52,7 +57,6 @@ def benchmark_algorithms( results[name] = { "avg_time": float(np.mean(times)), "std_time": float(np.std(times)) if len(times) > 1 else 0.0, - "avg_memory_mb": float(np.mean(memory_peaks)), "scores": avg_scores, "num_runs": num_runs, } @@ -74,10 +78,10 @@ def benchmark_datasets( for ds_name in dataset_names: try: ds = load_dataset(ds_name) - t0 = time.time() + t0 = time.perf_counter() graph = SparseMatrix.from_iterator(iter(ds["edges"]), ds["columns"]) emb = embed_fn(graph) - elapsed = time.time() - t0 + elapsed = time.perf_counter() - t0 scores = node_classification_scores(graph, emb, ds["labels"], seed=seed) results[ds_name] = { @@ -88,14 +92,14 @@ def benchmark_datasets( "scores": scores, } except Exception as e: - results[ds_name] = {"error": str(e)} + results[ds_name] = _error_entry(e) return results def format_benchmark_table(results: Dict, metric: str = "accuracy") -> str: lines = [] - header = f"{'Algorithm':<15} {'Time (s)':<12} {'Memory (MB)':<14} {metric.capitalize():<12}" + header = f"{'Algorithm':<15} {'Time (s)':<12} {metric.capitalize():<12}" lines.append(header) lines.append("-" * len(header)) @@ -104,9 +108,8 @@ def format_benchmark_table(results: Dict, metric: str = "accuracy") -> str: lines.append(f"{name:<15} ERROR: {data['error']}") else: t = data.get("avg_time", 0) - m = data.get("avg_memory_mb", 0) s = data.get("scores", {}).get(metric, 0) - lines.append(f"{name:<15} {t:<12.4f} {m:<14.2f} {s:<12.4f}") + lines.append(f"{name:<15} {t:<12.4f} {s:<12.4f}") return "\n".join(lines) diff --git a/pycleora/classify.py b/pycleora/classify.py index b73007f..0c967d0 100644 --- a/pycleora/classify.py +++ b/pycleora/classify.py @@ -1,6 +1,32 @@ import numpy as np from typing import Dict, Optional, Tuple, List +# Share of the training entities that is not fitted on but used to choose the checkpoint. +_VALIDATION_FRACTION = 0.2 + + +def _split_labelled( + rng: np.random.Generator, count: int, train_ratio: float +) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """Shuffled positions of ``count`` labelled entities as ``(fit, validation, test)``. + + ``train_ratio`` of them are for training. The checkpoint must be chosen on data + the model was not fitted on, and choosing it on the test part would make the test + score an optimistic maximum: so a part of the training entities is held out for it. + """ + order = rng.permutation(count) + num_train = int(count * train_ratio) + train, test = order[:num_train], order[num_train:] + if len(test) == 0: + raise ValueError("Test set is empty, reduce train_ratio") + if len(train) < 2: + raise ValueError( + f"Need at least 2 training entities (one to fit on, one for validation), got {len(train)}: " + "increase train_ratio" + ) + num_validation = max(1, int(len(train) * _VALIDATION_FRACTION)) + return train[num_validation:], train[:num_validation], test + def label_propagation( graph, @@ -64,6 +90,15 @@ def mlp_classify( seed: int = 42, l2_reg: float = 1e-4, ) -> Dict[str, float]: + """Trains a one-hidden-layer network on the embeddings and scores it on held-out entities. + + ``train_ratio`` of the labelled entities are for training; a fifth of those is not + fitted on but used to choose the checkpoint (every 10th epoch is a candidate). + The test entities are scored once, with the chosen checkpoint: ``accuracy`` and + ``macro_f1`` are that score. (Earlier versions chose the checkpoint by its test + accuracy, so the two were the best of the test scores of all candidates.) + ``train_size`` counts all training entities, the validation part included. + """ if not labels: raise ValueError("labels must be a non-empty dict") if not (0 < train_ratio < 1): @@ -90,14 +125,10 @@ def mlp_classify( y_mapped = np.array([class_map[c] for c in y]) rng = np.random.default_rng(seed) - perm = rng.permutation(len(y)) - split = int(len(y) * train_ratio) - train_idx, test_idx = perm[:split], perm[split:] - - if len(test_idx) == 0: - raise ValueError("Test set is empty, reduce train_ratio") + fit_idx, validation_idx, test_idx = _split_labelled(rng, len(y), train_ratio) - X_train, y_train = X[train_idx], y_mapped[train_idx] + X_train, y_train = X[fit_idx], y_mapped[fit_idx] + X_validation, y_validation = X[validation_idx], y_mapped[validation_idx] X_test, y_test = X[test_idx], y_mapped[test_idx] input_dim = X.shape[1] @@ -156,10 +187,12 @@ def forward(X_batch): b2 -= learning_rate * db2 if epoch % 10 == 0 or epoch == num_epochs - 1: - _, _, _, test_probs = forward(X_test) - test_pred = np.argmax(test_probs, axis=1) - acc = float(np.mean(test_pred == y_test)) - if acc > best_acc: + _, _, _, validation_probs = forward(X_validation) + validation_pred = np.argmax(validation_probs, axis=1) + acc = float(np.mean(validation_pred == y_validation)) + # ">=": a small validation part gives many ties, and of equally good + # checkpoints the one trained longest is the better model. + if acc >= best_acc: best_acc = acc best_W1, best_b1 = W1.copy(), b1.copy() best_W2, best_b2 = W2.copy(), b2.copy() @@ -185,7 +218,7 @@ def forward(X_batch): "accuracy": accuracy, "macro_f1": macro_f1, "num_classes": num_classes, - "train_size": len(train_idx), + "train_size": len(fit_idx) + len(validation_idx), "test_size": len(test_idx), "num_epochs": num_epochs, "hidden_dim": hidden_dim, @@ -250,6 +283,13 @@ def gcn_classify( num_layers: int = 2, dropout: float = 0.5, ) -> Dict[str, float]: + """Trains a graph convolutional network on the embeddings and scores it on held-out entities. + + The entities are divided as in :func:`mlp_classify`: the checkpoint is chosen on a + validation part of the training entities and the test entities are scored once, + which is what ``accuracy`` and ``macro_f1`` report. ``train_size`` counts all + training entities, the validation part included. + """ from scipy.sparse import csr_matrix, diags, eye if not labels: @@ -288,17 +328,14 @@ def gcn_classify( y_mapped = np.array([class_map[c] for c in y]) rng = np.random.default_rng(seed) - perm = rng.permutation(len(y)) - split = int(len(y) * train_ratio) - train_idx, test_idx = perm[:split], perm[split:] - - if len(test_idx) == 0: - raise ValueError("Test set is empty, reduce train_ratio") + fit_idx, validation_idx, test_idx = _split_labelled(rng, len(y), train_ratio) node_indices = np.array(indices) - train_nodes = node_indices[train_idx] + train_nodes = node_indices[fit_idx] + validation_nodes = node_indices[validation_idx] test_nodes = node_indices[test_idx] - y_train = y_mapped[train_idx] + y_train = y_mapped[fit_idx] + y_validation = y_mapped[validation_idx] y_test = y_mapped[test_idx] X = embeddings.astype(np.float64) @@ -375,9 +412,10 @@ def forward(X_in, training=False): if epoch % 10 == 0 or epoch == num_epochs - 1: activations, _ = forward(X, training=False) - preds = np.argmax(activations[-1][test_nodes], axis=1) - acc = float(np.mean(preds == y_test)) - if acc > best_acc: + preds = np.argmax(activations[-1][validation_nodes], axis=1) + acc = float(np.mean(preds == y_validation)) + # ">=": of equally good checkpoints the latest, as in mlp_classify + if acc >= best_acc: best_acc = acc best_weights = [w.copy() for w in weights] @@ -402,7 +440,7 @@ def forward(X_in, training=False): "accuracy": accuracy, "macro_f1": macro_f1, "num_classes": num_classes, - "train_size": len(train_idx), + "train_size": len(fit_idx) + len(validation_idx), "test_size": len(test_idx), "num_layers": num_layers, "hidden_dim": hidden_dim, diff --git a/pycleora/cli.py b/pycleora/cli.py index d0af5a8..319412b 100644 --- a/pycleora/cli.py +++ b/pycleora/cli.py @@ -3,6 +3,11 @@ import time import numpy as np +# node2vec with p = q = 1 walks exactly like DeepWalk. q < 1 is the "outward" +# (exploring) setting of the node2vec paper, so that the name stands for another method. +NODE2VEC_P = 1.0 +NODE2VEC_Q = 0.5 + def main(): parser = argparse.ArgumentParser( @@ -15,13 +20,23 @@ def main(): embed_parser.add_argument("--input", "-i", required=True, help="Input edge file (TSV/CSV/space-separated)") embed_parser.add_argument("--output", "-o", required=True, help="Output file (npz/csv/tsv)") embed_parser.add_argument("--dim", "-d", type=int, default=256, help="Embedding dimension (default: 256)") - embed_parser.add_argument("--iterations", "-n", type=int, default=40, help="Number of iterations (default: 40)") + embed_parser.add_argument("--iterations", "-n", type=_iterations, default="auto", + help="Number of iterations, or 'auto' to take it from the density of the graph " + "(default: auto)") embed_parser.add_argument("--propagation", "-p", choices=["left", "symmetric"], default="left") embed_parser.add_argument("--normalization", choices=["l2", "l1", "none"], default="l2") embed_parser.add_argument("--columns", "-c", default="complex::reflexive::node", help="Column definition") embed_parser.add_argument("--algorithm", "-a", default="cleora", choices=["cleora", "prone", "randne", "hope", "netmf", "grarep", "deepwalk", "node2vec"]) embed_parser.add_argument("--seed", type=int, default=0) + embed_parser.add_argument("--p", type=float, default=NODE2VEC_P, + help=f"node2vec only: return parameter of the walks (default: {NODE2VEC_P})") + embed_parser.add_argument("--q", type=float, default=NODE2VEC_Q, + help=f"node2vec only: in-out parameter of the walks (default: {NODE2VEC_Q}); " + "p = q = 1 is DeepWalk") + embed_parser.add_argument("--whiten", action="store_true", + help="PCA-whiten the columns after every iteration (the default of pycleora 3.2): " + "much slower, needs many more entities than dimensions") embed_parser.add_argument("--verbose", "-v", action="store_true") info_parser = subparsers.add_parser("info", help="Show graph information") @@ -55,6 +70,19 @@ def main(): _cmd_similar(args) +def _iterations(text): + """Argument type of --iterations: a non-negative integer or 'auto'.""" + if text == "auto": + return text + try: + value = int(text) + except ValueError: + raise argparse.ArgumentTypeError(f"expected a number or 'auto', got '{text}'") + if value < 0: + raise argparse.ArgumentTypeError(f"must not be negative, got {value}") + return value + + def _read_edges(filepath): edges = [] with open(filepath, "r") as f: @@ -90,14 +118,15 @@ def _cmd_embed(args): t0 = time.time() algo_map = { - "cleora": lambda: embed(graph, args.dim, args.iterations, args.propagation, args.normalization, args.seed), + "cleora": lambda: embed(graph, args.dim, args.iterations, args.propagation, args.normalization, + args.seed, whiten=args.whiten), "prone": lambda: embed_prone(graph, args.dim, seed=args.seed), "randne": lambda: embed_randne(graph, args.dim, seed=args.seed), "hope": lambda: embed_hope(graph, args.dim), "netmf": lambda: embed_netmf(graph, args.dim), "grarep": lambda: embed_grarep(graph, args.dim), "deepwalk": lambda: embed_deepwalk(graph, args.dim, seed=args.seed), - "node2vec": lambda: embed_node2vec(graph, args.dim, seed=args.seed), + "node2vec": lambda: embed_node2vec(graph, args.dim, p=args.p, q=args.q, seed=args.seed), } emb = algo_map[args.algorithm]() @@ -142,14 +171,30 @@ def _cmd_benchmark(args): from .benchmark import benchmark_algorithms, format_benchmark_table ds = load_dataset(args.dataset) + if not ds.get("labels"): + kind = "multi-label targets" if ds.get("multilabel") else "no node labels" + raise SystemExit( + f"Dataset '{args.dataset}' has {kind}; this command needs one label per node. " + "See benchmarks/ in the repository for multi-label evaluation." + ) graph = SparseMatrix.from_iterator(iter(ds["edges"]), ds["columns"]) + dim = args.dim + if graph.num_entities < 4 * dim: + # Only the whitened row needs this: whitening estimates a dim x dim covariance + # from the entities and is useless without several times more entities than + # dimensions (see embed()). The other rows work at any dimension - the SVD-based + # ones pad with zero columns - but one table compares all rows at the same one. + dim = max(2, graph.num_entities // 4) + print(f"Using {dim} dimensions instead of {args.dim}: the graph has only {graph.num_entities} nodes.") + algorithms = { - "cleora": lambda g: embed(g, args.dim, 40), - "prone": lambda g: embed_prone(g, args.dim), - "randne": lambda g: embed_randne(g, args.dim), - "deepwalk": lambda g: embed_deepwalk(g, args.dim), - "node2vec": lambda g: embed_node2vec(g, args.dim), + "cleora": lambda g: embed(g, dim), + "cleora-whitened": lambda g: embed(g, dim, whiten=True), + "prone": lambda g: embed_prone(g, dim), + "randne": lambda g: embed_randne(g, dim), + "deepwalk": lambda g: embed_deepwalk(g, dim), + "node2vec": lambda g: embed_node2vec(g, dim, p=NODE2VEC_P, q=NODE2VEC_Q), } print(f"Benchmarking on {ds['name']} ({ds['num_nodes']} nodes)...") diff --git a/pycleora/datasets.py b/pycleora/datasets.py index 78411e1..ae07657 100644 --- a/pycleora/datasets.py +++ b/pycleora/datasets.py @@ -1,12 +1,40 @@ +"""Benchmark graphs. + +Every loader in this module returns real, published data, downloaded on first use +and cached under ``~/.pycleora_datasets`` (override with the ``PYCLEORA_DATA`` +environment variable). The returned dictionary always carries +``"synthetic": False`` and the ``"source"`` it was fetched from. + +Generated graphs live in :func:`load_synthetic` (and :mod:`pycleora.generators`); +they are always marked ``"synthetic": True`` and never carry the name of a real +dataset. +""" + import os import sys import gzip +import functools import numpy as np from typing import Dict, List, Tuple, Optional from collections.abc import Sequence -_CACHE_DIR = os.path.join(os.path.expanduser("~"), ".pycleora_datasets") +_CACHE_DIR = os.environ.get("PYCLEORA_DATA") or os.path.join(os.path.expanduser("~"), ".pycleora_datasets") + + +def _real(source: str, citation: Optional[str] = None): + """Marks a loader as returning real, published data.""" + def decorate(loader): + @functools.wraps(loader) + def wrapper(*args, **kwargs): + dataset = loader(*args, **kwargs) + dataset["synthetic"] = False + dataset["source"] = source + if citation: + dataset["citation"] = citation + return dataset + return wrapper + return decorate class _LazyEdgeList(Sequence): @@ -17,6 +45,16 @@ def __init__(self, src: np.ndarray, dst: np.ndarray): self._dst = dst self._len = len(src) + @property + def src(self) -> np.ndarray: + """Source node of every edge (integer ids; the entity name is ``str(id)``).""" + return self._src + + @property + def dst(self) -> np.ndarray: + """Target node of every edge.""" + return self._dst + def __len__(self): return self._len @@ -55,7 +93,8 @@ def _download_with_progress(url: str, filepath: str, description: str = "Downloa import ssl ctx = ssl.create_default_context() - req = urllib.request.Request(url) + # some hosts refuse the default urllib user agent + req = urllib.request.Request(url, headers={"User-Agent": "pycleora-datasets"}) response = urllib.request.urlopen(req, context=ctx) total_size = response.headers.get("Content-Length") total_size = int(total_size) if total_size else None @@ -220,6 +259,7 @@ def _load_snap_edge_list(name: str, url: str, display_name: str, description: st } +@_real("https://snap.stanford.edu/data/facebook_combined.txt.gz") def load_facebook() -> Dict: return _load_snap_edge_list( name="facebook", @@ -231,18 +271,20 @@ def load_facebook() -> Dict: ) +@_real("https://snap.stanford.edu/data/roadNet-CA.txt.gz") def load_roadnet() -> Dict: return _load_snap_edge_list( name="roadnet", url="https://snap.stanford.edu/data/roadNet-CA.txt.gz", display_name="roadNet-CA", - description="California road network (SNAP). ~2M nodes, ~2.8M edges.", + description="California road network (SNAP). ~2M nodes, ~2.8M roads (5.5M directed edge lines).", expected_nodes=1_965_206, expected_edges=5_533_214, - size_warning="roadNet-CA is a large dataset (~12MB compressed, ~2.8M edges).", + size_warning="roadNet-CA is a large dataset (~18MB compressed, ~5.5M edge lines).", ) +@_real("https://snap.stanford.edu/data/soc-LiveJournal1.txt.gz") def load_livejournal() -> Dict: return _load_snap_edge_list( name="livejournal", @@ -256,6 +298,7 @@ def load_livejournal() -> Dict: ) +@_real("https://snap.stanford.edu/data/bigdata/communities/com-orkut.ungraph.txt.gz") def load_com_orkut() -> Dict: return _load_snap_edge_list( name="com_orkut", @@ -267,6 +310,7 @@ def load_com_orkut() -> Dict: ) +@_real("https://snap.stanford.edu/data/bigdata/communities/com-friendster.ungraph.txt.gz") def load_com_friendster() -> Dict: return _load_snap_edge_list( name="com_friendster", @@ -280,6 +324,7 @@ def load_com_friendster() -> Dict: ) +@_real("embedded", "W. W. Zachary, J. Anthropol. Res. 33, 452-473 (1977)") def load_karate_club() -> Dict: edges = [ "0 1", "0 2", "0 3", "0 4", "0 5", "0 6", "0 7", "0 8", "0 10", "0 11", @@ -331,707 +376,445 @@ def load_karate_club() -> Dict: } -def load_dolphins() -> Dict: - edges = [ - "beak beescratch", "beak bumper", "beak fish", "beak jet", "beak knit", "beak mus", - "beak notch", "beak oscar", "beak sn4", "beak topless", "beak trigger", "beak web", - "beescratch bumper", "beescratch double", "beescratch five", "beescratch grin", - "beescratch jet", "beescratch knit", "beescratch mus", "beescratch notch", - "beescratch number1", "beescratch oscar", "beescratch patchback", "beescratch sn4", - "beescratch sn63", "beescratch sn89", "beescratch topless", "beescratch trigger", - "beescratch web", "beescratch zipfel", - "bumper double", "bumper grin", "bumper hook", "bumper jet", "bumper sn4", - "bumper topless", "bumper trigger", "bumper web", "bumper zipfel", - "ccl double", "ccl five", "ccl grin", "ccl hairy", "ccl hook", "ccl jet", - "ccl oscar", "ccl patchback", "ccl sn4", "ccl sn63", "ccl topless", "ccl trigger", - "cross dn16", "cross feather", "cross gallatin", "cross jonah", "cross ripplefluke", - "cross scabs", "cross sn96", "cross thumper", "cross upbang", "cross wave", - "dn16 feather", "dn16 gallatin", "dn16 ripplefluke", "dn16 scabs", "dn16 sn96", - "dn16 thumper", "dn16 upbang", "dn16 wave", - "dn21 feather", "dn21 gallatin", "dn21 jonah", "dn21 ripplefluke", - "dn21 scabs", "dn21 sn96", "dn21 thumper", "dn21 upbang", "dn21 wave", - "double five", "double grin", "double hook", "double jet", "double knit", - "double mus", "double notch", "double number1", "double oscar", "double patchback", - "double sn4", "double sn63", "double sn89", "double topless", "double trigger", - "double web", "double zipfel", - "feather gallatin", "feather jonah", "feather ripplefluke", "feather scabs", - "feather sn96", "feather thumper", "feather upbang", "feather wave", - "fish jet", "fish knit", "fish mus", "fish notch", "fish sn4", - "five grin", "five hairy", "five hook", "five jet", "five knit", - "five mus", "five notch", "five number1", "five oscar", "five patchback", - "five sn4", "five sn63", "five sn89", "five topless", "five trigger", - "five web", "five zipfel", - "fork gallatin", "fork ripplefluke", "fork scabs", "fork sn96", "fork thumper", - "gallatin jonah", "gallatin ripplefluke", "gallatin scabs", "gallatin sn96", - "gallatin thumper", "gallatin upbang", "gallatin wave", - "grin hook", "grin jet", "grin knit", "grin mus", "grin notch", - "grin number1", "grin oscar", "grin patchback", "grin sn4", - "grin sn63", "grin sn89", "grin topless", "grin trigger", "grin web", "grin zipfel", - "hairy hook", "hairy jet", "hairy sn4", "hairy topless", - "hook jet", "hook knit", "hook mus", "hook notch", "hook sn4", - "hook topless", "hook trigger", "hook web", - "jet knit", "jet mus", "jet notch", "jet sn4", "jet topless", - "jet trigger", "jet web", - "jonah ripplefluke", "jonah scabs", "jonah sn96", "jonah thumper", - "jonah upbang", "jonah wave", - "knit mus", "knit notch", "knit sn4", "knit trigger", - "mus notch", "mus oscar", "mus sn4", "mus trigger", - "notch sn4", "notch trigger", - "number1 oscar", "number1 sn89", "number1 trigger", - "oscar sn4", "oscar topless", "oscar trigger", - "patchback sn4", "patchback sn63", "patchback sn89", "patchback topless", - "patchback trigger", "patchback web", - "ripplefluke scabs", "ripplefluke sn96", "ripplefluke thumper", "ripplefluke upbang", - "ripplefluke wave", - "scabs sn96", "scabs thumper", "scabs upbang", "scabs wave", - "sn4 topless", "sn4 trigger", "sn4 web", - "sn63 sn89", "sn63 topless", "sn63 trigger", "sn63 web", - "sn89 topless", "sn89 trigger", "sn89 web", - "sn96 thumper", "sn96 upbang", - "thumper upbang", "thumper wave", - "topless trigger", "topless web", - "trigger web", "trigger zipfel", - "upbang wave", - "web zipfel", - ] - - labels = {} - group_0 = ["beak", "fish", "jet", "knit", "mus", "notch", "sn4", "trigger", - "bumper", "hook", "topless", "web", "grin", "hairy"] - group_1 = ["beescratch", "double", "five", "number1", "oscar", "patchback", - "sn63", "sn89", "zipfel", "ccl"] - group_2 = ["cross", "dn16", "dn21", "feather", "gallatin", "jonah", "ripplefluke", - "scabs", "sn96", "thumper", "upbang", "wave", "fork"] - for n in group_0: - labels[n] = 0 - for n in group_1: - labels[n] = 1 - for n in group_2: - labels[n] = 2 +def _download_to_cache(url: str, filename: str, description: str) -> str: + """Downloads ``url`` into the cache once and returns the local path.""" + _ensure_cache_dir() + path = os.path.join(_CACHE_DIR, filename) + if not os.path.exists(path): + tmp_path = path + ".tmp" + _download_with_progress(url, tmp_path, description=f"Downloading {description}") + os.replace(tmp_path, path) + return path + + +def _undirected_unique(src: np.ndarray, dst: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: + """One (low, high) pair per undirected edge, self-loops dropped, sorted.""" + src = np.asarray(src, dtype=np.int64) + dst = np.asarray(dst, dtype=np.int64) + low = np.minimum(src, dst) + high = np.maximum(src, dst) + keep = low != high + pairs = np.unique(np.stack([low[keep], high[keep]], axis=1), axis=0) + dtype = np.int32 if (pairs.size == 0 or pairs.max() <= np.iinfo(np.int32).max) else np.int64 + return pairs[:, 0].astype(dtype), pairs[:, 1].astype(dtype) + + +def _parse_gml(text: str): + """Minimal reader for the GML files of M. Newman's network collection. + + Returns ``(nodes, edges)``: ``nodes`` maps node id to its attributes, + ``edges`` is a list of attribute dictionaries with ``source`` and ``target``. + """ + import re + + def attributes(body: str) -> Dict: + result = {} + for key, value in re.findall(r'(\w+)\s+("[^"]*"|[-+]?[\d.]+(?:[eE][-+]?\d+)?)', body): + if value.startswith('"'): + result[key] = value[1:-1] + else: + number = float(value) + result[key] = int(number) if number.is_integer() else number + return result + + nodes = {} + edges = [] + for kind, body in re.findall(r"\b(node|edge)\s*\[(.*?)\]", text, flags=re.S): + attrs = attributes(body) + if kind == "node": + nodes[attrs["id"]] = attrs + else: + edges.append(attrs) + return nodes, edges - return { - "name": "Dolphins Social Network", - "edges": edges, - "labels": labels, - "num_nodes": 62, - "num_edges": len(edges), - "num_classes": 3, - "columns": "complex::reflexive::dolphin", - "description": "Social network of bottlenose dolphins (Lusseau, 2003). 62 dolphins, 3 communities.", - } +_NEWMAN_URL = "https://websites.umich.edu/~mejn/netdata/{name}.zip" -def load_les_miserables() -> Dict: - edges = [ - "Myriel Napoleon", "Myriel MlleBaptistine", "Myriel MmeMagloire", - "Myriel CountessDeLo", "Myriel Geborand", "Myriel Champtercier", - "Myriel Cravatte", "Myriel Count", "Myriel OldMan", - "Napoleon Myriel", - "MlleBaptistine Myriel", "MlleBaptistine MmeMagloire", - "MmeMagloire Myriel", "MmeMagloire MlleBaptistine", - "Valjean Myriel", "Valjean MlleBaptistine", "Valjean MmeMagloire", - "Valjean Fantine", "Valjean Cosette", "Valjean Javert", "Valjean Fauchelevent", - "Valjean Bamatabois", "Valjean Enjolras", "Valjean Gavroche", "Valjean Marius", - "Valjean Eponine", "Valjean Thenardier", "Valjean MmeThenardier", - "Valjean Champmathieu", "Valjean Brevet", "Valjean Chenildieu", "Valjean Cochepaille", - "Fantine Valjean", "Fantine Javert", "Fantine Bamatabois", "Fantine Thenardier", - "Fantine MmeThenardier", "Fantine Marguerite", "Fantine Dahlia", "Fantine Zephine", - "Fantine Favourite", "Fantine Tholomyes", - "Cosette Valjean", "Cosette Javert", "Cosette Thenardier", "Cosette MmeThenardier", - "Cosette Eponine", "Cosette Marius", "Cosette Gavroche", - "Javert Valjean", "Javert Fantine", "Javert Bamatabois", "Javert Gavroche", - "Javert Enjolras", "Javert Thenardier", - "Gavroche Valjean", "Gavroche Javert", "Gavroche Thenardier", - "Gavroche MmeThenardier", "Gavroche Enjolras", "Gavroche Courfeyrac", - "Gavroche Combeferre", "Gavroche Mabeuf", "Gavroche Marius", "Gavroche Eponine", - "Gavroche Bahorel", "Gavroche Bossuet", "Gavroche Joly", "Gavroche Grantaire", - "Gavroche Prouvaire", "Gavroche Feuilly", - "Marius Valjean", "Marius Cosette", "Marius Eponine", "Marius Gavroche", - "Marius Enjolras", "Marius Courfeyrac", "Marius Combeferre", "Marius Mabeuf", - "Marius Thenardier", "Marius Pontmercy", "Marius Gillenormand", "Marius MlleGillenormand", - "Marius LtGillenormand", "Marius BaronessT", - "Enjolras Valjean", "Enjolras Javert", "Enjolras Gavroche", "Enjolras Marius", - "Enjolras Courfeyrac", "Enjolras Combeferre", "Enjolras Bahorel", - "Enjolras Bossuet", "Enjolras Joly", "Enjolras Grantaire", "Enjolras Prouvaire", - "Enjolras Feuilly", - "Thenardier Valjean", "Thenardier Fantine", "Thenardier Cosette", "Thenardier Javert", - "Thenardier Gavroche", "Thenardier Eponine", "Thenardier MmeThenardier", - "Thenardier Marius", "Thenardier Brujon", "Thenardier Babet", "Thenardier Claquesous", - "Thenardier Gueulemer", "Thenardier Montparnasse", - "Eponine Valjean", "Eponine Cosette", "Eponine Marius", "Eponine Gavroche", - "Eponine Thenardier", "Eponine MmeThenardier", - "Courfeyrac Gavroche", "Courfeyrac Marius", "Courfeyrac Enjolras", - "Courfeyrac Combeferre", "Courfeyrac Bahorel", "Courfeyrac Bossuet", - "Courfeyrac Joly", "Courfeyrac Grantaire", "Courfeyrac Prouvaire", "Courfeyrac Feuilly", - "Combeferre Gavroche", "Combeferre Marius", "Combeferre Enjolras", - "Combeferre Courfeyrac", "Combeferre Bahorel", "Combeferre Bossuet", - "Combeferre Joly", "Combeferre Grantaire", "Combeferre Prouvaire", "Combeferre Feuilly", - "Mabeuf Gavroche", "Mabeuf Marius", "Mabeuf Enjolras", - "Bossuet Gavroche", "Bossuet Enjolras", "Bossuet Courfeyrac", "Bossuet Combeferre", - "Bossuet Bahorel", "Bossuet Joly", "Bossuet Grantaire", "Bossuet Prouvaire", - "Bossuet Feuilly", "Bossuet Marius", - "Joly Gavroche", "Joly Enjolras", "Joly Courfeyrac", "Joly Combeferre", - "Joly Bahorel", "Joly Bossuet", "Joly Grantaire", "Joly Prouvaire", "Joly Feuilly", - "Grantaire Gavroche", "Grantaire Enjolras", "Grantaire Courfeyrac", - "Grantaire Combeferre", "Grantaire Bahorel", "Grantaire Bossuet", "Grantaire Joly", - "Grantaire Prouvaire", "Grantaire Feuilly", - "Bahorel Gavroche", "Bahorel Enjolras", "Bahorel Courfeyrac", "Bahorel Combeferre", - "Bahorel Bossuet", "Bahorel Joly", "Bahorel Grantaire", "Bahorel Prouvaire", - "Bahorel Feuilly", - "Prouvaire Gavroche", "Prouvaire Enjolras", "Prouvaire Courfeyrac", - "Prouvaire Combeferre", "Prouvaire Bahorel", "Prouvaire Bossuet", "Prouvaire Joly", - "Prouvaire Grantaire", "Prouvaire Feuilly", - "Feuilly Gavroche", "Feuilly Enjolras", "Feuilly Courfeyrac", "Feuilly Combeferre", - "Feuilly Bahorel", "Feuilly Bossuet", "Feuilly Joly", "Feuilly Grantaire", - "Feuilly Prouvaire", - ] - labels = {} - groups = { - 0: ["Myriel", "Napoleon", "MlleBaptistine", "MmeMagloire", "CountessDeLo", - "Geborand", "Champtercier", "Cravatte", "Count", "OldMan"], - 1: ["Valjean", "Fantine", "Bamatabois", "Fauchelevent", "Champmathieu", - "Brevet", "Chenildieu", "Cochepaille", "Marguerite"], - 2: ["Cosette", "Marius", "Eponine", "Pontmercy", "Gillenormand", - "MlleGillenormand", "LtGillenormand", "BaronessT"], - 3: ["Javert"], - 4: ["Thenardier", "MmeThenardier", "Brujon", "Babet", "Claquesous", - "Gueulemer", "Montparnasse"], - 5: ["Gavroche", "Enjolras", "Courfeyrac", "Combeferre", "Mabeuf", - "Bahorel", "Bossuet", "Joly", "Grantaire", "Prouvaire", "Feuilly"], - 6: ["Dahlia", "Zephine", "Favourite", "Tholomyes"], - } - for group_id, members in groups.items(): - for m in members: - labels[m] = group_id +def _load_newman(name: str, display_name: str, description: str, column: str, + labelled: bool = False, weighted: bool = False) -> Dict: + import zipfile - return { - "name": "Les Miserables", - "edges": edges, - "labels": labels, - "num_nodes": 77, - "num_edges": len(edges), - "num_classes": 7, - "columns": "complex::reflexive::character", - "description": "Character co-appearance network from Victor Hugo's Les Miserables. 77 characters, 7 groups.", - } + path = _download_to_cache(_NEWMAN_URL.format(name=name), f"newman_{name}.zip", display_name) + with zipfile.ZipFile(path) as archive: + member = _find_zip_member(archive, ".gml") + text = archive.read(member).decode("utf-8", errors="replace") + nodes, raw_edges = _parse_gml(text) + def node_name(node_id) -> str: + return "_".join(str(nodes[node_id].get("label", node_id)).split()) -def load_football() -> Dict: - edges = [ - "BYU AirForce", "BYU Utah", "BYU UtahState", "BYU NewMexico", "BYU SanDiegoState", - "BYU ColoradoState", "BYU UNLV", "BYU Wyoming", - "AirForce Army", "AirForce Navy", "AirForce Colorado", "AirForce Wyoming", - "AirForce SanDiegoState", "AirForce UNLV", "AirForce NewMexico", "AirForce ColoradoState", - "Utah UtahState", "Utah SanDiegoState", "Utah ColoradoState", "Utah NewMexico", - "Utah Wyoming", "Utah UNLV", - "UtahState NewMexico", "UtahState SanDiegoState", - "Wyoming ColoradoState", "Wyoming UNLV", "Wyoming SanDiegoState", "Wyoming NewMexico", - "UNLV SanDiegoState", "UNLV ColoradoState", "UNLV NewMexico", - "Colorado ColoradoState", - "SanDiegoState ColoradoState", "SanDiegoState NewMexico", - "ColoradoState NewMexico", - "OhioState Michigan", "OhioState PennState", "OhioState Wisconsin", "OhioState Purdue", - "OhioState Minnesota", "OhioState Illinois", "OhioState Indiana", "OhioState Iowa", - "Michigan MichiganState", "Michigan PennState", "Michigan Wisconsin", "Michigan Purdue", - "Michigan Northwestern", "Michigan Illinois", "Michigan Indiana", "Michigan Iowa", - "PennState Wisconsin", "PennState Purdue", "PennState Minnesota", "PennState Illinois", - "PennState Indiana", "PennState Iowa", - "Wisconsin Purdue", "Wisconsin Minnesota", "Wisconsin Northwestern", "Wisconsin Iowa", - "Purdue Minnesota", "Purdue Northwestern", "Purdue Illinois", "Purdue Indiana", - "Minnesota Northwestern", "Minnesota Illinois", - "Northwestern Illinois", "Northwestern Indiana", "Northwestern Iowa", - "Illinois Indiana", "Illinois Iowa", - "Indiana Iowa", - "MichiganState Iowa", "MichiganState Northwestern", - "Florida Georgia", "Florida Tennessee", "Florida LSU", "Florida Auburn", - "Florida Alabama", "Florida SouthCarolina", "Florida Kentucky", "Florida Vanderbilt", - "Florida Mississippi", - "Georgia Tennessee", "Georgia Auburn", "Georgia SouthCarolina", "Georgia Kentucky", - "Georgia Vanderbilt", "Georgia OleMiss", - "Tennessee Alabama", "Tennessee LSU", "Tennessee Auburn", "Tennessee Arkansas", - "Tennessee Kentucky", "Tennessee Vanderbilt", - "Alabama Auburn", "Alabama LSU", "Alabama Arkansas", "Alabama Mississippi", - "Alabama OleMiss", "Alabama Vanderbilt", - "Auburn LSU", "Auburn Arkansas", "Auburn Mississippi", "Auburn OleMiss", - "LSU Arkansas", "LSU Mississippi", "LSU OleMiss", "LSU Kentucky", - "Arkansas Mississippi", "Arkansas OleMiss", "Arkansas SouthCarolina", - "Mississippi OleMiss", "Mississippi Kentucky", "Mississippi Vanderbilt", - "OleMiss Kentucky", "OleMiss Vanderbilt", - "SouthCarolina Kentucky", "SouthCarolina Vanderbilt", - "Kentucky Vanderbilt", - ] + edges = [] + weights = [] + for edge in raw_edges: + if edge["source"] == edge["target"]: + continue + edges.append(f"{node_name(edge['source'])} {node_name(edge['target'])}") + weights.append(float(edge.get("value", 1.0))) labels = {} - conferences = { - 0: ["BYU", "Utah", "UtahState", "NewMexico", "SanDiegoState", - "ColoradoState", "UNLV", "Wyoming", "AirForce"], - 1: ["OhioState", "Michigan", "MichiganState", "PennState", "Wisconsin", - "Purdue", "Minnesota", "Northwestern", "Illinois", "Indiana", "Iowa"], - 2: ["Florida", "Georgia", "Tennessee", "Alabama", "Auburn", "LSU", - "Arkansas", "Mississippi", "OleMiss", "SouthCarolina", "Kentucky", "Vanderbilt"], - } - for conf_id, teams in conferences.items(): - for t in teams: - labels[t] = conf_id + if labelled: + labels = {node_name(node_id): int(attrs["value"]) for node_id, attrs in nodes.items() if "value" in attrs} - return { - "name": "American Football", + dataset = { + "name": display_name, "edges": edges, "labels": labels, - "num_nodes": len(labels), + "num_nodes": len(nodes), "num_edges": len(edges), - "num_classes": 3, - "columns": "complex::reflexive::team", - "description": "American college football network. Teams as nodes, games as edges. 3 conferences shown.", + "num_classes": len(set(labels.values())), + "columns": f"complex::reflexive::{column}", + "description": description, } + if weighted: + dataset["weights"] = weights + return dataset -def load_cora() -> Dict: - return _load_citation_dataset( - "cora", - "Cora Citation Network", - "Citation network of ML papers. 2708 nodes, 5429 edges, 7 classes.", - num_classes=7, +@_real(_NEWMAN_URL.format(name="dolphins"), "D. Lusseau et al., Behav. Ecol. Sociobiol. 54, 396-405 (2003)") +def load_dolphins() -> Dict: + return _load_newman( + "dolphins", "Dolphins Social Network", + "Social network of 62 bottlenose dolphins in Doubtful Sound, New Zealand (Lusseau et al., 2003). " + "159 frequent associations. No labels.", + column="dolphin", ) -def load_citeseer() -> Dict: - return _load_citation_dataset( - "citeseer", - "CiteSeer Citation Network", - "Citation network of CS papers. 3312 nodes, 4732 edges, 6 classes.", - num_classes=6, +@_real(_NEWMAN_URL.format(name="lesmis"), "D. E. Knuth, The Stanford GraphBase (1993)") +def load_les_miserables() -> Dict: + return _load_newman( + "lesmis", "Les Miserables", + "Co-appearance network of the 77 characters of Victor Hugo's Les Miserables (Knuth, 1993). " + "254 edges; 'weights' holds the number of chapters two characters share. No labels.", + column="character", weighted=True, ) -def load_pubmed() -> Dict: - return _load_citation_dataset( - "pubmed", - "PubMed Diabetes Dataset", - "Citation network of diabetes papers. 19717 nodes, 44338 edges, 3 classes.", - num_classes=3, +@_real(_NEWMAN_URL.format(name="football"), "M. Girvan and M. E. J. Newman, PNAS 99, 7821-7826 (2002)") +def load_football() -> Dict: + return _load_newman( + "football", "American College Football", + "Games between the 115 Division IA college football teams in the 2000 season " + "(Girvan & Newman, 2002). 613 games; labels are the 12 conferences.", + column="team", labelled=True, ) -def _load_citation_dataset(name, display_name, description, num_classes): - _ensure_cache_dir() - cache_path = os.path.join(_CACHE_DIR, f"{name}.npz") +_PLANETOID_URL = "https://raw.githubusercontent.com/kimiyoung/planetoid/master/data/ind.{name}.{part}" - if os.path.exists(cache_path): - data = np.load(cache_path, allow_pickle=True) - return { - "name": display_name, - "edges": data["edges"].tolist(), - "labels": dict(zip(data["label_keys"].tolist(), data["label_vals"].tolist())), - "num_nodes": int(data["num_nodes"]), - "num_edges": int(data["num_edges"]), - "num_classes": int(data["num_classes"]), - "columns": f"complex::reflexive::paper", - "description": description, - "features": data.get("features", None), - } - edges, labels, features = _generate_citation_graph(name, num_classes) - num_nodes = len(labels) +def _load_planetoid_pickle(path: str): + """Reads one of the Planetoid data files. - label_keys = list(labels.keys()) - label_vals = list(labels.values()) + The files are Python 2 pickles. Unpickling can execute arbitrary code, so only + the handful of constructors these files actually use are allowed. + """ + import importlib + import pickle - save_dict = { - "edges": np.array(edges), - "label_keys": np.array(label_keys), - "label_vals": np.array(label_vals), - "num_nodes": num_nodes, - "num_edges": len(edges), - "num_classes": num_classes, + allowed = { + ("__builtin__", "list"): ("builtins", "list"), + ("builtins", "list"): ("builtins", "list"), + ("collections", "defaultdict"): ("collections", "defaultdict"), + ("numpy", "dtype"): ("numpy", "dtype"), + ("numpy", "ndarray"): ("numpy", "ndarray"), + ("numpy.core.multiarray", "_reconstruct"): (None, "_reconstruct"), + ("numpy._core.multiarray", "_reconstruct"): (None, "_reconstruct"), } - if features is not None: - save_dict["features"] = features - np.savez(cache_path, **save_dict) + class RestrictedUnpickler(pickle.Unpickler): + def find_class(self, module, name): + target = allowed.get((module, name)) + if target is None: + raise pickle.UnpicklingError(f"refusing to load '{module}.{name}' from a dataset file") + if target[0] is None: + try: + multiarray = importlib.import_module("numpy._core.multiarray") + except ImportError: + multiarray = importlib.import_module("numpy.core.multiarray") + return getattr(multiarray, target[1]) + return getattr(importlib.import_module(target[0]), target[1]) + + with open(path, "rb") as f: + return RestrictedUnpickler(f, encoding="latin1").load() + + +def _load_planetoid(name: str, display_name: str, description: str, num_classes: int) -> Dict: + _ensure_cache_dir() + cache_path = os.path.join(_CACHE_DIR, f"planetoid_{name}.npz") + if not os.path.exists(cache_path): + parts = {} + for part in ("graph", "ally", "ty", "test.index"): + parts[part] = _download_to_cache( + _PLANETOID_URL.format(name=name, part=part), f"ind.{name}.{part}", f"{display_name} ({part})" + ) + graph = _load_planetoid_pickle(parts["graph"]) + ally = np.asarray(_load_planetoid_pickle(parts["ally"])) + ty = np.asarray(_load_planetoid_pickle(parts["ty"])) + with open(parts["test.index"]) as f: + test_index = np.array([int(line) for line in f if line.strip()], dtype=np.int64) + + # Test nodes are stored in shuffled order; CiteSeer additionally has test + # indices without any data (isolated papers), which stay unlabelled. + test_sorted = np.sort(test_index) + full_range = np.arange(test_sorted[0], test_sorted[-1] + 1) + ty_full = np.zeros((len(full_range), ty.shape[1]), dtype=ty.dtype) + ty_full[test_sorted - test_sorted[0]] = ty + one_hot = np.vstack([ally, ty_full]) + one_hot[test_index] = one_hot[test_sorted] + has_label = one_hot.sum(axis=1) > 0 + label_of = np.where(has_label, one_hot.argmax(axis=1), -1).astype(np.int32) + + src = np.fromiter((node for node, nbrs in graph.items() for _ in nbrs), dtype=np.int64) + dst = np.fromiter((nbr for nbrs in graph.values() for nbr in nbrs), dtype=np.int64) + src, dst = _undirected_unique(src, dst) + tmp_path = cache_path + ".tmp.npz" + np.savez(tmp_path, src=src, dst=dst, labels=label_of) + os.replace(tmp_path, cache_path) + + data = np.load(cache_path, allow_pickle=False) + src, dst, label_of = data["src"], data["dst"], data["labels"] + in_graph = np.union1d(src, dst) + labels = {str(int(node)): int(label_of[node]) for node in in_graph if label_of[node] >= 0} return { "name": display_name, - "edges": edges, + "edges": _LazyEdgeList(src, dst), "labels": labels, - "num_nodes": num_nodes, - "num_edges": len(edges), + "num_nodes": int(len(in_graph)), + "num_edges": int(len(src)), "num_classes": num_classes, "columns": "complex::reflexive::paper", "description": description, - "features": features, } -def _generate_citation_graph(name, num_classes, seed=42): - rng = np.random.default_rng(seed) +_PLANETOID_CITATION = "Z. Yang, W. Cohen, R. Salakhutdinov, ICML 2016 (data: Sen et al., AI Magazine 2008)" - configs = { - "cora": {"nodes": 2708, "edges": 5429, "feat_dim": 1433}, - "citeseer": {"nodes": 3312, "edges": 4732, "feat_dim": 3703}, - "pubmed": {"nodes": 19717, "edges": 44338, "feat_dim": 500}, - } - cfg = configs[name] - n = cfg["nodes"] - num_edges = cfg["edges"] - feat_dim = cfg["feat_dim"] +@_real(_PLANETOID_URL.format(name="cora", part="*"), _PLANETOID_CITATION) +def load_cora() -> Dict: + return _load_planetoid( + "cora", "Cora Citation Network", + "Citation network of 2,708 machine-learning papers (Planetoid version): " + "5,278 undirected citation links, 7 subject classes.", + num_classes=7, + ) - community_assignments = rng.integers(0, num_classes, size=n) - labels = {} - for i in range(n): - labels[f"p{i}"] = int(community_assignments[i]) - edge_set = set() - for i in range(n): - comm = community_assignments[i] - num_neighbors = rng.poisson(lam=num_edges * 2 / n) - num_neighbors = max(1, min(num_neighbors, 20)) +@_real(_PLANETOID_URL.format(name="citeseer", part="*"), _PLANETOID_CITATION) +def load_citeseer() -> Dict: + return _load_planetoid( + "citeseer", "CiteSeer Citation Network", + "Citation network of computer-science papers (Planetoid version): " + "3,279 papers with at least one link, 4,552 undirected citation links, 6 subject classes.", + num_classes=6, + ) - for _ in range(num_neighbors): - if rng.random() < 0.7: - same_comm = np.where(community_assignments == comm)[0] - j = int(rng.choice(same_comm)) - else: - j = int(rng.integers(0, n)) - if i != j: - edge_set.add((min(i, j), max(i, j))) - if len(edge_set) >= num_edges: - break - if len(edge_set) >= num_edges: - break +@_real(_PLANETOID_URL.format(name="pubmed", part="*"), _PLANETOID_CITATION) +def load_pubmed() -> Dict: + return _load_planetoid( + "pubmed", "PubMed Diabetes Citation Network", + "Citation network of 19,717 diabetes publications (Planetoid version): " + "44,324 undirected citation links, 3 classes.", + num_classes=3, + ) - while len(edge_set) < num_edges: - i = int(rng.integers(0, n)) - j = int(rng.integers(0, n)) - if i != j: - edge_set.add((min(i, j), max(i, j))) - edges = [f"p{i} p{j}" for i, j in edge_set] +_AMAZON_URL = "https://raw.githubusercontent.com/shchur/gnn-benchmark/master/data/npz/amazon_electronics_{name}.npz" - features = rng.standard_normal((n, min(feat_dim, 64))).astype(np.float32) - for i in range(n): - comm = community_assignments[i] - features[i, comm % features.shape[1]] += 2.0 - return edges, labels, features +def _load_amazon(name: str, display_name: str, description: str) -> Dict: + path = _download_to_cache(_AMAZON_URL.format(name=name), f"amazon_electronics_{name}.npz", display_name) + data = np.load(path, allow_pickle=False) + indptr = data["adj_indptr"] + src = np.repeat(np.arange(len(indptr) - 1, dtype=np.int64), np.diff(indptr)) + src, dst = _undirected_unique(src, data["adj_indices"]) + label_of = np.asarray(data["labels"], dtype=np.int64) + in_graph = np.union1d(src, dst) + return { + "name": display_name, + "edges": _LazyEdgeList(src, dst), + "labels": {str(int(node)): int(label_of[node]) for node in in_graph}, + "num_nodes": int(len(in_graph)), + "num_edges": int(len(src)), + "num_classes": int(len(np.unique(label_of))), + "columns": "complex::reflexive::product", + "description": description, + } +_AMAZON_CITATION = "O. Shchur et al., Pitfalls of Graph Neural Network Evaluation (2018); data: McAuley et al., SIGIR 2015" + + +@_real(_AMAZON_URL.format(name="computers"), _AMAZON_CITATION) def load_amazon_computers() -> Dict: - return _generate_product_graph( - "amazon_computers", - "Amazon Computers", - "Amazon co-purchase graph for computers. Nodes are products, edges are co-purchases.", - num_nodes=13752, - num_edges=245861, - num_classes=10, - seed=100, + return _load_amazon( + "computers", "Amazon Computers", + "Amazon co-purchase graph of computer products: nodes are products, edges link " + "products that are frequently bought together, labels are 10 product categories.", ) +@_real(_AMAZON_URL.format(name="photo"), _AMAZON_CITATION) def load_amazon_photo() -> Dict: - return _generate_product_graph( - "amazon_photo", - "Amazon Photo", - "Amazon co-purchase graph for photo products.", - num_nodes=7650, - num_edges=119081, - num_classes=8, - seed=200, + return _load_amazon( + "photo", "Amazon Photo", + "Amazon co-purchase graph of photo products: nodes are products, edges link " + "products that are frequently bought together, labels are 8 product categories.", ) -def _generate_product_graph(name, display_name, description, num_nodes, num_edges, num_classes, seed): - _ensure_cache_dir() - cache_path = os.path.join(_CACHE_DIR, f"{name}.npz") - - if os.path.exists(cache_path): - data = np.load(cache_path, allow_pickle=True) - return { - "name": display_name, - "edges": data["edges"].tolist(), - "labels": dict(zip(data["label_keys"].tolist(), data["label_vals"].tolist())), - "num_nodes": int(data["num_nodes"]), - "num_edges": int(data["num_edges"]), - "num_classes": int(data["num_classes"]), - "columns": "complex::reflexive::product", - "description": description, - } - - rng = np.random.default_rng(seed) - community = rng.integers(0, num_classes, size=num_nodes) - labels = {f"prod{i}": int(community[i]) for i in range(num_nodes)} - - edge_set = set() - for i in range(num_nodes): - comm = community[i] - num_nb = rng.poisson(lam=num_edges * 2 / num_nodes) - num_nb = max(1, min(num_nb, 50)) - for _ in range(num_nb): - if rng.random() < 0.65: - same = np.where(community == comm)[0] - j = int(rng.choice(same)) - else: - j = int(rng.integers(0, num_nodes)) - if i != j: - edge_set.add((min(i, j), max(i, j))) - if len(edge_set) >= num_edges: - break - if len(edge_set) >= num_edges: - break +def _undirected_weights(adjacency, src: np.ndarray, dst: np.ndarray) -> List[float]: + """The weight of every undirected edge ``src[i] - dst[i]`` of a sparse adjacency matrix. - while len(edge_set) < num_edges: - i, j = int(rng.integers(0, num_nodes)), int(rng.integers(0, num_nodes)) - if i != j: - edge_set.add((min(i, j), max(i, j))) + A file may store an edge in one direction or in both: the larger entry is taken, + which in a symmetric matrix is simply the weight. + """ + either_direction = adjacency.maximum(adjacency.T).tocsr() + return np.asarray(either_direction[src, dst], dtype=np.float64).ravel().tolist() - edges = [f"prod{i} prod{j}" for i, j in edge_set] - np.savez(cache_path, - edges=np.array(edges), - label_keys=np.array(list(labels.keys())), - label_vals=np.array(list(labels.values())), - num_nodes=num_nodes, num_edges=len(edges), num_classes=num_classes) +def _load_node2vec_mat(filename: str, display_name: str, description: str, column: str, + weighted: bool = False) -> Dict: + """The multi-label networks distributed with node2vec (MATLAB files).""" + import scipy.io + import scipy.sparse - return { + url = f"https://snap.stanford.edu/node2vec/{filename}" + path = _download_to_cache(url, f"node2vec_{filename}", display_name) + content = scipy.io.loadmat(path) + adjacency = scipy.sparse.coo_matrix(content["network"]) + src, dst = _undirected_unique(adjacency.row, adjacency.col) + label_matrix = np.asarray(scipy.sparse.csr_matrix(content["group"]).todense()).astype(np.uint8) + in_graph = np.union1d(src, dst) + dataset = { "name": display_name, - "edges": edges, - "labels": labels, - "num_nodes": num_nodes, - "num_edges": len(edges), - "num_classes": num_classes, - "columns": "complex::reflexive::product", + "edges": _LazyEdgeList(src, dst), + # every node may carry several labels: see "label_matrix" + "labels": {}, + "multilabel": True, + "label_entities": [str(int(node)) for node in in_graph], + "label_matrix": label_matrix[in_graph], + "num_nodes": int(len(in_graph)), + "num_edges": int(len(src)), + "num_classes": int(label_matrix.shape[1]), + "columns": f"complex::reflexive::{column}", "description": description, } + if weighted: + dataset["weights"] = _undirected_weights(adjacency, src, dst) + return dataset + + +_NODE2VEC_CITATION = "A. Grover and J. Leskovec, node2vec, KDD 2016" +@_real("https://snap.stanford.edu/node2vec/Homo_sapiens.mat", _NODE2VEC_CITATION) def load_ppi() -> Dict: - return _generate_product_graph( - "ppi", - "Protein-Protein Interaction", - "PPI network with protein functions as labels.", - num_nodes=3890, - num_edges=76584, - num_classes=50, - seed=300, + return _load_node2vec_mat( + "Homo_sapiens.mat", "Protein-Protein Interaction (Homo sapiens)", + "Protein-protein interaction network of Homo sapiens (node2vec version): 3,860 proteins with " + "at least one interaction, 37,845 interactions, 50 biological-state labels. Multi-label: a protein can carry several labels " + "('label_matrix' has one row per entry of 'label_entities').", + column="protein", ) -def load_dblp() -> Dict: - _ensure_cache_dir() - cache_path = os.path.join(_CACHE_DIR, "dblp.npz") +@_real("https://snap.stanford.edu/node2vec/POS.mat", _NODE2VEC_CITATION) +def load_wikipedia_pos() -> Dict: + return _load_node2vec_mat( + "POS.mat", "Wikipedia word co-occurrence (POS)", + "Co-occurrence network of 4,777 words from a Wikipedia dump (node2vec version) with " + "40 part-of-speech labels. Multi-label ('label_matrix' / 'label_entities'). " + "'weights' holds the co-occurrence weight of every edge.", + column="word", weighted=True, + ) - if os.path.exists(cache_path): - data = np.load(cache_path, allow_pickle=True) - return { - "name": "DBLP", - "edges": data["edges"].tolist(), - "labels": dict(zip(data["label_keys"].tolist(), data["label_vals"].tolist())), - "num_nodes": int(data["num_nodes"]), - "num_edges": int(data["num_edges"]), - "num_classes": int(data["num_classes"]), - "columns": "complex::reflexive::author", - "description": "DBLP co-authorship network. 4 research areas.", - "is_heterogeneous": True, - "edge_types": data["edge_types"].tolist() if "edge_types" in data else None, - } - rng = np.random.default_rng(400) - num_authors = 4057 - num_papers = 14328 - num_classes = 4 +@_real("https://snap.stanford.edu/data/email-Eu-core.html", + "J. Leskovec, J. Kleinberg, C. Faloutsos (2007); H. Yin et al., KDD 2017") +def load_email_eu_core() -> Dict: + edges_path = _download_to_cache( + "https://snap.stanford.edu/data/email-Eu-core.txt.gz", "email-Eu-core.txt.gz", "email-Eu-core") + labels_path = _download_to_cache( + "https://snap.stanford.edu/data/email-Eu-core-department-labels.txt.gz", + "email-Eu-core-department-labels.txt.gz", "email-Eu-core labels") + pairs = np.loadtxt(edges_path, dtype=np.int64, ndmin=2) + src, dst = _undirected_unique(pairs[:, 0], pairs[:, 1]) + departments = np.loadtxt(labels_path, dtype=np.int64, ndmin=2) + department_of = dict(zip(departments[:, 0].tolist(), departments[:, 1].tolist())) + in_graph = np.union1d(src, dst) + return { + "name": "email-Eu-core", + "edges": _LazyEdgeList(src, dst), + "labels": {str(int(node)): int(department_of[int(node)]) for node in in_graph if int(node) in department_of}, + "num_nodes": int(len(in_graph)), + "num_edges": int(len(src)), + "num_classes": int(len(set(department_of.values()))), + "columns": "complex::reflexive::person", + "description": "E-mail network of a European research institution (SNAP): nodes are people, an edge " + "means at least one e-mail was exchanged, labels are the 42 departments.", + } - author_area = rng.integers(0, num_classes, size=num_authors) - labels = {f"author{i}": int(author_area[i]) for i in range(num_authors)} - author_edges = set() - author_paper_edges = [] +@_real("https://snap.stanford.edu/graphsage/ppi.zip", "W. Hamilton, R. Ying, J. Leskovec, GraphSAGE, NeurIPS 2017") +def load_ppi_large() -> Dict: + import json + import zipfile - for p in range(num_papers): - area = rng.integers(0, num_classes) - same_area = np.where(author_area == area)[0] - num_authors_per_paper = rng.integers(2, 5) - if len(same_area) >= num_authors_per_paper: - paper_authors = rng.choice(same_area, size=num_authors_per_paper, replace=False) - else: - paper_authors = rng.choice(num_authors, size=num_authors_per_paper, replace=False) + path = _download_to_cache("https://snap.stanford.edu/graphsage/ppi.zip", "graphsage_ppi.zip", "PPI (GraphSAGE)") + with zipfile.ZipFile(path) as archive: + graph = json.loads(archive.read(_find_zip_member(archive, "ppi-G.json"))) + class_map = json.loads(archive.read(_find_zip_member(archive, "ppi-class_map.json"))) + src = np.fromiter((link["source"] for link in graph["links"]), dtype=np.int64) + dst = np.fromiter((link["target"] for link in graph["links"]), dtype=np.int64) + src, dst = _undirected_unique(src, dst) + in_graph = np.union1d(src, dst) + label_matrix = np.array([class_map[str(int(node))] for node in in_graph], dtype=np.uint8) + return { + "name": "PPI (GraphSAGE)", + "edges": _LazyEdgeList(src, dst), + "labels": {}, + "multilabel": True, + "label_entities": [str(int(node)) for node in in_graph], + "label_matrix": label_matrix, + "num_nodes": int(len(in_graph)), + "num_edges": int(len(src)), + "num_classes": int(label_matrix.shape[1]), + "columns": "complex::reflexive::protein", + "description": "Protein-protein interaction graphs of 24 human tissues (GraphSAGE version): " + "56,688 proteins with at least one interaction, 121 gene-ontology labels. Multi-label " + "('label_matrix' / 'label_entities').", + } - for a in paper_authors: - author_paper_edges.append((f"author{a}", f"paper{p}")) - for i in range(len(paper_authors)): - for j in range(i + 1, len(paper_authors)): - a1, a2 = int(paper_authors[i]), int(paper_authors[j]) - author_edges.add((min(a1, a2), max(a1, a2))) +@_real("https://snap.stanford.edu/ogb/data/nodeproppred/arxiv.zip", "W. Hu et al., Open Graph Benchmark, NeurIPS 2020") +def load_ogbn_arxiv() -> Dict: + return _load_ogb_dataset( + name="ogb_arxiv", + display_name="ogbn-arxiv", + description="OGB arxiv citation network: 169,343 computer-science papers, 1.17M citations, " + "40 subject areas.", + zip_url="https://snap.stanford.edu/ogb/data/nodeproppred/arxiv.zip", + edge_csv_path_in_zip="arxiv/raw/edge.csv.gz", + expected_nodes=169_343, + expected_edges=1_166_243, + label_csv_path_in_zip="arxiv/raw/node-label.csv.gz", + num_classes=40, + columns="complex::reflexive::paper", + ) - edges = [f"author{i} author{j}" for i, j in author_edges] - edge_types_data = [f"{a} {p}" for a, p in author_paper_edges] +@_real("https://snap.stanford.edu/data/soc-redditHyperlinks-body.tsv") +def load_reddit_hyperlink() -> Dict: + import tempfile + import csv - np.savez(cache_path, - edges=np.array(edges), - label_keys=np.array(list(labels.keys())), - label_vals=np.array(list(labels.values())), - num_nodes=num_authors, num_edges=len(edges), - num_classes=num_classes, - edge_types=np.array(edge_types_data)) - - return { - "name": "DBLP", - "edges": edges, - "labels": labels, - "num_nodes": num_authors, - "num_edges": len(edges), - "num_classes": num_classes, - "columns": "complex::reflexive::author", - "description": "DBLP co-authorship network. 4 research areas.", - "is_heterogeneous": True, - } - - -def _generate_large_community_graph(name, display_name, description, num_nodes, num_edges, - num_classes, columns, seed, intra_prob=0.6): - _ensure_cache_dir() - cache_path = os.path.join(_CACHE_DIR, f"{name}.npz") - - if os.path.exists(cache_path): - data = np.load(cache_path, allow_pickle=True) - return { - "name": display_name, - "edges": data["edges"].tolist(), - "labels": dict(zip(data["label_keys"].tolist(), data["label_vals"].tolist())), - "num_nodes": int(data["num_nodes"]), - "num_edges": int(data["num_edges"]), - "num_classes": int(data["num_classes"]), - "columns": columns, - "description": description, - } - - sys.stderr.write(f"Generating {display_name} ({num_nodes:,} nodes, {num_edges:,} edges)...\n") - sys.stderr.flush() - - rng = np.random.default_rng(seed) - - community = rng.integers(0, num_classes, size=num_nodes) - - comm_members = {} - for c in range(num_classes): - comm_members[c] = np.where(community == c)[0] - - edge_set = set() - batch = max(num_edges // 20, 100000) - - while len(edge_set) < num_edges: - remaining = num_edges - len(edge_set) - gen_count = min(remaining * 2, batch * 2) - srcs = rng.integers(0, num_nodes, size=gen_count) - is_intra = rng.random(size=gen_count) < intra_prob - - for k in range(gen_count): - i = int(srcs[k]) - if is_intra[k]: - members = comm_members[community[i]] - j = int(members[rng.integers(0, len(members))]) - else: - j = int(rng.integers(0, num_nodes)) - if i != j: - edge_set.add((min(i, j), max(i, j))) - if len(edge_set) >= num_edges: - break - - if len(edge_set) % 500000 < batch: - sys.stderr.write(f"\r Generated {len(edge_set):,}/{num_edges:,} edges...") - sys.stderr.flush() - - sys.stderr.write(f"\r Generated {len(edge_set):,} edges total. Caching...\n") - sys.stderr.flush() - - prefix = name.replace("_", "")[:3] - edges = [f"{prefix}{i} {prefix}{j}" for i, j in edge_set] - labels = {f"{prefix}{i}": int(community[i]) for i in range(num_nodes)} - - np.savez(cache_path, - edges=np.array(edges), - label_keys=np.array(list(labels.keys())), - label_vals=np.array(list(labels.values())), - num_nodes=num_nodes, num_edges=len(edges), num_classes=num_classes) - - return { - "name": display_name, - "edges": edges, - "labels": labels, - "num_nodes": num_nodes, - "num_edges": len(edges), - "num_classes": num_classes, - "columns": columns, - "description": description, - } - - -def load_ogbn_arxiv() -> Dict: - return _generate_large_community_graph( - "ogbn_arxiv", - "ogbn-arxiv", - "OGB arxiv citation network. 169,343 CS papers, 40 subject areas.", - num_nodes=169343, - num_edges=1166243, - num_classes=40, - columns="complex::reflexive::paper", - seed=1001, - intra_prob=0.65, - ) - - -def load_flickr() -> Dict: - return _generate_large_community_graph( - "flickr", - "Flickr", - "Flickr image graph. 89,250 images, 7 categories. GraphSAINT benchmark.", - num_nodes=89250, - num_edges=899756, - num_classes=7, - columns="complex::reflexive::image", - seed=1002, - intra_prob=0.55, - ) - - -def load_ppi_large() -> Dict: - return _generate_large_community_graph( - "ppi_large", - "PPI-large", - "Large protein-protein interaction network. 56,944 proteins, 121 function labels (multi-label, using dominant label).", - num_nodes=56944, - num_edges=818716, - num_classes=121, - columns="complex::reflexive::protein", - seed=1003, - intra_prob=0.50, - ) - - -def load_yelp() -> Dict: - return _generate_large_community_graph( - "yelp", - "Yelp", - "Yelp review graph. 716,847 businesses, edges from shared reviewers. GraphSAINT benchmark.", - num_nodes=716847, - num_edges=6977410, - num_classes=100, - columns="complex::reflexive::business", - seed=1004, - intra_prob=0.55, - ) - - -def load_reddit_hyperlink() -> Dict: - import tempfile - import csv - - name = "reddit_hyperlink" - display_name = "Reddit Hyperlink Network" - description = "Reddit hyperlink network (SNAP). Subreddits as nodes, hyperlinks between posts as edges. ~55K nodes, ~858K edges." + name = "reddit_hyperlink" + display_name = "Reddit Hyperlink Network" + description = "Reddit hyperlink network (SNAP). Subreddits as nodes, hyperlinks between posts as edges. ~55K nodes, ~858K edges." _ensure_cache_dir() cache_path = os.path.join(_CACHE_DIR, f"{name}.npz") @@ -1156,7 +939,7 @@ def _load_ogb_dataset(name: str, display_name: str, description: str, num_edges = int(data["num_edges"]) labels = {} if "label_keys" in data and "label_vals" in data: - labels = dict(zip(data["label_keys"].tolist(), data["label_vals"].tolist())) + labels = {str(k): int(v) for k, v in zip(data["label_keys"].tolist(), data["label_vals"].tolist())} return { "name": display_name, "edges": _LazyEdgeList(src_arr, dst_arr), @@ -1244,8 +1027,8 @@ def _load_ogb_dataset(name: str, display_name: str, description: str, try: label_val = int(lline.split(",")[0]) label_keys.append(str(node_id)) - label_vals.append(str(label_val)) - labels[str(node_id)] = str(label_val) + label_vals.append(label_val) + labels[str(node_id)] = label_val except ValueError: continue except (KeyError, FileNotFoundError): @@ -1296,6 +1079,7 @@ def _load_ogb_dataset(name: str, display_name: str, description: str, } +@_real("https://snap.stanford.edu/ogb/data/nodeproppred/ogbn-products.zip", "W. Hu et al., Open Graph Benchmark, NeurIPS 2020") def load_ogbn_products() -> Dict: return _load_ogb_dataset( name="ogbn_products", @@ -1311,6 +1095,7 @@ def load_ogbn_products() -> Dict: ) +@_real("https://snap.stanford.edu/ogb/data/linkproppred/ogbl-citation2.zip", "W. Hu et al., Open Graph Benchmark, NeurIPS 2020") def load_ogbl_citation2() -> Dict: return _load_ogb_dataset( name="ogbl_citation2", @@ -1325,6 +1110,7 @@ def load_ogbl_citation2() -> Dict: ) +@_real("https://nrvis.com/download/data/soc/soc-twitter.zip") def load_twitter() -> Dict: import tempfile import zipfile @@ -1494,102 +1280,401 @@ def load_twitter() -> Dict: } -def load_reddit() -> Dict: - return _generate_product_graph( - "reddit", - "Reddit", - "Reddit post graph. Posts as nodes, shared commenters as edges.", - num_nodes=10000, - num_edges=100000, - num_classes=41, - seed=500, - ) +# --------------------------------------------------------------------------- +# Synthetic graphs +# +# pycleora <= 3.2 returned the graphs below from loaders named after real +# datasets (load_cora, load_ppi, load_flickr, ...). They are planted-partition +# random graphs that merely share the node / edge / class counts of those +# datasets; their labels are the planted communities. They are kept, under an +# explicit name, so that earlier experiments can be reproduced. +# --------------------------------------------------------------------------- + +def _generate_citation_graph(name, num_classes, seed=42): + rng = np.random.default_rng(seed) + + configs = { + "cora": {"nodes": 2708, "edges": 5429, "feat_dim": 1433}, + "citeseer": {"nodes": 3312, "edges": 4732, "feat_dim": 3703}, + "pubmed": {"nodes": 19717, "edges": 44338, "feat_dim": 500}, + } + + cfg = configs[name] + n = cfg["nodes"] + num_edges = cfg["edges"] + feat_dim = cfg["feat_dim"] + + community_assignments = rng.integers(0, num_classes, size=n) + labels = {} + for i in range(n): + labels[f"p{i}"] = int(community_assignments[i]) + + edge_set = set() + for i in range(n): + comm = community_assignments[i] + num_neighbors = rng.poisson(lam=num_edges * 2 / n) + num_neighbors = max(1, min(num_neighbors, 20)) + + for _ in range(num_neighbors): + if rng.random() < 0.7: + same_comm = np.where(community_assignments == comm)[0] + j = int(rng.choice(same_comm)) + else: + j = int(rng.integers(0, n)) + if i != j: + edge_set.add((min(i, j), max(i, j))) + + if len(edge_set) >= num_edges: + break + if len(edge_set) >= num_edges: + break + + while len(edge_set) < num_edges: + i = int(rng.integers(0, n)) + j = int(rng.integers(0, n)) + if i != j: + edge_set.add((min(i, j), max(i, j))) + + edges = [f"p{i} p{j}" for i, j in edge_set] + + features = rng.standard_normal((n, min(feat_dim, 64))).astype(np.float32) + for i in range(n): + comm = community_assignments[i] + features[i, comm % features.shape[1]] += 2.0 + + return edges, labels, features + + +def _generate_product_graph(name, display_name, description, num_nodes, num_edges, num_classes, seed): + _ensure_cache_dir() + cache_path = os.path.join(_CACHE_DIR, f"synthetic_{name}.npz") + + if os.path.exists(cache_path): + data = np.load(cache_path, allow_pickle=False) + return { + "name": display_name, + "edges": data["edges"].tolist(), + "labels": dict(zip(data["label_keys"].tolist(), data["label_vals"].tolist())), + "num_nodes": int(data["num_nodes"]), + "num_edges": int(data["num_edges"]), + "num_classes": int(data["num_classes"]), + "columns": "complex::reflexive::product", + "description": description, + } + + rng = np.random.default_rng(seed) + community = rng.integers(0, num_classes, size=num_nodes) + labels = {f"prod{i}": int(community[i]) for i in range(num_nodes)} + + edge_set = set() + for i in range(num_nodes): + comm = community[i] + num_nb = rng.poisson(lam=num_edges * 2 / num_nodes) + num_nb = max(1, min(num_nb, 50)) + for _ in range(num_nb): + if rng.random() < 0.65: + same = np.where(community == comm)[0] + j = int(rng.choice(same)) + else: + j = int(rng.integers(0, num_nodes)) + if i != j: + edge_set.add((min(i, j), max(i, j))) + if len(edge_set) >= num_edges: + break + if len(edge_set) >= num_edges: + break + + while len(edge_set) < num_edges: + i, j = int(rng.integers(0, num_nodes)), int(rng.integers(0, num_nodes)) + if i != j: + edge_set.add((min(i, j), max(i, j))) + + edges = [f"prod{i} prod{j}" for i, j in edge_set] + + np.savez(cache_path, + edges=np.array(edges), + label_keys=np.array(list(labels.keys())), + label_vals=np.array(list(labels.values())), + num_nodes=num_nodes, num_edges=len(edges), num_classes=num_classes) + + return { + "name": display_name, + "edges": edges, + "labels": labels, + "num_nodes": num_nodes, + "num_edges": len(edges), + "num_classes": num_classes, + "columns": "complex::reflexive::product", + "description": description, + } + + +def _generate_large_community_graph(name, display_name, description, num_nodes, num_edges, + num_classes, columns, seed, intra_prob=0.6): + _ensure_cache_dir() + cache_path = os.path.join(_CACHE_DIR, f"synthetic_{name}.npz") + + if os.path.exists(cache_path): + data = np.load(cache_path, allow_pickle=False) + return { + "name": display_name, + "edges": data["edges"].tolist(), + "labels": dict(zip(data["label_keys"].tolist(), data["label_vals"].tolist())), + "num_nodes": int(data["num_nodes"]), + "num_edges": int(data["num_edges"]), + "num_classes": int(data["num_classes"]), + "columns": columns, + "description": description, + } + + sys.stderr.write(f"Generating {display_name} ({num_nodes:,} nodes, {num_edges:,} edges)...\n") + sys.stderr.flush() + + rng = np.random.default_rng(seed) + + community = rng.integers(0, num_classes, size=num_nodes) + + comm_members = {} + for c in range(num_classes): + comm_members[c] = np.where(community == c)[0] + + edge_set = set() + batch = max(num_edges // 20, 100000) + + while len(edge_set) < num_edges: + remaining = num_edges - len(edge_set) + gen_count = min(remaining * 2, batch * 2) + srcs = rng.integers(0, num_nodes, size=gen_count) + is_intra = rng.random(size=gen_count) < intra_prob + + for k in range(gen_count): + i = int(srcs[k]) + if is_intra[k]: + members = comm_members[community[i]] + j = int(members[rng.integers(0, len(members))]) + else: + j = int(rng.integers(0, num_nodes)) + if i != j: + edge_set.add((min(i, j), max(i, j))) + if len(edge_set) >= num_edges: + break + + if len(edge_set) % 500000 < batch: + sys.stderr.write(f"\r Generated {len(edge_set):,}/{num_edges:,} edges...") + sys.stderr.flush() + + sys.stderr.write(f"\r Generated {len(edge_set):,} edges total. Caching...\n") + sys.stderr.flush() + + prefix = name.replace("_", "")[:3] + edges = [f"{prefix}{i} {prefix}{j}" for i, j in edge_set] + labels = {f"{prefix}{i}": int(community[i]) for i in range(num_nodes)} + + np.savez(cache_path, + edges=np.array(edges), + label_keys=np.array(list(labels.keys())), + label_vals=np.array(list(labels.values())), + num_nodes=num_nodes, num_edges=len(edges), num_classes=num_classes) + + return { + "name": display_name, + "edges": edges, + "labels": labels, + "num_nodes": num_nodes, + "num_edges": len(edges), + "num_classes": num_classes, + "columns": columns, + "description": description, + } + + +def _generate_coauthor_graph() -> Dict: + _ensure_cache_dir() + cache_path = os.path.join(_CACHE_DIR, "synthetic_dblp.npz") + + if os.path.exists(cache_path): + data = np.load(cache_path, allow_pickle=False) + return { + "name": "DBLP", + "edges": data["edges"].tolist(), + "labels": dict(zip(data["label_keys"].tolist(), data["label_vals"].tolist())), + "num_nodes": int(data["num_nodes"]), + "num_edges": int(data["num_edges"]), + "num_classes": int(data["num_classes"]), + "columns": "complex::reflexive::author", + "description": "DBLP co-authorship network. 4 research areas.", + "is_heterogeneous": True, + } + + rng = np.random.default_rng(400) + num_authors = 4057 + num_papers = 14328 + num_classes = 4 + + author_area = rng.integers(0, num_classes, size=num_authors) + labels = {f"author{i}": int(author_area[i]) for i in range(num_authors)} + + author_edges = set() + author_paper_edges = [] + + for p in range(num_papers): + area = rng.integers(0, num_classes) + same_area = np.where(author_area == area)[0] + num_authors_per_paper = rng.integers(2, 5) + if len(same_area) >= num_authors_per_paper: + paper_authors = rng.choice(same_area, size=num_authors_per_paper, replace=False) + else: + paper_authors = rng.choice(num_authors, size=num_authors_per_paper, replace=False) + + for a in paper_authors: + author_paper_edges.append((f"author{a}", f"paper{p}")) + + for i in range(len(paper_authors)): + for j in range(i + 1, len(paper_authors)): + a1, a2 = int(paper_authors[i]), int(paper_authors[j]) + author_edges.add((min(a1, a2), max(a1, a2))) + + edges = [f"author{i} author{j}" for i, j in author_edges] + + np.savez(cache_path, + edges=np.array(edges), + label_keys=np.array(list(labels.keys())), + label_vals=np.array(list(labels.values())), + num_nodes=num_authors, num_edges=len(edges), + num_classes=num_classes) + + return { + "name": "DBLP", + "edges": edges, + "labels": labels, + "num_nodes": num_authors, + "num_edges": len(edges), + "num_classes": num_classes, + "columns": "complex::reflexive::author", + "description": "DBLP co-authorship network. 4 research areas.", + "is_heterogeneous": True, + } + + + +_SYNTHETIC_SPECS = { + # name: (generator, arguments) + "cora": ("citation", dict(num_classes=7)), + "citeseer": ("citation", dict(num_classes=6)), + "pubmed": ("citation", dict(num_classes=3)), + "amazon_computers": ("product", dict(num_nodes=13752, num_edges=245861, num_classes=10, seed=100)), + "amazon_photo": ("product", dict(num_nodes=7650, num_edges=119081, num_classes=8, seed=200)), + "ppi": ("product", dict(num_nodes=3890, num_edges=76584, num_classes=50, seed=300)), + "reddit": ("product", dict(num_nodes=10000, num_edges=100000, num_classes=41, seed=500)), + "dblp": ("coauthor", dict()), + "ogbn_arxiv": ("community", dict(num_nodes=169343, num_edges=1166243, num_classes=40, + columns="complex::reflexive::paper", seed=1001, intra_prob=0.65)), + "flickr": ("community", dict(num_nodes=89250, num_edges=899756, num_classes=7, + columns="complex::reflexive::image", seed=1002, intra_prob=0.55)), + "ppi_large": ("community", dict(num_nodes=56944, num_edges=818716, num_classes=121, + columns="complex::reflexive::protein", seed=1003, intra_prob=0.50)), + "yelp": ("community", dict(num_nodes=716847, num_edges=6977410, num_classes=100, + columns="complex::reflexive::business", seed=1004, intra_prob=0.55)), +} + + +def list_synthetic() -> List[str]: + """Names accepted by :func:`load_synthetic`.""" + return list(_SYNTHETIC_SPECS) + + +def load_synthetic(name: str) -> Dict: + """A planted-partition random graph with the size of the named dataset. + + These graphs are NOT the datasets they are sized after: edges are random, with + a fixed share falling inside randomly assigned communities, and the labels are + those communities. Classification accuracy on them says how well a method + recovers planted communities, nothing about the real dataset. + """ + if name not in _SYNTHETIC_SPECS: + raise ValueError(f"Unknown synthetic graph: '{name}'. Available: {', '.join(_SYNTHETIC_SPECS)}") + kind, arguments = _SYNTHETIC_SPECS[name] + title = f"Synthetic planted-partition graph (sized like {name})" + note = "Synthetic planted-partition graph; labels are the planted communities." + if kind == "citation": + edges, labels, features = _generate_citation_graph(name, arguments["num_classes"]) + dataset = { + "edges": edges, + "labels": labels, + "num_nodes": len(labels), + "num_edges": len(edges), + "num_classes": arguments["num_classes"], + "columns": "complex::reflexive::paper", + "features": features, + } + elif kind == "product": + dataset = _generate_product_graph(name, title, note, **arguments) + elif kind == "coauthor": + dataset = _generate_coauthor_graph() + else: + dataset = _generate_large_community_graph(name, title, note, **arguments) + dataset["name"] = title + dataset["description"] = note + dataset["synthetic"] = True + dataset["source"] = "generated" + return dataset + + +_DATASETS = { + # name: (loader, nodes, edges, classes, description) + "karate_club": (load_karate_club, 34, 78, 2, "Zachary's Karate Club social network"), + "dolphins": (load_dolphins, 62, 159, 0, "Bottlenose dolphins social network (no labels)"), + "les_miserables": (load_les_miserables, 77, 254, 0, "Les Miserables character co-appearances (weighted, no labels)"), + "football": (load_football, 115, 613, 12, "American college football games, 12 conferences"), + "email_eu_core": (load_email_eu_core, 986, 16064, 42, "E-mail network of a research institution (SNAP), 42 departments"), + "cora": (load_cora, 2708, 5278, 7, "Cora citation network (Planetoid)"), + "citeseer": (load_citeseer, 3279, 4552, 6, "CiteSeer citation network (Planetoid)"), + "pubmed": (load_pubmed, 19717, 44324, 3, "PubMed diabetes citation network (Planetoid)"), + "ppi": (load_ppi, 3860, 37845, 50, "Protein-protein interaction network (node2vec), multi-label"), + "wikipedia_pos": (load_wikipedia_pos, 4777, 92295, 40, "Wikipedia word co-occurrence network (node2vec), weighted, multi-label"), + "amazon_photo": (load_amazon_photo, 7535, 119081, 8, "Amazon co-purchase graph (photo)"), + "amazon_computers": (load_amazon_computers, 13471, 245861, 10, "Amazon co-purchase graph (computers)"), + "ppi_large": (load_ppi_large, 56688, 793632, 121, "PPI graphs of 24 tissues (GraphSAGE), multi-label"), + "ogbn_arxiv": (load_ogbn_arxiv, 169343, 1166243, 40, "OGB arxiv citation network"), + "facebook": (load_facebook, 4039, 88234, 0, "Facebook ego networks (SNAP, ~4k nodes, ~88k edges)"), + "reddit_hyperlink": (load_reddit_hyperlink, 55863, 858490, 0, "Reddit hyperlink network (SNAP, ~55K subreddits, ~858K edges)"), + "roadnet": (load_roadnet, 1965206, 5533214, 0, "California road network (SNAP, ~2M nodes, ~5.5M edge lines)"), + "ogbn_products": (load_ogbn_products, 2449029, 61859140, 47, "OGB products co-purchasing graph (2.4M nodes, 62M edges, 47 classes)"), + "ogbl_citation2": (load_ogbl_citation2, 2927963, 30561187, 0, "OGB citation2 graph (2.9M nodes, 30M edges, link prediction)"), + "com_orkut": (load_com_orkut, 3072441, 117185083, 0, "Orkut online social network (SNAP, ~3M nodes, ~117M edges)"), + "livejournal": (load_livejournal, 4847571, 68993773, 0, "LiveJournal social network (SNAP, ~4.8M nodes, ~69M edges)"), + "twitter": (load_twitter, 41652230, 1468365182, 0, "Twitter-2010 follower network (~41.7M nodes, ~1.47B edges)"), + "com_friendster": (load_com_friendster, 65608366, 1806067135, 0, "Friendster online social network (SNAP, ~65.6M nodes, ~1.8B edges)"), +} + +# Names that pycleora <= 3.2 served with a synthetic stand-in and for which no +# stable public download of the real data exists. +_UNAVAILABLE = { + "flickr": "the GraphSAINT Flickr graph", + "yelp": "the GraphSAINT Yelp graph", + "dblp": "the DBLP heterogeneous graph", + "reddit": "the GraphSAGE Reddit graph", +} def list_datasets() -> List[Dict]: + """The real datasets that can be loaded with :func:`load_dataset`.""" return [ - {"name": "karate_club", "nodes": 34, "edges": 78, "classes": 2, - "description": "Zachary's Karate Club social network"}, - {"name": "dolphins", "nodes": 62, "edges": 159, "classes": 3, - "description": "Bottlenose dolphins social network"}, - {"name": "les_miserables", "nodes": 77, "edges": 254, "classes": 7, - "description": "Les Miserables character co-appearances"}, - {"name": "football", "nodes": 32, "edges": 117, "classes": 3, - "description": "American college football games"}, - {"name": "cora", "nodes": 2708, "edges": 5429, "classes": 7, - "description": "Cora citation network (ML papers)"}, - {"name": "citeseer", "nodes": 3312, "edges": 4732, "classes": 6, - "description": "CiteSeer citation network (CS papers)"}, - {"name": "pubmed", "nodes": 19717, "edges": 44338, "classes": 3, - "description": "PubMed diabetes citation network"}, - {"name": "amazon_computers", "nodes": 13752, "edges": 245861, "classes": 10, - "description": "Amazon co-purchase graph (computers)"}, - {"name": "amazon_photo", "nodes": 7650, "edges": 119081, "classes": 8, - "description": "Amazon co-purchase graph (photo)"}, - {"name": "ppi", "nodes": 3890, "edges": 76584, "classes": 50, - "description": "Protein-protein interaction network"}, - {"name": "dblp", "nodes": 4057, "edges": 14328, "classes": 4, - "description": "DBLP co-authorship network"}, - {"name": "reddit", "nodes": 10000, "edges": 100000, "classes": 41, - "description": "Reddit post network"}, - {"name": "facebook", "nodes": 4039, "edges": 88234, "classes": 0, - "description": "Facebook ego networks (SNAP, ~4k nodes, ~88k edges)"}, - {"name": "roadnet", "nodes": 1965206, "edges": 5533214, "classes": 0, - "description": "California road network (SNAP, ~2M nodes, ~5.5M edges)"}, - {"name": "livejournal", "nodes": 4847571, "edges": 68993773, "classes": 0, - "description": "LiveJournal social network (SNAP, ~4.8M nodes, ~69M edges)"}, - {"name": "com_orkut", "nodes": 3072441, "edges": 117185083, "classes": 0, - "description": "Orkut online social network (SNAP, ~3M nodes, ~117M edges)"}, - {"name": "com_friendster", "nodes": 65608366, "edges": 1806067135, "classes": 0, - "description": "Friendster online social network (SNAP, ~65.6M nodes, ~1.8B edges)"}, - {"name": "ogbn_arxiv", "nodes": 169343, "edges": 1166243, "classes": 40, - "description": "OGB arxiv citation network (169K nodes, 1.2M edges, 40 classes)"}, - {"name": "flickr", "nodes": 89250, "edges": 899756, "classes": 7, - "description": "Flickr image graph (89K nodes, 900K edges, 7 classes)"}, - {"name": "ppi_large", "nodes": 56944, "edges": 818716, "classes": 121, - "description": "Large PPI network (57K nodes, 819K edges, 121 classes)"}, - {"name": "yelp", "nodes": 716847, "edges": 6977410, "classes": 100, - "description": "Yelp review graph (717K nodes, 7M edges, 100 classes)"}, - {"name": "reddit_hyperlink", "nodes": 55863, "edges": 858490, "classes": 0, - "description": "Reddit hyperlink network (SNAP, ~55K subreddits, ~858K edges)"}, - {"name": "ogbn_products", "nodes": 2449029, "edges": 61859140, "classes": 47, - "description": "OGB products co-purchasing graph (2.4M nodes, 62M edges, 47 classes)"}, - {"name": "ogbl_citation2", "nodes": 2927963, "edges": 30561187, "classes": 0, - "description": "OGB citation2 graph (2.9M nodes, 30M edges, link prediction)"}, - {"name": "twitter", "nodes": 41652230, "edges": 1468365182, "classes": 0, - "description": "Twitter-2010 follower network (~41.7M nodes, ~1.47B edges)"}, + {"name": name, "nodes": nodes, "edges": edges, "classes": classes, + "description": description, "synthetic": False} + for name, (_, nodes, edges, classes, description) in _DATASETS.items() ] def load_dataset(name: str) -> Dict: - loaders = { - "karate_club": load_karate_club, - "dolphins": load_dolphins, - "les_miserables": load_les_miserables, - "football": load_football, - "cora": load_cora, - "citeseer": load_citeseer, - "pubmed": load_pubmed, - "amazon_computers": load_amazon_computers, - "amazon_photo": load_amazon_photo, - "ppi": load_ppi, - "dblp": load_dblp, - "reddit": load_reddit, - "facebook": load_facebook, - "roadnet": load_roadnet, - "livejournal": load_livejournal, - "com_orkut": load_com_orkut, - "com_friendster": load_com_friendster, - "ogbn_arxiv": load_ogbn_arxiv, - "flickr": load_flickr, - "ppi_large": load_ppi_large, - "yelp": load_yelp, - "reddit_hyperlink": load_reddit_hyperlink, - "ogbn_products": load_ogbn_products, - "ogbl_citation2": load_ogbl_citation2, - "twitter": load_twitter, - } - if name not in loaders: - available = ", ".join(loaders.keys()) - raise ValueError(f"Unknown dataset: '{name}'. Available: {available}") - return loaders[name]() + """Loads a real dataset by name (see :func:`list_datasets`).""" + if name in _DATASETS: + return _DATASETS[name][0]() + if name in _UNAVAILABLE: + raise ValueError( + f"'{name}' is not available: pycleora cannot download {_UNAVAILABLE[name]}. " + f"Earlier versions returned a synthetic random graph under this name; " + f"if that is what you want, call load_synthetic('{name}')." + ) + available = ", ".join(_DATASETS) + raise ValueError(f"Unknown dataset: '{name}'. Available: {available}") diff --git a/pycleora/hetero.py b/pycleora/hetero.py index fb902ed..03ccee7 100644 --- a/pycleora/hetero.py +++ b/pycleora/hetero.py @@ -1,6 +1,7 @@ import numpy as np from typing import Dict, List, Optional, Tuple, Union from .pycleora import SparseMatrix +from . import DEFAULT_FEATURE_DIM, DEFAULT_NUM_ITERATIONS, DEFAULT_WHITEN class HeteroGraph: @@ -88,15 +89,25 @@ def to_homogeneous_edges(self) -> List[str]: def embed_per_relation( self, - feature_dim: int = 256, - num_iterations: int = 40, + feature_dim: int = DEFAULT_FEATURE_DIM, + num_iterations: int = DEFAULT_NUM_ITERATIONS, propagation: str = "left", normalization: str = "l2", combine: str = "concat", seed: int = 0, - whiten: bool = True, + whiten: bool = DEFAULT_WHITEN, ) -> Tuple[Dict[str, SparseMatrix], Dict[str, np.ndarray], Optional[np.ndarray]]: - from . import embed + """Embeds every edge type on its own and optionally combines the results. + + Edge weights given to ``add_edge_type`` are used. ``combine="concat"`` + concatenates the per-relation vectors of every entity (zeros where an + entity does not take part in a relation). ``combine="mean"`` averages them; + because embeddings of separate runs live in unrelated coordinate systems, + every relation is first rotated onto the first one (orthogonal Procrustes + over the shared entities) so that the average is meaningful. + """ + from . import embed, _align_to_previous + from .io_utils import from_arrays graphs = {} embeddings = {} @@ -104,16 +115,10 @@ def embed_per_relation( for et_name, et_info in self._edge_types.items(): src_type = et_info["source_type"] tgt_type = et_info["target_type"] + sources = [f"{src_type}_{src}" for src, _ in et_info["edges"]] + targets = [f"{tgt_type}_{tgt}" for _, tgt in et_info["edges"]] - columns = f"complex::reflexive::node" - - edge_strs = [] - for src, tgt in et_info["edges"]: - s_id = f"{src_type}_{src}" - t_id = f"{tgt_type}_{tgt}" - edge_strs.append(f"{s_id} {t_id}") - - graph = SparseMatrix.from_iterator(iter(edge_strs), columns) + graph = from_arrays(sources, targets, weights=et_info["weights"]) emb = embed(graph, feature_dim=feature_dim, num_iterations=num_iterations, propagation=propagation, normalization=normalization, seed=seed, whiten=whiten) @@ -122,50 +127,43 @@ def embed_per_relation( embeddings[et_name] = emb combined = None - if combine == "concat" and len(embeddings) > 1: - all_entities = set() - for g in graphs.values(): - all_entities.update(g.entity_ids) - all_entities = sorted(all_entities) - entity_to_idx = {e: i for i, e in enumerate(all_entities)} - - parts = [] - for et_name in self._edge_types: - g = graphs[et_name] - emb = embeddings[et_name] - part = np.zeros((len(all_entities), emb.shape[1]), dtype=np.float32) - for i, eid in enumerate(g.entity_ids): - if eid in entity_to_idx: - part[entity_to_idx[eid]] = emb[i] - parts.append(part) - - combined = np.concatenate(parts, axis=1) - norms = np.linalg.norm(combined, axis=1, keepdims=True) - norms = np.maximum(norms, 1e-10) - combined = combined / norms - - elif combine == "mean" and len(embeddings) > 1: + if combine in ("concat", "mean") and len(embeddings) > 1: all_entities = set() for g in graphs.values(): all_entities.update(g.entity_ids) all_entities = sorted(all_entities) entity_to_idx = {e: i for i, e in enumerate(all_entities)} + rows_of = { + et_name: np.fromiter( + (entity_to_idx[eid] for eid in graphs[et_name].entity_ids), + dtype=np.int64, + count=graphs[et_name].num_entities, + ) + for et_name in self._edge_types + } + + if combine == "concat": + parts = [] + for et_name in self._edge_types: + emb = embeddings[et_name] + part = np.zeros((len(all_entities), emb.shape[1]), dtype=np.float32) + part[rows_of[et_name]] = emb + parts.append(part) + combined = np.concatenate(parts, axis=1) + else: + names = list(self._edge_types) + reference_ids = graphs[names[0]].entity_ids + reference = embeddings[names[0]] + combined = np.zeros((len(all_entities), feature_dim), dtype=np.float64) + counts = np.zeros(len(all_entities), dtype=np.float64) + for et_name in names: + emb = embeddings[et_name] + if et_name != names[0]: + emb = _align_to_previous(emb, graphs[et_name].entity_ids, reference, reference_ids) + combined[rows_of[et_name]] += emb + counts[rows_of[et_name]] += 1 + combined = (combined / np.maximum(counts, 1)[:, None]).astype(np.float32) - dim = feature_dim - combined = np.zeros((len(all_entities), dim), dtype=np.float64) - counts = np.zeros(len(all_entities), dtype=np.float64) - - for et_name in self._edge_types: - g = graphs[et_name] - emb = embeddings[et_name] - for i, eid in enumerate(g.entity_ids): - if eid in entity_to_idx: - idx = entity_to_idx[eid] - combined[idx] += emb[i].astype(np.float64) - counts[idx] += 1 - - counts = np.maximum(counts, 1) - combined = (combined / counts[:, None]).astype(np.float32) norms = np.linalg.norm(combined, axis=1, keepdims=True) norms = np.maximum(norms, 1e-10) combined = combined / norms @@ -175,11 +173,11 @@ def embed_per_relation( def embed_metapath( self, metapath: List[str], - feature_dim: int = 256, - num_iterations: int = 40, + feature_dim: int = DEFAULT_FEATURE_DIM, + num_iterations: int = DEFAULT_NUM_ITERATIONS, normalization: str = "l2", seed: int = 0, - whiten: bool = True, + whiten: bool = DEFAULT_WHITEN, ) -> Tuple[SparseMatrix, np.ndarray]: from . import embed diff --git a/pycleora/io_utils.py b/pycleora/io_utils.py index bf4f45b..1df556b 100644 --- a/pycleora/io_utils.py +++ b/pycleora/io_utils.py @@ -1,5 +1,12 @@ import numpy as np -from typing import Dict, List, Optional, Tuple +from typing import List, Optional, Tuple + + +def _upper_triangle(graph, markov_type: str = "left"): + """One entry per undirected edge (self-loops included): (rows, cols, values).""" + rows, cols, vals, _, _ = graph.to_sparse_csr(markov_type) + keep = rows <= cols + return rows[keep], cols[keep], vals[keep] def to_networkx(graph, embeddings: Optional[np.ndarray] = None): @@ -9,33 +16,39 @@ def to_networkx(graph, embeddings: Optional[np.ndarray] = None): raise ImportError("networkx is required for graph export. Install with: pip install networkx") G = nx.Graph() + entity_ids = graph.entity_ids - for i, eid in enumerate(graph.entity_ids): + for i, eid in enumerate(entity_ids): attrs = {"index": i} if embeddings is not None: attrs["embedding"] = embeddings[i].tolist() G.add_node(eid, **attrs) - rows, cols, vals, _, _ = graph.to_sparse_csr() - seen = set() - for r, c, v in zip(rows, cols, vals): - r, c = int(r), int(c) - edge_key = (min(r, c), max(r, c)) - if edge_key not in seen: - seen.add(edge_key) - G.add_edge(graph.entity_ids[r], graph.entity_ids[c], weight=float(v)) + rows, cols, vals = _upper_triangle(graph) + G.add_weighted_edges_from( + (entity_ids[r], entity_ids[c], v) + for r, c, v in zip(rows.tolist(), cols.tolist(), vals.tolist()) + ) return G -def from_networkx(G, columns: str = "complex::reflexive::node", hyperedge_trim_n: int = 16, num_workers=None): - from .pycleora import SparseMatrix - - edges = [] - for u, v in G.edges(): - edges.append(f"{u} {v}") +def from_networkx(G, columns: str = "complex::reflexive::node", hyperedge_trim_n: int = 16, num_workers=None, + weight: Optional[str] = None): + """Create a SparseMatrix from a networkx graph. - return SparseMatrix.from_iterator(iter(edges), columns, hyperedge_trim_n, num_workers) + Node names are converted with ``str``. ``weight`` optionally names the edge + attribute that holds the edge weight (edges without it count as 1). + """ + sources = [] + targets = [] + weights = [] if weight is not None else None + for u, v, data in G.edges(data=True): + sources.append(str(u)) + targets.append(str(v)) + if weights is not None: + weights.append(float(data.get(weight, 1.0))) + return from_arrays(sources, targets, weights=weights, columns=columns, num_workers=num_workers) def to_pyg_data(graph, embeddings: np.ndarray): @@ -104,7 +117,7 @@ def save_embeddings(graph, embeddings: np.ndarray, filepath: str, format: str = except ImportError: raise ImportError("pyarrow is required for parquet export. Install with: pip install pyarrow") - arrays = {"entity_id": graph.entity_ids} + arrays = {"entity_id": list(graph.entity_ids)} for i in range(embeddings.shape[1]): arrays[f"dim_{i}"] = embeddings[:, i].tolist() table = pa.table(arrays) @@ -115,7 +128,7 @@ def save_embeddings(graph, embeddings: np.ndarray, filepath: str, format: str = def load_embeddings(filepath: str, format: str = "npz") -> Tuple[np.ndarray, List[str]]: if format == "npz": - data = np.load(filepath, allow_pickle=True) + data = np.load(filepath, allow_pickle=False) return data["embeddings"], data["entity_ids"].tolist() elif format == "csv": import csv @@ -142,23 +155,64 @@ def load_embeddings(filepath: str, format: str = "npz") -> Tuple[np.ndarray, Lis raise ValueError(f"Unknown format: {format}. Use 'npz', 'csv', or 'tsv'.") +def _as_id_array(values, name: str): + """Node identifiers as an int64 array or a list of str.""" + array = np.asarray(values) + if array.ndim != 1: + raise ValueError(f"{name} must be 1-dimensional, got {array.ndim} dimension(s)") + if array.dtype.kind in "iu": + if array.dtype.kind == "u" and array.size and int(array.max()) > np.iinfo(np.int64).max: + return [str(v) for v in array.tolist()] + return np.ascontiguousarray(array, dtype=np.int64) + if array.dtype.kind == "b": + raise ValueError(f"{name} must hold node identifiers, got booleans") + return [str(v) for v in array.tolist()] + + +def from_arrays(src, dst, weights=None, columns: str = "complex::reflexive::node", num_workers=None): + """Create a SparseMatrix from two parallel arrays of node identifiers. + + ``src[i]`` and ``dst[i]`` are the two ends of edge ``i``. Integer arrays are + consumed directly, without building Python strings (the entity name of node + ``7`` is ``"7"``); anything else is converted with ``str``. ``weights`` + optionally holds one finite, non-negative weight per edge. + + With the default ``columns`` every edge is a two-entity hyperedge of a single + reflexive column, exactly like the line ``f"{src} {dst}"``. Pass two column + names (for example ``"user product"``) for a bipartite graph without + self-loops, like the line ``f"{src}\t{dst}"``. + """ + from .pycleora import SparseMatrix + + sources = _as_id_array(src, "src") + targets = _as_id_array(dst, "dst") + if len(sources) != len(targets): + raise ValueError(f"src has {len(sources)} element(s) but dst has {len(targets)}") + if isinstance(sources, list) != isinstance(targets, list): + # mixed integer / non-integer identifiers: treat both as names + if not isinstance(sources, list): + sources = [str(v) for v in sources.tolist()] + if not isinstance(targets, list): + targets = [str(v) for v in targets.tolist()] + if weights is not None: + weights = np.ascontiguousarray(weights, dtype=np.float32) + return SparseMatrix.from_edges(sources, targets, columns, weights, num_workers) + + def from_pandas(df, source_col: str, target_col: str, weight_col: Optional[str] = None, columns: str = "complex::reflexive::node", hyperedge_trim_n: int = 16, num_workers=None): """Create a SparseMatrix from a pandas DataFrame. - Each row becomes an edge from source_col to target_col. When weight_col is - provided, rows with NaN or zero weight are filtered out; the weight values - themselves are not encoded into the SparseMatrix (use embed_weighted for - weighted graph embedding). + Each row becomes an edge between ``source_col`` and ``target_col``; rows with a + missing endpoint are dropped. When ``weight_col`` is given its values are used + as edge weights (rows with a missing or zero weight are dropped). """ try: import pandas as pd except ImportError: raise ImportError("pandas is required for DataFrame import. Install with: pip install pandas") - from .pycleora import SparseMatrix - if source_col not in df.columns: raise ValueError(f"source_col '{source_col}' not found in DataFrame columns: {list(df.columns)}") if target_col not in df.columns: @@ -166,40 +220,40 @@ def from_pandas(df, source_col: str, target_col: str, weight_col: Optional[str] if weight_col is not None and weight_col not in df.columns: raise ValueError(f"weight_col '{weight_col}' not found in DataFrame columns: {list(df.columns)}") - edges = [] - for _, row in df.iterrows(): - src = row[source_col] - tgt = row[target_col] - if pd.isna(src) or pd.isna(tgt): - continue - if weight_col is not None: - w = row[weight_col] - if pd.isna(w) or float(w) == 0: - continue - edges.append(f"{src} {tgt}") - - if not edges: + keep = df[source_col].notna() & df[target_col].notna() + weights = None + if weight_col is not None: + weight_values = pd.to_numeric(df[weight_col], errors="coerce") + keep &= weight_values.notna() & (weight_values != 0) + weights = weight_values[keep].to_numpy(dtype=np.float32) + if not bool(keep.any()): raise ValueError("No valid edges found in DataFrame (all rows may have NaN values)") - return SparseMatrix.from_iterator(iter(edges), columns, hyperedge_trim_n, num_workers) + return from_arrays( + df.loc[keep, source_col].to_numpy(), + df.loc[keep, target_col].to_numpy(), + weights=weights, + columns=columns, + num_workers=num_workers, + ) def from_scipy_sparse(matrix, entity_ids: Optional[List[str]] = None, columns: str = "complex::reflexive::node", - hyperedge_trim_n: int = 16, num_workers=None): + hyperedge_trim_n: int = 16, num_workers=None, + use_weights: bool = False): """Create a SparseMatrix from a scipy sparse adjacency matrix. If entity_ids is None, uses stringified integer indices as node IDs. - The adjacency is treated as undirected: symmetric edge pairs are - deduplicated so each edge appears once. + The adjacency is treated as undirected: an edge is created between nodes i and + j if either (i, j) or (j, i) is stored, once. With ``use_weights=True`` the + stored values become edge weights (the larger of the two directions). """ try: import scipy.sparse except ImportError: raise ImportError("scipy is required for sparse matrix import. Install with: pip install scipy") - from .pycleora import SparseMatrix - if not scipy.sparse.issparse(matrix): raise ValueError("matrix must be a scipy sparse matrix") @@ -207,65 +261,84 @@ def from_scipy_sparse(matrix, entity_ids: Optional[List[str]] = None, raise ValueError(f"matrix must be square, got shape {matrix.shape}") n = matrix.shape[0] - if entity_ids is not None: - if len(entity_ids) != n: - raise ValueError(f"entity_ids has {len(entity_ids)} elements but matrix has {n} rows") - ids = [str(eid) for eid in entity_ids] - else: - ids = [str(i) for i in range(n)] + if entity_ids is not None and len(entity_ids) != n: + raise ValueError(f"entity_ids has {len(entity_ids)} elements but matrix has {n} rows") coo = matrix.tocoo() - seen = set() - edges = [] - for r, c in zip(coo.row, coo.col): - edge_key = (min(r, c), max(r, c)) - if edge_key not in seen: - seen.add(edge_key) - edges.append(f"{ids[r]} {ids[c]}") - - if not edges: + if coo.nnz == 0: raise ValueError("No edges found in the sparse matrix") - - return SparseMatrix.from_iterator(iter(edges), columns, hyperedge_trim_n, num_workers) + rows = coo.row.astype(np.int64) + cols = coo.col.astype(np.int64) + # One edge per unordered pair, in order of first appearance and with the + # orientation of that first appearance. + key = np.minimum(rows, cols) * n + np.maximum(rows, cols) + unique_keys, first_index, inverse = np.unique(key, return_index=True, return_inverse=True) + order = np.argsort(first_index, kind="stable") + picked = first_index[order] + weights = None + if use_weights: + strongest = np.zeros(len(unique_keys), dtype=np.float64) + np.maximum.at(strongest, inverse, np.abs(np.asarray(coo.data, dtype=np.float64))) + weights = strongest[order] + + return _from_index_edges(rows[picked], cols[picked], weights, entity_ids, columns, num_workers) + + +def _from_index_edges(low, high, weights, entity_ids, columns, num_workers): + if weights is not None: + keep = weights > 0 + low, high, weights = low[keep], high[keep], weights[keep] + if len(low) == 0: + raise ValueError("No edges with a positive weight found") + if entity_ids is None: + return from_arrays(low, high, weights=weights, columns=columns, num_workers=num_workers) + names = np.asarray([str(eid) for eid in entity_ids], dtype=object) + return from_arrays(names[low], names[high], weights=weights, columns=columns, num_workers=num_workers) def from_edge_list(edges: List, columns: str = "complex::reflexive::node", hyperedge_trim_n: int = 16, num_workers=None): """Create a SparseMatrix from a list of (source, target) or (source, target, weight) tuples. - Weight values in 3-tuples are accepted but not encoded into the SparseMatrix - (use embed_weighted for weighted graph embedding). + When the tuples carry weights they are used as edge weights (edges given as + pairs count as 1). """ - from .pycleora import SparseMatrix - if not edges: raise ValueError("edges list must not be empty") - edge_strs = [] + sources = [] + targets = [] + weights = [] + weighted = False for edge in edges: if len(edge) == 2: src, tgt = edge - edge_strs.append(f"{src} {tgt}") + weight = 1.0 elif len(edge) == 3: - src, tgt, _weight = edge - edge_strs.append(f"{src} {tgt}") + src, tgt, weight = edge + weighted = True else: raise ValueError(f"Each edge must be a (source, target) or (source, target, weight) tuple, got length {len(edge)}") + sources.append(str(src)) + targets.append(str(tgt)) + weights.append(float(weight)) - return SparseMatrix.from_iterator(iter(edge_strs), columns, hyperedge_trim_n, num_workers) + return from_arrays( + sources, targets, weights=weights if weighted else None, columns=columns, num_workers=num_workers + ) def from_numpy(adjacency_matrix, entity_ids: Optional[List[str]] = None, columns: str = "complex::reflexive::node", - hyperedge_trim_n: int = 16, num_workers=None): + hyperedge_trim_n: int = 16, num_workers=None, + use_weights: bool = False): """Create a SparseMatrix from a dense numpy adjacency matrix. If entity_ids is None, uses stringified integer indices as node IDs. The adjacency is treated as undirected: an edge is created between nodes i - and j if either (i,j) or (j,i) is nonzero. + and j if either (i,j) or (j,i) is nonzero. With ``use_weights=True`` the + values become edge weights (the larger magnitude of the two directions). """ - from .pycleora import SparseMatrix - if not isinstance(adjacency_matrix, np.ndarray): raise ValueError("adjacency_matrix must be a numpy ndarray") @@ -276,33 +349,24 @@ def from_numpy(adjacency_matrix, entity_ids: Optional[List[str]] = None, raise ValueError(f"adjacency_matrix must be square, got shape {adjacency_matrix.shape}") n = adjacency_matrix.shape[0] - if entity_ids is not None: - if len(entity_ids) != n: - raise ValueError(f"entity_ids has {len(entity_ids)} elements but matrix has {n} rows") - ids = [str(eid) for eid in entity_ids] - else: - ids = [str(i) for i in range(n)] - - edges = [] - for i in range(n): - for j in range(i, n): - if adjacency_matrix[i, j] != 0 or adjacency_matrix[j, i] != 0: - edges.append(f"{ids[i]} {ids[j]}") + if entity_ids is not None and len(entity_ids) != n: + raise ValueError(f"entity_ids has {len(entity_ids)} elements but matrix has {n} rows") - if not edges: + magnitude = np.abs(adjacency_matrix) + magnitude = np.triu(np.maximum(magnitude, magnitude.T)) + low, high = np.nonzero(magnitude) + if len(low) == 0: raise ValueError("No edges found in the adjacency matrix") + weights = magnitude[low, high].astype(np.float64) if use_weights else None - return SparseMatrix.from_iterator(iter(edges), columns, hyperedge_trim_n, num_workers) + return _from_index_edges(low.astype(np.int64), high.astype(np.int64), weights, entity_ids, columns, num_workers) def to_edge_list(graph) -> List[Tuple[str, str, float]]: - rows, cols, vals, _, _ = graph.to_sparse_csr() - seen = set() - result = [] - for r, c, v in zip(rows, cols, vals): - r, c = int(r), int(c) - edge_key = (min(r, c), max(r, c)) - if edge_key not in seen: - seen.add(edge_key) - result.append((graph.entity_ids[r], graph.entity_ids[c], float(v))) - return result + """One (source, target, transition probability) triple per undirected edge.""" + rows, cols, vals = _upper_triangle(graph) + entity_ids = graph.entity_ids + return [ + (entity_ids[r], entity_ids[c], v) + for r, c, v in zip(rows.tolist(), cols.tolist(), vals.tolist()) + ] diff --git a/pycleora/metrics.py b/pycleora/metrics.py index 0d25d03..a6333e7 100644 --- a/pycleora/metrics.py +++ b/pycleora/metrics.py @@ -1,407 +1,583 @@ -import numpy as np -from typing import List, Tuple, Optional, Dict, Callable - +"""Evaluation metrics for embeddings. -def link_prediction_scores( - graph, - embeddings: np.ndarray, - test_edges: List[Tuple[str, str]], - negative_edges: Optional[List[Tuple[str, str]]] = None, - num_negatives_per_positive: int = 50, -) -> Dict[str, float]: - index_map = {eid: i for i, eid in enumerate(graph.entity_ids)} - n = graph.num_entities +The module has two layers. - norms = np.linalg.norm(embeddings, axis=1, keepdims=True) - norms = np.maximum(norms, 1e-10) - normed = embeddings / norms +*Array-level metrics* take labels and scores and return numbers. They are the single +definition of every metric the library and its benchmark report: - pos_scores = [] - for a, b in test_edges: - ia, ib = index_map.get(a), index_map.get(b) - if ia is None or ib is None: - continue - pos_scores.append(float(np.dot(normed[ia], normed[ib]))) +* :func:`classification_metrics` - single-label node classification, +* :func:`multilabel_metrics` - multi-label node classification, +* :func:`ranking_metrics` - positions of the correct answer among candidates (MRR, Hits@k), +* :func:`retrieval_metrics` - top-k lists against sets of relevant items (Recall, NDCG, MAP), +* :func:`roc_auc`, :func:`average_precision` - binary scores, +* :func:`normalized_mutual_info`, :func:`adjusted_rand_index`, :func:`purity` - clusterings. - if not pos_scores: - raise ValueError("No valid positive edges found") +They need NumPy only and are tested against scikit-learn. - rng = np.random.default_rng(42) +*Convenience functions* (:func:`link_prediction_scores`, :func:`node_classification_scores`, +:func:`clustering_scores`, :func:`map_at_k`, :func:`ndcg_at_k`, :func:`silhouette_score`, +:func:`cross_validate`) take a graph and its embeddings and apply those metrics to a +simple, parameter-free use of the vectors (cosine similarity, nearest centroid, k-means). +""" - if negative_edges is not None: - neg_scores = [] - for a, b in negative_edges: - ia, ib = index_map.get(a), index_map.get(b) - if ia is None or ib is None: - continue - neg_scores.append(float(np.dot(normed[ia], normed[ib]))) - else: - neg_scores = [] - for _ in range(len(pos_scores) * num_negatives_per_positive): - i, j = rng.integers(0, n, size=2) - neg_scores.append(float(np.dot(normed[i], normed[j]))) - - pos_arr = np.array(pos_scores) - neg_arr = np.array(neg_scores) +import numpy as np +from typing import Callable, Dict, List, Optional, Sequence, Tuple + + +# ----------------------------------------------------------------------------- binary scores + + +def _average_ranks(values: np.ndarray) -> np.ndarray: + """Ranks starting at 1; tied values share the mean of their ranks.""" + order = np.argsort(values, kind="stable") + ordered = values[order] + starts = np.flatnonzero(np.concatenate([[True], ordered[1:] != ordered[:-1]])) + ends = np.concatenate([starts[1:], [len(values)]]) + group_rank = (starts + ends + 1) / 2.0 + ranks = np.empty(len(values), dtype=np.float64) + ranks[order] = np.repeat(group_rank, ends - starts) + return ranks + + +def roc_auc(labels: np.ndarray, scores: np.ndarray) -> float: + """Area under the ROC curve: the probability that a random positive scores higher + than a random negative (ties count one half). ``nan`` if one class is missing.""" + labels = np.asarray(labels).astype(bool).ravel() + scores = np.asarray(scores, dtype=np.float64).ravel() + positives = int(labels.sum()) + negatives = len(labels) - positives + if positives == 0 or negatives == 0: + return float("nan") + rank_sum = _average_ranks(scores)[labels].sum() + return float((rank_sum - positives * (positives + 1) / 2.0) / (positives * negatives)) + + +def average_precision(labels: np.ndarray, scores: np.ndarray) -> float: + """Average precision: the mean of the precision at every positive, taken over the + distinct score thresholds (the definition scikit-learn uses). ``nan`` without positives.""" + labels = np.asarray(labels).astype(bool).ravel() + scores = np.asarray(scores, dtype=np.float64).ravel() + positives = int(labels.sum()) + if positives == 0: + return float("nan") + order = np.argsort(-scores, kind="stable") + ordered = scores[order] + # last position of every group of equal scores + ends = np.flatnonzero(np.concatenate([ordered[1:] != ordered[:-1], [True]])) + true_positives = np.cumsum(labels[order])[ends] + precision = true_positives / (ends + 1.0) + recall_steps = np.diff(np.concatenate([[0], true_positives])) / positives + return float((precision * recall_steps).sum()) + + +# ----------------------------------------------------------------------------- classification + + +def _f1_from_counts(true_positive, predicted, actual): + denominator = predicted + actual + return np.where(denominator > 0, 2.0 * true_positive / np.maximum(denominator, 1), 0.0) + + +def classification_metrics(y_true: np.ndarray, scores: np.ndarray, top_k: Sequence[int] = (3, 5)) -> Dict[str, float]: + """Metrics of a single-label classifier. + + ``y_true`` holds class indices ``0..C-1`` and ``scores`` one column per class (any + monotone score: probabilities, logits or margins). + + * ``accuracy`` - share of correct predictions (equal to micro-F1 for single-label data); + * ``balanced_accuracy`` - mean recall over the classes that occur in ``y_true``; + * ``macro_f1`` / ``weighted_f1`` - F1 per class, averaged over the classes that occur in + the labels or the predictions, unweighted / weighted by class frequency; + * ``mcc`` - Matthews correlation coefficient (multi-class form); + * ``cohen_kappa`` - agreement beyond chance; + * ``top{k}_accuracy`` - the true class is among the ``k`` highest scores; + * ``macro_roc_auc`` / ``macro_average_precision`` - one-vs-rest, averaged over the + classes that have both positive and negative examples. + """ + y_true = np.asarray(y_true).ravel() + scores = np.asarray(scores) + count, num_classes = scores.shape + predicted = scores.argmax(axis=1) + confusion = np.bincount(y_true * num_classes + predicted, minlength=num_classes * num_classes) + confusion = confusion.reshape(num_classes, num_classes).astype(np.float64) + correct = np.diag(confusion) + actual = confusion.sum(axis=1) + predicted_count = confusion.sum(axis=0) + occurring = (actual + predicted_count) > 0 + f1 = _f1_from_counts(correct, predicted_count, actual) + + accuracy = correct.sum() / count + expected = (actual * predicted_count).sum() / count ** 2 + mcc_denominator = np.sqrt((count ** 2 - (predicted_count ** 2).sum()) * (count ** 2 - (actual ** 2).sum())) + result = { + "accuracy": float(accuracy), + "balanced_accuracy": float((correct[actual > 0] / actual[actual > 0]).mean()), + "macro_f1": float(f1[occurring].mean()), + "weighted_f1": float((f1 * actual).sum() / count), + "mcc": float((correct.sum() * count - (actual * predicted_count).sum()) / mcc_denominator) + if mcc_denominator > 0 else 0.0, + "cohen_kappa": float((accuracy - expected) / (1 - expected)) if expected < 1 else 0.0, + } + true_score = scores[np.arange(count), y_true] + better = (scores > true_score[:, None]).sum(axis=1) + for k in top_k: + if k < num_classes: + result[f"top{k}_accuracy"] = float((better < k).mean()) + aucs, precisions = [], [] + for label in np.flatnonzero((actual > 0) & (actual < count)): + aucs.append(roc_auc(y_true == label, scores[:, label])) + precisions.append(average_precision(y_true == label, scores[:, label])) + result["macro_roc_auc"] = float(np.mean(aucs)) if aucs else float("nan") + result["macro_average_precision"] = float(np.mean(precisions)) if precisions else float("nan") + return result + + +def _multilabel_f1(y_true: np.ndarray, predicted: np.ndarray) -> Tuple[float, float, float]: + """micro-, macro- and samples-F1 of 0/1 predictions.""" + true_positive = (y_true & predicted).sum(axis=0).astype(np.float64) + micro = _f1_from_counts(true_positive.sum(), predicted.sum(), y_true.sum()) + macro = _f1_from_counts(true_positive, predicted.sum(axis=0), y_true.sum(axis=0)).mean() + per_sample = _f1_from_counts((y_true & predicted).sum(axis=1), predicted.sum(axis=1), y_true.sum(axis=1)) + return float(micro), float(macro), float(per_sample.mean()) + + +def label_ranking_average_precision(y_true: np.ndarray, scores: np.ndarray) -> float: + """For every true label of a sample: the share of true labels among the labels ranked + at least as high; averaged over the labels of a sample, then over the samples that + have at least one true and one false label (others count 1, as in scikit-learn).""" + y_true = np.asarray(y_true).astype(bool) + scores = np.asarray(scores, dtype=np.float64) + total = 0.0 + for row in range(0, len(y_true), 4096): + truth, block = y_true[row:row + 4096], scores[row:row + 4096] + order = np.argsort(-block, axis=1, kind="stable") + sorted_scores = np.take_along_axis(block, order, axis=1) + sorted_truth = np.take_along_axis(truth, order, axis=1) + # for position p: the last position holding the same score (ties rank last) + last = np.empty(sorted_scores.shape, dtype=np.int64) + last[:, -1] = sorted_scores.shape[1] - 1 + for position in range(sorted_scores.shape[1] - 2, -1, -1): + same = sorted_scores[:, position] == sorted_scores[:, position + 1] + last[:, position] = np.where(same, last[:, position + 1], position) + true_until = np.take_along_axis(np.cumsum(sorted_truth, axis=1), last, axis=1) + precision = np.where(sorted_truth, true_until / (last + 1.0), 0.0) + labels_per_sample = truth.sum(axis=1) + informative = (labels_per_sample > 0) & (labels_per_sample < truth.shape[1]) + total += np.where(informative, precision.sum(axis=1) / np.maximum(labels_per_sample, 1), 1.0).sum() + return float(total / len(y_true)) + + +def multilabel_metrics(y_true: np.ndarray, scores: np.ndarray, threshold: float = 0.0) -> Dict[str, float]: + """Metrics of a multi-label classifier (``y_true`` and ``scores`` are ``[n, C]``). + + Decisions at the classifier's own threshold (``scores > threshold``): + ``micro_f1``, ``macro_f1``, ``samples_f1``, ``subset_accuracy``, ``hamming_loss``. + + ``micro_f1_known_count`` / ``macro_f1_known_count`` follow the protocol of the DeepWalk + and node2vec papers: every sample is assigned its ``k`` highest-scoring labels, where + ``k`` is its true number of labels. They are reported for comparability with that + literature; the number of labels is not available in practice. + + Threshold-free: ``micro_roc_auc``, ``macro_roc_auc``, ``micro_average_precision``, + ``macro_average_precision`` (labels without positives, or without negatives for the + AUC, are left out of the macro averages), ``label_ranking_average_precision`` and + ``precision_at_1`` (the highest-scoring label is a true one). + """ + y_true = np.asarray(y_true).astype(bool) + scores = np.asarray(scores, dtype=np.float64) + predicted = scores > threshold + micro, macro, samples = _multilabel_f1(y_true, predicted) + + order = np.argsort(-scores, axis=1, kind="stable") + position = np.empty_like(order) + np.put_along_axis(position, order, np.arange(scores.shape[1])[None, :], axis=1) + known_count = position < y_true.sum(axis=1, keepdims=True) + micro_known, macro_known, _ = _multilabel_f1(y_true, known_count) + + positives = y_true.sum(axis=0) + with_both = np.flatnonzero((positives > 0) & (positives < len(y_true))) + with_positives = np.flatnonzero(positives > 0) + top_label = order[:, 0] + return { + "micro_f1": micro, + "macro_f1": macro, + "samples_f1": samples, + "micro_f1_known_count": micro_known, + "macro_f1_known_count": macro_known, + "subset_accuracy": float((predicted == y_true).all(axis=1).mean()), + "hamming_loss": float((predicted != y_true).mean()), + "micro_roc_auc": roc_auc(y_true.ravel(), scores.ravel()), + "macro_roc_auc": float(np.mean([roc_auc(y_true[:, j], scores[:, j]) for j in with_both])) + if len(with_both) else float("nan"), + "micro_average_precision": average_precision(y_true.ravel(), scores.ravel()), + "macro_average_precision": float(np.mean([average_precision(y_true[:, j], scores[:, j]) for j in with_positives])) + if len(with_positives) else float("nan"), + "label_ranking_average_precision": label_ranking_average_precision(y_true, scores), + "precision_at_1": float(y_true[np.arange(len(y_true)), top_label].mean()), + } - all_scores = np.concatenate([pos_arr, neg_arr]) - all_labels = np.concatenate([np.ones(len(pos_arr)), np.zeros(len(neg_arr))]) - sorted_idx = np.argsort(-all_scores) - sorted_labels = all_labels[sorted_idx] +# ----------------------------------------------------------------------------- ranking - tp = np.cumsum(sorted_labels) - fp = np.cumsum(1 - sorted_labels) - tpr = tp / max(tp[-1], 1) - fpr = fp / max(fp[-1], 1) - auc = float(np.trapezoid(tpr, fpr)) if hasattr(np, 'trapezoid') else float(np.trapz(tpr, fpr)) - ranks = [] - for ps in pos_scores: - rank = int(np.sum(neg_arr >= ps)) + 1 - ranks.append(rank) - ranks = np.array(ranks, dtype=np.float64) - mrr = float(np.mean(1.0 / ranks)) +def ranks_among(target_scores: np.ndarray, candidate_scores: np.ndarray) -> np.ndarray: + """Rank (1 = best) of every target score among its own row of candidate scores. - hits_at_1 = float(np.mean(ranks <= 1)) - hits_at_3 = float(np.mean(ranks <= 3)) - hits_at_10 = float(np.mean(ranks <= 10)) - hits_at_50 = float(np.mean(ranks <= 50)) + A candidate with the same score as the target counts as half a place, so that a + constant scorer gets the middle rank instead of the best or the worst one. + ``nan`` candidates are ignored (they stand for candidates that do not exist). + """ + target = np.asarray(target_scores, dtype=np.float64)[:, None] + candidates = np.asarray(candidate_scores, dtype=np.float64) + return 1.0 + (candidates > target).sum(axis=1) + 0.5 * (candidates == target).sum(axis=1) - ap = float(np.mean(pos_arr > np.median(neg_arr))) - return { - "auc": auc, - "mrr": mrr, - "hits@1": hits_at_1, - "hits@3": hits_at_3, - "hits@10": hits_at_10, - "hits@50": hits_at_50, - "average_precision": ap, - "num_positive": len(pos_scores), - "num_negative": len(neg_scores), - "mean_positive_score": float(np.mean(pos_arr)), - "mean_negative_score": float(np.mean(neg_arr)), +def ranking_metrics(ranks: np.ndarray, ks: Sequence[int] = (1, 3, 10, 50, 100)) -> Dict[str, float]: + """Summary of the ranks of the correct answers (1 = best): mean reciprocal rank, + mean and median rank, and Hits@k (the share of answers ranked within the top ``k``).""" + ranks = np.asarray(ranks, dtype=np.float64) + result = { + "mrr": float((1.0 / ranks).mean()), + "mean_rank": float(ranks.mean()), + "median_rank": float(np.median(ranks)), } + for k in ks: + result[f"hits@{k}"] = float((ranks <= k).mean()) + return result + + +def retrieval_metrics(hits: np.ndarray, num_relevant: np.ndarray, ks: Sequence[int] = (10, 20, 50)) -> Dict[str, float]: + """Quality of top-k lists, averaged over queries. + + ``hits[q, r]`` tells whether the item at rank ``r`` (0 = first) of query ``q`` is + relevant and ``num_relevant[q]`` how many relevant items the query has in total. + + * ``recall@k`` - relevant items found in the top ``k`` / all relevant items; + * ``precision@k`` - relevant items in the top ``k`` / ``k``; + * ``hit_rate@k`` - at least one relevant item in the top ``k``; + * ``ndcg@k`` - discounted gain ``1 / log2(rank + 1)`` relative to the ideal list; + * ``map@k`` - mean of the precision at every relevant position, relative to + ``min(num_relevant, k)``. + """ + hits = np.asarray(hits).astype(bool) + num_relevant = np.asarray(num_relevant, dtype=np.float64) + width = hits.shape[1] + discount = 1.0 / np.log2(np.arange(width) + 2.0) + ideal = np.concatenate([[0.0], np.cumsum(discount)]) + found = np.cumsum(hits, axis=1) + precision_at = found / (np.arange(width) + 1.0) + result = {} + for k in ks: + if k > width: + continue + in_top = found[:, k - 1] + attainable = np.minimum(num_relevant, k) + result[f"recall@{k}"] = float((in_top / np.maximum(num_relevant, 1)).mean()) + result[f"precision@{k}"] = float((in_top / k).mean()) + result[f"hit_rate@{k}"] = float((in_top > 0).mean()) + gain = (hits[:, :k] * discount[:k]).sum(axis=1) + result[f"ndcg@{k}"] = float((gain / np.maximum(ideal[attainable.astype(np.int64)], 1e-12)).mean()) + result[f"map@{k}"] = float(((precision_at[:, :k] * hits[:, :k]).sum(axis=1) / np.maximum(attainable, 1)).mean()) + return result -def node_classification_scores( - graph, - embeddings: np.ndarray, - labels: Dict[str, int], - train_ratio: float = 0.8, - seed: int = 42, -) -> Dict[str, float]: - index_map = {eid: i for i, eid in enumerate(graph.entity_ids)} - - indices = [] - y = [] - for entity_id, label in labels.items(): - idx = index_map.get(entity_id) - if idx is not None: - indices.append(idx) - y.append(label) - - if len(indices) < 4: - raise ValueError(f"Need at least 4 labeled entities, got {len(indices)}") +# ----------------------------------------------------------------------------- clusterings - X = embeddings[indices] - y = np.array(y) - rng = np.random.default_rng(seed) - perm = rng.permutation(len(y)) - split = int(len(y) * train_ratio) - train_idx, test_idx = perm[:split], perm[split:] +def _contingency(a: np.ndarray, b: np.ndarray) -> np.ndarray: + _, a = np.unique(a, return_inverse=True) + _, b = np.unique(b, return_inverse=True) + width = int(b.max()) + 1 + return np.bincount(a * width + b, minlength=(int(a.max()) + 1) * width).reshape(-1, width).astype(np.float64) - if len(test_idx) == 0: - raise ValueError("Test set is empty, reduce train_ratio") - X_train, y_train = X[train_idx], y[train_idx] - X_test, y_test = X[test_idx], y[test_idx] - - classes = np.unique(y_train) - centroids = {} - for c in classes: - mask = y_train == c - centroids[c] = np.mean(X_train[mask], axis=0) - - norms_test = np.linalg.norm(X_test, axis=1, keepdims=True) - norms_test = np.maximum(norms_test, 1e-10) - X_test_normed = X_test / norms_test - - y_pred = [] - for i in range(len(X_test)): - best_sim = -2.0 - best_class = classes[0] - for c in classes: - c_norm = np.linalg.norm(centroids[c]) - if c_norm < 1e-10: - continue - sim = float(np.dot(X_test_normed[i], centroids[c] / c_norm)) - if sim > best_sim: - best_sim = sim - best_class = c - y_pred.append(best_class) - - y_pred = np.array(y_pred) - accuracy = float(np.mean(y_pred == y_test)) - - per_class_f1 = [] - for c in np.unique(y): - tp = np.sum((y_pred == c) & (y_test == c)) - fp = np.sum((y_pred == c) & (y_test != c)) - fn = np.sum((y_pred != c) & (y_test == c)) - precision = tp / max(tp + fp, 1) - recall = tp / max(tp + fn, 1) - f1 = 2 * precision * recall / max(precision + recall, 1e-10) - per_class_f1.append(f1) - - macro_f1 = float(np.mean(per_class_f1)) - - weights = [] - weighted_f1_sum = 0.0 - for i, c in enumerate(np.unique(y)): - w = np.sum(y_test == c) - weights.append(w) - weighted_f1_sum += per_class_f1[i] * w - weighted_f1 = float(weighted_f1_sum / max(sum(weights), 1)) +def normalized_mutual_info(labels_true: np.ndarray, labels_pred: np.ndarray) -> float: + """Mutual information of two labelings divided by the mean of their entropies.""" + table = _contingency(np.asarray(labels_true), np.asarray(labels_pred)) + total = table.sum() + rows, cols = table.sum(axis=1), table.sum(axis=0) + nonzero = table > 0 + mutual = (table[nonzero] / total * np.log(table[nonzero] * total / np.outer(rows, cols)[nonzero])).sum() + entropy = lambda counts: -(counts[counts > 0] / total * np.log(counts[counts > 0] / total)).sum() + denominator = (entropy(rows) + entropy(cols)) / 2 + return float(mutual / denominator) if denominator > 1e-12 else 0.0 - return { - "accuracy": accuracy, - "macro_f1": macro_f1, - "weighted_f1": weighted_f1, - "num_classes": len(classes), - "train_size": len(train_idx), - "test_size": len(test_idx), - } +def adjusted_rand_index(labels_true: np.ndarray, labels_pred: np.ndarray) -> float: + table = _contingency(np.asarray(labels_true), np.asarray(labels_pred)) + pairs = lambda counts: (counts * (counts - 1) / 2).sum() + total_pairs = pairs(np.array([table.sum()])) + both, in_true, in_pred = pairs(table), pairs(table.sum(axis=1)), pairs(table.sum(axis=0)) + expected = in_true * in_pred / max(total_pairs, 1) + denominator = (in_true + in_pred) / 2 - expected + return float((both - expected) / denominator) if abs(denominator) > 1e-10 else 0.0 -def clustering_scores( - embeddings: np.ndarray, - labels: np.ndarray, -) -> Dict[str, float]: - n = len(labels) - if n != embeddings.shape[0]: - raise ValueError(f"embeddings has {embeddings.shape[0]} rows but labels has {n} entries") - unique_labels = np.unique(labels) - k = len(unique_labels) +def purity(labels_true: np.ndarray, labels_pred: np.ndarray) -> float: + """Share of samples that belong to the most common true class of their cluster.""" + table = _contingency(np.asarray(labels_true), np.asarray(labels_pred)) + return float(table.max(axis=0).sum() / table.sum()) - norms = np.linalg.norm(embeddings, axis=1, keepdims=True) - norms = np.maximum(norms, 1e-10) - normed = embeddings / norms - - label_map = {l: i for i, l in enumerate(unique_labels)} - mapped_labels = np.array([label_map[l] for l in labels]) - - centroids = np.zeros((k, embeddings.shape[1])) - for i in range(k): - mask = mapped_labels == i - if np.sum(mask) > 0: - centroids[i] = np.mean(normed[mask], axis=0) - - sim_matrix = normed @ centroids.T - predicted = np.argmax(sim_matrix, axis=1) - - contingency = np.zeros((k, k), dtype=np.int64) - for i in range(n): - contingency[mapped_labels[i], predicted[i]] += 1 - - from itertools import permutations - if k <= 10: - best_acc = 0.0 - for perm in permutations(range(k)): - acc = sum(contingency[i, perm[i]] for i in range(k)) / n - if acc > best_acc: - best_acc = acc - purity = best_acc - else: - row_max = np.max(contingency, axis=1) - purity = float(np.sum(row_max) / n) - - a = np.zeros(n, dtype=np.int64) - b = np.zeros(n, dtype=np.int64) - for i in range(n): - a[i] = mapped_labels[i] - b[i] = predicted[i] - - nmi = _normalized_mutual_info(a, b, k) - - intra_sim = 0.0 - count = 0 - for i in range(k): - mask = mapped_labels == i - cluster_vecs = normed[mask] - if len(cluster_vecs) > 1: - sims = cluster_vecs @ cluster_vecs.T - n_c = len(cluster_vecs) - intra_sim += (np.sum(sims) - n_c) / max(n_c * (n_c - 1), 1) - count += 1 - avg_intra_similarity = float(intra_sim / max(count, 1)) - return { - "nmi": nmi, - "purity": purity, - "avg_intra_cluster_similarity": avg_intra_similarity, - "num_clusters": k, - } +# ----------------------------------------------------------------------------- helpers for the convenience functions -def map_at_k( - graph, - embeddings: np.ndarray, - test_edges: List[Tuple[str, str]], - k: int = 10, -) -> float: - index_map = {eid: i for i, eid in enumerate(graph.entity_ids)} +def _unit_rows(embeddings: np.ndarray) -> np.ndarray: norms = np.linalg.norm(embeddings, axis=1, keepdims=True) - norms = np.maximum(norms, 1e-10) - normed = embeddings / norms - - rows, cols, _, _, _ = graph.to_sparse_csr() - existing = set() - for r, c in zip(rows, cols): - existing.add((int(r), int(c))) - - aps = [] - queries = {} - for a, b in test_edges: - ia, ib = index_map.get(a), index_map.get(b) - if ia is not None and ib is not None: - queries.setdefault(ia, set()).add(ib) - - for src, true_targets in queries.items(): - sims = normed @ normed[src] - sims[src] = -2.0 - for other in range(len(sims)): - if (src, other) in existing and other not in true_targets: - sims[other] = -2.0 - top_k = np.argsort(sims)[::-1][:k] - - hits = 0 - ap_sum = 0.0 - for rank, idx in enumerate(top_k): - if idx in true_targets: - hits += 1 - ap_sum += hits / (rank + 1) - aps.append(ap_sum / min(len(true_targets), k)) - - return float(np.mean(aps)) if aps else 0.0 - - -def ndcg_at_k( - graph, - embeddings: np.ndarray, - test_edges: List[Tuple[str, str]], - k: int = 10, -) -> float: - index_map = {eid: i for i, eid in enumerate(graph.entity_ids)} - norms = np.linalg.norm(embeddings, axis=1, keepdims=True) - norms = np.maximum(norms, 1e-10) - normed = embeddings / norms + return embeddings / np.maximum(norms, 1e-10) - queries = {} - for a, b in test_edges: - ia, ib = index_map.get(a), index_map.get(b) - if ia is not None and ib is not None: - queries.setdefault(ia, set()).add(ib) - rows, cols, _, _, _ = graph.to_sparse_csr() - existing = set() - for r, c in zip(rows, cols): - existing.add((int(r), int(c))) +def _index_map(graph) -> Dict[str, int]: + return {entity_id: index for index, entity_id in enumerate(graph.entity_ids)} - ndcgs = [] - for src, true_targets in queries.items(): - sims = normed @ normed[src] - sims[src] = -2.0 - for other in range(len(sims)): - if (src, other) in existing and other not in true_targets: - sims[other] = -2.0 - top_k = np.argsort(sims)[::-1][:k] - dcg = 0.0 - for rank, idx in enumerate(top_k): - if idx in true_targets: - dcg += 1.0 / np.log2(rank + 2) +def _pairs_to_indices(index_map: Dict[str, int], pairs) -> np.ndarray: + """Index pairs of the edges whose two entities are both known.""" + rows = [(index_map[a], index_map[b]) for a, b in pairs if a in index_map and b in index_map] + return np.asarray(rows, dtype=np.int64).reshape(-1, 2) - ideal_hits = min(len(true_targets), k) - idcg = sum(1.0 / np.log2(r + 2) for r in range(ideal_hits)) - ndcgs.append(dcg / max(idcg, 1e-10)) +def _spherical_kmeans(unit_vectors: np.ndarray, num_clusters: int, seed: int = 0, restarts: int = 5, + iterations: int = 50) -> np.ndarray: + """k-means on the unit sphere (cosine similarity), k-means++ seeding, best of ``restarts``.""" + rng = np.random.default_rng(seed) + count = len(unit_vectors) + best_assignment, best_quality = None, -np.inf + for _ in range(restarts): + centres = [unit_vectors[rng.integers(count)]] + distance = 1.0 - unit_vectors @ centres[0] + for _ in range(1, num_clusters): + weights = np.maximum(distance, 0) ** 2 + choice = rng.choice(count, p=weights / weights.sum()) if weights.sum() > 0 else rng.integers(count) + centres.append(unit_vectors[choice]) + distance = np.minimum(distance, 1.0 - unit_vectors @ centres[-1]) + centres = np.array(centres) + assignment = None + for _ in range(iterations): + similarity = unit_vectors @ centres.T + new_assignment = similarity.argmax(axis=1) + if assignment is not None and (new_assignment == assignment).all(): + break + assignment = new_assignment + sums = np.zeros_like(centres) + np.add.at(sums, assignment, unit_vectors) + empty = np.linalg.norm(sums, axis=1) < 1e-10 + sums[empty] = unit_vectors[rng.integers(count, size=int(empty.sum()))] + centres = _unit_rows(sums) + quality = float((unit_vectors @ centres.T).max(axis=1).sum()) + if quality > best_quality: + best_assignment, best_quality = assignment, quality + return best_assignment + + +def _nearest_centroid(train_x, train_y, test_x) -> np.ndarray: + """Predicts, for every test vector, the class whose mean training vector is most + similar (cosine).""" + classes = np.unique(train_y) + centroids = np.stack([train_x[train_y == c].mean(axis=0) for c in classes]) + return classes[(_unit_rows(test_x) @ _unit_rows(centroids).T).argmax(axis=1)] + + +def _label_scores(y_true: np.ndarray, y_pred: np.ndarray) -> Dict[str, float]: + """accuracy / macro-F1 / weighted-F1 of hard predictions, through + :func:`classification_metrics`.""" + classes, encoded = np.unique(np.concatenate([y_true, y_pred]), return_inverse=True) + truth, predicted = encoded[:len(y_true)], encoded[len(y_true):] + one_hot = np.zeros((len(truth), len(classes))) + one_hot[np.arange(len(truth)), predicted] = 1.0 + return classification_metrics(truth, one_hot, top_k=()) + + +# ----------------------------------------------------------------------------- convenience functions - return float(np.mean(ndcgs)) if ndcgs else 0.0 +def link_prediction_scores( + graph, + embeddings: np.ndarray, + test_edges: List[Tuple[str, str]], + negative_edges: Optional[List[Tuple[str, str]]] = None, + num_negatives_per_positive: int = 50, +) -> Dict[str, float]: + """Scores held-out edges against non-edges by cosine similarity. + + Without ``negative_edges``, ``num_negatives_per_positive`` random pairs per test edge + are drawn (pairs of an entity with itself and edges of ``graph`` are excluded). + ``mrr`` and ``hits@k`` rank every test edge among *all* negative pairs. + """ + index_map = _index_map(graph) + unit = _unit_rows(np.asarray(embeddings, dtype=np.float32)) + positives = _pairs_to_indices(index_map, test_edges) + if len(positives) == 0: + raise ValueError("No valid positive edges found") -def adjusted_rand_index(labels_true: np.ndarray, labels_pred: np.ndarray) -> float: - n = len(labels_true) - classes_true = np.unique(labels_true) - classes_pred = np.unique(labels_pred) - contingency = np.zeros((len(classes_true), len(classes_pred)), dtype=np.int64) + if negative_edges is not None: + negatives = _pairs_to_indices(index_map, negative_edges) + else: + rng = np.random.default_rng(42) + count = graph.num_entities + indptr, indices, _ = graph.to_csr() + edge_keys = np.repeat(np.arange(count, dtype=np.int64), np.diff(indptr)) * count + indices + wanted = len(positives) * num_negatives_per_positive + drawn = rng.integers(0, count, size=(2 * wanted + 16, 2)) + keep = (drawn[:, 0] != drawn[:, 1]) & ~np.isin(drawn[:, 0] * count + drawn[:, 1], edge_keys) + negatives = drawn[keep][:wanted] + if len(negatives) == 0: + raise ValueError("No valid negative edges found") + + score = lambda pairs: np.einsum("ij,ij->i", unit[pairs[:, 0]], unit[pairs[:, 1]]).astype(np.float64) + positive_scores, negative_scores = score(positives), score(negatives) + labels = np.concatenate([np.ones(len(positive_scores), bool), np.zeros(len(negative_scores), bool)]) + all_scores = np.concatenate([positive_scores, negative_scores]) + ordered_negatives = np.sort(negative_scores) + above = len(ordered_negatives) - np.searchsorted(ordered_negatives, positive_scores, side="right") + equal = np.searchsorted(ordered_negatives, positive_scores, side="right") - \ + np.searchsorted(ordered_negatives, positive_scores, side="left") + summary = ranking_metrics(1.0 + above + 0.5 * equal, ks=(1, 3, 10, 50)) + return { + "auc": roc_auc(labels, all_scores), + "mrr": summary["mrr"], + "hits@1": summary["hits@1"], + "hits@3": summary["hits@3"], + "hits@10": summary["hits@10"], + "hits@50": summary["hits@50"], + "average_precision": average_precision(labels, all_scores), + "num_positive": len(positive_scores), + "num_negative": len(negative_scores), + "mean_positive_score": float(positive_scores.mean()), + "mean_negative_score": float(negative_scores.mean()), + } - true_map = {c: i for i, c in enumerate(classes_true)} - pred_map = {c: i for i, c in enumerate(classes_pred)} - for i in range(n): - contingency[true_map[labels_true[i]], pred_map[labels_pred[i]]] += 1 +def node_classification_scores( + graph, + embeddings: np.ndarray, + labels: Dict[str, int], + train_ratio: float = 0.8, + seed: int = 42, +) -> Dict[str, float]: + """Nearest-centroid classification of the labelled entities on one random split. + + A quick, training-free check of how well the classes separate; see + ``benchmarks/`` for the protocol with trained probes. + """ + index_map = _index_map(graph) + known = [(index_map[entity], label) for entity, label in labels.items() if entity in index_map] + if len(known) < 4: + raise ValueError(f"Need at least 4 labeled entities, got {len(known)}") + features = np.asarray(embeddings)[[index for index, _ in known]] + targets = np.array([label for _, label in known]) + + order = np.random.default_rng(seed).permutation(len(targets)) + split = int(len(targets) * train_ratio) + train, test = order[:split], order[split:] + if len(test) == 0: + raise ValueError("Test set is empty, reduce train_ratio") + predicted = _nearest_centroid(features[train], targets[train], features[test]) + scores = _label_scores(targets[test], predicted) + return { + "accuracy": scores["accuracy"], + "macro_f1": scores["macro_f1"], + "weighted_f1": scores["weighted_f1"], + "num_classes": len(np.unique(targets[train])), + "train_size": len(train), + "test_size": len(test), + } - sum_comb_c = sum(int(nij) * (int(nij) - 1) // 2 for row in contingency for nij in row) - sum_comb_a = sum(int(ai) * (int(ai) - 1) // 2 for ai in contingency.sum(axis=1)) - sum_comb_b = sum(int(bj) * (int(bj) - 1) // 2 for bj in contingency.sum(axis=0)) - total_comb = n * (n - 1) // 2 - expected = sum_comb_a * sum_comb_b / max(total_comb, 1) - max_index = (sum_comb_a + sum_comb_b) / 2 - denom = max_index - expected +def clustering_scores(embeddings: np.ndarray, labels: np.ndarray, seed: int = 0) -> Dict[str, float]: + """Clusters the embeddings (spherical k-means, as many clusters as there are classes) + and compares the clusters with the classes: ``nmi``, ``ari`` and ``purity``. + + ``avg_intra_cluster_similarity`` is the mean cosine similarity of pairs of vectors + of the same class. + """ + labels = np.asarray(labels) + if len(labels) != embeddings.shape[0]: + raise ValueError(f"embeddings has {embeddings.shape[0]} rows but labels has {len(labels)} entries") + unit = _unit_rows(np.asarray(embeddings, dtype=np.float64)) + classes, encoded = np.unique(labels, return_inverse=True) + clusters = _spherical_kmeans(unit, len(classes), seed=seed) + + # mean pairwise cosine within a class, from the norm of the class sum + sums = np.zeros((len(classes), unit.shape[1])) + np.add.at(sums, encoded, unit) + sizes = np.bincount(encoded) + several = sizes > 1 + within = ((sums[several] ** 2).sum(axis=1) - sizes[several]) / (sizes[several] * (sizes[several] - 1)) + return { + "nmi": normalized_mutual_info(encoded, clusters), + "ari": adjusted_rand_index(encoded, clusters), + "purity": purity(encoded, clusters), + "avg_intra_cluster_similarity": float(within.mean()) if several.any() else 0.0, + "num_clusters": len(classes), + } - if abs(denom) < 1e-10: - return 0.0 - return float((sum_comb_c - expected) / denom) +def _top_k_hits(graph, embeddings: np.ndarray, test_edges, k: int) -> Tuple[np.ndarray, np.ndarray]: + """For every source entity of the test edges: which of its ``k`` nearest entities + (cosine; the entity itself and its neighbours in ``graph`` excluded, unless they are + test targets) are test targets, and how many test targets it has.""" + index_map = _index_map(graph) + pairs = _pairs_to_indices(index_map, test_edges) + if len(pairs) == 0: + return np.zeros((0, k), dtype=bool), np.zeros(0) + unit = _unit_rows(np.asarray(embeddings, dtype=np.float32)) + count = graph.num_entities + indptr, indices, _ = graph.to_csr() + sources, inverse = np.unique(pairs[:, 0], return_inverse=True) + relevant = np.zeros((len(sources), count), dtype=bool) + relevant[inverse, pairs[:, 1]] = True + width = min(k, count) + hits = np.zeros((len(sources), k), dtype=bool) + block = max(1, (1 << 26) // max(count, 1)) + for start in range(0, len(sources), block): + rows = sources[start:start + block] + similarity = unit[rows] @ unit.T + for local, source in enumerate(rows): + similarity[local, indices[indptr[source]:indptr[source + 1]]] = -2.0 + similarity[np.arange(len(rows)), rows] = -2.0 + truth = relevant[start:start + block] + similarity[truth] = (unit[rows] @ unit.T)[truth] + top = np.argpartition(-similarity, width - 1, axis=1)[:, :width] + top = np.take_along_axis(top, np.argsort(-np.take_along_axis(similarity, top, axis=1), axis=1, kind="stable"), axis=1) + hits[start:start + block, :width] = np.take_along_axis(truth, top, axis=1) + return hits, relevant.sum(axis=1) + + +def map_at_k(graph, embeddings: np.ndarray, test_edges: List[Tuple[str, str]], k: int = 10) -> float: + hits, num_relevant = _top_k_hits(graph, embeddings, test_edges, k) + return retrieval_metrics(hits, num_relevant, ks=(k,))[f"map@{k}"] if len(hits) else 0.0 + + +def ndcg_at_k(graph, embeddings: np.ndarray, test_edges: List[Tuple[str, str]], k: int = 10) -> float: + hits, num_relevant = _top_k_hits(graph, embeddings, test_edges, k) + return retrieval_metrics(hits, num_relevant, ks=(k,))[f"ndcg@{k}"] if len(hits) else 0.0 -def silhouette_score(embeddings: np.ndarray, labels: np.ndarray) -> float: - n = len(labels) - if n < 2: - return 0.0 - unique_labels = np.unique(labels) - if len(unique_labels) < 2: +def silhouette_score(embeddings: np.ndarray, labels: np.ndarray) -> float: + """Mean silhouette coefficient with the cosine distance. + + The mean distance of a vector to a group of unit vectors follows from the sum of + the group, so no pairwise distance matrix is built.""" + labels = np.asarray(labels) + count = len(labels) + classes, encoded = np.unique(labels, return_inverse=True) + if count < 2 or len(classes) < 2: return 0.0 - - norms = np.linalg.norm(embeddings, axis=1, keepdims=True) - norms = np.maximum(norms, 1e-10) - normed = embeddings / norms - dist_matrix = 1.0 - normed @ normed.T - - silhouettes = [] - for i in range(n): - own_label = labels[i] - own_mask = labels == own_label - own_count = np.sum(own_mask) - 1 - - if own_count <= 0: - silhouettes.append(0.0) - continue - - a_i = np.sum(dist_matrix[i, own_mask]) / own_count - - b_i = np.inf - for label in unique_labels: - if label == own_label: - continue - other_mask = labels == label - other_count = np.sum(other_mask) - if other_count > 0: - avg_dist = np.sum(dist_matrix[i, other_mask]) / other_count - b_i = min(b_i, avg_dist) - - if b_i == np.inf: - silhouettes.append(0.0) - else: - s_i = (b_i - a_i) / max(a_i, b_i, 1e-10) - silhouettes.append(s_i) - - return float(np.mean(silhouettes)) + unit = _unit_rows(np.asarray(embeddings, dtype=np.float64)) + sums = np.zeros((len(classes), unit.shape[1])) + np.add.at(sums, encoded, unit) + sizes = np.bincount(encoded).astype(np.float64) + similarity_sum = unit @ sums.T # [n, classes]: sum of cosines to every member of the class + own = similarity_sum[np.arange(count), encoded] + own_size = sizes[encoded] + with np.errstate(divide="ignore", invalid="ignore"): + within = 1.0 - (own - 1.0) / (own_size - 1.0) + other = 1.0 - similarity_sum / sizes[None, :] + other[np.arange(count), encoded] = np.inf + nearest = other.min(axis=1) + silhouette = np.where(own_size > 1, (nearest - within) / np.maximum(np.maximum(within, nearest), 1e-10), 0.0) + return float(silhouette.mean()) def cross_validate( @@ -412,131 +588,46 @@ def cross_validate( eval_fn: Optional[Callable] = None, seed: int = 42, ) -> Dict[str, float]: - index_map = {eid: i for i, eid in enumerate(graph.entity_ids)} - valid_entities = [(eid, label) for eid, label in labels.items() if eid in index_map] + index_map = _index_map(graph) + valid_entities = [(entity, label) for entity, label in labels.items() if entity in index_map] if k_folds < 2: raise ValueError(f"k_folds must be >= 2, got {k_folds}") if len(valid_entities) < k_folds: raise ValueError(f"Not enough labeled entities ({len(valid_entities)}) for {k_folds}-fold CV") - rng = np.random.default_rng(seed) - perm = rng.permutation(len(valid_entities)) + order = np.random.default_rng(seed).permutation(len(valid_entities)) fold_size = len(valid_entities) // k_folds - - all_accuracies = [] - all_f1s = [] - + accuracies, f1s = [], [] for fold in range(k_folds): - test_start = fold * fold_size - test_end = test_start + fold_size if fold < k_folds - 1 else len(valid_entities) - test_indices = set(perm[test_start:test_end].tolist()) - - train_labels = {} - test_labels = {} - for idx, (eid, label) in enumerate(valid_entities): - if idx in test_indices: - test_labels[eid] = label - else: - train_labels[eid] = label - - if eval_fn: - scores = eval_fn(graph, embeddings, train_labels, test_labels) - else: - scores = _simple_classify(graph, embeddings, train_labels, test_labels) - - all_accuracies.append(scores.get("accuracy", 0.0)) - all_f1s.append(scores.get("macro_f1", 0.0)) + start = fold * fold_size + end = start + fold_size if fold < k_folds - 1 else len(valid_entities) + test_positions = set(order[start:end].tolist()) + train_labels = {e: l for i, (e, l) in enumerate(valid_entities) if i not in test_positions} + test_labels = {e: l for i, (e, l) in enumerate(valid_entities) if i in test_positions} + evaluate = eval_fn or _simple_classify + scores = evaluate(graph, embeddings, train_labels, test_labels) + accuracies.append(scores.get("accuracy", 0.0)) + f1s.append(scores.get("macro_f1", 0.0)) return { - "mean_accuracy": float(np.mean(all_accuracies)), - "std_accuracy": float(np.std(all_accuracies)), - "mean_macro_f1": float(np.mean(all_f1s)), - "std_macro_f1": float(np.std(all_f1s)), - "fold_accuracies": all_accuracies, + "mean_accuracy": float(np.mean(accuracies)), + "std_accuracy": float(np.std(accuracies)), + "mean_macro_f1": float(np.mean(f1s)), + "std_macro_f1": float(np.std(f1s)), + "fold_accuracies": accuracies, "k_folds": k_folds, } def _simple_classify(graph, embeddings, train_labels, test_labels): - index_map = {eid: i for i, eid in enumerate(graph.entity_ids)} - classes = sorted(set(train_labels.values())) - centroids = {} - for c in classes: - vecs = [embeddings[index_map[eid]] for eid, label in train_labels.items() if label == c and eid in index_map] - if vecs: - centroids[c] = np.mean(vecs, axis=0) - - correct = 0 - total = 0 - y_true = [] - y_pred = [] - for eid, true_label in test_labels.items(): - idx = index_map.get(eid) - if idx is None: - continue - vec = embeddings[idx] - norm_v = np.linalg.norm(vec) - if norm_v < 1e-10: - continue - vec_n = vec / norm_v - - best_sim = -2 - best_class = classes[0] - for c, centroid in centroids.items(): - cn = np.linalg.norm(centroid) - if cn < 1e-10: - continue - sim = float(np.dot(vec_n, centroid / cn)) - if sim > best_sim: - best_sim = sim - best_class = c - - y_true.append(true_label) - y_pred.append(best_class) - total += 1 - if best_class == true_label: - correct += 1 - - accuracy = correct / max(total, 1) - - per_class_f1 = [] - all_classes = sorted(set(y_true + y_pred)) - y_true_arr = np.array(y_true) - y_pred_arr = np.array(y_pred) - for c in all_classes: - tp = np.sum((y_pred_arr == c) & (y_true_arr == c)) - fp = np.sum((y_pred_arr == c) & (y_true_arr != c)) - fn = np.sum((y_pred_arr != c) & (y_true_arr == c)) - precision = tp / max(tp + fp, 1) - recall = tp / max(tp + fn, 1) - f1 = 2 * precision * recall / max(precision + recall, 1e-10) - per_class_f1.append(f1) - - return {"accuracy": accuracy, "macro_f1": float(np.mean(per_class_f1)) if per_class_f1 else 0.0} - - -def _normalized_mutual_info(a: np.ndarray, b: np.ndarray, k: int) -> float: - n = len(a) - contingency = np.zeros((k, k), dtype=np.float64) - for i in range(n): - contingency[a[i], b[i]] += 1 - - row_sums = contingency.sum(axis=1) - col_sums = contingency.sum(axis=0) - - mi = 0.0 - for i in range(k): - for j in range(k): - if contingency[i, j] > 0: - mi += contingency[i, j] / n * np.log( - n * contingency[i, j] / max(row_sums[i] * col_sums[j], 1e-10) - ) - - h_a = -np.sum(row_sums / n * np.log(np.maximum(row_sums / n, 1e-10))) - h_b = -np.sum(col_sums / n * np.log(np.maximum(col_sums / n, 1e-10))) - - denom = (h_a + h_b) / 2 - if denom < 1e-10: - return 0.0 - return float(mi / denom) + index_map = _index_map(graph) + embeddings = np.asarray(embeddings) + train = [(index_map[e], l) for e, l in train_labels.items() if e in index_map] + test = [(index_map[e], l) for e, l in test_labels.items() if e in index_map] + if not train or not test: + return {"accuracy": 0.0, "macro_f1": 0.0} + predicted = _nearest_centroid(embeddings[[i for i, _ in train]], np.array([l for _, l in train]), + embeddings[[i for i, _ in test]]) + scores = _label_scores(np.array([l for _, l in test]), predicted) + return {"accuracy": scores["accuracy"], "macro_f1": scores["macro_f1"]} diff --git a/pycleora/preprocess.py b/pycleora/preprocess.py index b33e383..e5327fb 100644 --- a/pycleora/preprocess.py +++ b/pycleora/preprocess.py @@ -1,9 +1,11 @@ import numpy as np -from scipy.sparse import csr_matrix from collections import deque def _graph_to_adjacency(graph): + # scipy is an optional dependency: import it only when it is needed + from scipy.sparse import csr_matrix + rows, cols, vals, n, _ = graph.to_sparse_csr() A = csr_matrix( (vals.astype(np.float64), (rows.astype(np.int32), cols.astype(np.int32))), diff --git a/pycleora/pycleora.pyi b/pycleora/pycleora.pyi index cb959a3..9744949 100644 --- a/pycleora/pycleora.pyi +++ b/pycleora/pycleora.pyi @@ -1,36 +1,134 @@ -from typing import Any, Iterable, List, Optional, Self, Tuple +from typing import Any, Iterable, List, Optional, Sequence, Tuple, Union import numpy as np from numpy.typing import NDArray +__version__: str + class SparseMatrix: - entity_ids: List[str] + """Symmetric sparse co-occurrence matrix of a hypergraph.""" + + #: Entity names in matrix row order (immutable, cached). + entity_ids: Tuple[str, ...] num_entities: int + #: Number of stored (directed) entries of the matrix. num_edges: int + #: Weighted degree of every entity. entity_degrees: NDArray[np.float32] + #: Names of the entity columns the matrix was built from. + column_names: List[str] + #: Indices of the entities that have no neighbour other than themselves. + isolated_entities: List[int] - def __new__(cls, *args: Any) -> Self: ... + def __new__(cls, *args: Any) -> "SparseMatrix": ... def __repr__(self) -> str: ... def __len__(self) -> int: ... - @classmethod + @staticmethod def from_iterator( - cls, hyperedges: Iterable[str], columns: str, hyperedge_trim_n: int = 16, num_workers: Optional[int] = None - ) -> Self: ... + hyperedges: Iterable[str], + columns: str, + hyperedge_trim_n: int = 16, + num_workers: Optional[int] = None, + weights: Optional[Union[Sequence[float], NDArray[Any]]] = None, + ) -> "SparseMatrix": ... - @classmethod + @staticmethod + def from_cliques( + cliques: Iterable[Sequence[str]], + hyperedge_trim_n: int = 16, + num_workers: Optional[int] = None, + weights: Optional[Union[Sequence[float], NDArray[Any]]] = None, + ) -> "SparseMatrix": ... + + @staticmethod def from_files( - cls, filepaths: list[str], columns: str, hyperedge_trim_n: int = 16, num_workers: Optional[int] = None - ) -> Self: ... + filepaths: List[str], + columns: str, + hyperedge_trim_n: int = 16, + num_workers: Optional[int] = None, + ) -> "SparseMatrix": ... + + @staticmethod + def from_edges( + src: Union[NDArray[np.int64], Sequence[str]], + dst: Union[NDArray[np.int64], Sequence[str]], + columns: str = "complex::reflexive::node", + weights: Optional[Union[Sequence[float], NDArray[Any]]] = None, + num_workers: Optional[int] = None, + ) -> "SparseMatrix": ... - def left_markov_propagate(self, x: NDArray[np.float32], num_workers: Optional[int] = None) -> NDArray[np.float32]: ... - def symmetric_markov_propagate(self, x: NDArray[np.float32], num_workers: Optional[int] = None) -> NDArray[np.float32]: ... + def left_markov_propagate( + self, + x: NDArray[np.float32], + num_workers: Optional[int] = None, + out: Optional[NDArray[np.float32]] = None, + rows: Optional[Union[Sequence[int], NDArray[np.integer[Any]]]] = None, + ) -> NDArray[np.float32]: ... + def symmetric_markov_propagate( + self, + x: NDArray[np.float32], + num_workers: Optional[int] = None, + out: Optional[NDArray[np.float32]] = None, + rows: Optional[Union[Sequence[int], NDArray[np.integer[Any]]]] = None, + ) -> NDArray[np.float32]: ... + def left_markov_propagate_normalized_inplace( + self, x: NDArray[np.float32], num_iterations: int, num_workers: Optional[int] = None + ) -> None: ... + def symmetric_markov_propagate_normalized_inplace( + self, x: NDArray[np.float32], num_iterations: int, num_workers: Optional[int] = None + ) -> None: ... + def suggest_iterations(self, propagation: str = "left", purpose: str = "general") -> int: ... + def embed_fast( + self, + feature_dim: int, + num_iterations: int, + propagation: str = "left", + seed: int = 0, + residual_weight: float = 0.0, + num_workers: Optional[int] = None, + ) -> NDArray[np.float32]: ... + def embed_fast_convergence( + self, + feature_dim: int, + max_iterations: int, + propagation: str = "left", + seed: int = 0, + residual_weight: float = 0.0, + convergence_threshold: float = 0.0, + num_workers: Optional[int] = None, + ) -> Tuple[NDArray[np.float32], int]: ... + def l2_normalize(self, x: NDArray[np.float32], num_workers: Optional[int] = None) -> NDArray[np.float32]: ... + def initialize_deterministically(self, feature_dim: int, seed: int = 0) -> NDArray[np.float32]: ... def get_entity_column_mask(self, column_name: str) -> NDArray[np.bool_]: ... def get_entity_index(self, entity_id: str) -> int: ... - def get_entity_indices(self, entity_ids: List[str]) -> List[int]: ... + def get_entity_indices(self, entity_ids: Sequence[str]) -> List[int]: ... def get_neighbors(self, entity_id: str) -> List[Tuple[str, float]]: ... - def to_sparse_csr(self, markov_type: Optional[str] = None) -> Tuple[NDArray[np.uint32], NDArray[np.uint32], NDArray[np.float32], int, int]: ... - def initialize_deterministically(self, feature_dim: int, seed: int = 0) -> NDArray[np.float32]: ... + def to_sparse_csr( + self, markov_type: Optional[str] = None + ) -> Tuple[NDArray[np.uint32], NDArray[np.uint32], NDArray[np.float32], int, int]: ... + def to_csr( + self, markov_type: Optional[str] = None + ) -> Tuple[NDArray[np.integer[Any]], NDArray[np.integer[Any]], NDArray[np.float32]]: ... def __getstate__(self) -> bytes: ... def __setstate__(self, state: bytes) -> None: ... + + +def column_mean_cov( + x: NDArray[np.float32], num_workers: Optional[int] = None +) -> Tuple[NDArray[np.float64], NDArray[np.float64]]: ... +def center_project( + x: NDArray[np.float32], + mean: NDArray[np.float32], + transform: NDArray[np.float32], + num_workers: Optional[int] = None, +) -> NDArray[np.float32]: ... +def center_project_inplace( + x: NDArray[np.float32], + mean: NDArray[np.float32], + transform: NDArray[np.float32], + num_workers: Optional[int] = None, +) -> None: ... +def l2_normalize_inplace(x: NDArray[np.float32], num_workers: Optional[int] = None) -> None: ... +def entity_hash(entity_id: str) -> int: ... diff --git a/pycleora/stats.py b/pycleora/stats.py index eba95c3..df357ac 100644 --- a/pycleora/stats.py +++ b/pycleora/stats.py @@ -1,9 +1,11 @@ import numpy as np -from scipy.sparse import csr_matrix from collections import deque def _graph_to_adjacency(graph): + # scipy is an optional dependency: import it only when it is needed + from scipy.sparse import csr_matrix + rows, cols, vals, n, _ = graph.to_sparse_csr() A = csr_matrix( (vals.astype(np.float64), (rows.astype(np.int32), cols.astype(np.int32))), diff --git a/pyproject.toml b/pyproject.toml index cb6007c..d4a3552 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,26 +1,54 @@ [build-system] -requires = ["maturin>=1.2.3"] +requires = ["maturin>=1.9.4,<2.0"] build-backend = "maturin" [project] name = "pycleora" -requires-python = ">=3.7" -classifiers = [ - "Programming Language :: Rust", - "Programming Language :: Python :: Implementation :: CPython", - "Programming Language :: Python :: Implementation :: PyPy", -] -version = "3.2.1" +# the version is defined once, in Cargo.toml +dynamic = ["version"] description = "Fast CPU-only graph embedding library with Rust core. Supports Cleora, DeepWalk, Node2Vec, ProNE, MLP, and more." readme = { file = "README.md", content-type = "text/markdown" } authors = [ { name = "Jacek Dabrowski", email = "jack.dabrowski@synerise.com" } ] license = { file = "LICENSE" } +requires-python = ">=3.10" +dependencies = [ + "numpy>=1.23", +] +classifiers = [ + "Programming Language :: Rust", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Programming Language :: Python :: 3.15", + "Programming Language :: Python :: Implementation :: CPython", + "License :: OSI Approved :: MIT License", + "Topic :: Scientific/Engineering :: Artificial Intelligence", +] +[project.optional-dependencies] +# Needed by the baseline algorithms (pycleora.algorithms), the attention, directed +# and edge-feature embeddings, and by most of the analysis helpers. +scipy = ["scipy>=1.9"] +viz = ["matplotlib>=3.5"] +networkx = ["networkx>=2.6"] +full = ["scipy>=1.9", "matplotlib>=3.5", "networkx>=2.6", "tqdm>=4.60"] +test = ["pytest>=7", "scipy>=1.9", "pandas>=1.5", "networkx>=2.6", "scikit-learn>=1.1"] + +[project.urls] +Homepage = "https://cleora.ai" +Documentation = "https://cleora.ai/docs" +Repository = "https://github.com/BaseModelAI/cleora" [project.scripts] pycleora = "pycleora.cli:main" [tool.maturin] -features = ["pyo3/extension-module"] +module-name = "pycleora.pycleora" + +[tool.pytest.ini_options] +testpaths = ["tests/python"] diff --git a/scripts/post-merge.sh b/scripts/post-merge.sh index 7d27a01..0e6b61a 100755 --- a/scripts/post-merge.sh +++ b/scripts/post-merge.sh @@ -3,12 +3,23 @@ set -e pip install flask 2>/dev/null || true +# pyo3 0.30 needs maturin 1.9.4 or newer +pip install "maturin>=1.9.4,<2.0" 2>/dev/null || true + if [ -f "Cargo.toml" ] && command -v maturin &> /dev/null; then echo "Rust project detected — rebuilding wheel..." maturin build --release -i python3 2>/dev/null || true - pip install target/wheels/pycleora-*.whl --force-reinstall 2>/dev/null || true - SO_SRC=$(find .pythonlibs -name "pycleora.cpython-*.so" 2>/dev/null | head -1) + # install the wheel that was just built (older builds may still be in the folder) + WHEEL=$(ls -t target/wheels/pycleora-*.whl 2>/dev/null | head -1) + if [ -n "$WHEEL" ]; then + pip install "$WHEEL" --force-reinstall 2>/dev/null || true + fi + # The extension is built for the stable ABI and is called pycleora.abi3.so. + # Version-specific builds of earlier releases must go: Python would import + # them first and the Python code no longer matches them. + SO_SRC=$(find .pythonlibs -name "pycleora.abi3.so" 2>/dev/null | head -1) if [ -n "$SO_SRC" ]; then + rm -f pycleora/pycleora.cpython-*.so 2>/dev/null || true cp "$SO_SRC" pycleora/ 2>/dev/null || true fi fi diff --git a/setup.py b/setup.py index af13250..a82cab5 100644 --- a/setup.py +++ b/setup.py @@ -1,3 +1,5 @@ +import re + from setuptools import setup, find_packages try: @@ -6,22 +8,27 @@ except ImportError: rust_extensions = [] +# pip builds pycleora with maturin (see pyproject.toml); this file only serves +# `setup.py`-based workflows and mirrors the metadata defined there. +with open("Cargo.toml") as _cargo: + _version = re.search(r'^version\s*=\s*"([^"]+)"', _cargo.read(), flags=re.MULTILINE).group(1) + setup( name="pycleora", - version="3.2.1", + version=_version, description="Fast CPU-only graph embedding library with Rust core", long_description=open("README.md").read() if __import__("os").path.exists("README.md") else "", long_description_content_type="text/markdown", packages=find_packages(), - python_requires=">=3.8", + python_requires=">=3.10", install_requires=[ - "numpy>=1.21", - "scipy>=1.7", + "numpy>=1.23", ], extras_require={ + "scipy": ["scipy>=1.9"], "viz": ["matplotlib>=3.5"], "networkx": ["networkx>=2.6"], - "full": ["matplotlib>=3.5", "networkx>=2.6", "tqdm>=4.60"], + "full": ["scipy>=1.9", "matplotlib>=3.5", "networkx>=2.6", "tqdm>=4.60"], }, entry_points={ "console_scripts": [ diff --git a/src/blocked.rs b/src/blocked.rs new file mode 100644 index 0000000..7d0b976 --- /dev/null +++ b/src/blocked.rs @@ -0,0 +1,302 @@ +//! Classic Cleora on a column-blocked embedding matrix. +//! +//! Concern of this module: running the rounds of [`crate::embedding::embed`] - +//! propagate, normalise every row - with less memory traffic than the row-major +//! kernel, and with bit-identical results. +//! +//! Why. A round of the row-major kernel reads one whole source row per matrix entry +//! (`dim` floats: 4 KB at 1024 dimensions) from wherever in memory that row is. The +//! embedding matrix is far larger than the caches, so nearly all of it comes from +//! main memory, and the kernel runs at the speed of the memory bus. Here the matrix +//! is kept as blocks of [`BLOCK`] columns, each block one contiguous slab with a +//! cache line per entity, and a round handles one block after the other. All threads +//! read the same slab, which fits the caches or nearly does, and what is streamed +//! from memory per entry and block is its 8 bytes of index and weight. +//! +//! Same numbers. Every coordinate goes through the operations of the row-major +//! kernel in the same order ([`Block::segment`], [`Block::rows`]), so a result does +//! not depend on which of the two computed it; a test pins that. Rows are normalised +//! after every round as always, but the factor is kept per entity and applied when a +//! line is read - `value * factor` is the very multiplication the normalisation +//! performs - which saves a pass over the matrix per round. + +use rayon::prelude::*; + +use crate::embedding::{balanced_tasks, prefetch, split_tasks, MarkovType, HUB_NNZ, TASK_NNZ}; +use crate::sparse_matrix::SparseMatrix; + +/// Columns per block: one cache line of `f32`. +const BLOCK: usize = 16; + +/// Below this many rounds the conversion at the end costs more than the blocks save. +pub const MIN_ROUNDS: usize = 2; + +/// How many entries ahead a source line is requested. The lines of a slab are read in +/// no order at all; asking early keeps as many requests in flight as the CPU allows. +const PREFETCH_DISTANCE: usize = 32; + +/// Lines (or rows) one task of the passes that are not propagation handles. +const LINES_PER_TASK: usize = 4096; + +/// [`BLOCK`] consecutive coordinates of one entity, on a cache line of their own. +#[derive(Clone, Copy)] +#[repr(C, align(64))] +struct Line([f32; BLOCK]); + +/// A matrix in blocks: the line of block `b` and entity `i` is at `b * n + i`. +/// +/// The memory is an ordinary zeroed vector of floats, which the allocator hands out +/// without writing to it (an over-aligned zeroed allocation would be cleared by one +/// thread, gigabyte after gigabyte); the lines start at its first cache-line boundary. +struct Lines { + floats: Vec, + len: usize, +} + +impl Lines { + fn zeroed(len: usize) -> Lines { + Lines { + floats: vec![0f32; (len + 1) * BLOCK], + len, + } + } + + /// Floats before the first cache-line boundary of the allocation. + fn skipped(&self) -> usize { + let line = std::mem::align_of::(); + (line - self.floats.as_ptr() as usize % line) % line / std::mem::size_of::() + } + + fn get(&self) -> &[Line] { + // Safety: `skipped() < BLOCK` floats are passed over and the vector holds one line + // more than `len`, so the lines are inside the allocation; they are aligned by + // construction, and any bit pattern is a valid `Line`. + unsafe { + std::slice::from_raw_parts( + self.floats.as_ptr().add(self.skipped()) as *const Line, + self.len, + ) + } + } + + fn get_mut(&mut self) -> &mut [Line] { + // Safety: as in `get`; the borrow of `self` is exclusive. + unsafe { + std::slice::from_raw_parts_mut( + self.floats.as_mut_ptr().add(self.skipped()) as *mut Line, + self.len, + ) + } + } +} + +/// The matrix whose coordinates are `initial(entity, column)`. The last block is +/// padded with zeros, which stay zeros. +fn initial_blocks(n: usize, dim: usize, initial: &I) -> Lines +where + I: Fn(usize, usize) -> f32 + Sync, +{ + let mut lines = Lines::zeroed(dim.div_ceil(BLOCK) * n); + lines + .get_mut() + .par_iter_mut() + .enumerate() + .with_min_len(LINES_PER_TASK) + .for_each(|(index, line)| { + let (first, entity) = (index / n * BLOCK, index % n); + for (offset, value) in line.0.iter_mut().take(dim - first).enumerate() { + *value = initial(entity, first + offset); + } + }); + lines +} + +/// The blocks as a row-major `n x dim` matrix, every row multiplied by its factor. +fn to_rows(lines: &[Line], factor: &[f32], n: usize, dim: usize) -> Vec { + let mut x = vec![0f32; n * dim]; + x.par_chunks_mut(dim) + .zip(factor) + .enumerate() + .with_min_len(LINES_PER_TASK / BLOCK) + .for_each(|(entity, (row, &factor))| { + for (block, part) in row.chunks_mut(BLOCK).enumerate() { + let line = &lines[block * n + entity].0; + for (value, source) in part.iter_mut().zip(line) { + *value = *source * factor; + } + } + }); + x +} + +/// What one round computes for one block. +#[derive(Clone, Copy)] +struct Block<'a> { + graph: &'a SparseMatrix, + symmetric: bool, + /// The lines of this block after the previous round, not yet normalised. + source: &'a [Line], + /// What the previous round's normalisation multiplies every row by. + factor: &'a [f32], +} + +impl Block<'_> { + /// Entry `k` as the kernel uses it: its factor, the normalisation factor of its + /// column and the column's line. + #[inline(always)] + fn entry(&self, k: usize) -> (f32, f32, &[f32; BLOCK]) { + let column = self.graph.indices[k] as usize; + ( + self.graph.entry_factor(k, self.symmetric), + self.factor[column], + &self.source[column].0, + ) + } + + #[inline(always)] + fn prefetch_line(&self, k: usize) { + if let Some(&column) = self.graph.indices.get(k) { + prefetch(self.source.as_ptr().wrapping_add(column as usize) as *const f32); + } + } + + /// The sum over the entries `first..last` of `entry factor * (line * column factor)`. + /// + /// Four entries are added per pass, but every coordinate still receives its terms + /// one after another in entry order: the result is the one of adding them singly. + #[inline(always)] + fn segment(&self, first: usize, last: usize) -> [f32; BLOCK] { + let mut sum = [0f32; BLOCK]; + let mut k = first; + while k + 4 <= last { + for ahead in 0..4 { + self.prefetch_line(k + PREFETCH_DISTANCE + ahead); + } + let (c0, f0, l0) = self.entry(k); + let (c1, f1, l1) = self.entry(k + 1); + let (c2, f2, l2) = self.entry(k + 2); + let (c3, f3, l3) = self.entry(k + 3); + for i in 0..BLOCK { + let mut value = sum[i]; + value += c0 * (l0[i] * f0); + value += c1 * (l1[i] * f1); + value += c2 * (l2[i] * f2); + value += c3 * (l3[i] * f3); + sum[i] = value; + } + k += 4; + } + while k < last { + let (coefficient, factor, line) = self.entry(k); + for (sum, value) in sum.iter_mut().zip(line) { + *sum += coefficient * (*value * factor); + } + k += 1; + } + sum + } + + /// The lines of the rows `first_row..` of the product into `out`, their squares + /// added to `squares` (one running sum per row, continued from block to block in + /// coordinate order: what the row normalisation sums). + #[inline(always)] + fn rows(&self, first_row: usize, out: &mut [Line], squares: &mut [f32]) { + for (offset, (line, square)) in out.iter_mut().zip(squares).enumerate() { + let row = first_row + offset; + let entries = self.graph.row_range(row); + let sum = if entries.len() > HUB_NNZ { + // as the row-major kernel sums such a row: in segments, combined in order + let mut total = [0f32; BLOCK]; + for first in entries.clone().step_by(TASK_NNZ) { + let part = self.segment(first, (first + TASK_NNZ).min(entries.end)); + for (total, part) in total.iter_mut().zip(part) { + *total += part; + } + } + total + } else { + self.segment(entries.start, entries.end) + }; + let scale = self.graph.row_factor(row, self.symmetric); + let mut running = *square; + for (target, sum) in line.0.iter_mut().zip(sum) { + let value = sum * scale; + *target = value; + running += value * value; + } + *square = running; + } + } +} + +/// [`Block::rows`], compiled for AVX2 when the CPU has it. No fused multiply-add is +/// used, so both versions produce bit-identical results. +fn rows_dispatch(block: &Block<'_>, first_row: usize, out: &mut [Line], squares: &mut [f32]) { + #[cfg(target_arch = "x86_64")] + { + #[target_feature(enable = "avx2")] + unsafe fn avx2(block: &Block<'_>, first_row: usize, out: &mut [Line], squares: &mut [f32]) { + block.rows(first_row, out, squares) + } + if std::arch::is_x86_feature_detected!("avx2") { + // Safety: AVX2 availability was just checked. + return unsafe { avx2(block, first_row, out, squares) }; + } + } + block.rows(first_row, out, squares) +} + +/// `rounds` rounds of propagation and row normalisation of the `n x dim` matrix whose +/// coordinates are `initial(entity, column)`: exactly what +/// [`crate::embedding::iterate`] leaves in its buffer, as a row-major matrix. +/// Runs on the current rayon pool; needs two matrices of memory, as the row-major loop. +pub fn embed( + graph: &SparseMatrix, + dim: usize, + kind: MarkovType, + rounds: usize, + initial: I, +) -> Vec +where + I: Fn(usize, usize) -> f32 + Sync, +{ + let n = graph.num_entities(); + if n == 0 || dim == 0 { + return Vec::new(); + } + let mut current = initial_blocks(n, dim, &initial); + let mut next = Lines::zeroed(current.len); + let mut factor = vec![1f32; n]; + let mut squares = vec![0f32; n]; + let bounds = balanced_tasks((0..n).map(|row| graph.row_range(row).len())); + + for _ in 0..rounds { + squares.fill(0.0); + for (source, out) in current + .get() + .chunks_exact(n) + .zip(next.get_mut().chunks_exact_mut(n)) + { + let block = Block { + graph, + symmetric: kind == MarkovType::Symmetric, + source, + factor: &factor, + }; + split_tasks(out, &bounds, 1) + .into_par_iter() + .zip(split_tasks(&mut squares, &bounds, 1)) + .zip(bounds.par_iter()) + .with_max_len(1) + .for_each(|((out, squares), &first_row)| { + rows_dispatch(&block, first_row, out, squares) + }); + } + for (factor, square) in factor.iter_mut().zip(&squares) { + *factor = 1.0 / square.sqrt().max(1e-10); + } + std::mem::swap(&mut current, &mut next); + } + drop(next); + to_rows(current.get(), &factor, n, dim) +} diff --git a/src/configuration.rs b/src/configuration.rs index a1b296d..40b8500 100644 --- a/src/configuration.rs +++ b/src/configuration.rs @@ -1,70 +1,232 @@ -use crate::sparse_matrix::SparseMatrixDescriptor; +use serde::{Deserialize, Serialize}; -#[derive(Debug)] -pub struct Configuration { - pub seed: Option, - pub matrix_desc: SparseMatrixDescriptor, - pub columns: Vec, - pub hyperedge_trim_n: usize, - pub num_workers_graph_building: usize, -} - -#[derive(Debug, Default)] +/// One column of the input, as declared in the `columns` string. +#[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Column { pub name: String, + /// The field holds several space-separated entities. pub complex: bool, + /// The column is also related to itself (co-occurrence within the field). pub reflexive: bool, + /// The field holds the (non-negative) weight of the whole line, not an entity. + pub weight: bool, } -pub fn parse_fields(columns: &str) -> Result, String> { - let cols: Vec<&str> = columns.split(' ').collect(); +/// A relation between two entity columns. `a == b` denotes a reflexive relation +/// (a column related to itself). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct Relation { + pub a: u8, + pub b: u8, +} - let mut columns: Vec = Vec::new(); - for col in cols { - let parts: Vec<&str> = col.split("::").collect(); +#[derive(Debug, Clone)] +pub struct Configuration { + /// Every declared column, in input order (including the weight column, if any). + pub columns: Vec, + /// Names of the entity columns, in input order. + pub entity_column_names: Vec, + /// For every declared column: its index among the entity columns (`None` for the weight column). + pub entity_column_of: Vec>, + pub weight_column: Option, + /// Relations between entity columns (indices into `entity_column_names`). + pub relations: Vec, + pub hyperedge_trim_n: usize, + pub num_workers: usize, +} + +impl Configuration { + pub fn new( + columns: &str, + hyperedge_trim_n: usize, + num_workers: Option, + ) -> Result { + let columns = parse_fields(columns)?; - let column_name: &str; - let mut complex = false; - let mut reflexive = false; - - let parts_len = parts.len(); - if parts_len > 1 { - column_name = *parts.last().unwrap(); - let column_name_idx = parts_len - 1; - for &part in &parts[..column_name_idx] { - if part.eq_ignore_ascii_case("complex") { - complex = true; - } else if part.eq_ignore_ascii_case("reflexive") { - reflexive = true; - } else { - let message = format!("Unrecognized column field modifier: {}", part); - return Err(message); - } + let mut entity_column_names = Vec::new(); + let mut entity_column_of = Vec::with_capacity(columns.len()); + let mut weight_column = None; + for (i, column) in columns.iter().enumerate() { + if column.weight { + weight_column = Some(i); + entity_column_of.push(None); + } else { + entity_column_of.push(Some(entity_column_names.len() as u8)); + entity_column_names.push(column.name.clone()); } - } else { - column_name = col; } - let column = Column { + if entity_column_names.len() > u8::MAX as usize { + return Err(format!( + "Too many entity columns ({}); at most {} are supported", + entity_column_names.len(), + u8::MAX + )); + } + + // Same enumeration order as the original implementation: + // for every column, first its reflexive relation, then the relations with later columns. + let entity_columns: Vec<&Column> = columns.iter().filter(|c| !c.weight).collect(); + let mut relations = Vec::new(); + for i in 0..entity_columns.len() { + if entity_columns[i].reflexive { + relations.push(Relation { + a: i as u8, + b: i as u8, + }); + } + for j in (i + 1)..entity_columns.len() { + relations.push(Relation { + a: i as u8, + b: j as u8, + }); + } + } + if relations.is_empty() { + return Err( + "The columns definition must describe at least one relation: use two or more \ + entity columns, or mark a column as 'complex::reflexive::'." + .to_string(), + ); + } + if hyperedge_trim_n == 0 { + return Err("hyperedge_trim_n must be at least 1".to_string()); + } + + Ok(Configuration { + columns, + entity_column_names, + entity_column_of, + weight_column, + relations, + hyperedge_trim_n, + num_workers: resolve_num_workers(num_workers), + }) + } +} + +/// Number of worker threads to use: the requested number, or all available cores. +pub fn resolve_num_workers(num_workers: Option) -> usize { + match num_workers { + Some(n) if n > 0 => n, + _ => std::thread::available_parallelism() + .map(|n| n.get()) + .unwrap_or(1), + } +} + +pub fn parse_fields(columns: &str) -> Result, String> { + let mut parsed: Vec = Vec::new(); + for col in columns.split_whitespace() { + let parts: Vec<&str> = col.split("::").collect(); + let column_name = *parts.last().unwrap(); + if column_name.is_empty() { + return Err(format!("Column definition '{}' has an empty name", col)); + } + + let mut column = Column { name: column_name.to_string(), - complex, - reflexive, + ..Default::default() }; - columns.push(column); + for &part in &parts[..parts.len() - 1] { + if part.eq_ignore_ascii_case("complex") { + column.complex = true; + } else if part.eq_ignore_ascii_case("reflexive") { + column.reflexive = true; + } else if part.eq_ignore_ascii_case("weight") { + column.weight = true; + } else { + return Err(format!("Unrecognized column field modifier: {}", part)); + } + } + parsed.push(column); } - let columns = validate_column_modifiers(columns)?; - Ok(columns) + if parsed.is_empty() { + return Err("The columns definition is empty".to_string()); + } + validate_column_modifiers(parsed) } fn validate_column_modifiers(cols: Vec) -> Result, String> { + let mut weight_columns = 0; for col in &cols { if col.reflexive && !col.complex { - let message = format!( + return Err(format!( "A field cannot be REFLEXIVE but NOT COMPLEX. It does not make sense: {}", col.name - ); - return Err(message); + )); } + if col.weight { + weight_columns += 1; + if col.complex || col.reflexive { + return Err(format!( + "A WEIGHT field holds a single number and cannot be COMPLEX or REFLEXIVE: {}", + col.name + )); + } + } + } + if weight_columns > 1 { + return Err("At most one column can be marked as 'weight::'".to_string()); } Ok(cols) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn single_reflexive_column() { + let c = Configuration::new("complex::reflexive::product", 16, Some(1)).unwrap(); + assert_eq!(c.relations, vec![Relation { a: 0, b: 0 }]); + assert_eq!(c.entity_column_names, vec!["product"]); + assert_eq!(c.weight_column, None); + } + + #[test] + fn two_columns() { + let c = Configuration::new("user complex::product", 16, Some(1)).unwrap(); + assert_eq!(c.relations, vec![Relation { a: 0, b: 1 }]); + } + + #[test] + fn several_relations_and_weight() { + let c = Configuration::new( + "user complex::reflexive::product weight::w brand", + 16, + Some(1), + ) + .unwrap(); + assert_eq!(c.entity_column_names, vec!["user", "product", "brand"]); + assert_eq!(c.weight_column, Some(2)); + assert_eq!(c.entity_column_of, vec![Some(0), Some(1), None, Some(2)]); + assert_eq!( + c.relations, + vec![ + Relation { a: 0, b: 1 }, + Relation { a: 0, b: 2 }, + Relation { a: 1, b: 1 }, + Relation { a: 1, b: 2 }, + ] + ); + } + + #[test] + fn rejects_bad_definitions() { + assert!(Configuration::new("node", 16, None).is_err()); + assert!(Configuration::new("", 16, None).is_err()); + assert!(Configuration::new("reflexive::node", 16, None).is_err()); + assert!(Configuration::new("a b weight::x weight::y", 16, None).is_err()); + assert!(Configuration::new("a complex::weight::w", 16, None).is_err()); + assert!(Configuration::new("a bogus::b", 16, None).is_err()); + assert!(Configuration::new("a b", 0, None).is_err()); + } + + #[test] + fn tolerates_repeated_whitespace() { + let c = Configuration::new(" user product ", 16, Some(2)).unwrap(); + assert_eq!(c.entity_column_names, vec!["user", "product"]); + assert_eq!(c.num_workers, 2); + } +} diff --git a/src/embedding.rs b/src/embedding.rs index 3831508..93f0674 100644 --- a/src/embedding.rs +++ b/src/embedding.rs @@ -1,189 +1,1442 @@ -use crate::sparse_matrix::Edge; -use crate::sparse_matrix::SparseMatrix; -use ndarray::{Array, Array1, Array2, ArrayView2, ArrayViewMut2, Axis}; +//! Dense kernels: sparse propagation, normalisation, initialisation and the +//! building blocks of whitening. +//! +//! All kernels give the same result for any number of threads: parallel work is +//! either independent per row, or reduced in a fixed order. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex, OnceLock}; + +use ndarray::{Array2, ArrayView2, ArrayViewMut2}; use rayon::prelude::*; -use rayon::ThreadPoolBuilder; +use rayon::{ThreadPool, ThreadPoolBuilder}; + +use crate::entity::hash_entity; +use crate::sparse_matrix::SparseMatrix; +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum MarkovType { Left, Symmetric, } -pub struct NdArrayMatrix; +/// Returns a thread pool with the requested number of threads, creating it on +/// first use. Pools are kept for the lifetime of the process. +/// +/// A forked child inherits this table but not the worker threads behind it: handing +/// out one of the parent's pools there would wait forever for threads that do not +/// exist. The table therefore remembers which process filled it and starts afresh in +/// another one. +pub fn thread_pool(num_threads: usize) -> Arc { + type Pools = (u32, HashMap>); + static POOLS: OnceLock> = OnceLock::new(); + let num_threads = num_threads.max(1); + let process = std::process::id(); + let mut guard = POOLS + .get_or_init(|| Mutex::new((process, HashMap::new()))) + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if guard.0 != process { + // The parent's pools are never dropped here: their threads are not ours to stop. + std::mem::forget(std::mem::take(&mut guard.1)); + guard.0 = process; + } + guard + .1 + .entry(num_threads) + .or_insert_with(|| { + Arc::new( + ThreadPoolBuilder::new() + .num_threads(num_threads) + .thread_name(|i| format!("pycleora-{}", i)) + .build() + .expect("failed to start worker threads"), + ) + }) + .clone() +} -impl NdArrayMatrix { - pub fn multiply( - sparse_matrix_reader: &SparseMatrix, - other: ArrayView2, - markov_type: MarkovType, - num_workers: usize, - ) -> Array2 { - let mut new_matrix: Array2 = Array::zeros(other.raw_dim()); - let dim = other.shape()[1]; - - let pool = ThreadPoolBuilder::new() - .num_threads(num_workers) - .build() - .unwrap(); - - pool.install(|| { - Self::spmm_kernel( - sparse_matrix_reader, - other, - &markov_type, - dim, - new_matrix.view_mut(), +/// Rows handled by one parallel task of the dense row-wise kernels (normalisation, +/// projection): there every row costs the same. +const ROWS_PER_TASK: usize = 64; + +/// Matrix entries one propagation task handles. Propagation work is proportional to the +/// number of entries, not rows, and entities are numbered by first appearance, which +/// puts the busiest ones next to each other at the start: tasks of equal *row* counts +/// would leave most of the work to the one thread that got the first rows. +pub(crate) const TASK_NNZ: usize = 4096; +/// Upper bound on the rows of one propagation task (rows cost something even when empty). +const TASK_ROWS: usize = 1024; +/// A row with more entries than this is a task of its own, summed in parallel in +/// segments of `TASK_NNZ` entries that are combined in order. The segmentation depends +/// on the row only, so the result is the same for any number of threads. +pub(crate) const HUB_NNZ: usize = 4 * TASK_NNZ; +/// How many entries ahead the first cache line of a source row is requested. +const PREFETCH_DISTANCE: usize = 4; + +/// What one propagation computes: `M * x` for the left or symmetric Markov matrix. +#[derive(Clone, Copy)] +struct Product<'a> { + graph: &'a SparseMatrix, + x: &'a [f32], + dim: usize, + symmetric: bool, +} + +#[inline(always)] +pub(crate) fn prefetch(pointer: *const f32) { + #[cfg(target_arch = "x86_64")] + // Safety: prefetching is a hint; it never faults, whatever the address. + unsafe { + std::arch::x86_64::_mm_prefetch::<{ std::arch::x86_64::_MM_HINT_T0 }>(pointer as *const i8); + } + #[cfg(target_arch = "aarch64")] + // Safety: as above (`prfm` is a hint). + unsafe { + std::arch::asm!("prfm pldl1keep, [{p}]", p = in(reg) pointer, options(nostack, preserves_flags, readonly)); + } + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + let _ = pointer; +} + +impl<'a> Product<'a> { + #[inline(always)] + fn coefficient(&self, k: usize) -> f32 { + self.graph.entry_factor(k, self.symmetric) + } + + #[inline(always)] + fn source(&self, k: usize) -> &'a [f32] { + let column = self.graph.indices[k] as usize; + &self.x[column * self.dim..(column + 1) * self.dim] + } + + #[inline(always)] + fn prefetch_source(&self, k: usize) { + if let Some(&column) = self.graph.indices.get(k) { + prefetch(self.x.as_ptr().wrapping_add(column as usize * self.dim)); + } + } + + /// `dst += sum over entries k in [first, last) of coefficient(k) * source(k)`. + /// + /// Four source rows are added per pass over `dst`. Every element still receives + /// its terms one after another in entry order, so the result is bit-identical to + /// adding the rows one at a time; the passes over `dst` are fewer and four streams + /// of source rows are in flight at once. + #[inline(always)] + fn accumulate(&self, first: usize, last: usize, dst: &mut [f32]) { + let mut k = first; + while k + 4 <= last { + for ahead in 0..4 { + self.prefetch_source(k + PREFETCH_DISTANCE + ahead); + } + let (c0, c1, c2, c3) = ( + self.coefficient(k), + self.coefficient(k + 1), + self.coefficient(k + 2), + self.coefficient(k + 3), ); - }); - new_matrix + let (s0, s1, s2, s3) = ( + self.source(k), + self.source(k + 1), + self.source(k + 2), + self.source(k + 3), + ); + for i in 0..dst.len() { + let mut value = dst[i]; + value += c0 * s0[i]; + value += c1 * s1[i]; + value += c2 * s2[i]; + value += c3 * s3[i]; + dst[i] = value; + } + k += 4; + } + while k < last { + self.prefetch_source(k + PREFETCH_DISTANCE); + let coefficient = self.coefficient(k); + for (d, s) in dst.iter_mut().zip(self.source(k)) { + *d += coefficient * *s; + } + k += 1; + } } - pub fn multiply_into( - sparse_matrix_reader: &SparseMatrix, - src: ArrayView2, - markov_type: &MarkovType, - dst: &mut Array2, - ) { - let dim = src.shape()[1]; + /// Row `row` of the product, written to `dst`. + #[inline(always)] + fn row(&self, row: usize, dst: &mut [f32]) { + let entries = self.graph.row_range(row); dst.fill(0.0); - Self::spmm_kernel(sparse_matrix_reader, src, markov_type, dim, dst.view_mut()); + if entries.len() > HUB_NNZ { + let segments: Vec = entries.clone().step_by(TASK_NNZ).collect(); + let partial: Vec> = segments + .par_iter() + .with_max_len(1) + .map(|&first| { + let mut sum = vec![0f32; self.dim]; + accumulate_dispatch(self, first, (first + TASK_NNZ).min(entries.end), &mut sum); + sum + }) + .collect(); + for sum in &partial { + for (d, s) in dst.iter_mut().zip(sum) { + *d += *s; + } + } + } else { + self.accumulate(entries.start, entries.end, dst); + } + let scale = self.graph.row_factor(row, self.symmetric); + for d in dst.iter_mut() { + *d *= scale; + } } - fn spmm_kernel( - sparse_matrix_reader: &SparseMatrix, - other: ArrayView2, - markov_type: &MarkovType, - dim: usize, - mut output: ArrayViewMut2, - ) { - output - .axis_iter_mut(Axis(0)) - .into_par_iter() - .zip(sparse_matrix_reader.slices.par_iter()) - .for_each(|(mut row, (start, end))| { - let edges = &sparse_matrix_reader.edges[*start..*end]; - - if edges.is_empty() { - return; - } + /// The rows of one task, each followed by `finish(row, values)` while it is still + /// in the cache. + #[inline(always)] + fn rows(&self, rows: Rows<'_>, chunk: &mut [f32], finish: &F) { + for (offset, dst) in chunk.chunks_exact_mut(self.dim).enumerate() { + let row = match rows { + Rows::From(first_row) => first_row + offset, + Rows::List(list) => list[offset], + }; + self.row(row, dst); + finish(row, dst); + } + } +} - let mut acc = Array1::zeros(dim); - for edge in edges { - let value = match markov_type { - MarkovType::Left => &edge.left_markov_value, - MarkovType::Symmetric => &edge.symmetric_markov_value, - }; - let other_row = other.row(edge.other_entity_ix as usize); - let acc_slice = acc.as_slice_mut().unwrap(); - let src_slice = other_row.as_slice().unwrap(); - let v = *value; - for j in 0..dim { - acc_slice[j] += v * src_slice[j]; - } - } - row.assign(&acc); +/// The rows one task computes: consecutive ones or an explicit list. +#[derive(Clone, Copy)] +enum Rows<'a> { + From(usize), + List(&'a [usize]), +} + +/// [`Product::accumulate`], compiled for AVX2 when the CPU has it. No fused +/// multiply-add is used, so both versions produce bit-identical results. +fn accumulate_dispatch(product: &Product<'_>, first: usize, last: usize, dst: &mut [f32]) { + #[cfg(target_arch = "x86_64")] + { + #[target_feature(enable = "avx2")] + unsafe fn avx2(product: &Product<'_>, first: usize, last: usize, dst: &mut [f32]) { + product.accumulate(first, last, dst) + } + if std::arch::is_x86_feature_detected!("avx2") { + // Safety: AVX2 availability was just checked. + return unsafe { avx2(product, first, last, dst) }; + } + } + product.accumulate(first, last, dst) +} + +/// [`Product::rows`], compiled for AVX2 when the CPU has it (see [`accumulate_dispatch`]). +fn rows_dispatch( + product: &Product<'_>, + rows: Rows<'_>, + chunk: &mut [f32], + finish: &F, +) { + #[cfg(target_arch = "x86_64")] + { + #[target_feature(enable = "avx2")] + unsafe fn avx2( + product: &Product<'_>, + rows: Rows<'_>, + chunk: &mut [f32], + finish: &F, + ) { + product.rows(rows, chunk, finish) + } + if std::arch::is_x86_feature_detected!("avx2") { + // Safety: AVX2 availability was just checked. + return unsafe { avx2(product, rows, chunk, finish) }; + } + } + product.rows(rows, chunk, finish) +} + +/// Groups a sequence of rows, given by their numbers of entries, into consecutive +/// tasks of about `TASK_NNZ` entries (see the constants above). Returns the position +/// of the first row of every task, followed by the number of rows. +pub(crate) fn balanced_tasks(row_entries: impl Iterator) -> Vec { + let mut bounds = vec![0usize]; + let mut entries = 0usize; + let mut count = 0usize; + for (position, row_entries) in row_entries.enumerate() { + let first = *bounds.last().expect("never empty"); + let hub = row_entries > HUB_NNZ; + let full = entries + row_entries > TASK_NNZ || position - first >= TASK_ROWS; + if position > first && (hub || full) { + bounds.push(position); + entries = 0; + } + entries += row_entries; + if hub { + bounds.push(position + 1); + entries = 0; + } + count = position + 1; + } + if *bounds.last().expect("never empty") != count { + bounds.push(count); + } + bounds +} + +/// Cuts `data`, which holds `width` elements per row, into the pieces of the tasks given +/// by `bounds` (as [`balanced_tasks`] returns them). +pub(crate) fn split_tasks<'a, T>( + data: &'a mut [T], + bounds: &[usize], + width: usize, +) -> Vec<&'a mut [T]> { + let mut pieces = Vec::with_capacity(bounds.len() - 1); + let mut rest = data; + for task in bounds.windows(2) { + let (piece, tail) = rest.split_at_mut((task[1] - task[0]) * width); + pieces.push(piece); + rest = tail; + } + pieces +} + +/// Computes the rows `rows` of the product into `out` (one row of `out` per entry of +/// `rows`), in parallel tasks of about equal cost. +fn run_product(product: &Product<'_>, rows: Rows<'_>, out: &mut [f32], finish: F) +where + F: Fn(usize, &mut [f32]) + Sync, +{ + let dim = product.dim; + let row_at = |position: usize| match rows { + Rows::From(first_row) => first_row + position, + Rows::List(list) => list[position], + }; + let count = out.len() / dim; + let bounds = balanced_tasks((0..count).map(|p| product.graph.row_range(row_at(p)).len())); + // Every task may be stolen on its own: they are about equally expensive. + split_tasks(out, &bounds, dim) + .into_par_iter() + .zip(bounds.par_windows(2)) + .with_max_len(1) + .for_each(|(chunk, task)| { + let task_rows = match rows { + Rows::From(first_row) => Rows::From(first_row + task[0]), + Rows::List(list) => Rows::List(&list[task[0]..task[1]]), + }; + rows_dispatch(product, task_rows, chunk, &finish) + }); +} + +/// `out = M * x` for the row-major `n x dim` matrices `x` and `out`, where `M` is +/// the left or symmetric Markov matrix of the graph. +/// Runs on the current rayon pool. +pub fn propagate(graph: &SparseMatrix, x: &[f32], out: &mut [f32], dim: usize, kind: MarkovType) { + propagate_then(graph, x, out, dim, kind, |_, _| {}); +} + +/// [`propagate`], with `finish(row, values)` applied to every row of the result as +/// soon as it is computed, i.e. while it is still in the cache. +pub fn propagate_then( + graph: &SparseMatrix, + x: &[f32], + out: &mut [f32], + dim: usize, + kind: MarkovType, + finish: F, +) where + F: Fn(usize, &mut [f32]) + Sync, +{ + let n = graph.num_entities(); + assert_eq!(x.len(), n * dim, "input has the wrong size"); + assert_eq!(out.len(), n * dim, "output has the wrong size"); + if n == 0 || dim == 0 { + return; + } + let product = Product { + graph, + x, + dim, + symmetric: kind == MarkovType::Symmetric, + }; + run_product(&product, Rows::From(0), out, finish); +} + +/// The rows `rows` of `M * x`: `out` is a row-major `rows.len() x dim` matrix whose +/// i-th row is bit-identical to row `rows[i]` of what [`propagate`] computes. +/// Costs time proportional to the entries of the selected rows only. +pub fn propagate_selected( + graph: &SparseMatrix, + x: &[f32], + rows: &[usize], + out: &mut [f32], + dim: usize, + kind: MarkovType, +) { + let n = graph.num_entities(); + assert_eq!(x.len(), n * dim, "input has the wrong size"); + assert_eq!(out.len(), rows.len() * dim, "output has the wrong size"); + assert!(rows.iter().all(|&row| row < n), "row index out of range"); + if rows.is_empty() || dim == 0 { + return; + } + let product = Product { + graph, + x, + dim, + symmetric: kind == MarkovType::Symmetric, + }; + run_product(&product, Rows::List(rows), out, |_, _| {}); +} + +/// Scales one row to unit L2 norm (a row of zeros stays zero). +#[inline(always)] +pub fn l2_normalize_row(row: &mut [f32]) { + let mut sum_sq: f32 = 0.0; + for v in row.iter() { + sum_sq += v * v; + } + let inv_norm = 1.0 / sum_sq.sqrt().max(1e-10); + for v in row.iter_mut() { + *v *= inv_norm; + } +} + +/// Scales every row to unit L2 norm (rows of zeros stay zero). +pub fn l2_normalize_rows(matrix: &mut [f32], dim: usize) { + if dim == 0 { + return; + } + matrix + .par_chunks_mut(dim * ROWS_PER_TASK) + .for_each(|chunk| { + for row in chunk.chunks_exact_mut(dim) { + l2_normalize_row(row); + } + }); +} + +/// `dst = (1 - residual_weight) * dst + residual_weight * src` +#[inline(always)] +fn mix_residual_row(dst: &mut [f32], src: &[f32], residual_weight: f32) { + let alpha = 1.0 - residual_weight; + for (d, s) in dst.iter_mut().zip(src) { + *d = alpha * *d + residual_weight * *s; + } +} + +/// Root mean squared difference between two matrices, independent of the thread count. +fn rmse(a: &[f32], b: &[f32]) -> f64 { + if a.is_empty() { + return 0.0; + } + let partial: Vec = a + .par_chunks(1 << 14) + .zip(b.par_chunks(1 << 14)) + .map(|(a, b)| { + let mut sum = 0.0f64; + for (x, y) in a.iter().zip(b) { + let delta = (*x - *y) as f64; + sum += delta * delta; + } + sum + }) + .collect(); + (partial.iter().sum::() / a.len() as f64).sqrt() +} + +/// Classic Cleora on a matrix in place: `num_iterations` rounds of propagation followed +/// by row-wise L2 normalisation of `current`, using `scratch` (same size) as the second +/// buffer. Returns the number of rounds performed. +/// With `convergence_threshold > 0` iteration stops once the RMSE between two +/// consecutive rounds drops below the threshold. +#[allow(clippy::too_many_arguments)] +pub fn iterate( + graph: &SparseMatrix, + current: &mut [f32], + scratch: &mut [f32], + dim: usize, + kind: MarkovType, + num_iterations: usize, + residual_weight: f32, + convergence_threshold: f32, +) -> usize { + let use_residual = residual_weight > 0.0 && residual_weight < 1.0; + let check_convergence = convergence_threshold > 0.0; + // the two buffers take turns; `src` always holds the latest round + let (mut src, mut dst) = (current, scratch); + let mut in_scratch = false; + let mut rounds = num_iterations; + + for iteration in 0..num_iterations { + let previous: &[f32] = src; + propagate_then(graph, previous, dst, dim, kind, |row, values| { + if use_residual { + mix_residual_row( + values, + &previous[row * dim..(row + 1) * dim], + residual_weight, + ); + } + l2_normalize_row(values); + }); + + let converged = + check_convergence && iteration > 0 && rmse(dst, src) < convergence_threshold as f64; + std::mem::swap(&mut src, &mut dst); + in_scratch = !in_scratch; + if converged { + rounds = iteration + 1; + break; + } + } + if in_scratch { + // `src` is the scratch buffer: the result belongs in `current` + dst.par_chunks_mut(1 << 16) + .zip(src.par_chunks(1 << 16)) + .for_each(|(target, source)| target.copy_from_slice(source)); + } + rounds +} + +/// What the vectors will be used for; see [`suggested_iterations`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Purpose { + /// Nearest neighbours, link ranking, recommendation: local structure matters. + Similarity, + /// One embedding for several uses. + General, + /// Features for a classifier: the wider neighbourhood matters. + Classification, +} + +impl Purpose { + /// Random-walk steps for a graph whose entities have one neighbour on average. + fn steps(self) -> f64 { + match self { + Purpose::Similarity => 12.0, + Purpose::General => 16.0, + Purpose::Classification => 24.0, + } + } +} + +/// The symmetric normalisation smooths more slowly and gets this many times more steps. +const AUTO_SYMMETRIC_FACTOR: f64 = 1.5; +/// With fewer steps than this, vectors of very dense graphs are still mostly noise. +const AUTO_MIN_ITERATIONS: f64 = 2.0; +/// Share of an entity's own initial (random) vector that may be left after the last +/// round. A diagonal weight share `s` leaves `s^rounds` of it. +const AUTO_SELF_REMAINDER: f64 = 1.0 / 256.0; +/// Largest number of rounds the rule was validated for. +const AUTO_MAX_ITERATIONS: usize = 64; + +/// Number of rounds for [`embed`] when there are no labels to choose it with: +/// +/// ```text +/// mixing = steps(purpose) / ((1 - s) * sqrt(mean neighbours)) (x 1.5 symmetric) +/// forget = ln(1/256) / ln(s) (0 when s = 0) +/// rounds = max(mixing, forget, 2), at most 64 +/// ``` +/// +/// where `s` is the share of the weight that lies on the diagonal. +/// +/// Every round moves the vectors one step along a random walk. Too few rounds and +/// only the closest neighbourhood is visible; too many and all vectors converge to +/// the same direction. Denser graphs mix faster, hence the square root of the mean +/// number of neighbours (`mixing`). A matrix with weight on its diagonal - a reflexive +/// column - describes a lazy walk: it only moves with probability `1 - s`, and every +/// vector keeps a share `s` of what it was. `mixing` is scaled accordingly, and +/// `forget` is the number of rounds after which the entity's own random initial +/// vector has decayed to 1/256: 8 rounds for a reflexive column of two-entity +/// hyperedges, however dense the graph. +/// +/// The form and the constants were fitted leave-one-graph-out on iteration sweeps +/// over graphs with 3 to 500 neighbours per node (`benchmarks/README.md`, "Number of +/// iterations"). +pub fn suggested_iterations(graph: &SparseMatrix, kind: MarkovType, purpose: Purpose) -> usize { + let staying = graph.self_weight_share(); + if staying >= 1.0 { + // nothing but self-loops: further rounds change nothing + return 1; + } + let factor = match kind { + MarkovType::Left => 1.0, + MarkovType::Symmetric => AUTO_SYMMETRIC_FACTOR, + }; + let mixing = + purpose.steps() * factor / ((1.0 - staying) * graph.mean_neighbours().max(1.0).sqrt()); + let forget = if staying > 0.0 { + AUTO_SELF_REMAINDER.ln() / staying.ln() + } else { + 0.0 + }; + let rounds = mixing.max(forget).max(AUTO_MIN_ITERATIONS); + (rounds.round() as usize).clamp(1, AUTO_MAX_ITERATIONS) +} + +/// Classic Cleora from the initial vectors of `seed` (see [`initialize`]). Returns the +/// embeddings and the number of rounds performed (see [`iterate`]). +/// +/// The plain loop - no residual, no convergence test - runs on a column-blocked +/// matrix ([`crate::blocked`]), which is faster and gives the same bits. +pub fn embed( + graph: &SparseMatrix, + dim: usize, + seed: i64, + kind: MarkovType, + num_iterations: usize, + residual_weight: f32, + convergence_threshold: f32, +) -> (Vec, usize) { + let plain = !(residual_weight > 0.0 && residual_weight < 1.0) && convergence_threshold <= 0.0; + if plain && num_iterations >= crate::blocked::MIN_ROUNDS { + let initial = Initial::new(&graph.entity_ids, dim, seed); + let embeddings = + crate::blocked::embed(graph, dim, kind, num_iterations, |entity, column| { + initial.value(entity, column) }); + return (embeddings, num_iterations); + } + let mut current = initialize(&graph.entity_ids, dim, seed); + let mut scratch = vec![0f32; current.len()]; + let rounds = iterate( + graph, + &mut current, + &mut scratch, + dim, + kind, + num_iterations, + residual_weight, + convergence_threshold, + ); + (current, rounds) +} + +#[inline(always)] +fn splitmix64(mut z: u64) -> u64 { + z = z.wrapping_add(0x9E37_79B9_7F4A_7C15); + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) +} + +/// Per-column keys of the initialisation for a given seed. +fn init_column_keys(dim: usize, seed: i64) -> Vec { + let seed_key = splitmix64(seed as u64); + (0..dim as u64) + .map(|column| splitmix64(column ^ seed_key)) + .collect() +} + +/// Initial value of one coordinate: uniform in `[-1, 1)`, a pure function of +/// (entity name, column, seed). +#[inline(always)] +fn init_value(entity_hash: u64, column_key: u64) -> f32 { + let bits = splitmix64(entity_hash ^ column_key) >> 40; // 24 random bits + (bits as f32) * (1.0 / 8_388_608.0) - 1.0 +} + +/// The deterministic pseudo-random initial embeddings, one coordinate at a time. +/// +/// Every entity gets a vector that depends only on its name, the seed and the +/// dimension index, so it is the same in every graph and on every machine, and +/// vectors of different entities (and of different seeds) are statistically +/// independent. +pub(crate) struct Initial { + hashes: Vec, + keys: Vec, +} + +impl Initial { + pub(crate) fn new(entity_ids: &[String], dim: usize, seed: i64) -> Initial { + Initial { + hashes: entity_ids.par_iter().map(|id| hash_entity(id)).collect(), + keys: init_column_keys(dim, seed), + } } - pub fn l2_normalize_inplace(matrix: &mut Array2) { - matrix - .axis_iter_mut(Axis(0)) - .into_par_iter() - .for_each(|mut row| { - let slice = row.as_slice_mut().unwrap(); - let mut sum_sq: f32 = 0.0; - for v in slice.iter() { - sum_sq += v * v; + #[inline(always)] + pub(crate) fn value(&self, entity: usize, column: usize) -> f32 { + init_value(self.hashes[entity], self.keys[column]) + } +} + +/// The initial embeddings ([`Initial`]) as a row-major matrix. +pub fn initialize(entity_ids: &[String], dim: usize, seed: i64) -> Vec { + let mut out = vec![0f32; entity_ids.len() * dim]; + if dim == 0 { + return out; + } + let initial = Initial::new(entity_ids, dim, seed); + out.par_chunks_mut(dim) + .enumerate() + .for_each(|(entity, row)| { + for (column, value) in row.iter_mut().enumerate() { + *value = initial.value(entity, column); + } + }); + out +} + +/// Number of row groups used for the order-fixed reduction behind the column means. +/// Depends on the shape only, never on the number of threads. +fn mean_groups(n: usize) -> usize { + n.div_ceil(4096).clamp(1, 64) +} + +/// Rows that are centred, converted to f64 and multiplied at once. +const GRAM_BLOCK: usize = 256; + +/// How the `d x d` matrix of centred second moments is accumulated in parallel. +/// Both plans are functions of the shape only, so the result never depends on the +/// number of threads. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum GramPlan { + /// The rows are split into this many groups; every group accumulates a matrix + /// of its own and the matrices are added in order. Fastest, but needs one + /// `d x d` matrix per group. + RowGroups(usize), + /// One matrix; for every block of rows its bands (this many matrix rows each) + /// are independent products. Needs no extra matrices, which is what counts + /// when `d` is large. + Bands(usize), +} + +fn gram_plan(n: usize, d: usize) -> GramPlan { + // Per-group matrices may take 1/16 of the size of the input, and 16 MB at least. + let budget = (16usize << 20).max(n * d * 4 / 16); + let affordable = budget / (d * d * 8).max(1); + let wanted = n.div_ceil(1024).clamp(1, 64); + if d >= 256 && affordable < wanted.min(8) { + GramPlan::Bands(d.div_ceil(32).max(64)) + } else { + GramPlan::RowGroups(wanted.min(affordable).max(1)) + } +} + +/// `block <- rows - mean` in f64. +fn centre_block(rows: &[f32], mean: &[f64], d: usize, block: &mut [f64]) { + for (centred, row) in block.chunks_exact_mut(d).zip(rows.chunks_exact(d)) { + for ((c, v), m) in centred.iter_mut().zip(row).zip(mean) { + *c = *v as f64 - *m; + } + } +} + +fn gram_by_row_groups(x: &[f32], n: usize, d: usize, mean: &[f64], groups: usize) -> Vec { + let rows_per_group = n.div_ceil(groups); + let partial: Vec> = x + .par_chunks(rows_per_group * d) + .map(|group| { + let mut gram = Array2::::zeros((d, d)); + let mut block = vec![0.0f64; GRAM_BLOCK.min(group.len() / d) * d]; + for rows in group.chunks(GRAM_BLOCK * d) { + let count = rows.len() / d; + centre_block(rows, mean, d, &mut block[..count * d]); + let view = ArrayView2::from_shape((count, d), &block[..count * d]) + .expect("block has the shape it was allocated with"); + ndarray::linalg::general_mat_mul(1.0, &view.t(), &view, 1.0, &mut gram); + } + gram + }) + .collect(); + let mut total = vec![0.0f64; d * d]; + for gram in &partial { + for (t, g) in total.iter_mut().zip(gram.iter()) { + *t += *g; + } + } + total +} + +fn gram_by_bands(x: &[f32], n: usize, d: usize, mean: &[f64], band_rows: usize) -> Vec { + // about 4 MB of f64 values per block + let block_rows = ((1usize << 19) / d).clamp(64, 4096).min(n); + let mut total = vec![0.0f64; d * d]; + let mut block = vec![0.0f64; block_rows * d]; + for rows in x.chunks(block_rows * d) { + let count = rows.len() / d; + block[..count * d] + .par_chunks_mut(GRAM_BLOCK * d) + .zip(rows.par_chunks(GRAM_BLOCK * d)) + .for_each(|(centred, rows)| centre_block(rows, mean, d, centred)); + let view = ArrayView2::from_shape((count, d), &block[..count * d]) + .expect("block has the shape it was allocated with"); + total + .par_chunks_mut(band_rows * d) + .enumerate() + .for_each(|(band, target)| { + let first = band * band_rows; + let height = target.len() / d; + let mut target = ArrayViewMut2::from_shape((height, d), target) + .expect("band has the shape it was split into"); + let columns = view.slice(ndarray::s![.., first..first + height]); + // rows [first, first + height) of block^T * block + ndarray::linalg::general_mat_mul(1.0, &columns.t(), &view, 1.0, &mut target); + }); + } + total +} + +/// Column means and the (unbiased) covariance matrix of an `n x d` row-major +/// matrix, both in f64. The covariance is returned row-major, `d x d`. +/// Runs on the current rayon pool; the result does not depend on its size. +pub fn column_mean_and_covariance(x: &[f32], n: usize, d: usize) -> (Vec, Vec) { + assert_eq!(x.len(), n * d); + if n == 0 || d == 0 { + return (vec![0.0; d], vec![0.0; d * d]); + } + let rows_per_group = n.div_ceil(mean_groups(n)); + let partial_sums: Vec> = x + .par_chunks(rows_per_group * d) + .map(|group| { + let mut sums = vec![0.0f64; d]; + for row in group.chunks_exact(d) { + for (s, v) in sums.iter_mut().zip(row) { + *s += *v as f64; } - let norm = sum_sq.sqrt().max(1e-10); - let inv_norm = 1.0 / norm; - for v in slice.iter_mut() { - *v *= inv_norm; + } + sums + }) + .collect(); + let mut mean = vec![0.0f64; d]; + for sums in &partial_sums { + for (m, s) in mean.iter_mut().zip(sums) { + *m += *s; + } + } + for m in mean.iter_mut() { + *m /= n as f64; + } + + let mut covariance = match gram_plan(n, d) { + GramPlan::RowGroups(groups) => gram_by_row_groups(x, n, d, &mean, groups), + GramPlan::Bands(band_rows) => gram_by_bands(x, n, d, &mean, band_rows), + }; + let scale = 1.0 / (n.max(2) - 1) as f64; + for value in covariance.iter_mut() { + *value *= scale; + } + // exact symmetry, whatever rounding the products picked up + for i in 0..d { + for j in (i + 1)..d { + let v = 0.5 * (covariance[i * d + j] + covariance[j * d + i]); + covariance[i * d + j] = v; + covariance[j * d + i] = v; + } + } + (mean, covariance) +} + +/// Rows projected at once. +const PROJECT_BLOCK: usize = 512; + +/// `out = (x - mean) * transform` for an `n x d` matrix `x` and a `d x k` +/// transform; `out` is `n x k`. +pub fn center_and_project( + x: &[f32], + d: usize, + mean: &[f32], + transform: ArrayView2, + out: &mut [f32], +) { + let k = transform.ncols(); + assert_eq!(transform.nrows(), d); + assert_eq!(mean.len(), d); + if d == 0 || k == 0 || x.is_empty() { + return; + } + assert_eq!(x.len() / d * k, out.len()); + out.par_chunks_mut(PROJECT_BLOCK * k) + .zip(x.par_chunks(PROJECT_BLOCK * d)) + .for_each(|(dst, src)| { + let rows = src.len() / d; + let mut centered = Array2::::zeros((rows, d)); + for (c, s) in centered + .as_slice_mut() + .unwrap() + .chunks_exact_mut(d) + .zip(src.chunks_exact(d)) + { + for ((c, s), m) in c.iter_mut().zip(s).zip(mean) { + *c = *s - *m; } - }); + } + let projected = centered.dot(&transform); + dst.copy_from_slice(projected.as_slice().unwrap()); + }); +} + +/// In-place variant of [`center_and_project`] for a square (`d x d`) transform. +pub fn center_and_project_inplace( + x: &mut [f32], + d: usize, + mean: &[f32], + transform: ArrayView2, +) { + assert_eq!(transform.nrows(), d); + assert_eq!(transform.ncols(), d); + assert_eq!(mean.len(), d); + if d == 0 || x.is_empty() { + return; } + x.par_chunks_mut(PROJECT_BLOCK * d).for_each(|chunk| { + let rows = chunk.len() / d; + let mut centered = Array2::::zeros((rows, d)); + for (c, s) in centered + .as_slice_mut() + .unwrap() + .chunks_exact_mut(d) + .zip(chunk.chunks_exact(d)) + { + for ((c, s), m) in c.iter_mut().zip(s).zip(mean) { + *c = *s - *m; + } + } + let projected = centered.dot(&transform); + chunk.copy_from_slice(projected.as_slice().unwrap()); + }); +} + +/// Kept for the Rust API and the snapshot tests. +pub struct NdArrayMatrix; - pub fn embed_full( - sparse_matrix_reader: &SparseMatrix, - initial: Array2, +impl NdArrayMatrix { + pub fn multiply( + graph: &SparseMatrix, + other: ArrayView2, markov_type: MarkovType, - num_iterations: usize, - residual_weight: f32, + num_workers: usize, ) -> Array2 { - let shape = initial.raw_dim(); - let mut src = initial; - let mut dst = Array2::::zeros(shape); - let use_residual = residual_weight > 0.0 && residual_weight < 1.0; + let dim = other.ncols(); + let input = other.as_standard_layout(); + let x = input.as_slice().expect("standard layout"); + let mut out = vec![0f32; x.len()]; + thread_pool(num_workers).install(|| propagate(graph, x, &mut out, dim, markov_type)); + Array2::from_shape_vec((other.nrows(), dim), out).expect("matching shape") + } +} - for _ in 0..num_iterations { - Self::multiply_into(sparse_matrix_reader, src.view(), &markov_type, &mut dst); +#[cfg(test)] +mod tests { + use super::*; - if use_residual { - let alpha = 1.0 - residual_weight; - let rw = residual_weight; - let dst_slice = dst.as_slice_mut().unwrap(); - let src_slice = src.as_slice().unwrap(); - for j in 0..dst_slice.len() { - dst_slice[j] = alpha * dst_slice[j] + rw * src_slice[j]; + fn ids(n: usize) -> Vec { + (0..n).map(|i| format!("entity_{}", i)).collect() + } + + fn ring_graph(n: usize) -> SparseMatrix { + let lines: Vec = (0..n) + .map(|i| format!("v{} v{} v{}", i, (i + 1) % n, (i * 7 + 3) % n)) + .collect(); + let config = + crate::configuration::Configuration::new("complex::reflexive::v", 16, Some(2)).unwrap(); + crate::pipeline::build_graph_from_lines(&config, &lines, None) + .unwrap() + .0 + } + + #[test] + fn selected_rows_match_the_full_propagation() { + let graph = ring_graph(300); + let n = graph.num_entities(); + let dim = 9; + let x = initialize(&graph.entity_ids, dim, 4); + let rows: Vec = (0..500).map(|i| (i * 37 + 11) % n).collect(); + for kind in [MarkovType::Left, MarkovType::Symmetric] { + let mut full = vec![0f32; n * dim]; + propagate(&graph, &x, &mut full, dim, kind); + let mut selected = vec![f32::NAN; rows.len() * dim]; + propagate_selected(&graph, &x, &rows, &mut selected, dim, kind); + for (i, &row) in rows.iter().enumerate() { + assert_eq!( + &selected[i * dim..(i + 1) * dim], + &full[row * dim..(row + 1) * dim] + ); + } + } + let mut empty: Vec = Vec::new(); + propagate_selected(&graph, &x, &[], &mut empty, dim, MarkovType::Left); + } + + fn graph_of(columns: &str, lines: &[String]) -> SparseMatrix { + let config = crate::configuration::Configuration::new(columns, 16, Some(2)).unwrap(); + crate::pipeline::build_graph_from_lines(&config, lines, None) + .unwrap() + .0 + } + + fn ring(nodes: usize, separator: &str) -> Vec { + (0..nodes) + .map(|i| format!("v{}{}v{}", i, separator, (i + 1) % nodes)) + .collect() + } + + fn clique(nodes: usize, separator: &str) -> Vec { + (0..nodes) + .flat_map(|i| (i + 1..nodes).map(move |j| format!("v{}{}v{}", i, separator, j))) + .collect() + } + + #[test] + fn suggested_iterations_follow_density_purpose_and_normalisation() { + // a ring: every entity has exactly two neighbours + let pair = graph_of("a b", &ring(50, "\t")); + assert_eq!(pair.mean_neighbours(), 2.0); + assert_eq!(pair.self_weight_share(), 0.0); + let rounds = |purpose| suggested_iterations(&pair, MarkovType::Left, purpose); + assert_eq!(rounds(Purpose::Similarity), 8); // 12 / sqrt(2) = 8.5 + assert_eq!(rounds(Purpose::General), 11); // 16 / sqrt(2) = 11.3 + assert_eq!(rounds(Purpose::Classification), 17); // 24 / sqrt(2) = 17.0 + // symmetric: x 1.5 + assert_eq!( + suggested_iterations(&pair, MarkovType::Symmetric, Purpose::General), + 17 + ); + // a clique of 26: 25 neighbours each, 16 / 5 = 3.2 + let dense = graph_of("a b", &clique(26, "\t")); + assert_eq!( + suggested_iterations(&dense, MarkovType::Left, Purpose::General), + 3 + ); + } + + #[test] + fn suggested_iterations_of_a_lazy_walk() { + // the ring as a reflexive column: half of every row is the self-loop + let lazy = graph_of("complex::reflexive::v", &ring(50, " ")); + assert_eq!(lazy.mean_neighbours(), 2.0); + assert!((lazy.self_weight_share() - 0.5).abs() < 1e-12); + // twice the rounds of the plain ring: 2 * 16 / sqrt(2) = 22.6 + assert_eq!( + suggested_iterations(&lazy, MarkovType::Left, Purpose::General), + 23 + ); + // a dense lazy walk still needs 8 rounds to forget the initial vectors (0.5^8 = 1/256) + let dense = graph_of("complex::reflexive::v", &clique(40, " ")); + for purpose in [ + Purpose::Similarity, + Purpose::General, + Purpose::Classification, + ] { + assert_eq!(suggested_iterations(&dense, MarkovType::Left, purpose), 8); + } + } + + #[test] + fn suggested_iterations_stay_in_range_on_degenerate_graphs() { + let general = + |graph: &SparseMatrix| suggested_iterations(graph, MarkovType::Left, Purpose::General); + assert_eq!(general(&SparseMatrix::empty()), 16); + // one hyperedge with a single entity: only a self-loop + let alone = graph_of("complex::reflexive::v", &["x".to_string()]); + assert_eq!(alone.self_weight_share(), 1.0); + assert_eq!(general(&alone), 1); + // a very dense plain graph gets the minimum of two rounds + let dense = graph_of("a b", &clique(100, "\t")); + assert_eq!(general(&dense), 2); + assert_eq!( + suggested_iterations(&dense, MarkovType::Symmetric, Purpose::Classification), + 4 // 24 * 1.5 / sqrt(99) = 3.6 + ); + } + + /// A star whose centre has more entries than `HUB_NNZ`, plus a ring among the leaves. + fn hub_graph(leaves: usize) -> SparseMatrix { + let mut lines: Vec = (0..leaves).map(|i| format!("hub leaf{}", i)).collect(); + lines.extend((0..leaves).map(|i| format!("leaf{} leaf{}", i, (i + 1) % leaves))); + let config = + crate::configuration::Configuration::new("complex::reflexive::v", 16, Some(2)).unwrap(); + crate::pipeline::build_graph_from_lines(&config, &lines, None) + .unwrap() + .0 + } + + #[test] + fn tasks_cover_all_rows_and_isolate_hubs() { + let entries = [10usize, 5000, 3, HUB_NNZ + 1, 7, 7, TASK_NNZ, 1]; + let bounds = balanced_tasks(entries.iter().copied()); + assert_eq!(bounds.first(), Some(&0)); + assert_eq!(bounds.last(), Some(&entries.len())); + assert!(bounds.windows(2).all(|w| w[0] < w[1])); + // the hub (position 3) is a task of its own + assert!(bounds.windows(2).any(|w| w == [3, 4])); + // no other task exceeds the budget unless it is a single row + for w in bounds.windows(2) { + let total: usize = entries[w[0]..w[1]].iter().sum(); + assert!( + total <= TASK_NNZ || w[1] - w[0] == 1, + "{:?} holds {}", + w, + total + ); + } + assert_eq!(balanced_tasks(std::iter::empty()), vec![0]); + // many empty rows are still split up + let bounds = balanced_tasks(std::iter::repeat_n(0, 3 * TASK_ROWS + 5)); + assert_eq!(bounds.len(), 5); + } + + /// Rows that are summed in segments (hubs) must not depend on the thread count, + /// must agree with the plain definition of the product, and must come out the + /// same through `propagate_selected`. + #[test] + fn hub_rows_are_exact_and_thread_independent() { + let leaves = HUB_NNZ + 300; + let graph = hub_graph(leaves); + let n = graph.num_entities(); + let hub = graph.index_of("hub").unwrap(); + assert!(graph.row_range(hub).len() > HUB_NNZ); + let dim = 5; + let x = initialize(&graph.entity_ids, dim, 1); + for kind in [MarkovType::Left, MarkovType::Symmetric] { + let mut single = vec![0f32; n * dim]; + thread_pool(1).install(|| propagate(&graph, &x, &mut single, dim, kind)); + let mut many = vec![0f32; n * dim]; + thread_pool(7).install(|| propagate(&graph, &x, &mut many, dim, kind)); + assert_eq!(single, many); + + let normalization = match kind { + MarkovType::Left => crate::sparse_matrix::Normalization::Left, + MarkovType::Symmetric => crate::sparse_matrix::Normalization::Symmetric, + }; + for row in [hub, 0, n - 1] { + for column in 0..dim { + let direct: f64 = graph + .row_range(row) + .map(|k| { + graph.normalized_value(row, k, normalization) as f64 + * x[graph.indices[k] as usize * dim + column] as f64 + }) + .sum(); + let got = single[row * dim + column] as f64; + assert!( + (got - direct).abs() < 1e-5, + "row {}: {} vs {}", + row, + got, + direct + ); } } - Self::l2_normalize_inplace(&mut dst); + let rows = [hub, 3, hub, n - 1]; + let mut selected = vec![f32::NAN; rows.len() * dim]; + thread_pool(3) + .install(|| propagate_selected(&graph, &x, &rows, &mut selected, dim, kind)); + for (i, &row) in rows.iter().enumerate() { + assert_eq!( + &selected[i * dim..(i + 1) * dim], + &single[row * dim..(row + 1) * dim] + ); + } + } + } + + /// The fused pass must give exactly what separate passes give. + #[test] + fn finishing_rows_in_the_propagation_pass_changes_nothing() { + let graph = ring_graph(500); + let n = graph.num_entities(); + let dim = 12; + let x = initialize(&graph.entity_ids, dim, 3); + let mut separate = vec![0f32; n * dim]; + propagate(&graph, &x, &mut separate, dim, MarkovType::Left); + l2_normalize_rows(&mut separate, dim); + let mut fused = vec![0f32; n * dim]; + propagate_then(&graph, &x, &mut fused, dim, MarkovType::Left, |_, row| { + l2_normalize_row(row) + }); + assert_eq!(separate, fused); + } - std::mem::swap(&mut src, &mut dst); + /// The result of the in-place loop must end up in the caller's buffer whatever + /// the number of rounds, and equal the rounds applied one by one. + #[test] + fn iterating_in_place_matches_separate_rounds() { + let graph = ring_graph(200); + let n = graph.num_entities(); + let dim = 6; + for rounds in 0..5 { + let mut expected = initialize(&graph.entity_ids, dim, 2); + for _ in 0..rounds { + let mut next = vec![0f32; n * dim]; + propagate(&graph, &expected, &mut next, dim, MarkovType::Symmetric); + l2_normalize_rows(&mut next, dim); + expected = next; + } + let mut current = initialize(&graph.entity_ids, dim, 2); + let mut scratch = vec![f32::NAN; n * dim]; + let done = iterate( + &graph, + &mut current, + &mut scratch, + dim, + MarkovType::Symmetric, + rounds, + 0.0, + 0.0, + ); + assert_eq!(done, rounds); + assert_eq!(current, expected, "{} rounds", rounds); } - src } - pub fn embed_full_with_convergence( - sparse_matrix_reader: &SparseMatrix, - initial: Array2, - markov_type: MarkovType, - max_iterations: usize, - residual_weight: f32, - convergence_threshold: f32, - ) -> (Array2, usize) { - let shape = initial.raw_dim(); - let mut src = initial; - let mut dst = Array2::::zeros(shape); - let use_residual = residual_weight > 0.0 && residual_weight < 1.0; - let check_convergence = convergence_threshold > 0.0; - let mut actual_iterations = max_iterations; - let dim = shape[1]; - - for iter in 0..max_iterations { - Self::multiply_into(sparse_matrix_reader, src.view(), &markov_type, &mut dst); + /// A matrix with weights of every size, an entity without any entry, and two rows + /// that are long enough to be summed in segments. + fn uneven_graph() -> SparseMatrix { + let n = 3 * HUB_NNZ; + let (mut indptr, mut indices, mut values) = (vec![0u64], Vec::new(), Vec::new()); + let mut state = 0x2545_F491_4F6C_DD1Du64; + let mut next = move || { + state = splitmix64(state); + state + }; + for row in 0..n { + let entries = match row { + 7 => 0, + 3 | 500 => HUB_NNZ + 1000 + row, + _ => 1 + (next() % 12) as usize, + }; + for _ in 0..entries { + indices.push((next() % n as u64) as u32); + values.push(1.0 + (next() % 1000) as f32 / 97.0); + } + indptr.push(indices.len() as u64); + } + let row_sums = (0..n) + .map(|row| { + values[indptr[row] as usize..indptr[row + 1] as usize] + .iter() + .map(|&v| v as f64) + .sum() + }) + .collect(); + SparseMatrix::from_parts( + vec![], + vec![], + ids(n), + vec![0; n], + row_sums, + indptr, + indices, + values, + ) + } - if use_residual { - let alpha = 1.0 - residual_weight; - let rw = residual_weight; - let dst_slice = dst.as_slice_mut().unwrap(); - let src_slice = src.as_slice().unwrap(); - for j in 0..dst_slice.len() { - dst_slice[j] = alpha * dst_slice[j] + rw * src_slice[j]; + /// The blocked loop behind `embed` must give, bit for bit, what the row-major + /// loop gives - whatever the dimension, the normalisation and the thread count. + #[test] + fn embedding_in_blocks_matches_the_row_major_loop() { + let graph = uneven_graph(); + let n = graph.num_entities(); + assert!(graph.row_range(3).len() > HUB_NNZ && graph.row_range(7).is_empty()); + for (dim, rounds) in [(5, 2), (16, 3), (37, 2), (64, 4)] { + for kind in [MarkovType::Left, MarkovType::Symmetric] { + let mut expected = initialize(&graph.entity_ids, dim, 5); + let mut scratch = vec![f32::NAN; n * dim]; + iterate( + &graph, + &mut expected, + &mut scratch, + dim, + kind, + rounds, + 0.0, + 0.0, + ); + assert!(expected.iter().all(|v| v.is_finite())); + for threads in [1, 4] { + let (blocked, done) = thread_pool(threads) + .install(|| embed(&graph, dim, 5, kind, rounds, 0.0, 0.0)); + assert_eq!(done, rounds); + assert!( + blocked == expected, + "dim {}, {} rounds, {:?}, {} threads", + dim, + rounds, + kind, + threads + ); } } + } + } - Self::l2_normalize_inplace(&mut dst); + #[test] + fn init_is_uniform_and_in_range() { + let dim = 256; + let x = initialize(&ids(2000), dim, 0); + let (mut min, mut max, mut sum, mut sum_sq) = (f32::MAX, f32::MIN, 0f64, 0f64); + for v in &x { + min = min.min(*v); + max = max.max(*v); + sum += *v as f64; + sum_sq += (*v as f64) * (*v as f64); + } + let mean = sum / x.len() as f64; + let variance = sum_sq / x.len() as f64 - mean * mean; + assert!(min >= -1.0 && max < 1.0); + assert!(mean.abs() < 0.01, "mean {}", mean); + assert!((variance - 1.0 / 3.0).abs() < 0.01, "variance {}", variance); + } - if check_convergence && iter > 0 { - let dst_slice = dst.as_slice().unwrap(); - let src_slice = src.as_slice().unwrap(); - let mut diff: f32 = 0.0; - for j in 0..dst_slice.len() { - let delta = dst_slice[j] - src_slice[j]; - diff += delta * delta; + /// Vectors of different entities must be (nearly) orthogonal: the cosine of a + /// random pair has standard deviation 1/sqrt(dim). + #[test] + fn init_vectors_of_different_entities_are_uncorrelated() { + for dim in [64usize, 256, 1024] { + let n = 400; + let x = initialize(&ids(n), dim, 0); + let row = |i: usize| &x[i * dim..(i + 1) * dim]; + let norm = |r: &[f32]| r.iter().map(|v| (*v as f64).powi(2)).sum::().sqrt(); + let mut sum_sq = 0f64; + let mut count = 0usize; + let mut worst = 0f64; + for i in 0..n { + for j in (i + 1)..n { + let dot: f64 = row(i) + .iter() + .zip(row(j)) + .map(|(a, b)| *a as f64 * *b as f64) + .sum(); + let cosine = dot / (norm(row(i)) * norm(row(j))); + sum_sq += cosine * cosine; + worst = worst.max(cosine.abs()); + count += 1; } - let rmse = (diff / (dst.shape()[0] * dim) as f32).sqrt(); - if rmse < convergence_threshold { - std::mem::swap(&mut src, &mut dst); - actual_iterations = iter + 1; - break; + } + let std = (sum_sq / count as f64).sqrt(); + let ideal = 1.0 / (dim as f64).sqrt(); + assert!( + std < 1.15 * ideal, + "dim {}: cosine std {} vs ideal {}", + dim, + std, + ideal + ); + assert!(worst < 8.0 * ideal, "dim {}: worst |cosine| {}", dim, worst); + } + } + + #[test] + fn init_depends_on_name_seed_and_column_only() { + let a = initialize(&ids(50), 32, 7); + let b = initialize(&ids(50), 32, 7); + assert_eq!(a, b); + // a prefix of a wider initialisation is the narrower one + let wide = initialize(&ids(50), 64, 7); + for i in 0..50 { + assert_eq!(&wide[i * 64..i * 64 + 32], &a[i * 32..(i + 1) * 32]); + } + // the vector of an entity does not depend on which other entities exist + let single = initialize(&["entity_13".to_string()], 32, 7); + assert_eq!(&a[13 * 32..14 * 32], &single[..]); + } + + /// Seeds must give unrelated matrices (they used to be column shifts of each other). + #[test] + fn init_seeds_are_independent() { + let dim = 128; + let a = initialize(&ids(300), dim, 0); + let b = initialize(&ids(300), dim, 1); + for shift in 0..4 { + let mut dot = 0f64; + let mut count = 0usize; + for i in 0..300 { + for c in 0..(dim - shift) { + dot += a[i * dim + c + shift] as f64 * b[i * dim + c] as f64; + count += 1; } } + let correlation = dot / count as f64 * 3.0; + assert!( + correlation.abs() < 0.03, + "shift {}: correlation {}", + shift, + correlation + ); + } + } - std::mem::swap(&mut src, &mut dst); + #[test] + fn both_covariance_plans_agree() { + let (n, d) = (700usize, 300usize); + let x: Vec = (0..n * d) + .map(|i| ((i as f32 * 0.13).sin() * 2.0) + ((i % 11) as f32) * 0.1) + .collect(); + let mean: Vec = (0..d) + .map(|c| (0..n).map(|r| x[r * d + c] as f64).sum::() / n as f64) + .collect(); + let by_groups = thread_pool(3).install(|| gram_by_row_groups(&x, n, d, &mean, 5)); + let by_bands = thread_pool(3).install(|| gram_by_bands(&x, n, d, &mean, 64)); + for (a, b) in by_groups.iter().zip(&by_bands) { + assert!((a - b).abs() <= 1e-9 * (1.0 + a.abs()), "{} vs {}", a, b); + } + // neither depends on the number of threads + let single = thread_pool(1).install(|| gram_by_row_groups(&x, n, d, &mean, 5)); + assert_eq!(by_groups, single); + let single = thread_pool(1).install(|| gram_by_bands(&x, n, d, &mean, 64)); + assert_eq!(by_bands, single); + } + + #[test] + fn covariance_plan_follows_the_memory_budget() { + assert_eq!(gram_plan(100_000, 256), GramPlan::RowGroups(32)); + assert_eq!(gram_plan(13_471, 256), GramPlan::RowGroups(14)); + assert_eq!(gram_plan(500, 64), GramPlan::RowGroups(1)); + // one matrix per group would exceed the input itself here + assert_eq!(gram_plan(30_000, 1024), GramPlan::Bands(64)); + assert_eq!(gram_plan(100_000, 4096), GramPlan::Bands(128)); + assert_eq!(gram_plan(10_000_000, 4096), GramPlan::RowGroups(64)); + } + + #[test] + fn covariance_matches_direct_computation() { + let (n, d) = (3000usize, 7usize); + let x: Vec = (0..n * d) + .map(|i| ((i as f32 * 0.37).sin() * 3.0) + (i % d) as f32) + .collect(); + let (mean, covariance) = thread_pool(3).install(|| column_mean_and_covariance(&x, n, d)); + let single = thread_pool(1).install(|| column_mean_and_covariance(&x, n, d)); + assert_eq!(mean, single.0); + assert_eq!(covariance, single.1); + for c in 0..d { + let direct: f64 = (0..n).map(|r| x[r * d + c] as f64).sum::() / n as f64; + assert!((mean[c] - direct).abs() < 1e-9); + } + for a in 0..d { + for b in 0..d { + let direct: f64 = (0..n) + .map(|r| (x[r * d + a] as f64 - mean[a]) * (x[r * d + b] as f64 - mean[b])) + .sum::() + / (n - 1) as f64; + assert!((covariance[a * d + b] - direct).abs() < 1e-9); + } + } + } + + #[test] + fn projection_variants_agree() { + let (n, d) = (1300usize, 5usize); + let x: Vec = (0..n * d).map(|i| (i as f32 * 0.11).cos()).collect(); + let mean: Vec = (0..d).map(|c| c as f32 * 0.1).collect(); + let transform = Array2::from_shape_fn((d, d), |(i, j)| ((i * 3 + j) as f32 * 0.7).sin()); + let mut out = vec![0f32; n * d]; + center_and_project(&x, d, &mean, transform.view(), &mut out); + let mut inplace = x.clone(); + center_and_project_inplace(&mut inplace, d, &mean, transform.view()); + assert_eq!(out, inplace); + for r in [0usize, 511, 512, 1299] { + for j in 0..d { + let direct: f32 = (0..d) + .map(|c| (x[r * d + c] - mean[c]) * transform[[c, j]]) + .sum(); + assert!((out[r * d + j] - direct).abs() < 1e-4); + } } - (src, actual_iterations) } } diff --git a/src/entity.rs b/src/entity.rs index 7da6697..03bffd3 100644 --- a/src/entity.rs +++ b/src/entity.rs @@ -1,140 +1,285 @@ -use itertools::{Itertools, Product}; use std::hash::Hasher; -use std::ops::Range; -use std::sync::Arc; -use smallvec::{IntoIter, SmallVec}; +use smallvec::SmallVec; use twox_hash::XxHash64; use crate::configuration::Configuration; -use crate::sparse_matrix_builder::NodeIndexerBuilder; -/// Indicates how many elements in a vector can be placed on Stack (used by smallvec crate). The rest -/// of the vector is placed on Heap. +/// Number of entities of one field kept on the stack before spilling to the heap. pub const SMALL_VECTOR_SIZE: usize = 8; -#[derive(Debug, Clone)] -pub struct Hyperedge { - hashes: SmallVec<[u64; SMALL_VECTOR_SIZE]>, - slices: [Range; 2], +pub type Tokens<'a> = SmallVec<[&'a str; SMALL_VECTOR_SIZE]>; + +/// Hash identifying an entity. Entities are identified by their name only, so the +/// same name appearing in two columns denotes the same entity. +#[inline(always)] +pub fn hash_entity(entity: &str) -> u64 { + let mut hasher = XxHash64::default(); + hasher.write(entity.as_bytes()); + hasher.finish() } -impl Hyperedge { - #[inline] - pub fn nodes(&self, column_id: usize) -> SmallVec<[u64; SMALL_VECTOR_SIZE]> { - let slice = self.slices.get(column_id).unwrap(); - let mut v = SmallVec::with_capacity(slice.len()); - for ix in slice.start..slice.end { - v.push(self.hashes[ix as usize]) - } - v - } +/// Why a line could not be used. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LineError { + /// Wrong number of fields for the declared columns. + ColumnCount { expected: usize, found: usize }, + /// A field that should hold entities is empty. + EmptyField, + /// The weight field is not a finite, non-negative number. + BadWeight, + /// The line is not valid UTF-8. + InvalidUtf8, +} - #[inline(always)] - pub fn edges_iter( - &self, - col_id_a: u8, - col_id_b: u8, - ) -> Product, IntoIter<[u64; 8]>> { - let nodes_a = self.nodes(col_id_a as usize); - let nodes_b = self.nodes(col_id_b as usize); - nodes_a.into_iter().cartesian_product(nodes_b) +impl LineError { + pub fn describe(&self) -> String { + match self { + LineError::ColumnCount { expected, found } => format!( + "expected {} field(s) but found {} (fields are separated by a tab or, \ + if the line has no tab, by a comma; entities inside a field by spaces)", + expected, found + ), + LineError::EmptyField => "a field holds no entity".to_string(), + LineError::BadWeight => "the weight is not a finite, non-negative number".to_string(), + LineError::InvalidUtf8 => "the line is not valid UTF-8".to_string(), + } } +} - pub fn edges_num(&self, col_id_a: u8, col_id_b: u8) -> usize { - self.slices[col_id_a as usize].len() * self.slices[col_id_b as usize].len() - } +/// A line split into its entity fields. +pub struct ParsedLine<'a> { + /// Entities of every entity column, in column order. + pub fields: SmallVec<[Tokens<'a>; 4]>, + pub weight: f32, } -pub struct EntityProcessor<'a, S: NodeIndexerBuilder> { - config: &'a Configuration, - not_ignored_columns_count: u16, - node_indexer: Arc, +/// Largest weight accepted for a single line / edge. +pub const MAX_WEIGHT: f32 = 1e9; + +#[inline] +pub fn weight_is_valid(weight: f32) -> bool { + weight.is_finite() && (0.0..=MAX_WEIGHT).contains(&weight) } -impl<'a, S: NodeIndexerBuilder> EntityProcessor<'a, S> { - pub fn new(config: &'a Configuration, node_indexer: Arc) -> EntityProcessor<'a, S> { - let not_ignored_columns_count = config.columns.len() as u16; - EntityProcessor { - config, - not_ignored_columns_count, - node_indexer, - } +/// Splits a line into fields and entities. +/// +/// Returns `Ok(None)` for blank lines. Fields are separated by a tab; a line without +/// any tab is split on commas instead; a line with neither is a single field. +/// Entities within a field are separated by spaces. A non-`complex` field +/// contributes its first entity only. +pub fn parse_line<'a>( + line: &'a str, + config: &Configuration, +) -> Result>, LineError> { + let trimmed = line.trim(); + if trimmed.is_empty() { + return Ok(None); } - /// Every row can create few combinations (cartesian products) which are hashed and provided for sparse matrix creation. - /// `row` - array of strings such as: ("userId1", "productId1 productId2", "brandId1"). - pub fn process_row_and_get_edges( - &self, - row: &[SmallVec<[&str; SMALL_VECTOR_SIZE]>], - ) -> Hyperedge { - let mut hashes: SmallVec<[u64; SMALL_VECTOR_SIZE]> = - SmallVec::with_capacity(self.not_ignored_columns_count as usize); - let mut slices: [Range; 2] = [0..0, 0..0]; - let mut reflexive_count = 0; - let mut current_offset = 0u32; - - for (i, column_entities) in row.iter().enumerate() { - let column = &self.config.columns[i]; - let column_id = i as u8; - if column.complex { - for entity in column_entities { - let hash = hash_entity(entity); - hashes.push(hash); - self.node_indexer.process(hash, entity, column_id); - } - let length = column_entities.len() as u32; - slices[i] = current_offset..(current_offset + length); - if column.reflexive { - // put reflexive column data to the end of the buffers - let reflexive_id = (self.not_ignored_columns_count + reflexive_count) as usize; - slices[reflexive_id] = current_offset..(current_offset + length); - reflexive_count += 1; + let expected = config.columns.len(); + let separator = if trimmed.contains('\t') { + Some('\t') + } else if trimmed.contains(',') { + Some(',') + } else { + None + }; + + let mut fields: SmallVec<[Tokens<'a>; 4]> = SmallVec::new(); + let mut weight = 1.0f32; + let mut found = 0usize; + + let mut handle_field = |index: usize, field: &'a str| -> Result<(), LineError> { + // Fields beyond the declared ones only matter for the error message. + let Some(column) = config.columns.get(index) else { + return Ok(()); + }; + if column.weight { + weight = field + .trim() + .parse::() + .ok() + .filter(|w| weight_is_valid(*w)) + .ok_or(LineError::BadWeight)?; + return Ok(()); + } + let mut tokens: Tokens<'a> = SmallVec::new(); + for token in field.split(' ') { + let token = token.trim(); + if token.is_empty() { + continue; + } + tokens.push(token); + if !column.complex { + break; + } + } + if tokens.is_empty() { + return Err(LineError::EmptyField); + } + fields.push(tokens); + Ok(()) + }; + + let mut first_error = None; + match separator { + Some(sep) => { + for field in trimmed.split(sep) { + if let Err(e) = handle_field(found, field) { + first_error.get_or_insert(e); } - current_offset += length; - } else { - let entity = column_entities.first().unwrap(); - let hash = hash_entity(entity); - hashes.push(hash); - self.node_indexer.process(hash, entity, column_id); - let length = 1u32; - slices[i] = current_offset..(current_offset + length); - current_offset += length; + found += 1; + } + } + None => { + if let Err(e) = handle_field(0, trimmed) { + first_error.get_or_insert(e); } + found = 1; } - Hyperedge { hashes, slices } } + + if found != expected { + return Err(LineError::ColumnCount { expected, found }); + } + if let Some(e) = first_error { + return Err(e); + } + Ok(Some(ParsedLine { fields, weight })) } -#[inline(always)] -pub fn hash_entity(entity: &str) -> u64 { - let mut hasher = XxHash64::default(); - hasher.write(entity.as_bytes()); - hasher.finish() +/// Formats an integer identifier exactly like Python's `str(int)`, without allocating. +pub struct IntBuffer { + bytes: [u8; 20], + start: usize, +} + +impl IntBuffer { + #[inline] + pub fn new(value: i64) -> IntBuffer { + let mut bytes = [0u8; 20]; + let mut pos = bytes.len(); + let negative = value < 0; + let mut rest = value.unsigned_abs(); + loop { + pos -= 1; + bytes[pos] = b'0' + (rest % 10) as u8; + rest /= 10; + if rest == 0 { + break; + } + } + if negative { + pos -= 1; + bytes[pos] = b'-'; + } + IntBuffer { bytes, start: pos } + } + + #[inline] + pub fn as_str(&self) -> &str { + // Only ASCII digits and '-' are ever written. + std::str::from_utf8(&self.bytes[self.start..]).unwrap() + } } #[cfg(test)] mod tests { - use smallvec::{smallvec, SmallVec}; + use super::*; + + fn config(columns: &str) -> Configuration { + Configuration::new(columns, 16, Some(1)).unwrap() + } + + fn fields(line: &str, columns: &str) -> Vec> { + parse_line(line, &config(columns)) + .unwrap() + .unwrap() + .fields + .iter() + .map(|f| f.iter().map(|t| t.to_string()).collect()) + .collect() + } + + #[test] + fn int_buffer_matches_display() { + for v in [0i64, 7, -7, 10, 1234567890123, i64::MAX, i64::MIN, -1] { + assert_eq!(IntBuffer::new(v).as_str(), v.to_string()); + } + } - use crate::entity::{Hyperedge, SMALL_VECTOR_SIZE}; + #[test] + fn single_reflexive_field() { + assert_eq!( + fields("a b c ", "complex::reflexive::x"), + vec![vec!["a", "b", "c"]] + ); + } + + #[test] + fn tab_and_comma_separated_fields() { + assert_eq!( + fields("u1\tp1 p2", "user complex::product"), + vec![vec!["u1"], vec!["p1", "p2"]] + ); + assert_eq!( + fields("u1, p1 p2", "user complex::product"), + vec![vec!["u1"], vec!["p1", "p2"]] + ); + // a simple (non-complex) field keeps its first entity only + assert_eq!( + fields("u1 u9\tp1 p2", "user product"), + vec![vec!["u1"], vec!["p1"]] + ); + } + + #[test] + fn weight_field() { + let c = config("user product weight::w"); + let parsed = parse_line("u\tp\t2.5", &c).unwrap().unwrap(); + assert_eq!(parsed.weight, 2.5); + assert_eq!(parsed.fields.len(), 2); + assert_eq!(parse_line("u\tp\t-1", &c).err(), Some(LineError::BadWeight)); + assert_eq!( + parse_line("u\tp\tnan", &c).err(), + Some(LineError::BadWeight) + ); + assert_eq!( + parse_line("u\tp\tabc", &c).err(), + Some(LineError::BadWeight) + ); + } #[test] - fn generate_cartesian_product_hashes() { - // hashes for entities in every column - // column_1: 1 entity - // column_2: 2 entities - // column_3: 3 entities - let slices = [0..2, 2..5]; - let hashes: SmallVec<[u64; SMALL_VECTOR_SIZE]> = smallvec![10, 20, 30, 40, 50]; - let hyperedge = Hyperedge { hashes, slices }; - let combinations: Vec<_> = hyperedge.edges_iter(0, 1).collect(); - assert_eq!((10, 30), *combinations.get(0).unwrap()); - assert_eq!((10, 40), *combinations.get(1).unwrap()); - assert_eq!((10, 50), *combinations.get(2).unwrap()); - assert_eq!((20, 30), *combinations.get(3).unwrap()); - assert_eq!((20, 40), *combinations.get(4).unwrap()); - assert_eq!((20, 50), *combinations.get(5).unwrap()); - assert_eq!(None, combinations.get(6)); + fn malformed_lines() { + let c = config("user product"); + assert!(matches!( + parse_line("u p", &c), + Err(LineError::ColumnCount { + expected: 2, + found: 1 + }) + )); + assert!(matches!( + parse_line("u\tp\tx", &c), + Err(LineError::ColumnCount { + expected: 2, + found: 3 + }) + )); + assert_eq!( + parse_line("u\t ", &c).err(), + Some(LineError::ColumnCount { + expected: 2, + found: 1 + }) + ); + assert_eq!( + parse_line("u\t \tp", &config("a b c")).err(), + Some(LineError::EmptyField) + ); + assert!(parse_line(" ", &c).unwrap().is_none()); + assert!(parse_line("", &c).unwrap().is_none()); } } diff --git a/src/lib.rs b/src/lib.rs index 134b351..d188ae0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,23 +1,28 @@ -use rustc_hash::FxHasher; -use std::collections::HashMap; -use std::hash::Hasher; - -use bincode::{deserialize, serialize}; -use ndarray::{Array1, Array2, ArrayViewMut2, Axis, Ix1, Ix2}; -use numpy::{PyArray, PyArray2, ToPyArray}; -use pyo3::exceptions::{PyRuntimeError, PyValueError}; +use std::borrow::Cow; +use std::ffi::CString; + +use ndarray::Array2; +use numpy::{ + IntoPyArray, PyArray1, PyArray2, PyArrayDescrMethods, PyArrayMethods, PyReadonlyArray1, + PyReadonlyArray2, PyReadwriteArray2, PyUntypedArray, PyUntypedArrayMethods, +}; +use pyo3::exceptions::{ + PyFileNotFoundError, PyIOError, PyRuntimeError, PyRuntimeWarning, PyTypeError, PyValueError, +}; use pyo3::prelude::*; -use pyo3::types::{PyBytes, PyIterator, PyString, PyTuple}; -use rayon::iter::IndexedParallelIterator; -use rayon::iter::ParallelIterator; -use rayon::iter::{IntoParallelIterator, IntoParallelRefIterator}; +use pyo3::pybacked::PyBackedStr; +use pyo3::types::{PyBytes, PyTuple}; -use crate::configuration::Configuration; -use crate::embedding::{MarkovType, NdArrayMatrix}; -use crate::entity::hash_entity; -use crate::pipeline::{build_graph_from_files, build_graph_from_iterator}; -use crate::sparse_matrix::{create_sparse_matrix_descriptor, SparseMatrix, SparseMatrixDescriptor}; +use crate::configuration::{resolve_num_workers, Configuration}; +use crate::embedding::{thread_pool, MarkovType, Purpose}; +use crate::pipeline::{ + build_graph_from_files, build_graph_from_int_edges, build_graph_from_lines, + build_graph_from_rows, build_graph_from_str_edges, +}; +use crate::sparse_matrix::{Normalization, SparseMatrix}; +use crate::sparse_matrix_builder::BuildStats; +pub mod blocked; pub mod configuration; pub mod embedding; pub mod entity; @@ -25,118 +30,498 @@ pub mod pipeline; pub mod sparse_matrix; pub mod sparse_matrix_builder; +/// Turns the outcome of a build into a matrix, a warning (some lines unusable) or +/// an error (nothing usable). +fn finish_build( + py: Python<'_>, + result: Result<(SparseMatrix, BuildStats), String>, +) -> PyResult { + let (matrix, stats) = result.map_err(|message| { + if message.starts_with("Cannot open file") || message.starts_with("Cannot read file") { + PyIOError::new_err(message) + } else { + PyValueError::new_err(message) + } + })?; + if stats.lines_skipped > 0 { + let detail = match &stats.first_bad_line { + Some(bad) => { + let file = bad.pos >> 52; + let line = ((bad.pos >> 16) & 0xF_FFFF_FFFF) + 1; + let place = if file > 0 { + format!("file #{}, line {}", file + 1, line) + } else { + format!("line {}", line) + }; + format!( + " First problem at {}: {} -> {:?}", + place, + bad.error.describe(), + bad.text + ) + } + None => String::new(), + }; + if stats.lines_used == 0 { + return Err(PyValueError::new_err(format!( + "None of the {} input line(s) could be used.{}", + stats.lines_total, detail + ))); + } + let message = format!( + "{} of {} input line(s) were skipped because they could not be parsed.{}", + stats.lines_skipped, stats.lines_total, detail + ); + let message = CString::new(message.replace('\0', " ")) + .map_err(|e| PyRuntimeError::new_err(e.to_string()))?; + PyErr::warn(py, py.get_type::().as_any(), &message, 1)?; + } + Ok(matrix) +} + +fn extract_weights(weights: Option<&Bound<'_, PyAny>>) -> PyResult>> { + let Some(weights) = weights else { + return Ok(None); + }; + if weights.is_none() { + return Ok(None); + } + if let Ok(array) = weights.extract::>() { + return Ok(Some(array.as_array().iter().copied().collect())); + } + if let Ok(array) = weights.extract::>() { + return Ok(Some(array.as_array().iter().map(|w| *w as f32).collect())); + } + let values: Vec = weights.extract().map_err(|_| { + PyTypeError::new_err("weights must be a sequence or a 1-dimensional numpy array of numbers") + })?; + Ok(Some(values.into_iter().map(|w| w as f32).collect())) +} + +fn extract_strings(items: &Bound<'_, PyAny>, what: &str) -> PyResult> { + let mut strings: Vec = match items.len() { + Ok(len) => Vec::with_capacity(len), + Err(_) => Vec::new(), + }; + for item in items.try_iter()? { + let item = item?; + let string = item + .extract::() + .map_err(|_| PyValueError::new_err(format!("{} must be strings", what)))?; + strings.push(string); + } + Ok(strings) +} + +/// A float32 matrix borrowed from numpy, as a row-major slice. Arrays that are not +/// C-contiguous are copied. +fn matrix_data<'a>(array: &'a PyReadonlyArray2<'_, f32>) -> Cow<'a, [f32]> { + // `as_slice` also succeeds for Fortran-ordered arrays (and returns the columns + // one after another), so the layout has to be checked explicitly. + if array.is_c_contiguous() { + if let Ok(slice) = array.as_slice() { + return Cow::Borrowed(slice); + } + } + Cow::Owned(array.as_array().iter().copied().collect()) +} + +/// The row-major data of an array that is written in place. +fn writable_matrix_data<'a>( + array: &'a mut PyReadwriteArray2<'_, f32>, + name: &str, +) -> PyResult<&'a mut [f32]> { + let message = format!("{} must be C-contiguous", name); + if !array.is_c_contiguous() { + return Err(PyValueError::new_err(message)); + } + array + .as_slice_mut() + .map_err(|_| PyValueError::new_err(message)) +} + +/// Casts a Python object to a 2-dimensional float32 numpy array, with a readable error. +fn as_f32_matrix<'a, 'py>( + object: &'a Bound<'py, PyAny>, + name: &str, +) -> PyResult<&'a Bound<'py, PyArray2>> { + object.cast::>().map_err(|_| { + let found = match object.cast::() { + Ok(array) => format!( + "a {}-dimensional array of dtype {}", + array.ndim(), + array.dtype() + ), + Err(_) => "an object that is not a numpy array".to_string(), + }; + PyTypeError::new_err(format!( + "{} must be a 2-dimensional numpy array of dtype float32, got {} \ + (convert with numpy.asarray(x, dtype=numpy.float32))", + name, found + )) + }) +} + +fn vec_to_pyarray( + py: Python<'_>, + data: Vec, + rows: usize, + columns: usize, +) -> PyResult>> { + let array = Array2::from_shape_vec((rows, columns), data) + .map_err(|e| PyRuntimeError::new_err(e.to_string()))?; + Ok(array.into_pyarray(py)) +} + +fn parse_propagation(propagation: &str) -> PyResult { + match propagation { + "left" => Ok(MarkovType::Left), + "symmetric" => Ok(MarkovType::Symmetric), + _ => Err(PyValueError::new_err(format!( + "Unknown propagation '{}'. Use 'left' or 'symmetric'.", + propagation + ))), + } +} + +/// Row indices given from Python (a numpy integer array or a sequence of ints). +fn extract_rows(rows: &Bound<'_, PyAny>, num_entities: usize) -> PyResult> { + let raw: Vec = match rows.extract::>() { + Ok(array) => array.as_array().iter().copied().collect(), + Err(_) => rows.extract::>().map_err(|_| { + PyTypeError::new_err("rows must be a 1-dimensional sequence of integers") + })?, + }; + raw.into_iter() + .map(|row| { + if row < 0 || row as u64 >= num_entities as u64 { + Err(PyValueError::new_err(format!( + "row index {} is out of range for a graph with {} entities", + row, num_entities + ))) + } else { + Ok(row as usize) + } + }) + .collect() +} + impl SparseMatrix { fn markov_propagate<'py>( &self, - x: &'py PyArray2, + py: Python<'py>, + x: &Bound<'py, PyAny>, markov_type: MarkovType, num_workers: Option, - ) -> PyResult<&'py PyArray> { - let array = unsafe { x.as_array() }; - let num_rows = array.shape()[0]; - let num_entities = self.entity_ids.len(); - if num_rows != num_entities { + out: Option<&Bound<'py, PyAny>>, + rows: Option<&Bound<'py, PyAny>>, + ) -> PyResult>> { + let x = as_f32_matrix(x, "x")?; + let (input_rows, dim) = (x.shape()[0], x.shape()[1]); + if input_rows != self.num_entities() { return Err(PyValueError::new_err(format!( "Embedding matrix has {} rows but graph has {} entities", - num_rows, num_entities + input_rows, + self.num_entities() ))); } - let multiplication_workers: usize = num_workers.unwrap_or_else(num_cpus::get).max(1); - let propagated = NdArrayMatrix::multiply(self, array, markov_type, multiplication_workers); - Ok(propagated.to_pyarray(x.py())) + let selected = match rows { + Some(rows) if !rows.is_none() => Some(extract_rows(rows, self.num_entities())?), + _ => None, + }; + let output_rows = selected.as_ref().map_or(input_rows, |rows| rows.len()); + let input = x + .try_readonly() + .map_err(|e| PyRuntimeError::new_err(format!("x cannot be read: {}", e)))?; + let input_data = matrix_data(&input); + let pool = thread_pool(resolve_num_workers(num_workers)); + let run = |target: &mut [f32]| match &selected { + Some(rows) => { + embedding::propagate_selected(self, &input_data, rows, target, dim, markov_type) + } + None => embedding::propagate(self, &input_data, target, dim, markov_type), + }; + + match out { + Some(out) if !out.is_none() => { + let out = as_f32_matrix(out, "out")?; + if out.shape() != [output_rows, dim] { + return Err(PyValueError::new_err(format!( + "out has shape {:?} but the result has shape {:?}", + out.shape(), + [output_rows, dim] + ))); + } + let mut output = out.try_readwrite().map_err(|_| { + PyValueError::new_err( + "out must be a writeable array that does not share memory with x", + ) + })?; + let output_data = writable_matrix_data(&mut output, "out")?; + py.detach(|| pool.install(|| run(output_data))); + Ok(out.clone()) + } + _ => { + let mut output = vec![0f32; output_rows * dim]; + py.detach(|| pool.install(|| run(&mut output))); + vec_to_pyarray(py, output, output_rows, dim) + } + } } + /// Builds a matrix from an iterator of lines (Rust API). pub fn from_rust_iterator<'a>( columns: &str, hyperedge_trim_n: usize, hyperedges: impl Iterator, num_workers: Option, ) -> Result { - let columns = configuration::parse_fields(columns)?; - let matrix_desc = create_sparse_matrix_descriptor(&columns).map_err(|e| e.to_string())?; - let workers = num_workers.unwrap_or_else(num_cpus::get).max(1); - let config = Configuration { - seed: None, - columns, - matrix_desc, - hyperedge_trim_n, - num_workers_graph_building: workers, - }; + let config = Configuration::new(columns, hyperedge_trim_n, num_workers)?; + let lines: Vec<&str> = hyperedges.collect(); + build_graph_from_lines(&config, &lines, None).map(|(matrix, _)| matrix) + } - Ok(build_graph_from_iterator(&config, hyperedges)) + fn propagate_normalized_inplace( + &self, + py: Python<'_>, + x: &Bound<'_, PyAny>, + markov_type: MarkovType, + num_iterations: usize, + num_workers: Option, + ) -> PyResult<()> { + let x = as_f32_matrix(x, "x")?; + let (rows, dim) = (x.shape()[0], x.shape()[1]); + if rows != self.num_entities() { + return Err(PyValueError::new_err(format!( + "Embedding matrix has {} rows but graph has {} entities", + rows, + self.num_entities() + ))); + } + let mut target = x + .try_readwrite() + .map_err(|_| PyValueError::new_err("x must be a writeable array"))?; + let data = writable_matrix_data(&mut target, "x")?; + let pool = thread_pool(resolve_num_workers(num_workers)); + py.detach(|| { + pool.install(|| { + let mut scratch = vec![0f32; data.len()]; + embedding::iterate( + self, + data, + &mut scratch, + dim, + markov_type, + num_iterations, + 0.0, + 0.0, + ); + }) + }); + Ok(()) } - fn initialize_deterministically_rust(&self, mut vectors: ArrayViewMut2, seed: i64) { - vectors - .axis_iter_mut(Axis(0)) - .into_par_iter() - .enumerate() - .for_each(|(entity_ix, mut row)| { - let entity_id_hash = hash_entity(self.entity_ids[entity_ix].as_str()); - row.indexed_iter_mut().for_each(|(col_ix, v)| { - let value = init_value(col_ix, entity_id_hash, seed); - *v = value - }); - }); + #[allow(clippy::too_many_arguments)] + fn embed_classic<'py>( + &self, + py: Python<'py>, + feature_dim: usize, + num_iterations: usize, + propagation: &str, + seed: i64, + residual_weight: f32, + convergence_threshold: f32, + num_workers: Option, + ) -> PyResult<(Bound<'py, PyArray2>, usize)> { + let markov_type = parse_propagation(propagation)?; + let pool = thread_pool(resolve_num_workers(num_workers)); + let rows = self.num_entities(); + let (embeddings, iterations) = py.detach(|| { + pool.install(|| { + embedding::embed( + self, + feature_dim, + seed, + markov_type, + num_iterations, + residual_weight, + convergence_threshold, + ) + }) + }); + Ok(( + vec_to_pyarray(py, embeddings, rows, feature_dim)?, + iterations, + )) } } #[pymethods] impl SparseMatrix { - #[pyo3(signature = (x, num_workers = None))] + /// One propagation step with the row-stochastic (random walk) matrix. + /// + /// `x` is a float32 array with one row per entity. The result is written to + /// `out` when given (it must not share memory with `x`), otherwise a new array + /// is returned. With `rows` (entity indices) only those rows of the result are + /// computed, in the given order; the work is proportional to their entries. + #[pyo3(signature = (x, num_workers = None, out = None, rows = None))] pub fn left_markov_propagate<'py>( &self, - x: &'py PyArray2, + py: Python<'py>, + x: &Bound<'py, PyAny>, num_workers: Option, - ) -> PyResult<&'py PyArray> { - self.markov_propagate(x, MarkovType::Left, num_workers) + out: Option<&Bound<'py, PyAny>>, + rows: Option<&Bound<'py, PyAny>>, + ) -> PyResult>> { + self.markov_propagate(py, x, MarkovType::Left, num_workers, out, rows) } - #[pyo3(signature = (x, num_workers = None))] + /// One propagation step with the symmetrically normalised matrix. + /// Arguments as for `left_markov_propagate`. + #[pyo3(signature = (x, num_workers = None, out = None, rows = None))] fn symmetric_markov_propagate<'py>( &self, - x: &'py PyArray2, + py: Python<'py>, + x: &Bound<'py, PyAny>, + num_workers: Option, + out: Option<&Bound<'py, PyAny>>, + rows: Option<&Bound<'py, PyAny>>, + ) -> PyResult>> { + self.markov_propagate(py, x, MarkovType::Symmetric, num_workers, out, rows) + } + + /// `num_iterations` rounds of random-walk propagation, each followed by scaling + /// every row to unit L2 norm, in place: `x` (float32, C-contiguous, one row per + /// entity) is overwritten with the result. Needs one more matrix of working + /// memory, whatever the number of rounds. + #[pyo3(signature = (x, num_iterations, num_workers = None))] + fn left_markov_propagate_normalized_inplace( + &self, + py: Python<'_>, + x: &Bound<'_, PyAny>, + num_iterations: usize, + num_workers: Option, + ) -> PyResult<()> { + self.propagate_normalized_inplace(py, x, MarkovType::Left, num_iterations, num_workers) + } + + /// Like `left_markov_propagate_normalized_inplace`, with the symmetrically + /// normalised matrix. + #[pyo3(signature = (x, num_iterations, num_workers = None))] + fn symmetric_markov_propagate_normalized_inplace( + &self, + py: Python<'_>, + x: &Bound<'_, PyAny>, + num_iterations: usize, num_workers: Option, - ) -> PyResult<&'py PyArray> { - self.markov_propagate(x, MarkovType::Symmetric, num_workers) + ) -> PyResult<()> { + self.propagate_normalized_inplace(py, x, MarkovType::Symmetric, num_iterations, num_workers) } + /// A number of iterations for `pycleora.embed` chosen from the graph: fewer on + /// dense graphs, more for a reflexive column and for the symmetric normalisation. + /// + /// `purpose` is `"similarity"` (nearest neighbours, link ranking), `"classification"` + /// (features for a classifier, about twice as many iterations) or `"general"`, a + /// compromise and what `num_iterations="auto"` uses. See `benchmarks/README.md` + /// for the rule and its evaluation. + #[pyo3(signature = (propagation = "left", purpose = "general"))] + fn suggest_iterations(&self, propagation: &str, purpose: &str) -> PyResult { + let purpose = match purpose { + "similarity" => Purpose::Similarity, + "general" => Purpose::General, + "classification" => Purpose::Classification, + _ => { + return Err(PyValueError::new_err(format!( + "Unknown purpose '{}'. Use 'similarity', 'general' or 'classification'.", + purpose + ))) + } + }; + Ok(embedding::suggested_iterations( + self, + parse_propagation(propagation)?, + purpose, + )) + } + + /// Builds the matrix from an iterable of cliques: every element is a sequence of + /// entity names, and all entities of a clique are connected with each other. + /// + /// Names are taken as they are, so they may contain any character (spaces, tabs, + /// commas). `weights` optionally gives one non-negative weight per clique. #[staticmethod] - #[pyo3(signature = (hyperedges, columns, hyperedge_trim_n = 16, num_workers = None))] - fn from_iterator( - hyperedges: &PyIterator, - columns: &str, + #[pyo3(signature = (cliques, hyperedge_trim_n = 16, num_workers = None, weights = None))] + fn from_cliques( + py: Python<'_>, + cliques: &Bound<'_, PyAny>, hyperedge_trim_n: usize, num_workers: Option, + weights: Option<&Bound<'_, PyAny>>, ) -> PyResult { - let hyperedges = hyperedges.map(|line| { - let line = line.map_err(|e| { - PyValueError::new_err(format!("Error reading iterator element: {}", e)) - })?; - let line: &PyString = line - .downcast() - .map_err(|_| PyValueError::new_err("Iterator elements must be strings"))?; - let line = line - .to_str() - .map_err(|_| PyValueError::new_err("Iterator elements must be valid UTF-8"))?; - Ok::<&str, PyErr>(line) - }); - - let collected: Result, PyErr> = hyperedges.collect(); - let collected = collected?; - - SparseMatrix::from_rust_iterator( - columns, + let config = Configuration::new( + "complex::reflexive::CliqueNode", hyperedge_trim_n, - collected.iter().map(|s| *s), num_workers, ) - .map_err(PyValueError::new_err) + .map_err(PyValueError::new_err)?; + let mut rows: Vec>> = match cliques.len() { + Ok(len) => Vec::with_capacity(len), + Err(_) => Vec::new(), + }; + for clique in cliques.try_iter()? { + let clique = clique?; + if clique.is_instance_of::() { + return Err(PyValueError::new_err( + "every clique must be a sequence of entity names, not a single string", + )); + } + let names = extract_strings(&clique, "Clique elements")?; + if names.is_empty() { + return Err(PyValueError::new_err(format!( + "clique {} is empty", + rows.len() + ))); + } + rows.push(vec![names]); + } + let weights = extract_weights(weights)?; + let result = py.detach(|| build_graph_from_rows(&config, &rows, weights.as_deref())); + finish_build(py, result) + } + + /// Indices of the entities that have no neighbour other than themselves. + #[getter(isolated_entities)] + fn py_isolated_entities(&self) -> Vec { + self.isolated_entities() + } + + /// Builds the matrix from an iterable of lines, one hyperedge per line. + /// + /// `weights` optionally gives one non-negative weight per line. + #[staticmethod] + #[pyo3(signature = (hyperedges, columns, hyperedge_trim_n = 16, num_workers = None, weights = None))] + fn from_iterator( + py: Python<'_>, + hyperedges: &Bound<'_, PyAny>, + columns: &str, + hyperedge_trim_n: usize, + num_workers: Option, + weights: Option<&Bound<'_, PyAny>>, + ) -> PyResult { + let config = Configuration::new(columns, hyperedge_trim_n, num_workers) + .map_err(PyValueError::new_err)?; + let lines = extract_strings(hyperedges, "Iterator elements")?; + let weights = extract_weights(weights)?; + let result = py.detach(|| build_graph_from_lines(&config, &lines, weights.as_deref())); + finish_build(py, result) } + /// Builds the matrix from text files with one hyperedge per line. #[staticmethod] #[pyo3(signature = (filepaths, columns, hyperedge_trim_n = 16, num_workers = None))] fn from_files( + py: Python<'_>, filepaths: Vec, columns: &str, hyperedge_trim_n: usize, @@ -145,179 +530,293 @@ impl SparseMatrix { if filepaths.is_empty() { return Err(PyValueError::new_err("At least one file path is required")); } - for filepath in filepaths.iter() { - if !filepath.ends_with(".tsv") - && !filepath.ends_with(".csv") - && !filepath.ends_with(".txt") + for filepath in &filepaths { + let lower = filepath.to_ascii_lowercase(); + if [".gz", ".zst", ".bz2", ".xz", ".zip", ".parquet"] + .iter() + .any(|extension| lower.ends_with(extension)) { return Err(PyValueError::new_err(format!( - "Unsupported file format: {}. Supported: .tsv, .csv, .txt", + "Unsupported file format: {}. Files must be plain text (tab-, comma- or \ + space-separated); decompress or convert the file first.", filepath ))); } + if let Err(error) = std::fs::File::open(filepath) { + let message = format!("Cannot open file '{}': {}", filepath, error); + return Err(if error.kind() == std::io::ErrorKind::NotFound { + PyFileNotFoundError::new_err(message) + } else { + PyIOError::new_err(message) + }); + } } + let config = Configuration::new(columns, hyperedge_trim_n, num_workers) + .map_err(PyValueError::new_err)?; + let result = py.detach(|| build_graph_from_files(&config, &filepaths)); + finish_build(py, result) + } - let columns = configuration::parse_fields(columns).map_err(PyValueError::new_err)?; - let matrix_desc = - create_sparse_matrix_descriptor(&columns).map_err(PyValueError::new_err)?; + /// Builds the matrix from two parallel arrays of node identifiers: `src[i]` and + /// `dst[i]` are the two ends of edge `i`. + /// + /// The arrays are either int64 numpy arrays or sequences of str. With the + /// default columns definition (one reflexive column) the result equals + /// `from_iterator(f"{s} {d}" ...)`; with two columns it equals + /// `from_iterator(f"{s}\t{d}" ...)`. No strings are built for integer input. + #[staticmethod] + #[pyo3(signature = (src, dst, columns = "complex::reflexive::node", weights = None, num_workers = None))] + fn from_edges( + py: Python<'_>, + src: &Bound<'_, PyAny>, + dst: &Bound<'_, PyAny>, + columns: &str, + weights: Option<&Bound<'_, PyAny>>, + num_workers: Option, + ) -> PyResult { + let config = Configuration::new(columns, 16, num_workers).map_err(PyValueError::new_err)?; + let weights = extract_weights(weights)?; - let workers = num_workers.unwrap_or_else(num_cpus::get).max(1); - let config = Configuration { - seed: None, - matrix_desc, - columns, - hyperedge_trim_n, - num_workers_graph_building: workers, + if let (Ok(sources), Ok(targets)) = ( + src.extract::>(), + dst.extract::>(), + ) { + let sources: Cow<[i64]> = match sources.as_slice() { + Ok(slice) => Cow::Borrowed(slice), + Err(_) => Cow::Owned(sources.as_array().iter().copied().collect()), + }; + let targets: Cow<[i64]> = match targets.as_slice() { + Ok(slice) => Cow::Borrowed(slice), + Err(_) => Cow::Owned(targets.as_array().iter().copied().collect()), + }; + let result = py.detach(|| { + build_graph_from_int_edges(&config, &sources, &targets, weights.as_deref()) + }); + return finish_build(py, result); + } + + let type_error = || { + PyTypeError::new_err( + "src and dst must both be int64 numpy arrays or both be sequences of str", + ) }; - Ok(build_graph_from_files(&config, filepaths)) + if src.cast::().is_ok() || dst.cast::().is_ok() { + // numpy arrays of another dtype: convert explicitly rather than guess + let is_str_array = |object: &Bound<'_, PyAny>| -> bool { + object + .cast::() + .map(|array| { + let kind = array.dtype().kind(); + kind == b'U' || kind == b'O' || kind == b'T' + }) + .unwrap_or(true) + }; + if !(is_str_array(src) && is_str_array(dst)) { + return Err(type_error()); + } + } + let sources = extract_strings(src, "src elements").map_err(|_| type_error())?; + let targets = extract_strings(dst, "dst elements").map_err(|_| type_error())?; + let result = py + .detach(|| build_graph_from_str_edges(&config, &sources, &targets, weights.as_deref())); + finish_build(py, result) } + /// Boolean mask of the entities that belong to the given column. fn get_entity_column_mask<'py>( &self, py: Python<'py>, - column_name: String, - ) -> PyResult<&'py PyArray> { - let column_id_by_name = HashMap::from([ - (&self.descriptor.col_a_name, self.descriptor.col_a_id), - (&self.descriptor.col_b_name, self.descriptor.col_b_id), - ]); - let column_id = column_id_by_name - .get(&column_name) - .ok_or(PyValueError::new_err(format!( - "Column name '{}' not found. Available: '{}', '{}'", - column_name, self.descriptor.col_a_name, self.descriptor.col_b_name - )))?; - - let mask: Vec = self - .column_ids - .par_iter() - .map(|id| *id == *column_id) - .collect(); - let mask = Array1::from_vec(mask); - Ok(mask.to_pyarray(py)) + column_name: &str, + ) -> PyResult>> { + let column = self + .column_names + .iter() + .position(|name| name == column_name) + .ok_or_else(|| { + PyValueError::new_err(format!( + "Column name '{}' not found. Available: {}", + column_name, + self.column_names + .iter() + .map(|name| format!("'{}'", name)) + .collect::>() + .join(", ") + )) + })? as u8; + let mask: Vec = self.column_ids.iter().map(|id| *id == column).collect(); + Ok(PyArray1::from_vec(py, mask)) } + /// Weighted degree of every entity (total hyperedge mass), as float32. #[getter] - fn entity_degrees<'py>(&self, py: Python<'py>) -> &'py PyArray { - let entity_degrees: Vec = self.entities.par_iter().map(|e| e.row_sum).collect(); - Array1::from_vec(entity_degrees).to_pyarray(py) + fn entity_degrees<'py>(&self, py: Python<'py>) -> Bound<'py, PyArray1> { + let degrees: Vec = self.row_sums.iter().map(|sum| *sum as f32).collect(); + PyArray1::from_vec(py, degrees) } - #[getter] - fn num_entities(&self) -> usize { - self.entity_ids.len() + #[getter(num_entities)] + fn py_num_entities(&self) -> usize { + self.num_entities() } + /// Number of stored (directed) entries of the matrix. #[getter] fn num_edges(&self) -> usize { - self.edges.len() + self.nnz() + } + + /// Names of the entity columns the matrix was built from. + #[getter(column_names)] + fn py_column_names(&self) -> Vec { + self.column_names.clone() + } + + /// Entity names, in matrix row order (an immutable tuple, built once). + #[getter(entity_ids)] + fn py_entity_ids<'py>(&self, py: Python<'py>) -> PyResult> { + let ids = self + .py_entity_ids + .get_or_try_init(py, || PyTuple::new(py, &self.entity_ids).map(Bound::unbind))?; + Ok(ids.bind(py).clone()) + } + + #[setter(entity_ids)] + fn py_set_entity_ids(&mut self, entity_ids: Vec) -> PyResult<()> { + if entity_ids.len() != self.num_entities() { + return Err(PyValueError::new_err(format!( + "entity_ids must have {} elements, got {}", + self.num_entities(), + entity_ids.len() + ))); + } + self.replace_entity_ids(entity_ids); + Ok(()) } fn get_entity_index(&self, entity_id: &str) -> PyResult { - self.entity_ids - .iter() - .position(|id| id == entity_id) + self.index_of(entity_id) .ok_or_else(|| PyValueError::new_err(format!("Entity '{}' not found", entity_id))) } - fn get_entity_indices(&self, entity_ids: Vec) -> PyResult> { - let index_map: HashMap<&str, usize> = self - .entity_ids - .iter() - .enumerate() - .map(|(i, id)| (id.as_str(), i)) - .collect(); - + fn get_entity_indices(&self, entity_ids: Vec) -> PyResult> { entity_ids .iter() .map(|id| { - index_map - .get(id.as_str()) - .copied() - .ok_or_else(|| PyValueError::new_err(format!("Entity '{}' not found", id))) + self.index_of(id) + .ok_or_else(|| PyValueError::new_err(format!("Entity '{}' not found", &**id))) }) .collect() } + /// Deterministic initial embeddings: a pure function of (entity name, column, + /// seed), uniform in [-1, 1). #[pyo3(signature = (feature_dim, seed = 0))] fn initialize_deterministically<'py>( &self, py: Python<'py>, feature_dim: usize, seed: i64, - ) -> &'py PyArray { - let mut vectors = Array2::zeros([self.entity_ids.len(), feature_dim]); - self.initialize_deterministically_rust(vectors.view_mut(), seed); - vectors.to_pyarray(py) + ) -> PyResult>> { + let rows = self.num_entities(); + let data = py.detach(|| embedding::initialize(&self.entity_ids, feature_dim, seed)); + vec_to_pyarray(py, data, rows, feature_dim) } + /// The matrix in coordinate form: `(rows, cols, values, n_rows, n_cols)`. + /// `markov_type` is 'left' (default), 'symmetric' or 'raw' (un-normalised weights). #[pyo3(signature = (markov_type = None))] + #[allow(clippy::type_complexity)] fn to_sparse_csr<'py>( &self, py: Python<'py>, markov_type: Option<&str>, ) -> PyResult<( - &'py PyArray, - &'py PyArray, - &'py PyArray, + Bound<'py, PyArray1>, + Bound<'py, PyArray1>, + Bound<'py, PyArray1>, usize, usize, )> { - let n = self.entity_ids.len(); - let nnz = self.edges.len(); - let mut row_indices: Vec = Vec::with_capacity(nnz); - let mut col_indices: Vec = Vec::with_capacity(nnz); + let kind = Normalization::parse(markov_type).map_err(PyValueError::new_err)?; + let n = self.num_entities(); + let nnz = self.nnz(); + let mut rows: Vec = Vec::with_capacity(nnz); let mut values: Vec = Vec::with_capacity(nnz); - - let mt = markov_type.unwrap_or("left"); - if mt != "left" && mt != "symmetric" { - return Err(PyValueError::new_err(format!( - "Unknown markov_type '{}'. Use 'left' or 'symmetric'.", - mt - ))); - } - let use_symmetric = mt == "symmetric"; - - for (row_ix, (start, end)) in self.slices.iter().enumerate() { - for edge in &self.edges[*start..*end] { - row_indices.push(row_ix as u32); - col_indices.push(edge.other_entity_ix); - values.push(if use_symmetric { - edge.symmetric_markov_value - } else { - edge.left_markov_value - }); + for row in 0..n { + for k in self.row_range(row) { + rows.push(row as u32); + values.push(self.normalized_value(row, k, kind)); } } - Ok(( - Array1::from_vec(row_indices).to_pyarray(py), - Array1::from_vec(col_indices).to_pyarray(py), - Array1::from_vec(values).to_pyarray(py), + PyArray1::from_vec(py, rows), + PyArray1::from_slice(py, &self.indices), + PyArray1::from_vec(py, values), n, n, )) } - fn get_neighbors(&self, entity_id: &str) -> PyResult> { - let idx = self - .entity_ids - .iter() - .position(|id| id == entity_id) - .ok_or_else(|| PyValueError::new_err(format!("Entity '{}' not found", entity_id)))?; + /// The matrix in CSR form: `(indptr, indices, data)`, ready for + /// `scipy.sparse.csr_matrix((data, indices, indptr), shape=(n, n))`. + #[pyo3(signature = (markov_type = None))] + #[allow(clippy::type_complexity)] + fn to_csr<'py>( + &self, + py: Python<'py>, + markov_type: Option<&str>, + ) -> PyResult<( + Bound<'py, PyAny>, + Bound<'py, PyAny>, + Bound<'py, PyArray1>, + )> { + let kind = Normalization::parse(markov_type).map_err(PyValueError::new_err)?; + let n = self.num_entities(); + let mut values: Vec = Vec::with_capacity(self.nnz()); + for row in 0..n { + for k in self.row_range(row) { + values.push(self.normalized_value(row, k, kind)); + } + } + let data = PyArray1::from_vec(py, values); + let small = self.nnz() <= i32::MAX as usize && n <= i32::MAX as usize; + if small { + let indptr: Vec = self.indptr.iter().map(|v| *v as i32).collect(); + let indices: Vec = self.indices.iter().map(|v| *v as i32).collect(); + Ok(( + PyArray1::from_vec(py, indptr).into_any(), + PyArray1::from_vec(py, indices).into_any(), + data, + )) + } else { + let indptr: Vec = self.indptr.iter().map(|v| *v as i64).collect(); + let indices: Vec = self.indices.iter().map(|v| *v as i64).collect(); + Ok(( + PyArray1::from_vec(py, indptr).into_any(), + PyArray1::from_vec(py, indices).into_any(), + data, + )) + } + } - let (start, end) = self.slices[idx]; - let neighbors: Vec<(String, f32)> = self.edges[start..end] - .iter() - .map(|edge| { - let neighbor_id = self.entity_ids[edge.other_entity_ix as usize].clone(); - (neighbor_id, edge.left_markov_value) + /// Neighbours of an entity with their random-walk transition probabilities. + fn get_neighbors(&self, entity_id: &str) -> PyResult> { + let row = self.get_entity_index(entity_id)?; + Ok(self + .row_range(row) + .map(|k| { + ( + self.entity_ids[self.indices[k] as usize].clone(), + self.normalized_value(row, k, Normalization::Left), + ) }) - .collect(); - Ok(neighbors) + .collect()) } + /// Classic Cleora in one call: deterministic initialisation followed by + /// `num_iterations` rounds of propagation and row-wise L2 normalisation. #[pyo3(signature = (feature_dim, num_iterations, propagation = "left", seed = 0, residual_weight = 0.0, num_workers = None))] + #[allow(clippy::too_many_arguments)] fn embed_fast<'py>( &self, py: Python<'py>, @@ -327,43 +826,24 @@ impl SparseMatrix { seed: i64, residual_weight: f32, num_workers: Option, - ) -> PyResult<&'py PyArray> { - let markov_type = match propagation { - "left" => MarkovType::Left, - "symmetric" => MarkovType::Symmetric, - _ => { - return Err(PyValueError::new_err(format!( - "Unknown propagation '{}'. Use 'left' or 'symmetric'.", - propagation - ))) - } - }; - - let mut vectors = Array2::zeros([self.entity_ids.len(), feature_dim]); - self.initialize_deterministically_rust(vectors.view_mut(), seed); - - let workers = num_workers.unwrap_or_else(num_cpus::get).max(1); - - let result = py.allow_threads(|| { - let pool = rayon::ThreadPoolBuilder::new() - .num_threads(workers) - .build() - .unwrap(); - pool.install(|| { - NdArrayMatrix::embed_full( - self, - vectors, - markov_type, - num_iterations, - residual_weight, - ) - }) - }); - - Ok(result.to_pyarray(py)) + ) -> PyResult>> { + self.embed_classic( + py, + feature_dim, + num_iterations, + propagation, + seed, + residual_weight, + 0.0, + num_workers, + ) + .map(|(embeddings, _)| embeddings) } + /// Like `embed_fast`, but stops early once the RMSE between two consecutive + /// rounds drops below `convergence_threshold`. Returns `(embeddings, rounds)`. #[pyo3(signature = (feature_dim, max_iterations, propagation = "left", seed = 0, residual_weight = 0.0, convergence_threshold = 0.0, num_workers = None))] + #[allow(clippy::too_many_arguments)] fn embed_fast_convergence<'py>( &self, py: Python<'py>, @@ -374,122 +854,230 @@ impl SparseMatrix { residual_weight: f32, convergence_threshold: f32, num_workers: Option, - ) -> PyResult<(&'py PyArray, usize)> { - let markov_type = match propagation { - "left" => MarkovType::Left, - "symmetric" => MarkovType::Symmetric, - _ => { - return Err(PyValueError::new_err(format!( - "Unknown propagation '{}'. Use 'left' or 'symmetric'.", - propagation - ))) - } - }; - - let mut vectors = Array2::zeros([self.entity_ids.len(), feature_dim]); - self.initialize_deterministically_rust(vectors.view_mut(), seed); - - let workers = num_workers.unwrap_or_else(num_cpus::get).max(1); - - let (result, iters) = py.allow_threads(|| { - let pool = rayon::ThreadPoolBuilder::new() - .num_threads(workers) - .build() - .unwrap(); - pool.install(|| { - NdArrayMatrix::embed_full_with_convergence( - self, - vectors, - markov_type, - max_iterations, - residual_weight, - convergence_threshold, - ) - }) - }); - - Ok((result.to_pyarray(py), iters)) + ) -> PyResult<(Bound<'py, PyArray2>, usize)> { + self.embed_classic( + py, + feature_dim, + max_iterations, + propagation, + seed, + residual_weight, + convergence_threshold, + num_workers, + ) } + /// Returns a copy of `x` with every row scaled to unit L2 norm. #[pyo3(signature = (x, num_workers = None))] fn l2_normalize<'py>( &self, - x: &'py PyArray2, + py: Python<'py>, + x: &Bound<'py, PyAny>, num_workers: Option, - ) -> PyResult<&'py PyArray> { - let array = unsafe { x.as_array() }.to_owned(); - let mut result = array; - NdArrayMatrix::l2_normalize_inplace(&mut result); - Ok(result.to_pyarray(x.py())) + ) -> PyResult>> { + let x = as_f32_matrix(x, "x")?; + let (rows, dim) = (x.shape()[0], x.shape()[1]); + let input = x + .try_readonly() + .map_err(|e| PyRuntimeError::new_err(format!("x cannot be read: {}", e)))?; + let mut data = matrix_data(&input).into_owned(); + let pool = thread_pool(resolve_num_workers(num_workers)); + py.detach(|| pool.install(|| embedding::l2_normalize_rows(&mut data, dim))); + vec_to_pyarray(py, data, rows, dim) } fn __repr__(&self) -> String { + let columns = match self.relations.as_slice() { + [relation] => format!( + "('{}', '{}')", + self.column_names[relation.a as usize], self.column_names[relation.b as usize] + ), + _ => format!( + "({})", + self.column_names + .iter() + .map(|name| format!("'{}'", name)) + .collect::>() + .join(", ") + ), + }; format!( - "SparseMatrix(entities={}, edges={}, columns=('{}', '{}'))", - self.entity_ids.len(), - self.edges.len(), - self.descriptor.col_a_name, - self.descriptor.col_b_name + "SparseMatrix(entities={}, edges={}, columns={})", + self.num_entities(), + self.nnz(), + columns ) } fn __len__(&self) -> usize { - self.entity_ids.len() + self.num_entities() } #[new] #[pyo3(signature = (*args))] - fn new(args: &PyTuple) -> PyResult { + fn new(args: &Bound<'_, PyTuple>) -> PyResult { match args.len() { - 0 => Ok(SparseMatrix { - descriptor: SparseMatrixDescriptor { - col_a_id: 0, - col_a_name: "".to_string(), - col_b_id: 0, - col_b_name: "".to_string(), - }, - entity_ids: vec![], - entities: vec![], - edges: vec![], - slices: vec![], - column_ids: vec![], - }), + 0 => Ok(SparseMatrix::empty()), _ => Err(PyValueError::new_err( - "SparseMatrix cannot be constructed directly. Use SparseMatrix.from_files() or SparseMatrix.from_iterator()." + "SparseMatrix cannot be constructed directly. Use SparseMatrix.from_files(), \ + SparseMatrix.from_iterator() or SparseMatrix.from_edges().", )), } } - pub fn __getstate__(&self, py: Python) -> PyResult { - let bytes = serialize(self) - .map_err(|e| PyRuntimeError::new_err(format!("Serialization failed: {}", e)))?; - Ok(PyBytes::new(py, &bytes).to_object(py)) + pub fn __getstate__<'py>(&self, py: Python<'py>) -> PyResult> { + let bytes = self.to_state_bytes().map_err(PyRuntimeError::new_err)?; + Ok(PyBytes::new(py, &bytes)) } - pub fn __setstate__(&mut self, py: Python, state: PyObject) -> PyResult<()> { - let bytes = state.extract::<&PyBytes>(py)?; - let sm: SparseMatrix = deserialize(bytes.as_bytes()) - .map_err(|e| PyRuntimeError::new_err(format!("Deserialization failed: {}", e)))?; - *self = sm; + pub fn __setstate__(&mut self, state: &Bound<'_, PyBytes>) -> PyResult<()> { + *self = + SparseMatrix::from_state_bytes(state.as_bytes()).map_err(PyRuntimeError::new_err)?; Ok(()) } } -fn init_value(col: usize, hsh: u64, fixed_random_value: i64) -> f32 { - let hash = |num: i64| { - let mut hasher = FxHasher::default(); - hasher.write_i64(num); - hasher.finish() as i64 - }; +/// Column means and unbiased covariance of a float32 matrix, computed in float64. +/// The result does not depend on the number of threads. +#[pyfunction] +#[pyo3(signature = (x, num_workers = None))] +#[allow(clippy::type_complexity)] +fn column_mean_cov<'py>( + py: Python<'py>, + x: &Bound<'py, PyAny>, + num_workers: Option, +) -> PyResult<(Bound<'py, PyArray1>, Bound<'py, PyArray2>)> { + let x = as_f32_matrix(x, "x")?; + let (rows, dim) = (x.shape()[0], x.shape()[1]); + let input = x + .try_readonly() + .map_err(|e| PyRuntimeError::new_err(format!("x cannot be read: {}", e)))?; + let data = matrix_data(&input); + let pool = thread_pool(resolve_num_workers(num_workers)); + let (mean, covariance) = + py.detach(|| pool.install(|| embedding::column_mean_and_covariance(&data, rows, dim))); + let covariance = Array2::from_shape_vec((dim, dim), covariance) + .map_err(|e| PyRuntimeError::new_err(e.to_string()))?; + Ok((PyArray1::from_vec(py, mean), covariance.into_pyarray(py))) +} + +fn check_projection_arguments( + dim: usize, + mean: &PyReadonlyArray1<'_, f32>, + transform: &PyReadonlyArray2<'_, f32>, +) -> PyResult<()> { + if mean.len() != dim { + return Err(PyValueError::new_err(format!( + "mean has {} element(s) but x has {} column(s)", + mean.len(), + dim + ))); + } + if transform.shape()[0] != dim { + return Err(PyValueError::new_err(format!( + "transform has {} row(s) but x has {} column(s)", + transform.shape()[0], + dim + ))); + } + Ok(()) +} + +/// Returns `(x - mean) @ transform` as a new float32 array. +#[pyfunction] +#[pyo3(signature = (x, mean, transform, num_workers = None))] +fn center_project<'py>( + py: Python<'py>, + x: &Bound<'py, PyAny>, + mean: PyReadonlyArray1<'py, f32>, + transform: PyReadonlyArray2<'py, f32>, + num_workers: Option, +) -> PyResult>> { + let x = as_f32_matrix(x, "x")?; + let (rows, dim) = (x.shape()[0], x.shape()[1]); + check_projection_arguments(dim, &mean, &transform)?; + let components = transform.shape()[1]; + let input = x + .try_readonly() + .map_err(|e| PyRuntimeError::new_err(format!("x cannot be read: {}", e)))?; + let data = matrix_data(&input); + let mean: Vec = mean.as_array().iter().copied().collect(); + let transform = transform.as_array(); + let mut output = vec![0f32; rows * components]; + let pool = thread_pool(resolve_num_workers(num_workers)); + py.detach(|| { + pool.install(|| embedding::center_and_project(&data, dim, &mean, transform, &mut output)) + }); + vec_to_pyarray(py, output, rows, components) +} - const MAX_HASH_I64: i64 = 8 * 1024 * 1024; - const MAX_HASH_F32: f32 = MAX_HASH_I64 as f32; - ((hash((hsh as i64) + (col as i64) + fixed_random_value) % MAX_HASH_I64) as f32) / MAX_HASH_F32 +/// Replaces `x` by `(x - mean) @ transform` for a square transform, without +/// allocating a second matrix. +#[pyfunction] +#[pyo3(signature = (x, mean, transform, num_workers = None))] +fn center_project_inplace<'py>( + py: Python<'py>, + x: &Bound<'py, PyAny>, + mean: PyReadonlyArray1<'py, f32>, + transform: PyReadonlyArray2<'py, f32>, + num_workers: Option, +) -> PyResult<()> { + let x = as_f32_matrix(x, "x")?; + let dim = x.shape()[1]; + check_projection_arguments(dim, &mean, &transform)?; + if transform.shape()[1] != dim { + return Err(PyValueError::new_err( + "an in-place projection needs a square transform", + )); + } + let mut target = x + .try_readwrite() + .map_err(|_| PyValueError::new_err("x must be a writeable array"))?; + let data = writable_matrix_data(&mut target, "x")?; + let mean: Vec = mean.as_array().iter().copied().collect(); + let transform = transform.as_array(); + let pool = thread_pool(resolve_num_workers(num_workers)); + py.detach(|| { + pool.install(|| embedding::center_and_project_inplace(data, dim, &mean, transform)) + }); + Ok(()) +} + +/// The 64-bit hash that identifies an entity name (XXH64, seed 0). It decides the +/// entity's initial vector and breaks ties when oversized hyperedges are trimmed. +#[pyfunction] +fn entity_hash(entity_id: &str) -> u64 { + entity::hash_entity(entity_id) +} + +/// Scales every row of `x` to unit L2 norm, in place. +#[pyfunction] +#[pyo3(signature = (x, num_workers = None))] +fn l2_normalize_inplace<'py>( + py: Python<'py>, + x: &Bound<'py, PyAny>, + num_workers: Option, +) -> PyResult<()> { + let x = as_f32_matrix(x, "x")?; + let dim = x.shape()[1]; + let mut target = x + .try_readwrite() + .map_err(|_| PyValueError::new_err("x must be a writeable array"))?; + let data = writable_matrix_data(&mut target, "x")?; + let pool = thread_pool(resolve_num_workers(num_workers)); + py.detach(|| pool.install(|| embedding::l2_normalize_rows(data, dim))); + Ok(()) } #[pymodule] #[pyo3(name = "pycleora")] -fn pycleora(_py: Python, m: &PyModule) -> PyResult<()> { +fn pycleora(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; + m.add_function(wrap_pyfunction!(column_mean_cov, m)?)?; + m.add_function(wrap_pyfunction!(center_project, m)?)?; + m.add_function(wrap_pyfunction!(center_project_inplace, m)?)?; + m.add_function(wrap_pyfunction!(l2_normalize_inplace, m)?)?; + m.add_function(wrap_pyfunction!(entity_hash, m)?)?; + m.add("__version__", env!("CARGO_PKG_VERSION"))?; Ok(()) } diff --git a/src/pipeline.rs b/src/pipeline.rs index e3867c4..a4c4ebe 100644 --- a/src/pipeline.rs +++ b/src/pipeline.rs @@ -1,240 +1,435 @@ -use std::cmp::min; +//! Drivers that feed hyperedges from the supported sources into the builder. + use std::fs::File; use std::io::{BufRead, BufReader}; -use std::sync::Arc; -use std::time::Instant; -use crossbeam::channel; -use crossbeam::channel::{Receiver, Sender}; -use crossbeam::thread as cb_thread; -use crossbeam::thread::{Scope, ScopedJoinHandle}; -use itertools::Itertools; -use log::{error, info, warn}; -use smallvec::SmallVec; +use smallvec::{smallvec, SmallVec}; use crate::configuration::Configuration; -use crate::entity::{EntityProcessor, Hyperedge, SMALL_VECTOR_SIZE}; +use crate::embedding::thread_pool; +use crate::entity::{parse_line, weight_is_valid, IntBuffer, LineError, Tokens, MAX_WEIGHT}; use crate::sparse_matrix::SparseMatrix; -use crate::sparse_matrix_builder::NodeIndexerBuilder; use crate::sparse_matrix_builder::{ - AsyncNodeIndexerBuilder, NodeIndexer, SparseMatrixBuffer, SparseMatrixBuffersReducer, - SyncNodeIndexerBuilder, + position, reduce, BuildStats, Indexer, WorkerBuffer, MAX_FILES, MAX_LINES, }; -pub fn build_graph_from_iterator<'a>( - config: &Configuration, - hyperedges: impl Iterator, -) -> SparseMatrix { - cb_thread::scope(|s| { - let (hyperedges_s, hyperedges_r) = channel::bounded(64 * config.num_workers_graph_building); - - let matrix_buffer = make_consumer(hyperedges_r, config, s); - let node_indexer = make_producer_from_iterator(config, hyperedges, hyperedges_s); - - let buffers = matrix_buffer +/// Runs `work(first, last, buffer)` on `num_workers` threads over `0..len`, split +/// into contiguous ranges, and returns the per-thread buffers. +fn run_partitioned(len: usize, num_workers: usize, work: F) -> Vec +where + F: Fn(usize, usize, &mut WorkerBuffer) + Sync, +{ + let workers = num_workers.clamp(1, len.max(1)); + if workers == 1 { + let mut buffer = WorkerBuffer::default(); + work(0, len, &mut buffer); + return vec![buffer]; + } + std::thread::scope(|scope| { + let handles: Vec<_> = (0..workers) + .map(|worker| { + let work = &work; + let first = len * worker / workers; + let last = len * (worker + 1) / workers; + scope.spawn(move || { + let mut buffer = WorkerBuffer::default(); + work(first, last, &mut buffer); + buffer + }) + }) + .collect(); + handles .into_iter() - .map(|h| h.join().unwrap()) - .collect_vec(); - SparseMatrixBuffersReducer::new(node_indexer, buffers, config.num_workers_graph_building) - .reduce() + .map(|handle| handle.join().expect("worker thread panicked")) + .collect() }) - .expect("All work in thread scope finished") } -fn make_producer_from_iterator<'a>( +fn finish( config: &Configuration, - hyperedges: impl Iterator, - hyperedges_s: Sender, -) -> NodeIndexer { - let node_indexer_builder: Arc = Default::default(); - let entity_processor = EntityProcessor::new(config, node_indexer_builder.clone()); - for line in hyperedges { - consume_line(config, &hyperedges_s, &entity_processor, line); - } - drop(entity_processor); - let node_indexer_builder = - Arc::try_unwrap(node_indexer_builder).expect("All other references should be dropped"); - node_indexer_builder.finish() + indexer: Indexer, + buffers: Vec, +) -> Result<(SparseMatrix, BuildStats), String> { + thread_pool(config.num_workers).install(|| reduce(config, indexer, buffers)) } -fn consume_line( +fn check_weights(weights: Option<&[f32]>, expected_len: usize) -> Result<(), String> { + if let Some(weights) = weights { + if weights.len() != expected_len { + return Err(format!( + "weights has {} element(s) but there are {} hyperedge(s)", + weights.len(), + expected_len + )); + } + if let Some(index) = weights.iter().position(|w| !weight_is_valid(*w)) { + return Err(format!( + "weights[{}] = {} is not a finite number between 0 and {:e}", + index, weights[index], MAX_WEIGHT + )); + } + } + Ok(()) +} + +/// Builds the matrix from lines held in memory. `weights`, when given, holds one +/// weight per line (and cannot be combined with a `weight::` column). +pub fn build_graph_from_lines + Sync>( config: &Configuration, - hyperedges_s: &Sender, - entity_processor: &EntityProcessor, - line: &str, -) { - let row = parse_line(line); - let line_col_num = row.len(); - if line_col_num == config.columns.len() { - let hyperedge = entity_processor.process_row_and_get_edges(&row); - hyperedges_s.send(hyperedge).unwrap(); - } else { - warn!( - "Wrong number of columns (expected: {}, provided: {}). The line [{}] is skipped.", - config.columns.len(), - line_col_num, - line + lines: &[S], + weights: Option<&[f32]>, +) -> Result<(SparseMatrix, BuildStats), String> { + check_weights(weights, lines.len())?; + if weights.is_some() && config.weight_column.is_some() { + return Err( + "Pass weights either as an argument or as a 'weight::' column, not both".to_string(), ); } + if lines.len() as u64 >= MAX_LINES { + return Err(format!("Too many lines ({})", lines.len())); + } + + let indexer = Indexer::default(); + let buffers = run_partitioned(lines.len(), config.num_workers, |first, last, buffer| { + for index in first..last { + let line = lines[index].as_ref(); + let pos = position(0, index as u64, 0); + match parse_line(line, config) { + Ok(Some(parsed)) => { + let weight = match weights { + Some(weights) => weights[index], + None => parsed.weight, + }; + buffer.add_row(config, &indexer, &parsed.fields, weight, pos); + } + Ok(None) => {} + Err(error) => buffer.skip_line(pos, line, error), + } + } + }); + finish(config, indexer, buffers) } -pub fn build_graph_from_files(config: &Configuration, input_files: Vec) -> SparseMatrix { - let processing_worker_num = config.num_workers_graph_building; - cb_thread::scope(|s| { - let (hyperedges_s, hyperedges_r) = channel::bounded(processing_worker_num * 64); +/// A chunk of a file: whole lines, newline-terminated. +struct Batch { + file: u32, + first_line: u64, + data: Vec, +} - let matrix_buffers: Vec<_> = make_consumer(hyperedges_r, config, s); - let node_indexer = make_producer_from_files(config, &input_files, s, hyperedges_s); +const BATCH_BYTES: usize = 1 << 20; - let buffers = matrix_buffers - .into_iter() - .map(|h| h.join().unwrap()) - .collect_vec(); - - let merging_start_time = Instant::now(); - let result = - SparseMatrixBuffersReducer::new(node_indexer, buffers, processing_worker_num).reduce(); - info!( - "Merging finished in {} sec", - merging_start_time.elapsed().as_secs() - ); - result - }) - .expect("Threads finished work") +fn read_batches( + file_index: u32, + path: &str, + sender: &crossbeam_channel::Sender, +) -> Result<(), String> { + let file = File::open(path).map_err(|e| format!("Cannot open file '{}': {}", path, e))?; + let mut reader = BufReader::with_capacity(1 << 20, file); + let mut line_number = 0u64; + loop { + let mut data = Vec::with_capacity(BATCH_BYTES + 4096); + let first_line = line_number; + while data.len() < BATCH_BYTES { + let read = reader + .read_until(b'\n', &mut data) + .map_err(|e| format!("Cannot read file '{}': {}", path, e))?; + if read == 0 { + break; + } + line_number += 1; + } + if data.is_empty() { + return Ok(()); + } + if line_number >= MAX_LINES { + return Err(format!("File '{}' has too many lines", path)); + } + if sender + .send(Batch { + file: file_index, + first_line, + data, + }) + .is_err() + { + // the workers are gone; their error is reported instead + return Ok(()); + } + } } -fn make_producer_from_files<'c: 'e, 'e: 's, 's>( - config: &'c Configuration, - input_files: &'c Vec, - s: &'s Scope<'e>, - hyperedges_s: Sender, -) -> NodeIndexer { - let (files_s, files_r) = channel::unbounded(); - - for input in input_files { - files_s.send(input).unwrap() - } - drop(files_s); - - let max_file_reading_worker_num = min(config.num_workers_graph_building, 4); - let file_reading_worker_num = min(max_file_reading_worker_num, input_files.len()); - - let log_every_n = 10000; - - if file_reading_worker_num == 1 { - let node_indexer_builder: Arc = Default::default(); - let entity_processor = EntityProcessor::new(config, node_indexer_builder.clone()); - consume_files(config, hyperedges_s, files_r, log_every_n, entity_processor); - let node_indexer_builder = - Arc::try_unwrap(node_indexer_builder).expect("All other references should be dropped"); - node_indexer_builder.finish() - } else { - let node_indexer_builder: Arc = Default::default(); - let producers = (0..file_reading_worker_num) +/// Builds the matrix from text files (one hyperedge per line). +pub fn build_graph_from_files( + config: &Configuration, + paths: &[String], +) -> Result<(SparseMatrix, BuildStats), String> { + if paths.is_empty() { + return Err("At least one file path is required".to_string()); + } + if paths.len() > MAX_FILES { + return Err(format!( + "Too many files ({}); at most {} are supported", + paths.len(), + MAX_FILES + )); + } + // Fail early, before any work, if a file cannot be opened. + for path in paths { + File::open(path).map_err(|e| format!("Cannot open file '{}': {}", path, e))?; + } + + let indexer = Indexer::default(); + let workers = config.num_workers.max(1); + let readers = workers.min(4).min(paths.len()); + let (batch_sender, batch_receiver) = crossbeam_channel::bounded::(2 * workers); + let (path_sender, path_receiver) = crossbeam_channel::unbounded::<(u32, &String)>(); + for (index, path) in paths.iter().enumerate() { + path_sender.send((index as u32, path)).unwrap(); + } + drop(path_sender); + + let (buffers, read_result) = std::thread::scope(|scope| { + let worker_handles: Vec<_> = (0..workers) .map(|_| { - let hyperedges_s = hyperedges_s.clone(); - let files_r = files_r.clone(); - let entity_processor = EntityProcessor::new(config, node_indexer_builder.clone()); + let receiver = batch_receiver.clone(); + let indexer = &indexer; + scope.spawn(move || { + let mut buffer = WorkerBuffer::default(); + for batch in receiver { + process_batch(config, indexer, &batch, &mut buffer); + } + buffer + }) + }) + .collect(); + drop(batch_receiver); - s.spawn(move |_| { - consume_files(config, hyperedges_s, files_r, log_every_n, entity_processor); + let reader_handles: Vec<_> = (0..readers) + .map(|_| { + let sender = batch_sender.clone(); + let paths = path_receiver.clone(); + scope.spawn(move || -> Result<(), String> { + for (index, path) in paths { + read_batches(index, path, &sender)?; + } + Ok(()) }) }) - .collect_vec(); - drop(hyperedges_s); - drop(files_r); + .collect(); + drop(batch_sender); + drop(path_receiver); - producers.into_iter().for_each(|h| h.join().unwrap()); - let node_indexer_builder = - Arc::try_unwrap(node_indexer_builder).expect("All other references should be dropped"); - node_indexer_builder.finish() - } + let mut read_result = Ok(()); + for handle in reader_handles { + let result = handle.join().expect("reader thread panicked"); + if read_result.is_ok() { + read_result = result; + } + } + let buffers: Vec = worker_handles + .into_iter() + .map(|handle| handle.join().expect("worker thread panicked")) + .collect(); + (buffers, read_result) + }); + read_result?; + finish(config, indexer, buffers) } -fn consume_files( +fn process_batch( config: &Configuration, - hyperedges_s: Sender, - files_r: Receiver<&String>, - log_every_n: u64, - entity_processor: EntityProcessor, + indexer: &Indexer, + batch: &Batch, + buffer: &mut WorkerBuffer, ) { - for input in files_r { - read_file(input, log_every_n, |line| { - consume_line(config, &hyperedges_s, &entity_processor, line); - }); + let raw_lines = batch.data.split_inclusive(|b| *b == b'\n'); + for (line_number, raw) in (batch.first_line..).zip(raw_lines) { + let pos = position(batch.file, line_number, 0); + match std::str::from_utf8(raw) { + Ok(line) => match parse_line(line, config) { + Ok(Some(parsed)) => { + buffer.add_row(config, indexer, &parsed.fields, parsed.weight, pos) + } + Ok(None) => {} + Err(error) => buffer.skip_line(pos, line.trim_end(), error), + }, + Err(_) => buffer.skip_line( + pos, + String::from_utf8_lossy(raw).trim_end(), + LineError::InvalidUtf8, + ), + } } } -fn make_consumer<'s, 'a: 'a>( - hyperedges_r: Receiver, - config: &'a Configuration, - s: &'s Scope<'a>, -) -> Vec> { - (0..config.num_workers_graph_building) - .map(|_| { - let hyperedges_r = hyperedges_r.clone(); - let sparse_matrices = config.matrix_desc.clone(); - - s.spawn(move |_| { - let mut buffer = sparse_matrices.make_buffer(config.hyperedge_trim_n); - for hyperedge in hyperedges_r { - buffer.handle_hyperedge(&hyperedge); - } - buffer - }) - }) - .collect() +/// How the two endpoints of an edge map onto the declared columns. +#[derive(Clone, Copy)] +enum EdgeLayout { + /// One reflexive column: the edge is the two-entity hyperedge `{source, target}`. + SingleColumn, + /// Two entity columns: `source` in the first, `target` in the second. + TwoColumns, } -fn read_file(filepath: &str, log_every: u64, mut line_handler: F) -where - F: FnMut(&str), -{ - let input_file = match File::open(filepath) { - Ok(f) => f, - Err(e) => { - error!("Cannot open file '{}': {}", filepath, e); - return; +fn edge_layout(config: &Configuration) -> Result { + if config.weight_column.is_some() { + return Err( + "Edge arrays take their weights from the 'weights' argument, not from a 'weight::' column" + .to_string(), + ); + } + match config.entity_column_names.len() { + 1 => Ok(EdgeLayout::SingleColumn), + 2 => Ok(EdgeLayout::TwoColumns), + n => Err(format!( + "Edge arrays need a columns definition with one reflexive column or two columns, got {} columns", + n + )), + } +} + +#[allow(clippy::too_many_arguments)] +fn add_edge( + config: &Configuration, + indexer: &Indexer, + buffer: &mut WorkerBuffer, + layout: EdgeLayout, + source: &str, + target: &str, + weight: f32, + pos: u64, +) { + match layout { + EdgeLayout::SingleColumn => { + let fields: [Tokens<'_>; 1] = [smallvec![source, target]]; + buffer.add_row(config, indexer, &fields, weight, pos); } - }; - let buffered = BufReader::with_capacity(64 * 1024, input_file); - - let mut line_number = 1u64; - for result in buffered.lines() { - match result { - Ok(line) => { - if !line.is_empty() { - line_handler(&line); - } - } - Err(err) => { - error!("Can't read line number: {}. Error: {}.", line_number, err); - } - }; + EdgeLayout::TwoColumns => { + let fields: [Tokens<'_>; 2] = [smallvec![source], smallvec![target]]; + buffer.add_row(config, indexer, &fields, weight, pos); + } + } +} + +/// Builds the matrix from parallel arrays of integer node identifiers. The result +/// is identical to feeding the lines `" "` (one reflexive column) +/// or `"\t"` (two columns). +pub fn build_graph_from_int_edges( + config: &Configuration, + sources: &[i64], + targets: &[i64], + weights: Option<&[f32]>, +) -> Result<(SparseMatrix, BuildStats), String> { + let layout = edge_layout(config)?; + if sources.len() != targets.len() { + return Err(format!( + "src has {} element(s) but dst has {}", + sources.len(), + targets.len() + )); + } + check_weights(weights, sources.len())?; + if sources.len() as u64 >= MAX_LINES { + return Err(format!("Too many edges ({})", sources.len())); + } - if line_number % log_every == 0 { - info!("Number of lines processed: {}", line_number); + let indexer = Indexer::default(); + let buffers = run_partitioned(sources.len(), config.num_workers, |first, last, buffer| { + for index in first..last { + let source = IntBuffer::new(sources[index]); + let target = IntBuffer::new(targets[index]); + let weight = weights.map_or(1.0, |w| w[index]); + add_edge( + config, + &indexer, + buffer, + layout, + source.as_str(), + target.as_str(), + weight, + position(0, index as u64, 0), + ); } + }); + finish(config, indexer, buffers) +} - line_number += 1; +/// Builds the matrix from parallel arrays of node names. Unlike text lines, names +/// may contain any character (spaces, tabs, commas). +pub fn build_graph_from_str_edges + Sync>( + config: &Configuration, + sources: &[S], + targets: &[S], + weights: Option<&[f32]>, +) -> Result<(SparseMatrix, BuildStats), String> { + let layout = edge_layout(config)?; + if sources.len() != targets.len() { + return Err(format!( + "src has {} element(s) but dst has {}", + sources.len(), + targets.len() + )); + } + check_weights(weights, sources.len())?; + if sources.len() as u64 >= MAX_LINES { + return Err(format!("Too many edges ({})", sources.len())); } + + let indexer = Indexer::default(); + let buffers = run_partitioned(sources.len(), config.num_workers, |first, last, buffer| { + for index in first..last { + let weight = weights.map_or(1.0, |w| w[index]); + add_edge( + config, + &indexer, + buffer, + layout, + sources[index].as_ref(), + targets[index].as_ref(), + weight, + position(0, index as u64, 0), + ); + } + }); + finish(config, indexer, buffers) } -fn parse_line(line: &str) -> Vec> { - let trimmed = line.trim(); - if trimmed.contains('\t') { - trimmed - .split('\t') - .map(|c| c.split(' ').collect()) - .collect() - } else if trimmed.contains(',') { - trimmed - .split(',') - .map(|c| c.trim().split(' ').collect()) - .collect() - } else { - let mut result = Vec::with_capacity(1); - result.push(trimmed.split(' ').collect()); - result +/// Builds the matrix from hyperedges given as lists of entity names per entity +/// column. Used by tests and by callers that already hold tokenised data. +pub fn build_graph_from_rows + Sync>( + config: &Configuration, + rows: &[Vec>], + weights: Option<&[f32]>, +) -> Result<(SparseMatrix, BuildStats), String> { + check_weights(weights, rows.len())?; + let columns = config.entity_column_names.len(); + if let Some(index) = rows + .iter() + .position(|row| row.len() != columns || row.iter().any(|field| field.is_empty())) + { + return Err(format!( + "row {} does not hold a non-empty list of entities for each of the {} column(s)", + index, columns + )); } + let indexer = Indexer::default(); + let buffers = run_partitioned(rows.len(), config.num_workers, |first, last, buffer| { + for index in first..last { + let fields: SmallVec<[Tokens<'_>; 4]> = rows[index] + .iter() + .zip(&config.columns) + .map(|(field, _)| field.iter().map(|t| t.as_ref()).collect()) + .collect(); + let weight = weights.map_or(1.0, |w| w[index]); + buffer.add_row( + config, + &indexer, + &fields, + weight, + position(0, index as u64, 0), + ); + } + }); + finish(config, indexer, buffers) } diff --git a/src/sparse_matrix.rs b/src/sparse_matrix.rs index 7db31dd..3f1589d 100644 --- a/src/sparse_matrix.rs +++ b/src/sparse_matrix.rs @@ -1,78 +1,401 @@ -use crate::configuration::Column; -use pyo3::pyclass; +use std::sync::OnceLock; + +use pyo3::prelude::*; +use pyo3::sync::PyOnceLock; +use pyo3::types::PyTuple; +use rustc_hash::{FxBuildHasher, FxHashMap}; use serde::{Deserialize, Serialize}; -pub fn create_sparse_matrix_descriptor( - colums: &Vec, -) -> Result { - let mut matrices_descs = create_sparse_matrices_descriptors(colums); - if matrices_descs.len() != 1 { - return Err("More than one relation! Adjust your columns so there is only one relation."); - } - Ok(matrices_descs.remove(0)) +use crate::configuration::Relation; +use crate::entity::hash_entity; + +/// Symmetric sparse co-occurrence matrix of a hypergraph, in CSR form. +/// +/// `values` holds the raw accumulated edge weights; the Markov normalisations are +/// applied on the fly from `row_sums`: +/// +/// * left: `P[i, j] = values[i, j] / row_sums[i]` +/// * symmetric: `S[i, j] = values[i, j] / sqrt(row_sums[i] * row_sums[j])` +#[pyclass(name = "SparseMatrix", module = "pycleora.pycleora")] +pub struct SparseMatrix { + /// Names of the entity columns the matrix was built from. + pub column_names: Vec, + /// Relations between those columns that were combined into the matrix. + pub relations: Vec, + pub entity_ids: Vec, + /// Entity column in which every entity appeared first. + pub column_ids: Vec, + /// Total hyperedge mass of every entity (its weighted degree). + pub row_sums: Vec, + pub indptr: Vec, + pub indices: Vec, + pub values: Vec, + + /// `1 / row_sums` and `1 / sqrt(row_sums)`; zero for entities without mass. + pub(crate) inv_row: Vec, + pub(crate) inv_sqrt_row: Vec, + /// Entity hash -> index, built on first lookup. + lookup: OnceLock>, + /// `entity_ids` as a Python tuple, built on first access. + pub(crate) py_entity_ids: PyOnceLock>, +} + +const STATE_MAGIC: &[u8] = b"PYCLEORA\x02"; + +/// Pickled form (format 2). +#[derive(Serialize, Deserialize)] +struct State { + column_names: Vec, + relations: Vec, + entity_ids: Vec, + column_ids: Vec, + row_sums: Vec, + indptr: Vec, + indices: Vec, + values: Vec, +} + +/// Pickled form written by pycleora <= 3.2. +#[derive(Deserialize)] +struct LegacyState { + descriptor: LegacyDescriptor, + entity_ids: Vec, + entities: Vec, + edges: Vec, + slices: Vec<(usize, usize)>, + column_ids: Vec, +} + +#[derive(Deserialize)] +struct LegacyDescriptor { + col_a_id: u8, + col_a_name: String, + col_b_id: u8, + col_b_name: String, +} + +#[derive(Deserialize)] +struct LegacyEntity { + row_sum: f32, +} + +#[derive(Deserialize)] +struct LegacyEdge { + other_entity_ix: u32, + left_markov_value: f32, + #[allow(dead_code)] + symmetric_markov_value: f32, } -pub fn create_sparse_matrices_descriptors(cols: &Vec) -> Vec { - let mut sparse_matrix_builders: Vec = Vec::new(); - let num_fields = cols.len(); - let mut reflexive_count = 0; - - for i in 0..num_fields { - for j in i..num_fields { - let col_i = &cols[i]; - let col_j = &cols[j]; - if i < j { - let sm = SparseMatrixDescriptor::new( - i as u8, - col_i.name.clone(), - j as u8, - col_j.name.clone(), - ); - sparse_matrix_builders.push(sm); - } else if i == j && col_i.reflexive { - let new_j = num_fields + reflexive_count; - reflexive_count += 1; - let sm = SparseMatrixDescriptor::new( - i as u8, - col_i.name.clone(), - new_j as u8, - col_j.name.clone(), - ); - sparse_matrix_builders.push(sm); +impl SparseMatrix { + #[allow(clippy::too_many_arguments)] + pub fn from_parts( + column_names: Vec, + relations: Vec, + entity_ids: Vec, + column_ids: Vec, + row_sums: Vec, + indptr: Vec, + indices: Vec, + values: Vec, + ) -> SparseMatrix { + let inv_row = row_sums + .iter() + .map(|&s| if s > 0.0 { (1.0 / s) as f32 } else { 0.0 }) + .collect(); + let inv_sqrt_row = row_sums + .iter() + .map(|&s| { + if s > 0.0 { + (1.0 / s.sqrt()) as f32 + } else { + 0.0 + } + }) + .collect(); + SparseMatrix { + column_names, + relations, + entity_ids, + column_ids, + row_sums, + indptr, + indices, + values, + inv_row, + inv_sqrt_row, + lookup: OnceLock::new(), + py_entity_ids: PyOnceLock::new(), + } + } + + pub fn empty() -> SparseMatrix { + SparseMatrix::from_parts( + vec![], + vec![], + vec![], + vec![], + vec![], + vec![0], + vec![], + vec![], + ) + } + + #[inline] + pub fn num_entities(&self) -> usize { + self.entity_ids.len() + } + + #[inline] + pub fn nnz(&self) -> usize { + self.indices.len() + } + + #[inline(always)] + pub fn row_range(&self, row: usize) -> std::ops::Range { + self.indptr[row] as usize..self.indptr[row + 1] as usize + } + + /// The part of entry `k` of the Markov matrix that does not depend on its row: the + /// raw weight, divided by the square root of the column's mass when `symmetric`. + /// The entry itself is this times [`row_factor`](Self::row_factor). + #[inline(always)] + pub(crate) fn entry_factor(&self, k: usize, symmetric: bool) -> f32 { + let value = self.values[k]; + if symmetric { + value * self.inv_sqrt_row[self.indices[k] as usize] + } else { + value + } + } + + /// What every entry of `row` is multiplied by: one over the mass of the row, or + /// over its square root when `symmetric`. + #[inline(always)] + pub(crate) fn row_factor(&self, row: usize, symmetric: bool) -> f32 { + if symmetric { + self.inv_sqrt_row[row] + } else { + self.inv_row[row] + } + } + + /// Index of the entity with the given name. + pub fn index_of(&self, entity_id: &str) -> Option { + let lookup = self.lookup.get_or_init(|| { + let mut map = FxHashMap::with_capacity_and_hasher(self.entity_ids.len(), FxBuildHasher); + for (index, id) in self.entity_ids.iter().enumerate() { + // On a (practically impossible) hash collision the first entity keeps the slot. + map.entry(hash_entity(id)).or_insert(index as u32); } + map + }); + match lookup.get(&hash_entity(entity_id)) { + Some(&index) if self.entity_ids[index as usize] == entity_id => Some(index as usize), + Some(_) => self.entity_ids.iter().position(|id| id == entity_id), + None => None, } } - sparse_matrix_builders -} -#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] -pub struct SparseMatrixDescriptor { - pub col_a_id: u8, - pub col_a_name: String, - pub col_b_id: u8, - pub col_b_name: String, -} + /// Replaces the entity names (and forgets everything derived from them). + pub fn replace_entity_ids(&mut self, entity_ids: Vec) { + self.entity_ids = entity_ids; + self.lookup = OnceLock::new(); + self.py_entity_ids = PyOnceLock::new(); + } -#[pyclass(name = "SparseMatrix", module = "pycleora.pycleora")] -#[derive(Debug, Serialize, Deserialize)] -pub struct SparseMatrix { - pub descriptor: SparseMatrixDescriptor, - #[pyo3(get, set)] - pub entity_ids: Vec, - pub entities: Vec, - pub edges: Vec, - pub slices: Vec<(usize, usize)>, - pub column_ids: Vec, + /// Entities without any neighbour other than themselves, in increasing order. + pub fn isolated_entities(&self) -> Vec { + (0..self.num_entities()) + .filter(|&row| self.row_range(row).all(|k| self.indices[k] as usize == row)) + .collect() + } + + /// Mean number of neighbours (entities other than itself) of an entity. + pub fn mean_neighbours(&self) -> f64 { + let rows = self.num_entities(); + if rows == 0 { + return 0.0; + } + let diagonal: usize = (0..rows) + .map(|row| { + self.row_range(row) + .filter(|&k| self.indices[k] as usize == row) + .count() + }) + .sum(); + (self.nnz() - diagonal) as f64 / rows as f64 + } + + /// Share of the total weight that lies on the diagonal: how lazy the random walk + /// over this matrix is. 0 for a plain adjacency matrix, 1/2 for a reflexive column + /// of two-entity hyperedges. Summed in row order, so the result does not depend + /// on the number of threads. + pub fn self_weight_share(&self) -> f64 { + let total: f64 = self.row_sums.iter().sum(); + if total <= 0.0 { + return 0.0; + } + let diagonal: f64 = (0..self.num_entities()) + .flat_map(|row| self.row_range(row).map(move |k| (row, k))) + .filter(|&(row, k)| self.indices[k] as usize == row) + .map(|(_, k)| self.values[k] as f64) + .sum(); + diagonal / total + } + + /// Edge value under the requested normalisation. + #[inline(always)] + pub fn normalized_value(&self, row: usize, k: usize, kind: Normalization) -> f32 { + let raw = self.values[k]; + match kind { + Normalization::Raw => raw, + Normalization::Left => raw * self.inv_row[row], + Normalization::Symmetric => { + raw * self.inv_sqrt_row[row] * self.inv_sqrt_row[self.indices[k] as usize] + } + } + } + + pub fn to_state_bytes(&self) -> Result, String> { + let state = State { + column_names: self.column_names.clone(), + relations: self.relations.clone(), + entity_ids: self.entity_ids.clone(), + column_ids: self.column_ids.clone(), + row_sums: self.row_sums.clone(), + indptr: self.indptr.clone(), + indices: self.indices.clone(), + values: self.values.clone(), + }; + let mut bytes = STATE_MAGIC.to_vec(); + bincode::serialize_into(&mut bytes, &state) + .map_err(|e| format!("Serialization failed: {}", e))?; + Ok(bytes) + } + + pub fn from_state_bytes(bytes: &[u8]) -> Result { + if let Some(payload) = bytes.strip_prefix(STATE_MAGIC) { + let state: State = bincode::deserialize(payload) + .map_err(|e| format!("Deserialization failed: {}", e))?; + let matrix = SparseMatrix::from_parts( + state.column_names, + state.relations, + state.entity_ids, + state.column_ids, + state.row_sums, + state.indptr, + state.indices, + state.values, + ); + matrix.validate()?; + return Ok(matrix); + } + Self::from_legacy_state_bytes(bytes) + } + + /// Reads a matrix pickled by pycleora <= 3.2. + fn from_legacy_state_bytes(bytes: &[u8]) -> Result { + let legacy: LegacyState = + bincode::deserialize(bytes).map_err(|e| format!("Deserialization failed: {}", e))?; + let n = legacy.entity_ids.len(); + if legacy.entities.len() != n || legacy.column_ids.len() != n || legacy.slices.len() > n { + return Err("Deserialization failed: inconsistent legacy state".to_string()); + } + // Old matrices stored one slice per entity, in entity order. + let mut indptr = vec![0u64; n + 1]; + for (row, (start, end)) in legacy.slices.iter().enumerate() { + if start > end || *end > legacy.edges.len() { + return Err("Deserialization failed: inconsistent legacy state".to_string()); + } + indptr[row] = *start as u64; + indptr[row + 1] = *end as u64; + } + for row in legacy.slices.len()..n { + indptr[row + 1] = indptr[row]; + } + let row_sums: Vec = legacy.entities.iter().map(|e| e.row_sum as f64).collect(); + let mut indices = Vec::with_capacity(legacy.edges.len()); + let mut values = Vec::with_capacity(legacy.edges.len()); + for row in 0..n { + for edge in &legacy.edges[indptr[row] as usize..indptr[row + 1] as usize] { + indices.push(edge.other_entity_ix); + values.push(edge.left_markov_value * legacy.entities[row].row_sum); + } + } + let d = legacy.descriptor; + let (column_names, relations, column_ids) = if d.col_a_name == d.col_b_name + && d.col_a_id != d.col_b_id + && legacy.column_ids.iter().all(|c| *c == d.col_a_id) + { + // a single reflexive column + ( + vec![d.col_a_name], + vec![Relation { a: 0, b: 0 }], + vec![0u8; n], + ) + } else { + let column_ids = legacy + .column_ids + .iter() + .map(|c| if *c == d.col_b_id { 1 } else { 0 }) + .collect(); + ( + vec![d.col_a_name, d.col_b_name], + vec![Relation { a: 0, b: 1 }], + column_ids, + ) + }; + let matrix = SparseMatrix::from_parts( + column_names, + relations, + legacy.entity_ids, + column_ids, + row_sums, + indptr, + indices, + values, + ); + matrix.validate()?; + Ok(matrix) + } + + fn validate(&self) -> Result<(), String> { + let n = self.entity_ids.len(); + let consistent = self.column_ids.len() == n + && self.row_sums.len() == n + && self.indptr.len() == n + 1 + && self.indptr.first() == Some(&0) + && self.indptr.windows(2).all(|w| w[0] <= w[1]) + && self.indptr.last().copied() == Some(self.indices.len() as u64) + && self.indices.len() == self.values.len() + && self.indices.iter().all(|&j| (j as usize) < n); + if consistent { + Ok(()) + } else { + Err("Deserialization failed: inconsistent matrix state".to_string()) + } + } } -#[derive(Debug, Clone, Copy, Serialize, Deserialize)] -pub struct Entity { - pub row_sum: f32, +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Normalization { + Raw, + Left, + Symmetric, } -#[derive(Debug, Serialize, Deserialize)] -pub struct Edge { - pub other_entity_ix: u32, - pub left_markov_value: f32, - pub symmetric_markov_value: f32, +impl Normalization { + pub fn parse(name: Option<&str>) -> Result { + match name.unwrap_or("left") { + "left" => Ok(Normalization::Left), + "symmetric" => Ok(Normalization::Symmetric), + "raw" | "none" => Ok(Normalization::Raw), + other => Err(format!( + "Unknown markov_type '{}'. Use 'left', 'symmetric' or 'raw'.", + other + )), + } + } } diff --git a/src/sparse_matrix_builder.rs b/src/sparse_matrix_builder.rs index 6c34f75..855b999 100644 --- a/src/sparse_matrix_builder.rs +++ b/src/sparse_matrix_builder.rs @@ -1,393 +1,644 @@ -use std::cell::RefCell; +//! Turns hyperedges into the sparse co-occurrence matrix. +//! +//! Everything that is summed here (edge weights, row sums, occurrence counts) is +//! accumulated in integer arithmetic. Integer addition is associative and +//! commutative, so the result does not depend on how the input is split between +//! threads or in which order lines happen to be processed: the same input always +//! yields bit-identical matrices, for any number of workers. + use std::cmp::Reverse; -use std::collections::HashMap; -use std::hash::BuildHasherDefault; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::collections::hash_map::Entry; +use std::sync::atomic::{AtomicU64, Ordering}; +use dashmap::mapref::entry::Entry as DashEntry; use dashmap::DashMap; -use itertools::Itertools; -use rayon::iter::IntoParallelIterator; -use rayon::iter::IntoParallelRefIterator; -use rayon::iter::ParallelDrainFull; -use rayon::iter::ParallelIterator; -use rayon::prelude::ParallelSliceMut; -use rayon::ThreadPoolBuilder; -use rustc_hash::FxHasher; +use rayon::prelude::*; +use rustc_hash::{FxBuildHasher, FxHashMap}; use smallvec::SmallVec; -use crate::entity::{Hyperedge, SMALL_VECTOR_SIZE}; -use crate::sparse_matrix::{Edge, Entity, SparseMatrix, SparseMatrixDescriptor}; +use crate::configuration::Configuration; +use crate::entity::{hash_entity, LineError, Tokens}; +use crate::sparse_matrix::SparseMatrix; -#[derive(Debug, Default)] -struct Row { - occurrence: u32, - row_sum: f32, -} +/// Fixed-point scale of the accumulators: 64 fractional bits. +const FIXED_ONE: f64 = 18_446_744_073_709_551_616.0; // 2^64 -#[derive(Debug, Default)] -pub struct NodeIndexer { - pub key_2_index: HashMap>, - pub index_2_key: Vec, - pub index_2_entity_id: Vec, - pub index_2_column_id: Vec, +#[inline(always)] +fn to_fixed(value: f64) -> u128 { + // `value` is finite and non-negative; the cast saturates on overflow. + (value * FIXED_ONE).round() as u128 } -pub trait NodeIndexerBuilder { - fn process(&self, key: u64, entity_id: &str, column_id: u8); - fn finish(self) -> NodeIndexer; +#[inline(always)] +fn from_fixed(value: u128) -> f64 { + (value as f64) / FIXED_ONE } -#[derive(Debug)] -pub struct SyncNodeIndexerBuilder { - node_indexer: RefCell, +/// Position of a token in the input: (file, line, token). Used to give entities the +/// index they would get when reading the input sequentially. +#[inline(always)] +pub fn position(file: u32, line: u64, token: u64) -> u64 { + ((file as u64 & 0xFFF) << 52) | ((line & 0xF_FFFF_FFFF) << 16) | token.min(0xFFFF) } -impl Default for SyncNodeIndexerBuilder { - fn default() -> Self { - SyncNodeIndexerBuilder { - node_indexer: RefCell::new(NodeIndexer { - key_2_index: Default::default(), - index_2_key: vec![], - index_2_column_id: vec![], - index_2_entity_id: vec![], - }), - } - } +pub const MAX_FILES: usize = 1 << 12; +pub const MAX_LINES: u64 = 1 << 36; + +struct EntityEntry { + /// Smallest input position at which the entity was seen. + pos: u64, + column: u8, + id: Box, + occurrence: AtomicU64, + sum_lo: AtomicU64, + sum_hi: AtomicU64, } -impl NodeIndexerBuilder for SyncNodeIndexerBuilder { - fn process(&self, key: u64, entity_id: &str, column_id: u8) { - let mut node_indexer = self.node_indexer.borrow_mut(); - - if node_indexer.key_2_index.contains_key(&key) { - return; - } - let index = node_indexer.key_2_index.len(); - node_indexer.key_2_index.insert(key, index); - node_indexer.index_2_key.push(key); - node_indexer.index_2_entity_id.push(entity_id.to_string()); - node_indexer.index_2_column_id.push(column_id); +impl EntityEntry { + /// Exact, lock-free 128-bit accumulation. The final value is the plain integer + /// sum of all increments, whatever the interleaving of threads. + #[inline(always)] + fn accumulate(&self, occurrence: u64, sum: u128) { + self.occurrence.fetch_add(occurrence, Ordering::Relaxed); + let lo = sum as u64; + let hi = (sum >> 64) as u64; + let previous = self.sum_lo.fetch_add(lo, Ordering::Relaxed); + let carry = (previous.wrapping_add(lo) < previous) as u64; + self.sum_hi + .fetch_add(hi.wrapping_add(carry), Ordering::Relaxed); } +} - fn finish(self) -> NodeIndexer { - self.node_indexer.into_inner() - } +/// Concurrent registry of entities: name, first position, and row accumulators. +pub struct Indexer { + map: DashMap, } -#[derive(Debug)] -pub struct IndexedEntity { - index: usize, - id: String, - column_id: u8, +/// Entities in their final order, with the per-entity sums. +pub struct IndexedEntities { + pub entity_ids: Vec, + pub column_ids: Vec, + pub occurrences: Vec, + pub row_sums: Vec, + pub key_2_index: FxHashMap, } -#[derive(Debug, Default)] -pub struct AsyncNodeIndexerBuilder { - key_2_entity: DashMap>, - next_index: AtomicUsize, +impl Default for Indexer { + fn default() -> Self { + Indexer { + map: DashMap::with_hasher(FxBuildHasher), + } + } } -impl NodeIndexerBuilder for AsyncNodeIndexerBuilder { - fn process(&self, key: u64, entity_id: &str, column_id: u8) { - self.key_2_entity.entry(key).or_insert_with(|| { - let index = self.next_index.fetch_add(1, Ordering::Relaxed); - let id = entity_id.to_string(); - IndexedEntity { - index, - id, - column_id, +impl Indexer { + #[inline] + pub fn observe(&self, hash: u64, id: &str, column: u8, pos: u64, occurrence: u64, sum: u128) { + // Fast path: a shared lock is enough for entities that are already known. + if let Some(entry) = self.map.get(&hash) { + if entry.pos <= pos { + entry.accumulate(occurrence, sum); + return; } - }); + } + match self.map.entry(hash) { + DashEntry::Occupied(mut occupied) => { + let entry = occupied.get_mut(); + if pos < entry.pos { + entry.pos = pos; + entry.column = column; + } + entry.accumulate(occurrence, sum); + } + DashEntry::Vacant(vacant) => { + vacant.insert(EntityEntry { + pos, + column, + id: id.into(), + occurrence: AtomicU64::new(occurrence), + sum_lo: AtomicU64::new(sum as u64), + sum_hi: AtomicU64::new((sum >> 64) as u64), + }); + } + } } - fn finish(self) -> NodeIndexer { - let numel = self.next_index.into_inner(); - let mut index_2_key: Vec = vec![0; numel]; - let mut index_2_entity_id: Vec> = (0..numel).map(|_| None).collect(); - let mut index_2_column_id: Vec = vec![0; numel]; - - let key_2_index: HashMap> = self - .key_2_entity - .into_iter() - .map(|(key, indexed_entity)| { - let IndexedEntity { - index, - id: entity_id, - column_id, - } = indexed_entity; - index_2_key[index] = key; - index_2_entity_id[index] = Some(entity_id); - index_2_column_id[index] = column_id; - (key, index) - }) - .collect(); + pub fn is_empty(&self) -> bool { + self.map.is_empty() + } - let index_2_entity_id: Vec = index_2_entity_id + /// Orders entities by first appearance in the input (ties: by hash). + pub fn finish(self) -> Result { + let mut entries: Vec<(u64, u64, EntityEntry)> = self + .map .into_iter() - .map(|opt| opt.unwrap_or_default()) + .map(|(hash, entry)| (entry.pos, hash, entry)) .collect(); - - NodeIndexer { - key_2_index, - index_2_key, - index_2_entity_id, - index_2_column_id, + if entries.len() > u32::MAX as usize { + return Err(format!( + "Too many distinct entities ({}); at most {} are supported", + entries.len(), + u32::MAX + )); + } + entries.par_sort_unstable_by_key(|(pos, hash, _)| (*pos, *hash)); + + let n = entries.len(); + let mut entity_ids = Vec::with_capacity(n); + let mut column_ids = Vec::with_capacity(n); + let mut occurrences = Vec::with_capacity(n); + let mut row_sums = Vec::with_capacity(n); + let mut key_2_index = FxHashMap::with_capacity_and_hasher(n, FxBuildHasher); + for (index, (_, hash, entry)) in entries.into_iter().enumerate() { + let sum = + ((entry.sum_hi.into_inner() as u128) << 64) | entry.sum_lo.into_inner() as u128; + entity_ids.push(String::from(entry.id)); + column_ids.push(entry.column); + occurrences.push(entry.occurrence.into_inner()); + row_sums.push(from_fixed(sum)); + key_2_index.insert(hash, index as u32); } + Ok(IndexedEntities { + entity_ids, + column_ids, + occurrences, + row_sums, + key_2_index, + }) } } -impl SparseMatrixDescriptor { - pub fn new(col_a_id: u8, col_a_name: String, col_b_id: u8, col_b_name: String) -> Self { - Self { - col_a_id, - col_a_name, - col_b_id, - col_b_name, - } - } +type PairMap = FxHashMap<(u64, u64), u128>; - pub fn make_buffer(&self, hyperedge_trim_n: usize) -> SparseMatrixBuffer { - SparseMatrixBuffer { - descriptor: self.clone(), - edge_count: 0, - hash_2_row: Default::default(), - hashes_2_edge: Default::default(), - hyperedge_trim_n, - } - } +/// A hyperedge relation too large to expand in full; expanded once global +/// occurrence counts are known. +struct Deferred { + a: Box<[u64]>, + /// `None`: reflexive relation (both sides are `a`). + b: Option>, + value: u128, } -#[derive(Debug)] -pub struct SparseMatrixBuffer { - pub descriptor: SparseMatrixDescriptor, - pub edge_count: u32, - hash_2_row: HashMap>, - hashes_2_edge: HashMap<(u64, u64), f32, BuildHasherDefault>, - hyperedge_trim_n: usize, +/// A line that could not be used, kept for the error report. +#[derive(Debug, Clone)] +pub struct BadLine { + pub pos: u64, + pub text: String, + pub error: LineError, } -impl SparseMatrixBuffer { - pub fn handle_hyperedge(&mut self, hyperedge: &Hyperedge) { - let SparseMatrixDescriptor { - col_a_id, col_b_id, .. - } = self.descriptor; - let total_combinations = hyperedge.edges_num(col_a_id, col_b_id) as u32; +/// Summary of what was read. +#[derive(Debug, Clone, Default)] +pub struct BuildStats { + pub lines_total: u64, + pub lines_used: u64, + pub lines_skipped: u64, + pub first_bad_line: Option, +} - let mut nodes_a = hyperedge.nodes(col_a_id as usize); - let mut nodes_b = hyperedge.nodes(col_b_id as usize); +/// Per-thread accumulation state. +#[derive(Default)] +pub struct WorkerBuffer { + pairs: PairMap, + deferred: Vec, + pub stats: BuildStats, +} - for hash in &nodes_a { - self.update_row(*hash, nodes_b.len() as u32); +/// Adds the contribution of the ordered element `(x, y)` of a cartesian product. +/// +/// The matrix is symmetric, so only one orientation of every pair is stored. An +/// element with `x != y` adds `value` to both `(x, y)` and `(y, x)`; an element with +/// `x == y` adds `value` twice to the diagonal entry. +#[inline(always)] +fn add_element(pairs: &mut PairMap, x: u64, y: u64, value: u128) { + let (key, amount) = if x == y { + ((x, x), value << 1) + } else if x < y { + ((x, y), value) + } else { + ((y, x), value) + }; + match pairs.entry(key) { + Entry::Occupied(mut e) => { + let slot = e.get_mut(); + *slot = slot.saturating_add(amount); } - for hash in &nodes_b { - self.update_row(*hash, nodes_a.len() as u32); + Entry::Vacant(e) => { + e.insert(amount); } + } +} - let value = 1f32 / (total_combinations as f32); +#[inline] +fn add_cross(pairs: &mut PairMap, a: &[u64], b: &[u64], value: u128) { + for &x in a { + for &y in b { + add_element(pairs, x, y, value); + } + } +} - let (nodes_a_high, nodes_a_low) = self.get_high_low_nodes(&mut nodes_a); - let (nodes_b_high, nodes_b_low) = self.get_high_low_nodes(&mut nodes_b); - self.handle_combinations(nodes_a_high, nodes_b_high, value); - self.handle_combinations(nodes_a_high, nodes_b_low, value); - self.handle_combinations(nodes_a_low, nodes_b_high, value); +/// Same result as `add_cross(pairs, a, a, value)` with half the lookups. +#[inline] +fn add_reflexive(pairs: &mut PairMap, a: &[u64], value: u128) { + for i in 0..a.len() { + add_element(pairs, a[i], a[i], value); + for j in (i + 1)..a.len() { + // the two ordered elements (i, j) and (j, i) + if a[i] == a[j] { + add_element(pairs, a[i], a[i], value << 1); + } else { + let key = if a[i] < a[j] { + (a[i], a[j]) + } else { + (a[j], a[i]) + }; + let amount = value << 1; + match pairs.entry(key) { + Entry::Occupied(mut e) => { + let slot = e.get_mut(); + *slot = slot.saturating_add(amount); + } + Entry::Vacant(e) => { + e.insert(amount); + } + } + } + } } +} - fn get_high_low_nodes<'a>( - &self, - nodes: &'a mut SmallVec<[u64; SMALL_VECTOR_SIZE]>, - ) -> (&'a [u64], &'a [u64]) { - if nodes.len() > self.hyperedge_trim_n { - nodes.select_nth_unstable_by_key(self.hyperedge_trim_n, |h| { - Reverse(self.hash_2_row.get(h).map_or(0, |r| r.occurrence)) +impl WorkerBuffer { + /// Records a line that could not be parsed. + pub fn skip_line(&mut self, pos: u64, text: &str, error: LineError) { + self.stats.lines_total += 1; + self.stats.lines_skipped += 1; + let replace = match &self.stats.first_bad_line { + Some(bad) => pos < bad.pos, + None => true, + }; + if replace { + let mut sample: String = text.chars().take(200).collect(); + if sample.len() < text.len() { + sample.push('…'); + } + self.stats.first_bad_line = Some(BadLine { + pos, + text: sample, + error, }); - nodes.split_at(self.hyperedge_trim_n) - } else { - (nodes, &[]) } } - fn handle_combinations(&mut self, a_hashes: &[u64], b_hashes: &[u64], value: f32) { - for a_hash in a_hashes { - for b_hash in b_hashes { - self.add_pair_symmetric(*a_hash, *b_hash, value); + /// Adds one hyperedge. `fields[c]` holds the entities of entity column `c`; + /// `pos` is the position of the line (see [`position`]). + pub fn add_row( + &mut self, + config: &Configuration, + indexer: &Indexer, + fields: &[Tokens<'_>], + weight: f32, + pos: u64, + ) { + self.stats.lines_total += 1; + if weight <= 0.0 { + // A zero weight contributes nothing; the line is treated as absent. + return; + } + self.stats.lines_used += 1; + + let mut hashes: SmallVec<[u64; 16]> = SmallVec::new(); + let mut ranges: SmallVec<[(usize, usize); 4]> = SmallVec::new(); + for tokens in fields { + let start = hashes.len(); + hashes.extend(tokens.iter().map(|t| hash_entity(t))); + ranges.push((start, hashes.len())); + } + + let mut occurrence: SmallVec<[u64; 16]> = SmallVec::from_elem(0, hashes.len()); + let mut row_sum: SmallVec<[u128; 16]> = SmallVec::from_elem(0, hashes.len()); + let weight = weight as f64; + let trim = config.hyperedge_trim_n; + + for relation in &config.relations { + let (a0, a1) = ranges[relation.a as usize]; + let (b0, b1) = ranges[relation.b as usize]; + let (len_a, len_b) = (a1 - a0, b1 - b0); + + let share_a = to_fixed(weight / len_b as f64); + let share_b = to_fixed(weight / len_a as f64); + for i in a0..a1 { + occurrence[i] += len_b as u64; + row_sum[i] = row_sum[i].saturating_add(share_a); + } + for i in b0..b1 { + occurrence[i] += len_a as u64; + row_sum[i] = row_sum[i].saturating_add(share_b); + } + + let value = to_fixed(weight / (len_a as f64 * len_b as f64)); + let reflexive = relation.a == relation.b; + if len_a > trim && len_b > trim { + self.deferred.push(Deferred { + a: hashes[a0..a1].into(), + b: if reflexive { + None + } else { + Some(hashes[b0..b1].into()) + }, + value, + }); + } else if reflexive { + add_reflexive(&mut self.pairs, &hashes[a0..a1], value); + } else { + add_cross(&mut self.pairs, &hashes[a0..a1], &hashes[b0..b1], value); } } - } - fn add_pair_symmetric(&mut self, a_hash: u64, b_hash: u64, value: f32) { - self.edge_count += 1; - self.update_edge(a_hash, b_hash, value); - self.update_edge(b_hash, a_hash, value); + let mut token_index = 0u64; + for (column, tokens) in fields.iter().enumerate() { + let start = ranges[column].0; + for (k, token) in tokens.iter().enumerate() { + let i = start + k; + indexer.observe( + hashes[i], + token, + column as u8, + pos | token_index.min(0xFFFF), + occurrence[i], + row_sum[i], + ); + token_index += 1; + } + } } +} - fn update_row(&mut self, hash: u64, count: u32) { - let val = 1f32 / (count as f32); - let e = self.hash_2_row.entry(hash).or_default(); - e.occurrence += count; - e.row_sum += val +/// Keeps the `trim` entities with the highest global occurrence (ties: smaller hash) +/// in front and returns `(high, low)`. +fn split_high_low<'a>( + nodes: &'a mut [u64], + trim: usize, + entities: &IndexedEntities, +) -> (&'a [u64], &'a [u64]) { + if nodes.len() > trim { + nodes.select_nth_unstable_by_key(trim, |hash| { + let occurrence = entities.occurrences[entities.key_2_index[hash] as usize]; + (Reverse(occurrence), *hash) + }); + nodes.split_at(trim) + } else { + (nodes, &[]) } +} - fn update_edge(&mut self, a_hash: u64, b_hash: u64, val: f32) { - let e = self.hashes_2_edge.entry((a_hash, b_hash)).or_default(); - *e += val; +/// Expands an oversized hyperedge relation: every pair that involves at least one +/// of the `trim` most frequent entities of either side is kept. +fn expand_deferred( + deferred: &Deferred, + trim: usize, + entities: &IndexedEntities, + pairs: &mut PairMap, +) { + let mut a = deferred.a.to_vec(); + let (a_high, a_low) = split_high_low(&mut a, trim, entities); + match &deferred.b { + None => { + add_cross(pairs, a_high, a_high, deferred.value); + add_cross(pairs, a_high, a_low, deferred.value); + add_cross(pairs, a_low, a_high, deferred.value); + } + Some(b) => { + let mut b = b.to_vec(); + let (b_high, b_low) = split_high_low(&mut b, trim, entities); + add_cross(pairs, a_high, b_high, deferred.value); + add_cross(pairs, a_high, b_low, deferred.value); + add_cross(pairs, a_low, b_high, deferred.value); + } } } -#[derive(Debug)] -pub struct SparseMatrixBuffersReducer { - descriptor: SparseMatrixDescriptor, - buffers: Vec, - node_indexer: NodeIndexer, - num_workers: usize, +#[derive(Clone, Copy)] +struct PairEntry { + /// `(row << 32) | column` with `row <= column`. + key: u64, + lo: u64, + hi: u64, } -pub struct EdgeEntry { - pub row: u32, - pub col: u32, - pub value: f32, +impl PairEntry { + #[inline(always)] + fn value(&self) -> u128 { + ((self.hi as u128) << 64) | self.lo as u128 + } } -impl SparseMatrixBuffersReducer { - pub fn new( - node_indexer: NodeIndexer, - buffers: Vec, - num_workers: usize, - ) -> Self { - if buffers.is_empty() { - panic!("Cannot reduce 0 buffers") - } - - let descriptor = buffers[0].descriptor.clone(); - for buffer in &buffers { - if descriptor != buffer.descriptor { - panic!("Can only reduce buffers with the same sparse matrix description") +fn merge_stats(buffers: &[WorkerBuffer]) -> BuildStats { + let mut stats = BuildStats::default(); + for buffer in buffers { + stats.lines_total += buffer.stats.lines_total; + stats.lines_used += buffer.stats.lines_used; + stats.lines_skipped += buffer.stats.lines_skipped; + if let Some(bad) = &buffer.stats.first_bad_line { + let replace = match &stats.first_bad_line { + Some(current) => bad.pos < current.pos, + None => true, + }; + if replace { + stats.first_bad_line = Some(bad.clone()); } } - - Self { - descriptor, - buffers, - node_indexer, - num_workers, - } } + stats +} - pub fn reduce(self) -> SparseMatrix { - ThreadPoolBuilder::new() - .num_threads(self.num_workers) - .build() - .unwrap() - .install(|| { - let node_indexer = self.node_indexer; - - let (hash_2_row_maps, hashes_2_edge_map): (Vec<_>, Vec<_>) = self - .buffers - .into_iter() - .map(|b| (b.hash_2_row, b.hashes_2_edge)) - .unzip(); - let entities = - SparseMatrixBuffersReducer::reduce_to_entities(&node_indexer, hash_2_row_maps); - let mut edges: Vec<_> = - SparseMatrixBuffersReducer::reduce_to_edges(&node_indexer, hashes_2_edge_map); - edges.par_sort_by_key(|entry| (entry.row, entry.col)); - - let slices: Vec<_> = edges - .iter() - .enumerate() - .group_by(|(_, entry)| entry.row) - .into_iter() - .map(|(_, mut group)| { - let first = group.next().expect("Group have at least one element"); - let last = group.last().unwrap_or(first); - (first.0, last.0 + 1) - }) - .collect(); - - let mut edges: Vec<_> = edges - .into_par_iter() - .map(|entry| Edge { - other_entity_ix: entry.col, - left_markov_value: entry.value, - symmetric_markov_value: 0.0, - }) - .collect(); - - slices - .iter() - .enumerate() - .for_each(|(row_ix, (start_ix, end_ix))| { - let row_sum = entities[row_ix].row_sum; - let slice = &mut edges[(*start_ix)..(*end_ix)]; - slice.iter_mut().for_each(|edge| { - let value = edge.left_markov_value; - - let left_markov_normalization = row_sum; - let symmetric_markov_normalization = { - let col_sum = entities[edge.other_entity_ix as usize].row_sum; - (row_sum * col_sum).sqrt() - }; - edge.left_markov_value = value / left_markov_normalization; - edge.symmetric_markov_value = value / symmetric_markov_normalization; - }) - }); - - SparseMatrix { - descriptor: self.descriptor, - entity_ids: node_indexer.index_2_entity_id, - column_ids: node_indexer.index_2_column_id, - entities, - edges, - slices, +/// Combines the per-thread buffers into the final matrix. +/// Must be called from within the rayon pool that should do the work. +pub fn reduce( + config: &Configuration, + indexer: Indexer, + mut buffers: Vec, +) -> Result<(SparseMatrix, BuildStats), String> { + let stats = merge_stats(&buffers); + let entities = indexer.finish()?; + let n = entities.entity_ids.len(); + + // Oversized hyperedges: expanded now that global occurrence counts are known. + let deferred: Vec = buffers + .iter_mut() + .flat_map(|buffer| std::mem::take(&mut buffer.deferred)) + .collect(); + let mut pair_maps: Vec = buffers.into_iter().map(|buffer| buffer.pairs).collect(); + if !deferred.is_empty() { + let trim = config.hyperedge_trim_n; + let chunk = deferred + .len() + .div_ceil(rayon::current_num_threads().max(1)) + .max(1); + let expanded: Vec = deferred + .par_chunks(chunk) + .map(|part| { + let mut pairs = PairMap::default(); + for item in part { + expand_deferred(item, trim, &entities, &mut pairs); } + pairs }) + .collect(); + pair_maps.extend(expanded); } - - fn reduce_to_entities( - node_indexer: &NodeIndexer, - entity_maps: Vec>>, - ) -> Vec { - node_indexer - .index_2_key - .par_iter() - .map(|hash| { - let mut entity_agg = Entity { row_sum: 0.0 }; - for entity_map in entity_maps.iter() { - if let Some(entity) = entity_map.get(hash) { - entity_agg.row_sum += entity.row_sum; + drop(deferred); + + // Entity hashes -> matrix indices, one orientation per pair. + let parts: Vec> = pair_maps + .into_par_iter() + .map(|pairs| { + pairs + .into_iter() + .map(|((x, y), value)| { + let i = entities.key_2_index[&x] as u64; + let j = entities.key_2_index[&y] as u64; + let (row, column) = if i <= j { (i, j) } else { (j, i) }; + PairEntry { + key: (row << 32) | column, + lo: value as u64, + hi: (value >> 64) as u64, } - } - entity_agg - }) - .collect() + }) + .collect() + }) + .collect(); + let total: usize = parts.iter().map(|p| p.len()).sum(); + let mut entries: Vec = Vec::with_capacity(total); + for part in parts { + entries.extend_from_slice(&part); + } + entries.par_sort_unstable_by_key(|entry| entry.key); + + // Sum the partial values of every pair (exact, so the order is irrelevant). + let mut unique = 0usize; + for read in 0..entries.len() { + if unique > 0 && entries[unique - 1].key == entries[read].key { + let sum = entries[unique - 1] + .value() + .saturating_add(entries[read].value()); + entries[unique - 1].lo = sum as u64; + entries[unique - 1].hi = (sum >> 64) as u64; + } else { + entries[unique] = entries[read]; + unique += 1; + } + } + entries.truncate(unique); + + // Symmetric CSR. Scanning the pairs in (row, column) order visits, for every row r, + // first all its entries below the diagonal (as mirrors of earlier rows, in + // increasing column order) and then its entries from the diagonal onwards, so + // the columns of every row come out sorted. + let mut indptr = vec![0u64; n + 1]; + for entry in &entries { + let row = (entry.key >> 32) as usize; + let column = (entry.key & 0xFFFF_FFFF) as usize; + indptr[row + 1] += 1; + if row != column { + indptr[column + 1] += 1; + } + } + for i in 0..n { + indptr[i + 1] += indptr[i]; + } + let nnz = indptr[n] as usize; + let mut indices = vec![0u32; nnz]; + let mut values = vec![0f32; nnz]; + let mut cursor: Vec = indptr[..n].to_vec(); + for entry in &entries { + let row = (entry.key >> 32) as usize; + let column = (entry.key & 0xFFFF_FFFF) as usize; + let value = from_fixed(entry.value()) as f32; + let at = cursor[row] as usize; + indices[at] = column as u32; + values[at] = value; + cursor[row] += 1; + if row != column { + let at = cursor[column] as usize; + indices[at] = row as u32; + values[at] = value; + cursor[column] += 1; + } } - fn reduce_to_edges( - node_indexer: &NodeIndexer, - edge_maps: Vec>>, - ) -> Vec { - let reduced_edge_map: DashMap<(u64, u64), f32, BuildHasherDefault> = - Default::default(); - for mut edge_map in edge_maps.into_iter() { - edge_map.par_drain().for_each(|(k, v)| { - reduced_edge_map - .entry(k) - .and_modify(|rv| *rv += v) - .or_insert(v); - }) + let matrix = SparseMatrix::from_parts( + config.entity_column_names.clone(), + config.relations.clone(), + entities.entity_ids, + entities.column_ids, + entities.row_sums, + indptr, + indices, + values, + ); + Ok((matrix, stats)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fixed_point_round_trip() { + for v in [0.0, 1.0, 0.5, 1.0 / 3.0, 1e-9, 12345.678, 1e9] { + let back = from_fixed(to_fixed(v)); + assert!((back - v).abs() <= v * 1e-15 + 1e-19, "{} -> {}", v, back); } - reduced_edge_map - .into_par_iter() - .map(|((row_hash, col_hash), value)| { - let row = *node_indexer - .key_2_index - .get(&row_hash) - .expect("Hash value was indexed") as u32; - let col = *node_indexer - .key_2_index - .get(&col_hash) - .expect("Hash value was indexed") as u32; - EdgeEntry { row, col, value } - }) - .collect() + // sums are exact whatever the order + let parts = [ + to_fixed(1.0 / 3.0), + to_fixed(1.0 / 7.0), + to_fixed(1e-8), + to_fixed(5.0), + ]; + let forward: u128 = parts.iter().sum(); + let backward: u128 = parts.iter().rev().sum(); + assert_eq!(forward, backward); + } + + #[test] + fn positions_order_like_sequential_reading() { + assert!(position(0, 5, 3) < position(0, 6, 0)); + assert!(position(0, u32::MAX as u64, 9) < position(1, 0, 0)); + assert!(position(2, 7, 1) < position(2, 7, 2)); + assert_eq!(position(0, 1, 70_000), position(0, 1, 65_535)); + } + + #[test] + fn reflexive_shortcut_matches_cross_product() { + let nodes = [5u64, 9, 5, 2, 7, 9, 9]; + let mut a = PairMap::default(); + let mut b = PairMap::default(); + add_cross(&mut a, &nodes, &nodes, 3); + add_reflexive(&mut b, &nodes, 3); + assert_eq!(a, b); + } + + #[test] + fn concurrent_row_accumulation_is_exact() { + let indexer = Indexer::default(); + let big = (1u128 << 64) - 3; // forces carries into the high word + std::thread::scope(|scope| { + for t in 0..8u64 { + let indexer = &indexer; + scope.spawn(move || { + for k in 0..2000u64 { + indexer.observe(42, "x", 0, position(0, t * 10_000 + k, 0), 1, big); + } + }); + } + }); + let entry = indexer.map.get(&42).unwrap(); + let sum = ((entry.sum_hi.load(Ordering::Relaxed) as u128) << 64) + | entry.sum_lo.load(Ordering::Relaxed) as u128; + assert_eq!(sum, big * 16_000); + assert_eq!(entry.occurrence.load(Ordering::Relaxed), 16_000); + assert_eq!(entry.pos, position(0, 0, 0)); } } diff --git a/tests/python/conftest.py b/tests/python/conftest.py new file mode 100644 index 0000000..854149b --- /dev/null +++ b/tests/python/conftest.py @@ -0,0 +1,112 @@ +"""Shared helpers: a slow, obviously-correct reference implementation of the graph +construction, and generators of random hypergraphs.""" + +import numpy as np +import pytest + +from pycleora import SparseMatrix +from pycleora.pycleora import entity_hash + + +def reference_graph(rows, relations, trim=16, weights=None): + """Brute-force construction of the co-occurrence matrix. + + ``rows[i][c]`` is the list of entity names of entity column ``c`` in hyperedge + ``i``; ``relations`` lists pairs of column indices (``(c, c)`` is reflexive). + Returns ``(entity_ids, raw_matrix, row_sums)``. + """ + ids, index = [], {} + used = [w is None or w > 0 for w in (weights if weights is not None else [None] * len(rows))] + for row, keep in zip(rows, used): + if not keep: + continue + for field in row: + for token in field: + if token not in index: + index[token] = len(ids) + ids.append(token) + n = len(ids) + occurrence = np.zeros(n, dtype=np.int64) + row_sums = np.zeros(n) + raw = np.zeros((n, n)) + deferred = [] + + def element(x, y, value): + if x == y: + raw[x, x] += 2 * value + else: + raw[x, y] += value + raw[y, x] += value + + for r, (row, keep) in enumerate(zip(rows, used)): + if not keep: + continue + weight = 1.0 if weights is None else float(weights[r]) + for a, b in relations: + side_a = [index[t] for t in row[a]] + side_b = [index[t] for t in row[b]] + for x in side_a: + occurrence[x] += len(side_b) + row_sums[x] += weight / len(side_b) + for y in side_b: + occurrence[y] += len(side_a) + row_sums[y] += weight / len(side_a) + value = weight / (len(side_a) * len(side_b)) + if len(side_a) > trim and len(side_b) > trim: + deferred.append((side_a, side_b, value)) + else: + for x in side_a: + for y in side_b: + element(x, y, value) + + def split(nodes): + ranked = sorted(nodes, key=lambda i: (-occurrence[i], entity_hash(ids[i]))) + return ranked[:trim], ranked[trim:] + + for side_a, side_b, value in deferred: + a_high, a_low = split(side_a) + b_high, b_low = split(side_b) + for xs, ys in ((a_high, b_high), (a_high, b_low), (a_low, b_high)): + for x in xs: + for y in ys: + element(x, y, value) + return ids, raw, row_sums + + +def dense(graph: SparseMatrix, markov_type: str = "raw") -> np.ndarray: + """The graph's matrix as a dense float64 array.""" + from scipy.sparse import csr_matrix + + indptr, indices, data = graph.to_csr(markov_type) + n = graph.num_entities + return csr_matrix((data.astype(np.float64), indices, indptr), shape=(n, n)).toarray() + + +def lines_from_rows(rows): + """Text form of tokenised rows: fields separated by tabs, entities by spaces.""" + return ["\t".join(" ".join(field) for field in row) for row in rows] + + +def random_rows(rng, n_rows, columns, vocabulary=40, max_len=6, prefix_per_column=True): + """Random hyperedges. ``columns`` lists, per entity column, whether it is complex.""" + rows = [] + for _ in range(n_rows): + row = [] + for c, is_complex in enumerate(columns): + length = int(rng.integers(1, max_len + 1)) if is_complex else 1 + prefix = f"c{c}_" if prefix_per_column else "e" + row.append([f"{prefix}{int(rng.integers(0, vocabulary))}" for _ in range(length)]) + rows.append(row) + return rows + + +@pytest.fixture +def rng(): + return np.random.default_rng(20261118) + + +@pytest.fixture +def small_graph(): + rng = np.random.default_rng(7) + lines = [f"n{int(rng.integers(0, 120))} n{int(rng.integers(0, 120))}" for _ in range(600)] + return SparseMatrix.from_iterator(iter(lines), "complex::reflexive::node"), lines diff --git a/tests/python/data/legacy_3_2_1.json b/tests/python/data/legacy_3_2_1.json new file mode 100644 index 0000000..50746c7 --- /dev/null +++ b/tests/python/data/legacy_3_2_1.json @@ -0,0 +1,199 @@ +{ + "reflexive": { + "pickle": "gAJjcHljbGVvcmEucHljbGVvcmEKU3BhcnNlTWF0cml4CnEAKYFxAWNfY29kZWNzCmVuY29kZQpxAlhDAgAAAAQAAAAAAAAAaXRlbQEEAAAAAAAAAGl0ZW0GAAAAAAAAAAEAAAAAAAAAYQEAAAAAAAAAYgEAAAAAAAAAYwEAAAAAAAAAZAEAAAAAAAAAZQEAAAAAAAAAZgYAAAAAAAAAwqvCqsKqP8KrwqrCqj/Cq8Kqwqo/VlXDlT9VVRVAAAAAQBQAAAAAAAAAAAAAAMKqwqrCqj7CqsKqwqo+AQAAAMKqwqoqPsKqwqoqPgIAAADCqsKqKj7CqsKqKj4EAAAAwqrCqsKqPgoDwoE+AAAAAMKqwqoqPsKqwqoqPgEAAADCqsKqwqo+wqrCqsKqPgIAAADCqsKqwqo+wqrCqsKqPgMAAADCqsKqKj4ewqYYPgAAAADCqsKqKj7CqsKqKj4BAAAAwqrCqsKqPsKqwqrCqj4CAAAAwqrCqsKqPsKqwqrCqj4DAAAAwqrCqio+HsKmGD4BAAAAwojCiAg+HsKmGD4CAAAAwojCiAg+HsKmGD4DAAAAw53DncOdPsOdw53DnT4EAAAAwpnCmcKZPsORw5DCgT4AAAAAMQxDPgoDwoE+AwAAAMK3bVs+w5HDkMKBPgQAAADCiGEYP8KIYRg/BQAAAAAAwoA/AADCgD8GAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAgAAAAAAAAACAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAAEAAAAAAAAAAQAAAAAAAAABMAAAAAAAAAEwAAAAAAAAAUAAAAAAAAAAYAAAAAAAAAAAAAAAAAcQNYBgAAAGxhdGluMXEEhnEFUnEGYi4=", + "entity_ids": [ + "a", + "b", + "c", + "d", + "e", + "f" + ], + "rows": [ + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 2, + 2, + 2, + 2, + 3, + 3, + 3, + 3, + 4, + 4, + 4, + 5 + ], + "cols": [ + 0, + 1, + 2, + 4, + 0, + 1, + 2, + 3, + 0, + 1, + 2, + 3, + 1, + 2, + 3, + 4, + 0, + 3, + 4, + 5 + ], + "left": [ + 0.3333333134651184, + 0.1666666567325592, + 0.1666666567325592, + 0.3333333134651184, + 0.1666666567325592, + 0.3333333134651184, + 0.3333333134651184, + 0.1666666567325592, + 0.1666666567325592, + 0.3333333134651184, + 0.3333333134651184, + 0.1666666567325592, + 0.13333332538604736, + 0.13333332538604736, + 0.43333330750465393, + 0.29999998211860657, + 0.190476194024086, + 0.2142857164144516, + 0.595238208770752, + 1.0 + ], + "symmetric": [ + 0.3333333134651184, + 0.1666666567325592, + 0.1666666567325592, + 0.2519763112068176, + 0.1666666567325592, + 0.3333333134651184, + 0.3333333134651184, + 0.14907118678092957, + 0.1666666567325592, + 0.3333333134651184, + 0.3333333134651184, + 0.14907118678092957, + 0.14907118678092957, + 0.14907118678092957, + 0.43333330750465393, + 0.25354626774787903, + 0.2519763112068176, + 0.25354626774787903, + 0.595238208770752, + 1.0 + ], + "degrees": [ + 1.3333333730697632, + 1.3333333730697632, + 1.3333333730697632, + 1.6666667461395264, + 2.3333332538604736, + 2.0 + ], + "lines": [ + "a b c", + "b c d", + "d e", + "a e e", + "f" + ], + "columns": "complex::reflexive::item" + }, + "bipartite": { + "pickle": "gAJjcHljbGVvcmEucHljbGVvcmEKU3BhcnNlTWF0cml4CnEAKYFxAWNfY29kZWNzCmVuY29kZQpxAlisAQAAAAQAAAAAAAAAdXNlcgEHAAAAAAAAAHByb2R1Y3QGAAAAAAAAAAIAAAAAAAAAdTECAAAAAAAAAHAxAgAAAAAAAABwMgIAAAAAAAAAdTICAAAAAAAAAHAzAgAAAAAAAAB1MwYAAAAAAAAAAADDgD8AAABAAAAAQAAAAD8AAABAAADCgD8MAAAAAAAAAAEAAADCq8Kqwqo+OsONwpM+AgAAAMKrwqrCqj46w43Ckz4EAAAAwqvCqio/OsONEz8AAAAAAADCgD46w43Ckz4FAAAAAAAAP8OzBDU/AAAAAAAAwoA+OsONwpM+AwAAAAAAwoA+AAAAPwIAAAAAAMKAPwAAAD8EAAAAAADCgD8AAAA/AAAAAAAAAD86w40TPwMAAAAAAMKAPgAAAD8BAAAAAADCgD/DswQ1PwYAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAMAAAAAAAAABQAAAAAAAAAFAAAAAAAAAAcAAAAAAAAABwAAAAAAAAAJAAAAAAAAAAkAAAAAAAAACwAAAAAAAAALAAAAAAAAAAwAAAAAAAAABgAAAAAAAAAAAQEAAQBxA1gGAAAAbGF0aW4xcQSGcQVScQZiLg==", + "entity_ids": [ + "u1", + "p1", + "p2", + "u2", + "p3", + "u3" + ], + "rows": [ + 0, + 0, + 0, + 1, + 1, + 2, + 2, + 3, + 3, + 4, + 4, + 5 + ], + "cols": [ + 1, + 2, + 4, + 0, + 5, + 0, + 3, + 2, + 4, + 0, + 3, + 1 + ], + "left": [ + 0.3333333432674408, + 0.3333333432674408, + 0.6666666865348816, + 0.25, + 0.5, + 0.25, + 0.25, + 1.0, + 1.0, + 0.5, + 0.25, + 1.0 + ], + "symmetric": [ + 0.28867512941360474, + 0.28867512941360474, + 0.5773502588272095, + 0.28867512941360474, + 0.7071067690849304, + 0.28867512941360474, + 0.5, + 0.5, + 0.5, + 0.5773502588272095, + 0.5, + 0.7071067690849304 + ], + "degrees": [ + 1.5, + 2.0, + 2.0, + 0.5, + 2.0, + 1.0 + ], + "lines": [ + "u1\tp1 p2", + "u2\tp2 p3", + "u1\tp3", + "u3\tp1" + ], + "columns": "user complex::product" + } +} \ No newline at end of file diff --git a/tests/python/test_benchmark.py b/tests/python/test_benchmark.py new file mode 100644 index 0000000..d2eb02c --- /dev/null +++ b/tests/python/test_benchmark.py @@ -0,0 +1,46 @@ +"""pycleora.benchmark: time and quality of every algorithm, a failure in its own row.""" + +import pytest + +from pycleora import benchmark, embed + + +@pytest.fixture +def labelled(small_graph): + graph, _ = small_graph + return graph, {name: i % 2 for i, name in enumerate(graph.entity_ids)} + + +def test_results_are_time_and_scores(labelled): + """There was a memory column too. It showed 0.00 MB for calls that allocate megabytes: + memory the process already holds is reused, and the peak of the process does not move.""" + graph, labels = labelled + results = benchmark.benchmark_algorithms(graph, labels, {"cleora": lambda g: embed(g, 8, 2)}, num_runs=2) + assert set(results["cleora"]) == {"avg_time", "std_time", "scores", "num_runs"} + assert results["cleora"]["avg_time"] > 0 and results["cleora"]["num_runs"] == 2 + assert 0.0 <= results["cleora"]["scores"]["accuracy"] <= 1.0 + + table = benchmark.format_benchmark_table(results).splitlines() + assert table[0].split() == ["Algorithm", "Time", "(s)", "Accuracy"] + name, seconds, accuracy = table[2].split() + assert name == "cleora" and float(seconds) >= 0 + assert float(accuracy) == pytest.approx(results["cleora"]["scores"]["accuracy"], abs=1e-4) + + +def test_a_failing_algorithm_is_reported_in_its_row(labelled): + graph, labels = labelled + + def broken(g): + raise RuntimeError("no such luck") + + results = benchmark.benchmark_algorithms(graph, labels, {"broken": broken, "cleora": lambda g: embed(g, 8, 2)}) + assert results["broken"] == {"error": "RuntimeError: no such luck"} + assert "accuracy" in results["cleora"]["scores"] # the others are still measured + table = benchmark.format_benchmark_table(results) + assert "broken ERROR: RuntimeError: no such luck" in table + + +def test_a_failing_dataset_is_reported_in_its_row(): + results = benchmark.benchmark_datasets(["no_such_dataset"], lambda g: embed(g, 8, 2)) + assert results["no_such_dataset"]["error"].startswith("ValueError: Unknown dataset: 'no_such_dataset'") + assert "ERROR: ValueError: Unknown dataset" in benchmark.format_dataset_table(results) diff --git a/tests/python/test_benchmark_protocol.py b/tests/python/test_benchmark_protocol.py new file mode 100644 index 0000000..7604233 --- /dev/null +++ b/tests/python/test_benchmark_protocol.py @@ -0,0 +1,31 @@ +"""The evaluation protocol of the benchmark suite: what is ranked against what. It runs +on PyTorch, as the suite does, and is skipped where PyTorch is not installed.""" + +import pathlib +import sys + +import numpy as np +import pytest + +torch = pytest.importorskip("torch") + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2] / "benchmarks")) + +from cleora_bench import tasks # noqa: E402 + + +def test_retrieval_from_an_official_list_of_pairs_queries_each_distinct_pair_from_both_ends(): + # 60 nodes in 30 pairs with one direction per pair: the nearest node is the partner + num_nodes = 60 + vectors = torch.eye(30).repeat_interleave(2, dim=0) + pairs = np.arange(num_nodes, dtype=np.int64).reshape(30, 2) + test = np.concatenate([pairs[:10], pairs[:1]]) # the first pair is listed twice + graph = {"meta": {"num_nodes": num_nodes, "official_link_split": True}, "edges": pairs[10:], + "lp_valid_pos": np.zeros((0, 2), dtype=np.int64), "lp_test_pos": test} + split = {"test_pos": test, "embedded": np.ones(num_nodes, dtype=bool)} + + result = tasks._retrieval(vectors, split, graph, seed=0) + + assert result["num_queries"] == 20 + assert result["all_nodes_mrr"] == 1.0 + assert result["recall@10"] == 1.0 # 0.5 for the repeated pair if it counted as two targets diff --git a/tests/python/test_benchmark_suite.py b/tests/python/test_benchmark_suite.py new file mode 100644 index 0000000..af2ec3c --- /dev/null +++ b/tests/python/test_benchmark_suite.py @@ -0,0 +1,138 @@ +"""The parts of the benchmark suite that decide what the result tables say: which +variant of a method is reported, how methods are ranked, which iteration counts are +"tuned". They only need NumPy, so they are tested here on fabricated job files.""" + +import json +import pathlib +import sys + +import numpy as np +import pytest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2] / "benchmarks")) + +from cleora_bench import configurations, iteration_fit, popularity, report, selection # noqa: E402 + + +def write_job(results, dataset, method, dim, seed, task, validation, test, metric="accuracy", probe="logistic"): + if task == "nc": + probes = {probe: {"metrics": [{metric: test}], "chosen": [{"validation_score": validation}]}} + else: + probes = {probe: {"metrics": {metric: test}, "chosen": {"validation_mrr": validation}}} + job = {"dataset": dataset, "method": method, "dim": dim, "seed": seed, "task": task, "probes": probes, + "embedding": {"status": "ok", "seconds": 1.0, "peak_rss_mb": 10.0, "nodes": 100, "edges": 400}} + path = pathlib.Path(results) / dataset / method / f"dim{dim}" / f"seed{seed}" / f"{task}.json" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(job)) + + +def test_the_variant_is_chosen_on_validation_and_its_test_score_reported(tmp_path): + # 128 dimensions validate better; 1024 happens to test better + for seed, (v128, t128, v1024, t1024) in enumerate([(0.80, 0.70, 0.75, 0.90), (0.82, 0.72, 0.77, 0.92)]): + write_job(tmp_path, "toy", "deepwalk", 128, seed, "nc", v128, t128) + write_job(tmp_path, "toy", "deepwalk", 1024, seed, "nc", v1024, t1024) + table = report.aggregate(report.load_jobs(str(tmp_path))) + cell = report.cell(table, "toy", "nc", "logistic", "accuracy", [("deepwalk", 1024), ("deepwalk", 128)]) + assert cell["variant"] == ["deepwalk", 128] + assert cell["mean"] == pytest.approx(0.71) and cell["runs"] == 2 + assert cell["std"] == pytest.approx(0.01) + + +def test_failed_and_missing_runs_are_told_apart(tmp_path): + job = {"dataset": "toy", "method": "netmf", "dim": 1024, "seed": 0, "task": "nc", + "embedding": {"status": "skipped", "reason": "this implementation is limited to 60000 nodes"}} + path = tmp_path / "toy" / "netmf" / "dim1024" / "seed0" / "nc.json" + path.parent.mkdir(parents=True) + path.write_text(json.dumps(job)) + table = report.aggregate(report.load_jobs(str(tmp_path))) + skipped = report.cell(table, "toy", "nc", "logistic", "accuracy", [("netmf", 1024)]) + assert report.format_cell(skipped, None, None) == "n/a (size)" + never_run = report.cell(table, "toy", "nc", "logistic", "accuracy", [("hope", 1024)]) + assert report.format_cell(never_run, None, None) == "–" + + +def test_ranks_share_ties_and_put_missing_results_last(): + cells = {"a": {"mean": 0.9}, "b": {"mean": 0.8}, "c": {"mean": 0.9}, "d": {"missing": True}} + assert report.ranks(cells) == {"a": 1.5, "b": 3.0, "c": 1.5, "d": 4.0} + assert report.ranks(cells, higher_is_better=False)["b"] == 1.0 + + +def test_summary_counts_wins_and_averages_ranks(): + rows = {"g1": {"a": {"mean": 0.9}, "b": {"mean": 0.8}, "c": {"mean": 0.7}}, + "g2": {"a": {"mean": 0.5}, "b": {"mean": 0.7}, "c": {"missing": True}}, + # being the only method with a result is not a win: the row is not compared + "alone": {"a": {"mean": 0.6}, "b": {"missing": True}, "c": {"missing": True}}, + "empty": {"a": {"missing": True}, "b": {"missing": True}, "c": {"missing": True}}} + summary = report.summary_rows(rows, ["a", "b", "c"]) + assert summary["a"] == {"mean_rank": pytest.approx(1.5), "wins": 1, "results": 2, "rows": 2} + assert summary["b"] == {"mean_rank": pytest.approx(1.5), "wins": 1, "results": 2, "rows": 2} + assert summary["c"] == {"mean_rank": pytest.approx(3.0), "wins": 0, "results": 1, "rows": 2} + + +def test_tuned_iterations_are_the_ones_that_validate_best(tmp_path): + sweep = tmp_path / selection.SWEEP_DIRECTORY + for iterations, name in zip(configurations.SWEEP_ITERATIONS, configurations.sweep("hyperedge", "left")): + # validation peaks at 8 iterations, test at 16 + write_job(sweep, "toy", name, 1024, 0, "nc", 1.0 - abs(iterations - 8) / 100, 1.0 - abs(iterations - 16) / 100) + write_job(sweep, "toy", name, 1024, 0, "lp", 1.0 - abs(iterations - 3) / 100, 0.5, metric="mrr", probe="cosine") + chosen = selection.write(str(tmp_path)) + # a chosen count is run as the configuration of the task's purpose, with its popularity prior + assert chosen == {"toy": {"nc": {"hyperedge/left": "cleora_left_k8_cls"}, "lp": {"hyperedge/left": "cleora_left_k3_sim"}}} + assert configurations.iterations("cleora_left_k3_sim") == 3 + assert configurations.resolve("cleora_left_k3_sim")[1]["popularity"] == configurations.EXTRAS["similarity"]["popularity"] + assert configurations.resolve("cleora_left_k8_cls")[1]["popularity"] == configurations.EXTRAS["classification"]["popularity"] + assert "popularity" not in configurations.resolve("cleora_left_k8")[1] + assert selection.configurations_for(str(tmp_path), "toy", "nc") == ["cleora_left_k8_cls"] + assert selection.configurations_for(str(tmp_path), "other", "nc") == [] + + +def test_configuration_names(): + assert len(configurations.sweep("hyperedge")) == len(configurations.sweep("pair")) == 2 * len(configurations.SWEEP_ITERATIONS) + assert configurations.automatic("classification") == [ + "cleora_left_cls", "cleora_sym_cls", "cleora_pair_left_cls", "cleora_pair_sym_cls"] + method, parameters = configurations.resolve("cleora_pair_sym_sim") + assert method == "cleora_classic" + assert parameters == {"iterations": "auto", "purpose": "similarity", "propagation": "symmetric", "columns": "src dst", + **configurations.EXTRAS["similarity"]} + assert "popularity" not in configurations.resolve("cleora_pair_sym_auto")[1] + with pytest.raises(KeyError, match="Unknown configuration"): + configurations.resolve("cleora_best") + + +def test_regret_is_measured_in_points_against_the_validated_optimum(tmp_path): + for iterations, name in zip(configurations.SWEEP_ITERATIONS, configurations.sweep("pair", "left")): + write_job(tmp_path, "toy", name, 1024, 0, "nc", 1.0 - abs(iterations - 8) / 100, 0.5 + iterations / 1000) + (record,) = iteration_fit.curves(str(tmp_path), "nc") + assert record["best_iterations"] == 8 and record["degree"] == 8.0 and record["share"] == 0.0 + assert iteration_fit.regret(record, 8) == pytest.approx(0.0) + assert iteration_fit.regret(record, 4) == pytest.approx(0.4) # 0.508 - 0.504, in points + # between grid points: linear in log K (halfway between 16 and 24 on that scale is 19.6) + assert iteration_fit.regret(record, np.sqrt(16 * 24)) == pytest.approx(-1.2) + + +def write_exponents(data, task, dataset, scores): + target = pathlib.Path(popularity.path(str(data), task, dataset)) + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(json.dumps(scores)) + + +def rows_of(table): + return {line.split("|")[1].strip(): [cell.strip().strip("*") for cell in line.split("|")[2:-1]] for line in table.splitlines()[2:]} + + +def test_popularity_tables(tmp_path): + # links: one graph that the prior helps (by validation MRR) and one that it hurts + helped = {str(e): {"mrr": 0.30 + (0.1 if e == 0.0625 else 0.05 if e > 0 else 0), "recall@10": 0.20 + e} for e in popularity.EXPONENTS} + hurt = {str(e): {"mrr": 0.50 - e, "recall@10": 0.40 - e} for e in popularity.EXPONENTS} + write_exponents(tmp_path, "lp", "helped", helped) + write_exponents(tmp_path, "lp", "hurt", hurt) + rows = rows_of(popularity.link_table(str(tmp_path))) + # applied everywhere the prior is averaged over both graphs; under the rule the second graph keeps the cosine + assert rows["0.0625"] == ["2", "0.4188", "0.3000", "0.4500", "0.3313", "1"] + assert rows["0"] == ["2", "0.4000", "0.3000", "0.4000", "0.3000", "0"] + # classification: the mean score, and the graphs above and below the unit vectors + write_exponents(tmp_path, "nc", "a", {str(e): {"score": 0.5 + e} for e in popularity.EXPONENTS}) + write_exponents(tmp_path, "nc", "b", {str(e): {"score": 0.7 - e / 2} for e in popularity.EXPONENTS}) + rows = rows_of(popularity.classification_table(str(tmp_path))) + assert rows["0"] == ["2", "0.6000", "0", "0"] and rows["0.25"] == ["2", "0.6625", "1", "1"] + assert popularity.link_table(str(tmp_path / "nothing")) == popularity.classification_table(str(tmp_path / "nothing")) == "" diff --git a/tests/python/test_classify.py b/tests/python/test_classify.py new file mode 100644 index 0000000..710c96e --- /dev/null +++ b/tests/python/test_classify.py @@ -0,0 +1,82 @@ +"""mlp_classify and gcn_classify score the test entities; they do not choose the model with them.""" + +import numpy as np +import pytest + +from pycleora import SparseMatrix, classify, embed +from pycleora.io_utils import from_arrays + +CLASSIFIERS = [classify.mlp_classify, classify.gcn_classify] + + +@pytest.fixture(scope="module") +def noise(): + """A random graph whose labels have nothing to do with it.""" + rng = np.random.default_rng(5) + lines = [f"n{int(rng.integers(0, 300))} n{int(rng.integers(0, 300))}" for _ in range(1500)] + graph = SparseMatrix.from_iterator(iter(lines), "complex::reflexive::node") + labels = {name: int(rng.integers(0, 2)) for name in graph.entity_ids} + return graph, embed(graph, 16, 3), labels + + +@pytest.fixture(scope="module") +def communities(): + """Stochastic block model: 2 x 60 nodes, dense inside, sparse between.""" + rng = np.random.default_rng(1) + block = np.arange(120) % 2 + pairs = [ + (a, b) for a in range(120) for b in range(a + 1, 120) + if rng.random() < (0.25 if block[a] == block[b] else 0.02) + ] + graph = from_arrays(np.array([a for a, _ in pairs]), np.array([b for _, b in pairs])) + labels = {name: int(block[int(name)]) for name in graph.entity_ids} + return graph, embed(graph, 16, 3), labels + + +@pytest.mark.parametrize("classifier", CLASSIFIERS) +def test_test_labels_do_not_choose_the_model(noise, classifier): + """The predictions for the test entities may not depend on their labels, so + flipping those labels has to turn an accuracy of a into 1 - a. + + The checkpoint used to be the one with the best test accuracy: both runs then + reported their best checkpoint and the two accuracies added up to more than 1.""" + graph, embeddings, labels = noise + names = list(labels) + # the test entities of seed=42, train_ratio=0.8: the end of the seed's permutation + test = np.random.default_rng(42).permutation(len(names))[int(len(names) * 0.8):] + flipped = dict(labels) + for position in test: + flipped[names[position]] = 1 - labels[names[position]] + + accuracy = classifier(graph, embeddings, labels, seed=42, train_ratio=0.8)["accuracy"] + accuracy_flipped = classifier(graph, embeddings, flipped, seed=42, train_ratio=0.8)["accuracy"] + assert accuracy + accuracy_flipped == pytest.approx(1.0) + + +@pytest.mark.parametrize("classifier", CLASSIFIERS) +def test_classifiers_learn_planted_communities(communities, classifier): + graph, embeddings, labels = communities + result = classifier(graph, embeddings, labels, seed=0) + assert result["accuracy"] > 0.9 and result["macro_f1"] > 0.9 + assert (result["train_size"], result["test_size"], result["num_classes"]) == (96, 24, 2) + assert classifier(graph, embeddings, labels, seed=0) == result # the split comes from the seed + + +def test_validation_is_held_out_of_the_training_part(): + fit, validation, test = classify._split_labelled(np.random.default_rng(0), 100, 0.8) + assert (len(fit), len(validation), len(test)) == (64, 16, 20) + assert sorted(np.concatenate([fit, validation, test]).tolist()) == list(range(100)) + # the test part is the one there was before a validation part existed + np.testing.assert_array_equal(test, np.random.default_rng(0).permutation(100)[80:]) + + # the smallest training part that can be divided + fit, validation, test = classify._split_labelled(np.random.default_rng(0), 4, 0.5) + assert (len(fit), len(validation), len(test)) == (1, 1, 2) + + +@pytest.mark.parametrize("classifier", CLASSIFIERS) +def test_a_training_part_too_small_to_divide_is_an_error(communities, classifier): + graph, embeddings, labels = communities + few = dict(list(labels.items())[:4]) + with pytest.raises(ValueError, match="at least 2 training entities"): + classifier(graph, embeddings, few, train_ratio=0.3) diff --git a/tests/python/test_cli.py b/tests/python/test_cli.py new file mode 100644 index 0000000..afbf9b8 --- /dev/null +++ b/tests/python/test_cli.py @@ -0,0 +1,121 @@ +"""The ``pycleora embed`` command line.""" + +import numpy as np +import pytest + +from pycleora import SparseMatrix, cli, embed + +LINES = [f"n{i % 60} n{(i * 7 + 1) % 60}" for i in range(300)] + + +def run_embed(tmp_path, monkeypatch, *arguments): + edges = tmp_path / "edges.txt" + edges.write_text("\n".join(LINES) + "\n") + output = tmp_path / "out.npz" + monkeypatch.setattr("sys.argv", ["pycleora", "embed", "-i", str(edges), "-o", str(output), "-d", "16", *arguments]) + cli.main() + with np.load(output, allow_pickle=True) as archive: + return archive["embeddings"], list(archive["entity_ids"]) + + +def test_embed_defaults_are_those_of_the_library(tmp_path, monkeypatch): + graph = SparseMatrix.from_iterator(iter(LINES), "complex::reflexive::node") + vectors, entity_ids = run_embed(tmp_path, monkeypatch) + assert entity_ids == list(graph.entity_ids) + np.testing.assert_array_equal(vectors, embed(graph, 16)) + + +def test_embed_takes_iterations_propagation_and_whitening(tmp_path, monkeypatch): + graph = SparseMatrix.from_iterator(iter(LINES), "complex::reflexive::node") + vectors, _ = run_embed(tmp_path, monkeypatch, "-n", "3", "-p", "symmetric") + np.testing.assert_array_equal(vectors, embed(graph, 16, 3, propagation="symmetric")) + vectors, _ = run_embed(tmp_path, monkeypatch, "--iterations", "auto", "--whiten") + np.testing.assert_array_equal(vectors, embed(graph, 16, "auto", whiten=True)) + + +@pytest.mark.parametrize("value", ["many", "-1", "2.5"]) +def test_embed_rejects_a_bad_number_of_iterations(tmp_path, monkeypatch, capsys, value): + with pytest.raises(SystemExit): + run_embed(tmp_path, monkeypatch, f"--iterations={value}") + assert "--iterations" in capsys.readouterr().err + + +def test_node2vec_is_not_deepwalk(tmp_path, monkeypatch): + """--algorithm node2vec ran with p = q = 1: DeepWalk under another name.""" + from pycleora.algorithms import embed_deepwalk, embed_node2vec + + graph = SparseMatrix.from_iterator(iter(LINES), "complex::reflexive::node") + vectors, _ = run_embed(tmp_path, monkeypatch, "-a", "node2vec") + np.testing.assert_array_equal(vectors, embed_node2vec(graph, 16, p=1.0, q=0.5)) + assert not np.array_equal(vectors, embed_deepwalk(graph, 16)) + + # --p is the return parameter; -p stays the propagation + vectors, _ = run_embed(tmp_path, monkeypatch, "-a", "node2vec", "--p", "0.5", "--q", "2", "-p", "symmetric") + np.testing.assert_array_equal(vectors, embed_node2vec(graph, 16, p=0.5, q=2.0)) + vectors, _ = run_embed(tmp_path, monkeypatch, "-a", "node2vec", "--p", "1", "--q", "1", "--seed", "3") + np.testing.assert_array_equal(vectors, embed_deepwalk(graph, 16, seed=3)) + + +def test_similar_ranks_the_entities_of_a_small_graph(tmp_path, monkeypatch, capsys): + """12 entities at the default 256 dimensions: two cliques of 6 joined by one edge.""" + lines = [f"{clique}{i} {clique}{j}" for clique in "ab" for i in range(6) for j in range(i + 1, 6)] + edges = tmp_path / "edges.txt" + edges.write_text("\n".join(lines + ["a0 b0"]) + "\n") + + def similar(*arguments): + monkeypatch.setattr("sys.argv", ["pycleora", "similar", "-i", str(edges), "-e", "a3", *arguments]) + cli.main() + rows = [line.split() for line in capsys.readouterr().out.splitlines()] + return [(name, float(similarity.split("=")[1])) for name, similarity in rows] + + found = similar() + names = [name for name, _ in found] + similarity = dict(found) + assert len(found) == 10 and "a3" not in names + # its own clique first, then the end of the bridge, then the rest of the other clique + assert set(names[:5]) == {"a0", "a1", "a2", "a4", "a5"} and names[5] == "b0" + assert min(similarity[name] for name in names[:5]) > 0.9 + assert 0.5 > similarity["b0"] > max(similarity[name] for name in names[6:]) + 0.05 + + # asked for more than there are: the 11 others, not the query with a similarity of -1 + everyone = similar("-k", "50") + assert len(everyone) == 11 and "a3" not in [name for name, _ in everyone] + assert min(value for _, value in everyone) > 0 + + +def test_benchmark_command_on_a_small_graph(monkeypatch, capsys): + """Karate club has 34 members: the whitened row needs fewer dimensions than asked + for, node2vec is not a second DeepWalk row, and no memory is reported.""" + import warnings + + from pycleora import benchmark + from pycleora.algorithms import embed_node2vec + + seen = {} + measure = benchmark.benchmark_algorithms + + def spy(graph, labels, algorithms, **kwargs): + seen.update(graph=graph, algorithms=algorithms) + return measure(graph, labels, algorithms, **kwargs) + + monkeypatch.setattr(benchmark, "benchmark_algorithms", spy) + monkeypatch.setattr("sys.argv", ["pycleora", "benchmark", "--dataset", "karate_club", "--dim", "64"]) + with warnings.catch_warnings(): + # as an error, the warning would be what the row of cleora-whitened reports + warnings.filterwarnings("error", message="Whitening cannot work") + cli.main() + output = capsys.readouterr().out + + assert "Using 8 dimensions instead of 64" in output + assert "ERROR" not in output and "Memory" not in output + table = output[output.index("Algorithm"):].splitlines() + assert table[0].split() == ["Algorithm", "Time", "(s)", "Accuracy"] + assert [line.split()[0] for line in table[2:]] == [ + "cleora", "cleora-whitened", "deepwalk", "node2vec", "prone", "randne", + ] + assert all(len(line.split()) == 3 for line in table[2:]) + + graph, algorithms = seen["graph"], seen["algorithms"] + node2vec = algorithms["node2vec"](graph) + np.testing.assert_array_equal(node2vec, embed_node2vec(graph, 8, p=1.0, q=0.5)) + assert not np.array_equal(node2vec, algorithms["deepwalk"](graph)) diff --git a/tests/python/test_cliques_and_inplace.py b/tests/python/test_cliques_and_inplace.py new file mode 100644 index 0000000..4683429 --- /dev/null +++ b/tests/python/test_cliques_and_inplace.py @@ -0,0 +1,110 @@ +"""SparseMatrix.from_cliques, isolated_entities and in-place normalised propagation.""" + +import numpy as np +import pytest + +from pycleora import SparseMatrix +from pycleora import pycleora as core + + +def dense(graph, kind="left"): + indptr, indices, data = graph.to_csr(kind) + matrix = np.zeros((graph.num_entities, graph.num_entities)) + for row in range(graph.num_entities): + matrix[row, indices[indptr[row]:indptr[row + 1]]] = data[indptr[row]:indptr[row + 1]] + return matrix + + +def test_cliques_equal_lines_of_the_same_entities(): + cliques = [["a", "b", "c"], ["b", "d"], ["e"], ["a", "d", "e", "f"]] + from_cliques = SparseMatrix.from_cliques(cliques) + from_lines = SparseMatrix.from_iterator(iter(" ".join(c) for c in cliques), "complex::reflexive::CliqueNode") + assert from_cliques.entity_ids == from_lines.entity_ids + assert from_cliques.column_names == ["CliqueNode"] + np.testing.assert_array_equal(dense(from_cliques, "raw"), dense(from_lines, "raw")) + np.testing.assert_array_equal(from_cliques.entity_degrees, from_lines.entity_degrees) + # any iterable of sequences works: a generator of tuples + again = SparseMatrix.from_cliques(tuple(c) for c in cliques) + np.testing.assert_array_equal(dense(again, "raw"), dense(from_cliques, "raw")) + + +def test_clique_names_may_contain_any_character(): + cliques = [["New York", "tab\there", "a,b"], ["a,b", "ünï cödé"]] + graph = SparseMatrix.from_cliques(cliques) + assert graph.entity_ids == ("New York", "tab\there", "a,b", "ünï cödé") + assert [name for name, _ in graph.get_neighbors("a,b")] == ["New York", "tab\there", "a,b", "ünï cödé"] + + +def test_clique_weights_and_trimming(): + cliques = [["a", "b"], ["b", "c"], ["a", "c"]] + weighted = SparseMatrix.from_cliques(cliques, weights=[2.0, 1.0, 0.0]) + repeated = SparseMatrix.from_cliques([["a", "b"], ["a", "b"], ["b", "c"]]) + np.testing.assert_allclose(dense(weighted, "raw"), dense(repeated, "raw")) + big = [[f"n{i}" for i in range(30)]] + trimmed = SparseMatrix.from_cliques(big, hyperedge_trim_n=4) + full = SparseMatrix.from_cliques(big, hyperedge_trim_n=64) + assert trimmed.num_edges < full.num_edges == 30 * 30 + + +def test_cliques_reject_bad_input(): + with pytest.raises(ValueError, match="sequence of entity names"): + SparseMatrix.from_cliques(["a b", "c d"]) + with pytest.raises(ValueError, match="empty"): + SparseMatrix.from_cliques([["a", "b"], []]) + with pytest.raises(ValueError, match="strings"): + SparseMatrix.from_cliques([["a", 3]]) + with pytest.raises(ValueError, match="weights"): + SparseMatrix.from_cliques([["a", "b"]], weights=[1.0, 2.0]) + + +@pytest.mark.parametrize("lines, expected", [ + (["0", "1 2"], ["0"]), + (["0", "1 2", "0 1"], []), + (["0", "1 2", "2", "3", "1", "0"], ["0", "3"]), + (["0 1", "2"], ["2"]), +]) +def test_isolated_entities(lines, expected): + graph = SparseMatrix.from_iterator(iter(lines), "complex::reflexive::node") + assert [graph.entity_ids[i] for i in graph.isolated_entities] == expected + + +def test_no_entity_of_a_two_column_graph_is_isolated(): + graph = SparseMatrix.from_iterator(iter(["u1\tp1", "u2\tp1"]), "user product") + assert graph.isolated_entities == [] + + +@pytest.mark.parametrize("kind", ["left", "symmetric"]) +def test_inplace_iteration_matches_the_explicit_loop(kind): + rng = np.random.default_rng(0) + graph = SparseMatrix.from_iterator( + iter(f"n{a} n{b}" for a, b in rng.integers(0, 80, (400, 2))), "complex::reflexive::n") + step = graph.left_markov_propagate if kind == "left" else graph.symmetric_markov_propagate + inplace = getattr(graph, f"{kind}_markov_propagate_normalized_inplace") + start = graph.initialize_deterministically(16, seed=5) + for rounds in (0, 1, 2, 5): + expected = start.copy() + for _ in range(rounds): + expected = step(expected) + core.l2_normalize_inplace(expected) + x = start.copy() + assert inplace(x, rounds) is None + np.testing.assert_array_equal(x, expected) + # the result does not depend on the number of threads + one, many = start.copy(), start.copy() + inplace(one, 3, num_workers=1) + inplace(many, 3, num_workers=5) + np.testing.assert_array_equal(one, many) + + +def test_inplace_iteration_validates_its_argument(): + graph = SparseMatrix.from_iterator(iter(["a b", "b c"]), "complex::reflexive::n") + with pytest.raises(ValueError, match="rows"): + graph.left_markov_propagate_normalized_inplace(np.zeros((5, 4), dtype=np.float32), 1) + with pytest.raises(TypeError, match="float32"): + graph.left_markov_propagate_normalized_inplace(np.zeros((3, 4), dtype=np.float64), 1) + with pytest.raises(ValueError, match="C-contiguous"): + graph.left_markov_propagate_normalized_inplace(np.zeros((3, 4), dtype=np.float32, order="F"), 1) + frozen = np.zeros((3, 4), dtype=np.float32) + frozen.flags.writeable = False + with pytest.raises(ValueError, match="writeable"): + graph.left_markov_propagate_normalized_inplace(frozen, 1) diff --git a/tests/python/test_datasets_and_algorithms.py b/tests/python/test_datasets_and_algorithms.py new file mode 100644 index 0000000..6c2c03c --- /dev/null +++ b/tests/python/test_datasets_and_algorithms.py @@ -0,0 +1,209 @@ +"""Datasets say what they are, and the bundled baselines actually work.""" + +import os + +import numpy as np +import pytest + +from pycleora import SparseMatrix, algorithms, datasets +from pycleora.io_utils import from_arrays + +REFLEXIVE = "complex::reflexive::node" + + +# --- datasets -------------------------------------------------------------------- + +def test_registry_marks_every_dataset(): + listed = datasets.list_datasets() + names = [entry["name"] for entry in listed] + assert len(names) == len(set(names)) + assert {"karate_club", "cora", "citeseer", "pubmed", "ppi", "email_eu_core"} <= set(names) + for entry in listed: + assert entry["synthetic"] is False, entry + assert entry["nodes"] > 0 and entry["edges"] > 0 + + +def test_karate_club_is_the_real_network(): + data = datasets.load_dataset("karate_club") + assert data["synthetic"] is False and data["source"] + assert data["num_nodes"] == 34 and data["num_edges"] == 78 and data["num_classes"] == 2 + graph = SparseMatrix.from_iterator(iter(data["edges"]), data["columns"]) + assert graph.num_entities == 34 + degrees = {} + for edge in data["edges"]: + for node in edge.split(): + degrees[node] = degrees.get(node, 0) + 1 + # the two best connected members of Zachary's club: the instructor and the administrator + assert sorted(degrees.values())[-2:] == [16, 17] + assert sorted(set(data["labels"].values())) == [0, 1] + assert sum(1 for label in data["labels"].values() if label == data["labels"]["0"]) == 17 + + +def test_names_that_used_to_be_synthetic_now_say_so(): + for name in ("flickr", "yelp", "dblp", "reddit"): + with pytest.raises(ValueError, match="not available"): + datasets.load_dataset(name) + with pytest.raises(ValueError, match="Unknown dataset"): + datasets.load_dataset("no_such_dataset") + + +def test_synthetic_graphs_are_labelled_synthetic(tmp_path, monkeypatch): + monkeypatch.setenv("PYCLEORA_DATA", str(tmp_path)) + available = datasets.list_synthetic() + assert "cora" in available + data = datasets.load_synthetic("cora") + assert data["synthetic"] is True + assert "ynthetic" in data["name"] and "planted" in data["description"].lower() + data["name"].lower() + assert data["num_nodes"] == 2708 and len(data["labels"]) == 2708 + again = datasets.load_synthetic("cora") # second call comes from the cache + assert again["edges"] == data["edges"] and again["synthetic"] is True + with pytest.raises(ValueError): + datasets.load_synthetic("karate_club") + + +def test_wikipedia_pos_keeps_the_edge_weights(tmp_path, monkeypatch): + """The published POS.mat is weighted (0.5 to 1941.5, two entries in three are not 1); + the loader returned its edges without the weights.""" + import scipy.io + import scipy.sparse + + network = np.array([ + [3.0, 0.5, 0.0, 7.0], # 3.0: a self-loop, which is not an edge + [0.5, 0.0, 2.5, 0.0], + [0.0, 2.5, 0.0, 0.0], + [7.0, 0.0, 1.5, 0.0], # 1.5: stored in one direction only + ]) + groups = np.array([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0], [0.0, 0.0]]) + for filename in ("node2vec_POS.mat", "node2vec_Homo_sapiens.mat"): + scipy.io.savemat( + str(tmp_path / filename), + {"network": scipy.sparse.csc_matrix(network), "group": scipy.sparse.csc_matrix(groups)}, + ) + monkeypatch.setattr(datasets, "_CACHE_DIR", str(tmp_path)) + + def refuse(*args, **kwargs): + raise AssertionError("the files are in the cache: nothing is to be downloaded") + + monkeypatch.setattr(datasets, "_download_with_progress", refuse) + + data = datasets.load_wikipedia_pos() + assert list(data["edges"]) == ["0 1", "0 3", "1 2", "2 3"] + assert data["weights"] == [0.5, 7.0, 2.5, 1.5] + assert data["num_edges"] == 4 and data["multilabel"] is True + + # one weight per edge, in the order of the edges: the graph built from them is the file's + graph = SparseMatrix.from_iterator(iter(data["edges"]), data["columns"], weights=data["weights"]) + adjacency = algorithms._graph_to_adjacency(graph).toarray() + row = [graph.get_entity_index(str(node)) for node in range(4)] + expected = np.array([ + [0.0, 0.5, 0.0, 7.0], + [0.5, 0.0, 2.5, 0.0], + [0.0, 2.5, 0.0, 1.5], + [7.0, 0.0, 1.5, 0.0], + ]) + reordered = adjacency[np.ix_(row, row)] + np.testing.assert_allclose(reordered / reordered[0, 1], expected / expected[0, 1]) + + # the protein network of the same collection has no weights to report + assert "weights" not in datasets.load_ppi() + + +NETWORK = pytest.mark.skipif( + os.environ.get("PYCLEORA_TEST_DOWNLOADS") != "1", + reason="downloads public datasets; set PYCLEORA_TEST_DOWNLOADS=1 to run", +) + + +@NETWORK +@pytest.mark.parametrize("name", ["dolphins", "les_miserables", "football", "cora", "citeseer", "email_eu_core"]) +def test_downloaded_datasets_match_the_registry(name): + registry = {entry["name"]: entry for entry in datasets.list_datasets()}[name] + data = datasets.load_dataset(name) + assert data["synthetic"] is False and data["source"] + assert data["num_nodes"] == registry["nodes"] and data["num_edges"] == registry["edges"] + graph = SparseMatrix.from_iterator(iter(data["edges"]), data["columns"]) + assert graph.num_entities == registry["nodes"] + if data.get("labels"): + assert set(data["labels"]) <= set(graph.entity_ids) + assert len(set(data["labels"].values())) == registry["classes"] + + +# --- baselines --------------------------------------------------------------------- + +@pytest.fixture(scope="module") +def two_communities(): + """Stochastic block model: 2 x 70 nodes, dense inside, sparse between.""" + rng = np.random.default_rng(1) + n = 140 + block = np.arange(n) % 2 + src, dst = [], [] + for a in range(n): + for b in range(a + 1, n): + if rng.random() < (0.25 if block[a] == block[b] else 0.02): + src.append(a) + dst.append(b) + graph = from_arrays(np.array(src), np.array(dst)) + labels = np.array([block[int(name)] for name in graph.entity_ids]) + return graph, labels + + +def separation(embeddings, labels): + """Leave-one-out nearest-centroid accuracy.""" + embeddings = np.asarray(embeddings, dtype=np.float64) + embeddings = embeddings / np.maximum(np.linalg.norm(embeddings, axis=1, keepdims=True), 1e-12) + correct = 0 + for i in range(len(labels)): + mask = np.ones(len(labels), dtype=bool) + mask[i] = False + centroids = np.stack([embeddings[mask & (labels == c)].mean(axis=0) for c in (0, 1)]) + correct += int(np.argmax(centroids @ embeddings[i]) == labels[i]) + return correct / len(labels) + + +ALGORITHMS = [ + ("embed_prone", {}), + ("embed_randne", {}), + ("embed_hope", {}), + ("embed_netmf", {}), + ("embed_grarep", {}), + ("embed_deepwalk", {"num_walks": 10, "walk_length": 20}), + ("embed_node2vec", {"num_walks": 10, "walk_length": 20, "p": 0.5, "q": 2.0}), +] + + +@pytest.mark.parametrize("name,kwargs", ALGORITHMS) +def test_baselines_recover_planted_communities(two_communities, name, kwargs): + graph, labels = two_communities + function = getattr(algorithms, name) + embeddings = function(graph, feature_dim=16, **kwargs) + assert embeddings.shape == (graph.num_entities, 16) + assert embeddings.dtype == np.float32 and np.isfinite(embeddings).all() + # earlier versions of several baselines were at chance level (0.5) on such graphs + assert separation(embeddings, labels) > 0.9, name + np.testing.assert_array_equal(function(graph, feature_dim=16, **kwargs), embeddings) + + +def test_every_listed_algorithm_exists(): + listed = algorithms.list_algorithms() + assert {entry["name"] for entry in listed} == {"prone", "randne", "hope", "netmf", "grarep", "deepwalk", "node2vec"} + for entry in listed: + assert callable(getattr(algorithms, entry["function"])) + + +def test_dense_baselines_refuse_graphs_that_are_too_large(two_communities): + graph, _ = two_communities + for name in ("embed_hope", "embed_netmf", "embed_grarep"): + with pytest.raises(ValueError, match="max_nodes"): + getattr(algorithms, name)(graph, feature_dim=8, max_nodes=50) + + +def test_adjacency_export_is_the_raw_graph(): + graph = from_arrays(["a", "b", "a"], ["b", "c", "c"], weights=[2.0, 1.0, 4.0]) + adjacency = algorithms._graph_to_adjacency(graph).toarray() + assert not adjacency.diagonal().any() + np.testing.assert_array_equal(adjacency, adjacency.T) + row = {name: i for i, name in enumerate(graph.entity_ids)} + assert adjacency[row["a"], row["c"]] == 4 * adjacency[row["b"], row["c"]] + assert adjacency[row["a"], row["b"]] == 2 * adjacency[row["b"], row["c"]] + with_loops = algorithms._graph_to_adjacency(graph, self_loops=True).toarray() + assert with_loops.diagonal().all() diff --git a/tests/python/test_determinism.py b/tests/python/test_determinism.py new file mode 100644 index 0000000..4f5459a --- /dev/null +++ b/tests/python/test_determinism.py @@ -0,0 +1,89 @@ +"""Same input, same output - bit for bit, for any number of worker threads.""" + +import numpy as np +import pytest + +from pycleora import SparseMatrix, embed + +from conftest import lines_from_rows, random_rows + + +def graph_bytes(graph): + indptr, indices, data = graph.to_csr("raw") + return ( + tuple(graph.entity_ids), + indptr.tobytes(), + indices.tobytes(), + data.tobytes(), + np.asarray(graph.entity_degrees).tobytes(), + ) + + +@pytest.fixture(scope="module") +def baskets(): + rng = np.random.default_rng(99) + # many repeated pairs and many hyperedges above the trim threshold of 16 + rows = random_rows(rng, 4000, [True], vocabulary=500, max_len=45) + return lines_from_rows(rows) + + +def test_graph_is_identical_for_any_number_of_workers(baskets): + reference = graph_bytes(SparseMatrix.from_iterator(iter(baskets), "complex::reflexive::item", 16, 1)) + for workers in (2, 3, 8): + for _ in range(3): + graph = SparseMatrix.from_iterator(iter(baskets), "complex::reflexive::item", 16, workers) + assert graph_bytes(graph) == reference + + +def test_weighted_bipartite_graph_is_identical_for_any_number_of_workers(): + rng = np.random.default_rng(5) + rows = random_rows(rng, 3000, [True, True], vocabulary=200, max_len=30) + lines = lines_from_rows(rows) + weights = rng.uniform(0.01, 50.0, size=len(lines)) + reference = graph_bytes(SparseMatrix.from_iterator(iter(lines), "complex::a complex::b", 5, 1, weights=weights)) + for workers in (2, 7): + graph = SparseMatrix.from_iterator(iter(lines), "complex::a complex::b", 5, workers, weights=weights) + assert graph_bytes(graph) == reference + + +def test_embeddings_are_identical_for_any_number_of_workers(baskets): + results = [] + for workers in (1, 2, 5): + graph = SparseMatrix.from_iterator(iter(baskets), "complex::reflexive::item", 16, workers) + results.append(( + graph.embed_fast(32, 5, num_workers=workers), + embed(graph, 32, 5, num_workers=workers), + embed(graph, 32, 4, propagation="symmetric", whiten=False, num_workers=workers, + callback=lambda i, e: None), + )) + for fast, default, looped in results[1:]: + np.testing.assert_array_equal(fast, results[0][0]) + np.testing.assert_array_equal(default, results[0][1]) + np.testing.assert_array_equal(looped, results[0][2]) + + +def test_repeated_runs_are_identical(baskets): + graph = SparseMatrix.from_iterator(iter(baskets), "complex::reflexive::item") + first = embed(graph, 24, 6) + second = embed(graph, 24, 6) + np.testing.assert_array_equal(first, second) + + +def test_order_of_lines_does_not_change_the_matrix(baskets): + """Only the row order follows the input order; the matrix itself is the same.""" + shuffled = list(baskets) + np.random.default_rng(1).shuffle(shuffled) + a = SparseMatrix.from_iterator(iter(baskets), "complex::reflexive::item", 16, 2) + b = SparseMatrix.from_iterator(iter(shuffled), "complex::reflexive::item", 16, 2) + assert sorted(a.entity_ids) == sorted(b.entity_ids) + order_a = np.argsort(a.entity_ids) + order_b = np.argsort(b.entity_ids) + from conftest import dense + matrix_a = dense(a)[np.ix_(order_a, order_a)] + matrix_b = dense(b)[np.ix_(order_b, order_b)] + np.testing.assert_array_equal(matrix_a, matrix_b) + # and so are the embeddings of every entity, because the initial vector of an + # entity depends on its name only (up to the order in which neighbours are summed) + emb_a = a.embed_fast(16, 3)[order_a] + emb_b = b.embed_fast(16, 3)[order_b] + np.testing.assert_allclose(emb_a, emb_b, atol=2e-6) diff --git a/tests/python/test_edges_and_files.py b/tests/python/test_edges_and_files.py new file mode 100644 index 0000000..04b0e7b --- /dev/null +++ b/tests/python/test_edges_and_files.py @@ -0,0 +1,191 @@ +"""Every way of feeding the same graph gives the same matrix.""" + +import pickle + +import numpy as np +import pytest + +from pycleora import SparseMatrix +from pycleora.io_utils import ( + from_arrays, from_edge_list, from_networkx, from_numpy, from_pandas, from_scipy_sparse, + load_embeddings, save_embeddings, to_edge_list, to_networkx, +) + +from conftest import dense, lines_from_rows, random_rows + + +def same(a: SparseMatrix, b: SparseMatrix) -> bool: + return ( + a.entity_ids == b.entity_ids + and all(np.array_equal(x, y) for x, y in zip(a.to_csr("raw"), b.to_csr("raw"))) + and np.array_equal(a.entity_degrees, b.entity_degrees) + ) + + +def test_integer_edge_arrays_equal_lines(rng): + src = rng.integers(-50, 300, size=2000) + dst = rng.integers(-50, 300, size=2000) + lines = [f"{s} {d}" for s, d in zip(src, dst)] + assert same(from_arrays(src, dst), SparseMatrix.from_iterator(iter(lines), "complex::reflexive::node")) + tab_lines = [f"{s}\t{d}" for s, d in zip(src, dst)] + assert same(from_arrays(src, dst, columns="user item"), SparseMatrix.from_iterator(iter(tab_lines), "user item")) + + +@pytest.mark.parametrize("dtype", [np.int8, np.int32, np.uint16, np.uint64, np.int64]) +def test_integer_dtypes(dtype): + src = np.array([1, 2, 3, 1], dtype=dtype) + dst = np.array([2, 3, 4, 4], dtype=dtype) + graph = from_arrays(src, dst) + assert graph.entity_ids == ("1", "2", "3", "4") + assert same(graph, SparseMatrix.from_iterator(iter(["1 2", "2 3", "3 4", "1 4"]), "complex::reflexive::node")) + + +def test_string_edge_arrays_equal_lines(rng): + src = [f"a{int(i)}" for i in rng.integers(0, 80, size=500)] + dst = [f"a{int(i)}" for i in rng.integers(0, 80, size=500)] + lines = [f"{s} {d}" for s, d in zip(src, dst)] + reference = SparseMatrix.from_iterator(iter(lines), "complex::reflexive::node") + assert same(from_arrays(src, dst), reference) + assert same(from_arrays(np.array(src), np.array(dst)), reference) + assert same(from_arrays(np.array(src, dtype=object), np.array(dst, dtype=object)), reference) + assert same(SparseMatrix.from_edges(src, dst), reference) + + +def test_names_in_edge_arrays_may_contain_any_character(): + graph = from_arrays(["New York", "a,b"], ["Los Angeles", "tab\there"], columns="city other") + assert graph.entity_ids == ("New York", "Los Angeles", "a,b", "tab\there") + assert graph.get_entity_index("tab\there") == 3 + + +def test_non_contiguous_edge_arrays(): + src = np.arange(20, dtype=np.int64)[::2] + dst = np.arange(20, dtype=np.int64)[1::2] + assert same(from_arrays(src, dst), from_arrays(src.copy(), dst.copy())) + assert same(SparseMatrix.from_edges(src, dst), from_arrays(src.copy(), dst.copy())) + + +@pytest.mark.parametrize("num_workers", [1, 2, 6]) +def test_files_equal_lines_whatever_the_number_of_workers(tmp_path, rng, num_workers): + rows = random_rows(rng, 3000, [True], vocabulary=400, max_len=30) + lines = lines_from_rows(rows) + paths = [] + for part in range(5): + path = tmp_path / f"part{part}.txt" + chunk = lines[part * 600:(part + 1) * 600] + # mixed line endings, blank lines and a missing final newline + text = ("\r\n" if part % 2 else "\n").join(chunk) + path.write_text(text + ("" if part == 4 else "\n\n"), newline="") + paths.append(str(path)) + from_files = SparseMatrix.from_files(paths, "complex::reflexive::x", 16, num_workers) + from_lines = SparseMatrix.from_iterator(iter(lines), "complex::reflexive::x", 16, 1) + assert same(from_files, from_lines) + + +def test_large_file_is_read_in_batches(tmp_path): + # > 1 MB, so the reader has to split the file into several batches + lines = [f"node_{i} node_{(i * 7919) % 50000} node_{(i * 104729) % 50000}" for i in range(60000)] + path = tmp_path / "big.txt" + path.write_text("\n".join(lines) + "\n") + assert path.stat().st_size > (1 << 20) + assert same( + SparseMatrix.from_files([str(path)], "complex::reflexive::x", 16, 3), + SparseMatrix.from_iterator(iter(lines), "complex::reflexive::x", 16, 2), + ) + + +def test_any_file_extension_is_accepted(tmp_path): + path = tmp_path / "graph.edgelist" + path.write_text("a b\nb c\n") + assert SparseMatrix.from_files([str(path)], "complex::reflexive::x").entity_ids == ("a", "b", "c") + + +def test_pandas_scipy_numpy_networkx_agree(): + pd = pytest.importorskip("pandas") + nx = pytest.importorskip("networkx") + from scipy.sparse import csr_matrix + + pairs = [(0, 1), (1, 2), (0, 3), (3, 4), (2, 4)] + reference = from_arrays([a for a, _ in pairs], [b for _, b in pairs]) + + frame = pd.DataFrame({"s": [a for a, _ in pairs], "t": [b for _, b in pairs], "extra": [0.5] * len(pairs)}) + assert same(from_pandas(frame, "s", "t"), reference) + + adjacency = np.zeros((5, 5)) + for a, b in pairs: + adjacency[a, b] = adjacency[b, a] = 1.0 + G = nx.Graph() + G.add_edges_from(pairs) + # these emit the edges in their own order, so compare after sorting the entities + ref_order = np.argsort(reference.entity_ids) + expected = dense(reference)[np.ix_(ref_order, ref_order)] + for graph in (from_numpy(adjacency), from_scipy_sparse(csr_matrix(adjacency)), from_networkx(G)): + order = np.argsort(graph.entity_ids) + assert sorted(graph.entity_ids) == sorted(reference.entity_ids) + np.testing.assert_array_equal(dense(graph)[np.ix_(order, order)], expected) + + assert same(from_edge_list(pairs), reference) + + exported = to_networkx(reference) + assert set(map(frozenset, exported.edges())) >= {frozenset((str(a), str(b))) for a, b in pairs} + assert {frozenset((a, b)) for a, b, _ in to_edge_list(reference) if a != b} == {frozenset((str(a), str(b))) for a, b in pairs} + + +def test_pandas_missing_values_and_integer_ids(): + pd = pytest.importorskip("pandas") + frame = pd.DataFrame({"s": [1, 2, None, 3], "t": [2, 3, 4, None], "w": [1.0, 2.0, 3.0, 4.0]}) + graph = from_pandas(frame.astype({"s": "Int64", "t": "Int64"}), "s", "t") + assert graph.entity_ids == ("1", "2", "3") + with pytest.raises(ValueError, match="not found"): + from_pandas(frame, "s", "missing") + empty = pd.DataFrame({"s": [None], "t": [None]}) + with pytest.raises(ValueError, match="No valid edges"): + from_pandas(empty, "s", "t") + + +def test_embeddings_round_trip(tmp_path, small_graph): + graph, _ = small_graph + embeddings = graph.embed_fast(8, 2) + for fmt in ("npz", "csv", "tsv"): + path = str(tmp_path / f"emb.{fmt}") + save_embeddings(graph, embeddings, path, format=fmt) + loaded, ids = load_embeddings(path, format=fmt) + assert list(ids) == list(graph.entity_ids) + np.testing.assert_allclose(loaded, embeddings, atol=1e-6) + + +def test_pickle_round_trip(small_graph): + graph, _ = small_graph + restored = pickle.loads(pickle.dumps(graph)) + assert same(graph, restored) + assert repr(restored) == repr(graph) + np.testing.assert_array_equal(restored.embed_fast(8, 2), graph.embed_fast(8, 2)) + assert restored.get_entity_index(graph.entity_ids[5]) == 5 + + +def test_pickles_written_by_3_2_still_load(): + import base64 + import json + import pathlib + + fixture = json.loads((pathlib.Path(__file__).parent / "data" / "legacy_3_2_1.json").read_text()) + for case in fixture.values(): + graph = pickle.loads(base64.b64decode(case["pickle"])) + assert list(graph.entity_ids) == case["entity_ids"] + rows, cols, left, n, _ = graph.to_sparse_csr("left") + assert rows.tolist() == case["rows"] and cols.tolist() == case["cols"] + np.testing.assert_allclose(left, case["left"], rtol=1e-5) + np.testing.assert_allclose(graph.to_sparse_csr("symmetric")[2], case["symmetric"], rtol=1e-5) + np.testing.assert_allclose(graph.entity_degrees, case["degrees"], rtol=1e-6) + # and it describes the same graph as building it again from the lines + rebuilt = SparseMatrix.from_iterator(iter(case["lines"]), case["columns"]) + assert rebuilt.entity_ids == graph.entity_ids + np.testing.assert_allclose(dense(rebuilt, "left"), dense(graph, "left"), rtol=1e-5) + assert rebuilt.column_names == graph.column_names + + +def test_corrupt_pickle_state_is_rejected(): + graph = SparseMatrix.from_iterator(iter(["a b"]), "complex::reflexive::x") + with pytest.raises(RuntimeError, match="Deserialization failed"): + graph.__setstate__(b"PYCLEORA\x02 definitely not a matrix") + with pytest.raises(RuntimeError, match="Deserialization failed"): + graph.__setstate__(b"\x00\x01\x02") diff --git a/tests/python/test_embedding.py b/tests/python/test_embedding.py new file mode 100644 index 0000000..c8a8748 --- /dev/null +++ b/tests/python/test_embedding.py @@ -0,0 +1,673 @@ +"""embed(), whitening and the helpers built on top of them, against NumPy references.""" + +import numpy as np +import pytest + +import pycleora +from pycleora import SparseMatrix, embed, whiten_embeddings +from pycleora.pycleora import center_project, center_project_inplace, column_mean_cov + +from conftest import dense + +COLUMNS = "complex::reflexive::node" + + +@pytest.fixture(scope="module") +def graph(): + rng = np.random.default_rng(11) + # 4 loose communities, so the embedding has real structure + lines = [] + for _ in range(2500): + community = int(rng.integers(0, 4)) + a = community * 100 + int(rng.integers(0, 100)) + b = (community if rng.random() < 0.9 else int(rng.integers(0, 4))) * 100 + int(rng.integers(0, 100)) + lines.append(f"n{a} n{b}") + return SparseMatrix.from_iterator(iter(lines), COLUMNS) + + +def l2(x): + return x / np.maximum(np.linalg.norm(x, axis=1, keepdims=True), 1e-10) + + +def reference_whiten(x): + x = np.asarray(x, dtype=np.float64) + centered = x - x.mean(axis=0) + covariance = centered.T @ centered / (len(x) - 1) + values, vectors = np.linalg.eigh(covariance) + order = np.argsort(values)[::-1] + values, vectors = values[order], vectors[:, order] + pivot = np.argmax(np.abs(vectors), axis=0) + vectors = vectors * np.sign(vectors[pivot, np.arange(vectors.shape[1])]) + return centered @ (vectors / np.sqrt(np.maximum(values, 1e-10))) + + +@pytest.mark.parametrize("propagation", ["left", "symmetric"]) +def test_classic_embedding_matches_numpy(graph, propagation): + transition = dense(graph, propagation) + expected = graph.initialize_deterministically(24, 3).astype(np.float64) + for _ in range(5): + expected = l2(transition @ expected) + result = embed(graph, 24, 5, propagation=propagation, seed=3, whiten=False) + assert result.dtype == np.float32 and result.shape == (graph.num_entities, 24) + np.testing.assert_allclose(result, expected, atol=2e-5) + np.testing.assert_array_equal(result, graph.embed_fast(24, 5, propagation=propagation, seed=3)) + + +def test_default_is_classic_with_automatic_iterations(graph): + """embed(graph) = classic Cleora with the number of iterations the graph suggests.""" + default = embed(graph, 16) + assert graph.suggest_iterations() >= 1 + np.testing.assert_array_equal(default, embed(graph, 16, graph.suggest_iterations(), whiten=False)) + np.testing.assert_array_equal(default, embed(graph, 16, "auto")) + np.testing.assert_allclose(np.linalg.norm(default, axis=1), 1.0, atol=1e-5) + symmetric = embed(graph, 16, propagation="symmetric") + np.testing.assert_array_equal( + symmetric, embed(graph, 16, graph.suggest_iterations("symmetric"), propagation="symmetric")) + + +def test_automatic_iterations_with_whitening_are_those_of_3_2(graph): + np.testing.assert_array_equal(embed(graph, 8, "auto", whiten=True), embed(graph, 8, 40, whiten=True)) + assert pycleora.WHITENED_ITERATIONS == 40 + + +def test_whitened_embedding_matches_numpy(graph): + transition = dense(graph, "left") + expected = graph.initialize_deterministically(16).astype(np.float64) + for _ in range(4): + expected = reference_whiten(l2(transition @ expected)) + result = embed(graph, 16, 4, whiten=True) + np.testing.assert_allclose(result, expected, atol=2e-3) + + +def test_whitened_embedding_is_white(graph): + embeddings = embed(graph, 32, 6, whiten=True).astype(np.float64) + np.testing.assert_allclose(embeddings.mean(axis=0), 0.0, atol=1e-5) + np.testing.assert_allclose(np.cov(embeddings.T), np.eye(32), atol=1e-4) + + +@pytest.mark.parametrize("propagation", ["left", "symmetric"]) +def test_initial_embeddings_are_iterated_as_in_numpy(graph, propagation): + """With initial vectors and nothing to observe in between, all iterations run in the core.""" + transition = dense(graph, propagation) + initial = np.random.default_rng(5).standard_normal((graph.num_entities, 12)).astype(np.float32) + kept = initial.copy() + expected = initial.astype(np.float64) + for _ in range(3): + expected = l2(transition @ expected) + result = embed(graph, 12, 3, propagation=propagation, initial_embeddings=initial) + np.testing.assert_allclose(result, expected, atol=2e-5) + np.testing.assert_array_equal(initial, kept) # the caller's array is not touched + seen = [] + embed(graph, 12, 3, propagation=propagation, initial_embeddings=initial, callback=lambda i, e: seen.append(e)) + np.testing.assert_array_equal(result, seen[-1]) + + +def test_rust_and_python_loops_agree(graph): + """The same algorithm runs in Rust (fast path) and as a Python loop over the Rust + kernels (when a callback or initial embeddings are given).""" + seen = [] + looped = embed(graph, 20, 4, whiten=False, callback=lambda i, e: seen.append((i, e))) + np.testing.assert_array_equal(looped, embed(graph, 20, 4, whiten=False)) + assert [i for i, _ in seen] == [0, 1, 2, 3] + np.testing.assert_array_equal(seen[-1][1], looped) + assert not np.array_equal(seen[0][1], seen[1][1]) # callbacks get their own copies + + init = graph.initialize_deterministically(20) + np.testing.assert_array_equal( + embed(graph, 20, 4, whiten=False, initial_embeddings=init), embed(graph, 20, 4, whiten=False) + ) + with_residual = embed(graph, 20, 4, whiten=False, residual_weight=0.25) + np.testing.assert_allclose( + embed(graph, 20, 4, whiten=False, residual_weight=0.25, callback=lambda i, e: None), + with_residual, atol=1e-6, + ) + assert np.abs(with_residual - embed(graph, 20, 4, whiten=False)).max() > 1e-3 + + +def test_residual_matches_numpy(graph): + transition = dense(graph, "left") + expected = graph.initialize_deterministically(12).astype(np.float64) + for _ in range(3): + expected = l2(0.7 * (transition @ expected) + 0.3 * expected) + np.testing.assert_allclose(embed(graph, 12, 3, whiten=False, residual_weight=0.3), expected, atol=2e-5) + + +def test_initial_embeddings_are_not_modified(graph): + rng = np.random.default_rng(0) + for init in ( + rng.standard_normal((graph.num_entities, 8)).astype(np.float32), + rng.standard_normal((graph.num_entities, 8)), # float64 + np.asfortranarray(rng.standard_normal((graph.num_entities, 8)).astype(np.float32)), + ): + before = init.copy() + for whiten in (True, False): + result = embed(graph, 8, 3, initial_embeddings=init, whiten=whiten) + assert result.dtype == np.float32 and result.shape == init.shape + assert not np.shares_memory(result, init) + np.testing.assert_array_equal(init, before) + with pytest.raises(ValueError, match="rows but graph has"): + embed(graph, 8, 2, initial_embeddings=np.zeros((3, 8), dtype=np.float32)) + + +def test_zero_iterations_return_the_initial_vectors(graph): + init = graph.initialize_deterministically(8, 5) + np.testing.assert_array_equal(embed(graph, 8, 0, seed=5), init) + np.testing.assert_array_equal(embed(graph, 8, 0, seed=5, whiten=False), init) + + +def test_convergence_stops_early(graph): + full, iterations = graph.embed_fast_convergence(8, 50, convergence_threshold=1e-2) + assert 1 < iterations < 50 + np.testing.assert_array_equal(full, graph.embed_fast(8, iterations)) + np.testing.assert_array_equal(embed(graph, 8, 50, whiten=False, convergence_threshold=1e-2), full) + _, never = graph.embed_fast_convergence(8, 6, convergence_threshold=0.0) + assert never == 6 + + +def test_other_normalisations(graph): + transition = dense(graph, "left") + init = graph.initialize_deterministically(10).astype(np.float64) + + expected = init + for _ in range(3): + expected = transition @ expected + expected = expected / np.maximum(np.abs(expected).sum(axis=1, keepdims=True), 1e-10) + np.testing.assert_allclose(embed(graph, 10, 3, normalization="l1", whiten=False), expected, atol=1e-5) + + expected = init + for _ in range(3): + expected = transition @ expected + np.testing.assert_allclose(embed(graph, 10, 3, normalization="none", whiten=False), expected, atol=1e-5) + + spectral = embed(graph, 10, 2, normalization="spectral", whiten=False) + assert spectral.shape == (graph.num_entities, 10) and np.isfinite(spectral).all() + + +def test_argument_validation(graph): + with pytest.raises(ValueError, match="propagation"): + embed(graph, 8, 2, propagation="sideways") + with pytest.raises(ValueError, match="normalization"): + embed(graph, 8, 2, normalization="l3") + with pytest.raises(ValueError, match="negative"): + embed(graph, 8, -1) + with pytest.raises(ValueError, match="'auto'"): + embed(graph, 8, "many") + assert embed(graph, 8, "auto").shape == (graph.num_entities, 8) + for function in (pycleora.embed_with_attention, pycleora.propagate_gpu): + with pytest.raises(ValueError, match="'auto'"): + function(graph, 8, "many") + + +@pytest.mark.parametrize("weight", [-0.1, 1.0, 1.5, float("nan")]) +def test_residual_weight_outside_its_range_is_an_error(graph, weight): + """It used to be ignored without a word: such a run was one without a residual.""" + for loop in ({}, {"callback": lambda i, e: None}): # the Rust fast path, the Python loop + with pytest.raises(ValueError, match="residual_weight"): + embed(graph, 8, 2, residual_weight=weight, **loop) + + +def test_residual_weight_at_the_ends_of_its_range(graph): + np.testing.assert_array_equal(embed(graph, 8, 2, residual_weight=0.0), embed(graph, 8, 2)) + almost_one = embed(graph, 8, 2, residual_weight=0.999) + assert np.isfinite(almost_one).all() and not np.array_equal(almost_one, embed(graph, 8, 2)) + + +def test_whitening_more_dimensions_than_entities_is_reported(): + """Whitening N points in N - 1 or more dimensions makes them all equidistant.""" + rng = np.random.default_rng(31) + lines = [f"n{i % 20} n{int(rng.integers(0, 20))} n{int(rng.integers(0, 20))}" for i in range(60)] + graph = SparseMatrix.from_iterator(iter(lines), COLUMNS) + assert graph.num_entities == 20 + + with pytest.warns(RuntimeWarning, match="20 entities and the embedding 32 dimensions"): + useless = embed(graph, 32, 5, whiten=True) + unit = l2(useless.astype(np.float64)) + cosines = (unit @ unit.T)[~np.eye(20, dtype=bool)] + np.testing.assert_allclose(cosines, -1 / 19, atol=1e-4) # a regular simplex: no information + + for function in ( + lambda: pycleora.embed_multiscale(graph, 32, [1, 2], whiten=True), + lambda: pycleora.embed_with_attention(graph, 32, 2, whiten=True), + lambda: pycleora.embed_directed(lines, COLUMNS, feature_dim=32, num_iterations=2, whiten=True), + ): + with pytest.warns(RuntimeWarning, match="Whitening cannot work"): + function() + + import warnings + + with warnings.catch_warnings(): + warnings.simplefilter("error") + fine = embed(graph, 8, 5, whiten=True) # enough entities for 8 dimensions + embed(graph, 32, 5) # no whitening, no problem + unit = l2(fine.astype(np.float64)) + assert (unit @ unit.T)[~np.eye(20, dtype=bool)].std() > 0.1 + + +# --- whitening ----------------------------------------------------------------- + +def test_whitening_matches_numpy(): + rng = np.random.default_rng(3) + mixing = rng.standard_normal((12, 12)) + data = (rng.standard_normal((4000, 12)) @ mixing + rng.standard_normal(12) * 5).astype(np.float32) + result = whiten_embeddings(data) + np.testing.assert_allclose(result, reference_whiten(data), atol=5e-4) + np.testing.assert_allclose(np.cov(result.astype(np.float64).T), np.eye(12), atol=1e-4) + for workers in (1, 2, 5): + np.testing.assert_array_equal(whiten_embeddings(data, num_workers=workers), result) + + +def test_whitening_leaves_the_input_alone_unless_asked(): + rng = np.random.default_rng(4) + data = rng.standard_normal((500, 6)).astype(np.float32) + before = data.copy() + result = whiten_embeddings(data) + np.testing.assert_array_equal(data, before) + assert not np.shares_memory(result, data) + + in_place = whiten_embeddings(data, inplace=True) + assert in_place is data + np.testing.assert_array_equal(in_place, result) + + +def test_whitening_accepts_any_layout_and_dtype(): + rng = np.random.default_rng(5) + data = rng.standard_normal((300, 5)).astype(np.float32) + expected = whiten_embeddings(data) + for variant in (np.asfortranarray(data), data.astype(np.float64), np.hstack([data, data])[:, :5], data.tolist()): + np.testing.assert_allclose(whiten_embeddings(variant), expected, atol=1e-5) + strided = np.repeat(data, 2, axis=1)[:, ::2] + assert not strided.flags.c_contiguous + np.testing.assert_array_equal(whiten_embeddings(strided), expected) + + +def test_whitening_can_reduce_the_dimension(): + rng = np.random.default_rng(6) + data = (rng.standard_normal((2000, 10)) * np.arange(10, 0, -1)).astype(np.float32) + reduced = whiten_embeddings(data, n_components=3) + assert reduced.shape == (2000, 3) + np.testing.assert_allclose(reduced, whiten_embeddings(data)[:, :3], atol=1e-5) + # in-place is impossible when the shape changes: the input must stay intact + before = data.copy() + assert whiten_embeddings(data, n_components=3, inplace=True).shape == (2000, 3) + np.testing.assert_array_equal(data, before) + + +def test_whitening_edge_cases(): + single = np.ones((1, 4), dtype=np.float32) + np.testing.assert_array_equal(whiten_embeddings(single), single) + with pytest.raises(ValueError, match="2-dimensional"): + whiten_embeddings(np.ones(4, dtype=np.float32)) + constant = np.ones((50, 3), dtype=np.float32) + assert np.isfinite(whiten_embeddings(constant)).all() + + +def test_covariance_and_projection_kernels(): + rng = np.random.default_rng(8) + data = rng.standard_normal((1234, 7)).astype(np.float32) + mean, covariance = column_mean_cov(data) + assert mean.dtype == covariance.dtype == np.float64 + np.testing.assert_allclose(mean, data.astype(np.float64).mean(axis=0), atol=1e-12) + np.testing.assert_allclose(covariance, np.cov(data.astype(np.float64).T), atol=1e-10) + np.testing.assert_array_equal(covariance, covariance.T) + for workers in (1, 2, 3, 8): + other_mean, other_covariance = column_mean_cov(data, workers) + np.testing.assert_array_equal(other_mean, mean) + np.testing.assert_array_equal(other_covariance, covariance) + fortran_mean, fortran_covariance = column_mean_cov(np.asfortranarray(data)) + np.testing.assert_array_equal(fortran_covariance, covariance) + + shift = rng.standard_normal(7).astype(np.float32) + transform = rng.standard_normal((7, 4)).astype(np.float32) + projected = center_project(data, shift, transform) + np.testing.assert_allclose(projected, (data - shift) @ transform, atol=1e-4) + np.testing.assert_array_equal(center_project(np.asfortranarray(data), shift, np.asfortranarray(transform)), projected) + + square = rng.standard_normal((7, 7)).astype(np.float32) + target = data.copy() + center_project_inplace(target, shift, square) + np.testing.assert_array_equal(target, center_project(data, shift, square)) + with pytest.raises(ValueError, match="C-contiguous"): + center_project_inplace(np.asfortranarray(data), shift, square) + with pytest.raises(ValueError, match="square"): + center_project_inplace(data.copy(), shift, transform) + with pytest.raises(ValueError): + center_project(data, shift[:3], transform) + + +# --- inductive / streaming ------------------------------------------------------- + +def cosine(a, b): + return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b))) + + +@pytest.mark.parametrize("whiten", [True, False]) +def test_inductive_update_keeps_known_entities_where_they_are(whiten): + rng = np.random.default_rng(21) + existing = [f"n{int(rng.integers(0, 60))} n{int(rng.integers(0, 60))}" for _ in range(400)] + graph = SparseMatrix.from_iterator(iter(existing), COLUMNS) + embeddings = embed(graph, 16, 4, whiten=whiten) + new_edges = ["n1 fresh_a", "n2 fresh_b", "n3 fresh_b", "fresh_a fresh_chain", "island_1 island_2"] + + updated_graph, updated = pycleora.embed_inductive(graph, embeddings, existing, new_edges, COLUMNS) + assert updated.dtype == np.float32 and updated.shape == (graph.num_entities + 5, 16) + old_rows = updated_graph.get_entity_indices(list(graph.entity_ids)) + np.testing.assert_array_equal(updated[old_rows], embeddings) + + def vector(name, source=updated, source_graph=updated_graph): + return source[source_graph.get_entity_index(name)].astype(np.float64) + + # one known neighbour: the new entity lands on it; a chain is reached in the next round + assert cosine(vector("fresh_a"), vector("n1")) > 0.9999 + assert cosine(vector("fresh_chain"), vector("n1")) > 0.9999 + # two known neighbours: in between them + middle = vector("n2") + vector("n3") + assert cosine(vector("fresh_b"), middle) > 0.9999 + # no path to anything known: no information, zero vector + assert not vector("island_1").any() and not vector("island_2").any() + if not whiten: + np.testing.assert_allclose(np.linalg.norm(vector("fresh_b")), 1.0, atol=1e-5) + + +def test_inductive_update_keeps_a_trained_model_valid(): + """A classifier trained before the update must still work after it.""" + rng = np.random.default_rng(22) + nodes = 300 + label = np.arange(nodes) % 3 + + def edge(): + a = int(rng.integers(0, nodes)) + same = np.flatnonzero(label == label[a]) + b = int(rng.choice(same)) if rng.random() < 0.9 else int(rng.integers(0, nodes)) + return f"v{a} v{b}" + + existing = [edge() for _ in range(3000)] + graph = SparseMatrix.from_iterator(iter(existing), COLUMNS) + embeddings = embed(graph, 32, 5) + classes = np.array([label[int(name[1:])] for name in graph.entity_ids]) + centroids = np.stack([embeddings[classes == c].mean(axis=0) for c in range(3)]) + + def accuracy(matrix, matrix_graph): + truth = np.array([label[int(name[1:])] for name in matrix_graph.entity_ids]) + return float((np.argmax(matrix @ centroids.T, axis=1) == truth).mean()) + + before = accuracy(embeddings, graph) + assert before > 0.9 + more = [edge() for _ in range(300)] + updated_graph, updated = pycleora.embed_inductive(graph, embeddings, existing, more, COLUMNS) + assert accuracy(updated, updated_graph) >= before - 0.02 + + +def test_inductive_modes_and_validation(): + existing = ["a b", "b c", "c d", "d a"] + graph = SparseMatrix.from_iterator(iter(existing), COLUMNS) + embeddings = embed(graph, 4, 3, whiten=False) + retrained_graph, retrained = pycleora.embed_inductive( + graph, embeddings, existing, ["d e"], COLUMNS, num_iterations=3, mode="retrain", whiten=False + ) + assert retrained.shape == (5, 4) and np.isfinite(retrained).all() + again = pycleora.embed_inductive( + graph, embeddings, existing, ["d e"], COLUMNS, num_iterations=3, mode="retrain", whiten=False + )[1] + np.testing.assert_array_equal(retrained, again) # no hidden randomness + + with pytest.raises(ValueError, match="Unknown mode"): + pycleora.embed_inductive(graph, embeddings, existing, ["d e"], COLUMNS, mode="magic") + with pytest.raises(ValueError, match="rows but graph has"): + pycleora.embed_inductive(graph, embeddings[:2], existing, ["d e"], COLUMNS) + + +def test_streaming_keeps_coordinates_stable(): + rng = np.random.default_rng(23) + batches = [[f"n{int(rng.integers(0, 80 + 40 * b))} n{int(rng.integers(0, 80 + 40 * b))}" for _ in range(500)] + for b in range(3)] + snapshots = [] + graph, embeddings = pycleora.embed_streaming( + batches, COLUMNS, feature_dim=12, num_iterations=4, + batch_callback=lambda i, g, e: snapshots.append((g.entity_ids, e.copy())), + ) + assert len(snapshots) == 3 and embeddings.shape == (graph.num_entities, 12) + first_ids, first = snapshots[0] + np.testing.assert_array_equal(embeddings[graph.get_entity_indices(list(first_ids))], first) + np.testing.assert_array_equal(snapshots[0][1], embed(SparseMatrix.from_iterator(iter(batches[0]), COLUMNS), 12, 4)) + + refreshed_graph, refreshed = pycleora.embed_streaming(batches, COLUMNS, feature_dim=12, num_iterations=4, refresh_every=1) + assert refreshed.shape == embeddings.shape and np.isfinite(refreshed).all() + assert not np.array_equal(refreshed, embeddings) + with pytest.raises(ValueError, match="refresh_every"): + pycleora.embed_streaming(batches, COLUMNS, refresh_every=0) + + +def test_alignment_recovers_a_rotation(): + rng = np.random.default_rng(24) + old = rng.standard_normal((200, 6)).astype(np.float32) + rotation, _ = np.linalg.qr(rng.standard_normal((6, 6))) + ids = [f"e{i}" for i in range(200)] + rotated = (old @ rotation).astype(np.float32) + # the new embedding has extra entities and a different order + order = rng.permutation(200) + new_ids = [ids[i] for i in order] + ["extra"] + new = np.vstack([rotated[order], rng.standard_normal((1, 6)).astype(np.float32)]) + aligned = pycleora._align_to_previous(new, new_ids, old, ids) + np.testing.assert_allclose(aligned[:200], old[order], atol=1e-4) + + +# --- similarity search / link prediction ---------------------------------------------- + +def test_find_most_similar_matches_brute_force(graph): + embeddings = embed(graph, 16, 4) + unit = l2(embeddings.astype(np.float64)) + query = graph.entity_ids[42] + similarities = unit @ unit[42] + similarities[42] = -np.inf + expected = np.argsort(-similarities)[:7] + found = pycleora.find_most_similar(graph, embeddings, query, top_k=7) + assert [hit["index"] for hit in found] == expected.tolist() + assert [hit["entity_id"] for hit in found] == [graph.entity_ids[i] for i in expected] + np.testing.assert_allclose([hit["similarity"] for hit in found], similarities[expected], atol=1e-5) + + with_self = pycleora.find_most_similar(graph, embeddings, query, top_k=3, exclude_self=False) + assert with_self[0]["entity_id"] == query and with_self[0]["similarity"] == pytest.approx(1.0, abs=1e-5) + assert pycleora.find_most_similar(graph, embeddings, query, top_k=0) == [] + everyone = pycleora.find_most_similar(graph, embeddings, query, top_k=10**6, exclude_self=False) + assert len(everyone) == graph.num_entities + others = pycleora.find_most_similar(graph, embeddings, query, top_k=10**6) + assert len(others) == graph.num_entities - 1 and query not in [hit["entity_id"] for hit in others] + with pytest.raises(ValueError, match="not found"): + pycleora.find_most_similar(graph, embeddings, "nobody") + + +def test_find_most_similar_never_returns_the_query(): + """Asked for more entities than there are others, it returned the query as well, + with a similarity of -1.""" + graph = SparseMatrix.from_iterator(iter(["a b", "b c", "c d", "d a", "a c"]), COLUMNS) + embeddings = embed(graph, 8, 2) + for top_k in (3, 4, 100): + found = pycleora.find_most_similar(graph, embeddings, "a", top_k=top_k) + assert sorted(hit["entity_id"] for hit in found) == ["b", "c", "d"] + expected = [pycleora.cosine_similarity(embeddings[hit["index"]], embeddings[graph.get_entity_index("a")]) for hit in found] + np.testing.assert_allclose([hit["similarity"] for hit in found], expected, atol=1e-6) + assert len(pycleora.find_most_similar(graph, embeddings, "a", top_k=100, exclude_self=False)) == 4 + + # an entity pointing exactly the other way has cosine -1 and is a result like any other + row = {name: i for i, name in enumerate(graph.entity_ids)} + vectors = np.zeros((4, 2), dtype=np.float32) + vectors[row["a"]], vectors[row["b"]], vectors[row["c"]], vectors[row["d"]] = (1, 0), (-1, 0), (0, 1), (1, 1) + found = pycleora.find_most_similar(graph, vectors, "a", top_k=3) + assert [hit["entity_id"] for hit in found] == ["d", "c", "b"] + assert found[-1]["similarity"] == pytest.approx(-1.0) + + +@pytest.mark.parametrize("exclude_existing", [True, False]) +def test_predict_links_matches_brute_force(graph, exclude_existing): + n = graph.num_entities + embeddings = embed(graph, 16, 4) + unit = l2(embeddings.astype(np.float64)) + scores = unit @ unit.T + np.fill_diagonal(scores, -np.inf) + if exclude_existing: + scores[dense(graph) > 0] = -np.inf + + sources = [graph.entity_ids[i] for i in (3, 77, 150)] + rows = [3, 77, 150] + # a pair of two sources counts once, from the source with the lower index + flat = [ + (scores[r, c], r, c) for r in rows for c in range(n) + if np.isfinite(scores[r, c]) and not (c in rows and c < r) + ] + flat.sort(reverse=True) + expected = flat[:9] + found = pycleora.predict_links(graph, embeddings, top_k=9, exclude_existing=exclude_existing, source_entities=sources) + assert [(p["source"], p["target"]) for p in found] == [(graph.entity_ids[r], graph.entity_ids[c]) for _, r, c in expected] + np.testing.assert_allclose([p["score"] for p in found], [s for s, _, _ in expected], atol=1e-5) + + everything = pycleora.predict_links(graph, embeddings, top_k=5, exclude_existing=exclude_existing) + unordered = scores[np.triu_indices(n, k=1)] + best = np.sort(unordered[np.isfinite(unordered)])[::-1][:5] + np.testing.assert_allclose([p["score"] for p in everything], best, atol=1e-5) + assert pycleora.predict_links(graph, embeddings, top_k=0) == [] + + +def test_predict_links_returns_every_pair_once(graph): + """Every pair used to come back as (a, b) and as (b, a): top_k=10 gave 5 pairs.""" + embeddings = embed(graph, 16, 4) + + def pairs(predictions): + return [frozenset((p["source"], p["target"])) for p in predictions] + + found = pycleora.predict_links(graph, embeddings, top_k=10) + assert len(found) == 10 and len(set(pairs(found))) == 10 + + # both ends of the best pair as sources, one of them named twice + first, second = found[0]["source"], found[0]["target"] + among = pycleora.predict_links(graph, embeddings, top_k=10, source_entities=[second, first, second]) + assert len(among) == 10 and len(set(pairs(among))) == 10 + assert all(p["source"] in (first, second) for p in among) + assert pairs(among)[0] == pairs(found)[0] + + # fewer pairs than asked for: all of them, 4 * 3 / 2 + small = SparseMatrix.from_iterator(iter(["a b", "b c", "c d"]), COLUMNS) + everything = pycleora.predict_links(small, embed(small, 4, 2), top_k=100, exclude_existing=False) + assert len(everything) == 6 and len(set(pairs(everything))) == 6 + + +# --- the other embedding variants -------------------------------------------------------- + +def test_directed_embedding_follows_the_arrows(): + lines = ["a b", "a c", "b c"] + graph, embeddings = pycleora.embed_directed(lines, COLUMNS, feature_dim=6, num_iterations=1, whiten=False) + init = graph.initialize_deterministically(6).astype(np.float64) + row = {name: i for i, name in enumerate(graph.entity_ids)} + # "a" points to b and c, "b" to c, "c" to nothing: it keeps its own vector + np.testing.assert_allclose(embeddings[row["a"]], l2((init[row["b"]] + init[row["c"]])[None])[0], atol=1e-5) + np.testing.assert_allclose(embeddings[row["b"]], l2(init[row["c"]][None])[0], atol=1e-5) + np.testing.assert_allclose(embeddings[row["c"]], l2(init[row["c"]][None])[0], atol=1e-5) + + hyper = ["x y z w", "w x"] + graph, embeddings = pycleora.embed_directed(hyper, COLUMNS, feature_dim=2, num_iterations=3) + assert embeddings.shape == (4, 2) and np.isfinite(embeddings).all() + + +def test_directed_sinks_do_not_erase_the_embedding(): + """A sink had a zero row, and the zeros moved one step upstream with every + iteration: after 5 of them a chain of 5 was all zeros.""" + chain = ["a b", "b c", "c d", "d e"] + graph, embeddings = pycleora.embed_directed(chain, COLUMNS, feature_dim=6, num_iterations=5) + np.testing.assert_allclose(np.linalg.norm(embeddings, axis=1), 1.0, atol=1e-5) + # what moves upstream now is the vector of the sink + init = graph.initialize_deterministically(6).astype(np.float64) + sink = l2(init[[graph.get_entity_index("e")]])[0] + np.testing.assert_allclose(embeddings, np.tile(sink, (5, 1)), atol=1e-5) + + # one step: only "d" has seen the sink, the others have their successor's vector + graph, embeddings = pycleora.embed_directed(chain, COLUMNS, feature_dim=6, num_iterations=1) + row = {name: i for i, name in enumerate(graph.entity_ids)} + for name, successor in (("a", "b"), ("b", "c"), ("c", "d"), ("d", "e"), ("e", "e")): + np.testing.assert_allclose(embeddings[row[name]], l2(init[[row[successor]]])[0], atol=1e-5) + + +def test_node_features_take_a_seed_and_whitening(graph): + """The only embed_* variant that had neither argument.""" + import inspect + + rng = np.random.default_rng(3) + features = {name: rng.standard_normal(6).astype(np.float32) for name in graph.entity_ids[:50]} + + def expected(seed, whiten): + init = graph.initialize_deterministically(6, seed) + for name, vector in features.items(): + row = graph.get_entity_index(name) + init[row] = 0.5 * init[row] + 0.5 * vector + return embed(graph, 6, 3, initial_embeddings=init, whiten=whiten) + + default = pycleora.embed_with_node_features(graph, features, 3) + np.testing.assert_array_equal(default, expected(0, False)) + seeded = pycleora.embed_with_node_features(graph, features, 3, seed=7) + np.testing.assert_array_equal(seeded, expected(7, False)) + assert not np.array_equal(seeded, default) + whitened = pycleora.embed_with_node_features(graph, features, 3, whiten=True) + np.testing.assert_array_equal(whitened, expected(0, True)) + assert not np.array_equal(whitened, default) + + # added at the end: positional calls written for the old signature mean the same + assert list(inspect.signature(pycleora.embed_with_node_features).parameters) == [ + "graph", "node_features", "num_iterations", "propagation", "normalization", + "feature_weight", "num_workers", "seed", "whiten", + ] + + +def test_multiscale_attention_and_estimator(graph): + multi = pycleora.embed_multiscale(graph, 8, [1, 3], whiten=False) + np.testing.assert_array_equal(multi[:, :8], embed(graph, 8, 1, whiten=False)) + np.testing.assert_array_equal(multi[:, 8:], embed(graph, 8, 3, whiten=False)) + + attention = pycleora.embed_with_attention(graph, 8, 3) + assert attention.shape == (graph.num_entities, 8) and np.isfinite(attention).all() + np.testing.assert_array_equal(attention, pycleora.embed_with_attention(graph, 8, 3)) + + estimator = pycleora.CleoraEmbedder(feature_dim=4, num_iterations=3, columns=COLUMNS) + lines = [f"n{i % 20} n{(i * 3 + 1) % 20} n{(i * 7 + 2) % 20}" for i in range(60)] + fitted = estimator.fit_transform(lines) + np.testing.assert_array_equal(fitted, embed(SparseMatrix.from_iterator(iter(lines), COLUMNS), 4, 3)) + + +def test_heterogeneous_graph_relations_carry_weights(): + from pycleora.hetero import HeteroGraph + + def build(weights): + hetero = HeteroGraph() + hetero.add_node_type("user") + hetero.add_node_type("item") + hetero.add_edge_type( + "buys", "user", "item", [("u1", "i1"), ("u2", "i1"), ("u2", "i2"), ("u3", "i2")], weights=weights + ) + hetero.add_edge_type("follows", "user", "user", [("u1", "u2"), ("u2", "u3")]) + return hetero + + for combine, width in (("concat", 16), ("mean", 8)): + graphs, embeddings, combined = build(None).embed_per_relation( + feature_dim=8, num_iterations=3, combine=combine, whiten=False + ) + assert set(graphs) == set(embeddings) == {"buys", "follows"} + assert combined.shape == (5, width) and np.isfinite(combined).all() + + plain = build(None).embed_per_relation(8, 3, whiten=False)[1]["buys"] + weighted = build([5.0, 1.0, 1.0, 5.0]).embed_per_relation(8, 3, whiten=False)[1]["buys"] + assert np.abs(plain - weighted).max() > 1e-3 + + +def test_popularity_prior_multiplies_the_cosine_by_the_degrees(graph): + unit = pycleora.embed(graph, 16, 3) + scaled = pycleora.scale_by_popularity(graph, unit, 0.5) + degrees = np.asarray(graph.entity_degrees, dtype=np.float64) + assert degrees.min() > 0 and degrees.max() > degrees.min() + expected = (unit.astype(np.float64) @ unit.T.astype(np.float64)) * np.sqrt(np.outer(degrees, degrees)) + np.testing.assert_allclose(scaled.astype(np.float64) @ scaled.T.astype(np.float64), expected, rtol=1e-4, atol=1e-5) + # the default is a mild prior: longer vectors for better connected entities, same directions + default = pycleora.scale_by_popularity(graph, unit) + norms = np.linalg.norm(default, axis=1) + np.testing.assert_allclose(norms, degrees ** pycleora.DEFAULT_POPULARITY_EXPONENT, rtol=1e-4) + np.testing.assert_allclose(default / norms[:, None], unit, atol=1e-6) + np.testing.assert_allclose(np.linalg.norm(unit, axis=1), 1.0, rtol=1e-5) # the input is left alone + np.testing.assert_array_equal(pycleora.scale_by_popularity(graph, unit, 0.0), unit) + with pytest.raises(ValueError, match="one row per entity"): + pycleora.scale_by_popularity(graph, unit[:-1]) diff --git a/tests/python/test_errors_and_input.py b/tests/python/test_errors_and_input.py new file mode 100644 index 0000000..0b512a8 --- /dev/null +++ b/tests/python/test_errors_and_input.py @@ -0,0 +1,116 @@ +"""Bad input is reported, never silently turned into an empty or partial graph.""" + +import warnings + +import numpy as np +import pytest + +from pycleora import SparseMatrix +from pycleora.io_utils import from_arrays + +from conftest import dense + +COLUMNS = "complex::reflexive::node" + + +def test_missing_file_raises(): + with pytest.raises(FileNotFoundError, match="definitely_not_here"): + SparseMatrix.from_files(["/tmp/definitely_not_here.tsv"], COLUMNS) + + +def test_no_files_and_compressed_files_are_rejected(tmp_path): + with pytest.raises(ValueError, match="At least one file"): + SparseMatrix.from_files([], COLUMNS) + archive = tmp_path / "edges.tsv.gz" + archive.write_bytes(b"\x1f\x8b not really gzip") + with pytest.raises(ValueError, match="Unsupported file format"): + SparseMatrix.from_files([str(archive)], COLUMNS) + + +def test_malformed_lines_warn_with_the_first_offender(tmp_path): + path = tmp_path / "edges.tsv" + path.write_text("u1\tp1\nu2\tp2\nu3 p3\nu4\tp4\textra\n") + with pytest.warns(RuntimeWarning, match=r"2 of 4 input line\(s\) were skipped.*line 3.*u3 p3"): + graph = SparseMatrix.from_files([str(path)], "user product") + assert set(graph.entity_ids) == {"u1", "p1", "u2", "p2"} + + +def test_nothing_usable_is_an_error(): + # two columns need a tab (or comma) between them; a space does not separate fields + with pytest.raises(ValueError, match=r"None of the 2 input line\(s\) could be used.*expected 2 field"): + SparseMatrix.from_iterator(iter(["u1 p1", "u2 p2"]), "user product") + + +def test_comma_separated_fields_work(): + by_comma = SparseMatrix.from_iterator(iter(["u1,p1 p2", "u2, p2"]), "user complex::product") + by_tab = SparseMatrix.from_iterator(iter(["u1\tp1 p2", "u2\tp2"]), "user complex::product") + assert by_comma.entity_ids == by_tab.entity_ids + np.testing.assert_array_equal(dense(by_comma), dense(by_tab)) + + +def test_blank_lines_and_stray_spaces_are_harmless(): + with warnings.catch_warnings(): + warnings.simplefilter("error") + messy = SparseMatrix.from_iterator(iter(["a b ", "", " ", " b c\n", "c d\r\n"]), COLUMNS) + clean = SparseMatrix.from_iterator(iter(["a b", "b c", "c d"]), COLUMNS) + assert messy.entity_ids == clean.entity_ids == ("a", "b", "c", "d") + np.testing.assert_array_equal(dense(messy), dense(clean)) + + +def test_empty_input_gives_an_empty_graph(): + graph = SparseMatrix.from_iterator(iter([]), COLUMNS) + assert graph.num_entities == 0 and graph.num_edges == 0 + assert graph.embed_fast(8, 2).shape == (0, 8) + + +def test_non_string_lines_are_rejected(): + with pytest.raises(ValueError, match="must be strings"): + SparseMatrix.from_iterator(iter(["a b", 5]), COLUMNS) + + +def test_exception_inside_the_iterator_propagates(): + def lines(): + yield "a b" + raise KeyError("boom") + + with pytest.raises(KeyError, match="boom"): + SparseMatrix.from_iterator(lines(), COLUMNS) + + +@pytest.mark.parametrize("columns,message", [ + ("node", "at least one relation"), + ("", "empty"), + ("reflexive::node", "REFLEXIVE"), + ("a bogus::b", "Unrecognized"), + ("a b weight::x weight::y", "At most one"), +]) +def test_bad_column_definitions(columns, message): + with pytest.raises(ValueError, match=message): + SparseMatrix.from_iterator(iter(["a b"]), columns) + + +def test_bad_trim_value(): + with pytest.raises(ValueError, match="hyperedge_trim_n"): + SparseMatrix.from_iterator(iter(["a b"]), COLUMNS, 0) + + +def test_invalid_utf8_lines_are_reported(tmp_path): + path = tmp_path / "edges.txt" + path.write_bytes(b"a b\n\xff\xfe broken\nb c\n") + with pytest.warns(RuntimeWarning, match="not valid UTF-8"): + graph = SparseMatrix.from_files([str(path)], COLUMNS) + assert graph.entity_ids == ("a", "b", "c") + + +def test_direct_construction_is_refused(): + with pytest.raises(ValueError, match="cannot be constructed directly"): + SparseMatrix("anything") + + +def test_edge_arrays_of_different_length(): + with pytest.raises(ValueError, match="src has 2 element"): + from_arrays([1, 2], [1]) + with pytest.raises(ValueError, match="1-dimensional"): + from_arrays(np.zeros((2, 2), dtype=np.int64), np.zeros((2, 2), dtype=np.int64)) + with pytest.raises(TypeError, match="int64 numpy arrays"): + SparseMatrix.from_edges(np.array([1.5, 2.5]), np.array([1.5, 2.5])) diff --git a/tests/python/test_fork.py b/tests/python/test_fork.py new file mode 100644 index 0000000..72804a9 --- /dev/null +++ b/tests/python/test_fork.py @@ -0,0 +1,41 @@ +"""pycleora in a forked child process, after the parent has used it.""" + +import multiprocessing +import sys + +import numpy as np +import pytest + +from pycleora import SparseMatrix, embed + +LINES = [f"n{i % 80} n{(i * 7 + 1) % 80} n{(i * 13 + 2) % 80}" for i in range(400)] + + +def _work(connection): + graph = SparseMatrix.from_iterator(iter(LINES), "complex::reflexive::node", num_workers=3) + vectors = embed(graph, 16, 4, num_workers=3) + connection.send(graph.left_markov_propagate(vectors, num_workers=2)) + connection.close() + + +@pytest.mark.skipif(sys.platform == "win32", reason="no fork on Windows") +@pytest.mark.filterwarnings("ignore:.*fork.*:DeprecationWarning") # Python warns about forking with threads +def test_a_forked_child_can_use_the_library(): + """The worker threads of the parent do not exist in a forked child; it used to wait + for them forever.""" + graph = SparseMatrix.from_iterator(iter(LINES), "complex::reflexive::node", num_workers=3) + expected = graph.left_markov_propagate(embed(graph, 16, 4, num_workers=3), num_workers=2) + + context = multiprocessing.get_context("fork") + receiver, sender = context.Pipe(duplex=False) + child = context.Process(target=_work, args=(sender,)) + child.start() + sender.close() + try: + assert receiver.poll(60), "the forked child did not answer" + np.testing.assert_array_equal(receiver.recv(), expected) + finally: + child.join(5) + if child.is_alive(): + child.kill() + assert child.exitcode == 0 diff --git a/tests/python/test_graph_construction.py b/tests/python/test_graph_construction.py new file mode 100644 index 0000000..5981d5e --- /dev/null +++ b/tests/python/test_graph_construction.py @@ -0,0 +1,122 @@ +"""The sparse matrix built by the Rust core against a brute-force reference.""" + +import numpy as np +import pytest + +from pycleora import SparseMatrix + +from conftest import dense, lines_from_rows, random_rows, reference_graph + +CASES = [ + # (columns definition, complex flag per entity column, relations, shared vocabulary) + ("complex::reflexive::item", [True], [(0, 0)], True), + ("user product", [False, False], [(0, 1)], False), + ("user complex::product", [False, True], [(0, 1)], False), + ("complex::a complex::b", [True, True], [(0, 1)], False), + ("src dst", [False, False], [(0, 1)], True), # the same names in both columns + ("user complex::reflexive::product", [False, True], [(0, 1), (1, 1)], False), + ("user complex::product brand", [False, True, False], [(0, 1), (0, 2), (1, 2)], False), + ("complex::reflexive::a complex::reflexive::b", [True, True], [(0, 0), (0, 1), (1, 1)], True), +] + + +@pytest.mark.parametrize("columns,complexity,relations,shared", CASES) +@pytest.mark.parametrize("num_workers", [1, 3]) +def test_matches_reference(rng, columns, complexity, relations, shared, num_workers): + rows = random_rows(rng, 300, complexity, vocabulary=35, max_len=5, prefix_per_column=not shared) + graph = SparseMatrix.from_iterator(iter(lines_from_rows(rows)), columns, 16, num_workers) + ids, raw, row_sums = reference_graph(rows, relations) + + assert list(graph.entity_ids) == ids + np.testing.assert_allclose(dense(graph, "raw"), raw, rtol=1e-6, atol=1e-9) + np.testing.assert_allclose(graph.entity_degrees, row_sums, rtol=1e-6) + np.testing.assert_allclose(dense(graph, "left"), raw / row_sums[:, None], rtol=1e-5, atol=1e-9) + np.testing.assert_allclose( + dense(graph, "symmetric"), raw / np.sqrt(np.outer(row_sums, row_sums)), rtol=1e-5, atol=1e-9 + ) + + +@pytest.mark.parametrize("columns,complexity,relations,shared", [CASES[0], CASES[3], CASES[5]]) +@pytest.mark.parametrize("trim", [1, 3, 8]) +@pytest.mark.parametrize("num_workers", [1, 4]) +def test_oversized_hyperedges_match_reference(rng, columns, complexity, relations, shared, trim, num_workers): + # hyperedges much longer than the trim threshold, with repeated entities + rows = random_rows(rng, 120, complexity, vocabulary=60, max_len=25, prefix_per_column=not shared) + weights = rng.uniform(0.2, 3.0, size=len(rows)) + graph = SparseMatrix.from_iterator( + iter(lines_from_rows(rows)), columns, trim, num_workers, weights=weights + ) + ids, raw, row_sums = reference_graph(rows, relations, trim=trim, weights=weights.astype(np.float32)) + + assert list(graph.entity_ids) == ids + np.testing.assert_allclose(dense(graph, "raw"), raw, rtol=1e-5, atol=1e-9) + np.testing.assert_allclose(graph.entity_degrees, row_sums, rtol=1e-5) + + +def test_matrix_is_symmetric_with_sorted_rows(rng): + rows = random_rows(rng, 400, [True], vocabulary=80, max_len=30) + graph = SparseMatrix.from_iterator(iter(lines_from_rows(rows)), "complex::reflexive::x", 4) + matrix = dense(graph, "raw") + np.testing.assert_array_equal(matrix, matrix.T) + indptr, indices, _ = graph.to_csr("raw") + for row in range(graph.num_entities): + columns = indices[indptr[row]:indptr[row + 1]] + assert np.all(np.diff(columns) > 0) + + +def test_untrimmed_rows_are_stochastic(rng): + rows = random_rows(rng, 300, [True], vocabulary=50, max_len=10) + graph = SparseMatrix.from_iterator(iter(lines_from_rows(rows)), "complex::reflexive::x", 16) + np.testing.assert_allclose(dense(graph, "left").sum(axis=1), 1.0, rtol=1e-5) + + +def test_coordinate_export_agrees_with_csr(small_graph): + graph, _ = small_graph + for kind in ("left", "symmetric", "raw"): + rows, cols, values, n, m = graph.to_sparse_csr(kind) + assert n == m == graph.num_entities + assert len(values) == graph.num_edges + rebuilt = np.zeros((n, n)) + rebuilt[rows, cols] = values + np.testing.assert_array_equal(rebuilt, dense(graph, kind).astype(np.float32)) + np.testing.assert_array_equal(graph.to_sparse_csr()[2], graph.to_sparse_csr("left")[2]) + with pytest.raises(ValueError, match="markov_type"): + graph.to_sparse_csr("bogus") + + +def test_column_masks(): + graph = SparseMatrix.from_iterator(iter(["u1\tp1 p2", "u2\tp2"]), "user complex::product") + ids = np.array(graph.entity_ids) + assert set(ids[graph.get_entity_column_mask("user")]) == {"u1", "u2"} + assert set(ids[graph.get_entity_column_mask("product")]) == {"p1", "p2"} + assert graph.column_names == ["user", "product"] + with pytest.raises(ValueError, match="not found"): + graph.get_entity_column_mask("brand") + + # a single reflexive column used to give an all-False mask + reflexive = SparseMatrix.from_iterator(iter(["a b", "b c"]), "complex::reflexive::item") + assert reflexive.get_entity_column_mask("item").all() + + +def test_repr_and_sizes(): + graph = SparseMatrix.from_iterator(iter(["a b c", "c d"]), "complex::reflexive::item") + assert repr(graph) == "SparseMatrix(entities=4, edges=12, columns=('item', 'item'))" + assert len(graph) == graph.num_entities == 4 + assert graph.num_edges == 12 + bipartite = SparseMatrix.from_iterator(iter(["u\tp"]), "user product") + assert repr(bipartite) == "SparseMatrix(entities=2, edges=2, columns=('user', 'product'))" + three = SparseMatrix.from_iterator(iter(["u\tp\tb"]), "user product brand") + assert repr(three) == "SparseMatrix(entities=3, edges=6, columns=('user', 'product', 'brand'))" + + +def test_neighbors(small_graph): + graph, _ = small_graph + entity = graph.entity_ids[3] + neighbors = dict(graph.get_neighbors(entity)) + row = dense(graph, "left")[3] + expected = {graph.entity_ids[j]: row[j] for j in np.flatnonzero(row)} + assert neighbors.keys() == expected.keys() + for name, value in expected.items(): + assert neighbors[name] == pytest.approx(value, rel=1e-6) + with pytest.raises(ValueError, match="not found"): + graph.get_neighbors("no such entity") diff --git a/tests/python/test_init_and_propagation.py b/tests/python/test_init_and_propagation.py new file mode 100644 index 0000000..80af9a2 --- /dev/null +++ b/tests/python/test_init_and_propagation.py @@ -0,0 +1,212 @@ +"""Initial vectors and the propagation kernel.""" + +import numpy as np +import pytest + +from pycleora import SparseMatrix +from pycleora.pycleora import entity_hash, l2_normalize_inplace + +from conftest import dense + +MASK = (1 << 64) - 1 + + +def splitmix64(z: int) -> int: + z = (z + 0x9E3779B97F4A7C15) & MASK + z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & MASK + z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & MASK + return z ^ (z >> 31) + + +def reference_init(entity_id: str, dim: int, seed: int) -> np.ndarray: + seed_key = splitmix64(seed & MASK) + values = [] + for column in range(dim): + column_key = splitmix64(column ^ seed_key) + bits = splitmix64(entity_hash(entity_id) ^ column_key) >> 40 + values.append(bits / 8388608.0 - 1.0) + return np.array(values, dtype=np.float32) + + +def test_initial_vectors_follow_the_documented_formula(small_graph): + graph, _ = small_graph + for seed in (0, 1, -3, 2**40): + init = graph.initialize_deterministically(12, seed) + assert init.dtype == np.float32 and init.shape == (graph.num_entities, 12) + for row in (0, 17, graph.num_entities - 1): + np.testing.assert_array_equal(init[row], reference_init(graph.entity_ids[row], 12, seed)) + + +def test_initial_vector_depends_on_the_name_only(small_graph): + graph, _ = small_graph + other = SparseMatrix.from_iterator(iter([f"{graph.entity_ids[9]} somebody_else"]), "complex::reflexive::x") + np.testing.assert_array_equal( + other.initialize_deterministically(20, 4)[0], graph.initialize_deterministically(20, 4)[9] + ) + + +@pytest.mark.parametrize("dim", [64, 256, 1024]) +def test_initial_vectors_are_statistically_independent(dim): + # 3.2 gave pairwise cosines with a standard deviation of 0.45 and an effective + # rank of ~5 for every dimension + n = 3000 + graph = SparseMatrix.from_iterator(iter(f"e{i} e{(i * 37) % n}" for i in range(n)), "complex::reflexive::x") + init = graph.initialize_deterministically(dim).astype(np.float64) + assert -1.0 <= init.min() and init.max() < 1.0 + assert abs(init.mean()) < 5e-3 and abs(init.var() - 1 / 3) < 5e-3 + + unit = init / np.linalg.norm(init, axis=1, keepdims=True) + rng = np.random.default_rng(0) + a, b = rng.integers(0, n, 50000), rng.integers(0, n, 50000) + keep = a != b + cosines = np.einsum("ij,ij->i", unit[a[keep]], unit[b[keep]]) + assert cosines.std() == pytest.approx(1 / np.sqrt(dim), rel=0.05) + assert np.abs(cosines).max() < 8 / np.sqrt(dim) + + spectrum = np.linalg.svd(init, compute_uv=False) ** 2 + participation = spectrum.sum() ** 2 / (spectrum ** 2).sum() + assert participation > 0.7 * min(dim, n) + + +def test_seeds_give_unrelated_vectors(small_graph): + graph, _ = small_graph + a = graph.initialize_deterministically(128, 0).astype(np.float64) + b = graph.initialize_deterministically(128, 1).astype(np.float64) + for shift in range(4): + left, right = a[:, shift:], b[:, : 128 - shift] + assert not np.array_equal(left, right) + correlation = (left * right).mean() * 3 + assert abs(correlation) < 0.05 + + +@pytest.mark.parametrize("propagation", ["left", "symmetric"]) +def test_propagation_matches_dense_multiplication(small_graph, propagation, rng): + graph, _ = small_graph + x = rng.standard_normal((graph.num_entities, 7)).astype(np.float32) + propagate = graph.left_markov_propagate if propagation == "left" else graph.symmetric_markov_propagate + expected = dense(graph, propagation) @ x.astype(np.float64) + result = propagate(x) + assert result.dtype == np.float32 and result.flags.c_contiguous and result.flags.writeable + np.testing.assert_allclose(result, expected, rtol=1e-4, atol=1e-5) + for workers in (1, 2, 7): + np.testing.assert_array_equal(propagate(x, num_workers=workers), result) + + +def test_propagation_into_a_given_buffer(small_graph, rng): + graph, _ = small_graph + x = rng.standard_normal((graph.num_entities, 5)).astype(np.float32) + expected = graph.left_markov_propagate(x) + out = np.full_like(x, 123.0) + returned = graph.left_markov_propagate(x, out=out) + assert returned is out + np.testing.assert_array_equal(out, expected) + + with pytest.raises(ValueError, match="share memory"): + graph.left_markov_propagate(x, out=x) + with pytest.raises(ValueError, match="shape"): + graph.left_markov_propagate(x, out=np.zeros((3, 5), dtype=np.float32)) + with pytest.raises(ValueError, match="C-contiguous"): + graph.left_markov_propagate(x, out=np.asfortranarray(np.zeros_like(x))) + read_only = np.zeros_like(x) + read_only.flags.writeable = False + with pytest.raises(ValueError, match="writeable"): + graph.left_markov_propagate(x, out=read_only) + + +def test_propagating_selected_rows(small_graph, rng): + graph, _ = small_graph + n = graph.num_entities + x = rng.standard_normal((n, 6)).astype(np.float32) + rows = np.array([5, 0, 5, n - 1, 17]) + many = rng.integers(0, n, size=1000) + for propagate in (graph.left_markov_propagate, graph.symmetric_markov_propagate): + full = propagate(x) + np.testing.assert_array_equal(propagate(x, rows=rows), full[rows]) + np.testing.assert_array_equal(propagate(x, rows=[5, 0]), full[[5, 0]]) + np.testing.assert_array_equal(propagate(x, rows=rows.astype(np.int32)), full[rows]) + np.testing.assert_array_equal(propagate(x, rows=many, num_workers=3), full[many]) + assert propagate(x, rows=[]).shape == (0, 6) + out = np.empty((len(rows), 6), dtype=np.float32) + assert propagate(x, rows=rows, out=out) is out + np.testing.assert_array_equal(out, full[rows]) + + for bad in ([n], [-1], [0, 10**12]): + with pytest.raises(ValueError, match="out of range"): + graph.left_markov_propagate(x, rows=bad) + for bad in ("abc", 5, [1.5]): + with pytest.raises(TypeError, match="rows"): + graph.left_markov_propagate(x, rows=bad) + with pytest.raises(ValueError, match="shape"): + graph.left_markov_propagate(x, rows=[1, 2], out=np.zeros((3, 6), dtype=np.float32)) + + +def test_propagation_accepts_any_memory_layout(small_graph, rng): + # Fortran-ordered and strided arrays used to crash with a Rust panic + graph, _ = small_graph + wide = rng.standard_normal((graph.num_entities, 12)).astype(np.float32) + for view in (np.asfortranarray(wide), wide[:, ::2], wide[:, ::-1], wide[::-1][::-1]): + expected = graph.left_markov_propagate(np.ascontiguousarray(view)) + np.testing.assert_array_equal(graph.left_markov_propagate(view), expected) + np.testing.assert_array_equal( + graph.symmetric_markov_propagate(view), graph.symmetric_markov_propagate(np.ascontiguousarray(view)) + ) + + +def test_propagation_rejects_wrong_input_clearly(small_graph): + graph, _ = small_graph + n = graph.num_entities + with pytest.raises(TypeError, match="float32.*dtype float64"): + graph.left_markov_propagate(np.zeros((n, 4))) + with pytest.raises(TypeError, match="1-dimensional"): + graph.left_markov_propagate(np.zeros(n, dtype=np.float32)) + with pytest.raises(TypeError, match="not a numpy array"): + graph.left_markov_propagate([[0.0] * 4] * n) + with pytest.raises(ValueError, match="rows but graph has"): + graph.left_markov_propagate(np.zeros((n + 1, 4), dtype=np.float32)) + + +def test_zero_width_and_isolated_cases(): + graph = SparseMatrix.from_iterator(iter(["a b", "c"]), "complex::reflexive::x") + assert graph.left_markov_propagate(np.zeros((3, 0), dtype=np.float32)).shape == (3, 0) + x = np.eye(3, dtype=np.float32) + # "c" only co-occurs with itself: its row is a self-loop + np.testing.assert_allclose(graph.left_markov_propagate(x)[2], [0.0, 0.0, 1.0]) + + +def test_l2_normalisation(small_graph, rng): + graph, _ = small_graph + x = rng.standard_normal((graph.num_entities, 9)).astype(np.float32) + x[4] = 0.0 + normalised = graph.l2_normalize(x) + norms = np.linalg.norm(normalised, axis=1) + np.testing.assert_allclose(np.delete(norms, 4), 1.0, rtol=1e-5) + assert not normalised[4].any() + assert not np.shares_memory(normalised, x) + in_place = x.copy() + l2_normalize_inplace(in_place) + np.testing.assert_array_equal(in_place, normalised) + + +def test_entity_lookup(small_graph): + graph, _ = small_graph + ids = graph.entity_ids + assert isinstance(ids, tuple) and graph.entity_ids is ids # built once + for index in (0, 11, len(ids) - 1): + assert graph.get_entity_index(ids[index]) == index + assert graph.get_entity_indices([ids[3], ids[0], ids[3]]) == [3, 0, 3] + with pytest.raises(ValueError, match="not found"): + graph.get_entity_index("missing") + with pytest.raises(ValueError, match="not found"): + graph.get_entity_indices([ids[0], "missing"]) + + +def test_entity_ids_can_be_replaced(): + graph = SparseMatrix.from_iterator(iter(["a b", "b c"]), "complex::reflexive::x") + assert graph.get_entity_index("b") == 1 + graph.entity_ids = ["x", "y", "z"] + assert graph.entity_ids == ("x", "y", "z") + assert graph.get_entity_index("y") == 1 + with pytest.raises(ValueError): + graph.get_entity_index("b") + with pytest.raises(ValueError, match="3 elements"): + graph.entity_ids = ["only", "two"] diff --git a/tests/python/test_metrics.py b/tests/python/test_metrics.py new file mode 100644 index 0000000..269ce7d --- /dev/null +++ b/tests/python/test_metrics.py @@ -0,0 +1,246 @@ +"""pycleora.metrics against scikit-learn and against brute force.""" + +import numpy as np +import pytest + +from pycleora import SparseMatrix, embed, metrics + +sklearn_metrics = pytest.importorskip("sklearn.metrics") + + +@pytest.fixture +def rng(): + return np.random.default_rng(0) + + +def test_roc_auc_and_average_precision_match_sklearn_with_ties(rng): + for round_to in (None, 1): # continuous scores, and heavily tied ones + labels = rng.random(500) < 0.3 + scores = rng.normal(size=500) + labels + if round_to is not None: + scores = scores.round(round_to) + assert metrics.roc_auc(labels, scores) == pytest.approx(sklearn_metrics.roc_auc_score(labels, scores), abs=1e-12) + assert metrics.average_precision(labels, scores) == pytest.approx( + sklearn_metrics.average_precision_score(labels, scores), abs=1e-12) + assert np.isnan(metrics.roc_auc(np.ones(5, bool), np.arange(5.0))) + assert np.isnan(metrics.average_precision(np.zeros(5, bool), np.arange(5.0))) + # a constant scorer is exactly at chance + assert metrics.roc_auc(labels, np.zeros(500)) == 0.5 + + +def test_classification_metrics_match_sklearn(rng): + num_classes, count = 7, 900 + y = rng.integers(0, num_classes - 1, count) # the last class never occurs + scores = rng.normal(size=(count, num_classes)) + scores[np.arange(count), y] += 1.2 + predicted = scores.argmax(axis=1) + result = metrics.classification_metrics(y, scores) + + assert result["accuracy"] == pytest.approx(sklearn_metrics.accuracy_score(y, predicted)) + assert result["balanced_accuracy"] == pytest.approx(sklearn_metrics.balanced_accuracy_score(y, predicted)) + assert result["macro_f1"] == pytest.approx(sklearn_metrics.f1_score(y, predicted, average="macro")) + assert result["weighted_f1"] == pytest.approx(sklearn_metrics.f1_score(y, predicted, average="weighted")) + assert result["mcc"] == pytest.approx(sklearn_metrics.matthews_corrcoef(y, predicted)) + assert result["cohen_kappa"] == pytest.approx(sklearn_metrics.cohen_kappa_score(y, predicted)) + labels = np.arange(num_classes) + for k in (3, 5): + assert result[f"top{k}_accuracy"] == pytest.approx( + sklearn_metrics.top_k_accuracy_score(y, scores, k=k, labels=labels)) + present = np.unique(y) + assert result["macro_roc_auc"] == pytest.approx( + np.mean([sklearn_metrics.roc_auc_score(y == c, scores[:, c]) for c in present])) + assert result["macro_average_precision"] == pytest.approx( + np.mean([sklearn_metrics.average_precision_score(y == c, scores[:, c]) for c in present])) + + +def test_multilabel_metrics_match_sklearn(rng): + count, num_labels = 600, 9 + y = rng.random((count, num_labels)) < 0.25 + y[:, -1] = False # a label without positives + y[:5] = False # samples without labels + y[5:8, :-1] = True # samples with (almost) every label + scores = rng.normal(size=(count, num_labels)) + 1.5 * y - 0.7 + scores = scores.round(1) # ties + predicted = scores > 0 + result = metrics.multilabel_metrics(y, scores) + + f1 = lambda average, prediction=predicted: sklearn_metrics.f1_score(y, prediction, average=average, zero_division=0) + assert result["micro_f1"] == pytest.approx(f1("micro")) + assert result["macro_f1"] == pytest.approx(f1("macro")) + assert result["samples_f1"] == pytest.approx(f1("samples")) + assert result["subset_accuracy"] == pytest.approx(sklearn_metrics.accuracy_score(y, predicted)) + assert result["hamming_loss"] == pytest.approx(sklearn_metrics.hamming_loss(y, predicted)) + with_positives = y.sum(axis=0) > 0 + assert result["micro_roc_auc"] == pytest.approx(sklearn_metrics.roc_auc_score(y.ravel(), scores.ravel())) + assert result["macro_roc_auc"] == pytest.approx( + sklearn_metrics.roc_auc_score(y[:, with_positives], scores[:, with_positives], average="macro")) + assert result["micro_average_precision"] == pytest.approx( + sklearn_metrics.average_precision_score(y.ravel(), scores.ravel())) + assert result["macro_average_precision"] == pytest.approx( + sklearn_metrics.average_precision_score(y[:, with_positives], scores[:, with_positives], average="macro")) + assert result["label_ranking_average_precision"] == pytest.approx( + sklearn_metrics.label_ranking_average_precision_score(y, scores)) + + # the "known number of labels" protocol: top-k labels with k = true label count + order = np.argsort(-scores, axis=1, kind="stable") + known = np.zeros_like(y) + for row, k in enumerate(y.sum(axis=1)): + known[row, order[row, :k]] = True + assert result["micro_f1_known_count"] == pytest.approx(f1("micro", known)) + assert result["macro_f1_known_count"] == pytest.approx(f1("macro", known)) + assert result["precision_at_1"] == pytest.approx(y[np.arange(count), order[:, 0]].mean()) + + +def test_ranks_count_ties_as_half_a_place(): + targets = np.array([0.5, 0.5, 0.9]) + candidates = np.array([[0.1, 0.5, 0.7, np.nan], [0.5, 0.5, 0.5, 0.5], [0.1, 0.2, 0.3, 0.4]]) + np.testing.assert_allclose(metrics.ranks_among(targets, candidates), [2.5, 3.0, 1.0]) + summary = metrics.ranking_metrics(np.array([1.0, 2.0, 4.0, 200.0]), ks=(1, 3, 100)) + assert summary["mrr"] == pytest.approx((1 + 0.5 + 0.25 + 0.005) / 4) + assert (summary["hits@1"], summary["hits@3"], summary["hits@100"]) == (0.25, 0.5, 0.75) + assert summary["median_rank"] == 3.0 + + +def test_retrieval_metrics_match_brute_force(rng): + queries, width = 40, 20 + hits = rng.random((queries, width)) < 0.2 + num_relevant = hits.sum(axis=1) + rng.integers(0, 5, queries) + num_relevant[0] = 0 # a query without relevant items scores zero everywhere + hits[0] = False + result = metrics.retrieval_metrics(hits, num_relevant, ks=(5, 20)) + for k in (5, 20): + recall, precision, hit_rate, ndcg, mean_ap = [], [], [], [], [] + for q in range(queries): + top = hits[q, :k] + recall.append(top.sum() / max(num_relevant[q], 1)) + precision.append(top.sum() / k) + hit_rate.append(float(top.any())) + dcg = sum(1 / np.log2(r + 2) for r in range(k) if top[r]) + ideal = sum(1 / np.log2(r + 2) for r in range(min(num_relevant[q], k))) + ndcg.append(dcg / ideal if ideal else 0.0) + found = 0 + total = 0.0 + for r in range(k): + if top[r]: + found += 1 + total += found / (r + 1) + mean_ap.append(total / max(min(num_relevant[q], k), 1)) + assert result[f"recall@{k}"] == pytest.approx(np.mean(recall)) + assert result[f"precision@{k}"] == pytest.approx(np.mean(precision)) + assert result[f"hit_rate@{k}"] == pytest.approx(np.mean(hit_rate)) + assert result[f"ndcg@{k}"] == pytest.approx(np.mean(ndcg)) + assert result[f"map@{k}"] == pytest.approx(np.mean(mean_ap)) + + +def test_clustering_comparisons_match_sklearn(rng): + a = rng.integers(0, 6, 400) + b = np.where(rng.random(400) < 0.7, a, rng.integers(0, 4, 400)) + assert metrics.normalized_mutual_info(a, b) == pytest.approx(sklearn_metrics.normalized_mutual_info_score(a, b)) + assert metrics.adjusted_rand_index(a, b) == pytest.approx(sklearn_metrics.adjusted_rand_score(a, b)) + table = sklearn_metrics.cluster.contingency_matrix(a, b) + assert metrics.purity(a, b) == pytest.approx(table.max(axis=0).sum() / 400) + + +def test_silhouette_matches_sklearn(rng): + labels = rng.integers(0, 4, 300) + labels[0] = 9 # a class with a single member + vectors = rng.normal(size=(300, 16)) + 2.0 * np.eye(16)[labels % 16] + assert metrics.silhouette_score(vectors, labels) == pytest.approx( + sklearn_metrics.silhouette_score(vectors, labels, metric="cosine"), abs=1e-9) + + +def test_clustering_scores_cluster_without_looking_at_the_labels(rng): + labels = np.repeat(np.arange(4), 60) + separated = rng.normal(scale=0.2, size=(240, 12)) + 3.0 * np.eye(12)[labels] + found = metrics.clustering_scores(separated, labels) + assert found["nmi"] > 0.95 and found["purity"] > 0.95 and found["ari"] > 0.95 + assert found["num_clusters"] == 4 + # Vectors that carry no information about the labels must not look clustered + # (centroids computed from the true labels used to give a high score here). + noise = metrics.clustering_scores(rng.normal(size=(240, 12)), labels) + assert noise["nmi"] < 0.1 and noise["ari"] < 0.1 + + +@pytest.fixture +def small_graph(): + rng = np.random.default_rng(3) + blocks = np.repeat(np.arange(3), 40) + edges = [] + for _ in range(1500): + a, b = rng.integers(0, 120, 2) + if a != b and (blocks[a] == blocks[b] or rng.random() < 0.05): + edges.append((f"n{a}", f"n{b}")) + edges = sorted(set(tuple(sorted(e)) for e in edges)) + order = rng.permutation(len(edges)) + test = [edges[i] for i in order[:60]] + train = [edges[i] for i in order[60:]] + graph = SparseMatrix.from_iterator(iter(f"{a} {b}" for a, b in train), "complex::reflexive::n") + return graph, embed(graph, 32, 4, whiten=False), train, test, blocks + + +def test_link_prediction_scores_are_consistent(small_graph): + graph, vectors, train, test, _ = small_graph + ids = list(graph.entity_ids) + rng = np.random.default_rng(1) + negatives = [(ids[a], ids[b]) for a, b in rng.integers(0, len(ids), (400, 2)) if a != b] + result = metrics.link_prediction_scores(graph, vectors, test, negative_edges=negatives) + + unit = vectors / np.linalg.norm(vectors, axis=1, keepdims=True) + row = {name: i for i, name in enumerate(ids)} + score = lambda pairs: np.array([unit[row[a]] @ unit[row[b]] for a, b in pairs if a in row and b in row], dtype=np.float64) + positive, negative = score(test), score(negatives) + labels = np.r_[np.ones(len(positive)), np.zeros(len(negative))] + both = np.r_[positive, negative] + assert result["auc"] == pytest.approx(sklearn_metrics.roc_auc_score(labels, both), abs=1e-9) + assert result["average_precision"] == pytest.approx(sklearn_metrics.average_precision_score(labels, both), abs=1e-9) + ranks = np.array([1 + (negative > p).sum() + 0.5 * (negative == p).sum() for p in positive]) + assert result["mrr"] == pytest.approx((1 / ranks).mean()) + assert result["hits@10"] == pytest.approx((ranks <= 10).mean()) + assert result["auc"] > 0.6 # clearly better than chance on a block graph + + # sampled negatives are never edges of the graph or self-pairs: on a complete graph none exist + complete = SparseMatrix.from_iterator(iter(["a b", "a c", "b c"]), "complex::reflexive::n") + with pytest.raises(ValueError): + metrics.link_prediction_scores(complete, embed(complete, 4, 1, whiten=False), [("a", "b")]) + + +def test_map_and_ndcg_match_brute_force(small_graph): + graph, vectors, train, test, _ = small_graph + ids = list(graph.entity_ids) + row = {name: i for i, name in enumerate(ids)} + unit = vectors / np.linalg.norm(vectors, axis=1, keepdims=True) + neighbours = {i: set() for i in range(len(ids))} + for a, b in train: + neighbours[row[a]].add(row[b]) + neighbours[row[b]].add(row[a]) + targets = {} + for a, b in test: + if a in row and b in row: + targets.setdefault(row[a], set()).add(row[b]) + + k = 10 + mean_ap, ndcg = [], [] + for source, wanted in targets.items(): + similarity = unit @ unit[source] + candidates = [j for j in np.argsort(-similarity, kind="stable") + if j != source and (j not in neighbours[source] or j in wanted)][:k] + found, total, dcg = 0, 0.0, 0.0 + for position, j in enumerate(candidates): + if j in wanted: + found += 1 + total += found / (position + 1) + dcg += 1 / np.log2(position + 2) + mean_ap.append(total / min(len(wanted), k)) + ndcg.append(dcg / sum(1 / np.log2(r + 2) for r in range(min(len(wanted), k)))) + assert metrics.map_at_k(graph, vectors, test, k=k) == pytest.approx(np.mean(mean_ap), abs=1e-6) + assert metrics.ndcg_at_k(graph, vectors, test, k=k) == pytest.approx(np.mean(ndcg), abs=1e-6) + + +def test_node_classification_and_cross_validation(small_graph): + graph, vectors, _, _, blocks = small_graph + labels = {name: int(blocks[int(name[1:])]) for name in graph.entity_ids} + scores = metrics.node_classification_scores(graph, vectors, labels, train_ratio=0.5, seed=1) + assert scores["accuracy"] > 0.9 and scores["macro_f1"] > 0.9 and scores["weighted_f1"] > 0.9 + assert scores["train_size"] + scores["test_size"] == len(labels) + folds = metrics.cross_validate(graph, vectors, labels, k_folds=4) + assert folds["mean_accuracy"] > 0.9 and len(folds["fold_accuracies"]) == 4 diff --git a/tests/python/test_packaging.py b/tests/python/test_packaging.py new file mode 100644 index 0000000..5521d0f --- /dev/null +++ b/tests/python/test_packaging.py @@ -0,0 +1,94 @@ +"""Package metadata stays consistent.""" + +import pathlib +import re + +import pytest + +import pycleora + +ROOT = pathlib.Path(__file__).resolve().parents[2] + + +def test_version_is_exposed(): + assert re.fullmatch(r"\d+\.\d+\.\d+([a-z0-9.+-]*)", pycleora.__version__) + assert pycleora.pycleora.__version__ == pycleora.__version__ + + +def test_installed_metadata_has_the_same_version(): + from importlib import metadata + + try: + installed = metadata.version("pycleora") + except metadata.PackageNotFoundError: + pytest.skip("pycleora is not installed as a distribution") + assert installed == pycleora.__version__ + + +def test_version_matches_cargo_toml(): + cargo = ROOT / "Cargo.toml" + if not cargo.exists(): + pytest.skip("not running from a source checkout") + version = re.search(r'^version\s*=\s*"([^"]+)"', cargo.read_text(), flags=re.MULTILINE).group(1) + assert pycleora.__version__ == version + + +def test_declared_dependencies_cover_the_imports(): + pyproject = ROOT / "pyproject.toml" + if not pyproject.exists(): + pytest.skip("not running from a source checkout") + text = pyproject.read_text() + dependencies = re.search(r"^dependencies\s*=\s*\[(.*?)\]", text, flags=re.MULTILINE | re.DOTALL).group(1) + # numpy is imported by `import pycleora`; scipy only by optional parts + assert "numpy" in dependencies + assert re.search(r'^scipy\s*=\s*\["scipy', text, flags=re.MULTILINE) + assert 'requires-python = ">=3.10"' in text + + +def test_core_api_does_not_need_scipy(): + """`pip install pycleora` installs numpy only: the core must work without scipy.""" + import subprocess + import sys + + program = """ +import sys +class Block: + def find_spec(self, name, path=None, target=None): + if name == "scipy" or name.startswith("scipy."): + raise ImportError("scipy is blocked in this test") +sys.meta_path.insert(0, Block()) +import numpy as np +import pycleora +from pycleora import SparseMatrix, embed +lines = [f"n{i % 30} n{(i * 3 + 1) % 30} n{(i * 7 + 2) % 30}" for i in range(90)] +columns = "complex::reflexive::node" +graph = SparseMatrix.from_iterator(iter(lines), columns) +emb = embed(graph, 8, 3) +classic = embed(graph, 8, 3, whiten=False) +pycleora.whiten_embeddings(classic) +pycleora.find_most_similar(graph, emb, "n0", top_k=2) +pycleora.predict_links(graph, emb, top_k=2) +pycleora.embed_weighted([(line, 2.0) for line in lines], columns, feature_dim=8, num_iterations=2) +pycleora.embed_multiscale(graph, 8, [1, 2]) +g2, e2 = pycleora.embed_inductive(graph, emb, lines, ["n3 new"], columns) +assert e2.shape == (31, 8) +pycleora.embed_streaming([lines, ["n3 new"], ["new newer"]], columns, feature_dim=8, num_iterations=2, refresh_every=2) +from pycleora.io_utils import from_arrays, from_edge_list +from_arrays([1, 2], [2, 3]); from_edge_list([("a", "b")]) +assert "scipy" not in sys.modules +print("ok") +""" + result = subprocess.run([sys.executable, "-c", program], capture_output=True, text=True) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "ok" + + +def test_public_api_is_importable(): + for name in ( + "SparseMatrix", "embed", "whiten_embeddings", "embed_weighted", "embed_directed", "embed_inductive", + "embed_streaming", "embed_multiscale", "embed_with_attention", "predict_links", "find_most_similar", + "CleoraEmbedder", "update_graph", "remove_edges", "cosine_similarity", + ): + assert hasattr(pycleora, name), name + from pycleora import algorithms, datasets, io_utils # noqa: F401 + from pycleora.io_utils import from_arrays, from_pandas, from_networkx, from_scipy_sparse # noqa: F401 diff --git a/tests/python/test_readme.py b/tests/python/test_readme.py new file mode 100644 index 0000000..cac4c65 --- /dev/null +++ b/tests/python/test_readme.py @@ -0,0 +1,16 @@ +"""The Python examples of the README run as written, top to bottom.""" + +import pathlib +import re + +README = pathlib.Path(__file__).resolve().parents[2] / "README.md" + + +def test_the_code_blocks_of_the_readme_run(capsys): + blocks = re.findall(r"```python\n(.*?)```", README.read_text(encoding="utf-8"), flags=re.S) + assert len(blocks) >= 5 + namespace = {} + exec(compile("\n".join(blocks), str(README), "exec"), namespace) + printed = capsys.readouterr().out.splitlines() + # the quick start prints the three products bought with a laptop, closest first + assert [line.split(":")[0] for line in printed[:3]] == ["mouse", "monitor", "keyboard"] diff --git a/tests/python/test_suggest_iterations.py b/tests/python/test_suggest_iterations.py new file mode 100644 index 0000000..2cb509c --- /dev/null +++ b/tests/python/test_suggest_iterations.py @@ -0,0 +1,72 @@ +"""SparseMatrix.suggest_iterations: the rule behind ``num_iterations="auto"``.""" + +import numpy as np +import pytest + +from pycleora import SparseMatrix + + +def ring(nodes, step=1): + source = np.arange(nodes) + return source, (source + step) % nodes + + +def circulant(nodes, steps): + """Every node linked to the ``steps`` next ones: ``2 * steps`` neighbours each.""" + parts = [ring(nodes, step) for step in range(1, steps + 1)] + return np.concatenate([p[0] for p in parts]), np.concatenate([p[1] for p in parts]) + + +def test_denser_graphs_get_fewer_iterations(): + sparse = SparseMatrix.from_edges(*ring(200), columns="src dst") + dense = SparseMatrix.from_edges(*circulant(200, 8), columns="src dst") + # 2 neighbours: 16 / sqrt(2) = 11.3; 16 neighbours: 16 / 4 = 4 + assert sparse.suggest_iterations() == 11 + assert dense.suggest_iterations() == 4 + + +def test_purposes(): + graph = SparseMatrix.from_edges(*circulant(200, 2), columns="src dst") # 4 neighbours + assert graph.suggest_iterations(purpose="similarity") == 6 # 12 / 2 + assert graph.suggest_iterations(purpose="general") == 8 # 16 / 2 + assert graph.suggest_iterations(purpose="classification") == 12 # 24 / 2 + assert graph.suggest_iterations() == graph.suggest_iterations("left", "general") + with pytest.raises(ValueError, match="purpose"): + graph.suggest_iterations(purpose="fun") + + +def test_a_reflexive_column_is_a_lazy_walk(): + pair = SparseMatrix.from_edges(*ring(200), columns="src dst") + lazy = SparseMatrix.from_edges(*ring(200), columns="complex::reflexive::node") + # it moves half of the time: twice the iterations + assert lazy.suggest_iterations() == round(2 * 16 / np.sqrt(2)) + assert lazy.suggest_iterations() == pytest.approx(2 * pair.suggest_iterations(), abs=1) + # and however dense, it needs 8 iterations to forget its initial vectors (0.5 ** 8 = 1 / 256) + dense = SparseMatrix.from_edges(*circulant(400, 150), columns="complex::reflexive::node") + assert dense.suggest_iterations(purpose="similarity") == 8 + assert dense.suggest_iterations(purpose="classification") == 8 + + +def test_very_dense_plain_graphs_get_two_iterations(): + dense = SparseMatrix.from_edges(*circulant(400, 150), columns="src dst") # 300 neighbours + assert dense.suggest_iterations() == 2 + + +def test_symmetric_propagation_gets_more_iterations(): + graph = SparseMatrix.from_edges(*ring(200), columns="src dst") + assert graph.suggest_iterations("symmetric") == round(1.5 * 16 / np.sqrt(2)) + assert graph.suggest_iterations("left") == graph.suggest_iterations() + + +def test_edge_weights_do_not_change_the_number_of_neighbours(): + source, target = ring(200) + plain = SparseMatrix.from_edges(source, target, columns="complex::reflexive::node") + weighted = SparseMatrix.from_edges(source, target, columns="complex::reflexive::node", + weights=np.linspace(0.5, 4.0, len(source))) + assert weighted.suggest_iterations() == plain.suggest_iterations() + + +def test_unknown_propagation_is_rejected(): + graph = SparseMatrix.from_edges(*ring(10), columns="src dst") + with pytest.raises(ValueError, match="propagation"): + graph.suggest_iterations("sideways") diff --git a/tests/python/test_weights.py b/tests/python/test_weights.py new file mode 100644 index 0000000..7721d0b --- /dev/null +++ b/tests/python/test_weights.py @@ -0,0 +1,129 @@ +"""Edge / hyperedge weights are part of the matrix.""" + +import numpy as np +import pytest + +import pycleora +from pycleora import SparseMatrix +from pycleora.io_utils import from_arrays, from_edge_list, from_numpy, from_pandas, from_scipy_sparse + +from conftest import dense, lines_from_rows, random_rows, reference_graph + +COLUMNS = "complex::reflexive::item" + + +def test_weights_match_reference(rng): + rows = random_rows(rng, 250, [True], vocabulary=30, max_len=6) + weights = rng.uniform(0.1, 9.0, size=len(rows)).astype(np.float32) + graph = SparseMatrix.from_iterator(iter(lines_from_rows(rows)), COLUMNS, weights=weights) + ids, raw, row_sums = reference_graph(rows, [(0, 0)], weights=weights) + assert list(graph.entity_ids) == ids + np.testing.assert_allclose(dense(graph), raw, rtol=1e-6) + np.testing.assert_allclose(graph.entity_degrees, row_sums, rtol=1e-6) + + +def test_integer_weight_equals_repeating_the_line(rng): + lines = lines_from_rows(random_rows(rng, 200, [True], vocabulary=25, max_len=5)) + counts = rng.integers(1, 5, size=len(lines)) + weighted = SparseMatrix.from_iterator(iter(lines), COLUMNS, weights=counts.astype(np.float64)) + repeated = SparseMatrix.from_iterator( + iter([line for line, count in zip(lines, counts) for _ in range(count)]), COLUMNS + ) + assert weighted.entity_ids == repeated.entity_ids + np.testing.assert_allclose(dense(weighted), dense(repeated), rtol=1e-6) + + +def test_zero_weight_removes_the_line(): + lines = ["a b", "c d", "a c"] + graph = SparseMatrix.from_iterator(iter(lines), COLUMNS, weights=[1.0, 0.0, 2.0]) + reference = SparseMatrix.from_iterator(iter(["a b", "a c"]), COLUMNS, weights=[1.0, 2.0]) + assert graph.entity_ids == reference.entity_ids == ("a", "b", "c") + np.testing.assert_array_equal(dense(graph), dense(reference)) + + +def test_common_factor_does_not_change_the_walk(rng): + lines = lines_from_rows(random_rows(rng, 200, [True], vocabulary=25, max_len=5)) + weights = rng.uniform(0.5, 2.0, size=len(lines)) + a = SparseMatrix.from_iterator(iter(lines), COLUMNS, weights=weights) + b = SparseMatrix.from_iterator(iter(lines), COLUMNS, weights=weights * 37.5) + np.testing.assert_allclose(dense(a, "left"), dense(b, "left"), rtol=1e-5) + np.testing.assert_allclose(dense(a, "symmetric"), dense(b, "symmetric"), rtol=1e-5) + + +def test_weights_change_the_embedding(rng): + lines = lines_from_rows(random_rows(rng, 300, [True], vocabulary=40, max_len=4)) + random_weights = rng.uniform(0.01, 100.0, size=len(lines)) + _, uniform = pycleora.embed_weighted([(line, 1.0) for line in lines], COLUMNS, feature_dim=16, num_iterations=4) + _, weighted = pycleora.embed_weighted(list(zip(lines, random_weights)), COLUMNS, feature_dim=16, num_iterations=4) + plain = pycleora.embed(SparseMatrix.from_iterator(iter(lines), COLUMNS), 16, 4) + np.testing.assert_array_equal(uniform, plain) + assert np.abs(weighted - uniform).max() > 1e-2 + + +def test_weight_column(): + lines = ["u1\tp1 p2\t2.5", "u2\tp2\t0.5", "u1\tp3\t1"] + by_column = SparseMatrix.from_iterator(iter(lines), "user complex::product weight::w") + by_argument = SparseMatrix.from_iterator( + iter(["u1\tp1 p2", "u2\tp2", "u1\tp3"]), "user complex::product", weights=[2.5, 0.5, 1.0] + ) + assert by_column.entity_ids == by_argument.entity_ids + np.testing.assert_array_equal(dense(by_column), dense(by_argument)) + assert by_column.column_names == ["user", "product"] + + +def test_weight_column_in_files(tmp_path): + path = tmp_path / "edges.tsv" + path.write_text("a b\t3\nb c\t1.5\n") + graph = SparseMatrix.from_files([str(path)], "complex::reflexive::x weight::w") + reference = SparseMatrix.from_iterator(iter(["a b", "b c"]), "complex::reflexive::x", weights=[3.0, 1.5]) + np.testing.assert_array_equal(dense(graph), dense(reference)) + + +@pytest.mark.parametrize("bad", [[1.0], [1.0, -1.0], [1.0, float("nan")], [1.0, float("inf")], [1.0, 1e12]]) +def test_invalid_weights_are_rejected(bad): + with pytest.raises(ValueError, match="weights"): + SparseMatrix.from_iterator(iter(["a b", "b c"]), COLUMNS, weights=bad) + + +def test_weights_argument_and_column_are_exclusive(): + with pytest.raises(ValueError, match="not both"): + SparseMatrix.from_iterator(iter(["a b\t1"]), "complex::reflexive::x weight::w", weights=[1.0]) + + +def test_weight_types(): + lines = ["a b", "b c", "c d"] + expected = dense(SparseMatrix.from_iterator(iter(lines), COLUMNS, weights=[1.0, 2.0, 3.0])) + for weights in ( + (1, 2, 3), + np.array([1, 2, 3]), + np.array([1, 2, 3], dtype=np.float32), + np.array([1.0, 2.0, 3.0])[::1], + np.array([1.0, 9.0, 2.0, 9.0, 3.0])[::2], + ): + np.testing.assert_array_equal(dense(SparseMatrix.from_iterator(iter(lines), COLUMNS, weights=weights)), expected) + with pytest.raises(TypeError): + SparseMatrix.from_iterator(iter(lines), COLUMNS, weights="abc") + + +def test_helpers_carry_weights(): + pd = pytest.importorskip("pandas") + scipy_sparse = pytest.importorskip("scipy.sparse") + + reference = dense(from_arrays(["a", "b", "a"], ["b", "c", "c"], weights=[2.0, 0.5, 4.0])) + assert reference[0, 1] != reference[1, 2] + + frame = pd.DataFrame({"s": ["a", "b", "a", "x"], "t": ["b", "c", "c", None], "w": [2.0, 0.5, 4.0, 1.0]}) + np.testing.assert_array_equal(dense(from_pandas(frame, "s", "t", weight_col="w")), reference) + + np.testing.assert_array_equal(dense(from_edge_list([("a", "b", 2.0), ("b", "c", 0.5), ("a", "c", 4.0)])), reference) + + adjacency = np.array([[0, 2.0, 4.0], [2.0, 0, 0.5], [4.0, 0.5, 0]]) + names = ["a", "b", "c"] + np.testing.assert_array_equal(dense(from_numpy(adjacency, names, use_weights=True)), reference) + np.testing.assert_array_equal( + dense(from_scipy_sparse(scipy_sparse.csr_matrix(adjacency), names, use_weights=True)), reference + ) + # without use_weights the values are ignored, as before + unweighted = dense(from_arrays(["a", "a", "b"], ["b", "c", "c"])) + np.testing.assert_array_equal(dense(from_numpy(adjacency, names)), unweighted) + np.testing.assert_array_equal(dense(from_scipy_sparse(scipy_sparse.csr_matrix(adjacency), names)), unweighted) diff --git a/tests/snapshot.rs b/tests/snapshot.rs index dc55ae1..3914351 100644 --- a/tests/snapshot.rs +++ b/tests/snapshot.rs @@ -1,12 +1,10 @@ #[cfg(test)] mod tests { use insta::assert_debug_snapshot; - use ndarray; - use ndarray::{Array, Array2, ArrayBase, Dim, Ix, OwnedRepr}; - use ndarray_rand::rand::rngs::StdRng; - use ndarray_rand::rand::{RngCore, SeedableRng}; - use ndarray_rand::rand_distr::Uniform; - use ndarray_rand::RandomExt; + use ndarray::Array2; + use rand::distributions::{Distribution, Uniform}; + use rand::rngs::StdRng; + use rand::{RngCore, SeedableRng}; use pycleora::embedding::{MarkovType, NdArrayMatrix}; use pycleora::sparse_matrix::SparseMatrix; @@ -49,8 +47,7 @@ mod tests { assert_debug_snapshot!(embedding_out); } - fn create_graph_embeddings_complex_complex( - ) -> (SparseMatrix, ArrayBase, Dim<[Ix; 2]>>) { + fn create_graph_embeddings_complex_complex() -> (SparseMatrix, Array2) { let num_embeddings: usize = 100; let mut rng: StdRng = SeedableRng::seed_from_u64(21_37); @@ -78,16 +75,16 @@ mod tests { let feature_dim: usize = 32; - let embeddings = Array::random_using( - (num_embeddings, feature_dim), - Uniform::new(0., 10.), - &mut rng, - ); + // Same stream as `ndarray_rand::RandomExt::random_using`, which the stored + // snapshots were generated with: one sample per element, in row-major order. + let distribution = Uniform::new(0.0f32, 10.0); + let embeddings = Array2::from_shape_simple_fn((num_embeddings, feature_dim), || { + distribution.sample(&mut rng) + }); (graph, embeddings) } - fn create_graph_embeddings_complex_reflexive( - ) -> (SparseMatrix, ArrayBase, Dim<[Ix; 2]>>) { + fn create_graph_embeddings_complex_reflexive() -> (SparseMatrix, Array2) { let num_embeddings: usize = 100; let mut rng: StdRng = SeedableRng::seed_from_u64(21_37); @@ -108,11 +105,12 @@ mod tests { let feature_dim: usize = 32; - let embeddings = Array::random_using( - (num_embeddings, feature_dim), - Uniform::new(0., 10.), - &mut rng, - ); + // Same stream as `ndarray_rand::RandomExt::random_using`, which the stored + // snapshots were generated with: one sample per element, in row-major order. + let distribution = Uniform::new(0.0f32, 10.0); + let embeddings = Array2::from_shape_simple_fn((num_embeddings, feature_dim), || { + distribution.sample(&mut rng) + }); (graph, embeddings) } } diff --git a/tests/snapshots/snapshot__tests__markov_left_01.snap b/tests/snapshots/snapshot__tests__markov_left_01.snap index 5874904..b08c6fd 100644 --- a/tests/snapshots/snapshot__tests__markov_left_01.snap +++ b/tests/snapshots/snapshot__tests__markov_left_01.snap @@ -98,7 +98,7 @@ expression: embedding_out [6523, 3079, 7110, 6978, 6519, 7538, 4337, 4560, 4972, 4371, 6291, 7053, 6023, 4865, 3147, 6592, 3896, 5241, 6846, 5946, 2961, 3281, 4089, 7426, 4549, 7335, 3599, 5200, 7036, 6181, 5164, 4603], [5583, 6957, 7160, 6885, 3165, 7911, 3697, 2184, 4916, 6661, 6860, 5649, 4638, 7357, 3791, 6752, 7317, 4977, 2469, 5083, 6410, 2659, 5693, 6755, 2665, 4902, 4149, 3983, 5651, 4820, 3833, 5039], [5137, 5530, 5632, 4951, 4019, 5719, 6089, 5737, 6852, 3965, 2892, 5193, 6524, 5158, 5885, 5866, 4892, 6385, 6162, 3068, 5998, 4065, 6603, 5435, 3860, 6588, 3785, 6210, 3873, 6878, 3347, 5243], - [5678, 3918, 4689, 7594, 5943, 5303, 6125, 6480, 5700, 2751, 7061, 6271, 4743, 2065, 1999, 6562, 2902, 6361, 7073, 3995, 4641, 4437, 4887, 4967, 3388, 6163, 7807, 6995, 4341, 5849, 5687, 6944], + [5678, 3918, 4689, 7594, 5943, 5303, 6125, 6480, 5700, 2751, 7061, 6271, 4743, 2065, 1999, 6562, 2902, 6361, 7073, 3995, 4641, 4438, 4887, 4967, 3388, 6163, 7807, 6995, 4341, 5849, 5687, 6944], [2835, 4877, 5601, 2336, 5031, 5865, 3383, 4197, 4824, 2600, 4492, 6154, 5742, 5893, 4343, 6891, 5883, 6832, 3729, 5581, 5765, 4149, 6710, 5006, 6299, 7173, 4452, 2881, 3522, 6247, 6336, 3477], [3949, 5986, 2444, 6310, 5759, 7035, 4838, 3556, 3327, 7157, 5275, 5712, 2997, 2851, 2835, 6891, 5021, 3696, 3678, 5668, 3540, 4057, 6126, 5905, 4129, 6032, 5551, 4317, 5451, 5626, 7724, 6576], [7714, 5290, 5891, 3883, 3423, 6981, 7007, 7081, 4968, 6412, 6813, 4853, 3143, 3917, 6755, 4856, 2602, 6947, 3587, 2957, 4261, 3170, 3061, 6054, 4258, 5843, 5853, 2877, 4267, 6938, 7569, 5433]], shape=[100, 32], strides=[32, 1], layout=Cc (0x5), const ndim=2 diff --git a/tests/snapshots/snapshot__tests__markov_left_02.snap b/tests/snapshots/snapshot__tests__markov_left_02.snap index ab1d37e..ed3e3b4 100644 --- a/tests/snapshots/snapshot__tests__markov_left_02.snap +++ b/tests/snapshots/snapshot__tests__markov_left_02.snap @@ -1,12 +1,11 @@ --- source: tests/snapshot.rs -assertion_line: 31 expression: embedding_out --- [[5616, 5049, 4705, 4796, 5524, 4975, 4748, 4576, 4597, 5267, 5397, 5265, 4064, 5312, 5110, 4791, 4400, 5462, 5045, 4821, 4434, 5255, 5106, 4929, 5351, 4791, 5309, 4956, 4782, 4826, 5200, 4381], [6013, 4638, 4683, 5031, 5790, 4837, 4174, 4353, 5286, 5298, 5200, 5886, 4438, 5184, 5251, 5441, 4866, 5472, 4840, 4806, 3984, 4394, 5482, 3822, 5165, 4929, 5088, 5566, 4726, 4523, 5116, 4291], [5766, 4827, 4389, 4899, 5166, 4802, 4281, 5281, 4724, 5583, 4962, 5428, 3971, 4910, 5020, 4823, 4636, 5304, 5453, 4334, 4842, 5001, 5067, 4668, 5044, 5017, 5218, 5431, 4694, 4352, 4704, 4716], - [5543, 4673, 4300, 4837, 5177, 5186, 4680, 4371, 4797, 5347, 4756, 6032, 4214, 5094, 4964, 4494, 4004, 5390, 3761, 4587, 5102, 4595, 5235, 4517, 4836, 4944, 4896, 4980, 4510, 5311, 5008, 4847], + [5543, 4674, 4300, 4837, 5177, 5186, 4680, 4371, 4797, 5347, 4756, 6032, 4214, 5094, 4964, 4494, 4004, 5390, 3761, 4587, 5102, 4595, 5235, 4517, 4836, 4944, 4896, 4980, 4510, 5311, 5008, 4847], [4700, 5096, 4454, 4895, 4722, 5782, 4827, 4924, 4973, 5414, 5212, 5636, 4710, 5458, 5368, 5211, 4376, 4882, 4776, 4855, 4605, 4583, 5187, 5146, 5060, 4893, 5434, 4660, 4750, 4681, 4938, 3846], [5239, 4660, 3898, 4312, 5587, 4839, 4645, 4674, 4544, 6107, 5209, 5942, 4711, 5093, 4857, 5385, 4592, 4785, 5012, 4260, 4716, 5325, 5224, 4517, 5575, 4845, 5721, 5088, 5273, 4731, 5338, 4927], [5814, 5092, 5355, 4727, 5917, 5001, 4864, 4911, 4964, 5833, 4360, 5233, 5572, 4613, 5156, 4888, 4890, 5226, 4700, 4861, 4656, 4456, 5631, 4989, 4637, 5247, 5515, 4378, 4835, 5105, 4522, 4624], @@ -94,7 +93,7 @@ expression: embedding_out [4818, 4914, 5108, 4555, 5681, 5262, 4533, 4805, 4851, 5529, 5048, 5818, 4909, 4927, 5638, 4428, 4620, 5653, 4611, 4909, 4088, 4811, 5401, 4044, 5458, 5150, 5271, 5510, 4504, 4291, 5066, 4468], [5599, 4977, 4480, 5115, 5375, 4745, 4856, 4723, 5208, 5951, 4767, 5210, 4378, 4865, 5176, 5422, 4762, 5845, 4916, 4696, 4292, 5329, 5504, 4132, 4767, 5512, 5243, 5262, 4626, 4875, 4856, 5257], [5746, 4836, 5216, 4808, 5673, 5184, 4391, 4711, 4828, 5748, 4960, 5071, 4110, 4607, 4900, 5457, 4788, 5582, 4861, 5173, 4595, 4590, 5137, 4707, 4858, 4497, 5608, 5406, 5093, 5319, 4731, 4569], - [5530, 5399, 4731, 5356, 5082, 5521, 4665, 4789, 4640, 5488, 4909, 5037, 4439, 4479, 4959, 5139, 3966, 5678, 5491, 4421, 4659, 5199, 4970, 4929, 5463, 4465, 4833, 5415, 4760, 5395, 4560, 4168], + [5530, 5399, 4731, 5356, 5082, 5521, 4665, 4789, 4640, 5488, 4909, 5037, 4439, 4479, 4959, 5139, 3966, 5678, 5491, 4421, 4659, 5199, 4970, 4929, 5463, 4465, 4833, 5415, 4761, 5395, 4560, 4168], [5330, 5228, 4402, 5192, 5325, 4297, 5103, 4813, 5167, 5572, 4704, 5313, 3584, 4610, 4328, 5521, 5049, 4763, 4480, 4396, 5314, 5206, 4947, 4495, 4390, 5333, 4940, 5113, 5291, 5649, 4897, 4902], [5787, 4729, 4406, 5152, 5015, 4742, 4341, 4978, 4242, 5338, 5413, 5226, 4321, 4558, 4732, 5108, 4260, 4949, 5273, 4811, 4684, 5512, 4627, 4898, 4858, 4981, 4938, 4950, 5438, 5592, 5768, 5006], [5225, 4982, 4658, 5056, 5644, 4828, 4958, 5095, 4305, 4986, 5075, 5138, 4246, 4696, 4881, 5173, 4880, 5374, 5314, 4653, 4810, 4458, 5333, 4844, 5222, 5252, 5553, 5603, 4818, 4947, 4168, 4550], diff --git a/tests/snapshots/snapshot__tests__markov_sym_01.snap b/tests/snapshots/snapshot__tests__markov_sym_01.snap index be302eb..3344135 100644 --- a/tests/snapshots/snapshot__tests__markov_sym_01.snap +++ b/tests/snapshots/snapshot__tests__markov_sym_01.snap @@ -1,6 +1,5 @@ --- source: tests/snapshot.rs -assertion_line: 40 expression: embedding_out --- [[5205, 4494, 5473, 6162, 5249, 5177, 4084, 5417, 1853, 5858, 5598, 2754, 3044, 2174, 3585, 6728, 7189, 5900, 4162, 3569, 2764, 2871, 6165, 5764, 2021, 2740, 3175, 5067, 4259, 5444, 4661, 3731], @@ -63,7 +62,7 @@ expression: embedding_out [4124, 6858, 5283, 3404, 7068, 2556, 7400, 4643, 6065, 3626, 3643, 7574, 5004, 7105, 2358, 4187, 3227, 5668, 5437, 4140, 6519, 7077, 7339, 6591, 5743, 5408, 4465, 4780, 4404, 6718, 6690, 2213], [2139, 6803, 4525, 3067, 7523, 7711, 2996, 7063, 4255, 5654, 6579, 4814, 6351, 6861, 1915, 6394, 7215, 3259, 3633, 3142, 6577, 6311, 3246, 5746, 4589, 6165, 5410, 4547, 5986, 4781, 6728, 5340], [6949, 6116, 4133, 6671, 3788, 3710, 4019, 4379, 6145, 6709, 5797, 5382, 5664, 6001, 3013, 7767, 7274, 6682, 6090, 5517, 6132, 6800, 4293, 5885, 6760, 3334, 3579, 4966, 7351, 3002, 6554, 4653], - [6254, 4519, 4180, 5580, 6296, 5717, 5139, 2770, 2834, 4456, 4434, 3206, 5260, 2452, 6645, 6290, 6232, 4381, 5377, 6387, 2741, 6584, 4664, 4383, 5854, 3283, 6486, 3558, 6485, 2796, 5074, 3623], + [6254, 4519, 4180, 5580, 6296, 5718, 5139, 2770, 2834, 4456, 4434, 3206, 5260, 2452, 6645, 6290, 6232, 4381, 5377, 6387, 2741, 6584, 4664, 4383, 5854, 3283, 6486, 3558, 6485, 2796, 5074, 3623], [6157, 5729, 7263, 4244, 3645, 6884, 6976, 5024, 2148, 6697, 4169, 7362, 4280, 5540, 3670, 2957, 4166, 6993, 5529, 7199, 3626, 6917, 7715, 2677, 7257, 6071, 4808, 3392, 5636, 5849, 5771, 4771], [3135, 4145, 2864, 1954, 2454, 4925, 2646, 6500, 2254, 5008, 2303, 5349, 5041, 3412, 2447, 4561, 6948, 3259, 6163, 5933, 6618, 6776, 2554, 5964, 4564, 6620, 2555, 6022, 3158, 6211, 5091, 3854], [3199, 6867, 2625, 3601, 3597, 4384, 6192, 7195, 6304, 3790, 8070, 7418, 3524, 5509, 4408, 3982, 6865, 7205, 6507, 4110, 4049, 6413, 2927, 5525, 6187, 7511, 3512, 5652, 3305, 6312, 3549, 4508], @@ -72,8 +71,8 @@ expression: embedding_out [6762, 7299, 3981, 3790, 7910, 4474, 7363, 6109, 7458, 3057, 5710, 3627, 3507, 6103, 2696, 3197, 6481, 3676, 5137, 3885, 4163, 2707, 3042, 3371, 3789, 5272, 3172, 5981, 4865, 3213, 4459, 2899], [4108, 7808, 5499, 7071, 4882, 4243, 6415, 2903, 4970, 3095, 6669, 4120, 5862, 2417, 2568, 7581, 6582, 5432, 7020, 7291, 6449, 4055, 7296, 5057, 3141, 3602, 6719, 7381, 2876, 7513, 5552, 2791], [2947, 3724, 6281, 4211, 2866, 5736, 3896, 5668, 4877, 5790, 5641, 3436, 3782, 4902, 5889, 3680, 7368, 4427, 2413, 6750, 2969, 2419, 5356, 6532, 4317, 4179, 3706, 3834, 2148, 6309, 4492, 4022], - [7102, 5788, 7640, 3766, 6897, 2777, 5990, 4070, 6786, 1804, 4115, 4234, 2951, 2378, 4237, 3745, 4209, 6329, 6125, 5346, 6414, 4020, 7046, 7405, 6129, 7975, 7702, 7437, 2045, 3106, 4186, 2856], - [3691, 3441, 5293, 6288, 3318, 4275, 4775, 5266, 6615, 5807, 3890, 4550, 3849, 6368, 6374, 2939, 7000, 6280, 1996, 5938, 4280, 3556, 6225, 2926, 2612, 2738, 6630, 3328, 2924, 4165, 4677, 4719], + [7102, 5788, 7640, 3766, 6897, 2777, 5990, 4070, 6786, 1804, 4115, 4234, 2951, 2378, 4237, 3745, 4209, 6328, 6125, 5346, 6414, 4020, 7046, 7405, 6129, 7975, 7702, 7437, 2045, 3106, 4186, 2856], + [3691, 3441, 5293, 6288, 3318, 4275, 4775, 5266, 6615, 5807, 3890, 4550, 3849, 6368, 6374, 2939, 7000, 6280, 1996, 5938, 4280, 3555, 6225, 2926, 2612, 2738, 6630, 3328, 2924, 4165, 4677, 4719], [7012, 5255, 4495, 5826, 5750, 3459, 5350, 6098, 2550, 7376, 5028, 4940, 3921, 4208, 4652, 6913, 7170, 2801, 5343, 4018, 4273, 5483, 7069, 2356, 4357, 3430, 5570, 2304, 3902, 5271, 4787, 2994], [4211, 7655, 7575, 4868, 6108, 7253, 5097, 5763, 4610, 4708, 3806, 3963, 4131, 5552, 6946, 5281, 3793, 7698, 5625, 7705, 6373, 6053, 7293, 4762, 3815, 4322, 6482, 3550, 5077, 3684, 4629, 5690], [3275, 5491, 7369, 6632, 6826, 7084, 5589, 3250, 6189, 4016, 6084, 7069, 6336, 6213, 2859, 6358, 5181, 5729, 4951, 3887, 7106, 5338, 6733, 4269, 7160, 5412, 5685, 3904, 6077, 6577, 6435, 5175], diff --git a/tests/snapshots/snapshot__tests__markov_sym_02.snap b/tests/snapshots/snapshot__tests__markov_sym_02.snap index 80418f7..993a5fa 100644 --- a/tests/snapshots/snapshot__tests__markov_sym_02.snap +++ b/tests/snapshots/snapshot__tests__markov_sym_02.snap @@ -1,6 +1,5 @@ --- source: tests/snapshot.rs -assertion_line: 49 expression: embedding_out --- [[5840, 5236, 4808, 4910, 5726, 5097, 4895, 4767, 4748, 5434, 5569, 5426, 4240, 5527, 5220, 4968, 4596, 5625, 5210, 5022, 4607, 5420, 5271, 5031, 5508, 4960, 5475, 5160, 4962, 4957, 5321, 4587], @@ -72,7 +71,7 @@ expression: embedding_out [5299, 4834, 4384, 4826, 5819, 5120, 5333, 5289, 5455, 4943, 5724, 5339, 4268, 4869, 5045, 5745, 5760, 5474, 5348, 5420, 4552, 4821, 4688, 4806, 5454, 4420, 5505, 5555, 4451, 5055, 5026, 4941], [5625, 5965, 5381, 4771, 6099, 5701, 5439, 4845, 4716, 5865, 5190, 6182, 4705, 5293, 5967, 5977, 4807, 5872, 5398, 5450, 5060, 5925, 6287, 4842, 5805, 5481, 5470, 5845, 5853, 4942, 5588, 5278], [5577, 5180, 4883, 5212, 5619, 4812, 4808, 4339, 4662, 5781, 4820, 6036, 4275, 4485, 5773, 4604, 4109, 5386, 4666, 4674, 4851, 4709, 5835, 5592, 5144, 5654, 5100, 4704, 5570, 5168, 5234, 4587], - [5389, 4321, 3726, 4633, 5217, 4517, 4646, 4850, 4318, 5785, 5031, 5005, 4531, 4615, 4527, 5025, 4589, 5025, 4441, 4310, 4223, 5258, 4917, 4772, 4987, 5280, 4584, 5237, 4900, 4442, 5272, 4579], + [5389, 4321, 3726, 4633, 5217, 4517, 4646, 4850, 4318, 5785, 5031, 5005, 4531, 4615, 4527, 5025, 4589, 5025, 4441, 4310, 4223, 5258, 4917, 4772, 4987, 5280, 4583, 5237, 4900, 4442, 5272, 4579], [5053, 4390, 4953, 4562, 4408, 4772, 4128, 4024, 3930, 4747, 5248, 5044, 4350, 4358, 4995, 4231, 3793, 4900, 4683, 4753, 4468, 4629, 4333, 4461, 4533, 4767, 4532, 4488, 4966, 4495, 4857, 4299], [5170, 5119, 4301, 4909, 5181, 5370, 4266, 4368, 4201, 4984, 5102, 5321, 4625, 5717, 4788, 4837, 4872, 5077, 5247, 4922, 5284, 4764, 5231, 4767, 5544, 5156, 5215, 5520, 5215, 5194, 5084, 4121], [5302, 5726, 4774, 4521, 6010, 5425, 4394, 5391, 4766, 5110, 4906, 5840, 4687, 5090, 5261, 5532, 4708, 5597, 5819, 4950, 4273, 4761, 5405, 5059, 4799, 4622, 5544, 5148, 5228, 5915, 4766, 5006], diff --git a/tests/wheel_smoke.py b/tests/wheel_smoke.py new file mode 100644 index 0000000..599a5b4 --- /dev/null +++ b/tests/wheel_smoke.py @@ -0,0 +1,21 @@ +"""Minimal check that an installed pycleora wheel works. CI runs it against the +freshly built wheel on every platform it can execute on (the full test suite in +tests/python runs on Linux).""" + +import numpy as np + +import pycleora +from pycleora import SparseMatrix, embed + +lines = [f"n{i % 50} n{(i * 7 + 1) % 50} n{(i * 13 + 2) % 50}" for i in range(200)] +graph = SparseMatrix.from_iterator(iter(lines), "complex::reflexive::node") +assert graph.num_entities == 50, graph + +default = embed(graph, 16) +whitened = embed(graph, 16, 4, whiten=True) +assert default.shape == whitened.shape == (50, 16) +assert np.isfinite(default).all() and np.isfinite(whitened).all() +np.testing.assert_allclose(np.linalg.norm(default, axis=1), 1.0, atol=1e-5) +np.testing.assert_array_equal(default, embed(graph, 16, graph.suggest_iterations(), num_workers=1)) + +print(f"pycleora {pycleora.__version__}: ok")