This repository has been archived by the owner on Jan 3, 2023. It is now read-only.
/
serializer.cpp
3709 lines (3603 loc) · 139 KB
/
serializer.cpp
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-2020 Intel Corporation
//
// 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 <fstream>
#include <functional>
#include <queue>
#include <stack>
#include "ngraph/attribute_visitor.hpp"
#include "ngraph/cpio.hpp"
#include "ngraph/env_util.hpp"
#include "ngraph/factory.hpp"
#include "ngraph/file_util.hpp"
#include "ngraph/graph_util.hpp"
#include "ngraph/log.hpp"
#include "ngraph/ops.hpp"
#include "ngraph/provenance.hpp"
#include "ngraph/serializer.hpp"
#include "ngraph/util.hpp"
#include "nlohmann/json.hpp"
using namespace ngraph;
using namespace std;
using json = nlohmann::json;
using const_data_callback_t = shared_ptr<Node>(const string&, const element::Type&, const Shape&);
static json write_element_type(const ngraph::element::Type& n);
static element::Type read_element_type(json j);
static json write_partial_shape(const PartialShape& s);
static PartialShape read_partial_shape(json j);
namespace
{
#define OBSOLETE_OPS \
NGRAPH_OP(Add, 0) \
NGRAPH_OP(And, 0) \
NGRAPH_OP(Divide, 0) \
NGRAPH_OP(Equal, 0) \
NGRAPH_OP(GetOutputElement, 0) \
NGRAPH_OP(Greater, 0) \
NGRAPH_OP(GreaterEq, 0) \
NGRAPH_OP(Less, 0) \
NGRAPH_OP(LessEq, 0) \
NGRAPH_OP(Maximum, 0) \
NGRAPH_OP(Minimum, 0) \
NGRAPH_OP(Multiply, 0) \
NGRAPH_OP(Not, 0) \
NGRAPH_OP(NotEqual, 0) \
NGRAPH_OP(Or, 0) \
NGRAPH_OP(Power, 0) \
NGRAPH_OP(Subtract, 0) \
NGRAPH_OP(Xor, 0)
// This expands the op list in op_tbl.hpp into a list of enumerations that look like this:
// Abs,
// Acos,
// ...
enum class OP_TYPEID
{
#define NGRAPH_OP(NAME, VERSION) NAME##_v##VERSION,
#include "ngraph/op_version_tbl.hpp"
OBSOLETE_OPS
#undef NGRAPH_OP
UnknownOp
};
}
static OP_TYPEID get_typeid(const string& type_info)
{
// This expands the op list in op_tbl.hpp into a list of enumerations that look like this:
// {"Abs_v0", OP_TYPEID::Abs},
// {"Acos_v0", OP_TYPEID::Acos},
// ...
static const map<string, OP_TYPEID> type_info_map{
#define NGRAPH_OP(NAME, VERSION) {#NAME "_v" #VERSION, OP_TYPEID::NAME##_v##VERSION},
#include "ngraph/op_version_tbl.hpp"
// Still need to deserialize GetOutputElement because it may be in some old json files
// This is just to handle such cases.
OBSOLETE_OPS
#undef NGRAPH_OP
};
OP_TYPEID rc = OP_TYPEID::UnknownOp;
auto it = type_info_map.find(type_info);
if (it != type_info_map.end())
{
rc = it->second;
}
return rc;
}
bool has_key(json j, const std::string& key)
{
return j.count(key) != 0;
}
template <typename T>
T get_or_default(json j, const std::string& key, const T& default_value)
{
return has_key(j, key) ? j.at(key).get<T>() : default_value;
}
class JSONAttributeSerializer : public AttributeVisitor
{
public:
JSONAttributeSerializer(json& j)
: m_json(j)
{
}
void on_adapter(const std::string& name, ValueAccessor<void>& adapter) override
{
NGRAPH_CHECK(false, "Adapter ", adapter.get_type_info().name, " is not handled");
}
void on_adapter(const std::string& name, ValueAccessor<bool>& adapter) override
{
m_json[name] = adapter.get();
}
void on_adapter(const std::string& name, ValueAccessor<std::string>& adapter) override
{
m_json[name] = adapter.get();
}
void on_adapter(const std::string& name, ValueAccessor<int64_t>& adapter) override
{
m_json[name] = adapter.get();
}
void on_adapter(const std::string& name, ValueAccessor<double>& adapter) override
{
m_json[name] = adapter.get();
}
void on_adapter(const std::string& name, ValueAccessor<std::vector<int64_t>>& adapter) override
{
m_json[name] = adapter.get();
}
void on_adapter(const std::string& name, ValueAccessor<std::vector<uint64_t>>& adapter) override
{
m_json[name] = adapter.get();
}
void on_adapter(const std::string& name, ValueAccessor<std::vector<float>>& adapter) override
{
m_json[name] = adapter.get();
}
void on_adapter(const std::string& name,
ValueAccessor<std::vector<std::string>>& adapter) override
{
m_json[name] = adapter.get();
}
protected:
json& m_json;
};
class JSONSerializer
{
public:
void set_indent(size_t indent) { m_indent = indent; }
void set_serialize_output_shapes(bool serialize_output_shapes)
{
m_serialize_output_shapes = serialize_output_shapes;
}
void set_binary_constant_data(bool binary_constant_data)
{
m_binary_constant_data = binary_constant_data;
}
json serialize_function(const Function& function);
json serialize_output(const Output<Node>& output);
json serialize_parameter_vector(const ParameterVector& parameters);
json serialize_output_vector(const OutputVector& output_vector);
json serialize_node(const Node& node);
json serialize_axis_set(const AxisSet& axis_set);
json serialize_tensor_iterator_input_description(
const std::shared_ptr<op::v0::TensorIterator::InputDescription>&);
json serialize_tensor_iterator_output_description(
const std::shared_ptr<op::v0::TensorIterator::OutputDescription>&);
protected:
size_t m_indent{0};
bool m_serialize_output_shapes{false};
bool m_binary_constant_data{false};
json m_json_nodes;
};
class JSONAttributeDeserializer : public AttributeVisitor
{
public:
JSONAttributeDeserializer(json& j)
: m_json(j)
{
}
void on_adapter(const std::string& name, ValueAccessor<void>& adapter) override
{
NGRAPH_CHECK(false, "Adapter ", adapter.get_type_info().name, " is not handled");
}
void on_adapter(const std::string& name, ValueAccessor<std::string>& adapter) override
{
if (has_key(m_json, name))
{
adapter.set(m_json.at(name).get<std::string>());
}
}
void on_adapter(const std::string& name, ValueAccessor<bool>& adapter) override
{
if (has_key(m_json, name))
{
adapter.set(m_json.at(name).get<bool>());
}
}
void on_adapter(const std::string& name, ValueAccessor<int64_t>& adapter) override
{
if (has_key(m_json, name))
{
adapter.set(m_json.at(name).get<int64_t>());
}
}
void on_adapter(const std::string& name, ValueAccessor<double>& adapter) override
{
if (has_key(m_json, name))
{
adapter.set(m_json.at(name).get<double>());
}
}
void on_adapter(const std::string& name, ValueAccessor<std::vector<int64_t>>& adapter) override
{
if (has_key(m_json, name))
{
adapter.set(m_json.at(name).get<std::vector<int64_t>>());
}
}
void on_adapter(const std::string& name, ValueAccessor<std::vector<uint64_t>>& adapter) override
{
if (has_key(m_json, name))
{
adapter.set(m_json.at(name).get<std::vector<uint64_t>>());
}
}
void on_adapter(const std::string& name, ValueAccessor<std::vector<float>>& adapter) override
{
if (has_key(m_json, name))
{
adapter.set(m_json.at(name).get<std::vector<float>>());
}
}
void on_adapter(const std::string& name,
ValueAccessor<std::vector<std::string>>& adapter) override
{
if (has_key(m_json, name))
{
adapter.set(m_json.at(name).get<std::vector<std::string>>());
}
}
protected:
json& m_json;
};
class JSONDeserializer
{
public:
void set_const_data_callback(function<const_data_callback_t> const_data_callback)
{
m_const_data_callback = const_data_callback;
}
shared_ptr<Function> deserialize_function(json j);
Output<Node> deserialize_output(json j);
OutputVector deserialize_output_vector(json j);
ParameterVector deserialize_parameter_vector(json j);
shared_ptr<Node> deserialize_node_reference(json j);
shared_ptr<Node> deserialize_node(json j);
AxisSet deserialize_axis_set(json j);
shared_ptr<op::v0::TensorIterator::InputDescription>
deserialize_tensor_iterator_input_description(json j);
shared_ptr<op::v0::TensorIterator::OutputDescription>
deserialize_tensor_iterator_output_description(json j);
protected:
unordered_map<string, shared_ptr<Node>> m_node_map;
unordered_map<string, shared_ptr<Function>> m_function_map;
function<const_data_callback_t> m_const_data_callback;
map<string, Output<Node>> m_goe_alias;
};
static string
serialize(shared_ptr<ngraph::Function> func, size_t indent, bool binary_constant_data);
static json write_dimension(Dimension d)
{
if (d.is_dynamic())
{
return nullptr;
}
else
{
return d.get_length();
}
}
static Dimension read_dimension(json j)
{
if (j.is_null())
{
return Dimension::dynamic();
}
else
{
return Dimension(static_cast<int64_t>(j));
}
}
static json write_partial_shape(const PartialShape& s)
{
if (s.rank().is_dynamic())
{
return nullptr;
}
else
{
std::vector<json> vals(s.rank().get_length());
for (size_t i = 0; i < vals.size(); i++)
{
vals[i] = write_dimension(s[i]);
}
return move(vals);
}
}
static PartialShape read_partial_shape(json j)
{
if (j.is_null())
{
return PartialShape::dynamic();
}
else
{
std::vector<Dimension> dims(j.size());
for (size_t i = 0; i < j.size(); i++)
{
dims[i] = read_dimension(j[i]);
}
return PartialShape(dims);
}
}
static json write_auto_broadcast(const op::AutoBroadcastSpec& autob)
{
json j;
j["type"] = autob.m_type;
j["axis"] = autob.m_axis;
return j;
}
static op::AutoBroadcastSpec
read_auto_broadcast(json js_node,
const std::string& attr,
const op::AutoBroadcastSpec& autob = op::AutoBroadcastSpec())
{
if (has_key(js_node, attr))
{
json j = js_node[attr];
return op::AutoBroadcastSpec(static_cast<op::AutoBroadcastType>(j.at("type")),
j.at("axis").get<int64_t>());
}
else
{
return autob;
}
}
static op::PadType read_pad_type(json node_js)
{
return has_key(node_js, "pad_type") ? static_cast<op::PadType>(node_js.at("pad_type"))
: op::PadType::EXPLICIT;
}
static op::PadMode read_pad_mode(json node_js)
{
return has_key(node_js, "pad_mode") ? static_cast<op::PadMode>(node_js.at("pad_mode"))
: op::PadMode::CONSTANT;
}
static json write_element_type(const ngraph::element::Type& n)
{
json j;
j = n.c_type_string();
return j;
}
static element::Type read_element_type(json j)
{
string c_type_string;
element::Type rc;
if (j.is_object())
{
c_type_string = j.at("c_type_string").get<string>();
}
else
{
c_type_string = j.get<string>();
}
for (element::Type t : element::Type::get_known_types())
{
if (t.c_type_string() == c_type_string)
{
rc = t;
break;
}
}
return rc;
}
void ngraph::serialize(const string& path, shared_ptr<ngraph::Function> func, size_t indent)
{
ofstream out(path);
serialize(out, func, indent);
}
void ngraph::serialize(ostream& out, shared_ptr<ngraph::Function> func, size_t indent)
{
out << ::serialize(func, indent, false);
}
#if defined ENABLE_CPIO_FILE
static void serialize_to_cpio(ostream& out, shared_ptr<ngraph::Function> func, size_t indent)
{
string j = ::serialize(func, indent, true);
cpio::Writer writer(out);
writer.write(func->get_name(), j.c_str(), static_cast<uint32_t>(j.size()));
traverse_nodes(const_cast<Function*>(func.get()),
[&](shared_ptr<Node> node) {
if (auto c = node->as_type<op::v0::Constant>())
{
uint32_t size =
static_cast<uint32_t>(shape_size(c->get_output_shape(0)) *
c->get_output_element_type(0).size());
writer.write(c->get_name(), c->get_data_ptr(), size);
}
},
true);
}
#endif
static string serialize(shared_ptr<Function> func, size_t indent, bool binary_constant_data)
{
JSONSerializer serializer;
serializer.set_binary_constant_data(binary_constant_data);
serializer.set_indent(indent);
json j;
j.push_back(serializer.serialize_function(*func));
string rc;
if (indent == 0)
{
rc = j.dump();
}
else
{
rc = j.dump(static_cast<int>(indent));
}
return rc;
}
std::string ngraph::serialize(std::shared_ptr<ngraph::Function> func, size_t indent)
{
return ::serialize(func, indent, false);
}
shared_ptr<ngraph::Function> ngraph::deserialize(istream& in)
{
shared_ptr<Function> rc;
if (cpio::is_cpio(in))
{
cpio::Reader reader(in);
vector<cpio::FileInfo> file_info = reader.get_file_info();
if (file_info.size() > 0)
{
// The first file is the model
uint32_t size = static_cast<uint32_t>(file_info[0].get_size());
char* data = new char[size];
reader.read(file_info[0].get_name(), data, size);
string jstr(data, size);
delete[] data;
json js = json::parse(jstr);
JSONDeserializer deserializer;
deserializer.set_const_data_callback(
[&](const string& const_name, const element::Type& et, const Shape& shape) {
shared_ptr<Node> const_node;
for (const cpio::FileInfo& info : file_info)
{
if (info.get_name() == const_name)
{
void* const_data = ngraph_malloc(info.get_size());
reader.read(const_name, const_data, info.get_size());
const_node = make_shared<op::v0::Constant>(et, shape, const_data);
ngraph_free(const_data);
break;
}
}
return const_node;
});
for (json func : js)
{
rc = deserializer.deserialize_function(func);
}
}
}
else
{
// json file?
std::stringstream ss;
ss << in.rdbuf();
rc = deserialize(ss.str());
}
return rc;
}
shared_ptr<ngraph::Function> ngraph::deserialize(const string& s)
{
shared_ptr<Function> rc;
if (file_util::exists(s))
{
// s is a file and not a json string
ifstream in(s, ios_base::binary | ios_base::in);
rc = deserialize(in);
}
else
{
json js = json::parse(s);
JSONDeserializer deserializer;
for (json func : js)
{
rc = deserializer.deserialize_function(func);
}
}
return rc;
}
json JSONSerializer::serialize_parameter_vector(const ParameterVector& parameters)
{
json json_parameters = json::array();
for (auto param : parameters)
{
json_parameters.push_back(param->get_name());
}
return json_parameters;
}
json JSONSerializer::serialize_function(const Function& f)
{
json function;
function["name"] = f.get_name();
function["parameters"] = serialize_parameter_vector(f.get_parameters());
// TODO Functions can return multiple results
for (size_t i = 0; i < f.get_output_size(); ++i)
{
function["result"].push_back(f.get_output_op(i)->get_name());
}
json nodes;
for (shared_ptr<Node> node : f.get_ordered_ops())
{
nodes.push_back(serialize_node(*node));
}
function["ops"] = nodes;
return function;
}
template <typename T>
T get_value(json js, const string& key)
{
T rc = {};
auto it = js.find(key);
if (it != js.end())
{
rc = it->get<T>();
}
return rc;
}
shared_ptr<Node> JSONDeserializer::deserialize_node_reference(json j)
{
const string& name = j;
return m_node_map.at(name);
}
Output<Node> JSONDeserializer::deserialize_output(json j)
{
size_t index;
json json_node_reference;
if (j.is_string())
{
json_node_reference = j;
index = 0;
}
else if (j.is_object())
{
json_node_reference = j["node"];
index = j["index"];
}
else
{
throw ngraph_error("Expected string or object an output while deserializing");
}
const string& name = json_node_reference;
auto it = m_goe_alias.find(name);
if (it != m_goe_alias.end())
{
return it->second.get_node_shared_ptr();
}
else
{
return Output<Node>(m_node_map.at(name), index);
}
}
OutputVector JSONDeserializer::deserialize_output_vector(json j)
{
OutputVector result;
if (j.is_array())
{
for (json jelt : j)
{
result.push_back(deserialize_output(jelt));
}
}
return result;
}
json JSONSerializer::serialize_axis_set(const AxisSet& axis_set)
{
return static_cast<set<size_t>>(axis_set);
}
AxisSet JSONDeserializer::deserialize_axis_set(json j)
{
AxisSet result;
if (j.is_array())
{
result = j.get<set<size_t>>();
}
return result;
}
json JSONSerializer::serialize_tensor_iterator_input_description(
const std::shared_ptr<op::v0::TensorIterator::InputDescription>& input_description)
{
json result;
if (auto slice = as_type_ptr<op::v0::TensorIterator::SliceInputDescription>(input_description))
{
result["kind"] = "slice";
result["input_index"] = slice->m_input_index;
result["body_parameter_index"] = slice->m_body_parameter_index;
result["start"] = slice->m_start;
result["stride"] = slice->m_stride;
result["part_size"] = slice->m_part_size;
result["end"] = slice->m_end;
result["axis"] = slice->m_axis;
}
else if (auto merged =
as_type_ptr<op::v0::TensorIterator::MergedInputDescription>(input_description))
{
result["kind"] = "merged";
result["input_index"] = merged->m_input_index;
result["body_parameter_index"] = merged->m_body_parameter_index;
result["body_value_index"] = merged->m_body_value_index;
}
else if (auto constant =
as_type_ptr<op::v0::TensorIterator::InvariantInputDescription>(input_description))
{
result["kind"] = "constant";
result["input_index"] = constant->m_input_index;
result["body_parameter_index"] = constant->m_body_parameter_index;
}
else
{
NGRAPH_UNREACHABLE("Unknown input description type");
}
return result;
}
shared_ptr<op::v0::TensorIterator::InputDescription>
JSONDeserializer::deserialize_tensor_iterator_input_description(json j)
{
string kind = j["kind"];
shared_ptr<op::v0::TensorIterator::InputDescription> result;
if (kind == "slice")
{
uint64_t input_index = j["input_index"].get<uint64_t>();
uint64_t body_parameter_index = j["body_parameter_index"].get<uint64_t>();
int64_t start = j["start"].get<int64_t>();
int64_t stride = j["stride"].get<int64_t>();
uint64_t part_size = j["part_size"].get<int64_t>();
int64_t end = j["end"].get<int64_t>();
int64_t axis = j["axis"].get<int64_t>();
result = make_shared<op::v0::TensorIterator::SliceInputDescription>(
input_index, body_parameter_index, start, stride, part_size, end, axis);
}
else if (kind == "merged")
{
uint64_t input_index = j["input_index"].get<uint64_t>();
uint64_t body_parameter_index = j["body_parameter_index"].get<uint64_t>();
uint64_t body_value_index = j["body_value_index"].get<uint64_t>();
result = make_shared<op::v0::TensorIterator::MergedInputDescription>(
input_index, body_parameter_index, body_value_index);
}
else if (kind == "constant")
{
uint64_t input_index = j["input_index"].get<uint64_t>();
uint64_t body_parameter_index = j["body_parameter_index"].get<uint64_t>();
result = make_shared<op::v0::TensorIterator::InvariantInputDescription>(
input_index, body_parameter_index);
}
else
{
NGRAPH_UNREACHABLE("Unknown input description type: ", kind);
}
return result;
}
json JSONSerializer::serialize_tensor_iterator_output_description(
const std::shared_ptr<op::v0::TensorIterator::OutputDescription>& output_description)
{
json result;
if (auto concat =
as_type_ptr<op::v0::TensorIterator::ConcatOutputDescription>(output_description))
{
result["kind"] = "concat";
result["body_value_index"] = concat->m_body_value_index;
result["output_index"] = concat->m_output_index;
result["start"] = concat->m_start;
result["stride"] = concat->m_stride;
result["part_size"] = concat->m_part_size;
result["end"] = concat->m_end;
result["axis"] = concat->m_axis;
}
else if (auto body_output =
as_type_ptr<op::v0::TensorIterator::BodyOutputDescription>(output_description))
{
result["kind"] = "body_output";
result["body_value_index"] = body_output->m_body_value_index;
result["output_index"] = body_output->m_output_index;
result["iteration"] = body_output->m_iteration;
}
else
{
NGRAPH_UNREACHABLE("Unknown input description type");
}
return result;
}
std::shared_ptr<op::v0::TensorIterator::OutputDescription>
JSONDeserializer::deserialize_tensor_iterator_output_description(json j)
{
string kind = j["kind"];
shared_ptr<op::v0::TensorIterator::OutputDescription> result;
if (kind == "concat")
{
uint64_t body_value_index = j["body_value_index"].get<uint64_t>();
uint64_t output_index = j["output_index"].get<uint64_t>();
int64_t start = j["start"].get<int64_t>();
int64_t stride = j["stride"].get<int64_t>();
uint64_t part_size = j["part_size"].get<int64_t>();
int64_t end = j["end"].get<int64_t>();
int64_t axis = j["axis"].get<int64_t>();
result = make_shared<op::v0::TensorIterator::ConcatOutputDescription>(
body_value_index, output_index, start, stride, part_size, end, axis);
}
else if (kind == "body_output")
{
uint64_t body_value_index = j["body_value_index"].get<uint64_t>();
uint64_t output_index = j["output_index"].get<uint64_t>();
int64_t iteration = j["iteration"].get<int64_t>();
result = make_shared<op::v0::TensorIterator::BodyOutputDescription>(
body_value_index, output_index, iteration);
}
else
{
NGRAPH_UNREACHABLE("Unknown input description type: ", kind);
}
return result;
}
ParameterVector JSONDeserializer::deserialize_parameter_vector(json json_parameters)
{
ParameterVector params;
for (auto& param_ref : json_parameters)
{
params.push_back(as_type_ptr<op::v0::Parameter>(deserialize_node_reference(param_ref)));
}
return params;
}
shared_ptr<Function> JSONDeserializer::deserialize_function(json func_js)
{
string func_name = func_js.at("name").get<string>();
vector<json> func_result = func_js.at("result");
for (json node_js : func_js.at("ops"))
{
deserialize_node(node_js);
}
// This handles both graphs w/ `op::v0::Result` and legacy graphs w/o it
// If we are dealing w/ a legacy graph, add op::v0::Result for each output node
ResultVector result;
size_t results = 0;
for (auto& result_ref : func_result)
{
auto fr = deserialize_node_reference(result_ref);
if (auto res = as_type_ptr<op::v0::Result>(fr))
{
result.push_back(res);
// make sure we have `op::v0::Result` on top of all outputs
results++;
}
else
{
result.push_back(std::make_shared<op::v0::Result>(fr));
}
}
if (results != 0 && results != func_result.size())
{
throw ngraph_error(
"Graph serialization is inconsistent. Some op::v0::Results appear to be missing");
}
ParameterVector params = deserialize_parameter_vector(func_js.at("parameters"));
shared_ptr<Function> rc{make_shared<Function>(result, params, func_name)};
m_function_map[func_name] = rc;
return rc;
}
shared_ptr<Node> JSONDeserializer::deserialize_node(json node_js)
{
auto& factory_registry = FactoryRegistry<Node>::get();
shared_ptr<Node> node;
try
{
string node_op = node_js.at("op").get<string>();
size_t op_version = get_value<size_t>(node_js, "op_version");
Node::type_info_t type_info{node_op.c_str(), op_version};
string node_name = node_js.at("name").get<string>();
string friendly_name = get_value<string>(node_js, "friendly_name");
vector<json> control_deps_inputs = get_value<vector<json>>(node_js, "control_deps");
vector<string> node_outputs = get_value<vector<string>>(node_js, "outputs");
OutputVector args(deserialize_output_vector(node_js["inputs"]));
if (has_key(node_js, "attribute_visitor"))
{
if (factory_registry.has_factory(type_info))
{
node = shared_ptr<Node>(factory_registry.create(type_info));
JSONAttributeDeserializer visitor(node_js);
node->set_arguments(static_cast<OutputVector>(args));
node->visit_attributes(visitor);
for (auto& control_dep : control_deps_inputs)
{
node->add_control_dependency(deserialize_node_reference(control_dep));
}
if (!friendly_name.empty())
{
node->set_friendly_name(friendly_name);
}
else
{
node->set_friendly_name(node_name);
}
if (ngraph::get_provenance_enabled())
{
std::vector<json> prov_js = node_js.at("provenance_tags");
for (auto prov_tag : prov_js)
{
node->add_provenance_tag(prov_tag);
}
}
node->constructor_validate_and_infer_types();
m_node_map[node_name] = node;
return node;
}
}
string op_full_name = node_op + "_v" + to_string(op_version);
#if defined(__GNUC__) && !(__GNUC__ == 4 && __GNUC_MINOR__ == 8)
#pragma GCC diagnostic push
#pragma GCC diagnostic error "-Wswitch"
// #pragma GCC diagnostic error "-Wswitch-enum"
// #pragma GCC diagnostic error "-Wimplicit-fallthrough"
#endif
switch (get_typeid(op_full_name))
{
case OP_TYPEID::Abs_v0:
{
node = make_shared<op::v0::Abs>(args[0]);
break;
}
case OP_TYPEID::Acos_v0:
{
node = make_shared<op::v0::Acos>(args[0]);
break;
}
case OP_TYPEID::Add_v0:
{
node = make_shared<op::v1::Add>(
args[0], args[1], read_auto_broadcast(node_js, "auto_broadcast"));
break;
}
case OP_TYPEID::All_v0:
{
auto reduction_axes = deserialize_axis_set(node_js.at("reduction_axes"));
node = make_shared<op::v0::All>(args[0], reduction_axes);
break;
}
case OP_TYPEID::AllReduce_v0:
{
node = make_shared<op::v0::AllReduce>(args[0]);
break;
}
case OP_TYPEID::And_v0:
{
node = make_shared<op::v1::LogicalAnd>(
args[0], args[1], read_auto_broadcast(node_js, "auto_broadcast"));
break;
}
case OP_TYPEID::Any_v0:
{
auto reduction_axes = deserialize_axis_set(node_js.at("reduction_axes"));
node = make_shared<op::v0::Any>(args[0], reduction_axes);
break;
}
case OP_TYPEID::ArgMin_v0:
{
auto axis = node_js.at("axis").get<size_t>();
auto target_type = read_element_type(node_js.at("index_element_type"));
node = make_shared<op::v0::ArgMin>(args[0], axis, target_type);
break;
}
case OP_TYPEID::ArgMax_v0:
{
auto axis = node_js.at("axis").get<size_t>();
auto target_type = read_element_type(node_js.at("index_element_type"));
node = make_shared<op::v0::ArgMax>(args[0], axis, target_type);
break;
}
case OP_TYPEID::Asin_v0:
{
node = make_shared<op::v0::Asin>(args[0]);
break;
}
case OP_TYPEID::Atan_v0:
{
node = make_shared<op::v0::Atan>(args[0]);
break;
}
case OP_TYPEID::Atan2_v0:
{
node =
make_shared<op::v0::Atan2>(args[0], args[1], read_auto_broadcast(node_js, "autob"));
break;
}
case OP_TYPEID::AvgPool_v0:
{
auto window_shape = node_js.at("window_shape").get<vector<size_t>>();
auto window_movement_strides =
node_js.at("window_movement_strides").get<vector<size_t>>();
auto padding_below = node_js.at("padding_below").get<vector<size_t>>();
auto padding_above = node_js.at("padding_above").get<vector<size_t>>();
auto include_padding_in_avg_computation =
node_js.at("include_padding_in_avg_computation").get<bool>();
op::PadType pad_type = read_pad_type(node_js);
bool ceil_mode = get_or_default<bool>(node_js, "ceil_mode", false);
node = make_shared<op::v0::AvgPool>(args[0],
window_shape,
window_movement_strides,
padding_below,
padding_above,
include_padding_in_avg_computation,
pad_type,