forked from ml-explore/mlx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgpu_core.cpp
More file actions
1724 lines (1429 loc) · 62.8 KB
/
gpu_core.cpp
File metadata and controls
1724 lines (1429 loc) · 62.8 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
// Copyright (c) 2024-2026 Lux Industries Inc.
// SPDX-License-Identifier: BSD-3-Clause-Eco
//
// Core GPU Library - Plugin-based backend management
#include "gpu_internal.h"
#include "plugin_loader.hpp"
#include <chrono>
#include <cstring>
#include <limits>
#include <memory>
#include <vector>
// =============================================================================
// Built-in CPU backend declaration
// =============================================================================
extern "C" bool cpu_backend_init(lux_gpu_backend_desc* out);
// =============================================================================
// LuxGPU Implementation (declared in gpu_internal.h)
// =============================================================================
LuxGPU::~LuxGPU() {
if (ctx && vtbl && vtbl->destroy_context) {
vtbl->destroy_context(ctx);
}
}
void LuxGPU::set_error(const char* msg) {
std::lock_guard<std::mutex> lock(mutex);
last_error = msg ? msg : "";
}
// =============================================================================
// Tensor wrapper (bridges plugin buffers to public API)
// =============================================================================
struct LuxTensor {
std::vector<int64_t> shape;
LuxDtype dtype;
std::vector<uint8_t> host_data;
LuxBackendBuffer* device_buffer = nullptr;
const lux_gpu_backend_vtbl* vtbl = nullptr;
LuxBackendContext* ctx = nullptr;
// Returns total number of elements, or -1 on overflow
int64_t size() const {
int64_t s = 1;
for (auto d : shape) {
// Check for overflow before multiplication
if (d <= 0) return 0;
if (s > std::numeric_limits<int64_t>::max() / d) {
return -1; // Overflow
}
s *= d;
}
return s;
}
// Safe size check - returns false on overflow or invalid size
bool size_valid() const {
return size() > 0;
}
size_t element_size() const {
switch (dtype) {
case LUX_FLOAT32: case LUX_INT32: case LUX_UINT32: return 4;
case LUX_FLOAT16: case LUX_BFLOAT16: return 2;
case LUX_INT64: case LUX_UINT64: return 8;
case LUX_BOOL: return 1;
default: return 0;
}
}
~LuxTensor() {
if (device_buffer && vtbl && vtbl->buffer_free && ctx) {
vtbl->buffer_free(ctx, device_buffer);
}
}
};
// =============================================================================
// Global initialization
// =============================================================================
static std::once_flag g_init_flag;
static lux_gpu_backend_desc g_cpu_backend = {};
static void global_init() {
// Initialize built-in CPU backend
cpu_backend_init(&g_cpu_backend);
// Scan for plugins in all search paths
auto& loader = lux::gpu::PluginLoader::instance();
// Try to load each backend (will search all paths)
loader.load_backend("metal");
loader.load_backend("cuda");
loader.load_backend("webgpu");
}
// =============================================================================
// C API Implementation
// =============================================================================
extern "C" {
LuxGPU* lux_gpu_create(void) {
return lux_gpu_create_with_backend(LUX_BACKEND_AUTO);
}
LuxGPU* lux_gpu_create_with_backend(LuxBackend backend) {
return lux_gpu_create_with_device(backend, 0);
}
LuxGPU* lux_gpu_create_with_device(LuxBackend backend, int device_index) {
std::call_once(g_init_flag, global_init);
auto gpu = new LuxGPU();
auto& loader = lux::gpu::PluginLoader::instance();
const lux_gpu_backend_vtbl* vtbl = nullptr;
std::string name;
if (backend == LUX_BACKEND_AUTO) {
// Try to find the best available backend
if (auto* best = loader.get_best_backend()) {
vtbl = best->desc.vtbl;
name = best->name;
}
// Fall back to CPU
if (!vtbl) {
vtbl = g_cpu_backend.vtbl;
name = "cpu";
}
} else {
// Specific backend requested
switch (backend) {
case LUX_BACKEND_CPU:
vtbl = g_cpu_backend.vtbl;
name = "cpu";
break;
case LUX_BACKEND_METAL:
if (!loader.is_available("metal")) {
loader.load_backend("metal");
}
if (auto* b = loader.get_backend("metal")) {
vtbl = b->desc.vtbl;
name = "metal";
}
break;
case LUX_BACKEND_CUDA:
if (!loader.is_available("cuda")) {
loader.load_backend("cuda");
}
if (auto* b = loader.get_backend("cuda")) {
vtbl = b->desc.vtbl;
name = "cuda";
}
break;
case LUX_BACKEND_DAWN:
if (!loader.is_available("webgpu")) {
loader.load_backend("webgpu");
}
if (auto* b = loader.get_backend("webgpu")) {
vtbl = b->desc.vtbl;
name = "webgpu";
}
break;
default:
break;
}
}
if (!vtbl) {
// Fall back to CPU
vtbl = g_cpu_backend.vtbl;
name = "cpu";
}
gpu->vtbl = vtbl;
gpu->backend_name = name;
// Create context
if (vtbl && vtbl->create_context) {
gpu->ctx = vtbl->create_context(device_index);
if (!gpu->ctx) {
gpu->set_error("Failed to create backend context");
// Fall back to CPU
gpu->vtbl = g_cpu_backend.vtbl;
gpu->backend_name = "cpu";
gpu->ctx = g_cpu_backend.vtbl->create_context(0);
}
}
return gpu;
}
void lux_gpu_destroy(LuxGPU* gpu) {
delete gpu;
}
LuxBackend lux_gpu_backend(LuxGPU* gpu) {
if (!gpu) return LUX_BACKEND_CPU;
if (gpu->backend_name == "cpu") return LUX_BACKEND_CPU;
if (gpu->backend_name == "metal") return LUX_BACKEND_METAL;
if (gpu->backend_name == "cuda") return LUX_BACKEND_CUDA;
if (gpu->backend_name == "webgpu") return LUX_BACKEND_DAWN;
return LUX_BACKEND_CPU;
}
const char* lux_gpu_backend_name(LuxGPU* gpu) {
return gpu ? gpu->backend_name.c_str() : "cpu";
}
LuxError lux_gpu_set_backend(LuxGPU* gpu, LuxBackend backend) {
if (!gpu) return LUX_ERROR_INVALID_ARGUMENT;
// Create new context for requested backend
auto* new_gpu = lux_gpu_create_with_backend(backend);
if (!new_gpu || (new_gpu->backend_name == "cpu" && backend != LUX_BACKEND_CPU && backend != LUX_BACKEND_AUTO)) {
delete new_gpu;
return LUX_ERROR_BACKEND_NOT_AVAILABLE;
}
// Swap internals
std::swap(gpu->vtbl, new_gpu->vtbl);
std::swap(gpu->ctx, new_gpu->ctx);
std::swap(gpu->backend_name, new_gpu->backend_name);
delete new_gpu;
return LUX_OK;
}
LuxError lux_gpu_device_info(LuxGPU* gpu, LuxDeviceInfo* info) {
if (!gpu || !gpu->vtbl || !info) return LUX_ERROR_INVALID_ARGUMENT;
LuxBackendDeviceInfo binfo = {};
LuxBackendError err = gpu->vtbl->get_device_info(gpu->ctx, &binfo);
if (err != LUX_BACKEND_OK) return static_cast<LuxError>(err);
info->backend = lux_gpu_backend(gpu);
info->index = 0;
info->name = binfo.name;
info->vendor = binfo.vendor;
info->memory_total = binfo.memory_total;
info->memory_available = binfo.memory_available;
info->compute_units = binfo.compute_units;
info->max_workgroup_size = binfo.max_workgroup_size;
info->is_discrete = binfo.is_discrete;
info->is_unified_memory = binfo.is_unified_memory;
return LUX_OK;
}
LuxError lux_gpu_sync(LuxGPU* gpu) {
if (!gpu || !gpu->vtbl) return LUX_ERROR_INVALID_ARGUMENT;
return static_cast<LuxError>(gpu->vtbl->sync(gpu->ctx));
}
const char* lux_gpu_error(LuxGPU* gpu) {
return gpu ? gpu->last_error.c_str() : "null gpu";
}
// Backend query
int lux_backend_count(void) {
std::call_once(g_init_flag, global_init);
return static_cast<int>(lux::gpu::PluginLoader::instance().available_backends().size());
}
bool lux_backend_available(LuxBackend backend) {
std::call_once(g_init_flag, global_init);
auto& loader = lux::gpu::PluginLoader::instance();
switch (backend) {
case LUX_BACKEND_CPU: return true;
case LUX_BACKEND_METAL: return loader.is_available("metal") || loader.load_backend("metal");
case LUX_BACKEND_CUDA: return loader.is_available("cuda") || loader.load_backend("cuda");
case LUX_BACKEND_DAWN: return loader.is_available("webgpu") || loader.load_backend("webgpu");
default: return false;
}
}
const char* lux_backend_name(LuxBackend backend) {
switch (backend) {
case LUX_BACKEND_AUTO: return "auto";
case LUX_BACKEND_CPU: return "cpu";
case LUX_BACKEND_METAL: return "metal";
case LUX_BACKEND_CUDA: return "cuda";
case LUX_BACKEND_DAWN: return "webgpu";
default: return "unknown";
}
}
int lux_device_count(LuxBackend backend) {
std::call_once(g_init_flag, global_init);
auto& loader = lux::gpu::PluginLoader::instance();
if (backend == LUX_BACKEND_CPU) {
return 1; // CPU always has one "device"
}
const char* name = nullptr;
switch (backend) {
case LUX_BACKEND_METAL: name = "metal"; break;
case LUX_BACKEND_CUDA: name = "cuda"; break;
case LUX_BACKEND_DAWN: name = "webgpu"; break;
default: return 0;
}
if (!loader.is_available(name)) {
if (!loader.load_backend(name)) {
return 0;
}
}
const auto* b = loader.get_backend(name);
if (!b || !b->desc.vtbl || !b->desc.vtbl->get_device_count) {
return 0;
}
int count = 0;
if (b->desc.vtbl->get_device_count(&count) == LUX_BACKEND_OK) {
return count;
}
return 0;
}
LuxError lux_device_info(LuxBackend backend, int index, LuxDeviceInfo* info) {
if (!info) return LUX_ERROR_INVALID_ARGUMENT;
std::call_once(g_init_flag, global_init);
auto& loader = lux::gpu::PluginLoader::instance();
if (backend == LUX_BACKEND_CPU) {
// CPU backend info
info->backend = LUX_BACKEND_CPU;
info->index = 0;
info->name = "CPU";
info->vendor = "Host";
info->memory_total = 0;
info->memory_available = 0;
info->is_discrete = false;
info->is_unified_memory = true;
info->compute_units = 1;
info->max_workgroup_size = 1;
return LUX_OK;
}
const char* name = nullptr;
switch (backend) {
case LUX_BACKEND_METAL: name = "metal"; break;
case LUX_BACKEND_CUDA: name = "cuda"; break;
case LUX_BACKEND_DAWN: name = "webgpu"; break;
default: return LUX_ERROR_BACKEND_NOT_AVAILABLE;
}
if (!loader.is_available(name)) {
if (!loader.load_backend(name)) {
return LUX_ERROR_BACKEND_NOT_AVAILABLE;
}
}
const auto* b = loader.get_backend(name);
if (!b || !b->desc.vtbl) {
return LUX_ERROR_BACKEND_NOT_AVAILABLE;
}
// Create temporary context for device info query
// NOTE: The returned name/vendor pointers must be static strings in the backend.
// Backend implementations must not return pointers to context-owned memory.
if (!b->desc.vtbl->create_context) {
return LUX_ERROR_NOT_SUPPORTED;
}
LuxBackendContext* ctx = b->desc.vtbl->create_context(index);
if (!ctx) {
return LUX_ERROR_DEVICE_NOT_FOUND;
}
LuxBackendDeviceInfo binfo = {};
LuxBackendError err = LUX_BACKEND_OK;
if (b->desc.vtbl->get_device_info) {
err = b->desc.vtbl->get_device_info(ctx, &binfo);
}
// Copy string data before destroying context (in case backend returns
// context-owned strings - backends should return static strings per contract)
const char* saved_name = binfo.name;
const char* saved_vendor = binfo.vendor;
if (b->desc.vtbl->destroy_context) {
b->desc.vtbl->destroy_context(ctx);
}
if (err != LUX_BACKEND_OK) {
return static_cast<LuxError>(err);
}
info->backend = backend;
info->index = index;
info->name = saved_name;
info->vendor = saved_vendor;
info->memory_total = binfo.memory_total;
info->memory_available = binfo.memory_available;
info->compute_units = binfo.compute_units;
info->max_workgroup_size = binfo.max_workgroup_size;
info->is_discrete = binfo.is_discrete;
info->is_unified_memory = binfo.is_unified_memory;
return LUX_OK;
}
// =============================================================================
// Tensor Operations
// =============================================================================
LuxTensor* lux_tensor_zeros(LuxGPU* gpu, const int64_t* shape, int ndim, LuxDtype dtype) {
if (!gpu || !gpu->vtbl || !shape || ndim <= 0) return nullptr;
auto t = new LuxTensor();
t->shape.assign(shape, shape + ndim);
t->dtype = dtype;
t->vtbl = gpu->vtbl;
t->ctx = gpu->ctx;
// Check for size overflow
int64_t total = t->size();
if (total <= 0) {
delete t;
return nullptr;
}
size_t elem_size = t->element_size();
// Check for byte count overflow
if (static_cast<uint64_t>(total) > std::numeric_limits<size_t>::max() / elem_size) {
delete t;
return nullptr;
}
size_t bytes = static_cast<size_t>(total) * elem_size;
t->host_data.resize(bytes, 0);
if (gpu->vtbl->buffer_alloc_with_data) {
t->device_buffer = gpu->vtbl->buffer_alloc_with_data(gpu->ctx, t->host_data.data(), bytes);
} else if (gpu->vtbl->buffer_alloc) {
t->device_buffer = gpu->vtbl->buffer_alloc(gpu->ctx, bytes);
}
return t;
}
LuxTensor* lux_tensor_ones(LuxGPU* gpu, const int64_t* shape, int ndim, LuxDtype dtype) {
return lux_tensor_full(gpu, shape, ndim, dtype, 1.0);
}
LuxTensor* lux_tensor_full(LuxGPU* gpu, const int64_t* shape, int ndim, LuxDtype dtype, double value) {
if (!gpu || !gpu->vtbl || !shape || ndim <= 0) return nullptr;
auto t = new LuxTensor();
t->shape.assign(shape, shape + ndim);
t->dtype = dtype;
t->vtbl = gpu->vtbl;
t->ctx = gpu->ctx;
// Check for size overflow
int64_t total = t->size();
if (total <= 0) {
delete t;
return nullptr;
}
size_t elem_size = t->element_size();
if (static_cast<uint64_t>(total) > std::numeric_limits<size_t>::max() / elem_size) {
delete t;
return nullptr;
}
size_t bytes = static_cast<size_t>(total) * elem_size;
t->host_data.resize(bytes);
// Fill host data
if (dtype == LUX_FLOAT32) {
float v = static_cast<float>(value);
float* ptr = reinterpret_cast<float*>(t->host_data.data());
for (int64_t i = 0; i < t->size(); i++) ptr[i] = v;
}
// Copy to device
if (gpu->vtbl->buffer_alloc_with_data) {
t->device_buffer = gpu->vtbl->buffer_alloc_with_data(gpu->ctx, t->host_data.data(), bytes);
}
return t;
}
LuxTensor* lux_tensor_from_data(LuxGPU* gpu, const void* data, const int64_t* shape, int ndim, LuxDtype dtype) {
if (!gpu || !gpu->vtbl || !data || !shape || ndim <= 0) return nullptr;
auto t = new LuxTensor();
t->shape.assign(shape, shape + ndim);
t->dtype = dtype;
t->vtbl = gpu->vtbl;
t->ctx = gpu->ctx;
// Check for size overflow
int64_t total = t->size();
if (total <= 0) {
delete t;
return nullptr;
}
size_t elem_size = t->element_size();
if (static_cast<uint64_t>(total) > std::numeric_limits<size_t>::max() / elem_size) {
delete t;
return nullptr;
}
size_t bytes = static_cast<size_t>(total) * elem_size;
t->host_data.resize(bytes);
std::memcpy(t->host_data.data(), data, bytes);
if (gpu->vtbl->buffer_alloc_with_data) {
t->device_buffer = gpu->vtbl->buffer_alloc_with_data(gpu->ctx, data, bytes);
}
return t;
}
void lux_tensor_destroy(LuxTensor* tensor) {
delete tensor;
}
int lux_tensor_ndim(LuxTensor* tensor) {
return tensor ? static_cast<int>(tensor->shape.size()) : 0;
}
int64_t lux_tensor_shape(LuxTensor* tensor, int dim) {
return (tensor && dim >= 0 && dim < static_cast<int>(tensor->shape.size()))
? tensor->shape[dim] : 0;
}
int64_t lux_tensor_size(LuxTensor* tensor) {
return tensor ? tensor->size() : 0;
}
LuxDtype lux_tensor_dtype(LuxTensor* tensor) {
return tensor ? tensor->dtype : LUX_FLOAT32;
}
LuxError lux_tensor_to_host(LuxTensor* tensor, void* data, size_t size) {
if (!tensor || !data) return LUX_ERROR_INVALID_ARGUMENT;
size_t bytes = tensor->size() * tensor->element_size();
if (size < bytes) return LUX_ERROR_INVALID_ARGUMENT;
// If we have device buffer, sync from it
if (tensor->device_buffer && tensor->vtbl && tensor->vtbl->buffer_copy_to_host) {
LuxBackendError err = tensor->vtbl->buffer_copy_to_host(
tensor->ctx, tensor->device_buffer, data, bytes
);
return static_cast<LuxError>(err);
}
// Otherwise copy from host data
std::memcpy(data, tensor->host_data.data(), bytes);
return LUX_OK;
}
// Binary operations helper
static LuxTensor* binary_op(LuxGPU* gpu, LuxTensor* a, LuxTensor* b,
LuxBackendError (*op)(LuxBackendContext*, LuxBackendBuffer*, LuxBackendBuffer*, LuxBackendBuffer*, size_t)) {
if (!gpu || !a || !b || a->shape != b->shape) return nullptr;
auto out = lux_tensor_zeros(gpu, a->shape.data(), static_cast<int>(a->shape.size()), a->dtype);
if (!out) return nullptr;
if (op && a->device_buffer && b->device_buffer && out->device_buffer) {
LuxBackendError err = op(gpu->ctx, a->device_buffer, b->device_buffer, out->device_buffer, a->size());
if (err != LUX_BACKEND_OK) {
delete out;
return nullptr;
}
}
return out;
}
LuxTensor* lux_tensor_add(LuxGPU* gpu, LuxTensor* a, LuxTensor* b) {
if (!gpu || !gpu->vtbl) return nullptr;
return binary_op(gpu, a, b, gpu->vtbl->op_add_f32);
}
LuxTensor* lux_tensor_sub(LuxGPU* gpu, LuxTensor* a, LuxTensor* b) {
if (!gpu || !gpu->vtbl) return nullptr;
return binary_op(gpu, a, b, gpu->vtbl->op_sub_f32);
}
LuxTensor* lux_tensor_mul(LuxGPU* gpu, LuxTensor* a, LuxTensor* b) {
if (!gpu || !gpu->vtbl) return nullptr;
return binary_op(gpu, a, b, gpu->vtbl->op_mul_f32);
}
LuxTensor* lux_tensor_div(LuxGPU* gpu, LuxTensor* a, LuxTensor* b) {
if (!gpu || !gpu->vtbl || !gpu->vtbl->op_div_f32) return nullptr;
return binary_op(gpu, a, b, gpu->vtbl->op_div_f32);
}
LuxTensor* lux_tensor_matmul(LuxGPU* gpu, LuxTensor* a, LuxTensor* b) {
if (!gpu || !gpu->vtbl || !a || !b) return nullptr;
if (a->shape.size() != 2 || b->shape.size() != 2) return nullptr;
if (a->shape[1] != b->shape[0]) return nullptr;
int M = static_cast<int>(a->shape[0]);
int K = static_cast<int>(a->shape[1]);
int N = static_cast<int>(b->shape[1]);
int64_t out_shape[2] = {M, N};
auto out = lux_tensor_zeros(gpu, out_shape, 2, a->dtype);
if (!out) return nullptr;
if (gpu->vtbl->op_matmul_f32 && a->device_buffer && b->device_buffer && out->device_buffer) {
LuxBackendError err = gpu->vtbl->op_matmul_f32(
gpu->ctx, a->device_buffer, b->device_buffer, out->device_buffer, M, K, N
);
if (err != LUX_BACKEND_OK) {
delete out;
return nullptr;
}
}
return out;
}
// =============================================================================
// Unary operations helper
// =============================================================================
static LuxTensor* unary_op(LuxGPU* gpu, LuxTensor* t,
LuxBackendError (*op)(LuxBackendContext*, LuxBackendBuffer*, LuxBackendBuffer*, size_t)) {
if (!gpu || !gpu->vtbl || !t || !op) return nullptr;
auto out = lux_tensor_zeros(gpu, t->shape.data(), static_cast<int>(t->shape.size()), t->dtype);
if (!out) return nullptr;
if (t->device_buffer && out->device_buffer) {
LuxBackendError err = op(gpu->ctx, t->device_buffer, out->device_buffer, t->size());
if (err != LUX_BACKEND_OK) {
delete out;
return nullptr;
}
}
return out;
}
LuxTensor* lux_tensor_neg(LuxGPU* gpu, LuxTensor* t) {
if (!gpu || !gpu->vtbl || !gpu->vtbl->op_neg_f32) return nullptr;
return unary_op(gpu, t, gpu->vtbl->op_neg_f32);
}
LuxTensor* lux_tensor_exp(LuxGPU* gpu, LuxTensor* t) {
if (!gpu || !gpu->vtbl || !gpu->vtbl->op_exp_f32) return nullptr;
return unary_op(gpu, t, gpu->vtbl->op_exp_f32);
}
LuxTensor* lux_tensor_log(LuxGPU* gpu, LuxTensor* t) {
if (!gpu || !gpu->vtbl || !gpu->vtbl->op_log_f32) return nullptr;
return unary_op(gpu, t, gpu->vtbl->op_log_f32);
}
LuxTensor* lux_tensor_sqrt(LuxGPU* gpu, LuxTensor* t) {
if (!gpu || !gpu->vtbl || !gpu->vtbl->op_sqrt_f32) return nullptr;
return unary_op(gpu, t, gpu->vtbl->op_sqrt_f32);
}
LuxTensor* lux_tensor_abs(LuxGPU* gpu, LuxTensor* t) {
if (!gpu || !gpu->vtbl || !gpu->vtbl->op_abs_f32) return nullptr;
return unary_op(gpu, t, gpu->vtbl->op_abs_f32);
}
LuxTensor* lux_tensor_tanh(LuxGPU* gpu, LuxTensor* t) {
if (!gpu || !gpu->vtbl || !gpu->vtbl->op_tanh_f32) return nullptr;
return unary_op(gpu, t, gpu->vtbl->op_tanh_f32);
}
LuxTensor* lux_tensor_sigmoid(LuxGPU* gpu, LuxTensor* t) {
if (!gpu || !gpu->vtbl || !gpu->vtbl->op_sigmoid_f32) return nullptr;
return unary_op(gpu, t, gpu->vtbl->op_sigmoid_f32);
}
LuxTensor* lux_tensor_relu(LuxGPU* gpu, LuxTensor* t) {
if (!gpu || !gpu->vtbl || !gpu->vtbl->op_relu_f32) return nullptr;
return unary_op(gpu, t, gpu->vtbl->op_relu_f32);
}
LuxTensor* lux_tensor_gelu(LuxGPU* gpu, LuxTensor* t) {
if (!gpu || !gpu->vtbl || !gpu->vtbl->op_gelu_f32) return nullptr;
return unary_op(gpu, t, gpu->vtbl->op_gelu_f32);
}
// =============================================================================
// Scalar reductions
// =============================================================================
float lux_tensor_reduce_sum(LuxGPU* gpu, LuxTensor* t) {
if (!gpu || !gpu->vtbl || !t || !gpu->vtbl->op_reduce_sum_f32) return 0.0f;
int64_t one = 1;
auto out = lux_tensor_zeros(gpu, &one, 1, LUX_FLOAT32);
if (!out) return 0.0f;
if (t->device_buffer && out->device_buffer) {
gpu->vtbl->op_reduce_sum_f32(gpu->ctx, t->device_buffer, out->device_buffer, t->size());
}
float result = 0.0f;
lux_tensor_to_host(out, &result, sizeof(float));
lux_tensor_destroy(out);
return result;
}
float lux_tensor_reduce_max(LuxGPU* gpu, LuxTensor* t) {
if (!gpu || !gpu->vtbl || !t || !gpu->vtbl->op_reduce_max_f32) return 0.0f;
int64_t one = 1;
auto out = lux_tensor_zeros(gpu, &one, 1, LUX_FLOAT32);
if (!out) return 0.0f;
if (t->device_buffer && out->device_buffer) {
gpu->vtbl->op_reduce_max_f32(gpu->ctx, t->device_buffer, out->device_buffer, t->size());
}
float result = 0.0f;
lux_tensor_to_host(out, &result, sizeof(float));
lux_tensor_destroy(out);
return result;
}
float lux_tensor_reduce_min(LuxGPU* gpu, LuxTensor* t) {
if (!gpu || !gpu->vtbl || !t || !gpu->vtbl->op_reduce_min_f32) return 0.0f;
int64_t one = 1;
auto out = lux_tensor_zeros(gpu, &one, 1, LUX_FLOAT32);
if (!out) return 0.0f;
if (t->device_buffer && out->device_buffer) {
gpu->vtbl->op_reduce_min_f32(gpu->ctx, t->device_buffer, out->device_buffer, t->size());
}
float result = 0.0f;
lux_tensor_to_host(out, &result, sizeof(float));
lux_tensor_destroy(out);
return result;
}
float lux_tensor_reduce_mean(LuxGPU* gpu, LuxTensor* t) {
if (!gpu || !gpu->vtbl || !t || !gpu->vtbl->op_reduce_mean_f32) return 0.0f;
int64_t one = 1;
auto out = lux_tensor_zeros(gpu, &one, 1, LUX_FLOAT32);
if (!out) return 0.0f;
if (t->device_buffer && out->device_buffer) {
gpu->vtbl->op_reduce_mean_f32(gpu->ctx, t->device_buffer, out->device_buffer, t->size());
}
float result = 0.0f;
lux_tensor_to_host(out, &result, sizeof(float));
lux_tensor_destroy(out);
return result;
}
// =============================================================================
// Axis Reduction Helpers
// =============================================================================
// Compute output shape after reducing along specified axes
static std::vector<int64_t> compute_reduced_shape(const std::vector<int64_t>& shape, const int* axes, int naxes) {
std::vector<bool> reduce_axis(shape.size(), false);
for (int i = 0; i < naxes; i++) {
int ax = axes[i];
if (ax < 0) ax += static_cast<int>(shape.size());
if (ax >= 0 && ax < static_cast<int>(shape.size())) {
reduce_axis[ax] = true;
}
}
std::vector<int64_t> out_shape;
for (size_t i = 0; i < shape.size(); i++) {
if (!reduce_axis[i]) {
out_shape.push_back(shape[i]);
}
}
if (out_shape.empty()) {
out_shape.push_back(1); // Scalar result
}
return out_shape;
}
// Compute outer_size and inner_size for contiguous last-axis reduction
// Returns true if reduction can be expressed as (outer_size, inner_size) -> outer_size
static bool can_use_axis_reduction(const std::vector<int64_t>& shape, const int* axes, int naxes,
size_t* outer_size, size_t* inner_size) {
if (naxes != 1 || shape.empty()) return false;
int ax = axes[0];
if (ax < 0) ax += static_cast<int>(shape.size());
if (ax < 0 || ax >= static_cast<int>(shape.size())) return false;
// Only support reduction along last axis for backend dispatch
if (ax != static_cast<int>(shape.size()) - 1) return false;
*inner_size = static_cast<size_t>(shape.back());
*outer_size = 1;
for (size_t i = 0; i < shape.size() - 1; i++) {
*outer_size *= static_cast<size_t>(shape[i]);
}
return true;
}
// CPU fallback for sum reduction along axes
static void cpu_reduce_sum_axes(const float* in, float* out, const std::vector<int64_t>& shape,
const int* axes, int naxes, const std::vector<int64_t>& out_shape) {
std::vector<bool> reduce_axis(shape.size(), false);
for (int i = 0; i < naxes; i++) {
int ax = axes[i];
if (ax < 0) ax += static_cast<int>(shape.size());
if (ax >= 0 && ax < static_cast<int>(shape.size())) {
reduce_axis[ax] = true;
}
}
// Compute strides for input
std::vector<size_t> strides(shape.size());
size_t stride = 1;
for (int i = static_cast<int>(shape.size()) - 1; i >= 0; i--) {
strides[i] = stride;
stride *= static_cast<size_t>(shape[i]);
}
// Compute output size
size_t out_size = 1;
for (auto d : out_shape) out_size *= static_cast<size_t>(d);
std::memset(out, 0, out_size * sizeof(float));
// Iterate over input and accumulate
size_t in_size = stride;
for (size_t idx = 0; idx < in_size; idx++) {
// Decompose linear index into multi-index
size_t tmp = idx;
size_t out_idx = 0;
size_t out_stride = 1;
for (int d = static_cast<int>(shape.size()) - 1; d >= 0; d--) {
size_t coord = tmp % static_cast<size_t>(shape[d]);
tmp /= static_cast<size_t>(shape[d]);
if (!reduce_axis[d]) {
// Find position in output
int out_d = 0;
for (int k = 0; k < d; k++) {
if (!reduce_axis[k]) out_d++;
}
// Compute contribution to out_idx
size_t os = 1;
for (size_t k = out_d + 1; k < out_shape.size(); k++) {
os *= static_cast<size_t>(out_shape[k]);
}
out_idx += coord * os;
}
}
out[out_idx] += in[idx];
}
}
// CPU fallback for max reduction along axes
static void cpu_reduce_max_axes(const float* in, float* out, const std::vector<int64_t>& shape,
const int* axes, int naxes, const std::vector<int64_t>& out_shape) {
std::vector<bool> reduce_axis(shape.size(), false);
for (int i = 0; i < naxes; i++) {
int ax = axes[i];
if (ax < 0) ax += static_cast<int>(shape.size());
if (ax >= 0 && ax < static_cast<int>(shape.size())) {
reduce_axis[ax] = true;
}
}
std::vector<size_t> strides(shape.size());
size_t stride = 1;
for (int i = static_cast<int>(shape.size()) - 1; i >= 0; i--) {
strides[i] = stride;
stride *= static_cast<size_t>(shape[i]);
}
size_t out_size = 1;
for (auto d : out_shape) out_size *= static_cast<size_t>(d);
// Initialize with -inf
for (size_t i = 0; i < out_size; i++) {
out[i] = -std::numeric_limits<float>::infinity();
}
size_t in_size = stride;
for (size_t idx = 0; idx < in_size; idx++) {
size_t tmp = idx;
size_t out_idx = 0;
for (int d = static_cast<int>(shape.size()) - 1; d >= 0; d--) {
size_t coord = tmp % static_cast<size_t>(shape[d]);
tmp /= static_cast<size_t>(shape[d]);
if (!reduce_axis[d]) {
int out_d = 0;
for (int k = 0; k < d; k++) {
if (!reduce_axis[k]) out_d++;
}
size_t os = 1;
for (size_t k = out_d + 1; k < out_shape.size(); k++) {
os *= static_cast<size_t>(out_shape[k]);
}
out_idx += coord * os;
}
}
if (in[idx] > out[out_idx]) {
out[out_idx] = in[idx];
}
}
}
// CPU fallback for min reduction along axes
static void cpu_reduce_min_axes(const float* in, float* out, const std::vector<int64_t>& shape,
const int* axes, int naxes, const std::vector<int64_t>& out_shape) {
std::vector<bool> reduce_axis(shape.size(), false);
for (int i = 0; i < naxes; i++) {
int ax = axes[i];
if (ax < 0) ax += static_cast<int>(shape.size());
if (ax >= 0 && ax < static_cast<int>(shape.size())) {
reduce_axis[ax] = true;
}
}
std::vector<size_t> strides(shape.size());
size_t stride = 1;
for (int i = static_cast<int>(shape.size()) - 1; i >= 0; i--) {
strides[i] = stride;
stride *= static_cast<size_t>(shape[i]);
}
size_t out_size = 1;
for (auto d : out_shape) out_size *= static_cast<size_t>(d);
for (size_t i = 0; i < out_size; i++) {
out[i] = std::numeric_limits<float>::infinity();
}
size_t in_size = stride;
for (size_t idx = 0; idx < in_size; idx++) {
size_t tmp = idx;
size_t out_idx = 0;
for (int d = static_cast<int>(shape.size()) - 1; d >= 0; d--) {
size_t coord = tmp % static_cast<size_t>(shape[d]);
tmp /= static_cast<size_t>(shape[d]);
if (!reduce_axis[d]) {
int out_d = 0;
for (int k = 0; k < d; k++) {
if (!reduce_axis[k]) out_d++;
}
size_t os = 1;
for (size_t k = out_d + 1; k < out_shape.size(); k++) {
os *= static_cast<size_t>(out_shape[k]);
}
out_idx += coord * os;
}
}
if (in[idx] < out[out_idx]) {
out[out_idx] = in[idx];
}
}
}
// =============================================================================
// Axis Reduction API
// =============================================================================
LuxTensor* lux_tensor_sum(LuxGPU* gpu, LuxTensor* t, const int* axes, int naxes) {
if (!gpu || !gpu->vtbl || !t) return nullptr;
// Global reduction: axes=null && naxes=0
if (axes == nullptr || naxes <= 0) {
// Return scalar with global sum
float sum = lux_tensor_reduce_sum(gpu, t);
int64_t one = 1;
auto out = lux_tensor_zeros(gpu, &one, 1, t->dtype);
if (!out) return nullptr;
// Set the scalar value
float* data = ∑
out->host_data.resize(sizeof(float));
std::memcpy(out->host_data.data(), data, sizeof(float));
if (out->device_buffer && gpu->vtbl->buffer_copy_from_host) {
gpu->vtbl->buffer_copy_from_host(gpu->ctx, out->device_buffer, data, sizeof(float));