ef.ablation¶
Embedder ablations on a graded benchmark: run named arms over one corpus.
An ablation asks “which change to the embedder moved the metric?”. Each arm
is one embedding configuration (a query-side embedder, optionally a different
document-side one); every arm ranks the same segmented corpus for the same
queries and is scored by evaluate_retrieval(), so the only
thing that varies is the embedder.
Simple use, an A/B over any two embedders:
bench = read_graded_cases("cases.jsonl", "named_sets.json")
report = run_arms(corpus, {"A": Arm(emb_a), "B": Arm(emb_b)}, bench)
print(report)
The instruction-embedding experiment of ef#34 is one instance:
instruction_arms() builds its four arms (A: plain model, B: plain model +
instruction, the control, C: instruction-tuned model + instruction, C’: the same
model without it) and instruction_verdict() checks its success line.
Ranking is dense and document-level: every segment is embedded once per
document-side embedder (input_type="document"), a query is embedded with
the arm’s embedder (input_type="query"), and a document scores the best
cosine of any of its segments (max-pooling). Arms that share a document-side
embedder share its vectors: pass doc_vectors (any MutableMapping, e.g. a
dol store) to keep them across calls too. Only the query side differs between
an instructed arm and its bare twin, so the corpus is embedded once per model.
The labels format read_graded_cases() reads is the one ir.eval writes:
a JSONL of {"artifact_id", "labels": {theme: level}} cases with an optional
{"__meta__": {"probes": {theme: query}}} header, plus an optional
{theme: {"distractors": [...], "hard_positives": [...]}} JSON of named sets.
Module Attributes
Graded level -> relevance. |
|
The topical instruction for the instruction-tuned arm, in Qwen3-Embedding's format ( |
Functions
|
The four arms of the instruction experiment (A, B, C, C'). |
|
Check ef#34's success line from |
|
Load an |
|
Score every arm on the same segmented corpus; one row per arm. |
|
|
Classes
|
One embedding configuration: |
|
Queries, graded qrels and the named diagnostic sets, keyed by query id. |
|
Rank documents by the best cosine of any of their segments to the query. |
- class ef.ablation.Arm(embedder, doc_embedder=None)[source]¶
Bases:
objectOne embedding configuration:
embedderfor queries,doc_embedderfor documents.doc_embedderdefaults toembedder. Give an instructed arm its bare twin asdoc_embedderwhen the instruction is query-side only, so the corpus vectors are shared rather than recomputed. Either may be anythingef.as_embedder()accepts (anEmbedder, a spec string, a callable).
- ef.ablation.DFLT_GRADES: Mapping[str, float] = {'core': 2.0, 'strong': 1.0}¶
Graded level -> relevance. Levels absent here count as not relevant, so recall is “core/strong recall”.
- ef.ablation.DFLT_TOPICAL_INSTRUCTION = 'Instruct: Given a topic, retrieve software packages whose main purpose is that topic, not packages that only mention related words\nQuery:'¶
The topical instruction for the instruction-tuned arm, in Qwen3-Embedding’s format (
Instruct: <task>\nQuery:with the query appended directly; E5-instruct wantsQuery: `` with a space, so pass ``instruction=there). It asks for what a document is about, which a plain model confuses with surface keywords.
- class ef.ablation.GradedBenchmark(qrels, queries, distractors=dict(), hard_positives=dict())[source]¶
Bases:
objectQueries, graded qrels and the named diagnostic sets, keyed by query id.
>>> b = GradedBenchmark(qrels={'t': {'d1': 2.0, 'd9': 1.0}}, queries={'t': 'x'}, ... distractors={'t': ('d2', 'd8')}) >>> b.restrict(['d1', 'd2']).qrels, b.restrict(['d1', 'd2']).distractors ({'t': {'d1': 2.0}}, {'t': ('d2',)})
- class ef.ablation.MaxPoolRetriever(doc_ids, vectors, query_embedder)[source]¶
Bases:
objectRank documents by the best cosine of any of their segments to the query.
>>> from ef.embedders import HashingEmbedder >>> emb = HashingEmbedder() >>> segs = {'fruit': ['red apple', 'ripe pear'], 'car': ['blue car engine']} >>> r = MaxPoolRetriever.from_segments(segs, emb) >>> r('apple', limit=1) ['fruit']
- ef.ablation.instruction_arms(base, tuned=None, *, instruction='Instruct: Given a topic, retrieve software packages whose main purpose is that topic, not packages that only mention related words\nQuery:', base_instruction=None)[source]¶
The four arms of the instruction experiment (A, B, C, C’).
A:baseas is (the plain baseline);B:basewith the instruction on queries: the control, expected to move little, since a plain model was not trained to read instructions;C:tuned(an instruction-tuned model) with the instruction;C':tunedwithout it, attributing C’s gain to the instruction rather than to the bigger model.
Instructions are query-side only (documents bare), so each model embeds the corpus once.
base/tunedare embedders oref.as_embedder()specs; withouttunedonly A and B are built.- Parameters:
- Return type:
>>> from ef.embedders import HashingEmbedder >>> sorted(instruction_arms(HashingEmbedder(), HashingEmbedder())) ['A', 'B', 'C', "C'"]
- ef.ablation.instruction_verdict(metrics, *, k=20, fp_cut=0.5, control_tolerance=0.02, control_metrics=('ndcg', 'recall', 'fp_rate'))[source]¶
Check ef#34’s success line from
{arm: {"fp_rate@20": ..., ...}}.Success = C cuts the named-distractor
fp_rate@kby at leastfp_cut(relative) vs A, at equal-or-betterrecall@k(core/strong recall), and the control B moves everycontrol_metricsatkby less thancontrol_tolerance(absolute; 0.02 = 2 points). Also reports whether C beats its bare twin C’ onfp_rate@k(the gain is the instruction’s). If A has no distractor in its topkthere is nothing to cut:fp_baseline_zerois set and the verdict is not a success.- Raises:
ValueError – when an arm (A, B, C) or one of its metrics at
kis missing.- Return type:
Accepts
BenchmarkReport.rowsturned into a mapping, e.g.{r['embedder']: r for r in report.rows}.>>> m = {'A': {'fp_rate@20': .2, 'recall@20': .4, 'ndcg@20': .7}, ... 'B': {'fp_rate@20': .2, 'recall@20': .41, 'ndcg@20': .7}, ... 'C': {'fp_rate@20': .05, 'recall@20': .5, 'ndcg@20': .8}, ... "C'": {'fp_rate@20': .15, 'recall@20': .45, 'ndcg@20': .75}} >>> v = instruction_verdict(m) >>> v['success'], round(v['fp_reduction'], 2), v['instruction_beats_bare'] (True, 0.75, True)
- ef.ablation.read_graded_cases(cases_path, named_sets_path=None, *, grades={'core': 2.0, 'strong': 1.0}, probes=None)[source]¶
Load an
ir.eval-style graded case file (and named sets) as a benchmark.Each theme is one query: its text comes from
probesor, failing that, the__meta__header’sprobes; its qrels are the cases whose level for that theme is ingrades. A theme with no such case is left out.- Parameters:
cases_path (
str|Path) – JSONL of{"artifact_id", "labels": {theme: level}}.named_sets_path (
str|Path|None) – optional JSON{theme: {"distractors", "hard_positives"}}.grades (
Mapping[str,float]) – level -> relevance grade; other levels are not relevant.probes (
Mapping[str,str] |None) –{theme: query text}, overriding the header’s.
- Raises:
ValueError – when a labelled theme has no query text.
- Return type:
- ef.ablation.run_arms(corpus, arms, benchmark, *, k_values=(10, 20), segmenter=None, doc_vectors=None)[source]¶
Score every arm on the same segmented corpus; one row per arm.
- Parameters:
corpus (
Mapping[str,str|Sequence[str]]) –{doc_id: text}(segmented withsegmenter) or{doc_id: [segment, ...]}(used as is).arms (
Mapping[str,Arm|Any]) –{name: Arm}; a bare embedder is taken asArm(embedder).benchmark (
GradedBenchmark) – what to score against (read_graded_cases()).segmenter (
Any) – for string documents; seesegment_corpus().doc_vectors (
MutableMapping[str,ndarray] |None) – cache of segment matrices keyed by"<document-side model_id>/<digest of the segmented corpus>", so a persistent store (e.g. adolstore) can be reused across runs and corpora. A fresh dict by default; embedders without amodel_idare never cached.
- Return type:
>>> from ef.embedders import HashingEmbedder >>> bench = GradedBenchmark({'q': {'fruit': 1.0}}, {'q': 'apple'}) >>> rep = run_arms({'fruit': 'red apple', 'car': 'blue car'}, ... {'A': HashingEmbedder()}, bench, k_values=(1,)) >>> rep.rows[0]['embedder'], rep.rows[0]['recall@1'] ('A', 1.0)
- ef.ablation.segment_corpus(corpus, *, segmenter=None)[source]¶
{doc_id: [segment text, ...]}: strings are segmented, sequences kept.segmenteris anythingef.as_segmenter()accepts (default: the recursive character splitter). Empty segments are dropped; a document left with none is represented by its id, so it stays rankable.>>> segment_corpus({'a': ['x', ''], 'b': ''}) {'a': ['x'], 'b': ['b']}