Skip to main content

PyPI version GitHub

Granuscore

Granuscore is a Python library for measuring the semantic granularity of natural language text.

It provides an end-to-end pipeline that:

  1. splits text into referential units,
  2. assigns continuous granularity scores to each unit,
  3. aggregates these scores into document-level estimates.

Granuscore is designed for analyzing how fine-grained or coarse-grained textual expressions are in applications such as question answering, educational dialogue, summarization, and scientific writing.


Installation

Requires Python 3.10–3.12. See the release notes for changes in version 1.1.0.

On minimal Debian/Ubuntu installations, install the OpenMP runtime required by LightGBM: apt-get install libgomp1.

Install from PyPI:

pip install granuscore

Or install the latest development version locally:

git clone https://github.com/lukasellinger/granuscore.git
cd granuscore
pip install -e .

Optional development dependencies:

pip install -e ".[dev]"

Quick Start

from granuscore import GranuScore

scorer = GranuScore()

text = """
Tony Hawk was born in San Diego.
"""

score = scorer(text)

print(score)

By default, Granuscore returns percentile scores, where higher values correspond to coarser-grained expressions.


Default Configuration

The default configuration reproduces the setup used in the paper.

scorer = GranuScore()

Equivalent to:

scorer = GranuScore(
    predictor_type="hit",
)

Default settings:

  • predictor_type="hit"
  • model_name="Hierarchy-Transformers/HiT-MiniLM-L12-WordNetNoun"
  • search_method="random_anchors"
  • random_anchors_k=999

The anchor vectors, LightGBM model, and reference percentile distribution are automatically downloaded and cached on first use. Default scoring does not require or import FAISS, and does not load a FAISS index.

For the optional nearest_neighbor and random search methods, install FAISS:

pip install "granuscore[faiss]"

Reuse a GranuScore instance when scoring multiple batches so its models, normalized anchors, and sorted percentile reference are loaded only once. The granuscore(texts) convenience function creates a new instance per call.


Important Compatibility Note

The default configuration works out of the box and is the recommended setup.

If you customize components such as:

  • the embedding model,
  • search method,
  • FAISS index,
  • anchor vectors,
  • or LightGBM model,

you must ensure that all resources are compatible with each other.

For example, a LightGBM model trained using:

search_method="random_anchors"

should not be combined with:

search_method="nearest_neighbor"

Similarly, FAISS indices, anchor vectors, percentile reference distributions, and LightGBM models must originate from the same embedding space and training configuration.

Compatibility between custom resources is not validated automatically.


Notebook Tutorial

An interactive introduction is available in:

notebooks/getting_started.ipynb

Repository Structure

granuscore/
├── src/
│   └── granuscore/
│       ├── pipeline.py
│       ├── granularity_predictor.py
│       ├── claim_splitter.py
│       ├── bucket_output.py
│       ├── cache.py
│       └── artifacts.py
├── notebooks/
│   ├── build_granola_dataset.ipynb
│   └── getting_started.ipynb
├── training_scripts/
├── evaluation/
├── assets/
├── data/ (needs to be externally downloaded)
├── pyproject.toml
├── LICENSE
└── README.md

Reproducing Paper Experiments

The datasets and precomputed resources required to reproduce the experiments from the paper are available here:

https://drive.google.com/drive/folders/1mJdUENOxHEiuYn-_f1KRQ1PZggXJDnb4?usp=sharing

Download the archive and extract it into the repository root:

unzip data.zip

This will create the expected directory structure used by the training and evaluation scripts.



GRANOLA Dataset Construction

We use a processed version of the GRANOLA-EQ Dataset introduced by Yona et al. (2024). Due to licensing restrictions of upstream resources, the processed dataset version used in this work is not redistributed directly in this repository or on external hosting platforms.

Instead, the dataset can be reconstructed locally using the notebook:

notebooks/build_granola_dataset.ipynb

Training Pipeline

Training uses precomputed .pkl feature files.

  1. Generate precomputed datasets:
training_scripts/build_precalc_data/
  1. Train LightGBM models:
python training_scripts/train_lgb_models.py

Inference checks

Run the regression tests from a development checkout:

PYTHONPATH=src python -m unittest discover -s tests -v

Compare the original and optimized anchor search, uncached scoring (including embedding), and percentile conversion:

PYTHONPATH=src python benchmarks/inference.py --offline

The benchmark uses cached default models and checks identical features, raw scores, and percentiles. Omit --offline to allow model downloads.

Compare the embedding and hyperbolic-distance changes against their previous implementation, using the same models and alternating execution order:

PYTHONPATH=src python benchmarks/compute.py --offline \
  --input path/to/records.jsonl --field predicted_answer --limit 64 \
  --output /tmp/granuscore-compute.json

This checks exact equality of embeddings, features, raw scores, and final scores. Accelerator embedding conversion uses a single tensor transfer while retaining the encoder's batch size and precision. CPU encoding avoids an extra float32 array copy. On CPU, distance computation broadcasts cached anchors and bounds intermediate array sizes, then sorts the resulting distances. MPS also shares cached anchors and sorts the distance matrix; its encoder batching and full query-distance batches are retained. CUDA retains the previous distance layout. All paths use the same manifold formula. Fixed CPU anchor operations are constant-folded from Geoopt's existing scripted distance function, with numerical rewrites disabled. Unsupported compiler or manifold configurations use the regular implementation.

Use --baseline previous-pass to isolate the latest constant folding from the preceding optimization pass.

Select an embedding/feature device explicitly with GranuScore(device="cpu"), GranuScore(device="cuda"), or GranuScore(device="mps"). Omitting device keeps automatic selection. Score caches are scoped by the resolved device, including automatic selection, so CPU and MPS results cannot mix.

