Skip to content

Index

LazyTensor

Bases: OverrideTensor

Source code in src/finch/interface/lazy.py
class LazyTensor(OverrideTensor):
    def __init__(
        self,
        data: Alias,
        ctx: EffectBlob,
        shape: tuple,
        fill_value: AbstractFill,
        element_type: FType,
        device=None,
    ):
        self.data: Alias = data
        self.ctx = ctx
        self._shape = shape
        # Held as an AbstractFill so a dynamic fill survives ftype round trips.
        self._fill_value = fill_value
        self._element_type = element_type
        self._device = normalize_device(device)

    def override_module(self):
        return sys.modules[__name__]

    @property
    def ftype(self):
        return LazyTensorFType(
            _fill_type=self._fill_value.ftype,
            _element_type=self._element_type,
            _shape_type=tuple(ftype(dim) for dim in self._shape),
            _device=self._device,
        )

    @property
    def shape(self) -> tuple:
        """
        Returns the shape of the LazyTensor as a tuple.
        The shape is determined by the data and is a static property.
        """
        return self._shape

    @property
    def fill_value(self) -> Any:
        """Default value to fill the tensor."""
        return self._fill_value.value

    @property
    def device(self):
        return self._device

    def to_device(self, device, /, *, stream=None):
        if stream is not None:
            raise ValueError(f"stream argument is not supported; got {stream!r}")
        device = normalize_device(device)
        if device == self.device:
            return self
        return LazyTensor(
            self.data,
            self.ctx,
            self._shape,
            self._fill_value,
            self._element_type,
            device=device,
        )

    @property
    def element_type(self) -> FType:
        """Data type of the tensor elements."""
        return self.ftype.element_type

    @property
    def shape_type(self) -> tuple:
        """Shape type of the tensor."""
        return self.ftype.shape_type

    def item(self):
        raise ValueError(
            "Cannot convert LazyTensor to Python scalar. "
            "Use compute() to evaluate it first."
        )

    def to_numpy(self):
        raise ValueError(
            "Cannot convert LazyTensor to Python scalar. "
            "Use compute() to evaluate it first."
        )

    def to_scipy(self):
        raise ValueError(
            "Cannot convert LazyTensor to Python scalar. "
            "Use compute() to evaluate it first."
        )

    # raise ValueError for unsupported operations according to the data-apis spec.
    # NOT tested, since this isn't necessary as it will throw an error anyways.
    def __complex__(self) -> complex:
        """
        Converts the LazyTensor to a complex number.
        This is a no-op for LazyTensors, as they are symbolic representations.
        """
        raise ValueError(
            "Cannot convert LazyTensor to complex. Use compute() to evaluate it first."
        )

    def __float__(self) -> float:
        """
        Converts the LazyTensor to a float.
        This is a no-op for LazyTensors, as they are symbolic representations.
        """
        raise ValueError(
            "Cannot convert LazyTensor to float. Use compute() to evaluate it first."
        )

    def __int__(self) -> int:
        """
        Converts the LazyTensor to an int.
        This is a no-op for LazyTensors, as they are symbolic representations.
        """
        raise ValueError(
            "Cannot convert LazyTensor to int. Use compute() to evaluate it first."
        )

    def __bool__(self) -> bool:
        """
        Converts the LazyTensor to a bool.
        This is a no-op for LazyTensors, as they are symbolic representations.
        """
        raise ValueError(
            "Cannot convert LazyTensor to bool. Use compute() to evaluate it first."
        )

    def reshape(self, shape, /, *, copy=None):
        return reshape(self, shape, copy=copy)

element_type property

Data type of the tensor elements.

fill_value property

Default value to fill the tensor.

shape property

Returns the shape of the LazyTensor as a tuple. The shape is determined by the data and is a static property.

shape_type property

Shape type of the tensor.

__bool__()

Converts the LazyTensor to a bool. This is a no-op for LazyTensors, as they are symbolic representations.

Source code in src/finch/interface/lazy.py
def __bool__(self) -> bool:
    """
    Converts the LazyTensor to a bool.
    This is a no-op for LazyTensors, as they are symbolic representations.
    """
    raise ValueError(
        "Cannot convert LazyTensor to bool. Use compute() to evaluate it first."
    )

__complex__()

Converts the LazyTensor to a complex number. This is a no-op for LazyTensors, as they are symbolic representations.

Source code in src/finch/interface/lazy.py
def __complex__(self) -> complex:
    """
    Converts the LazyTensor to a complex number.
    This is a no-op for LazyTensors, as they are symbolic representations.
    """
    raise ValueError(
        "Cannot convert LazyTensor to complex. Use compute() to evaluate it first."
    )

__float__()

Converts the LazyTensor to a float. This is a no-op for LazyTensors, as they are symbolic representations.

Source code in src/finch/interface/lazy.py
def __float__(self) -> float:
    """
    Converts the LazyTensor to a float.
    This is a no-op for LazyTensors, as they are symbolic representations.
    """
    raise ValueError(
        "Cannot convert LazyTensor to float. Use compute() to evaluate it first."
    )

__int__()

Converts the LazyTensor to an int. This is a no-op for LazyTensors, as they are symbolic representations.

Source code in src/finch/interface/lazy.py
def __int__(self) -> int:
    """
    Converts the LazyTensor to an int.
    This is a no-op for LazyTensors, as they are symbolic representations.
    """
    raise ValueError(
        "Cannot convert LazyTensor to int. Use compute() to evaluate it first."
    )

NumPyFType

Bases: TensorFType

Source code in src/finch/tensor/np_wrapper.py
class NumPyFType(TensorFType):
    def __init__(self, dtype: np.dtype, ndim: int, device=None):
        self._dtype = np.dtype(dtype)
        self._ndim = ndim
        self._device = normalize_device(device)

    @property
    def fill_type(self) -> AbstractFillFType:
        return StaticFillFType(self._dtype.type(0))

    @property
    def element_type(self) -> FType:
        return ftype(self._dtype.type)

    @property
    def shape_type(self) -> tuple[FType, ...]:
        return (intp,) * self._ndim

    @property
    def device(self):
        return self._device

    def construct(self, shape: tuple) -> "NumPyWrapper":
        # creates a zero-filled tensor
        return NumPyWrapper(np.zeros(shape, dtype=self._dtype), device=self.device)

    def __call__(self, val: "NumPyWrapper") -> "NumPyWrapper":
        """
        Convert a tensor to this numpy tensor type.

        Args:
            val: A tensor to convert to this type.
        Returns:
            A NumPyWrapper instance of this type.
        """
        raise NotImplementedError(
            f"Tensor conversion not yet implemented for {type(self).__name__}"
        )

    def __eq__(self, other):
        if not isinstance(other, NumPyFType):
            return False
        return (
            self._dtype == other._dtype
            and self._ndim == other._ndim
            and self.device == other.device
        )

    def __hash__(self):
        return hash((self._dtype, self._ndim, self.device))

    def from_numpy(self, arr: np.ndarray) -> "NumPyWrapper":
        return NumPyWrapper(arr, device=self.device)

