Skip to main content

GeoPres

GeoPres compresses high-dimensional text embeddings with a single linear map that is trained to keep pairwise Euclidean distances. It is post-hoc: the embedding model stays frozen, and at inference time the whole "reduction" is one matrix multiply. The method is described in our EACL paper: "On Post-Hoc Dimensionality Reduction of Text Embeddings".

This repository features three parts:

  1. geopres, a small library — train a projection on your own embeddings, save it, reload it, and use it on new text (no GPU required).
  2. Reproducing the paper: pre-encode 10M C4 passages, train, run MTEB, compare against PCA / random projection / random selection / truncation / autoencoder baselines, and rebuild the paper's tables and plots.
  3. Miscellanea like a repository overview, FAQ, and a bibtex citation that you can use for citing the project.

Install

Python 3.10 or newer is required (tested on 3.10, 3.11, 3.12 and 3.13).

git clone https://github.com/konstantinoskalyfommatos/geopres
cd geopres

# recommended: uv, exactly how the paper runs were made
uv sync --extra research                     # package + paper dependencies
uv sync --extra research --extra spearman    # ... plus torchsort, for --spearman

# or with plain pip
pip install -e .                             # library only (torch + sentence-transformers)
pip install -e ".[research]"                 # + datasets, mteb, matplotlib, ...
pip install -e ".[spearman]"                 # + torchsort, only for the --spearman loss

torchsort is not installed by default because it has to be compiled against your CUDA toolchain; see Common issues.

PyPI. pip install geopres installs the library only. Add [research] or [spearman] for the paper pipeline: pip install "geopres[research]".


Quick start (PyPI library)

Fitting a dimension-reduced embedding model:

from geopres import GeoPres

model = GeoPres("sentence-transformers/all-mpnet-base-v2", dim=32)
model.fit(texts)                       # texts: list[str]
reduced = model.embed(texts)           # numpy array, shape (len(texts), 32)

model.save("geopres-mpnet-32")

Note that fit also accepts embeddings you already have, which allows much cheaper training:

import torch
from geopres import GeoPres

# mmap=True maps the file instead of reading it into RAM.
embeddings = torch.load("my_embeddings.pt", mmap=True, weights_only=True)  # (n, 768)
model = GeoPres("sentence-transformers/all-mpnet-base-v2", dim=32)
model.fit(embeddings)                                                      # no encoding, just the projection
reduced = model.embed(embeddings)                                          # (n, 32)

Encoding is the expensive part, and fit encodes your texts every time you call it. Encode once, then train as many projections as you like:

import torch
from geopres import GeoPres, encode_corpus

encode_corpus(texts, "c4.pt", "sentence-transformers/all-mpnet-base-v2")

embeddings = torch.load("c4.pt", weights_only=True)
GeoPres(dim=32).fit(embeddings)
GeoPres(dim=64).fit(embeddings)

Load a trained projection and use it on new text:

from geopres import GeoPres

model = GeoPres.load_path("geopres-mpnet-32")  # backbone id comes from config.json
reduced = model.embed(["a sentence I have never seen before"])

