File size: 1,652 Bytes
4d34156
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Evaluate one output using the task's explicit, unchanged acceptance policy."""


def compare_output(actual, expected, tolerance):
    import torch

    if (
        actual.shape != expected.shape
        or actual.dtype != expected.dtype
        or actual.device != expected.device
    ):
        raise AssertionError("Output shape, dtype or device differs")
    if not actual.is_floating_point():
        if not torch.equal(actual, expected):
            raise AssertionError("Integer output differs")
        return {"exact": True}
    if not bool(torch.isfinite(actual).all()) or not bool(
        torch.isfinite(expected).all()
    ):
        raise AssertionError("Nonfinite output")
    error = (actual.float() - expected.float()).abs()
    if tolerance.get("comparison") == "absolute_or_relative":
        close = (error <= tolerance["atol"]) | (
            error / (expected.float().abs() + 1e-8) <= tolerance["rtol"]
        )
    else:
        close = error <= tolerance["atol"] + tolerance["rtol"] * expected.float().abs()
    # Count in integer arithmetic; a floating-point mean can round below 1
    # even when every element passes.
    matched = int(close.sum())
    ratio = matched / close.numel() if close.numel() else 1.0
    required = tolerance.get("required_matched_ratio")
    if ratio < (1.0 if required is None else required):
        raise AssertionError(
            f"Matched {matched}/{close.numel()} output elements ({ratio})"
        )
    return {
        "max_absolute_error": error.max().item() if error.numel() else 0.0,
        "matched_ratio": ratio,
        "mismatched_elements": close.numel() - matched,
    }