| 576 | |
| 577 | template <typename TYPE> |
| 578 | int64_t StridedTensorCountNonZero(int dim_index, int64_t offset, const Tensor& tensor) { |
| 579 | using c_type = typename TYPE::c_type; |
| 580 | const c_type zero = c_type(0); |
| 581 | int64_t nnz = 0; |
| 582 | if (dim_index == tensor.ndim() - 1) { |
| 583 | for (int64_t i = 0; i < tensor.shape()[dim_index]; ++i) { |
| 584 | const auto* ptr = tensor.raw_data() + offset + i * tensor.strides()[dim_index]; |
| 585 | auto& elem = *reinterpret_cast<const c_type*>(ptr); |
| 586 | if (elem != zero) ++nnz; |
| 587 | } |
| 588 | return nnz; |
| 589 | } |
| 590 | for (int64_t i = 0; i < tensor.shape()[dim_index]; ++i) { |
| 591 | nnz += StridedTensorCountNonZero<TYPE>(dim_index + 1, offset, tensor); |
| 592 | offset += tensor.strides()[dim_index]; |
| 593 | } |
| 594 | return nnz; |
| 595 | } |
| 596 | |
| 597 | template <typename TYPE> |
| 598 | int64_t ContiguousTensorCountNonZero(const Tensor& tensor) { |