-
Notifications
You must be signed in to change notification settings - Fork 74k
/
pywrap_tfe_src.cc
4726 lines (4232 loc) · 167 KB
/
pywrap_tfe_src.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 <atomic>
#include <cstring>
#include <unordered_map>
#include "absl/debugging/leak_check.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_replace.h"
#include "absl/types/variant.h"
#include "tensorflow/c/c_api.h"
#include "tensorflow/c/c_api_internal.h"
#include "tensorflow/c/eager/c_api.h"
#include "tensorflow/c/eager/c_api_internal.h"
#include "tensorflow/c/eager/tape.h"
#include "tensorflow/c/eager/tfe_context_internal.h"
#include "tensorflow/c/eager/tfe_op_internal.h"
#include "tensorflow/c/eager/tfe_tensorhandle_internal.h"
#include "tensorflow/c/tf_status.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/gtl/cleanup.h"
#include "tensorflow/core/lib/gtl/compactptrset.h"
#include "tensorflow/core/lib/gtl/flatmap.h"
#include "tensorflow/core/lib/gtl/flatset.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/platform/casts.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/statusor.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/profiler/lib/traceme.h"
#include "tensorflow/core/util/managed_stack_trace.h"
#include "tensorflow/python/eager/pywrap_gradient_exclusions.h"
#include "tensorflow/python/eager/pywrap_tensor.h"
#include "tensorflow/python/eager/pywrap_tfe.h"
#include "tensorflow/python/lib/core/py_util.h"
#include "tensorflow/python/lib/core/safe_ptr.h"
#include "tensorflow/python/util/stack_trace.h"
#include "tensorflow/python/util/util.h"
using tensorflow::Status;
using tensorflow::string;
using tensorflow::strings::Printf;
namespace {
// NOTE: Items are retrieved from and returned to these unique_ptrs, and they
// act as arenas. This is important if the same thread requests 2 items without
// releasing one.
// The following sequence of events on the same thread will still succeed:
// - GetOp <- Returns existing.
// - GetOp <- Allocates and returns a new pointer.
// - ReleaseOp <- Sets the item in the unique_ptr.
// - ReleaseOp <- Sets the item in the unique_ptr, deleting the old one.
// This occurs when a PyFunc kernel is run. This behavior makes it safe in that
// case, as well as the case where python decides to reuse the underlying
// C++ thread in 2 python threads case.
struct OpDeleter {
void operator()(TFE_Op* op) const { TFE_DeleteOp(op); }
};
thread_local std::unordered_map<TFE_Context*,
std::unique_ptr<TFE_Op, OpDeleter>>
thread_local_eager_operation_map; // NOLINT
thread_local std::unique_ptr<TF_Status> thread_local_tf_status = // NOLINT
nullptr;
std::unique_ptr<TFE_Op, OpDeleter> ReleaseThreadLocalOp(TFE_Context* ctx) {
auto it = thread_local_eager_operation_map.find(ctx);
if (it == thread_local_eager_operation_map.end()) {
return nullptr;
}
return std::move(it->second);
}
TFE_Op* GetOp(TFE_Context* ctx, const char* op_or_function_name,
const char* raw_device_name, TF_Status* status) {
auto op = ReleaseThreadLocalOp(ctx);
if (!op) {
op.reset(tensorflow::wrap(tensorflow::unwrap(ctx)->CreateOperation()));
}
status->status =
tensorflow::unwrap(op.get())->Reset(op_or_function_name, raw_device_name);
if (!status->status.ok()) {
op.reset();
}
return op.release();
}
void ReturnOp(TFE_Context* ctx, TFE_Op* op) {
if (op) {
tensorflow::unwrap(op)->Clear();
thread_local_eager_operation_map[ctx].reset(op);
}
}
TF_Status* ReleaseThreadLocalStatus() {
if (thread_local_tf_status == nullptr) {
return nullptr;
}
return thread_local_tf_status.release();
}
struct InputInfo {
InputInfo(int i, bool is_list) : i(i), is_list(is_list) {}
int i;
bool is_list = false;
};
// Takes in output gradients, returns input gradients.
typedef std::function<PyObject*(PyObject*, const std::vector<int64_t>&)>
PyBackwardFunction;
using AttrToInputsMap =
tensorflow::gtl::FlatMap<string,
tensorflow::gtl::InlinedVector<InputInfo, 4>>;
tensorflow::gtl::FlatMap<string, AttrToInputsMap*>* GetAllAttrToInputsMaps() {
static auto* all_attr_to_input_maps =
new tensorflow::gtl::FlatMap<string, AttrToInputsMap*>;
return all_attr_to_input_maps;
}
// This function doesn't use a lock, since we depend on the GIL directly.
AttrToInputsMap* GetAttrToInputsMapHoldingGIL(const tensorflow::OpDef& op_def) {
#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 4
DCHECK(PyGILState_Check())
<< "This function needs to hold the GIL when called.";
#endif
auto* all_attr_to_input_maps = GetAllAttrToInputsMaps();
auto* output =
tensorflow::gtl::FindPtrOrNull(*all_attr_to_input_maps, op_def.name());
if (output != nullptr) {
return output;
}
std::unique_ptr<AttrToInputsMap> m(new AttrToInputsMap);
// Store a list of InputIndex -> List of corresponding inputs.
for (int i = 0; i < op_def.input_arg_size(); i++) {
if (!op_def.input_arg(i).type_attr().empty()) {
auto it = m->find(op_def.input_arg(i).type_attr());
if (it == m->end()) {
it = m->insert({op_def.input_arg(i).type_attr(), {}}).first;
}
it->second.emplace_back(i, !op_def.input_arg(i).number_attr().empty());
}
}
auto* retval = m.get();
(*all_attr_to_input_maps)[op_def.name()] = m.release();
return retval;
}
// This function doesn't use a lock, since we depend on the GIL directly.
tensorflow::gtl::FlatMap<
string, tensorflow::gtl::FlatMap<string, tensorflow::DataType>*>*
GetAllAttrToDefaultsMaps() {
static auto* all_attr_to_defaults_maps = new tensorflow::gtl::FlatMap<
string, tensorflow::gtl::FlatMap<string, tensorflow::DataType>*>;
return all_attr_to_defaults_maps;
}
tensorflow::gtl::FlatMap<string, tensorflow::DataType>*
GetAttrToDefaultsMapHoldingGIL(const tensorflow::OpDef& op_def) {
#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 4
DCHECK(PyGILState_Check())
<< "This function needs to hold the GIL when called.";
#endif
auto* all_attr_to_defaults_maps = GetAllAttrToDefaultsMaps();
auto* output =
tensorflow::gtl::FindPtrOrNull(*all_attr_to_defaults_maps, op_def.name());
if (output != nullptr) {
return output;
}
auto* new_map = new tensorflow::gtl::FlatMap<string, tensorflow::DataType>;
for (const auto& attr : op_def.attr()) {
if (attr.type() == "type" && attr.has_default_value()) {
new_map->insert({attr.name(), attr.default_value().type()});
}
}
(*all_attr_to_defaults_maps)[op_def.name()] = new_map;
return new_map;
}
struct FastPathOpExecInfo {
TFE_Context* ctx;
const char* device_name;
bool run_callbacks;
bool run_post_exec_callbacks;
bool run_gradient_callback;
// The op name of the main op being executed.
PyObject* name;
// The op type name of the main op being executed.
PyObject* op_name;
PyObject* callbacks;
// All the args passed into the FastPathOpExecInfo.
PyObject* args;
// DTypes can come from another input that has the same attr. So build that
// map.
const AttrToInputsMap* attr_to_inputs_map;
const tensorflow::gtl::FlatMap<string, tensorflow::DataType>* default_dtypes;
tensorflow::gtl::FlatMap<string, tensorflow::DataType> cached_dtypes;
};
#define PARSE_VALUE(fn_name, type, check_fn, parse_fn) \
bool fn_name(const string& key, PyObject* py_value, TF_Status* status, \
type* value) { \
if (check_fn(py_value)) { \
*value = static_cast<type>(parse_fn(py_value)); \
return true; \
} else { \
TF_SetStatus(status, TF_INVALID_ARGUMENT, \
tensorflow::strings::StrCat( \
"Expecting " #type " value for attr ", key, ", got ", \
py_value->ob_type->tp_name) \
.c_str()); \
return false; \
} \
}
#if PY_MAJOR_VERSION >= 3
PARSE_VALUE(ParseIntValue, int, PyLong_Check, PyLong_AsLong)
PARSE_VALUE(ParseInt64Value, int64_t, PyLong_Check, PyLong_AsLongLong)
#else
PARSE_VALUE(ParseIntValue, int, PyInt_Check, PyInt_AsLong)
#endif
PARSE_VALUE(ParseFloatValue, float, PyFloat_Check, PyFloat_AsDouble)
#undef PARSE_VALUE
#if PY_MAJOR_VERSION < 3
bool ParseInt64Value(const string& key, PyObject* py_value, TF_Status* status,
int64_t* value) {
if (py_value == nullptr) {
TF_SetStatus(status, TF_INVALID_ARGUMENT,
tensorflow::strings::StrCat(
"Expecting int or long value for attr ", key, "."))
.c_str();
return false;
}
if (PyInt_Check(py_value)) {
*value = static_cast<int64_t>(PyInt_AsLong(py_value));
return true;
} else if (PyLong_Check(py_value)) {
*value = static_cast<int64_t>(PyLong_AsLong(py_value));
return true;
}
TF_SetStatus(
status, TF_INVALID_ARGUMENT,
tensorflow::strings::StrCat("Expecting int or long value for attr ", key,
", got ", py_value->ob_type->tp_name)
.c_str());
return false;
}
#endif
Py_ssize_t TensorShapeNumDims(PyObject* value) {
const auto size = PySequence_Size(value);
if (size == -1) {
// TensorShape.__len__ raises an error in the scenario where the shape is an
// unknown, which needs to be cleared.
// TODO(nareshmodi): ensure that this is actually a TensorShape.
PyErr_Clear();
}
return size;
}
bool IsInteger(PyObject* py_value) {
#if PY_MAJOR_VERSION >= 3
return PyLong_Check(py_value);
#else
return PyInt_Check(py_value) || PyLong_Check(py_value);
#endif
}
// This function considers a Dimension._value of None to be valid, and sets the
// value to be -1 in that case.
bool ParseDimensionValue(const string& key, PyObject* py_value,
TF_Status* status, int64_t* value) {
if (IsInteger(py_value)) {
return ParseInt64Value(key, py_value, status, value);
}
tensorflow::Safe_PyObjectPtr dimension_value(
PyObject_GetAttrString(py_value, "_value"));
if (dimension_value == nullptr) {
PyErr_Clear();
TF_SetStatus(
status, TF_INVALID_ARGUMENT,
tensorflow::strings::StrCat("Expecting a Dimension for attr ", key,
", got ", py_value->ob_type->tp_name)
.c_str());
return false;
}
if (dimension_value.get() == Py_None) {
*value = -1;
return true;
}
return ParseInt64Value(key, dimension_value.get(), status, value);
}
bool ParseStringValue(const string& key, PyObject* py_value, TF_Status* status,
tensorflow::StringPiece* value) {
if (PyBytes_Check(py_value)) {
Py_ssize_t size = 0;
char* buf = nullptr;
if (PyBytes_AsStringAndSize(py_value, &buf, &size) < 0) return false;
*value = tensorflow::StringPiece(buf, size);
return true;
}
#if PY_MAJOR_VERSION >= 3
if (PyUnicode_Check(py_value)) {
Py_ssize_t size = 0;
const char* buf = PyUnicode_AsUTF8AndSize(py_value, &size);
if (buf == nullptr) return false;
*value = tensorflow::StringPiece(buf, size);
return true;
}
#endif
TF_SetStatus(
status, TF_INVALID_ARGUMENT,
tensorflow::strings::StrCat("Expecting a string value for attr ", key,
", got ", py_value->ob_type->tp_name)
.c_str());
return false;
}
bool ParseBoolValue(const string& key, PyObject* py_value, TF_Status* status,
unsigned char* value) {
*value = PyObject_IsTrue(py_value);
return true;
}
// The passed in py_value is expected to be an object of the python type
// dtypes.DType or an int.
bool ParseTypeValue(const string& key, PyObject* py_value, TF_Status* status,
int* value) {
if (IsInteger(py_value)) {
return ParseIntValue(key, py_value, status, value);
}
tensorflow::Safe_PyObjectPtr py_type_enum(
PyObject_GetAttrString(py_value, "_type_enum"));
if (py_type_enum == nullptr) {
PyErr_Clear();
TF_SetStatus(
status, TF_INVALID_ARGUMENT,
tensorflow::strings::StrCat("Expecting a DType.dtype for attr ", key,
", got ", py_value->ob_type->tp_name)
.c_str());
return false;
}
return ParseIntValue(key, py_type_enum.get(), status, value);
}
bool SetOpAttrList(TFE_Context* ctx, TFE_Op* op, const char* key,
PyObject* py_list, TF_AttrType type,
tensorflow::gtl::FlatMap<string, int64_t>* attr_list_sizes,
TF_Status* status) {
if (!PySequence_Check(py_list)) {
TF_SetStatus(
status, TF_INVALID_ARGUMENT,
tensorflow::strings::StrCat("Expecting sequence value for attr ", key,
", got ", py_list->ob_type->tp_name)
.c_str());
return false;
}
const int num_values = PySequence_Size(py_list);
if (attr_list_sizes != nullptr) (*attr_list_sizes)[key] = num_values;
#define PARSE_LIST(c_type, parse_fn) \
std::unique_ptr<c_type[]> values(new c_type[num_values]); \
for (int i = 0; i < num_values; ++i) { \
tensorflow::Safe_PyObjectPtr py_value(PySequence_ITEM(py_list, i)); \
if (py_value == nullptr) { \
TF_SetStatus(status, TF_INVALID_ARGUMENT, \
tensorflow::strings::StrCat( \
"Expecting sequence of " #c_type " for attr ", key, \
", got ", py_list->ob_type->tp_name) \
.c_str()); \
return false; \
} else if (!parse_fn(key, py_value.get(), status, &values[i])) { \
return false; \
} \
}
if (type == TF_ATTR_STRING) {
std::unique_ptr<const void*[]> values(new const void*[num_values]);
std::unique_ptr<size_t[]> lengths(new size_t[num_values]);
for (int i = 0; i < num_values; ++i) {
tensorflow::StringPiece value;
tensorflow::Safe_PyObjectPtr py_value(PySequence_ITEM(py_list, i));
if (!ParseStringValue(key, py_value.get(), status, &value)) return false;
values[i] = value.data();
lengths[i] = value.size();
}
TFE_OpSetAttrStringList(op, key, values.get(), lengths.get(), num_values);
} else if (type == TF_ATTR_INT) {
PARSE_LIST(int64_t, ParseInt64Value);
TFE_OpSetAttrIntList(op, key, values.get(), num_values);
} else if (type == TF_ATTR_FLOAT) {
PARSE_LIST(float, ParseFloatValue);
TFE_OpSetAttrFloatList(op, key, values.get(), num_values);
} else if (type == TF_ATTR_BOOL) {
PARSE_LIST(unsigned char, ParseBoolValue);
TFE_OpSetAttrBoolList(op, key, values.get(), num_values);
} else if (type == TF_ATTR_TYPE) {
PARSE_LIST(int, ParseTypeValue);
TFE_OpSetAttrTypeList(op, key,
reinterpret_cast<const TF_DataType*>(values.get()),
num_values);
} else if (type == TF_ATTR_SHAPE) {
// Make one pass through the input counting the total number of
// dims across all the input lists.
int total_dims = 0;
for (int i = 0; i < num_values; ++i) {
tensorflow::Safe_PyObjectPtr py_value(PySequence_ITEM(py_list, i));
if (py_value.get() != Py_None) {
if (!PySequence_Check(py_value.get())) {
TF_SetStatus(
status, TF_INVALID_ARGUMENT,
tensorflow::strings::StrCat(
"Expecting None or sequence value for element", i,
" of attr ", key, ", got ", py_value->ob_type->tp_name)
.c_str());
return false;
}
const auto size = TensorShapeNumDims(py_value.get());
if (size >= 0) {
total_dims += size;
}
}
}
// Allocate a buffer that can fit all of the dims together.
std::unique_ptr<int64_t[]> buffer(new int64_t[total_dims]);
// Copy the input dims into the buffer and set dims to point to
// the start of each list's dims.
std::unique_ptr<const int64_t*[]> dims(new const int64_t*[num_values]);
std::unique_ptr<int[]> num_dims(new int[num_values]);
int64_t* offset = buffer.get();
for (int i = 0; i < num_values; ++i) {
tensorflow::Safe_PyObjectPtr py_value(PySequence_ITEM(py_list, i));
if (py_value.get() == Py_None) {
dims[i] = nullptr;
num_dims[i] = -1;
} else {
const auto size = TensorShapeNumDims(py_value.get());
if (size == -1) {
dims[i] = nullptr;
num_dims[i] = -1;
continue;
}
dims[i] = offset;
num_dims[i] = size;
for (int j = 0; j < size; ++j) {
tensorflow::Safe_PyObjectPtr inner_py_value(
PySequence_ITEM(py_value.get(), j));
if (inner_py_value.get() == Py_None) {
*offset = -1;
} else if (!ParseDimensionValue(key, inner_py_value.get(), status,
offset)) {
return false;
}
++offset;
}
}
}
TFE_OpSetAttrShapeList(op, key, dims.get(), num_dims.get(), num_values,
status);
if (!status->status.ok()) return false;
} else if (type == TF_ATTR_FUNC) {
std::unique_ptr<const TFE_Op*[]> funcs(new const TFE_Op*[num_values]);
for (int i = 0; i < num_values; ++i) {
tensorflow::Safe_PyObjectPtr py_value(PySequence_ITEM(py_list, i));
// Allow:
// (1) String function name, OR
// (2) A Python object with a .name attribute
// (A crude test for being a
// tensorflow.python.framework.function._DefinedFunction)
// (which is what the various "defun" or "Defun" decorators do).
// And in the future also allow an object that can encapsulate
// the function name and its attribute values.
tensorflow::StringPiece func_name;
if (!ParseStringValue(key, py_value.get(), status, &func_name)) {
PyObject* name_attr = PyObject_GetAttrString(py_value.get(), "name");
if (name_attr == nullptr ||
!ParseStringValue(key, name_attr, status, &func_name)) {
TF_SetStatus(
status, TF_INVALID_ARGUMENT,
tensorflow::strings::StrCat(
"unable to set function value attribute from a ",
py_value.get()->ob_type->tp_name,
" object. If you think this is an error, please file an "
"issue at "
"https://github.com/tensorflow/tensorflow/issues/new")
.c_str());
return false;
}
}
funcs[i] = TFE_NewOp(ctx, func_name.data(), status);
if (!status->status.ok()) return false;
}
TFE_OpSetAttrFunctionList(op, key, funcs.get(), num_values);
if (!status->status.ok()) return false;
} else {
TF_SetStatus(status, TF_UNIMPLEMENTED,
tensorflow::strings::StrCat("Attr ", key,
" has unhandled list type ", type)
.c_str());
return false;
}
#undef PARSE_LIST
return true;
}
TFE_Op* GetFunc(TFE_Context* ctx, const tensorflow::NameAttrList& func,
TF_Status* status) {
TFE_Op* func_op = TFE_NewOp(ctx, func.name().data(), status);
for (const auto& attr : func.attr()) {
if (!status->status.ok()) return nullptr;
SetOpAttrValueScalar(ctx, func_op, attr.second, attr.first.data(), status);
if (!status->status.ok()) return nullptr;
}
return func_op;
}
void SetOpAttrListDefault(
TFE_Context* ctx, TFE_Op* op, const tensorflow::OpDef::AttrDef& attr,
const char* key, TF_AttrType type,
tensorflow::gtl::FlatMap<string, int64_t>* attr_list_sizes,
TF_Status* status) {
if (type == TF_ATTR_STRING) {
int num_values = attr.default_value().list().s_size();
std::unique_ptr<const void*[]> values(new const void*[num_values]);
std::unique_ptr<size_t[]> lengths(new size_t[num_values]);
(*attr_list_sizes)[key] = num_values;
for (int i = 0; i < num_values; i++) {
const string& v = attr.default_value().list().s(i);
values[i] = v.data();
lengths[i] = v.size();
}
TFE_OpSetAttrStringList(op, key, values.get(), lengths.get(), num_values);
} else if (type == TF_ATTR_INT) {
int num_values = attr.default_value().list().i_size();
std::unique_ptr<int64_t[]> values(new int64_t[num_values]);
(*attr_list_sizes)[key] = num_values;
for (int i = 0; i < num_values; i++) {
values[i] = attr.default_value().list().i(i);
}
TFE_OpSetAttrIntList(op, key, values.get(), num_values);
} else if (type == TF_ATTR_FLOAT) {
int num_values = attr.default_value().list().f_size();
std::unique_ptr<float[]> values(new float[num_values]);
(*attr_list_sizes)[key] = num_values;
for (int i = 0; i < num_values; i++) {
values[i] = attr.default_value().list().f(i);
}
TFE_OpSetAttrFloatList(op, key, values.get(), num_values);
} else if (type == TF_ATTR_BOOL) {
int num_values = attr.default_value().list().b_size();
std::unique_ptr<unsigned char[]> values(new unsigned char[num_values]);
(*attr_list_sizes)[key] = num_values;
for (int i = 0; i < num_values; i++) {
values[i] = attr.default_value().list().b(i);
}
TFE_OpSetAttrBoolList(op, key, values.get(), num_values);
} else if (type == TF_ATTR_TYPE) {
int num_values = attr.default_value().list().type_size();
std::unique_ptr<int[]> values(new int[num_values]);
(*attr_list_sizes)[key] = num_values;
for (int i = 0; i < num_values; i++) {
values[i] = attr.default_value().list().type(i);
}
TFE_OpSetAttrTypeList(op, key,
reinterpret_cast<const TF_DataType*>(values.get()),
attr.default_value().list().type_size());
} else if (type == TF_ATTR_SHAPE) {
int num_values = attr.default_value().list().shape_size();
(*attr_list_sizes)[key] = num_values;
int total_dims = 0;
for (int i = 0; i < num_values; ++i) {
if (!attr.default_value().list().shape(i).unknown_rank()) {
total_dims += attr.default_value().list().shape(i).dim_size();
}
}
// Allocate a buffer that can fit all of the dims together.
std::unique_ptr<int64_t[]> buffer(new int64_t[total_dims]);
// Copy the input dims into the buffer and set dims to point to
// the start of each list's dims.
std::unique_ptr<const int64_t*[]> dims(new const int64_t*[num_values]);
std::unique_ptr<int[]> num_dims(new int[num_values]);
int64_t* offset = buffer.get();
for (int i = 0; i < num_values; ++i) {
const auto& shape = attr.default_value().list().shape(i);
if (shape.unknown_rank()) {
dims[i] = nullptr;
num_dims[i] = -1;
} else {
for (int j = 0; j < shape.dim_size(); j++) {
*offset = shape.dim(j).size();
++offset;
}
}
}
TFE_OpSetAttrShapeList(op, key, dims.get(), num_dims.get(), num_values,
status);
} else if (type == TF_ATTR_FUNC) {
int num_values = attr.default_value().list().func_size();
(*attr_list_sizes)[key] = num_values;
std::unique_ptr<const TFE_Op*[]> funcs(new const TFE_Op*[num_values]);
for (int i = 0; i < num_values; i++) {
funcs[i] = GetFunc(ctx, attr.default_value().list().func(i), status);
}
TFE_OpSetAttrFunctionList(op, key, funcs.get(), num_values);
} else {
TF_SetStatus(status, TF_UNIMPLEMENTED,
"Lists of tensors are not yet implemented for default valued "
"attributes for an operation.");
}
}
bool SetOpAttrScalar(TFE_Context* ctx, TFE_Op* op, const char* key,
PyObject* py_value, TF_AttrType type,
tensorflow::gtl::FlatMap<string, int64_t>* attr_list_sizes,
TF_Status* status) {
if (type == TF_ATTR_STRING) {
tensorflow::StringPiece value;
if (!ParseStringValue(key, py_value, status, &value)) return false;
TFE_OpSetAttrString(op, key, value.data(), value.size());
} else if (type == TF_ATTR_INT) {
int64_t value;
if (!ParseInt64Value(key, py_value, status, &value)) return false;
TFE_OpSetAttrInt(op, key, value);
// attr_list_sizes is set for all int attributes (since at this point we are
// not aware if that attribute might be used to calculate the size of an
// output list or not).
if (attr_list_sizes != nullptr) (*attr_list_sizes)[key] = value;
} else if (type == TF_ATTR_FLOAT) {
float value;
if (!ParseFloatValue(key, py_value, status, &value)) return false;
TFE_OpSetAttrFloat(op, key, value);
} else if (type == TF_ATTR_BOOL) {
unsigned char value;
if (!ParseBoolValue(key, py_value, status, &value)) return false;
TFE_OpSetAttrBool(op, key, value);
} else if (type == TF_ATTR_TYPE) {
int value;
if (!ParseTypeValue(key, py_value, status, &value)) return false;
TFE_OpSetAttrType(op, key, static_cast<TF_DataType>(value));
} else if (type == TF_ATTR_SHAPE) {
if (py_value == Py_None) {
TFE_OpSetAttrShape(op, key, nullptr, -1, status);
} else {
if (!PySequence_Check(py_value)) {
TF_SetStatus(status, TF_INVALID_ARGUMENT,
tensorflow::strings::StrCat(
"Expecting None or sequence value for attr", key,
", got ", py_value->ob_type->tp_name)
.c_str());
return false;
}
const auto num_dims = TensorShapeNumDims(py_value);
if (num_dims == -1) {
TFE_OpSetAttrShape(op, key, nullptr, -1, status);
return true;
}
std::unique_ptr<int64_t[]> dims(new int64_t[num_dims]);
for (int i = 0; i < num_dims; ++i) {
tensorflow::Safe_PyObjectPtr inner_py_value(
PySequence_ITEM(py_value, i));
// If an error is generated when iterating through object, we can
// sometimes get a nullptr.
if (inner_py_value.get() == Py_None) {
dims[i] = -1;
} else if (inner_py_value.get() == nullptr ||
!ParseDimensionValue(key, inner_py_value.get(), status,
&dims[i])) {
return false;
}
}
TFE_OpSetAttrShape(op, key, dims.get(), num_dims, status);
}
if (!status->status.ok()) return false;
} else if (type == TF_ATTR_FUNC) {
// Allow:
// (1) String function name, OR
// (2) A Python object with a .name attribute
// (A crude test for being a
// tensorflow.python.framework.function._DefinedFunction)
// (which is what the various "defun" or "Defun" decorators do).
// And in the future also allow an object that can encapsulate
// the function name and its attribute values.
tensorflow::StringPiece func_name;
if (!ParseStringValue(key, py_value, status, &func_name)) {
PyObject* name_attr = PyObject_GetAttrString(py_value, "name");
if (name_attr == nullptr ||
!ParseStringValue(key, name_attr, status, &func_name)) {
TF_SetStatus(
status, TF_INVALID_ARGUMENT,
tensorflow::strings::StrCat(
"unable to set function value attribute from a ",
py_value->ob_type->tp_name,
" object. If you think this is an error, please file an issue "
"at https://github.com/tensorflow/tensorflow/issues/new")
.c_str());
return false;
}
}
TF_SetStatus(status, TF_OK, "");
TFE_OpSetAttrFunctionName(op, key, func_name.data(), func_name.size());
} else {
TF_SetStatus(
status, TF_UNIMPLEMENTED,
tensorflow::strings::StrCat("Attr ", key, " has unhandled type ", type)
.c_str());
return false;
}
return true;
}
void SetOpAttrScalarDefault(
TFE_Context* ctx, TFE_Op* op, const tensorflow::AttrValue& default_value,
const char* attr_name,
tensorflow::gtl::FlatMap<string, int64_t>* attr_list_sizes,
TF_Status* status) {
SetOpAttrValueScalar(ctx, op, default_value, attr_name, status);
if (default_value.value_case() == tensorflow::AttrValue::kI) {
(*attr_list_sizes)[attr_name] = default_value.i();
}
}
// start_index is the index at which the Tuple/List attrs will start getting
// processed.
void SetOpAttrs(TFE_Context* ctx, TFE_Op* op, PyObject* attrs, int start_index,
TF_Status* out_status) {
if (attrs == Py_None) return;
Py_ssize_t len = PyTuple_GET_SIZE(attrs) - start_index;
if ((len & 1) != 0) {
TF_SetStatus(out_status, TF_INVALID_ARGUMENT,
"Expecting attrs tuple to have even length.");
return;
}
// Parse attrs
for (Py_ssize_t i = 0; i < len; i += 2) {
PyObject* py_key = PyTuple_GET_ITEM(attrs, start_index + i);
PyObject* py_value = PyTuple_GET_ITEM(attrs, start_index + i + 1);
#if PY_MAJOR_VERSION >= 3
const char* key = PyBytes_Check(py_key) ? PyBytes_AsString(py_key)
: PyUnicode_AsUTF8(py_key);
#else
const char* key = PyBytes_AsString(py_key);
#endif
unsigned char is_list = 0;
const TF_AttrType type = TFE_OpGetAttrType(op, key, &is_list, out_status);
if (!out_status->status.ok()) return;
if (is_list != 0) {
if (!SetOpAttrList(ctx, op, key, py_value, type, nullptr, out_status))
return;
} else {
if (!SetOpAttrScalar(ctx, op, key, py_value, type, nullptr, out_status))
return;
}
}
}
// This function will set the op attrs required. If an attr has the value of
// None, then it will read the AttrDef to get the default value and set that
// instead. Any failure in this function will simply fall back to the slow
// path.
void SetOpAttrWithDefaults(
TFE_Context* ctx, TFE_Op* op, const tensorflow::OpDef::AttrDef& attr,
const char* attr_name, PyObject* attr_value,
tensorflow::gtl::FlatMap<string, int64_t>* attr_list_sizes,
TF_Status* status) {
unsigned char is_list = 0;
const TF_AttrType type = TFE_OpGetAttrType(op, attr_name, &is_list, status);
if (!status->status.ok()) return;
if (attr_value == Py_None) {
if (is_list != 0) {
SetOpAttrListDefault(ctx, op, attr, attr_name, type, attr_list_sizes,
status);
} else {
SetOpAttrScalarDefault(ctx, op, attr.default_value(), attr_name,
attr_list_sizes, status);
}
} else {
if (is_list != 0) {
SetOpAttrList(ctx, op, attr_name, attr_value, type, attr_list_sizes,
status);
} else {
SetOpAttrScalar(ctx, op, attr_name, attr_value, type, attr_list_sizes,
status);
}
}
}
PyObject* GetPythonObjectFromInt(int num) {
#if PY_MAJOR_VERSION >= 3
return PyLong_FromLong(num);
#else
return PyInt_FromLong(num);
#endif
}
// Python subclass of Exception that is created on not ok Status.
tensorflow::mutex exception_class_mutex(tensorflow::LINKER_INITIALIZED);
PyObject* exception_class TF_GUARDED_BY(exception_class_mutex) = nullptr;
// Python subclass of Exception that is created to signal fallback.
PyObject* fallback_exception_class = nullptr;
// Python function that returns input gradients given output gradients.
PyObject* gradient_function = nullptr;
// Python function that returns output gradients given input gradients.
PyObject* forward_gradient_function = nullptr;
static std::atomic<int64_t> _uid;
} // namespace
TF_Status* GetStatus() {
TF_Status* maybe_status = ReleaseThreadLocalStatus();
if (maybe_status) {
TF_SetStatus(maybe_status, TF_OK, "");
return maybe_status;
} else {
return TF_NewStatus();
}
}
void ReturnStatus(TF_Status* status) {
TF_SetStatus(status, TF_OK, "");
thread_local_tf_status.reset(status);
}
void TFE_Py_Execute(TFE_Context* ctx, const char* device_name,
const char* op_name, TFE_InputTensorHandles* inputs,
PyObject* attrs, TFE_OutputTensorHandles* outputs,
TF_Status* out_status) {
TFE_Py_ExecuteCancelable(ctx, device_name, op_name, inputs, attrs,
/*cancellation_manager=*/nullptr, outputs,
out_status);
}
void TFE_Py_ExecuteCancelable(TFE_Context* ctx, const char* device_name,
const char* op_name,
TFE_InputTensorHandles* inputs, PyObject* attrs,
TFE_CancellationManager* cancellation_manager,
TFE_OutputTensorHandles* outputs,
TF_Status* out_status) {
tensorflow::profiler::TraceMe activity(
"TFE_Py_ExecuteCancelable", tensorflow::profiler::TraceMeLevel::kInfo);
TFE_Op* op = GetOp(ctx, op_name, device_name, out_status);
auto cleaner = tensorflow::gtl::MakeCleanup([ctx, op] { ReturnOp(ctx, op); });
if (!out_status->status.ok()) return;
tensorflow::unwrap(op)->SetStackTrace(tensorflow::GetStackTrace(
tensorflow::StackTrace::kStackTraceInitialSize));
for (int i = 0; i < inputs->size() && out_status->status.ok(); ++i) {
TFE_OpAddInput(op, inputs->at(i), out_status);
}
if (cancellation_manager && out_status->status.ok()) {
TFE_OpSetCancellationManager(op, cancellation_manager, out_status);
}
if (out_status->status.ok()) {
SetOpAttrs(ctx, op, attrs, 0, out_status);
}
Py_BEGIN_ALLOW_THREADS;
int num_outputs = outputs->size();
if (out_status->status.ok()) {
TFE_Execute(op, outputs->data(), &num_outputs, out_status);
}
if (out_status->status.ok()) {
outputs->resize(num_outputs);
} else {
TF_SetStatus(out_status, TF_GetCode(out_status),
tensorflow::strings::StrCat(TF_Message(out_status),
" [Op:", op_name, "]")
.c_str());
}
Py_END_ALLOW_THREADS;
}
PyObject* TFE_Py_RegisterExceptionClass(PyObject* e) {
tensorflow::mutex_lock l(exception_class_mutex);
if (exception_class != nullptr) {
Py_DECREF(exception_class);
}
if (PyObject_IsSubclass(e, PyExc_Exception) <= 0) {
exception_class = nullptr;
PyErr_SetString(PyExc_TypeError,
"TFE_Py_RegisterExceptionClass: "
"Registered class should be subclass of Exception.");
return nullptr;
}
Py_INCREF(e);
exception_class = e;
Py_RETURN_NONE;
}
PyObject* TFE_Py_RegisterFallbackExceptionClass(PyObject* e) {
if (fallback_exception_class != nullptr) {
Py_DECREF(fallback_exception_class);
}
if (PyObject_IsSubclass(e, PyExc_Exception) <= 0) {
fallback_exception_class = nullptr;
PyErr_SetString(PyExc_TypeError,
"TFE_Py_RegisterFallbackExceptionClass: "
"Registered class should be subclass of Exception.");
return nullptr;
} else {
Py_INCREF(e);
fallback_exception_class = e;
Py_RETURN_NONE;
}
}
PyObject* TFE_Py_RegisterGradientFunction(PyObject* e) {
if (gradient_function != nullptr) {
Py_DECREF(gradient_function);
}
if (!PyCallable_Check(e)) {
gradient_function = nullptr;
PyErr_SetString(PyExc_TypeError,
"TFE_Py_RegisterGradientFunction: "
"Registered object should be function.");
return nullptr;
} else {
Py_INCREF(e);
gradient_function = e;
Py_RETURN_NONE;
}
}
PyObject* TFE_Py_RegisterJVPFunction(PyObject* e) {
if (forward_gradient_function != nullptr) {
Py_DECREF(forward_gradient_function);
}
if (!PyCallable_Check(e)) {
forward_gradient_function = nullptr;
PyErr_SetString(PyExc_TypeError,
"TFE_Py_RegisterJVPFunction: "
"Registered object should be function.");
return nullptr;
} else {
Py_INCREF(e);
forward_gradient_function = e;
Py_RETURN_NONE;
}
}
void RaiseFallbackException(const char* message) {
if (fallback_exception_class != nullptr) {
PyErr_SetString(fallback_exception_class, message);
return;
}
PyErr_SetString(
PyExc_RuntimeError,
tensorflow::strings::StrCat(
"Fallback exception type not set, attempting to fallback due to ",
message)
.data());