-
Notifications
You must be signed in to change notification settings - Fork 74k
/
c_api.cc
2703 lines (2387 loc) · 97.8 KB
/
c_api.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/c/c_api.h"
#include <algorithm>
#include <limits>
#include <memory>
#include <vector>
#include "absl/strings/match.h"
// Required for IS_MOBILE_PLATFORM
#include "tensorflow/core/platform/platform.h" // NOLINT
#if !defined(IS_MOBILE_PLATFORM) && !defined(IS_SLIM_BUILD)
#include "tensorflow/c/experimental/filesystem/modular_filesystem.h"
#include "tensorflow/cc/framework/gradients.h"
#include "tensorflow/cc/framework/ops.h"
#include "tensorflow/cc/framework/scope_internal.h"
#include "tensorflow/cc/ops/while_loop.h"
#include "tensorflow/cc/saved_model/loader.h"
#include "tensorflow/core/distributed_runtime/server_lib.h"
#include "tensorflow/core/framework/logging.h"
#include "tensorflow/core/framework/op_gen_lib.h"
#endif // !defined(IS_MOBILE_PLATFORM) && !defined(IS_SLIM_BUILD)
#include "tensorflow/c/c_api_internal.h"
#include "tensorflow/c/tf_status_internal.h"
#include "tensorflow/c/tf_tensor.h"
#include "tensorflow/core/common_runtime/device_mgr.h"
#include "tensorflow/core/common_runtime/eval_const_tensor.h"
#include "tensorflow/core/common_runtime/graph_constructor.h"
#include "tensorflow/core/common_runtime/shape_refiner.h"
#include "tensorflow/core/framework/allocation_description.pb.h"
#include "tensorflow/core/framework/kernel_def.pb.h"
#include "tensorflow/core/framework/log_memory.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor.pb.h" // NOLINT
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/framework/versions.pb.h"
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/graph/node_builder.h"
#include "tensorflow/core/graph/validate.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
#include "tensorflow/core/platform/coding.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/mem.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/str_util.h"
#include "tensorflow/core/platform/strcat.h"
#include "tensorflow/core/platform/stringpiece.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/public/version.h"
// The implementation below is at the top level instead of the
// brain namespace because we are defining 'extern "C"' functions.
using tensorflow::AllocationDescription;
using tensorflow::AttrValueMap;
using tensorflow::DataType;
using tensorflow::ExtendSessionGraphHelper;
using tensorflow::Graph;
using tensorflow::GraphDef;
using tensorflow::mutex_lock;
using tensorflow::NameRangeMap;
using tensorflow::NameRangesForNode;
using tensorflow::NewSession;
using tensorflow::Node;
using tensorflow::NodeBuilder;
using tensorflow::NodeDef;
using tensorflow::OpDef;
using tensorflow::OpRegistry;
using tensorflow::OutputTensor;
using tensorflow::PartialTensorShape;
using tensorflow::RunMetadata;
using tensorflow::RunOptions;
using tensorflow::Session;
using tensorflow::Status;
using tensorflow::string;
using tensorflow::Tensor;
using tensorflow::TensorBuffer;
using tensorflow::TensorId;
using tensorflow::TensorShape;
using tensorflow::TensorShapeProto;
using tensorflow::VersionDef;
using tensorflow::errors::FailedPrecondition;
using tensorflow::errors::InvalidArgument;
using tensorflow::errors::OutOfRange;
using tensorflow::gtl::ArraySlice;
using tensorflow::strings::StrCat;
extern "C" {
// --------------------------------------------------------------------------
const char* TF_Version() { return TF_VERSION_STRING; }
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
TF_SessionOptions* TF_NewSessionOptions() { return new TF_SessionOptions; }
void TF_DeleteSessionOptions(TF_SessionOptions* opt) { delete opt; }
void TF_SetTarget(TF_SessionOptions* options, const char* target) {
options->options.target = target;
}
void TF_SetConfig(TF_SessionOptions* options, const void* proto,
size_t proto_len, TF_Status* status) {
if (!options->options.config.ParseFromArray(proto, proto_len)) {
status->status = InvalidArgument("Unparseable ConfigProto");
}
}
// --------------------------------------------------------------------------
TF_Buffer* TF_NewBuffer() { return new TF_Buffer{nullptr, 0, nullptr}; }
TF_Buffer* TF_NewBufferFromString(const void* proto, size_t proto_len) {
void* copy = tensorflow::port::Malloc(proto_len);
memcpy(copy, proto, proto_len);
TF_Buffer* buf = new TF_Buffer;
buf->data = copy;
buf->length = proto_len;
buf->data_deallocator = [](void* data, size_t length) {
tensorflow::port::Free(data);
};
return buf;
}
void TF_DeleteBuffer(TF_Buffer* buffer) {
if (buffer == nullptr) return;
if (buffer->data_deallocator != nullptr) {
(*buffer->data_deallocator)(const_cast<void*>(buffer->data),
buffer->length);
}
delete buffer;
}
TF_Buffer TF_GetBuffer(TF_Buffer* buffer) { return *buffer; }
void TF_TensorFromProto(const TF_Buffer* from, TF_Tensor* to,
TF_Status* status) {
TF_SetStatus(status, TF_OK, "");
tensorflow::TensorProto from_tensor_proto;
status->status = BufferToMessage(from, &from_tensor_proto);
if (!status->status.ok()) {
return;
}
status->status =
tensorflow::down_cast<tensorflow::TensorInterface*>(to->tensor)
->FromProto(from_tensor_proto);
}
// --------------------------------------------------------------------------
TF_DeprecatedSession* TF_NewDeprecatedSession(const TF_SessionOptions* opt,
TF_Status* status) {
Session* session;
status->status = NewSession(opt->options, &session);
if (status->status.ok()) {
return new TF_DeprecatedSession({session});
} else {
DCHECK_EQ(nullptr, session);
return nullptr;
}
}
void TF_CloseDeprecatedSession(TF_DeprecatedSession* s, TF_Status* status) {
status->status = s->session->Close();
}
void TF_DeleteDeprecatedSession(TF_DeprecatedSession* s, TF_Status* status) {
status->status = ::tensorflow::OkStatus();
if (s == nullptr) return;
delete s->session;
delete s;
}
void TF_ExtendGraph(TF_DeprecatedSession* s, const void* proto,
size_t proto_len, TF_Status* status) {
GraphDef g;
if (!tensorflow::ParseProtoUnlimited(&g, proto, proto_len)) {
status->status = InvalidArgument("Invalid GraphDef");
return;
}
status->status = s->session->Extend(g);
}
} // end extern "C"
// Reset helper for converting character arrays to string vectors.
static void TF_Reset_Helper(const TF_SessionOptions* opt,
const char** containers, int ncontainers,
TF_Status* status) {
std::vector<string> container_names(ncontainers);
for (int i = 0; i < ncontainers; ++i) {
container_names[i] = containers[i];
}
status->status = Reset(opt->options, container_names);
}
extern "C" {
void TF_Reset(const TF_SessionOptions* opt, const char** containers,
int ncontainers, TF_Status* status) {
TF_Reset_Helper(opt, containers, ncontainers, status);
}
} // end extern "C"
namespace tensorflow {
Status MessageToBuffer(const tensorflow::protobuf::MessageLite& in,
TF_Buffer* out) {
if (out->data != nullptr) {
return InvalidArgument("Passing non-empty TF_Buffer is invalid.");
}
const size_t proto_size = in.ByteSizeLong();
void* buf = port::Malloc(proto_size);
if (buf == nullptr) {
return tensorflow::errors::ResourceExhausted(
"Failed to allocate memory to serialize message of type '",
in.GetTypeName(), "' and size ", proto_size);
}
if (!in.SerializeWithCachedSizesToArray(static_cast<uint8*>(buf))) {
port::Free(buf);
return InvalidArgument("Unable to serialize ", in.GetTypeName(),
" protocol buffer, perhaps the serialized size (",
proto_size, " bytes) is too large?");
}
out->data = buf;
out->length = proto_size;
out->data_deallocator = [](void* data, size_t length) { port::Free(data); };
return OkStatus();
}
Status BufferToMessage(const TF_Buffer* in,
tensorflow::protobuf::MessageLite* out) {
if (in == nullptr || !out->ParseFromArray(in->data, in->length)) {
return errors::InvalidArgument("Unparseable ", out->GetTypeName(),
" proto");
}
return OkStatus();
}
void RecordMutation(TF_Graph* graph, const TF_Operation& op,
const char* mutation_type) {
// If any session has already run this node_id, mark this session as
// unrunnable.
for (auto it : graph->sessions) {
mutex_lock session_lock(it.first->mu);
if (it.first->last_num_graph_nodes > op.node.id()) {
it.second = strings::StrCat(
"Operation '", op.node.DebugString(), "' was changed by ",
mutation_type,
" after it was run by a session. This mutation will have no effect, "
"and will trigger an error in the future. Either don't modify "
"nodes after running them or create a new session.");
}
}
}
namespace {
// Helper method that creates a shape handle for a shape described by dims.
tensorflow::shape_inference::ShapeHandle ShapeHandleFromDims(
tensorflow::shape_inference::InferenceContext* ic, int num_dims,
const int64_t* dims) {
if (num_dims != -1) {
std::vector<tensorflow::shape_inference::DimensionHandle> dim_vec;
dim_vec.reserve(num_dims);
for (int i = 0; i < num_dims; ++i) {
dim_vec.push_back(ic->MakeDim(dims[i]));
}
return ic->MakeShape(dim_vec);
} else {
return ic->UnknownShape();
}
}
} // namespace
void TF_GraphSetOutputHandleShapesAndTypes(TF_Graph* graph, TF_Output output,
int num_shapes_and_types,
const int64_t** shapes,
const int* ranks,
const TF_DataType* types,
TF_Status* status) {
Node* node = &output.oper->node;
mutex_lock l(graph->mu);
tensorflow::shape_inference::InferenceContext* ic =
graph->refiner.GetContext(node);
if (ic == nullptr) {
status->status =
InvalidArgument("Node ", node->name(), " was not found in the graph");
return;
}
auto shape_and_type_vec =
std::vector<tensorflow::shape_inference::ShapeAndType>(
num_shapes_and_types);
for (int i = 0; i < num_shapes_and_types; ++i) {
tensorflow::shape_inference::ShapeHandle shape_handle =
ShapeHandleFromDims(ic, ranks[i], shapes[i]);
shape_and_type_vec[i] = tensorflow::shape_inference::ShapeAndType(
shape_handle, static_cast<DataType>(types[i]));
}
ic->set_output_handle_shapes_and_types(output.index, shape_and_type_vec);
}
// Helpers for loading a TensorFlow plugin (a .so file).
Status LoadDynamicLibrary(const char* library_filename, void** result,
const void** buf, size_t* len);
// TODO(josh11b,mrry): Change Session to be able to use a Graph*
// directly, instead of requiring us to serialize to a GraphDef and
// call Session::Extend().
bool ExtendSessionGraphHelper(TF_Session* session, TF_Status* status) {
if (session->graph != nullptr) {
// Take the graph lock before the session lock to avoid deadlock. This is
// safe since session->graph does not change.
session->graph->mu.lock();
mutex_lock session_lock(session->mu);
const Graph& graph = session->graph->graph;
const string& mutation_warning = session->graph->sessions[session];
if (!mutation_warning.empty()) {
// TODO(b/74949947): turn this back into an error status
LOG(WARNING) << mutation_warning;
session->graph->sessions[session].clear();
}
const auto num_nodes = graph.num_node_ids();
if (session->last_num_graph_nodes < num_nodes) {
// TODO(nolivia): check this on a subset of the graph instead of all of
// it.
status->status = graph::ValidateGraphHasNoCycle(session->graph->graph);
if (!status->status.ok()) {
session->graph->mu.unlock();
return false;
}
GraphDef graph_def;
*graph_def.mutable_versions() = graph.versions();
// Fill graph_def with nodes with ids in the range
// [session->last_num_graph_nodes, num_nodes), that is the nodes
// added since the last TF_SessionRun() call.
for (auto id = session->last_num_graph_nodes; id < num_nodes; ++id) {
Node* const node = graph.FindNodeId(id);
if (node != nullptr && node->IsOp()) {
NodeDef* const node_def = graph_def.add_node();
*node_def = node->def();
}
}
*graph_def.mutable_library() = graph.flib_def().ToProto();
session->graph->mu.unlock();
status->status = session->session->Extend(std::move(graph_def));
if (!status->status.ok()) {
// Contract is we always delete input_values[i].
return false;
}
// Note: session->session is not modified if Extend() fails, so
// we only set last_num_graph_nodes if it succeeds.
session->last_num_graph_nodes = num_nodes;
} else {
session->graph->mu.unlock();
}
}
return true;
}
} // namespace tensorflow
static void TF_Run_Setup(int noutputs, TF_Tensor** c_outputs,
TF_Status* status) {
status->status = ::tensorflow::OkStatus();
for (int i = 0; i < noutputs; ++i) {
c_outputs[i] = nullptr;
}
}
// TF_TensorToTensorV1 decodes a string serialization to DT_RESOURCE.
// In the TFv1 convention, TF_Tensor can hold a string serialization of
// DT_RESOURCE. The string serialization is converted back to a
// ResourceHandle during Session run where the TF_Tensor is converted to a
// Tensor.
// TFv2 does not depend on this conversion. There is no matching
// TF_TensorFromTensorV1 because the conversion to string is performed by the
// python side of Session.
static Status TF_TensorToTensorV1(const TF_Tensor* src, Tensor* dst) {
Status status = TF_TensorToTensor(src, dst);
if (!status.ok()) {
return status;
}
if (dst->dtype() == tensorflow::DT_RESOURCE) {
const auto tensor_interface =
tensorflow::down_cast<const tensorflow::TensorInterface*>(src->tensor);
if (dst->dims() != 0) {
return InvalidArgument(
"Malformed TF_RESOURCE tensor: expected a scalar, got a tensor with "
"shape ",
dst->shape().DebugString());
}
*dst = tensorflow::Tensor(tensorflow::DT_RESOURCE, dst->shape());
if (!dst->scalar<tensorflow::ResourceHandle>()().ParseFromString(
string(static_cast<const char*>(tensor_interface->Data()),
tensor_interface->ByteSize()))) {
return InvalidArgument(
"Malformed TF_RESOURCE tensor: unable to parse resource handle");
}
return ::tensorflow::OkStatus();
}
return ::tensorflow::OkStatus();
}
static bool TF_Run_Inputs(TF_Tensor* const* c_inputs,
std::vector<std::pair<string, Tensor>>* input_pairs,
TF_Status* status) {
const int ninputs = input_pairs->size();
for (int i = 0; i < ninputs; ++i) {
status->status =
TF_TensorToTensorV1(c_inputs[i], &(*input_pairs)[i].second);
if (!status->status.ok()) return false;
}
return true;
}
// Create an empty tensor of type 'dtype'. 'shape' can be arbitrary, but has to
// result in a zero-sized tensor.
static TF_Tensor* EmptyTensor(TF_DataType dtype,
const tensorflow::TensorShape& shape) {
static char empty;
int64_t nelems = 1;
std::vector<int64_t> dims;
dims.reserve(shape.dims());
for (int i = 0; i < shape.dims(); ++i) {
dims.push_back(shape.dim_size(i));
nelems *= shape.dim_size(i);
}
CHECK_EQ(nelems, 0);
return TF_NewTensor(
dtype, reinterpret_cast<const int64_t*>(dims.data()), shape.dims(),
reinterpret_cast<void*>(&empty), 0, [](void*, size_t, void*) {}, nullptr);
}
static void TF_Run_Helper(
Session* session, const char* handle, const TF_Buffer* run_options,
// Input tensors
const std::vector<std::pair<string, Tensor>>& input_pairs,
// Output tensors
const std::vector<string>& output_tensor_names, TF_Tensor** c_outputs,
// Target nodes
const std::vector<string>& target_oper_names, TF_Buffer* run_metadata,
TF_Status* status) {
const int noutputs = output_tensor_names.size();
std::vector<Tensor> outputs(noutputs);
Status result;
if (handle == nullptr) {
RunOptions run_options_proto;
if (run_options != nullptr && !run_options_proto.ParseFromArray(
run_options->data, run_options->length)) {
status->status = InvalidArgument("Unparseable RunOptions proto");
return;
}
if (run_metadata != nullptr && run_metadata->data != nullptr) {
status->status =
InvalidArgument("Passing non-empty run_metadata is invalid.");
return;
}
RunMetadata run_metadata_proto;
result = session->Run(run_options_proto, input_pairs, output_tensor_names,
target_oper_names, &outputs, &run_metadata_proto);
// Serialize back to upstream client, who now owns the new buffer
if (run_metadata != nullptr) {
status->status = MessageToBuffer(run_metadata_proto, run_metadata);
if (!status->status.ok()) return;
}
} else {
// NOTE(zongheng): PRun does not support RunOptions yet.
result = session->PRun(handle, input_pairs, output_tensor_names, &outputs);
}
if (!result.ok()) {
status->status = result;
return;
}
// Store results in c_outputs[]
for (int i = 0; i < noutputs; ++i) {
const Tensor& src = outputs[i];
if (!src.IsInitialized() || src.NumElements() == 0) {
c_outputs[i] =
EmptyTensor(static_cast<TF_DataType>(src.dtype()), src.shape());
continue;
}
c_outputs[i] = TF_TensorFromTensor(src, &status->status);
if (!status->status.ok()) return;
}
}
extern "C" {
void TF_Run(TF_DeprecatedSession* s, const TF_Buffer* run_options,
// Input tensors
const char** c_input_names, TF_Tensor** c_inputs, int ninputs,
// Output tensors
const char** c_output_names, TF_Tensor** c_outputs, int noutputs,
// Target nodes
const char** c_target_oper_names, int ntargets,
TF_Buffer* run_metadata, TF_Status* status) {
TF_Run_Setup(noutputs, c_outputs, status);
std::vector<std::pair<string, Tensor>> input_pairs(ninputs);
if (!TF_Run_Inputs(c_inputs, &input_pairs, status)) return;
for (int i = 0; i < ninputs; ++i) {
input_pairs[i].first = c_input_names[i];
}
std::vector<string> output_names(noutputs);
for (int i = 0; i < noutputs; ++i) {
output_names[i] = c_output_names[i];
}
std::vector<string> target_oper_names(ntargets);
for (int i = 0; i < ntargets; ++i) {
target_oper_names[i] = c_target_oper_names[i];
}
TF_Run_Helper(s->session, nullptr, run_options, input_pairs, output_names,
c_outputs, target_oper_names, run_metadata, status);
}
void TF_PRunSetup(TF_DeprecatedSession* s,
// Input names
const char** c_input_names, int ninputs,
// Output names
const char** c_output_names, int noutputs,
// Target nodes
const char** c_target_oper_names, int ntargets,
const char** handle, TF_Status* status) {
*handle = nullptr;
std::vector<string> input_names(ninputs);
std::vector<string> output_names(noutputs);
std::vector<string> target_oper_names(ntargets);
for (int i = 0; i < ninputs; ++i) {
input_names[i] = c_input_names[i];
}
for (int i = 0; i < noutputs; ++i) {
output_names[i] = c_output_names[i];
}
for (int i = 0; i < ntargets; ++i) {
target_oper_names[i] = c_target_oper_names[i];
}
string new_handle;
status->status = s->session->PRunSetup(input_names, output_names,
target_oper_names, &new_handle);
if (status->status.ok()) {
char* buf = new char[new_handle.size() + 1];
memcpy(buf, new_handle.c_str(), new_handle.size() + 1);
*handle = buf;
}
}
void TF_PRun(TF_DeprecatedSession* s, const char* handle,
// Input tensors
const char** c_input_names, TF_Tensor** c_inputs, int ninputs,
// Output tensors
const char** c_output_names, TF_Tensor** c_outputs, int noutputs,
// Target nodes
const char** c_target_oper_names, int ntargets,
TF_Status* status) {
TF_Run_Setup(noutputs, c_outputs, status);
std::vector<std::pair<string, Tensor>> input_pairs(ninputs);
if (!TF_Run_Inputs(c_inputs, &input_pairs, status)) return;
for (int i = 0; i < ninputs; ++i) {
input_pairs[i].first = c_input_names[i];
}
std::vector<string> output_names(noutputs);
for (int i = 0; i < noutputs; ++i) {
output_names[i] = c_output_names[i];
}
std::vector<string> target_oper_names(ntargets);
for (int i = 0; i < ntargets; ++i) {
target_oper_names[i] = c_target_oper_names[i];
}
TF_Run_Helper(s->session, handle, nullptr, input_pairs, output_names,
c_outputs, target_oper_names, nullptr, status);
}
TF_Library* TF_LoadLibrary(const char* library_filename, TF_Status* status) {
TF_Library* lib_handle = new TF_Library;
status->status = tensorflow::LoadDynamicLibrary(
library_filename, &lib_handle->lib_handle, &lib_handle->op_list.data,
&lib_handle->op_list.length);
if (!status->status.ok()) {
delete lib_handle;
return nullptr;
}
return lib_handle;
}
TF_Buffer TF_GetOpList(TF_Library* lib_handle) { return lib_handle->op_list; }
void TF_DeleteLibraryHandle(TF_Library* lib_handle) {
if (lib_handle == nullptr) return;
tensorflow::port::Free(const_cast<void*>(lib_handle->op_list.data));
delete lib_handle;
}
TF_Buffer* TF_GetAllOpList() {
std::vector<tensorflow::OpDef> op_defs;
tensorflow::OpRegistry::Global()->GetRegisteredOps(&op_defs);
tensorflow::OpList op_list;
for (const auto& op : op_defs) {
*(op_list.add_op()) = op;
}
TF_Buffer* ret = TF_NewBuffer();
TF_CHECK_OK(MessageToBuffer(op_list, ret));
return ret;
}
// --------------------------------------------------------------------------
// ListDevices & SessionListDevices API
void TF_DeleteDeviceList(TF_DeviceList* list) { delete list; }
TF_DeviceList* TF_SessionListDevices(TF_Session* session, TF_Status* status) {
TF_DeviceList* response = new TF_DeviceList;
if (session && session->session)
status->status = session->session->ListDevices(&response->response);
return response;
}
TF_DeviceList* TF_DeprecatedSessionListDevices(TF_DeprecatedSession* session,
TF_Status* status) {
TF_DeviceList* response = new TF_DeviceList;
if (session && session->session)
status->status = session->session->ListDevices(&response->response);
return response;
}
int TF_DeviceListCount(const TF_DeviceList* list) {
return list->response.size();
}
#define TF_DEVICELIST_METHOD(return_type, method_name, accessor, err_val) \
return_type method_name(const TF_DeviceList* list, const int index, \
TF_Status* status) { \
if (list == nullptr) { \
status->status = InvalidArgument("list is null!"); \
return err_val; \
} \
if (index < 0 || index >= list->response.size()) { \
status->status = InvalidArgument("index out of bounds"); \
return err_val; \
} \
status->status = ::tensorflow::OkStatus(); \
return list->response[index].accessor; \
}
TF_DEVICELIST_METHOD(const char*, TF_DeviceListName, name().c_str(), nullptr);
TF_DEVICELIST_METHOD(const char*, TF_DeviceListType, device_type().c_str(),
nullptr);
TF_DEVICELIST_METHOD(int64_t, TF_DeviceListMemoryBytes, memory_limit(), -1);
TF_DEVICELIST_METHOD(uint64_t, TF_DeviceListIncarnation, incarnation(), 0);
#undef TF_DEVICELIST_METHOD
} // end extern "C"
// --------------------------------------------------------------------------
// New Graph and Session API
// Helper functions -----------------------------------------------------------
namespace {
TF_Operation* ToOperation(Node* node) {
return static_cast<TF_Operation*>(static_cast<void*>(node));
}
string OutputName(const TF_Output& output) {
return StrCat(output.oper->node.name(), ":", output.index);
}
const tensorflow::AttrValue* GetAttrValue(TF_Operation* oper,
const char* attr_name,
TF_Status* status) {
const tensorflow::AttrValue* attr = oper->node.attrs().Find(attr_name);
if (attr == nullptr) {
status->status = InvalidArgument("Operation '", oper->node.name(),
"' has no attr named '", attr_name, "'.");
}
return attr;
}
TensorId ToTensorId(const TF_Output& output) {
return TensorId(output.oper->node.name(), output.index);
}
#if !defined(IS_MOBILE_PLATFORM) && !defined(IS_SLIM_BUILD)
std::vector<tensorflow::Output> OutputsFromTFOutputs(TF_Output* tf_outputs,
int n) {
std::vector<tensorflow::Output> outputs(n);
for (int i = 0; i < n; ++i) {
outputs[i] =
tensorflow::Output(&tf_outputs[i].oper->node, tf_outputs[i].index);
}
return outputs;
}
void TFOutputsFromOutputs(const std::vector<tensorflow::Output>& outputs,
TF_Output* tf_outputs) {
for (int i = 0; i < outputs.size(); i++) {
tf_outputs[i].oper = ToOperation(outputs[i].node());
tf_outputs[i].index = outputs[i].index();
}
}
#endif // !defined(IS_MOBILE_PLATFORM) && !defined(IS_SLIM_BUILD)
} // namespace
// Shape functions -----------------------------------------------------------
void TF_GraphSetTensorShape(TF_Graph* graph, TF_Output output,
const int64_t* dims, const int num_dims,
TF_Status* status) {
Node* node = &output.oper->node;
mutex_lock l(graph->mu);
tensorflow::shape_inference::InferenceContext* ic =
graph->refiner.GetContext(node);
if (ic == nullptr) {
status->status =
InvalidArgument("Node ", node->name(), " was not found in the graph");
return;
}
tensorflow::shape_inference::ShapeHandle new_shape =
tensorflow::ShapeHandleFromDims(ic, num_dims, dims);
status->status = graph->refiner.SetShape(node, output.index, new_shape);
}
int TF_GraphGetTensorNumDims(TF_Graph* graph, TF_Output output,
TF_Status* status) {
Node* node = &output.oper->node;
mutex_lock l(graph->mu);
tensorflow::shape_inference::InferenceContext* ic =
graph->refiner.GetContext(node);
if (ic == nullptr) {
status->status =
InvalidArgument("Node ", node->name(), " was not found in the graph");
return -1;
}
tensorflow::shape_inference::ShapeHandle shape = ic->output(output.index);
// Unknown rank means the number of dimensions is -1.
if (!ic->RankKnown(shape)) {
return -1;
}
return ic->Rank(shape);
}
void TF_GraphGetTensorShape(TF_Graph* graph, TF_Output output, int64_t* dims,
int num_dims, TF_Status* status) {
Node* node = &output.oper->node;
mutex_lock l(graph->mu);
tensorflow::shape_inference::InferenceContext* ic =
graph->refiner.GetContext(node);
if (ic == nullptr) {
status->status =
InvalidArgument("Node ", node->name(), " was not found in the graph");
return;
}
tensorflow::shape_inference::ShapeHandle shape = ic->output(output.index);
int rank = -1;
if (ic->RankKnown(shape)) {
rank = ic->Rank(shape);
}
if (num_dims != rank) {
status->status = InvalidArgument("Expected rank is ", num_dims,
" but actual rank is ", rank);
return;
}
if (num_dims == 0) {
// Output shape is a scalar.
return;
}
// Rank is greater than 0, so fill in the values, if known, and
// -1 for unknown values.
for (int i = 0; i < num_dims; ++i) {
auto dim = ic->Dim(shape, i);
int64_t value = -1;
if (ic->ValueKnown(dim)) {
value = ic->Value(dim);
}
dims[i] = value;
}
}
// TF_OperationDescription functions ------------------------------------------
extern "C" {
TF_OperationDescription* TF_NewOperationLocked(TF_Graph* graph,
const char* op_type,
const char* oper_name)
TF_EXCLUSIVE_LOCKS_REQUIRED(graph->mu) {
return new TF_OperationDescription(graph, op_type, oper_name);
}
TF_OperationDescription* TF_NewOperation(TF_Graph* graph, const char* op_type,
const char* oper_name) {
mutex_lock l(graph->mu);
return TF_NewOperationLocked(graph, op_type, oper_name);
}
void TF_SetDevice(TF_OperationDescription* desc, const char* device) {
desc->node_builder.Device(device);
}
void TF_AddInput(TF_OperationDescription* desc, TF_Output input) {
desc->node_builder.Input(&input.oper->node, input.index);
}
void TF_AddInputList(TF_OperationDescription* desc, const TF_Output* inputs,
int num_inputs) {
std::vector<NodeBuilder::NodeOut> input_list;
input_list.reserve(num_inputs);
for (int i = 0; i < num_inputs; ++i) {
input_list.emplace_back(&inputs[i].oper->node, inputs[i].index);
}
desc->node_builder.Input(input_list);
}
void TF_AddControlInput(TF_OperationDescription* desc, TF_Operation* input) {
desc->node_builder.ControlInput(&input->node);
}
void TF_ColocateWith(TF_OperationDescription* desc, TF_Operation* op) {
desc->colocation_constraints.emplace(
StrCat(tensorflow::kColocationGroupPrefix, op->node.name()));
}
void TF_SetAttrString(TF_OperationDescription* desc, const char* attr_name,
const void* value, size_t length) {
tensorflow::StringPiece s(static_cast<const char*>(value), length);
desc->node_builder.Attr(attr_name, s);
}
void TF_SetAttrStringList(TF_OperationDescription* desc, const char* attr_name,
const void* const* values, const size_t* lengths,
int num_values) {
if (strcmp(attr_name, tensorflow::kColocationAttrName) == 0) {
desc->colocation_constraints.clear();
for (int i = 0; i < num_values; ++i) {
desc->colocation_constraints.emplace(static_cast<const char*>(values[i]),
lengths[i]);
}
} else {
std::vector<tensorflow::StringPiece> v;
v.reserve(num_values);
for (int i = 0; i < num_values; ++i) {
v.emplace_back(static_cast<const char*>(values[i]), lengths[i]);
}
desc->node_builder.Attr(attr_name, v);
}
}
void TF_SetAttrInt(TF_OperationDescription* desc, const char* attr_name,
int64_t value) {
desc->node_builder.Attr(attr_name, static_cast<int64_t>(value));
}
void TF_SetAttrIntList(TF_OperationDescription* desc, const char* attr_name,
const int64_t* values, int num_values) {
desc->node_builder.Attr(
attr_name, ArraySlice<const int64_t>(
reinterpret_cast<const int64_t*>(values), num_values));
}
void TF_SetAttrFloat(TF_OperationDescription* desc, const char* attr_name,
float value) {
desc->node_builder.Attr(attr_name, value);
}
void TF_SetAttrFloatList(TF_OperationDescription* desc, const char* attr_name,
const float* values, int num_values) {
desc->node_builder.Attr(attr_name,
ArraySlice<const float>(values, num_values));
}
void TF_SetAttrBool(TF_OperationDescription* desc, const char* attr_name,
unsigned char value) {
desc->node_builder.Attr(attr_name, static_cast<bool>(value));
}
void TF_SetAttrBoolList(TF_OperationDescription* desc, const char* attr_name,
const unsigned char* values, int num_values) {
std::unique_ptr<bool[]> b(new bool[num_values]);
for (int i = 0; i < num_values; ++i) {
b[i] = values[i];
}
desc->node_builder.Attr(attr_name,
ArraySlice<const bool>(b.get(), num_values));
}
void TF_SetAttrType(TF_OperationDescription* desc, const char* attr_name,
TF_DataType value) {
desc->node_builder.Attr(attr_name, static_cast<DataType>(value));
}
void TF_SetAttrTypeList(TF_OperationDescription* desc, const char* attr_name,
const TF_DataType* values, int num_values) {
desc->node_builder.Attr(
attr_name, ArraySlice<const DataType>(
reinterpret_cast<const DataType*>(values), num_values));
}
void TF_SetAttrPlaceholder(TF_OperationDescription* desc, const char* attr_name,
const char* placeholder) {
tensorflow::AttrValue attr_value;
attr_value.set_placeholder(placeholder);
desc->node_builder.Attr(attr_name, attr_value);
}
void TF_SetAttrFuncName(TF_OperationDescription* desc, const char* attr_name,
const char* value, size_t length) {
tensorflow::NameAttrList func_name;
func_name.set_name(string(value, value + length));
desc->node_builder.Attr(attr_name, func_name);
}
void TF_SetAttrShape(TF_OperationDescription* desc, const char* attr_name,
const int64_t* dims, int num_dims) {
PartialTensorShape shape;
if (num_dims >= 0) {
shape = PartialTensorShape(
ArraySlice<int64_t>(reinterpret_cast<const int64_t*>(dims), num_dims));
}
desc->node_builder.Attr(attr_name, shape);
}
void TF_SetAttrShapeList(TF_OperationDescription* desc, const char* attr_name,
const int64_t* const* dims, const int* num_dims,
int num_shapes) {
std::vector<PartialTensorShape> shapes;
shapes.reserve(num_shapes);
for (int i = 0; i < num_shapes; ++i) {
if (num_dims[i] < 0) {
shapes.emplace_back();
} else {
shapes.emplace_back(ArraySlice<int64_t>(
reinterpret_cast<const int64_t*>(dims[i]), num_dims[i]));
}
}
desc->node_builder.Attr(attr_name, shapes);
}
void TF_SetAttrTensorShapeProto(TF_OperationDescription* desc,
const char* attr_name, const void* proto,
size_t proto_len, TF_Status* status) {
// shape.ParseFromArray takes an int as length, this function takes size_t,
// make sure there is no information loss.
if (proto_len > std::numeric_limits<int>::max()) {
status->status = InvalidArgument(
"proto_len (", proto_len,
" bytes) is too large to be parsed by the protocol buffer library");
return;
}
TensorShapeProto shape;