.. _nki-language:

nki.language
====================

.. currentmodule:: nki.language

The ``nki.language`` module provides high-level constructs for writing NKI kernels.
It includes tensor creation, indexing, type casting, math operations, and loop constructs
that the NKI compiler translates into efficient hardware instructions.

.. _nl_creation:

Creation operations
--------------------

.. autosummary::
   :toctree: generated
   :nosignatures:

   ndarray
   zeros
   ones
   full
   zeros_like
   empty_like
   shared_constant
   shared_identity_matrix
   rand
   random_seed

.. _nl_tensor_class:

Tensor class
------------

:class:`NkiTensor` is the tensor type returned by the creation operations
above. Its view methods (``slice``, ``select``, ``reshape``, ``permute``,
``view``, ``ap``, etc.) return new ``NkiTensor`` views that share the same
underlying storage, without copying data.

.. autosummary::
   :toctree: generated
   :template: nki-custom-class-template.rst
   :nosignatures:

   NkiTensor

.. _nl_tiled_grids:

Tiled grids
-----------

Tiled grids organize a tensor into logical tile or block coordinates without
copying its data. Indexing preserves the grid abstraction; use
:attr:`NkiGrid.data` to produce the exact :class:`NkiTensor` operand consumed
by an NKI instruction. The series starting with
:ref:`nki-tiled-grid-fundamentals` covers the programming model,
remainder handling, runtime indexing, sharding, and stream-buffer examples.

View and allocation functions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. autosummary::
   :toctree: generated
   :nosignatures:

   tiles
   blocks
   alloc_tiles
   alloc_blocks
   alloc_stream_buffers

For an allocation that matches an existing tensor or grid, use
:func:`empty_like`.

Selection and sharding functions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. autosummary::
   :toctree: generated
   :nosignatures:

   grid_element_offset
   contiguous_indices
   interleaved_indices

Grid classes
~~~~~~~~~~~~

Grid and stream objects are created by the functions above rather than by
calling their constructors.

.. autosummary::
   :toctree: generated
   :template: nki-indexable-class-template.rst
   :nosignatures:

   NkiGrid
   NkiStreamBuffers

.. autosummary::
   :toctree: generated
   :template: nki-custom-class-template.rst
   :nosignatures:

   NkiTileGrid
   NkiBlockGrid

.. autosummary::
   :toctree: generated
   :template: nki-autoclass-template.rst
   :nosignatures:

   GridElementOffset

The ``GridIndex`` and ``GridKey`` type aliases describe the accepted
:meth:`NkiGrid.__getitem__` keys.

.. _nl_tensor_ops:

Tensor operations
------------------

.. autosummary::
   :toctree: generated
   :nosignatures:

   load
   load_transpose2d
   store
   copy
   matmul
   transpose

.. _nl_operators:

Operators
---------

.. autosummary::
   :toctree: generated
   :template: nki-custom-class-template.rst
   :nosignatures:

   Op

.. _nl_math:

Math operations
----------------

A binary math operation such as :func:`add` or :func:`multiply` lowers to
:func:`nki.isa.tensor_scalar` when one operand is a scalar or a ``(P, 1)`` tile, and to
:func:`nki.isa.tensor_tensor` when both operands are tiles of the same shape. The
constraints of the chosen instruction apply:

- On the ``tensor_scalar`` path, a tile operand must be float32 with shape ``(P, 1)``,
  where ``P`` is the partition count of the other operand.
- The ``tensor_scalar`` path does not support ``divide``, ``mod`` or ``fmod``.
- Neither path divides float tiles. Multiply by :func:`reciprocal` instead. The result
  can differ from exact division: the reciprocal is approximate (see
  :ref:`tbl-act-func`), and the multiply rounds again.

.. autosummary::
   :toctree: generated
   :nosignatures:

   abs
   abs_max
   abs_min
   add
   arctan
   ceil
   cos

   .. divide : not supported

   exp
   floor
   is_finite
   log
   maximum
   minimum
   multiply
   negative
   power
   reciprocal
   rsqrt
   sign
   sin
   sqrt
   square
   subtract
   tan
   tanh
   trunc

.. _nl_activation_and_backpropagation:

Activation and Backpropagation functions
-----------------------------------------

.. autosummary::
   :toctree: generated
   :nosignatures:

   relu
   sigmoid
   silu
   silu_dx
   gelu
   gelu_dx
   gelu_apprx_sigmoid
   gelu_apprx_sigmoid_dx
   gelu_apprx_tanh
   mish
   softplus
   log1p
   softmax
   erf
   erf_dx


.. _nl_normalization_and_regularization:

Normalization and Regularization functions
------------------------------------------

.. autosummary::
   :toctree: generated
   :nosignatures:

   dropout
   rms_norm


.. _nl_reduction:

Reduction operations
---------------------

.. autosummary::
   :toctree: generated
   :nosignatures:

   all
   max
   mean
   min
   prod
   sum
   var

.. _nl_comparison:

Comparison operations
----------------------

.. autosummary::
   :toctree: generated
   :nosignatures:

   equal
   not_equal
   less
   less_equal
   greater
   greater_equal

.. _nl_logical:

Logical operations
-------------------

.. autosummary::
   :toctree: generated
   :nosignatures:

   logical_and
   logical_or
   logical_xor
   logical_not

.. _nl_bitwise:

Bitwise operations
-------------------

.. autosummary::
   :toctree: generated
   :nosignatures:

   bitwise_and
   bitwise_or
   bitwise_xor
   invert
   left_shift
   right_shift

.. _nl_tensor_manipulation_operations:

Tensor manipulation operations
-------------------------------

.. autosummary::
   :toctree: generated
   :nosignatures:

   broadcast_to
   ds
   expand_dims


.. _nl_indexing:

Indexing operations
------------------------------

.. autosummary::
   :toctree: generated
   :nosignatures:

   where
   gather_flattened

.. _nl_iterators:

Iterators
----------

.. autosummary::
   :toctree: generated
   :nosignatures:

   affine_range
   sequential_range
   static_range


.. _nl_control_flow:

Control Flow
------------

.. autosummary::
   :toctree: generated
   :nosignatures:

   fori_loop
   if_else
   while_loop


.. _nl_memory_hierarchy:

Memory Hierarchy
-----------------

.. autosummary::
   :toctree: generated
   :nosignatures:

   psum
   sbuf
   hbm
   private_hbm
   shared_hbm
   is_psum
   is_sbuf
   is_hbm
   is_on_chip

.. _nl_others:

Others
-------

.. autosummary::
   :toctree: generated
   :nosignatures:

   device_print
   no_reorder
   program_id
   num_programs
   program_ndim

.. _nl_datatypes:

Data Types
-----------

.. autosummary::
   :toctree: generated
   :nosignatures:

   bool_
   int8
   int16
   int32
   uint8
   uint16
   uint32
   float16
   float32
   bfloat16
   tfloat32
   float8_e4m3
   float8_e5m2
   float8_e4m3fn
   float8_e8m0fnu
   float8_e5m2_x4
   float8_e4m3fn_x4
   float4_e2m1fn_x4


.. _nl_constants:

Constants
----------

.. list-table::

   * - :doc:`tile_size <nki.language.tile_size>`
     - Hardware tile size constants (pmax, psum_bank_fmax, gemm_stationary_fmax, etc.)

.. toctree::
   :hidden:

   nki.language.tile_size


.. _nl_operator_constants:

Operator Constants
-------------------

.. autosummary::
   :toctree: generated
   :nosignatures:

   prelu
   bypass
