aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/core/example/example_parser_configuration_test.cc
blob: a2238faaf372237bae3092fe0dad2b880caa6507 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/* 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 "tensorflow/core/example/example_parser_configuration.h"

#include <memory>

#include "tensorflow/core/framework/attr_value.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/public/session_options.h"
#include "tensorflow/core/util/example_proto_helper.h"

namespace tensorflow {
namespace {

void ReadFileToStringOrDie(Env* env, const string& filename, string* output) {
  TF_CHECK_OK(ReadFileToString(env, filename, output));
}

std::unique_ptr<Session> CreateSession() {
  SessionOptions options;
  (*options.config.mutable_device_count())["CPU"] = 2;
  return std::unique_ptr<Session>(NewSession(options));
}

class ExtractExampleParserConfigurationTest : public ::testing::Test {
 protected:
  void SetUp() override {
    string proto_string;
    string filename =
        io::JoinPath(testing::TensorFlowSrcRoot(),
                     "core/example/testdata/parse_example_graph_def.pbtxt");
    ReadFileToStringOrDie(Env::Default(), filename, &proto_string);
    protobuf::TextFormat::ParseFromString(proto_string, &graph_def_);
    session_ = CreateSession();
    TF_CHECK_OK(session_->Create(graph_def_));
  }

  NodeDef* parse_example_node() {
    for (auto& node : *graph_def_.mutable_node()) {
      if (node.name() == "ParseExample/ParseExample") {
        return &node;
      }
    }
    return nullptr;
  }

  GraphDef graph_def_;
  std::unique_ptr<Session> session_;
};

TEST_F(ExtractExampleParserConfigurationTest, OpNotFound) {
  std::vector<FixedLenFeature> dense_vec;
  std::vector<VarLenFeature> sparse_vec;
  Status status = ExtractExampleParserConfiguration(
      graph_def_, "BlarseExample/ParseExample", session_.get(), &dense_vec,
      &sparse_vec);

  EXPECT_EQ(status.code(), error::INVALID_ARGUMENT);
}

TEST_F(ExtractExampleParserConfigurationTest, InconsistentAttrNsparse) {
  std::vector<FixedLenFeature> dense_vec;
  std::vector<VarLenFeature> sparse_vec;

  NodeDef* node = parse_example_node();
  auto mutable_attr = node->mutable_attr();
  (*mutable_attr)["Nsparse"].set_i(3);

  Status status = ExtractExampleParserConfiguration(
      graph_def_, "ParseExample/ParseExample", session_.get(), &dense_vec,
      &sparse_vec);

  EXPECT_EQ(status.code(), error::INVALID_ARGUMENT);
}

TEST_F(ExtractExampleParserConfigurationTest, InconsistentAttrNdense) {
  std::vector<FixedLenFeature> dense_vec;
  std::vector<VarLenFeature> sparse_vec;

  NodeDef* node = parse_example_node();
  auto mutable_attr = node->mutable_attr();
  (*mutable_attr)["Ndense"].set_i(2);

  Status status = ExtractExampleParserConfiguration(
      graph_def_, "ParseExample/ParseExample", session_.get(), &dense_vec,
      &sparse_vec);

  EXPECT_EQ(status.code(), error::INVALID_ARGUMENT);
}

TEST_F(ExtractExampleParserConfigurationTest, Basic) {
  std::vector<FixedLenFeature> dense_vec;
  std::vector<VarLenFeature> sparse_vec;
  Status status = ExtractExampleParserConfiguration(
      graph_def_, "ParseExample/ParseExample", session_.get(), &dense_vec,
      &sparse_vec);

  EXPECT_EQ(Status::OK(), status);
  EXPECT_EQ(2, sparse_vec.size());
  EXPECT_EQ(3, dense_vec.size());

  EXPECT_EQ("sf0", sparse_vec[0].key);
  EXPECT_EQ(DT_STRING, sparse_vec[0].dtype);
  EXPECT_EQ("ParseExample/ParseExample:0",
            sparse_vec[0].indices_output_tensor_name);
  EXPECT_EQ("ParseExample/ParseExample:2",
            sparse_vec[0].values_output_tensor_name);
  EXPECT_EQ("ParseExample/ParseExample:4",
            sparse_vec[0].shapes_output_tensor_name);

  EXPECT_EQ("sf1", sparse_vec[1].key);
  EXPECT_EQ(DT_STRING, sparse_vec[1].dtype);
  EXPECT_EQ("ParseExample/ParseExample:1",
            sparse_vec[1].indices_output_tensor_name);
  EXPECT_EQ("ParseExample/ParseExample:3",
            sparse_vec[1].values_output_tensor_name);
  EXPECT_EQ("ParseExample/ParseExample:5",
            sparse_vec[1].shapes_output_tensor_name);

  EXPECT_EQ("x", dense_vec[0].key);
  EXPECT_EQ(DT_FLOAT, dense_vec[0].dtype);
  EXPECT_EQ("ParseExample/ParseExample:6",
            dense_vec[0].values_output_tensor_name);

  EXPECT_EQ("y", dense_vec[1].key);
  EXPECT_EQ(DT_FLOAT, dense_vec[1].dtype);
  EXPECT_EQ("ParseExample/ParseExample:7",
            dense_vec[1].values_output_tensor_name);

  EXPECT_EQ("z", dense_vec[2].key);
  EXPECT_EQ(DT_FLOAT, dense_vec[2].dtype);
  EXPECT_EQ("ParseExample/ParseExample:8",
            dense_vec[2].values_output_tensor_name);
}

static const char kExampleParseConfigurationProto[] = R"( feature_map {
  key: "x"
  value {
    fixed_len_feature {
      dtype: DT_FLOAT
      shape {
        dim {
          size: 1
        }
      }
      default_value {
        dtype: DT_FLOAT
        tensor_shape {
          dim {
            size: 1
          }
        }
        float_val: 33.0
      }
      values_output_tensor_name: "ParseExample/ParseExample:3"
    }
  }
}
feature_map {
  key: "y"
  value {
    var_len_feature {
      dtype: DT_STRING
      values_output_tensor_name: "ParseExample/ParseExample:1"
      indices_output_tensor_name: "ParseExample/ParseExample:0"
      shapes_output_tensor_name: "ParseExample/ParseExample:2"
    }
  }
}
)";

class ExampleParserConfigurationProtoToFeatureVectorsTest
    : public ::testing::Test {
 protected:
  void SetUp() override {
    CHECK(protobuf::TextFormat::ParseFromString(kExampleParseConfigurationProto,
                                                &config_proto_));
  }
  ExampleParserConfiguration config_proto_;
};

TEST_F(ExampleParserConfigurationProtoToFeatureVectorsTest, Basic) {
  std::vector<FixedLenFeature> fixed_len_features;
  std::vector<VarLenFeature> var_len_features;
  TF_ASSERT_OK(ExampleParserConfigurationProtoToFeatureVectors(
      config_proto_, &fixed_len_features, &var_len_features));
  ASSERT_EQ(1, fixed_len_features.size());
  ASSERT_EQ(1, var_len_features.size());

  const FixedLenFeature& f = fixed_len_features[0];
  ASSERT_EQ(DT_FLOAT, f.dtype);
  ASSERT_EQ("x", f.key);
  ASSERT_EQ("ParseExample/ParseExample:3", f.values_output_tensor_name);

  TensorShape expected_shape({1});
  ASSERT_EQ(expected_shape.dims(), f.shape.dims());
  ASSERT_EQ(1, f.shape.dim_size(0));

  Tensor expected_default(DT_FLOAT, TensorShape({1}));
  test::FillIota<float>(&expected_default, 33.0);
  test::ExpectTensorEqual<float>(expected_default, f.default_value);

  const VarLenFeature& v = var_len_features[0];
  ASSERT_EQ(DT_STRING, v.dtype);
  ASSERT_EQ("ParseExample/ParseExample:0", v.indices_output_tensor_name);
  ASSERT_EQ("ParseExample/ParseExample:1", v.values_output_tensor_name);
  ASSERT_EQ("ParseExample/ParseExample:2", v.shapes_output_tensor_name);
}

}  // namespace
}  // namespace tensorflow