/
util.cc
1252 lines (1118 loc) · 42.1 KB
/
util.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 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 "tensorflow/python/util/util.h"
#include <Python.h>
#include <functional>
#include <memory>
#include <unordered_map>
#include <vector>
#include "absl/memory/memory.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/python/lib/core/safe_pyobject_ptr.h"
namespace tensorflow {
namespace swig {
namespace {
constexpr const char ITERATOR_OPS_MODULE[] =
"tensorflow.python.data.ops.iterator_ops";
constexpr const char COMPOSITE_TENSOR_MODULE[] =
"tensorflow.python.framework.composite_tensor";
constexpr const char INDEXED_SLICES_MODULE[] =
"tensorflow.python.framework.indexed_slices";
constexpr const char OPS_MODULE[] =
"tensorflow.python.framework.ops";
constexpr const char SPARSE_TENSOR_MODULE[] =
"tensorflow.python.framework.sparse_tensor";
constexpr const char TENSOR_MODULE[] =
"tensorflow.python.framework.tensor";
constexpr const char TYPE_SPEC_MODULE[] =
"tensorflow.python.framework.type_spec";
constexpr const char RESOURCE_VAR_MODULE[] =
"tensorflow.python.ops.resource_variable_ops";
constexpr const char VARIABLES_MODULE[] =
"tensorflow.python.ops.variables";
constexpr const char CORE_TYPES_MODULE[] =
"tensorflow.python.types.core";
string PyObjectToString(PyObject* o);
} // namespace
std::unordered_map<string, PyObject*>* RegisteredPyObjectMap() {
static auto* m = new std::unordered_map<string, PyObject*>();
return m;
}
PyObject* GetRegisteredPyObject(const string& name) {
const auto* m = RegisteredPyObjectMap();
auto it = m->find(name);
if (it == m->end()) {
PyErr_SetString(PyExc_TypeError,
tensorflow::strings::StrCat("No object with name ", name,
" has been registered.")
.c_str());
return nullptr;
}
return it->second;
}
PyObject* RegisterPyObject(PyObject* name, PyObject* value) {
string key;
if (PyBytes_Check(name)) {
key = PyBytes_AsString(name);
#if PY_MAJOR_VERSION >= 3
} else if (PyUnicode_Check(name)) {
key = PyUnicode_AsUTF8(name);
#endif
} else {
PyErr_SetString(PyExc_TypeError, tensorflow::strings::StrCat(
"Expected name to be a str, got",
PyObjectToString(name))
.c_str());
return nullptr;
}
auto* m = RegisteredPyObjectMap();
if (m->find(key) != m->end()) {
PyErr_SetString(PyExc_TypeError, tensorflow::strings::StrCat(
"Value already registered for ", key)
.c_str());
return nullptr;
}
Py_INCREF(value);
m->emplace(key, value);
Py_RETURN_NONE;
}
namespace {
const int kMaxItemsInCache = 1024;
bool IsString(PyObject* o) {
return PyBytes_Check(o) ||
#if PY_MAJOR_VERSION < 3
PyString_Check(o) ||
#endif
PyUnicode_Check(o);
}
// Equivalent to Python's 'o.__class__.__name__'
// Note that '__class__' attribute is set only in new-style classes.
// A lot of tensorflow code uses __class__ without checks, so it seems like
// we only support new-style classes.
StringPiece GetClassName(PyObject* o) {
// __class__ is equivalent to type() for new style classes.
// type() is equivalent to PyObject_Type()
// (https://docs.python.org/3.5/c-api/object.html#c.PyObject_Type)
// PyObject_Type() is equivalent to o->ob_type except for Py_INCREF, which
// we don't need here.
PyTypeObject* type = o->ob_type;
// __name__ is the value of `tp_name` after the last '.'
// (https://docs.python.org/2/c-api/typeobj.html#c.PyTypeObject.tp_name)
StringPiece name(type->tp_name);
size_t pos = name.rfind('.');
if (pos != StringPiece::npos) {
name.remove_prefix(pos + 1);
}
return name;
}
string PyObjectToString(PyObject* o) {
if (o == nullptr) {
return "<null object>";
}
PyObject* str = PyObject_Str(o);
if (str) {
#if PY_MAJOR_VERSION < 3
string s(PyString_AS_STRING(str));
#else
string s(PyUnicode_AsUTF8(str));
#endif
Py_DECREF(str);
return tensorflow::strings::StrCat("type=", GetClassName(o), " str=", s);
} else {
return "<failed to execute str() on object>";
}
}
// FIXME(b/280464631): Consider remove this class.
class CachedTypeCheck {
public:
explicit CachedTypeCheck(std::function<int(PyObject*)> ternary_predicate)
: ternary_predicate_(std::move(ternary_predicate)) {}
~CachedTypeCheck() {
mutex_lock l(type_to_sequence_map_mu_);
for (const auto& pair : type_to_sequence_map_) {
Py_DECREF(pair.first);
}
}
// Caches successful executions of the one-argument (PyObject*) callable
// "ternary_predicate" based on the type of "o". -1 from the callable
// indicates an unsuccessful check (not cached), 0 indicates that "o"'s type
// does not match the predicate, and 1 indicates that it does. Used to avoid
// calling back into Python for expensive isinstance checks.
int CachedLookup(PyObject* o) {
// Try not to return to Python - see if the type has already been seen
// before.
auto* type = Py_TYPE(o);
{
tf_shared_lock l(type_to_sequence_map_mu_);
auto it = type_to_sequence_map_.find(type);
if (it != type_to_sequence_map_.end()) {
return it->second;
}
}
int check_result = ternary_predicate_(o);
if (check_result == -1) {
return -1; // Type check error, not cached.
}
// NOTE: This is never decref'd as long as the object lives, which is likely
// forever, but we don't want the type to get deleted as long as it is in
// the map. This should not be too much of a leak, as there should only be a
// relatively small number of types in the map, and an even smaller number
// that are eligible for decref. As a precaution, we limit the size of the
// map to 1024.
{
mutex_lock l(type_to_sequence_map_mu_);
if (type_to_sequence_map_.size() < kMaxItemsInCache) {
Py_INCREF(type);
auto insert_result = type_to_sequence_map_.insert({type, check_result});
if (!insert_result.second) {
// The type was added to the cache by a concurrent thread after we
// looked it up above.
Py_DECREF(type);
}
}
}
return check_result;
}
private:
std::function<int(PyObject*)> ternary_predicate_;
mutex type_to_sequence_map_mu_;
std::unordered_map<PyTypeObject*, bool> type_to_sequence_map_
TF_GUARDED_BY(type_to_sequence_map_mu_);
};
PyObject* ImportTypeFromModule(const char* module_name, const char* type_name) {
static PyObject* given_type;
given_type = [module_name, type_name]() {
PyObject* module = PyImport_ImportModule(module_name);
PyObject* attr =
module ? PyObject_GetAttrString(module, type_name) : nullptr;
if (attr == nullptr) {
PyErr_WriteUnraisable(nullptr);
PyErr_Clear();
}
if (module) Py_DECREF(module);
return attr;
}();
return given_type;
}
// Returns true if 'obj' is an instance of 'type_name'
// Returns false otherwise.
int IsInstanceOfGivenType(PyObject* obj, const char* module_name,
const char* type_name) {
PyObject* given_type = ImportTypeFromModule(module_name, type_name);
if (TF_PREDICT_FALSE(given_type == nullptr)) {
return false;
}
return PyObject_IsInstance(obj, given_type);
}
// Returns 1 if `o` is considered a mapping for the purposes of Flatten().
// Returns 0 otherwise.
// Returns -1 if an error occurred.
int IsMappingHelper(PyObject* o) {
static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) {
return IsInstanceOfGivenType(to_check, "collections.abc", "Mapping");
});
if (PyDict_Check(o)) return true;
return check_cache->CachedLookup(o);
}
// Returns 1 if `o` is considered a mutable mapping for the purposes of
// Flatten(). Returns 0 otherwise. Returns -1 if an error occurred.
int IsMutableMappingHelper(PyObject* o) {
static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) {
return IsInstanceOfGivenType(to_check, "collections.abc", "MutableMapping");
});
if (PyDict_Check(o)) return true;
return check_cache->CachedLookup(o);
}
// Returns 1 if `o` is considered a mapping view for the purposes of Flatten().
// Returns 0 otherwise.
// Returns -1 if an error occurred.
int IsMappingViewHelper(PyObject* o) {
static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) {
return IsInstanceOfGivenType(to_check, "collections.abc", "MappingView");
});
return check_cache->CachedLookup(o);
}
// Returns 1 if `o` is considered an object proxy
// Returns 0 otherwise.
// Returns -1 if an error occurred.
int IsObjectProxy(PyObject* o) {
static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) {
return IsInstanceOfGivenType(to_check, "wrapt", "ObjectProxy");
});
return check_cache->CachedLookup(o);
}
// Returns 1 if `o` is an instance of attrs-decorated class.
// Returns 0 otherwise.
int IsAttrsHelper(PyObject* o) {
static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) {
Safe_PyObjectPtr cls(PyObject_GetAttrString(to_check, "__class__"));
if (cls) {
return PyObject_HasAttrString(cls.get(), "__attrs_attrs__");
}
// PyObject_GetAttrString returns null on error
PyErr_Clear();
return 0;
});
return check_cache->CachedLookup(o);
}
// Returns 1 if `o` is an instance that implements the custom nest protocol.
// Returns 0 otherwise.
int IsCustomNestProtocolDefined(PyObject* o) {
static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) {
Safe_PyObjectPtr cls(PyObject_GetAttrString(to_check, "__class__"));
if (cls) {
return PyObject_HasAttrString(cls.get(), "__tf_flatten__") &
PyObject_HasAttrString(cls.get(), "__tf_unflatten__");
}
// PyObject_GetAttrString returns null on error
PyErr_Clear();
return 0;
});
return check_cache->CachedLookup(o);
}
// Returns 1 if `o` is an object of type IndexedSlices.
// Returns 0 otherwise.
// Returns -1 if an error occurred.
int IsIndexedSlicesHelper(PyObject* o) {
static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) {
return IsInstanceOfGivenType(to_check, INDEXED_SLICES_MODULE,
"IndexedSlices");
});
return check_cache->CachedLookup(o);
}
// Returns 1 if `o` is a Tensor.
// Returns 0 otherwise.
// Returns -1 if an error occurred.
int IsTensorHelper(PyObject* o) {
static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) {
return IsInstanceOfGivenType(to_check, TENSOR_MODULE, "Tensor");
});
return check_cache->CachedLookup(o);
}
// Returns 1 if `o` is a TensorSpec.
// Returns 0 otherwise.
// Returns -1 if an error occurred.
int IsTensorSpecHelper(PyObject* o) {
static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) {
return IsInstanceOfGivenType(to_check, TENSOR_MODULE, "TensorSpec");
});
return check_cache->CachedLookup(o);
}
// Returns 1 if `o` is an EagerTensor.
// Returns 0 otherwise.
// Returns -1 if an error occurred.
int IsEagerTensorHelper(PyObject* o) {
static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) {
return IsInstanceOfGivenType(to_check, OPS_MODULE, "EagerTensor");
});
return check_cache->CachedLookup(o);
}
int IsTensorProtocolHelper(PyObject* o) {
static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) {
return IsInstanceOfGivenType(to_check, CORE_TYPES_MODULE, "TensorProtocol");
});
return check_cache->CachedLookup(o);
}
int IsCoreTypeValueHelper(PyObject* o) {
static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) {
return IsInstanceOfGivenType(to_check, CORE_TYPES_MODULE, "Value");
});
return check_cache->CachedLookup(o);
}
// Returns 1 if `o` is a ResourceVariable.
// Returns 0 otherwise.
// Returns -1 if an error occurred.
int IsResourceVariableHelper(PyObject* o) {
static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) {
return IsInstanceOfGivenType(to_check, RESOURCE_VAR_MODULE,
"ResourceVariable");
});
return check_cache->CachedLookup(o);
}
// Returns 1 if `o` is a OwnedIterator.
// Returns 0 otherwise.
// Returns -1 if an error occurred.
int IsOwnedIteratorHelper(PyObject* o) {
static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) {
return IsInstanceOfGivenType(to_check, ITERATOR_OPS_MODULE,
"OwnedIterator");
});
return check_cache->CachedLookup(o);
}
// Returns 1 if `o` is a ResourceVariable.
// Returns 0 otherwise.
// Returns -1 if an error occurred.
int IsVariableHelper(PyObject* o) {
static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) {
return IsInstanceOfGivenType(to_check, VARIABLES_MODULE, "Variable");
});
return check_cache->CachedLookup(o);
}
// Returns 1 if `o` is considered a sequence for the purposes of Flatten().
// Returns 0 otherwise.
// Returns -1 if an error occurred.
int IsNestedHelper(PyObject* o) {
// We treat dicts and other mappings as special cases of sequences.
if (IsMappingHelper(o)) return true;
if (IsMappingViewHelper(o)) return true;
if (IsAttrsHelper(o)) return true;
if (IsCustomNestProtocolDefined(o)) return true;
static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) {
int is_instance =
IsInstanceOfGivenType(to_check, "collections.abc", "Sequence");
// Don't cache a failed is_instance check.
if (is_instance == -1) return -1;
return static_cast<int>(is_instance != 0 && !IsString(to_check));
});
return check_cache->CachedLookup(o);
}
// Returns 1 if `o`'s class has a `__tf_dispatch__` attribute.
// Returns 0 otherwise.
int IsDispatchableHelper(PyObject* o) {
static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) {
return PyObject_HasAttrString(
reinterpret_cast<PyObject*>(to_check->ob_type), "__tf_dispatch__");
});
return check_cache->CachedLookup(o);
}
// ValueIterator interface
class ValueIterator {
public:
virtual ~ValueIterator() {}
virtual Safe_PyObjectPtr next() = 0;
bool valid() const { return is_valid_; }
protected:
void invalidate() { is_valid_ = false; }
private:
bool is_valid_ = true;
};
using ValueIteratorPtr = std::unique_ptr<ValueIterator>;
// Iterate through dictionaries in a deterministic order by sorting the
// keys. Notice this means that we ignore the original order of
// `OrderedDict` instances. This is intentional, to avoid potential
// bugs caused by mixing ordered and plain dicts (e.g., flattening
// a dict but using a corresponding `OrderedDict` to pack it back).
class DictValueIterator : public ValueIterator {
public:
explicit DictValueIterator(PyObject* dict)
: dict_(dict), keys_(PyDict_Keys(dict)) {
if (PyList_Sort(keys_.get()) == -1) {
invalidate();
} else {
iter_.reset(PyObject_GetIter(keys_.get()));
}
}
Safe_PyObjectPtr next() override {
Safe_PyObjectPtr result;
Safe_PyObjectPtr key(PyIter_Next(iter_.get()));
if (key) {
// PyDict_GetItem returns a borrowed reference.
PyObject* elem = PyDict_GetItem(dict_, key.get());
if (elem) {
Py_INCREF(elem);
result.reset(elem);
} else {
PyErr_SetString(PyExc_RuntimeError,
"Dictionary was modified during iteration over it");
}
}
return result;
}
private:
PyObject* dict_;
Safe_PyObjectPtr keys_;
Safe_PyObjectPtr iter_;
};
// Iterate over mapping objects by sorting the keys first
class MappingValueIterator : public ValueIterator {
public:
explicit MappingValueIterator(PyObject* mapping)
: mapping_(mapping), keys_(MappingKeys(mapping)) {
if (!keys_ || PyList_Sort(keys_.get()) == -1) {
invalidate();
} else {
iter_.reset(PyObject_GetIter(keys_.get()));
}
}
Safe_PyObjectPtr next() override {
Safe_PyObjectPtr result;
Safe_PyObjectPtr key(PyIter_Next(iter_.get()));
if (key) {
// Unlike PyDict_GetItem, PyObject_GetItem returns a new reference.
PyObject* elem = PyObject_GetItem(mapping_, key.get());
if (elem) {
result.reset(elem);
} else {
PyErr_SetString(PyExc_RuntimeError,
"Mapping was modified during iteration over it");
}
}
return result;
}
private:
PyObject* mapping_;
Safe_PyObjectPtr keys_;
Safe_PyObjectPtr iter_;
};
// Iterate over a sequence, by index.
class SequenceValueIterator : public ValueIterator {
public:
explicit SequenceValueIterator(PyObject* iterable)
: seq_(PySequence_Fast(iterable, "")),
size_(seq_.get() ? PySequence_Fast_GET_SIZE(seq_.get()) : 0),
index_(0) {}
Safe_PyObjectPtr next() override {
Safe_PyObjectPtr result;
if (index_ < size_) {
// PySequence_Fast_GET_ITEM returns a borrowed reference.
PyObject* elem = PySequence_Fast_GET_ITEM(seq_.get(), index_);
++index_;
if (elem) {
Py_INCREF(elem);
result.reset(elem);
}
}
return result;
}
private:
Safe_PyObjectPtr seq_;
const Py_ssize_t size_;
Py_ssize_t index_;
};
// Iterator that just returns a single python object.
class SingleValueIterator : public ValueIterator {
public:
explicit SingleValueIterator(PyObject* x) : x_(x) { Py_INCREF(x); }
Safe_PyObjectPtr next() override { return std::move(x_); }
private:
Safe_PyObjectPtr x_;
};
// Returns nullptr (to raise an exception) when next() is called. Caller
// should have already called PyErr_SetString.
class ErrorValueIterator : public ValueIterator {
public:
ErrorValueIterator() {}
Safe_PyObjectPtr next() override { return nullptr; }
};
class AttrsValueIterator : public ValueIterator {
public:
explicit AttrsValueIterator(PyObject* nested) : nested_(nested) {
Py_INCREF(nested);
cls_.reset(PyObject_GetAttrString(nested_.get(), "__class__"));
if (cls_) {
attrs_.reset(PyObject_GetAttrString(cls_.get(), "__attrs_attrs__"));
if (attrs_) {
iter_.reset(PyObject_GetIter(attrs_.get()));
}
}
if (!iter_ || PyErr_Occurred()) invalidate();
}
Safe_PyObjectPtr next() override {
Safe_PyObjectPtr result;
Safe_PyObjectPtr item(PyIter_Next(iter_.get()));
if (item) {
Safe_PyObjectPtr name(PyObject_GetAttrString(item.get(), "name"));
result.reset(PyObject_GetAttr(nested_.get(), name.get()));
}
return result;
}
private:
Safe_PyObjectPtr nested_;
Safe_PyObjectPtr cls_;
Safe_PyObjectPtr attrs_;
Safe_PyObjectPtr iter_;
};
class CustomNestedIterator : public ValueIterator {
public:
explicit CustomNestedIterator(PyObject* nested) : nested_(nested) {
Py_INCREF(nested);
flattened_.reset(
PyObject_CallMethod(nested_.get(), "__tf_flatten__", nullptr));
if (flattened_) {
Safe_PyObjectPtr seq = make_safe(PySequence_GetItem(flattened_.get(), 1));
if (seq) {
iter_.reset(PyObject_GetIter(seq.get()));
}
}
if (!iter_ || PyErr_Occurred()) invalidate();
}
Safe_PyObjectPtr next() override {
Safe_PyObjectPtr result(PyIter_Next(iter_.get()));
return result;
}
private:
Safe_PyObjectPtr nested_;
Safe_PyObjectPtr flattened_;
Safe_PyObjectPtr iter_;
};
bool IsSparseTensorValueType(PyObject* o) {
PyObject* sparse_tensor_value_type =
ImportTypeFromModule(SPARSE_TENSOR_MODULE, "SparseTensorValue");
if (TF_PREDICT_FALSE(sparse_tensor_value_type == nullptr)) {
return false;
}
return PyObject_TypeCheck(
o, reinterpret_cast<PyTypeObject*>(sparse_tensor_value_type)) == 1;
}
// Returns 1 if `o` is an instance of CompositeTensor.
// Returns 0 otherwise.
// Returns -1 if an error occurred.
bool IsCompositeTensorHelper(PyObject* o) {
static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) {
// TODO(b/246438937): Remove the ResourceVariable test.
return IsInstanceOfGivenType(to_check, COMPOSITE_TENSOR_MODULE,
"CompositeTensor") &&
!IsResourceVariable(to_check);
});
return check_cache->CachedLookup(o);
}
// Returns 1 if `o` is an instance of TypeSpec, but is not TensorSpec or
// VariableSpec.
// Returns 0 otherwise.
// Returns -1 if an error occurred.
bool IsTypeSpecHelper(PyObject* o) {
static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) {
int is_type_spec =
IsInstanceOfGivenType(to_check, TYPE_SPEC_MODULE, "TypeSpec");
// TODO(b/246438937): Remove the VariableSpec special case.
int is_dense_spec =
(IsInstanceOfGivenType(to_check, TENSOR_MODULE, "TensorSpec") ||
IsInstanceOfGivenType(to_check, RESOURCE_VAR_MODULE, "VariableSpec"));
if ((is_type_spec == -1) || (is_dense_spec == -1)) return -1;
return static_cast<int>(is_type_spec && !is_dense_spec);
});
return check_cache->CachedLookup(o);
}
// Returns 1 if `o` is a (non-string) sequence or CompositeTensor or
// (non-TensorSpec and non-VariableSpec) TypeSpec.
// Returns 0 otherwise.
// Returns -1 if an error occurred.
int IsNestedOrCompositeHelper(PyObject* o) {
int is_nested = IsNestedHelper(o);
int is_composite = IsCompositeTensorHelper(o);
int is_type_spec = IsTypeSpecHelper(o);
if ((is_nested == -1) || (is_composite == -1) || (is_type_spec == -1)) {
return -1;
}
return is_nested || is_composite || is_type_spec;
}
int IsNestedForDataHelper(PyObject* o) {
return IsNestedHelper(o) == 1 && !PyList_Check(o) &&
!IsSparseTensorValueType(o);
}
ValueIteratorPtr GetValueIterator(PyObject* nested) {
if (PyDict_Check(nested)) {
return absl::make_unique<DictValueIterator>(nested);
} else if (IsMappingHelper(nested)) {
return absl::make_unique<MappingValueIterator>(nested);
} else if (IsAttrsHelper(nested)) {
return absl::make_unique<AttrsValueIterator>(nested);
} else if (IsCustomNestProtocolDefined(nested)) {
return std::make_unique<CustomNestedIterator>(nested);
} else {
return absl::make_unique<SequenceValueIterator>(nested);
}
}
// Similar to above, just specialized for the functions in the data package.
ValueIteratorPtr GetValueIteratorForData(PyObject* nested) {
if (PyDict_Check(nested)) {
return absl::make_unique<DictValueIterator>(nested);
} else if (IsMappingHelper(nested)) {
return absl::make_unique<MappingValueIterator>(nested);
} else if (IsAttrsHelper(nested)) {
return absl::make_unique<AttrsValueIterator>(nested);
} else if (IsSparseTensorValueType(nested)) {
return absl::make_unique<SingleValueIterator>(nested);
} else if (IsCustomNestProtocolDefined(nested)) {
return std::make_unique<CustomNestedIterator>(nested);
} else {
return absl::make_unique<SequenceValueIterator>(nested);
}
}
// Similar to GetValueIterator above, but expands CompositeTensor and TypeSpec.
ValueIteratorPtr GetValueIteratorForComposite(PyObject* nested) {
if (IsCompositeTensor(nested)) {
Safe_PyObjectPtr spec(PyObject_GetAttrString(nested, "_type_spec"));
if (PyErr_Occurred() || !spec) {
return absl::make_unique<ErrorValueIterator>();
}
static char to_components[] = "_to_components";
static char argspec[] = "(O)";
Safe_PyObjectPtr components(
PyObject_CallMethod(spec.get(), to_components, argspec, nested));
if (PyErr_Occurred() || components == nullptr) {
return absl::make_unique<ErrorValueIterator>();
}
return absl::make_unique<SingleValueIterator>(components.get());
}
if (IsTypeSpec(nested)) {
Safe_PyObjectPtr specs(PyObject_GetAttrString(nested, "_component_specs"));
if (PyErr_Occurred() || specs == nullptr) {
return absl::make_unique<ErrorValueIterator>();
}
return absl::make_unique<SingleValueIterator>(specs.get());
}
return GetValueIterator(nested);
}
bool FlattenHelper(
PyObject* nested, PyObject* list,
const std::function<int(PyObject*)>& is_nested_helper,
const std::function<ValueIteratorPtr(PyObject*)>& value_iterator_getter) {
// if nested is not a sequence, append itself and exit
int is_nested = is_nested_helper(nested);
if (is_nested == -1) return false;
if (!is_nested) {
return PyList_Append(list, nested) != -1;
}
ValueIteratorPtr iter = value_iterator_getter(nested);
if (!iter->valid()) return false;
for (Safe_PyObjectPtr item = iter->next(); item; item = iter->next()) {
if (Py_EnterRecursiveCall(" in flatten")) {
return false;
}
const bool success = FlattenHelper(item.get(), list, is_nested_helper,
value_iterator_getter);
Py_LeaveRecursiveCall();
if (!success) {
return false;
}
}
return true;
}
// Sets error using keys of 'dict1' and 'dict2'.
// 'dict1' and 'dict2' are assumed to be Python dictionaries.
void SetDifferentKeysError(PyObject* dict1, PyObject* dict2, string* error_msg,
bool* is_type_error) {
Safe_PyObjectPtr k1(MappingKeys(dict1));
if (PyErr_Occurred() || k1.get() == nullptr) {
*error_msg =
("The two dictionaries don't have the same set of keys. Failed to "
"fetch keys.");
return;
}
Safe_PyObjectPtr k2(MappingKeys(dict2));
if (PyErr_Occurred() || k2.get() == nullptr) {
*error_msg =
("The two dictionaries don't have the same set of keys. Failed to "
"fetch keys.");
return;
}
*is_type_error = false;
*error_msg = tensorflow::strings::StrCat(
"The two dictionaries don't have the same set of keys. "
"First structure has keys ",
PyObjectToString(k1.get()), ", while second structure has keys ",
PyObjectToString(k2.get()));
}
// Returns true iff there were no "internal" errors. In other words,
// errors that has nothing to do with structure checking.
// If an "internal" error occurred, the appropriate Python error will be
// set and the caller can propage it directly to the user.
//
// Both `error_msg` and `is_type_error` must be non-null. `error_msg` must
// be empty.
// Leaves `error_msg` empty if structures matched. Else, fills `error_msg`
// with appropriate error and sets `is_type_error` to true iff
// the error to be raised should be TypeError.
bool AssertSameStructureHelper(
PyObject* o1, PyObject* o2, bool check_types, string* error_msg,
bool* is_type_error, const std::function<int(PyObject*)>& is_nested_helper,
const std::function<ValueIteratorPtr(PyObject*)>& value_iterator_getter,
bool check_composite_tensor_type_spec) {
DCHECK(error_msg);
DCHECK(is_type_error);
const bool is_nested1 = is_nested_helper(o1);
const bool is_nested2 = is_nested_helper(o2);
if (PyErr_Occurred()) return false;
if (is_nested1 != is_nested2) {
string seq_str = is_nested1 ? PyObjectToString(o1) : PyObjectToString(o2);
string non_seq_str =
is_nested1 ? PyObjectToString(o2) : PyObjectToString(o1);
*is_type_error = false;
*error_msg = tensorflow::strings::StrCat(
"Substructure \"", seq_str, "\" is a sequence, while substructure \"",
non_seq_str, "\" is not");
return true;
}
// Got to objects that are considered non-sequences. Note that in tf.data
// use case lists and sparse_tensors are not considered sequences. So finished
// checking, structures are the same.
if (!is_nested1) return true;
if (check_types) {
// Treat wrapped tuples as tuples.
tensorflow::Safe_PyObjectPtr o1_wrapped;
if (IsObjectProxy(o1)) {
o1_wrapped.reset(PyObject_GetAttrString(o1, "__wrapped__"));
o1 = o1_wrapped.get();
}
tensorflow::Safe_PyObjectPtr o2_wrapped;
if (IsObjectProxy(o2)) {
o2_wrapped.reset(PyObject_GetAttrString(o2, "__wrapped__"));
o2 = o2_wrapped.get();
}
const PyTypeObject* type1 = o1->ob_type;
const PyTypeObject* type2 = o2->ob_type;
// We treat two different namedtuples with identical name and fields
// as having the same type.
const PyObject* o1_tuple = IsNamedtuple(o1, false);
if (o1_tuple == nullptr) return false;
const PyObject* o2_tuple = IsNamedtuple(o2, false);
if (o2_tuple == nullptr) {
Py_DECREF(o1_tuple);
return false;
}
bool both_tuples = o1_tuple == Py_True && o2_tuple == Py_True;
Py_DECREF(o1_tuple);
Py_DECREF(o2_tuple);
if (both_tuples) {
const PyObject* same_tuples = SameNamedtuples(o1, o2);
if (same_tuples == nullptr) return false;
bool not_same_tuples = same_tuples != Py_True;
Py_DECREF(same_tuples);
if (not_same_tuples) {
*is_type_error = true;
*error_msg = tensorflow::strings::StrCat(
"The two namedtuples don't have the same sequence type. "
"First structure ",
PyObjectToString(o1), " has type ", type1->tp_name,
", while second structure ", PyObjectToString(o2), " has type ",
type2->tp_name);
return true;
}
} else if (type1 != type2
/* If both sequences are list types, don't complain. This allows
one to be a list subclass (e.g. _ListWrapper used for
automatic dependency tracking.) */
&& !(PyList_Check(o1) && PyList_Check(o2))
/* Two mapping types will also compare equal, making _DictWrapper
and dict compare equal. */
&& !(IsMappingHelper(o1) && IsMappingHelper(o2))
/* For CompositeTensor & TypeSpec, we check below. */
&& !(check_composite_tensor_type_spec &&
(IsCompositeTensor(o1) || IsTypeSpec(o1)) &&
(IsCompositeTensor(o2) || IsTypeSpec(o2)))) {
*is_type_error = true;
*error_msg = tensorflow::strings::StrCat(
"The two namedtuples don't have the same sequence type. "
"First structure ",
PyObjectToString(o1), " has type ", type1->tp_name,
", while second structure ", PyObjectToString(o2), " has type ",
type2->tp_name);
return true;
}
if (PyDict_Check(o1) && PyDict_Check(o2)) {
if (PyDict_Size(o1) != PyDict_Size(o2)) {
SetDifferentKeysError(o1, o2, error_msg, is_type_error);
return true;
}
PyObject* key;
Py_ssize_t pos = 0;
while (PyDict_Next(o1, &pos, &key, nullptr)) {
if (PyDict_GetItem(o2, key) == nullptr) {
SetDifferentKeysError(o1, o2, error_msg, is_type_error);
return true;
}
}
} else if (IsMappingHelper(o1)) {
// Fallback for custom mapping types. Instead of using PyDict methods
// which stay in C, we call iter(o1).
if (PyMapping_Size(o1) != PyMapping_Size(o2)) {
SetDifferentKeysError(o1, o2, error_msg, is_type_error);
return true;
}
Safe_PyObjectPtr iter(PyObject_GetIter(o1));
PyObject* key;
while ((key = PyIter_Next(iter.get())) != nullptr) {
if (!PyMapping_HasKey(o2, key)) {
SetDifferentKeysError(o1, o2, error_msg, is_type_error);
Py_DECREF(key);
return true;
}
Py_DECREF(key);
}
}
}
if (check_composite_tensor_type_spec &&
(IsCompositeTensor(o1) || IsCompositeTensor(o2))) {
Safe_PyObjectPtr owned_type_spec_1;
PyObject* type_spec_1 = o1;
if (IsCompositeTensor(o1)) {
owned_type_spec_1.reset(PyObject_GetAttrString(o1, "_type_spec"));
type_spec_1 = owned_type_spec_1.get();
}
Safe_PyObjectPtr owned_type_spec_2;
PyObject* type_spec_2 = o2;
if (IsCompositeTensor(o2)) {
owned_type_spec_2.reset(PyObject_GetAttrString(o2, "_type_spec"));
type_spec_2 = owned_type_spec_2.get();
}
// Two composite tensors are considered to have the same structure if
// they share a type spec that is a supertype of both of them. We do *not*
// use is_subtype_of, since that would prevent us from e.g. using a
// cond statement where the two sides have different shapes.
// TODO(b/206014848): We have to explicitly remove the names.
Safe_PyObjectPtr owned_nameless_type_spec_1(
PyObject_CallMethod(type_spec_1, "_without_tensor_names", nullptr));
Safe_PyObjectPtr owned_nameless_type_spec_2(
PyObject_CallMethod(type_spec_2, "_without_tensor_names", nullptr));
// TODO(b/222123181): Reconsider most_specific_common_supertype usage.
static char compatible_type[] = "most_specific_common_supertype";
static char argspec[] = "([O])";
Safe_PyObjectPtr struct_compatible(
PyObject_CallMethod(owned_nameless_type_spec_1.get(), compatible_type,
argspec, owned_nameless_type_spec_2.get()));
if (PyErr_Occurred()) {
return false;
}
if (struct_compatible.get() == Py_None) {
*is_type_error = false;
*error_msg = tensorflow::strings::StrCat(
"Incompatible CompositeTensor TypeSpecs: ",
PyObjectToString(type_spec_1), " vs. ",
PyObjectToString(type_spec_2));
return true;
}
}
ValueIteratorPtr iter1 = value_iterator_getter(o1);
ValueIteratorPtr iter2 = value_iterator_getter(o2);
if (!iter1->valid() || !iter2->valid()) return false;