.. meta::
   :description: nrtpy tensor cast and compute API — convert tensor dtypes and run element-wise ADD, MIN, and MAX on AWS Neuron devices from Python without loading a NEFF.
   :date-modified: 2026-11-17
   :keywords: Neuron, nrtpy, tensor_cast, tensor_compute, NrtComputeOp, NrtDtype, dtype conversion, element-wise reduction, Trainium

.. _nrtpy-tensor-compute-ref:

====================================
nrtpy tensor cast and compute API
====================================

This page documents :py:func:`~nrtpy.tensor_cast` and
:py:func:`~nrtpy.tensor_compute`, which run dtype conversion and element-wise
reductions on device tensors directly on Neuron hardware, without compiling or
loading a NEFF. They wrap the ``nrt_tensor_cast`` and ``nrt_tensor_compute``
APIs in ``libnrt``.

Both functions are synchronous. They block until the operation completes, and
they release the Python global interpreter lock (GIL) while they run, so other
Python threads can continue.

Requirements and limitations
----------------------------

- Supported only on Trn2 and later instances.
- Requires Neuron Driver 2.31 or later.
- All source and destination tensors must be allocated on the same logical
  NeuronCore (LNC).
- Every tensor passed to these functions must have a device dtype attached.
  See :ref:`nrtpy-tensor-compute-dtypes`.
- Operations always start at element 0 of each tensor.

Functions
---------

.. py:function:: nrtpy.tensor_cast(src, dst, num_elements)

   Convert ``num_elements`` elements of ``src`` from its device dtype to the
   device dtype of ``dst`` and write the result to ``dst``.

   :param src: Source tensor. Must have a device dtype attached.
   :type src: nrtpy.NrtpyTensor
   :param dst: Destination tensor. Must have a device dtype attached and be
      large enough to hold ``num_elements`` elements of that dtype.
   :type dst: nrtpy.NrtpyTensor
   :param int num_elements: Number of elements to convert.
   :raises TypeError: If ``src`` or ``dst`` is not an ``NrtpyTensor``.
   :raises nrtpy.NrtpyError: If a tensor has been freed or has no dtype.
   :raises nrtpy.NrtError: If ``libnrt`` rejects or fails the cast.

.. py:function:: nrtpy.tensor_compute(op, srcs, dst, num_elements)

   Apply the element-wise reduction ``op`` across all tensors in ``srcs`` and
   write ``num_elements`` result elements to ``dst``. For example, with
   ``NrtComputeOp.ADD`` and sources ``[a, b, c]``, ``dst[i] = a[i] + b[i] + c[i]``.

   :param op: Reduction to apply.
   :type op: nrtpy.NrtComputeOp
   :param srcs: One or more source tensors. Each must have a device dtype
      attached. Source dtypes can differ from each other and from ``dst``.
   :type srcs: Sequence[nrtpy.NrtpyTensor]
   :param dst: Destination tensor. Must have a device dtype attached.
   :type dst: nrtpy.NrtpyTensor
   :param int num_elements: Number of elements to process in each tensor.
   :raises TypeError: If ``dst`` or any element of ``srcs`` is not an
      ``NrtpyTensor``.
   :raises nrtpy.NrtpyError: If ``srcs`` is empty, or if a tensor has been
      freed or has no dtype.
   :raises nrtpy.NrtError: If ``libnrt`` rejects or fails the operation.

Both functions take :py:class:`~nrtpy.NrtpyTensor` objects and raise
``TypeError`` for any other argument type.

Enumerations
------------

.. py:class:: nrtpy.NrtComputeOp

   Element-wise reduction applied by :py:func:`~nrtpy.tensor_compute`.

   .. py:attribute:: ADD

      Element-wise sum of all sources.

   .. py:attribute:: MIN

      Element-wise minimum of all sources.

   .. py:attribute:: MAX

      Element-wise maximum of all sources.

