| 39 | } |
| 40 | |
| 41 | std::vector<std::pair<int64, int64>> MakePadding( |
| 42 | absl::Span<const int64> input_dimensions, |
| 43 | absl::Span<const int64> window_dimensions, |
| 44 | absl::Span<const int64> window_strides, Padding padding) { |
| 45 | TF_CHECK_OK(ValidatePaddingValues(input_dimensions, window_dimensions, |
| 46 | window_strides)); |
| 47 | std::vector<std::pair<int64, int64>> low_high_padding; |
| 48 | switch (padding) { |
| 49 | case Padding::kValid: |
| 50 | low_high_padding.resize(window_dimensions.size(), {0, 0}); |
| 51 | return low_high_padding; |
| 52 | |
| 53 | case Padding::kSame: |
| 54 | for (size_t i = 0; i < input_dimensions.size(); ++i) { |
| 55 | int64 input_dimension = input_dimensions[i]; |
| 56 | int64 window_dimension = window_dimensions[i]; |
| 57 | int64 window_stride = window_strides[i]; |
| 58 | // We follow the same convention as in Tensorflow, such that |
| 59 | // output dimension := ceil(input_dimension / window_stride). |
| 60 | // See tensorflow/tensorflow/python/ops/nn.py |
| 61 | // for the reference. See also tensorflow/core/kernels/ops_util.cc |
| 62 | // for the part where we avoid negative padding using max(0, x). |
| 63 | // |
| 64 | // |
| 65 | // For an odd sized window dimension 2N+1 with stride 1, the middle |
| 66 | // element is always inside the base area, so we can see it as N + 1 + |
| 67 | // N elements. In the example below, we have a kernel of size |
| 68 | // 2*3+1=7 so that the center element is 4 with 123 to the |
| 69 | // left and 567 to the right. |
| 70 | // |
| 71 | // base area: ------------------------ |
| 72 | // kernel at left: 1234567 |
| 73 | // kernel at right: 1234567 |
| 74 | // |
| 75 | // We can see visually here that we need to pad the base area |
| 76 | // by 3 on each side: |
| 77 | // |
| 78 | // padded base area: 000------------------------000 |
| 79 | // |
| 80 | // For an even number 2N, there are two options: |
| 81 | // |
| 82 | // *** Option A |
| 83 | // |
| 84 | // We view 2N as (N - 1) + 1 + N, so for N=3 we have 12 to the |
| 85 | // left, 3 is the center and 456 is to the right, like this: |
| 86 | // |
| 87 | // base area: ------------------------ |
| 88 | // kernel at left: 123456 |
| 89 | // kernel at right: 123456 |
| 90 | // padded base area: 00------------------------000 |
| 91 | // |
| 92 | // Note how we pad by one more to the right than to the left. |
| 93 | // |
| 94 | // *** Option B |
| 95 | // |
| 96 | // We view 2N as N + 1 + (N - 1), so for N=3 we have 123 to |
| 97 | // the left, 4 is the center and 56 is to the right, like |
| 98 | // this: |