Metadata-Version: 2.4
Name: granuscore
Version: 1.1.0
Summary: Granularity scoring for natural language
Author-email: Lukas Ellinger <lukas.ellinger@tum.de>
License-Expression: MIT
Project-URL: Repository, https://github.com/lukasellinger/granuscore
Project-URL: Issues, https://github.com/lukasellinger/granuscore/issues
Keywords: granularity,natural language processing,nlp,text analysis,semantic abstraction,specificity
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Text Processing :: Linguistic
Requires-Python: <3.13,>=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: hierarchy_transformers>=0.1.1
Requires-Dist: lightgbm>=4.6.0
Requires-Dist: spacy>=3.8.11
Requires-Dist: torch>=2.9.1
Requires-Dist: numpy>=1.26.4
Requires-Dist: platformdirs>=3.10.0
Requires-Dist: requests>=2.31.0
Requires-Dist: tqdm>=4.66.0
Requires-Dist: openai>=2.21.0
Provides-Extra: faiss
Requires-Dist: faiss-cpu>=1.13.2; extra == "faiss"
Provides-Extra: dev
Requires-Dist: faiss-cpu>=1.13.2; extra == "dev"
Requires-Dist: optuna>=4.6.0; extra == "dev"
Requires-Dist: pygam>=0.12.0; extra == "dev"
Requires-Dist: python-dotenv>=1.2.1; extra == "dev"
Requires-Dist: ollama>=0.6.1; extra == "dev"
Requires-Dist: google-genai>=1.66.0; extra == "dev"
Requires-Dist: wget>=3.2; extra == "dev"
Dynamic: license-file

[![PyPI version](https://img.shields.io/pypi/v/granuscore.svg)](https://pypi.org/project/granuscore/)
[![GitHub](https://img.shields.io/badge/GitHub-Repository-black)](https://github.com/lukasellinger/granuscore)
# 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](https://github.com/lukasellinger/granuscore/blob/main/CHANGELOG.md)
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:

```bash
pip install granuscore
```

Or install the latest development version locally:

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

Optional development dependencies:

```bash
pip install -e ".[dev]"
```

---

## Quick Start

```python
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.

```python
scorer = GranuScore()
```

Equivalent to:

```python
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:

```bash
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:

```python
search_method="random_anchors"
```

should not be combined with:

```python
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:

```text
notebooks/getting_started.ipynb
```

---

## Repository Structure

```text
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:

```bash
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](https://huggingface.co/datasets/google/granola-entity-questions) introduced by [Yona et al. (2024)](https://aclanthology.org/2024.acl-long.365/). 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:

```text
notebooks/build_granola_dataset.ipynb
```

---

## Training Pipeline

Training uses precomputed `.pkl` feature files.

1. Generate precomputed datasets:

```text
training_scripts/build_precalc_data/
```

2. Train LightGBM models:

```bash
python training_scripts/train_lgb_models.py
```

---

## Inference checks

Run the regression tests from a development checkout:

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

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

```bash
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:

```bash
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:

```bash
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:

```bash
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:

```python
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:

```bash
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

```bibtex
@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"
}
```
