-
Notifications
You must be signed in to change notification settings - Fork 1
/
mint.h
3427 lines (2964 loc) · 127 KB
/
mint.h
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
/*
M I N T
A minimalist tensor library
Mint is a single-file header only library for tensor manipulation. It also
enables importing and executing *some* of neural net models. Mint aims to be
dependency-free and easily distributed, but it is possible to integrate with
the other libraries such as BLAS if needed.
Some of notable features:
- NumPy style broadcasting
- BLAS backend (optional)
- OpenMP acceleration (optional)
****************************************************************************
TABLE OF CONTENTS MT001
****************************************************************************
[MT001] Table of contents
[MT002] Usage
[MT003] Concepts
[MT004] Compile-time options
[MT005] Mint APIs
[MT006] Mint implementations
Tips: you can search faster within this file using the code MTXXX
****************************************************************************
USAGE MT002
****************************************************************************
Do this:
> #define MT_IMPLEMENTATION
before you include this file in *one* C or C++ file. For example:
> #include ...
> #include ...
> #include ...
>
> #define MT_IMPLEMENTATION
> #include "mint.h"
****************************************************************************
CONCEPTS MT003
****************************************************************************
Tensor (mt_tensor)
--------------------------------------------------------------------------
A multi-dimensional matrix representation. The data type by default is set
to C float, defined as `mt_float`. This can be overridden easily like this:
> #define mt_float YOUR_FLOAT
> #include "mint.h"
>
> // ...rest of your code
Model (mt_model)
--------------------------------------------------------------------------
Mint provides a functionality to load a pretrained model. Currently it can
only load models converted from ONNX format. The script to convert ONNX into
*.mt (Mint model format) is provided in `scripts` directory. The mint format
is specified as follows:
┌──────────────────────────────────────────────────────────┐
│ MODEL HEADER │
│┌────────────────────────────────────────────────────────┐│
││ 4 bytes: Layer Count ││
│├────────────────────────────────────────────────────────┤│
││ 4 bytes: Tensor Count ││
│└────────────────────────────────────────────────────────┘│
├──────────────────────────────────────────────────────────┤
│ MODEL DATA │
│┌────────────────────────────────────────────────────────┐│
││ LAYER HEADER ││
││┌──────────────────────────────────────────────────────┐││
│││ 4 bytes: layer kind │││
│││ 4 bytes: layer ID │││
│││ 4 bytes: prev_count, count of dependencies │││
│││ 4 * prev_count bytes: list of dependency IDs │││
│││ 4 bytes: next_count, count of dependents │││
│││ 4 * next_count bytes: list of dependent ID │││
│││ 4 bytes: input_count, count of input tensors │││
│││ 4 * input_count bytes: list of input tensor IDs │││
│││ 4 bytes: output_count, count of output tensors │││
│││ 4 * output_count bytes: list of output tensor IDs │││
││└──────────────────────────────────────────────────────┘││
│├────────────────────────────────────────────────────────┤│
││ LAYER DATA ││
││ Content depends on layer kind ││
│└────────────────────────────────────────────────────────┘│
│ . . . │
│┌────────────────────────────────────────────────────────┐│
││ LAYER HEADER ││
│├────────────────────────────────────────────────────────┤│
││ LAYER DATA ││
│└────────────────────────────────────────────────────────┘│
├──────────────────────────────────────────────────────────┤
│┌─────────────┐┌─────────────┐ ┌─────────────┐│
││ TENSOR DATA ││ TENSOR DATA │ . . . │ TENSOR DATA ││
│└─────────────┘└─────────────┘ └─────────────┘│
└──────────────────────────────────────────────────────────┘
****************************************************************************
COMPILE-TIME OPTIONS MT004
****************************************************************************
All compile-time options should be placed before including `mint.h`.
NDEBUG
--------------------------------------------------------------------------
When enabled, assertion and debug logging will be disabled.
MT_USE_STB_IMAGE
-------------------------------------------------------------------------
Whether or not to use image loading functionality supported by stb_image.h
for example, mt_tensor_load_image. If you enable this, then you must include
`stb_image.h` BEFORE incuding `mint.h`. For example:
> #define STB_IMAGE_IMPLEMENTATION
> #include "stb_image.h"
>
> #define MT_USE_STB_IMAGE
> #include "mint.h"
>
> // ...rest of your code
>
MT_USE_BLAS
--------------------------------------------------------------------------
Whether or not to use BLAS. This will accelerate some operations involving
matrix multiplication. You must also include `cblas.h` yourself right before
including `mint.h`. You need to link your program with BLAS by adding -lblas
compiler flag.
MT_USE_IM2COL_CONV
--------------------------------------------------------------------------
When enabled, mint will use im2col operation to convert the input data and
the convolution kernels into matrices. Then, instead of performing a regular
convolution, mint will treat convolution operation to be performed as a more
efficient matrix multiplication. This way, we effectively unroll convolution
operation.
More on this: https://arxiv.org/pdf/1410.0759
Notes:
1. It is recommended to enable this flag along with MT_USE_BLAS flag for the
optimal result.
2. Convolution by matrix multiplication with im2col requires more memory.
*/
#ifndef _MINT_H_
#define _MINT_H_
#ifdef __cplusplus
extern "C" {
#endif
/***************************************************************************
MINT APIs MT005
**************************************************************************/
/*
* Tensor operation API
*/
// The tensor values data type
#ifndef mt_float
#define mt_float float
#define mt_float_max 3.402823466e+38F
#endif
#ifndef MTDEF
#define MTDEF static inline
#endif
typedef struct mt_tensor mt_tensor;
typedef enum {
MT_PAD_REFLECT,
MT_PAD_CONSTANT,
MT_PAD_EDGE,
} mt_pad_mode;
// float-valued reduce function
typedef mt_float (*mt_reduce_func)(mt_float a, mt_float b);
// Adaptive version of average pooling. This typically allows the use of any
// arbitrary input size to obtain consistent size for the intermediate layer
// representation.
MTDEF mt_tensor *mt_adaptive_avg_pool_2d(mt_tensor *x, int out_h, int out_w);
// Element-wise addition
MTDEF mt_tensor *mt_add(mt_tensor *a, mt_tensor *b);
// Affine transformation, i.e., matmul(x, w) + b. Tensor b needs to have one
// dimension with length of matmul result's trailing dimension. The addition
// operation will broadcast b along matmul(x, w)'s first dimension.
MTDEF mt_tensor *mt_affine(mt_tensor *x, mt_tensor *w, mt_tensor *b);
// Average pooling
MTDEF mt_tensor *mt_avg_pool_2d(mt_tensor *x, int kernel_size, int stride,
int *pad);
// Concatenate several tensors at a certain axis
MTDEF mt_tensor *mt_concat(mt_tensor **inputs, int num_inputs, int axis);
// Convolution 2d
MTDEF mt_tensor *mt_convolve_2d(mt_tensor *x, mt_tensor *w, mt_tensor *b,
int stride, int *pads, int *dilations,
int group);
// Element-wise division
MTDEF mt_tensor *mt_div(mt_tensor *a, mt_tensor *b);
// Element-wise exponentiation
MTDEF mt_tensor *mt_exp(mt_tensor *a);
// Pooling by taking average of each channel, reducing each channel's matrix
// into a single value, i.e., the mean.
MTDEF mt_tensor *mt_global_avg_pool_2d(mt_tensor *x);
// Resize image to a certain target using bilinear interpolation
MTDEF mt_tensor *mt_image_resize(mt_tensor *t, int target_height,
int target_width);
// Standardize tensor RGB image. Both mu and std must have 3 elements.
MTDEF void mt_image_standardize(mt_tensor *t, mt_float *mu, mt_float *std);
// Perform instance normalization
MTDEF mt_tensor *mt_instance_normalize(mt_tensor *t, mt_tensor *scale,
mt_tensor *b, mt_float epsilon);
// Leaky relu
MTDEF void mt_leaky_relu_inplace(mt_tensor *t, mt_float alpha);
// Local response norm, as introduced in AlexNet paper
MTDEF mt_tensor *mt_local_response_norm(mt_tensor *t, int size, mt_float alpha,
mt_float beta, mt_float k);
// Matrix multiplication. Both a and b must have 2 dimensions.
MTDEF mt_tensor *mt_matmul(mt_tensor *a, mt_tensor *b);
// Max-pooling
MTDEF mt_tensor *mt_maxpool_2d(mt_tensor *x, int kernel_size, int stride,
int *pads);
// Find maximum values along dimensions
MTDEF mt_tensor *mt_max(mt_tensor *input, int axis, int keep_dims);
// Find mean values along dimensions
MTDEF mt_tensor *mt_mean(mt_tensor *input, int axis, int keep_dims);
// Find minimum values along dimensions
MTDEF mt_tensor *mt_min(mt_tensor *input, int axis, int keep_dims);
// Element-wise multiplication
MTDEF mt_tensor *mt_mul(mt_tensor *a, mt_tensor *b);
// Generic reduce function
MTDEF mt_tensor *mt_reduce(mt_tensor *t, int axis, mt_reduce_func reduce_op,
mt_float init_val, int keep_dims);
// Relu activation function, in-place version.
MTDEF void mt_relu_inplace(mt_tensor *t);
// Sigmoid activation function, in-place version.
MTDEF void mt_sigmoid_inplace(mt_tensor *t);
// softmax
MTDEF mt_tensor *mt_softmax(mt_tensor *input, int axis);
// Element-wise subtraction
MTDEF mt_tensor *mt_sub(mt_tensor *a, mt_tensor *b);
// Find sum values along dimensions
MTDEF mt_tensor *mt_sum(mt_tensor *input, int axis, int keep_dims);
/*
* Tensor memory management API
*/
// Allocate tensor without value initialization
MTDEF mt_tensor *mt_tensor_alloc(int *shape, int ndim);
// Allocate tensor and fill the data with a consant value
MTDEF mt_tensor *mt_tensor_alloc_fill(int *shape, int ndim, mt_float value);
// Allocate tensor and fill the data with a specified array of values
MTDEF mt_tensor *mt_tensor_alloc_values(int *shape, int ndim, mt_float *values);
// Allocate tensor and fill the data with random values, ranging from 0 to 1
MTDEF mt_tensor *mt_tensor_alloc_random(int *shape, int ndim);
// Clone a tensor. The new tensor will manage its own memory region for its
// data.
MTDEF mt_tensor *mt_tensor_clone(mt_tensor *t);
// Get the number of elements of a tensor
MTDEF int mt_tensor_count_element(mt_tensor *t);
// Helper function to print tensor summary
MTDEF void mt_tensor_debug_info(mt_tensor *t);
// Free tensor
MTDEF void mt_tensor_free(mt_tensor *t);
// Load image as a tensor with shape of CxHxW. C is the number of channel, H
// is the image height, and W is the image widthmt_tensor
// *mt_tensor_load_image(char *filename); Pad along tensor's dimension
MTDEF mt_tensor *mt_tensor_pad(mt_tensor *t, int *pads, mt_pad_mode mode,
mt_float constant_val);
// Swap tensor's dimensions
MTDEF mt_tensor *mt_tensor_permute_dims(mt_tensor *t, int *dims);
// Print tensor content representation
MTDEF void mt_tensor_print(mt_tensor *t);
// Reshape tensor in-place. The old and new shape should be compatible.
MTDEF void mt_tensor_reshape_inplace(mt_tensor *t, int *new_shape,
int new_ndim);
// Tensor slice
MTDEF mt_tensor *mt_tensor_slice(mt_tensor *t, int *starts, int *ends,
int *axes, int *steps, int num_axes);
// Split tensor into `n_split` parts
MTDEF void mt_tensor_split(mt_tensor *t, int axis, int *splits, int n_split,
mt_tensor **out);
// Unsqueeze at given axis
MTDEF void mt_tensor_unsqueeze_inplace(mt_tensor *t, int axis);
/*
* Model API
*/
typedef struct mt_model mt_model;
#define LAYER_TYPES(T) \
T(MT_LAYER_UNKNOWN) \
T(MT_LAYER_ADD) \
T(MT_LAYER_AVG_POOL_2D) \
T(MT_LAYER_CAST) \
T(MT_LAYER_CONCAT) \
T(MT_LAYER_CONSTANT) \
T(MT_LAYER_CONV_2D) \
T(MT_LAYER_DENSE) \
T(MT_LAYER_DIV) \
T(MT_LAYER_DROPOUT) \
T(MT_LAYER_EXP) \
T(MT_LAYER_FLATTEN) \
T(MT_LAYER_GLOBAL_AVG_POOL) \
T(MT_LAYER_INSTANCE_NORMALIZATION) \
T(MT_LAYER_LEAKY_RELU) \
T(MT_LAYER_LOCAL_RESPONSE_NORM) \
T(MT_LAYER_LOG) \
T(MT_LAYER_MAX_POOL_2D) \
T(MT_LAYER_MUL) \
T(MT_LAYER_PAD) \
T(MT_LAYER_POW) \
T(MT_LAYER_RELU) \
T(MT_LAYER_RESHAPE) \
T(MT_LAYER_RESIZE) \
T(MT_LAYER_SIGMOID) \
T(MT_LAYER_SLICE) \
T(MT_LAYER_SOFTMAX) \
T(MT_LAYER_SPLIT) \
T(MT_LAYER_SUB) \
T(MT_LAYER_TANH) \
T(MT_LAYER_TRANSPOSE)
typedef enum {
#define T(name) name,
LAYER_TYPES(T)
#undef T
} mt_layer_kind;
static const char *mt_layer_kind_strings[] = {
#define T(name) #name,
LAYER_TYPES(T)
#undef T
};
MTDEF mt_model *mt_model_load(const char *filename);
MTDEF void mt_model_free(mt_model *model);
MTDEF mt_tensor *mt_model_get_output(mt_model *model, const char *name);
MTDEF void mt_model_run(mt_model *model,
void (*callbak)(int layer_index, int layer_count,
void *data),
void *data);
MTDEF void mt_model_set_input(mt_model *model, const char *name, mt_tensor *t);
typedef struct mt_layer mt_layer;
MTDEF const char *mt_layer_kind_to_string(mt_layer_kind kind);
MTDEF void mt_layer_debug_info(mt_layer *l);
#ifdef __cplusplus
}
#endif
/***************************************************************************
MINT IMPLEMENTATION MT006
**************************************************************************/
#ifdef MT_IMPLEMENTATION
#include <limits.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifdef MT_USE_OPEN_MP
#include <omp.h>
#endif
#ifdef MT_USE_NEON
#include <arm_neon.h>
#endif
#ifdef MT_USE_BLAS
#include <cblas.h>
#endif
#define MAX_LAYER_COUNT 1000
#define MAX_LAYER_INPUT_COUNT 10
#define MAX_LAYER_OUTPUT_COUNT 10
#define MAX_LAYER_PREV_COUNT 5
#define MAX_LAYER_NEXT_COUNT 5
#define MAX_MODEL_INITIALIZER_COUNT 1500
#define MAX_TENSOR_NDIM 5
#define MAX_TENSOR_SPLITS 5
#define MAX_INPUT_OUTPUT_COUNT 5
#define MAX_INPUT_OUTPUT_NAME_LEN 50
#define MATMUL_BLOCK_SIZE 64
#define UNROLL_FACTOR 16
#ifndef MT_MALLOC
#define MT_MALLOC(sz) malloc(sz)
#define MT_FREE(sz) free(sz)
#endif
typedef struct mt_tensor {
mt_float *data;
int ndim;
int shape[MAX_TENSOR_NDIM];
} mt_tensor;
typedef struct mt_layer {
int id;
mt_layer_kind kind;
/* This member holds data of different layer types. Some layers do not
* have any data/attribute to store, such as ReLU, simple binary
* operations, etc. In that case, they are not listed here. */
union {
// MT_LAYER_AVG_POOL_2D
struct {
int size;
int stride;
int pads[4];
int group;
} avg_pool_2d;
// MT_LAYER_CONCAT
struct {
int axis;
} concat;
// MT_LAYER_CONSTANT
struct {
int tensor_idx;
} constant;
// MT_LAYER_CONV_2D
struct {
int auto_pad;
int w_id;
int b_id;
int stride;
int pads[4];
int dilations[2];
int group;
} conv_2d;
// MT_LAYER_DENSE
struct {
int w_id;
int b_id;
} dense;
// MT_LAYER_FLATTEN
struct {
int axis;
} flatten;
// MT_LAYER_INSTANCE_NORMALIZATION
struct {
mt_float eps;
} instance_normalization;
// MT_LAYER_LEAKY_RELU
struct {
mt_float alpha;
} leaky_relu;
// MT_LAYER_LOCAL_RESPONSE_NORM
struct {
int size;
mt_float alpha;
mt_float beta;
mt_float bias;
} local_response_norm;
// MT_LAYER_MAX_POOL_2D
struct {
int auto_pad;
int size;
int stride;
int pads[4];
} max_pool_2d;
// MT_LAYER_RESIZE
struct {
int mode;
} resize;
// MT_LAYER_SOFTMAX
struct {
int axis;
} softmax;
// MT_LAYER_SPLIT
struct {
int axis;
int n_split;
int splits[MAX_TENSOR_SPLITS];
} split;
// MT_LAYER_TRANSPOSE
struct {
int perm[MAX_TENSOR_NDIM];
} transpose;
} data;
int prev_count;
int prev[MAX_LAYER_PREV_COUNT];
int next_count;
int next[MAX_LAYER_NEXT_COUNT];
int input_count;
int inputs[MAX_LAYER_INPUT_COUNT];
int output_count;
int outputs[MAX_LAYER_OUTPUT_COUNT];
} mt_layer;
typedef struct mt_model {
int layer_count;
int tensor_count;
mt_layer *layers[MAX_LAYER_COUNT];
mt_tensor *tensors[MAX_MODEL_INITIALIZER_COUNT];
int input_count;
struct {
int id;
char name[MAX_INPUT_OUTPUT_NAME_LEN];
} inputs[MAX_INPUT_OUTPUT_COUNT];
int output_count;
struct {
int id;
char name[MAX_INPUT_OUTPUT_COUNT];
} outputs[10];
} mt_model;
#define MT_ARR_INT(...) ((int[]){__VA_ARGS__})
#define MT_ARR_FLOAT(...) ((mt_float[]){__VA_ARGS__})
#ifdef NDEBUG
#define MT_ASSERT_F(condition, format, ...) ((void)0)
#define DEBUG_LOG_F(format, ...) ((void)0)
#define DEBUG_LOG(msg) ((void)0)
#define WARN_LOG_F(format, ...) ((void)0)
#define WARN_LOG(msg) ((void)0)
#else
#define MT_ASSERT_F(condition, format, ...) \
do { \
if (!(condition)) { \
fprintf(stderr, "\x1b[31m"); \
fprintf(stderr, "Assertion failed [%s:%d]: %s\n", __FILE__, \
__LINE__, #condition); \
fprintf(stderr, format, __VA_ARGS__); \
fprintf(stderr, "\n"); \
fprintf(stderr, "\x1b[0m"); \
abort(); \
} \
} while (0)
#define DEBUG_LOG_F(format, ...) \
do { \
fprintf(stderr, "DEBUG [%s:%d]: ", __FILE__, __LINE__); \
fprintf(stderr, format, __VA_ARGS__); \
fprintf(stderr, "\n"); \
} while (0)
#define DEBUG_LOG(msg) \
do { \
fprintf(stderr, "DEBUG [%s:%d]: ", __FILE__, __LINE__); \
fprintf(stderr, msg); \
fprintf(stderr, "\n"); \
} while (0)
#define WARN_LOG_F(format, ...) \
do { \
fprintf(stderr, "\x1b[33m"); \
fprintf(stderr, "WARNING [%s:%d]: ", __FILE__, __LINE__); \
fprintf(stderr, format, __VA_ARGS__); \
fprintf(stderr, "\x1b[0m\n"); \
} while (0)
#define WARN_LOG(msg) \
do { \
fprintf(stderr, "\x1b[33m"); \
fprintf(stderr, "WARNING [%s:%d]: ", __FILE__, __LINE__); \
fprintf(stderr, msg); \
fprintf(stderr, "\x1b[0m\n"); \
} while (0)
#endif
#ifdef NDEBUG
#define MT_ASSERT(condition, msg) ((void)0)
#else
#define MT_ASSERT(condition, msg) \
do { \
if (!(condition)) { \
fprintf(stderr, "\x1b[31m"); \
fprintf(stderr, "Assertion failed [%s:%d]: %s\n", __FILE__, \
__LINE__, #condition); \
fprintf(stderr, msg); \
fprintf(stderr, "\n"); \
fprintf(stderr, "\x1b[0m"); \
abort(); \
} \
} while (0)
#endif
#define ERROR(msg) \
do { \
fprintf(stderr, \
"\x1b[31m" \
"[ERROR] %s\n" \
"\x1b[0m", \
msg); \
exit(1); \
} while (0)
#define ERROR_F(fmt, ...) \
do { \
fprintf(stderr, \
"\x1b[31m" \
"[ERROR] " fmt "\n" \
"\x1b[0m", \
__VA_ARGS__); \
exit(1); \
} while (0)
mt_tensor *mt_tensor_clone(mt_tensor *t) {
return mt_tensor_alloc_values(t->shape, t->ndim, t->data);
}
int mt_tensor_count_element(mt_tensor *t) {
int count = 1;
for (int i = 0; i < t->ndim; i++) {
count *= t->shape[i];
}
return count;
}
// Some helper functions
static int mt__product(const int *arr, int n) {
int result = 1;
for (int i = 0; i < n; i++) {
result *= arr[i];
}
return result;
}
mt_tensor *mt_adaptive_avg_pool_2d(mt_tensor *x, int out_h, int out_w) {
MT_ASSERT_F(x->ndim == 4,
"input tensor must have 4 dimensions (an image), found %d",
x->ndim);
int channels = x->shape[0];
int in_h = x->shape[1];
int in_w = x->shape[2];
float stride_h = (float)in_h / out_h;
float stride_w = (float)in_w / out_w;
// Allocate output tensor
mt_tensor *output = mt_tensor_alloc(MT_ARR_INT(channels, out_h, out_w), 3);
for (int c = 0; c < channels; c++) {
for (int oh = 0; oh < out_h; oh++) {
for (int ow = 0; ow < out_w; ow++) {
int h_start = (int)(oh * stride_h);
int w_start = (int)(ow * stride_w);
int h_end = (int)((oh + 1) * stride_h);
int w_end = (int)((ow + 1) * stride_w);
mt_float sum = 0.0;
int count = 0;
for (int ih = h_start; ih < h_end; ih++) {
for (int iw = w_start; iw < w_end; iw++) {
sum += x->data[c * (in_h * in_w) + ih * in_w + iw];
count++;
}
}
int didx = c * (out_h * out_w) + oh * out_w + ow;
output->data[didx] = sum / count;
}
}
}
return output;
}
// Helper function to calculate the broadcasted shape
MTDEF void mt__calc_broadcast_shape(int *shape1, int ndim1, int *shape2,
int ndim2, int *result_shape,
int *result_ndim) {
*result_ndim = (ndim1 > ndim2) ? ndim1 : ndim2;
for (int i = 0; i < *result_ndim; i++) {
int dim1 =
(i < *result_ndim - ndim1) ? 1 : shape1[i - (*result_ndim - ndim1)];
int dim2 =
(i < *result_ndim - ndim2) ? 1 : shape2[i - (*result_ndim - ndim2)];
if (dim1 == dim2) {
result_shape[i] = dim1;
} else if (dim1 == 1 || dim2 == 1) {
result_shape[i] = (dim1 > dim2) ? dim1 : dim2;
} else {
fprintf(stderr, "Shapes are not compatible for broadcasting\n");
exit(1);
}
}
}
static void mt__calc_strides(int *shape, int ndim, int *strides) {
strides[ndim - 1] = 1;
for (int i = ndim - 2; i >= 0; i--) {
strides[i] = strides[i + 1] * shape[i + 1];
}
}
// Optimized 1D broadcasting
static void mt__binop_1d(mt_float *a, int a_size, mt_float *b, int b_size,
mt_float *result, int result_size,
mt_float f(mt_float, mt_float)) {
if (a_size == result_size && b_size == 1) {
for (int i = 0; i < result_size; i++) {
result[i] = f(a[i], b[0]);
}
} else if (b_size == result_size && a_size == 1) {
for (int i = 0; i < result_size; i++) {
result[i] = f(a[0], b[i]);
}
} else {
for (int i = 0; i < result_size; i++) {
result[i] = f(a[i % a_size], b[i % b_size]);
}
}
}
// Optimized 2D broadcasting
static void mt__binop_2d(mt_float *a, int *a_shape, mt_float *b, int *b_shape,
mt_float *result, int *result_shape,
mt_float f(mt_float, mt_float)) {
int a_rows = a_shape[0], a_cols = a_shape[1];
int b_rows = b_shape[0], b_cols = b_shape[1];
int result_rows = result_shape[0], result_cols = result_shape[1];
for (int i = 0; i < result_rows; i++) {
for (int j = 0; j < result_cols; j++) {
int a_i = i % a_rows, a_j = j % a_cols;
int b_i = i % b_rows, b_j = j % b_cols;
result[i * result_cols + j] =
f(a[a_i * a_cols + a_j], b[b_i * b_cols + b_j]);
}
}
}
// Optimized 3D broadcasting
static void mt__binop_3d(mt_float *a, int *a_shape, mt_float *b, int *b_shape,
mt_float *result, int *result_shape,
mt_float f(mt_float, mt_float)) {
int a_dim0 = a_shape[0], a_dim1 = a_shape[1], a_dim2 = a_shape[2];
int b_dim0 = b_shape[0], b_dim1 = b_shape[1], b_dim2 = b_shape[2];
int result_dim0 = result_shape[0], result_dim1 = result_shape[1],
result_dim2 = result_shape[2];
for (int i = 0; i < result_dim0; i++) {
for (int j = 0; j < result_dim1; j++) {
for (int k = 0; k < result_dim2; k++) {
int a_i = i % a_dim0, a_j = j % a_dim1, a_k = k % a_dim2;
int b_i = i % b_dim0, b_j = j % b_dim1, b_k = k % b_dim2;
result[(i * result_dim1 + j) * result_dim2 + k] =
f(a[(a_i * a_dim1 + a_j) * a_dim2 + a_k],
b[(b_i * b_dim1 + b_j) * b_dim2 + b_k]);
}
}
}
}
// General binary operator.
// NOTE(Aria): This is meant to be used internally.
MTDEF mt_tensor *mt__binop(mt_tensor *a, mt_tensor *b,
mt_float f(mt_float, mt_float)) {
/*
* We first check if we have ideal condition, i.e., both tensors have
* identical shape
*/
int same_shape = 1;
int ndim = a->ndim > b->ndim ? a->ndim : b->ndim;
for (int i = 0; i < ndim; ++i) {
if (a->shape[i] != b->shape[i]) {
same_shape = 0;
break;
}
}
if ((a->ndim == b->ndim) && same_shape) {
mt_tensor *result = mt_tensor_alloc(a->shape, a->ndim);
int numel = mt_tensor_count_element(a);
#pragma omp parallel for
for (int i = 0; i < numel; ++i) {
result->data[i] = f(a->data[i], b->data[i]);
}
/* try to return early */
return result;
}
/* check if tensor-scalar specialization is needed */
int b_numel = mt_tensor_count_element(b);
if (b_numel == 1) {
mt_tensor *result = mt_tensor_alloc(a->shape, a->ndim);
int a_numel = mt_tensor_count_element(a);
#pragma omp parallel for
for (int i = 0; i < a_numel; ++i) {
result->data[i] = f(a->data[i], b->data[0]);
}
/* try to return early */
return result;
}
/*
* Otherwise, try broadcasting
*/
int result_shape[MAX_TENSOR_NDIM];
int result_ndim;
mt__calc_broadcast_shape(a->shape, a->ndim, b->shape, b->ndim, result_shape,
&result_ndim);
mt_tensor *result = mt_tensor_alloc(result_shape, result_ndim);
if (result_ndim == 1) {
mt__binop_1d(a->data, a->shape[0], b->data, b->shape[0], result->data,
result_shape[0], f);
} else if (result_ndim == 2) {
mt__binop_2d(a->data, a->shape, b->data, b->shape, result->data,
result_shape, f);
} else if (result_ndim == 3) {
mt__binop_3d(a->data, a->shape, b->data, b->shape, result->data,
result_shape, f);
} else {
int a_strides[MAX_TENSOR_NDIM], b_strides[MAX_TENSOR_NDIM],
result_strides[MAX_TENSOR_NDIM];
mt__calc_strides(a->shape, a->ndim, a_strides);
mt__calc_strides(b->shape, b->ndim, b_strides);
mt__calc_strides(result_shape, result_ndim, result_strides);
int a_broadcast_shape[MAX_TENSOR_NDIM],
b_broadcast_shape[MAX_TENSOR_NDIM];
for (int i = 0; i < result_ndim; i++) {
a_broadcast_shape[i] = (i < result_ndim - a->ndim)
? 1
: a->shape[i - (result_ndim - a->ndim)];
b_broadcast_shape[i] = (i < result_ndim - b->ndim)
? 1
: b->shape[i - (result_ndim - b->ndim)];
}
int numel = mt_tensor_count_element(result);
#pragma omp parallel for
// TODO: optimize for special ndims, identic shape, and
// tensor-scalar ops
for (int i = 0; i < numel; i++) {
int indices[MAX_TENSOR_NDIM];
int temp = i;
for (int j = 0; j < result_ndim; j++) {
indices[j] = temp / result_strides[j];
temp %= result_strides[j];
}
int a_index = 0, b_index = 0;
for (int j = 0; j < result_ndim; j++) {
a_index += (indices[j] % a_broadcast_shape[j]) *
(j < result_ndim - a->ndim
? 0
: a_strides[j - (result_ndim - a->ndim)]);
b_index += (indices[j] % b_broadcast_shape[j]) *
(j < result_ndim - b->ndim
? 0
: b_strides[j - (result_ndim - b->ndim)]);
}
result->data[i] = f(a->data[a_index], b->data[b_index]);
}
}
return result;
}
MTDEF mt_tensor *mt__unop(mt_tensor *t, mt_float f(mt_float)) {
mt_tensor *output = mt_tensor_alloc(t->shape, t->ndim);
for (int i = 0; i < mt_tensor_count_element(t); ++i) {
output->data[i] = f(t->data[i]);
}
return output;
}
static mt_float mt__s_add(mt_float a, mt_float b) { return a + b; }
mt_tensor *mt_add(mt_tensor *a, mt_tensor *b) {
return mt__binop(a, b, mt__s_add);
}
mt_tensor *mt_affine(mt_tensor *x, mt_tensor *w, mt_tensor *b) {
MT_ASSERT_F(w->shape[1] == b->shape[0],
"Width of `w` (%d) must match length of `b` (%d)", w->shape[1],
b->shape[0]);
mt_tensor *res = mt_matmul(x, w);
// add bias
int batch_size = res->shape[0];
int output_size = res->shape[1];
#pragma omp parallel for collapse(2)
for (int i = 0; i < batch_size; i++) {
for (int j = 0; j < output_size; j++) {
res->data[i * output_size + j] += b->data[j];
}
}
return res;
}
mt_tensor *mt_avg_pool_2d(mt_tensor *x, int kernel_size, int stride,
int *pads) {
MT_ASSERT(x->ndim == 4, "Input tensor must be 4-dimensional (NCHW format)");
int N = x->shape[0]; // Batch size
int C = x->shape[1]; // Number of channels
int H_in = x->shape[2];
int W_in = x->shape[3];
// Calculate output dimensions with padding
int pad_h_begin = pads[0];
int pad_w_begin = pads[1];
int pad_h_end = pads[2];
int pad_w_end = pads[3];
// Calculate output dimensions with padding
int H_out = (H_in + pad_h_begin + pad_h_end - kernel_size) / stride + 1;
int W_out = (W_in + pad_w_begin + pad_w_end - kernel_size) / stride + 1;
// Allocate output tensor
mt_tensor *output = mt_tensor_alloc(MT_ARR_INT(N, C, H_out, W_out), 4);
for (int n = 0; n < N; n++) {
for (int c = 0; c < C; c++) {
for (int h_out = 0; h_out < H_out; h_out++) {
for (int w_out = 0; w_out < W_out; w_out++) {
mt_float sum = 0.0f;
int count = 0;
for (int kh = 0; kh < kernel_size; kh++) {
for (int kw = 0; kw < kernel_size; kw++) {
int h_in = h_out * stride + kh - pad_h_begin;
int w_in = w_out * stride + kw - pad_w_begin;
if (h_in >= 0 && h_in < H_in && w_in >= 0 &&
w_in < W_in) {
sum +=
x->data[((n * C + c) * H_in + h_in) * W_in +
w_in];
count++;
}
}
}
// Calculate average and set output value
mt_float avg = (count > 0) ? sum / count : 0.0f;
output
->data[((n * C + c) * H_out + h_out) * W_out + w_out] =
avg;
}
}
}
}
return output;
}
mt_tensor *mt_concat(mt_tensor **inputs, int num_inputs, int axis) {
MT_ASSERT(num_inputs > 0, "provide at least one tensor to concat");
MT_ASSERT_F(axis >= -inputs[0]->ndim && axis < inputs[0]->ndim,
"axis must be between %d and %d (inclusive)", -inputs[0]->ndim,
inputs[0]->ndim);
// Normalize negative axis
if (axis < 0) {
axis += inputs[0]->ndim;