|
| 1 | +import numpy as np |
| 2 | + |
| 3 | +import pytensor.tensor as pt |
| 4 | +from pytensor.compile.ops import DeepCopyOp, ViewOp |
| 5 | +from pytensor.configdefaults import config |
| 6 | +from pytensor.graph.fg import FunctionGraph |
| 7 | +from pytensor.tensor.shape import Shape, Shape_i, Unbroadcast, reshape |
| 8 | +from pytensor.tensor.type import iscalar, vector |
| 9 | +from tests.link.pytorch.test_basic import compare_pytorch_and_py |
| 10 | + |
| 11 | + |
| 12 | +def test_pytorch_shape_ops(): |
| 13 | + x_np = np.zeros((20, 3)) |
| 14 | + x = Shape()(pt.as_tensor_variable(x_np)) |
| 15 | + x_fg = FunctionGraph([], [x]) |
| 16 | + |
| 17 | + compare_pytorch_and_py(x_fg, [], must_be_device_array=False) |
| 18 | + |
| 19 | + x = Shape_i(1)(pt.as_tensor_variable(x_np)) |
| 20 | + x_fg = FunctionGraph([], [x]) |
| 21 | + |
| 22 | + compare_pytorch_and_py(x_fg, [], must_be_device_array=False) |
| 23 | + |
| 24 | + |
| 25 | +def test_pytorch_specify_shape(): |
| 26 | + in_pt = pt.matrix("in") |
| 27 | + x = pt.specify_shape(in_pt, (4, None)) |
| 28 | + x_fg = FunctionGraph([in_pt], [x]) |
| 29 | + compare_pytorch_and_py(x_fg, [np.ones((4, 5)).astype(config.floatX)]) |
| 30 | + |
| 31 | + # When used to assert two arrays have similar shapes |
| 32 | + in_pt = pt.matrix("in") |
| 33 | + shape_pt = pt.matrix("shape") |
| 34 | + x = pt.specify_shape(in_pt, shape_pt.shape) |
| 35 | + x_fg = FunctionGraph([in_pt, shape_pt], [x]) |
| 36 | + compare_pytorch_and_py( |
| 37 | + x_fg, |
| 38 | + [np.ones((4, 5)).astype(config.floatX), np.ones((4, 5)).astype(config.floatX)], |
| 39 | + ) |
| 40 | + |
| 41 | + |
| 42 | +def test_pytorch_Reshape_constant(): |
| 43 | + a = vector("a") |
| 44 | + x = reshape(a, (2, 2)) |
| 45 | + x_fg = FunctionGraph([a], [x]) |
| 46 | + compare_pytorch_and_py(x_fg, [np.r_[1.0, 2.0, 3.0, 4.0].astype(config.floatX)]) |
| 47 | + |
| 48 | + |
| 49 | +def test_pytorch_Reshape_shape_graph_input(): |
| 50 | + a = vector("a") |
| 51 | + shape_pt = iscalar("b") |
| 52 | + x = reshape(a, (shape_pt, shape_pt)) |
| 53 | + x_fg = FunctionGraph([a, shape_pt], [x]) |
| 54 | + compare_pytorch_and_py(x_fg, [np.r_[1.0, 2.0, 3.0, 4.0].astype(config.floatX), 2]) |
| 55 | + |
| 56 | + |
| 57 | +def test_pytorch_compile_ops(): |
| 58 | + x = DeepCopyOp()(pt.as_tensor_variable(1.1)) |
| 59 | + x_fg = FunctionGraph([], [x]) |
| 60 | + |
| 61 | + compare_pytorch_and_py(x_fg, []) |
| 62 | + |
| 63 | + x_np = np.zeros((20, 1, 1)) |
| 64 | + x = Unbroadcast(0, 2)(pt.as_tensor_variable(x_np)) |
| 65 | + x_fg = FunctionGraph([], [x]) |
| 66 | + |
| 67 | + compare_pytorch_and_py(x_fg, []) |
| 68 | + |
| 69 | + x = ViewOp()(pt.as_tensor_variable(x_np)) |
| 70 | + x_fg = FunctionGraph([], [x]) |
| 71 | + |
| 72 | + compare_pytorch_and_py(x_fg, []) |
0 commit comments