Skip to content

Dtypes

Simplegrad uses float32 as its global default dtype, matching PyTorch conventions. The dtype utilities let you inspect and change the global default, convert raw Python or NumPy data into properly typed arrays, and look up NumPy dtype classes by string name. The global default is consulted by the conversion utilities as_array and convert_to_dtype (used when building tensors from raw Python or NumPy data); the factory functions take an explicit dtype argument that defaults to float32.

import simplegrad as sg

sg.default_dtype("float64")
print(sg.get_default_dtype())          # "float64"

# Conversion utilities pick up the global default:
print(sg.as_array([1.0, 2.0]).dtype)   # float64

# Factory functions keep their own explicit default of float32:
print(sg.ones((3, 3)).dtype)           # float32

default_dtype(dtype: str)

Set global default dtype (string key).

get_default_dtype()

Return current dtype string key.

get_default_dtype_class()

Return current NumPy dtype class.

get_dtype_class(dtype: str)

Return NumPy dtype class for given dtype string key.

as_array(values, dtype=None, device: str = 'cpu', **kwargs)

Convert values into an array on the given device with the specified dtype.

Routes to numpy for "cpu" and cupy for "cuda:N". The dtype defaults to the current global dtype when not specified.

Parameters:

  • values –

    Input data (list, ndarray, scalar, or backend array).

  • dtype –

    NumPy dtype class or None to use the global default.

  • device (str, default: 'cpu' ) –

    Device string controlling which backend to use.

  • **kwargs –

    Forwarded to the backend array() constructor.

Returns:

  • –

    Array of the requested dtype on the given device.

convert_to_dtype(array: np.ndarray, dtype: str | None = None)

Convert a numpy array to the specified dtype or to the global default dtype.