5

Does

b = tf.slice(a, [...], [...])

allocate a new memory buffer and then copy from a's buffer? or do a and b share the same buffer?

And, what about

... = tf.nn.convolution(tf.slice(a, [...], [...]), ...)

In this case, the slice is not being named. Does this incur an allocation and copy?

In general, is there some resource for learning these memory management details?

Thanks!

cs95
  • 379,657
  • 97
  • 704
  • 746
Henry Bigelow
  • 313
  • 1
  • 10
  • Please tag the language python. "tensorflow" is not a language, it is an API. – cs95 Jun 10 '18 at 03:14
  • 1
    Thanks @coldspeed. Although the syntax of my code is python, this question is not specific to python since it is only a binding. That's why I was hesitant to tag it as python. – Henry Bigelow Jun 10 '18 at 04:15
  • Be aware that the answer may depend on the language as well. – cs95 Jun 10 '18 at 04:24
  • @cs95: No, this answer will not depend on the language. It is the `SliceOp` in TF, no matter what language you use. – Albert Nov 08 '21 at 13:01

1 Answers1

4

I was curious of this as well and went into the kernel implementation of tf.slice.

The only time memory is not allocated is when the slice is the identity slice (so there are no changes), and when the slice is dimension 0 aligned.

Identity Lines

  if (is_identity) {
    VLOG(1) << "Slice identity";
    context->set_output(0, input);
    *done = true;
    return;
  }

Dim0Aligned

  if (slice_dim0 &&
      IsDim0SliceAligned<T>(input.shape(), (*begin)[0], (*size)[0])) {
    VLOG(1) << "Slice dim 0: " << input.shape().DebugString();
    CHECK_GE(input.dims(), 1);  // Otherwise, is_identity should be true.
    context->set_output(0, input.Slice((*begin)[0], (*begin)[0] + (*size)[0]));
    *done = true;
    return;
  }

Otherwise the following will be called

  OP_REQUIRES_OK(context, context->allocate_output(0, *output_shape, result));
Ouwen Huang
  • 1,037
  • 2
  • 9
  • 25