import torch
import torch_npu
import ascend_ops
import pytest
def test_abs_interface_exist():
"""
Test that the 'ascend_ops.abs' operator is present in torch.ops.
This existence test asserts that the custom operator registered under the
'ascend_ops' namespace is discoverable from Python via torch.ops.ascend_ops.add.
It does not exercise operator functionality — only that the Python binding
and registration are available.
Rationale:
The presence of this test guards against a common failure mode where an
operator is implemented and registered in C++/ATen but is not exposed to
the Python torch.ops namespace due to mismatches between the PyTorch
operator schema and the C++ registration signature (argument names, types,
or overloads). Such schema/signature inconsistencies can cause the
operator to be hidden or not exported to Python, breaking consumers that
expect to call torch.ops.ascend_ops.add. This test will fail loudly if the
binding is missing, prompting investigation into schema/registration issues.
"""
print(torch.ops.ascend_ops.abs)
assert hasattr(torch.ops.ascend_ops, "abs"), "The 'abs' operator is not registered in the 'torch.ops.ascend_ops'."
SHAPES = [
(32, 32),
(100, 100),
(10, 100),
(100, 10),
(256, 512),
(1000, 1000),
]
DTYPES = [
torch.float32,
]
@pytest.mark.skipif(not torch.npu.is_available(), reason="NPU device not found")
@pytest.mark.parametrize("shape", SHAPES)
@pytest.mark.parametrize("dtype", DTYPES)
def test_abs_operator(shape, dtype):
"""
Test the functionality of the abs operator, using concise but comprehensive combinations of shapes and data types.
Parameters:
shape: Tensor shape
dtype: Data type
"""
a = torch.randn(*shape, dtype=dtype)
expected = torch.abs(a)
a_npu = a.npu()
result_npu = torch.ops.ascend_ops.abs(a_npu)
result = result_npu.cpu()
assert torch.allclose(result, expected, rtol=1e-4, atol=1e-4), \
f"Abs failed for shape {shape}, dtype {dtype}. " \
f"Max diff: {torch.max(torch.abs(result - expected)):.6f}"
print(f"✓ Test passed: shape={shape}, dtype={dtype}")