Manuscript Offprint
arXiv:2609.06328SparseConflicts: Handling Conflicting Data Layouts in Sparse Tensor Contractions
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
ADHITHA DIAS, Purdue University, USA
KIRSHANTHAN SUNDARARAJAH, Virginia Tech, USA
ARTEM PELENITSYN, Purdue University, USA
MILIND KULKARNI, Purdue University, USA
Optimizing sparse tensor computations is challenging due to the use of compressed storage formats, which leads to non-affine loop nests and a vast, complex schedule space. The performance of a given schedule is sensitive to the sparsity pattern of the input tensors, making it difficult to find a single optimal solution. When input tensors in the same tensor contraction have conflicting data layouts in relation to the iteration order, it requires costly—both in time and memory—layout transformation, such as transposition. A promising but under-explored alternative is to generate a schedule that avoids explicit transposition, but this has not been systematically supported in existing compilers.
This paper presents a new code generation strategy that generalizes the intermediate representation of the TACO sparse tensor compiler to generate a single loop nest, circumventing explicit transposition of tensors when the tensors have conflicting data layout iteration orders. We extend TACO's iteration graph to express a search-based strategy for locating elements in tensors with conflicting layouts, and we introduce new intermediate representation nodes to lower these schedules to efficient code. This enables the systematic generation of loops that do not require explicit transposition, thus avoiding the overhead of materializing temporary tensors.
We evaluate our approach on a set of sparse tensor contractions using both real-world and synthetic datasets. Our results demonstrate that for computations with misaligned data layouts, our fused approach achieves up to 2× speedup for some sparsity patterns over the traditional approach of explicitly creating a transposed temporary. We also provide guidelines for when this new scheduling strategy is likely to be beneficial.
CCS Concepts: • Software and its engineering → Source code generation; Domain specific languages.
Additional Key Words and Phrases: Sparse Tensor Algebra, Loop Transformations, Tensor Transposition
1 INTRODUCTION
Sparse tensor computations are key components in many scientific computing areas, including, but not limited to numerical simulations, data analysis, and machine learning applications [Hirato 2003; Hu et al. 2020; Markov 2008; Rahman et al. 2021; Ran et al. 2017, 2020]. Sparse tensors are often represented using compressed storage formats such as Compressed Sparse Row (CSR) or Compressed Sparse Fiber (CSF) to save memory and improve computational efficiency [Chou et al. 2018]. Memory saving comes from storing only the non-zero elements of the tensor along with their indices, while computation efficiency is achieved by not performing operations on zero elements (i.e., and ). Using these compressed storage formats makes it challenging to perform tensor operations directly on the compressed data because it requires iteration over the non-zero elements and their indices, which can be complex compared to dense tensor operations [Chou et al. 2018; Kjolstad et al. 2017].
A key challenge in optimizing sparse tensor computations is minimizing the overhead associated with accessing and manipulating compressed data structures. The use of compressed storage
Authors' Contact Information: Adithita Dias, Electrical and Computer Engineering, Purdue University, West Lafayette, IN, USA, kadithita@purdue.edu; Kirshanthan Sundararajah, Computer Science, Virginia Tech, Blacksburg, VA, USA, kirshanthans@vt.edu; Artem Pelenitsyn, Electrical and Computer Engineering, Purdue University, West Lafayette, IN, USA, apelenit@purdue.edu; Milind Kulkarni, Electrical and Computer Engineering, Purdue University, West Lafayette, IN, USA, milind@purdue.edu.
X:2
Adhitha Dias, Kirshanthan Sundararajah, Artem Pelenitsyn, and Milind Kulkarni
formats in sparse tensor computations leads to non-affine loops, where loop bounds and memory accesses depend on metadata arrays. These non-affine loop nests prevent the direct application of classical affine loop nest transformation frameworks. Consequently, determining an optimal execution schedule¹ for sparse computations is significantly more challenging than for their dense counterparts that operate on affine loops. This problem has been extensively studied in the compiler literature [Bik et al. 2022; Bik and Wijshoff 1993; Chou et al. 2018; Deeds et al. 2025; Kjolstad et al. 2017; Shaikhha et al. 2024; Tian et al. 2021; Won et al. 2023a; Ye et al. 2023], with proposed solutions involving techniques such as fusion, tiling, and data layout transformations, etc [Ahrens et al. 2025; Chou et al. 2020; Dias et al. 2022; Kjolstad et al. 2019; Mueller et al. 2020; Senanayake et al. 2020].
The effectiveness of a schedule for non-affine loops is highly sensitive to the sparsity pattern of the input tensors [Won et al. 2023b]. A loop structure that performs well for one pattern may be inefficient for another. Since it is impractical for programmers to manually explore the vast space of possible implementations for every use case, modern sparse tensor compilers provide frameworks that use domain-specific languages (DSLs) to express a wide range of schedules without exposing the complexity of low-level details. This allows the user to select the most performant schedule for a specific problem instance [Kjolstad et al. 2017; Senanayake et al. 2020].
A common scheduling challenge arises when a computation involves tensors with conflicting iteration orders. For example, consider an element-wise matrix product²:
where tensor is stored in a row-major format (CSR) and tensor is in a column-major format (CSC). Co-iterating over both tensors is difficult due to their conflicting layouts. Specifically, accessing elements of requires iterating over index before , while accessing elements of requires iterating over index before . This means that requires a loop order of outer and inner, while requires outer and inner. This mismatch in iteration order is our core problem and complicates the generation of loop code. The standard solution is to create a temporary sparse tensor by explicitly transposing one of the inputs to match the other's layout. In this case, converting to a row-major format (CSR) to match 's layout. However, this materialization of a temporary copy incurs time and memory costs, as does the use of alternative structures like hash maps [Dias et al. 2022; Raje et al. 2024].
An alternative to materializing a temporary is to generate a schedule that can handle the conflicting iteration orders directly within the computation. This can be achieved with a search-based strategy that locates corresponding elements in the compressed data structures on the fly. For example, using a search and a conditional to match corresponding coordinates in with , or vice versa. This approach eliminates the need for a temporary copy of the entire tensor and may use lower-dimensional dense temporaries to store intermediate results.
By eliminating an explicit transposition, we

Fig. 1. The effect of omitting an explicit transpose step on execution time.
can reduce the overhead of data manipulation, leading to improved performance. This is particularly important for sparse tensors, where the cost of creating temporary tensors can be significant
¹A schedule is a concrete realization of the computation, which encompasses, for instance, a loop structure, parallelization strategies, tiling/blocking, loop fusion, etc.
²We use bold letters, like and , to denote sparse matrices or tensors. Dense tensors are not bolded.
X:3
compared to the actual computation. Figure 1 illustrates the benefits of a single, fused computation over a separate transpose-then-compute approach.
This search-based mechanism has not been explored systematically as a generic loop generation strategy to eliminate explicit transpositions in sparse tensor computations. Existing sparse tensor compilers, such as TACO [Kjolstad et al. 2017], lack a formal mechanism to implement this strategy because their internal representation is over-constrained and not expressive enough to describe such schedules. In this work, we introduce a more generic representation that extends TACO's iteration graph to support a wider range of schedules, including those that avoid explicit transposition. Our key idea is to introduce a relaxed iteration graph that can express a search-based strategy, which we then lower to a new intermediate representation for code generation. This allows us to systematically generate fused transposition schedules for sparse tensor computations.
The contributions of this paper are as follows:
Relaxed Iteration Graph and IR We generalize the iteration graph of TACO to support conflicting iteration orders to circumvent explicit transposition steps in the computation and enable more flexible scheduling. To this end, we generalize the intermediate representation to a relaxed version, by introducing two new IR nodes, forsome and forsame.
Novel Code Generation Strategy We add support for the new IR nodes in the code generation phase, and adapt the existing code generation capabilities of TACO. We further show how the new IR can be transformed into existing IR constructs in certain scenarios.
Demonstrating Performance for Suitable Tensors We identify two classes of problems where this new code generation strategy can provide substantial speedups.
The rest of the paper is organized as follows. We provide the necessary background in Section 2. We motivate the problem in Section 3. The new compiler design is explained in detail in Section 4. We discuss implementation details in Section 5. Evaluation of our compiler is presented in Section 6. We conclude the paper in Section 8 with a discussion.
2.1 Sparse Tensor Access Constraints
Sparse tensors can be stored using various compressed data formats, including Compressed Sparse Row (CSR), Sorted Coordinate (Sorted COO), and Compressed Sparse Fiber (CSF), among others. These formats are abstracted through the level format, a tree structure that defines the order in which index arrays must be traversed to access an element. The compressed data formats impose sparse tensor access constraints based on the required traversal order of their index arrays. For instance, when is stored in CSR format, the row index must be traversed before accessing the column index, creating a dependency between indices and (which traverse the rows and columns of , respectively). Consequently, the loops containing and cannot be arbitrarily reordered. The TACO Format Abstraction [Chou et al. 2018] provides a detailed description of level formats.
2.2 Tensor Index Notation for Tensor Contractions
Tensor contraction operations are described using notation based on the Einstein Summation (Einsum) convention. This convention implicitly denotes summation over repeated indices. For instance, the expression indicates summation over the repeated index
X:4
Adhitha Dias, Kirshanthan Sundararajah, Artem Pelenitsyn, and Milind Kulkarni

