| 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 | |