[Mlir-commits] [mlir] 0f65df7 - [mlir][sparse] remove the MLIR PyTACO tests (#66302)
llvmlistbot at llvm.org
llvmlistbot at llvm.org
Wed Sep 13 15:54:53 PDT 2023
Author: Aart Bik
Date: 2023-09-13T15:54:49-07:00
New Revision: 0f65df732ca2b124f473179eda801abf4496a350
URL: https://github.com/llvm/llvm-project/commit/0f65df732ca2b124f473179eda801abf4496a350
DIFF: https://github.com/llvm/llvm-project/commit/0f65df732ca2b124f473179eda801abf4496a350.diff
LOG: [mlir][sparse] remove the MLIR PyTACO tests (#66302)
Rationale:
This test was really fun to compare the MLIR sparsifier with TACO using
the PyTACO format. However, the underlying mechanism is rapidly growing
outdated with our recent developments. Rather than maintaining the old
code, we are moving toward the newer, better approaches. So if you are
sad this is gone, stay tuned, something better is coming!
Added:
Modified:
Removed:
mlir/test/Integration/Dialect/SparseTensor/taco/README.md
mlir/test/Integration/Dialect/SparseTensor/taco/data/A.mtx
mlir/test/Integration/Dialect/SparseTensor/taco/data/B.mtx
mlir/test/Integration/Dialect/SparseTensor/taco/data/gold_A.tns
mlir/test/Integration/Dialect/SparseTensor/taco/data/gold_C.tns
mlir/test/Integration/Dialect/SparseTensor/taco/data/gold_y.tns
mlir/test/Integration/Dialect/SparseTensor/taco/data/nell-2.tns
mlir/test/Integration/Dialect/SparseTensor/taco/data/pwtk.mtx
mlir/test/Integration/Dialect/SparseTensor/taco/lit.local.cfg
mlir/test/Integration/Dialect/SparseTensor/taco/test_MTTKRP.py
mlir/test/Integration/Dialect/SparseTensor/taco/test_SDDMM.py
mlir/test/Integration/Dialect/SparseTensor/taco/test_SpMM.py
mlir/test/Integration/Dialect/SparseTensor/taco/test_SpMV.py
mlir/test/Integration/Dialect/SparseTensor/taco/test_Tensor.py
mlir/test/Integration/Dialect/SparseTensor/taco/test_scalar_tensor_algebra.py
mlir/test/Integration/Dialect/SparseTensor/taco/test_simple_tensor_algebra.py
mlir/test/Integration/Dialect/SparseTensor/taco/test_tensor_complex.py
mlir/test/Integration/Dialect/SparseTensor/taco/test_tensor_types.py
mlir/test/Integration/Dialect/SparseTensor/taco/test_tensor_unary_ops.py
mlir/test/Integration/Dialect/SparseTensor/taco/test_true_dense_tensor_algebra.py
mlir/test/Integration/Dialect/SparseTensor/taco/tools/lit.local.cfg
mlir/test/Integration/Dialect/SparseTensor/taco/tools/mlir_pytaco.py
mlir/test/Integration/Dialect/SparseTensor/taco/tools/mlir_pytaco_api.py
mlir/test/Integration/Dialect/SparseTensor/taco/tools/mlir_pytaco_io.py
mlir/test/Integration/Dialect/SparseTensor/taco/tools/mlir_pytaco_utils.py
mlir/test/Integration/Dialect/SparseTensor/taco/tools/mlir_sparse_compiler.py
mlir/test/Integration/Dialect/SparseTensor/taco/tools/testing_utils.py
mlir/test/Integration/Dialect/SparseTensor/taco/unit_test_tensor_core.py
mlir/test/Integration/Dialect/SparseTensor/taco/unit_test_tensor_io.py
mlir/test/Integration/Dialect/SparseTensor/taco/unit_test_tensor_utils.py
################################################################################
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/README.md b/mlir/test/Integration/Dialect/SparseTensor/taco/README.md
deleted file mode 100644
index 88a8ce258196202..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/README.md
+++ /dev/null
@@ -1,27 +0,0 @@
-# MLIR-PyTACO: Implementing PyTACO with MLIR
-
-TACO (http://tensor-compiler.org/) is a tensor algebra compiler. TACO defines
-PyTACO, a domain specific language in Python, for writing tensor algebra
-applications.
-
-This directory contains the implementation of PyTACO using MLIR. In particular,
-we implement a Python layer that accepts the PyTACO language, generates MLIR
-linalg.generic OPs with sparse tensor annotation to represent the tensor
-computation, and invokes the MLIR sparse tensor code generator
-(https://mlir.llvm.org/docs/Dialects/SparseTensorOps/) as well as other MLIR
-compilation passes to generate an executable. Then, we invoke the MLIR execution
-engine to execute the program and pass the result back to the Python layer.
-
-As can be seen from the tests in this directory, in order to port a PyTACO
-program to MLIR-PyTACO, we basically only need to replace this line that imports
-PyTACO:
-
-```python
-import pytaco as pt
-```
-
-with this line to import MLIR-PyTACO:
-
-```python
-from tools import mlir_pytaco_api as pt
-```
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/data/A.mtx b/mlir/test/Integration/Dialect/SparseTensor/taco/data/A.mtx
deleted file mode 100644
index 6ea0893af616432..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/data/A.mtx
+++ /dev/null
@@ -1,11 +0,0 @@
-%%MatrixMarket matrix coordinate real general
-3 3 9
-1 1 1.0
-1 2 2.0
-1 3 4.0
-2 1 4.0
-2 2 5.0
-2 3 6.0
-3 1 7.0
-3 2 8.0
-3 3 9.0
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/data/B.mtx b/mlir/test/Integration/Dialect/SparseTensor/taco/data/B.mtx
deleted file mode 100644
index 9bb604d44c7c9f5..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/data/B.mtx
+++ /dev/null
@@ -1,11 +0,0 @@
-%%MatrixMarket matrix coordinate real general
-3 3 9
-1 1 10.0
-1 2 11.0
-1 3 12.0
-2 1 13.0
-2 2 14.0
-2 3 15.0
-3 1 16.0
-3 2 17.0
-3 3 18.0
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/data/gold_A.tns b/mlir/test/Integration/Dialect/SparseTensor/taco/data/gold_A.tns
deleted file mode 100644
index f06646b51feca77..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/data/gold_A.tns
+++ /dev/null
@@ -1,53 +0,0 @@
-# See http://frostt.io/tensors/file-formats.html for FROSTT (.tns) format
-2 50
-2 25
-1 1 12
-1 2 12
-1 3 12
-1 4 12
-1 5 12
-1 6 12
-1 7 12
-1 8 12
-1 9 12
-1 10 12
-1 11 12
-1 12 12
-1 13 12
-1 14 12
-1 15 12
-1 16 12
-1 17 12
-1 18 12
-1 19 12
-1 20 12
-1 21 12
-1 22 12
-1 23 12
-1 24 12
-1 25 12
-2 1 6
-2 2 6
-2 3 6
-2 4 6
-2 5 6
-2 6 6
-2 7 6
-2 8 6
-2 9 6
-2 10 6
-2 11 6
-2 12 6
-2 13 6
-2 14 6
-2 15 6
-2 16 6
-2 17 6
-2 18 6
-2 19 6
-2 20 6
-2 21 6
-2 22 6
-2 23 6
-2 24 6
-2 25 6
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/data/gold_C.tns b/mlir/test/Integration/Dialect/SparseTensor/taco/data/gold_C.tns
deleted file mode 100644
index 61bec5dece95121..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/data/gold_C.tns
+++ /dev/null
@@ -1,12 +0,0 @@
-# See http://frostt.io/tensors/file-formats.html for FROSTT (.tns) format
-2 9
-3 3
-1 1 100
-1 2 107
-1 3 114
-2 1 201
-2 2 216
-2 3 231
-3 1 318
-3 2 342
-3 3 366
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/data/gold_y.tns b/mlir/test/Integration/Dialect/SparseTensor/taco/data/gold_y.tns
deleted file mode 100644
index 832cb1795aaaa25..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/data/gold_y.tns
+++ /dev/null
@@ -1,6 +0,0 @@
-# See http://frostt.io/tensors/file-formats.html for FROSTT (.tns) format
-1 3
-3
-1 37102
-2 -20.4138
-3 804927
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/data/nell-2.tns b/mlir/test/Integration/Dialect/SparseTensor/taco/data/nell-2.tns
deleted file mode 100644
index b82ce864820fba3..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/data/nell-2.tns
+++ /dev/null
@@ -1,10 +0,0 @@
-# Extended FROSTT format:
-# rank number-non-zero-elements
-# dimension-sizes
-3 5
-2 4 4
-1 1 1 1.0
-1 2 2 2.0
-1 3 4 3.0
-2 1 1 1.0
-2 4 3 2.0
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/data/pwtk.mtx b/mlir/test/Integration/Dialect/SparseTensor/taco/data/pwtk.mtx
deleted file mode 100644
index c207a8681c4e9ea..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/data/pwtk.mtx
+++ /dev/null
@@ -1,14 +0,0 @@
-%%MatrixMarket matrix coordinate real general
-%-------------------------------------------------------------------------------
-% To download a matrix for a real world application
-% https://math.nist.gov/MatrixMarket/
-%-------------------------------------------------------------------------------
-3 3 8
-1 1 37423.0879671
-1 2 -22.4050781162
-1 3 -300.654980157
-2 1 -22.4050781162
-2 3 -.00869762944058
-3 1 -300.654980157
-3 2 -.00869762944058
-3 3 805225.750212
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/lit.local.cfg b/mlir/test/Integration/Dialect/SparseTensor/taco/lit.local.cfg
deleted file mode 100644
index f1bbcf486bc2705..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/lit.local.cfg
+++ /dev/null
@@ -1,5 +0,0 @@
-# Disable ASAN's leak detection for python taco tests.
-config.environment["ASAN_OPTIONS"] = "detect_leaks=0"
-# Only run when python bindings are enabled.
-if not config.enable_bindings_python:
- config.unsupported = True
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/test_MTTKRP.py b/mlir/test/Integration/Dialect/SparseTensor/taco/test_MTTKRP.py
deleted file mode 100644
index 2d558f8d6ddff4d..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/test_MTTKRP.py
+++ /dev/null
@@ -1,55 +0,0 @@
-# RUN: env SUPPORTLIB=%mlir_c_runner_utils %PYTHON %s | FileCheck %s
-
-import numpy as np
-import os
-import sys
-import tempfile
-
-_SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
-sys.path.append(_SCRIPT_PATH)
-
-from tools import mlir_pytaco_api as pt
-from tools import testing_utils as utils
-
-###### This PyTACO part is taken from the TACO open-source project. ######
-# See http://tensor-compiler.org/docs/data_analytics/index.html.
-
-compressed = pt.compressed
-dense = pt.dense
-
-# Define formats for storing the sparse tensor and dense matrices.
-csf = pt.format([compressed, compressed, compressed])
-rm = pt.format([dense, dense])
-
-# Load a sparse three-dimensional tensor from file (stored in the FROSTT
-# format) and store it as a compressed sparse fiber tensor. We use a small
-# tensor for the purpose of testing. To run the program using the data from
-# the real application, please download the data from:
-# http://frostt.io/tensors/nell-2/
-B = pt.read(os.path.join(_SCRIPT_PATH, "data/nell-2.tns"), csf)
-
-# These two lines have been modified from the original program to use static
-# data to support result comparison.
-C = pt.from_array(np.full((B.shape[1], 25), 1, dtype=np.float32))
-D = pt.from_array(np.full((B.shape[2], 25), 2, dtype=np.float32))
-
-# Declare the result to be a dense matrix.
-A = pt.tensor([B.shape[0], 25], rm)
-
-# Declare index vars.
-i, j, k, l = pt.get_index_vars(4)
-
-# Define the MTTKRP computation.
-A[i, j] = B[i, k, l] * D[l, j] * C[k, j]
-
-##########################################################################
-
-# Perform the MTTKRP computation and write the result to file.
-with tempfile.TemporaryDirectory() as test_dir:
- golden_file = os.path.join(_SCRIPT_PATH, "data/gold_A.tns")
- out_file = os.path.join(test_dir, "A.tns")
- pt.write(out_file, A)
- #
- # CHECK: Compare result True
- #
- print(f"Compare result {utils.compare_sparse_tns(golden_file, out_file)}")
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/test_SDDMM.py b/mlir/test/Integration/Dialect/SparseTensor/taco/test_SDDMM.py
deleted file mode 100644
index ef94ea9900fe496..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/test_SDDMM.py
+++ /dev/null
@@ -1,58 +0,0 @@
-# RUN: env SUPPORTLIB=%mlir_c_runner_utils %PYTHON %s | FileCheck %s
-
-import filecmp
-import numpy as np
-import os
-import sys
-import tempfile
-
-_SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
-sys.path.append(_SCRIPT_PATH)
-
-from tools import mlir_pytaco_api as pt
-from tools import testing_utils as utils
-
-i, j, k = pt.get_index_vars(3)
-
-# Set up dense matrices.
-A = pt.from_array(np.full((8, 8), 2.0, dtype=np.float32))
-B = pt.from_array(np.full((8, 8), 3.0, dtype=np.float32))
-
-# Set up sparse matrices.
-S = pt.tensor([8, 8], pt.format([pt.compressed, pt.compressed]))
-X = pt.tensor([8, 8], pt.format([pt.compressed, pt.compressed]))
-Y = pt.tensor([8, 8], pt.compressed) # alternative syntax works too
-
-S.insert([0, 7], 42.0)
-
-# Define the SDDMM kernel. Since this performs the reduction as
-# sum(k, S[i, j] * A[i, k] * B[k, j])
-# we only compute the intermediate dense matrix product that are actually
-# needed to compute the result, with proper asymptotic complexity.
-X[i, j] = S[i, j] * A[i, k] * B[k, j]
-
-# Alternative way to define SDDMM kernel. Since this performs the reduction as
-# sum(k, A[i, k] * B[k, j]) * S[i, j]
-# the MLIR lowering results in two separate tensor index expressions that are
-# fused prior to running the sparse compiler in order to guarantee proper
-# asymptotic complexity.
-Y[i, j] = A[i, k] * B[k, j] * S[i, j]
-
-expected = """; extended FROSTT format
-2 1
-8 8
-1 8 2016
-"""
-
-# Force evaluation of the kernels by writing out X and Y.
-with tempfile.TemporaryDirectory() as test_dir:
- x_file = os.path.join(test_dir, "X.tns")
- y_file = os.path.join(test_dir, "Y.tns")
- pt.write(x_file, X)
- pt.write(y_file, Y)
- #
- # CHECK: Compare result True True
- #
- x_data = utils.file_as_string(x_file)
- y_data = utils.file_as_string(y_file)
- print(f"Compare result {x_data == expected} {y_data == expected}")
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/test_SpMM.py b/mlir/test/Integration/Dialect/SparseTensor/taco/test_SpMM.py
deleted file mode 100644
index 02bbbc096e7a3ea..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/test_SpMM.py
+++ /dev/null
@@ -1,35 +0,0 @@
-# RUN: env SUPPORTLIB=%mlir_c_runner_utils %PYTHON %s | FileCheck %s
-
-import filecmp
-import numpy as np
-import os
-import sys
-import tempfile
-
-_SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
-sys.path.append(_SCRIPT_PATH)
-
-from tools import mlir_pytaco_api as pt
-from tools import testing_utils as utils
-
-# Define the CSR format.
-csr = pt.format([pt.dense, pt.compressed], [0, 1])
-
-# Read matrices A and B from file, infer size of output matrix C.
-A = pt.read(os.path.join(_SCRIPT_PATH, "data/A.mtx"), csr)
-B = pt.read(os.path.join(_SCRIPT_PATH, "data/B.mtx"), csr)
-C = pt.tensor([A.shape[0], B.shape[1]], csr)
-
-# Define the kernel.
-i, j, k = pt.get_index_vars(3)
-C[i, j] = A[i, k] * B[k, j]
-
-# Force evaluation of the kernel by writing out C.
-with tempfile.TemporaryDirectory() as test_dir:
- golden_file = os.path.join(_SCRIPT_PATH, "data/gold_C.tns")
- out_file = os.path.join(test_dir, "C.tns")
- pt.write(out_file, C)
- #
- # CHECK: Compare result True
- #
- print(f"Compare result {utils.compare_sparse_tns(golden_file, out_file)}")
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/test_SpMV.py b/mlir/test/Integration/Dialect/SparseTensor/taco/test_SpMV.py
deleted file mode 100644
index 2038a473ae53030..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/test_SpMV.py
+++ /dev/null
@@ -1,56 +0,0 @@
-# RUN: env SUPPORTLIB=%mlir_c_runner_utils %PYTHON %s | FileCheck %s
-
-import numpy as np
-import os
-import sys
-import tempfile
-
-_SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
-sys.path.append(_SCRIPT_PATH)
-
-from tools import mlir_pytaco_api as pt
-from tools import testing_utils as utils
-
-###### This PyTACO part is taken from the TACO open-source project. ######
-# See http://tensor-compiler.org/docs/scientific_computing/index.html.
-
-compressed = pt.compressed
-dense = pt.dense
-
-# Define formats for storing the sparse matrix and dense vectors.
-csr = pt.format([dense, compressed])
-dv = pt.format([dense])
-
-# Load a sparse matrix stored in the matrix market format) and store it
-# as a CSR matrix. The matrix in this test is a reduced version of the data
-# downloaded from here:
-# https://www.cise.ufl.edu/research/sparse/MM/Boeing/pwtk.tar.gz
-# In order to run the program using the matrix above, you can download the
-# matrix and replace this path to the actual path to the file.
-A = pt.read(os.path.join(_SCRIPT_PATH, "data/pwtk.mtx"), csr)
-
-# These two lines have been modified from the original program to use static
-# data to support result comparison.
-x = pt.from_array(np.full((A.shape[1],), 1, dtype=np.float32))
-z = pt.from_array(np.full((A.shape[0],), 2, dtype=np.float32))
-
-# Declare the result to be a dense vector
-y = pt.tensor([A.shape[0]], dv)
-
-# Declare index vars
-i, j = pt.get_index_vars(2)
-
-# Define the SpMV computation
-y[i] = A[i, j] * x[j] + z[i]
-
-##########################################################################
-
-# Perform the SpMV computation and write the result to file
-with tempfile.TemporaryDirectory() as test_dir:
- golden_file = os.path.join(_SCRIPT_PATH, "data/gold_y.tns")
- out_file = os.path.join(test_dir, "y.tns")
- pt.write(out_file, y)
- #
- # CHECK: Compare result True
- #
- print(f"Compare result {utils.compare_sparse_tns(golden_file, out_file)}")
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/test_Tensor.py b/mlir/test/Integration/Dialect/SparseTensor/taco/test_Tensor.py
deleted file mode 100644
index cd24e0dbb0a43ae..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/test_Tensor.py
+++ /dev/null
@@ -1,99 +0,0 @@
-# RUN: env SUPPORTLIB=%mlir_c_runner_utils %PYTHON %s | FileCheck %s
-
-import filecmp
-import numpy as np
-import os
-import sys
-import tempfile
-
-_SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
-sys.path.append(_SCRIPT_PATH)
-
-from tools import mlir_pytaco_api as pt
-from tools import testing_utils as utils
-
-i, j, k, l, m = pt.get_index_vars(5)
-
-# Set up scalar.
-alpha = pt.tensor(42.0)
-
-# Set up some sparse tensors with
diff erent dim annotations and ordering.
-S = pt.tensor([8, 8, 8], pt.format([pt.compressed, pt.dense, pt.compressed], [1, 0, 2]))
-X = pt.tensor(
- [8, 8, 8], pt.format([pt.compressed, pt.compressed, pt.compressed], [1, 0, 2])
-)
-S.insert([0, 0, 0], 2.0)
-S.insert([1, 1, 1], 3.0)
-S.insert([4, 4, 4], 4.0)
-S.insert([7, 7, 7], 5.0)
-
-X[i, j, k] = alpha[0] * S[i, j, k]
-
-# Set up tensors with a dense last dimension. This results in a full
-# enveloping storage of all last "rows" with one or more nonzeros.
-T = pt.tensor(
- [1, 2, 3, 4, 5],
- pt.format([pt.compressed, pt.compressed, pt.compressed, pt.compressed, pt.dense]),
-)
-Y = pt.tensor(
- [1, 2, 3, 4, 5],
- pt.format([pt.compressed, pt.compressed, pt.compressed, pt.compressed, pt.dense]),
-)
-T.insert([0, 1, 2, 3, 4], -2.0)
-
-Y[i, j, k, l, m] = alpha[0] * T[i, j, k, l, m]
-
-# Set up a sparse tensor and dense tensor with
diff erent access.
-U = pt.tensor([2, 3], pt.format([pt.compressed, pt.compressed], [1, 0]))
-Z = pt.tensor([3, 2], pt.format([pt.dense, pt.dense]))
-U.insert([1, 2], 3.0)
-
-Z[i, j] = alpha[0] * U[j, i]
-
-x_expected = """; extended FROSTT format
-3 4
-8 8 8
-1 1 1 84
-2 2 2 126
-5 5 5 168
-8 8 8 210
-"""
-
-y_expected = """; extended FROSTT format
-5 5
-1 2 3 4 5
-1 2 3 4 1 0
-1 2 3 4 2 0
-1 2 3 4 3 0
-1 2 3 4 4 0
-1 2 3 4 5 -84
-"""
-
-z_expected = """; extended FROSTT format
-2 6
-3 2
-1 1 0
-1 2 0
-2 1 0
-2 2 0
-3 1 0
-3 2 126
-"""
-
-# Force evaluation of the kernel by writing out X.
-with tempfile.TemporaryDirectory() as test_dir:
- x_file = os.path.join(test_dir, "X.tns")
- pt.write(x_file, X)
- y_file = os.path.join(test_dir, "Y.tns")
- pt.write(y_file, Y)
- z_file = os.path.join(test_dir, "Z.tns")
- pt.write(z_file, Z)
- #
- # CHECK: Compare result True True True
- #
- x_data = utils.file_as_string(x_file)
- y_data = utils.file_as_string(y_file)
- z_data = utils.file_as_string(z_file)
- print(
- f"Compare result {x_data == x_expected} {y_data == y_expected} {z_data == z_expected}"
- )
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/test_scalar_tensor_algebra.py b/mlir/test/Integration/Dialect/SparseTensor/taco/test_scalar_tensor_algebra.py
deleted file mode 100644
index 206ffa9316d48f4..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/test_scalar_tensor_algebra.py
+++ /dev/null
@@ -1,36 +0,0 @@
-# RUN: env SUPPORTLIB=%mlir_c_runner_utils %PYTHON %s | FileCheck %s
-
-import numpy as np
-import os
-import sys
-
-_SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
-sys.path.append(_SCRIPT_PATH)
-from tools import mlir_pytaco_api as pt
-
-compressed = pt.compressed
-
-i, j = pt.get_index_vars(2)
-A = pt.tensor([2, 3])
-S = pt.tensor(3) # S is a scalar tensor.
-B = pt.tensor([2, 3], compressed)
-A.insert([0, 1], 10)
-A.insert([1, 2], 40)
-
-# Use [0] to index the scalar tensor.
-B[i, j] = A[i, j] * S[0]
-
-indices, values = B.get_coordinates_and_values()
-passed = np.array_equal(indices, [[0, 1], [1, 2]])
-passed += np.array_equal(values, [30.0, 120.0])
-
-# Sum all the values in A.
-S[0] = A[i, j]
-passed += S.get_scalar_value() == 50.0
-
-indices, values = S.get_coordinates_and_values()
-passed += len(indices) == 0
-passed += values == 50.0
-
-# CHECK: Number of passed: 5
-print("Number of passed:", passed)
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/test_simple_tensor_algebra.py b/mlir/test/Integration/Dialect/SparseTensor/taco/test_simple_tensor_algebra.py
deleted file mode 100644
index 7ceb8585a7e0cf2..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/test_simple_tensor_algebra.py
+++ /dev/null
@@ -1,61 +0,0 @@
-# RUN: env SUPPORTLIB=%mlir_c_runner_utils %PYTHON %s | FileCheck %s
-
-import numpy as np
-import os
-import sys
-
-_SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
-sys.path.append(_SCRIPT_PATH)
-from tools import mlir_pytaco_api as pt
-
-compressed = pt.compressed
-dense = pt.dense
-
-# Ensure that we can run an unmodified PyTACO program with a simple tensor
-# algebra expression using tensor index notation, and produce the expected
-# result.
-i, j = pt.get_index_vars(2)
-A = pt.tensor([2, 3])
-B = pt.tensor([2, 3])
-C = pt.tensor([2, 3])
-D = pt.tensor([2, 3], compressed)
-A.insert([0, 1], 10)
-A.insert([1, 2], 40)
-B.insert([0, 0], 20)
-B.insert([1, 2], 30)
-C.insert([0, 1], 5)
-C.insert([1, 2], 7)
-D[i, j] = A[i, j] + B[i, j] - C[i, j]
-
-indices, values = D.get_coordinates_and_values()
-passed = np.array_equal(indices, [[0, 0], [0, 1], [1, 2]])
-passed += np.allclose(values, [20.0, 5.0, 63.0])
-
-# PyTACO doesn't allow the use of index values, but MLIR-PyTACO removes this
-# restriction.
-E = pt.tensor([3])
-E[i] = i
-indices, values = E.get_coordinates_and_values()
-passed += np.array_equal(indices, [[0], [1], [2]])
-passed += np.allclose(values, [0.0, 1.0, 2.0])
-
-F = pt.tensor([3])
-G = pt.tensor([3])
-F.insert([0], 10)
-F.insert([2], 40)
-G[i] = F[i] + i
-indices, values = G.get_coordinates_and_values()
-passed += np.array_equal(indices, [[0], [1], [2]])
-passed += np.allclose(values, [10.0, 1.0, 42.0])
-
-H = pt.tensor([3])
-I = pt.tensor([3])
-H.insert([0], 10)
-H.insert([2], 40)
-I[i] = H[i] * i
-indices, values = I.get_coordinates_and_values()
-passed += np.array_equal(indices, [[0], [2]])
-passed += np.allclose(values, [0.0, 80.0])
-
-# CHECK: Number of passed: 8
-print("Number of passed:", passed)
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/test_tensor_complex.py b/mlir/test/Integration/Dialect/SparseTensor/taco/test_tensor_complex.py
deleted file mode 100644
index b0fed50f8b5dbe3..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/test_tensor_complex.py
+++ /dev/null
@@ -1,31 +0,0 @@
-# RUN: env SUPPORTLIB=%mlir_c_runner_utils %PYTHON %s | FileCheck %s
-import numpy as np
-import os
-import sys
-
-_SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
-sys.path.append(_SCRIPT_PATH)
-from tools import mlir_pytaco_api as pt
-
-compressed = pt.compressed
-
-passed = 0
-all_types = [pt.complex64, pt.complex128]
-for t in all_types:
- i, j = pt.get_index_vars(2)
- A = pt.tensor([2, 3], dtype=t)
- B = pt.tensor([2, 3], dtype=t)
- C = pt.tensor([2, 3], compressed, dtype=t)
- A.insert([0, 1], 10 + 20j)
- A.insert([1, 2], 40 + 0.5j)
- B.insert([0, 0], 20)
- B.insert([1, 2], 30 + 15j)
- C[i, j] = A[i, j] + B[i, j]
-
- indices, values = C.get_coordinates_and_values()
- passed += isinstance(values[0], t.value)
- passed += np.array_equal(indices, [[0, 0], [0, 1], [1, 2]])
- passed += np.allclose(values, [20, 10 + 20j, 70 + 15.5j])
-
-# CHECK: Number of passed: 6
-print("Number of passed:", passed)
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/test_tensor_types.py b/mlir/test/Integration/Dialect/SparseTensor/taco/test_tensor_types.py
deleted file mode 100644
index 4ba2836dd4616b8..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/test_tensor_types.py
+++ /dev/null
@@ -1,33 +0,0 @@
-# RUN: env SUPPORTLIB=%mlir_c_runner_utils %PYTHON %s | FileCheck %s
-
-import numpy as np
-import os
-import sys
-
-_SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
-sys.path.append(_SCRIPT_PATH)
-from tools import mlir_pytaco_api as pt
-
-compressed = pt.compressed
-dense = pt.dense
-
-passed = 0
-all_types = [pt.int8, pt.int16, pt.int32, pt.int64, pt.float16, pt.float32, pt.float64]
-for t in all_types:
- i, j = pt.get_index_vars(2)
- A = pt.tensor([2, 3], dtype=t)
- B = pt.tensor([2, 3], dtype=t)
- C = pt.tensor([2, 3], compressed, dtype=t)
- A.insert([0, 1], 10)
- A.insert([1, 2], 40)
- B.insert([0, 0], 20)
- B.insert([1, 2], 30)
- C[i, j] = A[i, j] + B[i, j]
-
- indices, values = C.get_coordinates_and_values()
- passed += isinstance(values[0], t.value)
- passed += np.array_equal(indices, [[0, 0], [0, 1], [1, 2]])
- passed += np.allclose(values, [20.0, 10.0, 70.0])
-
-# CHECK: Number of passed: 21
-print("Number of passed:", passed)
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/test_tensor_unary_ops.py b/mlir/test/Integration/Dialect/SparseTensor/taco/test_tensor_unary_ops.py
deleted file mode 100644
index 6fcb41e30eea32c..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/test_tensor_unary_ops.py
+++ /dev/null
@@ -1,40 +0,0 @@
-# RUN: env SUPPORTLIB=%mlir_c_runner_utils %PYTHON %s | FileCheck %s
-
-import numpy as np
-import os
-import sys
-
-_SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
-sys.path.append(_SCRIPT_PATH)
-from tools import mlir_pytaco_api as pt
-
-i, j = pt.get_index_vars(2)
-A = pt.tensor([2, 3])
-B = pt.tensor([2, 3])
-A.insert([0, 1], 10.3)
-A.insert([1, 1], 40.7)
-A.insert([0, 2], -11.3)
-A.insert([1, 2], -41.7)
-
-B[i, j] = abs(A[i, j])
-indices, values = B.get_coordinates_and_values()
-passed = np.array_equal(indices, [[0, 1], [0, 2], [1, 1], [1, 2]])
-passed += np.allclose(values, [10.3, 11.3, 40.7, 41.7])
-
-B[i, j] = pt.ceil(A[i, j])
-indices, values = B.get_coordinates_and_values()
-passed += np.array_equal(indices, [[0, 1], [0, 2], [1, 1], [1, 2]])
-passed += np.allclose(values, [11, -11, 41, -41])
-
-B[i, j] = pt.floor(A[i, j])
-indices, values = B.get_coordinates_and_values()
-passed += np.array_equal(indices, [[0, 1], [0, 2], [1, 1], [1, 2]])
-passed += np.allclose(values, [10, -12, 40, -42])
-
-B[i, j] = -A[i, j]
-indices, values = B.get_coordinates_and_values()
-passed += np.array_equal(indices, [[0, 1], [0, 2], [1, 1], [1, 2]])
-passed += np.allclose(values, [-10.3, 11.3, -40.7, 41.7])
-
-# CHECK: Number of passed: 8
-print("Number of passed:", passed)
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/test_true_dense_tensor_algebra.py b/mlir/test/Integration/Dialect/SparseTensor/taco/test_true_dense_tensor_algebra.py
deleted file mode 100644
index 78bce344e3b6f0f..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/test_true_dense_tensor_algebra.py
+++ /dev/null
@@ -1,22 +0,0 @@
-# RUN: env SUPPORTLIB=%mlir_c_runner_utils %PYTHON %s | FileCheck %s
-
-import numpy as np
-import os
-import sys
-
-_SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
-sys.path.append(_SCRIPT_PATH)
-from tools import mlir_pytaco_api as pt
-
-i, j = pt.get_index_vars(2)
-# Both tensors are true dense tensors.
-A = pt.from_array(np.full([2, 3], 1, dtype=np.float64))
-B = pt.from_array(np.full([2, 3], 2, dtype=np.float64))
-# Define the result tensor as a true dense tensor. The parameter is_dense=True
-# is an MLIR-PyTACO extension.
-C = pt.tensor([2, 3], dtype=pt.float64, is_dense=True)
-
-C[i, j] = A[i, j] + B[i, j]
-
-# CHECK: [3. 3. 3. 3. 3. 3.]
-print(C.to_array().reshape(6))
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/tools/lit.local.cfg b/mlir/test/Integration/Dialect/SparseTensor/taco/tools/lit.local.cfg
deleted file mode 100644
index 650ca33613cc6c0..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/tools/lit.local.cfg
+++ /dev/null
@@ -1,2 +0,0 @@
-# Files in this directory are tools, not tests.
-config.unsupported = True
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/tools/mlir_pytaco.py b/mlir/test/Integration/Dialect/SparseTensor/taco/tools/mlir_pytaco.py
deleted file mode 100644
index c8cb77086ea34f3..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/tools/mlir_pytaco.py
+++ /dev/null
@@ -1,2279 +0,0 @@
-# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-# See https://llvm.org/LICENSE.txt for license information.
-# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-
-"""Experimental MLIR-PyTACO with sparse tensor support.
-
-See http://tensor-compiler.org/ for TACO tensor compiler.
-
-This module implements the Python classes for PyTACO index notation. These
-include classes for data types, tensor dimension formats (aka mode formats),
-tensor dimension orderings (aka mode ordering), tensor storage formats, and
-tensors.
-
-The PyTACO API doesn't follow the naming conversion required by the style guide
-for this module. As such, we first implement the supporting classes and routines
-following the style guide, and then define the type aliases and constants to
-support the PyTACO API in the pytaco_api module.
-"""
-
-from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, Union
-
-import abc
-import ctypes
-import dataclasses
-import enum
-import numpy as np
-import functools
-import operator
-import os
-import threading
-
-# Import MLIR related modules.
-from mlir import execution_engine
-from mlir import ir
-from mlir import runtime
-from mlir.dialects import arith
-from mlir.dialects import bufferization
-from mlir.dialects import builtin
-from mlir.dialects import func
-from mlir.dialects import linalg
-from mlir.dialects import sparse_tensor
-from mlir.dialects import tensor
-from mlir.dialects.linalg.opdsl import lang
-
-from . import mlir_pytaco_utils as utils
-
-# TACO naming prefixes.
-_TACO_INDEX_PREFIX = "i"
-_TACO_TENSOR_PREFIX = "A"
-
-# Bitwidths for positions and coordinates.
-_POS_WIDTH = 0
-_CRD_WIDTH = 0
-# The entry point to the JIT compiled program.
-_ENTRY_NAME = "main"
-
-# Type aliases for type annotation.
-_UnaryOp = Callable[[Any], Any]
-_BinaryOp = Callable[[Any, Any], Any]
-_ExprVisitor = Callable[..., None]
-_ExprInfoDict = Dict["IndexExpr", "_ExprInfo"]
-_LogicalOp = Callable[[bool, bool], bool]
-_ModeFormatOp = Callable[["ModeFormat", "ModeFormat"], "ModeFormat"]
-_SubtreeLeafChecker = Optional[Callable[..., bool]]
-
-
-class Type(enum.Enum):
- """The data types supported by TACO.
-
- We use numpy data types to implement the enum data types.
- """
-
- INT8 = np.int8
- INT16 = np.int16
- INT32 = np.int32
- INT64 = np.int64
- FLOAT16 = np.float16
- FLOAT32 = np.float32
- FLOAT64 = np.float64
- COMPLEX64 = np.complex64
- COMPLEX128 = np.complex128
-
-
-# All floating point type enums.
-_FLOAT_TYPES = (Type.FLOAT16, Type.FLOAT32, Type.FLOAT64)
-# All integral type enums.
-_INT_TYPES = (Type.INT8, Type.INT16, Type.INT32, Type.INT64)
-# All complex type enums.
-_COMPLEX_TYPES = (Type.COMPLEX64, Type.COMPLEX128)
-# Type alias for any numpy type used to implement the runtime support for the
-# enum data types.
-_AnyRuntimeType = Union[
- np.int8,
- np.int16,
- np.int32,
- np.int64,
- np.float16,
- np.float32,
- np.float64,
- np.complex64,
- np.complex128,
-]
-
-
- at dataclasses.dataclass(frozen=True)
-class DType:
- """The data type class.
-
- We support the TACO API dtype class with an alias of this class.
-
- The following methods are defined by the TACO API:
- is_float: Returns whether the data type represents a floating point value.
- is_int: Returns whether the data type represents an integral value.
-
- Attributes:
- kind: A Type enum representing the data type.
- value: The numpy data type for the TACO data type.
- """
-
- kind: Type = Type.FLOAT32
-
- def is_float(self) -> bool:
- """Returns whether the data type represents a floating point value."""
- return self.kind in _FLOAT_TYPES
-
- def is_int(self) -> bool:
- """Returns whether the data type represents an integral value."""
- return self.kind in _INT_TYPES
-
- def is_complex(self) -> bool:
- """Returns whether the data type represents a complex value."""
- return self.kind in _COMPLEX_TYPES
-
- @property
- def value(self) -> _AnyRuntimeType:
- """Returns the numpy dtype for the data type."""
- return self.kind.value
-
-
-def _dtype_to_mlir_str(dtype: DType) -> str:
- """Returns the MLIR string for the given dtype."""
- dtype_to_str = {
- Type.INT16: "i8",
- Type.INT16: "i16",
- Type.INT32: "i32",
- Type.INT64: "i64",
- Type.FLOAT16: "f16",
- Type.FLOAT32: "f32",
- Type.FLOAT64: "f64",
- Type.COMPLEX64: "complex<f32>",
- Type.COMPLEX128: "complex<f64>",
- }
- return dtype_to_str[dtype.kind]
-
-
-def _nptype_to_taco_type(ty: np.dtype) -> DType:
- """Returns the TACO type for the given numpy type."""
- nptype_to_dtype = {
- np.int8: Type.INT8,
- np.int16: Type.INT16,
- np.int32: Type.INT32,
- np.int64: Type.INT64,
- np.float16: Type.FLOAT16,
- np.float32: Type.FLOAT32,
- np.float64: Type.FLOAT64,
- np.complex64: Type.COMPLEX64,
- np.complex128: Type.COMPLEX128,
- }
- return DType(nptype_to_dtype[ty])
-
-
-def _mlir_type_from_taco_type(dtype: DType) -> ir.Type:
- """Returns the MLIR type corresponding to the given TACO type."""
- dtype_to_irtype = {
- Type.INT8: ir.IntegerType.get_signless(8),
- Type.INT16: ir.IntegerType.get_signless(16),
- Type.INT32: ir.IntegerType.get_signless(32),
- Type.INT64: ir.IntegerType.get_signless(64),
- Type.FLOAT16: ir.F16Type.get(),
- Type.FLOAT32: ir.F32Type.get(),
- Type.FLOAT64: ir.F64Type.get(),
- Type.COMPLEX64: ir.ComplexType.get(ir.F32Type.get()),
- Type.COMPLEX128: ir.ComplexType.get(ir.F64Type.get()),
- }
- return dtype_to_irtype[dtype.kind]
-
-
-def _ctype_pointer_from_array(array: np.ndarray) -> ctypes.pointer:
- """Returns the ctype pointer for the given numpy array."""
- return ctypes.pointer(ctypes.pointer(runtime.get_ranked_memref_descriptor(array)))
-
-
-class ModeFormat(enum.Enum):
- """The tensor dimension storage format class.
-
- We support the TACO API mode_format class with an alias of this class.
-
- In TACO, a tensor dimension is called a mode and the storage format for a
- tensor dimension is called a mode format.
- """
-
- DENSE = sparse_tensor.DimLevelType.dense
- COMPRESSED = sparse_tensor.DimLevelType.compressed
-
-
-def _mode_format_operation(a: ModeFormat, b: ModeFormat, op: _LogicalOp) -> ModeFormat:
- """Implements the given operator on ModeFormat."""
- return (
- ModeFormat.COMPRESSED
- if op(a == ModeFormat.COMPRESSED, b == ModeFormat.COMPRESSED)
- else ModeFormat.DENSE
- )
-
-
-def _mode_format_estimator(op: _BinaryOp) -> _ModeFormatOp:
- """Produces a ModeFormat operator for the given binary operator.
-
- The ModeFormat operator is used as a heuristic to derive the destination
- dimension sparsity from the source dimension sparsity. In particular, if the
- binary operator produces a disjunction of the zero values from its source
- operands, such as the MUL operator, we return a ModeFormat operator that
- uses operator.or_. That is, we estimate that a dimension for the MUL
- operation result to be sparse if either of its source operands is sparse.
-
- On the other hand, if the binary operator produces a conjunction of the
- zero values from its source operands, such as the ADD operator, we return
- a ModeFormat operator that uses operator.and_. In this case, we estimate
- that a dimension for the ADD operation result to be sparse if both of its
- source operands are sparse.
-
- Args:
- op: A _BinaryOp object representing a supporting operator on tensors.
-
- Returns:
- A ModeFormatOp for estimating the destination dimension sparsity from
- the source dimension sparsity.
- """
- conjunction = functools.partial(_mode_format_operation, op=operator.and_)
- disjunction = functools.partial(_mode_format_operation, op=operator.or_)
- return conjunction if op(0, 1) != 0 else disjunction
-
-
-def _all_instance_of(collection: Iterable, cls: Any) -> bool:
- """Returns true if all elements of the iterable is an instance of cls."""
- return all(isinstance(e, cls) for e in collection)
-
-
-def _identity_ordering(rank: int) -> List[int]:
- """Returns the identity ordering for tensor of given rank."""
- return list(range(rank))
-
-
- at dataclasses.dataclass(frozen=True)
-class ModeOrdering:
- """The tensor dimension ordering class.
-
- We support the TACO API mode_ordering class with an alias of this class.
-
- Attributes:
- ordering: A list of integers representing the ordering of the tensor
- dimensions.
- """
-
- ordering: List[int]
-
- def __post_init__(self) -> None:
- """Verifies the value in ordering.
-
- Raises:
- ValueError: If ordering is not a list of integers.
- """
- if not isinstance(self.ordering, list) or not _all_instance_of(
- self.ordering, int
- ):
- raise ValueError("Ordering must be a list of integers: " f"{self.ordering}")
- # Check that ordering is a permutation of the dimension numbers.
- if sorted(self.ordering) != _identity_ordering(self.rank()):
- raise ValueError(
- f"Invalid ordering: {self.ordering} != "
- f"permutation{_identity_ordering(self.rank())}."
- )
-
- def rank(self) -> int:
- """Returns the number of dimensions represented by the ordering."""
- return len(self.ordering)
-
-
- at dataclasses.dataclass(frozen=True)
-class ModeFormatPack:
- """The tensor dimension format class.
-
- We support the TACO API mode_format_pack class with an alias of this class.
-
- The storage format of a tensor contains one mode_format for each tensor
- dimension.
-
- Attributes:
- formats: A list of ModeFormat representing the storage format for each of
- the tensor dimension.
- """
-
- formats: List[ModeFormat]
-
- def __post_init__(self) -> None:
- """Verifies the value in formats.
-
- Raises:
- ValueError: If formats is not a list of ModeFormats.
- """
- if not isinstance(self.formats, list) or not _all_instance_of(
- self.formats, ModeFormat
- ):
- raise ValueError("Formats must be a list of ModeFormat: " f"{self.formats}")
-
- def rank(self) -> int:
- """Returns the number of dimensions represented by the format pack."""
- return len(self.formats)
-
-
- at dataclasses.dataclass
-class Format:
- """The tensor format class defined by the TACO API.
-
- Attributes:
- format_pack: A ModeFormatPack representing the storage format for the tensor
- dimensions.
- ordering: A ModeOrdering representing the tensor dimension ordering in the
- storage.
- """
-
- format_pack: ModeFormatPack
- ordering: Optional[ModeOrdering] = None
-
- def __post_init__(self) -> None:
- """Verifies and fixes up the values in format_pack and ordering.
-
- Verifies and fixes up the values in format_pack and ordering to supports the
- initializer syntax defined by the TACO API. If format_pack is a list of
- ModeFormat, replaces it with ModeFormatPack constructed from the list. If
- ordering is not provided, set ordering to the natural ordering for the rank
- corresponding to format_pack.
-
- Raises:
- ValueError: If format_pack is not an instance of ModeFormatPack or if
- ordering is not an instance of ModeOrdering.
- """
- if isinstance(self.format_pack, list):
- if not _all_instance_of(self.format_pack, ModeFormat):
- raise ValueError(f"Expected a list of ModeFormat: {self.format_pack}")
- self.format_pack = ModeFormatPack(self.format_pack)
- if not isinstance(self.format_pack, ModeFormatPack):
- raise ValueError(f"Expected ModeFormatpack: {self.format_pack}")
-
- if self.ordering is None:
- self.ordering = ModeOrdering(list(range(self.rank())))
- if isinstance(self.ordering, list):
- if not _all_instance_of(self.ordering, int):
- raise ValueError(f"Expected a list of integer: {self.ordering}")
- self.ordering = ModeOrdering(self.ordering)
- if not isinstance(self.ordering, ModeOrdering):
- raise ValueError(f"Expected ModeOrdering: {self.ordering}")
-
- if self.format_pack.rank() != self.ordering.rank():
- raise ValueError(
- "Inconsistent ModeFormatPack and ModeOrdering: "
- f"len({self.format_pack}) != "
- f"len({self.ordering})"
- )
-
- def rank(self) -> int:
- """Returns the number of dimensions represented by the format."""
- return self.format_pack.rank()
-
- def get_permutation_and_sparsity(self) -> Tuple[np.ndarray, np.ndarray]:
- """Constructs the numpy arrays for the permutation and sparsity."""
- perm = np.array(self.ordering.ordering, dtype=np.ulonglong)
- a = [f.value for f in self.format_pack.formats]
- sparse = np.array(a, dtype=np.uint8)
- return (perm, sparse)
-
- def mlir_tensor_attr(self) -> Optional[sparse_tensor.EncodingAttr]:
- """Constructs the MLIR attributes for the tensor format."""
- order = (
- range(self.rank()) if (self.ordering is None) else self.ordering.ordering
- )
- mlir_storage_format = [f.value for f in self.format_pack.formats]
- return sparse_tensor.EncodingAttr.get(
- mlir_storage_format,
- ir.AffineMap.get_permutation(order),
- _POS_WIDTH,
- _CRD_WIDTH,
- )
-
-
-def _make_format(
- formats: List[ModeFormat], ordering: Optional[List[int]] = None
-) -> Format:
- """Constructs a format from a list of ModeFormat and an optional ordering.
-
- Args:
- formats: A list of ModeFormat, one for each dimension of a tensor.
- ordering: An optional list of integer, for the ordering of the tensor
- dimensions. When an ordering is not given, the identity ordering is used.
-
- Returns:
- A tensor format object.
-
- Raises:
- ValueError: If formats is not a list of ModeFormat or the length of formats
- is not consistent with the len of ordering.
- """
- ordering = ordering or _identity_ordering(len(formats))
- return Format(ModeFormatPack(formats), ModeOrdering(ordering))
-
-
-class IndexExpr(abc.ABC):
- """The index notation base class.
-
- We support the TACO API index_expression class with an alias of this class.
- """
-
- def _verify_operand_and_build_expr(self, rhs, op: _BinaryOp) -> "_BinaryExpr":
- """Verifies the RHS operand and returns a binary expression.
-
- Args:
- rhs: The RHS of the binary operation, which could be any Python object
- from user inputs.
- op: A _BinaryOp object representing the binary operator.
-
- Raises:
- ValueError: If rhs is not an IndexExpr.
- """
- if not isinstance(rhs, IndexExpr):
- raise ValueError(f"Expected IndexExpr: {rhs}")
- return _BinaryExpr(op, self, rhs)
-
- def _build_unary_expr(self, op: _UnaryOp) -> "_UnaryExpr":
- """Build a unary expression.
-
- Args:
- op: A _UnaryOp object representing the unary operation.
- """
- return _UnaryExpr(op, self)
-
- def __add__(self, rhs) -> "_BinaryExpr":
- """Defines the operator +.
-
- Args:
- rhs: The value being added, which could be any Python object from user
- inputs.
-
- Returns:
- A _BinaryExpr object representing the operation.
-
- Raises:
- ValueError: If rhs is not an IndexExpr.
- """
- return self._verify_operand_and_build_expr(rhs, operator.add)
-
- def __mul__(self, rhs) -> "_BinaryExpr":
- """Defines the operator *.
-
- Args:
- rhs: The value being multiplied, which could be any Python object from
- user inputs.
-
- Returns:
- A _BinaryExpr object representing the operation.
-
- Raises:
- ValueError: If rhs is not an IndexExpr.
- """
- return self._verify_operand_and_build_expr(rhs, operator.mul)
-
- def __abs__(self) -> "_UnaryExpr":
- """Defines the operator abs.
-
- Returns:
- A _UnaryExpr object representing the operation.
- """
- return self._build_unary_expr(operator.abs)
-
- def __neg__(self) -> "_UnaryExpr":
- """Defines the operator neg.
-
- Returns:
- A _UnaryExpr object representing the operation.
- """
- return self._build_unary_expr(operator.neg)
-
- def __sub__(self, rhs) -> "_BinaryExpr":
- """Defines the operator -.
-
- Args:
- rhs: The value being subtracted, which could be any Python object from
- user inputs.
-
- Returns:
- A _BinaryExpr object representing the operation.
-
- Raises:
- ValueError: If rhs is not an IndexExpr.
- """
- return self._verify_operand_and_build_expr(rhs, operator.sub)
-
- @abc.abstractmethod
- def _visit(
- self, func: _ExprVisitor, args, *, leaf_checker: _SubtreeLeafChecker = None
- ) -> None:
- """A post-order visitor.
-
- Args:
- func: A callable applied to each node in the expression tree.
- args: The variable-length arguments passed to the callable. These
- arguments are grouped as an iterable and will be unpacked before passing
- to the callable. This is to enable the keyword argument only syntax
- after this argument.
- leaf_checker: A callable object to identify nodes that should be treated
- as leaf nodes to support partial tree visiting.
- """
- pass
-
- @abc.abstractmethod
- def _emit_expression(
- self,
- expr_to_opnd: Dict["IndexExpr", lang.OperandDef],
- expr_to_info: _ExprInfoDict,
- ) -> lang.ScalarExpression:
- """Emits MLIR for the expression tree.
-
- Args:
- expr_to_opnd: A dictionary for looking up structured op input operands for
- the input nodes of the structured op.
- expr_to_info: A dictionary for looking up code generation information for
- expressions.
-
- Returns:
- A linalg dialect ScalarExpression for the expression.
- """
- pass
-
- @abc.abstractmethod
- def dtype(self) -> DType:
- """Returns the data type for the result of the expression."""
- pass
-
- def _emit_structured_op(self, expr_to_info: _ExprInfoDict) -> None:
- """Emits a structured op in the linalg dialect for the expression tree.
-
- We define a DefineOpcallable in the domain specific language for the linalg
- dialect and execute the callable to generate the structured op. Self is the
- root of the expression tree for the structured op.
-
- Args:
- expr_to_info: A dictionary for looking up code generation information for
- expressions.
- """
- op_info = expr_to_info[self].structop_info
- op_name = op_info.dst_name
- op_def = lang.LinalgOpDef(name=op_name)
- op_callable = lang.DefinedOpCallable(op_name, op_def)
-
- # Collect the input expression nodes for the structured op.
- expr_inputs = []
- self._visit(
- _gather_structured_op_input,
- (self, expr_to_info, expr_inputs),
- leaf_checker=_is_structured_op_leaf,
- )
-
- # Create a linalg structured op operand for each input expression node and
- # build a dictionary for looking up the information.
- expr_to_input_opnd = {
- e: _emit_structured_op_input(e, expr_to_info, op_def) for e in expr_inputs
- }
-
- # Emit the expression tree, which produces the value assigned to the
- # destination tensor.
- value = self._emit_expression(expr_to_input_opnd, expr_to_info)
- # Emit the structured op representation for the destination tensor.
- dst_opnd = _emit_operand(
- op_def,
- op_info.dst_indices,
- op_info.dst_name,
- lang.OperandKind.OUTPUT_TENSOR,
- )
- dst_dim_syms = _mlir_dimensions_from_index_vars(op_info.dst_indices)
- dst_use = lang.TensorUse(dst_opnd, dst_dim_syms)
-
- expr_info = expr_to_info[self]
- # If the structured op reduces some indices, explicitly represent the
- # reduction. This is done by generating a ReduceFn for the dimensions being
- # reduced in the linalg dialect and calling the function with the value
- # being reduced. We only support add reduction currently.
- if expr_info.reduce_indices:
- reduce_dims = _mlir_dimensions_from_index_vars(expr_info.reduce_indices)
- value = lang.ReduceFn.add[reduce_dims](value)
-
- # Emit the assignment as a comprehension in the linalg dialect.
- comp = lang.Comprehension((dst_use, value))
- op_def.comprehensions.append(comp)
-
- # The structured op in the linalg dialect requires an explicit
- # initialization for the destination tensor. Emit MLIR to initialize the
- # destination tensor.
- init = op_info.emit_tensor_init()
-
- # Collect MLIR values for the linalg input operands, with the assumption
- # that dictionary preserves the insertion order.
- args = [
- expr_to_info[expr].mlir_value for expr, opnd in expr_to_input_opnd.items()
- ]
- # Execute the DefineOpcallable object for the linalg dialect operation to
- # emit MLIR for the linalg structured op.
- expr_info.mlir_value = op_callable(*args, outs=[init])
-
- def _identify_structured_ops(
- self,
- expr_to_info: _ExprInfoDict,
- dst: "Tensor",
- dst_indices: Tuple["IndexVar", ...],
- ) -> List["IndexExpr"]:
- """Returns expression nodes for the roots of the identified structured ops.
-
- A structured op in the linalg dialect only supports reduction performed on
- the whole expression. If the expression tree contains reduction that are
- performed on part of the expression tree, the expression tree needs to be
- implemented with multiple structured ops. This routine identifies all the
- expression nodes that contain reduction as the root of structured ops in the
- linalg dialect.
-
- Args:
- expr_to_info: A dictionary for looking up code generation information for
- expressions.
- dst: A destination Tensor that accepts the value of the expression tree.
- dst_indices: The indices used by the destination index expression.
-
- Returns:
- An ordered list of IndexExpr for the root expressions of the structured
- ops, where child expressions go before parent expressions that use their
- results.
- """
- reduce_indices = tuple(set(expr_to_info[self].src_indices) - set(dst_indices))
- for reduce_index in reduce_indices:
- _mark_structured_op_root(self, reduce_index, expr_to_info)
-
- self._visit(_accumulate_reduce_indices, (expr_to_info,))
- structop_roots = []
- self._visit(_gather_structured_op, (expr_to_info, structop_roots))
-
- # Handle the root of the top level expression.
- if not structop_roots or structop_roots[-1] != self:
- # The top level expression is not a reduction. Add the top level
- # expression as a structured op root.
- structop_roots.append(self)
-
- # Use user specified information for the destination tensor to build an
- # _StructOpInfo for the top level expression.
- expr_to_info[self].structop_info = _StructOpInfo(
- dst_indices, tuple(dst.shape), dst.dtype, dst.name, dst.format
- )
-
- return structop_roots
-
- def _validate_and_collect_expr_info(
- self,
- dst: "Tensor",
- dst_indices: Tuple["IndexVar", ...],
- ) -> _ExprInfoDict:
- """Propagates expression information for validation.
-
- Propagates the indices used by child expression nodes to parent expression
- nodes. Also collects and validates the sizes for the dimensions
- corresponding to the indices.
-
- Args:
- dst: A destination Tensor that accepts the value of the expression tree.
- dst_indices: The indices used by the destination index expression.
-
- Raises:
- ValueError if there is any inconsistency in indices or dimensional
- values.
-
- Returns:
- A dictionary of (IndexExpr, _ExprInfo).
- """
- expr_to_info = {}
- # Validate the expression tree and construct expression information.
- self._visit(_validate_and_collect_expr_info, (expr_to_info,))
-
- # Validate the destination dimension information.
- info = expr_to_info[self]
- index_to_dim_info = {i: d for i, d in zip(info.src_indices, info.dim_infos)}
- for (
- i,
- d,
- ) in zip(dst_indices, dst.shape):
- if i not in index_to_dim_info:
- raise ValueError(
- "Destination IndexVar not used in the " f"source expression: {i}"
- )
- else:
- if d != index_to_dim_info[i].dim and index_to_dim_info[i].dim != -1:
- raise ValueError(
- f"Inconsistent destination dimension for {i}: "
- f"{d} vs {index_to_dim_info[i].dim}"
- )
-
- return expr_to_info
-
- def _emit_assignment(
- self,
- module: ir.Module,
- dst: "Tensor",
- dst_indices: Tuple["IndexVar", ...],
- expr_to_info: _ExprInfoDict,
- input_accesses: List["Access"],
- ) -> None:
- """Emits an MLIR function for assigning the expression to a tensor."""
- input_types = [a.tensor.mlir_tensor_type() for a in input_accesses]
-
- # Build the kernel for the operations.
- with ir.InsertionPoint(module.body):
-
- @func.FuncOp.from_py_func(*input_types, name=_ENTRY_NAME)
- def linalg_funcop(*args):
- # Set up the mapping from the Access nodes to their MLIR values.
- for e, mlir in zip(input_accesses, args):
- expr_to_info[e].mlir_value = mlir
-
- # Emit structured ops in the linalg dialect to implement the assignment.
- for structop_root in self._identify_structured_ops(
- expr_to_info, dst, dst_indices
- ):
- structop_root._emit_structured_op(expr_to_info)
- dst._record_stats(expr_to_info[structop_root].structop_info)
-
- # The function returns the MLIR value of the root expression.
- return expr_to_info[self].mlir_value
-
- linalg_funcop.func_op.attributes[
- "llvm.emit_c_interface"
- ] = ir.UnitAttr.get()
-
- def get_input_accesses(self) -> List["Access"]:
- """Compute the list of input accesses for the expression."""
- input_accesses = []
- self._visit(_gather_input_accesses_index_vars, (input_accesses,))
- return input_accesses
-
- def compile(
- self,
- dst: "Tensor",
- dst_indices: Tuple["IndexVar", ...],
- ) -> execution_engine.ExecutionEngine:
- """Compiles the tensor assignment dst[dst_indices] = expression.
-
- Args:
- dst: The destination tensor.
- dst_indices: The tuple of IndexVar used to access the destination tensor.
-
- Returns:
- The execution engine for the tensor assignment.
-
- Raises:
- ValueError: If the expression is not proper or not supported.
- """
- expr_to_info = self._validate_and_collect_expr_info(dst, dst_indices)
- input_accesses = self.get_input_accesses()
-
- # Build and compile the module to produce the execution engine.
- with ir.Context(), ir.Location.unknown():
- module = ir.Module.create()
- self._emit_assignment(
- module, dst, dst_indices, expr_to_info, input_accesses
- )
- engine = utils.compile_and_build_engine(module)
-
- return engine
-
-
-class _AtomicCounter:
- """An atomic counter."""
-
- def __init__(self):
- self._counter = 0
- self._counter_lock = threading.Lock()
-
- def increment(self) -> int:
- """Increments the counter by one and returns the old value."""
- old_value = self._counter
- with self._counter_lock:
- self._counter = self._counter + 1
- return old_value
-
-
-class IndexVar(IndexExpr):
- """The tensor index class.
-
- We support the TACO API index_var class with an alias of this class.
-
- An IndexVar object represents an index variable in tensor index notation.
-
- Attributes:
- name: A unique string name of the IndexVar.
- """
-
- _counter = _AtomicCounter()
-
- def __init__(self):
- id = self._counter.increment()
- self._name = f"{_TACO_INDEX_PREFIX}{id}"
-
- def __repr__(self) -> str:
- return f"IndexVar(name={repr(self._name)})"
-
- @property
- def name(self) -> str:
- """Returns the name of the IndexVar."""
- return self._name
-
- def _visit(
- self, func: _ExprVisitor, args, *, leaf_checker: _SubtreeLeafChecker = None
- ) -> None:
- """A post-order visitor."""
- if leaf_checker:
- assert leaf_checker(self, *args)
- func(self, *args)
-
- def _emit_expression(
- self,
- expr_to_opnd: Dict[IndexExpr, lang.OperandDef],
- expr_to_info: _ExprInfoDict,
- ) -> lang.ScalarExpression:
- """Emits a index value casted to the data type of the tensor expression."""
- dim = getattr(lang.D, self.name)
- index = lang.index(dim)
- int_value = lang.TypeFn.cast_unsigned(lang.TV.I64, index)
- return lang.TypeFn.cast_unsigned(lang.T, int_value)
-
- def dtype(self) -> DType:
- """Returns the data type for the index value.
-
- This is unreachable for IndexVar.
- """
- assert 0
-
-
-def get_index_vars(n: int) -> List[IndexVar]:
- """Returns a list of n IndexVar.
-
- This routine is defined by the TACO API.
-
- Args:
- n: An integer representing the number of IndexVar to get.
-
- Returns:
- A list of IndexVar.
-
- Raises:
- ValueError: if n is not a positive integer.
- """
- if not isinstance(n, int) or n <= 0:
- raise ValueError(f"Expected an integer: {n}.")
- # If lock contention ever becomes an issue, we could implement a bulk getter
- # that returns a range by only claiming the lock once.
- return [IndexVar() for i in range(n)]
-
-
-def _mlir_symbols_from_index_vars(
- index_vars: Tuple[IndexVar, ...]
-) -> Tuple[lang.SymbolDef, ...]:
- """Returns a tuple of MLIR symbols for the given tuple of index_var."""
- return tuple(getattr(lang.S, i.name) for i in index_vars)
-
-
-def _mlir_dimensions_from_index_vars(
- index_vars: Tuple[IndexVar, ...]
-) -> Tuple[lang.DimDef, ...]:
- """Returns a tuple of MLIR dimensions for the given tuple of index_var."""
- return tuple(getattr(lang.D, i.name) for i in index_vars)
-
-
-def _mlir_tensor_type(
- dtype: DType, shape: Tuple[int, ...], attr: Optional[sparse_tensor.EncodingAttr]
-) -> ir.RankedTensorType:
- """Returns an MLIR tensor type.
-
- Args:
- dtype: An DType object for the element data type of the tensor.
- shape: A tuple of integer for the shape of the tensor.
- attr: An optional MLIR sparse tensor attribute, only provided if the tensor
- is a sparse tensor.
-
- Returns:
- An MLIR ranked tensor type.
- """
- ir_type = _mlir_type_from_taco_type(dtype)
- return ir.RankedTensorType.get(shape, ir_type, attr)
-
-
- at dataclasses.dataclass(frozen=True)
-class _StructOpInfo:
- """Information for generating a structured op in the linalg dialect.
-
- This information is associated with an expression node that serves as the
- root for an expression subtree implemented with a structured op.
-
- Attributes:
- dst_indices: A tuple of IndexVar, representing the result dimensions of the
- structured op. This is used to construct the temporary variable for the
- tensor to hold the structured op result.
- dst_dims: A tuple of int, representing the result shape of the structured
- op.
- dst_dtype: A DType representing the data type of the structured op result.
- dst_name: A string representing the name of the structured op result.
- dst_format: An optional Format object representing the destination tensor
- format. None represents a true dense tensor.
- """
-
- dst_indices: Tuple[IndexVar, ...]
- dst_dims: Tuple[int, ...]
- dst_dtype: DType
- dst_name: str
- dst_format: Optional[Format]
-
- def __post_init__(self) -> None:
- """Verifies the integrity of the attribute values."""
- assert len(self.dst_indices) == len(self.dst_dims)
-
- def emit_tensor_init(self) -> ir.RankedTensorType:
- """Returns an initialization for the destination tensor."""
- if self.dst_format is None or self.dst_format.rank() == 0:
- # Initialize the dense tensor.
- ir_type = _mlir_type_from_taco_type(self.dst_dtype)
- empty = tensor.EmptyOp(self.dst_dims, ir_type).result
- zero = arith.ConstantOp(ir_type, 0.0)
- return linalg.fill(zero, outs=[empty])
-
- # Initialize the sparse tensor.
- mlir_type = _mlir_tensor_type(
- self.dst_dtype, self.dst_dims, self.dst_format.mlir_tensor_attr()
- )
- index_type = ir.IndexType.get()
- return bufferization.AllocTensorOp(mlir_type, [], None, None, None)
-
-
-class _Stats:
- """Information to describe how a tensor expression is implemented.
-
- Currently, we only record the temporary tensors introduced for splitting the
- original expression.
- """
-
- def __init__(self):
- self._temps = []
-
- def __repr__(self) -> str:
- return f"_Stats({repr(self._temps)})"
-
- def add_element(self, structop: _StructOpInfo):
- """Adds a temporary tensor."""
- self._temps.append(structop)
-
- def get_total(self) -> int:
- """Gets the total number of temporary tensors."""
- return len(self._temps)
-
- def _get_element(self, idx: int) -> _StructOpInfo:
- """Gets the ith temporary tensor."""
- assert idx < self.get_total()
- return self._temps[idx]
-
- def get_dimensions(self, idx: int) -> Tuple[int]:
- """Gets the dimensions for the ith temporary tensor."""
- return self._get_element(idx).dst_dims
-
- def get_formats(self, idx: int) -> Tuple[ModeFormat]:
- """Gets the ModeFormats for the ith temporary tensor."""
- return tuple(self._get_element(idx).dst_format.format_pack.formats)
-
-
-class _SparseValueInfo(enum.Enum):
- """Describes how a sparse tensor value is stored.
- _UNPACKED: The sparse tensor value is stored as (coordnates, values) in
- Python.
- _PACKED: The sparse tensor value is stored as a C pointer to a packed MLIR
- sparse tensor.
- """
-
- _UNPACKED = 0
- _PACKED = 1
-
-
- at dataclasses.dataclass(frozen=True)
-class _Assignment:
- """Records an assignment to a tensor T as T[indices] = expression."""
-
- indices: Tuple["IndexVar", ...]
- expression: "IndexExpr"
-
-
-class Tensor:
- """The tensor class.
-
- We support the TACO API tensor class with an alias of this class.
-
- This class is part of the TACO API with the following methods:
- insert: Inserts a value to the given coordinate in the tensor.
- to_array: Returns a numpy ndarray for the tensor.
-
- TACO API also defines the following arrtibutes for the class:
- dtype: A dtype object representing the data type of the tensor.
- format: A format object representing the storage format of the tensor.
- name: A string object representing the name of the tensor.
- order: An integral rank of the tensor.
- shape: A list of integers representing the shape of the tensor.
-
- We currently ignore the tensor dimension ordering for dense tensor.
- """
-
- _counter = _AtomicCounter()
-
- def _get_unique_name(self) -> str:
- """Returns a unique name for creating a new Tensor."""
- return f"{_TACO_TENSOR_PREFIX}{self._counter.increment()}"
-
- def _init_format(self, fmt: Union[ModeFormat, List[ModeFormat], Format]) -> None:
- """Process the fmt argument for the Tensor constructor.
-
- Args:
- fmt: This argument can be a ModeFormat, List[ModeFormat], or format. If
- this argument is a ModeFormat, uses this ModeFormat for all the tensor
- dimensions. If this argument is a list of ModeFormat, the len of the
- list should equal to the rank of the tensor. If this argument is a
- format, uses it for the format of the tensor.
-
- Raises:
- ValueError: If fmt is not one of the expected type or is inconsistent
- with the rank of the tensor. This is because fmt could be an users
- input.
- """
- if isinstance(fmt, ModeFormat):
- self._format = _make_format([fmt] * self.order)
- elif isinstance(fmt, list):
- if len(fmt) == self.order and isinstance(fmt[0], ModeFormat):
- self._format = _make_format(fmt)
- else:
- raise ValueError(
- "Inconsistent shape and format: " f"{self._shape}, {fmt}."
- )
- elif isinstance(fmt, Format):
- if fmt.rank() != self.order:
- raise ValueError(
- "Inconsistent shape and format: " f"{self._shape}, {fmt}."
- )
- else:
- self._format = fmt
- else:
- raise ValueError(f"Invalid format argument: {fmt}.")
-
- def __init__(
- self,
- value_or_shape: Optional[
- Union[List[int], Tuple[int, ...], complex, float, int]
- ] = None,
- fmt: Optional[Union[ModeFormat, List[ModeFormat], Format]] = None,
- dtype: Optional[DType] = None,
- name: Optional[str] = None,
- is_dense: bool = False,
- ):
- """The tensor constructor interface defined by TACO API.
-
- Args:
- value_or_shape: This argument is optional and can be int, float,
- List[int], or Tuple[int, ...]. If this argument is an int or float,
- creates a scalar tensor and initializes it with the value. If this
- argument is a list or tuple of int, uses it as the shape to create a
- tensor.
- fmt: This argument can be a ModeFormat, List[ModeFormat], or format. If
- this argument is a ModeFormat, uses this ModeFormat for all the tensor
- dimensions. If this argument is a list of ModeFormat, the len of the
- list should equal to the rank of the tensor. If this argument is a
- format, uses it for the format of the tensor.
- dtype: An object of dtype, representing the data type of the tensor.
- name: A string name of the tensor. If a name is not given, creates a
- unique name for the tensor.
- is_dense: A boolean variable to indicate whether the tensor is a dense
- tensor without any sparsity annotation.
-
- Raises:
- ValueError: If there is any inconsistency among the input arguments.
- """
- # Take care of the argument default values common to both sparse tensors
- # and dense tensors.
- dtype = dtype or DType(Type.FLOAT32)
- self._name = name or self._get_unique_name()
- self._assignment = None
- self._engine = None
- self._sparse_value_location = _SparseValueInfo._UNPACKED
- self._dense_storage = None
- self._dtype = dtype
-
- if is_dense:
- assert fmt is None
- assert (
- isinstance(value_or_shape, tuple) or isinstance(value_or_shape, list)
- ) and _all_instance_of(value_or_shape, int)
- self._shape = value_or_shape
- self._format = None
- return
-
- fmt = fmt or ModeFormat.COMPRESSED
- # We currently use _coords and _values to host the sparse tensor value with
- # COO format, and _dense_storage to host the dense tensor value. We don't
- # support the conversion between the two storages.
- self._coords = []
- self._values = []
- self._stats = _Stats()
- if (
- value_or_shape is None
- or isinstance(value_or_shape, int)
- or isinstance(value_or_shape, float)
- or isinstance(value_or_shape, complex)
- ):
- # Create a scalar tensor and ignore the fmt parameter.
- self._shape = []
- self._format = _make_format([], [])
- if value_or_shape is not None:
- self._dense_storage = np.array(value_or_shape, dtype=self._dtype.value)
- elif (
- isinstance(value_or_shape, tuple) or isinstance(value_or_shape, list)
- ) and _all_instance_of(value_or_shape, int):
- # Create a tensor with the specified shape and format.
- self._shape = list(value_or_shape)
- self._init_format(fmt)
- else:
- raise ValueError(
- "Invalid first argument. "
- "Must be a tuple or list for a shape or a single value"
- f"if initializing a scalar tensor: {value_or_shape}."
- )
-
- def _set_packed_sparse_tensor(self, pointer: ctypes.c_void_p) -> None:
- """Records the MLIR sparse tensor pointer."""
- self._sparse_value_location = _SparseValueInfo._PACKED
- self._packed_sparse_value = pointer
-
- def is_unpacked(self) -> bool:
- """Returns true if the tensor value is not packed as MLIR sparse tensor."""
- return self._sparse_value_location == _SparseValueInfo._UNPACKED
-
- def unpack(self) -> None:
- """Unpacks the MLIR sparse tensor representation."""
- if self.is_dense() or self.is_unpacked():
- return
-
- # Use the output MLIR sparse tensor pointer to retrieve the COO-flavored
- # values and verify the values.
- rank, nse, shape, values, indices = utils.sparse_tensor_to_coo_tensor(
- self._packed_sparse_value, self._dtype.value
- )
- assert rank == self.order
- assert np.array_equal(self.shape, shape)
- assert nse == len(values)
- self._coords = indices
- self._values = values
- self._sparse_value_location = _SparseValueInfo._UNPACKED
-
- def __repr__(self) -> str:
- self._sync_value()
- self.unpack()
- value_str = (
- f"{repr(self._dense_storage)})"
- if self.is_dense()
- else f"{repr(self._coords)} {repr(self._values)})"
- )
- return (
- f"Tensor(_name={repr(self._name)} " f"_dtype={repr(self._dtype)} : "
- ) + value_str
-
- def insert(self, coords: List[int], val: Union[complex, float, int]) -> None:
- """Inserts a value to the given coordinate.
-
- Args:
- coords: A list of integer coordinates. The length of the list must be the
- same as the rank of the tensor.
- val: A value being inserted. It is either an integral or a floating point
- value. This value will be converted to the data type of the tensor.
-
- Raises:
- ValueError: When there is any problem in the parameters.
- """
- if self.is_dense():
- raise ValueError("Insert method is not supported for dense tensors.")
- if self._assignment != None or not self.is_unpacked():
- raise ValueError(
- "Can't use Insert method for a tensor constructed from a file."
- )
- if not isinstance(coords, list):
- raise ValueError(f"Non list coordinate detected: {coords}.")
- if not _all_instance_of(coords, int):
- raise ValueError(f"Non integer coordinate detected: {coords}.")
- if len(coords) != self.order or any(
- [c < 0 or c >= self._shape[i] for i, c in enumerate(coords)]
- ):
- raise ValueError("Invalid coordinate for rank: " f"{self.order}, {coords}.")
-
- if (
- not isinstance(val, int)
- and not isinstance(val, float)
- and not isinstance(val, complex)
- ):
- raise ValueError(f"Value is neither int nor float: {val}.")
-
- self._coords.append(tuple(coords))
- self._values.append(self._dtype.value(val))
-
- def is_dense(self) -> bool:
- """Returns true if the tensor doesn't have sparsity annotation."""
- return self.order == 0 or self._format is None
-
- def to_array(self) -> np.ndarray:
- """Returns the numpy array for the Tensor.
-
- This is currenly only implemented for dense Tensor.
- """
- if not self.is_dense():
- raise ValueError(
- "Conversion from non-dense Tensor " "to numpy array not supported yet."
- )
-
- self._sync_value()
-
- return self._dense_storage
-
- @staticmethod
- def from_array(array: np.ndarray) -> "Tensor":
- """Returns a dense tensor with the value copied from the input array.
-
- We currently only support the conversion of float32 and float64 numpy arrays
- to Tensor.
-
- Args:
- array: The numpy array that provides the data type, shape and value for
- the tensor.
-
- Returns:
- A Tensor object.
-
- Raises:
- ValueError if the data type of the numpy array is not supported.
- """
- if array.dtype != np.float32 and array.dtype != np.float64:
- raise ValueError(f"Expected floating point value type: {array.dtype}.")
- t = Tensor(
- array.shape, dtype=_nptype_to_taco_type(array.dtype.type), is_dense=True
- )
- t._dense_storage = np.copy(array)
- return t
-
- @staticmethod
- def from_coo(
- coordinates: List[Tuple[int, ...]],
- values: List[_AnyRuntimeType],
- fmt: Format,
- dtype: DType,
- ) -> "Tensor":
- """Converts coordinates and values to a sparse tensor representation.
-
- Args:
- coordinates: A list of coordinates with non-zero values.
- values: The non-zero values.
- fmt: The tensor storage format.
- dtype: The tensor element data type.
-
- Returns:
- A tensor with the given non-zero values and storage format. The shape of
- the tensor has the minimum size for each dimension to make the given
- coordinates valid.
- """
- assert isinstance(coordinates, List) and _all_instance_of(coordinates, Tuple)
- assert isinstance(values, List) and _all_instance_of(values, dtype.value)
- assert isinstance(fmt, Format)
-
- rank = fmt.rank()
- assert all(len(c) == rank and _all_instance_of(c, int) for c in coordinates)
-
- # Find the maximum coordinate value for each dimension.
- max_coordinate = list(map(max, zip(*coordinates)))
- # The size of each dimension is one more that such a maximum coordinate
- # value.
- shape = [c + 1 for c in max_coordinate]
- t = Tensor(shape, fmt, dtype=dtype)
- t._coords = coordinates
- t._values = values
-
- return tensor
-
- @staticmethod
- def from_file(
- filename: str,
- fmt: Format,
- dtype: DType,
- ) -> "Tensor":
- """Constructs a sparse tensor using the COO-flavored values from a file.
-
- Args:
- filename: A string for the name of the file that contains the sparse
- tensor data.
- fmt: The tensor storage format.
- dtype: The tensor element data type.
-
- Returns:
- A tensor with the given non-zero values and storage format. The tensor
- value is stored as an MLIR sparse tensor.
- """
- sparse_tensor, shape = utils.create_sparse_tensor(
- filename, fmt.format_pack.formats, _dtype_to_mlir_str(dtype)
- )
- t = Tensor(shape.tolist(), fmt, dtype=dtype)
- t._set_packed_sparse_tensor(sparse_tensor)
-
- return t
-
- def to_file(self, filename: str) -> None:
- """Output the tensor value to a file.
-
- This method evaluates any pending assignment to the tensor and outputs the
- tensor value.
-
- Args:
- filename: A string file name.
-
- Raises:
- ValueError: If the tensor is dense, or an unpacked sparse tensor.
- """
- self._sync_value()
-
- if self.is_dense():
- raise ValueError(
- "Writing dense tensors without sparsity annotation to "
- "file is not supported."
- )
-
- if self.is_unpacked():
- raise ValueError(
- "Writing unpacked sparse tensors to file is not " "supported."
- )
-
- utils.output_sparse_tensor(
- self._packed_sparse_value,
- filename,
- self._format.format_pack.formats,
- _dtype_to_mlir_str(self._dtype),
- )
-
- @property
- def dtype(self) -> DType:
- """Returns the data type for the Tensor."""
- return self._dtype
-
- @property
- def format(self) -> Format:
- """Returns the storage format for the Tensor."""
- return self._format
-
- @property
- def name(self) -> str:
- """Returns the name for the Tensor."""
- return self._name
-
- @property
- def order(self) -> int:
- """Returns the rank of the Tensor."""
- return len(self._shape)
-
- @property
- def shape(self) -> List[int]:
- """Returns the shape of the Tensor."""
- return self._shape
-
- def _verify_and_normalize_indices(self, indices) -> Tuple[IndexVar, ...]:
- """Verifies and normalizes the indices to access the tensor.
-
- Args:
- indices: The index expression used to access a tensor, which could be any
- Python object from user inputs.
-
- Returns:
- A tuple of IndexVar.
-
- Raises:
- ValueError: If indices is not 0 for scalar tensors, or not an IndexVar or
- a tuple of IndexVar for other tensors.
- """
- if self.order == 0:
- if not isinstance(indices, int) or indices != 0:
- raise ValueError(f"Expected 0 to index scalar tensors: {indices}")
- return ()
-
- if isinstance(indices, IndexVar):
- return (indices,)
- elif isinstance(indices, tuple) and _all_instance_of(indices, IndexVar):
- return indices
-
- raise ValueError(f"Expected IndexVars: {indices}")
-
- def __getitem__(self, key) -> "Access":
- """Verifies and processes a tensor access.
-
- In the tensor index notation, a tensor access T[i, j] is represented as
- retrieving a value with key (i, j) from the tensor object T in Python. This
- routine verifies the key for the tensor access and returns a tensor access
- object.
-
- Args:
- key: The key used to access the tensor, which could be any Python object
- from user inputs.
-
- Returns:
- The corresponding tensor access object.
-
- Raises:
- ValueError: If key is not an IndexVar or a tuple of IndexVar.
- """
- indices = self._verify_and_normalize_indices(key)
- return Access(self, indices)
-
- def __setitem__(self, key, value) -> None:
- """Verifies and processes a tensor assignment.
-
- In the tensor index notation, a tensor assignment "T[i, j] = ..." is
- represented as setting a value for a tensor object T via key (i, j) in
- Python. This routine verifies the key, evaluates the value, and assigns the
- value to the tensor.
-
- We only support assignment of dense tensor currently.
-
- Args:
- key: The key used to access the tensor, which could be any Python object
- from user inputs.
- value: The value assigned to the tensor, which could be any Python object
- from user inputs.
-
- Raises:
- ValueError: If tensor is not a dense tensor, or the key is not an IndexVar
- or a tuple of IndexVar, or the length of the indices is not the same as
- the rank of the tensor.
- """
- indices = self._verify_and_normalize_indices(key)
- if len(indices) != self.order:
- raise ValueError(
- "Mismatch between indices and tensor rank: "
- f"len({indices}) != {self.order}."
- )
-
- self._assignment = _Assignment(indices, value)
- self._engine = None
-
- def compile(self, force_recompile: bool = False) -> None:
- """Compiles the tensor assignment to an execution engine.
-
- Calling compile the second time does not do anything unless
- force_recompile is True.
-
- Args:
- force_recompile: A boolean value to enable recompilation, such as for the
- purpose of timing.
-
- Raises:
- ValueError: If the assignment is not proper or not supported.
- """
- if self._assignment is None or (
- self._engine is not None and not force_recompile
- ):
- return
-
- self._engine = self._assignment.expression.compile(
- self, self._assignment.indices
- )
-
- def compute(self) -> None:
- """Executes the engine for the tensor assignment.
-
- Raises:
- ValueError: If the assignment hasn't been compiled yet.
- """
- if self._assignment is None:
- return
-
- if self._engine is None:
- raise ValueError("Need to invoke compile() before invoking compute().")
-
- input_accesses = self._assignment.expression.get_input_accesses()
- # Gather the pointers for the input buffers.
- input_pointers = [a.tensor.ctype_pointer() for a in input_accesses]
- if self.is_dense():
- # The pointer to receive dense output is the first argument to the
- # execution engine.
- arg_pointers = [self.dense_dst_ctype_pointer()] + input_pointers
- else:
- # The pointer to receive the sparse tensor output is the last argument
- # to the execution engine and is a pointer to pointer of char.
- arg_pointers = input_pointers + [
- ctypes.pointer(ctypes.pointer(ctypes.c_char(0)))
- ]
-
- # Invoke the execution engine to run the module.
- self._engine.invoke(_ENTRY_NAME, *arg_pointers)
-
- # Retrieve the result.
- if self.is_dense():
- result = runtime.ranked_memref_to_numpy(arg_pointers[0][0])
- assert isinstance(result, np.ndarray)
- self._dense_storage = result
- else:
- self._set_packed_sparse_tensor(arg_pointers[-1][0])
-
- self._assignment = None
- self._engine = None
-
- def evaluate(self) -> None:
- """Evaluates the tensor assignment."""
- self.compile()
- self.compute()
-
- def _sync_value(self) -> None:
- """Updates the tensor value by evaluating the pending assignment."""
- if self._assignment is not None:
- self.evaluate()
-
- def mlir_tensor_type(self) -> ir.RankedTensorType:
- """Returns the MLIR type for the tensor."""
- mlir_attr = (
- None
- if (self._format is None or self.order == 0)
- else self._format.mlir_tensor_attr()
- )
- return _mlir_tensor_type(self._dtype, tuple(self._shape), mlir_attr)
-
- def dense_dst_ctype_pointer(self) -> ctypes.pointer:
- """Returns the ctypes pointer for the pointer to an MemRefDescriptor.
-
- For a dense tensor output, the MLIR compiler allocates the storage for
- the tensor. This routine returns the pointer to an MLIR MemRefDescriptor for
- receiving the tensor.
- """
- assert self.is_dense()
- mem_ref_desc = runtime.make_nd_memref_descriptor(
- self.order, np.ctypeslib.as_ctypes_type(self.dtype.value)
- )()
- return ctypes.pointer(ctypes.pointer(mem_ref_desc))
-
- def ctype_pointer(self) -> ctypes.pointer:
- """Returns the ctypes pointer for the pointer to the input tensor."""
- if self.is_dense():
- if self._dense_storage is None:
- self._dense_storage = np.zeros(self._shape, self._dtype.value)
- return _ctype_pointer_from_array(self._dense_storage)
-
- if self.is_unpacked():
- shape = np.array(self._shape, np.int64)
- indices = np.array(self._coords, np.int64)
- values = np.array(self._values, self._dtype.value)
- perm, sparse = self.format.get_permutation_and_sparsity()
- ptr = utils.coo_tensor_to_sparse_tensor(
- shape, values, indices, perm, sparse
- )
- else:
- ptr = self._packed_sparse_value
-
- return ctypes.pointer(ctypes.cast(ptr, ctypes.c_void_p))
-
- def get_scalar_value(self) -> _AnyRuntimeType:
- """Returns the value for the scalar tensor.
-
- This method also evaluates the assignment to the tensor.
-
- Raises:
- ValueError: If the tensor is not a scalar.
- """
- if self.order != 0:
- raise ValueError(f"Expected a scalar tensor, got: rank={self.order}")
-
- self._sync_value()
- return self._dense_storage
-
- def get_coordinates_and_values(
- self,
- ) -> Tuple[List[Tuple[int, ...]], List[_AnyRuntimeType]]:
- """Returns the coordinates and values for the non-zero elements.
-
- This method also evaluates the assignment to the tensor and unpack the
- sparse tensor.
- """
- self._sync_value()
-
- if not self.is_dense():
- self.unpack()
- return (self._coords, self._values)
-
- if self.order == 0:
- return ([], self._dense_storage)
-
- # Coordinates for non-zero elements, grouped by dimensions.
- coords_by_dims = self._dense_storage.nonzero()
- # Coordinates for non-zero elements, grouped by elements.
- coords = np.transpose(coords_by_dims)
- values = self._dense_storage[coords_by_dims]
- return (coords, values)
-
- def _record_stats(self, structop: "_StructOpInfo"):
- """Collects information for temporary tensors."""
- # Exclude user specified destination tensors.
- if structop.dst_name == self.name:
- return
-
- self._stats.add_element(structop)
-
-
-def _emit_operand(
- op_def: lang.LinalgOpDef,
- indices: Tuple[IndexVar, ...],
- name: str,
- kind: lang.OperandKind,
-) -> lang.OperandDef:
- """Emits an operand for a tensor access in the current linalg operation.
-
- Args:
- op_def: A LinalgOpDef representing the current linalg dialect operation.
- indices: A tuple of IndexVar used to access the tensor.
- name: A unique string name of the tensor.
- kind: An OperandKind for the operand.
-
- Returns:
- An OperandDef representing the operand.
- """
- dim_sym = _mlir_symbols_from_index_vars(indices)
- opnd = lang.OperandDef(kind, lang.T, dim_sym)
- op_def.add_operand(name, opnd)
- return opnd
-
-
- at dataclasses.dataclass(frozen=True)
-class _DimInfo:
- """Information for an operand dimension.
-
- Attributes:
- dim: An integer for the size of the dimension.
- mode_format: A ModeFormat for the dimension sparsity.
- """
-
- dim: int
- mode_format: ModeFormat
-
-
-def _get_dummy_dim_info() -> _DimInfo:
- """Constructs the _DimInfo for an index used in tensor expressions."""
- return _DimInfo(-1, ModeFormat.DENSE)
-
-
- at dataclasses.dataclass()
-class _ExprInfo:
- """Expression information for validation and code generation.
-
- Attributes:
- src_indices: A tuple of IndexVar for the indices used by the tensors in the
- expression tree.
- dim_infos: A tuple of _DimInfo, representing the dimension information
- corresponding to the src_indices.
- reduce_indices: A set of IndexVar for the indices reduced by the expression.
- acc_reduce_indices: An accumulated set of IndexVar for the indices reduced
- by the expression and its children.
- structop_info: Information to support the code generation for a structured
- op in the linalg dialect, if the corresponding expression node is the root
- of a subtree for a structured op.
- mlir_value: The MLIR value generated for the structured op.
- """
-
- src_indices: Tuple[IndexVar, ...]
- dim_infos: Tuple[_DimInfo, ...]
- reduce_indices: Optional[Set[IndexVar]] = None
- acc_reduce_indices: Optional[Set[IndexVar]] = None
- structop_info: Optional[_StructOpInfo] = None
- mlir_value: Optional[ir.Value] = None
-
- def __post_init__(self) -> None:
- """Verifies and fix up attribute values.
-
- Verifies the consistency of the attributes and modifies the default values
- to support convenient initializer syntax.
- """
- assert len(self.src_indices) == len(self.dim_infos)
- self.reduce_indices = self.reduce_indices or set()
- self.acc_reduce_indices = self.acc_reduce_indices or set()
-
-
- at dataclasses.dataclass(frozen=True)
-class Access(IndexExpr):
- """The tensor access class.
-
- We support the TACO API access class with an alias of this class.
-
- Attributes:
- tensor: A Tensor being accessed.
- indices: A tuple of IndexVar, representing the indices used to access the
- Tensor.
- """
-
- tensor: Tensor
- indices: Tuple[IndexVar, ...]
-
- def __post_init__(self) -> None:
- """Verifies the tensor and indices for a tensor access.
-
- Raises:
- ValueError: If indices is not a list of IndexVar or the len of indices
- doesn't equal to the rank of the tensor.
- """
- if not isinstance(self.indices, tuple) or not _all_instance_of(
- self.indices, IndexVar
- ):
- raise ValueError(f"Indices contain non IndexVar: {str(self.indices)}.")
- if self.tensor.order != len(self.indices):
- raise ValueError(
- "Invalid indices for rank: "
- f"str{self.tensor.order} != len({str(self.indices)})."
- )
-
- def __repr__(self) -> str:
- # The Tensor __repr__ method evaluates the pending assignment to the tensor.
- # We want to define the __repr__ method here to avoid such evaluation of the
- # tensor assignment.
- indices_str = ", ".join(map(lambda i: i.name, self.indices))
- return f"Tensor({self.tensor.name}) " f"Indices({indices_str})"
-
- def _emit_expression(
- self,
- expr_to_opnd: Dict[IndexExpr, lang.OperandDef],
- expr_to_info: _ExprInfoDict,
- ) -> lang.ScalarExpression:
- """Emits a linalg dialect TensorUse expression for the tensor access."""
- assert self in expr_to_opnd
- dims = _mlir_dimensions_from_index_vars(self.indices)
- return lang.TensorUse(expr_to_opnd[self], dims)
-
- def _visit(
- self, func: _ExprVisitor, args, *, leaf_checker: _SubtreeLeafChecker = None
- ) -> None:
- if leaf_checker:
- assert leaf_checker(self, *args)
- func(self, *args)
-
- def dtype(self) -> DType:
- return self.tensor.dtype
-
-
-def _gather_input_accesses_index_vars(
- expr: IndexExpr,
- input_accesses: List[Access],
-) -> None:
- """Collects Access nodes."""
- if isinstance(expr, Access) and expr not in input_accesses:
- input_accesses.append(expr)
-
-
-def _op_ceil(__a: Any) -> Any:
- """A _UnaryOp object for operation ceil."""
- pass
-
-
-def _op_floor(__a: Any) -> Any:
- """A _UnaryOp object for operation floor."""
- pass
-
-
-def _op_unary_to_callable(op: _UnaryOp) -> lang.UnaryFnType:
- """Returns the linalg dialect function object for the given operation."""
- op_to_callable = {
- operator.abs: lang.UnaryFn.abs,
- operator.neg: lang.UnaryFn.negf,
- _op_ceil: lang.UnaryFn.ceil,
- _op_floor: lang.UnaryFn.floor,
- }
- return op_to_callable[op]
-
-
- at dataclasses.dataclass(frozen=True)
-class _UnaryExpr(IndexExpr):
- """The representation for a Unary operation.
-
- Attributes:
- op: A _UnaryOp representing the operation.
- a: An IndexExpr representing the operand for the operation.
- """
-
- op: _BinaryOp
- a: IndexExpr
-
- def __post_init__(self) -> None:
- """Verifies that the operand being added is an IndexExpr."""
- assert isinstance(self.a, IndexExpr)
-
- def _emit_expression(
- self,
- expr_to_opnd: Dict[IndexExpr, lang.OperandDef],
- expr_to_info: _ExprInfoDict,
- ) -> lang.ScalarExpression:
- """Emits the expression tree and returns the expression."""
- # The current expression node is an internal node of the structured op.
- if self not in expr_to_opnd:
- a = self.a._emit_expression(expr_to_opnd, expr_to_info)
- return _op_unary_to_callable(self.op)(a)
-
- # The current expression is a leaf node of the structured op. That is, it is
- # a temporary tensor generated by its child structured op.
- op_info = expr_to_info[self].structop_info
- assert op_info is not None
- dims = _mlir_dimensions_from_index_vars(op_info.dst_indices)
- return lang.TensorUse(expr_to_opnd[self], dims)
-
- def _visit(
- self, func: _ExprVisitor, args, *, leaf_checker: _SubtreeLeafChecker = None
- ) -> None:
- """A post-order visitor."""
- if leaf_checker is None or not leaf_checker(self, *args):
- self.a._visit(func, args, leaf_checker=leaf_checker)
- func(self, *args)
-
- def dtype(self) -> DType:
- """Returns the data type of the operation."""
- return self.a.dtype()
-
-
-def _op_to_callable(op: _BinaryOp) -> lang.BinaryFnType:
- """Returns the linalg dialect function object for the given operation."""
- op_to_callable = {
- operator.add: lang.BinaryFn.add,
- operator.sub: lang.BinaryFn.sub,
- operator.mul: lang.BinaryFn.mul,
- }
- return op_to_callable[op]
-
-
- at dataclasses.dataclass(frozen=True)
-class _BinaryExpr(IndexExpr):
- """The representation for a binary operation.
-
- Attributes:
- op: A _BinaryOp representing the binary operation.
- a: An IndexExpr representing the first operand of the operation.
- b: An IndexExpr representing the second operand of the operation.
- """
-
- op: _BinaryOp
- a: IndexExpr
- b: IndexExpr
-
- def __post_init__(self) -> None:
- """Verifies that the operands being added are IndexExpr."""
- assert isinstance(self.a, IndexExpr) and isinstance(self.b, IndexExpr)
-
- def _emit_expression(
- self,
- expr_to_opnd: Dict[IndexExpr, lang.OperandDef],
- expr_to_info: _ExprInfoDict,
- ) -> lang.ScalarExpression:
- """Emits the expression tree and returns the expression."""
- # The current expression node is an internal node of the structured op.
- if self not in expr_to_opnd:
- a = self.a._emit_expression(expr_to_opnd, expr_to_info)
- b = self.b._emit_expression(expr_to_opnd, expr_to_info)
- return _op_to_callable(self.op)(a, b)
-
- # The current expression is a leaf node of the structured op. That is, it is
- # a temporary tensor generated by its child structured op.
- op_info = expr_to_info[self].structop_info
- assert op_info is not None
- dims = _mlir_dimensions_from_index_vars(op_info.dst_indices)
- return lang.TensorUse(expr_to_opnd[self], dims)
-
- def _visit(
- self, func: _ExprVisitor, args, *, leaf_checker: _SubtreeLeafChecker = None
- ) -> None:
- """A post-order visitor."""
- if leaf_checker is None or not leaf_checker(self, *args):
- self.a._visit(func, args, leaf_checker=leaf_checker)
- self.b._visit(func, args, leaf_checker=leaf_checker)
- func(self, *args)
-
- def dtype(self) -> DType:
- """Returns the data type of the binary operation."""
- return self.a.dtype()
-
-
-def _validate_and_collect_dim_info(
- index_to_dim_info: Dict[IndexVar, _DimInfo],
- indices: Tuple[IndexVar, ...],
- dim_infos: Tuple[_DimInfo, ...],
- expr: _BinaryExpr,
-) -> None:
- """Validates and collects the dimension information for an index notation.
-
- Validates (indices, dim_infos) against the information collected from other
- source operands and is represented by index_to_dim_info. In particular, we
- ensure that each IndexVar corresponds to only one dimension size. We also
- aggregate the new information represented in (indices, dim_infos) to
- index_to_dim_info.
-
- Args:
- index_to_dim: A dictionary of (IndexVar, _DimInfo) collected from the
- previous operands.
- indices: The IndexVars to be validated.
- dim_infos: The dimension information for the IndexVars to be validated.
- expr: The binary expression where (indices, dim_infos) is used.
-
- Raises:
- ValueError if there is any problem in the IndexVars or dimensional values.
- """
- assert len(indices) == len(dim_infos)
- for i, d in zip(indices, dim_infos):
- if i not in index_to_dim_info:
- index_to_dim_info[i] = d
- else:
- dim = index_to_dim_info[i].dim
- if dim == -1 or d.dim == -1:
- dim = dim if dim != -1 else d.dim
- elif dim != d.dim:
- raise ValueError(
- f"Inconsistent source dimension for {i}: " f"{d.dim} vs {dim}"
- )
- mode_format = _mode_format_estimator(expr.op)(
- index_to_dim_info[i].mode_format, d.mode_format
- )
- index_to_dim_info[i] = _DimInfo(d.dim, mode_format)
-
-
-def _validate_and_collect_expr_info(
- expr: IndexExpr,
- expr_to_info: _ExprInfoDict,
-) -> None:
- """Validates dimension information and constructs _ExprInfo.
-
- Validates that dimensional values for the same IndexVar are the same. Collects
- a list of IndexVar used by the expression and their corresponding dimensional
- values. Constructs an _ExprInfo object to record the information for the
- IndexExpr.
-
- This routine is passed to the post-order visitor as an _ExprVisitor object.
-
- Args:
- expr: The IndexExpr being validated.
- expr_to_info: The dictionary of (IndexExpr, _ExprInfo) for recording the
- expression information.
-
- Raises:
- ValueError if there is any problem in the IndexVars or dimensional values.
- """
- # Objects of class Access can be shared by
diff erent expressions. Avoid
- # processing Access objects multiple times by skipping the processing if expr
- # is already in the dictionary.
- if expr in expr_to_info:
- return
-
- if isinstance(expr, IndexVar):
- src_indices = (expr,) # A tuple with one element.
- dim_infos = (_get_dummy_dim_info(),) # A tuple with one element.
- elif isinstance(expr, Access):
- src_indices = expr.indices
- src_dims = tuple(expr.tensor.shape)
- if expr.tensor.format is None:
- # Treat each dimension of a dense tensor as DENSE for the purpose of
- # calculating temporary tensor storage format.
- mode_formats = tuple([ModeFormat.DENSE] * len(src_dims))
- else:
- mode_formats = tuple(expr.tensor.format.format_pack.formats)
- assert len(src_dims) == len(mode_formats)
- dim_infos = tuple([_DimInfo(d, m) for d, m in zip(src_dims, mode_formats)])
- elif isinstance(expr, _UnaryExpr):
- a_info = expr_to_info[expr.a]
- index_to_dim_info = {i: d for i, d in zip(a_info.src_indices, a_info.dim_infos)}
- # Here we rely on the fact that dictionaries keep the insertion order for
- # keys and values.
- src_indices = tuple(index_to_dim_info.keys())
- dim_infos = tuple(index_to_dim_info.values())
- else:
- assert isinstance(expr, _BinaryExpr)
- a_info = expr_to_info[expr.a]
- index_to_dim_info = {i: d for i, d in zip(a_info.src_indices, a_info.dim_infos)}
- b_info = expr_to_info[expr.b]
- _validate_and_collect_dim_info(
- index_to_dim_info, b_info.src_indices, b_info.dim_infos, expr
- )
- # Here we rely on the fact that dictionaries keep the insertion order for
- # keys and values.
- src_indices = tuple(index_to_dim_info.keys())
- dim_infos = tuple(index_to_dim_info.values())
-
- expr_to_info[expr] = _ExprInfo(src_indices, dim_infos)
-
-
-def _mark_structured_op_root(
- expr: IndexExpr,
- reduce_index: IndexVar,
- expr_to_info: _ExprInfoDict,
-) -> None:
- """Identifies the root expression for a structured op in the linalg dialect.
-
- An linalg structured op can only perform reduction on the whole expression.
- For a TACO tensor algebra expression, the reduction on an IndexVar is done at
- the smallest expression that contains all the uses of the IndexVar. If such an
- expression is only part of the whole expression, we need to split this
- sub-expression tree out from its parent and implement the sub-expression as a
- structured op.
-
- This routine identifies the root expression node for performing a reduction on
- the given IndexVar. If the reduction of the given IndexVar should be performed
- on expression X, then the IndexVar is added to expr_to_info[X].reduce_indices
-
- Args:
- expr: The root IndexExpr for the tensor algebra expression.
- reduce_index: The IndexVar which we want to find out the proper expression
- to perform a reduction.
- expr_to_info: The dictionary to look up _ExprInfo for IndexExpr.
-
- Raises:
- ValueError: If the expression is not proper or not supported.
- """
- expr_info = expr_to_info[expr]
- if isinstance(expr, Access):
- # Handle simple reduction expression in the format of A[i] = B[i, j].
- if reduce_index in expr_info.src_indices:
- expr_info.reduce_indices.add(reduce_index)
- return
- elif isinstance(expr, IndexVar):
- # A[i] = B[i] + j is not allowed.
- raise ValueError(f"IndexVar is not part of the iteration domain: {expr}.")
-
- assert isinstance(expr, _BinaryExpr)
- a_info = expr_to_info[expr.a]
- b_info = expr_to_info[expr.b]
-
- if reduce_index in a_info.src_indices and reduce_index in b_info.src_indices:
- expr_info.reduce_indices.add(reduce_index)
- return
-
- if reduce_index in a_info.src_indices:
- _mark_structured_op_root(expr.a, reduce_index, expr_to_info)
- elif reduce_index in b_info.src_indices:
- _mark_structured_op_root(expr.b, reduce_index, expr_to_info)
- else:
- assert False, "Unreachable path"
-
-
-def _accumulate_reduce_indices(
- expr: IndexExpr,
- expr_to_info: _ExprInfoDict,
-) -> None:
- """Propagates reduction indices from child expressions to parent expressions.
-
- This routine is passed to the post-order visitor as an _ExprVisitor object.
-
- Args:
- expr: The IndexExpr being visited.
- expr_to_info: The dictionary of (IndexExpr, _ExprInfo) for recording the
- expression information.
- """
- assert expr in expr_to_info
- expr_info = expr_to_info[expr]
-
- if isinstance(expr, _BinaryExpr):
- a_info = expr_to_info[expr.a]
- b_info = expr_to_info[expr.b]
- expr_info.acc_reduce_indices = (
- a_info.acc_reduce_indices
- | b_info.acc_reduce_indices
- | expr_info.reduce_indices
- )
- elif isinstance(expr, _UnaryExpr):
- a_info = expr_to_info[expr.a]
- expr_info.acc_reduce_indices = (
- a_info.acc_reduce_indices | expr_info.reduce_indices
- )
- elif isinstance(expr, IndexVar):
- # If an IndexVar is reducing itself, it means the IndexVar is outside the
- # iteration domain. This usage is now allowed and we should emit an error
- # before reaching here.
- assert not expr_info.reduce_indices
- else:
- assert isinstance(expr, Access)
- # Handle simple reduction expression in the format of A[i] = B[i, j].
- expr_info.acc_reduce_indices = expr_info.reduce_indices
-
-
-def _gather_structured_op(
- expr: IndexExpr,
- expr_to_info: _ExprInfoDict,
- structop_roots: List[IndexExpr],
-) -> None:
- """Adds structured op root expression information to structop_roots.
-
- This routine is passed to the post-order visitor as an _ExprVisitor object.
-
- Args:
- expr: The IndexExpr being visited.
- expr_to_info: The dictionary to look up _ExprInfo for IndexExpr.
- structop_roots: The resulting list of IndexExpr that are the roots for
- linalg structured ops.
- """
- if not expr_to_info[expr].reduce_indices:
- return
-
- # If the expression is the root for reducing some indices, collect the indices
- # and dimensions for the reduction result.
- dst_indices = []
- dst_dims = []
- mode_fmts = []
- for i, d in zip(expr_to_info[expr].src_indices, expr_to_info[expr].dim_infos):
- if i not in expr_to_info[expr].acc_reduce_indices:
- dst_indices.append(i)
- dst_dims.append(d.dim)
- mode_fmts.append(d.mode_format)
-
- # Add the information to the dictionary.
- op_info = _StructOpInfo(
- tuple(dst_indices),
- tuple(dst_dims),
- expr.dtype(),
- f"temp{len(structop_roots)}",
- _make_format(mode_fmts),
- )
- expr_to_info[expr].structop_info = op_info
-
- # Add the expression to the list of structured op roots.
- structop_roots.append(expr)
-
-
-def _is_structured_op_leaf(
- expr: IndexExpr,
- root: IndexExpr,
- expr_to_info: _ExprInfoDict,
- *unused_args,
-) -> bool:
- """Returns true iff the expression is a leaf node for a structured op.
-
- The root of a structured op is a leaf of its parent structured op that uses
- its result. An expression node is a leaf node for the current structured op if
- it is an Access node or the root for a structured op that is not the current
- structured op.
-
- This routine is passed to the post-order visitor as a _SubtreeLeafChecker
- object. Because the post-order visitor pass the same parameters to both
- _SubtreeLeafChecker and _ExprVisitor, this routine may received unused
- parameters.
-
- Args:
- expr: The IndexExpr being visited.
- root: The root of the current structured op.
- expr_to_info: The dictionary to look up _ExprInfo for IndexExpr.
-
- Returns:
- True if the current IndexExpr is a leaf for the current structured op.
- """
- return (
- (expr != root and expr_to_info[expr].structop_info is not None)
- or isinstance(expr, Access)
- or isinstance(expr, IndexVar)
- )
-
-
-def _gather_structured_op_input(
- expr: IndexExpr,
- root: IndexExpr,
- expr_to_info: _ExprInfoDict,
- structop_inputs: List[IndexExpr],
-) -> None:
- """Adds the IndexExpr to structop_inputs if it is an input.
-
- If the current IndexExpr is an input for the current structured op, adds it to
- structop_inputs. The current IndexExpr is an input if it is an Access node or
- if it is the root for a structured op that is not the current structured op.
-
- This routine is passed to the post-order visitor as an _ExprVisitor object.
-
- Args:
- expr: The IndexExpr being visited.
- root: The root of the current structured op.
- expr_to_info: The dictionary to look up _ExprInfo for IndexExpr.
- structop_inputs: The resulting list of IndexExpr that provide input to the
- current structured op.
- """
- if (
- (expr != root or isinstance(expr, Access)) and expr not in structop_inputs
- ) and (
- isinstance(expr, Access)
- or (expr in expr_to_info and expr_to_info[expr].structop_info)
- ):
- structop_inputs.append(expr)
-
-
-def _emit_structured_op_input(
- expr: IndexExpr,
- expr_to_info: _ExprInfoDict,
- op_def: lang.LinalgOpDef,
-) -> lang.OperandDef:
- """Emits OperandDef in the linalg dialect for the input IndexExpr.
-
- Args:
- expr: The input IndexExpr for the current structured op.
- expr_to_info: The dictionary to look up _ExprInfo for IndexExpr.
- op_def: The linalg operation for the current structured op.
-
- Returns:
- An OperandDef in the linalg dialect for the input IndexExpr.
- """
- op_info = expr_to_info[expr].structop_info
- if op_info and not isinstance(expr, Access):
- # The input is a temporary tensor produced by another structured op.
- indices = op_info.dst_indices
- name = op_info.dst_name
- else:
- # The input is a user provided tensor.
- assert isinstance(expr, Access)
- indices = expr.indices
- name = expr.tensor.name
-
- dim_sym = _mlir_symbols_from_index_vars(indices)
- opnd = lang.OperandDef(lang.OperandKind.INPUT_TENSOR, lang.T, dim_sym)
- op_def.add_operand(name, opnd)
- return opnd
-
-
-def _check_and_build_unary(a: Access, op: _UnaryOp) -> "_UnaryExpr":
- """Build a unary operation ceil.
-
- Args:
- a: The operand, which could be any Python object from user inputs.
- op: An _UnaryOp object representing the operation.
-
- Returns:
- A _UnaryExpr object representing the operation.
-
- Raises:
- ValueError: If a is not an IndexExpr.
- """
- if not isinstance(a, Access):
- raise ValueError(f"Expected an Access Operand: {a}")
- return a._build_unary_expr(op)
-
-
-def ceil(a: Access) -> "_UnaryExpr":
- """Defines the operation ceil.
-
- Args:
- a: The operand, which could be any Python object from user inputs.
-
- Returns:
- A _UnaryExpr object representing the operation.
-
- Raises:
- ValueError: If a is not an IndexExpr.
- """
- return _check_and_build_unary(a, _op_ceil)
-
-
-def floor(a: Access) -> "_UnaryExpr":
- """Defines the operation floor.
-
- Args:
- a: The operand, which could be any Python object from user inputs.
-
- Returns:
- A _UnaryExpr object representing the operation.
-
- Raises:
- ValueError: If a is not an IndexExpr.
- """
- return _check_and_build_unary(a, _op_floor)
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/tools/mlir_pytaco_api.py b/mlir/test/Integration/Dialect/SparseTensor/taco/tools/mlir_pytaco_api.py
deleted file mode 100644
index d11eb76edca93c7..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/tools/mlir_pytaco_api.py
+++ /dev/null
@@ -1,53 +0,0 @@
-# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-# See https://llvm.org/LICENSE.txt for license information.
-# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-
-"""Supports the PyTACO API with the MLIR-PyTACO implementation.
-
-See http://tensor-compiler.org/ for TACO tensor compiler.
-
-This module exports the MLIR-PyTACO implementation through the language defined
-by PyTACO. In particular, it defines the function and type aliases and constants
-needed for the PyTACO API to support the execution of PyTACO programs using the
-MLIR-PyTACO implementation.
-"""
-
-from . import mlir_pytaco
-from . import mlir_pytaco_io
-
-# Functions defined by PyTACO API.
-ceil = mlir_pytaco.ceil
-floor = mlir_pytaco.floor
-get_index_vars = mlir_pytaco.get_index_vars
-from_array = mlir_pytaco.Tensor.from_array
-read = mlir_pytaco_io.read
-write = mlir_pytaco_io.write
-
-# Classes defined by PyTACO API.
-dtype = mlir_pytaco.DType
-mode_format = mlir_pytaco.ModeFormat
-mode_ordering = mlir_pytaco.ModeOrdering
-mode_format_pack = mlir_pytaco.ModeFormatPack
-format = mlir_pytaco.Format
-index_var = mlir_pytaco.IndexVar
-tensor = mlir_pytaco.Tensor
-index_expression = mlir_pytaco.IndexExpr
-access = mlir_pytaco.Access
-
-# Data type constants defined by PyTACO API.
-int8 = mlir_pytaco.DType(mlir_pytaco.Type.INT8)
-int16 = mlir_pytaco.DType(mlir_pytaco.Type.INT16)
-int32 = mlir_pytaco.DType(mlir_pytaco.Type.INT32)
-int64 = mlir_pytaco.DType(mlir_pytaco.Type.INT64)
-float16 = mlir_pytaco.DType(mlir_pytaco.Type.FLOAT16)
-float32 = mlir_pytaco.DType(mlir_pytaco.Type.FLOAT32)
-float64 = mlir_pytaco.DType(mlir_pytaco.Type.FLOAT64)
-complex64 = mlir_pytaco.DType(mlir_pytaco.Type.COMPLEX64)
-complex128 = mlir_pytaco.DType(mlir_pytaco.Type.COMPLEX128)
-
-# Storage format constants defined by the PyTACO API. In PyTACO, each storage
-# format constant has two aliasing names.
-compressed = mlir_pytaco.ModeFormat.COMPRESSED
-Compressed = mlir_pytaco.ModeFormat.COMPRESSED
-dense = mlir_pytaco.ModeFormat.DENSE
-Dense = mlir_pytaco.ModeFormat.DENSE
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/tools/mlir_pytaco_io.py b/mlir/test/Integration/Dialect/SparseTensor/taco/tools/mlir_pytaco_io.py
deleted file mode 100644
index 785401c25dc87ce..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/tools/mlir_pytaco_io.py
+++ /dev/null
@@ -1,82 +0,0 @@
-# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-# See https://llvm.org/LICENSE.txt for license information.
-# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-
-"""Experimental MLIR-PyTACO with sparse tensor support.
-
-See http://tensor-compiler.org/ for TACO tensor compiler.
-
-This module implements the PyTACO API for writing a tensor to a file or reading
-a tensor from a file.
-
-See the following links for Matrix Market Exchange (.mtx) format and FROSTT
-(.tns) format:
- https://math.nist.gov/MatrixMarket/formats.html
- http://frostt.io/tensors/file-formats.html
-"""
-
-from typing import List, TextIO
-
-from . import mlir_pytaco
-
-# Define the type aliases so that we can write the implementation here as if
-# it were part of mlir_pytaco.py.
-Tensor = mlir_pytaco.Tensor
-Format = mlir_pytaco.Format
-DType = mlir_pytaco.DType
-Type = mlir_pytaco.Type
-
-# Constants used in the implementation.
-_MTX_FILENAME_SUFFIX = ".mtx"
-_TNS_FILENAME_SUFFIX = ".tns"
-
-
-def read(filename: str, fmt: Format, dtype: DType = DType(Type.FLOAT32)) -> Tensor:
- """Inputs a tensor from a given file.
-
- The name suffix of the file specifies the format of the input tensor. We
- currently only support .mtx format for support sparse tensors.
-
- Args:
- filename: A string input filename.
- fmt: The storage format of the tensor.
- dtype: The data type, default to float32.
-
- Raises:
- ValueError: If filename doesn't end with .mtx or .tns, or fmt is not an
- instance of Format or fmt is not a sparse tensor.
- """
- if not isinstance(filename, str) or (
- not filename.endswith(_MTX_FILENAME_SUFFIX)
- and not filename.endswith(_TNS_FILENAME_SUFFIX)
- ):
- raise ValueError(
- "Expected string filename ends with "
- f"{_MTX_FILENAME_SUFFIX} or {_TNS_FILENAME_SUFFIX}: "
- f"{filename}."
- )
-
- return Tensor.from_file(filename, fmt, dtype)
-
-
-def write(filename: str, tensor: Tensor) -> None:
- """Outputs a tensor to a given file.
-
- The name suffix of the file specifies the format of the output. We currently
- only support .tns format.
-
- Args:
- filename: A string output filename.
- tensor: The tensor to output.
-
- Raises:
- ValueError: If filename doesn't end with .tns or tensor is not a Tensor.
- """
- if not isinstance(filename, str) or not filename.endswith(_TNS_FILENAME_SUFFIX):
- raise ValueError(
- "Expected string filename ends with" f" {_TNS_FILENAME_SUFFIX}: {filename}."
- )
- if not isinstance(tensor, Tensor):
- raise ValueError(f"Expected a Tensor object: {tensor}.")
-
- tensor.to_file(filename)
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/tools/mlir_pytaco_utils.py b/mlir/test/Integration/Dialect/SparseTensor/taco/tools/mlir_pytaco_utils.py
deleted file mode 100644
index 1e1061b8b858d77..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/tools/mlir_pytaco_utils.py
+++ /dev/null
@@ -1,424 +0,0 @@
-# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-# See https://llvm.org/LICENSE.txt for license information.
-# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-
-# This file contains the utilities to process sparse tensor outputs.
-
-from typing import Callable, Dict, Sequence, Tuple
-import ctypes
-import functools
-import numpy as np
-import os
-
-# Import MLIR related modules.
-from mlir import execution_engine
-from mlir import ir
-from mlir import runtime
-from mlir.dialects import sparse_tensor
-
-from . import mlir_sparse_compiler
-
-# Type aliases for type annotation.
-_SupportFunc = Callable[..., None]
-_SupportFuncLocator = Callable[[np.dtype], Tuple[_SupportFunc, _SupportFunc]]
-
-# The name for the environment variable that provides the full path for the
-# supporting library.
-_SUPPORTLIB_ENV_VAR = "SUPPORTLIB"
-# The default supporting library if the environment variable is not provided.
-_DEFAULT_SUPPORTLIB = "libmlir_c_runner_utils.so"
-
-# The JIT compiler optimization level.
-_OPT_LEVEL = 2
-# The entry point to the JIT compiled program.
-_ENTRY_NAME = "main"
-
-
- at functools.lru_cache()
-def _get_support_lib_name() -> str:
- """Gets the string name for the supporting C shared library."""
- return os.getenv(_SUPPORTLIB_ENV_VAR, _DEFAULT_SUPPORTLIB)
-
-
- at functools.lru_cache()
-def _get_sparse_compiler() -> mlir_sparse_compiler.SparseCompiler:
- """Gets the MLIR sparse compiler with default setting."""
- return mlir_sparse_compiler.SparseCompiler(
- options="", opt_level=_OPT_LEVEL, shared_libs=[_get_support_lib_name()]
- )
-
-
-def _record_support_funcs(
- ty: np.dtype,
- to_func: _SupportFunc,
- from_func: _SupportFunc,
- ty_to_funcs: Dict[np.dtype, Tuple[_SupportFunc, _SupportFunc]],
-) -> None:
- """Records the two supporting functions for a given data type."""
- to_func.restype = ctypes.c_void_p
- from_func.restype = ctypes.c_void_p
- ty_to_funcs[ty] = (to_func, from_func)
-
-
- at functools.lru_cache()
-def _get_support_func_locator() -> _SupportFuncLocator:
- """Constructs a function to locate the supporting functions for a data type.
-
- Loads the supporting C shared library with the needed routines. Constructs a
- dictionary from the supported data types to the routines for the data types,
- and then a function to look up the dictionary for a given data type.
-
- The name of the supporting C shared library is either provided by an
- an environment variable or a default value.
-
- Returns:
- The function to look up the supporting functions for a given data type.
-
- Raises:
- OSError: If there is any problem in loading the shared library.
- ValueError: If the shared library doesn't contain the needed routines.
- """
- # This raises OSError exception if there is any problem in loading the shared
- # library.
- c_lib = ctypes.CDLL(_get_support_lib_name())
-
- type_to_funcs = {}
- try:
- support_types = [
- (
- np.int8,
- c_lib.convertToMLIRSparseTensorI8,
- c_lib.convertFromMLIRSparseTensorI8,
- ),
- (
- np.int16,
- c_lib.convertToMLIRSparseTensorI16,
- c_lib.convertFromMLIRSparseTensorI16,
- ),
- (
- np.int32,
- c_lib.convertToMLIRSparseTensorI32,
- c_lib.convertFromMLIRSparseTensorI32,
- ),
- (
- np.int64,
- c_lib.convertToMLIRSparseTensorI64,
- c_lib.convertFromMLIRSparseTensorI64,
- ),
- (
- np.float16,
- c_lib.convertToMLIRSparseTensorF16,
- c_lib.convertFromMLIRSparseTensorF16,
- ),
- (
- np.float32,
- c_lib.convertToMLIRSparseTensorF32,
- c_lib.convertFromMLIRSparseTensorF32,
- ),
- (
- np.float64,
- c_lib.convertToMLIRSparseTensorF64,
- c_lib.convertFromMLIRSparseTensorF64,
- ),
- (
- np.complex64,
- c_lib.convertToMLIRSparseTensorC32,
- c_lib.convertFromMLIRSparseTensorC32,
- ),
- (
- np.complex128,
- c_lib.convertToMLIRSparseTensorC64,
- c_lib.convertFromMLIRSparseTensorC64,
- ),
- ]
- except Exception as e:
- raise ValueError(f"Missing supporting function: {e}") from e
- for i, info in enumerate(support_types):
- _record_support_funcs(info[0], info[1], info[2], type_to_funcs)
-
- def get_support_funcs(ty: np.dtype):
- funcs = type_to_funcs[ty]
- assert funcs is not None
- return funcs
-
- return get_support_funcs
-
-
-def sparse_tensor_to_coo_tensor(
- sparse_tensor: ctypes.c_void_p,
- dtype: np.dtype,
-) -> Tuple[int, int, np.ndarray, np.ndarray, np.ndarray]:
- """Converts an MLIR sparse tensor to a COO-flavored format tensor.
-
- Args:
- sparse_tensor: A ctypes.c_void_p to the MLIR sparse tensor descriptor.
- dtype: The numpy data type for the tensor elements.
-
- Returns:
- A tuple that contains the following values for the COO-flavored format
- tensor:
- rank: An integer for the rank of the tensor.
- nse: An integer for the number of non-zero values in the tensor.
- shape: A 1D numpy array of integers, for the shape of the tensor.
- values: A 1D numpy array, for the non-zero values in the tensor.
- indices: A 2D numpy array of integers, representing the indices for the
- non-zero values in the tensor.
-
- Raises:
- OSError: If there is any problem in loading the shared library.
- ValueError: If the shared library doesn't contain the needed routines.
- """
- convert_from = _get_support_func_locator()(dtype)[1]
- rank = ctypes.c_ulonglong(0)
- nse = ctypes.c_ulonglong(0)
- shape = ctypes.POINTER(ctypes.c_ulonglong)()
-
- values = ctypes.POINTER(runtime.as_ctype(np.dtype(dtype)))()
- indices = ctypes.POINTER(ctypes.c_ulonglong)()
- convert_from(
- sparse_tensor,
- ctypes.byref(rank),
- ctypes.byref(nse),
- ctypes.byref(shape),
- ctypes.byref(values),
- ctypes.byref(indices),
- )
-
- # Convert the returned values to the corresponding numpy types.
- shape = np.ctypeslib.as_array(shape, shape=[rank.value])
- values = runtime.to_numpy(np.ctypeslib.as_array(values, shape=[nse.value]))
- indices = np.ctypeslib.as_array(indices, shape=[nse.value, rank.value])
- return rank.value, nse.value, shape, values, indices
-
-
-def coo_tensor_to_sparse_tensor(
- np_shape: np.ndarray,
- np_values: np.ndarray,
- np_indices: np.ndarray,
- np_perm: np.ndarray,
- np_sparse: np.ndarray,
-) -> int:
- """Converts a COO-flavored format sparse tensor to an MLIR sparse tensor.
-
- Args:
- np_shape: A 1D numpy array of integers, for the shape of the tensor.
- np_values: A 1D numpy array, for the non-zero values in the tensor.
- np_indices: A 2D numpy array of integers, representing the indices for the
- non-zero values in the tensor.
- np_perm: A 1D numpy array of integers, representing the storage ordering
- for the dimensions.
- np_sparse: A 1D numpy array of uint8, representing the sparsity values
- for the dimensions.
-
- Returns:
- An integer for the non-null ctypes.c_void_p to the MLIR sparse tensor
- descriptor.
-
- Raises:
- OSError: If there is any problem in loading the shared library.
- ValueError: If the shared library doesn't contain the needed routines.
- """
-
- r = len(np_shape)
- rank = ctypes.c_ulonglong(r)
- nse = ctypes.c_ulonglong(len(np_values))
- shape = np_shape.ctypes.data_as(ctypes.POINTER(ctypes.c_ulonglong))
- values = np_values.ctypes.data_as(
- ctypes.POINTER(runtime.as_ctype(np.dtype(np_values.dtype)))
- )
- indices = np_indices.ctypes.data_as(ctypes.POINTER(ctypes.c_ulonglong))
-
- perm = np_perm.ctypes.data_as(ctypes.POINTER(ctypes.c_ulonglong))
- sparse = np_sparse.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8))
-
- convert_to = _get_support_func_locator()(np_values.dtype.type)[0]
- ptr = convert_to(rank, nse, shape, values, indices, perm, sparse)
- assert ptr is not None, "Problem with calling convertToMLIRSparseTensorF64"
- return ptr
-
-
-def compile_and_build_engine(module: ir.Module) -> execution_engine.ExecutionEngine:
- """Compiles an MLIR module and builds a JIT execution engine.
-
- Args:
- module: The MLIR module.
-
- Returns:
- A JIT execution engine for the MLIR module.
-
- """
- return _get_sparse_compiler().compile_and_jit(module)
-
-
-class _SparseTensorDescriptor(ctypes.Structure):
- """A C structure for an MLIR sparse tensor."""
-
- _fields_ = [
- # A pointer for the MLIR sparse tensor storage.
- ("storage", ctypes.POINTER(ctypes.c_ulonglong)),
- # An MLIR MemRef descriptor for the shape of the sparse tensor.
- ("shape", runtime.make_nd_memref_descriptor(1, ctypes.c_ulonglong)),
- ]
-
-
-def _output_one_dim(dim: int, rank: int, shape: str, type: str) -> str:
- """Produces the MLIR text code to output the size for the given dimension."""
- return f"""
- %c{dim} = arith.constant {dim} : index
- %d{dim} = tensor.dim %t, %c{dim} : tensor<{shape}x{type}, #enc>
- memref.store %d{dim}, %b[%c{dim}] : memref<{rank}xindex>
-"""
-
-
-# TODO: With better support from MLIR, we may improve the current implementation
-# by doing the following:
-# (1) Use Python code to generate the kernel instead of doing MLIR text code
-# stitching.
-# (2) Use scf.for instead of an unrolled loop to write out the dimension sizes
-# when tensor.dim supports non-constant dimension value.
-def _get_create_sparse_tensor_kernel(
- sparsity_codes: Sequence[sparse_tensor.DimLevelType], type: str
-) -> str:
- """Creates an MLIR text kernel to contruct a sparse tensor from a file.
-
- The kernel returns a _SparseTensorDescriptor structure.
- """
- rank = len(sparsity_codes)
-
- # Use ? to represent a dimension in the dynamic shape string representation.
- shape = "x".join(map(lambda d: "?", range(rank)))
-
- # Convert the encoded sparsity values to a string representation.
- sparsity = ", ".join(
- map(lambda s: '"compressed"' if s.value else '"dense"', sparsity_codes)
- )
-
- # Get the MLIR text code to write the dimension sizes to the output buffer.
- output_dims = "\n".join(
- map(lambda d: _output_one_dim(d, rank, shape, type), range(rank))
- )
-
- # Return the MLIR text kernel.
- return f"""
-!Ptr = !llvm.ptr<i8>
-#enc = #sparse_tensor.encoding<{{
- lvlTypes = [ {sparsity} ]
-}}>
-func.func @{_ENTRY_NAME}(%filename: !Ptr) -> (tensor<{shape}x{type}, #enc>, memref<{rank}xindex>)
-attributes {{ llvm.emit_c_interface }} {{
- %t = sparse_tensor.new %filename : !Ptr to tensor<{shape}x{type}, #enc>
- %b = memref.alloc() : memref<{rank}xindex>
- {output_dims}
- return %t, %b : tensor<{shape}x{type}, #enc>, memref<{rank}xindex>
-}}"""
-
-
-def create_sparse_tensor(
- filename: str, sparsity: Sequence[sparse_tensor.DimLevelType], type: str
-) -> Tuple[ctypes.c_void_p, np.ndarray]:
- """Creates an MLIR sparse tensor from the input file.
-
- Args:
- filename: A string for the name of the file that contains the tensor data in
- a COO-flavored format.
- sparsity: A sequence of DimLevelType values, one for each dimension of the
- tensor.
-
- Returns:
- A Tuple containing the following values:
- storage: A ctypes.c_void_p for the MLIR sparse tensor storage.
- shape: A 1D numpy array of integers, for the shape of the tensor.
-
- Raises:
- OSError: If there is any problem in loading the supporting C shared library.
- ValueError: If the shared library doesn't contain the needed routine.
- """
- with ir.Context() as ctx, ir.Location.unknown():
- module = _get_create_sparse_tensor_kernel(sparsity, type)
- module = ir.Module.parse(module)
- engine = compile_and_build_engine(module)
-
- # A sparse tensor descriptor to receive the kernel result.
- c_tensor_desc = _SparseTensorDescriptor()
- # Convert the filename to a byte stream.
- c_filename = ctypes.c_char_p(bytes(filename, "utf-8"))
-
- arg_pointers = [
- ctypes.byref(ctypes.pointer(c_tensor_desc)),
- ctypes.byref(c_filename),
- ]
-
- # Invoke the execution engine to run the module and return the result.
- engine.invoke(_ENTRY_NAME, *arg_pointers)
- shape = runtime.ranked_memref_to_numpy(ctypes.pointer(c_tensor_desc.shape))
- return c_tensor_desc.storage, shape
-
-
-# TODO: With better support from MLIR, we may improve the current implementation
-# by using Python code to generate the kernel instead of doing MLIR text code
-# stitching.
-def _get_output_sparse_tensor_kernel(
- sparsity_codes: Sequence[sparse_tensor.DimLevelType], type: str
-) -> str:
- """Creates an MLIR text kernel to output a sparse tensor to a file.
-
- The kernel returns void.
- """
- rank = len(sparsity_codes)
-
- # Use ? to represent a dimension in the dynamic shape string representation.
- shape = "x".join(map(lambda d: "?", range(rank)))
-
- # Convert the encoded sparsity values to a string representation.
- sparsity = ", ".join(
- map(lambda s: '"compressed"' if s.value else '"dense"', sparsity_codes)
- )
-
- # Return the MLIR text kernel.
- return f"""
-!Ptr = !llvm.ptr<i8>
-#enc = #sparse_tensor.encoding<{{
- lvlTypes = [ {sparsity} ]
-}}>
-func.func @{_ENTRY_NAME}(%t: tensor<{shape}x{type}, #enc>, %filename: !Ptr)
-attributes {{ llvm.emit_c_interface }} {{
- sparse_tensor.out %t, %filename : tensor<{shape}x{type}, #enc>, !Ptr
- func.return
-}}"""
-
-
-def output_sparse_tensor(
- tensor: ctypes.c_void_p,
- filename: str,
- sparsity: Sequence[sparse_tensor.DimLevelType],
- type: str,
-) -> None:
- """Outputs an MLIR sparse tensor to the given file.
-
- Args:
- tensor: A C pointer to the MLIR sparse tensor.
- filename: A string for the name of the file that contains the tensor data in
- a COO-flavored format.
- sparsity: A sequence of DimLevelType values, one for each dimension of the
- tensor.
- type: The MLIR string for the data type.
-
- Raises:
- OSError: If there is any problem in loading the supporting C shared library.
- ValueError: If the shared library doesn't contain the needed routine.
- """
- with ir.Context() as ctx, ir.Location.unknown():
- module = _get_output_sparse_tensor_kernel(sparsity, type)
- module = ir.Module.parse(module)
- engine = compile_and_build_engine(module)
-
- # Convert the filename to a byte stream.
- c_filename = ctypes.c_char_p(bytes(filename, "utf-8"))
-
- arg_pointers = [
- ctypes.byref(ctypes.cast(tensor, ctypes.c_void_p)),
- ctypes.byref(c_filename),
- ]
-
- # Invoke the execution engine to run the module and return the result.
- engine.invoke(_ENTRY_NAME, *arg_pointers)
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/tools/mlir_sparse_compiler.py b/mlir/test/Integration/Dialect/SparseTensor/taco/tools/mlir_sparse_compiler.py
deleted file mode 100644
index 8f193b81bb07c43..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/tools/mlir_sparse_compiler.py
+++ /dev/null
@@ -1,41 +0,0 @@
-# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-# See https://llvm.org/LICENSE.txt for license information.
-# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-
-# This file contains the sparse compiler class. It is copied from
-# test/Integration/Dialect/SparseTensor/python/ until we have a better
-# solution.
-
-from mlir import execution_engine
-from mlir import ir
-from mlir import passmanager
-from typing import Sequence
-
-
-class SparseCompiler:
- """Sparse compiler class for compiling and building MLIR modules."""
-
- def __init__(self, options: str, opt_level: int, shared_libs: Sequence[str]):
- pipeline = f"builtin.module(sparse-compiler{{{options} reassociate-fp-reductions=1 enable-index-optimizations=1}})"
- self.pipeline = pipeline
- self.opt_level = opt_level
- self.shared_libs = shared_libs
-
- def __call__(self, module: ir.Module):
- """Convenience application method."""
- self.compile(module)
-
- def compile(self, module: ir.Module):
- """Compiles the module by invoking the sparse copmiler pipeline."""
- passmanager.PassManager.parse(self.pipeline).run(module.operation)
-
- def jit(self, module: ir.Module) -> execution_engine.ExecutionEngine:
- """Wraps the module in a JIT execution engine."""
- return execution_engine.ExecutionEngine(
- module, opt_level=self.opt_level, shared_libs=self.shared_libs
- )
-
- def compile_and_jit(self, module: ir.Module) -> execution_engine.ExecutionEngine:
- """Compiles and jits the module."""
- self.compile(module)
- return self.jit(module)
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/tools/testing_utils.py b/mlir/test/Integration/Dialect/SparseTensor/taco/tools/testing_utils.py
deleted file mode 100644
index 1be88fa8bd7092c..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/tools/testing_utils.py
+++ /dev/null
@@ -1,47 +0,0 @@
-# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-# See https://llvm.org/LICENSE.txt for license information.
-# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-
-# This file contains the utilities to support testing.
-
-import numpy as np
-
-
-def compare_sparse_tns(expected: str, actual: str, rtol: float = 0.0001) -> bool:
- """Compares sparse tensor actual output file with expected output file.
-
- This routine assumes the input files are in FROSTT format. See
- http://frostt.io/tensors/file-formats.html for FROSTT (.tns) format.
-
- It also assumes the first line in the output file is a comment line.
-
- """
- with open(actual, "r") as actual_f:
- with open(expected, "r") as expected_f:
- # Skip the first comment line.
- _ = actual_f.readline()
- _ = expected_f.readline()
-
- # Compare the two lines of meta data
- if (
- actual_f.readline() != expected_f.readline()
- or actual_f.readline() != expected_f.readline()
- ):
- return FALSE
-
- actual_data = np.loadtxt(actual, np.float64, skiprows=3)
- expected_data = np.loadtxt(expected, np.float64, skiprows=3)
- return np.allclose(actual_data, expected_data, rtol=rtol)
-
-
-def file_as_string(file: str) -> str:
- """Returns contents of file as string."""
- with open(file, "r") as f:
- return f.read()
-
-
-def run_test(f):
- """Prints the test name and runs the test."""
- print(f.__name__)
- f()
- return f
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/unit_test_tensor_core.py b/mlir/test/Integration/Dialect/SparseTensor/taco/unit_test_tensor_core.py
deleted file mode 100644
index 45ce446478dee98..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/unit_test_tensor_core.py
+++ /dev/null
@@ -1,647 +0,0 @@
-# RUN: env SUPPORTLIB=%mlir_c_runner_utils %PYTHON %s | FileCheck %s
-
-from string import Template
-
-import numpy as np
-import os
-import sys
-import tempfile
-
-_SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
-sys.path.append(_SCRIPT_PATH)
-from tools import mlir_pytaco
-from tools import testing_utils as testing_utils
-
-# Define the aliases to shorten the code.
-_COMPRESSED = mlir_pytaco.ModeFormat.COMPRESSED
-_DENSE = mlir_pytaco.ModeFormat.DENSE
-
-
-def _init_3d(T, I, J, K):
- for i in range(I):
- for j in range(J):
- for k in range(K):
- T.insert([i, j, k], i + j + k + 1)
-
-
-def _init_2d(T, I, J):
- for i in range(I):
- for j in range(J):
- T.insert([i, j], i + j + 1)
-
-
-def _init_1d_with_value(T, I, v):
- for i in range(I):
- T.insert([i], v)
-
-
-def test_expect_error(name, code, error):
- """Executes the code then verifies the expected error message."""
- try:
- exec(code)
- except ValueError as e:
- passed = "passed" if (str(e).startswith(error)) else "failed"
- print(f"test_{name}: {passed}")
-
-
-# CHECK-LABEL: test_tensor_dtype
- at testing_utils.run_test
-def test_tensor_dtype():
- passed = mlir_pytaco.DType(mlir_pytaco.Type.INT16).is_int()
- passed += mlir_pytaco.DType(mlir_pytaco.Type.INT32).is_int()
- passed += mlir_pytaco.DType(mlir_pytaco.Type.INT64).is_int()
- passed += mlir_pytaco.DType(mlir_pytaco.Type.FLOAT32).is_float()
- passed += mlir_pytaco.DType(mlir_pytaco.Type.FLOAT64).is_float()
- # CHECK: Number of passed: 5
- print("Number of passed:", passed)
-
-
-# CHECK: test_mode_ordering_not_int: passed
-test_expect_error(
- "mode_ordering_not_int",
- "m = mlir_pytaco.ModeOrdering(['x'])",
- "Ordering must be a list of integers",
-)
-
-# CHECK: test_mode_ordering_not_permutation: passed
-test_expect_error(
- "mode_ordering_not_permutation",
- "m = mlir_pytaco.ModeOrdering([2, 1])",
- "Invalid ordering",
-)
-
-# CHECK: test_mode_format_invalid: passed
-test_expect_error(
- "mode_format_invalid",
- "m = mlir_pytaco.ModeFormatPack(['y'])",
- "Formats must be a list of ModeFormat",
-)
-
-# CHECK: test_expect_mode_format_pack: passed
-test_expect_error(
- "expect_mode_format_pack",
- (
- """
-mode_ordering = mlir_pytaco.ModeOrdering([0, 1, 2])
-f = mlir_pytaco.Format(["x"], mode_ordering)
- """
- ),
- "Expected a list of ModeFormat",
-)
-
-# CHECK: test_expect_mode_ordering: passed
-test_expect_error(
- "expect_mode_ordering",
- (
- """
-mode_format_pack = mlir_pytaco.ModeFormatPack([_COMPRESSED, _COMPRESSED])
-f = mlir_pytaco.Format(mode_format_pack, "x")
- """
- ),
- "Expected ModeOrdering",
-)
-
-# CHECK: test_inconsistent_mode_format_pack_and_mode_ordering: passed
-test_expect_error(
- "inconsistent_mode_format_pack_and_mode_ordering",
- (
- """
-mode_format_pack = mlir_pytaco.ModeFormatPack([_COMPRESSED, _COMPRESSED])
-mode_ordering = mlir_pytaco.ModeOrdering([0, 1, 2])
-f = mlir_pytaco.Format(mode_format_pack, mode_ordering)
- """
- ),
- "Inconsistent ModeFormatPack and ModeOrdering",
-)
-
-
-# CHECK-LABEL: test_format_default_ordering
- at testing_utils.run_test
-def test_format_default_ordering():
- f = mlir_pytaco.Format([_COMPRESSED, _COMPRESSED])
- passed = 0
- passed += np.array_equal(f.ordering.ordering, [0, 1])
- # CHECK: Number of passed: 1
- print("Number of passed:", passed)
-
-
-# CHECK-LABEL: test_format_explicit_ordering
- at testing_utils.run_test
-def test_format_explicit_ordering():
- f = mlir_pytaco.Format([_COMPRESSED, _DENSE], [1, 0])
- passed = 0
- passed += np.array_equal(f.ordering.ordering, [1, 0])
- # CHECK: Number of passed: 1
- print("Number of passed:", passed)
-
-
-# CHECK-LABEL: test_index_var
- at testing_utils.run_test
-def test_index_var():
- i = mlir_pytaco.IndexVar()
- j = mlir_pytaco.IndexVar()
- passed = i.name != j.name
-
- vars = mlir_pytaco.get_index_vars(10)
- passed += len(vars) == 10
- passed += all([isinstance(e, mlir_pytaco.IndexVar) for e in vars])
-
- # CHECK: Number of passed: 3
- print("Number of passed:", passed)
-
-
-# CHECK: test_tensor_invalid_first_argument: passed
-test_expect_error(
- "tensor_invalid_first_argument",
- "t = mlir_pytaco.Tensor('f')",
- "Invalid first argument",
-)
-
-# CHECK: test_tensor_inconsistent_shape_and_format: passed
-test_expect_error(
- "tensor_inconsistent_shape_and_format",
- (
- """
-mode_format_pack = mlir_pytaco.ModeFormatPack([_COMPRESSED, _COMPRESSED])
-mode_ordering = mlir_pytaco.ModeOrdering([0, 1])
-f = mlir_pytaco.Format(mode_format_pack, mode_ordering)
-t = mlir_pytaco.Tensor([3], f)
- """
- ),
- "Inconsistent shape and format",
-)
-
-# CHECK: test_tensor_invalid_format: passed
-test_expect_error(
- "tensor_invalid_format",
- "t = mlir_pytaco.Tensor([3], 'f')",
- "Invalid format argument",
-)
-
-# CHECK: test_tensor_insert_nonlist_coordinate: passed
-test_expect_error(
- "tensor_insert_nonlist_coordinate",
- (
- """
-t = mlir_pytaco.Tensor([3])
-t.insert(1, 0)
- """
- ),
- "Non list coordinate detected",
-)
-
-# CHECK: test_tensor_insert_too_much_coordinate: passed
-test_expect_error(
- "tensor_insert_too_much_coordinate",
- (
- """
-t = mlir_pytaco.Tensor([3])
-t.insert([0, 0], 0)
- """
- ),
- "Invalid coordinate",
-)
-
-# CHECK: test_tensor_insert_coordinate_outof_range: passed
-test_expect_error(
- "tensor_insert_coordinate_outof_range",
- (
- """
-t = mlir_pytaco.Tensor([1, 1])
-t.insert([1, 0], 0)
- """
- ),
- "Invalid coordinate",
-)
-
-# CHECK: test_tensor_insert_coordinate_nonint: passed
-test_expect_error(
- "tensor_insert_coordinate_nonint",
- (
- """
-t = mlir_pytaco.Tensor([1, 1])
-t.insert([0, "xy"], 0)
- """
- ),
- "Non integer coordinate detected",
-)
-
-# CHECK: test_tensor_insert_invalid_value: passed
-test_expect_error(
- "tensor_insert_invalid_value",
- (
- """
-t = mlir_pytaco.Tensor([1, 1])
-t.insert([0, 0], "x")
- """
- ),
- "Value is neither int nor float",
-)
-
-# CHECK: test_access_non_index_var_index: passed
-test_expect_error(
- "access_non_index_var_index",
- (
- """
-t = mlir_pytaco.Tensor([5, 6])
-i = mlir_pytaco.IndexVar()
-a = mlir_pytaco.Access(t, (i, "j"))
- """
- ),
- "Indices contain non IndexVar",
-)
-
-# CHECK: test_access_inconsistent_rank_indices: passed
-test_expect_error(
- "access_inconsistent_rank_indices",
- (
- """
-t = mlir_pytaco.Tensor([5, 6])
-i = mlir_pytaco.IndexVar()
-a = mlir_pytaco.Access(t, (i,))
- """
- ),
- "Invalid indices for rank",
-)
-
-# CHECK: test_access_invalid_indices_for_rank: passed
-test_expect_error(
- "access_invalid_indices_for_rank",
- (
- """
-t = mlir_pytaco.Tensor([5, 6])
-i, j, k = mlir_pytaco.get_index_vars(3)
-a = mlir_pytaco.Access(t, (i,j, k))
- """
- ),
- "Invalid indices for rank",
-)
-
-# CHECK: test_invalid_indices: passed
-test_expect_error(
- "invalid_indices",
- (
- """
-i, j = mlir_pytaco.get_index_vars(2)
-A = mlir_pytaco.Tensor([2, 3])
-B = mlir_pytaco.Tensor([2, 3])
-C = mlir_pytaco.Tensor([2, 3], _DENSE)
-C[i, j] = A[1, j] + B[i, j]
- """
- ),
- "Expected IndexVars",
-)
-
-# CHECK: test_inconsistent_rank_indices: passed
-test_expect_error(
- "inconsistent_rank_indices",
- (
- """
-i, j = mlir_pytaco.get_index_vars(2)
-A = mlir_pytaco.Tensor([2, 3])
-C = mlir_pytaco.Tensor([2, 3], _DENSE)
-C[i, j] = A[i]
- """
- ),
- "Invalid indices for rank",
-)
-
-# CHECK: test_destination_index_not_used_in_source: passed
-test_expect_error(
- "destination_index_not_used_in_source",
- (
- """
-i, j = mlir_pytaco.get_index_vars(2)
-A = mlir_pytaco.Tensor([3])
-C = mlir_pytaco.Tensor([3], _DENSE)
-C[j] = A[i]
-C.evaluate()
- """
- ),
- "Destination IndexVar not used in the source expression",
-)
-
-# CHECK: test_destination_dim_not_consistent_with_source: passed
-test_expect_error(
- "destination_dim_not_consistent_with_source",
- (
- """
-i = mlir_pytaco.IndexVar()
-A = mlir_pytaco.Tensor([3])
-C = mlir_pytaco.Tensor([5], _DENSE)
-C[i] = A[i]
-C.evaluate()
- """
- ),
- "Inconsistent destination dimension for IndexVar",
-)
-
-# CHECK: test_inconsistent_source_dim: passed
-test_expect_error(
- "inconsistent_source_dim",
- (
- """
-i = mlir_pytaco.IndexVar()
-A = mlir_pytaco.Tensor([3])
-B = mlir_pytaco.Tensor([5])
-C = mlir_pytaco.Tensor([3], _DENSE)
-C[i] = A[i] + B[i]
-C.evaluate()
- """
- ),
- "Inconsistent source dimension for IndexVar",
-)
-
-# CHECK: test_index_var_outside_domain: passed
-test_expect_error(
- "index_var_outside_domain",
- (
- """
-i, j = mlir_pytaco.get_index_vars(2)
-A = mlir_pytaco.Tensor([3])
-B = mlir_pytaco.Tensor([3])
-B[i] = A[i] + j
-B.evaluate()
- """
- ),
- "IndexVar is not part of the iteration domain",
-)
-
-
-# CHECK-LABEL: test_tensor_all_dense_sparse
- at testing_utils.run_test
-def test_tensor_all_dense_sparse():
- a = mlir_pytaco.Tensor([4], [_DENSE])
- passed = not a.is_dense()
- passed += a.order == 1
- passed += a.shape[0] == 4
- # CHECK: Number of passed: 3
- print("Number of passed:", passed)
-
-
-# CHECK-LABEL: test_tensor_true_dense
- at testing_utils.run_test
-def test_tensor_true_dense():
- a = mlir_pytaco.Tensor.from_array(np.random.uniform(size=5))
- passed = a.is_dense()
- passed += a.order == 1
- passed += a.shape[0] == 5
- # CHECK: Number of passed: 3
- print("Number of passed:", passed)
-
-
-# CHECK-LABEL: test_tensor_copy
- at testing_utils.run_test
-def test_tensor_copy():
- i, j = mlir_pytaco.get_index_vars(2)
- I = 2
- J = 3
- A = mlir_pytaco.Tensor([I, J])
- A.insert([0, 1], 5.0)
- A.insert([1, 2], 6.0)
- B = mlir_pytaco.Tensor([I, J])
- B[i, j] = A[i, j]
- passed = B._assignment is not None
- passed += B._engine is None
- try:
- B.compute()
- except ValueError as e:
- passed += str(e).startswith("Need to invoke compile")
- B.compile()
- passed += B._engine is not None
- B.compute()
- passed += B._assignment is None
- passed += B._engine is None
- indices, values = B.get_coordinates_and_values()
- passed += np.array_equal(indices, [[0, 1], [1, 2]])
- passed += np.allclose(values, [5.0, 6.0])
- # No temporary tensor is used.
- passed += B._stats.get_total() == 0
- # CHECK: Number of passed: 9
- print("Number of passed:", passed)
-
-
-# CHECK-LABEL: test_tensor_trivial_reduction
- at testing_utils.run_test
-def test_tensor_trivial_reduction():
- i, j = mlir_pytaco.get_index_vars(2)
- I = 2
- J = 3
- A = mlir_pytaco.Tensor([I, J])
- A.insert([0, 1], 5.0)
- A.insert([0, 2], 3.0)
- A.insert([1, 2], 6.0)
- B = mlir_pytaco.Tensor([I])
- B[i] = A[i, j]
- indices, values = B.get_coordinates_and_values()
- passed = np.array_equal(indices, [[0], [1]])
- passed += np.allclose(values, [8.0, 6.0])
- # No temporary tensor is used.
- passed += B._stats.get_total() == 0
-
- # CHECK: Number of passed: 3
- print("Number of passed:", passed)
-
-
-# CHECK-LABEL: test_binary_add
- at testing_utils.run_test
-def test_binary_add():
- i = mlir_pytaco.IndexVar()
- A = mlir_pytaco.Tensor([4])
- B = mlir_pytaco.Tensor([4])
- C = mlir_pytaco.Tensor([4])
- A.insert([1], 10)
- A.insert([2], 1)
- B.insert([3], 20)
- B.insert([2], 2)
- C[i] = A[i] + B[i]
- indices, values = C.get_coordinates_and_values()
- passed = np.array_equal(indices, [[1], [2], [3]])
- passed += np.array_equal(values, [10.0, 3.0, 20.0])
- # No temporary tensor is used.
- passed += C._stats.get_total() == 0
- # CHECK: Number of passed: 3
- print("Number of passed:", passed)
-
-
-# CHECK-LABEL: test_binary_add_sub
- at testing_utils.run_test
-def test_binary_add_sub():
- i = mlir_pytaco.IndexVar()
- j = mlir_pytaco.IndexVar()
- A = mlir_pytaco.Tensor([2, 3])
- B = mlir_pytaco.Tensor([2, 3])
- C = mlir_pytaco.Tensor([2, 3])
- D = mlir_pytaco.Tensor([2, 3])
- A.insert([0, 1], 10)
- A.insert([1, 2], 40)
- B.insert([0, 0], 20)
- B.insert([1, 2], 30)
- C.insert([0, 1], 5)
- C.insert([1, 2], 7)
- D[i, j] = A[i, j] + B[i, j] - C[i, j]
- indices, values = D.get_coordinates_and_values()
- passed = np.array_equal(indices, [[0, 0], [0, 1], [1, 2]])
- passed += np.array_equal(values, [20.0, 5.0, 63.0])
- # No temporary tensor is used.
- passed += D._stats.get_total() == 0
- # CHECK: Number of passed: 3
- print("Number of passed:", passed)
-
-
-# CHECK-LABEL: test_binary_mul_add
- at testing_utils.run_test
-def test_binary_mul_add():
- i = mlir_pytaco.IndexVar()
- j = mlir_pytaco.IndexVar()
- A = mlir_pytaco.Tensor([2, 3])
- B = mlir_pytaco.Tensor([2, 3])
- C = mlir_pytaco.Tensor([2, 3])
- D = mlir_pytaco.Tensor([2, 3])
- A.insert([0, 1], 10)
- A.insert([1, 2], 40)
- B.insert([0, 0], 20)
- B.insert([1, 2], 30)
- C.insert([0, 1], 5)
- C.insert([1, 2], 7)
- D[i, j] = A[i, j] * C[i, j] + B[i, j]
- indices, values = D.get_coordinates_and_values()
- passed = np.array_equal(indices, [[0, 0], [0, 1], [1, 2]])
- passed += np.array_equal(values, [20.0, 50.0, 310.0])
- # No temporary tensor is used.
- passed += D._stats.get_total() == 0
- # CHECK: Number of passed: 3
- print("Number of passed:", passed)
-
-
-# CHECK-LABEL: test_binary_add_reduce_at_root
- at testing_utils.run_test
-def test_binary_add_reduce_at_root():
- i = mlir_pytaco.IndexVar()
- j = mlir_pytaco.IndexVar()
- A = mlir_pytaco.Tensor([2, 3])
- B = mlir_pytaco.Tensor([2, 3])
- C = mlir_pytaco.Tensor([2], _DENSE)
- A.insert([0, 1], 10)
- A.insert([1, 2], 40)
- B.insert([0, 0], 20)
- B.insert([1, 2], 30)
- C[i] = A[i, j] + B[i, j]
- indices, values = C.get_coordinates_and_values()
- passed = np.array_equal(indices, [[0], [1]])
- passed += np.array_equal(values, [30.0, 70.0])
- # No temporary tensor is used.
- passed += C._stats.get_total() == 0
- # CHECK: Number of passed: 3
- print("Number of passed:", passed)
-
-
-# CHECK-LABEL: test_binary_add_reduce_at_child
- at testing_utils.run_test
-def test_binary_add_reduce_at_child():
- i = mlir_pytaco.IndexVar()
- j = mlir_pytaco.IndexVar()
- I = 2
- J = 3
- A = mlir_pytaco.Tensor([I, J])
- B = mlir_pytaco.Tensor([J])
- C = mlir_pytaco.Tensor([I])
- D = mlir_pytaco.Tensor([I], _DENSE)
-
- _init_2d(A, I, J)
- _init_1d_with_value(C, I, 2)
- _init_1d_with_value(B, J, 1)
-
- D[i] = A[i, j] * B[j] + C[i]
- indices, values = D.get_coordinates_and_values()
- passed = np.array_equal(indices, [[0], [1]])
- passed += np.array_equal(values, [8.0, 11.0])
-
- # The expression is implemented as:
- # temp0[i] = A[i, j] * B[i]
- # D[i] = temp0[i] + C[i]
- # Check the temporary tensor introduced by the implementation.
- stats = D._stats
- passed += stats.get_total() == 1
- passed += stats.get_formats(0) == (_COMPRESSED,)
- passed += stats.get_dimensions(0) == (I,)
- # CHECK: Number of passed: 5
- print("Number of passed:", passed)
-
-
-# CHECK-LABEL: test_binary_add_reduce_3d_1
- at testing_utils.run_test
-def test_binary_add_reduce_3d_1():
- i, j, k, l = mlir_pytaco.get_index_vars(4)
- I = 2
- J = 3
- K = 4
- L = 5
- A = mlir_pytaco.Tensor([I, J, K])
- B = mlir_pytaco.Tensor([I, J, L])
- C = mlir_pytaco.Tensor([K])
- D = mlir_pytaco.Tensor([L])
- E = mlir_pytaco.Tensor([I], _DENSE)
-
- _init_3d(A, I, J, K)
- _init_3d(B, I, J, L)
- _init_1d_with_value(C, K, 1)
- _init_1d_with_value(D, L, 2)
-
- E[i] = A[i, j, k] * C[k] + B[i, j, l] * D[l]
- indices, values = E.get_coordinates_and_values()
- passed = np.array_equal(indices, [[0], [1]])
- passed += np.array_equal(values, [162.0, 204.0])
-
- # The expression is implemented as:
- # temp0[i, j] = A[i, j, k] * C[k]
- # temp1[i, j] = B[i, j, l] * D[l]
- # E[i] = temp0[i, j] + temp1[i, j]
- # Check the two temporary tensors introduced by the implementation.
- stats = E._stats
- passed += stats.get_total() == 2
- passed += stats.get_formats(0) == (_COMPRESSED, _COMPRESSED)
- passed += stats.get_dimensions(0) == (I, J)
- passed += stats.get_formats(1) == (_COMPRESSED, _COMPRESSED)
- passed += stats.get_dimensions(1) == (I, J)
- # CHECK: Number of passed: 7
- print("Number of passed:", passed)
-
-
-# CHECK-LABEL: test_binary_add_reduce_3d_2
- at testing_utils.run_test
-def test_binary_add_reduce_3d_2():
- i, j, k, l = mlir_pytaco.get_index_vars(4)
- I = 2
- J = 3
- K = 4
- L = 5
- A = mlir_pytaco.Tensor([I, J, K], [_COMPRESSED, _COMPRESSED, _DENSE])
- B = mlir_pytaco.Tensor([I, L, K], [_DENSE, _COMPRESSED, _COMPRESSED])
- C = mlir_pytaco.Tensor([J, K], [_COMPRESSED, _COMPRESSED])
- D = mlir_pytaco.Tensor([L])
- E = mlir_pytaco.Tensor([I], _DENSE)
-
- _init_3d(A, I, J, K)
- _init_3d(B, I, L, K)
- _init_2d(C, J, K)
- _init_1d_with_value(D, L, 2)
-
- E[i] = A[i, j, k] + C[j, k] + B[i, l, k] * D[l]
- indices, values = E.get_coordinates_and_values()
- passed = np.array_equal(indices, [[0], [1]])
- passed += np.array_equal(values, [264.0, 316.0])
-
- # The expression is implemented as:
- # temp0[i, k] = A[i, j, k] + C[j, k]
- # temp1[i, k] = B[i, l, k] * D[l]
- # E[i] = temp0[i, k] + temp1[i, k]
- # Check the two temporary tensors introduced by the implementation.
- stats = E._stats
- passed += stats.get_total() == 2
- passed += stats.get_formats(0) == (_COMPRESSED, _DENSE)
- passed += stats.get_dimensions(0) == (I, K)
- passed += stats.get_formats(1) == (_DENSE, _COMPRESSED)
- passed += stats.get_dimensions(1) == (I, K)
- # CHECK: Number of passed: 7
- print("Number of passed:", passed)
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/unit_test_tensor_io.py b/mlir/test/Integration/Dialect/SparseTensor/taco/unit_test_tensor_io.py
deleted file mode 100644
index 1d5274759b6a968..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/unit_test_tensor_io.py
+++ /dev/null
@@ -1,116 +0,0 @@
-# RUN: env SUPPORTLIB=%mlir_c_runner_utils %PYTHON %s | FileCheck %s
-
-from string import Template
-
-import numpy as np
-import os
-import sys
-import tempfile
-
-_SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
-sys.path.append(_SCRIPT_PATH)
-from tools import mlir_pytaco
-from tools import mlir_pytaco_io
-from tools import mlir_pytaco_utils as pytaco_utils
-from tools import testing_utils as testing_utils
-
-
-# Define the aliases to shorten the code.
-_COMPRESSED = mlir_pytaco.ModeFormat.COMPRESSED
-_DENSE = mlir_pytaco.ModeFormat.DENSE
-
-
-_FORMAT = mlir_pytaco.Format([_COMPRESSED, _COMPRESSED])
-_MTX_DATA = """%%MatrixMarket matrix coordinate real general
-3 3 3
-3 1 3
-1 2 2
-3 2 4
-"""
-
-
-# CHECK-LABEL: test_read_mtx_matrix_general
- at testing_utils.run_test
-def test_read_mtx_matrix_general():
- with tempfile.TemporaryDirectory() as test_dir:
- file_name = os.path.join(test_dir, "data.mtx")
- with open(file_name, "w") as file:
- file.write(_MTX_DATA)
- a = mlir_pytaco_io.read(file_name, _FORMAT)
- passed = 0
- # The value of a is stored as an MLIR sparse tensor.
- passed += not a.is_unpacked()
- a.unpack()
- passed += a.is_unpacked()
- coords, values = a.get_coordinates_and_values()
- passed += np.array_equal(coords, [[0, 1], [2, 0], [2, 1]])
- passed += np.allclose(values, [2.0, 3.0, 4.0])
- # CHECK: 4
- print(passed)
-
-
-_TNS_DATA = """2 3
-3 2
-3 1 3
-1 2 2
-3 2 4
-"""
-
-
-# CHECK-LABEL: test_read_tns
- at testing_utils.run_test
-def test_read_tns():
- with tempfile.TemporaryDirectory() as test_dir:
- file_name = os.path.join(test_dir, "data.tns")
- with open(file_name, "w") as file:
- file.write(_TNS_DATA)
- a = mlir_pytaco_io.read(file_name, _FORMAT)
- passed = 0
- # The value of a is stored as an MLIR sparse tensor.
- passed += not a.is_unpacked()
- a.unpack()
- passed += a.is_unpacked()
- coords, values = a.get_coordinates_and_values()
- passed += np.array_equal(coords, [[0, 1], [2, 0], [2, 1]])
- passed += np.allclose(values, [2.0, 3.0, 4.0])
- # CHECK: 4
- print(passed)
-
-
-# CHECK-LABEL: test_write_unpacked_tns
- at testing_utils.run_test
-def test_write_unpacked_tns():
- a = mlir_pytaco.Tensor([2, 3])
- a.insert([0, 1], 10)
- a.insert([1, 2], 40)
- a.insert([0, 0], 20)
- with tempfile.TemporaryDirectory() as test_dir:
- file_name = os.path.join(test_dir, "data.tns")
- try:
- mlir_pytaco_io.write(file_name, a)
- except ValueError as e:
- # CHECK: Writing unpacked sparse tensors to file is not supported
- print(e)
-
-
-# CHECK-LABEL: test_write_packed_tns
- at testing_utils.run_test
-def test_write_packed_tns():
- a = mlir_pytaco.Tensor([2, 3])
- a.insert([0, 1], 10)
- a.insert([1, 2], 40)
- a.insert([0, 0], 20)
- b = mlir_pytaco.Tensor([2, 3])
- i, j = mlir_pytaco.get_index_vars(2)
- b[i, j] = a[i, j] + a[i, j]
- with tempfile.TemporaryDirectory() as test_dir:
- file_name = os.path.join(test_dir, "data.tns")
- mlir_pytaco_io.write(file_name, b)
- with open(file_name, "r") as file:
- lines = file.readlines()
- passed = 0
- # Skip the comment line in the output.
- if lines[1:] == ["2 3\n", "2 3\n", "1 1 40\n", "1 2 20\n", "2 3 80\n"]:
- passed = 1
- # CHECK: 1
- print(passed)
diff --git a/mlir/test/Integration/Dialect/SparseTensor/taco/unit_test_tensor_utils.py b/mlir/test/Integration/Dialect/SparseTensor/taco/unit_test_tensor_utils.py
deleted file mode 100644
index 1344f4aa741ab9b..000000000000000
--- a/mlir/test/Integration/Dialect/SparseTensor/taco/unit_test_tensor_utils.py
+++ /dev/null
@@ -1,135 +0,0 @@
-# RUN: env SUPPORTLIB=%mlir_c_runner_utils %PYTHON %s | FileCheck %s
-
-from typing import Sequence
-import dataclasses
-import numpy as np
-import os
-import sys
-import tempfile
-
-from mlir.dialects import sparse_tensor
-
-_SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
-sys.path.append(_SCRIPT_PATH)
-from tools import mlir_pytaco
-from tools import mlir_pytaco_utils as pytaco_utils
-
-# Define the aliases to shorten the code.
-_COMPRESSED = mlir_pytaco.ModeFormat.COMPRESSED
-_DENSE = mlir_pytaco.ModeFormat.DENSE
-
-
-def _to_string(s: Sequence[int]) -> str:
- """Converts a sequence of integer to a space separated value string."""
- return " ".join(map(lambda e: str(e), s))
-
-
-def _add_one(s: Sequence[int]) -> Sequence[int]:
- """Adds one to each element in the sequence of integer."""
- return [i + 1 for i in s]
-
-
- at dataclasses.dataclass(frozen=True)
-class _SparseTensorCOO:
- """Values for a COO-flavored format sparse tensor.
-
- Attributes:
- rank: An integer rank for the tensor.
- nse: An integer for the number of non-zero values.
- shape: A sequence of integer for the dimension size.
- values: A sequence of float for the non-zero values of the tensor.
- indices: A sequence of coordinate, each coordinate is a sequence of integer.
- """
-
- rank: int
- nse: int
- shape: Sequence[int]
- values: Sequence[float]
- indices: Sequence[Sequence[int]]
-
-
-def _coo_values_to_tns_format(t: _SparseTensorCOO) -> str:
- """Converts a sparse tensor COO-flavored values to TNS text format."""
- # The coo_value_str contains one line for each (coordinate value) pair.
- # Indices are 1-based in TNS text format but 0-based in MLIR.
- coo_value_str = "\n".join(
- map(
- lambda i: _to_string(_add_one(t.indices[i])) + " " + str(t.values[i]),
- range(t.nse),
- )
- )
-
- # Returns the TNS text format representation for the tensor.
- return f"""{t.rank} {t.nse}
-{_to_string(t.shape)}
-{coo_value_str}
-"""
-
-
-def _implement_read_tns_test(
- t: _SparseTensorCOO, sparsity_codes: Sequence[sparse_tensor.DimLevelType]
-) -> int:
- tns_data = _coo_values_to_tns_format(t)
-
- # Write sparse tensor data to a file.
- with tempfile.TemporaryDirectory() as test_dir:
- file_name = os.path.join(test_dir, "data.tns")
- with open(file_name, "w") as file:
- file.write(tns_data)
-
- # Read the data from the file and construct an MLIR sparse tensor.
- sparse_tensor, o_shape = pytaco_utils.create_sparse_tensor(
- file_name, sparsity_codes, "f64"
- )
-
- passed = 0
-
- # Verify the output shape for the tensor.
- if np.array_equal(o_shape, t.shape):
- passed += 1
-
- # Use the output MLIR sparse tensor pointer to retrieve the COO-flavored
- # values and verify the values.
- (
- o_rank,
- o_nse,
- o_shape,
- o_values,
- o_indices,
- ) = pytaco_utils.sparse_tensor_to_coo_tensor(sparse_tensor, np.float64)
- if (
- o_rank == t.rank
- and o_nse == t.nse
- and np.array_equal(o_shape, t.shape)
- and np.allclose(o_values, t.values)
- and np.array_equal(o_indices, t.indices)
- ):
- passed += 1
-
- return passed
-
-
-# A 2D sparse tensor data in COO-flavored format.
-_rank = 2
-_nse = 3
-_shape = [4, 5]
-_values = [3.0, 2.0, 4.0]
-_indices = [[0, 4], [1, 0], [3, 1]]
-
-_t = _SparseTensorCOO(_rank, _nse, _shape, _values, _indices)
-_s = [_COMPRESSED, _COMPRESSED]
-# CHECK: PASSED 2D: 2
-print("PASSED 2D: ", _implement_read_tns_test(_t, _s))
-
-
-# A 3D sparse tensor data in COO-flavored format.
-_rank = 3
-_nse = 3
-_shape = [2, 5, 4]
-_values = [3.0, 2.0, 4.0]
-_indices = [[0, 4, 3], [1, 3, 0], [1, 3, 1]]
-
-_t = _SparseTensorCOO(_rank, _nse, _shape, _values, _indices)
-_s = [_DENSE, _COMPRESSED, _COMPRESSED]
-# CHECK: PASSED 3D: 2
-print("PASSED 3D: ", _implement_read_tns_test(_t, _s))
More information about the Mlir-commits
mailing list