Skip to content

Commit 225648e

Browse files
authored
[mlir][python] add type wrappers (#71218)
1 parent 6a9613e commit 225648e

File tree

7 files changed

+276
-25
lines changed

7 files changed

+276
-25
lines changed

mlir/lib/Bindings/Python/IRCore.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2558,8 +2558,8 @@ void mlir::python::populateIRCore(py::module &m) {
25582558
[](py::object & /*class*/) {
25592559
auto *context = PyThreadContextEntry::getDefaultContext();
25602560
if (!context)
2561-
throw py::value_error("No current Context");
2562-
return context;
2561+
return py::none().cast<py::object>();
2562+
return py::cast(context);
25632563
},
25642564
"Gets the Context bound to the current thread or raises ValueError")
25652565
.def_property_readonly(

mlir/lib/Bindings/Python/IRTypes.cpp

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -463,7 +463,7 @@ class PyVectorType : public PyConcreteType<PyVectorType, PyShapedType> {
463463

464464
static void bindDerived(ClassTy &c) {
465465
c.def_static("get", &PyVectorType::get, py::arg("shape"),
466-
py::arg("elementType"), py::kw_only(),
466+
py::arg("element_type"), py::kw_only(),
467467
py::arg("scalable") = py::none(),
468468
py::arg("scalable_dims") = py::none(),
469469
py::arg("loc") = py::none(), "Create a vector type")
@@ -689,13 +689,9 @@ class PyTupleType : public PyConcreteType<PyTupleType> {
689689
static void bindDerived(ClassTy &c) {
690690
c.def_static(
691691
"get_tuple",
692-
[](py::list elementList, DefaultingPyMlirContext context) {
693-
intptr_t num = py::len(elementList);
694-
// Mapping py::list to SmallVector.
695-
SmallVector<MlirType, 4> elements;
696-
for (auto element : elementList)
697-
elements.push_back(element.cast<PyType>());
698-
MlirType t = mlirTupleTypeGet(context->get(), num, elements.data());
692+
[](std::vector<MlirType> elements, DefaultingPyMlirContext context) {
693+
MlirType t = mlirTupleTypeGet(context->get(), elements.size(),
694+
elements.data());
699695
return PyTupleType(context->getRef(), t);
700696
},
701697
py::arg("elements"), py::arg("context") = py::none(),
@@ -727,13 +723,11 @@ class PyFunctionType : public PyConcreteType<PyFunctionType> {
727723
static void bindDerived(ClassTy &c) {
728724
c.def_static(
729725
"get",
730-
[](std::vector<PyType> inputs, std::vector<PyType> results,
726+
[](std::vector<MlirType> inputs, std::vector<MlirType> results,
731727
DefaultingPyMlirContext context) {
732-
SmallVector<MlirType, 4> inputsRaw(inputs.begin(), inputs.end());
733-
SmallVector<MlirType, 4> resultsRaw(results.begin(), results.end());
734-
MlirType t = mlirFunctionTypeGet(context->get(), inputsRaw.size(),
735-
inputsRaw.data(), resultsRaw.size(),
736-
resultsRaw.data());
728+
MlirType t =
729+
mlirFunctionTypeGet(context->get(), inputs.size(), inputs.data(),
730+
results.size(), results.data());
737731
return PyFunctionType(context->getRef(), t);
738732
},
739733
py::arg("inputs"), py::arg("results"), py::arg("context") = py::none(),
@@ -742,7 +736,6 @@ class PyFunctionType : public PyConcreteType<PyFunctionType> {
742736
"inputs",
743737
[](PyFunctionType &self) {
744738
MlirType t = self;
745-
auto contextRef = self.getContext();
746739
py::list types;
747740
for (intptr_t i = 0, e = mlirFunctionTypeGetNumInputs(self); i < e;
748741
++i) {
@@ -754,7 +747,6 @@ class PyFunctionType : public PyConcreteType<PyFunctionType> {
754747
c.def_property_readonly(
755748
"results",
756749
[](PyFunctionType &self) {
757-
auto contextRef = self.getContext();
758750
py::list types;
759751
for (intptr_t i = 0, e = mlirFunctionTypeGetNumResults(self); i < e;
760752
++i) {

mlir/python/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ declare_mlir_python_sources(MLIRPythonSources.Core.Python
2121
_mlir_libs/__init__.py
2222
ir.py
2323
passmanager.py
24+
extras/types.py
2425
dialects/_ods_common.py
2526

2627
# The main _mlir module has submodules: include stubs from each.

mlir/python/mlir/extras/__init__.py

Whitespace-only changes.

mlir/python/mlir/extras/types.py

Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
2+
# See https://llvm.org/LICENSE.txt for license information.
3+
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
4+
5+
from functools import partial
6+
from typing import Optional, List
7+
8+
from ..ir import (
9+
Attribute,
10+
BF16Type,
11+
ComplexType,
12+
F16Type,
13+
F32Type,
14+
F64Type,
15+
Float8E4M3B11FNUZType,
16+
Float8E4M3FNType,
17+
Float8E5M2Type,
18+
FunctionType,
19+
IndexType,
20+
IntegerType,
21+
MemRefType,
22+
NoneType,
23+
OpaqueType,
24+
RankedTensorType,
25+
StridedLayoutAttr,
26+
StringAttr,
27+
TupleType,
28+
Type,
29+
UnrankedMemRefType,
30+
UnrankedTensorType,
31+
VectorType,
32+
)
33+
34+
index = lambda: IndexType.get()
35+
36+
37+
def i(width):
38+
return IntegerType.get_signless(width)
39+
40+
41+
def si(width):
42+
return IntegerType.get_signed(width)
43+
44+
45+
def ui(width):
46+
return IntegerType.get_unsigned(width)
47+
48+
49+
bool = lambda: i(1)
50+
i8 = lambda: i(8)
51+
i16 = lambda: i(16)
52+
i32 = lambda: i(32)
53+
i64 = lambda: i(64)
54+
55+
si8 = lambda: si(8)
56+
si16 = lambda: si(16)
57+
si32 = lambda: si(32)
58+
si64 = lambda: si(64)
59+
60+
ui8 = lambda: ui(8)
61+
ui16 = lambda: ui(16)
62+
ui32 = lambda: ui(32)
63+
ui64 = lambda: ui(64)
64+
65+
f16 = lambda: F16Type.get()
66+
f32 = lambda: F32Type.get()
67+
f64 = lambda: F64Type.get()
68+
bf16 = lambda: BF16Type.get()
69+
70+
f8E5M2 = lambda: Float8E5M2Type.get()
71+
f8E4M3 = lambda: Float8E4M3FNType.get()
72+
f8E4M3B11FNUZ = lambda: Float8E4M3B11FNUZType.get()
73+
74+
none = lambda: NoneType.get()
75+
76+
77+
def complex(type):
78+
return ComplexType.get(type)
79+
80+
81+
def opaque(dialect_namespace, type_data):
82+
return OpaqueType.get(dialect_namespace, type_data)
83+
84+
85+
def _shaped(*shape, element_type: Type = None, type_constructor=None):
86+
if type_constructor is None:
87+
raise ValueError("shaped is an abstract base class - cannot be constructed.")
88+
if (element_type is None and shape and not isinstance(shape[-1], Type)) or (
89+
shape and isinstance(shape[-1], Type) and element_type is not None
90+
):
91+
raise ValueError(
92+
f"Either element_type must be provided explicitly XOR last arg to tensor type constructor must be the element type."
93+
)
94+
if element_type is not None:
95+
type = element_type
96+
sizes = shape
97+
else:
98+
type = shape[-1]
99+
sizes = shape[:-1]
100+
if sizes:
101+
return type_constructor(sizes, type)
102+
else:
103+
return type_constructor(type)
104+
105+
106+
def vector(
107+
*shape,
108+
element_type: Type = None,
109+
scalable: Optional[List[bool]] = None,
110+
scalable_dims: Optional[List[int]] = None,
111+
):
112+
return _shaped(
113+
*shape,
114+
element_type=element_type,
115+
type_constructor=partial(
116+
VectorType.get, scalable=scalable, scalable_dims=scalable_dims
117+
),
118+
)
119+
120+
121+
def tensor(*shape, element_type: Type = None, encoding: Optional[str] = None):
122+
if encoding is not None:
123+
encoding = StringAttr.get(encoding)
124+
if not shape or (len(shape) == 1 and isinstance(shape[-1], Type)):
125+
if encoding is not None:
126+
raise ValueError("UnrankedTensorType does not support encoding.")
127+
return _shaped(
128+
*shape, element_type=element_type, type_constructor=UnrankedTensorType.get
129+
)
130+
return _shaped(
131+
*shape,
132+
element_type=element_type,
133+
type_constructor=partial(RankedTensorType.get, encoding=encoding),
134+
)
135+
136+
137+
def memref(
138+
*shape,
139+
element_type: Type = None,
140+
memory_space: Optional[int] = None,
141+
layout: Optional[StridedLayoutAttr] = None,
142+
):
143+
if memory_space is not None:
144+
memory_space = Attribute.parse(str(memory_space))
145+
if not shape or (len(shape) == 1 and isinstance(shape[-1], Type)):
146+
return _shaped(
147+
*shape,
148+
element_type=element_type,
149+
type_constructor=partial(UnrankedMemRefType.get, memory_space=memory_space),
150+
)
151+
return _shaped(
152+
*shape,
153+
element_type=element_type,
154+
type_constructor=partial(
155+
MemRefType.get, memory_space=memory_space, layout=layout
156+
),
157+
)
158+
159+
160+
def tuple(*elements):
161+
return TupleType.get_tuple(elements)
162+
163+
164+
def function(*, inputs, results):
165+
return FunctionType.get(inputs, results)

mlir/test/python/ir/builtin_types.py

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import gc
44
from mlir.ir import *
55
from mlir.dialects import arith, tensor, func, memref
6+
import mlir.extras.types as T
67

78

89
def run(f):
@@ -772,3 +773,101 @@ def testCustomTypeTypeCaster():
772773
print(t)
773774
# CHECK: OperationType(!transform.op<"foo.bar">)
774775
print(repr(t))
776+
777+
778+
# CHECK-LABEL: TEST: testTypeWrappers
779+
@run
780+
def testTypeWrappers():
781+
def stride(strides, offset=0):
782+
return StridedLayoutAttr.get(offset, strides)
783+
784+
with Context(), Location.unknown():
785+
ia = T.i(5)
786+
sia = T.si(6)
787+
uia = T.ui(7)
788+
assert repr(ia) == "IntegerType(i5)"
789+
assert repr(sia) == "IntegerType(si6)"
790+
assert repr(uia) == "IntegerType(ui7)"
791+
792+
assert T.i(16) == T.i16()
793+
assert T.si(16) == T.si16()
794+
assert T.ui(16) == T.ui16()
795+
796+
c1 = T.complex(T.f16())
797+
c2 = T.complex(T.i32())
798+
assert repr(c1) == "ComplexType(complex<f16>)"
799+
assert repr(c2) == "ComplexType(complex<i32>)"
800+
801+
vec_1 = T.vector(2, 3, T.f32())
802+
vec_2 = T.vector(2, 3, 4, T.f32())
803+
assert repr(vec_1) == "VectorType(vector<2x3xf32>)"
804+
assert repr(vec_2) == "VectorType(vector<2x3x4xf32>)"
805+
806+
m1 = T.memref(2, 3, 4, T.f64())
807+
assert repr(m1) == "MemRefType(memref<2x3x4xf64>)"
808+
809+
m2 = T.memref(2, 3, 4, T.f64(), memory_space=1)
810+
assert repr(m2) == "MemRefType(memref<2x3x4xf64, 1>)"
811+
812+
m3 = T.memref(2, 3, 4, T.f64(), memory_space=1, layout=stride([5, 7, 13]))
813+
assert repr(m3) == "MemRefType(memref<2x3x4xf64, strided<[5, 7, 13]>, 1>)"
814+
815+
m4 = T.memref(2, 3, 4, T.f64(), memory_space=1, layout=stride([5, 7, 13], 42))
816+
assert (
817+
repr(m4)
818+
== "MemRefType(memref<2x3x4xf64, strided<[5, 7, 13], offset: 42>, 1>)"
819+
)
820+
821+
S = ShapedType.get_dynamic_size()
822+
823+
t1 = T.tensor(S, 3, S, T.f64())
824+
assert repr(t1) == "RankedTensorType(tensor<?x3x?xf64>)"
825+
ut1 = T.tensor(T.f64())
826+
assert repr(ut1) == "UnrankedTensorType(tensor<*xf64>)"
827+
t2 = T.tensor(S, 3, S, element_type=T.f64())
828+
assert repr(t2) == "RankedTensorType(tensor<?x3x?xf64>)"
829+
ut2 = T.tensor(element_type=T.f64())
830+
assert repr(ut2) == "UnrankedTensorType(tensor<*xf64>)"
831+
832+
t3 = T.tensor(S, 3, S, T.f64(), encoding="encoding")
833+
assert repr(t3) == 'RankedTensorType(tensor<?x3x?xf64, "encoding">)'
834+
835+
v = T.vector(3, 3, 3, T.f64())
836+
assert repr(v) == "VectorType(vector<3x3x3xf64>)"
837+
838+
m5 = T.memref(S, 3, S, T.f64())
839+
assert repr(m5) == "MemRefType(memref<?x3x?xf64>)"
840+
um1 = T.memref(T.f64())
841+
assert repr(um1) == "UnrankedMemRefType(memref<*xf64>)"
842+
m6 = T.memref(S, 3, S, element_type=T.f64())
843+
assert repr(m6) == "MemRefType(memref<?x3x?xf64>)"
844+
um2 = T.memref(element_type=T.f64())
845+
assert repr(um2) == "UnrankedMemRefType(memref<*xf64>)"
846+
847+
m7 = T.memref(S, 3, S, T.f64())
848+
assert repr(m7) == "MemRefType(memref<?x3x?xf64>)"
849+
um3 = T.memref(T.f64())
850+
assert repr(um3) == "UnrankedMemRefType(memref<*xf64>)"
851+
852+
scalable_1 = T.vector(2, 3, T.f32(), scalable=[False, True])
853+
scalable_2 = T.vector(2, 3, 4, T.f32(), scalable=[True, False, True])
854+
assert repr(scalable_1) == "VectorType(vector<2x[3]xf32>)"
855+
assert repr(scalable_2) == "VectorType(vector<[2]x3x[4]xf32>)"
856+
857+
scalable_3 = T.vector(2, 3, T.f32(), scalable_dims=[1])
858+
scalable_4 = T.vector(2, 3, 4, T.f32(), scalable_dims=[0, 2])
859+
assert scalable_3 == scalable_1
860+
assert scalable_4 == scalable_2
861+
862+
opaq = T.opaque("scf", "placeholder")
863+
assert repr(opaq) == "OpaqueType(!scf.placeholder)"
864+
865+
tup1 = T.tuple(T.i16(), T.i32(), T.i64())
866+
tup2 = T.tuple(T.f16(), T.f32(), T.f64())
867+
assert repr(tup1) == "TupleType(tuple<i16, i32, i64>)"
868+
assert repr(tup2) == "TupleType(tuple<f16, f32, f64>)"
869+
870+
func = T.function(
871+
inputs=(T.i16(), T.i32(), T.i64()), results=(T.f16(), T.f32(), T.f64())
872+
)
873+
assert repr(func) == "FunctionType((i16, i32, i64) -> (f16, f32, f64))"

mlir/test/python/ir/context_managers.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,7 @@ def run(f):
1515
def testContextEnterExit():
1616
with Context() as ctx:
1717
assert Context.current is ctx
18-
try:
19-
_ = Context.current
20-
except ValueError as e:
21-
# CHECK: No current Context
22-
print(e)
23-
else:
24-
assert False, "Expected exception"
18+
assert Context.current is None
2519

2620

2721
run(testContextEnterExit)

0 commit comments

Comments
 (0)