Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions python/CuTeDSL/_mlir_helpers/vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -1255,6 +1255,7 @@ def broadcast_to(
"""Broadcast a scalar or narrower ``Vector`` to ``target_shape``."""
from ..base_dsl.typing import Numeric

dtype = src.dtype if isinstance(src, (Numeric, Vector)) else None
target_shape = _shape_tuple(target_shape)
if isinstance(src, (int, float, bool)):
elem_type = _infer_element_type(src)
Expand All @@ -1275,7 +1276,8 @@ def broadcast_to(
)

target_type = T.vector(*target_shape, elem_type)
return vector.broadcast(target_type, src, loc=loc, ip=ip)
result = vector.broadcast(target_type, src, loc=loc, ip=ip)
return Vector(result, dtype=dtype, loc=loc, ip=ip)


@dsl_user_op
Expand All @@ -1288,11 +1290,16 @@ def full(
ip: ir.InsertionPoint | None = None,
) -> Vector:
"""Return a new ``Vector`` of ``shape`` filled with ``fill_value``."""
from ..base_dsl.typing import Numeric

if dtype is None and isinstance(fill_value, Numeric):
dtype = fill_value.dtype
shape = _shape_tuple(shape)
elem_type = _infer_element_type(fill_value) if dtype is None else dtype.mlir_type
fill_val = _value_to_ir_value(fill_value, elem_type, loc=loc, ip=ip)
res_type = T.vector(*shape, elem_type)
return vector.broadcast(res_type, fill_val, loc=loc, ip=ip)
result = vector.broadcast(res_type, fill_val, loc=loc, ip=ip)
return Vector(result, dtype=dtype, loc=loc, ip=ip)


@dsl_user_op
Expand Down Expand Up @@ -1364,14 +1371,16 @@ def where(
elif isinstance(y, Vector):
result_dtype = y.dtype

def _promote(v: object) -> object:
def _promote(v: object) -> Vector:
if isinstance(v, Vector):
return v
if isinstance(v, (int, float, bool)):
return full(cond.shape, v, result_dtype, loc=loc, ip=ip)
return broadcast_to(v, cond.shape, loc=loc, ip=ip)

return arith.select(cond, _promote(x), _promote(y), loc=loc, ip=ip)
x, y = _promote(x), _promote(y)
result = arith.select(cond, x, y, loc=loc, ip=ip)
return Vector(result, dtype=x.dtype, loc=loc, ip=ip)


@dsl_user_op
Expand Down Expand Up @@ -1424,7 +1433,7 @@ def outerproduct(
raise ValueError(f"'b' must be 1-D, got shape {b.shape}")

result_type = ir.VectorType.get([a.shape[0], b.shape[0]], element_type(a.type))
return vector.outerproduct(
result = vector.outerproduct(
result_type,
a,
b,
Expand All @@ -1433,6 +1442,7 @@ def outerproduct(
loc=loc,
ip=ip,
)
return Vector(result, dtype=a.dtype, loc=loc, ip=ip)


@dsl_user_op
Expand Down
78 changes: 77 additions & 1 deletion test/python/CuTeDSL/test_vector_reduction_fastmath.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,16 @@
# is strictly prohibited.

"""
Unit test for the ``fastmath`` parameter on ``Vector.reduce``.
Unit tests for Vector reductions and element dtype preservation.
"""

import unittest

import cutlass
from cutlass._mlir import ir
from cutlass._mlir.dialects import arith, func
from cutlass._mlir.passmanager import PassManager
from cutlass._mlir_helpers import vector
from cutlass._mlir_helpers.vector import Vector


Expand All @@ -40,5 +43,78 @@ def test_fastmath_flag(self):
self.assertNotIn("reassoc", _reduce_ir())


class TestVectorDtypePreservation(unittest.TestCase):
def test_helpers_preserve_runtime_dtype(self):
with ir.Context(), ir.Location.unknown():
module = ir.Module.create()
vec_ty = ir.VectorType.get([2], cutlass.Uint8.mlir_type)
mask_ty = ir.VectorType.get([2], cutlass.Boolean.mlir_type)
with ir.InsertionPoint(module.body):
fn = func.FuncOp(
"test",
ir.FunctionType.get([vec_ty, cutlass.Uint8.mlir_type, mask_ty], []),
)
with ir.InsertionPoint(fn.add_entry_block()):
x = Vector(fn.arguments[0], dtype=cutlass.Uint8)
scalar = cutlass.Uint8(fn.arguments[1])
mask = Vector(fn.arguments[2], dtype=cutlass.Boolean)
zero = Vector.from_elements((0, 0), cutlass.Uint8)
one = Vector.from_elements((1, 1), cutlass.Uint8)
helpers = {
"full_explicit": lambda: cutlass.full((2,), 255, cutlass.Uint8),
"full_scalar": lambda: cutlass.full((2,), scalar),
"broadcast_scalar": lambda: vector.broadcast_to(scalar, (2,)),
"broadcast_vector": lambda: vector.broadcast_to(x, (2, 2)),
"where_vectors": lambda: vector.where(mask, x, zero),
"where_literal_lhs": lambda: vector.where(mask, 0, x),
"where_scalars": lambda: vector.where(
mask, scalar, cutlass.Uint8(0)
),
"outerproduct": lambda: vector.outerproduct(x, one),
}
for name, build in helpers.items():
with self.subTest(helper=name):
result = build()
self.assertIs(result.dtype, cutlass.Uint8)
self.assertIsInstance(
result[(0,) * len(result.shape)], cutlass.Uint8
)
self.assertEqual(
result.to(cutlass.Float32).owner.name, "arith.uitofp"
)
selected = vector.where(mask, x, 0)
for kind in ("min", "max"):
kind_attr = (
selected.reduce(kind).ir_value().owner.attributes["kind"]
)
self.assertIn(f"<{kind}ui>", str(kind_attr))
func.ReturnOp([])
module.operation.verify()

def test_where_dequantization_values(self):
with ir.Context(), ir.Location.unknown():
module = ir.Module.create()
with ir.InsertionPoint(module.body):
fn = func.FuncOp(
"dequantize",
ir.FunctionType.get([], [cutlass.Float32.mlir_type] * 2),
)
with ir.InsertionPoint(fn.add_entry_block()):
q = Vector.from_elements((128, 255), cutlass.Uint8)
zero = Vector.from_elements((0, 0), cutlass.Uint8)
mask = Vector.from_elements((True, True), cutlass.Boolean)
selected = vector.where(mask, q, zero)
out = (selected.to(cutlass.Float32) - 128.0) * 0.5
func.ReturnOp([out[0].ir_value(), out[1].ir_value()])
module.operation.verify()
PassManager.parse("builtin.module(canonicalize)").run(module.operation)
module.operation.verify()
actual = [
ir.FloatAttr(value.owner.attributes["value"]).value
for value in fn.entry_block.operations[-1].operands
]
self.assertEqual(actual, [0.0, 63.5])


if __name__ == "__main__":
unittest.main()