The projection is a plain matrix, therefore it can be applied on embeddings created elsewhere (e.g. Hugging Face's TEI), as long as the underlying vector-generator function (e.g. embedding model) is the same during training and inference. "Same" includes the pooling, the normalisation and, for instruction-based models such as Qwen3-Embedding, the same query/passage prefixes.

Projection is the API for exactly that: the matrix and nothing else. No backbone is loaded, downloaded or needed.

from geopres import Projection

projection = Projection.load_path("geopres-mpnet-32")
# or: Projection.from_pretrained("kkalyfo/geopres-mpnet-32")
projection.source_dim, projection.dim                # (768, 32)

# any vector from the same embedding model: TEI, a vector DB, another service
vector = get_embedding(embedding_model_name="sentence-transformers/all-mpnet-base-v2")
reduced = projection.project(vector)                # (32,)

vectors = ...                                       # (1000, 768)
reduced = projection.project(vectors)               # (1000, 32)

If you would rather not depend on geopres at inference time, the matrix is just projection.weight, of shape (dim, source_dim): one vectors @ weight.T.

Trained projections released with the paper live under huggingface.co/kkalyfo/geopres-projections.

API summary

Call What it does
GeoPres(model, dim=32) model is a sentence-transformers id, a loaded SentenceTransformer, or None (embeddings only).
.fit(data, ...) Train on texts or on an (n, source_dim) array/tensor. Returns self.
encode_corpus(texts, path, model) Encode a corpus once and save it as one float32 tensor, so fit can be re-run without re-encoding.
.embed(data, ...) Project texts or embeddings to dim. Returns (n, dim) numpy by default, (dim,) for a single vector.
.save(path) Writes config.json + projection.safetensors.
GeoPres.load_path(path) Reloads a saved directory (or a bare .pt / .safetensors weight file).
.to_sentence_transformer() Backbone + projection as a SentenceTransformer, e.g. for MTEB.
.push_to_hub(repo_id, private=False) Upload config.json, weights and a model card to the HF Hub.
GeoPres.from_pretrained(repo_id) Download and load a projection from the HF Hub.
Projection.load_path(path) / .from_pretrained(repo_id) The projection alone, for embeddings you already have. .project(vectors), no backbone. .to_torch() for the nn.Module.

fit defaults follow the paper (10 epochs, AdamW, lr 1e-2, weight decay 0.1, linear warmup 0.1, early stopping patience 3, batch size 20 000). Batch size is a hyperparameter, not only a memory setting: the loss compares all pairs inside a batch, so a smaller batch trains on a different signal.

Data size matters less than batch size. The paper trained on 10M passages because more data kept helping, but a few hundred thousand text samples are enough to get a good projection (see Data).


Reproducing the paper

The pipeline is precalculate → train → evaluate → collect.

# 0) environment
uv sync --extra research

# 1) pre-encode the corpora with a backbone (one-time per backbone, GPU, slow)
uv run geopres-precalculate \
    --model_name jinaai/jina-embeddings-v2-small-en \
    --train --val_test --batch_size 8192

# 2) train the projection
uv run geopres-train \
    --backbone_model jinaai/jina-embeddings-v2-small-en \
    --source_dim 512 --target_dim 32 \
    --train_batch_size 20000 --val_batch_size 20000 \
    --positional_loss_factor 1 --weighted_loss

# 3) evaluate on MTEB (this is also run automatically at the end of step 2)
uv run geopres-eval --backbone_model jinaai/jina-embeddings-v2-small-en --source_dim 512 --target_dim 32

# 4) merge all MTEB caches into one CSV
uv run geopres-compare

Everything is also runnable as a module (python -m geopres.train_model ...) if you prefer not to use the console scripts.

Data. Step 1 uses allenai/c4 (en split, 10M passages longer than 200 words) for training and agentlans/sentence-paraphrases for validation/test. No dataset is downloaded by the library; only step 1 needs the datasets package.

We used 10M training samples because results kept improving as we added more data, but this is not a requirement: a few hundred thousand text samples are already enough for a good projection, and they make the one-time encoding step much cheaper. Pass --max_train_examples to cap the training set.

Baselines read the same cached embeddings:

uv run python -m geopres.baselines.fit_pca --model_name <backbone> --target_dim 32
uv run python -m geopres.baselines.eval_pca --backbone_model <backbone> --target_dim 32
uv run python -m geopres.baselines.train_autoencoder --backbone_model <backbone> --target_dim 32
# ... eval_random_projection, eval_random_selection, eval_truncation

Tables and plots. analysis/ contains the scripts that regenerate the paper's figures, LaTeX tables and bootstrap tests from the cached results. They are not part of the installed package, e.g. uv run python analysis/create_scatter_plot.py.

Where files go

Everything lands under storage/ in the repository:

storage/
├── precalculated_embeddings/<dataset>/<backbone>/{train,validation,test}_embeddings.pt
├── trained_models/<backbone>/<model_name>/checkpoint-N/ + best_model.pt
├── trained_autoencoders/<backbone>/<model_name>/...
├── pca/<backbone>/<target_dim>/
└── evaluation_results/{backbone,trained_models,autoencoders}/...

HF_TOKEN is picked up from the environment by huggingface_hub if you need gated datasets.


Miscellanea

Repository layout overview

geopres/
├── api.py                          # public API: GeoPres (fit / embed / save) and Projection
├── projection.py                   # the linear map W (a bias-free nn.Linear)
├── losses.py                       # positional / angular / Spearman losses
├── encode.py                       # loading a backbone and encoding text
├── config.py                       # paths + dtype helpers
├── train_model.py                  # paper training entry point (HF Trainer)
├── geopres_trainer.py              # HF Trainer subclass with the pairwise loss
├── reduced_sentence_transformer.py # backbone + projection as a SentenceTransformer
├── precalculate_embeddings.py      # one-time encoding of C4 / sentence-paraphrases
├── eval_model.py                   # MTEB + intrinsic eval of a trained projection
├── eval_backbone.py                # MTEB eval of the raw backbone (reference point)
├── eval_utils.py                   # shared MTEB runner and intrinsic metrics
├── compare_results.py              # merges MTEB caches into comparison_results.csv
├── py.typed                        # this package ships type hints
└── baselines/                      # PCA, random projection, random selection, truncation, autoencoder
analysis/                           # paper tables, plots, bootstrap tests (not shipped)
tests/                              # pytest: API, persistence, losses, hub (no GPU, no network)

Common issues

torchsort fails to install or build

torchsort is only needed for --spearman. It builds from source, so it needs a CUDA toolchain. If that fails, install a pre-built wheel from the torchsort releases:

export TORCHSORT=0.1.10
export TORCH=pt26      # your torch version: pt26, pt25, pt24, pt21, pt20, pt113
export CUDA=cu126      # cpu, cu113, cu117, cu118, cu121, cu124, cu126
export PYTHON=cp312    # cp310, cp311, cp312

uv pip install https://github.com/teddykoker/torchsort/releases/download/v${TORCHSORT}/torchsort-${TORCHSORT}+${TORCH}${CUDA}-${PYTHON}-${PYTHON}-linux_x86_64.whl

Alibaba-NLP/gte-multilingual-base (mGTE) breaks with newer transformers

The paper's environment pins transformers==4.57.6. Newer versions break mGTE at encode time. If you change the pin, re-test mGTE.

Out of memory during training

Memory is dominated by the pairwise loss, which compares every pair of embeddings in a batch, so it grows quadratically with the batch size. The paper trains with --train_batch_size 20000, and that is the configuration the reported numbers come from: keep it if you want comparable results.

Shrinking the batch is not a free fix. Fewer pairs per step means a different training signal, so a smaller batch produces a different model, not the same model on less memory. If 20000 does not fit on your GPU, treat the smaller batch as a new configuration and re-check the intrinsic validation loss (ideally also a task or two) instead of assuming the published numbers carry over.


Development

uv sync --extra research
uv run pytest            # fast, CPU-only, no downloads

Citation

@inproceedings{kalyfommatos2027geopres,
  title     = {On Post-Hoc Dimensionality Reduction of Text Embeddings},
  author    = {Kalyfommatos, Konstantinos and Michail, Andrianos and Huber, Marius
               and Psomas, Bill and Clematide, Simon and Opitz, Juri},
  booktitle = {Proceedings of the 2027 Conference of the European Chapter of the
               Association for Computational Linguistics (EACL 2027)},
  year      = {2027},
  url       = {https://openreview.net/forum?id=vAWo3CIzqp}
}

See also CITATION.cff.

License

MIT — see LICENSE.

Metadata

Release files for geopres 0.1.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for geopres 0.1.2
File Size Uploaded Provenance Actions
geopres-0.1.2.tar.gz 318.4 kB Without provenance Details for geopres-0.1.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for geopres 0.1.2
File Interpreter ABI Platform Actions
geopres-0.1.2-py3-none-any.whl Python 3 none any Details for geopres-0.1.2-py3-none-any.whl

Total release size: 375.9 kB

Release files / geopres-0.1.2.tar.gz

Download URL geopres-0.1.2.tar.gz
Size 318.4 kB
Tags Source
SHA-256 checksum
How to use checksums
bc2cd4a9587ff6f7919e07b7cec85c27d00c84025e1bca7d65c19f5421720e05
BLAKE2b-256 checksum
How to use checksums
a6eb7143c436542c39e86340ac6b26d7a4bc894b9f8d48f0604ce55df276c8ea
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.7.2

Release files / geopres-0.1.2-py3-none-any.whl

Download URL geopres-0.1.2-py3-none-any.whl
Size 57.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
433002a1fb69a2877fc1f724454d5bf5a1146b479167dec9c3479d046c1038b1
BLAKE2b-256 checksum
How to use checksums
94b6b544bacd51f016ef4502f09dc7c789036ad78c5e2a01450fd5d6fd955478
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.7.2

Security for geopres 0.1.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page