Print the first max_errors tensor indexes that exceed the absolute/relative tolerance and the error at each of those locations. Args: tensor1: First tensor to compare tensor2: Second tensor to compare atol: Absolute tolerance rtol: Relative tolerance
(
tensor1, tensor2, atol=1e-03, rtol=1e-03, max_errors=10
)
| 415 | |
| 416 | |
| 417 | def print_tensor_comparison_errors( |
| 418 | tensor1, tensor2, atol=1e-03, rtol=1e-03, max_errors=10 |
| 419 | ): |
| 420 | """ |
| 421 | Print the first max_errors tensor indexes that exceed the absolute/relative tolerance |
| 422 | and the error at each of those locations. |
| 423 | |
| 424 | Args: |
| 425 | tensor1: First tensor to compare |
| 426 | tensor2: Second tensor to compare |
| 427 | atol: Absolute tolerance |
| 428 | rtol: Relative tolerance |
| 429 | max_errors: Maximum number of errors to print (default: 10) |
| 430 | """ |
| 431 | # Handle lists/tuples of tensors |
| 432 | if isinstance(tensor1, (list, tuple)) and isinstance(tensor2, (list, tuple)): |
| 433 | if len(tensor1) != len(tensor2): |
| 434 | print(f"Tensor count mismatch: {len(tensor1)} vs {len(tensor2)}") |
| 435 | return |
| 436 | |
| 437 | for i, (t1, t2) in enumerate(zip(tensor1, tensor2)): |
| 438 | print(f"\n=== Tensor {i} comparison ===") |
| 439 | print_tensor_comparison_errors(t1, t2, atol, rtol, max_errors) |
| 440 | return |
| 441 | |
| 442 | # Handle single tensor comparison |
| 443 | if not isinstance(tensor1, torch.Tensor) or not isinstance(tensor2, torch.Tensor): |
| 444 | print("Error: Both inputs must be torch.Tensor objects") |
| 445 | return |
| 446 | |
| 447 | if tensor1.shape != tensor2.shape: |
| 448 | print(f"Shape mismatch: {tensor1.shape} vs {tensor2.shape}") |
| 449 | return |
| 450 | |
| 451 | # Calculate absolute and relative errors |
| 452 | abs_diff = torch.abs(tensor1 - tensor2) |
| 453 | rel_diff = abs_diff / ( |
| 454 | torch.abs(tensor2) + 1e-8 |
| 455 | ) # Add small epsilon to avoid division by zero |
| 456 | |
| 457 | # Find locations where tolerance is exceeded |
| 458 | tolerance_mask = (abs_diff > atol) & (rel_diff > rtol) |
| 459 | |
| 460 | if not tolerance_mask.any(): |
| 461 | print("All values are within tolerance") |
| 462 | return |
| 463 | |
| 464 | # Get indices where tolerance is exceeded |
| 465 | error_indices = torch.nonzero(tolerance_mask, as_tuple=False) |
| 466 | total_errors = error_indices.shape[0] |
| 467 | |
| 468 | print(f"Found {total_errors} values exceeding tolerance (atol={atol}, rtol={rtol})") |
| 469 | print(f"Showing first {min(max_errors, total_errors)} errors:") |
| 470 | print("Index -> tensor1_value, tensor2_value, abs_error, rel_error") |
| 471 | |
| 472 | # Print first max_errors locations |
| 473 | for i in range(min(max_errors, total_errors)): |
| 474 | idx = tuple(error_indices[i].tolist()) |
no outgoing calls
no test coverage detected