Datasets:
Languages:
English
Size:
1K<n<10K
ArXiv:
Tags:
temporal-reasoning
knowledge-graph
question-answering
benchmark
retrieval-augmented-generation
DOI:
License:
| """ | |
| TempBench Builder | |
| ========================== | |
| Constructs a 10K-question multi-hop temporal QA benchmark (see the TempBench paper). | |
| Implements the full 6-stage pipeline: | |
| 1. Question generation from KG triples and templates | |
| 2. Composability filtering (validate temporal consistency) | |
| 3. Answer uniqueness filtering (discard ambiguous questions) | |
| 4. MinHash deduplication (Jaccard similarity threshold) | |
| 5. Subgraph construction (S_star, S_dist, S_stale) | |
| 6. Train/dev/test split (stratified by complexity) | |
| Output: JSONL benchmark with one question per line, including supporting subgraphs. | |
| Usage: | |
| python build_benchmark.py --kg_path kg.json --output_dir ./benchmark/ --target_n 10000 | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import math | |
| import random | |
| import sys | |
| from collections import defaultdict | |
| from dataclasses import dataclass, asdict | |
| from pathlib import Path | |
| from typing import Dict, List, Optional, Set, Tuple | |
| from indexer import ( | |
| TemporalKGIndexer, | |
| Triple, | |
| ValidityWindow, | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Question generation templates | |
| # --------------------------------------------------------------------------- | |
| QUESTION_TEMPLATES = { | |
| # The TempBench paper cites the TimelineKGQA taxonomy for four operator types. | |
| # Each operator takes a compositional chain "path" (= anchor + hop | |
| # relations, joined by "'s") and attaches an operator-specific temporal | |
| # qualifier. See benchmark-design-decisions.md §1 for semantics. | |
| "point_in_time": [ | |
| "In {year}, what was the {final_relation} of {path}?", | |
| "What was the {final_relation} of {path} in {year}?", | |
| "{path}'s {final_relation} in {year} was?", | |
| ], | |
| "before_after": [ | |
| "Who was the {final_relation} of {path} {qualifier} {sibling}?", | |
| "{qualifier_cap} {sibling}, who was the {final_relation} of {path}?", | |
| ], | |
| "interval": [ | |
| "In what year was the {final_relation} of {path} equal to {terminal}?", | |
| "When was {terminal} the {final_relation} of {path}?", | |
| ], | |
| "sequence": [ | |
| "After {ref_subject} {ref_relation} {ref_object}, what was the {final_relation} of {path}?", | |
| "What was the {final_relation} of {path} after {ref_subject} {ref_relation} {ref_object}?", | |
| ], | |
| } | |
| def _render_composition_path(anchor: str, relations: List[str]) -> str: | |
| """ | |
| Render the nested possessive prefix for compositional multi-hop questions. | |
| Example: | |
| anchor = "Obama", relations = ["spouse", "country"] | |
| returns: "Obama's spouse's country" | |
| Used as the {path} placeholder for the last-but-one hop; the final | |
| relation becomes the {final_relation} placeholder. | |
| """ | |
| parts = [anchor] + relations | |
| return "'s ".join(parts) | |
| # --------------------------------------------------------------------------- | |
| # Data structures | |
| # --------------------------------------------------------------------------- | |
| class Candidate: | |
| """An intermediate candidate question before filtering.""" | |
| id: str | |
| question: str | |
| t_query: float | |
| answer: str | |
| complexity: str # "1hop", "2hop", "3plus" | |
| operator_type: str # "point_in_time", "before_after", "interval", "sequence" | |
| question_type: str # "explicit", "implicit", "ordinal" | |
| gold_chain: List[Triple] | |
| class BenchmarkQuestion: | |
| """A final, fully-validated benchmark question.""" | |
| id: str | |
| question: str | |
| t_query: float | |
| answer: str | |
| complexity: str | |
| operator_type: str | |
| question_type: str | |
| S_star: List[Dict] # Gold chain | |
| S_dist: List[Dict] # Distractor chain | |
| S_stale: List[Dict] # Stale-fact chain | |
| split: str # "train", "dev", "test" | |
| def to_jsonl_dict(self) -> Dict: | |
| """Convert to dict for JSONL serialization.""" | |
| return { | |
| "id": self.id, | |
| "question": self.question, | |
| "t_query": self.t_query, | |
| "answer": self.answer, | |
| "complexity": self.complexity, | |
| "operator_type": self.operator_type, | |
| "question_type": self.question_type, | |
| "S_star": self.S_star, | |
| "S_dist": self.S_dist, | |
| "S_stale": self.S_stale, | |
| "split": self.split, | |
| } | |
| # --------------------------------------------------------------------------- | |
| # Stage 1: Question generation (fallback mode) | |
| # --------------------------------------------------------------------------- | |
| class QuestionGenerator: | |
| """ | |
| Generates candidate questions from KG triples using templates. | |
| Fallback mode when TimelineKGQA is not available. | |
| """ | |
| def __init__(self, indexer: TemporalKGIndexer, seed: int = 42): | |
| self.indexer = indexer | |
| self.rng = random.Random(seed) | |
| self.triples = indexer._all_triples | |
| self.candidate_id_counter = 0 | |
| # Collect all actual timestamps for point-in-time TKGs (t_start == t_end) | |
| self._timestamps: List[float] = sorted( | |
| {t.t_start for t in self.triples} | |
| ) | |
| # tkgl-smallpedia is 100% point-in-time; multi-hop chains need every | |
| # hop at exactly the same year. Pre-index (subject, year) → triples | |
| # so the 2-hop and 3+-hop samplers can forward-chain in O(bucket_size) | |
| # instead of O(entity_degree across all years). | |
| self._subject_year: Dict[str, Dict[float, List[Triple]]] = defaultdict( | |
| lambda: defaultdict(list) | |
| ) | |
| for t in self.triples: | |
| self._subject_year[t.subject][t.t_start].append(t) | |
| self._subjects_with_outgoing: List[str] = list(self._subject_year.keys()) | |
| # --- Public entry point --------------------------------------------- | |
| def generate_candidates( | |
| self, | |
| target_candidates: int = 40000, | |
| min_depth: int = 1, | |
| max_depth: int = 4, | |
| ) -> List[Candidate]: | |
| """ | |
| Generate candidates across the 12-cell matrix (3 complexity levels × | |
| 4 temporal operator types). Target per cell is an even split of the | |
| per-complexity budget (4K/4K/2K per the TempBench paper). | |
| Implementation: sample chains per complexity, and for each chain try | |
| each of the four operator builders. PIT and INT succeed for almost | |
| every chain; BA requires a sibling fact and SEQ requires an earlier | |
| reference triple, so those buckets yield less per chain. | |
| """ | |
| # The TempBench paper commits to 4000 / 4000 / 2000 at target_n = 10000. | |
| # Scale proportionally to target_candidates (= 4 × target_n from the | |
| # BenchmarkBuilder). | |
| per_complexity = { | |
| "1hop": target_candidates // 10, # 40% of target_n | |
| "2hop": target_candidates // 10, # 40% of target_n | |
| "3plus": target_candidates // 20, # 20% of target_n | |
| } | |
| # 3× oversample to absorb Stage 3/4 attrition (uniqueness + dedup). | |
| pool_per_complexity = {k: v * 3 for k, v in per_complexity.items()} | |
| operators = ["point_in_time", "before_after", "interval", "sequence"] | |
| candidates: List[Candidate] = [] | |
| for complexity, pool_target in pool_per_complexity.items(): | |
| sampler = { | |
| "1hop": lambda n: self._sample_1hop_chains(n), | |
| "2hop": lambda n: self._sample_2hop_chains(n), | |
| "3plus": lambda n: self._sample_3plus_chains(n, max_depth), | |
| }[complexity] | |
| # Each chain can produce up to len(operators) candidates, so we | |
| # only need pool_target / len(operators) chains — but many | |
| # BA/SEQ attempts fail, so keep a healthy buffer. | |
| chains = sampler(pool_target // 2) | |
| for chain, t_query in chains: | |
| for op in operators: | |
| cand = self._build_operator_candidate( | |
| op, chain, t_query, complexity | |
| ) | |
| if cand is not None: | |
| candidates.append(cand) | |
| self.rng.shuffle(candidates) | |
| return candidates | |
| # --- Chain samplers (return chain + t_query, no templating) --------- | |
| def _sample_1hop_chains( | |
| self, target_count: int | |
| ) -> List[Tuple[List[Triple], float]]: | |
| chains = [] | |
| sampled = self.rng.sample( | |
| self.triples, min(len(self.triples), target_count) | |
| ) | |
| for t in sampled: | |
| chains.append(([t], t.t_start)) | |
| return chains | |
| def _sample_2hop_chains( | |
| self, target_count: int | |
| ) -> List[Tuple[List[Triple], float]]: | |
| """ | |
| Year-first 2-hop sampler. Pick an anchor subject that has outgoing | |
| facts, pick a year from that subject, then find a second hop from the | |
| pivot at the same year. Much higher success rate than sampling t1 | |
| first and hoping for a matching t2. | |
| """ | |
| chains = [] | |
| attempts = 0 | |
| max_attempts = target_count * 8 | |
| while len(chains) < target_count and attempts < max_attempts: | |
| attempts += 1 | |
| anchor = self.rng.choice(self._subjects_with_outgoing) | |
| year_index = self._subject_year[anchor] | |
| year = self.rng.choice(list(year_index.keys())) | |
| t1_candidates = year_index[year] | |
| t1 = self.rng.choice(t1_candidates) | |
| pivot_year_index = self._subject_year.get(t1.obj) | |
| if pivot_year_index is None: | |
| continue | |
| t2_candidates = [ | |
| t for t in pivot_year_index.get(year, []) | |
| if t.relation != t1.relation | |
| and t.obj != t1.subject # cycle guard | |
| ] | |
| if not t2_candidates: | |
| continue | |
| t2 = self.rng.choice(t2_candidates) | |
| chains.append(([t1, t2], year)) | |
| return chains | |
| def _sample_3plus_chains( | |
| self, target_count: int, max_depth: int | |
| ) -> List[Tuple[List[Triple], float]]: | |
| """ | |
| Year-first 3+-hop sampler. Pick an anchor subject, pick a year that | |
| subject has outgoing facts, walk forward through hops at that year. | |
| Uses the pre-built (subject, year) index for fast forward-chaining. | |
| """ | |
| chains = [] | |
| attempts = 0 | |
| max_attempts = target_count * 15 | |
| while len(chains) < target_count and attempts < max_attempts: | |
| attempts += 1 | |
| anchor = self.rng.choice(self._subjects_with_outgoing) | |
| year_index = self._subject_year[anchor] | |
| year = self.rng.choice(list(year_index.keys())) | |
| depth = self.rng.randint(3, min(max_depth, 4)) | |
| chain: List[Triple] = [] | |
| current = anchor | |
| visited = {current} | |
| for _ in range(depth): | |
| hops = [ | |
| t for t in self._subject_year.get(current, {}).get(year, []) | |
| if t.obj not in visited | |
| ] | |
| if not hops: | |
| break | |
| hop = self.rng.choice(hops) | |
| chain.append(hop) | |
| current = hop.obj | |
| visited.add(current) | |
| if len(chain) < 3: | |
| continue | |
| if any( | |
| chain[i].relation == chain[i - 1].relation | |
| for i in range(1, len(chain)) | |
| ): | |
| continue | |
| window = ValidityWindow.full() | |
| valid = True | |
| for triple in chain: | |
| window = TemporalKGIndexer.compose(window, triple, year) | |
| if window is None or window.is_empty(): | |
| valid = False | |
| break | |
| if not valid: | |
| continue | |
| chains.append((chain, year)) | |
| return chains | |
| # --- Operator builders ---------------------------------------------- | |
| def _build_operator_candidate( | |
| self, | |
| operator: str, | |
| chain: List[Triple], | |
| t_query: float, | |
| complexity: str, | |
| ) -> Optional[Candidate]: | |
| """Dispatch to the right operator builder.""" | |
| dispatch = { | |
| "point_in_time": self._build_pit, | |
| "before_after": self._build_ba, | |
| "interval": self._build_interval, | |
| "sequence": self._build_sequence, | |
| } | |
| return dispatch[operator](chain, t_query, complexity) | |
| def _build_pit( | |
| self, chain: List[Triple], t_query: float, complexity: str | |
| ) -> Optional[Candidate]: | |
| """Point-in-time: "In {year}, what was {path}'s {r_n}?".""" | |
| path = _render_composition_path( | |
| chain[0].subject, [h.relation for h in chain[:-1]] | |
| ) | |
| template = self.rng.choice(QUESTION_TEMPLATES["point_in_time"]) | |
| question = template.format( | |
| path=path, | |
| final_relation=chain[-1].relation, | |
| year=int(t_query), | |
| ) | |
| return self._make_candidate( | |
| question, t_query, chain[-1].obj, chain, complexity, | |
| "point_in_time", "explicit", | |
| ) | |
| def _build_ba( | |
| self, chain: List[Triple], t_query: float, complexity: str | |
| ) -> Optional[Candidate]: | |
| """ | |
| Before/after: same chain as PIT, but the temporal anchor is a sibling | |
| fact (another holder of the terminal relation at a different time). | |
| The candidate is dropped if no such sibling exists. | |
| """ | |
| terminal = chain[-1] | |
| siblings = [ | |
| t for t in self.indexer.entity_index.get(terminal.subject, []) | |
| if t.subject == terminal.subject | |
| and t.relation == terminal.relation | |
| and t.obj != terminal.obj | |
| and t.t_start != t_query | |
| ] | |
| if not siblings: | |
| return None | |
| sibling = self.rng.choice(siblings) | |
| # Qualifier: answer came *before* sibling if t_query < sibling.t_start. | |
| if sibling.t_start > t_query: | |
| qualifier, qualifier_cap = "before", "Before" | |
| else: | |
| qualifier, qualifier_cap = "after", "After" | |
| path = _render_composition_path( | |
| chain[0].subject, [h.relation for h in chain[:-1]] | |
| ) | |
| template = self.rng.choice(QUESTION_TEMPLATES["before_after"]) | |
| question = template.format( | |
| path=path, | |
| final_relation=terminal.relation, | |
| qualifier=qualifier, | |
| qualifier_cap=qualifier_cap, | |
| sibling=sibling.obj, | |
| ) | |
| return self._make_candidate( | |
| question, t_query, terminal.obj, chain, complexity, | |
| "before_after", "ordinal", | |
| ) | |
| def _build_interval( | |
| self, chain: List[Triple], t_query: float, complexity: str | |
| ) -> Optional[Candidate]: | |
| """ | |
| Interval (temporal pinpoint): "In what year was {path}'s {r_n} equal | |
| to {terminal}?". Answer is the query year. Uniqueness of the year | |
| is enforced by a custom check in Stage 3 (AnswerUniquenessFilter). | |
| """ | |
| path = _render_composition_path( | |
| chain[0].subject, [h.relation for h in chain[:-1]] | |
| ) | |
| terminal = chain[-1] | |
| template = self.rng.choice(QUESTION_TEMPLATES["interval"]) | |
| question = template.format( | |
| path=path, | |
| final_relation=terminal.relation, | |
| terminal=terminal.obj, | |
| ) | |
| return self._make_candidate( | |
| question, t_query, str(int(t_query)), chain, complexity, | |
| "interval", "ordinal", | |
| ) | |
| def _build_sequence( | |
| self, chain: List[Triple], t_query: float, complexity: str | |
| ) -> Optional[Candidate]: | |
| """ | |
| Sequence: "After {ref_subject} {ref_rel} {ref_obj}, what was {path}'s | |
| {r_n}?". Reference triple is an earlier fact involving any entity in | |
| the chain (makes the anchor event contextually relevant). | |
| """ | |
| chain_entities = {h.subject for h in chain} | {h.obj for h in chain} | |
| chain_ids = {(h.subject, h.relation, h.obj) for h in chain} | |
| answer_entity = chain[-1].obj | |
| refs = [] | |
| for e in chain_entities: | |
| for t in self.indexer.entity_index.get(e, []): | |
| if ( | |
| t.t_start < t_query | |
| and (t.subject, t.relation, t.obj) not in chain_ids | |
| # The reference must not contain the answer anywhere — | |
| # otherwise the question literally names its own answer. | |
| and t.subject != answer_entity | |
| and t.obj != answer_entity | |
| ): | |
| refs.append(t) | |
| if not refs: | |
| return None | |
| ref = self.rng.choice(refs) | |
| path = _render_composition_path( | |
| chain[0].subject, [h.relation for h in chain[:-1]] | |
| ) | |
| template = self.rng.choice(QUESTION_TEMPLATES["sequence"]) | |
| question = template.format( | |
| path=path, | |
| final_relation=chain[-1].relation, | |
| ref_subject=ref.subject, | |
| ref_relation=ref.relation, | |
| ref_object=ref.obj, | |
| ) | |
| return self._make_candidate( | |
| question, t_query, chain[-1].obj, chain, complexity, | |
| "sequence", "ordinal", | |
| ) | |
| def _make_candidate( | |
| self, | |
| question: str, | |
| t_query: float, | |
| answer: str, | |
| chain: List[Triple], | |
| complexity: str, | |
| operator_type: str, | |
| question_type: str, | |
| ) -> Candidate: | |
| cand = Candidate( | |
| id=f"cand_{self.candidate_id_counter}", | |
| question=question, | |
| t_query=t_query, | |
| answer=answer, | |
| complexity=complexity, | |
| operator_type=operator_type, | |
| question_type=question_type, | |
| gold_chain=chain, | |
| ) | |
| self.candidate_id_counter += 1 | |
| return cand | |
| # --------------------------------------------------------------------------- | |
| # Stage 2: Composability filter | |
| # --------------------------------------------------------------------------- | |
| class ComposabilityFilter: | |
| """Validates temporal consistency of candidate chains.""" | |
| def filter_candidates(candidates: List[Candidate]) -> List[Candidate]: | |
| """ | |
| Discard candidates whose gold chain has empty composed validity window. | |
| Uses the ⊕ operator from ValidityWindow.intersect(). | |
| """ | |
| valid = [] | |
| for cand in candidates: | |
| # Compose all triples in the chain | |
| window = ValidityWindow.full() | |
| is_valid = True | |
| for triple in cand.gold_chain: | |
| window = TemporalKGIndexer.compose(window, triple, cand.t_query) | |
| if window is None or window.is_empty(): | |
| is_valid = False | |
| break | |
| if is_valid: | |
| valid.append(cand) | |
| return valid | |
| # --------------------------------------------------------------------------- | |
| # Stage 3: Answer uniqueness filter | |
| # --------------------------------------------------------------------------- | |
| class AnswerUniquenessFilter: | |
| """Discards ambiguous questions with multiple valid answers at t_query.""" | |
| def __init__(self, indexer: TemporalKGIndexer): | |
| self.indexer = indexer | |
| def filter_candidates(self, candidates: List[Candidate]) -> List[Candidate]: | |
| valid = [c for c in candidates if self._answer_is_unique(c)] | |
| return valid | |
| def _answer_is_unique(self, cand: Candidate) -> bool: | |
| """ | |
| Construction pipeline, Step 4: "removing ambiguous questions with multiple valid | |
| answers at t_q". Scope is terminal-answer only — intermediate fan-out | |
| along the chain is permitted. | |
| Entity-valued operators (PIT, BA, SEQ): the final hop's (subject, | |
| relation) must have exactly one valid object at t_q, and that object | |
| must equal the recorded answer. | |
| Year-valued operator (INT): the specific terminal triple (subject, | |
| relation, object) must be valid at exactly one distinct t in the KG. | |
| Otherwise the year-answer is ambiguous. | |
| See benchmark-design-decisions.md §3 for the full rationale. | |
| """ | |
| if not cand.gold_chain: | |
| return False | |
| terminal = cand.gold_chain[-1] | |
| if cand.operator_type == "interval": | |
| # Year answer: the specific (s, r, o) triple must be unique in time. | |
| matches = [ | |
| t for t in self.indexer.entity_index.get(terminal.subject, []) | |
| if t.subject == terminal.subject | |
| and t.relation == terminal.relation | |
| and t.obj == terminal.obj | |
| ] | |
| distinct_years = {t.t_start for t in matches} | |
| return len(distinct_years) == 1 | |
| # Entity-valued operators: terminal (s, r) must have a single valid | |
| # object at t_q. | |
| terminal_objs = { | |
| t.obj | |
| for t in self.indexer.entity_index.get(terminal.subject, []) | |
| if t.subject == terminal.subject | |
| and t.relation == terminal.relation | |
| and t.valid_at(cand.t_query) | |
| } | |
| return len(terminal_objs) == 1 and cand.answer in terminal_objs | |
| # --------------------------------------------------------------------------- | |
| # Stage 4: MinHash deduplication | |
| # --------------------------------------------------------------------------- | |
| class MinHasher: | |
| """ | |
| MinHash with Jaccard similarity for deduplicating near-duplicate questions. | |
| Uses character 3-grams and 128 hash functions. | |
| """ | |
| def __init__(self, num_hashes: int = 128, gram_size: int = 3, seed: int = 42): | |
| self.num_hashes = num_hashes | |
| self.gram_size = gram_size | |
| self.seed = seed | |
| def _get_grams(text: str, gram_size: int) -> Set[str]: | |
| """Extract character n-grams from text.""" | |
| text = text.lower() | |
| return {text[i : i + gram_size] for i in range(len(text) - gram_size + 1)} | |
| def _hash_gram(self, gram: str, hash_idx: int) -> int: | |
| """Compute hash value for a gram and hash function index.""" | |
| seed_str = f"{self.seed}_{hash_idx}_{gram}" | |
| h = hashlib.sha256(seed_str.encode()).hexdigest() | |
| return int(h, 16) | |
| def signature(self, text: str) -> List[int]: | |
| """Compute MinHash signature for a text.""" | |
| grams = self._get_grams(text, self.gram_size) | |
| if not grams: | |
| return [0] * self.num_hashes | |
| sig = [] | |
| for hash_idx in range(self.num_hashes): | |
| min_hash = float("inf") | |
| for gram in grams: | |
| h = self._hash_gram(gram, hash_idx) | |
| min_hash = min(min_hash, h) | |
| sig.append(min_hash) | |
| return sig | |
| def jaccard_similarity(sig_a: List[int], sig_b: List[int]) -> float: | |
| """Estimate Jaccard similarity from MinHash signatures.""" | |
| if len(sig_a) == 0 or len(sig_b) == 0: | |
| return 0.0 | |
| matches = sum(1 for a, b in zip(sig_a, sig_b) if a == b) | |
| return matches / len(sig_a) | |
| class MinHashDeduplicator: | |
| """Deduplicates candidates using MinHash with Jaccard threshold.""" | |
| def __init__(self, similarity_threshold: float = 0.8, seed: int = 42): | |
| self.threshold = similarity_threshold | |
| self.hasher = MinHasher(num_hashes=128, seed=seed) | |
| def deduplicate(self, candidates: List[Candidate]) -> List[Candidate]: | |
| """ | |
| Remove near-duplicate questions (Jaccard > threshold). | |
| Keep the first occurrence of each group. | |
| """ | |
| if not candidates: | |
| return [] | |
| # Compute signatures | |
| sigs = [(c, self.hasher.signature(c.question)) for c in candidates] | |
| # Greedy clustering: each candidate either starts a cluster or is merged | |
| clusters = [] | |
| used = set() | |
| for i, (cand_i, sig_i) in enumerate(sigs): | |
| if i in used: | |
| continue | |
| cluster = [cand_i] | |
| used.add(i) | |
| for j in range(i + 1, len(sigs)): | |
| if j in used: | |
| continue | |
| cand_j, sig_j = sigs[j] | |
| sim = self.hasher.jaccard_similarity(sig_i, sig_j) | |
| if sim > self.threshold: | |
| used.add(j) | |
| clusters.append(cluster[0]) # Keep first of each cluster | |
| return clusters | |
| # --------------------------------------------------------------------------- | |
| # Stage 5: Subgraph construction | |
| # --------------------------------------------------------------------------- | |
| class SubgraphConstructor: | |
| """ | |
| Builds three subgraphs for each question: | |
| - S_star: ground truth chain | |
| - S_dist: distractor (one wrong hop, same relation, different object) | |
| - S_stale: stale-fact (one hop replaced by temporally adjacent version) | |
| """ | |
| def __init__(self, indexer: TemporalKGIndexer, seed: int = 42): | |
| self.indexer = indexer | |
| self.rng = random.Random(seed) | |
| def construct( | |
| self, | |
| candidate: Candidate, | |
| ) -> Tuple[List[Dict], List[Dict], List[Dict]]: | |
| """ | |
| Build S_star, S_dist, S_stale for a candidate. | |
| Returns (S_star, S_dist, S_stale) as list of triple dicts. | |
| """ | |
| # S_star: the gold chain | |
| S_star = [t.to_dict() for t in candidate.gold_chain] | |
| # S_dist: replace one hop with a distractor (same relation, different object, valid at t_query) | |
| S_dist = self._build_distractor(candidate) | |
| # S_stale: replace one hop with a temporally adjacent version | |
| S_stale = self._build_stale(candidate) | |
| return S_star, S_dist, S_stale | |
| def _build_distractor(self, candidate: Candidate) -> List[Dict]: | |
| """ | |
| Replace one random hop with a semantically similar but wrong triple. | |
| Same subject, same relation, different object, valid at t_query. | |
| """ | |
| if not candidate.gold_chain: | |
| return [t.to_dict() for t in candidate.gold_chain] | |
| S_dist = [t.to_dict() for t in candidate.gold_chain] | |
| hop_to_replace = self.rng.randint(0, len(candidate.gold_chain) - 1) | |
| replaced_triple = candidate.gold_chain[hop_to_replace] | |
| # Find alternative triples with same (s, r) but different object AT ANY TIME. | |
| # We can't require valid_at(t_query) — the answer-uniqueness filter has | |
| # already guaranteed no such alternatives exist, so that constraint would | |
| # always return an empty list. Taking any alternative object across time | |
| # gives a semantically plausible but factually wrong distractor (e.g. a | |
| # former CEO when the question asks about a later year). | |
| alternatives = [ | |
| t for t in self.indexer.entity_index.get(replaced_triple.subject, []) | |
| if (t.subject == replaced_triple.subject and | |
| t.relation == replaced_triple.relation and | |
| t.obj != replaced_triple.obj) | |
| ] | |
| if alternatives: | |
| distractor = self.rng.choice(alternatives) | |
| S_dist[hop_to_replace] = distractor.to_dict() | |
| return S_dist | |
| def _build_stale(self, candidate: Candidate) -> List[Dict]: | |
| """ | |
| Replace one hop with a temporally adjacent version | |
| (same s, r, o but different validity window that does NOT contain t_query). | |
| """ | |
| if not candidate.gold_chain: | |
| return [t.to_dict() for t in candidate.gold_chain] | |
| S_stale = [t.to_dict() for t in candidate.gold_chain] | |
| hop_to_replace = self.rng.randint(0, len(candidate.gold_chain) - 1) | |
| replaced_triple = candidate.gold_chain[hop_to_replace] | |
| # Find temporally adjacent versions of the same triple | |
| adjacent = [ | |
| t for t in self.indexer._all_triples | |
| if (t.subject == replaced_triple.subject and | |
| t.relation == replaced_triple.relation and | |
| t.obj == replaced_triple.obj and | |
| t.t_start != replaced_triple.t_start and | |
| not t.valid_at(candidate.t_query)) | |
| ] | |
| if adjacent: | |
| stale_triple = self.rng.choice(adjacent) | |
| S_stale[hop_to_replace] = stale_triple.to_dict() | |
| return S_stale | |
| # --------------------------------------------------------------------------- | |
| # Stage 6: Train/dev/test split | |
| # --------------------------------------------------------------------------- | |
| class DatasetSplitter: | |
| """Stratified split by complexity level.""" | |
| def __init__(self, seed: int = 42): | |
| self.rng = random.Random(seed) | |
| def split( | |
| self, | |
| questions: List[BenchmarkQuestion], | |
| train_frac: float = 0.7, | |
| dev_frac: float = 0.1, | |
| test_frac: float = 0.2, | |
| ) -> List[BenchmarkQuestion]: | |
| """ | |
| Stratified split by complexity. | |
| Target: 1-hop: 4K (2.8K train), 2-hop: 4K (2.8K train), 3+-hop: 2K (1.4K train) | |
| """ | |
| # Group by complexity | |
| by_complexity: Dict[str, List[BenchmarkQuestion]] = defaultdict(list) | |
| for q in questions: | |
| by_complexity[q.complexity].append(q) | |
| # Split each group | |
| result = [] | |
| for complexity, qs in by_complexity.items(): | |
| self.rng.shuffle(qs) | |
| n = len(qs) | |
| train_end = int(n * train_frac) | |
| dev_end = train_end + int(n * dev_frac) | |
| for i, q in enumerate(qs): | |
| if i < train_end: | |
| q.split = "train" | |
| elif i < dev_end: | |
| q.split = "dev" | |
| else: | |
| q.split = "test" | |
| result.extend(qs) | |
| return result | |
| # --------------------------------------------------------------------------- | |
| # Main builder | |
| # --------------------------------------------------------------------------- | |
| class BenchmarkBuilder: | |
| """Orchestrates all six pipeline stages.""" | |
| def __init__( | |
| self, | |
| kg_path: str, | |
| output_dir: str = "./benchmark/", | |
| target_n: int = 10000, | |
| seed: int = 42, | |
| min_depth: int = 1, | |
| max_depth: int = 4, | |
| ): | |
| self.kg_path = kg_path | |
| self.output_dir = Path(output_dir) | |
| self.target_n = target_n | |
| self.seed = seed | |
| self.min_depth = min_depth | |
| self.max_depth = max_depth | |
| self.rng = random.Random(seed) | |
| # Build or load indexer | |
| self.indexer = TemporalKGIndexer() | |
| if kg_path.endswith(".json"): | |
| self.indexer.load_from_json(kg_path) | |
| else: | |
| self.indexer.load_tkgl_smallpedia(kg_path) | |
| def build(self) -> List[BenchmarkQuestion]: | |
| """Run the full 6-stage pipeline.""" | |
| print("[Benchmark Builder] Starting pipeline...") | |
| print(f"[Indexer] {self.indexer}") | |
| # Stage 1: Generate candidates | |
| print("\n[Stage 1] Question generation...") | |
| gen = QuestionGenerator(self.indexer, seed=self.seed) | |
| target_candidates = int(self.target_n * 4) # 40K to yield 10K | |
| candidates = gen.generate_candidates( | |
| target_candidates=target_candidates, | |
| min_depth=self.min_depth, | |
| max_depth=self.max_depth, | |
| ) | |
| print(f" Generated {len(candidates):,} candidates") | |
| # Stage 2: Composability filter | |
| print("\n[Stage 2] Composability filtering...") | |
| comp_filter = ComposabilityFilter() | |
| candidates = comp_filter.filter_candidates(candidates) | |
| print(f" Passed composability check: {len(candidates):,}") | |
| # Stage 3: Answer uniqueness filter | |
| print("\n[Stage 3] Answer uniqueness filtering...") | |
| uniq_filter = AnswerUniquenessFilter(self.indexer) | |
| candidates = uniq_filter.filter_candidates(candidates) | |
| print(f" Passed uniqueness check: {len(candidates):,}") | |
| # Stage 4: MinHash deduplication | |
| print("\n[Stage 4] MinHash deduplication...") | |
| deduplicator = MinHashDeduplicator(similarity_threshold=0.8, seed=self.seed) | |
| candidates = deduplicator.deduplicate(candidates) | |
| print(f" After deduplication: {len(candidates):,}") | |
| # Stratified trim: hit the paper's per-complexity targets | |
| # (4K / 4K / 2K at target_n = 10K) and, within each complexity, spread | |
| # across the four operator types. Under-yield in an operator cell | |
| # is topped up with point-in-time from the same complexity, because | |
| # PIT is the most reliable operator and degrades the benchmark least | |
| # if it fills in for a short cell. | |
| candidates = self._stratified_trim(candidates) | |
| print(f" Trimmed to target: {len(candidates):,}") | |
| # Stage 5: Subgraph construction | |
| print("\n[Stage 5] Subgraph construction...") | |
| sg_constructor = SubgraphConstructor(self.indexer, seed=self.seed) | |
| questions = [] | |
| for i, cand in enumerate(candidates): | |
| S_star, S_dist, S_stale = sg_constructor.construct(cand) | |
| q = BenchmarkQuestion( | |
| id=f"q_{i:06d}", | |
| question=cand.question, | |
| t_query=cand.t_query, | |
| answer=cand.answer, | |
| complexity=cand.complexity, | |
| operator_type=cand.operator_type, | |
| question_type=cand.question_type, | |
| S_star=S_star, | |
| S_dist=S_dist, | |
| S_stale=S_stale, | |
| split="", # Will be set in Stage 6 | |
| ) | |
| questions.append(q) | |
| print(f" Subgraphs constructed: {len(questions):,}") | |
| # Stage 6: Train/dev/test split | |
| print("\n[Stage 6] Train/dev/test split (stratified)...") | |
| splitter = DatasetSplitter(seed=self.seed) | |
| questions = splitter.split(questions) | |
| # Print split statistics | |
| splits = defaultdict(lambda: defaultdict(int)) | |
| for q in questions: | |
| splits[q.complexity][q.split] += 1 | |
| print(" Split distribution:") | |
| for complexity in ["1hop", "2hop", "3plus"]: | |
| if complexity in splits: | |
| train = splits[complexity]["train"] | |
| dev = splits[complexity]["dev"] | |
| test = splits[complexity]["test"] | |
| total = train + dev + test | |
| print(f" {complexity:8s}: {total:5d} ({train:4d} train, {dev:3d} dev, {test:3d} test)") | |
| return questions | |
| def _stratified_trim(self, candidates: List[Candidate]) -> List[Candidate]: | |
| """ | |
| Reduce candidates to per-complexity/per-operator quotas matching paper | |
| the TempBench paper (4K 1-hop, 4K 2-hop, 2K 3+-hop at target_n = 10K), with each | |
| complexity split evenly across four operators. Cells that under-yield | |
| are topped up from PIT in the same complexity. | |
| """ | |
| per_complexity_target = { | |
| "1hop": self.target_n * 4 // 10, # 40% | |
| "2hop": self.target_n * 4 // 10, # 40% | |
| "3plus": self.target_n * 2 // 10, # 20% | |
| } | |
| operators = ("point_in_time", "before_after", "interval", "sequence") | |
| # Bucket candidates by (complexity, operator) | |
| buckets: Dict[Tuple[str, str], List[Candidate]] = defaultdict(list) | |
| for c in candidates: | |
| buckets[(c.complexity, c.operator_type)].append(c) | |
| for bucket in buckets.values(): | |
| self.rng.shuffle(bucket) | |
| trimmed: List[Candidate] = [] | |
| for complexity, cx_target in per_complexity_target.items(): | |
| per_op_target = cx_target // len(operators) | |
| cx_kept: List[Candidate] = [] | |
| # First pass: take up to per_op_target from each operator cell. | |
| for op in operators: | |
| cell = buckets.get((complexity, op), []) | |
| cx_kept.extend(cell[:per_op_target]) | |
| # Top up shortfall with PIT first, then anything available. | |
| shortfall = cx_target - len(cx_kept) | |
| if shortfall > 0: | |
| topup_pool: List[Candidate] = [] | |
| for op in ("point_in_time", "sequence", "before_after", "interval"): | |
| cell = buckets.get((complexity, op), []) | |
| if len(cell) > per_op_target: | |
| topup_pool.extend(cell[per_op_target:]) | |
| self.rng.shuffle(topup_pool) | |
| cx_kept.extend(topup_pool[:shortfall]) | |
| trimmed.extend(cx_kept) | |
| self.rng.shuffle(trimmed) | |
| return trimmed | |
| def save(self, questions: List[BenchmarkQuestion]) -> None: | |
| """Write benchmark to JSONL file.""" | |
| self.output_dir.mkdir(parents=True, exist_ok=True) | |
| output_path = self.output_dir / "benchmark.jsonl" | |
| with open(output_path, "w", encoding="utf-8") as f: | |
| for q in questions: | |
| f.write(json.dumps(q.to_jsonl_dict()) + "\n") | |
| print(f"\n[Output] Benchmark saved to {output_path}") | |
| print(f" {len(questions):,} questions written") | |
| # --------------------------------------------------------------------------- | |
| # Smoke test | |
| # --------------------------------------------------------------------------- | |
| def smoke_test(): | |
| """Run on synthetic Deutsche Bank KG (same 5 triples as indexer.py tests).""" | |
| print("=" * 70) | |
| print("SMOKE TEST: TempBench Builder") | |
| print("=" * 70) | |
| # Create a temporary indexer with synthetic data | |
| indexer = TemporalKGIndexer() | |
| indexer.build([ | |
| ("Deutsche_Bank", "has_CFO", "John_Cryan", 2015.0, 2018.0), | |
| ("Deutsche_Bank", "has_CFO", "Christian_Sewing", 2018.0, math.inf), | |
| ("Deutsche_Bank", "settled", "LIBOR_Case", 2015.25, 2015.25), | |
| ("John_Cryan", "member_of", "Deutsche_Bank", 2015.0, 2018.0), | |
| ("Christian_Sewing", "member_of", "Deutsche_Bank", 2018.0, math.inf), | |
| ]) | |
| print(f"\nIndexer: {indexer}\n") | |
| # Generate candidates | |
| gen = QuestionGenerator(indexer, seed=42) | |
| candidates = gen.generate_candidates( | |
| target_candidates=100, | |
| min_depth=1, | |
| max_depth=3, | |
| ) | |
| print(f"Generated {len(candidates)} candidates") | |
| # Filter by composability | |
| comp_filter = ComposabilityFilter() | |
| candidates = comp_filter.filter_candidates(candidates) | |
| print(f"Passed composability: {len(candidates)}") | |
| # Filter by uniqueness | |
| uniq_filter = AnswerUniquenessFilter(indexer) | |
| candidates = uniq_filter.filter_candidates(candidates) | |
| print(f"Passed uniqueness: {len(candidates)}") | |
| # Deduplicate | |
| deduplicator = MinHashDeduplicator(similarity_threshold=0.8, seed=42) | |
| candidates = deduplicator.deduplicate(candidates) | |
| print(f"After deduplication: {len(candidates)}") | |
| # Build subgraphs | |
| sg_constructor = SubgraphConstructor(indexer, seed=42) | |
| questions = [] | |
| for i, cand in enumerate(candidates[:min(5, len(candidates))]): | |
| S_star, S_dist, S_stale = sg_constructor.construct(cand) | |
| q = BenchmarkQuestion( | |
| id=f"q_{i:06d}", | |
| question=cand.question, | |
| t_query=cand.t_query, | |
| answer=cand.answer, | |
| complexity=cand.complexity, | |
| operator_type=cand.operator_type, | |
| question_type=cand.question_type, | |
| S_star=S_star, | |
| S_dist=S_dist, | |
| S_stale=S_stale, | |
| split="train", | |
| ) | |
| questions.append(q) | |
| print(f"Built {len(questions)} benchmark questions\n") | |
| # Print sample | |
| print("Sample questions:") | |
| for q in questions[:3]: | |
| print(f"\n ID: {q.id}") | |
| print(f" Question: {q.question}") | |
| print(f" Complexity: {q.complexity}") | |
| print(f" Answer: {q.answer}") | |
| print(f" t_query: {q.t_query}") | |
| print(f" Operator: {q.operator_type}") | |
| print(f" S_star: {len(q.S_star)} triples") | |
| print(f" S_dist: {len(q.S_dist)} triples") | |
| print(f" S_stale: {len(q.S_stale)} triples") | |
| print("\n" + "=" * 70) | |
| print("SMOKE TEST PASSED") | |
| print("=" * 70) | |
| # --------------------------------------------------------------------------- | |
| # CLI | |
| # --------------------------------------------------------------------------- | |
| def main(): | |
| parser = argparse.ArgumentParser( | |
| description="Build TempBench: 10K-question temporal QA benchmark" | |
| ) | |
| parser.add_argument( | |
| "--kg_path", | |
| type=str, | |
| default=None, | |
| help="Path to KG file (JSON or TKGL CSV)", | |
| ) | |
| parser.add_argument( | |
| "--output_dir", | |
| type=str, | |
| default="./benchmark/", | |
| help="Output directory for benchmark JSONL", | |
| ) | |
| parser.add_argument( | |
| "--target_n", | |
| type=int, | |
| default=10000, | |
| help="Target number of benchmark questions (default 10000)", | |
| ) | |
| parser.add_argument( | |
| "--seed", | |
| type=int, | |
| default=42, | |
| help="Random seed (default 42)", | |
| ) | |
| parser.add_argument( | |
| "--min_depth", | |
| type=int, | |
| default=1, | |
| help="Minimum chain depth (default 1)", | |
| ) | |
| parser.add_argument( | |
| "--max_depth", | |
| type=int, | |
| default=4, | |
| help="Maximum chain depth (default 4)", | |
| ) | |
| parser.add_argument( | |
| "--smoke_test", | |
| action="store_true", | |
| help="Run smoke test on synthetic data", | |
| ) | |
| args = parser.parse_args() | |
| if args.smoke_test: | |
| smoke_test() | |
| sys.exit(0) | |
| if not args.kg_path: | |
| print("Error: --kg_path required (or use --smoke_test)") | |
| sys.exit(1) | |
| builder = BenchmarkBuilder( | |
| kg_path=args.kg_path, | |
| output_dir=args.output_dir, | |
| target_n=args.target_n, | |
| seed=args.seed, | |
| min_depth=args.min_depth, | |
| max_depth=args.max_depth, | |
| ) | |
| questions = builder.build() | |
| builder.save(questions) | |
| if __name__ == "__main__": | |
| main() | |