-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathodla_dnnl.cc
1938 lines (1735 loc) · 71 KB
/
odla_dnnl.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
//===- odla_dnnl.cc -------------------------------------------------------===//
//
// Copyright (C) 2019-2020 Alibaba Group Holding Limited.
//
// 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 <ODLA/odla.h>
#include <cassert>
#include <cmath>
#include <cstddef>
#include <cstring>
#include <iostream>
#include <numeric>
#include <unordered_map>
#include <vector>
#include "ODLA/odla_compute.h"
#include "dnnl.hpp"
#include "dnnl_threadpool_iface.hpp"
#include "dnnl_utils.h"
#if !defined(ODLA_VERSION_NUMBER) || (ODLA_VERSION_NUMBER < 50)
#error This library requires minimum ODLA version 0.5
#endif
struct _odla_value {
dnnl::memory mem;
bool is_const;
uint8_t elem_size;
odla_value_shape shape;
std::string name;
_odla_value(const dnnl::memory& m, const odla_value_shape& shape_,
const std::string& id)
: mem(m), is_const(false), shape(shape_), name(id), elem_size(4) {
if (shape.size == 0) {
shape.size = 1;
shape.dims[0] = 1;
}
}
};
typedef struct TargetOpts {
odla_bf16_mode bf16_mode;
} target_opts;
struct operation {
void execute(dnnl::stream& stream) {
if (func) {
return func();
}
prim.execute(stream, args);
}
dnnl::primitive prim;
std::function<void()> func;
std::unordered_map<int, dnnl::memory> args;
};
struct _odla_computation {
dnnl::engine eng;
// std::vector<dnnl::primitive> primitives;
// std::vector<std::unordered_map<int, dnnl::memory>> args;
std::vector<operation> ops;
std::vector<std::unique_ptr<_odla_value>> vals;
std::unordered_map<std::string, odla_value> inputs;
std::unordered_map<std::string, odla_value> outputs;
std::unordered_map<std::string, std::pair<odla_value, void*>> outputs_v;
target_opts opts;
_odla_computation() : eng(dnnl::engine::kind::cpu, 0), opts({BF16_DISABLE}) {}
};
struct _odla_context {
odla_computation comp;
std::unique_ptr<dnnl::stream> stream;
};
static dnnl::memory::format_tag getFormatTag(const odla_value_shape& od) {
static const dnnl::memory::format_tag tags[] = {
dnnl::memory::format_tag::undef, dnnl::memory::format_tag::a,
dnnl::memory::format_tag::ab, dnnl::memory::format_tag::abc,
dnnl::memory::format_tag::abcd, dnnl::memory::format_tag::abcde,
dnnl::memory::format_tag::abcdef,
};
return (od.size <= 0 || od.size > 6) ? tags[0] : tags[od.size];
}
static dnnl::memory::format_tag getFormatTag(odla_memory_layout layout,
unsigned group = 1) {
switch (layout) {
case ODLA_CHANNELS_FIRST:
return dnnl::memory::format_tag::nchw;
case ODLA_CHANNELS_LAST:
return dnnl::memory::format_tag::nhwc;
case ODLA_SIO:
return (group > 1) ? dnnl::memory::format_tag::hwigo
: dnnl::memory::format_tag::hwio;
case ODLA_OIS:
return (group > 1) ? dnnl::memory::format_tag::goihw
: dnnl::memory::format_tag::oihw;
case ODLA_IOS:
return (group > 1) ? dnnl::memory::format_tag::giohw
: dnnl::memory::format_tag::iohw;
default:
assert(0);
return dnnl::memory::format_tag::any;
}
}
static int64_t GetTotalElements(const odla_value_shape& dims) {
return std::accumulate(dims.dims, dims.dims + dims.size, 1,
std::multiplies<size_t>());
}
// The strides used by DNNL's memory desc.
static dnnl::memory::dims getStrides(const odla_value_shape& od) {
std::vector<int64_t> strides(od.size, 1);
for (int i = od.size - 2; i >= 0; --i)
strides[i] = strides[i + 1] * od.dims[i + 1];
auto dims = dnnl::memory::dims(strides);
return dims;
}
static int GetDataSize(dnnl::memory::data_type dt) {
switch (dt) {
case dnnl::memory::data_type::s8:
return 1;
case dnnl::memory::data_type::bf16:
return 2;
case dnnl::memory::data_type::f32:
case dnnl::memory::data_type::s32:
return 4;
}
assert(0 && "invalid data type");
return 0;
}
static dnnl::memory::data_type getDataType(const odla_element_type ty) {
dnnl::memory::data_type dt;
switch (ty) {
case ODLA_FLOAT32:
dt = dnnl::memory::data_type::f32;
break;
case ODLA_INT8:
dt = dnnl::memory::data_type::s8;
break;
case ODLA_INT32:
dt = dnnl::memory::data_type::s32;
break;
case ODLA_INT64:
dt = dnnl::memory::data_type::s32; // FIXME:
break;
case ODLA_BFLOAT16:
dt = dnnl::memory::data_type::bf16;
break;
default:
dt = dnnl::memory::data_type::undef;
}
return dt;
}
// get shape total element size.
static inline int64_t GetCountFromAxis(const odla_value_shape& shape,
const odla_int32 axis) {
int64_t size = 1;
for (int i = axis; i < shape.size; i++) {
size = size * shape.dims[i];
}
return size;
}
template <typename Tin, typename Tout>
static void ArgMax(const Tin* input, Tout* output, odla_int32 axis,
const odla_value_shape& shape) {
int64_t dim, axis_dist;
axis = axis < 0 ? shape.size + axis : axis;
dim = shape.dims[axis];
// Distance between values of axis in blob
axis_dist = GetCountFromAxis(shape, axis) / dim;
int num = GetCountFromAxis(shape, 0) / dim;
std::vector<std::pair<Tin, Tout>> output_data_vector(dim);
for (int i = 0; i < num; ++i) {
for (Tout j = 0; j < dim; ++j) {
output_data_vector[j] = std::make_pair(
input[(i / axis_dist * dim + j) * axis_dist + i % axis_dist], j);
}
std::partial_sort(output_data_vector.begin(),
output_data_vector.begin() + 1, output_data_vector.end(),
std::greater<std::pair<Tin, Tout>>());
// Produces max_ind per axis
output[(i / axis_dist) * axis_dist + i % axis_dist] =
output_data_vector[0].second;
}
}
static dnnl::memory::dims getDims(const odla_value_shape& od) {
auto dims = dnnl::memory::dims(od.dims, od.dims + od.size);
return dims;
}
static dnnl::memory::desc getMemoryDesc(const odla_value_shape& dims,
dnnl::memory::data_type ty) {
return dnnl::memory::desc(getDims(dims), ty, getFormatTag(dims));
}
static dnnl::memory::desc getMemoryDesc(const odla_value_shape& dims,
odla_element_type ty) {
return dnnl::memory::desc(getDims(dims), getDataType(ty), getFormatTag(dims));
}
static dnnl::memory::desc getMemoryDesc(const odla_value_type& ty) {
return getMemoryDesc(ty.shape, ty.element_type);
}
thread_local odla_computation g_comp;
static std::vector<std::unique_ptr<_odla_computation>> g_comps;
thread_local bool g_interpret_mode = false;
static void add_op(dnnl::primitive prim,
const std::unordered_map<int, dnnl::memory>& args) {
operation op;
op.prim = prim;
op.args = args;
g_comp->ops.emplace_back(op);
}
static void add_op(std::function<void()> func) {
operation op;
op.func = func;
g_comp->ops.emplace_back(op);
}
#ifdef ODLA_DNNL_BUILD_AS_INTERPRETER
struct Initializer {
Initializer() {
odla_CreateComputation(nullptr);
g_interpret_mode = true;
}
};
static Initializer interpreter_initializer;
#endif
static odla_value CreateValue(const dnnl::memory& mem,
const odla_value_shape shape,
const odla_value_id id) {
std::string name = id == nullptr ? "" : std::string((const char*)id);
auto v = std::make_unique<_odla_value>(mem, shape, name);
auto ret = v.get();
g_comp->vals.push_back(std::move(v));
return ret;
}
static dnnl::memory cast_odla_mem(dnnl::memory src_mem,
const odla_value_shape shape,
const dnnl::memory::data_type dt,
const bool is_const) {
auto dst_md = dnnl::memory::desc(getDims(shape), dt, getFormatTag(shape));
auto dst_mem = dnnl::memory(dst_md, g_comp->eng);
auto r = dnnl::reorder(src_mem, dst_mem);
if (is_const) {
r.execute(dnnl::stream(g_comp->eng),
{{DNNL_ARG_FROM, src_mem}, {DNNL_ARG_TO, dst_mem}});
} else {
add_op(r, {{DNNL_ARG_FROM, src_mem}, {DNNL_ARG_TO, dst_mem}});
}
return dst_mem;
}
static dnnl::memory cast_op(odla_value& input, dnnl::memory::data_type dt) {
auto src_md = dnnl::memory::desc(getDims(input->shape),
input->mem.get_desc().data_type(),
getFormatTag(input->shape));
auto src_mem =
dnnl::memory(src_md, g_comp->eng, input->mem.get_data_handle());
return cast_odla_mem(src_mem, input->shape, dt, input->is_const);
}
extern "C" {
odla_status odla_SetComputationItem(odla_computation comp, odla_item_type type,
odla_item_value value) {
switch (type) {
case ODLA_BF16_MODE:
comp->opts.bf16_mode = *(reinterpret_cast<odla_bf16_mode*>(value));
break;
default:
std::cerr << "Unsupported property type: " << type << std::endl;
return ODLA_FAILURE;
}
return ODLA_SUCCESS;
}
odla_status odla_CreateComputation(odla_computation* computation) {
g_comps.push_back(std::make_unique<_odla_computation>());
g_comp = g_comps.back().get();
if (computation != nullptr) {
*computation = g_comp;
}
return ODLA_SUCCESS;
}
odla_status odla_SetActiveComputation(odla_computation computation) {
g_comp = computation;
return ODLA_SUCCESS;
}
odla_status odla_DestroyComputation(odla_computation computation) {
// TODO:
return ODLA_SUCCESS;
}
odla_status odla_CreateContext(odla_context* ctx) {
*ctx = new _odla_context();
(*ctx)->comp = g_comp;
return ODLA_SUCCESS;
}
odla_status odla_DestroyContext(odla_context ctx) {
delete (ctx);
return ODLA_SUCCESS;
}
odla_status odla_ExecuteComputation(odla_computation comp, odla_context context,
odla_compute_mode mode,
odla_device device) {
if (context->stream == nullptr) {
context->stream = std::make_unique<dnnl::stream>(comp->eng);
}
for (auto& op : comp->ops) {
op.execute(*context->stream);
}
context->stream->wait();
// copy to outputs
auto outputs_v = context->comp->outputs_v;
for (auto& output_pair : outputs_v) {
auto& src_val = output_pair.second.first;
auto& dst_ptr = output_pair.second.second;
memcpy(dst_ptr, src_val->mem.get_data_handle(),
GetTotalElements(src_val->shape) * src_val->elem_size);
}
return ODLA_SUCCESS;
}
static void InterpretIfNeeded() {
#if ODLA_DNNL_BUILD_AS_INTERPRETER
if (!g_interpret_mode) {
return;
}
static odla_context context;
if (!context) {
odla_CreateContext(&context);
}
if (context->stream == nullptr) {
context->stream = std::make_unique<dnnl::stream>(g_comp->eng);
}
for (auto& op : g_comp->ops) {
op.execute(*context->stream);
}
context->stream->wait();
g_comp->ops.clear();
#endif
}
void rewrite_scalar_type(odla_value_type& type) {
if (type.shape.size == 0) {
type.shape.size = 1;
type.shape.dims[0] = 1;
}
}
odla_value odla_CreateArgument(odla_value_type type, const odla_value_id id) {
const char* name = (const char*)id;
rewrite_scalar_type(type);
if (g_comp->opts.bf16_mode == BF16_PERFORMACE_MODE &&
type.element_type == ODLA_FLOAT32) {
type.element_type = ODLA_BFLOAT16;
}
dnnl::memory::desc md = getMemoryDesc(type);
dnnl::memory mem = dnnl::memory(md, g_comp->eng);
odla_value v = CreateValue(mem, type.shape, id);
if (type.element_type == ODLA_INT64) {
v->elem_size = 8;
}
g_comp->inputs[name] = v;
return v;
}
odla_value odla_CreateValue(odla_value_type type, const odla_value_id id) {
assert(g_interpret_mode);
rewrite_scalar_type(type);
auto v = odla_CreateArgument(type, id);
return v;
}
odla_status odla_GetValueType(const odla_value value,
odla_value_type* value_type) {
value_type->element_type = ODLA_FLOAT32;
value_type->shape = value->shape;
return ODLA_SUCCESS;
}
odla_status odla_BindToArgument(odla_value value, const odla_void* data_ptr,
odla_context context) {
if (context->comp->opts.bf16_mode == BF16_PERFORMACE_MODE &&
value->mem.get_desc().data_type() == dnnl::memory::data_type::bf16) {
auto src_md = dnnl::memory::desc(value->mem.get_desc().dims(),
getDataType(ODLA_FLOAT32),
getFormatTag(value->shape));
auto src_mem =
dnnl::memory(src_md, context->comp->eng, const_cast<void*>(data_ptr));
auto r = dnnl::reorder(src_mem, value->mem);
r.execute(dnnl::stream(context->comp->eng),
{{DNNL_ARG_FROM, src_mem}, {DNNL_ARG_TO, value->mem}});
} else {
value->mem.set_data_handle(const_cast<void*>(data_ptr));
}
return ODLA_SUCCESS;
}
odla_status odla_SetValueData(odla_value value, const void* ptr) {
assert(g_interpret_mode);
value->mem.set_data_handle(const_cast<void*>(ptr));
return ODLA_SUCCESS;
}
odla_status odla_GetValueData(const odla_value value, odla_void* data_ptr) {
assert(g_interpret_mode == true);
memcpy(data_ptr, value->mem.get_data_handle(),
value->mem.get_desc().get_size());
return ODLA_SUCCESS;
}
odla_status odla_BindToArgumentById(const odla_value_id value_id,
const odla_void* data_ptr,
odla_context context) {
std::string name((const char*)value_id);
odla_value value = context->comp->inputs[name];
return odla_BindToArgument(value, data_ptr, context);
}
odla_value odla_CreateConstant(odla_value_type type, const void* ptr,
const odla_value_id id) {
// TODO:
// dnnl::memory::desc md(getDims(dims), getDataType(type),
// dnnl::memory::format_tag::hwio);
rewrite_scalar_type(type);
dnnl::memory::desc md = getMemoryDesc(type);
dnnl::memory mem = dnnl::memory(md, g_comp->eng, const_cast<void*>(ptr));
if (g_comp->opts.bf16_mode == BF16_PERFORMACE_MODE &&
type.element_type == ODLA_FLOAT32) {
type.element_type = ODLA_BFLOAT16;
mem = cast_odla_mem(mem, type.shape, getDataType(type.element_type), true);
}
odla_value v = CreateValue(mem, type.shape, id);
v->is_const = true;
if (type.element_type == ODLA_INT64) {
v->elem_size = 8;
}
return v;
}
odla_status odla_SetValueAsOutput(const odla_value val) {
g_comp->outputs[val->name] = val;
// convert output to float32
if (g_comp->opts.bf16_mode != BF16_DISABLE &&
val->mem.get_desc().data_type() == dnnl::memory::data_type::bf16) {
val->mem =
cast_odla_mem(val->mem, val->shape, getDataType(ODLA_FLOAT32), false);
}
return ODLA_SUCCESS;
}
odla_status odla_BindToOutput(odla_value value, odla_void* data_ptr,
odla_context context) {
// Handle the case of output is constant due to compile-time optimization.
if (value->is_const) {
size_t len = value->mem.get_desc().get_size();
if (value->elem_size == 8) {
len *= 2;
}
memcpy(data_ptr, value->mem.get_data_handle(), len);
} else {
auto name = value->name;
auto& outputs_v = context->comp->outputs_v;
auto val = context->comp->outputs[name];
outputs_v[name] = {val, data_ptr};
}
return ODLA_SUCCESS;
}
odla_status odla_BindToOutputById(const odla_value_id value_id,
odla_void* data_ptr, odla_context context) {
std::string name((const char*)value_id);
auto& outputs_v = context->comp->outputs_v;
auto val = context->comp->outputs[name];
outputs_v[name] = {val, data_ptr};
return ODLA_SUCCESS;
}
odla_value odla_Floor(odla_value input, const odla_value_id id) {
int64_t total_elems = GetTotalElements(input->shape);
auto ret_md = input->mem.get_desc();
auto ret_mem = dnnl::memory(ret_md, g_comp->eng);
std::function<void()> op;
if (g_comp->opts.bf16_mode == BF16_PERFORMACE_MODE) {
op = [total_elems, input, ret_mem]() {
dnnl_utils::floorbf_func(total_elems,
(int16_t*)input->mem.get_data_handle(),
(float*)ret_mem.get_data_handle());
};
} else {
op = [total_elems, input, ret_mem]() {
dnnl_utils::floorf_func(total_elems, (float*)input->mem.get_data_handle(),
(float*)ret_mem.get_data_handle());
};
}
add_op(op);
InterpretIfNeeded();
return CreateValue(ret_mem, input->shape, id);
}
odla_value odla_Rsqrt(odla_value input, const odla_value_id id) {
int64_t total_elems = GetTotalElements(input->shape);
auto ret_md = input->mem.get_desc();
auto ret_mem = dnnl::memory(ret_md, g_comp->eng);
std::function<void()> op;
if (g_comp->opts.bf16_mode == BF16_PERFORMACE_MODE) {
op = [total_elems, input, ret_mem]() {
dnnl_utils::rsqrtbf_func(total_elems,
(int16_t*)input->mem.get_data_handle(),
(float*)ret_mem.get_data_handle());
};
} else {
op = [total_elems, input, ret_mem]() {
dnnl_utils::rsqrtf_func(total_elems, (float*)input->mem.get_data_handle(),
(float*)ret_mem.get_data_handle());
};
}
add_op(op);
InterpretIfNeeded();
return CreateValue(ret_mem, input->shape, id);
}
odla_value odla_Gather(odla_value params, const odla_value indices,
odla_int32 axis, odla_value_shape output_dims,
const odla_value_id id) {
std::function<void()> op;
axis = axis < 0 ? params->shape.size + axis : axis;
size_t batch_size;
size_t idx_size;
auto dt = params->mem.get_desc().data_type();
if (indices->shape.size > 1) {
batch_size = indices->shape.dims[0];
idx_size = indices->shape.dims[1];
} else {
batch_size = 1;
idx_size = indices->shape.dims[0];
}
size_t inner_size = 1;
size_t outer_loop = 1;
for (int i = axis + 1; i < params->shape.size; ++i) {
inner_size *= params->shape.dims[i];
}
size_t outer_size = inner_size * params->shape.dims[axis];
for (int i = 0; i < axis; ++i) {
outer_loop *= params->shape.dims[i];
}
auto ret_md =
dnnl::memory::desc(getDims(output_dims), dt, getFormatTag(output_dims));
auto ret_mem = dnnl::memory(ret_md, g_comp->eng);
int byte_size =
params->mem.get_desc().get_size() / GetTotalElements(params->shape);
auto one_batch_byte_size =
GetTotalElements(output_dims) / batch_size * byte_size;
op = [params, indices, batch_size, idx_size, inner_size, outer_loop,
outer_size, byte_size, ret_mem, one_batch_byte_size, axis]() {
int32_t* indices_ptr = (int32_t*)indices->mem.get_data_handle();
std::vector<int> indices_i32;
if (indices->elem_size == 8) {
int64_t* src = (int64_t*)indices_ptr;
indices_i32.insert(indices_i32.begin(), src, src + idx_size);
indices_ptr = indices_i32.data();
}
char* ret_ptr = (char*)ret_mem.get_data_handle();
#pragma omp parallel for
for (int i = 0; i < batch_size; i++) {
dnnl_utils::gather_func((char*)params->mem.get_data_handle(),
indices_ptr + i * idx_size, idx_size, inner_size,
outer_loop, outer_size, byte_size,
ret_ptr + i * one_batch_byte_size);
}
};
add_op(op);
InterpretIfNeeded();
return CreateValue(ret_mem, output_dims, id);
}
odla_value odla_Cast(odla_value input, odla_element_type target_type,
const odla_value_id id) {
auto dst_mem = cast_op(input, getDataType(target_type));
InterpretIfNeeded();
return CreateValue(dst_mem, input->shape, id);
}
static odla_value unary_eltwise_op(
dnnl::algorithm algo, odla_value input, odla_float32 alpha,
odla_float32 beta, const odla_value_id id,
dnnl::primitive_attr attr = dnnl::primitive_attr()) {
auto eltwise_d =
dnnl::eltwise_forward::desc(dnnl::prop_kind::forward_inference, algo,
input->mem.get_desc(), alpha, beta);
auto pd = dnnl::eltwise_forward::primitive_desc(eltwise_d, attr, g_comp->eng);
dnnl::primitive prim = dnnl::eltwise_forward(pd);
auto ret_mem = dnnl::memory(input->mem.get_desc(), g_comp->eng);
odla_value v = CreateValue(ret_mem, input->shape, id);
add_op(prim, {{DNNL_ARG_SRC, input->mem}, {DNNL_ARG_DST, ret_mem}});
InterpretIfNeeded();
return v;
}
static odla_value binary_eltwise_s32(dnnl::algorithm alg, dnnl::memory lhs_mem,
dnnl::memory rhs_mem,
odla_value_shape shape,
const odla_value_id id) {
std::function<void()> elem_op;
int ln = GetTotalElements(shape);
elem_op = [lhs_mem, rhs_mem, ln, alg]() {
int32_t* rhs_ptr = nullptr;
rhs_ptr = (int32_t*)rhs_mem.get_data_handle();
dnnl_utils::binary_s32_func(alg, (int32_t*)lhs_mem.get_data_handle(),
rhs_ptr, rhs_ptr, ln);
};
add_op(elem_op);
odla_value v = CreateValue(rhs_mem, shape, id);
InterpretIfNeeded();
return v;
}
static void expand_dims(odla_value& src, odla_value& dst) {
// src shape is [1,5], dst shape is [1,4,1], we expand src shape to [1,1,5]
// src shape is [64], dst shape is [1,64,128], we expand src shape to [1,64,1]
// src shape is [64], dst shape is [1,64,64], we expand src shape to [1,1,64]
// src shape is [7,31,64], dst shape is [2,31,64,64], failed
const int src_n = src->shape.size;
const int dst_n = dst->shape.size;
odla_value_shape new_shape;
auto CompareDims = [src, dst, src_n](int loc,
odla_value_shape& new_shape) -> bool {
int src_idx = src_n - 1;
int dst_idx = loc;
for (int k = 0; k < src_n; k++) {
if (dst->shape.dims[dst_idx - k] != src->shape.dims[src_idx - k] &&
dst->shape.dims[dst_idx - k] != 1 &&
src->shape.dims[src_idx - k] != 1) {
return false;
}
new_shape.dims[dst_idx - k] = src->shape.dims[src_idx - k];
}
return true;
};
// slide from the last item in dst
for (int j = dst_n - 1; j >= 0; j--) {
if (CompareDims(j, new_shape)) {
// the src shape cannot be expanded
assert(j + 1 >= src_n);
const int sub_array_start = j + 1 - src_n;
for (int i = 0; i < sub_array_start; i++) {
new_shape.dims[i] = 1;
}
break;
} else {
new_shape.dims[j] = 1;
}
}
new_shape.size = dst_n;
src->shape = new_shape;
}
static odla_value broadcast_func(odla_value& input, odla_value_shape shape) {
bool skip_broadcast = true;
for (int i = 0; i < shape.size; i++) {
skip_broadcast &= (input->shape.dims[i] == shape.dims[i]);
}
if (skip_broadcast) return input;
std::vector<int64_t> strides_v(input->shape.size, 0);
std::function<void()> op;
auto ln = GetTotalElements(shape);
auto rn = GetTotalElements(input->shape);
if (rn != 1) { // if there is only one elemets, it's strides = 0
for (int i = shape.size - 1, s = 1; i >= 0; --i) {
if (input->shape.dims[i] != shape.dims[i]) {
assert(input->shape.dims[i] == 1);
} else {
strides_v[i] = s;
s *= input->shape.dims[i];
}
}
}
auto src_md =
dnnl::memory::desc(getDims(shape), input->mem.get_desc().data_type(),
dnnl::memory::dims(strides_v));
auto ret_md = dnnl::memory::desc(
getDims(shape), input->mem.get_desc().data_type(), getFormatTag(shape));
auto ret_mem = dnnl::memory(ret_md, g_comp->eng);
auto reorder_pd =
dnnl::reorder::primitive_desc(g_comp->eng, src_md, g_comp->eng, ret_md);
auto reorder_prim = dnnl::reorder(reorder_pd);
add_op(reorder_prim, {{DNNL_ARG_SRC, input->mem}, {DNNL_ARG_DST, ret_mem}});
return CreateValue(ret_mem, shape, nullptr);
}
std::pair<odla_value, odla_value> broadcast_op(odla_value lhs, odla_value rhs) {
auto dims_lhs = lhs->shape;
auto dims_rhs = rhs->shape;
if (dims_lhs.size != dims_rhs.size) {
auto& from = dims_lhs.size > dims_rhs.size ? rhs : lhs;
auto& to = dims_lhs.size > dims_rhs.size ? lhs : rhs;
expand_dims(from, to);
}
uint32_t repeat_lhs[10];
uint32_t repeat_rhs[10];
odla_value_shape tiled_shape;
for (int i = 0; i < lhs->shape.size; i++) {
auto curr_output_dim = lhs->shape.dims[i] >= rhs->shape.dims[i]
? lhs->shape.dims[i]
: rhs->shape.dims[i];
repeat_lhs[i] = curr_output_dim / lhs->shape.dims[i];
repeat_rhs[i] = curr_output_dim / rhs->shape.dims[i];
tiled_shape.dims[i] = curr_output_dim;
}
tiled_shape.size = lhs->shape.size;
auto new_lhs = broadcast_func(lhs, tiled_shape);
auto new_rhs = broadcast_func(rhs, tiled_shape);
lhs->shape = dims_lhs;
rhs->shape = dims_rhs;
return std::pair<odla_value, odla_value>(new_lhs, new_rhs);
}
static odla_value binary_eltwise(dnnl::algorithm algo, odla_value lhs,
odla_value rhs, const odla_value_id id) {
if (lhs->mem.get_data_handle() != rhs->mem.get_data_handle()) {
auto new_inputs = broadcast_op(lhs, rhs);
lhs = new_inputs.first;
rhs = new_inputs.second;
}
auto type = lhs->mem.get_desc().data_type();
if (type == dnnl::memory::data_type::s32) {
return binary_eltwise_s32(algo, lhs->mem, rhs->mem, lhs->shape, id);
}
const auto& dims_lhs = lhs->shape;
const auto& dims_rhs = rhs->shape;
auto lhs_md = dnnl::memory::desc(
getDims(dims_lhs), lhs->mem.get_desc().data_type(), getStrides(dims_lhs));
auto rhs_md = lhs_md;
auto ret_md = lhs_md;
auto ret_mem = dnnl::memory(ret_md, g_comp->eng);
dnnl::binary::desc bd(algo, lhs_md, rhs_md, ret_md);
dnnl::binary::primitive_desc pd(bd, g_comp->eng);
dnnl::primitive prim = dnnl::binary(pd);
add_op(prim, {{DNNL_ARG_SRC_0, lhs->mem},
{DNNL_ARG_SRC_1, rhs->mem},
{DNNL_ARG_DST, ret_mem}});
odla_value v = CreateValue(ret_mem, lhs->shape, id);
InterpretIfNeeded();
return v;
}
odla_value odla_Add(odla_value lhs, odla_value rhs, const odla_value_id id) {
return binary_eltwise(dnnl::algorithm::binary_add, lhs, rhs, id);
}
odla_value odla_Mul(odla_value lhs, odla_value rhs, const odla_value_id id) {
if (lhs == rhs) {
return unary_eltwise_op(dnnl::algorithm::eltwise_square, lhs, 1.f, 0.f, id);
}
return binary_eltwise(dnnl::algorithm::binary_mul, lhs, rhs, id);
}
odla_value odla_Sub(odla_value lhs, odla_value rhs, const odla_value_id id) {
#if (DNNL_VERSION_MINOR != 8)
auto v = unary_eltwise_op(dnnl::algorithm::eltwise_linear, rhs, -1.f, 0.f,
nullptr);
return binary_eltwise(dnnl::algorithm::binary_add, lhs, v, id);
#else
return binary_eltwise(dnnl::algorithm::binary_sub, lhs, rhs, id);
#endif
}
odla_value odla_Div(odla_value lhs, odla_value rhs, const odla_value_id id) {
return binary_eltwise(dnnl::algorithm::binary_div, lhs, rhs, id);
}
odla_value odla_Round(odla_value input, const odla_value_id id) {
return unary_eltwise_op(dnnl::algorithm::eltwise_round, input, 0.f, 0.f, id);
}
odla_value odla_Exp(odla_value input, const odla_value_id value_id) {
return unary_eltwise_op(dnnl::algorithm::eltwise_exp, input, 0.f, 0.f,
value_id);
}
odla_value odla_Sqrt(odla_value input, const odla_value_id value_id) {
auto v = unary_eltwise_op(dnnl::algorithm::eltwise_sqrt, input, 0.f, 0.f,
value_id);
return v;
}
odla_value odla_Sigmoid(odla_value input, const odla_value_id id) {
return unary_eltwise_op(dnnl::algorithm::eltwise_logistic, input, 0.f, 0.f,
id);
}
odla_value odla_LeakyRelu(odla_value input, odla_float32 alpha,
const odla_value_id id) {
return unary_eltwise_op(dnnl::algorithm::eltwise_relu, input, alpha, 0.f, id);
}
odla_value odla_Relu(odla_value input, const odla_value_id value_id) {
return unary_eltwise_op(dnnl::algorithm::eltwise_relu, input, 0.f, 0.f,
value_id);
}
odla_value odla_PRelu(odla_value input, odla_value slope,
const odla_value_id value_id) {
// current dnnl is not support prelu primitive, so we use below equation to
// get prelu():
// prelu(input, slope) = (input < 0 ? input * slope : input)
// = relu(input) - relu(-input) * slope
// = relu(input) - mul(relu(mul(input, -1)), slope)
// = relu(input) + mul(-slope,relu(mul(input,-1)))
auto relu_v = odla_Relu(input, nullptr);
auto neg_input = unary_eltwise_op(dnnl::algorithm::eltwise_linear, input,
-1.f, 0.f, nullptr);
auto neg_relu_v = odla_Relu(neg_input, nullptr);
auto neg_slope = unary_eltwise_op(dnnl::algorithm::eltwise_linear, slope,
-1.f, 0.f, nullptr);
auto neg_relu_v_mul = odla_Mul(neg_relu_v, neg_slope, nullptr);
auto v = odla_Add(neg_relu_v_mul, relu_v, value_id);
InterpretIfNeeded();
return v;
}
odla_value odla_Clamp(odla_value input, odla_float32 lo, odla_float32 hi,
const odla_value_id id) {
return unary_eltwise_op(dnnl::algorithm::eltwise_clip, input, lo, hi, id);
}
static odla_value_shape getNCHWDims(const odla_value_shape& src_dims) {
assert(src_dims.size == 4);
return {
src_dims.size,
{src_dims.dims[0], src_dims.dims[3], src_dims.dims[1], src_dims.dims[2]}};
}
static odla_value_shape getOIHWDims(const odla_value_shape& src_dims) {
assert(src_dims.size == 4);
return {
src_dims.size,
{src_dims.dims[3], src_dims.dims[2], src_dims.dims[0], src_dims.dims[1]}};
}
static odla_value_shape getGOIHWDims(const odla_value_shape& src_dims,
unsigned groups, unsigned data_in_ch,
odla_memory_layout layout) {
assert(src_dims.size == 4);
assert(layout == ODLA_OIS);
auto group_in_ch = data_in_ch / groups;
auto group_out_ch =
src_dims.dims[0] * src_dims.dims[1] / (groups * group_in_ch);
return {
src_dims.size + 1,
{groups, group_out_ch, group_in_ch, src_dims.dims[2], src_dims.dims[3]}};
}
odla_value odla_Transpose(odla_value input, odla_value_shape permutations,
odla_value_shape output_dims,
const odla_value_id id) {
const auto& input_dims = input->shape;
auto strides = getStrides(input_dims);
auto new_strides = strides;
for (int i = 0; i < permutations.size; ++i)
new_strides[i] = strides[permutations.dims[i]];
auto type = input->mem.get_desc().data_type();
dnnl::memory::desc src_md(getDims(output_dims), type, new_strides);
dnnl::memory::desc dst_md(getDims(output_dims), type,
getStrides(output_dims));
auto src_mem = dnnl::memory(src_md, g_comp->eng, nullptr);
auto dst_mem = dnnl::memory(dst_md, g_comp->eng);
auto prim = dnnl::reorder(src_mem, dst_mem);
add_op(prim, {{DNNL_ARG_FROM, input->mem}, {DNNL_ARG_TO, dst_mem}});
auto v = CreateValue(dst_mem, output_dims, id);
InterpretIfNeeded();
return v;
}
odla_value odla_Reshape(odla_value input, odla_value_shape output_dims,
const odla_value_id id) {
return CreateValue(input->mem, output_dims, id);
}
odla_value odla_Conv(odla_value input, odla_memory_layout input_layout,
odla_uint32 group, odla_value kernel,
odla_memory_layout kernel_layout,
const odla_uint32* strides, const odla_uint32* dilations,
const odla_uint32* paddings_front,
const odla_uint32* paddings_back, odla_value bias,
odla_value_shape output_dims, const odla_value_id id) {
auto input_dims = input->shape;
auto kernel_dims = kernel->shape;
auto dt = input->mem.get_desc().data_type();
auto dt_dst = (g_comp->opts.bf16_mode == BF16_ACCURACY_MODE)
? getDataType(ODLA_BFLOAT16)
: dt;
dnnl::memory::dims stride_dims{strides[0], strides[1]};
dnnl::memory::dims paddings_before{paddings_front[0], paddings_front[1]};
dnnl::memory::dims paddings_after{paddings_back[0], paddings_back[1]};
odla_value_shape orig_output_dims = output_dims;
if (input_layout == ODLA_CHANNELS_LAST) {
input_dims = getNCHWDims(input_dims);
output_dims = getNCHWDims(output_dims);
}
if (kernel_layout == ODLA_SIO) {
kernel_dims = getOIHWDims(kernel_dims);
}
if (group > 1) {
if (kernel_layout == ODLA_SIO) {
if (kernel_dims.dims[0] * group == kernel_dims.dims[1])
std::swap(kernel_dims.dims[0], kernel_dims.dims[1]);
}
kernel_dims =
getGOIHWDims(kernel_dims, group, input_dims.dims[1], ODLA_OIS);
}
auto ret_md_any = dnnl::memory::desc(getDims(output_dims), dt_dst,
dnnl::memory::format_tag::any);
auto input_md_any = dnnl::memory::desc(getDims(input_dims), dt_dst,
dnnl::memory::format_tag::any);
auto input_md_src =
dnnl::memory::desc(getDims(input_dims), dt, getFormatTag(input_layout));
auto kernel_md_any = dnnl::memory::desc(getDims(kernel_dims), dt_dst,
dnnl::memory::format_tag::any);
auto kernel_md_src = dnnl::memory::desc(getDims(kernel_dims), dt,
getFormatTag(kernel_layout, group));
auto kernel_mem =
dnnl::memory(kernel_md_src, g_comp->eng, kernel->mem.get_data_handle());
dnnl::memory::desc bias_md;
if (bias != nullptr) {
odla_value_shape scalar{.size = 1, .dims = {GetTotalElements(bias->shape)}};
bias_md = dnnl::memory::desc(getDims(scalar), dt_dst,
dnnl::memory::format_tag::a);
}
assert(dilations[0] == 1 && dilations[1] == 1);
auto conv_desc = dnnl::convolution_forward::desc(
dnnl::prop_kind::forward_inference, dnnl::algorithm::convolution_direct,
input_md_any, kernel_md_any, bias_md, ret_md_any, stride_dims,
paddings_before, paddings_after);
auto pd = dnnl::convolution_forward::primitive_desc(conv_desc, g_comp->eng);
auto ret_md_exp =
dnnl::memory::desc(getDims(output_dims), dt, getFormatTag(input_layout));
bool need_reorder_src = pd.src_desc() != input_md_src;
bool need_reorder_kernel = pd.weights_desc() != kernel_mem.get_desc();
bool need_reorder_dst = pd.dst_desc() != ret_md_exp;
dnnl::memory orig_mem;