File size: 12,078 Bytes
ae5b1ef
4881d06
ae5b1ef
4881d06
 
 
ae5b1ef
 
4881d06
 
 
ae5b1ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4881d06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae5b1ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4881d06
 
 
ae5b1ef
 
4881d06
 
 
ae5b1ef
 
 
 
 
 
 
 
 
 
 
 
4881d06
ae5b1ef
 
 
 
 
 
 
 
 
 
 
 
 
4881d06
 
 
 
 
 
 
 
 
 
 
 
 
ae5b1ef
 
 
 
 
 
 
 
 
4881d06
ae5b1ef
 
4881d06
 
 
ae5b1ef
4881d06
 
 
 
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
"""Score complete experimental rankings by weighted Spearman correlation."""
import argparse
import errno
import hashlib
import json
import math
import os
import stat
from pathlib import Path


class TaskError(ValueError):
    pass


class SubmissionError(ValueError):
    pass


def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise SubmissionError("duplicate_json_key")
        result[key] = value
    return result


def load_json(raw):
    def reject_constant(value):
        raise SubmissionError("nonfinite_json_constant")
    return json.loads(raw.decode("utf-8"), object_pairs_hook=unique_object,
                      parse_constant=reject_constant)


def finite(value, name, minimum=None):
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        raise TaskError(name + " is not numeric")
    if not math.isfinite(value) or (minimum is not None and value < minimum):
        raise TaskError(name + " is out of range")
    return float(value)


def bounded(value):
    if not math.isfinite(value) or not -1 - 1e-12 <= value <= 1 + 1e-12:
        raise TaskError('Spearman outside its finite range')
    return min(1.0, max(-1.0, value))


def average_ranks(values):
    if len(values) < 2 or any(isinstance(x, bool) or not isinstance(x, (int, float))
                              or not math.isfinite(x) for x in values):
        raise TaskError('Invalid measurements')
    ordered = sorted(range(len(values)), key=values.__getitem__)
    ranks = [0.0] * len(values)
    start = 0
    while start < len(values):
        stop = start + 1
        while stop < len(values) and values[ordered[stop]] == values[ordered[start]]:
            stop += 1
        mean_rank = (start + 1 + stop) / 2
        for index in ordered[start:stop]:
            ranks[index] = mean_rank
        start = stop
    return ranks


def spearman(values, predicted_positions):
    ranks = average_ranks(values)
    n = len(values)
    if sorted(predicted_positions) != list(range(n)):
        raise ValueError('Not a complete permutation')
    predicted_ranks = [p + 1 for p in predicted_positions]
    true_mean = math.fsum(ranks) / n
    predicted_mean = math.fsum(predicted_ranks) / n
    x = [r - true_mean for r in ranks]
    y = [p - predicted_mean for p in predicted_ranks]
    denominator = math.sqrt(math.fsum(r * r for r in x) * math.fsum(p * p for p in y))
    if denominator <= 0:
        raise TaskError('Undefined Spearman for constant results')
    return bounded(math.fsum(r * p for r, p in zip(x, y)) / denominator)


def read_regular(path, limit):
    try:
        fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
        try:
            info = os.fstat(fd)
            if not stat.S_ISREG(info.st_mode):
                raise SubmissionError("not_regular_file")
            if info.st_size > limit:
                raise SubmissionError("submission_too_large")
            with os.fdopen(fd, "rb", closefd=False) as stream:
                raw = stream.read(limit + 1)
            if len(raw) > limit:
                raise SubmissionError("submission_too_large")
            return raw
        finally:
            os.close(fd)
    except OSError as error:
        if error.errno in (errno.ENOENT, errno.ELOOP, errno.EISDIR, errno.ENOTDIR,
                           errno.ENXIO, errno.EACCES, errno.EPERM):
            raise SubmissionError("missing_or_unreadable_submission") from error
        raise


