Ejemplo n.º 1
0
 def testConvParameterRankExceptions(self):
     A = pkb.variable(m(2, 3, 1))
     B = pkb.variable(m(1, 2, 1))
     C = pkb.variable(m(2, 2, 2, 1))
     with self.assertRaises(ValueError):
         pkb.conv(A, C)
     with self.assertRaises(ValueError):
         pkb.conv(A, B, strides=(2, 3))
     with self.assertRaises(ValueError):
         pkb.conv(A, B, dilation_rate=(1, 1))
Ejemplo n.º 2
0
 def testTwoOutputs(self):
     x = pkb.variable(m(3))
     f = '''function (I[N]) -> (O1, O2) { O1 = I; O2 = I; }'''
     result = pkb._Op("TwoOut", x.dtype, (None, ), f, {'I': x},
                      ['O1', 'O2'])
     output = result.eval()
     return 0
Ejemplo n.º 3
0
 def testMicroAddElementsFail(self):
     data = [m(3, 3), m(3, 3)]
     test_func = self.testAddElements
     args = list()
     ###############
     x = [
         pkb.placeholder(shape=t.shape) for t in data
         if isinstance(t, np.ndarray)
     ]
     xv = [
         pkb.variable(t, dtype=floatx()) for t in data
         if isinstance(t, np.ndarray)
     ]
     par = [t for t in data if not isinstance(t, np.ndarray)]
     grad_funcs = test_func(pkb, *(x + par + list(args)))
     funcs = test_func(pkb, *(xv + par + list(args)))
     #for gf, f in zip(grad_funcs, funcs):
     gf = grad_funcs[0]
     f = funcs[0]
     df = pkb.gradients(pkb.mean(gf), x)
     gfn = pkb.function(x, df, updates=[])
     fr = f.eval()
     gr = gfn([t for t in data if isinstance(t, np.ndarray)])
     if args.verbose:
         print(pkb, fr, gr)
     results.append((fr, gr))
     return results
Ejemplo n.º 4
0
 def testAssignmentExceptions(self):
     A = pkb.variable(m(5, 1))
     B = pkb.variable(m(1, 5))
     f = """function (A[L, M], B[M, N]) -> (O) {
                O[i, k: L, N] = =(A[i, j] * B[j, k]);
            }"""
     # A * B has each entry a "sum" of exactly one product, and so assignment
     # is valid and should be the same as + aggregation.
     O = pkb._Op('assign_mul', A.dtype, (A.shape[0], B.shape[1]), f,
                 OrderedDict([('A', A), ('B', B)]), ['O']).eval()
     npt.assert_allclose(O, np.dot(m(5, 1), m(1, 5)))
     # B * A sums multiple products into one output entry, and so assignment
     # is not valid and should raise a multiple assignment error.
     with self.assertRaises(plaidml.exceptions.Unknown) as cm:
         pkb._Op('assign_mul', A.dtype, (A.shape[0], B.shape[1]), f,
                 OrderedDict([('A', B), ('B', A)]), ['O']).eval()
     self.assertTrue("Multiple assignment" in str(cm.exception))
Ejemplo n.º 5
0
 def _init_calcs(self):
     if not self._use_tile:
         self.step_frame = self.step_frame_np
         return
     kernel = np.ones((3, 3, 1), dtype=np.uint8)
     kernel[1, 1, 0] = 10
     self.step_frame = self.step_frame_tile
     blibs = K.variable(self._blibs.reshape(self._blibs.shape + (1, )),
                        dtype=self._blibs.dtype)
     tile_op = GolOp.function(blibs,
                              K.constant(kernel, dtype=kernel.dtype),
                              wrap=self._warp_mode)
     self._tile_func = CopyFunction([self.frame], [], [tile_op[1]],
                                    updates=[(blibs, tile_op[0])],
                                    name="Foo")
Ejemplo n.º 6
0
 def __call__(self, inputs):
     for (name, val) in zip(self._input_names, inputs):
         if isinstance(val, six.integer_types):
             val = plaidml.Integer(val)
         elif isinstance(val, float):
             val = plaidml.Real(val)
         else:
             val = K.variable(val, dtype=self._input_types[name]).var
         self._invoker.set_input(name, val)
     tensors = [
         plaidml.Tensor(K._device(), self._invoker.get_output_shape(name))
         for name in self._output_names
     ]
     for (name, t) in zip(self._output_names, tensors):
         self._invoker.set_output(name, t)
     self._invoker.invoke()
     res = []
     for t, np_arr in zip(tensors, self._np_arrs):
         with t.mmap_current() as view:
             view.copy_to_ndarray(np_arr)
         res.append(np_arr)
     return res
Ejemplo n.º 7
0
    def __init__(self, frame, kernel, rules=((3, ), (2, 3)), wrap=True):
        code = """
            function (I[Y, X, Z], K[KY, KX, Z], NULL, ONE, RGB) -> (O, ORGB){{
                {conv};
                O = {rules};
                ORGB = RGB * O;
            }}
        """
        # TODO: we could simplify this
        # TODO: add other rules
        rule_map = {
            ((3, ), (2, 3)):
            '( T < 12 ? (T == 3 ? ONE : NULL) : (T > 13 ? NULL : ONE) )',
            # labyrinthish
            ((3, ), (2, 3, 4)):
            '( T < 12 ? (T == 3 ? ONE : NULL) : (T > 14 ? NULL : ONE) )',
        }
        if isinstance(rules, (list, tuple)):
            rules = rule_map[tuple(rules)]
        if wrap:
            # TODO:
            raise NotImplementedError("Wrap not implemented because no modulo")
        else:
            conv = 'T[y, x, z: Y, X, Z] = +(I[y -1 + ky, x -1 + kx, z] * K[ky, kx, z]), ky < KY, kx < KX'

        code = code.format(rules=rules, conv=conv)
        logger.debug("TILE CODE: %s:", code)
        rgb = np.zeros(frame.shape.dims[:-1] + (4, ), dtype="uint8")
        rgb[:, :] = (255, 255, 255, 255)
        super(GolOp, self).__init__(code, [
            ('I', frame),
            ('K', kernel),
            ('NULL', K.constant(np.array(0, dtype='uint8'), dtype='uint8')),
            ('ONE', K.constant(np.array(1, dtype='uint8'), dtype='uint8')),
            ('RGB', K.variable(rgb, dtype='uint8')),
        ], [('O', frame.shape),
            ('ORGB', ptile.Shape(frame.shape.dtype, rgb.shape))])
Ejemplo n.º 8
0
 def testTileIdentity(self):
     x = pkb.variable(m(3))
     f = '''function (I[N]) -> (O) { O = I; }'''
     result = pkb._Op("TileIdent", x.dtype, (3, ), f, {'I': x}, ['O'])
     output = result.eval()
     return 0