__call__(val)

Convert a tensor to this numpy tensor type.

Parameters:

Name Type Description Default
val NumPyWrapper

A tensor to convert to this type.

required

Returns: A NumPyWrapper instance of this type.

Source code in src/finch/tensor/np_wrapper.py
def __call__(self, val: "NumPyWrapper") -> "NumPyWrapper":
    """
    Convert a tensor to this numpy tensor type.

    Args:
        val: A tensor to convert to this type.
    Returns:
        A NumPyWrapper instance of this type.
    """
    raise NotImplementedError(
        f"Tensor conversion not yet implemented for {type(self).__name__}"
    )

NumPyWrapper

Bases: Tensor

Source code in src/finch/tensor/np_wrapper.py
class NumPyWrapper(Tensor):
    def __init__(self, data: np.ndarray, device=None):
        self._data = np.asarray(data)
        self._device = normalize_device(device)

    @property
    def ftype(self) -> NumPyFType:
        return NumPyFType(self._data.dtype, self._data.ndim, self._device)

    @property
    def shape(self) -> tuple:
        return self._data.shape

    @property
    def fill_value(self) -> Any:
        """Default fill value."""
        return resolve_fill(self.ftype.fill_type).value

    @property
    def element_type(self) -> FType:
        """Data type of the tensor's elements."""
        return self.ftype.element_type

    @property
    def shape_type(self) -> tuple[FType, ...]:
        """Shape type of the tensor."""
        return self.ftype.shape_type

    @property
    def device(self):
        return self._device

    def to_device(self, device, /, *, stream=None):
        if stream is not None:
            raise ValueError(f"stream argument is not supported; got {stream!r}")
        device = normalize_device(device)
        if device == self.device:
            return self
        return NumPyWrapper(self._data, device=device)

    def item(self):
        if self.ndim != 0:
            raise ValueError("Cannot convert non-scalar tensor to Python scalar.")
        return self._data.item()

    def to_numpy(self):
        return self._data

    def to_scipy(self):
        raise NotImplementedError(f"{type(self).__name__} does not support to_scipy.")

element_type property

Data type of the tensor's elements.

fill_value property

Default fill value.

shape_type property

Shape type of the tensor.

Scalar

Bases: OverrideTensor

Source code in src/finch/tensor/scalar.py
class Scalar(OverrideTensor):
    def __init__(self, val: Any, fill_value: Any = None, device=None):
        if fill_value is None:
            fill_value = val
        self.val = val
        self._fill_value = as_fill(fill_value)
        self._device = normalize_device(device)

    @property
    def ftype(self):
        elem_t = ftype(self.val)
        return ScalarFType(elem_t, DynamicFillFType(elem_t), self._device)

    @property
    def shape(self):
        return ()

    @property
    def fill_value(self) -> Any:
        """Default value to fill the scalar."""
        return self._fill_value.value

    @property
    def device(self):
        return self._device

    def with_fill(self, fill_value: AbstractFill) -> Scalar:
        if is_dynamic(fill_value):
            return Scalar(self.val, fill_value=fill_value, device=self._device)
        if not bool(ffuncs.same(fill_value.value, self.val)):
            raise NotImplementedError(
                "a ConstantScalar's fill is its value, so a scalar of "
                f"{self.val!r} cannot take the static fill {fill_value.value!r}"
            )
        return ConstantScalar(self.val, device=self._device)

    def to_device(self, device, /, *, stream=None):
        if stream is not None:
            raise ValueError(f"stream argument is not supported; got {stream!r}")
        device = normalize_device(device)
        if device == self.device:
            return self
        return Scalar(self.val, fill_value=self._fill_value, device=device)

    @property
    def element_type(self) -> FType:
        """Data type of the scalar."""
        return self.ftype.element_type

    @property
    def shape_type(self) -> tuple:
        """Shape type of the scalar."""
        return self.ftype.shape_type

    def item(self):
        return self.val.item() if hasattr(self.val, "item") else self.val

    def __array__(self, dtype=None, copy=None):
        if copy is None:
            return np.asarray(self.val, dtype=dtype)
        return np.array(self.val, dtype=dtype, copy=copy)

    def __getitem__(self, idx):
        if idx == () or idx is Ellipsis or idx == (...,):
            return self
        raise IndexError("Too many indices for scalar tensor.")

    def __str__(self):
        return str(self.val)

    def to_numpy(self):
        return self.val

    def to_scipy(self):
        raise NotImplementedError(f"{type(self).__name__} does not support to_scipy.")

element_type property

Data type of the scalar.

fill_value property

Default value to fill the scalar.

shape_type property

Shape type of the scalar.

ScalarFType

Bases: TensorFType, ImmutableStructFType

