Skip to content

Commit

Permalink
Add ExtractExampleParserConfiguration method
Browse files Browse the repository at this point in the history
- Extract the fixed length and variable length feature configurations
  output tensor names from a given GraphDef.
- This will allow for the use case of bypassing an unnecessary tensorflow.Example
  serialize/deserialize at serving/inference time by extracting the configuration,
  running  the proto -> tensor helpers directly and feeding the graph with
  the properly named tensors
Change: 122636456
  • Loading branch information
A. Unique TensorFlower authored and tensorflower-gardener committed May 18, 2016
1 parent 91615e7 commit 60adf6f
Show file tree
Hide file tree
Showing 6 changed files with 752 additions and 3 deletions.
55 changes: 55 additions & 0 deletions tensorflow/core/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@
# ":direct_session" - An implementation of the Session interface that
# directly runs Graphs via the internal TensorFlow executor.
#
# ":example_parser_configuration" -- A library for extracting the
# tensorflow.Example proto configuration from a Graph.
#
# Public Android targets:
#
# filegroup ":android_proto_srcs" - Protos
Expand Down Expand Up @@ -506,6 +509,7 @@ tf_cuda_library(
":all_kernels",
":core",
":direct_session",
":example_parser_configuration",
":gpu_runtime",
":lib",
],
Expand Down Expand Up @@ -821,6 +825,7 @@ tf_cuda_library(
exclude = [
"**/*test*",
"**/*main.cc",
"example/example_parser_configuration.*",
"util/tf_status_helper.*",
"util/checkpoint_reader.*",
"util/reporter.h",
Expand Down Expand Up @@ -1023,6 +1028,23 @@ tf_cuda_library(
alwayslink = 1,
)

cc_library(
name = "example_parser_configuration",
srcs = ["example/example_parser_configuration.cc"],
hdrs = ["example/example_parser_configuration.h"],
copts = tf_copts(),
linkstatic = 1,
deps = [
":core_cpu_internal",
":framework",
":lib",
":lib_internal",
":proto_text",
":protos_all_cc",
],
alwayslink = 1,
)

tf_cuda_library(
name = "cupti_wrapper",
srcs = [
Expand Down Expand Up @@ -1234,6 +1256,7 @@ tf_cc_tests(
"common_runtime/gpu/gpu_allocator_retry_test.cc",
"common_runtime/gpu/gpu_bfc_allocator_test.cc",
"common_runtime/gpu/gpu_region_allocator_test.cc",
"example/example_parser_configuration_test.cc",
"framework/op_segment_test.cc",
"ops/array_grad_test.cc",
"ops/math_grad_test.cc",
Expand Down Expand Up @@ -1562,6 +1585,32 @@ tf_cc_test(
],
)

cc_test(
name = "example_example_parser_configuration_test",
size = "small",
srcs = ["example/example_parser_configuration_test.cc"],
data = [":example_parser_configuration_testdata"],
deps = [
":core",
":core_cpu",
":core_cpu_internal",
":direct_session_internal",
":example_parser_configuration",
":framework",
":framework_internal",
":lib",
":lib_internal",
":ops",
":protos_all_cc",
":test",
":test_main",
":testlib",
"//tensorflow/cc:cc_ops",
"//tensorflow/core/kernels:example_parsing_ops",
"//tensorflow/core/kernels:ops_util",
],
)

tf_cc_test_gpu(
name = "common_runtime/gpu/gpu_tracer_test",
size = "small",
Expand Down Expand Up @@ -1611,6 +1660,12 @@ filegroup(
],
)

filegroup(
name = "example_parser_configuration_testdata",
srcs = [
"example/testdata/parse_example_graph_def.pbtxt",
],
)
# -----------------------------------------------------------------------------
# Google-internal targets go here (must be at the end).

Expand Down
160 changes: 160 additions & 0 deletions tensorflow/core/example/example_parser_configuration.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
/* Copyright 2016 Google Inc. 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 "tensorflow/core/example/example_parser_configuration.h"

#include <vector>

#include "tensorflow/core/example/example.pb.h"
#include "tensorflow/core/example/feature.pb_text.h"
#include "tensorflow/core/framework/numeric_op.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/protobuf.h"

namespace tensorflow {

Status FindNodeIndexByName(const tensorflow::GraphDef& graph,
const string& node_name, int* node_idx) {
for (int i = 0; i < graph.node_size(); ++i) {
const auto& node = graph.node(i);
if (node.name() == node_name) {
*node_idx = i;
return Status::OK();
}
}
return errors::InvalidArgument(node_name, " not found in GraphDef");
}

Status ExtractExampleParserConfiguration(
const tensorflow::GraphDef& graph, const string& node_name,
tensorflow::Session* session,
std::vector<FixedLenFeature>* fixed_len_features,
std::vector<VarLenFeature>* var_len_features) {
int node_idx;
TF_RETURN_IF_ERROR(FindNodeIndexByName(graph, node_name, &node_idx));

const auto& node = graph.node(node_idx);
if (node.op() != "ParseExample") {
return errors::InvalidArgument(node_name, " node is not a ParseExample op");
}

auto& attr_map = node.attr();
auto num_sparse = attr_map.at("Nsparse").i();
auto num_dense = attr_map.at("Ndense").i();
fixed_len_features->resize(num_dense);
var_len_features->resize(num_sparse);

auto tdense = attr_map.at("Tdense");
auto dense_shapes = attr_map.at("dense_shapes");
auto sparse_types = attr_map.at("sparse_types");

// Consistency check attributes.
if (tdense.list().type_size() != num_dense) {
return errors::InvalidArgument("Node attr Tdense has ",
tdense.list().type_size(),
" elements != Ndense attr: ", num_dense);
}

if (dense_shapes.list().shape_size() != num_dense) {
return errors::InvalidArgument("Node attr dense_shapes has ",
dense_shapes.list().shape_size(),
" elements != Ndense attr: ", num_dense);
}

if (sparse_types.list().type_size() != num_sparse) {
return errors::InvalidArgument("Node attr sparse_types has ",
sparse_types.list().type_size(),
" elements != NSparse attr: ", num_sparse);
}

for (int i = 0; i < tdense.list().type_size(); ++i) {
(*fixed_len_features)[i].dtype = tdense.list().type(i);
// Convert TensorShapeProto to TensorShape.
(*fixed_len_features)[i].shape = TensorShape(dense_shapes.list().shape(i));
}

for (int i = 0; i < sparse_types.list().type_size(); ++i) {
(*var_len_features)[i].dtype = sparse_types.list().type(i);
}

// We must fetch the configuration input tensors to the ParseExample op.
// Skipping index = 0, which is the serialized proto input.
std::vector<string> fetch_names(node.input_size() - 1);
for (int i = 1; i < node.input_size(); ++i) {
fetch_names[i - 1] = node.input(i);
}

std::vector<Tensor> op_input_tensors;

TF_RETURN_IF_ERROR(session->Run({}, // no_inputs,
fetch_names, {}, // no target_node_names,
&op_input_tensors));

// The input tensors are laid out sequentially in a flat manner.
// Here are the various start offsets.
int sparse_keys_start = 1;
int dense_keys_start = sparse_keys_start + num_sparse;
int dense_defaults_start = dense_keys_start + num_dense;

for (int i = 0; i < num_sparse; ++i) {
int input_idx = sparse_keys_start + i;
(*var_len_features)[i].key = op_input_tensors[input_idx].scalar<string>()();
}

for (int i = 0; i < num_dense; ++i) {
FixedLenFeature& config = (*fixed_len_features)[i];
int dense_keys_offset = dense_keys_start + i;
config.key = op_input_tensors[dense_keys_offset].scalar<string>()();

int defaults_offset = dense_defaults_start + i;
config.default_value = op_input_tensors[defaults_offset];
}

// The output tensors are laid out sequentially in a flat manner.
// Here are the various start offsets.
int sparse_indices_output_start = 0;
int sparse_values_output_start = sparse_indices_output_start + num_sparse;
int sparse_shapes_output_start = sparse_values_output_start + num_sparse;
int dense_values_output_start = sparse_shapes_output_start + num_sparse;

string node_output_prefix = strings::StrCat(node_name, ":");

for (int i = 0; i < num_sparse; ++i) {
VarLenFeature& config = (*var_len_features)[i];

int indices_offset = sparse_indices_output_start + i;
config.indices_output_tensor_name =
strings::StrCat(node_output_prefix, indices_offset);

int values_offset = sparse_values_output_start + i;
config.values_output_tensor_name =
strings::StrCat(node_output_prefix, values_offset);

int shapes_offset = sparse_shapes_output_start + i;
config.shapes_output_tensor_name =
strings::StrCat(node_output_prefix, shapes_offset);
}

for (int i = 0; i < num_dense; ++i) {
int output_idx = dense_values_output_start + i;
(*fixed_len_features)[i].values_output_tensor_name =
strings::StrCat(node_output_prefix, output_idx);
}
return Status::OK();
}

} // namespace tensorflow
47 changes: 47 additions & 0 deletions tensorflow/core/example/example_parser_configuration.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/* Copyright 2016 Google Inc. 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.
==============================================================================*/

#ifndef THIRD_PARTY_TENSORFLOW_CORE_EXAMPLE_EXAMPLE_PARSER_CONFIGURATION_H_
#define THIRD_PARTY_TENSORFLOW_CORE_EXAMPLE_EXAMPLE_PARSER_CONFIGURATION_H_

#include <string>
#include <vector>

#include "tensorflow/core/example/example.pb.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/util/example_proto_helper.h"
#include "tensorflow/core/util/sparse/sparse_tensor.h"

// This is a set of helper methods that will make it possible to share
// tensorflow::Example proto Tensor conversion code inside the ExampleParserOp
// OpKernel as well as in external code.
namespace tensorflow {

// Given a graph and the node_name of a ParseExample op,
// extract the FixedLenFeature/VarLenFeature configurations.
Status ExtractExampleParserConfiguration(
const tensorflow::GraphDef& graph, const string& node_name,
tensorflow::Session* session,
std::vector<FixedLenFeature>* fixed_len_features,
std::vector<VarLenFeature>* var_len_features);

} // namespace tensorflow

#endif // THIRD_PARTY_TENSORFLOW_CORE_EXAMPLE_EXAMPLE_PARSE_CONFIGURATION_H_
Loading

0 comments on commit 60adf6f

Please sign in to comment.