.. py:class:: nrtpy.NrtDtype

   Element data type of a device tensor, matching ``nrt_dtype_t`` in
   ``libnrt``.

   .. list-table::
      :header-rows: 1
      :widths: 30 70

      * - Value
        - Description
      * - ``FLOAT32``
        - 32-bit IEEE float
      * - ``FP32R``
        - 32-bit float (``fp32r`` hardware format)
      * - ``FLOAT16``
        - 16-bit IEEE float
      * - ``BFLOAT16``
        - 16-bit brain float
      * - ``FP8_E3``, ``FP8_E4``, ``FP8_E5``
        - 8-bit floats with 3, 4, or 5 exponent bits
      * - ``INT8``, ``INT16``, ``INT32``, ``INT64``
        - Signed integers
      * - ``UINT8``, ``UINT16``, ``UINT32``, ``UINT64``
        - Unsigned integers

.. _nrtpy-tensor-compute-dtypes:

Device dtypes
-------------

Cast and compute use each tensor's device dtype, not its NumPy dtype.
:py:meth:`NrtpyTensor.from_numpy <nrtpy.NrtpyTensor.from_numpy>` sets the
device dtype automatically for ``float16``, ``float32``, and the signed and
unsigned 8- to 64-bit integer types. Tensors created from other NumPy dtypes
have no device dtype and are rejected with ``NrtpyError``. See
:ref:`nrtpy-tensor-dtypes` for the full mapping.

Output tensors that :py:class:`~nrtpy.NrtpyModel` allocates automatically also
have no device dtype. To cast or reduce model outputs, pass your own output
tensors created with ``from_numpy``.

Numerical behavior
------------------

The hardware block behind these APIs computes only in FP32. For every
operation it:

1. Converts each source element from its dtype to FP32.
2. Applies the operation in FP32 (``ADD``, ``MIN``, ``MAX``, or a multiply by
   1.0 for a cast).
3. Converts the FP32 result to the destination dtype.

Results can therefore differ from the equivalent host computation:

- **Casts that don't involve FP32 round twice.** For example, ``FLOAT16`` to
  ``BFLOAT16`` goes fp16 → fp32 (exact) → bf16 (rounded), which may not match a
  single-step host conversion of the original data. Casts where one side is
  FP32 round only once and match the host result.
- **Reductions accumulate in FP32.** Summing BF16 sources keeps FP32 precision
  across the reduction and rounds once, on the final store. This is more
  accurate than accumulating in BF16, but FP32 addition is not associative, so
  results are not bit-identical to a different summation order.
- **Wide integers lose low bits.** FP32 has a 24-bit significand, so
  ``INT32``, ``UINT32``, ``INT64``, and ``UINT64`` values with magnitude above
  2\ :sup:`24` are rounded. Don't use these APIs to move wide integer data
  byte-for-byte; use a plain tensor copy when no dtype change is needed.

Examples
--------

Cast FP32 to FP16
~~~~~~~~~~~~~~~~~

.. code-block:: python

   import numpy as np
   import nrtpy
   from nrtpy import NrtpyTensor

   src_data = np.array([1.5, -2.0, 3.25, 4.0], dtype=np.float32)
   src = NrtpyTensor.from_numpy(src_data, name="cast_src")
   dst = NrtpyTensor.from_numpy(np.zeros(src_data.size, dtype=np.float16),
                                name="cast_dst")

   nrtpy.tensor_cast(src, dst, src_data.size)

   print(dst.numpy())  # [ 1.5  -2.    3.25  4.  ]

Element-wise ADD of two tensors
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code-block:: python

   import numpy as np
   import nrtpy
   from nrtpy import NrtComputeOp, NrtpyTensor

   lhs = NrtpyTensor.from_numpy(np.array([1.0, 2.0, -3.0, 4.0], dtype=np.float32))
   rhs = NrtpyTensor.from_numpy(np.array([5.0, -2.0, 7.0, 8.0], dtype=np.float32))
   out = NrtpyTensor.from_numpy(np.zeros(4, dtype=np.float32))

   nrtpy.tensor_compute(
       NrtComputeOp.ADD,
       [lhs, rhs],
       out,
       4,
   )

   print(out.numpy())  # [ 6.  0.  4. 12.]

Related reference
-----------------

- :ref:`nrtpy-tensor-ref` — allocate device tensors and move data to and from
  NumPy.
- :ref:`nrtpy-errors-ref` — the ``NrtpyError`` and ``NrtError`` exceptions.
- :ref:`api_nrt_h` — the ``nrt_tensor_cast`` and ``nrt_tensor_compute`` C APIs.
