-
Notifications
You must be signed in to change notification settings - Fork 169
Expand file tree
/
Copy pathh3_gpu.m
More file actions
4711 lines (4554 loc) · 230 KB
/
Copy pathh3_gpu.m
File metadata and controls
4711 lines (4554 loc) · 230 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
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
#import <MetalPerformanceShaders/MetalPerformanceShaders.h>
#import <MetalPerformanceShadersGraph/MetalPerformanceShadersGraph.h>
#include "h3_gpu.h"
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <time.h>
#include <unistd.h>
@class H3GPU;
@interface H3Tensor : NSObject
@property(nonatomic, strong) id<MTLBuffer> buffer;
@property(nonatomic) size_t elements;
@property(nonatomic) size_t bytes;
@property(nonatomic) h3_gpu_dtype dtype;
@property(nonatomic, weak) H3GPU *owner;
@property(nonatomic, strong) MPSGraphTensorData *graphData;
@property(nonatomic, strong) NSArray<NSNumber *> *graphDataShape;
@property(nonatomic) MPSDataType graphDataType;
@end
@implementation H3Tensor
@end
@interface H3SDPA : NSObject
@property(nonatomic, strong) MPSGraph *graph;
@property(nonatomic, strong) MPSGraphTensor *query;
@property(nonatomic, strong) MPSGraphTensor *key;
@property(nonatomic, strong) MPSGraphTensor *value;
@property(nonatomic, strong) MPSGraphTensor *output;
@property(nonatomic, strong) NSArray<NSNumber *> *inputShape;
@property(nonatomic, strong) NSArray<NSNumber *> *outputShape;
@end
@implementation H3SDPA
@end
@interface H3GQA : NSObject
@property(nonatomic, strong) MPSGraph *graph;
@property(nonatomic, strong) MPSGraphTensor *query;
@property(nonatomic, strong) MPSGraphTensor *key;
@property(nonatomic, strong) MPSGraphTensor *value;
@property(nonatomic, strong) MPSGraphTensor *output;
@property(nonatomic, strong) NSArray<NSNumber *> *queryShape;
@property(nonatomic, strong) NSArray<NSNumber *> *kvShape;
@end
@implementation H3GQA
@end
@interface H3Linear : NSObject
@property(nonatomic, strong) MPSGraph *graph;
@property(nonatomic, strong) MPSGraphTensor *input;
@property(nonatomic, strong) MPSGraphTensor *weight;
@property(nonatomic, strong) MPSGraphTensor *bias;
@property(nonatomic, strong) MPSGraphTensor *output;
@property(nonatomic, strong) NSArray<NSNumber *> *inputShape;
@property(nonatomic, strong) NSArray<NSNumber *> *weightShape;
@property(nonatomic, strong) NSArray<NSNumber *> *biasShape;
@property(nonatomic, strong) NSArray<NSNumber *> *outputShape;
@end
@implementation H3Linear
@end
@interface H3MLP : NSObject
@property(nonatomic, strong) MPSGraph *graph;
@property(nonatomic, strong) MPSGraphTensor *input;
@property(nonatomic, strong) MPSGraphTensor *fc1Weight;
@property(nonatomic, strong) MPSGraphTensor *fc2Weight;
@property(nonatomic, strong) MPSGraphTensor *output;
@property(nonatomic, strong) NSArray<NSNumber *> *inputShape;
@property(nonatomic, strong) NSArray<NSNumber *> *fc1Shape;
@property(nonatomic, strong) NSArray<NSNumber *> *fc2Shape;
@property(nonatomic, strong) NSArray<NSNumber *> *outputShape;
@end
@implementation H3MLP
@end
@interface H3Conv : NSObject
@property(nonatomic, strong) MPSGraph *graph;
@property(nonatomic, strong) MPSGraphTensor *input;
@property(nonatomic, strong) MPSGraphTensor *weight;
@property(nonatomic, strong) MPSGraphTensor *bias;
@property(nonatomic, strong) MPSGraphTensor *output;
@property(nonatomic, strong) NSArray<NSNumber *> *inputShape;
@property(nonatomic, strong) NSArray<NSNumber *> *weightShape;
@property(nonatomic, strong) NSArray<NSNumber *> *biasShape;
@property(nonatomic, strong) NSArray<NSNumber *> *outputShape;
@end
@implementation H3Conv
@end
@interface H3GPU : NSObject
@property(nonatomic, strong) id<MTLDevice> device;
@property(nonatomic, strong) id<MTLCommandQueue> queue;
@property(nonatomic, strong) id<MTLLibrary> library;
@property(nonatomic, strong) id<MTLCommandBuffer> command;
@property(nonatomic, strong) NSMutableArray<id<MTLCommandBuffer>> *inflightCommands;
@property(nonatomic, strong) NSDictionary<NSString *, id<MTLComputePipelineState>> *pipelines;
@property(nonatomic, strong) NSMutableDictionary<NSString *, H3SDPA *> *sdpaCache;
@property(nonatomic, strong) NSMutableDictionary<NSString *, H3GQA *> *gqaCache;
@property(nonatomic, strong) NSMutableDictionary<NSString *, H3Linear *> *linearCache;
@property(nonatomic, strong) NSMutableDictionary<NSString *, H3MLP *> *mlpCache;
@property(nonatomic, strong) NSMutableDictionary<NSString *, H3Conv *> *convCache;
@property(nonatomic, strong) MPSCommandBuffer *mpsCommand;
@property(nonatomic) BOOL reuseMPSCommandDefault;
@property(nonatomic, copy) NSString *lastError;
@property(nonatomic) h3_gpu_stats stats;
@property(nonatomic, copy) NSString *profileLabel;
@property(nonatomic) BOOL tensorOpsEnabled;
@property(nonatomic) NSUInteger tensorOpsMode;
@property(nonatomic) BOOL headMajorSDPAInputs;
@property(nonatomic) h3_gpu_stats profileStartStats;
@property(nonatomic) h3_gpu_stats profileMarkStats;
@property(nonatomic) double profileStartWall;
@property(nonatomic) double profileMarkWall;
@property(nonatomic) double commandStartWall;
@end
@implementation H3GPU
@end
static H3GPU *GPU(h3_gpu *gpu) {
return (__bridge H3GPU *)gpu;
}
static H3Tensor *TENSOR(const h3_gpu_tensor *tensor) {
return (__bridge H3Tensor *)(void *)tensor;
}
static MPSGraphTensorData *h3_gpu_graph_data(const h3_gpu_tensor *tensor,
NSArray<NSNumber *> *shape,
MPSDataType data_type,
int stable) {
H3Tensor *object = TENSOR(tensor);
if (!stable || getenv("H3_DISABLE_GRAPH_DATA_CACHE"))
return [[MPSGraphTensorData alloc] initWithMTLBuffer:object.buffer
shape:shape dataType:data_type];
if (object.graphData && object.graphDataShape == shape &&
object.graphDataType == data_type) return object.graphData;
MPSGraphTensorData *data = [[MPSGraphTensorData alloc]
initWithMTLBuffer:object.buffer shape:shape dataType:data_type];
if (!object.graphData) {
object.graphData = data;
object.graphDataShape = shape;
object.graphDataType = data_type;
}
return data;
}
static MPSCommandBuffer *h3_gpu_mps_command(H3GPU *gpu) {
const char *override = getenv("H3_REUSE_MPS_COMMAND");
BOOL reuse = override ? (*override && strcmp(override, "0")) :
gpu.reuseMPSCommandDefault;
if (!reuse)
return [MPSCommandBuffer commandBufferWithCommandBuffer:gpu.command];
if (!gpu.mpsCommand || gpu.mpsCommand.rootCommandBuffer != gpu.command)
gpu.mpsCommand =
[MPSCommandBuffer commandBufferWithCommandBuffer:gpu.command];
return gpu.mpsCommand;
}
static double h3_gpu_now(void) {
struct timespec time;
if (clock_gettime(CLOCK_MONOTONIC, &time) != 0) return 0.0;
return (double)time.tv_sec + (double)time.tv_nsec * 1e-9;
}
static int h3_gpu_profile_enabled(void) {
const char *value = getenv("H3_PROFILE");
return value && *value && strcmp(value, "0");
}
static uint64_t h3_gpu_counter_delta(uint64_t value, uint64_t start) {
return value >= start ? value - start : 0;
}
static void h3_gpu_profile_emit(H3GPU *gpu, NSString *phase,
h3_gpu_stats start, double wall_start) {
if (!h3_gpu_profile_enabled()) return;
h3_gpu_stats value = gpu.stats;
double wall = h3_gpu_now() - wall_start;
NSString *label = gpu.profileLabel ? gpu.profileLabel : @"Metal context";
fprintf(stderr,
"h3 profile: %-24s %-14s wall=%8.3fs encode=%7.3fs "
"wait=%8.3fs root-gpu=%7.3fs "
"peak=%7.3fGiB alloc=%7.3fGiB submissions=%llu "
"direct=%llu linear=%llu conv=%llu attention=%llu\n",
label.UTF8String, phase.UTF8String, wall,
value.command_encode_seconds - start.command_encode_seconds,
value.command_wait_seconds - start.command_wait_seconds,
value.gpu_seconds - start.gpu_seconds,
(double)value.peak_live_bytes / (1024.0 * 1024.0 * 1024.0),
(double)h3_gpu_counter_delta(value.allocated_bytes,
start.allocated_bytes) /
(1024.0 * 1024.0 * 1024.0),
(unsigned long long)h3_gpu_counter_delta(value.submissions,
start.submissions),
(unsigned long long)h3_gpu_counter_delta(value.direct_dispatches,
start.direct_dispatches),
(unsigned long long)h3_gpu_counter_delta(value.mps_linear_dispatches,
start.mps_linear_dispatches),
(unsigned long long)h3_gpu_counter_delta(value.mps_conv_dispatches,
start.mps_conv_dispatches),
(unsigned long long)h3_gpu_counter_delta(value.mps_sdpa_dispatches,
start.mps_sdpa_dispatches));
}
static void h3_gpu_set_error(H3GPU *gpu, NSString *format, ...) {
va_list arguments;
va_start(arguments, format);
gpu.lastError = [[NSString alloc] initWithFormat:format arguments:arguments];
va_end(arguments);
}
static int h3_gpu_require_command(H3GPU *gpu) {
if (!gpu || !gpu.command) {
if (gpu) h3_gpu_set_error(gpu, @"h3_gpu_begin() was not called");
return 0;
}
return 1;
}
static int h3_gpu_require_elements(H3GPU *gpu, const h3_gpu_tensor *tensor,
size_t elements, NSString *label) {
if (!tensor || TENSOR(tensor).elements < elements) {
h3_gpu_set_error(gpu, @"%@ tensor is absent or too small", label);
return 0;
}
return 1;
}
static id<MTLComputePipelineState> h3_gpu_pipeline(H3GPU *gpu, NSString *name) {
id<MTLComputePipelineState> pipeline = gpu.pipelines[name];
if (!pipeline) h3_gpu_set_error(gpu, @"missing Metal pipeline %@", name);
return pipeline;
}
static int h3_gpu_dispatch_1d(H3GPU *gpu, NSString *name, uint32_t count,
void (^bindings)(id<MTLComputeCommandEncoder>)) {
if (!h3_gpu_require_command(gpu)) return 0;
id<MTLComputePipelineState> pipeline = h3_gpu_pipeline(gpu, name);
if (!pipeline) return 0;
@autoreleasepool {
id<MTLComputeCommandEncoder> encoder = [gpu.command computeCommandEncoder];
[encoder setComputePipelineState:pipeline];
bindings(encoder);
NSUInteger width = MIN((NSUInteger)256, pipeline.maxTotalThreadsPerThreadgroup);
[encoder dispatchThreads:MTLSizeMake(count, 1, 1)
threadsPerThreadgroup:MTLSizeMake(width, 1, 1)];
[encoder endEncoding];
}
h3_gpu_stats stats = gpu.stats;
stats.direct_dispatches++;
gpu.stats = stats;
return 1;
}
static int h3_gpu_dispatch_2d(H3GPU *gpu, NSString *name, uint32_t width,
uint32_t height,
void (^bindings)(id<MTLComputeCommandEncoder>)) {
if (!h3_gpu_require_command(gpu)) return 0;
id<MTLComputePipelineState> pipeline = h3_gpu_pipeline(gpu, name);
if (!pipeline) return 0;
@autoreleasepool {
id<MTLComputeCommandEncoder> encoder = [gpu.command computeCommandEncoder];
[encoder setComputePipelineState:pipeline];
bindings(encoder);
NSUInteger x = 16;
NSUInteger y = MIN((NSUInteger)16, pipeline.maxTotalThreadsPerThreadgroup / x);
[encoder dispatchThreads:MTLSizeMake(width, height, 1)
threadsPerThreadgroup:MTLSizeMake(x, y, 1)];
[encoder endEncoding];
}
h3_gpu_stats stats = gpu.stats;
stats.direct_dispatches++;
gpu.stats = stats;
return 1;
}
static int h3_gpu_dispatch_3d(H3GPU *gpu, NSString *name, MTLSize grid,
void (^bindings)(id<MTLComputeCommandEncoder>)) {
if (!h3_gpu_require_command(gpu)) return 0;
id<MTLComputePipelineState> pipeline = h3_gpu_pipeline(gpu, name);
if (!pipeline) return 0;
@autoreleasepool {
id<MTLComputeCommandEncoder> encoder = [gpu.command computeCommandEncoder];
[encoder setComputePipelineState:pipeline];
bindings(encoder);
[encoder dispatchThreads:grid threadsPerThreadgroup:MTLSizeMake(8, 4, 1)];
[encoder endEncoding];
}
h3_gpu_stats stats = gpu.stats;
stats.direct_dispatches++;
gpu.stats = stats;
return 1;
}
static int h3_gpu_dispatch_rows(H3GPU *gpu, NSString *name, uint32_t rows,
void (^bindings)(id<MTLComputeCommandEncoder>)) {
if (!h3_gpu_require_command(gpu)) return 0;
id<MTLComputePipelineState> pipeline = h3_gpu_pipeline(gpu, name);
if (!pipeline) return 0;
NSUInteger maximum = MIN((NSUInteger)256,
pipeline.maxTotalThreadsPerThreadgroup);
NSUInteger threads = 1;
while (threads * 2 <= maximum) threads *= 2;
@autoreleasepool {
id<MTLComputeCommandEncoder> encoder = [gpu.command computeCommandEncoder];
[encoder setComputePipelineState:pipeline];
bindings(encoder);
[encoder dispatchThreadgroups:MTLSizeMake(rows, 1, 1)
threadsPerThreadgroup:MTLSizeMake(threads, 1, 1)];
[encoder endEncoding];
}
h3_gpu_stats stats = gpu.stats;
stats.direct_dispatches++;
gpu.stats = stats;
return 1;
}
h3_gpu *h3_gpu_create(const char *shader_source_path,
char *error, size_t error_size) {
@autoreleasepool {
H3GPU *gpu = [[H3GPU alloc] init];
gpu.profileLabel = @"Metal context";
gpu.profileStartWall = h3_gpu_now();
gpu.profileMarkWall = gpu.profileStartWall;
gpu.device = MTLCreateSystemDefaultDevice();
gpu.queue = [gpu.device newCommandQueue];
gpu.reuseMPSCommandDefault = YES;
gpu.inflightCommands = [NSMutableArray array];
gpu.sdpaCache = [NSMutableDictionary dictionary];
gpu.gqaCache = [NSMutableDictionary dictionary];
gpu.linearCache = [NSMutableDictionary dictionary];
gpu.mlpCache = [NSMutableDictionary dictionary];
gpu.convCache = [NSMutableDictionary dictionary];
if (!gpu.device || !gpu.queue) {
if (error && error_size) snprintf(error, error_size, "cannot initialize Metal");
return NULL;
}
if (getenv("H3_DEBUG_GPU_MEMORY")) {
fprintf(stderr, "h3: Metal live allocation at GPU startup: "
"%.3f GiB\n", (double)gpu.device.currentAllocatedSize /
(1024.0 * 1024.0 * 1024.0));
}
const char *source_path = shader_source_path ? shader_source_path :
"h3_shaders.metal";
NSString *path = [NSString stringWithUTF8String:source_path];
NSError *libraryError = nil;
NSString *source = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:&libraryError];
if (source) {
MTLCompileOptions *options = [[MTLCompileOptions alloc] init];
options.mathMode = MTLMathModeSafe;
const char *nax = getenv("H3_NAX");
BOOL m5 = [gpu.device.name rangeOfString:@"M5"].location !=
NSNotFound;
BOOL wantsTensorOps =
m5 && (!nax || !*nax || strcmp(nax, "0") != 0);
if (wantsTensorOps)
options.preprocessorMacros = @{ @"H3_METAL_HAS_TENSOR": @"1" };
gpu.library = [gpu.device newLibraryWithSource:source
options:options
error:&libraryError];
gpu.tensorOpsEnabled = gpu.library && wantsTensorOps;
if (gpu.tensorOpsEnabled) {
const char *mode = nax && *nax ? nax : "qkv-attn";
gpu.tensorOpsMode = !strcmp(mode, "attn") ? 2u :
!strcmp(mode, "qkv-attn") ? 3u :
!strcmp(mode, "qkv") ? 4u :
!strcmp(mode, "mlp") ? 5u : 1u;
}
if (!gpu.library && wantsTensorOps) {
/* TensorOps is optional: an older runtime must retain the
* ordinary MPSGraph/direct Metal implementation. */
if (getenv("H3_NAX_DIAGNOSTIC"))
fprintf(stderr, "h3: TensorOps compile failed: %s\n",
libraryError.localizedDescription.UTF8String);
options.preprocessorMacros = @{};
libraryError = nil;
gpu.library = [gpu.device newLibraryWithSource:source
options:options
error:&libraryError];
gpu.tensorOpsEnabled = NO;
gpu.tensorOpsMode = 0;
}
}
if (!gpu.library) {
if (error && error_size) {
const char *description = libraryError.localizedDescription.UTF8String;
snprintf(error, error_size, "cannot compile %s: %s",
source_path, description ? description : "unknown error");
}
return NULL;
}
NSMutableArray<NSString *> *names = [@[
@"h3_linear_f32", @"h3_linear_f32_tiled",
@"h3_linear_f32_tiled_bf16", @"h3_silu_f32",
@"h3_linear_f32_tiled_bf16_map",
@"h3_cast_f32_to_bf16",
@"h3_cast_bf16_to_f32",
@"h3_rms_norm_f32",
@"h3_scale_add_f32", @"h3_layer_norm_f32",
@"h3_video_qkv_rope_f32",
@"h3_adaln_f32", @"h3_gate_f32", @"h3_qkv_rope_f32",
@"h3_swiglu_f32", @"h3_linear_bf16", @"h3_silu_bf16",
@"h3_rms_norm_bf16", @"h3_adaln_bf16", @"h3_gate_bf16",
@"h3_rms_inverse_bf16", @"h3_adaln_linear_bf16",
@"h3_gate_adaln_bf16", @"h3_gate_adaln_bf16_exact_simd",
@"h3_qkv_rope_bf16", @"h3_qkv_rope_bf16_coop",
@"h3_qkv_rope_bf16_coop_uncached",
@"h3_swiglu_bf16",
@"h3_layer_norm_bf16", @"h3_gelu_bf16",
@"h3_vision_qkv_rope_bf16",
@"h3_embedding_bf16", @"h3_text_qk_rope_bf16",
@"h3_head_rms_norm_bf16", @"h3_rope_text_bf16",
@"h3_gqa_causal_bf16", @"h3_add_bf16", @"h3_sub_bf16",
@"h3_token_pool_bf16", @"h3_token_pool_adaln_bf16",
@"h3_token_expand_delta_bf16",
@"h3_token_expand_adaln_bf16",
@"h3_euler_bf16", @"h3_silu_mul_bf16",
@"h3_weight_norm_f32", @"h3_add_scaled_f32",
@"h3_alias_free_snake_f32", @"h3_snake1d_f32",
@"h3_audio_qkv_split_f32", @"h3_audio_attention_pool_f32",
@"h3_geglu_f32", @"h3_clip_f32",
@"h3_vae_encoder_pad_f32",
@"h3_vae_encoder_group_norm_silu_f32"
] mutableCopy];
if (gpu.tensorOpsEnabled) {
[names addObject:@"h3_linear_bf16_nax_r128"];
[names addObject:@"h3_linear_bf16_nax_r128_morton"];
[names addObject:@"h3_linear_bf16_nax_r128_morton4"];
[names addObject:
@"h3_qkv_project_split_bf16_nax_r128_morton4"];
[names addObject:@"h3_qk_rope_bf16_nax_inplace"];
[names addObject:@"h3_fc1_swiglu_bf16_nax_r128"];
[names addObject:@"h3_fc1_swiglu_bf16_nax_r128_morton"];
[names addObject:@"h3_fc1_swiglu_bf16_nax_r128_morton4"];
[names addObject:@"h3_quantize_bf16_int8_rows"];
[names addObject:@"h3_quantize_bf16_int8_rows_scalar"];
[names addObject:
@"h3_quantize_bf16_int8_head_major_to_rows_cached"];
[names addObject:@"h3_quantize_bf16_int8_groups"];
[names addObject:@"h3_quantize_bf16_int8_groups_scalar"];
[names addObject:@"h3_quantize_bf16_int8_groups_scalar128"];
[names addObject:
@"h3_quantize_bf16_int8_groups_scalar128_cached"];
[names addObject:
@"h3_qkv_project_split_int8_nax_r128_morton4"];
[names addObject:
@"h3_qkv_project_split_int8_rope_nax_r128_morton4"];
[names addObject:
@"h3_qkv_project_split_int8_rope_nax_r128_k5376_morton4"];
[names addObject:
@"h3_qkv_project_split_int8_rope_local_scales_nax_r128_morton4"];
[names addObject:
@"h3_qkv_project_split_int8_rope_local_scales_nax_r128_k5376_morton4"];
[names addObject:@"h3_fc1_swiglu_int8_nax_r128"];
[names addObject:@"h3_fc1_swiglu_int8_nax_r128_k5376"];
[names addObject:@"h3_fc1_swiglu_int8_nax_r128_full_k5376"];
[names addObject:@"h3_fc1_swiglu_int8_local_nax_r128"];
[names addObject:@"h3_linear_int8_nax_r128"];
[names addObject:
@"h3_linear_int8_nax_r128_full_k14336"];
[names addObject:
@"h3_linear_int8_nax_r128x256_full_k14336"];
[names addObject:@"h3_linear_int8_local_scales_nax_r128"];
[names addObject:@"h3_linear_int8_local_scales_nax_r128_k7168"];
[names addObject:@"h3_gate_adaln_quantize_int8"];
[names addObject:@"h3_gate_adaln_quantize_int8_scalar"];
[names addObject:@"h3_linear_int8_grouped_nax_r128x64"];
[names addObject:
@"h3_linear_int8_grouped_local_nax_r128x64"];
[names addObject:
@"h3_linear_int8_grouped_local_nax_r128x128"];
}
NSMutableDictionary *pipelines = [NSMutableDictionary dictionary];
for (NSString *name in names) {
id<MTLFunction> function = [gpu.library newFunctionWithName:name];
NSError *pipelineError = nil;
id<MTLComputePipelineState> pipeline =
function ? [gpu.device newComputePipelineStateWithFunction:function
error:&pipelineError] : nil;
if (!pipeline) {
if (error && error_size) {
const char *description = pipelineError.localizedDescription.UTF8String;
snprintf(error, error_size, "cannot build %s: %s", name.UTF8String,
description ? description : "function missing");
}
return NULL;
}
pipelines[name] = pipeline;
}
gpu.pipelines = pipelines;
return (__bridge_retained h3_gpu *)gpu;
}
}
void h3_gpu_free(h3_gpu *gpu) {
if (!gpu) return;
@autoreleasepool {
H3GPU *object = CFBridgingRelease(gpu);
h3_gpu_profile_emit(object, @"total", object.profileStartStats,
object.profileStartWall);
id<MTLDevice> device = object.device;
NSUInteger before = device.currentAllocatedSize;
object.command = nil;
object.inflightCommands = nil;
object.sdpaCache = nil;
object.linearCache = nil;
object.pipelines = nil;
object.library = nil;
object.queue = nil;
object.device = nil;
if (getenv("H3_DEBUG_GPU_MEMORY")) {
fprintf(stderr, "h3: Metal live allocation at GPU teardown: "
"%.3f GiB\n", (double)before /
(1024.0 * 1024.0 * 1024.0));
}
}
}
int h3_gpu_is_m5(const h3_gpu *opaque) {
if (!opaque) return 0;
H3GPU *gpu = GPU((h3_gpu *)(void *)opaque);
return [gpu.device.name rangeOfString:@"M5"].location != NSNotFound;
}
int h3_gpu_has_nax_mlp(const h3_gpu *opaque) {
if (!opaque) return 0;
H3GPU *gpu = GPU((h3_gpu *)(void *)opaque);
return gpu.tensorOpsEnabled && gpu.tensorOpsMode == 5;
}
int h3_gpu_has_int8_mlp(const h3_gpu *opaque) {
if (!opaque) return 0;
H3GPU *gpu = GPU((h3_gpu *)(void *)opaque);
return gpu.tensorOpsEnabled;
}
static h3_gpu_tensor *h3_gpu_tensor_new(h3_gpu *opaque, const void *values,
size_t elements, size_t item_size,
h3_gpu_dtype dtype) {
H3GPU *gpu = GPU(opaque);
if (!gpu || elements > SIZE_MAX / item_size) return NULL;
size_t bytes = elements * item_size;
H3Tensor *tensor = [[H3Tensor alloc] init];
tensor.elements = elements;
tensor.bytes = bytes;
tensor.dtype = dtype;
tensor.buffer = [gpu.device newBufferWithLength:MAX(bytes, (size_t)1)
options:MTLResourceStorageModeShared];
if (!tensor.buffer) {
h3_gpu_set_error(gpu, @"cannot allocate %zu-byte Metal buffer", bytes);
return NULL;
}
tensor.owner = gpu;
if (values && bytes) memcpy(tensor.buffer.contents, values, bytes);
h3_gpu_stats stats = gpu.stats;
stats.allocated_bytes += bytes;
stats.live_bytes += bytes;
if (stats.live_bytes > stats.peak_live_bytes)
stats.peak_live_bytes = stats.live_bytes;
stats.tensor_allocations++;
gpu.stats = stats;
return (__bridge_retained h3_gpu_tensor *)tensor;
}
h3_gpu_tensor *h3_gpu_tensor_new_f32(h3_gpu *gpu, size_t elements) {
return h3_gpu_tensor_new(gpu, NULL, elements, sizeof(float), H3_GPU_F32);
}
h3_gpu_tensor *h3_gpu_tensor_new_bf16(h3_gpu *gpu, size_t elements) {
return h3_gpu_tensor_new(gpu, NULL, elements, sizeof(uint16_t), H3_GPU_BF16);
}
h3_gpu_tensor *h3_gpu_tensor_new_i8(h3_gpu *gpu, size_t elements) {
return h3_gpu_tensor_new(gpu, NULL, elements, sizeof(int8_t), H3_GPU_I8);
}
h3_gpu_tensor *h3_gpu_tensor_from_f32(h3_gpu *gpu, const float *values,
size_t elements) {
return h3_gpu_tensor_new(gpu, values, elements, sizeof(float), H3_GPU_F32);
}
h3_gpu_tensor *h3_gpu_tensor_from_bf16(h3_gpu *gpu, const uint16_t *values,
size_t elements) {
return h3_gpu_tensor_new(gpu, values, elements, sizeof(uint16_t), H3_GPU_BF16);
}
h3_gpu_tensor *h3_gpu_tensor_from_u32(h3_gpu *gpu, const uint32_t *values,
size_t elements) {
return h3_gpu_tensor_new(gpu, values, elements, sizeof(uint32_t), H3_GPU_U32);
}
static h3_gpu_tensor *h3_gpu_tensor_load_file(h3_gpu *opaque, const char *path,
uint64_t file_offset,
size_t elements,
size_t item_size,
h3_gpu_dtype dtype,
const char *label) {
H3GPU *gpu = GPU(opaque);
if (!gpu || !path || !*path || file_offset > INT64_MAX ||
elements > SIZE_MAX / item_size) return NULL;
size_t bytes = elements * item_size;
if ((uint64_t)bytes > (uint64_t)INT64_MAX - file_offset) return NULL;
const char *zero_copy = getenv("H3_ZERO_COPY_WEIGHTS");
int transformer_weight = strstr(path, "/transformer/") != NULL;
int m5 = [gpu.device.name rangeOfString:@"M5"].location != NSNotFound;
int map_weight = bytes &&
((zero_copy && !strcmp(zero_copy, "1")) ||
(transformer_weight &&
((zero_copy && !strcmp(zero_copy, "transformer")) ||
(!zero_copy && m5))));
if (map_weight) {
int descriptor = open(path, O_RDONLY | O_CLOEXEC);
if (descriptor < 0) {
h3_gpu_set_error(gpu, @"cannot open %s: %s", path,
strerror(errno));
return NULL;
}
size_t page = (size_t)getpagesize();
uint64_t aligned_offset = file_offset - file_offset % page;
size_t delta = (size_t)(file_offset - aligned_offset);
if (bytes > SIZE_MAX - delta) {
close(descriptor);
return NULL;
}
size_t map_bytes = bytes + delta;
void *mapping = mmap(NULL, map_bytes, PROT_READ | PROT_WRITE,
MAP_PRIVATE, descriptor, (off_t)aligned_offset);
int map_error = errno;
close(descriptor);
if (mapping == MAP_FAILED) {
h3_gpu_set_error(gpu, @"cannot map %s payload from %s: %s", label,
path, strerror(map_error));
return NULL;
}
void *values = (unsigned char *)mapping + delta;
id<MTLBuffer> buffer = [gpu.device
newBufferWithBytesNoCopy:values length:MAX(bytes, (size_t)1)
options:MTLResourceStorageModeShared
deallocator:^(void *pointer, NSUInteger length) {
(void)pointer;
(void)length;
munmap(mapping, map_bytes);
}];
if (!buffer) {
munmap(mapping, map_bytes);
h3_gpu_set_error(gpu, @"cannot map %zu-byte Metal buffer", bytes);
return NULL;
}
H3Tensor *tensor = [[H3Tensor alloc] init];
tensor.elements = elements;
tensor.bytes = bytes;
tensor.dtype = dtype;
tensor.buffer = buffer;
tensor.owner = gpu;
h3_gpu_stats stats = gpu.stats;
stats.allocated_bytes += bytes;
stats.live_bytes += bytes;
if (stats.live_bytes > stats.peak_live_bytes)
stats.peak_live_bytes = stats.live_bytes;
stats.tensor_allocations++;
gpu.stats = stats;
return (__bridge_retained h3_gpu_tensor *)tensor;
}
h3_gpu_tensor *opaque_tensor = h3_gpu_tensor_new(
opaque, NULL, elements, item_size, dtype);
if (!opaque_tensor) return NULL;
H3Tensor *tensor = TENSOR(opaque_tensor);
int descriptor = open(path, O_RDONLY | O_CLOEXEC);
if (descriptor < 0) {
h3_gpu_set_error(gpu, @"cannot open %s: %s", path, strerror(errno));
h3_gpu_tensor_free(opaque_tensor);
return NULL;
}
size_t remaining = bytes;
size_t completed = 0;
while (remaining) {
size_t request = MIN(remaining, (size_t)SSIZE_MAX);
ssize_t count = pread(descriptor,
(unsigned char *)tensor.buffer.contents + completed,
request, (off_t)(file_offset + completed));
if (count < 0 && errno == EINTR) continue;
if (count <= 0) {
int detail = count < 0 ? errno : 0;
h3_gpu_set_error(gpu, @"cannot read %s payload from %s: %s", label,
path, detail ? strerror(detail) :
"unexpected end of file");
close(descriptor);
h3_gpu_tensor_free(opaque_tensor);
return NULL;
}
completed += (size_t)count;
remaining -= (size_t)count;
}
close(descriptor);
return opaque_tensor;
}
h3_gpu_tensor *h3_gpu_tensor_load_bf16(h3_gpu *opaque, const char *path,
uint64_t file_offset, size_t elements) {
return h3_gpu_tensor_load_file(opaque, path, file_offset, elements,
sizeof(uint16_t), H3_GPU_BF16, "BF16");
}
h3_gpu_tensor *h3_gpu_tensor_load_f32(h3_gpu *opaque, const char *path,
uint64_t file_offset, size_t elements) {
return h3_gpu_tensor_load_file(opaque, path, file_offset, elements,
sizeof(float), H3_GPU_F32, "F32");
}
static int h3_gpu_tensor_read_file_bf16_mode(
h3_gpu_tensor *opaque, const char *path,
uint64_t file_offset, size_t elements,
int uncached,
char *error, size_t error_size) {
if (error && error_size) error[0] = '\0';
if (!opaque || !path || !*path ||
TENSOR(opaque).dtype != H3_GPU_BF16 ||
elements != TENSOR(opaque).elements ||
elements > SIZE_MAX / sizeof(uint16_t) || file_offset > INT64_MAX) {
if (error && error_size)
snprintf(error, error_size, "invalid BF16 file read request");
return 0;
}
size_t bytes = elements * sizeof(uint16_t);
if ((uint64_t)bytes > (uint64_t)INT64_MAX - file_offset) {
if (error && error_size)
snprintf(error, error_size, "BF16 file read range overflows");
return 0;
}
int descriptor = open(path, O_RDONLY | O_CLOEXEC);
if (descriptor < 0) {
if (error && error_size)
snprintf(error, error_size, "cannot open %s: %s", path,
strerror(errno));
return 0;
}
#ifdef F_NOCACHE
if (uncached) (void)fcntl(descriptor, F_NOCACHE, 1);
#else
(void)uncached;
#endif
unsigned char *destination = TENSOR(opaque).buffer.contents;
size_t completed = 0;
while (completed < bytes) {
size_t request = MIN(bytes - completed, (size_t)SSIZE_MAX);
ssize_t count = pread(descriptor, destination + completed, request,
(off_t)(file_offset + completed));
if (count < 0 && errno == EINTR) continue;
if (count <= 0) {
int detail = count < 0 ? errno : 0;
if (error && error_size) {
snprintf(error, error_size, "cannot read BF16 payload from %s: %s",
path, detail ? strerror(detail) :
"unexpected end of file");
}
close(descriptor);
return 0;
}
completed += (size_t)count;
}
close(descriptor);
return 1;
}
int h3_gpu_tensor_read_file_bf16(h3_gpu_tensor *opaque, const char *path,
uint64_t file_offset, size_t elements,
char *error, size_t error_size) {
return h3_gpu_tensor_read_file_bf16_mode(
opaque, path, file_offset, elements, 0, error, error_size);
}
int h3_gpu_tensor_stream_file_bf16(h3_gpu_tensor *opaque, const char *path,
uint64_t file_offset, size_t elements,
char *error, size_t error_size) {
return h3_gpu_tensor_read_file_bf16_mode(
opaque, path, file_offset, elements, 1, error, error_size);
}
void h3_gpu_tensor_free(h3_gpu_tensor *tensor) {
if (!tensor) return;
@autoreleasepool {
H3Tensor *object = CFBridgingRelease(tensor);
H3GPU *owner = object.owner;
if (owner) {
h3_gpu_stats stats = owner.stats;
stats.live_bytes = stats.live_bytes >= object.bytes ?
stats.live_bytes - object.bytes : 0;
owner.stats = stats;
}
[object.buffer setPurgeableState:MTLPurgeableStateEmpty];
object.buffer = nil;
}
}
size_t h3_gpu_tensor_elements(const h3_gpu_tensor *tensor) {
return tensor ? TENSOR(tensor).elements : 0;
}
h3_gpu_dtype h3_gpu_tensor_dtype(const h3_gpu_tensor *tensor) {
return tensor ? TENSOR(tensor).dtype : H3_GPU_F32;
}
int h3_gpu_tensor_read_f32(const h3_gpu_tensor *tensor, float *values,
size_t elements) {
return h3_gpu_tensor_read_f32_range(tensor, 0, values, elements);
}
int h3_gpu_tensor_read_f32_range(const h3_gpu_tensor *tensor,
size_t source_offset, float *values,
size_t elements) {
if (!tensor || !values || TENSOR(tensor).dtype != H3_GPU_F32 ||
source_offset > TENSOR(tensor).elements ||
elements > TENSOR(tensor).elements - source_offset) return 0;
const unsigned char *source = TENSOR(tensor).buffer.contents;
memcpy(values, source + source_offset * sizeof(float),
elements * sizeof(float));
return 1;
}
int h3_gpu_tensor_read_bf16(const h3_gpu_tensor *tensor, uint16_t *values,
size_t elements) {
if (!tensor || !values || TENSOR(tensor).dtype != H3_GPU_BF16 ||
elements > TENSOR(tensor).elements) return 0;
memcpy(values, TENSOR(tensor).buffer.contents, elements * sizeof(uint16_t));
return 1;
}
int h3_gpu_tensor_write_f32(h3_gpu_tensor *tensor, const float *values,
size_t elements) {
return h3_gpu_tensor_write_f32_range(tensor, 0, values, elements);
}
int h3_gpu_tensor_write_f32_range(h3_gpu_tensor *tensor,
size_t destination_offset,
const float *values, size_t elements) {
if (!tensor || !values || TENSOR(tensor).dtype != H3_GPU_F32 ||
destination_offset > TENSOR(tensor).elements ||
elements > TENSOR(tensor).elements - destination_offset) return 0;
unsigned char *destination = TENSOR(tensor).buffer.contents;
memcpy(destination + destination_offset * sizeof(float), values,
elements * sizeof(float));
return 1;
}
int h3_gpu_tensor_write_bf16(h3_gpu_tensor *tensor, const uint16_t *values,
size_t elements) {
return h3_gpu_tensor_write_bf16_range(tensor, 0, values, elements);
}
int h3_gpu_tensor_write_bf16_range(h3_gpu_tensor *tensor,
size_t destination_offset,
const uint16_t *values, size_t elements) {
if (!tensor || !values || TENSOR(tensor).dtype != H3_GPU_BF16 ||
destination_offset > TENSOR(tensor).elements ||
elements > TENSOR(tensor).elements - destination_offset) return 0;
unsigned char *destination = TENSOR(tensor).buffer.contents;
memcpy(destination + destination_offset * sizeof(uint16_t), values,
elements * sizeof(uint16_t));
return 1;
}
int h3_gpu_begin(h3_gpu *opaque) {
H3GPU *gpu = GPU(opaque);
if (!gpu || gpu.command || gpu.inflightCommands.count) return 0;
gpu.lastError = nil;
@autoreleasepool {
gpu.command = [gpu.queue commandBuffer];
}
if (!gpu.command) {
h3_gpu_set_error(gpu, @"cannot create Metal command buffer");
return 0;
}
gpu.commandStartWall = h3_gpu_now();
return 1;
}
int h3_gpu_continue(h3_gpu *opaque) {
H3GPU *gpu = GPU(opaque);
if (!gpu || !gpu.command) return 0;
@autoreleasepool {
id<MTLCommandBuffer> command = gpu.command;
gpu.command = nil;
gpu.mpsCommand = nil;
double commit_time = h3_gpu_now();
[command commit];
[gpu.inflightCommands addObject:command];
h3_gpu_stats stats = gpu.stats;
stats.submissions++;
stats.command_encode_seconds += commit_time - gpu.commandStartWall;
gpu.stats = stats;
gpu.command = [gpu.queue commandBuffer];
}
if (!gpu.command) {
h3_gpu_set_error(gpu, @"cannot continue Metal command chain");
return 0;
}
gpu.commandStartWall = h3_gpu_now();
return 1;
}
int h3_gpu_submit(h3_gpu *opaque) {
H3GPU *gpu = GPU(opaque);
if (!gpu || !gpu.command) return 0;
@autoreleasepool {
id<MTLCommandBuffer> command = gpu.command;
gpu.command = nil;
gpu.mpsCommand = nil;
double commit_time = h3_gpu_now();
[command commit];
[gpu.inflightCommands addObject:command];
for (id<MTLCommandBuffer> pending in gpu.inflightCommands)
[pending waitUntilCompleted];
double complete_time = h3_gpu_now();
for (id<MTLCommandBuffer> pending in gpu.inflightCommands) {
if (pending.status == MTLCommandBufferStatusError) {
h3_gpu_set_error(gpu, @"Metal command failed: %@",
pending.error.localizedDescription);
[gpu.inflightCommands removeAllObjects];
return 0;
}
}
h3_gpu_stats stats = gpu.stats;
stats.submissions++;
stats.command_encode_seconds += commit_time - gpu.commandStartWall;
stats.command_wait_seconds += complete_time - commit_time;
for (id<MTLCommandBuffer> pending in gpu.inflightCommands) {
if (pending.GPUEndTime >= pending.GPUStartTime)
stats.gpu_seconds += pending.GPUEndTime - pending.GPUStartTime;
}
gpu.stats = stats;
[gpu.inflightCommands removeAllObjects];
}
return 1;
}
const char *h3_gpu_error(const h3_gpu *opaque) {
H3GPU *gpu = GPU((h3_gpu *)(void *)opaque);
const char *message = gpu.lastError.UTF8String;
return message ? message : "unknown Metal error";
}
int h3_gpu_get_stats(const h3_gpu *opaque, h3_gpu_stats *stats) {
if (!opaque || !stats) return 0;
*stats = GPU((h3_gpu *)(void *)opaque).stats;
return 1;
}
void h3_gpu_profile_set_label(h3_gpu *opaque, const char *label) {
H3GPU *gpu = GPU(opaque);
if (!gpu || !label || !*label) return;
gpu.profileLabel = [NSString stringWithUTF8String:label];
}
void h3_gpu_profile_mark(h3_gpu *opaque, const char *phase) {
H3GPU *gpu = GPU(opaque);
if (!gpu || !phase || !*phase || !h3_gpu_profile_enabled()) return;
h3_gpu_profile_emit(gpu, [NSString stringWithUTF8String:phase],
gpu.profileMarkStats, gpu.profileMarkWall);
gpu.profileMarkStats = gpu.stats;
gpu.profileMarkWall = h3_gpu_now();
}
typedef struct { uint32_t rows, input_dim, output_dim, has_bias; } linear_args;
typedef struct { uint32_t rows, columns; float clip; } int8_quant_args;
typedef struct {
uint32_t rows, padded_rows, heads, head_dim;
float clip;
} int8_head_major_quant_args;
typedef struct { uint32_t rows, columns, group_size, groups; }
int8_group_quant_args;
typedef struct { uint32_t rows, width; float epsilon; } norm_args;
typedef struct {
uint32_t rows, width, slots, shift_slot, scale_slot;
float epsilon;
} adaln_args;
typedef struct { uint32_t rows, width, slots, gate_slot; } gate_args;
typedef struct {
uint32_t sequence, heads, head_dim, rope_half, grouped;
float epsilon;
} qkv_args;
typedef struct { uint32_t outer, inner; } weight_norm_args;
typedef struct { uint32_t elements; float left_scale, right_scale; }
add_scaled_args;
typedef struct { uint32_t batch, length, channels; } audio_activation_args;
typedef struct { uint32_t batch, length, heads, head_dim; } audio_qkv_args;
typedef struct {
uint32_t batch, length, heads, head_dim, output_dim;
} audio_pool_args;