ONE - On-device Neural Engine
Loading...
Searching...
No Matches
CircleStridedSlice.cpp
Go to the documentation of this file.
1/*
2 * Copyright (c) 2021 Samsung Electronics Co., Ltd. All Rights Reserved
3 * Copyright 2018 The TensorFlow Authors. All Rights Reserved.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
18
19#include "Check.h"
20#include "CircleCloneNode.h"
22
23#include <luci/IR/CircleNode.h>
24#include <loco/IR/DataType.h>
25#include <loco/IR/NodeShape.h>
26#include <oops/InternalExn.h>
27
28#include <algorithm>
29#include <cmath>
30#include <cstdint>
31#include <limits>
32
33namespace luci
34{
35
37{
38 auto *cloned = _graph->nodes()->create<luci::CircleStridedSlice>();
39 if (cloned != nullptr)
40 {
41 cloned->begin_mask(node->begin_mask());
42 cloned->end_mask(node->end_mask());
43 cloned->ellipsis_mask(node->ellipsis_mask());
44 cloned->new_axis_mask(node->new_axis_mask());
45 cloned->shrink_axis_mask(node->shrink_axis_mask());
46 }
47 return cloned;
48}
49
50// code referenced from
51// https://github.com/tensorflow/tensorflow/blob/3f878cff5b698b82eea85db2b60d65a2e320850e/
52// tensorflow/lite/kernels/strided_slice.cc
53// tensorflow/lite/kernels/internal/strided_slice_logic.h
54namespace sinf
55{
56
57// This Op only supports 1-5D cases and since we use the reference 4D
58// implementation, the 1-3D tensors are mapped to 4D.
59const int kMaxDim = 5;
60
61const loco::DataType S32 = loco::DataType::S32;
62
64{
66 int32_t start_indices[kMaxDim] = {0};
68 int32_t stop_indices[kMaxDim] = {0};
69 int8_t strides_count = 0;
70 int32_t strides[kMaxDim] = {0};
71
72 int16_t begin_mask = 0;
73 int16_t ellipsis_mask = 0;
74 int16_t end_mask = 0;
75 int16_t new_axis_mask = 0;
76 int16_t shrink_axis_mask = 0;
77};
78
80{
82 {
83 // check overflow issues
84 assert(static_cast<int16_t>(node->begin_mask()) == node->begin_mask());
85 assert(static_cast<int16_t>(node->ellipsis_mask()) == node->ellipsis_mask());
86 assert(static_cast<int16_t>(node->end_mask()) == node->end_mask());
87 assert(static_cast<int16_t>(node->new_axis_mask()) == node->new_axis_mask());
88 assert(static_cast<int16_t>(node->shrink_axis_mask()) == node->shrink_axis_mask());
89
92 params.end_mask = node->end_mask();
95
96 input = loco::must_cast<luci::CircleNode *>(node->input());
97 begin = loco::must_cast<luci::CircleConst *>(node->begin());
98 end = loco::must_cast<luci::CircleConst *>(node->end());
99 strides = loco::must_cast<luci::CircleConst *>(node->strides());
100
101 loco::TensorShape input_shape = circle_shape(input);
102 input_dims = static_cast<int64_t>(input_shape.rank());
103 }
109
110 // Equivalent input shape after adding axis according to new_axis_mask.
112 int64_t input_dims = 0;
113};
114
115// Use until std::clamp() is available from C++17.
116inline int Clamp(const int32_t v, const int32_t lo, const int32_t hi)
117{
118 LUCI_ASSERT(!(hi < lo), "Clamp hi < lo");
119 if (hi < v)
120 return hi;
121 if (v < lo)
122 return lo;
123 return v;
124}
125
126// Return the index for the first element along that axis. This index will be a
127// positive integer between [0, axis_size - 1] that can be used to index
128// directly into the data.
129inline int64_t StartForAxis(const StridedSliceParams &params, const loco::TensorShape &input_shape,
130 int64_t axis)
131{
132 const auto begin_mask = params.begin_mask;
133 const auto *start_indices = params.start_indices;
134 const auto *strides = params.strides;
135 const int64_t axis_size = static_cast<int64_t>(input_shape.dim(axis).value());
136 if (axis_size == 0)
137 {
138 return 0;
139 }
140 // Begin with the specified index.
141 int64_t start = start_indices[axis];
142
143 // begin_mask override
144 if (begin_mask & (1LL << axis))
145 {
146 if (strides[axis] > 0)
147 {
148 // Forward iteration - use the first element. These values will get
149 // clamped below (Note: We could have set them to 0 and axis_size-1, but
150 // use lowest() and max() to maintain symmetry with StopForAxis())
151 start = std::numeric_limits<int32_t>::lowest();
152 }
153 else
154 {
155 // Backward iteration - use the last element.
156 start = std::numeric_limits<int32_t>::max();
157 }
158 }
159
160 // Handle negative indices
161 if (start < 0)
162 {
163 start += axis_size;
164 }
165
166 // Clamping
167 if (strides[axis] > 0)
168 {
169 // Forward iteration
170 start = Clamp(start, 0, axis_size);
171 }
172 else
173 {
174 // Backward iteration
175 start = Clamp(start, -1, axis_size - 1);
176 }
177
178 return start;
179}
180
181// Return the "real" index for the end of iteration along that axis. This is an
182// "end" in the traditional C sense, in that it points to one past the last
183// element. ie. So if you were iterating through all elements of a 1D array of
184// size 4, this function would return 4 as the stop, because it is one past the
185// "real" indices of 0, 1, 2 & 3.
186inline int64_t StopForAxis(const StridedSliceParams &params, const loco::TensorShape &input_shape,
187 int64_t axis, int64_t start_for_axis)
188{
189 const auto end_mask = params.end_mask;
190 const auto shrink_axis_mask = params.shrink_axis_mask;
191 const auto *stop_indices = params.stop_indices;
192 const auto *strides = params.strides;
193 const int64_t axis_size = static_cast<int64_t>(input_shape.dim(axis).value());
194 if (axis_size == 0)
195 {
196 return 0;
197 }
198
199 // Begin with the specified index
200 const bool shrink_axis = shrink_axis_mask & (1LL << axis);
201 int64_t stop = stop_indices[axis];
202
203 // When shrinking an axis, the end position does not matter (and can be
204 // incorrect when negative indexing is used, see Issue #19260). Always use
205 // start_for_axis + 1 to generate a length 1 slice, since start_for_axis has
206 // already been adjusted for negative indices.
207 if (shrink_axis)
208 {
209 return start_for_axis + 1;
210 }
211
212 // end_mask override
213 if (end_mask & (1LL << axis))
214 {
215 if (strides[axis] > 0)
216 {
217 // Forward iteration - use the last element. These values will get
218 // clamped below
219 stop = std::numeric_limits<int32_t>::max();
220 }
221 else
222 {
223 // Backward iteration - use the first element.
224 stop = std::numeric_limits<int32_t>::lowest();
225 }
226 }
227
228 // Handle negative indices
229 if (stop < 0)
230 {
231 stop += axis_size;
232 }
233
234 // Clamping
235 // Because the end index points one past the last element, we need slightly
236 // different clamping ranges depending on the direction.
237 if (strides[axis] > 0)
238 {
239 // Forward iteration
240 stop = Clamp(stop, 0, axis_size);
241 }
242 else
243 {
244 // Backward iteration
245 stop = Clamp(stop, -1, axis_size - 1);
246 }
247
248 return stop;
249}
250
252{
253 StridedSliceParams op_params;
254
255 // The ellipsis_mask and new_axis_mask in op_params are not used. Those masks
256 // are processed here to update begin_mask, end_mask and the index range.
257 op_params.begin_mask = 0;
258 op_params.ellipsis_mask = 0;
259 op_params.end_mask = 0;
260 op_params.new_axis_mask = 0;
261 op_params.shrink_axis_mask = 0;
262
263 // Count indexes where the new_axis_mask is set but the ellipsis_mask is not.
264 loco::TensorShape begin_shape = circle_shape(op_context->begin);
265 const int64_t begin_count = static_cast<int64_t>(begin_shape.dim(0).value());
266 int64_t num_add_axis = 0;
267 for (int64_t i = 0; i < begin_count; ++i)
268 {
269 if (!((1LL << i) & op_context->params.ellipsis_mask) &&
270 ((1LL << i) & op_context->params.new_axis_mask))
271 {
272 num_add_axis++;
273 }
274 }
275
276 // Calculate the dims of input after adding new axises.
277 const int64_t effective_dims = op_context->input_dims + num_add_axis;
278
279 // If begin, end and strides are not fully provided, it means Ellipsis should
280 // be expanded to multiple dimensions (Ex: for spec [Ellipsis, 2] on a 3D
281 // input, the Ellipsis should be applied for the first 2 dimensions). Besides,
282 // If the new_axis_mask and the ellipsis_mask are set at the same index, the
283 // new_axis_mask will have no effect.
284 int64_t effective_ellipsis_mask = 0, effective_new_axis_mask = 0;
285 int64_t ellipsis_start_idx = effective_dims, expanded_ellipsis = 0;
286 for (int64_t i = 0; i < effective_dims;)
287 {
288 if ((1LL << i) & op_context->params.ellipsis_mask)
289 {
290 ellipsis_start_idx = i;
291 int64_t ellipsis_end_idx =
292 std::max(i + 1, std::min(i + 1 + num_add_axis + op_context->input_dims - begin_count,
293 effective_dims));
294 expanded_ellipsis = ellipsis_end_idx - ellipsis_start_idx - 1;
295
296 // Set bit for effective_ellipsis_mask.
297 for (; i < ellipsis_end_idx; ++i)
298 {
299 effective_ellipsis_mask |= (1LL << i);
300 }
301 continue;
302 }
303
304 if ((1LL << (i - expanded_ellipsis)) & op_context->params.new_axis_mask)
305 {
306 effective_new_axis_mask |= (1LL << i);
307 }
308 ++i;
309 }
310
311 // Calculate effective_input_shape and its corresponding begin, end, strides.
312 loco::TensorShape input_shape = circle_shape(op_context->input);
313 int64_t added_ellipsis = 0, added_axises = 0;
314 // make sure no overflow
315 assert(static_cast<uint32_t>(effective_dims) == effective_dims);
316 op_context->effective_input_shape.rank(effective_dims);
317
318 for (int64_t i = 0; i < effective_dims; ++i)
319 {
320 if ((1LL << i) & effective_ellipsis_mask)
321 {
322 // If ellipsis_mask, set the begin_mask and end_mask at that index.
323 added_ellipsis = std::max(int64_t(0), i - ellipsis_start_idx);
324 assert(i < 16);
325 op_params.begin_mask |= (1LL << i);
326 op_params.end_mask |= (1LL << i);
327 op_params.strides[i] = 1;
328 op_context->effective_input_shape.dim(i) = input_shape.dim(i - added_axises);
329 }
330 else if ((1LL << i) & effective_new_axis_mask)
331 {
332 // If new_axis_mask is set, it is equivalent to adding a new dim of 1 to
333 // input tensor. Store added shape to effective_input_shape.
334 op_params.start_indices[i] = 0;
335 op_params.stop_indices[i] = 1;
336 op_params.strides[i] = 1;
337 op_context->effective_input_shape.dim(i) = loco::Dimension(1);
338 added_axises++;
339 }
340 else if (i >= begin_count + expanded_ellipsis)
341 {
342 op_params.start_indices[i] = 0;
343 op_params.stop_indices[i] = 0;
344 op_params.strides[i] = 1;
345 assert(i < 16);
346 op_params.begin_mask |= (1LL << i);
347 op_params.end_mask |= (1LL << i);
348 op_context->effective_input_shape.dim(i) = input_shape.dim(i - added_axises);
349 }
350 else
351 {
352 const int64_t orig_idx = i - added_ellipsis;
353 op_params.start_indices[i] = op_context->begin->at<S32>(orig_idx);
354 op_params.stop_indices[i] = op_context->end->at<S32>(orig_idx);
355 op_params.strides[i] = op_context->strides->at<S32>(orig_idx);
356 if (op_context->params.begin_mask & (1LL << orig_idx))
357 {
358 assert(i < 16);
359 op_params.begin_mask |= (1LL << i);
360 }
361 if (op_context->params.end_mask & (1LL << orig_idx))
362 {
363 assert(i < 16);
364 op_params.end_mask |= (1LL << i);
365 }
366 if (op_context->params.shrink_axis_mask & (1LL << orig_idx))
367 {
368 assert(i < 16);
369 op_params.shrink_axis_mask |= (1LL << i);
370 }
371 op_context->effective_input_shape.dim(i) = input_shape.dim(i - added_axises);
372 }
373 }
374
375 // make sure no overflow
376 assert(static_cast<int8_t>(effective_dims) == static_cast<int32_t>(effective_dims));
377
378 op_params.start_indices_count = effective_dims;
379 op_params.stop_indices_count = effective_dims;
380 op_params.strides_count = effective_dims;
381
382 return op_params;
383}
384
386{
388
389 auto input_node = loco::must_cast<luci::CircleNode *>(node->input());
390
391 auto begin_node = loco::must_cast<luci::CircleNode *>(node->begin());
392 auto end_node = loco::must_cast<luci::CircleNode *>(node->end());
393 auto strides_node = loco::must_cast<luci::CircleNode *>(node->strides());
394
395 LUCI_ASSERT(begin_node->dtype() == S32, "Only support S32 for begin_node");
396 LUCI_ASSERT(end_node->dtype() == S32, "Only support S32 for end_node");
397 LUCI_ASSERT(strides_node->dtype() == S32, "Only support S32 for strides_node");
398
399 LUCI_ASSERT(begin_node->rank() == 1, "Only support rank 1 for begin_node");
400 LUCI_ASSERT(end_node->rank() == 1, "Only support rank 1 for end_node");
401 LUCI_ASSERT(strides_node->rank() == 1, "Only support rank 1 for strides_node");
402
403 auto begin_const = dynamic_cast<luci::CircleConst *>(node->begin());
404 auto end_const = dynamic_cast<luci::CircleConst *>(node->end());
405 auto strides_const = dynamic_cast<luci::CircleConst *>(node->strides());
406 // TODO support non-const strides_node
407 if (strides_const == nullptr)
408 {
409 INTERNAL_EXN("StridedSlice strides node is not Constant");
410 }
411 if (begin_const == nullptr || end_const == nullptr)
412 {
413 // The dimensions of the output shape are all set to unknown.
414 output_shape.rank(input_node->rank());
415 return output_shape;
416 }
417
419
420 assert(begin_const->size<S32>() <= input_shape.rank());
421 assert(end_const->size<S32>() <= input_shape.rank());
422 assert(strides_const->size<S32>() <= input_shape.rank());
423
424 StridedSliceContext op_context(node);
425 auto op_params = BuildStridedSliceParams(&op_context);
426 auto &effective_input_shape = op_context.effective_input_shape;
427 std::vector<int64_t> output_shape_vector;
428 std::vector<bool> output_known_vector;
429
430 for (int32_t idx = effective_input_shape.rank() - 1; idx >= 0; --idx)
431 {
432 int32_t stride = op_params.strides[idx];
433 LUCI_ASSERT(stride != 0, "stride value has to be non-zero");
434
435 int64_t begin = StartForAxis(op_params, effective_input_shape, idx);
436 int64_t end = StopForAxis(op_params, effective_input_shape, idx, begin);
437
438 // When shrinking an axis, the end position does not matter (and can be
439 // incorrect when negative indexing is used, see Issue #19260). Always use
440 // begin + 1 to generate a length 1 slice, since begin has
441 // already been adjusted for negative indices by GetBeginValueAtIndex.
442 const bool shrink_axis = op_params.shrink_axis_mask & (1 << idx);
443 if (shrink_axis)
444 {
445 end = begin + 1;
446 }
447
448 // This is valid for both positive and negative strides
449 int64_t dim_shape = std::ceil((end - begin) / static_cast<float>(stride));
450 dim_shape = dim_shape < 0 ? 0 : dim_shape;
451 if (!shrink_axis)
452 {
453 output_shape_vector.push_back(dim_shape);
454 output_known_vector.push_back(effective_input_shape.dim(idx).known());
455 }
456 }
457
458 auto shape_size = output_shape_vector.size();
459 output_shape.rank(shape_size);
460 for (uint32_t idx = 0; idx < shape_size; ++idx)
461 {
462 bool known = output_known_vector[shape_size - 1u - idx];
463 if (not known)
464 continue;
465 int64_t dim = output_shape_vector.at(shape_size - 1u - idx);
466 LUCI_ASSERT(0 <= dim && dim < 0xfffffffL, "Dimension size exceeds limit");
467 // reverse copy
468 output_shape.dim(idx) = static_cast<uint32_t>(dim);
469 }
470
471 return output_shape;
472}
473
474} // namespace sinf
475
476} // namespace luci
#define INTERNAL_EXN(msg)
@ brief throw internal exception with message
Definition InternalExn.h:25
The value of one dimension in a tensor shape.
Definition Dimension.h:30
uint32_t value(void) const
Return the value.
Definition Dimension.h:51
const Dimension & dim(uint32_t axis) const
Definition TensorShape.h:38
uint32_t rank(void) const
Definition TensorShape.h:35
Class to build tensor data.
Definition CircleConst.h:35
const loco::DataTypeImpl< DT >::Type & at(uint32_t n) const
STRIDED_SLICE in Circle.
loco::Node * input(void) const
loco::Node * begin(void) const
loco::Node * strides(void) const
loco::Node * end(void) const
loco::TensorShape visit(const luci::CircleNode *node) final
Default fallback.
const luci_interpreter::RuntimeShape output_shape
#define LUCI_ASSERT(condition, msg)
Definition Check.h:26
DataType
"scalar" value type
Definition DataType.h:27
int64_t StopForAxis(const StridedSliceParams &params, const loco::TensorShape &input_shape, int64_t axis, int64_t start_for_axis)
const loco::DataType S32
int Clamp(const int32_t v, const int32_t lo, const int32_t hi)
loco::TensorShape circle_shape(const luci::CircleNode *node)
int64_t StartForAxis(const StridedSliceParams &params, const loco::TensorShape &input_shape, int64_t axis)
StridedSliceParams BuildStridedSliceParams(StridedSliceContext *op_context)
CircleInput * input_node(loco::Graph *g, const loco::GraphInputIndex &index)
Find a Pull node with a given input index.
int8_t begin_count
Definition Slice.cpp:32
int32_t begin[5]
Definition Slice.cpp:33
StridedSliceContext(const luci::CircleStridedSlice *node)