|
| 1 | +/* |
| 2 | + * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | + * All rights reserved. |
| 4 | + * |
| 5 | + * This source code is licensed under the BSD-style license found in the |
| 6 | + * LICENSE file in the root directory of this source tree. |
| 7 | + */ |
| 8 | + |
| 9 | +#pragma once |
| 10 | + |
| 11 | +#include <cstdint> |
| 12 | + |
| 13 | +#include <executorch/runtime/core/array_ref.h> |
| 14 | + |
| 15 | +namespace executorch::backends::aoti::slim::c10 { |
| 16 | + |
| 17 | +using ::executorch::runtime::ArrayRef; |
| 18 | + |
| 19 | +/** |
| 20 | + * Compute whether a tensor with given sizes, strides, and numel is contiguous. |
| 21 | + * |
| 22 | + * A tensor is contiguous if its elements are laid out in memory in row-major |
| 23 | + * order, i.e., the stride of the last dimension is 1, and each preceding |
| 24 | + * dimension's stride equals the product of all following dimensions' sizes. |
| 25 | + * |
| 26 | + * @param sizes The sizes of each dimension |
| 27 | + * @param strides The strides of each dimension |
| 28 | + * @param numel The total number of elements |
| 29 | + * @return true if the tensor is contiguous, false otherwise |
| 30 | + */ |
| 31 | +template <typename T> |
| 32 | +bool _compute_contiguous(ArrayRef<T> sizes, ArrayRef<T> strides, T numel) { |
| 33 | + if (numel == 0) { |
| 34 | + return true; |
| 35 | + } |
| 36 | + |
| 37 | + T expected_stride = 1; |
| 38 | + // Iterate from last dimension to first |
| 39 | + for (int64_t d = static_cast<int64_t>(sizes.size()) - 1; d >= 0; d--) { |
| 40 | + const auto& size_d = sizes[d]; |
| 41 | + if (size_d == 1) { |
| 42 | + // Size-1 dimensions don't affect contiguity |
| 43 | + continue; |
| 44 | + } |
| 45 | + |
| 46 | + if (strides[d] != expected_stride) { |
| 47 | + return false; |
| 48 | + } |
| 49 | + expected_stride *= size_d; |
| 50 | + } |
| 51 | + return true; |
| 52 | +} |
| 53 | + |
| 54 | +} // namespace executorch::backends::aoti::slim::c10 |
0 commit comments