Removed PyTorch wrapper nodes. They were moved to ComfyUI-Py-Wrapper extension.

This commit is contained in:
HowToSD
2025-03-10 15:54:51 -07:00
parent 5fee9ffb60
commit 60692bf9c2
338 changed files with 6 additions and 14298 deletions
View File
-40
View File
@@ -1,40 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_abs import PtAbs # Updated import to PtAbs
class TestPtAbs(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtAbs()
# Test cases: (Tensor A, Expected result)
self.test_cases = [
(torch.tensor([-1, 2, -3, 4], dtype=torch.float32), torch.tensor([1, 2, 3, 4], dtype=torch.float32)), # Mixed positive/negative
(torch.tensor([0, -5, 10, -15], dtype=torch.int32), torch.tensor([0, 5, 10, 15], dtype=torch.int32)), # Integer case
(torch.tensor([[-1.5, 2.3], [-3.7, 4.9]], dtype=torch.float32), torch.tensor([[1.5, 2.3], [3.7, 4.9]], dtype=torch.float32)), # 2D case
(torch.tensor([[-100, 0, 50], [-25, -75, 100]], dtype=torch.int64), torch.tensor([[100, 0, 50], [25, 75, 100]], dtype=torch.int64)), # Large numbers
(torch.full((2, 2), -7.7, dtype=torch.float32), torch.full((2, 2), 7.7, dtype=torch.float32)), # Constant matrix
]
def test_absolute_value(self):
"""Test tensor element-wise absolute value using torch.abs()."""
for tens_a, expected in self.test_cases:
with self.subTest(tens_a=tens_a):
result, = self.node.f(tens_a)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected absolute value operation
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-39
View File
@@ -1,39 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_acos import PtAcos # Updated import to PtAcos
class TestPtAcos(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtAcos()
# Test cases: (Tensor A, Expected result)
self.test_cases = [
(torch.tensor([1.0, 0.0, -1.0], dtype=torch.float32), torch.acos(torch.tensor([1.0, 0.0, -1.0], dtype=torch.float32))), # Edge cases
(torch.tensor([0.5, -0.5], dtype=torch.float32), torch.acos(torch.tensor([0.5, -0.5], dtype=torch.float32))), # Common values
(torch.tensor([[0.1, -0.3], [0.7, -0.9]], dtype=torch.float32), torch.acos(torch.tensor([[0.1, -0.3], [0.7, -0.9]], dtype=torch.float32))), # 2D case
(torch.full((2, 2), 0.6, dtype=torch.float32), torch.acos(torch.full((2, 2), 0.6, dtype=torch.float32))), # Constant matrix
]
def test_acos(self):
"""Test tensor element-wise arc cosine using torch.acos()."""
for tens_a, expected in self.test_cases:
with self.subTest(tens_a=tens_a):
result, = self.node.f(tens_a)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected acos values
self.assertTrue(torch.allclose(result, expected, atol=1e-6), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-39
View File
@@ -1,39 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_add import PtAdd
class TestPtAdd(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtAdd()
# Test cases: (Tensor A, Tensor B, Expected result)
self.test_cases = [
(torch.tensor([1.0, 2.0, 3.0]), torch.tensor([4.0, 5.0, 6.0]), torch.tensor([5.0, 7.0, 9.0])),
(torch.ones(3, 3), torch.ones(3, 3), torch.full((3, 3), 2.0)),
(torch.zeros(2, 2), torch.ones(2, 2), torch.ones(2, 2)),
(torch.tensor([[1.0], [2.0]]), torch.tensor([[3.0], [4.0]]), torch.tensor([[4.0], [6.0]])),
]
def test_addition(self):
"""Test tensor addition."""
for tens_a, tens_b, expected in self.test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected sum
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-44
View File
@@ -1,44 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_arange import PtArange
class TestPtArange(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtArange()
# Test cases: (start, end, step, dtype, expected_tensor, expected_dtype)
self.test_cases = [
("0", "5", "1", "int32", torch.tensor([0, 1, 2, 3, 4], dtype=torch.int32), torch.int32), # Simple range
("-3", "3", "1", "float32", torch.tensor([-3, -2, -1, 0, 1, 2], dtype=torch.float32), torch.float32), # Negative start
("1.5", "4.5", "1", "float64", torch.tensor([1.5, 2.5, 3.5], dtype=torch.float64), torch.float64), # Floating point step
("10", "0", "-2", "int64", torch.tensor([10, 8, 6, 4, 2], dtype=torch.int64), torch.int64), # Decreasing range
("", "5", "1", "int8", torch.tensor([0, 1, 2, 3, 4], dtype=torch.int8), torch.int8), # Default start (0)
("0", "10", "", "uint8", torch.tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=torch.uint8), torch.uint8), # Default step (1)
]
def test_arange_tensor_creation(self):
"""Test tensor generation using torch.arange(), including values and dtype."""
for start, end, step, dtype, expected, expected_dtype in self.test_cases:
with self.subTest(start=start, end=end, step=step, dtype=dtype):
result, = self.node.f(start, end, step, dtype)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected tensor values
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
# Ensure result has the correct dtype
self.assertEqual(result.dtype, expected_dtype, f"Expected dtype {expected_dtype}, got {result.dtype}")
if __name__ == "__main__":
unittest.main()
-39
View File
@@ -1,39 +0,0 @@
import os
import sys
import unittest
import torch
import ast
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_argmax import PtArgmax
class TestPtArgmax(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtArgmax()
# Test cases: (Tensor, Dim (as string), keepdim, Expected result)
self.test_cases = [
(torch.tensor([[1, 3, 2], [4, 0, 5]]), "0", False, torch.tensor([1, 0, 1])),
(torch.tensor([[1, 3, 2], [4, 0, 5]]), "1", True, torch.tensor([[1], [2]])),
(torch.tensor([[10, 3, 2], [123, 0, 5]]), "", False, torch.tensor(3)),
]
def test_argmax(self):
"""Test torch.argmax behavior."""
for tens, dim, keepdim, expected in self.test_cases:
with self.subTest(tens=tens, dim=dim, keepdim=keepdim):
result, = self.node.f(tens, dim, keepdim)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected indices
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-39
View File
@@ -1,39 +0,0 @@
import os
import sys
import unittest
import torch
import ast
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_argmin import PtArgmin
class TestPtArgmin(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtArgmin()
# Test cases: (Tensor, Dim (as string), keepdim, Expected result)
self.test_cases = [
(torch.tensor([[1, 3, 2], [4, 0, 5]]), "0", False, torch.tensor([0, 1, 0])),
(torch.tensor([[1, 3, 2], [4, 0, 5]]), "1", True, torch.tensor([[0], [1]])),
(torch.tensor([[1, 3, 2], [4, 0, 5]]), "", False, torch.tensor(4)),
]
def test_argmin(self):
"""Test torch.argmin behavior."""
for tens, dim, keepdim, expected in self.test_cases:
with self.subTest(tens=tens, dim=dim, keepdim=keepdim):
result, = self.node.f(tens, dim, keepdim)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected indices
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-39
View File
@@ -1,39 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_asin import PtAsin # Updated import to PtAsin
class TestPtAsin(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtAsin()
# Test cases: (Tensor A, Expected result)
self.test_cases = [
(torch.tensor([1.0, 0.0, -1.0], dtype=torch.float32), torch.asin(torch.tensor([1.0, 0.0, -1.0], dtype=torch.float32))), # Edge cases
(torch.tensor([0.5, -0.5], dtype=torch.float32), torch.asin(torch.tensor([0.5, -0.5], dtype=torch.float32))), # Common values
(torch.tensor([[0.1, -0.3], [0.7, -0.9]], dtype=torch.float32), torch.asin(torch.tensor([[0.1, -0.3], [0.7, -0.9]], dtype=torch.float32))), # 2D case
(torch.full((2, 2), 0.6, dtype=torch.float32), torch.asin(torch.full((2, 2), 0.6, dtype=torch.float32))), # Constant matrix
]
def test_asin(self):
"""Test tensor element-wise arc sine using torch.asin()."""
for tens_a, expected in self.test_cases:
with self.subTest(tens_a=tens_a):
result, = self.node.f(tens_a)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected asin values
self.assertTrue(torch.allclose(result, expected, atol=1e-6), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-39
View File
@@ -1,39 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_atan import PtAtan # Updated import to PtAtan
class TestPtAtan(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtAtan()
# Test cases: (Tensor A, Expected result)
self.test_cases = [
(torch.tensor([1.0, 0.0, -1.0], dtype=torch.float32), torch.atan(torch.tensor([1.0, 0.0, -1.0], dtype=torch.float32))), # Edge cases
(torch.tensor([0.5, -0.5], dtype=torch.float32), torch.atan(torch.tensor([0.5, -0.5], dtype=torch.float32))), # Common values
(torch.tensor([[0.1, -0.3], [0.7, -0.9]], dtype=torch.float32), torch.atan(torch.tensor([[0.1, -0.3], [0.7, -0.9]], dtype=torch.float32))), # 2D case
(torch.full((2, 2), 0.6, dtype=torch.float32), torch.atan(torch.full((2, 2), 0.6, dtype=torch.float32))), # Constant matrix
]
def test_atan(self):
"""Test tensor element-wise arc tangent using torch.atan()."""
for tens_a, expected in self.test_cases:
with self.subTest(tens_a=tens_a):
result, = self.node.f(tens_a)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected atan values
self.assertTrue(torch.allclose(result, expected, atol=1e-6), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
@@ -1,40 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_bitwise_and import PtBitwiseAnd # Updated import to PtBitwiseAnd
class TestPtBitwiseAnd(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtBitwiseAnd()
# Test cases: (Tensor A, Tensor B, Expected result)
self.test_cases = [
(torch.tensor([0b0001, 0b0011, 0b0101]), torch.tensor([0b0001, 0b0010, 0b0110]), torch.tensor([0b0001, 0b0010, 0b0100])),
(torch.tensor([0b1111, 0b1010, 0b1100]), torch.tensor([0b0101, 0b1100, 0b1010]), torch.tensor([0b0101, 0b1000, 0b1000])),
(torch.tensor([1, 2, 3]), torch.tensor([3, 2, 1]), torch.tensor([1, 2, 1])),
(torch.ones(2, 2, dtype=torch.int32), torch.zeros(2, 2, dtype=torch.int32), torch.zeros(2, 2, dtype=torch.int32)),
(torch.full((2, 2), 0b1010, dtype=torch.int32), torch.full((2, 2), 0b1100, dtype=torch.int32), torch.full((2, 2), 0b1000, dtype=torch.int32)),
]
def test_bitwise_and(self):
"""Test tensor element-wise bitwise AND using torch.bitwise_and()."""
for tens_a, tens_b, expected in self.test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected bitwise AND operation
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
@@ -1,40 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_bitwise_left_shift import PtBitwiseLeftShift # Updated import to PtBitwiseLeftShift
class TestPtBitwiseLeftShift(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtBitwiseLeftShift()
# Test cases: (Tensor A, Tensor B, Expected result)
self.test_cases = [
(torch.tensor([1, 2, 4], dtype=torch.int64), torch.tensor([1, 2, 3], dtype=torch.int64), torch.tensor([2, 8, 32], dtype=torch.int64)), # 1<<1, 2<<2, 4<<3
(torch.tensor([4, 8, 16], dtype=torch.int64), torch.tensor([2, 1, 3], dtype=torch.int64), torch.tensor([16, 16, 128], dtype=torch.int64)), # 4<<2, 8<<1, 16<<3
(torch.tensor([0b0001, 0b0010, 0b0100], dtype=torch.int64), torch.tensor([1, 2, 3], dtype=torch.int64), torch.tensor([0b0010, 0b1000, 0b100000], dtype=torch.int64)), # Bitwise shift
(torch.ones(3, 3, dtype=torch.int64), torch.full((3, 3), 2, dtype=torch.int64), torch.full((3, 3), 4, dtype=torch.int64)), # 1<<2 = 4
(torch.full((2, 2), 5, dtype=torch.int64), torch.full((2, 2), 3, dtype=torch.int64), torch.full((2, 2), 40, dtype=torch.int64)), # 5<<3 = 40
]
def test_bitwise_left_shift(self):
"""Test tensor element-wise bitwise left shift using torch.bitwise_left_shift()."""
for tens_a, tens_b, expected in self.test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected bitwise left shift operation
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
@@ -1,40 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_bitwise_not import PtBitwiseNot # Updated import to PtBitwiseNot
class TestPtBitwiseNot(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtBitwiseNot()
# Test cases: (Tensor A, Expected result)
self.test_cases = [
(torch.tensor([0, 1, 2, 3], dtype=torch.int32), torch.tensor([-1, -2, -3, -4], dtype=torch.int32)), # Bitwise NOT
(torch.tensor([0b0000, 0b0001, 0b0010], dtype=torch.int32), torch.tensor([-1, -2, -3], dtype=torch.int32)), # Binary representation
(torch.tensor([[5, 10], [15, 20]], dtype=torch.int32), torch.tensor([[-6, -11], [-16, -21]], dtype=torch.int32)), # Matrix case
(torch.full((2, 2), 0, dtype=torch.int32), torch.full((2, 2), -1, dtype=torch.int32)), # NOT 0 -> -1
(torch.full((3, 3), -1, dtype=torch.int32), torch.full((3, 3), 0, dtype=torch.int32)), # NOT -1 -> 0
]
def test_bitwise_not(self):
"""Test tensor element-wise bitwise NOT using torch.bitwise_not()."""
for tens_a, expected in self.test_cases:
with self.subTest(tens_a=tens_a):
result, = self.node.f(tens_a)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected bitwise NOT operation
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
@@ -1,54 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_bitwise_or import PtBitwiseOr # Updated import to PtBitwiseOr
class TestPtBitwiseOr(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtBitwiseOr()
# Test cases: (Tensor A, Tensor B, Expected result)
self.test_cases = [
(torch.tensor([0b0001, 0b0011, 0b0101], dtype=torch.int32),
torch.tensor([0b0010, 0b0100, 0b0110], dtype=torch.int32),
torch.tensor([0b0011, 0b0111, 0b0111], dtype=torch.int32)), # Binary OR
(torch.tensor([1, 2, 4], dtype=torch.int32),
torch.tensor([8, 16, 32], dtype=torch.int32),
torch.tensor([9, 18, 36], dtype=torch.int32)), # Decimal OR
(torch.tensor([5, 10, 15], dtype=torch.int32),
torch.tensor([3, 6, 12], dtype=torch.int32),
torch.tensor([7, 14, 15], dtype=torch.int32)), # Mixed values
(torch.zeros(3, 3, dtype=torch.int32),
torch.ones(3, 3, dtype=torch.int32),
torch.ones(3, 3, dtype=torch.int32)), # OR with all ones
(torch.full((2, 2), 0b1010, dtype=torch.int32),
torch.full((2, 2), 0b1100, dtype=torch.int32),
torch.full((2, 2), 0b1110, dtype=torch.int32)), # OR with constant matrices
]
def test_bitwise_or(self):
"""Test tensor element-wise bitwise OR using torch.bitwise_or()."""
for tens_a, tens_b, expected in self.test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected bitwise OR operation
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
@@ -1,40 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_bitwise_right_shift import PtBitwiseRightShift # Updated import to PtBitwiseRightShift
class TestPtBitwiseRightShift(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtBitwiseRightShift()
# Test cases: (Tensor A, Tensor B, Expected result)
self.test_cases = [
(torch.tensor([4, 8, 16], dtype=torch.int64), torch.tensor([1, 2, 3], dtype=torch.int64), torch.tensor([2, 2, 2], dtype=torch.int64)), # 4>>1, 8>>2, 16>>3
(torch.tensor([32, 64, 128], dtype=torch.int64), torch.tensor([2, 3, 4], dtype=torch.int64), torch.tensor([8, 8, 8], dtype=torch.int64)), # 32>>2, 64>>3, 128>>4
(torch.tensor([0b1000, 0b10000, 0b100000], dtype=torch.int64), torch.tensor([1, 2, 3], dtype=torch.int64), torch.tensor([0b0100, 0b00100, 0b000100], dtype=torch.int64)), # Bitwise shift
(torch.full((3, 3), 16, dtype=torch.int64), torch.full((3, 3), 2, dtype=torch.int64), torch.full((3, 3), 4, dtype=torch.int64)), # 16>>2 = 4
(torch.full((2, 2), 40, dtype=torch.int64), torch.full((2, 2), 3, dtype=torch.int64), torch.full((2, 2), 5, dtype=torch.int64)), # 40>>3 = 5
]
def test_bitwise_right_shift(self):
"""Test tensor element-wise bitwise right shift using torch.bitwise_right_shift()."""
for tens_a, tens_b, expected in self.test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected bitwise right shift operation
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
@@ -1,54 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_bitwise_xor import PtBitwiseXor # Updated import to PtBitwiseXor
class TestPtBitwiseXor(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtBitwiseXor()
# Test cases: (Tensor A, Tensor B, Expected result)
self.test_cases = [
(torch.tensor([0b0001, 0b0011, 0b0101], dtype=torch.int32),
torch.tensor([0b0010, 0b0100, 0b0110], dtype=torch.int32),
torch.tensor([0b0011, 0b0111, 0b0011], dtype=torch.int32)), # Binary XOR
(torch.tensor([1, 2, 4], dtype=torch.int32),
torch.tensor([8, 16, 32], dtype=torch.int32),
torch.tensor([9, 18, 36], dtype=torch.int32)), # Decimal XOR
(torch.tensor([5, 10, 15], dtype=torch.int32),
torch.tensor([3, 6, 12], dtype=torch.int32),
torch.tensor([6, 12, 3], dtype=torch.int32)), # Mixed values
(torch.zeros(3, 3, dtype=torch.int32),
torch.ones(3, 3, dtype=torch.int32),
torch.ones(3, 3, dtype=torch.int32)), # XOR with all ones
(torch.full((2, 2), 0b1010, dtype=torch.int32),
torch.full((2, 2), 0b1100, dtype=torch.int32),
torch.full((2, 2), 0b0110, dtype=torch.int32)), # XOR with constant matrices
]
def test_bitwise_xor(self):
"""Test tensor element-wise bitwise XOR using torch.bitwise_xor()."""
for tens_a, tens_b, expected in self.test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected bitwise XOR operation
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-60
View File
@@ -1,60 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_bmm import PtBmm # Updated import to PtBmm
class TestPtBmm(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtBmm()
# Valid test cases: (Tensor A, Tensor B, Expected result)
self.valid_test_cases = [
# Case 1: Batch of 2 matrices (3x4) * (4x5) → (2, 3, 5)
(torch.ones(2, 3, 4), torch.ones(2, 4, 5), torch.full((2, 3, 5), 4.0)),
# Case 2: Batch of 3 matrices (2x3) * (3x2) → (3, 2, 2)
(torch.tensor([[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]]),
torch.tensor([[[7.0, 8.0], [9.0, 10.0], [11.0, 12.0]]]),
torch.tensor([[[58.0, 64.0], [139.0, 154.0]]])),
# Case 3: Identity matrix batch multiplication (should remain the same)
(torch.eye(3).expand(4, -1, -1), torch.eye(3).expand(4, -1, -1), torch.eye(3).expand(4, -1, -1)),
]
# Invalid test cases (should raise errors)
self.invalid_test_cases = [
(torch.ones(3, 4), torch.ones(4, 5)), # 2D tensors (not allowed)
(torch.ones(2, 3, 4), torch.ones(3, 4, 5)), # Mismatched batch size
(torch.ones(2, 3, 4, 5), torch.ones(2, 5, 6)), # 4D tensors (not allowed)
(torch.ones(2, 3, 4), torch.ones(2, 5, 6)), # Matmul shape mismatch within batch
]
def test_batched_matrix_multiplication(self):
"""Test valid batched matrix multiplication cases."""
for tens_a, tens_b, expected in self.valid_test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected batch matrix multiplication
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
def test_invalid_multiplication(self):
"""Test invalid cases where dimensions do not match."""
for tens_a, tens_b in self.invalid_test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
with self.assertRaises(Exception, msg=f"torch.bmm() should fail for shapes {tens_a.shape} and {tens_b.shape}"):
self.node.f(tens_a, tens_b)
if __name__ == "__main__":
unittest.main()
@@ -1,58 +0,0 @@
import os
import sys
import unittest
import torch
import ast
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_bool_create import PtBoolCreate
class TestPtBoolCreate(unittest.TestCase):
def setUp(self):
"""Set up test data."""
self.node = PtBoolCreate()
# Test cases covering various ranks
self.test_cases = [
# Rank 0 (scalar)
("True", torch.tensor(True, dtype=torch.bool)),
("False", torch.tensor(False, dtype=torch.bool)),
# Rank 1 (1D array)
("[True, False, True]", torch.tensor([True, False, True], dtype=torch.bool)),
# Rank 2 (2D matrix)
("[[True, False], [False, True]]", torch.tensor([[True, False], [False, True]], dtype=torch.bool)),
# Rank 3 (3D tensor)
(
"[[[True, False], [False, True]], [[False, True], [True, False]]]",
torch.tensor([[[True, False], [False, True]], [[False, True], [True, False]]], dtype=torch.bool),
),
]
def test_create_tensor(self):
"""Test PyTorch boolean tensor creation from various structured inputs."""
for data_str, expected_tensor in self.test_cases:
with self.subTest(data=data_str):
retval = self.node.f(data_str)[0]
# Ensure the returned value is a PyTorch tensor
self.assertTrue(isinstance(retval, torch.Tensor), f"Expected tensor, got {type(retval)}")
# Ensure the dtype is bool
self.assertEqual(retval.dtype, torch.bool, f"Dtype mismatch for input: {data_str}")
# Ensure the shape matches
self.assertEqual(retval.shape, expected_tensor.shape,
f"Shape mismatch for input: {data_str} (Expected {expected_tensor.shape}, got {retval.shape})")
# Ensure values match
torch.testing.assert_close(retval, expected_tensor,
msg=f"Value mismatch for input: {data_str}")
if __name__ == "__main__":
unittest.main()
-39
View File
@@ -1,39 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_cos import PtCos # Updated import to PtCos
class TestPtCos(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtCos()
# Test cases: (Tensor A, Expected result)
self.test_cases = [
(torch.tensor([0.0, torch.pi / 2, torch.pi], dtype=torch.float32), torch.cos(torch.tensor([0.0, torch.pi / 2, torch.pi], dtype=torch.float32))), # Edge cases
(torch.tensor([0.5, -0.5], dtype=torch.float32), torch.cos(torch.tensor([0.5, -0.5], dtype=torch.float32))), # Common values
(torch.tensor([[0.1, -0.3], [0.7, -0.9]], dtype=torch.float32), torch.cos(torch.tensor([[0.1, -0.3], [0.7, -0.9]], dtype=torch.float32))), # 2D case
(torch.full((2, 2), 0.6, dtype=torch.float32), torch.cos(torch.full((2, 2), 0.6, dtype=torch.float32))), # Constant matrix
]
def test_cos(self):
"""Test tensor element-wise cosine using torch.cos()."""
for tens_a, expected in self.test_cases:
with self.subTest(tens_a=tens_a):
result, = self.node.f(tens_a)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected cos values
self.assertTrue(torch.allclose(result, expected, atol=1e-6), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-39
View File
@@ -1,39 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_cosh import PtCosh # Updated import to PtCosh
class TestPtCosh(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtCosh()
# Test cases: (Tensor A, Expected result)
self.test_cases = [
(torch.tensor([0.0, 1.0, -1.0], dtype=torch.float32), torch.cosh(torch.tensor([0.0, 1.0, -1.0], dtype=torch.float32))), # Edge cases
(torch.tensor([0.5, -0.5], dtype=torch.float32), torch.cosh(torch.tensor([0.5, -0.5], dtype=torch.float32))), # Common values
(torch.tensor([[0.1, -0.3], [0.7, -0.9]], dtype=torch.float32), torch.cosh(torch.tensor([[0.1, -0.3], [0.7, -0.9]], dtype=torch.float32))), # 2D case
(torch.full((2, 2), 0.6, dtype=torch.float32), torch.cosh(torch.full((2, 2), 0.6, dtype=torch.float32))), # Constant matrix
]
def test_cosh(self):
"""Test tensor element-wise hyperbolic cosine using torch.cosh()."""
for tens_a, expected in self.test_cases:
with self.subTest(tens_a=tens_a):
result, = self.node.f(tens_a)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected cosh values
self.assertTrue(torch.allclose(result, expected, atol=1e-6), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-49
View File
@@ -1,49 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_crop import PtCrop
class TestPtCrop(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtCrop()
# Test cases: (Input tensor, Height, Width, Expected shape)
self.test_cases = [
(torch.rand(1, 3, 16, 16), 8, 8, (1, 3, 8, 8)), # Crop 4D tensor
(torch.rand(3, 16, 16), 8, 8, (3, 8, 8)), # Crop 3D tensor
(torch.rand(1, 3, 16, 16), 16, 16, (1, 3, 16, 16)), # No crop, same size
]
def test_crop(self):
"""Test tensor cropping to specific sizes."""
for tens, height, width, expected_shape in self.test_cases:
with self.subTest(height=height, width=width):
result, = self.node.f(tens, height, width)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result shape matches expected shape
self.assertEqual(result.shape, expected_shape, f"Expected shape {expected_shape}, got {result.shape}")
def test_invalid_tensor_rank(self):
"""Test that an invalid tensor rank raises an error."""
tens = torch.rand(16, 16) # 2D tensor (invalid)
with self.assertRaises(ValueError, msg="Only rank 3 or 4 tensors are supported for crop."):
self.node.f(tens, 8, 8)
def test_crop_exceeds_dimensions(self):
"""Test that cropping beyond tensor dimensions raises an error."""
tens = torch.rand(1, 3, 16, 16)
with self.assertRaises(ValueError, msg="Specified crop size exceeds tensor dimensions."):
self.node.f(tens, 32, 32)
if __name__ == "__main__":
unittest.main()
@@ -1,43 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.ptv_dataset import PtvDataset
from pytorch_wrapper.ptv_transforms_to_tensor import PtvTransformsToTensor
from pytorch_wrapper.pt_data_loader import PtDataLoader
class TestPtDataLoader(unittest.TestCase):
def setUp(self):
"""Set up test data."""
self.dataset_node = PtvDataset()
self.compose_node = PtvTransformsToTensor()
self.data_loader_node = PtDataLoader()
def test_with_transform(self):
"""Tests with transform"""
bs = 2
transform = self.compose_node.f()[0]
dataset = self.dataset_node.f("MNIST",
True, # download
"", # root
'{"train": True}',
transform=transform)[0]
train_data = self.data_loader_node.f(
dataset=dataset,
batch_size=bs,
shuffle=True,
parameters='{"num_workers":1}'
)[0]
x, y = next(iter(train_data))
self.assertEqual(x.size(), torch.Size([bs, 1, 28, 28]))
self.assertEqual(y.size(), torch.Size([bs]))
if __name__ == "__main__":
unittest.main()
-39
View File
@@ -1,39 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_div import PtDiv # Updated import to PtDiv
class TestPtDiv(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtDiv()
# Test cases: (Tensor A, Tensor B, Expected result)
self.test_cases = [
(torch.tensor([4.0, 10.0, 18.0]), torch.tensor([2.0, 5.0, 6.0]), torch.tensor([2.0, 2.0, 3.0])),
(torch.ones(3, 3), torch.ones(3, 3), torch.ones(3, 3)), # 1 / 1 = 1
(torch.full((2, 2), 4.0), torch.full((2, 2), 2.0), torch.full((2, 2), 2.0)), # 4 / 2 = 2
(torch.tensor([[6.0], [12.0]]), torch.tensor([[3.0], [4.0]]), torch.tensor([[2.0], [3.0]])), # Element-wise division
]
def test_division(self):
"""Test tensor division."""
for tens_a, tens_b, expected in self.test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected quotient
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-99
View File
@@ -1,99 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_einsum import PtEinsum # Updated import to PtEinsum
class TestPtEinsum(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtEinsum()
def test_trace_extraction(self):
"""Extract the diagonal (1,2,3,4,5) and sum it up (trace)."""
matrix = torch.tensor([[1, 0, 0, 0, 0],
[0, 2, 0, 0, 0],
[0, 0, 3, 0, 0],
[0, 0, 0, 4, 0],
[0, 0, 0, 0, 5]], dtype=torch.float32)
expected = torch.tensor(15.0) # Sum of diagonal
result, = self.node.f("ii", matrix) # Only requires `tens_a`
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
def test_diagonal_extraction(self):
"""Extract diagonal elements (1,2,3,4,5)."""
matrix = torch.tensor([[1, 0, 0, 0, 0],
[0, 2, 0, 0, 0],
[0, 0, 3, 0, 0],
[0, 0, 0, 4, 0],
[0, 0, 0, 0, 5]], dtype=torch.float32)
expected = torch.tensor([1, 2, 3, 4, 5], dtype=torch.float32)
result, = self.node.f("ii->i", matrix) # Only requires `tens_a`
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
def test_hadamard_product(self):
"""Compute Hadamard product (element-wise multiplication)."""
a = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=torch.float32)
b = torch.tensor([[9, 10, 11, 12], [13, 14, 15, 16]], dtype=torch.float32)
expected = a * b
result, = self.node.f("ij,ij->ij", a, b)
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
def test_matrix_multiplication(self):
"""Test standard matrix multiplication."""
a = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=torch.float32)
b = torch.tensor([[9, 10], [11, 12], [13, 14], [15, 16]], dtype=torch.float32)
expected = torch.mm(a, b)
result, = self.node.f("ij,jk->ik", a, b)
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
def test_3d_tensor_multiplication(self):
"""Test matrix multiplication for rank-3 tensors."""
a = torch.ones(2, 3, 4, dtype=torch.float32)
b = torch.ones(2, 4, 5, dtype=torch.float32)
expected = torch.matmul(a, b)
result, = self.node.f("bij,bjk->bik", a, b)
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
def test_4d_tensor_multiplication(self):
"""Test matrix multiplication for rank-4 tensors."""
a = torch.ones(2, 3, 4, 6, dtype=torch.float32) # (batch, groups, rows, cols)
b = torch.ones(2, 3, 6, 5, dtype=torch.float32) # (batch, groups, cols, out_features)
expected = torch.matmul(a, b) # Standard 4D matrix multiplication
result, = self.node.f("bijk,bikl->bijl", a, b) # Correct einsum notation
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
def test_bilinear_transformation(self):
"""Test bilinear transformation: a vector, W matrix, and b vector."""
a = torch.tensor([1, 2, 3, 4, 5], dtype=torch.float32)
W = torch.tensor([[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]], dtype=torch.float32)
b = torch.tensor([31, 32, 33, 34, 35], dtype=torch.float32)
expected = torch.dot(a, torch.matmul(W, b))
result, = self.node.f("i,ij,j->", a, W, b)
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
def test_tensor_format_conversion(self):
"""Test conversion from (B, C, H, W) format to (B, H, W, C) format."""
a = torch.randn(2, 3, 64, 64, dtype=torch.float32) # (Batch, Channels, Height, Width)
expected = a.permute(0, 2, 3, 1) # Convert to (Batch, Height, Width, Channels)
result, = self.node.f("bchw->bhwc", a) # Correct einsum notation for format swap
self.assertTrue(torch.equal(result, expected), f"Expected {expected.shape}, got {result.shape}")
if __name__ == "__main__":
unittest.main()
-40
View File
@@ -1,40 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_eq import PtEq # Updated import to PtEq
class TestPtEq(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtEq()
# Test cases: (Tensor A, Tensor B, Expected result)
self.test_cases = [
(torch.tensor([1, 2, 3]), torch.tensor([1, 2, 3]), torch.tensor([True, True, True])),
(torch.tensor([1, 2, 3]), torch.tensor([3, 2, 1]), torch.tensor([False, True, False])),
(torch.ones(3, 3), torch.ones(3, 3), torch.full((3, 3), True, dtype=torch.bool)),
(torch.zeros(2, 2), torch.ones(2, 2), torch.full((2, 2), False, dtype=torch.bool)),
(torch.tensor([[1], [2]]), torch.tensor([[1], [3]]), torch.tensor([[True], [False]])),
]
def test_equality(self):
"""Test tensor element-wise equality using torch.eq()."""
for tens_a, tens_b, expected in self.test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected element-wise equality
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
@@ -1,83 +0,0 @@
import os
import sys
import unittest
import torch
import torch.nn as nn
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.ptn_conv_model import PtnConvModel
from pytorch_wrapper.ptv_dataset import PtvDataset
from pytorch_wrapper.ptv_transforms_to_tensor import PtvTransformsToTensor
from pytorch_wrapper.pt_data_loader import PtDataLoader
from pytorch_wrapper.pt_evaluate_classification_model import PtEvaluateClassificationModel
from pytorch_wrapper.pt_load_model import PtLoadModel
class TestPtEvaluate(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
# Transform
compose_node = PtvTransformsToTensor()
transform = compose_node.f()[0]
# Dataset
dataset_node = PtvDataset()
dataset = dataset_node.f("FashionMNIST",
True, # download
"", # root
'{"train": False}',
transform=transform)[0]
# Data loader
data_loader_node = PtDataLoader()
self.data_loader = data_loader_node.f(
dataset=dataset,
batch_size=32,
shuffle=True,
parameters='{"num_workers":1}'
)[0]
# Model
self.model_node = PtnConvModel()
self.model = self.model_node.f(
input_dim="(1, 28, 28)",
penultimate_dim=0,
output_dim=10,
channel_list="[32,64,128,256]",
kernel_size_list="[3,3,3,3]",
padding_list="[1,1,1,1]",
downsample_list="[True,True,True,True]"
)[0]
# Load weights
self.load_model = PtLoadModel()
epochs = 1
self.loaded_model = self.load_model.f(self.model, f"fashion_mnist_{epochs}_epochs_conv.pt")
# Instantiates evaluation node
self.evaluate = PtEvaluateClassificationModel()
def test_evaluation(self):
"""
Tests evaluation.
Note that this test requires a trained model file on the file system.
Unit test will fail if you run this for the first time.
Run the unit test for training to generate the weight, and re-run this unit test.
"""
accuracy, precision, recall, f1, num_samples = \
self.evaluate.f(self.model, self.data_loader, use_gpu=True)
print(f"""
accuracy: {accuracy}
precision: {precision}
recall: {recall}
f1: {f1}
Number of samples: {num_samples}
""")
self.assertTrue(accuracy > 0.8)
self.assertEqual(num_samples, 10000)
if __name__ == "__main__":
unittest.main()
@@ -1,83 +0,0 @@
import os
import sys
import unittest
import torch
import torch.nn as nn
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.ptn_conv_model import PtnConvModel
from pytorch_wrapper.ptv_image_folder_dataset import PtvImageFolderDataset
from pytorch_wrapper.ptv_transforms_resize import PtvTransformsResize
from pytorch_wrapper.pt_data_loader import PtDataLoader
from pytorch_wrapper.pt_evaluate_classification_model import PtEvaluateClassificationModel
from pytorch_wrapper.pt_load_model import PtLoadModel
class TestPtEvaluate(unittest.TestCase):
@unittest.skipIf(os.getenv("RUN_SKIPPED_TESTS") != "1", "Skipping unless explicitly enabled")
def setUp(self):
"""Set up test instance."""
# Transform
compose_node = PtvTransformsResize()
transform = compose_node.f(256, 256)[0]
# Dataset
self.node = PtvImageFolderDataset()
dataset = self.node.f("dog_and_cat/val",
transform=transform)[0]
# Data loader
data_loader_node = PtDataLoader()
self.data_loader = data_loader_node.f(
dataset=dataset,
batch_size=32,
shuffle=True,
parameters='{"num_workers":1}'
)[0]
# Model
self.model_node = PtnConvModel()
self.model = self.model_node.f(
input_dim="(3, 256, 256)",
penultimate_dim=0,
output_dim=2,
channel_list="[32,64,128,256,512]", # To 128, 64, 32, 16, 8
kernel_size_list="[3,3,3,3,3]",
padding_list="[1,1,1,1,1]",
downsample_list="[True,True,True,True,True]"
)[0]
# Load weights
self.load_model = PtLoadModel()
epochs = 20
self.loaded_model = self.load_model.f(self.model,f"dog_cat_{epochs}_epochs_conv.pt")
# Instantiates evaluation node
self.evaluate = PtEvaluateClassificationModel()
@unittest.skipIf(os.getenv("RUN_SKIPPED_TESTS") != "1", "Skipping unless explicitly enabled")
def test_evaluation(self):
"""
Tests evaluation.
Note that this test requires a trained model file on the file system.
Unit test will fail if you run this for the first time.
Run the unit test for training to generate the weight, and re-run this unit test.
"""
accuracy, precision, recall, f1, num_samples = \
self.evaluate.f(self.model, self.data_loader, use_gpu=True)
print(f"""
accuracy: {accuracy}
precision: {precision}
recall: {recall}
f1: {f1}
Number of samples: {num_samples}
""")
self.assertTrue(accuracy > 0.7)
self.assertEqual(num_samples, 300)
if __name__ == "__main__":
unittest.main()
@@ -1,79 +0,0 @@
import os
import sys
import unittest
import torch
import torch.nn as nn
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.ptn_linear_model import PtnLinearModel
from pytorch_wrapper.ptv_dataset import PtvDataset
from pytorch_wrapper.ptv_transforms_to_tensor import PtvTransformsToTensor
from pytorch_wrapper.pt_data_loader import PtDataLoader
from pytorch_wrapper.pt_evaluate_classification_model import PtEvaluateClassificationModel
from pytorch_wrapper.pt_load_model import PtLoadModel
class TestPtEvaluate(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
# Transform
compose_node = PtvTransformsToTensor()
transform = compose_node.f()[0]
# Dataset
dataset_node = PtvDataset()
dataset = dataset_node.f("FashionMNIST",
True, # download
"", # root
'{"train": False}',
transform=transform)[0]
# Data loader
data_loader_node = PtDataLoader()
self.data_loader = data_loader_node.f(
dataset=dataset,
batch_size=32,
shuffle=True,
parameters='{"num_workers":1}'
)[0]
# Model
self.model_node = PtnLinearModel()
self.model = self.model_node.f(
"784,180,42,10", # input dim for first layer, output dim for each layer
"True,True,True", # bias
3 # num layers
)[0]
# Load weights
self.load_model = PtLoadModel()
epochs = 1
self.loaded_model = self.load_model.f(self.model, f"fashion_mnist_{epochs}_epochs.pt")
# Instntiates evaluation node
self.evaluate = PtEvaluateClassificationModel()
def test_evaluation(self):
"""
Tests evaluation.
Note that this test requires a trained model file on the file system.
Unit test will fail if you run this for the first time.
Run the unit test for training to generate the weight, and re-run this unit test.
"""
accuracy, precision, recall, f1, num_samples = \
self.evaluate.f(self.model, self.data_loader, use_gpu=True)
print(f"""
accuracy: {accuracy}
precision: {precision}
recall: {recall}
f1: {f1}
Number of samples: {num_samples}
""")
self.assertTrue(accuracy > 0.8)
self.assertEqual(num_samples, 10000)
if __name__ == "__main__":
unittest.main()
-39
View File
@@ -1,39 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_exp import PtExp # Updated import to PtExp
class TestPtExp(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtExp()
# Test cases: (Tensor A, Expected result)
self.test_cases = [
(torch.tensor([0.0, 1.0, 2.0], dtype=torch.float32), torch.exp(torch.tensor([0.0, 1.0, 2.0], dtype=torch.float32))), # Edge cases
(torch.tensor([-1.0, -2.0, 0.5], dtype=torch.float32), torch.exp(torch.tensor([-1.0, -2.0, 0.5], dtype=torch.float32))), # Common values
(torch.tensor([[0.1, -0.3], [0.7, -0.9]], dtype=torch.float32), torch.exp(torch.tensor([[0.1, -0.3], [0.7, -0.9]], dtype=torch.float32))), # 2D case
(torch.full((2, 2), 0.6, dtype=torch.float32), torch.exp(torch.full((2, 2), 0.6, dtype=torch.float32))), # Constant matrix
]
def test_exp(self):
"""Test tensor element-wise exponential function using torch.exp()."""
for tens_a, expected in self.test_cases:
with self.subTest(tens_a=tens_a):
result, = self.node.f(tens_a)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected exp values
self.assertTrue(torch.allclose(result, expected, atol=1e-6), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-39
View File
@@ -1,39 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_flatten import PtFlatten
class TestPtFlatten(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtFlatten()
# Test cases: (Input tensor, Expected flattened tensor shape)
self.test_cases = [
(torch.randn(3, 4, 5), (60,)), # 3D Tensor
(torch.randn(2, 3, 4, 5), (120,)), # 4D Tensor
(torch.randn(10, 10), (100,)), # 2D Tensor
(torch.randn(1), (1,)), # 1D Tensor remains unchanged
]
def test_flatten(self):
"""Test flattening tensors correctly."""
for tensor, expected_shape in self.test_cases:
with self.subTest(tensor_shape=tensor.shape):
flattened, = self.node.f(tensor)
# Ensure return value is a tensor
self.assertTrue(isinstance(flattened, torch.Tensor), "Output is not a tensor")
# Ensure shape matches expected flattened shape
self.assertEqual(flattened.shape, expected_shape, f"Shape mismatch: expected {expected_shape}, got {flattened.shape}")
if __name__ == "__main__":
unittest.main()
@@ -1,65 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_float_create import PtFloatCreate
class TestPtFloatCreate(unittest.TestCase):
def setUp(self):
"""Set up test data."""
self.node = PtFloatCreate()
# Test cases covering rank 0 (scalar) to rank 5 tensors
self.test_cases = [
# Rank 0 (scalar)
("12345", torch.tensor(12345, dtype=torch.float32)),
("12345.6", torch.tensor(12345.6, dtype=torch.float32)),
# Rank 1 (1D array)
("[1, 2, 3]", torch.tensor([1, 2, 3], dtype=torch.float32)),
("[1.1, 2.2, 3.3]", torch.tensor([1.1, 2.2, 3.3], dtype=torch.float32)),
# Rank 2 (2D matrix)
("[[1, 2, 3], [4, 5, 6]]", torch.tensor([[1, 2, 3], [4, 5, 6]], dtype=torch.float32)),
("[[1.1, 2.2], [3.3, 4.4]]", torch.tensor([[1.1, 2.2], [3.3, 4.4]], dtype=torch.float32)),
# Rank 3 (3D tensor)
("[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]",
torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], dtype=torch.float32)),
# Rank 4 (4D tensor)
("[[[[1, 2], [3, 4]]], [[[5, 6], [7, 8]]]]",
torch.tensor([[[[1, 2], [3, 4]]], [[[5, 6], [7, 8]]]], dtype=torch.float32)),
# Rank 5 (5D tensor)
("[[[[[1], [2]], [[3], [4]]]], [[[[5], [6]], [[7], [8]]]]]",
torch.tensor([[[[[1], [2]], [[3], [4]]]], [[[[5], [6]], [[7], [8]]]]], dtype=torch.float32)),
]
def test_create_tensor(self):
"""Test PyTorch tensor creation from various structured inputs."""
for data_str, expected_tensor in self.test_cases:
with self.subTest(data=data_str):
retval = self.node.f(data_str)[0]
# Ensure the returned value is a PyTorch tensor
self.assertTrue(isinstance(retval, torch.Tensor), f"Expected tensor, got {type(retval)}")
# Ensure the dtype is float32
self.assertEqual(retval.dtype, torch.float32, f"Dtype mismatch for input: {data_str}")
# Ensure the shape matches
self.assertEqual(retval.shape, expected_tensor.shape,
f"Shape mismatch for input: {data_str} (Expected {expected_tensor.shape}, got {retval.shape})")
# Ensure values match
torch.testing.assert_close(retval, expected_tensor,
msg=f"Value mismatch for input: {data_str}")
if __name__ == "__main__":
unittest.main()
@@ -1,39 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_floor_divide import PtFloorDiv
class TestPtFloorDiv(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtFloorDiv()
# Test cases: (Tensor A, Tensor B, Expected result)
self.test_cases = [
(torch.tensor([4.0, 10.0, 18.0]), torch.tensor([3.0, 4.0, 5.0]), torch.tensor([1.0, 2.0, 3.0])),
(torch.ones(3, 3) * 7, torch.ones(3, 3) * 3, torch.ones(3, 3) * 2), # 7 // 3 = 2
(torch.full((2, 2), 9.0), torch.full((2, 2), 2.0), torch.full((2, 2), 4.0)), # 9 // 2 = 4
(torch.tensor([[7.0], [15.0]]), torch.tensor([[2.0], [4.0]]), torch.tensor([[3.0], [3.0]])), # Element-wise floor division
]
def test_floor_division(self):
"""Test tensor floor division."""
for tens_a, tens_b, expected in self.test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected floor quotient
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
@@ -1,57 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_from_image_transpose import PtFromImageTranspose
class TestPtFromImageTranspose(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtFromImageTranspose()
# Define test cases: (input_tensor, expected_shape)
self.test_cases = [
# Case 1: 3D tensor (H, W, C) -> (C, H, W)
(torch.ones(64, 128, 3), (3, 64, 128)), # (64,128,3) -> (3,64,128)
# Case 2: 4D tensor (N, H, W, C) -> (N, C, H, W)
(torch.ones(10, 64, 128, 3), (10, 3, 64, 128)), # (10,64,128,3) -> (10,3,64,128)
# Case 3: Invalid input (2D tensor)
(torch.ones(64, 128), ValueError), # 2D tensors should raise an error
# Case 4: Invalid input (5D tensor)
(torch.ones(10, 64, 128, 3, 2), ValueError), # 5D tensors should raise an error
]
def test_transpose(self):
"""Test image transposition operation with valid and invalid cases."""
for input_tensor, expected in self.test_cases:
with self.subTest(input_shape=input_tensor.shape):
if isinstance(expected, tuple):
# Valid cases
result, = self.node.f(input_tensor)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result has correct shape
self.assertEqual(result.shape, torch.Size(expected), f"Expected shape {expected}, got {result.shape}")
# Ensure result has the same dtype
self.assertEqual(result.dtype, input_tensor.dtype, "Dtype mismatch after transpose operation")
else:
# Invalid cases should raise an error
with self.assertRaises(expected):
self.node.f(input_tensor)
if __name__ == "__main__":
unittest.main()
@@ -1,65 +0,0 @@
import os
import sys
import unittest
import torch
import numpy as np
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_from_numpy import PtFromNumpy
class TestPtFromNumpy(unittest.TestCase):
def setUp(self):
"""Set up test data."""
self.node = PtFromNumpy()
# Test cases covering rank 0 (scalar) to rank 3 tensors
self.test_cases = [
# Rank 0 (scalar) int32
(np.array(12345, dtype=np.int32), torch.tensor(12345, dtype=torch.int32)),
# Rank 0 (scalar) float32
(np.array(12345.6, dtype=np.float32), torch.tensor(12345.6, dtype=torch.float32)),
# Rank 1 (1D array) int32
(np.array([1, 2, 3], dtype=np.int32), torch.tensor([1, 2, 3], dtype=torch.int32)),
# Rank 1 (1D array) float32
(np.array([1.1, 2.2, 3.3], dtype=np.float32), torch.tensor([1.1, 2.2, 3.3], dtype=torch.float32)),
# Rank 2 (2D matrix) int32
(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32), torch.tensor([[1, 2, 3], [4, 5, 6]], dtype=torch.int32)),
# Rank 2 (2D matrix) float32
(np.array([[1.1, 2.2], [3.3, 4.4]], dtype=np.float32), torch.tensor([[1.1, 2.2], [3.3, 4.4]], dtype=torch.float32)),
# Rank 3 (3D tensor) int32
(np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], dtype=np.int32),
torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], dtype=torch.int32)),
# Rank 3 (3D tensor) float32
(np.array([[[1.1, 2.2], [3.3, 4.4]], [[5.5, 6.6], [7.7, 8.8]]], dtype=np.float32),
torch.tensor([[[1.1, 2.2], [3.3, 4.4]], [[5.5, 6.6], [7.7, 8.8]]], dtype=torch.float32)),
]
def test_convert_numpy_to_tensor(self):
"""Test conversion of NumPy ndarray to PyTorch tensor."""
for np_array, expected_tensor in self.test_cases:
with self.subTest(data=np_array):
retval = self.node.f(np_array)[0]
# Ensure the returned value is a PyTorch tensor
self.assertTrue(isinstance(retval, torch.Tensor), f"Expected tensor, got {type(retval)}")
# Ensure the dtype matches
self.assertEqual(retval.dtype, expected_tensor.dtype, f"Dtype mismatch for input: {np_array}")
# Ensure the shape matches
self.assertEqual(retval.shape, expected_tensor.shape,
f"Shape mismatch for input: {np_array} (Expected {expected_tensor.shape}, got {retval.shape})")
# Ensure values match
torch.testing.assert_close(retval, expected_tensor,
msg=f"Value mismatch for input: {np_array}")
if __name__ == "__main__":
unittest.main()
-71
View File
@@ -1,71 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_full import PtFull
from pytorch_wrapper.utils import DTYPE_MAPPING
class TestPtFull(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtFull()
# Tensor size to test
self.size_str = "[2, 3]" # Using a small 2D tensor size for all tests
self.expected_shape = (2, 3)
# Values to test (using representative values for each type)
self.test_values = {
"float32": "1.5",
"float16": "-2.3",
"bfloat16": "3.7",
"float64": "4.9",
"uint8": "255", # Max value for uint8
"int8": "-128", # Min value for int8
"int16": "32767", # Max value for int16
"int32": "-2147483648", # Min value for int32
"int64": "9223372036854775807", # Max value for int64
"bool": "True"
}
def test_full_tensor_all_dtypes(self):
"""Test tensor creation with a specified value for all supported data types."""
for data_type, torch_dtype in DTYPE_MAPPING.items():
value_str = self.test_values[data_type]
with self.subTest(data_type=data_type, value=value_str):
result, = self.node.f(value_str, self.size_str, data_type)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result has correct shape
self.assertEqual(result.shape, torch.Size(self.expected_shape), f"Expected shape {self.expected_shape}, got {result.shape}")
# Ensure result has correct dtype
self.assertEqual(result.dtype, torch_dtype, f"Expected dtype {torch_dtype}, got {result.dtype}")
# Convert value_str to correct type
if torch_dtype in {torch.float32, torch.float16, torch.bfloat16, torch.float64}:
expected_value = float(value_str)
elif torch_dtype in {torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64}:
expected_value = int(value_str)
elif torch_dtype == torch.bool:
expected_value = value_str.lower() == "true"
else:
raise ValueError(f"Unsupported data type: {data_type}")
# Ensure all elements match the expected value
expected = torch.full(self.expected_shape, expected_value, dtype=torch_dtype)
self.assertTrue(torch.equal(result, expected), f"Tensor values do not match expected tensor for dtype {data_type}")
if __name__ == "__main__":
unittest.main()
-48
View File
@@ -1,48 +0,0 @@
import os
import sys
import unittest
import torch
import ast
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_gather import PtGather
class TestPtGather(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtGather()
# Test cases: (Tensor, Dim, Index (as string), Expected result)
self.test_cases = [
(
torch.tensor([[10, 20, 30, 40, 50], [100, 200, 300, 400, 500]]),
1,
"[[0, 4, 3, 2, 0], [4, 3, 0, 0, 0]]",
torch.tensor([[10, 50, 40, 30, 10], [500, 400, 100, 100, 100]])
),
(
torch.tensor([[1, 2], [3, 4]]),
0,
"[[1, 0], [0, 1]]",
torch.tensor([[3, 2], [1, 4]])
),
]
def test_gather(self):
"""Test torch.gather behavior."""
for tens, dim, index, expected in self.test_cases:
with self.subTest(tens=tens, dim=dim, index=index):
result, = self.node.f(tens, dim, index)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected gathered values
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-40
View File
@@ -1,40 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_ge import PtGe # Updated import to PtGe
class TestPtGe(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtGe()
# Test cases: (Tensor A, Tensor B, Expected result)
self.test_cases = [
(torch.tensor([1, 2, 3]), torch.tensor([0, 2, 4]), torch.tensor([True, True, False])),
(torch.tensor([3, 5, 7]), torch.tensor([1, 5, 10]), torch.tensor([True, True, False])),
(torch.ones(3, 3), torch.ones(3, 3), torch.full((3, 3), True, dtype=torch.bool)),
(torch.zeros(2, 2), torch.ones(2, 2), torch.full((2, 2), False, dtype=torch.bool)),
(torch.tensor([[5], [10]]), torch.tensor([[5], [10]]), torch.tensor([[True], [True]])),
]
def test_greater_or_equal(self):
"""Test tensor element-wise greater-than-or-equal condition using torch.ge()."""
for tens_a, tens_b, expected in self.test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected greater-than-or-equal comparison
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-40
View File
@@ -1,40 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_gt import PtGt # Updated import to PtGt
class TestPtGt(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtGt()
# Test cases: (Tensor A, Tensor B, Expected result)
self.test_cases = [
(torch.tensor([1, 2, 3]), torch.tensor([0, 2, 4]), torch.tensor([True, False, False])),
(torch.tensor([3, 5, 7]), torch.tensor([1, 5, 10]), torch.tensor([True, False, False])),
(torch.ones(3, 3), torch.zeros(3, 3), torch.full((3, 3), True, dtype=torch.bool)),
(torch.zeros(2, 2), torch.ones(2, 2), torch.full((2, 2), False, dtype=torch.bool)),
(torch.tensor([[5], [10]]), torch.tensor([[3], [10]]), torch.tensor([[True], [False]])),
]
def test_greater_than(self):
"""Test tensor element-wise greater-than condition using torch.gt()."""
for tens_a, tens_b, expected in self.test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected greater-than comparison
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
@@ -1,48 +0,0 @@
import os
import sys
import unittest
import torch
import ast
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_index_select import PtIndexSelect
class TestPtIndexSelect(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtIndexSelect()
# Test cases: (Tensor, Dim, Index (as string), Expected result)
self.test_cases = [
(
torch.tensor([[1, 2, 3], [40, 50, 60], [700, 800, 900]]),
0,
"[0, 2]",
torch.tensor([[1, 2, 3], [700, 800, 900]])
),
(
torch.tensor([[1, 2, 3], [40, 50, 60], [700, 800, 900]]),
1,
"[1, 2]",
torch.tensor([[2, 3], [50, 60], [800, 900]])
),
]
def test_index_select(self):
"""Test torch.index_select behavior."""
for tens, dim, index, expected in self.test_cases:
with self.subTest(tens=tens, dim=dim, index=index):
result, = self.node.f(tens, dim, index)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected selected values
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
@@ -1,62 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_int_create import PtIntCreate
class TestPtIntCreate(unittest.TestCase):
def setUp(self):
"""Set up test data."""
self.node = PtIntCreate()
# Test cases covering rank 0 (scalar) to rank 5 tensors
self.test_cases = [
# Rank 0 (scalar)
("12345", torch.tensor(12345, dtype=torch.int32)),
# Rank 1 (1D array)
("[1, 2, 3]", torch.tensor([1, 2, 3], dtype=torch.int32)),
# Rank 2 (2D matrix)
("[[1, 2, 3], [4, 5, 6]]", torch.tensor([[1, 2, 3], [4, 5, 6]], dtype=torch.int32)),
# Rank 3 (3D tensor)
("[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]",
torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], dtype=torch.int32)),
# Rank 4 (4D tensor)
("[[[[1, 2], [3, 4]]], [[[5, 6], [7, 8]]]]",
torch.tensor([[[[1, 2], [3, 4]]], [[[5, 6], [7, 8]]]], dtype=torch.int32)),
# Rank 5 (5D tensor)
("[[[[[1], [2]], [[3], [4]]]], [[[[5], [6]], [[7], [8]]]]]",
torch.tensor([[[[[1], [2]], [[3], [4]]]], [[[[5], [6]], [[7], [8]]]]], dtype=torch.int32)),
]
def test_create_tensor(self):
"""Test PyTorch tensor creation from various structured inputs."""
for data_str, expected_tensor in self.test_cases:
with self.subTest(data=data_str):
retval = self.node.f(data_str)[0]
# Ensure the returned value is a PyTorch tensor
self.assertTrue(isinstance(retval, torch.Tensor), f"Expected tensor, got {type(retval)}")
# Ensure the dtype is int32
self.assertEqual(retval.dtype, torch.int32, f"Dtype mismatch for input: {data_str}")
# Ensure the shape matches
self.assertEqual(retval.shape, expected_tensor.shape,
f"Shape mismatch for input: {data_str} (Expected {expected_tensor.shape}, got {retval.shape})")
# Ensure values match
torch.testing.assert_close(retval, expected_tensor,
msg=f"Value mismatch for input: {data_str}")
if __name__ == "__main__":
unittest.main()
@@ -1,60 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_interpolate_by_scale_factor import PtInterpolateByScaleFactor
class TestPtInterpolateByScaleFactor(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtInterpolateByScaleFactor()
# Test cases 3d: (Input tensor, Scale factor, Mode, Expected shape)
self.test_cases_3d = [
(torch.rand(3, 16, 16), 2.0, "nearest", (3, 32, 32)),
(torch.rand(3, 16, 16), 2.0, "nearest-exact", (3, 32, 32)),
(torch.rand(3, 16, 16), 0.5, "bilinear", (3, 8, 8)),
(torch.rand(3, 16, 16), 1.5, "bicubic", (3, 24, 24)),
]
# Test cases: (Input tensor, Scale factor, Mode, Expected shape)
self.test_cases_4d = [
(torch.rand(1, 3, 16, 16), 2.0, "nearest", (1, 3, 32, 32)), # Upscale 4D tensor
(torch.rand(1, 3, 16, 16), 2.0, "nearest-exact", (1, 3, 32, 32)), # Upscale 4D tensor
(torch.rand(1, 3, 16, 16), 0.5, "bilinear", (1, 3, 8, 8)), # Downscale 4D tensor
(torch.rand(1, 3, 16, 16), 1.5, "bicubic", (1, 3, 24, 24)), # Bicubic mode with 4D tensor
]
def test_interpolation_3d(self):
"""Test tensor interpolation with different scale factors and modes."""
for tens, scale_factor, mode, expected_shape in self.test_cases_3d:
with self.subTest(scale_factor=scale_factor, mode=mode):
result, = self.node.f(tens, scale_factor, mode)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result shape matches expected shape
self.assertEqual(result.shape, expected_shape, f"Expected shape {expected_shape}, got {result.shape}")
def test_interpolation_4d(self):
"""Test tensor interpolation with different scale factors and modes."""
for tens, scale_factor, mode, expected_shape in self.test_cases_4d:
with self.subTest(scale_factor=scale_factor, mode=mode):
result, = self.node.f(tens, scale_factor, mode)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result shape matches expected shape
self.assertEqual(result.shape, expected_shape, f"Expected shape {expected_shape}, got {result.shape}")
if __name__ == "__main__":
unittest.main()
@@ -1,61 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_interpolate_to_size import PtInterpolateToSize
class TestPtInterpolateToSize(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtInterpolateToSize()
# Test cases 3d: (Input tensor, Height, Width, Mode, Expected shape)
self.test_cases_3d = [
(torch.rand(3, 16, 16), 32, 32, "nearest", (3, 32, 32)), # Upscale 3D tensor
(torch.rand(3, 16, 16), 32, 32, "nearest-exact", (3, 32, 32)), # Upscale 3D tensor
(torch.rand(3, 16, 16), 8, 8, "bilinear", (3, 8, 8)), # Downscale 3D tensor
(torch.rand(3, 16, 16), 24, 24, "bicubic", (3, 24, 24)), # Bicubic mode with 3D tensor
]
# Test cases 4d: (Input tensor, Height, Width, Mode, Expected shape)
self.test_cases_4d = [
(torch.rand(1, 3, 16, 16), 32, 32, "nearest", (1, 3, 32, 32)), # Upscale 4D tensor
(torch.rand(1, 3, 16, 16), 32, 32, "nearest-exact", (1, 3, 32, 32)), # Upscale 4D tensor
(torch.rand(1, 3, 16, 16), 8, 8, "bilinear", (1, 3, 8, 8)), # Downscale 4D tensor
(torch.rand(1, 3, 16, 16), 24, 24, "bicubic", (1, 3, 24, 24)), # Bicubic mode with 4D tensor
]
def test_interpolation_3d(self):
"""Test tensor interpolation with different target sizes and modes."""
for tens, height, width, mode, expected_shape in self.test_cases_3d:
with self.subTest(height=height, width=width, mode=mode):
result, = self.node.f(tens, height, width, mode)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result shape matches expected shape
self.assertEqual(result.shape, expected_shape, f"Expected shape {expected_shape}, got {result.shape}")
def test_interpolation_4d(self):
"""Test tensor interpolation with different target sizes and modes."""
for tens, height, width, mode, expected_shape in self.test_cases_4d:
with self.subTest(height=height, width=width, mode=mode):
result, = self.node.f(tens, height, width, mode)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result shape matches expected shape
self.assertEqual(result.shape, expected_shape, f"Expected shape {expected_shape}, got {result.shape}")
if __name__ == "__main__":
unittest.main()
-40
View File
@@ -1,40 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_le import PtLe # Updated import to PtLe
class TestPtLe(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtLe()
# Test cases: (Tensor A, Tensor B, Expected result)
self.test_cases = [
(torch.tensor([1, 2, 3]), torch.tensor([0, 2, 4]), torch.tensor([False, True, True])),
(torch.tensor([3, 5, 7]), torch.tensor([1, 5, 10]), torch.tensor([False, True, True])),
(torch.ones(3, 3), torch.ones(3, 3), torch.full((3, 3), True, dtype=torch.bool)),
(torch.zeros(2, 2), torch.ones(2, 2), torch.full((2, 2), True, dtype=torch.bool)),
(torch.tensor([[5], [10]]), torch.tensor([[5], [10]]), torch.tensor([[True], [True]])),
]
def test_less_or_equal(self):
"""Test tensor element-wise less-than-or-equal condition using torch.le()."""
for tens_a, tens_b, expected in self.test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected less-than-or-equal comparison
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-43
View File
@@ -1,43 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_linspace import PtLinspace
class TestPtLinspace(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtLinspace()
# Test cases: (start, end, steps, dtype, expected_tensor, expected_dtype)
self.test_cases = [
("0", "10", "5", "float32", torch.tensor([0, 2.5, 5, 7.5, 10], dtype=torch.float32), torch.float32), # Basic float32 case
("-5", "5", "6", "float64", torch.tensor([-5, -3, -1, 1, 3, 5], dtype=torch.float64), torch.float64), # Negative to positive
("1", "2", "3", "float16", torch.tensor([1, 1.5, 2], dtype=torch.float16), torch.float16), # Small float16 case
("100", "200", "5", "int32", torch.tensor([100, 125, 150, 175, 200], dtype=torch.int32), torch.int32), # Large int32 case
("0", "1", "2", "bfloat16", torch.tensor([0, 1], dtype=torch.bfloat16), torch.bfloat16), # Simple two-step bfloat16
]
def test_linspace_tensor_creation(self):
"""Test tensor generation using torch.linspace(), including values and dtype."""
for start, end, steps, dtype, expected, expected_dtype in self.test_cases:
with self.subTest(start=start, end=end, steps=steps, dtype=dtype):
result, = self.node.f(start, end, steps, dtype)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected tensor values
self.assertTrue(torch.allclose(result, expected, atol=1e-5), f"Expected {expected}, got {result}")
# Ensure result has the correct dtype
self.assertEqual(result.dtype, expected_dtype, f"Expected dtype {expected_dtype}, got {result.dtype}")
if __name__ == "__main__":
unittest.main()
-39
View File
@@ -1,39 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_log import PtLog # Updated import to PtLog
class TestPtLog(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtLog()
# Test cases: (Tensor A, Expected result)
self.test_cases = [
(torch.tensor([1.0, torch.e, 10.0], dtype=torch.float32), torch.log(torch.tensor([1.0, torch.e, 10.0], dtype=torch.float32))), # Edge cases
(torch.tensor([0.5, 2.0, 3.0], dtype=torch.float32), torch.log(torch.tensor([0.5, 2.0, 3.0], dtype=torch.float32))), # Common values
(torch.tensor([[1.5, 3.2], [4.7, 5.9]], dtype=torch.float32), torch.log(torch.tensor([[1.5, 3.2], [4.7, 5.9]], dtype=torch.float32))), # 2D case
(torch.full((2, 2), 2.5, dtype=torch.float32), torch.log(torch.full((2, 2), 2.5, dtype=torch.float32))), # Constant matrix
]
def test_log(self):
"""Test tensor element-wise natural logarithm using torch.log()."""
for tens_a, expected in self.test_cases:
with self.subTest(tens_a=tens_a):
result, = self.node.f(tens_a)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected log values
self.assertTrue(torch.allclose(result, expected, atol=1e-6), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
@@ -1,40 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_logical_and import PtLogicalAnd # Updated import to PtLogicalAnd
class TestPtLogicalAnd(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtLogicalAnd()
# Test cases: (Tensor A, Tensor B, Expected result)
self.test_cases = [
(torch.tensor([True, False, True]), torch.tensor([False, False, True]), torch.tensor([False, False, True])),
(torch.tensor([[True, True], [False, False]]), torch.tensor([[True, False], [True, False]]), torch.tensor([[True, False], [False, False]])),
(torch.ones(3, 3, dtype=torch.bool), torch.zeros(3, 3, dtype=torch.bool), torch.zeros(3, 3, dtype=torch.bool)), # All true AND all false -> all false
(torch.ones(2, 2, dtype=torch.bool), torch.ones(2, 2, dtype=torch.bool), torch.ones(2, 2, dtype=torch.bool)), # All true AND all true -> all true
(torch.tensor([1, 0, 1, 0], dtype=torch.bool), torch.tensor([1, 1, 0, 0], dtype=torch.bool), torch.tensor([True, False, False, False])), # Mixed cases
]
def test_logical_and(self):
"""Test tensor element-wise logical AND using torch.logical_and()."""
for tens_a, tens_b, expected in self.test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected logical AND operation
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
@@ -1,40 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_logical_not import PtLogicalNot # Updated import to PtLogicalNot
class TestPtLogicalNot(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtLogicalNot()
# Test cases: (Tensor A, Expected result)
self.test_cases = [
(torch.tensor([True, False, True]), torch.tensor([False, True, False])),
(torch.tensor([[True, True], [False, False]]), torch.tensor([[False, False], [True, True]])),
(torch.ones(3, 3, dtype=torch.bool), torch.zeros(3, 3, dtype=torch.bool)), # NOT all true -> all false
(torch.zeros(2, 2, dtype=torch.bool), torch.ones(2, 2, dtype=torch.bool)), # NOT all false -> all true
(torch.tensor([1, 0, 1, 0], dtype=torch.bool), torch.tensor([False, True, False, True])), # Mixed cases
]
def test_logical_not(self):
"""Test tensor element-wise logical NOT using torch.logical_not()."""
for tens_a, expected in self.test_cases:
with self.subTest(tens_a=tens_a):
result, = self.node.f(tens_a)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected logical NOT operation
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
@@ -1,40 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_logical_or import PtLogicalOr # Updated import to PtLogicalOr
class TestPtLogicalOr(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtLogicalOr()
# Test cases: (Tensor A, Tensor B, Expected result)
self.test_cases = [
(torch.tensor([True, False, True]), torch.tensor([False, False, True]), torch.tensor([True, False, True])),
(torch.tensor([[True, True], [False, False]]), torch.tensor([[False, True], [True, False]]), torch.tensor([[True, True], [True, False]])),
(torch.ones(3, 3, dtype=torch.bool), torch.zeros(3, 3, dtype=torch.bool), torch.ones(3, 3, dtype=torch.bool)), # All true OR all false -> all true
(torch.zeros(2, 2, dtype=torch.bool), torch.zeros(2, 2, dtype=torch.bool), torch.zeros(2, 2, dtype=torch.bool)), # All false OR all false -> all false
(torch.tensor([1, 0, 1, 0], dtype=torch.bool), torch.tensor([1, 1, 0, 0], dtype=torch.bool), torch.tensor([True, True, True, False])), # Mixed cases
]
def test_logical_or(self):
"""Test tensor element-wise logical OR using torch.logical_or()."""
for tens_a, tens_b, expected in self.test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected logical OR operation
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
@@ -1,40 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_logical_xor import PtLogicalXor # Updated import to PtLogicalXor
class TestPtLogicalXor(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtLogicalXor()
# Test cases: (Tensor A, Tensor B, Expected result)
self.test_cases = [
(torch.tensor([True, False, True]), torch.tensor([False, False, True]), torch.tensor([True, False, False])),
(torch.tensor([[True, True], [False, False]]), torch.tensor([[False, True], [True, False]]), torch.tensor([[True, False], [True, False]])),
(torch.ones(3, 3, dtype=torch.bool), torch.zeros(3, 3, dtype=torch.bool), torch.ones(3, 3, dtype=torch.bool)), # True XOR False -> True
(torch.zeros(2, 2, dtype=torch.bool), torch.zeros(2, 2, dtype=torch.bool), torch.zeros(2, 2, dtype=torch.bool)), # False XOR False -> False
(torch.tensor([1, 0, 1, 0], dtype=torch.bool), torch.tensor([1, 1, 0, 0], dtype=torch.bool), torch.tensor([False, True, True, False])), # Mixed cases
]
def test_logical_xor(self):
"""Test tensor element-wise logical XOR using torch.logical_xor()."""
for tens_a, tens_b, expected in self.test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected logical XOR operation
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-40
View File
@@ -1,40 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_lt import PtLt # Updated import to PtLt
class TestPtLt(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtLt()
# Test cases: (Tensor A, Tensor B, Expected result)
self.test_cases = [
(torch.tensor([1, 2, 3]), torch.tensor([0, 2, 4]), torch.tensor([False, False, True])),
(torch.tensor([3, 5, 7]), torch.tensor([1, 5, 10]), torch.tensor([False, False, True])),
(torch.ones(3, 3), torch.ones(3, 3), torch.full((3, 3), False, dtype=torch.bool)),
(torch.zeros(2, 2), torch.ones(2, 2), torch.full((2, 2), True, dtype=torch.bool)),
(torch.tensor([[5], [10]]), torch.tensor([[5], [10]]), torch.tensor([[False], [False]])),
]
def test_less_than(self):
"""Test tensor element-wise less-than condition using torch.lt()."""
for tens_a, tens_b, expected in self.test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected less-than comparison
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
@@ -1,40 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_masked_select import PtMaskedSelect
class TestPtMaskedSelect(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtMaskedSelect()
# Test cases: (Tensor, Masked Tensor, Expected result)
self.test_cases = [
(
torch.tensor([[1, 2, 3], [40, 50, 60], [700, 800, 900]]),
torch.tensor([[True, False, False], [False, True, False], [False, False, True]]),
torch.tensor([1, 50, 900])
),
]
def test_masked_select(self):
"""Test torch.masked_select behavior."""
for tens, masked_tens, expected in self.test_cases:
with self.subTest(tens=tens, masked_tens=masked_tens):
result, = self.node.f(tens, masked_tens)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected selected values
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-63
View File
@@ -1,63 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_matmul import PtMatMul # Updated import to PtMatMul
class TestPtMatMul(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtMatMul()
# Valid test cases: (Tensor A, Tensor B, Expected result)
self.valid_test_cases = [
# Case 1: 1D x 1D (dot product)
(torch.tensor([1.0, 2.0, 3.0]), torch.tensor([4.0, 5.0, 6.0]), torch.tensor(32.0)),
# Case 2: 1D x 2D (vector-matrix multiplication)
(torch.tensor([1.0, 2.0]), torch.tensor([[3.0, 4.0], [5.0, 6.0]]), torch.tensor([13.0, 16.0])),
# Case 3: 2D x 2D (matrix-matrix multiplication)
(torch.tensor([[1.0, 2.0], [3.0, 4.0]]), torch.tensor([[5.0, 6.0], [7.0, 8.0]]), torch.tensor([[19.0, 22.0], [43.0, 50.0]])),
# Case 4: 3D x 2D (batched matrix-matrix multiplication)
(torch.ones(2, 3, 4), torch.ones(4, 5), torch.full((2, 3, 5), 4.0)), # (2,3,4) * (4,5) → (2,3,5)
# Case 5: 3D x 3D (batched matrix multiplication with broadcasting)
(torch.ones(2, 3, 4), torch.ones(2, 4, 5), torch.full((2, 3, 5), 4.0)), # (2,3,4) * (2,4,5) → (2,3,5)
]
# Invalid test cases (should raise errors)
self.invalid_test_cases = [
(torch.ones(2, 3), torch.ones(4, 2)), # (2,3) * (4,2) is invalid
(torch.tensor([1.0, 2.0, 3.0]), torch.tensor([4.0, 5.0])), # Vector size mismatch
(torch.ones(2, 3, 4), torch.ones(3, 5)), # (2,3,4) * (3,5) should fail due to misalignment
]
def test_matrix_multiplication(self):
"""Test valid matrix multiplication cases."""
for tens_a, tens_b, expected in self.valid_test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected matrix multiplication
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
def test_invalid_multiplication(self):
"""Test invalid cases where dimensions do not match."""
for tens_a, tens_b in self.invalid_test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
with self.assertRaises(RuntimeError, msg=f"MatMul should fail for shapes {tens_a.shape} and {tens_b.shape}"):
self.node.f(tens_a, tens_b)
if __name__ == "__main__":
unittest.main()
-61
View File
@@ -1,61 +0,0 @@
import os
import sys
import unittest
import torch
import ast
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_max import PtMax
class TestPtMax(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtMax()
# Test cases: (Tensor, Dim (as string), keepdim, Expected result)
self.test_cases = [
(
torch.tensor([[1, 3, 2], [4, 0, 5]]),
"0",
False,
torch.tensor([4, 3, 5])
),
(
torch.tensor([[1, 3, 2], [4, 0, 5]]),
"1",
True,
torch.tensor([[3], [5]])
),
(
torch.tensor([[[1, 5], [2, 8]], [[3, 4], [6, 7]]]),
"(0, 1)",
False,
torch.tensor([6, 8])
),
(
# Reduce across all axes
torch.tensor([[1, 3, 2], [4, 0, 5]]),
"", # Passing empty string to reduce across all dimensions
False,
torch.tensor(5)
)
]
def test_max(self):
"""Test torch.max behavior."""
for tens, dim, keepdim, expected in self.test_cases:
with self.subTest(tens=tens, dim=dim, keepdim=keepdim):
result, = self.node.f(tens, dim, keepdim)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected max values
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-87
View File
@@ -1,87 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_mean import PtMean
class TestPtMean(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtMean()
# Test cases: (Tensor, Dim (as string), keepdim, Expected result)
self.test_cases = [
# Float tensor cases
(
torch.tensor([[1.0, 3.0, 2.0], [4.0, 0.0, 5.0]], dtype=torch.float),
"0",
False,
torch.tensor([2.5, 1.5, 3.5], dtype=torch.float)
),
(
torch.tensor([[1.0, 3.0, 2.0], [4.0, 0.0, 5.0]], dtype=torch.float),
"1",
True,
torch.tensor([[2.], [3.]], dtype=torch.float)
),
(
torch.tensor([[[1.0, 5.0], [2.0, 8.0]], [[3.0, 4.0], [6.0, 7.0]]], dtype=torch.float),
"(0, 1)",
False,
torch.tensor([3.0, 6.0], dtype=torch.float)
),
(
# Reduce across all axes
torch.tensor([[1.0, 3.0, 2.0], [4.0, 0.0, 5.0]], dtype=torch.float),
"", # Passing empty string to reduce across all dimensions
False,
torch.tensor(2.5, dtype=torch.float)
),
# Complex tensor cases
(
torch.tensor([[1 + 1j, 3 + 3j, 2 + 2j], [4 + 4j, 0 + 0j, 5 + 5j]], dtype=torch.complex64),
"0",
False,
torch.tensor([2.5 + 2.5j, 1.5 + 1.5j, 3.5 + 3.5j], dtype=torch.complex64)
),
(
torch.tensor([[1 + 1j, 3 + 3j, 2 + 2j], [4 + 4j, 0 + 0j, 5 + 5j]], dtype=torch.complex64),
"1",
True,
torch.tensor([[2. + 2j], [3. + 3j]], dtype=torch.complex64)
),
(
torch.tensor([[[1 + 1j, 5 + 5j], [2 + 2j, 8 + 8j]], [[3 + 3j, 4 + 4j], [6 + 6j, 7 + 7j]]], dtype=torch.complex64),
"(0, 1)",
False,
torch.tensor([3. + 3j, 6. + 6j], dtype=torch.complex64)
),
(
# Reduce across all axes
torch.tensor([[1 + 1j, 3 + 3j, 2 + 2j], [4 + 4j, 0 + 0j, 5 + 5j]], dtype=torch.complex64),
"", # Passing empty string to reduce across all dimensions
False,
torch.tensor(2.5 + 2.5j, dtype=torch.complex64)
)
]
def test_mean(self):
"""Test torch.mean behavior."""
for tens, dim, keepdim, expected in self.test_cases:
with self.subTest(tens=tens, dim=dim, keepdim=keepdim):
result, = self.node.f(tens, dim, keepdim)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected mean values
self.assertTrue(torch.allclose(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-66
View File
@@ -1,66 +0,0 @@
import os
import sys
import unittest
import torch
import ast
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_median import PtMedian
class TestPtMedian(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtMedian()
# Test cases: (Tensor, Dim (as string), keepdim, Expected result)
self.test_cases = [
(
torch.tensor([[1, 3, 2], [2, 1, 3], [4, 0, 5]]),
"0",
False,
torch.tensor([2, 1, 3])
),
(
torch.tensor([[1, 3, 2], [4, 0, 5]]),
"0",
False,
torch.tensor([1, 0, 2]) # Fix: torch.median returns the lower value when between two numbers
),
(
torch.tensor([[1, 3, 2], [4, 0, 5]]),
"1",
True,
torch.tensor([[2], [4]])
),
(
torch.tensor([[1, 3, 2], [4, 0, 5], [7, 8, 6], [9, 2, 10]]),
"0",
False,
torch.tensor([4, 2, 5])
),
(
torch.tensor([[1, 3, 2, 8], [4, 0, 5, 6], [7, 8, 6, 9]]),
"1",
False,
torch.tensor([2, 4, 7])
)
]
def test_median(self):
"""Test torch.median behavior."""
for tens, dim, keepdim, expected in self.test_cases:
with self.subTest(tens=tens, dim=dim, keepdim=keepdim):
result, = self.node.f(tens, dim, keepdim)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected median values
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-61
View File
@@ -1,61 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_min import PtMin
class TestPtMin(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtMin()
# Test cases: (Tensor, Dim (as string), keepdim, Expected result)
self.test_cases = [
(
torch.tensor([[1, 3, 2], [4, 0, 5]]),
"0",
False,
torch.tensor([1, 0, 2])
),
(
torch.tensor([[1, 3, 2], [4, 0, 5]]),
"1",
True,
torch.tensor([[1], [0]])
),
(
torch.tensor([[[1, 5], [2, 8]], [[3, 4], [6, 7]]]),
"(0, 1)",
False,
torch.tensor([1, 4])
),
(
# Reduce across all axes
torch.tensor([[1, 3, 2], [4, 0, 5]]),
"", # Passing empty string to reduce across all dimensions
False,
torch.tensor(0)
)
]
def test_amin(self):
"""Test torch.amin behavior."""
for tens, dim, keepdim, expected in self.test_cases:
with self.subTest(tens=tens, dim=dim, keepdim=keepdim):
result, = self.node.f(tens, dim, keepdim)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected min values
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-58
View File
@@ -1,58 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_mm import PtMm # Updated import to PtMm
class TestPtMm(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtMm()
# Valid test cases: (Tensor A, Tensor B, Expected result)
self.valid_test_cases = [
# Case 1: 2D x 2D (matrix-matrix multiplication)
(torch.tensor([[1.0, 2.0], [3.0, 4.0]]), torch.tensor([[5.0, 6.0], [7.0, 8.0]]), torch.tensor([[19.0, 22.0], [43.0, 50.0]])),
# Case 2: 2D identity matrix multiplication (should remain the same)
(torch.eye(3), torch.eye(3), torch.eye(3)),
# Case 3: Rectangular 2D matrix multiplication
(torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), torch.tensor([[7.0, 8.0], [9.0, 10.0], [11.0, 12.0]]), torch.tensor([[58.0, 64.0], [139.0, 154.0]])),
]
# Invalid test cases (should raise errors)
self.invalid_test_cases = [
(torch.tensor([1.0, 2.0, 3.0]), torch.tensor([4.0, 5.0, 6.0])), # 1D x 1D (dot product not supported by mm)
(torch.tensor([[1.0, 2.0]]), torch.tensor([3.0, 4.0])), # 2D x 1D mismatch
(torch.ones(2, 3, 4), torch.ones(4, 5)), # 3D x 2D is invalid for mm
(torch.ones(2, 3, 4), torch.ones(2, 4, 5)), # 3D x 3D is invalid for mm
]
def test_matrix_multiplication(self):
"""Test valid matrix multiplication cases."""
for tens_a, tens_b, expected in self.valid_test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected matrix multiplication
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
def test_invalid_multiplication(self):
"""Test invalid cases where dimensions do not match."""
for tens_a, tens_b in self.invalid_test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
with self.assertRaises(ValueError, msg=f"torch.mm() should fail for shapes {tens_a.shape} and {tens_b.shape}"):
self.node.f(tens_a, tens_b)
if __name__ == "__main__":
unittest.main()
-39
View File
@@ -1,39 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_mul import PtMul # Updated import to PtMul
class TestPtMul(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtMul()
# Test cases: (Tensor A, Tensor B, Expected result)
self.test_cases = [
(torch.tensor([1.0, 2.0, 3.0]), torch.tensor([4.0, 5.0, 6.0]), torch.tensor([4.0, 10.0, 18.0])),
(torch.ones(3, 3), torch.ones(3, 3), torch.ones(3, 3)), # 1 * 1 = 1
(torch.zeros(2, 2), torch.ones(2, 2), torch.zeros(2, 2)), # 0 * 1 = 0
(torch.tensor([[2.0], [3.0]]), torch.tensor([[3.0], [4.0]]), torch.tensor([[6.0], [12.0]])), # Element-wise multiplication
]
def test_multiplication(self):
"""Test tensor multiplication."""
for tens_a, tens_b, expected in self.test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected product
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-40
View File
@@ -1,40 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_ne import PtNe # Updated import to PtNe
class TestPtNe(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtNe()
# Test cases: (Tensor A, Tensor B, Expected result)
self.test_cases = [
(torch.tensor([1, 2, 3]), torch.tensor([1, 2, 3]), torch.tensor([False, False, False])),
(torch.tensor([1, 2, 3]), torch.tensor([3, 2, 1]), torch.tensor([True, False, True])),
(torch.ones(3, 3), torch.ones(3, 3), torch.full((3, 3), False, dtype=torch.bool)),
(torch.zeros(2, 2), torch.ones(2, 2), torch.full((2, 2), True, dtype=torch.bool)),
(torch.tensor([[1], [2]]), torch.tensor([[1], [3]]), torch.tensor([[False], [True]])),
]
def test_inequality(self):
"""Test tensor element-wise inequality using torch.ne()."""
for tens_a, tens_b, expected in self.test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected element-wise inequality
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-40
View File
@@ -1,40 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_neg import PtNeg # Updated import to PtNeg
class TestPtNeg(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtNeg()
# Test cases: (Tensor A, Expected result)
self.test_cases = [
(torch.tensor([1, -2, 3]), torch.tensor([-1, 2, -3])),
(torch.tensor([0, 5, -7]), torch.tensor([0, -5, 7])),
(torch.ones(3, 3), torch.full((3, 3), -1.0)), # Negation of ones
(torch.zeros(2, 2), torch.zeros(2, 2)), # Negation of zeros
(torch.tensor([[5], [-10]]), torch.tensor([[-5], [10]])), # Column vector case
]
def test_neg(self):
"""Test tensor element-wise negation using torch.neg()."""
for tens_a, expected in self.test_cases:
with self.subTest(tens_a=tens_a):
result, = self.node.f(tens_a)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected negation
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-44
View File
@@ -1,44 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_ones import PtOnes # Importing the PtOnes class
from pytorch_wrapper.utils import DTYPE_MAPPING # Importing the dtype mapping
class TestPtOnes(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtOnes()
# Tensor size to test
self.size_str = "[2, 3]" # Using a small 2D tensor size for all tests
self.expected_shape = (2, 3)
def test_ones_tensor_all_dtypes(self):
"""Test tensor creation with ones for all supported data types."""
for data_type, torch_dtype in DTYPE_MAPPING.items():
with self.subTest(data_type=data_type):
result, = self.node.f(self.size_str, data_type)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result has correct shape
self.assertEqual(result.shape, torch.Size(self.expected_shape), f"Expected shape {self.expected_shape}, got {result.shape}")
# Ensure result has correct dtype
self.assertEqual(result.dtype, torch_dtype, f"Expected dtype {torch_dtype}, got {result.dtype}")
# Ensure all elements are ones
expected = torch.ones(self.expected_shape, dtype=torch_dtype)
self.assertTrue(torch.equal(result, expected), f"Tensor values do not match expected ones tensor for dtype {data_type}")
if __name__ == "__main__":
unittest.main()
-50
View File
@@ -1,50 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_pad import PtPad
class TestPtPad(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtPad()
# Test cases: (Input tensor, Height, Width, Expected shape)
self.test_cases = [
(torch.rand(1, 3, 16, 16), 32, 32, (1, 3, 32, 32)), # Pad 4D tensor
(torch.rand(3, 16, 16), 32, 32, (3, 32, 32)), # Pad 3D tensor
(torch.rand(1, 3, 16, 16), 16, 16, (1, 3, 16, 16)), # No padding, same size
]
def test_padding(self):
"""Test tensor padding to specific sizes."""
for tens, height, width, expected_shape in self.test_cases:
with self.subTest(height=height, width=width):
result, = self.node.f(tens, height, width)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result shape matches expected shape
self.assertEqual(result.shape, expected_shape, f"Expected shape {expected_shape}, got {result.shape}")
def test_invalid_tensor_rank(self):
"""Test that an invalid tensor rank raises an error."""
tens = torch.rand(16, 16) # 2D tensor (invalid)
with self.assertRaises(ValueError, msg="Only rank 3 or 4 tensors are supported for padding."):
self.node.f(tens, 32, 32)
def test_padding_smaller_than_tensor(self):
"""Test that padding to a smaller size raises an error."""
tens = torch.rand(1, 3, 16, 16)
with self.assertRaises(ValueError, msg="Specified dimensions must be greater than or equal to tensor dimensions."):
self.node.f(tens, 8, 8)
if __name__ == "__main__":
unittest.main()
-59
View File
@@ -1,59 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_permute import PtPermute
class TestPtPermute(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtPermute()
# Define test cases: (input_tensor, new_axes, expected_shape)
self.test_cases = [
# Case 1: Basic 2D permutation
(torch.ones(2, 3), "[1, 0]", (3, 2)), # (2,3) -> (3,2)
# Case 2: Permute dimensions of a 3D tensor
(torch.ones(2, 3, 4), "[2, 0, 1]", (4, 2, 3)), # (2,3,4) -> (4,2,3)
# Case 3: Identity permutation (no change)
(torch.ones(2, 3, 4), "[0, 1, 2]", (2, 3, 4)), # (2,3,4) -> (2,3,4)
# Case 4: Permute 4D tensor (like a channel-first transformation)
(torch.ones(2, 3, 96, 32), "[0, 3, 1, 2]", (2, 32, 3, 96)), # (2,3,96,32) -> (2,32,3,96)
# Case 5: Swapping first and last dimensions
(torch.ones(5, 10, 15), "[2, 1, 0]", (15, 10, 5)), # (5,10,15) -> (15,10,5)
# Case 6: Edge case with a single-dimension tensor
(torch.ones(10,), "[0]", (10,)), # (10,) -> (10,) (No change)
# Case 7: Larger 5D tensor permutation
(torch.ones(2, 3, 4, 5, 6), "[4, 3, 2, 1, 0]", (6, 5, 4, 3, 2)), # Reverse all dimensions
]
def test_permute(self):
"""Test tensor permutation operation with various dimension orders."""
for input_tensor, new_axes, expected_shape in self.test_cases:
with self.subTest(input_shape=input_tensor.shape, new_axes=new_axes):
result, = self.node.f(input_tensor, new_axes)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result has correct shape
self.assertEqual(result.shape, torch.Size(expected_shape), f"Expected shape {expected_shape}, got {result.shape}")
# Ensure result has the same dtype
self.assertEqual(result.dtype, input_tensor.dtype, "Dtype mismatch after permute operation")
if __name__ == "__main__":
unittest.main()
-39
View File
@@ -1,39 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_pow import PtPow
class TestPtPow(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtPow()
# Test cases: (Tensor A, Tensor B, Expected result)
self.test_cases = [
(torch.tensor([2.0, 3.0, 4.0]), torch.tensor([3.0, 2.0, 1.0]), torch.tensor([8.0, 9.0, 4.0])), # 2^3, 3^2, 4^1
(torch.ones(3, 3) * 4, torch.ones(3, 3) * 2, torch.ones(3, 3) * 16), # 4^2 = 16
(torch.full((2, 2), 5.0), torch.full((2, 2), 3.0), torch.full((2, 2), 125.0)), # 5^3 = 125
(torch.tensor([[2.0], [3.0]]), torch.tensor([[4.0], [5.0]]), torch.tensor([[16.0], [243.0]])), # 2^4 = 16, 3^5 = 243
]
def test_power(self):
"""Test tensor exponentiation."""
for tens_a, tens_b, expected in self.test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected power computation
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
@@ -1,68 +0,0 @@
import os
import sys
import unittest
import torch
import torch.nn as nn
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.ptn_conv_model import PtnConvModel
from pytorch_wrapper.ptv_image_folder_dataset import PtvImageFolderDataset
from pytorch_wrapper.ptv_transforms_resize import PtvTransformsResize
from pytorch_wrapper.pt_data_loader import PtDataLoader
from pytorch_wrapper.pt_predict_classification_model import PtPredictClassificationModel
from pytorch_wrapper.pt_load_model import PtLoadModel
class TestPtPrediction(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
# Transform
compose_node = PtvTransformsResize()
transform = compose_node.f(256, 256)[0]
# Dataset
self.node = PtvImageFolderDataset()
self.dataset = self.node.f("dog_and_cat/val",
transform=transform)[0]
# Model
self.model_node = PtnConvModel()
self.model = self.model_node.f(
input_dim="(3, 256, 256)",
penultimate_dim=0,
output_dim=2,
channel_list="[32,64,128,256,512]", # To 128, 64, 32, 16, 8
kernel_size_list="[3,3,3,3,3]",
padding_list="[1,1,1,1,1]",
downsample_list="[True,True,True,True,True]"
)[0]
# Load weights
epochs = 20
self.load_model = PtLoadModel()
self.loaded_model = self.load_model.f(self.model,f"dog_cat_{epochs}_epochs_conv.pt")
# Instantiates evaluation node
self.predict = PtPredictClassificationModel()
def test_prediction(self):
"""
Tests prediction.
Note that this test requires a trained model file on the file system.
Unit test will fail if you run this for the first time.
Run the unit test for training to generate the weight, and re-run this unit test.
"""
inputs, y = next(iter(self.dataset))
class_id_to_name_map = {0:"cat", 1:"dog"}
class_name, class_id, prob = \
self.predict.f(self.model, inputs, class_id_to_name_map, use_gpu=True)
self.assertTrue(prob > 0.8)
self.assertEqual(class_id, 0)
self.assertEqual(class_name, "cat")
if __name__ == "__main__":
unittest.main()
-59
View File
@@ -1,59 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_prod import PtProd
class TestPtProd(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtProd()
# Test cases: (Tensor, Dim (as string), keepdim, Expected result)
self.test_cases = [
(
torch.tensor([[1, 3, 2], [2, 1, 3]]),
"0",
False,
torch.tensor([2, 3, 6])
),
(
torch.tensor([[1, 3, 2], [4, 0, 5]]),
"1",
True,
torch.tensor([[6], [0]])
),
(
torch.tensor([[1, 3, 2], [4, 5, 6]]),
"0",
False,
torch.tensor([4, 15, 12])
),
(
torch.tensor([[1, 3, 2], [4, 5, 6], [7, 8, 9]]),
"1",
False,
torch.tensor([6, 120, 504])
)
]
def test_prod(self):
"""Test torch.prod behavior."""
for tens, dim, keepdim, expected in self.test_cases:
with self.subTest(tens=tens, dim=dim, keepdim=keepdim):
result, = self.node.f(tens, dim, keepdim)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected product values
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-40
View File
@@ -1,40 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_neg import PtNeg # Updated import to PtNeg
class TestPtNeg(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtNeg()
# Test cases: (Tensor A, Expected result)
self.test_cases = [
(torch.tensor([1, -2, 3]), torch.tensor([-1, 2, -3])),
(torch.tensor([0, 5, -7]), torch.tensor([0, -5, 7])),
(torch.ones(3, 3), torch.full((3, 3), -1.0)), # Negation of ones
(torch.zeros(2, 2), torch.zeros(2, 2)), # Negation of zeros
(torch.tensor([[5], [-10]]), torch.tensor([[-5], [10]])), # Column vector case
]
def test_neg(self):
"""Test tensor element-wise negation using torch.neg()."""
for tens_a, expected in self.test_cases:
with self.subTest(tens_a=tens_a):
result, = self.node.f(tens_a)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected negation
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-46
View File
@@ -1,46 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_rand import PtRand # Importing the PtRand class
from pytorch_wrapper.utils import DTYPE_MAPPING # Importing the dtype mapping
class TestPtRand(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtRand()
# Tensor size to test
self.size_str = "[2, 3]" # Using a small 2D tensor size for all tests
self.expected_shape = (2, 3)
# Only floating-point types are valid for torch.rand()
self.valid_dtypes = {k: v for k, v in DTYPE_MAPPING.items() if v in {torch.float32, torch.float16, torch.bfloat16, torch.float64}}
def test_rand_tensor_all_floating_dtypes(self):
"""Test random tensor creation for all supported floating-point data types."""
for data_type, torch_dtype in self.valid_dtypes.items():
with self.subTest(data_type=data_type):
result, = self.node.f(self.size_str, data_type)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result has correct shape
self.assertEqual(result.shape, torch.Size(self.expected_shape), f"Expected shape {self.expected_shape}, got {result.shape}")
# Ensure result has correct dtype
self.assertEqual(result.dtype, torch_dtype, f"Expected dtype {torch_dtype}, got {result.dtype}")
# Ensure all elements are within range [0,1)
self.assertTrue(torch.all(result >= 0) and torch.all(result < 1), f"Tensor values are not in the range [0,1) for dtype {data_type}")
if __name__ == "__main__":
unittest.main()
-61
View File
@@ -1,61 +0,0 @@
import os
import sys
import unittest
import torch
import ast
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_rand_int import PtRandInt # Importing the PtRandInt class
from pytorch_wrapper.utils import DTYPE_MAPPING # Importing the dtype mapping
class TestPtRandInt(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtRandInt()
# Tensor size to test
self.size_str = "[2, 3]" # Using a small 2D tensor size for all tests
self.expected_shape = (2, 3)
# Only integer types are valid for torch.randint()
self.valid_dtypes = {
k: v for k, v in DTYPE_MAPPING.items() if v in {torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8}
}
# Define min and max values for each integer type
self.test_ranges = {
"int8": (-128, 127),
"int16": (-32768, 32767),
"int32": (-2147483648, 2147483647),
"int64": (-9223372036854775808, 9223372036854775807),
"uint8": (0, 255),
}
def test_randint_tensor_all_integer_dtypes(self):
"""Test random integer tensor creation for all supported integer data types."""
for data_type, torch_dtype in self.valid_dtypes.items():
min_value, max_value = self.test_ranges[data_type]
with self.subTest(data_type=data_type, min_value=min_value, max_value=max_value):
result, = self.node.f(min_value, max_value, self.size_str, data_type)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result has correct shape
self.assertEqual(result.shape, torch.Size(self.expected_shape), f"Expected shape {self.expected_shape}, got {result.shape}")
# Ensure result has correct dtype
self.assertEqual(result.dtype, torch_dtype, f"Expected dtype {torch_dtype}, got {result.dtype}")
# Ensure all elements are within range [min_value, max_value)
self.assertTrue(torch.all(result >= min_value), f"Tensor contains values less than min_value for dtype {data_type}")
self.assertTrue(torch.all(result < max_value), f"Tensor contains values greater than or equal to max_value for dtype {data_type}")
if __name__ == "__main__":
unittest.main()
@@ -1,39 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_remainder import PtRemainder
class TestPtRemainder(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtRemainder()
# Test cases: (Tensor A, Tensor B, Expected result)
self.test_cases = [
(torch.tensor([4.0, 10.0, 18.0]), torch.tensor([3.0, 4.0, 5.0]), torch.tensor([1.0, 2.0, 3.0])),
(torch.ones(3, 3) * 7, torch.ones(3, 3) * 3, torch.ones(3, 3) * 1), # 7 % 3 = 1
(torch.full((2, 2), 9.0), torch.full((2, 2), 2.0), torch.full((2, 2), 1.0)), # 9 % 2 = 1
(torch.tensor([[7.0], [15.0]]), torch.tensor([[2.0], [4.0]]), torch.tensor([[1.0], [3.0]])), # Element-wise remainder
]
def test_remainder(self):
"""Test tensor remainder computation."""
for tens_a, tens_b, expected in self.test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected remainder
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-60
View File
@@ -1,60 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_reshape import PtReshape # Importing the PtReshape class
class TestPtReshape(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtReshape()
# Define test cases: (input_tensor, new_shape, expected_shape)
self.test_cases = [
# Case 1: Reshape a 2D tensor
(torch.ones(2, 3), "[3, 2]", (3, 2)), # (2,3) -> (3,2)
# Case 2: Reshape a 3D tensor
(torch.ones(2, 3, 4), "[6, 4]", (6, 4)), # (2,3,4) -> (6,4)
# Case 3: Using -1 for automatic inference
(torch.ones(2, 3, 4), "[2, -1]", (2, 12)), # (2,3,4) -> (2,12)
(torch.ones(6, 4), "[-1, 4]", (6, 4)), # (6,4) -> (6,4)
# Case 4: Flattening a multi-dimensional tensor
(torch.ones(2, 3, 4), "[-1]", (24,)), # (2,3,4) -> (24,)
# Case 5: Expanding dimensions
(torch.ones(6,), "[2, 3]", (2, 3)), # (6,) -> (2,3)
# Case 6: Reshaping a 4D tensor
(torch.ones(2, 3, 4, 5), "[6, -1, 5]", (6, 4, 5)), # (2,3,4,5) -> (6,4,5)
# Case 7: Edge case with 1D tensor
(torch.ones(10,), "[10, 1]", (10, 1)), # (10,) -> (10,1)
]
def test_reshape(self):
"""Test tensor reshape operation with various shape orders."""
for input_tensor, new_shape, expected_shape in self.test_cases:
with self.subTest(input_shape=input_tensor.shape, new_shape=new_shape):
result, = self.node.f(input_tensor, new_shape)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result has correct shape
self.assertEqual(result.shape, torch.Size(expected_shape), f"Expected shape {expected_shape}, got {result.shape}")
# Ensure result has the same dtype
self.assertEqual(result.dtype, input_tensor.dtype, "Dtype mismatch after reshape operation")
if __name__ == "__main__":
unittest.main()
-51
View File
@@ -1,51 +0,0 @@
import os
import sys
import unittest
import torch
import ast
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_scatter import PtScatter
class TestPtScatter(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtScatter()
# Test cases: (Target Tensor, Dim, Index Tensor (as string), Source Tensor (as string), Expected Output)
self.test_cases = [
(
torch.tensor([
[10, 11, 12],
[21, 22, 23],
[31, 32, 33],
]),
0,
"[[0, 1, 0], [1, 1, 2]]",
"[[2, 4, 6], [4, 4, 2]]",
torch.tensor([
[2, 11, 6],
[4, 4, 23],
[31, 32, 2],
])
)
]
def test_scatter(self):
"""Test torch.scatter behavior."""
for tens, dim, index, src, expected in self.test_cases:
with self.subTest(tens=tens, dim=dim, index=index, src=src):
result, = self.node.f(tens, dim, index, src)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected values
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-39
View File
@@ -1,39 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_sin import PtSin # Updated import to PtSin
class TestPtSin(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtSin()
# Test cases: (Tensor A, Expected result)
self.test_cases = [
(torch.tensor([0.0, torch.pi / 2, torch.pi], dtype=torch.float32), torch.sin(torch.tensor([0.0, torch.pi / 2, torch.pi], dtype=torch.float32))), # Edge cases
(torch.tensor([0.5, -0.5], dtype=torch.float32), torch.sin(torch.tensor([0.5, -0.5], dtype=torch.float32))), # Common values
(torch.tensor([[0.1, -0.3], [0.7, -0.9]], dtype=torch.float32), torch.sin(torch.tensor([[0.1, -0.3], [0.7, -0.9]], dtype=torch.float32))), # 2D case
(torch.full((2, 2), 0.6, dtype=torch.float32), torch.sin(torch.full((2, 2), 0.6, dtype=torch.float32))), # Constant matrix
]
def test_sin(self):
"""Test tensor element-wise sine using torch.sin()."""
for tens_a, expected in self.test_cases:
with self.subTest(tens_a=tens_a):
result, = self.node.f(tens_a)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected sin values
self.assertTrue(torch.allclose(result, expected, atol=1e-6), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-39
View File
@@ -1,39 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_sinh import PtSinh # Updated import to PtSinh
class TestPtSinh(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtSinh()
# Test cases: (Tensor A, Expected result)
self.test_cases = [
(torch.tensor([0.0, 1.0, -1.0], dtype=torch.float32), torch.sinh(torch.tensor([0.0, 1.0, -1.0], dtype=torch.float32))), # Edge cases
(torch.tensor([0.5, -0.5], dtype=torch.float32), torch.sinh(torch.tensor([0.5, -0.5], dtype=torch.float32))), # Common values
(torch.tensor([[0.1, -0.3], [0.7, -0.9]], dtype=torch.float32), torch.sinh(torch.tensor([[0.1, -0.3], [0.7, -0.9]], dtype=torch.float32))), # 2D case
(torch.full((2, 2), 0.6, dtype=torch.float32), torch.sinh(torch.full((2, 2), 0.6, dtype=torch.float32))), # Constant matrix
]
def test_sinh(self):
"""Test tensor element-wise hyperbolic sine using torch.sinh()."""
for tens_a, expected in self.test_cases:
with self.subTest(tens_a=tens_a):
result, = self.node.f(tens_a)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected sinh values
self.assertTrue(torch.allclose(result, expected, atol=1e-6), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
@@ -1,46 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_size_create import PtSizeCreate
class TestPtSizeCreate(unittest.TestCase):
def setUp(self):
"""Set up test data."""
self.node = PtSizeCreate()
# Test cases with torch.Size objects
self.test_cases = [
# Empty size (zero-rank tensor shape)
("[]", torch.Size([])),
# Rank 1 (single-dimension size)
("[3]", torch.Size([3])),
# Rank 2 (matrix size)
("[3, 4]", torch.Size([3, 4])),
# Rank 3 (3D tensor size)
("[2, 3, 4]", torch.Size([2, 3, 4])),
# Rank 4 (higher-dimensional tensor size)
("[1, 2, 3, 4]", torch.Size([1, 2, 3, 4])),
# Rank 5 (very high-dimensional tensor size)
("[5, 4, 3, 2, 1]", torch.Size([5, 4, 3, 2, 1])),
]
def test_create_size(self):
"""Test PyTorch Size creation from various structured inputs."""
for data_str, expected_size in self.test_cases:
with self.subTest(data=data_str):
retval = self.node.f(data_str)[0]
# Ensure the returned value is a PyTorch Size
self.assertTrue(isinstance(retval, torch.Size), f"Expected Size, got {type(retval)}")
# Ensure the value matches expected size
self.assertEqual(retval, expected_size, f"Value mismatch for input: {data_str}")
if __name__ == "__main__":
unittest.main()
-44
View File
@@ -1,44 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_size import PtSize
class TestPtSize(unittest.TestCase):
def setUp(self):
"""Set up test data."""
self.node = PtSize()
# Test cases with torch.Tensor objects
self.test_cases = [
# Rank 0 (scalar tensor)
(torch.tensor(42), torch.Size([])),
# Rank 1 (vector tensor)
(torch.tensor([1, 2, 3]), torch.Size([3])),
# Rank 2 (matrix tensor)
(torch.tensor([[1, 2], [3, 4]]), torch.Size([2, 2])),
# Rank 3 (3D tensor)
(torch.tensor([[[1], [2]], [[3], [4]]]), torch.Size([2, 2, 1])),
# Rank 4 (4D tensor)
(torch.tensor([[[[1, 2], [3, 4]]]]), torch.Size([1, 1, 2, 2])),
]
def test_extract_size(self):
"""Test PyTorch Size extraction from tensors."""
for tensor, expected_size in self.test_cases:
with self.subTest(data=tensor):
retval = self.node.f(tensor)[0]
# Ensure the returned value is a PyTorch Size
self.assertTrue(isinstance(retval, torch.Size), f"Expected Size, got {type(retval)}")
# Ensure the value matches expected size
self.assertEqual(retval, expected_size, f"Value mismatch for input: {tensor}")
if __name__ == "__main__":
unittest.main()
@@ -1,55 +0,0 @@
import os
import sys
import unittest
import torch
import numpy as np
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_size_to_numpy import PtSizeToNumpy
class TestPtSizeToNumpy(unittest.TestCase):
def setUp(self):
"""Set up test data."""
self.node = PtSizeToNumpy()
# Test cases with torch.Size objects
self.test_cases = [
# Empty size (zero-rank tensor shape)
(torch.Size([]), np.array([], dtype=int)),
# Rank 1 (single-dimension size)
(torch.Size([3]), np.array([3], dtype=int)),
# Rank 2 (matrix size)
(torch.Size([3, 4]), np.array([3, 4], dtype=int)),
# Rank 3 (3D tensor size)
(torch.Size([2, 3, 4]), np.array([2, 3, 4], dtype=int)),
# Rank 4 (higher-dimensional tensor size)
(torch.Size([1, 2, 3, 4]), np.array([1, 2, 3, 4], dtype=int)),
# Rank 5 (very high-dimensional tensor size)
(torch.Size([5, 4, 3, 2, 1]), np.array([5, 4, 3, 2, 1], dtype=int)),
]
def test_convert_size_to_numpy(self):
"""Test conversion of PyTorch Size to NumPy ndarray."""
for torch_size, expected_array in self.test_cases:
with self.subTest(data=torch_size):
retval = self.node.f(torch_size)[0]
# Ensure the returned value is a NumPy array
self.assertTrue(isinstance(retval, np.ndarray), f"Expected ndarray, got {type(retval)}")
# Ensure the dtype is integer
self.assertEqual(retval.dtype, expected_array.dtype, f"Dtype mismatch for input: {torch_size}")
# Ensure the shape matches
self.assertEqual(retval.shape, expected_array.shape,
f"Shape mismatch for input: {torch_size} (Expected {expected_array.shape}, got {retval.shape})")
# Ensure values match
np.testing.assert_array_equal(retval, expected_array,
f"Value mismatch for input: {torch_size}")
if __name__ == "__main__":
unittest.main()
@@ -1,46 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_size_to_string import PtSizeToString
class TestPtSizeToString(unittest.TestCase):
def setUp(self):
"""Set up test data."""
self.node = PtSizeToString()
# Test cases with torch.Size objects
self.test_cases = [
# Empty size (zero-rank tensor shape)
(torch.Size([]), "torch.Size([])"),
# Rank 1 (single-dimension size)
(torch.Size([3]), "torch.Size([3])"),
# Rank 2 (matrix size)
(torch.Size([3, 4]), "torch.Size([3, 4])"),
# Rank 3 (3D tensor size)
(torch.Size([2, 3, 4]), "torch.Size([2, 3, 4])"),
# Rank 4 (higher-dimensional tensor size)
(torch.Size([1, 2, 3, 4]), "torch.Size([1, 2, 3, 4])"),
# Rank 5 (very high-dimensional tensor size)
(torch.Size([5, 4, 3, 2, 1]), "torch.Size([5, 4, 3, 2, 1])"),
]
def test_convert_size_to_string(self):
"""Test conversion of PyTorch Size to string."""
for torch_size, expected_string in self.test_cases:
with self.subTest(data=torch_size):
retval = self.node.f(torch_size)[0]
# Ensure the returned value is a string
self.assertTrue(isinstance(retval, str), f"Expected str, got {type(retval)}")
# Ensure the value matches expected string
self.assertEqual(retval, expected_string, f"Value mismatch for input: {torch_size}")
if __name__ == "__main__":
unittest.main()
-39
View File
@@ -1,39 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_sqrt import PtSqrt # Updated import to PtSqrt
class TestPtSqrt(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtSqrt()
# Test cases: (Tensor A, Expected result)
self.test_cases = [
(torch.tensor([1.0, 4.0, 9.0], dtype=torch.float32), torch.sqrt(torch.tensor([1.0, 4.0, 9.0], dtype=torch.float32))), # Perfect squares
(torch.tensor([0.5, 2.0, 3.0], dtype=torch.float32), torch.sqrt(torch.tensor([0.5, 2.0, 3.0], dtype=torch.float32))), # Common values
(torch.tensor([[1.5, 3.2], [4.7, 5.9]], dtype=torch.float32), torch.sqrt(torch.tensor([[1.5, 3.2], [4.7, 5.9]], dtype=torch.float32))), # 2D case
(torch.full((2, 2), 2.5, dtype=torch.float32), torch.sqrt(torch.full((2, 2), 2.5, dtype=torch.float32))), # Constant matrix
]
def test_sqrt(self):
"""Test tensor element-wise square root using torch.sqrt()."""
for tens_a, expected in self.test_cases:
with self.subTest(tens_a=tens_a):
result, = self.node.f(tens_a)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected sqrt values
self.assertTrue(torch.allclose(result, expected, atol=1e-6), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-57
View File
@@ -1,57 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_squeeze import PtSqueeze # Importing the PtSqueeze class
class TestPtSqueeze(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtSqueeze()
# Define test cases: (input_tensor, dim, expected_shape)
self.test_cases = [
# Case 1: Squeezing a singleton dimension
(torch.ones(1, 3, 4), 0, (3, 4)), # (1,3,4) -> (3,4)
(torch.ones(2, 1, 4), 1, (2, 4)), # (2,1,4) -> (2,4)
# Case 2: No change if dim is not a singleton
(torch.ones(2, 3, 4), 1, (2, 3, 4)), # (2,3,4) -> (2,3,4)
# Case 3: Multiple singleton dimensions, squeezing one
(torch.ones(1, 2, 1, 4), 2, (1, 2, 4)), # (1,2,1,4) -> (1,2,4)
# Case 4: Squeezing a negative index
(torch.ones(2, 3, 1), -1, (2, 3)), # (2,3,1) -> (2,3)
# Case 5: Squeezing all size 1 dimensions
(torch.ones(1, 1, 1), 0, (1, 1)), # (1,1,1) -> (1,1)
(torch.ones(1, 1, 1), 1, (1, 1)), # (1,1,1) -> (1,1)
(torch.ones(1, 1, 1), 2, (1, 1)), # (1,1,1) -> (1,1)
]
def test_squeeze(self):
"""Test tensor squeeze operation on various dimensions."""
for input_tensor, dim, expected_shape in self.test_cases:
with self.subTest(input_shape=input_tensor.shape, dim=dim):
result, = self.node.f(input_tensor, dim)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result has correct shape
self.assertEqual(result.shape, torch.Size(expected_shape), f"Expected shape {expected_shape}, got {result.shape}")
# Ensure result has the same dtype
self.assertEqual(result.dtype, input_tensor.dtype, "Dtype mismatch after squeeze operation")
if __name__ == "__main__":
unittest.main()
-84
View File
@@ -1,84 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_std import PtStd
class TestPtStd(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtStd()
# Define test cases with string-based dimensions
self.test_cases = [
# Sample standard deviation (Bessel's correction) along dim=0
(
torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]),
"0",
1,
False,
torch.std(torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), dim=0, correction=1, keepdim=False)
),
# Sample standard deviation along dim=1, with keepdim=True
(
torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]),
"1",
1,
True,
torch.std(torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), dim=1, correction=1, keepdim=True)
),
# Sample standard deviation across both axes (dim=(0,1))
(
torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]),
"(0, 1)",
1,
False,
torch.std(torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), dim=(0, 1), correction=1, keepdim=False)
),
# Sample standard deviation across all elements (dim=None) - Entire tensor
(
torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]),
"",
1,
False,
torch.std(torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), correction=1, keepdim=False)
),
# Population standard deviation along dim=0 (correction=0)
(
torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]),
"0",
0,
False,
torch.std(torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), dim=0, correction=0, keepdim=False)
),
# Population standard deviation along dim=1 with keepdim=True (correction=0)
(
torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]),
"1",
0,
True,
torch.std(torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), dim=1, correction=0, keepdim=True)
)
]
def test_std(self):
"""Test torch.std behavior."""
for tens, dim, correction, keepdim, expected in self.test_cases:
with self.subTest(tens=tens, dim=dim, correction=correction, keepdim=keepdim):
result, = self.node.f(tens, dim, correction, keepdim)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected standard deviation values
self.assertTrue(torch.allclose(result, expected, atol=1e-6), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-39
View File
@@ -1,39 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_sub import PtSub
class TestPtSub(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtSub()
# Test cases: (Tensor A, Tensor B, Expected result)
self.test_cases = [
(torch.tensor([5.0, 7.0, 9.0]), torch.tensor([4.0, 5.0, 6.0]), torch.tensor([1.0, 2.0, 3.0])),
(torch.full((3, 3), 2.0), torch.ones(3, 3), torch.ones(3, 3)),
(torch.ones(2, 2), torch.ones(2, 2), torch.zeros(2, 2)),
(torch.tensor([[4.0], [6.0]]), torch.tensor([[3.0], [4.0]]), torch.tensor([[1.0], [2.0]])),
]
def test_subtraction(self):
"""Test tensor subtraction."""
for tens_a, tens_b, expected in self.test_cases:
with self.subTest(tens_a=tens_a, tens_b=tens_b):
result, = self.node.f(tens_a, tens_b)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected difference
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-71
View File
@@ -1,71 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_sum import PtSum
class TestPtSum(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtSum()
# Test cases: (Tensor, Dim (as string), keepdim, Expected result)
self.test_cases = [
(
torch.tensor([[1, 3, 2], [2, 1, 3]]),
"0",
False,
torch.tensor([3, 4, 5])
),
(
torch.tensor([[1, 3, 2], [4, 0, 5]]),
"1",
True,
torch.tensor([[6], [9]])
),
(
torch.tensor([[1, 3, 2], [4, 5, 6]]),
"0",
False,
torch.tensor([5, 8, 8])
),
(
torch.tensor([[1, 3, 2], [4, 5, 6], [7, 8, 9]]),
"1",
False,
torch.tensor([6, 15, 24])
),
(
torch.tensor([[1, 2], [3, 4]]),
"",
False,
torch.tensor(10) # Sum of all elements
),
(
torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]),
"(0, 1)",
False,
torch.tensor([16, 20]) # Sum over dimensions (0, 1)
)
]
def test_sum(self):
"""Test torch.sum behavior."""
for tens, dim, keepdim, expected in self.test_cases:
with self.subTest(tens=tens, dim=dim, keepdim=keepdim):
result, = self.node.f(tens, dim, keepdim)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected sum values
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-39
View File
@@ -1,39 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_tan import PtTan # Updated import to PtTan
class TestPtTan(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtTan()
# Test cases: (Tensor A, Expected result)
self.test_cases = [
(torch.tensor([0.0, torch.pi / 4, -torch.pi / 4], dtype=torch.float32), torch.tan(torch.tensor([0.0, torch.pi / 4, -torch.pi / 4], dtype=torch.float32))), # Common angles
(torch.tensor([0.5, -0.5], dtype=torch.float32), torch.tan(torch.tensor([0.5, -0.5], dtype=torch.float32))), # General values
(torch.tensor([[0.1, -0.3], [0.7, -0.9]], dtype=torch.float32), torch.tan(torch.tensor([[0.1, -0.3], [0.7, -0.9]], dtype=torch.float32))), # 2D case
(torch.full((2, 2), 0.6, dtype=torch.float32), torch.tan(torch.full((2, 2), 0.6, dtype=torch.float32))), # Constant matrix
]
def test_tan(self):
"""Test tensor element-wise tangent using torch.tan()."""
for tens_a, expected in self.test_cases:
with self.subTest(tens_a=tens_a):
result, = self.node.f(tens_a)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected tan values
self.assertTrue(torch.allclose(result, expected, atol=1e-6), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-39
View File
@@ -1,39 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_tanh import PtTanh # Updated import to PtTanh
class TestPtTanh(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtTanh()
# Test cases: (Tensor A, Expected result)
self.test_cases = [
(torch.tensor([0.0, 1.0, -1.0], dtype=torch.float32), torch.tanh(torch.tensor([0.0, 1.0, -1.0], dtype=torch.float32))), # Common values
(torch.tensor([0.5, -0.5], dtype=torch.float32), torch.tanh(torch.tensor([0.5, -0.5], dtype=torch.float32))), # General cases
(torch.tensor([[0.1, -0.3], [0.7, -0.9]], dtype=torch.float32), torch.tanh(torch.tensor([[0.1, -0.3], [0.7, -0.9]], dtype=torch.float32))), # 2D case
(torch.full((2, 2), 0.6, dtype=torch.float32), torch.tanh(torch.full((2, 2), 0.6, dtype=torch.float32))), # Constant matrix
]
def test_tanh(self):
"""Test tensor element-wise hyperbolic tangent using torch.tanh()."""
for tens_a, expected in self.test_cases:
with self.subTest(tens_a=tens_a):
result, = self.node.f(tens_a)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected tanh values
self.assertTrue(torch.allclose(result, expected, atol=1e-6), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
@@ -1,54 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_to_image_transpose import PtToImageTranspose
class TestPtToImageTranspose(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtToImageTranspose()
# Define test cases: (input_tensor, expected_shape)
self.test_cases = [
# Case 1: 3D tensor (C, H, W) -> (H, W, C)
(torch.ones(3, 64, 128), (64, 128, 3)), # (3,64,128) -> (64,128,3)
# Case 2: 4D tensor (N, C, H, W) -> (N, H, W, C)
(torch.ones(10, 3, 64, 128), (10, 64, 128, 3)), # (10,3,64,128) -> (10,64,128,3)
# Case 3: Invalid input (2D tensor)
(torch.ones(64, 128), ValueError), # 2D tensors should raise an error
# Case 4: Invalid input (5D tensor)
(torch.ones(10, 3, 64, 128, 2), ValueError), # 5D tensors should raise an error
]
def test_transpose(self):
"""Test tensor to image transposition with valid and invalid cases."""
for input_tensor, expected in self.test_cases:
with self.subTest(input_shape=input_tensor.shape):
if isinstance(expected, tuple):
# Valid cases
result, = self.node.f(input_tensor)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result has correct shape
self.assertEqual(result.shape, torch.Size(expected), f"Expected shape {expected}, got {result.shape}")
# Ensure result has the same dtype
self.assertEqual(result.dtype, input_tensor.dtype, "Dtype mismatch after transpose operation")
else:
# Invalid cases should raise an error
with self.assertRaises(expected):
self.node.f(input_tensor)
if __name__ == "__main__":
unittest.main()
-64
View File
@@ -1,64 +0,0 @@
import os
import sys
import unittest
import torch
import numpy as np
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_to_numpy import PtToNumpy
class TestPtToNumpy(unittest.TestCase):
def setUp(self):
"""Set up test data."""
self.node = PtToNumpy()
# Test cases covering rank 0 (scalar) to rank 5 tensors
self.test_cases = [
# Rank 0 (scalar) int32
(torch.tensor(12345, dtype=torch.int32), np.array(12345, dtype=np.int32)),
# Rank 0 (scalar) float32
(torch.tensor(12345.6, dtype=torch.float32), np.array(12345.6, dtype=np.float32)),
# Rank 1 (1D array) int32
(torch.tensor([1, 2, 3], dtype=torch.int32), np.array([1, 2, 3], dtype=np.int32)),
# Rank 1 (1D array) float32
(torch.tensor([1.1, 2.2, 3.3], dtype=torch.float32), np.array([1.1, 2.2, 3.3], dtype=np.float32)),
# Rank 2 (2D matrix) int32
(torch.tensor([[1, 2, 3], [4, 5, 6]], dtype=torch.int32), np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32)),
# Rank 2 (2D matrix) float32
(torch.tensor([[1.1, 2.2], [3.3, 4.4]], dtype=torch.float32), np.array([[1.1, 2.2], [3.3, 4.4]], dtype=np.float32)),
# Rank 3 (3D tensor) int32
(torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], dtype=torch.int32),
np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], dtype=np.int32)),
# Rank 3 (3D tensor) float32
(torch.tensor([[[1.1, 2.2], [3.3, 4.4]], [[5.5, 6.6], [7.7, 8.8]]], dtype=torch.float32),
np.array([[[1.1, 2.2], [3.3, 4.4]], [[5.5, 6.6], [7.7, 8.8]]], dtype=np.float32)),
]
def test_convert_tensor_to_numpy(self):
"""Test conversion of PyTorch tensor to NumPy ndarray."""
for torch_tensor, expected_array in self.test_cases:
with self.subTest(data=torch_tensor):
retval = self.node.f(torch_tensor)[0]
# Ensure the returned value is a NumPy array
self.assertTrue(isinstance(retval, np.ndarray), f"Expected ndarray, got {type(retval)}")
# Ensure the dtype matches
self.assertEqual(retval.dtype, expected_array.dtype, f"Dtype mismatch for input: {torch_tensor}")
# Ensure the shape matches
self.assertEqual(retval.shape, expected_array.shape,
f"Shape mismatch for input: {torch_tensor} (Expected {expected_array.shape}, got {retval.shape})")
# Ensure values match
np.testing.assert_array_equal(retval, expected_array,
f"Value mismatch for input: {torch_tensor}")
if __name__ == "__main__":
unittest.main()
@@ -1,69 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_to_rgb_tensors import PtToRgbTensors
class TestPtToRgbTensors(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtToRgbTensors()
# Test cases: (Input tensor, Expected R, Expected G, Expected B)
self.test_cases = [
# 3D Tensor: [H, W, C]
(
torch.tensor([[[255, 128, 64], [0, 127, 255]]], dtype=torch.uint8),
torch.tensor([[255, 0]], dtype=torch.uint8),
torch.tensor([[128, 127]], dtype=torch.uint8),
torch.tensor([[64, 255]], dtype=torch.uint8),
),
# 4D Tensor: [B, H, W, C]
(
torch.tensor(
[[[[255, 0, 0], [0, 255, 0]], [[0, 0, 255], [255, 255, 255]]]], dtype=torch.uint8
),
torch.tensor([[[255, 0], [0, 255]]], dtype=torch.uint8),
torch.tensor([[[0, 255], [0, 255]]], dtype=torch.uint8),
torch.tensor([[[0, 0], [255, 255]]], dtype=torch.uint8),
),
]
def test_split_rgb(self):
"""Test splitting RGB tensors correctly."""
for tensor, expected_r, expected_g, expected_b in self.test_cases:
with self.subTest(tensor_shape=tensor.shape):
r, g, b = self.node.f(tensor)
# Ensure return values are tensors
self.assertTrue(isinstance(r, torch.Tensor), "R is not a tensor")
self.assertTrue(isinstance(g, torch.Tensor), "G is not a tensor")
self.assertTrue(isinstance(b, torch.Tensor), "B is not a tensor")
# Ensure shapes match
self.assertEqual(r.shape, expected_r.shape, f"R shape mismatch: expected {expected_r.shape}, got {r.shape}")
self.assertEqual(g.shape, expected_g.shape, f"G shape mismatch: expected {expected_g.shape}, got {g.shape}")
self.assertEqual(b.shape, expected_b.shape, f"B shape mismatch: expected {expected_b.shape}, got {b.shape}")
# Ensure values match
torch.testing.assert_close(r, expected_r, msg="R values mismatch")
torch.testing.assert_close(g, expected_g, msg="G values mismatch")
torch.testing.assert_close(b, expected_b, msg="B values mismatch")
def test_invalid_input(self):
"""Test error handling for non-3-channel input."""
invalid_tensor = torch.rand(1, 512, 512, 4) # 4 channels instead of 3
with self.assertRaises(ValueError) as context:
self.node.f(invalid_tensor)
self.assertIn("Expected a 3-channel tensor", str(context.exception))
if __name__ == "__main__":
unittest.main()
@@ -1,63 +0,0 @@
import os
import sys
import unittest
import torch
import torch.nn as nn
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.ptn_conv_model import PtnConvModel
from pytorch_wrapper.pto_adam import PtoAdam
from pytorch_wrapper.ptv_dataset import PtvDataset
from pytorch_wrapper.ptv_transforms_to_tensor import PtvTransformsToTensor
from pytorch_wrapper.pt_data_loader import PtDataLoader
from pytorch_wrapper.pt_train_classification_model import PtTrainClassificationModel
from pytorch_wrapper.pt_save_model import PtSaveModel
class TestPtTrainConvModel(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
compose_node = PtvTransformsToTensor()
transform = compose_node.f()[0]
dataset_node = PtvDataset()
dataset = dataset_node.f("FashionMNIST",
True, # download
"", # root
'{"train": True}',
transform=transform)[0]
data_loader_node = PtDataLoader()
self.train_loader = data_loader_node.f(
dataset=dataset,
batch_size=32,
shuffle=True,
parameters='{"num_workers":1}'
)[0]
self.model_node = PtnConvModel()
self.model = self.model_node.f(
input_dim="(1, 28, 28)",
penultimate_dim=0,
output_dim=10,
channel_list="[32,64,128,256]",
kernel_size_list="[3,3,3,3]",
padding_list="[1,1,1,1]",
downsample_list="[True,True,True,True]"
)[0]
self.optimizer = PtoAdam().f(self.model, 0.001, 0.9, 0.999)[0]
self.trainer = PtTrainClassificationModel()
self.save_model = PtSaveModel()
def test_1(self):
epochs = 1
trained_model = self.trainer.f(self.model, self.train_loader, self.optimizer,
epochs, # epochs
use_gpu=True)[0]
self.save_model.f(trained_model, f"fashion_mnist_{epochs}_epochs_conv.pt")
if __name__ == "__main__":
unittest.main()
@@ -1,73 +0,0 @@
import os
import sys
import unittest
import torch
import torch.nn as nn
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.ptn_conv_model import PtnConvModel
from pytorch_wrapper.pto_adam import PtoAdam
from pytorch_wrapper.ptv_image_folder_dataset import PtvImageFolderDataset
from pytorch_wrapper.ptv_transforms_resize import PtvTransformsResize
from pytorch_wrapper.pt_data_loader import PtDataLoader
from pytorch_wrapper.pt_train_classification_model import PtTrainClassificationModel
from pytorch_wrapper.pt_save_model import PtSaveModel
class TestPtTrainConvModel2(unittest.TestCase):
@unittest.skipIf(os.getenv("RUN_SKIPPED_TESTS") != "1", "Skipping unless explicitly enabled")
def setUp(self):
"""Set up test instance."""
compose_node = PtvTransformsResize()
transform = compose_node.f(256, 256)[0]
self.node = PtvImageFolderDataset()
train_dataset = self.node.f("dog_and_cat/train",
transform=transform)[0]
train_data_loader_node = PtDataLoader()
val_dataset = self.node.f("dog_and_cat/val",
transform=transform)[0]
val_data_loader_node = PtDataLoader()
self.train_loader = train_data_loader_node.f(
dataset=train_dataset,
batch_size=32,
shuffle=True,
parameters='{"num_workers":1}'
)[0]
self.val_loader = val_data_loader_node.f(
dataset=val_dataset,
batch_size=32,
shuffle=True,
parameters='{"num_workers":1}'
)[0]
self.model_node = PtnConvModel()
self.model = self.model_node.f(
input_dim="(3, 256, 256)",
penultimate_dim=0,
output_dim=2,
channel_list="[32,64,128,256,512]", # To 128, 64, 32, 16, 8
kernel_size_list="[3,3,3,3,3]",
padding_list="[1,1,1,1,1]",
downsample_list="[True,True,True,True,True]"
)[0]
self.optimizer = PtoAdam().f(self.model, 0.0001, 0.9, 0.999)[0]
self.trainer = PtTrainClassificationModel()
self.save_model = PtSaveModel()
@unittest.skipIf(os.getenv("RUN_SKIPPED_TESTS") != "1", "Skipping unless explicitly enabled")
def test_1(self):
epochs = 20
trained_model = self.trainer.f(self.model, self.train_loader, self.optimizer,
epochs, # epochs
use_gpu=True,
val_loader=self.val_loader)[0]
self.save_model.f(trained_model, f"dog_cat_{epochs}_epochs_conv.pt")
if __name__ == "__main__":
unittest.main()
@@ -1,59 +0,0 @@
import os
import sys
import unittest
import torch
import torch.nn as nn
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.ptn_linear_model import PtnLinearModel
from pytorch_wrapper.pto_adam import PtoAdam
from pytorch_wrapper.ptv_dataset import PtvDataset
from pytorch_wrapper.ptv_transforms_to_tensor import PtvTransformsToTensor
from pytorch_wrapper.pt_data_loader import PtDataLoader
from pytorch_wrapper.pt_train_classification_model import PtTrainClassificationModel
from pytorch_wrapper.pt_save_model import PtSaveModel
class TestPtTrainModel(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
compose_node = PtvTransformsToTensor()
transform = compose_node.f()[0]
dataset_node = PtvDataset()
dataset = dataset_node.f("FashionMNIST",
True, # download
"", # root
'{"train": True}',
transform=transform)[0]
data_loader_node = PtDataLoader()
self.train_loader = data_loader_node.f(
dataset=dataset,
batch_size=32,
shuffle=True,
parameters='{"num_workers":1}'
)[0]
self.model_node = PtnLinearModel()
self.model = self.model_node.f(
"784,180,42,10", # input dim for first layer, output dim for each layer
"True,True,True", # bias
3 # num layers
)[0]
self.optimizer = PtoAdam().f(self.model, 0.001, 0.9, 0.999)[0]
self.trainer = PtTrainClassificationModel()
self.save_model = PtSaveModel()
def test_1(self):
epochs = 1
trained_model = self.trainer.f(self.model, self.train_loader, self.optimizer,
epochs, # epochs
use_gpu=True)[0]
self.save_model.f(trained_model, f"fashion_mnist_{epochs}_epochs.pt")
if __name__ == "__main__":
unittest.main()
@@ -1,51 +0,0 @@
import os
import sys
import unittest
import torch
import torch.nn as nn
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.ptn_linear_model import PtnLinearModel
from pytorch_wrapper.pto_adam import PtoAdam
from pytorch_wrapper.ptv_dataset_loader import PtvDatasetLoader
from pytorch_wrapper.pt_train_classification_model import PtTrainClassificationModel
from pytorch_wrapper.pt_save_model import PtSaveModel
class TestPtTrainModelWithDatasetLoader(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.dataset_loader_node = PtvDatasetLoader()
self.train_loader = self.dataset_loader_node.f(
"MNIST",
True, # download
"", # root
batch_size=128,
shuffle=True,
dataset_parameters='{"train": True}',
load_parameters='{"num_workers":1}'
)[0]
self.model_node = PtnLinearModel()
self.model = self.model_node.f(
"784,180,42,10", # input dim for first layer, output dim for each layer
"True,True,True", # bias
3 # num layers
)[0]
self.optimizer = PtoAdam().f(self.model, 0.001, 0.9, 0.999)[0]
self.trainer = PtTrainClassificationModel()
self.save_model = PtSaveModel()
def test_1(self):
epochs = 2
trained_model = self.trainer.f(self.model, self.train_loader, self.optimizer,
epochs, # epochs
use_gpu=True)[0]
self.save_model.f(trained_model, f"mnist_{epochs}_epochs.pt")
if __name__ == "__main__":
unittest.main()
@@ -1,57 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_unsqueeze import PtUnsqueeze # Importing the PtUnsqueeze class
class TestPtUnsqueeze(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtUnsqueeze()
# Define test cases: (input_tensor, dim, expected_shape)
self.test_cases = [
# Case 1: Adding a singleton dimension at different positions
(torch.ones(3, 4), 0, (1, 3, 4)), # (3,4) -> (1,3,4)
(torch.ones(3, 4), 1, (3, 1, 4)), # (3,4) -> (3,1,4)
(torch.ones(3, 4), 2, (3, 4, 1)), # (3,4) -> (3,4,1)
# Case 2: Adding a singleton dimension at negative indices
(torch.ones(3, 4), -1, (3, 4, 1)), # (3,4) -> (3,4,1)
(torch.ones(3, 4), -2, (3, 1, 4)), # (3,4) -> (3,1,4)
(torch.ones(3, 4), -3, (1, 3, 4)), # (3,4) -> (1,3,4)
# Case 3: Adding multiple dimensions one by one
(torch.ones(3,), 0, (1, 3)), # (3,) -> (1,3)
(torch.ones(3,), 1, (3, 1)), # (3,) -> (3,1)
(torch.ones(3,), -1, (3, 1)), # (3,) -> (3,1)
# Case 4: Expanding an already multi-dimensional tensor
(torch.ones(2, 3, 4), 1, (2, 1, 3, 4)), # (2,3,4) -> (2,1,3,4)
(torch.ones(2, 3, 4), -1, (2, 3, 4, 1)), # (2,3,4) -> (2,3,4,1)
]
def test_unsqueeze(self):
"""Test tensor unsqueeze operation on various dimensions."""
for input_tensor, dim, expected_shape in self.test_cases:
with self.subTest(input_shape=input_tensor.shape, dim=dim):
result, = self.node.f(input_tensor, dim)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result has correct shape
self.assertEqual(result.shape, torch.Size(expected_shape), f"Expected shape {expected_shape}, got {result.shape}")
# Ensure result has the same dtype
self.assertEqual(result.dtype, input_tensor.dtype, "Dtype mismatch after unsqueeze operation")
if __name__ == "__main__":
unittest.main()
-83
View File
@@ -1,83 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_var import PtVar
class TestPtVar(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtVar()
# Define test cases with string-based dimensions
self.test_cases = [
# Sample variance (Bessel's correction) along dim=0
(
torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]),
"0",
1,
False,
torch.var(torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), dim=0, correction=1, keepdim=False)
),
# Sample variance along dim=1, with keepdim=True
(
torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]),
"1",
1,
True,
torch.var(torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), dim=1, correction=1, keepdim=True)
),
# Sample variance across both axes (dim=(0,1))
(
torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]),
"(0, 1)",
1,
False,
torch.var(torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), dim=(0, 1), correction=1, keepdim=False)
),
# Sample variance across all elements (dim=None) - Entire tensor
(
torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]),
"",
1,
False,
torch.var(torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), correction=1, keepdim=False)
),
# Population variance along dim=0 (correction=0)
(
torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]),
"0",
0,
False,
torch.var(torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), dim=0, correction=0, keepdim=False)
),
# Population variance along dim=1 with keepdim=True (correction=0)
(
torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]),
"1",
0,
True,
torch.var(torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), dim=1, correction=0, keepdim=True)
)
]
def test_var(self):
"""Test torch.var behavior."""
for tens, dim, correction, keepdim, expected in self.test_cases:
with self.subTest(tens=tens, dim=dim, correction=correction, keepdim=keepdim):
result, = self.node.f(tens, dim, correction, keepdim)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected variance values
self.assertTrue(torch.allclose(result, expected, atol=1e-6), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-61
View File
@@ -1,61 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_view import PtView # Importing the PtView class
class TestPtView(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtView()
# Define test cases: (input_tensor, new_shape, expected_shape)
self.test_cases = [
# Case 1: Reshape a 2D tensor
(torch.ones(2, 3), "[3, 2]", (3, 2)), # (2,3) -> (3,2)
# Case 2: Reshape a 3D tensor
(torch.ones(2, 3, 4), "[6, 4]", (6, 4)), # (2,3,4) -> (6,4)
# Case 3: Using -1 for automatic inference
(torch.ones(2, 3, 4), "[2, -1]", (2, 12)), # (2,3,4) -> (2,12)
(torch.ones(6, 4), "[-1, 4]", (6, 4)), # (6,4) -> (6,4)
# Case 4: Flattening a multi-dimensional tensor
(torch.ones(2, 3, 4), "[-1]", (24,)), # (2,3,4) -> (24,)
# Case 5: Expanding dimensions
(torch.ones(6,), "[2, 3]", (2, 3)), # (6,) -> (2,3)
# Case 6: Reshaping a 4D tensor
(torch.ones(2, 3, 4, 5), "[6, -1, 5]", (6, 4, 5)), # (2,3,4,5) -> (6,4,5)
# Case 7: Edge case with 1D tensor
(torch.ones(10,), "[10, 1]", (10, 1)), # (10,) -> (10,1)
]
def test_view(self):
"""Test tensor reshape operation with various shape orders."""
for input_tensor, new_shape, expected_shape in self.test_cases:
with self.subTest(input_shape=input_tensor.shape, new_shape=new_shape):
result, = self.node.f(input_tensor, new_shape)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result has correct shape
self.assertEqual(result.shape, torch.Size(expected_shape), f"Expected shape {expected_shape}, got {result.shape}")
# Ensure result has the same dtype
self.assertEqual(result.dtype, input_tensor.dtype, "Dtype mismatch after view operation")
if __name__ == "__main__":
unittest.main()
-59
View File
@@ -1,59 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_where import PtWhere
class TestPtWhere(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtWhere()
# Test cases: (Condition Tensor, True Tensor, False Tensor, Expected Output)
self.test_cases = [
(
torch.tensor([[True, False], [False, True]]),
torch.tensor([[1, 2], [3, 4]]),
torch.tensor([[5, 6], [7, 8]]),
torch.tensor([[1, 6], [7, 4]])
),
(
torch.tensor([True, False, True]),
torch.tensor([10, 20, 30]),
torch.tensor([100, 200, 300]),
torch.tensor([10, 200, 30])
),
(
torch.tensor([[False, False], [True, True]]),
torch.tensor([[1.5, 2.5], [3.5, 4.5]]),
torch.tensor([[5.5, 6.5], [7.5, 8.5]]),
torch.tensor([[5.5, 6.5], [3.5, 4.5]])
),
(
torch.tensor([[[True, False], [False, True]], [[False, True], [True, False]]]),
torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]),
torch.tensor([[[9, 10], [11, 12]], [[13, 14], [15, 16]]]),
torch.tensor([[[1, 10], [11, 4]], [[13, 6], [7, 16]]])
),
]
def test_where(self):
"""Test torch.where behavior."""
for condition_tens, true_tens, false_tens, expected in self.test_cases:
with self.subTest(condition_tens=condition_tens, true_tens=true_tens, false_tens=false_tens):
result, = self.node.f(condition_tens, true_tens, false_tens)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result matches expected values
self.assertTrue(torch.equal(result, expected), f"Expected {expected}, got {result}")
if __name__ == "__main__":
unittest.main()
-44
View File
@@ -1,44 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.pt_zeros import PtZeros # Importing the PtZeros class
from pytorch_wrapper.utils import DTYPE_MAPPING # Importing the dtype mapping
class TestPtZeros(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.node = PtZeros()
# Tensor size to test
self.size_str = "[2, 3]" # Using a small 2D tensor size for all tests
self.expected_shape = (2, 3)
def test_zeros_tensor_all_dtypes(self):
"""Test tensor creation with zeros for all supported data types."""
for data_type, torch_dtype in DTYPE_MAPPING.items():
with self.subTest(data_type=data_type):
result, = self.node.f(self.size_str, data_type)
# Ensure return value is a tensor
self.assertTrue(isinstance(result, torch.Tensor), "Output is not a tensor")
# Ensure result has correct shape
self.assertEqual(result.shape, torch.Size(self.expected_shape), f"Expected shape {self.expected_shape}, got {result.shape}")
# Ensure result has correct dtype
self.assertEqual(result.dtype, torch_dtype, f"Expected dtype {torch_dtype}, got {result.dtype}")
# Ensure all elements are zeros
expected = torch.zeros(self.expected_shape, dtype=torch_dtype)
self.assertTrue(torch.equal(result, expected), f"Tensor values do not match expected zeros tensor for dtype {data_type}")
if __name__ == "__main__":
unittest.main()
@@ -1,158 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.ptn_conv_model_def import ConvModel, ConvSingleLayer
class TestPtnConvModelDef(unittest.TestCase):
def setUp(self):
"""Setup method for initializing test conditions."""
pass
def test_single_layer_1_with_padding(self):
"""Test ConvSingleLayer with padding=1, no downsampling."""
model = ConvSingleLayer(
in_channels=4,
out_channels=32,
kernel_size=3,
padding=1,
downsample=False,
apply_activation=True)
x = torch.ones(1, 4, 28, 28)
out = model(x)
self.assertEqual(out.size(), torch.Size([1, 32, 28, 28]))
def test_single_layer_no_padding(self):
"""Test ConvSingleLayer with padding=0, no downsampling."""
model = ConvSingleLayer(
in_channels=4,
out_channels=32,
kernel_size=3,
padding=0,
downsample=False,
apply_activation=True)
x = torch.ones(1, 4, 28, 28)
out = model(x)
self.assertEqual(out.size(), torch.Size([1, 32, 26, 26]))
def test_single_layer_3_no_padding_downsample(self):
"""Test ConvSingleLayer with padding=0 and downsampling enabled."""
model = ConvSingleLayer(
in_channels=4,
out_channels=32,
kernel_size=3,
padding=0,
downsample=True,
apply_activation=True)
x = torch.ones(1, 4, 28, 28)
out = model(x)
self.assertEqual(out.size(), torch.Size([1, 32, 13, 13]))
def test_1(self):
"""Test ConvModel with a single convolutional layer, checking output size."""
model = ConvModel(
input_dim=(4, 28, 28),
penultimate_dim=0,
output_dim=10,
channel_list=[32],
kernel_size_list=[3],
padding_list=[1],
downsample_list=[False])
x = torch.ones(1, 4, 28, 28)
out = model(x)
self.assertEqual(out.size(), torch.Size([1, 10]))
def test_2(self):
"""Test ConvModel intermediate convolution layers' output size."""
model = ConvModel(
input_dim=(4, 28, 28),
penultimate_dim=0,
output_dim=10,
channel_list=[32],
kernel_size_list=[3],
padding_list=[1],
downsample_list=[False])
x = torch.ones(1, 4, 28, 28)
for c in model.conv_layers:
x = c(x)
out = x
self.assertEqual(out.size(), torch.Size([1, 32, 28, 28]))
def test_3(self):
"""Test ConvModel with two convolutional layers and downsampling enabled."""
model = ConvModel(
input_dim=(4, 28, 28),
penultimate_dim=0,
output_dim=10,
channel_list=[32,64],
kernel_size_list=[3,3],
padding_list=[1,1],
downsample_list=[True,True])
x = torch.ones(1, 4, 28, 28)
for c in model.conv_layers:
x = c(x)
out = x
self.assertEqual(out.size(), torch.Size([1, 64, 7, 7]))
def test_4(self):
"""Test ConvModel with three convolutional layers and downsampling enabled."""
model = ConvModel(
input_dim=(4, 28, 28),
penultimate_dim=0,
output_dim=10,
channel_list=[32,64,128],
kernel_size_list=[3,3,3],
padding_list=[1,1,1],
downsample_list=[True,True,True])
x = torch.ones(1, 4, 28, 28)
for c in model.conv_layers:
x = c(x)
out = x
self.assertEqual(out.size(), torch.Size([1, 128, 3, 3]))
def test_5(self):
"""Test ConvModel with four convolutional layers and downsampling enabled."""
model = ConvModel(
input_dim=(4, 28, 28),
penultimate_dim=0,
output_dim=10,
channel_list=[32,64,128,256],
kernel_size_list=[3,3,3,3],
padding_list=[1,1,1,1],
downsample_list=[True,True,True,True])
x = torch.ones(1, 4, 28, 28)
for c in model.conv_layers:
x = c(x)
out = x
self.assertEqual(out.size(), torch.Size([1, 256, 1, 1]))
def test_6(self):
"""Test ConvModel with five convolutional layers, last layer without downsampling."""
model = ConvModel(
input_dim=(4, 28, 28),
penultimate_dim=0,
output_dim=10,
channel_list=[32,64,128,256,512],
kernel_size_list=[3,3,3,3,1],
padding_list=[1,1,1,1,0],
downsample_list=[True,True,True,True,False])
x = torch.ones(1, 4, 28, 28)
for c in model.conv_layers:
x = c(x)
out = x
self.assertEqual(out.size(), torch.Size([1, 512, 1, 1]))
if __name__ == "__main__":
unittest.main()
@@ -1,64 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.ptn_conv_model import PtnConvModel
class TestPtnConvModel(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.model_node = PtnConvModel()
def test_forward(self):
model = self.model_node.f(
input_dim="(4, 28, 28)",
penultimate_dim=0,
output_dim=10,
channel_list="[32,64,128,256]",
kernel_size_list="[3,3,3,3]",
padding_list="[1,1,1,1]",
downsample_list="[True,True,True,True]"
)[0]
bs = 2
x = torch.ones(bs, 4, 28, 28)
out = model(x)
self.assertEqual(out.size(), torch.Size([bs, 10]))
def test_rank3_input(self):
model = self.model_node.f(
input_dim="(1, 28, 28)",
penultimate_dim=0,
output_dim=10,
channel_list="[32,64,128,256]",
kernel_size_list="[3,3,3,3]",
padding_list="[1,1,1,1]",
downsample_list="[True,True,True,True]"
)[0]
bs = 2
x = torch.ones(bs, 28, 28)
out = model(x)
self.assertEqual(out.size(), torch.Size([bs, 10]))
def test_rank2_input(self):
model = self.model_node.f(
input_dim="(1, 28, 28)",
penultimate_dim=0,
output_dim=10,
channel_list="[32,64,128,256]",
kernel_size_list="[3,3,3,3]",
padding_list="[1,1,1,1]",
downsample_list="[True,True,True,True]"
)[0]
bs = 2
x = torch.ones(bs, 28)
with self.assertRaises(ValueError) as context:
model(x)
if __name__ == "__main__":
unittest.main()
@@ -1,29 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.ptn_linear_model import PtnLinearModel # Updated import to PtnLinear
class TestPtnLinearModel(unittest.TestCase):
def setUp(self):
"""Set up test instance."""
self.model_node = PtnLinearModel()
self.model = self.model_node.f(
"784,180,42,10", # input dim for first layer, output dim for each layer
"True,True,True", # bias
3 # num layers
)[0] # HINADA note: Using roughly 0.23x ratio for reduction
def test_forward(self):
x = torch.ones(4, 28, 28)
out = self.model(x)
self.assertEqual(out.size(), torch.Size([4, 10]))
if __name__ == "__main__":
unittest.main()
@@ -1,34 +0,0 @@
import os
import sys
import unittest
import torch
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
MODULE_ROOT = os.path.join(PROJECT_ROOT, "modules")
sys.path.append(MODULE_ROOT)
from pytorch_wrapper.ptv_dataset_loader import PtvDatasetLoader
class TestPtDataLoader(unittest.TestCase):
def setUp(self):
"""Set up test data."""
self.dataset_loader_node = PtvDatasetLoader()
def test1(self):
"""Tests downloading data and checks dimension"""
bs = 2
train_data = self.dataset_loader_node.f(
"MNIST",
True, # download
"", # root
batch_size=bs,
shuffle=True,
dataset_parameters='{"train": True}',
load_parameters='{"num_workers":1}'
)[0]
x, y = next(iter(train_data))
self.assertEqual(x.size(), torch.Size([bs, 1, 28, 28]))
self.assertEqual(y.size(), torch.Size([bs]))
if __name__ == "__main__":
unittest.main()

Some files were not shown because too many files have changed in this diff Show More