How to use the coremltools.converters.nnssa.commons.builtins.tensor function in coremltools

To help you get started, we’ve selected a few coremltools examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github apple / coremltools / coremltools / converters / nnssa / frontend / graph_pass / type_inference.py View on Github external
if is_symbolic_or_known(idim):
                            node.attr['split'] = [idim // num_split] * num_split
                            output_shape[split_dim] = idim // num_split
                        else:
                            node.attr['split'] = [-1] * num_split
                            output_shape[split_dim] = -1
                        shapes = [output_shape] * num_split
                        try_materialize = True
                    else:
                        assert (np.sum(split_size) == idim or is_symbolic_or_unknown(idim))
                        node.attr['split'] = list(split_size)
                        shapes = [output_shape[:] for _ in range(len(split_size))]
                        for idx, s in enumerate(split_size):
                            shapes[idx][split_dim] = s

            types = [builtins.tensor(datatype, tuple(shape)) for shape in shapes]
        else:
            types = [
                builtins.tensor(datatype, tuple(shape)) for shape in node.attr['_output_shapes']
            ]
        rettype = builtins.tuple(types)
        if try_materialize:
            value = try_get_non_sym_val(self.gdict[node.inputs[value_idx]])
            if value is not None:
                node.attr["symbolic_value"] = rettype()
                node.attr["symbolic_value"].val = np.split(value, num_split, axis=split_dim)
        return rettype
github apple / coremltools / coremltools / converters / nnssa / frontend / graph_pass / type_inference.py View on Github external
def visit_ExpandDims(self, node):
        """
        Inputs:
            0 (str): The name of a tensor or scalar.
            1 (str): The name of an int indicating the dimension index to expand. Must be in
                     range [-rank(input) - 1, rank(input)] and able to be determined at compile
                     time.
        """
        if len(node.inputs) != 2:
            raise ValueError('Expected 2 inputs to {} node {}'.format(node.op, node.name))

        typea = self.visit(node.inputs[0])
        if not builtins.is_tensor(typea):
            typea = builtins.tensor(typea, (1, ))
            shape = []
        else:
            shape = list(typea.get_shape())  # input[0] should be a tensor.

        axis_type = self.visit(node.inputs[1])
        axis_value = None
        if builtins.is_tensor(axis_type):
            axis_shape = axis_type.get_shape()
            size = 1
            for s in axis_shape:
                size *= s
            if size != 1:
                raise ValueError(
                    'Unexpected value for axis specified for {} node {}'.format(node.op, node.name))
            axis_value = self._get_symbolic_value(node.inputs[1]).val[0]
        elif builtins.is_int(axis_type):
github apple / coremltools / coremltools / converters / nnssa / frontend / graph_pass / type_inference.py View on Github external
def visit_Shape(self, node):
        # need to parse node itself.
        parent_type = self.visit(node.inputs[0])
        shape = []
        if parent_type is None or not builtins.is_tensor(parent_type):
            return builtins.tensor(builtins.int32, [make_symbol(node.name + '_shape')])
        if parent_type is not None:
            shape = parent_type.get_shape()
            rettype = builtins.tensor(builtins.int32, [len(shape)])
        else:
            rettype = builtins.tensor(builtins.int32, [make_symbol(node.name + '_shape')])
        if len(shape) > 0:
            # we have the true value
            node.attr['symbolic_value'] = rettype()
            node.attr['symbolic_value'].val = np.array(shape)
        return rettype
github apple / coremltools / coremltools / converters / nnssa / frontend / graph_pass / type_inference.py View on Github external
shape_value = self._get_symbolic_value(node.inputs[0])
        if shape_value is not None:
            shape_value = shape_value.val.flatten()
            shape = tuple([int(s) if not is_symbolic(s) else s for s in shape_value])
            rettype = builtins.tensor(typeb, shape)

            fill_value = self._get_symbolic_value(node.inputs[1])
            if fill_value is not None and not any_symbolic_or_unknown(shape):
                value = np.ones(shape, dtype=builtins.utils.nptype_from_builtin(typeb)) * fill_value.val
                self._set_symbolic_value(node, rettype, value)
        else:
            # shape unknown.
            # we should be able to derive a rank
            shape = tuple(make_symbol(node.name + str(i)) for i in range(typea.get_shape()[0]))
            rettype = builtins.tensor(typeb, shape)
        return rettype
github apple / coremltools / coremltools / converters / nnssa / frontend / graph_pass / type_inference.py View on Github external
# Interpret positional arguments
        if len(node.inputs) == 2:
            limit_type, delta_type = input_types
            start = 0
            limit, delta = input_values
        elif len(node.inputs) == 3:
            start_type, limit_type, delta_type = input_types
            start, limit, delta = input_values
        else:
            assert False, "logic error"

        # Figure out the node type
        shape = (limit - start) / delta
        shape = shape if is_symbolic(shape) else int(math.ceil(shape))
        rettype = builtins.tensor(datatype, [shape])

        # Evaluate the symbolic value
        if not any_symbolic_or_unknown([start, limit, delta]):
            nptype = builtins.utils.nptype_from_builtin(datatype)
            self._set_symbolic_value(
                node, rettype, np.arange(start=start, stop=limit, step=delta, dtype=nptype))
        elif delta == 1:
            self._set_symbolic_value(node, rettype, sm.Interval(start, limit))
        return rettype
github apple / coremltools / coremltools / converters / nnssa / coreml / graph_pass / op_fusions.py View on Github external
cropping_values[3] = croppings[0, 1]  # bottom
                cropping_values[0] = croppings[1, 0]  # left
                cropping_values[1] = croppings[1, 1]  # right
                needs_cropping_after = False
                border_mode = n.attr.get('padding', '').lower()
                if sum(cropping_values) != 0:
                    if border_mode != 'valid':
                        needs_cropping_after = True
                    else:
                        raise NotImplementedError('unhandled BatchToSpaceND case.')
                if needs_cropping_after:
                    graph[output_node].attr.update({'_cropping_after': cropping_values})

            # adjust type inference
            shape = list(graph[previous_node].datatype.get_shape())
            graph[output_node].datatype = builtins.tensor(graph[output_node].datatype.get_primitive(), tuple(shape))

            delete_node(graph, n.name)
            count += 1

        if count > 0:
            print('[Op Fusion] Skipped {} BatchToSpaceND / SpaceToBatchND nodes.'.format(count))
github apple / coremltools / coremltools / converters / nnssa / frontend / graph_pass / type_inference.py View on Github external
# Check shape compatibility
        if not all(is_symbolic_or_unknown(s) for s in [mata_shape[-1], matb_shape[-2]]):
            if mata_shape[-1] != matb_shape[-2]:
                raise ValueError('Incompatible dimensions in {} op {}'.format(node.op, node.name))

        # Figure out the resulting shape. Outer dimensions are broadcastable.
        outera = mata_shape[0:-2]
        outerb = matb_shape[0:-2]
        outer_shape = self._broadcast_shape(node, outera, outerb)
        shape = outer_shape + [mata_shape[-2], matb_shape[-1]]

        if len(shape) > 2:
            node.op = 'BatchMatMul'

        primitive = self._promoted_primitive_type(typea, typeb)
        return builtins.tensor(primitive, tuple(shape))
github apple / coremltools / coremltools / converters / nnssa / frontend / graph_pass / type_inference.py View on Github external
if transpose_axes is None or transpose_axes.val is None:
            # We can't determine the output shape right now: figure it out at runtime
            shape = tuple(make_symbol(node.name + str(i)) for i in range(len(shape)))
            rettype = builtins.tensor(primitive, shape)
            return rettype

        if len(transpose_axes.val) != len(shape):
            raise ValueError(
                'Permutation symbolic value must be a 1-D tensor as long as input rank in {} node {}'
                .format(node.op, node.name))

        # Compute the output shape
        new_shape = []
        for ax in transpose_axes.val:
            new_shape.append(shape[ax])
        rettype = builtins.tensor(primitive, new_shape)

        # Compute a symbolic value for this node if possible
        input0 = try_get_non_sym_val(self.gdict[node.inputs[0]])
        input1 = try_get_non_sym_val(self.gdict[node.inputs[1]])
        if input0 is not None and input1 is not None:
            self._set_symbolic_value(node, rettype, np.transpose(input0, axes=input1))

        return rettype
github apple / coremltools / coremltools / converters / nnssa / frontend / graph_pass / type_inference.py View on Github external
begin = to_int(begin)
                    size = [
                        input_shape[i] - begin[i] if s in (-1, 2147483647) else s
                        for i, s in enumerate(size)
                    ]
                except:
                    # Adjust size if begin is available, otherwise trust the
                    # materialized size assuming it's reasonable.
                    if max(size) == 2147483647:
                        raise RuntimeError()
                size = to_int(size)

                if len(size) == 1 and size[0] == 1:
                    rettype = input_type.get_primitive()
                else:
                    rettype = builtins.tensor(input_type.get_primitive(), size)
                node.attr['generic_slice'] = True
                node.attr['size'] = size
            except:
                retshape = []
                for i in range(len(input_shape)):
                    retshape.append(make_symbol(node.name + '_' + str(i)))
                if len(retshape) == 0:
                    rettype = input_type.get_primitive()
                else:
                    rettype = builtins.tensor(input_type.get_primitive(), retshape)
        return rettype