Fig. 2. An example of an iteration graph for sparse matrix-matrix multiplication and corresponding code.
and is equivalent to the standard mathematical notation . Throughout this text, we use both notations interchangeably. This computation can be implemented using a triply nested loop with time complexity , assuming dense matrices, where , and represent the loop bounds. When is sparse, the time complexity reduces to , where denotes the number of non-zero elements.
2.3 Iteration Graph
Consider the sparse matrix-matrix multiplication (SpMM) example: . An iterator traversing indices , and reads values from and , multiplies corresponding values that share the same index, and accumulates the results in . Figure 2a shows an example iteration graph, whose internal representation (IR) generates the code shown in Figure 2b. In this iteration graph, nodes represent indices from the Einsum notation. The graph is acyclic, with edges representing tensor dimensions and their mapping to indices. Since is sparse, the edges and incident on indices and must maintain their order, while other indices can appear in any order when traversing dense tensors (e.g., and ). No additional sparse tensor access constraints (§ 2.1) apply in this case. TACO provides a detailed description of iteration graphs.
2.4 Tensor Transposition
Tensor transposition involves permuting the dimensions of a tensor. For instance, transposing a matrix produces a new matrix with swapped rows and columns. Sparse tensor transposition is significantly more complex than dense tensor transposition due to the compressed storage formats employed for sparse tensors. In certain cases, transposing a sparse tensor is equivalent to changing its storage format. For the matrix example above, transposition is analogous to converting between CSR and CSC formats. However, in other scenarios, sparse tensor transposition requires reordering the non-zero elements and their corresponding indices within the compressed storage format. This operation can be computationally expensive. Research has explored efficient transposition algorithms using various sorting techniques [Mueller et al. 2020], as well as automatic code generation approaches for sparse format conversion [Chou et al. 2020].
3 OVERVIEW
Existing sparse tensor compilers impose specific index access patterns on tensor operands to enable efficient computation. When the required access pattern differs from the tensor's storage format,
³This is the matrix-matrix multiplication operation.
X:5
1 iterator i (over A, B, C): 2 iterator j (over A, B, C): 3 A(i,j) = B(i,j) * C(i,j)
(a)
1 iterator iB (over A, B): 2 iterator j (over A, B, C): 3 iterator iC (over C): 4 if iB == iC: 5 A(i,j) = B(i,j) * C(j,i)
(b) Computation of without transposing .
Fig. 3. (a) Computing . cannot be computed since , and have conflicting index access patterns. (b) shows how we can transpose from CSR format to CSC format to have the indexing pattern. (c) shows the computation.
indices must be reordered through tensor transposition before computation can proceed. While conceptually straightforward, this approach introduces significant memory and computational overheads that can severely impact performance, particularly for large-scale sparse computations.
3.1 Motivating Example
3.1.1 Element-wise Product with Transpose. Consider the tensor algebra operation:
This element-wise multiplication (Hadamard product) computes each element of as the product of corresponding elements from and . Such operations are fundamental in tensor factorizations and neural network computations [Buluc and Gilbert 2011; Davis 2019]. We assume all tensors are stored in Compressed Sparse Row (CSR) format.⁴
The key challenge arises from mismatched index access patterns: requires access order ① → ⑦, while follows ⑦ → ①. This incompatibility prevents direct computation using existing sparse tensor compilers, which enforce strict access pattern constraints. The conventional solution involves transposing tensor to align both operands' access patterns:
While this approach yields the correct result, it introduces significant performance penalties. First, it demands additional memory allocation for the transposed tensor , which scales with tensor size and can be prohibitive in memory-constrained environments. Second, it incurs substantial computational overhead for the transpose operation itself, particularly for large sparse tensors. In practice, this approach requires converting the storage format of matrix from CSR to CSC, followed by the element-wise computation shown in Code Snippet 3a.
However, we can avoid the transpose operation overheads by directly computing the Hadamard product through a search operation over the index of to match the index of . Code Snippet 3b demonstrates this approach. While iterating over the same index of both and introduces additional computational overhead, the iteration over traverses only non-zero element indices. Moreover, CSR format maintains sorted indices within each row, enabling binary search to locate matching index in for each index in . This optimization reduces the time complexity of each index search operation from to , where represents the average number of non-zero elements in a row of . The relative performance between these scheduling approaches depends on the sparsity attributes and patterns of the tensors, as we will demonstrate in Section 6.
⁴This computation is equivalent to where is stored in Compressed Sparse Column (CSC) format while the other tensors remain in CSR format.
X:6
Adhitha Dias, Kirshanthan Sundararajah, Artem Pelenitsyn, and Milind Kulkarni
1 iterator i (over A, B):
2 iterator jA (over A):
3 float sum = 0;
4 bool found = false;
5 iterator k (over B, C):
6 iterator jC (over C):
7 if jA == jC:
8 found = true;
9 sum += B(i,k)*C(k,jC);
10 if found:
11 // extend A's indexing arrays
12 A(i,jA) = sum;
(a) SparseConflicts pseudocode for $A_{ij}$ =
$\sum B_{ij}C_{ij}$
1 set<int> relevant_js;
2 iterator i (over A, B):
3 float vals[J];
4 iterator k (over B, C):
5 iterator j (over C):
6 relevant_js.insert(j);
7 vals[j] += B(i,k)*C(k,j);
8 iterator j (over A): // only
relevant_js
9 A(i,j) = vals[j];
10 relevant_js.remove(j);
(b) Transformed pseudocode to a nested multi-child/inner loop structure.
Fig. 4. Computing using SparseConflicts IR and transforming it to an optimized version.
In these two cases, the transpose-plus-compute approach has a time complexity of , which includes the cost of transposing and performing the element-wise multiplication. Here, we use to denote the union of the non-zero elements in and , because the iterators traverse the union of the indices of non-zero elements in both tensors. In contrast, the fused approach has a time complexity of , where is the average number of non-zero elements per row in . The fused approach can be more efficient when has a high sparsity level, making the transpose operation relatively expensive.
3.1.2 Sparse Matrix-Sparse Matrix Multiplication. Consider the tensor algebra operation:
where , and are stored in CSR format. This operation represents sparse matrix-matrix multiplication and is widely used in various applications [Buluc and Gilbert 2008; Buluç and Gilbert 2011].
When the output of a tensor contraction is sparse and stored in a level-format, the output tensor indices must be positioned as the outermost indices in the compute loop nest. For example, in the above contraction, when indices and are the outermost indices in that order, the value of the output tensor can be computed by contracting over the index of the input tensors. If no values exist to contract, the value of the output tensor is zero and can be omitted from the output tensor in both the indexing arrays and the value array. Code snippet 4a outlines the basic loop structure of this computation. Similar to the previous example, these loop nests do not contradict the index access patterns of the input tensors or the output tensor. Although the iteration order of followed by followed by does not contradict the access constraints of each individual tensor, we cannot generate this loop structure because the output tensor is in CSR format. It requires the outermost indices to be followed by so that we can extend the indexing arrays of in the correct order.
Although this approach is functionally correct, it is highly inefficient. The inefficiency stems from the need to iterate over all possible indices to populate the output tensor's indexing arrays in the correct order. This requirement leads to two separate iterations over the index, with one of them traversing all possible indices, resulting in a sub-optimal time complexity of . This computation can be optimized by restructuring the loop nest and introducing a temporary
X:7
workspace. The optimized code, shown in Code Snippet 4b, computes all values for a single row of the output tensor (i.e., for a single instance of ) within the inner and loops. The temporary array accumulates the partial results corresponding to the non-zero columns in for the current output row .
While general-purpose sparse compilers like TACO [Kjolstad et al. 2017] support computation mechanisms similar to the one shown in Code Snippet 4b, they require users to define computations at a lower level of abstraction. Consequently, users cannot rely solely on high-level Einsum notation and must instead work with a more complex lower-level IR. To circumvent this complexity for common operations, TACO's implementation includes a hardcoded SpMM kernel that generates the optimized code from Code Snippet 4b using low-level primitives.
3.2 Our approach: SparseConflicts
The insights drawn from the motivating examples and our approach to code generation can be summarized as follows.
Constraints on Initial Index Layout We use sparse access constraints to build the initial layout of the loop iterators (§ 4.1).
A Leader-Follower Model We use the initial index layout to identify leader and follower nodes in the iteration graph and build a relaxed iteration graph representation that allows more flexible index traversal orders (§ 4.1). This relaxed iteration graph serves as the foundation for generating a new intermediate representation (IR) that supports more adaptable code generation strategies (§ 4.2).
Transformation Rules for New IR We introduce transformation rules to convert the new IR into existing IR constructs when specific conditions are met, enabling the reuse of established code generation techniques (§ 4.3).
4 DESIGN OF THE TRANSFORMATION
To support tensor contractions where operand storage formats are incompatible, we introduce a new transformation algorithm. Our approach generates an efficient loop nest by treating the index order as a modified Shortest Common Supersequence (SCS) problem [sho 2025]. The algorithm proceeds in three phases:
(1) Iteration Graph Scheduling: We first find the Shortest Common Supersequence (SCS) of the index orders of all tensors in the expression (§ 4.1). This SCS defines the loop nest order. For sparse output tensors, we constrain the SCS to begin with the output tensor's free indices⁵ to enable in-order generation of the output. For dense outputs, no such constraint is imposed, allowing for more flexible loop orderings.
(2) IR Generation: The scheduled SCS is then lowered to a new Internal Representation (IR) that extends TACO's concrete index notation (§ 4.2). This IR introduces new iterators to explicitly represent iteration over subsets of tensors and to model searches required when an index appears in multiple positions in the loop nest.
(3) IR Transformation: Finally, we apply transformations to the new IR to optimize the loop structure (§ 4.3). For instance, we can transform a linear loop nest into a branched structure with producer-consumer semantics. This is particularly effective for sparse outputs where an index appears only in the output tensor, avoiding unnecessary computation.
We now describe each phase in detail.
⁵Free indices are those that appear in the output tensor.
X:8
Adhitha Dias, Kirshanthan Sundararajah, Artem Pelenitsyn, and Milind Kulkarni