Source code in src/finch/tensor/scalar.py
class ScalarFType(TensorFType, ImmutableStructFType):
    def __init__(
        self, _element_type: FType, _fill_type: AbstractFillFType, _device=None
    ):
        self._element_type = _element_type
        self._fill_type = _fill_type
        self._device = normalize_device(_device)

    def __eq__(self, other):
        if isinstance(other, ScalarFType):
            return (
                self._element_type == other._element_type
                and self._fill_type == other._fill_type
                and self.device == other.device
            )
        return False

    def __hash__(self):
        return hash((self._element_type, self._fill_type, self.device))

    def construct(self, shape: tuple) -> Scalar:
        if shape != ():
            raise ValueError("ScalarFType can only be called with empty shape ()")
        return self._element_type(resolve_fill(self._fill_type).value)

    def __call__(self, val: Any) -> Scalar:
        """
        Convert a tensor to this scalar tensor type.

        Args:
            val: A value to convert to this type.
        Returns:
            A Scalar instance of this type.
        """
        raise NotImplementedError(
            f"Tensor conversion not yet implemented for {type(self).__name__}"
        )

    def from_numpy(self, arr):
        return self(arr)

    @property
    def fill_type(self) -> AbstractFillFType:
        return self._fill_type

    @property
    def device(self):
        return self._device

    @property
    def element_type(self) -> FType:
        return self._element_type

    @property
    def shape_type(self):
        return ()

    @property
    def struct_name(self) -> str:
        return "Scalar"

    @property
    def struct_fields(self) -> list[tuple[str, FType]]:
        return [("val", self._element_type)]

    def from_fields(self, val):
        if is_dynamic(self._fill_type):
            # A scalar's fill defaults to its value.
            return Scalar(val, device=self._device)
        return Scalar(
            val, fill_value=resolve_fill(self._fill_type), device=self._device
        )

    def with_fill(self, fill_type: AbstractFillFType) -> ScalarFType:
        return ScalarFType(self._element_type, fill_type, self._device)

    def fisinstance(self, other):
        other_t = ftype(other)
        if is_dynamic(self._fill_type) and isinstance(other_t, ScalarFType):
            # A dynamic-fill ftype accepts any fill value of matching dtype.
            other_t = other_t.with_fill(self._fill_type)
        return other_t == self

    def lower_fill(self, ctx, obj):
        if is_static(self._fill_type):
            return asm.Literal(self._fill_type.value)
        # The dynamic fill of a scalar is its value.
        return self.lower_unwrap(ctx, obj)

    def lower_unwrap(self, ctx, obj):
        match obj:
            case ntn.Fiber():
                # A slot-bound scalar argument: read the value struct field.
                return asm.GetAttr(ctx(obj.lvl.root), asm.Literal("val"))
            case _:
                # An inline scalar value (e.g. a sparse gap read).
                return ctx(obj)

__call__(val)

Convert a tensor to this scalar tensor type.

Parameters:

Name Type Description Default
val Any

A value to convert to this type.

required

Returns: A Scalar instance of this type.

Source code in src/finch/tensor/scalar.py
def __call__(self, val: Any) -> Scalar:
    """
    Convert a tensor to this scalar tensor type.

    Args:
        val: A value to convert to this type.
    Returns:
        A Scalar instance of this type.
    """
    raise NotImplementedError(
        f"Tensor conversion not yet implemented for {type(self).__name__}"
    )

asarray(obj, /, *, dtype=None, device=None, copy=None, format=None)

asarray(
    obj: np.ndarray,
    /,
    *,
    dtype=None,
    device=None,
    copy=None,
    format: None = None,
) -> BufferizedNDArray
asarray(
    obj: sps.spmatrix | sps.sparray,
    /,
    *,
    dtype=None,
    device=None,
    copy=None,
    format: None = None,
) -> FiberTensor
asarray(
    obj: Any,
    /,
    *,
    dtype=None,
    device=None,
    copy=None,
    format: FiberTensorFType,
) -> FiberTensor
asarray(
    obj: np.generic | complex,
    /,
    *,
    dtype=None,
    device=None,
    copy=None,
    format: None = None,
) -> Scalar
asarray(
    obj: Any,
    /,
    *,
    dtype=None,
    device=None,
    copy=None,
    format: TensorFType | None = None,
) -> Tensor

Convert given argument and return wrapper type instance. If input argument is already array type, return unchanged. https://data-apis.org/array-api/latest/API_specification/generated/array_api.asarray.html

Source code in src/finch/interface/lazy.py
def asarray(
    obj: Any,
    /,
    *,
    dtype=None,
    device=None,
    copy=None,
    format: TensorFType | None = None,
) -> Tensor:
    """
    Convert given argument and return wrapper type instance.
    If input argument is already array type, return unchanged.
    https://data-apis.org/array-api/latest/API_specification/generated/array_api.asarray.html
    """
    explicit_device = device is not None
    device = normalize_device(device)

    if format is None:
        if isinstance(obj, Scalar):
            if copy is True or (explicit_device and obj.device != device):
                return Scalar(obj.val, fill_value=obj.fill_value, device=device)
            return obj
        if isinstance(obj, BufferizedNDArray):
            if copy is True:
                return BufferizedNDArray.from_numpy(
                    obj.to_numpy().copy(), fill_value=obj.fill_value, device=device
                )
            if explicit_device and obj.device != device:
                return obj.to_device(device)
            return obj
        if isinstance(obj, Tensor) and copy is not True:
            if explicit_device and obj.device != device:
                return obj.to_device(device)
            return obj
        if isinstance(obj, np.ndarray):
            if copy is True:
                obj = obj.copy()
            return BufferizedNDArray.from_numpy(obj, device=device)
        if sps.issparse(obj):
            if obj.format == "csc":  # CSC has no native Finch layout yet
                if dtype is not None or copy is True:
                    raise NotImplementedError(
                        "asarray cannot honor dtype or copy for CSC input; "
                        "convert to CSR or COO first."
                    )
                return obj
            if copy is False and not (
                obj.format in ("coo", "csr") and obj.has_canonical_format
            ):
                raise ValueError(
                    "Unable to avoid copy while creating an array as requested."
                )
            if obj.format not in ("coo", "csr"):
                obj = obj.asformat("coo")

            if dtype is not None:
                if copy is False:
                    obj = obj.astype(dtype, copy=False)
                else:
                    obj = obj.astype(dtype, copy=True)
            elif copy is True:
                obj = obj.copy()

            if not obj.has_canonical_format:
                obj = obj.copy()
                obj.sum_duplicates()

            match obj.format:
                case "csr":
                    return FiberTensor.from_scipy_csr(obj, device=device)
                case "coo":
                    return FiberTensor.from_scipy_coo(obj, device=device)

        if np.isscalar(obj) or obj is None:
            if dtype is not None:
                obj = ftype(dtype)(obj)
            elif isinstance(obj, bool | int | float | complex):
                obj = np.asarray(obj)[()]
            return Scalar(obj, device=device)
        try:
            np_arr = np.asarray(obj)
            if np_arr.dtype != object:
                if dtype is not None:
                    np_arr = np_arr.astype(np_dtype(ftype(dtype)))
                elif copy is True:
                    np_arr = np_arr.copy()
                return BufferizedNDArray.from_numpy(np_arr, device=device)
        except (TypeError, ValueError):
            pass
        return obj

    out = format.from_numpy(obj) if isinstance(obj, np.ndarray) else format(obj)
    return out.to_device(device) if explicit_device else out

broadcast_arrays(*args)

Broadcasts one or more arrays against one another.

Parameters

