Repository navigation
feat(atlas): evaluate scoped session co-occurrence candidates offline #13600
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+220
−5
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| { | ||
| "schema": "atlas-recommendation-eval/v1", | ||
| "subject": "reader", | ||
| "cutoff": 10, | ||
| "eligible_sessions": ["early-a", "early-b", "test", "no-overlap"], | ||
| "eligible_items": ["anchor", "bridge", "companion", "novel"], | ||
| "sessions": [ | ||
| {"subject": "reader", "id": "early-a", "start": 1, "end": 4, "opens": ["anchor", "bridge", "bridge"]}, | ||
| {"subject": "reader", "id": "early-b", "start": 5, "end": 10, "opens": ["anchor", "companion"]}, | ||
| {"subject": "reader", "id": "test", "start": 11, "end": 12, "opens": ["anchor", "bridge"]}, | ||
| {"subject": "reader", "id": "no-overlap", "start": 13, "end": 14, "opens": ["novel", "companion"]} | ||
| ] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| """Offline single-subject item candidates and temporal held-out evaluation.""" | ||
|
|
||
| import argparse | ||
| from collections import Counter, defaultdict | ||
| import json | ||
| from math import log2 | ||
|
|
||
|
|
||
| def reference(value): | ||
| if not isinstance(value, str) or not value.strip(): | ||
| raise ValueError("expected a nonempty opaque reference") | ||
| return value | ||
|
|
||
|
|
||
| def reference_set(values): | ||
| if not isinstance(values, list): | ||
| raise ValueError("expected a reference list") | ||
| return {reference(value) for value in values} | ||
|
|
||
|
|
||
| def partitions(data): | ||
| if data["schema"] != "atlas-recommendation-eval/v1": | ||
| raise ValueError("unsupported evaluation schema") | ||
| subject = reference(data["subject"]) | ||
| allowed_sessions = reference_set(data["eligible_sessions"]) | ||
| allowed_items = reference_set(data["eligible_items"]) | ||
| cutoff = data["cutoff"] | ||
| if type(cutoff) is not int or not isinstance(data["sessions"], list): | ||
| raise ValueError("expected integer cutoff and sessions array") | ||
|
|
||
| train, held_out = [], [] | ||
| seen = set() | ||
| for session in data["sessions"]: | ||
| if session["subject"] != subject or session["id"] not in allowed_sessions: | ||
| continue | ||
| if session["id"] in seen: | ||
| raise ValueError("duplicate scoped session") | ||
| seen.add(session["id"]) | ||
| start, end = session["start"], session["end"] | ||
| if type(start) is not int or type(end) is not int or start > end: | ||
| raise ValueError("invalid session interval") | ||
| if start <= cutoff < end: | ||
| continue | ||
| if not isinstance(session["opens"], list): | ||
| raise ValueError("expected ordered opens") | ||
| opens = dict.fromkeys(item for item in session["opens"] if reference(item) in allowed_items) | ||
| if end <= cutoff: | ||
| train.append(tuple(opens)) | ||
| else: | ||
| held_out.append(tuple(opens)) | ||
| return train, held_out | ||
|
|
||
|
|
||
| def index_sessions(sessions): | ||
| index = defaultdict(list) | ||
| for session in sessions: | ||
| items = frozenset(session) | ||
| for item in items: | ||
| index[item].append(items) | ||
| return index | ||
|
|
||
|
|
||
| def candidates(index, seeds, k): | ||
| """One vote per training session and distinct seed/candidate pair.""" | ||
| scores = Counter() | ||
| seen = set(seeds) | ||
| for seed in seen: | ||
| for session in index.get(seed, ()): | ||
| scores.update(session - seen) | ||
| return sorted(scores, key=lambda item: (-scores[item], item))[:k] | ||
|
|
||
|
|
||
| def evaluate(data, k): | ||
| if type(k) is not int or k <= 0: | ||
| raise ValueError("k must be a positive integer") | ||
| train, held_out = partitions(data) | ||
| index = index_sessions(train) | ||
| scored = hits = relevant = 0 | ||
| reciprocal_ranks = ndcg = 0.0 | ||
| for session in held_out: | ||
| if len(session) < 2: | ||
| continue | ||
| half = len(session) // 2 | ||
| targets = set(session[half:]) | ||
| ranking = candidates(index, session[:half], k) | ||
| ranks = [i for i, item in enumerate(ranking, 1) if item in targets] | ||
| scored += 1 | ||
| hits += len(ranks) | ||
| relevant += len(targets) | ||
| if ranks: | ||
| reciprocal_ranks += 1 / ranks[0] | ||
| dcg = sum(1 / log2(rank + 1) for rank in ranks) | ||
| ideal = sum(1 / log2(rank + 1) for rank in range(1, min(k, len(targets)) + 1)) | ||
| ndcg += dcg / ideal | ||
| return { | ||
| "k": k, "training_sessions": len(train), "held_out_sessions": len(held_out), | ||
| "scored_sessions": scored, "hits": hits, "held_out_items": relevant, | ||
| "precision_at_k": hits / (scored * k) if scored else None, | ||
| "recall_at_k": hits / relevant if relevant else None, | ||
| "mrr_at_k": reciprocal_ranks / scored if scored else None, | ||
| "ndcg_at_k": ndcg / scored if scored else None, | ||
| } | ||
|
|
||
|
|
||
| def main(): | ||
| parser = argparse.ArgumentParser(description=__doc__) | ||
| parser.add_argument("fixture", type=argparse.FileType("r", encoding="utf-8")) | ||
| parser.add_argument("-k", type=int, default=10) | ||
| args = parser.parse_args() | ||
| try: | ||
| with args.fixture as stream: | ||
| result = evaluate(json.load(stream), args.k) | ||
| except (KeyError, ValueError, TypeError) as error: | ||
| parser.exit(2, f"invalid evaluation input ({type(error).__name__})\n") | ||
| print(json.dumps(result, sort_keys=True)) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| """Oracles use explicit session sets, chronological halves and hand-counted pairs.""" | ||
|
|
||
| import json | ||
| from pathlib import Path | ||
| import unittest | ||
|
|
||
| from session_cooccurrence import candidates, evaluate, index_sessions, partitions | ||
|
|
||
|
|
||
| def fixture(): | ||
| path = Path(__file__).with_name("fixtures") / "session-cooccurrence.json" | ||
| return json.loads(path.read_text(encoding="utf-8")) | ||
|
|
||
|
|
||
| class SessionCooccurrenceTests(unittest.TestCase): | ||
| def test_hand_counted_tie_and_cold_start(self): | ||
| report = evaluate(fixture(), 2) | ||
| self.assertEqual(report["scored_sessions"], 2) | ||
| self.assertEqual(report["hits"], 1) | ||
| self.assertEqual(report["held_out_items"], 2) | ||
| self.assertEqual(report["precision_at_k"], 0.25) | ||
| self.assertEqual(report["recall_at_k"], 0.5) | ||
| self.assertEqual(report["mrr_at_k"], 0.5) | ||
| self.assertEqual(report["ndcg_at_k"], 0.5) | ||
|
|
||
| def test_retired_foreign_and_cross_cutoff_cannot_change_candidates_or_metrics(self): | ||
| data = fixture() | ||
| original = evaluate(data, 2) | ||
| data["eligible_sessions"] += ["crossing", "another"] | ||
| for sid, owner, start, end in [ | ||
| ("retired", "reader", 1, 2), | ||
| ("crossing", "reader", 2, 14), | ||
| ("another", "different-reader", 1, 2), | ||
| ]: | ||
| data["sessions"].append(dict(id=sid, subject=owner, start=start, end=end, | ||
| opens=["anchor", "companion", "novel"])) | ||
| for session in data["sessions"]: | ||
| session["opens"].insert(0, "retired-item") | ||
| self.assertEqual(original, evaluate(data, 2)) | ||
| train, _ = partitions(data) | ||
| self.assertEqual(candidates(index_sessions(train), ["anchor"], 3), ["bridge", "companion"]) | ||
|
|
||
| def test_deduplicates_before_scoring_and_splitting(self): | ||
| data = fixture() | ||
| data["sessions"][2]["opens"] = ["anchor", "anchor", "bridge", "anchor"] | ||
| self.assertEqual(evaluate(data, 2), evaluate(fixture(), 2)) | ||
| index = index_sessions([["a", "x", "x", "y"], ["a", "y"], ["b", "x"]]) | ||
| self.assertEqual(candidates(index, ["a", "a"], 2), ["y", "x"]) | ||
| self.assertEqual(candidates(index, ["a", "b"], 2), ["x", "y"]) | ||
|
|
||
| def test_held_out_sessions_never_train_the_graph(self): | ||
| data = fixture() | ||
| data["sessions"] = data["sessions"][2:] | ||
| report = evaluate(data, 2) | ||
| self.assertEqual((report["training_sessions"], report["hits"], report["mrr_at_k"]), (0, 0, 0)) | ||
|
|
||
| def test_empty_scope_and_ambiguous_input(self): | ||
| data = fixture() | ||
| data["eligible_items"] = [] | ||
| self.assertIsNone(evaluate(data, 2)["ndcg_at_k"]) | ||
| data["sessions"].append(data["sessions"][0]) | ||
| with self.assertRaises(ValueError): | ||
| evaluate(data, 2) | ||
| with self.assertRaises(ValueError): | ||
| evaluate(fixture(), 0) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The scope-isolation and duplicate-open tests assert meaningful invariants, but exercise only fixed mutations of one synthetic fixture. Add generated fixtures and mutations checked against these invariants (or a generated reference model) to cover exclusion of foreign, retired, and cross-cutoff sessions and duplicate-open idempotence. The repository testing doctrine requires property/model-based coverage where these invariants exist; the hand-counted examples remain useful smoke coverage but do not replace that requirement.
AGENTS.md reference: AGENTS.md:L37-L39
Useful? React with 👍 / 👎.