# GT4Py - GridTools Framework
#
# Copyright (c) 2014-2024, ETH Zurich
# All rights reserved.
#
# Please, refer to the LICENSE file in the root directory.
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import collections.abc
import dataclasses
import enum
import functools
import math
import numbers
from collections.abc import Iterator, Sequence
from typing import (
TYPE_CHECKING,
Any,
Final,
Generic,
Literal,
Self,
TypeAlias,
TypeGuard,
TypeVar,
Union,
cast,
overload,
)
import numpy as np
import numpy.typing as npt
from typing_extensions import Protocol
import gt4py.eve as eve
from gt4py._core import types as core_types
try:
import cupy as cp
except ImportError:
cp = None
if TYPE_CHECKING:
CuPyNDArray: TypeAlias = cp.ndarray
import jax.numpy as jnp
JaxNDArray: TypeAlias = jnp.ndarray
# The actual assignment happens after the definition of `DeviceType` enum.
CUPY_DEVICE_TYPE: Literal[None, DeviceType.CUDA, DeviceType.ROCM]
"""Type of the GPU accelerator device, if present."""
# -- Scalar types supported by GT4Py --
BoolScalar: TypeAlias = Union[core_types.bool, bool]
BoolT = TypeVar("BoolT", bound=BoolScalar)
BOOL_TYPES: Final[tuple[type, ...]] = cast(
tuple[type, ...],
BoolScalar.__args__, # type: ignore[attr-defined]
)
IntScalar: TypeAlias = Union[
core_types.int8, core_types.int16, core_types.int32, core_types.int64, int
]
IntT = TypeVar("IntT", bound=IntScalar)
INT_TYPES: Final[tuple[type, ...]] = cast(
tuple[type, ...],
IntScalar.__args__, # type: ignore[attr-defined]
)
UnsignedIntScalar: TypeAlias = Union[
core_types.uint8, core_types.uint16, core_types.uint32, core_types.uint64
]
UnsignedIntT = TypeVar("UnsignedIntT", bound=UnsignedIntScalar)
UINT_TYPES: Final[tuple[type, ...]] = cast(
tuple[type, ...],
UnsignedIntScalar.__args__, # type: ignore[attr-defined]
)
IntegralScalar: TypeAlias = Union[IntScalar, UnsignedIntScalar]
IntegralT = TypeVar("IntegralT", bound=IntegralScalar)
INTEGRAL_TYPES: Final[tuple[type, ...]] = (*INT_TYPES, *UINT_TYPES)
FloatingScalar: TypeAlias = Union[core_types.float32, core_types.float64, float]
FloatingT = TypeVar("FloatingT", bound=FloatingScalar)
FLOAT_TYPES: Final[tuple[type, ...]] = cast(
tuple[type, ...],
FloatingScalar.__args__, # type: ignore[attr-defined]
)
#: Type alias for all scalar types supported by GT4Py
Scalar: TypeAlias = Union[BoolScalar, IntegralScalar, FloatingScalar]
ScalarT = TypeVar("ScalarT", bound=Scalar)
SCALAR_TYPES: Final[tuple[type, ...]] = (*BOOL_TYPES, *INTEGRAL_TYPES, *FLOAT_TYPES)
[docs]
def is_scalar_type(t: Any) -> TypeGuard[Scalar]:
return isinstance(t, SCALAR_TYPES)
[docs]
class BooleanIntegral(numbers.Integral):
"""Abstract base class for boolean integral types."""
...
[docs]
class PositiveIntegral(numbers.Integral):
"""Abstract base class representing positive integral numbers.."""
...
[docs]
def is_boolean_integral_type(integral_type: type) -> TypeGuard[type[BooleanIntegral]]:
return issubclass(integral_type, BOOL_TYPES)
[docs]
def is_positive_integral_type(integral_type: type) -> TypeGuard[type[PositiveIntegral]]:
return issubclass(integral_type, UINT_TYPES)
TensorShape: TypeAlias = Sequence[
int
] # TODO(egparedes) figure out if PositiveIntegral can be made to work
[docs]
def is_valid_tensor_shape(value: Sequence[IntegralScalar]) -> TypeGuard[TensorShape]:
return isinstance(value, collections.abc.Sequence) and all(
isinstance(v, numbers.Integral) and v > 0 for v in value
)
# -- Data type descriptors --
[docs]
class DTypeKind(eve.StrEnum):
"""
Kind of a specific data type.
Character codes match the type code for the corresponding kind in the
array interface protocol (https://numpy.org/doc/stable/reference/arrays.interface.html).
"""
BOOL = "b"
INT = "i"
UINT = "u"
FLOAT = "f"
OPAQUE_POINTER = "V"
COMPLEX = "c"
@overload
def dtype_kind(
sc_type: type[IntT] | type[BoolT], # mypy doesn't distinguish IntT and BoolT
) -> Literal[DTypeKind.INT, DTypeKind.BOOL]: ...
@overload
def dtype_kind(sc_type: type[UnsignedIntT]) -> Literal[DTypeKind.UINT]: ... # type: ignore[overload-cannot-match] # precision blurring from mypy plugin seems to interfere
@overload
def dtype_kind(sc_type: type[FloatingT]) -> Literal[DTypeKind.FLOAT]: ...
@overload
def dtype_kind(sc_type: type[ScalarT]) -> DTypeKind: ...
[docs]
def dtype_kind(sc_type: type[ScalarT]) -> DTypeKind:
"""Return the data type kind of the given scalar type."""
# `np.bool_` is not registered as `numbers.Integral`
if is_boolean_integral_type(sc_type):
return DTypeKind.BOOL
if issubclass(sc_type, numbers.Integral):
if is_positive_integral_type(sc_type):
return DTypeKind.UINT
else:
return DTypeKind.INT
if issubclass(sc_type, numbers.Real):
return DTypeKind.FLOAT
if issubclass(sc_type, numbers.Complex):
return DTypeKind.COMPLEX
raise TypeError("Unknown scalar type kind.")
[docs]
@dataclasses.dataclass(frozen=True)
class DType(Generic[ScalarT]):
"""
Descriptor of data type for Field elements.
This definition is based on DLPack and Array API standards. The data type
should be interpreted as packed `lanes` repetitions of elements from
`kind` data-category of `bit_width` width.
The Array API standard only requires DTypes to be comparable with `__eq__`.
Additionally, instances of this class can also be used as valid NumPy
`dtype`s definitions due to the `.dtype` attribute.
"""
scalar_type: type[ScalarT]
tensor_shape: TensorShape = dataclasses.field(default=())
def __post_init__(self) -> None:
if not isinstance(self.scalar_type, type):
raise TypeError(f"Invalid scalar type '{self.scalar_type}'")
if not is_valid_tensor_shape(self.tensor_shape):
raise TypeError(f"Invalid tensor shape '{self.tensor_shape}'")
[docs]
@functools.cached_property
def kind(self) -> DTypeKind:
return dtype_kind(self.scalar_type)
[docs]
@functools.cached_property
def dtype(self) -> np.dtype:
"""The NumPy dtype corresponding to this DType."""
return np.dtype(f"{self.tensor_shape}{np.dtype(self.scalar_type).name}")
[docs]
@functools.cached_property
def byte_size(self) -> int:
return np.dtype(self.scalar_type).itemsize * self.lanes
@property
def bit_width(self) -> int:
return 8 * np.dtype(self.scalar_type).itemsize
@property
def lanes(self) -> int:
return math.prod(self.tensor_shape or (1,))
@property
def subndim(self) -> int:
return len(self.tensor_shape)
def __eq__(self, other: Any) -> bool:
return (
isinstance(other, DType)
and self.scalar_type == other.scalar_type
and self.tensor_shape == other.tensor_shape
)
def __hash__(self) -> int:
return hash((self.scalar_type, self.tensor_shape))
[docs]
@dataclasses.dataclass(frozen=True)
class IntegerDType(DType[IntegralT]):
pass
[docs]
@dataclasses.dataclass(frozen=True)
class UnsignedIntDType(DType[UnsignedIntT]):
pass
[docs]
@dataclasses.dataclass(frozen=True)
class UInt8DType(UnsignedIntDType[core_types.uint8]):
scalar_type: Final[type[core_types.uint8]] = dataclasses.field(
default=core_types.uint8, init=False
)
[docs]
@dataclasses.dataclass(frozen=True)
class UInt16DType(UnsignedIntDType[core_types.uint16]):
scalar_type: Final[type[core_types.uint16]] = dataclasses.field(
default=core_types.uint16, init=False
)
[docs]
@dataclasses.dataclass(frozen=True)
class UInt32DType(UnsignedIntDType[core_types.uint32]):
scalar_type: Final[type[core_types.uint32]] = dataclasses.field(
default=core_types.uint32, init=False
)
[docs]
@dataclasses.dataclass(frozen=True)
class UInt64DType(UnsignedIntDType[core_types.uint64]):
scalar_type: Final[type[core_types.uint64]] = dataclasses.field(
default=core_types.uint64, init=False
)
[docs]
@dataclasses.dataclass(frozen=True)
class SignedIntDType(DType[IntT]):
pass
[docs]
@dataclasses.dataclass(frozen=True)
class Int8DType(SignedIntDType[core_types.int8]):
scalar_type: Final[type[core_types.int8]] = dataclasses.field(
default=core_types.int8, init=False
)
[docs]
@dataclasses.dataclass(frozen=True)
class Int16DType(SignedIntDType[core_types.int16]):
scalar_type: Final[type[core_types.int16]] = dataclasses.field(
default=core_types.int16, init=False
)
[docs]
@dataclasses.dataclass(frozen=True)
class Int32DType(SignedIntDType[core_types.int32]):
scalar_type: Final[type[core_types.int32]] = dataclasses.field(
default=core_types.int32, init=False
)
[docs]
@dataclasses.dataclass(frozen=True)
class Int64DType(SignedIntDType[core_types.int64]):
scalar_type: Final[type[core_types.int64]] = dataclasses.field(
default=core_types.int64, init=False
)
[docs]
@dataclasses.dataclass(frozen=True)
class FloatingDType(DType[FloatingT]):
pass
[docs]
@dataclasses.dataclass(frozen=True)
class Float32DType(FloatingDType[core_types.float32]):
scalar_type: Final[type[core_types.float32]] = dataclasses.field(
default=core_types.float32, init=False
)
[docs]
@dataclasses.dataclass(frozen=True)
class Float64DType(FloatingDType[core_types.float64]):
scalar_type: Final[type[core_types.float64]] = dataclasses.field(
default=core_types.float64, init=False
)
[docs]
@dataclasses.dataclass(frozen=True)
class BoolDType(DType[core_types.bool]):
scalar_type: Final[type[core_types.bool]] = dataclasses.field(
default=core_types.bool, init=False
)
DTypeLike = Union[DType, npt.DTypeLike]
[docs]
def dtype(dtype_like: DTypeLike) -> DType:
"""Return the DType corresponding to the given dtype-like object."""
return dtype_like if isinstance(dtype_like, DType) else DType(np.dtype(dtype_like).type)
# -- Custom protocols --
[docs]
class GTDimsInterface(Protocol):
"""
A `GTDimsInterface` is an object providing the `__gt_dims__` property, naming the buffer dimensions.
In `gt4py.cartesian` the allowed values are `"I"`, `"J"` and `"K"` with the established semantics.
See :ref:`cartesian-arrays-dimension-mapping` for details.
"""
@property
def __gt_dims__(self) -> tuple[str, ...]: ...
[docs]
class GTOriginInterface(Protocol):
"""
A `GTOriginInterface` is an object providing `__gt_origin__`, describing the origin of a buffer.
See :ref:`cartesian-arrays-default-origin` for details.
"""
@property
def __gt_origin__(self) -> tuple[int, ...]: ...
# -- Device representation --
[docs]
class DeviceType(enum.IntEnum):
"""The type of the device where a memory buffer is allocated.
Enum values taken from DLPack reference implementation at:
https://github.com/dmlc/dlpack/blob/main/include/dlpack/dlpack.h
"""
CPU = 1
CUDA = 2
# CPU_PINNED = 3 # noqa: ERA001
# OPENCL = 4 # noqa: ERA001
# VULKAN = 7 # noqa: ERA001
# METAL = 8 # noqa: ERA001
# VPI = 9 # noqa: ERA001
ROCM = 10
# CUDA_MANAGED = 13 # noqa: ERA001
# ONE_API = 14 # noqa: ERA001
CPUDeviceTyping: TypeAlias = Literal[DeviceType.CPU]
CUDADeviceTyping: TypeAlias = Literal[DeviceType.CUDA]
ROCMDeviceTyping: TypeAlias = Literal[DeviceType.ROCM]
DeviceTypeT = TypeVar(
"DeviceTypeT",
CPUDeviceTyping,
CUDADeviceTyping,
ROCMDeviceTyping,
)
CUPY_DEVICE_TYPE = (
None if not cp else (DeviceType.ROCM if cp.cuda.runtime.is_hip else DeviceType.CUDA)
)
[docs]
def gpu_device_count() -> int:
"""Return how many GPU devices are usable, or 0 if there are none.
A `cupy` install alone does not imply a usable GPU: the wheels install
cleanly on machines with no driver and no visible device.
Returns:
The number of visible GPU devices, or 0 when `cupy` is missing or the
driver cannot be queried.
Note:
Enumerating is what makes the "installed but no visible device" case
answerable at all: it reports 0. A `cupy.cuda.Device()` probe only
resolves the *current* device and says nothing about how many exist.
"""
if cp is None:
return 0
try:
return cp.cuda.runtime.getDeviceCount()
except Exception:
# A broken driver or runtime raises rather than reporting zero devices.
return 0
[docs]
@dataclasses.dataclass(frozen=True)
class Device(Generic[DeviceTypeT]):
"""
Representation of a computing device.
This definition is based on the DLPack device definition. A device is
described by a pair of `DeviceType` and `device_id`. The `device_id`
is an integer that is interpreted differently depending on the
`DeviceType`. For example, for `DeviceType.CPU` it could be the CPU
core number, for `DeviceType.CUDA` it could be the CUDA device number, etc.
"""
device_type: DeviceTypeT
device_id: int
[docs]
@classmethod
def from_dlpack_device(cls: type[Self], dlpack_device: tuple[DeviceTypeT, int]) -> Self:
return cls(*dlpack_device)
def __iter__(self) -> Iterator[DeviceTypeT | int]:
yield self.device_type
yield self.device_id
# -- NDArrays and slices --
SliceLike = Union[int, tuple[int, ...], None, slice, "NDArrayObject"]
[docs]
class NDArrayObject(Protocol):
@property
def ndim(self) -> int: ...
@property
def shape(self) -> tuple[int, ...]: ...
@property
def strides(self) -> tuple[int, ...]: ...
@property
def dtype(self) -> Any: ...
@property
def itemsize(self) -> int: ...
[docs]
def item(self) -> Any: ...
[docs]
def astype(self, dtype: npt.DTypeLike) -> NDArrayObject: ...
[docs]
def any(self) -> bool: ...
def __getitem__(self, item: Any) -> NDArrayObject: ...
def __abs__(self) -> NDArrayObject: ...
def __neg__(self) -> NDArrayObject: ...
def __add__(self, other: NDArrayObject | Scalar) -> NDArrayObject: ...
def __radd__(self, other: Any) -> NDArrayObject: ...
def __sub__(self, other: NDArrayObject | Scalar) -> NDArrayObject: ...
def __rsub__(self, other: Any) -> NDArrayObject: ...
def __mul__(self, other: NDArrayObject | Scalar) -> NDArrayObject: ...
def __rmul__(self, other: Any) -> NDArrayObject: ...
def __floordiv__(self, other: NDArrayObject | Scalar) -> NDArrayObject: ...
def __rfloordiv__(self, other: Any) -> NDArrayObject: ...
def __truediv__(self, other: NDArrayObject | Scalar) -> NDArrayObject: ...
def __rtruediv__(self, other: Any) -> NDArrayObject: ...
def __pow__(self, other: NDArrayObject | Scalar) -> NDArrayObject: ...
def __eq__(self, other: NDArrayObject | Scalar) -> NDArrayObject: # type: ignore[override] # mypy wants to return `bool`
...
def __ne__(self, other: NDArrayObject | Scalar) -> NDArrayObject: # type: ignore[override] # mypy wants to return `bool`
...
def __gt__(self, other: NDArrayObject | Scalar) -> NDArrayObject: ...
def __ge__(self, other: NDArrayObject | Scalar) -> NDArrayObject: ...
def __lt__(self, other: NDArrayObject | Scalar) -> NDArrayObject: ...
def __le__(self, other: NDArrayObject | Scalar) -> NDArrayObject: ...
def __and__(self, other: NDArrayObject | Scalar) -> NDArrayObject: ...
def __or__(self, other: NDArrayObject | Scalar) -> NDArrayObject: ...
def __xor__(self, other: NDArrayObject | Scalar) -> NDArrayObject: ...