-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruby_matrix.c
More file actions
1367 lines (1179 loc) · 46.7 KB
/
ruby_matrix.c
File metadata and controls
1367 lines (1179 loc) · 46.7 KB
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 <ruby.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#ifdef _OPENMP
#include <omp.h>
#endif
// Define data types
typedef enum {
DTYPE_FLOAT64,
DTYPE_FLOAT32,
DTYPE_INT16,
DTYPE_INT8
} DataType;
// Define a Matrix/Tensor struct (order-2 today, extensible to higher orders)
typedef struct {
size_t rows;
size_t cols;
void *data; // Pointer to data (numeric storage)
DataType dtype; // Data type of the tensor
size_t rank; // Tensor rank (2 for matrices)
size_t *dims; // Dimensions array of length `rank` (optional today)
} Matrix;
// Compute total number of elements in a tensor
static size_t tensor_numel(const Matrix *tensor) {
if (tensor->rank > 0 && tensor->dims) {
size_t n = 1;
for (size_t i = 0; i < tensor->rank; i++) {
n *= tensor->dims[i];
}
return n;
}
return tensor->rows * tensor->cols;
}
// Compute row-major strides for each dimension
static void tensor_compute_strides(const Matrix *tensor, size_t *strides_out) {
if (tensor->rank == 0 || !tensor->dims) {
strides_out[0] = 1;
return;
}
size_t r = tensor->rank;
strides_out[r - 1] = 1;
for (ssize_t i = (ssize_t)r - 2; i >= 0; i--) {
strides_out[i] = strides_out[i + 1] * tensor->dims[i + 1];
}
}
// Read a scalar value at a given flat index
static VALUE tensor_value_at(const Matrix *tensor, size_t index) {
if (tensor->dtype == DTYPE_FLOAT64) {
return DBL2NUM(((double *)tensor->data)[index]);
} else if (tensor->dtype == DTYPE_FLOAT32) {
return DBL2NUM((double)((float *)tensor->data)[index]);
} else if (tensor->dtype == DTYPE_INT16) {
return DBL2NUM((double)((int16_t *)tensor->data)[index]);
} else if (tensor->dtype == DTYPE_INT8) {
return DBL2NUM((double)((int8_t *)tensor->data)[index]);
} else {
rb_raise(rb_eArgError, "Unsupported data type in tensor_value_at");
}
}
// Write a scalar value at a given flat index
static void tensor_set_value_at(Matrix *tensor, size_t index, VALUE value) {
if (tensor->dtype == DTYPE_FLOAT64) {
((double *)tensor->data)[index] = NUM2DBL(value);
} else if (tensor->dtype == DTYPE_FLOAT32) {
((float *)tensor->data)[index] = (float)NUM2DBL(value);
} else if (tensor->dtype == DTYPE_INT16) {
((int16_t *)tensor->data)[index] = (int16_t)NUM2INT(value);
} else if (tensor->dtype == DTYPE_INT8) {
((int8_t *)tensor->data)[index] = (int8_t)NUM2INT(value);
} else {
rb_raise(rb_eArgError, "Unsupported data type in tensor_set_value_at");
}
}
// Get number of available threads
static size_t get_num_threads() {
#ifdef _OPENMP
return omp_get_max_threads(); // Default to max threads
#else
return 16; // Fallback value (adjust as needed)
#endif
}
// Function to allocate a new Matrix
Matrix *matrix_new(size_t rows, size_t cols, DataType dtype) {
if (rows == 0 || cols == 0) {
rb_raise(rb_eArgError, "Rows and columns must be greater than zero");
}
Matrix *matrix = malloc(sizeof(Matrix));
if (!matrix) {
rb_raise(rb_eNoMemError, "Failed to allocate memory for matrix");
}
matrix->rows = rows;
matrix->cols = cols;
matrix->dtype = dtype;
matrix->rank = 2;
matrix->dims = NULL;
if (dtype == DTYPE_FLOAT64) {
matrix->data = calloc(rows * cols, sizeof(double));
} else if (dtype == DTYPE_FLOAT32) {
matrix->data = calloc(rows * cols, sizeof(float));
} else if (dtype == DTYPE_INT16) {
matrix->data = calloc(rows * cols, sizeof(int16_t));
} else if (dtype == DTYPE_INT8) {
matrix->data = calloc(rows * cols, sizeof(int8_t));
} else {
free(matrix);
rb_raise(rb_eArgError, "Unsupported data type");
}
if (!matrix->data) {
free(matrix);
rb_raise(rb_eNoMemError, "Failed to allocate memory for matrix data");
}
// Initialize dims for 2D tensor (matrix)
matrix->dims = malloc(2 * sizeof(size_t));
if (!matrix->dims) {
free(matrix->data);
free(matrix);
rb_raise(rb_eNoMemError, "Failed to allocate memory for tensor dimensions");
}
matrix->dims[0] = rows;
matrix->dims[1] = cols;
return matrix;
}
// Function to free a Matrix
void matrix_free(Matrix *matrix) {
if (matrix) {
if (matrix->data) free(matrix->data);
if (matrix->dims) free(matrix->dims);
free(matrix);
}
}
// Matrix multiplication with OpenMP
Matrix *matrix_multiply(const Matrix *a, const Matrix *b) {
if (a->cols != b->rows || a->dtype != b->dtype) {
rb_raise(rb_eArgError, "Incompatible matrix dimensions or data types");
}
if (a->dtype != DTYPE_FLOAT64 && a->dtype != DTYPE_FLOAT32) {
rb_raise(rb_eArgError, "matrix_multiply supports only float32/float64 matrices");
}
Matrix *result = matrix_new(a->rows, b->cols, a->dtype);
size_t num_threads = get_num_threads();
if (a->dtype == DTYPE_FLOAT64) {
#pragma omp parallel for schedule(dynamic) collapse(2) num_threads(num_threads)
for (size_t i = 0; i < a->rows; i++) {
for (size_t j = 0; j < b->cols; j++) {
double sum = 0.0;
for (size_t k = 0; k < a->cols; k++) {
sum += ((double *)a->data)[i * a->cols + k] *
((double *)b->data)[k * b->cols + j];
}
((double *)result->data)[i * result->cols + j] = sum;
}
}
} else { // DTYPE_FLOAT32
#pragma omp parallel for schedule(dynamic) collapse(2) num_threads(num_threads)
for (size_t i = 0; i < a->rows; i++) {
for (size_t j = 0; j < b->cols; j++) {
float sum = 0.0f;
for (size_t k = 0; k < a->cols; k++) {
sum += ((float *)a->data)[i * a->cols + k] *
((float *)b->data)[k * b->cols + j];
}
((float *)result->data)[i * result->cols + j] = sum;
}
}
}
return result;
}
// ReLU activation with OpenMP
void matrix_relu(Matrix *matrix) {
size_t size = matrix->rows * matrix->cols;
size_t num_threads = get_num_threads();
if (matrix->dtype != DTYPE_FLOAT64 && matrix->dtype != DTYPE_FLOAT32) {
rb_raise(rb_eArgError, "relu supports only float32/float64 matrices");
}
if (matrix->dtype == DTYPE_FLOAT64) {
double *data = (double *)matrix->data;
#pragma omp parallel for schedule(dynamic) num_threads(num_threads)
for (size_t i = 0; i < size; i++) {
data[i] = data[i] > 0 ? data[i] : 0;
}
} else { // DTYPE_FLOAT32
float *data = (float *)matrix->data;
#pragma omp parallel for schedule(dynamic) num_threads(num_threads)
for (size_t i = 0; i < size; i++) {
data[i] = data[i] > 0 ? data[i] : 0;
}
}
}
// ReLU gradient with OpenMP
Matrix *matrix_relu_grad(const Matrix *input) {
if (input->dtype != DTYPE_FLOAT64 && input->dtype != DTYPE_FLOAT32) {
rb_raise(rb_eArgError, "relu_grad supports only float32/float64 matrices");
}
Matrix *output = matrix_new(input->rows, input->cols, input->dtype);
size_t size = input->rows * input->cols;
size_t num_threads = get_num_threads();
if (input->dtype == DTYPE_FLOAT64) {
double *in_data = (double *)input->data;
double *out_data = (double *)output->data;
#pragma omp parallel for schedule(dynamic) num_threads(num_threads)
for (size_t i = 0; i < size; i++) {
out_data[i] = in_data[i] > 0 ? 1.0 : 0.0;
}
} else { // DTYPE_FLOAT32
float *in_data = (float *)input->data;
float *out_data = (float *)output->data;
#pragma omp parallel for schedule(dynamic) num_threads(num_threads)
for (size_t i = 0; i < size; i++) {
out_data[i] = in_data[i] > 0 ? 1.0f : 0.0f;
}
}
return output;
}
// Recursive helper to convert tensor to nested Ruby arrays
static VALUE tensor_to_a_recursive(const Matrix *tensor, size_t depth, size_t base_index, const size_t *strides) {
if (tensor->rank == 0 || !tensor->dims) {
// Treat as a flat vector
VALUE ary = rb_ary_new();
size_t total = tensor_numel(tensor);
for (size_t i = 0; i < total; i++) {
rb_ary_push(ary, tensor_value_at(tensor, i));
}
return ary;
}
size_t dim = tensor->dims[depth];
VALUE ary = rb_ary_new_capa((long)dim);
if (depth == tensor->rank - 1) {
// Last dimension: return scalars
for (size_t i = 0; i < dim; i++) {
size_t index = base_index + i * strides[depth];
rb_ary_push(ary, tensor_value_at(tensor, index));
}
} else {
// Nested arrays
for (size_t i = 0; i < dim; i++) {
size_t next_base = base_index + i * strides[depth];
rb_ary_push(ary, tensor_to_a_recursive(tensor, depth + 1, next_base, strides));
}
}
return ary;
}
// Convert tensor to nested Ruby arrays
VALUE matrix_to_a(const Matrix *matrix) {
if (matrix->rank <= 1 || !matrix->dims) {
// 0D/1D fallback: flat array
VALUE ary = rb_ary_new();
size_t total = tensor_numel(matrix);
for (size_t i = 0; i < total; i++) {
rb_ary_push(ary, tensor_value_at(matrix, i));
}
return ary;
}
size_t *strides = malloc(matrix->rank * sizeof(size_t));
if (!strides) {
rb_raise(rb_eNoMemError, "Failed to allocate memory for tensor strides");
}
tensor_compute_strides(matrix, strides);
VALUE result = tensor_to_a_recursive(matrix, 0, 0, strides);
free(strides);
return result;
}
// Ruby method bindings
VALUE rb_tensor_class = Qnil;
// Allocate a new Matrix (Ruby allocator function)
VALUE rb_matrix_allocate(VALUE klass) {
Matrix *matrix = malloc(sizeof(Matrix));
if (!matrix) {
rb_raise(rb_eNoMemError, "Failed to allocate memory for matrix");
}
matrix->rows = 0;
matrix->cols = 0;
matrix->data = NULL;
matrix->dtype = DTYPE_FLOAT64; // Default to FLOAT64
matrix->rank = 0;
matrix->dims = NULL;
return Data_Wrap_Struct(klass, NULL, matrix_free, matrix);
}
// Ruby method to initialize a Matrix
VALUE rb_matrix_initialize(int argc, VALUE *argv, VALUE self) {
Matrix *matrix;
Data_Get_Struct(self, Matrix, matrix);
if (matrix->data) {
free(matrix->data);
matrix->data = NULL;
}
if (matrix->dims) {
free(matrix->dims);
matrix->dims = NULL;
}
// Parse arguments
VALUE rows, cols, kwargs;
rb_scan_args(argc, argv, "2:", &rows, &cols, &kwargs);
size_t r = NUM2SIZET(rows);
size_t c = NUM2SIZET(cols);
if (r == 0 || c == 0) {
rb_raise(rb_eArgError, "Rows and columns must be greater than zero");
}
matrix->rows = r;
matrix->cols = c;
matrix->rank = 2;
// Default dtype is float32
matrix->dtype = DTYPE_FLOAT32;
// Parse dtype from kwargs
if (!NIL_P(kwargs)) {
VALUE dtype_arg = rb_hash_aref(kwargs, ID2SYM(rb_intern("dtype")));
if (!NIL_P(dtype_arg)) {
const char *dtype_str = StringValueCStr(dtype_arg);
if (strcmp(dtype_str, "float64") == 0) {
matrix->dtype = DTYPE_FLOAT64;
} else if (strcmp(dtype_str, "float32") == 0) {
matrix->dtype = DTYPE_FLOAT32;
} else if (strcmp(dtype_str, "int16") == 0) {
matrix->dtype = DTYPE_INT16;
} else if (strcmp(dtype_str, "int8") == 0) {
matrix->dtype = DTYPE_INT8;
} else {
rb_raise(rb_eArgError, "Unsupported data type: %s", dtype_str);
}
}
}
// Allocate memory based on dtype
if (matrix->dtype == DTYPE_FLOAT64) {
matrix->data = calloc(r * c, sizeof(double));
} else if (matrix->dtype == DTYPE_FLOAT32) {
matrix->data = calloc(r * c, sizeof(float));
} else if (matrix->dtype == DTYPE_INT16) {
matrix->data = calloc(r * c, sizeof(int16_t));
} else if (matrix->dtype == DTYPE_INT8) {
matrix->data = calloc(r * c, sizeof(int8_t));
} else {
rb_raise(rb_eArgError, "Unsupported data type");
}
if (!matrix->data) {
rb_raise(rb_eNoMemError, "Failed to allocate memory for matrix data");
}
// Initialize dims for 2D tensor (matrix)
matrix->dims = malloc(2 * sizeof(size_t));
if (!matrix->dims) {
free(matrix->data);
matrix->data = NULL;
rb_raise(rb_eNoMemError, "Failed to allocate memory for tensor dimensions");
}
matrix->dims[0] = r;
matrix->dims[1] = c;
return self;
}
Matrix *matrix_convert_dtype(const Matrix *input, DataType new_dtype) {
Matrix *result = matrix_new(input->rows, input->cols, new_dtype);
size_t size = input->rows * input->cols;
if (input->dtype == DTYPE_FLOAT64) {
double *in_data = (double *)input->data;
if (new_dtype == DTYPE_FLOAT32) {
float *out_data = (float *)result->data;
for (size_t i = 0; i < size; i++) {
out_data[i] = (float)in_data[i];
}
} else if (new_dtype == DTYPE_INT16) {
int16_t *out_data = (int16_t *)result->data;
for (size_t i = 0; i < size; i++) {
out_data[i] = (int16_t)in_data[i];
}
} else if (new_dtype == DTYPE_INT8) {
int8_t *out_data = (int8_t *)result->data;
for (size_t i = 0; i < size; i++) {
out_data[i] = (int8_t)in_data[i];
}
}
} else if (input->dtype == DTYPE_FLOAT32) {
float *in_data = (float *)input->data;
if (new_dtype == DTYPE_FLOAT64) {
double *out_data = (double *)result->data;
for (size_t i = 0; i < size; i++) {
out_data[i] = (double)in_data[i];
}
} else if (new_dtype == DTYPE_INT16) {
int16_t *out_data = (int16_t *)result->data;
for (size_t i = 0; i < size; i++) {
out_data[i] = (int16_t)in_data[i];
}
} else if (new_dtype == DTYPE_INT8) {
int8_t *out_data = (int8_t *)result->data;
for (size_t i = 0; i < size; i++) {
out_data[i] = (int8_t)in_data[i];
}
}
} else if (input->dtype == DTYPE_INT16) {
int16_t *in_data = (int16_t *)input->data;
if (new_dtype == DTYPE_FLOAT64) {
double *out_data = (double *)result->data;
for (size_t i = 0; i < size; i++) {
out_data[i] = (double)in_data[i];
}
} else if (new_dtype == DTYPE_FLOAT32) {
float *out_data = (float *)result->data;
for (size_t i = 0; i < size; i++) {
out_data[i] = (float)in_data[i];
}
} else if (new_dtype == DTYPE_INT8) {
int8_t *out_data = (int8_t *)result->data;
for (size_t i = 0; i < size; i++) {
out_data[i] = (int8_t)in_data[i];
}
}
} else if (input->dtype == DTYPE_INT8) {
int8_t *in_data = (int8_t *)input->data;
if (new_dtype == DTYPE_FLOAT64) {
double *out_data = (double *)result->data;
for (size_t i = 0; i < size; i++) {
out_data[i] = (double)in_data[i];
}
} else if (new_dtype == DTYPE_FLOAT32) {
float *out_data = (float *)result->data;
for (size_t i = 0; i < size; i++) {
out_data[i] = (float)in_data[i];
}
} else if (new_dtype == DTYPE_INT16) {
int16_t *out_data = (int16_t *)result->data;
for (size_t i = 0; i < size; i++) {
out_data[i] = (int16_t)in_data[i];
}
}
}
return result;
}
// Ruby method for dtype conversion
VALUE rb_matrix_convert_dtype(VALUE self, VALUE dtype_arg) {
Matrix *input;
Data_Get_Struct(self, Matrix, input);
const char *dtype_str = StringValueCStr(dtype_arg);
DataType new_dtype;
if (strcmp(dtype_str, "float64") == 0) {
new_dtype = DTYPE_FLOAT64;
} else if (strcmp(dtype_str, "float32") == 0) {
new_dtype = DTYPE_FLOAT32;
} else if (strcmp(dtype_str, "int16") == 0) {
new_dtype = DTYPE_INT16;
} else if (strcmp(dtype_str, "int8") == 0) {
new_dtype = DTYPE_INT8;
} else {
rb_raise(rb_eArgError, "Unsupported data type: %s", dtype_str);
}
Matrix *result = matrix_convert_dtype(input, new_dtype);
return Data_Wrap_Struct(rb_tensor_class, NULL, matrix_free, result);
}
// Ruby method to access a single element of the matrix
VALUE rb_matrix_get_element(int argc, VALUE *argv, VALUE self) {
Matrix *tensor;
Data_Get_Struct(self, Matrix, tensor);
if (tensor->rank == 0 || !tensor->dims) {
rb_raise(rb_eArgError, "Tensor has no dimensions");
}
if ((size_t)argc != tensor->rank) {
rb_raise(rb_eArgError, "Expected %zu indices, got %d", tensor->rank, argc);
}
size_t *strides = malloc(tensor->rank * sizeof(size_t));
if (!strides) {
rb_raise(rb_eNoMemError, "Failed to allocate memory for tensor strides");
}
tensor_compute_strides(tensor, strides);
size_t index = 0;
for (size_t d = 0; d < tensor->rank; d++) {
long idx = NUM2LONG(argv[d]);
long dim = (long)tensor->dims[d];
if (idx < 0) {
idx += dim; // negative indexing from the end
}
if (idx < 0 || idx >= dim) {
free(strides);
rb_raise(rb_eArgError, "Index out of bounds");
}
index += (size_t)idx * strides[d];
}
VALUE result = tensor_value_at(tensor, index);
free(strides);
return result;
}
// Ruby method to set a single element of the matrix
VALUE rb_matrix_set_element(int argc, VALUE *argv, VALUE self) {
if (argc < 1) {
rb_raise(rb_eArgError, "Value required for assignment");
}
VALUE value = argv[argc - 1];
int index_count = argc - 1;
Matrix *tensor;
Data_Get_Struct(self, Matrix, tensor);
if (tensor->rank == 0 || !tensor->dims) {
rb_raise(rb_eArgError, "Tensor has no dimensions");
}
if ((size_t)index_count != tensor->rank) {
rb_raise(rb_eArgError, "Expected %zu indices, got %d", tensor->rank, index_count);
}
size_t *strides = malloc(tensor->rank * sizeof(size_t));
if (!strides) {
rb_raise(rb_eNoMemError, "Failed to allocate memory for tensor strides");
}
tensor_compute_strides(tensor, strides);
size_t index = 0;
for (size_t d = 0; d < tensor->rank; d++) {
long idx = NUM2LONG(argv[d]);
long dim = (long)tensor->dims[d];
if (idx < 0) {
idx += dim;
}
if (idx < 0 || idx >= dim) {
free(strides);
rb_raise(rb_eArgError, "Index out of bounds");
}
index += (size_t)idx * strides[d];
}
tensor_set_value_at(tensor, index, value);
free(strides);
return Qnil;
}
// Ruby method for matrix multiplication
VALUE rb_matrix_multiply(VALUE self, VALUE other) {
Matrix *a, *b;
Data_Get_Struct(self, Matrix, a);
Data_Get_Struct(other, Matrix, b);
Matrix *result = matrix_multiply(a, b);
return Data_Wrap_Struct(rb_tensor_class, NULL, matrix_free, result);
}
// Ruby method for matrix subtraction
VALUE rb_matrix_subtract(VALUE self, VALUE other) {
Matrix *a, *b;
Data_Get_Struct(self, Matrix, a);
Data_Get_Struct(other, Matrix, b);
if (a->rows != b->rows || a->cols != b->cols || a->dtype != b->dtype) {
rb_raise(rb_eArgError, "Matrices must have the same dimensions and data types for subtraction");
}
if (a->dtype != DTYPE_FLOAT64 && a->dtype != DTYPE_FLOAT32) {
rb_raise(rb_eArgError, "subtract supports only float32/float64 matrices");
}
Matrix *result = matrix_new(a->rows, a->cols, a->dtype);
size_t num_threads = get_num_threads();
if (a->dtype == DTYPE_FLOAT64) {
#pragma omp parallel for schedule(dynamic) num_threads(num_threads)
for (size_t i = 0; i < a->rows; i++) {
for (size_t j = 0; j < a->cols; j++) {
((double *)result->data)[i * a->cols + j] =
((double *)a->data)[i * a->cols + j] -
((double *)b->data)[i * a->cols + j];
}
}
} else { // DTYPE_FLOAT32
#pragma omp parallel for schedule(dynamic) num_threads(num_threads)
for (size_t i = 0; i < a->rows; i++) {
for (size_t j = 0; j < a->cols; j++) {
((float *)result->data)[i * a->cols + j] =
((float *)a->data)[i * a->cols + j] -
((float *)b->data)[i * a->cols + j];
}
}
}
return Data_Wrap_Struct(rb_tensor_class, NULL, matrix_free, result);
}
// Ruby method for ReLU activation
VALUE rb_matrix_relu(VALUE self) {
Matrix *matrix;
Data_Get_Struct(self, Matrix, matrix);
matrix_relu(matrix);
return self;
}
// Ruby method for ReLU gradient
VALUE rb_matrix_relu_grad(VALUE self) {
Matrix *matrix;
Data_Get_Struct(self, Matrix, matrix);
Matrix *result = matrix_relu_grad(matrix);
return Data_Wrap_Struct(rb_tensor_class, NULL, matrix_free, result);
}
// Ruby method for transpose
VALUE rb_matrix_transpose(VALUE self) {
Matrix *matrix;
Data_Get_Struct(self, Matrix, matrix);
if (matrix->dtype != DTYPE_FLOAT64 && matrix->dtype != DTYPE_FLOAT32) {
rb_raise(rb_eArgError, "transpose supports only float32/float64 matrices");
}
Matrix *result = matrix_new(matrix->cols, matrix->rows, matrix->dtype);
size_t num_threads = get_num_threads();
if (matrix->dtype == DTYPE_FLOAT64) {
#pragma omp parallel for schedule(dynamic) num_threads(num_threads)
for (size_t i = 0; i < matrix->rows; i++) {
for (size_t j = 0; j < matrix->cols; j++) {
((double *)result->data)[j * result->cols + i] =
((double *)matrix->data)[i * matrix->cols + j];
}
}
} else { // DTYPE_FLOAT32
#pragma omp parallel for schedule(dynamic) num_threads(num_threads)
for (size_t i = 0; i < matrix->rows; i++) {
for (size_t j = 0; j < matrix->cols; j++) {
((float *)result->data)[j * result->cols + i] =
((float *)matrix->data)[i * matrix->cols + j];
}
}
}
return Data_Wrap_Struct(rb_tensor_class, NULL, matrix_free, result);
}
// Ruby method for Hadamard product
VALUE rb_matrix_hadamard(VALUE self, VALUE other) {
Matrix *a, *b;
Data_Get_Struct(self, Matrix, a);
Data_Get_Struct(other, Matrix, b);
if (a->rows != b->rows || a->cols != b->cols || a->dtype != b->dtype) {
rb_raise(rb_eArgError, "Matrices must have the same dimensions and data types for Hadamard product");
}
if (a->dtype != DTYPE_FLOAT64 && a->dtype != DTYPE_FLOAT32) {
rb_raise(rb_eArgError, "hadamard supports only float32/float64 matrices");
}
Matrix *result = matrix_new(a->rows, a->cols, a->dtype);
size_t num_threads = get_num_threads();
if (a->dtype == DTYPE_FLOAT64) {
#pragma omp parallel for schedule(dynamic) num_threads(num_threads)
for (size_t i = 0; i < a->rows; i++) {
for (size_t j = 0; j < a->cols; j++) {
((double *)result->data)[i * a->cols + j] =
((double *)a->data)[i * a->cols + j] *
((double *)b->data)[i * a->cols + j];
}
}
} else { // DTYPE_FLOAT32
#pragma omp parallel for schedule(dynamic) num_threads(num_threads)
for (size_t i = 0; i < a->rows; i++) {
for (size_t j = 0; j < a->cols; j++) {
((float *)result->data)[i * a->cols + j] =
((float *)a->data)[i * a->cols + j] *
((float *)b->data)[i * a->cols + j];
}
}
}
return Data_Wrap_Struct(rb_tensor_class, NULL, matrix_free, result);
}
// Ruby method for scalar multiplication
VALUE rb_matrix_scale(VALUE self, VALUE scalar) {
Matrix *matrix;
Data_Get_Struct(self, Matrix, matrix);
if (matrix->dtype != DTYPE_FLOAT64 && matrix->dtype != DTYPE_FLOAT32) {
rb_raise(rb_eArgError, "scale supports only float32/float64 matrices");
}
double s = NUM2DBL(scalar);
Matrix *result = matrix_new(matrix->rows, matrix->cols, matrix->dtype);
size_t num_threads = get_num_threads();
if (matrix->dtype == DTYPE_FLOAT64) {
#pragma omp parallel for schedule(dynamic) num_threads(num_threads)
for (size_t i = 0; i < matrix->rows; i++) {
for (size_t j = 0; j < matrix->cols; j++) {
((double *)result->data)[i * matrix->cols + j] =
((double *)matrix->data)[i * matrix->cols + j] * s;
}
}
} else { // DTYPE_FLOAT32
#pragma omp parallel for schedule(dynamic) num_threads(num_threads)
for (size_t i = 0; i < matrix->rows; i++) {
for (size_t j = 0; j < matrix->cols; j++) {
((float *)result->data)[i * matrix->cols + j] =
((float *)matrix->data)[i * matrix->cols + j] * (float)s;
}
}
}
return Data_Wrap_Struct(rb_tensor_class, NULL, matrix_free, result);
}
// Ruby method to convert matrix to a 2D array
VALUE rb_matrix_to_a(VALUE self) {
Matrix *matrix;
Data_Get_Struct(self, Matrix, matrix);
return matrix_to_a(matrix);
}
// Ruby methods for tensor metadata
VALUE rb_tensor_shape(VALUE self) {
Matrix *tensor;
Data_Get_Struct(self, Matrix, tensor);
if (tensor->rank == 0 || !tensor->dims) {
return rb_ary_new();
}
VALUE ary = rb_ary_new_capa((long)tensor->rank);
for (size_t i = 0; i < tensor->rank; i++) {
rb_ary_push(ary, SIZET2NUM(tensor->dims[i]));
}
return ary;
}
VALUE rb_tensor_rank(VALUE self) {
Matrix *tensor;
Data_Get_Struct(self, Matrix, tensor);
return SIZET2NUM(tensor->rank);
}
VALUE rb_tensor_size(VALUE self) {
Matrix *tensor;
Data_Get_Struct(self, Matrix, tensor);
return SIZET2NUM(tensor_numel(tensor));
}
// Ruby method to extract a specific row from the matrix
VALUE rb_matrix_row(VALUE self, VALUE row_index) {
Matrix *matrix;
Data_Get_Struct(self, Matrix, matrix);
size_t r = NUM2SIZET(row_index);
if (r >= matrix->rows) {
rb_raise(rb_eArgError, "Row index out of bounds");
}
VALUE row = rb_ary_new();
for (size_t j = 0; j < matrix->cols; j++) {
size_t index = r * matrix->cols + j;
if (matrix->dtype == DTYPE_FLOAT64) {
rb_ary_push(row, DBL2NUM(((double *)matrix->data)[index]));
} else if (matrix->dtype == DTYPE_FLOAT32) {
rb_ary_push(row, DBL2NUM((double)((float *)matrix->data)[index]));
} else if (matrix->dtype == DTYPE_INT16) {
rb_ary_push(row, DBL2NUM((double)((int16_t *)matrix->data)[index]));
} else if (matrix->dtype == DTYPE_INT8) {
rb_ary_push(row, DBL2NUM((double)((int8_t *)matrix->data)[index]));
} else {
rb_raise(rb_eArgError, "Unsupported data type in row");
}
}
return row;
}
// Ruby method to get the number of rows
VALUE rb_matrix_row_count(VALUE self) {
Matrix *matrix;
Data_Get_Struct(self, Matrix, matrix);
return SIZET2NUM(matrix->rows);
}
// Ruby method to get the number of columns
VALUE rb_matrix_column_count(VALUE self) {
Matrix *matrix;
Data_Get_Struct(self, Matrix, matrix);
return SIZET2NUM(matrix->cols);
}
// Create a matrix from a 2D array (Ruby Array of Arrays)
Matrix *matrix_from_arrays(VALUE arrays, DataType dtype) {
Check_Type(arrays, T_ARRAY);
size_t rows = RARRAY_LEN(arrays);
if (rows == 0) {
rb_raise(rb_eArgError, "arrays must contain at least one row");
}
VALUE first_row = rb_ary_entry(arrays, 0);
Check_Type(first_row, T_ARRAY);
size_t cols = RARRAY_LEN(first_row);
if (cols == 0) {
rb_raise(rb_eArgError, "arrays must contain at least one column");
}
if (dtype != DTYPE_FLOAT64 && dtype != DTYPE_FLOAT32) {
rb_raise(rb_eArgError, "from_arrays currently supports only float32/float64 dtypes");
}
// Allocate a new matrix with the specified data type
Matrix *matrix = matrix_new(rows, cols, dtype);
// Populate the matrix with data from the Ruby array
for (size_t i = 0; i < rows; i++) {
VALUE row = rb_ary_entry(arrays, i);
Check_Type(row, T_ARRAY);
if (RARRAY_LEN(row) != cols) {
rb_raise(rb_eArgError, "all rows must have the same length");
}
for (size_t j = 0; j < cols; j++) {
VALUE elem = rb_ary_entry(row, j);
if (dtype == DTYPE_FLOAT64) {
((double *)matrix->data)[i * cols + j] = NUM2DBL(elem);
} else { // DTYPE_FLOAT32
((float *)matrix->data)[i * cols + j] = (float)NUM2DBL(elem);
}
}
}
return matrix;
}
// Ruby class method to create a matrix from a 2D array
VALUE rb_matrix_from_arrays(int argc, VALUE *argv, VALUE klass) {
VALUE arrays, dtype;
rb_scan_args(argc, argv, "11", &arrays, &dtype); // Accept 1 required argument and 1 optional argument
// Default to FLOAT64 if dtype is not provided
DataType dt = (NIL_P(dtype)) ? DTYPE_FLOAT64 : (NUM2INT(dtype) == 32) ? DTYPE_FLOAT32 : DTYPE_FLOAT64;
// Create the matrix and wrap it in a Ruby object
Matrix *matrix = matrix_from_arrays(arrays, dt);
return Data_Wrap_Struct(klass, NULL, matrix_free, matrix);
}
// Helper to allocate a tensor with arbitrary shape
static Matrix *tensor_new_with_shape(size_t rank, const size_t *dims, DataType dtype) {
if (rank == 0) {
rb_raise(rb_eArgError, "Shape must have at least one dimension");
}
size_t total = 1;
for (size_t i = 0; i < rank; i++) {
if (dims[i] == 0) {
rb_raise(rb_eArgError, "All tensor dimensions must be greater than zero");
}
total *= dims[i];
}
Matrix *tensor = malloc(sizeof(Matrix));
if (!tensor) {
rb_raise(rb_eNoMemError, "Failed to allocate memory for tensor");
}
tensor->rank = rank;
tensor->dims = malloc(rank * sizeof(size_t));
if (!tensor->dims) {
free(tensor);
rb_raise(rb_eNoMemError, "Failed to allocate memory for tensor dimensions");
}
for (size_t i = 0; i < rank; i++) {
tensor->dims[i] = dims[i];
}
// For compatibility with 2D code, set rows/cols so that rows * cols == total elements
if (rank == 1) {
tensor->rows = dims[0];
tensor->cols = 1;
} else {
tensor->rows = dims[0];
tensor->cols = total / tensor->rows;
}
tensor->dtype = dtype;
if (dtype == DTYPE_FLOAT64) {
tensor->data = calloc(total, sizeof(double));
} else if (dtype == DTYPE_FLOAT32) {
tensor->data = calloc(total, sizeof(float));
} else if (dtype == DTYPE_INT16) {
tensor->data = calloc(total, sizeof(int16_t));
} else if (dtype == DTYPE_INT8) {
tensor->data = calloc(total, sizeof(int8_t));
} else {
free(tensor->dims);
free(tensor);
rb_raise(rb_eArgError, "Unsupported data type");
}
if (!tensor->data) {
free(tensor->dims);
free(tensor);
rb_raise(rb_eNoMemError, "Failed to allocate memory for tensor data");
}
return tensor;
}
// Infer tensor shape from a nested Ruby array
static void infer_shape(VALUE array, size_t *rank_out, size_t **dims_out) {
VALUE current = array;
size_t rank = 0;
// First pass: follow first elements to determine rank and dimensions
while (RB_TYPE_P(current, T_ARRAY)) {
long len = RARRAY_LEN(current);
if (len == 0) {
rb_raise(rb_eArgError, "All tensor dimensions must be greater than zero");
}
rank++;
current = rb_ary_entry(current, 0);
}
size_t *dims = malloc(rank * sizeof(size_t));
if (!dims) {
rb_raise(rb_eNoMemError, "Failed to allocate memory for tensor dimensions");
}
current = array;
for (size_t i = 0; i < rank; i++) {
Check_Type(current, T_ARRAY);
long len = RARRAY_LEN(current);
if (len <= 0) {
free(dims);
rb_raise(rb_eArgError, "All tensor dimensions must be greater than zero");
}
dims[i] = (size_t)len;
current = rb_ary_entry(current, 0);
}
*rank_out = rank;
*dims_out = dims;
}
// Recursive helper to fill a tensor from a nested Ruby array
static void tensor_fill_from_array(VALUE value, Matrix *tensor, size_t depth, size_t base_index, const size_t *strides) {
if (depth == tensor->rank - 1) {
Check_Type(value, T_ARRAY);
if ((size_t)RARRAY_LEN(value) != tensor->dims[depth]) {
rb_raise(rb_eArgError, "All inner arrays must have the same length");
}
for (size_t i = 0; i < tensor->dims[depth]; i++) {
VALUE elem = rb_ary_entry(value, (long)i);
size_t index = base_index + i * strides[depth];
tensor_set_value_at(tensor, index, elem);
}
} else {