tensor-sensor
90 строк · 2.9 Кб
1"""
2MIT License
3
4Copyright (c) 2021 Terence Parr
5
6Permission is hereby granted, free of charge, to any person obtaining a copy
7of this software and associated documentation files (the "Software"), to deal
8in the Software without restriction, including without limitation the rights
9to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10copies of the Software, and to permit persons to whom the Software is
11furnished to do so, subject to the following conditions:
12
13The above copyright notice and this permission notice shall be included in all
14copies or substantial portions of the Software.
15
16THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22SOFTWARE.
23"""
24import jax.numpy as jnp25import numpy as np26import tsensor27
28def test_dot():29size = 500030x = np.random.normal(size=(size, size)).astype(np.float32)31y = np.random.normal(size=(5, 1)).astype(np.float32)32
33msg = ""34try:35with tsensor.clarify():36z = jnp.dot(x, y).block_until_ready()37except TypeError as e:38msg = e.args[0]39
40expected = "Incompatible shapes for dot: got (5000, 5000) and (5, 1).\n"+\41"Cause: jnp.dot(x, y) tensor arg x w/shape (5000, 5000), arg y w/shape (5, 1)"42assert msg==expected43
44
45def test_scalar_arg():46size = 500047x = np.random.normal(size=(size, size)).astype(np.float32)48
49msg = ""50try:51with tsensor.clarify():52z = jnp.dot(x, "foo")53except TypeError as e:54msg = e.args[0]55
56expected = 'data type \'foo\' not understood\n'+\57'Cause: jnp.dot(x, "foo") tensor arg x w/shape (5000, 5000)'58assert msg==expected59
60
61def test_mmul():62W = jnp.array([[1, 2], [3, 4]])63b = jnp.array([9, 10, 11])64
65msg = ""66try:67with tsensor.clarify():68y = W @ b69except TypeError as e:70msg = e.args[0]71
72expected = "dot_general requires contracting dimensions to have the same shape, got [2] and [3].\n"+\73"Cause: @ on tensor operand W w/shape (2, 2) and operand b w/shape (3,)"74assert msg==expected75
76
77def test_fft():78"Test a library function that doesn't have a shape related message in the exception."79x = np.exp(2j * np.pi * np.arange(8) / 8)80msg = ""81try:82with tsensor.clarify():83y = jnp.fft.fft(x, norm="something weird")84except BaseException as e:85msg = e.args[0]86print(msg)87
88expected = 'jax.numpy.fft.fft only supports norm=None, got something weird\n'+\89'Cause: jnp.fft.fft(x, norm="something weird") tensor arg x w/shape (8,)'90assert msg==expected91