embed-ab 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
embed_ab/__init__.py ADDED
@@ -0,0 +1,17 @@
1
+ """embed-ab: A/B-test two embedding models on your own documents."""
2
+
3
+ from embed_ab.compare import CompareResult, compare
4
+ from embed_ab.evalset import EvalSet, EvalSetError, load_evalset
5
+ from embed_ab.providers import ProviderError
6
+
7
+ __version__ = "0.1.0"
8
+
9
+ __all__ = [
10
+ "CompareResult",
11
+ "EvalSet",
12
+ "EvalSetError",
13
+ "ProviderError",
14
+ "__version__",
15
+ "compare",
16
+ "load_evalset",
17
+ ]
embed_ab/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from embed_ab.cli import main
4
+
5
+ sys.exit(main())
embed_ab/bm25.py ADDED
@@ -0,0 +1,55 @@
1
+ """Okapi BM25 in numpy, matching ``rank_bm25.BM25Okapi`` scores (k1=1.5, b=0.75, epsilon=0.25)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import re
7
+ from collections import Counter
8
+ from collections.abc import Sequence
9
+
10
+ import numpy as np
11
+
12
+ TOKENIZERS = ("word", "char2")
13
+
14
+
15
+ def tokenize(text: str, kind: str = "word") -> list[str]:
16
+ """``word``: lower-cased ``\\w+`` tokens. ``char2``: character bigrams inside each word.
17
+
18
+ Character bigrams make Korean particles ("백업을" / "백업은") share the stem bigram "백업".
19
+ """
20
+ words = re.findall(r"\w+", text.lower())
21
+ if kind == "word":
22
+ return words
23
+ if kind != "char2":
24
+ raise ValueError(f"Unknown BM25 tokenizer {kind!r}; choose one of {', '.join(TOKENIZERS)}.")
25
+ out: list[str] = []
26
+ for w in words:
27
+ out.extend([w] if len(w) < 2 else [w[i : i + 2] for i in range(len(w) - 1)])
28
+ return out
29
+
30
+
31
+ class BM25:
32
+ def __init__(self, documents: Sequence[str], tokenizer: str = "word", k1: float = 1.5, b: float = 0.75, epsilon: float = 0.25):
33
+ self.tokenizer = tokenizer
34
+ self.k1, self.b = k1, b
35
+ self.docs = [Counter(tokenize(d, tokenizer)) for d in documents]
36
+ self.lengths = np.array([sum(c.values()) for c in self.docs], dtype=np.float64)
37
+ n = len(self.docs)
38
+ self.avgdl = float(self.lengths.mean()) if n else 0.0
39
+ df: Counter[str] = Counter()
40
+ for c in self.docs:
41
+ df.update(c.keys())
42
+ idf = {t: math.log((n - f + 0.5) / (f + 0.5)) for t, f in df.items()}
43
+ floor = epsilon * (sum(idf.values()) / len(idf) if idf else 0.0)
44
+ self.idf = {t: (v if v >= 0 else floor) for t, v in idf.items()} # rank_bm25 floors negative idf
45
+
46
+ def scores(self, query: str) -> np.ndarray:
47
+ out = np.zeros(len(self.docs))
48
+ norm = self.k1 * (1 - self.b + self.b * self.lengths / (self.avgdl or 1.0))
49
+ for term in tokenize(query, self.tokenizer):
50
+ idf = self.idf.get(term)
51
+ if idf is None:
52
+ continue
53
+ tf = np.array([c.get(term, 0) for c in self.docs], dtype=np.float64)
54
+ out += idf * tf * (self.k1 + 1) / (tf + norm)
55
+ return out
embed_ab/cache.py ADDED
@@ -0,0 +1,58 @@
1
+ """On-disk embedding cache keyed by (provider, model, prompts, text hash)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import os
7
+ import re
8
+ from collections.abc import Callable, Sequence
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+
13
+ MAX_ENTRIES = 100_000 # per model file; oldest entries are dropped beyond this
14
+
15
+
16
+ def _text_key(kind: str, text: str) -> str:
17
+ return kind + ":" + hashlib.blake2b(text.encode("utf-8"), digest_size=16).hexdigest()
18
+
19
+
20
+ class EmbeddingCache:
21
+ """One ``.npz`` file per (spec, prompts) holding text-hash keys and float32 vectors."""
22
+
23
+ def __init__(self, directory: Path, namespace: str):
24
+ slug = re.sub(r"[^A-Za-z0-9._-]+", "_", namespace)[:60]
25
+ digest = hashlib.blake2b(namespace.encode("utf-8"), digest_size=5).hexdigest()
26
+ self.path = directory / f"{slug}-{digest}.npz"
27
+ self._vecs: dict[str, np.ndarray] = {}
28
+ if self.path.is_file():
29
+ try:
30
+ with np.load(self.path, allow_pickle=False) as data:
31
+ for key, vec in zip(data["keys"].tolist(), data["vecs"], strict=True):
32
+ self._vecs[key] = vec
33
+ except (OSError, ValueError, KeyError):
34
+ self._vecs = {} # corrupt cache: start over rather than fail the run
35
+
36
+ def embed(
37
+ self, kind: str, texts: Sequence[str], fn: Callable[[Sequence[str]], np.ndarray]
38
+ ) -> tuple[np.ndarray, int, int]:
39
+ """Return (matrix, hits, misses); only missing texts are sent to ``fn``."""
40
+ keys = [_text_key(kind, t) for t in texts]
41
+ missing = [i for i, k in enumerate(keys) if k not in self._vecs]
42
+ if missing:
43
+ fresh = fn([texts[i] for i in missing])
44
+ for i, vec in zip(missing, fresh, strict=True):
45
+ self._vecs[keys[i]] = np.asarray(vec, dtype=np.float32)
46
+ self._save()
47
+ if not texts:
48
+ return np.zeros((0, 1), dtype=np.float32), 0, 0
49
+ matrix = np.stack([self._vecs[k] for k in keys])
50
+ return matrix, len(texts) - len(missing), len(missing)
51
+
52
+ def _save(self) -> None:
53
+ items = list(self._vecs.items())[-MAX_ENTRIES:]
54
+ self._vecs = dict(items)
55
+ self.path.parent.mkdir(parents=True, exist_ok=True)
56
+ tmp = self.path.with_name(self.path.stem + ".tmp.npz")
57
+ np.savez(tmp, keys=np.array([k for k, _ in items]), vecs=np.stack([v for _, v in items]))
58
+ os.replace(tmp, self.path)
embed_ab/checks.py ADDED
@@ -0,0 +1,61 @@
1
+ """Warnings that tell you when a comparison cannot be trusted."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ MIN_QUERIES = 30
8
+ CEILING_MEAN = 0.95
9
+ CEILING_TIE_SHARE = 0.8
10
+ COPY_THRESHOLD = 0.6
11
+ COPY_SHARE_WARN = 0.3
12
+ CHARS_PER_TOKEN = 3 # rough lower bound used only to flag likely truncation
13
+
14
+
15
+ def run_checks(
16
+ *,
17
+ n_queries: int,
18
+ mean_a: float,
19
+ mean_b: float,
20
+ tie_share: float,
21
+ ci: tuple[float, float],
22
+ copy_share: float,
23
+ max_chunk_chars: int,
24
+ max_seq_lengths: dict[str, int | None] | None = None,
25
+ metric: str = "ndcg",
26
+ ) -> list[dict[str, Any]]:
27
+ """Return warnings as ``{"code", "message"}`` dicts (empty list = nothing suspicious)."""
28
+ out: list[dict[str, Any]] = []
29
+ if n_queries < MIN_QUERIES:
30
+ out.append({
31
+ "code": "few_queries",
32
+ "message": f"Only {n_queries} queries (< {MIN_QUERIES}): differences are easy to over-read. "
33
+ "Add more queries, ideally some hard ones.",
34
+ })
35
+ if (mean_a >= CEILING_MEAN and mean_b >= CEILING_MEAN) or tie_share >= CEILING_TIE_SHARE:
36
+ out.append({
37
+ "code": "ceiling",
38
+ "message": f"Score ceiling: both systems are near perfect or {tie_share:.0%} of queries tie on {metric}. "
39
+ "This evaluation set is too easy to tell the models apart.",
40
+ })
41
+ lo, hi = ci
42
+ if lo <= 0 <= hi:
43
+ out.append({
44
+ "code": "not_significant",
45
+ "message": f"The 95% confidence interval [{lo:+.3f}, {hi:+.3f}] of the {metric} difference includes 0: "
46
+ "the difference may be noise.",
47
+ })
48
+ if copy_share >= COPY_SHARE_WARN:
49
+ out.append({
50
+ "code": "copied_queries",
51
+ "message": f"{copy_share:.0%} of queries reuse >= {COPY_THRESHOLD:.0%} of their answer chunk's words. "
52
+ "Lexical overlap favours BM25 and word-level models; mix in real user questions.",
53
+ })
54
+ for spec, limit in (max_seq_lengths or {}).items():
55
+ if limit and max_chunk_chars > limit * CHARS_PER_TOKEN:
56
+ out.append({
57
+ "code": "chunk_truncation",
58
+ "message": f"{spec} reads at most {limit} tokens (~{limit * CHARS_PER_TOKEN} characters) but the "
59
+ f"longest chunk has {max_chunk_chars} characters: the tail is ignored. Use smaller chunks.",
60
+ })
61
+ return out
embed_ab/chunking.py ADDED
@@ -0,0 +1,88 @@
1
+ """Turn a folder of documents into chunks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ from embed_ab.evalset import EvalSetError
11
+
12
+ TEXT_SUFFIXES = {".md", ".txt"}
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Chunk:
17
+ id: str
18
+ text: str
19
+
20
+
21
+ def _split_long(paragraph: str, limit: int) -> list[str]:
22
+ """Split an over-long paragraph on sentence ends, then on hard windows."""
23
+ pieces = [s.strip() for s in re.split(r"(?<=[.!?。])\s+", paragraph) if s.strip()]
24
+ out: list[str] = []
25
+ for piece in pieces:
26
+ while len(piece) > limit:
27
+ out.append(piece[:limit])
28
+ piece = piece[limit:]
29
+ out.append(piece)
30
+ return out
31
+
32
+
33
+ def chunk_text(text: str, chunk_chars: int = 600, overlap: int = 0) -> list[str]:
34
+ """Pack paragraphs greedily into chunks of about ``chunk_chars`` characters."""
35
+ if chunk_chars < 1:
36
+ raise EvalSetError("--chunk-chars must be at least 1.")
37
+ if overlap < 0 or overlap >= chunk_chars:
38
+ raise EvalSetError("--overlap must be >= 0 and smaller than --chunk-chars.")
39
+ units: list[str] = []
40
+ for para in re.split(r"\n\s*\n", text):
41
+ para = " ".join(para.split())
42
+ if not para:
43
+ continue
44
+ units.extend(_split_long(para, chunk_chars) if len(para) > chunk_chars else [para])
45
+ chunks: list[str] = []
46
+ current = ""
47
+ for unit in units:
48
+ if current and len(current) + 1 + len(unit) > chunk_chars:
49
+ chunks.append(current)
50
+ current = unit
51
+ else:
52
+ current = f"{current} {unit}".strip()
53
+ if current:
54
+ chunks.append(current)
55
+ if overlap:
56
+ for i in range(len(chunks) - 1, 0, -1):
57
+ tail = chunks[i - 1][-overlap:]
58
+ tail = tail[tail.find(" ") + 1 :] if " " in tail else tail
59
+ chunks[i] = f"{tail} {chunks[i]}"
60
+ return chunks
61
+
62
+
63
+ def chunk_folder(folder: str | Path, chunk_chars: int = 600, overlap: int = 0) -> list[Chunk]:
64
+ """Chunk every ``.md``/``.txt``/``.jsonl`` file under ``folder`` (sorted, deterministic).
65
+
66
+ Chunk ids are ``relative/path.md#0003``. ``.jsonl`` files hold ``{"id", "text"}`` rows.
67
+ """
68
+ root = Path(folder)
69
+ if not root.is_dir():
70
+ raise EvalSetError(f"Documents folder not found: {root}")
71
+ chunks: list[Chunk] = []
72
+ for path in sorted(p for p in root.rglob("*") if p.is_file()):
73
+ rel = path.relative_to(root).as_posix()
74
+ if path.suffix in TEXT_SUFFIXES:
75
+ for i, piece in enumerate(chunk_text(path.read_text(encoding="utf-8"), chunk_chars, overlap)):
76
+ chunks.append(Chunk(f"{rel}#{i:04d}", piece))
77
+ elif path.suffix == ".jsonl":
78
+ for lineno, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
79
+ if not line.strip():
80
+ continue
81
+ try:
82
+ obj = json.loads(line)
83
+ chunks.append(Chunk(str(obj["id"]), str(obj["text"])))
84
+ except (json.JSONDecodeError, KeyError, TypeError) as exc:
85
+ raise EvalSetError(f'{rel} line {lineno}: expected {{"id", "text"}} JSON.') from exc
86
+ if not chunks:
87
+ raise EvalSetError(f"No .md, .txt or .jsonl documents with text found under {root}.")
88
+ return chunks
embed_ab/cli.py ADDED
@@ -0,0 +1,181 @@
1
+ """Command line interface: ``embed-ab demo | build-set | compare``.
2
+
3
+ Exit codes: 0 ok, 1 regression gate failed, 2 input or configuration error.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import re
10
+ import shutil
11
+ import sys
12
+ import time
13
+ from pathlib import Path
14
+
15
+ from embed_ab import __version__
16
+ from embed_ab.chunking import chunk_folder
17
+ from embed_ab.compare import compare, parse_metric_name
18
+ from embed_ab.evalset import EvalSetError, load_evalset, write_evalset
19
+ from embed_ab.paths import cache_subdir
20
+ from embed_ab.providers import ProviderError
21
+ from embed_ab.report import render_text, write_report
22
+ from embed_ab.synth import build_evalset, make_generator
23
+
24
+ DEMO_DIR = Path(__file__).parent / "data" / "demo"
25
+ EXIT_OK, EXIT_REGRESSION, EXIT_INPUT = 0, 1, 2
26
+
27
+
28
+ def _log(msg: str) -> None:
29
+ print(msg, file=sys.stderr, flush=True)
30
+
31
+
32
+ def _fraction(text: str) -> float:
33
+ value = float(text)
34
+ if not 0 <= value <= 1:
35
+ raise argparse.ArgumentTypeError("must be between 0 and 1")
36
+ return value
37
+
38
+
39
+ def _parse_gate(raw: str, k: int) -> tuple[str, float]:
40
+ metric, sep, delta = raw.partition(":")
41
+ if not sep:
42
+ raise EvalSetError(f"--fail-if-worse expects METRIC@K:DELTA such as ndcg@{k}:0.02, got {raw!r}.")
43
+ try:
44
+ threshold = float(delta)
45
+ except ValueError as exc:
46
+ raise EvalSetError(f"--fail-if-worse threshold {delta!r} is not a number (example: ndcg@{k}:0.02).") from exc
47
+ if threshold < 0:
48
+ raise EvalSetError("--fail-if-worse threshold must be >= 0.")
49
+ return parse_metric_name(metric, k), threshold
50
+
51
+
52
+ def _report_paths(args: argparse.Namespace, label: str) -> tuple[Path, Path]:
53
+ stamp = time.strftime("%Y%m%d-%H%M%S")
54
+ default_dir = cache_subdir("reports") / f"{re.sub(r'[^A-Za-z0-9._-]+', '_', label)[:60]}-{stamp}"
55
+ out = Path(args.out) if getattr(args, "out", None) else default_dir
56
+ html = Path(args.report) if getattr(args, "report", None) else out / "report.html"
57
+ js = Path(args.json) if getattr(args, "json", None) else out / "result.json"
58
+ return html, js
59
+
60
+
61
+ def _run_compare(args: argparse.Namespace, evalset, a: str, b: str, gate: tuple[str, float] | None, bm25: str | None) -> int:
62
+ result = compare(
63
+ evalset.subset_queries(args.max_queries), a, b, k=args.k, bm25=bm25, seed=args.seed,
64
+ n_boot=args.bootstrap, use_cache=not args.no_cache,
65
+ a_prompts=(getattr(args, "a_query_prompt", ""), getattr(args, "a_doc_prompt", "")),
66
+ b_prompts=(getattr(args, "b_query_prompt", ""), getattr(args, "b_doc_prompt", "")),
67
+ log=_log,
68
+ )
69
+ data = result.to_dict()
70
+ html_path, json_path = _report_paths(args, f"{a}__vs__{b}")
71
+ write_report(data, html_path, json_path)
72
+ print(render_text(data))
73
+ print(f"\nreport: {html_path}\njson: {json_path}")
74
+ if gate:
75
+ metric, threshold = gate
76
+ d = result.diff(metric)
77
+ failed = d["mean_diff"] < -threshold and d["ci_hi"] < 0
78
+ verdict = "FAIL" if failed else "PASS"
79
+ print(f"gate {metric}: B-A = {d['mean_diff']:+.3f} (95% CI [{d['ci_lo']:+.3f}, {d['ci_hi']:+.3f}]), "
80
+ f"fails when worse than -{threshold} with the whole interval below 0 -> {verdict}")
81
+ return EXIT_REGRESSION if failed else EXIT_OK
82
+ return EXIT_OK
83
+
84
+
85
+ def cmd_demo(args: argparse.Namespace) -> int:
86
+ if args.export:
87
+ dest = Path(args.export)
88
+ if dest.exists() and any(dest.iterdir()):
89
+ raise EvalSetError(f"{dest} is not empty; choose a new folder for --export.")
90
+ shutil.copytree(DEMO_DIR, dest, dirs_exist_ok=True)
91
+ print(f"Demo documents and evaluation set copied to {dest} (docs/ holds the source documents).")
92
+ return EXIT_OK
93
+ print("embed-ab demo: practice mock mode (hashed n-gram embedders; not real model quality).")
94
+ evalset = load_evalset(DEMO_DIR)
95
+ return _run_compare(args, evalset, "mock:char3", "mock:word", None, "word")
96
+
97
+
98
+ def cmd_build_set(args: argparse.Namespace) -> int:
99
+ chunks = chunk_folder(args.docs, args.chunk_chars, args.overlap)
100
+ if args.max_chunks:
101
+ chunks = chunks[: args.max_chunks]
102
+ gen = make_generator(args.llm)
103
+ result = build_evalset(chunks, gen, per_chunk=args.per_chunk, max_copy=args.max_copy,
104
+ max_queries=args.max_queries,
105
+ progress=lambda i, n: _log(f" generating questions {i}/{n}") if i % 10 == 0 or i == n else None)
106
+ out = Path(args.out) if args.out else cache_subdir("evalsets") / f"evalset-{time.strftime('%Y%m%d-%H%M%S')}"
107
+ write_evalset(result.evalset, out)
108
+ es = result.evalset
109
+ print(f"Wrote {len(es.corpus)} chunks, {len(es.queries)} queries to {out}"
110
+ + (f" ({result.dropped} dropped by --max-copy)" if result.dropped else ""))
111
+ for w in result.warnings:
112
+ print(f"WARNING {w}")
113
+ if args.llm == "mock":
114
+ print("NOTE: --llm mock copies chunk wording on purpose (practice mode). Use --llm ollama:<model> for real questions.")
115
+ return EXIT_OK
116
+
117
+
118
+ def cmd_compare(args: argparse.Namespace) -> int:
119
+ gate = _parse_gate(args.fail_if_worse, args.k) if args.fail_if_worse else None # validate before the slow part
120
+ evalset = load_evalset(args.evalset)
121
+ return _run_compare(args, evalset, args.a, args.b, gate, args.bm25)
122
+
123
+
124
+ def build_parser() -> argparse.ArgumentParser:
125
+ p = argparse.ArgumentParser(prog="embed-ab", description="A/B-test embedding models on your own documents.")
126
+ p.add_argument("--version", action="version", version=f"embed-ab {__version__}")
127
+ sub = p.add_subparsers(dest="command", required=True)
128
+
129
+ def common(sp: argparse.ArgumentParser) -> None:
130
+ sp.add_argument("-k", type=int, default=10, help="cut-off for metrics and overlap (default 10)")
131
+ sp.add_argument("--seed", type=int, default=0, help="bootstrap seed (default 0)")
132
+ sp.add_argument("--bootstrap", type=int, default=2000, help="bootstrap resamples (default 2000)")
133
+ sp.add_argument("--max-queries", type=int, default=None, help="use only the first N queries")
134
+ sp.add_argument("--no-cache", action="store_true", help="do not read or write the embedding cache")
135
+ sp.add_argument("--out", help="folder for report.html and result.json (default: cache dir)")
136
+
137
+ d = sub.add_parser("demo", help="offline demo with mock embedders and the built-in evaluation set")
138
+ common(d)
139
+ d.add_argument("--export", metavar="DIR", help="copy the demo documents and evaluation set to DIR and exit")
140
+ d.set_defaults(func=cmd_demo)
141
+
142
+ b = sub.add_parser("build-set", help="documents folder -> corpus.jsonl, queries.jsonl, qrels.tsv")
143
+ b.add_argument("docs", help="folder with .md/.txt/.jsonl files")
144
+ b.add_argument("--out", help="output folder (default: cache dir)")
145
+ b.add_argument("--llm", default="mock", help="question generator: mock or ollama:<model> (default mock)")
146
+ b.add_argument("--per-chunk", type=int, default=1, help="questions per chunk (default 1)")
147
+ b.add_argument("--chunk-chars", type=int, default=600, help="target chunk size in characters (default 600)")
148
+ b.add_argument("--overlap", type=int, default=0, help="characters carried over between chunks (default 0)")
149
+ b.add_argument("--max-copy", type=_fraction, default=None, help="drop questions copying more than this share of chunk words (0-1)")
150
+ b.add_argument("--max-queries", type=int, default=None, help="stop after N questions")
151
+ b.add_argument("--max-chunks", type=int, default=None, help="use only the first N chunks")
152
+ b.set_defaults(func=cmd_build_set)
153
+
154
+ c = sub.add_parser("compare", help="compare model A (baseline) with model B (candidate)")
155
+ c.add_argument("evalset", help="folder with corpus.jsonl, queries.jsonl, qrels.tsv")
156
+ c.add_argument("-a", required=True, help="baseline, e.g. st:sentence-transformers/all-MiniLM-L6-v2")
157
+ c.add_argument("-b", required=True, help="candidate, e.g. ollama:bge-m3 or openai:text-embedding-3-small")
158
+ c.add_argument("--bm25", nargs="?", const="word", default=None, choices=["word", "char2"],
159
+ help="add a BM25 baseline (tokenizer word or char2; default word)")
160
+ c.add_argument("--report", help="path of report.html (default: cache dir)")
161
+ c.add_argument("--json", help="path of result.json (default: cache dir)")
162
+ c.add_argument("--fail-if-worse", metavar="METRIC@K:DELTA",
163
+ help="exit 1 if B is worse than A by more than DELTA and the 95%% interval is below 0")
164
+ for side in ("a", "b"):
165
+ c.add_argument(f"--{side}-query-prompt", default="", help=f"text prepended to queries for model {side.upper()}")
166
+ c.add_argument(f"--{side}-doc-prompt", default="", help=f"text prepended to documents for model {side.upper()}")
167
+ common(c)
168
+ c.set_defaults(func=cmd_compare)
169
+ return p
170
+
171
+
172
+ def main(argv: list[str] | None = None) -> int:
173
+ args = build_parser().parse_args(argv)
174
+ try:
175
+ return args.func(args)
176
+ except (EvalSetError, ProviderError) as exc:
177
+ print(f"error: {exc}", file=sys.stderr)
178
+ return EXIT_INPUT
179
+ except KeyboardInterrupt:
180
+ print("interrupted", file=sys.stderr)
181
+ return 130