def validate_task(contract, answers):
    expected = {
        "scoring_method": "spearman",
        "primary_score": "task_spearman",
        "spearman_range": [-1, 1],
        "spearman_tie_method": "average",
        "spearman_undefined_policy": "task_error",
    }
    if any(contract.get(key) != value for key, value in expected.items()):
        raise TaskError("Unsupported scoring contract")
    for key in ("task_id", "task_version"):
        if not isinstance(contract.get(key), str) or answers.get(key) != contract[key]:
            raise TaskError("Invalid task identity")
    limit = contract.get("max_submission_bytes")
    if type(limit) is not int or not 0 < limit <= 1048576:
        raise TaskError("Invalid submission size limit")
    minimum = contract.get("minimum_conditions_per_group", 2)
    if type(minimum) is not int or minimum < 2:
        raise TaskError("Invalid minimum group size")
    groups = contract["groups"]
    references = {g["group_id"]: g for g in answers["groups"]}
    if not groups or len(groups) != len(references) or len(references) != len(answers["groups"]):
        raise TaskError("Invalid reference groups")

    measurements = {}
    all_ids = set()
    for group in groups:
        gid = group["group_id"]
        ids = group["item_ids"]
        if not isinstance(gid, str) or not gid or gid in measurements or gid not in references:
            raise TaskError("Invalid group ID")
        if (group["direction"] != "ascending" or not isinstance(ids, list) or len(ids) < minimum
                or any(not isinstance(i, str) or not i for i in ids)
                or len(set(ids)) != len(ids) or all_ids.intersection(ids)):
            raise TaskError("Invalid group definition")
        all_ids.update(ids)
        if finite(group["group_weight"], "group_weight", 0) == 0:
            raise TaskError("Zero group weight")
        items = references[gid]["items"]
        values = {item["item_id"]: item["mean"] for item in items}
        if len(items) != len(ids) or set(values) != set(ids):
            raise TaskError("Reference items differ from the contract")
        measurements[gid] = [values[i] for i in ids]
        spearman(measurements[gid], list(range(len(ids))))
    if not math.isclose(math.fsum(g["group_weight"] for g in groups), 1.0, rel_tol=0, abs_tol=1e-12):
        raise TaskError("Group weights must sum to one")
    return measurements


def group_entries(submission, contract):
    if not isinstance(submission, dict):
        raise SubmissionError("invalid_top_level_structure")
    if any(submission.get(key) != contract[key] for key in ("task_id", "task_version")):
        raise SubmissionError("task_identity_mismatch")
    if not isinstance(submission.get("rankings"), list):
        raise SubmissionError("rankings_not_array")
    entries = {group["group_id"]: [] for group in contract["groups"]}
    for entry in submission["rankings"]:
        if not isinstance(entry, dict) or not isinstance(entry.get("group_id"), str):
            raise SubmissionError("unassignable_group_entry")
        if entry["group_id"] not in entries:
            raise SubmissionError("unknown_group_id")
        entries[entry["group_id"]].append(entry)
    return entries


def score_group(group, entries, values):
    gid = group["group_id"]
    ids = group["item_ids"]
    result = {"group_id": gid, "group_weight": group["group_weight"],
              "group_spearman_g": None, "spearman_for_aggregation": -1.0}
    if entries is None:
        result["status"] = "whole_task_format_error"
        return result
    matches = entries[gid]
    if len(matches) != 1:
        result["status"] = "duplicate_group" if matches else "missing_group"
        return result
    order = matches[0].get("order")
    if (not isinstance(order, list) or len(order) != len(ids)
            or any(not isinstance(i, str) for i in order) or set(order) != set(ids)):
        result["status"] = "invalid_permutation"
        return result
    positions = {item: p for p, item in enumerate(order)}
    rho = spearman(values, [positions[i] for i in ids])
    result.update(status="valid", order=order, group_spearman_g=rho, spearman_for_aggregation=rho)
    return result


