-
Notifications
You must be signed in to change notification settings - Fork 74k
/
map_stage_op.cc
804 lines (642 loc) · 25.9 KB
/
map_stage_op.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
/* Copyright 2017 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 <cstddef>
#include <functional>
#include <map>
#include <mutex>
#include <numeric>
#include <unordered_map>
#include <vector>
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/gtl/optional.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/thread_annotations.h"
namespace tensorflow {
namespace {
// Partial Ordering Comparator for Tensor keys containing scalar int64's
struct KeyTensorLess {
bool operator()(const Tensor& lhs, const Tensor& rhs) const {
return std::less<int64_t>{}(lhs.scalar<int64_t>()(),
rhs.scalar<int64_t>()());
}
};
// Key Equality operator for Tensor keys containing scalar int64's
struct KeyTensorEqual {
bool operator()(const Tensor& lhs, const Tensor& rhs) const {
return std::equal_to<int64_t>{}(lhs.scalar<int64_t>()(),
rhs.scalar<int64_t>()());
}
};
// Hash for Tensor keys containing scalar int64's
struct KeyTensorHash {
std::size_t operator()(const Tensor& key) const {
return std::hash<int64_t>{}(key.scalar<int64_t>()());
}
};
// Primary template.
template <bool Ordered, typename Data>
struct MapTraits;
// Partial specialization for ordered.
template <typename Data>
struct MapTraits<true, Data> {
using KeyType = Tensor;
using DataType = Data;
using MapType = std::map<KeyType, Data, KeyTensorLess>;
};
// Partial specialization for unordered.
template <typename Data>
struct MapTraits<false, Data> {
using KeyType = Tensor;
using DataType = Data;
using MapType =
std::unordered_map<KeyType, Data, KeyTensorHash, KeyTensorEqual>;
};
// Wrapper around map/unordered_map.
template <bool Ordered>
class StagingMap : public ResourceBase {
public:
// Public typedefs
using Tuple = std::vector<Tensor>;
using OptionalTensor = gtl::optional<Tensor>;
using OptionalTuple = std::vector<OptionalTensor>;
using MapType = typename MapTraits<Ordered, OptionalTuple>::MapType;
using KeyType = typename MapTraits<Ordered, OptionalTuple>::KeyType;
using IncompleteType = typename MapTraits<false, OptionalTuple>::MapType;
private:
// Private variables
DataTypeVector dtypes_ TF_GUARDED_BY(mu_);
std::size_t capacity_ TF_GUARDED_BY(mu_);
std::size_t memory_limit_ TF_GUARDED_BY(mu_);
std::size_t current_bytes_ TF_GUARDED_BY(mu_);
tensorflow::mutex mu_;
tensorflow::condition_variable not_empty_;
tensorflow::condition_variable full_;
IncompleteType incomplete_ TF_GUARDED_BY(mu_);
MapType map_ TF_GUARDED_BY(mu_);
private:
// private methods
// If map is configured for bounded capacity, notify
// waiting inserters that space is now available
void notify_inserters_if_bounded() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
if (has_capacity() || has_memory_limit()) {
// Notify all inserters. The removal of an element
// may make memory available for many inserters
// to insert new elements
full_.notify_all();
}
}
// Notify all removers waiting to extract values
// that data is now available
void notify_removers() {
// Notify all removers. This is because they are
// waiting for specific keys to appear in the map
// so we don't know which one to wake up.
not_empty_.notify_all();
}
bool has_capacity() const TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
return capacity_ > 0;
}
bool has_memory_limit() const TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
return memory_limit_ > 0;
}
bool would_exceed_memory_limit(std::size_t bytes) const
TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
return has_memory_limit() && bytes + current_bytes_ > memory_limit_;
}
bool is_capacity_full() const TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
return has_capacity() && map_.size() >= capacity_;
}
// Get number of bytes in the tuple
std::size_t get_tuple_bytes(const Tuple& tuple) {
return std::accumulate(tuple.begin(), tuple.end(),
static_cast<std::size_t>(0),
[](const std::size_t& lhs, const Tensor& rhs) {
return lhs + rhs.TotalBytes();
});
}
// Get number of bytes in the incomplete tuple
std::size_t get_tuple_bytes(const OptionalTuple& tuple) {
return std::accumulate(
tuple.begin(), tuple.end(), static_cast<std::size_t>(0),
[](const std::size_t& lhs, const OptionalTensor& rhs) {
return (lhs + rhs.has_value()) ? rhs.value().TotalBytes() : 0;
});
}
// Check that the index is within bounds
Status check_index(const Tensor& key, std::size_t index)
TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
if (index >= dtypes_.size()) {
return Status(errors::InvalidArgument(
"Index '", index, "' for key '", key.scalar<int64_t>()(),
"' was out of bounds '", dtypes_.size(), "'."));
}
return OkStatus();
}
Status copy_or_move_tensors(OptionalTuple* map_tuple, const Tensor& key,
const Tensor& indices, Tuple* output,
bool copy = false)
TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
auto findices = indices.flat<int>();
// Return values at specified indices
for (std::size_t i = 0; i < findices.dimension(0); ++i) {
std::size_t index = findices(i);
TF_RETURN_IF_ERROR(check_index(key, index));
// Insist on a value present at the specified index
if (!(*map_tuple)[index].has_value()) {
return Status(errors::InvalidArgument(
"Tensor at index '", index, "' for key '", key.scalar<int64_t>()(),
"' has already been removed."));
}
// Copy the contained tensor and
// remove from the OptionalTuple
output->push_back((*map_tuple)[index].value());
// Clear out the entry if we're not copying (moving)
if (!copy) {
(*map_tuple)[index].reset();
}
}
return OkStatus();
}
// Check that the optional value at the specified index
// is uninitialized
Status check_index_uninitialized(const Tensor& key, std::size_t index,
const OptionalTuple& tuple)
TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
if (tuple[index].has_value()) {
return errors::InvalidArgument("The tensor for index '", index,
"' for key '", key.scalar<int64_t>()(),
"' was already initialized '",
dtypes_.size(), "'.");
}
return OkStatus();
}
// Check that the indices are strictly ordered
Status check_index_ordering(const Tensor& indices) {
if (indices.NumElements() == 0) {
return errors::InvalidArgument("Indices are empty");
}
auto findices = indices.flat<int>();
for (std::size_t i = 0; i < findices.dimension(0) - 1; ++i) {
if (findices(i) < findices(i + 1)) {
continue;
}
return errors::InvalidArgument("Indices are not strictly ordered");
}
return OkStatus();
}
// Check bytes are within memory limits memory limits
Status check_memory_limit(std::size_t bytes)
TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
if (has_memory_limit() && bytes > memory_limit_) {
return errors::ResourceExhausted(
"Attempted to insert tensors with combined size of '", bytes,
"' bytes into Staging Area with a memory limit of '", memory_limit_,
"'.");
}
return OkStatus();
}
// Insert incomplete data into the Barrier
Status put_incomplete(const KeyType& key, const Tensor& indices,
OptionalTuple* tuple, tensorflow::mutex_lock* lock)
TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
auto findices = indices.flat<int>();
// Search for the key in our incomplete set
auto it = incomplete_.find(key);
// Check that the tuple fits within the memory limit
std::size_t tuple_bytes = get_tuple_bytes(*tuple);
TF_RETURN_IF_ERROR(check_memory_limit(tuple_bytes));
// Wait until we don't exceed the memory limit
while (would_exceed_memory_limit(tuple_bytes)) {
full_.wait(*lock);
}
// This key isn't present in the incomplete set
// Create OptionalTuple and insert
if (it == incomplete_.end()) {
OptionalTuple empty(dtypes_.size());
// Initialize empty tuple with given dta
for (std::size_t i = 0; i < findices.dimension(0); ++i) {
std::size_t index = findices(i);
TF_RETURN_IF_ERROR(check_index(key, index));
// Assign tuple at this index
empty[index] = std::move((*tuple)[i]);
}
// Insert into incomplete map
incomplete_.insert({key, std::move(empty)});
// Increment size
current_bytes_ += tuple_bytes;
}
// Found an entry in the incomplete index
// Update with given data and insert complete entries
// into the main map
else {
// Reference existing incomplete tuple
OptionalTuple& present = it->second;
// Assign given data
for (std::size_t i = 0; i < findices.dimension(0); ++i) {
std::size_t index = findices(i);
TF_RETURN_IF_ERROR(check_index(key, index));
TF_RETURN_IF_ERROR(check_index_uninitialized(key, index, present));
// Assign tuple at this index
present[index] = std::move((*tuple)[i]);
}
// Increment size
current_bytes_ += tuple_bytes;
// Do we have values at all tuple elements?
bool complete =
std::all_of(present.begin(), present.end(),
[](const OptionalTensor& v) { return v.has_value(); });
// If so, put the tuple in the actual map
if (complete) {
OptionalTuple insert_tuple = std::move(it->second);
// Remove from incomplete
incomplete_.erase(it);
TF_RETURN_IF_ERROR(put_complete(key, &insert_tuple));
}
}
return OkStatus();
}
// Does the insertion into the actual staging area
Status put_complete(const KeyType& key, OptionalTuple* tuple)
TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
// Insert key and tuples into the map
map_.insert({key, std::move(*tuple)});
notify_removers();
return OkStatus();
}
public:
// public methods
explicit StagingMap(const DataTypeVector& dtypes, std::size_t capacity,
std::size_t memory_limit)
: dtypes_(dtypes),
capacity_(capacity),
memory_limit_(memory_limit),
current_bytes_(0) {}
Status put(KeyType* key, const Tensor* indices, OptionalTuple* tuple) {
tensorflow::mutex_lock lock(mu_);
// Sanity check the indices
TF_RETURN_IF_ERROR(check_index_ordering(*indices));
// Handle incomplete inserts
if (indices->NumElements() != dtypes_.size()) {
return put_incomplete(*key, *indices, tuple, &lock);
}
std::size_t tuple_bytes = get_tuple_bytes(*tuple);
// Check that tuple_bytes fits within the memory limit
TF_RETURN_IF_ERROR(check_memory_limit(tuple_bytes));
// Wait until there's space for insertion.
while (would_exceed_memory_limit(tuple_bytes) || is_capacity_full()) {
full_.wait(lock);
}
// Do the put operation
TF_RETURN_IF_ERROR(put_complete(*key, tuple));
// Update the current size
current_bytes_ += tuple_bytes;
return OkStatus();
}
Status get(const KeyType* key, const Tensor* indices, Tuple* tuple) {
tensorflow::mutex_lock lock(mu_);
// Sanity check the indices
TF_RETURN_IF_ERROR(check_index_ordering(*indices));
typename MapType::iterator it;
// Wait until the element with the requested key is present
while ((it = map_.find(*key)) == map_.end()) {
not_empty_.wait(lock);
}
TF_RETURN_IF_ERROR(
copy_or_move_tensors(&it->second, *key, *indices, tuple, true));
// Update bytes in the Staging Area
current_bytes_ -= get_tuple_bytes(*tuple);
return OkStatus();
}
Status pop(const KeyType* key, const Tensor* indices, Tuple* tuple) {
tensorflow::mutex_lock lock(mu_);
// Sanity check the indices
TF_RETURN_IF_ERROR(check_index_ordering(*indices));
typename MapType::iterator it;
// Wait until the element with the requested key is present
while ((it = map_.find(*key)) == map_.end()) {
not_empty_.wait(lock);
}
TF_RETURN_IF_ERROR(
copy_or_move_tensors(&it->second, *key, *indices, tuple));
// Remove entry if all the values have been consumed
if (!std::any_of(
it->second.begin(), it->second.end(),
[](const OptionalTensor& tensor) { return tensor.has_value(); })) {
map_.erase(it);
}
// Update bytes in the Staging Area
current_bytes_ -= get_tuple_bytes(*tuple);
notify_inserters_if_bounded();
return OkStatus();
}
Status popitem(KeyType* key, const Tensor* indices, Tuple* tuple) {
tensorflow::mutex_lock lock(mu_);
// Sanity check the indices
TF_RETURN_IF_ERROR(check_index_ordering(*indices));
// Wait until map is not empty
while (this->map_.empty()) {
not_empty_.wait(lock);
}
// Move from the first element and erase it
auto it = map_.begin();
TF_RETURN_IF_ERROR(
copy_or_move_tensors(&it->second, *key, *indices, tuple));
*key = it->first;
// Remove entry if all the values have been consumed
if (!std::any_of(
it->second.begin(), it->second.end(),
[](const OptionalTensor& tensor) { return tensor.has_value(); })) {
map_.erase(it);
}
// Update bytes in the Staging Area
current_bytes_ -= get_tuple_bytes(*tuple);
notify_inserters_if_bounded();
return OkStatus();
}
Status clear() {
tensorflow::mutex_lock lock(mu_);
map_.clear();
incomplete_.clear();
current_bytes_ = 0;
notify_inserters_if_bounded();
return OkStatus();
}
std::size_t incomplete_size() {
tensorflow::mutex_lock lock(mu_);
return incomplete_.size();
}
std::size_t size() {
tensorflow::mutex_lock lock(mu_);
return map_.size();
}
string DebugString() const override { return "StagingMap"; }
};
template <bool Ordered>
Status GetStagingMap(OpKernelContext* ctx, const NodeDef& ndef,
StagingMap<Ordered>** map) {
auto rm = ctx->resource_manager();
ContainerInfo cinfo;
// Lambda for creating the Staging Area
auto create_fn = [&ndef](StagingMap<Ordered>** ret) -> Status {
DataTypeVector dtypes;
int64_t capacity;
int64_t memory_limit;
TF_RETURN_IF_ERROR(GetNodeAttr(ndef, "dtypes", &dtypes));
TF_RETURN_IF_ERROR(GetNodeAttr(ndef, "capacity", &capacity));
TF_RETURN_IF_ERROR(GetNodeAttr(ndef, "memory_limit", &memory_limit));
*ret = new StagingMap<Ordered>(dtypes, capacity, memory_limit);
return OkStatus();
};
TF_RETURN_IF_ERROR(cinfo.Init(rm, ndef, true /* use name() */));
TF_RETURN_IF_ERROR(rm->LookupOrCreate<StagingMap<Ordered>>(
cinfo.container(), cinfo.name(), map, create_fn));
return OkStatus();
}
template <bool Ordered>
class MapStageOp : public OpKernel {
public:
explicit MapStageOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
StagingMap<Ordered>* map = nullptr;
OP_REQUIRES_OK(ctx, GetStagingMap(ctx, def(), &map));
core::ScopedUnref scope(map);
typename StagingMap<Ordered>::OptionalTuple tuple;
const Tensor* key_tensor;
const Tensor* indices_tensor;
OpInputList values_tensor;
OP_REQUIRES_OK(ctx, ctx->input("key", &key_tensor));
OP_REQUIRES_OK(ctx, ctx->input("indices", &indices_tensor));
OP_REQUIRES_OK(ctx, ctx->input_list("values", &values_tensor));
OP_REQUIRES(ctx, key_tensor->NumElements() > 0,
errors::InvalidArgument("key must not be empty"));
OP_REQUIRES(ctx, key_tensor->NumElements() == 1,
errors::InvalidArgument(
"key must be an int64 scalar, got tensor with shape: ",
key_tensor->shape()));
// Create copy for insertion into Staging Area
Tensor key(*key_tensor);
// Create the tuple to store
for (std::size_t i = 0; i < values_tensor.size(); ++i) {
tuple.push_back(values_tensor[i]);
}
// Store the tuple in the map
OP_REQUIRES_OK(ctx, map->put(&key, indices_tensor, &tuple));
}
};
REGISTER_KERNEL_BUILDER(Name("MapStage").Device(DEVICE_CPU), MapStageOp<false>);
REGISTER_KERNEL_BUILDER(Name("OrderedMapStage").Device(DEVICE_CPU),
MapStageOp<true>);
REGISTER_KERNEL_BUILDER(Name("MapStage")
.HostMemory("key")
.HostMemory("indices")
.Device(DEVICE_DEFAULT),
MapStageOp<false>);
REGISTER_KERNEL_BUILDER(Name("OrderedMapStage")
.HostMemory("key")
.HostMemory("indices")
.Device(DEVICE_DEFAULT),
MapStageOp<true>);
template <bool Ordered>
class MapUnstageOp : public OpKernel {
public:
explicit MapUnstageOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
// Using this op in such a way that it blocks forever
// is an error. As such cancellation is not handled.
void Compute(OpKernelContext* ctx) override {
StagingMap<Ordered>* map = nullptr;
OP_REQUIRES_OK(ctx, GetStagingMap(ctx, def(), &map));
core::ScopedUnref scope(map);
typename StagingMap<Ordered>::Tuple tuple;
const Tensor* key_tensor;
const Tensor* indices_tensor;
OP_REQUIRES_OK(ctx, ctx->input("key", &key_tensor));
OP_REQUIRES_OK(ctx, ctx->input("indices", &indices_tensor));
OP_REQUIRES_OK(ctx, map->pop(key_tensor, indices_tensor, &tuple));
OP_REQUIRES(
ctx, tuple.size() == indices_tensor->NumElements(),
errors::InvalidArgument("output/indices size mismatch: ", tuple.size(),
" vs. ", indices_tensor->NumElements()));
for (std::size_t i = 0; i < tuple.size(); ++i) {
ctx->set_output(i, tuple[i]);
}
}
};
REGISTER_KERNEL_BUILDER(Name("MapUnstage").Device(DEVICE_CPU),
MapUnstageOp<false>);
REGISTER_KERNEL_BUILDER(Name("OrderedMapUnstage").Device(DEVICE_CPU),
MapUnstageOp<true>);
REGISTER_KERNEL_BUILDER(Name("MapUnstage")
.HostMemory("key")
.HostMemory("indices")
.Device(DEVICE_DEFAULT),
MapUnstageOp<false>);
REGISTER_KERNEL_BUILDER(Name("OrderedMapUnstage")
.HostMemory("key")
.HostMemory("indices")
.Device(DEVICE_DEFAULT),
MapUnstageOp<true>);
template <bool Ordered>
class MapPeekOp : public OpKernel {
public:
explicit MapPeekOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
// Using this op in such a way that it blocks forever
// is an error. As such cancellation is not handled.
void Compute(OpKernelContext* ctx) override {
StagingMap<Ordered>* map = nullptr;
OP_REQUIRES_OK(ctx, GetStagingMap(ctx, def(), &map));
core::ScopedUnref scope(map);
typename StagingMap<Ordered>::Tuple tuple;
const Tensor* key_tensor;
const Tensor* indices_tensor;
OP_REQUIRES_OK(ctx, ctx->input("key", &key_tensor));
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(key_tensor->shape()),
errors::InvalidArgument("key must be an int64 scalar: ",
key_tensor->shape().DebugString()));
OP_REQUIRES_OK(ctx, ctx->input("indices", &indices_tensor));
OP_REQUIRES_OK(ctx, map->get(key_tensor, indices_tensor, &tuple));
OP_REQUIRES(
ctx, tuple.size() == indices_tensor->NumElements(),
errors::InvalidArgument("output/indices size mismatch: ", tuple.size(),
" vs. ", indices_tensor->NumElements()));
for (std::size_t i = 0; i < tuple.size(); ++i) {
ctx->set_output(i, tuple[i]);
}
}
};
REGISTER_KERNEL_BUILDER(Name("MapPeek").Device(DEVICE_CPU), MapPeekOp<false>);
REGISTER_KERNEL_BUILDER(Name("OrderedMapPeek").Device(DEVICE_CPU),
MapPeekOp<true>);
REGISTER_KERNEL_BUILDER(
Name("MapPeek").HostMemory("key").HostMemory("indices").Device(
DEVICE_DEFAULT),
MapPeekOp<false>);
REGISTER_KERNEL_BUILDER(Name("OrderedMapPeek")
.HostMemory("key")
.HostMemory("indices")
.Device(DEVICE_DEFAULT),
MapPeekOp<true>);
template <bool Ordered>
class MapUnstageNoKeyOp : public OpKernel {
public:
explicit MapUnstageNoKeyOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
// Using this op in such a way that it blocks forever
// is an error. As such cancellation is not handled.
void Compute(OpKernelContext* ctx) override {
StagingMap<Ordered>* map = nullptr;
OP_REQUIRES_OK(ctx, GetStagingMap(ctx, def(), &map));
core::ScopedUnref scope(map);
// Pop a random (key, value) off the map
typename StagingMap<Ordered>::KeyType key;
typename StagingMap<Ordered>::Tuple tuple;
const Tensor* indices_tensor;
OP_REQUIRES_OK(ctx, ctx->input("indices", &indices_tensor));
OP_REQUIRES_OK(ctx, map->popitem(&key, indices_tensor, &tuple));
// Allocate a key tensor and assign the key as the first output
ctx->set_output(0, key);
// Set the rest of the outputs to the tuple Tensors
OP_REQUIRES(
ctx, tuple.size() == indices_tensor->NumElements(),
errors::InvalidArgument("output/indices size mismatch: ", tuple.size(),
" vs. ", indices_tensor->NumElements()));
for (std::size_t i = 0; i < tuple.size(); ++i) {
ctx->set_output(i + 1, tuple[i]);
}
}
};
REGISTER_KERNEL_BUILDER(Name("MapUnstageNoKey").Device(DEVICE_CPU),
MapUnstageNoKeyOp<false>);
REGISTER_KERNEL_BUILDER(Name("OrderedMapUnstageNoKey").Device(DEVICE_CPU),
MapUnstageNoKeyOp<true>);
REGISTER_KERNEL_BUILDER(Name("MapUnstageNoKey")
.HostMemory("key")
.HostMemory("indices")
.Device(DEVICE_DEFAULT),
MapUnstageNoKeyOp<false>);
REGISTER_KERNEL_BUILDER(Name("OrderedMapUnstageNoKey")
.HostMemory("key")
.HostMemory("indices")
.Device(DEVICE_DEFAULT),
MapUnstageNoKeyOp<true>);
template <bool Ordered>
class MapSizeOp : public OpKernel {
public:
explicit MapSizeOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
StagingMap<Ordered>* map = nullptr;
OP_REQUIRES_OK(ctx, GetStagingMap(ctx, def(), &map));
core::ScopedUnref scope(map);
// Allocate size output tensor
Tensor* size = nullptr;
OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &size));
// Set it to the actual size
size->scalar<int32>().setConstant(map->size());
}
};
REGISTER_KERNEL_BUILDER(Name("MapSize").Device(DEVICE_CPU), MapSizeOp<false>);
REGISTER_KERNEL_BUILDER(Name("OrderedMapSize").Device(DEVICE_CPU),
MapSizeOp<true>);
REGISTER_KERNEL_BUILDER(
Name("MapSize").Device(DEVICE_DEFAULT).HostMemory("size"),
MapSizeOp<false>);
REGISTER_KERNEL_BUILDER(
Name("OrderedMapSize").Device(DEVICE_DEFAULT).HostMemory("size"),
MapSizeOp<true>);
template <bool Ordered>
class MapIncompleteSizeOp : public OpKernel {
public:
explicit MapIncompleteSizeOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
StagingMap<Ordered>* map = nullptr;
OP_REQUIRES_OK(ctx, GetStagingMap(ctx, def(), &map));
core::ScopedUnref scope(map);
// Allocate size output tensor
Tensor* size = nullptr;
OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &size));
// Set it to the actual size
size->scalar<int32>().setConstant(map->incomplete_size());
}
};
REGISTER_KERNEL_BUILDER(Name("MapIncompleteSize").Device(DEVICE_CPU),
MapIncompleteSizeOp<false>);
REGISTER_KERNEL_BUILDER(Name("OrderedMapIncompleteSize").Device(DEVICE_CPU),
MapIncompleteSizeOp<true>);
REGISTER_KERNEL_BUILDER(
Name("MapIncompleteSize").Device(DEVICE_DEFAULT).HostMemory("size"),
MapIncompleteSizeOp<false>);
REGISTER_KERNEL_BUILDER(
Name("OrderedMapIncompleteSize").Device(DEVICE_DEFAULT).HostMemory("size"),
MapIncompleteSizeOp<true>);
template <bool Ordered>
class MapClearOp : public OpKernel {
public:
explicit MapClearOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
StagingMap<Ordered>* map = nullptr;
OP_REQUIRES_OK(ctx, GetStagingMap(ctx, def(), &map));
core::ScopedUnref scope(map);
OP_REQUIRES_OK(ctx, map->clear());
}
};
REGISTER_KERNEL_BUILDER(Name("MapClear").Device(DEVICE_CPU), MapClearOp<false>);
REGISTER_KERNEL_BUILDER(Name("OrderedMapClear").Device(DEVICE_CPU),
MapClearOp<true>);
REGISTER_KERNEL_BUILDER(Name("MapClear").Device(DEVICE_DEFAULT),
MapClearOp<false>);
REGISTER_KERNEL_BUILDER(Name("OrderedMapClear").Device(DEVICE_DEFAULT),
MapClearOp<true>);
} // namespace
} // namespace tensorflow