File size: 8,213 Bytes
b9bc266
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
"""TempBench retrieval-quality metrics: TRP and Chain Consistency Rate.

Scores *your* retriever against TempBench's per-question gold subgraphs. You
supply the evidence your system retrieved; this module supplies the metrics the
paper reports, so numbers are comparable without re-implementing the
definitions.

Both metrics are answer-independent: they score the evidence, not the generated
string. That is the point of the benchmark -- a system can produce the right
answer from stale evidence, and end-task exact-match cannot see it.

    TRP  (Temporal Retrieval Precision)
         per question: |retrieved triples that are in S* AND valid at t_query|
                       / |retrieved triples|
         Macro-averaged over questions that retrieved anything. Undefined (and
         excluded) when a system returns nothing.

    CCR  (Chain Consistency Rate)
         per question: 1 if every triple of S* was retrieved and time-valid,
         else 0. Averaged over all questions, including empty retrievals.

A triple counts as time-valid when t_start <= t_query <= t_end. On a
point-in-time KG (t_start == t_end, as in the released benchmark) that reduces
to exact-year equality.

TRP is a precision-at-k quantity against 1-3-triple gold chains, so its absolute
scale is low by construction; read the gap between retrievers and the
per-complexity profile, not the raw value. TRP and CCR are not redundant: at
3+-hop the reference retriever scores TRP 0.203 against CCR 0.014 -- partial
gold evidence is routinely retrieved, the full chain almost never.

Stdlib only. Python 3.9+.

Usage
-----
    import json
    from tempbench_eval import score_question, aggregate

    rows = []
    for line in open('benchmark/benchmark_labelled.jsonl', encoding='utf-8'):
        q = json.loads(line)
        if q['split'] != 'test':
            continue
        evidence = my_retriever(q['question'], q['t_query'])   # your system
        rows.append(score_question(q, evidence))

    print(aggregate(rows))

`evidence` is whatever your retriever returned, as an iterable of triples. Each
may be a dict with keys s/r/o/t_start/t_end (label space, matching
`benchmark_labelled.jsonl`), a dict with s_id/r_id/o_id (Wikidata id space,
matching `benchmark.jsonl`), or a 5-tuple (s, r, o, t_start, t_end). Mixing
spaces within one run will silently score zero, so pick one and stay in it --
`key='auto'` infers it from the first item.

Restrict negative-dependent analysis to the functional subset: see
`benchmark/functional_negatives.jsonl`, and read `v1.0.1-addendum.md` before
evaluating -- interval questions leak their answer under the original prompt
protocol.
"""

from collections import defaultdict

__all__ = ['score_question', 'aggregate', 'as_triple']

_LABEL_KEYS = ('s', 'r', 'o')
_ID_KEYS = ('s_id', 'r_id', 'o_id')


def as_triple(item, key='auto'):
    """Normalise one retrieved item to (s, r, o, t_start, t_end).

    key: 'label' to match on surface labels, 'id' to match on Wikidata ids,
    'auto' to use ids when the item carries them and labels otherwise.
    """
    if isinstance(item, (tuple, list)):
        if len(item) != 5:
            raise ValueError('tuple evidence must be (s, r, o, t_start, t_end),'
                             ' got %d fields' % len(item))
        s, r, o, ts, te = item
    elif isinstance(item, dict):
        use_id = (key == 'id' or
                  (key == 'auto' and all(k in item for k in _ID_KEYS)))
        ks = _ID_KEYS if use_id else _LABEL_KEYS
        missing = [k for k in ks if k not in item]
        if missing:
            raise KeyError('evidence dict is missing %s; it has %s'
                           % (missing, sorted(item)))
        s, r, o = (item[k] for k in ks)
        ts, te = item.get('t_start'), item.get('t_end')
        if ts is None or te is None:
            raise KeyError('evidence dict needs t_start and t_end to be scored '
                           'for temporal validity')
    else:
        raise TypeError('evidence items must be dicts or 5-tuples, got %r'
                        % type(item).__name__)
    return (s, r, o, float(ts), float(te))


