-
Notifications
You must be signed in to change notification settings - Fork 74k
/
example_parsing_ops.cc
1237 lines (1134 loc) · 55.5 KB
/
example_parsing_ops.cc
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright 2015 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.
==============================================================================*/
// See docs in ../ops/parsing_ops.cc.
#include <numeric>
#include <unordered_set>
#include <vector>
#include "absl/base/call_once.h"
#include "tensorflow/core/example/example.pb.h"
#include "tensorflow/core/example/feature.pb.h"
#include "tensorflow/core/framework/common_shape_fns.h"
#include "tensorflow/core/framework/metrics.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/gtl/array_slice.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/util/example_proto_fast_parsing.h"
#include "tensorflow/core/util/example_proto_helper.h"
#include "tensorflow/core/util/sparse/sparse_tensor.h"
#include "tensorflow/core/util/work_sharder.h"
namespace tensorflow {
namespace {
constexpr char kParseExampleV2[] = "ParseExampleV2";
constexpr char kParseSequenceExampleV2[] = "ParseSequenceExampleV2";
} // namespace
// Note: this kernel is used by both the ParseExample op and the ParseExampleV2
// op. It automatically determines which op was used by checking if the
// "ragged_value_types" attribute exists.
class ParseExampleOp : public OpKernel {
public:
explicit ParseExampleOp(OpKernelConstruction* ctx)
: OpKernel(ctx), op_version_(ctx->def().op() == kParseExampleV2 ? 2 : 1) {
OP_REQUIRES_OK(ctx, attrs_.Init(ctx, op_version_));
}
void Compute(OpKernelContext* ctx) override {
const Tensor* names;
const Tensor* serialized;
std::vector<StringPiece> dense_keys_t;
std::vector<StringPiece> sparse_keys_t;
std::vector<StringPiece> ragged_keys_t;
OpInputList dense_defaults;
// Grab the inputs.
OP_REQUIRES_OK(ctx, ctx->input("serialized", &serialized));
OP_REQUIRES(ctx, serialized->NumElements() == 0 || serialized->data(),
errors::InvalidArgument(
"Serialized data must not be null if there are elements"));
OP_REQUIRES_OK(ctx, ctx->input("names", &names));
if (op_version_ == 2) {
OP_REQUIRES_OK(ctx, GetTensorKeys(ctx, "dense_keys", &dense_keys_t));
OP_REQUIRES_OK(ctx, GetTensorKeys(ctx, "sparse_keys", &sparse_keys_t));
OP_REQUIRES_OK(ctx, GetTensorKeys(ctx, "ragged_keys", &ragged_keys_t));
} else {
OP_REQUIRES_OK(ctx, GetInputListKeys(ctx, "dense_keys", &dense_keys_t));
OP_REQUIRES_OK(ctx, GetInputListKeys(ctx, "sparse_keys", &sparse_keys_t));
}
absl::call_once(flag_, [&dense_keys_t, &sparse_keys_t, &ragged_keys_t]() {
metrics::RecordParseDenseFeature(dense_keys_t.size());
metrics::RecordParseSparseFeature(sparse_keys_t.size());
metrics::RecordParseRaggedFeature(ragged_keys_t.size());
});
OP_REQUIRES_OK(ctx, ctx->input_list("dense_defaults", &dense_defaults));
// Validate input tensor shapes.
OP_REQUIRES_OK(
ctx, CheckInputShapes(serialized, names, dense_defaults, dense_keys_t,
sparse_keys_t, ragged_keys_t));
example::FastParseExampleConfig config =
MakeConfig(dense_keys_t, sparse_keys_t, ragged_keys_t, dense_defaults);
example::Result result;
if (TensorShapeUtils::IsVector(serialized->shape())) {
OP_REQUIRES_OK(
ctx, ParseExampleVector(config, serialized, names, ctx, &result));
} else {
OP_REQUIRES_OK(ctx, ParseExampleScalar(config, serialized, ctx, &result));
}
OP_REQUIRES_OK(ctx, WriteOutput(result, ctx));
}
protected:
// Copies keys from tensor to std::vector<string>.
Status GetTensorKeys(OpKernelContext* ctx, StringPiece input_name,
std::vector<StringPiece>* keys) const {
const Tensor* key_t;
TF_RETURN_IF_ERROR(ctx->input(input_name, &key_t));
keys->reserve(key_t->NumElements());
auto keys_flat = key_t->flat<tstring>();
for (int i = 0; i < keys_flat.size(); ++i) {
keys->push_back(keys_flat(i));
}
return OkStatus();
}
// Copies keys from OpInputList of scalar to std::vector<string>.
Status GetInputListKeys(OpKernelContext* ctx, StringPiece input_name,
std::vector<StringPiece>* keys) const {
OpInputList key_list;
TF_RETURN_IF_ERROR(ctx->input_list(input_name, &key_list));
keys->reserve(key_list.size());
for (const auto& key : key_list) {
keys->push_back(key.scalar<tstring>()());
}
return OkStatus();
}
// Validates the shapes of input tensors.
Status CheckInputShapes(const Tensor* serialized, const Tensor* names,
const OpInputList& dense_defaults,
const std::vector<StringPiece>& dense_keys_t,
const std::vector<StringPiece>& sparse_keys_t,
const std::vector<StringPiece>& ragged_keys_t) const {
if (op_version_ == 2) {
if (TensorShapeUtils::IsMatrixOrHigher(serialized->shape())) {
return errors::InvalidArgument(
"Expected serialized to be a scalar or vector, got shape: ",
serialized->shape().DebugString());
}
} else {
if (!TensorShapeUtils::IsVector(serialized->shape())) {
return errors::InvalidArgument(
"Expected serialized to be a vector, got shape: ",
serialized->shape().DebugString());
}
}
if (names->NumElements() > 0 && names->shape() != serialized->shape()) {
return errors::InvalidArgument(
"Expected names have the same shape as serialized: name.shape=",
names->shape().DebugString(),
", serialized.shape=", serialized->shape().DebugString());
}
if (op_version_ == 2) {
if (dense_keys_t.size() != attrs_.num_dense) {
return errors::InvalidArgument(
"Expected len(dense_keys) == len(dense_types) but got: ",
dense_keys_t.size(), " vs. ", attrs_.num_dense);
}
if (sparse_keys_t.size() != attrs_.num_sparse) {
return errors::InvalidArgument(
"Expected len(sparse_keys) == num_sparse but got: ",
sparse_keys_t.size(), " vs. ", attrs_.num_sparse);
}
if (ragged_keys_t.size() != attrs_.num_ragged) {
return errors::InvalidArgument(
"Expected len(ragged_keys) == len(ragged_value_types) but got: ",
ragged_keys_t.size(), " vs. ", attrs_.num_ragged);
}
}
if (dense_defaults.size() != attrs_.num_dense) {
return errors::InvalidArgument(
"Expected len(dense_defaults) == len(dense_keys) but got: ",
dense_defaults.size(), " vs. ", attrs_.num_dense);
}
for (int d = 0; d < static_cast<int>(attrs_.num_dense); ++d) {
const Tensor& def_value = dense_defaults[d];
if (attrs_.variable_length[d]) {
if (def_value.NumElements() != 1) {
return errors::InvalidArgument(
"dense_shape[", d, "] is a variable length shape: ",
attrs_.dense_shapes[d].DebugString(),
", therefore "
"def_value[",
d,
"] must contain a single element ("
"the padding element). But its shape is: ",
def_value.shape().DebugString());
}
} else if (def_value.NumElements() > 0) {
if (!attrs_.dense_shapes[d].IsCompatibleWith(def_value.shape())) {
return errors::InvalidArgument(
"def_value[", d, "].shape() == ", def_value.shape().DebugString(),
" is not compatible with dense_shapes_[", d,
"] == ", attrs_.dense_shapes[d].DebugString());
}
}
if (def_value.dtype() != attrs_.dense_types[d]) {
return errors::InvalidArgument(
"dense_defaults[", d,
"].dtype() == ", DataTypeString(def_value.dtype()),
" != dense_types_[", d,
"] == ", DataTypeString(attrs_.dense_types[d]));
}
}
return OkStatus();
}
// Populates the FastParseExampleConfig from keys & defaults.
example::FastParseExampleConfig MakeConfig(
const std::vector<StringPiece>& dense_keys_t,
const std::vector<StringPiece>& sparse_keys_t,
const std::vector<StringPiece>& ragged_keys_t,
const OpInputList& dense_defaults) const {
example::FastParseExampleConfig config;
config.dense.reserve(attrs_.num_dense);
for (int d = 0; d < attrs_.num_dense; ++d) {
config.dense.emplace_back(dense_keys_t[d], attrs_.dense_types[d],
attrs_.dense_shapes[d], dense_defaults[d],
attrs_.variable_length[d],
attrs_.elements_per_stride[d]);
}
config.sparse.reserve(attrs_.num_sparse);
for (int d = 0; d < attrs_.num_sparse; ++d) {
config.sparse.emplace_back(sparse_keys_t[d], attrs_.sparse_types[d]);
}
config.ragged.reserve(attrs_.num_ragged);
for (int d = 0; d < attrs_.num_ragged; ++d) {
config.ragged.emplace_back(ragged_keys_t[d], attrs_.ragged_value_types[d],
attrs_.ragged_split_types[d]);
}
return config;
}
// Parses a single example.
Status ParseExampleScalar(const example::FastParseExampleConfig& config,
const Tensor* serialized, OpKernelContext* ctx,
example::Result* result) const {
const tstring& serialized_proto = serialized->scalar<tstring>()();
return FastParseSingleExample(config, serialized_proto, result);
}
// Parses a vector of examples.
Status ParseExampleVector(const example::FastParseExampleConfig& config,
const Tensor* serialized, const Tensor* names,
OpKernelContext* ctx,
example::Result* result) const {
auto serialized_t = serialized->flat<tstring>();
auto names_t = names->flat<tstring>();
gtl::ArraySlice<tstring> slice(serialized_t.data(), serialized_t.size());
gtl::ArraySlice<tstring> names_slice(names_t.data(), names_t.size());
return FastParseExample(
config, slice, names_slice,
ctx->device()->tensorflow_cpu_worker_threads()->workers, result);
}
Status WriteOutput(const example::Result& result,
OpKernelContext* ctx) const {
OpOutputList dense_values;
OpOutputList sparse_indices;
OpOutputList sparse_values;
OpOutputList sparse_shapes;
TF_RETURN_IF_ERROR(ctx->output_list("dense_values", &dense_values));
TF_RETURN_IF_ERROR(ctx->output_list("sparse_indices", &sparse_indices));
TF_RETURN_IF_ERROR(ctx->output_list("sparse_values", &sparse_values));
TF_RETURN_IF_ERROR(ctx->output_list("sparse_shapes", &sparse_shapes));
for (int d = 0; d < attrs_.num_dense; ++d) {
dense_values.set(d, result.dense_values[d]);
}
for (int d = 0; d < attrs_.num_sparse; ++d) {
sparse_indices.set(d, result.sparse_indices[d]);
sparse_values.set(d, result.sparse_values[d]);
sparse_shapes.set(d, result.sparse_shapes[d]);
}
if (op_version_ == 2) {
OpOutputList ragged_values;
OpOutputList ragged_splits;
TF_RETURN_IF_ERROR(ctx->output_list("ragged_values", &ragged_values));
TF_RETURN_IF_ERROR(ctx->output_list("ragged_row_splits", &ragged_splits));
for (int d = 0; d < attrs_.num_ragged; ++d) {
ragged_values.set(d, result.ragged_values[d]);
ragged_splits.set(d, result.ragged_splits[d]);
}
}
return OkStatus();
}
ParseExampleAttrs attrs_;
int op_version_;
absl::once_flag flag_;
};
REGISTER_KERNEL_BUILDER(Name("ParseExample").Device(DEVICE_CPU),
ParseExampleOp);
REGISTER_KERNEL_BUILDER(Name("ParseExampleV2").Device(DEVICE_CPU),
ParseExampleOp);
class ParseSingleExampleOp : public OpKernel {
public:
explicit ParseSingleExampleOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
OP_REQUIRES_OK(ctx, attrs_.Init(ctx));
metrics::RecordParseDenseFeature(attrs_.dense_keys.size());
metrics::RecordParseSparseFeature(attrs_.sparse_keys.size());
}
void Compute(OpKernelContext* ctx) override {
const Tensor* serialized;
OpInputList dense_defaults;
// Grab the input list arguments.
OP_REQUIRES_OK(ctx, ctx->input("serialized", &serialized));
OP_REQUIRES_OK(ctx, ctx->input_list("dense_defaults", &dense_defaults));
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(serialized->shape()),
errors::InvalidArgument(
"Expected serialized to be a scalar, got shape: ",
serialized->shape().DebugString()));
OP_REQUIRES(ctx, dense_defaults.size() == attrs_.dense_keys.size(),
errors::InvalidArgument(
"Expected len(dense_defaults) == len(dense_keys) but got: ",
dense_defaults.size(), " vs. ", attrs_.dense_keys.size()));
for (size_t d = 0; d < attrs_.dense_keys.size(); ++d) {
const Tensor& def_value = dense_defaults[d];
if (attrs_.variable_length[d]) {
OP_REQUIRES(ctx, def_value.NumElements() == 1,
errors::InvalidArgument(
"dense_shape[", d, "] is a variable length shape: ",
attrs_.dense_shapes[d].DebugString(),
", therefore "
"def_value[",
d,
"] must contain a single element ("
"the padding element). But its shape is: ",
def_value.shape().DebugString()));
} else if (def_value.NumElements() > 0) {
OP_REQUIRES(ctx,
attrs_.dense_shapes[d].IsCompatibleWith(def_value.shape()),
errors::InvalidArgument(
"def_value[", d,
"].shape() == ", def_value.shape().DebugString(),
" is not compatible with dense_shapes_[", d,
"] == ", attrs_.dense_shapes[d].DebugString()));
}
OP_REQUIRES(ctx, def_value.dtype() == attrs_.dense_types[d],
errors::InvalidArgument(
"dense_defaults[", d, "].dtype() == ",
DataTypeString(def_value.dtype()), " != dense_types_[", d,
"] == ", DataTypeString(attrs_.dense_types[d])));
}
example::Result result;
// TODO(mrry): Build the configuration once and cache it.
example::FastParseExampleConfig config;
for (int d = 0; d < attrs_.dense_keys.size(); ++d) {
config.dense.push_back({attrs_.dense_keys[d], attrs_.dense_types[d],
attrs_.dense_shapes[d], dense_defaults[d],
attrs_.variable_length[d],
attrs_.elements_per_stride[d]});
}
for (int d = 0; d < attrs_.sparse_keys.size(); ++d) {
config.sparse.push_back({attrs_.sparse_keys[d], attrs_.sparse_types[d]});
}
const tstring& serialized_proto = serialized->scalar<tstring>()();
OP_REQUIRES_OK(ctx,
FastParseSingleExample(config, serialized_proto, &result));
OpOutputList dense_values;
OpOutputList sparse_indices;
OpOutputList sparse_values;
OpOutputList sparse_shapes;
OP_REQUIRES_OK(ctx, ctx->output_list("dense_values", &dense_values));
OP_REQUIRES_OK(ctx, ctx->output_list("sparse_indices", &sparse_indices));
OP_REQUIRES_OK(ctx, ctx->output_list("sparse_values", &sparse_values));
OP_REQUIRES_OK(ctx, ctx->output_list("sparse_shapes", &sparse_shapes));
for (int d = 0; d < attrs_.dense_keys.size(); ++d) {
dense_values.set(d, result.dense_values[d]);
}
for (int d = 0; d < attrs_.sparse_keys.size(); ++d) {
sparse_indices.set(d, result.sparse_indices[d]);
sparse_values.set(d, result.sparse_values[d]);
sparse_shapes.set(d, result.sparse_shapes[d]);
}
}
protected:
ParseSingleExampleAttrs attrs_;
};
REGISTER_KERNEL_BUILDER(Name("ParseSingleExample").Device(DEVICE_CPU),
ParseSingleExampleOp);
class ParseSequenceExampleOp : public OpKernel {
public:
explicit ParseSequenceExampleOp(OpKernelConstruction* ctx)
: OpKernel(ctx),
op_version_(ctx->def().op() == kParseSequenceExampleV2 ? 2 : 1) {
OP_REQUIRES_OK(ctx, attrs_.Init(ctx, op_version_));
metrics::RecordParseDenseFeature(attrs_.context_dense_keys.size() +
attrs_.feature_list_dense_keys.size());
metrics::RecordParseSparseFeature(attrs_.context_sparse_keys.size() +
attrs_.feature_list_sparse_keys.size());
}
void Compute(OpKernelContext* ctx) override {
const Tensor* debug_name;
const Tensor* serialized;
OpInputList context_dense_defaults;
OP_REQUIRES_OK(ctx, ctx->input("debug_name", &debug_name));
OP_REQUIRES_OK(ctx, ctx->input("serialized", &serialized));
OP_REQUIRES_OK(ctx, ctx->input_list("context_dense_defaults",
&context_dense_defaults));
const Tensor* context_dense_keys = nullptr;
const Tensor* context_sparse_keys = nullptr;
const Tensor* context_ragged_keys = nullptr;
const Tensor* feature_list_dense_keys = nullptr;
const Tensor* feature_list_sparse_keys = nullptr;
const Tensor* feature_list_ragged_keys = nullptr;
const Tensor* feature_list_dense_missing_assumed_empty = nullptr;
if (op_version_ == 2) {
OP_REQUIRES_OK(ctx,
ctx->input("feature_list_dense_missing_assumed_empty",
&feature_list_dense_missing_assumed_empty));
OP_REQUIRES_OK(ctx,
ctx->input("context_dense_keys", &context_dense_keys));
OP_REQUIRES_OK(ctx,
ctx->input("context_sparse_keys", &context_sparse_keys));
OP_REQUIRES_OK(ctx,
ctx->input("context_ragged_keys", &context_ragged_keys));
OP_REQUIRES_OK(
ctx, ctx->input("feature_list_dense_keys", &feature_list_dense_keys));
OP_REQUIRES_OK(ctx, ctx->input("feature_list_sparse_keys",
&feature_list_sparse_keys));
OP_REQUIRES_OK(ctx, ctx->input("feature_list_ragged_keys",
&feature_list_ragged_keys));
absl::call_once(flag_, [&]() {
metrics::RecordParseDenseFeature(
context_dense_keys->NumElements() +
feature_list_dense_keys->NumElements());
metrics::RecordParseSparseFeature(
context_sparse_keys->NumElements() +
feature_list_sparse_keys->NumElements());
metrics::RecordParseRaggedFeature(
context_ragged_keys->NumElements() +
feature_list_ragged_keys->NumElements());
});
}
// Validate input tensor shapes.
OP_REQUIRES_OK(ctx, CheckInputShapes(
serialized, debug_name, context_dense_defaults,
context_dense_keys, context_sparse_keys,
context_ragged_keys, feature_list_dense_keys,
feature_list_sparse_keys, feature_list_ragged_keys,
feature_list_dense_missing_assumed_empty));
example::FastParseExampleConfig context_config =
MakeContextConfig(context_dense_keys, context_sparse_keys,
context_ragged_keys, context_dense_defaults);
example::FastParseExampleConfig feature_list_config = MakeFeatureListConfig(
feature_list_dense_keys, feature_list_sparse_keys,
feature_list_ragged_keys, feature_list_dense_missing_assumed_empty);
bool is_batch = TensorShapeUtils::IsVector(serialized->shape());
auto serialized_t = serialized->flat<tstring>();
auto debug_name_t = debug_name->flat<tstring>();
gtl::ArraySlice<tstring> slice(serialized_t.data(), serialized_t.size());
gtl::ArraySlice<tstring> names_slice(debug_name_t.data(),
debug_name_t.size());
example::Result context_result, feature_list_result;
std::vector<Tensor> dense_feature_lengths;
OP_REQUIRES_OK(
ctx, FastParseSequenceExample(
context_config, feature_list_config, slice, names_slice,
ctx->device()->tensorflow_cpu_worker_threads()->workers,
&context_result, &feature_list_result, &dense_feature_lengths,
is_batch));
OP_REQUIRES_OK(ctx, WriteOutput(context_result, feature_list_result,
dense_feature_lengths, ctx));
}
protected:
Status CheckInputShapes(
const Tensor* serialized, const Tensor* names,
const OpInputList& context_dense_defaults,
const Tensor* context_dense_keys, const Tensor* context_sparse_keys,
const Tensor* context_ragged_keys, const Tensor* feature_list_dense_keys,
const Tensor* feature_list_sparse_keys,
const Tensor* feature_list_ragged_keys,
const Tensor* feature_list_dense_missing_assumed_empty) const {
if (TensorShapeUtils::IsMatrixOrHigher(serialized->shape())) {
return errors::InvalidArgument(
"Expected serialized to be a scalar or vector, got shape: ",
serialized->shape().DebugString());
}
if (op_version_ > 1) {
if (context_dense_keys->NumElements() != attrs_.num_context_dense) {
return errors::InvalidArgument(
"Expected len(context_dense_keys) to match len(Tcontext_dense)");
}
if (context_sparse_keys->NumElements() != attrs_.num_context_sparse) {
return errors::InvalidArgument(
"Expected len(context_sparse_keys) to match Ncontext_sparse");
}
if (context_ragged_keys->NumElements() != attrs_.num_context_ragged) {
return errors::InvalidArgument(
"Expected len(context_ragged_keys) to match "
"len(context_ragged_value_types)");
}
if (feature_list_dense_keys->NumElements() !=
attrs_.num_feature_list_dense) {
return errors::InvalidArgument(
"Expected len(feature_list_dense_keys) to match "
"Nfeature_list_dense");
}
if (feature_list_dense_missing_assumed_empty->NumElements() !=
attrs_.num_feature_list_dense) {
return errors::InvalidArgument(
"Expected len(feature_list_dense_missing_assumed_empty to match "
"Nfeature_list_dense");
}
if (feature_list_sparse_keys->NumElements() !=
attrs_.num_feature_list_sparse) {
return errors::InvalidArgument(
"Expected len(feature_list_sparse_keys) to match "
"Nfeature_list_sparse");
}
if (feature_list_ragged_keys->NumElements() !=
attrs_.num_feature_list_ragged) {
return errors::InvalidArgument(
"Expected len(feature_list_ragged_keys) to match "
"len(feature_list_ragged_value_types)");
}
}
if (context_dense_defaults.size() != attrs_.num_context_dense) {
return errors::InvalidArgument(
"Expected len(context_dense_defaults) "
"== len(context_dense_keys) but got: ",
context_dense_defaults.size(), " vs. ", attrs_.num_context_dense);
}
for (int d = 0; d < attrs_.num_context_dense; ++d) {
const Tensor& def_value = context_dense_defaults[d];
if (def_value.NumElements() > 0) {
if (def_value.shape() != attrs_.context_dense_shapes[d]) {
return errors::InvalidArgument(
"default_value[", d,
"].shape() == ", def_value.shape().DebugString(),
" != context_dense_shapes[", d,
"] == ", attrs_.context_dense_shapes[d].DebugString());
}
if (def_value.dtype() != attrs_.context_dense_types[d]) {
return errors::InvalidArgument(
"context_dense_defaults[", d,
"].dtype() == ", DataTypeString(def_value.dtype()),
" != context_dense_types[", d,
"] == ", DataTypeString(attrs_.context_dense_types[d]));
}
}
}
return OkStatus();
}
example::FastParseExampleConfig MakeContextConfig(
const Tensor* dense_keys, const Tensor* sparse_keys,
const Tensor* ragged_keys,
const OpInputList& context_dense_defaults) const {
// Convert the tensors/attrs to ArraySlices once, instead of re-evaluating
// them in each loop iteration.
gtl::ArraySlice<tstring> dense_keys_slice =
dense_keys
? gtl::ArraySlice<tstring>(dense_keys->flat<tstring>().data(),
attrs_.num_context_dense)
: attrs_.context_dense_keys;
gtl::ArraySlice<tstring> sparse_keys_slice =
sparse_keys
? gtl::ArraySlice<tstring>(sparse_keys->flat<tstring>().data(),
attrs_.num_context_sparse)
: attrs_.context_sparse_keys;
gtl::ArraySlice<tstring> ragged_keys_slice =
ragged_keys
? gtl::ArraySlice<tstring>(ragged_keys->flat<tstring>().data(),
attrs_.num_context_ragged)
: gtl::ArraySlice<tstring>(nullptr, 0);
example::FastParseExampleConfig config;
config.dense.reserve(attrs_.num_context_dense);
for (int d = 0; d < attrs_.num_context_dense; ++d) {
const tstring& key = dense_keys_slice[d];
config.dense.emplace_back(key, attrs_.context_dense_types[d],
attrs_.context_dense_shapes[d],
context_dense_defaults[d],
false /* attrs_.context_variable_length[d] */,
0 /*attrs_.context_elements_per_stride[d] */);
}
config.sparse.reserve(attrs_.num_context_sparse);
for (int d = 0; d < attrs_.num_context_sparse; ++d) {
const tstring& key = sparse_keys_slice[d];
config.sparse.emplace_back(key, attrs_.context_sparse_types[d]);
}
config.ragged.reserve(attrs_.num_context_ragged);
for (int d = 0; d < attrs_.num_context_ragged; ++d) {
config.ragged.emplace_back(ragged_keys_slice[d],
attrs_.context_ragged_value_types[d],
attrs_.context_ragged_split_types[d]);
}
return config;
}
static Tensor ConstructDefaultScalar(DataType dtype) {
switch (dtype) {
case DT_INT64:
return Tensor(static_cast<int64_t>(0));
case DT_FLOAT:
return Tensor(static_cast<float>(0.0));
case DT_STRING:
return Tensor("");
default:
return Tensor(DT_INVALID);
}
}
example::FastParseExampleConfig MakeFeatureListConfig(
const Tensor* dense_keys, const Tensor* sparse_keys,
const Tensor* ragged_keys,
const Tensor* feature_list_dense_missing_assumed_empty) const {
// Convert the tensors/attrs to ArraySlices once, instead of re-evaluating
// them in each loop iteration.
gtl::ArraySlice<tstring> dense_keys_slice =
dense_keys
? gtl::ArraySlice<tstring>(dense_keys->flat<tstring>().data(),
attrs_.num_feature_list_dense)
: attrs_.feature_list_dense_keys;
gtl::ArraySlice<tstring> sparse_keys_slice =
sparse_keys
? gtl::ArraySlice<tstring>(sparse_keys->flat<tstring>().data(),
attrs_.num_feature_list_sparse)
: attrs_.feature_list_sparse_keys;
gtl::ArraySlice<tstring> ragged_keys_slice =
ragged_keys
? gtl::ArraySlice<tstring>(ragged_keys->flat<tstring>().data(),
attrs_.num_feature_list_ragged)
: gtl::ArraySlice<tstring>(nullptr, 0);
// Use an empty slice to indicate that the map in attrs_ should be used
// instead.
gtl::ArraySlice<bool> feature_list_dense_missing_assumed_empty_slice =
feature_list_dense_missing_assumed_empty
? gtl::ArraySlice<bool>(
feature_list_dense_missing_assumed_empty->flat<bool>().data(),
attrs_.num_feature_list_dense)
: gtl::ArraySlice<bool>(nullptr, 0);
example::FastParseExampleConfig config;
config.dense.reserve(attrs_.num_feature_list_dense);
for (int d = 0; d < attrs_.num_feature_list_dense; ++d) {
const tstring& key = dense_keys_slice[d];
bool missing_assumed_empty =
!feature_list_dense_missing_assumed_empty_slice.empty()
? feature_list_dense_missing_assumed_empty_slice[d]
: attrs_.feature_list_dense_missing_assumed_empty.count(key) > 0;
DataType dtype = attrs_.feature_list_dense_types[d];
config.dense.emplace_back(
key, dtype, attrs_.feature_list_dense_shapes[d],
ConstructDefaultScalar(dtype), missing_assumed_empty,
0 /*attrs_.feature_list_elements_per_stride[d] */);
}
config.sparse.reserve(attrs_.num_feature_list_sparse);
for (int d = 0; d < attrs_.num_feature_list_sparse; ++d) {
const tstring& key = sparse_keys_slice[d];
config.sparse.emplace_back(key, attrs_.feature_list_sparse_types[d]);
}
config.ragged.reserve(attrs_.num_feature_list_ragged);
for (int d = 0; d < attrs_.num_feature_list_ragged; ++d) {
config.ragged.emplace_back(ragged_keys_slice[d],
attrs_.feature_list_ragged_value_types[d],
attrs_.feature_list_ragged_split_types[d]);
}
return config;
}
Status WriteOutput(const example::Result& context_result,
const example::Result& feature_list_result,
const std::vector<Tensor>& dense_feature_lengths,
OpKernelContext* ctx) const {
OpOutputList context_sparse_indices;
OpOutputList context_sparse_values;
OpOutputList context_sparse_shapes;
OpOutputList context_dense_values;
OpOutputList feature_list_sparse_indices;
OpOutputList feature_list_sparse_values;
OpOutputList feature_list_sparse_shapes;
OpOutputList feature_list_dense_values;
OpOutputList feature_list_dense_lengths;
TF_RETURN_IF_ERROR(
ctx->output_list("context_sparse_indices", &context_sparse_indices));
TF_RETURN_IF_ERROR(
ctx->output_list("context_sparse_values", &context_sparse_values));
TF_RETURN_IF_ERROR(
ctx->output_list("context_sparse_shapes", &context_sparse_shapes));
TF_RETURN_IF_ERROR(
ctx->output_list("context_dense_values", &context_dense_values));
TF_RETURN_IF_ERROR(
ctx->output_list("context_sparse_indices", &context_sparse_indices));
TF_RETURN_IF_ERROR(ctx->output_list("feature_list_sparse_indices",
&feature_list_sparse_indices));
TF_RETURN_IF_ERROR(ctx->output_list("feature_list_sparse_values",
&feature_list_sparse_values));
TF_RETURN_IF_ERROR(ctx->output_list("feature_list_sparse_shapes",
&feature_list_sparse_shapes));
TF_RETURN_IF_ERROR(ctx->output_list("feature_list_dense_values",
&feature_list_dense_values));
TF_RETURN_IF_ERROR(ctx->output_list("feature_list_dense_lengths",
&feature_list_dense_lengths));
for (int d = 0; d < attrs_.num_context_dense; ++d) {
context_dense_values.set(d, context_result.dense_values[d]);
}
for (int d = 0; d < attrs_.num_feature_list_dense; ++d) {
feature_list_dense_values.set(d, feature_list_result.dense_values[d]);
feature_list_dense_lengths.set(d, dense_feature_lengths[d]);
}
for (int d = 0; d < attrs_.num_context_sparse; ++d) {
context_sparse_indices.set(d, context_result.sparse_indices[d]);
context_sparse_values.set(d, context_result.sparse_values[d]);
context_sparse_shapes.set(d, context_result.sparse_shapes[d]);
}
for (int d = 0; d < attrs_.num_feature_list_sparse; ++d) {
feature_list_sparse_indices.set(d, feature_list_result.sparse_indices[d]);
feature_list_sparse_values.set(d, feature_list_result.sparse_values[d]);
feature_list_sparse_shapes.set(d, feature_list_result.sparse_shapes[d]);
}
if (op_version_ == 2) {
OpOutputList context_ragged_values;
OpOutputList context_ragged_splits;
OpOutputList feature_list_ragged_values;
OpOutputList feature_list_ragged_inner_splits;
OpOutputList feature_list_ragged_outer_splits;
TF_RETURN_IF_ERROR(
ctx->output_list("context_ragged_values", &context_ragged_values));
TF_RETURN_IF_ERROR(ctx->output_list("context_ragged_row_splits",
&context_ragged_splits));
TF_RETURN_IF_ERROR(ctx->output_list("feature_list_ragged_values",
&feature_list_ragged_values));
TF_RETURN_IF_ERROR(ctx->output_list("feature_list_ragged_inner_splits",
&feature_list_ragged_inner_splits));
TF_RETURN_IF_ERROR(ctx->output_list("feature_list_ragged_outer_splits",
&feature_list_ragged_outer_splits));
for (int d = 0; d < attrs_.num_context_ragged; ++d) {
context_ragged_values.set(d, context_result.ragged_values[d]);
context_ragged_splits.set(d, context_result.ragged_splits[d]);
}
for (int d = 0; d < attrs_.num_feature_list_ragged; ++d) {
feature_list_ragged_values.set(d, feature_list_result.ragged_values[d]);
feature_list_ragged_outer_splits.set(
d, feature_list_result.ragged_outer_splits[d]);
feature_list_ragged_inner_splits.set(
d, feature_list_result.ragged_splits[d]);
}
}
return OkStatus();
}
ParseSequenceExampleAttrs attrs_;
int op_version_;
absl::once_flag flag_;
};
REGISTER_KERNEL_BUILDER(Name("ParseSequenceExample").Device(DEVICE_CPU),
ParseSequenceExampleOp);
REGISTER_KERNEL_BUILDER(Name("ParseSequenceExampleV2").Device(DEVICE_CPU),
ParseSequenceExampleOp);
class ParseSingleSequenceExampleOp : public OpKernel {
public:
explicit ParseSingleSequenceExampleOp(OpKernelConstruction* ctx)
: OpKernel(ctx) {
OP_REQUIRES_OK(ctx, attrs_.Init(ctx));
}
void Compute(OpKernelContext* ctx) override {
const Tensor* debug_name;
const Tensor* serialized;
OpInputList context_dense_keys;
OpInputList context_sparse_keys;
OpInputList context_dense_defaults;
OpInputList feature_list_dense_keys;
OpInputList feature_list_sparse_keys;
const Tensor* feature_list_dense_missing_assumed_empty;
OP_REQUIRES_OK(ctx, ctx->input("debug_name", &debug_name));
OP_REQUIRES_OK(ctx, ctx->input("serialized", &serialized));
OP_REQUIRES_OK(ctx, ctx->input("feature_list_dense_missing_assumed_empty",
&feature_list_dense_missing_assumed_empty));
OP_REQUIRES_OK(ctx,
ctx->input_list("context_dense_keys", &context_dense_keys));
OP_REQUIRES_OK(ctx, ctx->input_list("feature_list_dense_keys",
&feature_list_dense_keys));
OP_REQUIRES_OK(
ctx, ctx->input_list("context_sparse_keys", &context_sparse_keys));
OP_REQUIRES_OK(ctx, ctx->input_list("feature_list_sparse_keys",
&feature_list_sparse_keys));
OP_REQUIRES_OK(ctx, ctx->input_list("context_dense_defaults",
&context_dense_defaults));
std::vector<string> context_dense_keys_t(attrs_.num_context_dense);
std::vector<string> context_sparse_keys_t(attrs_.num_context_sparse);
std::vector<string> feature_list_dense_keys_t(
attrs_.num_feature_list_dense);
std::vector<string> feature_list_sparse_keys_t(
attrs_.num_feature_list_sparse);
absl::call_once(
flag_, [&context_dense_keys_t, &context_sparse_keys_t,
&feature_list_dense_keys_t, &feature_list_sparse_keys_t]() {
metrics::RecordParseDenseFeature(context_dense_keys_t.size() +
feature_list_dense_keys_t.size());
metrics::RecordParseSparseFeature(context_sparse_keys_t.size() +
feature_list_sparse_keys_t.size());
});
std::unordered_set<string> feature_list_dense_missing_assumed_empty_set;
CHECK_EQ(context_dense_keys.size(), attrs_.num_context_dense);
CHECK_EQ(context_sparse_keys.size(), attrs_.num_context_sparse);
CHECK_EQ(feature_list_dense_keys.size(), attrs_.num_feature_list_dense);
CHECK_EQ(feature_list_sparse_keys.size(), attrs_.num_feature_list_sparse);
for (int di = 0; di < attrs_.num_context_dense; ++di) {
OP_REQUIRES(ctx,
TensorShapeUtils::IsScalar(context_dense_keys[di].shape()),
errors::InvalidArgument(
"Expected context_dense_keys[", di,
"] to be a scalar, got shape: ",
context_dense_keys[di].shape().DebugString()));
context_dense_keys_t[di] = context_dense_keys[di].scalar<tstring>()();
}
for (int di = 0; di < attrs_.num_context_sparse; ++di) {
OP_REQUIRES(ctx,
TensorShapeUtils::IsScalar(context_sparse_keys[di].shape()),
errors::InvalidArgument(
"Expected context_sparse_keys[", di,
"] to be a scalar, got shape: ",
context_sparse_keys[di].shape().DebugString()));
context_sparse_keys_t[di] = context_sparse_keys[di].scalar<tstring>()();
}
for (int di = 0; di < attrs_.num_feature_list_dense; ++di) {
OP_REQUIRES(
ctx, TensorShapeUtils::IsScalar(feature_list_dense_keys[di].shape()),
errors::InvalidArgument(
"Expected feature_list_dense_keys[", di,
"] to be a scalar, got shape: ",
feature_list_dense_keys[di].shape().DebugString()));
feature_list_dense_keys_t[di] =
feature_list_dense_keys[di].scalar<tstring>()();
}
for (int di = 0; di < attrs_.num_feature_list_sparse; ++di) {
OP_REQUIRES(
ctx, TensorShapeUtils::IsScalar(feature_list_sparse_keys[di].shape()),
errors::InvalidArgument(
"Expected feature_list_sparse_keys[", di,
"] to be a scalar, got shape: ",
feature_list_sparse_keys[di].shape().DebugString()));
feature_list_sparse_keys_t[di] =
feature_list_sparse_keys[di].scalar<tstring>()();
}
OP_REQUIRES(
ctx,
TensorShapeUtils::IsVector(
feature_list_dense_missing_assumed_empty->shape()),
errors::InvalidArgument(
"Expected feature_list_dense_missing_assumed_empty ",
"to be a vector, got shape: ",
feature_list_dense_missing_assumed_empty->shape().DebugString()));
auto feature_list_dense_missing_assumped_empty_t =
feature_list_dense_missing_assumed_empty->vec<tstring>();
for (int de = 0;
de < feature_list_dense_missing_assumed_empty->NumElements(); ++de) {
feature_list_dense_missing_assumed_empty_set.insert(
feature_list_dense_missing_assumped_empty_t(de));
}
bool has_debug_name = (debug_name->NumElements() > 0);
if (has_debug_name) {
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(debug_name->shape()),
errors::InvalidArgument(
"Expected debug_name to be a scalar, got shape: ",
debug_name->shape().DebugString()));
}
auto debug_name_t = debug_name->scalar<tstring>();
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(serialized->shape()),
errors::InvalidArgument(
"Expected serialized to be a scalar, got shape: ",
serialized->shape().DebugString()));
OP_REQUIRES(ctx, context_dense_defaults.size() == attrs_.num_context_dense,
errors::InvalidArgument("Expected len(context_dense_defaults) "
"== len(context_dense_keys) but got: ",
context_dense_defaults.size(), " vs. ",
attrs_.num_context_dense));
std::vector<bool> required(attrs_.num_context_dense);
for (int d = 0; d < attrs_.num_context_dense; ++d) {
const Tensor& def_value = context_dense_defaults[d];
required[d] = (def_value.NumElements() == 0); // No default provided.
if (def_value.NumElements() > 0) {
OP_REQUIRES(ctx, def_value.shape() == attrs_.context_dense_shapes[d],
errors::InvalidArgument(
"def_value[", d,
"].shape() == ", def_value.shape().DebugString(),
" != context_dense_shapes_[", d,
"] == ", attrs_.context_dense_shapes[d].DebugString()));
OP_REQUIRES(
ctx, def_value.dtype() == attrs_.context_dense_types[d],
errors::InvalidArgument(
"context_dense_defaults[", d, "].dtype() == ",
DataTypeString(def_value.dtype()), " != context_dense_types_[",
d, "] == ", DataTypeString(attrs_.context_dense_types[d])));
}
}
auto serialized_t = serialized->scalar<tstring>();
OpOutputList context_sparse_indices;
OpOutputList context_sparse_values;
OpOutputList context_sparse_shapes;
OpOutputList context_dense_values;
OpOutputList feature_list_sparse_indices;
OpOutputList feature_list_sparse_values;
OpOutputList feature_list_sparse_shapes;
OpOutputList feature_list_dense_values;
OP_REQUIRES_OK(ctx, ctx->output_list("context_sparse_indices",
&context_sparse_indices));
OP_REQUIRES_OK(
ctx, ctx->output_list("context_sparse_values", &context_sparse_values));
OP_REQUIRES_OK(
ctx, ctx->output_list("context_sparse_shapes", &context_sparse_shapes));
OP_REQUIRES_OK(
ctx, ctx->output_list("context_dense_values", &context_dense_values));
OP_REQUIRES_OK(ctx, ctx->output_list("context_sparse_indices",
&context_sparse_indices));
OP_REQUIRES_OK(ctx, ctx->output_list("feature_list_sparse_indices",
&feature_list_sparse_indices));
OP_REQUIRES_OK(ctx, ctx->output_list("feature_list_sparse_values",
&feature_list_sparse_values));
OP_REQUIRES_OK(ctx, ctx->output_list("feature_list_sparse_shapes",
&feature_list_sparse_shapes));
OP_REQUIRES_OK(ctx, ctx->output_list("feature_list_dense_values",
&feature_list_dense_values));
// Allocate the SequenceExample on an arena. Provides better memory locality
// and greatly speeds up destruction.
protobuf::ArenaOptions options;
// We have some hint of what the final proto size will be based on the size
// of the serialized bytes- use this to set a custom allocation strategy.
// Note that the default allocation strategy is quite conservative (min
// block size of 256 bytes, and a max of 8 kilobytes).
const size_t block_size = serialized_t().size() * 1.1;
options.start_block_size = std::max(options.start_block_size, block_size);
options.max_block_size = std::max(options.max_block_size, block_size);
protobuf::Arena arena(options);
auto& ex = *protobuf::Arena::CreateMessage<SequenceExample>(&arena);
OP_REQUIRES(
ctx, ParseProtoUnlimited(&ex, serialized_t()),
errors::InvalidArgument("Could not parse example input, value: '",
serialized_t(), "'"));
const tstring& name = (has_debug_name) ? debug_name_t() : "<unknown>";
const Features& context = ex.context();
const auto& context_dict = context.feature();
// Context Dense -----------------------------------------------------------
// Preallocate context_dense_values, since we know their sizes
for (int d = 0; d < attrs_.num_context_dense; ++d) {
TensorShape out_shape;
for (const int dim : attrs_.context_dense_shapes[d].dim_sizes())
OP_REQUIRES_OK(ctx, out_shape.AddDimWithStatus(dim));
Tensor* out = nullptr;
OP_REQUIRES_OK(ctx, context_dense_values.allocate(d, out_shape, &out));
}
for (int d = 0; d < attrs_.num_context_dense; ++d) {
const tstring& key = context_dense_keys_t[d];
const DataType& dtype = attrs_.context_dense_types[d];
const TensorShape& shape = attrs_.context_dense_shapes[d];
const auto& feature_found = context_dict.find(key);
OP_REQUIRES(
ctx, (feature_found != context_dict.end()) || !required[d],
errors::InvalidArgument("Name: ", name, ", Context feature '", key,
"' is required but could not be found."));
if (feature_found != context_dict.end()) {