*args: array an arbitrary number of to-be broadcasted arrays.

Returns

out: List[array] a list of broadcasted arrays. Each array has the same shape. Element types are preserved.

Source code in src/finch/interface/eager.py
def broadcast_arrays(*args):
    """
    Broadcasts one or more arrays against one another.

    Parameters
    ----------
    *args: array
        an arbitrary number of to-be broadcasted arrays.

    Returns
    -------
    out: List[array]
        a list of broadcasted arrays. Each array has the same shape.
        Element types are preserved.
    """
    if builtins.any(isinstance(arg, lazy.LazyTensor) for arg in args):
        return lazy.broadcast_arrays(*args)
    # compute can take in a list of LazyTensors
    return compute(lazy.broadcast_arrays(*args))

broadcast_to(x, /, shape)

Broadcasts an array to a new shape.

Parameters

x: array The input tensor to be broadcasted. shape: Sequence[int] The target shape to which the input tensor should be broadcasted.

Returns

out: array A tensor with the same data as x, but with the specified shape.

Source code in src/finch/interface/eager.py
def broadcast_to(x, /, shape: Sequence[int]):
    """
    Broadcasts an array to a new shape.

    Parameters
    ----------
    x: array
        The input tensor to be broadcasted.
    shape: Sequence[int]
        The target shape to which the input tensor should be broadcasted.

    Returns
    -------
    out: array
        A tensor with the same data as `x`, but with the specified shape.
    """
    shape = tuple(shape)  # Ensure shape is a tuple for consistency
    if isinstance(x, lazy.LazyTensor):
        return lazy.broadcast_to(x, shape=shape)
    return compute(lazy.broadcast_to(x, shape=shape))

compute(arg, ctx=None)

Executes a fused operation represented by LazyTensors. This function evaluates the entire operation in an optimized manner using the provided scheduler.

  • arg: A lazy tensor or a tuple of lazy tensors representing the fused operation to be computed.
  • ctx: The scheduler to use for computation. Defaults to the result of get_default_scheduler().

Returns: - A tensor or a list of tensors computed by the fused operation.

Source code in src/finch/interface/fuse.py
def compute(arg, ctx=None):
    """
    Executes a fused operation represented by LazyTensors. This function evaluates the
    entire operation in an optimized manner using the provided scheduler.

    Parameters:
    - arg: A lazy tensor or a tuple of lazy tensors representing the fused operation to
      be computed.
    - ctx: The scheduler to use for computation. Defaults to the result of
      `get_default_scheduler()`.

    Returns:
    - A tensor or a list of tensors computed by the fused operation.
    """
    if ctx is None:
        ctx = get_default_scheduler()

    args = arg if isinstance(arg, tuple) else (arg,)
    outputs = [None for _ in args]
    lazy_args = []
    lazy_arg_idxs = []
    for i, arg_i in enumerate(args):
        if not isinstance(arg_i, LazyTensor):
            outputs[i] = arg_i
        else:
            lazy_args.append(arg_i)
            lazy_arg_idxs.append(i)

    if lazy_args:
        vars = tuple(HardAlias(gensym("A")) for _ in lazy_args)
        ctx_2 = lazy_args[0].ctx.join(*[x.ctx for x in lazy_args[1:]])
        bodies = []
        for arg_i, var in zip(lazy_args, vars, strict=True):
            idxs = tuple(Field(gensym("i")) for _ in range(len(arg_i.shape)))
            bodies.append(Query(Table(var, idxs), Table(arg_i.data, idxs)))
        prgm = Plan((*ctx_2.trace(), *bodies, Produces(vars)))
        res = ctx(prgm)
        for lazy_idx, out_idx in enumerate(lazy_arg_idxs):
            device = lazy_args[lazy_idx].device
            if (
                len(res[lazy_idx].shape) == 0
            ):  # if the result is a scalar, extract the value and turn it into a
                # finch `Scalar`
                outputs[out_idx] = asarray(res[lazy_idx][()], device=device)
            else:
                outputs[out_idx] = asarray(res[lazy_idx], device=device)

    return tuple(outputs) if isinstance(arg, tuple) else outputs[0]

defer(arr)

defer(arr: tuple[Any, ...]) -> tuple[Any, ...]
defer(arr: Any) -> LazyTensor
  • defer(arr) -> LazyTensor: Converts an array into a LazyTensor. If the input is already a LazyTensor, it is returned as-is. Otherwise, it creates a LazyTensor representation of the input array.

Parameters: - arr: The input array to be converted into a LazyTensor.

Returns: - LazyTensor: A lazy representation of the input array.

Source code in src/finch/interface/lazy.py
def defer(arr: Any) -> LazyTensor | tuple[Any, ...]:
    """
    - defer(arr) -> LazyTensor:
    Converts an array into a LazyTensor. If the input is already a LazyTensor, it is
    returned as-is.
    Otherwise, it creates a LazyTensor representation of the input array.

    Parameters:
    - arr: The input array to be converted into a LazyTensor.

    Returns:
    - LazyTensor: A lazy representation of the input array.
    """
    if isinstance(arr, tuple):
        return tuple(defer(arr_i) for arr_i in arr)

    if isinstance(arr, LazyTensor):
        return arr
    if _is_numeric_constant(arr):
        arr = ConstantScalar(arr) if is_specializable_value(arr) else Scalar(arr)
    else:
        arr = asarray(arr)
    tns = HardAlias(gensym("A"))
    idxs = tuple(Field(gensym("i")) for _ in range(arr.ndim))
    shape = tuple(arr.shape)
    ctx = EffectBlob(stmt=Query(Table(tns, idxs), Table(Literal(arr), idxs)))
    return LazyTensor(tns, ctx, shape, arr.fill, arr.element_type, arr.device)

einop(prgm, /, **kwargs)

Execute an einsum expression using the specified array framework.

This function parses and executes einsum-like expressions with extended syntax that supports various operations beyond traditional Einstein summation notation.

Parameters:

Name Type Description Default
prgm str

Einsum program string specifying the computation. The syntax supports: - Assignment: "C[i,j] = A[i,j] + B[j,i]" - Increment: "C[i,j] += A[i,k] * B[k,j]" - Reductions: "C[i] += A[i,j]", "C[i] max= A[i,j]", "C[i] &= A[i,j]" - Arithmetic operations: +, -, *, /, //, %, ** - Comparison operations: ==, !=, <, <=, >, >= - Logical operations: and, or, not - Bitwise operations: &, |, ^, <<, >> - Function calls and complex expressions with parentheses - Mathematical functions: abs, sqrt, exp, log, sin, cos, tan, etc. - Literal values: integers, floats, booleans, and complex numbers - Python operator precedence and parentheses for grouping

