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)