def grade_file(contract, answers, path):
    measurements = validate_task(contract, answers)
    report = {"task_id": contract["task_id"], "task_version": contract["task_version"],
              "scoring_method": "spearman", "primary_score": "task_spearman",
              "evaluation_status": "completed"}
    entries = None
    try:
        raw = read_regular(path, contract["max_submission_bytes"])
        submission = load_json(raw)
        report["submission_sha256"] = hashlib.sha256(raw).hexdigest()
        entries = group_entries(submission, contract)
    except (SubmissionError, UnicodeError, json.JSONDecodeError, RecursionError) as error:
        report["submission_status"] = str(error) or type(error).__name__
        report["core_penalty_reason"] = "whole_task_format_error"
    groups = [score_group(g, entries, measurements[g["group_id"]]) for g in contract["groups"]]
    report["groups"] = groups
    if entries is None:
        report["task_spearman"] = -1.0
    else:
        report["submission_status"] = "valid" if all(g["status"] == "valid" for g in groups) else "group_errors"
        report["task_spearman"] = bounded(math.fsum(g["group_weight"] * g["spearman_for_aggregation"]
                                                   for g in groups))
    return report


def dump(path, value):
    path.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n", encoding="utf-8")



def supporting_artifact_status(submission):
    root = submission.parent
    report_path = root / 'report.md'
    paths = {'report_file': report_path, 'sources_file': root / 'sources.json',
             'analysis_directory': root / 'analysis'}
    present = {}
    for name, path in paths.items():
        try:
            mode = path.lstat().st_mode
            present[name] = stat.S_ISDIR(mode) if name == 'analysis_directory' else stat.S_ISREG(mode)
        except OSError:
            present[name] = False

    declared_stop = False
    if present['report_file']:
        try:
            fd = os.open(report_path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
            with os.fdopen(fd, 'rb') as stream:
                if stat.S_ISREG(os.fstat(stream.fileno()).st_mode):
                    declared_stop = stream.readline(256).rstrip(b'\r\n') == b'SPU_POLICY_STOP'
        except OSError:
            pass
    status = 'artifacts_present' if all(present.values()) else 'artifacts_incomplete'
    if declared_stop:
        status = 'declared_stop_with_ranking' if os.path.lexists(submission) else 'declared_stop'
    return {'status': status, **present, 'policy_stop_declared': declared_stop}


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--interface', choices=['txt', 'json'], default='txt')
    parser.add_argument('--root', type=Path, default=Path('/tests'))
    parser.add_argument('--submission', type=Path, default=Path('/logs/artifacts/rankings.json'))
    parser.add_argument('--output', type=Path, default=Path('/logs/verifier'))
    args = parser.parse_args()
    args.output.mkdir(parents=True, exist_ok=True)
    for name in ('reward.txt', 'reward.json', 'report.json', 'evaluator_error.json'):
        (args.output / name).unlink(missing_ok=True)
    try:
        bindings = load_json((args.root / 'scoring_hashes.json').read_bytes())
        for name in ('contract.json', 'answers.json', 'grade.py'):
            if hashlib.sha256((args.root / name).read_bytes()).hexdigest() != bindings[name]:
                raise TaskError('Scoring file hash mismatch: ' + name)
        contract = load_json((args.root / 'contract.json').read_bytes())
        answers = load_json((args.root / 'answers.json').read_bytes())
        report = grade_file(contract, answers, args.submission)
    except (TaskError, SubmissionError, OSError, ValueError, KeyError, TypeError) as error:
        dump(args.output / 'evaluator_error.json', {'status': 'task_error', 'error': str(error)})
        raise SystemExit(2) from error
    report['supporting_artifact_review'] = supporting_artifact_status(args.submission)
    dump(args.output / 'report.json', report)
    if args.interface == 'txt':
        (args.output / 'reward.txt').write_text(str(report['task_spearman']) + '\n')
    else:
        dump(args.output / 'reward.json', {'reward': report['task_spearman']})


if __name__ == '__main__':
    main()