1 //===- DialectSparseTensor.cpp - 'sparse_tensor' dialect submodule --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "mlir-c/Dialect/SparseTensor.h" 10 #include "mlir-c/IR.h" 11 #include "mlir/Bindings/Python/PybindAdaptors.h" 12 13 namespace py = pybind11; 14 using namespace llvm; 15 using namespace mlir; 16 using namespace mlir::python::adaptors; 17 18 static void populateDialectSparseTensorSubmodule(const py::module &m) { 19 py::enum_<MlirSparseTensorDimLevelType>(m, "DimLevelType", py::module_local()) 20 .value("dense", MLIR_SPARSE_TENSOR_DIM_LEVEL_DENSE) 21 .value("compressed", MLIR_SPARSE_TENSOR_DIM_LEVEL_COMPRESSED); 22 23 mlir_attribute_subclass(m, "EncodingAttr", 24 mlirAttributeIsASparseTensorEncodingAttr) 25 .def_classmethod( 26 "get", 27 [](py::object cls, 28 std::vector<MlirSparseTensorDimLevelType> dimLevelTypes, 29 llvm::Optional<MlirAffineMap> dimOrdering, int pointerBitWidth, 30 int indexBitWidth, MlirContext context) { 31 return cls(mlirSparseTensorEncodingAttrGet( 32 context, dimLevelTypes.size(), dimLevelTypes.data(), 33 dimOrdering ? *dimOrdering : MlirAffineMap{nullptr}, 34 pointerBitWidth, indexBitWidth)); 35 }, 36 py::arg("cls"), py::arg("dim_level_types"), py::arg("dim_ordering"), 37 py::arg("pointer_bit_width"), py::arg("index_bit_width"), 38 py::arg("context") = py::none(), 39 "Gets a sparse_tensor.encoding from parameters.") 40 .def_property_readonly( 41 "dim_level_types", 42 [](MlirAttribute self) { 43 std::vector<MlirSparseTensorDimLevelType> ret; 44 for (int i = 0, 45 e = mlirSparseTensorEncodingGetNumDimLevelTypes(self); 46 i < e; ++i) 47 ret.push_back( 48 mlirSparseTensorEncodingAttrGetDimLevelType(self, i)); 49 return ret; 50 }) 51 .def_property_readonly( 52 "dim_ordering", 53 [](MlirAttribute self) -> llvm::Optional<MlirAffineMap> { 54 MlirAffineMap ret = 55 mlirSparseTensorEncodingAttrGetDimOrdering(self); 56 if (mlirAffineMapIsNull(ret)) 57 return {}; 58 return ret; 59 }) 60 .def_property_readonly( 61 "pointer_bit_width", 62 [](MlirAttribute self) { 63 return mlirSparseTensorEncodingAttrGetPointerBitWidth(self); 64 }) 65 .def_property_readonly("index_bit_width", [](MlirAttribute self) { 66 return mlirSparseTensorEncodingAttrGetIndexBitWidth(self); 67 }); 68 } 69 70 PYBIND11_MODULE(_mlirDialectsSparseTensor, m) { 71 m.doc() = "MLIR SparseTensor dialect."; 72 populateDialectSparseTensorSubmodule(m); 73 } 74