def test_seq_batchmatmul6(): """ No sequence axis, left operand is matrix, right operand is tensor """ dynamic_batch = 2 matmul_batch = 3 batch_shape = (dynamic_batch, matmul_batch) inner_dim = 2 left_operand_shape = (5, inner_dim) right_operand_shape = (inner_dim, 6, 3) final_shape = (5, 6, 3) n = np.random.random(batch_shape + left_operand_shape).astype(np.float32) m = np.random.random(batch_shape + right_operand_shape).astype(np.float32) a = C.input_variable((matmul_batch,) + left_operand_shape) b = C.input_variable((matmul_batch,) + right_operand_shape) c = batchmatmul(a, b, output_rank=2) assert c.shape == (matmul_batch, ) + final_shape desired_packed = n @ m.reshape(batch_shape + (inner_dim, -1)) desired = desired_packed.reshape(batch_shape + final_shape) result = c.eval({a: n, b: m}) result = np.array(result) np.testing.assert_almost_equal(result, desired, decimal=7)
def test_seq_batchmatmul7(): """ sequence axis present with samples of uneven sequence length left operand is matrix, right operand is matrix """ # uneven sequence length between batches n = [np.random.random((4, 3, 5, 2)).astype(np.float32), np.random.random((2, 3, 5, 2)).astype(np.float32), np.random.random((7, 3, 5, 2)).astype(np.float32)] m = [np.random.random((4, 3, 2, 7)).astype(np.float32), np.random.random((2, 3, 2, 7)).astype(np.float32), np.random.random((7, 3, 2, 7)).astype(np.float32)] a = C.sequence.input_variable((3, 5, 2)) b = C.sequence.input_variable((3, 2, 7)) c = batchmatmul(a, b) assert c.shape == (3, 5, 7) desired_packed = [nn @ mm for nn, mm in zip(n, m)] desired_results = desired_packed results = c.eval({a: n, b: m}) assert len(results) == len(desired_results) for result, desired in zip(results, desired_results): np.testing.assert_almost_equal(result, desired, decimal=7)
def test_seq_batchmatmul3(): """ sequence axis present, left operand is matrix and right operand is tensor """ dynamic_batch = 2 seq_len = 4 matmul_batch = 3 batch_shape = (dynamic_batch, seq_len, matmul_batch) left_operand_shape = (5, 2) right_operand_shape = (2, 6, 3) final_shape = (5, 6, 3) n = np.random.random(batch_shape + left_operand_shape).astype(np.float32) m = np.random.random(batch_shape + right_operand_shape).astype(np.float32) a = C.sequence.input_variable((matmul_batch, ) + left_operand_shape) b = C.sequence.input_variable((matmul_batch, ) + right_operand_shape) c = batchmatmul(a, b, output_rank=2) assert c.shape == (matmul_batch, ) + final_shape desired_packed = n @ m.reshape(batch_shape + (2, -1)) desired = desired_packed.reshape(batch_shape + final_shape) result = c.eval({a: n, b: m}) result = np.array(result) np.testing.assert_almost_equal(result, desired, decimal=7)