FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
tensorflow/tensorflow/python/tfe_wrapper.cc at master · IBMZ-Linux-OSS-Python/tensorflow · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
IBMZ-Linux-OSS-Python
/
tensorflow
Public
forked from
tensorflow/tensorflow
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
tensorflow
/
tensorflow
/
python
/
tfe_wrapper.cc
Copy path
More file actions
More file actions
Latest commit
History
History
History
1995 lines (1875 loc) · 87.1 KB
Breadcrumbs
tensorflow
/
tensorflow
/
python
/
tfe_wrapper.cc
Copy path
File metadata and controls
1995 lines (1875 loc) · 87.1 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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 2019 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
<
memory
>
//
Must be included first
//
clang-format off
#
include
"
absl/status/status.h
"
#
include
"
absl/strings/str_cat.h
"
#
include
"
pybind11/attr.h
"
//
from @pybind11
#
include
"
xla/tsl/python/lib/core/numpy.h
"
//
NOLINT
//
clang-format on
#
include
"
Python.h
"
#
include
"
absl/strings/str_format.h
"
#
include
"
absl/strings/str_join.h
"
#
include
"
absl/strings/str_split.h
"
#
include
"
include/dlpack/dlpack.h
"
//
from @dlpack
#
include
"
pybind11/chrono.h
"
//
from @pybind11
#
include
"
pybind11/complex.h
"
//
from @pybind11
#
include
"
pybind11/functional.h
"
//
from @pybind11
#
include
"
pybind11/pybind11.h
"
//
from @pybind11
#
include
"
pybind11/pytypes.h
"
//
from @pybind11
#
include
"
pybind11/stl.h
"
//
from @pybind11
#
include
"
tensorflow/c/c_api.h
"
#
include
"
tensorflow/c/c_api_experimental.h
"
#
include
"
tensorflow/c/eager/c_api.h
"
#
include
"
tensorflow/c/eager/c_api_experimental.h
"
#
include
"
tensorflow/c/eager/c_api_internal.h
"
#
include
"
tensorflow/c/eager/dlpack.h
"
#
include
"
tensorflow/c/eager/tfe_cancellation_manager_internal.h
"
#
include
"
tensorflow/c/eager/tfe_context_internal.h
"
#
include
"
tensorflow/c/eager/tfe_tensorhandle_internal.h
"
#
include
"
tensorflow/c/safe_ptr.h
"
#
include
"
tensorflow/c/tf_status.h
"
#
include
"
tensorflow/c/tf_status_helper.h
"
#
include
"
tensorflow/compiler/jit/flags.h
"
#
include
"
tensorflow/compiler/jit/get_compiler_ir.h
"
#
include
"
tensorflow/core/common_runtime/eager/context.h
"
#
include
"
tensorflow/python/eager/pywrap_tensor_conversion.h
"
#
include
"
tensorflow/python/eager/pywrap_tfe.h
"
#
include
"
tensorflow/python/lib/core/py_exception_registry.h
"
#
include
"
tensorflow/python/lib/core/pybind11_lib.h
"
#
include
"
tensorflow/python/lib/core/pybind11_status.h
"
#
include
"
tensorflow/python/lib/core/safe_pyobject_ptr.h
"
#
include
"
tensorflow/python/util/util.h
"
//
TODO(b/309152522): Remove this switch once it works on Windows.
#
define
IS_OSS
true
#
if
!IS_OSS
#
include
"
pybind11_protobuf/native_proto_caster.h
"
//
from @pybind11_protobuf
#
endif
namespace
py
=
pybind11;
PYBIND11_MAKE_OPAQUE
(TFE_Executor);
PYBIND11_MAKE_OPAQUE
(TFE_ContextOptions);
PYBIND11_MAKE_OPAQUE
(tensorflow::CancellationManager);
PYBIND11_MAKE_OPAQUE
(TFE_MonitoringCounter0);
PYBIND11_MAKE_OPAQUE
(TFE_MonitoringCounter1);
PYBIND11_MAKE_OPAQUE
(TFE_MonitoringCounter2);
PYBIND11_MAKE_OPAQUE
(TFE_MonitoringStringGauge0);
PYBIND11_MAKE_OPAQUE
(TFE_MonitoringStringGauge1);
PYBIND11_MAKE_OPAQUE
(TFE_MonitoringStringGauge2);
PYBIND11_MAKE_OPAQUE
(TFE_MonitoringStringGauge3);
PYBIND11_MAKE_OPAQUE
(TFE_MonitoringStringGauge4);
PYBIND11_MAKE_OPAQUE
(TFE_MonitoringIntGauge0);
PYBIND11_MAKE_OPAQUE
(TFE_MonitoringIntGauge1);
PYBIND11_MAKE_OPAQUE
(TFE_MonitoringIntGauge2);
PYBIND11_MAKE_OPAQUE
(TFE_MonitoringBoolGauge0);
PYBIND11_MAKE_OPAQUE
(TFE_MonitoringBoolGauge1);
PYBIND11_MAKE_OPAQUE
(TFE_MonitoringBoolGauge2);
PYBIND11_MAKE_OPAQUE
(TFE_MonitoringSampler0);
PYBIND11_MAKE_OPAQUE
(TFE_MonitoringSampler1);
PYBIND11_MAKE_OPAQUE
(TFE_MonitoringSampler2);
PYBIND11_MAKE_OPAQUE
(TFE_MonitoringCounterCell);
PYBIND11_MAKE_OPAQUE
(TFE_MonitoringIntGaugeCell);
PYBIND11_MAKE_OPAQUE
(TFE_MonitoringStringGaugeCell);
PYBIND11_MAKE_OPAQUE
(TFE_MonitoringBoolGaugeCell);
PYBIND11_MAKE_OPAQUE
(TFE_MonitoringSamplerCell);
PYBIND11_MAKE_OPAQUE
(TF_DeviceList);
PYBIND11_MAKE_OPAQUE
(TF_Function);
PYBIND11_MAKE_OPAQUE
(TF_Buffer);
//
Eager helper functions migrated from pywrap_tfe.i.
namespace
tensorflow
{
//
We cannot use Context as an opaque type. SWIG also had
//
difficult directly passing the pointer around. These
//
typemaps are migrated over from pywrap_tfe.i. I tried
//
using a custom type caster, but we get segfaults periodically.
//
TODO(amitpatankar): Move input and output logic of Context into a
//
pybind11 custom type caster.
TFE_Context*
InputTFE_Context
(
const
py::handle& ctx) {
return
static_cast
<TFE_Context*>(
PyCapsule_GetPointer
(ctx.
ptr
(),
nullptr
));
}
PyObject*
OutputTFE_Context
(TFE_Context* context) {
return
PyCapsule_New
(context,
nullptr
, TFE_DeleteContextCapsule);
}
TF_Buffer*
ProtoStringToTFBuffer
(PyObject* input) {
//
Convert a Python string object to TF_Buffer.
char
* c_string;
Py_ssize_t py_size;
//
PyBytes_AsStringAndSize() does not copy but simply interprets the input
if
(
PyBytes_AsStringAndSize
(input, &c_string, &py_size) == -
1
) {
//
Python has raised an error (likely TypeError or UnicodeEncodeError).
throw
py::error_already_set
();
}
return
TF_NewBufferFromString
(
static_cast
<
void
*>(c_string),
static_cast
<
size_t
>(py_size));
}
//
These functions are typemaps from the Python side. I did not use
//
a custom type caster since the logic is slightly harder to follow. This
//
converter is also only used once in `TFE_Py_ExecuteCancelable_wrapper`.
TFE_InputTensorHandles
InputTFE_InputTensorHandles
(
const
py::handle& input_tensors) {
TFE_InputTensorHandles input_tensor_handles;
if
(input_tensors.
ptr
() != Py_None) {
if
(!
PyList_Check
(input_tensors.
ptr
())) {
tensorflow::ThrowTypeError
(
"
must provide a list of Tensors as inputs
"
);
}
Py_ssize_t len =
PyList_Size
(input_tensors.
ptr
());
input_tensor_handles.
resize
(len);
for
(Py_ssize_t i =
0
; i < len; ++i) {
PyObject* elem =
PyList_GetItem
(input_tensors.
ptr
(), i);
if
(!elem) {
tensorflow::ThrowTypeError
(
"
Input Tensor does not exist.
"
);
}
if
(
EagerTensor_CheckExact
(elem)) {
(input_tensor_handles)[i] =
EagerTensor_Handle
(elem);
}
else
if
(
tensorflow::swig::IsEagerTensorSlow
(elem)) {
//
Use equivalent of object.__getattribute__ to get the underlying
//
tf wrapped EagerTensor (if there is one).
tensorflow::Safe_PyObjectPtr
tf_should_use_attr
(
#
if
PY_MAJOR_VERSION < 3
PyString_InternFromString
(
"
_tf_should_use_wrapped_value
"
)
#
else
PyUnicode_InternFromString
(
"
_tf_should_use_wrapped_value
"
)
#
endif
);
tensorflow::Safe_PyObjectPtr
value_attr
(
PyObject_GenericGetAttr
(elem, tf_should_use_attr.
get
()));
if
(value_attr) {
//
This is an EagerTensor wrapped inside a TFShouldUse wrapped object.
(input_tensor_handles)[i] =
EagerTensor_Handle
(value_attr.
get
());
}
else
{
//
This is a subclass of EagerTensor that we don't support.
PyErr_Clear
();
tensorflow::ThrowTypeError
(
tensorflow::strings::StrCat
(
"
Saw an object that is an instance of a strict subclass of
"
"
EagerTensor, which is not supported. Item
"
,
i,
"
is type:
"
, elem->
ob_type
->
tp_name
)
.
c_str
());
}
}
else
if
(
tensorflow::swig::IsTensorProtocol
(elem) &&
tensorflow::swig::IsCoreTypeValue
(elem)) {
//
For WeakTensors, fetch the underlying Tensors.
//
This is placed after the branches `IsEagerTensorSlow` and
//
`EagerTensor_CheckExact` to ensure those paths are quick.
elem =
PyObject_CallMethod
(elem,
"
__tf_tensor__
"
,
nullptr
);
(input_tensor_handles)[i] =
EagerTensor_Handle
(elem);
}
else
if
(
tensorflow::swig::IsTensor
(elem)) {
//
If it isnt an EagerTensor, but is still a Tensor, it must be a graph
//
tensor.
tensorflow::Safe_PyObjectPtr
py_tensor_repr
(
PyObject_Repr
(elem));
std::string tensor_repr =
py_tensor_repr ?
TFE_GetPythonString
(py_tensor_repr.
get
())
:
"
<unknown>
"
;
tensorflow::Safe_PyObjectPtr
py_op
(
PyObject_GetAttrString
(elem,
"
op
"
));
tensorflow::Safe_PyObjectPtr
py_defined_graph
(
PyObject_GetAttrString
(py_op.
get
(),
"
graph
"
));
tensorflow::Safe_PyObjectPtr
py_defined_graph_str
(
PyObject_Str
(py_defined_graph.
get
()));
std::string defined_graph_str =
py_defined_graph_str
?
TFE_GetPythonString
(py_defined_graph_str.
get
())
:
"
<unknown>
"
;
tensorflow::Safe_PyObjectPtr
c_op
(
PyObject_GetAttrString
(py_op.
get
(),
"
_c_op
"
));
auto
& node = py::cast<TF_Operation*>(c_op.
get
())->
node
;
auto
node_name_str = node.
name
();
std::string frame_str, traceback_str;
if
(
auto
stack_trace = node.
GetStackTrace
()) {
auto
frame = stack_trace->
LastUserFrame
();
frame_str =
absl::StrFormat
(
"
File
\"
%s
\"
, line %d, in %s
"
, frame.
file_name
,
frame.
line_number
, frame.
function_name
);
auto
stack_trace_list =
absl::StrSplit
(stack_trace->
ToString
({
true
}),
'
\n
'
);
traceback_str =
absl::StrJoin
(
stack_trace_list,
"
"
, [&](std::string* out,
const
auto
line) {
absl::StrAppend
(out,
"
"
, line,
"
\n
"
);
});
}
else
{
frame_str =
"
<unknown>
"
;
traceback_str =
"
<unknown>
\n
"
;
}
//
Keep in sync with func_graph.py.
//
TODO(b/200991648): Unify those two paths.
tensorflow::ThrowTypeError
(
tensorflow::strings::StrCat
(
tensor_repr,
"
is out of scope and cannot be used here.
"
"
Use return values, explicit Python locals or TensorFlow
"
"
collections to access it.
\n
"
"
Please see https://www.tensorflow.org/guide/
"
"
function#all_outputs_of_a_tffunction_must_be_return_values
"
"
for more information.
\n\n
"
,
tensor_repr,
"
was defined here:
\n
"
, traceback_str,
"
\n
The tensor
"
, tensor_repr,
"
cannot be accessed from here, because it was
"
"
defined in
"
,
defined_graph_str,
"
, which is out of scope.
"
)
.
c_str
());
}
else
{
tensorflow::ThrowTypeError
(
tensorflow::strings::StrCat
(
"
provided list of inputs contains objects other
"
"
than 'EagerTensor'. Item
"
,
i,
"
is type:
"
, elem->
ob_type
->
tp_name
)
.
c_str
());
}
}
}
return
input_tensor_handles;
}
//
These functions are typemaps from the Python side. I did not use
//
a custom type caster since the logic is slightly harder to follow. This
//
converter is also only used once in `TFE_Py_ExecuteCancelable_wrapper`.
//
This function actually takes a number rather than an output Tensor holder.
TFE_OutputTensorHandles
InputTFE_OutputTensorHandles
(
const
py::handle& num_outputs) {
TFE_OutputTensorHandles output_tensor_handles;
#
if
PY_MAJOR_VERSION < 3
if
(!
PyInt_Check
(num_outputs.
ptr
())) {
#
else
if
(!
PyLong_Check
(num_outputs.
ptr
())) {
#endif
PyErr_SetString
(PyExc_TypeError,
"
expected an integer value (size of the number of
"
"
outputs of the operation)
"
);
throw
py::error_already_set
();
}
#
if
PY_MAJOR_VERSION < 3
long
sz =
PyInt_AsLong
(num_outputs.
ptr
());
//
NOLINT
#
else
long
sz =
PyLong_AsLong
(num_outputs.
ptr
());
//
NOLINT
#
endif
//
PyLong_AsLong might throw an error if an overflow occurs.
if
(
PyErr_Occurred
()) {
PyErr_SetString
(PyExc_ValueError,
tensorflow::strings::StrCat
(
"
Number of outputs is too big:
"
, sz)
.
c_str
());
throw
py::error_already_set
();
}
//
We can't handle more than int32 sizes for number of outputs.
if
(
static_cast
<
long
>(
static_cast
<
int32_t
>(sz)) != sz) {
//
NOLINT
PyErr_SetString
(PyExc_ValueError,
tensorflow::strings::StrCat
(
"
Number of outputs is too big:
"
, sz)
.
c_str
());
throw
py::error_already_set
();
}
if
(sz >
0
) {
#
if
PY_MAJOR_VERSION < 3
output_tensor_handles.
resize
(
PyInt_AsLong
(num_outputs.
ptr
()),
nullptr
);
#
else
output_tensor_handles.
resize
(
PyLong_AsLong
(num_outputs.
ptr
()),
nullptr
);
#
endif
}
return
output_tensor_handles;
}
tensorflow::Device*
GetMatchedDevice
(py::handle& ctx,
const
char
* device_name) {
auto
* context =
reinterpret_cast
<tensorflow::ImmediateExecutionContext*>(
tensorflow::InputTFE_Context
(ctx));
tensorflow::DeviceNameUtils::ParsedName input_device_name;
if
(!
tensorflow::DeviceNameUtils::ParseFullOrLocalName
(device_name,
&input_device_name)) {
tensorflow::ThrowValueError
(
absl::StrFormat
(
"
Failed parsing device name: '%s'. Note a valid device
"
"
string should at least contain a device type and a
"
"
device index, like
\"
GPU:0
\"
.
"
,
device_name)
.
c_str
());
}
std::vector<tensorflow::Device*> devices = context->
ListLocalTfDevices
();
tensorflow::Device* matched_device =
nullptr
;
for
(
int
device_idx =
0
; device_idx < devices.
size
(); device_idx++) {
tensorflow::Device* device = devices[device_idx];
if
(
tensorflow::DeviceNameUtils::AreCompatibleDevNames
(
input_device_name, device->
parsed_name
())) {
if
(matched_device !=
nullptr
) {
tensorflow::ThrowValueError
(
absl::StrFormat
(
"
Multiple devices match the provided string
"
"
'%s': '%s' and '%s'.
"
,
device_name, matched_device->
name
(), device->
name
())
.
c_str
());
}
matched_device = device;
}
}
if
(matched_device ==
nullptr
) {
tensorflow::ThrowValueError
(
absl::StrFormat
(
"
No matching devices found for '%s'
"
, device_name)
.
c_str
());
}
return
matched_device;
}
//
Packs multiple `EagerTensor`s of the same dtype and shape into one
//
`EagerTensor`.
py::object
TFE_Py_PackEagerTensors_wrapper
(
const
py::handle& context,
const
py::handle& tensors) {
TFE_Context* ctx =
tensorflow::InputTFE_Context
(context);
TFE_InputTensorHandles handles =
InputTFE_InputTensorHandles
(tensors);
tensorflow::Safe_TF_StatusPtr status =
tensorflow::make_safe
(
TF_NewStatus
());
int
size = handles.
size
();
TFE_TensorHandle* packed_handle =
TFE_CreatePackedTensorHandle
(ctx, handles.
data
(), &size, status.
get
());
tensorflow::MaybeRaiseRegisteredFromTFStatus
(status.
get
());
PyObject* packed_tensor =
EagerTensorFromHandle
(packed_handle,
/*
is_packed=
*/
true
);
return
tensorflow::PyoOrThrow
(packed_tensor);
}
//
This function was created from fusing the typemap logic in platform/base.i.
py::object
TFE_Py_ExecuteCancelable_wrapper
(
const
py::handle& context,
const
char
* device_name,
const
char
* op_name,
const
py::handle& inputs,
const
py::handle& attrs,
tensorflow::CancellationManager* cancellation_manager,
const
py::handle& num_outputs) {
TFE_Context* ctx =
tensorflow::InputTFE_Context
(context);
TFE_InputTensorHandles input_tensor_handles =
InputTFE_InputTensorHandles
(inputs);
TFE_OutputTensorHandles output_tensor_handles =
InputTFE_OutputTensorHandles
(num_outputs);
tensorflow::Safe_TF_StatusPtr status =
tensorflow::make_safe
(
TF_NewStatus
());
TFE_Py_ExecuteCancelable
(ctx, device_name, op_name, &input_tensor_handles,
attrs.
ptr
(),
tensorflow::wrap
(cancellation_manager),
&output_tensor_handles, status.
get
());
int
output_len = output_tensor_handles.
size
();
PyObject* output_list =
PyList_New
(output_len);
for
(
int
i =
0
; i < output_len; ++i) {
PyObject* output;
output =
EagerTensorFromHandle
(output_tensor_handles.
at
(i));
PyList_SetItem
(output_list, i, output);
}
tensorflow::MaybeRaiseRegisteredFromTFStatus
(status.
get
());
return
tensorflow::PyoOrThrow
(output_list);
}
static
py::object
TF_ListPhysicalDevices
() {
std::vector<string> devices;
absl::Status s =
tensorflow::DeviceFactory::ListAllPhysicalDevices
(&devices);
MaybeRaiseRegisteredFromStatus
(s);
PyObject* result =
PyList_New
(devices.
size
());
int
i =
0
;
for
(
auto
& dev : devices) {
PyObject* dev_obj =
PyBytes_FromStringAndSize
(dev.
data
(), dev.
size
());
PyList_SetItem
(result, i, dev_obj);
++i;
}
return
tensorflow::PyoOrThrow
(result);
}
static
py::object
TF_ListPluggablePhysicalDevices
() {
std::vector<string> devices;
absl::Status s =
tensorflow::DeviceFactory::ListPluggablePhysicalDevices
(&devices);
MaybeRaiseRegisteredFromStatus
(s);
Safe_PyObjectPtr
result
(
PyList_New
(devices.
size
()));
int
i =
0
;
for
(
auto
& dev : devices) {
PyObject* dev_obj =
PyBytes_FromStringAndSize
(dev.
data
(), dev.
size
());
PyList_SetItem
(result.
get
(), i, dev_obj);
++i;
}
return
tensorflow::PyoOrThrow
(result.
release
());
}
static
std::unordered_map<string, string>
TF_GetDeviceDetails
(
int
index) {
tensorflow::Safe_TF_StatusPtr status =
tensorflow::make_safe
(
TF_NewStatus
());
std::unordered_map<string, string> device_details;
absl::Status s =
tensorflow::DeviceFactory::GetAnyDeviceDetails
(index, &device_details);
tensorflow::Set_TF_Status_from_Status
(status.
get
(), s);
MaybeRaiseRegisteredFromTFStatus
(status.
get
());
return
device_details;
}
static
py::object
TFE_ClearScalarCache
() {
tensorflow::TFE_TensorHandleCache::Get
()->
Clear
();
return
py::none
();
}
static
Device*
GetDevice
(EagerContext* context,
const
char
* device_name,
const
char
* platform_name,
const
std::vector<Device*>& devices) {
auto
device_name_str = platform_name !=
nullptr
?
absl::StrCat
(
"
/device:
"
, platform_name,
"
:0
"
)
:
std::string
(device_name);
DeviceNameUtils::ParsedName input_device_name;
if
(!
DeviceNameUtils::ParseFullOrLocalName
(device_name_str,
&input_device_name)) {
ThrowValueError
(
absl::StrFormat
(
"
Failed parsing derived device name: '%s'
"
,
device_name_str)
.
c_str
());
}
auto
selected_device =
absl::c_find_if
(devices, [&](
const
Device* d) {
return
DeviceNameUtils::AreCompatibleDevNames
(input_device_name,
d->
parsed_name
());
});
if
(selected_device == devices.
end
()) {
return
nullptr
;
}
return
*selected_device;
}
//
Returns compiler IR for a given function.
static
py::bytes
TFE_GetCompilerIr
(py::handle& ctx,
const
char
* concrete_function_name,
const
char
* stage,
const
char
* device_name,
py::handle& flat_arg_inputs,
py::handle& captured_inputs,
const
char
* platform_name) {
EagerContext* context =
ContextFromInterface
(
reinterpret_cast
<ImmediateExecutionContext*>(
InputTFE_Context
(ctx)));
std::string
s_stage
(stage);
IrExportStage selected_stage = [&] {
if
(s_stage ==
"
stablehlo
"
) {
return
IrExportStage::
STABLEHLO
;
}
else
if
(s_stage ==
"
stablehlo_serialized
"
) {
return
IrExportStage::
STABLEHLO_SERIALIZED
;
}
else
if
(s_stage ==
"
hlo
"
) {
return
IrExportStage::
HLO
;
}
else
if
(s_stage ==
"
hlo_no_metadata
"
) {
return
IrExportStage::
HLO_NO_METADATA
;
}
else
if
(s_stage ==
"
hlo_serialized
"
) {
return
IrExportStage::
HLO_SERIALIZED
;
}
else
if
(s_stage ==
"
optimized_hlo
"
) {
return
IrExportStage::
OPTIMIZED_HLO
;
}
else
if
(s_stage ==
"
optimized_hlo_serialized
"
) {
return
IrExportStage::
OPTIMIZED_HLO_SERIALIZED
;
}
else
if
(s_stage ==
"
optimized_hlo_proto_serialized
"
) {
return
IrExportStage::
OPTIMIZED_HLO_PROTO_SERIALIZED
;
}
else
if
(s_stage ==
"
optimized_hlo_dot
"
) {
return
IrExportStage::
OPTIMIZED_HLO_DOT
;
}
else
{
ThrowValueError
(
absl::StrFormat
(
"
Invalid stage selected: '%s'. Valid values are:
"
"
'hlo', 'hlo_serialized', 'optimized_hlo',
"
"
'optimized_hlo_serialized', 'optimized_hlo_dot'
"
,
s_stage)
.
c_str
());
}
}();
CompilerArgSource compiler_arg_source = [&] {
if
(
PyList_Size
(flat_arg_inputs.
ptr
()) ==
0
) {
return
CompilerArgSource::
CONCRETE_INPUT
;
}
PyObject* elem =
PyList_GetItem
(flat_arg_inputs.
ptr
(),
0
);
if
(
swig::IsTensorSpec
(elem)) {
return
CompilerArgSource::
TENSOR_SPEC
;
}
else
if
(
swig::IsTensor
(elem)) {
return
CompilerArgSource::
CONCRETE_INPUT
;
}
else
{
ThrowValueError
(
tensorflow::strings::StrCat
(
"
Only accept tf.TensorSpec or tf.Tensor but got type
"
,
elem->
ob_type
->
tp_name
)
.
c_str
());
}
}();
Py_ssize_t flat_arg_len =
PyList_Size
(flat_arg_inputs.
ptr
());
Py_ssize_t captured_input_len =
PyList_Size
(captured_inputs.
ptr
());
std::vector<ArgShapeAndDType> flat_args;
std::vector<
const
TensorHandle*> captured_input_handles;
if
(compiler_arg_source == CompilerArgSource::
TENSOR_SPEC
) {
flat_args.
resize
(flat_arg_len);
captured_input_handles.
reserve
(captured_input_len);
for
(Py_ssize_t i =
0
; i < flat_arg_len; ++i) {
PyObject* elem_ptr =
PyList_GetItem
(flat_arg_inputs.
ptr
(), i);
py::object elem = py::reinterpret_borrow<py::object>(elem_ptr);
py::object py_dtype = elem.
attr
(
"
dtype
"
);
py::object py_shape = elem.
attr
(
"
shape
"
);
int
dtype = py::cast<
int
>(py_dtype.
attr
(
"
_type_enum
"
));
auto
shape = py::cast<std::vector<
int64_t
>>(py_shape);
flat_args[i].
dtype
=
DataType
(dtype);
flat_args[i].
shape
=
TensorShape
(shape);
}
}
else
if
(compiler_arg_source == CompilerArgSource::
CONCRETE_INPUT
) {
captured_input_handles.
reserve
(flat_arg_len + captured_input_len);
TFE_InputTensorHandles handles =
InputTFE_InputTensorHandles
(flat_arg_inputs);
for
(TFE_TensorHandle* tensor_handle : handles) {
AbstractTensorHandle* abstract_tensor_handle =
unwrap
(tensor_handle);
captured_input_handles.
push_back
(
TensorHandleFromInterface
(abstract_tensor_handle));
}
}
TFE_InputTensorHandles handles =
InputTFE_InputTensorHandles
(captured_inputs);
for
(TFE_TensorHandle* tensor_handle : handles) {
AbstractTensorHandle* abstract_tensor_handle =
unwrap
(tensor_handle);
captured_input_handles.
push_back
(
TensorHandleFromInterface
(abstract_tensor_handle));
}
absl::StatusOr<std::string> hlo_str;
std::vector<Device*> devices = context->
local_device_mgr
()->
ListDevices
();
Device* selected_device =
GetDevice
(context, device_name, platform_name, devices);
if
(selected_device !=
nullptr
) {
hlo_str =
GetCompilerIr
(selected_stage, context->
pflr
(), concrete_function_name,
selected_device, context, flat_args,
captured_input_handles, compiler_arg_source);
}
else
if
(platform_name !=
nullptr
) {
hlo_str =
GetCompilerIr
(
selected_stage, context->
pflr
(), concrete_function_name, platform_name,
context, flat_args, captured_input_handles, compiler_arg_source);
}
else
{
ThrowValueError
(
absl::StrFormat
(
"
No matching device found for '%s'
"
, device_name)
.
c_str
());
}
if
(!hlo_str.
ok
()) {
ThrowValueError
(
absl::StrFormat
(
"
Failed getting HLO text: '%s'
"
,
hlo_str.
status
().
message
())
.
c_str
());
}
return
py::bytes
(*hlo_str);
}
}
//
namespace tensorflow
namespace
{
//
Wrapper around the EagerContextThreadLocalData struct (defined in
//
pywrap_tfe.h), so it can be accessed from Python.
//
//
For PyObject* fields, the get_*() methods return a new reference; and the
//
set_*() methods create a new reference (i.e., they do not steal a reference).
class
EagerContextThreadLocalDataWrapper
{
public:
explicit
EagerContextThreadLocalDataWrapper
(py::handle py_eager_context,
py::handle is_eager,
py::handle device_spec)
: py_eager_context_(py_eager_context.ptr()) {
tensorflow::MakeEagerContextThreadLocalData
(
py_eager_context.
ptr
(), is_eager.
ptr
(), device_spec.
ptr
());
}
~EagerContextThreadLocalDataWrapper
() {
tensorflow::DestroyEagerContextThreadLocalData
(py_eager_context_);
}
bool
get_is_eager
()
const
{
return
GetData
()->
is_eager
; }
void
set_is_eager
(
bool
v) {
GetData
()->
is_eager
= v; }
bool
get_invoking_op_callbacks
()
const
{
return
GetData
()->
invoking_op_callbacks
;
}
void
set_invoking_op_callbacks
(
bool
v) {
GetData
()->
invoking_op_callbacks
= v;
}
py::object
get_device_name
()
const
{
return
GetPyObject
(&
GetData
()->
device_name
);
}
void
set_device_name
(py::handle v) {
SetPyObject
(v, &
GetData
()->
device_name
);
}
py::object
get_scope_name
()
const
{
return
GetPyObject
(&
GetData
()->
scope_name
);
}
void
set_scope_name
(py::handle v) {
SetPyObject
(v, &
GetData
()->
scope_name
); }
py::object
get_device_spec
()
const
{
return
GetPyObject
(&
GetData
()->
device_spec
);
}
void
set_device_spec
(py::handle v) {
SetPyObject
(v, &
GetData
()->
device_spec
);
}
py::object
get_function_call_options
()
const
{
return
GetPyObject
(&
GetData
()->
function_call_options
);
}
void
set_function_call_options
(py::handle v) {
SetPyObject
(v, &
GetData
()->
function_call_options
);
}
py::handle
get_executor
()
const
{
return
GetPyObject
(&
GetData
()->
executor
); }
void
set_executor
(py::handle v) {
SetPyObject
(v, &
GetData
()->
executor
); }
py::object
get_op_callbacks
()
const
{
return
GetPyObject
(&
GetData
()->
op_callbacks
);
}
void
set_op_callbacks
(py::handle v) {
SetPyObject
(v, &
GetData
()->
op_callbacks
);
}
private:
tensorflow::EagerContextThreadLocalData*
GetData
()
const
{
auto
* result =
tensorflow::GetEagerContextThreadLocalData
(py_eager_context_);
if
(!result) {
throw
py::error_already_set
();
}
return
result;
}
py::object
GetPyObject
(tensorflow::Safe_PyObjectPtr* obj)
const
{
return
pybind11::reinterpret_borrow<py::object>(obj->
get
());
}
void
SetPyObject
(py::handle value, tensorflow::Safe_PyObjectPtr* ptr) {
Py_INCREF
(value.
ptr
());
ptr->
reset
(value.
ptr
());
}
PyObject* py_eager_context_;
//
not owned (borrowed reference).
};
}
//
namespace
//
py::return_value_policy::reference is defined as specified by the
//
pybind11 documents listed here.
//
https://pybind11.readthedocs.io/en/stable/advanced/functions.html#return-value-policies
//
This means that C++ maintains ownership of the object. We
//
are only assigning this to functions that return opaque types.
PYBIND11_MODULE
(_pywrap_tfe, m) {
//
Numpy initialization code for array functions.
tsl::ImportNumpy
();
py::class_<TFE_Executor>
TFE_Executor_class
(m,
"
TFE_Executor
"
);
py::class_<TFE_ContextOptions>
TFE_ContextOptions_class
(m,
"
TFE_ContextOptions
"
);
py::class_<TFE_MonitoringCounter0>
TFE_MonitoringCounter0_class
(
m,
"
TFE_MonitoringCounter0
"
);
py::class_<TFE_MonitoringCounter1>
TFE_MonitoringCounter1_class
(
m,
"
TFE_MonitoringCounter1
"
);
py::class_<TFE_MonitoringCounter2>
TFE_MonitoringCounter2_class
(
m,
"
TFE_MonitoringCounter2
"
);
py::class_<TFE_MonitoringStringGauge0>
TFE_MonitoringStringGauge0_class
(
m,
"
TFE_MonitoringStringGauge0
"
);
py::class_<TFE_MonitoringStringGauge1>
TFE_MonitoringStringGauge1_class
(
m,
"
TFE_MonitoringStringGauge1
"
);
py::class_<TFE_MonitoringStringGauge2>
TFE_MonitoringStringGauge2_class
(
m,
"
TFE_MonitoringStringGauge2
"
);
py::class_<TFE_MonitoringStringGauge3>
TFE_MonitoringStringGauge3_class
(
m,
"
TFE_MonitoringStringGauge3
"
);
py::class_<TFE_MonitoringStringGauge4>
TFE_MonitoringStringGauge4_class
(
m,
"
TFE_MonitoringStringGauge4
"
);
py::class_<TFE_MonitoringIntGauge0>
TFE_MonitoringIntGauge0_class
(
m,
"
TFE_MonitoringIntGauge0
"
);
py::class_<TFE_MonitoringIntGauge1>
TFE_MonitoringIntGauge1_class
(
m,
"
TFE_MonitoringIntGauge1
"
);
py::class_<TFE_MonitoringIntGauge2>
TFE_MonitoringIntGauge2_class
(
m,
"
TFE_MonitoringIntGauge2
"
);
py::class_<TFE_MonitoringBoolGauge0>
TFE_MonitoringBoolGauge0_class
(
m,
"
TFE_MonitoringBoolGauge0
"
);
py::class_<TFE_MonitoringBoolGauge1>
TFE_MonitoringBoolGauge1_class
(
m,
"
TFE_MonitoringBoolGauge1
"
);
py::class_<TFE_MonitoringBoolGauge2>
TFE_MonitoringBoolGauge2_class
(
m,
"
TFE_MonitoringBoolGauge2
"
);
py::class_<TFE_MonitoringCounterCell>
TFE_MonitoringCounterCell_class
(
m,
"
TFE_MonitoringCounterCell
"
);
py::class_<TFE_MonitoringIntGaugeCell>
TFE_MonitoringIntGaugeCell_class
(
m,
"
TFE_MonitoringIntGaugeCell
"
);
py::class_<TFE_MonitoringStringGaugeCell>
TFE_MonitoringStringGaugeCell_class
(
m,
"
TFE_MonitoringStringGaugeCell
"
);
py::class_<TFE_MonitoringBoolGaugeCell>
TFE_MonitoringBoolGaugeCell_class
(
m,
"
TFE_MonitoringBoolGaugeCell
"
);
py::class_<TFE_MonitoringSamplerCell>
TFE_MonitoringSamplerCell_class
(
m,
"
TFE_MonitoringSamplerCell
"
);
py::class_<TFE_MonitoringBuckets>
TFE_MonitoringBuckets_class
(
m,
"
TFE_MonitoringBuckets
"
);
py::class_<TFE_MonitoringSampler0>
TFE_MonitoringSampler0_class
(
m,
"
TFE_MonitoringSampler0
"
);
py::class_<TFE_MonitoringSampler1>
TFE_MonitoringSampler1_class
(
m,
"
TFE_MonitoringSampler1
"
);
py::class_<TFE_MonitoringSampler2>
TFE_MonitoringSampler2_class
(
m,
"
TFE_MonitoringSampler2
"
);
py::class_<tensorflow::CancellationManager>
TFE_CancellationManager_class
(
m,
"
TFE_CancellationManager
"
);
py::class_<TF_DeviceList>
TF_DeviceList_class
(m,
"
TF_DeviceList
"
);
py::class_<TF_Function>
TF_Function_class
(m,
"
TF_Function
"
);
py::class_<TF_Buffer>
TF_Buffer_class
(m,
"
TF_Buffer
"
,
py::module_local
());
m.
def
(
"
TFE_Py_RegisterExceptionClass
"
, [](
const
py::handle& e) {
return
tensorflow::PyoOrThrow
(
TFE_Py_RegisterExceptionClass
(e.
ptr
()));
});
m.
def
(
"
TFE_Py_RegisterFallbackExceptionClass
"
, [](
const
py::handle& e) {
return
tensorflow::PyoOrThrow
(
TFE_Py_RegisterFallbackExceptionClass
(e.
ptr
()));
});
m.
def
(
"
TFE_GetMemoryInfo
"
, [](py::handle& ctx,
const
char
* device_name) {
tensorflow::Device* matched_device =
tensorflow::GetMatchedDevice
(ctx, device_name);
tensorflow::AllocatorAttributes attrs;
tensorflow::Allocator* allocator = matched_device->
GetAllocator
(attrs);
if
(absl::optional<tensorflow::AllocatorStats> stats =
allocator->
GetStats
()) {
return
std::map<std::string,
int64_t
>{{
"
current
"
, stats->
bytes_in_use
},
{
"
peak
"
, stats->
peak_bytes_in_use
}};
}
tensorflow::ThrowValueError
(
absl::StrFormat
(
"
Allocator stats not available for device '%s'
"
,
device_name)
.
c_str
());
});
m.
def
(
"
TFE_ResetMemoryStats
"
, [](py::handle& ctx,
const
char
* device_name) {
tensorflow::Device* matched_device =
tensorflow::GetMatchedDevice
(ctx, device_name);
tensorflow::AllocatorAttributes attrs;
tensorflow::Allocator* allocator = matched_device->
GetAllocator
(attrs);
if
(!allocator->
ClearStats
()) {
tensorflow::ThrowValueError
(
absl::StrFormat
(
"
Cannot reset memory stats for device '%s'
"
,
device_name)
.
c_str
());
}
});
//
XLA Eager Logic
m.
def
(
"
TF_SetXlaEnableLazyCompilation
"
, &TF_SetXlaEnableLazyCompilation);
m.
def
(
"
TF_SetTfXlaCpuGlobalJit
"
, &TF_SetTfXlaCpuGlobalJit);
m.
def
(
"
TF_SetXlaAutoJitMode
"
, &TF_SetXlaAutoJitMode);
m.
def
(
"
TF_SetXlaConstantFoldingDisabled
"
, &TF_SetXlaConstantFoldingDisabled);
m.
def
(
"
TF_GetXlaConstantFoldingDisabled
"
, &TF_GetXlaConstantFoldingDisabled);
m.
def
(
"
TF_SetXlaMinClusterSize
"
, &TF_SetXlaMinClusterSize);
m.
def
(
"
TF_GetCompilerIr
"
, &tensorflow::TFE_GetCompilerIr);
//
MLIR Logic
m.
def
(
"
TF_IsMlirBridgeEnabled
"
, [] {
//
Since python protobuf enums are integers, cast to an integer before
//
returning the enum to python.
return
static_cast
<
int32_t
>(
tensorflow::GetMlirCommonFlags
()->
tf_mlir_enable_mlir_bridge
);
});
m.
def
(
"
TF_EnableMlirBridge
"
, [](
bool
enabled) {
tensorflow::GetMlirCommonFlags
()->
tf_mlir_enable_mlir_bridge
=
enabled
? tensorflow::ConfigProto::Experimental::
MLIR_BRIDGE_ROLLOUT_ENABLED
: tensorflow::ConfigProto::Experimental::
MLIR_BRIDGE_ROLLOUT_DISABLED
;
});
m.
def
(
"
TF_EnableXlaDevices
"
, [] {
tensorflow::GetXlaDeviceFlags
()->
tf_xla_enable_xla_devices
=
true
;
});
m.
def
(
"
TF_ResetJitCompilerFlags
"
,
[] {
tensorflow::ResetJitCompilerFlags
(); });
//
TFE_Context Logic
m.
def
(
"
TFE_NewContext
"
,
[](
const
TFE_ContextOptions* opts) {
tensorflow::Safe_TF_StatusPtr status =
tensorflow::make_safe
(
TF_NewStatus
());
TFE_Context* context =
TFE_NewContext
(opts, status.
get
());
tensorflow::MaybeRaiseRegisteredFromTFStatus
(status.
get
());
return
tensorflow::PyoOrThrow
(
tensorflow::OutputTFE_Context
(context));
},
py::return_value_policy::reference);
m.
def
(
"
TFE_DeleteContext
"
, [](py::handle& o) {
TFE_DeleteContext
(
tensorflow::InputTFE_Context
(o));
});
m.
def
(
"
TFE_ContextListDevices
"
,
[](py::handle& o) {
tensorflow::Safe_TF_StatusPtr status =
tensorflow::make_safe
(
TF_NewStatus
());
auto
output =
TFE_ContextListDevices
(
tensorflow::InputTFE_Context
(o),
status.
get
());
tensorflow::MaybeRaiseRegisteredFromTFStatus
(status.
get
());
return
output;
},
py::return_value_policy::reference);
m.
def
(
"
TFE_SetLogicalCpuDevices
"
,
[](py::handle& ctx,
int
num_cpus,
const
char
* prefix) {
tensorflow::Safe_TF_StatusPtr status =
tensorflow::make_safe
(
TF_NewStatus
());
TFE_SetLogicalCpuDevices
(
tensorflow::InputTFE_Context
(ctx), num_cpus,
prefix, status.
get
());
tensorflow::MaybeRaiseRegisteredFromTFStatus
(status.
get
());
},
py::return_value_policy::reference);
m.
def
(
"
TFE_HostAddressSpace
"
, [](py::handle& o, TF_Buffer& buf) {
TFE_HostAddressSpace
(
tensorflow::InputTFE_Context
(o), &buf);
});
m.
def
(
"
TFE_ContextAddFunction
"
, [](py::handle& ctx, TF_Function* func) {
tensorflow::Safe_TF_StatusPtr status =
tensorflow::make_safe
(
TF_NewStatus
());
TFE_ContextAddFunction
(
tensorflow::InputTFE_Context
(ctx), func,
status.
get
());
tensorflow::MaybeRaiseRegisteredFromTFStatus
(status.
get
());
});
m.
def
(
"
TFE_ContextAddFunctionDef
"
,
[](py::handle& ctx,
const
char
* serialized_function_def,
size_t
size) {
tensorflow::Safe_TF_StatusPtr status =
tensorflow::make_safe
(
TF_NewStatus
());
TFE_ContextAddFunctionDef
(
tensorflow::InputTFE_Context
(ctx),
serialized_function_def, size,
status.
get
());
tensorflow::MaybeRaiseRegisteredFromTFStatus
(status.
get
());
});
m.
def
(
"
TFE_ContextGetFunction
"
,
[](py::handle& ctx,
const
char
* function_name) {
tensorflow::Safe_TF_StatusPtr status =
tensorflow::make_safe
(
TF_NewStatus
());
TF_Function* tf_function =
TFE_ContextGetFunction
(
tensorflow::InputTFE_Context
(ctx), function_name, status.
get
());
tensorflow::MaybeRaiseRegisteredFromTFStatus
(status.
get
());
return
tf_function;
},
py::return_value_policy::reference);
m.
def
(
"
TFE_ContextGetFunctionDef
"
,
[](py::handle& ctx,
const
char
* function_name, TF_Buffer& buf) {
tensorflow::Safe_TF_StatusPtr status =
tensorflow::make_safe
(
TF_NewStatus
());
TFE_ContextGetFunctionDef
(
tensorflow::InputTFE_Context
(ctx),
function_name, &buf, status.
get
());
tensorflow::MaybeRaiseRegisteredFromTFStatus
(status.
get
());
});
//
TODO(b/309152522): Remove the switch once it works on Windows.
#
if
!IS_OSS
pybind11_protobuf::ImportNativeProtoCasters
();
m.
def
(
"
TFE_ContextAddFunctionDefNoSerialization
"
,
[](py::handle& ctx, tensorflow::FunctionDef function_def) {
tensorflow::Safe_TF_StatusPtr status =
tensorflow::make_safe
(
TF_NewStatus
());
//
Annotate eager runtime construction context to the given
//
`function_def` as an attribute.
tensorflow::AttrValue value;
SetAttrValue
(
"
kEagerRuntime
"
, &value);
(*function_def.
mutable_attr
())[
"
_construction_context
"
] = value;
status->
status
=
tensorflow::unwrap
(
tensorflow::InputTFE_Context
(ctx))
->
AddFunctionDef
(function_def);
tensorflow::MaybeRaiseRegisteredFromTFStatus
(status.
get
());
return
;
},
pybind11::arg
(
"
ctx
"
),
pybind11::arg
(
"
function_def
"
));
m.
def
(
"
TFE_ContextGetFunctionDefNoSerialization
"
,
[](py::handle& ctx,
const
char
* function_name) -> tensorflow::FunctionDef {
tensorflow::Safe_TF_StatusPtr status =
tensorflow::make_safe
(
TF_NewStatus
());
const
tensorflow::FunctionDef* ctx_function_def =
tensorflow::unwrap
(
tensorflow::InputTFE_Context
(ctx))
->
FindFunctionDef
(function_name);
if
(ctx_function_def ==
nullptr
) {
status->
status
=
absl::NotFoundError
(
absl::StrCat
(
"
Unable to find FunctionDef with name:
"
, function_name));
tensorflow::MaybeRaiseRegisteredFromTFStatus
(status.
get
());
tensorflow::FunctionDef function_def;
return
function_def;
}
status->
status
=
absl::OkStatus
();
tensorflow::MaybeRaiseRegisteredFromTFStatus
(status.
get
());
return
*ctx_function_def;
});
#
else
//
Defining this function to make type checker happy, as there's an entry in
//
_pywrap_tfe.pyi.
m.
def
(
"
TFE_ContextGetFunctionDefNoSerialization
"
,
[](py::handle& ctx,
const
char
* function_name) ->
int
{
LOG
(
FATAL
) <<
"
This function cannot be called.
"
;
return
-
1
;
});
m.
def
(
"
TFE_ContextAddFunctionDefNoSerialization
"
,
//
Opensource fails whenever a protobuf is used as argument. The
//
disrepency in the type is to make opensource tests pass.
[](py::handle& ctx,
int
function_def) {
LOG
(
FATAL
) <<
"
This function cannot be called.
"
;
return
-
1
;
});
#
endif
m.
def
(
"
TFE_ContextGetGraphDebugInfo
"
,
[](py::handle& ctx,
const
char
* function_name, TF_Buffer& buf) {
tensorflow::Safe_TF_StatusPtr status =
tensorflow::make_safe
(
TF_NewStatus
());
TFE_ContextGetGraphDebugInfo
(
tensorflow::InputTFE_Context
(ctx),
function_name, &buf, status.
get
());
tensorflow::MaybeRaiseRegisteredFromTFStatus
(status.
get
());
});
m.
def
(
"
TFE_ContextRemoveFunction
"
, [](py::handle& ctx,
const
char
* name) {
tensorflow::Safe_TF_StatusPtr status =
tensorflow::make_safe
(
TF_NewStatus
());
TFE_ContextRemoveFunction
(
tensorflow::InputTFE_Context
(ctx), name,
status.
get
());
tensorflow::MaybeRaiseRegisteredFromTFStatus
(status.
get
());
});
m.
def
(
"
TFE_ContextHasFunction
"
, [](py::handle& ctx,
const
char
* name) {
tensorflow::Safe_TF_StatusPtr status =
tensorflow::make_safe
(
TF_NewStatus
());
auto
output =
TFE_ContextHasFunction
(
tensorflow::InputTFE_Context
(ctx), name);
tensorflow::MaybeRaiseRegisteredFromTFStatus
(status.
get
());
return
output;
});
m.
def
(
"
TFE_ContextListFunctionNames
"
, [](py::handle& ctx) {
return
tensorflow::unwrap
(
tensorflow::InputTFE_Context
(ctx))
->
ListFunctionNames
();
});
m.
def
(
"
TFE_ContextEnableRunMetadata
"
, [](py::handle& ctx) {
TFE_ContextEnableRunMetadata
(
tensorflow::InputTFE_Context
(ctx));
});
m.
def
(
"
TFE_ContextDisableRunMetadata
"
, [](py::handle& ctx) {
TFE_ContextEnableRunMetadata
(
tensorflow::InputTFE_Context
(ctx));
});
m.
def
(
"
TFE_ContextEnableGraphCollection
"
, [](py::handle& ctx) {
TFE_ContextEnableGraphCollection
(
tensorflow::InputTFE_Context
(ctx));
});
m.
def
(
"
TFE_ContextDisableGraphCollection
"
, [](py::handle& ctx) {
TFE_ContextDisableGraphCollection
(
tensorflow::InputTFE_Context
(ctx));
});
m.
def
(
"
TFE_ContextExportRunMetadata
"
, [](py::handle& ctx, TF_Buffer& buf) {
tensorflow::Safe_TF_StatusPtr status =
tensorflow::make_safe
(
TF_NewStatus
());
TFE_ContextExportRunMetadata
(
tensorflow::InputTFE_Context
(ctx), &buf,
status.
get
());
tensorflow::MaybeRaiseRegisteredFromTFStatus
(status.
get
());
});
m.
def
(
"
TFE_ContextClearCaches
"
, [](py::handle& o) {
TFE_ContextClearCaches
(
tensorflow::InputTFE_Context
(o));
});
m.
def
(
"
TFE_GetContextId
"
, [](py::handle& ctx) {
return
TFE_GetContextId
(
tensorflow::InputTFE_Context
(ctx));
});
m.
def
(
"
TFE_ContextGetDevicePlacementPolicy
"
, [](py::handle& ctx) {
return
TFE_ContextGetDevicePlacementPolicy
(
tensorflow::InputTFE_Context
(ctx));
});
m.
def
(
"
TFE_ContextSetThreadLocalDevicePlacementPolicy
"
,
[](py::handle& ctx, TFE_ContextDevicePlacementPolicy policy) {
TFE_ContextSetThreadLocalDevicePlacementPolicy
(
tensorflow::InputTFE_Context
(ctx), policy);
});
m.
def
(
"
TFE_ContextSetServerDef
"
, [](py::handle& ctx,
int
keep_alive_secs,
py::bytes proto) {
tensorflow::Safe_TF_StatusPtr status =
tensorflow::make_safe
(
TF_NewStatus
());
tensorflow::Safe_TF_BufferPtr buf =
tensorflow::make_safe
(
tensorflow::ProtoStringToTFBuffer
(proto.
ptr
()));
TFE_ContextSetServerDef
(
tensorflow::InputTFE_Context
(ctx), keep_alive_secs,
buf.
get
()->
data
, buf.
get
()->
length
, status.
get
());
tensorflow::MaybeRaiseRegisteredFromTFStatus
(status.
get
());
});
m.
def
(
"
TFE_ContextSetServerDefWithTimeoutAndRetries
"
,
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL