1 //===- SparseTensorUtils.cpp - Sparse Tensor Utils for MLIR execution -----===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements a light-weight runtime support library that is useful 10 // for sparse tensor manipulations. The functionality provided in this library 11 // is meant to simplify benchmarking, testing, and debugging MLIR code that 12 // operates on sparse tensors. The provided functionality is **not** part 13 // of core MLIR, however. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "mlir/ExecutionEngine/SparseTensorUtils.h" 18 #include "mlir/ExecutionEngine/CRunnerUtils.h" 19 20 #ifdef MLIR_CRUNNERUTILS_DEFINE_FUNCTIONS 21 22 #include <algorithm> 23 #include <cassert> 24 #include <cctype> 25 #include <cinttypes> 26 #include <cstdio> 27 #include <cstdlib> 28 #include <cstring> 29 #include <fstream> 30 #include <iostream> 31 #include <limits> 32 #include <numeric> 33 #include <vector> 34 35 //===----------------------------------------------------------------------===// 36 // 37 // Internal support for storing and reading sparse tensors. 38 // 39 // The following memory-resident sparse storage schemes are supported: 40 // 41 // (a) A coordinate scheme for temporarily storing and lexicographically 42 // sorting a sparse tensor by index (SparseTensorCOO). 43 // 44 // (b) A "one-size-fits-all" sparse tensor storage scheme defined by 45 // per-dimension sparse/dense annnotations together with a dimension 46 // ordering used by MLIR compiler-generated code (SparseTensorStorage). 47 // 48 // The following external formats are supported: 49 // 50 // (1) Matrix Market Exchange (MME): *.mtx 51 // https://math.nist.gov/MatrixMarket/formats.html 52 // 53 // (2) Formidable Repository of Open Sparse Tensors and Tools (FROSTT): *.tns 54 // http://frostt.io/tensors/file-formats.html 55 // 56 // Two public APIs are supported: 57 // 58 // (I) Methods operating on MLIR buffers (memrefs) to interact with sparse 59 // tensors. These methods should be used exclusively by MLIR 60 // compiler-generated code. 61 // 62 // (II) Methods that accept C-style data structures to interact with sparse 63 // tensors. These methods can be used by any external runtime that wants 64 // to interact with MLIR compiler-generated code. 65 // 66 // In both cases (I) and (II), the SparseTensorStorage format is externally 67 // only visible as an opaque pointer. 68 // 69 //===----------------------------------------------------------------------===// 70 71 namespace { 72 73 static constexpr int kColWidth = 1025; 74 75 /// A sparse tensor element in coordinate scheme (value and indices). 76 /// For example, a rank-1 vector element would look like 77 /// ({i}, a[i]) 78 /// and a rank-5 tensor element like 79 /// ({i,j,k,l,m}, a[i,j,k,l,m]) 80 template <typename V> 81 struct Element { 82 Element(const std::vector<uint64_t> &ind, V val) : indices(ind), value(val){}; 83 std::vector<uint64_t> indices; 84 V value; 85 /// Returns true if indices of e1 < indices of e2. 86 static bool lexOrder(const Element<V> &e1, const Element<V> &e2) { 87 uint64_t rank = e1.indices.size(); 88 assert(rank == e2.indices.size()); 89 for (uint64_t r = 0; r < rank; r++) { 90 if (e1.indices[r] == e2.indices[r]) 91 continue; 92 return e1.indices[r] < e2.indices[r]; 93 } 94 return false; 95 } 96 }; 97 98 /// A memory-resident sparse tensor in coordinate scheme (collection of 99 /// elements). This data structure is used to read a sparse tensor from 100 /// any external format into memory and sort the elements lexicographically 101 /// by indices before passing it back to the client (most packed storage 102 /// formats require the elements to appear in lexicographic index order). 103 template <typename V> 104 struct SparseTensorCOO { 105 public: 106 SparseTensorCOO(const std::vector<uint64_t> &szs, uint64_t capacity) 107 : sizes(szs), iteratorLocked(false), iteratorPos(0) { 108 if (capacity) 109 elements.reserve(capacity); 110 } 111 /// Adds element as indices and value. 112 void add(const std::vector<uint64_t> &ind, V val) { 113 assert(!iteratorLocked && "Attempt to add() after startIterator()"); 114 uint64_t rank = getRank(); 115 assert(rank == ind.size()); 116 for (uint64_t r = 0; r < rank; r++) 117 assert(ind[r] < sizes[r]); // within bounds 118 elements.emplace_back(ind, val); 119 } 120 /// Sorts elements lexicographically by index. 121 void sort() { 122 assert(!iteratorLocked && "Attempt to sort() after startIterator()"); 123 // TODO: we may want to cache an `isSorted` bit, to avoid 124 // unnecessary/redundant sorting. 125 std::sort(elements.begin(), elements.end(), Element<V>::lexOrder); 126 } 127 /// Returns rank. 128 uint64_t getRank() const { return sizes.size(); } 129 /// Getter for sizes array. 130 const std::vector<uint64_t> &getSizes() const { return sizes; } 131 /// Getter for elements array. 132 const std::vector<Element<V>> &getElements() const { return elements; } 133 134 /// Switch into iterator mode. 135 void startIterator() { 136 iteratorLocked = true; 137 iteratorPos = 0; 138 } 139 /// Get the next element. 140 const Element<V> *getNext() { 141 assert(iteratorLocked && "Attempt to getNext() before startIterator()"); 142 if (iteratorPos < elements.size()) 143 return &(elements[iteratorPos++]); 144 iteratorLocked = false; 145 return nullptr; 146 } 147 148 /// Factory method. Permutes the original dimensions according to 149 /// the given ordering and expects subsequent add() calls to honor 150 /// that same ordering for the given indices. The result is a 151 /// fully permuted coordinate scheme. 152 static SparseTensorCOO<V> *newSparseTensorCOO(uint64_t rank, 153 const uint64_t *sizes, 154 const uint64_t *perm, 155 uint64_t capacity = 0) { 156 std::vector<uint64_t> permsz(rank); 157 for (uint64_t r = 0; r < rank; r++) { 158 assert(sizes[r] > 0 && "Dimension size zero has trivial storage"); 159 permsz[perm[r]] = sizes[r]; 160 } 161 return new SparseTensorCOO<V>(permsz, capacity); 162 } 163 164 private: 165 const std::vector<uint64_t> sizes; // per-dimension sizes 166 std::vector<Element<V>> elements; 167 bool iteratorLocked; 168 unsigned iteratorPos; 169 }; 170 171 /// Abstract base class of sparse tensor storage. Note that we use 172 /// function overloading to implement "partial" method specialization. 173 class SparseTensorStorageBase { 174 public: 175 /// Dimension size query. 176 virtual uint64_t getDimSize(uint64_t) const = 0; 177 178 /// Overhead storage. 179 virtual void getPointers(std::vector<uint64_t> **, uint64_t) { fatal("p64"); } 180 virtual void getPointers(std::vector<uint32_t> **, uint64_t) { fatal("p32"); } 181 virtual void getPointers(std::vector<uint16_t> **, uint64_t) { fatal("p16"); } 182 virtual void getPointers(std::vector<uint8_t> **, uint64_t) { fatal("p8"); } 183 virtual void getIndices(std::vector<uint64_t> **, uint64_t) { fatal("i64"); } 184 virtual void getIndices(std::vector<uint32_t> **, uint64_t) { fatal("i32"); } 185 virtual void getIndices(std::vector<uint16_t> **, uint64_t) { fatal("i16"); } 186 virtual void getIndices(std::vector<uint8_t> **, uint64_t) { fatal("i8"); } 187 188 /// Primary storage. 189 virtual void getValues(std::vector<double> **) { fatal("valf64"); } 190 virtual void getValues(std::vector<float> **) { fatal("valf32"); } 191 virtual void getValues(std::vector<int64_t> **) { fatal("vali64"); } 192 virtual void getValues(std::vector<int32_t> **) { fatal("vali32"); } 193 virtual void getValues(std::vector<int16_t> **) { fatal("vali16"); } 194 virtual void getValues(std::vector<int8_t> **) { fatal("vali8"); } 195 196 /// Element-wise insertion in lexicographic index order. 197 virtual void lexInsert(const uint64_t *, double) { fatal("insf64"); } 198 virtual void lexInsert(const uint64_t *, float) { fatal("insf32"); } 199 virtual void lexInsert(const uint64_t *, int64_t) { fatal("insi64"); } 200 virtual void lexInsert(const uint64_t *, int32_t) { fatal("insi32"); } 201 virtual void lexInsert(const uint64_t *, int16_t) { fatal("ins16"); } 202 virtual void lexInsert(const uint64_t *, int8_t) { fatal("insi8"); } 203 204 /// Expanded insertion. 205 virtual void expInsert(uint64_t *, double *, bool *, uint64_t *, uint64_t) { 206 fatal("expf64"); 207 } 208 virtual void expInsert(uint64_t *, float *, bool *, uint64_t *, uint64_t) { 209 fatal("expf32"); 210 } 211 virtual void expInsert(uint64_t *, int64_t *, bool *, uint64_t *, uint64_t) { 212 fatal("expi64"); 213 } 214 virtual void expInsert(uint64_t *, int32_t *, bool *, uint64_t *, uint64_t) { 215 fatal("expi32"); 216 } 217 virtual void expInsert(uint64_t *, int16_t *, bool *, uint64_t *, uint64_t) { 218 fatal("expi16"); 219 } 220 virtual void expInsert(uint64_t *, int8_t *, bool *, uint64_t *, uint64_t) { 221 fatal("expi8"); 222 } 223 224 /// Finishes insertion. 225 virtual void endInsert() = 0; 226 227 virtual ~SparseTensorStorageBase() = default; 228 229 private: 230 static void fatal(const char *tp) { 231 fprintf(stderr, "unsupported %s\n", tp); 232 exit(1); 233 } 234 }; 235 236 /// A memory-resident sparse tensor using a storage scheme based on 237 /// per-dimension sparse/dense annotations. This data structure provides a 238 /// bufferized form of a sparse tensor type. In contrast to generating setup 239 /// methods for each differently annotated sparse tensor, this method provides 240 /// a convenient "one-size-fits-all" solution that simply takes an input tensor 241 /// and annotations to implement all required setup in a general manner. 242 template <typename P, typename I, typename V> 243 class SparseTensorStorage : public SparseTensorStorageBase { 244 public: 245 /// Constructs a sparse tensor storage scheme with the given dimensions, 246 /// permutation, and per-dimension dense/sparse annotations, using 247 /// the coordinate scheme tensor for the initial contents if provided. 248 SparseTensorStorage(const std::vector<uint64_t> &szs, const uint64_t *perm, 249 const DimLevelType *sparsity, 250 SparseTensorCOO<V> *tensor = nullptr) 251 : sizes(szs), rev(getRank()), idx(getRank()), pointers(getRank()), 252 indices(getRank()) { 253 uint64_t rank = getRank(); 254 // Store "reverse" permutation. 255 for (uint64_t r = 0; r < rank; r++) 256 rev[perm[r]] = r; 257 // Provide hints on capacity of pointers and indices. 258 // TODO: needs fine-tuning based on sparsity 259 bool allDense = true; 260 uint64_t sz = 1; 261 for (uint64_t r = 0; r < rank; r++) { 262 assert(sizes[r] > 0 && "Dimension size zero has trivial storage"); 263 sz *= sizes[r]; 264 if (sparsity[r] == DimLevelType::kCompressed) { 265 pointers[r].reserve(sz + 1); 266 indices[r].reserve(sz); 267 sz = 1; 268 allDense = false; 269 // Prepare the pointer structure. We cannot use `appendPointer` 270 // here, because `isCompressedDim` won't work until after this 271 // preparation has been done. 272 pointers[r].push_back(0); 273 } else { 274 assert(sparsity[r] == DimLevelType::kDense && 275 "singleton not yet supported"); 276 } 277 } 278 // Then assign contents from coordinate scheme tensor if provided. 279 if (tensor) { 280 // Ensure both preconditions of `fromCOO`. 281 assert(tensor->getSizes() == sizes && "Tensor size mismatch"); 282 tensor->sort(); 283 // Now actually insert the `elements`. 284 const std::vector<Element<V>> &elements = tensor->getElements(); 285 uint64_t nnz = elements.size(); 286 values.reserve(nnz); 287 fromCOO(elements, 0, nnz, 0); 288 } else if (allDense) { 289 values.resize(sz, 0); 290 } 291 } 292 293 ~SparseTensorStorage() override = default; 294 295 /// Get the rank of the tensor. 296 uint64_t getRank() const { return sizes.size(); } 297 298 /// Get the size of the given dimension of the tensor. 299 uint64_t getDimSize(uint64_t d) const override { 300 assert(d < getRank()); 301 return sizes[d]; 302 } 303 304 /// Partially specialize these getter methods based on template types. 305 void getPointers(std::vector<P> **out, uint64_t d) override { 306 assert(d < getRank()); 307 *out = &pointers[d]; 308 } 309 void getIndices(std::vector<I> **out, uint64_t d) override { 310 assert(d < getRank()); 311 *out = &indices[d]; 312 } 313 void getValues(std::vector<V> **out) override { *out = &values; } 314 315 /// Partially specialize lexicographical insertions based on template types. 316 void lexInsert(const uint64_t *cursor, V val) override { 317 // First, wrap up pending insertion path. 318 uint64_t diff = 0; 319 uint64_t top = 0; 320 if (!values.empty()) { 321 diff = lexDiff(cursor); 322 endPath(diff + 1); 323 top = idx[diff] + 1; 324 } 325 // Then continue with insertion path. 326 insPath(cursor, diff, top, val); 327 } 328 329 /// Partially specialize expanded insertions based on template types. 330 /// Note that this method resets the values/filled-switch array back 331 /// to all-zero/false while only iterating over the nonzero elements. 332 void expInsert(uint64_t *cursor, V *values, bool *filled, uint64_t *added, 333 uint64_t count) override { 334 if (count == 0) 335 return; 336 // Sort. 337 std::sort(added, added + count); 338 // Restore insertion path for first insert. 339 uint64_t rank = getRank(); 340 uint64_t index = added[0]; 341 cursor[rank - 1] = index; 342 lexInsert(cursor, values[index]); 343 assert(filled[index]); 344 values[index] = 0; 345 filled[index] = false; 346 // Subsequent insertions are quick. 347 for (uint64_t i = 1; i < count; i++) { 348 assert(index < added[i] && "non-lexicographic insertion"); 349 index = added[i]; 350 cursor[rank - 1] = index; 351 insPath(cursor, rank - 1, added[i - 1] + 1, values[index]); 352 assert(filled[index]); 353 values[index] = 0.0; 354 filled[index] = false; 355 } 356 } 357 358 /// Finalizes lexicographic insertions. 359 void endInsert() override { 360 if (values.empty()) 361 endDim(0); 362 else 363 endPath(0); 364 } 365 366 /// Returns this sparse tensor storage scheme as a new memory-resident 367 /// sparse tensor in coordinate scheme with the given dimension order. 368 SparseTensorCOO<V> *toCOO(const uint64_t *perm) { 369 // Restore original order of the dimension sizes and allocate coordinate 370 // scheme with desired new ordering specified in perm. 371 uint64_t rank = getRank(); 372 std::vector<uint64_t> orgsz(rank); 373 for (uint64_t r = 0; r < rank; r++) 374 orgsz[rev[r]] = sizes[r]; 375 SparseTensorCOO<V> *tensor = SparseTensorCOO<V>::newSparseTensorCOO( 376 rank, orgsz.data(), perm, values.size()); 377 // Populate coordinate scheme restored from old ordering and changed with 378 // new ordering. Rather than applying both reorderings during the recursion, 379 // we compute the combine permutation in advance. 380 std::vector<uint64_t> reord(rank); 381 for (uint64_t r = 0; r < rank; r++) 382 reord[r] = perm[rev[r]]; 383 toCOO(*tensor, reord, 0, 0); 384 assert(tensor->getElements().size() == values.size()); 385 return tensor; 386 } 387 388 /// Factory method. Constructs a sparse tensor storage scheme with the given 389 /// dimensions, permutation, and per-dimension dense/sparse annotations, 390 /// using the coordinate scheme tensor for the initial contents if provided. 391 /// In the latter case, the coordinate scheme must respect the same 392 /// permutation as is desired for the new sparse tensor storage. 393 static SparseTensorStorage<P, I, V> * 394 newSparseTensor(uint64_t rank, const uint64_t *shape, const uint64_t *perm, 395 const DimLevelType *sparsity, SparseTensorCOO<V> *tensor) { 396 SparseTensorStorage<P, I, V> *n = nullptr; 397 if (tensor) { 398 assert(tensor->getRank() == rank); 399 for (uint64_t r = 0; r < rank; r++) 400 assert(shape[r] == 0 || shape[r] == tensor->getSizes()[perm[r]]); 401 n = new SparseTensorStorage<P, I, V>(tensor->getSizes(), perm, sparsity, 402 tensor); 403 } else { 404 std::vector<uint64_t> permsz(rank); 405 for (uint64_t r = 0; r < rank; r++) { 406 assert(shape[r] > 0 && "Dimension size zero has trivial storage"); 407 permsz[perm[r]] = shape[r]; 408 } 409 n = new SparseTensorStorage<P, I, V>(permsz, perm, sparsity); 410 } 411 return n; 412 } 413 414 private: 415 /// Appends the next free position of `indices[d]` to `pointers[d]`. 416 /// Thus, when called after inserting the last element of a segment, 417 /// it will append the position where the next segment begins. 418 inline void appendPointer(uint64_t d) { 419 assert(isCompressedDim(d)); // Entails `d < getRank()`. 420 uint64_t p = indices[d].size(); 421 assert(p <= std::numeric_limits<P>::max() && 422 "Pointer value is too large for the P-type"); 423 pointers[d].push_back(p); // Here is where we convert to `P`. 424 } 425 426 /// Appends the given index to `indices[d]`. 427 inline void appendIndex(uint64_t d, uint64_t i) { 428 assert(isCompressedDim(d)); // Entails `d < getRank()`. 429 assert(i <= std::numeric_limits<I>::max() && 430 "Index value is too large for the I-type"); 431 indices[d].push_back(i); // Here is where we convert to `I`. 432 } 433 434 /// Initializes sparse tensor storage scheme from a memory-resident sparse 435 /// tensor in coordinate scheme. This method prepares the pointers and 436 /// indices arrays under the given per-dimension dense/sparse annotations. 437 /// 438 /// Preconditions: 439 /// (1) the `elements` must be lexicographically sorted. 440 /// (2) the indices of every element are valid for `sizes` (equal rank 441 /// and pointwise less-than). 442 void fromCOO(const std::vector<Element<V>> &elements, uint64_t lo, 443 uint64_t hi, uint64_t d) { 444 // Once dimensions are exhausted, insert the numerical values. 445 assert(d <= getRank() && hi <= elements.size()); 446 if (d == getRank()) { 447 assert(lo < hi); 448 values.push_back(elements[lo].value); 449 return; 450 } 451 // Visit all elements in this interval. 452 uint64_t full = 0; 453 while (lo < hi) { // If `hi` is unchanged, then `lo < elements.size()`. 454 // Find segment in interval with same index elements in this dimension. 455 uint64_t i = elements[lo].indices[d]; 456 uint64_t seg = lo + 1; 457 while (seg < hi && elements[seg].indices[d] == i) 458 seg++; 459 // Handle segment in interval for sparse or dense dimension. 460 if (isCompressedDim(d)) { 461 appendIndex(d, i); 462 } else { 463 // For dense storage we must fill in all the zero values between 464 // the previous element (when last we ran this for-loop) and the 465 // current element. 466 for (; full < i; full++) 467 endDim(d + 1); 468 full++; 469 } 470 fromCOO(elements, lo, seg, d + 1); 471 // And move on to next segment in interval. 472 lo = seg; 473 } 474 // Finalize the sparse pointer structure at this dimension. 475 if (isCompressedDim(d)) { 476 appendPointer(d); 477 } else { 478 // For dense storage we must fill in all the zero values after 479 // the last element. 480 for (uint64_t sz = sizes[d]; full < sz; full++) 481 endDim(d + 1); 482 } 483 } 484 485 /// Stores the sparse tensor storage scheme into a memory-resident sparse 486 /// tensor in coordinate scheme. 487 void toCOO(SparseTensorCOO<V> &tensor, std::vector<uint64_t> &reord, 488 uint64_t pos, uint64_t d) { 489 assert(d <= getRank()); 490 if (d == getRank()) { 491 assert(pos < values.size()); 492 tensor.add(idx, values[pos]); 493 } else if (isCompressedDim(d)) { 494 // Sparse dimension. 495 for (uint64_t ii = pointers[d][pos]; ii < pointers[d][pos + 1]; ii++) { 496 idx[reord[d]] = indices[d][ii]; 497 toCOO(tensor, reord, ii, d + 1); 498 } 499 } else { 500 // Dense dimension. 501 for (uint64_t i = 0, sz = sizes[d], off = pos * sz; i < sz; i++) { 502 idx[reord[d]] = i; 503 toCOO(tensor, reord, off + i, d + 1); 504 } 505 } 506 } 507 508 /// Ends a deeper, never seen before dimension. 509 void endDim(uint64_t d) { 510 assert(d <= getRank()); 511 if (d == getRank()) { 512 values.push_back(0); 513 } else if (isCompressedDim(d)) { 514 appendPointer(d); 515 } else { 516 for (uint64_t full = 0, sz = sizes[d]; full < sz; full++) 517 endDim(d + 1); 518 } 519 } 520 521 /// Wraps up a single insertion path, inner to outer. 522 void endPath(uint64_t diff) { 523 uint64_t rank = getRank(); 524 assert(diff <= rank); 525 for (uint64_t i = 0; i < rank - diff; i++) { 526 uint64_t d = rank - i - 1; 527 if (isCompressedDim(d)) { 528 appendPointer(d); 529 } else { 530 for (uint64_t full = idx[d] + 1, sz = sizes[d]; full < sz; full++) 531 endDim(d + 1); 532 } 533 } 534 } 535 536 /// Continues a single insertion path, outer to inner. 537 void insPath(const uint64_t *cursor, uint64_t diff, uint64_t top, V val) { 538 uint64_t rank = getRank(); 539 assert(diff < rank); 540 for (uint64_t d = diff; d < rank; d++) { 541 uint64_t i = cursor[d]; 542 if (isCompressedDim(d)) { 543 appendIndex(d, i); 544 } else { 545 for (uint64_t full = top; full < i; full++) 546 endDim(d + 1); 547 } 548 top = 0; 549 idx[d] = i; 550 } 551 values.push_back(val); 552 } 553 554 /// Finds the lexicographic differing dimension. 555 uint64_t lexDiff(const uint64_t *cursor) const { 556 for (uint64_t r = 0, rank = getRank(); r < rank; r++) 557 if (cursor[r] > idx[r]) 558 return r; 559 else 560 assert(cursor[r] == idx[r] && "non-lexicographic insertion"); 561 assert(0 && "duplication insertion"); 562 return -1u; 563 } 564 565 /// Returns true if dimension is compressed. 566 inline bool isCompressedDim(uint64_t d) const { 567 assert(d < getRank()); 568 return (!pointers[d].empty()); 569 } 570 571 private: 572 const std::vector<uint64_t> sizes; // per-dimension sizes 573 std::vector<uint64_t> rev; // "reverse" permutation 574 std::vector<uint64_t> idx; // index cursor 575 std::vector<std::vector<P>> pointers; 576 std::vector<std::vector<I>> indices; 577 std::vector<V> values; 578 }; 579 580 /// Helper to convert string to lower case. 581 static char *toLower(char *token) { 582 for (char *c = token; *c; c++) 583 *c = tolower(*c); 584 return token; 585 } 586 587 /// Read the MME header of a general sparse matrix of type real. 588 static void readMMEHeader(FILE *file, char *filename, char *line, 589 uint64_t *idata, bool *isSymmetric) { 590 char header[64]; 591 char object[64]; 592 char format[64]; 593 char field[64]; 594 char symmetry[64]; 595 // Read header line. 596 if (fscanf(file, "%63s %63s %63s %63s %63s\n", header, object, format, field, 597 symmetry) != 5) { 598 fprintf(stderr, "Corrupt header in %s\n", filename); 599 exit(1); 600 } 601 *isSymmetric = (strcmp(toLower(symmetry), "symmetric") == 0); 602 // Make sure this is a general sparse matrix. 603 if (strcmp(toLower(header), "%%matrixmarket") || 604 strcmp(toLower(object), "matrix") || 605 strcmp(toLower(format), "coordinate") || strcmp(toLower(field), "real") || 606 (strcmp(toLower(symmetry), "general") && !(*isSymmetric))) { 607 fprintf(stderr, 608 "Cannot find a general sparse matrix with type real in %s\n", 609 filename); 610 exit(1); 611 } 612 // Skip comments. 613 while (true) { 614 if (!fgets(line, kColWidth, file)) { 615 fprintf(stderr, "Cannot find data in %s\n", filename); 616 exit(1); 617 } 618 if (line[0] != '%') 619 break; 620 } 621 // Next line contains M N NNZ. 622 idata[0] = 2; // rank 623 if (sscanf(line, "%" PRIu64 "%" PRIu64 "%" PRIu64 "\n", idata + 2, idata + 3, 624 idata + 1) != 3) { 625 fprintf(stderr, "Cannot find size in %s\n", filename); 626 exit(1); 627 } 628 } 629 630 /// Read the "extended" FROSTT header. Although not part of the documented 631 /// format, we assume that the file starts with optional comments followed 632 /// by two lines that define the rank, the number of nonzeros, and the 633 /// dimensions sizes (one per rank) of the sparse tensor. 634 static void readExtFROSTTHeader(FILE *file, char *filename, char *line, 635 uint64_t *idata) { 636 // Skip comments. 637 while (true) { 638 if (!fgets(line, kColWidth, file)) { 639 fprintf(stderr, "Cannot find data in %s\n", filename); 640 exit(1); 641 } 642 if (line[0] != '#') 643 break; 644 } 645 // Next line contains RANK and NNZ. 646 if (sscanf(line, "%" PRIu64 "%" PRIu64 "\n", idata, idata + 1) != 2) { 647 fprintf(stderr, "Cannot find metadata in %s\n", filename); 648 exit(1); 649 } 650 // Followed by a line with the dimension sizes (one per rank). 651 for (uint64_t r = 0; r < idata[0]; r++) { 652 if (fscanf(file, "%" PRIu64, idata + 2 + r) != 1) { 653 fprintf(stderr, "Cannot find dimension size %s\n", filename); 654 exit(1); 655 } 656 } 657 fgets(line, kColWidth, file); // end of line 658 } 659 660 /// Reads a sparse tensor with the given filename into a memory-resident 661 /// sparse tensor in coordinate scheme. 662 template <typename V> 663 static SparseTensorCOO<V> *openSparseTensorCOO(char *filename, uint64_t rank, 664 const uint64_t *shape, 665 const uint64_t *perm) { 666 // Open the file. 667 FILE *file = fopen(filename, "r"); 668 if (!file) { 669 assert(filename && "Received nullptr for filename"); 670 fprintf(stderr, "Cannot find file %s\n", filename); 671 exit(1); 672 } 673 // Perform some file format dependent set up. 674 char line[kColWidth]; 675 uint64_t idata[512]; 676 bool isSymmetric = false; 677 if (strstr(filename, ".mtx")) { 678 readMMEHeader(file, filename, line, idata, &isSymmetric); 679 } else if (strstr(filename, ".tns")) { 680 readExtFROSTTHeader(file, filename, line, idata); 681 } else { 682 fprintf(stderr, "Unknown format %s\n", filename); 683 exit(1); 684 } 685 // Prepare sparse tensor object with per-dimension sizes 686 // and the number of nonzeros as initial capacity. 687 assert(rank == idata[0] && "rank mismatch"); 688 uint64_t nnz = idata[1]; 689 for (uint64_t r = 0; r < rank; r++) 690 assert((shape[r] == 0 || shape[r] == idata[2 + r]) && 691 "dimension size mismatch"); 692 SparseTensorCOO<V> *tensor = 693 SparseTensorCOO<V>::newSparseTensorCOO(rank, idata + 2, perm, nnz); 694 // Read all nonzero elements. 695 std::vector<uint64_t> indices(rank); 696 for (uint64_t k = 0; k < nnz; k++) { 697 if (!fgets(line, kColWidth, file)) { 698 fprintf(stderr, "Cannot find next line of data in %s\n", filename); 699 exit(1); 700 } 701 char *linePtr = line; 702 for (uint64_t r = 0; r < rank; r++) { 703 uint64_t idx = strtoul(linePtr, &linePtr, 10); 704 // Add 0-based index. 705 indices[perm[r]] = idx - 1; 706 } 707 // The external formats always store the numerical values with the type 708 // double, but we cast these values to the sparse tensor object type. 709 double value = strtod(linePtr, &linePtr); 710 tensor->add(indices, value); 711 // We currently chose to deal with symmetric matrices by fully constructing 712 // them. In the future, we may want to make symmetry implicit for storage 713 // reasons. 714 if (isSymmetric && indices[0] != indices[1]) 715 tensor->add({indices[1], indices[0]}, value); 716 } 717 // Close the file and return tensor. 718 fclose(file); 719 return tensor; 720 } 721 722 /// Writes the sparse tensor to extended FROSTT format. 723 template <typename V> 724 static void outSparseTensor(void *tensor, void *dest, bool sort) { 725 assert(tensor && dest); 726 auto coo = static_cast<SparseTensorCOO<V> *>(tensor); 727 if (sort) 728 coo->sort(); 729 char *filename = static_cast<char *>(dest); 730 auto &sizes = coo->getSizes(); 731 auto &elements = coo->getElements(); 732 uint64_t rank = coo->getRank(); 733 uint64_t nnz = elements.size(); 734 std::fstream file; 735 file.open(filename, std::ios_base::out | std::ios_base::trunc); 736 assert(file.is_open()); 737 file << "; extended FROSTT format\n" << rank << " " << nnz << std::endl; 738 for (uint64_t r = 0; r < rank - 1; r++) 739 file << sizes[r] << " "; 740 file << sizes[rank - 1] << std::endl; 741 for (uint64_t i = 0; i < nnz; i++) { 742 auto &idx = elements[i].indices; 743 for (uint64_t r = 0; r < rank; r++) 744 file << (idx[r] + 1) << " "; 745 file << elements[i].value << std::endl; 746 } 747 file.flush(); 748 file.close(); 749 assert(file.good()); 750 } 751 752 /// Initializes sparse tensor from an external COO-flavored format. 753 template <typename V> 754 static SparseTensorStorage<uint64_t, uint64_t, V> * 755 toMLIRSparseTensor(uint64_t rank, uint64_t nse, uint64_t *shape, V *values, 756 uint64_t *indices, uint64_t *perm, uint8_t *sparse) { 757 const DimLevelType *sparsity = (DimLevelType *)(sparse); 758 #ifndef NDEBUG 759 // Verify that perm is a permutation of 0..(rank-1). 760 std::vector<uint64_t> order(perm, perm + rank); 761 std::sort(order.begin(), order.end()); 762 for (uint64_t i = 0; i < rank; ++i) { 763 if (i != order[i]) { 764 fprintf(stderr, "Not a permutation of 0..%" PRIu64 "\n", rank); 765 exit(1); 766 } 767 } 768 769 // Verify that the sparsity values are supported. 770 for (uint64_t i = 0; i < rank; ++i) { 771 if (sparsity[i] != DimLevelType::kDense && 772 sparsity[i] != DimLevelType::kCompressed) { 773 fprintf(stderr, "Unsupported sparsity value %d\n", 774 static_cast<int>(sparsity[i])); 775 exit(1); 776 } 777 } 778 #endif 779 780 // Convert external format to internal COO. 781 auto *coo = SparseTensorCOO<V>::newSparseTensorCOO(rank, shape, perm, nse); 782 std::vector<uint64_t> idx(rank); 783 for (uint64_t i = 0, base = 0; i < nse; i++) { 784 for (uint64_t r = 0; r < rank; r++) 785 idx[perm[r]] = indices[base + r]; 786 coo->add(idx, values[i]); 787 base += rank; 788 } 789 // Return sparse tensor storage format as opaque pointer. 790 auto *tensor = SparseTensorStorage<uint64_t, uint64_t, V>::newSparseTensor( 791 rank, shape, perm, sparsity, coo); 792 delete coo; 793 return tensor; 794 } 795 796 /// Converts a sparse tensor to an external COO-flavored format. 797 template <typename V> 798 static void fromMLIRSparseTensor(void *tensor, uint64_t *pRank, uint64_t *pNse, 799 uint64_t **pShape, V **pValues, 800 uint64_t **pIndices) { 801 auto sparseTensor = 802 static_cast<SparseTensorStorage<uint64_t, uint64_t, V> *>(tensor); 803 uint64_t rank = sparseTensor->getRank(); 804 std::vector<uint64_t> perm(rank); 805 std::iota(perm.begin(), perm.end(), 0); 806 SparseTensorCOO<V> *coo = sparseTensor->toCOO(perm.data()); 807 808 const std::vector<Element<V>> &elements = coo->getElements(); 809 uint64_t nse = elements.size(); 810 811 uint64_t *shape = new uint64_t[rank]; 812 for (uint64_t i = 0; i < rank; i++) 813 shape[i] = coo->getSizes()[i]; 814 815 V *values = new V[nse]; 816 uint64_t *indices = new uint64_t[rank * nse]; 817 818 for (uint64_t i = 0, base = 0; i < nse; i++) { 819 values[i] = elements[i].value; 820 for (uint64_t j = 0; j < rank; j++) 821 indices[base + j] = elements[i].indices[j]; 822 base += rank; 823 } 824 825 delete coo; 826 *pRank = rank; 827 *pNse = nse; 828 *pShape = shape; 829 *pValues = values; 830 *pIndices = indices; 831 } 832 833 } // namespace 834 835 extern "C" { 836 837 //===----------------------------------------------------------------------===// 838 // 839 // Public API with methods that operate on MLIR buffers (memrefs) to interact 840 // with sparse tensors, which are only visible as opaque pointers externally. 841 // These methods should be used exclusively by MLIR compiler-generated code. 842 // 843 // Some macro magic is used to generate implementations for all required type 844 // combinations that can be called from MLIR compiler-generated code. 845 // 846 //===----------------------------------------------------------------------===// 847 848 #define CASE(p, i, v, P, I, V) \ 849 if (ptrTp == (p) && indTp == (i) && valTp == (v)) { \ 850 SparseTensorCOO<V> *coo = nullptr; \ 851 if (action <= Action::kFromCOO) { \ 852 if (action == Action::kFromFile) { \ 853 char *filename = static_cast<char *>(ptr); \ 854 coo = openSparseTensorCOO<V>(filename, rank, shape, perm); \ 855 } else if (action == Action::kFromCOO) { \ 856 coo = static_cast<SparseTensorCOO<V> *>(ptr); \ 857 } else { \ 858 assert(action == Action::kEmpty); \ 859 } \ 860 auto *tensor = SparseTensorStorage<P, I, V>::newSparseTensor( \ 861 rank, shape, perm, sparsity, coo); \ 862 if (action == Action::kFromFile) \ 863 delete coo; \ 864 return tensor; \ 865 } \ 866 if (action == Action::kEmptyCOO) \ 867 return SparseTensorCOO<V>::newSparseTensorCOO(rank, shape, perm); \ 868 coo = static_cast<SparseTensorStorage<P, I, V> *>(ptr)->toCOO(perm); \ 869 if (action == Action::kToIterator) { \ 870 coo->startIterator(); \ 871 } else { \ 872 assert(action == Action::kToCOO); \ 873 } \ 874 return coo; \ 875 } 876 877 #define CASE_SECSAME(p, v, P, V) CASE(p, p, v, P, P, V) 878 879 #define IMPL_SPARSEVALUES(NAME, TYPE, LIB) \ 880 void _mlir_ciface_##NAME(StridedMemRefType<TYPE, 1> *ref, void *tensor) { \ 881 assert(ref &&tensor); \ 882 std::vector<TYPE> *v; \ 883 static_cast<SparseTensorStorageBase *>(tensor)->LIB(&v); \ 884 ref->basePtr = ref->data = v->data(); \ 885 ref->offset = 0; \ 886 ref->sizes[0] = v->size(); \ 887 ref->strides[0] = 1; \ 888 } 889 890 #define IMPL_GETOVERHEAD(NAME, TYPE, LIB) \ 891 void _mlir_ciface_##NAME(StridedMemRefType<TYPE, 1> *ref, void *tensor, \ 892 index_type d) { \ 893 assert(ref &&tensor); \ 894 std::vector<TYPE> *v; \ 895 static_cast<SparseTensorStorageBase *>(tensor)->LIB(&v, d); \ 896 ref->basePtr = ref->data = v->data(); \ 897 ref->offset = 0; \ 898 ref->sizes[0] = v->size(); \ 899 ref->strides[0] = 1; \ 900 } 901 902 #define IMPL_ADDELT(NAME, TYPE) \ 903 void *_mlir_ciface_##NAME(void *tensor, TYPE value, \ 904 StridedMemRefType<index_type, 1> *iref, \ 905 StridedMemRefType<index_type, 1> *pref) { \ 906 assert(tensor &&iref &&pref); \ 907 assert(iref->strides[0] == 1 && pref->strides[0] == 1); \ 908 assert(iref->sizes[0] == pref->sizes[0]); \ 909 const index_type *indx = iref->data + iref->offset; \ 910 const index_type *perm = pref->data + pref->offset; \ 911 uint64_t isize = iref->sizes[0]; \ 912 std::vector<index_type> indices(isize); \ 913 for (uint64_t r = 0; r < isize; r++) \ 914 indices[perm[r]] = indx[r]; \ 915 static_cast<SparseTensorCOO<TYPE> *>(tensor)->add(indices, value); \ 916 return tensor; \ 917 } 918 919 #define IMPL_GETNEXT(NAME, V) \ 920 bool _mlir_ciface_##NAME(void *tensor, \ 921 StridedMemRefType<index_type, 1> *iref, \ 922 StridedMemRefType<V, 0> *vref) { \ 923 assert(tensor &&iref &&vref); \ 924 assert(iref->strides[0] == 1); \ 925 index_type *indx = iref->data + iref->offset; \ 926 V *value = vref->data + vref->offset; \ 927 const uint64_t isize = iref->sizes[0]; \ 928 auto iter = static_cast<SparseTensorCOO<V> *>(tensor); \ 929 const Element<V> *elem = iter->getNext(); \ 930 if (elem == nullptr) \ 931 return false; \ 932 for (uint64_t r = 0; r < isize; r++) \ 933 indx[r] = elem->indices[r]; \ 934 *value = elem->value; \ 935 return true; \ 936 } 937 938 #define IMPL_LEXINSERT(NAME, V) \ 939 void _mlir_ciface_##NAME(void *tensor, \ 940 StridedMemRefType<index_type, 1> *cref, V val) { \ 941 assert(tensor &&cref); \ 942 assert(cref->strides[0] == 1); \ 943 index_type *cursor = cref->data + cref->offset; \ 944 assert(cursor); \ 945 static_cast<SparseTensorStorageBase *>(tensor)->lexInsert(cursor, val); \ 946 } 947 948 #define IMPL_EXPINSERT(NAME, V) \ 949 void _mlir_ciface_##NAME( \ 950 void *tensor, StridedMemRefType<index_type, 1> *cref, \ 951 StridedMemRefType<V, 1> *vref, StridedMemRefType<bool, 1> *fref, \ 952 StridedMemRefType<index_type, 1> *aref, index_type count) { \ 953 assert(tensor &&cref &&vref &&fref &&aref); \ 954 assert(cref->strides[0] == 1); \ 955 assert(vref->strides[0] == 1); \ 956 assert(fref->strides[0] == 1); \ 957 assert(aref->strides[0] == 1); \ 958 assert(vref->sizes[0] == fref->sizes[0]); \ 959 index_type *cursor = cref->data + cref->offset; \ 960 V *values = vref->data + vref->offset; \ 961 bool *filled = fref->data + fref->offset; \ 962 index_type *added = aref->data + aref->offset; \ 963 static_cast<SparseTensorStorageBase *>(tensor)->expInsert( \ 964 cursor, values, filled, added, count); \ 965 } 966 967 // Assume index_type is in fact uint64_t, so that _mlir_ciface_newSparseTensor 968 // can safely rewrite kIndex to kU64. We make this assertion to guarantee 969 // that this file cannot get out of sync with its header. 970 static_assert(std::is_same<index_type, uint64_t>::value, 971 "Expected index_type == uint64_t"); 972 973 /// Constructs a new sparse tensor. This is the "swiss army knife" 974 /// method for materializing sparse tensors into the computation. 975 /// 976 /// Action: 977 /// kEmpty = returns empty storage to fill later 978 /// kFromFile = returns storage, where ptr contains filename to read 979 /// kFromCOO = returns storage, where ptr contains coordinate scheme to assign 980 /// kEmptyCOO = returns empty coordinate scheme to fill and use with kFromCOO 981 /// kToCOO = returns coordinate scheme from storage in ptr to use with kFromCOO 982 /// kToIterator = returns iterator from storage in ptr (call getNext() to use) 983 void * 984 _mlir_ciface_newSparseTensor(StridedMemRefType<DimLevelType, 1> *aref, // NOLINT 985 StridedMemRefType<index_type, 1> *sref, 986 StridedMemRefType<index_type, 1> *pref, 987 OverheadType ptrTp, OverheadType indTp, 988 PrimaryType valTp, Action action, void *ptr) { 989 assert(aref && sref && pref); 990 assert(aref->strides[0] == 1 && sref->strides[0] == 1 && 991 pref->strides[0] == 1); 992 assert(aref->sizes[0] == sref->sizes[0] && sref->sizes[0] == pref->sizes[0]); 993 const DimLevelType *sparsity = aref->data + aref->offset; 994 const index_type *shape = sref->data + sref->offset; 995 const index_type *perm = pref->data + pref->offset; 996 uint64_t rank = aref->sizes[0]; 997 998 // Rewrite kIndex to kU64, to avoid introducing a bunch of new cases. 999 // This is safe because of the static_assert above. 1000 if (ptrTp == OverheadType::kIndex) 1001 ptrTp = OverheadType::kU64; 1002 if (indTp == OverheadType::kIndex) 1003 indTp = OverheadType::kU64; 1004 1005 // Double matrices with all combinations of overhead storage. 1006 CASE(OverheadType::kU64, OverheadType::kU64, PrimaryType::kF64, uint64_t, 1007 uint64_t, double); 1008 CASE(OverheadType::kU64, OverheadType::kU32, PrimaryType::kF64, uint64_t, 1009 uint32_t, double); 1010 CASE(OverheadType::kU64, OverheadType::kU16, PrimaryType::kF64, uint64_t, 1011 uint16_t, double); 1012 CASE(OverheadType::kU64, OverheadType::kU8, PrimaryType::kF64, uint64_t, 1013 uint8_t, double); 1014 CASE(OverheadType::kU32, OverheadType::kU64, PrimaryType::kF64, uint32_t, 1015 uint64_t, double); 1016 CASE(OverheadType::kU32, OverheadType::kU32, PrimaryType::kF64, uint32_t, 1017 uint32_t, double); 1018 CASE(OverheadType::kU32, OverheadType::kU16, PrimaryType::kF64, uint32_t, 1019 uint16_t, double); 1020 CASE(OverheadType::kU32, OverheadType::kU8, PrimaryType::kF64, uint32_t, 1021 uint8_t, double); 1022 CASE(OverheadType::kU16, OverheadType::kU64, PrimaryType::kF64, uint16_t, 1023 uint64_t, double); 1024 CASE(OverheadType::kU16, OverheadType::kU32, PrimaryType::kF64, uint16_t, 1025 uint32_t, double); 1026 CASE(OverheadType::kU16, OverheadType::kU16, PrimaryType::kF64, uint16_t, 1027 uint16_t, double); 1028 CASE(OverheadType::kU16, OverheadType::kU8, PrimaryType::kF64, uint16_t, 1029 uint8_t, double); 1030 CASE(OverheadType::kU8, OverheadType::kU64, PrimaryType::kF64, uint8_t, 1031 uint64_t, double); 1032 CASE(OverheadType::kU8, OverheadType::kU32, PrimaryType::kF64, uint8_t, 1033 uint32_t, double); 1034 CASE(OverheadType::kU8, OverheadType::kU16, PrimaryType::kF64, uint8_t, 1035 uint16_t, double); 1036 CASE(OverheadType::kU8, OverheadType::kU8, PrimaryType::kF64, uint8_t, 1037 uint8_t, double); 1038 1039 // Float matrices with all combinations of overhead storage. 1040 CASE(OverheadType::kU64, OverheadType::kU64, PrimaryType::kF32, uint64_t, 1041 uint64_t, float); 1042 CASE(OverheadType::kU64, OverheadType::kU32, PrimaryType::kF32, uint64_t, 1043 uint32_t, float); 1044 CASE(OverheadType::kU64, OverheadType::kU16, PrimaryType::kF32, uint64_t, 1045 uint16_t, float); 1046 CASE(OverheadType::kU64, OverheadType::kU8, PrimaryType::kF32, uint64_t, 1047 uint8_t, float); 1048 CASE(OverheadType::kU32, OverheadType::kU64, PrimaryType::kF32, uint32_t, 1049 uint64_t, float); 1050 CASE(OverheadType::kU32, OverheadType::kU32, PrimaryType::kF32, uint32_t, 1051 uint32_t, float); 1052 CASE(OverheadType::kU32, OverheadType::kU16, PrimaryType::kF32, uint32_t, 1053 uint16_t, float); 1054 CASE(OverheadType::kU32, OverheadType::kU8, PrimaryType::kF32, uint32_t, 1055 uint8_t, float); 1056 CASE(OverheadType::kU16, OverheadType::kU64, PrimaryType::kF32, uint16_t, 1057 uint64_t, float); 1058 CASE(OverheadType::kU16, OverheadType::kU32, PrimaryType::kF32, uint16_t, 1059 uint32_t, float); 1060 CASE(OverheadType::kU16, OverheadType::kU16, PrimaryType::kF32, uint16_t, 1061 uint16_t, float); 1062 CASE(OverheadType::kU16, OverheadType::kU8, PrimaryType::kF32, uint16_t, 1063 uint8_t, float); 1064 CASE(OverheadType::kU8, OverheadType::kU64, PrimaryType::kF32, uint8_t, 1065 uint64_t, float); 1066 CASE(OverheadType::kU8, OverheadType::kU32, PrimaryType::kF32, uint8_t, 1067 uint32_t, float); 1068 CASE(OverheadType::kU8, OverheadType::kU16, PrimaryType::kF32, uint8_t, 1069 uint16_t, float); 1070 CASE(OverheadType::kU8, OverheadType::kU8, PrimaryType::kF32, uint8_t, 1071 uint8_t, float); 1072 1073 // Integral matrices with both overheads of the same type. 1074 CASE_SECSAME(OverheadType::kU64, PrimaryType::kI64, uint64_t, int64_t); 1075 CASE_SECSAME(OverheadType::kU64, PrimaryType::kI32, uint64_t, int32_t); 1076 CASE_SECSAME(OverheadType::kU64, PrimaryType::kI16, uint64_t, int16_t); 1077 CASE_SECSAME(OverheadType::kU64, PrimaryType::kI8, uint64_t, int8_t); 1078 CASE_SECSAME(OverheadType::kU32, PrimaryType::kI32, uint32_t, int32_t); 1079 CASE_SECSAME(OverheadType::kU32, PrimaryType::kI16, uint32_t, int16_t); 1080 CASE_SECSAME(OverheadType::kU32, PrimaryType::kI8, uint32_t, int8_t); 1081 CASE_SECSAME(OverheadType::kU16, PrimaryType::kI32, uint16_t, int32_t); 1082 CASE_SECSAME(OverheadType::kU16, PrimaryType::kI16, uint16_t, int16_t); 1083 CASE_SECSAME(OverheadType::kU16, PrimaryType::kI8, uint16_t, int8_t); 1084 CASE_SECSAME(OverheadType::kU8, PrimaryType::kI32, uint8_t, int32_t); 1085 CASE_SECSAME(OverheadType::kU8, PrimaryType::kI16, uint8_t, int16_t); 1086 CASE_SECSAME(OverheadType::kU8, PrimaryType::kI8, uint8_t, int8_t); 1087 1088 // Unsupported case (add above if needed). 1089 fputs("unsupported combination of types\n", stderr); 1090 exit(1); 1091 } 1092 1093 /// Methods that provide direct access to pointers. 1094 IMPL_GETOVERHEAD(sparsePointers, index_type, getPointers) 1095 IMPL_GETOVERHEAD(sparsePointers64, uint64_t, getPointers) 1096 IMPL_GETOVERHEAD(sparsePointers32, uint32_t, getPointers) 1097 IMPL_GETOVERHEAD(sparsePointers16, uint16_t, getPointers) 1098 IMPL_GETOVERHEAD(sparsePointers8, uint8_t, getPointers) 1099 1100 /// Methods that provide direct access to indices. 1101 IMPL_GETOVERHEAD(sparseIndices, index_type, getIndices) 1102 IMPL_GETOVERHEAD(sparseIndices64, uint64_t, getIndices) 1103 IMPL_GETOVERHEAD(sparseIndices32, uint32_t, getIndices) 1104 IMPL_GETOVERHEAD(sparseIndices16, uint16_t, getIndices) 1105 IMPL_GETOVERHEAD(sparseIndices8, uint8_t, getIndices) 1106 1107 /// Methods that provide direct access to values. 1108 IMPL_SPARSEVALUES(sparseValuesF64, double, getValues) 1109 IMPL_SPARSEVALUES(sparseValuesF32, float, getValues) 1110 IMPL_SPARSEVALUES(sparseValuesI64, int64_t, getValues) 1111 IMPL_SPARSEVALUES(sparseValuesI32, int32_t, getValues) 1112 IMPL_SPARSEVALUES(sparseValuesI16, int16_t, getValues) 1113 IMPL_SPARSEVALUES(sparseValuesI8, int8_t, getValues) 1114 1115 /// Helper to add value to coordinate scheme, one per value type. 1116 IMPL_ADDELT(addEltF64, double) 1117 IMPL_ADDELT(addEltF32, float) 1118 IMPL_ADDELT(addEltI64, int64_t) 1119 IMPL_ADDELT(addEltI32, int32_t) 1120 IMPL_ADDELT(addEltI16, int16_t) 1121 IMPL_ADDELT(addEltI8, int8_t) 1122 1123 /// Helper to enumerate elements of coordinate scheme, one per value type. 1124 IMPL_GETNEXT(getNextF64, double) 1125 IMPL_GETNEXT(getNextF32, float) 1126 IMPL_GETNEXT(getNextI64, int64_t) 1127 IMPL_GETNEXT(getNextI32, int32_t) 1128 IMPL_GETNEXT(getNextI16, int16_t) 1129 IMPL_GETNEXT(getNextI8, int8_t) 1130 1131 /// Insert elements in lexicographical index order, one per value type. 1132 IMPL_LEXINSERT(lexInsertF64, double) 1133 IMPL_LEXINSERT(lexInsertF32, float) 1134 IMPL_LEXINSERT(lexInsertI64, int64_t) 1135 IMPL_LEXINSERT(lexInsertI32, int32_t) 1136 IMPL_LEXINSERT(lexInsertI16, int16_t) 1137 IMPL_LEXINSERT(lexInsertI8, int8_t) 1138 1139 /// Insert using expansion, one per value type. 1140 IMPL_EXPINSERT(expInsertF64, double) 1141 IMPL_EXPINSERT(expInsertF32, float) 1142 IMPL_EXPINSERT(expInsertI64, int64_t) 1143 IMPL_EXPINSERT(expInsertI32, int32_t) 1144 IMPL_EXPINSERT(expInsertI16, int16_t) 1145 IMPL_EXPINSERT(expInsertI8, int8_t) 1146 1147 #undef CASE 1148 #undef IMPL_SPARSEVALUES 1149 #undef IMPL_GETOVERHEAD 1150 #undef IMPL_ADDELT 1151 #undef IMPL_GETNEXT 1152 #undef IMPL_LEXINSERT 1153 #undef IMPL_EXPINSERT 1154 1155 /// Output a sparse tensor, one per value type. 1156 void outSparseTensorF64(void *tensor, void *dest, bool sort) { 1157 return outSparseTensor<double>(tensor, dest, sort); 1158 } 1159 void outSparseTensorF32(void *tensor, void *dest, bool sort) { 1160 return outSparseTensor<float>(tensor, dest, sort); 1161 } 1162 void outSparseTensorI64(void *tensor, void *dest, bool sort) { 1163 return outSparseTensor<int64_t>(tensor, dest, sort); 1164 } 1165 void outSparseTensorI32(void *tensor, void *dest, bool sort) { 1166 return outSparseTensor<int32_t>(tensor, dest, sort); 1167 } 1168 void outSparseTensorI16(void *tensor, void *dest, bool sort) { 1169 return outSparseTensor<int16_t>(tensor, dest, sort); 1170 } 1171 void outSparseTensorI8(void *tensor, void *dest, bool sort) { 1172 return outSparseTensor<int8_t>(tensor, dest, sort); 1173 } 1174 1175 //===----------------------------------------------------------------------===// 1176 // 1177 // Public API with methods that accept C-style data structures to interact 1178 // with sparse tensors, which are only visible as opaque pointers externally. 1179 // These methods can be used both by MLIR compiler-generated code as well as by 1180 // an external runtime that wants to interact with MLIR compiler-generated code. 1181 // 1182 //===----------------------------------------------------------------------===// 1183 1184 /// Helper method to read a sparse tensor filename from the environment, 1185 /// defined with the naming convention ${TENSOR0}, ${TENSOR1}, etc. 1186 char *getTensorFilename(index_type id) { 1187 char var[80]; 1188 sprintf(var, "TENSOR%" PRIu64, id); 1189 char *env = getenv(var); 1190 if (!env) { 1191 fprintf(stderr, "Environment variable %s is not set\n", var); 1192 exit(1); 1193 } 1194 return env; 1195 } 1196 1197 /// Returns size of sparse tensor in given dimension. 1198 index_type sparseDimSize(void *tensor, index_type d) { 1199 return static_cast<SparseTensorStorageBase *>(tensor)->getDimSize(d); 1200 } 1201 1202 /// Finalizes lexicographic insertions. 1203 void endInsert(void *tensor) { 1204 return static_cast<SparseTensorStorageBase *>(tensor)->endInsert(); 1205 } 1206 1207 /// Releases sparse tensor storage. 1208 void delSparseTensor(void *tensor) { 1209 delete static_cast<SparseTensorStorageBase *>(tensor); 1210 } 1211 1212 /// Releases sparse tensor coordinate scheme. 1213 #define IMPL_DELCOO(VNAME, V) \ 1214 void delSparseTensorCOO##VNAME(void *coo) { \ 1215 delete static_cast<SparseTensorCOO<V> *>(coo); \ 1216 } 1217 IMPL_DELCOO(F64, double) 1218 IMPL_DELCOO(F32, float) 1219 IMPL_DELCOO(I64, int64_t) 1220 IMPL_DELCOO(I32, int32_t) 1221 IMPL_DELCOO(I16, int16_t) 1222 IMPL_DELCOO(I8, int8_t) 1223 #undef IMPL_DELCOO 1224 1225 /// Initializes sparse tensor from a COO-flavored format expressed using C-style 1226 /// data structures. The expected parameters are: 1227 /// 1228 /// rank: rank of tensor 1229 /// nse: number of specified elements (usually the nonzeros) 1230 /// shape: array with dimension size for each rank 1231 /// values: a "nse" array with values for all specified elements 1232 /// indices: a flat "nse x rank" array with indices for all specified elements 1233 /// perm: the permutation of the dimensions in the storage 1234 /// sparse: the sparsity for the dimensions 1235 /// 1236 /// For example, the sparse matrix 1237 /// | 1.0 0.0 0.0 | 1238 /// | 0.0 5.0 3.0 | 1239 /// can be passed as 1240 /// rank = 2 1241 /// nse = 3 1242 /// shape = [2, 3] 1243 /// values = [1.0, 5.0, 3.0] 1244 /// indices = [ 0, 0, 1, 1, 1, 2] 1245 // 1246 // TODO: generalize beyond 64-bit indices. 1247 // 1248 void *convertToMLIRSparseTensorF64(uint64_t rank, uint64_t nse, uint64_t *shape, 1249 double *values, uint64_t *indices, 1250 uint64_t *perm, uint8_t *sparse) { 1251 return toMLIRSparseTensor<double>(rank, nse, shape, values, indices, perm, 1252 sparse); 1253 } 1254 void *convertToMLIRSparseTensorF32(uint64_t rank, uint64_t nse, uint64_t *shape, 1255 float *values, uint64_t *indices, 1256 uint64_t *perm, uint8_t *sparse) { 1257 return toMLIRSparseTensor<float>(rank, nse, shape, values, indices, perm, 1258 sparse); 1259 } 1260 1261 /// Converts a sparse tensor to COO-flavored format expressed using C-style 1262 /// data structures. The expected output parameters are pointers for these 1263 /// values: 1264 /// 1265 /// rank: rank of tensor 1266 /// nse: number of specified elements (usually the nonzeros) 1267 /// shape: array with dimension size for each rank 1268 /// values: a "nse" array with values for all specified elements 1269 /// indices: a flat "nse x rank" array with indices for all specified elements 1270 /// 1271 /// The input is a pointer to SparseTensorStorage<P, I, V>, typically returned 1272 /// from convertToMLIRSparseTensor. 1273 /// 1274 // TODO: Currently, values are copied from SparseTensorStorage to 1275 // SparseTensorCOO, then to the output. We may want to reduce the number of 1276 // copies. 1277 // 1278 // TODO: generalize beyond 64-bit indices, no dim ordering, all dimensions 1279 // compressed 1280 // 1281 void convertFromMLIRSparseTensorF64(void *tensor, uint64_t *pRank, 1282 uint64_t *pNse, uint64_t **pShape, 1283 double **pValues, uint64_t **pIndices) { 1284 fromMLIRSparseTensor<double>(tensor, pRank, pNse, pShape, pValues, pIndices); 1285 } 1286 void convertFromMLIRSparseTensorF32(void *tensor, uint64_t *pRank, 1287 uint64_t *pNse, uint64_t **pShape, 1288 float **pValues, uint64_t **pIndices) { 1289 fromMLIRSparseTensor<float>(tensor, pRank, pNse, pShape, pValues, pIndices); 1290 } 1291 1292 } // extern "C" 1293 1294 #endif // MLIR_CRUNNERUTILS_DEFINE_FUNCTIONS 1295