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
3512 lines (3178 loc) · 132 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 <unordered_map>
#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/subgraph/common.h"
#include "../operator/tensor/matrix_op-inl.h"
#include "../operator/tvmop/op_module.h"
#include "../operator/subgraph/partitioner/custom_subgraph_property.h"
#include "../operator/subgraph/subgraph_property.h"
#include "../common/utils.h"
#include "../profiler/profiler.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
std::string getExtensionMsgs(mxnet::ext::msgSize_t msgSize,
mxnet::ext::msgGet_t msgGet) {
std::string str;
if (msgSize() > 0) {
str = "\nExtension Traceback:\n";
for (int i = 0; i < msgSize(); i++) {
const char* tmp;
msgGet(i, &tmp);
// format: [i] message
str += std::string("\t[") + std::to_string(i) + std::string("] ")
+ std::string(tmp) + std::string("\n");
}
}
return str;
}
/*!
* \brief Common compute function dispatcher for forward/backward and stateful forward/backward
* state_ptr will be nullptr for regular ops; fcomp_fp is nullptr for stateful ops
*/
void CustomFComputeDispatcher(const std::string op_name,
const mxnet::ext::opCallFComp_t callFComp,
const mxnet::ext::fcomp_t fcomp_fp,
const nnvm::NodeAttrs* attrs,
const mxnet::ext::opCallFStatefulComp_t callFStatefulComp,
int stateful_forward_flag,
const OpStatePtr* state_ptr,
const OpContext& ctx,
const std::vector<NDArray>& inputs,
const std::vector<OpReqType>& req,
const std::vector<NDArray>& outputs,
mxnet::ext::msgSize_t msgSize,
mxnet::ext::msgGet_t msgGet) {
using namespace mxnet::ext;
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;
std::vector<size_t> in_verIDs, out_verIDs;
std::vector<const char*> in_dev_type, out_dev_type;
std::vector<int> in_dev_id, out_dev_id;
std::vector<NDArray> conv_mkl; // converted NDArrays from MKLDNN format
// Extra data for sparse inputs and outputs.
std::vector<int> in_stypes(inputs.size(), 0), out_stypes(outputs.size(), 0);
std::vector<void*> in_indices(inputs.size(), nullptr), out_indices(outputs.size(), nullptr);
std::vector<void*> in_indptr(inputs.size(), nullptr), out_indptr(outputs.size(), nullptr);
std::vector<int64_t> in_indices_shapes(inputs.size(), 0), out_indices_shapes(outputs.size(), 0);
std::vector<int64_t> in_indptr_shapes(inputs.size(), 0), out_indptr_shapes(outputs.size(), 0);
// convert inputs/outpus NDArray to C types to be passed to lib_api.h
for (size_t i = 0; i < inputs.size(); i++) {
NDArray const* in_nd = &(inputs[i]);
#if MXNET_USE_MKLDNN == 1
// reorder data if in MKLDNN format
if (in_nd->IsMKLDNNData()) {
// convert from MKLDNN
conv_mkl.push_back(in_nd->Reorder2Default());
in_nd = &(conv_mkl.back());
}
#endif
// pull out parts to pass over to library
in_data.push_back(in_nd->data().dptr_);
in_shapes.push_back(in_nd->shape().data());
in_dims.push_back(in_nd->shape().ndim());
in_types.push_back(in_nd->dtype());
in_verIDs.push_back(in_nd->version());
// string repr of supported context for custom library, currently only "cpu" and "gpu"
const char* ctx_str = in_nd->ctx().dev_mask() == Context::kCPU ? "cpu" : "gpu";
in_dev_type.push_back(ctx_str);
in_dev_id.push_back(in_nd->ctx().real_dev_id());
if (inputs[i].storage_type() == mxnet::kRowSparseStorage) {
in_stypes[i] = 1;
in_indices[i] = inputs[i].aux_data(rowsparse::kIdx).dptr_;
in_indices_shapes[i] = inputs[i].aux_shape(rowsparse::kIdx).Size();
} else if (inputs[i].storage_type() == mxnet::kCSRStorage) {
in_stypes[i] = 2;
in_indices[i] = inputs[i].aux_data(csr::kIdx).dptr_;
in_indptr[i] = inputs[i].aux_data(csr::kIndPtr).dptr_;
in_indices_shapes[i] = inputs[i].aux_shape(csr::kIdx).Size();
in_indptr_shapes[i] = inputs[i].aux_shape(csr::kIndPtr).Size();
}
}
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());
out_verIDs.push_back(outputs[i].version());
const char* ctx_str = outputs[i].ctx().dev_mask() == Context::kCPU ? "cpu" : "gpu";
out_dev_type.push_back(ctx_str);
out_dev_id.push_back(outputs[i].ctx().real_dev_id());
if (outputs[i].storage_type() == mxnet::kRowSparseStorage) {
out_stypes[i] = 1;
out_indices[i] = outputs[i].aux_data(rowsparse::kIdx).dptr_;
out_indices_shapes[i] = outputs[i].aux_shape(rowsparse::kIdx).Size();
} else if (outputs[i].storage_type() == mxnet::kCSRStorage) {
out_stypes[i] = 2;
out_indices[i] = outputs[i].aux_data(csr::kIdx).dptr_;
out_indptr[i] = outputs[i].aux_data(csr::kIndPtr).dptr_;
out_indices_shapes[i] = outputs[i].aux_shape(csr::kIdx).Size();
out_indptr_shapes[i] = outputs[i].aux_shape(csr::kIndPtr).Size();
}
}
// get memory resource and mxnet backend streams
CHECK(ctx.requested.size() >= 2)
<< "Custom operator should register at least memory resource and parallel random resource";
const Resource &resource = ctx.requested.at(0);
mshadow::Stream<mxnet::cpu> *cpu_stream = ctx.get_stream<mxnet::cpu>();
mshadow::Stream<mxnet::gpu> *gpu_stream = ctx.get_stream<mxnet::gpu>();
// 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_;
};
auto gpu_alloc = [&](int size) {
mshadow::Tensor<mxnet::gpu, 1, char> workspace =
resource.get_space_typed<mxnet::gpu, 1, char>(mshadow::Shape1(size), gpu_stream);
return workspace.dptr_;
};
// create lambda that allocates memory for sparse and
// returns allocated arrays for data, indices and indptr.
auto sparse_alloc = [&](int index, int indices_len, int idxptr_len,
void** data, int64_t** indices, int64_t** indptr) {
if (idxptr_len == 0) {
// Row Sparse
outputs[index].CheckAndAlloc({mshadow::Shape1(indices_len)});
*data = outputs[index].data().dptr_;
*indices = reinterpret_cast<int64_t*>(outputs[index].aux_data(rowsparse::kIdx).dptr_);
} else {
// CSR
outputs[index].CheckAndAlloc({mshadow::Shape1(idxptr_len), mshadow::Shape1(indices_len)});
*data = outputs[index].data().dptr_;
*indices = reinterpret_cast<int64_t*>(outputs[index].aux_data(csr::kIdx).dptr_);
*indptr = reinterpret_cast<int64_t*>(outputs[index].aux_data(csr::kIndPtr).dptr_);
}
};
// create no-capture lambda so that we can cast it to function pointer
// lambda with captures cannot be cast to function pointer and pass to lib_api.h
// this needs to be a lambda function so that we can do the decltype cast
typedef decltype(cpu_alloc) alloc_type_cpu;
auto cpu_malloc = [](void* _cpu_alloc, int size) {
// cast the void* argument to the type for the cpu_alloc lambda function
alloc_type_cpu* cpualloc = static_cast<alloc_type_cpu*>(_cpu_alloc);
// call cpu_alloc to actually allocate memory and return the pointer
return static_cast<void*>((*cpualloc)(size));
};
using alloc_type_gpu = decltype(gpu_alloc);
auto gpu_malloc = [](void* _gpu_alloc, int size) {
alloc_type_gpu* gpualloc = static_cast<alloc_type_gpu*>(_gpu_alloc);
return static_cast<void*>((*gpualloc)(size));
};
using alloc_type_sparse = decltype(sparse_alloc);
auto sparse_malloc = [](void* _sparse_alloc, int index, int indices_len, int idxptr_len,
void** data, int64_t** indices, int64_t** indptr) {
alloc_type_sparse* sparsealloc = static_cast<alloc_type_sparse*>(_sparse_alloc);
(*sparsealloc)(index, indices_len, idxptr_len, data, indices, indptr);
};
// get actual cudaStream_t out of mxnet gpu stream and pass to lib_api.h
void *cuda_stream = nullptr;
#if MXNET_USE_CUDA
if ((inputs.size() > 0 && inputs[0].ctx().dev_mask() == Context::kGPU) ||
(outputs.size() > 0 && outputs[0].ctx().dev_mask() == Context::kGPU)) {
cuda_stream = static_cast<void*>(gpu_stream->stream_);
}
#endif
// get mxnet initialized and seeded RNG states and pass to lib_api.h
void *rng_cpu_states = nullptr, *rng_gpu_states = nullptr;
using mxnet::common::random::RandGenerator;
RandGenerator<cpu, float> *pgen_cpu = ctx.requested.at(1).get_parallel_random<cpu, float>();
rng_cpu_states = pgen_cpu->GetStates();
#if MXNET_USE_CUDA
RandGenerator<gpu, float> *pgen_gpu = ctx.requested.at(1).get_parallel_random<gpu, float>();
rng_gpu_states = pgen_gpu->GetStates();
#endif
CHECK((fcomp_fp != nullptr && state_ptr == nullptr)
|| (fcomp_fp == nullptr && state_ptr != nullptr))
<< "Can only register either regular op or stateful op for '" << op_name << "'";
if (fcomp_fp != nullptr) {
// 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());
}
// call fcompute function
int retval = 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_verIDs.data(), in_dev_type.data(), in_dev_id.data(), in_data.size(),
out_shapes.data(), out_dims.data(), out_data.data(), out_types.data(),
out_verIDs.data(), out_dev_type.data(), out_dev_id.data(),
out_data.size(),
cpu_malloc, &cpu_alloc, gpu_malloc, &gpu_alloc, cuda_stream,
sparse_malloc, &sparse_alloc, in_stypes.data(), out_stypes.data(),
in_indices.data(), out_indices.data(), in_indptr.data(),
out_indptr.data(),
in_indices_shapes.data(), out_indices_shapes.data(),
in_indptr_shapes.data(), out_indptr_shapes.data(),
rng_cpu_states, rng_gpu_states);
std::string msgs = getExtensionMsgs(msgSize, msgGet);
CHECK(retval) << "Error calling FCompute for custom operator '" << op_name << "'" << msgs;
}
if (state_ptr != nullptr) {
// retrieve op state object created from CreateOpState
CustomStatefulOpWrapper& op = state_ptr->get_state<CustomStatefulOpWrapper>();
CustomStatefulOp* state_op_inst = op.get_instance();
std::string msgs = getExtensionMsgs(msgSize, msgGet);
CHECK(state_op_inst != nullptr)
<< "Error custom stateful operator is null for operator '" << op_name << "'" << msgs;
// call fcompute function
int retval = callFStatefulComp(stateful_forward_flag, state_op_inst,
in_shapes.data(), in_dims.data(), in_data.data(),
in_types.data(),
in_verIDs.data(), in_dev_type.data(), in_dev_id.data(),
in_data.size(),
out_shapes.data(), out_dims.data(), out_data.data(),
out_types.data(),
out_verIDs.data(), out_dev_type.data(), out_dev_id.data(),
out_data.size(),
cpu_malloc, &cpu_alloc, gpu_malloc, &gpu_alloc, cuda_stream,
sparse_malloc, &sparse_alloc, in_stypes.data(),
out_stypes.data(), in_indices.data(), out_indices.data(),
in_indptr.data(), out_indptr.data(),
in_indices_shapes.data(), out_indices_shapes.data(),
in_indptr_shapes.data(), out_indptr_shapes.data(),
rng_cpu_states, rng_gpu_states);
msgs = getExtensionMsgs(msgSize, msgGet);
CHECK(retval) << "Error calling FStatefulCompute for custom operator '" << op_name << "'"
<< msgs;
}
}
template <typename RescReq, typename AttrParser, typename NumInputs, typename NumOutputs,
typename NumInOuts,
typename InferType, typename InferShape, typename InferSType, typename MutateInputs,
typename SubgraphNumInputs, typename SubgraphInferType, typename SubgraphInferShape,
typename SubgraphInferSType, typename CreateOpState, typename GradReg>
void registerOp(const char* name, const std::string& name_str, bool isSubgraphOp,
RescReq resc_req, AttrParser attr_parser, NumInputs num_inputs,
NumOutputs num_outputs, NumInOuts num_inouts, InferType infer_type,
InferShape infer_shape, InferSType infer_storage_type,
MutateInputs mutate_inputs, SubgraphNumInputs num_subgraph_inputs,
SubgraphInferType infer_subgraph_type, SubgraphInferShape infer_subgraph_shape,
SubgraphInferSType infer_subgraph_storage_type, CreateOpState create_opstate,
GradReg grad_reg, mxnet::ext::mutateInputs_t mutate_fp,
const std::unordered_map<std::string, mxnet::ext::createOpState_t> &createop_map,
const std::unordered_map<std::string, mxnet::ext::fcomp_t> &forward_ctx_map,
const std::unordered_map<std::string, mxnet::ext::fcomp_t> &backward_ctx_map,
mxnet::ext::opCallFComp_t callFComp,
mxnet::ext::opCallFStatefulComp_t callFStatefulComp,
mxnet::ext::msgSize_t msgSize,
mxnet::ext::msgGet_t msgGet) {
using namespace mxnet::ext;
// 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);
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++;
}
// define supported resources for both subgraph ops and regular ops
regOp.set_attr<FResourceRequest>("FResourceRequest", resc_req, plevel);
if (!isSubgraphOp) {
regOp.set_attr_parser(attr_parser);
regOp.set_num_inputs(num_inputs);
regOp.set_num_outputs(num_outputs);
regOp.set_attr<nnvm::FInferType>("FInferType", infer_type, plevel);
regOp.set_attr<FInferStorageType>("FInferStorageType", infer_storage_type, plevel);
regOp.set_attr<mxnet::FInferShape>("FInferShape", infer_shape, plevel);
// optionally add fmutate inputs if user specified a function
if (mutate_fp != nullptr)
regOp.set_attr<nnvm::FMutateInputs>("FMutateInputs", mutate_inputs, plevel);
} else {
using namespace mxnet::op;
regOp.set_num_inputs(num_subgraph_inputs);
regOp.set_num_outputs(DefaultSubgraphOpNumOutputs);
regOp.set_attr<nnvm::FInferType>("FInferType", infer_subgraph_type, plevel);
regOp.set_attr<mxnet::FInferShape>("FInferShape", infer_subgraph_shape, plevel);
regOp.set_attr<FInferStorageType>("FInferStorageType",
infer_subgraph_storage_type, plevel);
regOp.set_attr<nnvm::FMutateInputs>("FMutateInputs",
DefaultSubgraphOpMutableInputs, plevel);
}
// optionally add stateful forward
if (createop_map.size() != 0) {
regOp.set_attr<FCreateOpState>("FCreateOpState", create_opstate, plevel);
auto fstate_forward = [=](const OpStatePtr& state_ptr,
const OpContext& ctx,
const std::vector<NDArray>& inputs,
const std::vector<OpReqType>& req,
const std::vector<NDArray>& outputs) {
CustomFComputeDispatcher(name_str, nullptr, nullptr, nullptr,
callFStatefulComp, 1, &state_ptr, ctx, inputs, req, outputs,
msgSize, msgGet);
};
if (createop_map.count("cpu") > 0)
regOp.set_attr<FStatefulComputeEx>("FStatefulComputeEx<cpu>", fstate_forward, plevel);
if (createop_map.count("gpu") > 0)
regOp.set_attr<FStatefulComputeEx>("FStatefulComputeEx<gpu>", fstate_forward, plevel);
} else {
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) {
if (ctx.run_ctx.ctx.dev_mask() == Context::kCPU) {
CHECK_GT(forward_ctx_map.count("cpu"), 0);
fcomp_t fcomp = forward_ctx_map.at("cpu");
CustomFComputeDispatcher(name_str, callFComp, fcomp, &attrs,
nullptr, 0, nullptr, ctx, inputs, req, outputs, msgSize, msgGet);
} else if (ctx.run_ctx.ctx.dev_mask() == Context::kGPU) {
CHECK_GT(forward_ctx_map.count("gpu"), 0);
fcomp_t fcomp = forward_ctx_map.at("gpu");
CustomFComputeDispatcher(name_str, callFComp, fcomp, &attrs,
nullptr, 0, nullptr, ctx, inputs, req, outputs, msgSize, msgGet);
}
};
if (forward_ctx_map.count("cpu") > 0)
regOp.set_attr<FComputeEx>("FComputeEx<cpu>", forward_lambda, plevel);
if (forward_ctx_map.count("gpu") > 0)
regOp.set_attr<FComputeEx>("FComputeEx<gpu>", forward_lambda, plevel);
}
// optionally add fgradient if user specified a function, or for stateful ops
if (backward_ctx_map.size() != 0 || createop_map.size() != 0) {
std::string grad_name = "_backward_" + name_str;
nnvm::Op &gradOp = dmlc::Registry<nnvm::Op>::Get()->__REGISTER_OR_GET__(grad_name);
regOp.set_attr<nnvm::FGradient>("FGradient", grad_reg, plevel);
gradOp.set_attr<nnvm::TIsBackward>("TIsBackward", true, plevel);
gradOp.set_attr<FInferStorageType>("FInferStorageType", infer_storage_type, plevel);
gradOp.set_attr<FResourceRequest>("FResourceRequest", resc_req, plevel);
if (!isSubgraphOp) {
// register attr parser and standard functions for non-subgraph ops
gradOp.set_attr_parser(attr_parser);
gradOp.set_num_inputs(num_inouts);
gradOp.set_num_outputs(num_inputs);
} else {
// for subgraph ops use special functions that do not invoke attr_parser
using namespace mxnet::op;
auto grad_inouts = [=](const nnvm::NodeAttrs& attrs) {
// for backward passes, inputs + outputs + input gradients (one for each output)
uint32_t cnt = num_subgraph_inputs(attrs);
cnt += 2 * DefaultSubgraphOpNumOutputs(attrs);
return cnt;
};
gradOp.set_num_inputs(grad_inouts);
gradOp.set_num_outputs(num_subgraph_inputs);
}
if (createop_map.size() != 0) {
// for stateful operators
gradOp.set_attr<bool>("TIsLayerOpBackward", true, plevel);
auto fstate_backward = [=](const OpStatePtr& state_ptr,
const OpContext& ctx,
const std::vector<NDArray>& inputs,
const std::vector<OpReqType>& req,
const std::vector<NDArray>& outputs) {
CustomFComputeDispatcher(name_str, nullptr, nullptr, nullptr,
callFStatefulComp, 0, &state_ptr, ctx, inputs, req, outputs,
msgSize, msgGet);
};
gradOp.set_attr<FStatefulComputeEx>("FStatefulComputeEx<cpu>", fstate_backward, plevel);
gradOp.set_attr<FStatefulComputeEx>("FStatefulComputeEx<gpu>", fstate_backward, plevel);
} else {
// for stateless operators
if (backward_ctx_map.count("cpu") > 0) {
fcomp_t fcomp_back_cpu = backward_ctx_map.at("cpu");
auto backward_cpu_lambda = [=](const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<NDArray>& inputs,
const std::vector<OpReqType>& req,
const std::vector<NDArray>& outputs) {
CustomFComputeDispatcher(name_str, callFComp, fcomp_back_cpu, &attrs,
nullptr, 0, nullptr, ctx, inputs, req, outputs, msgSize, msgGet);
};
gradOp.set_attr<FComputeEx>("FComputeEx<cpu>", backward_cpu_lambda, plevel);
}
if (backward_ctx_map.count("gpu") > 0) {
fcomp_t fcomp_back_gpu = backward_ctx_map.at("gpu");
auto backward_gpu_lambda = [=](const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<NDArray>& inputs,
const std::vector<OpReqType>& req,
const std::vector<NDArray>& outputs) {
CustomFComputeDispatcher(name_str, callFComp, fcomp_back_gpu, &attrs,
nullptr, 0, nullptr, ctx, inputs, req, outputs, msgSize, msgGet);
};
gradOp.set_attr<FComputeEx>("FComputeEx<gpu>", backward_gpu_lambda, plevel);
}
}
}
regOp.add_argument("data", "NDArray[]", "Source inputs");
}
void registerOperators(void *lib, int verbose, mxnet::ext::msgSize_t msgSize,
mxnet::ext::msgGet_t msgGet) {
using namespace mxnet::ext;
// 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));
opCallInferSType_t callInferSType =
get_func<opCallInferSType_t>(lib, const_cast<char*>(MXLIB_OPCALLINFERSTYPE_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();
if (verbose) 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
parseAttrs_t parse_fp = nullptr;
inferType_t type_fp = nullptr;
inferSType_t stype_fp = nullptr;
inferShape_t shape_fp = nullptr;
// optional attributes
mutateInputs_t mutate_fp = nullptr;
bool isSubgraphOp = false;
int _isSubgraphOp = 0;
// lists of forward and backward function associated with each context
const char **forward_ctx, **backward_ctx, **createop_ctx;
fcomp_t *forward_fcomp, *backward_fcomp;
createOpState_t *createop_fp;
int forward_count, backward_count, createop_count;
// main function to get custom operator implemenation from the custom library
opRegGet(i, &name, &_isSubgraphOp,
&forward_ctx, &forward_fcomp, &forward_count,
&backward_ctx, &backward_fcomp, &backward_count,
&createop_ctx, &createop_fp, &createop_count,
&parse_fp, &type_fp, &stype_fp, &shape_fp, &mutate_fp);
// construct maps of context to forward/backward custom library function
std::unordered_map<std::string, fcomp_t> forward_ctx_map;
std::unordered_map<std::string, fcomp_t> backward_ctx_map;
std::unordered_map<std::string, createOpState_t> createop_map;
for (int i=0; i < forward_count; i++) {
std::string ctx_str(forward_ctx[i]);
forward_ctx_map[ctx_str] = forward_fcomp[i];
}
for (int i=0; i < backward_count; i++) {
std::string ctx_str(backward_ctx[i]);
backward_ctx_map[ctx_str] = backward_fcomp[i];
}
for (int i=0; i < createop_count; i++) {
std::string ctx_str(createop_ctx[i]);
createop_map[ctx_str] = createop_fp[i];
}
// set bool, dont pass bool across ABI boundary
isSubgraphOp = _isSubgraphOp;
// validate custom operator functions from the dynamic library
if (!isSubgraphOp) {
CHECK(parse_fp != nullptr) << "Error loading '" << name
<< "' custom op, ParseAttrs function was not set.";
CHECK(forward_ctx_map.size() != 0 || createop_map.size() != 0)
<< "Error loading '" << name
<< "' custom op, Forward or CreateOpState 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.";
} else {
CHECK(createop_map.size() != 0) << "Error loading '" << name
<< "' custom subgraph op, CreateOpState function was not set.";
}
if (verbose) LOG(INFO) << "\tOp[" << i << "] " << name;
if (verbose && isSubgraphOp) LOG(INFO) << "\t\tisSubgraphOp";
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(MX_STR_SUBGRAPH_SYM_JSON);
attr_vals.push_back(subgraph_json.c_str());
}
int num_in = -1;
int num_out = -1;
int retval = callParseAttrs(parse_fp, attr_keys.data(), attr_vals.data(), attr_keys.size(),
&num_in, &num_out);
std::string msgs = getExtensionMsgs(msgSize, msgGet);
CHECK(retval) << "Error calling ParseAttrs for custom operator '" << name_str << "'" << msgs;
// 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;
int retval = callParseAttrs(parse_fp, attr_keys.data(), attr_vals.data(), attr_keys.size(),
&num_in, &num_out);
std::string msgs = getExtensionMsgs(msgSize, msgGet);
CHECK(retval) << "Error calling ParseAttrs::num_inputs for custom operator '" << name_str
<< "'" << msgs;
// get extra inputs, if exists
int extra_inputs = 0;
if (attrs.dict.count(MX_STR_EXTRA_INPUTS) > 0)
extra_inputs = std::stoi(attrs.dict.at(MX_STR_EXTRA_INPUTS));
return num_in + extra_inputs;
};
// lambda function to call parse attributes and return the number of inputs for subgraph ops
auto num_subgraph_inputs = [=](const NodeAttrs& attrs) {
// get number of inputs for subgraph
int num_in = mxnet::op::DefaultSubgraphOpNumInputs(attrs);
// get extra inputs, if exists
int extra_inputs = 0;
if (attrs.dict.count(MX_STR_EXTRA_INPUTS) > 0)
extra_inputs = std::stoi(attrs.dict.at(MX_STR_EXTRA_INPUTS));
return num_in + extra_inputs;
};
// 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;
int retval = callParseAttrs(parse_fp, attr_keys.data(), attr_vals.data(), attr_keys.size(),
&num_in, &num_out);
std::string msgs = getExtensionMsgs(msgSize, msgGet);
CHECK(retval) << "Error calling ParseAttrs::num_outputs for custom operator '" << name_str
<< "'" << msgs;
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;
int retval = callParseAttrs(parse_fp, attr_keys.data(), attr_vals.data(), attr_keys.size(),
&num_in, &num_out);
std::string msgs = getExtensionMsgs(msgSize, msgGet);
CHECK(retval) << "Error calling ParseAttrs::num_outputs for custom operator '" << name_str
<< "'" << msgs;
// for backward passes, inputs + outputs + input gradients (one for each output)
// get extra inputs, if exists
int extra_inputs = 0;
if (attrs.dict.count(MX_STR_EXTRA_INPUTS) > 0)
extra_inputs = std::stoi(attrs.dict.at(MX_STR_EXTRA_INPUTS));
return num_in + extra_inputs + 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());
}
// get extra inputs, if exists
int extra_inputs = 0;
if (attrs.dict.count(MX_STR_EXTRA_INPUTS) > 0)
extra_inputs = std::stoi(attrs.dict.at(MX_STR_EXTRA_INPUTS));
int num_inputs = in_shape->size() - extra_inputs;
std::vector<uint32_t*> inshapes(num_inputs);
std::vector<int> indims(num_inputs);
// determine amount of memory needed to store all the input shapes
size_t buff_size = 0;
for (size_t i = 0; i < num_inputs; ++i)
buff_size += (*in_shape)[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 < num_inputs; ++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]);
}
}
// modified input shapes will be allocated by infer shape function
uint32_t** mod_inshapes = nullptr;
int* mod_indims = nullptr;
// output shapes will be allocated by infer shape function
uint32_t** outshapes = nullptr;
int* outdims = nullptr;
int retval = callInferShape(shape_fp, attr_keys.data(), attr_vals.data(), attr_keys.size(),
inshapes.data(), indims.data(), num_inputs,
&mod_inshapes, &mod_indims,
&outshapes, &outdims, out_shape->size());
std::string msgs = getExtensionMsgs(msgSize, msgGet);
CHECK(retval) << "Error calling InferShape for custom operator '" << name_str << "'" << msgs;
std::vector<uint32_t*> in_shapes(num_inputs);
// determine amount of memory needed to store all the modified input shapes
buff_size = 0;
for (unsigned i = 0; i < num_inputs; i++) {
buff_size += mod_indims[i];
}
// copy modified input shapes from custom op memory to MXNet memory
std::vector<uint32_t> mod_inbuff(buff_size);
ptr = mod_inbuff.data();
for (unsigned i = 0; i < num_inputs; ++i) {
in_shapes[i] = ptr;
for (int j = 0; j < mod_indims[i]; ++j, ++ptr) {
*ptr = static_cast<uint32_t>(mod_inshapes[i][j]);
}
}
// assign modified input shapes to ShapeVector
for (unsigned i = 0; i < num_inputs; ++i) {
SHAPE_ASSIGN_CHECK(*in_shape, i,
mxnet::TShape(in_shapes[i], in_shapes[i]+mod_indims[i]));
}
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(mod_indims);
for (unsigned i = 0; i < num_inputs; i++) {
callFree(mod_inshapes[i]);
}
callFree(mod_inshapes);
callFree(outdims);
for (unsigned i = 0; i < out_shape->size(); i++) {
callFree(outshapes[i]);
}
callFree(outshapes);
return true;
};
// lambda function to call infer shape for subgraph ops
auto infer_subgraph_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());
}
// get extra inputs, if exists
int extra_inputs = 0;
if (attrs.dict.count(MX_STR_EXTRA_INPUTS) > 0)
extra_inputs = std::stoi(attrs.dict.at(MX_STR_EXTRA_INPUTS));
auto in_first = in_shape->begin();
auto in_last = in_first + in_shape->size() - extra_inputs;
mxnet::ShapeVector *sg_in_shapes = new mxnet::ShapeVector(in_first, in_last);
return mxnet::op::DefaultSubgraphOpShape(attrs, sg_in_shapes, out_shape);
};
// 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());
}
// get extra inputs, if exists
int extra_inputs = 0;
if (attrs.dict.count(MX_STR_EXTRA_INPUTS) > 0)
extra_inputs = std::stoi(attrs.dict.at(MX_STR_EXTRA_INPUTS));
int num_inputs = in_type->size() - extra_inputs;
// 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());
int retval = callInferType(type_fp, attr_keys.data(), attr_vals.data(), attr_keys.size(),
intypes.data(), num_inputs,
outtypes.data(), out_type->size());
std::string msgs = getExtensionMsgs(msgSize, msgGet);
CHECK(retval) << "Error calling InferType for custom operator '" << name_str << "'" << msgs;
// copy and assign modified input types from custom op to MXNet memory
for (size_t i = 0; i < num_inputs; i++) {
TYPE_ASSIGN_CHECK(*in_type, i, intypes[i]);
}
// 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 call infer type for subgraph ops
auto infer_subgraph_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());
}
// get extra inputs, if exists
int extra_inputs = 0;
if (attrs.dict.count(MX_STR_EXTRA_INPUTS) > 0)
extra_inputs = std::stoi(attrs.dict.at(MX_STR_EXTRA_INPUTS));
auto in_first = in_type->begin();
auto in_last = in_first + in_type->size() - extra_inputs;
std::vector<int> *sg_in_types = new std::vector<int>(in_first, in_last);
return mxnet::op::DefaultSubgraphOpType(attrs, sg_in_types, out_type);
};
// 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
int retval = callMutateInputs(mutate_fp, attr_keys.data(), attr_vals.data(), attr_keys.size(),
&mutate_indices, &indices_size);
std::string msgs = getExtensionMsgs(msgSize, msgGet);
CHECK(retval) << "Error calling MutateInputs for custom operator '" << name_str << "'"
<< msgs;
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) {
if (stype_fp == nullptr) {
// InferSType is not defined in customized lib.
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);
} else {
// InferSType is defined in customized lib.
// 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());
}
// get extra inputs, if exists
int extra_inputs = 0;
if (attrs.dict.count(MX_STR_EXTRA_INPUTS) > 0)
extra_inputs = std::stoi(attrs.dict.at(MX_STR_EXTRA_INPUTS));
int num_inputs = in_stypes->size() - extra_inputs;
// copy input types from in_stype
std::vector<int> instypes(*in_stypes);
// output types will be populated by inferType function
std::vector<int> outstypes(out_stypes->size());