-
Notifications
You must be signed in to change notification settings - Fork 0
/
ctorch.c
2643 lines (2195 loc) · 83.1 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 {
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,
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 = (double *)malloc(total_size * sizeof(double));
(*out_tensor)->dimensions = dimensions;
(*out_tensor)->total_size = total_size;
memcpy((*out_tensor)->shape, shape, dimensions * sizeof(int));
calculate_strides(shape, dimensions, (*out_tensor)->strides);
calculate_strides(shape, dimensions, (*out_tensor)->org_strides);
}
// Function to initialize a tensor with a given shape
void deep_copy_tensor(
Tensor *tensor,
Tensor **out_tensor
) {
double *data = tensor->data;
int *shape = tensor->shape;
int dimensions = tensor->dimensions;
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 = (double *)malloc(total_size * sizeof(double));
(*out_tensor)->dimensions = dimensions;
(*out_tensor)->total_size = total_size;
memcpy((*out_tensor)->data, data, total_size * sizeof(double));
memcpy((*out_tensor)->shape, shape, dimensions * sizeof(int));
calculate_strides(shape, dimensions, (*out_tensor)->strides);
calculate_strides(shape, dimensions, (*out_tensor)->org_strides);
}
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);
}
void print(
int *arr,
int count
) {
for (int i = 0; i < count; i++) {
printf("%d", arr[i]);
if (i < count - 1) {
printf(", ");
}
}
printf("\n\n");
}
// Function to broadcast tensors so that they would align each other
void 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
) {
// 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]) {
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);
}
}
}
// 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);
}
double ct_add(
double a,
double b,
double *out_grad_a,
double *out_grad_b
) {
double out = a + b;
if (out_grad_a) *out_grad_a = 1;
if (out_grad_b) *out_grad_b = 1;
return out;
}
double ct_sub(
double a,
double b,
double *out_grad_a,
double *out_grad_b
) {
double out = a - b;
if (out_grad_a) *out_grad_a = 1;
if (out_grad_b) *out_grad_b = -1;
return out;
}
double ct_mul(
double a,
double b,
double *out_grad_a,
double *out_grad_b
) {
double out = a * b;
if (out_grad_a) *out_grad_a = b;
if (out_grad_b) *out_grad_b = a;
return out;
}
double ct_pow(
double a,
double b,
double *out_grad_a,
double *out_grad_b
) {
double out = pow(a, b);
if (out_grad_a) *out_grad_a = b * pow(a, b - 1);
return out;
}
double ct_div(
double a,
double b,
double *out_grad_a,
double *out_grad_b
) {
if (b == 0) {
fprintf(stderr, "Error: Division by zero.\n");
exit(EXIT_FAILURE);
}
double out = a / b;
if (out_grad_a) *out_grad_a = 1 / b;
if (out_grad_b) *out_grad_b = -a / (b * b);
return out;
}
double ct_neg(
double a,
double *out_grad_a
) {
double out = -a;
if (out_grad_a) *out_grad_a = -1;
return out;
}
double ct_exp(
double a,
double *out_grad_a
) {
double out = exp(a);
if (out_grad_a) *out_grad_a = out;
return out;
}
double ct_log(
double a,
double *out_grad_a
) {
double out = log(a);
if (out_grad_a) *out_grad_a = 1.0 / a;
return out;
}
double ct_tanh(
double a,
double *out_grad_a
) {
double e_pos = ct_exp(a, NULL);
double e_neg = ct_exp(-a, NULL);
double out = (e_pos - e_neg) / (e_pos + e_neg);
if (out_grad_a) *out_grad_a = 1 - (out * out);
return out;
}
double ct_tan(
double a,
double *out_grad_a
) {
double out = tan(a);
double c = cos(a);
if (out_grad_a) *out_grad_a = 1.0 / (c * c);
return out;
}
double ct_abs(
double a,
double *out_grad_a
) {
double out = a >= 0 ? a : -a;
if (out_grad_a) *out_grad_a = a >= 0 ? 1 : -1;
return out;
}
double ct_relu(
double a,
double *out_grad_a
) {
double out = a > 0 ? a : 0;
if (out_grad_a) *out_grad_a = a > 0 ? 1 : 0;
return out;
}
double ct_pow2(
double a,
double *out_grad_a
) {
double out = a * a;
if (out_grad_a) *out_grad_a = 2 * a;
return out;
}
// Function to perform matrix multiplication on 2D arrays
void ct_matrix_multiply(
double *a,
double *b,
double *out,
int n,
int m,
int p
) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < p; j++) {
out[i * p + j] = 0;
for (int k = 0; k < m; k++) {
out[i * p + j] += a[i * m + k] * b[k * p + j];
}
}
}
}
void ct_sum(
Tensor *tensor,
int dim,
Tensor **out_grad_tensor,
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 < tensor->total_size; i++) {
(*out_tensor)->data[0] += tensor->data[i];
}
// Create gradient tensor with all entries set to 1 for broadcasting
if (out_grad_tensor) {
create_tensor(tensor->shape, tensor->dimensions, out_grad_tensor);
init_tensor(1.0, *out_grad_tensor);
}
} else {
// Compute the new shape by removing the specified dimension and create output tensor
if (tensor->dimensions == 2) {
int new_shape[tensor->dimensions];
for (int i = 0, j = 0; i < tensor->dimensions; i++) {
if (i != dim) {
new_shape[j++] = tensor->shape[i];
} else {
new_shape[j++] = 1;
}
}
create_tensor(new_shape, tensor->dimensions, out_tensor);
} else {
int new_shape[tensor->dimensions - 1];
for (int i = 0, j = 0; i < tensor->dimensions; i++) {
if (i != dim) {
new_shape[j++] = tensor->shape[i];
}
}
create_tensor(new_shape, tensor->dimensions - 1, out_tensor);
}
int outer_size = 1, inner_size = 1;
for (int i = 0; i < dim; i++) outer_size *= tensor->shape[i];
for (int i = dim + 1; i < tensor->dimensions; i++) inner_size *= tensor->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 < tensor->shape[dim]; k++) {
int idx = (i * tensor->shape[dim] * inner_size) + (k * inner_size) + j;
sum += tensor->data[idx];
}
int out_idx = i * inner_size + j;
(*out_tensor)->data[out_idx] = sum;
}
}
// Create the gradient tensor for backpropagation if requested
if (out_grad_tensor) {
create_tensor(tensor->shape, tensor->dimensions, out_grad_tensor);
init_tensor(0.0, *out_grad_tensor);
// Distribute the gradients equally across summed elements
for (int i = 0; i < outer_size; i++) {
for (int j = 0; j < inner_size; j++) {
int out_idx = i * inner_size + j;
for (int k = 0; k < tensor->shape[dim]; k++) {
int idx = (i * tensor->shape[dim] * inner_size) + (k * inner_size) + j;
(*out_grad_tensor)->data[idx] = 1.0;
}
}
}
}
}
}
void ct_softmax(
Tensor *tensor,
int dim,
Tensor **out_grad_tensor,
Tensor **out_tensor
) {
// Create output tensor with the same shape as the input tensor
create_tensor(tensor->shape, tensor->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 *= tensor->shape[i];
for (int i = dim + 1; i < tensor->dimensions; i++) inner_size *= tensor->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 < tensor->shape[dim]; k++) {
int idx = (i * tensor->shape[dim] * inner_size) + (k * inner_size) + j;
sum_exp += ct_exp(tensor->data[idx], NULL);
}
// Calculate softmax for each element along `dim`
for (int k = 0; k < tensor->shape[dim]; k++) {
int idx = (i * tensor->shape[dim] * inner_size) + (k * inner_size) + j;
(*out_tensor)->data[idx] = ct_exp(tensor->data[idx], NULL) / sum_exp;
}
}
}
// If gradient tensor is requested, calculate Jacobian
if (out_grad_tensor) {
// Define shape for the Jacobian tensor
int shape[tensor->dimensions + 1];
for (int i = 0; i < tensor->dimensions + 1; i++) {
shape[i] = (i <= dim) ? tensor->shape[i] : tensor->shape[i - 1];
}
create_tensor(shape, tensor->dimensions + 1, out_grad_tensor);
int jacobian_indices[tensor->dimensions + 1]; // To hold indices in the Jacobian tensor
for (int i = 0; i < outer_size; i++) {
for (int j = 0; j < inner_size; j++) {
for (int m = 0; m < tensor->shape[dim]; m++) {
int idx_m = (i * tensor->shape[dim] * inner_size) + (m * inner_size) + j;
double sm_m = (*out_tensor)->data[idx_m];
for (int n = 0; n < tensor->shape[dim]; n++) {
int idx_n = (i * tensor->shape[dim] * inner_size) + (n * inner_size) + j;
double sm_n = (*out_tensor)->data[idx_n];
// Calculate gradient value
double grad_value = (m == n) ? sm_m * (1 - sm_m) : -sm_m * sm_n;
// Construct the full Jacobian index
int original_indices[tensor->dimensions]; // To hold original indices
int tmp = i * inner_size * tensor->shape[dim] + j;
// Calculate all original indices, both before and after dim
for (int d = tensor->dimensions - 1; d >= 0; d--) {
if (d != dim) {
original_indices[d] = tmp % tensor->shape[d];
tmp /= tensor->shape[d];
}
}
// Populate jacobian_indices with original indices, inserting m and n at the extra dimension
for (int d = 0; d < tensor->dimensions + 1; d++) {
if (d < dim) {
jacobian_indices[d] = original_indices[d];
} else if (d == dim) {
jacobian_indices[d] = m; // For the softmax dim index m
} else if (d == dim + 1) {
jacobian_indices[d] = n; // For the softmax dim index n
} else {
jacobian_indices[d] = original_indices[d - 1];
}
}
// Set the value in the Jacobian tensor
int flat_idx = get_flat_index(*out_grad_tensor, jacobian_indices);
(*out_grad_tensor)->data[flat_idx] = grad_value;
}
}
}
}
}
}
// Function to perform batch matrix multiplication
void ct_matmul(
Tensor *a,
Tensor *b,
Tensor **out_result
) {
// 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};
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_result);
// 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;
double *a_slice = &broadcasted_a->data[a_batch_idx];
double *b_slice = &broadcasted_b->data[b_batch_idx];
double *out_slice = &(*out_result)->data[i * a_second_last_dim * b_last_dim];
// Perform matrix multiplication for this slice
ct_matrix_multiply(a_slice, b_slice, out_slice, a_second_last_dim, a_last_dim, b_last_dim);
}
// Free allocated memory
free(out_shape);
dispose_tensor(broadcasted_a, true);