Skip to main content

Project that uses theory of From Word Embeddings To Document Distances / Optimal Transport to give meaningful distance from one document to another, useful if building agentic projects that convert or extract information from one document to another using frontier models but without the ability to calculate KL divergence from logits

Project description

docdistance

CI PyPI version Total PyPI downloads

Semantic distance between two documents via Statement Mover's Distance - optimal transport over mmBERT statement embeddings, after Kusner et al. 2015 (From Word Embeddings To Document Distances). A thin frontend to the library; the SOTA docs carry the mechanics, benchmarks, and validation.

docdistance

  • Input - two documents, raw text or a file path
  • Output - an SMD distance, a 0..1 closeness, a verdict, and the statement alignment
  • Use - agentic document conversion and extraction pipelines, where token logits are unavailable and KL divergence cannot be computed
  • Unit - statement-level and position-invariant, with an interpretable transport plan

Theory

A document distance grounded in embeddings and optimal transport, not surface overlap.

  • WMD - Word Mover's Distance (Kusner et al. 2015) casts document similarity as optimal transport between embedded tokens
  • SMD - this project lifts it to statements: segment, embed, transport between the two statement clouds
  • Beyond cosine - whole-document cosine collapses when the same claims sit in a different place or order; statement-level transport is position-invariant
  • Metric - the ground cost √(2 − 2cos) on L2-normalized embeddings is a metric, so the document distance is one too
  • Logit-free - an embedding-grounded alternative where token probabilities (KL divergence) are unavailable, as in frontier-model pipelines

Method

Three stages; the transport plan is the interpretable by-product.

  1. Segment - split each document into atomic statements with the SAT (Segment Any Text) segmenter
  2. Embed - encode each statement with the mmBERT contextual encoder (mean-pooled, L2-normalized)
  3. Compare - optimal transport between the two statement clouds (Statement Mover's Distance), optionally unbalanced so added or missing statements are scored, not force-matched
  • Closeness - 1 − SMD/√2, on a 0..1 scale
  • Source-conditioned - a variant d(A, B | S) re-bases the transport onto a shared source S and reads off a selection axis and a grounding axis

Which distance

Both compare two documents; they differ in what the answer tells you and what you must supply.

  • Method 1 - symmetric distance (robust, fast) - answers how far apart are A and B? as one number (a 0..1 closeness plus a similar / not-similar verdict). Sub-millisecond, needs only the two documents, and is a true metric - the distance is symmetric and obeys the triangle inequality, so the numbers are consistent enough to threshold, rank and cache. The production default; use it whenever you need a reliable similarity score - dedup, drift detection, "did this conversion change the meaning?"
  • Method 2 - source-conditioned d(A, B | S) (slower, experimental) - answers why do A and B differ, given a shared source S? You supply S, and instead of one number it returns two axes: a selection axis (did A and B pick different parts of the source?) and a grounding axis (did one drift from the source - dropped content vs unsupported or fabricated content?). It runs a cross-encoder × NLI pass (~seconds on GPU, far slower on CPU). Use it to audit a summary or an extraction against its source, when "how far" is not enough and you need to name the failure
  • Which to pick - default to Method 1 for a similarity number; reach for Method 2 only when you hold the shared source and need to know why two documents derived from it diverge. Method 2's value is interpretation and ordering the failure modes correctly, not a higher pass rate, and it is validated on a single fixture so far - validate on your own sources first

Usage

The quickest way to a result is the CLI - install once, then run it.

pip install docdistance                        # from PyPI
docdistance install                            # download + cache the models (once)
docdistance --help                             # full reference (or <command> --help)

# method 1 - symmetric distance (robust, fast, the default)
docdistance distance a.md b.md                 # rich verdict (add --json for machine-readable)
docdistance distance a.md b.md --transport-map-json map.json   # + statement → statement map

# method 2 - source-conditioned d(A,B|S) (slower, experimental)
docdistance distance-wrt-source a.md b.md --source s.md                       # two-axis verdict
docdistance distance-wrt-source a.md b.md -s s.md --source-map-json map.json   # + statement → source map

Or from Python:

from docdistance import document_distance, source_conditioned_distance

r = document_distance("report_v1.md", "report_v2.md")           # method 1
print(r.closeness, r.verdict)               # 0..1 closeness, "similar" | "not similar"

s = source_conditioned_distance("sum_a.md", "sum_b.md", source="article.md")  # method 2
print(s.d_sel, s.residual_a, s.residual_b)  # selection divergence + each doc's distance to S

Reading the result

  • Method 1 - closeness 0..1 - 1.0 identical, 0.0 unrelated. Good (same meaning): closeness near 1, verdict similar (default cutoff 0.725, set with --threshold). Bad (meaning changed): closeness falls toward 0, verdict flips to not similar

  • Method 2 - two distances, lower is closer - d_sel near 0 means A and B drew on the same source content, high means they picked different parts; a low residual means a document stays grounded in S, a high one flags drift (dropped or unsupported content). Good: both residuals and d_sel low. Bad: a residual spikes for the document that drifted

  • Transport map - add --transport-map-json map.json to distance to also write the optimal-transport map: for every statement of A, which statements of B its mass flows to, with the weight (fraction of that statement's mass) and the match cost - the interpretable statement-to-statement alignment behind the distance, readable by a human or a machine (the same map is returned in Python by DocDistance.distance_with_map)

  • Source map - add --source-map-json map.json to distance-wrt-source to also write, for every statement of A and B, the top-3 source statements it covers with their weights - a per-statement alignment showing which part of the source each statement draws on

  • Offline after install - distance calls run fully offline once the models are cached

  • Backend - --backend openvino|torch, default openvino (CPU INT8)

  • Full reference - the CLI reference and the API reference

Documentation

The SOTA documents explain how it works in detail; this README only introduces it.

Note: Scaffolded with the copier-data-science template.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

docdistance-1.0.17.tar.gz (28.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

docdistance-1.0.17-py3-none-any.whl (25.1 kB view details)

Uploaded Python 3

File details

Details for the file docdistance-1.0.17.tar.gz.

File metadata

  • Download URL: docdistance-1.0.17.tar.gz
  • Upload date:
  • Size: 28.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.14

File hashes

Hashes for docdistance-1.0.17.tar.gz
Algorithm Hash digest
SHA256 fd8ebf4be250348b41f1aea79890e485d00b13a548d7beb21e66deea8022a282
MD5 af9254659cb34db0b131f35a8dabd0fb
BLAKE2b-256 2d85b20a988e55c101c2f88d324e6eaa96d81fcc685f2845ab4eb6db49e9fa3d

See more details on using hashes here.

File details

Details for the file docdistance-1.0.17-py3-none-any.whl.

File metadata

  • Download URL: docdistance-1.0.17-py3-none-any.whl
  • Upload date:
  • Size: 25.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.14

File hashes

Hashes for docdistance-1.0.17-py3-none-any.whl
Algorithm Hash digest
SHA256 18baa12be3a12ce476dd2260c2981069921d0ab6e684426aa0897cdfb6386398
MD5 0cd801d2a6c0ae2fc4af5f4c6d48f01d
BLAKE2b-256 ecb1a34e5c787262828a80e5e42de39455afbb704fe4e692fac6ae9cda83d410

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page