This repository has been archived by the owner on Nov 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6.8k
/
c_api.cc
2345 lines (2113 loc) · 80.9 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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/*!
* Copyright (c) 2015 by Contributors
* \file c_api.cc
* \brief C API of mxnet
*/
#include <vector>
#include <sstream>
#include <string>
#include <mutex>
#include <memory>
#include <functional>
#include <utility>
#include "dmlc/base.h"
#include "dmlc/logging.h"
#include "dmlc/io.h"
#include "dmlc/memory_io.h"
#include "dmlc/recordio.h"
#include "dmlc/omp.h"
#include "mxnet/base.h"
#include "mxnet/ndarray.h"
#include "mxnet/operator.h"
#include "mxnet/io.h"
#include "mxnet/c_api.h"
#include "mxnet/kvstore.h"
#include "mxnet/rtc.h"
#include "mxnet/storage.h"
#include "mxnet/libinfo.h"
#include "mxnet/imperative.h"
#include "mxnet/lib_api.h"
#include "../initialize.h"
#include "./c_api_common.h"
#include "../operator/custom/custom-inl.h"
#include "../operator/operator_common.h"
#include "../operator/tensor/matrix_op-inl.h"
#include "../operator/tvmop/op_module.h"
#include "../common/utils.h"
#include "nnvm/pass_functions.h"
using namespace mxnet;
// Internal function to get the information
// from function registry
// Used to implement MXSymbolGetAtomicSymbolInfo and MXFuncGetInfo
template<typename FunRegType>
inline int MXAPIGetFunctionRegInfo(const FunRegType *e,
const char **name,
const char **description,
uint32_t *num_args,
const char ***arg_names,
const char ***arg_type_infos,
const char ***arg_descriptions,
const char **return_type) {
MXAPIThreadLocalEntry<> *ret = MXAPIThreadLocalStore<>::Get();
API_BEGIN();
*name = e->name.c_str();
*description = e->description.c_str();
*num_args = static_cast<uint32_t>(e->arguments.size());
if (return_type) *return_type = e->return_type.c_str();
ret->ret_vec_charp.clear();
for (size_t i = 0; i < e->arguments.size(); ++i) {
ret->ret_vec_charp.push_back(e->arguments[i].name.c_str());
}
for (size_t i = 0; i < e->arguments.size(); ++i) {
ret->ret_vec_charp.push_back(e->arguments[i].type_info_str.c_str());
}
for (size_t i = 0; i < e->arguments.size(); ++i) {
ret->ret_vec_charp.push_back(e->arguments[i].description.c_str());
}
*arg_names = dmlc::BeginPtr(ret->ret_vec_charp);
*arg_type_infos = dmlc::BeginPtr(ret->ret_vec_charp) + e->arguments.size();
*arg_descriptions = dmlc::BeginPtr(ret->ret_vec_charp) + (e->arguments.size() * 2);
API_END();
}
// NOTE: return value is added in API_END
/*!
* \brief Loads dynamic library and initializes it
* \param path library path
*/
int MXLoadLib(const char *path) {
API_BEGIN();
void *lib = LibraryInitializer::Get()->lib_load(path);
if (!lib)
LOG(FATAL) << "Unable to load library";
// check that library and MXNet use same version of library API
opVersion_t opVersion = get_func<opVersion_t>(lib, const_cast<char*>(MXLIB_OPVERSION_STR));
int libVersion = opVersion();
if (MX_LIBRARY_VERSION != libVersion)
LOG(FATAL) << "Library version (" << libVersion << ") does not match MXNet version ("
<< MX_LIBRARY_VERSION << ")";
// initialize library by passing MXNet version
initialize_t initialize = get_func<initialize_t>(lib, const_cast<char*>(MXLIB_INITIALIZE_STR));
if (!initialize(static_cast<int>(MXNET_VERSION)))
LOG(FATAL) << "Library failed to initialize";
// get C type interface functions
opCallFree_t callFree = get_func<opCallFree_t>(lib, const_cast<char*>(MXLIB_OPCALLFREE_STR));
opCallParseAttrs_t callParseAttrs =
get_func<opCallParseAttrs_t>(lib, const_cast<char*>(MXLIB_OPCALLPARSEATTRS_STR));
opCallInferShape_t callInferShape =
get_func<opCallInferShape_t>(lib, const_cast<char*>(MXLIB_OPCALLINFERSHAPE_STR));
opCallInferType_t callInferType =
get_func<opCallInferType_t>(lib, const_cast<char*>(MXLIB_OPCALLINFERTYPE_STR));
opCallFComp_t callFComp =
get_func<opCallFComp_t>(lib, const_cast<char*>(MXLIB_OPCALLFCOMP_STR));
opCallMutateInputs_t callMutateInputs =
get_func<opCallMutateInputs_t>(lib, const_cast<char*>(MXLIB_OPCALLMUTATEINPUTS_STR));
opCallCreateOpState_t callCreateOpState =
get_func<opCallCreateOpState_t>(lib, const_cast<char*>(MXLIB_OPCALLCREATEOPSTATE_STR));
opCallFStatefulComp_t callFStatefulComp =
get_func<opCallFStatefulComp_t>(lib, const_cast<char*>(MXLIB_OPCALLFSTATEFULCOMP_STR));
// get number of operators registered in the library
opRegSize_t opRegSize = get_func<opRegSize_t>(lib, const_cast<char*>(MXLIB_OPREGSIZE_STR));
int numOps = opRegSize();
LOG(INFO) << "Found " << numOps << " operators in library";
/*
* Get all custom operators implementation from custom library
* loop and register each operator in the library to NNVM
*/
opRegGet_t opRegGet = get_func<opRegGet_t>(lib, const_cast<char*>(MXLIB_OPREGGET_STR));
for (int i = 0; i < numOps; i++) {
const char* name;
// function pointers holding implementation from custom library
fcomp_t fcomp_fp = nullptr;
parseAttrs_t parse_fp = nullptr;
inferType_t type_fp = nullptr;
inferShape_t shape_fp = nullptr;
// optional attributes
fcomp_t fgrad_fp = nullptr;
mutateInputs_t mutate_fp = nullptr;
createOpState_t create_opstate_fp = nullptr;
// get custom operator implemenation from the dynamic library
opRegGet(i, &name, &fcomp_fp, &fgrad_fp, &parse_fp, &type_fp, &shape_fp,
&mutate_fp, &create_opstate_fp);
// validate custom operator functions from the dynamic library
CHECK(fcomp_fp != nullptr || create_opstate_fp != nullptr) << "Error loading '" << name
<< "' custom op, Forward or CreateOpState function was not set.";
CHECK(parse_fp != nullptr) << "Error loading '" << name
<< "' custom op, ParseAttrs function was not set.";
CHECK(type_fp != nullptr) << "Error loading '" << name
<< "' custom op, InferType function was not set.";
CHECK(shape_fp != nullptr) << "Error loading '" << name
<< "' custom op, InferShape function was not set.";
LOG(INFO) << "\tOp[" << i << "] " << name;
std::string name_str(name);
/*
* Below are a series of lambda functions that will be registered in the NNVM op registration
* Each one has the standard MXNet signature and converts to types supported by externally
* registered operators.
*/
// lambda function to call parse attributes
auto attr_parser = [=](const NodeAttrs* attrs) {
// convert attributes to vector of char
std::vector<const char*> attr_keys, attr_vals;
for (auto kv : attrs->dict) {
attr_keys.push_back(kv.first.c_str());
attr_vals.push_back(kv.second.c_str());
}
// convert subgraph symbol from node attributes to char*
std::string subgraph_json;
if (!attrs->subgraphs.empty()) {
nnvm::Graph g;
g.outputs = attrs->subgraphs[0].get()->outputs;
subgraph_json = nnvm::pass::SaveJSON(g);
attr_keys.push_back(SUBGRAPH_SYM_JSON);
attr_vals.push_back(subgraph_json.c_str());
}
int num_in = -1;
int num_out = -1;
CHECK(callParseAttrs(parse_fp, attr_keys.data(), attr_vals.data(), attr_keys.size(),
&num_in, &num_out))
<< "Error calling ParseAttrs for custom operator '" << name_str << "'";
// return type void
};
// lambda function to call parse attributes and return the number of inputs
auto num_inputs = [=](const NodeAttrs& attrs) {
// convert attributes to vector of char
std::vector<const char*> attr_keys, attr_vals;
for (auto kv : attrs.dict) {
attr_keys.push_back(kv.first.c_str());
attr_vals.push_back(kv.second.c_str());
}
int num_in = -1;
int num_out = -1;
CHECK(callParseAttrs(parse_fp, attr_keys.data(), attr_vals.data(), attr_keys.size(),
&num_in, &num_out))
<< "Error calling ParseAttrs::num_inputs for custom operator '" << name_str << "'";
return num_in;
};
// lambda function to call parse attributes and return the number of outputs
auto num_outputs = [=](const NodeAttrs& attrs) {
// convert attributes to vector of char*
std::vector<const char*> attr_keys, attr_vals;
for (auto kv : attrs.dict) {
attr_keys.push_back(kv.first.c_str());
attr_vals.push_back(kv.second.c_str());
}
int num_in = -1;
int num_out = -1;
CHECK(callParseAttrs(parse_fp, attr_keys.data(), attr_vals.data(), attr_keys.size(),
&num_in, &num_out))
<< "Error calling ParseAttrs::num_outputs for custom operator '" << name_str << "'";
return num_out;
};
// lambda function to call parse attributes and return the number of inputs and outputs
// for backward computation
auto num_inouts = [=](const NodeAttrs& attrs) {
// convert attributes to vector of char*
std::vector<const char*> attr_keys, attr_vals;
for (auto kv : attrs.dict) {
attr_keys.push_back(kv.first.c_str());
attr_vals.push_back(kv.second.c_str());
}
int num_in = -1;
int num_out = -1;
CHECK(callParseAttrs(parse_fp, attr_keys.data(), attr_vals.data(), attr_keys.size(),
&num_in, &num_out))
<< "Error calling ParseAttrs::num_outputs for custom operator '" << name_str << "'";
return num_in + 2*num_out;
};
// lambda function to call infer shape
auto infer_shape = [=] (const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_shape,
mxnet::ShapeVector *out_shape) {
// convert attributes to vector of char*
std::vector<const char*> attr_keys, attr_vals;
for (auto kv : attrs.dict) {
attr_keys.push_back(kv.first.c_str());
attr_vals.push_back(kv.second.c_str());
}
std::vector<uint32_t*> inshapes(in_shape->size());
std::vector<int> indims(in_shape->size());
// determine amount of memory needed to store all the input shapes
size_t buff_size = 0;
for (const auto& i : *in_shape) buff_size += i.ndim();
// copy input shapes from ShapeVector to raw memory layout
std::vector<uint32_t> inbuff(buff_size);
uint32_t *ptr = inbuff.data();
for (size_t i = 0; i < in_shape->size(); ++i) {
inshapes[i] = ptr;
indims[i] = (*in_shape)[i].ndim();
for (int j = 0; j < (*in_shape)[i].ndim(); ++j, ++ptr) {
*ptr = static_cast<uint32_t>((*in_shape)[i][j]);
}
}
// output shapes will be allocated by infer shape function
uint32_t** outshapes = nullptr;
int* outdims = nullptr;
CHECK(callInferShape(shape_fp, attr_keys.data(), attr_vals.data(), attr_keys.size(),
inshapes.data(), indims.data(), in_shape->size(),
&outshapes, &outdims, out_shape->size()))
<< "Error calling InferShape for custom operator '" << name_str << "'";
std::vector<uint32_t*> out_shapes(out_shape->size());
// determine amount of memory needed to store all the output shapes
buff_size = 0;
for (unsigned i = 0; i < out_shape->size(); i++) {
buff_size += outdims[i];
}
// copy output shapes from custom op memory to MXNet memory
std::vector<uint32_t> outbuff(buff_size);
ptr = outbuff.data();
for (unsigned i = 0; i < out_shape->size(); ++i) {
out_shapes[i] = ptr;
for (int j = 0; j < outdims[i]; ++j, ++ptr) {
*ptr = static_cast<uint32_t>(outshapes[i][j]);
}
}
// assign output shapes to ShapeVector
for (unsigned i = 0; i < out_shape->size(); ++i) {
SHAPE_ASSIGN_CHECK(*out_shape, i,
mxnet::TShape(out_shapes[i], out_shapes[i]+outdims[i]));
}
// free memory used by custom op to allocate shapes/dims
callFree(outdims);
for (unsigned i = 0; i < out_shape->size(); i++) {
callFree(outshapes[i]);
}
callFree(outshapes);
return true;
};
// lambda function to call infer type
auto infer_type = [=] (const nnvm::NodeAttrs& attrs,
std::vector<int> *in_type,
std::vector<int> *out_type) {
// convert attributes to vector of char*
std::vector<const char*> attr_keys, attr_vals;
for (auto kv : attrs.dict) {
attr_keys.push_back(kv.first.c_str());
attr_vals.push_back(kv.second.c_str());
}
// copy input types from in_type
std::vector<int> intypes(*in_type);
// output types will be populated by inferType function
std::vector<int> outtypes(out_type->size());
CHECK(callInferType(type_fp, attr_keys.data(), attr_vals.data(), attr_keys.size(),
intypes.data(), in_type->size(),
outtypes.data(), out_type->size()))
<< "Error calling InferType for custom operator '" << name_str << "'";
// copy and assign output types from custom op to MXNet memory
for (size_t i = 0; i < out_type->size(); i++) {
TYPE_ASSIGN_CHECK(*out_type, i, outtypes[i]);
}
return true;
};
// lambda function to convert from external fcompute to internal MXNet types
auto fcomp_lambda = [=](fcomp_t fcomp_fp,
const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<NDArray>& inputs,
const std::vector<OpReqType>& req,
const std::vector<NDArray>& outputs) {
// convert attributes to vector of char*
std::vector<const char*> attr_keys, attr_vals;
for (auto kv : attrs.dict) {
attr_keys.push_back(kv.first.c_str());
attr_vals.push_back(kv.second.c_str());
}
std::vector<void*> in_data, out_data;
std::vector<const int64_t *> in_shapes, out_shapes;
std::vector<int> in_dims, out_dims;
std::vector<int> in_types, out_types;
// convert input tensors to constituent parts
for (size_t i = 0; i < inputs.size(); i++) {
in_data.push_back(inputs[i].data().dptr_);
in_shapes.push_back(inputs[i].shape().data());
in_dims.push_back(inputs[i].shape().ndim());
in_types.push_back(inputs[i].dtype());
}
// convert output tensors to constituent parts
for (size_t i = 0; i < outputs.size(); i++) {
out_data.push_back(outputs[i].data().dptr_);
out_shapes.push_back(outputs[i].shape().data());
out_dims.push_back(outputs[i].shape().ndim());
out_types.push_back(outputs[i].dtype());
}
// get memory resource
const Resource &resource = ctx.requested[0];
mshadow::Stream<mxnet::cpu> *cpu_stream = ctx.get_stream<mxnet::cpu>();
// create lambda that captures stream & resource objects
// this temp workspace holds memory allocated by custom library via OpResource
auto cpu_alloc = [&](int size) {
mshadow::Tensor<mxnet::cpu, 1, char> workspace =
resource.get_space_typed<mxnet::cpu, 1, char>(mshadow::Shape1(size), cpu_stream);
return workspace.dptr_;
};
// create lambda without captures so that we can cast it to function pointer
// this needs to be a lambda function so that we can do the decltype cast
typedef decltype(cpu_alloc) alloc_type;
auto cpu_malloc = [](void* _cpu_alloc, int size) {
// cast the void* argument to the type for the cpu_alloc lambda function
alloc_type* cpualloc = static_cast<alloc_type*>(_cpu_alloc);
// call cpu_alloc to actually allocate memory and get the pointer
void* ptr = (*cpualloc)(size);
return ptr;
};
// call fcompute function
CHECK(callFComp(fcomp_fp, attr_keys.data(), attr_vals.data(), attr_keys.size(),
in_shapes.data(), in_dims.data(), in_data.data(),
in_types.data(), in_data.size(),
out_shapes.data(), out_dims.data(), out_data.data(),
out_types.data(), out_data.size(), cpu_malloc, &cpu_alloc))
<< "Error calling FCompute for custom operator '" << name_str << "'";
// return type void
};
auto forward_lambda = [=](const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<NDArray>& inputs,
const std::vector<OpReqType>& req,
const std::vector<NDArray>& outputs) {
return fcomp_lambda(fcomp_fp, attrs, ctx, inputs, req, outputs);
};
auto backward_lambda = [=](const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<NDArray>& inputs,
const std::vector<OpReqType>& req,
const std::vector<NDArray>& outputs) {
return fcomp_lambda(fgrad_fp, attrs, ctx, inputs, req, outputs);
};
// lambda function to convert from external mutate_inputs to internal MXNet types
auto mutate_inputs = [=](const nnvm::NodeAttrs& attrs) {
// convert attributes to vector of char*
std::vector<const char*> attr_keys, attr_vals;
for (auto kv : attrs.dict) {
attr_keys.push_back(kv.first.c_str());
attr_vals.push_back(kv.second.c_str());
}
// C type placeholder for mutate input indices vector
int* mutate_indices = nullptr;
int indices_size = 0;
// call mutate inputs function
CHECK(callMutateInputs(mutate_fp, attr_keys.data(), attr_vals.data(), attr_keys.size(),
&mutate_indices, &indices_size))
<< "Error calling MutateInputs for custom operator '" << name_str << "'";
std::vector<uint32_t> mutate_indices_list(indices_size);
for (int i=0; i < indices_size; i++) {
mutate_indices_list[i] = static_cast<uint32_t>(mutate_indices[i]);
}
return mutate_indices_list;
};
// lambda function to set storage types
auto infer_storage_type = [=](const nnvm::NodeAttrs& attrs,
const int dev_mask,
DispatchMode* dispatch_mode,
std::vector<int>* in_stypes,
std::vector<int>* out_stypes) {
// TODO(ziyimu): remove this dense enforce check after supporting sparse tensor
CHECK(mxnet::common::ContainsOnlyStorage(*in_stypes, mxnet::kDefaultStorage))
<< "Error input tensors are not dense for custom operator '" << name_str << "'";
// set outputs as dense
return op::storage_type_assign(out_stypes, mxnet::kDefaultStorage,
dispatch_mode, DispatchMode::kFComputeEx);
};
// FGradient register lambda
auto grad_reg = [=](const nnvm::NodePtr& n, const std::vector<nnvm::NodeEntry>& ograds) {
// copy gradients first
std::vector<nnvm::NodeEntry> heads(ograds.begin(), ograds.end());
// copy inputs second
for (auto& h : n->inputs) {
heads.push_back(h);
}
// copy outputs last
uint32_t n_out = n->num_outputs();
for (uint32_t i = 0; i < n_out; ++i) {
heads.emplace_back(n, i, 0);
}
std::string grad_name = "_backward_" + name_str;
return mxnet::op::MakeGradNode(grad_name.c_str(), n, heads, n->attrs.dict);
};
auto resc_req = [=](const NodeAttrs& attrs) {
return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};
};
// library author should implement and return a 'state' which points to an instance
// in lambda we create OpStatePtr using the returned 'state'
auto create_opstate = [=] (const NodeAttrs& attrs,
Context ctx,
const std::vector<TShape>& in_shapes,
const std::vector<int>& in_types) {
// convert attributes to vector of char*
std::vector<const char*> attr_keys, attr_vals;
for (auto kv : attrs.dict) {
attr_keys.push_back(kv.first.c_str());
attr_vals.push_back(kv.second.c_str());
}
// convert subgraph symbol from node attributes to char*
std::string subgraph_json;
if (!attrs.subgraphs.empty()) {
nnvm::Graph g;
g.outputs = attrs.subgraphs[0].get()->outputs;
subgraph_json = nnvm::pass::SaveJSON(g);
attr_keys.push_back(SUBGRAPH_SYM_JSON);
attr_vals.push_back(subgraph_json.c_str());
}
// create a pointer to hold custom op state object
void* state_op_inst = nullptr;
CHECK(callCreateOpState(create_opstate_fp, attr_keys.data(), attr_vals.data(),
attr_keys.size(), &state_op_inst))
<< "Error calling CreateOpState for custom operator '" << name_str << "'";
CHECK(state_op_inst != nullptr)
<< "Error custom library failed to create stateful operator '" << name_str << "'";
CustomStatefulOp* state_op = reinterpret_cast<CustomStatefulOp*>(state_op_inst);
return OpStatePtr::Create<CustomStatefulOpWrapper>(state_op);
};
// stateful forward and backward
auto fstateful_lambda = [=](bool is_forward,
const OpStatePtr& state_ptr,
const OpContext& ctx,
const std::vector<NDArray>& inputs,
const std::vector<OpReqType>& req,
const std::vector<NDArray>& outputs) {
std::vector<void*> in_data, out_data;
std::vector<const int64_t *> in_shapes, out_shapes;
std::vector<int> in_dims, out_dims;
std::vector<int> in_types, out_types;
// convert input tensors to constituent parts
for (size_t i = 0; i < inputs.size(); i++) {
in_data.push_back(inputs[i].data().dptr_);
in_shapes.push_back(inputs[i].shape().data());
in_dims.push_back(inputs[i].shape().ndim());
in_types.push_back(inputs[i].dtype());
}
// convert output tensors to constituent parts
for (size_t i = 0; i < outputs.size(); i++) {
out_data.push_back(outputs[i].data().dptr_);
out_shapes.push_back(outputs[i].shape().data());
out_dims.push_back(outputs[i].shape().ndim());
out_types.push_back(outputs[i].dtype());
}
// get memory resource
const Resource &resource = ctx.requested[0];
mshadow::Stream<mxnet::cpu> *cpu_stream = ctx.get_stream<mxnet::cpu>();
// create lambda that captures stream & resource objects
// this temp workspace holds memory allocated by custom library via OpResource
auto cpu_alloc = [&](int size) {
mshadow::Tensor<mxnet::cpu, 1, char> data =
resource.get_space_typed<mxnet::cpu, 1, char>(mshadow::Shape1(size), cpu_stream);
return data.dptr_;
};
// create lambda without captures so that we can cast it to function pointer
// this needs to be a lambda function so that we can do the decltype cast
typedef decltype(cpu_alloc) alloc_type;
auto cpu_malloc = [](void* _cpu_alloc, int size) {
// cast the void* argument to the type for the cpu_alloc lambda function
alloc_type* cpualloc = static_cast<alloc_type*>(_cpu_alloc);
// call cpu_alloc to actually allocate memory and get the pointer
void* ptr = (*cpualloc)(size);
return ptr;
};
// retrieve op state object created from CreateOpState
CustomStatefulOpWrapper& op = state_ptr.get_state<CustomStatefulOpWrapper>();
CustomStatefulOp* state_op_inst = op.get_instance();
CHECK(state_op_inst != nullptr)
<< "Error MXNet cannot load custom stateful operator'" << name_str << "'";
// call fcompute function
CHECK(callFStatefulComp(is_forward, state_op_inst, in_shapes.data(), in_dims.data(),
in_data.data(), in_types.data(), in_data.size(),
out_shapes.data(), out_dims.data(), out_data.data(),
out_types.data(), out_data.size(), cpu_malloc, &cpu_alloc))
<< "Error calling FStatefulCompute for custom operator '" << name_str << "'";
};
auto fstateful_forward = [=](const OpStatePtr& state_ptr,
const OpContext& ctx,
const std::vector<NDArray>& inputs,
const std::vector<OpReqType>& req,
const std::vector<NDArray>& outputs) {
fstateful_lambda(true, state_ptr, ctx, inputs, req, outputs);
};
auto fstateful_backward = [=](const OpStatePtr& state_ptr,
const OpContext& ctx,
const std::vector<NDArray>& inputs,
const std::vector<OpReqType>& req,
const std::vector<NDArray>& outputs) {
fstateful_lambda(false, state_ptr, ctx, inputs, req, outputs);
};
// check if operator is already registered
const nnvm::Op *regOpPtr = dmlc::Registry<nnvm::Op>::Get()->Find(name);
nnvm::Op ®Op = dmlc::Registry<nnvm::Op>::Get()->__REGISTER_OR_GET__(name);
regOp.set_attr_parser(attr_parser);
regOp.set_num_inputs(num_inputs);
regOp.set_num_outputs(num_outputs);
int plevel = 10;
if (regOpPtr != nullptr) {
// overwrite registration of existing op with custom op
regOp.arguments.clear();
// set attribute with higher plevel (11) to allow re-registering once
// TODO(samskalicky): enable constant overwriting of registertion multiple times
plevel++;
}
regOp.set_attr<nnvm::FInferType>("FInferType", infer_type, plevel);
regOp.set_attr<mxnet::FInferShape>("FInferShape", infer_shape, plevel);
regOp.set_attr<FInferStorageType>("FInferStorageType", infer_storage_type, plevel);
regOp.set_attr<FResourceRequest>("FResourceRequest", resc_req, plevel);
// optionally add stateful forward
if (create_opstate_fp != nullptr) {
regOp.set_attr<FCreateOpState>("FCreateOpState", create_opstate, plevel);
regOp.set_attr<FStatefulComputeEx>("FStatefulComputeEx<cpu>",
fstateful_forward, plevel);
} else {
regOp.set_attr<FComputeEx>("FComputeEx<cpu>", forward_lambda, plevel);
}
// optionally add fmutate inputs if user specified a function
if (mutate_fp != nullptr)
regOp.set_attr<nnvm::FMutateInputs>("FMutateInputs", mutate_inputs, plevel);
// optionally add fgradient if user specified a function
if (fgrad_fp != nullptr || create_opstate_fp != nullptr) {
regOp.set_attr<nnvm::FGradient>("FGradient", grad_reg, plevel);
std::string grad_name = "_backward_" + name_str;
nnvm::Op &gradOp = dmlc::Registry<nnvm::Op>::Get()->__REGISTER_OR_GET__(grad_name);
gradOp.set_attr<nnvm::TIsBackward>("TIsBackward", true, plevel);
gradOp.set_attr_parser(attr_parser);
gradOp.set_num_inputs(num_inouts);
gradOp.set_num_outputs(num_inputs);
gradOp.set_attr<FInferStorageType>("FInferStorageType", infer_storage_type, plevel);
gradOp.set_attr<FResourceRequest>("FResourceRequest", resc_req, plevel);
if (create_opstate_fp != nullptr) {
gradOp.set_attr<bool>("TIsLayerOpBackward", true, plevel);
gradOp.set_attr<FStatefulComputeEx>("FStatefulComputeEx<cpu>",
fstateful_backward, plevel);
} else {
gradOp.set_attr<FComputeEx>("FComputeEx<cpu>", backward_lambda, plevel);
}
}
regOp.add_argument("data", "NDArray[]", "Source inputs");
}
API_END();
}
int MXLibInfoFeatures(const struct LibFeature **lib_features, size_t *size) {
using namespace features;
API_BEGIN();
LibInfo* lib_info = LibInfo::getInstance();
*lib_features = lib_info->getFeatures().data();
*size = lib_info->getFeatures().size();
API_END();
}
int MXRandomSeed(int seed) {
API_BEGIN();
mxnet::RandomSeed(seed);
API_END();
}
int MXRandomSeedContext(int seed, int dev_type, int dev_id) {
API_BEGIN();
Context ctx = Context::Create(static_cast<Context::DeviceType>(dev_type), dev_id);
mxnet::RandomSeed(ctx, seed);
API_END();
}
int MXNotifyShutdown() {
API_BEGIN();
mxnet::op::custom::CustomOperator::Get()->Stop();
Engine::Get()->NotifyShutdown();
API_END();
}
int MXSetNumOMPThreads(int thread_num) {
API_BEGIN();
omp_set_num_threads(thread_num);
API_END();
}
int MXEngineSetBulkSize(int bulk_size, int* prev_bulk_size) {
API_BEGIN();
*prev_bulk_size = Engine::Get()->set_bulk_size(bulk_size);
API_END();
}
int MXGetGPUCount(int* out) {
API_BEGIN();
*out = Context::GetGPUCount();
API_END();
}
// Deprecated: use MXGetGPUMemoryInformation64() instead.
int MXGetGPUMemoryInformation(int dev, int *free_mem, int *total_mem) {
API_BEGIN();
uint64_t free_mem64 = 0UL;
uint64_t total_mem64 = 0UL;
Context::GetGPUMemoryInformation(dev, &free_mem64, &total_mem64);
*free_mem = static_cast<int>(free_mem64);
*total_mem = static_cast<int>(total_mem64);
API_END();
}
int MXGetGPUMemoryInformation64(int dev, uint64_t *free_mem, uint64_t *total_mem) {
API_BEGIN();
Context::GetGPUMemoryInformation(dev, free_mem, total_mem);
API_END();
}
int MXGetVersion(int *out) {
API_BEGIN();
*out = static_cast<int>(MXNET_VERSION);
API_END();
}
#if MXNET_USE_TVM_OP
int MXLoadTVMOp(const char *libpath) {
API_BEGIN();
tvm::runtime::TVMOpModule::Get()->Load(libpath);
API_END();
}
int MXLoadTVMConfig(ConfigSpaces config) {
API_BEGIN();
for (int k = 0; k < config.spaces_size; ++k) {
tvm::runtime::TVMOpConfig& entry = ::dmlc::Registry<tvm::runtime::TVMOpConfig>::Get()
->__REGISTER_OR_GET__(std::string(config.spaces_key[k]));
const ConfigSpace& c = config.spaces_val[k];
for (int i = 0; i < c.entity_map_size; ++i) {
entry.add_entity(std::string(c.entity_map_key[i]), c.entity_map_val[i].val);
}
for (int i = 0; i < c.space_map_size; ++i) {
std::string name = std::string(c.space_map_key[i]);
std::vector<int> entities;
for (int j = 0; j < c.space_map_val[i].entities_size; ++j) {
int val = c.space_map_val[i].entities[j].val;
entities.push_back(val);
}
entry.add_space(name, entities);
}
}
API_END();
}
#endif // MXNET_USE_TVM_OP
int MXNDArrayCreateNone(NDArrayHandle *out) {
API_BEGIN();
*out = new NDArray();
API_END();
}
template<typename DataType, typename dimtype>
void CreateNDArray(const DataType* shape,
dimtype ndim,
int dev_type,
int dev_id,
int delay_alloc,
int dtype,
NDArrayHandle* out) {
mxnet::TShape requested_shape = mxnet::TShape(shape, shape + ndim);
if (!features::is_enabled(features::INT64_TENSOR_SIZE)) {
CHECK_LT(requested_shape.Size(), (int64_t{1} << 31) - 1) <<
"[CreateNDArray] Size of tensor you are trying to allocate is larger than "
"2^31 elements. Please build with flag USE_INT64_TENSOR_SIZE=1";
}
*out = new NDArray(requested_shape,
Context::Create(static_cast<Context::DeviceType>(dev_type), dev_id),
delay_alloc != 0, dtype);
}
int MXNDArrayCreate(const uint32_t *shape,
uint32_t ndim,
int dev_type,
int dev_id,
int delay_alloc,
NDArrayHandle *out) {
API_BEGIN();
*out = new NDArray(mxnet::TShape(shape, shape + ndim),
Context::Create(static_cast<Context::DeviceType>(dev_type), dev_id),
delay_alloc != 0);
API_END();
}
int MXNDArrayCreateEx64(const int64_t *shape,
int ndim,
int dev_type,
int dev_id,
int delay_alloc,
int dtype,
NDArrayHandle *out) {
API_BEGIN();
CreateNDArray<int64_t, int>(shape, ndim, dev_type, dev_id, delay_alloc, dtype, out);
API_END();
}
int MXNDArrayCreateEx(const uint32_t *shape,
uint32_t ndim,
int dev_type,
int dev_id,
int delay_alloc,
int dtype,
NDArrayHandle *out) {
API_BEGIN();
CreateNDArray<uint32_t, uint32_t>(shape, ndim, dev_type, dev_id, delay_alloc, dtype, out);
API_END();
}
int MXNDArrayCreateSparseEx(int storage_type,
const uint32_t *shape,
uint32_t ndim,
int dev_type,
int dev_id,
int delay_alloc,
int dtype,
uint32_t num_aux,
int *aux_type,
uint32_t *aux_ndims,
const uint32_t *aux_shape,
NDArrayHandle *out) {
API_BEGIN();
std::vector<int> aux_types;
mxnet::ShapeVector aux_shapes;
auto shape_start = aux_shape;
for (size_t i = 0; i < num_aux; i++) {
// types
aux_types.push_back(aux_type[i]);
// shapes
aux_shapes.emplace_back(shape_start, shape_start + aux_ndims[i]);
shape_start += aux_ndims[i];
}
*out = new NDArray(
NDArrayStorageType(storage_type),
mxnet::TShape(shape, shape + ndim),
Context::Create(static_cast<Context::DeviceType>(dev_type), dev_id),
delay_alloc != 0,
dtype, aux_types, aux_shapes);
API_END();
}
int MXNDArrayLoadFromRawBytes(const void *buf,
size_t size,
NDArrayHandle *out) {
NDArray *ptr = nullptr;
API_BEGIN();
dmlc::MemoryFixedSizeStream strm((void*)buf, size); // NOLINT(*)
ptr = new NDArray();
if (!ptr->Load(&strm)) {
throw dmlc::Error("Invalid NDArray serialization format");
}
*out = ptr;
API_END_HANDLE_ERROR(delete ptr);
}
int MXNDArraySaveRawBytes(NDArrayHandle handle,
size_t *out_size,
const char **out_buf) {
MXAPIThreadLocalEntry<> *ret = MXAPIThreadLocalStore<>::Get();
API_BEGIN();
ret->ret_str.resize(0);
dmlc::MemoryStringStream strm(&ret->ret_str);
static_cast<NDArray*>(handle)->Save(&strm);
*out_size = ret->ret_str.length();
*out_buf = ret->ret_str.c_str();
API_END();
}
int MXNDArraySyncCopyFromCPU(NDArrayHandle handle,
const void *data,
size_t size) {
API_BEGIN();
static_cast<NDArray*>(handle)->SyncCopyFromCPU(data, size);
API_END();
}
int MXNDArraySyncCopyToCPU(NDArrayHandle handle,
void *data,
size_t size) {
API_BEGIN();
static_cast<NDArray*>(handle)->SyncCopyToCPU(data, size);
API_END();
}
/*!
* \brief Copy src.data() to dst.data() if i = -1, else dst.aux_data(i) if i >= 0
* This function blocks. Do not use it in performance critical code.
* \param handle_dst handle of a dst ndarray whose data/aux_data has been allocated
* \param handle_src handle of a src ndarray which has default storage type
* \param i dst data blob indicator
*/
int MXNDArraySyncCopyFromNDArray(NDArrayHandle handle_dst,
const NDArrayHandle handle_src,
const int i) {
API_BEGIN();
NDArray* dst = static_cast<NDArray*>(handle_dst);
NDArray* src = static_cast<NDArray*>(handle_src);
dst->SyncCopyFromNDArray(*src, -1, i);
API_END();
}
int MXNDArraySyncCheckFormat(NDArrayHandle handle, const bool full_check) {
API_BEGIN();
NDArray *arr = static_cast<NDArray*>(handle);
arr->SyncCheckFormat(full_check);
API_END();
}
int MXNDArrayWaitToRead(NDArrayHandle handle) {
API_BEGIN();
static_cast<NDArray*>(handle)->WaitToRead();
API_END();
}
int MXNDArrayWaitToWrite(NDArrayHandle handle) {
API_BEGIN();
static_cast<NDArray*>(handle)->WaitToWrite();
API_END();
}
int MXNDArrayWaitAll() {
API_BEGIN();
Engine::Get()->WaitForAll();
API_END();
}
int MXNDArraySave(const char* fname,
uint32_t num_args,
NDArrayHandle* args,
const char** keys) {
API_BEGIN();
std::vector<NDArray> data(num_args);
std::vector<std::string> names;
for (uint32_t i = 0; i < num_args; ++i) {
data[i] = *static_cast<NDArray*>(args[i]);
}
if (keys != nullptr) {
names.resize(num_args);
for (uint32_t i = 0; i < num_args; ++i) {
names[i] = keys[i];
}
}
{
std::unique_ptr<dmlc::Stream> fo(dmlc::Stream::Create(fname, "w"));
mxnet::NDArray::Save(fo.get(), data, names);
}
API_END();
}
int MXNDArrayLoad(const char* fname,
uint32_t *out_size,
NDArrayHandle** out_arr,
uint32_t *out_name_size,
const char*** out_names) {
MXAPIThreadLocalEntry<> *ret = MXAPIThreadLocalStore<>::Get();
ret->ret_vec_str.clear();
API_BEGIN();
std::vector<NDArray> data;