"""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, }