Measure encoder batch sizes on the hardware and inputs you actually use:

PYTHONPATH=src python benchmarks/batch_sizes.py --offline --device cpu \
  --input path/to/records.jsonl --field predicted_answer --limit 64 \
  --batch-sizes 16 32 64 128 --output /tmp/granuscore-batches.json

Use --device mps for Metal. If MPS is built but reported unavailable inside a sandbox, run the benchmark in a normal terminal with GPU access. To compare the MPS anchor layout against its previous implementation, use benchmarks/compute.py --device mps --baseline mps-layout with the same input options. Splitting runs every call.

Use --device cuda on an NVIDIA GPU. CUDA benchmarks warm Geoopt's scripted distance kernels before comparing features: the original implementation also changes features during TorchScript warm-up. The CUDA regression tests check cold execution in separate fresh processes as well as warmed feature equality.

The report includes changed embeddings and raw scores, not just latency. It does not change the production batch size of 32: a larger batch can change raw scores, and a match on one sample does not establish equality on future inputs or other devices.

Exact comparisons are against the original calculation on the same device. CPU and MPS can already produce different scores at batch size 32; use a fixed device when exact reproducibility is required.

Profile the full default pipeline, including spaCy, with isolated score caches:

PYTHONPATH=src python benchmarks/profile_pipeline.py --offline \
  --output /tmp/granuscore-profile.json --cprofile /tmp/granuscore-profile.prof

Use --input path/to/records.jsonl --field predicted_answer --limit 128 to profile your own inputs (JSON arrays are also supported). The profiler reports uncached, cold-cache, and warm-cache timings, with model loading timed separately. Cold-cache measurements clear the unit-score cache. Uncached measurements disable it; warm-cache measurements populate it before timing. Splitting runs every time. The built-in sample repeats eight passages; use representative inputs when assessing cache performance.

The default spaCy splitter batches document and sentence parsing with nlp.pipe, disables entity recognition and lemmatization, and retains independent sentence parses to preserve noun-phrase extraction. To adjust spaCy's batch size:

from granuscore.claim_splitter import SpacyNounPhraseSplitter

scorer = GranuScore(claim_splitter=SpacyNounPhraseSplitter(batch_size=64))

There is no full-text, sentence-splitting, or final-document-score cache. The original SQLite cache stores scores for referential units; disable it with GranuScore(use_cache=False). When split=False, the provided strings themselves are the units. Earlier measurements in refinements_cpu.json that included a split-batch cache are historical and do not describe the current configuration. Cache misses retain their original order and repetitions, because deduplicating them changes encoder batch composition and can change scores. The cache namespace separates this behavior from the earlier experimental deduplicated batches.

For a complete beginning-to-current comparison, load the original scoring code from Git and compare it with the current implementation on the same device:

PYTHONPATH=src python benchmarks/from_start.py --offline --ref 2c4979e \
  --input path/to/records.jsonl --field predicted_answer --limit 64 \
  --repeats 3 --output /tmp/granuscore-from-start.json

This excludes imports and model loading and measures uncached, fresh unit-cache, and warmed unit-cache calls. Both variants share identical preloaded weights; the original unused FAISS import is omitted to avoid its native runtime conflict.

On macOS, the optional FAISS and PyTorch wheels can load conflicting OpenMP runtimes and abort Python. Default scoring avoids this conflict by leaving FAISS unloaded. The native FAISS integration test is opt-in on macOS (GRANUSCORE_TEST_FAISS=1) for environments with compatible builds.


Citation

@inproceedings{ellinger-2026-granuscore,
    title = "Granuscore: A Reference-Free Measure of Granularity for Text Analysis and Question Answering",
    author = {Ellinger, Lukas  and
      Fichtl, Alexander M.  and
      Ansch{\"u}tz, Miriam  and
      Groh, Georg},
    editor = "Lee, Hung-Yi  and
      Dev, Sunipa  and
      Li, Jessy  and
      Elliott, Desmond",
    booktitle = "Proceedings of the 2026 Conference on Empirical Methods in Natural Language Processing",
    month = oct,
    year = "2026",
    address = "Budapest, Hungary",
    publisher = "Association for Computational Linguistics",
    url = "https://aclanthology.org/2026.emnlp-main.16/",
    pages = "373--390",
    ISBN = "979-8-89176-459-0"
}

Metadata

Release files for granuscore 1.1.0

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

Source distribution (sdist)

Source distribution for granuscore 1.1.0
File Size Uploaded Provenance Actions
granuscore-1.1.0.tar.gz 48.0 kB Without provenance Details for granuscore-1.1.0.tar.gz

Built distribution (wheel)

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

Total release size: 80.3 kB

Release files / granuscore-1.1.0.tar.gz

Download URL granuscore-1.1.0.tar.gz
Size 48.0 kB
Tags Source
SHA-256 checksum
How to use checksums
433cce3e8c473e790f1c6271bd60cccdedc141cfa37afd8dc7bdc340eb904936
BLAKE2b-256 checksum
How to use checksums
9057a5c20af3246eca49844fa06092987c7621a540dd65e25beffe351d0d83e5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.6

Release files / granuscore-1.1.0-py3-none-any.whl

Download URL granuscore-1.1.0-py3-none-any.whl
Size 32.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
19129e4a1138437949f254efa6653f456b073356d20982faf8f18fbe9a486034
BLAKE2b-256 checksum
How to use checksums
4cc472a3aed3018a55227e17f4404a07d9a24f0aa2c00a295e25f31c7c8a3796
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.6

Security for granuscore 1.1.0

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