def score_question(question, evidence, key='auto'):
    """Score one question's retrieved evidence. Returns a per-question row.

    `question` is a record from benchmark_labelled.jsonl (or benchmark.jsonl).
    `evidence` is what your retriever returned for it, already truncated to
    your k -- TRP is a precision quantity, so this module does not truncate for
    you.
    """
    retrieved = [as_triple(e, key) for e in evidence]
    tq = float(question['t_query'])

    gold = question['S_star']
    use_id = (key == 'id' or
              (key == 'auto' and all(k in gold[0] for k in _ID_KEYS)))
    gk = _ID_KEYS if use_id else _LABEL_KEYS
    gold_ids = {tuple(g[k] for k in gk) for g in gold}

    hits = [t for t in retrieved
            if t[:3] in gold_ids and t[3] <= tq <= t[4]]
    covered = {t[:3] for t in hits}
    n_ret = len(retrieved)

    return {
        'id': question.get('id'),
        'complexity': question.get('complexity'),
        'operator': question.get('operator_type'),
        'n_ret': n_ret,
        'hits': len(hits),
        'n_gold': len(gold_ids),
        'trp': (len(hits) / n_ret) if n_ret else None,
        'ccr': 1 if (gold_ids and covered == gold_ids) else 0,
    }


def _cell(rows):
    scored = [r for r in rows if r['n_ret'] > 0]
    trp = [r['trp'] for r in scored]
    return {
        'n': len(rows),
        'TRP': (sum(trp) / len(trp)) if trp else 0.0,
        'CCR': (sum(r['ccr'] for r in rows) / len(rows)) if rows else 0.0,
    }


def aggregate(rows, by=('complexity', 'operator')):
    """Corpus-level metrics, plus the per-slice breakdowns the paper reports.

    TRP is macro-averaged over questions that retrieved something; CCR is
    averaged over all of them. `coverage` is the fraction that retrieved
    anything -- report it, because a system that returns nothing on hard
    questions otherwise inflates its own TRP.
    """
    if not rows:
        return {'n_questions': 0}
    scored = [r for r in rows if r['n_ret'] > 0]
    total_ret = sum(r['n_ret'] for r in rows)
    out = {
        'n_questions': len(rows),
        'coverage': len(scored) / len(rows),
        'TRP_macro': (sum(r['trp'] for r in scored) / len(scored)) if scored else 0.0,
        'TRP_micro': (sum(r['hits'] for r in rows) / total_ret) if total_ret else 0.0,
        'CCR': sum(r['ccr'] for r in rows) / len(rows),
    }
    for field in by:
        buckets = defaultdict(list)
        for r in rows:
            buckets[r.get(field)].append(r)
        out['by_' + field] = {k: _cell(v) for k, v in sorted(
            buckets.items(), key=lambda kv: str(kv[0]))}
    return out


if __name__ == '__main__':
    # Self-check on a synthetic question: a perfect retrieval, a stale-fact
    # retrieval, and an empty one. Needs no data files.
    q = {
        'id': 'demo', 'complexity': '1hop', 'operator_type': 'point_in_time',
        't_query': 1994.0,
        'S_star': [{'s': 'A', 'r': 'rel', 'o': 'B',
                    't_start': 1994.0, 't_end': 1994.0}],
    }
    gold = {'s': 'A', 'r': 'rel', 'o': 'B', 't_start': 1994.0, 't_end': 1994.0}
    stale = dict(gold, t_start=1991.0, t_end=1991.0)
    noise = {'s': 'A', 'r': 'rel', 'o': 'C',
             't_start': 1994.0, 't_end': 1994.0}

    perfect = score_question(q, [gold])
    diluted = score_question(q, [gold, noise])
    stale_only = score_question(q, [stale])
    empty = score_question(q, [])

    assert (perfect['trp'], perfect['ccr']) == (1.0, 1)
    assert (diluted['trp'], diluted['ccr']) == (0.5, 1), diluted
    assert (stale_only['trp'], stale_only['ccr']) == (0.0, 0), stale_only
    assert empty['trp'] is None and empty['ccr'] == 0

    agg = aggregate([perfect, diluted, stale_only, empty])
    assert agg['coverage'] == 0.75, agg
    assert agg['CCR'] == 0.5, agg
    print('tempbench_eval self-check OK')
    print('  perfect     ', perfect)
    print('  +1 distractor', diluted)
    print('  stale only  ', stale_only)
    print('  aggregate   ', {k: v for k, v in agg.items()
                             if not k.startswith('by_')})