(a) default iteration graph.
1 for (int i = 0; i < B1_dimension; i++) { 2 int jB = B2_pos[i]; int pB2_end = B2_pos[i+1]; 3 int jC = C1_pos[i]; int pC2_end = C2_pos[i+1]; 4 while (jB < pB2_end && jC < pC2_end) { 5 int jB0 = B2_crd[jB]; int jC0 = C2_crd[jC]; 6 int j = min(jB0, jC0); 7 if (jB0 == j && jC0 == j) { 8 A_vals[jA] += B_vals[jB] * C_vals[jC]; jA++; } 9 jB += (int) (jB0 == j); 10 jC += (int) (jC0 == j); 11 } 12 }
(b) Generated code from the graph in Figure 5a.

(c) relaxed iteration graph.
1 int jA = 0; 2 for (int i = 0; i < B1_dimension; i++) { 3 for (int jB = B2_pos[i]; jB < B2_pos[i+1]; jB++) { 4 int j = B2_crd[jB]; 5 int iC = binary_search_index( idx_array=C2_crd, start=C2_pos[j], end=C2_pos[j+1], match=i); 6 if (iC != -1) { 7 A_vals[jA] += B_vals[jB] * C_vals[iC]; 8 jA++; 9 } 10 } 11 }
(d) Generated code from the graph in Figure 5c.
Fig. 5. Iteration graphs and generated code for the hadamard product of two sparse matrices.
4.1 Relaxed Iteration Graph Representation
Let's consider our previous example of the Hadamard product of the two matrices.
The output is generated by iterating over and , multiplying values that share the same and indices, and storing the result in . In its simplest form, we can think of the iterations over the input and output tensors individually, as shown in Figure 5a, and then combine them into a single iteration graph. This iteration graph can be converted into code, as shown in Figure 5b, by mapping each index in the graph to loops in the code (Lines 1–3 correspond to the index, while Lines 4–7 and 9–10 correspond to the index). The indexing arrays of the input tensors can be co-iterated to traverse their non-zero elements.
However, if the computation is
the individual iteration graphs can be combined into a single graph while keeping all sparse iteration constraints intact, as shown in Figure 5c. Before our work, no systematic method existed for combining individual iteration graphs in such scenarios. We introduce a novel approach that
X-9
models the problem as finding a Shortest Common Supersequence (SCS) of the tensor index orders, which defines a unified loop nest. This, in turn, allows us to create a single, combined iteration graph. The subsequent paragraphs describe our approach to this problem, simplifying it by explaining the concepts using this example.
In this example, the duplicated node becomes a search node, where the iterator must find the corresponding instance of from the outermost loop. This mechanism can be viewed as a leader-follower approach: the first instance of the index (the leader) iterates freely over the tensors it is incident upon, while the second instance (the follower) finds the same value by searching the indexing array of the other tensor. The code generated from this iteration graph is shown in Figure 5d. Note that line 2 corresponds to the first index, lines 3–4 to the index, and lines 5–6 to the second index. Line 5 performs a binary search over the indexing array of to find the instance of from the outermost loop. The conditional line 6 uses the output from the binary search to decide whether to continue the computation. By combining the iteration graphs in this manner, we can avoid an explicit transposition of to match the computation patterns supported by existing sparse tensor compilers.
The algorithm to build the resulting iteration graph for (1) proceeds as follows. The constraints imposed by each tensor in the computation are collected. In particular, both and are sparse and in CSR format, which imposes the constraint that the index must follow the index in the loop nest. Similarly, for , the index must follow the index. Together, these yield two constraints: . Conforming to these constraints allows for two possible index orders: and . However, because the output tensor is sparse, the order must be eliminated, as it would prevent the output indexing arrays from being generated in the correct order if the indices are not placed as the outermost indices in the loop nest.
As another example, consider the contraction , where the output is dense, and the inputs and are in CSF format. The constraints collected from the tensors are from and from . Two possible indexing orders that conform to these constraints are and . Both are valid because the output is dense, so the free index does not need to be fixed at the beginning of the index order.
Algorithm 1 describes a procedure to find all possible index orders that conform to the given constraints. We describe the formal model and provide proof sketches for optimality and completeness of the algorithm below.
Notation:
-
: the set of input sequences where each sequence is a sparse access constraint.
-
: the required fixed prefix sequence (if any).
-
: the set of resulting SCS.
-
: a state vector where is the current index in sequence .
-
: the terminal state where all sequences are fully consumed.
-
: the current supersequence being constructed, or a path representing a partially or fully constructed supersequence.
-
: a queue for the BFS, storing start node objects.
-
: a map storing the length of the shortest path found to a state, i.e., is the length of the shortest path found to state .
-
: concatenation of character with sequence .
Specification We model the problem on a state-space graph .
X:10
Adhitha Dias, Kirshanthan Sundararajah, Artem Pelenitsyn, and Milind Kulkarni
Algorithm 1 FIND ALL SHORTEST COMMON SUPERSEQUENCES
1: procedure FIND-ALL-SCS() returns 2: 3: 4: 5: 6: Number of sequences 7: Calculate the initial state based on the prefix 8: Let be a new state vector of size 9: for to do 10: length of the longest prefix of that is a subsequence of . 11: end for 12: 13: node Initialize the BFS 14: 15: 16: 17: while is not empty do 18: 19: if then Pruning check 20: continue 21: end if
22: if then Goal check 23: if then 24: 25: end if 26: Add to ; continue 27: end if 28: Generate successor states 29: and 30: for each character do 31: Let be a new state vector 32: for to do 33: if and then 34: 35: else 36: 37: end if 38: end for 39: 40: if or then 41: 42: 43: end if 44: end for 45: end while 46: return 47: end procedure
- A vertex represents a state vector indicating the current position in each sequence .
- An edge with label exists if state is reachable from by appending character to the supersequence (lines 30–44), advancing the position in each sequence that has at its current position.
- The problem is to find all shortest paths from a starting vertex to the terminal vertex . The vertex corresponds to the state vector computed in lines 8–11 of the algorithm.
- The final supersequence is the concatenation of and the labels of a path from to . Minimizing the total length is equivalent to minimizing the length of the path from to .
Proof Sketch of Correctness (Optimality) The algorithm FIND-ALL-SCS finds a supersequence that both starts with and has the shortest possible total length. The proof of correctness is based on the following observations:
- Objective Equivalence: Minimizing the total length of the supersequence is equivalent to finding a shortest path in the unweighted graph from the vertex to .
- BFS Implementation: The algorithm implements a Breadth-First Search (BFS) strategy to explore the state-space graph . The queue is used to explore states level by level, ensuring that the first time a state is reached, it is via the shortest path. It begins the search at the single node as initialized in lines 13–15.
X:11
-
BFS Optimality Property: BFS guarantees that the first time it reaches any vertex from a source, it has found a shortest path from the source to . In our case, this means that when the algorithm first reaches the terminal state , it has found a shortest path from to .
-
First Solution: The algorithm finds its first solution when it processes a node where (line 22). At this point, is the length of the shortest path from to , and is set to this length (lines 23–25).
-
Conclusion: The length of the first solution is , where is the length of the shortest path from to . Since BFS guarantees is minimal, the total length stored in is the shortest possible for any valid supersequence that adheres to the prefix constraint.
Proof Sketch of Completeness (Finding All Shortest Paths) The algorithm FIND-ALL-SCS finds all distinct supersequences of the shortest possible length that begin with . The proof of completeness is based on the following observations:
-
Assumption for Contradiction: Assume there exists a valid SCS, , of the minimal length which the algorithm fails to add to the result set .
-
Path Correspondence: corresponds to a specific shortest path of length from the vertex to in the state-space graph .
-
Systematic Exploration: The BFS systematically explores all possible paths of length from before any of length . The pruning condition (line 19) ensures the algorithm only stops extending the paths after they have exceeded the known shortest length, , but it fully explores all paths of length .
-
Path Discovery/Preservation of Parallel Paths: The crucial condition on line 40 ensures that if the algorithm discovers a new path to an existing state that is equally short as a previously discovered path, it still enqueues this new path for further exploration. This mechanism preserves all parallel paths of the same length, ensuring that no potential shortest path is overlooked.
-
Contradiction and Conclusion: Because the algorithm explores all equally short paths to any intermediate state, it is guaranteed to discover all shortest paths from to . Each such path corresponds to a unique state node that will be processed at line 18, and its path will be added to the result set (line 26). Therefore, the assumption that a valid shortest solution could be missed is contradicted, proving that the algorithm is complete in finding all shortest supersequences.
While our method selects one of these valid orders, the selection of the optimal index order is left as future work. Furthermore, any indices not constrained by sparse tensor access patterns can be inserted at any position in the chosen order.
4.2 Internal Representation (IR)
We extend TACO's concrete index notation (CIN) [Kjolstad et al. 2019]. Figure 6 presents the grammar for this extended IR, with our additions highlighted in red.
Two key components of the IR are the Forall and Where constructs. The Forall construct defines a loop over an index variable that iterates over all the tensors which contain that index, while the Where construct splits a computation into a producer and a consumer. The producer computes intermediate results into a dense temporary tensor, which the consumer then uses to generate the final output. In the grammar, Index and Tensor are identifiers, Access is a tensor with its indices, and Expr can be a literal, a tensor access, or a combination of expressions.
To support the relaxed iteration graphs, we extend the IR with two new constructs.
X:12
Adhitha Dias, Kirshanthan Sundararajah, Artem Pelenitsyn, and Milind Kulkarni
Stmt ::= Assignment
| Forall
| Forsome
| Forsame
| Where
Assignment ::= Access = Expr
| Access += Expr ...
Forall ::= forall(Index, Stmt)
Forsome ::= forsome(Index, {Tensor*}, Stmt)
Forsame ::= forsome(Index, {Tensor*}, Stmt)
Where ::= Stmt where Stmt
Access ::= Tensor(Indices)
Indices ::= Index*
Expr ::= Literal | Access | (Expr) | Expr × Expr | ...
Fig. 6. Subset of the grammar of the extended TACO IR. The extensions are highlighted in red. In the diagram, the first letter of the non-terminals are capitalized.

Fig. 7. Iteration graphs and the corresponding IR of the Hadamard product. (a) Iteration graph of the Hadamard product when the indexing orders have the same order. (b) Iteration graph of the Hadamard product when the indexing orders have different orders. (c) IR of the Hadamard product when the indexing orders have the same order. (d) IR of the Hadamard product when the indexing orders have different orders.
- Forsome ::= forsome(Index, {Tensor*}, Stmt): This construct defines a loop over the specified index, iterating only over the tensors listed in the set {Tensor*}. It is used when the index appears multiple times in the iteration graph, and we want to iterate over a subset of tensors that contain this index.
- Forsame ::= forsame(Index, {Tensor*}, Stmt): This construct defines a search operation for the specified index within each of the indexing array of the tensors listed in {Tensor*} individually. It is used when the index appears multiple times in the iteration graph, and we want to find the same instance of this index as in a previous loop.
These two constructs allow us to represent the leader-follower iteration strategy in the IR, enabling efficient code generation for computations involving sparse tensors with differing index orders.
The SCS is transformed into this IR. For the Hadamard product, Figures 7a and 7c show the iteration graph and corresponding IR when the indexing orders are the same. When the orders differ, Figures 7b and 7d illustrate the newly formed iteration graph and IR, respectively.

Fig. 8. Example of IR generation from SCS.
X:13
Algorithm 2 CREATE ACCESS MAP
1: procedure CREATE-ACCESS-MAP(scs, expr) 2: accessMap ← Map(size=|scs|) ▷ empty [] elements 3: for acc in TENSORACCESSES(expr) do 4: ptr ← 0 5: for idx in acc.indexVars do 6: if ISSPARSE(acc) then 7: while ptr < |scs| and scs[ptr] ≠ idx do 8: ptr ← ptr + 1 9: end while 10: else ▷ Dense tensor 11: ptr ← first position of idx in scs 12: end if 13: accessMap[ptr].append(acc) 14: end for 15: end for 16: return accessMap 17: end procedure
Algorithm 3 CONVERT SCS TO IR
1: procedure CONVERT-SCS-To-IR(scs, accessMap, stmt) 2: duplicateIndices ← DUPLICATEINDICES(scs) 3: idxCntMap ← IDXCOUNTS(scs) 4: for i = |scs| - 1 down to 0 do ▷ Reverse order 5: idx ← scs[i] 6: accesses ← accessMap[i] 7: if idx ≠ duplicateIndices then 8: stmt ← FORALL(idx, stmt) 9: else if idxCntMap[idx] > 1 then 10: stmt ← FORSAME(idx, stmt, accesses) 11: idxCntMap[idx] ← idxCntMap[idx] - 1 12: else 13: stmt ← FORSOME(idx, stmt, accesses) 14: end if 15: end for 16: return stmt 17: end procedure
The figures illustrate the use of the forsome and forsame iterators to define loops in the IR. The naming of these constructs reflects their function. The forsome iterator, a variation of TACO's forall, iterates over a subset of tensors containing a given index—in this case,
iterating over index i for tensors B and A. Correspondingly, the forsame iterator is used to find the same instance of index i from the forsome loop by searching within another tensor, here C.
The process of converting the SCS to our IR is illustrated in Figure 8. The algorithm begins by identifying duplicate indices within the SCS, which is the key to differentiating between forall, forsome, and forsame loop constructs. It then establishes a mapping from each index in the SCS to the set of tensor accesses that use that index. The construction of the SCS guarantees two properties: first, that every index from every tensor in the expression is present in the SCS, and second, that the SCS contains subsequences that respect the ordering constraints imposed by each sparse tensor. To assign tensor accesses to specific positions in the SCS, the algorithm proceeds from the start of each tensor's index list, advancing its position within the SCS for each index of a sparse tensor access.
We explain these procedures in Algorithms 2 and 3. Algorithm 2 builds a map from each index in the SCS to its corresponding tensor accesses. This map is then consumed by Algorithm 3, which traverses the SCS in reverse to generate the final IR, creating the appropriate loop constructs by checking for duplicated indices.
Our co-iteration strategy is analogous to the merge lattice construction used in TACO, but with a key difference: we relax the requirement to co-iterate over all tensors in the contraction. This is achieved through our new iterators. The forsome iterator co-iterates only over the subset of tensors incident upon it, while the forsame iterator performs a targeted search operation on a single tensor.
Co-iteration refers to iterating over indexing meta arrays of multiple tensors in tandem.
Merge lattice construction is a technique used in TACO [Kjolstad et al. 2017] to efficiently coiterate over multiple sparse tensors by constructing a lattice of iteration points that represent the merged iteration space.
X:14
Adhitha Dias, Kirshanthan Sundararajah, Artem Pelenitsyn, and Milind Kulkarni

(a)

(b)
1 forall i: 2 where: 3 t(j) = 0 // workspace 4 forall k: // producer 5 forall j: 6 t(j) += B(i,k) * C(k,j) 7 forall j: // consumer 8 A(i,j) = t(j)
(c)
(d)
Fig. 9. (a) Relaxed iteration graph of SpMM. (b) Nested multi-inner/child iteration graph of SpMM. (c) IR of SpMM from the relaxed iteration graph (Figure 9a). (d) IR from the Nested multi-inner/child iteration graph in Figure 9b.
4.3 Transformations on the Relaxed Iteration Graph and the IR
A significant advantage of having our relaxed iteration graph and the accompanying new IR constructs is the application of automatic transformations on this new IR to other already existing IR constructs in the TACO. This allows us to leverage existing optimizations and code generation techniques in TACO while supporting more flexible and efficient iteration patterns, all without requiring the user to manage the underlying complexity.
Now let's consider our second example of sparse matrix-sparse matrix multiplication (SpMM),
Figure 9a displays the relaxed iteration graph for SpMM, and Figure 9c presents its corresponding IR. A key observation is that the forsome iterator is incident only upon the output tensor. Because the output tensor is sparse, we lack advance knowledge of which indices will be non-zero. A naive but correct implementation would therefore require the forsome iterator to traverse all possible values of and subsequently filter out those indices that did not actually contribute to the result after the contraction. This approach is not only computationally wasteful and inefficient but also adds significant implementation complexity.
In these scenarios, we can transform the relaxed iteration graph into a more efficient branched loop nest structure [Dias et al. 2022; Kjolstad et al. 2019; Zhou et al. 2023]. This transformation is triggered by identifying loop indices that appear exclusively in the sparse output tensor and not in any of the input tensors. The result of this transformation is depicted in Figure 9b, which shows the new iteration graph, and Figure 9d, which shows the corresponding IR. This new structure splits the computation into two distinct phases using the where construct: a producer and a consumer. The producer computes the results into a dense temporary workspace, and the consumer then copies only the non-zero values from this workspace into the final sparse output tensor. This approach yields two significant benefits: it avoids the wasteful computation of iterating over all possible values of the index, and it allows us to leverage the powerful, pre-existing optimizations and code generation techniques available in TACO for these types of branched loop structures.
We describe this transformation formally using transformation rules in Figure 10.
X:15
(a) Transformation rule. reads returns the set of tensors in RHS of all Assignments, writes returns the set of all tensors in LHS of all Assignments. op is a Stmt.
(b) Helper function rewrite(i,S) to rewrite the producer part. This function is applied recursively to the statement S.
Fig. 10. Transformation from a for some iterator to a where clause with a producer and consumer part. A is the output tensor, i is an iterator index variable, S, , are Stmt, is a vector of index variables, and t is a fresh temporary dense workspace tensor.
The transformation rule is defined as in Figure 10a. Our implementation of this transformation begins by identifying an outermost for some iterator that exclusively iterates over the output tensor. Once identified, we rewrite the IR by splitting the computation into a producer and a consumer, encapsulated within a where construct. The consumer part, , is created as a new loop that iterates over the original for some index, copying the non-zero values from the dense workspace to the sparse output tensor. The producer, , is constructed by duplicating the loop nest originally inside the identified for some iterator. Finally, the original for some iterator is removed from the IR.
The rewrite(S) helper function, detailed in Figure 10b, applies a set of transformations to the producer block. These transformations consist of the following rules:
(1) Accesses to the output tensor are redirected to a dense temporary workspace.
(2) The first for some iterator within the producer section that corresponds to the for some iterator index is converted. If it is the only such iterator, it becomes a forall iterator; otherwise, it is rewritten as a for some iterator.
(3) All other statements are recursively processed to apply the same transformation rules.
This process yields a more efficient computation by eliminating unnecessary iterations over non-contributing indices, while still benefiting from the existing optimization and code generation capabilities within TACO.
5 IMPLEMENTATION
We use TACO as the base library for our implementation. We build our library in C++ and use TACO's formats, tensor reading, and other functionalities.
We implement our relaxed iteration graph construction ( ) by modifying TACO's existing iteration graph construction code. We extend TACO's concrete index notation (CIN) [Kjolstad et al. 2019] to introduce the new IR nodes for some and for some ( ). We implement the code generation for these new IR nodes by modifying TACO's existing code generation module. We also
X:16
Adhitha Dias, Kirshanthan Sundararajah, Artem Pelenitsyn, and Milind Kulkarni
Table 1. Tensors and matrices used in the evaluation from various matrix and tensor collections
| Tensor | Dimensions | Non-zeros | Sparsity |
|---|---|---|---|
| bcsstk17 | 11K × 11K | 429K | 4e-3 |
| scircuit | 171K × 171K | 959K | 3e-5 |
| mac_econ_fwd500 | 207K × 207K | 1.27M | 9e-5 |
| majorbasis | 160K × 160K | 1.75M | 7e-5 |
| Lin | 256K × 256 | 1.77M | 3e-5 |
| rma10 | 47K × 47K | 2.37M | 1e-3 |
| cop20k_A | 12K × 12K | 2.62M | 2e-4 |
| webbase-1M | 1.00M × 1.00M | 3.11M | 3e-6 |
| cant | 62K × 62K | 4.01M | 1e-3 |
| pdb1HYS | 36K × 36K | 4.34M | 3e-3 |
| ecology1 | 1M × 1M | 5.00M | 5e-6 |
| largebasis | 440K × 440K | 5.24M | 2.7e-5 |
| consph | 83K × 83K | 6.01M | 9e-4 |
| shipsec1 | 140K × 140K | 7.81M | 2e-4 |
| atmosmodd | 1.27M × 1.27M | 8.81M | 5.4e-6 |
| pwtk | 217K × 217K | 11.52M | 2.4e-4 |
| vast-2015-mc1-3d | 165K × 11K × 2 | 26.02M | 8.36e-08 |
| darpa1998 | 22K × 22K × 23.7M | 28.42M | 2.50e-06 |
| nell-2 | 12K × 9K × 288K | 76.88M | 5.73e-05 |
| freebase_music | 23M × 23M × 23M | 99.55M | 8.13e-15 |
| flickr-3d | 320K × 2.82M × 1.60M | 112.89M | 3.92e-11 |
| freebase_sampled | 39M × 39M × 39M | 139.92M | 2.36e-15 |
| nell-1 | 2.9M × 2.1M × 25.5M | 143.60M | 9.27e-13 |
implement the transformation rules to convert the new IR into existing IR constructs (§ 4.3) by adding a new transformation pass in TACO's existing transformation framework. We limit this transformation pass to be applied only when the new IR can be converted to a branched IR with only one 1-D intermediate temporary tensor. We impose this restriction because 2-D dense intermediate temporaries are usually large leading to high memory consumption, and slower performance. We assume all the storage formats are ordered and unique, and we only add support for Compressed Sparse Fiber (CSF) like formats and dense formats.
6 EVALUATION
This section evaluates SparseConflicts against TACO and other state-of-the-art tensor transpose libraries through two case studies. In the first study (§ 6.3), we assess the performance of SparseC-conflicts on tensor contractions that require searching over the indexing arrays of input tensors. In the second study (§ 6.4), we evaluate its ability to generate code for contractions that need to be reordered into a branched loop nest.
6.1 Experimental Setup
All experiments were conducted on a single-socket 64-Core AMD Ryzen Threadripper 3990X processor clocked at 2.2 GHz. The machine is equipped with a 32 KB L1 data cache, a 512 KB shared L2 cache, and a 16 MB shared L3 cache. We compiled all code using GCC 11.4.0 with the -O3 and -ffast-math optimization flags. For each benchmark, we report the median of 31 serial executions to ensure stable and reliable performance measurements.
X:17

(a) Execution time.

(b) Speedup (Baseline Time / SparseConflicts Time).
Fig. 11. Performance evaluation of elementwise multiplication kernel without output index array assembly during compute.

(a) Execution time.

(b) Speedup (Baseline Time / SparseConflicts Time).
Fig. 12. Performance evaluation of elementwise multiplication kernel with output index array assembly during compute.

(a) shipsec1
(b) ecology1
(c) largebasis
(d) pdb1HYS
(e) scircuit
Fig. 13. Sparsity patterns of the matrices used in the elementwise multiplication benchmarks.
6.2 Datasets
Our evaluation uses a diverse set of real-world tensors from the SuiteSparse Collection [Davis and Hu 2011], Network Repository [Rossi et al. 2015], Formidable Repository of Open Sparse Tensors and Tools (FROSTT) [Smith et al. 2017], and the 1998 DARPA Intrusion Detection Evaluation Dataset [Lippmann et al. 2000]. Table 1 details these tensors, which cover a wide range of sizes and sparsities. We represent two-dimensional sparse matrices in the Compressed Sparse Row (CSR) format and three-dimensional sparse tensors in the Compressed Sparse Fiber (CSF) format. To ensure matching dimensions for tensor contractions, we duplicate input tensors when necessary.
X:18
Adhitha Dias, Kirshanthan Sundararajah, Artem Pelenitsyn, and Milind Kulkarni

(a) shipsec1

(b) ecology1

(c) largebasis

(d) pdb1HYS

(e) scircuit
Fig. 14. Histograms of the number of non-zero elements in rows of the matrices.
6.3 Case Study 1: Tensor contractions containing search over indexing arrays
The first set of experiments evaluates SparseConflicts's performance on tensor contractions that require searching over an input tensor's indexing arrays. This technique is particularly useful when one of the input tensors must be transposed to match the computation's requirements.
For this case study, we evaluate the performance of the following kernels:
Element-wise-mul An element-wise product of two matrices.
Dot-product A batched dot product between the rows of one matrix and the columns of another.
3D-tensor-contraction A contraction of two 3D tensors.
We present the results for the element-wise multiplication kernel in Figures 11 and 12. We compare the performance of SparseConflicts against baselines that adopt a two-step, transpose-then-compute strategy. First, one of the input tensors is explicitly transposed. Second, the kernel is executed using the pre-transposed tensor. All baseline computations are performed using TACO's default schedule. We evaluate the following transpose methods for the baselines:
TACO Transpose We use TACO's built-in functionality to perform the initial tensor transposition. This approach combines TACO's transpose with its default computation schedule.
SOTA Transpose We use other state-of-the-art libraries for the transposition. For 2D sparse matrices, we use SciPy.sparse. For 3D sparse tensors in COO format, we measure the time taken by the C standard library implementation of quick sort function to reorder the indices, representing a lower bound on the achievable performance for 3D tensor transposition.
Since the output of this element-wise multiplication is also a sparse matrix, we evaluate two scenarios. In the first, presented in Figure 11, we generate the output matrix indexing arrays first and then report only the time taken to compute the output matrix value array. In the second, shown
X:19
Table 2. Row-statistics of the matrices used in our evaluation.
| Matrix | Min | Max | Med. | Mean | Std. Dev. |
|---|---|---|---|---|---|
| bcsstk17 | 1 | 150 | 45 | 39.06 | 15.41 |
| scircuit | 1 | 353 | 5 | 5.61 | 4.39 |
| mac_econ_f | 1 | 44 | 5 | 6.17 | 4.44 |
| majorbasis | 6 | 11 | 11 | 10.94 | 0.42 |
| Lin | 4 | 7 | 7 | 6.90 | 0.31 |
| rma10 | 4 | 145 | 46 | 50.69 | 27.78 |
| cop20k_A | 0 | 81 | 23 | 21.65 | 13.79 |
| webbase-1M | 1 | 4700 | 2 | 3.11 | 25.35 |
| Matrix | Min | Max | Med. | Mean | Std. Dev. |
|---|---|---|---|---|---|
| cant | 1 | 78 | 74 | 64.17 | 14.06 |
| pdb1HYS | 18 | 204 | 123 | 119.31 | 31.86 |
| ecology1 | 3 | 5 | 5 | 5 | 0.06 |
| largebasis | 4 | 14 | 12 | 12.64 | 1.15 |
| consph | 1 | 81 | 81 | 72.13 | 19.08 |
| shipsec1 | 24 | 102 | 54 | 55.46 | 11.07 |
| atmosmodd | 4 | 7 | 7 | 6.94 | 0.24 |
| pwtk | 2 | 180 | 54 | 53.39 | 4.74 |
in Figure 12, we generate the output matrix indexing arrays while computing the output values. The first case is useful for computations where the output structure is known a priori, and only the output values need to be computed. In this computation, we use a duplicate copy of the same input matrix for both inputs to ensure matching dimensions.
The results are similar for both scenarios, although the second takes longer due to the overhead of assembling the output matrix indexing arrays concurrently with the output values. In both cases, SparseConflicts outperforms the [TACO Transpose + TACO compute] baseline by a large margin. SparseConflicts is also faster than TACO in most cases when considering the [TACO ([Chou et al. 2020] Transpose) + TACO compute] baseline. However, when a SOTA transpose library is used, SparseConflicts is faster in only some cases.
The performance of SparseConflicts relative to the baselines depends on the input matrices' sparsity patterns (Figure 13). For instance, with shipsec1 (Figure 13a), ecology1 (Figure 13b), and largebasis (Figure 13c), SparseConflicts is faster than all baselines. However, for pdb1HYS (Figure 13d) and scircuit (Figure 13e), it is slower than the fastest baseline. This performance difference arises because the non-zero elements in shipsec1 and ecology1 are clustered around the diagonal or have some structure, whereas in pdb1HYS and scircuit, they are scattered across the matrix.
The Figure 14 shows the histograms of the number of non-zero elements in each row of the matrices, and the Table 2 shows the row statistics of the matrices used in this evaluation. Evidently, ecology1 and largebasis have low number of non-zeros per row, hence better search performance. Although shipsec1 has a higher number of non-zeros per row, these are clustered around the diagonal and have some structure in the matrix, making it easier for the binary search to break from the search early on. When the non-zeros are clustered around the diagonal and the number of non-zeros per row/column is relatively low, the search operation over the indexing array can quickly find the matching index or conclude that there is no matching index.
We see that there are a high number of non-zero values, considering both mean and median, per row in pdb1HYS, resulting in higher search time. Hence, performing poorly compared to the best baseline. Although there are lower number of non-zeros per row in scircuit, the non-zero elements are scattered along the row, making it difficult for the search to exit early on. When the non-zeros are scattered across the matrix or the number of non-zeros per row/column is high, the search operation, although logarithmic in complexity, takes more time to find the matching index or conclude that there is no matching index. Hence, the performance of SparseConflicts is better when the non-zeros are clustered around the diagonal and the number of non-zeros per row/column is low. A performance engineer or an auto-scheduler [Ahrens et al. 2022; Dias et al. 2024] can use this insight to choose between SparseConflicts and the baselines based on the sparsity patterns of
X:20
Adhitha Dias, Kirshanthan Sundararajah, Artem Pelenitsyn, and Milind Kulkarni

(a) Execution time.
(b) Speedup (Baseline Time / SparseConflicts Time).
Fig. 15. Performance comparison of a dot-product contraction kernel: . The output can be easily assembled in these kernels since it is dense in these examples, and we only report the time taken to compute the output values.

(a) Execution time.
(b) Speedup (Baseline Time / SparseConflicts Time).
Fig. 16. Performance comparison of a 3D tensor contraction kernel: .
the input matrices, or save some metadata with the matrices so that the right choice can be made automatically based on the statistics of the input matrices.
Furthermore, we evaluate two other tensor contractions that require searching over one of the indexing arrays of the input tensors. The results are shown in Figures 15 and 16. We use the same matrix/tensor for both inputs to ensure matching dimensions in the computation. The dot-product kernel results in Figure 15 show results similar to the elementwise multiplication kernel. Therefore, the results can be analyzed and explained using the same arguments as previously mentioned.
The 3D tensor contraction kernel results in Figure 16 show mixed results across different datasets. We have two baselines in this evaluation. The first one uses TACO to transpose the tensor. The second one only benchmarks the time it takes to sort, using quick sort, the indices of an index and value tuples. For example if the coordinate values of the tensor are with indexing pattern and we want to transpose it to have the order, then the output after the sorting operation would be . Notice how the position indices are changed in the output array. The performance of SparseConflicts compared to the baselines depends on the sparsity patterns of the input tensors, and the dimensionality (bounds of the tensors, especially the tensor dimension which the search operation is performed) of the tensors. For example, in the case of vast-2015-mc1-3d, the search is done over the third dimension which has a bound of 2, adding almost no overhead to the search operation. Hence, SparseConflicts outperforms the baselines. The sparsities of freebase_music and freebase_sampled are extremely
X:21
1 // define tensors (not shown here) 2 // define the computation 3 4 // define workspace intermediate temporary 5 TensorVar w("w", 6 Type(A.getType().getDataType(), 7 {A.getType().getShape().getDimension(1)}), 8 taco::dense); 9 // define the nested multi-child/inner loop structure in lower IR 10 IndexStmt stmt = forall(i, 11 where( 12 forall(j, 13 , 14 forall(k, 15 forall(j, 16 ); 17 A.compile(stmt); 18 A.evaluate();
1 // define tensors (not shown here) 2 // define the computation 3 4 IndexStmt stmt = A.getAssignment().concretize( sparseFused=true); 5 A.compile(stmt); 6 A.evaluate();
(b) SparseConflicts implementation.
(a) TACO SpMM using lower-level IR.
Fig. 17. Code snippets for SpMM using TACO's lower level IR and SparseConflicts.

