|
5 | 5 | import pytest
|
6 | 6 |
|
7 | 7 | import pytensor
|
8 |
| -from pytensor import config |
| 8 | +from pytensor import config, function |
9 | 9 | from pytensor.gradient import grad
|
10 | 10 | from pytensor.graph import Apply, Op
|
11 | 11 | from pytensor.graph.replace import vectorize_node
|
@@ -38,6 +38,56 @@ def test_vectorize_blockwise():
|
38 | 38 | assert new_vect_node.inputs[0] is tns4
|
39 | 39 |
|
40 | 40 |
|
| 41 | +def check_blockwise_runtime_broadcasting(mode): |
| 42 | + a = tensor("a", shape=(None, 3, 5)) |
| 43 | + b = tensor("b", shape=(None, 5, 3)) |
| 44 | + |
| 45 | + out = a @ b |
| 46 | + fn = function([a, b], out, mode=mode) |
| 47 | + assert isinstance(fn.maker.fgraph.outputs[0].owner.op, Blockwise) |
| 48 | + |
| 49 | + for valid_test_values in [ |
| 50 | + ( |
| 51 | + np.ones((2, 3, 5)).astype(config.floatX), |
| 52 | + np.ones((2, 5, 3)).astype(config.floatX), |
| 53 | + ), |
| 54 | + ( |
| 55 | + np.ones((1, 3, 5)).astype(config.floatX), |
| 56 | + np.ones((1, 5, 3)).astype(config.floatX), |
| 57 | + ), |
| 58 | + ]: |
| 59 | + batch_dim = valid_test_values[0].shape[0] |
| 60 | + np.testing.assert_allclose( |
| 61 | + fn(*valid_test_values), np.full((batch_dim, 3, 3), 5.0) |
| 62 | + ) |
| 63 | + |
| 64 | + for invalid_test_values in [ |
| 65 | + ( |
| 66 | + np.ones((1, 3, 5)).astype(config.floatX), |
| 67 | + np.ones((2, 5, 3)).astype(config.floatX), |
| 68 | + ), |
| 69 | + ( |
| 70 | + np.ones((2, 3, 5)).astype(config.floatX), |
| 71 | + np.ones((1, 5, 3)).astype(config.floatX), |
| 72 | + ), |
| 73 | + ]: |
| 74 | + with pytest.raises(ValueError, match="Runtime broadcasting not allowed"): |
| 75 | + fn(*invalid_test_values) |
| 76 | + |
| 77 | + invalid_test_values = ( |
| 78 | + np.ones((2, 3, 5)).astype(config.floatX), |
| 79 | + np.ones((3, 5, 3)).astype(config.floatX), |
| 80 | + ) |
| 81 | + # Error message is backend specific |
| 82 | + with pytest.raises(ValueError): |
| 83 | + fn(*invalid_test_values) |
| 84 | + |
| 85 | + |
| 86 | +@pytest.mark.parametrize("mode", ("FAST_COMPILE", "FAST_RUN")) |
| 87 | +def test_runtime_broadcast(mode): |
| 88 | + check_blockwise_runtime_broadcasting(mode) |
| 89 | + |
| 90 | + |
41 | 91 | class TestOp(Op):
|
42 | 92 | def make_node(self, *inputs):
|
43 | 93 | return Apply(self, inputs, [i.type() for i in inputs])
|
|
0 commit comments