Skip to content

Commit 0f84780

Browse files
author
Peiming Liu
committed
[mlir][sparse] introduce sparse_tensor.coiterate operation.
1 parent c99bd3c commit 0f84780

File tree

6 files changed

+430
-91
lines changed

6 files changed

+430
-91
lines changed

mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensor.h

Lines changed: 40 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -61,37 +61,62 @@ struct COOSegment {
6161
/// A simple wrapper to encode a bitset of (at most 64) levels, currently used
6262
/// by `sparse_tensor.iterate` operation for the set of levels on which the
6363
/// coordinates should be loaded.
64-
class LevelSet {
65-
uint64_t bits = 0;
64+
class I64BitSet {
65+
uint64_t storage = 0;
6666

6767
public:
68-
LevelSet() = default;
69-
explicit LevelSet(uint64_t bits) : bits(bits) {}
70-
operator uint64_t() const { return bits; }
68+
using const_set_bits_iterator = llvm::const_set_bits_iterator_impl<I64BitSet>;
69+
const_set_bits_iterator begin() const {
70+
return const_set_bits_iterator(*this);
71+
}
72+
const_set_bits_iterator end() const {
73+
return const_set_bits_iterator(*this, -1);
74+
}
75+
iterator_range<const_set_bits_iterator> bits() const {
76+
return make_range(begin(), end());
77+
}
78+
79+
I64BitSet() = default;
80+
explicit I64BitSet(uint64_t bits) : storage(bits) {}
81+
operator uint64_t() const { return storage; }
7182

72-
LevelSet &set(unsigned i) {
83+
I64BitSet &set(unsigned i) {
7384
assert(i < 64);
74-
bits |= static_cast<uint64_t>(0x01u) << i;
85+
storage |= static_cast<uint64_t>(0x01u) << i;
7586
return *this;
7687
}
7788

78-
LevelSet &operator|=(LevelSet lhs) {
79-
bits |= static_cast<uint64_t>(lhs);
89+
I64BitSet &operator|=(I64BitSet lhs) {
90+
storage |= static_cast<uint64_t>(lhs);
8091
return *this;
8192
}
8293

83-
LevelSet &lshift(unsigned offset) {
84-
bits = bits << offset;
94+
I64BitSet &lshift(unsigned offset) {
95+
storage = storage << offset;
8596
return *this;
8697
}
8798

99+
// Needed by `llvm::const_set_bits_iterator_impl`.
100+
int find_first() const { return min(); }
101+
int find_next(unsigned prev) const {
102+
if (prev >= max())
103+
return -1;
104+
105+
uint64_t b = storage >> (prev + 1);
106+
if (b == 0)
107+
return -1;
108+
109+
return llvm::countr_zero(b) + prev + 1;
110+
}
111+
88112
bool operator[](unsigned i) const {
89113
assert(i < 64);
90-
return (bits & (1 << i)) != 0;
114+
return (storage & (1 << i)) != 0;
91115
}
92-
unsigned max() const { return 64 - llvm::countl_zero(bits); }
93-
unsigned count() const { return llvm::popcount(bits); }
94-
bool empty() const { return bits == 0; }
116+
unsigned min() const { return llvm::countr_zero(storage); }
117+
unsigned max() const { return 64 - llvm::countl_zero(storage); }
118+
unsigned count() const { return llvm::popcount(storage); }
119+
bool empty() const { return storage == 0; }
95120
};
96121

97122
} // namespace sparse_tensor

mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorAttrDefs.td

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,16 +24,17 @@ class SparseTensor_Attr<string name,
2424
// sparse tensor levels.
2525
//===----------------------------------------------------------------------===//
2626

27-
def LevelSetAttr :
28-
TypedAttrBase<
29-
I64, "IntegerAttr",
27+
def I64BitSetAttr : TypedAttrBase<I64, "IntegerAttr",
3028
And<[CPred<"::llvm::isa<::mlir::IntegerAttr>($_self)">,
3129
CPred<"::llvm::cast<::mlir::IntegerAttr>($_self).getType().isInteger(64)">]>,
3230
"LevelSet attribute"> {
33-
let returnType = [{::mlir::sparse_tensor::LevelSet}];
34-
let convertFromStorage = [{::mlir::sparse_tensor::LevelSet($_self.getValue().getZExtValue())}];
31+
let returnType = [{::mlir::sparse_tensor::I64BitSet}];
32+
let convertFromStorage = [{::mlir::sparse_tensor::I64BitSet($_self.getValue().getZExtValue())}];
3533
}
3634

35+
def I64BitSetArrayAttr :
36+
TypedArrayAttrBase<I64BitSetAttr, "I64BitSet array attribute">;
37+
3738
//===----------------------------------------------------------------------===//
3839
// These attributes are just like `IndexAttr` except that they clarify whether
3940
// the index refers to a dimension (an axis of the semantic tensor) or a level

mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorOps.td

Lines changed: 120 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1306,7 +1306,7 @@ def SparseTensor_SelectOp : SparseTensor_Op<"select", [Pure, SameOperandsAndResu
13061306

13071307
def SparseTensor_YieldOp : SparseTensor_Op<"yield", [Pure, Terminator,
13081308
ParentOneOf<["BinaryOp", "UnaryOp", "ReduceOp", "SelectOp",
1309-
"ForeachOp", "IterateOp"]>]> {
1309+
"ForeachOp", "IterateOp", "CoIterateOp"]>]> {
13101310
let summary = "Yield from sparse_tensor set-like operations";
13111311
let description = [{
13121312
Yields a value from within a `binary`, `unary`, `reduce`,
@@ -1604,14 +1604,14 @@ def IterateOp : SparseTensor_Op<"iterate",
16041604

16051605
let arguments = (ins AnySparseIterSpace:$iterSpace,
16061606
Variadic<AnyType>:$initArgs,
1607-
LevelSetAttr:$crdUsedLvls);
1607+
I64BitSetAttr:$crdUsedLvls);
16081608
let results = (outs Variadic<AnyType>:$results);
16091609
let regions = (region SizedRegion<1>:$region);
16101610

16111611
let skipDefaultBuilders = 1;
16121612
let builders = [
16131613
OpBuilder<(ins "Value":$iterSpace, "ValueRange":$initArgs)>,
1614-
OpBuilder<(ins "Value":$iterSpace, "ValueRange":$initArgs, "LevelSet" :$crdUsedLvls)>
1614+
OpBuilder<(ins "Value":$iterSpace, "ValueRange":$initArgs, "I64BitSet" :$crdUsedLvls)>
16151615
];
16161616

16171617
let extraClassDeclaration = [{
@@ -1644,6 +1644,123 @@ def IterateOp : SparseTensor_Op<"iterate",
16441644
let hasCustomAssemblyFormat = 1;
16451645
}
16461646

1647+
def SparseTensor_CoIterateOp : SparseTensor_Op<"coiterate",
1648+
[AttrSizedOperandSegments,
1649+
SingleBlockImplicitTerminator<"sparse_tensor::YieldOp">,
1650+
RecursiveMemoryEffects]> {
1651+
let summary = "CoIterates over a set of sparse iteration spaces";
1652+
let description = [{
1653+
The `sparse_tensor.coiterate` operation represents a loop (nest) over
1654+
the a set of iteration spaces.
1655+
The operation can have multiple regions, with each of them defining a
1656+
case to compute a result at the current iterations. The case condition
1657+
is defined solely based on the pattern of specified iterators.
1658+
For example:
1659+
```mlir
1660+
%ret = sparse_tensor.coiterate (%sp1, %sp2) at(%coord) iter_args(%arg = %init)
1661+
: (!sparse_tensor.iter_space<#CSR, lvls = 0>,
1662+
!sparse_tensor.iter_space<#COO, lvls = 0>)
1663+
-> index
1664+
case %it1, _ {
1665+
// %coord is specifed in space %sp1 but *NOT* specified in space %sp2.
1666+
}
1667+
case %it1, %it2 {
1668+
// %coord is specifed in *BOTH* spaces %sp1 and %sp2.
1669+
}
1670+
```
1671+
1672+
`sparse_tensor.coiterate` can also operate on loop-carried variables.
1673+
It returns the final values after loop termination.
1674+
The initial values of the variables are passed as additional SSA operands
1675+
to the iterator SSA value and used coordinate SSA values.
1676+
Each operation region has variadic arguments for specified (used), one argument
1677+
for each loop-carried variable, representing the value of the variable
1678+
at the current iteration, followed by a list of arguments for iterators.
1679+
The body region must contain exactly one block that terminates with
1680+
`sparse_tensor.yield`.
1681+
1682+
The results of an `sparse_tensor.coiterate` hold the final values after
1683+
the last iteration. If the `sparse_tensor.coiterate` defines any values,
1684+
a yield must be explicitly present in every region defined in the operation.
1685+
The number and types of the `sparse_tensor.coiterate` results must match
1686+
the initial values in the iter_args binding and the yield operands.
1687+
1688+
1689+
A `sparse_tensor.coiterate` example that does elementwise addition between two
1690+
sparse vectors.
1691+
1692+
1693+
```mlir
1694+
%ret = sparse_tensor.coiterate (%sp1, %sp2) at(%coord) iter_args(%arg = %init)
1695+
: (!sparse_tensor.iter_space<#CSR, lvls = 0>,
1696+
!sparse_tensor.iter_space<#CSR, lvls = 0>)
1697+
-> tensor<?xindex, #CSR>
1698+
case %it1, _ {
1699+
// v = v1 + 0 = v1
1700+
%v1 = sparse_tensor.extract_value %t1 at %it1 : index
1701+
%yield = sparse_tensor.insert %v1 into %arg[%coord]
1702+
sparse_tensor.yield %yield
1703+
}
1704+
case _, %it2 {
1705+
// v = v2 + 0 = v2
1706+
%v2 = sparse_tensor.extract_value %t2 at %it2 : index
1707+
%yield = sparse_tensor.insert %v1 into %arg[%coord]
1708+
sparse_tensor.yield %yield
1709+
}
1710+
case %it1, %it2 {
1711+
// v = v1 + v2
1712+
%v1 = sparse_tensor.extract_value %t1 at %it1 : index
1713+
%v2 = sparse_tensor.extract_value %t2 at %it2 : index
1714+
%v = arith.addi %v1, %v2 : index
1715+
%yield = sparse_tensor.insert %v into %arg[%coord]
1716+
sparse_tensor.yield %yield
1717+
}
1718+
```
1719+
}];
1720+
1721+
let arguments = (ins Variadic<AnySparseIterSpace>:$iterSpaces,
1722+
Variadic<AnyType>:$initArgs,
1723+
I64BitSetAttr:$crdUsedLvls,
1724+
I64BitSetArrayAttr:$cases);
1725+
let results = (outs Variadic<AnyType>:$results);
1726+
let regions = (region VariadicRegion<SizedRegion<1>>:$caseRegions);
1727+
1728+
let extraClassDeclaration = [{
1729+
unsigned getSpaceDim() {
1730+
return llvm::cast<::mlir::sparse_tensor::IterSpaceType>(
1731+
getIterSpaces().front().getType())
1732+
.getSpaceDim();
1733+
}
1734+
I64BitSet getRegionDefinedSpace(unsigned regionIdx) {
1735+
return I64BitSet(llvm::cast<IntegerAttr>(getCases()[regionIdx])
1736+
.getValue().getZExtValue());
1737+
}
1738+
// The block arguments starts with referenced coordinates, follows by
1739+
// user-provided iteration arguments and ends with iterators.
1740+
Block::BlockArgListType getCrds(unsigned regionIdx) {
1741+
return getRegion(regionIdx).getArguments()
1742+
.take_front(getCrdUsedLvls().count());
1743+
}
1744+
unsigned getNumRegionIterArgs(unsigned regionIdx) {
1745+
return getInitArgs().size();
1746+
}
1747+
Block::BlockArgListType getRegionIterArgs(unsigned regionIdx) {
1748+
return getRegion(regionIdx).getArguments()
1749+
.slice(getCrdUsedLvls().count(), getNumRegionIterArgs(regionIdx));
1750+
}
1751+
Block::BlockArgListType getRegionIterators(unsigned regionIdx) {
1752+
return getRegion(regionIdx).getArguments()
1753+
.take_back(getRegionDefinedSpace(regionIdx).count());
1754+
}
1755+
}];
1756+
1757+
// TODO:
1758+
// let hasVerifier = 1;
1759+
// let hasRegionVerifier = 1;
1760+
// let hasCanonicalizer = 1;
1761+
let hasCustomAssemblyFormat = 1;
1762+
}
1763+
16471764
//===----------------------------------------------------------------------===//
16481765
// Sparse Tensor Debugging and Test-Only Operations.
16491766
//===----------------------------------------------------------------------===//

0 commit comments

Comments
 (0)