Skip to content
GregorKornhardtPublic

About

Sliced Optimal Transport for Language

Resources

Contributing

Stars

11 stars

Watchers

0 watching

Forks

Repository files navigation

SOL - Sliced Optimal Transport for Language

SOL compares generated and reference text distributions using a double-sliced Wasserstein distance over contextual token embeddings. It requires only samples and measures differences in quality and diversity. Lower is closer; identical corpora score zero.

Paper · Website · API · Models · Changelog · Contributing

SOL embeds texts as token clouds, projects them to quantiles, slices again, and compares the resulting corpus distributions.

SOL compares corpora by embedding texts as token clouds and slicing twice (paper, Fig. 1).

Install

pip install 'sol-metric[text]'    # compare texts (PyTorch + Transformers)
pip install 'sol-metric[torch]'   # score existing embeddings on a GPU
pip install sol-metric            # score existing embeddings with NumPy only

Python 3.10 or newer. For a specific CUDA version, install PyTorch first; add accelerate to load large checkpoints straight onto the GPU.

Use

The default encoder is Dream 7B (~15 GB of FP16 weights, plus activations). This example uses the smaller GPT-2 Large; omit encoder to use Dream.

from sol_metric import SOL, TextEncoder

reference = ["The train arrived at noon.", "It rained throughout the night."]
generated = ["The afternoon train was late.", "Heavy rain fell overnight."]
encoder = TextEncoder('gpt2-large')
metric = SOL()
print(metric.from_texts(reference, generated, encoder=encoder))

Compare scores with the same encoder and evaluation settings; there is no universal "good" score. The tiny example illustrates the API; the bundled validation uses 5,000 texts per corpus.

Features can be saved and reused, for example one reference against several generated corpora:

from tempfile import TemporaryDirectory
from sol_metric import Features

with TemporaryDirectory() as tmp:
    metric.featurize_texts(reference, encoder=encoder, path=f'{tmp}/reference').close()
    with Features.load(f'{tmp}/reference') as ref:
        with metric.featurize_texts(generated, encoder=encoder) as gen:
            print(metric.from_features(ref, gen))

Existing token embeddings need only NumPy. Stack the token states of all documents in one array and mark where each document starts and ends:

import numpy as np
from sol_metric import SOL

rng = np.random.default_rng(0)
x = rng.normal(size=(12, 16))  # corpus 1: 12 token states of dimension 16
x_offsets = [0, 4, 7, 12]      # 3 documents: rows 0-3, 4-6 and 7-11
y = rng.normal(size=(10, 16))  # corpus 2: 10 token states
y_offsets = [0, 5, 10]         # 2 documents: rows 0-4 and 5-9
print(SOL().from_tokens(x, x_offsets, y, y_offsets))

Good to know:

  • seed and gp_seed default to 0; vary both to measure spread over seeds.
  • Dream, GPT-2 Large, OLMo 2 and Qwen3 use pinned paper checkpoints; revision='main' selects the latest.
  • Encoders use FP16 on GPU, FP32 on CPU, and truncate with a warning beyond the model limit (Dream: 2,048 tokens; GPT-2 Large: 1,024).
  • CUDA is selected automatically; pass device='cpu' to force the CPU.
  • metric.last_run records the score, encoder, revision and settings.

Validate the frozen 5k pairs

The bundled LM1B and OpenWebText pairs validate the package against the paper's GPT-2 Large evaluation code. The OpenWebText pair is the paper's seed-0 MDLM subset.

git clone https://github.com/GregorKornhardt/SOL.git
cd SOL
pip install '.[text]'
python examples/compare_corpora.py owt                             # 32 texts per corpus
python examples/compare_corpora.py owt --validate --device cuda:0  # 5,000 per corpus
5k pair Generated by Expected score (FP16)
LM1B vMF flow model 0.961872093
OpenWebText MDLM, exact sampling 2.167415507

--validate re-encodes both corpora and checks the recorded scores. Under the fixed protocol, this package matched the independent paper code within 1e-10 relative. On an RTX 5090 the OpenWebText check takes about 2.5 minutes. The paper's table reports 2.167356 because it used GPT-2 token IDs instead of the decoded text. The 5k texts (20 MB) are in the Git repository, not the PyPI package; see the validation manifest.

Settings

SOL(...) Default Meaning
n_directions, n_projections 8,192 for Dream, else 1,024 token directions and GP slices
n_quantiles 64 quantile bins per direction
lengthscale 0.1 RBF length scale of the GP slices
seed, gp_seed 0, 0 random directions and GP draws
scale hidden dimension factor on the squared distance
device 'auto' CUDA when available, else NumPy

Text features spill to temporary files beyond the RAM budget. FP16 encoder batching can slightly affect scores; see precision. Memory errors during binning or scoring name the batch size to lower. Settings are in the API reference.

What SOL computes

Each document is the uniform measure μᵢ on its token states in ℝᵈ, and a corpus is the uniform distribution over its documents. A unit direction ξ and a Gaussian-process draw g map every document to one number, M(μᵢ) = ⟨g, Q((e_ξ)#μᵢ)⟩, the GP-weighted integral of its projected quantile function. SOL averages one-dimensional Wasserstein distances over both:

$$\mathrm{SOL}(\boldsymbol\mu,\boldsymbol\nu)^2 = d\;\mathbb E_{\xi\sim\mathcal U(\mathbb S^{d-1}),\,g\sim\gamma} \Big[\mathrm W_2^2\big((M_{\xi,g})_\#\boldsymbol\mu,\ (M_{\xi,g})_\#\boldsymbol\nu\big)\Big]$$

with d the hidden dimension and γ a zero-mean GP with RBF covariance. The estimator uses n_directions × n_projections slices, exact quantile-bin integrals and exact transport for unequal corpus sizes.

Cite

@misc{kornhardt2026solmeasuringgapstext,
      title={SOL: Measuring Gaps between Text Distributions by Double Sliced Wasserstein Metrics},
      author={Gregor Kornhardt and Moritz Piening and Jannis Chemseddine and Gabriele Steidl},
      year={2026},
      eprint={2610.06513},
      archivePrefix={arXiv},
      primaryClass={cs.CL},
      url={https://arxiv.org/abs/2610.06513},
}

License

Apache-2.0. Model checkpoints and corpora keep their own licenses.

About

Sliced Optimal Transport for Language

Resources

Contributing

Stars

11 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages