Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
978dd58
Add initial code for substr op
samjabrahams Sep 12, 2016
52bf0ad
Fix naming of substr
samjabrahams Sep 12, 2016
b68ec8f
Add complete substr op, tests, and documentation
samjabrahams Sep 12, 2016
947ef9d
Update date 2015->2016
samjabrahams Sep 12, 2016
c2ffd19
Remove unnecessary header includes
samjabrahams Sep 12, 2016
d466140
Add dtype specific tests
samjabrahams Sep 12, 2016
20ddb0d
Add element-wise version of Op, comments for bcast
samjabrahams Sep 29, 2016
5bb0e1a
Removed cheeky line break in string_ops.py
samjabrahams Sep 29, 2016
31b9596
Change commented `int` vars to `size_t`
samjabrahams Sep 29, 2016
6a796fa
Add case statements for static template dimensions
samjabrahams Oct 13, 2016
aa6cee8
Clean substr_op, update shape function, more tests
samjabrahams Oct 14, 2016
b2c79b8
Adds info about pos/len needing the same shape
samjabrahams Oct 14, 2016
58276be
Remove #include of bcast statement
samjabrahams Oct 14, 2016
798f7a1
Add working broadcast code with tests
samjabrahams Oct 28, 2016
5df316d
Clean line widths and comments
samjabrahams Oct 28, 2016
6e6fe14
Add broadcasting note to string_ops.cc
samjabrahams Oct 28, 2016
6f8580f
Add print_function __future__ import to tests
samjabrahams Oct 28, 2016
985667d
Add comment in to shape function in string_ops.cc
samjabrahams Oct 28, 2016
375306e
Add SubtleMustCopy wrapper for scalar pos/len
samjabrahams Oct 30, 2016
7ddc419
Add SubtleMustCopy to element-wise path
samjabrahams Oct 30, 2016
1019efa
Add SubtleMustCopy and FastBoundsCheck, tests
samjabrahams Oct 30, 2016
2e6e800
Add examples to documentation in string_ops.cc
samjabrahams Oct 30, 2016
0d6d29e
Avoid repeat accessor calls to input tensor
samjabrahams Oct 30, 2016
30939fc
Reorder variable declarations in loop
samjabrahams Oct 30, 2016
711a312
Reorder python imports to be alphabetical
samjabrahams Oct 31, 2016
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions tensorflow/core/kernels/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -2136,6 +2136,7 @@ tf_kernel_libraries(
"reduce_join_op",
"string_join_op",
"string_split_op",
"substr_op",
"as_string_op",
"base64_ops",
],
Expand Down
233 changes: 233 additions & 0 deletions tensorflow/core/kernels/substr_op.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,233 @@
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include <string>

#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/kernel_def_builder.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/kernels/bounds_check.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/util/bcast.h"

namespace tensorflow {

// Position/length can be 32 or 64-bit integers
template <typename T>
class SubstrOp : public OpKernel {
public:
using OpKernel::OpKernel;

void Compute(OpKernelContext* context) override {
// Get inputs
const Tensor& input_tensor = context->input(0);
const Tensor& pos_tensor = context->input(1);
const Tensor& len_tensor = context->input(2);
const TensorShape input_shape = input_tensor.shape();
const TensorShape pos_shape = pos_tensor.shape();
const TensorShape len_shape = len_tensor.shape();

bool is_scalar = TensorShapeUtils::IsScalar(pos_shape);

if (is_scalar || input_shape == pos_shape) {
// pos/len are either scalar or match the shape of input_tensor
// Do not need to do broadcasting

// Reshape input
auto input = input_tensor.flat<string>();
// Allocate output
Tensor* output_tensor = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output("output", input_tensor.shape(),
&output_tensor));
auto output = output_tensor->flat<string>();
if (is_scalar) {
// Perform Op with scalar pos/len
const T pos = tensorflow::internal::SubtleMustCopy(pos_tensor.scalar<T>()());
const T len = tensorflow::internal::SubtleMustCopy(len_tensor.scalar<T>()());
for (size_t i = 0; i < input_tensor.NumElements(); ++i) {
string in = input(i);
OP_REQUIRES(context, FastBoundsCheck(pos, in.size()),
errors::InvalidArgument("pos ", pos, " out of range for string",
"b'", in, "' at index ", i));
output(i) = in.substr(pos, len);
}
} else {
// Perform Op element-wise with tensor pos/len
auto pos_flat = pos_tensor.flat<T>();
auto len_flat = len_tensor.flat<T>();
for (size_t i = 0; i < input_tensor.NumElements(); ++i) {
string in = input(i);
const T pos = tensorflow::internal::SubtleMustCopy(pos_flat(i));
const T len = tensorflow::internal::SubtleMustCopy(len_flat(i));
OP_REQUIRES(context, FastBoundsCheck(pos, in.size()),
errors::InvalidArgument("pos ", pos, " out of range for string",
"b'", in, "' at index ", i));
output(i) = in.substr(pos, len);
}
}
} else {
// Perform op with broadcasting
// TODO: Use ternary broadcasting for once available in Eigen. Current
// implementation iterates through broadcasted ops element-wise;
// this should be parallelized.

// Create BCast helper with shape of input and pos/len
BCast bcast(BCast::FromShape(input_shape), BCast::FromShape(pos_shape));
OP_REQUIRES(context, bcast.IsValid(),
errors::InvalidArgument("Incompatible shapes: ",
input_shape.DebugString(), " vs. ",
pos_shape.DebugString()));
TensorShape output_shape = BCast::ToShape(bcast.result_shape());
int ndims = output_shape.dims();
Tensor* output_tensor = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output("output", output_shape,
&output_tensor));
switch (ndims) {
case 1: {
// Reshape tensors according to BCast results
auto input = input_tensor.shaped<string,1>(bcast.x_reshape());
auto output = output_tensor->shaped<string,1>(bcast.result_shape());
auto pos_shaped = pos_tensor.shaped<T,1>(bcast.y_reshape());
auto len_shaped = len_tensor.shaped<T,1>(bcast.y_reshape());

// Allocate temporary buffer for broadcasted input tensor
Tensor input_buffer;
OP_REQUIRES_OK(context,
context->allocate_temp(DT_STRING,
output_shape,
&input_buffer));
typename TTypes<string,1>::Tensor input_bcast =
input_buffer.shaped<string,1>(bcast.result_shape());
input_bcast = input.broadcast(
BCast::ToIndexArray<1>(bcast.x_bcast()));

// Allocate temporary buffer for broadcasted position tensor
Tensor pos_buffer;
OP_REQUIRES_OK(context,
context->allocate_temp(DataTypeToEnum<T>::v(),
output_shape,
&pos_buffer));
typename TTypes<T,1>::Tensor pos_bcast = pos_buffer.shaped<T,1>(
bcast.result_shape());
pos_bcast = pos_shaped.broadcast(
BCast::ToIndexArray<1>(bcast.y_bcast()));

// Allocate temporary buffer for broadcasted length tensor
Tensor len_buffer;
OP_REQUIRES_OK(context,
context->allocate_temp(DataTypeToEnum<T>::v(),
output_shape,
&len_buffer));
typename TTypes<T,1>::Tensor len_bcast = len_buffer.shaped<T,1>(
bcast.result_shape());
len_bcast = len_shaped.broadcast(
BCast::ToIndexArray<1>(bcast.y_bcast()));

// Iterate through broadcasted tensors and perform substr
for (int i = 0; i < output_shape.dim_size(0); ++i) {
string in = input_bcast(i);
const T pos = tensorflow::internal::SubtleMustCopy(pos_bcast(i));
const T len = tensorflow::internal::SubtleMustCopy(len_bcast(i));
OP_REQUIRES(context, FastBoundsCheck(pos, input_bcast(i).size()),
errors::InvalidArgument("pos ", pos, " out of range for string",
"b'", in, "' at index ", i));
output(i) = in.substr(pos, len);
}
break;
}
case 2: {
// Reshape tensors according to BCast results
auto input = input_tensor.shaped<string,2>(bcast.x_reshape());
auto output = output_tensor->shaped<string,2>(bcast.result_shape());
auto pos_shaped = pos_tensor.shaped<T,2>(bcast.y_reshape());
auto len_shaped = len_tensor.shaped<T,2>(bcast.y_reshape());

// Allocate temporary buffer for broadcasted input tensor
Tensor input_buffer;
OP_REQUIRES_OK(context,
context->allocate_temp(DT_STRING,
output_shape,
&input_buffer));
typename TTypes<string,2>::Tensor input_bcast =
input_buffer.shaped<string,2>(bcast.result_shape());
input_bcast = input.broadcast(
BCast::ToIndexArray<2>(bcast.x_bcast()));

// Allocate temporary buffer for broadcasted position tensor
Tensor pos_buffer;
OP_REQUIRES_OK(context,
context->allocate_temp(DataTypeToEnum<T>::v(),
output_shape,
&pos_buffer));
typename TTypes<T,2>::Tensor pos_bcast = pos_buffer.shaped<T,2>(
bcast.result_shape());
pos_bcast = pos_shaped.broadcast(
BCast::ToIndexArray<2>(bcast.y_bcast()));

// Allocate temporary buffer for broadcasted length tensor
Tensor len_buffer;
OP_REQUIRES_OK(context,
context->allocate_temp(DataTypeToEnum<T>::v(),
output_shape,
&len_buffer));
typename TTypes<T,2>::Tensor len_bcast = len_buffer.shaped<T,2>(
bcast.result_shape());
len_bcast = len_shaped.broadcast(
BCast::ToIndexArray<2>(bcast.y_bcast()));

// Iterate through broadcasted tensors and perform substr
for (int i = 0; i < output_shape.dim_size(0); ++i) {
for (int j = 0; j < output_shape.dim_size(1); ++j) {
string in = input_bcast(i, j);
const T pos = tensorflow::internal::SubtleMustCopy(
pos_bcast(i, j));
const T len = tensorflow::internal::SubtleMustCopy(
len_bcast(i, j));
OP_REQUIRES(
context,
FastBoundsCheck(pos, in.size()),
errors::InvalidArgument("pos ", pos, " out of range for ",
"string b'", in, "' at index ("
, i, ", ", j, ")"));
output(i, j) = in.substr(pos, len);

}
}
break;
}
default: {
context->SetStatus(errors::Unimplemented(
"Substr broadcast not implemented for ", ndims, " dimensions"));
}
}
}
}
};

#define REGISTER_SUBSTR(type) \
REGISTER_KERNEL_BUILDER(Name("Substr") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T"), \
SubstrOp<type>);
REGISTER_SUBSTR(int32);
REGISTER_SUBSTR(int64);
} // namespace tensorflow
109 changes: 109 additions & 0 deletions tensorflow/core/ops/string_ops.cc
Original file line number Diff line number Diff line change
Expand Up @@ -280,4 +280,113 @@ input: Base64 strings to decode.
output: Decoded strings.
)doc");

REGISTER_OP("Substr")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm a little dubious about this op as written -- I can see the use case if all inputs were scalars, but applying pos/len scalars to all elements of an input seems potentially limiting.

I was maybe thinking that pos and len could be equal-shaped tensors, and have pos and len be broadcastable against 'input'. For example, if they were scalars, then they would apply to every element.

If the shape of 'pos' and 'len' matched 'input', then the entries in pos and len would be elementwise applied to input. Otherwise, they would follow our standard broadcasting rules. (e.g., you could have a matrix [MxN] of strings, have pos and len be [1xN], and then pos and len would apply row-wise to every element of the input matrix).

From an API perspective, that seems more flexible, even if for now, you only implement the scalar or equal-shaped versions and threw errors for the rest.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking about doing a broadcasted version of this Op, but I wasn't exactly sure how to approach it, so I pushed what I had. I'll give this a go over the next few days!

.Input("input: string")
.Input("pos: T")
.Input("len: T")
.Output("output: string")
.Attr("T: {int32, int64}")
.SetShapeFn([](InferenceContext* c) {
ShapeHandle pos_shape = c->input(1);
ShapeHandle len_shape = c->input(2);
ShapeHandle unused;
// Check that pos/len have same rank
TF_RETURN_IF_ERROR(c->WithRank(pos_shape, c->Rank(len_shape), &unused));
// Check that dimensions are equal
for (int32 i = 0; i < c->Rank(pos_shape); ++i) {
DimensionHandle pos_dim = c->Dim(pos_shape, i);
DimensionHandle len_dim = c->Dim(len_shape, i);
if (c->Value(pos_dim) != c->Value(len_dim)) {
return errors::InvalidArgument("pos and len shapes must match: ",
c->DebugString(pos_shape), " vs. ",
c->DebugString(len_shape));
}
}
// c->input(0) is the ShapeHandle to input strings
// BroadcastBinaryOpShapeFn infers shape from c->input(0) and c->input(1).
return shape_inference::BroadcastBinaryOpShapeFn(c);
})
.Doc(R"doc(
Return substrings from `Tensor` of strings.

For each string in the input `Tensor`, creates a substring starting at index
`pos` with a total length of `len`.

If `len` defines a substring that would extend beyond the length of the input
string, then as many characters as possible are used.

If `pos` is negative or specifies a character index larger than any of the input
strings, then an `InvalidArgumentError` is thrown.

`pos` and `len` must have the same shape, otherwise a `ValueError` is thrown on
Op creation.

*NOTE*: `Substr` supports broadcasting up to two dimensions. More about
broadcasting
[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)

---

Examples

Using scalar `pos` and `len`:

```
input = [b'Hello', b'World']
position = 1
length = 3

output = [b'ell', b'orl']
```

Using `pos` and `len` with same shape as `input`:

```
input = [[b'ten', b'eleven', b'twelve'],
[b'thirteen', b'fourteen', b'fifteen'],
[b'sixteen', b'seventeen', b'eighteen']]
position = [[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]
length = [[2, 3, 4],
[4, 3, 2],
[5, 5, 5]]

output = [[b'en', b'eve', b'lve'],
[b'hirt', b'urt', b'te'],
[b'ixtee', b'vente', b'hteen']]
```

Broadcasting `pos` and `len` onto `input`:

```
input = [[b'ten', b'eleven', b'twelve'],
[b'thirteen', b'fourteen', b'fifteen'],
[b'sixteen', b'seventeen', b'eighteen'],
[b'nineteen', b'twenty', b'twentyone']]
position = [1, 2, 3]
length = [1, 2, 3]

output = [[b'e', b'ev', b'lve'],
[b'h', b'ur', b'tee'],
[b'i', b've', b'hte'],
[b'i', b'en', b'nty']]
```

Broadcasting `input` onto `pos` and `len`:

```
input = b'thirteen'
position = [1, 5, 7]
length = [3, 2, 1]

output = [b'hir', b'ee', b'n"]
```

input: Tensor of strings
pos: Scalar defining the position of first character in each substring
len: Scalar defining the number of characters to include in each substring
output: Tensor of substrings
)doc");

} // namespace tensorflow
7 changes: 7 additions & 0 deletions tensorflow/python/kernel_tests/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,13 @@ tf_py_test(
additional_deps = ["//tensorflow:tensorflow_py"],
)

tf_py_test(
name = "substr_op_test",
size = "small",
srcs = ["substr_op_test.py"],
additional_deps = ["//tensorflow:tensorflow_py"],
)

tf_py_test(
name = "summary_ops_test",
size = "small",
Expand Down
Loading