File size: 1,124 Bytes
f0d6538
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch


def compare_tensors(
    a: torch.Tensor,
    b: torch.Tensor,
    atol: float = 1e-5,
    rtol: float = 1e-5,
) -> float:
    """
    Compare two tensors and return the ratio of matching values.

    Args:
        a, b: Tensors to compare
        atol, rtol: Absolute and relative tolerance thresholds

    Returns:
        ratio: Float between 0.0 and 1.0 indicating fraction of close values
    """
    mask = torch.isclose(a, b, atol=atol, rtol=rtol)
    matching = mask.sum().item()
    total = mask.numel()
    ratio = matching / total

    # Log mismatches for debugging
    if ratio < 1.0:
        not_close_count = total - matching
        pct_not_close = (not_close_count / total) * 100
        print(f"  {pct_not_close:.2f}% of values not close ({not_close_count}/{total})")

        # Show details if small number of mismatches
        if not_close_count <= 10:
            mismatches = torch.where(torch.logical_not(mask))
            print(f"  Mismatch indices: {mismatches}")
            print(f"  Actual:   {a[mismatches]}")
            print(f"  Expected: {b[mismatches]}")

    return ratio