(a)

(b)
Fig. 18. Combination of elementwise multiplication and SpMM. . Figure 18a shows the breakdown of time taken for elementwise multiplication and SpMM. Figure 18b shows the speedup of our approach for different matrix sizes and densities.
high, making the search operation take a shorter time. However, the search dimensionality of nell-1, and nell-2 are higher compared to the other two dimensions, making the search operation take a longer time. Hence, SparseConflicts performs poorly compared to the baselines in these two cases.
X:22
Adhitha Dias, Kirshanthan Sundararajah, Artem Pelenitsyn, and Milind Kulkarni
6.4 Case Study 2: Tensor contractions that require reordering to a branched loop nest
This section focuses on two cases where the tensor contraction requires reordering to a nested multi-child/inner loop structure. We evaluate the following kernels for this case study:
SpMM Sparse matrix-sparse matrix multiplication (SpMM)
Elmul-SpMM Combination of elementwise multiplication and sparse matrix-sparse matrix multiplication
TACO has a hardcoded pattern match for SpMM to rewrite the computation to lower level IR that represents a nested multi-child/inner loop structure. Therefore, we do not compare with TACO for SpMM. We qualitatively compare our implementation with TACO's current implementation in the discussion below.
The pattern matching in TACO only works when the input tensors are in a specific order. In einsum notation, both and are semantically equivalent, and should yield the same result. However, TACO's pattern matching is brittle and only works for the first case. It generates incorrect code for the second case. If the user wanted to use the lower level IR that represents the nested multi-child/inner loop structure, it would require the user to write the code snippet as shown in Figure 17a where as SparseConflicts only requires the user to write the code snippet as shown in Figure 17b. Writing the lower level IR code snippet is tedious and requires the user to have a good understanding of TACO's lower level IR. Our implementation only requires a few lines of code (LoC), whereas the TACO lower level IR implementation requires comparatively more LoC.
The second example in this case study is a combination of elementwise multiplication and SpMM. We use the baseline below for this comparison.
TACO Split-Computation In this setting, we split a larger tensor contraction into two smaller tensor contractions to be used with default TACO compiler.
The computation we use here is . We compare our implementation with a split computation that first computes the elementwise multiplication and then computes the SpMM using TACO. Figure 18a shows the breakdown of time taken for elementwise multiplication and SpMM. Figure 18b shows the speedup of our approach for different matrix sizes and densities. Our approach outperforms the split computation in cases where the input matrices have high sparsities or when they are smaller in size.
7 RELATED WORK
There has been significant prior work on optimizing sparse tensor algebra computations. Works such as TACO [Kjolstad et al. 2019, 2017; Senanayake et al. 2020], COMET [Tian et al. 2021], Sparsifier [Bik et al. 2022] in MLIR, SparseTIR [Ye et al. 2023], Galley [Deeds et al. 2025], and Finch [Ahrens et al. 2025] have contributed to various aspects of compiler optimizations in sparse tensor algebra. But none of these works have explored the idea of generating code without having to explicitly transpose tensors when there are conflicting iteration orders in the computation, and they have relied on transpose operations or temporary data structures such as hash maps to resolve these conflicts.
Several prior works have explored optimizations for sparse tensor transpositions. Sparse Tensor Transpositions [Mueller et al. 2020] presents two parallel sorting algorithms to efficiently transpose sparse tensors stored in the coordinate format. Format Abstraction for Sparse Tensor Algebra Compilers [Chou et al. 2018] introduces a level format abstraction to represent various compressed
X:23
storage formats that can be easily composed with sparse tensor compilers. They also present an automatic code generation approach for sparse format conversion [Chou et al. 2020]. UniSparse [Liu et al. 2024] is another work that introduces custom data layouts for sparse tensors and provides support for tensor algebra code generation for these custom data layouts. These works primarily focus on customizing sparse data formats, providing ways for format conversion or transpositions, and optimizing the transposition operation itself, rather than exploring ways to avoid explicit transpositions in tensor computations. These works complement the previous works on sparse tensor compilers.
8 DISCUSSION AND CONCLUSION
Designing sparse tensor algebra compilers is a challenging problem due to the complexity of compressed storage formats and the non-affine loop nests they create. Since no single schedule is optimal for all sparsity patterns, it is crucial for compilers to express a wide range of schedules.
In this paper, we presented SparseConflicts, a sparse tensor algebra compiler that addresses this by generating code for tensor contractions with conflicting iteration orders without explicitly transposing tensors. This is achieved by fusing the transposition into the main computation, which avoids materializing large temporary tensors and is particularly advantageous in memory-constrained environments. Our evaluation shows that for certain sparsity patterns, this fused approach significantly outperforms traditional transpose-and-compute strategies. However, this method introduces search overheads, creating a trade-off that depends on the tensor properties.
This work opens a clear path for future research, most notably the development of an auto-scheduling framework with a cost model to automatically choose the best strategy. In conclusion, SparseConflicts expands the scheduling possibilities for sparse tensor algebra, enabling higher performance across a broader range of computations.
Data Availability Statement
The paper will be accompanied by an artifact that contains the source code of SparseConflicts, the benchmarks, and the scripts to reproduce the results presented in the paper.
References
- Shortest common supersequence. https://en.wikipedia.org/wiki/Shortest_common_supersequence
Willow Ahrens, Teodoro Fields Collin, Radha Patel, Kyle Deeds, Changwan Hong, and Saman Amarasinghe. 2025. Finch: Sparse and Structured Tensor Programming with Control Flow. Proc. ACM Program. Lang. 9, OOPSLA1, Article 117 (April 2025), 31 pages. doi:10.1145/3720473
Willow Ahrens, Fredrik Kjolstad, and Saman Amarasinghe. 2022. Autoscheduling for Sparse Tensor Algebra with an Asymptotic Cost Model. In Proceedings of the 43rd ACM SIGPLAN International Conference on Programming Language Design and Implementation (San Diego, CA, USA) (PLDI 2022). Association for Computing Machinery, New York, NY, USA, 269–285. doi:10.1145/3519939.3523442
Aart Bik, Penporn Koanantakool, Tatiana Shpeisman, Nicolas Vasilache, Bixia Zheng, and Fredrik Kjolstad. 2022. Compiler Support for Sparse Tensor Computations in MLIR. ACM Trans. Archit. Code Optim. 19, 4, Article 50 (sep 2022), 25 pages. doi:10.1145/3544559
Aart J. C. Bik and Harry A. G. Wijshoff. 1993. Compilation Techniques for Sparse Matrix Computations. In Proceedings of the 7th International Conference on Supercomputing (Tokyo, Japan) (ICS '93). Association for Computing Machinery, New York, NY, USA, 416–424. doi:10.1145/165939.166023
Aydin Buluc and John R. Gilbert. 2008. On the representation and multiplication of hypersparse matrices. In 2008 IEEE International Symposium on Parallel and Distributed Processing. 1–11. doi:10.1109/IPDPS.2008.4536313
Aydin Buluc and John R Gilbert. 2011. The Combinatorial BLAS: design, implementation, and applications. The International Journal of High Performance Computing Applications 25, 4 (2011), 496–509. arXiv:https://doi.org/10.1177/1094342011403516 doi:10.1177/1094342011403516
Stephen Chou, Fredrik Kjolstad, and Saman Amarasinghe. 2018. Format Abstraction for Sparse Tensor Algebra Compilers. Proc. ACM Program. Lang. 2, OOPSLA, Article 123 (oct 2018), 30 pages. doi:10.1145/3276493
X:24
Adhitha Dias, Kirshanthan Sundararajah, Artem Pelenitsyn, and Milind Kulkarni
Stephen Chou, Fredrik Kjolstad, and Saman Amarasinghe. 2020. Automatic generation of efficient sparse tensor format conversion routines. In Proceedings of the 41st ACM SIGPLAN Conference on Programming Language Design and Implementation (London, UK) (PLDI 2020). Association for Computing Machinery, New York, NY, USA, 823–838. doi:10.1145/3385412.3385963
Timothy A. Davis. 2019. Algorithm 1000: SuiteSparse:GraphBLAS: Graph Algorithms in the Language of Sparse Linear Algebra. ACM Trans. Math. Softw. 45, 4, Article 44 (Dec. 2019), 25 pages. doi:10.1145/3322125
Timothy A. Davis and Yifan Hu. 2011. The University of Florida Sparse Matrix Collection. ACM Trans. Math. Softw. 38, 1, Article 1 (dec 2011), 25 pages. doi:10.1145/2049662.2049663
Kyle Deeds, Willow Ahrens, Magdalena Balazinska, and Dan Suciu. 2025. Galley: Modern Query Optimization for Sparse Tensor Programs. Proc. ACM Management of Data 3, 3, Article 164 (June 2025), 24 pages. doi:10.1145/3725301
Adhitha Dias, Logan Anderson, Kirshanthan Sundararajah, Artem Pelenitsyn, and Milind Kulkarni. 2024. SparseAuto: An Auto-scheduler for Sparse Tensor Computations using Recursive Loop Nest Restructuring. Proc. ACM Program. Lang. 8, OOPSLA2, Article 290 (Oct. 2024), 30 pages. doi:10.1145/3689730
Adhitha Dias, Kirshanthan Sundararajah, Charitha Saumya, and Milind Kulkarni. 2022. SparseLNR: accelerating sparse tensor computations using loop nest restructuring. In Proceedings of the 36th ACM International Conference on Supercomputing (Virtual Event) (ICS '22). Association for Computing Machinery, New York, NY, USA, Article 15, 14 pages. doi:10.1145/3524059.3532386
So Hirato. 2003. Tensor Contraction Engine: Abstraction an Automated Parallel Implementation of Configuration-Interaction, Coupled-Cluster, and Many-Body Perturbation Theories. The journal of physical chemistry. A 107, 46 (2003), 9887–9897. doi:10.1021/jp034596z
Yuwei Hu, Zihao Ye, Minjie Wang, Jiali Yu, Da Zheng, Mu Li, Zheng Zhang, Zhiru Zhang, and Yida Wang. 2020. FeatGraph: A Flexible and Efficient Backend for Graph Neural Network Systems. In Proceedings of the International Conference for High Performance Computing, Networking, Storage and Analysis (Atlanta, Georgia) (SC '20). IEEE Press, Article 71, 13 pages.
Fredrik Kjolstad, Peter Ahrens, Shoaib Kamil, and Saman Amarasinghe. 2019. Tensor Algebra Compilation with Workspaces. In Proceedings of the 2019 IEEE/ACM International Symposium on Code Generation and Optimization (Washington, DC, USA) (CGO 2019). IEEE Press, Piscataway, NJ, USA, 180–192. http://dl.acm.org/citation.cfm?id=3314872.3314894
Fredrik Kjolstad, Shoaib Kamil, Stephen Chou, David Lugato, and Saman Amarasinghe. 2017. The Tensor Algebra Compiler. Proc. ACM Program. Lang. 1, OOPSLA, Article 77 (Oct. 2017), 29 pages. doi:10.1145/3133901
Richard Lippmann, David Fried, Isaac Graf, Joshua Haines, Kristopher Kendall, David McClung, Dan Weber, Seth Webster, Daniel Wyschogrod, Robert Cunningham, and Marc Zissman. 2000. Evaluating intrusion detection systems: the 1998 DARPA off-line intrusion detection evaluation. 2 (02 2000), 12 – 26 vol.2. doi:10.1109/DISCEX.2000.821506
Jie Liu, Zhongyuan Zhao, Zijian Ding, Benjamin Brock, Hongbo Rong, and Zhiru Zhang. 2024. UniSparse: An Intermediate Language for General Sparse Format Customization. Proc. ACM Program. Lang. 8, OOPSLA1, Article 99 (April 2024), 29 pages. doi:10.1145/3649816
Igor L. an Shi Yaoyun Markov. 2008. Simulating Quantum Computation by Contracting Tensor Networks. SIAM J. Comput. 38, 3 (2008), 963–981. doi:10.1137/050644756
Suzanne Mueller, Peter Ahrens, Stephen Chou, Fredrik Kjolstad, and Saman Amarasinghe. 2020. Sparse Tensor Transpositions. In Proceedings of the 32nd ACM Symposium on Parallelism in Algorithms and Architectures (Virtual Event, USA) (SPAA '20). Association for Computing Machinery, New York, NY, USA, 559–561. doi:10.1145/3350755.3400245
Md. Khaledur Rahman, Majedul Haque Sujon, and Ariful Azad. 2021. FusedMM: A Unified SDDMM-SpMM Kernel for Graph Embedding and Graph Neural Networks. In 2021 IEEE International Parallel and Distributed Processing Symposium (IPDPS). 256–266. doi:10.1109/IPDPS49936.2021.00034
Saurabh Raje, Yufan Xu, Atanas Rountev, Edward F. Valeev, and P. Sadayappan. 2024. CoNST: Code Generator for Sparse Tensor Networks. ACM Trans. Archit. Code Optim. 21, 4, Article 82 (Nov. 2024), 24 pages. doi:10.1145/3689342
Shi-Ju Ran, Emanuele Tirrito, Cheng Peng, Xi Chen, Gang Su, and Maciej Lewenstein. 2017. Review of tensor network contraction approaches. arXiv preprint arXiv:1708.09213 (2017).
Shi-Ju Ran, Emanuele Tirrito, Cheng Peng, Xi Chen, Luca Tagliacozzo, Gang Su, and Maciej Lewenstein. 2020. Tensor Network Contractions: Methods and Applications to Quantum Many-Body Systems. Springer Nature. doi:10.1007/978-3-030-34489-4 Luca Rossi, Nesreen K. Ahmed, Jennifer Neville, and Keith Henderson. 2015. The Network Data Repository with Interactive Graph Analytics and Visualization. 42, 1 (2015). doi:10.1145/2740908
Ryan Senanayake, Changwan Hong, Ziheng Wang, Amalee Wilson, Stephen Chou, Shoaib Kamil, Saman Amarasinghe, and Fredrik Kjolstad. 2020. A Sparse Iteration Space Transformation Framework for Sparse Tensor Algebra. Proc. ACM Program. Lang. 4, OOPSLA, Article 158 (Nov. 2020), 30 pages. doi:10.1145/3428226
Amir Shaikhha, Mathieu Huot, and Shideh Hashemian. 2024. A Tensor Algebra Compiler for Sparse Differentiation. In 2024 IEEE/ACM International Symposium on Code Generation and Optimization (CGO). 1–12. doi:10.1109/CGO57630.2024.10444787
X:25
Shaden Smith, Jee W. Choi, Jiajia Li, Richard Vuduc, Jongsoo Park, Xing Liu, and George Karypis. 2017. FROSTT: The Formidable Repository of Open Sparse Tensors and Tools. New York, NY, USA. doi:10.1145/2049662.2049663
Ruiqin Tian, Luanzheng Guo, Jiajia Li, Bin Ren, and Gokcen Kestor. 2021. A High Performance Sparse Tensor Algebra Compiler in MLIR. In 2021 IEEE/ACM 7th Workshop on the LLVM Compiler Infrastructure in HPC (LLVM-HPC). 27–38. doi:10.1109/LLVMHPC54804.2021.00009
Jaeyeon Won, Changwan Hong, Charith Mendis, Joel Emer, and Saman Amarasinghe. 2023a. Unified Convolution Framework: A compiler-based approach to support sparse convolutions. In Proceedings of Machine Learning and Systems, D. Song, M. Carbin, and T. Chen (Eds.), Vol. 5. Curan, 666–679. https://proceedings.mlsys.org/paper_files/paper/2023/file/ccf7262fb986e4367ccd3903960c57a0-Paper-mlsys2023.pdf
Jaeyeon Won, Charith Mendis, Joel S. Emer, and Saman Amarasinghe. 2023b. WACO: Learning Workload-Aware Co-optimization of the Format and Schedule of a Sparse Tensor Program. In Proceedings of the 28th ACM International Conference on Architectural Support for Programming Languages and Operating Systems, Volume 2 (Vancouver, BC, Canada) (ASPLOS 2023). Association for Computing Machinery, New York, NY, USA, 920–934. doi:10.1145/3575693.3575742
Zihao Ye, Ruihang Lai, Junru Shao, Tianqi Chen, and Luis Ceze. 2023. SparseTIR: Composable Abstractions for Sparse Compilation in Deep Learning. In Proceedings of the 28th ACM International Conference on Architectural Support for Programming Languages and Operating Systems, Volume 3 (Vancouver, BC, Canada) (ASPLOS 2023). Association for Computing Machinery, New York, NY, USA, 660–678. doi:10.1145/3582016.3582047
Tong Zhou, Ruiqin Tian, Rizwan A. Ashraf, Roberto Gioiosa, Gokcen Kestor, and Vivek Sarkar. 2023. ReACT: Redundancy-Aware Code Generation for Tensor Expressions. In Proceedings of the International Conference on Parallel Architectures and Compilation Techniques (Chicago, Illinois) (PACT '22). Association for Computing Machinery, New York, NY, USA, 1–13. doi:10.1145/3559009.3569685