required
**kwargs Any

Named arrays referenced in the einsum expression. The keys should match the tensor names used in the program string.

{}

Returns:

Type Description
Any

The result array from executing the einsum expression.

Examples:

>>> rng = np.random.default_rng(42)
>>> A = rng.integers(0, 10, size=(3, 4))
>>> B = rng.integers(0, 10, size=(4, 3))
>>> # Matrix addition with transpose
>>> C = einop("C[i,j] = A[i,j] + B[j,i]", A=A, B=B)
>>> # Matrix multiplication
>>> D = einop("D[i,j] += A[i,k] * B[k,j]", A=A, B=B)
>>> # Min-Plus multiplication with shift
>>> E = einop("E[i] min= A[k,i] + D[k,j] << 1", A=A, D=D)
Source code in src/finch/interface/eager.py
def einop(prgm: str, /, **kwargs: Any) -> Any:
    """Execute an einsum expression using the specified array framework.

    This function parses and executes einsum-like expressions with extended syntax
    that supports various operations beyond traditional Einstein summation notation.

    Args:
        prgm (str): Einsum program string specifying the computation. The syntax
            supports:
            - Assignment: "C[i,j] = A[i,j] + B[j,i]"
            - Increment: "C[i,j] += A[i,k] * B[k,j]"
            - Reductions: "C[i] += A[i,j]", "C[i] max= A[i,j]", "C[i] &= A[i,j]"
            - Arithmetic operations: +, -, *, /, //, %, **
            - Comparison operations: ==, !=, <, <=, >, >=
            - Logical operations: and, or, not
            - Bitwise operations: &, |, ^, <<, >>
            - Function calls and complex expressions with parentheses
            - Mathematical functions: abs, sqrt, exp, log, sin, cos, tan, etc.
            - Literal values: integers, floats, booleans, and complex numbers
            - Python operator precedence and parentheses for grouping
        **kwargs: Named arrays referenced in the einsum expression. The keys
            should match the tensor names used in the program string.

    Returns:
        The result array from executing the einsum expression.

    Examples:
        >>> rng = np.random.default_rng(42)
        >>> A = rng.integers(0, 10, size=(3, 4))
        >>> B = rng.integers(0, 10, size=(4, 3))
        >>> # Matrix addition with transpose
        >>> C = einop("C[i,j] = A[i,j] + B[j,i]", A=A, B=B)
        >>> # Matrix multiplication
        >>> D = einop("D[i,j] += A[i,k] * B[k,j]", A=A, B=B)
        >>> # Min-Plus multiplication with shift
        >>> E = einop("E[i] min= A[k,i] + D[k,j] << 1", A=A, D=D)
    """
    if builtins.any(isinstance(v, lazy.LazyTensor) for v in kwargs.values()):
        return lazy.einop(prgm, **kwargs)
    return compute(lazy.einop(prgm, **kwargs))

einsum(*args, **kwargs)

einsum(subscripts, *operands)

Evaluates the Einstein summation convention on the operands.

Using the Einstein summation convention, many common multi-dimensional, linear algebraic array operations can be represented in a simple fashion. In implicit mode einsum computes these values.

In explicit mode, einsum provides further flexibility to compute other array operations that might not be considered classical Einstein summation operations, by disabling, or forcing summation over specified subscript labels.

See the notes and examples for clarification.

Parameters

subscripts : str Specifies the subscripts for summation as comma separated list of subscript labels. An implicit (classical Einstein summation) calculation is performed unless the explicit indicator '->' is included as well as subscript labels of the precise output form. operands : list of array_like These are the arrays for the operation.

Returns

output : ndarray The calculation based on the Einstein summation convention.

Notes

The Einstein summation convention can be used to compute many multi-dimensional, linear algebraic array operations. einsum provides a succinct way of representing these.

A non-exhaustive list of these operations, which can be computed by einsum, is shown below along with examples:

  • Trace of an array, 🇵🇾func:numpy.trace.
  • Return a diagonal, 🇵🇾func:numpy.diag.
  • Array axis summations, 🇵🇾func:numpy.sum.
  • Transpositions and permutations, 🇵🇾func:numpy.transpose.
  • Matrix multiplication and dot product, 🇵🇾func:numpy.matmul 🇵🇾func:numpy.dot.
  • Vector inner and outer products, 🇵🇾func:numpy.inner 🇵🇾func:numpy.outer.
  • Broadcasting, element-wise and scalar multiplication, 🇵🇾func:numpy.multiply.
  • Tensor contractions, 🇵🇾func:numpy.tensordot.
  • Chained array operations, in efficient calculation order, 🇵🇾func:numpy.einsum_path.

The subscripts string is a comma-separated list of subscript labels, where each label refers to a dimension of the corresponding operand. Whenever a label is repeated it is summed, so np.einsum('i,i', a, b) is equivalent to 🇵🇾func:np.inner(a,b) <numpy.inner>. If a label appears only once, it is not summed, so np.einsum('i', a) produces a view of a with no changes. A further example np.einsum('ij,jk', a, b) describes traditional matrix multiplication and is equivalent to 🇵🇾func:np.matmul(a,b) <numpy.matmul>. Repeated subscript labels in one operand take the diagonal. For example, np.einsum('ii', a) is equivalent to 🇵🇾func:np.trace(a) <numpy.trace>.

In implicit mode, the chosen subscripts are important since the axes of the output are reordered alphabetically. This means that np.einsum('ij', a) doesn't affect a 2D array, while np.einsum('ji', a) takes its transpose. Additionally, np.einsum('ij,jk', a, b) returns a matrix multiplication, while, np.einsum('ij,jh', a, b) returns the transpose of the multiplication since subscript 'h' precedes subscript 'i'.

In explicit mode the output can be directly controlled by specifying output subscript labels. This requires the identifier '->' as well as the list of output subscript labels. This feature increases the flexibility of the function since summing can be disabled or forced when required. The call np.einsum('i->', a) is like 🇵🇾func:np.sum(a) <numpy.sum> if a is a 1-D array, and np.einsum('ii->i', a) is like 🇵🇾func:np.diag(a) <numpy.diag> if a is a square 2-D array. The difference is that einsum does not allow broadcasting by default. Additionally np.einsum('ij,jh->ih', a, b) directly specifies the order of the output subscript labels and therefore returns matrix multiplication, unlike the example above in implicit mode.

