File size: 5,038 Bytes
6b3ffe8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Create an exact cross-architecture plan and optionally score aligned embeddings."""
import argparse
import hashlib
import json
from pathlib import Path

ARCHES = ['arm32', 'arm64', 'mips32', 'mips64', 'ppc32', 'ppc64', 'x86', 'x64']


def plan(records, source, target):
    candidates = sorted([r for r in records if r['arch'] == target], key=lambda r: r['id'])
    relevant = {r['group_id'] for r in candidates}
    source_rows = sorted([r for r in records if r['arch'] == source], key=lambda r: r['id'])
    queries = [r for r in source_rows if r['group_id'] in relevant]
    return queries, candidates, len(source_rows) - len(queries)


def metrics(query_vectors, candidate_vectors, queries, candidates, cutoffs=(1, 10, 50)):
    import numpy as np
    q = np.asarray(query_vectors, dtype=np.float32)
    d = np.asarray(candidate_vectors, dtype=np.float32)
    if q.ndim != 2 or d.ndim != 2 or q.shape[1] != d.shape[1]:
        raise ValueError('Embeddings must be two matrices with the same feature dimension')
    if len(q) != len(queries) or len(d) != len(candidates) or not len(q) or not len(d):
        raise ValueError('Embedding rows must match a nonempty exported plan exactly')
    if not np.isfinite(q).all() or not np.isfinite(d).all():
        raise ValueError('Embeddings contain non-finite values')
    qnorm = np.linalg.norm(q, axis=1, keepdims=True)
    dnorm = np.linalg.norm(d, axis=1, keepdims=True)
    if (qnorm <= 0).any() or (dnorm <= 0).any():
        raise ValueError('Zero-norm embeddings are not valid')
    q, d = q / qnorm, d / dnorm
    dg = np.array([r['group_id'] for r in candidates])
    scores = {'mrr': []}
    for k in cutoffs:
        scores.update({f'{m}@{k}': [] for m in ['recall', 'hit', 'ndcg']})
    for start in range(0, len(q), 128):
        similarities = q[start:start + 128] @ d.T
        # Candidate IDs were sorted in the plan, so stable sorting resolves ties.
        orders = np.argsort(-similarities, axis=1, kind='stable')
        for offset, order in enumerate(orders):
            gold = dg == queries[start + offset]['group_id']
            ranked = gold[order]
            count = int(gold.sum())
            if count == 0:
                raise ValueError('Plan contains a query with no known counterpart')
            scores['mrr'].append(1. / (np.flatnonzero(ranked)[0] + 1))
            for k in cutoffs:
                found = ranked[:k]
                scores[f'recall@{k}'].append(float(found.sum()) / count)
                scores[f'hit@{k}'].append(float(found.any()))
                discounts = 1. / np.log2(np.arange(2, len(found) + 2))
                ideal = (1. / np.log2(np.arange(2, min(k, count) + 2))).sum()
                scores[f'ndcg@{k}'].append(float((found * discounts).sum() / ideal))
    return {key: float(np.mean(values)) for key, values in scores.items()}


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--dataset-dir', required=True)
    p.add_argument('--split', choices=['validation', 'test'], default='test')
    p.add_argument('--source', choices=ARCHES, required=True)
    p.add_argument('--target', choices=ARCHES, required=True)
    p.add_argument('--output-dir', required=True)
    p.add_argument('--query-embeddings', type=Path)
    p.add_argument('--candidate-embeddings', type=Path)
    args = p.parse_args()
    if args.source == args.target:
        p.error('Source and target must differ for this cross-architecture example')
    if bool(args.query_embeddings) != bool(args.candidate_embeddings):
        p.error('Provide both embedding files or neither')
    source = Path(args.dataset_dir) / f'{args.split}.functions.jsonl'
    with source.open(encoding='utf-8') as stream:
        records = [json.loads(line) for line in stream]
    queries, candidates, skipped = plan(records, args.source, args.target)
    out = Path(args.output_dir)
    out.mkdir(parents=True, exist_ok=True)
    for filename, rows in [('queries.jsonl', queries), ('candidates.jsonl', candidates)]:
        with (out / filename).open('w', encoding='utf-8') as stream:
            for row in rows:
                stream.write(json.dumps(row, ensure_ascii=False) + '\n')
    signature = hashlib.sha256(source.read_bytes()).hexdigest()
    result = {'split': args.split, 'direction': args.source + '->' + args.target,
              'queries': len(queries), 'candidates': len(candidates), 'skipped_queries': skipped,
              'source_sha256': signature, 'ordering': 'function ID ascending',
              'relevance': 'same group_id', 'candidate_scope': 'all target-architecture functions in split'}
    if args.query_embeddings:
        import numpy as np
        result['metrics'] = metrics(np.load(args.query_embeddings, allow_pickle=False),
                                    np.load(args.candidate_embeddings, allow_pickle=False), queries, candidates)
    (out / 'report.json').write_text(json.dumps(result, indent=2) + '\n')
    print(json.dumps(result, indent=2))


if __name__ == '__main__':
    main()