-
Notifications
You must be signed in to change notification settings - Fork 0
/
ctorch.c
2226 lines (1896 loc) · 68.6 KB
/
ctorch.c
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
#include <math.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <stdbool.h>
/////////////////////////////////////////////////////////////////////
// Structure to hold an n-dimensional tensor with index mapping
typedef struct Tensor {
int *shape; // Array to hold the size of each dimension
int dimensions; // Number of dimensions
double *data; // Shared data array
int total_size; // Total number of elements in the tensor
int *strides; // Array to hold the stride of each dimension
int *org_strides; // Array to hold the stride of each dimension regardless of whether it is a shared transposed tensor or not
} Tensor;
// Function to calculate the total size of the tensor
int calculate_total_size(
int *shape,
int dimensions
) {
int total_size = 1;
for (int i = 0; i < dimensions; i++) {
total_size *= shape[i];
}
return total_size;
}
// Function to calculate strides for a tensor based on its shape
void calculate_strides(
int *shape,
int dimensions,
int *out_strides
) {
out_strides[dimensions - 1] = 1;
for (int i = dimensions - 2; i >= 0; i--) {
out_strides[i] = out_strides[i + 1] * shape[i + 1];
}
}
// Function to free the tensor's memory
void dispose_tensor(
Tensor *tensor,
bool free_data
) {
if (tensor == NULL) return;
free(tensor->shape); tensor->shape = NULL;
free(tensor->strides); tensor->strides = NULL;
free(tensor->org_strides); tensor->org_strides = NULL;
if (free_data) { free(tensor->data); tensor->data = NULL; }
free(tensor);
}
// Function to initialize a tensor with a given shape
void __create_tensor(
int *shape,
int dimensions,
bool allocate_data,
bool calc_strides,
Tensor **out_tensor
) {
int total_size = calculate_total_size(shape, dimensions);
// Allocate memory and initialization
*out_tensor = (Tensor *)malloc(sizeof(Tensor));
(*out_tensor)->shape = (int *)malloc(dimensions * sizeof(int));
(*out_tensor)->strides = (int *)malloc(dimensions * sizeof(int));
(*out_tensor)->org_strides = (int *)malloc(dimensions * sizeof(int));
(*out_tensor)->data = (allocate_data) ? (double *)malloc(total_size * sizeof(double)) : NULL;
(*out_tensor)->dimensions = dimensions;
(*out_tensor)->total_size = total_size;
memcpy((*out_tensor)->shape, shape, dimensions * sizeof(int));
if (calc_strides) {
calculate_strides(shape, dimensions, (*out_tensor)->strides);
calculate_strides(shape, dimensions, (*out_tensor)->org_strides);
}
}
void create_tensor(
int *shape,
int dimensions,
Tensor **out_tensor
) {
__create_tensor(shape, dimensions, true, true, out_tensor);
}
void create_tensor_without_data(
int *shape,
int dimensions,
Tensor **out_tensor
) {
__create_tensor(shape, dimensions, false, true, out_tensor);
}
void create_tensor_like(
Tensor *tensor,
Tensor **out_tensor
) {
__create_tensor(tensor->shape, tensor->dimensions, true, false, out_tensor);
// When creating a tensor from another one, strides must be preserved
memcpy((*out_tensor)->strides, tensor->strides, tensor->dimensions * sizeof(int));
memcpy((*out_tensor)->org_strides, tensor->org_strides, tensor->dimensions * sizeof(int));
}
void create_tensor_like_without_data(
Tensor *tensor,
Tensor **out_tensor
) {
__create_tensor(tensor->shape, tensor->dimensions, false, false, out_tensor);
// When creating a tensor from another one, strides must be preserved
memcpy((*out_tensor)->strides, tensor->strides, tensor->dimensions * sizeof(int));
memcpy((*out_tensor)->org_strides, tensor->org_strides, tensor->dimensions * sizeof(int));
}
void deep_copy_tensor(
Tensor *tensor,
Tensor **out_tensor
) {
create_tensor_like(tensor, out_tensor);
memcpy((*out_tensor)->data, tensor->data, tensor->total_size * sizeof(double));
}
void create_tensor_from_scalar(
double value,
Tensor **out_tensor
) {
int tensor_shape[] = {1, 1};
create_tensor(tensor_shape, 2, out_tensor);
(*out_tensor)->data[0] = value;
}
// Initialize all elements to default_vlaue
void init_tensor(
double default_vlaue,
Tensor *tensor
) {
for (int i = 0; i < tensor->total_size; i++) {
tensor->data[i] = default_vlaue;
}
}
// Initialize all elements randomly between -sqrt(k) and sqrt(k)
void init_tensor_rand(
double k, // Parameter for controlling the range
Tensor *tensor
) {
double range = sqrt(k); // Calculate sqrt(k) once for efficiency
// Fill each element of the tensor with a random double between -sqrt(k) and sqrt(k)
for (int i = 0; i < tensor->total_size; i++) {
// Generate a uniform random number in [-sqrt(k), sqrt(k)]
double random_value = ((double)rand() / RAND_MAX) * 2 - 1; // Uniformly in [-1, 1]
tensor->data[i] = random_value * range; // Scale to [-sqrt(k), sqrt(k)]
}
}
// Function to store tensor values in a file with specified precision
void store_tensor(
const char *filename,
Tensor *tensor,
int precision
) {
FILE *file = fopen(filename, "w");
if (file == NULL) {
printf("Error: Unable to open file %s\n", filename);
exit(1);
}
// Format string to control precision, e.g., "%.3f\n" for 3 decimal places
char format[10];
snprintf(format, sizeof(format), "%%.%df\n", precision);
// Write each element of the tensor's data to the file with the specified precision
for (int i = 0; i < tensor->total_size; i++) {
fprintf(file, format, tensor->data[i]);
}
fclose(file);
}
// Initialize all elements from a previous specified values in a file
void load_tensor(
const char *filename,
Tensor *tensor
) {
FILE *file = fopen(filename, "r");
if (file == NULL) {
printf("Error: Unable to open file %s\n", filename);
exit(1);
}
// Read each line in the file
char line[4096]; // Large enough to hold a line with 785 values (label + 784 pixels)
int idx = 0;
while (fgets(line, sizeof(line), file)) {
char *token = strtok(line, "\n"); // Tokenize the line by commas
// First token is the label
tensor->data[idx++] = atof(token);
}
fclose(file);
}
// Function to calculate the flattened index for the tensor from multi-dimensional indices
int get_flat_index(
Tensor *tensor,
int *indices
) {
int flat_index = 0;
// Iterate through each dimension
for (int i = 0; i < tensor->dimensions; i++) {
int index = indices[i];
if (index >= tensor->shape[i] || index < 0) {
fprintf(stderr, "Error: Index out of bounds for dimension %d.\n", i);
exit(EXIT_FAILURE);
}
// Use the precomputed stride to calculate the flat index
flat_index += index * tensor->strides[i];
}
return flat_index;
}
// Function to calculate the multi-dimensional indices from a flattened index
void get_multi_dimensional_index(
Tensor *tensor,
int flat_index,
int *out_multi_dim_indices
) {
// Ensure the flat index is within bounds
if (flat_index < 0 || flat_index >= tensor->total_size) {
fprintf(stderr, "Error: Flattened index out of bounds.\n");
exit(EXIT_FAILURE);
}
// Calculate the indices for each dimension using strides
for (int i = 0; i < tensor->dimensions; i++) {
// Determine the index for this dimension using the corresponding precomputed stride
out_multi_dim_indices[i] = flat_index / tensor->org_strides[i];
// Update the flat_index to the remainder for the next dimensions
flat_index %= tensor->org_strides[i];
}
}
// Function to get an element from the tensor using multi-dimensional indices
double get_element(
Tensor *tensor,
...
) {
va_list args;
int *index_in_d = (int *)malloc(tensor->dimensions * sizeof(int));
va_start(args, tensor);
for (int i = 0; i < tensor->dimensions; i++) {
int index = va_arg(args, int);
index_in_d[i] = index;
}
va_end(args);
int flat_index = get_flat_index(tensor, index_in_d);
// Free the index_in_d array
free(index_in_d);
return tensor->data[flat_index];
}
// Function to set an element in the tensor using multi-dimensional indices
void set_element(
Tensor *tensor,
double value,
...
) {
va_list args;
int *index_in_d = (int *)malloc(tensor->dimensions * sizeof(int));
va_start(args, value);
for (int i = 0; i < tensor->dimensions; i++) {
int index = va_arg(args, int);
index_in_d[i] = index;
}
va_end(args);
int flat_index = get_flat_index(tensor, index_in_d);
tensor->data[flat_index] = value;
// Free the index_in_d array
free(index_in_d);
}
// Function to compare two tensors for equality
bool equal(
Tensor *a,
Tensor *b
) {
// Check if the number of dimensions is the same
if (a->dimensions != b->dimensions) {
return false;
}
// Check if the shape of each dimension is the same
for (int i = 0; i < a->dimensions; i++) {
if (a->shape[i] != b->shape[i]) {
return false;
}
}
// Check if the data in each tensor is the same
int *indices = (int *)malloc(a->dimensions * sizeof(int));
for (int i = 0; i < a->total_size; i++) {
// Get the multi-dimensional index for the current flat index
// Multi-dim is the common index type among A and AT
get_multi_dimensional_index(a, i, indices);
int flat_index_a = get_flat_index(a, indices);
int flat_index_b = get_flat_index(b, indices);
// Compare the data values at the calculated flat indices
if (a->data[flat_index_a] != b->data[flat_index_b]) {
free(indices);
return false;
}
}
// Free allocated memory
free(indices);
// If all checks passed, the tensors are equal
return true;
}
// Function to compare two tensors for equality except their data
bool equal_exclude_data(
Tensor *a,
Tensor *b
) {
// Check if the number of dimensions is the same
if (a->dimensions != b->dimensions) {
return false;
}
// Check if the shape of each dimension is the same
for (int i = 0; i < a->dimensions; i++) {
if (a->shape[i] != b->shape[i]) {
return false;
}
}
// Check if the strides of each dimension is the same
for (int i = 0; i < a->dimensions; i++) {
if (a->strides[i] != b->strides[i]) {
return false;
}
}
// Check if the org_strides of each dimension is the same
for (int i = 0; i < a->dimensions; i++) {
if (a->org_strides[i] != b->org_strides[i]) {
return false;
}
}
// If all checks passed, the tensors are equal
return true;
}
// Print double number with specified precision
void __print_double(
double number,
int precision
) {
// Format string to control precision dynamically
char format[50];
snprintf(format, sizeof(format), "%%.%df", precision);
// Print the number with the specified precision
printf(format, number);
}
// Print info of a tensor
void __print_info_helper(
Tensor *tensor,
int precision,
int dim,
int* index
) {
if (tensor->dimensions == 1 && tensor->shape[0] == 1) {
printf("[");
__print_double(tensor->data[0], precision);
printf("]");
} else if (dim < tensor->dimensions - 1) {
printf("[");
for (int i = 0; i < tensor->shape[dim]; i++) {
index[dim] = i;
__print_info_helper(tensor, precision, dim + 1, index);
if (i < tensor->shape[dim] - 1) {
printf(",\n");
for (int j = 0; j < tensor->dimensions - 2 - dim; j++) {
printf("\n");
}
}
}
printf("]");
} else {
printf("[");
for (int i = 0; i < tensor->shape[dim]; i++) {
index[dim] = i;
int flat_idx = get_flat_index(tensor, index);
if (i == tensor->shape[dim] - 1) {
__print_double(tensor->data[flat_idx], precision);
} else {
__print_double(tensor->data[flat_idx], precision);
printf(", ");
}
}
printf("]");
}
}
// Print info of a tensor
void __print_info(
Tensor *tensor,
int precision
) {
int *index = (int *)malloc(tensor->dimensions * sizeof(int));
for (int i = 0; i < tensor->dimensions; i++) {
index[i] = 0;
}
printf("[");
for (int i = 0; i < tensor->shape[0]; i++) {
index[0] = i;
__print_info_helper(tensor, precision, 1, index);
if (i < tensor->shape[0] - 1) {
printf(",\n");
for (int j = 0; j < tensor->dimensions - 2; j++) {
printf("\n");
}
}
}
printf("]\n\n");
printf("(");
for (int i = 0; i < tensor->dimensions; i++) {
if (i < tensor->dimensions - 1) {
printf("%d,", tensor->shape[i]);
} else {
printf("%d", tensor->shape[i]);
}
}
printf(")\n\n");
free(index);
}
void print_info(
Tensor *tensor
) {
__print_info(tensor, 4);
}
void print_info_with_precision(
Tensor *tensor,
int precision
) {
__print_info(tensor, precision);
}
/////////////////////////////////////////////////////////////////////
bool tensor_broadcast(Tensor *, Tensor *, int, int *, int, int *, Tensor **, Tensor **);
void tensor_sum (Tensor *, int, bool, Tensor **);
void tensor_reduce (Tensor *, Tensor *, Tensor **);
void tensor_transpose(Tensor *, int, int, bool, Tensor **);
void tensor_matmul (Tensor *, Tensor *, Tensor **);
void tensor_softmax (Tensor *, int, Tensor **);
void tensor_neg (Tensor *, Tensor **);
void tensor_log (Tensor *, Tensor **);
void tensor_tan (Tensor *, Tensor **);
void tensor_tanh (Tensor *, Tensor **);
void tensor_exp (Tensor *, Tensor **);
void tensor_relu (Tensor *, Tensor **);
void tensor_abs (Tensor *, Tensor **);
void tensor_add (Tensor *, Tensor *, Tensor **);
void tensor_sub (Tensor *, Tensor *, Tensor **);
void tensor_mul (Tensor *, Tensor *, Tensor **);
void tensor_div (Tensor *, Tensor *, Tensor **);
void tensor_pow (Tensor *, Tensor *, Tensor **);
void tensor_view (Tensor *, Tensor *, bool, Tensor **);
void grad_tensor_sum (Tensor *, Tensor *, Tensor **);
void grad_tensor_transpose(Tensor *, int, int, Tensor **);
void grad_tensor_matmul (Tensor *, Tensor *, Tensor *, Tensor **, Tensor **);
void grad_tensor_softmax (Tensor *, Tensor *, Tensor *, int, Tensor **);
void grad_tensor_neg (Tensor *, Tensor **);
void grad_tensor_log (Tensor *, Tensor *, Tensor **);
void grad_tensor_tan (Tensor *, Tensor *, Tensor **);
void grad_tensor_tanh (Tensor *, Tensor *, Tensor **);
void grad_tensor_exp (Tensor *, Tensor *, Tensor **);
void grad_tensor_relu (Tensor *, Tensor *, Tensor **);
void grad_tensor_abs (Tensor *, Tensor *, Tensor **);
void grad_tensor_add (Tensor *, Tensor *, Tensor *, Tensor **, Tensor **);
void grad_tensor_sub (Tensor *, Tensor *, Tensor *, Tensor **, Tensor **);
void grad_tensor_mul (Tensor *, Tensor *, Tensor *, Tensor **, Tensor **);
void grad_tensor_div (Tensor *, Tensor *, Tensor *, Tensor **, Tensor **);
void grad_tensor_pow (Tensor *, Tensor *, Tensor *, Tensor *, Tensor **, Tensor **);
void grad_tensor_view (Tensor *, Tensor *, Tensor **);
///////////////////////////////
// Function to broadcast tensors so that they would align each other
bool tensor_broadcast(
Tensor *a,
Tensor *b,
int num_preserved_dims_a,
int *preserved_dims_a,
int num_preserved_dims_b,
int *preserved_dims_b,
Tensor **out_a,
Tensor **out_b
) {
bool need_broadcasting = false;
// Determine the maximum number of dimensions
int max_dims = (a->dimensions > b->dimensions) ? a->dimensions : b->dimensions;
int offset_dims = (a->dimensions > b->dimensions) ? a->dimensions - b->dimensions : b->dimensions - a->dimensions;
// Allocate memory for broadcasted shapes
int *broadcast_shape_a = (int *)malloc(max_dims * sizeof(int));
int *broadcast_shape_b = (int *)malloc(max_dims * sizeof(int));
// Arrays to store preserved situation of dimensions (initialize all as false)
bool *state_dims_a = (bool *)calloc(max_dims, sizeof(bool));
bool *state_dims_b = (bool *)calloc(max_dims, sizeof(bool));
// Identify preserved dimensions
for (int i = 0; i < num_preserved_dims_a; i++) {
int dim_to_preserve = preserved_dims_a[i];
if (a->dimensions < max_dims) {
state_dims_a[offset_dims + dim_to_preserve] = true;
} else {
state_dims_a[dim_to_preserve] = true;
}
}
for (int i = 0; i < num_preserved_dims_b; i++) {
int dim_to_preserve = preserved_dims_b[i];
if (b->dimensions < max_dims) {
state_dims_b[offset_dims + dim_to_preserve] = true;
} else {
state_dims_b[dim_to_preserve] = true;
}
}
// Fill in the shapes starting from the leftmost dimension
for (int i = 0; i < max_dims; i++) {
int dim_a = (i >= max_dims - a->dimensions) ? a->shape[i - (max_dims - a->dimensions)] : 1;
int dim_b = (i >= max_dims - b->dimensions) ? b->shape[i - (max_dims - b->dimensions)] : 1;
// Determine the broadcasted dimension size, only if the dimension is not preserved
if ((state_dims_a[i] == false || state_dims_b[i] == false) && dim_a != dim_b) {
need_broadcasting = true;
}
if (state_dims_a[i]) {
broadcast_shape_a[i] = dim_a;
} else {
// Apply regular broadcasting rules
if (dim_a == dim_b) {
broadcast_shape_a[i] = dim_a;
} else if (dim_a > 1 && dim_b == 1) {
broadcast_shape_a[i] = dim_a;
} else if (dim_a == 1) {
broadcast_shape_a[i] = dim_b;
} else {
fprintf(stderr, "Error: Tensors are not broadcastable.\n");
exit(EXIT_FAILURE);
}
}
if (state_dims_b[i]) {
broadcast_shape_b[i] = dim_b;
} else {
// Apply regular broadcasting rules
if (dim_a == dim_b) {
broadcast_shape_b[i] = dim_b;
} else if (dim_b > 1 && dim_a == 1) {
broadcast_shape_b[i] = dim_b;
} else if (dim_b == 1) {
broadcast_shape_b[i] = dim_a;
} else {
fprintf(stderr, "Error: Tensors are not broadcastable.\n");
exit(EXIT_FAILURE);
}
}
}
if (need_broadcasting == false) {
// Free allocated memory
free(broadcast_shape_a);
free(broadcast_shape_b);
free(state_dims_a);
free(state_dims_b);
deep_copy_tensor(a, out_a);
deep_copy_tensor(b, out_b);
return false;
}
// Create the output tensors with the broadcasted shape
create_tensor(broadcast_shape_a, max_dims, out_a);
create_tensor(broadcast_shape_b, max_dims, out_b);
// Broadcast tensor a and fill in tensor out_a
int offset_a = max_dims - a->dimensions;
int *src_idx_a = (int *)malloc(a->dimensions * sizeof(int));
int *dest_idx_a = (int *)malloc((*out_a)->dimensions * sizeof(int));
for (int i = 0; i < (*out_a)->total_size; i++) {
get_multi_dimensional_index(*out_a, i, dest_idx_a);
for (int j = offset_a; j < max_dims; j++) {
int orig_idx = j - offset_a;
src_idx_a[orig_idx] = (a->shape[orig_idx] > 1) ? dest_idx_a[j] : 0;
}
int flat_src_idx = get_flat_index(a, src_idx_a);
double ref_value = a->data[flat_src_idx];
(*out_a)->data[i] = ref_value;
}
free(src_idx_a);
free(dest_idx_a);
// Broadcast tensor b and fill in tensor out_b
int offset_b = max_dims - b->dimensions;
int *src_idx_b = (int *)malloc(b->dimensions * sizeof(int));
int *dest_idx_b = (int *)malloc((*out_b)->dimensions * sizeof(int));
for (int i = 0; i < (*out_b)->total_size; i++) {
get_multi_dimensional_index(*out_b, i, dest_idx_b);
for (int j = offset_b; j < max_dims; j++) {
int orig_idx = j - offset_b;
src_idx_b[orig_idx] = (b->shape[orig_idx] > 1) ? dest_idx_b[j] : 0;
}
int flat_src_idx = get_flat_index(b, src_idx_b);
double ref_value = b->data[flat_src_idx];
(*out_b)->data[i] = ref_value;
}
free(src_idx_b);
free(dest_idx_b);
// Free allocated memory
free(broadcast_shape_a);
free(broadcast_shape_b);
free(state_dims_a);
free(state_dims_b);
return true;
}
///////////////////////////////
void tensor_sum(
Tensor *a,
int dim,
bool keepdim,
Tensor **out_tensor
) {
if (dim < 0) {
// Sum all elements in the tensor
create_tensor_from_scalar(0.0, out_tensor);
for (int i = 0; i < a->total_size; i++) {
(*out_tensor)->data[0] += a->data[i];
}
} else {
// Determine the output shape based on `keepdim`
int out_dims = (a->dimensions == 2 || keepdim) ? a->dimensions : a->dimensions - 1;
int new_shape[out_dims];
for (int i = 0, j = 0; i < a->dimensions; i++) {
if (i == dim) {
if (a->dimensions == 2 || keepdim) {
new_shape[j++] = 1; // Keep the dimension with size 1
}
} else {
new_shape[j++] = a->shape[i];
}
}
create_tensor(new_shape, out_dims, out_tensor);
// Calculate outer and inner sizes
int outer_size = 1, inner_size = 1;
for (int i = 0; i < dim; i++) outer_size *= a->shape[i];
for (int i = dim + 1; i < a->dimensions; i++) inner_size *= a->shape[i];
// Sum along the specified dimension
for (int i = 0; i < outer_size; i++) {
for (int j = 0; j < inner_size; j++) {
double sum = 0.0;
for (int k = 0; k < a->shape[dim]; k++) {
int idx = (i * a->shape[dim] * inner_size) + (k * inner_size) + j;
sum += a->data[idx];
}
int out_idx = i * inner_size + j;
(*out_tensor)->data[out_idx] = sum;
}
}
}
}
void grad_tensor_sum(
Tensor *a,
Tensor *grad,
Tensor **out_grad_a
) {
if (out_grad_a) {
Tensor *broadcasted_a = NULL;
Tensor *broadcasted_grad = NULL;
tensor_broadcast(a, grad, 0, NULL, 0, NULL, &broadcasted_a, &broadcasted_grad);
create_tensor(broadcasted_a->shape, broadcasted_a->dimensions, out_grad_a);
for (int i = 0; i < broadcasted_a->total_size; i++) {
(*out_grad_a)->data[i] = broadcasted_grad->data[i];
}
dispose_tensor(broadcasted_a, true);
dispose_tensor(broadcasted_grad, true);
}
}
///////////////////////////////
void tensor_reduce(
Tensor *source_tensor,
Tensor *target_tensor,
Tensor **out_tensor
) {
deep_copy_tensor(source_tensor, out_tensor);
int max_dims = (*out_tensor)->dimensions;
// Fill in the shapes starting from the leftmost dimension
for (int i = 0; i < max_dims; i++) {
int dim_out_size = (*out_tensor)->shape[i];
int dim_dst_size = (i >= max_dims - target_tensor->dimensions) ? target_tensor->shape[i - (max_dims - target_tensor->dimensions)] : 1;
// Determine the broadcasted dimension size
if (dim_dst_size == 1 && dim_out_size > 1) {
Tensor *tmp_grad_input = NULL;
if (i >= max_dims - target_tensor->dimensions) {
tensor_sum(*out_tensor, i, true, &tmp_grad_input);
} else {
tensor_sum(*out_tensor, i, false, &tmp_grad_input);
}
dispose_tensor(*out_tensor, true);
deep_copy_tensor(tmp_grad_input, out_tensor);
dispose_tensor(tmp_grad_input, true);
max_dims = (*out_tensor)->dimensions;
} else if (dim_dst_size != dim_out_size && dim_dst_size > 1 && dim_out_size > 1) {
// Handle the default error case
fprintf(stderr, "Error: Can not reduce source tensor to the target tensor.\n");
exit(EXIT_FAILURE);
}
}
}
///////////////////////////////
// Function to transpose a tensor by swapping two dimensions
void tensor_transpose(
Tensor *a,
int dim1,
int dim2,
bool clone_data,
Tensor **out_tensor
) {
if (clone_data) {
// Create a new tensor structure with transposed shape
create_tensor(a->shape, a->dimensions, out_tensor);
// Swap the dimensions in the shape array
int temp_shape = (*out_tensor)->shape[dim1];
(*out_tensor)->shape[dim1] = (*out_tensor)->shape[dim2];
(*out_tensor)->shape[dim2] = temp_shape;
// Re-calculate strides for a contiguous layout
calculate_strides((*out_tensor)->shape, (*out_tensor)->dimensions, (*out_tensor)->strides);
calculate_strides((*out_tensor)->shape, (*out_tensor)->dimensions, (*out_tensor)->org_strides);
// Copy data from the input tensor to the output tensor with transposed indices
for (int i = 0; i < a->total_size; i++) {
int indices[a->dimensions];
get_multi_dimensional_index(a, i, indices);
// Swap the indices for the transposed dimensions
int temp_index = indices[dim1];
indices[dim1] = indices[dim2];
indices[dim2] = temp_index;
// Calculate the flat index for the output tensor
int flat_index = get_flat_index(*out_tensor, indices);
// Copy the data
(*out_tensor)->data[flat_index] = a->data[i];
}
} else {
// The data pointer is shared between input and result tensors
create_tensor_without_data(a->shape, a->dimensions, out_tensor);
(*out_tensor)->data = a->data;
// Swap the dimensions in the shape array
int temp_shape = (*out_tensor)->shape[dim1];
(*out_tensor)->shape[dim1] = (*out_tensor)->shape[dim2];
(*out_tensor)->shape[dim2] = temp_shape;
// Swap the strides for the transposed dimensions
int temp_stride = (*out_tensor)->strides[dim1];
(*out_tensor)->strides[dim1] = (*out_tensor)->strides[dim2];
(*out_tensor)->strides[dim2] = temp_stride;
// Re-calculate the original strides for the transposed tensor
calculate_strides((*out_tensor)->shape, (*out_tensor)->dimensions, (*out_tensor)->org_strides);
}
}
void grad_tensor_transpose(
Tensor *grad,
int dim1,
int dim2,
Tensor **out_grad_a
) {
tensor_transpose(grad, dim1, dim2, true, out_grad_a);
}
///////////////////////////////
// Helper function to perform matrix multiplication on 2D arrays with strides
void __matrix_multiply_strided(
double *a, int *a_strides, // Data pointer and strides for A
double *b, int *b_strides, // Data pointer and strides for B
double *out, int *out_strides, // Data pointer and strides for the output
int n, int m, int p // Dimensions: n x m x p
) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < p; j++) {
// Compute the address of the current output element using strides
double *out_ptr = out + i * out_strides[0] + j * out_strides[1];
*out_ptr = 0;
for (int k = 0; k < m; k++) {
// Compute the addresses for the current A and B elements using strides
double *a_ptr = a + i * a_strides[0] + k * a_strides[1];
double *b_ptr = b + k * b_strides[0] + j * b_strides[1];
// Perform the multiplication and add to the output
*out_ptr += (*a_ptr) * (*b_ptr);
}
}
}
}
// Function to perform batch matrix multiplication
void tensor_matmul(
Tensor *a,
Tensor *b,
Tensor **out_tensor
) {
// Dimensions of the matrices to multiply
int a_last_dim = a->shape[a->dimensions - 1];
int a_second_last_dim = (a->dimensions > 1) ? a->shape[a->dimensions - 2] : 1;
int b_last_dim = b->shape[b->dimensions - 1];
int b_second_last_dim = (b->dimensions > 1) ? b->shape[b->dimensions - 2] : 1;
// Ensure matrix multiplication dimensions match
if (a_last_dim != b_second_last_dim) {
fprintf(stderr, "Error: Matrix multiplication dimensions do not align.\n");
exit(EXIT_FAILURE);
}
// Calculate the number of batch dimensions for each tensor
int a_batch_dims = a->dimensions - 2;
int b_batch_dims = b->dimensions - 2;
// Broadcasted batch dimensions for both tensors and preserve the last two dimensions (matrix dimensions)
Tensor *broadcasted_a = NULL;
Tensor *broadcasted_b = NULL;
int preserved_dims_a[] = {a->dimensions - 1, a->dimensions - 2};
int preserved_dims_b[] = {b->dimensions - 1, b->dimensions - 2};
tensor_broadcast(a, b, 2, preserved_dims_a, 2, preserved_dims_b, &broadcasted_a, &broadcasted_b);
// Create the output tensor
int *out_shape = (int *)malloc((broadcasted_a->dimensions) * sizeof(int));
memcpy(out_shape, broadcasted_a->shape, (broadcasted_a->dimensions - 2) * sizeof(int));
out_shape[broadcasted_a->dimensions - 2] = a_second_last_dim; // n from a
out_shape[broadcasted_a->dimensions - 1] = b_last_dim; // p from b
create_tensor(out_shape, broadcasted_a->dimensions, out_tensor);
// Get strides for each tensor
int *a_strides = broadcasted_a->strides;
int *b_strides = broadcasted_b->strides;
int *out_strides = (*out_tensor)->strides;
// Iterate over the broadcasted batch dimensions
for (int i = 0; i < calculate_total_size(broadcasted_a->shape, broadcasted_a->dimensions - 2); i++) {
// Identify the correct slices for 'a' and 'b'
int a_batch_idx = i * a_second_last_dim * a_last_dim;
int b_batch_idx = i * b_second_last_dim * b_last_dim;
int out_batch_idx = i * a_second_last_dim * b_last_dim;
double *a_slice = &broadcasted_a->data[a_batch_idx];
double *b_slice = &broadcasted_b->data[b_batch_idx];
double *out_slice = &(*out_tensor)->data[out_batch_idx];
// Perform matrix multiplication for this slice
__matrix_multiply_strided(
a_slice, a_strides + broadcasted_a->dimensions - 2,
b_slice, b_strides + broadcasted_b->dimensions - 2,
out_slice, out_strides + (*out_tensor)->dimensions - 2,
a_second_last_dim, a_last_dim, b_last_dim
);
}
// Free allocated memory
free(out_shape);
dispose_tensor(broadcasted_a, true);
dispose_tensor(broadcasted_b, true);
}
void grad_tensor_matmul(
Tensor *a,
Tensor *b,
Tensor *grad,
Tensor **out_grad_a,
Tensor **out_grad_b
) {
Tensor *tmp_out_grad_a = NULL, *tmp_out_grad_b = NULL;
if (out_grad_a) {
Tensor *b_T = NULL;
int dim1 = b->dimensions - 2, dim2 = b->dimensions - 1;
tensor_transpose(b, dim1, dim2, false, &b_T);
tensor_matmul(grad, b_T, &tmp_out_grad_a);
dispose_tensor(b_T, false);
tensor_reduce(tmp_out_grad_a, a, out_grad_a);
dispose_tensor(tmp_out_grad_a, true);
}
if (out_grad_b) {
Tensor *a_T = NULL;
int dim1 = a->dimensions - 2, dim2 = a->dimensions - 1;
tensor_transpose(a, dim1, dim2, false, &a_T);
tensor_matmul(a_T, grad, &tmp_out_grad_b);
dispose_tensor(a_T, false);
tensor_reduce(tmp_out_grad_b, b, out_grad_b);
dispose_tensor(tmp_out_grad_b, true);
}
}
///////////////////////////////
void tensor_softmax(
Tensor *a,
int dim,
Tensor **out_tensor
) {
// Create output tensor with the same shape as the input
create_tensor(a->shape, a->dimensions, out_tensor);
// Calculate softmax along the specified dimension
int outer_size = 1, inner_size = 1;
for (int i = 0; i < dim; i++) outer_size *= a->shape[i];
for (int i = dim + 1; i < a->dimensions; i++) inner_size *= a->shape[i];
// Compute softmax along the specified dimension
for (int i = 0; i < outer_size; i++) {
for (int j = 0; j < inner_size; j++) {
// Calculate the sum of exponentials along `dim`
double sum_exp = 0.0;
for (int k = 0; k < a->shape[dim]; k++) {
int idx = (i * a->shape[dim] * inner_size) + (k * inner_size) + j;
sum_exp += exp(a->data[idx]);
}
// Calculate softmax for each element along `dim`
for (int k = 0; k < a->shape[dim]; k++) {
int idx = (i * a->shape[dim] * inner_size) + (k * inner_size) + j;