To enable and control broadcasting, use an ellipsis. Default NumPy-style broadcasting is done by adding an ellipsis to the left of each term, like np.einsum('...ii->...i', a). np.einsum('...i->...', a) is like 🇵🇾func:np.sum(a, axis=-1) <numpy.sum> for array a of any shape. To take the trace along the first and last axes, you can do np.einsum('i...i', a), or to do a matrix-matrix product with the left-most indices instead of rightmost, one can do np.einsum('ij...,jk...->ik...', a, b).

einsum also provides an alternative way to provide the subscripts and operands as einsum(op0, sublist0, op1, sublist1, ..., [sublistout]). If the output shape is not provided in this format einsum will be calculated in implicit mode, otherwise it will be performed explicitly. The examples below have corresponding einsum calls with the two parameter methods.

Examples

a = np.arange(25).reshape(5, 5) b = np.arange(5) c = np.arange(6).reshape(2, 3)

Trace of a matrix:

np.einsum("ii", a) np.int64(60) np.einsum(a, [0, 0]) np.int64(60) np.trace(a) np.int64(60)

Extract the diagonal (requires explicit form):

np.einsum("ii->i", a) array([ 0, 6, 12, 18, 24]) np.einsum(a, [0, 0], [0]) array([ 0, 6, 12, 18, 24]) np.diag(a) array([ 0, 6, 12, 18, 24])

Sum over an axis (requires explicit form):

np.einsum("ij->i", a) array([ 10, 35, 60, 85, 110]) np.einsum(a, [0, 1], [0]) array([ 10, 35, 60, 85, 110]) np.sum(a, axis=1) array([ 10, 35, 60, 85, 110])

For higher dimensional arrays summing a single axis can be done with ellipsis:

np.einsum("...j->...", a) array([ 10, 35, 60, 85, 110]) np.einsum(a, [Ellipsis, 1], [Ellipsis]) array([ 10, 35, 60, 85, 110])

Compute a matrix transpose, or reorder any number of axes:

np.einsum("ji", c) array([[0, 3], [1, 4], [2, 5]]) np.einsum("ij->ji", c) array([[0, 3], [1, 4], [2, 5]]) np.einsum(c, [1, 0]) array([[0, 3], [1, 4], [2, 5]]) np.transpose© array([[0, 3], [1, 4], [2, 5]])

Vector inner products:

np.einsum("i,i", b, b) np.int64(30) np.einsum(b, [0], b, [0]) np.int64(30) np.inner(b, b) np.int64(30)

Matrix vector multiplication:

np.einsum("ij,j", a, b) array([ 30, 80, 130, 180, 230]) np.einsum(a, [0, 1], b, [1]) array([ 30, 80, 130, 180, 230]) np.dot(a, b) array([ 30, 80, 130, 180, 230]) np.einsum("...j,j", a, b) array([ 30, 80, 130, 180, 230])

Broadcasting and scalar multiplication:

np.einsum("..., ...", 3, c) array([[ 0, 3, 6], [ 9, 12, 15]]) np.einsum(",ij", 3, c) array([[ 0, 3, 6], [ 9, 12, 15]]) np.einsum(3, [Ellipsis], c, [Ellipsis]) array([[ 0, 3, 6], [ 9, 12, 15]]) np.multiply(3, c) array([[ 0, 3, 6], [ 9, 12, 15]])

Vector outer product:

np.einsum("i,j", np.arange(2) + 1, b) array([[0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]) np.einsum(np.arange(2) + 1, [0], b, [1]) array([[0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]) np.outer(np.arange(2) + 1, b) array([[0, 1, 2, 3, 4], [0, 2, 4, 6, 8]])

Tensor contraction:

a = np.arange(60.0).reshape(3, 4, 5) b = np.arange(24.0).reshape(4, 3, 2) np.einsum("ijk,jil->kl", a, b) array([[4400., 4730.], [4532., 4874.], [4664., 5018.], [4796., 5162.], [4928., 5306.]]) np.einsum(a, [0, 1, 2], b, [1, 0, 3], [2, 3]) array([[4400., 4730.], [4532., 4874.], [4664., 5018.], [4796., 5162.], [4928., 5306.]]) np.tensordot(a, b, axes=([1, 0], [0, 1])) array([[4400., 4730.], [4532., 4874.], [4664., 5018.], [4796., 5162.], [4928., 5306.]])

Example of ellipsis use:

a = np.arange(6).reshape((3, 2)) b = np.arange(12).reshape((4, 3)) np.einsum("ki,jk->ij", a, b) array([[10, 28, 46, 64], [13, 40, 67, 94]]) np.einsum("ki,...k->i...", a, b) array([[10, 28, 46, 64], [13, 40, 67, 94]]) np.einsum("k...,jk", a, b) array([[10, 28, 46, 64], [13, 40, 67, 94]])

Source code in src/finch/interface/eager.py
def einsum(*args, **kwargs):
    """
    einsum(subscripts, *operands)

    Evaluates the Einstein summation convention on the operands.

    Using the Einstein summation convention, many common multi-dimensional,
    linear algebraic array operations can be represented in a simple fashion.
    In *implicit* mode `einsum` computes these values.

    In *explicit* mode, `einsum` provides further flexibility to compute
    other array operations that might not be considered classical Einstein
    summation operations, by disabling, or forcing summation over specified
    subscript labels.

    See the notes and examples for clarification.

    Parameters
    ----------
    subscripts : str
        Specifies the subscripts for summation as comma separated list of
        subscript labels. An implicit (classical Einstein summation)
        calculation is performed unless the explicit indicator '->' is
        included as well as subscript labels of the precise output form.
    operands : list of array_like
        These are the arrays for the operation.

    Returns
    -------
    output : ndarray
        The calculation based on the Einstein summation convention.

    Notes
    -----
    The Einstein summation convention can be used to compute
    many multi-dimensional, linear algebraic array operations. `einsum`
    provides a succinct way of representing these.

    A non-exhaustive list of these operations,
    which can be computed by `einsum`, is shown below along with examples:

    * Trace of an array, :py:func:`numpy.trace`.
    * Return a diagonal, :py:func:`numpy.diag`.
    * Array axis summations, :py:func:`numpy.sum`.
    * Transpositions and permutations, :py:func:`numpy.transpose`.
    * Matrix multiplication and dot product, :py:func:`numpy.matmul`
        :py:func:`numpy.dot`.
    * Vector inner and outer products, :py:func:`numpy.inner`
        :py:func:`numpy.outer`.
    * Broadcasting, element-wise and scalar multiplication,
        :py:func:`numpy.multiply`.
    * Tensor contractions, :py:func:`numpy.tensordot`.
    * Chained array operations, in efficient calculation order,
        :py:func:`numpy.einsum_path`.

    The subscripts string is a comma-separated list of subscript labels,
    where each label refers to a dimension of the corresponding operand.
    Whenever a label is repeated it is summed, so ``np.einsum('i,i', a, b)``
    is equivalent to :py:func:`np.inner(a,b) <numpy.inner>`. If a label
    appears only once, it is not summed, so ``np.einsum('i', a)``
    produces a view of ``a`` with no changes. A further example
    ``np.einsum('ij,jk', a, b)`` describes traditional matrix multiplication
    and is equivalent to :py:func:`np.matmul(a,b) <numpy.matmul>`.
    Repeated subscript labels in one operand take the diagonal.
    For example, ``np.einsum('ii', a)`` is equivalent to
    :py:func:`np.trace(a) <numpy.trace>`.

    In *implicit mode*, the chosen subscripts are important
    since the axes of the output are reordered alphabetically.  This
    means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while
    ``np.einsum('ji', a)`` takes its transpose. Additionally,
    ``np.einsum('ij,jk', a, b)`` returns a matrix multiplication, while,
    ``np.einsum('ij,jh', a, b)`` returns the transpose of the
    multiplication since subscript 'h' precedes subscript 'i'.

    In *explicit mode* the output can be directly controlled by
    specifying output subscript labels.  This requires the
    identifier '->' as well as the list of output subscript labels.
    This feature increases the flexibility of the function since
    summing can be disabled or forced when required. The call
    ``np.einsum('i->', a)`` is like :py:func:`np.sum(a) <numpy.sum>`
    if ``a`` is a 1-D array, and ``np.einsum('ii->i', a)``
    is like :py:func:`np.diag(a) <numpy.diag>` if ``a`` is a square 2-D array.
    The difference is that `einsum` does not allow broadcasting by default.
    Additionally ``np.einsum('ij,jh->ih', a, b)`` directly specifies the
    order of the output subscript labels and therefore returns matrix
    multiplication, unlike the example above in implicit mode.

    To enable and control broadcasting, use an ellipsis.  Default
    NumPy-style broadcasting is done by adding an ellipsis
    to the left of each term, like ``np.einsum('...ii->...i', a)``.
    ``np.einsum('...i->...', a)`` is like
    :py:func:`np.sum(a, axis=-1) <numpy.sum>` for array ``a`` of any shape.
    To take the trace along the first and last axes,
    you can do ``np.einsum('i...i', a)``, or to do a matrix-matrix
    product with the left-most indices instead of rightmost, one can do
    ``np.einsum('ij...,jk...->ik...', a, b)``.

    `einsum` also provides an alternative way to provide the subscripts and
    operands as ``einsum(op0, sublist0, op1, sublist1, ..., [sublistout])``.
    If the output shape is not provided in this format `einsum` will be
    calculated in implicit mode, otherwise it will be performed explicitly.
    The examples below have corresponding `einsum` calls with the two
    parameter methods.

    Examples
    --------
    >>> a = np.arange(25).reshape(5, 5)
    >>> b = np.arange(5)
    >>> c = np.arange(6).reshape(2, 3)

    Trace of a matrix:

    >>> np.einsum("ii", a)
    np.int64(60)
    >>> np.einsum(a, [0, 0])
    np.int64(60)
    >>> np.trace(a)
    np.int64(60)

    Extract the diagonal (requires explicit form):

    >>> np.einsum("ii->i", a)
    array([ 0,  6, 12, 18, 24])
    >>> np.einsum(a, [0, 0], [0])
    array([ 0,  6, 12, 18, 24])
    >>> np.diag(a)
    array([ 0,  6, 12, 18, 24])

    Sum over an axis (requires explicit form):

    >>> np.einsum("ij->i", a)
    array([ 10,  35,  60,  85, 110])
    >>> np.einsum(a, [0, 1], [0])
    array([ 10,  35,  60,  85, 110])
    >>> np.sum(a, axis=1)
    array([ 10,  35,  60,  85, 110])

    For higher dimensional arrays summing a single axis can be done
    with ellipsis:

    >>> np.einsum("...j->...", a)
    array([ 10,  35,  60,  85, 110])
    >>> np.einsum(a, [Ellipsis, 1], [Ellipsis])
    array([ 10,  35,  60,  85, 110])

    Compute a matrix transpose, or reorder any number of axes:

    >>> np.einsum("ji", c)
    array([[0, 3],
           [1, 4],
           [2, 5]])
    >>> np.einsum("ij->ji", c)
    array([[0, 3],
           [1, 4],
           [2, 5]])
    >>> np.einsum(c, [1, 0])
    array([[0, 3],
           [1, 4],
           [2, 5]])
    >>> np.transpose(c)
    array([[0, 3],
           [1, 4],
           [2, 5]])

    Vector inner products:

    >>> np.einsum("i,i", b, b)
    np.int64(30)
    >>> np.einsum(b, [0], b, [0])
    np.int64(30)
    >>> np.inner(b, b)
    np.int64(30)

    Matrix vector multiplication:

    >>> np.einsum("ij,j", a, b)
    array([ 30,  80, 130, 180, 230])
    >>> np.einsum(a, [0, 1], b, [1])
    array([ 30,  80, 130, 180, 230])
    >>> np.dot(a, b)
    array([ 30,  80, 130, 180, 230])
    >>> np.einsum("...j,j", a, b)
    array([ 30,  80, 130, 180, 230])

    Broadcasting and scalar multiplication:

    >>> np.einsum("..., ...", 3, c)
    array([[ 0,  3,  6],
           [ 9, 12, 15]])
    >>> np.einsum(",ij", 3, c)
    array([[ 0,  3,  6],
           [ 9, 12, 15]])
    >>> np.einsum(3, [Ellipsis], c, [Ellipsis])
    array([[ 0,  3,  6],
           [ 9, 12, 15]])
    >>> np.multiply(3, c)
    array([[ 0,  3,  6],
           [ 9, 12, 15]])

    Vector outer product:

    >>> np.einsum("i,j", np.arange(2) + 1, b)
    array([[0, 1, 2, 3, 4],
           [0, 2, 4, 6, 8]])
    >>> np.einsum(np.arange(2) + 1, [0], b, [1])
    array([[0, 1, 2, 3, 4],
           [0, 2, 4, 6, 8]])
    >>> np.outer(np.arange(2) + 1, b)
    array([[0, 1, 2, 3, 4],
           [0, 2, 4, 6, 8]])

    Tensor contraction:

    >>> a = np.arange(60.0).reshape(3, 4, 5)
    >>> b = np.arange(24.0).reshape(4, 3, 2)
    >>> np.einsum("ijk,jil->kl", a, b)
    array([[4400., 4730.],
           [4532., 4874.],
           [4664., 5018.],
           [4796., 5162.],
           [4928., 5306.]])
    >>> np.einsum(a, [0, 1, 2], b, [1, 0, 3], [2, 3])
    array([[4400., 4730.],
           [4532., 4874.],
           [4664., 5018.],
           [4796., 5162.],
           [4928., 5306.]])
    >>> np.tensordot(a, b, axes=([1, 0], [0, 1]))
    array([[4400., 4730.],
           [4532., 4874.],
           [4664., 5018.],
           [4796., 5162.],
           [4928., 5306.]])

    Example of ellipsis use:

    >>> a = np.arange(6).reshape((3, 2))
    >>> b = np.arange(12).reshape((4, 3))
    >>> np.einsum("ki,jk->ij", a, b)
    array([[10, 28, 46, 64],
           [13, 40, 67, 94]])
    >>> np.einsum("ki,...k->i...", a, b)
    array([[10, 28, 46, 64],
           [13, 40, 67, 94]])
    >>> np.einsum("k...,jk", a, b)
    array([[10, 28, 46, 64],
           [13, 40, 67, 94]])
    """

    if builtins.any(isinstance(v, lazy.LazyTensor) for v in args):
        return lazy.einsum(*args, **kwargs)
    return compute(lazy.einsum(*args, **kwargs))

fused(f, /, ctx=None)

  • fused(f): A decorator that marks a function as fused. This allows the function to be used with the fuse function for automatic fusion of operations.

Parameters: - f: The function to be marked as fused.

Returns: - A wrapper function that applies the fusion mechanism to the original function.

Source code in src/finch/interface/fuse.py
def fused(f, /, ctx=None):
    """
    - fused(f):
    A decorator that marks a function as fused. This allows the function to be used with
    the `fuse` function for automatic fusion of operations.

    Parameters:
    - f: The function to be marked as fused.

    Returns:
    - A wrapper function that applies the fusion mechanism to the original function.
    """
    if ctx is None:
        ctx = get_default_scheduler()

    def wrapper(*args):
        return fuse(f, *args, ctx=ctx)

    return wrapper

matmul(x1, x2)

Computes the matrix product.

Returns a LazyTensor if either x1 or x2 is a LazyTensor. Otherwise, computes the result eagerly.

Source code in src/finch/interface/eager.py
def matmul(x1, x2, /):
    """
    Computes the matrix product.

    Returns a LazyTensor if either x1 or x2 is a LazyTensor.
    Otherwise, computes the result eagerly.
    """
    if isinstance(x1, lazy.LazyTensor) or isinstance(x2, lazy.LazyTensor):
        return lazy.matmul(x1, x2)
    c = lazy.matmul(x1, x2)
    return compute(c)

matrix_transpose(x)

Computes the transpose of a matrix or stack of matrices.

Source code in src/finch/interface/eager.py
def matrix_transpose(x, /):
    """
    Computes the transpose of a matrix or stack of matrices.
    """
    if isinstance(x, lazy.LazyTensor):
        return lazy.matrix_transpose(x)
    return compute(lazy.matrix_transpose(x))

moveaxis(x, source, destination)

Moves array axes (dimensions) to new positions, while leaving other axes in their original positions.

Args

  • x (array) - input array.
  • source - Axes to move.
  • destination - indices defining the desired positions for each respective source axis index.

Returns

  • out (array) - an array containing reordered axes.
Source code in src/finch/interface/eager.py
def moveaxis(x, source: int | tuple[int, ...], destination: int | tuple[int, ...], /):
    """
    Moves array axes (dimensions) to new positions,
    while leaving other axes in their original positions.

    Args
    ---------
    - x (array) - input array.
    - source - Axes to move.
    - destination - indices defining the desired
    positions for each respective source axis index.

    Returns
    --------
    - out (array) - an array containing reordered axes.
    """
    if isinstance(x, lazy.LazyTensor):
        return lazy.moveaxis(x, source, destination)
    return compute(lazy.moveaxis(x, source, destination))

tensordot(x1, x2, /, *, axes=2)

Computes the tensordot operation.

Returns a LazyTensor if either x1 or x2 is a LazyTensor. Otherwise, computes the result eagerly.

Source code in src/finch/interface/eager.py
def tensordot(x1, x2, /, *, axes: int | tuple[Sequence[int], Sequence[int]] = 2):
    """
    Computes the tensordot operation.

    Returns a LazyTensor if either x1 or x2 is a LazyTensor.
    Otherwise, computes the result eagerly.
    """
    if isinstance(x1, lazy.LazyTensor) or isinstance(x2, lazy.LazyTensor):
        return lazy.tensordot(x1, x2, axes=axes)
    return compute(lazy.tensordot(x1, x2, axes=axes))

vecdot(x1, x2, /, *, axis=-1)

Computes the (vector) dot product of two arrays.

Parameters

x1: array The first input tensor. x2: array The second input tensor. axis: int, optional The axis along which to compute the dot product. Default is -1 (last axis).

Returns

out: array A tensor containing the dot product of x1 and x2 along the specified axis.

Source code in src/finch/interface/eager.py
def vecdot(x1, x2, /, *, axis=-1):
    """
    Computes the (vector) dot product of two arrays.

    Parameters
    ----------
    x1: array
        The first input tensor.
    x2: array
        The second input tensor.
    axis: int, optional
        The axis along which to compute the dot product. Default is -1 (last axis).

    Returns
    -------
    out: array
        A tensor containing the dot product of `x1` and `x2` along the specified axis.
    """
    if isinstance(x1, lazy.LazyTensor) or isinstance(x2, lazy.LazyTensor):
        return lazy.vecdot(x1, x2, axis=axis)
    return compute(lazy.vecdot(x1, x2, axis=axis))