Brunobkr commited on
Commit
d48d2ff
·
verified ·
1 Parent(s): 2d7ac98

Upload folder using huggingface_hub (part 5)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ggml/src/ggml-metal/ggml-metal-common.h +52 -0
  2. ggml/src/ggml-metal/ggml-metal-context.h +41 -0
  3. ggml/src/ggml-metal/ggml-metal-context.m +739 -0
  4. ggml/src/ggml-metal/ggml-metal-device.cpp +2227 -0
  5. ggml/src/ggml-metal/ggml-metal-device.h +330 -0
  6. ggml/src/ggml-metal/ggml-metal-device.m +2028 -0
  7. ggml/src/ggml-metal/ggml-metal-impl.h +1296 -0
  8. ggml/src/ggml-metal/ggml-metal-ops.cpp +0 -0
  9. ggml/src/ggml-metal/ggml-metal-ops.h +104 -0
  10. ggml/src/ggml-metal/ggml-metal.cpp +950 -0
  11. ggml/src/ggml-metal/ggml-metal.metal +0 -0
  12. ggml/src/ggml-musa/CMakeLists.txt +124 -0
  13. ggml/src/ggml-musa/mudnn.cu +112 -0
  14. ggml/src/ggml-musa/mudnn.cuh +12 -0
  15. ggml/src/ggml-opencl/CMakeLists.txt +238 -0
  16. ggml/src/ggml-opencl/cl-program-cache.cpp +453 -0
  17. ggml/src/ggml-opencl/cl-program-cache.h +75 -0
  18. ggml/src/ggml-opencl/fa_tune.h +92 -0
  19. ggml/src/ggml-opencl/ggml-opencl.cpp +0 -0
  20. ggml/src/ggml-opencl/kernels/abs.cl +113 -0
  21. ggml/src/ggml-opencl/kernels/add.cl +190 -0
  22. ggml/src/ggml-opencl/kernels/add_id.cl +42 -0
  23. ggml/src/ggml-opencl/kernels/argsort.cl +86 -0
  24. ggml/src/ggml-opencl/kernels/clamp.cl +20 -0
  25. ggml/src/ggml-opencl/kernels/concat.cl +118 -0
  26. ggml/src/ggml-opencl/kernels/conv2d.cl +185 -0
  27. ggml/src/ggml-opencl/kernels/conv2d_f16_f32.cl +176 -0
  28. ggml/src/ggml-opencl/kernels/cpy.cl +288 -0
  29. ggml/src/ggml-opencl/kernels/cumsum.cl +139 -0
  30. ggml/src/ggml-opencl/kernels/cvt.cl +2492 -0
  31. ggml/src/ggml-opencl/kernels/diag.cl +27 -0
  32. ggml/src/ggml-opencl/kernels/diag_mask_inf.cl +58 -0
  33. ggml/src/ggml-opencl/kernels/div.cl +138 -0
  34. ggml/src/ggml-opencl/kernels/embed_kernel.py +26 -0
  35. ggml/src/ggml-opencl/kernels/exp.cl +125 -0
  36. ggml/src/ggml-opencl/kernels/expm1.cl +113 -0
  37. ggml/src/ggml-opencl/kernels/fill.cl +17 -0
  38. ggml/src/ggml-opencl/kernels/flash_attn_f16.cl +410 -0
  39. ggml/src/ggml-opencl/kernels/flash_attn_f32.cl +420 -0
  40. ggml/src/ggml-opencl/kernels/flash_attn_f32_f16.cl +0 -0
  41. ggml/src/ggml-opencl/kernels/flash_attn_f32_q4_0.cl +2011 -0
  42. ggml/src/ggml-opencl/kernels/flash_attn_f32_q8_0.cl +1840 -0
  43. ggml/src/ggml-opencl/kernels/flash_attn_pre_f16.cl +156 -0
  44. ggml/src/ggml-opencl/kernels/gated_delta_net.cl +249 -0
  45. ggml/src/ggml-opencl/kernels/gelu.cl +89 -0
  46. ggml/src/ggml-opencl/kernels/gemm_moe_mxfp4_f32.cl +162 -0
  47. ggml/src/ggml-opencl/kernels/gemm_moe_mxfp4_f32_ns.cl +376 -0
  48. ggml/src/ggml-opencl/kernels/gemm_moe_mxfp4_q8_1_dp4a.cl +190 -0
  49. ggml/src/ggml-opencl/kernels/gemm_moe_q4_0_f32_ns.cl +324 -0
  50. ggml/src/ggml-opencl/kernels/gemm_moe_q4_0_q8_1_dp4a.cl +169 -0
ggml/src/ggml-metal/ggml-metal-common.h ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // helper functions for ggml-metal that are too difficult to implement in Objective-C
2
+
3
+ #pragma once
4
+
5
+ #include <stdbool.h>
6
+
7
+ #ifdef __cplusplus
8
+ extern "C" {
9
+ #endif
10
+
11
+ struct ggml_tensor;
12
+ struct ggml_cgraph;
13
+
14
+ enum ggml_mem_range_type {
15
+ MEM_RANGE_TYPE_SRC = 0,
16
+ MEM_RANGE_TYPE_DST = 1,
17
+ };
18
+
19
+ // a helper object that can be used for reordering operations to improve concurrency
20
+ //
21
+ // the fundamental idea is that a set of tasks (either ggml ops, or something else) can run concurrently if they
22
+ // don't write to a memory that is being read by another task or written to by another task in the set
23
+ //
24
+ // with this structure, we can add tasks to the set, setting memory constraints. we can also check if a new task
25
+ // can be added to the set without violating the constraints (i.e. if it can be executed concurrently with the
26
+ // tasks already in the set)
27
+ //
28
+ typedef struct ggml_mem_ranges * ggml_mem_ranges_t;
29
+
30
+ ggml_mem_ranges_t ggml_mem_ranges_init(int debug);
31
+ void ggml_mem_ranges_free(ggml_mem_ranges_t mrs);
32
+
33
+ // remove all ranges from the set
34
+ void ggml_mem_ranges_reset(ggml_mem_ranges_t mrs);
35
+
36
+ // add src or dst ranges to track
37
+ bool ggml_mem_ranges_add(ggml_mem_ranges_t mrs, const struct ggml_tensor * tensor);
38
+
39
+ // return false if:
40
+ // - new src range overlaps with any existing dst range
41
+ // - new dst range overlaps with any existing range (src or dst)
42
+ bool ggml_mem_ranges_check(ggml_mem_ranges_t mrs, const struct ggml_tensor * tensor);
43
+
44
+ // reorder the nodes in the graph to improve concurrency, while respecting fusion
45
+ //
46
+ // note: this implementation is generic and not specific to metal
47
+ // if it proves to work well, we can start using it for other backends in the future
48
+ void ggml_graph_optimize(struct ggml_cgraph * gf);
49
+
50
+ #ifdef __cplusplus
51
+ }
52
+ #endif
ggml/src/ggml-metal/ggml-metal-context.h ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include "ggml-metal-device.h"
4
+
5
+ #ifdef __cplusplus
6
+ extern "C" {
7
+ #endif
8
+
9
+ //
10
+ // backend context
11
+ //
12
+
13
+ typedef struct ggml_metal * ggml_metal_t;
14
+
15
+ ggml_metal_t ggml_metal_init(ggml_metal_device_t dev);
16
+ void ggml_metal_free(ggml_metal_t ctx);
17
+
18
+ const char * ggml_metal_get_name(ggml_metal_t ctx);
19
+
20
+ void ggml_metal_synchronize(ggml_metal_t ctx);
21
+
22
+ void ggml_metal_set_tensor_async(ggml_metal_t ctx, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size);
23
+ void ggml_metal_get_tensor_async(ggml_metal_t ctx, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size);
24
+ bool ggml_metal_cpy_tensor_async(ggml_metal_t ctx_src, ggml_metal_t ctx_dst, const struct ggml_tensor * src, struct ggml_tensor * dst);
25
+
26
+ enum ggml_status ggml_metal_graph_compute (ggml_metal_t ctx, struct ggml_cgraph * gf);
27
+ void ggml_metal_graph_optimize(ggml_metal_t ctx, struct ggml_cgraph * gf);
28
+
29
+ void ggml_metal_event_record(ggml_metal_t ctx, ggml_metal_event_t ev);
30
+ void ggml_metal_event_wait (ggml_metal_t ctx, ggml_metal_event_t ev);
31
+
32
+ ggml_metal_event_t ggml_metal_get_ev_cpy(ggml_metal_t ctx);
33
+
34
+ void ggml_metal_set_n_cb (ggml_metal_t ctx, int n_cb);
35
+ void ggml_metal_set_abort_callback (ggml_metal_t ctx, ggml_abort_callback abort_callback, void * user_data);
36
+ bool ggml_metal_supports_family (ggml_metal_t ctx, int family);
37
+ void ggml_metal_capture_next_compute(ggml_metal_t ctx);
38
+
39
+ #ifdef __cplusplus
40
+ }
41
+ #endif
ggml/src/ggml-metal/ggml-metal-context.m ADDED
@@ -0,0 +1,739 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #import "ggml-metal-context.h"
2
+
3
+ #import "ggml-impl.h"
4
+ #import "ggml-backend-impl.h"
5
+
6
+ #import "ggml-metal-impl.h"
7
+ #import "ggml-metal-common.h"
8
+ #import "ggml-metal-ops.h"
9
+
10
+ #import <Foundation/Foundation.h>
11
+
12
+ #import <Metal/Metal.h>
13
+
14
+ #undef MIN
15
+ #undef MAX
16
+ #define MIN(a, b) ((a) < (b) ? (a) : (b))
17
+ #define MAX(a, b) ((a) > (b) ? (a) : (b))
18
+
19
+ // max number of MTLCommandBuffer used to submit a graph for processing
20
+ #define GGML_METAL_MAX_COMMAND_BUFFERS 8
21
+
22
+ struct ggml_metal_command_buffer {
23
+ id<MTLCommandBuffer> obj;
24
+ };
25
+
26
+ struct ggml_metal {
27
+ char name[128];
28
+
29
+ ggml_metal_device_t dev;
30
+ ggml_metal_library_t lib;
31
+
32
+ ggml_metal_event_t ev_cpy; // for async copies
33
+
34
+ dispatch_queue_t d_queue;
35
+
36
+ // additional, inference-time compiled pipelines
37
+ ggml_metal_pipelines_t pipelines_ext;
38
+
39
+ bool use_fusion;
40
+ bool use_concurrency;
41
+ bool use_graph_optimize;
42
+
43
+ int debug_graph;
44
+ int debug_fusion;
45
+
46
+ // how many times a given op was fused
47
+ uint64_t fuse_cnt[GGML_OP_COUNT];
48
+
49
+ // capture state
50
+ int capture_compute;
51
+ bool capture_started;
52
+
53
+ id<MTLCaptureScope> capture_scope;
54
+
55
+ // command buffer state
56
+ int n_cb; // number of extra threads used to submit the command buffers
57
+ int n_nodes_0; // number of nodes submitted by the main thread
58
+ int n_nodes_1; // remaining number of nodes submitted by the n_cb threads
59
+ int n_nodes_per_cb;
60
+
61
+ struct ggml_cgraph * gf;
62
+
63
+ // the callback given to the thread pool
64
+ void (^encode_async)(size_t ith);
65
+
66
+ // n_cb command buffers + 1 used by the main thread
67
+ struct ggml_metal_command_buffer cmd_bufs[GGML_METAL_MAX_COMMAND_BUFFERS + 1];
68
+
69
+ // extra command buffers for things like getting, setting and copying tensors
70
+ NSMutableArray * cmd_bufs_ext;
71
+
72
+ // the last command buffer queued into the Metal queue with operations relevant to the current Metal backend
73
+ id<MTLCommandBuffer> cmd_buf_last;
74
+
75
+ // abort ggml_metal_graph_compute if callback returns true
76
+ ggml_abort_callback abort_callback;
77
+ void * abort_callback_data;
78
+
79
+ // error state - set when a command buffer fails during synchronize
80
+ // once set, graph_compute will return GGML_STATUS_FAILED until the backend is recreated
81
+ bool has_error;
82
+ };
83
+
84
+ ggml_metal_t ggml_metal_init(ggml_metal_device_t dev) {
85
+ GGML_LOG_INFO("%s: allocating\n", __func__);
86
+
87
+ #if TARGET_OS_OSX && !GGML_METAL_NDEBUG
88
+ // Show all the Metal device instances in the system
89
+ NSArray * devices = MTLCopyAllDevices();
90
+ for (id<MTLDevice> device in devices) {
91
+ GGML_LOG_INFO("%s: found device: %s\n", __func__, [[device name] UTF8String]);
92
+ }
93
+ [devices release]; // since it was created by a *Copy* C method
94
+ #endif
95
+
96
+ // init context
97
+ ggml_metal_t res = calloc(1, sizeof(struct ggml_metal));
98
+
99
+ id<MTLDevice> device = ggml_metal_device_get_obj(dev);
100
+
101
+ GGML_LOG_INFO("%s: picking default device: %s\n", __func__, [[device name] UTF8String]);
102
+
103
+ // TODO: would it be better to have one queue for the backend and one queue for the device?
104
+ // the graph encoders and async ops would use the backend queue while the sync ops would use the device queue?
105
+ //res->queue = [device newCommandQueue]; [TAG_QUEUE_PER_BACKEND]
106
+ id<MTLCommandQueue> queue = ggml_metal_device_get_queue(dev);
107
+ if (queue == nil) {
108
+ GGML_LOG_ERROR("%s: error: failed to create command queue\n", __func__);
109
+ return NULL;
110
+ }
111
+
112
+ res->dev = dev;
113
+ res->lib = ggml_metal_device_get_library(dev);
114
+ if (res->lib == NULL) {
115
+ GGML_LOG_WARN("%s: the device does not have a precompiled Metal library - this is unexpected\n", __func__);
116
+ GGML_LOG_WARN("%s: will try to compile it on the fly\n", __func__);
117
+
118
+ res->lib = ggml_metal_library_init(dev);
119
+ if (res->lib == NULL) {
120
+ GGML_LOG_ERROR("%s: error: failed to initialize the Metal library\n", __func__);
121
+
122
+ free(res);
123
+
124
+ return NULL;
125
+ }
126
+ }
127
+
128
+ res->ev_cpy = ggml_metal_device_event_init(dev);
129
+
130
+ const struct ggml_metal_device_props * props_dev = ggml_metal_device_get_props(dev);
131
+
132
+ snprintf(res->name, sizeof(res->name), "%s", props_dev->name);
133
+
134
+ res->d_queue = dispatch_queue_create("ggml-metal", DISPATCH_QUEUE_CONCURRENT);
135
+
136
+ res->use_fusion = getenv("GGML_METAL_FUSION_DISABLE") == nil;
137
+ res->use_concurrency = getenv("GGML_METAL_CONCURRENCY_DISABLE") == nil;
138
+
139
+ {
140
+ const char * val = getenv("GGML_METAL_GRAPH_DEBUG");
141
+ res->debug_graph = val ? atoi(val) : 0;
142
+ }
143
+
144
+ {
145
+ const char * val = getenv("GGML_METAL_FUSION_DEBUG");
146
+ res->debug_fusion = val ? atoi(val) : 0;
147
+ }
148
+
149
+ res->use_graph_optimize = true;
150
+
151
+ if (getenv("GGML_METAL_GRAPH_OPTIMIZE_DISABLE") != NULL) {
152
+ res->use_graph_optimize = false;
153
+ }
154
+
155
+ memset(res->fuse_cnt, 0, sizeof(res->fuse_cnt));
156
+
157
+ GGML_LOG_INFO("%s: use fusion = %s\n", __func__, res->use_fusion ? "true" : "false");
158
+ GGML_LOG_INFO("%s: use concurrency = %s\n", __func__, res->use_concurrency ? "true" : "false");
159
+ GGML_LOG_INFO("%s: use graph optimize = %s\n", __func__, res->use_graph_optimize ? "true" : "false");
160
+
161
+ res->capture_compute = 0;
162
+ res->capture_started = false;
163
+ res->capture_scope = nil;
164
+
165
+ {
166
+ const char * val = getenv("GGML_METAL_CAPTURE_COMPUTE");
167
+ if (val) {
168
+ res->capture_compute = atoi(val);
169
+ }
170
+ }
171
+
172
+ res->has_error = false;
173
+
174
+ res->gf = nil;
175
+ res->encode_async = nil;
176
+ for (int i = 0; i < GGML_METAL_MAX_COMMAND_BUFFERS; ++i) {
177
+ res->cmd_bufs[i].obj = nil;
178
+ }
179
+
180
+ res->cmd_bufs_ext = [[NSMutableArray alloc] init];
181
+
182
+ res->cmd_buf_last = nil;
183
+
184
+ res->pipelines_ext = ggml_metal_pipelines_init();
185
+
186
+ return res;
187
+ }
188
+
189
+ void ggml_metal_free(ggml_metal_t ctx) {
190
+ GGML_LOG_INFO("%s: deallocating\n", __func__);
191
+
192
+ for (int i = 0; i < GGML_METAL_MAX_COMMAND_BUFFERS; ++i) {
193
+ if (ctx->cmd_bufs[i].obj) {
194
+ [ctx->cmd_bufs[i].obj release];
195
+ }
196
+ }
197
+
198
+ for (int i = 0; i < (int) ctx->cmd_bufs_ext.count; ++i) {
199
+ if (ctx->cmd_bufs_ext[i]) {
200
+ [ctx->cmd_bufs_ext[i] release];
201
+ }
202
+ }
203
+
204
+ [ctx->cmd_bufs_ext removeAllObjects];
205
+ [ctx->cmd_bufs_ext release];
206
+
207
+ if (ctx->pipelines_ext) {
208
+ ggml_metal_pipelines_free(ctx->pipelines_ext);
209
+ ctx->pipelines_ext = nil;
210
+ }
211
+
212
+ if (ctx->debug_fusion > 0) {
213
+ GGML_LOG_DEBUG("%s: fusion stats:\n", __func__);
214
+ for (int i = 0; i < GGML_OP_COUNT; i++) {
215
+ if (ctx->fuse_cnt[i] == 0) {
216
+ continue;
217
+ }
218
+
219
+ // note: cannot use ggml_log here
220
+ GGML_LOG_DEBUG("%s: - %s: %" PRIu64 "\n", __func__, ggml_op_name((enum ggml_op) i), ctx->fuse_cnt[i]);
221
+ }
222
+ }
223
+
224
+ Block_release(ctx->encode_async);
225
+
226
+ //[ctx->queue release]; // [TAG_QUEUE_PER_BACKEND]
227
+
228
+ dispatch_release(ctx->d_queue);
229
+
230
+ ggml_metal_device_event_free(ctx->dev, ctx->ev_cpy);
231
+
232
+ free(ctx);
233
+ }
234
+
235
+ const char * ggml_metal_get_name(ggml_metal_t ctx) {
236
+ return ctx->name;
237
+ }
238
+
239
+ void ggml_metal_synchronize(ggml_metal_t ctx) {
240
+ // wait for any backend operations to finish
241
+ if (ctx->cmd_buf_last) {
242
+ [ctx->cmd_buf_last waitUntilCompleted];
243
+ ctx->cmd_buf_last = nil;
244
+ }
245
+
246
+ // check status of all command buffers
247
+ {
248
+ const int n_cb = ctx->n_cb;
249
+
250
+ for (int cb_idx = 0; cb_idx <= n_cb; ++cb_idx) {
251
+ id<MTLCommandBuffer> cmd_buf = ctx->cmd_bufs[cb_idx].obj;
252
+ if (!cmd_buf) {
253
+ continue;
254
+ }
255
+
256
+ MTLCommandBufferStatus status = [cmd_buf status];
257
+ if (status != MTLCommandBufferStatusCompleted) {
258
+ GGML_LOG_ERROR("%s: error: command buffer %d failed with status %d\n", __func__, cb_idx, (int) status);
259
+ if (status == MTLCommandBufferStatusError) {
260
+ GGML_LOG_ERROR("error: %s\n", [[cmd_buf error].localizedDescription UTF8String]);
261
+ }
262
+ ctx->has_error = true;
263
+ return;
264
+ }
265
+ }
266
+ }
267
+
268
+ // release any completed extra command buffers
269
+ if (ctx->cmd_bufs_ext.count > 0) {
270
+ for (size_t i = 0; i < ctx->cmd_bufs_ext.count; ++i) {
271
+ id<MTLCommandBuffer> cmd_buf = ctx->cmd_bufs_ext[i];
272
+
273
+ MTLCommandBufferStatus status = [cmd_buf status];
274
+ if (status != MTLCommandBufferStatusCompleted) {
275
+ GGML_LOG_ERROR("%s: error: command buffer %d failed with status %d\n", __func__, (int) i, (int) status);
276
+ if (status == MTLCommandBufferStatusError) {
277
+ GGML_LOG_ERROR("error: %s\n", [[cmd_buf error].localizedDescription UTF8String]);
278
+ }
279
+
280
+ // release this and all remaining command buffers before returning
281
+ for (size_t j = i; j < ctx->cmd_bufs_ext.count; ++j) {
282
+ [ctx->cmd_bufs_ext[j] release];
283
+ }
284
+ [ctx->cmd_bufs_ext removeAllObjects];
285
+
286
+ ctx->has_error = true;
287
+ return;
288
+ }
289
+
290
+ [cmd_buf release];
291
+ }
292
+
293
+ [ctx->cmd_bufs_ext removeAllObjects];
294
+ }
295
+ }
296
+
297
+ static struct ggml_metal_buffer_id ggml_metal_get_buffer_id(const struct ggml_tensor * t) {
298
+ if (!t) {
299
+ return (struct ggml_metal_buffer_id) { nil, 0 };
300
+ }
301
+
302
+ ggml_backend_buffer_t buffer = t->view_src ? t->view_src->buffer : t->buffer;
303
+
304
+ return ggml_metal_buffer_get_id(buffer->context, t);
305
+ }
306
+
307
+ void ggml_metal_set_tensor_async(ggml_metal_t ctx, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
308
+ @autoreleasepool {
309
+ // wrap the source data into a Metal buffer
310
+ id<MTLDevice> device = ggml_metal_device_get_obj(ctx->dev);
311
+ id<MTLBuffer> buf_src = [device newBufferWithBytes:data
312
+ length:size
313
+ options:MTLResourceStorageModeShared];
314
+
315
+ GGML_ASSERT(buf_src);
316
+
317
+ struct ggml_metal_buffer_id bid_dst = ggml_metal_get_buffer_id(tensor);
318
+ if (bid_dst.metal == nil) {
319
+ GGML_ABORT("%s: failed to find buffer for tensor '%s'\n", __func__, tensor->name);
320
+ }
321
+
322
+ bid_dst.offs += offset;
323
+
324
+ // queue the copy operation into the queue of the Metal context
325
+ // this will be queued at the end, after any currently ongoing GPU operations
326
+ id<MTLCommandQueue> queue = ggml_metal_device_get_queue(ctx->dev);
327
+ id<MTLCommandBuffer> cmd_buf = [queue commandBuffer];
328
+ id<MTLBlitCommandEncoder> encoder = [cmd_buf blitCommandEncoder];
329
+
330
+ [encoder copyFromBuffer:buf_src
331
+ sourceOffset:0
332
+ toBuffer:bid_dst.metal
333
+ destinationOffset:bid_dst.offs
334
+ size:size];
335
+
336
+ [encoder endEncoding];
337
+ [cmd_buf commit];
338
+ [buf_src release];
339
+
340
+ // do not wait here for completion
341
+ //[cmd_buf waitUntilCompleted];
342
+
343
+ // instead, remember a reference to the command buffer and wait for it later if needed
344
+ [ctx->cmd_bufs_ext addObject:cmd_buf];
345
+ ctx->cmd_buf_last = cmd_buf;
346
+
347
+ [cmd_buf retain];
348
+ }
349
+ }
350
+
351
+ void ggml_metal_get_tensor_async(ggml_metal_t ctx, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size) {
352
+ @autoreleasepool {
353
+ id<MTLDevice> device = ggml_metal_device_get_obj(ctx->dev);
354
+ id<MTLBuffer> buf_dst = [device newBufferWithBytesNoCopy:data
355
+ length:size
356
+ options:MTLResourceStorageModeShared
357
+ deallocator:nil];
358
+
359
+ GGML_ASSERT(buf_dst);
360
+
361
+ struct ggml_metal_buffer_id bid_src = ggml_metal_get_buffer_id(tensor);
362
+ if (bid_src.metal == nil) {
363
+ GGML_ABORT("%s: failed to find buffer for tensor '%s'\n", __func__, tensor->name);
364
+ }
365
+
366
+ bid_src.offs += offset;
367
+
368
+ // queue the copy operation into the queue of the Metal context
369
+ // this will be queued at the end, after any currently ongoing GPU operations
370
+ id<MTLCommandQueue> queue = ggml_metal_device_get_queue(ctx->dev);
371
+ id<MTLCommandBuffer> cmd_buf = [queue commandBuffer];
372
+ id<MTLBlitCommandEncoder> encoder = [cmd_buf blitCommandEncoder];
373
+
374
+ [encoder copyFromBuffer:bid_src.metal
375
+ sourceOffset:bid_src.offs
376
+ toBuffer:buf_dst
377
+ destinationOffset:0
378
+ size:size];
379
+
380
+ [encoder endEncoding];
381
+ [cmd_buf commit];
382
+ [buf_dst release];
383
+
384
+ // do not wait here for completion
385
+ //[cmd_buf waitUntilCompleted];
386
+
387
+ // instead, remember a reference to the command buffer and wait for it later if needed
388
+ [ctx->cmd_bufs_ext addObject:cmd_buf];
389
+ ctx->cmd_buf_last = cmd_buf;
390
+
391
+ [cmd_buf retain];
392
+ }
393
+ }
394
+
395
+ bool ggml_metal_cpy_tensor_async(ggml_metal_t ctx_src, ggml_metal_t ctx_dst, const struct ggml_tensor * src, struct ggml_tensor * dst) {
396
+ @autoreleasepool {
397
+ struct ggml_metal_buffer_id bid_src = ggml_metal_get_buffer_id(src);
398
+ struct ggml_metal_buffer_id bid_dst = ggml_metal_get_buffer_id(dst);
399
+
400
+ if (bid_src.metal == nil || bid_dst.metal == nil) {
401
+ return false;
402
+ }
403
+
404
+ // queue the copy operation into the Metal context
405
+ // this will be queued at the end, after any currently ongoing GPU operations
406
+ id<MTLCommandQueue> queue = ggml_metal_device_get_queue(ctx_src->dev);
407
+ id<MTLCommandBuffer> cmd_buf = [queue commandBuffer];
408
+ id<MTLBlitCommandEncoder> encoder = [cmd_buf blitCommandEncoder];
409
+
410
+ [encoder copyFromBuffer:bid_src.metal
411
+ sourceOffset:bid_src.offs
412
+ toBuffer:bid_dst.metal
413
+ destinationOffset:bid_dst.offs
414
+ size:ggml_nbytes(src)];
415
+
416
+ [encoder endEncoding];
417
+
418
+ ggml_metal_event_t ev_cpy = ggml_metal_get_ev_cpy(ctx_src);
419
+ ggml_metal_event_encode_signal(ev_cpy, cmd_buf);
420
+
421
+ [cmd_buf commit];
422
+
423
+ // do not wait here for completion
424
+ //[cmd_buf waitUntilCompleted];
425
+
426
+ // instead, remember a reference to the command buffer and wait for it later if needed
427
+ [ctx_src->cmd_bufs_ext addObject:cmd_buf];
428
+ ctx_src->cmd_buf_last = cmd_buf;
429
+
430
+ [cmd_buf retain];
431
+
432
+ ggml_metal_event_wait(ctx_dst, ev_cpy);
433
+
434
+ return true;
435
+ }
436
+ }
437
+
438
+ enum ggml_status ggml_metal_graph_compute(ggml_metal_t ctx, struct ggml_cgraph * gf) {
439
+ if (ctx->has_error) {
440
+ GGML_LOG_ERROR("%s: backend is in error state from a previous command buffer failure - recreate the backend to recover\n", __func__);
441
+ return GGML_STATUS_FAILED;
442
+ }
443
+
444
+ // number of nodes encoded by the main thread (empirically determined)
445
+ const int n_main = MAX(64, 0.1*gf->n_nodes);
446
+
447
+ // number of threads in addition to the main thread
448
+ const int n_cb = ctx->n_cb;
449
+
450
+ // keep the memory wired
451
+ ggml_metal_device_rsets_keep_alive(ctx->dev);
452
+
453
+ // submit the ggml compute graph to the GPU by creating command buffers and encoding the ops in them
454
+ // the first n_nodes_0 are encoded and submitted for processing directly by the calling thread
455
+ // while these nodes are processing, we start n_cb threads to enqueue the rest of the nodes
456
+ // each thread creates it's own command buffer and enqueues the ops in parallel
457
+ //
458
+ // tests on M1 Pro and M2 Ultra using LLaMA models, show that optimal values for n_cb are 1 or 2
459
+
460
+ @autoreleasepool {
461
+ ctx->gf = gf;
462
+
463
+ ctx->n_nodes_0 = MIN(n_main, gf->n_nodes);
464
+ ctx->n_nodes_1 = gf->n_nodes - ctx->n_nodes_0;
465
+
466
+ ctx->n_nodes_per_cb = (ctx->n_nodes_1 + ctx->n_cb - 1) / ctx->n_cb;
467
+
468
+ if (ctx->capture_compute >= 0) {
469
+ ctx->capture_compute--;
470
+ }
471
+
472
+ const bool use_capture = ctx->capture_compute == 0;
473
+ if (use_capture) {
474
+ ctx->capture_compute = -1;
475
+
476
+ // make sure all previous computations have finished before starting the capture
477
+ if (ctx->cmd_buf_last) {
478
+ [ctx->cmd_buf_last waitUntilCompleted];
479
+ ctx->cmd_buf_last = nil;
480
+ }
481
+
482
+ if (!ctx->capture_started) {
483
+ NSString * path = [NSString stringWithFormat:@"/tmp/perf-metal-%d.gputrace", getpid()];
484
+
485
+ GGML_LOG_WARN("%s: capturing graph in %s\n", __func__, [path UTF8String]);
486
+
487
+ // create capture scope
488
+ id<MTLDevice> device = ggml_metal_device_get_obj(ctx->dev);
489
+ ctx->capture_scope = [[MTLCaptureManager sharedCaptureManager] newCaptureScopeWithDevice:device];
490
+
491
+ MTLCaptureDescriptor * descriptor = [MTLCaptureDescriptor new];
492
+ descriptor.captureObject = ctx->capture_scope;
493
+ descriptor.destination = MTLCaptureDestinationGPUTraceDocument;
494
+ descriptor.outputURL = [NSURL fileURLWithPath:path];
495
+
496
+ NSError * error = nil;
497
+ if (![[MTLCaptureManager sharedCaptureManager] startCaptureWithDescriptor:descriptor error:&error]) {
498
+ GGML_LOG_ERROR("%s: error: unable to start capture '%s'\n", __func__, [[error localizedDescription] UTF8String]);
499
+ } else {
500
+ [ctx->capture_scope beginScope];
501
+ ctx->capture_started = true;
502
+ }
503
+ }
504
+ }
505
+
506
+ // short-hand
507
+ id<MTLCommandQueue> queue = ggml_metal_device_get_queue(ctx->dev);
508
+
509
+ // the main thread commits the first few commands immediately
510
+ // cmd_buf[n_cb]
511
+ {
512
+ id<MTLCommandBuffer> cmd_buf = [queue commandBufferWithUnretainedReferences];
513
+ [cmd_buf retain];
514
+
515
+ if (ctx->cmd_bufs[n_cb].obj) {
516
+ [ctx->cmd_bufs[n_cb].obj release];
517
+ }
518
+ ctx->cmd_bufs[n_cb].obj = cmd_buf;
519
+
520
+ [cmd_buf enqueue];
521
+
522
+ ctx->encode_async(n_cb);
523
+ }
524
+
525
+ // remember the command buffer for the next iteration
526
+ ctx->cmd_buf_last = ctx->cmd_bufs[n_cb].obj;
527
+
528
+ // prepare the rest of the command buffers asynchronously (optional)
529
+ // cmd_buf[0.. n_cb)
530
+ for (int cb_idx = 0; cb_idx < n_cb; ++cb_idx) {
531
+ id<MTLCommandBuffer> cmd_buf = [queue commandBufferWithUnretainedReferences];
532
+ [cmd_buf retain];
533
+
534
+ if (ctx->cmd_bufs[cb_idx].obj) {
535
+ [ctx->cmd_bufs[cb_idx].obj release];
536
+ }
537
+ ctx->cmd_bufs[cb_idx].obj = cmd_buf;
538
+
539
+ // always enqueue the first two command buffers
540
+ // enqueue all of the command buffers if we don't need to abort
541
+ if (cb_idx < 2 || ctx->abort_callback == NULL) {
542
+ [cmd_buf enqueue];
543
+
544
+ // update the pointer to the last queued command buffer
545
+ // this is needed to implement synchronize()
546
+ ctx->cmd_buf_last = cmd_buf;
547
+ }
548
+ }
549
+
550
+ dispatch_apply(n_cb, ctx->d_queue, ctx->encode_async);
551
+
552
+ // for debugging: block until graph is computed
553
+ //[ctx->cmd_buf_last waitUntilCompleted];
554
+
555
+ // enter here only when capturing in order to wait for all computation to finish
556
+ // otherwise, we leave the graph to compute asynchronously
557
+ if (use_capture && ctx->capture_started) {
558
+ // wait for completion and check status of each command buffer
559
+ // needed to detect if the device ran out-of-memory for example (#1881)
560
+ {
561
+ id<MTLCommandBuffer> cmd_buf = ctx->cmd_bufs[n_cb].obj;
562
+ [cmd_buf waitUntilCompleted];
563
+
564
+ MTLCommandBufferStatus status = [cmd_buf status];
565
+ if (status != MTLCommandBufferStatusCompleted) {
566
+ GGML_LOG_INFO("%s: command buffer %d failed with status %lu\n", __func__, n_cb, status);
567
+ if (status == MTLCommandBufferStatusError) {
568
+ GGML_LOG_INFO("error: %s\n", [[cmd_buf error].localizedDescription UTF8String]);
569
+ }
570
+
571
+ return GGML_STATUS_FAILED;
572
+ }
573
+ }
574
+
575
+ for (int i = 0; i < n_cb; ++i) {
576
+ id<MTLCommandBuffer> cmd_buf = ctx->cmd_bufs[i].obj;
577
+ [cmd_buf waitUntilCompleted];
578
+
579
+ MTLCommandBufferStatus status = [cmd_buf status];
580
+ if (status != MTLCommandBufferStatusCompleted) {
581
+ GGML_LOG_INFO("%s: command buffer %d failed with status %lu\n", __func__, i, status);
582
+ if (status == MTLCommandBufferStatusError) {
583
+ GGML_LOG_INFO("error: %s\n", [[cmd_buf error].localizedDescription UTF8String]);
584
+ }
585
+
586
+ return GGML_STATUS_FAILED;
587
+ }
588
+
589
+ id<MTLCommandBuffer> next_buffer = (i + 1 < n_cb ? ctx->cmd_bufs[i + 1].obj : nil);
590
+ if (!next_buffer) {
591
+ continue;
592
+ }
593
+
594
+ const bool next_queued = ([next_buffer status] != MTLCommandBufferStatusNotEnqueued);
595
+ if (next_queued) {
596
+ continue;
597
+ }
598
+
599
+ if (ctx->abort_callback && ctx->abort_callback(ctx->abort_callback_data)) {
600
+ GGML_LOG_INFO("%s: command buffer %d aborted", __func__, i);
601
+ return GGML_STATUS_ABORTED;
602
+ }
603
+
604
+ [next_buffer commit];
605
+ }
606
+
607
+ [ctx->capture_scope endScope];
608
+ [[MTLCaptureManager sharedCaptureManager] stopCapture];
609
+
610
+ ctx->capture_started = false;
611
+ }
612
+ }
613
+
614
+ return GGML_STATUS_SUCCESS;
615
+ }
616
+
617
+ void ggml_metal_graph_optimize(ggml_metal_t ctx, struct ggml_cgraph * gf) {
618
+ //const int64_t t_start = ggml_time_us();
619
+
620
+ if (ctx->use_graph_optimize) {
621
+ ggml_graph_optimize(gf);
622
+ }
623
+
624
+ //printf("%s: graph optimize took %.3f ms\n", __func__, (ggml_time_us() - t_start) / 1000.0);
625
+ }
626
+
627
+ void ggml_metal_event_record(ggml_metal_t ctx, ggml_metal_event_t ev) {
628
+ @autoreleasepool {
629
+ id<MTLCommandQueue> queue = ggml_metal_device_get_queue(ctx->dev);
630
+ id<MTLCommandBuffer> cmd_buf = [queue commandBuffer];
631
+
632
+ ggml_metal_event_encode_signal(ev, cmd_buf);
633
+
634
+ [cmd_buf commit];
635
+
636
+ [ctx->cmd_bufs_ext addObject:cmd_buf];
637
+ ctx->cmd_buf_last = cmd_buf;
638
+
639
+ [cmd_buf retain];
640
+ }
641
+ }
642
+
643
+ void ggml_metal_event_wait(ggml_metal_t ctx, ggml_metal_event_t ev) {
644
+ @autoreleasepool {
645
+ id<MTLCommandQueue> queue = ggml_metal_device_get_queue(ctx->dev);
646
+ id<MTLCommandBuffer> cmd_buf = [queue commandBuffer];
647
+
648
+ ggml_metal_event_encode_wait(ev, cmd_buf);
649
+
650
+ [cmd_buf commit];
651
+
652
+ [ctx->cmd_bufs_ext addObject:cmd_buf];
653
+ ctx->cmd_buf_last = cmd_buf;
654
+
655
+ [cmd_buf retain];
656
+ }
657
+ }
658
+
659
+ ggml_metal_event_t ggml_metal_get_ev_cpy(ggml_metal_t ctx) {
660
+ return ctx->ev_cpy;
661
+ }
662
+
663
+ void ggml_metal_set_n_cb(ggml_metal_t ctx, int n_cb) {
664
+ if (ctx->n_cb != n_cb) {
665
+ ctx->n_cb = MIN(n_cb, GGML_METAL_MAX_COMMAND_BUFFERS);
666
+
667
+ if (ctx->n_cb > 2) {
668
+ GGML_LOG_WARN("%s: n_cb = %d, using n_cb > 2 is not recommended and can degrade the performance in some cases\n", __func__, n_cb);
669
+ }
670
+ }
671
+
672
+ if (ctx->encode_async) {
673
+ Block_release(ctx->encode_async);
674
+ }
675
+
676
+ ctx->encode_async = Block_copy(^(size_t iter) {
677
+ const int cb_idx = iter;
678
+ const int n_cb_l = ctx->n_cb;
679
+
680
+ const int n_nodes_0 = ctx->n_nodes_0;
681
+ const int n_nodes_1 = ctx->n_nodes_1;
682
+
683
+ const int n_nodes_per_cb = ctx->n_nodes_per_cb;
684
+
685
+ int idx_start = 0;
686
+ int idx_end = n_nodes_0;
687
+
688
+ if (cb_idx < n_cb_l) {
689
+ idx_start = n_nodes_0 + ( (cb_idx + 0) * n_nodes_per_cb);
690
+ idx_end = n_nodes_0 + (MIN((cb_idx == n_cb_l - 1) ? n_nodes_1 : (cb_idx + 1) * n_nodes_per_cb, n_nodes_1));
691
+ }
692
+
693
+ id<MTLCommandBuffer> cmd_buf = ctx->cmd_bufs[cb_idx].obj;
694
+
695
+ ggml_metal_op_t ctx_op = ggml_metal_op_init(
696
+ ctx->dev,
697
+ cmd_buf,
698
+ ctx->gf,
699
+ idx_start,
700
+ idx_end,
701
+ ctx->use_fusion,
702
+ ctx->use_concurrency,
703
+ ctx->capture_compute,
704
+ ctx->debug_graph,
705
+ ctx->debug_fusion);
706
+
707
+ for (int idx = 0; idx < ggml_metal_op_n_nodes(ctx_op); ++idx) {
708
+ const int res = ggml_metal_op_encode(ctx_op, idx);
709
+ if (res == 0) {
710
+ break;
711
+ }
712
+
713
+ idx += res - 1;
714
+ }
715
+
716
+ ggml_metal_op_free(ctx_op);
717
+
718
+ if (cb_idx < 2 || ctx->abort_callback == NULL) {
719
+ [cmd_buf commit];
720
+ }
721
+ });
722
+ }
723
+
724
+ void ggml_metal_set_abort_callback(ggml_metal_t ctx, ggml_abort_callback abort_callback, void * user_data) {
725
+ ctx->abort_callback = abort_callback;
726
+ ctx->abort_callback_data = user_data;
727
+ }
728
+
729
+ bool ggml_metal_supports_family(ggml_metal_t ctx, int family) {
730
+ GGML_ASSERT(ctx->dev != nil);
731
+
732
+ id<MTLDevice> device = ggml_metal_device_get_obj(ctx->dev);
733
+
734
+ return [device supportsFamily:(MTLGPUFamilyApple1 + family - 1)];
735
+ }
736
+
737
+ void ggml_metal_capture_next_compute(ggml_metal_t ctx) {
738
+ ctx->capture_compute = 1;
739
+ }
ggml/src/ggml-metal/ggml-metal-device.cpp ADDED
@@ -0,0 +1,2227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "ggml-metal-device.h"
2
+
3
+ #include "ggml-metal-impl.h"
4
+
5
+ #include "ggml-impl.h"
6
+
7
+ #include <cassert>
8
+ #include <memory>
9
+ #include <string>
10
+ #include <unordered_map>
11
+
12
+ struct ggml_metal_device_deleter {
13
+ void operator()(ggml_metal_device_t ctx) {
14
+ ggml_metal_device_free(ctx);
15
+ }
16
+ };
17
+
18
+ typedef std::unique_ptr<ggml_metal_device, ggml_metal_device_deleter> ggml_metal_device_ptr;
19
+
20
+ ggml_metal_device_t ggml_metal_device_get(int device) {
21
+ static std::vector<ggml_metal_device_ptr> devs;
22
+
23
+ devs.emplace_back(ggml_metal_device_init(device));
24
+
25
+ return devs.back().get();
26
+ }
27
+
28
+ struct ggml_metal_pipelines {
29
+ std::unordered_map<std::string, ggml_metal_pipeline_t> data;
30
+ };
31
+
32
+ ggml_metal_pipelines_t ggml_metal_pipelines_init(void) {
33
+ ggml_metal_pipelines_t res = new ggml_metal_pipelines();
34
+
35
+ return res;
36
+ }
37
+
38
+ void ggml_metal_pipelines_free(ggml_metal_pipelines_t ppls) {
39
+ if (!ppls) {
40
+ return;
41
+ }
42
+
43
+ for (auto it = ppls->data.begin(); it != ppls->data.end(); ++it) {
44
+ ggml_metal_pipeline_free(it->second);
45
+ }
46
+
47
+ delete ppls;
48
+ }
49
+
50
+ void ggml_metal_pipelines_add(ggml_metal_pipelines_t ppls, const char * name, ggml_metal_pipeline_t pipeline) {
51
+ ppls->data[name] = pipeline;
52
+ }
53
+
54
+ ggml_metal_pipeline_t ggml_metal_pipelines_get(ggml_metal_pipelines_t ppls, const char * name) {
55
+ if (ppls->data.find(name) == ppls->data.end()) {
56
+ return nullptr;
57
+ }
58
+
59
+ return ppls->data[name];
60
+ }
61
+
62
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_base(ggml_metal_library_t lib, ggml_op op) {
63
+ char base[256];
64
+ char name[256];
65
+
66
+ const char * op_str = "undefined";
67
+ switch (op) {
68
+ case GGML_OP_ADD_ID: op_str = "add_id"; break;
69
+ default: GGML_ABORT("fatal error");
70
+ };
71
+
72
+ snprintf(base, 256, "kernel_%s", op_str);
73
+ snprintf(name, 256, "%s", base);
74
+
75
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
76
+ if (!res.pipeline) {
77
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
78
+ }
79
+
80
+ return res;
81
+ }
82
+
83
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_cpy(ggml_metal_library_t lib, ggml_type tsrc, ggml_type tdst) {
84
+ char base[256];
85
+ char name[256];
86
+
87
+ snprintf(base, 256, "kernel_cpy_%s_%s", ggml_type_name(tsrc), ggml_type_name(tdst));
88
+ snprintf(name, 256, "%s", base);
89
+
90
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
91
+ if (!res.pipeline) {
92
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
93
+ }
94
+
95
+ return res;
96
+ }
97
+
98
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_pool_1d(ggml_metal_library_t lib, const ggml_tensor * op, ggml_op_pool op_pool) {
99
+ GGML_ASSERT(ggml_is_contiguous(op->src[0]));
100
+ GGML_ASSERT(op->src[0]->type == GGML_TYPE_F32 && op->src[0]->type == op->type);
101
+
102
+ const char * pool_str = "undefined";
103
+ switch (op_pool) {
104
+ case GGML_OP_POOL_AVG: pool_str = "avg"; break;
105
+ case GGML_OP_POOL_MAX: pool_str = "max"; break;
106
+ default: GGML_ASSERT(false && "not implemented");
107
+ };
108
+
109
+ char base[256];
110
+ char name[256];
111
+
112
+ snprintf(base, sizeof(base), "kernel_pool_1d_%s_%s", pool_str, ggml_type_name(op->src[0]->type));
113
+ snprintf(name, sizeof(name), "%s", base);
114
+
115
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
116
+ if (!res.pipeline) {
117
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
118
+ }
119
+
120
+ return res;
121
+ }
122
+
123
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_pool_2d(ggml_metal_library_t lib, const ggml_tensor * op, ggml_op_pool op_pool) {
124
+ GGML_ASSERT(ggml_is_contiguous(op->src[0]));
125
+ GGML_ASSERT(op->src[0]->type == GGML_TYPE_F32 && op->src[0]->type == op->type);
126
+
127
+ const char * pool_str = "undefined";
128
+ switch (op_pool) {
129
+ case GGML_OP_POOL_AVG: pool_str = "avg"; break;
130
+ case GGML_OP_POOL_MAX: pool_str = "max"; break;
131
+ default: GGML_ASSERT(false && "not implemented");
132
+ };
133
+
134
+ char base[256];
135
+ char name[256];
136
+
137
+ snprintf(base, 256, "kernel_pool_2d_%s_%s", pool_str, ggml_type_name(op->src[0]->type));
138
+ snprintf(name, 256, "%s", base);
139
+
140
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
141
+ if (!res.pipeline) {
142
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
143
+ }
144
+
145
+ return res;
146
+ }
147
+
148
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_get_rows(ggml_metal_library_t lib, ggml_type tsrc) {
149
+ char base[256];
150
+ char name[256];
151
+
152
+ snprintf(base, 256, "kernel_get_rows_%s", ggml_type_name(tsrc));
153
+ snprintf(name, 256, "%s", base);
154
+
155
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
156
+ if (!res.pipeline) {
157
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
158
+ }
159
+
160
+ return res;
161
+ }
162
+
163
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_set_rows(ggml_metal_library_t lib, const ggml_tensor * op) {
164
+ char base[256];
165
+ char name[256];
166
+
167
+ const auto tsrc = op->src[0]->type;
168
+ const auto tidx = op->src[1]->type;
169
+ const auto tdst = op->type;
170
+
171
+ snprintf(base, 256, "kernel_set_rows_%s_%s_%s", ggml_type_name(tsrc), ggml_type_name(tidx), ggml_type_name(tdst));
172
+ snprintf(name, 256, "%s", base);
173
+
174
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
175
+ if (!res.pipeline) {
176
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
177
+ }
178
+
179
+ return res;
180
+ }
181
+
182
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_diag(ggml_metal_library_t lib, const ggml_tensor * op) {
183
+ char base[256];
184
+ char name[256];
185
+
186
+ const int n = op->src[0]->ne[0];
187
+
188
+ snprintf(base, 256, "kernel_diag_%s", ggml_type_name(op->src[0]->type));
189
+ snprintf(name, 256, "%s_n=%d", base, n);
190
+
191
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
192
+ if (!res.pipeline) {
193
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
194
+ }
195
+
196
+ res.nsg = 1;
197
+ res.smem = 0;
198
+
199
+ return res;
200
+ }
201
+
202
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_repeat(ggml_metal_library_t lib, ggml_type tsrc) {
203
+ char base[256];
204
+ char name[256];
205
+
206
+ snprintf(base, 256, "kernel_repeat_%s", ggml_type_name(tsrc));
207
+ snprintf(name, 256, "%s", base);
208
+
209
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
210
+ if (!res.pipeline) {
211
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
212
+ }
213
+
214
+ return res;
215
+ }
216
+
217
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_concat(ggml_metal_library_t lib, ggml_type tsrc) {
218
+ char base[256];
219
+ char name[256];
220
+
221
+ snprintf(base, 256, "kernel_concat_%s", ggml_type_name(tsrc));
222
+ snprintf(name, 256, "%s", base);
223
+
224
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
225
+ if (!res.pipeline) {
226
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
227
+ }
228
+
229
+ return res;
230
+ }
231
+
232
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_unary(ggml_metal_library_t lib, const ggml_tensor * op) {
233
+ char base[256];
234
+ char name[256];
235
+
236
+ int op_num = -1;
237
+
238
+ switch (op->op) {
239
+ case GGML_OP_SCALE: op_num = OP_UNARY_NUM_SCALE; break;
240
+ case GGML_OP_FILL: op_num = OP_UNARY_NUM_FILL; break;
241
+ case GGML_OP_CLAMP: op_num = OP_UNARY_NUM_CLAMP; break;
242
+ case GGML_OP_SQR: op_num = OP_UNARY_NUM_SQR; break;
243
+ case GGML_OP_SQRT: op_num = OP_UNARY_NUM_SQRT; break;
244
+ case GGML_OP_SIN: op_num = OP_UNARY_NUM_SIN; break;
245
+ case GGML_OP_COS: op_num = OP_UNARY_NUM_COS; break;
246
+ case GGML_OP_LOG: op_num = OP_UNARY_NUM_LOG; break;
247
+ case GGML_OP_LEAKY_RELU: op_num = OP_UNARY_NUM_LEAKY_RELU; break;
248
+ case GGML_OP_UNARY:
249
+ switch (ggml_get_unary_op(op)) {
250
+ case GGML_UNARY_OP_TANH: op_num = OP_UNARY_NUM_TANH; break;
251
+ case GGML_UNARY_OP_RELU: op_num = OP_UNARY_NUM_RELU; break;
252
+ case GGML_UNARY_OP_SIGMOID: op_num = OP_UNARY_NUM_SIGMOID; break;
253
+ case GGML_UNARY_OP_GELU: op_num = OP_UNARY_NUM_GELU; break;
254
+ case GGML_UNARY_OP_GELU_ERF: op_num = OP_UNARY_NUM_GELU_ERF; break;
255
+ case GGML_UNARY_OP_GELU_QUICK: op_num = OP_UNARY_NUM_GELU_QUICK; break;
256
+ case GGML_UNARY_OP_SILU: op_num = OP_UNARY_NUM_SILU; break;
257
+ case GGML_UNARY_OP_ELU: op_num = OP_UNARY_NUM_ELU; break;
258
+ case GGML_UNARY_OP_NEG: op_num = OP_UNARY_NUM_NEG; break;
259
+ case GGML_UNARY_OP_ABS: op_num = OP_UNARY_NUM_ABS; break;
260
+ case GGML_UNARY_OP_SGN: op_num = OP_UNARY_NUM_SGN; break;
261
+ case GGML_UNARY_OP_STEP: op_num = OP_UNARY_NUM_STEP; break;
262
+ case GGML_UNARY_OP_HARDSWISH: op_num = OP_UNARY_NUM_HARDSWISH; break;
263
+ case GGML_UNARY_OP_HARDSIGMOID: op_num = OP_UNARY_NUM_HARDSIGMOID; break;
264
+ case GGML_UNARY_OP_EXP: op_num = OP_UNARY_NUM_EXP; break;
265
+ case GGML_UNARY_OP_SOFTPLUS: op_num = OP_UNARY_NUM_SOFTPLUS; break;
266
+ case GGML_UNARY_OP_EXPM1: op_num = OP_UNARY_NUM_EXPM1; break;
267
+ case GGML_UNARY_OP_FLOOR: op_num = OP_UNARY_NUM_FLOOR; break;
268
+ case GGML_UNARY_OP_CEIL: op_num = OP_UNARY_NUM_CEIL; break;
269
+ case GGML_UNARY_OP_ROUND: op_num = OP_UNARY_NUM_ROUND; break;
270
+ case GGML_UNARY_OP_TRUNC: op_num = OP_UNARY_NUM_TRUNC; break;
271
+ case GGML_UNARY_OP_XIELU: op_num = OP_UNARY_NUM_XIELU; break;
272
+ default: GGML_ABORT("fatal error");
273
+ } break;
274
+ default: GGML_ABORT("fatal error");
275
+ };
276
+
277
+ const char * t0_str = ggml_type_name(op->src[0]->type);
278
+ const char * t_str = ggml_type_name(op->type);
279
+
280
+ const bool is_c4 = op->src[0]->ne[0] % 4 == 0;
281
+ const bool is_cnt = ggml_is_contiguous(op->src[0]) && ggml_nelements(op) < 32768;
282
+
283
+ snprintf(base, 256, "kernel_unary_%s_%s%s", t0_str, t_str, is_c4 ? "_4" : "");
284
+ snprintf(name, 256, "%s_op=%d_cnt=%d", base, op_num, is_cnt);
285
+
286
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
287
+ if (!res.pipeline) {
288
+ ggml_metal_cv_t cv = ggml_metal_cv_init();
289
+
290
+ ggml_metal_cv_set_int16(cv, op_num, FC_UNARY + 0);
291
+ ggml_metal_cv_set_bool (cv, is_cnt, FC_UNARY + 1);
292
+
293
+ res = ggml_metal_library_compile_pipeline(lib, base, name, cv);
294
+
295
+ ggml_metal_cv_free(cv);
296
+ }
297
+
298
+ res.c4 = is_c4;
299
+ res.cnt = is_cnt;
300
+
301
+ return res;
302
+ }
303
+
304
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_glu(ggml_metal_library_t lib, const ggml_tensor * op) {
305
+ GGML_ASSERT(ggml_is_contiguous_1(op->src[0]));
306
+
307
+ char base[256];
308
+ char name[256];
309
+
310
+ const char * op_str = "undefined";
311
+ switch (op->op) {
312
+ case GGML_OP_GLU:
313
+ switch (ggml_get_glu_op(op)) {
314
+ case GGML_GLU_OP_REGLU: op_str = "reglu"; break;
315
+ case GGML_GLU_OP_GEGLU: op_str = "geglu"; break;
316
+ case GGML_GLU_OP_SWIGLU: op_str = "swiglu"; break;
317
+ case GGML_GLU_OP_SWIGLU_OAI: op_str = "swiglu_oai"; break;
318
+ case GGML_GLU_OP_GEGLU_ERF: op_str = "geglu_erf"; break;
319
+ case GGML_GLU_OP_GEGLU_QUICK: op_str = "geglu_quick"; break;
320
+ default: GGML_ABORT("fatal error");
321
+ } break;
322
+ default: GGML_ABORT("fatal error");
323
+ };
324
+
325
+ snprintf(base, 256, "kernel_%s_%s", op_str, ggml_type_name(op->src[0]->type));
326
+ snprintf(name, 256, "%s", base);
327
+
328
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
329
+ if (!res.pipeline) {
330
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
331
+ }
332
+
333
+ return res;
334
+ }
335
+
336
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_sum(ggml_metal_library_t lib, const ggml_tensor * op) {
337
+ assert(op->op == GGML_OP_SUM);
338
+
339
+ char base[256];
340
+ char name[256];
341
+
342
+ snprintf(base, 256, "kernel_op_sum_%s", ggml_type_name(op->src[0]->type));
343
+ snprintf(name, 256, "%s", base);
344
+
345
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
346
+ if (!res.pipeline) {
347
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
348
+ }
349
+
350
+ return res;
351
+ }
352
+
353
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_sum_rows(ggml_metal_library_t lib, const ggml_tensor * op) {
354
+ GGML_ASSERT(ggml_is_contiguous_rows(op->src[0]));
355
+
356
+ char base[256];
357
+ char name[256];
358
+
359
+ int op_num = -1;
360
+
361
+ switch (op->op) {
362
+ case GGML_OP_SUM_ROWS: op_num = OP_SUM_ROWS_NUM_SUM_ROWS; break;
363
+ case GGML_OP_MEAN: op_num = OP_SUM_ROWS_NUM_MEAN; break;
364
+ default: GGML_ABORT("fatal error");
365
+ };
366
+
367
+ const char * t0_str = ggml_type_name(op->src[0]->type);
368
+ const char * t_str = ggml_type_name(op->type);
369
+
370
+ const bool is_c4 = op->src[0]->ne[0] % 4 == 0;
371
+
372
+ snprintf(base, 256, "kernel_sum_rows_%s_%s%s", t0_str, t_str, is_c4 ? "_4" : "");
373
+ snprintf(name, 256, "%s_op=%d", base, op_num);
374
+
375
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
376
+ if (!res.pipeline) {
377
+ ggml_metal_cv_t cv = ggml_metal_cv_init();
378
+
379
+ ggml_metal_cv_set_int16(cv, op_num, FC_SUM_ROWS + 0);
380
+
381
+ res = ggml_metal_library_compile_pipeline(lib, base, name, cv);
382
+
383
+ ggml_metal_cv_free(cv);
384
+ }
385
+
386
+ res.smem = 32*sizeof(float);
387
+
388
+ if (is_c4) {
389
+ res.smem *= 4;
390
+ }
391
+
392
+ res.c4 = is_c4;
393
+
394
+ return res;
395
+ }
396
+
397
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_cumsum_blk(ggml_metal_library_t lib, const ggml_tensor * op) {
398
+ GGML_ASSERT(op->op == GGML_OP_CUMSUM);
399
+
400
+ char base[256];
401
+ char name[256];
402
+
403
+ snprintf(base, 256, "kernel_cumsum_blk_%s", ggml_type_name(op->src[0]->type));
404
+ snprintf(name, 256, "%s", base);
405
+
406
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
407
+ if (!res.pipeline) {
408
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
409
+ }
410
+
411
+ return res;
412
+ }
413
+
414
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_cumsum_add(ggml_metal_library_t lib, const ggml_tensor * op) {
415
+ GGML_ASSERT(op->op == GGML_OP_CUMSUM);
416
+
417
+ char base[256];
418
+ char name[256];
419
+
420
+ snprintf(base, 256, "kernel_cumsum_add_%s", ggml_type_name(op->src[0]->type));
421
+ snprintf(name, 256, "%s", base);
422
+
423
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
424
+ if (!res.pipeline) {
425
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
426
+ }
427
+
428
+ return res;
429
+ }
430
+
431
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_tri(ggml_metal_library_t lib, const ggml_tensor * op) {
432
+ GGML_ASSERT(op->op == GGML_OP_TRI);
433
+ GGML_ASSERT(op->src[0]->nb[0] == ggml_type_size(op->src[0]->type));
434
+
435
+ char base[256];
436
+ char name[256];
437
+
438
+ const char * op_str = "tri";
439
+ const int ttype = op->op_params[0];
440
+
441
+ snprintf(base, 256, "kernel_%s_%s_%d", op_str, ggml_type_name(op->src[0]->type), ttype);
442
+
443
+ snprintf(name, 256, "%s", base);
444
+
445
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
446
+ if (!res.pipeline) {
447
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
448
+ }
449
+
450
+ return res;
451
+ }
452
+
453
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_soft_max(ggml_metal_library_t lib, const ggml_tensor * op) {
454
+ GGML_ASSERT(!op->src[1] || op->src[1]->type == GGML_TYPE_F16 || op->src[1]->type == GGML_TYPE_F32);
455
+
456
+ char base[256];
457
+ char name[256];
458
+
459
+ const char * suffix = "";
460
+
461
+ if (op->src[0]->ne[0] % 4 == 0) {
462
+ suffix = "_4";
463
+ }
464
+
465
+ const ggml_type tsrc1 = op->src[1] ? op->src[1]->type : GGML_TYPE_F32;
466
+
467
+ snprintf(base, 256, "kernel_soft_max_%s%s", ggml_type_name(tsrc1), suffix);
468
+ snprintf(name, 256, "%s", base);
469
+
470
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
471
+ if (!res.pipeline) {
472
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
473
+ }
474
+
475
+ res.smem = 32*sizeof(float);
476
+
477
+ return res;
478
+ }
479
+
480
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_lightning_indexer(
481
+ ggml_metal_library_t lib,
482
+ const ggml_tensor * op) {
483
+ GGML_ASSERT(op->op == GGML_OP_LIGHTNING_INDEXER);
484
+
485
+ char name[256];
486
+
487
+ snprintf(name, 256, "kernel_lightning_indexer_%s", ggml_type_name(op->src[1]->type));
488
+
489
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
490
+ if (!res.pipeline) {
491
+ res = ggml_metal_library_compile_pipeline(lib, name, name, nullptr);
492
+ }
493
+
494
+ return res;
495
+ }
496
+
497
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_dsv4_hc(ggml_metal_library_t lib, ggml_op op) {
498
+ const char * name = nullptr;
499
+
500
+ switch (op) {
501
+ case GGML_OP_DSV4_HC_COMB: name = "kernel_dsv4_hc_comb_f32"; break;
502
+ case GGML_OP_DSV4_HC_PRE: name = "kernel_dsv4_hc_pre_f32"; break;
503
+ case GGML_OP_DSV4_HC_POST: name = "kernel_dsv4_hc_post_f32"; break;
504
+ default: GGML_ABORT("fatal error");
505
+ }
506
+
507
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
508
+ if (!res.pipeline) {
509
+ res = ggml_metal_library_compile_pipeline(lib, name, name, nullptr);
510
+ }
511
+
512
+ return res;
513
+ }
514
+
515
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_ssm_conv(ggml_metal_library_t lib, const ggml_tensor * op) {
516
+ GGML_ASSERT(op->src[0]->type == GGML_TYPE_F32);
517
+ GGML_ASSERT(op->src[1]->type == GGML_TYPE_F32);
518
+
519
+ GGML_ASSERT(ggml_is_contiguous(op->src[0]));
520
+ GGML_ASSERT(ggml_is_contiguous(op->src[1]));
521
+
522
+ char base[256];
523
+ char name[256];
524
+
525
+ const char * suffix = "";
526
+
527
+ if (op->src[1]->ne[0] % 4 == 0) {
528
+ suffix = "_4";
529
+ }
530
+
531
+ snprintf(base, 256, "kernel_ssm_conv_%s_%s%s", ggml_type_name(op->src[0]->type), ggml_type_name(op->src[1]->type), suffix);
532
+ snprintf(name, 256, "%s", base);
533
+
534
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
535
+ if (!res.pipeline) {
536
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
537
+ }
538
+
539
+ return res;
540
+ }
541
+
542
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_ssm_conv_batched(ggml_metal_library_t lib, const ggml_tensor * op, int ssm_conv_bs) {
543
+ GGML_ASSERT(op->src[0]->type == GGML_TYPE_F32);
544
+ GGML_ASSERT(op->src[1]->type == GGML_TYPE_F32);
545
+
546
+ GGML_ASSERT(ggml_is_contiguous(op->src[0]));
547
+ GGML_ASSERT(ggml_is_contiguous(op->src[1]));
548
+
549
+ char base[256];
550
+ char name[256];
551
+
552
+ const char * suffix = "";
553
+ if (op->src[1]->ne[0] % 4 == 0) {
554
+ suffix = "_4";
555
+ }
556
+
557
+ snprintf(base, 256, "kernel_ssm_conv_%s_%s_batched%s", ggml_type_name(op->src[0]->type), ggml_type_name(op->src[1]->type), suffix);
558
+ snprintf(name, 256, "%s_ssm_conv_bs=%d", base, ssm_conv_bs);
559
+
560
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
561
+ if (!res.pipeline) {
562
+ ggml_metal_cv_t cv = ggml_metal_cv_init();
563
+
564
+ ggml_metal_cv_set_int16(cv, ssm_conv_bs, FC_SSM_CONV + 0);
565
+
566
+ res = ggml_metal_library_compile_pipeline(lib, base, name, cv);
567
+
568
+ ggml_metal_cv_free(cv);
569
+ }
570
+
571
+ return res;
572
+ }
573
+
574
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_ssm_scan(ggml_metal_library_t lib, const ggml_tensor * op) {
575
+ GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
576
+
577
+ char base[256];
578
+ char name[256];
579
+
580
+ const int nsg = (ne00 + 31)/32;
581
+
582
+ snprintf(base, 256, "kernel_ssm_scan_%s", ggml_type_name(op->src[0]->type));
583
+ snprintf(name, 256, "%s_nsg=%d", base, nsg);
584
+
585
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
586
+ if (!res.pipeline) {
587
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
588
+ }
589
+
590
+ // Shared memory layout:
591
+ // - sgptg * NW floats for partial sums (nsg * 32)
592
+ // - sgptg floats for shared_x_dt (nsg)
593
+ // - sgptg floats for shared_dA (nsg)
594
+ // Total: nsg * (32 + 2) floats
595
+ res.smem = (32 + 2)*sizeof(float)*nsg;
596
+
597
+ return res;
598
+ }
599
+
600
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_rwkv(ggml_metal_library_t lib, const ggml_tensor * op) {
601
+ char base[256];
602
+ char name[256];
603
+
604
+ const int64_t C = op->ne[0];
605
+ const int64_t H = op->src[0]->ne[1];
606
+
607
+ switch (op->op) {
608
+ case GGML_OP_RWKV_WKV6:
609
+ {
610
+ GGML_ASSERT(op->src[5]->type == GGML_TYPE_F32);
611
+ GGML_ASSERT(C % H == 0);
612
+ GGML_ASSERT(C / H == 64);
613
+
614
+ snprintf(base, 256, "kernel_rwkv_wkv6_%s", ggml_type_name(op->src[0]->type));
615
+ } break;
616
+ case GGML_OP_RWKV_WKV7:
617
+ {
618
+ GGML_ASSERT(op->src[6]->type == GGML_TYPE_F32);
619
+ GGML_ASSERT(C % H == 0);
620
+ GGML_ASSERT(C / H == 64);
621
+
622
+ snprintf(base, 256, "kernel_rwkv_wkv7_%s", ggml_type_name(op->src[0]->type));
623
+ } break;
624
+ default:
625
+ GGML_ABORT("fatal error");
626
+ }
627
+
628
+ snprintf(name, 256, "%s", base);
629
+
630
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
631
+ if (!res.pipeline) {
632
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
633
+ }
634
+
635
+ return res;
636
+ }
637
+
638
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_gated_delta_net(ggml_metal_library_t lib, const ggml_tensor * op) {
639
+ char base[256];
640
+ char name[256];
641
+
642
+ // v is src[2], dimensions: S_v = ne[0], H = ne[1]
643
+ const int ne20 = op->src[2]->ne[0]; // S_v
644
+ const int ne21 = op->src[2]->ne[1]; // H
645
+ const int ne30 = op->src[3]->ne[0]; // G
646
+ // state is src[5], 4D [S_v, S_v, H_v, n_seqs] (s0 only); K is op param 0.
647
+ const int K = ggml_get_op_params_i32(op, 0);
648
+
649
+ const int nsg = op->src[2]->ne[0]/32;
650
+
651
+ GGML_ASSERT(op->src[5]->type == GGML_TYPE_F32);
652
+ GGML_ASSERT(op->ne[0] == ne20 * ne21);
653
+ GGML_ASSERT(ne20 % 32 == 0);
654
+
655
+ snprintf(base, 256, "kernel_gated_delta_net_%s_%d", ggml_type_name(op->src[0]->type), nsg);
656
+ snprintf(name, 256, "%s_ne20=%d_ne30=%d_K=%d", base, ne20, ne30, K);
657
+
658
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
659
+ if (!res.pipeline) {
660
+ ggml_metal_cv_t cv = ggml_metal_cv_init();
661
+
662
+ ggml_metal_cv_set_int16(cv, ne20, FC_GATED_DELTA_NET + 0);
663
+ ggml_metal_cv_set_int16(cv, ne30, FC_GATED_DELTA_NET + 1);
664
+ ggml_metal_cv_set_int16(cv, K, FC_GATED_DELTA_NET + 2);
665
+
666
+ res = ggml_metal_library_compile_pipeline(lib, base, name, cv);
667
+
668
+ ggml_metal_cv_free(cv);
669
+ }
670
+
671
+ res.nsg = nsg;
672
+
673
+ return res;
674
+ }
675
+
676
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_solve_tri(ggml_metal_library_t lib, const ggml_tensor * op) {
677
+ char base[256];
678
+ char name[256];
679
+
680
+ const int nsg = 8;
681
+ const int n = op->src[1]->ne[1];
682
+ const int k = op->src[1]->ne[0];
683
+
684
+ snprintf(base, 256, "kernel_solve_tri_%s", ggml_type_name(op->src[0]->type));
685
+ snprintf(name, 256, "%s_nsg=%d_n=%d_k=%d", base, nsg, n, k);
686
+
687
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
688
+ if (!res.pipeline) {
689
+ ggml_metal_cv_t cv = ggml_metal_cv_init();
690
+
691
+ ggml_metal_cv_set_int16(cv, nsg, FC_SOLVE_TRI + 0);
692
+ ggml_metal_cv_set_int16(cv, n, FC_SOLVE_TRI + 1);
693
+ ggml_metal_cv_set_int16(cv, k, FC_SOLVE_TRI + 2);
694
+
695
+ res = ggml_metal_library_compile_pipeline(lib, base, name, cv);
696
+
697
+ ggml_metal_cv_free(cv);
698
+ }
699
+
700
+ res.nsg = nsg;
701
+ res.smem = GGML_PAD(GGML_PAD(n, 32)*nsg*sizeof(float), 16);
702
+
703
+ return res;
704
+ }
705
+
706
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mv_ext(ggml_metal_library_t lib, const ggml_tensor * op, int nsg, int nxpsg, int r1ptg) {
707
+ char base[256];
708
+ char name[256];
709
+
710
+ const ggml_type tsrc0 = op->src[0]->type;
711
+ const ggml_type tsrc1 = op->src[1]->type;
712
+ const int ne12 = op->src[1]->ne[2];
713
+ const int r2 = ne12 / op->src[0]->ne[2];
714
+ const int r3 = op->src[1]->ne[3] / op->src[0]->ne[3];
715
+
716
+ GGML_ASSERT(ne12 <= INT16_MAX && r2 <= INT16_MAX && r3 <= INT16_MAX);
717
+
718
+ snprintf(base, 256, "kernel_mul_mv_ext_%s_%s_r1_%d", ggml_type_name(tsrc0), ggml_type_name(tsrc1), r1ptg);
719
+ snprintf(name, 256, "%s_nsg=%d_nxpsg=%d_ne12=%d_r2=%d_r3=%d", base, nsg, nxpsg, ne12, r2, r3);
720
+
721
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
722
+ if (!res.pipeline) {
723
+ ggml_metal_cv_t cv = ggml_metal_cv_init();
724
+
725
+ ggml_metal_cv_set_int16(cv, nsg, FC_MUL_MV + 0);
726
+ ggml_metal_cv_set_int16(cv, nxpsg, FC_MUL_MV + 1);
727
+ ggml_metal_cv_set_int16(cv, (int16_t) ne12, FC_MUL_MV + 2);
728
+ ggml_metal_cv_set_int16(cv, (int16_t) r2, FC_MUL_MV + 3);
729
+ ggml_metal_cv_set_int16(cv, (int16_t) r3, FC_MUL_MV + 4);
730
+
731
+ res = ggml_metal_library_compile_pipeline(lib, base, name, cv);
732
+
733
+ ggml_metal_cv_free(cv);
734
+ }
735
+
736
+ return res;
737
+ }
738
+
739
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm(ggml_metal_library_t lib, const ggml_tensor * op) {
740
+ char base[256];
741
+ char name[256];
742
+
743
+ const ggml_type tsrc0 = op->src[0]->type;
744
+ const ggml_type tsrc1 = op->src[1]->type;
745
+
746
+ const bool bc_inp = op->src[0]->ne[0] % 32 != 0;
747
+
748
+ constexpr int NRA = SZ_SIMDGROUP * N_MM_BLOCK_Y * N_MM_SIMD_GROUP_Y;
749
+ constexpr int NRB = SZ_SIMDGROUP * N_MM_BLOCK_X * N_MM_SIMD_GROUP_X;
750
+
751
+ const bool has_tensor = ggml_metal_device_get_props(ggml_metal_library_get_device(lib))->has_tensor;
752
+
753
+ const bool bc_out = has_tensor
754
+ ? (op->ne[0] % NRA != 0 || op->ne[1] % NRB != 0)
755
+ : (op->ne[0] % 64 != 0 || op->ne[1] % 32 != 0);
756
+
757
+ GGML_ASSERT(op->src[1]->ne[2] <= INT16_MAX && op->src[1]->ne[3] <= INT16_MAX);
758
+ const int16_t ne12 = (int16_t) op->src[1]->ne[2];
759
+ const int16_t ne13 = (int16_t) op->src[1]->ne[3];
760
+ const int16_t r2 = (int16_t) (ne12 / op->src[0]->ne[2]);
761
+ const int16_t r3 = (int16_t) (ne13 / op->src[0]->ne[3]);
762
+
763
+ snprintf(base, 256, "kernel_mul_mm_%s_%s", ggml_type_name(tsrc0), ggml_type_name(tsrc1));
764
+ snprintf(name, 256, "%s_bci=%d_bco=%d_ne12=%d_ne13=%d_r2=%d_r3=%d",
765
+ base, bc_inp, bc_out, ne12, ne13, r2, r3);
766
+
767
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
768
+ if (!res.pipeline) {
769
+ ggml_metal_cv_t cv = ggml_metal_cv_init();
770
+
771
+ ggml_metal_cv_set_bool(cv, bc_inp, FC_MUL_MM + 0);
772
+ ggml_metal_cv_set_bool(cv, bc_out, FC_MUL_MM + 1);
773
+ ggml_metal_cv_set_int16(cv, ne12, FC_MUL_MM + 2);
774
+ ggml_metal_cv_set_int16(cv, ne13, FC_MUL_MM + 3);
775
+ ggml_metal_cv_set_int16(cv, r2, FC_MUL_MM + 4);
776
+ ggml_metal_cv_set_int16(cv, r3, FC_MUL_MM + 5);
777
+
778
+ res = ggml_metal_library_compile_pipeline(lib, base, name, cv);
779
+
780
+ ggml_metal_cv_free(cv);
781
+ }
782
+
783
+ if (has_tensor) {
784
+ res.nr0 = NRA;
785
+ res.nr1 = NRB;
786
+
787
+ const size_t smem_a = NRA * N_MM_NK_TOTAL * sizeof(ggml_fp16_t);
788
+ res.smem = smem_a;
789
+ } else {
790
+ res.nr0 = 64;
791
+ res.nr1 = 32;
792
+
793
+ res.smem = bc_out ? 8192 : (4096 + 2048);
794
+ }
795
+
796
+ res.nsg = N_MM_SIMD_GROUP_X * N_MM_SIMD_GROUP_Y;
797
+
798
+ return res;
799
+ }
800
+
801
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mv(ggml_metal_library_t lib, const ggml_tensor * op) {
802
+ GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
803
+ GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
804
+
805
+ char base[256];
806
+ char name[256];
807
+
808
+ int nsg = 0; // number of simdgroups
809
+ int nr0 = 0; // number of src0 rows per simdgroup
810
+ int nr1 = 1; // number of src1 rows per threadgroup
811
+
812
+ size_t smem = 0; // shared memory
813
+
814
+ const ggml_type tsrc0 = op->src[0]->type;
815
+ const ggml_type tsrc1 = op->src[1]->type;
816
+
817
+ const char * suffix = "";
818
+
819
+ // use custom matrix x vector kernel
820
+ switch (tsrc0) {
821
+ case GGML_TYPE_F32:
822
+ case GGML_TYPE_F16:
823
+ case GGML_TYPE_BF16:
824
+ {
825
+ if (ne00 < 32) {
826
+ nsg = 1;
827
+ nr0 = 32;
828
+ nr1 = 1;
829
+ suffix = "_short";
830
+ } else {
831
+ nsg = std::min(4, (ne00 + 127) / 128);
832
+ nr0 = 2;
833
+ nr1 = 1;
834
+ smem = 32*sizeof(float)*nr0;
835
+ suffix = ne00 % 4 == 0 ? "_4" : "";
836
+ }
837
+ } break;
838
+ case GGML_TYPE_Q1_0:
839
+ {
840
+ nsg = N_SG_Q1_0;
841
+ nr0 = N_R0_Q1_0;
842
+ } break;
843
+ case GGML_TYPE_Q2_0:
844
+ {
845
+ nsg = N_SG_Q2_0;
846
+ nr0 = N_R0_Q2_0;
847
+ } break;
848
+ case GGML_TYPE_Q4_0:
849
+ {
850
+ nsg = N_SG_Q4_0;
851
+ nr0 = N_R0_Q4_0;
852
+ } break;
853
+ case GGML_TYPE_Q4_1:
854
+ {
855
+ nsg = N_SG_Q4_1;
856
+ nr0 = N_R0_Q4_1;
857
+ } break;
858
+ case GGML_TYPE_Q5_0:
859
+ {
860
+ nsg = N_SG_Q5_0;
861
+ nr0 = N_R0_Q5_0;
862
+ } break;
863
+ case GGML_TYPE_Q5_1:
864
+ {
865
+ nsg = N_SG_Q5_1;
866
+ nr0 = N_R0_Q5_1;
867
+ } break;
868
+ case GGML_TYPE_Q8_0:
869
+ {
870
+ nsg = N_SG_Q8_0;
871
+ nr0 = N_R0_Q8_0;
872
+ smem = 32*sizeof(float)*N_R0_Q8_0;
873
+ } break;
874
+ case GGML_TYPE_MXFP4:
875
+ {
876
+ nsg = N_SG_MXFP4;
877
+ nr0 = N_R0_MXFP4;
878
+ smem = 32*sizeof(float);
879
+ } break;
880
+ case GGML_TYPE_Q2_K:
881
+ {
882
+ nsg = N_SG_Q2_K;
883
+ nr0 = N_R0_Q2_K;
884
+ } break;
885
+ case GGML_TYPE_Q3_K:
886
+ {
887
+ nsg = N_SG_Q3_K;
888
+ nr0 = N_R0_Q3_K;
889
+ } break;
890
+ case GGML_TYPE_Q4_K:
891
+ {
892
+ nsg = N_SG_Q4_K;
893
+ nr0 = N_R0_Q4_K;
894
+ } break;
895
+ case GGML_TYPE_Q5_K:
896
+ {
897
+ nsg = N_SG_Q5_K;
898
+ nr0 = N_R0_Q5_K;
899
+ } break;
900
+ case GGML_TYPE_Q6_K:
901
+ {
902
+ nsg = N_SG_Q6_K;
903
+ nr0 = N_R0_Q6_K;
904
+ } break;
905
+ case GGML_TYPE_IQ2_XXS:
906
+ {
907
+ nsg = N_SG_IQ2_XXS;
908
+ nr0 = N_R0_IQ2_XXS;
909
+ smem = 256*8+128;
910
+ } break;
911
+ case GGML_TYPE_IQ2_XS:
912
+ {
913
+ nsg = N_SG_IQ2_XS;
914
+ nr0 = N_R0_IQ2_XS;
915
+ smem = 512*8+128;
916
+ } break;
917
+ case GGML_TYPE_IQ3_XXS:
918
+ {
919
+ nsg = N_SG_IQ3_XXS;
920
+ nr0 = N_R0_IQ3_XXS;
921
+ smem = 256*4+128;
922
+ } break;
923
+ case GGML_TYPE_IQ3_S:
924
+ {
925
+ nsg = N_SG_IQ3_S;
926
+ nr0 = N_R0_IQ3_S;
927
+ smem = 512*4;
928
+ } break;
929
+ case GGML_TYPE_IQ2_S:
930
+ {
931
+ nsg = N_SG_IQ2_S;
932
+ nr0 = N_R0_IQ2_S;
933
+ } break;
934
+ case GGML_TYPE_IQ1_S:
935
+ {
936
+ nsg = N_SG_IQ1_S;
937
+ nr0 = N_R0_IQ1_S;
938
+ } break;
939
+ case GGML_TYPE_IQ1_M:
940
+ {
941
+ nsg = N_SG_IQ1_M;
942
+ nr0 = N_R0_IQ1_M;
943
+ } break;
944
+ case GGML_TYPE_IQ4_NL:
945
+ {
946
+ nsg = N_SG_IQ4_NL;
947
+ nr0 = N_R0_IQ4_NL;
948
+ smem = 32*sizeof(float);
949
+ } break;
950
+ case GGML_TYPE_IQ4_XS:
951
+ {
952
+ nsg = N_SG_IQ4_XS;
953
+ nr0 = N_R0_IQ4_XS;
954
+ smem = 32*sizeof(float);
955
+ } break;
956
+ default:
957
+ {
958
+ GGML_LOG_ERROR("Asserting on type %d\n", (int) tsrc0);
959
+ GGML_ABORT("not implemented");
960
+ }
961
+ };
962
+
963
+ GGML_ASSERT(ne12 <= INT16_MAX && ne13 <= INT16_MAX);
964
+ const int16_t r2 = (int16_t) (ne12 / ne02);
965
+ const int16_t r3 = (int16_t) (ne13 / ne03);
966
+
967
+ snprintf(base, 256, "kernel_mul_mv_%s_%s%s", ggml_type_name(tsrc0), ggml_type_name(tsrc1), suffix);
968
+ snprintf(name, 256, "%s_nsg=%d_ne12=%d_r2=%d_r3=%d", base, nsg, ne12, r2, r3);
969
+
970
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
971
+ if (!res.pipeline) {
972
+ ggml_metal_cv_t cv = ggml_metal_cv_init();
973
+
974
+ ggml_metal_cv_set_int16(cv, nsg, FC_MUL_MV + 0);
975
+ ggml_metal_cv_set_int16(cv, (int16_t) ne12, FC_MUL_MV + 2);
976
+ ggml_metal_cv_set_int16(cv, r2, FC_MUL_MV + 3);
977
+ ggml_metal_cv_set_int16(cv, r3, FC_MUL_MV + 4);
978
+
979
+ res = ggml_metal_library_compile_pipeline(lib, base, name, cv);
980
+
981
+ ggml_metal_cv_free(cv);
982
+ }
983
+
984
+ res.nr0 = nr0;
985
+ res.nr1 = nr1;
986
+ res.nsg = nsg;
987
+ res.smem = smem;
988
+
989
+ return res;
990
+ }
991
+
992
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm_id_map0(ggml_metal_library_t lib, int ne02, int ne20) {
993
+ char base[256];
994
+ char name[256];
995
+
996
+ snprintf(base, 256, "kernel_mul_mm_id_map0_ne20_%d", ne20);
997
+ snprintf(name, 256, "%s_ne02=%d", base, ne02);
998
+
999
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1000
+ if (!res.pipeline) {
1001
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
1002
+ }
1003
+
1004
+ res.smem = (size_t) ne02*ne20*sizeof(uint16_t);
1005
+
1006
+ return res;
1007
+ }
1008
+
1009
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm_id(ggml_metal_library_t lib, const ggml_tensor * op) {
1010
+ char base[256];
1011
+ char name[256];
1012
+
1013
+ const ggml_type tsrc0 = op->src[0]->type;
1014
+ const ggml_type tsrc1 = op->src[1]->type;
1015
+
1016
+ const bool bc_inp = op->src[0]->ne[0] % 32 != 0;
1017
+
1018
+ snprintf(base, 256, "kernel_mul_mm_id_%s_%s", ggml_type_name(tsrc0), ggml_type_name(tsrc1));
1019
+ snprintf(name, 256, "%s_bci=%d", base, bc_inp);
1020
+
1021
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1022
+ if (!res.pipeline) {
1023
+ ggml_metal_cv_t cv = ggml_metal_cv_init();
1024
+
1025
+ ggml_metal_cv_set_bool(cv, bc_inp, FC_MUL_MM + 0);
1026
+
1027
+ res = ggml_metal_library_compile_pipeline(lib, base, name, cv);
1028
+
1029
+ ggml_metal_cv_free(cv);
1030
+ }
1031
+
1032
+ res.smem = 8192;
1033
+
1034
+ return res;
1035
+ }
1036
+
1037
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mv_id(ggml_metal_library_t lib, const ggml_tensor * op) {
1038
+ GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
1039
+ GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
1040
+
1041
+ char base[256];
1042
+ char name[256];
1043
+
1044
+ int nsg = 0; // number of simdgroups
1045
+ int nr0 = 0; // number of src0 rows per simdgroup
1046
+ int nr1 = 1; // number of src1 rows per threadgroup
1047
+
1048
+ size_t smem = 0; // shared memory
1049
+
1050
+ const ggml_type tsrc0 = op->src[0]->type;
1051
+ const ggml_type tsrc1 = op->src[1]->type;
1052
+
1053
+ const char * suffix = "";
1054
+
1055
+ // use custom matrix x vector kernel
1056
+ switch (tsrc0) {
1057
+ case GGML_TYPE_F32:
1058
+ case GGML_TYPE_F16:
1059
+ case GGML_TYPE_BF16:
1060
+ {
1061
+ nsg = std::min(4, (ne00 + 127) / 128);
1062
+ nr0 = 2;
1063
+ nr1 = 1;
1064
+ smem = 32*sizeof(float)*nr0;
1065
+ suffix = ne00 % 4 == 0 ? "_4" : "";
1066
+ } break;
1067
+ case GGML_TYPE_Q1_0:
1068
+ {
1069
+ nsg = N_SG_Q1_0;
1070
+ nr0 = N_R0_Q1_0;
1071
+ } break;
1072
+ case GGML_TYPE_Q2_0:
1073
+ {
1074
+ nsg = N_SG_Q2_0;
1075
+ nr0 = N_R0_Q2_0;
1076
+ } break;
1077
+ case GGML_TYPE_Q4_0:
1078
+ {
1079
+ nsg = N_SG_Q4_0;
1080
+ nr0 = N_R0_Q4_0;
1081
+ } break;
1082
+ case GGML_TYPE_Q4_1:
1083
+ {
1084
+ nsg = N_SG_Q4_1;
1085
+ nr0 = N_R0_Q4_1;
1086
+ } break;
1087
+ case GGML_TYPE_Q5_0:
1088
+ {
1089
+ nsg = N_SG_Q5_0;
1090
+ nr0 = N_R0_Q5_0;
1091
+ } break;
1092
+ case GGML_TYPE_Q5_1:
1093
+ {
1094
+ nsg = N_SG_Q5_1;
1095
+ nr0 = N_R0_Q5_1;
1096
+ } break;
1097
+ case GGML_TYPE_Q8_0:
1098
+ {
1099
+ nsg = N_SG_Q8_0;
1100
+ nr0 = N_R0_Q8_0;
1101
+ smem = 32*sizeof(float)*N_R0_Q8_0;
1102
+ } break;
1103
+ case GGML_TYPE_MXFP4:
1104
+ {
1105
+ nsg = N_SG_MXFP4;
1106
+ nr0 = N_R0_MXFP4;
1107
+ smem = 32*sizeof(float);
1108
+ } break;
1109
+ case GGML_TYPE_Q2_K:
1110
+ {
1111
+ nsg = N_SG_Q2_K;
1112
+ nr0 = N_R0_Q2_K;
1113
+ } break;
1114
+ case GGML_TYPE_Q3_K:
1115
+ {
1116
+ nsg = N_SG_Q3_K;
1117
+ nr0 = N_R0_Q3_K;
1118
+ } break;
1119
+ case GGML_TYPE_Q4_K:
1120
+ {
1121
+ nsg = N_SG_Q4_K;
1122
+ nr0 = N_R0_Q4_K;
1123
+ } break;
1124
+ case GGML_TYPE_Q5_K:
1125
+ {
1126
+ nsg = N_SG_Q5_K;
1127
+ nr0 = N_R0_Q5_K;
1128
+ } break;
1129
+ case GGML_TYPE_Q6_K:
1130
+ {
1131
+ nsg = N_SG_Q6_K;
1132
+ nr0 = N_R0_Q6_K;
1133
+ } break;
1134
+ case GGML_TYPE_IQ2_XXS:
1135
+ {
1136
+ nsg = N_SG_IQ2_XXS;
1137
+ nr0 = N_R0_IQ2_XXS;
1138
+ smem = 256*8+128;
1139
+ } break;
1140
+ case GGML_TYPE_IQ2_XS:
1141
+ {
1142
+ nsg = N_SG_IQ2_XS;
1143
+ nr0 = N_R0_IQ2_XS;
1144
+ smem = 512*8+128;
1145
+ } break;
1146
+ case GGML_TYPE_IQ3_XXS:
1147
+ {
1148
+ nsg = N_SG_IQ3_XXS;
1149
+ nr0 = N_R0_IQ3_XXS;
1150
+ smem = 256*4+128;
1151
+ } break;
1152
+ case GGML_TYPE_IQ3_S:
1153
+ {
1154
+ nsg = N_SG_IQ3_S;
1155
+ nr0 = N_R0_IQ3_S;
1156
+ smem = 512*4;
1157
+ } break;
1158
+ case GGML_TYPE_IQ2_S:
1159
+ {
1160
+ nsg = N_SG_IQ2_S;
1161
+ nr0 = N_R0_IQ2_S;
1162
+ } break;
1163
+ case GGML_TYPE_IQ1_S:
1164
+ {
1165
+ nsg = N_SG_IQ1_S;
1166
+ nr0 = N_R0_IQ1_S;
1167
+ } break;
1168
+ case GGML_TYPE_IQ1_M:
1169
+ {
1170
+ nsg = N_SG_IQ1_M;
1171
+ nr0 = N_R0_IQ1_M;
1172
+ } break;
1173
+ case GGML_TYPE_IQ4_NL:
1174
+ {
1175
+ nsg = N_SG_IQ4_NL;
1176
+ nr0 = N_R0_IQ4_NL;
1177
+ smem = 32*sizeof(float);
1178
+ } break;
1179
+ case GGML_TYPE_IQ4_XS:
1180
+ {
1181
+ nsg = N_SG_IQ4_XS;
1182
+ nr0 = N_R0_IQ4_XS;
1183
+ smem = 32*sizeof(float);
1184
+ } break;
1185
+ default:
1186
+ {
1187
+ GGML_LOG_ERROR("Asserting on type %d\n", (int)op->src[2]->type);
1188
+ GGML_ABORT("not implemented");
1189
+ }
1190
+ };
1191
+
1192
+ snprintf(base, 256, "kernel_mul_mv_id_%s_%s%s", ggml_type_name(tsrc0), ggml_type_name(tsrc1), suffix);
1193
+ snprintf(name, 256, "%s_nsg=%d", base, nsg);
1194
+
1195
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1196
+ if (!res.pipeline) {
1197
+ ggml_metal_cv_t cv = ggml_metal_cv_init();
1198
+
1199
+ ggml_metal_cv_set_int16(cv, nsg, FC_MUL_MV + 0);
1200
+ ggml_metal_cv_set_int16(cv, 1, FC_MUL_MV + 2);
1201
+ ggml_metal_cv_set_int16(cv, 1, FC_MUL_MV + 3);
1202
+ ggml_metal_cv_set_int16(cv, 1, FC_MUL_MV + 4);
1203
+
1204
+ res = ggml_metal_library_compile_pipeline(lib, base, name, cv);
1205
+
1206
+ ggml_metal_cv_free(cv);
1207
+ }
1208
+
1209
+ res.nr0 = nr0;
1210
+ res.nr1 = nr1;
1211
+ res.nsg = nsg;
1212
+ res.smem = smem;
1213
+
1214
+ return res;
1215
+ }
1216
+
1217
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_argmax(ggml_metal_library_t lib, const ggml_tensor * op) {
1218
+ GGML_ASSERT(op->src[0]->type == GGML_TYPE_F32);
1219
+ GGML_ASSERT(ggml_is_contiguous_1(op->src[0]));
1220
+ GGML_ASSERT(op->src[0]->nb[0] == ggml_type_size(op->src[0]->type));
1221
+
1222
+ char base[256];
1223
+ char name[256];
1224
+
1225
+ snprintf(base, 256, "kernel_argmax_%s", ggml_type_name(op->src[0]->type));
1226
+ snprintf(name, 256, "%s", base);
1227
+
1228
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1229
+ if (!res.pipeline) {
1230
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
1231
+ }
1232
+
1233
+ res.smem = 32*(sizeof(float) + sizeof(int32_t));
1234
+
1235
+ return res;
1236
+ }
1237
+
1238
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_argsort(ggml_metal_library_t lib, const ggml_tensor * op) {
1239
+ assert(op->op == GGML_OP_ARGSORT);
1240
+
1241
+ char base[256];
1242
+ char name[256];
1243
+
1244
+ ggml_sort_order order = (ggml_sort_order) op->op_params[0];
1245
+
1246
+ const char * order_str = "undefined";
1247
+ switch (order) {
1248
+ case GGML_SORT_ORDER_ASC: order_str = "asc"; break;
1249
+ case GGML_SORT_ORDER_DESC: order_str = "desc"; break;
1250
+ default: GGML_ABORT("fatal error");
1251
+ };
1252
+
1253
+ snprintf(base, 256, "kernel_argsort_%s_%s_%s", ggml_type_name(op->src[0]->type), ggml_type_name(op->type), order_str);
1254
+ snprintf(name, 256, "%s", base);
1255
+
1256
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1257
+ if (!res.pipeline) {
1258
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
1259
+ }
1260
+
1261
+ return res;
1262
+ }
1263
+
1264
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_argsort_merge(ggml_metal_library_t lib, const ggml_tensor * op) {
1265
+ assert(op->op == GGML_OP_ARGSORT);
1266
+
1267
+ char base[256];
1268
+ char name[256];
1269
+
1270
+ ggml_sort_order order = (ggml_sort_order) op->op_params[0];
1271
+
1272
+ const char * order_str = "undefined";
1273
+ switch (order) {
1274
+ case GGML_SORT_ORDER_ASC: order_str = "asc"; break;
1275
+ case GGML_SORT_ORDER_DESC: order_str = "desc"; break;
1276
+ default: GGML_ABORT("fatal error");
1277
+ };
1278
+
1279
+ snprintf(base, 256, "kernel_argsort_merge_%s_%s_%s", ggml_type_name(op->src[0]->type), ggml_type_name(op->type), order_str);
1280
+ snprintf(name, 256, "%s", base);
1281
+
1282
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1283
+ if (!res.pipeline) {
1284
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
1285
+ }
1286
+
1287
+ return res;
1288
+ }
1289
+
1290
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_fwht(ggml_metal_library_t lib, int n) {
1291
+ char base[256];
1292
+ char name[256];
1293
+
1294
+ snprintf(base, 256, "kernel_fwht_f32_%d", n);
1295
+ snprintf(name, 256, "%s", base);
1296
+
1297
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1298
+ if (!res.pipeline) {
1299
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
1300
+ }
1301
+
1302
+ return res;
1303
+ }
1304
+
1305
+ // note: reuse the argsort kernel for top_k
1306
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_top_k(ggml_metal_library_t lib, const ggml_tensor * op) {
1307
+ assert(op->op == GGML_OP_TOP_K);
1308
+
1309
+ char base[256];
1310
+ char name[256];
1311
+
1312
+ // note: the top_k kernel is always descending order
1313
+ ggml_sort_order order = GGML_SORT_ORDER_DESC;
1314
+
1315
+ const char * order_str = "undefined";
1316
+ switch (order) {
1317
+ case GGML_SORT_ORDER_ASC: order_str = "asc"; break;
1318
+ case GGML_SORT_ORDER_DESC: order_str = "desc"; break;
1319
+ default: GGML_ABORT("fatal error");
1320
+ };
1321
+
1322
+ snprintf(base, 256, "kernel_argsort_%s_%s_%s", ggml_type_name(op->src[0]->type), ggml_type_name(op->type), order_str);
1323
+ snprintf(name, 256, "%s", base);
1324
+
1325
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1326
+ if (!res.pipeline) {
1327
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
1328
+ }
1329
+
1330
+ return res;
1331
+ }
1332
+
1333
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_top_k_merge(ggml_metal_library_t lib, const ggml_tensor * op) {
1334
+ assert(op->op == GGML_OP_TOP_K);
1335
+
1336
+ char base[256];
1337
+ char name[256];
1338
+
1339
+ ggml_sort_order order = GGML_SORT_ORDER_DESC;
1340
+
1341
+ const char * order_str = "undefined";
1342
+ switch (order) {
1343
+ case GGML_SORT_ORDER_ASC: order_str = "asc"; break;
1344
+ case GGML_SORT_ORDER_DESC: order_str = "desc"; break;
1345
+ default: GGML_ABORT("fatal error");
1346
+ };
1347
+
1348
+ snprintf(base, 256, "kernel_argsort_merge_%s_%s_%s", ggml_type_name(op->src[0]->type), ggml_type_name(op->type), order_str);
1349
+ snprintf(name, 256, "%s", base);
1350
+
1351
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1352
+ if (!res.pipeline) {
1353
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
1354
+ }
1355
+
1356
+ return res;
1357
+ }
1358
+
1359
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_pad(
1360
+ ggml_metal_library_t lib,
1361
+ const struct ggml_tensor * op,
1362
+ bool has_mask,
1363
+ int32_t ncpsg) {
1364
+ assert(op->op == GGML_OP_FLASH_ATTN_EXT);
1365
+ GGML_UNUSED(op);
1366
+
1367
+ char base[256];
1368
+ char name[256];
1369
+
1370
+ snprintf(base, 256, "kernel_%s",
1371
+ "flash_attn_ext_pad");
1372
+
1373
+ snprintf(name, 256, "%s_mask=%d_ncpsg=%d",
1374
+ base,
1375
+ has_mask,
1376
+ ncpsg);
1377
+
1378
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1379
+ if (!res.pipeline) {
1380
+ ggml_metal_cv_t cv = ggml_metal_cv_init();
1381
+
1382
+ ggml_metal_cv_set_bool(cv, has_mask, FC_FLASH_ATTN_EXT_PAD + 0);
1383
+ //ggml_metal_cv_set_bool(cv, has_sinks, FC_FLASH_ATTN_EXT_PAD + 1);
1384
+ //ggml_metal_cv_set_bool(cv, has_bias, FC_FLASH_ATTN_EXT_PAD + 2);
1385
+ //ggml_metal_cv_set_bool(cv, has_scap, FC_FLASH_ATTN_EXT_PAD + 3);
1386
+
1387
+ //ggml_metal_cv_set_int32(cv, ns10, FC_FLASH_ATTN_EXT_PAD + 20);
1388
+ //ggml_metal_cv_set_int32(cv, ns20, FC_FLASH_ATTN_EXT_PAD + 21);
1389
+ //ggml_metal_cv_set_int32(cv, nsg, FC_FLASH_ATTN_EXT_PAD + 22);
1390
+ //ggml_metal_cv_set_int32(cv, nwg, FC_FLASH_ATTN_EXT_PAD + 23);
1391
+ //ggml_metal_cv_set_int32(cv, nqptg, FC_FLASH_ATTN_EXT_PAD + 24);
1392
+ ggml_metal_cv_set_int32(cv, ncpsg, FC_FLASH_ATTN_EXT_PAD + 25);
1393
+
1394
+ res = ggml_metal_library_compile_pipeline(lib, base, name, cv);
1395
+
1396
+ ggml_metal_cv_free(cv);
1397
+ }
1398
+
1399
+ return res;
1400
+ }
1401
+
1402
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_blk(
1403
+ ggml_metal_library_t lib,
1404
+ const struct ggml_tensor * op,
1405
+ int32_t nqptg,
1406
+ int32_t ncpsg) {
1407
+ assert(op->op == GGML_OP_FLASH_ATTN_EXT);
1408
+ GGML_UNUSED(op);
1409
+
1410
+ char base[256];
1411
+ char name[256];
1412
+
1413
+ snprintf(base, 256, "kernel_%s",
1414
+ "flash_attn_ext_blk");
1415
+
1416
+ snprintf(name, 256, "%s_nqptg=%d_ncpsg=%d",
1417
+ base,
1418
+ nqptg,
1419
+ ncpsg);
1420
+
1421
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1422
+ if (!res.pipeline) {
1423
+ ggml_metal_cv_t cv = ggml_metal_cv_init();
1424
+
1425
+ //ggml_metal_cv_set_bool(cv, has_mask, FC_FLASH_ATTN_EXT_BLK + 0);
1426
+ //ggml_metal_cv_set_bool(cv, has_sinks, FC_FLASH_ATTN_EXT_BLK + 1);
1427
+ //ggml_metal_cv_set_bool(cv, has_bias, FC_FLASH_ATTN_EXT_BLK + 2);
1428
+ //ggml_metal_cv_set_bool(cv, has_scap, FC_FLASH_ATTN_EXT_BLK + 3);
1429
+
1430
+ //ggml_metal_cv_set_int32(cv, ns10, FC_FLASH_ATTN_EXT_BLK + 20);
1431
+ //ggml_metal_cv_set_int32(cv, ns20, FC_FLASH_ATTN_EXT_BLK + 21);
1432
+ //ggml_metal_cv_set_int32(cv, nsg, FC_FLASH_ATTN_EXT_BLK + 22);
1433
+ //ggml_metal_cv_set_int32(cv, nwg, FC_FLASH_ATTN_EXT_BLK + 23);
1434
+ ggml_metal_cv_set_int32(cv, nqptg, FC_FLASH_ATTN_EXT_BLK + 24);
1435
+ ggml_metal_cv_set_int32(cv, ncpsg, FC_FLASH_ATTN_EXT_BLK + 25);
1436
+
1437
+ res = ggml_metal_library_compile_pipeline(lib, base, name, cv);
1438
+
1439
+ ggml_metal_cv_free(cv);
1440
+ }
1441
+
1442
+ return res;
1443
+ }
1444
+
1445
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext(
1446
+ ggml_metal_library_t lib,
1447
+ const ggml_tensor * op,
1448
+ bool has_mask,
1449
+ bool has_sinks,
1450
+ bool has_bias,
1451
+ bool has_scap,
1452
+ bool has_kvpad,
1453
+ int32_t nsg) {
1454
+ assert(op->op == GGML_OP_FLASH_ATTN_EXT);
1455
+
1456
+ char base[256];
1457
+ char name[256];
1458
+
1459
+ const int32_t dk = (int32_t) op->src[1]->ne[0];
1460
+ const int32_t dv = (int32_t) op->src[2]->ne[0];
1461
+
1462
+ const int32_t ns10 = op->src[1]->nb[1]/op->src[1]->nb[0];
1463
+ const int32_t ns20 = op->src[2]->nb[1]/op->src[2]->nb[0];
1464
+
1465
+ // do bounds checks for the mask?
1466
+ const bool bc_mask = op->src[3] && (op->src[3]->ne[1] % 8 != 0);
1467
+
1468
+ snprintf(base, 256, "kernel_%s_%s_dk%d_dv%d",
1469
+ "flash_attn_ext",
1470
+ ggml_type_name(op->src[1]->type),
1471
+ dk,
1472
+ dv);
1473
+
1474
+ snprintf(name, 256, "%s_mask=%d_sinks=%d_bias=%d_scap=%d_kvpad=%d_bcm=%d_ns10=%d_ns20=%d_nsg=%d",
1475
+ base,
1476
+ has_mask,
1477
+ has_sinks,
1478
+ has_bias,
1479
+ has_scap,
1480
+ has_kvpad,
1481
+ bc_mask,
1482
+ ns10,
1483
+ ns20,
1484
+ nsg);
1485
+
1486
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1487
+ if (!res.pipeline) {
1488
+ ggml_metal_cv_t cv = ggml_metal_cv_init();
1489
+
1490
+ ggml_metal_cv_set_bool(cv, has_mask, FC_FLASH_ATTN_EXT + 0);
1491
+ ggml_metal_cv_set_bool(cv, has_sinks, FC_FLASH_ATTN_EXT + 1);
1492
+ ggml_metal_cv_set_bool(cv, has_bias, FC_FLASH_ATTN_EXT + 2);
1493
+ ggml_metal_cv_set_bool(cv, has_scap, FC_FLASH_ATTN_EXT + 3);
1494
+ ggml_metal_cv_set_bool(cv, has_kvpad, FC_FLASH_ATTN_EXT + 4);
1495
+
1496
+ ggml_metal_cv_set_bool(cv, bc_mask, FC_FLASH_ATTN_EXT + 10);
1497
+
1498
+ ggml_metal_cv_set_int32(cv, ns10, FC_FLASH_ATTN_EXT + 20);
1499
+ ggml_metal_cv_set_int32(cv, ns20, FC_FLASH_ATTN_EXT + 21);
1500
+ ggml_metal_cv_set_int32(cv, nsg, FC_FLASH_ATTN_EXT + 22);
1501
+
1502
+ res = ggml_metal_library_compile_pipeline(lib, base, name, cv);
1503
+
1504
+ ggml_metal_cv_free(cv);
1505
+ }
1506
+
1507
+ return res;
1508
+ }
1509
+
1510
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_vec(
1511
+ ggml_metal_library_t lib,
1512
+ const ggml_tensor * op,
1513
+ bool has_mask,
1514
+ bool has_sinks,
1515
+ bool has_bias,
1516
+ bool has_scap,
1517
+ bool has_kvpad,
1518
+ int32_t nsg,
1519
+ int32_t nwg) {
1520
+ assert(op->op == GGML_OP_FLASH_ATTN_EXT);
1521
+
1522
+ char base[256];
1523
+ char name[256];
1524
+
1525
+ const int32_t dk = (int32_t) op->src[1]->ne[0];
1526
+ const int32_t dv = (int32_t) op->src[2]->ne[0];
1527
+
1528
+ const int32_t ns10 = op->src[1]->nb[1]/op->src[1]->nb[0];
1529
+ const int32_t ns20 = op->src[2]->nb[1]/op->src[2]->nb[0];
1530
+
1531
+ snprintf(base, 256, "kernel_%s_%s_dk%d_dv%d",
1532
+ "flash_attn_ext_vec",
1533
+ ggml_type_name(op->src[1]->type),
1534
+ dk,
1535
+ dv);
1536
+
1537
+ snprintf(name, 256, "%s_mask=%d_sink=%d_bias=%d_scap=%d_kvpad=%d_ns10=%d_ns20=%d_nsg=%d_nwg=%d",
1538
+ base,
1539
+ has_mask,
1540
+ has_sinks,
1541
+ has_bias,
1542
+ has_scap,
1543
+ has_kvpad,
1544
+ ns10,
1545
+ ns20,
1546
+ nsg, nwg);
1547
+
1548
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1549
+ if (!res.pipeline) {
1550
+ ggml_metal_cv_t cv = ggml_metal_cv_init();
1551
+
1552
+ ggml_metal_cv_set_bool(cv, has_mask, FC_FLASH_ATTN_EXT_VEC + 0);
1553
+ ggml_metal_cv_set_bool(cv, has_sinks, FC_FLASH_ATTN_EXT_VEC + 1);
1554
+ ggml_metal_cv_set_bool(cv, has_bias, FC_FLASH_ATTN_EXT_VEC + 2);
1555
+ ggml_metal_cv_set_bool(cv, has_scap, FC_FLASH_ATTN_EXT_VEC + 3);
1556
+ ggml_metal_cv_set_bool(cv, has_kvpad, FC_FLASH_ATTN_EXT_VEC + 4);
1557
+
1558
+ ggml_metal_cv_set_int32(cv, ns10, FC_FLASH_ATTN_EXT_VEC + 20);
1559
+ ggml_metal_cv_set_int32(cv, ns20, FC_FLASH_ATTN_EXT_VEC + 21);
1560
+ ggml_metal_cv_set_int32(cv, nsg, FC_FLASH_ATTN_EXT_VEC + 22);
1561
+ ggml_metal_cv_set_int32(cv, nwg, FC_FLASH_ATTN_EXT_VEC + 23);
1562
+
1563
+ res = ggml_metal_library_compile_pipeline(lib, base, name, cv);
1564
+
1565
+ ggml_metal_cv_free(cv);
1566
+ }
1567
+
1568
+ return res;
1569
+ }
1570
+
1571
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_vec_reduce(
1572
+ ggml_metal_library_t lib,
1573
+ const ggml_tensor * op,
1574
+ int32_t dv,
1575
+ int32_t nwg) {
1576
+ assert(op->op == GGML_OP_FLASH_ATTN_EXT);
1577
+
1578
+ char base[256];
1579
+ char name[256];
1580
+
1581
+ snprintf(base, 256, "kernel_flash_attn_ext_vec_reduce");
1582
+ snprintf(name, 256, "%s_dv=%d_nwg=%d", base, dv, nwg);
1583
+
1584
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1585
+ if (!res.pipeline) {
1586
+ ggml_metal_cv_t cv = ggml_metal_cv_init();
1587
+
1588
+ ggml_metal_cv_set_int32(cv, dv, FC_FLASH_ATTN_EXT_VEC_REDUCE + 0);
1589
+ ggml_metal_cv_set_int32(cv, nwg, FC_FLASH_ATTN_EXT_VEC_REDUCE + 1);
1590
+
1591
+ res = ggml_metal_library_compile_pipeline(lib, base, name, cv);
1592
+
1593
+ ggml_metal_cv_free(cv);
1594
+ }
1595
+
1596
+ return res;
1597
+
1598
+ GGML_UNUSED(op);
1599
+ }
1600
+
1601
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_bin(ggml_metal_library_t lib, const ggml_tensor * op, int32_t n_fuse) {
1602
+ char base[256];
1603
+ char name[256];
1604
+
1605
+ int op_num = -1;
1606
+
1607
+ switch (op->op) {
1608
+ case GGML_OP_ADD: op_num = 0; break;
1609
+ case GGML_OP_SUB: op_num = 1; break;
1610
+ case GGML_OP_MUL: op_num = 2; break;
1611
+ case GGML_OP_DIV: op_num = 3; break;
1612
+ default: GGML_ABORT("fatal error");
1613
+ };
1614
+
1615
+ const char * t0_str = ggml_type_name(op->src[0]->type);
1616
+ const char * t1_str = ggml_type_name(op->src[1]->type);
1617
+ const char * t_str = ggml_type_name(op->type);
1618
+
1619
+ const bool is_c4 = (op->src[0]->ne[0] % 4 == 0) && (op->src[1]->ne[0] % 4 == 0);
1620
+
1621
+ const bool is_cb = op->src[0]->ne[0] != op->src[1]->ne[0];
1622
+ const bool is_rb = ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op->src[1]) && (ggml_nrows(op->src[1]) == 1) && ggml_nelements(op) < 65536;
1623
+
1624
+ snprintf(base, 256, "kernel_bin_fuse_%s_%s_%s%s", t0_str, t1_str, t_str, is_c4 ? "_4" : "");
1625
+ snprintf(name, 256, "%s_op=%d_nf=%d_rb=%d_cb=%d", base, op_num, n_fuse, is_rb, is_cb);
1626
+
1627
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1628
+ if (!res.pipeline) {
1629
+ ggml_metal_cv_t cv = ggml_metal_cv_init();
1630
+
1631
+ ggml_metal_cv_set_int16(cv, op_num, FC_BIN + 0);
1632
+ ggml_metal_cv_set_int16(cv, n_fuse, FC_BIN + 1);
1633
+ ggml_metal_cv_set_bool (cv, is_rb, FC_BIN + 2);
1634
+ ggml_metal_cv_set_bool (cv, is_cb, FC_BIN + 3);
1635
+
1636
+ res = ggml_metal_library_compile_pipeline(lib, base, name, cv);
1637
+
1638
+ ggml_metal_cv_free(cv);
1639
+ }
1640
+
1641
+ res.c4 = is_c4;
1642
+ res.cnt = is_rb;
1643
+
1644
+ return res;
1645
+ }
1646
+
1647
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_bin_one(ggml_metal_library_t lib, ggml_op op) {
1648
+ char base[256];
1649
+ char name[256];
1650
+
1651
+ int op_num = -1;
1652
+
1653
+ switch (op) {
1654
+ case GGML_OP_ADD: op_num = 0; break;
1655
+ case GGML_OP_SUB: op_num = 1; break;
1656
+ case GGML_OP_MUL: op_num = 2; break;
1657
+ case GGML_OP_DIV: op_num = 3; break;
1658
+ default: GGML_ABORT("fatal error");
1659
+ };
1660
+
1661
+ snprintf(base, 256, "kernel_bin_fuse_%s_%s_%s", "f32", "f32", "f32");
1662
+ snprintf(name, 256, "%s_op=%d_nf=%d", base, op_num, 1);
1663
+
1664
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1665
+ if (!res.pipeline) {
1666
+ ggml_metal_cv_t cv = ggml_metal_cv_init();
1667
+
1668
+ ggml_metal_cv_set_int16(cv, op_num, FC_BIN + 0);
1669
+ ggml_metal_cv_set_int16(cv, 1, FC_BIN + 1);
1670
+ ggml_metal_cv_set_bool (cv, false, FC_BIN + 2);
1671
+
1672
+ res = ggml_metal_library_compile_pipeline(lib, base, name, cv);
1673
+
1674
+ ggml_metal_cv_free(cv);
1675
+ }
1676
+
1677
+ return res;
1678
+ }
1679
+
1680
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_l2_norm(ggml_metal_library_t lib, const ggml_tensor * op) {
1681
+ assert(op->op == GGML_OP_L2_NORM);
1682
+
1683
+ char base[256];
1684
+ char name[256];
1685
+
1686
+ const bool is_c4 = op->src[0]->ne[0] % 4 == 0;
1687
+
1688
+ const char * t0_str = ggml_type_name(op->src[0]->type);
1689
+ const char * t_str = ggml_type_name(op->type);
1690
+
1691
+ snprintf(base, 256, "kernel_l2_norm_%s_%s%s", t0_str, t_str, is_c4 ? "_4" : "");
1692
+ snprintf(name, 256, "%s", base);
1693
+
1694
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1695
+ if (!res.pipeline) {
1696
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
1697
+ }
1698
+
1699
+ res.c4 = is_c4;
1700
+ res.smem = 32*sizeof(float);
1701
+
1702
+ return res;
1703
+ }
1704
+
1705
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_group_norm(ggml_metal_library_t lib, const ggml_tensor * op) {
1706
+ assert(op->op == GGML_OP_GROUP_NORM);
1707
+
1708
+ GGML_ASSERT(ggml_is_contiguous(op->src[0]));
1709
+
1710
+ char base[256];
1711
+ char name[256];
1712
+
1713
+ snprintf(base, 256, "kernel_group_norm_f32");
1714
+ snprintf(name, 256, "%s", base);
1715
+
1716
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1717
+ if (!res.pipeline) {
1718
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
1719
+ }
1720
+
1721
+ res.smem = 32*sizeof(float);
1722
+
1723
+ return res;
1724
+ }
1725
+
1726
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_norm(ggml_metal_library_t lib, const ggml_tensor * op, int n_fuse) {
1727
+ assert(op->op == GGML_OP_NORM || op->op == GGML_OP_RMS_NORM);
1728
+
1729
+ GGML_ASSERT(ggml_is_contiguous_rows(op->src[0]));
1730
+
1731
+ char base[256];
1732
+ char name[256];
1733
+
1734
+ const char * suffix = "";
1735
+ if (op->ne[0] % 4 == 0) {
1736
+ suffix = "_4";
1737
+ }
1738
+
1739
+ switch (op->op) {
1740
+ case GGML_OP_NORM:
1741
+ switch (n_fuse) {
1742
+ case 1: snprintf(base, 256, "kernel_norm_f32%s", suffix); break;
1743
+ case 2: snprintf(base, 256, "kernel_norm_mul_f32%s", suffix); break;
1744
+ case 3: snprintf(base, 256, "kernel_norm_mul_add_f32%s", suffix); break;
1745
+ default: GGML_ABORT("fatal error");
1746
+ } break;
1747
+ case GGML_OP_RMS_NORM:
1748
+ switch (n_fuse) {
1749
+ case 1: snprintf(base, 256, "kernel_rms_norm_f32%s", suffix); break;
1750
+ case 2: snprintf(base, 256, "kernel_rms_norm_mul_f32%s", suffix); break;
1751
+ case 3: snprintf(base, 256, "kernel_rms_norm_mul_add_f32%s", suffix); break;
1752
+ default: GGML_ABORT("fatal error");
1753
+ } break;
1754
+ default: GGML_ABORT("fatal error");
1755
+ }
1756
+
1757
+ snprintf(name, 256, "%s", base);
1758
+
1759
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1760
+ if (!res.pipeline) {
1761
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
1762
+ }
1763
+
1764
+ res.smem = 32*sizeof(float);
1765
+
1766
+ return res;
1767
+ }
1768
+
1769
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_rope(ggml_metal_library_t lib, const ggml_tensor * op) {
1770
+ assert(op->op == GGML_OP_ROPE || op->op == GGML_OP_ROPE_BACK);
1771
+
1772
+ const bool is_back = op->op == GGML_OP_ROPE_BACK;
1773
+
1774
+ char base[256];
1775
+ char name[256];
1776
+
1777
+ const int mode = ((const int32_t *) op->op_params)[2];
1778
+
1779
+ const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
1780
+ const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE;
1781
+ const bool is_imrope = mode == GGML_ROPE_TYPE_IMROPE;
1782
+ const bool is_vision = mode == GGML_ROPE_TYPE_VISION;
1783
+
1784
+ if (is_neox) {
1785
+ snprintf(base, 256, "kernel_rope_neox_%s", ggml_type_name(op->src[0]->type));
1786
+ } else if ((is_mrope || is_imrope) && !is_vision) {
1787
+ GGML_ASSERT(op->src[1]->ne[0]*4 >= op->src[0]->ne[2]); // need at least 4 pos per token
1788
+ snprintf(base, 256, "kernel_rope_multi_%s", ggml_type_name(op->src[0]->type));
1789
+ } else if (is_vision) {
1790
+ GGML_ASSERT(op->src[1]->ne[0]*4 >= op->src[0]->ne[2]); // need at least 4 pos per token
1791
+ snprintf(base, 256, "kernel_rope_vision_%s", ggml_type_name(op->src[0]->type));
1792
+ } else {
1793
+ snprintf(base, 256, "kernel_rope_norm_%s", ggml_type_name(op->src[0]->type));
1794
+ }
1795
+
1796
+ snprintf(name, 256, "%s_imrope=%d_is_back=%d", base, is_imrope ? 1 : 0, is_back ? 1 : 0);
1797
+
1798
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1799
+ if (!res.pipeline) {
1800
+ ggml_metal_cv_t cv = ggml_metal_cv_init();
1801
+
1802
+ ggml_metal_cv_set_bool(cv, is_imrope, FC_ROPE + 0);
1803
+ ggml_metal_cv_set_bool(cv, is_back, FC_ROPE + 1);
1804
+
1805
+ res = ggml_metal_library_compile_pipeline(lib, base, name, cv);
1806
+
1807
+ ggml_metal_cv_free(cv);
1808
+ }
1809
+
1810
+ return res;
1811
+ }
1812
+
1813
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_im2col(ggml_metal_library_t lib, const ggml_tensor * op) {
1814
+ assert(op->op == GGML_OP_IM2COL);
1815
+
1816
+ GGML_TENSOR_LOCALS(int64_t, ne0, op->src[0], ne);
1817
+
1818
+ GGML_ASSERT(ggml_is_contiguous(op->src[1]));
1819
+ GGML_ASSERT(op->src[1]->type == GGML_TYPE_F32);
1820
+ GGML_ASSERT(op->type == GGML_TYPE_F16 || op->type == GGML_TYPE_F32);
1821
+
1822
+ const bool is_2D = ((const int32_t *)(op->op_params))[6] == 1;
1823
+ const int64_t KH = is_2D ? ne01 : 1;
1824
+ const int64_t KW = ne00;
1825
+
1826
+ char base[256];
1827
+ char name[256];
1828
+
1829
+ if (KH*KW <= 1024) {
1830
+ snprintf(base, 256, "kernel_im2col_%s", ggml_type_name(op->type));
1831
+ } else {
1832
+ snprintf(base, 256, "kernel_im2col_ext_%s", ggml_type_name(op->type));
1833
+ }
1834
+ snprintf(name, 256, "%s", base);
1835
+
1836
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1837
+ if (!res.pipeline) {
1838
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
1839
+ }
1840
+
1841
+ return res;
1842
+ }
1843
+
1844
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_conv_transpose_1d(ggml_metal_library_t lib, const ggml_tensor * op) {
1845
+ assert(op->op == GGML_OP_CONV_TRANSPOSE_1D);
1846
+
1847
+ GGML_ASSERT(ggml_is_contiguous(op->src[0]));
1848
+ GGML_ASSERT(ggml_is_contiguous(op->src[1]));
1849
+ GGML_ASSERT(op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_F32);
1850
+ GGML_ASSERT(op->src[1]->type == GGML_TYPE_F32);
1851
+ GGML_ASSERT(op->type == GGML_TYPE_F32);
1852
+
1853
+ char base[256];
1854
+ char name[256];
1855
+
1856
+ snprintf(base, 256, "kernel_conv_transpose_1d_%s_%s", ggml_type_name(op->src[0]->type), ggml_type_name(op->src[1]->type));
1857
+ snprintf(name, 256, "%s", base);
1858
+
1859
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1860
+ if (!res.pipeline) {
1861
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
1862
+ }
1863
+
1864
+ return res;
1865
+ }
1866
+
1867
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_col2im_1d(ggml_metal_library_t lib, const ggml_tensor * op) {
1868
+ assert(op->op == GGML_OP_COL2IM_1D);
1869
+
1870
+ GGML_ASSERT(ggml_is_contiguous(op->src[0]));
1871
+ GGML_ASSERT(op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_BF16);
1872
+
1873
+ char base[256];
1874
+ char name[256];
1875
+
1876
+ snprintf(base, 256, "kernel_col2im_1d_%s", ggml_type_name(op->src[0]->type));
1877
+ snprintf(name, 256, "%s", base);
1878
+
1879
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1880
+ if (!res.pipeline) {
1881
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
1882
+ }
1883
+
1884
+ return res;
1885
+ }
1886
+
1887
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_snake(ggml_metal_library_t lib, enum ggml_type type) {
1888
+ GGML_ASSERT(type == GGML_TYPE_F32 || type == GGML_TYPE_F16 || type == GGML_TYPE_BF16);
1889
+
1890
+ char base[256];
1891
+ char name[256];
1892
+
1893
+ snprintf(base, 256, "kernel_snake_%s", ggml_type_name(type));
1894
+ snprintf(name, 256, "%s", base);
1895
+
1896
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1897
+ if (!res.pipeline) {
1898
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
1899
+ }
1900
+
1901
+ return res;
1902
+ }
1903
+
1904
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_conv_transpose_2d(ggml_metal_library_t lib, const ggml_tensor * op) {
1905
+ assert(op->op == GGML_OP_CONV_TRANSPOSE_2D);
1906
+
1907
+ GGML_ASSERT(ggml_is_contiguous(op->src[0]));
1908
+ GGML_ASSERT(ggml_is_contiguous(op->src[1]));
1909
+ GGML_ASSERT(op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_F32);
1910
+ GGML_ASSERT(op->src[1]->type == GGML_TYPE_F32);
1911
+ GGML_ASSERT(op->type == GGML_TYPE_F32);
1912
+
1913
+ char base[256];
1914
+ char name[256];
1915
+
1916
+ snprintf(base, 256, "kernel_conv_transpose_2d_%s_%s", ggml_type_name(op->src[0]->type), ggml_type_name(op->src[1]->type));
1917
+ snprintf(name, 256, "%s", base);
1918
+
1919
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1920
+ if (!res.pipeline) {
1921
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
1922
+ }
1923
+
1924
+ return res;
1925
+ }
1926
+
1927
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_conv_2d(ggml_metal_library_t lib, const ggml_tensor * op) {
1928
+ assert(op->op == GGML_OP_CONV_2D);
1929
+
1930
+ GGML_ASSERT(ggml_is_contiguous(op->src[0]));
1931
+ GGML_ASSERT(op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_F32);
1932
+ GGML_ASSERT(op->src[1]->type == GGML_TYPE_F32);
1933
+ GGML_ASSERT(op->type == GGML_TYPE_F32);
1934
+
1935
+ char base[256];
1936
+ char name[256];
1937
+
1938
+ snprintf(base, 256, "kernel_conv_2d_%s_%s", ggml_type_name(op->src[0]->type), ggml_type_name(op->src[1]->type));
1939
+ snprintf(name, 256, "%s", base);
1940
+
1941
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1942
+ if (!res.pipeline) {
1943
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
1944
+ }
1945
+
1946
+ return res;
1947
+ }
1948
+
1949
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_conv_2d_dw(ggml_metal_library_t lib, const ggml_tensor * op, bool tiled) {
1950
+ assert(op->op == GGML_OP_CONV_2D_DW);
1951
+
1952
+ GGML_ASSERT(op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_F32);
1953
+ GGML_ASSERT(op->src[1]->type == GGML_TYPE_F32);
1954
+ GGML_ASSERT(op->type == GGML_TYPE_F32);
1955
+
1956
+ char base[256];
1957
+ char name[256];
1958
+
1959
+ snprintf(base, 256, "kernel_conv_2d_dw%s_%s_%s",
1960
+ tiled ? "_tiled" : "",
1961
+ ggml_type_name(op->src[0]->type), ggml_type_name(op->src[1]->type));
1962
+ snprintf(name, 256, "%s", base);
1963
+
1964
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1965
+ if (!res.pipeline) {
1966
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
1967
+ }
1968
+
1969
+ return res;
1970
+ }
1971
+
1972
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_conv_3d(ggml_metal_library_t lib, const ggml_tensor * op) {
1973
+ assert(op->op == GGML_OP_CONV_3D);
1974
+
1975
+ GGML_ASSERT(ggml_is_contiguous(op->src[0]));
1976
+ GGML_ASSERT(op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_F32);
1977
+ GGML_ASSERT(op->src[1]->type == GGML_TYPE_F32);
1978
+ GGML_ASSERT(op->type == GGML_TYPE_F32);
1979
+
1980
+ char base[256];
1981
+ char name[256];
1982
+
1983
+ snprintf(base, 256, "kernel_conv_3d_%s_%s", ggml_type_name(op->src[0]->type), ggml_type_name(op->src[1]->type));
1984
+ snprintf(name, 256, "%s", base);
1985
+
1986
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
1987
+ if (!res.pipeline) {
1988
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
1989
+ }
1990
+
1991
+ return res;
1992
+ }
1993
+
1994
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_upscale(ggml_metal_library_t lib, const ggml_tensor * op) {
1995
+ assert(op->op == GGML_OP_UPSCALE);
1996
+
1997
+ char base[256];
1998
+ char name[256];
1999
+
2000
+ const int32_t mode_flags = ggml_get_op_params_i32(op, 0);
2001
+ const ggml_scale_mode mode = (ggml_scale_mode) (mode_flags & 0xFF);
2002
+
2003
+ const bool antialias = (mode_flags & GGML_SCALE_FLAG_ANTIALIAS);
2004
+
2005
+ if (mode == GGML_SCALE_MODE_BILINEAR) {
2006
+ snprintf(base, 256, "kernel_upscale_bilinear_%s", ggml_type_name(op->src[0]->type));
2007
+ } else if (mode == GGML_SCALE_MODE_BICUBIC) {
2008
+ snprintf(base, 256, "kernel_upscale_bicubic_%s", ggml_type_name(op->src[0]->type));
2009
+ } else {
2010
+ snprintf(base, 256, "kernel_upscale_nearest_%s", ggml_type_name(op->src[0]->type));
2011
+ }
2012
+ snprintf(name, 256, "%s_aa=%d", base, antialias);
2013
+
2014
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
2015
+ if (!res.pipeline) {
2016
+ ggml_metal_cv_t cv = ggml_metal_cv_init();
2017
+
2018
+ ggml_metal_cv_set_bool(cv, antialias, FC_UPSCALE + 0);
2019
+
2020
+ res = ggml_metal_library_compile_pipeline(lib, base, name, cv);
2021
+
2022
+ ggml_metal_cv_free(cv);
2023
+ }
2024
+
2025
+ return res;
2026
+ }
2027
+
2028
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_roll(ggml_metal_library_t lib, const ggml_tensor * op) {
2029
+ assert(op->op == GGML_OP_ROLL);
2030
+
2031
+ char base[256];
2032
+ char name[256];
2033
+
2034
+ snprintf(base, 256, "kernel_roll_%s", ggml_type_name(op->src[0]->type));
2035
+ snprintf(name, 256, "%s", base);
2036
+
2037
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
2038
+ if (!res.pipeline) {
2039
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
2040
+ }
2041
+
2042
+ return res;
2043
+ }
2044
+
2045
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_pad(ggml_metal_library_t lib, const ggml_tensor * op) {
2046
+ assert(op->op == GGML_OP_PAD);
2047
+
2048
+ char base[256];
2049
+ char name[256];
2050
+
2051
+ // note: this is slower
2052
+ //const bool is_c4 = op->src[0]->ne[0] % 4 == 0 && op->ne[0] % 4 == 0;
2053
+ const bool is_c4 = false;
2054
+
2055
+ snprintf(base, 256, "kernel_pad_%s%s", ggml_type_name(op->src[0]->type), is_c4 ? "_4" : "");
2056
+ snprintf(name, 256, "%s", base);
2057
+
2058
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
2059
+ if (res.pipeline) {
2060
+ return res;
2061
+ }
2062
+
2063
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
2064
+
2065
+ res.c4 = is_c4;
2066
+
2067
+ return res;
2068
+ }
2069
+
2070
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_pad_reflect_1d(ggml_metal_library_t lib, const ggml_tensor * op) {
2071
+ assert(op->op == GGML_OP_PAD_REFLECT_1D);
2072
+
2073
+ char base[256];
2074
+ char name[256];
2075
+
2076
+ snprintf(base, 256, "kernel_pad_reflect_1d_%s", ggml_type_name(op->src[0]->type));
2077
+ snprintf(name, 256, "%s", base);
2078
+
2079
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
2080
+ if (!res.pipeline) {
2081
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
2082
+ }
2083
+
2084
+ return res;
2085
+ }
2086
+
2087
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_arange(ggml_metal_library_t lib, const ggml_tensor * op) {
2088
+ assert(op->op == GGML_OP_ARANGE);
2089
+
2090
+ char base[256];
2091
+ char name[256];
2092
+
2093
+ snprintf(base, 256, "kernel_arange_%s", ggml_type_name(op->type));
2094
+ snprintf(name, 256, "%s", base);
2095
+
2096
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
2097
+ if (!res.pipeline) {
2098
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
2099
+ }
2100
+
2101
+ return res;
2102
+ }
2103
+
2104
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_timestep_embedding(ggml_metal_library_t lib, const ggml_tensor * op) {
2105
+ assert(op->op == GGML_OP_TIMESTEP_EMBEDDING);
2106
+
2107
+ char base[256];
2108
+ char name[256];
2109
+
2110
+ snprintf(base, 256, "kernel_timestep_embedding_%s", ggml_type_name(op->src[0]->type));
2111
+ snprintf(name, 256, "%s", base);
2112
+
2113
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
2114
+ if (!res.pipeline) {
2115
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
2116
+ }
2117
+
2118
+ return res;
2119
+ }
2120
+
2121
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_opt_step_adamw(ggml_metal_library_t lib, const ggml_tensor * op) {
2122
+ assert(op->op == GGML_OP_OPT_STEP_ADAMW);
2123
+
2124
+ char base[256];
2125
+ char name[256];
2126
+
2127
+ snprintf(base, 256, "kernel_opt_step_adamw_%s", ggml_type_name(op->src[0]->type));
2128
+ snprintf(name, 256, "%s", base);
2129
+
2130
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
2131
+ if (!res.pipeline) {
2132
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
2133
+ }
2134
+
2135
+ return res;
2136
+ }
2137
+
2138
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_opt_step_sgd(ggml_metal_library_t lib, const ggml_tensor * op) {
2139
+ assert(op->op == GGML_OP_OPT_STEP_SGD);
2140
+
2141
+ char base[256];
2142
+ char name[256];
2143
+
2144
+ snprintf(base, 256, "kernel_opt_step_sgd_%s", ggml_type_name(op->src[0]->type));
2145
+ snprintf(name, 256, "%s", base);
2146
+
2147
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
2148
+ if (!res.pipeline) {
2149
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
2150
+ }
2151
+
2152
+ return res;
2153
+ }
2154
+
2155
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_silu_back(ggml_metal_library_t lib, const ggml_tensor * op) {
2156
+ assert(op->op == GGML_OP_SILU_BACK);
2157
+
2158
+ char base[256];
2159
+ char name[256];
2160
+
2161
+ snprintf(base, 256, "kernel_silu_back_%s", ggml_type_name(op->src[0]->type));
2162
+ snprintf(name, 256, "%s", base);
2163
+
2164
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
2165
+ if (!res.pipeline) {
2166
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
2167
+ }
2168
+
2169
+ return res;
2170
+ }
2171
+
2172
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_memset(ggml_metal_library_t lib, const ggml_tensor * op) {
2173
+ GGML_ASSERT(op->type == GGML_TYPE_I64);
2174
+
2175
+ char base[256];
2176
+ char name[256];
2177
+
2178
+ snprintf(base, 256, "kernel_memset_%s", ggml_type_name(op->type));
2179
+ snprintf(name, 256, "%s", base);
2180
+
2181
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
2182
+ if (!res.pipeline) {
2183
+ res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr);
2184
+ }
2185
+
2186
+ return res;
2187
+ }
2188
+
2189
+ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_count_equal(ggml_metal_library_t lib, const ggml_tensor * op) {
2190
+ assert(op->op == GGML_OP_COUNT_EQUAL);
2191
+
2192
+ GGML_TENSOR_LOCALS(int64_t, ne0, op->src[0], ne);
2193
+
2194
+ GGML_ASSERT(op->src[0]->type == op->src[1]->type);
2195
+ GGML_ASSERT(op->src[0]->type == GGML_TYPE_I32);
2196
+ GGML_ASSERT(op->type == GGML_TYPE_I64);
2197
+
2198
+ // note: the kernel only supports i32 output due to metal atomic add only supporting atomic_int
2199
+ GGML_ASSERT(ggml_nelements(op->src[0]) < (1LL << 31));
2200
+
2201
+ char base[256];
2202
+ char name[256];
2203
+
2204
+ int nsg = 1;
2205
+ while (32*nsg < ne00 && nsg < 32) {
2206
+ nsg *= 2;
2207
+ }
2208
+
2209
+ snprintf(base, 256, "kernel_count_equal_%s", ggml_type_name(op->src[0]->type));
2210
+ snprintf(name, 256, "%s_nsg=%d", base, nsg);
2211
+
2212
+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
2213
+ if (!res.pipeline) {
2214
+ ggml_metal_cv_t cv = ggml_metal_cv_init();
2215
+
2216
+ ggml_metal_cv_set_int16(cv, nsg, FC_COUNT_EQUAL + 0);
2217
+
2218
+ res = ggml_metal_library_compile_pipeline(lib, base, name, cv);
2219
+
2220
+ ggml_metal_cv_free(cv);
2221
+ }
2222
+
2223
+ res.smem = 32 * sizeof(int32_t);
2224
+ res.nsg = nsg;
2225
+
2226
+ return res;
2227
+ }
ggml/src/ggml-metal/ggml-metal-device.h ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include "ggml.h"
4
+
5
+ #ifdef __cplusplus
6
+ extern "C" {
7
+ #endif
8
+
9
+ struct ggml_metal_buffer_id {
10
+ void * metal; // id<MTLBuffer>
11
+ size_t offs;
12
+ };
13
+
14
+ typedef struct ggml_metal_device * ggml_metal_device_t;
15
+
16
+ //
17
+ // MTLFunctionConstantValues wrapper
18
+ //
19
+
20
+ typedef struct ggml_metal_cv * ggml_metal_cv_t;
21
+
22
+ ggml_metal_cv_t ggml_metal_cv_init(void);
23
+ void ggml_metal_cv_free(ggml_metal_cv_t cv);
24
+
25
+ void ggml_metal_cv_set_int16(ggml_metal_cv_t cv, int16_t value, int32_t idx);
26
+ void ggml_metal_cv_set_int32(ggml_metal_cv_t cv, int32_t value, int32_t idx);
27
+ void ggml_metal_cv_set_bool (ggml_metal_cv_t cv, bool value, int32_t idx);
28
+
29
+ //
30
+ // MTLComputePipelineState wrapper
31
+ //
32
+
33
+ typedef struct ggml_metal_pipeline * ggml_metal_pipeline_t;
34
+
35
+ ggml_metal_pipeline_t ggml_metal_pipeline_init(void);
36
+ void ggml_metal_pipeline_free(ggml_metal_pipeline_t pipeline);
37
+
38
+ // a collection of pipelines
39
+ typedef struct ggml_metal_pipelines * ggml_metal_pipelines_t;
40
+
41
+ ggml_metal_pipelines_t ggml_metal_pipelines_init(void);
42
+ void ggml_metal_pipelines_free(ggml_metal_pipelines_t ppls);
43
+
44
+ void ggml_metal_pipelines_add(ggml_metal_pipelines_t ppls, const char * name, ggml_metal_pipeline_t pipeline);
45
+ ggml_metal_pipeline_t ggml_metal_pipelines_get(ggml_metal_pipelines_t ppls, const char * name);
46
+
47
+ struct ggml_metal_pipeline_with_params {
48
+ ggml_metal_pipeline_t pipeline;
49
+
50
+ int nsg;
51
+
52
+ int nr0;
53
+ int nr1;
54
+
55
+ size_t smem;
56
+
57
+ bool c4;
58
+ bool cnt;
59
+ };
60
+
61
+ int ggml_metal_pipeline_max_theads_per_threadgroup(struct ggml_metal_pipeline_with_params pipeline);
62
+
63
+ //
64
+ // MTLCommandBuffer wrapper
65
+ //
66
+
67
+ typedef void * ggml_metal_cmd_buf_t;
68
+
69
+ //
70
+ // MTLComputeCommandEncoder wrapper
71
+ //
72
+
73
+ typedef struct ggml_metal_encoder * ggml_metal_encoder_t;
74
+
75
+ ggml_metal_encoder_t ggml_metal_encoder_init(ggml_metal_cmd_buf_t cmd_buf_raw, bool concurrent);
76
+ void ggml_metal_encoder_free(ggml_metal_encoder_t encoder);
77
+
78
+ void ggml_metal_encoder_debug_group_push(ggml_metal_encoder_t encoder, const char * name);
79
+ void ggml_metal_encoder_debug_group_pop (ggml_metal_encoder_t encoder);
80
+
81
+ void ggml_metal_encoder_set_pipeline(ggml_metal_encoder_t encoder, struct ggml_metal_pipeline_with_params pipeline);
82
+
83
+ void ggml_metal_encoder_set_bytes (ggml_metal_encoder_t encoder, void * data, size_t size, int idx);
84
+ void ggml_metal_encoder_set_buffer(ggml_metal_encoder_t encoder, struct ggml_metal_buffer_id buffer, int idx);
85
+
86
+ void ggml_metal_encoder_set_threadgroup_memory_size(ggml_metal_encoder_t encoder, size_t size, int idx);
87
+
88
+ void ggml_metal_encoder_dispatch_threadgroups(ggml_metal_encoder_t encoder, int tg0, int tg1, int tg2, int tptg0, int tptg1, int tptg2);
89
+
90
+ void ggml_metal_encoder_memory_barrier(ggml_metal_encoder_t encoder);
91
+
92
+ void ggml_metal_encoder_end_encoding(ggml_metal_encoder_t encoder);
93
+
94
+ //
95
+ // MTLLibrary wrapper
96
+ //
97
+
98
+ typedef struct ggml_metal_library * ggml_metal_library_t;
99
+
100
+ ggml_metal_library_t ggml_metal_library_init (ggml_metal_device_t dev);
101
+ ggml_metal_library_t ggml_metal_library_init_from_source(ggml_metal_device_t dev, const char * source, bool verbose);
102
+
103
+ void ggml_metal_library_free(ggml_metal_library_t lib);
104
+
105
+ ggml_metal_device_t ggml_metal_library_get_device(ggml_metal_library_t lib);
106
+
107
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline (ggml_metal_library_t lib, const char * name);
108
+ struct ggml_metal_pipeline_with_params ggml_metal_library_compile_pipeline(ggml_metal_library_t lib, const char * base, const char * name, ggml_metal_cv_t cv);
109
+
110
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_base (ggml_metal_library_t lib, enum ggml_op op);
111
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_cpy (ggml_metal_library_t lib, enum ggml_type tsrc, enum ggml_type tdst);
112
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_pool_1d (ggml_metal_library_t lib, const struct ggml_tensor * op, enum ggml_op_pool op_pool);
113
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_pool_2d (ggml_metal_library_t lib, const struct ggml_tensor * op, enum ggml_op_pool op_pool);
114
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_get_rows (ggml_metal_library_t lib, enum ggml_type tsrc);
115
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_set_rows (ggml_metal_library_t lib, const struct ggml_tensor * op);
116
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_diag (ggml_metal_library_t lib, const struct ggml_tensor * op);
117
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_repeat (ggml_metal_library_t lib, enum ggml_type tsrc);
118
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_concat (ggml_metal_library_t lib, enum ggml_type tsrc);
119
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_unary (ggml_metal_library_t lib, const struct ggml_tensor * op);
120
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_silu_back (ggml_metal_library_t lib, const struct ggml_tensor * op);
121
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_glu (ggml_metal_library_t lib, const struct ggml_tensor * op);
122
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_sum (ggml_metal_library_t lib, const struct ggml_tensor * op);
123
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_sum_rows (ggml_metal_library_t lib, const struct ggml_tensor * op);
124
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_cumsum_blk (ggml_metal_library_t lib, const struct ggml_tensor * op);
125
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_cumsum_add (ggml_metal_library_t lib, const struct ggml_tensor * op);
126
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_tri (ggml_metal_library_t lib, const struct ggml_tensor * op);
127
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_soft_max (ggml_metal_library_t lib, const struct ggml_tensor * op);
128
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_lightning_indexer (ggml_metal_library_t lib, const struct ggml_tensor * op);
129
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_dsv4_hc (ggml_metal_library_t lib, enum ggml_op op);
130
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_ssm_conv (ggml_metal_library_t lib, const struct ggml_tensor * op);
131
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_ssm_conv_batched (ggml_metal_library_t lib, const struct ggml_tensor * op, int ssm_conv_bs);
132
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_ssm_scan (ggml_metal_library_t lib, const struct ggml_tensor * op);
133
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_rwkv (ggml_metal_library_t lib, const struct ggml_tensor * op);
134
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_gated_delta_net (ggml_metal_library_t lib, const struct ggml_tensor * op);
135
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_solve_tri (ggml_metal_library_t lib, const struct ggml_tensor * op);
136
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mv_ext (ggml_metal_library_t lib, const struct ggml_tensor * op, int nsg, int nxpsg, int r1ptg);
137
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm (ggml_metal_library_t lib, const struct ggml_tensor * op);
138
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mv (ggml_metal_library_t lib, const struct ggml_tensor * op);
139
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm_id_map0 (ggml_metal_library_t lib, int ne02, int ne20);
140
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm_id (ggml_metal_library_t lib, const struct ggml_tensor * op);
141
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mv_id (ggml_metal_library_t lib, const struct ggml_tensor * op);
142
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_argmax (ggml_metal_library_t lib, const struct ggml_tensor * op);
143
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_argsort (ggml_metal_library_t lib, const struct ggml_tensor * op);
144
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_argsort_merge (ggml_metal_library_t lib, const struct ggml_tensor * op);
145
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_fwht (ggml_metal_library_t lib, int n);
146
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_top_k (ggml_metal_library_t lib, const struct ggml_tensor * op);
147
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_top_k_merge (ggml_metal_library_t lib, const struct ggml_tensor * op);
148
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_bin (ggml_metal_library_t lib, const struct ggml_tensor * op, int32_t n_fuse );
149
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_bin_one (ggml_metal_library_t lib, enum ggml_op op);
150
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_l2_norm (ggml_metal_library_t lib, const struct ggml_tensor * op);
151
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_group_norm (ggml_metal_library_t lib, const struct ggml_tensor * op);
152
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_norm (ggml_metal_library_t lib, const struct ggml_tensor * op, int32_t n_fuse);
153
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_rope (ggml_metal_library_t lib, const struct ggml_tensor * op);
154
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_im2col (ggml_metal_library_t lib, const struct ggml_tensor * op);
155
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_conv_transpose_1d (ggml_metal_library_t lib, const struct ggml_tensor * op);
156
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_conv_transpose_2d (ggml_metal_library_t lib, const struct ggml_tensor * op);
157
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_col2im_1d (ggml_metal_library_t lib, const struct ggml_tensor * op);
158
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_snake (ggml_metal_library_t lib, enum ggml_type type);
159
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_conv_2d (ggml_metal_library_t lib, const struct ggml_tensor * op);
160
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_conv_2d_dw (ggml_metal_library_t lib, const struct ggml_tensor * op, bool tiled);
161
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_conv_3d (ggml_metal_library_t lib, const struct ggml_tensor * op);
162
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_upscale (ggml_metal_library_t lib, const struct ggml_tensor * op);
163
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_pad (ggml_metal_library_t lib, const struct ggml_tensor * op);
164
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_pad_reflect_1d (ggml_metal_library_t lib, const struct ggml_tensor * op);
165
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_roll (ggml_metal_library_t lib, const struct ggml_tensor * op);
166
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_arange (ggml_metal_library_t lib, const struct ggml_tensor * op);
167
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_timestep_embedding(ggml_metal_library_t lib, const struct ggml_tensor * op);
168
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_opt_step_adamw (ggml_metal_library_t lib, const struct ggml_tensor * op);
169
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_opt_step_sgd (ggml_metal_library_t lib, const struct ggml_tensor * op);
170
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_memset (ggml_metal_library_t lib, const struct ggml_tensor * op);
171
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_count_equal (ggml_metal_library_t lib, const struct ggml_tensor * op);
172
+
173
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_pad(
174
+ ggml_metal_library_t lib,
175
+ const struct ggml_tensor * op,
176
+ bool has_mask,
177
+ int32_t ncpsg);
178
+
179
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_blk(
180
+ ggml_metal_library_t lib,
181
+ const struct ggml_tensor * op,
182
+ int32_t nqptg,
183
+ int32_t ncpsg);
184
+
185
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext(
186
+ ggml_metal_library_t lib,
187
+ const struct ggml_tensor * op,
188
+ bool has_mask,
189
+ bool has_sinks,
190
+ bool has_bias,
191
+ bool has_scap,
192
+ bool has_kvpad,
193
+ int32_t nsg);
194
+
195
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_vec(
196
+ ggml_metal_library_t lib,
197
+ const struct ggml_tensor * op,
198
+ bool has_mask,
199
+ bool has_sinks,
200
+ bool has_bias,
201
+ bool has_scap,
202
+ bool has_kvpad,
203
+ int32_t nsg,
204
+ int32_t nwg);
205
+
206
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_vec_reduce(
207
+ ggml_metal_library_t lib,
208
+ const struct ggml_tensor * op,
209
+ int32_t dv,
210
+ int32_t nwg);
211
+
212
+ // MTLResidencySet wrapper
213
+
214
+ typedef void * ggml_metal_rset_t;
215
+
216
+ // a collection of residency sets (non-owning)
217
+ typedef struct ggml_metal_rsets * ggml_metal_rsets_t;
218
+
219
+ ggml_metal_rsets_t ggml_metal_rsets_init(ggml_metal_device_t dev);
220
+ void ggml_metal_rsets_free(ggml_metal_rsets_t rsets);
221
+
222
+ //
223
+ // device
224
+ //
225
+
226
+ enum ggml_metal_device_id {
227
+ GGML_METAL_DEVICE_GENERIC = 0,
228
+
229
+ GGML_METAL_DEVICE_M1,
230
+ GGML_METAL_DEVICE_M1_PRO,
231
+ GGML_METAL_DEVICE_M1_MAX,
232
+ GGML_METAL_DEVICE_M1_ULTRA,
233
+ GGML_METAL_DEVICE_M2,
234
+ GGML_METAL_DEVICE_M2_PRO,
235
+ GGML_METAL_DEVICE_M2_MAX,
236
+ GGML_METAL_DEVICE_M2_ULTRA,
237
+ GGML_METAL_DEVICE_M3,
238
+ GGML_METAL_DEVICE_M3_PRO,
239
+ GGML_METAL_DEVICE_M3_MAX,
240
+ GGML_METAL_DEVICE_M3_ULTRA,
241
+ GGML_METAL_DEVICE_M4,
242
+ GGML_METAL_DEVICE_M4_PRO,
243
+ GGML_METAL_DEVICE_M4_MAX,
244
+ GGML_METAL_DEVICE_M5,
245
+ GGML_METAL_DEVICE_M5_PRO,
246
+ GGML_METAL_DEVICE_M5_MAX,
247
+ GGML_METAL_DEVICE_M5_ULTRA,
248
+ };
249
+
250
+ struct ggml_metal_device_props {
251
+ int device;
252
+ char name[128];
253
+ char desc[128];
254
+
255
+ size_t max_buffer_size;
256
+ size_t max_working_set_size;
257
+ size_t max_theadgroup_memory_size;
258
+
259
+ bool has_simdgroup_reduction;
260
+ bool has_simdgroup_mm;
261
+ bool has_unified_memory;
262
+ bool has_bfloat;
263
+ bool has_tensor;
264
+ bool use_residency_sets;
265
+ bool use_shared_buffers;
266
+
267
+ bool supports_gpu_family_apple7;
268
+
269
+ enum ggml_metal_device_id device_id;
270
+
271
+ int op_offload_min_batch_size;
272
+ };
273
+
274
+ typedef struct ggml_metal_event * ggml_metal_event_t;
275
+
276
+ void ggml_metal_event_encode_signal(ggml_metal_event_t ev, ggml_metal_cmd_buf_t cmd_buf);
277
+ void ggml_metal_event_encode_wait (ggml_metal_event_t ev, ggml_metal_cmd_buf_t cmd_buf);
278
+
279
+ ggml_metal_device_t ggml_metal_device_init(int device);
280
+ void ggml_metal_device_free(ggml_metal_device_t dev);
281
+
282
+ ggml_metal_device_t ggml_metal_device_get(int device);
283
+
284
+ void * ggml_metal_device_get_obj (ggml_metal_device_t dev); // id<MTLDevice>
285
+ void * ggml_metal_device_get_queue(ggml_metal_device_t dev); // id<MTLCommandQueue>
286
+
287
+ ggml_metal_library_t ggml_metal_device_get_library(ggml_metal_device_t dev);
288
+
289
+ void ggml_metal_device_rsets_add(ggml_metal_device_t dev, ggml_metal_rset_t rset);
290
+ void ggml_metal_device_rsets_rm (ggml_metal_device_t dev, ggml_metal_rset_t rset);
291
+
292
+ void ggml_metal_device_rsets_keep_alive(ggml_metal_device_t dev);
293
+
294
+ ggml_metal_event_t ggml_metal_device_event_init(ggml_metal_device_t dev);
295
+ void ggml_metal_device_event_free(ggml_metal_device_t dev, ggml_metal_event_t ev);
296
+ void ggml_metal_device_event_synchronize(ggml_metal_device_t dev, ggml_metal_event_t ev);
297
+
298
+ void ggml_metal_device_get_memory(ggml_metal_device_t dev, size_t * free, size_t * total);
299
+ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_tensor * op);
300
+
301
+ const struct ggml_metal_device_props * ggml_metal_device_get_props(ggml_metal_device_t dev);
302
+
303
+ //
304
+ // device buffers
305
+ //
306
+
307
+ typedef struct ggml_metal_buffer * ggml_metal_buffer_t;
308
+
309
+ ggml_metal_buffer_t ggml_metal_buffer_init(ggml_metal_device_t dev, size_t size, bool shared);
310
+ ggml_metal_buffer_t ggml_metal_buffer_map (ggml_metal_device_t dev, void * ptr, size_t size, size_t max_tensor_size);
311
+
312
+ void ggml_metal_buffer_free (ggml_metal_buffer_t buf);
313
+ void * ggml_metal_buffer_get_base (ggml_metal_buffer_t buf);
314
+ bool ggml_metal_buffer_is_shared(ggml_metal_buffer_t buf);
315
+
316
+ void ggml_metal_buffer_memset_tensor(ggml_metal_buffer_t buf, struct ggml_tensor * tensor, uint8_t value, size_t offset, size_t size);
317
+ void ggml_metal_buffer_set_tensor (ggml_metal_buffer_t buf, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size);
318
+ void ggml_metal_buffer_get_tensor (ggml_metal_buffer_t buf, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size);
319
+ bool ggml_metal_buffer_cpy_tensor (ggml_metal_buffer_t buf, const struct ggml_tensor * src, struct ggml_tensor * dst);
320
+ void ggml_metal_buffer_clear (ggml_metal_buffer_t buf, uint8_t value);
321
+
322
+ // finds the Metal buffer that contains the tensor data on the GPU device
323
+ // the assumption is that there is 1-to-1 mapping between the host and device memory buffers, so we can find the
324
+ // Metal buffer based on the host memory pointer
325
+ //
326
+ struct ggml_metal_buffer_id ggml_metal_buffer_get_id(ggml_metal_buffer_t buf, const struct ggml_tensor * t);
327
+
328
+ #ifdef __cplusplus
329
+ }
330
+ #endif
ggml/src/ggml-metal/ggml-metal-device.m ADDED
@@ -0,0 +1,2028 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #import "ggml-metal-device.h"
2
+
3
+ #import "ggml-impl.h"
4
+ #import "ggml-backend-impl.h"
5
+ #import "ggml-metal-impl.h"
6
+
7
+ #include <Foundation/Foundation.h>
8
+
9
+ #include <Metal/Metal.h>
10
+
11
+ #include <stdatomic.h>
12
+
13
+ #ifndef TARGET_OS_VISION
14
+ #define TARGET_OS_VISION 0
15
+ #endif
16
+
17
+ // create residency sets only on macOS >= 15.0
18
+ #if !TARGET_CPU_X86_64 && TARGET_OS_OSX && __MAC_OS_X_VERSION_MAX_ALLOWED >= 150000 || \
19
+ TARGET_OS_IOS && __IPHONE_OS_VERSION_MAX_ALLOWED >= 180000 || \
20
+ TARGET_OS_TV && __TV_OS_VERSION_MAX_ALLOWED >= 180000 || \
21
+ TARGET_OS_VISION && __VISION_OS_VERSION_MAX_ALLOWED >= 200000
22
+ #define GGML_METAL_HAS_RESIDENCY_SETS 1
23
+ #endif
24
+
25
+ // overload of MTLGPUFamilyMetalX (not available in some environments)
26
+ static const NSInteger MTLGPUFamilyMetal3_GGML = 5001;
27
+ static const NSInteger MTLGPUFamilyMetal4_GGML = 5002;
28
+
29
+ #if !GGML_METAL_EMBED_LIBRARY
30
+ // Here to assist with NSBundle Path Hack
31
+ @interface GGMLMetalClass : NSObject
32
+ @end
33
+ @implementation GGMLMetalClass
34
+ @end
35
+ #endif
36
+
37
+ //
38
+ // MTLFunctionConstantValues wrapper
39
+ //
40
+
41
+ struct ggml_metal_cv {
42
+ MTLFunctionConstantValues * obj;
43
+ };
44
+
45
+ ggml_metal_cv_t ggml_metal_cv_init(void) {
46
+ ggml_metal_cv_t res = calloc(1, sizeof(struct ggml_metal_cv));
47
+
48
+ res->obj = [[MTLFunctionConstantValues alloc] init];
49
+
50
+ return res;
51
+ }
52
+
53
+ void ggml_metal_cv_free(ggml_metal_cv_t cv) {
54
+ [cv->obj release];
55
+ free(cv);
56
+ }
57
+
58
+ void ggml_metal_cv_set_int16(ggml_metal_cv_t cv, int16_t value, int32_t idx) {
59
+ [cv->obj setConstantValue:&value type:MTLDataTypeShort atIndex:idx];
60
+ }
61
+
62
+ void ggml_metal_cv_set_int32(ggml_metal_cv_t cv, int32_t value, int32_t idx) {
63
+ [cv->obj setConstantValue:&value type:MTLDataTypeInt atIndex:idx];
64
+ }
65
+
66
+ void ggml_metal_cv_set_bool(ggml_metal_cv_t cv, bool value, int32_t idx) {
67
+ [cv->obj setConstantValue:&value type:MTLDataTypeBool atIndex:idx];
68
+ }
69
+
70
+ //
71
+ // MTLComputePipelineState wrapper
72
+ //
73
+
74
+ struct ggml_metal_pipeline {
75
+ id<MTLComputePipelineState> obj;
76
+ };
77
+
78
+ ggml_metal_pipeline_t ggml_metal_pipeline_init(void) {
79
+ ggml_metal_pipeline_t res = calloc(1, sizeof(struct ggml_metal_pipeline));
80
+
81
+ *res = (struct ggml_metal_pipeline) {
82
+ /*.obj =*/ nil,
83
+ };
84
+
85
+ return res;
86
+ }
87
+
88
+ void ggml_metal_pipeline_free(ggml_metal_pipeline_t pipeline) {
89
+ [pipeline->obj release];
90
+
91
+ free(pipeline);
92
+ }
93
+
94
+ int ggml_metal_pipeline_max_theads_per_threadgroup(struct ggml_metal_pipeline_with_params pipeline) {
95
+ return pipeline.pipeline->obj.maxTotalThreadsPerThreadgroup;
96
+ }
97
+
98
+ struct ggml_metal_library {
99
+ id<MTLLibrary> obj;
100
+
101
+ ggml_metal_device_t dev;
102
+ ggml_metal_pipelines_t pipelines; // cache of compiled pipelines
103
+
104
+ NSLock * lock;
105
+ };
106
+
107
+ ggml_metal_library_t ggml_metal_library_init(ggml_metal_device_t dev) {
108
+ id<MTLLibrary> library = nil;
109
+ id<MTLDevice> device = ggml_metal_device_get_obj(dev);
110
+
111
+ // load library
112
+ //
113
+ // - first check if the library is embedded
114
+ // - then check if the library is in the bundle
115
+ // - if not found, load the source and compile it
116
+ // - if that fails, return NULL
117
+ //
118
+ // TODO: move to a function
119
+ {
120
+ const int64_t t_start = ggml_time_us();
121
+
122
+ NSError * error = nil;
123
+ NSString * src = nil;
124
+
125
+ #if GGML_METAL_EMBED_LIBRARY
126
+ GGML_LOG_INFO("%s: using embedded metal library\n", __func__);
127
+
128
+ extern const char ggml_metallib_start[];
129
+ extern const char ggml_metallib_end[];
130
+
131
+ src = [[NSString alloc] initWithBytes:ggml_metallib_start length:(ggml_metallib_end-ggml_metallib_start) encoding:NSUTF8StringEncoding];
132
+ #else
133
+
134
+ #ifdef SWIFT_PACKAGE
135
+ NSBundle * bundle = SWIFTPM_MODULE_BUNDLE;
136
+ #else
137
+ NSBundle * bundle = [NSBundle bundleForClass:[GGMLMetalClass class]];
138
+ #endif
139
+
140
+ NSString * path_lib = [bundle pathForResource:@"default" ofType:@"metallib"];
141
+ if (path_lib == nil) {
142
+ // Try to find the resource in the directory where the current binary located.
143
+ NSString * bin_cur = [[NSProcessInfo processInfo] arguments][0];
144
+ NSString * bin_dir = [bin_cur stringByDeletingLastPathComponent];
145
+
146
+ NSString * path_lib_default = [NSString pathWithComponents:@[bin_dir, @"default.metallib"]];
147
+ if ([[NSFileManager defaultManager] isReadableFileAtPath:path_lib_default]) {
148
+ GGML_LOG_INFO("%s: found '%s'\n", __func__, [path_lib_default UTF8String]);
149
+
150
+ NSDictionary * atts = [[NSFileManager defaultManager] attributesOfItemAtPath:path_lib_default error:&error];
151
+ if (atts && atts[NSFileType] == NSFileTypeSymbolicLink) {
152
+ // Optionally, if this is a symlink, try to resolve it.
153
+ path_lib_default = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath:path_lib_default error:&error];
154
+ if (path_lib_default && [path_lib_default length] > 0 && ![[path_lib_default substringToIndex:1] isEqualToString:@"/"]) {
155
+ // It is a relative path, adding the binary directory as directory prefix.
156
+ path_lib_default = [NSString pathWithComponents:@[bin_dir, path_lib_default]];
157
+ }
158
+ if (!path_lib_default || ![[NSFileManager defaultManager] isReadableFileAtPath:path_lib_default]) {
159
+ // Link to the resource could not be resolved.
160
+ path_lib_default = nil;
161
+ } else {
162
+ GGML_LOG_INFO("%s: symlink resolved '%s'\n", __func__, [path_lib_default UTF8String]);
163
+ }
164
+ }
165
+ } else {
166
+ // The resource couldn't be found in the binary's directory.
167
+ path_lib_default = nil;
168
+ }
169
+
170
+ path_lib = path_lib_default;
171
+ }
172
+
173
+ if (path_lib != nil) {
174
+ // pre-compiled library found
175
+ NSURL * libURL = [NSURL fileURLWithPath:path_lib];
176
+ GGML_LOG_INFO("%s: loading '%s'\n", __func__, [path_lib UTF8String]);
177
+
178
+ library = [device newLibraryWithURL:libURL error:&error];
179
+ if (error) {
180
+ GGML_LOG_ERROR("%s: error: %s\n", __func__, [[error description] UTF8String]);
181
+ return nil;
182
+ }
183
+ } else {
184
+ GGML_LOG_INFO("%s: default.metallib not found, loading from source\n", __func__);
185
+
186
+ NSString * path_source;
187
+ NSString * path_resource = [[NSProcessInfo processInfo].environment objectForKey:@"GGML_METAL_PATH_RESOURCES"];
188
+
189
+ GGML_LOG_INFO("%s: GGML_METAL_PATH_RESOURCES = %s\n", __func__, path_resource ? [path_resource UTF8String] : "nil");
190
+
191
+ if (path_resource) {
192
+ path_source = [path_resource stringByAppendingPathComponent:@"ggml-metal.metal"];
193
+ } else {
194
+ path_source = [bundle pathForResource:@"ggml-metal" ofType:@"metal"];
195
+ }
196
+
197
+ if (path_source == nil) {
198
+ GGML_LOG_WARN("%s: error: could not use bundle path to find ggml-metal.metal, falling back to trying cwd\n", __func__);
199
+ path_source = @"ggml-metal.metal";
200
+ }
201
+
202
+ GGML_LOG_INFO("%s: loading '%s'\n", __func__, [path_source UTF8String]);
203
+
204
+ src = [NSString stringWithContentsOfFile:path_source encoding:NSUTF8StringEncoding error:&error];
205
+ if (error) {
206
+ GGML_LOG_ERROR("%s: error: %s\n", __func__, [[error description] UTF8String]);
207
+ return nil;
208
+ }
209
+ }
210
+ #endif
211
+
212
+ if (!library) {
213
+ @autoreleasepool {
214
+ // dictionary of preprocessor macros
215
+ NSMutableDictionary * prep = [NSMutableDictionary dictionary];
216
+
217
+ if (ggml_metal_device_get_props(dev)->has_bfloat) {
218
+ [prep setObject:@"1" forKey:@"GGML_METAL_HAS_BF16"];
219
+ }
220
+
221
+ if (ggml_metal_device_get_props(dev)->has_tensor) {
222
+ [prep setObject:@"1" forKey:@"GGML_METAL_HAS_TENSOR"];
223
+ }
224
+
225
+ #if GGML_METAL_EMBED_LIBRARY
226
+ [prep setObject:@"1" forKey:@"GGML_METAL_EMBED_LIBRARY"];
227
+ #endif
228
+
229
+ MTLCompileOptions * options = [MTLCompileOptions new];
230
+ options.preprocessorMacros = prep;
231
+
232
+ //[options setFastMathEnabled:false];
233
+
234
+ library = [device newLibraryWithSource:src options:options error:&error];
235
+ if (error) {
236
+ GGML_LOG_ERROR("%s: error: %s\n", __func__, [[error description] UTF8String]);
237
+ return nil;
238
+ }
239
+
240
+ #if !__has_feature(objc_arc)
241
+ [options release];
242
+ #endif
243
+ }
244
+ }
245
+
246
+ #if GGML_METAL_EMBED_LIBRARY
247
+ [src release];
248
+ #endif // GGML_METAL_EMBED_LIBRARY
249
+
250
+ GGML_LOG_INFO("%s: loaded in %.3f sec\n", __func__, (ggml_time_us() - t_start) / 1e6);
251
+ }
252
+
253
+ ggml_metal_library_t res = calloc(1, sizeof(struct ggml_metal_library));
254
+
255
+ res->obj = library;
256
+ res->dev = dev;
257
+ res->pipelines = ggml_metal_pipelines_init();
258
+ res->lock = [NSLock new];
259
+
260
+ return res;
261
+ }
262
+
263
+ ggml_metal_library_t ggml_metal_library_init_from_source(ggml_metal_device_t dev, const char * source, bool verbose) {
264
+ if (source == NULL) {
265
+ GGML_LOG_ERROR("%s: source is NULL\n", __func__);
266
+ return NULL;
267
+ }
268
+
269
+ id<MTLDevice> device = ggml_metal_device_get_obj(dev);
270
+ id<MTLLibrary> library = nil;
271
+ NSError * error = nil;
272
+
273
+ const int64_t t_start = ggml_time_us();
274
+
275
+ NSString * src = [[NSString alloc] initWithBytes:source
276
+ length:strlen(source)
277
+ encoding:NSUTF8StringEncoding];
278
+ if (!src) {
279
+ GGML_LOG_ERROR("%s: failed to create NSString from source\n", __func__);
280
+ return NULL;
281
+ }
282
+
283
+ @autoreleasepool {
284
+ NSMutableDictionary * prep = [NSMutableDictionary dictionary];
285
+
286
+ MTLCompileOptions * options = [MTLCompileOptions new];
287
+ options.preprocessorMacros = prep;
288
+
289
+ library = [device newLibraryWithSource:src options:options error:&error];
290
+ if (error) {
291
+ if (verbose) {
292
+ GGML_LOG_ERROR("%s: error compiling source: %s\n", __func__, [[error description] UTF8String]);
293
+ } else {
294
+ GGML_LOG_ERROR("%s: error compiling source\n", __func__);
295
+ }
296
+ library = nil;
297
+ }
298
+
299
+ [options release];
300
+ }
301
+
302
+ [src release];
303
+
304
+ if (!library) {
305
+ if (verbose) {
306
+ GGML_LOG_ERROR("%s: failed to create Metal library from source\n", __func__);
307
+ }
308
+
309
+ return NULL;
310
+ }
311
+
312
+ if (verbose) {
313
+ GGML_LOG_INFO("%s: compiled in %.3f sec\n", __func__, (ggml_time_us() - t_start) / 1e6);
314
+ }
315
+
316
+ ggml_metal_library_t res = calloc(1, sizeof(struct ggml_metal_library));
317
+ if (!res) {
318
+ GGML_LOG_ERROR("%s: calloc failed\n", __func__);
319
+ return NULL;
320
+ }
321
+
322
+ res->obj = library;
323
+ res->dev = dev;
324
+ res->pipelines = ggml_metal_pipelines_init();
325
+ res->lock = [NSLock new];
326
+
327
+ return res;
328
+ }
329
+
330
+ void ggml_metal_library_free(ggml_metal_library_t lib) {
331
+ if (!lib) {
332
+ return;
333
+ }
334
+
335
+ if (lib->obj) {
336
+ [lib->obj release];
337
+ }
338
+
339
+ ggml_metal_pipelines_free(lib->pipelines);
340
+
341
+ [lib->lock release];
342
+
343
+ free(lib);
344
+ }
345
+
346
+ ggml_metal_device_t ggml_metal_library_get_device(ggml_metal_library_t lib) {
347
+ return lib->dev;
348
+ }
349
+
350
+ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline(ggml_metal_library_t lib, const char * name) {
351
+ [lib->lock lock];
352
+
353
+ struct ggml_metal_pipeline_with_params res = {
354
+ /*.pipeline =*/ nil,
355
+ /*.nsg =*/ 0,
356
+ /*.nr0 =*/ 0,
357
+ /*.nr1 =*/ 0,
358
+ /*.smem =*/ 0,
359
+ /*.c4 =*/ false,
360
+ /*.cnt =*/ false,
361
+ };
362
+
363
+ res.pipeline = ggml_metal_pipelines_get(lib->pipelines, name);
364
+
365
+ [lib->lock unlock];
366
+
367
+ return res;
368
+ }
369
+
370
+ struct ggml_metal_pipeline_with_params ggml_metal_library_compile_pipeline(ggml_metal_library_t lib, const char * base, const char * name, ggml_metal_cv_t cv) {
371
+ struct ggml_metal_pipeline_with_params res = {
372
+ /*.pipeline =*/ nil,
373
+ /*.nsg =*/ 0,
374
+ /*.nr0 =*/ 0,
375
+ /*.nr1 =*/ 0,
376
+ /*.smem =*/ 0,
377
+ /*.c4 =*/ false,
378
+ /*.cnt =*/ false,
379
+ };
380
+
381
+ [lib->lock lock];
382
+
383
+ res.pipeline = ggml_metal_pipelines_get(lib->pipelines, name);
384
+ if (res.pipeline) {
385
+ [lib->lock unlock];
386
+
387
+ return res;
388
+ }
389
+
390
+ @autoreleasepool {
391
+ NSError * error = nil;
392
+
393
+ NSString * base_func = [NSString stringWithUTF8String:base];
394
+
395
+ GGML_LOG_DEBUG("%s: compiling pipeline: base = '%s', name = '%s'\n", __func__, base, name);
396
+
397
+ id<MTLFunction> mtl_function;
398
+ if (!cv) {
399
+ mtl_function = [lib->obj newFunctionWithName:base_func];
400
+ } else {
401
+ mtl_function = [lib->obj newFunctionWithName:base_func constantValues:cv->obj error:&error];
402
+ }
403
+ if (!mtl_function) {
404
+ [lib->lock unlock];
405
+
406
+ GGML_LOG_ERROR("%s: failed to compile pipeline: base = '%s', name = '%s'\n", __func__, base, name);
407
+ if (error) {
408
+ GGML_LOG_ERROR("%s: %s\n", __func__, [[error description] UTF8String]);
409
+ }
410
+
411
+ return res;
412
+ }
413
+
414
+ id<MTLDevice> device = ggml_metal_device_get_obj(lib->dev);
415
+ id<MTLComputePipelineState> obj = [device newComputePipelineStateWithFunction:mtl_function error:&error];
416
+
417
+ [mtl_function release];
418
+
419
+ if (!obj) {
420
+ [lib->lock unlock];
421
+
422
+ GGML_LOG_ERROR("%s: failed to create pipeline state: base = '%s', name = '%s'\n", __func__, base, name);
423
+ if (error) {
424
+ GGML_LOG_ERROR("%s: %s\n", __func__, [[error description] UTF8String]);
425
+ }
426
+
427
+ return res;
428
+ }
429
+
430
+ GGML_LOG_DEBUG("%s: loaded %-40s %16p | th_max = %4d | th_width = %4d\n", __func__, name,
431
+ (void *) obj,
432
+ (int) obj.maxTotalThreadsPerThreadgroup,
433
+ (int) obj.threadExecutionWidth);
434
+
435
+ if (obj.maxTotalThreadsPerThreadgroup == 0 || obj.threadExecutionWidth == 0) {
436
+ [obj release];
437
+
438
+ [lib->lock unlock];
439
+
440
+ GGML_LOG_ERROR("%s: incompatible pipeline %s\n", __func__, name);
441
+
442
+ return res;
443
+ }
444
+
445
+ res.pipeline = ggml_metal_pipeline_init();
446
+ res.pipeline->obj = obj;
447
+
448
+ ggml_metal_pipelines_add(lib->pipelines, name, res.pipeline);
449
+ }
450
+
451
+ [lib->lock unlock];
452
+
453
+ return res;
454
+ }
455
+
456
+ //
457
+ // MTLComputeCommandEncoder wrapper
458
+ //
459
+
460
+ struct ggml_metal_encoder {
461
+ id<MTLComputeCommandEncoder> obj;
462
+ };
463
+
464
+ ggml_metal_encoder_t ggml_metal_encoder_init(ggml_metal_cmd_buf_t cmd_buf_raw, bool concurrent) {
465
+ ggml_metal_encoder_t res = calloc(1, sizeof(struct ggml_metal_encoder));
466
+
467
+ id<MTLCommandBuffer> cmd_buf = (id<MTLCommandBuffer>) cmd_buf_raw;
468
+
469
+ if (concurrent) {
470
+ res->obj = [cmd_buf computeCommandEncoderWithDispatchType: MTLDispatchTypeConcurrent];
471
+ } else {
472
+ res->obj = [cmd_buf computeCommandEncoder];
473
+ }
474
+
475
+ [res->obj retain];
476
+
477
+ return res;
478
+ }
479
+
480
+ void ggml_metal_encoder_free(ggml_metal_encoder_t encoder) {
481
+ [encoder->obj release];
482
+ free(encoder);
483
+ }
484
+
485
+ void ggml_metal_encoder_debug_group_push(ggml_metal_encoder_t encoder, const char * name) {
486
+ [encoder->obj pushDebugGroup:[NSString stringWithCString:name encoding:NSUTF8StringEncoding]];
487
+ }
488
+
489
+ void ggml_metal_encoder_debug_group_pop (ggml_metal_encoder_t encoder) {
490
+ [encoder->obj popDebugGroup];
491
+ }
492
+
493
+ void ggml_metal_encoder_set_pipeline(ggml_metal_encoder_t encoder, struct ggml_metal_pipeline_with_params pipeline) {
494
+ [encoder->obj setComputePipelineState:pipeline.pipeline->obj];
495
+ }
496
+
497
+ void ggml_metal_encoder_set_bytes(ggml_metal_encoder_t encoder, void * data, size_t size, int idx) {
498
+ [encoder->obj setBytes:data length:size atIndex:idx];
499
+ }
500
+
501
+ void ggml_metal_encoder_set_buffer(ggml_metal_encoder_t encoder, struct ggml_metal_buffer_id buffer, int idx) {
502
+ [encoder->obj setBuffer:buffer.metal offset:buffer.offs atIndex:idx];
503
+ }
504
+
505
+ void ggml_metal_encoder_set_threadgroup_memory_size(ggml_metal_encoder_t encoder, size_t size, int idx) {
506
+ [encoder->obj setThreadgroupMemoryLength:size atIndex:idx];
507
+ }
508
+
509
+ void ggml_metal_encoder_dispatch_threadgroups(ggml_metal_encoder_t encoder, int tg0, int tg1, int tg2, int tptg0, int tptg1, int tptg2) {
510
+ [encoder->obj dispatchThreadgroups:MTLSizeMake(tg0, tg1, tg2) threadsPerThreadgroup:MTLSizeMake(tptg0, tptg1, tptg2)];
511
+ }
512
+
513
+ void ggml_metal_encoder_memory_barrier(ggml_metal_encoder_t encoder) {
514
+ [encoder->obj memoryBarrierWithScope:MTLBarrierScopeBuffers];
515
+ }
516
+
517
+ void ggml_metal_encoder_end_encoding(ggml_metal_encoder_t encoder) {
518
+ [encoder->obj endEncoding];
519
+ }
520
+
521
+ struct ggml_metal_device {
522
+ id<MTLDevice> mtl_device;
523
+
524
+ // a single global queue shared by all Metal backends
525
+ // technically not needed for devices with unified memory, but enables discrete GPUs support
526
+ // ref: https://github.com/ggml-org/llama.cpp/pull/15906
527
+ id<MTLCommandQueue> mtl_queue;
528
+
529
+ ggml_metal_rsets_t rsets;
530
+
531
+ ggml_metal_library_t library;
532
+
533
+ struct ggml_metal_device_props props;
534
+
535
+ // virtual address for GPU memory allocations
536
+ atomic_uintptr_t addr_virt;
537
+ };
538
+
539
+ //
540
+ // MTLResidenceSet wrapper
541
+ //
542
+
543
+ struct ggml_metal_rsets {
544
+ NSLock * lock;
545
+
546
+ NSMutableArray * data;
547
+
548
+ // number of seconds since the last graph computation
549
+ // keep the residency sets wired for that amount of time to avoid being collected by the OS
550
+ int keep_alive_s;
551
+ int loops_per_s;
552
+ int time_per_loop_ms;
553
+
554
+ // background heartbeat thread to keep the residency sets alive
555
+ atomic_bool d_stop;
556
+ atomic_int d_loop;
557
+
558
+ dispatch_group_t d_group;
559
+ };
560
+
561
+ #if defined(GGML_METAL_HAS_RESIDENCY_SETS)
562
+ static void ggml_metal_dummy_work(ggml_metal_device_t dev) {
563
+ if (dev->mtl_queue == nil) {
564
+ return;
565
+ }
566
+
567
+ @autoreleasepool {
568
+ // perform a minimal dummy operation on the GPU
569
+ id<MTLBuffer> buf = [dev->mtl_device newBufferWithLength:1 options:MTLResourceStorageModePrivate];
570
+ id<MTLCommandBuffer> cmd_buf = [dev->mtl_queue commandBuffer];
571
+
572
+ {
573
+ id<MTLBlitCommandEncoder> encoder = [cmd_buf blitCommandEncoder];
574
+
575
+ [encoder fillBuffer:buf range:NSMakeRange(0, 1) value:0];
576
+
577
+ [encoder endEncoding];
578
+ }
579
+
580
+ [cmd_buf commit];
581
+ [buf release];
582
+ }
583
+ }
584
+ #endif
585
+
586
+ ggml_metal_rsets_t ggml_metal_rsets_init(ggml_metal_device_t dev) {
587
+ ggml_metal_rsets_t res = calloc(1, sizeof(struct ggml_metal_rsets));
588
+
589
+ res->lock = [[NSLock alloc] init];
590
+ res->data = [[NSMutableArray alloc] init];
591
+
592
+ // by default keep the memory wired for 3 minutes
593
+ res->keep_alive_s = 3*60;
594
+
595
+ const char * GGML_METAL_RESIDENCY_KEEP_ALIVE_S = getenv("GGML_METAL_RESIDENCY_KEEP_ALIVE_S");
596
+ if (GGML_METAL_RESIDENCY_KEEP_ALIVE_S) {
597
+ res->keep_alive_s = atoi(GGML_METAL_RESIDENCY_KEEP_ALIVE_S);
598
+ }
599
+
600
+ if (res->keep_alive_s <= 0) {
601
+ res->keep_alive_s = 3*60;
602
+ }
603
+
604
+ res->time_per_loop_ms = 5;
605
+ res->loops_per_s = 1000/res->time_per_loop_ms;
606
+
607
+ GGML_LOG_INFO("%s: creating a residency set collection (keep_alive = %d s)\n", __func__, res->keep_alive_s);
608
+
609
+ atomic_store_explicit(&res->d_stop, false, memory_order_relaxed);
610
+ atomic_store_explicit(&res->d_loop, res->loops_per_s*res->keep_alive_s, memory_order_relaxed);
611
+
612
+ res->d_group = dispatch_group_create();
613
+
614
+ // start a background thread that periodically requests residency for all the currently active sets in the collection
615
+ // the requests stop after a certain amount of time (keep_alive_s) of inactivity
616
+ dispatch_queue_t d_queue = dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0);
617
+ dispatch_group_async(res->d_group, d_queue, ^{
618
+ #if defined(GGML_METAL_HAS_RESIDENCY_SETS)
619
+ if (@available(macOS 15.0, iOS 18.0, tvOS 18.0, visionOS 2.0, *)) {
620
+ while (!atomic_load_explicit(&res->d_stop, memory_order_relaxed)) {
621
+ if (atomic_load_explicit(&res->d_loop, memory_order_relaxed) > 0) {
622
+ [res->lock lock];
623
+
624
+ for (int i = 0; i < (int) res->data.count; ++i) {
625
+ [res->data[i] requestResidency];
626
+ }
627
+
628
+ atomic_fetch_sub_explicit(&res->d_loop, 1, memory_order_relaxed);
629
+
630
+ [res->lock unlock];
631
+ }
632
+
633
+ usleep(res->time_per_loop_ms * 1000);
634
+ }
635
+ }
636
+ #endif
637
+ });
638
+
639
+ #if defined(GGML_METAL_HAS_RESIDENCY_SETS)
640
+ if (@available(macOS 15.0, iOS 18.0, tvOS 18.0, visionOS 2.0, *)) {
641
+ // workaround for residency set memory not being released if no GPU operation occurs
642
+ // https://developer.apple.com/forums/thread/839089
643
+ // https://github.com/ggml-org/llama.cpp/issues/25937
644
+ ggml_metal_dummy_work(dev);
645
+ }
646
+ #endif
647
+
648
+ return res;
649
+ }
650
+
651
+ void ggml_metal_rsets_free(ggml_metal_rsets_t rsets) {
652
+ if (rsets == NULL) {
653
+ return;
654
+ }
655
+
656
+ // note: if you hit this assert, most likely you haven't deallocated all Metal resources before exiting
657
+ GGML_ASSERT([rsets->data count] == 0);
658
+
659
+ atomic_store_explicit(&rsets->d_stop, true, memory_order_relaxed);
660
+
661
+ dispatch_group_wait(rsets->d_group, DISPATCH_TIME_FOREVER);
662
+ dispatch_release(rsets->d_group);
663
+
664
+ [rsets->data release];
665
+ [rsets->lock release];
666
+
667
+ free(rsets);
668
+ }
669
+
670
+ static enum ggml_metal_device_id ggml_metal_device_id_parse(const char * name) {
671
+ if (!name) {
672
+ return GGML_METAL_DEVICE_GENERIC;
673
+ }
674
+
675
+ static const char prefix[] = "Apple ";
676
+ if (strncmp(name, prefix, sizeof(prefix) - 1) != 0) {
677
+ return GGML_METAL_DEVICE_GENERIC;
678
+ }
679
+ const char * suffix = name + sizeof(prefix) - 1;
680
+
681
+ static const struct {
682
+ const char * name;
683
+ enum ggml_metal_device_id id;
684
+ } table[] = {
685
+ {"M1", GGML_METAL_DEVICE_M1},
686
+ {"M1 Pro", GGML_METAL_DEVICE_M1_PRO},
687
+ {"M1 Max", GGML_METAL_DEVICE_M1_MAX},
688
+ {"M1 Ultra", GGML_METAL_DEVICE_M1_ULTRA},
689
+ {"M2", GGML_METAL_DEVICE_M2},
690
+ {"M2 Pro", GGML_METAL_DEVICE_M2_PRO},
691
+ {"M2 Max", GGML_METAL_DEVICE_M2_MAX},
692
+ {"M2 Ultra", GGML_METAL_DEVICE_M2_ULTRA},
693
+ {"M3", GGML_METAL_DEVICE_M3},
694
+ {"M3 Pro", GGML_METAL_DEVICE_M3_PRO},
695
+ {"M3 Max", GGML_METAL_DEVICE_M3_MAX},
696
+ {"M3 Ultra", GGML_METAL_DEVICE_M3_ULTRA},
697
+ {"M4", GGML_METAL_DEVICE_M4},
698
+ {"M4 Pro", GGML_METAL_DEVICE_M4_PRO},
699
+ {"M4 Max", GGML_METAL_DEVICE_M4_MAX},
700
+ {"M5", GGML_METAL_DEVICE_M5},
701
+ {"M5 Pro", GGML_METAL_DEVICE_M5_PRO},
702
+ {"M5 Max", GGML_METAL_DEVICE_M5_MAX},
703
+ {"M5 Ultra", GGML_METAL_DEVICE_M5_ULTRA},
704
+ };
705
+
706
+ for (size_t i = 0; i < sizeof(table)/sizeof(table[0]); ++i) {
707
+ if (strcmp(suffix, table[i].name) == 0) {
708
+ return table[i].id;
709
+ }
710
+ }
711
+ return GGML_METAL_DEVICE_GENERIC;
712
+ }
713
+
714
+ ggml_metal_device_t ggml_metal_device_init(int device) {
715
+ ggml_metal_device_t dev = calloc(1, sizeof(struct ggml_metal_device));
716
+
717
+ assert(dev != NULL);
718
+
719
+ if (dev->mtl_device == nil) {
720
+ dev->mtl_device = MTLCreateSystemDefaultDevice();
721
+
722
+ if (dev->mtl_device) {
723
+ dev->mtl_queue = [dev->mtl_device newCommandQueue];
724
+ if (dev->mtl_queue == nil) {
725
+ GGML_LOG_ERROR("%s: error: failed to create command queue\n", __func__);
726
+ }
727
+
728
+ dev->addr_virt = 0x000000400ULL;
729
+
730
+ dev->props.device = device;
731
+ dev->props.has_simdgroup_reduction = [dev->mtl_device supportsFamily:MTLGPUFamilyApple7];
732
+ dev->props.has_simdgroup_reduction |= [dev->mtl_device supportsFamily:MTLGPUFamilyMetal3_GGML];
733
+
734
+ dev->props.has_simdgroup_mm = [dev->mtl_device supportsFamily:MTLGPUFamilyApple7];
735
+ dev->props.has_unified_memory = dev->mtl_device.hasUnifiedMemory;
736
+
737
+ dev->props.has_bfloat = [dev->mtl_device supportsFamily:MTLGPUFamilyMetal3_GGML];
738
+ dev->props.has_bfloat |= [dev->mtl_device supportsFamily:MTLGPUFamilyApple6];
739
+ if (getenv("GGML_METAL_BF16_DISABLE") != NULL) {
740
+ dev->props.has_bfloat = false;
741
+ }
742
+
743
+ dev->props.has_tensor = [dev->mtl_device supportsFamily:MTLGPUFamilyMetal4_GGML];
744
+ if (getenv("GGML_METAL_TENSOR_DISABLE") != NULL) {
745
+ dev->props.has_tensor = false;
746
+ }
747
+
748
+ // note: disable the tensor API by default for old chips because with the current implementation it is not useful
749
+ // - M2 Ultra: ~5% slower
750
+ // - M4, M4 Max: no significant difference
751
+ //
752
+ // TODO: try to update the tensor API kernels to at least match the simdgroup performance
753
+ if (getenv("GGML_METAL_TENSOR_ENABLE") == NULL &&
754
+ ![[dev->mtl_device name] containsString:@"M5"] &&
755
+ ![[dev->mtl_device name] containsString:@"M6"] &&
756
+ ![[dev->mtl_device name] containsString:@"A19"] &&
757
+ ![[dev->mtl_device name] containsString:@"A20"]) {
758
+ GGML_LOG_INFO("%s: tensor API disabled for pre-M5 and pre-A19 devices\n", __func__);
759
+ dev->props.has_tensor = false;
760
+ }
761
+
762
+ // double-check that the tensor API compiles
763
+ if (dev->props.has_tensor) {
764
+ const char * src_tensor_f16 = "\n"
765
+ "#include <metal_stdlib> \n"
766
+ "#include <metal_tensor> \n"
767
+ "#include <MetalPerformancePrimitives/MetalPerformancePrimitives.h> \n"
768
+ " \n"
769
+ "using namespace metal; \n"
770
+ "using namespace mpp::tensor_ops; \n"
771
+ " \n"
772
+ "kernel void dummy_kernel( \n"
773
+ " tensor<device half, dextents<int32_t, 2>> A [[buffer(0)]], \n"
774
+ " tensor<device half, dextents<int32_t, 2>> B [[buffer(1)]], \n"
775
+ " device float * C [[buffer(2)]], \n"
776
+ " uint2 tgid [[threadgroup_position_in_grid]]) \n"
777
+ "{ \n"
778
+ " auto tA = A.slice(0, (int)tgid.y); \n"
779
+ " auto tB = B.slice((int)tgid.x, 0); \n"
780
+ " \n"
781
+ " matmul2d< \n"
782
+ " matmul2d_descriptor(16, 16, dynamic_extent), \n"
783
+ " execution_simdgroups<4>> mm; \n"
784
+ " \n"
785
+ " auto cT = mm.get_destination_cooperative_tensor<decltype(tA), decltype(tB), float>(); \n"
786
+ " \n"
787
+ " auto sA = tA.slice(0, 0); \n"
788
+ " auto sB = tB.slice(0, 0); \n"
789
+ " mm.run(sB, sA, cT); \n"
790
+ " \n"
791
+ " auto tC = tensor<device float, dextents<int32_t, 2>, tensor_inline>(C, dextents<int32_t, 2>(16, 16)); \n"
792
+ " \n"
793
+ " cT.store(tC); \n"
794
+ "}";
795
+
796
+ GGML_LOG_INFO("%s: testing tensor API for f16 support\n", __func__);
797
+ ggml_metal_library_t lib = ggml_metal_library_init_from_source(dev, src_tensor_f16, false);
798
+ if (lib == NULL) {
799
+ GGML_LOG_WARN("%s: - the tensor API is not supported in this environment - disabling\n", __func__);
800
+ dev->props.has_tensor = false;
801
+ } else {
802
+ struct ggml_metal_pipeline_with_params ppl = ggml_metal_library_compile_pipeline(lib, "dummy_kernel", "dummy_kernel", nil);
803
+ if (!ppl.pipeline) {
804
+ GGML_LOG_WARN("%s: - the tensor API is not supported in this environment - disabling\n", __func__);
805
+ dev->props.has_tensor = false;
806
+ }
807
+
808
+ ggml_metal_library_free(lib);
809
+ }
810
+ }
811
+
812
+ // try to compile a dummy kernel to determine if the tensor API is supported for bfloat
813
+ if (dev->props.has_tensor && dev->props.has_bfloat) {
814
+ const char * src_tensor_bf16 = "\n"
815
+ "#include <metal_stdlib> \n"
816
+ "#include <metal_tensor> \n"
817
+ "#include <MetalPerformancePrimitives/MetalPerformancePrimitives.h> \n"
818
+ " \n"
819
+ "using namespace metal; \n"
820
+ "using namespace mpp::tensor_ops; \n"
821
+ " \n"
822
+ "kernel void dummy_kernel( \n"
823
+ " tensor<device bfloat, dextents<int32_t, 2>> A [[buffer(0)]], \n"
824
+ " tensor<device bfloat, dextents<int32_t, 2>> B [[buffer(1)]], \n"
825
+ " device float * C [[buffer(2)]], \n"
826
+ " uint2 tgid [[threadgroup_position_in_grid]]) \n"
827
+ "{ \n"
828
+ " auto tA = A.slice(0, (int)tgid.y); \n"
829
+ " auto tB = B.slice((int)tgid.x, 0); \n"
830
+ " \n"
831
+ " matmul2d< \n"
832
+ " matmul2d_descriptor(16, 16, dynamic_extent), \n"
833
+ " execution_simdgroups<4>> mm; \n"
834
+ " \n"
835
+ " auto cT = mm.get_destination_cooperative_tensor<decltype(tA), decltype(tB), float>(); \n"
836
+ " \n"
837
+ " auto sA = tA.slice(0, 0); \n"
838
+ " auto sB = tB.slice(0, 0); \n"
839
+ " mm.run(sB, sA, cT); \n"
840
+ " \n"
841
+ " auto tC = tensor<device float, dextents<int32_t, 2>, tensor_inline>(C, dextents<int32_t, 2>(16, 16)); \n"
842
+ " \n"
843
+ " cT.store(tC); \n"
844
+ "}";
845
+
846
+ GGML_LOG_INFO("%s: testing tensor API for bfloat support\n", __func__);
847
+ ggml_metal_library_t lib = ggml_metal_library_init_from_source(dev, src_tensor_bf16, false);
848
+ if (lib == NULL) {
849
+ GGML_LOG_WARN("%s: - the tensor API does not support bfloat - disabling bfloat support\n", __func__);
850
+ dev->props.has_bfloat = false;
851
+ } else {
852
+ struct ggml_metal_pipeline_with_params ppl = ggml_metal_library_compile_pipeline(lib, "dummy_kernel", "dummy_kernel", nil);
853
+ if (!ppl.pipeline) {
854
+ GGML_LOG_WARN("%s: - the tensor API does not support bfloat - disabling bfloat support\n", __func__);
855
+ dev->props.has_bfloat = false;
856
+ }
857
+
858
+ ggml_metal_library_free(lib);
859
+ }
860
+ }
861
+
862
+ dev->props.use_residency_sets = true;
863
+ #if defined(GGML_METAL_HAS_RESIDENCY_SETS)
864
+ dev->props.use_residency_sets = getenv("GGML_METAL_NO_RESIDENCY") == nil;
865
+ #endif
866
+
867
+ dev->props.use_shared_buffers = dev->props.has_unified_memory;
868
+ #if TARGET_OS_OSX
869
+ // In case of eGPU, shared memory may be preferable.
870
+ dev->props.use_shared_buffers |= [dev->mtl_device location] == MTLDeviceLocationExternal;
871
+ #endif
872
+ if (getenv("GGML_METAL_SHARED_BUFFERS_DISABLE") != NULL) {
873
+ dev->props.use_shared_buffers = false;
874
+ }
875
+ if (getenv("GGML_METAL_SHARED_BUFFERS_ENABLE") != NULL) {
876
+ dev->props.use_shared_buffers = true;
877
+ }
878
+
879
+ dev->props.supports_gpu_family_apple7 = [dev->mtl_device supportsFamily:MTLGPUFamilyApple7];
880
+
881
+ dev->props.device_id = ggml_metal_device_id_parse([[dev->mtl_device name] UTF8String]);
882
+
883
+ dev->props.op_offload_min_batch_size = getenv("GGML_OP_OFFLOAD_MIN_BATCH") ? atoi(getenv("GGML_OP_OFFLOAD_MIN_BATCH")) : 32;
884
+
885
+ dev->props.max_buffer_size = dev->mtl_device.maxBufferLength;
886
+ dev->props.max_theadgroup_memory_size = dev->mtl_device.maxThreadgroupMemoryLength;
887
+ if (@available(macOS 10.12, iOS 16.0, *)) {
888
+ dev->props.max_working_set_size = dev->mtl_device.recommendedMaxWorkingSetSize;
889
+ } else {
890
+ dev->props.max_working_set_size = dev->mtl_device.maxBufferLength;
891
+ }
892
+
893
+ snprintf(dev->props.name, sizeof(dev->props.name), "%s%d", "MTL", device);
894
+ snprintf(dev->props.desc, sizeof(dev->props.desc), "%s", [[dev->mtl_device name] UTF8String]);
895
+
896
+ dev->library = ggml_metal_library_init(dev);
897
+ if (!dev->library) {
898
+ GGML_LOG_ERROR("%s: error: failed to create library\n", __func__);
899
+ }
900
+
901
+ if (dev->props.use_residency_sets) {
902
+ dev->rsets = ggml_metal_rsets_init(dev);
903
+ } else {
904
+ dev->rsets = nil;
905
+ }
906
+
907
+ // print MTL GPU family:
908
+ GGML_LOG_INFO("%s: GPU name: %s (%s)\n", __func__, dev->props.name, dev->props.desc);
909
+
910
+ // determine max supported GPU family
911
+ // https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf
912
+ // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf
913
+ {
914
+ for (int i = MTLGPUFamilyApple1 + 20; i >= MTLGPUFamilyApple1; --i) {
915
+ if ([dev->mtl_device supportsFamily:i]) {
916
+ GGML_LOG_INFO("%s: GPU family: MTLGPUFamilyApple%d (%d)\n", __func__, i - (int) MTLGPUFamilyApple1 + 1, i);
917
+ break;
918
+ }
919
+ }
920
+
921
+ for (int i = MTLGPUFamilyCommon1 + 5; i >= MTLGPUFamilyCommon1; --i) {
922
+ if ([dev->mtl_device supportsFamily:i]) {
923
+ GGML_LOG_INFO("%s: GPU family: MTLGPUFamilyCommon%d (%d)\n", __func__, i - (int) MTLGPUFamilyCommon1 + 1, i);
924
+ break;
925
+ }
926
+ }
927
+
928
+ for (int i = MTLGPUFamilyMetal3_GGML + 5; i >= MTLGPUFamilyMetal3_GGML; --i) {
929
+ if ([dev->mtl_device supportsFamily:i]) {
930
+ GGML_LOG_INFO("%s: GPU family: MTLGPUFamilyMetal%d (%d)\n", __func__, i - (int) MTLGPUFamilyMetal3_GGML + 3, i);
931
+ break;
932
+ }
933
+ }
934
+ }
935
+
936
+ GGML_LOG_INFO("%s: simdgroup reduction = %s\n", __func__, dev->props.has_simdgroup_reduction ? "true" : "false");
937
+ GGML_LOG_INFO("%s: simdgroup matrix mul. = %s\n", __func__, dev->props.has_simdgroup_mm ? "true" : "false");
938
+ GGML_LOG_INFO("%s: has unified memory = %s\n", __func__, dev->props.has_unified_memory ? "true" : "false");
939
+ GGML_LOG_INFO("%s: has bfloat = %s\n", __func__, dev->props.has_bfloat ? "true" : "false");
940
+ GGML_LOG_INFO("%s: has tensor = %s\n", __func__, dev->props.has_tensor ? "true" : "false");
941
+ GGML_LOG_INFO("%s: use residency sets = %s\n", __func__, dev->props.use_residency_sets ? "true" : "false");
942
+ GGML_LOG_INFO("%s: use shared buffers = %s\n", __func__, dev->props.use_shared_buffers ? "true" : "false");
943
+
944
+ #if TARGET_OS_OSX || (TARGET_OS_IOS && __clang_major__ >= 15)
945
+ if (@available(macOS 10.12, iOS 16.0, *)) {
946
+ GGML_LOG_INFO("%s: recommendedMaxWorkingSetSize = %8.2f MB\n", __func__, dev->props.max_working_set_size / 1e6);
947
+ }
948
+ #endif
949
+ }
950
+ }
951
+
952
+ return dev;
953
+ }
954
+
955
+ void ggml_metal_device_free(ggml_metal_device_t dev) {
956
+ assert(dev != NULL);
957
+
958
+ ggml_metal_rsets_free(dev->rsets);
959
+
960
+ ggml_metal_library_free(dev->library);
961
+ dev->library = NULL;
962
+
963
+ if (dev->mtl_queue) {
964
+ [dev->mtl_queue release];
965
+ dev->mtl_queue = nil;
966
+ }
967
+
968
+ if (dev->mtl_device) {
969
+ [dev->mtl_device release];
970
+ dev->mtl_device = nil;
971
+ }
972
+
973
+ free(dev);
974
+ }
975
+
976
+ void * ggml_metal_device_get_obj(ggml_metal_device_t dev) {
977
+ return dev->mtl_device;
978
+ }
979
+
980
+ void * ggml_metal_device_get_queue(ggml_metal_device_t dev) {
981
+ return dev->mtl_queue;
982
+ }
983
+
984
+ ggml_metal_library_t ggml_metal_device_get_library(ggml_metal_device_t dev) {
985
+ return dev->library;
986
+ }
987
+
988
+ void ggml_metal_device_rsets_add(ggml_metal_device_t dev, ggml_metal_rset_t rset) {
989
+ if (rset == nil) {
990
+ return;
991
+ }
992
+
993
+ GGML_ASSERT(dev->rsets);
994
+
995
+ [dev->rsets->lock lock];
996
+
997
+ [dev->rsets->data addObject:rset];
998
+
999
+ [dev->rsets->lock unlock];
1000
+ }
1001
+
1002
+ void ggml_metal_device_rsets_rm(ggml_metal_device_t dev, ggml_metal_rset_t rset) {
1003
+ if (rset == nil) {
1004
+ return;
1005
+ }
1006
+
1007
+ GGML_ASSERT(dev->rsets);
1008
+
1009
+ [dev->rsets->lock lock];
1010
+
1011
+ [dev->rsets->data removeObject:rset];
1012
+
1013
+ [dev->rsets->lock unlock];
1014
+ }
1015
+
1016
+ void ggml_metal_device_rsets_keep_alive(ggml_metal_device_t dev) {
1017
+ if (dev->rsets == NULL) {
1018
+ return;
1019
+ }
1020
+
1021
+ atomic_store_explicit(&dev->rsets->d_loop, dev->rsets->loops_per_s*dev->rsets->keep_alive_s, memory_order_relaxed);
1022
+ }
1023
+
1024
+ struct ggml_metal_event {
1025
+ void * obj; // id<MTLSharedEvent>
1026
+
1027
+ atomic_int value;
1028
+ };
1029
+
1030
+ void ggml_metal_event_encode_signal(ggml_metal_event_t ev, ggml_metal_cmd_buf_t cmd_buf_raw) {
1031
+ id<MTLSharedEvent> event = (id<MTLSharedEvent>)ev->obj;
1032
+
1033
+ id<MTLCommandBuffer> cmd_buf = (id<MTLCommandBuffer>) cmd_buf_raw;
1034
+
1035
+ [cmd_buf encodeSignalEvent:event value:atomic_fetch_add_explicit(&ev->value, 1, memory_order_relaxed) + 1];
1036
+ }
1037
+
1038
+ void ggml_metal_event_encode_wait(ggml_metal_event_t ev, ggml_metal_cmd_buf_t cmd_buf_raw) {
1039
+ id<MTLSharedEvent> event = (id<MTLSharedEvent>)ev->obj;
1040
+
1041
+ id<MTLCommandBuffer> cmd_buf = (id<MTLCommandBuffer>) cmd_buf_raw;
1042
+
1043
+ [cmd_buf encodeWaitForEvent:event value:atomic_load_explicit(&ev->value, memory_order_relaxed)];
1044
+ }
1045
+
1046
+ ggml_metal_event_t ggml_metal_device_event_init(ggml_metal_device_t dev) {
1047
+ id<MTLSharedEvent> event = [dev->mtl_device newSharedEvent];
1048
+
1049
+ ggml_metal_event_t ev = calloc(1, sizeof(struct ggml_metal_event));
1050
+
1051
+ ev->obj = (__bridge void *)event;
1052
+ ev->value = 0;
1053
+
1054
+ return ev;
1055
+ }
1056
+
1057
+ void ggml_metal_device_event_free(ggml_metal_device_t dev, ggml_metal_event_t ev) {
1058
+ id<MTLSharedEvent> event = ev->obj;
1059
+ [event release];
1060
+
1061
+ free(ev);
1062
+
1063
+ GGML_UNUSED(dev);
1064
+ }
1065
+
1066
+ void ggml_metal_device_event_synchronize(ggml_metal_device_t dev, ggml_metal_event_t ev) {
1067
+ id<MTLSharedEvent> event = ev->obj;
1068
+ const bool res = [event waitUntilSignaledValue:atomic_load_explicit(&ev->value, memory_order_relaxed) timeoutMS:60000];
1069
+ if (!res) {
1070
+ GGML_ABORT("%s: failed to wait for event\n", __func__);
1071
+ }
1072
+
1073
+ GGML_UNUSED(dev);
1074
+ }
1075
+
1076
+ void ggml_metal_device_get_memory(ggml_metal_device_t dev, size_t * free, size_t * total) {
1077
+ if (@available(macOS 10.12, iOS 16.0, *)) {
1078
+ *total = dev->mtl_device.recommendedMaxWorkingSetSize;
1079
+ *free = *total - dev->mtl_device.currentAllocatedSize;
1080
+ } else {
1081
+ *free = 0;
1082
+ *total = 0;
1083
+ }
1084
+ }
1085
+
1086
+ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_tensor * op) {
1087
+ const bool has_simdgroup_mm = dev->props.has_simdgroup_mm;
1088
+ const bool has_simdgroup_reduction = dev->props.has_simdgroup_reduction;
1089
+ const bool has_bfloat = dev->props.has_bfloat;
1090
+
1091
+ if (!has_bfloat) {
1092
+ if (op->type == GGML_TYPE_BF16) {
1093
+ return false;
1094
+ }
1095
+
1096
+ for (size_t i = 0, n = 3; i < n; ++i) {
1097
+ if (op->src[i] != NULL && op->src[i]->type == GGML_TYPE_BF16) {
1098
+ return false;
1099
+ }
1100
+ }
1101
+ }
1102
+
1103
+ switch (op->op) {
1104
+ case GGML_OP_SCALE:
1105
+ case GGML_OP_FILL:
1106
+ case GGML_OP_CLAMP:
1107
+ case GGML_OP_SQR:
1108
+ case GGML_OP_SQRT:
1109
+ case GGML_OP_SIN:
1110
+ case GGML_OP_COS:
1111
+ case GGML_OP_LOG:
1112
+ return ggml_is_contiguous_rows(op->src[0]) && (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16);
1113
+ case GGML_OP_UNARY:
1114
+ switch (ggml_get_unary_op(op)) {
1115
+ case GGML_UNARY_OP_TANH:
1116
+ case GGML_UNARY_OP_RELU:
1117
+ case GGML_UNARY_OP_SIGMOID:
1118
+ case GGML_UNARY_OP_GELU:
1119
+ case GGML_UNARY_OP_GELU_ERF:
1120
+ case GGML_UNARY_OP_GELU_QUICK:
1121
+ case GGML_UNARY_OP_SILU:
1122
+ case GGML_UNARY_OP_ELU:
1123
+ case GGML_UNARY_OP_NEG:
1124
+ case GGML_UNARY_OP_ABS:
1125
+ case GGML_UNARY_OP_SGN:
1126
+ case GGML_UNARY_OP_STEP:
1127
+ case GGML_UNARY_OP_HARDSWISH:
1128
+ case GGML_UNARY_OP_HARDSIGMOID:
1129
+ case GGML_UNARY_OP_EXP:
1130
+ case GGML_UNARY_OP_SOFTPLUS:
1131
+ case GGML_UNARY_OP_EXPM1:
1132
+ case GGML_UNARY_OP_FLOOR:
1133
+ case GGML_UNARY_OP_CEIL:
1134
+ case GGML_UNARY_OP_ROUND:
1135
+ case GGML_UNARY_OP_TRUNC:
1136
+ case GGML_UNARY_OP_XIELU:
1137
+ return ggml_is_contiguous_rows(op->src[0]) && (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16);
1138
+ default:
1139
+ return false;
1140
+ }
1141
+ case GGML_OP_SILU_BACK:
1142
+ return (op->src[0]->type == GGML_TYPE_F32) &&
1143
+ (op->src[1]->type == GGML_TYPE_F32) &&
1144
+ (op->type == GGML_TYPE_F32) &&
1145
+ ggml_is_contiguous(op->src[0]) &&
1146
+ ggml_is_contiguous(op->src[1]) &&
1147
+ ggml_is_contiguous(op) &&
1148
+ ggml_are_same_shape(op->src[0], op->src[1]);
1149
+ case GGML_OP_GLU:
1150
+ switch (ggml_get_glu_op(op)) {
1151
+ case GGML_GLU_OP_REGLU:
1152
+ case GGML_GLU_OP_GEGLU:
1153
+ case GGML_GLU_OP_SWIGLU:
1154
+ case GGML_GLU_OP_SWIGLU_OAI:
1155
+ case GGML_GLU_OP_GEGLU_ERF:
1156
+ case GGML_GLU_OP_GEGLU_QUICK:
1157
+ return ggml_is_contiguous_1(op->src[0]) && (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16);
1158
+ default:
1159
+ return false;
1160
+ }
1161
+ case GGML_OP_NONE:
1162
+ case GGML_OP_RESHAPE:
1163
+ case GGML_OP_VIEW:
1164
+ case GGML_OP_TRANSPOSE:
1165
+ case GGML_OP_PERMUTE:
1166
+ return true;
1167
+ case GGML_OP_CONCAT:
1168
+ {
1169
+ const enum ggml_type src0_type = op->src[0]->type;
1170
+ const enum ggml_type src1_type = op->src[1]->type;
1171
+ if (src0_type != src1_type || src0_type != op->type) {
1172
+ return false;
1173
+ }
1174
+ switch (src0_type) {
1175
+ case GGML_TYPE_F32:
1176
+ case GGML_TYPE_F16:
1177
+ case GGML_TYPE_I8:
1178
+ case GGML_TYPE_I16:
1179
+ case GGML_TYPE_I32:
1180
+ case GGML_TYPE_I64:
1181
+ return true;
1182
+ case GGML_TYPE_BF16:
1183
+ return has_bfloat;
1184
+ default:
1185
+ return false;
1186
+ }
1187
+ }
1188
+ case GGML_OP_ADD:
1189
+ case GGML_OP_SUB:
1190
+ case GGML_OP_MUL:
1191
+ case GGML_OP_DIV:
1192
+ case GGML_OP_ADD_ID:
1193
+ return ggml_is_contiguous_rows(op->src[0]) && ggml_is_contiguous_rows(op->src[1]) && (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) && (op->src[0]->type == op->src[1]->type);
1194
+ case GGML_OP_ACC:
1195
+ return ggml_is_contiguous_rows(op->src[0]) && ggml_is_contiguous_rows(op->src[1]) && op->src[0]->type == GGML_TYPE_F32;
1196
+ case GGML_OP_REPEAT:
1197
+ case GGML_OP_CONV_TRANSPOSE_1D:
1198
+ return true;
1199
+ case GGML_OP_CONV_TRANSPOSE_2D:
1200
+ return ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op->src[1]) &&
1201
+ (op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_F32) &&
1202
+ op->src[1]->type == GGML_TYPE_F32 &&
1203
+ op->type == GGML_TYPE_F32;
1204
+ case GGML_OP_COL2IM_1D:
1205
+ return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_BF16) &&
1206
+ op->type == op->src[0]->type &&
1207
+ ggml_is_contiguous(op->src[0]) &&
1208
+ ggml_is_contiguous(op);
1209
+ case GGML_OP_CONV_3D:
1210
+ return ggml_is_contiguous(op->src[0]) &&
1211
+ ggml_is_contiguous(op->src[1]) &&
1212
+ (op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_F32) &&
1213
+ op->src[1]->type == GGML_TYPE_F32;
1214
+ case GGML_OP_SUM:
1215
+ return has_simdgroup_reduction && ggml_is_contiguous(op->src[0]);
1216
+ case GGML_OP_TRI:
1217
+ return ggml_is_contiguous_rows(op->src[0]);
1218
+ case GGML_OP_SUM_ROWS:
1219
+ case GGML_OP_CUMSUM:
1220
+ case GGML_OP_MEAN:
1221
+ case GGML_OP_SOFT_MAX:
1222
+ case GGML_OP_GROUP_NORM:
1223
+ case GGML_OP_L2_NORM:
1224
+ return has_simdgroup_reduction && ggml_is_contiguous_rows(op->src[0]);
1225
+ case GGML_OP_COUNT_EQUAL:
1226
+ return has_simdgroup_reduction &&
1227
+ op->src[0]->type == GGML_TYPE_I32 &&
1228
+ op->src[1]->type == GGML_TYPE_I32 &&
1229
+ op->type == GGML_TYPE_I64;
1230
+ case GGML_OP_ARGMAX:
1231
+ return has_simdgroup_reduction;
1232
+ case GGML_OP_NORM:
1233
+ case GGML_OP_RMS_NORM:
1234
+ return has_simdgroup_reduction && (ggml_is_contiguous_rows(op->src[0]));
1235
+ case GGML_OP_ROPE:
1236
+ case GGML_OP_ROPE_BACK:
1237
+ return true;
1238
+ case GGML_OP_IM2COL:
1239
+ return ggml_is_contiguous(op->src[1]) && op->src[1]->type == GGML_TYPE_F32 && (op->type == GGML_TYPE_F16 || op->type == GGML_TYPE_F32);
1240
+ case GGML_OP_CONV_2D:
1241
+ return ggml_is_contiguous(op->src[0]) &&
1242
+ op->src[1]->type == GGML_TYPE_F32 &&
1243
+ op->type == GGML_TYPE_F32 &&
1244
+ (op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_F32);
1245
+ case GGML_OP_CONV_2D_DW:
1246
+ return op->src[1]->type == GGML_TYPE_F32 &&
1247
+ op->type == GGML_TYPE_F32 &&
1248
+ (op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_F32);
1249
+ case GGML_OP_UPSCALE:
1250
+ return op->src[0]->type == GGML_TYPE_F32;
1251
+ case GGML_OP_POOL_1D:
1252
+ return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
1253
+ case GGML_OP_POOL_2D:
1254
+ return op->src[0]->type == GGML_TYPE_F32;
1255
+ case GGML_OP_PAD:
1256
+ // TODO: add circular padding support for metal, see https://github.com/ggml-org/llama.cpp/pull/16985
1257
+ if (ggml_get_op_params_i32(op, 8) != 0) {
1258
+ return false;
1259
+ }
1260
+
1261
+ return (ggml_get_op_params_i32(op, 0) == 0) && (ggml_get_op_params_i32(op, 2) == 0) &&
1262
+ (ggml_get_op_params_i32(op, 4) == 0) && (ggml_get_op_params_i32(op, 6) == 0);
1263
+ case GGML_OP_PAD_REFLECT_1D:
1264
+ case GGML_OP_TIMESTEP_EMBEDDING:
1265
+ return op->src[0]->type == GGML_TYPE_F32;
1266
+ case GGML_OP_LEAKY_RELU:
1267
+ return op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16;
1268
+ case GGML_OP_ARGSORT:
1269
+ case GGML_OP_TOP_K:
1270
+ case GGML_OP_ARANGE:
1271
+ return true;
1272
+ case GGML_OP_ROLL:
1273
+ return ggml_is_contiguous(op->src[0]);
1274
+ case GGML_OP_FLASH_ATTN_EXT:
1275
+ // for new head sizes, add checks here
1276
+ if (op->src[0]->ne[0] != 32 &&
1277
+ op->src[0]->ne[0] != 40 &&
1278
+ op->src[0]->ne[0] != 48 &&
1279
+ op->src[0]->ne[0] != 64 &&
1280
+ op->src[0]->ne[0] != 72 &&
1281
+ op->src[0]->ne[0] != 80 &&
1282
+ op->src[0]->ne[0] != 96 &&
1283
+ op->src[0]->ne[0] != 112 &&
1284
+ op->src[0]->ne[0] != 128 &&
1285
+ op->src[0]->ne[0] != 192 &&
1286
+ op->src[0]->ne[0] != 256 &&
1287
+ op->src[0]->ne[0] != 320 &&
1288
+ op->src[0]->ne[0] != 512 &&
1289
+ op->src[0]->ne[0] != 576) {
1290
+ return false;
1291
+ }
1292
+ if (op->src[1]->type != op->src[2]->type) {
1293
+ return false;
1294
+ }
1295
+ switch (op->src[1]->type) {
1296
+ case GGML_TYPE_F32:
1297
+ case GGML_TYPE_F16:
1298
+ case GGML_TYPE_Q8_0:
1299
+ case GGML_TYPE_Q4_0:
1300
+ case GGML_TYPE_Q4_1:
1301
+ case GGML_TYPE_Q5_0:
1302
+ case GGML_TYPE_Q5_1:
1303
+ break;
1304
+ case GGML_TYPE_BF16:
1305
+ if (!has_bfloat) {
1306
+ return false;
1307
+ }
1308
+ break;
1309
+ default:
1310
+ return false;
1311
+ }
1312
+ return has_simdgroup_mm; // TODO: over-restricted for vec-kernels
1313
+ case GGML_OP_LIGHTNING_INDEXER:
1314
+ if (op->src[0]->ne[0] != OP_LIGHTNING_INDEXER_DK ||
1315
+ op->src[0]->ne[1] != OP_LIGHTNING_INDEXER_NH) {
1316
+ return false;
1317
+ }
1318
+ if (!has_simdgroup_mm ||
1319
+ op->src[0]->type != GGML_TYPE_F32 ||
1320
+ op->src[2]->type != GGML_TYPE_F32 ||
1321
+ op->src[3]->type != GGML_TYPE_F16 ||
1322
+ op->type != GGML_TYPE_F32 ||
1323
+ !ggml_is_contiguous_rows(op->src[0]) ||
1324
+ !ggml_is_contiguous_rows(op->src[1]) ||
1325
+ !ggml_is_contiguous_rows(op->src[2]) ||
1326
+ !ggml_is_contiguous_rows(op->src[3])) {
1327
+ return false;
1328
+ }
1329
+ switch (op->src[1]->type) {
1330
+ case GGML_TYPE_F32:
1331
+ case GGML_TYPE_F16:
1332
+ case GGML_TYPE_Q4_0:
1333
+ case GGML_TYPE_Q4_1:
1334
+ case GGML_TYPE_Q5_0:
1335
+ case GGML_TYPE_Q5_1:
1336
+ case GGML_TYPE_Q8_0:
1337
+ return true;
1338
+ case GGML_TYPE_BF16:
1339
+ return has_bfloat;
1340
+ default:
1341
+ return false;
1342
+ }
1343
+ case GGML_OP_DSV4_HC_COMB:
1344
+ return has_simdgroup_reduction &&
1345
+ op->src[0]->type == GGML_TYPE_F32 &&
1346
+ op->src[1]->type == GGML_TYPE_F32 &&
1347
+ op->src[2]->type == GGML_TYPE_F32 &&
1348
+ op->type == GGML_TYPE_F32 &&
1349
+ op->src[0]->ne[0] == 24 &&
1350
+ op->src[1]->ne[0] >= 3 &&
1351
+ op->src[2]->ne[0] == 24 &&
1352
+ ggml_is_contiguous_rows(op->src[0]) &&
1353
+ ggml_is_contiguous_rows(op->src[1]) &&
1354
+ ggml_is_contiguous_rows(op->src[2]);
1355
+ case GGML_OP_DSV4_HC_PRE:
1356
+ return has_simdgroup_reduction &&
1357
+ op->src[0]->type == GGML_TYPE_F32 &&
1358
+ op->src[1]->type == GGML_TYPE_F32 &&
1359
+ op->type == GGML_TYPE_F32 &&
1360
+ op->src[0]->ne[1] == 4 &&
1361
+ op->src[1]->ne[0] == 4 &&
1362
+ ggml_is_contiguous_rows(op->src[0]) &&
1363
+ ggml_is_contiguous_rows(op->src[1]);
1364
+ case GGML_OP_DSV4_HC_POST:
1365
+ return has_simdgroup_reduction &&
1366
+ op->src[0]->type == GGML_TYPE_F32 &&
1367
+ op->src[1]->type == GGML_TYPE_F32 &&
1368
+ op->src[2]->type == GGML_TYPE_F32 &&
1369
+ op->src[3]->type == GGML_TYPE_F32 &&
1370
+ op->type == GGML_TYPE_F32 &&
1371
+ op->src[1]->ne[1] == 4 &&
1372
+ op->src[2]->ne[0] == 4 &&
1373
+ op->src[3]->ne[0] == 4 &&
1374
+ op->src[3]->ne[1] == 4 &&
1375
+ ggml_is_contiguous_rows(op->src[0]) &&
1376
+ ggml_is_contiguous_rows(op->src[1]) &&
1377
+ ggml_is_contiguous_rows(op->src[2]) &&
1378
+ ggml_is_contiguous_rows(op->src[3]);
1379
+ case GGML_OP_SSM_CONV:
1380
+ case GGML_OP_SSM_SCAN:
1381
+ return has_simdgroup_reduction;
1382
+ case GGML_OP_RWKV_WKV6:
1383
+ case GGML_OP_RWKV_WKV7:
1384
+ return true;
1385
+ case GGML_OP_GATED_DELTA_NET:
1386
+ return has_simdgroup_reduction && op->src[2]->ne[0] % 32 == 0;
1387
+ case GGML_OP_SOLVE_TRI:
1388
+ case GGML_OP_MUL_MAT:
1389
+ case GGML_OP_MUL_MAT_ID:
1390
+ return has_simdgroup_reduction && op->src[0]->type != GGML_TYPE_NVFP4;
1391
+ case GGML_OP_SET:
1392
+ case GGML_OP_CPY:
1393
+ case GGML_OP_DUP:
1394
+ case GGML_OP_CONT:
1395
+ {
1396
+ switch (op->src[0]->type) {
1397
+ case GGML_TYPE_F32:
1398
+ switch (op->type) {
1399
+ case GGML_TYPE_F32:
1400
+ case GGML_TYPE_F16:
1401
+ case GGML_TYPE_BF16:
1402
+ case GGML_TYPE_Q8_0:
1403
+ case GGML_TYPE_Q1_0:
1404
+ case GGML_TYPE_Q2_0:
1405
+ case GGML_TYPE_Q4_0:
1406
+ case GGML_TYPE_Q4_1:
1407
+ case GGML_TYPE_Q5_0:
1408
+ case GGML_TYPE_Q5_1:
1409
+ case GGML_TYPE_IQ4_NL:
1410
+ case GGML_TYPE_I32:
1411
+ return true;
1412
+ default:
1413
+ return false;
1414
+ }
1415
+ case GGML_TYPE_F16:
1416
+ switch (op->type) {
1417
+ case GGML_TYPE_F32:
1418
+ case GGML_TYPE_F16:
1419
+ return true;
1420
+ default:
1421
+ return false;
1422
+ }
1423
+ case GGML_TYPE_BF16:
1424
+ switch (op->type) {
1425
+ case GGML_TYPE_F32:
1426
+ case GGML_TYPE_BF16:
1427
+ return true;
1428
+ default:
1429
+ return false;
1430
+ }
1431
+ case GGML_TYPE_Q1_0:
1432
+ case GGML_TYPE_Q2_0:
1433
+ case GGML_TYPE_Q4_0:
1434
+ case GGML_TYPE_Q4_1:
1435
+ case GGML_TYPE_Q5_0:
1436
+ case GGML_TYPE_Q5_1:
1437
+ case GGML_TYPE_Q8_0:
1438
+ switch (op->type) {
1439
+ case GGML_TYPE_F32:
1440
+ case GGML_TYPE_F16:
1441
+ return true;
1442
+ default:
1443
+ return false;
1444
+ }
1445
+ case GGML_TYPE_I32:
1446
+ return op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_I32;
1447
+ default:
1448
+ return false;
1449
+ };
1450
+ }
1451
+ case GGML_OP_GET_ROWS:
1452
+ return op->src[0]->type != GGML_TYPE_NVFP4;
1453
+ case GGML_OP_SET_ROWS:
1454
+ {
1455
+ if (op->src[0]->type == GGML_TYPE_F16) {
1456
+ return op->type == GGML_TYPE_F16;
1457
+ }
1458
+
1459
+ if (op->src[0]->type != GGML_TYPE_F32) {
1460
+ return false;
1461
+ }
1462
+
1463
+ switch (op->type) {
1464
+ case GGML_TYPE_F32:
1465
+ case GGML_TYPE_F16:
1466
+ case GGML_TYPE_BF16:
1467
+ case GGML_TYPE_Q8_0:
1468
+ case GGML_TYPE_Q4_0:
1469
+ case GGML_TYPE_Q4_1:
1470
+ case GGML_TYPE_Q5_0:
1471
+ case GGML_TYPE_Q5_1:
1472
+ case GGML_TYPE_IQ4_NL:
1473
+ return true;
1474
+ default:
1475
+ return false;
1476
+ };
1477
+ }
1478
+ case GGML_OP_DIAG:
1479
+ return true;
1480
+ case GGML_OP_OPT_STEP_ADAMW:
1481
+ case GGML_OP_OPT_STEP_SGD:
1482
+ return has_simdgroup_reduction;
1483
+ default:
1484
+ return false;
1485
+ }
1486
+ }
1487
+
1488
+ const struct ggml_metal_device_props * ggml_metal_device_get_props(ggml_metal_device_t dev) {
1489
+ return &dev->props;
1490
+ }
1491
+
1492
+ //
1493
+ // device buffers
1494
+ //
1495
+
1496
+ // max memory buffers that can be mapped to the device
1497
+ #define GGML_METAL_MAX_BUFFERS 64
1498
+
1499
+ struct ggml_metal_buffer_wrapper {
1500
+ void * data;
1501
+ size_t size;
1502
+
1503
+ id<MTLBuffer> metal;
1504
+ };
1505
+
1506
+ struct ggml_metal_buffer {
1507
+ void * all_data;
1508
+ size_t all_size;
1509
+
1510
+ // if false, the Metal buffer data is allocated in private GPU memory and is not shared with the host
1511
+ bool is_shared;
1512
+ bool owned;
1513
+
1514
+ // multiple buffers are used only to avoid the maximum buffer size limitation when using mmap
1515
+ int n_buffers;
1516
+ struct ggml_metal_buffer_wrapper buffers[GGML_METAL_MAX_BUFFERS];
1517
+
1518
+ bool use_residency_sets;
1519
+
1520
+ // optional MTLResidencySet
1521
+ // note: cannot use explicitly "id<MTLResidencySet>" here because it is not available on certain OSes
1522
+ id rset;
1523
+
1524
+ // pointers to global device
1525
+ ggml_metal_device_t dev;
1526
+ };
1527
+
1528
+ static void ggml_metal_log_allocated_size(id<MTLDevice> device, size_t size_aligned) {
1529
+ #ifndef GGML_METAL_NDEBUG
1530
+ #if TARGET_OS_OSX || (TARGET_OS_IOS && __clang_major__ >= 15)
1531
+ if (@available(macOS 10.12, iOS 16.0, *)) {
1532
+ GGML_LOG_DEBUG("%s: allocated buffer, size = %8.2f MiB, (%8.2f / %8.2f)\n",
1533
+ __func__,
1534
+ size_aligned / 1024.0 / 1024.0,
1535
+ device.currentAllocatedSize / 1024.0 / 1024.0,
1536
+ device.recommendedMaxWorkingSetSize / 1024.0 / 1024.0);
1537
+
1538
+ if (device.currentAllocatedSize > device.recommendedMaxWorkingSetSize) {
1539
+ GGML_LOG_WARN("%s: warning: current allocated size is greater than the recommended max working set size\n", __func__);
1540
+ }
1541
+ } else {
1542
+ GGML_LOG_INFO("%s: allocated buffer, size = %8.2f MiB, (%8.2f)\n",
1543
+ __func__,
1544
+ size_aligned / 1024.0 / 1024.0,
1545
+ device.currentAllocatedSize / 1024.0 / 1024.0);
1546
+ }
1547
+ #endif
1548
+ #endif
1549
+ GGML_UNUSED(device);
1550
+ GGML_UNUSED(size_aligned);
1551
+ }
1552
+
1553
+ // rset init
1554
+ static bool ggml_metal_buffer_rset_init(ggml_metal_buffer_t buf) {
1555
+ buf->rset = nil;
1556
+
1557
+ if (!buf->use_residency_sets) {
1558
+ return true;
1559
+ }
1560
+
1561
+ #if defined(GGML_METAL_HAS_RESIDENCY_SETS)
1562
+ if (@available(macOS 15.0, iOS 18.0, tvOS 18.0, visionOS 2.0, *)) {
1563
+ MTLResidencySetDescriptor * desc = [[MTLResidencySetDescriptor alloc] init];
1564
+ desc.label = @"ggml_metal";
1565
+ desc.initialCapacity = buf->n_buffers;
1566
+
1567
+ NSError * error;
1568
+ buf->rset = [buf->dev->mtl_device newResidencySetWithDescriptor:desc error:&error];
1569
+ if (error) {
1570
+ GGML_LOG_ERROR("%s: error: %s\n", __func__, [[error description] UTF8String]);
1571
+ [desc release];
1572
+ return false;
1573
+ }
1574
+
1575
+ [desc release];
1576
+
1577
+ for (int i = 0; i < buf->n_buffers; i++) {
1578
+ [buf->rset addAllocation:buf->buffers[i].metal];
1579
+ }
1580
+
1581
+ [buf->rset commit];
1582
+ [buf->rset requestResidency];
1583
+
1584
+ return true;
1585
+ }
1586
+ #endif
1587
+
1588
+ return true;
1589
+ }
1590
+
1591
+ // rset free
1592
+ static void ggml_metal_buffer_rset_free(ggml_metal_buffer_t buf) {
1593
+ #if defined(GGML_METAL_HAS_RESIDENCY_SETS)
1594
+ if (@available(macOS 15.0, iOS 18.0, tvOS 18.0, visionOS 2.0, *)) {
1595
+ if (buf->rset) {
1596
+ [buf->rset endResidency];
1597
+ [buf->rset removeAllAllocations];
1598
+ [buf->rset commit];
1599
+ [buf->rset release];
1600
+ }
1601
+ }
1602
+ #else
1603
+ GGML_UNUSED(buf);
1604
+ #endif
1605
+ }
1606
+
1607
+ static void * ggml_metal_host_malloc(size_t n) {
1608
+ void * data = NULL;
1609
+
1610
+ #if TARGET_OS_OSX
1611
+ kern_return_t err = vm_allocate((vm_map_t) mach_task_self(), (void *) &data, n, VM_FLAGS_ANYWHERE);
1612
+ if (err != KERN_SUCCESS) {
1613
+ GGML_LOG_ERROR("%s: error: vm_allocate failed\n", __func__);
1614
+ return NULL;
1615
+ }
1616
+ #else
1617
+ const int result = posix_memalign((void **) &data, sysconf(_SC_PAGESIZE), n);
1618
+ if (result != 0) {
1619
+ GGML_LOG_ERROR("%s: error: posix_memalign failed\n", __func__);
1620
+ return NULL;
1621
+ }
1622
+ #endif
1623
+
1624
+ return data;
1625
+ }
1626
+
1627
+ ggml_metal_buffer_t ggml_metal_buffer_init(ggml_metal_device_t dev, size_t size, bool shared) {
1628
+ ggml_metal_buffer_t res = calloc(1, sizeof(struct ggml_metal_buffer));
1629
+
1630
+ res->dev = dev;
1631
+
1632
+ const size_t size_page = sysconf(_SC_PAGESIZE);
1633
+
1634
+ size_t size_aligned = size;
1635
+ if ((size_aligned % size_page) != 0) {
1636
+ size_aligned += (size_page - (size_aligned % size_page));
1637
+ }
1638
+
1639
+ const struct ggml_metal_device_props * props_dev = ggml_metal_device_get_props(dev);
1640
+
1641
+ shared = shared && props_dev->use_shared_buffers;
1642
+
1643
+ // allocate shared buffer if the device supports it and it is required by the buffer type
1644
+ if (shared) {
1645
+ res->all_data = ggml_metal_host_malloc(size_aligned);
1646
+ res->is_shared = true;
1647
+ } else {
1648
+ // use virtual address
1649
+ res->all_data = (void *) atomic_fetch_add_explicit(&dev->addr_virt, size_aligned, memory_order_relaxed);
1650
+ res->is_shared = false;
1651
+ }
1652
+ res->all_size = size_aligned;
1653
+
1654
+ res->owned = true;
1655
+
1656
+ res->n_buffers = 1;
1657
+
1658
+ if (res->all_data != NULL) {
1659
+ res->buffers[0].size = size;
1660
+ res->buffers[0].metal = nil;
1661
+
1662
+ if (size_aligned > 0) {
1663
+ if (props_dev->use_shared_buffers && shared) {
1664
+ res->buffers[0].metal = [res->dev->mtl_device newBufferWithBytesNoCopy:res->all_data
1665
+ length:size_aligned
1666
+ options:MTLResourceStorageModeShared
1667
+ deallocator:nil];
1668
+ } else {
1669
+ res->buffers[0].metal = [res->dev->mtl_device newBufferWithLength:size_aligned options:MTLResourceStorageModePrivate];
1670
+ }
1671
+ }
1672
+
1673
+ res->buffers[0].data = res->all_data;
1674
+ }
1675
+
1676
+ if (size_aligned > 0 && (res->all_data == NULL || res->buffers[0].metal == nil)) {
1677
+ GGML_LOG_ERROR("%s: error: failed to allocate buffer, size = %8.2f MiB\n", __func__, size_aligned / 1024.0 / 1024.0);
1678
+ free(res);
1679
+ return NULL;
1680
+ }
1681
+
1682
+ res->use_residency_sets = props_dev->use_residency_sets;
1683
+
1684
+ if (!ggml_metal_buffer_rset_init(res)) {
1685
+ GGML_LOG_ERROR("%s: error: failed to initialize residency set\n", __func__);
1686
+ free(res);
1687
+ return NULL;
1688
+ }
1689
+
1690
+ ggml_metal_device_rsets_add(dev, res->rset);
1691
+
1692
+ //ggml_metal_log_allocated_size(device, size_aligned);
1693
+
1694
+ return res;
1695
+ }
1696
+
1697
+ ggml_metal_buffer_t ggml_metal_buffer_map(ggml_metal_device_t dev, void * ptr, size_t size, size_t max_tensor_size) {
1698
+ ggml_metal_buffer_t res = calloc(1, sizeof(struct ggml_metal_buffer));
1699
+
1700
+ res->dev = dev;
1701
+
1702
+ res->all_data = ptr;
1703
+ res->all_size = size;
1704
+
1705
+ res->is_shared = true;
1706
+ res->owned = false;
1707
+
1708
+ res->n_buffers = 0;
1709
+
1710
+ const size_t size_page = sysconf(_SC_PAGESIZE);
1711
+
1712
+ // page-align the data ptr
1713
+ {
1714
+ const uintptr_t offs = (uintptr_t) ptr % size_page;
1715
+ ptr = (void *) ((char *) ptr - offs);
1716
+ size += offs;
1717
+ }
1718
+
1719
+ size_t size_aligned = size;
1720
+ if ((size_aligned % size_page) != 0) {
1721
+ size_aligned += (size_page - (size_aligned % size_page));
1722
+ }
1723
+
1724
+ const struct ggml_metal_device_props * props_dev = ggml_metal_device_get_props(dev);
1725
+
1726
+ // the buffer fits into the max buffer size allowed by the device
1727
+ if (size_aligned <= props_dev->max_buffer_size) {
1728
+ res->buffers[res->n_buffers].data = ptr;
1729
+ res->buffers[res->n_buffers].size = size;
1730
+ res->buffers[res->n_buffers].metal = nil;
1731
+
1732
+ if (size_aligned > 0) {
1733
+ res->buffers[res->n_buffers].metal = [res->dev->mtl_device newBufferWithBytesNoCopy:ptr length:size_aligned options:MTLResourceStorageModeShared deallocator:nil];
1734
+
1735
+ if (res->buffers[res->n_buffers].metal == nil) {
1736
+ GGML_LOG_ERROR("%s: error: failed to allocate buffer, size = %8.2f MiB\n", __func__, size_aligned / 1024.0 / 1024.0);
1737
+ free(res);
1738
+ return NULL;
1739
+ }
1740
+ }
1741
+
1742
+ ggml_metal_log_allocated_size(res->dev->mtl_device, size_aligned);
1743
+
1744
+ ++res->n_buffers;
1745
+ } else {
1746
+ // this overlap between the views will guarantee that the tensor with the maximum size will fully fit into
1747
+ // one of the views
1748
+ const size_t size_ovlp = ((max_tensor_size + size_page - 1) / size_page + 1) * size_page; // round-up 2 pages just in case
1749
+ const size_t size_step = props_dev->max_buffer_size - size_ovlp;
1750
+ const size_t size_view = props_dev->max_buffer_size;
1751
+
1752
+ for (size_t i = 0; i < size; i += size_step) {
1753
+ const size_t size_step_aligned = (i + size_view <= size) ? size_view : (size_aligned - i);
1754
+
1755
+ res->buffers[res->n_buffers].data = (void *) ((uint8_t *) ptr + i);
1756
+ res->buffers[res->n_buffers].size = size_step_aligned;
1757
+ res->buffers[res->n_buffers].metal = nil;
1758
+
1759
+ if (size_step_aligned > 0) {
1760
+ res->buffers[res->n_buffers].metal = [res->dev->mtl_device newBufferWithBytesNoCopy:(void *) ((uint8_t *) ptr + i) length:size_step_aligned options:MTLResourceStorageModeShared deallocator:nil];
1761
+
1762
+ if (res->buffers[res->n_buffers].metal == nil) {
1763
+ GGML_LOG_ERROR("%s: error: failed to allocate buffer, size = %8.2f MiB\n", __func__, size_step_aligned / 1024.0 / 1024.0);
1764
+ free(res);
1765
+ return NULL;
1766
+ }
1767
+ }
1768
+
1769
+ ggml_metal_log_allocated_size(res->dev->mtl_device, size_step_aligned);
1770
+
1771
+ if (i + size_step < size) {
1772
+ GGML_LOG_INFO("\n");
1773
+ }
1774
+
1775
+ ++res->n_buffers;
1776
+ }
1777
+ }
1778
+
1779
+ res->use_residency_sets = props_dev->use_residency_sets;
1780
+
1781
+ if (!ggml_metal_buffer_rset_init(res)) {
1782
+ GGML_LOG_ERROR("%s: error: failed to initialize residency set\n", __func__);
1783
+ free(res);
1784
+ return NULL;
1785
+ }
1786
+
1787
+ ggml_metal_device_rsets_add(dev, res->rset);
1788
+
1789
+ return res;
1790
+ }
1791
+
1792
+ void ggml_metal_buffer_free(ggml_metal_buffer_t buf) {
1793
+ ggml_metal_device_rsets_rm(buf->dev, buf->rset);
1794
+
1795
+ for (int i = 0; i < buf->n_buffers; i++) {
1796
+ [buf->buffers[i].metal release];
1797
+ }
1798
+
1799
+ ggml_metal_buffer_rset_free(buf);
1800
+
1801
+ if (buf->is_shared && buf->owned) {
1802
+ #if TARGET_OS_OSX
1803
+ vm_deallocate((vm_map_t)mach_task_self(), (vm_address_t)buf->all_data, buf->all_size);
1804
+ #else
1805
+ free(buf->all_data);
1806
+ #endif
1807
+ }
1808
+
1809
+ free(buf);
1810
+ }
1811
+
1812
+ void * ggml_metal_buffer_get_base(ggml_metal_buffer_t buf) {
1813
+ return buf->all_data;
1814
+ }
1815
+
1816
+ bool ggml_metal_buffer_is_shared(ggml_metal_buffer_t buf) {
1817
+ return buf->is_shared;
1818
+ }
1819
+
1820
+ void ggml_metal_buffer_memset_tensor(ggml_metal_buffer_t buf, struct ggml_tensor * tensor, uint8_t value, size_t offset, size_t size) {
1821
+ if (buf->is_shared) {
1822
+ memset((char *) tensor->data + offset, value, size);
1823
+ return;
1824
+ }
1825
+
1826
+ @autoreleasepool {
1827
+ // dst
1828
+ struct ggml_metal_buffer_id bid_dst = ggml_metal_buffer_get_id(buf, tensor);
1829
+ bid_dst.offs += offset;
1830
+
1831
+ id<MTLCommandBuffer> cmd_buf = [buf->dev->mtl_queue commandBufferWithUnretainedReferences];
1832
+
1833
+ {
1834
+ id<MTLBlitCommandEncoder> encoder = [cmd_buf blitCommandEncoder];
1835
+
1836
+ [encoder fillBuffer:bid_dst.metal
1837
+ range:NSMakeRange(bid_dst.offs, bid_dst.offs + size)
1838
+ value:value];
1839
+
1840
+ [encoder endEncoding];
1841
+ }
1842
+
1843
+ [cmd_buf commit];
1844
+ [cmd_buf waitUntilCompleted];
1845
+ }
1846
+ }
1847
+
1848
+ void ggml_metal_buffer_set_tensor(ggml_metal_buffer_t buf, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
1849
+ if (buf->is_shared) {
1850
+ memcpy((char *) tensor->data + offset, data, size);
1851
+ return;
1852
+ }
1853
+
1854
+ @autoreleasepool {
1855
+ // src
1856
+ void * data_ptr = (void *)(uintptr_t) data; // "const cast" the src data
1857
+ id<MTLBuffer> buf_src = [buf->dev->mtl_device newBufferWithBytesNoCopy:data_ptr
1858
+ length:size
1859
+ options:MTLResourceStorageModeShared
1860
+ deallocator:nil];
1861
+
1862
+ GGML_ASSERT(buf_src);
1863
+
1864
+ // dst
1865
+ struct ggml_metal_buffer_id bid_dst = ggml_metal_buffer_get_id(buf, tensor);
1866
+ bid_dst.offs += offset;
1867
+
1868
+ // note: for experimentation purposes, here we use a semaphore to wait for the copy to complete
1869
+ // this is alternative to waitUntilCompleted, which should be faster, but don't seem to make much difference
1870
+ dispatch_semaphore_t completion_semaphore = dispatch_semaphore_create(0);
1871
+
1872
+ id<MTLCommandBuffer> cmd_buf = [buf->dev->mtl_queue commandBufferWithUnretainedReferences];
1873
+
1874
+ {
1875
+ id<MTLBlitCommandEncoder> encoder = [cmd_buf blitCommandEncoder];
1876
+
1877
+ [encoder copyFromBuffer:buf_src
1878
+ sourceOffset:0
1879
+ toBuffer:bid_dst.metal
1880
+ destinationOffset:bid_dst.offs
1881
+ size:size];
1882
+
1883
+ [encoder endEncoding];
1884
+ }
1885
+
1886
+ [cmd_buf addCompletedHandler:^(id<MTLCommandBuffer> cb) {
1887
+ // TODO: can check for errors here
1888
+ GGML_UNUSED(cb);
1889
+
1890
+ dispatch_semaphore_signal(completion_semaphore);
1891
+ }];
1892
+
1893
+ [cmd_buf commit];
1894
+
1895
+ dispatch_semaphore_wait(completion_semaphore, DISPATCH_TIME_FOREVER);
1896
+ dispatch_release(completion_semaphore);
1897
+
1898
+ //[cmd_buf waitUntilCompleted];
1899
+ }
1900
+ }
1901
+
1902
+ void ggml_metal_buffer_get_tensor(ggml_metal_buffer_t buf, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size) {
1903
+ if (buf->is_shared) {
1904
+ memcpy(data, (const char *) tensor->data + offset, size);
1905
+ return;
1906
+ }
1907
+
1908
+ @autoreleasepool {
1909
+ // src
1910
+ struct ggml_metal_buffer_id bid_src = ggml_metal_buffer_get_id(buf, tensor);
1911
+ bid_src.offs += offset;
1912
+
1913
+ // dst
1914
+ id<MTLBuffer> buf_dst = [buf->dev->mtl_device newBufferWithBytesNoCopy:data
1915
+ length:size
1916
+ options:MTLResourceStorageModeShared
1917
+ deallocator:nil];
1918
+
1919
+ GGML_ASSERT(buf_dst);
1920
+
1921
+ id<MTLCommandBuffer> cmd_buf = [buf->dev->mtl_queue commandBufferWithUnretainedReferences];
1922
+
1923
+ {
1924
+ id<MTLBlitCommandEncoder> encoder = [cmd_buf blitCommandEncoder];
1925
+
1926
+ [encoder copyFromBuffer:bid_src.metal
1927
+ sourceOffset:bid_src.offs
1928
+ toBuffer:buf_dst
1929
+ destinationOffset:0
1930
+ size:size];
1931
+
1932
+ [encoder endEncoding];
1933
+ }
1934
+
1935
+ [cmd_buf commit];
1936
+ [cmd_buf waitUntilCompleted];
1937
+ }
1938
+ }
1939
+
1940
+ bool ggml_metal_buffer_cpy_tensor(ggml_metal_buffer_t buf_dst, const struct ggml_tensor * src, struct ggml_tensor * dst) {
1941
+ ggml_metal_buffer_t buf_src = (ggml_metal_buffer_t)src->buffer->context;
1942
+
1943
+ const size_t size = ggml_nbytes(src);
1944
+
1945
+ // if both buffers are shared, we can use memcpy directly
1946
+ if (buf_dst->is_shared && buf_src->is_shared) {
1947
+ memcpy(dst->data, src->data, size);
1948
+ return true;
1949
+ }
1950
+
1951
+ // for private buffers, we need to use Metal blit commands
1952
+ @autoreleasepool {
1953
+ struct ggml_metal_buffer_id bid_src = ggml_metal_buffer_get_id(buf_src, src);
1954
+ struct ggml_metal_buffer_id bid_dst = ggml_metal_buffer_get_id(buf_dst, dst);
1955
+
1956
+ if (bid_src.metal == nil || bid_dst.metal == nil) {
1957
+ return false;
1958
+ }
1959
+
1960
+ id<MTLCommandBuffer> cmd_buf = [buf_dst->dev->mtl_queue commandBufferWithUnretainedReferences];
1961
+
1962
+ {
1963
+ id<MTLBlitCommandEncoder> encoder = [cmd_buf blitCommandEncoder];
1964
+
1965
+ [encoder copyFromBuffer:bid_src.metal
1966
+ sourceOffset:bid_src.offs
1967
+ toBuffer:bid_dst.metal
1968
+ destinationOffset:bid_dst.offs
1969
+ size:size];
1970
+
1971
+ [encoder endEncoding];
1972
+ }
1973
+
1974
+ [cmd_buf commit];
1975
+ [cmd_buf waitUntilCompleted];
1976
+ }
1977
+
1978
+ return true;
1979
+ }
1980
+
1981
+ void ggml_metal_buffer_clear(ggml_metal_buffer_t buf, uint8_t value) {
1982
+ if (buf->is_shared) {
1983
+ memset(buf->all_data, value, buf->all_size);
1984
+ return;
1985
+ }
1986
+
1987
+ @autoreleasepool {
1988
+ id<MTLCommandBuffer> cmd_buf = [buf->dev->mtl_queue commandBufferWithUnretainedReferences];
1989
+
1990
+ {
1991
+ id<MTLBlitCommandEncoder> encoder = [cmd_buf blitCommandEncoder];
1992
+
1993
+ [encoder fillBuffer:buf->buffers[0].metal
1994
+ range:NSMakeRange(0, buf->buffers[0].size)
1995
+ value:value];
1996
+
1997
+ [encoder endEncoding];
1998
+ }
1999
+
2000
+ [cmd_buf commit];
2001
+ [cmd_buf waitUntilCompleted];
2002
+ }
2003
+ }
2004
+
2005
+ struct ggml_metal_buffer_id ggml_metal_buffer_get_id(ggml_metal_buffer_t buf, const struct ggml_tensor * t) {
2006
+ struct ggml_metal_buffer_id res = { nil, 0 };
2007
+
2008
+ const int64_t tsize = ggml_nbytes(t);
2009
+
2010
+ // find the view that contains the tensor fully
2011
+ for (int i = 0; i < buf->n_buffers; ++i) {
2012
+ const int64_t ioffs = (int64_t) t->data - (int64_t) buf->buffers[i].data;
2013
+
2014
+ //GGML_LOG_INFO("ioffs = %10ld, tsize = %10ld, sum = %10ld, buf->buffers[%d].size = %10ld\n", ioffs, tsize, ioffs + tsize, i, buf->buffers[i].size);
2015
+ if (ioffs >= 0 && ioffs + tsize <= (int64_t) buf->buffers[i].size) {
2016
+ res.metal = buf->buffers[i].metal;
2017
+ res.offs = (size_t) ioffs;
2018
+
2019
+ //GGML_LOG_INFO("%s: tensor '%16s', offs = %8ld\n", __func__, t->name, *offs);
2020
+
2021
+ return res;
2022
+ }
2023
+ }
2024
+
2025
+ GGML_LOG_ERROR("%s: error: tensor '%s' buffer is nil\n", __func__, t->name);
2026
+
2027
+ return res;
2028
+ }
ggml/src/ggml-metal/ggml-metal-impl.h ADDED
@@ -0,0 +1,1296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef GGML_METAL_IMPL
2
+ #define GGML_METAL_IMPL
3
+
4
+ // kernel parameters for mat-mat threadgroups
5
+ //
6
+ // TODO: become function constants
7
+
8
+ #define SZ_SIMDGROUP 16
9
+ #define N_MM_NK 2
10
+ #define N_MM_NK_TOTAL (SZ_SIMDGROUP * N_MM_NK)
11
+
12
+ #define N_MM_BLOCK_X 4
13
+ #define N_MM_BLOCK_Y 2
14
+ #define N_MM_SIMD_GROUP_X 2
15
+ #define N_MM_SIMD_GROUP_Y 2
16
+
17
+ // kernel parameters for mat-vec threadgroups
18
+ //
19
+ // N_R0: number of src0 rows to process per simdgroup
20
+ // N_SG: number of simdgroups per threadgroup
21
+ //
22
+ // TODO: for optimal performance, become function of the device and work size
23
+
24
+ #define N_R0_Q1_0 8
25
+ #define N_SG_Q1_0 2
26
+
27
+ #define N_R0_Q2_0 8
28
+ #define N_SG_Q2_0 2
29
+
30
+ #define N_R0_Q4_0 4
31
+ #define N_SG_Q4_0 2
32
+
33
+ #define N_R0_Q4_1 4
34
+ #define N_SG_Q4_1 2
35
+
36
+ #define N_R0_Q5_0 4
37
+ #define N_SG_Q5_0 2
38
+
39
+ #define N_R0_Q5_1 4
40
+ #define N_SG_Q5_1 2
41
+
42
+ #define N_R0_Q8_0 2
43
+ #define N_SG_Q8_0 4
44
+
45
+ #define N_R0_MXFP4 2
46
+ #define N_SG_MXFP4 2
47
+
48
+ #define N_R0_Q2_K 4
49
+ #define N_SG_Q2_K 2
50
+
51
+ #define N_R0_Q3_K 2
52
+ #define N_SG_Q3_K 2
53
+
54
+ #define N_R0_Q4_K 2
55
+ #define N_SG_Q4_K 2
56
+
57
+ #define N_R0_Q5_K 1
58
+ #define N_SG_Q5_K 2
59
+
60
+ #define N_R0_Q6_K 2
61
+ #define N_SG_Q6_K 2
62
+
63
+ #define N_R0_IQ1_S 4
64
+ #define N_SG_IQ1_S 2
65
+
66
+ #define N_R0_IQ1_M 4
67
+ #define N_SG_IQ1_M 2
68
+
69
+ #define N_R0_IQ2_XXS 4
70
+ #define N_SG_IQ2_XXS 2
71
+
72
+ #define N_R0_IQ2_XS 4
73
+ #define N_SG_IQ2_XS 2
74
+
75
+ #define N_R0_IQ2_S 4
76
+ #define N_SG_IQ2_S 2
77
+
78
+ #define N_R0_IQ3_XXS 4
79
+ #define N_SG_IQ3_XXS 2
80
+
81
+ #define N_R0_IQ3_S 4
82
+ #define N_SG_IQ3_S 2
83
+
84
+ #define N_R0_IQ4_NL 2
85
+ #define N_SG_IQ4_NL 2
86
+
87
+ #define N_R0_IQ4_XS 2
88
+ #define N_SG_IQ4_XS 2
89
+
90
+ // function constants offsets
91
+ #define FC_FLASH_ATTN_EXT_PAD 100
92
+ #define FC_FLASH_ATTN_EXT_BLK 200
93
+ #define FC_FLASH_ATTN_EXT 300
94
+ #define FC_FLASH_ATTN_EXT_VEC 400
95
+ #define FC_FLASH_ATTN_EXT_VEC_REDUCE 500
96
+ #define FC_MUL_MV 600
97
+ #define FC_MUL_MM 700
98
+ #define FC_ROPE 800
99
+ #define FC_SSM_CONV 900
100
+ #define FC_SOLVE_TRI 1000
101
+ #define FC_COUNT_EQUAL 1100
102
+ #define FC_UNARY 1200
103
+ #define FC_BIN 1300
104
+ #define FC_SUM_ROWS 1400
105
+ #define FC_UPSCALE 1500
106
+ #define FC_GATED_DELTA_NET 1600
107
+
108
+ // op-specific constants
109
+ #define OP_FLASH_ATTN_EXT_NQPSG 8
110
+ #define OP_FLASH_ATTN_EXT_NCPSG 64
111
+
112
+ #define OP_FLASH_ATTN_EXT_VEC_NQPSG 1
113
+ #define OP_FLASH_ATTN_EXT_VEC_NCPSG 32
114
+
115
+ #define OP_LIGHTNING_INDEXER_DK 128
116
+ #define OP_LIGHTNING_INDEXER_NH 64
117
+ #define OP_LIGHTNING_INDEXER_NHPTG 8
118
+ #define OP_LIGHTNING_INDEXER_NKPSG 8
119
+ #define OP_LIGHTNING_INDEXER_NSG 8
120
+ #define OP_LIGHTNING_INDEXER_NBPTG 8
121
+
122
+ #define OP_UNARY_NUM_SCALE 10
123
+ #define OP_UNARY_NUM_FILL 11
124
+ #define OP_UNARY_NUM_CLAMP 12
125
+ #define OP_UNARY_NUM_SQR 13
126
+ #define OP_UNARY_NUM_SQRT 14
127
+ #define OP_UNARY_NUM_SIN 15
128
+ #define OP_UNARY_NUM_COS 16
129
+ #define OP_UNARY_NUM_LOG 17
130
+ #define OP_UNARY_NUM_LEAKY_RELU 18
131
+
132
+ #define OP_UNARY_NUM_TANH 100
133
+ #define OP_UNARY_NUM_RELU 101
134
+ #define OP_UNARY_NUM_SIGMOID 102
135
+ #define OP_UNARY_NUM_GELU 103
136
+ #define OP_UNARY_NUM_GELU_ERF 104
137
+ #define OP_UNARY_NUM_GELU_QUICK 105
138
+ #define OP_UNARY_NUM_SILU 106
139
+ #define OP_UNARY_NUM_ELU 107
140
+ #define OP_UNARY_NUM_NEG 108
141
+ #define OP_UNARY_NUM_ABS 109
142
+ #define OP_UNARY_NUM_SGN 110
143
+ #define OP_UNARY_NUM_STEP 111
144
+ #define OP_UNARY_NUM_HARDSWISH 112
145
+ #define OP_UNARY_NUM_HARDSIGMOID 113
146
+ #define OP_UNARY_NUM_EXP 114
147
+ #define OP_UNARY_NUM_SOFTPLUS 115
148
+ #define OP_UNARY_NUM_EXPM1 116
149
+ #define OP_UNARY_NUM_FLOOR 117
150
+ #define OP_UNARY_NUM_CEIL 118
151
+ #define OP_UNARY_NUM_ROUND 119
152
+ #define OP_UNARY_NUM_TRUNC 120
153
+ #define OP_UNARY_NUM_XIELU 121
154
+
155
+ #define OP_SUM_ROWS_NUM_SUM_ROWS 10
156
+ #define OP_SUM_ROWS_NUM_MEAN 11
157
+
158
+ // kernel argument structs
159
+ //
160
+ // - element counters (e.g. ne00) typically use int32_t to reduce register usage
161
+ // however, be careful from int overflows when using those in the kernel implementation
162
+ //
163
+ // - strides (e.g. nb00) use uint64_t
164
+
165
+ typedef struct {
166
+ int32_t ne00;
167
+ int32_t ne01;
168
+ int32_t ne02;
169
+ int32_t ne03;
170
+ uint64_t nb00;
171
+ uint64_t nb01;
172
+ uint64_t nb02;
173
+ uint64_t nb03;
174
+ int32_t ne10;
175
+ int32_t ne11;
176
+ int32_t ne12;
177
+ int32_t ne13;
178
+ uint64_t nb10;
179
+ uint64_t nb11;
180
+ uint64_t nb12;
181
+ uint64_t nb13;
182
+ int32_t ne0;
183
+ int32_t ne1;
184
+ int32_t ne2;
185
+ int32_t ne3;
186
+ uint64_t nb0;
187
+ uint64_t nb1;
188
+ uint64_t nb2;
189
+ uint64_t nb3;
190
+ int32_t dim;
191
+ } ggml_metal_kargs_concat;
192
+
193
+ typedef struct {
194
+ int32_t ne00;
195
+ int32_t ne01;
196
+ int32_t ne02;
197
+ int32_t ne03;
198
+ uint64_t nb00;
199
+ uint64_t nb01;
200
+ uint64_t nb02;
201
+ uint64_t nb03;
202
+ int32_t ne0;
203
+ int32_t ne1;
204
+ int32_t ne2;
205
+ int32_t ne3;
206
+ uint64_t nb0;
207
+ uint64_t nb1;
208
+ uint64_t nb2;
209
+ uint64_t nb3;
210
+ float slope;
211
+ float scale;
212
+ float bias;
213
+ float val;
214
+ float min;
215
+ float max;
216
+ } ggml_metal_kargs_unary;
217
+
218
+ typedef struct {
219
+ int32_t ne00;
220
+ int32_t ne01;
221
+ int32_t ne02;
222
+ int32_t ne03;
223
+ uint64_t nb00;
224
+ uint64_t nb01;
225
+ uint64_t nb02;
226
+ uint64_t nb03;
227
+ int32_t ne10;
228
+ int32_t ne11;
229
+ int32_t ne12;
230
+ int32_t ne13;
231
+ uint64_t nb10;
232
+ uint64_t nb11;
233
+ uint64_t nb12;
234
+ uint64_t nb13;
235
+ int32_t ne0;
236
+ int32_t ne1;
237
+ int32_t ne2;
238
+ int32_t ne3;
239
+ uint64_t nb0;
240
+ uint64_t nb1;
241
+ uint64_t nb2;
242
+ uint64_t nb3;
243
+ uint64_t offs;
244
+ uint64_t o1[8];
245
+ } ggml_metal_kargs_bin;
246
+
247
+ typedef struct {
248
+ int64_t ne0;
249
+ int64_t ne1;
250
+ size_t nb01;
251
+ size_t nb02;
252
+ size_t nb11;
253
+ size_t nb21;
254
+ } ggml_metal_kargs_add_id;
255
+
256
+ typedef struct {
257
+ int32_t ne00;
258
+ int32_t ne01;
259
+ int32_t ne02;
260
+ int32_t ne03;
261
+ uint64_t nb00;
262
+ uint64_t nb01;
263
+ uint64_t nb02;
264
+ uint64_t nb03;
265
+ int32_t ne0;
266
+ int32_t ne1;
267
+ int32_t ne2;
268
+ int32_t ne3;
269
+ uint64_t nb0;
270
+ uint64_t nb1;
271
+ uint64_t nb2;
272
+ uint64_t nb3;
273
+ } ggml_metal_kargs_repeat;
274
+
275
+ typedef struct {
276
+ int64_t nk0;
277
+ int64_t ne00;
278
+ int64_t ne01;
279
+ int64_t ne02;
280
+ int64_t ne03;
281
+ uint64_t nb00;
282
+ uint64_t nb01;
283
+ uint64_t nb02;
284
+ uint64_t nb03;
285
+ int64_t ne0;
286
+ int64_t ne1;
287
+ int64_t ne2;
288
+ int64_t ne3;
289
+ uint64_t nb0;
290
+ uint64_t nb1;
291
+ uint64_t nb2;
292
+ uint64_t nb3;
293
+ } ggml_metal_kargs_cpy;
294
+
295
+ typedef struct {
296
+ int64_t ne10;
297
+ int64_t ne11;
298
+ int64_t ne12;
299
+ uint64_t nb10;
300
+ uint64_t nb11;
301
+ uint64_t nb12;
302
+ uint64_t nb13;
303
+ uint64_t nb1;
304
+ uint64_t nb2;
305
+ uint64_t nb3;
306
+ uint64_t offs;
307
+ bool inplace;
308
+ } ggml_metal_kargs_set;
309
+
310
+ typedef struct {
311
+ int32_t ne00;
312
+ int32_t ne01;
313
+ int32_t ne02;
314
+ int32_t ne03;
315
+ uint64_t nb00;
316
+ uint64_t nb01;
317
+ uint64_t nb02;
318
+ uint64_t nb03;
319
+ int32_t ne0;
320
+ int32_t ne1;
321
+ int32_t ne2;
322
+ int32_t ne3;
323
+ uint64_t nb0;
324
+ uint64_t nb1;
325
+ uint64_t nb2;
326
+ uint64_t nb3;
327
+ int32_t n_past;
328
+ int32_t n_dims;
329
+ int32_t n_ctx_orig;
330
+ float freq_base;
331
+ float freq_scale;
332
+ float ext_factor;
333
+ float attn_factor;
334
+ float beta_fast;
335
+ float beta_slow;
336
+ int32_t sect_0;
337
+ int32_t sect_1;
338
+ int32_t sect_2;
339
+ int32_t sect_3;
340
+ bool src2;
341
+ } ggml_metal_kargs_rope;
342
+
343
+ typedef struct {
344
+ int32_t ne11;
345
+ int32_t ne_12_2; // assume K and V are same shape
346
+ int32_t ne_12_3;
347
+ uint64_t nb11;
348
+ uint64_t nb12;
349
+ uint64_t nb13;
350
+ uint64_t nb21;
351
+ uint64_t nb22;
352
+ uint64_t nb23;
353
+ int32_t ne31;
354
+ int32_t ne32;
355
+ int32_t ne33;
356
+ uint64_t nb31;
357
+ uint64_t nb32;
358
+ uint64_t nb33;
359
+ } ggml_metal_kargs_flash_attn_ext_pad;
360
+
361
+ typedef struct {
362
+ int32_t ne01;
363
+ int32_t ne30;
364
+ int32_t ne31;
365
+ int32_t ne32;
366
+ int32_t ne33;
367
+ uint64_t nb31;
368
+ uint64_t nb32;
369
+ uint64_t nb33;
370
+ } ggml_metal_kargs_flash_attn_ext_blk;
371
+
372
+ typedef struct {
373
+ int32_t ne01;
374
+ int32_t ne02;
375
+ int32_t ne03;
376
+ uint64_t nb01;
377
+ uint64_t nb02;
378
+ uint64_t nb03;
379
+ int32_t ne11;
380
+ int32_t ne_12_2; // assume K and V are same shape
381
+ int32_t ne_12_3;
382
+ int32_t ns10;
383
+ uint64_t nb11;
384
+ uint64_t nb12;
385
+ uint64_t nb13;
386
+ int32_t ns20;
387
+ uint64_t nb21;
388
+ uint64_t nb22;
389
+ uint64_t nb23;
390
+ int32_t ne31;
391
+ int32_t ne32;
392
+ int32_t ne33;
393
+ uint64_t nb31;
394
+ uint64_t nb32;
395
+ uint64_t nb33;
396
+ int32_t ne1;
397
+ int32_t ne2;
398
+ int32_t ne3;
399
+ float scale;
400
+ float max_bias;
401
+ float m0;
402
+ float m1;
403
+ int32_t n_head_log2;
404
+ float logit_softcap;
405
+ } ggml_metal_kargs_flash_attn_ext;
406
+
407
+ typedef struct {
408
+ int32_t ne01;
409
+ int32_t ne02;
410
+ int32_t ne03;
411
+ uint64_t nb01;
412
+ uint64_t nb02;
413
+ uint64_t nb03;
414
+ int32_t ne11;
415
+ int32_t ne_12_2; // assume K and V are same shape
416
+ int32_t ne_12_3;
417
+ int32_t ns10;
418
+ uint64_t nb11;
419
+ uint64_t nb12;
420
+ uint64_t nb13;
421
+ int32_t ns20;
422
+ uint64_t nb21;
423
+ uint64_t nb22;
424
+ uint64_t nb23;
425
+ int32_t ne31;
426
+ int32_t ne32;
427
+ int32_t ne33;
428
+ uint64_t nb31;
429
+ uint64_t nb32;
430
+ uint64_t nb33;
431
+ int32_t ne1;
432
+ int32_t ne2;
433
+ int32_t ne3;
434
+ float scale;
435
+ float max_bias;
436
+ float m0;
437
+ float m1;
438
+ int32_t n_head_log2;
439
+ float logit_softcap;
440
+ } ggml_metal_kargs_flash_attn_ext_vec;
441
+
442
+ typedef struct {
443
+ int32_t nrows;
444
+ } ggml_metal_kargs_flash_attn_ext_vec_reduce;
445
+
446
+ typedef struct {
447
+ int32_t ne00;
448
+ int32_t ne02;
449
+ uint64_t nb01;
450
+ uint64_t nb02;
451
+ uint64_t nb03;
452
+ int32_t ne12;
453
+ uint64_t nb10;
454
+ uint64_t nb11;
455
+ uint64_t nb12;
456
+ uint64_t nb13;
457
+ int32_t ne0;
458
+ int32_t ne1;
459
+ int16_t r2;
460
+ int16_t r3;
461
+ } ggml_metal_kargs_mul_mm;
462
+
463
+ typedef struct {
464
+ int32_t ne00;
465
+ int32_t ne01;
466
+ int32_t ne02;
467
+ uint64_t nb00;
468
+ uint64_t nb01;
469
+ uint64_t nb02;
470
+ uint64_t nb03;
471
+ int32_t ne10;
472
+ int32_t ne11;
473
+ int32_t ne12;
474
+ uint64_t nb10;
475
+ uint64_t nb11;
476
+ uint64_t nb12;
477
+ uint64_t nb13;
478
+ int32_t ne0;
479
+ int32_t ne1;
480
+ int32_t nr0;
481
+ int16_t r2;
482
+ int16_t r3;
483
+ } ggml_metal_kargs_mul_mv;
484
+
485
+ typedef struct {
486
+ int32_t ne00;
487
+ int32_t ne01;
488
+ int32_t ne02;
489
+ uint64_t nb00;
490
+ uint64_t nb01;
491
+ uint64_t nb02;
492
+ uint64_t nb03;
493
+ int32_t ne10;
494
+ int32_t ne11;
495
+ int32_t ne12;
496
+ uint64_t nb10;
497
+ uint64_t nb11;
498
+ uint64_t nb12;
499
+ uint64_t nb13;
500
+ int32_t ne0;
501
+ int32_t ne1;
502
+ int16_t r2;
503
+ int16_t r3;
504
+ } ggml_metal_kargs_mul_mv_ext;
505
+
506
+ typedef struct {
507
+ int32_t ne02;
508
+ int32_t ne10;
509
+ int32_t ne11; // n_expert_used (bcast)
510
+ uint64_t nb11;
511
+ uint64_t nb12;
512
+ int32_t ne21; // n_tokens
513
+ int32_t ne20; // n_expert_used
514
+ uint64_t nb21;
515
+ } ggml_metal_kargs_mul_mm_id_map0;
516
+
517
+ typedef struct {
518
+ int32_t ne00;
519
+ int32_t ne02;
520
+ uint64_t nb01;
521
+ uint64_t nb02;
522
+ uint64_t nb03;
523
+ int32_t ne11;
524
+ uint64_t nb10;
525
+ uint64_t nb11;
526
+ uint64_t nb12;
527
+ uint64_t nb13;
528
+ int32_t ne20;
529
+ int32_t ne21;
530
+ int32_t ne0;
531
+ int32_t ne1;
532
+ int16_t r2;
533
+ int16_t r3;
534
+ } ggml_metal_kargs_mul_mm_id;
535
+
536
+ typedef struct {
537
+ int32_t nei0;
538
+ int32_t nei1;
539
+ uint64_t nbi1;
540
+ int32_t ne00;
541
+ int32_t ne01;
542
+ int32_t ne02;
543
+ uint64_t nb00;
544
+ uint64_t nb01;
545
+ uint64_t nb02;
546
+ int32_t ne10;
547
+ int32_t ne11;
548
+ int32_t ne12;
549
+ int32_t ne13;
550
+ uint64_t nb10;
551
+ uint64_t nb11;
552
+ uint64_t nb12;
553
+ int32_t ne0;
554
+ int32_t ne1;
555
+ uint64_t nb1;
556
+ int32_t nr0;
557
+ } ggml_metal_kargs_mul_mv_id;
558
+
559
+ // NORM
560
+ // RMS_NORM
561
+ typedef struct {
562
+ int32_t ne00;
563
+ int32_t ne00_t;
564
+ uint64_t nb1;
565
+ uint64_t nb2;
566
+ uint64_t nb3;
567
+ float eps;
568
+ int32_t nef1[3];
569
+ int32_t nef2[3];
570
+ int32_t nef3[3];
571
+ uint64_t nbf1[3];
572
+ uint64_t nbf2[3];
573
+ uint64_t nbf3[3];
574
+ } ggml_metal_kargs_norm;
575
+
576
+ typedef struct {
577
+ int32_t ne00;
578
+ int32_t ne01;
579
+ int32_t ne02;
580
+ int32_t ne03;
581
+ uint64_t nb00;
582
+ uint64_t nb01;
583
+ uint64_t nb02;
584
+ uint64_t nb03;
585
+ int32_t ne0;
586
+ int32_t ne1;
587
+ int32_t ne2;
588
+ int32_t ne3;
589
+ uint64_t nb0;
590
+ uint64_t nb1;
591
+ uint64_t nb2;
592
+ uint64_t nb3;
593
+ float eps;
594
+ } ggml_metal_kargs_l2_norm;
595
+
596
+ typedef struct {
597
+ int64_t ne00;
598
+ int64_t ne01;
599
+ int64_t ne02;
600
+ uint64_t nb00;
601
+ uint64_t nb01;
602
+ uint64_t nb02;
603
+ int32_t ngrp;
604
+ float eps;
605
+ } ggml_metal_kargs_group_norm;
606
+
607
+ typedef struct {
608
+ int32_t IC;
609
+ int32_t IL;
610
+ int32_t K;
611
+ int32_t s0;
612
+ uint64_t nb0;
613
+ uint64_t nb1;
614
+ } ggml_metal_kargs_conv_transpose_1d;
615
+
616
+ typedef struct {
617
+ int32_t T_in;
618
+ int32_t T_out;
619
+ int32_t OC;
620
+ int32_t K;
621
+ int32_t K_OC;
622
+ int32_t s0;
623
+ int32_t p0;
624
+ } ggml_metal_kargs_col2im_1d;
625
+
626
+ typedef struct {
627
+ int32_t T;
628
+ int32_t C;
629
+ } ggml_metal_kargs_snake;
630
+
631
+ typedef struct {
632
+ int32_t IC;
633
+ int32_t IH;
634
+ int32_t IW;
635
+ int32_t KH;
636
+ int32_t KW;
637
+ int32_t OC;
638
+ int32_t s0;
639
+ uint64_t nb0;
640
+ uint64_t nb1;
641
+ uint64_t nb2;
642
+ } ggml_metal_kargs_conv_transpose_2d;
643
+
644
+ typedef struct {
645
+ uint64_t nb00;
646
+ uint64_t nb01;
647
+ uint64_t nb02;
648
+ uint64_t nb03;
649
+ uint64_t nb10;
650
+ uint64_t nb11;
651
+ uint64_t nb12;
652
+ uint64_t nb13;
653
+ uint64_t nb0;
654
+ uint64_t nb1;
655
+ uint64_t nb2;
656
+ uint64_t nb3;
657
+ int32_t IW;
658
+ int32_t IH;
659
+ int32_t KW;
660
+ int32_t KH;
661
+ int32_t IC;
662
+ int32_t OC;
663
+ int32_t OW;
664
+ int32_t OH;
665
+ int32_t N;
666
+ int32_t s0;
667
+ int32_t s1;
668
+ int32_t p0;
669
+ int32_t p1;
670
+ int32_t d0;
671
+ int32_t d1;
672
+ } ggml_metal_kargs_conv_2d;
673
+
674
+ typedef struct {
675
+ uint64_t nb00; // kernel strides
676
+ uint64_t nb01;
677
+ uint64_t nb02;
678
+ uint64_t nb10; // input strides
679
+ uint64_t nb11;
680
+ uint64_t nb12;
681
+ uint64_t nb13;
682
+ uint64_t nb0; // output strides
683
+ uint64_t nb1;
684
+ uint64_t nb2;
685
+ uint64_t nb3;
686
+ int32_t IW; // input width
687
+ int32_t IH; // input height
688
+ int32_t KW; // kernel width
689
+ int32_t KH; // kernel height
690
+ int32_t C; // channels (IC == OC for depthwise)
691
+ int32_t OW; // output width
692
+ int32_t OH; // output height
693
+ int32_t N; // batch size
694
+ int32_t s0; // stride x
695
+ int32_t s1; // stride y
696
+ int32_t p0; // padding x
697
+ int32_t p1; // padding y
698
+ int32_t d0; // dilation x
699
+ int32_t d1; // dilation y
700
+ } ggml_metal_kargs_conv_2d_dw;
701
+
702
+ typedef struct {
703
+ uint64_t ofs0;
704
+ uint64_t ofs1;
705
+ int32_t IW;
706
+ int32_t IH;
707
+ int32_t CHW;
708
+ int32_t s0;
709
+ int32_t s1;
710
+ int32_t p0;
711
+ int32_t p1;
712
+ int32_t d0;
713
+ int32_t d1;
714
+ int32_t N;
715
+ int32_t KH;
716
+ int32_t KW;
717
+ int32_t KHW; // KH * KW, pre-computed on CPU to save GPU resources
718
+ } ggml_metal_kargs_im2col;
719
+
720
+ typedef struct {
721
+ int32_t IW;
722
+ int32_t IH;
723
+ int32_t ID;
724
+ int32_t OW;
725
+ int32_t OH;
726
+ int32_t OD;
727
+ int32_t KW;
728
+ int32_t KH;
729
+ int32_t KD;
730
+ int32_t s0;
731
+ int32_t s1;
732
+ int32_t s2;
733
+ int32_t p0;
734
+ int32_t p1;
735
+ int32_t p2;
736
+ int32_t d0;
737
+ int32_t d1;
738
+ int32_t d2;
739
+ int32_t IC;
740
+ int32_t N;
741
+ int32_t OC;
742
+ uint64_t nb00;
743
+ uint64_t nb01;
744
+ uint64_t nb02;
745
+ uint64_t nb03;
746
+ uint64_t nb10;
747
+ uint64_t nb11;
748
+ uint64_t nb12;
749
+ uint64_t nb13;
750
+ uint64_t nb0;
751
+ uint64_t nb1;
752
+ uint64_t nb2;
753
+ uint64_t nb3;
754
+ } ggml_metal_kargs_conv_3d;
755
+
756
+ typedef struct{
757
+ int32_t ne00;
758
+ uint64_t nb01;
759
+ int32_t ne10;
760
+ uint64_t nb11;
761
+ int32_t ne0;
762
+ uint64_t nb1;
763
+ int32_t i00;
764
+ int32_t i10;
765
+ float alpha;
766
+ float limit;
767
+ } ggml_metal_kargs_glu;
768
+
769
+ typedef struct {
770
+ uint64_t np;
771
+ } ggml_metal_kargs_sum;
772
+
773
+ typedef struct {
774
+ int64_t ne00;
775
+ int64_t ne01;
776
+ int64_t ne02;
777
+ int64_t ne03;
778
+ uint64_t nb00;
779
+ uint64_t nb01;
780
+ uint64_t nb02;
781
+ uint64_t nb03;
782
+ int64_t ne0;
783
+ int64_t ne1;
784
+ int64_t ne2;
785
+ int64_t ne3;
786
+ uint64_t nb0;
787
+ uint64_t nb1;
788
+ uint64_t nb2;
789
+ uint64_t nb3;
790
+ } ggml_metal_kargs_sum_rows;
791
+
792
+ typedef struct {
793
+ int64_t ne00;
794
+ int64_t ne01;
795
+ int64_t ne02;
796
+ int64_t ne03;
797
+ uint64_t nb00;
798
+ uint64_t nb01;
799
+ uint64_t nb02;
800
+ uint64_t nb03;
801
+ int64_t net0;
802
+ int64_t net1;
803
+ int64_t net2;
804
+ int64_t net3;
805
+ uint64_t nbt0;
806
+ uint64_t nbt1;
807
+ uint64_t nbt2;
808
+ uint64_t nbt3;
809
+ bool outb;
810
+ } ggml_metal_kargs_cumsum_blk;
811
+
812
+ typedef struct {
813
+ int64_t ne00;
814
+ int64_t ne01;
815
+ int64_t ne02;
816
+ int64_t ne03;
817
+ uint64_t nb00;
818
+ uint64_t nb01;
819
+ uint64_t nb02;
820
+ uint64_t nb03;
821
+ int64_t net0;
822
+ int64_t net1;
823
+ int64_t net2;
824
+ int64_t net3;
825
+ uint64_t nbt0;
826
+ uint64_t nbt1;
827
+ uint64_t nbt2;
828
+ uint64_t nbt3;
829
+ } ggml_metal_kargs_cumsum_add;
830
+
831
+ typedef struct {
832
+ int32_t ne00;
833
+ int32_t ne01;
834
+ int32_t ne02;
835
+ uint64_t nb01;
836
+ uint64_t nb02;
837
+ uint64_t nb03;
838
+ int32_t ne11;
839
+ int32_t ne12;
840
+ int32_t ne13;
841
+ uint64_t nb11;
842
+ uint64_t nb12;
843
+ uint64_t nb13;
844
+ uint64_t nb1;
845
+ uint64_t nb2;
846
+ uint64_t nb3;
847
+ float scale;
848
+ float max_bias;
849
+ float m0;
850
+ float m1;
851
+ int32_t n_head_log2;
852
+ } ggml_metal_kargs_soft_max;
853
+
854
+ typedef struct {
855
+ int64_t ne00;
856
+ int64_t ne01;
857
+ int64_t ne02;
858
+ uint64_t nb00;
859
+ uint64_t nb01;
860
+ uint64_t nb02;
861
+ int64_t ne10;
862
+ int64_t ne11;
863
+ uint64_t nb10;
864
+ uint64_t nb11;
865
+ int64_t ne0;
866
+ int64_t ne1;
867
+ int64_t ne2;
868
+ uint64_t nb0;
869
+ uint64_t nb1;
870
+ uint64_t nb2;
871
+ } ggml_metal_kargs_ssm_conv;
872
+
873
+ typedef struct {
874
+ int64_t d_state;
875
+ int64_t d_inner;
876
+ int64_t n_head;
877
+ int64_t n_group;
878
+ int64_t n_seq_tokens;
879
+ int64_t n_seqs;
880
+ uint64_t s_off;
881
+ uint64_t nb00;
882
+ uint64_t nb01;
883
+ uint64_t nb02;
884
+ uint64_t nb03;
885
+ uint64_t nb10;
886
+ uint64_t nb11;
887
+ uint64_t nb12;
888
+ uint64_t ns12;
889
+ uint64_t nb13;
890
+ uint64_t nb20;
891
+ uint64_t nb21;
892
+ uint64_t ns21;
893
+ uint64_t nb22;
894
+ int64_t ne30;
895
+ uint64_t nb31;
896
+ uint64_t nb41;
897
+ uint64_t nb42;
898
+ uint64_t ns42;
899
+ uint64_t nb43;
900
+ uint64_t nb51;
901
+ uint64_t nb52;
902
+ uint64_t ns52;
903
+ uint64_t nb53;
904
+ uint64_t nb0;
905
+ } ggml_metal_kargs_ssm_scan;
906
+
907
+ typedef struct {
908
+ int32_t ne00;
909
+ int32_t ne01;
910
+ int32_t ne02;
911
+ int32_t ne03;
912
+ uint64_t nb00;
913
+ uint64_t nb01;
914
+ uint64_t nb02;
915
+ uint64_t nb03;
916
+ int32_t ne10;
917
+ int32_t ne11;
918
+ int32_t ne12;
919
+ int32_t ne13;
920
+ uint64_t nb10;
921
+ uint64_t nb11;
922
+ uint64_t nb12;
923
+ uint64_t nb13;
924
+ int32_t ne20;
925
+ int32_t ne21;
926
+ int32_t ne22;
927
+ int32_t ne23;
928
+ uint64_t nb20;
929
+ uint64_t nb21;
930
+ uint64_t nb22;
931
+ uint64_t nb23;
932
+ int32_t ns02;
933
+ int32_t ns12;
934
+ int32_t ns22;
935
+ int32_t ne0;
936
+ int32_t ne1;
937
+ int32_t ne2;
938
+ int32_t ne3;
939
+ uint64_t nb0;
940
+ uint64_t nb1;
941
+ uint64_t nb2;
942
+ uint64_t nb3;
943
+ } ggml_metal_kargs_gated_delta_net;
944
+
945
+ typedef struct {
946
+ int32_t ne00;
947
+ int32_t ne01;
948
+ int32_t ne02;
949
+ int32_t ne03;
950
+ uint64_t nb00;
951
+ uint64_t nb01;
952
+ uint64_t nb02;
953
+ uint64_t nb03;
954
+ int32_t ne10;
955
+ int32_t ne11;
956
+ int32_t ne12;
957
+ int32_t ne13;
958
+ uint64_t nb10;
959
+ uint64_t nb11;
960
+ uint64_t nb12;
961
+ uint64_t nb13;
962
+ int32_t ne0;
963
+ int32_t ne1;
964
+ int32_t ne2;
965
+ int32_t ne3;
966
+ uint64_t nb0;
967
+ uint64_t nb1;
968
+ uint64_t nb2;
969
+ uint64_t nb3;
970
+ } ggml_metal_kargs_solve_tri;
971
+
972
+ typedef struct {
973
+ int32_t ne00t;
974
+ int32_t ne00;
975
+ uint64_t nb01;
976
+ uint64_t nb02;
977
+ uint64_t nb03;
978
+ int32_t ne10;
979
+ uint64_t nb10;
980
+ uint64_t nb11;
981
+ uint64_t nb12;
982
+ uint64_t nb1;
983
+ uint64_t nb2;
984
+ uint64_t nb3;
985
+ } ggml_metal_kargs_get_rows;
986
+
987
+ typedef struct {
988
+ int32_t nk0;
989
+ int32_t ne01;
990
+ uint64_t nb01;
991
+ uint64_t nb02;
992
+ uint64_t nb03;
993
+ int32_t ne11;
994
+ int32_t ne12;
995
+ uint64_t nb10;
996
+ uint64_t nb11;
997
+ uint64_t nb12;
998
+ uint64_t nb1;
999
+ uint64_t nb2;
1000
+ uint64_t nb3;
1001
+ } ggml_metal_kargs_set_rows;
1002
+
1003
+ typedef struct {
1004
+ int32_t ne00;
1005
+ int32_t ne01;
1006
+ int32_t ne02;
1007
+ int32_t ne03;
1008
+ uint64_t nb00;
1009
+ uint64_t nb01;
1010
+ uint64_t nb02;
1011
+ uint64_t nb03;
1012
+ int32_t ne0;
1013
+ int32_t ne1;
1014
+ int32_t ne2;
1015
+ int32_t ne3;
1016
+ uint64_t nb0;
1017
+ uint64_t nb1;
1018
+ uint64_t nb2;
1019
+ uint64_t nb3;
1020
+ } ggml_metal_kargs_diag;
1021
+
1022
+ typedef struct {
1023
+ int64_t ne00;
1024
+ int64_t ne01;
1025
+ int64_t ne02;
1026
+ int64_t ne03;
1027
+ uint64_t nb00;
1028
+ uint64_t nb01;
1029
+ uint64_t nb02;
1030
+ uint64_t nb03;
1031
+ int64_t ne0;
1032
+ int64_t ne1;
1033
+ int64_t ne2;
1034
+ int64_t ne3;
1035
+ uint64_t nb0;
1036
+ uint64_t nb1;
1037
+ uint64_t nb2;
1038
+ uint64_t nb3;
1039
+ float sf0;
1040
+ float sf1;
1041
+ float sf2;
1042
+ float sf3;
1043
+ float poffs;
1044
+ } ggml_metal_kargs_upscale;
1045
+
1046
+ typedef struct {
1047
+ int64_t ne00;
1048
+ int64_t ne01;
1049
+ int64_t ne02;
1050
+ int64_t ne03;
1051
+ uint64_t nb00;
1052
+ uint64_t nb01;
1053
+ uint64_t nb02;
1054
+ uint64_t nb03;
1055
+ int64_t ne0;
1056
+ int64_t ne1;
1057
+ int64_t ne2;
1058
+ int64_t ne3;
1059
+ uint64_t nb0;
1060
+ uint64_t nb1;
1061
+ uint64_t nb2;
1062
+ uint64_t nb3;
1063
+ } ggml_metal_kargs_pad;
1064
+
1065
+ typedef struct {
1066
+ int64_t ne00;
1067
+ int64_t ne01;
1068
+ int64_t ne02;
1069
+ int64_t ne03;
1070
+ uint64_t nb00;
1071
+ uint64_t nb01;
1072
+ uint64_t nb02;
1073
+ uint64_t nb03;
1074
+ int64_t ne0;
1075
+ int64_t ne1;
1076
+ int64_t ne2;
1077
+ int64_t ne3;
1078
+ uint64_t nb0;
1079
+ uint64_t nb1;
1080
+ uint64_t nb2;
1081
+ uint64_t nb3;
1082
+ int32_t p0;
1083
+ int32_t p1;
1084
+ } ggml_metal_kargs_pad_reflect_1d;
1085
+
1086
+ typedef struct {
1087
+ int64_t ne00;
1088
+ int64_t ne01;
1089
+ int64_t ne02;
1090
+ int64_t ne03;
1091
+ uint64_t nb00;
1092
+ uint64_t nb01;
1093
+ uint64_t nb02;
1094
+ uint64_t nb03;
1095
+ int64_t ne0;
1096
+ int64_t ne1;
1097
+ int64_t ne2;
1098
+ int64_t ne3;
1099
+ uint64_t nb0;
1100
+ uint64_t nb1;
1101
+ uint64_t nb2;
1102
+ uint64_t nb3;
1103
+ int32_t s0;
1104
+ int32_t s1;
1105
+ int32_t s2;
1106
+ int32_t s3;
1107
+ } ggml_metal_kargs_roll;
1108
+
1109
+ typedef struct {
1110
+ uint64_t nb1;
1111
+ int dim;
1112
+ int max_period;
1113
+ } ggml_metal_kargs_timestep_embedding;
1114
+
1115
+ typedef struct {
1116
+ int32_t ne00;
1117
+ int32_t ne01;
1118
+ int32_t ne02;
1119
+ int32_t ne03;
1120
+ uint64_t nb00;
1121
+ uint64_t nb01;
1122
+ uint64_t nb02;
1123
+ uint64_t nb03;
1124
+ int32_t ne0;
1125
+ int32_t ne1;
1126
+ int32_t ne2;
1127
+ int32_t ne3;
1128
+ uint64_t nb0;
1129
+ uint64_t nb1;
1130
+ uint64_t nb2;
1131
+ uint64_t nb3;
1132
+ } ggml_metal_kargs_tri;
1133
+
1134
+ typedef struct {
1135
+ int32_t ne00;
1136
+ int32_t ne01;
1137
+ int32_t ne02;
1138
+ int32_t ne03;
1139
+ uint64_t nb00;
1140
+ uint64_t nb01;
1141
+ uint64_t nb02;
1142
+ uint64_t nb03;
1143
+ int32_t ne0;
1144
+ int32_t ne1;
1145
+ int32_t ne2;
1146
+ int32_t ne3;
1147
+ int32_t top_k;
1148
+ } ggml_metal_kargs_argsort;
1149
+
1150
+ typedef struct {
1151
+ int64_t ne00;
1152
+ int64_t ne01;
1153
+ int64_t ne02;
1154
+ int64_t ne03;
1155
+ uint64_t nb00;
1156
+ uint64_t nb01;
1157
+ uint64_t nb02;
1158
+ uint64_t nb03;
1159
+ int32_t ne0;
1160
+ int32_t ne1;
1161
+ int32_t ne2;
1162
+ int32_t ne3;
1163
+ int32_t top_k;
1164
+ int32_t len;
1165
+ } ggml_metal_kargs_argsort_merge;
1166
+
1167
+ typedef struct {
1168
+ int32_t nrows;
1169
+ } ggml_metal_kargs_fwht;
1170
+
1171
+ typedef struct {
1172
+ int64_t ne0;
1173
+ float start;
1174
+ float step;
1175
+ } ggml_metal_kargs_arange;
1176
+
1177
+ typedef struct {
1178
+ int64_t val;
1179
+ } ggml_metal_kargs_memset;
1180
+
1181
+ typedef struct {
1182
+ int32_t n_kv;
1183
+ int32_t n_batch;
1184
+ int32_t mask_ne3;
1185
+ uint64_t nb1;
1186
+ uint64_t nb3;
1187
+ uint64_t nbq1;
1188
+ uint64_t nbq2;
1189
+ uint64_t nbq3;
1190
+ uint64_t nbk2;
1191
+ uint64_t nbk3;
1192
+ uint64_t nbw1;
1193
+ uint64_t nbw3;
1194
+ uint64_t nbm1;
1195
+ uint64_t nbm3;
1196
+ } ggml_metal_kargs_lightning_indexer;
1197
+
1198
+ typedef struct {
1199
+ int32_t n_tokens;
1200
+ int32_t n_iter;
1201
+ uint64_t nb_m0;
1202
+ uint64_t nb_m1;
1203
+ uint64_t nb_s0;
1204
+ uint64_t nb_b0;
1205
+ uint64_t nb_d0;
1206
+ uint64_t nb_d1;
1207
+ uint64_t nb_d2;
1208
+ float eps;
1209
+ } ggml_metal_kargs_dsv4_hc_comb;
1210
+
1211
+ typedef struct {
1212
+ int32_t n_embd;
1213
+ int32_t n_tokens;
1214
+ uint64_t nb_x0;
1215
+ uint64_t nb_x1;
1216
+ uint64_t nb_x2;
1217
+ uint64_t nb_w0;
1218
+ uint64_t nb_w1;
1219
+ uint64_t nb_d0;
1220
+ uint64_t nb_d1;
1221
+ } ggml_metal_kargs_dsv4_hc_pre;
1222
+
1223
+ typedef struct {
1224
+ int32_t n_embd;
1225
+ int32_t n_tokens;
1226
+ uint64_t nb_x0;
1227
+ uint64_t nb_x1;
1228
+ uint64_t nb_r0;
1229
+ uint64_t nb_r1;
1230
+ uint64_t nb_r2;
1231
+ uint64_t nb_p0;
1232
+ uint64_t nb_p1;
1233
+ uint64_t nb_c0;
1234
+ uint64_t nb_c1;
1235
+ uint64_t nb_c2;
1236
+ uint64_t nb_d0;
1237
+ uint64_t nb_d1;
1238
+ uint64_t nb_d2;
1239
+ } ggml_metal_kargs_dsv4_hc_post;
1240
+
1241
+ typedef struct {
1242
+ int32_t ne00;
1243
+ int32_t ne01;
1244
+ int32_t ne02;
1245
+ int32_t ne03;
1246
+ uint64_t nb00;
1247
+ uint64_t nb01;
1248
+ uint64_t nb02;
1249
+ uint64_t nb03;
1250
+ uint64_t nb10;
1251
+ uint64_t nb11;
1252
+ uint64_t nb12;
1253
+ uint64_t nb13;
1254
+ } ggml_metal_kargs_count_equal;
1255
+
1256
+ typedef struct {
1257
+ int32_t k0;
1258
+ int32_t k1;
1259
+ int32_t s0;
1260
+ int32_t s1;
1261
+ int32_t p0;
1262
+ int32_t p1;
1263
+ int64_t IH;
1264
+ int64_t IW;
1265
+ int64_t OH;
1266
+ int64_t OW;
1267
+ int64_t np;
1268
+ } ggml_metal_kargs_pool_2d;
1269
+
1270
+ typedef struct {
1271
+ int32_t k0;
1272
+ int32_t s0;
1273
+ int32_t p0;
1274
+ int64_t IW;
1275
+ int64_t OW;
1276
+ int64_t np;
1277
+ } ggml_metal_kargs_pool_1d;
1278
+
1279
+ typedef struct {
1280
+ int64_t ne00;
1281
+ uint64_t nb01;
1282
+ } ggml_metal_kargs_argmax;
1283
+
1284
+ typedef struct {
1285
+ int64_t np;
1286
+ } ggml_metal_kargs_opt_step_adamw;
1287
+
1288
+ typedef struct {
1289
+ int64_t np;
1290
+ } ggml_metal_kargs_opt_step_sgd;
1291
+
1292
+ typedef struct {
1293
+ int64_t ne;
1294
+ } ggml_metal_kargs_silu_back;
1295
+
1296
+ #endif // GGML_METAL_IMPL
ggml/src/ggml-metal/ggml-metal-ops.cpp ADDED
The diff for this file is too large to render. See raw diff
 
ggml/src/ggml-metal/ggml-metal-ops.h ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include "ggml-metal-device.h"
4
+
5
+ #ifdef __cplusplus
6
+ extern "C" {
7
+ #endif
8
+
9
+ typedef struct ggml_metal_op * ggml_metal_op_t;
10
+
11
+ ggml_metal_op_t ggml_metal_op_init(
12
+ ggml_metal_device_t dev,
13
+ ggml_metal_cmd_buf_t cmd_buf,
14
+ struct ggml_cgraph * gf,
15
+ int idx_start,
16
+ int idx_end,
17
+ bool use_fusion,
18
+ bool use_concurrency,
19
+ bool use_capture,
20
+ int debug_graph,
21
+ int debug_fusion);
22
+
23
+ void ggml_metal_op_free(ggml_metal_op_t ctx);
24
+
25
+ int ggml_metal_op_n_nodes(ggml_metal_op_t ctx);
26
+
27
+ int ggml_metal_op_encode(ggml_metal_op_t ctx, int idx);
28
+
29
+ //
30
+ // available ops:
31
+ //
32
+
33
+ // tokens per expert
34
+ size_t ggml_metal_op_mul_mat_id_extra_tpe(const struct ggml_tensor * op);
35
+
36
+ // id map [n_tokens, n_expert]
37
+ size_t ggml_metal_op_mul_mat_id_extra_ids(const struct ggml_tensor * op);
38
+
39
+ // return true if we should use the FA vector kernel for this op
40
+ bool ggml_metal_op_flash_attn_ext_use_vec(const struct ggml_tensor * op);
41
+
42
+ size_t ggml_metal_op_flash_attn_ext_extra_pad(const struct ggml_tensor * op);
43
+ size_t ggml_metal_op_flash_attn_ext_extra_blk(const struct ggml_tensor * op);
44
+ size_t ggml_metal_op_flash_attn_ext_extra_tmp(const struct ggml_tensor * op);
45
+
46
+ int ggml_metal_op_concat (ggml_metal_op_t ctx, int idx);
47
+ int ggml_metal_op_repeat (ggml_metal_op_t ctx, int idx);
48
+ int ggml_metal_op_acc (ggml_metal_op_t ctx, int idx);
49
+ int ggml_metal_op_unary (ggml_metal_op_t ctx, int idx);
50
+ int ggml_metal_op_glu (ggml_metal_op_t ctx, int idx);
51
+ int ggml_metal_op_sum (ggml_metal_op_t ctx, int idx);
52
+ int ggml_metal_op_sum_rows (ggml_metal_op_t ctx, int idx);
53
+ int ggml_metal_op_cumsum (ggml_metal_op_t ctx, int idx);
54
+ int ggml_metal_op_get_rows (ggml_metal_op_t ctx, int idx);
55
+ int ggml_metal_op_set_rows (ggml_metal_op_t ctx, int idx);
56
+ int ggml_metal_op_diag (ggml_metal_op_t ctx, int idx);
57
+ int ggml_metal_op_lightning_indexer (ggml_metal_op_t ctx, int idx);
58
+ int ggml_metal_op_dsv4_hc (ggml_metal_op_t ctx, int idx);
59
+ int ggml_metal_op_soft_max (ggml_metal_op_t ctx, int idx);
60
+ int ggml_metal_op_ssm_conv (ggml_metal_op_t ctx, int idx);
61
+ int ggml_metal_op_ssm_scan (ggml_metal_op_t ctx, int idx);
62
+ int ggml_metal_op_rwkv (ggml_metal_op_t ctx, int idx);
63
+ int ggml_metal_op_gated_delta_net (ggml_metal_op_t ctx, int idx);
64
+ int ggml_metal_op_solve_tri (ggml_metal_op_t ctx, int idx);
65
+ int ggml_metal_op_set (ggml_metal_op_t ctx, int idx);
66
+ int ggml_metal_op_cpy (ggml_metal_op_t ctx, int idx);
67
+ int ggml_metal_op_pool_1d (ggml_metal_op_t ctx, int idx);
68
+ int ggml_metal_op_pool_2d (ggml_metal_op_t ctx, int idx);
69
+ int ggml_metal_op_fwht (ggml_metal_op_t ctx, int idx);
70
+ int ggml_metal_op_mul_mat (ggml_metal_op_t ctx, int idx);
71
+ int ggml_metal_op_mul_mat_id (ggml_metal_op_t ctx, int idx);
72
+ int ggml_metal_op_add_id (ggml_metal_op_t ctx, int idx);
73
+ int ggml_metal_op_flash_attn_ext (ggml_metal_op_t ctx, int idx);
74
+ int ggml_metal_op_bin (ggml_metal_op_t ctx, int idx);
75
+ int ggml_metal_op_silu_back (ggml_metal_op_t ctx, int idx);
76
+ int ggml_metal_op_l2_norm (ggml_metal_op_t ctx, int idx);
77
+ int ggml_metal_op_group_norm (ggml_metal_op_t ctx, int idx);
78
+ int ggml_metal_op_norm (ggml_metal_op_t ctx, int idx);
79
+ int ggml_metal_op_rope (ggml_metal_op_t ctx, int idx);
80
+ int ggml_metal_op_im2col (ggml_metal_op_t ctx, int idx);
81
+ int ggml_metal_op_conv_2d (ggml_metal_op_t ctx, int idx);
82
+ int ggml_metal_op_conv_2d_dw (ggml_metal_op_t ctx, int idx);
83
+ int ggml_metal_op_conv_3d (ggml_metal_op_t ctx, int idx);
84
+ int ggml_metal_op_conv_transpose_1d (ggml_metal_op_t ctx, int idx);
85
+ int ggml_metal_op_conv_transpose_2d (ggml_metal_op_t ctx, int idx);
86
+ int ggml_metal_op_col2im_1d (ggml_metal_op_t ctx, int idx);
87
+ int ggml_metal_op_snake_fused (ggml_metal_op_t ctx, int idx);
88
+ int ggml_metal_op_upscale (ggml_metal_op_t ctx, int idx);
89
+ int ggml_metal_op_pad (ggml_metal_op_t ctx, int idx);
90
+ int ggml_metal_op_pad_reflect_1d (ggml_metal_op_t ctx, int idx);
91
+ int ggml_metal_op_roll (ggml_metal_op_t ctx, int idx);
92
+ int ggml_metal_op_arange (ggml_metal_op_t ctx, int idx);
93
+ int ggml_metal_op_timestep_embedding(ggml_metal_op_t ctx, int idx);
94
+ int ggml_metal_op_argmax (ggml_metal_op_t ctx, int idx);
95
+ int ggml_metal_op_argsort (ggml_metal_op_t ctx, int idx);
96
+ int ggml_metal_op_top_k (ggml_metal_op_t ctx, int idx);
97
+ int ggml_metal_op_tri (ggml_metal_op_t ctx, int idx);
98
+ int ggml_metal_op_opt_step_adamw (ggml_metal_op_t ctx, int idx);
99
+ int ggml_metal_op_opt_step_sgd (ggml_metal_op_t ctx, int idx);
100
+ int ggml_metal_op_count_equal (ggml_metal_op_t ctx, int idx);
101
+
102
+ #ifdef __cplusplus
103
+ }
104
+ #endif
ggml/src/ggml-metal/ggml-metal.cpp ADDED
@@ -0,0 +1,950 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "ggml-metal.h"
2
+
3
+ #include "ggml-impl.h"
4
+ #include "ggml-backend-impl.h"
5
+
6
+ #include "ggml-metal-device.h"
7
+ #include "ggml-metal-context.h"
8
+ #include "ggml-metal-ops.h"
9
+
10
+ #include <mutex>
11
+ #include <string>
12
+
13
+ #define GGML_METAL_NAME "MTL"
14
+ #define GGML_METAL_MAX_DEVICES 16
15
+
16
+ // number of Metal devices
17
+ // note: can be overridden with GGML_METAL_DEVICES env to simulate virtual devices
18
+ static int g_devices = 1;
19
+
20
+ // forward declaration
21
+ static bool ggml_backend_buffer_is_metal(ggml_backend_buffer_t buffer);
22
+
23
+ ////////////////////////////////////////////////////////////////////////////////
24
+ // backend interface
25
+ ////////////////////////////////////////////////////////////////////////////////
26
+
27
+ // shared buffer
28
+
29
+ static void ggml_backend_metal_buffer_shared_free_buffer(ggml_backend_buffer_t buffer) {
30
+ ggml_metal_buffer_t ctx = (ggml_metal_buffer_t)buffer->context;
31
+
32
+ GGML_ASSERT(ggml_metal_buffer_is_shared(ctx));
33
+
34
+ ggml_metal_buffer_free(ctx);
35
+ }
36
+
37
+ static void * ggml_backend_metal_buffer_shared_get_base(ggml_backend_buffer_t buffer) {
38
+ ggml_metal_buffer_t ctx = (ggml_metal_buffer_t)buffer->context;
39
+
40
+ GGML_ASSERT(ggml_metal_buffer_is_shared(ctx));
41
+
42
+ return ggml_metal_buffer_get_base(ctx);
43
+ }
44
+
45
+ static void ggml_backend_metal_buffer_shared_memset_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, uint8_t value, size_t offset, size_t size) {
46
+ ggml_metal_buffer_t ctx = (ggml_metal_buffer_t)buffer->context;
47
+
48
+ GGML_ASSERT(ggml_metal_buffer_is_shared(ctx));
49
+
50
+ ggml_metal_buffer_memset_tensor(ctx, tensor, value, offset, size);
51
+ }
52
+
53
+ static void ggml_backend_metal_buffer_shared_set_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
54
+ ggml_metal_buffer_t ctx = (ggml_metal_buffer_t)buffer->context;
55
+
56
+ GGML_ASSERT(ggml_metal_buffer_is_shared(ctx));
57
+
58
+ ggml_metal_buffer_set_tensor(ctx, tensor, data, offset, size);
59
+ }
60
+
61
+ static void ggml_backend_metal_buffer_shared_get_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
62
+ ggml_metal_buffer_t ctx = (ggml_metal_buffer_t)buffer->context;
63
+
64
+ GGML_ASSERT(ggml_metal_buffer_is_shared(ctx));
65
+
66
+ ggml_metal_buffer_get_tensor(ctx, tensor, data, offset, size);
67
+ }
68
+
69
+ static bool ggml_backend_metal_buffer_shared_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
70
+ ggml_metal_buffer_t ctx = (ggml_metal_buffer_t)buffer->context;
71
+
72
+ GGML_ASSERT(ggml_metal_buffer_is_shared(ctx));
73
+
74
+ if (!ggml_backend_buffer_is_metal(src->buffer)) {
75
+ return false;
76
+ }
77
+
78
+ return ggml_metal_buffer_cpy_tensor(ctx, src, dst);
79
+ }
80
+
81
+ static void ggml_backend_metal_buffer_shared_clear(ggml_backend_buffer_t buffer, uint8_t value) {
82
+ ggml_metal_buffer_t ctx = (ggml_metal_buffer_t)buffer->context;
83
+
84
+ GGML_ASSERT(ggml_metal_buffer_is_shared(ctx));
85
+
86
+ ggml_metal_buffer_clear(ctx, value);
87
+ }
88
+
89
+ static ggml_backend_buffer_i ggml_backend_metal_buffer_shared_i = {
90
+ /* .free_buffer = */ ggml_backend_metal_buffer_shared_free_buffer,
91
+ /* .get_base = */ ggml_backend_metal_buffer_shared_get_base,
92
+ /* .init_tensor = */ NULL,
93
+ /* .memset_tensor = */ ggml_backend_metal_buffer_shared_memset_tensor,
94
+ /* .set_tensor = */ ggml_backend_metal_buffer_shared_set_tensor,
95
+ /* .get_tensor = */ ggml_backend_metal_buffer_shared_get_tensor,
96
+ /* .set_tensor_2d = */ NULL,
97
+ /* .get_tensor_2d = */ NULL,
98
+ /* .cpy_tensor = */ ggml_backend_metal_buffer_shared_cpy_tensor,
99
+ /* .clear = */ ggml_backend_metal_buffer_shared_clear,
100
+ /* .reset = */ NULL,
101
+ };
102
+
103
+ // private buffer
104
+
105
+ static void ggml_backend_metal_buffer_private_free_buffer(ggml_backend_buffer_t buffer) {
106
+ ggml_metal_buffer_t ctx = (ggml_metal_buffer_t)buffer->context;
107
+
108
+ GGML_ASSERT(!ggml_metal_buffer_is_shared(ctx));
109
+
110
+ ggml_metal_buffer_free(ctx);
111
+ }
112
+
113
+ static void * ggml_backend_metal_buffer_private_get_base(ggml_backend_buffer_t buffer) {
114
+ ggml_metal_buffer_t ctx = (ggml_metal_buffer_t)buffer->context;
115
+
116
+ GGML_ASSERT(!ggml_metal_buffer_is_shared(ctx));
117
+
118
+ return ggml_metal_buffer_get_base(ctx);
119
+ }
120
+
121
+ static void ggml_backend_metal_buffer_private_memset_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, uint8_t value, size_t offset, size_t size) {
122
+ ggml_metal_buffer_t ctx = (ggml_metal_buffer_t)buffer->context;
123
+
124
+ GGML_ASSERT(!ggml_metal_buffer_is_shared(ctx));
125
+
126
+ ggml_metal_buffer_memset_tensor(ctx, tensor, value, offset, size);
127
+ }
128
+
129
+ static void ggml_backend_metal_buffer_private_set_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
130
+ ggml_metal_buffer_t ctx = (ggml_metal_buffer_t)buffer->context;
131
+
132
+ GGML_ASSERT(!ggml_metal_buffer_is_shared(ctx));
133
+
134
+ ggml_metal_buffer_set_tensor(ctx, tensor, data, offset, size);
135
+ }
136
+
137
+ static void ggml_backend_metal_buffer_private_get_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
138
+ ggml_metal_buffer_t ctx = (ggml_metal_buffer_t)buffer->context;
139
+
140
+ GGML_ASSERT(!ggml_metal_buffer_is_shared(ctx));
141
+
142
+ ggml_metal_buffer_get_tensor(ctx, tensor, data, offset, size);
143
+ }
144
+
145
+ static bool ggml_backend_metal_buffer_private_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
146
+ ggml_metal_buffer_t ctx = (ggml_metal_buffer_t)buffer->context;
147
+
148
+ GGML_ASSERT(!ggml_metal_buffer_is_shared(ctx));
149
+
150
+ if (!ggml_backend_buffer_is_metal(src->buffer)) {
151
+ return false;
152
+ }
153
+
154
+ return ggml_metal_buffer_cpy_tensor(ctx, src, dst);
155
+ }
156
+
157
+ static void ggml_backend_metal_buffer_private_clear(ggml_backend_buffer_t buffer, uint8_t value) {
158
+ ggml_metal_buffer_t ctx = (ggml_metal_buffer_t)buffer->context;
159
+
160
+ GGML_ASSERT(!ggml_metal_buffer_is_shared(ctx));
161
+
162
+ ggml_metal_buffer_clear(ctx, value);
163
+ }
164
+
165
+ static ggml_backend_buffer_i ggml_backend_metal_buffer_private_i = {
166
+ /* .free_buffer = */ ggml_backend_metal_buffer_private_free_buffer,
167
+ /* .get_base = */ ggml_backend_metal_buffer_private_get_base,
168
+ /* .init_tensor = */ NULL,
169
+ /* .memset_tensor = */ ggml_backend_metal_buffer_private_memset_tensor,
170
+ /* .set_tensor = */ ggml_backend_metal_buffer_private_set_tensor,
171
+ /* .get_tensor = */ ggml_backend_metal_buffer_private_get_tensor,
172
+ /* .set_tensor_2d = */ NULL,
173
+ /* .get_tensor_2d = */ NULL,
174
+ /* .cpy_tensor = */ ggml_backend_metal_buffer_private_cpy_tensor,
175
+ /* .clear = */ ggml_backend_metal_buffer_private_clear,
176
+ /* .reset = */ NULL,
177
+ };
178
+
179
+ static bool ggml_backend_buffer_is_metal(ggml_backend_buffer_t buffer) {
180
+ return buffer->iface.free_buffer == ggml_backend_metal_buffer_shared_free_buffer ||
181
+ buffer->iface.free_buffer == ggml_backend_metal_buffer_private_free_buffer;
182
+ }
183
+
184
+ //
185
+ // buffer types
186
+ //
187
+
188
+ struct ggml_backend_metal_buffer_type {
189
+ int device;
190
+ std::string name;
191
+ };
192
+
193
+ struct ggml_backend_metal_buffer_type_deleter {
194
+ void operator()(ggml_backend_metal_buffer_type * ctx) const {
195
+ delete ctx;
196
+ }
197
+ };
198
+
199
+ typedef std::unique_ptr<ggml_backend_metal_buffer_type, ggml_backend_metal_buffer_type_deleter> ggml_backend_metal_buffer_type_ptr;
200
+
201
+ // common method for allocating shread or private Metal buffers
202
+ static ggml_backend_buffer_t ggml_backend_metal_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size, bool shared) {
203
+ ggml_metal_device_t ctx_dev = (ggml_metal_device_t)buft->device->context;
204
+ ggml_metal_buffer_t res = ggml_metal_buffer_init(ctx_dev, size, shared);
205
+
206
+ ggml_backend_buffer_i buf_i = ggml_metal_buffer_is_shared(res)
207
+ ? ggml_backend_metal_buffer_shared_i
208
+ : ggml_backend_metal_buffer_private_i;
209
+
210
+ return ggml_backend_buffer_init(buft, buf_i, res, size);
211
+ }
212
+
213
+ static size_t ggml_backend_metal_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
214
+ size_t res = ggml_nbytes(tensor);
215
+
216
+ // some operations require additional memory for fleeting data:
217
+ switch (tensor->op) {
218
+ case GGML_OP_MUL_MAT_ID:
219
+ {
220
+ res += ggml_metal_op_mul_mat_id_extra_tpe(tensor);
221
+ res += ggml_metal_op_mul_mat_id_extra_ids(tensor);
222
+ } break;
223
+ case GGML_OP_FLASH_ATTN_EXT:
224
+ {
225
+ res += ggml_metal_op_flash_attn_ext_extra_pad(tensor);
226
+ res += ggml_metal_op_flash_attn_ext_extra_blk(tensor);
227
+ res += ggml_metal_op_flash_attn_ext_extra_tmp(tensor);
228
+ } break;
229
+ case GGML_OP_CUMSUM:
230
+ case GGML_OP_ARGSORT:
231
+ {
232
+ res *= 2;
233
+ } break;
234
+ case GGML_OP_TOP_K:
235
+ {
236
+ res = 2*sizeof(int32_t)*ggml_nelements(tensor->src[0]);
237
+ } break;
238
+ default:
239
+ break;
240
+ }
241
+
242
+ return res;
243
+
244
+ GGML_UNUSED(buft);
245
+ }
246
+
247
+ // default (shared) buffer type
248
+
249
+ static const char * ggml_backend_metal_buffer_type_shared_get_name(ggml_backend_buffer_type_t buft) {
250
+ ggml_backend_metal_buffer_type * ctx = (ggml_backend_metal_buffer_type *)buft->context;
251
+
252
+ return ctx->name.c_str();
253
+ }
254
+
255
+ static ggml_backend_buffer_t ggml_backend_metal_buffer_type_shared_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
256
+ return ggml_backend_metal_buffer_type_alloc_buffer(buft, size, true);
257
+ }
258
+
259
+ static size_t ggml_backend_metal_buffer_type_shared_get_alignment(ggml_backend_buffer_type_t buft) {
260
+ return 32;
261
+
262
+ GGML_UNUSED(buft);
263
+ }
264
+
265
+ static size_t ggml_backend_metal_buffer_type_shared_get_max_size(ggml_backend_buffer_type_t buft) {
266
+ ggml_metal_device_t ctx_dev = (ggml_metal_device_t)buft->device->context;
267
+
268
+ return ggml_metal_device_get_props(ctx_dev)->max_buffer_size;
269
+ }
270
+
271
+ static size_t ggml_backend_metal_buffer_type_shared_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
272
+ return ggml_backend_metal_buffer_type_get_alloc_size(buft, tensor);
273
+ }
274
+
275
+ static bool ggml_backend_metal_buffer_type_shared_is_host(ggml_backend_buffer_type_t buft) {
276
+ return false;
277
+
278
+ GGML_UNUSED(buft);
279
+ }
280
+
281
+ static ggml_backend_buffer_type_t ggml_backend_metal_buffer_type_shared(int device) {
282
+ static std::mutex mutex;
283
+ std::lock_guard<std::mutex> lock(mutex);
284
+
285
+ static std::vector<ggml_backend_buffer_type> bufts;
286
+ static std::vector<ggml_backend_metal_buffer_type_ptr> ctxs;
287
+
288
+ static bool initialized = false;
289
+ if (!initialized) {
290
+ bufts.reserve(g_devices);
291
+ ctxs.reserve(g_devices);
292
+
293
+ for (int i = 0; i < g_devices; ++i) {
294
+ ggml_backend_metal_buffer_type * raw_ctx =
295
+ new ggml_backend_metal_buffer_type {
296
+ /* .device = */ i,
297
+ /* .name = */ GGML_METAL_NAME + std::to_string(i),
298
+ };
299
+ ctxs.emplace_back(raw_ctx);
300
+
301
+ ggml_backend_buffer_type buft = {
302
+ /* .iface = */ {
303
+ /* .get_name = */ ggml_backend_metal_buffer_type_shared_get_name,
304
+ /* .alloc_buffer = */ ggml_backend_metal_buffer_type_shared_alloc_buffer,
305
+ /* .get_alignment = */ ggml_backend_metal_buffer_type_shared_get_alignment,
306
+ /* .get_max_size = */ ggml_backend_metal_buffer_type_shared_get_max_size,
307
+ /* .get_alloc_size = */ ggml_backend_metal_buffer_type_shared_get_alloc_size,
308
+ /* .is_host = */ ggml_backend_metal_buffer_type_shared_is_host,
309
+ },
310
+ /* .device = */ ggml_backend_reg_dev_get(ggml_backend_metal_reg(), i),
311
+ /* .context = */ raw_ctx,
312
+ };
313
+
314
+ bufts.emplace_back(buft);
315
+ }
316
+
317
+ initialized = true;
318
+ }
319
+
320
+ return &bufts[device];
321
+ }
322
+
323
+ // default (private) buffer type
324
+
325
+ static const char * ggml_backend_metal_buffer_type_private_get_name(ggml_backend_buffer_type_t buft) {
326
+ ggml_backend_metal_buffer_type * ctx = (ggml_backend_metal_buffer_type *)buft->context;
327
+
328
+ return ctx->name.c_str();
329
+ }
330
+
331
+ static ggml_backend_buffer_t ggml_backend_metal_buffer_type_private_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
332
+ return ggml_backend_metal_buffer_type_alloc_buffer(buft, size, false);
333
+ }
334
+
335
+ static size_t ggml_backend_metal_buffer_type_private_get_alignment(ggml_backend_buffer_type_t buft) {
336
+ return 32;
337
+
338
+ GGML_UNUSED(buft);
339
+ }
340
+
341
+ static size_t ggml_backend_metal_buffer_type_private_get_max_size(ggml_backend_buffer_type_t buft) {
342
+ ggml_metal_device_t ctx_dev = (ggml_metal_device_t)buft->device->context;
343
+
344
+ return ggml_metal_device_get_props(ctx_dev)->max_buffer_size;
345
+ }
346
+
347
+ static size_t ggml_backend_metal_buffer_type_private_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
348
+ return ggml_backend_metal_buffer_type_get_alloc_size(buft, tensor);
349
+ }
350
+
351
+ static bool ggml_backend_metal_buffer_type_private_is_host(ggml_backend_buffer_type_t buft) {
352
+ return false;
353
+
354
+ GGML_UNUSED(buft);
355
+ }
356
+
357
+ static ggml_backend_buffer_type_t ggml_backend_metal_buffer_type_private(int device) {
358
+ static std::mutex mutex;
359
+ std::lock_guard<std::mutex> lock(mutex);
360
+
361
+ static std::vector<ggml_backend_buffer_type> bufts;
362
+ static std::vector<ggml_backend_metal_buffer_type_ptr> ctxs;
363
+
364
+ static bool initialized = false;
365
+ if (!initialized) {
366
+ bufts.reserve(g_devices);
367
+ ctxs.reserve(g_devices);
368
+
369
+ for (int i = 0; i < g_devices; ++i) {
370
+ ggml_backend_metal_buffer_type * raw_ctx = new ggml_backend_metal_buffer_type{
371
+ /* .device = */ i,
372
+ /* .name = */ GGML_METAL_NAME + std::to_string(i) + "_Private"
373
+ };
374
+ ctxs.emplace_back(raw_ctx);
375
+
376
+ ggml_backend_buffer_type buft = {
377
+ /* .iface = */ {
378
+ /* .get_name = */ ggml_backend_metal_buffer_type_private_get_name,
379
+ /* .alloc_buffer = */ ggml_backend_metal_buffer_type_private_alloc_buffer,
380
+ /* .get_alignment = */ ggml_backend_metal_buffer_type_private_get_alignment,
381
+ /* .get_max_size = */ ggml_backend_metal_buffer_type_private_get_max_size,
382
+ /* .get_alloc_size = */ ggml_backend_metal_buffer_type_private_get_alloc_size,
383
+ /* .is_host = */ ggml_backend_metal_buffer_type_private_is_host,
384
+ },
385
+ /* .device = */ ggml_backend_reg_dev_get(ggml_backend_metal_reg(), i),
386
+ /* .context = */ raw_ctx,
387
+ };
388
+
389
+ bufts.emplace_back(buft);
390
+ }
391
+
392
+ initialized = true;
393
+ }
394
+
395
+ return &bufts[device];
396
+ }
397
+
398
+ // mapped buffer type
399
+
400
+ static const char * ggml_backend_metal_buffer_type_mapped_get_name(ggml_backend_buffer_type_t buft) {
401
+ ggml_backend_metal_buffer_type * ctx = (ggml_backend_metal_buffer_type *)buft->context;
402
+
403
+ return ctx->name.c_str();
404
+ }
405
+
406
+ static ggml_backend_buffer_t ggml_backend_metal_buffer_type_mapped_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
407
+ // for mapped buffers, prefer shared memory
408
+ return ggml_backend_metal_buffer_type_alloc_buffer(buft, size, true);
409
+ }
410
+
411
+ static size_t ggml_backend_metal_buffer_type_mapped_get_alignment(ggml_backend_buffer_type_t buft) {
412
+ return 32;
413
+
414
+ GGML_UNUSED(buft);
415
+ }
416
+
417
+ static size_t ggml_backend_metal_buffer_type_mapped_get_max_size(ggml_backend_buffer_type_t buft) {
418
+ ggml_metal_device_t ctx_dev = (ggml_metal_device_t)buft->device->context;
419
+
420
+ return ggml_metal_device_get_props(ctx_dev)->max_buffer_size;
421
+ }
422
+
423
+ static size_t ggml_backend_metal_buffer_type_mapped_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
424
+ return ggml_backend_metal_buffer_type_get_alloc_size(buft, tensor);
425
+ }
426
+
427
+ static bool ggml_backend_metal_buffer_type_mapped_is_host(ggml_backend_buffer_type_t buft) {
428
+ return false;
429
+
430
+ GGML_UNUSED(buft);
431
+ }
432
+
433
+ static ggml_backend_buffer_type_t ggml_backend_metal_buffer_type_mapped(int device) {
434
+ static std::mutex mutex;
435
+ std::lock_guard<std::mutex> lock(mutex);
436
+
437
+ static std::vector<ggml_backend_buffer_type> bufts;
438
+ static std::vector<ggml_backend_metal_buffer_type_ptr> ctxs;
439
+
440
+ static bool initialized = false;
441
+ if (!initialized) {
442
+ bufts.reserve(g_devices);
443
+ ctxs.reserve(g_devices);
444
+
445
+ for (int i = 0; i < g_devices; ++i) {
446
+ ggml_backend_metal_buffer_type * raw_ctx = new ggml_backend_metal_buffer_type{
447
+ /* .device = */ i,
448
+ /* .name = */ GGML_METAL_NAME + std::to_string(i) + "_Mapped"
449
+ };
450
+ ctxs.emplace_back(raw_ctx);
451
+
452
+ // note: not obvious, but this buffer type still needs to implement .alloc_buffer:
453
+ // https://github.com/ggml-org/llama.cpp/pull/15832#discussion_r2333177099
454
+ ggml_backend_buffer_type buft = {
455
+ /* .iface = */ {
456
+ /* .get_name = */ ggml_backend_metal_buffer_type_mapped_get_name,
457
+ /* .alloc_buffer = */ ggml_backend_metal_buffer_type_mapped_alloc_buffer,
458
+ /* .get_alignment = */ ggml_backend_metal_buffer_type_mapped_get_alignment,
459
+ /* .get_max_size = */ ggml_backend_metal_buffer_type_mapped_get_max_size,
460
+ /* .get_alloc_size = */ ggml_backend_metal_buffer_type_mapped_get_alloc_size,
461
+ /* .is_host = */ ggml_backend_metal_buffer_type_mapped_is_host,
462
+ },
463
+ /* .device = */ ggml_backend_reg_dev_get(ggml_backend_metal_reg(), i),
464
+ /* .context = */ raw_ctx,
465
+ };
466
+
467
+ bufts.emplace_back(buft);
468
+ }
469
+
470
+ initialized = true;
471
+ }
472
+
473
+ return &bufts[device];
474
+ }
475
+
476
+ // backend
477
+
478
+ static const char * ggml_backend_metal_name(ggml_backend_t backend) {
479
+ ggml_metal_t ctx = (ggml_metal_t)backend->context;
480
+
481
+ return ggml_metal_get_name(ctx);
482
+ }
483
+
484
+ static void ggml_backend_metal_free(ggml_backend_t backend) {
485
+ ggml_metal_t ctx = (ggml_metal_t)backend->context;
486
+
487
+ // wait for any ongoing async operations to finish
488
+ ggml_metal_synchronize(ctx);
489
+
490
+ ggml_metal_free(ctx);
491
+
492
+ free(backend);
493
+ }
494
+
495
+ static void ggml_backend_metal_synchronize(ggml_backend_t backend) {
496
+ ggml_metal_t ctx = (ggml_metal_t)backend->context;
497
+
498
+ ggml_metal_synchronize(ctx);
499
+ }
500
+
501
+ static void ggml_backend_metal_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
502
+ ggml_metal_t ctx = (ggml_metal_t)backend->context;
503
+
504
+ ggml_metal_set_tensor_async(ctx, tensor, data, offset, size);
505
+ }
506
+
507
+ static void ggml_backend_metal_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
508
+ ggml_metal_t ctx = (ggml_metal_t)backend->context;
509
+
510
+ ggml_metal_get_tensor_async(ctx, tensor, data, offset, size);
511
+ }
512
+
513
+ static bool ggml_backend_metal_cpy_tensor_async(ggml_backend_t backend_src, ggml_backend_t backend_dst, const ggml_tensor * src, ggml_tensor * dst) {
514
+ if (!ggml_backend_is_metal(backend_src) || !ggml_backend_is_metal(backend_dst)) {
515
+ return false;
516
+ }
517
+
518
+ if (!ggml_backend_buffer_is_metal(src->buffer) || !ggml_backend_buffer_is_metal(dst->buffer)) {
519
+ return false;
520
+ }
521
+
522
+ ggml_metal_t ctx_src = (ggml_metal_t)backend_src->context;
523
+ ggml_metal_t ctx_dst = (ggml_metal_t)backend_dst->context;
524
+
525
+ //ggml_backend_buffer_t buf_src = src->view_src ? src->view_src->buffer : src->buffer;
526
+ //ggml_backend_buffer_t buf_dst = dst->view_src ? dst->view_src->buffer : dst->buffer;
527
+
528
+ //ggml_metal_buffer_t buf_ctx_src = (ggml_metal_buffer_t)buf_src->context;
529
+ //ggml_metal_buffer_t buf_ctx_dst = (ggml_metal_buffer_t)buf_dst->context;
530
+
531
+ return ggml_metal_cpy_tensor_async(ctx_src, ctx_dst, src, dst);
532
+ }
533
+
534
+ static enum ggml_status ggml_backend_metal_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
535
+ ggml_metal_t ctx = (ggml_metal_t)backend->context;
536
+
537
+ return ggml_metal_graph_compute(ctx, cgraph);
538
+ }
539
+
540
+ static void ggml_backend_metal_event_record(ggml_backend_t backend, ggml_backend_event_t event) {
541
+ ggml_metal_t ctx = (ggml_metal_t)backend->context;
542
+ ggml_metal_event_t ev = (ggml_metal_event_t)event->context;
543
+
544
+ ggml_metal_event_record(ctx, ev);
545
+ }
546
+
547
+ static void ggml_backend_metal_event_wait(ggml_backend_t backend, ggml_backend_event_t event) {
548
+ ggml_metal_t ctx = (ggml_metal_t)backend->context;
549
+ ggml_metal_event_t ev = (ggml_metal_event_t)event->context;
550
+
551
+ ggml_metal_event_wait(ctx, ev);
552
+ }
553
+
554
+ static void ggml_backend_metal_graph_optimize(ggml_backend_t backend, ggml_cgraph * cgraph) {
555
+ ggml_metal_t ctx = (ggml_metal_t)backend->context;
556
+
557
+ ggml_metal_graph_optimize(ctx, cgraph);
558
+ }
559
+
560
+ static void ggml_backend_metal_set_n_cb(ggml_backend_t backend, int n_cb) {
561
+ GGML_ASSERT(ggml_backend_is_metal(backend));
562
+
563
+ ggml_metal_t ctx = (ggml_metal_t)backend->context;
564
+
565
+ ggml_metal_set_n_cb(ctx, n_cb);
566
+ }
567
+
568
+ static ggml_backend_i ggml_backend_metal_i = {
569
+ /* .get_name = */ ggml_backend_metal_name,
570
+ /* .free = */ ggml_backend_metal_free,
571
+ /* .set_tensor_async = */ ggml_backend_metal_set_tensor_async,
572
+ /* .get_tensor_async = */ ggml_backend_metal_get_tensor_async,
573
+ /* .set_tensor_2d_async = */ NULL,
574
+ /* .get_tensor_2d_async = */ NULL,
575
+ /* .cpy_tensor_async = */ ggml_backend_metal_cpy_tensor_async, // only needed for multi-GPU setups
576
+ /* .synchronize = */ ggml_backend_metal_synchronize,
577
+ /* .graph_plan_create = */ NULL,
578
+ /* .graph_plan_free = */ NULL,
579
+ /* .graph_plan_update = */ NULL,
580
+ /* .graph_plan_compute = */ NULL,
581
+ /* .graph_compute = */ ggml_backend_metal_graph_compute,
582
+ /* .event_record = */ ggml_backend_metal_event_record,
583
+ /* .event_wait = */ ggml_backend_metal_event_wait,
584
+ /* .graph_optimize = */ ggml_backend_metal_graph_optimize,
585
+ };
586
+
587
+ static ggml_guid_t ggml_backend_metal_guid(void) {
588
+ static ggml_guid guid = { 0x81, 0xa1, 0x8b, 0x1e, 0x71, 0xec, 0x79, 0xed, 0x2b, 0x85, 0xdc, 0x8a, 0x61, 0x98, 0x30, 0xe6 };
589
+ return &guid;
590
+ }
591
+
592
+ ggml_backend_t ggml_backend_metal_init(void) {
593
+ ggml_backend_dev_t dev = ggml_backend_reg_dev_get(ggml_backend_metal_reg(), 0);
594
+ ggml_metal_device_t ctx_dev = (ggml_metal_device_t)dev->context;
595
+
596
+ ggml_metal_t ctx = ggml_metal_init(ctx_dev);
597
+ if (ctx == NULL) {
598
+ GGML_LOG_ERROR("%s: error: failed to allocate context\n", __func__);
599
+ return NULL;
600
+ }
601
+
602
+ ggml_backend_t backend = (ggml_backend_t) malloc(sizeof(ggml_backend));
603
+
604
+ *backend = {
605
+ /* .guid = */ ggml_backend_metal_guid(),
606
+ /* .interface = */ ggml_backend_metal_i,
607
+ /* .device = */ dev,
608
+ /* .context = */ ctx,
609
+ };
610
+
611
+ ggml_backend_metal_set_n_cb(backend, 1);
612
+
613
+ return backend;
614
+ }
615
+
616
+ bool ggml_backend_is_metal(ggml_backend_t backend) {
617
+ return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_metal_guid());
618
+ }
619
+
620
+ void ggml_backend_metal_set_abort_callback(ggml_backend_t backend, ggml_abort_callback abort_callback, void * user_data) {
621
+ GGML_ASSERT(ggml_backend_is_metal(backend));
622
+
623
+ ggml_metal_t ctx = (ggml_metal_t)backend->context;
624
+
625
+ ggml_metal_set_abort_callback(ctx, abort_callback, user_data);
626
+ }
627
+
628
+ bool ggml_backend_metal_supports_family(ggml_backend_t backend, int family) {
629
+ GGML_ASSERT(ggml_backend_is_metal(backend));
630
+
631
+ ggml_metal_t ctx = (ggml_metal_t)backend->context;
632
+
633
+ return ggml_metal_supports_family(ctx, family);
634
+ }
635
+
636
+ void ggml_backend_metal_capture_next_compute(ggml_backend_t backend) {
637
+ GGML_ASSERT(ggml_backend_is_metal(backend));
638
+
639
+ ggml_metal_t ctx = (ggml_metal_t)backend->context;
640
+
641
+ ggml_metal_capture_next_compute(ctx);
642
+ }
643
+
644
+ // backend device
645
+
646
+ static const char * ggml_backend_metal_device_get_name(ggml_backend_dev_t dev) {
647
+ ggml_metal_device_t ctx_dev = (ggml_metal_device_t)dev->context;
648
+
649
+ const ggml_metal_device_props * props_dev = ggml_metal_device_get_props(ctx_dev);
650
+
651
+ return props_dev->name;
652
+ }
653
+
654
+ static const char * ggml_backend_metal_device_get_description(ggml_backend_dev_t dev) {
655
+ ggml_metal_device_t ctx_dev = (ggml_metal_device_t)dev->context;
656
+
657
+ return ggml_metal_device_get_props(ctx_dev)->desc;
658
+ }
659
+
660
+ static void ggml_backend_metal_device_get_memory(ggml_backend_dev_t dev, size_t * free, size_t * total) {
661
+ ggml_metal_device_t ctx_dev = (ggml_metal_device_t)dev->context;
662
+
663
+ ggml_metal_device_get_memory(ctx_dev, free, total);
664
+ }
665
+
666
+ static enum ggml_backend_dev_type ggml_backend_metal_device_get_type(ggml_backend_dev_t dev) {
667
+ return GGML_BACKEND_DEVICE_TYPE_GPU;
668
+
669
+ GGML_UNUSED(dev);
670
+ }
671
+
672
+ static void ggml_backend_metal_device_get_props(ggml_backend_dev_t dev, ggml_backend_dev_props * props) {
673
+ props->name = ggml_backend_metal_device_get_name(dev);
674
+ props->description = ggml_backend_metal_device_get_description(dev);
675
+ props->type = ggml_backend_metal_device_get_type(dev);
676
+
677
+ ggml_backend_metal_device_get_memory(dev, &props->memory_free, &props->memory_total);
678
+
679
+ props->caps = {
680
+ /* .async = */ true,
681
+ /* .host_buffer = */ false,
682
+ /* .buffer_from_host_ptr = */ true,
683
+ /* .events = */ true,
684
+ };
685
+ }
686
+
687
+ static ggml_backend_t ggml_backend_metal_device_init_backend(ggml_backend_dev_t dev, const char * params) {
688
+ ggml_metal_device_t ctx_dev = (ggml_metal_device_t)dev->context;
689
+
690
+ ggml_metal_t ctx = ggml_metal_init(ctx_dev);
691
+ if (ctx == NULL) {
692
+ GGML_LOG_ERROR("%s: error: failed to allocate context\n", __func__);
693
+ return NULL;
694
+ }
695
+
696
+ ggml_backend_t backend = (ggml_backend_t) malloc(sizeof(ggml_backend));
697
+
698
+ *backend = {
699
+ /* .guid = */ ggml_backend_metal_guid(),
700
+ /* .interface = */ ggml_backend_metal_i,
701
+ /* .device = */ dev,
702
+ /* .context = */ ctx,
703
+ };
704
+
705
+ ggml_backend_metal_set_n_cb(backend, 1);
706
+
707
+ return backend;
708
+
709
+ GGML_UNUSED(params);
710
+ }
711
+
712
+ static ggml_backend_buffer_type_t ggml_backend_metal_device_get_buffer_type(ggml_backend_dev_t dev) {
713
+ ggml_metal_device_t ctx_dev = (ggml_metal_device_t)dev->context;
714
+
715
+ const ggml_metal_device_props * props_dev = ggml_metal_device_get_props(ctx_dev);
716
+
717
+ return props_dev->use_shared_buffers ? ggml_backend_metal_buffer_type_shared(props_dev->device) : ggml_backend_metal_buffer_type_private(props_dev->device);
718
+ }
719
+
720
+ static ggml_backend_buffer_t ggml_backend_metal_device_buffer_mapped(ggml_backend_dev_t dev, void * ptr, size_t size, size_t max_tensor_size) {
721
+ ggml_metal_device_t ctx_dev = (ggml_metal_device_t)dev->context;
722
+
723
+ ggml_metal_buffer_t res = ggml_metal_buffer_map(ctx_dev, ptr, size, max_tensor_size);
724
+
725
+ const ggml_metal_device_props * props_dev = ggml_metal_device_get_props(ctx_dev);
726
+
727
+ return ggml_backend_buffer_init(ggml_backend_metal_buffer_type_mapped(props_dev->device), ggml_backend_metal_buffer_shared_i, res, size);
728
+ }
729
+
730
+ static bool ggml_backend_metal_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
731
+ ggml_metal_device_t ctx_dev = (ggml_metal_device_t)dev->context;
732
+
733
+ return ggml_metal_device_supports_op(ctx_dev, op);
734
+ }
735
+
736
+ static bool ggml_backend_metal_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
737
+ return
738
+ buft->device == dev && (
739
+ buft->iface.get_name == ggml_backend_metal_buffer_type_shared_get_name ||
740
+ buft->iface.get_name == ggml_backend_metal_buffer_type_private_get_name ||
741
+ buft->iface.get_name == ggml_backend_metal_buffer_type_mapped_get_name);
742
+
743
+ GGML_UNUSED(dev);
744
+ }
745
+
746
+ static int64_t get_op_batch_size(const ggml_tensor * op) {
747
+ switch (op->op) {
748
+ case GGML_OP_MUL_MAT:
749
+ return op->ne[1];
750
+ case GGML_OP_MUL_MAT_ID:
751
+ return op->ne[2];
752
+ default:
753
+ return ggml_nrows(op);
754
+ }
755
+ }
756
+
757
+ static bool ggml_backend_metal_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
758
+ ggml_metal_device_t ctx_dev = (ggml_metal_device_t)dev->context;
759
+
760
+ return (op->op == GGML_OP_MUL_MAT ||
761
+ op->op == GGML_OP_MUL_MAT_ID) &&
762
+ get_op_batch_size(op) >= ggml_metal_device_get_props(ctx_dev)->op_offload_min_batch_size;
763
+ }
764
+
765
+ static ggml_backend_event_t ggml_backend_metal_device_event_new(ggml_backend_dev_t dev) {
766
+ ggml_metal_device_t ctx_dev = (ggml_metal_device_t)dev->context;
767
+
768
+ ggml_metal_event_t event = ggml_metal_device_event_init(ctx_dev);
769
+ GGML_ASSERT(event);
770
+
771
+ ggml_backend_event_t ev = new ggml_backend_event {
772
+ /* .device = */ dev,
773
+ /* .context = */ event,
774
+ };
775
+
776
+ return ev;
777
+ }
778
+
779
+ static void ggml_backend_metal_device_event_free(ggml_backend_dev_t dev, ggml_backend_event_t event) {
780
+ ggml_metal_device_t ctx_dev = (ggml_metal_device_t)dev->context;
781
+
782
+ ggml_metal_event_t ev = (ggml_metal_event_t)event->context;
783
+
784
+ ggml_metal_device_event_free(ctx_dev, ev);
785
+
786
+ delete event;
787
+ }
788
+
789
+ static void ggml_backend_metal_device_event_synchronize(ggml_backend_dev_t dev, ggml_backend_event_t event) {
790
+ ggml_metal_device_t ctx_dev = (ggml_metal_device_t)dev->context;
791
+
792
+ ggml_metal_event_t evt = (ggml_metal_event_t)event->context;
793
+
794
+ ggml_metal_device_event_synchronize(ctx_dev, evt);
795
+ }
796
+
797
+ static ggml_backend_device_i ggml_backend_metal_device_i = {
798
+ /* .get_name = */ ggml_backend_metal_device_get_name,
799
+ /* .get_description = */ ggml_backend_metal_device_get_description,
800
+ /* .get_memory = */ ggml_backend_metal_device_get_memory,
801
+ /* .get_type = */ ggml_backend_metal_device_get_type,
802
+ /* .get_props = */ ggml_backend_metal_device_get_props,
803
+ /* .init_backend = */ ggml_backend_metal_device_init_backend,
804
+ /* .get_buffer_type = */ ggml_backend_metal_device_get_buffer_type,
805
+ /* .get_host_buffer_type = */ NULL,
806
+ /* .buffer_from_host_ptr = */ ggml_backend_metal_device_buffer_mapped,
807
+ /* .supports_op = */ ggml_backend_metal_device_supports_op,
808
+ /* .supports_buft = */ ggml_backend_metal_device_supports_buft,
809
+ /* .offload_op = */ ggml_backend_metal_device_offload_op,
810
+ /* .event_new = */ ggml_backend_metal_device_event_new,
811
+ /* .event_free = */ ggml_backend_metal_device_event_free,
812
+ /* .event_synchronize = */ ggml_backend_metal_device_event_synchronize,
813
+ };
814
+
815
+ // backend registry
816
+
817
+ struct ggml_backend_metal_reg {
818
+ std::vector<ggml_backend_dev_t> devices;
819
+ };
820
+
821
+ typedef struct ggml_backend_metal_reg * ggml_backend_metal_reg_t;
822
+
823
+ static ggml_backend_metal_reg_t ggml_backend_metal_reg_init(void) {
824
+ ggml_backend_metal_reg_t ctx = new struct ggml_backend_metal_reg;
825
+
826
+ return ctx;
827
+ }
828
+
829
+ static void ggml_backend_metal_reg_free(ggml_backend_metal_reg_t ctx) {
830
+ delete ctx;
831
+ }
832
+
833
+ struct ggml_backend_metal_reg_deleter {
834
+ void operator()(ggml_backend_metal_reg_t ctx) {
835
+ ggml_backend_metal_reg_free(ctx);
836
+ }
837
+ };
838
+
839
+ typedef std::unique_ptr<struct ggml_backend_metal_reg, ggml_backend_metal_reg_deleter> ggml_backend_metal_reg_ptr;
840
+
841
+ static const char * ggml_backend_metal_reg_get_name(ggml_backend_reg_t reg) {
842
+ return GGML_METAL_NAME;
843
+
844
+ GGML_UNUSED(reg);
845
+ }
846
+
847
+ static size_t ggml_backend_metal_reg_device_count(ggml_backend_reg_t reg) {
848
+ ggml_backend_metal_reg_t ctx = (ggml_backend_metal_reg_t)reg->context;
849
+ return ctx->devices.size();
850
+ }
851
+
852
+ static ggml_backend_dev_t ggml_backend_metal_reg_device_get(ggml_backend_reg_t reg, size_t index) {
853
+ ggml_backend_metal_reg_t ctx = (ggml_backend_metal_reg_t)reg->context;
854
+ GGML_ASSERT(index < ctx->devices.size());
855
+ return ctx->devices[index];
856
+ }
857
+
858
+ static ggml_backend_feature g_ggml_backend_metal_features[] = {
859
+ #if defined(GGML_METAL_EMBED_LIBRARY)
860
+ { "EMBED_LIBRARY", "1" },
861
+ #endif
862
+ { NULL, NULL },
863
+ };
864
+
865
+ static ggml_backend_feature * ggml_backend_metal_get_features(ggml_backend_reg_t reg) {
866
+ return g_ggml_backend_metal_features;
867
+
868
+ GGML_UNUSED(reg);
869
+ }
870
+
871
+ static void * ggml_backend_metal_get_proc_address(ggml_backend_reg_t reg, const char * name) {
872
+ if (strcmp(name, "ggml_backend_get_features") == 0) {
873
+ return (void *)ggml_backend_metal_get_features;
874
+ }
875
+
876
+ return NULL;
877
+
878
+ GGML_UNUSED(reg);
879
+ }
880
+
881
+ static ggml_backend_reg_i ggml_backend_metal_reg_i = {
882
+ /* .get_name = */ ggml_backend_metal_reg_get_name,
883
+ /* .get_device_count = */ ggml_backend_metal_reg_device_count,
884
+ /* .get_device = */ ggml_backend_metal_reg_device_get,
885
+ /* .get_proc_address = */ ggml_backend_metal_get_proc_address,
886
+ };
887
+
888
+ static ggml_backend_dev_t ggml_backend_metal_device_init(ggml_backend_reg_t reg, int device) {
889
+ return new ggml_backend_device {
890
+ /* .iface = */ ggml_backend_metal_device_i,
891
+ /* .reg = */ reg,
892
+ /* .context = */ ggml_metal_device_get(device),
893
+ };
894
+ }
895
+
896
+ static void ggml_backend_metal_device_free(ggml_backend_dev_t dev) {
897
+ delete dev;
898
+ }
899
+
900
+ struct ggml_backend_device_deleter {
901
+ void operator()(ggml_backend_dev_t ctx) {
902
+ ggml_backend_metal_device_free(ctx);
903
+ }
904
+ };
905
+
906
+ typedef std::unique_ptr<ggml_backend_device, ggml_backend_device_deleter> ggml_backend_device_ptr;
907
+
908
+ ggml_backend_reg_t ggml_backend_metal_reg(void) {
909
+ static ggml_backend_reg reg;
910
+ static bool initialized = false;
911
+
912
+ {
913
+ static std::mutex mutex;
914
+ std::lock_guard<std::mutex> lock(mutex);
915
+
916
+ const char * env = getenv("GGML_METAL_DEVICES");
917
+ if (env) {
918
+ g_devices = atoi(env);
919
+ }
920
+
921
+ static std::vector<ggml_backend_device_ptr> devs;
922
+
923
+ if (!initialized) {
924
+ // workaround macOS limitation (kIOGPUCommandBufferCallbackErrorImpactingInteractivity) until proper fix becomes possible
925
+ // ref: https://github.com/ggml-org/llama.cpp/issues/20141#issuecomment-4272947703
926
+ setenv("AGX_RELAX_CDM_CTXSTORE_TIMEOUT", "1", true);
927
+
928
+ static ggml_backend_metal_reg_ptr reg_ctx(ggml_backend_metal_reg_init());
929
+
930
+ for (int i = 0; i < g_devices; ++i) {
931
+ auto * dev = ggml_backend_metal_device_init(&reg, i);
932
+ devs.emplace_back(dev);
933
+
934
+ reg_ctx->devices.push_back(dev);
935
+ }
936
+
937
+ reg = {
938
+ /* .api_version = */ GGML_BACKEND_API_VERSION,
939
+ /* .iface = */ ggml_backend_metal_reg_i,
940
+ /* .context = */ reg_ctx.get(),
941
+ };
942
+ }
943
+
944
+ initialized = true;
945
+ }
946
+
947
+ return &reg;
948
+ }
949
+
950
+ GGML_BACKEND_DL_IMPL(ggml_backend_metal_reg)
ggml/src/ggml-metal/ggml-metal.metal ADDED
The diff for this file is too large to render. See raw diff
 
ggml/src/ggml-musa/CMakeLists.txt ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ if (NOT EXISTS $ENV{MUSA_PATH})
2
+ if (NOT EXISTS /opt/musa)
3
+ set(MUSA_PATH /usr/local/musa)
4
+ else()
5
+ set(MUSA_PATH /opt/musa)
6
+ endif()
7
+ else()
8
+ set(MUSA_PATH $ENV{MUSA_PATH})
9
+ endif()
10
+
11
+ set(CMAKE_C_COMPILER "${MUSA_PATH}/bin/clang")
12
+ set(CMAKE_C_EXTENSIONS OFF)
13
+ set(CMAKE_CXX_COMPILER "${MUSA_PATH}/bin/clang++")
14
+ set(CMAKE_CXX_EXTENSIONS OFF)
15
+
16
+ list(APPEND CMAKE_MODULE_PATH "${MUSA_PATH}/cmake")
17
+
18
+ find_package(MUSAToolkit)
19
+
20
+ if (MUSAToolkit_FOUND)
21
+ message(STATUS "MUSA Toolkit found")
22
+
23
+ if (NOT DEFINED MUSA_ARCHITECTURES)
24
+ set(MUSA_ARCHITECTURES "21;22;31")
25
+ endif()
26
+ message(STATUS "Using MUSA architectures: ${MUSA_ARCHITECTURES}")
27
+
28
+ file(GLOB GGML_HEADERS_MUSA "../ggml-cuda/*.cuh")
29
+ list(APPEND GGML_HEADERS_MUSA "../../include/ggml-cuda.h")
30
+ list(APPEND GGML_HEADERS_MUSA "../ggml-musa/mudnn.cuh")
31
+
32
+ file(GLOB GGML_SOURCES_MUSA "../ggml-cuda/*.cu")
33
+ file(GLOB SRCS "../ggml-cuda/template-instances/fattn-tile*.cu")
34
+ list(APPEND GGML_SOURCES_MUSA ${SRCS})
35
+ file(GLOB SRCS "../ggml-cuda/template-instances/fattn-mma*.cu")
36
+ list(APPEND GGML_SOURCES_MUSA ${SRCS})
37
+ file(GLOB SRCS "../ggml-cuda/template-instances/mmq*.cu")
38
+ list(APPEND GGML_SOURCES_MUSA ${SRCS})
39
+
40
+ if (GGML_MUSA_MUDNN_COPY)
41
+ file(GLOB SRCS "../ggml-musa/*.cu")
42
+ list(APPEND GGML_SOURCES_MUSA ${SRCS})
43
+ add_compile_definitions(GGML_MUSA_MUDNN_COPY)
44
+ endif()
45
+
46
+ if (GGML_CUDA_FA_ALL_QUANTS)
47
+ file(GLOB SRCS "../ggml-cuda/template-instances/fattn-vec*.cu")
48
+ list(APPEND GGML_SOURCES_MUSA ${SRCS})
49
+ add_compile_definitions(GGML_CUDA_FA_ALL_QUANTS)
50
+ else()
51
+ list(APPEND GGML_SOURCES_MUSA
52
+ ../ggml-cuda/template-instances/fattn-vec-instance-f16-f16.cu
53
+ ../ggml-cuda/template-instances/fattn-vec-instance-q4_0-q4_0.cu
54
+ ../ggml-cuda/template-instances/fattn-vec-instance-q8_0-q8_0.cu
55
+ ../ggml-cuda/template-instances/fattn-vec-instance-bf16-bf16.cu)
56
+ endif()
57
+
58
+ set_source_files_properties(${GGML_SOURCES_MUSA} PROPERTIES LANGUAGE CXX)
59
+ foreach(SOURCE ${GGML_SOURCES_MUSA})
60
+ set(COMPILE_FLAGS "-Od3 -fno-strict-aliasing -ffast-math -fsigned-char -x musa -mtgpu -fmusa-flush-denormals-to-zero")
61
+ foreach(ARCH ${MUSA_ARCHITECTURES})
62
+ set(COMPILE_FLAGS "${COMPILE_FLAGS} --cuda-gpu-arch=mp_${ARCH}")
63
+ endforeach()
64
+ set_property(SOURCE ${SOURCE} PROPERTY COMPILE_FLAGS ${COMPILE_FLAGS})
65
+ endforeach()
66
+
67
+ ggml_add_backend_library(ggml-musa
68
+ ${GGML_HEADERS_MUSA}
69
+ ${GGML_SOURCES_MUSA}
70
+ )
71
+
72
+ # TODO: do not use CUDA definitions for MUSA
73
+ if (NOT GGML_BACKEND_DL)
74
+ target_compile_definitions(ggml PUBLIC GGML_USE_CUDA)
75
+ endif()
76
+
77
+ add_compile_definitions(GGML_USE_MUSA)
78
+ add_compile_definitions(GGML_CUDA_PEER_MAX_BATCH_SIZE=${GGML_CUDA_PEER_MAX_BATCH_SIZE})
79
+
80
+ if (GGML_MUSA_GRAPHS)
81
+ add_compile_definitions(GGML_MUSA_GRAPHS)
82
+ endif()
83
+
84
+ if (GGML_CUDA_FORCE_MMQ)
85
+ add_compile_definitions(GGML_CUDA_FORCE_MMQ)
86
+ endif()
87
+
88
+ if (GGML_CUDA_FORCE_CUBLAS)
89
+ add_compile_definitions(GGML_CUDA_FORCE_CUBLAS)
90
+ endif()
91
+
92
+ if (GGML_CUDA_NO_VMM)
93
+ add_compile_definitions(GGML_CUDA_NO_VMM)
94
+ endif()
95
+
96
+ if (NOT GGML_CUDA_FA)
97
+ add_compile_definitions(GGML_CUDA_NO_FA)
98
+ endif()
99
+
100
+ if (GGML_CUDA_NO_PEER_COPY)
101
+ add_compile_definitions(GGML_CUDA_NO_PEER_COPY)
102
+ endif()
103
+
104
+ if (GGML_STATIC)
105
+ target_link_libraries(ggml-musa PRIVATE MUSA::musart_static MUSA::mublas_static)
106
+ # TODO: mudnn has not provided static libraries yet
107
+ # if (GGML_MUSA_MUDNN_COPY)
108
+ # target_link_libraries(ggml-musa PRIVATE mudnn_static)
109
+ # endif()
110
+ else()
111
+ target_link_libraries(ggml-musa PRIVATE MUSA::musart MUSA::mublas)
112
+ if (GGML_MUSA_MUDNN_COPY)
113
+ target_link_libraries(ggml-musa PRIVATE mudnn)
114
+ endif()
115
+ endif()
116
+
117
+ if (GGML_CUDA_NO_VMM)
118
+ # No VMM requested, no need to link directly with the musa driver lib (libmusa.so)
119
+ else()
120
+ target_link_libraries(ggml-musa PRIVATE MUSA::musa_driver)
121
+ endif()
122
+ else()
123
+ message(FATAL_ERROR "MUSA Toolkit not found")
124
+ endif()
ggml/src/ggml-musa/mudnn.cu ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <mutex>
2
+ #include <mudnn.h>
3
+
4
+ #include "mudnn.cuh"
5
+
6
+ namespace mudnn = musa::dnn;
7
+
8
+ // Returns a human-readable error string for mudnn::Status
9
+ const char* mudnnGetErrorString(mudnn::Status err) {
10
+ switch (err) {
11
+ case mudnn::Status::SUCCESS:
12
+ return "Success";
13
+ case mudnn::Status::INVALID_PARAMETER:
14
+ return "Invalid parameter";
15
+ case mudnn::Status::NOT_INITIALIZED:
16
+ return "Not initialized";
17
+ case mudnn::Status::ALLOC_FAILED:
18
+ return "Allocation failed";
19
+ case mudnn::Status::NOT_SUPPORTED:
20
+ return "Not supported";
21
+ case mudnn::Status::INTERNAL_ERROR:
22
+ return "Internal error";
23
+ case mudnn::Status::ARCH_MISMATCH:
24
+ return "Architecture mismatch";
25
+ case mudnn::Status::EXECUTION_FAILED:
26
+ return "Execution failed";
27
+ default:
28
+ return "Unknown mudnn status";
29
+ }
30
+ }
31
+
32
+ // Error checking macro for MUDNN calls
33
+ #define MUDNN_CHECK(err) CUDA_CHECK_GEN(err, mudnn::Status::SUCCESS, mudnnGetErrorString)
34
+
35
+ namespace {
36
+ // Thread-safe cache for mudnn::Handle objects per device
37
+ std::unordered_map<int, std::unique_ptr<mudnn::Handle>> handle_cache;
38
+ std::mutex handle_cache_mutex;
39
+
40
+ mudnn::Handle* get_cached_handle(int device_id) {
41
+ std::lock_guard<std::mutex> lock(handle_cache_mutex);
42
+ auto it = handle_cache.find(device_id);
43
+ if (it != handle_cache.end()) {
44
+ return it->second.get();
45
+ }
46
+ auto handle = std::make_unique<mudnn::Handle>(device_id);
47
+ mudnn::Handle* handle_ptr = handle.get();
48
+ handle_cache[device_id] = std::move(handle);
49
+ return handle_ptr;
50
+ }
51
+ }
52
+
53
+ // Extracts dimensions and strides from a ggml_tensor
54
+ int get_ggml_dims_and_strides(const ggml_tensor* tensor,
55
+ std::vector<int64_t>& dims,
56
+ std::vector<int64_t>& strides) {
57
+ const int ndims = ggml_n_dims(tensor);
58
+ const size_t element_size = ggml_element_size(tensor);
59
+
60
+ dims.resize(ndims);
61
+ strides.resize(ndims);
62
+
63
+ for (int i = 0; i < ndims; ++i) {
64
+ dims[i] = tensor->ne[i];
65
+ strides[i] = tensor->nb[i] / static_cast<int64_t>(element_size);
66
+ }
67
+ return ndims;
68
+ }
69
+
70
+ // Converts ggml_type to mudnn::Tensor::Type
71
+ mudnn::Tensor::Type ggml_type_to_mudnn_type(ggml_type type) {
72
+ switch (type) {
73
+ case GGML_TYPE_F32:
74
+ return mudnn::Tensor::Type::FLOAT;
75
+ case GGML_TYPE_F16:
76
+ return mudnn::Tensor::Type::HALF;
77
+
78
+ // TODO: Add support for other types
79
+
80
+ default:
81
+ MUDNN_CHECK(mudnn::Status::NOT_SUPPORTED);
82
+ }
83
+
84
+ return mudnn::Tensor::Type::FLOAT; // Default fallback
85
+ }
86
+
87
+ // Asynchronous memory copy using mudnn::Unary::IDENTITY
88
+ musaError_t mudnnMemcpyAsync(ggml_backend_cuda_context& ctx, const ggml_tensor* dst, const ggml_tensor* src) {
89
+ mudnn::Tensor tensor_dst, tensor_src;
90
+
91
+ MUDNN_CHECK(tensor_dst.SetType(ggml_type_to_mudnn_type(dst->type)));
92
+ MUDNN_CHECK(tensor_src.SetType(ggml_type_to_mudnn_type(src->type)));
93
+
94
+ std::vector<int64_t> dims, strides;
95
+ const int ndims = get_ggml_dims_and_strides(src, dims, strides);
96
+
97
+ MUDNN_CHECK(tensor_dst.SetNdInfo(ndims, dims.data(), strides.data()));
98
+ MUDNN_CHECK(tensor_src.SetNdInfo(ndims, dims.data(), strides.data()));
99
+ MUDNN_CHECK(tensor_dst.SetAddr(dst->data));
100
+ MUDNN_CHECK(tensor_src.SetAddr(src->data));
101
+
102
+ mudnn::Unary op;
103
+ MUDNN_CHECK(op.SetMode(mudnn::Unary::Mode::IDENTITY));
104
+ MUDNN_CHECK(op.SetAlpha(0.0f));
105
+ MUDNN_CHECK(op.SetBeta(0.0f));
106
+
107
+ mudnn::Handle* handle = get_cached_handle(ctx.device);
108
+ MUDNN_CHECK(handle->SetStream(ctx.stream()));
109
+ MUDNN_CHECK(op.Run(*handle, tensor_dst, tensor_src));
110
+
111
+ return musaSuccess;
112
+ }
ggml/src/ggml-musa/mudnn.cuh ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include "ggml-cuda/common.cuh"
4
+ #include "ggml.h"
5
+
6
+ // Asynchronously copies data from src tensor to dst tensor using the provided context.
7
+ // Returns a musaError_t indicating success or failure.
8
+ musaError_t mudnnMemcpyAsync(
9
+ ggml_backend_cuda_context &ctx,
10
+ const ggml_tensor *dst,
11
+ const ggml_tensor *src
12
+ );
ggml/src/ggml-opencl/CMakeLists.txt ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ find_package(OpenCL REQUIRED)
2
+ find_package(Python3 REQUIRED)
3
+
4
+ set(TARGET_NAME ggml-opencl)
5
+
6
+ ggml_add_backend_library(${TARGET_NAME}
7
+ ggml-opencl.cpp
8
+ cl-program-cache.cpp
9
+ cl-program-cache.h
10
+ ../../include/ggml-opencl.h)
11
+ target_link_libraries(${TARGET_NAME} PRIVATE ${OpenCL_LIBRARIES})
12
+ target_include_directories(${TARGET_NAME} PRIVATE ${OpenCL_INCLUDE_DIRS})
13
+
14
+ if (GGML_OPENCL_PROFILING)
15
+ message(STATUS "OpenCL profiling enabled (increases CPU overhead)")
16
+ add_compile_definitions(GGML_OPENCL_PROFILING)
17
+ endif ()
18
+
19
+ add_compile_definitions(GGML_OPENCL_SOA_Q)
20
+ add_compile_definitions(GGML_OPENCL_TARGET_VERSION=${GGML_OPENCL_TARGET_VERSION})
21
+
22
+ if (GGML_OPENCL_USE_ADRENO_KERNELS)
23
+ message(STATUS "OpenCL will use matmul kernels optimized for Adreno")
24
+ add_compile_definitions(GGML_OPENCL_USE_ADRENO_KERNELS)
25
+ endif ()
26
+
27
+ if (GGML_OPENCL_EMBED_KERNELS)
28
+ add_compile_definitions(GGML_OPENCL_EMBED_KERNELS)
29
+
30
+ set(EMBED_KERNEL_SCRIPT "${CMAKE_CURRENT_SOURCE_DIR}/kernels/embed_kernel.py")
31
+ file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/autogenerated")
32
+
33
+ target_include_directories(${TARGET_NAME} PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/autogenerated")
34
+ endif ()
35
+
36
+ if (GGML_OPENCL_USE_ADRENO_BIN_KERNELS)
37
+ message(STATUS "OpenCL will use precompiled binary kernels for Adreno (improved performance on some platforms)")
38
+ add_compile_definitions(GGML_OPENCL_USE_ADRENO_BIN_KERNELS)
39
+ endif ()
40
+
41
+ function(ggml_opencl_add_kernel KNAME)
42
+ set(KERN_HDR ${CMAKE_CURRENT_BINARY_DIR}/autogenerated/${KNAME}.cl.h)
43
+ set(KERN_SRC ${CMAKE_CURRENT_SOURCE_DIR}/kernels/${KNAME}.cl)
44
+
45
+ if (GGML_OPENCL_EMBED_KERNELS)
46
+ message(STATUS "opencl: embedding kernel ${KNAME}")
47
+
48
+ # Python must be accessible from command line
49
+ add_custom_command(
50
+ OUTPUT ${KERN_HDR}
51
+ COMMAND ${Python3_EXECUTABLE} ${EMBED_KERNEL_SCRIPT} ${KERN_SRC} ${KERN_HDR}
52
+ DEPENDS ${KERN_SRC} ${EMBED_KERNEL_SCRIPT}
53
+ COMMENT "Generate ${KERN_HDR}"
54
+ )
55
+
56
+ target_sources(${TARGET_NAME} PRIVATE ${KERN_HDR})
57
+ else ()
58
+ message(STATUS "opencl: adding kernel ${KNAME}")
59
+ configure_file(${KERN_SRC} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${KNAME}.cl COPYONLY)
60
+ endif ()
61
+ endfunction()
62
+
63
+ set(GGML_OPENCL_KERNELS
64
+ add
65
+ add_id
66
+ argsort
67
+ tri
68
+ fill
69
+ clamp
70
+ cpy
71
+ cvt
72
+ diag_mask_inf
73
+ diag
74
+ div
75
+ gelu
76
+ get_rows
77
+ glu
78
+ group_norm
79
+ solve_tri
80
+ im2col_f32
81
+ im2col_f16
82
+ mean
83
+ mul_mv_f16_f16
84
+ mul_mv_f16_f32_1row
85
+ mul_mv_f16_f32_l4
86
+ mul_mv_f16_f32
87
+ mul_mv_f32_f32
88
+ mul_mv_q1_0_f32
89
+ mul_mv_q1_0_f32_flat
90
+ mul_mv_q4_0_f32
91
+ mul_mv_q4_0_f32_v
92
+ mul_mv_q4_0_f32_8x_flat
93
+ mul_mv_q4_0_f32_1d_8x_flat
94
+ mul_mv_q4_0_f32_1d_16x_flat
95
+ mul_mv_q4_1_f32
96
+ mul_mv_q4_1_f32_flat
97
+ mul_mv_q4_k_f32
98
+ mul_mv_q4_k_f32_flat
99
+ mul_mv_q5_0_f32
100
+ mul_mv_q5_0_f32_flat
101
+ mul_mv_q5_1_f32
102
+ mul_mv_q5_1_f32_flat
103
+ mul_mv_q5_k_f32
104
+ mul_mv_q5_k_f32_flat
105
+ mul_mv_q6_k_f32
106
+ mul_mv_q6_k_f32_flat
107
+ mul_mv_q8_0_f32
108
+ mul_mv_q8_0_f32_flat
109
+ mul_mv_iq4_nl_f32
110
+ mul_mv_iq4_nl_f32_flat
111
+ mul_mv_mxfp4_f32
112
+ mul_mv_mxfp4_f32_flat
113
+ mul_mv_id_q4_0_f32_8x_flat
114
+ mul_mv_id_q8_0_f32
115
+ mul_mv_id_q8_0_f32_flat
116
+ mul_mv_id_mxfp4_f32
117
+ mul_mv_id_mxfp4_f32_flat
118
+ gemm_moe_q4_0_f32_ns
119
+ gemm_moe_q4_0_q8_1_dp4a
120
+ gemv_moe_q4_0_f32_ns
121
+ gemm_moe_q8_0_f32_ns
122
+ gemm_moe_q4_1_f32_ns
123
+ gemv_moe_q4_1_f32_ns
124
+ gemm_moe_q5_0_f32_ns
125
+ gemv_moe_q5_0_f32_ns
126
+ gemm_moe_q5_1_f32_ns
127
+ gemv_moe_q5_1_f32_ns
128
+ gemm_moe_q4_k_f32_ns
129
+ gemm_moe_q4_k_q8_1_dp4a
130
+ gemm_moe_q6_k_q8_1_dp4a
131
+ gemm_moe_q8_1_dp4a
132
+ moe_reorder_quant_a_q8_1
133
+ gemm_noshuffle_q4_k_q8_1_dp4a
134
+ gemm_noshuffle_q5_k_q8_1_dp4a
135
+ gemm_noshuffle_q6_k_q8_1_dp4a
136
+ gemm_noshuffle_q8_0_q8_1_dp4a
137
+ gemm_noshuffle_q5_0_q8_1_dp4a
138
+ gemm_noshuffle_iq4_nl_q8_1_dp4a
139
+ gemm_noshuffle_q4_0_q8_1_dp4a
140
+ quant_a_q8_1
141
+ gemv_moe_q4_k_f32_ns
142
+ gemm_moe_q5_k_f32_ns
143
+ gemv_moe_q5_k_f32_ns
144
+ gemm_moe_q6_k_f32_ns
145
+ gemv_moe_q6_k_f32_ns
146
+ gemm_moe_mxfp4_f32
147
+ gemv_moe_mxfp4_f32
148
+ gemm_moe_mxfp4_f32_ns
149
+ gemm_moe_mxfp4_q8_1_dp4a
150
+ gemv_moe_mxfp4_f32_ns
151
+ moe_reorder_b
152
+ moe_combine
153
+ moe_sort_by_expert
154
+ mul_mm_f32_f32_l4_lm
155
+ mul_mm_f16_f32_l4_lm
156
+ mul_mm_q1_0_f32_l4_lm
157
+ mul_mm_q4_0_f32_l4_lm
158
+ mul_mm_q4_1_f32_l4_lm
159
+ mul_mm_q5_0_f32_l4_lm
160
+ mul_mm_q5_1_f32_l4_lm
161
+ mul_mm_q8_0_f32_l4_lm
162
+ mul_mm_iq4_nl_f32_l4_lm
163
+ mul_mm_q4_k_f32_l4_lm
164
+ mul_mm_q5_k_f32_l4_lm
165
+ mul_mm_q6_k_f32_l4_lm
166
+ gemv_noshuffle_q1_0_f32
167
+ gemm_noshuffle_q1_0_f32
168
+ gemv_noshuffle_q4_0_f32
169
+ gemv_noshuffle_q4_0_f32_spec
170
+ gemm_noshuffle_q4_0_f32
171
+ gemv_noshuffle_q4_1_f32
172
+ gemm_noshuffle_q4_1_f32
173
+ gemv_noshuffle_q5_0_f32
174
+ gemm_noshuffle_q5_0_f32
175
+ gemv_noshuffle_q5_1_f32
176
+ gemm_noshuffle_q5_1_f32
177
+ gemv_noshuffle_iq4_nl_f32
178
+ gemm_noshuffle_iq4_nl_f32
179
+ gemv_noshuffle_q8_0_f32
180
+ gemm_noshuffle_q8_0_f32
181
+ gemv_noshuffle_q4_k_f32
182
+ gemm_noshuffle_q4_k_f32
183
+ gemv_noshuffle_q6_k_f32
184
+ gemm_noshuffle_q6_k_f32
185
+ gemv_noshuffle_q5_k_f32
186
+ gemm_noshuffle_q5_k_f32
187
+ mul
188
+ neg
189
+ norm
190
+ relu
191
+ l2_norm
192
+ rms_norm
193
+ rope
194
+ scale
195
+ set_rows
196
+ sigmoid
197
+ silu
198
+ softmax_4_f32
199
+ softmax_4_f16
200
+ softmax_f32
201
+ softmax_f16
202
+ sqr
203
+ sqrt
204
+ ssm_conv
205
+ gated_delta_net
206
+ sub
207
+ sum_rows
208
+ cumsum
209
+ transpose
210
+ concat
211
+ tsembd
212
+ upscale
213
+ tanh
214
+ exp
215
+ expm1
216
+ abs
217
+ softplus
218
+ pad
219
+ repeat
220
+ mul_mat_f16_f32
221
+ mul_mm_f16_f32_kq_kqv
222
+ conv2d
223
+ conv2d_f16_f32
224
+ flash_attn_pre_f16
225
+ flash_attn_f32_f16
226
+ flash_attn_f32_q8_0
227
+ flash_attn_f32_q4_0
228
+ flash_attn_f16
229
+ flash_attn_f32
230
+ )
231
+
232
+ if (GGML_OPENCL_USE_ADRENO_KERNELS)
233
+ list(APPEND GGML_OPENCL_KERNELS gemm_xmem_f16_f32_os8)
234
+ endif ()
235
+
236
+ foreach (K ${GGML_OPENCL_KERNELS})
237
+ ggml_opencl_add_kernel(${K})
238
+ endforeach()
ggml/src/ggml-opencl/cl-program-cache.cpp ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Match the version setup ggml-opencl.cpp uses, so any cl.h declarations we
2
+ // touch are consistent across this backend's translation units.
3
+ #define CL_TARGET_OPENCL_VERSION GGML_OPENCL_TARGET_VERSION
4
+ #define CL_USE_DEPRECATED_OPENCL_1_2_APIS
5
+
6
+ #include "cl-program-cache.h"
7
+
8
+ #include "ggml-impl.h" // GGML_LOG_INFO / WARN
9
+
10
+ #include <cstdint>
11
+ #include <cstdio>
12
+ #include <cstdlib>
13
+ #include <cstring>
14
+ #include <filesystem>
15
+ #include <fstream>
16
+ #include <system_error>
17
+ #include <vector>
18
+
19
+ #if defined(_WIN32)
20
+ # ifndef WIN32_LEAN_AND_MEAN
21
+ # define WIN32_LEAN_AND_MEAN
22
+ # endif
23
+ # ifndef NOMINMAX
24
+ # define NOMINMAX
25
+ # endif
26
+ # include <windows.h>
27
+ # include <process.h>
28
+ # define ggml_getpid() ((int) GetCurrentProcessId())
29
+ #else
30
+ # include <unistd.h>
31
+ # define ggml_getpid() ((int) getpid())
32
+ #endif
33
+
34
+ namespace fs = std::filesystem;
35
+
36
+ // ----------------------------------------------------------------------------
37
+ // SHA-256 (FIPS 180-4). Self-contained, ~80 lines, public-domain reference.
38
+ // Hot path is a few KB of source per kernel ⇒ <1 ms total per process init.
39
+ // ----------------------------------------------------------------------------
40
+
41
+ namespace {
42
+
43
+ struct sha256_ctx {
44
+ uint32_t state[8];
45
+ uint64_t bitlen;
46
+ uint8_t buf[64];
47
+ size_t buf_len;
48
+ };
49
+
50
+ const uint32_t K256[64] = {
51
+ 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
52
+ 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
53
+ 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
54
+ 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
55
+ 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
56
+ 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
57
+ 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
58
+ 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2,
59
+ };
60
+
61
+ inline uint32_t rotr32(uint32_t x, unsigned n) { return (x >> n) | (x << (32 - n)); }
62
+
63
+ void sha256_compress(uint32_t state[8], const uint8_t block[64]) {
64
+ uint32_t w[64];
65
+ for (int i = 0; i < 16; ++i) {
66
+ w[i] = ((uint32_t)block[i*4 ] << 24) |
67
+ ((uint32_t)block[i*4 + 1] << 16) |
68
+ ((uint32_t)block[i*4 + 2] << 8) |
69
+ ((uint32_t)block[i*4 + 3] );
70
+ }
71
+ for (int i = 16; i < 64; ++i) {
72
+ uint32_t s0 = rotr32(w[i-15], 7) ^ rotr32(w[i-15], 18) ^ (w[i-15] >> 3);
73
+ uint32_t s1 = rotr32(w[i-2], 17) ^ rotr32(w[i-2], 19) ^ (w[i-2] >> 10);
74
+ w[i] = w[i-16] + s0 + w[i-7] + s1;
75
+ }
76
+
77
+ uint32_t a = state[0],b = state[1],c = state[2],d = state[3],e = state[4],f = state[5],g = state[6],h = state[7];
78
+
79
+ for (int i = 0; i < 64; ++i) {
80
+ uint32_t S1 = rotr32(e, 6) ^ rotr32(e, 11) ^ rotr32(e, 25);
81
+ uint32_t ch = (e & f) ^ ((~e) & g);
82
+ uint32_t t1 = h + S1 + ch + K256[i] + w[i];
83
+ uint32_t S0 = rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22);
84
+ uint32_t maj = (a & b) ^ (a & c) ^ (b & c);
85
+ uint32_t t2 = S0 + maj;
86
+ h = g; g = f; f = e; e = d + t1;
87
+ d = c; c = b; b = a; a = t1 + t2;
88
+ }
89
+ state[0]+=a; state[1]+=b; state[2]+=c; state[3]+=d;
90
+ state[4]+=e; state[5]+=f; state[6]+=g; state[7]+=h;
91
+ }
92
+
93
+ void sha256_init(sha256_ctx & c) {
94
+ c.state[0]=0x6a09e667; c.state[1]=0xbb67ae85; c.state[2]=0x3c6ef372; c.state[3]=0xa54ff53a;
95
+ c.state[4]=0x510e527f; c.state[5]=0x9b05688c; c.state[6]=0x1f83d9ab; c.state[7]=0x5be0cd19;
96
+ c.bitlen = 0;
97
+ c.buf_len = 0;
98
+ }
99
+
100
+ void sha256_update(sha256_ctx & c, const void * data, size_t len) {
101
+ const uint8_t * p = (const uint8_t *) data;
102
+ c.bitlen += (uint64_t) len * 8;
103
+ if (c.buf_len > 0) {
104
+ size_t n = 64 - c.buf_len;
105
+ if (n > len) { n = len; }
106
+ memcpy(c.buf + c.buf_len, p, n);
107
+ c.buf_len += n;
108
+ p += n;
109
+ len -= n;
110
+ if (c.buf_len == 64) {
111
+ sha256_compress(c.state, c.buf);
112
+ c.buf_len = 0;
113
+ }
114
+ }
115
+ while (len >= 64) {
116
+ sha256_compress(c.state, p);
117
+ p += 64;
118
+ len -= 64;
119
+ }
120
+ if (len > 0) {
121
+ memcpy(c.buf, p, len);
122
+ c.buf_len = len;
123
+ }
124
+ }
125
+
126
+ void sha256_final(sha256_ctx & c, uint8_t out[32]) {
127
+ uint64_t bitlen = c.bitlen;
128
+ c.buf[c.buf_len++] = 0x80;
129
+ if (c.buf_len > 56) {
130
+ while (c.buf_len < 64) { c.buf[c.buf_len++] = 0; }
131
+ sha256_compress(c.state, c.buf);
132
+ c.buf_len = 0;
133
+ }
134
+ while (c.buf_len < 56) { c.buf[c.buf_len++] = 0; }
135
+ for (int i = 7; i >= 0; --i) { c.buf[c.buf_len++] = (uint8_t) (bitlen >> (i * 8)); }
136
+ sha256_compress(c.state, c.buf);
137
+ for (int i = 0; i < 8; ++i) {
138
+ out[i*4 ] = (uint8_t) (c.state[i] >> 24);
139
+ out[i*4 + 1] = (uint8_t) (c.state[i] >> 16);
140
+ out[i*4 + 2] = (uint8_t) (c.state[i] >> 8);
141
+ out[i*4 + 3] = (uint8_t) (c.state[i] );
142
+ }
143
+ }
144
+
145
+ std::string sha256_hex(const uint8_t digest[32]) {
146
+ static const char hex[] = "0123456789abcdef";
147
+ std::string s(64, '0');
148
+ for (int i = 0; i < 32; ++i) {
149
+ s[i*2 ] = hex[digest[i] >> 4];
150
+ s[i*2 + 1] = hex[digest[i] & 0xf];
151
+ }
152
+ return s;
153
+ }
154
+
155
+ std::string compute_key(const std::string & key_suffix,
156
+ const char * source,
157
+ const std::string & compile_opts) {
158
+ sha256_ctx c;
159
+ sha256_init(c);
160
+
161
+ static const uint8_t sep = 0;
162
+ sha256_update(c, source, strlen(source));
163
+ sha256_update(c, &sep, 1);
164
+ sha256_update(c, compile_opts.data(), compile_opts.size());
165
+ sha256_update(c, &sep, 1);
166
+ sha256_update(c, key_suffix.data(), key_suffix.size());
167
+
168
+ uint8_t digest[32];
169
+ sha256_final(c, digest);
170
+ return sha256_hex(digest);
171
+ }
172
+
173
+ bool make_dir_recursive(const std::string & path) {
174
+ if (path.empty()) { return false; }
175
+ // create_directories() already creates missing parents. It returns false
176
+ // (with ec clear) when the directory is already there, so re-check.
177
+ const fs::path p = fs::u8path(path);
178
+ std::error_code ec;
179
+ if (fs::create_directories(p, ec)) { return true; }
180
+ std::error_code ec_stat;
181
+ return fs::is_directory(p, ec_stat);
182
+ }
183
+
184
+ std::string default_cache_dir() {
185
+ #if defined(_WIN32)
186
+ const char * base = std::getenv("LOCALAPPDATA");
187
+ if (!base || !*base) { base = std::getenv("APPDATA"); }
188
+ if (!base || !*base) { base = std::getenv("TEMP"); }
189
+ if (!base || !*base) { base = "."; }
190
+ return std::string(base) + "\\llama.cpp\\cl-cache";
191
+ #elif defined(__APPLE__)
192
+ const char * home = std::getenv("HOME");
193
+ if (!home || !*home) { home = "."; }
194
+ return std::string(home) + "/Library/Caches/llama.cpp/cl-cache";
195
+ #else
196
+ // The throwing overload aborts the process when no usable temp directory
197
+ // exists (e.g. Android app contexts with TMPDIR unset); an empty return
198
+ // here just disables the cache instead.
199
+ std::error_code ec;
200
+ const fs::path tmp_path = fs::temp_directory_path(ec);
201
+ if (ec || tmp_path.empty()) { return {}; }
202
+ return tmp_path.string() + "/llama.cpp/cl-cache";
203
+ #endif
204
+ }
205
+
206
+ // Query a NUL-terminated string from clGetDeviceInfo / clGetPlatformInfo.
207
+ template <typename GetInfoFn, typename Object>
208
+ std::string query_string(GetInfoFn fn, Object obj, cl_uint name) {
209
+ size_t sz = 0;
210
+ if (fn(obj, name, 0, nullptr, &sz) != CL_SUCCESS || sz == 0) {
211
+ return {};
212
+ }
213
+ std::string s(sz, '\0');
214
+ if (fn(obj, name, sz, &s[0], nullptr) != CL_SUCCESS) {
215
+ return {};
216
+ }
217
+ if (!s.empty() && s.back() == '\0') {
218
+ s.pop_back();
219
+ }
220
+ return s;
221
+ }
222
+
223
+ std::string compute_key_suffix(cl_device_id device) {
224
+ cl_platform_id platform = nullptr;
225
+ clGetDeviceInfo(device, CL_DEVICE_PLATFORM, sizeof(platform), &platform, nullptr);
226
+
227
+ std::string s;
228
+ s.reserve(512);
229
+ s += query_string(clGetDeviceInfo, device, CL_DEVICE_NAME); s.push_back('\0');
230
+ s += query_string(clGetDeviceInfo, device, CL_DRIVER_VERSION); s.push_back('\0');
231
+ s += query_string(clGetDeviceInfo, device, CL_DEVICE_VERSION); s.push_back('\0');
232
+ if (platform) {
233
+ s += query_string(clGetPlatformInfo, platform, CL_PLATFORM_VERSION); s.push_back('\0');
234
+ }
235
+ s += "fmt=" + std::to_string(CL_PROGRAM_CACHE_FORMAT_VERSION);
236
+ return s;
237
+ }
238
+
239
+ const uint8_t MAGIC[8] = { 'G','G','M','L','C','L','B','C' };
240
+
241
+ bool read_all(const std::string & path, std::vector<uint8_t> & out) {
242
+ std::ifstream f(fs::u8path(path), std::ios::binary);
243
+ if (!f) { return false; }
244
+ f.seekg(0, std::ios::end);
245
+ std::streamsize sz = f.tellg();
246
+ if (sz < 0) { return false; }
247
+ f.seekg(0, std::ios::beg);
248
+ out.resize((size_t) sz);
249
+ if (sz > 0) { f.read((char *) out.data(), sz); }
250
+ return f.good() || f.eof();
251
+ }
252
+
253
+ bool write_atomic(const std::string & path, const uint8_t * data, size_t len) {
254
+ const fs::path dst = fs::u8path(path);
255
+ const fs::path tmp = fs::u8path(path + ".tmp." + std::to_string(ggml_getpid()));
256
+ {
257
+ std::ofstream f(tmp, std::ios::binary | std::ios::trunc);
258
+ if (!f) { return false; }
259
+ f.write((const char *) data, (std::streamsize) len);
260
+ if (!f.good()) {
261
+ std::error_code ec_rm;
262
+ fs::remove(tmp, ec_rm);
263
+ return false;
264
+ }
265
+ }
266
+
267
+ std::error_code ec;
268
+ fs::rename(tmp, dst, ec);
269
+ if (ec) {
270
+ std::error_code ec_rm;
271
+ fs::remove(tmp, ec_rm);
272
+ return false;
273
+ }
274
+ return true;
275
+ }
276
+
277
+ } // namespace
278
+
279
+ static bool cache_debug_enabled() {
280
+ static int cached = -1;
281
+ if (cached < 0) {
282
+ const char * e = std::getenv("GGML_OPENCL_KERNEL_CACHE_DEBUG");
283
+ cached = (e && *e) ? 1 : 0;
284
+ }
285
+ return cached != 0;
286
+ }
287
+
288
+ static std::string opts_preview(const std::string & opts, size_t n = 120) {
289
+ if (opts.size() <= n) { return opts; }
290
+ return opts.substr(0, n) + "...";
291
+ }
292
+
293
+ // Running cache tally (diagnostic; plain ints — a benign race in the rare
294
+ // multi-threaded lazy-compile case at worst miscounts by one).
295
+ static int g_cache_hits = 0, g_cache_misses = 0, g_cache_saves = 0;
296
+
297
+ // Debug trace directly to stderr
298
+ static void cache_debug_line(const char * kind, const std::string & key,
299
+ const char * source, const std::string & opts) {
300
+ if (!cache_debug_enabled()) { return; }
301
+ fprintf(stderr, "ggml_opencl: cache %-4s [h=%d m=%d s=%d] key=%s src=%zuB opts='%s'\n",
302
+ kind, g_cache_hits, g_cache_misses, g_cache_saves,
303
+ key.substr(0, 16).c_str(), strlen(source), opts_preview(opts).c_str());
304
+ fflush(stderr);
305
+ }
306
+
307
+ cl_program_cache_state cl_program_cache_init(cl_device_id device) {
308
+ cl_program_cache_state st;
309
+
310
+ const char * env = std::getenv("GGML_OPENCL_KERNEL_CACHE_DIR");
311
+ if (env && (!std::strcmp(env, "0") || !std::strcmp(env, "off") ||
312
+ !std::strcmp(env, "none") || !std::strcmp(env, "disable") ||
313
+ !std::strcmp(env, "disabled"))) {
314
+ if (cache_debug_enabled()) {
315
+ fprintf(stderr, "ggml_opencl: kernel cache disabled by GGML_OPENCL_KERNEL_CACHE_DIR=%s\n", env);
316
+ fflush(stderr);
317
+ }
318
+ return st;
319
+ }
320
+
321
+ std::string dir;
322
+ if (!env || !*env || !std::strcmp(env, "1") || !std::strcmp(env, "default")) {
323
+ dir = default_cache_dir();
324
+ if (dir.empty()) {
325
+ GGML_LOG_INFO("ggml_opencl: kernel cache disabled (no usable default cache directory)\n");
326
+ return st;
327
+ }
328
+ } else {
329
+ dir = env;
330
+ }
331
+
332
+ if (!make_dir_recursive(dir)) {
333
+ GGML_LOG_INFO("ggml_opencl: kernel cache disabled (cannot create directory '%s')\n", dir.c_str());
334
+ return st;
335
+ }
336
+
337
+ st.dir = dir;
338
+ st.key_suffix = compute_key_suffix(device);
339
+ GGML_LOG_INFO("ggml_opencl: kernel cache enabled at '%s'\n", st.dir.c_str());
340
+ if (cache_debug_enabled()) {
341
+ fprintf(stderr, "ggml_opencl: kernel cache enabled at '%s' "
342
+ "(GGML_OPENCL_KERNEL_CACHE_DIR=off to disable)\n", st.dir.c_str());
343
+ fflush(stderr);
344
+ }
345
+ return st;
346
+ }
347
+
348
+ cl_program cl_program_cache_try_load(
349
+ const cl_program_cache_state & state,
350
+ cl_context context,
351
+ cl_device_id device,
352
+ const char * source,
353
+ const std::string & compile_opts) {
354
+
355
+ if (state.dir.empty() || !source) { return nullptr; }
356
+
357
+ const std::string key = compute_key(state.key_suffix, source, compile_opts);
358
+ const std::string path = state.dir + "/" + key + ".clbin";
359
+
360
+ std::vector<uint8_t> file;
361
+ if (!read_all(path, file)) {
362
+ ++g_cache_misses;
363
+ cache_debug_line("MISS", key, source, compile_opts);
364
+ return nullptr;
365
+ }
366
+ if (file.size() < 16 || std::memcmp(file.data(), MAGIC, 8) != 0) { return nullptr; }
367
+
368
+ uint32_t fmt =
369
+ ((uint32_t) file[ 8]) | ((uint32_t) file[ 9] << 8) |
370
+ ((uint32_t) file[10] << 16) | ((uint32_t) file[11] << 24);
371
+ if (fmt != CL_PROGRAM_CACHE_FORMAT_VERSION) { return nullptr; }
372
+
373
+ const size_t hdr_len = 16;
374
+ const unsigned char * bin = file.data() + hdr_len;
375
+ const size_t bin_len = file.size() - hdr_len;
376
+
377
+ cl_int err = CL_SUCCESS;
378
+ cl_int bin_err = CL_SUCCESS;
379
+ cl_program p = clCreateProgramWithBinary(context, 1, &device, &bin_len, &bin, &bin_err, &err);
380
+ if (err != CL_SUCCESS || bin_err != CL_SUCCESS || p == nullptr) {
381
+ if (p) { clReleaseProgram(p); }
382
+ return nullptr;
383
+ }
384
+
385
+ err = clBuildProgram(p, 0, nullptr, compile_opts.c_str(), nullptr, nullptr);
386
+ if (err != CL_SUCCESS) {
387
+ clReleaseProgram(p);
388
+ return nullptr;
389
+ }
390
+ ++g_cache_hits;
391
+ cache_debug_line("HIT", key, source, compile_opts);
392
+ return p;
393
+ }
394
+
395
+ void cl_program_cache_try_save(
396
+ const cl_program_cache_state & state,
397
+ cl_program program,
398
+ cl_device_id /*device*/,
399
+ const char * source,
400
+ const std::string & compile_opts) {
401
+
402
+ if (state.dir.empty() || !program || !source) {
403
+ return;
404
+ }
405
+
406
+ cl_uint n_dev = 0;
407
+ if (clGetProgramInfo(program, CL_PROGRAM_NUM_DEVICES, sizeof(n_dev), &n_dev, nullptr) != CL_SUCCESS || n_dev == 0) {
408
+ return;
409
+ }
410
+
411
+ std::vector<size_t> sizes(n_dev);
412
+ if (clGetProgramInfo(program, CL_PROGRAM_BINARY_SIZES, sizeof(size_t) * n_dev, sizes.data(), nullptr) != CL_SUCCESS) {
413
+ return;
414
+ }
415
+ if (sizes.empty() || sizes[0] == 0) {
416
+ return;
417
+ }
418
+
419
+ std::vector<std::vector<uint8_t>> binaries(n_dev);
420
+ std::vector<unsigned char *> bin_ptrs(n_dev);
421
+ for (cl_uint i = 0; i < n_dev; ++i) {
422
+ binaries[i].resize(sizes[i]);
423
+ bin_ptrs[i] = binaries[i].data();
424
+ }
425
+ if (clGetProgramInfo(program, CL_PROGRAM_BINARIES, sizeof(unsigned char *) * n_dev, bin_ptrs.data(), nullptr) != CL_SUCCESS) {
426
+ return;
427
+ }
428
+
429
+ // We only care about the first device's binary — that's the one we'd
430
+ // re-load with on a future cache hit. Multi-device contexts aren't a
431
+ // pattern this backend uses today.
432
+ const std::vector<uint8_t> & bin = binaries[0];
433
+
434
+ std::vector<uint8_t> file;
435
+ file.reserve(16 + bin.size());
436
+ file.insert(file.end(), MAGIC, MAGIC + 8);
437
+ uint32_t fmt = CL_PROGRAM_CACHE_FORMAT_VERSION;
438
+ file.push_back((uint8_t) (fmt & 0xff));
439
+ file.push_back((uint8_t) ((fmt >> 8) & 0xff));
440
+ file.push_back((uint8_t) ((fmt >> 16) & 0xff));
441
+ file.push_back((uint8_t) ((fmt >> 24) & 0xff));
442
+ file.push_back(0); file.push_back(0); file.push_back(0); file.push_back(0); // reserved
443
+ file.insert(file.end(), bin.begin(), bin.end());
444
+
445
+ const std::string key = compute_key(state.key_suffix, source, compile_opts);
446
+ const std::string path = state.dir + "/" + key + ".clbin";
447
+ if (!write_atomic(path, file.data(), file.size())) {
448
+ GGML_LOG_INFO("ggml_opencl: kernel cache: failed to write '%s'\n", path.c_str());
449
+ } else {
450
+ ++g_cache_saves;
451
+ cache_debug_line("SAVE", key, source, compile_opts);
452
+ }
453
+ }
ggml/src/ggml-opencl/cl-program-cache.h ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // On-disk cache for OpenCL cl_program binaries. Lets a fresh process skip the
2
+ // expensive clBuildProgram-from-source step when a binary for the exact same
3
+ // (source, compile options, device, driver, platform) was previously saved.
4
+ //
5
+ // Activation: default on via GGML_OPENCL_KERNEL_CACHE_DIR:
6
+ // unset / empty / "1" / "default" : platform default cache dir
7
+ // (%LOCALAPPDATA%\llama.cpp\cl-cache,
8
+ // ~/Library/Caches/llama.cpp/cl-cache,
9
+ // <temp dir>/llama.cpp/cl-cache elsewhere)
10
+ // "0" / "off" / "none" / "disable(d)" : disabled (all functions no-op)
11
+ // any other value : used verbatim as the cache path
12
+ // If the chosen directory cannot be created/used, the cache silently disables
13
+ // itself for the process and falls back to source compile.
14
+ // GGML_OPENCL_KERNEL_CACHE_DEBUG=1 prints a HIT/MISS/SAVE trace (with a running
15
+ // tally) straight to stderr — visible even in tools that filter INFO/WARN logs;
16
+ // redirect stderr to record it.
17
+ //
18
+ // Cache key (SHA-256 hex):
19
+ // sha256(source_bytes || '\x00' ||
20
+ // compile_opts || '\x00' ||
21
+ // CL_DEVICE_NAME || '\x00' ||
22
+ // CL_DRIVER_VERSION || '\x00' ||
23
+ // CL_PLATFORM_VERSION || '\x00' ||
24
+ // CL_PROGRAM_CACHE_FORMAT_VERSION)
25
+ //
26
+ // The key fully captures everything that can affect the produced binary,
27
+ // without needing the host source revision (a kernel source change shows up
28
+ // in source_bytes; a compile-option change shows up in compile_opts).
29
+ //
30
+ // File layout per cache entry: <cache_dir>/<sha256-hex>.clbin
31
+ // bytes [0..7] : magic "GGMLCLBC"
32
+ // bytes [8..11] : uint32_t format version (CL_PROGRAM_CACHE_FORMAT_VERSION)
33
+ // bytes [12..15] : uint32_t reserved (0)
34
+ // bytes [16..] : raw cl_program binary as returned by
35
+ // clGetProgramInfo(CL_PROGRAM_BINARIES)
36
+ //
37
+ // Concurrency: writes go to <name>.tmp.<pid> then atomic rename. On race,
38
+ // last-writer-wins. No locks.
39
+
40
+ #pragma once
41
+
42
+ #include <CL/cl.h>
43
+ #include <string>
44
+
45
+ // Bumped manually if host-side OpenCL API usage changes in a way that
46
+ // affects compile semantics but does not show up in source_bytes /
47
+ // compile_opts (e.g. switching from clCreateProgramWithSource to
48
+ // clCompileProgram + clLinkProgram, or changing how multiple sources
49
+ // are concatenated). Most commits — including kernel changes — do NOT
50
+ // require bumping this; the source bytes already capture those.
51
+ #define CL_PROGRAM_CACHE_FORMAT_VERSION 1u
52
+
53
+ struct cl_program_cache_state {
54
+ // Empty string means cache is disabled.
55
+ std::string dir;
56
+ // Concatenated device/driver/platform identity + cache format version,
57
+ // computed once at init and folded into every key.
58
+ std::string key_suffix;
59
+ };
60
+
61
+ cl_program_cache_state cl_program_cache_init(cl_device_id device);
62
+
63
+ cl_program cl_program_cache_try_load(
64
+ const cl_program_cache_state & state,
65
+ cl_context context,
66
+ cl_device_id device,
67
+ const char * source,
68
+ const std::string & compile_opts);
69
+
70
+ void cl_program_cache_try_save(
71
+ const cl_program_cache_state & state,
72
+ cl_program program,
73
+ cl_device_id device,
74
+ const char * source,
75
+ const std::string & compile_opts);
ggml/src/ggml-opencl/fa_tune.h ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // Flash-attention per-(dk,dv) tile tuning for the Adreno OpenCL backend.
4
+ // Isolated from ggml-opencl.cpp so the tuning numbers are easy to find and
5
+ // edit; the FA dispatch and kernel-compile logic stay in the main file.
6
+ // This header is a file section — it is #included exactly once, at the point
7
+ // in ggml-opencl.cpp where the ggml logging macros are already in scope.
8
+
9
+ // Per-(dk, dv) FA config; shared by dispatch and supports_op.
10
+ struct ggml_opencl_fa_dim {
11
+ int dk; int dv; int bm; int bn; int n_split; int nkv_split_threshold;
12
+ };
13
+
14
+ // Split variant fires when n_kv >= threshold (threshold=0 -> always split).
15
+ // Default tuning covers Adreno 7xx/8xx mobile and X1-series laptop GPUs.
16
+ static const ggml_opencl_fa_dim g_fa_dims_adreno_default[] = {
17
+ { 40, 40, 64, 32, 1, 0}, { 64, 64, 64, 32, 2, 64},
18
+ { 80, 80, 64, 32, 2, 64}, { 96, 96, 64, 32, 2, 64},
19
+ {112, 112, 64, 32, 2, 64}, {128, 128, 64, 32, 2, 64},
20
+ {192, 128, 16, 16, 1, 0},
21
+ {192, 192, 16, 16, 1, 0},
22
+ {256, 256, 16, 16, 16, 0},
23
+ {512, 512, 8, 16, 64, 0},
24
+ };
25
+
26
+ struct ggml_opencl_fa_dim_table {
27
+ const ggml_opencl_fa_dim * data;
28
+ size_t count;
29
+
30
+ const ggml_opencl_fa_dim * begin() const { return data; }
31
+ const ggml_opencl_fa_dim * end() const { return data + count; }
32
+ };
33
+
34
+ // Mutable copy of the active table; GGML_OPENCL_FA_TUNE patches entries here
35
+ // at backend init without touching the const source table.
36
+ static ggml_opencl_fa_dim g_fa_dims_runtime[
37
+ sizeof(g_fa_dims_adreno_default) / sizeof(g_fa_dims_adreno_default[0])];
38
+
39
+ static ggml_opencl_fa_dim_table g_opencl_fa_dims = {
40
+ g_fa_dims_adreno_default,
41
+ sizeof(g_fa_dims_adreno_default) / sizeof(g_fa_dims_adreno_default[0]),
42
+ };
43
+
44
+ // GGML_OPENCL_FA_TUNE=dk:dv:bm:bn:nsplit:thr[,…] — patches matching entries
45
+ // in the active table at backend init, before the first FA kernel compiles.
46
+ // Unmatched (dk,dv) pairs are warned and ignored.
47
+ static void ggml_opencl_fa_apply_env_overrides() {
48
+ const char * e = std::getenv("GGML_OPENCL_FA_TUNE");
49
+ if (!e || !e[0]) {
50
+ return;
51
+ }
52
+
53
+ std::string s = e;
54
+ size_t pos = 0;
55
+ while (pos < s.size()) {
56
+ size_t comma = s.find(',', pos);
57
+ std::string entry = s.substr(pos, comma == std::string::npos ? std::string::npos : comma - pos);
58
+ int dk, dv, bm, bn, nsplit, thr;
59
+ if (std::sscanf(entry.c_str(), "%d:%d:%d:%d:%d:%d", &dk, &dv, &bm, &bn, &nsplit, &thr) == 6) {
60
+ bool patched = false;
61
+ for (size_t i = 0; i < g_opencl_fa_dims.count; ++i) {
62
+ ggml_opencl_fa_dim & d = g_fa_dims_runtime[i];
63
+ if (d.dk == dk && d.dv == dv) {
64
+ d.bm = bm; d.bn = bn; d.n_split = nsplit; d.nkv_split_threshold = thr;
65
+ GGML_LOG_INFO("ggml_opencl: FA tune override DK=%d DV=%d -> bm=%d bn=%d n_split=%d thr=%d\n",
66
+ dk, dv, bm, bn, nsplit, thr);
67
+ patched = true;
68
+ break;
69
+ }
70
+ }
71
+ if (!patched) {
72
+ GGML_LOG_WARN("ggml_opencl: FA tune override DK=%d DV=%d ignored (no matching dim)\n", dk, dv);
73
+ }
74
+ } else {
75
+ GGML_LOG_WARN("ggml_opencl: FA tune override entry malformed: '%s'\n", entry.c_str());
76
+ }
77
+ if (comma == std::string::npos) break;
78
+ pos = comma + 1;
79
+ }
80
+ }
81
+
82
+ // Copy the default table into the mutable runtime buffer and apply any
83
+ // GGML_OPENCL_FA_TUNE overrides. A per-generation table can be added here
84
+ // once it has been tuned on hardware.
85
+ static void ggml_cl_init_fa_dims_table() {
86
+ const size_t count = sizeof(g_fa_dims_adreno_default) / sizeof(g_fa_dims_adreno_default[0]);
87
+ for (size_t i = 0; i < count; ++i) {
88
+ g_fa_dims_runtime[i] = g_fa_dims_adreno_default[i];
89
+ }
90
+ g_opencl_fa_dims = { g_fa_dims_runtime, count };
91
+ ggml_opencl_fa_apply_env_overrides();
92
+ }
ggml/src/ggml-opencl/ggml-opencl.cpp ADDED
The diff for this file is too large to render. See raw diff
 
ggml/src/ggml-opencl/kernels/abs.cl ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+
3
+ //------------------------------------------------------------------------------
4
+ // abs
5
+ //------------------------------------------------------------------------------
6
+
7
+ kernel void kernel_abs_f32(
8
+ global const float * src0,
9
+ ulong offset0,
10
+ global float * dst,
11
+ ulong offsetd
12
+ ) {
13
+ src0 = (global float*)((global char*)src0 + offset0);
14
+ dst = (global float*)((global char*)dst + offsetd);
15
+
16
+ dst[get_global_id(0)] = fabs(src0[get_global_id(0)]);
17
+ }
18
+
19
+ kernel void kernel_abs_f32_4(
20
+ global const float4 * src0,
21
+ ulong offset0,
22
+ global float4 * dst,
23
+ ulong offsetd
24
+ ) {
25
+ src0 = (global float4*)((global char*)src0 + offset0);
26
+ dst = (global float4*)((global char*)dst + offsetd);
27
+
28
+ dst[get_global_id(0)] = fabs(src0[get_global_id(0)]);
29
+ }
30
+
31
+ kernel void kernel_abs_f16(
32
+ global const half * src0,
33
+ ulong offset0,
34
+ global half * dst,
35
+ ulong offsetd
36
+ ) {
37
+ src0 = (global half*)((global char*)src0 + offset0);
38
+ dst = (global half*)((global char*)dst + offsetd);
39
+
40
+ dst[get_global_id(0)] = fabs(src0[get_global_id(0)]);
41
+ }
42
+
43
+ kernel void kernel_abs_f16_4(
44
+ global const half4 * src0,
45
+ ulong offset0,
46
+ global half4 * dst,
47
+ ulong offsetd
48
+ ) {
49
+ src0 = (global half4*)((global char*)src0 + offset0);
50
+ dst = (global half4*)((global char*)dst + offsetd);
51
+
52
+ dst[get_global_id(0)] = fabs(src0[get_global_id(0)]);
53
+ }
54
+
55
+ kernel void kernel_abs_f32_nc(
56
+ global const char * src0,
57
+ ulong offset0,
58
+ global char * dst,
59
+ ulong offsetd,
60
+ int ne00,
61
+ ulong nb00,
62
+ ulong nb01,
63
+ ulong nb02,
64
+ ulong nb03,
65
+ ulong nb0,
66
+ ulong nb1,
67
+ ulong nb2,
68
+ ulong nb3
69
+ ) {
70
+ src0 = src0 + offset0;
71
+ dst = dst + offsetd;
72
+
73
+ const int i3 = get_group_id(2);
74
+ const int i2 = get_group_id(1);
75
+ const int i1 = get_group_id(0);
76
+
77
+ for (int i0 = get_local_id(0); i0 < ne00; i0 += get_local_size(0)) {
78
+ global const float * x = (global const float *)(src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
79
+ global float * y = (global float *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
80
+
81
+ *y = fabs(*x);
82
+ }
83
+ }
84
+
85
+ kernel void kernel_abs_f16_nc(
86
+ global const char * src0,
87
+ ulong offset0,
88
+ global char * dst,
89
+ ulong offsetd,
90
+ int ne00,
91
+ ulong nb00,
92
+ ulong nb01,
93
+ ulong nb02,
94
+ ulong nb03,
95
+ ulong nb0,
96
+ ulong nb1,
97
+ ulong nb2,
98
+ ulong nb3
99
+ ) {
100
+ src0 = src0 + offset0;
101
+ dst = dst + offsetd;
102
+
103
+ const int i3 = get_group_id(2);
104
+ const int i2 = get_group_id(1);
105
+ const int i1 = get_group_id(0);
106
+
107
+ for (int i0 = get_local_id(0); i0 < ne00; i0 += get_local_size(0)) {
108
+ global const half * x = (global const half *)(src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
109
+ global half * y = (global half *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
110
+
111
+ *y = fabs(*x);
112
+ }
113
+ }
ggml/src/ggml-opencl/kernels/add.cl ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+
3
+ //------------------------------------------------------------------------------
4
+ // add
5
+ //------------------------------------------------------------------------------
6
+
7
+ // general-purpose kernel for addition of two tensors
8
+ // pros: works for non-contiguous tensors, supports broadcast across dims 1, 2 and 3
9
+ // cons: not very efficient
10
+ kernel void kernel_add(
11
+ global char * src0,
12
+ ulong offset0,
13
+ global char * src1,
14
+ ulong offset1,
15
+ global char * dst,
16
+ ulong offsetd,
17
+ int ne00,
18
+ int ne01,
19
+ int ne02,
20
+ int ne03,
21
+ ulong nb00,
22
+ ulong nb01,
23
+ ulong nb02,
24
+ ulong nb03,
25
+ int ne10,
26
+ int ne11,
27
+ int ne12,
28
+ int ne13,
29
+ ulong nb10,
30
+ ulong nb11,
31
+ ulong nb12,
32
+ ulong nb13,
33
+ int ne0,
34
+ int ne1,
35
+ int ne2,
36
+ int ne3,
37
+ ulong nb0,
38
+ ulong nb1,
39
+ ulong nb2,
40
+ ulong nb3
41
+ ) {
42
+ src0 = src0 + offset0;
43
+ src1 = src1 + offset1;
44
+ dst = dst + offsetd;
45
+
46
+ int i03 = get_group_id(2);
47
+ int i02 = get_group_id(1);
48
+ int i01 = get_group_id(0);
49
+
50
+ int i13 = i03 % ne13;
51
+ int i12 = i02 % ne12;
52
+ int i11 = i01 % ne11;
53
+
54
+ global char * src0_ptr = src0 + i03*nb03 + i02*nb02 + i01*nb01;
55
+ global char * src1_ptr = src1 + i13*nb13 + i12*nb12 + i11*nb11;
56
+ global char * dst_ptr = dst + i03*nb3 + i02*nb2 + i01*nb1;
57
+
58
+ for (int i0 = get_local_id(0); i0 < ne0; i0 += get_local_size(0)) {
59
+ const int i10 = i0 % ne10;
60
+ *((global float *)(dst_ptr + i0*nb0)) = *((global float *)(src0_ptr + i0*nb00)) + *((global float *)(src1_ptr + i10*nb10));
61
+ }
62
+ }
63
+
64
+ // assumption: src1 is a row
65
+ // broadcast src1 into src0
66
+ kernel void kernel_add_row(
67
+ global float4 * src0,
68
+ ulong offset0,
69
+ global float4 * src1,
70
+ ulong offset1,
71
+ global float4 * dst,
72
+ ulong offsetd,
73
+ int ne
74
+ ) {
75
+ src0 = (global float4*)((global char*)src0 + offset0);
76
+ src1 = (global float4*)((global char*)src1 + offset1);
77
+ dst = (global float4*)((global char*)dst + offsetd);
78
+
79
+ // This performs better than using %.
80
+ uint gid = get_global_id(0);
81
+ uint idx1 = gid - (gid/ne)*ne; // get_global_id(0) % ne
82
+ dst[gid] = src0[gid] + src1[idx1];
83
+ }
84
+
85
+ kernel void kernel_add_f16(
86
+ global char * src0,
87
+ ulong offset0,
88
+ global char * src1,
89
+ ulong offset1,
90
+ global char * dst,
91
+ ulong offsetd,
92
+ int ne00,
93
+ int ne01,
94
+ int ne02,
95
+ int ne03,
96
+ ulong nb00,
97
+ ulong nb01,
98
+ ulong nb02,
99
+ ulong nb03,
100
+ int ne10,
101
+ int ne11,
102
+ int ne12,
103
+ int ne13,
104
+ ulong nb10,
105
+ ulong nb11,
106
+ ulong nb12,
107
+ ulong nb13,
108
+ int ne0,
109
+ int ne1,
110
+ int ne2,
111
+ int ne3,
112
+ ulong nb0,
113
+ ulong nb1,
114
+ ulong nb2,
115
+ ulong nb3,
116
+ int type_src0,
117
+ int type_src1
118
+ ) {
119
+ src0 = src0 + offset0;
120
+ src1 = src1 + offset1;
121
+ dst = dst + offsetd;
122
+
123
+ int i03 = get_group_id(2);
124
+ int i02 = get_group_id(1);
125
+ int i01 = get_group_id(0);
126
+
127
+ int i13 = i03 % ne13;
128
+ int i12 = i02 % ne12;
129
+ int i11 = i01 % ne11;
130
+
131
+ global char * src0_ptr = src0 + i03*nb03 + i02*nb02 + i01*nb01;
132
+ global char * src1_ptr = src1 + i13*nb13 + i12*nb12 + i11*nb11;
133
+ global char * dst_ptr = dst + i03*nb3 + i02*nb2 + i01*nb1;
134
+
135
+ for (int i0 = get_local_id(0); i0 < ne0; i0 += get_local_size(0)) {
136
+ const int i10 = i0 % ne10;
137
+
138
+ half v0, v1;
139
+ if (type_src0 == 1) {
140
+ v0 = convert_half(*((global float *)(src0_ptr + i0*nb00)));
141
+ } else {
142
+ v0 = *((global half *)(src0_ptr + i0*nb00));
143
+ }
144
+
145
+ if (type_src1 == 1) {
146
+ v1 = convert_half(*((global float *)(src1_ptr + i10*nb10)));
147
+ } else {
148
+ v1 = *((global half *)(src1_ptr + i10*nb10));
149
+ }
150
+
151
+ *((global half *)(dst_ptr + i0*nb0)) = v0 + v1;
152
+ }
153
+ }
154
+
155
+ kernel void kernel_add_row_f16(
156
+ global char * src0,
157
+ ulong offset0,
158
+ global char * src1,
159
+ ulong offset1,
160
+ global half4 * dst,
161
+ ulong offsetd,
162
+ int ne,
163
+ int type_src0,
164
+ int type_src1
165
+ ) {
166
+ dst = (global half4*)((global char*)dst + offsetd);
167
+
168
+ // This performs better than using %.
169
+ uint gid = get_global_id(0);
170
+ uint idx1 = gid - (gid/ne)*ne; // get_global_id(0) % ne
171
+
172
+ half4 v0, v1;
173
+ if (type_src0 == 1) {
174
+ global float4* src0_f32 = (global float4*)((global char*)src0 + offset0);
175
+ v0 = convert_half4(src0_f32[gid]);
176
+ } else {
177
+ global half4* src0_f16 = (global half4*)((global char*)src0 + offset0);
178
+ v0 = src0_f16[gid];
179
+ }
180
+
181
+ if (type_src1 == 1) {
182
+ global float4* src1_f32 = (global float4*)((global char*)src1 + offset1);
183
+ v1 = convert_half4(src1_f32[idx1]);
184
+ } else {
185
+ global half4* src1_f16 = (global half4*)((global char*)src1 + offset1);
186
+ v1 = src1_f16[idx1];
187
+ }
188
+
189
+ dst[gid] = v0 + v1;
190
+ }
ggml/src/ggml-opencl/kernels/add_id.cl ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+
3
+ //------------------------------------------------------------------------------
4
+ // add_id
5
+ //------------------------------------------------------------------------------
6
+ kernel void kernel_add_id(
7
+ global char * src0,
8
+ ulong offset0,
9
+ global char * src1,
10
+ ulong offset1,
11
+ global char * src2,
12
+ ulong offset2,
13
+ global char * dst,
14
+ ulong offsetd,
15
+ ulong nb01,
16
+ ulong nb02,
17
+ ulong nb11,
18
+ ulong nb21,
19
+ int ne0,
20
+ int ne1
21
+ ) {
22
+ src0 = (global char*)((global char*)src0 + offset0);
23
+ src1 = (global char*)((global char*)src1 + offset1);
24
+ src2 = (global char*)((global char*)src2 + offset2);
25
+ dst = (global char*)((global char*)dst + offsetd);
26
+
27
+ int i1 = get_group_id(0);
28
+ int i2 = get_group_id(1);
29
+
30
+ const int i11 = *((global const int *) (src2 + i1*sizeof(int) + i2*nb21));
31
+
32
+ const size_t nb1 = ne0 * sizeof(float);
33
+ const size_t nb2 = ne1 * nb1;
34
+
35
+ global float * dst_row = (global float *)((global char *)dst + i1*nb1 + i2*nb2);
36
+ global float * src0_row = (global float *)((global char *)src0 + i1*nb01 + i2*nb02);
37
+ global float * src1_row = (global float *)((global char *)src1 + i11*nb11);
38
+
39
+ for (int i0 = get_local_id(0); i0 < ne0; i0 += get_local_size(0)) {
40
+ dst_row[i0] = src0_row[i0] + src1_row[i0];
41
+ }
42
+ }
ggml/src/ggml-opencl/kernels/argsort.cl ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+
3
+ #ifdef cl_intel_subgroups
4
+ #pragma OPENCL EXTENSION cl_intel_subgroups : enable
5
+ #else
6
+ #pragma OPENCL EXTENSION cl_khr_subgroups : enable
7
+ #endif
8
+
9
+ #ifdef cl_intel_required_subgroup_size
10
+ #pragma OPENCL EXTENSION cl_intel_required_subgroup_size : enable
11
+ #define INTEL_GPU 1
12
+ #define REQD_SUBGROUP_SIZE_16 __attribute__((intel_reqd_sub_group_size(16)))
13
+ #define REQD_SUBGROUP_SIZE_32 __attribute__((intel_reqd_sub_group_size(32)))
14
+ #elif defined(cl_qcom_reqd_sub_group_size)
15
+ #pragma OPENCL EXTENSION cl_qcom_reqd_sub_group_size : enable
16
+ #define ADRENO_GPU 1
17
+ #define REQD_SUBGROUP_SIZE_64 __attribute__((qcom_reqd_sub_group_size("half")))
18
+ #define REQD_SUBGROUP_SIZE_128 __attribute__((qcom_reqd_sub_group_size("full")))
19
+ #endif
20
+
21
+ #define SWAP(x, y, T) { T tmp = (x); (x) = (y); (y) = tmp; }
22
+
23
+ enum ggml_sort_order {
24
+ GGML_SORT_ORDER_ASC,
25
+ GGML_SORT_ORDER_DESC,
26
+ };
27
+
28
+ kernel void kernel_argsort_f32_i32(
29
+ global float * src0,
30
+ ulong offset0,
31
+ global int * dst,
32
+ ulong offsetd,
33
+ const int ne00,
34
+ const int ne00_pad,
35
+ const int order,
36
+ local int * dst_row
37
+ ) {
38
+ // bitonic sort
39
+ int col = get_local_id(0);
40
+ int row = get_group_id(1);
41
+
42
+ if (col >= ne00_pad) {
43
+ return;
44
+ }
45
+
46
+ src0 = (global char *)((global char *)src0 + offset0);
47
+ dst = (global float *)((global char *)dst + offsetd);
48
+
49
+ global float * x_row = src0 + row * ne00;
50
+
51
+ // initialize indices
52
+ dst_row[col] = col;
53
+
54
+ barrier(CLK_LOCAL_MEM_FENCE);
55
+
56
+ for (int k = 2; k <= ne00_pad; k *= 2) {
57
+ for (int j = k / 2; j > 0; j /= 2) {
58
+ int ixj = col ^ j;
59
+ if (ixj > col) {
60
+ if ((col & k) == 0) {
61
+ if (dst_row[col] >= ne00 ||
62
+ (dst_row[ixj] < ne00 && (order == GGML_SORT_ORDER_ASC ?
63
+ x_row[dst_row[col]] > x_row[dst_row[ixj]] :
64
+ x_row[dst_row[col]] < x_row[dst_row[ixj]]))
65
+ ) {
66
+ SWAP(dst_row[col], dst_row[ixj], int);
67
+ }
68
+ } else {
69
+ if (dst_row[ixj] >= ne00 ||
70
+ (dst_row[col] < ne00 && (order == GGML_SORT_ORDER_ASC ?
71
+ x_row[dst_row[col]] < x_row[dst_row[ixj]] :
72
+ x_row[dst_row[col]] > x_row[dst_row[ixj]]))
73
+ ) {
74
+ SWAP(dst_row[col], dst_row[ixj], int);
75
+ }
76
+ }
77
+ }
78
+ barrier(CLK_LOCAL_MEM_FENCE);
79
+ }
80
+ }
81
+
82
+ // copy the result to dst without the padding
83
+ if (col < ne00) {
84
+ dst[row * ne00 + col] = dst_row[col];
85
+ }
86
+ }
ggml/src/ggml-opencl/kernels/clamp.cl ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+
3
+ //------------------------------------------------------------------------------
4
+ // clamp
5
+ //------------------------------------------------------------------------------
6
+ kernel void kernel_clamp(
7
+ global float * src0,
8
+ ulong offset0,
9
+ global float * dst,
10
+ ulong offsetd,
11
+ float min,
12
+ float max
13
+ ) {
14
+ src0 = (global float*)((global char*)src0 + offset0);
15
+ dst = (global float*)((global char*)dst + offsetd);
16
+
17
+ dst[get_global_id(0)] = src0[get_global_id(0)] < min ?
18
+ min :
19
+ (src0[get_global_id(0)] > max ? max : src0[get_global_id(0)]);
20
+ }
ggml/src/ggml-opencl/kernels/concat.cl ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ kernel void kernel_concat_f32(
2
+ global const char * src0,
3
+ ulong offset0,
4
+ global const char * src1,
5
+ ulong offset1,
6
+ global char * dst,
7
+ ulong offsetd,
8
+ int ne00,
9
+ int ne01,
10
+ int ne02,
11
+ int ne03,
12
+ ulong nb00,
13
+ ulong nb01,
14
+ ulong nb02,
15
+ ulong nb03,
16
+ ulong nb10,
17
+ ulong nb11,
18
+ ulong nb12,
19
+ ulong nb13,
20
+ int ne0,
21
+ ulong nb0,
22
+ ulong nb1,
23
+ ulong nb2,
24
+ ulong nb3,
25
+ int dim
26
+ ) {
27
+ src0 = src0 + offset0;
28
+ src1 = src1 + offset1;
29
+ dst = dst + offsetd;
30
+
31
+ const int i3 = get_group_id(2);
32
+ const int i2 = get_group_id(1);
33
+ const int i1 = get_group_id(0);
34
+
35
+ int o[4] = {0, 0, 0, 0};
36
+ o[dim] = dim == 0 ? ne00 : (dim == 1 ? ne01 : (dim == 2 ? ne02 : ne03));
37
+
38
+ global const float * x;
39
+
40
+ for (int i0 = get_local_id(0); i0 < ne0; i0 += get_local_size(0)) {
41
+ if (i0 < ne00 && i1 < ne01 && i2 < ne02 && i3 < ne03) {
42
+ x = (global const float *)(src0 + (i3 )*nb03 + (i2 )*nb02 + (i1 )*nb01 + (i0 )*nb00);
43
+ } else {
44
+ x = (global const float *)(src1 + (i3 - o[3])*nb13 + (i2 - o[2])*nb12 + (i1 - o[1])*nb11 + (i0 - o[0])*nb10);
45
+ }
46
+
47
+ global float * y = (global float *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
48
+
49
+ *y = *x;
50
+ }
51
+ }
52
+
53
+ kernel void kernel_concat_f32_pack(
54
+ global const char * src0,
55
+ ulong offset0,
56
+ global const char * src1,
57
+ ulong offset1,
58
+ global char * dst,
59
+ ulong offsetd,
60
+ int ne00,
61
+ int ne01,
62
+ int ne02,
63
+ int ne03,
64
+ ulong nb00,
65
+ ulong nb01,
66
+ ulong nb02,
67
+ ulong nb03,
68
+ ulong nb10,
69
+ ulong nb11,
70
+ ulong nb12,
71
+ ulong nb13,
72
+ int ne0,
73
+ ulong nb0,
74
+ ulong nb1,
75
+ ulong nb2,
76
+ ulong nb3,
77
+ int dim,
78
+ int ne1,
79
+ int ne2,
80
+ int ne3
81
+ ) {
82
+ src0 = src0 + offset0;
83
+ src1 = src1 + offset1;
84
+ dst = dst + offsetd;
85
+
86
+ int lsz = get_local_size(0);
87
+ int tpr = min(ne0, lsz); // threads per row
88
+ int rpw = lsz / tpr; // rows per workgroup
89
+ int lid = get_local_id(0);
90
+ int row = get_group_id(0)*rpw + lid / tpr;
91
+ int lane = lid - (lid / tpr) * tpr;
92
+
93
+ int nrows = ne1*ne2*ne3;
94
+ if (row >= nrows) {
95
+ return;
96
+ }
97
+
98
+ int i1 = row % ne1;
99
+ int t = row / ne1;
100
+ int i2 = t % ne2;
101
+ int i3 = t / ne2;
102
+
103
+ int o[4] = {0, 0, 0, 0};
104
+ o[dim] = dim == 0 ? ne00 : (dim == 1 ? ne01 : (dim == 2 ? ne02 : ne03));
105
+
106
+ for (int i0 = lane; i0 < ne0; i0 += tpr) {
107
+ global const float * x;
108
+ if (i0 < ne00 && i1 < ne01 && i2 < ne02 && i3 < ne03) {
109
+ x = (global const float *)(src0 + (i3 )*nb03 + (i2 )*nb02 + (i1 )*nb01 + (i0 )*nb00);
110
+ } else {
111
+ x = (global const float *)(src1 + (i3 - o[3])*nb13 + (i2 - o[2])*nb12 + (i1 - o[1])*nb11 + (i0 - o[0])*nb10);
112
+ }
113
+
114
+ global float * y = (global float *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
115
+
116
+ *y = *x;
117
+ }
118
+ }
ggml/src/ggml-opencl/kernels/conv2d.cl ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifdef USE_FP16
2
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
3
+ #define T_FLOAT half
4
+ #define T_FLOAT4 half4
5
+ #define VSTORE_T_FLOAT4(data, offset, p) vstore_half4_rte(data, offset, p)
6
+ #else
7
+ #define T_FLOAT float
8
+ #define T_FLOAT4 float4
9
+ #define VSTORE_T_FLOAT4(data, offset, p) vstore4(data, offset, p)
10
+ #endif
11
+
12
+ #if defined(cl_qcom_reqd_sub_group_size)
13
+ #pragma OPENCL EXTENSION cl_qcom_reqd_sub_group_size : enable
14
+ #define REQD_SUBGROUP_SIZE_128 __attribute__((qcom_reqd_sub_group_size("full")))
15
+ #else
16
+ #define REQD_SUBGROUP_SIZE_128
17
+ #endif
18
+
19
+ #define T_ACCUM float4
20
+ #define VEC_SIZE 4
21
+
22
+ #define BS_K 64
23
+ #define BS_NPQ 64
24
+ #define BS_CRS 16
25
+
26
+ #define TS_K 4
27
+ #define TS_NPQ 8
28
+
29
+ #define WG_K (BS_K / TS_K)
30
+ #define WG_NPQ (BS_NPQ / TS_NPQ)
31
+
32
+ #define BS_NPQ_VEC (BS_NPQ / VEC_SIZE)
33
+ #define TS_NPQ_VEC (TS_NPQ / VEC_SIZE)
34
+
35
+ static inline uint splitWork(uint work_size, uint block_size){
36
+ return (work_size + block_size - 1) / block_size;
37
+ }
38
+
39
+ REQD_SUBGROUP_SIZE_128
40
+ kernel void kernel_conv_2d(
41
+ global void* p_knl,
42
+ ulong off_knl,
43
+ global void* p_src,
44
+ ulong off_src,
45
+ global void* p_dst,
46
+ ulong off_dst,
47
+ local void* shared,
48
+ uint Cout, uint Cin, uint N,
49
+ uint KW, uint KH, uint W, uint H, uint OW, uint OH,
50
+ uint s0, uint s1, uint p0, uint p1, uint d0, uint d1,
51
+ uint nb01, uint nb02, uint nb03,
52
+ uint nb11, uint nb12, uint nb13,
53
+ uint nb1, uint nb2, uint nb3
54
+ ) {
55
+ global T_FLOAT* knl_data = (global T_FLOAT*) ((global char*)p_knl + off_knl);
56
+ global T_FLOAT* src_data = (global T_FLOAT*) ((global char*)p_src + off_src);
57
+ global T_FLOAT* dst_data = (global T_FLOAT*) ((global char*)p_dst + off_dst);
58
+
59
+ const uint K = Cout;
60
+ const uint CRS = Cin*KH*KW;
61
+ const uint NPQ = N*OH*OW;
62
+
63
+ const uint lid_k = get_local_id(0);
64
+ const uint lid_npq = get_local_id(1);
65
+ const uint tid = lid_npq * WG_K + lid_k;
66
+
67
+ const uint B_idx_K = get_group_id(0);
68
+ const uint B_idx_NPQ = get_group_id(1);
69
+
70
+ const uint offset_k = B_idx_K * BS_K;
71
+ const uint offset_npq = B_idx_NPQ * BS_NPQ;
72
+
73
+ local T_FLOAT* Ash = (local T_FLOAT*)shared;
74
+ local T_FLOAT4* Bsh = (local T_FLOAT4*) &Ash[BS_K * BS_CRS];
75
+
76
+ T_ACCUM regC[TS_K][TS_NPQ_VEC];
77
+ for (int i = 0; i < TS_K; ++i) {
78
+ for (int j = 0; j < TS_NPQ_VEC; ++j) {
79
+ regC[i][j] = (T_ACCUM)(0.0f);
80
+ }
81
+ }
82
+
83
+ const uint NB_CRS = splitWork(CRS, BS_CRS);
84
+
85
+ for (uint B_idx_CRS = 0; B_idx_CRS < NB_CRS; ++B_idx_CRS) {
86
+ const uint offset_crs = B_idx_CRS * BS_CRS;
87
+
88
+ for (int i = tid; i < BS_K * BS_CRS; i += (WG_K * WG_NPQ)) {
89
+ const uint k_l = i / BS_CRS;
90
+ const uint crs_l = i % BS_CRS;
91
+ const uint k_g = offset_k + k_l;
92
+ const uint crs_g = offset_crs + crs_l;
93
+
94
+ if (k_g < K && crs_g < CRS) {
95
+ const uint Cin_idx = crs_g / (KW*KH);
96
+ const uint KH_idx = (crs_g - Cin_idx*KW*KH) / KW;
97
+ const uint KW_idx = crs_g - Cin_idx*KW*KH - KH_idx*KW;
98
+ const uint knl_idx = KW_idx + KH_idx*nb01 + Cin_idx*nb02 + k_g*nb03;
99
+ Ash[k_l * BS_CRS + crs_l] = knl_data[knl_idx];
100
+ } else {
101
+ Ash[k_l * BS_CRS + crs_l] = (T_FLOAT)0.0f;
102
+ }
103
+ }
104
+
105
+ for (int i = tid; i < BS_CRS * BS_NPQ_VEC; i += (WG_K * WG_NPQ)) {
106
+ const uint crs_l = i / BS_NPQ_VEC;
107
+ const uint npq_l_vec = i % BS_NPQ_VEC;
108
+ const uint crs_g = offset_crs + crs_l;
109
+
110
+ T_FLOAT4 val = (T_FLOAT4)(0.0f);
111
+ if (crs_g < CRS) {
112
+ const uint Cin_idx = crs_g / (KW * KH);
113
+ const uint KH_idx = (crs_g - Cin_idx * KW * KH) / KW;
114
+ const uint KW_idx = crs_g - Cin_idx * KW * KH - KH_idx * KW;
115
+ for (int v = 0; v < VEC_SIZE; ++v) {
116
+ const uint npq_g = offset_npq + npq_l_vec * VEC_SIZE + v;
117
+ if (npq_g < NPQ) {
118
+ const uint N_idx = npq_g / (OH * OW);
119
+ const uint pq_idx = npq_g % (OH * OW);
120
+ const uint OH_idx = pq_idx / OW;
121
+ const uint OW_idx = pq_idx % OW;
122
+ const int H_idx = (int)(OH_idx * s1 + KH_idx * d1 - p1);
123
+ const int W_idx = (int)(OW_idx * s0 + KW_idx * d0 - p0);
124
+
125
+ if (H_idx >= 0 && H_idx < H && W_idx >= 0 && W_idx < W) {
126
+ const uint src_idx = W_idx + H_idx * nb11 + Cin_idx * nb12 + N_idx * nb13;
127
+ ((T_FLOAT*)&val)[v] = src_data[src_idx];
128
+ }
129
+ }
130
+ }
131
+ }
132
+ Bsh[crs_l * BS_NPQ_VEC + npq_l_vec] = val;
133
+ }
134
+
135
+ barrier(CLK_LOCAL_MEM_FENCE);
136
+
137
+ #pragma unroll
138
+ for (uint crs_l = 0; crs_l < BS_CRS; ++crs_l) {
139
+ T_FLOAT regA[TS_K];
140
+ for (uint k_l_reg = 0; k_l_reg < TS_K; ++k_l_reg) {
141
+ regA[k_l_reg] = Ash[(lid_k * TS_K + k_l_reg) * BS_CRS + crs_l];
142
+ }
143
+
144
+ for (uint npq_l_vec_reg = 0; npq_l_vec_reg < TS_NPQ_VEC; ++npq_l_vec_reg) {
145
+ T_FLOAT4 regB = Bsh[crs_l * BS_NPQ_VEC + lid_npq * TS_NPQ_VEC + npq_l_vec_reg];
146
+ for (uint k_l_reg = 0; k_l_reg < TS_K; ++k_l_reg) {
147
+ regC[k_l_reg][npq_l_vec_reg] = mad(convert_float(regA[k_l_reg]), convert_float4(regB), regC[k_l_reg][npq_l_vec_reg]);
148
+ }
149
+ }
150
+ }
151
+ barrier(CLK_LOCAL_MEM_FENCE);
152
+ }
153
+
154
+ for (uint k_l_reg = 0; k_l_reg < TS_K; ++k_l_reg) {
155
+ const uint k_g = offset_k + lid_k * TS_K + k_l_reg;
156
+ if (k_g >= K) continue;
157
+
158
+ for (uint npq_l_vec_reg = 0; npq_l_vec_reg < TS_NPQ_VEC; ++npq_l_vec_reg) {
159
+ const uint npq_g_base = offset_npq + (lid_npq * TS_NPQ_VEC + npq_l_vec_reg) * VEC_SIZE;
160
+
161
+ const uint N_idx = npq_g_base / (OH * OW);
162
+ const uint pq_idx = npq_g_base % (OH * OW);
163
+ const uint OH_idx = pq_idx / OW;
164
+ const uint OW_idx = pq_idx % OW;
165
+
166
+ if (nb1 == OW && OW_idx + VEC_SIZE <= OW && npq_g_base + VEC_SIZE <= NPQ) {
167
+ const uint dst_idx = OW_idx + OH_idx*nb1 + k_g*nb2 + N_idx*nb3;
168
+ VSTORE_T_FLOAT4(regC[k_l_reg][npq_l_vec_reg], 0, &dst_data[dst_idx]);
169
+ } else {
170
+ T_ACCUM res = regC[k_l_reg][npq_l_vec_reg];
171
+ for (int v = 0; v < VEC_SIZE; ++v) {
172
+ const uint npq_g = npq_g_base + v;
173
+ if (npq_g < NPQ) {
174
+ const uint N_idx_s = npq_g / (OH*OW);
175
+ const uint pq_idx_s = npq_g % (OH*OW);
176
+ const uint OH_idx_s = pq_idx_s / OW;
177
+ const uint OW_idx_s = pq_idx_s % OW;
178
+ const uint dst_idx_s = OW_idx_s + OH_idx_s*nb1 + k_g*nb2 + N_idx_s*nb3;
179
+ dst_data[dst_idx_s] = (T_FLOAT)(((float*)&res)[v]);
180
+ }
181
+ }
182
+ }
183
+ }
184
+ }
185
+ }
ggml/src/ggml-opencl/kernels/conv2d_f16_f32.cl ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+
3
+ #if defined(cl_qcom_reqd_sub_group_size)
4
+ #pragma OPENCL EXTENSION cl_qcom_reqd_sub_group_size : enable
5
+ #define REQD_SUBGROUP_SIZE_128 __attribute__((qcom_reqd_sub_group_size("full")))
6
+ #else
7
+ #define REQD_SUBGROUP_SIZE_128
8
+ #endif
9
+
10
+ #define T_ACCUM float4
11
+ #define VEC_SIZE 4
12
+
13
+ #define BS_K 64
14
+ #define BS_NPQ 64
15
+ #define BS_CRS 16
16
+
17
+ #define TS_K 4
18
+ #define TS_NPQ 8
19
+
20
+ #define WG_K (BS_K / TS_K)
21
+ #define WG_NPQ (BS_NPQ / TS_NPQ)
22
+
23
+ #define BS_NPQ_VEC (BS_NPQ / VEC_SIZE)
24
+ #define TS_NPQ_VEC (TS_NPQ / VEC_SIZE)
25
+
26
+ static inline uint splitWork(uint work_size, uint block_size){
27
+ return (work_size + block_size - 1) / block_size;
28
+ }
29
+
30
+ REQD_SUBGROUP_SIZE_128
31
+ kernel void kernel_conv_2d(
32
+ global void* p_knl,
33
+ ulong off_knl,
34
+ global void* p_src,
35
+ ulong off_src,
36
+ global void* p_dst,
37
+ ulong off_dst,
38
+ local void* shared,
39
+ uint Cout, uint Cin, uint N,
40
+ uint KW, uint KH, uint W, uint H, uint OW, uint OH,
41
+ uint s0, uint s1, uint p0, uint p1, uint d0, uint d1,
42
+ uint nb01, uint nb02, uint nb03,
43
+ uint nb11, uint nb12, uint nb13,
44
+ uint nb1, uint nb2, uint nb3
45
+ ) {
46
+ global half* knl_data = (global half*) ((global char*)p_knl + off_knl);
47
+ global float* src_data = (global float*) ((global char*)p_src + off_src);
48
+ global float* dst_data = (global float*) ((global char*)p_dst + off_dst);
49
+
50
+ const uint K = Cout;
51
+ const uint CRS = Cin*KH*KW;
52
+ const uint NPQ = N*OH*OW;
53
+
54
+ const uint lid_k = get_local_id(0);
55
+ const uint lid_npq = get_local_id(1);
56
+ const uint tid = lid_npq * WG_K + lid_k;
57
+
58
+ const uint B_idx_K = get_group_id(0);
59
+ const uint B_idx_NPQ = get_group_id(1);
60
+
61
+ const uint offset_k = B_idx_K * BS_K;
62
+ const uint offset_npq = B_idx_NPQ * BS_NPQ;
63
+
64
+ local half* Ash = (local half*)shared;
65
+ local float4* Bsh = (local float4*) &Ash[BS_K * BS_CRS];
66
+
67
+ T_ACCUM regC[TS_K][TS_NPQ_VEC];
68
+ for (int i = 0; i < TS_K; ++i) {
69
+ for (int j = 0; j < TS_NPQ_VEC; ++j) {
70
+ regC[i][j] = (T_ACCUM)(0.0f);
71
+ }
72
+ }
73
+
74
+ const uint NB_CRS = splitWork(CRS, BS_CRS);
75
+
76
+ for (uint B_idx_CRS = 0; B_idx_CRS < NB_CRS; ++B_idx_CRS) {
77
+ const uint offset_crs = B_idx_CRS * BS_CRS;
78
+
79
+ for (int i = tid; i < BS_K * BS_CRS; i += (WG_K * WG_NPQ)) {
80
+ const uint k_l = i / BS_CRS;
81
+ const uint crs_l = i % BS_CRS;
82
+ const uint k_g = offset_k + k_l;
83
+ const uint crs_g = offset_crs + crs_l;
84
+
85
+ if (k_g < K && crs_g < CRS) {
86
+ const uint Cin_idx = crs_g / (KW*KH);
87
+ const uint KH_idx = (crs_g - Cin_idx*KW*KH) / KW;
88
+ const uint KW_idx = crs_g - Cin_idx*KW*KH - KH_idx*KW;
89
+ const uint knl_idx = KW_idx + KH_idx*nb01 + Cin_idx*nb02 + k_g*nb03;
90
+ Ash[k_l * BS_CRS + crs_l] = knl_data[knl_idx];
91
+ } else {
92
+ Ash[k_l * BS_CRS + crs_l] = (half)0.0f;
93
+ }
94
+ }
95
+
96
+ for (int i = tid; i < BS_CRS * BS_NPQ_VEC; i += (WG_K * WG_NPQ)) {
97
+ const uint crs_l = i / BS_NPQ_VEC;
98
+ const uint npq_l_vec = i % BS_NPQ_VEC;
99
+ const uint crs_g = offset_crs + crs_l;
100
+
101
+ float4 val = (float4)(0.0f);
102
+ if (crs_g < CRS) {
103
+ const uint Cin_idx = crs_g / (KW * KH);
104
+ const uint KH_idx = (crs_g - Cin_idx * KW * KH) / KW;
105
+ const uint KW_idx = crs_g - Cin_idx * KW * KH - KH_idx * KW;
106
+ for (int v = 0; v < VEC_SIZE; ++v) {
107
+ const uint npq_g = offset_npq + npq_l_vec * VEC_SIZE + v;
108
+ if (npq_g < NPQ) {
109
+ const uint N_idx = npq_g / (OH * OW);
110
+ const uint pq_idx = npq_g % (OH * OW);
111
+ const uint OH_idx = pq_idx / OW;
112
+ const uint OW_idx = pq_idx % OW;
113
+ const int H_idx = (int)(OH_idx * s1 + KH_idx * d1 - p1);
114
+ const int W_idx = (int)(OW_idx * s0 + KW_idx * d0 - p0);
115
+
116
+ if (H_idx >= 0 && H_idx < H && W_idx >= 0 && W_idx < W) {
117
+ const uint src_idx = W_idx + H_idx * nb11 + Cin_idx * nb12 + N_idx * nb13;
118
+ ((float*)&val)[v] = src_data[src_idx];
119
+ }
120
+ }
121
+ }
122
+ }
123
+ Bsh[crs_l * BS_NPQ_VEC + npq_l_vec] = val;
124
+ }
125
+
126
+ barrier(CLK_LOCAL_MEM_FENCE);
127
+
128
+ #pragma unroll
129
+ for (uint crs_l = 0; crs_l < BS_CRS; ++crs_l) {
130
+ half regA[TS_K];
131
+ for (uint k_l_reg = 0; k_l_reg < TS_K; ++k_l_reg) {
132
+ regA[k_l_reg] = Ash[(lid_k * TS_K + k_l_reg) * BS_CRS + crs_l];
133
+ }
134
+
135
+ for (uint npq_l_vec_reg = 0; npq_l_vec_reg < TS_NPQ_VEC; ++npq_l_vec_reg) {
136
+ float4 regB = Bsh[crs_l * BS_NPQ_VEC + lid_npq * TS_NPQ_VEC + npq_l_vec_reg];
137
+ for (uint k_l_reg = 0; k_l_reg < TS_K; ++k_l_reg) {
138
+ regC[k_l_reg][npq_l_vec_reg] = mad(convert_float(regA[k_l_reg]), regB, regC[k_l_reg][npq_l_vec_reg]);
139
+ }
140
+ }
141
+ }
142
+ barrier(CLK_LOCAL_MEM_FENCE);
143
+ }
144
+
145
+ for (uint k_l_reg = 0; k_l_reg < TS_K; ++k_l_reg) {
146
+ const uint k_g = offset_k + lid_k * TS_K + k_l_reg;
147
+ if (k_g >= K) continue;
148
+
149
+ for (uint npq_l_vec_reg = 0; npq_l_vec_reg < TS_NPQ_VEC; ++npq_l_vec_reg) {
150
+ const uint npq_g_base = offset_npq + (lid_npq * TS_NPQ_VEC + npq_l_vec_reg) * VEC_SIZE;
151
+
152
+ const uint N_idx = npq_g_base / (OH * OW);
153
+ const uint pq_idx = npq_g_base % (OH * OW);
154
+ const uint OH_idx = pq_idx / OW;
155
+ const uint OW_idx = pq_idx % OW;
156
+
157
+ if (nb1 == OW && OW_idx + VEC_SIZE <= OW && npq_g_base + VEC_SIZE <= NPQ) {
158
+ const uint dst_idx = OW_idx + OH_idx*nb1 + k_g*nb2 + N_idx*nb3;
159
+ vstore4(regC[k_l_reg][npq_l_vec_reg], 0, &dst_data[dst_idx]);
160
+ } else {
161
+ T_ACCUM res = regC[k_l_reg][npq_l_vec_reg];
162
+ for (int v = 0; v < VEC_SIZE; ++v) {
163
+ const uint npq_g = npq_g_base + v;
164
+ if (npq_g < NPQ) {
165
+ const uint N_idx_s = npq_g / (OH*OW);
166
+ const uint pq_idx_s = npq_g % (OH*OW);
167
+ const uint OH_idx_s = pq_idx_s / OW;
168
+ const uint OW_idx_s = pq_idx_s % OW;
169
+ const uint dst_idx_s = OW_idx_s + OH_idx_s*nb1 + k_g*nb2 + N_idx_s*nb3;
170
+ dst_data[dst_idx_s] = ((float*)&res)[v];
171
+ }
172
+ }
173
+ }
174
+ }
175
+ }
176
+ }
ggml/src/ggml-opencl/kernels/cpy.cl ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+
3
+ //------------------------------------------------------------------------------
4
+ // cpy
5
+ //------------------------------------------------------------------------------
6
+
7
+ kernel void kernel_cpy_f16_f16(
8
+ global half * src0,
9
+ ulong offset0,
10
+ global half * dst,
11
+ ulong offsetd,
12
+ int ne00,
13
+ int ne01,
14
+ int ne02,
15
+ int ne03,
16
+ ulong nb00,
17
+ ulong nb01,
18
+ ulong nb02,
19
+ ulong nb03,
20
+ int ne0,
21
+ int ne1,
22
+ int ne2,
23
+ int ne3,
24
+ ulong nb0,
25
+ ulong nb1,
26
+ ulong nb2,
27
+ ulong nb3
28
+ ) {
29
+ src0 = (global half*)((global char*)src0 + offset0);
30
+ dst = (global half*)((global char*)dst + offsetd);
31
+
32
+ int i03 = get_group_id(2);
33
+ int i02 = get_group_id(1);
34
+ int i01 = get_group_id(0);
35
+
36
+ int n = i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00;
37
+
38
+ int i3 = n / (ne2*ne1*ne0);
39
+ int i2 = (n - i3*ne2*ne1*ne0) / (ne1*ne0);
40
+ int i1 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0) / ne0;
41
+ int i0 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0 - i1*ne0);
42
+
43
+ global half * dst_data = (global half *) ((global char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
44
+
45
+ for (int i00 = get_local_id(0); i00 < ne00; i00 += get_local_size(0)) {
46
+ global const half * src = (global half *)((global char *) src0 + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00);
47
+ dst_data[i00] = src[0];
48
+ }
49
+ }
50
+
51
+ kernel void kernel_cpy_f16_f32(
52
+ global half * src0,
53
+ ulong offset0,
54
+ global float * dst,
55
+ ulong offsetd,
56
+ int ne00,
57
+ int ne01,
58
+ int ne02,
59
+ int ne03,
60
+ ulong nb00,
61
+ ulong nb01,
62
+ ulong nb02,
63
+ ulong nb03,
64
+ int ne0,
65
+ int ne1,
66
+ int ne2,
67
+ int ne3,
68
+ ulong nb0,
69
+ ulong nb1,
70
+ ulong nb2,
71
+ ulong nb3
72
+ ) {
73
+
74
+ src0 = (global half*)((global char*)src0 + offset0);
75
+ dst = (global float*)((global char*)dst + offsetd);
76
+
77
+ int i03 = get_group_id(2);
78
+ int i02 = get_group_id(1);
79
+ int i01 = get_group_id(0);
80
+
81
+ int n = i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00;
82
+
83
+ int i3 = n / (ne2*ne1*ne0);
84
+ int i2 = (n - i3*ne2*ne1*ne0) / (ne1*ne0);
85
+ int i1 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0) / ne0;
86
+ int i0 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0 - i1*ne0);
87
+
88
+ global float * dst_data = (global float *) ((global char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
89
+
90
+ for (int i00 = get_local_id(0); i00 < ne00; i00 += get_local_size(0)) {
91
+ global half * src = (global half *)((global char *) src0 + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00);
92
+ dst_data[i00] = src[0];
93
+ }
94
+ }
95
+
96
+ kernel void kernel_cpy_f32_f16(
97
+ global float * src0,
98
+ ulong offset0,
99
+ global half * dst,
100
+ ulong offsetd,
101
+ int ne00,
102
+ int ne01,
103
+ int ne02,
104
+ int ne03,
105
+ ulong nb00,
106
+ ulong nb01,
107
+ ulong nb02,
108
+ ulong nb03,
109
+ int ne0,
110
+ int ne1,
111
+ int ne2,
112
+ int ne3,
113
+ ulong nb0,
114
+ ulong nb1,
115
+ ulong nb2,
116
+ ulong nb3
117
+ ) {
118
+ src0 = (global float*)((global char*)src0 + offset0);
119
+ dst = (global half*)((global char*)dst + offsetd);
120
+
121
+ int i03 = get_group_id(2);
122
+ int i02 = get_group_id(1);
123
+ int i01 = get_group_id(0);
124
+
125
+ int n = i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00;
126
+
127
+ int i3 = n / (ne2*ne1*ne0);
128
+ int i2 = (n - i3*ne2*ne1*ne0) / (ne1*ne0);
129
+ int i1 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0) / ne0;
130
+ int i0 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0 - i1*ne0);
131
+
132
+ global half * dst_data = (global half *) ((global char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
133
+
134
+ for (int i00 = get_local_id(0); i00 < ne00; i00 += get_local_size(0)) {
135
+ global const float * src = (global float *)((global char *) src0 + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00);
136
+
137
+ dst_data[i00] = src[0];
138
+ }
139
+ }
140
+
141
+ kernel void kernel_cpy_f32_f32(
142
+ global float * src0,
143
+ ulong offset0,
144
+ global float * dst,
145
+ ulong offsetd,
146
+ int ne00,
147
+ int ne01,
148
+ int ne02,
149
+ int ne03,
150
+ ulong nb00,
151
+ ulong nb01,
152
+ ulong nb02,
153
+ ulong nb03,
154
+ int ne0,
155
+ int ne1,
156
+ int ne2,
157
+ int ne3,
158
+ ulong nb0,
159
+ ulong nb1,
160
+ ulong nb2,
161
+ ulong nb3
162
+ ) {
163
+ src0 = (global float*)((global char*)src0 + offset0);
164
+ dst = (global float*)((global char*)dst + offsetd);
165
+
166
+ int i03 = get_group_id(2);
167
+ int i02 = get_group_id(1);
168
+ int i01 = get_group_id(0);
169
+
170
+ int n = i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00;
171
+
172
+ int i3 = n / (ne2*ne1*ne0);
173
+ int i2 = (n - i3*ne2*ne1*ne0) / (ne1*ne0);
174
+ int i1 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0) / ne0;
175
+ int i0 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0 - i1*ne0);
176
+
177
+ global float * dst_data = (global float *) ((global char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
178
+
179
+ for (int i00 = get_local_id(0); i00 < ne00; i00 += get_local_size(0)) {
180
+ global const float * src = (global float *)((global char *) src0 + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00);
181
+
182
+ dst_data[i00] = src[0];
183
+ }
184
+ }
185
+
186
+ kernel void kernel_cpy_f32_f32_pack(
187
+ global float * src0,
188
+ ulong offset0,
189
+ global float * dst,
190
+ ulong offsetd,
191
+ int ne00,
192
+ int ne01,
193
+ int ne02,
194
+ int ne03,
195
+ ulong nb00,
196
+ ulong nb01,
197
+ ulong nb02,
198
+ ulong nb03,
199
+ int ne0,
200
+ int ne1,
201
+ int ne2,
202
+ int ne3,
203
+ ulong nb0,
204
+ ulong nb1,
205
+ ulong nb2,
206
+ ulong nb3
207
+ ) {
208
+ src0 = (global float*)((global char*)src0 + offset0);
209
+ dst = (global float*)((global char*)dst + offsetd);
210
+
211
+ int lsz = get_local_size(0);
212
+ int tpr = min(ne00, lsz); // threads per row
213
+ int rpw = lsz / tpr; // rows per workgroup
214
+ int lid = get_local_id(0);
215
+ int row = get_group_id(0)*rpw + lid / tpr;
216
+ int lane = lid - (lid / tpr) * tpr;
217
+
218
+ int nrows = ne01*ne02*ne03;
219
+ if (row >= nrows) {
220
+ return;
221
+ }
222
+
223
+ int i01 = row % ne01;
224
+ int t = row / ne01;
225
+ int i02 = t % ne02;
226
+ int i03 = t / ne02;
227
+
228
+ // linear index of the first element of this row, unflattened over dst dims
229
+ long n = (long)row * ne00;
230
+ int i3 = (int)(n / ((long)ne2*ne1*ne0));
231
+ long rm = n - (long)i3*ne2*ne1*ne0;
232
+ int i2 = (int)(rm / ((long)ne1*ne0));
233
+ rm -= (long)i2*ne1*ne0;
234
+ int i1 = (int)(rm / ne0);
235
+ int i0 = (int)(rm - (long)i1*ne0);
236
+
237
+ global float * dst_data = (global float *) ((global char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
238
+
239
+ for (int i00 = lane; i00 < ne00; i00 += tpr) {
240
+ global const float * src = (global float *)((global char *) src0 + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00);
241
+ dst_data[i00] = src[0];
242
+ }
243
+ }
244
+
245
+ kernel void kernel_cpy_i32_i32(
246
+ global int * src0,
247
+ ulong offset0,
248
+ global int * dst,
249
+ ulong offsetd,
250
+ int ne00,
251
+ int ne01,
252
+ int ne02,
253
+ int ne03,
254
+ ulong nb00,
255
+ ulong nb01,
256
+ ulong nb02,
257
+ ulong nb03,
258
+ int ne0,
259
+ int ne1,
260
+ int ne2,
261
+ int ne3,
262
+ ulong nb0,
263
+ ulong nb1,
264
+ ulong nb2,
265
+ ulong nb3
266
+ ) {
267
+ src0 = (global int*)((global char*)src0 + offset0);
268
+ dst = (global int*)((global char*)dst + offsetd);
269
+
270
+ int i03 = get_group_id(2);
271
+ int i02 = get_group_id(1);
272
+ int i01 = get_group_id(0);
273
+
274
+ int n = i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00;
275
+
276
+ int i3 = n / (ne2*ne1*ne0);
277
+ int i2 = (n - i3*ne2*ne1*ne0) / (ne1*ne0);
278
+ int i1 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0) / ne0;
279
+ int i0 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0 - i1*ne0);
280
+
281
+ global int * dst_data = (global int *) ((global char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
282
+
283
+ for (int i00 = get_local_id(0); i00 < ne00; i00 += get_local_size(0)) {
284
+ global const int * src = (global int *)((global char *) src0 + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00);
285
+
286
+ dst_data[i00] = src[0];
287
+ }
288
+ }
ggml/src/ggml-opencl/kernels/cumsum.cl ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+
3
+ #ifdef cl_intel_required_subgroup_size
4
+ #pragma OPENCL EXTENSION cl_intel_required_subgroup_size : enable
5
+ #define INTEL_GPU 1
6
+ #define REQD_SUBGROUP_SIZE_16 __attribute__((intel_reqd_sub_group_size(16)))
7
+ #define REQD_SUBGROUP_SIZE_32 __attribute__((intel_reqd_sub_group_size(32)))
8
+ #elif defined(cl_qcom_reqd_sub_group_size)
9
+ #pragma OPENCL EXTENSION cl_qcom_reqd_sub_group_size : enable
10
+ #define ADRENO_GPU 1
11
+ #define REQD_SUBGROUP_SIZE_64 __attribute__((qcom_reqd_sub_group_size("half")))
12
+ #define REQD_SUBGROUP_SIZE_128 __attribute__((qcom_reqd_sub_group_size("full")))
13
+ #endif
14
+
15
+ // max workgroup size is usually 1024, this covers various subgroups sizes
16
+ #define MAX_SUBGROUPS 128
17
+
18
+ #ifdef INTEL_GPU
19
+ REQD_SUBGROUP_SIZE_32
20
+ #elif defined (ADRENO_GPU)
21
+ REQD_SUBGROUP_SIZE_64
22
+ #endif
23
+ kernel void kernel_cumsum_blk(
24
+ global char * src0,
25
+ ulong offset0,
26
+ global char * tmp,
27
+ global char * dst,
28
+ ulong offsetd,
29
+ int ne00,
30
+ int ne01,
31
+ int ne02,
32
+ int ne03,
33
+ ulong nb00,
34
+ ulong nb01,
35
+ ulong nb02,
36
+ ulong nb03,
37
+ uint net0,
38
+ uint net1,
39
+ uint net2
40
+ ) {
41
+ src0 = src0 + offset0;
42
+ dst = dst + offsetd;
43
+
44
+ const int i3 = get_group_id(2);
45
+ const int i2 = get_group_id(1);
46
+ const int i1 = get_group_id(0);
47
+
48
+ const int nth = get_local_size(0);
49
+ const int tid = get_local_id(0);
50
+
51
+ const uint sg_size = get_sub_group_size();
52
+ const uint sg_id = get_sub_group_id();
53
+ const uint sg_lid = get_sub_group_local_id();
54
+
55
+ const int ib = i1 / ne01;
56
+ const int i00 = ib * nth;
57
+ const int i01 = i1 % ne01;
58
+ const int i02 = i2;
59
+ const int i03 = i3;
60
+
61
+ global const float * src0_row = (global const float *)(src0 + i03*nb03 + i02*nb02 + i01*nb01);
62
+ global float * tmp_row = (global float *)tmp + net0 * i01 + net0 * net1 * i02 + net0 * net1 * net2 * i03;
63
+ global float * dst_row = (global float *)dst + i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00;
64
+
65
+ __local float partial[MAX_SUBGROUPS];
66
+
67
+ float v = 0.0f;
68
+ if (i00 + tid < ne00) {
69
+ v = src0_row[i00 + tid];
70
+ }
71
+
72
+ float s = sub_group_scan_inclusive_add(v);
73
+ if (sg_lid == sg_size - 1) {
74
+ partial[sg_id] = s;
75
+ }
76
+ barrier(CLK_LOCAL_MEM_FENCE);
77
+
78
+ // NB: subgroup size should be larger than number of subgroups
79
+ // assuming max workgroup size of 1024, subgroup size should be >= 32
80
+ if (sg_id == 0) {
81
+ float x = 0.0f;
82
+ if (sg_lid < get_num_sub_groups()) {
83
+ x = partial[sg_lid];
84
+ }
85
+ float ex = sub_group_scan_exclusive_add(x);
86
+ if (sg_lid < get_num_sub_groups()) {
87
+ partial[sg_lid] = ex;
88
+ }
89
+ }
90
+ barrier(CLK_LOCAL_MEM_FENCE);
91
+
92
+ s += partial[sg_id];
93
+
94
+ if (i00 + tid < ne00) {
95
+ dst_row[i00 + tid] = s;
96
+ }
97
+ if (ne00 > nth && tid == nth - 1) {
98
+ tmp_row[ib] = s;
99
+ }
100
+ }
101
+
102
+ kernel void kernel_cumsum_add(
103
+ global char * tmp,
104
+ global char * dst,
105
+ ulong offsetd,
106
+ int ne00,
107
+ int ne01,
108
+ int ne02,
109
+ int ne03,
110
+ uint nbt0,
111
+ uint nbt1,
112
+ uint nbt2,
113
+ uint nbt3
114
+ ) {
115
+ dst = dst + offsetd;
116
+
117
+ const int i3 = get_group_id(2);
118
+ const int i2 = get_group_id(1);
119
+ const int i1 = get_group_id(0);
120
+
121
+ const int nth = get_local_size(0);
122
+ const int tid = get_local_id(0);
123
+
124
+ const int ib = i1 / ne01;
125
+ if (ib == 0) {
126
+ return;
127
+ }
128
+ const int i00 = ib * nth;
129
+ const int i01 = i1 % ne01;
130
+ const int i02 = i2;
131
+ const int i03 = i3;
132
+
133
+ global float * tmp_row = (global float *)(tmp + nbt1 * i01 + nbt2 * i02 + nbt3 * i03);
134
+ global float * dst_row = (global float *)dst + i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00;
135
+
136
+ if (i00 + tid < ne00) {
137
+ dst_row[i00 + tid] += tmp_row[ib - 1];
138
+ }
139
+ }
ggml/src/ggml-opencl/kernels/cvt.cl ADDED
@@ -0,0 +1,2492 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //------------------------------------------------------------------------------
2
+ // This file is contains kernels for data conversion.
3
+ // These kernels are used when loading the model, so its performance is less
4
+ // important.
5
+ //------------------------------------------------------------------------------
6
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
7
+
8
+ #ifdef cl_intel_required_subgroup_size
9
+ #pragma OPENCL EXTENSION cl_intel_required_subgroup_size : enable
10
+ #define INTEL_GPU 1
11
+ #define REQD_SUBGROUP_SIZE_16 __attribute__((intel_reqd_sub_group_size(16)))
12
+ #define REQD_SUBGROUP_SIZE_32 __attribute__((intel_reqd_sub_group_size(32)))
13
+ #elif defined(cl_qcom_reqd_sub_group_size)
14
+ #pragma OPENCL EXTENSION cl_qcom_reqd_sub_group_size : enable
15
+ #define ADRENO_GPU 1
16
+ #define REQD_SUBGROUP_SIZE_64 __attribute__((qcom_reqd_sub_group_size("half")))
17
+ #define REQD_SUBGROUP_SIZE_128 __attribute__((qcom_reqd_sub_group_size("full")))
18
+ #endif
19
+
20
+ #define QK4_0 32
21
+ #define QR4_0 2
22
+ #define QK4_1 32
23
+ #define QR4_1 2
24
+ #define QK5_0 32
25
+ #define QR5_0 2
26
+ #define QK5_1 32
27
+ #define QR5_1 2
28
+ #define QK8_0 32
29
+ #define QR8_0 1
30
+ #define QK1_0 128
31
+ #define QR1_0 1
32
+ #define QK_K 256
33
+ #define K_SCALE_SIZE (3 * QK_K / 64)
34
+ #define K_QUANTS_PER_ITERATION 2
35
+
36
+ typedef char int8_t;
37
+ typedef uchar uint8_t;
38
+ typedef short int16_t;
39
+ typedef ushort uint16_t;
40
+ typedef int int32_t;
41
+ typedef uint uint32_t;
42
+
43
+ //------------------------------------------------------------------------------
44
+ // block_q1_0
45
+ //------------------------------------------------------------------------------
46
+ typedef struct {
47
+ half d; // delta
48
+ uchar qs[QK1_0/8]; // 1-bit signs (16 bytes)
49
+ } block_q1_0;
50
+
51
+ //------------------------------------------------------------------------------
52
+ // block_q4_0
53
+ //------------------------------------------------------------------------------
54
+ struct block_q4_0
55
+ {
56
+ half d;
57
+ uint8_t qs[QK4_0 / 2];
58
+ };
59
+
60
+ //------------------------------------------------------------------------------
61
+ // block_q4_1
62
+ //------------------------------------------------------------------------------
63
+ struct block_q4_1 {
64
+ half d; // delta
65
+ half m; // min
66
+ uchar qs[QK4_1 / 2]; // nibbles / quants
67
+ };
68
+
69
+ //------------------------------------------------------------------------------
70
+ // block_q5_0
71
+ //------------------------------------------------------------------------------
72
+ struct block_q5_0 {
73
+ half d; // delta
74
+ uchar qh[4]; // 5-th bit of quants
75
+ uchar qs[QK5_0 / 2]; // nibbles / quants
76
+ };
77
+
78
+ //------------------------------------------------------------------------------
79
+ // block_q5_1
80
+ //------------------------------------------------------------------------------
81
+ struct block_q5_1 {
82
+ half d; // delta
83
+ half m; // min
84
+ uchar qh[4]; // 5-th bit of quants
85
+ uchar qs[QK5_1 / 2]; // nibbles / quants
86
+ };
87
+
88
+ //------------------------------------------------------------------------------
89
+ // block_q4_k
90
+ //------------------------------------------------------------------------------
91
+ struct block_q4_K {
92
+ half d; // delta
93
+ half dm; // min
94
+ uchar s[K_SCALE_SIZE];
95
+ uchar q[QK_K / 2]; // nibbles / quants
96
+ };
97
+
98
+ //------------------------------------------------------------------------------
99
+ // block_q5_k
100
+ //------------------------------------------------------------------------------
101
+ struct block_q5_K {
102
+ half d; // delta
103
+ half dm; // min
104
+ uchar s[K_SCALE_SIZE];
105
+ uchar qh[QK_K / 8];
106
+ uchar qs[QK_K / 2]; // nibbles / quants
107
+ };
108
+
109
+ //------------------------------------------------------------------------------
110
+ // block_q6_K
111
+ //------------------------------------------------------------------------------
112
+ struct block_q6_K {
113
+ uint8_t ql[QK_K/2]; // quants, lower 4 bits
114
+ uint8_t qh[QK_K/4]; // quants, upper 2 bits
115
+ int8_t scales[QK_K/16]; // scales, quantized with 8 bits
116
+ half d; // super-block scale
117
+ };
118
+
119
+ //------------------------------------------------------------------------------
120
+ // block_iq4_nl
121
+ //------------------------------------------------------------------------------
122
+ #define QK4_NL 32
123
+
124
+ struct block_iq4_nl
125
+ {
126
+ half d;
127
+ uint8_t qs[QK4_NL / 2];
128
+ };
129
+
130
+ //------------------------------------------------------------------------------
131
+ // bf16 to f16
132
+ //------------------------------------------------------------------------------
133
+ kernel void kernel_convert_bf16_to_f16(
134
+ global const ushort * src,
135
+ global half * dst,
136
+ ulong off_dst,
137
+ ulong n
138
+ ) {
139
+ uint i = get_global_id(0);
140
+ if (i >= n) {
141
+ return;
142
+ }
143
+
144
+ dst[i + off_dst] = (half) as_float((uint) src[i] << 16);
145
+ }
146
+
147
+ //------------------------------------------------------------------------------
148
+ // f16 to bf16
149
+ //------------------------------------------------------------------------------
150
+ kernel void kernel_convert_f16_to_bf16(
151
+ global const half * src,
152
+ ulong off_src,
153
+ global ushort * dst,
154
+ ulong n
155
+ ) {
156
+ uint i = get_global_id(0);
157
+ if (i >= n) {
158
+ return;
159
+ }
160
+
161
+ float f = (float) src[i + off_src];
162
+ uint bits = as_uint(f);
163
+ if ((bits & 0x7fffffffu) > 0x7f800000u) {
164
+ // nan to quiet nan
165
+ dst[i] = (ushort)((bits >> 16) | 0x40u);
166
+ } else {
167
+ uint rounded = bits + 0x7fffu + ((bits >> 16) & 1u);
168
+ dst[i] = (ushort)(rounded >> 16);
169
+ }
170
+ }
171
+
172
+ //------------------------------------------------------------------------------
173
+ // kernel_convert_block_q1_0
174
+ // Convert block_q1_0 (AOS) to 2 separate arrays (SOA): quant bytes + scales.
175
+ // q1_0 bits are stored in natural order (bit j of byte i -> weight 8*i + j)
176
+ //------------------------------------------------------------------------------
177
+ kernel void kernel_convert_block_q1_0(
178
+ global block_q1_0 * src0,
179
+ global uchar * dst_q,
180
+ global half * dst_d
181
+ ) {
182
+ global block_q1_0 * b = (global block_q1_0 *) src0 + get_global_id(0);
183
+ global uchar * q = (global uchar *) dst_q + (QK1_0/8)*get_global_id(0);
184
+ global half * d = (global half *) dst_d + get_global_id(0);
185
+
186
+ *d = b->d;
187
+
188
+ for (int i = 0; i < QK1_0/8; ++i) {
189
+ q[i] = b->qs[i];
190
+ }
191
+ }
192
+
193
+ kernel void kernel_restore_block_q1_0(
194
+ global uchar * src_q,
195
+ global half * src_d,
196
+ global block_q1_0 * dst
197
+ ) {
198
+ global block_q1_0 * b = (global block_q1_0 *) dst + get_global_id(0);
199
+ global uchar * q = (global uchar *) src_q + (QK1_0/8)*get_global_id(0);
200
+ global half * d = (global half *) src_d + get_global_id(0);
201
+
202
+ b->d = *d;
203
+ for (int i = 0; i < QK1_0/8; ++i) {
204
+ b->qs[i] = q[i];
205
+ }
206
+ }
207
+
208
+ //------------------------------------------------------------------------------
209
+ // kernel_convert_block_q4_0
210
+ // Convert the block_q4_0 format to 2 separate arrays (AOS -> SOA).
211
+ // This kernel does not deshuffle the bits.
212
+ //------------------------------------------------------------------------------
213
+ kernel void kernel_convert_block_q4_0(
214
+ global struct block_q4_0 * src0,
215
+ global uchar * dst_q,
216
+ global half * dst_d
217
+ ) {
218
+ global struct block_q4_0 * b = (global struct block_q4_0 *) src0 + get_global_id(0);
219
+ global uchar * q = (global uchar *) dst_q + QK4_0/2*get_global_id(0);
220
+ global half * d = (global half *) dst_d + get_global_id(0);
221
+
222
+ *d = b->d;
223
+
224
+ for (int i = 0; i < QK4_0/2; ++i) {
225
+ q[i] = b->qs[i];
226
+ }
227
+ }
228
+
229
+ kernel void kernel_restore_block_q4_0(
230
+ global uchar * src_q,
231
+ global half * src_d,
232
+ global struct block_q4_0 * dst
233
+ ) {
234
+ global struct block_q4_0 * b = (global struct block_q4_0 *) dst + get_global_id(0);
235
+ global uchar * q = (global uchar *) src_q + QK4_0/2*get_global_id(0);
236
+ global half * d = (global half *) src_d + get_global_id(0);
237
+
238
+ b->d = *d;
239
+ for (int i = 0; i < QK4_0/2; ++i) {
240
+ b->qs[i] = q[i];
241
+ }
242
+ }
243
+
244
+ //------------------------------------------------------------------------------
245
+ // kernel_convert_block_q4_0_noshuffle
246
+ // Flatten q4_0 weights and unshuffle the bits
247
+ //------------------------------------------------------------------------------
248
+
249
+ kernel void kernel_convert_block_q4_0_noshuffle(
250
+ global struct block_q4_0 * src0,
251
+ global uchar * dst_q,
252
+ global half * dst_d
253
+ ) {
254
+ global struct block_q4_0 * b = (global struct block_q4_0 *) src0 + get_global_id(0);
255
+ global uchar * q = (global uchar *) dst_q + QK4_0/2*get_global_id(0);
256
+ global half * d = (global half *) dst_d + get_global_id(0);
257
+
258
+ *d = b->d;
259
+ for (int i = 0; i < QK4_0/4; ++i) {
260
+ uchar x0 = b->qs[2*i + 0];
261
+ uchar x1 = b->qs[2*i + 1];
262
+
263
+ q[i + 0 ] = convert_uchar(x0 & 0x0F) | convert_uchar((x1 & 0x0F) << 4);
264
+ q[i + QK4_0/4] = convert_uchar((x0 & 0xF0) >> 4) | convert_uchar(x1 & 0xF0);
265
+
266
+ #ifdef ADRENO_GPU
267
+ // Workaround for adreno - must have the following printf statement for
268
+ // the kernel to work properly. Otherwise it produces incorrect result.
269
+ // convert_uchar above also seems necessary.
270
+ // Compare against a large number so that it does not print anything.
271
+ // get_sub_group_local_id() also works.
272
+ if (get_global_id(0) == 65536*4096) {
273
+ printf("%04x - %02x\n", *(global ushort*)d, ((x0 & 0xF0) >> 4) | (x1 & 0xF0));
274
+ }
275
+ #endif
276
+ }
277
+ }
278
+
279
+ kernel void kernel_restore_block_q4_0_noshuffle(
280
+ global uchar * src_q,
281
+ global half * src_d,
282
+ global struct block_q4_0 * dst,
283
+ uchar mask_0F,
284
+ uchar mask_F0
285
+ ) {
286
+ global struct block_q4_0 * b = (global struct block_q4_0 *) dst + get_global_id(0);
287
+ global uchar * q = (global uchar *) src_q + QK4_0/2*get_global_id(0);
288
+ global half * d = (global half *) src_d + get_global_id(0);
289
+
290
+ b->d = *d;
291
+ for (int i = 0; i < QK4_0/4; ++i) {
292
+ uchar x0 = q[i + 0 ] ;
293
+ uchar x1 = q[i + QK4_0/4];
294
+
295
+ b->qs[2*i + 0] = convert_uchar((x0 & mask_0F) | ((x1 & mask_0F) << 4));
296
+ b->qs[2*i + 1] = convert_uchar(((x0 & mask_F0) >> 4) | (x1 & mask_F0));
297
+ }
298
+ }
299
+
300
+ kernel void kernel_convert_block_q4_0_trans4_ns(
301
+ global struct block_q4_0 * src0,
302
+ __global uint * dst_q,
303
+ __global half * dst_d,
304
+ uint ne00,
305
+ uint ne01
306
+ ) {
307
+ uint i00 = get_global_id(1);
308
+ uint i01 = get_global_id(0);
309
+ uint i02 = get_global_id(2);
310
+
311
+ if (i01 >= ne01) {
312
+ return;
313
+ }
314
+
315
+ uint ne00_blk = ne00 / QK4_0;
316
+ uint src_blk_offset = i00 + i01 * ne00_blk + i02 * ne00_blk * ne01;
317
+ uint dst_blk_offset = i01 + i00 * ne01 + i02 * ne00_blk * ne01;
318
+
319
+ global struct block_q4_0 * b = src0 + src_blk_offset;
320
+ dst_d[dst_blk_offset] = b->d;
321
+
322
+ // extract quantization and unshuffle
323
+ ushort8 pre_block = ((global ushort8 *)(&(b->qs[0])))[0];
324
+
325
+ ushort8 post_block = (ushort8)(0);
326
+
327
+ uchar * pre_block_ptr = (uchar *)(&pre_block);
328
+ uchar * post_block_ptr = (uchar *)(&post_block);
329
+
330
+ for (int i = 0; i < QK4_0 / 4; ++i) {
331
+ uchar x0 = pre_block_ptr[2*i + 0];
332
+ uchar x1 = pre_block_ptr[2*i + 1];
333
+
334
+ post_block_ptr[i + 0 ] = convert_uchar(x0 & 0x0F) | convert_uchar((x1 & 0x0F) << 4);
335
+ post_block_ptr[i + QK4_0 / 4] = convert_uchar((x0 & 0xF0) >> 4) | convert_uchar(x1 & 0xF0);
336
+ }
337
+
338
+ uint4 q_block = as_uint4(post_block);
339
+
340
+ uint offset = i02 * ne00_blk * ne01 * 4 + i00 * ne01 * 4 + i01;
341
+ dst_q[offset] = q_block.x;
342
+ dst_q[offset + ne01] = q_block.y;
343
+ dst_q[offset + ne01 * 2] = q_block.z;
344
+ dst_q[offset + ne01 * 3] = q_block.w;
345
+ }
346
+
347
+ kernel void kernel_restore_block_q4_0_trans4_ns(
348
+ __global uint * src_q,
349
+ __global half * src_d,
350
+ __global struct block_q4_0 * dst0,
351
+ uint ne00,
352
+ uint ne01
353
+ ) {
354
+ uint i00 = get_global_id(1);
355
+ uint i01 = get_global_id(0);
356
+ uint i02 = get_global_id(2);
357
+
358
+ if (i01 >= ne01) {
359
+ return;
360
+ }
361
+
362
+ uint ne00_blk = ne00 / QK4_0;
363
+ uint dst_blk_offset = i00 + i01 * ne00_blk + i02 * ne00_blk * ne01;
364
+ uint src_d_offset = i01 + i00 * ne01 + i02 * ne00_blk * ne01;
365
+
366
+ __global struct block_q4_0 * b = dst0 + dst_blk_offset;
367
+ b->d = src_d[src_d_offset];
368
+
369
+ // collect transposed quantization parts for a block
370
+ uint src_q_offset = i02 * ne00_blk * ne01 * 4 + i00 * ne01 * 4 + i01;
371
+ uint4 q_block;
372
+ q_block.x = src_q[src_q_offset];
373
+ q_block.y = src_q[src_q_offset + ne01];
374
+ q_block.z = src_q[src_q_offset + ne01 * 2];
375
+ q_block.w = src_q[src_q_offset + ne01 * 3];
376
+
377
+ ushort8 post_block = as_ushort8(q_block);
378
+ ushort8 pre_block = (ushort8)(0);
379
+
380
+ uchar * pre_block_ptr = (uchar *)(&pre_block);
381
+ uchar * post_block_ptr = (uchar *)(&post_block);
382
+
383
+ for (int i = 0; i < QK4_0 / 4; ++i) {
384
+ uchar x0 = post_block_ptr[i + 0];
385
+ uchar x1 = post_block_ptr[i + QK4_0 / 4];
386
+
387
+ pre_block_ptr[2 * i + 0] = convert_uchar(x0 & 0x0F) | convert_uchar((x1 & 0x0F) << 4);
388
+ pre_block_ptr[2 * i + 1] = convert_uchar((x0 & 0xF0) >> 4) | convert_uchar(x1 & 0xF0);
389
+ }
390
+
391
+ ((__global ushort8 *)(&(b->qs[0])))[0] = pre_block;
392
+ }
393
+
394
+ //------------------------------------------------------------------------------
395
+ // kernel_convert_block_q4_1
396
+ // Convert the block_q4_1 format to 2 separate arrays (AOS -> SOA).
397
+ // This kernel does not deshuffle the bits.
398
+ //------------------------------------------------------------------------------
399
+ kernel void kernel_convert_block_q4_1(
400
+ global struct block_q4_1 * src0,
401
+ global uchar * dst_q,
402
+ global half * dst_d,
403
+ global half * dst_m
404
+ ) {
405
+ global struct block_q4_1 * b = (global struct block_q4_1 *) src0 + get_global_id(0);
406
+ global uchar * q = (global uchar *) dst_q + QK4_1/2*get_global_id(0);
407
+ global half * d = (global half *) dst_d + get_global_id(0);
408
+ global half * m = (global half *) dst_m + get_global_id(0);
409
+
410
+ *d = b->d;
411
+ *m = b->m;
412
+
413
+ for (int i = 0; i < QK4_1/2; ++i) {
414
+ q[i] = b->qs[i];
415
+ }
416
+ }
417
+
418
+ kernel void kernel_restore_block_q4_1(
419
+ global uchar * src_q,
420
+ global half * src_d,
421
+ global half * src_m,
422
+ global struct block_q4_1 * dst
423
+ ) {
424
+ global struct block_q4_1 * b = (global struct block_q4_1 *) dst + get_global_id(0);
425
+ global uchar * q = (global uchar *) src_q + QK4_1/2*get_global_id(0);
426
+ global half * d = (global half *) src_d + get_global_id(0);
427
+ global half * m = (global half *) src_m + get_global_id(0);
428
+
429
+ b->d = *d;
430
+ b->m = *m;
431
+ for (int i = 0; i < QK4_1/2; ++i) {
432
+ b->qs[i] = q[i];
433
+ }
434
+ }
435
+
436
+ kernel void kernel_convert_block_q4_1_noshuffle(
437
+ global struct block_q4_1 * src0,
438
+ global uchar * dst_q,
439
+ global half * dst_d,
440
+ global half * dst_m
441
+ ) {
442
+ global struct block_q4_1 * b = (global struct block_q4_1 *) src0 + get_global_id(0);
443
+ global uchar * q = (global uchar *) dst_q + QK4_1/2*get_global_id(0);
444
+ global half * d = (global half *) dst_d + get_global_id(0);
445
+ global half * m = (global half *) dst_m + get_global_id(0);
446
+
447
+ *d = b->d;
448
+ *m = b->m;
449
+ for (int i = 0; i < QK4_1/4; ++i) {
450
+ uchar x0 = b->qs[2*i + 0];
451
+ uchar x1 = b->qs[2*i + 1];
452
+
453
+ q[i + 0 ] = convert_uchar(x0 & 0x0F) | convert_uchar((x1 & 0x0F) << 4);
454
+ q[i + QK4_1/4] = convert_uchar((x0 & 0xF0) >> 4) | convert_uchar(x1 & 0xF0);
455
+
456
+ #ifdef ADRENO_GPU
457
+ if (get_global_id(0) == 65536*4096) {
458
+ printf("%04x - %02x\n", *(global ushort*)d, ((x0 & 0xF0) >> 4) | (x1 & 0xF0));
459
+ }
460
+ #endif
461
+ }
462
+ }
463
+
464
+ kernel void kernel_restore_block_q4_1_noshuffle(
465
+ global uchar * src_q,
466
+ global half * src_d,
467
+ global half * src_m,
468
+ global struct block_q4_1 * dst,
469
+ uchar mask_0F,
470
+ uchar mask_F0
471
+ ) {
472
+ global struct block_q4_1 * b = (global struct block_q4_1 *) dst + get_global_id(0);
473
+ global uchar * q = (global uchar *) src_q + QK4_1/2*get_global_id(0);
474
+ global half * d = (global half *) src_d + get_global_id(0);
475
+ global half * m = (global half *) src_m + get_global_id(0);
476
+
477
+ b->d = *d;
478
+ b->m = *m;
479
+ for (int i = 0; i < QK4_1/4; ++i) {
480
+ uchar x0 = q[i + 0 ] ;
481
+ uchar x1 = q[i + QK4_1/4];
482
+
483
+ b->qs[2*i + 0] = convert_uchar((x0 & mask_0F) | ((x1 & mask_0F) << 4));
484
+ b->qs[2*i + 1] = convert_uchar(((x0 & mask_F0) >> 4) | (x1 & mask_F0));
485
+ }
486
+ }
487
+
488
+ kernel void kernel_convert_block_q4_1_trans4_ns(
489
+ __global struct block_q4_1 * src0,
490
+ __global uint * dst_q,
491
+ __global half * dst_d,
492
+ __global half * dst_m,
493
+ uint ne00,
494
+ uint ne01
495
+ ) {
496
+ uint i00 = get_global_id(1);
497
+ uint i01 = get_global_id(0);
498
+ uint i02 = get_global_id(2);
499
+
500
+ if (i01 >= ne01) {
501
+ return;
502
+ }
503
+
504
+ uint ne00_blk = ne00 / QK4_1;
505
+ uint src_blk_offset = i00 + i01 * ne00_blk + i02 * ne00_blk * ne01;
506
+ uint dst_blk_offset = i01 + i00 * ne01 + i02 * ne00_blk * ne01;
507
+
508
+ global struct block_q4_1 * b = src0 + src_blk_offset;
509
+ dst_d[dst_blk_offset] = b->d;
510
+ dst_m[dst_blk_offset] = b->m;
511
+
512
+ // extract quantization and unshuffle
513
+ ushort8 pre_block = ((global ushort8 *)(&(b->qs[0])))[0];
514
+
515
+ ushort8 post_block = (ushort8)(0);
516
+
517
+ uchar * pre_block_ptr = (uchar *)(&pre_block);
518
+ uchar * post_block_ptr = (uchar *)(&post_block);
519
+
520
+ for (int i = 0; i < QK4_1 / 4; ++i) {
521
+ uchar x0 = pre_block_ptr[2*i + 0];
522
+ uchar x1 = pre_block_ptr[2*i + 1];
523
+
524
+ post_block_ptr[i + 0 ] = convert_uchar(x0 & 0x0F) | convert_uchar((x1 & 0x0F) << 4);
525
+ post_block_ptr[i + QK4_1 / 4] = convert_uchar((x0 & 0xF0) >> 4) | convert_uchar(x1 & 0xF0);
526
+ }
527
+
528
+ uint4 q_block = as_uint4(post_block);
529
+
530
+ uint offset = i02 * ne00_blk * ne01 * 4 + i00 * ne01 * 4 + i01;
531
+ dst_q[offset] = q_block.x;
532
+ dst_q[offset + ne01] = q_block.y;
533
+ dst_q[offset + ne01 * 2] = q_block.z;
534
+ dst_q[offset + ne01 * 3] = q_block.w;
535
+ }
536
+
537
+ kernel void kernel_restore_block_q4_1_trans4_ns(
538
+ __global uint * src_q,
539
+ __global half * src_d,
540
+ __global half * src_m,
541
+ __global struct block_q4_1 * dst0,
542
+ uint ne00,
543
+ uint ne01
544
+ ) {
545
+ int i00 = get_global_id(1);
546
+ uint i01 = get_global_id(0);
547
+ uint i02 = get_global_id(2);
548
+
549
+ if (i01 >= ne01) {
550
+ return;
551
+ }
552
+
553
+ uint ne00_blk = ne00 / QK4_1;
554
+ uint dst_blk_offset = i00 + i01 * ne00_blk + i02 * ne00_blk * ne01;
555
+ uint src_dm_offset = i01 + i00 * ne01 + i02 * ne00_blk * ne01;
556
+
557
+ __global struct block_q4_1 * b = dst0 + dst_blk_offset;
558
+ b->d = src_d[src_dm_offset];
559
+ b->m = src_m[src_dm_offset];
560
+
561
+ // collect transposed quantization parts for a block
562
+ uint src_q_offset = i02 * ne00_blk * ne01 * 4 + i00 * ne01 * 4 + i01;
563
+ uint4 q_block;
564
+ q_block.x = src_q[src_q_offset];
565
+ q_block.y = src_q[src_q_offset + ne01];
566
+ q_block.z = src_q[src_q_offset + ne01 * 2];
567
+ q_block.w = src_q[src_q_offset + ne01 * 3];
568
+
569
+ ushort8 post_block = as_ushort8(q_block);
570
+ ushort8 pre_block = (ushort8)(0);
571
+
572
+ uchar * pre_block_ptr = (uchar *)(&pre_block);
573
+ uchar * post_block_ptr = (uchar *)(&post_block);
574
+
575
+ for (int i = 0; i < QK4_0 / 4; ++i) {
576
+ uchar x0 = post_block_ptr[i + 0];
577
+ uchar x1 = post_block_ptr[i + QK4_0 / 4];
578
+
579
+ pre_block_ptr[2 * i + 0] = convert_uchar(x0 & 0x0F) | convert_uchar((x1 & 0x0F) << 4);
580
+ pre_block_ptr[2 * i + 1] = convert_uchar((x0 & 0xF0) >> 4) | convert_uchar(x1 & 0xF0);
581
+ }
582
+
583
+ ((__global ushort8 *)(&(b->qs[0])))[0] = pre_block;
584
+ }
585
+
586
+ //------------------------------------------------------------------------------
587
+ // kernel_convert_block_q5_0
588
+ // Convert the block_q5_0 format to 3 separate arrays (AOS -> SOA).
589
+ // This kernel does not deshuffle the bits.
590
+ //------------------------------------------------------------------------------
591
+ kernel void kernel_convert_block_q5_0(
592
+ global struct block_q5_0 * src0,
593
+ global uchar * dst_qs,
594
+ global uint * dst_qh,
595
+ global half * dst_d,
596
+ ulong n_blk
597
+ ) {
598
+ if (get_global_id(0) >= n_blk) {
599
+ return;
600
+ }
601
+
602
+ global struct block_q5_0 * b = (global struct block_q5_0 *) src0 + get_global_id(0);
603
+ global uchar * qs = (global uchar *) dst_qs + (QK5_0/2)*get_global_id(0);
604
+ global uint * qh = (global uint *) dst_qh + get_global_id(0);
605
+ global half * d = (global half *) dst_d + get_global_id(0);
606
+
607
+ *d = b->d;
608
+ *qh = *((global uint *)(b->qh));
609
+
610
+ for (int i = 0; i < QK5_0/2; ++i) {
611
+ qs[i] = b->qs[i];
612
+ }
613
+ }
614
+
615
+ kernel void kernel_restore_block_q5_0(
616
+ global uchar * src_qs,
617
+ global uint * src_qh,
618
+ global half * src_d,
619
+ global struct block_q5_0 * dst
620
+ ) {
621
+ global struct block_q5_0 * b = (global struct block_q5_0 *) dst + get_global_id(0);
622
+ global uchar * qs = (global uchar *) src_qs + (QK5_0/2)*get_global_id(0);
623
+ global uint * qh = (global uint *) src_qh + get_global_id(0);
624
+ global half * d = (global half *) src_d + get_global_id(0);
625
+
626
+ b->d = *d;
627
+ *((global uint *)(b->qh)) = *qh;
628
+ for (int i = 0; i < QK5_0/2; ++i) {
629
+ b->qs[i] = qs[i];
630
+ }
631
+ }
632
+
633
+ kernel void kernel_convert_block_q5_0_noshuffle(
634
+ global struct block_q5_0 * src0,
635
+ global uchar * dst_q,
636
+ global uint * dst_qh,
637
+ global half * dst_d
638
+ ) {
639
+ global struct block_q5_0 * b = (global struct block_q5_0 *) src0 + get_global_id(0);
640
+ global uchar * q = (global uchar *) dst_q + QK5_0/2*get_global_id(0);
641
+ global uint * qh = (global uint *) dst_qh + get_global_id(0);
642
+ global half * d = (global half *) dst_d + get_global_id(0);
643
+
644
+ *d = b->d;
645
+ *qh = *((global uint *)(b->qh));
646
+
647
+ for (int i = 0; i < QK5_0/4; ++i) {
648
+ uchar x0 = b->qs[2*i + 0];
649
+ uchar x1 = b->qs[2*i + 1];
650
+
651
+ q[i + 0 ] = convert_uchar(x0 & 0x0F) | convert_uchar((x1 & 0x0F) << 4);
652
+ q[i + QK5_0/4] = convert_uchar((x0 & 0xF0) >> 4) | convert_uchar(x1 & 0xF0);
653
+
654
+ #ifdef ADRENO_GPU
655
+ if (get_global_id(0) == 65536*4096) {
656
+ printf("%04x - %02x\n", *(global ushort*)d, ((x0 & 0xF0) >> 4) | (x1 & 0xF0));
657
+ }
658
+ #endif
659
+ }
660
+ }
661
+
662
+ kernel void kernel_restore_block_q5_0_noshuffle(
663
+ global uchar * src_q,
664
+ global uint * src_qh,
665
+ global half * src_d,
666
+ global struct block_q5_0 * dst,
667
+ uchar mask_0F,
668
+ uchar mask_F0
669
+ ) {
670
+ global struct block_q5_0 * b = (global struct block_q5_0 *) dst + get_global_id(0);
671
+ global uchar * q = (global uchar *) src_q + QK5_0/2*get_global_id(0);
672
+ global uint * qh = (global uint *) src_qh + get_global_id(0);
673
+ global half * d = (global half *) src_d + get_global_id(0);
674
+
675
+ b->d = *d;
676
+ *((global uint *)(b->qh)) = *qh;
677
+
678
+ for (int i = 0; i < QK5_0/4; ++i) {
679
+ uchar x0 = q[i + 0 ];
680
+ uchar x1 = q[i + QK5_0/4];
681
+
682
+ b->qs[2*i + 0] = convert_uchar((x0 & mask_0F) | ((x1 & mask_0F) << 4));
683
+ b->qs[2*i + 1] = convert_uchar(((x0 & mask_F0) >> 4) | (x1 & mask_F0));
684
+ }
685
+ }
686
+
687
+ kernel void kernel_convert_block_q5_0_trans4_ns(
688
+ __global struct block_q5_0 * src0,
689
+ __global uint * dst_qs,
690
+ __global uint * dst_qh,
691
+ __global half * dst_d,
692
+ uint ne00,
693
+ uint ne01
694
+ ) {
695
+ uint i00 = get_global_id(1);
696
+ uint i01 = get_global_id(0);
697
+ uint i02 = get_global_id(2);
698
+
699
+ if (i01 >= ne01) {
700
+ return;
701
+ }
702
+
703
+ uint ne00_blk = ne00 / QK5_0;
704
+ uint src_blk_offset = i00 + i01 * ne00_blk + i02 * ne00_blk * ne01;
705
+ uint dst_blk_offset = i01 + i00 * ne01 + i02 * ne00_blk * ne01;
706
+
707
+ global struct block_q5_0 * b = src0 + src_blk_offset;
708
+ dst_d[dst_blk_offset] = b->d;
709
+
710
+ dst_qh[dst_blk_offset] = ((global uint *)(&(b->qh[0])))[0];
711
+
712
+ // extract quantization and unshuffle
713
+ ushort8 pre_block = ((global ushort8 *)(&(b->qs[0])))[0];
714
+ ushort8 post_block = (ushort8)(0);
715
+
716
+ uchar * pre_block_ptr = (uchar *)(&pre_block);
717
+ uchar * post_block_ptr = (uchar *)(&post_block);
718
+
719
+ for (int i = 0; i < QK5_0 / 4; ++i) {
720
+ uchar x0 = pre_block_ptr[2*i + 0];
721
+ uchar x1 = pre_block_ptr[2*i + 1];
722
+
723
+ post_block_ptr[i + 0 ] = convert_uchar(x0 & 0x0F) | convert_uchar((x1 & 0x0F) << 4);
724
+ post_block_ptr[i + QK5_0 / 4] = convert_uchar((x0 & 0xF0) >> 4) | convert_uchar(x1 & 0xF0);
725
+ }
726
+
727
+ uint4 q_block = as_uint4(post_block);
728
+
729
+ uint offset = i02 * ne00_blk * ne01 * 4 + i00 * ne01 * 4 + i01;
730
+ dst_qs[offset] = q_block.x;
731
+ dst_qs[offset + ne01] = q_block.y;
732
+ dst_qs[offset + ne01 * 2] = q_block.z;
733
+ dst_qs[offset + ne01 * 3] = q_block.w;
734
+ }
735
+
736
+ kernel void kernel_restore_block_q5_0_trans4_ns(
737
+ __global uint * src_qs,
738
+ __global uint * src_qh,
739
+ __global half * src_d,
740
+ __global struct block_q5_0 * dst0,
741
+ uint ne00,
742
+ uint ne01
743
+ ) {
744
+ int i00 = get_global_id(1);
745
+ uint i01 = get_global_id(0);
746
+ uint i02 = get_global_id(2);
747
+
748
+ if (i01 >= ne01) {
749
+ return;
750
+ }
751
+
752
+ uint ne00_blk = ne00 / QK5_0;
753
+ uint dst_blk_offset = i00 + i01 * ne00_blk + i02 * ne00_blk * ne01;
754
+ uint src_blk_offset = i01 + i00 * ne01 + i02 * ne00_blk * ne01;
755
+
756
+ __global struct block_q5_0 * b = dst0 + dst_blk_offset;
757
+ b->d = src_d[src_blk_offset];
758
+
759
+ ((__global uint *)(&(b->qh[0])))[0] = src_qh[src_blk_offset];
760
+
761
+ // collect transposed quantization parts for a block
762
+ uint src_q_offset = i02 * ne00_blk * ne01 * 4 + i00 * ne01 * 4 + i01;
763
+ uint4 q_block;
764
+ q_block.x = src_qs[src_q_offset];
765
+ q_block.y = src_qs[src_q_offset + ne01];
766
+ q_block.z = src_qs[src_q_offset + ne01 * 2];
767
+ q_block.w = src_qs[src_q_offset + ne01 * 3];
768
+
769
+ ushort8 post_block = as_ushort8(q_block);
770
+ ushort8 pre_block = (ushort8)(0);
771
+
772
+ uchar * pre_block_ptr = (uchar *)(&pre_block);
773
+ uchar * post_block_ptr = (uchar *)(&post_block);
774
+
775
+ for (int i = 0; i < QK5_0 / 4; ++i) {
776
+ uchar x0 = post_block_ptr[i + 0];
777
+ uchar x1 = post_block_ptr[i + QK5_0 / 4];
778
+
779
+ pre_block_ptr[2 * i + 0] = convert_uchar(x0 & 0x0F) | convert_uchar((x1 & 0x0F) << 4);
780
+ pre_block_ptr[2 * i + 1] = convert_uchar((x0 & 0xF0) >> 4) | convert_uchar(x1 & 0xF0);
781
+ }
782
+
783
+ ((__global ushort8 *)(&(b->qs[0])))[0] = pre_block;
784
+ }
785
+
786
+ //------------------------------------------------------------------------------
787
+ // kernel_convert_block_q5_1
788
+ // Convert the block_q5_1 format to 4 separate arrays (AOS -> SOA).
789
+ // This kernel does not deshuffle the bits.
790
+ //------------------------------------------------------------------------------
791
+ kernel void kernel_convert_block_q5_1(
792
+ global struct block_q5_1 * src0,
793
+ global uchar * dst_qs,
794
+ global uint * dst_qh,
795
+ global half * dst_d,
796
+ global half * dst_m,
797
+ ulong n_blk
798
+ ) {
799
+ if (get_global_id(0) >= n_blk) {
800
+ return;
801
+ }
802
+
803
+ global struct block_q5_1 * b = (global struct block_q5_1 *) src0 + get_global_id(0);
804
+ global uchar * qs = (global uchar *) dst_qs + (QK5_1/2)*get_global_id(0);
805
+ global uint * qh = (global uint *) dst_qh + get_global_id(0);
806
+ global half * d = (global half *) dst_d + get_global_id(0);
807
+ global half * m = (global half *) dst_m + get_global_id(0);
808
+
809
+ *d = b->d;
810
+ *m = b->m;
811
+ *qh = *((global uint *)(b->qh));
812
+
813
+ for (int i = 0; i < QK5_1/2; ++i) {
814
+ qs[i] = b->qs[i];
815
+ }
816
+ }
817
+
818
+ kernel void kernel_restore_block_q5_1(
819
+ global uchar * src_qs,
820
+ global uint * src_qh,
821
+ global half * src_d,
822
+ global half * src_m,
823
+ global struct block_q5_1 * dst
824
+ ) {
825
+ global struct block_q5_1 * b = (global struct block_q5_1 *) dst + get_global_id(0);
826
+ global uchar * qs = (global uchar *) src_qs + (QK5_1/2)*get_global_id(0);
827
+ global uint * qh = (global uint *) src_qh + get_global_id(0);
828
+ global half * d = (global half *) src_d + get_global_id(0);
829
+ global half * m = (global half *) src_m + get_global_id(0);
830
+
831
+ b->d = *d;
832
+ b->m = *m;
833
+ *((global uint *)(b->qh)) = *qh;
834
+ for (int i = 0; i < QK5_1/2; ++i) {
835
+ b->qs[i] = qs[i];
836
+ }
837
+ }
838
+
839
+ kernel void kernel_convert_block_q5_1_noshuffle(
840
+ global struct block_q5_1 * src0,
841
+ global uchar * dst_q,
842
+ global uint * dst_qh,
843
+ global half * dst_d,
844
+ global half * dst_m
845
+ ) {
846
+ global struct block_q5_1 * b = (global struct block_q5_1 *) src0 + get_global_id(0);
847
+ global uchar * q = (global uchar *) dst_q + QK5_1/2*get_global_id(0);
848
+ global uint * qh = (global uint *) dst_qh + get_global_id(0);
849
+ global half * d = (global half *) dst_d + get_global_id(0);
850
+ global half * m = (global half *) dst_m + get_global_id(0);
851
+
852
+ *d = b->d;
853
+ *m = b->m;
854
+ *qh = *((global uint *)(b->qh));
855
+
856
+ for (int i = 0; i < QK5_1/4; ++i) {
857
+ uchar x0 = b->qs[2*i + 0];
858
+ uchar x1 = b->qs[2*i + 1];
859
+
860
+ q[i + 0 ] = convert_uchar(x0 & 0x0F) | convert_uchar((x1 & 0x0F) << 4);
861
+ q[i + QK5_1/4] = convert_uchar((x0 & 0xF0) >> 4) | convert_uchar(x1 & 0xF0);
862
+
863
+ #ifdef ADRENO_GPU
864
+ if (get_global_id(0) == 65536*4096) {
865
+ printf("%04x - %02x\n", *(global ushort*)d, ((x0 & 0xF0) >> 4) | (x1 & 0xF0));
866
+ }
867
+ #endif
868
+ }
869
+ }
870
+
871
+ kernel void kernel_restore_block_q5_1_noshuffle(
872
+ global uchar * src_q,
873
+ global uint * src_qh,
874
+ global half * src_d,
875
+ global half * src_m,
876
+ global struct block_q5_1 * dst,
877
+ uchar mask_0F,
878
+ uchar mask_F0
879
+ ) {
880
+ global struct block_q5_1 * b = (global struct block_q5_1 *) dst + get_global_id(0);
881
+ global uchar * q = (global uchar *) src_q + QK5_1/2*get_global_id(0);
882
+ global uint * qh = (global uint *) src_qh + get_global_id(0);
883
+ global half * d = (global half *) src_d + get_global_id(0);
884
+ global half * m = (global half *) src_m + get_global_id(0);
885
+
886
+ b->d = *d;
887
+ b->m = *m;
888
+ *((global uint *)(b->qh)) = *qh;
889
+
890
+ for (int i = 0; i < QK5_1/4; ++i) {
891
+ uchar x0 = q[i + 0 ];
892
+ uchar x1 = q[i + QK5_1/4];
893
+
894
+ b->qs[2*i + 0] = convert_uchar((x0 & mask_0F) | ((x1 & mask_0F) << 4));
895
+ b->qs[2*i + 1] = convert_uchar(((x0 & mask_F0) >> 4) | (x1 & mask_F0));
896
+ }
897
+ }
898
+
899
+ kernel void kernel_convert_block_q5_1_trans4_ns(
900
+ __global struct block_q5_1 * src0,
901
+ __global uint * dst_qs,
902
+ __global uint * dst_qh,
903
+ __global half * dst_d,
904
+ __global half * dst_m,
905
+ uint ne00,
906
+ uint ne01
907
+ ) {
908
+ uint i00 = get_global_id(1);
909
+ uint i01 = get_global_id(0);
910
+ uint i02 = get_global_id(2);
911
+
912
+ if (i01 >= ne01) {
913
+ return;
914
+ }
915
+
916
+ uint ne00_blk = ne00 / QK5_1;
917
+ uint src_blk_offset = i00 + i01 * ne00_blk + i02 * ne00_blk * ne01;
918
+ uint dst_blk_offset = i01 + i00 * ne01 + i02 * ne00_blk * ne01;
919
+
920
+ global struct block_q5_1 * b = src0 + src_blk_offset;
921
+ dst_d[dst_blk_offset] = b->d;
922
+ dst_m[dst_blk_offset] = b->m;
923
+
924
+ dst_qh[dst_blk_offset] = ((global uint *)(&(b->qh[0])))[0];
925
+
926
+ // extract quantization and unshuffle
927
+ ushort8 pre_block = ((global ushort8 *)(&(b->qs[0])))[0];
928
+ ushort8 post_block = (ushort8)(0);
929
+
930
+ uchar * pre_block_ptr = (uchar *)(&pre_block);
931
+ uchar * post_block_ptr = (uchar *)(&post_block);
932
+
933
+ for (int i = 0; i < QK5_1 / 4; ++i) {
934
+ uchar x0 = pre_block_ptr[2*i + 0];
935
+ uchar x1 = pre_block_ptr[2*i + 1];
936
+
937
+ post_block_ptr[i + 0 ] = convert_uchar(x0 & 0x0F) | convert_uchar((x1 & 0x0F) << 4);
938
+ post_block_ptr[i + QK5_1 / 4] = convert_uchar((x0 & 0xF0) >> 4) | convert_uchar(x1 & 0xF0);
939
+ }
940
+
941
+ uint4 q_block = as_uint4(post_block);
942
+
943
+ uint offset = i02 * ne00_blk * ne01 * 4 + i00 * ne01 * 4 + i01;
944
+ dst_qs[offset] = q_block.x;
945
+ dst_qs[offset + ne01] = q_block.y;
946
+ dst_qs[offset + ne01 * 2] = q_block.z;
947
+ dst_qs[offset + ne01 * 3] = q_block.w;
948
+ }
949
+
950
+ kernel void kernel_restore_block_q5_1_trans4_ns(
951
+ __global uint * src_qs,
952
+ __global uint * src_qh,
953
+ __global half * src_d,
954
+ __global half * src_m,
955
+ __global struct block_q5_1 * dst0,
956
+ uint ne00,
957
+ uint ne01
958
+ ) {
959
+ int i00 = get_global_id(1);
960
+ uint i01 = get_global_id(0);
961
+ uint i02 = get_global_id(2);
962
+
963
+ if (i01 >= ne01) {
964
+ return;
965
+ }
966
+
967
+ uint ne00_blk = ne00 / QK5_1;
968
+ uint dst_blk_offset = i00 + i01 * ne00_blk + i02 * ne00_blk * ne01;
969
+ uint src_blk_offset = i01 + i00 * ne01 + i02 * ne00_blk * ne01;
970
+
971
+ __global struct block_q5_1 * b = dst0 + dst_blk_offset;
972
+ b->d = src_d[src_blk_offset];
973
+ b->m = src_m[src_blk_offset];
974
+
975
+ ((__global uint *)(&(b->qh[0])))[0] = src_qh[src_blk_offset];
976
+
977
+ // collect transposed quantization parts for a block
978
+ uint src_q_offset = i02 * ne00_blk * ne01 * 4 + i00 * ne01 * 4 + i01;
979
+ uint4 q_block;
980
+ q_block.x = src_qs[src_q_offset];
981
+ q_block.y = src_qs[src_q_offset + ne01];
982
+ q_block.z = src_qs[src_q_offset + ne01 * 2];
983
+ q_block.w = src_qs[src_q_offset + ne01 * 3];
984
+
985
+ ushort8 post_block = as_ushort8(q_block);
986
+ ushort8 pre_block = (ushort8)(0);
987
+
988
+ uchar * pre_block_ptr = (uchar *)(&pre_block);
989
+ uchar * post_block_ptr = (uchar *)(&post_block);
990
+
991
+ for (int i = 0; i < QK5_1 / 4; ++i) {
992
+ uchar x0 = post_block_ptr[i + 0];
993
+ uchar x1 = post_block_ptr[i + QK5_1 / 4];
994
+
995
+ pre_block_ptr[2 * i + 0] = convert_uchar(x0 & 0x0F) | convert_uchar((x1 & 0x0F) << 4);
996
+ pre_block_ptr[2 * i + 1] = convert_uchar((x0 & 0xF0) >> 4) | convert_uchar(x1 & 0xF0);
997
+ }
998
+ ((__global ushort8 *)(&(b->qs[0])))[0] = pre_block;
999
+ }
1000
+
1001
+ kernel void kernel_convert_block_q4_k_trans4_ns(
1002
+ __global struct block_q4_K * src0,
1003
+ __global uint * dst_q,
1004
+ __global half * dst_d,
1005
+ __global half * dst_dm,
1006
+ __global uchar * dst_s,
1007
+ uint ne00,
1008
+ uint ne01,
1009
+ uchar mask_0F,
1010
+ uchar mask_F0
1011
+ ) {
1012
+ uint i00 = get_global_id(1);
1013
+ uint i01 = get_global_id(0);
1014
+ uint i02 = get_global_id(2);
1015
+
1016
+ if (i01 >= ne01) {
1017
+ return;
1018
+ }
1019
+
1020
+ uint ne00_blk = ne00 / QK_K;
1021
+ uint src_blk_offset = i00 + i01 * ne00_blk + i02 * ne00_blk * ne01;
1022
+ uint dst_blk_offset = i01 + i00 * ne01 + i02 * ne00_blk * ne01;
1023
+
1024
+ __global struct block_q4_K * b = src0 + src_blk_offset;
1025
+
1026
+ dst_d [dst_blk_offset] = b->d;
1027
+ dst_dm[dst_blk_offset] = b->dm;
1028
+
1029
+ uint4 qv[8];
1030
+ uchar * qv_bytes = (uchar *)qv;
1031
+ for (int i = 0; i < QK_K / 64; ++i) {
1032
+ for (int j = 0; j < 16; ++j) {
1033
+ uchar x0 = b->q[i*32 + 2*j];
1034
+ uchar x1 = b->q[i*32 + 2*j + 1];
1035
+
1036
+ qv_bytes[i*32 + j ] = convert_uchar(x0 & mask_0F) | convert_uchar((x1 & mask_0F) << 4);
1037
+ qv_bytes[i*32 + j + 16] = convert_uchar((x0 & mask_F0) >> 4) | convert_uchar(x1 & mask_F0);
1038
+ }
1039
+ }
1040
+
1041
+ uint base = i02 * ne00_blk * ne01 * 32 + i00 * ne01 * 32 + i01;
1042
+ #pragma unroll
1043
+ for (int p = 0; p < 8; ++p) {
1044
+ uint4 v = qv[p];
1045
+ dst_q[base + (p * 4 + 0) * ne01] = v.x;
1046
+ dst_q[base + (p * 4 + 1) * ne01] = v.y;
1047
+ dst_q[base + (p * 4 + 2) * ne01] = v.z;
1048
+ dst_q[base + (p * 4 + 3) * ne01] = v.w;
1049
+ }
1050
+
1051
+ __global uchar * s_dst = dst_s + (i02 * ne01 + i01) * ne00_blk * K_SCALE_SIZE + i00 * K_SCALE_SIZE;
1052
+ #pragma unroll
1053
+ for (int i = 0; i < K_SCALE_SIZE; ++i) {
1054
+ s_dst[i] = b->s[i];
1055
+ }
1056
+ }
1057
+
1058
+ kernel void kernel_restore_block_q4_k_trans4_ns(
1059
+ __global uint * src_q,
1060
+ __global half * src_d,
1061
+ __global half * src_dm,
1062
+ __global uchar * src_s,
1063
+ __global struct block_q4_K * dst0,
1064
+ uint ne00,
1065
+ uint ne01,
1066
+ uchar mask_0F,
1067
+ uchar mask_F0
1068
+ ) {
1069
+ uint i00 = get_global_id(1); // block index along K
1070
+ uint i01 = get_global_id(0); // row index
1071
+ uint i02 = get_global_id(2); // batch index
1072
+
1073
+ if (i01 >= ne01) {
1074
+ return;
1075
+ }
1076
+
1077
+ uint ne00_blk = ne00 / QK_K;
1078
+
1079
+ uint src_blk_offset = i01 + i00 * ne01 + i02 * ne00_blk * ne01;
1080
+ uint dst_blk_offset = i00 + i01 * ne00_blk + i02 * ne00_blk * ne01;
1081
+
1082
+ __global struct block_q4_K * b = dst0 + dst_blk_offset;
1083
+
1084
+ b->d = src_d[src_blk_offset];
1085
+ b->dm = src_dm[src_blk_offset];
1086
+
1087
+ __global uchar * s_src = src_s + (i02 * ne01 + i01) * ne00_blk * K_SCALE_SIZE + i00 * K_SCALE_SIZE;
1088
+ for (int i = 0; i < K_SCALE_SIZE; ++i) {
1089
+ b->s[i] = s_src[i];
1090
+ }
1091
+
1092
+ uint base = i02 * ne00_blk * ne01 * 32 + i00 * ne01 * 32 + i01;
1093
+
1094
+ uint4 qv[8];
1095
+ for (int p = 0; p < 8; ++p) {
1096
+ qv[p].x = src_q[base + (p * 4 + 0) * ne01];
1097
+ qv[p].y = src_q[base + (p * 4 + 1) * ne01];
1098
+ qv[p].z = src_q[base + (p * 4 + 2) * ne01];
1099
+ qv[p].w = src_q[base + (p * 4 + 3) * ne01];
1100
+ }
1101
+
1102
+ uchar * qv_bytes = (uchar *)qv;
1103
+ for (int i = 0; i < QK_K / 64; ++i) {
1104
+ for (int j = 0; j < 16; ++j) {
1105
+ uchar lo = qv_bytes[i*32 + j];
1106
+ uchar hi = qv_bytes[i*32 + j + 16];
1107
+ b->q[i*32 + 2*j] = convert_uchar((lo & mask_0F) | ((hi & mask_0F) << 4));
1108
+ b->q[i*32 + 2*j + 1] = convert_uchar(((lo & mask_F0) >> 4) | (hi & mask_F0));
1109
+ }
1110
+ }
1111
+ }
1112
+
1113
+ kernel void kernel_convert_block_q5_k_trans4_ns(
1114
+ __global struct block_q5_K * src0,
1115
+ __global uint * dst_qs,
1116
+ __global uint * dst_qh,
1117
+ __global half * dst_d,
1118
+ __global half * dst_dm,
1119
+ __global uchar * dst_s,
1120
+ uint ne00,
1121
+ uint ne01,
1122
+ uchar mask_0F,
1123
+ uchar mask_F0
1124
+ ) {
1125
+ uint i00 = get_global_id(1);
1126
+ uint i01 = get_global_id(0);
1127
+ uint i02 = get_global_id(2);
1128
+
1129
+ if (i01 >= ne01) {
1130
+ return;
1131
+ }
1132
+
1133
+ uint ne00_blk = ne00 / QK_K;
1134
+ uint src_blk_offset = i00 + i01 * ne00_blk + i02 * ne00_blk * ne01;
1135
+ uint dst_blk_offset = i01 + i00 * ne01 + i02 * ne00_blk * ne01;
1136
+
1137
+ __global struct block_q5_K * b = src0 + src_blk_offset;
1138
+
1139
+ dst_d [dst_blk_offset] = b->d;
1140
+ dst_dm[dst_blk_offset] = b->dm;
1141
+
1142
+ for (int k = 0; k < 8; k++) {
1143
+ uchar b0 = 0, b1 = 0, b2 = 0, b3 = 0;
1144
+ for (int bit = 0; bit < 8; bit++) {
1145
+ b0 |= (uchar)(((b->qh[bit] >> k) & 1) << bit);
1146
+ b1 |= (uchar)(((b->qh[8 + bit] >> k) & 1) << bit);
1147
+ b2 |= (uchar)(((b->qh[16 + bit] >> k) & 1) << bit);
1148
+ b3 |= (uchar)(((b->qh[24 + bit] >> k) & 1) << bit);
1149
+ }
1150
+ uint packed = (uint)b0 | ((uint)b1 << 8) | ((uint)b2 << 16) | ((uint)b3 << 24);
1151
+ dst_qh[i01 + (i00 * 8 + k) * ne01 + i02 * ne00_blk * 8 * ne01] = packed;
1152
+ }
1153
+
1154
+ uint4 qv[8];
1155
+ uchar * qv_bytes = (uchar *)qv;
1156
+ for (int i = 0; i < QK_K / 64; ++i) {
1157
+ for (int j = 0; j < 16; ++j) {
1158
+ uchar x0 = b->qs[i*32 + 2*j];
1159
+ uchar x1 = b->qs[i*32 + 2*j + 1];
1160
+
1161
+ qv_bytes[i*32 + j ] = convert_uchar(x0 & mask_0F) | convert_uchar((x1 & mask_0F) << 4);
1162
+ qv_bytes[i*32 + j + 16] = convert_uchar((x0 & mask_F0) >> 4) | convert_uchar(x1 & mask_F0);
1163
+ }
1164
+ }
1165
+
1166
+ uint base = i02 * ne00_blk * ne01 * 32 + i00 * ne01 * 32 + i01;
1167
+ #pragma unroll
1168
+ for (int p = 0; p < 8; ++p) {
1169
+ uint4 v = qv[p];
1170
+ dst_qs[base + (p * 4 + 0) * ne01] = v.x;
1171
+ dst_qs[base + (p * 4 + 1) * ne01] = v.y;
1172
+ dst_qs[base + (p * 4 + 2) * ne01] = v.z;
1173
+ dst_qs[base + (p * 4 + 3) * ne01] = v.w;
1174
+ }
1175
+
1176
+ __global uchar * s_dst = dst_s + (i02 * ne01 + i01) * ne00_blk * K_SCALE_SIZE + i00 * K_SCALE_SIZE;
1177
+ #pragma unroll
1178
+ for (int i = 0; i < K_SCALE_SIZE; ++i) {
1179
+ s_dst[i] = b->s[i];
1180
+ }
1181
+ }
1182
+
1183
+ kernel void kernel_restore_block_q5_k_trans4_ns(
1184
+ __global uint * src_qs,
1185
+ __global uint * src_qh,
1186
+ __global half * src_d,
1187
+ __global half * src_dm,
1188
+ __global uchar * src_s,
1189
+ __global struct block_q5_K * dst0,
1190
+ uint ne00,
1191
+ uint ne01,
1192
+ uchar mask_0F,
1193
+ uchar mask_F0
1194
+ ) {
1195
+ uint i00 = get_global_id(1); // block index along K
1196
+ uint i01 = get_global_id(0); // row index
1197
+ uint i02 = get_global_id(2); // batch index
1198
+
1199
+ if (i01 >= ne01) {
1200
+ return;
1201
+ }
1202
+
1203
+ uint ne00_blk = ne00 / QK_K;
1204
+
1205
+ uint src_blk_offset = i01 + i00 * ne01 + i02 * ne00_blk * ne01;
1206
+ uint dst_blk_offset = i00 + i01 * ne00_blk + i02 * ne00_blk * ne01;
1207
+
1208
+ __global struct block_q5_K * b = dst0 + dst_blk_offset;
1209
+
1210
+ b->d = src_d[src_blk_offset];
1211
+ b->dm = src_dm[src_blk_offset];
1212
+
1213
+ for (int j = 0; j < 32; j++) b->qh[j] = 0;
1214
+ for (int k = 0; k < 8; k++) {
1215
+ uint packed = src_qh[i01 + (i00 * 8 + k) * ne01 + i02 * ne00_blk * 8 * ne01];
1216
+ uchar b0 = (uchar)(packed & 0xFF);
1217
+ uchar b1 = (uchar)((packed >> 8) & 0xFF);
1218
+ uchar b2 = (uchar)((packed >> 16) & 0xFF);
1219
+ uchar b3 = (uchar)((packed >> 24) & 0xFF);
1220
+ for (int bit = 0; bit < 8; bit++) {
1221
+ b->qh[bit] |= (uchar)(((b0 >> bit) & 1) << k);
1222
+ b->qh[8 + bit] |= (uchar)(((b1 >> bit) & 1) << k);
1223
+ b->qh[16 + bit] |= (uchar)(((b2 >> bit) & 1) << k);
1224
+ b->qh[24 + bit] |= (uchar)(((b3 >> bit) & 1) << k);
1225
+ }
1226
+ }
1227
+
1228
+ __global uchar * s_src = src_s + (i02 * ne01 + i01) * ne00_blk * K_SCALE_SIZE + i00 * K_SCALE_SIZE;
1229
+ for (int i = 0; i < K_SCALE_SIZE; ++i) {
1230
+ b->s[i] = s_src[i];
1231
+ }
1232
+
1233
+ uint base = i02 * ne00_blk * ne01 * 32 + i00 * ne01 * 32 + i01;
1234
+
1235
+ uint4 qv[8];
1236
+ for (int p = 0; p < 8; ++p) {
1237
+ qv[p].x = src_qs[base + (p * 4 + 0) * ne01];
1238
+ qv[p].y = src_qs[base + (p * 4 + 1) * ne01];
1239
+ qv[p].z = src_qs[base + (p * 4 + 2) * ne01];
1240
+ qv[p].w = src_qs[base + (p * 4 + 3) * ne01];
1241
+ }
1242
+
1243
+ uchar * qv_bytes = (uchar *)qv;
1244
+ for (int i = 0; i < QK_K / 64; ++i) {
1245
+ for (int j = 0; j < 16; ++j) {
1246
+ uchar lo = qv_bytes[i*32 + j];
1247
+ uchar hi = qv_bytes[i*32 + j + 16];
1248
+ b->qs[i*32 + 2*j] = convert_uchar((lo & mask_0F) | ((hi & mask_0F) << 4));
1249
+ b->qs[i*32 + 2*j + 1] = convert_uchar(((lo & mask_F0) >> 4) | (hi & mask_F0));
1250
+ }
1251
+ }
1252
+ }
1253
+
1254
+ kernel void kernel_convert_block_q6_k_trans4_ns(
1255
+ __global struct block_q6_K * src0,
1256
+ __global uint * dst_ql,
1257
+ __global uint * dst_qh,
1258
+ __global half * dst_d,
1259
+ __global char * dst_s,
1260
+ uint ne00,
1261
+ uint ne01,
1262
+ uchar mask_0F,
1263
+ uchar mask_F0
1264
+ ) {
1265
+ uint i00 = get_global_id(1);
1266
+ uint i01 = get_global_id(0);
1267
+ uint i02 = get_global_id(2);
1268
+
1269
+ if (i01 >= ne01) {
1270
+ return;
1271
+ }
1272
+
1273
+ uint ne00_blk = ne00 / QK_K;
1274
+
1275
+ uint src_blk_offset = i00 + i01 * ne00_blk + i02 * ne00_blk * ne01;
1276
+ uint dst_blk_offset = i01 + i00 * ne01 + i02 * ne00_blk * ne01;
1277
+
1278
+ __global struct block_q6_K * b = src0 + src_blk_offset;
1279
+
1280
+ dst_d[dst_blk_offset] = b->d;
1281
+
1282
+ uint4 qlv[8];
1283
+ uchar * qlv_bytes = (uchar *)qlv;
1284
+ for (int i = 0; i < 2; ++i) {
1285
+ for (int j = 0; j < 16; ++j) {
1286
+ uchar x0 = b->ql[i*64 + 2*j];
1287
+ uchar x1 = b->ql[i*64 + 2*j + 1];
1288
+ uchar x2 = b->ql[i*64 + 32 + 2*j];
1289
+ uchar x3 = b->ql[i*64 + 32 + 2*j + 1];
1290
+ qlv_bytes[i*64 + j ] = convert_uchar(x0 & mask_0F) | convert_uchar((x1 & mask_0F) << 4);
1291
+ qlv_bytes[i*64 + j + 16] = convert_uchar(x2 & mask_0F) | convert_uchar((x3 & mask_0F) << 4);
1292
+ qlv_bytes[i*64 + j + 32] = convert_uchar((x0 & mask_F0) >> 4) | convert_uchar(x1 & mask_F0);
1293
+ qlv_bytes[i*64 + j + 48] = convert_uchar((x2 & mask_F0) >> 4) | convert_uchar(x3 & mask_F0);
1294
+ }
1295
+ }
1296
+
1297
+ uint ql_base = i02 * ne00_blk * ne01 * 32 + i00 * ne01 * 32 + i01;
1298
+
1299
+ #pragma unroll
1300
+ for (int p = 0; p < 8; ++p) {
1301
+ uint4 v = qlv[p];
1302
+ dst_ql[ql_base + (p * 4 + 0) * ne01] = v.x;
1303
+ dst_ql[ql_base + (p * 4 + 1) * ne01] = v.y;
1304
+ dst_ql[ql_base + (p * 4 + 2) * ne01] = v.z;
1305
+ dst_ql[ql_base + (p * 4 + 3) * ne01] = v.w;
1306
+ }
1307
+
1308
+ uint qhv[16] = {0};
1309
+
1310
+ for (int n = 0; n < 2; ++n) {
1311
+ for (int l = 0; l < 32; ++l) {
1312
+ uchar h = b->qh[n*32 + l];
1313
+ int u = l / 16;
1314
+ int bit_pos = (l % 16) * 2;
1315
+ qhv[(n*4 + 0)*2 + u] |= ((uint)((h >> 0) & 0x03)) << bit_pos;
1316
+ qhv[(n*4 + 1)*2 + u] |= ((uint)((h >> 2) & 0x03)) << bit_pos;
1317
+ qhv[(n*4 + 2)*2 + u] |= ((uint)((h >> 4) & 0x03)) << bit_pos;
1318
+ qhv[(n*4 + 3)*2 + u] |= ((uint)((h >> 6) & 0x03)) << bit_pos;
1319
+ }
1320
+ }
1321
+
1322
+ uint qh_base = i02 * ne00_blk * ne01 * 16 + i00 * ne01 * 16 + i01;
1323
+
1324
+ for (int p = 0; p < 16; ++p) {
1325
+ dst_qh[qh_base + p * ne01] = qhv[p];
1326
+ }
1327
+
1328
+ __global char * s_dst = dst_s + (i02 * ne01 + i01) * ne00_blk * 16 + i00 * 16;
1329
+ #pragma unroll
1330
+ for (int i = 0; i < 16; ++i) {
1331
+ s_dst[i] = b->scales[i];
1332
+ }
1333
+ }
1334
+
1335
+ kernel void kernel_restore_block_q6_k_trans4_ns(
1336
+ __global uint * src_ql,
1337
+ __global uint * src_qh,
1338
+ __global half * src_d,
1339
+ __global char * src_s,
1340
+ __global struct block_q6_K * dst0,
1341
+ uint ne00,
1342
+ uint ne01,
1343
+ uchar mask_0F,
1344
+ uchar mask_F0
1345
+ ) {
1346
+ uint i00 = get_global_id(1); // block index along K
1347
+ uint i01 = get_global_id(0); // row index
1348
+ uint i02 = get_global_id(2); // batch index
1349
+
1350
+ if (i01 >= ne01) {
1351
+ return;
1352
+ }
1353
+
1354
+ uint ne00_blk = ne00 / QK_K;
1355
+
1356
+ uint src_blk_offset = i01 + i00 * ne01 + i02 * ne00_blk * ne01;
1357
+ uint dst_blk_offset = i00 + i01 * ne00_blk + i02 * ne00_blk * ne01;
1358
+
1359
+ __global struct block_q6_K * b = dst0 + dst_blk_offset;
1360
+
1361
+ b->d = src_d[src_blk_offset];
1362
+
1363
+ uint ql_base = i02 * ne00_blk * ne01 * 32 + i00 * ne01 * 32 + i01;
1364
+ uint4 qlv[8];
1365
+ for (int p = 0; p < 8; ++p) {
1366
+ qlv[p].x = src_ql[ql_base + (p * 4 + 0) * ne01];
1367
+ qlv[p].y = src_ql[ql_base + (p * 4 + 1) * ne01];
1368
+ qlv[p].z = src_ql[ql_base + (p * 4 + 2) * ne01];
1369
+ qlv[p].w = src_ql[ql_base + (p * 4 + 3) * ne01];
1370
+ }
1371
+
1372
+ uchar * qlv_bytes = (uchar *)qlv;
1373
+ for (int i = 0; i < 2; ++i) {
1374
+ for (int j = 0; j < 16; ++j) {
1375
+ uchar lo_02 = qlv_bytes[i*64 + j];
1376
+ uchar lo_13 = qlv_bytes[i*64 + j + 16];
1377
+ uchar hi_02 = qlv_bytes[i*64 + j + 32];
1378
+ uchar hi_13 = qlv_bytes[i*64 + j + 48];
1379
+ b->ql[i*64 + 2*j] = convert_uchar((lo_02 & mask_0F) | ((hi_02 & mask_0F) << 4));
1380
+ b->ql[i*64 + 2*j + 1] = convert_uchar(((lo_02 & mask_F0) >> 4) | (hi_02 & mask_F0));
1381
+ b->ql[i*64 + 32 + 2*j] = convert_uchar((lo_13 & mask_0F) | ((hi_13 & mask_0F) << 4));
1382
+ b->ql[i*64 + 32 + 2*j + 1] = convert_uchar(((lo_13 & mask_F0) >> 4) | (hi_13 & mask_F0));
1383
+ }
1384
+ }
1385
+
1386
+ uint qh_base = i02 * ne00_blk * ne01 * 16 + i00 * ne01 * 16 + i01;
1387
+ uint qhv[16];
1388
+ for (int p = 0; p < 16; ++p) {
1389
+ qhv[p] = src_qh[qh_base + p * ne01];
1390
+ }
1391
+
1392
+ for (int n = 0; n < 2; ++n) {
1393
+ for (int l = 0; l < 32; ++l) {
1394
+ int u = l / 16;
1395
+ int bit_pos = (l % 16) * 2;
1396
+ uchar v0 = (uchar)((qhv[(n*4 + 0)*2 + u] >> bit_pos) & 0x03);
1397
+ uchar v1 = (uchar)((qhv[(n*4 + 1)*2 + u] >> bit_pos) & 0x03);
1398
+ uchar v2 = (uchar)((qhv[(n*4 + 2)*2 + u] >> bit_pos) & 0x03);
1399
+ uchar v3 = (uchar)((qhv[(n*4 + 3)*2 + u] >> bit_pos) & 0x03);
1400
+ b->qh[n*32 + l] = v0 | (v1 << 2) | (v2 << 4) | (v3 << 6);
1401
+ }
1402
+ }
1403
+
1404
+ __global char * s_src = src_s + (i02 * ne01 + i01) * ne00_blk * 16 + i00 * 16;
1405
+ for (int i = 0; i < 16; ++i) {
1406
+ b->scales[i] = s_src[i];
1407
+ }
1408
+ }
1409
+
1410
+ //------------------------------------------------------------------------------
1411
+ // block_mxfp4
1412
+ //------------------------------------------------------------------------------
1413
+ #define QK_MXFP4 32
1414
+ struct block_mxfp4 {
1415
+ uchar e; // E8M0
1416
+ uchar qs[QK_MXFP4 / 2];
1417
+ };
1418
+
1419
+ //------------------------------------------------------------------------------
1420
+ // kernel_convert_block_mxfp4
1421
+ // Convert the block_mxfp4 format to 2 separate arrays (AOS -> SOA).
1422
+ // This kernel does not deshuffle the bits.
1423
+ //------------------------------------------------------------------------------
1424
+ kernel void kernel_convert_block_mxfp4(
1425
+ global struct block_mxfp4 * src0,
1426
+ global uchar * dst_q,
1427
+ global uchar * dst_e
1428
+ ) {
1429
+ global struct block_mxfp4 * b = (global struct block_mxfp4 *) src0 + get_global_id(0);
1430
+ global uchar * q = (global uchar *) dst_q + QK_MXFP4 / 2 * get_global_id(0);
1431
+ global uchar * e = (global uchar *) dst_e + get_global_id(0);
1432
+
1433
+ *e = b->e;
1434
+
1435
+ for (int i = 0; i < QK_MXFP4 / 2; ++i) {
1436
+ q[i] = b->qs[i];
1437
+ }
1438
+ }
1439
+
1440
+ kernel void kernel_convert_block_mxfp4_trans(
1441
+ global struct block_mxfp4 * src0,
1442
+ __global uint4 * dst_q,
1443
+ __global uchar * dst_e,
1444
+ uint ne00,
1445
+ uint ne01
1446
+ ) {
1447
+ int i00 = get_global_id(1);
1448
+ uint i01 = get_global_id(0);
1449
+ uint i02 = get_global_id(2);
1450
+
1451
+ uint ne00_blk = ne00 / QK_MXFP4;
1452
+ uint src_blk_offset = i00 + i01 * ne00_blk + i02 * ne00_blk * ne01;
1453
+ uint dst_blk_offset = i01 + i00 * ne01 + i02 * ne00_blk * ne01;
1454
+
1455
+ global struct block_mxfp4 * b = src0 + src_blk_offset;
1456
+
1457
+ dst_q[dst_blk_offset] = ((global uint4 *)(&(b->qs[0])))[0];
1458
+ dst_e[dst_blk_offset] = b->e;
1459
+ }
1460
+
1461
+ kernel void kernel_restore_block_mxfp4(
1462
+ global uchar * src_q,
1463
+ global half * src_e,
1464
+ global struct block_mxfp4 * dst
1465
+ ) {
1466
+ global struct block_mxfp4 * b = (global struct block_mxfp4 *) dst + get_global_id(0);
1467
+ global uchar * q = (global uchar *) src_q + QK_MXFP4 / 2 * get_global_id(0);
1468
+ global uchar * e = (global uchar *) src_e + get_global_id(0);
1469
+
1470
+ b->e = *e;
1471
+ for (int i = 0; i < QK_MXFP4 / 2; ++i) {
1472
+ b->qs[i] = q[i];
1473
+ }
1474
+ }
1475
+
1476
+ kernel void kernel_restore_block_mxfp4_trans(
1477
+ __global uint4 * src_q,
1478
+ __global uchar * src_e,
1479
+ global struct block_mxfp4 * dst,
1480
+ uint ne00,
1481
+ uint ne01
1482
+ ) {
1483
+ int i00 = get_global_id(1);
1484
+ uint i01 = get_global_id(0);
1485
+ uint i02 = get_global_id(2);
1486
+
1487
+ uint ne00_blk = ne00 / QK_MXFP4;
1488
+ uint src_blk_offset = i01 + i00 * ne01 + i02 * ne00_blk * ne01;
1489
+ uint dst_blk_offset = i00 + i01 * ne00_blk + i02 * ne00_blk * ne01;
1490
+
1491
+ global struct block_mxfp4 * b = dst + dst_blk_offset;
1492
+
1493
+ ((global uint4 *)(&(b->qs[0])))[0] = src_q[src_blk_offset];
1494
+ b->e = src_e[src_blk_offset];
1495
+ }
1496
+
1497
+ kernel void kernel_convert_block_mxfp4_trans4_ns(
1498
+ global struct block_mxfp4 * src0,
1499
+ __global uint * dst_q,
1500
+ __global uchar * dst_e,
1501
+ uint ne00,
1502
+ uint ne01
1503
+ ) {
1504
+ uint i00 = get_global_id(1);
1505
+ uint i01 = get_global_id(0);
1506
+ uint i02 = get_global_id(2);
1507
+
1508
+ if (i01 >= ne01) {
1509
+ return;
1510
+ }
1511
+
1512
+ uint ne00_blk = ne00 / QK_MXFP4;
1513
+ uint src_blk_offset = i00 + i01 * ne00_blk + i02 * ne00_blk * ne01;
1514
+ uint dst_blk_offset = i01 + i00 * ne01 + i02 * ne00_blk * ne01;
1515
+
1516
+ global struct block_mxfp4 * b = src0 + src_blk_offset;
1517
+ dst_e[dst_blk_offset] = b->e;
1518
+
1519
+ // extract quantization and unshuffle
1520
+ ushort8 pre_block = ((global ushort8 *)(&(b->qs[0])))[0];
1521
+
1522
+ ushort8 post_block = (ushort8)(0);
1523
+
1524
+ uchar * pre_block_ptr = (uchar *)(&pre_block);
1525
+ uchar * post_block_ptr = (uchar *)(&post_block);
1526
+
1527
+ for (int i = 0; i < QK_MXFP4 / 4; ++i) {
1528
+ uchar x0 = pre_block_ptr[2*i + 0];
1529
+ uchar x1 = pre_block_ptr[2*i + 1];
1530
+
1531
+ post_block_ptr[i + 0 ] = convert_uchar(x0 & 0x0F) | convert_uchar((x1 & 0x0F) << 4);
1532
+ post_block_ptr[i + QK_MXFP4 / 4] = convert_uchar((x0 & 0xF0) >> 4) | convert_uchar(x1 & 0xF0);
1533
+ }
1534
+
1535
+ uint4 q_block = as_uint4(post_block);
1536
+
1537
+ uint offset = i02 * ne00_blk * ne01 * 4 + i00 * ne01 * 4 + i01;
1538
+ dst_q[offset] = q_block.x;
1539
+ dst_q[offset + ne01] = q_block.y;
1540
+ dst_q[offset + ne01 * 2] = q_block.z;
1541
+ dst_q[offset + ne01 * 3] = q_block.w;
1542
+ }
1543
+
1544
+ kernel void kernel_restore_block_mxfp4_trans4_ns(
1545
+ __global uint * src_q,
1546
+ __global uchar * src_e,
1547
+ __global struct block_mxfp4 * dst0,
1548
+ uint ne00,
1549
+ uint ne01
1550
+ ) {
1551
+ uint i00 = get_global_id(1);
1552
+ uint i01 = get_global_id(0);
1553
+ uint i02 = get_global_id(2);
1554
+
1555
+ if (i01 >= ne01) {
1556
+ return;
1557
+ }
1558
+
1559
+ uint ne00_blk = ne00 / QK_MXFP4;
1560
+ uint dst_blk_offset = i00 + i01 * ne00_blk + i02 * ne00_blk * ne01;
1561
+ uint src_d_offset = i01 + i00 * ne01 + i02 * ne00_blk * ne01;
1562
+
1563
+ __global struct block_mxfp4 * b = dst0 + dst_blk_offset;
1564
+ b->e = src_e[src_d_offset];
1565
+
1566
+ // collect transposed quantization parts for a block
1567
+ uint src_q_offset = i02 * ne00_blk * ne01 * 4 + i00 * ne01 * 4 + i01;
1568
+ uint4 q_block;
1569
+ q_block.x = src_q[src_q_offset];
1570
+ q_block.y = src_q[src_q_offset + ne01];
1571
+ q_block.z = src_q[src_q_offset + ne01 * 2];
1572
+ q_block.w = src_q[src_q_offset + ne01 * 3];
1573
+
1574
+ ushort8 post_block = as_ushort8(q_block);
1575
+ ushort8 pre_block = (ushort8)(0);
1576
+
1577
+ uchar * pre_block_ptr = (uchar *)(&pre_block);
1578
+ uchar * post_block_ptr = (uchar *)(&post_block);
1579
+
1580
+ for (int i = 0; i < QK_MXFP4 / 4; ++i) {
1581
+ uchar x0 = post_block_ptr[i + 0];
1582
+ uchar x1 = post_block_ptr[i + QK_MXFP4 / 4];
1583
+
1584
+ pre_block_ptr[2 * i + 0] = convert_uchar(x0 & 0x0F) | convert_uchar((x1 & 0x0F) << 4);
1585
+ pre_block_ptr[2 * i + 1] = convert_uchar((x0 & 0xF0) >> 4) | convert_uchar(x1 & 0xF0);
1586
+ }
1587
+
1588
+ ((__global ushort8 *)(&(b->qs[0])))[0] = pre_block;
1589
+ }
1590
+
1591
+
1592
+ //------------------------------------------------------------------------------
1593
+ // block_q8_0
1594
+ //------------------------------------------------------------------------------
1595
+ typedef struct {
1596
+ half d; // delta
1597
+ char qs[QK8_0]; // quants
1598
+ } block_q8_0;
1599
+
1600
+ kernel void kernel_convert_block_q8_0(
1601
+ global block_q8_0 * src0,
1602
+ global uchar * dst_q,
1603
+ global half * dst_d
1604
+ ) {
1605
+ global block_q8_0 * b = (global block_q8_0 *) src0 + get_global_id(0);
1606
+ global uchar * q = (global uchar *) dst_q + QK8_0*get_global_id(0);
1607
+ global half * d = (global half *) dst_d + get_global_id(0);
1608
+
1609
+ *d = b->d;
1610
+
1611
+ for (int i = 0; i < QK8_0; ++i) {
1612
+ q[i] = b->qs[i];
1613
+ }
1614
+ }
1615
+
1616
+ kernel void kernel_restore_block_q8_0(
1617
+ global uchar * src_q,
1618
+ global half * src_d,
1619
+ global block_q8_0 * dst
1620
+ ) {
1621
+ global block_q8_0 * b = (global block_q8_0 *) dst + get_global_id(0);
1622
+ global uchar * q = (global uchar *) src_q + QK8_0*get_global_id(0);
1623
+ global half * d = (global half *) src_d + get_global_id(0);
1624
+
1625
+ b->d = *d;
1626
+ for (int i = 0; i < QK8_0; ++i) {
1627
+ b->qs[i] = q[i];
1628
+ }
1629
+ }
1630
+
1631
+ // View-aware AoS q8_0 -> f32 dequant (f32/f32 FA path).
1632
+ kernel void kernel_dequant_q8_0_f32_view_aos(
1633
+ global char * src,
1634
+ ulong src_offset,
1635
+ ulong src_nb1,
1636
+ ulong src_nb2,
1637
+ ulong src_nb3,
1638
+ int nblk0,
1639
+ int ne1,
1640
+ int ne2,
1641
+ int ne3,
1642
+ global float * dst
1643
+ ) {
1644
+ int blk_i0 = get_global_id(0);
1645
+ int i1 = get_global_id(1);
1646
+ int batch = get_global_id(2);
1647
+
1648
+ if (blk_i0 >= nblk0) return;
1649
+ if (i1 >= ne1) return;
1650
+
1651
+ int i2 = batch % ne2;
1652
+ int i3 = batch / ne2;
1653
+ if (i3 >= ne3) return;
1654
+
1655
+ global char * block = src + src_offset + (ulong)i3*src_nb3 + (ulong)i2*src_nb2 + (ulong)i1*src_nb1 + (ulong)blk_i0 * (2 + QK8_0);
1656
+ float d = vload_half(0, (global half *)block);
1657
+ global char * qs = block + 2;
1658
+
1659
+ ulong dst_row_base = ((ulong)i3 * ne2 * ne1 + (ulong)i2 * ne1 + (ulong)i1) * nblk0;
1660
+ global float * out = dst + (dst_row_base + blk_i0) * QK8_0;
1661
+
1662
+ for (int i = 0; i < QK8_0; ++i) {
1663
+ out[i] = d * (float)qs[i];
1664
+ }
1665
+ }
1666
+
1667
+ // View-aware AoS q8_0 -> f16 dequant. Rows tight, batch strides may be gapped.
1668
+ kernel void kernel_dequant_q8_0_f16_view_aos(
1669
+ global char * src,
1670
+ ulong src_offset,
1671
+ ulong src_nb1,
1672
+ ulong src_nb2,
1673
+ ulong src_nb3,
1674
+ int nblk0,
1675
+ int ne1,
1676
+ int ne2,
1677
+ int ne3,
1678
+ global half * dst
1679
+ ) {
1680
+ int blk_i0 = get_global_id(0);
1681
+ int i1 = get_global_id(1);
1682
+ int batch = get_global_id(2);
1683
+
1684
+ if (blk_i0 >= nblk0) return;
1685
+ if (i1 >= ne1) return;
1686
+
1687
+ int i2 = batch % ne2;
1688
+ int i3 = batch / ne2;
1689
+ if (i3 >= ne3) return;
1690
+
1691
+ global char * block = src + src_offset + (ulong)i3*src_nb3 + (ulong)i2*src_nb2 + (ulong)i1*src_nb1 + (ulong)blk_i0 * (2 + QK8_0);
1692
+ float d = vload_half(0, (global half *)block);
1693
+ global char * qs = block + 2;
1694
+
1695
+ ulong dst_row_base = ((ulong)i3 * ne2 * ne1 + (ulong)i2 * ne1 + (ulong)i1) * nblk0;
1696
+ global half * out = dst + (dst_row_base + blk_i0) * QK8_0;
1697
+
1698
+ for (int i = 0; i < QK8_0; ++i) {
1699
+ out[i] = (half)(d * (float)qs[i]);
1700
+ }
1701
+ }
1702
+
1703
+ // View-aware AoS q4_0 -> f32 dequant (mirrors the q8_0 view variant).
1704
+ kernel void kernel_dequant_q4_0_f32_view_aos(
1705
+ global char * src,
1706
+ ulong src_offset,
1707
+ ulong src_nb1,
1708
+ ulong src_nb2,
1709
+ ulong src_nb3,
1710
+ int nblk0,
1711
+ int ne1,
1712
+ int ne2,
1713
+ int ne3,
1714
+ global float * dst
1715
+ ) {
1716
+ int blk_i0 = get_global_id(0);
1717
+ int i1 = get_global_id(1);
1718
+ int batch = get_global_id(2);
1719
+
1720
+ if (blk_i0 >= nblk0) return;
1721
+ if (i1 >= ne1) return;
1722
+
1723
+ int i2 = batch % ne2;
1724
+ int i3 = batch / ne2;
1725
+ if (i3 >= ne3) return;
1726
+
1727
+ global char * block = src + src_offset + (ulong)i3*src_nb3 + (ulong)i2*src_nb2 + (ulong)i1*src_nb1 + (ulong)blk_i0 * (2 + QK4_0/2);
1728
+ float d = vload_half(0, (global half *)block);
1729
+ global uchar * qs = (global uchar *)(block + 2);
1730
+
1731
+ ulong dst_row_base = ((ulong)i3 * ne2 * ne1 + (ulong)i2 * ne1 + (ulong)i1) * nblk0;
1732
+ global float * out = dst + (dst_row_base + blk_i0) * QK4_0;
1733
+
1734
+ for (int i = 0; i < QK4_0/2; ++i) {
1735
+ uchar byte = qs[i];
1736
+ int q0 = (int)(byte & 0x0F) - 8;
1737
+ int q1 = (int)(byte >> 4) - 8;
1738
+ out[i] = d * (float)q0;
1739
+ out[i + QK4_0/2] = d * (float)q1;
1740
+ }
1741
+ }
1742
+
1743
+ // View-aware AoS q4_0 -> f16 dequant (mirrors the q8_0 view variant).
1744
+ kernel void kernel_dequant_q4_0_f16_view_aos(
1745
+ global char * src,
1746
+ ulong src_offset,
1747
+ ulong src_nb1,
1748
+ ulong src_nb2,
1749
+ ulong src_nb3,
1750
+ int nblk0,
1751
+ int ne1,
1752
+ int ne2,
1753
+ int ne3,
1754
+ global half * dst
1755
+ ) {
1756
+ int blk_i0 = get_global_id(0);
1757
+ int i1 = get_global_id(1);
1758
+ int batch = get_global_id(2);
1759
+
1760
+ if (blk_i0 >= nblk0) return;
1761
+ if (i1 >= ne1) return;
1762
+
1763
+ int i2 = batch % ne2;
1764
+ int i3 = batch / ne2;
1765
+ if (i3 >= ne3) return;
1766
+
1767
+ global char * block = src + src_offset + (ulong)i3*src_nb3 + (ulong)i2*src_nb2 + (ulong)i1*src_nb1 + (ulong)blk_i0 * (2 + QK4_0/2);
1768
+ float d = vload_half(0, (global half *)block);
1769
+ global uchar * qs = (global uchar *)(block + 2);
1770
+
1771
+ ulong dst_row_base = ((ulong)i3 * ne2 * ne1 + (ulong)i2 * ne1 + (ulong)i1) * nblk0;
1772
+ global half * out = dst + (dst_row_base + blk_i0) * QK4_0;
1773
+
1774
+ for (int i = 0; i < QK4_0/2; ++i) {
1775
+ uchar byte = qs[i];
1776
+ int q0 = (int)(byte & 0x0F) - 8;
1777
+ int q1 = (int)(byte >> 4) - 8;
1778
+ out[i] = (half)(d * (float)q0);
1779
+ out[i + QK4_0/2] = (half)(d * (float)q1);
1780
+ }
1781
+ }
1782
+
1783
+ kernel void kernel_restore_block_q8_0_trans(
1784
+ global uchar * src_q,
1785
+ global half * src_d,
1786
+ global block_q8_0 * dst,
1787
+ uint ne00,
1788
+ uint ne01
1789
+ ){
1790
+ uint num_blk_per_row = ne00 / QK8_0;
1791
+
1792
+ global block_q8_0 * b = (global block_q8_0 *) dst + get_global_id(0) * num_blk_per_row;
1793
+ global uchar * q = (global uchar *) src_q + get_global_id(0) * 4; // 4 8-bit packed
1794
+ global half * d = (global half *) src_d + get_global_id(0);
1795
+
1796
+ for (uint blk = 0; blk < num_blk_per_row; blk++) {
1797
+ b->d = *d;
1798
+
1799
+ for (uint i = 0; i < QK8_0; i+=4) {
1800
+ b->qs[i] = q[0];
1801
+ b->qs[i+1] = q[1];
1802
+ b->qs[i+2] = q[2];
1803
+ b->qs[i+3] = q[3];
1804
+
1805
+ q += 4 * ne01; // M stride
1806
+ }
1807
+
1808
+ d += ne01;
1809
+
1810
+ b++;
1811
+ }
1812
+ }
1813
+
1814
+ //------------------------------------------------------------------------------
1815
+ // kernel_convert_block_q4_K
1816
+ // Convert the block_q4_K format to 4 separate arrays (AOS -> SOA).
1817
+ // This kernel does not deshuffle the bits.
1818
+ // Each thread processes a super block.
1819
+ // Mask args are just to keep the signature consistent with the no-shuffle
1820
+ // version and they are not used in this kernel.
1821
+ //------------------------------------------------------------------------------
1822
+ kernel void kernel_convert_block_q4_K(
1823
+ global struct block_q4_K * src0,
1824
+ global uchar * dst_q,
1825
+ global uchar * dst_s,
1826
+ global half * dst_d,
1827
+ global half * dst_dm,
1828
+ uchar mask_0F,
1829
+ uchar mask_F0
1830
+ ) {
1831
+ global struct block_q4_K * b = (global struct block_q4_K *) src0 + get_global_id(0);
1832
+ global uchar * q = (global uchar *) dst_q + QK_K/2*get_global_id(0);
1833
+ global uchar * s = (global uchar *) dst_s + K_SCALE_SIZE*get_global_id(0);
1834
+ global half * d = (global half *) dst_d + get_global_id(0);
1835
+ global half * dm = (global half *) dst_dm + get_global_id(0);
1836
+
1837
+ *d = b->d;
1838
+ *dm = b->dm;
1839
+
1840
+ for (int i = 0; i < QK_K/2; ++i) {
1841
+ q[i] = b->q[i];
1842
+ }
1843
+ for (int i = 0; i < K_SCALE_SIZE; ++i) {
1844
+ s[i] = b->s[i];
1845
+ }
1846
+ }
1847
+
1848
+ // Restore block_q4_K from flattened arrays.
1849
+ // Each thread processes a super block.
1850
+ // Mask args are just to keep the signature consistent with the no-shuffle ones.
1851
+ kernel void kernel_restore_block_q4_K(
1852
+ global uchar * src_q,
1853
+ global uchar * src_s,
1854
+ global half * src_d,
1855
+ global half * src_dm,
1856
+ global struct block_q4_K * dst,
1857
+ uchar mask_0F,
1858
+ uchar mask_F0
1859
+ ) {
1860
+ global struct block_q4_K * b = (global struct block_q4_K *) dst + get_global_id(0);
1861
+ global uchar * q = (global uchar *) src_q + QK_K/2*get_global_id(0);
1862
+ global uchar * s = (global uchar *) src_s + K_SCALE_SIZE*get_global_id(0);
1863
+ global half * d = (global half *) src_d + get_global_id(0);
1864
+ global half * dm = (global half *) src_dm + get_global_id(0);
1865
+
1866
+ b->d = *d;
1867
+ b->dm = *dm;
1868
+
1869
+ for (int i = 0; i < QK_K/2; ++i) {
1870
+ b->q[i] = q[i];
1871
+ }
1872
+ for (int i = 0; i < K_SCALE_SIZE; ++i) {
1873
+ b->s[i] = s[i];
1874
+ }
1875
+ }
1876
+
1877
+ kernel void kernel_convert_block_q4_K_noshuffle(
1878
+ global struct block_q4_K * src0,
1879
+ global uchar * dst_q,
1880
+ global uchar * dst_s,
1881
+ global half * dst_d,
1882
+ global half * dst_dm,
1883
+ uchar mask_0F,
1884
+ uchar mask_F0
1885
+ ) {
1886
+ global struct block_q4_K * b = (global struct block_q4_K *) src0 + get_global_id(0);
1887
+ global uchar * q = (global uchar *) dst_q + QK_K/2 * get_global_id(0);
1888
+ global uchar * s = (global uchar *) dst_s + K_SCALE_SIZE * get_global_id(0);
1889
+ global half * d = (global half *) dst_d + get_global_id(0);
1890
+ global half * dm = (global half *) dst_dm + get_global_id(0);
1891
+
1892
+ *d = b->d;
1893
+ *dm = b->dm;
1894
+
1895
+ for (int i = 0; i < QK_K / 64; ++i) {
1896
+ for (int j = 0; j < 16; ++j) {
1897
+ uchar x0 = b->q[i*32 + 2*j];
1898
+ uchar x1 = b->q[i*32 + 2*j + 1];
1899
+ q[i*32 + j] = convert_uchar(x0 & mask_0F) | convert_uchar((x1 & mask_0F) << 4);
1900
+ q[i*32 + j + 16] = convert_uchar((x0 & mask_F0) >> 4) | convert_uchar(x1 & mask_F0);
1901
+ }
1902
+ }
1903
+
1904
+ for (int i = 0; i < K_SCALE_SIZE; ++i) {
1905
+ s[i] = b->s[i];
1906
+ }
1907
+ }
1908
+
1909
+ kernel void kernel_restore_block_q4_K_noshuffle(
1910
+ global uchar * src_q,
1911
+ global uchar * src_s,
1912
+ global half * src_d,
1913
+ global half * src_dm,
1914
+ global struct block_q4_K * dst,
1915
+ uchar mask_0F,
1916
+ uchar mask_F0
1917
+ ) {
1918
+ global struct block_q4_K * b = (global struct block_q4_K *) dst + get_global_id(0);
1919
+ global uchar * q = (global uchar *) src_q + QK_K/2 * get_global_id(0);
1920
+ global uchar * s = (global uchar *) src_s + K_SCALE_SIZE * get_global_id(0);
1921
+ global half * d = (global half *) src_d + get_global_id(0);
1922
+ global half * dm = (global half *) src_dm + get_global_id(0);
1923
+
1924
+ b->d = *d;
1925
+ b->dm = *dm;
1926
+
1927
+ for (int i = 0; i < QK_K / 64; ++i) {
1928
+ for (int j = 0; j < 16; ++j) {
1929
+ uchar lo = q[i*32 + j];
1930
+ uchar hi = q[i*32 + j + 16];
1931
+ b->q[i*32 + 2*j] = convert_uchar((lo & mask_0F) | ((hi & mask_0F) << 4));
1932
+ b->q[i*32 + 2*j + 1] = convert_uchar(((lo & mask_F0) >> 4) | (hi & mask_F0));
1933
+ }
1934
+ }
1935
+
1936
+ for (int i = 0; i < K_SCALE_SIZE; ++i) {
1937
+ b->s[i] = s[i];
1938
+ }
1939
+ }
1940
+
1941
+ //------------------------------------------------------------------------------
1942
+ // kernel_convert_block_q5_K
1943
+ // Convert the block_q5_K format to 5 separate arrays (AOS -> SOA).
1944
+ // Each thread processes a super block.
1945
+ //------------------------------------------------------------------------------
1946
+ kernel void kernel_convert_block_q5_K(
1947
+ global struct block_q5_K * src0,
1948
+ global uchar * dst_q,
1949
+ global uchar * dst_qh,
1950
+ global uchar * dst_s,
1951
+ global half * dst_d,
1952
+ global half * dst_dm,
1953
+ uchar mask_0F,
1954
+ uchar mask_F0
1955
+ ) {
1956
+ global struct block_q5_K * b = (global struct block_q5_K *) src0 + get_global_id(0);
1957
+ global uchar * q = (global uchar *) dst_q + QK_K/2*get_global_id(0);
1958
+ global uchar * qh = (global uchar *) dst_qh + QK_K/8*get_global_id(0);
1959
+ global uchar * s = (global uchar *) dst_s + K_SCALE_SIZE*get_global_id(0);
1960
+ global half * d = (global half *) dst_d + get_global_id(0);
1961
+ global half * dm = (global half *) dst_dm + get_global_id(0);
1962
+
1963
+ *d = b->d;
1964
+ *dm = b->dm;
1965
+
1966
+ for (int i = 0; i < QK_K/2; ++i) {
1967
+ q[i] = b->qs[i];
1968
+ }
1969
+ for (int i = 0; i < QK_K/8; ++i) {
1970
+ qh[i] = b->qh[i];
1971
+ }
1972
+ for (int i = 0; i < K_SCALE_SIZE; ++i) {
1973
+ s[i] = b->s[i];
1974
+ }
1975
+ }
1976
+
1977
+ // Restore block_q5_K from flattened arrays.
1978
+ // Each thread processes a super block.
1979
+ kernel void kernel_restore_block_q5_K(
1980
+ global uchar * src_q,
1981
+ global uchar * src_qh,
1982
+ global uchar * src_s,
1983
+ global half * src_d,
1984
+ global half * src_dm,
1985
+ global struct block_q5_K * dst,
1986
+ uchar mask_0F,
1987
+ uchar mask_F0
1988
+ ) {
1989
+ global struct block_q5_K * b = (global struct block_q5_K *) dst + get_global_id(0);
1990
+ global uchar * q = (global uchar *) src_q + QK_K/2*get_global_id(0);
1991
+ global uchar * qh = (global uchar *) src_qh + QK_K/8*get_global_id(0);
1992
+ global uchar * s = (global uchar *) src_s + K_SCALE_SIZE*get_global_id(0);
1993
+ global half * d = (global half *) src_d + get_global_id(0);
1994
+ global half * dm = (global half *) src_dm + get_global_id(0);
1995
+
1996
+ b->d = *d;
1997
+ b->dm = *dm;
1998
+
1999
+ for (int i = 0; i < QK_K/2; ++i) {
2000
+ b->qs[i] = q[i];
2001
+ }
2002
+ for (int i = 0; i < QK_K/8; ++i) {
2003
+ b->qh[i] = qh[i];
2004
+ }
2005
+ for (int i = 0; i < K_SCALE_SIZE; ++i) {
2006
+ b->s[i] = s[i];
2007
+ }
2008
+ }
2009
+
2010
+ kernel void kernel_convert_block_q5_K_noshuffle(
2011
+ global struct block_q5_K * src0,
2012
+ global uchar * dst_q,
2013
+ global uchar * dst_qh,
2014
+ global uchar * dst_s,
2015
+ global half * dst_d,
2016
+ global half * dst_dm,
2017
+ uchar mask_0F,
2018
+ uchar mask_F0
2019
+ ) {
2020
+ global struct block_q5_K * b = (global struct block_q5_K *) src0 + get_global_id(0);
2021
+ global uchar * q = (global uchar *) dst_q + QK_K/2 * get_global_id(0);
2022
+ global uchar * qh = (global uchar *) dst_qh + QK_K/8 * get_global_id(0);
2023
+ global uchar * s = (global uchar *) dst_s + K_SCALE_SIZE * get_global_id(0);
2024
+ global half * d = (global half *) dst_d + get_global_id(0);
2025
+ global half * dm = (global half *) dst_dm + get_global_id(0);
2026
+
2027
+ *d = b->d;
2028
+ *dm = b->dm;
2029
+
2030
+ for (int i = 0; i < QK_K / 64; ++i) {
2031
+ for (int j = 0; j < 16; ++j) {
2032
+ uchar x0 = b->qs[i*32 + 2*j];
2033
+ uchar x1 = b->qs[i*32 + 2*j + 1];
2034
+ q[i*32 + j] = convert_uchar(x0 & mask_0F) | convert_uchar((x1 & mask_0F) << 4);
2035
+ q[i*32 + j + 16] = convert_uchar((x0 & mask_F0) >> 4) | convert_uchar(x1 & mask_F0);
2036
+ }
2037
+ }
2038
+
2039
+ for (int l = 0; l < QK_K/8; ++l) {
2040
+ uchar x0 = 0;
2041
+ for (int i = 0; i < 8; ++i) {
2042
+ x0 |= ((b->qh[(l%4)*8+i] >> (l/4)) & 0x01) << i;
2043
+ }
2044
+ qh[l] = x0;
2045
+ }
2046
+
2047
+ for (int i = 0; i < K_SCALE_SIZE; ++i) {
2048
+ s[i] = b->s[i];
2049
+ }
2050
+ }
2051
+
2052
+ kernel void kernel_restore_block_q5_K_noshuffle(
2053
+ global uchar * src_q,
2054
+ global uchar * src_qh,
2055
+ global uchar * src_s,
2056
+ global half * src_d,
2057
+ global half * src_dm,
2058
+ global struct block_q5_K * dst,
2059
+ uchar mask_0F,
2060
+ uchar mask_F0
2061
+ ) {
2062
+ global struct block_q5_K * b = (global struct block_q5_K *) dst + get_global_id(0);
2063
+ global uchar * q = (global uchar *) src_q + QK_K/2 * get_global_id(0);
2064
+ global uchar * qh = (global uchar *) src_qh + QK_K/8 * get_global_id(0);
2065
+ global uchar * s = (global uchar *) src_s + K_SCALE_SIZE * get_global_id(0);
2066
+ global half * d = (global half *) src_d + get_global_id(0);
2067
+ global half * dm = (global half *) src_dm + get_global_id(0);
2068
+
2069
+ b->d = *d;
2070
+ b->dm = *dm;
2071
+
2072
+ for (int i = 0; i < QK_K / 64; ++i) {
2073
+ for (int j = 0; j < 16; ++j) {
2074
+ uchar lo = q[i*32 + j];
2075
+ uchar hi = q[i*32 + j + 16];
2076
+ b->qs[i*32 + 2*j] = convert_uchar((lo & mask_0F) | ((hi & mask_0F) << 4));
2077
+ b->qs[i*32 + 2*j + 1] = convert_uchar(((lo & mask_F0) >> 4) | (hi & mask_F0));
2078
+ }
2079
+ }
2080
+
2081
+ for (int g = 0; g < 4; ++g) {
2082
+ for (int i = 0; i < 8; ++i) {
2083
+ uchar x0 = 0;
2084
+ for (int k = 0; k < 8; ++k) {
2085
+ x0 |= ((qh[4*k+g] >> i) & 0x01) << k;
2086
+ }
2087
+ b->qh[g*8+i] = x0;
2088
+ }
2089
+ }
2090
+
2091
+ for (int i = 0; i < K_SCALE_SIZE; ++i) {
2092
+ b->s[i] = s[i];
2093
+ }
2094
+ }
2095
+
2096
+ //------------------------------------------------------------------------------
2097
+ // kernel_convert_block_q6_K
2098
+ // Convert the block_q6_K format to 3 separate arrays (AOS -> SOA).
2099
+ // This kernel does not deshuffle the bits.
2100
+ // Each thread processes a super block.
2101
+ //------------------------------------------------------------------------------
2102
+ kernel void kernel_convert_block_q6_K(
2103
+ global struct block_q6_K * src0,
2104
+ global uchar * dst_ql,
2105
+ global uchar * dst_qh,
2106
+ global char * dst_s,
2107
+ global half * dst_d,
2108
+ uchar mask_lsb_8,
2109
+ ulong n_blk
2110
+ ) {
2111
+ if (get_global_id(0) >= n_blk) {
2112
+ return;
2113
+ }
2114
+ global struct block_q6_K * b = (global struct block_q6_K *) src0 + get_global_id(0);
2115
+ global uchar * ql = (global uchar *) dst_ql + QK_K/2*get_global_id(0);
2116
+ global uchar * qh = (global uchar *) dst_qh + QK_K/4*get_global_id(0);
2117
+ global char * s = (global char *) dst_s + QK_K/16*get_global_id(0);
2118
+ global half * d = (global half *) dst_d + get_global_id(0);
2119
+
2120
+ *d = b->d;
2121
+
2122
+ for (int i = 0; i < QK_K/2; ++i) {
2123
+ ql[i] = b->ql[i];
2124
+ }
2125
+ for (int i = 0; i < QK_K/4; ++i) {
2126
+ qh[i] = b->qh[i];
2127
+ }
2128
+ for (int i = 0; i < QK_K/16; ++i) {
2129
+ s[i] = b->scales[i];
2130
+ }
2131
+ }
2132
+
2133
+ // Restore block_q6_K from flattened arrays.
2134
+ // Each thread processes a super block.
2135
+ kernel void kernel_restore_block_q6_K(
2136
+ global uchar * dst_ql,
2137
+ global uchar * dst_qh,
2138
+ global char * dst_s,
2139
+ global half * dst_d,
2140
+ global struct block_q6_K * dst,
2141
+ uchar mask_lsb_8,
2142
+ ulong n_blk
2143
+ ) {
2144
+ if (get_global_id(0) >= n_blk) {
2145
+ return;
2146
+ }
2147
+ global struct block_q6_K * b = (global struct block_q6_K *) dst + get_global_id(0);
2148
+ global uchar * ql = (global uchar *) dst_ql + QK_K/2*get_global_id(0);
2149
+ global uchar * qh = (global uchar *) dst_qh + QK_K/4*get_global_id(0);
2150
+ global char * s = (global char *) dst_s + QK_K/16*get_global_id(0);
2151
+ global half * d = (global half *) dst_d + get_global_id(0);
2152
+
2153
+ b->d = *d;
2154
+
2155
+ for (int i = 0; i < QK_K/2; ++i) {
2156
+ b->ql[i] = ql[i];
2157
+ }
2158
+ for (int i = 0; i < QK_K/4; ++i) {
2159
+ b->qh[i] = qh[i];
2160
+ }
2161
+ for (int i = 0; i < QK_K/16; ++i) {
2162
+ b->scales[i] = s[i];
2163
+ }
2164
+ }
2165
+
2166
+ kernel void kernel_convert_block_q6_K_noshuffle(
2167
+ global struct block_q6_K * src0,
2168
+ global uchar * dst_ql,
2169
+ global uchar * dst_qh,
2170
+ global char * dst_s,
2171
+ global half * dst_d,
2172
+ uchar mask_lsb_8,
2173
+ ulong n_blk
2174
+ ) {
2175
+ if (get_global_id(0) >= n_blk) {
2176
+ return;
2177
+ }
2178
+ global struct block_q6_K * b = (global struct block_q6_K *) src0 + get_global_id(0);
2179
+ global uchar * ql = (global uchar *) dst_ql + QK_K/2*get_global_id(0);
2180
+ global uchar * qh = (global uchar *) dst_qh + QK_K/4*get_global_id(0);
2181
+ global char * s = (global char *) dst_s + QK_K/16*get_global_id(0);
2182
+ global half * d = (global half *) dst_d + get_global_id(0);
2183
+
2184
+ *d = b->d;
2185
+
2186
+ for (int i = 0; i < QK_K/2/4; ++i) {
2187
+ uchar x0 = b->ql[i*2 + 0] & mask_lsb_8;
2188
+ uchar x1 = b->ql[i*2 + 1] & mask_lsb_8;
2189
+ ql[i + 0] = (x0 & 0x0F) | ((x1 & 0x0F) << 4);
2190
+ ql[i + 32] = ((x0 & 0xF0) >> 4) | (x1 & 0xF0);
2191
+
2192
+ uchar x2 = b->ql[i*2 + 0 + 64] & mask_lsb_8;
2193
+ uchar x3 = b->ql[i*2 + 1 + 64] & mask_lsb_8;
2194
+ ql[i + 64] = (x2 & 0x0F) | ((x3 & 0x0F) << 4);
2195
+ ql[i + 96] = ((x2 & 0xF0) >> 4) | (x3 & 0xF0);
2196
+ }
2197
+
2198
+ for (int i = 0; i < QK_K/4/8; ++i) {
2199
+ uchar x0 = b->qh[i*4 + 0] & mask_lsb_8;
2200
+ uchar x1 = b->qh[i*4 + 1] & mask_lsb_8;
2201
+ uchar x2 = b->qh[i*4 + 2] & mask_lsb_8;
2202
+ uchar x3 = b->qh[i*4 + 3] & mask_lsb_8;
2203
+ qh[i + 0] = (x0 & 0x03) | ((x1 & 0x03) << 2) | ((x2 & 0x03) << 4) | ((x3 & 0x03) << 6);
2204
+ qh[i + 8] = ((x0 & 0x0C) >> 2) | (x1 & 0x0C) | ((x2 & 0x0C) << 2) | ((x3 & 0x0C) << 4);
2205
+ qh[i + 16] = ((x0 & 0x30) >> 4) | ((x1 & 0x30) >> 2) | (x2 & 0x30) | ((x3 & 0x30) << 2);
2206
+ qh[i + 24] = ((x0 & 0xC0) >> 6) | ((x1 & 0xC0) >> 4) | ((x2 & 0xC0) >> 2) | (x3 & 0xC0);
2207
+
2208
+ uchar x4 = b->qh[i*4 + 0 + 32] & mask_lsb_8;
2209
+ uchar x5 = b->qh[i*4 + 1 + 32] & mask_lsb_8;
2210
+ uchar x6 = b->qh[i*4 + 2 + 32] & mask_lsb_8;
2211
+ uchar x7 = b->qh[i*4 + 3 + 32] & mask_lsb_8;
2212
+ qh[i + 32] = (x4 & 0x03) | ((x5 & 0x03) << 2) | ((x6 & 0x03) << 4) | ((x7 & 0x03) << 6);
2213
+ qh[i + 40] = ((x4 & 0x0C) >> 2) | (x5 & 0x0C) | ((x6 & 0x0C) << 2) | ((x7 & 0x0C) << 4);
2214
+ qh[i + 48] = ((x4 & 0x30) >> 4) | ((x5 & 0x30) >> 2) | (x6 & 0x30) | ((x7 & 0x30) << 2);
2215
+ qh[i + 56] = ((x4 & 0xC0) >> 6) | ((x5 & 0xC0) >> 4) | ((x6 & 0xC0) >> 2) | (x7 & 0xC0);
2216
+ }
2217
+
2218
+ for (int i = 0; i < QK_K/16; ++i) {
2219
+ s[i] = b->scales[i];
2220
+ }
2221
+ }
2222
+
2223
+ kernel void kernel_restore_block_q6_K_noshuffle(
2224
+ global uchar * src_ql,
2225
+ global uchar * src_qh,
2226
+ global char * src_s,
2227
+ global half * src_d,
2228
+ global struct block_q6_K * dst,
2229
+ uchar mask_lsb_8,
2230
+ ulong n_blk
2231
+ ) {
2232
+ if (get_global_id(0) >= n_blk) {
2233
+ return;
2234
+ }
2235
+ global struct block_q6_K * b = (global struct block_q6_K *) dst + get_global_id(0);
2236
+ global uchar * ql = (global uchar *) src_ql + QK_K/2*get_global_id(0);
2237
+ global uchar * qh = (global uchar *) src_qh + QK_K/4*get_global_id(0);
2238
+ global char * s = (global char *) src_s + QK_K/16*get_global_id(0);
2239
+ global half * d = (global half *) src_d + get_global_id(0);
2240
+
2241
+ b->d = *d;
2242
+
2243
+ for (int i = 0; i < QK_K/2/4; ++i) {
2244
+ uchar x0 = ql[i + 0] & mask_lsb_8;
2245
+ uchar x1 = ql[i + 32] & mask_lsb_8;
2246
+ b->ql[i*2 + 0] = (x0 & 0x0F) | ((x1 & 0x0F) << 4);
2247
+ b->ql[i*2 + 1] = ((x0 & 0xF0) >> 4) | (x1 & 0xF0);
2248
+
2249
+ uchar x2 = ql[i + 64] & mask_lsb_8;
2250
+ uchar x3 = ql[i + 96] & mask_lsb_8;
2251
+ b->ql[i*2 + 0 + 64] = (x2 & 0x0F) | ((x3 & 0x0F) << 4);
2252
+ b->ql[i*2 + 1 + 64] = ((x2 & 0xF0) >> 4) | (x3 & 0xF0);
2253
+ }
2254
+
2255
+ for (int i = 0; i < QK_K/4/8; ++i) {
2256
+ uchar x0 = qh[i + 0] & mask_lsb_8;
2257
+ uchar x1 = qh[i + 8] & mask_lsb_8;
2258
+ uchar x2 = qh[i + 16] & mask_lsb_8;
2259
+ uchar x3 = qh[i + 24] & mask_lsb_8;
2260
+ b->qh[i*4 + 0] = (x0 & 0x03) | ((x1 & 0x03) << 2) | ((x2 & 0x03) << 4) | ((x3 & 0x03) << 6);
2261
+ b->qh[i*4 + 1] = ((x0 & 0x0C) >> 2) | (x1 & 0x0C) | ((x2 & 0x0C) << 2) | ((x3 & 0x0C) << 4);
2262
+ b->qh[i*4 + 2] = ((x0 & 0x30) >> 4) | ((x1 & 0x30) >> 2) | (x2 & 0x30) | ((x3 & 0x30) << 2);
2263
+ b->qh[i*4 + 3] = ((x0 & 0xC0) >> 6) | ((x1 & 0xC0) >> 4) | ((x2 & 0xC0) >> 2) | (x3 & 0xC0);
2264
+
2265
+ uchar x4 = qh[i + 0 + 32] & mask_lsb_8;
2266
+ uchar x5 = qh[i + 8 + 32] & mask_lsb_8;
2267
+ uchar x6 = qh[i + 16 + 32] & mask_lsb_8;
2268
+ uchar x7 = qh[i + 24 + 32] & mask_lsb_8;
2269
+ b->qh[i*4 + 0 + 32] = (x4 & 0x03) | ((x5 & 0x03) << 2) | ((x6 & 0x03) << 4) | ((x7 & 0x03) << 6);
2270
+ b->qh[i*4 + 1 + 32] = ((x4 & 0x0C) >> 2) | (x5 & 0x0C) | ((x6 & 0x0C) << 2) | ((x7 & 0x0C) << 4);
2271
+ b->qh[i*4 + 2 + 32] = ((x4 & 0x30) >> 4) | ((x5 & 0x30) >> 2) | (x6 & 0x30) | ((x7 & 0x30) << 2);
2272
+ b->qh[i*4 + 3 + 32] = ((x4 & 0xC0) >> 6) | ((x5 & 0xC0) >> 4) | ((x6 & 0xC0) >> 2) | (x7 & 0xC0);
2273
+ }
2274
+
2275
+ for (int i = 0; i < QK_K/16; ++i) {
2276
+ b->scales[i] = s[i];
2277
+ }
2278
+ }
2279
+
2280
+ //------------------------------------------------------------------------------
2281
+ // kernel_convert_block_iq4_nl
2282
+ // Convert the block_iq4_nl format to 2 separate arrays (AOS -> SOA).
2283
+ //------------------------------------------------------------------------------
2284
+ kernel void kernel_convert_block_iq4_nl(
2285
+ global struct block_iq4_nl * src0,
2286
+ global uchar * dst_q,
2287
+ global half * dst_d,
2288
+ uchar mask_0F,
2289
+ uchar mask_F0,
2290
+ ulong n_blk
2291
+ ) {
2292
+ if (get_global_id(0) >= n_blk) {
2293
+ return;
2294
+ }
2295
+ global struct block_iq4_nl * b = (global struct block_iq4_nl *) src0 + get_global_id(0);
2296
+ global uchar * q = (global uchar *) dst_q + QK4_NL/2*get_global_id(0);
2297
+ global half * d = (global half *) dst_d + get_global_id(0);
2298
+
2299
+ *d = b->d;
2300
+
2301
+ for (int i = 0; i < QK4_NL/2; ++i) {
2302
+ q[i] = b->qs[i];
2303
+ }
2304
+ }
2305
+
2306
+ kernel void kernel_restore_block_iq4_nl(
2307
+ global uchar * src_q,
2308
+ global half * src_d,
2309
+ global struct block_iq4_nl * dst,
2310
+ ulong n_blk
2311
+ ) {
2312
+ if (get_global_id(0) >= n_blk) {
2313
+ return;
2314
+ }
2315
+ global struct block_iq4_nl * b = (global struct block_iq4_nl *) dst + get_global_id(0);
2316
+ global uchar * q = (global uchar *) src_q + QK4_NL/2*get_global_id(0);
2317
+ global half * d = (global half *) src_d + get_global_id(0);
2318
+
2319
+ b->d = *d;
2320
+
2321
+ for (int i = 0; i < QK4_NL/2; ++i) {
2322
+ b->qs[i] = q[i];
2323
+ }
2324
+ }
2325
+
2326
+ kernel void kernel_convert_block_iq4_nl_noshuffle(
2327
+ global struct block_iq4_nl * src0,
2328
+ global uchar * dst_q,
2329
+ global half * dst_d,
2330
+ uchar mask_0F,
2331
+ uchar mask_F0,
2332
+ ulong n_blk
2333
+ ) {
2334
+ if (get_global_id(0) >= n_blk) {
2335
+ return;
2336
+ }
2337
+ global struct block_iq4_nl * b = (global struct block_iq4_nl *) src0 + get_global_id(0);
2338
+ global uchar * q = (global uchar *) dst_q + QK4_NL/2*get_global_id(0);
2339
+ global half * d = (global half *) dst_d + get_global_id(0);
2340
+
2341
+ *d = b->d;
2342
+ for (int i = 0; i < QK4_NL/4; ++i) {
2343
+ uchar x0 = b->qs[2*i + 0];
2344
+ uchar x1 = b->qs[2*i + 1];
2345
+
2346
+ q[i + 0 ] = convert_uchar(x0 & mask_0F) | convert_uchar((x1 & mask_0F) << 4);
2347
+ q[i + QK4_NL/4] = convert_uchar((x0 & mask_F0) >> 4) | convert_uchar(x1 & mask_F0);
2348
+ }
2349
+ }
2350
+
2351
+ kernel void kernel_restore_block_iq4_nl_noshuffle(
2352
+ global uchar * src_q,
2353
+ global half * src_d,
2354
+ global struct block_iq4_nl * dst,
2355
+ uchar mask_0F,
2356
+ uchar mask_F0,
2357
+ ulong n_blk
2358
+ ) {
2359
+ if (get_global_id(0) >= n_blk) {
2360
+ return;
2361
+ }
2362
+ global struct block_iq4_nl * b = (global struct block_iq4_nl *) dst + get_global_id(0);
2363
+ global uchar * q = (global uchar *) src_q + QK4_NL/2*get_global_id(0);
2364
+ global half * d = (global half *) src_d + get_global_id(0);
2365
+
2366
+ b->d = *d;
2367
+ for (int i = 0; i < QK4_NL/4; ++i) {
2368
+ uchar x0 = q[i + 0 ];
2369
+ uchar x1 = q[i + QK4_NL/4];
2370
+
2371
+ b->qs[2*i + 0] = convert_uchar((x0 & mask_0F) | ((x1 & mask_0F) << 4));
2372
+ b->qs[2*i + 1] = convert_uchar(((x0 & mask_F0) >> 4) | (x1 & mask_F0));
2373
+ }
2374
+ }
2375
+
2376
+ // ---------------------------------------------------------------------------
2377
+ // kernel_moe_expand_scale_q8_0
2378
+ //
2379
+ // Expand the q8_0 per-32-block scale d (one half/block, [expert][row][block]) into
2380
+ // the UNIFORM scale[16] format the generic dp4a MoE GEMM (kernel_gemm_moe_q8_1_dp4a,
2381
+ // MOE_QT=80) consumes: 16 f16 per 256-superblock (per-16-element segment), where the
2382
+ // two segments of each 32-block share the block's d. q8_0 is symmetric -> no min
2383
+ // buffer (the GEMM runs with has_min=0). The int8 weight codes are reused verbatim
2384
+ // from the existing flat q8_0 weight buffer (extra0_q8_0->q), so only the scale is
2385
+ // rebuilt here. One work-item per (row, superblock, expert).
2386
+ // ---------------------------------------------------------------------------
2387
+ kernel void kernel_moe_expand_scale_q8_0(
2388
+ global const half * src_d, // [expert][row][block], one scale per 32-block
2389
+ global half * dst_scale, // [expert][row][block][2] (FLAT per-32-block)
2390
+ int ne00,
2391
+ int ne01
2392
+ ) {
2393
+ int row = get_global_id(0);
2394
+ int blk = get_global_id(1); // 32-block index along K
2395
+ int e = get_global_id(2);
2396
+ if (row >= ne01) { return; }
2397
+
2398
+ long nb = ne00 / 32; // 32-blocks per row (K only needs % 32 == 0)
2399
+ half d = src_d[((long)e*ne01 + row)*nb + blk];
2400
+ long b = (((long)e*ne01 + row)*nb + blk) * 2;
2401
+ dst_scale[b + 0] = d;
2402
+ dst_scale[b + 1] = d;
2403
+ }
2404
+
2405
+ // ---------------------------------------------------------------------------
2406
+ // kernel_moe_expand_scale_q5_0
2407
+ //
2408
+ // q5_0 = symmetric, value = d*(code-16), code = nibble | (hi<<4) in 0..31. The
2409
+ // generic dp4a MoE GEMM keeps the unsigned code and centers via the min term:
2410
+ // scale*dp4a(code,a) - min*sum(a), scale = d, min = d*16.
2411
+ // Reads the existing q5_0 d ([expert][block][row], one half/32-block, from the
2412
+ // trans4 convert) and writes the FLAT per-32-block uniform scale[2]/min[1] in
2413
+ // [expert][row][block] order (a transpose). One work-item per (row, block, expert).
2414
+ // ---------------------------------------------------------------------------
2415
+ kernel void kernel_moe_expand_scale_q5_0(
2416
+ global const half * src_d, // [expert][block][row]
2417
+ global half * dst_scale, // [expert][row][block][2]
2418
+ global half * dst_min, // [expert][row][block]
2419
+ int ne00,
2420
+ int ne01
2421
+ ) {
2422
+ int row = get_global_id(0);
2423
+ int blk = get_global_id(1);
2424
+ int e = get_global_id(2);
2425
+ if (row >= ne01) { return; }
2426
+
2427
+ long nb = ne00 / 32;
2428
+ half d = src_d[(long)e*nb*ne01 + (long)blk*ne01 + row]; // [expert][block][row]
2429
+ long sb = (((long)e*ne01 + row)*nb + blk) * 2;
2430
+ long mb = ((long)e*ne01 + row)*nb + blk;
2431
+ dst_scale[sb + 0] = d;
2432
+ dst_scale[sb + 1] = d;
2433
+ dst_min[mb] = (half)((float)d * 16.0f);
2434
+ }
2435
+
2436
+ // ---------------------------------------------------------------------------
2437
+ // kernel_moe_expand_scale_q5_K
2438
+ //
2439
+ // q5_K value = d*sv*code + (-dm*mn), with the 6-bit packed per-sub-block scale sv
2440
+ // and min mn (8 sub-blocks of 32 per 256-superblock, decoded by get_scale_min_k4
2441
+ // from the 12-byte s[]). The generic dp4a MoE GEMM (kernel_gemm_moe_q8_1_dp4a,
2442
+ // MOE_QT=5) keeps the unsigned 5-bit code and applies scale/min via the uniform
2443
+ // per-32-block buffers:
2444
+ // acc += sc0*a_d*raw1 + sc1*a_d*raw2 - mn_u*a_s,
2445
+ // sc0 = sc1 = d*sv (both per-16 segments of a 32-block share the sub-block scale),
2446
+ // mn_u = dm*mn (positive; the GEMM subtracts it -> the -dm*mn min term).
2447
+ // q5_K's q_img (low nibbles) + qh (hi-bit plane) are already in the layout the GEMM
2448
+ // reads (same trans4_ns convert that feeds gemm_moe_q5_k_f32_ns), so only the scale
2449
+ // is rebuilt here.
2450
+ //
2451
+ // One work-item per (row, superblock, expert); each emits 8 sub-blocks.
2452
+ // ---------------------------------------------------------------------------
2453
+ kernel void kernel_moe_expand_scale_q5_K(
2454
+ global const uchar * src_s, // [expert][row][superblock][12]
2455
+ global const half * src_d, // [expert][superblock][row]
2456
+ global const half * src_dm, // [expert][superblock][row]
2457
+ global half * dst_scale, // [expert][row][32block][2]
2458
+ global half * dst_min, // [expert][row][32block]
2459
+ int ne00,
2460
+ int ne01
2461
+ ) {
2462
+ int row = get_global_id(0);
2463
+ int sb = get_global_id(1); // superblock index along K
2464
+ int e = get_global_id(2);
2465
+ if (row >= ne01) { return; }
2466
+
2467
+ long nsb = ne00 / 256; // superblocks per row
2468
+ long nblk32 = ne00 / 32; // 32-blocks per row
2469
+
2470
+ float d = (float)src_d [((long)e*nsb + sb)*ne01 + row];
2471
+ float dm = (float)src_dm[((long)e*nsb + sb)*ne01 + row];
2472
+
2473
+ __global const uchar * sc = src_s + ((long)e*ne01 + row)*nsb*12 + (long)sb*12;
2474
+
2475
+ for (int j = 0; j < 8; ++j) {
2476
+ uchar sv, mn;
2477
+ // get_scale_min_k4 (6-bit packed scale/min for sub-block j of 8)
2478
+ if (j < 4) {
2479
+ sv = sc[j] & 63;
2480
+ mn = sc[j+4] & 63;
2481
+ } else {
2482
+ sv = (sc[j+4] & 0x0F) | ((sc[j-4] & 0xC0) >> 2);
2483
+ mn = ((sc[j+4] >> 4) & 0x0F) | ((sc[j] & 0xC0) >> 2);
2484
+ }
2485
+ long sub = (long)sb*8 + j;
2486
+ long sbase = (((long)e*ne01 + row)*nblk32 + sub) * 2;
2487
+ half s_val = (half)(d * (float)sv);
2488
+ dst_scale[sbase + 0] = s_val;
2489
+ dst_scale[sbase + 1] = s_val;
2490
+ dst_min[((long)e*ne01 + row)*nblk32 + sub] = (half)(dm * (float)mn);
2491
+ }
2492
+ }
ggml/src/ggml-opencl/kernels/diag.cl ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ kernel void kernel_diag_f32(
2
+ global const char * src0,
3
+ ulong offset0,
4
+ global char * dst,
5
+ ulong offsetd,
6
+ ulong nb01,
7
+ ulong nb02,
8
+ ulong nb03,
9
+ int ne0,
10
+ ulong nb0,
11
+ ulong nb2,
12
+ ulong nb3
13
+ ) {
14
+ src0 = src0 + offset0;
15
+ dst = dst + offsetd;
16
+
17
+ int i3 = get_group_id(2);
18
+ int i2 = get_group_id(1);
19
+ int i1 = get_group_id(0);
20
+
21
+ global const float * src0_ptr = (global const float *)(src0 + i2*nb02 + i3*nb03);
22
+ global float * dst_ptr = (global float *)(dst + i1*nb01 + i2*nb2 + i3*nb3);
23
+
24
+ for (int i0 = get_local_id(0); i0 < ne0; i0 += get_local_size(0)) {
25
+ dst_ptr[i0] = i0 == i1 ? src0_ptr[i0] : 0.0f;
26
+ }
27
+ }
ggml/src/ggml-opencl/kernels/diag_mask_inf.cl ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+
3
+ //------------------------------------------------------------------------------
4
+ // diag_mask_inf kernels
5
+ //------------------------------------------------------------------------------
6
+ kernel void kernel_diag_mask_inf(
7
+ global float * src0,
8
+ ulong offset0,
9
+ global float * dst,
10
+ ulong offsetd,
11
+ int ne00,
12
+ int ne01,
13
+ int n_past
14
+ ) {
15
+ src0 = (global float*)((global char*)src0 + offset0);
16
+ dst = (global float*)((global char*)dst + offsetd);
17
+
18
+ int i02 = get_global_id(2);
19
+ int i01 = get_global_id(1);
20
+ int i00 = get_global_id(0);
21
+
22
+ if (i00 > n_past + i01) {
23
+ dst[i02*ne01*ne00 + i01*ne00 + i00] = -INFINITY;
24
+ } else {
25
+ dst[i02*ne01*ne00 + i01*ne00 + i00] = src0[i02*ne01*ne00 + i01*ne00 + i00];
26
+ }
27
+ }
28
+
29
+ kernel void kernel_diag_mask_inf_8(
30
+ global float4 * src0,
31
+ ulong offset0,
32
+ global float4 * dst,
33
+ ulong offsetd,
34
+ int ne00,
35
+ int ne01,
36
+ int n_past
37
+ ) {
38
+ src0 = (global float4*)((global char*)src0 + offset0);
39
+ dst = (global float4*)((global char*)dst + offsetd);
40
+
41
+ int i = 2*get_global_id(0);
42
+
43
+ dst[i+0] = src0[i+0];
44
+ dst[i+1] = src0[i+1];
45
+ int i4 = 4*i;
46
+ int i02 = i4/(ne00*ne01); i4 -= i02*ne00*ne01;
47
+ int i01 = i4/(ne00); i4 -= i01*ne00;
48
+ int i00 = i4;
49
+ for (int k = 3; k >= 0; --k) {
50
+ if (i00 + 4 + k <= n_past + i01) {
51
+ break;
52
+ }
53
+ (&dst[i+1])[k] = -INFINITY;
54
+ if (i00 + k > n_past + i01) {
55
+ (&dst[i])[k] = -INFINITY;
56
+ }
57
+ }
58
+ }
ggml/src/ggml-opencl/kernels/div.cl ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+
3
+ //------------------------------------------------------------------------------
4
+ // div
5
+ //------------------------------------------------------------------------------
6
+ kernel void kernel_div(
7
+ global char * src0,
8
+ ulong offset0,
9
+ global char * src1,
10
+ ulong offset1,
11
+ global char * dst,
12
+ ulong offsetd,
13
+ ulong nb00,
14
+ ulong nb01,
15
+ ulong nb02,
16
+ ulong nb03,
17
+ int ne10,
18
+ int ne11,
19
+ int ne12,
20
+ int ne13,
21
+ ulong nb10,
22
+ ulong nb11,
23
+ ulong nb12,
24
+ ulong nb13,
25
+ int ne0,
26
+ ulong nb0,
27
+ ulong nb1,
28
+ ulong nb2,
29
+ ulong nb3
30
+ ) {
31
+ src0 = src0 + offset0;
32
+ src1 = src1 + offset1;
33
+ dst = dst + offsetd;
34
+
35
+ int i03 = get_group_id(2);
36
+ int i02 = get_group_id(1);
37
+ int i01 = get_group_id(0);
38
+
39
+ int i13 = i03 % ne13;
40
+ int i12 = i02 % ne12;
41
+ int i11 = i01 % ne11;
42
+
43
+ global char * src0_ptr = src0 + i03*nb03 + i02*nb02 + i01*nb01;
44
+ global char * src1_ptr = src1 + i13*nb13 + i12*nb12 + i11*nb11;
45
+ global char * dst_ptr = dst + i03*nb3 + i02*nb2 + i01*nb1;
46
+
47
+ for (int i0 = get_local_id(0); i0 < ne0; i0 += get_local_size(0)) {
48
+ const int i10 = i0 % ne10;
49
+ *((global float *)(dst_ptr + i0*nb0)) = *((global float *)(src0_ptr + i0*nb00)) / *((global float *)(src1_ptr + i10*nb10));
50
+ }
51
+ }
52
+
53
+ // assumption: src1 is a row
54
+ // broadcast src1 into src0
55
+ kernel void kernel_div_row(
56
+ global float4 * src0,
57
+ ulong offset0,
58
+ global float4 * src1,
59
+ ulong offset1,
60
+ global float4 * dst,
61
+ ulong offsetd,
62
+ int ne
63
+ ) {
64
+ src0 = (global float4*)((global char*)src0 + offset0);
65
+ src1 = (global float4*)((global char*)src1 + offset1);
66
+ dst = (global float4*)((global char*)dst + offsetd);
67
+
68
+ // This performs better than using %.
69
+ uint gid = get_global_id(0);
70
+ uint idx1 = gid - (gid/ne)*ne; // get_global_id(0) % ne
71
+ dst[gid] = src0[gid] / src1[idx1];
72
+ }
73
+
74
+ kernel void kernel_div_f16(
75
+ global char * src0,
76
+ ulong offset0,
77
+ global char * src1,
78
+ ulong offset1,
79
+ global char * dst,
80
+ ulong offsetd,
81
+ ulong nb00,
82
+ ulong nb01,
83
+ ulong nb02,
84
+ ulong nb03,
85
+ int ne10,
86
+ int ne11,
87
+ int ne12,
88
+ int ne13,
89
+ ulong nb10,
90
+ ulong nb11,
91
+ ulong nb12,
92
+ ulong nb13,
93
+ int ne0,
94
+ ulong nb0,
95
+ ulong nb1,
96
+ ulong nb2,
97
+ ulong nb3
98
+ ) {
99
+ src0 = src0 + offset0;
100
+ src1 = src1 + offset1;
101
+ dst = dst + offsetd;
102
+
103
+ int i03 = get_group_id(2);
104
+ int i02 = get_group_id(1);
105
+ int i01 = get_group_id(0);
106
+
107
+ int i13 = i03 % ne13;
108
+ int i12 = i02 % ne12;
109
+ int i11 = i01 % ne11;
110
+
111
+ global char * src0_ptr = src0 + i03*nb03 + i02*nb02 + i01*nb01;
112
+ global char * src1_ptr = src1 + i13*nb13 + i12*nb12 + i11*nb11;
113
+ global char * dst_ptr = dst + i03*nb3 + i02*nb2 + i01*nb1;
114
+
115
+ for (int i0 = get_local_id(0); i0 < ne0; i0 += get_local_size(0)) {
116
+ const int i10 = i0 % ne10;
117
+ *((global half *)(dst_ptr + i0*nb0)) = *((global half *)(src0_ptr + i0*nb00)) / *((global half *)(src1_ptr + i10*nb10));
118
+ }
119
+ }
120
+
121
+ kernel void kernel_div_row_f16(
122
+ global half4 * src0,
123
+ ulong offset0,
124
+ global half4 * src1,
125
+ ulong offset1,
126
+ global half4 * dst,
127
+ ulong offsetd,
128
+ int ne
129
+ ) {
130
+ src0 = (global half4*)((global char*)src0 + offset0);
131
+ src1 = (global half4*)((global char*)src1 + offset1);
132
+ dst = (global half4*)((global char*)dst + offsetd);
133
+
134
+ // This performs better than using %.
135
+ uint gid = get_global_id(0);
136
+ uint idx1 = gid - (gid/ne)*ne; // get_global_id(0) % ne
137
+ dst[gid] = src0[gid] / src1[idx1];
138
+ }
ggml/src/ggml-opencl/kernels/embed_kernel.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+
3
+ import sys
4
+ import logging
5
+ logger = logging.getLogger("opencl-embed-kernel")
6
+
7
+
8
+ def main():
9
+ logging.basicConfig(level=logging.INFO)
10
+
11
+ if len(sys.argv) != 3:
12
+ logger.info("Usage: python embed_kernel.py <input_file> <output_file>")
13
+ sys.exit(1)
14
+
15
+ ifile = open(sys.argv[1], "r")
16
+ ofile = open(sys.argv[2], "w")
17
+
18
+ for i in ifile:
19
+ ofile.write('R"({})"\n'.format(i))
20
+
21
+ ifile.close()
22
+ ofile.close()
23
+
24
+
25
+ if __name__ == "__main__":
26
+ main()
ggml/src/ggml-opencl/kernels/exp.cl ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+
3
+ kernel void kernel_exp_f32(
4
+ global const float * src0,
5
+ ulong offset0,
6
+ global float * dst,
7
+ ulong offsetd,
8
+ int n
9
+ ) {
10
+ if (get_global_id(0) >= n) {
11
+ return;
12
+ }
13
+ src0 = (global float*)((global char*)src0 + offset0);
14
+ dst = (global float*)((global char*)dst + offsetd);
15
+
16
+ dst[get_global_id(0)] = exp(src0[get_global_id(0)]);
17
+ }
18
+
19
+ kernel void kernel_exp_f32_4(
20
+ global const float4 * src0,
21
+ ulong offset0,
22
+ global float4 * dst,
23
+ ulong offsetd,
24
+ int n
25
+ ) {
26
+ if (get_global_id(0) >= n) {
27
+ return;
28
+ }
29
+ src0 = (global float4*)((global char*)src0 + offset0);
30
+ dst = (global float4*)((global char*)dst + offsetd);
31
+
32
+ dst[get_global_id(0)] = exp(src0[get_global_id(0)]);
33
+ }
34
+
35
+ kernel void kernel_exp_f16(
36
+ global const half * src0,
37
+ ulong offset0,
38
+ global half * dst,
39
+ ulong offsetd,
40
+ int n
41
+ ) {
42
+ if (get_global_id(0) >= n) {
43
+ return;
44
+ }
45
+ src0 = (global half*)((global char*)src0 + offset0);
46
+ dst = (global half*)((global char*)dst + offsetd);
47
+
48
+ dst[get_global_id(0)] = exp(src0[get_global_id(0)]);
49
+ }
50
+
51
+ kernel void kernel_exp_f16_4(
52
+ global const half4 * src0,
53
+ ulong offset0,
54
+ global half4 * dst,
55
+ ulong offsetd,
56
+ int n
57
+ ) {
58
+ if (get_global_id(0) >= n) {
59
+ return;
60
+ }
61
+ src0 = (global half4*)((global char*)src0 + offset0);
62
+ dst = (global half4*)((global char*)dst + offsetd);
63
+
64
+ dst[get_global_id(0)] = exp(src0[get_global_id(0)]);
65
+ }
66
+
67
+ kernel void kernel_exp_f32_nc(
68
+ global const char * src0,
69
+ ulong offset0,
70
+ global char * dst,
71
+ ulong offsetd,
72
+ int ne00,
73
+ ulong nb00,
74
+ ulong nb01,
75
+ ulong nb02,
76
+ ulong nb03,
77
+ ulong nb0,
78
+ ulong nb1,
79
+ ulong nb2,
80
+ ulong nb3
81
+ ) {
82
+ src0 = src0 + offset0;
83
+ dst = dst + offsetd;
84
+
85
+ const int i3 = get_group_id(2);
86
+ const int i2 = get_group_id(1);
87
+ const int i1 = get_group_id(0);
88
+
89
+ for (int i0 = get_local_id(0); i0 < ne00; i0 += get_local_size(0)) {
90
+ global const float * x = (global const float *)(src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
91
+ global float * y = (global float *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
92
+
93
+ *y = exp(*x);
94
+ }
95
+ }
96
+
97
+ kernel void kernel_exp_f16_nc(
98
+ global const char * src0,
99
+ ulong offset0,
100
+ global char * dst,
101
+ ulong offsetd,
102
+ int ne00,
103
+ ulong nb00,
104
+ ulong nb01,
105
+ ulong nb02,
106
+ ulong nb03,
107
+ ulong nb0,
108
+ ulong nb1,
109
+ ulong nb2,
110
+ ulong nb3
111
+ ) {
112
+ src0 = src0 + offset0;
113
+ dst = dst + offsetd;
114
+
115
+ const int i3 = get_group_id(2);
116
+ const int i2 = get_group_id(1);
117
+ const int i1 = get_group_id(0);
118
+
119
+ for (int i0 = get_local_id(0); i0 < ne00; i0 += get_local_size(0)) {
120
+ global const half * x = (global const half *)(src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
121
+ global half * y = (global half *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
122
+
123
+ *y = exp(*x);
124
+ }
125
+ }
ggml/src/ggml-opencl/kernels/expm1.cl ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+
3
+ //------------------------------------------------------------------------------
4
+ // expm1
5
+ //------------------------------------------------------------------------------
6
+
7
+ kernel void kernel_expm1_f32(
8
+ global const float * src0,
9
+ ulong offset0,
10
+ global float * dst,
11
+ ulong offsetd
12
+ ) {
13
+ src0 = (global float*)((global char*)src0 + offset0);
14
+ dst = (global float*)((global char*)dst + offsetd);
15
+
16
+ dst[get_global_id(0)] = exp(src0[get_global_id(0)]) - 1.0f;
17
+ }
18
+
19
+ kernel void kernel_expm1_f32_4(
20
+ global const float4 * src0,
21
+ ulong offset0,
22
+ global float4 * dst,
23
+ ulong offsetd
24
+ ) {
25
+ src0 = (global float4*)((global char*)src0 + offset0);
26
+ dst = (global float4*)((global char*)dst + offsetd);
27
+
28
+ dst[get_global_id(0)] = exp(src0[get_global_id(0)]) - 1.0f;
29
+ }
30
+
31
+ kernel void kernel_expm1_f16(
32
+ global const half * src0,
33
+ ulong offset0,
34
+ global half * dst,
35
+ ulong offsetd
36
+ ) {
37
+ src0 = (global half*)((global char*)src0 + offset0);
38
+ dst = (global half*)((global char*)dst + offsetd);
39
+
40
+ dst[get_global_id(0)] = exp(src0[get_global_id(0)]) - 1.0h;
41
+ }
42
+
43
+ kernel void kernel_expm1_f16_4(
44
+ global const half4 * src0,
45
+ ulong offset0,
46
+ global half4 * dst,
47
+ ulong offsetd
48
+ ) {
49
+ src0 = (global half4*)((global char*)src0 + offset0);
50
+ dst = (global half4*)((global char*)dst + offsetd);
51
+
52
+ dst[get_global_id(0)] = exp(src0[get_global_id(0)]) - 1.0h;
53
+ }
54
+
55
+ kernel void kernel_expm1_f32_nc(
56
+ global const char * src0,
57
+ ulong offset0,
58
+ global char * dst,
59
+ ulong offsetd,
60
+ int ne00,
61
+ ulong nb00,
62
+ ulong nb01,
63
+ ulong nb02,
64
+ ulong nb03,
65
+ ulong nb0,
66
+ ulong nb1,
67
+ ulong nb2,
68
+ ulong nb3
69
+ ) {
70
+ src0 = src0 + offset0;
71
+ dst = dst + offsetd;
72
+
73
+ const int i3 = get_group_id(2);
74
+ const int i2 = get_group_id(1);
75
+ const int i1 = get_group_id(0);
76
+
77
+ for (int i0 = get_local_id(0); i0 < ne00; i0 += get_local_size(0)) {
78
+ global const float * x = (global const float *)(src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
79
+ global float * y = (global float *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
80
+
81
+ *y = exp(*x) - 1.0f;
82
+ }
83
+ }
84
+
85
+ kernel void kernel_expm1_f16_nc(
86
+ global const char * src0,
87
+ ulong offset0,
88
+ global char * dst,
89
+ ulong offsetd,
90
+ int ne00,
91
+ ulong nb00,
92
+ ulong nb01,
93
+ ulong nb02,
94
+ ulong nb03,
95
+ ulong nb0,
96
+ ulong nb1,
97
+ ulong nb2,
98
+ ulong nb3
99
+ ) {
100
+ src0 = src0 + offset0;
101
+ dst = dst + offsetd;
102
+
103
+ const int i3 = get_group_id(2);
104
+ const int i2 = get_group_id(1);
105
+ const int i1 = get_group_id(0);
106
+
107
+ for (int i0 = get_local_id(0); i0 < ne00; i0 += get_local_size(0)) {
108
+ global const half * x = (global const half *)(src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
109
+ global half * y = (global half *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
110
+
111
+ *y = exp(*x) - 1.0f;
112
+ }
113
+ }
ggml/src/ggml-opencl/kernels/fill.cl ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+
3
+ //------------------------------------------------------------------------------
4
+ // fill
5
+ //------------------------------------------------------------------------------
6
+ __kernel void kernel_fill_f32(
7
+ __global float *dst,
8
+ ulong offsetd,
9
+ float v,
10
+ int n
11
+
12
+ ) {
13
+ dst = (global float*)((global char*)dst + offsetd);
14
+ if(get_global_id(0) < n){
15
+ dst[get_global_id(0)] = v;
16
+ }
17
+ }
ggml/src/ggml-opencl/kernels/flash_attn_f16.cl ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+
3
+ #define ACC_TYPE float
4
+ #define ACC_TYPE4 float4
5
+ #define DATA_TYPE half
6
+ #define DATA_TYPE4 half4
7
+ #define CONVERT_ACC4(x) ((float4)((float)(x).s0, (float)(x).s1, (float)(x).s2, (float)(x).s3))
8
+ #define CONVERT_DATA4(x) ((half4)((half)(x).s0, (half)(x).s1, (half)(x).s2, (half)(x).s3))
9
+
10
+ #define DK_VEC (DK/4)
11
+ #define DV_VEC (DV/4)
12
+ #define WG_SIZE (BLOCK_M)
13
+ // q1 reduces over a Q1_WG_SIZE-wide WG via work-group barriers; the launch WG
14
+ // must match. Defaults to the Adreno sg (64); host passes -D FA_SG=32 on Intel.
15
+ #ifndef FA_SG
16
+ #define FA_SG 64
17
+ #endif
18
+ #define Q1_WG_SIZE FA_SG
19
+
20
+ // The kernels are built with -cl-finite-math-only. On some older Adreno GPUs,
21
+ // infinite operand can cause undefined behavior and miscompilation for exp.
22
+ // Therefore, a large negative value is used instead.
23
+ #define FA_M_INIT (-3.0e38f)
24
+
25
+ // Drop full unroll at DK>=192 — Adreno compiler host-memory budget.
26
+ #if DK >= 192
27
+ #define FA_UNROLL
28
+ #else
29
+ #define FA_UNROLL _Pragma("unroll")
30
+ #endif
31
+
32
+ inline float get_alibi_slope(
33
+ const float max_bias, const uint h, const uint n_head_log2, const float m0, const float m1
34
+ ) {
35
+ if (max_bias <= 0.0f) {
36
+ return 1.0f;
37
+ }
38
+ const float base = h < n_head_log2 ? m0 : m1;
39
+ const int exph = h < n_head_log2 ? h + 1 : 2*(h - n_head_log2) + 1;
40
+
41
+ return pow(base, exph);
42
+ }
43
+ __kernel void flash_attn_f16(
44
+ const global void * q_void, ulong q_offset,
45
+ const global void * k_void, ulong k_offset,
46
+ const global void * v_void, ulong v_offset,
47
+ global void * o_void, ulong o_offset,
48
+ const float scale,
49
+ const int n_q,
50
+ const int n_kv,
51
+ const int is_causal,
52
+ const int n_head,
53
+ const ulong q_nb1, const ulong q_nb2, const ulong q_nb3,
54
+ const ulong k_nb1, const ulong k_nb2, const ulong k_nb3,
55
+ const ulong v_nb1, const ulong v_nb2, const ulong v_nb3,
56
+ const ulong o_nb1, const ulong o_nb2, const ulong o_nb3,
57
+ const float max_bias,
58
+ const float m0,
59
+ const float m1,
60
+ const int n_head_log2,
61
+ const float logit_softcap,
62
+ const int n_head_kv,
63
+ const global void* mask_void,
64
+ const ulong mask_offset,
65
+ const ulong mask_nb1,
66
+ const ulong mask_nb2,
67
+ const ulong mask_nb3,
68
+ const int mask_ne2,
69
+ const int mask_ne3,
70
+ const global void* sinks_void,
71
+ const ulong sinks_offset
72
+ ) {
73
+ const int tid = get_local_id(0);
74
+ const int block_q_idx = get_group_id(0);
75
+ const int head_batch_idx = get_global_id(1);
76
+
77
+ const int my_query_row = block_q_idx * BLOCK_M + tid;
78
+
79
+ const int batch_idx = head_batch_idx / n_head;
80
+ const int head_idx = head_batch_idx % n_head;
81
+
82
+ const int gqa_ratio = n_head / n_head_kv;
83
+ const int head_kv_idx = head_idx / gqa_ratio;
84
+
85
+ const global char* q_base = (const global char*)q_void + q_offset;
86
+ const global char* k_base = (const global char*)k_void + k_offset;
87
+ const global char* v_base = (const global char*)v_void + v_offset;
88
+ global char* o_base = (global char*)o_void + o_offset;
89
+
90
+ const global char* mask_base = NULL;
91
+ if (mask_void != NULL) {
92
+ const int mask_head_idx = head_idx % mask_ne2;
93
+ const int mask_batch_idx = batch_idx % mask_ne3;
94
+ mask_base = (const global char*)mask_void + mask_offset + mask_batch_idx * mask_nb3 + mask_head_idx * mask_nb2;
95
+ }
96
+
97
+ ACC_TYPE4 q_priv[DK_VEC];
98
+ if (my_query_row < n_q) {
99
+ const ulong q_row_offset = batch_idx * q_nb3 + head_idx * q_nb2 + my_query_row * q_nb1;
100
+ const global DATA_TYPE4* q_ptr = (const global DATA_TYPE4*)(q_base + q_row_offset);
101
+ FA_UNROLL
102
+ for (int i = 0; i < DK_VEC; ++i) {
103
+ q_priv[i] = CONVERT_ACC4(q_ptr[i]);
104
+ }
105
+ }
106
+
107
+ ACC_TYPE4 o_acc[DV_VEC];
108
+ FA_UNROLL
109
+ for (int i = 0; i < DV_VEC; ++i) {
110
+ o_acc[i] = (ACC_TYPE4)(0.0f);
111
+ }
112
+ ACC_TYPE m_i = FA_M_INIT;
113
+ ACC_TYPE l_i = 0.0f;
114
+
115
+ float slope = get_alibi_slope(max_bias, head_idx, n_head_log2, m0, m1);
116
+
117
+ __local DATA_TYPE4 l_k[BLOCK_N][DK_VEC];
118
+ __local DATA_TYPE4 l_v[BLOCK_N][DV_VEC];
119
+
120
+ for (int k_start = 0; k_start < n_kv; k_start += BLOCK_N) {
121
+ for (int i = tid; i < BLOCK_N * DK_VEC; i += WG_SIZE) {
122
+ const int row = i / DK_VEC;
123
+ const int col = i % DK_VEC;
124
+ const int k_row_idx = k_start + row;
125
+ if (k_row_idx < n_kv) {
126
+ const ulong k_row_offset = batch_idx * k_nb3 + head_kv_idx * k_nb2 + k_row_idx * k_nb1;
127
+ l_k[row][col] = ((__global DATA_TYPE4*)(k_base + k_row_offset))[col];
128
+ }
129
+ }
130
+ for (int i = tid; i < BLOCK_N * DV_VEC; i += WG_SIZE) {
131
+ const int row = i / DV_VEC;
132
+ const int col = i % DV_VEC;
133
+ const int v_row_idx = k_start + row;
134
+ if (v_row_idx < n_kv) {
135
+ const ulong v_row_offset = batch_idx * v_nb3 + head_kv_idx * v_nb2 + v_row_idx * v_nb1;
136
+ l_v[row][col] = ((__global DATA_TYPE4*)(v_base + v_row_offset))[col];
137
+ }
138
+ }
139
+ barrier(CLK_LOCAL_MEM_FENCE);
140
+
141
+ if (my_query_row >= n_q) {
142
+ continue;
143
+ }
144
+
145
+ for (int j = 0; j < BLOCK_N; j += 4) {
146
+ const int k_row0 = k_start + j;
147
+ const int k_row1 = k_start + j + 1;
148
+ const int k_row2 = k_start + j + 2;
149
+ const int k_row3 = k_start + j + 3;
150
+
151
+ ACC_TYPE4 dot_acc0 = (ACC_TYPE4)(0.0f);
152
+ ACC_TYPE4 dot_acc1 = (ACC_TYPE4)(0.0f);
153
+ ACC_TYPE4 dot_acc2 = (ACC_TYPE4)(0.0f);
154
+ ACC_TYPE4 dot_acc3 = (ACC_TYPE4)(0.0f);
155
+ FA_UNROLL
156
+ for (int k = 0; k < DK_VEC; k++) {
157
+ const ACC_TYPE4 qk = q_priv[k];
158
+ dot_acc0 = mad(qk, CONVERT_ACC4(l_k[j][k]), dot_acc0);
159
+ dot_acc1 = mad(qk, CONVERT_ACC4(l_k[j+1][k]), dot_acc1);
160
+ dot_acc2 = mad(qk, CONVERT_ACC4(l_k[j+2][k]), dot_acc2);
161
+ dot_acc3 = mad(qk, CONVERT_ACC4(l_k[j+3][k]), dot_acc3);
162
+ }
163
+ ACC_TYPE s0 = (dot_acc0.s0 + dot_acc0.s1 + dot_acc0.s2 + dot_acc0.s3) * scale;
164
+ ACC_TYPE s1 = (dot_acc1.s0 + dot_acc1.s1 + dot_acc1.s2 + dot_acc1.s3) * scale;
165
+ ACC_TYPE s2 = (dot_acc2.s0 + dot_acc2.s1 + dot_acc2.s2 + dot_acc2.s3) * scale;
166
+ ACC_TYPE s3 = (dot_acc3.s0 + dot_acc3.s1 + dot_acc3.s2 + dot_acc3.s3) * scale;
167
+
168
+ if (is_causal) {
169
+ const int causal_limit = n_kv - n_q + my_query_row;
170
+ if (k_row0 > causal_limit) s0 = FA_M_INIT;
171
+ if (k_row1 > causal_limit) s1 = FA_M_INIT;
172
+ if (k_row2 > causal_limit) s2 = FA_M_INIT;
173
+ if (k_row3 > causal_limit) s3 = FA_M_INIT;
174
+ }
175
+ if (k_row0 >= n_kv) s0 = FA_M_INIT;
176
+ if (k_row1 >= n_kv) s1 = FA_M_INIT;
177
+ if (k_row2 >= n_kv) s2 = FA_M_INIT;
178
+ if (k_row3 >= n_kv) s3 = FA_M_INIT;
179
+
180
+ if (mask_base != NULL) {
181
+ const global DATA_TYPE* mask_ptr = (const global DATA_TYPE*)(mask_base + my_query_row * mask_nb1);
182
+ if (k_row0 < n_kv) s0 += slope * (ACC_TYPE)mask_ptr[k_row0];
183
+ if (k_row1 < n_kv) s1 += slope * (ACC_TYPE)mask_ptr[k_row1];
184
+ if (k_row2 < n_kv) s2 += slope * (ACC_TYPE)mask_ptr[k_row2];
185
+ if (k_row3 < n_kv) s3 += slope * (ACC_TYPE)mask_ptr[k_row3];
186
+ }
187
+
188
+ if (logit_softcap > 0.0f) {
189
+ s0 = logit_softcap * tanh(s0 / logit_softcap);
190
+ s1 = logit_softcap * tanh(s1 / logit_softcap);
191
+ s2 = logit_softcap * tanh(s2 / logit_softcap);
192
+ s3 = logit_softcap * tanh(s3 / logit_softcap);
193
+ }
194
+
195
+ const ACC_TYPE m_new = max(m_i, max(max(s0, s1), max(s2, s3)));
196
+ const ACC_TYPE scale_prev = native_exp(m_i - m_new);
197
+ const ACC_TYPE p0 = native_exp(s0 - m_new);
198
+ const ACC_TYPE p1 = native_exp(s1 - m_new);
199
+ const ACC_TYPE p2 = native_exp(s2 - m_new);
200
+ const ACC_TYPE p3 = native_exp(s3 - m_new);
201
+
202
+ FA_UNROLL
203
+ for (int i = 0; i < DV_VEC; ++i) {
204
+ o_acc[i] = mad(p3, CONVERT_ACC4(l_v[j+3][i]),
205
+ mad(p2, CONVERT_ACC4(l_v[j+2][i]),
206
+ mad(p1, CONVERT_ACC4(l_v[j+1][i]),
207
+ mad(p0, CONVERT_ACC4(l_v[j][i]),
208
+ o_acc[i] * scale_prev))));
209
+ }
210
+ l_i = l_i * scale_prev + p0 + p1 + p2 + p3;
211
+ m_i = m_new;
212
+ }
213
+ }
214
+
215
+ if (my_query_row < n_q) {
216
+ if (sinks_void != NULL) {
217
+ const global ACC_TYPE* sinks_ptr = (const global ACC_TYPE*)((const global char*)sinks_void + sinks_offset);
218
+ const ACC_TYPE m_sink = sinks_ptr[head_idx];
219
+ const ACC_TYPE m_final = max(m_i, m_sink);
220
+
221
+ const ACC_TYPE scale_o = exp(m_i - m_final);
222
+ FA_UNROLL
223
+ for (int i = 0; i < DV_VEC; ++i) {
224
+ o_acc[i] *= scale_o;
225
+ }
226
+
227
+ l_i = l_i * exp(m_i - m_final) + exp(m_sink - m_final);
228
+ }
229
+
230
+ const ulong o_row_offset = batch_idx * o_nb3 + my_query_row * o_nb2 + head_idx * o_nb1;
231
+ global DATA_TYPE4 *o_row = (global DATA_TYPE4 *)(o_base + o_row_offset);
232
+ if (l_i > 0.0f) {
233
+ const ACC_TYPE l_inv = 1.0f / l_i;
234
+ FA_UNROLL
235
+ for (int i = 0; i < DV_VEC; ++i) {
236
+ o_row[i] = CONVERT_DATA4(o_acc[i] * l_inv);
237
+ }
238
+ } else {
239
+ FA_UNROLL
240
+ for (int i = 0; i < DV_VEC; ++i) {
241
+ o_row[i] = (DATA_TYPE4)(0.0f);
242
+ }
243
+ }
244
+ }
245
+ }
246
+
247
+ __kernel void flash_attn_f16_q1(
248
+ const global void * q_void, ulong q_offset,
249
+ const global void * k_void, ulong k_offset,
250
+ const global void * v_void, ulong v_offset,
251
+ global void * o_void, ulong o_offset,
252
+ const float scale,
253
+ const int n_q,
254
+ const int n_kv,
255
+ const int is_causal,
256
+ const int n_head,
257
+ const ulong q_nb1, const ulong q_nb2, const ulong q_nb3,
258
+ const ulong k_nb1, const ulong k_nb2, const ulong k_nb3,
259
+ const ulong v_nb1, const ulong v_nb2, const ulong v_nb3,
260
+ const ulong o_nb1, const ulong o_nb2, const ulong o_nb3,
261
+ const float max_bias,
262
+ const float m0,
263
+ const float m1,
264
+ const int n_head_log2,
265
+ const float logit_softcap,
266
+ const int n_head_kv,
267
+ const global void* mask_void,
268
+ const ulong mask_offset,
269
+ const ulong mask_nb1,
270
+ const ulong mask_nb2,
271
+ const ulong mask_nb3,
272
+ const int mask_ne2,
273
+ const int mask_ne3,
274
+ const global void* sinks_void,
275
+ const ulong sinks_offset
276
+ ) {
277
+ const int tid = get_local_id(0);
278
+ const int head_batch_idx = get_global_id(1);
279
+
280
+ const int batch_idx = head_batch_idx / n_head;
281
+ const int head_idx = head_batch_idx % n_head;
282
+
283
+ const int gqa_ratio = n_head / n_head_kv;
284
+ const int head_kv_idx = head_idx / gqa_ratio;
285
+
286
+ const global char* q_base = (const global char*)q_void + q_offset;
287
+ const global char* k_base = (const global char*)k_void + k_offset;
288
+ const global char* v_base = (const global char*)v_void + v_offset;
289
+ global char* o_base = (global char*)o_void + o_offset;
290
+
291
+ const global char* mask_base = NULL;
292
+ if (mask_void != NULL) {
293
+ const int mask_head_idx = head_idx % mask_ne2;
294
+ const int mask_batch_idx = batch_idx % mask_ne3;
295
+ mask_base = (const global char*)mask_void + mask_offset + mask_batch_idx * mask_nb3 + mask_head_idx * mask_nb2;
296
+ }
297
+
298
+ ACC_TYPE4 q_priv[DK_VEC];
299
+ const ulong q_row_offset = batch_idx * q_nb3 + head_idx * q_nb2;
300
+ const global DATA_TYPE4* q_ptr = (const global DATA_TYPE4*)(q_base + q_row_offset);
301
+ FA_UNROLL
302
+ for (int i = 0; i < DK_VEC; ++i) {
303
+ q_priv[i] = CONVERT_ACC4(q_ptr[i]);
304
+ }
305
+
306
+ float slope = get_alibi_slope(max_bias, head_idx, n_head_log2, m0, m1);
307
+
308
+ const global ACC_TYPE* sinks_ptr = NULL;
309
+ if (sinks_void != NULL) {
310
+ sinks_ptr = (const global ACC_TYPE*)((const global char*)sinks_void + sinks_offset);
311
+ }
312
+
313
+ ACC_TYPE m_i = (sinks_ptr != NULL) ? sinks_ptr[head_idx] : FA_M_INIT;
314
+ for (int k_idx = tid; k_idx < n_kv; k_idx += Q1_WG_SIZE) {
315
+ const ulong k_row_offset = batch_idx * k_nb3 + head_kv_idx * k_nb2 + k_idx * k_nb1;
316
+ const global DATA_TYPE4* k_ptr = (const global DATA_TYPE4*)(k_base + k_row_offset);
317
+ ACC_TYPE4 dot_acc = (ACC_TYPE4)(0.0f);
318
+ FA_UNROLL
319
+ for (int k = 0; k < DK_VEC; k++) {
320
+ dot_acc = mad(q_priv[k], CONVERT_ACC4(k_ptr[k]), dot_acc);
321
+ }
322
+ ACC_TYPE score = (dot_acc.s0 + dot_acc.s1 + dot_acc.s2 + dot_acc.s3) * scale;
323
+ if (mask_base != NULL) {
324
+ const global DATA_TYPE* mask_ptr = (const global DATA_TYPE*)(mask_base);
325
+ score += slope * (ACC_TYPE)mask_ptr[k_idx];
326
+ }
327
+ if (logit_softcap > 0.0f) {
328
+ score = logit_softcap * tanh(score / logit_softcap);
329
+ }
330
+ m_i = max(m_i, score);
331
+ }
332
+
333
+ __local ACC_TYPE local_m[Q1_WG_SIZE];
334
+ local_m[tid] = m_i;
335
+ barrier(CLK_LOCAL_MEM_FENCE);
336
+ FA_UNROLL
337
+ for (int s = Q1_WG_SIZE / 2; s > 0; s >>= 1) {
338
+ if (tid < s) local_m[tid] = max(local_m[tid], local_m[tid + s]);
339
+ barrier(CLK_LOCAL_MEM_FENCE);
340
+ }
341
+ const ACC_TYPE m_final = local_m[0];
342
+
343
+ ACC_TYPE4 o_acc[DV_VEC];
344
+ FA_UNROLL
345
+ for (int i = 0; i < DV_VEC; ++i) o_acc[i] = (ACC_TYPE4)(0.0f);
346
+ ACC_TYPE l_i = 0.0f;
347
+
348
+ for (int k_idx = tid; k_idx < n_kv; k_idx += Q1_WG_SIZE) {
349
+ const ulong k_row_offset = batch_idx * k_nb3 + head_kv_idx * k_nb2 + k_idx * k_nb1;
350
+ const ulong v_row_offset = batch_idx * v_nb3 + head_kv_idx * v_nb2 + k_idx * v_nb1;
351
+ const global DATA_TYPE4* k_ptr = (const global DATA_TYPE4*)(k_base + k_row_offset);
352
+ const global DATA_TYPE4* v_ptr = (const global DATA_TYPE4*)(v_base + v_row_offset);
353
+ ACC_TYPE4 dot_acc = (ACC_TYPE4)(0.0f);
354
+ FA_UNROLL
355
+ for (int k = 0; k < DK_VEC; k++) {
356
+ dot_acc = mad(q_priv[k], CONVERT_ACC4(k_ptr[k]), dot_acc);
357
+ }
358
+ ACC_TYPE score = (dot_acc.s0 + dot_acc.s1 + dot_acc.s2 + dot_acc.s3) * scale;
359
+ if (mask_base != NULL) {
360
+ const global DATA_TYPE* mask_ptr = (const global DATA_TYPE*)(mask_base);
361
+ score += slope * (ACC_TYPE)mask_ptr[k_idx];
362
+ }
363
+ if (logit_softcap > 0.0f) {
364
+ score = logit_softcap * tanh(score / logit_softcap);
365
+ }
366
+ const ACC_TYPE p = exp(score - m_final);
367
+ l_i += p;
368
+ FA_UNROLL
369
+ for (int i = 0; i < DV_VEC; i++) {
370
+ o_acc[i] = mad(p, CONVERT_ACC4(v_ptr[i]), o_acc[i]);
371
+ }
372
+ }
373
+
374
+ __local ACC_TYPE local_l[Q1_WG_SIZE];
375
+ __local ACC_TYPE4 local_o_comp[Q1_WG_SIZE];
376
+ local_l[tid] = l_i;
377
+ barrier(CLK_LOCAL_MEM_FENCE);
378
+ FA_UNROLL
379
+ for (int s = Q1_WG_SIZE / 2; s > 0; s >>= 1) {
380
+ if (tid < s) local_l[tid] += local_l[tid + s];
381
+ barrier(CLK_LOCAL_MEM_FENCE);
382
+ }
383
+
384
+ const ulong o_row_offset = batch_idx * o_nb3 + head_idx * o_nb1;
385
+ global DATA_TYPE4 *o_row = (global DATA_TYPE4 *)(o_base + o_row_offset);
386
+ ACC_TYPE l_final = local_l[0];
387
+
388
+ if (sinks_ptr != NULL) {
389
+ l_final += exp(sinks_ptr[head_idx] - m_final);
390
+ }
391
+
392
+ if (l_final > 0.0f) {
393
+ const ACC_TYPE l_inv = 1.0f / l_final;
394
+ for (int i = 0; i < DV_VEC; i++) {
395
+ local_o_comp[tid] = o_acc[i];
396
+ barrier(CLK_LOCAL_MEM_FENCE);
397
+ FA_UNROLL
398
+ for (int s = Q1_WG_SIZE / 2; s > 0; s >>= 1) {
399
+ if (tid < s) local_o_comp[tid] += local_o_comp[tid + s];
400
+ barrier(CLK_LOCAL_MEM_FENCE);
401
+ }
402
+ if (tid == 0) {
403
+ o_row[i] = CONVERT_DATA4(local_o_comp[0] * l_inv);
404
+ }
405
+ }
406
+ } else if (tid == 0) {
407
+ FA_UNROLL
408
+ for (int i = 0; i < DV_VEC; ++i) o_row[i] = (DATA_TYPE4)(0.0f);
409
+ }
410
+ }
ggml/src/ggml-opencl/kernels/flash_attn_f32.cl ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+
3
+ #define ACC_TYPE float
4
+ #define ACC_TYPE4 float4
5
+ #define DATA_TYPE float
6
+ #define DATA_TYPE4 float4
7
+ #define MASK_DATA_TYPE half
8
+ #define CONVERT_ACC4(x) (x)
9
+ #define CONVERT_DATA4(x) (x)
10
+
11
+ #define DK_VEC (DK/4)
12
+ #define DV_VEC (DV/4)
13
+ #define WG_SIZE (BLOCK_M)
14
+ // q1 reduces over a Q1_WG_SIZE-wide WG via work-group barriers; the launch WG
15
+ // must match. Defaults to the Adreno sg (64); host passes -D FA_SG=32 on Intel.
16
+ #ifndef FA_SG
17
+ #define FA_SG 64
18
+ #endif
19
+ #define Q1_WG_SIZE FA_SG
20
+
21
+ // The kernels are built with -cl-finite-math-only. On some older Adreno GPUs,
22
+ // infinite operand can cause undefined behavior and miscompilation for exp.
23
+ // Therefore, a large negative value is used instead.
24
+ #define FA_M_INIT (-3.0e38f)
25
+
26
+ // Drop full unroll at DK>=192 — Adreno compiler host-memory budget.
27
+ #if DK >= 192
28
+ #define FA_UNROLL
29
+ #else
30
+ #define FA_UNROLL _Pragma("unroll")
31
+ #endif
32
+
33
+ inline float get_alibi_slope(
34
+ const float max_bias, const uint h, const uint n_head_log2, const float m0, const float m1
35
+ ) {
36
+ if (max_bias <= 0.0f) {
37
+ return 1.0f;
38
+ }
39
+ const float base = h < n_head_log2 ? m0 : m1;
40
+ const int exph = h < n_head_log2 ? h + 1 : 2*(h - n_head_log2) + 1;
41
+
42
+ return pow(base, exph);
43
+ }
44
+ __kernel void flash_attn_f32(
45
+ const global void * q_void, ulong q_offset,
46
+ const global void * k_void, ulong k_offset,
47
+ const global void * v_void, ulong v_offset,
48
+ global void * o_void, ulong o_offset,
49
+ const float scale,
50
+ const int n_q,
51
+ const int n_kv,
52
+ const int is_causal,
53
+ const int n_head,
54
+ const ulong q_nb1, const ulong q_nb2, const ulong q_nb3,
55
+ const ulong k_nb1, const ulong k_nb2, const ulong k_nb3,
56
+ const ulong v_nb1, const ulong v_nb2, const ulong v_nb3,
57
+ const ulong o_nb1, const ulong o_nb2, const ulong o_nb3,
58
+ const float max_bias,
59
+ const float m0,
60
+ const float m1,
61
+ const int n_head_log2,
62
+ const float logit_softcap,
63
+ const int n_head_kv,
64
+ const global void* mask_void,
65
+ const ulong mask_offset,
66
+ const ulong mask_nb1,
67
+ const ulong mask_nb2,
68
+ const ulong mask_nb3,
69
+ const int mask_ne2,
70
+ const int mask_ne3,
71
+ const global void* sinks_void,
72
+ const ulong sinks_offset
73
+ ) {
74
+ const int tid = get_local_id(0);
75
+ const int block_q_idx = get_group_id(0);
76
+ const int head_batch_idx = get_global_id(1);
77
+
78
+ const int my_query_row = block_q_idx * BLOCK_M + tid;
79
+
80
+ const int batch_idx = head_batch_idx / n_head;
81
+ const int head_idx = head_batch_idx % n_head;
82
+
83
+ const int gqa_ratio = n_head / n_head_kv;
84
+ const int head_kv_idx = head_idx / gqa_ratio;
85
+
86
+ const global char* q_base = (const global char*)q_void + q_offset;
87
+ const global char* k_base = (const global char*)k_void + k_offset;
88
+ const global char* v_base = (const global char*)v_void + v_offset;
89
+ global char* o_base = (global char*)o_void + o_offset;
90
+
91
+ const global char* mask_base = NULL;
92
+ if (mask_void != NULL) {
93
+ const int mask_head_idx = head_idx % mask_ne2;
94
+ const int mask_batch_idx = batch_idx % mask_ne3;
95
+ mask_base = (const global char*)mask_void + mask_offset + mask_batch_idx * mask_nb3 + mask_head_idx * mask_nb2;
96
+ }
97
+
98
+ ACC_TYPE4 q_priv[DK_VEC];
99
+ if (my_query_row < n_q) {
100
+ const ulong q_row_offset = batch_idx * q_nb3 + head_idx * q_nb2 + my_query_row * q_nb1;
101
+ const global DATA_TYPE4* q_ptr = (const global DATA_TYPE4*)(q_base + q_row_offset);
102
+ FA_UNROLL
103
+ for (int i = 0; i < DK_VEC; ++i) {
104
+ q_priv[i] = CONVERT_ACC4(q_ptr[i]);
105
+ }
106
+ }
107
+
108
+ ACC_TYPE4 o_acc[DV_VEC];
109
+ FA_UNROLL
110
+ for (int i = 0; i < DV_VEC; ++i) {
111
+ o_acc[i] = (ACC_TYPE4)(0.0f);
112
+ }
113
+ ACC_TYPE m_i = FA_M_INIT;
114
+ ACC_TYPE l_i = 0.0f;
115
+
116
+ float slope = get_alibi_slope(max_bias, head_idx, n_head_log2, m0, m1);
117
+
118
+ __local DATA_TYPE4 l_k[BLOCK_N][DK_VEC];
119
+ __local DATA_TYPE4 l_v[BLOCK_N][DV_VEC];
120
+
121
+ for (int k_start = 0; k_start < n_kv; k_start += BLOCK_N) {
122
+ #if FA_SG < 64
123
+ // WAR on l_k/l_v: threads with my_query_row >= n_q skip the compute below
124
+ // (continue) and would race ahead to reload the tiles while active threads
125
+ // still read them. A single 64-wide Adreno subgroup (WG == sg) runs lockstep
126
+ // and hides this; a WG that spans multiple narrower subgroups (Intel sg=32)
127
+ // corrupts the result. All threads reach this each iteration (no-op on the
128
+ // first), so it does not diverge with the continue. Compiled out at sg=64.
129
+ barrier(CLK_LOCAL_MEM_FENCE);
130
+ #endif
131
+ for (int i = tid; i < BLOCK_N * DK_VEC; i += WG_SIZE) {
132
+ const int row = i / DK_VEC;
133
+ const int col = i % DK_VEC;
134
+ const int k_row_idx = k_start + row;
135
+ if (k_row_idx < n_kv) {
136
+ const ulong k_row_offset = batch_idx * k_nb3 + head_kv_idx * k_nb2 + k_row_idx * k_nb1;
137
+ l_k[row][col] = ((__global DATA_TYPE4*)(k_base + k_row_offset))[col];
138
+ }
139
+ }
140
+ for (int i = tid; i < BLOCK_N * DV_VEC; i += WG_SIZE) {
141
+ const int row = i / DV_VEC;
142
+ const int col = i % DV_VEC;
143
+ const int v_row_idx = k_start + row;
144
+ if (v_row_idx < n_kv) {
145
+ const ulong v_row_offset = batch_idx * v_nb3 + head_kv_idx * v_nb2 + v_row_idx * v_nb1;
146
+ l_v[row][col] = ((__global DATA_TYPE4*)(v_base + v_row_offset))[col];
147
+ }
148
+ }
149
+ barrier(CLK_LOCAL_MEM_FENCE);
150
+
151
+ if (my_query_row >= n_q) {
152
+ continue;
153
+ }
154
+
155
+ for (int j = 0; j < BLOCK_N; j += 4) {
156
+ const int k_row0 = k_start + j;
157
+ const int k_row1 = k_start + j + 1;
158
+ const int k_row2 = k_start + j + 2;
159
+ const int k_row3 = k_start + j + 3;
160
+
161
+ ACC_TYPE4 dot_acc0 = (ACC_TYPE4)(0.0f);
162
+ ACC_TYPE4 dot_acc1 = (ACC_TYPE4)(0.0f);
163
+ ACC_TYPE4 dot_acc2 = (ACC_TYPE4)(0.0f);
164
+ ACC_TYPE4 dot_acc3 = (ACC_TYPE4)(0.0f);
165
+ FA_UNROLL
166
+ for (int k = 0; k < DK_VEC; k++) {
167
+ const ACC_TYPE4 qk = q_priv[k];
168
+ dot_acc0 = mad(qk, CONVERT_ACC4(l_k[j][k]), dot_acc0);
169
+ dot_acc1 = mad(qk, CONVERT_ACC4(l_k[j+1][k]), dot_acc1);
170
+ dot_acc2 = mad(qk, CONVERT_ACC4(l_k[j+2][k]), dot_acc2);
171
+ dot_acc3 = mad(qk, CONVERT_ACC4(l_k[j+3][k]), dot_acc3);
172
+ }
173
+ ACC_TYPE s0 = (dot_acc0.s0 + dot_acc0.s1 + dot_acc0.s2 + dot_acc0.s3) * scale;
174
+ ACC_TYPE s1 = (dot_acc1.s0 + dot_acc1.s1 + dot_acc1.s2 + dot_acc1.s3) * scale;
175
+ ACC_TYPE s2 = (dot_acc2.s0 + dot_acc2.s1 + dot_acc2.s2 + dot_acc2.s3) * scale;
176
+ ACC_TYPE s3 = (dot_acc3.s0 + dot_acc3.s1 + dot_acc3.s2 + dot_acc3.s3) * scale;
177
+
178
+ if (is_causal) {
179
+ const int causal_limit = n_kv - n_q + my_query_row;
180
+ if (k_row0 > causal_limit) s0 = FA_M_INIT;
181
+ if (k_row1 > causal_limit) s1 = FA_M_INIT;
182
+ if (k_row2 > causal_limit) s2 = FA_M_INIT;
183
+ if (k_row3 > causal_limit) s3 = FA_M_INIT;
184
+ }
185
+ if (k_row0 >= n_kv) s0 = FA_M_INIT;
186
+ if (k_row1 >= n_kv) s1 = FA_M_INIT;
187
+ if (k_row2 >= n_kv) s2 = FA_M_INIT;
188
+ if (k_row3 >= n_kv) s3 = FA_M_INIT;
189
+
190
+ if (mask_base != NULL) {
191
+ const global MASK_DATA_TYPE* mask_ptr = (const global MASK_DATA_TYPE*)(mask_base + my_query_row * mask_nb1);
192
+ if (k_row0 < n_kv) s0 += slope * (ACC_TYPE)mask_ptr[k_row0];
193
+ if (k_row1 < n_kv) s1 += slope * (ACC_TYPE)mask_ptr[k_row1];
194
+ if (k_row2 < n_kv) s2 += slope * (ACC_TYPE)mask_ptr[k_row2];
195
+ if (k_row3 < n_kv) s3 += slope * (ACC_TYPE)mask_ptr[k_row3];
196
+ }
197
+
198
+ if (logit_softcap > 0.0f) {
199
+ s0 = logit_softcap * tanh(s0 / logit_softcap);
200
+ s1 = logit_softcap * tanh(s1 / logit_softcap);
201
+ s2 = logit_softcap * tanh(s2 / logit_softcap);
202
+ s3 = logit_softcap * tanh(s3 / logit_softcap);
203
+ }
204
+
205
+ const ACC_TYPE m_new = max(m_i, max(max(s0, s1), max(s2, s3)));
206
+ const ACC_TYPE scale_prev = native_exp(m_i - m_new);
207
+ const ACC_TYPE p0 = native_exp(s0 - m_new);
208
+ const ACC_TYPE p1 = native_exp(s1 - m_new);
209
+ const ACC_TYPE p2 = native_exp(s2 - m_new);
210
+ const ACC_TYPE p3 = native_exp(s3 - m_new);
211
+
212
+ FA_UNROLL
213
+ for (int i = 0; i < DV_VEC; ++i) {
214
+ o_acc[i] = mad(p3, CONVERT_ACC4(l_v[j+3][i]),
215
+ mad(p2, CONVERT_ACC4(l_v[j+2][i]),
216
+ mad(p1, CONVERT_ACC4(l_v[j+1][i]),
217
+ mad(p0, CONVERT_ACC4(l_v[j][i]),
218
+ o_acc[i] * scale_prev))));
219
+ }
220
+ l_i = l_i * scale_prev + p0 + p1 + p2 + p3;
221
+ m_i = m_new;
222
+ }
223
+ }
224
+
225
+ if (my_query_row < n_q) {
226
+ if (sinks_void != NULL) {
227
+ const global ACC_TYPE* sinks_ptr = (const global ACC_TYPE*)((const global char*)sinks_void + sinks_offset);
228
+ const ACC_TYPE m_sink = sinks_ptr[head_idx];
229
+ const ACC_TYPE m_final = max(m_i, m_sink);
230
+
231
+ const ACC_TYPE scale_o = exp(m_i - m_final);
232
+ FA_UNROLL
233
+ for (int i = 0; i < DV_VEC; ++i) {
234
+ o_acc[i] *= scale_o;
235
+ }
236
+
237
+ l_i = l_i * exp(m_i - m_final) + exp(m_sink - m_final);
238
+ }
239
+
240
+ const ulong o_row_offset = batch_idx * o_nb3 + my_query_row * o_nb2 + head_idx * o_nb1;
241
+ global DATA_TYPE4 *o_row = (global DATA_TYPE4 *)(o_base + o_row_offset);
242
+ if (l_i > 0.0f) {
243
+ const ACC_TYPE l_inv = 1.0f / l_i;
244
+ FA_UNROLL
245
+ for (int i = 0; i < DV_VEC; ++i) {
246
+ o_row[i] = CONVERT_DATA4(o_acc[i] * l_inv);
247
+ }
248
+ } else {
249
+ FA_UNROLL
250
+ for (int i = 0; i < DV_VEC; ++i) {
251
+ o_row[i] = (DATA_TYPE4)(0.0f);
252
+ }
253
+ }
254
+ }
255
+ }
256
+
257
+ __kernel void flash_attn_f32_q1(
258
+ const global void * q_void, ulong q_offset,
259
+ const global void * k_void, ulong k_offset,
260
+ const global void * v_void, ulong v_offset,
261
+ global void * o_void, ulong o_offset,
262
+ const float scale,
263
+ const int n_q,
264
+ const int n_kv,
265
+ const int is_causal,
266
+ const int n_head,
267
+ const ulong q_nb1, const ulong q_nb2, const ulong q_nb3,
268
+ const ulong k_nb1, const ulong k_nb2, const ulong k_nb3,
269
+ const ulong v_nb1, const ulong v_nb2, const ulong v_nb3,
270
+ const ulong o_nb1, const ulong o_nb2, const ulong o_nb3,
271
+ const float max_bias,
272
+ const float m0,
273
+ const float m1,
274
+ const int n_head_log2,
275
+ const float logit_softcap,
276
+ const int n_head_kv,
277
+ const global void* mask_void,
278
+ const ulong mask_offset,
279
+ const ulong mask_nb1,
280
+ const ulong mask_nb2,
281
+ const ulong mask_nb3,
282
+ const int mask_ne2,
283
+ const int mask_ne3,
284
+ const global void* sinks_void,
285
+ const ulong sinks_offset
286
+ ) {
287
+ const int tid = get_local_id(0);
288
+ const int head_batch_idx = get_global_id(1);
289
+
290
+ const int batch_idx = head_batch_idx / n_head;
291
+ const int head_idx = head_batch_idx % n_head;
292
+
293
+ const int gqa_ratio = n_head / n_head_kv;
294
+ const int head_kv_idx = head_idx / gqa_ratio;
295
+
296
+ const global char* q_base = (const global char*)q_void + q_offset;
297
+ const global char* k_base = (const global char*)k_void + k_offset;
298
+ const global char* v_base = (const global char*)v_void + v_offset;
299
+ global char* o_base = (global char*)o_void + o_offset;
300
+
301
+ const global char* mask_base = NULL;
302
+ if (mask_void != NULL) {
303
+ const int mask_head_idx = head_idx % mask_ne2;
304
+ const int mask_batch_idx = batch_idx % mask_ne3;
305
+ mask_base = (const global char*)mask_void + mask_offset + mask_batch_idx * mask_nb3 + mask_head_idx * mask_nb2;
306
+ }
307
+
308
+ ACC_TYPE4 q_priv[DK_VEC];
309
+ const ulong q_row_offset = batch_idx * q_nb3 + head_idx * q_nb2;
310
+ const global DATA_TYPE4* q_ptr = (const global DATA_TYPE4*)(q_base + q_row_offset);
311
+ FA_UNROLL
312
+ for (int i = 0; i < DK_VEC; ++i) {
313
+ q_priv[i] = CONVERT_ACC4(q_ptr[i]);
314
+ }
315
+
316
+ float slope = get_alibi_slope(max_bias, head_idx, n_head_log2, m0, m1);
317
+
318
+ const global ACC_TYPE* sinks_ptr = NULL;
319
+ if (sinks_void != NULL) {
320
+ sinks_ptr = (const global ACC_TYPE*)((const global char*)sinks_void + sinks_offset);
321
+ }
322
+
323
+ ACC_TYPE m_i = (sinks_ptr != NULL) ? sinks_ptr[head_idx] : FA_M_INIT;
324
+ for (int k_idx = tid; k_idx < n_kv; k_idx += Q1_WG_SIZE) {
325
+ const ulong k_row_offset = batch_idx * k_nb3 + head_kv_idx * k_nb2 + k_idx * k_nb1;
326
+ const global DATA_TYPE4* k_ptr = (const global DATA_TYPE4*)(k_base + k_row_offset);
327
+ ACC_TYPE4 dot_acc = (ACC_TYPE4)(0.0f);
328
+ FA_UNROLL
329
+ for (int k = 0; k < DK_VEC; k++) {
330
+ dot_acc = mad(q_priv[k], CONVERT_ACC4(k_ptr[k]), dot_acc);
331
+ }
332
+ ACC_TYPE score = (dot_acc.s0 + dot_acc.s1 + dot_acc.s2 + dot_acc.s3) * scale;
333
+ if (mask_base != NULL) {
334
+ const global MASK_DATA_TYPE* mask_ptr = (const global MASK_DATA_TYPE*)(mask_base);
335
+ score += slope * (ACC_TYPE)mask_ptr[k_idx];
336
+ }
337
+ if (logit_softcap > 0.0f) {
338
+ score = logit_softcap * tanh(score / logit_softcap);
339
+ }
340
+ m_i = max(m_i, score);
341
+ }
342
+
343
+ __local ACC_TYPE local_m[Q1_WG_SIZE];
344
+ local_m[tid] = m_i;
345
+ barrier(CLK_LOCAL_MEM_FENCE);
346
+ FA_UNROLL
347
+ for (int s = Q1_WG_SIZE / 2; s > 0; s >>= 1) {
348
+ if (tid < s) local_m[tid] = max(local_m[tid], local_m[tid + s]);
349
+ barrier(CLK_LOCAL_MEM_FENCE);
350
+ }
351
+ const ACC_TYPE m_final = local_m[0];
352
+
353
+ ACC_TYPE4 o_acc[DV_VEC];
354
+ FA_UNROLL
355
+ for (int i = 0; i < DV_VEC; ++i) o_acc[i] = (ACC_TYPE4)(0.0f);
356
+ ACC_TYPE l_i = 0.0f;
357
+
358
+ for (int k_idx = tid; k_idx < n_kv; k_idx += Q1_WG_SIZE) {
359
+ const ulong k_row_offset = batch_idx * k_nb3 + head_kv_idx * k_nb2 + k_idx * k_nb1;
360
+ const ulong v_row_offset = batch_idx * v_nb3 + head_kv_idx * v_nb2 + k_idx * v_nb1;
361
+ const global DATA_TYPE4* k_ptr = (const global DATA_TYPE4*)(k_base + k_row_offset);
362
+ const global DATA_TYPE4* v_ptr = (const global DATA_TYPE4*)(v_base + v_row_offset);
363
+ ACC_TYPE4 dot_acc = (ACC_TYPE4)(0.0f);
364
+ FA_UNROLL
365
+ for (int k = 0; k < DK_VEC; k++) {
366
+ dot_acc = mad(q_priv[k], CONVERT_ACC4(k_ptr[k]), dot_acc);
367
+ }
368
+ ACC_TYPE score = (dot_acc.s0 + dot_acc.s1 + dot_acc.s2 + dot_acc.s3) * scale;
369
+ if (mask_base != NULL) {
370
+ const global MASK_DATA_TYPE* mask_ptr = (const global MASK_DATA_TYPE*)(mask_base);
371
+ score += slope * (ACC_TYPE)mask_ptr[k_idx];
372
+ }
373
+ if (logit_softcap > 0.0f) {
374
+ score = logit_softcap * tanh(score / logit_softcap);
375
+ }
376
+ const ACC_TYPE p = exp(score - m_final);
377
+ l_i += p;
378
+ FA_UNROLL
379
+ for (int i = 0; i < DV_VEC; i++) {
380
+ o_acc[i] = mad(p, CONVERT_ACC4(v_ptr[i]), o_acc[i]);
381
+ }
382
+ }
383
+
384
+ __local ACC_TYPE local_l[Q1_WG_SIZE];
385
+ __local ACC_TYPE4 local_o_comp[Q1_WG_SIZE];
386
+ local_l[tid] = l_i;
387
+ barrier(CLK_LOCAL_MEM_FENCE);
388
+ FA_UNROLL
389
+ for (int s = Q1_WG_SIZE / 2; s > 0; s >>= 1) {
390
+ if (tid < s) local_l[tid] += local_l[tid + s];
391
+ barrier(CLK_LOCAL_MEM_FENCE);
392
+ }
393
+
394
+ const ulong o_row_offset = batch_idx * o_nb3 + head_idx * o_nb1;
395
+ global DATA_TYPE4 *o_row = (global DATA_TYPE4 *)(o_base + o_row_offset);
396
+ ACC_TYPE l_final = local_l[0];
397
+
398
+ if (sinks_ptr != NULL) {
399
+ l_final += exp(sinks_ptr[head_idx] - m_final);
400
+ }
401
+
402
+ if (l_final > 0.0f) {
403
+ const ACC_TYPE l_inv = 1.0f / l_final;
404
+ for (int i = 0; i < DV_VEC; i++) {
405
+ local_o_comp[tid] = o_acc[i];
406
+ barrier(CLK_LOCAL_MEM_FENCE);
407
+ FA_UNROLL
408
+ for (int s = Q1_WG_SIZE / 2; s > 0; s >>= 1) {
409
+ if (tid < s) local_o_comp[tid] += local_o_comp[tid + s];
410
+ barrier(CLK_LOCAL_MEM_FENCE);
411
+ }
412
+ if (tid == 0) {
413
+ o_row[i] = CONVERT_DATA4(local_o_comp[0] * l_inv);
414
+ }
415
+ }
416
+ } else if (tid == 0) {
417
+ FA_UNROLL
418
+ for (int i = 0; i < DV_VEC; ++i) o_row[i] = (DATA_TYPE4)(0.0f);
419
+ }
420
+ }
ggml/src/ggml-opencl/kernels/flash_attn_f32_f16.cl ADDED
The diff for this file is too large to render. See raw diff
 
ggml/src/ggml-opencl/kernels/flash_attn_f32_q4_0.cl ADDED
@@ -0,0 +1,2011 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+ #ifdef cl_khr_integer_dot_product
3
+ #pragma OPENCL EXTENSION cl_khr_integer_dot_product : enable
4
+ #define FA_HAVE_INT_DOT 1
5
+ #endif
6
+
7
+ #ifdef cl_khr_subgroup_shuffle
8
+ #pragma OPENCL EXTENSION cl_khr_subgroup_shuffle : enable
9
+ #define HAS_SUBGROUP_SHUFFLE 1
10
+ #elif defined(cl_qcom_subgroup_shuffle)
11
+ #pragma OPENCL EXTENSION cl_qcom_subgroup_shuffle : enable
12
+ #define HAS_SUBGROUP_SHUFFLE 1
13
+ // Adreno compilers that expose only cl_qcom_subgroup_shuffle do not declare the KHR
14
+ // name, so calling it is an implicit declaration and the program fails to build.
15
+ // Route it to the qcom builtin.
16
+ #define sub_group_shuffle_xor(val, mask) qcom_sub_group_shuffle_xor((val), (mask), CLK_SUB_GROUP_SHUFFLE_WIDTH_WAVE_SIZE_QCOM, 0.0f)
17
+ #endif
18
+
19
+ // Flash attention: Q=f32, K=q4_0, V=q4_0.
20
+ // Block = half d + uchar qs[16]; qs[j] low/high nibble -> elem j / j+16.
21
+ // Dequant: val[i] = d * (nibble_i - 8). dp4a path runs on raw 0..15 nibbles
22
+ // and applies the -8*sum(q) correction once per block (needs Q q_sum).
23
+
24
+ #define ACC_TYPE float
25
+ #define ACC_TYPE4 float4
26
+ #define Q_DATA_TYPE4 float4
27
+ #define O_DATA_TYPE4 float4
28
+ #define MASK_DATA_TYPE half
29
+ #define CONVERT_Q_ACC4(x) (x)
30
+ #define CONVERT_O_DATA4(x) (x)
31
+
32
+ #define DK_VEC (DK/4)
33
+ #define DV_VEC (DV/4)
34
+
35
+ #ifndef FA_SG
36
+ #define FA_SG 64
37
+ #endif
38
+ #define Q1_WG_SIZE FA_SG
39
+
40
+ // The kernels are built with -cl-finite-math-only. On some older Adreno GPUs,
41
+ // infinite operand can cause undefined behavior and miscompilation for exp.
42
+ // Therefore, a large negative value is used instead.
43
+ #define FA_M_INIT (-3.0e38f)
44
+
45
+ #define QK4_0 32
46
+ #define Q4_0_BLOCK_SIZE 18
47
+
48
+ #define DK_Q4_BLOCKS (DK / QK4_0)
49
+ #define DV_Q4_BLOCKS (DV / QK4_0)
50
+
51
+ inline float dot_q4_0_f32(const global char * block_ptr, ACC_TYPE4 * q_slice) {
52
+ float d = vload_half(0, (const global half *)block_ptr);
53
+ const global uchar * qs = (const global uchar *)(block_ptr + 2);
54
+
55
+ float sum = 0.0f;
56
+ // Low nibbles -> elems 0..15.
57
+ #pragma unroll
58
+ for (int g = 0; g < 4; ++g) {
59
+ float4 nv = (float4)((float)(int)(qs[g*4 + 0] & 0x0F) - 8.0f,
60
+ (float)(int)(qs[g*4 + 1] & 0x0F) - 8.0f,
61
+ (float)(int)(qs[g*4 + 2] & 0x0F) - 8.0f,
62
+ (float)(int)(qs[g*4 + 3] & 0x0F) - 8.0f);
63
+ sum += dot(q_slice[g], nv);
64
+ }
65
+ // High nibbles -> elems 16..31.
66
+ #pragma unroll
67
+ for (int g = 0; g < 4; ++g) {
68
+ float4 nv = (float4)((float)(int)(qs[g*4 + 0] >> 4) - 8.0f,
69
+ (float)(int)(qs[g*4 + 1] >> 4) - 8.0f,
70
+ (float)(int)(qs[g*4 + 2] >> 4) - 8.0f,
71
+ (float)(int)(qs[g*4 + 3] >> 4) - 8.0f);
72
+ sum += dot(q_slice[4 + g], nv);
73
+ }
74
+ return sum * d;
75
+ }
76
+
77
+ #ifdef FA_HAVE_INT_DOT
78
+ inline uint pack_i8x4(char a, char b, char c, char d) {
79
+ return ((uint)(uchar)a) |
80
+ ((uint)(uchar)b) << 8 |
81
+ ((uint)(uchar)c) << 16 |
82
+ ((uint)(uchar)d) << 24;
83
+ }
84
+
85
+ // Returns (qd, q_sum); q_sum feeds the -8*sum(q) bias correction.
86
+ typedef struct {
87
+ float qd;
88
+ int q_sum;
89
+ } q4_q_block_info;
90
+
91
+ inline q4_q_block_info quant_q_block_int8_packed_q4(const ACC_TYPE4 * q_block,
92
+ uint * out_packed) {
93
+ float amax = 0.0f;
94
+ #pragma unroll
95
+ for (int i = 0; i < 8; ++i) {
96
+ float4 av = fabs(q_block[i]);
97
+ amax = fmax(amax, fmax(fmax(av.s0, av.s1), fmax(av.s2, av.s3)));
98
+ }
99
+ float qd = amax / 127.0f;
100
+ float qid = (amax > 0.0f) ? 127.0f / amax : 0.0f;
101
+
102
+ int q_sum = 0;
103
+ #pragma unroll
104
+ for (int i = 0; i < 8; ++i) {
105
+ float4 v = q_block[i] * qid;
106
+ char a = (char)((int)round(v.s0));
107
+ char b = (char)((int)round(v.s1));
108
+ char c = (char)((int)round(v.s2));
109
+ char d = (char)((int)round(v.s3));
110
+ out_packed[i] = pack_i8x4(a, b, c, d);
111
+ q_sum += (int)a + (int)b + (int)c + (int)d;
112
+ }
113
+ q4_q_block_info info = { qd, q_sum };
114
+ return info;
115
+ }
116
+
117
+ // k_packed[0..3] = low nibbles (Q elems 0..15), k_packed[4..7] = high (16..31).
118
+ inline void pack_q4_0_nibbles(const global uchar * qs, uint * k_packed) {
119
+ #pragma unroll
120
+ for (int g = 0; g < 4; ++g) {
121
+ uchar b0 = qs[g*4 + 0];
122
+ uchar b1 = qs[g*4 + 1];
123
+ uchar b2 = qs[g*4 + 2];
124
+ uchar b3 = qs[g*4 + 3];
125
+ k_packed[g] =
126
+ ((uint)(b0 & 0x0F)) |
127
+ ((uint)(b1 & 0x0F)) << 8 |
128
+ ((uint)(b2 & 0x0F)) << 16 |
129
+ ((uint)(b3 & 0x0F)) << 24;
130
+ k_packed[4 + g] =
131
+ ((uint)(b0 >> 4)) |
132
+ ((uint)(b1 >> 4)) << 8 |
133
+ ((uint)(b2 >> 4)) << 16 |
134
+ ((uint)(b3 >> 4)) << 24;
135
+ }
136
+ }
137
+
138
+ inline float dot_q4_0_int(const global char * k_block_ptr,
139
+ const uint * q_packed,
140
+ float q_d,
141
+ int q_sum) {
142
+ float kd = vload_half(0, (const global half *)k_block_ptr);
143
+ const global uchar * k_qs = (const global uchar *)(k_block_ptr + 2);
144
+
145
+ uint k_packed[8];
146
+ pack_q4_0_nibbles(k_qs, k_packed);
147
+
148
+ int sum = 0;
149
+ #pragma unroll
150
+ for (int i = 0; i < 8; ++i) {
151
+ sum = dot_acc_sat_4x8packed_ss_int(q_packed[i], k_packed[i], sum);
152
+ }
153
+ // Correct raw-nibble sum: (nibble - 8) bias -> subtract 8 * q_sum.
154
+ return (float)(sum - 8 * q_sum) * q_d * kd;
155
+ }
156
+ #endif // FA_HAVE_INT_DOT
157
+
158
+ inline void dequant_q4_0_f32(const global char * block_ptr, ACC_TYPE4 * out) {
159
+ float d = vload_half(0, (const global half *)block_ptr);
160
+ const global uchar * qs = (const global uchar *)(block_ptr + 2);
161
+
162
+ #pragma unroll
163
+ for (int g = 0; g < 4; ++g) {
164
+ out[g] = d * (float4)((float)(int)(qs[g*4 + 0] & 0x0F) - 8.0f,
165
+ (float)(int)(qs[g*4 + 1] & 0x0F) - 8.0f,
166
+ (float)(int)(qs[g*4 + 2] & 0x0F) - 8.0f,
167
+ (float)(int)(qs[g*4 + 3] & 0x0F) - 8.0f);
168
+ }
169
+ #pragma unroll
170
+ for (int g = 0; g < 4; ++g) {
171
+ out[4 + g] = d * (float4)((float)(int)(qs[g*4 + 0] >> 4) - 8.0f,
172
+ (float)(int)(qs[g*4 + 1] >> 4) - 8.0f,
173
+ (float)(int)(qs[g*4 + 2] >> 4) - 8.0f,
174
+ (float)(int)(qs[g*4 + 3] >> 4) - 8.0f);
175
+ }
176
+ }
177
+
178
+ // max_bias<=0 returns 1.0 so score += 1.0 * mask[k] stays a no-op multiplier.
179
+ inline float get_alibi_slope(float max_bias, int head_idx, int n_head_log2, float m0, float m1) {
180
+ if (max_bias <= 0.0f) return 1.0f;
181
+ float base = (head_idx < n_head_log2) ? m0 : m1;
182
+ int exph = (head_idx < n_head_log2) ? (head_idx + 1) : (2*(head_idx - n_head_log2) + 1);
183
+ return pow(base, (float)exph);
184
+ }
185
+
186
+ // q1 decode: one query row per WG, threads sweep KV positions.
187
+ __kernel void flash_attn_f32_q4_0_q1(
188
+ const global void * q_void, ulong q_offset,
189
+ const global void * k_void, ulong k_offset,
190
+ const global void * v_void, ulong v_offset,
191
+ global void * o_void, ulong o_offset,
192
+ const float scale,
193
+ const int n_q,
194
+ const int n_kv,
195
+ const int is_causal,
196
+ const int n_head,
197
+ const ulong q_nb1, const ulong q_nb2, const ulong q_nb3,
198
+ const ulong k_nb1, const ulong k_nb2, const ulong k_nb3,
199
+ const ulong v_nb1, const ulong v_nb2, const ulong v_nb3,
200
+ const ulong o_nb1, const ulong o_nb2, const ulong o_nb3,
201
+ const float max_bias,
202
+ const float m0,
203
+ const float m1,
204
+ const int n_head_log2,
205
+ const float logit_softcap,
206
+ const int n_head_kv,
207
+ const global void* mask_void,
208
+ const ulong mask_offset,
209
+ const ulong mask_nb1,
210
+ const ulong mask_nb2,
211
+ const ulong mask_nb3,
212
+ const int mask_ne2,
213
+ const int mask_ne3,
214
+ const global void* sinks_void,
215
+ const ulong sinks_offset
216
+ ) {
217
+ const int tid = get_local_id(0);
218
+ const int head_batch_idx = get_global_id(1);
219
+
220
+ const int batch_idx = head_batch_idx / n_head;
221
+ const int head_idx = head_batch_idx % n_head;
222
+
223
+ const int gqa_ratio = n_head / n_head_kv;
224
+ const int head_kv_idx = head_idx / gqa_ratio;
225
+
226
+ const global char* q_base = (const global char*)q_void + q_offset;
227
+ const global char* k_base = (const global char*)k_void + k_offset;
228
+ const global char* v_base = (const global char*)v_void + v_offset;
229
+ global char* o_base = (global char*)o_void + o_offset;
230
+
231
+ const global char* mask_base = NULL;
232
+ if (mask_void != NULL) {
233
+ const int mask_head_idx = head_idx % mask_ne2;
234
+ const int mask_batch_idx = batch_idx % mask_ne3;
235
+ mask_base = (const global char*)mask_void + mask_offset + mask_batch_idx * mask_nb3 + mask_head_idx * mask_nb2;
236
+ }
237
+
238
+ ACC_TYPE4 q_priv[DK_VEC];
239
+ const ulong q_row_offset = batch_idx * q_nb3 + head_idx * q_nb2;
240
+ const global Q_DATA_TYPE4* q_ptr = (const global Q_DATA_TYPE4*)(q_base + q_row_offset);
241
+ #pragma unroll
242
+ for (int i = 0; i < DK_VEC; ++i) {
243
+ q_priv[i] = CONVERT_Q_ACC4(q_ptr[i]);
244
+ }
245
+
246
+ #ifdef FA_HAVE_INT_DOT
247
+ // Quantise Q once per thread: 8 uints + qd + q_sum per block.
248
+ uint q_packed[DK_Q4_BLOCKS * 8];
249
+ float q_d_scale[DK_Q4_BLOCKS];
250
+ int q_sum_arr[DK_Q4_BLOCKS];
251
+ #pragma unroll
252
+ for (int b = 0; b < DK_Q4_BLOCKS; ++b) {
253
+ q4_q_block_info info = quant_q_block_int8_packed_q4(&q_priv[b * 8], &q_packed[b * 8]);
254
+ q_d_scale[b] = info.qd;
255
+ q_sum_arr[b] = info.q_sum;
256
+ }
257
+ #endif
258
+
259
+ float slope = get_alibi_slope(max_bias, head_idx, n_head_log2, m0, m1);
260
+
261
+ const global ACC_TYPE* sinks_ptr = NULL;
262
+ if (sinks_void != NULL) {
263
+ sinks_ptr = (const global ACC_TYPE*)((const global char*)sinks_void + sinks_offset);
264
+ }
265
+
266
+ // One-pass online softmax (FA-2): single sweep over kv positions,
267
+ // updating per-thread (m_i, l_i, o_acc) per K. Eliminates the second
268
+ // K read of the original two-pass implementation.
269
+ ACC_TYPE m_i = (sinks_ptr != NULL) ? sinks_ptr[head_idx] : FA_M_INIT;
270
+ ACC_TYPE l_i = 0.0f;
271
+ ACC_TYPE4 o_acc[DV_VEC];
272
+ #pragma unroll
273
+ for (int i = 0; i < DV_VEC; ++i) o_acc[i] = (ACC_TYPE4)(0.0f);
274
+
275
+ for (int k_idx = tid; k_idx < n_kv; k_idx += Q1_WG_SIZE) {
276
+ const global char* k_row = k_base + batch_idx * k_nb3 + head_kv_idx * k_nb2 + k_idx * k_nb1;
277
+ const global char* v_row = v_base + batch_idx * v_nb3 + head_kv_idx * v_nb2 + k_idx * v_nb1;
278
+
279
+ ACC_TYPE score = 0.0f;
280
+ #pragma unroll
281
+ for (int b = 0; b < DK_Q4_BLOCKS; b++) {
282
+ #ifdef FA_HAVE_INT_DOT
283
+ score += dot_q4_0_int(k_row + b * Q4_0_BLOCK_SIZE,
284
+ &q_packed[b * 8], q_d_scale[b], q_sum_arr[b]);
285
+ #else
286
+ score += dot_q4_0_f32(k_row + b * Q4_0_BLOCK_SIZE, &q_priv[b * 8]);
287
+ #endif
288
+ }
289
+ score *= scale;
290
+
291
+ if (mask_base != NULL) {
292
+ const global MASK_DATA_TYPE* mask_ptr = (const global MASK_DATA_TYPE*)(mask_base);
293
+ score += slope * (ACC_TYPE)mask_ptr[k_idx];
294
+ }
295
+ if (logit_softcap > 0.0f) {
296
+ score = logit_softcap * tanh(score / logit_softcap);
297
+ }
298
+
299
+ // Online softmax step.
300
+ const ACC_TYPE m_new = max(m_i, score);
301
+ const ACC_TYPE alpha = exp(m_i - m_new);
302
+ const ACC_TYPE p = exp(score - m_new);
303
+
304
+ l_i = alpha * l_i + p;
305
+ #pragma unroll
306
+ for (int i = 0; i < DV_VEC; ++i) o_acc[i] *= alpha;
307
+
308
+ #pragma unroll
309
+ for (int b = 0; b < DV_Q4_BLOCKS; b++) {
310
+ ACC_TYPE4 v_dequant[8];
311
+ dequant_q4_0_f32(v_row + b * Q4_0_BLOCK_SIZE, v_dequant);
312
+ #pragma unroll
313
+ for (int i = 0; i < 8; i++) {
314
+ o_acc[b * 8 + i] = mad(p, v_dequant[i], o_acc[b * 8 + i]);
315
+ }
316
+ }
317
+
318
+ m_i = m_new;
319
+ }
320
+
321
+ // Cross-thread reduce: max(m_i) -> m_final, rescale per-thread l_i and
322
+ // o_acc by alpha = exp(m_i_thread - m_final) before sum-reduce.
323
+ __local ACC_TYPE local_m[Q1_WG_SIZE];
324
+ local_m[tid] = m_i;
325
+ barrier(CLK_LOCAL_MEM_FENCE);
326
+ #pragma unroll
327
+ for (int s = Q1_WG_SIZE / 2; s > 0; s >>= 1) {
328
+ if (tid < s) local_m[tid] = max(local_m[tid], local_m[tid + s]);
329
+ barrier(CLK_LOCAL_MEM_FENCE);
330
+ }
331
+ const ACC_TYPE m_final = local_m[0];
332
+
333
+ const ACC_TYPE alpha_final = exp(m_i - m_final);
334
+ l_i *= alpha_final;
335
+ #pragma unroll
336
+ for (int i = 0; i < DV_VEC; ++i) o_acc[i] *= alpha_final;
337
+
338
+ __local ACC_TYPE local_l[Q1_WG_SIZE];
339
+ __local ACC_TYPE4 local_o_comp[Q1_WG_SIZE];
340
+ local_l[tid] = l_i;
341
+ barrier(CLK_LOCAL_MEM_FENCE);
342
+ #pragma unroll
343
+ for (int s = Q1_WG_SIZE / 2; s > 0; s >>= 1) {
344
+ if (tid < s) local_l[tid] += local_l[tid + s];
345
+ barrier(CLK_LOCAL_MEM_FENCE);
346
+ }
347
+
348
+ const ulong o_row_offset = batch_idx * o_nb3 + head_idx * o_nb1;
349
+ global O_DATA_TYPE4 *o_row = (global O_DATA_TYPE4 *)(o_base + o_row_offset);
350
+ ACC_TYPE l_final = local_l[0];
351
+
352
+ if (sinks_ptr != NULL) {
353
+ l_final += exp(sinks_ptr[head_idx] - m_final);
354
+ }
355
+
356
+ if (l_final > 0.0f) {
357
+ const ACC_TYPE l_inv = 1.0f / l_final;
358
+ for (int i = 0; i < DV_VEC; i++) {
359
+ local_o_comp[tid] = o_acc[i];
360
+ barrier(CLK_LOCAL_MEM_FENCE);
361
+ #pragma unroll
362
+ for (int s = Q1_WG_SIZE / 2; s > 0; s >>= 1) {
363
+ if (tid < s) local_o_comp[tid] += local_o_comp[tid + s];
364
+ barrier(CLK_LOCAL_MEM_FENCE);
365
+ }
366
+ if (tid == 0) {
367
+ o_row[i] = CONVERT_O_DATA4(local_o_comp[0] * l_inv);
368
+ }
369
+ }
370
+ } else if (tid == 0) {
371
+ #pragma unroll
372
+ for (int i = 0; i < DV_VEC; ++i) o_row[i] = (O_DATA_TYPE4)(0.0f);
373
+ }
374
+ }
375
+
376
+ #ifdef cl_intel_subgroups
377
+ #pragma OPENCL EXTENSION cl_intel_subgroups : enable
378
+ #else
379
+ #pragma OPENCL EXTENSION cl_khr_subgroups : enable
380
+ #endif
381
+
382
+ #ifdef cl_qcom_reqd_sub_group_size
383
+ #pragma OPENCL EXTENSION cl_qcom_reqd_sub_group_size : enable
384
+ #define REQD_SUBGROUP_SIZE_64 __attribute__((qcom_reqd_sub_group_size("half")))
385
+ #else
386
+ #define REQD_SUBGROUP_SIZE_64
387
+ #endif
388
+
389
+ #define VEC_NSG 4
390
+ #define VEC_WG_SIZE (Q1_WG_SIZE * VEC_NSG)
391
+ #define Q1V_DV_PER_THREAD ((DV_VEC + Q1_WG_SIZE - 1) / Q1_WG_SIZE)
392
+
393
+ // Dequant one float4 lane (0..7) from a q4_0 block.
394
+ // Lanes 0..3 → low nibbles of qs[0..15], lanes 4..7 → high nibbles.
395
+ inline float4 dequant_q4_0_lane(const global char * block_ptr, int lane) {
396
+ const float d = vload_half(0, (const global half *)block_ptr);
397
+ const global uchar * qs = (const global uchar *)(block_ptr + 2);
398
+ const int g = lane & 3;
399
+ const int shift = (lane < 4) ? 0 : 4;
400
+ return d * (float4)((float)((qs[g*4+0] >> shift) & 0x0F) - 8.0f,
401
+ (float)((qs[g*4+1] >> shift) & 0x0F) - 8.0f,
402
+ (float)((qs[g*4+2] >> shift) & 0x0F) - 8.0f,
403
+ (float)((qs[g*4+3] >> shift) & 0x0F) - 8.0f);
404
+ }
405
+
406
+ REQD_SUBGROUP_SIZE_64
407
+ __kernel void flash_attn_f32_q4_0_q1_vec(
408
+ const global void * q_void, ulong q_offset,
409
+ const global void * k_void, ulong k_offset,
410
+ const global void * v_void, ulong v_offset,
411
+ global void * o_void, ulong o_offset,
412
+ const float scale,
413
+ const int n_q,
414
+ const int n_kv,
415
+ const int is_causal,
416
+ const int n_head,
417
+ const ulong q_nb1, const ulong q_nb2, const ulong q_nb3,
418
+ const ulong k_nb1, const ulong k_nb2, const ulong k_nb3,
419
+ const ulong v_nb1, const ulong v_nb2, const ulong v_nb3,
420
+ const ulong o_nb1, const ulong o_nb2, const ulong o_nb3,
421
+ const float max_bias,
422
+ const float m0,
423
+ const float m1,
424
+ const int n_head_log2,
425
+ const float logit_softcap,
426
+ const int n_head_kv,
427
+ const global void* mask_void,
428
+ const ulong mask_offset,
429
+ const ulong mask_nb1,
430
+ const ulong mask_nb2,
431
+ const ulong mask_nb3,
432
+ const int mask_ne2,
433
+ const int mask_ne3,
434
+ const global void* sinks_void,
435
+ const ulong sinks_offset
436
+ ) {
437
+ const int tid = get_local_id(0);
438
+ const int sgid = tid / Q1_WG_SIZE;
439
+ const int tid_sg = tid % Q1_WG_SIZE;
440
+ const int head_batch_idx = get_global_id(1);
441
+
442
+ const int batch_idx = head_batch_idx / n_head;
443
+ const int head_idx = head_batch_idx % n_head;
444
+
445
+ const int gqa_ratio = n_head / n_head_kv;
446
+ const int head_kv_idx = head_idx / gqa_ratio;
447
+
448
+ const global char * q_base = (const global char *) q_void + q_offset;
449
+ const global char * k_base = (const global char *) k_void + k_offset;
450
+ const global char * v_base = (const global char *) v_void + v_offset;
451
+ global char * o_base = (global char *) o_void + o_offset;
452
+
453
+ const global char * mask_base = NULL;
454
+ if (mask_void != NULL) {
455
+ const int mask_head_idx = head_idx % mask_ne2;
456
+ const int mask_batch_idx = batch_idx % mask_ne3;
457
+ mask_base = (const global char *) mask_void + mask_offset +
458
+ mask_batch_idx * mask_nb3 + mask_head_idx * mask_nb2;
459
+ }
460
+
461
+ __local ACC_TYPE4 q_shared[DK_VEC];
462
+ {
463
+ const ulong q_row_offset = batch_idx * q_nb3 + head_idx * q_nb2;
464
+ const global Q_DATA_TYPE4 * q_ptr = (const global Q_DATA_TYPE4 *) (q_base + q_row_offset);
465
+ for (int i = tid; i < DK_VEC; i += VEC_WG_SIZE) {
466
+ q_shared[i] = CONVERT_Q_ACC4(q_ptr[i]);
467
+ }
468
+ }
469
+ barrier(CLK_LOCAL_MEM_FENCE);
470
+
471
+ #ifdef FA_HAVE_INT_DOT
472
+ // quantize Q to int8-packed uints + per-block (qd, q_sum) once per WG for dp4a
473
+ // one thread per Q block, remaining threads idle this step
474
+ __local uint q_packed_shared[DK_Q4_BLOCKS * 8];
475
+ __local float q_d_shared[DK_Q4_BLOCKS];
476
+ __local int q_sum_shared[DK_Q4_BLOCKS];
477
+ if (tid < DK_Q4_BLOCKS) {
478
+ ACC_TYPE4 q_block[8];
479
+ #pragma unroll
480
+ for (int i = 0; i < 8; ++i) q_block[i] = q_shared[tid * 8 + i];
481
+ uint packed[8];
482
+ q4_q_block_info info = quant_q_block_int8_packed_q4(q_block, packed);
483
+ #pragma unroll
484
+ for (int i = 0; i < 8; ++i) q_packed_shared[tid * 8 + i] = packed[i];
485
+ q_d_shared[tid] = info.qd;
486
+ q_sum_shared[tid] = info.q_sum;
487
+ }
488
+ barrier(CLK_LOCAL_MEM_FENCE);
489
+ #endif
490
+
491
+ const float slope = get_alibi_slope(max_bias, head_idx, n_head_log2, m0, m1);
492
+
493
+ const global ACC_TYPE * sinks_ptr = NULL;
494
+ if (sinks_void != NULL) {
495
+ sinks_ptr = (const global ACC_TYPE *) ((const global char *) sinks_void + sinks_offset);
496
+ }
497
+
498
+ ACC_TYPE4 o_acc[Q1V_DV_PER_THREAD];
499
+ #pragma unroll
500
+ for (int i = 0; i < Q1V_DV_PER_THREAD; ++i) o_acc[i] = (ACC_TYPE4)(0.0f);
501
+
502
+ ACC_TYPE m_i = FA_M_INIT;
503
+ ACC_TYPE l_i = 0.0f;
504
+
505
+ const int kv_per_sg = (n_kv + VEC_NSG - 1) / VEC_NSG;
506
+ const int kv_start = sgid * kv_per_sg;
507
+ const int kv_end = min(n_kv, kv_start + kv_per_sg);
508
+
509
+ for (int k_idx = kv_start; k_idx < kv_end; ++k_idx) {
510
+ const global char * k_row = k_base + batch_idx * k_nb3 + head_kv_idx * k_nb2 + k_idx * k_nb1;
511
+ const global char * v_row = v_base + batch_idx * v_nb3 + head_kv_idx * v_nb2 + k_idx * v_nb1;
512
+
513
+ #ifdef FA_HAVE_INT_DOT
514
+ // per-lane dp4a: each lane packs 4 raw q4_0 nibbles into a uint,
515
+ // then dot_acc_sat_4x8packed_ss_int against the matching uint.
516
+ ACC_TYPE lane_contrib = 0.0f;
517
+ for (int qk = tid_sg; qk < DK_VEC; qk += Q1_WG_SIZE) {
518
+ const int block_idx = qk / 8;
519
+ const int lane_in_block = qk % 8;
520
+ const int g = lane_in_block & 3;
521
+ const int shift = (lane_in_block < 4) ? 0 : 4;
522
+ const global char * k_block = k_row + block_idx * Q4_0_BLOCK_SIZE;
523
+ const float kd = vload_half(0, (const global half *)k_block);
524
+ const global uchar * k_qs = (const global uchar *)(k_block + 2);
525
+ const uchar b0 = k_qs[g*4 + 0];
526
+ const uchar b1 = k_qs[g*4 + 1];
527
+ const uchar b2 = k_qs[g*4 + 2];
528
+ const uchar b3 = k_qs[g*4 + 3];
529
+ const uint k_packed = ((uint)((b0 >> shift) & 0x0F)) |
530
+ ((uint)((b1 >> shift) & 0x0F)) << 8 |
531
+ ((uint)((b2 >> shift) & 0x0F)) << 16 |
532
+ ((uint)((b3 >> shift) & 0x0F)) << 24;
533
+ const uint q_packed_lane = q_packed_shared[block_idx * 8 + lane_in_block];
534
+ const int raw_dot = dot_acc_sat_4x8packed_ss_int(q_packed_lane, k_packed, 0);
535
+ const float qd = q_d_shared[block_idx];
536
+ const float block_scale = qd * kd;
537
+ float contrib = (float)raw_dot * block_scale;
538
+ if (lane_in_block == 0) {
539
+ // block bias correction is per-block
540
+ const int q_sum_b = q_sum_shared[block_idx];
541
+ contrib -= 8.0f * block_scale * (float)q_sum_b;
542
+ }
543
+ lane_contrib += contrib;
544
+ }
545
+ ACC_TYPE score = sub_group_reduce_add(lane_contrib) * scale;
546
+ #else
547
+ ACC_TYPE4 dot4 = (ACC_TYPE4)(0.0f);
548
+ for (int qk = tid_sg; qk < DK_VEC; qk += Q1_WG_SIZE) {
549
+ const int block_idx = qk / 8;
550
+ const int lane = qk % 8;
551
+ const float4 k_v = dequant_q4_0_lane(k_row + block_idx * Q4_0_BLOCK_SIZE, lane);
552
+ dot4 = mad(q_shared[qk], k_v, dot4);
553
+ }
554
+ ACC_TYPE dot_partial = dot4.s0 + dot4.s1 + dot4.s2 + dot4.s3;
555
+ ACC_TYPE score = sub_group_reduce_add(dot_partial) * scale;
556
+ #endif
557
+
558
+ if (mask_base != NULL) {
559
+ const global MASK_DATA_TYPE * mask_ptr = (const global MASK_DATA_TYPE *) mask_base;
560
+ score += slope * (ACC_TYPE) mask_ptr[k_idx];
561
+ }
562
+ if (logit_softcap > 0.0f) {
563
+ score = logit_softcap * tanh(score / logit_softcap);
564
+ }
565
+
566
+ const ACC_TYPE m_new = max(m_i, score);
567
+ const ACC_TYPE scale_prev = native_exp(m_i - m_new);
568
+ const ACC_TYPE p = native_exp(score - m_new);
569
+
570
+ int idx = 0;
571
+ for (int dv = tid_sg; dv < DV_VEC; dv += Q1_WG_SIZE, ++idx) {
572
+ const int block_idx = dv / 8;
573
+ const int lane = dv % 8;
574
+ const float4 v_v = dequant_q4_0_lane(v_row + block_idx * Q4_0_BLOCK_SIZE, lane);
575
+ o_acc[idx] = mad(p, v_v, o_acc[idx] * scale_prev);
576
+ }
577
+ l_i = l_i * scale_prev + p;
578
+ m_i = m_new;
579
+ }
580
+
581
+ __local ACC_TYPE sg_m[VEC_NSG];
582
+ __local ACC_TYPE sg_l[VEC_NSG];
583
+ __local ACC_TYPE4 sg_o[VEC_NSG][DV_VEC];
584
+
585
+ if (tid_sg == 0) {
586
+ sg_m[sgid] = m_i;
587
+ sg_l[sgid] = l_i;
588
+ }
589
+ {
590
+ int idx = 0;
591
+ for (int dv = tid_sg; dv < DV_VEC; dv += Q1_WG_SIZE, ++idx) {
592
+ sg_o[sgid][dv] = o_acc[idx];
593
+ }
594
+ }
595
+ barrier(CLK_LOCAL_MEM_FENCE);
596
+
597
+ if (sgid == 0) {
598
+ ACC_TYPE m_final = sg_m[0];
599
+ #pragma unroll
600
+ for (int s = 1; s < VEC_NSG; ++s) {
601
+ m_final = max(m_final, sg_m[s]);
602
+ }
603
+ if (sinks_ptr != NULL) {
604
+ m_final = max(m_final, sinks_ptr[head_idx]);
605
+ }
606
+
607
+ ACC_TYPE l_final = 0.0f;
608
+ #pragma unroll
609
+ for (int s = 0; s < VEC_NSG; ++s) {
610
+ l_final += sg_l[s] * native_exp(sg_m[s] - m_final);
611
+ }
612
+ if (sinks_ptr != NULL) {
613
+ l_final += native_exp(sinks_ptr[head_idx] - m_final);
614
+ }
615
+ const ACC_TYPE l_inv = (l_final > 0.0f) ? (1.0f / l_final) : 0.0f;
616
+
617
+ const ulong o_row_offset = batch_idx * o_nb3 + head_idx * o_nb1;
618
+ global O_DATA_TYPE4 * o_row = (global O_DATA_TYPE4 *) (o_base + o_row_offset);
619
+
620
+ int idx = 0;
621
+ for (int dv = tid_sg; dv < DV_VEC; dv += Q1_WG_SIZE, ++idx) {
622
+ ACC_TYPE4 o_merged = (ACC_TYPE4)(0.0f);
623
+ #pragma unroll
624
+ for (int s = 0; s < VEC_NSG; ++s) {
625
+ const ACC_TYPE alpha = native_exp(sg_m[s] - m_final);
626
+ o_merged = mad((ACC_TYPE4)(alpha), sg_o[s][dv], o_merged);
627
+ }
628
+ o_row[dv] = CONVERT_O_DATA4(o_merged * l_inv);
629
+ }
630
+ }
631
+ }
632
+
633
+ // Flash-decoding split pass for q4_0 KV. Merge kernel is type-agnostic and
634
+ // shared with the f16/q8_0 FA kernels.
635
+ #define FA_PARTIAL_FLOATS (2 + DV)
636
+
637
+ __kernel void flash_attn_f32_q4_0_q1_split(
638
+ const global void * q_void, ulong q_offset,
639
+ const global void * k_void, ulong k_offset,
640
+ const global void * v_void, ulong v_offset,
641
+ const float scale,
642
+ const int n_q,
643
+ const int n_kv,
644
+ const int n_head,
645
+ const ulong q_nb1, const ulong q_nb2, const ulong q_nb3,
646
+ const ulong k_nb1, const ulong k_nb2, const ulong k_nb3,
647
+ const ulong v_nb1, const ulong v_nb2, const ulong v_nb3,
648
+ const float max_bias,
649
+ const float m0,
650
+ const float m1,
651
+ const int n_head_log2,
652
+ const float logit_softcap,
653
+ const int n_head_kv,
654
+ const global void * mask_void,
655
+ const ulong mask_offset,
656
+ const ulong mask_nb1,
657
+ const ulong mask_nb2,
658
+ const ulong mask_nb3,
659
+ const int mask_ne2,
660
+ const int mask_ne3,
661
+ global float * partial_void,
662
+ const int n_splits,
663
+ const int kv_per_split
664
+ ) {
665
+ const int tid = get_local_id(0);
666
+ const int head_batch_idx = get_global_id(1);
667
+ const int split_q_idx = get_global_id(2);
668
+ const int split_idx = split_q_idx % n_splits;
669
+ const int q_idx = split_q_idx / n_splits;
670
+ const int batch_idx = head_batch_idx / n_head;
671
+ const int head_idx = head_batch_idx % n_head;
672
+ const int gqa_ratio = n_head / n_head_kv;
673
+ const int head_kv_idx = head_idx / gqa_ratio;
674
+
675
+ const int kv_start = split_idx * kv_per_split;
676
+ const int kv_end = min(kv_start + kv_per_split, n_kv);
677
+
678
+ const ulong record_stride = (ulong) FA_PARTIAL_FLOATS;
679
+ const ulong record_idx = ((((ulong) batch_idx * n_head + head_idx) * n_q + q_idx)
680
+ * n_splits + split_idx);
681
+ global float * rec = partial_void + record_idx * record_stride;
682
+ global float4 * rec_o = (global float4 *) (rec + 2);
683
+
684
+ if (kv_start >= kv_end) {
685
+ if (tid == 0) {
686
+ rec[0] = FA_M_INIT;
687
+ rec[1] = 0.0f;
688
+ }
689
+ return;
690
+ }
691
+
692
+ const global char * q_base = (const global char *) q_void + q_offset;
693
+ const global char * k_base = (const global char *) k_void + k_offset;
694
+ const global char * v_base = (const global char *) v_void + v_offset;
695
+
696
+ const global char * mask_base = NULL;
697
+ if (mask_void != NULL) {
698
+ const int mask_head_idx = head_idx % mask_ne2;
699
+ const int mask_batch_idx = batch_idx % mask_ne3;
700
+ mask_base = (const global char *) mask_void + mask_offset +
701
+ mask_batch_idx * mask_nb3 + mask_head_idx * mask_nb2 +
702
+ (ulong) q_idx * mask_nb1;
703
+ }
704
+
705
+ ACC_TYPE4 q_priv[DK_VEC];
706
+ const ulong q_row_offset = batch_idx * q_nb3 + head_idx * q_nb2 + (ulong) q_idx * q_nb1;
707
+ const global Q_DATA_TYPE4 * q_ptr = (const global Q_DATA_TYPE4 *) (q_base + q_row_offset);
708
+ #pragma unroll
709
+ for (int i = 0; i < DK_VEC; ++i) {
710
+ q_priv[i] = CONVERT_Q_ACC4(q_ptr[i]);
711
+ }
712
+
713
+ #ifdef FA_HAVE_INT_DOT
714
+ uint q_packed[DK_Q4_BLOCKS * 8];
715
+ float q_d_scale[DK_Q4_BLOCKS];
716
+ int q_sum_arr[DK_Q4_BLOCKS];
717
+ #pragma unroll
718
+ for (int b = 0; b < DK_Q4_BLOCKS; ++b) {
719
+ q4_q_block_info info = quant_q_block_int8_packed_q4(&q_priv[b * 8], &q_packed[b * 8]);
720
+ q_d_scale[b] = info.qd;
721
+ q_sum_arr[b] = info.q_sum;
722
+ }
723
+ #endif
724
+
725
+ const float slope = get_alibi_slope(max_bias, head_idx, n_head_log2, m0, m1);
726
+
727
+ // One-pass online softmax (FA-2): single sweep over the split's K range.
728
+ ACC_TYPE m_i = FA_M_INIT;
729
+ ACC_TYPE l_i = 0.0f;
730
+ ACC_TYPE4 o_acc[DV_VEC];
731
+ #pragma unroll
732
+ for (int i = 0; i < DV_VEC; ++i) o_acc[i] = (ACC_TYPE4)(0.0f);
733
+
734
+ for (int k_idx = kv_start + tid; k_idx < kv_end; k_idx += Q1_WG_SIZE) {
735
+ const global char * k_row = k_base + batch_idx * k_nb3 + head_kv_idx * k_nb2 + k_idx * k_nb1;
736
+ const global char * v_row = v_base + batch_idx * v_nb3 + head_kv_idx * v_nb2 + k_idx * v_nb1;
737
+ ACC_TYPE score = 0.0f;
738
+ #pragma unroll
739
+ for (int b = 0; b < DK_Q4_BLOCKS; ++b) {
740
+ #ifdef FA_HAVE_INT_DOT
741
+ score += dot_q4_0_int(k_row + b * Q4_0_BLOCK_SIZE,
742
+ &q_packed[b * 8], q_d_scale[b], q_sum_arr[b]);
743
+ #else
744
+ score += dot_q4_0_f32(k_row + b * Q4_0_BLOCK_SIZE, &q_priv[b * 8]);
745
+ #endif
746
+ }
747
+ score *= scale;
748
+ if (mask_base != NULL) {
749
+ const global MASK_DATA_TYPE * mask_ptr = (const global MASK_DATA_TYPE *) (mask_base);
750
+ score += slope * (ACC_TYPE) mask_ptr[k_idx];
751
+ }
752
+ if (logit_softcap > 0.0f) {
753
+ score = logit_softcap * tanh(score / logit_softcap);
754
+ }
755
+
756
+ // Online softmax step.
757
+ const ACC_TYPE m_new = max(m_i, score);
758
+ const ACC_TYPE alpha = exp(m_i - m_new);
759
+ const ACC_TYPE p = exp(score - m_new);
760
+
761
+ l_i = alpha * l_i + p;
762
+ #pragma unroll
763
+ for (int i = 0; i < DV_VEC; ++i) o_acc[i] *= alpha;
764
+
765
+ #pragma unroll
766
+ for (int b = 0; b < DV_Q4_BLOCKS; ++b) {
767
+ ACC_TYPE4 v_dequant[8];
768
+ dequant_q4_0_f32(v_row + b * Q4_0_BLOCK_SIZE, v_dequant);
769
+ #pragma unroll
770
+ for (int i = 0; i < 8; ++i) {
771
+ o_acc[b * 8 + i] = mad(p, v_dequant[i], o_acc[b * 8 + i]);
772
+ }
773
+ }
774
+
775
+ m_i = m_new;
776
+ }
777
+
778
+ // Cross-thread reduce: max(m_i) -> m_c, rescale per-thread l_i and o_acc
779
+ // by alpha = exp(m_i_thread - m_c) before sum-reduce.
780
+ __local ACC_TYPE local_m[Q1_WG_SIZE];
781
+ local_m[tid] = m_i;
782
+ barrier(CLK_LOCAL_MEM_FENCE);
783
+ #pragma unroll
784
+ for (int s = Q1_WG_SIZE / 2; s > 0; s >>= 1) {
785
+ if (tid < s) local_m[tid] = max(local_m[tid], local_m[tid + s]);
786
+ barrier(CLK_LOCAL_MEM_FENCE);
787
+ }
788
+ const ACC_TYPE m_c = local_m[0];
789
+
790
+ const ACC_TYPE alpha_final = exp(m_i - m_c);
791
+ l_i *= alpha_final;
792
+ #pragma unroll
793
+ for (int i = 0; i < DV_VEC; ++i) o_acc[i] *= alpha_final;
794
+
795
+ __local ACC_TYPE local_l[Q1_WG_SIZE];
796
+ __local ACC_TYPE4 local_o[Q1_WG_SIZE];
797
+ local_l[tid] = l_i;
798
+ barrier(CLK_LOCAL_MEM_FENCE);
799
+ #pragma unroll
800
+ for (int s = Q1_WG_SIZE / 2; s > 0; s >>= 1) {
801
+ if (tid < s) local_l[tid] += local_l[tid + s];
802
+ barrier(CLK_LOCAL_MEM_FENCE);
803
+ }
804
+ const ACC_TYPE l_c = local_l[0];
805
+
806
+ if (tid == 0) {
807
+ rec[0] = (float) m_c;
808
+ rec[1] = (float) l_c;
809
+ }
810
+ for (int i = 0; i < DV_VEC; ++i) {
811
+ local_o[tid] = o_acc[i];
812
+ barrier(CLK_LOCAL_MEM_FENCE);
813
+ #pragma unroll
814
+ for (int s = Q1_WG_SIZE / 2; s > 0; s >>= 1) {
815
+ if (tid < s) local_o[tid] += local_o[tid + s];
816
+ barrier(CLK_LOCAL_MEM_FENCE);
817
+ }
818
+ if (tid == 0) {
819
+ rec_o[i] = local_o[0];
820
+ }
821
+ }
822
+ }
823
+
824
+ // Prefill: q4_0 K/V, n_q > 1. BLOCK_M × BLOCK_N tiling.
825
+ // K in local as packed nibbles + per-block scale; V dequant -> half in local.
826
+ // Requires DK % QK4_0 == 0 and DV % QK4_0 == 0.
827
+ #define KV_DATA_TYPE4 half4
828
+ #define CONVERT_KV_ACC4(x) convert_float4(x)
829
+
830
+ #define DK_Q4_BLOCKS_PREFILL (DK / QK4_0)
831
+ #define DV_Q4_BLOCKS_PREFILL (DV / QK4_0)
832
+
833
+ // N_SPLIT>1 splits DK/DV across N_SPLIT threads per query row; needs
834
+ // sub_group_shuffle_xor and DK_Q4_BLOCKS_PREFILL % N_SPLIT == 0.
835
+ #ifndef N_SPLIT
836
+ #define N_SPLIT 1
837
+ #endif
838
+
839
+ #if N_SPLIT > 1
840
+ #define SPLIT_DK_VEC (DK_VEC / N_SPLIT)
841
+ #define SPLIT_DV_VEC (DV_VEC / N_SPLIT)
842
+ #define SPLIT_DK_Q4_BLOCKS (DK_Q4_BLOCKS_PREFILL / N_SPLIT)
843
+ #define WG_SIZE (BLOCK_M * N_SPLIT)
844
+ #else
845
+ #define SPLIT_DK_VEC DK_VEC
846
+ #define SPLIT_DV_VEC DV_VEC
847
+ #define SPLIT_DK_Q4_BLOCKS DK_Q4_BLOCKS_PREFILL
848
+ #define WG_SIZE BLOCK_M
849
+ #endif
850
+
851
+ #ifndef MQ_GQA
852
+ #define MQ_GQA 4
853
+ #endif
854
+ #ifndef MQ_NSG_SPLIT
855
+ #define MQ_NSG_SPLIT 4
856
+ #endif
857
+ #define MQ_SPLIT_WG_SIZE_Q4 (Q1_WG_SIZE * MQ_NSG_SPLIT)
858
+
859
+ REQD_SUBGROUP_SIZE_64
860
+ __kernel void flash_attn_f32_q4_0_q1_vec_mq_split(
861
+ const global void * q_void, ulong q_offset,
862
+ const global void * k_void, ulong k_offset,
863
+ const global void * v_void, ulong v_offset,
864
+ const float scale,
865
+ const int n_q,
866
+ const int n_kv,
867
+ const int n_head,
868
+ const ulong q_nb1, const ulong q_nb2, const ulong q_nb3,
869
+ const ulong k_nb1, const ulong k_nb2, const ulong k_nb3,
870
+ const ulong v_nb1, const ulong v_nb2, const ulong v_nb3,
871
+ const float max_bias,
872
+ const float m0,
873
+ const float m1,
874
+ const int n_head_log2,
875
+ const float logit_softcap,
876
+ const int n_head_kv,
877
+ const global void * mask_void,
878
+ const ulong mask_offset,
879
+ const ulong mask_nb1,
880
+ const ulong mask_nb2,
881
+ const ulong mask_nb3,
882
+ const int mask_ne2,
883
+ const int mask_ne3,
884
+ global float * partial_void,
885
+ const int n_splits,
886
+ const int kv_per_split
887
+ ) {
888
+ const int tid = get_local_id(0);
889
+ const int sgid = tid / Q1_WG_SIZE;
890
+ const int tid_sg = tid % Q1_WG_SIZE;
891
+ const int kvhead_batch_idx = get_global_id(1);
892
+ const int split_q_idx = get_global_id(2);
893
+ const int split_idx = split_q_idx % n_splits;
894
+ const int q_idx = split_q_idx / n_splits;
895
+
896
+ const int batch_idx = kvhead_batch_idx / n_head_kv;
897
+ const int head_kv_idx = kvhead_batch_idx % n_head_kv;
898
+
899
+ const int kv_start = split_idx * kv_per_split;
900
+ const int kv_end = min(kv_start + kv_per_split, n_kv);
901
+
902
+ const ulong record_stride = (ulong) FA_PARTIAL_FLOATS;
903
+
904
+ if (kv_start >= kv_end) {
905
+ if (tid == 0) {
906
+ #pragma unroll
907
+ for (int h = 0; h < MQ_GQA; ++h) {
908
+ const int head_idx = head_kv_idx * MQ_GQA + h;
909
+ const ulong rec_idx = ((((ulong) batch_idx * n_head + head_idx) * n_q + q_idx)
910
+ * n_splits + split_idx);
911
+ global float * rec = partial_void + rec_idx * record_stride;
912
+ rec[0] = FA_M_INIT;
913
+ rec[1] = 0.0f;
914
+ }
915
+ }
916
+ return;
917
+ }
918
+
919
+ const global char * q_base = (const global char *) q_void + q_offset;
920
+ const global char * k_base = (const global char *) k_void + k_offset;
921
+ const global char * v_base = (const global char *) v_void + v_offset;
922
+
923
+ __local ACC_TYPE4 q_shared[MQ_GQA * DK_VEC];
924
+ for (int i = tid; i < MQ_GQA * DK_VEC; i += MQ_SPLIT_WG_SIZE_Q4) {
925
+ const int h = i / DK_VEC;
926
+ const int k = i % DK_VEC;
927
+ const int head_idx = head_kv_idx * MQ_GQA + h;
928
+ const ulong q_row_offset = batch_idx * q_nb3 + head_idx * q_nb2 + (ulong) q_idx * q_nb1;
929
+ const global Q_DATA_TYPE4 * q_ptr = (const global Q_DATA_TYPE4 *) (q_base + q_row_offset);
930
+ q_shared[h * DK_VEC + k] = CONVERT_Q_ACC4(q_ptr[k]);
931
+ }
932
+ barrier(CLK_LOCAL_MEM_FENCE);
933
+
934
+ #ifdef FA_HAVE_INT_DOT
935
+ __local uint q_packed_shared[MQ_GQA * DK_Q4_BLOCKS * 8];
936
+ __local float q_d_shared[MQ_GQA * DK_Q4_BLOCKS];
937
+ __local int q_sum_shared[MQ_GQA * DK_Q4_BLOCKS];
938
+ {
939
+ const int active = MQ_GQA * DK_Q4_BLOCKS;
940
+ if (tid < active) {
941
+ const int h = tid / DK_Q4_BLOCKS;
942
+ const int block_id = tid % DK_Q4_BLOCKS;
943
+ ACC_TYPE4 q_block[8];
944
+ #pragma unroll
945
+ for (int i = 0; i < 8; ++i) q_block[i] = q_shared[h * DK_VEC + block_id * 8 + i];
946
+ uint packed[8];
947
+ q4_q_block_info info = quant_q_block_int8_packed_q4(q_block, packed);
948
+ #pragma unroll
949
+ for (int i = 0; i < 8; ++i) q_packed_shared[(h * DK_Q4_BLOCKS + block_id) * 8 + i] = packed[i];
950
+ q_d_shared[h * DK_Q4_BLOCKS + block_id] = info.qd;
951
+ q_sum_shared[h * DK_Q4_BLOCKS + block_id] = info.q_sum;
952
+ }
953
+ }
954
+ barrier(CLK_LOCAL_MEM_FENCE);
955
+ #endif
956
+
957
+ float slope[MQ_GQA];
958
+ #pragma unroll
959
+ for (int h = 0; h < MQ_GQA; ++h) {
960
+ slope[h] = get_alibi_slope(max_bias, head_kv_idx * MQ_GQA + h, n_head_log2, m0, m1);
961
+ }
962
+
963
+ const global char * mask_base[MQ_GQA];
964
+ if (mask_void != NULL) {
965
+ const int mask_batch_idx = batch_idx % mask_ne3;
966
+ const global char * mask_base_b = (const global char *) mask_void + mask_offset +
967
+ mask_batch_idx * mask_nb3 +
968
+ (ulong) q_idx * mask_nb1;
969
+ #pragma unroll
970
+ for (int h = 0; h < MQ_GQA; ++h) {
971
+ const int head_idx = head_kv_idx * MQ_GQA + h;
972
+ const int mask_head_idx = head_idx % mask_ne2;
973
+ mask_base[h] = mask_base_b + mask_head_idx * mask_nb2;
974
+ }
975
+ } else {
976
+ #pragma unroll
977
+ for (int h = 0; h < MQ_GQA; ++h) mask_base[h] = NULL;
978
+ }
979
+
980
+ ACC_TYPE4 o_acc[MQ_GQA][Q1V_DV_PER_THREAD];
981
+ ACC_TYPE m_i[MQ_GQA];
982
+ ACC_TYPE l_i[MQ_GQA];
983
+ #pragma unroll
984
+ for (int h = 0; h < MQ_GQA; ++h) {
985
+ m_i[h] = FA_M_INIT;
986
+ l_i[h] = 0.0f;
987
+ #pragma unroll
988
+ for (int i = 0; i < Q1V_DV_PER_THREAD; ++i) o_acc[h][i] = (ACC_TYPE4)(0.0f);
989
+ }
990
+
991
+ const int kv_len = kv_end - kv_start;
992
+ const int kv_per_sg = (kv_len + MQ_NSG_SPLIT - 1) / MQ_NSG_SPLIT;
993
+ const int kv_lo = kv_start + sgid * kv_per_sg;
994
+ const int kv_hi = min(kv_end, kv_lo + kv_per_sg);
995
+
996
+ for (int k_idx = kv_lo; k_idx < kv_hi; ++k_idx) {
997
+ const global char * k_row = k_base + batch_idx * k_nb3 + head_kv_idx * k_nb2 + k_idx * k_nb1;
998
+ const global char * v_row = v_base + batch_idx * v_nb3 + head_kv_idx * v_nb2 + k_idx * v_nb1;
999
+
1000
+ #ifdef FA_HAVE_INT_DOT
1001
+ ACC_TYPE lane_contrib[MQ_GQA];
1002
+ #pragma unroll
1003
+ for (int h = 0; h < MQ_GQA; ++h) lane_contrib[h] = 0.0f;
1004
+
1005
+ for (int qk = tid_sg; qk < DK_VEC; qk += Q1_WG_SIZE) {
1006
+ const int block_idx = qk / 8;
1007
+ const int lane_in_block = qk % 8;
1008
+ const int g = lane_in_block & 3;
1009
+ const int shift = (lane_in_block < 4) ? 0 : 4;
1010
+ const global char * k_block = k_row + block_idx * Q4_0_BLOCK_SIZE;
1011
+ const float kd = vload_half(0, (const global half *)k_block);
1012
+ const global uchar * k_qs = (const global uchar *)(k_block + 2);
1013
+ const uchar b0 = k_qs[g*4 + 0];
1014
+ const uchar b1 = k_qs[g*4 + 1];
1015
+ const uchar b2 = k_qs[g*4 + 2];
1016
+ const uchar b3 = k_qs[g*4 + 3];
1017
+ const uint k_packed = ((uint)((b0 >> shift) & 0x0F)) |
1018
+ ((uint)((b1 >> shift) & 0x0F)) << 8 |
1019
+ ((uint)((b2 >> shift) & 0x0F)) << 16 |
1020
+ ((uint)((b3 >> shift) & 0x0F)) << 24;
1021
+ #pragma unroll
1022
+ for (int h = 0; h < MQ_GQA; ++h) {
1023
+ const uint q_packed_lane = q_packed_shared[(h * DK_Q4_BLOCKS + block_idx) * 8 + lane_in_block];
1024
+ const int raw_dot = dot_acc_sat_4x8packed_ss_int(q_packed_lane, k_packed, 0);
1025
+ const float qd = q_d_shared[h * DK_Q4_BLOCKS + block_idx];
1026
+ const float block_scale = qd * kd;
1027
+ float contrib = (float) raw_dot * block_scale;
1028
+ if (lane_in_block == 0) {
1029
+ const int q_sum_b = q_sum_shared[h * DK_Q4_BLOCKS + block_idx];
1030
+ contrib -= 8.0f * block_scale * (float) q_sum_b;
1031
+ }
1032
+ lane_contrib[h] += contrib;
1033
+ }
1034
+ }
1035
+
1036
+ ACC_TYPE score[MQ_GQA];
1037
+ #pragma unroll
1038
+ for (int h = 0; h < MQ_GQA; ++h) {
1039
+ ACC_TYPE s = sub_group_reduce_add(lane_contrib[h]) * scale;
1040
+ if (mask_base[h] != NULL) {
1041
+ const global MASK_DATA_TYPE * mask_ptr = (const global MASK_DATA_TYPE *) mask_base[h];
1042
+ s += slope[h] * (ACC_TYPE) mask_ptr[k_idx];
1043
+ }
1044
+ if (logit_softcap > 0.0f) {
1045
+ s = logit_softcap * tanh(s / logit_softcap);
1046
+ }
1047
+ score[h] = s;
1048
+ }
1049
+ #else
1050
+ // fallback float-dequant K dot
1051
+ ACC_TYPE4 dot4[MQ_GQA];
1052
+ #pragma unroll
1053
+ for (int h = 0; h < MQ_GQA; ++h) dot4[h] = (ACC_TYPE4)(0.0f);
1054
+
1055
+ for (int qk = tid_sg; qk < DK_VEC; qk += Q1_WG_SIZE) {
1056
+ const int block_idx = qk / 8;
1057
+ const int lane = qk % 8;
1058
+ const float4 k_v = dequant_q4_0_lane(k_row + block_idx * Q4_0_BLOCK_SIZE, lane);
1059
+ #pragma unroll
1060
+ for (int h = 0; h < MQ_GQA; ++h) {
1061
+ dot4[h] = mad(q_shared[h * DK_VEC + qk], k_v, dot4[h]);
1062
+ }
1063
+ }
1064
+
1065
+ ACC_TYPE score[MQ_GQA];
1066
+ #pragma unroll
1067
+ for (int h = 0; h < MQ_GQA; ++h) {
1068
+ const ACC_TYPE dot_partial = dot4[h].s0 + dot4[h].s1 + dot4[h].s2 + dot4[h].s3;
1069
+ ACC_TYPE s = sub_group_reduce_add(dot_partial) * scale;
1070
+ if (mask_base[h] != NULL) {
1071
+ const global MASK_DATA_TYPE * mask_ptr = (const global MASK_DATA_TYPE *) mask_base[h];
1072
+ s += slope[h] * (ACC_TYPE) mask_ptr[k_idx];
1073
+ }
1074
+ if (logit_softcap > 0.0f) {
1075
+ s = logit_softcap * tanh(s / logit_softcap);
1076
+ }
1077
+ score[h] = s;
1078
+ }
1079
+ #endif
1080
+
1081
+ ACC_TYPE p_h[MQ_GQA];
1082
+ ACC_TYPE sp_h[MQ_GQA];
1083
+ #pragma unroll
1084
+ for (int h = 0; h < MQ_GQA; ++h) {
1085
+ const ACC_TYPE m_new = max(m_i[h], score[h]);
1086
+ sp_h[h] = native_exp(m_i[h] - m_new);
1087
+ p_h[h] = native_exp(score[h] - m_new);
1088
+ l_i[h] = l_i[h] * sp_h[h] + p_h[h];
1089
+ m_i[h] = m_new;
1090
+ }
1091
+
1092
+ int idx = 0;
1093
+ for (int dv = tid_sg; dv < DV_VEC; dv += Q1_WG_SIZE, ++idx) {
1094
+ const int block_idx = dv / 8;
1095
+ const int lane = dv % 8;
1096
+ const float4 v_v = dequant_q4_0_lane(v_row + block_idx * Q4_0_BLOCK_SIZE, lane);
1097
+ #pragma unroll
1098
+ for (int h = 0; h < MQ_GQA; ++h) {
1099
+ o_acc[h][idx] = mad(p_h[h], v_v, o_acc[h][idx] * sp_h[h]);
1100
+ }
1101
+ }
1102
+ }
1103
+
1104
+ // per-h cross-subgroup merge
1105
+ __local ACC_TYPE sg_m[MQ_GQA][MQ_NSG_SPLIT];
1106
+ __local ACC_TYPE sg_l[MQ_GQA][MQ_NSG_SPLIT];
1107
+ __local ACC_TYPE4 sg_o[MQ_NSG_SPLIT][DV_VEC];
1108
+
1109
+ if (tid_sg == 0) {
1110
+ #pragma unroll
1111
+ for (int h = 0; h < MQ_GQA; ++h) {
1112
+ sg_m[h][sgid] = m_i[h];
1113
+ sg_l[h][sgid] = l_i[h];
1114
+ }
1115
+ }
1116
+
1117
+ #pragma unroll
1118
+ for (int h = 0; h < MQ_GQA; ++h) {
1119
+ {
1120
+ int idx = 0;
1121
+ for (int dv_idx = tid_sg; dv_idx < DV_VEC; dv_idx += Q1_WG_SIZE, ++idx) {
1122
+ sg_o[sgid][dv_idx] = o_acc[h][idx];
1123
+ }
1124
+ }
1125
+ barrier(CLK_LOCAL_MEM_FENCE);
1126
+
1127
+ if (sgid == 0) {
1128
+ const int head_idx = head_kv_idx * MQ_GQA + h;
1129
+
1130
+ ACC_TYPE m_c = sg_m[h][0];
1131
+ #pragma unroll
1132
+ for (int s = 1; s < MQ_NSG_SPLIT; ++s) {
1133
+ m_c = max(m_c, sg_m[h][s]);
1134
+ }
1135
+ ACC_TYPE l_c = 0.0f;
1136
+ #pragma unroll
1137
+ for (int s = 0; s < MQ_NSG_SPLIT; ++s) {
1138
+ l_c += sg_l[h][s] * native_exp(sg_m[h][s] - m_c);
1139
+ }
1140
+
1141
+ const ulong rec_idx = ((((ulong) batch_idx * n_head + head_idx) * n_q + q_idx)
1142
+ * n_splits + split_idx);
1143
+ global float * rec = partial_void + rec_idx * record_stride;
1144
+ global float4 * rec_o = (global float4 *) (rec + 2);
1145
+
1146
+ if (tid_sg == 0) {
1147
+ rec[0] = (float) m_c;
1148
+ rec[1] = (float) l_c;
1149
+ }
1150
+ for (int dv_idx = tid_sg; dv_idx < DV_VEC; dv_idx += Q1_WG_SIZE) {
1151
+ ACC_TYPE4 o_merged = (ACC_TYPE4)(0.0f);
1152
+ #pragma unroll
1153
+ for (int s = 0; s < MQ_NSG_SPLIT; ++s) {
1154
+ const ACC_TYPE alpha = native_exp(sg_m[h][s] - m_c);
1155
+ o_merged = mad((ACC_TYPE4)(alpha), sg_o[s][dv_idx], o_merged);
1156
+ }
1157
+ rec_o[dv_idx] = o_merged;
1158
+ }
1159
+ }
1160
+ barrier(CLK_LOCAL_MEM_FENCE);
1161
+ }
1162
+ }
1163
+
1164
+ // flash_attn_f32_q4_0_q1_vec_mq_split_c8 — cluster-parallel variant of the MQ
1165
+ // split, port of flash_attn_f32_f16_q1_vec_mq_split_c8
1166
+ // Requires dp4a + subgroup shuffles
1167
+
1168
+ #if defined(FA_HAVE_INT_DOT) && defined(HAS_SUBGROUP_SHUFFLE)
1169
+
1170
+ #ifndef FA_CL_C
1171
+ #define FA_CL_C 8
1172
+ #endif
1173
+
1174
+ // Lane striping requires DK/DV to divide across the cluster (see f16 c8).
1175
+ #if (DK_VEC % FA_CL_C) == 0 && (DV_VEC % FA_CL_C) == 0
1176
+ #define FA_CL_NCL (Q1_WG_SIZE / FA_CL_C) // clusters (position streams) per subgroup
1177
+ #define FA_CL_DKQ (DK_VEC / FA_CL_C) // K quartets per lane per row
1178
+ #define FA_CL_DVQ (DV_VEC / FA_CL_C) // V quartets (o_acc float4s) per lane per head
1179
+
1180
+ #ifdef FA_C8_NO_SG_PIN
1181
+ #define FA_C8_SG_ATTR_Q4
1182
+ #else
1183
+ #define FA_C8_SG_ATTR_Q4 REQD_SUBGROUP_SIZE_64
1184
+ #endif
1185
+
1186
+ FA_C8_SG_ATTR_Q4
1187
+ __kernel void flash_attn_f32_q4_0_q1_vec_mq_split_c8(
1188
+ const global void * q_void, ulong q_offset,
1189
+ const global void * k_void, ulong k_offset,
1190
+ const global void * v_void, ulong v_offset,
1191
+ const float scale,
1192
+ const int n_q,
1193
+ const int n_kv,
1194
+ const int n_head,
1195
+ const ulong q_nb1, const ulong q_nb2, const ulong q_nb3,
1196
+ const ulong k_nb1, const ulong k_nb2, const ulong k_nb3,
1197
+ const ulong v_nb1, const ulong v_nb2, const ulong v_nb3,
1198
+ const float max_bias,
1199
+ const float m0,
1200
+ const float m1,
1201
+ const int n_head_log2,
1202
+ const float logit_softcap,
1203
+ const int n_head_kv,
1204
+ const global void * mask_void,
1205
+ const ulong mask_offset,
1206
+ const ulong mask_nb1,
1207
+ const ulong mask_nb2,
1208
+ const ulong mask_nb3,
1209
+ const int mask_ne2,
1210
+ const int mask_ne3,
1211
+ global float * partial_void,
1212
+ const int n_splits,
1213
+ const int kv_per_split
1214
+ ) {
1215
+ const int tid = get_local_id(0);
1216
+ const int sgid = tid / Q1_WG_SIZE;
1217
+ const int tid_sg = tid % Q1_WG_SIZE;
1218
+ const int cl = tid_sg / FA_CL_C; // cluster id
1219
+ const int lic = tid_sg % FA_CL_C; // lane in cluster
1220
+ const int kvhead_batch_idx = get_global_id(1);
1221
+ const int split_q_idx = get_global_id(2);
1222
+ const int split_idx = split_q_idx % n_splits;
1223
+ const int q_idx = split_q_idx / n_splits;
1224
+
1225
+ const int batch_idx = kvhead_batch_idx / n_head_kv;
1226
+ const int head_kv_idx = kvhead_batch_idx % n_head_kv;
1227
+
1228
+ const int kv_start = split_idx * kv_per_split;
1229
+ const int kv_end = min(kv_start + kv_per_split, n_kv);
1230
+
1231
+ const ulong record_stride = (ulong) FA_PARTIAL_FLOATS;
1232
+
1233
+ if (kv_start >= kv_end) {
1234
+ if (tid == 0) {
1235
+ #pragma unroll
1236
+ for (int h = 0; h < MQ_GQA; ++h) {
1237
+ const int head_idx = head_kv_idx * MQ_GQA + h;
1238
+ const ulong rec_idx = ((((ulong) batch_idx * n_head + head_idx) * n_q + q_idx)
1239
+ * n_splits + split_idx);
1240
+ global float * rec = partial_void + rec_idx * record_stride;
1241
+ rec[0] = FA_M_INIT;
1242
+ rec[1] = 0.0f;
1243
+ }
1244
+ }
1245
+ return;
1246
+ }
1247
+
1248
+ const global char * q_base = (const global char *) q_void + q_offset;
1249
+ const global char * k_base = (const global char *) k_void + k_offset;
1250
+ const global char * v_base = (const global char *) v_void + v_offset;
1251
+
1252
+ // Stage MQ_GQA Q rows in __local as float4 (source for the quantize pass).
1253
+ __local ACC_TYPE4 q_shared[MQ_GQA * DK_VEC];
1254
+ for (int i = tid; i < MQ_GQA * DK_VEC; i += MQ_SPLIT_WG_SIZE_Q4) {
1255
+ const int h = i / DK_VEC;
1256
+ const int k = i % DK_VEC;
1257
+ const int head_idx = head_kv_idx * MQ_GQA + h;
1258
+ const ulong q_row_offset = batch_idx * q_nb3 + head_idx * q_nb2 + (ulong) q_idx * q_nb1;
1259
+ const global Q_DATA_TYPE4 * q_ptr = (const global Q_DATA_TYPE4 *) (q_base + q_row_offset);
1260
+ q_shared[h * DK_VEC + k] = CONVERT_Q_ACC4(q_ptr[k]);
1261
+ }
1262
+ barrier(CLK_LOCAL_MEM_FENCE);
1263
+
1264
+ // Per-(h, block) int8-packed Q + (qd, q_sum), quantized once per WG.
1265
+ __local uint q_packed_shared[MQ_GQA * DK_Q4_BLOCKS * 8];
1266
+ __local float q_d_shared[MQ_GQA * DK_Q4_BLOCKS];
1267
+ __local int q_sum_shared[MQ_GQA * DK_Q4_BLOCKS];
1268
+ {
1269
+ const int active = MQ_GQA * DK_Q4_BLOCKS;
1270
+ if (tid < active) {
1271
+ const int h = tid / DK_Q4_BLOCKS;
1272
+ const int block_id = tid % DK_Q4_BLOCKS;
1273
+ ACC_TYPE4 q_block[8];
1274
+ #pragma unroll
1275
+ for (int i = 0; i < 8; ++i) q_block[i] = q_shared[h * DK_VEC + block_id * 8 + i];
1276
+ uint packed[8];
1277
+ q4_q_block_info info = quant_q_block_int8_packed_q4(q_block, packed);
1278
+ #pragma unroll
1279
+ for (int i = 0; i < 8; ++i) q_packed_shared[(h * DK_Q4_BLOCKS + block_id) * 8 + i] = packed[i];
1280
+ q_d_shared[h * DK_Q4_BLOCKS + block_id] = info.qd;
1281
+ q_sum_shared[h * DK_Q4_BLOCKS + block_id] = info.q_sum;
1282
+ }
1283
+ }
1284
+ barrier(CLK_LOCAL_MEM_FENCE);
1285
+
1286
+ float slope[MQ_GQA];
1287
+ #pragma unroll
1288
+ for (int h = 0; h < MQ_GQA; ++h) {
1289
+ slope[h] = get_alibi_slope(max_bias, head_kv_idx * MQ_GQA + h, n_head_log2, m0, m1);
1290
+ }
1291
+
1292
+ const global char * mask_base[MQ_GQA];
1293
+ if (mask_void != NULL) {
1294
+ const int mask_batch_idx = batch_idx % mask_ne3;
1295
+ const global char * mask_base_b = (const global char *) mask_void + mask_offset +
1296
+ mask_batch_idx * mask_nb3 +
1297
+ (ulong) q_idx * mask_nb1;
1298
+ #pragma unroll
1299
+ for (int h = 0; h < MQ_GQA; ++h) {
1300
+ const int head_idx = head_kv_idx * MQ_GQA + h;
1301
+ const int mask_head_idx = head_idx % mask_ne2;
1302
+ mask_base[h] = mask_base_b + mask_head_idx * mask_nb2;
1303
+ }
1304
+ } else {
1305
+ #pragma unroll
1306
+ for (int h = 0; h < MQ_GQA; ++h) mask_base[h] = NULL;
1307
+ }
1308
+
1309
+ // Per-CLUSTER online state; o_acc holds this lane's V quartets {lic + FA_CL_C*i}.
1310
+ ACC_TYPE4 o_acc[MQ_GQA][FA_CL_DVQ];
1311
+ ACC_TYPE m_i[MQ_GQA];
1312
+ ACC_TYPE l_i[MQ_GQA];
1313
+ #pragma unroll
1314
+ for (int h = 0; h < MQ_GQA; ++h) {
1315
+ m_i[h] = FA_M_INIT;
1316
+ l_i[h] = 0.0f;
1317
+ #pragma unroll
1318
+ for (int i = 0; i < FA_CL_DVQ; ++i) o_acc[h][i] = (ACC_TYPE4)(0.0f);
1319
+ }
1320
+
1321
+ const int kv_len = kv_end - kv_start;
1322
+ const int kv_per_sg = (kv_len + MQ_NSG_SPLIT - 1) / MQ_NSG_SPLIT;
1323
+ const int kv_lo = kv_start + sgid * kv_per_sg;
1324
+ const int kv_hi = min(kv_end, kv_lo + kv_per_sg);
1325
+
1326
+ // Uniform trip count; tail clamps the row address and drops the score to
1327
+ // FA_M_INIT (p underflows to 0) so shuffles stay convergent.
1328
+ const int n_iter = (kv_hi - kv_lo + FA_CL_NCL - 1) / FA_CL_NCL;
1329
+ const ulong k_row_base = batch_idx * k_nb3 + head_kv_idx * k_nb2;
1330
+ const ulong v_row_base = batch_idx * v_nb3 + head_kv_idx * v_nb2;
1331
+
1332
+ for (int it = 0; it < n_iter; ++it) {
1333
+ const int k_idx = kv_lo + cl + it * FA_CL_NCL;
1334
+ const int valid = k_idx < kv_hi;
1335
+ const int k_safe = valid ? k_idx : (kv_hi - 1);
1336
+
1337
+ const global char * k_row = k_base + k_row_base + (ulong) k_safe * k_nb1;
1338
+ const global char * v_row = v_base + v_row_base + (ulong) k_safe * v_nb1;
1339
+
1340
+ // dp4a K dot over this lane's quartets of the cluster's row.
1341
+ ACC_TYPE lane_contrib[MQ_GQA];
1342
+ #pragma unroll
1343
+ for (int h = 0; h < MQ_GQA; ++h) lane_contrib[h] = 0.0f;
1344
+
1345
+ #pragma unroll
1346
+ for (int i = 0; i < FA_CL_DKQ; ++i) {
1347
+ const int qk = lic + FA_CL_C * i;
1348
+ const int block_idx = qk / 8;
1349
+ const int lane_in_block = qk % 8;
1350
+ const int g = lane_in_block & 3;
1351
+ const int shift = (lane_in_block < 4) ? 0 : 4;
1352
+ const global char * k_block = k_row + block_idx * Q4_0_BLOCK_SIZE;
1353
+ const float kd = vload_half(0, (const global half *)k_block);
1354
+ const global uchar * k_qs = (const global uchar *)(k_block + 2);
1355
+ const uchar b0 = k_qs[g*4 + 0];
1356
+ const uchar b1 = k_qs[g*4 + 1];
1357
+ const uchar b2 = k_qs[g*4 + 2];
1358
+ const uchar b3 = k_qs[g*4 + 3];
1359
+ const uint k_packed = ((uint)((b0 >> shift) & 0x0F)) |
1360
+ ((uint)((b1 >> shift) & 0x0F)) << 8 |
1361
+ ((uint)((b2 >> shift) & 0x0F)) << 16 |
1362
+ ((uint)((b3 >> shift) & 0x0F)) << 24;
1363
+ #pragma unroll
1364
+ for (int h = 0; h < MQ_GQA; ++h) {
1365
+ const uint q_packed_lane = q_packed_shared[(h * DK_Q4_BLOCKS + block_idx) * 8 + lane_in_block];
1366
+ const int raw_dot = dot_acc_sat_4x8packed_ss_int(q_packed_lane, k_packed, 0);
1367
+ const float qd = q_d_shared[h * DK_Q4_BLOCKS + block_idx];
1368
+ const float block_scale = qd * kd;
1369
+ float contrib = (float) raw_dot * block_scale;
1370
+ if (lane_in_block == 0) {
1371
+ const int q_sum_b = q_sum_shared[h * DK_Q4_BLOCKS + block_idx];
1372
+ contrib -= 8.0f * block_scale * (float) q_sum_b;
1373
+ }
1374
+ lane_contrib[h] += contrib;
1375
+ }
1376
+ }
1377
+
1378
+ // Cluster-reduce + score.
1379
+ ACC_TYPE score[MQ_GQA];
1380
+ #pragma unroll
1381
+ for (int h = 0; h < MQ_GQA; ++h) {
1382
+ ACC_TYPE s = lane_contrib[h];
1383
+ #pragma unroll
1384
+ for (int step = 1; step < FA_CL_C; step <<= 1) {
1385
+ s += sub_group_shuffle_xor(s, step);
1386
+ }
1387
+ s *= scale;
1388
+ if (mask_base[h] != NULL) {
1389
+ const global MASK_DATA_TYPE * mask_ptr = (const global MASK_DATA_TYPE *) mask_base[h];
1390
+ s += slope[h] * (ACC_TYPE) mask_ptr[k_safe];
1391
+ }
1392
+ if (logit_softcap > 0.0f) {
1393
+ s = logit_softcap * tanh(s / logit_softcap);
1394
+ }
1395
+ score[h] = valid ? s : FA_M_INIT;
1396
+ }
1397
+
1398
+ // Per-cluster online update (serial chain depth n_iter, not kv_per_sg).
1399
+ ACC_TYPE p_h[MQ_GQA];
1400
+ ACC_TYPE sp_h[MQ_GQA];
1401
+ #pragma unroll
1402
+ for (int h = 0; h < MQ_GQA; ++h) {
1403
+ const ACC_TYPE m_new = max(m_i[h], score[h]);
1404
+ sp_h[h] = native_exp(m_i[h] - m_new);
1405
+ p_h[h] = native_exp(score[h] - m_new);
1406
+ l_i[h] = l_i[h] * sp_h[h] + p_h[h];
1407
+ m_i[h] = m_new;
1408
+ }
1409
+
1410
+ // V accumulate on this lane's quartets (p = 0 on tail -> inert).
1411
+ #pragma unroll
1412
+ for (int i = 0; i < FA_CL_DVQ; ++i) {
1413
+ const int dv = lic + FA_CL_C * i;
1414
+ const float4 v_v = dequant_q4_0_lane(v_row + (dv / 8) * Q4_0_BLOCK_SIZE, dv % 8);
1415
+ #pragma unroll
1416
+ for (int h = 0; h < MQ_GQA; ++h) {
1417
+ o_acc[h][i] = mad(p_h[h], v_v, o_acc[h][i] * sp_h[h]);
1418
+ }
1419
+ }
1420
+ }
1421
+
1422
+ // Merge stage 1: fold cluster partials inside the subgroup via shuffles.
1423
+ // Lanes with equal lic across clusters hold the SAME dv slice.
1424
+ #pragma unroll
1425
+ for (int h = 0; h < MQ_GQA; ++h) {
1426
+ ACC_TYPE m_c = m_i[h];
1427
+ #pragma unroll
1428
+ for (int step = FA_CL_C; step < Q1_WG_SIZE; step <<= 1) {
1429
+ m_c = max(m_c, sub_group_shuffle_xor(m_c, step));
1430
+ }
1431
+ const ACC_TYPE alpha = native_exp(m_i[h] - m_c);
1432
+ ACC_TYPE l_c = l_i[h] * alpha;
1433
+ #pragma unroll
1434
+ for (int step = FA_CL_C; step < Q1_WG_SIZE; step <<= 1) {
1435
+ l_c += sub_group_shuffle_xor(l_c, step);
1436
+ }
1437
+ #pragma unroll
1438
+ for (int i = 0; i < FA_CL_DVQ; ++i) {
1439
+ ACC_TYPE4 o = o_acc[h][i] * alpha;
1440
+ #pragma unroll
1441
+ for (int step = FA_CL_C; step < Q1_WG_SIZE; step <<= 1) {
1442
+ o.s0 += sub_group_shuffle_xor(o.s0, step);
1443
+ o.s1 += sub_group_shuffle_xor(o.s1, step);
1444
+ o.s2 += sub_group_shuffle_xor(o.s2, step);
1445
+ o.s3 += sub_group_shuffle_xor(o.s3, step);
1446
+ }
1447
+ o_acc[h][i] = o;
1448
+ }
1449
+ m_i[h] = m_c;
1450
+ l_i[h] = l_c;
1451
+ }
1452
+
1453
+ // Merge stage 2: baseline cross-subgroup LDS merge (o published by
1454
+ // cluster 0's lanes; layout identical to the baseline sg_o).
1455
+ __local ACC_TYPE sg_m[MQ_GQA][MQ_NSG_SPLIT];
1456
+ __local ACC_TYPE sg_l[MQ_GQA][MQ_NSG_SPLIT];
1457
+ __local ACC_TYPE4 sg_o[MQ_NSG_SPLIT][DV_VEC];
1458
+
1459
+ if (tid_sg == 0) {
1460
+ #pragma unroll
1461
+ for (int h = 0; h < MQ_GQA; ++h) {
1462
+ sg_m[h][sgid] = m_i[h];
1463
+ sg_l[h][sgid] = l_i[h];
1464
+ }
1465
+ }
1466
+
1467
+ #pragma unroll
1468
+ for (int h = 0; h < MQ_GQA; ++h) {
1469
+ if (cl == 0) {
1470
+ #pragma unroll
1471
+ for (int i = 0; i < FA_CL_DVQ; ++i) {
1472
+ sg_o[sgid][lic + FA_CL_C * i] = o_acc[h][i];
1473
+ }
1474
+ }
1475
+ barrier(CLK_LOCAL_MEM_FENCE);
1476
+
1477
+ if (sgid == 0) {
1478
+ const int head_idx = head_kv_idx * MQ_GQA + h;
1479
+
1480
+ ACC_TYPE m_c = sg_m[h][0];
1481
+ #pragma unroll
1482
+ for (int s = 1; s < MQ_NSG_SPLIT; ++s) {
1483
+ m_c = max(m_c, sg_m[h][s]);
1484
+ }
1485
+ ACC_TYPE l_c = 0.0f;
1486
+ #pragma unroll
1487
+ for (int s = 0; s < MQ_NSG_SPLIT; ++s) {
1488
+ l_c += sg_l[h][s] * native_exp(sg_m[h][s] - m_c);
1489
+ }
1490
+
1491
+ const ulong rec_idx = ((((ulong) batch_idx * n_head + head_idx) * n_q + q_idx)
1492
+ * n_splits + split_idx);
1493
+ global float * rec = partial_void + rec_idx * record_stride;
1494
+ global float4 * rec_o = (global float4 *) (rec + 2);
1495
+
1496
+ if (tid_sg == 0) {
1497
+ rec[0] = (float) m_c;
1498
+ rec[1] = (float) l_c;
1499
+ }
1500
+ for (int dv_idx = tid_sg; dv_idx < DV_VEC; dv_idx += Q1_WG_SIZE) {
1501
+ ACC_TYPE4 o_merged = (ACC_TYPE4)(0.0f);
1502
+ #pragma unroll
1503
+ for (int s = 0; s < MQ_NSG_SPLIT; ++s) {
1504
+ const ACC_TYPE alpha = native_exp(sg_m[h][s] - m_c);
1505
+ o_merged = mad((ACC_TYPE4)(alpha), sg_o[s][dv_idx], o_merged);
1506
+ }
1507
+ rec_o[dv_idx] = o_merged;
1508
+ }
1509
+ }
1510
+ barrier(CLK_LOCAL_MEM_FENCE);
1511
+ }
1512
+ }
1513
+
1514
+ #endif // DK_VEC/DV_VEC divisible by FA_CL_C
1515
+ #endif // FA_HAVE_INT_DOT && HAS_SUBGROUP_SHUFFLE (q1_vec_mq_split_c8)
1516
+
1517
+ __kernel void flash_attn_f32_q4_0(
1518
+ const global void * q_void, ulong q_offset,
1519
+ const global void * k_void, ulong k_offset,
1520
+ const global void * v_void, ulong v_offset,
1521
+ global void * o_void, ulong o_offset,
1522
+ const float scale,
1523
+ const int n_q,
1524
+ const int n_kv,
1525
+ const int is_causal,
1526
+ const int n_head,
1527
+ const ulong q_nb1, const ulong q_nb2, const ulong q_nb3,
1528
+ const ulong k_nb1, const ulong k_nb2, const ulong k_nb3,
1529
+ const ulong v_nb1, const ulong v_nb2, const ulong v_nb3,
1530
+ const ulong o_nb1, const ulong o_nb2, const ulong o_nb3,
1531
+ const float max_bias,
1532
+ const float m0,
1533
+ const float m1,
1534
+ const int n_head_log2,
1535
+ const float logit_softcap,
1536
+ const int n_head_kv,
1537
+ const global void* mask_void,
1538
+ const ulong mask_offset,
1539
+ const ulong mask_nb1,
1540
+ const ulong mask_nb2,
1541
+ const ulong mask_nb3,
1542
+ const int mask_ne2,
1543
+ const int mask_ne3,
1544
+ const global void* sinks_void,
1545
+ const ulong sinks_offset,
1546
+ // blk: per-(qblock,kvblock) class from flash_attn_blk_f16
1547
+ // (0=masked, 1=mixed, 2=unmasked). NULL disables the prepass opt.
1548
+ const global void * blk_void
1549
+ ) {
1550
+ const int tid = get_local_id(0);
1551
+ const int block_q_idx = get_group_id(0);
1552
+ const int head_batch_idx = get_global_id(1);
1553
+
1554
+ #if N_SPLIT > 1
1555
+ const int q_lane = tid / N_SPLIT;
1556
+ const int split_idx = tid % N_SPLIT;
1557
+ #else
1558
+ const int q_lane = tid;
1559
+ const int split_idx = 0;
1560
+ #endif
1561
+ const int my_query_row = block_q_idx * BLOCK_M + q_lane;
1562
+ const int query_valid = my_query_row < n_q;
1563
+
1564
+ const int batch_idx = head_batch_idx / n_head;
1565
+ const int head_idx = head_batch_idx % n_head;
1566
+
1567
+ const int gqa_ratio = n_head / n_head_kv;
1568
+ const int head_kv_idx = head_idx / gqa_ratio;
1569
+ const int mask_head_idx = mask_void != NULL ? head_idx % mask_ne2 : 0;
1570
+ const int mask_batch_idx = mask_void != NULL ? batch_idx % mask_ne3 : 0;
1571
+
1572
+ const global char * q_base = (const global char *) q_void + q_offset;
1573
+ const global char * k_base = (const global char *) k_void + k_offset;
1574
+ const global char * v_base = (const global char *) v_void + v_offset;
1575
+ global char * o_base = (global char *) o_void + o_offset;
1576
+
1577
+ const global char * mask_base = NULL;
1578
+ if (mask_void != NULL) {
1579
+ mask_base = (const global char *) mask_void + mask_offset +
1580
+ mask_batch_idx * mask_nb3 + mask_head_idx * mask_nb2;
1581
+ }
1582
+
1583
+ // BLK_PREPASS_BM may differ from this kernel's BLOCK_M; scale q-block idx.
1584
+ #ifndef BLK_PREPASS_BM
1585
+ #define BLK_PREPASS_BM BLOCK_M
1586
+ #endif
1587
+ const global char * blk_base = NULL;
1588
+ int n_kv_blocks = 0;
1589
+ if (blk_void != NULL) {
1590
+ n_kv_blocks = (n_kv + BLOCK_N - 1) / BLOCK_N;
1591
+ const int n_q_blocks_prepass = (n_q + BLK_PREPASS_BM - 1) / BLK_PREPASS_BM;
1592
+ const int prepass_q_block = (block_q_idx * BLOCK_M) / BLK_PREPASS_BM;
1593
+ blk_base = (const global char *) blk_void +
1594
+ (((mask_batch_idx * mask_ne2) + mask_head_idx) * n_q_blocks_prepass + prepass_q_block) * n_kv_blocks;
1595
+ }
1596
+
1597
+ const int dk_off_vec = split_idx * SPLIT_DK_VEC;
1598
+ ACC_TYPE4 q_priv[SPLIT_DK_VEC];
1599
+ if (query_valid) {
1600
+ const ulong q_row_offset = batch_idx * q_nb3 + head_idx * q_nb2 + my_query_row * q_nb1;
1601
+ const global float4 * q_ptr = (const global float4 *) (q_base + q_row_offset);
1602
+ #pragma unroll
1603
+ for (int i = 0; i < SPLIT_DK_VEC; ++i) {
1604
+ q_priv[i] = q_ptr[dk_off_vec + i];
1605
+ }
1606
+ } else {
1607
+ #pragma unroll
1608
+ for (int i = 0; i < SPLIT_DK_VEC; ++i) q_priv[i] = (ACC_TYPE4)(0.0f);
1609
+ }
1610
+
1611
+ #ifdef FA_HAVE_INT_DOT
1612
+ uint q_packed_pf[SPLIT_DK_Q4_BLOCKS * 8];
1613
+ float q_d_pf[SPLIT_DK_Q4_BLOCKS];
1614
+ int q_sum_pf[SPLIT_DK_Q4_BLOCKS];
1615
+ #pragma unroll
1616
+ for (int b = 0; b < SPLIT_DK_Q4_BLOCKS; ++b) {
1617
+ q4_q_block_info info = quant_q_block_int8_packed_q4(&q_priv[b * 8], &q_packed_pf[b * 8]);
1618
+ q_d_pf[b] = info.qd;
1619
+ q_sum_pf[b] = info.q_sum;
1620
+ }
1621
+ #endif
1622
+
1623
+ const int dv_off_vec = split_idx * SPLIT_DV_VEC;
1624
+ ACC_TYPE4 o_acc[SPLIT_DV_VEC];
1625
+ #pragma unroll
1626
+ for (int i = 0; i < SPLIT_DV_VEC; ++i) o_acc[i] = (ACC_TYPE4)(0.0f);
1627
+
1628
+ ACC_TYPE m_i = FA_M_INIT;
1629
+ ACC_TYPE l_i = 0.0f;
1630
+
1631
+ float slope = get_alibi_slope(max_bias, head_idx, n_head_log2, m0, m1);
1632
+
1633
+ #ifdef FA_HAVE_INT_DOT
1634
+ // Accessors so the staging code is layout-agnostic.
1635
+ #ifdef FA_K_LDS_T
1636
+ #define FA_K_PACKED(ROW, IDX) l_k_packed[IDX][ROW]
1637
+ #define FA_K_SCALE(ROW, BLK) l_k_scale[BLK][ROW]
1638
+ #else
1639
+ #define FA_K_PACKED(ROW, IDX) l_k_packed[ROW][IDX]
1640
+ #define FA_K_SCALE(ROW, BLK) l_k_scale[ROW][BLK]
1641
+ #endif
1642
+
1643
+ #ifdef FA_K_LDS_T
1644
+ // K tile transposed: the 4 KV rows the QK loop walks together become adjacent, so each
1645
+ // (block, group) step is ONE 128-bit local read instead of four 32-bit ones. The QK
1646
+ // loop is LDS-read-issue-bound.
1647
+ __local uint l_k_packed[DK_Q4_BLOCKS_PREFILL * 8][BLOCK_N];
1648
+ __local float l_k_scale [DK_Q4_BLOCKS_PREFILL][BLOCK_N];
1649
+ #else
1650
+ __local uint l_k_packed[BLOCK_N][DK_Q4_BLOCKS_PREFILL * 8];
1651
+ __local float l_k_scale [BLOCK_N][DK_Q4_BLOCKS_PREFILL];
1652
+ #endif
1653
+ #else
1654
+ __local half4 l_k[BLOCK_N][DK_VEC];
1655
+ #endif
1656
+
1657
+ __local half4 l_v[BLOCK_N][DV_VEC];
1658
+
1659
+ for (int k_start = 0; k_start < n_kv; k_start += BLOCK_N) {
1660
+ // Skip fully-masked KV tiles (uniform branch across WG).
1661
+ char blk_cur = 1;
1662
+ if (blk_base != NULL) {
1663
+ blk_cur = blk_base[k_start / BLOCK_N];
1664
+ if (blk_cur == 0) continue;
1665
+ }
1666
+
1667
+ {
1668
+ #ifdef FA_HAVE_INT_DOT
1669
+ const int k_blocks_per_row = DK_Q4_BLOCKS_PREFILL;
1670
+ const int n_blocks_total = BLOCK_N * k_blocks_per_row;
1671
+ for (int i = tid; i < n_blocks_total; i += WG_SIZE) {
1672
+ const int row = i / k_blocks_per_row;
1673
+ const int blk = i % k_blocks_per_row;
1674
+ const int k_row_idx = k_start + row;
1675
+ if (k_row_idx < n_kv) {
1676
+ const ulong k_row_off = batch_idx * k_nb3 + head_kv_idx * k_nb2 + k_row_idx * k_nb1;
1677
+ const global char * blk_ptr = k_base + k_row_off + blk * Q4_0_BLOCK_SIZE;
1678
+ const float df = (float) vload_half(0, (const global half *) blk_ptr);
1679
+ const global uchar * qs = (const global uchar *)(blk_ptr + 2);
1680
+ FA_K_SCALE(row, blk) = df;
1681
+ uint k_packed[8];
1682
+ pack_q4_0_nibbles(qs, k_packed);
1683
+ #pragma unroll
1684
+ for (int j = 0; j < 8; ++j) {
1685
+ FA_K_PACKED(row, blk * 8 + j) = k_packed[j];
1686
+ }
1687
+ } else {
1688
+ FA_K_SCALE(row, blk) = 0.0f;
1689
+ #pragma unroll
1690
+ for (int j = 0; j < 8; ++j) FA_K_PACKED(row, blk * 8 + j) = 0u;
1691
+ }
1692
+ }
1693
+ #else
1694
+ // Fallback: dequant q4_0 -> half in local memory.
1695
+ const int k_blocks_per_row = DK_Q4_BLOCKS_PREFILL;
1696
+ const int n_blocks_total = BLOCK_N * k_blocks_per_row;
1697
+ for (int i = tid; i < n_blocks_total; i += WG_SIZE) {
1698
+ const int row = i / k_blocks_per_row;
1699
+ const int blk = i % k_blocks_per_row;
1700
+ const int k_row_idx = k_start + row;
1701
+ if (k_row_idx < n_kv) {
1702
+ const ulong k_row_off = batch_idx * k_nb3 + head_kv_idx * k_nb2 + k_row_idx * k_nb1;
1703
+ const global char * blk_ptr = k_base + k_row_off + blk * Q4_0_BLOCK_SIZE;
1704
+ const float df = (float) vload_half(0, (const global half *) blk_ptr);
1705
+ const global uchar * qs = (const global uchar *)(blk_ptr + 2);
1706
+ #pragma unroll
1707
+ for (int g = 0; g < 4; ++g) {
1708
+ float4 vlo = df * (float4)((float)(int)(qs[g*4 + 0] & 0x0F) - 8.0f,
1709
+ (float)(int)(qs[g*4 + 1] & 0x0F) - 8.0f,
1710
+ (float)(int)(qs[g*4 + 2] & 0x0F) - 8.0f,
1711
+ (float)(int)(qs[g*4 + 3] & 0x0F) - 8.0f);
1712
+ float4 vhi = df * (float4)((float)(int)(qs[g*4 + 0] >> 4) - 8.0f,
1713
+ (float)(int)(qs[g*4 + 1] >> 4) - 8.0f,
1714
+ (float)(int)(qs[g*4 + 2] >> 4) - 8.0f,
1715
+ (float)(int)(qs[g*4 + 3] >> 4) - 8.0f);
1716
+ l_k[row][blk * 8 + g ] = (half4)((half)vlo.s0, (half)vlo.s1, (half)vlo.s2, (half)vlo.s3);
1717
+ l_k[row][blk * 8 + 4 + g] = (half4)((half)vhi.s0, (half)vhi.s1, (half)vhi.s2, (half)vhi.s3);
1718
+ }
1719
+ } else {
1720
+ #pragma unroll
1721
+ for (int j = 0; j < 8; ++j) l_k[row][blk * 8 + j] = (half4)(0.0h);
1722
+ }
1723
+ }
1724
+ #endif
1725
+ }
1726
+ // V tile load — dequant V -> half in local memory.
1727
+ {
1728
+ const int v_blocks_per_row = DV_Q4_BLOCKS_PREFILL;
1729
+ const int n_blocks_total = BLOCK_N * v_blocks_per_row;
1730
+ for (int i = tid; i < n_blocks_total; i += WG_SIZE) {
1731
+ const int row = i / v_blocks_per_row;
1732
+ const int blk = i % v_blocks_per_row;
1733
+ const int v_row_idx = k_start + row;
1734
+ if (v_row_idx < n_kv) {
1735
+ const ulong v_row_off = batch_idx * v_nb3 + head_kv_idx * v_nb2 + v_row_idx * v_nb1;
1736
+ const global char * blk_ptr = v_base + v_row_off + blk * Q4_0_BLOCK_SIZE;
1737
+ const float df = (float) vload_half(0, (const global half *) blk_ptr);
1738
+ const global uchar * qs = (const global uchar *)(blk_ptr + 2);
1739
+ #pragma unroll
1740
+ for (int g = 0; g < 4; ++g) {
1741
+ float4 vlo = df * (float4)((float)(int)(qs[g*4 + 0] & 0x0F) - 8.0f,
1742
+ (float)(int)(qs[g*4 + 1] & 0x0F) - 8.0f,
1743
+ (float)(int)(qs[g*4 + 2] & 0x0F) - 8.0f,
1744
+ (float)(int)(qs[g*4 + 3] & 0x0F) - 8.0f);
1745
+ float4 vhi = df * (float4)((float)(int)(qs[g*4 + 0] >> 4) - 8.0f,
1746
+ (float)(int)(qs[g*4 + 1] >> 4) - 8.0f,
1747
+ (float)(int)(qs[g*4 + 2] >> 4) - 8.0f,
1748
+ (float)(int)(qs[g*4 + 3] >> 4) - 8.0f);
1749
+ l_v[row][blk * 8 + g ] = (half4)((half)vlo.s0, (half)vlo.s1, (half)vlo.s2, (half)vlo.s3);
1750
+ l_v[row][blk * 8 + 4 + g] = (half4)((half)vhi.s0, (half)vhi.s1, (half)vhi.s2, (half)vhi.s3);
1751
+ }
1752
+ } else {
1753
+ #pragma unroll
1754
+ for (int j = 0; j < 8; ++j) l_v[row][blk * 8 + j] = (half4)(0.0h);
1755
+ }
1756
+ }
1757
+ }
1758
+ barrier(CLK_LOCAL_MEM_FENCE);
1759
+
1760
+ // QK dot + online softmax. N_SPLIT>1 reduces per-thread partials via shuffle_xor.
1761
+ #if N_SPLIT > 1
1762
+ {
1763
+ #else
1764
+ if (query_valid) {
1765
+ #endif
1766
+ const int k_blk_base = split_idx * SPLIT_DK_Q4_BLOCKS;
1767
+ for (int j = 0; j < BLOCK_N; j += 4) {
1768
+ const int k_row0 = k_start + j;
1769
+ const int k_row1 = k_start + j + 1;
1770
+ const int k_row2 = k_start + j + 2;
1771
+ const int k_row3 = k_start + j + 3;
1772
+
1773
+ ACC_TYPE s0, s1, s2, s3;
1774
+ #ifdef FA_HAVE_INT_DOT
1775
+ s0 = 0.0f; s1 = 0.0f; s2 = 0.0f; s3 = 0.0f;
1776
+ #pragma unroll
1777
+ for (int b_local = 0; b_local < SPLIT_DK_Q4_BLOCKS; ++b_local) {
1778
+ const int b = k_blk_base + b_local;
1779
+ int sum0 = 0, sum1 = 0, sum2 = 0, sum3 = 0;
1780
+ #ifdef FA_K_LDS_T
1781
+ // 4 KV rows are adjacent in the transposed tile: one 128-bit local
1782
+ // read per (block, group) instead of four 32-bit ones.
1783
+ #pragma unroll
1784
+ for (int g = 0; g < 8; ++g) {
1785
+ const uint qp = q_packed_pf[b_local * 8 + g];
1786
+ const uint4 kq4 = vload4(0, &l_k_packed[b * 8 + g][j]);
1787
+ sum0 = dot_acc_sat_4x8packed_ss_int(qp, kq4.s0, sum0);
1788
+ sum1 = dot_acc_sat_4x8packed_ss_int(qp, kq4.s1, sum1);
1789
+ sum2 = dot_acc_sat_4x8packed_ss_int(qp, kq4.s2, sum2);
1790
+ sum3 = dot_acc_sat_4x8packed_ss_int(qp, kq4.s3, sum3);
1791
+ }
1792
+ #else
1793
+ #pragma unroll
1794
+ for (int g = 0; g < 8; ++g) {
1795
+ const uint qp = q_packed_pf[b_local * 8 + g];
1796
+ sum0 = dot_acc_sat_4x8packed_ss_int(qp, l_k_packed[j ][b * 8 + g], sum0);
1797
+ sum1 = dot_acc_sat_4x8packed_ss_int(qp, l_k_packed[j+1][b * 8 + g], sum1);
1798
+ sum2 = dot_acc_sat_4x8packed_ss_int(qp, l_k_packed[j+2][b * 8 + g], sum2);
1799
+ sum3 = dot_acc_sat_4x8packed_ss_int(qp, l_k_packed[j+3][b * 8 + g], sum3);
1800
+ }
1801
+ #endif
1802
+ const float qd = q_d_pf[b_local];
1803
+ const int q_sum = q_sum_pf[b_local];
1804
+ #ifdef FA_K_LDS_T
1805
+ const float4 ks4 = vload4(0, &l_k_scale[b][j]);
1806
+ s0 += (float)(sum0 - 8 * q_sum) * qd * ks4.s0;
1807
+ s1 += (float)(sum1 - 8 * q_sum) * qd * ks4.s1;
1808
+ s2 += (float)(sum2 - 8 * q_sum) * qd * ks4.s2;
1809
+ s3 += (float)(sum3 - 8 * q_sum) * qd * ks4.s3;
1810
+ #else
1811
+ s0 += (float)(sum0 - 8 * q_sum) * qd * l_k_scale[j ][b];
1812
+ s1 += (float)(sum1 - 8 * q_sum) * qd * l_k_scale[j+1][b];
1813
+ s2 += (float)(sum2 - 8 * q_sum) * qd * l_k_scale[j+2][b];
1814
+ s3 += (float)(sum3 - 8 * q_sum) * qd * l_k_scale[j+3][b];
1815
+ #endif
1816
+ }
1817
+ #else
1818
+ ACC_TYPE4 dot_acc0 = (ACC_TYPE4)(0.0f);
1819
+ ACC_TYPE4 dot_acc1 = (ACC_TYPE4)(0.0f);
1820
+ ACC_TYPE4 dot_acc2 = (ACC_TYPE4)(0.0f);
1821
+ ACC_TYPE4 dot_acc3 = (ACC_TYPE4)(0.0f);
1822
+ #pragma unroll
1823
+ for (int k = 0; k < SPLIT_DK_VEC; ++k) {
1824
+ const ACC_TYPE4 qk = q_priv[k];
1825
+ const int k_abs = dk_off_vec + k;
1826
+ dot_acc0 = mad(qk, CONVERT_KV_ACC4(l_k[j ][k_abs]), dot_acc0);
1827
+ dot_acc1 = mad(qk, CONVERT_KV_ACC4(l_k[j+1][k_abs]), dot_acc1);
1828
+ dot_acc2 = mad(qk, CONVERT_KV_ACC4(l_k[j+2][k_abs]), dot_acc2);
1829
+ dot_acc3 = mad(qk, CONVERT_KV_ACC4(l_k[j+3][k_abs]), dot_acc3);
1830
+ }
1831
+ s0 = dot_acc0.s0 + dot_acc0.s1 + dot_acc0.s2 + dot_acc0.s3;
1832
+ s1 = dot_acc1.s0 + dot_acc1.s1 + dot_acc1.s2 + dot_acc1.s3;
1833
+ s2 = dot_acc2.s0 + dot_acc2.s1 + dot_acc2.s2 + dot_acc2.s3;
1834
+ s3 = dot_acc3.s0 + dot_acc3.s1 + dot_acc3.s2 + dot_acc3.s3;
1835
+ #endif
1836
+
1837
+ #if N_SPLIT > 1
1838
+ // Power-of-2 N_SPLIT: shuffle_xor butterfly. N_SPLIT=3 (DK=96):
1839
+ // explicit 3-lane shuffle.
1840
+ #if (N_SPLIT & (N_SPLIT - 1)) == 0
1841
+ #pragma unroll
1842
+ for (int step = 1; step < N_SPLIT; step <<= 1) {
1843
+ s0 += sub_group_shuffle_xor(s0, step);
1844
+ s1 += sub_group_shuffle_xor(s1, step);
1845
+ s2 += sub_group_shuffle_xor(s2, step);
1846
+ s3 += sub_group_shuffle_xor(s3, step);
1847
+ }
1848
+ #else
1849
+ const uint tri_base = (get_sub_group_local_id() / N_SPLIT) * N_SPLIT;
1850
+ s0 = sub_group_shuffle(s0, tri_base + 0) + sub_group_shuffle(s0, tri_base + 1) + sub_group_shuffle(s0, tri_base + 2);
1851
+ s1 = sub_group_shuffle(s1, tri_base + 0) + sub_group_shuffle(s1, tri_base + 1) + sub_group_shuffle(s1, tri_base + 2);
1852
+ s2 = sub_group_shuffle(s2, tri_base + 0) + sub_group_shuffle(s2, tri_base + 1) + sub_group_shuffle(s2, tri_base + 2);
1853
+ s3 = sub_group_shuffle(s3, tri_base + 0) + sub_group_shuffle(s3, tri_base + 1) + sub_group_shuffle(s3, tri_base + 2);
1854
+ #endif
1855
+ if (!query_valid) { s0 = FA_M_INIT; s1 = FA_M_INIT; s2 = FA_M_INIT; s3 = FA_M_INIT; }
1856
+ #endif
1857
+ s0 *= scale; s1 *= scale; s2 *= scale; s3 *= scale;
1858
+
1859
+ if (is_causal) {
1860
+ const int causal_limit = n_kv - n_q + my_query_row;
1861
+ if (k_row0 > causal_limit) s0 = FA_M_INIT;
1862
+ if (k_row1 > causal_limit) s1 = FA_M_INIT;
1863
+ if (k_row2 > causal_limit) s2 = FA_M_INIT;
1864
+ if (k_row3 > causal_limit) s3 = FA_M_INIT;
1865
+ }
1866
+ if (k_row0 >= n_kv) s0 = FA_M_INIT;
1867
+ if (k_row1 >= n_kv) s1 = FA_M_INIT;
1868
+ if (k_row2 >= n_kv) s2 = FA_M_INIT;
1869
+ if (k_row3 >= n_kv) s3 = FA_M_INIT;
1870
+
1871
+ if (query_valid && mask_base != NULL && blk_cur != 2) {
1872
+ const global MASK_DATA_TYPE * mask_ptr =
1873
+ (const global MASK_DATA_TYPE *) (mask_base + my_query_row * mask_nb1);
1874
+ if (k_row0 < n_kv) s0 += slope * (ACC_TYPE) mask_ptr[k_row0];
1875
+ if (k_row1 < n_kv) s1 += slope * (ACC_TYPE) mask_ptr[k_row1];
1876
+ if (k_row2 < n_kv) s2 += slope * (ACC_TYPE) mask_ptr[k_row2];
1877
+ if (k_row3 < n_kv) s3 += slope * (ACC_TYPE) mask_ptr[k_row3];
1878
+ }
1879
+ if (logit_softcap > 0.0f) {
1880
+ s0 = logit_softcap * tanh(s0 / logit_softcap);
1881
+ s1 = logit_softcap * tanh(s1 / logit_softcap);
1882
+ s2 = logit_softcap * tanh(s2 / logit_softcap);
1883
+ s3 = logit_softcap * tanh(s3 / logit_softcap);
1884
+ }
1885
+
1886
+ const ACC_TYPE m_new = max(m_i, max(max(s0, s1), max(s2, s3)));
1887
+ // Whole tile masked (m_new == FA_M_INIT): force the exp() args
1888
+ // far negative so the tile contributes 0, not exp(0)=1.
1889
+ const ACC_TYPE m_exp = (m_new == FA_M_INIT) ? 0.0f : m_new;
1890
+ const ACC_TYPE scale_prev = native_exp(m_i - m_exp);
1891
+ const ACC_TYPE p0 = native_exp(s0 - m_exp);
1892
+ const ACC_TYPE p1 = native_exp(s1 - m_exp);
1893
+ const ACC_TYPE p2 = native_exp(s2 - m_exp);
1894
+ const ACC_TYPE p3 = native_exp(s3 - m_exp);
1895
+
1896
+ #pragma unroll
1897
+ for (int i = 0; i < SPLIT_DV_VEC; ++i) {
1898
+ const int i_abs = dv_off_vec + i;
1899
+ o_acc[i] = mad(p3, CONVERT_KV_ACC4(l_v[j+3][i_abs]),
1900
+ mad(p2, CONVERT_KV_ACC4(l_v[j+2][i_abs]),
1901
+ mad(p1, CONVERT_KV_ACC4(l_v[j+1][i_abs]),
1902
+ mad(p0, CONVERT_KV_ACC4(l_v[j ][i_abs]),
1903
+ o_acc[i] * scale_prev))));
1904
+ }
1905
+ l_i = l_i * scale_prev + p0 + p1 + p2 + p3;
1906
+ m_i = m_new;
1907
+ }
1908
+ }
1909
+ barrier(CLK_LOCAL_MEM_FENCE);
1910
+ }
1911
+
1912
+ // Write output.
1913
+ if (query_valid) {
1914
+ if (sinks_void != NULL) {
1915
+ const global ACC_TYPE * sinks_ptr =
1916
+ (const global ACC_TYPE *) ((const global char *) sinks_void + sinks_offset);
1917
+ const ACC_TYPE m_sink = sinks_ptr[head_idx];
1918
+ const ACC_TYPE m_final = max(m_i, m_sink);
1919
+ const ACC_TYPE scale_o = exp(m_i - m_final);
1920
+ #pragma unroll
1921
+ for (int i = 0; i < SPLIT_DV_VEC; ++i) o_acc[i] *= scale_o;
1922
+ l_i = l_i * scale_o + exp(m_sink - m_final);
1923
+ m_i = m_final;
1924
+ }
1925
+ const ACC_TYPE l_inv = (l_i > 0.0f) ? (1.0f / l_i) : 0.0f;
1926
+ const ulong o_row_offset = batch_idx * o_nb3 + my_query_row * o_nb2 + head_idx * o_nb1;
1927
+ global float4 * o_row = (global float4 *) (o_base + o_row_offset);
1928
+ if (l_inv > 0.0f) {
1929
+ #pragma unroll
1930
+ for (int i = 0; i < SPLIT_DV_VEC; ++i) o_row[dv_off_vec + i] = o_acc[i] * l_inv;
1931
+ } else {
1932
+ #pragma unroll
1933
+ for (int i = 0; i < SPLIT_DV_VEC; ++i) o_row[dv_off_vec + i] = (float4)(0.0f);
1934
+ }
1935
+ }
1936
+ }
1937
+
1938
+ // FD Pass 2: merge split partials. Identical across q4_0/q8_0/f16; each FA
1939
+ // source owns a copy since kernels compile per-source-program.
1940
+ __kernel void flash_attn_f32_merge(
1941
+ const global float * partial_void,
1942
+ global void * o_void,
1943
+ const ulong o_offset,
1944
+ const int n_head,
1945
+ const int n_splits,
1946
+ const ulong o_nb1, const ulong o_nb2, const ulong o_nb3,
1947
+ const global void * sinks_void,
1948
+ const ulong sinks_offset,
1949
+ const int n_q
1950
+ ) {
1951
+ const int lane = get_local_id(0);
1952
+ const int head_batch_idx = get_global_id(1);
1953
+ const int q_idx = get_global_id(2);
1954
+ const int batch_idx = head_batch_idx / n_head;
1955
+ const int head_idx = head_batch_idx % n_head;
1956
+
1957
+ const ulong record_stride = (ulong) FA_PARTIAL_FLOATS;
1958
+ const ulong record_idx_0 = (((ulong) batch_idx * n_head + head_idx) * n_q + q_idx) * n_splits;
1959
+ const global float * rec0 = partial_void + record_idx_0 * record_stride;
1960
+
1961
+ __local ACC_TYPE m_final_shared;
1962
+ __local ACC_TYPE l_final_shared;
1963
+ if (lane == 0) {
1964
+ ACC_TYPE m = FA_M_INIT;
1965
+ for (int c = 0; c < n_splits; ++c) {
1966
+ const ACC_TYPE m_c = rec0[c * record_stride + 0];
1967
+ m = max(m, m_c);
1968
+ }
1969
+ ACC_TYPE m_sink = 0.0f;
1970
+ bool has_sink = false;
1971
+ if (sinks_void != NULL) {
1972
+ const global ACC_TYPE * sinks_ptr =
1973
+ (const global ACC_TYPE *) ((const global char *) sinks_void + sinks_offset);
1974
+ m_sink = sinks_ptr[head_idx];
1975
+ has_sink = true;
1976
+ m = max(m, m_sink);
1977
+ }
1978
+ ACC_TYPE l = 0.0f;
1979
+ for (int c = 0; c < n_splits; ++c) {
1980
+ const ACC_TYPE m_c = rec0[c * record_stride + 0];
1981
+ const ACC_TYPE l_c = rec0[c * record_stride + 1];
1982
+ if (m_c > FA_M_INIT) {
1983
+ l += l_c * exp(m_c - m);
1984
+ }
1985
+ }
1986
+ if (has_sink) {
1987
+ l += exp(m_sink - m);
1988
+ }
1989
+ m_final_shared = m;
1990
+ l_final_shared = l;
1991
+ }
1992
+ barrier(CLK_LOCAL_MEM_FENCE);
1993
+ const ACC_TYPE m_final = m_final_shared;
1994
+ const ACC_TYPE l_final = l_final_shared;
1995
+ const ACC_TYPE l_inv = (l_final > 0.0f) ? (1.0f / l_final) : 0.0f;
1996
+
1997
+ ACC_TYPE4 o = (ACC_TYPE4)(0.0f);
1998
+ for (int c = 0; c < n_splits; ++c) {
1999
+ const global float * rec_c = rec0 + c * record_stride;
2000
+ const ACC_TYPE m_c = rec_c[0];
2001
+ if (m_c <= FA_M_INIT) continue;
2002
+ const global float4 * rec_oc = (const global float4 *) (rec_c + 2);
2003
+ const ACC_TYPE scale_c = exp(m_c - m_final);
2004
+ o = mad((ACC_TYPE4)(scale_c), rec_oc[lane], o);
2005
+ }
2006
+ o = o * l_inv;
2007
+
2008
+ const ulong o_row_offset = (ulong) batch_idx * o_nb3 + (ulong) q_idx * o_nb2 + (ulong) head_idx * o_nb1;
2009
+ global O_DATA_TYPE4 * o_row = (global O_DATA_TYPE4 *) ((global char *) o_void + o_offset + o_row_offset);
2010
+ o_row[lane] = CONVERT_O_DATA4(o);
2011
+ }
ggml/src/ggml-opencl/kernels/flash_attn_f32_q8_0.cl ADDED
@@ -0,0 +1,1840 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+ #ifdef cl_khr_integer_dot_product
3
+ #pragma OPENCL EXTENSION cl_khr_integer_dot_product : enable
4
+ #define FA_HAVE_INT_DOT 1
5
+ #endif
6
+
7
+ #ifdef cl_khr_subgroup_shuffle
8
+ #pragma OPENCL EXTENSION cl_khr_subgroup_shuffle : enable
9
+ #define HAS_SUBGROUP_SHUFFLE 1
10
+ #elif defined(cl_qcom_subgroup_shuffle)
11
+ #pragma OPENCL EXTENSION cl_qcom_subgroup_shuffle : enable
12
+ #define HAS_SUBGROUP_SHUFFLE 1
13
+ // Adreno compilers that expose only cl_qcom_subgroup_shuffle do not declare the KHR
14
+ // name, so calling it is an implicit declaration and the program fails to build.
15
+ // Route it to the qcom builtin.
16
+ #define sub_group_shuffle_xor(val, mask) qcom_sub_group_shuffle_xor((val), (mask), CLK_SUB_GROUP_SHUFFLE_WIDTH_WAVE_SIZE_QCOM, 0.0f)
17
+ #endif
18
+
19
+ // Flash attention: Q=f32, K=q8_0, V=q8_0.
20
+
21
+ #define ACC_TYPE float
22
+ #define ACC_TYPE4 float4
23
+ #define Q_DATA_TYPE4 float4
24
+ #define O_DATA_TYPE4 float4
25
+ #define MASK_DATA_TYPE half
26
+ #define CONVERT_Q_ACC4(x) (x)
27
+ #define CONVERT_O_DATA4(x) (x)
28
+
29
+ #define DK_VEC (DK/4)
30
+ #define DV_VEC (DV/4)
31
+
32
+ #ifndef FA_SG
33
+ #define FA_SG 64
34
+ #endif
35
+ #define Q1_WG_SIZE FA_SG
36
+
37
+ // The kernels are built with -cl-finite-math-only. On some older Adreno GPUs,
38
+ // infinite operand can cause undefined behavior and miscompilation for exp.
39
+ // Therefore, a large negative value is used instead.
40
+ #define FA_M_INIT (-3.0e38f)
41
+
42
+ // q8_0 block: 2B scale (half) + 32B int8 quants.
43
+ #define QK8_0 32
44
+ #define Q8_0_BLOCK_SIZE 34
45
+
46
+ #define DK_Q8_BLOCKS (DK / QK8_0)
47
+ #define DV_Q8_BLOCKS (DV / QK8_0)
48
+
49
+ inline float dot_q8_0_f32(const global char * block_ptr, ACC_TYPE4 * q_slice) {
50
+ float d = vload_half(0, (const global half *)block_ptr);
51
+ const global char * qs = block_ptr + 2;
52
+
53
+ float sum = 0.0f;
54
+ #pragma unroll
55
+ for (int i = 0; i < 8; i++) {
56
+ float4 qv = (float4)((float)qs[i*4], (float)qs[i*4+1], (float)qs[i*4+2], (float)qs[i*4+3]);
57
+ sum += dot(q_slice[i], qv);
58
+ }
59
+ return sum * d;
60
+ }
61
+
62
+ #ifdef FA_HAVE_INT_DOT
63
+ inline uint pack_i8x4(char a, char b, char c, char d) {
64
+ return ((uint)(uchar)a) |
65
+ ((uint)(uchar)b) << 8 |
66
+ ((uint)(uchar)c) << 16 |
67
+ ((uint)(uchar)d) << 24;
68
+ }
69
+
70
+ inline float quant_q_block_int8_packed(const ACC_TYPE4 * q_block,
71
+ uint * out_packed) {
72
+ float amax = 0.0f;
73
+ #pragma unroll
74
+ for (int i = 0; i < 8; ++i) {
75
+ float4 av = fabs(q_block[i]);
76
+ amax = fmax(amax, fmax(fmax(av.s0, av.s1), fmax(av.s2, av.s3)));
77
+ }
78
+ float qd = amax / 127.0f;
79
+ float qid = (amax > 0.0f) ? 127.0f / amax : 0.0f;
80
+
81
+ #pragma unroll
82
+ for (int i = 0; i < 8; ++i) {
83
+ float4 v = q_block[i] * qid;
84
+ char a = (char)((int)round(v.s0));
85
+ char b = (char)((int)round(v.s1));
86
+ char c = (char)((int)round(v.s2));
87
+ char d = (char)((int)round(v.s3));
88
+ out_packed[i] = pack_i8x4(a, b, c, d);
89
+ }
90
+ return qd;
91
+ }
92
+
93
+ inline float dot_q8_0_int(const global char * k_block_ptr,
94
+ const uint * q_packed,
95
+ float q_d) {
96
+ float kd = vload_half(0, (const global half *)k_block_ptr);
97
+ const global uchar * k_qs = (const global uchar *)(k_block_ptr + 2);
98
+
99
+ // k_qs is 2-byte aligned; pack chars per iteration rather than cast to uint*.
100
+ int sum = 0;
101
+ #pragma unroll
102
+ for (int i = 0; i < 8; ++i) {
103
+ uint k_packed =
104
+ (uint)k_qs[i*4 + 0] |
105
+ ((uint)k_qs[i*4 + 1]) << 8 |
106
+ ((uint)k_qs[i*4 + 2]) << 16 |
107
+ ((uint)k_qs[i*4 + 3]) << 24;
108
+ sum = dot_acc_sat_4x8packed_ss_int(q_packed[i], k_packed, sum);
109
+ }
110
+ return (float)sum * q_d * kd;
111
+ }
112
+ #endif // FA_HAVE_INT_DOT
113
+
114
+ inline void dequant_q8_0_f32(const global char * block_ptr, ACC_TYPE4 * out) {
115
+ float d = vload_half(0, (const global half *)block_ptr);
116
+ const global char * qs = block_ptr + 2;
117
+
118
+ #pragma unroll
119
+ for (int i = 0; i < 8; i++) {
120
+ out[i] = d * (float4)((float)qs[i*4], (float)qs[i*4+1], (float)qs[i*4+2], (float)qs[i*4+3]);
121
+ }
122
+ }
123
+
124
+ // max_bias<=0 returns 1.0 so score += 1.0 * mask[k] stays a no-op multiplier.
125
+ inline float get_alibi_slope(float max_bias, int head_idx, int n_head_log2, float m0, float m1) {
126
+ if (max_bias <= 0.0f) return 1.0f;
127
+ float base = (head_idx < n_head_log2) ? m0 : m1;
128
+ int exph = (head_idx < n_head_log2) ? (head_idx + 1) : (2*(head_idx - n_head_log2) + 1);
129
+ return pow(base, (float)exph);
130
+ }
131
+
132
+ // q1 decode: one query row per WG, threads sweep KV positions.
133
+ __kernel void flash_attn_f32_q8_0_q1(
134
+ const global void * q_void, ulong q_offset,
135
+ const global void * k_void, ulong k_offset,
136
+ const global void * v_void, ulong v_offset,
137
+ global void * o_void, ulong o_offset,
138
+ const float scale,
139
+ const int n_q,
140
+ const int n_kv,
141
+ const int is_causal,
142
+ const int n_head,
143
+ const ulong q_nb1, const ulong q_nb2, const ulong q_nb3,
144
+ const ulong k_nb1, const ulong k_nb2, const ulong k_nb3,
145
+ const ulong v_nb1, const ulong v_nb2, const ulong v_nb3,
146
+ const ulong o_nb1, const ulong o_nb2, const ulong o_nb3,
147
+ const float max_bias,
148
+ const float m0,
149
+ const float m1,
150
+ const int n_head_log2,
151
+ const float logit_softcap,
152
+ const int n_head_kv,
153
+ const global void* mask_void,
154
+ const ulong mask_offset,
155
+ const ulong mask_nb1,
156
+ const ulong mask_nb2,
157
+ const ulong mask_nb3,
158
+ const int mask_ne2,
159
+ const int mask_ne3,
160
+ const global void* sinks_void,
161
+ const ulong sinks_offset
162
+ ) {
163
+ const int tid = get_local_id(0);
164
+ const int head_batch_idx = get_global_id(1);
165
+
166
+ const int batch_idx = head_batch_idx / n_head;
167
+ const int head_idx = head_batch_idx % n_head;
168
+
169
+ const int gqa_ratio = n_head / n_head_kv;
170
+ const int head_kv_idx = head_idx / gqa_ratio;
171
+
172
+ const global char* q_base = (const global char*)q_void + q_offset;
173
+ const global char* k_base = (const global char*)k_void + k_offset;
174
+ const global char* v_base = (const global char*)v_void + v_offset;
175
+ global char* o_base = (global char*)o_void + o_offset;
176
+
177
+ const global char* mask_base = NULL;
178
+ if (mask_void != NULL) {
179
+ const int mask_head_idx = head_idx % mask_ne2;
180
+ const int mask_batch_idx = batch_idx % mask_ne3;
181
+ mask_base = (const global char*)mask_void + mask_offset + mask_batch_idx * mask_nb3 + mask_head_idx * mask_nb2;
182
+ }
183
+
184
+ ACC_TYPE4 q_priv[DK_VEC];
185
+ const ulong q_row_offset = batch_idx * q_nb3 + head_idx * q_nb2;
186
+ const global Q_DATA_TYPE4* q_ptr = (const global Q_DATA_TYPE4*)(q_base + q_row_offset);
187
+ #pragma unroll
188
+ for (int i = 0; i < DK_VEC; ++i) {
189
+ q_priv[i] = CONVERT_Q_ACC4(q_ptr[i]);
190
+ }
191
+
192
+ #ifdef FA_HAVE_INT_DOT
193
+ // Quantise Q once per thread; q_priv stays as fp for the V accumulate.
194
+ uint q_packed[DK_Q8_BLOCKS * 8];
195
+ float q_d_scale[DK_Q8_BLOCKS];
196
+ #pragma unroll
197
+ for (int b = 0; b < DK_Q8_BLOCKS; ++b) {
198
+ q_d_scale[b] = quant_q_block_int8_packed(&q_priv[b * 8], &q_packed[b * 8]);
199
+ }
200
+ #endif
201
+
202
+ float slope = get_alibi_slope(max_bias, head_idx, n_head_log2, m0, m1);
203
+
204
+ const global ACC_TYPE* sinks_ptr = NULL;
205
+ if (sinks_void != NULL) {
206
+ sinks_ptr = (const global ACC_TYPE*)((const global char*)sinks_void + sinks_offset);
207
+ }
208
+
209
+ // One-pass online softmax: per-thread maintains running (m_i, l_i, o_acc),
210
+ // updating each as new K positions are processed. Eliminates the second
211
+ // K read of the original two-pass implementation. After the loop, threads
212
+ // are merged via the standard FA-2 cross-thread reduction (rescale each
213
+ // thread's l_i and o_acc by alpha=exp(m_i_thread - m_final), then sum).
214
+ ACC_TYPE m_i = (sinks_ptr != NULL) ? sinks_ptr[head_idx] : FA_M_INIT;
215
+ ACC_TYPE l_i = 0.0f;
216
+ ACC_TYPE4 o_acc[DV_VEC];
217
+ #pragma unroll
218
+ for (int i = 0; i < DV_VEC; ++i) o_acc[i] = (ACC_TYPE4)(0.0f);
219
+
220
+ for (int k_idx = tid; k_idx < n_kv; k_idx += Q1_WG_SIZE) {
221
+ const global char* k_row = k_base + batch_idx * k_nb3 + head_kv_idx * k_nb2 + k_idx * k_nb1;
222
+ const global char* v_row = v_base + batch_idx * v_nb3 + head_kv_idx * v_nb2 + k_idx * v_nb1;
223
+
224
+ ACC_TYPE score = 0.0f;
225
+ #pragma unroll
226
+ for (int b = 0; b < DK_Q8_BLOCKS; b++) {
227
+ #ifdef FA_HAVE_INT_DOT
228
+ score += dot_q8_0_int(k_row + b * Q8_0_BLOCK_SIZE,
229
+ &q_packed[b * 8], q_d_scale[b]);
230
+ #else
231
+ score += dot_q8_0_f32(k_row + b * Q8_0_BLOCK_SIZE, &q_priv[b * 8]);
232
+ #endif
233
+ }
234
+ score *= scale;
235
+
236
+ if (mask_base != NULL) {
237
+ const global MASK_DATA_TYPE* mask_ptr = (const global MASK_DATA_TYPE*)(mask_base);
238
+ score += slope * (ACC_TYPE)mask_ptr[k_idx];
239
+ }
240
+ if (logit_softcap > 0.0f) {
241
+ score = logit_softcap * tanh(score / logit_softcap);
242
+ }
243
+
244
+ // Online softmax step.
245
+ const ACC_TYPE m_new = max(m_i, score);
246
+ const ACC_TYPE alpha = exp(m_i - m_new);
247
+ const ACC_TYPE p = exp(score - m_new);
248
+
249
+ l_i = alpha * l_i + p;
250
+ #pragma unroll
251
+ for (int i = 0; i < DV_VEC; ++i) o_acc[i] *= alpha;
252
+
253
+ #pragma unroll
254
+ for (int b = 0; b < DV_Q8_BLOCKS; b++) {
255
+ ACC_TYPE4 v_dequant[8];
256
+ dequant_q8_0_f32(v_row + b * Q8_0_BLOCK_SIZE, v_dequant);
257
+ #pragma unroll
258
+ for (int i = 0; i < 8; i++) {
259
+ o_acc[b * 8 + i] = mad(p, v_dequant[i], o_acc[b * 8 + i]);
260
+ }
261
+ }
262
+
263
+ m_i = m_new;
264
+ }
265
+
266
+ // Cross-thread reduce: max(m_i) -> m_final, then rescale per-thread l_i
267
+ // and o_acc by alpha = exp(m_i_thread - m_final) before sum-reduce.
268
+ __local ACC_TYPE local_m[Q1_WG_SIZE];
269
+ local_m[tid] = m_i;
270
+ barrier(CLK_LOCAL_MEM_FENCE);
271
+ #pragma unroll
272
+ for (int s = Q1_WG_SIZE / 2; s > 0; s >>= 1) {
273
+ if (tid < s) local_m[tid] = max(local_m[tid], local_m[tid + s]);
274
+ barrier(CLK_LOCAL_MEM_FENCE);
275
+ }
276
+ const ACC_TYPE m_final = local_m[0];
277
+
278
+ const ACC_TYPE alpha_final = exp(m_i - m_final);
279
+ l_i *= alpha_final;
280
+ #pragma unroll
281
+ for (int i = 0; i < DV_VEC; ++i) o_acc[i] *= alpha_final;
282
+
283
+ __local ACC_TYPE local_l[Q1_WG_SIZE];
284
+ __local ACC_TYPE4 local_o_comp[Q1_WG_SIZE];
285
+ local_l[tid] = l_i;
286
+ barrier(CLK_LOCAL_MEM_FENCE);
287
+ #pragma unroll
288
+ for (int s = Q1_WG_SIZE / 2; s > 0; s >>= 1) {
289
+ if (tid < s) local_l[tid] += local_l[tid + s];
290
+ barrier(CLK_LOCAL_MEM_FENCE);
291
+ }
292
+
293
+ const ulong o_row_offset = batch_idx * o_nb3 + head_idx * o_nb1;
294
+ global O_DATA_TYPE4 *o_row = (global O_DATA_TYPE4 *)(o_base + o_row_offset);
295
+ ACC_TYPE l_final = local_l[0];
296
+
297
+ if (sinks_ptr != NULL) {
298
+ l_final += exp(sinks_ptr[head_idx] - m_final);
299
+ }
300
+
301
+ if (l_final > 0.0f) {
302
+ const ACC_TYPE l_inv = 1.0f / l_final;
303
+ for (int i = 0; i < DV_VEC; i++) {
304
+ local_o_comp[tid] = o_acc[i];
305
+ barrier(CLK_LOCAL_MEM_FENCE);
306
+ #pragma unroll
307
+ for (int s = Q1_WG_SIZE / 2; s > 0; s >>= 1) {
308
+ if (tid < s) local_o_comp[tid] += local_o_comp[tid + s];
309
+ barrier(CLK_LOCAL_MEM_FENCE);
310
+ }
311
+ if (tid == 0) {
312
+ o_row[i] = CONVERT_O_DATA4(local_o_comp[0] * l_inv);
313
+ }
314
+ }
315
+ } else if (tid == 0) {
316
+ #pragma unroll
317
+ for (int i = 0; i < DV_VEC; ++i) o_row[i] = (O_DATA_TYPE4)(0.0f);
318
+ }
319
+ }
320
+
321
+ #ifdef cl_intel_subgroups
322
+ #pragma OPENCL EXTENSION cl_intel_subgroups : enable
323
+ #else
324
+ #pragma OPENCL EXTENSION cl_khr_subgroups : enable
325
+ #endif
326
+
327
+ #ifdef cl_qcom_reqd_sub_group_size
328
+ #pragma OPENCL EXTENSION cl_qcom_reqd_sub_group_size : enable
329
+ #define REQD_SUBGROUP_SIZE_64 __attribute__((qcom_reqd_sub_group_size("half")))
330
+ #else
331
+ #define REQD_SUBGROUP_SIZE_64
332
+ #endif
333
+
334
+ #define VEC_NSG 4
335
+ #define VEC_WG_SIZE (Q1_WG_SIZE * VEC_NSG)
336
+ #define Q1V_DV_PER_THREAD ((DV_VEC + Q1_WG_SIZE - 1) / Q1_WG_SIZE)
337
+
338
+ inline float4 dequant_q8_0_lane(const global char * block_ptr, int lane) {
339
+ const float d = vload_half(0, (const global half *)block_ptr);
340
+ const global char * qs = block_ptr + 2 + lane * 4;
341
+ return d * (float4)((float)qs[0], (float)qs[1], (float)qs[2], (float)qs[3]);
342
+ }
343
+
344
+ REQD_SUBGROUP_SIZE_64
345
+ __kernel void flash_attn_f32_q8_0_q1_vec(
346
+ const global void * q_void, ulong q_offset,
347
+ const global void * k_void, ulong k_offset,
348
+ const global void * v_void, ulong v_offset,
349
+ global void * o_void, ulong o_offset,
350
+ const float scale,
351
+ const int n_q,
352
+ const int n_kv,
353
+ const int is_causal,
354
+ const int n_head,
355
+ const ulong q_nb1, const ulong q_nb2, const ulong q_nb3,
356
+ const ulong k_nb1, const ulong k_nb2, const ulong k_nb3,
357
+ const ulong v_nb1, const ulong v_nb2, const ulong v_nb3,
358
+ const ulong o_nb1, const ulong o_nb2, const ulong o_nb3,
359
+ const float max_bias,
360
+ const float m0,
361
+ const float m1,
362
+ const int n_head_log2,
363
+ const float logit_softcap,
364
+ const int n_head_kv,
365
+ const global void* mask_void,
366
+ const ulong mask_offset,
367
+ const ulong mask_nb1,
368
+ const ulong mask_nb2,
369
+ const ulong mask_nb3,
370
+ const int mask_ne2,
371
+ const int mask_ne3,
372
+ const global void* sinks_void,
373
+ const ulong sinks_offset
374
+ ) {
375
+ const int tid = get_local_id(0);
376
+ const int sgid = tid / Q1_WG_SIZE;
377
+ const int tid_sg = tid % Q1_WG_SIZE;
378
+ const int head_batch_idx = get_global_id(1);
379
+
380
+ const int batch_idx = head_batch_idx / n_head;
381
+ const int head_idx = head_batch_idx % n_head;
382
+
383
+ const int gqa_ratio = n_head / n_head_kv;
384
+ const int head_kv_idx = head_idx / gqa_ratio;
385
+
386
+ const global char * q_base = (const global char *) q_void + q_offset;
387
+ const global char * k_base = (const global char *) k_void + k_offset;
388
+ const global char * v_base = (const global char *) v_void + v_offset;
389
+ global char * o_base = (global char *) o_void + o_offset;
390
+
391
+ const global char * mask_base = NULL;
392
+ if (mask_void != NULL) {
393
+ const int mask_head_idx = head_idx % mask_ne2;
394
+ const int mask_batch_idx = batch_idx % mask_ne3;
395
+ mask_base = (const global char *) mask_void + mask_offset +
396
+ mask_batch_idx * mask_nb3 + mask_head_idx * mask_nb2;
397
+ }
398
+
399
+ __local ACC_TYPE4 q_shared[DK_VEC];
400
+ {
401
+ const ulong q_row_offset = batch_idx * q_nb3 + head_idx * q_nb2;
402
+ const global Q_DATA_TYPE4 * q_ptr = (const global Q_DATA_TYPE4 *) (q_base + q_row_offset);
403
+ for (int i = tid; i < DK_VEC; i += VEC_WG_SIZE) {
404
+ q_shared[i] = CONVERT_Q_ACC4(q_ptr[i]);
405
+ }
406
+ }
407
+ barrier(CLK_LOCAL_MEM_FENCE);
408
+
409
+ const float slope = get_alibi_slope(max_bias, head_idx, n_head_log2, m0, m1);
410
+
411
+ const global ACC_TYPE * sinks_ptr = NULL;
412
+ if (sinks_void != NULL) {
413
+ sinks_ptr = (const global ACC_TYPE *) ((const global char *) sinks_void + sinks_offset);
414
+ }
415
+
416
+ ACC_TYPE4 o_acc[Q1V_DV_PER_THREAD];
417
+ #pragma unroll
418
+ for (int i = 0; i < Q1V_DV_PER_THREAD; ++i) o_acc[i] = (ACC_TYPE4)(0.0f);
419
+
420
+ ACC_TYPE m_i = FA_M_INIT;
421
+ ACC_TYPE l_i = 0.0f;
422
+
423
+ const int kv_per_sg = (n_kv + VEC_NSG - 1) / VEC_NSG;
424
+ const int kv_start = sgid * kv_per_sg;
425
+ const int kv_end = min(n_kv, kv_start + kv_per_sg);
426
+
427
+ for (int k_idx = kv_start; k_idx < kv_end; ++k_idx) {
428
+ const global char * k_row = k_base + batch_idx * k_nb3 + head_kv_idx * k_nb2 + k_idx * k_nb1;
429
+ const global char * v_row = v_base + batch_idx * v_nb3 + head_kv_idx * v_nb2 + k_idx * v_nb1;
430
+
431
+ ACC_TYPE4 dot4 = (ACC_TYPE4)(0.0f);
432
+ for (int qk = tid_sg; qk < DK_VEC; qk += Q1_WG_SIZE) {
433
+ const int block_idx = qk / 8;
434
+ const int lane = qk % 8;
435
+ const float4 k_v = dequant_q8_0_lane(k_row + block_idx * Q8_0_BLOCK_SIZE, lane);
436
+ dot4 = mad(q_shared[qk], k_v, dot4);
437
+ }
438
+ ACC_TYPE dot_partial = dot4.s0 + dot4.s1 + dot4.s2 + dot4.s3;
439
+ ACC_TYPE score = sub_group_reduce_add(dot_partial) * scale;
440
+
441
+ if (mask_base != NULL) {
442
+ const global MASK_DATA_TYPE * mask_ptr = (const global MASK_DATA_TYPE *) mask_base;
443
+ score += slope * (ACC_TYPE) mask_ptr[k_idx];
444
+ }
445
+ if (logit_softcap > 0.0f) {
446
+ score = logit_softcap * tanh(score / logit_softcap);
447
+ }
448
+
449
+ const ACC_TYPE m_new = max(m_i, score);
450
+ const ACC_TYPE scale_prev = native_exp(m_i - m_new);
451
+ const ACC_TYPE p = native_exp(score - m_new);
452
+
453
+ int idx = 0;
454
+ for (int dv = tid_sg; dv < DV_VEC; dv += Q1_WG_SIZE, ++idx) {
455
+ const int block_idx = dv / 8;
456
+ const int lane = dv % 8;
457
+ const float4 v_v = dequant_q8_0_lane(v_row + block_idx * Q8_0_BLOCK_SIZE, lane);
458
+ o_acc[idx] = mad(p, v_v, o_acc[idx] * scale_prev);
459
+ }
460
+ l_i = l_i * scale_prev + p;
461
+ m_i = m_new;
462
+ }
463
+
464
+ __local ACC_TYPE sg_m[VEC_NSG];
465
+ __local ACC_TYPE sg_l[VEC_NSG];
466
+ __local ACC_TYPE4 sg_o[VEC_NSG][DV_VEC];
467
+
468
+ if (tid_sg == 0) {
469
+ sg_m[sgid] = m_i;
470
+ sg_l[sgid] = l_i;
471
+ }
472
+ {
473
+ int idx = 0;
474
+ for (int dv = tid_sg; dv < DV_VEC; dv += Q1_WG_SIZE, ++idx) {
475
+ sg_o[sgid][dv] = o_acc[idx];
476
+ }
477
+ }
478
+ barrier(CLK_LOCAL_MEM_FENCE);
479
+
480
+ if (sgid == 0) {
481
+ ACC_TYPE m_final = sg_m[0];
482
+ #pragma unroll
483
+ for (int s = 1; s < VEC_NSG; ++s) {
484
+ m_final = max(m_final, sg_m[s]);
485
+ }
486
+ if (sinks_ptr != NULL) {
487
+ m_final = max(m_final, sinks_ptr[head_idx]);
488
+ }
489
+
490
+ ACC_TYPE l_final = 0.0f;
491
+ #pragma unroll
492
+ for (int s = 0; s < VEC_NSG; ++s) {
493
+ l_final += sg_l[s] * native_exp(sg_m[s] - m_final);
494
+ }
495
+ if (sinks_ptr != NULL) {
496
+ l_final += native_exp(sinks_ptr[head_idx] - m_final);
497
+ }
498
+ const ACC_TYPE l_inv = (l_final > 0.0f) ? (1.0f / l_final) : 0.0f;
499
+
500
+ const ulong o_row_offset = batch_idx * o_nb3 + head_idx * o_nb1;
501
+ global O_DATA_TYPE4 * o_row = (global O_DATA_TYPE4 *) (o_base + o_row_offset);
502
+
503
+ int idx = 0;
504
+ for (int dv = tid_sg; dv < DV_VEC; dv += Q1_WG_SIZE, ++idx) {
505
+ ACC_TYPE4 o_merged = (ACC_TYPE4)(0.0f);
506
+ #pragma unroll
507
+ for (int s = 0; s < VEC_NSG; ++s) {
508
+ const ACC_TYPE alpha = native_exp(sg_m[s] - m_final);
509
+ o_merged = mad((ACC_TYPE4)(alpha), sg_o[s][dv], o_merged);
510
+ }
511
+ o_row[dv] = CONVERT_O_DATA4(o_merged * l_inv);
512
+ }
513
+ }
514
+ }
515
+
516
+ // Flash-decoding split pass for q8_0 KV. Partial record: [m, l, O[DV]].
517
+ // Merge kernel from flash_attn_f32_f16.cl is type-agnostic and reused.
518
+ #define FA_PARTIAL_FLOATS (2 + DV)
519
+
520
+ __kernel void flash_attn_f32_q8_0_q1_split(
521
+ const global void * q_void, ulong q_offset,
522
+ const global void * k_void, ulong k_offset,
523
+ const global void * v_void, ulong v_offset,
524
+ const float scale,
525
+ const int n_q,
526
+ const int n_kv,
527
+ const int n_head,
528
+ const ulong q_nb1, const ulong q_nb2, const ulong q_nb3,
529
+ const ulong k_nb1, const ulong k_nb2, const ulong k_nb3,
530
+ const ulong v_nb1, const ulong v_nb2, const ulong v_nb3,
531
+ const float max_bias,
532
+ const float m0,
533
+ const float m1,
534
+ const int n_head_log2,
535
+ const float logit_softcap,
536
+ const int n_head_kv,
537
+ const global void * mask_void,
538
+ const ulong mask_offset,
539
+ const ulong mask_nb1,
540
+ const ulong mask_nb2,
541
+ const ulong mask_nb3,
542
+ const int mask_ne2,
543
+ const int mask_ne3,
544
+ global float * partial_void,
545
+ const int n_splits,
546
+ const int kv_per_split
547
+ ) {
548
+ const int tid = get_local_id(0);
549
+ const int head_batch_idx = get_global_id(1);
550
+ const int split_q_idx = get_global_id(2);
551
+ const int split_idx = split_q_idx % n_splits;
552
+ const int q_idx = split_q_idx / n_splits;
553
+ const int batch_idx = head_batch_idx / n_head;
554
+ const int head_idx = head_batch_idx % n_head;
555
+ const int gqa_ratio = n_head / n_head_kv;
556
+ const int head_kv_idx = head_idx / gqa_ratio;
557
+
558
+ const int kv_start = split_idx * kv_per_split;
559
+ const int kv_end = min(kv_start + kv_per_split, n_kv);
560
+
561
+ const ulong record_stride = (ulong) FA_PARTIAL_FLOATS;
562
+ const ulong record_idx = ((((ulong) batch_idx * n_head + head_idx) * n_q + q_idx)
563
+ * n_splits + split_idx);
564
+ global float * rec = partial_void + record_idx * record_stride;
565
+ global float4 * rec_o = (global float4 *) (rec + 2);
566
+
567
+ if (kv_start >= kv_end) {
568
+ // Empty split: leave sentinel partial for merge.
569
+ if (tid == 0) {
570
+ rec[0] = FA_M_INIT;
571
+ rec[1] = 0.0f;
572
+ }
573
+ return;
574
+ }
575
+
576
+ const global char * q_base = (const global char *) q_void + q_offset;
577
+ const global char * k_base = (const global char *) k_void + k_offset;
578
+ const global char * v_base = (const global char *) v_void + v_offset;
579
+
580
+ const global char * mask_base = NULL;
581
+ if (mask_void != NULL) {
582
+ const int mask_head_idx = head_idx % mask_ne2;
583
+ const int mask_batch_idx = batch_idx % mask_ne3;
584
+ mask_base = (const global char *) mask_void + mask_offset +
585
+ mask_batch_idx * mask_nb3 + mask_head_idx * mask_nb2 +
586
+ (ulong) q_idx * mask_nb1;
587
+ }
588
+
589
+ ACC_TYPE4 q_priv[DK_VEC];
590
+ const ulong q_row_offset = batch_idx * q_nb3 + head_idx * q_nb2 + (ulong) q_idx * q_nb1;
591
+ const global Q_DATA_TYPE4 * q_ptr = (const global Q_DATA_TYPE4 *) (q_base + q_row_offset);
592
+ #pragma unroll
593
+ for (int i = 0; i < DK_VEC; ++i) {
594
+ q_priv[i] = CONVERT_Q_ACC4(q_ptr[i]);
595
+ }
596
+
597
+ #ifdef FA_HAVE_INT_DOT
598
+ uint q_packed[DK_Q8_BLOCKS * 8];
599
+ float q_d_scale[DK_Q8_BLOCKS];
600
+ #pragma unroll
601
+ for (int b = 0; b < DK_Q8_BLOCKS; ++b) {
602
+ q_d_scale[b] = quant_q_block_int8_packed(&q_priv[b * 8], &q_packed[b * 8]);
603
+ }
604
+ #endif
605
+
606
+ const float slope = get_alibi_slope(max_bias, head_idx, n_head_log2, m0, m1);
607
+
608
+ // One-pass online softmax (FA-2): single sweep over the split's K range,
609
+ // updating per-thread (m_i, l_i, o_acc) per position. Eliminates the
610
+ // second K read of the original two-pass implementation.
611
+ ACC_TYPE m_i = FA_M_INIT;
612
+ ACC_TYPE l_i = 0.0f;
613
+ ACC_TYPE4 o_acc[DV_VEC];
614
+ #pragma unroll
615
+ for (int i = 0; i < DV_VEC; ++i) o_acc[i] = (ACC_TYPE4)(0.0f);
616
+
617
+ for (int k_idx = kv_start + tid; k_idx < kv_end; k_idx += Q1_WG_SIZE) {
618
+ const global char * k_row = k_base + batch_idx * k_nb3 + head_kv_idx * k_nb2 + k_idx * k_nb1;
619
+ const global char * v_row = v_base + batch_idx * v_nb3 + head_kv_idx * v_nb2 + k_idx * v_nb1;
620
+ ACC_TYPE score = 0.0f;
621
+ #pragma unroll
622
+ for (int b = 0; b < DK_Q8_BLOCKS; ++b) {
623
+ #ifdef FA_HAVE_INT_DOT
624
+ score += dot_q8_0_int(k_row + b * Q8_0_BLOCK_SIZE, &q_packed[b * 8], q_d_scale[b]);
625
+ #else
626
+ score += dot_q8_0_f32(k_row + b * Q8_0_BLOCK_SIZE, &q_priv[b * 8]);
627
+ #endif
628
+ }
629
+ score *= scale;
630
+ if (mask_base != NULL) {
631
+ const global MASK_DATA_TYPE * mask_ptr = (const global MASK_DATA_TYPE *) (mask_base);
632
+ score += slope * (ACC_TYPE) mask_ptr[k_idx];
633
+ }
634
+ if (logit_softcap > 0.0f) {
635
+ score = logit_softcap * tanh(score / logit_softcap);
636
+ }
637
+
638
+ // Online softmax step.
639
+ const ACC_TYPE m_new = max(m_i, score);
640
+ const ACC_TYPE alpha = exp(m_i - m_new);
641
+ const ACC_TYPE p = exp(score - m_new);
642
+
643
+ l_i = alpha * l_i + p;
644
+ #pragma unroll
645
+ for (int i = 0; i < DV_VEC; ++i) o_acc[i] *= alpha;
646
+
647
+ #pragma unroll
648
+ for (int b = 0; b < DV_Q8_BLOCKS; ++b) {
649
+ ACC_TYPE4 v_dequant[8];
650
+ dequant_q8_0_f32(v_row + b * Q8_0_BLOCK_SIZE, v_dequant);
651
+ #pragma unroll
652
+ for (int i = 0; i < 8; ++i) {
653
+ o_acc[b * 8 + i] = mad(p, v_dequant[i], o_acc[b * 8 + i]);
654
+ }
655
+ }
656
+
657
+ m_i = m_new;
658
+ }
659
+
660
+ // Cross-thread reduce: max(m_i) -> m_c, then rescale per-thread l_i and
661
+ // o_acc by alpha = exp(m_i_thread - m_c) before sum-reduce.
662
+ __local ACC_TYPE local_m[Q1_WG_SIZE];
663
+ local_m[tid] = m_i;
664
+ barrier(CLK_LOCAL_MEM_FENCE);
665
+ #pragma unroll
666
+ for (int s = Q1_WG_SIZE / 2; s > 0; s >>= 1) {
667
+ if (tid < s) local_m[tid] = max(local_m[tid], local_m[tid + s]);
668
+ barrier(CLK_LOCAL_MEM_FENCE);
669
+ }
670
+ const ACC_TYPE m_c = local_m[0];
671
+
672
+ const ACC_TYPE alpha_final = exp(m_i - m_c);
673
+ l_i *= alpha_final;
674
+ #pragma unroll
675
+ for (int i = 0; i < DV_VEC; ++i) o_acc[i] *= alpha_final;
676
+
677
+ __local ACC_TYPE local_l[Q1_WG_SIZE];
678
+ __local ACC_TYPE4 local_o[Q1_WG_SIZE];
679
+ local_l[tid] = l_i;
680
+ barrier(CLK_LOCAL_MEM_FENCE);
681
+ #pragma unroll
682
+ for (int s = Q1_WG_SIZE / 2; s > 0; s >>= 1) {
683
+ if (tid < s) local_l[tid] += local_l[tid + s];
684
+ barrier(CLK_LOCAL_MEM_FENCE);
685
+ }
686
+ const ACC_TYPE l_c = local_l[0];
687
+
688
+ if (tid == 0) {
689
+ rec[0] = (float) m_c;
690
+ rec[1] = (float) l_c;
691
+ }
692
+ for (int i = 0; i < DV_VEC; ++i) {
693
+ local_o[tid] = o_acc[i];
694
+ barrier(CLK_LOCAL_MEM_FENCE);
695
+ #pragma unroll
696
+ for (int s = Q1_WG_SIZE / 2; s > 0; s >>= 1) {
697
+ if (tid < s) local_o[tid] += local_o[tid + s];
698
+ barrier(CLK_LOCAL_MEM_FENCE);
699
+ }
700
+ if (tid == 0) {
701
+ rec_o[i] = local_o[0];
702
+ }
703
+ }
704
+ }
705
+
706
+ // Prefill: q8_0 K/V, n_q > 1. BLOCK_M × BLOCK_N tiling.
707
+ // K path keeps packed int8 in local for dp4a QK dot; V path dequant -> half in local.
708
+ // Requires DK % QK8_0 == 0 and DV % QK8_0 == 0 (gated in supports_op).
709
+ #define KV_DATA_TYPE4 half4
710
+ #define CONVERT_KV_ACC4(x) convert_float4(x)
711
+
712
+ #define DK_Q8_BLOCKS_PREFILL (DK / QK8_0)
713
+ #define DV_Q8_BLOCKS_PREFILL (DV / QK8_0)
714
+
715
+ // N_SPLIT>1 splits DK/DV across N_SPLIT threads per query row; needs
716
+ // sub_group_shuffle_xor and DK_Q8_BLOCKS_PREFILL % N_SPLIT == 0.
717
+ #ifndef N_SPLIT
718
+ #define N_SPLIT 1
719
+ #endif
720
+
721
+ #if N_SPLIT > 1
722
+ #define SPLIT_DK_VEC (DK_VEC / N_SPLIT)
723
+ #define SPLIT_DV_VEC (DV_VEC / N_SPLIT)
724
+ #define SPLIT_DK_Q8_BLOCKS (DK_Q8_BLOCKS_PREFILL / N_SPLIT)
725
+ #define WG_SIZE (BLOCK_M * N_SPLIT)
726
+ #else
727
+ #define SPLIT_DK_VEC DK_VEC
728
+ #define SPLIT_DV_VEC DV_VEC
729
+ #define SPLIT_DK_Q8_BLOCKS DK_Q8_BLOCKS_PREFILL
730
+ #define WG_SIZE BLOCK_M
731
+ #endif
732
+
733
+ // FA_V_STRATEGY: 0 = dequant V to half in local (default); 2 = keep packed
734
+ // int8 in local, dequant in the accumulate loop (smaller local, slightly slower).
735
+ #ifndef FA_V_STRATEGY
736
+ #define FA_V_STRATEGY 0
737
+ #endif
738
+
739
+ #ifndef MQ_GQA
740
+ #define MQ_GQA 4
741
+ #endif
742
+ #ifndef MQ_NSG_SPLIT
743
+ #define MQ_NSG_SPLIT 4
744
+ #endif
745
+ #define MQ_SPLIT_WG_SIZE_Q8 (Q1_WG_SIZE * MQ_NSG_SPLIT)
746
+
747
+ REQD_SUBGROUP_SIZE_64
748
+ __kernel void flash_attn_f32_q8_0_q1_vec_mq_split(
749
+ const global void * q_void, ulong q_offset,
750
+ const global void * k_void, ulong k_offset,
751
+ const global void * v_void, ulong v_offset,
752
+ const float scale,
753
+ const int n_q,
754
+ const int n_kv,
755
+ const int n_head,
756
+ const ulong q_nb1, const ulong q_nb2, const ulong q_nb3,
757
+ const ulong k_nb1, const ulong k_nb2, const ulong k_nb3,
758
+ const ulong v_nb1, const ulong v_nb2, const ulong v_nb3,
759
+ const float max_bias,
760
+ const float m0,
761
+ const float m1,
762
+ const int n_head_log2,
763
+ const float logit_softcap,
764
+ const int n_head_kv,
765
+ const global void * mask_void,
766
+ const ulong mask_offset,
767
+ const ulong mask_nb1,
768
+ const ulong mask_nb2,
769
+ const ulong mask_nb3,
770
+ const int mask_ne2,
771
+ const int mask_ne3,
772
+ global float * partial_void,
773
+ const int n_splits,
774
+ const int kv_per_split
775
+ ) {
776
+ const int tid = get_local_id(0);
777
+ const int sgid = tid / Q1_WG_SIZE;
778
+ const int tid_sg = tid % Q1_WG_SIZE;
779
+ const int kvhead_batch_idx = get_global_id(1);
780
+ const int split_q_idx = get_global_id(2);
781
+ const int split_idx = split_q_idx % n_splits;
782
+ const int q_idx = split_q_idx / n_splits;
783
+
784
+ const int batch_idx = kvhead_batch_idx / n_head_kv;
785
+ const int head_kv_idx = kvhead_batch_idx % n_head_kv;
786
+
787
+ const int kv_start = split_idx * kv_per_split;
788
+ const int kv_end = min(kv_start + kv_per_split, n_kv);
789
+
790
+ const ulong record_stride = (ulong) FA_PARTIAL_FLOATS;
791
+
792
+ if (kv_start >= kv_end) {
793
+ // Empty split — write sentinel for each of the MQ_GQA Q-heads.
794
+ if (tid == 0) {
795
+ #pragma unroll
796
+ for (int h = 0; h < MQ_GQA; ++h) {
797
+ const int head_idx = head_kv_idx * MQ_GQA + h;
798
+ const ulong rec_idx = ((((ulong) batch_idx * n_head + head_idx) * n_q + q_idx)
799
+ * n_splits + split_idx);
800
+ global float * rec = partial_void + rec_idx * record_stride;
801
+ rec[0] = FA_M_INIT;
802
+ rec[1] = 0.0f;
803
+ }
804
+ }
805
+ return;
806
+ }
807
+
808
+ const global char * q_base = (const global char *) q_void + q_offset;
809
+ const global char * k_base = (const global char *) k_void + k_offset;
810
+ const global char * v_base = (const global char *) v_void + v_offset;
811
+
812
+ __local ACC_TYPE4 q_shared[MQ_GQA * DK_VEC];
813
+ for (int i = tid; i < MQ_GQA * DK_VEC; i += MQ_SPLIT_WG_SIZE_Q8) {
814
+ const int h = i / DK_VEC;
815
+ const int k = i % DK_VEC;
816
+ const int head_idx = head_kv_idx * MQ_GQA + h;
817
+ const ulong q_row_offset = batch_idx * q_nb3 + head_idx * q_nb2 + (ulong) q_idx * q_nb1;
818
+ const global Q_DATA_TYPE4 * q_ptr = (const global Q_DATA_TYPE4 *) (q_base + q_row_offset);
819
+ q_shared[h * DK_VEC + k] = CONVERT_Q_ACC4(q_ptr[k]);
820
+ }
821
+ barrier(CLK_LOCAL_MEM_FENCE);
822
+
823
+ float slope[MQ_GQA];
824
+ #pragma unroll
825
+ for (int h = 0; h < MQ_GQA; ++h) {
826
+ slope[h] = get_alibi_slope(max_bias, head_kv_idx * MQ_GQA + h, n_head_log2, m0, m1);
827
+ }
828
+
829
+ const global char * mask_base[MQ_GQA];
830
+ if (mask_void != NULL) {
831
+ const int mask_batch_idx = batch_idx % mask_ne3;
832
+ const global char * mask_base_b = (const global char *) mask_void + mask_offset +
833
+ mask_batch_idx * mask_nb3 +
834
+ (ulong) q_idx * mask_nb1;
835
+ #pragma unroll
836
+ for (int h = 0; h < MQ_GQA; ++h) {
837
+ const int head_idx = head_kv_idx * MQ_GQA + h;
838
+ const int mask_head_idx = head_idx % mask_ne2;
839
+ mask_base[h] = mask_base_b + mask_head_idx * mask_nb2;
840
+ }
841
+ } else {
842
+ #pragma unroll
843
+ for (int h = 0; h < MQ_GQA; ++h) mask_base[h] = NULL;
844
+ }
845
+
846
+ ACC_TYPE4 o_acc[MQ_GQA][Q1V_DV_PER_THREAD];
847
+ ACC_TYPE m_i[MQ_GQA];
848
+ ACC_TYPE l_i[MQ_GQA];
849
+ #pragma unroll
850
+ for (int h = 0; h < MQ_GQA; ++h) {
851
+ m_i[h] = FA_M_INIT;
852
+ l_i[h] = 0.0f;
853
+ #pragma unroll
854
+ for (int i = 0; i < Q1V_DV_PER_THREAD; ++i) o_acc[h][i] = (ACC_TYPE4)(0.0f);
855
+ }
856
+
857
+ const int kv_len = kv_end - kv_start;
858
+ const int kv_per_sg = (kv_len + MQ_NSG_SPLIT - 1) / MQ_NSG_SPLIT;
859
+ const int kv_lo = kv_start + sgid * kv_per_sg;
860
+ const int kv_hi = min(kv_end, kv_lo + kv_per_sg);
861
+
862
+ for (int k_idx = kv_lo; k_idx < kv_hi; ++k_idx) {
863
+ const global char * k_row = k_base + batch_idx * k_nb3 + head_kv_idx * k_nb2 + k_idx * k_nb1;
864
+ const global char * v_row = v_base + batch_idx * v_nb3 + head_kv_idx * v_nb2 + k_idx * v_nb1;
865
+
866
+ ACC_TYPE4 dot4[MQ_GQA];
867
+ #pragma unroll
868
+ for (int h = 0; h < MQ_GQA; ++h) dot4[h] = (ACC_TYPE4)(0.0f);
869
+
870
+ for (int qk = tid_sg; qk < DK_VEC; qk += Q1_WG_SIZE) {
871
+ const int block_idx = qk / 8;
872
+ const int lane = qk % 8;
873
+ const float4 k_v = dequant_q8_0_lane(k_row + block_idx * Q8_0_BLOCK_SIZE, lane);
874
+ #pragma unroll
875
+ for (int h = 0; h < MQ_GQA; ++h) {
876
+ dot4[h] = mad(q_shared[h * DK_VEC + qk], k_v, dot4[h]);
877
+ }
878
+ }
879
+
880
+ ACC_TYPE score[MQ_GQA];
881
+ #pragma unroll
882
+ for (int h = 0; h < MQ_GQA; ++h) {
883
+ const ACC_TYPE dot_partial = dot4[h].s0 + dot4[h].s1 + dot4[h].s2 + dot4[h].s3;
884
+ ACC_TYPE s = sub_group_reduce_add(dot_partial) * scale;
885
+ if (mask_base[h] != NULL) {
886
+ const global MASK_DATA_TYPE * mask_ptr = (const global MASK_DATA_TYPE *) mask_base[h];
887
+ s += slope[h] * (ACC_TYPE) mask_ptr[k_idx];
888
+ }
889
+ if (logit_softcap > 0.0f) {
890
+ s = logit_softcap * tanh(s / logit_softcap);
891
+ }
892
+ score[h] = s;
893
+ }
894
+
895
+ ACC_TYPE p_h[MQ_GQA];
896
+ ACC_TYPE sp_h[MQ_GQA];
897
+ #pragma unroll
898
+ for (int h = 0; h < MQ_GQA; ++h) {
899
+ const ACC_TYPE m_new = max(m_i[h], score[h]);
900
+ sp_h[h] = native_exp(m_i[h] - m_new);
901
+ p_h[h] = native_exp(score[h] - m_new);
902
+ l_i[h] = l_i[h] * sp_h[h] + p_h[h];
903
+ m_i[h] = m_new;
904
+ }
905
+
906
+ int idx = 0;
907
+ for (int dv = tid_sg; dv < DV_VEC; dv += Q1_WG_SIZE, ++idx) {
908
+ const int block_idx = dv / 8;
909
+ const int lane = dv % 8;
910
+ const float4 v_v = dequant_q8_0_lane(v_row + block_idx * Q8_0_BLOCK_SIZE, lane);
911
+ #pragma unroll
912
+ for (int h = 0; h < MQ_GQA; ++h) {
913
+ o_acc[h][idx] = mad(p_h[h], v_v, o_acc[h][idx] * sp_h[h]);
914
+ }
915
+ }
916
+ }
917
+
918
+ __local ACC_TYPE sg_m[MQ_GQA][MQ_NSG_SPLIT];
919
+ __local ACC_TYPE sg_l[MQ_GQA][MQ_NSG_SPLIT];
920
+ __local ACC_TYPE4 sg_o[MQ_NSG_SPLIT][DV_VEC];
921
+
922
+ if (tid_sg == 0) {
923
+ #pragma unroll
924
+ for (int h = 0; h < MQ_GQA; ++h) {
925
+ sg_m[h][sgid] = m_i[h];
926
+ sg_l[h][sgid] = l_i[h];
927
+ }
928
+ }
929
+
930
+ #pragma unroll
931
+ for (int h = 0; h < MQ_GQA; ++h) {
932
+ {
933
+ int idx = 0;
934
+ for (int dv_idx = tid_sg; dv_idx < DV_VEC; dv_idx += Q1_WG_SIZE, ++idx) {
935
+ sg_o[sgid][dv_idx] = o_acc[h][idx];
936
+ }
937
+ }
938
+ barrier(CLK_LOCAL_MEM_FENCE);
939
+
940
+ if (sgid == 0) {
941
+ const int head_idx = head_kv_idx * MQ_GQA + h;
942
+
943
+ ACC_TYPE m_c = sg_m[h][0];
944
+ #pragma unroll
945
+ for (int s = 1; s < MQ_NSG_SPLIT; ++s) {
946
+ m_c = max(m_c, sg_m[h][s]);
947
+ }
948
+ ACC_TYPE l_c = 0.0f;
949
+ #pragma unroll
950
+ for (int s = 0; s < MQ_NSG_SPLIT; ++s) {
951
+ l_c += sg_l[h][s] * native_exp(sg_m[h][s] - m_c);
952
+ }
953
+
954
+ const ulong rec_idx = ((((ulong) batch_idx * n_head + head_idx) * n_q + q_idx)
955
+ * n_splits + split_idx);
956
+ global float * rec = partial_void + rec_idx * record_stride;
957
+ global float4 * rec_o = (global float4 *) (rec + 2);
958
+
959
+ if (tid_sg == 0) {
960
+ rec[0] = (float) m_c;
961
+ rec[1] = (float) l_c;
962
+ }
963
+ for (int dv_idx = tid_sg; dv_idx < DV_VEC; dv_idx += Q1_WG_SIZE) {
964
+ ACC_TYPE4 o_merged = (ACC_TYPE4)(0.0f);
965
+ #pragma unroll
966
+ for (int s = 0; s < MQ_NSG_SPLIT; ++s) {
967
+ const ACC_TYPE alpha = native_exp(sg_m[h][s] - m_c);
968
+ o_merged = mad((ACC_TYPE4)(alpha), sg_o[s][dv_idx], o_merged);
969
+ }
970
+ rec_o[dv_idx] = o_merged;
971
+ }
972
+ }
973
+ barrier(CLK_LOCAL_MEM_FENCE);
974
+ }
975
+ }
976
+
977
+ // flash_attn_f32_q8_0_q1_vec_mq_split_c8 — cluster-parallel variant of the MQ
978
+ // split above, port of the f16/q4_0 c8 kernels
979
+
980
+ #ifdef HAS_SUBGROUP_SHUFFLE
981
+
982
+ #ifndef FA_CL_C
983
+ #define FA_CL_C 8
984
+ #endif
985
+
986
+ // Lane striping requires DK/DV to divide across the cluster (see f16 c8).
987
+ #if (DK_VEC % FA_CL_C) == 0 && (DV_VEC % FA_CL_C) == 0
988
+ #define FA_CL_NCL (Q1_WG_SIZE / FA_CL_C) // clusters (position streams) per subgroup
989
+ #define FA_CL_DKQ (DK_VEC / FA_CL_C) // K quartets per lane per row
990
+ #define FA_CL_DVQ (DV_VEC / FA_CL_C) // V quartets (o_acc float4s) per lane per head
991
+
992
+ #ifdef FA_C8_NO_SG_PIN
993
+ #define FA_C8_SG_ATTR_Q8
994
+ #else
995
+ #define FA_C8_SG_ATTR_Q8 REQD_SUBGROUP_SIZE_64
996
+ #endif
997
+
998
+ FA_C8_SG_ATTR_Q8
999
+ __kernel void flash_attn_f32_q8_0_q1_vec_mq_split_c8(
1000
+ const global void * q_void, ulong q_offset,
1001
+ const global void * k_void, ulong k_offset,
1002
+ const global void * v_void, ulong v_offset,
1003
+ const float scale,
1004
+ const int n_q,
1005
+ const int n_kv,
1006
+ const int n_head,
1007
+ const ulong q_nb1, const ulong q_nb2, const ulong q_nb3,
1008
+ const ulong k_nb1, const ulong k_nb2, const ulong k_nb3,
1009
+ const ulong v_nb1, const ulong v_nb2, const ulong v_nb3,
1010
+ const float max_bias,
1011
+ const float m0,
1012
+ const float m1,
1013
+ const int n_head_log2,
1014
+ const float logit_softcap,
1015
+ const int n_head_kv,
1016
+ const global void * mask_void,
1017
+ const ulong mask_offset,
1018
+ const ulong mask_nb1,
1019
+ const ulong mask_nb2,
1020
+ const ulong mask_nb3,
1021
+ const int mask_ne2,
1022
+ const int mask_ne3,
1023
+ global float * partial_void,
1024
+ const int n_splits,
1025
+ const int kv_per_split
1026
+ ) {
1027
+ const int tid = get_local_id(0);
1028
+ const int sgid = tid / Q1_WG_SIZE;
1029
+ const int tid_sg = tid % Q1_WG_SIZE;
1030
+ const int cl = tid_sg / FA_CL_C; // cluster id
1031
+ const int lic = tid_sg % FA_CL_C; // lane in cluster
1032
+ const int kvhead_batch_idx = get_global_id(1);
1033
+ const int split_q_idx = get_global_id(2);
1034
+ const int split_idx = split_q_idx % n_splits;
1035
+ const int q_idx = split_q_idx / n_splits;
1036
+
1037
+ const int batch_idx = kvhead_batch_idx / n_head_kv;
1038
+ const int head_kv_idx = kvhead_batch_idx % n_head_kv;
1039
+
1040
+ const int kv_start = split_idx * kv_per_split;
1041
+ const int kv_end = min(kv_start + kv_per_split, n_kv);
1042
+
1043
+ const ulong record_stride = (ulong) FA_PARTIAL_FLOATS;
1044
+
1045
+ if (kv_start >= kv_end) {
1046
+ if (tid == 0) {
1047
+ #pragma unroll
1048
+ for (int h = 0; h < MQ_GQA; ++h) {
1049
+ const int head_idx = head_kv_idx * MQ_GQA + h;
1050
+ const ulong rec_idx = ((((ulong) batch_idx * n_head + head_idx) * n_q + q_idx)
1051
+ * n_splits + split_idx);
1052
+ global float * rec = partial_void + rec_idx * record_stride;
1053
+ rec[0] = FA_M_INIT;
1054
+ rec[1] = 0.0f;
1055
+ }
1056
+ }
1057
+ return;
1058
+ }
1059
+
1060
+ const global char * q_base = (const global char *) q_void + q_offset;
1061
+ const global char * k_base = (const global char *) k_void + k_offset;
1062
+ const global char * v_base = (const global char *) v_void + v_offset;
1063
+
1064
+ // Stage MQ_GQA Q rows in __local once (uniform across WG).
1065
+ __local ACC_TYPE4 q_shared[MQ_GQA * DK_VEC];
1066
+ for (int i = tid; i < MQ_GQA * DK_VEC; i += MQ_SPLIT_WG_SIZE_Q8) {
1067
+ const int h = i / DK_VEC;
1068
+ const int k = i % DK_VEC;
1069
+ const int head_idx = head_kv_idx * MQ_GQA + h;
1070
+ const ulong q_row_offset = batch_idx * q_nb3 + head_idx * q_nb2 + (ulong) q_idx * q_nb1;
1071
+ const global Q_DATA_TYPE4 * q_ptr = (const global Q_DATA_TYPE4 *) (q_base + q_row_offset);
1072
+ q_shared[h * DK_VEC + k] = CONVERT_Q_ACC4(q_ptr[k]);
1073
+ }
1074
+ barrier(CLK_LOCAL_MEM_FENCE);
1075
+
1076
+ float slope[MQ_GQA];
1077
+ #pragma unroll
1078
+ for (int h = 0; h < MQ_GQA; ++h) {
1079
+ slope[h] = get_alibi_slope(max_bias, head_kv_idx * MQ_GQA + h, n_head_log2, m0, m1);
1080
+ }
1081
+
1082
+ const global char * mask_base[MQ_GQA];
1083
+ if (mask_void != NULL) {
1084
+ const int mask_batch_idx = batch_idx % mask_ne3;
1085
+ const global char * mask_base_b = (const global char *) mask_void + mask_offset +
1086
+ mask_batch_idx * mask_nb3 +
1087
+ (ulong) q_idx * mask_nb1;
1088
+ #pragma unroll
1089
+ for (int h = 0; h < MQ_GQA; ++h) {
1090
+ const int head_idx = head_kv_idx * MQ_GQA + h;
1091
+ const int mask_head_idx = head_idx % mask_ne2;
1092
+ mask_base[h] = mask_base_b + mask_head_idx * mask_nb2;
1093
+ }
1094
+ } else {
1095
+ #pragma unroll
1096
+ for (int h = 0; h < MQ_GQA; ++h) mask_base[h] = NULL;
1097
+ }
1098
+
1099
+ // Per-CLUSTER online state; o_acc holds this lane's V quartets {lic + FA_CL_C*i}.
1100
+ ACC_TYPE4 o_acc[MQ_GQA][FA_CL_DVQ];
1101
+ ACC_TYPE m_i[MQ_GQA];
1102
+ ACC_TYPE l_i[MQ_GQA];
1103
+ #pragma unroll
1104
+ for (int h = 0; h < MQ_GQA; ++h) {
1105
+ m_i[h] = FA_M_INIT;
1106
+ l_i[h] = 0.0f;
1107
+ #pragma unroll
1108
+ for (int i = 0; i < FA_CL_DVQ; ++i) o_acc[h][i] = (ACC_TYPE4)(0.0f);
1109
+ }
1110
+
1111
+ const int kv_len = kv_end - kv_start;
1112
+ const int kv_per_sg = (kv_len + MQ_NSG_SPLIT - 1) / MQ_NSG_SPLIT;
1113
+ const int kv_lo = kv_start + sgid * kv_per_sg;
1114
+ const int kv_hi = min(kv_end, kv_lo + kv_per_sg);
1115
+
1116
+ // Uniform trip count; tail clamps the row address and drops the score to
1117
+ // FA_M_INIT (p underflows to 0) so shuffles stay convergent.
1118
+ const int n_iter = (kv_hi - kv_lo + FA_CL_NCL - 1) / FA_CL_NCL;
1119
+ const ulong k_row_base = batch_idx * k_nb3 + head_kv_idx * k_nb2;
1120
+ const ulong v_row_base = batch_idx * v_nb3 + head_kv_idx * v_nb2;
1121
+
1122
+ for (int it = 0; it < n_iter; ++it) {
1123
+ const int k_idx = kv_lo + cl + it * FA_CL_NCL;
1124
+ const int valid = k_idx < kv_hi;
1125
+ const int k_safe = valid ? k_idx : (kv_hi - 1);
1126
+
1127
+ const global char * k_row = k_base + k_row_base + (ulong) k_safe * k_nb1;
1128
+ const global char * v_row = v_base + v_row_base + (ulong) k_safe * v_nb1;
1129
+
1130
+ // Float-dequant K dot over this lane's quartets of the cluster's row.
1131
+ ACC_TYPE4 dot4[MQ_GQA];
1132
+ #pragma unroll
1133
+ for (int h = 0; h < MQ_GQA; ++h) dot4[h] = (ACC_TYPE4)(0.0f);
1134
+ #pragma unroll
1135
+ for (int i = 0; i < FA_CL_DKQ; ++i) {
1136
+ const int qk = lic + FA_CL_C * i;
1137
+ const float4 k_v = dequant_q8_0_lane(k_row + (qk / 8) * Q8_0_BLOCK_SIZE, qk % 8);
1138
+ #pragma unroll
1139
+ for (int h = 0; h < MQ_GQA; ++h) {
1140
+ dot4[h] = mad(q_shared[h * DK_VEC + qk], k_v, dot4[h]);
1141
+ }
1142
+ }
1143
+
1144
+ // Cluster-reduce (xor steps < FA_CL_C stay inside the cluster) + score.
1145
+ ACC_TYPE score[MQ_GQA];
1146
+ #pragma unroll
1147
+ for (int h = 0; h < MQ_GQA; ++h) {
1148
+ ACC_TYPE s = dot4[h].s0 + dot4[h].s1 + dot4[h].s2 + dot4[h].s3;
1149
+ #pragma unroll
1150
+ for (int step = 1; step < FA_CL_C; step <<= 1) {
1151
+ s += sub_group_shuffle_xor(s, step);
1152
+ }
1153
+ s *= scale;
1154
+ if (mask_base[h] != NULL) {
1155
+ const global MASK_DATA_TYPE * mask_ptr = (const global MASK_DATA_TYPE *) mask_base[h];
1156
+ s += slope[h] * (ACC_TYPE) mask_ptr[k_safe];
1157
+ }
1158
+ if (logit_softcap > 0.0f) {
1159
+ s = logit_softcap * tanh(s / logit_softcap);
1160
+ }
1161
+ score[h] = valid ? s : FA_M_INIT;
1162
+ }
1163
+
1164
+ // Per-cluster online update (serial chain depth n_iter, not kv_per_sg).
1165
+ ACC_TYPE p_h[MQ_GQA];
1166
+ ACC_TYPE sp_h[MQ_GQA];
1167
+ #pragma unroll
1168
+ for (int h = 0; h < MQ_GQA; ++h) {
1169
+ const ACC_TYPE m_new = max(m_i[h], score[h]);
1170
+ sp_h[h] = native_exp(m_i[h] - m_new);
1171
+ p_h[h] = native_exp(score[h] - m_new);
1172
+ l_i[h] = l_i[h] * sp_h[h] + p_h[h];
1173
+ m_i[h] = m_new;
1174
+ }
1175
+
1176
+ // V accumulate on this lane's quartets (p = 0 on tail -> inert).
1177
+ #pragma unroll
1178
+ for (int i = 0; i < FA_CL_DVQ; ++i) {
1179
+ const int dv = lic + FA_CL_C * i;
1180
+ const float4 v_v = dequant_q8_0_lane(v_row + (dv / 8) * Q8_0_BLOCK_SIZE, dv % 8);
1181
+ #pragma unroll
1182
+ for (int h = 0; h < MQ_GQA; ++h) {
1183
+ o_acc[h][i] = mad(p_h[h], v_v, o_acc[h][i] * sp_h[h]);
1184
+ }
1185
+ }
1186
+ }
1187
+
1188
+ // Merge stage 1: fold cluster partials inside the subgroup via shuffles.
1189
+ #pragma unroll
1190
+ for (int h = 0; h < MQ_GQA; ++h) {
1191
+ ACC_TYPE m_c = m_i[h];
1192
+ #pragma unroll
1193
+ for (int step = FA_CL_C; step < Q1_WG_SIZE; step <<= 1) {
1194
+ m_c = max(m_c, sub_group_shuffle_xor(m_c, step));
1195
+ }
1196
+ const ACC_TYPE alpha = native_exp(m_i[h] - m_c);
1197
+ ACC_TYPE l_c = l_i[h] * alpha;
1198
+ #pragma unroll
1199
+ for (int step = FA_CL_C; step < Q1_WG_SIZE; step <<= 1) {
1200
+ l_c += sub_group_shuffle_xor(l_c, step);
1201
+ }
1202
+ #pragma unroll
1203
+ for (int i = 0; i < FA_CL_DVQ; ++i) {
1204
+ ACC_TYPE4 o = o_acc[h][i] * alpha;
1205
+ #pragma unroll
1206
+ for (int step = FA_CL_C; step < Q1_WG_SIZE; step <<= 1) {
1207
+ o.s0 += sub_group_shuffle_xor(o.s0, step);
1208
+ o.s1 += sub_group_shuffle_xor(o.s1, step);
1209
+ o.s2 += sub_group_shuffle_xor(o.s2, step);
1210
+ o.s3 += sub_group_shuffle_xor(o.s3, step);
1211
+ }
1212
+ o_acc[h][i] = o;
1213
+ }
1214
+ m_i[h] = m_c;
1215
+ l_i[h] = l_c;
1216
+ }
1217
+
1218
+ // Merge stage 2: baseline cross-subgroup LDS merge (o published by
1219
+ // cluster 0's lanes; layout identical to the baseline sg_o).
1220
+ __local ACC_TYPE sg_m[MQ_GQA][MQ_NSG_SPLIT];
1221
+ __local ACC_TYPE sg_l[MQ_GQA][MQ_NSG_SPLIT];
1222
+ __local ACC_TYPE4 sg_o[MQ_NSG_SPLIT][DV_VEC];
1223
+
1224
+ if (tid_sg == 0) {
1225
+ #pragma unroll
1226
+ for (int h = 0; h < MQ_GQA; ++h) {
1227
+ sg_m[h][sgid] = m_i[h];
1228
+ sg_l[h][sgid] = l_i[h];
1229
+ }
1230
+ }
1231
+
1232
+ #pragma unroll
1233
+ for (int h = 0; h < MQ_GQA; ++h) {
1234
+ if (cl == 0) {
1235
+ #pragma unroll
1236
+ for (int i = 0; i < FA_CL_DVQ; ++i) {
1237
+ sg_o[sgid][lic + FA_CL_C * i] = o_acc[h][i];
1238
+ }
1239
+ }
1240
+ barrier(CLK_LOCAL_MEM_FENCE);
1241
+
1242
+ if (sgid == 0) {
1243
+ const int head_idx = head_kv_idx * MQ_GQA + h;
1244
+
1245
+ ACC_TYPE m_c = sg_m[h][0];
1246
+ #pragma unroll
1247
+ for (int s = 1; s < MQ_NSG_SPLIT; ++s) {
1248
+ m_c = max(m_c, sg_m[h][s]);
1249
+ }
1250
+ ACC_TYPE l_c = 0.0f;
1251
+ #pragma unroll
1252
+ for (int s = 0; s < MQ_NSG_SPLIT; ++s) {
1253
+ l_c += sg_l[h][s] * native_exp(sg_m[h][s] - m_c);
1254
+ }
1255
+
1256
+ const ulong rec_idx = ((((ulong) batch_idx * n_head + head_idx) * n_q + q_idx)
1257
+ * n_splits + split_idx);
1258
+ global float * rec = partial_void + rec_idx * record_stride;
1259
+ global float4 * rec_o = (global float4 *) (rec + 2);
1260
+
1261
+ if (tid_sg == 0) {
1262
+ rec[0] = (float) m_c;
1263
+ rec[1] = (float) l_c;
1264
+ }
1265
+ for (int dv_idx = tid_sg; dv_idx < DV_VEC; dv_idx += Q1_WG_SIZE) {
1266
+ ACC_TYPE4 o_merged = (ACC_TYPE4)(0.0f);
1267
+ #pragma unroll
1268
+ for (int s = 0; s < MQ_NSG_SPLIT; ++s) {
1269
+ const ACC_TYPE alpha = native_exp(sg_m[h][s] - m_c);
1270
+ o_merged = mad((ACC_TYPE4)(alpha), sg_o[s][dv_idx], o_merged);
1271
+ }
1272
+ rec_o[dv_idx] = o_merged;
1273
+ }
1274
+ }
1275
+ barrier(CLK_LOCAL_MEM_FENCE);
1276
+ }
1277
+ }
1278
+
1279
+ #endif // DK_VEC/DV_VEC divisible by FA_CL_C
1280
+ #endif // HAS_SUBGROUP_SHUFFLE (q1_vec_mq_split_c8)
1281
+
1282
+ __kernel void flash_attn_f32_q8_0(
1283
+ const global void * q_void, ulong q_offset,
1284
+ const global void * k_void, ulong k_offset,
1285
+ const global void * v_void, ulong v_offset,
1286
+ global void * o_void, ulong o_offset,
1287
+ const float scale,
1288
+ const int n_q,
1289
+ const int n_kv,
1290
+ const int is_causal,
1291
+ const int n_head,
1292
+ const ulong q_nb1, const ulong q_nb2, const ulong q_nb3,
1293
+ const ulong k_nb1, const ulong k_nb2, const ulong k_nb3,
1294
+ const ulong v_nb1, const ulong v_nb2, const ulong v_nb3,
1295
+ const ulong o_nb1, const ulong o_nb2, const ulong o_nb3,
1296
+ const float max_bias,
1297
+ const float m0,
1298
+ const float m1,
1299
+ const int n_head_log2,
1300
+ const float logit_softcap,
1301
+ const int n_head_kv,
1302
+ const global void* mask_void,
1303
+ const ulong mask_offset,
1304
+ const ulong mask_nb1,
1305
+ const ulong mask_nb2,
1306
+ const ulong mask_nb3,
1307
+ const int mask_ne2,
1308
+ const int mask_ne3,
1309
+ const global void* sinks_void,
1310
+ const ulong sinks_offset,
1311
+ // blk: per-(qblock,kvblock) class from flash_attn_blk_f16
1312
+ // (0=masked, 1=mixed, 2=unmasked). NULL disables the prepass opt.
1313
+ const global void * blk_void
1314
+ ) {
1315
+ const int tid = get_local_id(0);
1316
+ const int block_q_idx = get_group_id(0);
1317
+ const int head_batch_idx = get_global_id(1);
1318
+
1319
+ #if N_SPLIT > 1
1320
+ const int q_lane = tid / N_SPLIT;
1321
+ const int split_idx = tid % N_SPLIT;
1322
+ #else
1323
+ const int q_lane = tid;
1324
+ const int split_idx = 0;
1325
+ #endif
1326
+ const int my_query_row = block_q_idx * BLOCK_M + q_lane;
1327
+ const int query_valid = my_query_row < n_q;
1328
+
1329
+ const int batch_idx = head_batch_idx / n_head;
1330
+ const int head_idx = head_batch_idx % n_head;
1331
+
1332
+ const int gqa_ratio = n_head / n_head_kv;
1333
+ const int head_kv_idx = head_idx / gqa_ratio;
1334
+ const int mask_head_idx = mask_void != NULL ? head_idx % mask_ne2 : 0;
1335
+ const int mask_batch_idx = mask_void != NULL ? batch_idx % mask_ne3 : 0;
1336
+
1337
+ const global char * q_base = (const global char *) q_void + q_offset;
1338
+ const global char * k_base = (const global char *) k_void + k_offset;
1339
+ const global char * v_base = (const global char *) v_void + v_offset;
1340
+ global char * o_base = (global char *) o_void + o_offset;
1341
+
1342
+ const global char * mask_base = NULL;
1343
+ if (mask_void != NULL) {
1344
+ mask_base = (const global char *) mask_void + mask_offset +
1345
+ mask_batch_idx * mask_nb3 + mask_head_idx * mask_nb2;
1346
+ }
1347
+
1348
+ // BLK_PREPASS_BM may differ from this kernel's BLOCK_M; scale q-block idx.
1349
+ #ifndef BLK_PREPASS_BM
1350
+ #define BLK_PREPASS_BM BLOCK_M
1351
+ #endif
1352
+ const global char * blk_base = NULL;
1353
+ int n_kv_blocks = 0;
1354
+ if (blk_void != NULL) {
1355
+ n_kv_blocks = (n_kv + BLOCK_N - 1) / BLOCK_N;
1356
+ const int n_q_blocks_prepass = (n_q + BLK_PREPASS_BM - 1) / BLK_PREPASS_BM;
1357
+ const int prepass_q_block = (block_q_idx * BLOCK_M) / BLK_PREPASS_BM;
1358
+ blk_base = (const global char *) blk_void +
1359
+ (((mask_batch_idx * mask_ne2) + mask_head_idx) * n_q_blocks_prepass + prepass_q_block) * n_kv_blocks;
1360
+ }
1361
+
1362
+ const int dk_off_vec = split_idx * SPLIT_DK_VEC;
1363
+ ACC_TYPE4 q_priv[SPLIT_DK_VEC];
1364
+ if (query_valid) {
1365
+ const ulong q_row_offset = batch_idx * q_nb3 + head_idx * q_nb2 + my_query_row * q_nb1;
1366
+ const global float4 * q_ptr = (const global float4 *) (q_base + q_row_offset);
1367
+ #pragma unroll
1368
+ for (int i = 0; i < SPLIT_DK_VEC; ++i) {
1369
+ q_priv[i] = q_ptr[dk_off_vec + i];
1370
+ }
1371
+ } else {
1372
+ #pragma unroll
1373
+ for (int i = 0; i < SPLIT_DK_VEC; ++i) q_priv[i] = (ACC_TYPE4)(0.0f);
1374
+ }
1375
+
1376
+ #ifdef FA_HAVE_INT_DOT
1377
+ uint q_packed_pf[SPLIT_DK_Q8_BLOCKS * 8];
1378
+ float q_d_pf[SPLIT_DK_Q8_BLOCKS];
1379
+ #pragma unroll
1380
+ for (int b = 0; b < SPLIT_DK_Q8_BLOCKS; ++b) {
1381
+ q_d_pf[b] = quant_q_block_int8_packed(&q_priv[b * 8], &q_packed_pf[b * 8]);
1382
+ }
1383
+ #endif
1384
+
1385
+ const int dv_off_vec = split_idx * SPLIT_DV_VEC;
1386
+ ACC_TYPE4 o_acc[SPLIT_DV_VEC];
1387
+ #pragma unroll
1388
+ for (int i = 0; i < SPLIT_DV_VEC; ++i) o_acc[i] = (ACC_TYPE4)(0.0f);
1389
+
1390
+ ACC_TYPE m_i = FA_M_INIT;
1391
+ ACC_TYPE l_i = 0.0f;
1392
+
1393
+ float slope = get_alibi_slope(max_bias, head_idx, n_head_log2, m0, m1);
1394
+
1395
+ #ifdef FA_HAVE_INT_DOT
1396
+ // Accessors so the staging code is layout-agnostic.
1397
+ #ifdef FA_K_LDS_T
1398
+ #define FA_K_PACKED(ROW, IDX) l_k_packed[IDX][ROW]
1399
+ #define FA_K_SCALE(ROW, BLK) l_k_scale[BLK][ROW]
1400
+ #else
1401
+ #define FA_K_PACKED(ROW, IDX) l_k_packed[ROW][IDX]
1402
+ #define FA_K_SCALE(ROW, BLK) l_k_scale[ROW][BLK]
1403
+ #endif
1404
+
1405
+ #ifdef FA_K_LDS_T
1406
+ // K tile transposed: [block*8 + g][kv row] instead of [kv row][block*8 + g].
1407
+ //
1408
+ // The QK loop walks 4 KV rows at a time against the same (b, g), so in the original
1409
+ // layout those 4 values are BLOCK_N*8 uints apart and cost 4 separate 32-bit local
1410
+ // reads. Transposed they are adjacent, so they are one 128-bit read -- 4x fewer LDS
1411
+ // issues for the same bytes and no extra registers. That matters because the QK loop
1412
+ // is LDS-read-issue-bound: a wrong-math probe that kept every dp4a but cut the LDS
1413
+ // reads ran the whole kernel 41% faster (18.51 -> 10.91 ms/op), and deleting QK
1414
+ // outright only reached 10.88 -- i.e. essentially ALL of QK's cost is these reads.
1415
+ __local uint l_k_packed[DK_Q8_BLOCKS_PREFILL * 8][BLOCK_N];
1416
+ __local float l_k_scale [DK_Q8_BLOCKS_PREFILL][BLOCK_N];
1417
+ #else
1418
+ __local uint l_k_packed[BLOCK_N][DK_Q8_BLOCKS_PREFILL * 8];
1419
+ __local float l_k_scale [BLOCK_N][DK_Q8_BLOCKS_PREFILL];
1420
+ #endif
1421
+ #else
1422
+ __local half4 l_k[BLOCK_N][DK_VEC];
1423
+ #endif
1424
+
1425
+ #if FA_V_STRATEGY == 2
1426
+ __local uint l_v_packed[BLOCK_N][DV_Q8_BLOCKS_PREFILL * 8];
1427
+ __local float l_v_scale [BLOCK_N][DV_Q8_BLOCKS_PREFILL];
1428
+ #else
1429
+ __local half4 l_v[BLOCK_N][DV_VEC];
1430
+ #endif
1431
+
1432
+ for (int k_start = 0; k_start < n_kv; k_start += BLOCK_N) {
1433
+ // Skip fully-masked KV tiles (uniform branch across WG).
1434
+ char blk_cur = 1;
1435
+ if (blk_base != NULL) {
1436
+ blk_cur = blk_base[k_start / BLOCK_N];
1437
+ if (blk_cur == 0) continue;
1438
+ }
1439
+
1440
+ {
1441
+ #ifdef FA_HAVE_INT_DOT
1442
+ const int k_blocks_per_row = DK_Q8_BLOCKS_PREFILL;
1443
+ const int n_blocks_total = BLOCK_N * k_blocks_per_row;
1444
+ for (int i = tid; i < n_blocks_total; i += WG_SIZE) {
1445
+ const int row = i / k_blocks_per_row;
1446
+ const int blk = i % k_blocks_per_row;
1447
+ const int k_row_idx = k_start + row;
1448
+ if (k_row_idx < n_kv) {
1449
+ const ulong k_row_off = batch_idx * k_nb3 + head_kv_idx * k_nb2 + k_row_idx * k_nb1;
1450
+ const global char * blk_ptr = k_base + k_row_off + blk * Q8_0_BLOCK_SIZE;
1451
+ const float df = (float) vload_half(0, (const global half *) blk_ptr);
1452
+ const global uchar * qs = (const global uchar *)(blk_ptr + 2);
1453
+ FA_K_SCALE(row, blk) = df;
1454
+ #pragma unroll
1455
+ for (int j = 0; j < 8; ++j) {
1456
+ uint k_packed =
1457
+ (uint) qs[j*4 + 0] |
1458
+ ((uint) qs[j*4 + 1]) << 8 |
1459
+ ((uint) qs[j*4 + 2]) << 16 |
1460
+ ((uint) qs[j*4 + 3]) << 24;
1461
+ FA_K_PACKED(row, blk * 8 + j) = k_packed;
1462
+ }
1463
+ } else {
1464
+ FA_K_SCALE(row, blk) = 0.0f;
1465
+ #pragma unroll
1466
+ for (int j = 0; j < 8; ++j) FA_K_PACKED(row, blk * 8 + j) = 0u;
1467
+ }
1468
+ }
1469
+ #else
1470
+ // Fallback: dequant q8_0 -> half in local memory.
1471
+ const int k_blocks_per_row = DK / QK8_0;
1472
+ const int n_blocks_total = BLOCK_N * k_blocks_per_row;
1473
+ for (int i = tid; i < n_blocks_total; i += WG_SIZE) {
1474
+ const int row = i / k_blocks_per_row;
1475
+ const int blk = i % k_blocks_per_row;
1476
+ const int k_row_idx = k_start + row;
1477
+ if (k_row_idx < n_kv) {
1478
+ const ulong k_row_off = batch_idx * k_nb3 + head_kv_idx * k_nb2 + k_row_idx * k_nb1;
1479
+ const global char * blk_ptr = k_base + k_row_off + blk * Q8_0_BLOCK_SIZE;
1480
+ const float df = (float) vload_half(0, (const global half *) blk_ptr);
1481
+ const global char * qs = blk_ptr + 2;
1482
+ #pragma unroll
1483
+ for (int j = 0; j < 8; ++j) {
1484
+ const float4 v = df * (float4)((float) qs[j*4 + 0],
1485
+ (float) qs[j*4 + 1],
1486
+ (float) qs[j*4 + 2],
1487
+ (float) qs[j*4 + 3]);
1488
+ l_k[row][blk * 8 + j] = (half4)((half) v.s0, (half) v.s1, (half) v.s2, (half) v.s3);
1489
+ }
1490
+ } else {
1491
+ #pragma unroll
1492
+ for (int j = 0; j < 8; ++j) l_k[row][blk * 8 + j] = (half4)(0.0h);
1493
+ }
1494
+ }
1495
+ #endif
1496
+ }
1497
+ // V tile load — strategy-dependent.
1498
+ #if FA_V_STRATEGY == 2
1499
+ {
1500
+ // Int8 packed V in local memory + per-block scale. Accumulate
1501
+ // step unpacks inline.
1502
+ const int v_blocks_per_row = DV_Q8_BLOCKS_PREFILL;
1503
+ const int n_blocks_total = BLOCK_N * v_blocks_per_row;
1504
+ for (int i = tid; i < n_blocks_total; i += WG_SIZE) {
1505
+ const int row = i / v_blocks_per_row;
1506
+ const int blk = i % v_blocks_per_row;
1507
+ const int v_row_idx = k_start + row;
1508
+ if (v_row_idx < n_kv) {
1509
+ const ulong v_row_off = batch_idx * v_nb3 + head_kv_idx * v_nb2 + v_row_idx * v_nb1;
1510
+ const global char * blk_ptr = v_base + v_row_off + blk * Q8_0_BLOCK_SIZE;
1511
+ const float df = (float) vload_half(0, (const global half *) blk_ptr);
1512
+ const global uchar * qs = (const global uchar *)(blk_ptr + 2);
1513
+ l_v_scale[row][blk] = df;
1514
+ #pragma unroll
1515
+ for (int j = 0; j < 8; ++j) {
1516
+ uint v_packed =
1517
+ (uint) qs[j*4 + 0] |
1518
+ ((uint) qs[j*4 + 1]) << 8 |
1519
+ ((uint) qs[j*4 + 2]) << 16 |
1520
+ ((uint) qs[j*4 + 3]) << 24;
1521
+ l_v_packed[row][blk * 8 + j] = v_packed;
1522
+ }
1523
+ } else {
1524
+ l_v_scale[row][blk] = 0.0f;
1525
+ #pragma unroll
1526
+ for (int j = 0; j < 8; ++j) l_v_packed[row][blk * 8 + j] = 0u;
1527
+ }
1528
+ }
1529
+ }
1530
+ #else
1531
+ {
1532
+ // Default: dequant V -> half in local memory.
1533
+ const int v_blocks_per_row = DV / QK8_0;
1534
+ const int n_blocks_total = BLOCK_N * v_blocks_per_row;
1535
+ for (int i = tid; i < n_blocks_total; i += WG_SIZE) {
1536
+ const int row = i / v_blocks_per_row;
1537
+ const int blk = i % v_blocks_per_row;
1538
+ const int v_row_idx = k_start + row;
1539
+ if (v_row_idx < n_kv) {
1540
+ const ulong v_row_off = batch_idx * v_nb3 + head_kv_idx * v_nb2 + v_row_idx * v_nb1;
1541
+ const global char * blk_ptr = v_base + v_row_off + blk * Q8_0_BLOCK_SIZE;
1542
+ const float df = (float) vload_half(0, (const global half *) blk_ptr);
1543
+ const global char * qs = blk_ptr + 2;
1544
+ #pragma unroll
1545
+ for (int j = 0; j < 8; ++j) {
1546
+ const float4 v = df * (float4)((float) qs[j*4 + 0],
1547
+ (float) qs[j*4 + 1],
1548
+ (float) qs[j*4 + 2],
1549
+ (float) qs[j*4 + 3]);
1550
+ l_v[row][blk * 8 + j] = (half4)((half) v.s0, (half) v.s1, (half) v.s2, (half) v.s3);
1551
+ }
1552
+ } else {
1553
+ #pragma unroll
1554
+ for (int j = 0; j < 8; ++j) l_v[row][blk * 8 + j] = (half4)(0.0h);
1555
+ }
1556
+ }
1557
+ }
1558
+ #endif
1559
+ barrier(CLK_LOCAL_MEM_FENCE);
1560
+
1561
+ // QK dot + online softmax. N_SPLIT>1 reduces per-thread partials via shuffle_xor.
1562
+ #if N_SPLIT > 1
1563
+ {
1564
+ #else
1565
+ if (query_valid) {
1566
+ #endif
1567
+ const int k_blk_base = split_idx * SPLIT_DK_Q8_BLOCKS;
1568
+ for (int j = 0; j < BLOCK_N; j += 4) {
1569
+ const int k_row0 = k_start + j;
1570
+ const int k_row1 = k_start + j + 1;
1571
+ const int k_row2 = k_start + j + 2;
1572
+ const int k_row3 = k_start + j + 3;
1573
+
1574
+ ACC_TYPE s0, s1, s2, s3;
1575
+ #ifdef FA_HAVE_INT_DOT
1576
+ // dp4a-accelerated QK dot over owned blocks.
1577
+ s0 = 0.0f; s1 = 0.0f; s2 = 0.0f; s3 = 0.0f;
1578
+ #pragma unroll
1579
+ for (int b_local = 0; b_local < SPLIT_DK_Q8_BLOCKS; ++b_local) {
1580
+ const int b = k_blk_base + b_local;
1581
+ int sum0 = 0, sum1 = 0, sum2 = 0, sum3 = 0;
1582
+ #if defined(FA_K_LDS_T)
1583
+ // The 4 KV rows are adjacent in the transposed tile, so each (b, g)
1584
+ // step is ONE 128-bit local read instead of four 32-bit ones.
1585
+ #pragma unroll
1586
+ for (int g = 0; g < 8; ++g) {
1587
+ const uint qp = q_packed_pf[b_local * 8 + g];
1588
+ const uint4 kq4 = vload4(0, &l_k_packed[b * 8 + g][j]);
1589
+ sum0 = dot_acc_sat_4x8packed_ss_int(qp, kq4.s0, sum0);
1590
+ sum1 = dot_acc_sat_4x8packed_ss_int(qp, kq4.s1, sum1);
1591
+ sum2 = dot_acc_sat_4x8packed_ss_int(qp, kq4.s2, sum2);
1592
+ sum3 = dot_acc_sat_4x8packed_ss_int(qp, kq4.s3, sum3);
1593
+ }
1594
+ #else
1595
+ #pragma unroll
1596
+ for (int g = 0; g < 8; ++g) {
1597
+ const uint qp = q_packed_pf[b_local * 8 + g];
1598
+ sum0 = dot_acc_sat_4x8packed_ss_int(qp, l_k_packed[j ][b * 8 + g], sum0);
1599
+ sum1 = dot_acc_sat_4x8packed_ss_int(qp, l_k_packed[j+1][b * 8 + g], sum1);
1600
+ sum2 = dot_acc_sat_4x8packed_ss_int(qp, l_k_packed[j+2][b * 8 + g], sum2);
1601
+ sum3 = dot_acc_sat_4x8packed_ss_int(qp, l_k_packed[j+3][b * 8 + g], sum3);
1602
+ }
1603
+ #endif
1604
+ const float qd = q_d_pf[b_local];
1605
+ #ifdef FA_K_LDS_T
1606
+ const float4 ks4 = vload4(0, &l_k_scale[b][j]);
1607
+ s0 += (float)sum0 * qd * ks4.s0;
1608
+ s1 += (float)sum1 * qd * ks4.s1;
1609
+ s2 += (float)sum2 * qd * ks4.s2;
1610
+ s3 += (float)sum3 * qd * ks4.s3;
1611
+ #else
1612
+ s0 += (float)sum0 * qd * l_k_scale[j ][b];
1613
+ s1 += (float)sum1 * qd * l_k_scale[j+1][b];
1614
+ s2 += (float)sum2 * qd * l_k_scale[j+2][b];
1615
+ s3 += (float)sum3 * qd * l_k_scale[j+3][b];
1616
+ #endif
1617
+ }
1618
+ #else
1619
+ ACC_TYPE4 dot_acc0 = (ACC_TYPE4)(0.0f);
1620
+ ACC_TYPE4 dot_acc1 = (ACC_TYPE4)(0.0f);
1621
+ ACC_TYPE4 dot_acc2 = (ACC_TYPE4)(0.0f);
1622
+ ACC_TYPE4 dot_acc3 = (ACC_TYPE4)(0.0f);
1623
+ #pragma unroll
1624
+ for (int k = 0; k < SPLIT_DK_VEC; ++k) {
1625
+ const ACC_TYPE4 qk = q_priv[k];
1626
+ const int k_abs = dk_off_vec + k;
1627
+ dot_acc0 = mad(qk, CONVERT_KV_ACC4(l_k[j ][k_abs]), dot_acc0);
1628
+ dot_acc1 = mad(qk, CONVERT_KV_ACC4(l_k[j+1][k_abs]), dot_acc1);
1629
+ dot_acc2 = mad(qk, CONVERT_KV_ACC4(l_k[j+2][k_abs]), dot_acc2);
1630
+ dot_acc3 = mad(qk, CONVERT_KV_ACC4(l_k[j+3][k_abs]), dot_acc3);
1631
+ }
1632
+ s0 = dot_acc0.s0 + dot_acc0.s1 + dot_acc0.s2 + dot_acc0.s3;
1633
+ s1 = dot_acc1.s0 + dot_acc1.s1 + dot_acc1.s2 + dot_acc1.s3;
1634
+ s2 = dot_acc2.s0 + dot_acc2.s1 + dot_acc2.s2 + dot_acc2.s3;
1635
+ s3 = dot_acc3.s0 + dot_acc3.s1 + dot_acc3.s2 + dot_acc3.s3;
1636
+ #endif
1637
+
1638
+ #if N_SPLIT > 1
1639
+ // Power-of-2 N_SPLIT: shuffle_xor butterfly. N_SPLIT=3 (DK=96): 3-way shuffle.
1640
+ #if (N_SPLIT & (N_SPLIT - 1)) == 0
1641
+ #pragma unroll
1642
+ for (int step = 1; step < N_SPLIT; step <<= 1) {
1643
+ s0 += sub_group_shuffle_xor(s0, step);
1644
+ s1 += sub_group_shuffle_xor(s1, step);
1645
+ s2 += sub_group_shuffle_xor(s2, step);
1646
+ s3 += sub_group_shuffle_xor(s3, step);
1647
+ }
1648
+ #else
1649
+ const uint tri_base = (get_sub_group_local_id() / N_SPLIT) * N_SPLIT;
1650
+ s0 = sub_group_shuffle(s0, tri_base + 0) + sub_group_shuffle(s0, tri_base + 1) + sub_group_shuffle(s0, tri_base + 2);
1651
+ s1 = sub_group_shuffle(s1, tri_base + 0) + sub_group_shuffle(s1, tri_base + 1) + sub_group_shuffle(s1, tri_base + 2);
1652
+ s2 = sub_group_shuffle(s2, tri_base + 0) + sub_group_shuffle(s2, tri_base + 1) + sub_group_shuffle(s2, tri_base + 2);
1653
+ s3 = sub_group_shuffle(s3, tri_base + 0) + sub_group_shuffle(s3, tri_base + 1) + sub_group_shuffle(s3, tri_base + 2);
1654
+ #endif
1655
+ if (!query_valid) { s0 = FA_M_INIT; s1 = FA_M_INIT; s2 = FA_M_INIT; s3 = FA_M_INIT; }
1656
+ #endif
1657
+ s0 *= scale; s1 *= scale; s2 *= scale; s3 *= scale;
1658
+
1659
+ if (is_causal) {
1660
+ const int causal_limit = n_kv - n_q + my_query_row;
1661
+ if (k_row0 > causal_limit) s0 = FA_M_INIT;
1662
+ if (k_row1 > causal_limit) s1 = FA_M_INIT;
1663
+ if (k_row2 > causal_limit) s2 = FA_M_INIT;
1664
+ if (k_row3 > causal_limit) s3 = FA_M_INIT;
1665
+ }
1666
+ if (k_row0 >= n_kv) s0 = FA_M_INIT;
1667
+ if (k_row1 >= n_kv) s1 = FA_M_INIT;
1668
+ if (k_row2 >= n_kv) s2 = FA_M_INIT;
1669
+ if (k_row3 >= n_kv) s3 = FA_M_INIT;
1670
+
1671
+ if (query_valid && mask_base != NULL && blk_cur != 2) {
1672
+ const global MASK_DATA_TYPE * mask_ptr =
1673
+ (const global MASK_DATA_TYPE *) (mask_base + my_query_row * mask_nb1);
1674
+ if (k_row0 < n_kv) s0 += slope * (ACC_TYPE) mask_ptr[k_row0];
1675
+ if (k_row1 < n_kv) s1 += slope * (ACC_TYPE) mask_ptr[k_row1];
1676
+ if (k_row2 < n_kv) s2 += slope * (ACC_TYPE) mask_ptr[k_row2];
1677
+ if (k_row3 < n_kv) s3 += slope * (ACC_TYPE) mask_ptr[k_row3];
1678
+ }
1679
+ if (logit_softcap > 0.0f) {
1680
+ s0 = logit_softcap * tanh(s0 / logit_softcap);
1681
+ s1 = logit_softcap * tanh(s1 / logit_softcap);
1682
+ s2 = logit_softcap * tanh(s2 / logit_softcap);
1683
+ s3 = logit_softcap * tanh(s3 / logit_softcap);
1684
+ }
1685
+
1686
+ const ACC_TYPE m_new = max(m_i, max(max(s0, s1), max(s2, s3)));
1687
+ // Whole tile masked (m_new == FA_M_INIT): force the exp() args
1688
+ // far negative so the tile contributes 0, not exp(0)=1.
1689
+ const ACC_TYPE m_exp = (m_new == FA_M_INIT) ? 0.0f : m_new;
1690
+ const ACC_TYPE scale_prev = native_exp(m_i - m_exp);
1691
+ const ACC_TYPE p0 = native_exp(s0 - m_exp);
1692
+ const ACC_TYPE p1 = native_exp(s1 - m_exp);
1693
+ const ACC_TYPE p2 = native_exp(s2 - m_exp);
1694
+ const ACC_TYPE p3 = native_exp(s3 - m_exp);
1695
+
1696
+ #if FA_V_STRATEGY == 2
1697
+ #pragma unroll
1698
+ for (int b_local = 0; b_local < DV_Q8_BLOCKS_PREFILL / N_SPLIT; ++b_local) {
1699
+ const int b_abs = split_idx * (DV_Q8_BLOCKS_PREFILL / N_SPLIT) + b_local;
1700
+ const float d0 = l_v_scale[j ][b_abs];
1701
+ const float d1 = l_v_scale[j+1][b_abs];
1702
+ const float d2 = l_v_scale[j+2][b_abs];
1703
+ const float d3 = l_v_scale[j+3][b_abs];
1704
+ #pragma unroll
1705
+ for (int g = 0; g < 8; ++g) {
1706
+ const int lane_abs = b_abs * 8 + g;
1707
+ const int lane_local = b_local * 8 + g;
1708
+ uint pk0 = l_v_packed[j ][lane_abs];
1709
+ uint pk1 = l_v_packed[j+1][lane_abs];
1710
+ uint pk2 = l_v_packed[j+2][lane_abs];
1711
+ uint pk3 = l_v_packed[j+3][lane_abs];
1712
+ float4 v0 = d0 * (float4)((float)(char)(pk0 & 0xff), (float)(char)((pk0>>8)&0xff), (float)(char)((pk0>>16)&0xff), (float)(char)((pk0>>24)&0xff));
1713
+ float4 v1 = d1 * (float4)((float)(char)(pk1 & 0xff), (float)(char)((pk1>>8)&0xff), (float)(char)((pk1>>16)&0xff), (float)(char)((pk1>>24)&0xff));
1714
+ float4 v2 = d2 * (float4)((float)(char)(pk2 & 0xff), (float)(char)((pk2>>8)&0xff), (float)(char)((pk2>>16)&0xff), (float)(char)((pk2>>24)&0xff));
1715
+ float4 v3 = d3 * (float4)((float)(char)(pk3 & 0xff), (float)(char)((pk3>>8)&0xff), (float)(char)((pk3>>16)&0xff), (float)(char)((pk3>>24)&0xff));
1716
+ o_acc[lane_local] = mad(p3, v3,
1717
+ mad(p2, v2,
1718
+ mad(p1, v1,
1719
+ mad(p0, v0,
1720
+ o_acc[lane_local] * scale_prev))));
1721
+ }
1722
+ }
1723
+ #else // FA_V_STRATEGY == 0
1724
+ #pragma unroll
1725
+ for (int i = 0; i < SPLIT_DV_VEC; ++i) {
1726
+ const int i_abs = dv_off_vec + i;
1727
+ o_acc[i] = mad(p3, CONVERT_KV_ACC4(l_v[j+3][i_abs]),
1728
+ mad(p2, CONVERT_KV_ACC4(l_v[j+2][i_abs]),
1729
+ mad(p1, CONVERT_KV_ACC4(l_v[j+1][i_abs]),
1730
+ mad(p0, CONVERT_KV_ACC4(l_v[j ][i_abs]),
1731
+ o_acc[i] * scale_prev))));
1732
+ }
1733
+ #endif
1734
+ l_i = l_i * scale_prev + p0 + p1 + p2 + p3;
1735
+ m_i = m_new;
1736
+ }
1737
+ }
1738
+ barrier(CLK_LOCAL_MEM_FENCE);
1739
+ }
1740
+
1741
+ // Write output. With N_SPLIT>1 each thread writes its SPLIT_DV_VEC slice.
1742
+ if (query_valid) {
1743
+ if (sinks_void != NULL) {
1744
+ const global ACC_TYPE * sinks_ptr =
1745
+ (const global ACC_TYPE *) ((const global char *) sinks_void + sinks_offset);
1746
+ const ACC_TYPE m_sink = sinks_ptr[head_idx];
1747
+ const ACC_TYPE m_final = max(m_i, m_sink);
1748
+ const ACC_TYPE scale_o = exp(m_i - m_final);
1749
+ #pragma unroll
1750
+ for (int i = 0; i < SPLIT_DV_VEC; ++i) o_acc[i] *= scale_o;
1751
+ l_i = l_i * scale_o + exp(m_sink - m_final);
1752
+ m_i = m_final;
1753
+ }
1754
+ const ACC_TYPE l_inv = (l_i > 0.0f) ? (1.0f / l_i) : 0.0f;
1755
+ const ulong o_row_offset = batch_idx * o_nb3 + my_query_row * o_nb2 + head_idx * o_nb1;
1756
+ global float4 * o_row = (global float4 *) (o_base + o_row_offset);
1757
+ if (l_inv > 0.0f) {
1758
+ #pragma unroll
1759
+ for (int i = 0; i < SPLIT_DV_VEC; ++i) o_row[dv_off_vec + i] = o_acc[i] * l_inv;
1760
+ } else {
1761
+ #pragma unroll
1762
+ for (int i = 0; i < SPLIT_DV_VEC; ++i) o_row[dv_off_vec + i] = (float4)(0.0f);
1763
+ }
1764
+ }
1765
+ }
1766
+
1767
+ // FD Pass 2: merge split partials. Identical across q4_0/q8_0/f16; each FA
1768
+ // source owns a copy since kernels compile per-source-program.
1769
+ __kernel void flash_attn_f32_merge(
1770
+ const global float * partial_void,
1771
+ global void * o_void,
1772
+ const ulong o_offset,
1773
+ const int n_head,
1774
+ const int n_splits,
1775
+ const ulong o_nb1, const ulong o_nb2, const ulong o_nb3,
1776
+ const global void * sinks_void,
1777
+ const ulong sinks_offset,
1778
+ const int n_q
1779
+ ) {
1780
+ const int lane = get_local_id(0);
1781
+ const int head_batch_idx = get_global_id(1);
1782
+ const int q_idx = get_global_id(2);
1783
+ const int batch_idx = head_batch_idx / n_head;
1784
+ const int head_idx = head_batch_idx % n_head;
1785
+
1786
+ const ulong record_stride = (ulong) FA_PARTIAL_FLOATS;
1787
+ const ulong record_idx_0 = (((ulong) batch_idx * n_head + head_idx) * n_q + q_idx) * n_splits;
1788
+ const global float * rec0 = partial_void + record_idx_0 * record_stride;
1789
+
1790
+ __local ACC_TYPE m_final_shared;
1791
+ __local ACC_TYPE l_final_shared;
1792
+ if (lane == 0) {
1793
+ ACC_TYPE m = FA_M_INIT;
1794
+ for (int c = 0; c < n_splits; ++c) {
1795
+ const ACC_TYPE m_c = rec0[c * record_stride + 0];
1796
+ m = max(m, m_c);
1797
+ }
1798
+ ACC_TYPE m_sink = 0.0f;
1799
+ bool has_sink = false;
1800
+ if (sinks_void != NULL) {
1801
+ const global ACC_TYPE * sinks_ptr =
1802
+ (const global ACC_TYPE *) ((const global char *) sinks_void + sinks_offset);
1803
+ m_sink = sinks_ptr[head_idx];
1804
+ has_sink = true;
1805
+ m = max(m, m_sink);
1806
+ }
1807
+ ACC_TYPE l = 0.0f;
1808
+ for (int c = 0; c < n_splits; ++c) {
1809
+ const ACC_TYPE m_c = rec0[c * record_stride + 0];
1810
+ const ACC_TYPE l_c = rec0[c * record_stride + 1];
1811
+ if (m_c > FA_M_INIT) {
1812
+ l += l_c * exp(m_c - m);
1813
+ }
1814
+ }
1815
+ if (has_sink) {
1816
+ l += exp(m_sink - m);
1817
+ }
1818
+ m_final_shared = m;
1819
+ l_final_shared = l;
1820
+ }
1821
+ barrier(CLK_LOCAL_MEM_FENCE);
1822
+ const ACC_TYPE m_final = m_final_shared;
1823
+ const ACC_TYPE l_final = l_final_shared;
1824
+ const ACC_TYPE l_inv = (l_final > 0.0f) ? (1.0f / l_final) : 0.0f;
1825
+
1826
+ ACC_TYPE4 o = (ACC_TYPE4)(0.0f);
1827
+ for (int c = 0; c < n_splits; ++c) {
1828
+ const global float * rec_c = rec0 + c * record_stride;
1829
+ const ACC_TYPE m_c = rec_c[0];
1830
+ if (m_c <= FA_M_INIT) continue;
1831
+ const global float4 * rec_oc = (const global float4 *) (rec_c + 2);
1832
+ const ACC_TYPE scale_c = exp(m_c - m_final);
1833
+ o = mad((ACC_TYPE4)(scale_c), rec_oc[lane], o);
1834
+ }
1835
+ o = o * l_inv;
1836
+
1837
+ const ulong o_row_offset = (ulong) batch_idx * o_nb3 + (ulong) q_idx * o_nb2 + (ulong) head_idx * o_nb1;
1838
+ global O_DATA_TYPE4 * o_row = (global O_DATA_TYPE4 *) ((global char *) o_void + o_offset + o_row_offset);
1839
+ o_row[lane] = CONVERT_O_DATA4(o);
1840
+ }
ggml/src/ggml-opencl/kernels/flash_attn_pre_f16.cl ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+
3
+ __kernel void flash_attn_kv_pad_f16(
4
+ const global void * k_void, ulong k_offset,
5
+ const global void * v_void, ulong v_offset,
6
+ global void * k_pad_void,
7
+ global void * v_pad_void,
8
+ const int n_kv,
9
+ const int n_head_kv,
10
+ const int n_batch,
11
+ const ulong k_nb1, const ulong k_nb2, const ulong k_nb3,
12
+ const ulong v_nb1, const ulong v_nb2, const ulong v_nb3
13
+ ) {
14
+ const int row_idx = get_global_id(0);
15
+ const int head_kv_idx = get_global_id(1);
16
+ const int batch_idx = get_global_id(2);
17
+
18
+ if (row_idx >= BLOCK_N || head_kv_idx >= n_head_kv || batch_idx >= n_batch) {
19
+ return;
20
+ }
21
+
22
+ const int tail_start = n_kv - (n_kv % BLOCK_N);
23
+ const int src_row_idx = tail_start + row_idx;
24
+
25
+ const global char * k_src = (const global char *) k_void + k_offset;
26
+ const global char * v_src = (const global char *) v_void + v_offset;
27
+ global char * k_pad = (global char *) k_pad_void;
28
+ global char * v_pad = (global char *) v_pad_void;
29
+
30
+ const ulong k_dst_offset = ((ulong) batch_idx * (ulong) n_head_kv + (ulong) head_kv_idx) * ((ulong) BLOCK_N * k_nb1) + (ulong) row_idx * k_nb1;
31
+ const ulong v_dst_offset = ((ulong) batch_idx * (ulong) n_head_kv + (ulong) head_kv_idx) * ((ulong) BLOCK_N * v_nb1) + (ulong) row_idx * v_nb1;
32
+
33
+ if (src_row_idx < n_kv) {
34
+ const ulong k_src_offset = (ulong) batch_idx * k_nb3 + (ulong) head_kv_idx * k_nb2 + (ulong) src_row_idx * k_nb1;
35
+ const ulong v_src_offset = (ulong) batch_idx * v_nb3 + (ulong) head_kv_idx * v_nb2 + (ulong) src_row_idx * v_nb1;
36
+
37
+ for (ulong i = 0; i < k_nb1; ++i) {
38
+ k_pad[k_dst_offset + i] = k_src[k_src_offset + i];
39
+ }
40
+ for (ulong i = 0; i < v_nb1; ++i) {
41
+ v_pad[v_dst_offset + i] = v_src[v_src_offset + i];
42
+ }
43
+ } else {
44
+ for (ulong i = 0; i < k_nb1; ++i) {
45
+ k_pad[k_dst_offset + i] = 0;
46
+ }
47
+ for (ulong i = 0; i < v_nb1; ++i) {
48
+ v_pad[v_dst_offset + i] = 0;
49
+ }
50
+ }
51
+ }
52
+
53
+ __kernel void flash_attn_mask_pad_f16(
54
+ const global void * mask_void, ulong mask_offset,
55
+ global void * mask_pad_void,
56
+ const int n_q,
57
+ const int n_kv,
58
+ const ulong mask_nb1,
59
+ const ulong mask_nb2,
60
+ const ulong mask_nb3,
61
+ const int mask_ne2,
62
+ const int mask_ne3
63
+ ) {
64
+ const int col_idx = get_global_id(0);
65
+ const int q_row = get_global_id(1);
66
+ const int mask_slice = get_global_id(2);
67
+
68
+ if (col_idx >= BLOCK_N || q_row >= n_q || mask_slice >= mask_ne2 * mask_ne3) {
69
+ return;
70
+ }
71
+
72
+ const int tail_start = n_kv - (n_kv % BLOCK_N);
73
+ const int src_col_idx = tail_start + col_idx;
74
+ const int mask_head_idx = mask_slice % mask_ne2;
75
+ const int mask_batch_idx = mask_slice / mask_ne2;
76
+
77
+ const global char * mask_src_base = (const global char *) mask_void + mask_offset +
78
+ (ulong) mask_batch_idx * mask_nb3 +
79
+ (ulong) mask_head_idx * mask_nb2 +
80
+ (ulong) q_row * mask_nb1;
81
+ const global half * mask_src = (const global half *) mask_src_base;
82
+
83
+ global half * mask_pad = (global half *) mask_pad_void;
84
+ const ulong dst_idx =
85
+ (((ulong) mask_batch_idx * (ulong) mask_ne2 + (ulong) mask_head_idx) * (ulong) n_q + (ulong) q_row) * (ulong) BLOCK_N +
86
+ (ulong) col_idx;
87
+
88
+ mask_pad[dst_idx] = src_col_idx < n_kv ? mask_src[src_col_idx] : (half) (-INFINITY);
89
+ }
90
+
91
+ // Per-KV-tile mask class. 0=all -inf (skip tile), 1=mixed (apply mask),
92
+ // 2=all zero, no -inf (skip mask lookup). Causal diagonal tiles are class 1.
93
+ __kernel void flash_attn_blk_f16(
94
+ const global void * mask_void, ulong mask_offset,
95
+ global char * blk,
96
+ const int n_q,
97
+ const int n_kv,
98
+ const ulong mask_nb1,
99
+ const ulong mask_nb2,
100
+ const ulong mask_nb3,
101
+ const int mask_ne2,
102
+ const int mask_ne3
103
+ ) {
104
+ const int kv_block_idx = get_global_id(0);
105
+ const int q_block_idx = get_global_id(1);
106
+ const int mask_slice = get_global_id(2);
107
+
108
+ const int n_q_blocks = (n_q + BLOCK_M - 1) / BLOCK_M;
109
+ const int n_kv_blocks = (n_kv + BLOCK_N - 1) / BLOCK_N;
110
+ if (kv_block_idx >= n_kv_blocks || q_block_idx >= n_q_blocks || mask_slice >= mask_ne2 * mask_ne3) {
111
+ return;
112
+ }
113
+
114
+ const int mask_head_idx = mask_slice % mask_ne2;
115
+ const int mask_batch_idx = mask_slice / mask_ne2;
116
+ const int q_start = q_block_idx * BLOCK_M;
117
+ const int k_start = kv_block_idx * BLOCK_N;
118
+ const int q_count = min(BLOCK_M, n_q - q_start);
119
+ const int k_count = min(BLOCK_N, n_kv - k_start);
120
+
121
+ const half neg_max_half = (half) (-65504.0f);
122
+ char has_unmasked = 0;
123
+ char has_masked = 0;
124
+ char has_nonzero = 0;
125
+
126
+ const global char * mask_base = (const global char *) mask_void + mask_offset +
127
+ (ulong) mask_batch_idx * mask_nb3 +
128
+ (ulong) mask_head_idx * mask_nb2;
129
+
130
+ for (int qi = 0; qi < q_count; ++qi) {
131
+ const global half * mask_row = (const global half *) (mask_base + (ulong) (q_start + qi) * mask_nb1) + k_start;
132
+ for (int ki = 0; ki < k_count; ++ki) {
133
+ const half v = mask_row[ki];
134
+ if (v <= neg_max_half) {
135
+ has_masked = 1;
136
+ } else {
137
+ has_unmasked = 1;
138
+ if (v != (half) 0.0f) {
139
+ has_nonzero = 1;
140
+ }
141
+ }
142
+ }
143
+ if (has_masked && has_unmasked) break; // mixed tile — short-circuit.
144
+ }
145
+
146
+ char res;
147
+ if (has_unmasked == 0) {
148
+ res = 0;
149
+ } else if (has_masked || has_nonzero) {
150
+ res = 1;
151
+ } else {
152
+ res = 2;
153
+ }
154
+
155
+ blk[((ulong) mask_slice * (ulong) n_q_blocks + (ulong) q_block_idx) * (ulong) n_kv_blocks + (ulong) kv_block_idx] = res;
156
+ }
ggml/src/ggml-opencl/kernels/gated_delta_net.cl ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_subgroups : enable
2
+
3
+ #ifdef cl_intel_required_subgroup_size
4
+ #pragma OPENCL EXTENSION cl_intel_required_subgroup_size : enable
5
+ #define INTEL_GPU 1
6
+ #define REQD_SUBGROUP_SIZE_16 __attribute__((intel_reqd_sub_group_size(16)))
7
+ #define REQD_SUBGROUP_SIZE_32 __attribute__((intel_reqd_sub_group_size(32)))
8
+ #elif defined(cl_qcom_reqd_sub_group_size)
9
+ #pragma OPENCL EXTENSION cl_qcom_reqd_sub_group_size : enable
10
+ #define ADRENO_GPU 1
11
+ #define REQD_SUBGROUP_SIZE_64 __attribute__((qcom_reqd_sub_group_size("half")))
12
+ #define REQD_SUBGROUP_SIZE_128 __attribute__((qcom_reqd_sub_group_size("full")))
13
+ #endif
14
+
15
+ #ifndef S_V
16
+ #define S_V 128
17
+ #endif
18
+ #ifndef KDA
19
+ #define KDA 0
20
+ #endif
21
+ #ifndef SUBGROUP_SIZE
22
+ #define SUBGROUP_SIZE 64
23
+ #endif
24
+ #ifndef LANES_PER_COLUMN
25
+ #define LANES_PER_COLUMN 8
26
+ #endif
27
+ #ifndef COLS_PER_LANE_GROUP
28
+ #define COLS_PER_LANE_GROUP 1
29
+ #endif
30
+ #ifndef SUBGROUPS_PER_WG
31
+ #define SUBGROUPS_PER_WG 1
32
+ #endif
33
+ #ifndef USE_QCOM_SUBGROUP_SHUFFLE
34
+ #define USE_QCOM_SUBGROUP_SHUFFLE 0
35
+ #endif
36
+
37
+ #define WG_SIZE (SUBGROUP_SIZE * SUBGROUPS_PER_WG)
38
+ #define LANE_GROUPS_PER_SG (SUBGROUP_SIZE / LANES_PER_COLUMN)
39
+ #define COLS_PER_SG (LANE_GROUPS_PER_SG * COLS_PER_LANE_GROUP)
40
+ #define COLS_PER_WG (SUBGROUPS_PER_WG * COLS_PER_SG)
41
+ #define ROWS_PER_LANE (S_V / LANES_PER_COLUMN)
42
+
43
+ #if USE_QCOM_SUBGROUP_SHUFFLE
44
+ #pragma OPENCL EXTENSION cl_qcom_subgroup_shuffle : enable
45
+ #endif
46
+
47
+ // XOR-based parallel sum
48
+ // This does a reduction across groups of LANES_PER_COLUMN
49
+ static inline float reduce_add_shmem(float partial, __local float * temp, uint lane) {
50
+ #if USE_QCOM_SUBGROUP_SHUFFLE
51
+ #pragma unroll
52
+ for (uint s = LANES_PER_COLUMN / 2u; s > 0u; s >>= 1u) {
53
+ partial += qcom_sub_group_shuffle_xor(partial, s, CLK_SUB_GROUP_SHUFFLE_WIDTH_WAVE_SIZE_QCOM, partial);
54
+ }
55
+ return partial;
56
+ #else
57
+ temp[lane] = partial;
58
+ sub_group_barrier(CLK_LOCAL_MEM_FENCE);
59
+ #pragma unroll
60
+ for (uint s = LANES_PER_COLUMN / 2u; s > 0u; s >>= 1u) {
61
+ float other = temp[lane ^ s];
62
+ sub_group_barrier(CLK_LOCAL_MEM_FENCE);
63
+ temp[lane] += other;
64
+ sub_group_barrier(CLK_LOCAL_MEM_FENCE);
65
+ }
66
+ const float result = temp[lane];
67
+ sub_group_barrier(CLK_LOCAL_MEM_FENCE);
68
+ return result;
69
+ #endif
70
+ }
71
+
72
+ #define REDUCE_PARTIAL(partial, temp_ptr, lid) \
73
+ ((LANES_PER_COLUMN == 1u) ? (partial) : reduce_add_shmem((partial), (temp_ptr), (lid)))
74
+
75
+ // force compiler to optimize kernel for a specific fixed work-group size
76
+ __attribute__((reqd_work_group_size(WG_SIZE, 1, 1)))
77
+ #ifdef INTEL_GPU
78
+ REQD_SUBGROUP_SIZE_32
79
+ #elif defined (ADRENO_GPU)
80
+ REQD_SUBGROUP_SIZE_64
81
+ #endif
82
+ kernel void kernel_gated_delta_net(
83
+ global const char * q_buf, ulong off_q,
84
+ global const char * k_buf, ulong off_k,
85
+ global const char * v_buf, ulong off_v,
86
+ global const char * g_buf, ulong off_g,
87
+ global const char * beta_buf, ulong off_beta,
88
+ global const char * state_buf, ulong off_state,
89
+ global char * dst_buf, ulong off_dst,
90
+ uint H_v,
91
+ uint n_tokens,
92
+ uint n_seqs,
93
+ uint s_off,
94
+ uint sq1, uint sq2, uint sq3,
95
+ uint sv1, uint sv2, uint sv3,
96
+ uint sb1, uint sb2, uint sb3,
97
+ uint H_k,
98
+ uint rq3,
99
+ float scale,
100
+ uint K) {
101
+
102
+ global const float * data_q = (global const float *)(q_buf + off_q);
103
+ global const float * data_k = (global const float *)(k_buf + off_k);
104
+ global const float * data_v = (global const float *)(v_buf + off_v);
105
+ global const float * data_g = (global const float *)(g_buf + off_g);
106
+ global const float * data_beta = (global const float *)(beta_buf + off_beta);
107
+ global const float * data_state = (global const float *)(state_buf + off_state);
108
+ global float * data_dst = (global float *)(dst_buf + off_dst);
109
+
110
+ const uint head_id = get_group_id(0);
111
+ const uint seq_id = get_group_id(1);
112
+ const uint tid = (uint)get_local_id(0);
113
+
114
+ const uint sg_id = get_sub_group_id(); // subgroup id
115
+ const uint sg_lid = get_sub_group_local_id(); // subgroup lane id
116
+
117
+ const uint lane = sg_lid % LANES_PER_COLUMN;
118
+ const uint lane_group = sg_lid / LANES_PER_COLUMN;
119
+ const uint wg_col_base = get_group_id(2) * COLS_PER_WG;
120
+ const uint sg_col_base = wg_col_base + sg_id * COLS_PER_SG;
121
+
122
+ const uint iq1 = head_id % H_k; // head index for Q and K
123
+ const uint iq3 = seq_id / rq3; // seq index for Q and K
124
+
125
+ const uint state_size = S_V * S_V;
126
+ // input state holds s0 only [S_v, S_v, H, n_seqs]: per-seq stride is H*D.
127
+ const uint state_base = (seq_id * H_v + head_id) * state_size;
128
+ const uint q_off_base = iq3 * sq3 + iq1 * sq1;
129
+ const uint v_off_base = seq_id * sv3 + head_id * sv1;
130
+ const uint gb_off_base = seq_id * sb3 + head_id * sb1;
131
+ const uint state_out_base = (seq_id * H_v + head_id) * state_size;
132
+ const uint state_size_per_snap = state_size * H_v * n_seqs;
133
+
134
+ __local float reduce_temp[WG_SIZE];
135
+ __local float * temp_ptr = reduce_temp + sg_id * SUBGROUP_SIZE;
136
+
137
+ float s_shard[COLS_PER_LANE_GROUP][ROWS_PER_LANE];
138
+ #pragma unroll
139
+ for (uint cg = 0; cg < COLS_PER_LANE_GROUP; cg++) {
140
+ const uint col = sg_col_base + cg * LANE_GROUPS_PER_SG + lane_group;
141
+ #pragma unroll
142
+ for (uint r = 0; r < ROWS_PER_LANE; r++) {
143
+ s_shard[cg][r] = data_state[state_base + col * S_V + r * LANES_PER_COLUMN + lane];
144
+ }
145
+ }
146
+
147
+ // snapshot slot mapping: slot 0 = most recent state, slot s = s tokens back.
148
+ // When n_tokens < K only slots 0..n_tokens-1 are written; older slots are caller-owned.
149
+ uint attn_off = (seq_id * n_tokens * H_v + head_id) * S_V;
150
+
151
+ for (uint t = 0; t < n_tokens; t++) {
152
+ const uint q_off = q_off_base + t * sq2;
153
+ const uint k_off = q_off;
154
+ const uint v_off = v_off_base + t * sv2;
155
+ const uint gb_off = gb_off_base + t * sb2;
156
+ const float beta_val = data_beta[gb_off];
157
+
158
+ float k_reg[ROWS_PER_LANE];
159
+ float q_reg[ROWS_PER_LANE];
160
+ #if KDA
161
+ float g_exp[ROWS_PER_LANE];
162
+ #pragma unroll
163
+ for (uint r = 0; r < ROWS_PER_LANE; r++) {
164
+ const uint i = r * LANES_PER_COLUMN + lane;
165
+ k_reg[r] = data_k[k_off + i];
166
+ q_reg[r] = data_q[q_off + i];
167
+ g_exp[r] = exp(data_g[gb_off * S_V + i]);
168
+ }
169
+ #else
170
+ const float g_val = exp(data_g[gb_off]);
171
+
172
+ #pragma unroll
173
+ for (uint r = 0; r < ROWS_PER_LANE; r++) {
174
+ const uint i = r * LANES_PER_COLUMN + lane;
175
+ k_reg[r] = data_k[k_off + i];
176
+ q_reg[r] = data_q[q_off + i];
177
+ }
178
+ #endif
179
+
180
+ #pragma unroll
181
+ for (uint cg = 0; cg < COLS_PER_LANE_GROUP; cg++) {
182
+ const uint col = sg_col_base + cg * LANE_GROUPS_PER_SG + lane_group;
183
+ float v_val = data_v[v_off + col];
184
+
185
+ float kv_shard = 0.0f;
186
+ #pragma unroll
187
+ for (uint r = 0; r < ROWS_PER_LANE; r++) {
188
+ #if KDA
189
+ float gs = g_exp[r] * s_shard[cg][r];
190
+ kv_shard += gs * k_reg[r];
191
+ #else
192
+ kv_shard += s_shard[cg][r] * k_reg[r];
193
+ #endif
194
+ }
195
+
196
+ #if !KDA
197
+ kv_shard *= g_val; // Applied once instead of ROWS_PER_LANE times
198
+ #endif
199
+
200
+ const float kv_col = REDUCE_PARTIAL(kv_shard, temp_ptr, sg_lid);
201
+
202
+ const float delta_col = (v_val - kv_col) * beta_val;
203
+
204
+ float attn_partial = 0.0f;
205
+ #pragma unroll
206
+ for (uint r = 0; r < ROWS_PER_LANE; r++) {
207
+ #if KDA
208
+ float gs = g_exp[r] * s_shard[cg][r];
209
+ #else
210
+ float gs = g_val * s_shard[cg][r];
211
+ #endif
212
+ s_shard[cg][r] = gs + k_reg[r] * delta_col;
213
+ attn_partial += s_shard[cg][r] * q_reg[r];
214
+ }
215
+ const float attn_col = REDUCE_PARTIAL(attn_partial, temp_ptr, sg_lid);
216
+
217
+ if (lane == 0) {
218
+ data_dst[attn_off + col] = attn_col * scale;
219
+ }
220
+ }
221
+ attn_off += S_V * H_v;
222
+
223
+ if (K > 1u) {
224
+ const int target_slot = (int)n_tokens - 1 - (int)t;
225
+ if (target_slot >= 0 && target_slot < (int)K) {
226
+ #pragma unroll
227
+ for (uint cg = 0; cg < COLS_PER_LANE_GROUP; cg++) {
228
+ const uint col = sg_col_base + cg * LANE_GROUPS_PER_SG + lane_group;
229
+ const uint slot_base = s_off + (uint)target_slot * state_size_per_snap + state_out_base;
230
+ #pragma unroll
231
+ for (uint r = 0; r < ROWS_PER_LANE; r++) {
232
+ data_dst[slot_base + col * S_V + r * LANES_PER_COLUMN + lane] = s_shard[cg][r];
233
+ }
234
+ }
235
+ }
236
+ }
237
+ }
238
+
239
+ if (K == 1u) {
240
+ #pragma unroll
241
+ for (uint cg = 0; cg < COLS_PER_LANE_GROUP; cg++) {
242
+ const uint col = sg_col_base + cg * LANE_GROUPS_PER_SG + lane_group;
243
+ #pragma unroll
244
+ for (uint r = 0; r < ROWS_PER_LANE; r++) {
245
+ data_dst[s_off + state_base + col * S_V + r * LANES_PER_COLUMN + lane] = s_shard[cg][r];
246
+ }
247
+ }
248
+ }
249
+ }
ggml/src/ggml-opencl/kernels/gelu.cl ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+
3
+ //------------------------------------------------------------------------------
4
+ // gelu
5
+ //------------------------------------------------------------------------------
6
+ #define GELU_COEF_A 0.044715f
7
+ #define GELU_QUICK_COEF -1.702f
8
+ #define SQRT_2_OVER_PI 0.79788456080286535587989211986876f
9
+ #define SQRT_2_INV 0.70710678118654752440084436210484f
10
+
11
+ kernel void kernel_gelu(
12
+ global float * src0,
13
+ ulong offset0,
14
+ global float * dst,
15
+ ulong offsetd
16
+ ) {
17
+ src0 = (global float*)((global char*)src0 + offset0);
18
+ dst = (global float*)((global char*)dst + offsetd);
19
+
20
+ float x = src0[get_global_id(0)];
21
+
22
+ dst[get_global_id(0)] = 0.5f*x*(1.0f + tanh(SQRT_2_OVER_PI*x*(1.0f + GELU_COEF_A*x*x)));
23
+ }
24
+
25
+ kernel void kernel_gelu_4(
26
+ global float4 * src0,
27
+ ulong offset0,
28
+ global float4 * dst,
29
+ ulong offsetd
30
+ ) {
31
+ src0 = (global float4*)((global char*)src0 + offset0);
32
+ dst = (global float4*)((global char*)dst + offsetd);
33
+
34
+ float4 x = src0[get_global_id(0)];
35
+
36
+ dst[get_global_id(0)] = 0.5f*x*(1.0f + tanh(SQRT_2_OVER_PI*x*(1.0f + GELU_COEF_A*x*x)));
37
+ }
38
+
39
+ kernel void kernel_gelu_erf(
40
+ global float * src0,
41
+ ulong offset0,
42
+ global float * dst,
43
+ ulong offsetd
44
+ ) {
45
+ src0 = (global float*)((global char*)src0 + offset0);
46
+ dst = (global float*)((global char*)dst + offsetd);
47
+
48
+ float x = src0[get_global_id(0)];
49
+ dst[get_global_id(0)] = 0.5f*x*(1.0f + erf(x*SQRT_2_INV));
50
+ }
51
+
52
+ kernel void kernel_gelu_erf_4(
53
+ global float4 * src0,
54
+ ulong offset0,
55
+ global float4 * dst,
56
+ ulong offsetd
57
+ ) {
58
+ src0 = (global float4*)((global char*)src0 + offset0);
59
+ dst = (global float4*)((global char*)dst + offsetd);
60
+
61
+ float4 x = src0[get_global_id(0)];
62
+ dst[get_global_id(0)] = 0.5f*x*(1.0f + erf(x*SQRT_2_INV));
63
+ }
64
+
65
+ kernel void kernel_gelu_quick(
66
+ global float * src0,
67
+ ulong offset0,
68
+ global float * dst,
69
+ ulong offsetd
70
+ ) {
71
+ src0 = (global float*)((global char*)src0 + offset0);
72
+ dst = (global float*)((global char*)dst + offsetd);
73
+
74
+ float x = src0[get_global_id(0)];
75
+ dst[get_global_id(0)] = x*(1.0f/(1.0f+exp(GELU_QUICK_COEF*x)));
76
+ }
77
+
78
+ kernel void kernel_gelu_quick_4(
79
+ global float4 * src0,
80
+ ulong offset0,
81
+ global float4 * dst,
82
+ ulong offsetd
83
+ ) {
84
+ src0 = (global float4*)((global char*)src0 + offset0);
85
+ dst = (global float4*)((global char*)dst + offsetd);
86
+
87
+ float4 x = src0[get_global_id(0)];
88
+ dst[get_global_id(0)] = x*(1.0f/(1.0f+exp(GELU_QUICK_COEF*x)));
89
+ }
ggml/src/ggml-opencl/kernels/gemm_moe_mxfp4_f32.cl ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+ #pragma OPENCL EXTENSION cl_khr_subgroups : enable
3
+ #pragma OPENCL EXTENSION cl_qcom_reqd_sub_group_size : enable
4
+
5
+ #define QK_MXFP4 32
6
+ #define N_SIMDGROUP 2
7
+ #define SIMDGROUP_WIDTH 64
8
+
9
+ static inline half8 mxfp4_to_fp16_packed8(ushort2 fp4x8) { //, ushort 0x0E00, ushort 0x8000) {
10
+ ushort2 fp16_packed_a_0, fp16_packed_b_0, bias_a, bias_b, sign_a, sign_b;
11
+ fp16_packed_a_0.lo = (fp4x8.s0 << 9) & 0x0E00;
12
+ fp16_packed_a_0.hi = (fp4x8.s0 << 5) & 0x0E00;
13
+ fp16_packed_b_0.lo = (fp4x8.s0 << 1) & 0x0E00;
14
+ fp16_packed_b_0.hi = (fp4x8.s0 >> 3) & 0x0E00;
15
+
16
+ bias_a.lo = (fp16_packed_a_0.lo != 0) ? 0x3800 : 0x0;
17
+ bias_a.hi = (fp16_packed_a_0.hi != 0) ? 0x3800 : 0x0;
18
+ bias_b.lo = (fp16_packed_b_0.lo != 0) ? 0x3800 : 0x0;
19
+ bias_b.hi = (fp16_packed_b_0.hi != 0) ? 0x3800 : 0x0;
20
+
21
+ fp16_packed_a_0.lo = (fp16_packed_a_0.lo != 0x0200) ? fp16_packed_a_0.lo : 0x0;
22
+ fp16_packed_a_0.hi = (fp16_packed_a_0.hi != 0x0200) ? fp16_packed_a_0.hi : 0x0;
23
+ fp16_packed_b_0.lo = (fp16_packed_b_0.lo != 0x0200) ? fp16_packed_b_0.lo : 0x0;
24
+ fp16_packed_b_0.hi = (fp16_packed_b_0.hi != 0x0200) ? fp16_packed_b_0.hi : 0x0;
25
+
26
+ sign_a.lo = (fp4x8.s0 << 12) & 0x8000;
27
+ sign_a.hi = (fp4x8.s0 << 8) & 0x8000;
28
+ sign_b.lo = (fp4x8.s0 << 4) & 0x8000;
29
+ sign_b.hi = fp4x8.s0 & 0x8000;
30
+
31
+ fp16_packed_a_0 = sign_a + bias_a + fp16_packed_a_0;
32
+ fp16_packed_b_0 = sign_b + bias_b + fp16_packed_b_0;
33
+
34
+ ushort2 fp16_packed_a_1, fp16_packed_b_1;
35
+ fp16_packed_a_1.lo = (fp4x8.s1 << 9) & 0x0E00;
36
+ fp16_packed_a_1.hi = (fp4x8.s1 << 5) & 0x0E00;
37
+ fp16_packed_b_1.lo = (fp4x8.s1 << 1) & 0x0E00;
38
+ fp16_packed_b_1.hi = (fp4x8.s1 >> 3) & 0x0E00;
39
+
40
+ bias_a.lo = (fp16_packed_a_1.lo != 0) ? 0x3800 : 0x0;
41
+ bias_a.hi = (fp16_packed_a_1.hi != 0) ? 0x3800 : 0x0;
42
+ bias_b.lo = (fp16_packed_b_1.lo != 0) ? 0x3800 : 0x0;
43
+ bias_b.hi = (fp16_packed_b_1.hi != 0) ? 0x3800 : 0x0;
44
+
45
+ fp16_packed_a_1.lo = (fp16_packed_a_1.lo != 0x0200) ? fp16_packed_a_1.lo : 0x0;
46
+ fp16_packed_a_1.hi = (fp16_packed_a_1.hi != 0x0200) ? fp16_packed_a_1.hi : 0x0;
47
+ fp16_packed_b_1.lo = (fp16_packed_b_1.lo != 0x0200) ? fp16_packed_b_1.lo : 0x0;
48
+ fp16_packed_b_1.hi = (fp16_packed_b_1.hi != 0x0200) ? fp16_packed_b_1.hi : 0x0;
49
+
50
+ sign_a.lo = (fp4x8.s1 << 12) & 0x8000;
51
+ sign_a.hi = (fp4x8.s1 << 8) & 0x8000;
52
+ sign_b.lo = (fp4x8.s1 << 4) & 0x8000;
53
+ sign_b.hi = fp4x8.s1 & 0x8000;
54
+
55
+ fp16_packed_a_1 = sign_a + bias_a + fp16_packed_a_1;
56
+ fp16_packed_b_1 = sign_b + bias_b + fp16_packed_b_1;
57
+
58
+ return as_half8((ushort8)(fp16_packed_a_0, fp16_packed_b_0, fp16_packed_a_1, fp16_packed_b_1));
59
+ }
60
+
61
+ static inline float e8m0_to_fp32(uchar x) {
62
+ int bits;
63
+ bits = (x == 0) ? 0x00400000 : ((uint) x << 23);
64
+ return as_float(bits);
65
+ }
66
+
67
+
68
+ __attribute__((qcom_reqd_sub_group_size("half")))
69
+ __kernel void kernel_gemm_moe_mxfp4_f32(
70
+ __global uint4 * src0_q,
71
+ __global uchar * src0_e,
72
+ __read_only image1d_buffer_t src1,
73
+ __global ushort4 * src2,
74
+ __global float * dst,
75
+ ulong offsetd,
76
+ int ne00,
77
+ int ne01,
78
+ int tile_size
79
+ ) {
80
+ uint i01 = get_global_id(0);
81
+ uint i20 = get_global_id(2);
82
+ uint sgid = get_local_id(1);
83
+ uint slid = get_sub_group_local_id();
84
+
85
+ ushort4 router = src2[i20];
86
+ ushort expert_id = router.x;
87
+ ushort i11 = router.y;
88
+ ushort i1 = router.z;
89
+ ushort tile_id = router.w;
90
+
91
+ if (tile_id * tile_size + i01 >= ne01) { // handle edge case when ne01 is not multiple of tile_size
92
+ return;
93
+ }
94
+
95
+ uint expert_offset = expert_id * ne00 * ne01 / 32;
96
+ uint tile_offset = expert_offset + tile_id * tile_size + i01;
97
+
98
+ __private float sum = 0.0f; // each thread calculate partial sum of one output
99
+
100
+ // loop along ne00 in block granularity, skip 4 blocks every iter
101
+ for (uint ib00 = sgid; ib00 < (ne00 / QK_MXFP4); ib00 += N_SIMDGROUP) {
102
+ // load one block of q
103
+ uint4 regQ = src0_q[tile_offset + ib00 * ne01];
104
+ // convert 8 fp4 to fp16
105
+ half8 fp16x8 = mxfp4_to_fp16_packed8(as_ushort2(regQ.s0));
106
+
107
+ uint offset = i11 * ne00 / 4 + ib00 * 8;
108
+ float4 shared_y4;
109
+ shared_y4 = read_imagef(src1, (offset + 0));
110
+ float4 acc = shared_y4 * (float4)(fp16x8.s0, fp16x8.s2, fp16x8.s4, fp16x8.s6);
111
+
112
+ shared_y4 = read_imagef(src1, (offset + 4));
113
+ acc += shared_y4 * (float4)(fp16x8.s1, fp16x8.s3, fp16x8.s5, fp16x8.s7);
114
+
115
+
116
+ fp16x8 = mxfp4_to_fp16_packed8(as_ushort2(regQ.s1));
117
+
118
+ shared_y4 = read_imagef(src1, (offset + 1));
119
+ acc += shared_y4 * (float4)(fp16x8.s0, fp16x8.s2, fp16x8.s4, fp16x8.s6);
120
+
121
+ shared_y4 = read_imagef(src1, (offset + 5));
122
+ acc += shared_y4 * (float4)(fp16x8.s1, fp16x8.s3, fp16x8.s5, fp16x8.s7);
123
+
124
+
125
+ fp16x8 = mxfp4_to_fp16_packed8(as_ushort2(regQ.s2));
126
+
127
+ shared_y4 = read_imagef(src1, (offset + 2));
128
+ acc += shared_y4 * (float4)(fp16x8.s0, fp16x8.s2, fp16x8.s4, fp16x8.s6);
129
+
130
+ shared_y4 = read_imagef(src1, (offset + 6));
131
+ acc += shared_y4 * (float4)(fp16x8.s1, fp16x8.s3, fp16x8.s5, fp16x8.s7);
132
+
133
+
134
+ fp16x8 = mxfp4_to_fp16_packed8(as_ushort2(regQ.s3));
135
+
136
+ shared_y4 = read_imagef(src1, (offset + 3));
137
+ acc += shared_y4 * (float4)(fp16x8.s0, fp16x8.s2, fp16x8.s4, fp16x8.s6);
138
+
139
+ shared_y4 = read_imagef(src1, (offset + 7));
140
+ acc += shared_y4 * (float4)(fp16x8.s1, fp16x8.s3, fp16x8.s5, fp16x8.s7);
141
+
142
+ uchar regE = src0_e[tile_offset + ib00 * ne01];
143
+ sum += e8m0_to_fp32(regE) * ((acc.s0 + acc.s1) + (acc.s2 + acc.s3));
144
+ }
145
+
146
+ // reduction in local memory, assumes #subgroups=4
147
+ __local float reduceLM[SIMDGROUP_WIDTH * (N_SIMDGROUP - 1)];
148
+ if (sgid == 1) reduceLM[SIMDGROUP_WIDTH * 0 + slid] = sum;
149
+ // if (sgid == 2) reduceLM[SIMDGROUP_WIDTH * 1 + slid] = sum;
150
+ // if (sgid == 3) reduceLM[SIMDGROUP_WIDTH * 2 + slid] = sum;
151
+ barrier(CLK_LOCAL_MEM_FENCE);
152
+ if (sgid == 0) sum += reduceLM[SIMDGROUP_WIDTH * 0 + slid];
153
+ // if (sgid == 0) sum += reduceLM[SIMDGROUP_WIDTH * 1 + slid];
154
+ // if (sgid == 0) sum += reduceLM[SIMDGROUP_WIDTH * 2 + slid];
155
+
156
+ // 1 outputs per thread in subgroup 0
157
+ if (sgid == 0) {
158
+ dst = dst + (offsetd >> 2);
159
+ dst[i01 + tile_id * tile_size + i1 * ne01] = sum;
160
+ }
161
+
162
+ }
ggml/src/ggml-opencl/kernels/gemm_moe_mxfp4_f32_ns.cl ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+ #pragma OPENCL EXTENSION cl_khr_subgroups : enable
3
+ #pragma OPENCL EXTENSION cl_qcom_subgroup_uniform_load: enable
4
+ #pragma OPENCL EXTENSION cl_qcom_subgroup_constant_load: enable
5
+ #pragma OPENCL EXTENSION cl_qcom_extra_vector_types : enable
6
+
7
+ #define TILESIZE_K 16
8
+ #define TILESIZE_M 64
9
+ #define TILESIZE_N 32
10
+
11
+
12
+ static inline half8 mxfp4_to_fp16_packed8(ushort2 fp4x8) {
13
+ ushort2 fp16_packed_a_0, fp16_packed_b_0, bias_a, bias_b, sign_a, sign_b;
14
+ fp16_packed_a_0.lo = (fp4x8.s0 << 9) & 0x0E00;
15
+ fp16_packed_a_0.hi = (fp4x8.s0 << 5) & 0x0E00;
16
+ fp16_packed_b_0.lo = (fp4x8.s0 << 1) & 0x0E00;
17
+ fp16_packed_b_0.hi = (fp4x8.s0 >> 3) & 0x0E00;
18
+
19
+ bias_a.lo = (fp16_packed_a_0.lo != 0) ? 0x3800 : 0x0;
20
+ bias_a.hi = (fp16_packed_a_0.hi != 0) ? 0x3800 : 0x0;
21
+ bias_b.lo = (fp16_packed_b_0.lo != 0) ? 0x3800 : 0x0;
22
+ bias_b.hi = (fp16_packed_b_0.hi != 0) ? 0x3800 : 0x0;
23
+
24
+ fp16_packed_a_0.lo = (fp16_packed_a_0.lo != 0x0200) ? fp16_packed_a_0.lo : 0x0;
25
+ fp16_packed_a_0.hi = (fp16_packed_a_0.hi != 0x0200) ? fp16_packed_a_0.hi : 0x0;
26
+ fp16_packed_b_0.lo = (fp16_packed_b_0.lo != 0x0200) ? fp16_packed_b_0.lo : 0x0;
27
+ fp16_packed_b_0.hi = (fp16_packed_b_0.hi != 0x0200) ? fp16_packed_b_0.hi : 0x0;
28
+
29
+ sign_a.lo = (fp4x8.s0 << 12) & 0x8000;
30
+ sign_a.hi = (fp4x8.s0 << 8) & 0x8000;
31
+ sign_b.lo = (fp4x8.s0 << 4) & 0x8000;
32
+ sign_b.hi = fp4x8.s0 & 0x8000;
33
+
34
+ fp16_packed_a_0 = sign_a + bias_a + fp16_packed_a_0;
35
+ fp16_packed_b_0 = sign_b + bias_b + fp16_packed_b_0;
36
+
37
+ ushort2 fp16_packed_a_1, fp16_packed_b_1;
38
+ fp16_packed_a_1.lo = (fp4x8.s1 << 9) & 0x0E00;
39
+ fp16_packed_a_1.hi = (fp4x8.s1 << 5) & 0x0E00;
40
+ fp16_packed_b_1.lo = (fp4x8.s1 << 1) & 0x0E00;
41
+ fp16_packed_b_1.hi = (fp4x8.s1 >> 3) & 0x0E00;
42
+
43
+ bias_a.lo = (fp16_packed_a_1.lo != 0) ? 0x3800 : 0x0;
44
+ bias_a.hi = (fp16_packed_a_1.hi != 0) ? 0x3800 : 0x0;
45
+ bias_b.lo = (fp16_packed_b_1.lo != 0) ? 0x3800 : 0x0;
46
+ bias_b.hi = (fp16_packed_b_1.hi != 0) ? 0x3800 : 0x0;
47
+
48
+ fp16_packed_a_1.lo = (fp16_packed_a_1.lo != 0x0200) ? fp16_packed_a_1.lo : 0x0;
49
+ fp16_packed_a_1.hi = (fp16_packed_a_1.hi != 0x0200) ? fp16_packed_a_1.hi : 0x0;
50
+ fp16_packed_b_1.lo = (fp16_packed_b_1.lo != 0x0200) ? fp16_packed_b_1.lo : 0x0;
51
+ fp16_packed_b_1.hi = (fp16_packed_b_1.hi != 0x0200) ? fp16_packed_b_1.hi : 0x0;
52
+
53
+ sign_a.lo = (fp4x8.s1 << 12) & 0x8000;
54
+ sign_a.hi = (fp4x8.s1 << 8) & 0x8000;
55
+ sign_b.lo = (fp4x8.s1 << 4) & 0x8000;
56
+ sign_b.hi = fp4x8.s1 & 0x8000;
57
+
58
+ fp16_packed_a_1 = sign_a + bias_a + fp16_packed_a_1;
59
+ fp16_packed_b_1 = sign_b + bias_b + fp16_packed_b_1;
60
+
61
+ return as_half8((ushort8)(fp16_packed_a_0, fp16_packed_b_0, fp16_packed_a_1, fp16_packed_b_1));
62
+ }
63
+
64
+
65
+ #define dotx16_reduce8(a_reg, b_lm, c_reg, lm_offset) \
66
+ acc.s0 = dot(a_reg.s0123, b_lm[lm_offset + 0]); \
67
+ acc.s1 = dot(a_reg.s0123, b_lm[lm_offset + 1]); \
68
+ acc.s2 = dot(a_reg.s0123, b_lm[lm_offset + 2]); \
69
+ acc.s3 = dot(a_reg.s0123, b_lm[lm_offset + 3]); \
70
+ acc.s4 = dot(a_reg.s0123, b_lm[lm_offset + 4]); \
71
+ acc.s5 = dot(a_reg.s0123, b_lm[lm_offset + 5]); \
72
+ acc.s6 = dot(a_reg.s0123, b_lm[lm_offset + 6]); \
73
+ acc.s7 = dot(a_reg.s0123, b_lm[lm_offset + 7]); \
74
+ acc.s8 = dot(a_reg.s0123, b_lm[lm_offset + 8]); \
75
+ acc.s9 = dot(a_reg.s0123, b_lm[lm_offset + 9]); \
76
+ acc.sa = dot(a_reg.s0123, b_lm[lm_offset + 10]); \
77
+ acc.sb = dot(a_reg.s0123, b_lm[lm_offset + 11]); \
78
+ acc.sc = dot(a_reg.s0123, b_lm[lm_offset + 12]); \
79
+ acc.sd = dot(a_reg.s0123, b_lm[lm_offset + 13]); \
80
+ acc.se = dot(a_reg.s0123, b_lm[lm_offset + 14]); \
81
+ acc.sf = dot(a_reg.s0123, b_lm[lm_offset + 15]); \
82
+ acc.s0 += dot(a_reg.s4567, b_lm[lm_offset + 32]); \
83
+ acc.s1 += dot(a_reg.s4567, b_lm[lm_offset + 33]); \
84
+ acc.s2 += dot(a_reg.s4567, b_lm[lm_offset + 34]); \
85
+ acc.s3 += dot(a_reg.s4567, b_lm[lm_offset + 35]); \
86
+ acc.s4 += dot(a_reg.s4567, b_lm[lm_offset + 36]); \
87
+ acc.s5 += dot(a_reg.s4567, b_lm[lm_offset + 37]); \
88
+ acc.s6 += dot(a_reg.s4567, b_lm[lm_offset + 38]); \
89
+ acc.s7 += dot(a_reg.s4567, b_lm[lm_offset + 39]); \
90
+ acc.s8 += dot(a_reg.s4567, b_lm[lm_offset + 40]); \
91
+ acc.s9 += dot(a_reg.s4567, b_lm[lm_offset + 41]); \
92
+ acc.sa += dot(a_reg.s4567, b_lm[lm_offset + 42]); \
93
+ acc.sb += dot(a_reg.s4567, b_lm[lm_offset + 43]); \
94
+ acc.sc += dot(a_reg.s4567, b_lm[lm_offset + 44]); \
95
+ acc.sd += dot(a_reg.s4567, b_lm[lm_offset + 45]); \
96
+ acc.se += dot(a_reg.s4567, b_lm[lm_offset + 46]); \
97
+ acc.sf += dot(a_reg.s4567, b_lm[lm_offset + 47]); \
98
+ c_reg.lo += convert_float8(acc.lo); \
99
+ c_reg.hi += convert_float8(acc.hi); \
100
+ acc.s0 = dot(a_reg.s89ab, b_lm[lm_offset + 64]); \
101
+ acc.s1 = dot(a_reg.s89ab, b_lm[lm_offset + 65]); \
102
+ acc.s2 = dot(a_reg.s89ab, b_lm[lm_offset + 66]); \
103
+ acc.s3 = dot(a_reg.s89ab, b_lm[lm_offset + 67]); \
104
+ acc.s4 = dot(a_reg.s89ab, b_lm[lm_offset + 68]); \
105
+ acc.s5 = dot(a_reg.s89ab, b_lm[lm_offset + 69]); \
106
+ acc.s6 = dot(a_reg.s89ab, b_lm[lm_offset + 70]); \
107
+ acc.s7 = dot(a_reg.s89ab, b_lm[lm_offset + 71]); \
108
+ acc.s8 = dot(a_reg.s89ab, b_lm[lm_offset + 72]); \
109
+ acc.s9 = dot(a_reg.s89ab, b_lm[lm_offset + 73]); \
110
+ acc.sa = dot(a_reg.s89ab, b_lm[lm_offset + 74]); \
111
+ acc.sb = dot(a_reg.s89ab, b_lm[lm_offset + 75]); \
112
+ acc.sc = dot(a_reg.s89ab, b_lm[lm_offset + 76]); \
113
+ acc.sd = dot(a_reg.s89ab, b_lm[lm_offset + 77]); \
114
+ acc.se = dot(a_reg.s89ab, b_lm[lm_offset + 78]); \
115
+ acc.sf = dot(a_reg.s89ab, b_lm[lm_offset + 79]); \
116
+ acc.s0 += dot(a_reg.scdef, b_lm[lm_offset + 96]); \
117
+ acc.s1 += dot(a_reg.scdef, b_lm[lm_offset + 97]); \
118
+ acc.s2 += dot(a_reg.scdef, b_lm[lm_offset + 98]); \
119
+ acc.s3 += dot(a_reg.scdef, b_lm[lm_offset + 99]); \
120
+ acc.s4 += dot(a_reg.scdef, b_lm[lm_offset + 100]); \
121
+ acc.s5 += dot(a_reg.scdef, b_lm[lm_offset + 101]); \
122
+ acc.s6 += dot(a_reg.scdef, b_lm[lm_offset + 102]); \
123
+ acc.s7 += dot(a_reg.scdef, b_lm[lm_offset + 103]); \
124
+ acc.s8 += dot(a_reg.scdef, b_lm[lm_offset + 104]); \
125
+ acc.s9 += dot(a_reg.scdef, b_lm[lm_offset + 105]); \
126
+ acc.sa += dot(a_reg.scdef, b_lm[lm_offset + 106]); \
127
+ acc.sb += dot(a_reg.scdef, b_lm[lm_offset + 107]); \
128
+ acc.sc += dot(a_reg.scdef, b_lm[lm_offset + 108]); \
129
+ acc.sd += dot(a_reg.scdef, b_lm[lm_offset + 109]); \
130
+ acc.se += dot(a_reg.scdef, b_lm[lm_offset + 110]); \
131
+ acc.sf += dot(a_reg.scdef, b_lm[lm_offset + 111]); \
132
+ c_reg.lo += convert_float8(acc.lo); \
133
+ c_reg.hi += convert_float8(acc.hi); \
134
+
135
+ // Quarter-tile variant: computes 8 output columns (one skip-group) into a float8
136
+ // accumulator. Same reduction order / flush cadence as dotx16_reduce8, so the
137
+ // non-skipped path is byte-identical; it just lets the caller skip empty
138
+ // 8-column groups at finer granularity. Uses a private half8 `acc8`.
139
+ #define dotx8_reduce4(a_reg, b_lm, c_reg, lm_offset) \
140
+ acc8.s0 = dot(a_reg.s0123, b_lm[lm_offset + 0]); \
141
+ acc8.s1 = dot(a_reg.s0123, b_lm[lm_offset + 1]); \
142
+ acc8.s2 = dot(a_reg.s0123, b_lm[lm_offset + 2]); \
143
+ acc8.s3 = dot(a_reg.s0123, b_lm[lm_offset + 3]); \
144
+ acc8.s4 = dot(a_reg.s0123, b_lm[lm_offset + 4]); \
145
+ acc8.s5 = dot(a_reg.s0123, b_lm[lm_offset + 5]); \
146
+ acc8.s6 = dot(a_reg.s0123, b_lm[lm_offset + 6]); \
147
+ acc8.s7 = dot(a_reg.s0123, b_lm[lm_offset + 7]); \
148
+ acc8.s0 += dot(a_reg.s4567, b_lm[lm_offset + 32]); \
149
+ acc8.s1 += dot(a_reg.s4567, b_lm[lm_offset + 33]); \
150
+ acc8.s2 += dot(a_reg.s4567, b_lm[lm_offset + 34]); \
151
+ acc8.s3 += dot(a_reg.s4567, b_lm[lm_offset + 35]); \
152
+ acc8.s4 += dot(a_reg.s4567, b_lm[lm_offset + 36]); \
153
+ acc8.s5 += dot(a_reg.s4567, b_lm[lm_offset + 37]); \
154
+ acc8.s6 += dot(a_reg.s4567, b_lm[lm_offset + 38]); \
155
+ acc8.s7 += dot(a_reg.s4567, b_lm[lm_offset + 39]); \
156
+ c_reg += convert_float8(acc8); \
157
+ acc8.s0 = dot(a_reg.s89ab, b_lm[lm_offset + 64]); \
158
+ acc8.s1 = dot(a_reg.s89ab, b_lm[lm_offset + 65]); \
159
+ acc8.s2 = dot(a_reg.s89ab, b_lm[lm_offset + 66]); \
160
+ acc8.s3 = dot(a_reg.s89ab, b_lm[lm_offset + 67]); \
161
+ acc8.s4 = dot(a_reg.s89ab, b_lm[lm_offset + 68]); \
162
+ acc8.s5 = dot(a_reg.s89ab, b_lm[lm_offset + 69]); \
163
+ acc8.s6 = dot(a_reg.s89ab, b_lm[lm_offset + 70]); \
164
+ acc8.s7 = dot(a_reg.s89ab, b_lm[lm_offset + 71]); \
165
+ acc8.s0 += dot(a_reg.scdef, b_lm[lm_offset + 96]); \
166
+ acc8.s1 += dot(a_reg.scdef, b_lm[lm_offset + 97]); \
167
+ acc8.s2 += dot(a_reg.scdef, b_lm[lm_offset + 98]); \
168
+ acc8.s3 += dot(a_reg.scdef, b_lm[lm_offset + 99]); \
169
+ acc8.s4 += dot(a_reg.scdef, b_lm[lm_offset + 100]); \
170
+ acc8.s5 += dot(a_reg.scdef, b_lm[lm_offset + 101]); \
171
+ acc8.s6 += dot(a_reg.scdef, b_lm[lm_offset + 102]); \
172
+ acc8.s7 += dot(a_reg.scdef, b_lm[lm_offset + 103]); \
173
+ c_reg += convert_float8(acc8); \
174
+
175
+
176
+ static inline half e8m0_to_fp16(uchar x) {
177
+ ushort bits;
178
+ bits = (ushort)(x) - (ushort)(112);
179
+ bits = ((bits & 0x00E0) != 0) ? 0x7C00 : (bits << 10);
180
+ return as_half(bits);
181
+ }
182
+
183
+ static inline float e8m0_to_fp32(uchar x) {
184
+ int bits;
185
+ bits = (x == 0) ? 0x00400000 : ((uint) x << 23);
186
+ return as_float(bits);
187
+ }
188
+
189
+
190
+ __attribute__((qcom_wave_pair_mode(1))) // 1=force single 2=force pair
191
+ kernel void kernel_gemm_moe_mxfp4_f32_ns(
192
+ __read_only image1d_buffer_t src0_q,
193
+ __global uchar * src0_d,
194
+ __read_only image1d_buffer_t src1,
195
+ __global uint * src2,
196
+ __global ushort * src2_emap,
197
+ __write_only image1d_buffer_t dst,
198
+ __global int * total_tiles,
199
+ uint ne00,
200
+ uint ne01,
201
+ uint is_ragged,
202
+ uint skip_gran
203
+ ) {
204
+ uint block_id_m = get_global_id(1); // m_tile
205
+ uint block_id_n = get_global_id(2); // n_tile
206
+
207
+ // Boundary check
208
+ if (block_id_n >= total_tiles[0]) {
209
+ return;
210
+ }
211
+
212
+ // Ragged tile-skip: when is_ragged and the upper 16 token-slots of this tile are all
213
+ // padding (router 0xFFFFFFFF), skip the second (reg_c.hi) dotx16_reduce8 half -> ~half
214
+ // the GEMM dot for sparse tiles. Numerically identical (the skipped lanes are padding).
215
+ // Ragged tile-skip: tokens are packed contiguously per expert (moe_scatter fills
216
+ // lanes 0..V-1, moe_fill pre-pads the rest), so router padding (0xFFFFFFFF) is always
217
+ // trailing. Find the valid-token count V and round it UP to the skip granularity
218
+ // skip_gran (columns per skip-group: 8 = quarter, 16 = half/legacy, 32 = disabled).
219
+ // A 8-column group g is all-padding iff its first column (8*g) >= n_active, so its
220
+ // dotx8_reduce4 is skipped. Numerically identical (skipped lanes are padding).
221
+ uint n_active = TILESIZE_N;
222
+ if (is_ragged && skip_gran < TILESIZE_N) {
223
+ uint n_valid = TILESIZE_N;
224
+ for (uint _t = 0; _t < TILESIZE_N; ++_t) {
225
+ if (src2[block_id_n * TILESIZE_N + _t] == 0xFFFFFFFFu) { n_valid = _t; break; }
226
+ }
227
+ n_active = min((uint)TILESIZE_N, ((n_valid + skip_gran - 1) / skip_gran) * skip_gran);
228
+ }
229
+ // Group 0 (cols 0-7) always runs; groups 1-3 skip when fully padding.
230
+ bool skip_g1 = (8u >= n_active);
231
+ bool skip_g2 = (16u >= n_active);
232
+ bool skip_g3 = (24u >= n_active);
233
+
234
+ __private half16 reg_a;
235
+ __private float32 reg_c = (float32)(0);
236
+ __local half4 shared_b[128];
237
+
238
+ const ushort expert_id = src2_emap[block_id_n];
239
+
240
+ const uint row = block_id_m * TILESIZE_M;
241
+ const uint col = block_id_n * TILESIZE_N;
242
+
243
+ uint sub_block_id_m = get_local_id(0);
244
+ uint2 b_global_offset;
245
+ b_global_offset.x = ((sub_block_id_m & 3) << 2) + (sub_block_id_m >> 2) * ne00;
246
+ b_global_offset.y = b_global_offset.x + (16 * ne00);
247
+ uint2 b_local_offset;
248
+ b_local_offset.x = (sub_block_id_m & 3) * 32 + (sub_block_id_m >> 2);
249
+ b_local_offset.y = b_local_offset.x + 16;
250
+
251
+ // Loop along K axis, 32 elements (one block) for each iteration, divided into 2 sub-blocks
252
+ for (uint step = 0; step < ne00; step += TILESIZE_K * 2) {
253
+ // First sub-block
254
+ uint q_sub_offset = row + ((ne01 * step) >> 3) + ((expert_id * ne00 * ne01) >> 3);
255
+ uint s_sub_offset = row + ((ne01 * step) >> 5) + ((expert_id * ne00 * ne01) >> 5);
256
+ uint b_sub_offset = col * ne00 + step;
257
+
258
+ // Load scale for current mxfp4 block
259
+ uint s_offset = s_sub_offset + get_global_id(0);
260
+ float s = e8m0_to_fp32(src0_d[s_offset]);
261
+
262
+ // Load 16 fp4 (64-bits) in transposed layout
263
+ uint2 mxfp4x16;
264
+ mxfp4x16.x = read_imageui(src0_q, q_sub_offset + sub_block_id_m).x;
265
+ mxfp4x16.y = read_imageui(src0_q, q_sub_offset + sub_block_id_m + ne01).x;
266
+
267
+ // Load 16x32 floats from matrix B, each fiber out of 64 in a sub-group loads 8 elements
268
+ float8 bx8_f32;
269
+ bx8_f32.lo = read_imagef(src1, (b_sub_offset + b_global_offset.x) / 4);
270
+ bx8_f32.hi = read_imagef(src1, (b_sub_offset + b_global_offset.y) / 4);
271
+ // Convert to half and store to LM to share within the subgroup
272
+ half8 bx8_f16 = convert_half8(bx8_f32);
273
+ shared_b[b_local_offset.x] = bx8_f16.lo;
274
+ shared_b[b_local_offset.y] = bx8_f16.hi;
275
+
276
+ // Dequantization
277
+ // Cast the e8m0 scale to half to satisfy E17 compilers
278
+ reg_a.lo = mxfp4_to_fp16_packed8(as_ushort2(mxfp4x16.lo)) * (half)s;
279
+ reg_a.hi = mxfp4_to_fp16_packed8(as_ushort2(mxfp4x16.hi)) * (half)s;
280
+
281
+ sub_group_barrier(CLK_LOCAL_MEM_FENCE);
282
+
283
+ // 32 16x16 fp16 dot product with 8 elements reduction for better precision
284
+ half8 acc8;
285
+ dotx8_reduce4(reg_a, shared_b, reg_c.lo.lo, 0);
286
+ if (!skip_g1) { dotx8_reduce4(reg_a, shared_b, reg_c.lo.hi, 8); }
287
+ if (!skip_g2) { dotx8_reduce4(reg_a, shared_b, reg_c.hi.lo, 16); }
288
+ if (!skip_g3) { dotx8_reduce4(reg_a, shared_b, reg_c.hi.hi, 24); }
289
+
290
+ // Repeat for second sub-block
291
+ uint half_step = step + TILESIZE_K;
292
+ q_sub_offset = row + ((ne01 * half_step) >> 3) + ((expert_id * ne00 * ne01) >> 3);
293
+ b_sub_offset = col * ne00 + half_step;
294
+
295
+ // Load next 16 fp4 (64-bits) in transposed layout
296
+ mxfp4x16.x = read_imageui(src0_q, q_sub_offset + sub_block_id_m).x;
297
+ mxfp4x16.y = read_imageui(src0_q, q_sub_offset + sub_block_id_m + ne01).x;
298
+
299
+ // Load 16x32 floats from matrix B, each fiber out of 64 in a sub-group loads 8 elements
300
+ bx8_f32.lo = read_imagef(src1, (b_sub_offset + b_global_offset.x) / 4);
301
+ bx8_f32.hi = read_imagef(src1, (b_sub_offset + b_global_offset.y) / 4);
302
+ // Convert to half and store to LM to share within the subgroup
303
+ bx8_f16 = convert_half8(bx8_f32);
304
+ shared_b[b_local_offset.x] = bx8_f16.lo;
305
+ shared_b[b_local_offset.y] = bx8_f16.hi;
306
+
307
+ // Dequantization
308
+ // Cast the e8m0 scale to half to satisfy E17 compilers
309
+ reg_a.lo = mxfp4_to_fp16_packed8(as_ushort2(mxfp4x16.lo)) * (half)s;
310
+ reg_a.hi = mxfp4_to_fp16_packed8(as_ushort2(mxfp4x16.hi)) * (half)s;
311
+
312
+ sub_group_barrier(CLK_LOCAL_MEM_FENCE);
313
+
314
+ // 32 16x16 fp16 dot product with 3-levels reduction for better precision
315
+ dotx8_reduce4(reg_a, shared_b, reg_c.lo.lo, 0);
316
+ if (!skip_g1) { dotx8_reduce4(reg_a, shared_b, reg_c.lo.hi, 8); }
317
+ if (!skip_g2) { dotx8_reduce4(reg_a, shared_b, reg_c.hi.lo, 16); }
318
+ if (!skip_g3) { dotx8_reduce4(reg_a, shared_b, reg_c.hi.hi, 24); }
319
+ }
320
+
321
+ if ((get_global_id(0) + block_id_m * TILESIZE_M) >= ne01) {
322
+ return;
323
+ }
324
+
325
+ // Load poster router and share in LM
326
+ __local uint out_idx[TILESIZE_N];
327
+
328
+ if (get_local_id(0) < TILESIZE_N) {
329
+ uint idx = src2[block_id_n * TILESIZE_N + get_local_id(0)];
330
+ if (idx == 0xFFFFFFFF) {
331
+ idx = src2[block_id_n * TILESIZE_N + 0];
332
+ }
333
+ out_idx[get_local_id(0)] = idx * ne01;
334
+ }
335
+
336
+ barrier(CLK_LOCAL_MEM_FENCE);
337
+
338
+ // Scatter results back to original position in output grid
339
+ uint m_offset = row + get_local_id(0);
340
+
341
+ write_imagef(dst, out_idx[1] + m_offset, (reg_c.s1));
342
+ write_imagef(dst, out_idx[2] + m_offset, (reg_c.s2));
343
+ write_imagef(dst, out_idx[3] + m_offset, (reg_c.s3));
344
+ write_imagef(dst, out_idx[4] + m_offset, (reg_c.s4));
345
+ write_imagef(dst, out_idx[5] + m_offset, (reg_c.s5));
346
+ write_imagef(dst, out_idx[6] + m_offset, (reg_c.s6));
347
+ write_imagef(dst, out_idx[7] + m_offset, (reg_c.s7));
348
+ write_imagef(dst, out_idx[8] + m_offset, (reg_c.s8));
349
+ write_imagef(dst, out_idx[9] + m_offset, (reg_c.s9));
350
+ write_imagef(dst, out_idx[10] + m_offset, (reg_c.sa));
351
+ write_imagef(dst, out_idx[11] + m_offset, (reg_c.sb));
352
+ write_imagef(dst, out_idx[12] + m_offset, (reg_c.sc));
353
+ write_imagef(dst, out_idx[13] + m_offset, (reg_c.sd));
354
+ write_imagef(dst, out_idx[14] + m_offset, (reg_c.se));
355
+ write_imagef(dst, out_idx[15] + m_offset, (reg_c.sf));
356
+ write_imagef(dst, out_idx[16] + m_offset, (reg_c.sg));
357
+ write_imagef(dst, out_idx[17] + m_offset, (reg_c.sh));
358
+ write_imagef(dst, out_idx[18] + m_offset, (reg_c.si));
359
+ write_imagef(dst, out_idx[19] + m_offset, (reg_c.sj));
360
+ write_imagef(dst, out_idx[20] + m_offset, (reg_c.sk));
361
+ write_imagef(dst, out_idx[21] + m_offset, (reg_c.sl));
362
+ write_imagef(dst, out_idx[22] + m_offset, (reg_c.sm));
363
+ write_imagef(dst, out_idx[23] + m_offset, (reg_c.sn));
364
+ write_imagef(dst, out_idx[24] + m_offset, (reg_c.so));
365
+ write_imagef(dst, out_idx[25] + m_offset, (reg_c.sp));
366
+ write_imagef(dst, out_idx[26] + m_offset, (reg_c.sq));
367
+ write_imagef(dst, out_idx[27] + m_offset, (reg_c.sr));
368
+ write_imagef(dst, out_idx[28] + m_offset, (reg_c.ss));
369
+ write_imagef(dst, out_idx[29] + m_offset, (reg_c.st));
370
+ write_imagef(dst, out_idx[30] + m_offset, (reg_c.su));
371
+ write_imagef(dst, out_idx[31] + m_offset, (reg_c.sv));
372
+
373
+ // Store zero padding parts to the index of first output in tile, override correct result in the end
374
+ barrier(CLK_GLOBAL_MEM_FENCE);
375
+ write_imagef(dst, out_idx[0] + m_offset, (reg_c.s0));
376
+ }
ggml/src/ggml-opencl/kernels/gemm_moe_mxfp4_q8_1_dp4a.cl ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+ #pragma OPENCL EXTENSION cl_khr_subgroups : enable
3
+ #ifdef cl_khr_integer_dot_product
4
+ #pragma OPENCL EXTENSION cl_khr_integer_dot_product : enable
5
+ #endif
6
+
7
+ #define TILESIZE_M 64
8
+ #define TILESIZE_N 32
9
+
10
+ // 2*mxfp4_value as signed int8, packed 4 codes per uint. Divergent nibble
11
+ // lookups read a __constant *uint* array + shift, never a byte array
12
+ // (byte-indexed __constant loads serialize on Adreno and are far slower).
13
+ // idx 0-3: 0, 1, 2, 3 = 0x03020100
14
+ // idx 4-7: 4, 6, 8, 12 = 0x0C080604
15
+ // idx 8-11: 0, -1, -2, -3 = 0xFDFEFF00 (-1=0xFF,-2=0xFE,-3=0xFD)
16
+ // idx 12-15:-4, -6, -8,-12 = 0xF4F8FAFC (-4=0xFC,-6=0xFA,-8=0xF8,-12=0xF4)
17
+ __constant uint mxfp4_i8x4[4] = {
18
+ 0x03020100u, 0x0C080604u, 0xFDFEFF00u, 0xF4F8FAFCu
19
+ };
20
+ inline uint mxfp4_code(uint n) {
21
+ return (mxfp4_i8x4[n >> 2] >> ((n & 3u) * 8u)) & 0xFFu;
22
+ }
23
+ // 4 nibbles in the low 16 bits of u -> 4 codebook int8, packed for dp4a.
24
+ inline uint mxfp4_pack(ushort u) {
25
+ return mxfp4_code((uint)( u & 0xF))
26
+ | (mxfp4_code((uint)((u >> 4) & 0xF)) << 8)
27
+ | (mxfp4_code((uint)((u >> 8) & 0xF)) << 16)
28
+ | (mxfp4_code((uint)((u >> 12) & 0xF)) << 24);
29
+ }
30
+
31
+ static inline float e8m0_to_fp32(uchar x) {
32
+ int bits;
33
+ bits = (x == 0) ? 0x00400000 : ((uint) x << 23);
34
+ return as_float(bits);
35
+ }
36
+
37
+ // One token's dp4a dot (8 uints = 32 K elems) + mxfp4 block-scale epilogue.
38
+ // blk_scale already carries the 0.5 factor (== 0.5 * 2^e).
39
+ #define MOE_MXFP4_DP4A_T(t) do { \
40
+ uint4 a0 = vload4(0, &sh_qa[t][0]); \
41
+ uint4 a1 = vload4(0, &sh_qa[t][4]); \
42
+ int raw = 0; \
43
+ raw = dot_acc_sat_4x8packed_ss_int(qw[0], a0.s0, raw); \
44
+ raw = dot_acc_sat_4x8packed_ss_int(qw[1], a0.s1, raw); \
45
+ raw = dot_acc_sat_4x8packed_ss_int(qw[2], a0.s2, raw); \
46
+ raw = dot_acc_sat_4x8packed_ss_int(qw[3], a0.s3, raw); \
47
+ raw = dot_acc_sat_4x8packed_ss_int(qw[4], a1.s0, raw); \
48
+ raw = dot_acc_sat_4x8packed_ss_int(qw[5], a1.s1, raw); \
49
+ raw = dot_acc_sat_4x8packed_ss_int(qw[6], a1.s2, raw); \
50
+ raw = dot_acc_sat_4x8packed_ss_int(qw[7], a1.s3, raw); \
51
+ acc[t] += blk_scale * (float)sh_d[t] * (float)raw; \
52
+ } while (0)
53
+
54
+ __attribute__((qcom_wave_pair_mode(1)))
55
+ kernel void kernel_gemm_moe_mxfp4_q8_1_dp4a(
56
+ __read_only image1d_buffer_t src0_q, // mxfp4 codes (transposed, packed nibbles)
57
+ __global uchar * src0_e, // e8m0 per-32-block scale
58
+ __global uint * src1_qa, // q8_1 activations: int8 quants (as uint, 4/elem)
59
+ __global half * src1_da, // q8_1 per-block scale [tok_slot * ne00/32]
60
+ __global uint * src2, // post-router (orig out positions)
61
+ __global ushort * src2_emap, // tile -> expert id
62
+ __write_only image1d_buffer_t dst,
63
+ __global int * total_tiles,
64
+ uint ne00,
65
+ uint ne01,
66
+ int is_ragged // 1: compute only real tokens per tile
67
+ ) {
68
+ const uint block_id_m = get_global_id(1); // m_tile
69
+ const uint block_id_n = get_global_id(2); // n_tile
70
+
71
+ if (block_id_n >= total_tiles[0]) {
72
+ return;
73
+ }
74
+
75
+ const uint lid = get_local_id(0); // 0..63, == this WI's output row in the M-tile
76
+
77
+ const ushort expert_id = src2_emap[block_id_n];
78
+ const uint row = block_id_m * TILESIZE_M;
79
+ const uint col = block_id_n * TILESIZE_N;
80
+
81
+ const uint num_blocks = ne00 >> 5; // blocks-of-32 per token
82
+ const uint row_idx = row + lid;
83
+
84
+ const uint ne00_u = ne00 >> 2; // ne00 in uint (int8x4) units
85
+
86
+ __local uint sh_qa[TILESIZE_N][8]; // 32 tokens x 8 uints (32 int8) = 1 KiB
87
+ __local half sh_d[TILESIZE_N];
88
+
89
+ // Real token count for this tile.
90
+ // Real tokens are packed contiguously at the tile start; padded slots hold
91
+ // 0xFFFFFFFF (only the last tile of each expert is partial). is_ragged skips
92
+ // the dp4a/staging/scatter for padded slots; is_ragged==0 forces n_real=32.
93
+ __local uint sh_src2[TILESIZE_N];
94
+ __local int sh_nreal;
95
+ if (lid < TILESIZE_N) {
96
+ sh_src2[lid] = src2[col + lid];
97
+ }
98
+ barrier(CLK_LOCAL_MEM_FENCE);
99
+ if (lid == 0) {
100
+ int nr = TILESIZE_N;
101
+ if (is_ragged) {
102
+ nr = 0;
103
+ #pragma unroll
104
+ for (int t = 0; t < TILESIZE_N; ++t) {
105
+ if (sh_src2[t] != 0xFFFFFFFFu) ++nr;
106
+ }
107
+ }
108
+ sh_nreal = nr;
109
+ }
110
+ barrier(CLK_LOCAL_MEM_FENCE);
111
+ const int n_real = sh_nreal;
112
+
113
+ float acc[TILESIZE_N];
114
+ #pragma unroll
115
+ for (int t = 0; t < TILESIZE_N; ++t) acc[t] = 0.0f;
116
+
117
+ for (uint step = 0; step < ne00; step += 32) {
118
+ const uint sub = step >> 5; // 32-block index along K
119
+
120
+ // e8m0 block scale for this WI's row, this 32-block (folded x0.5)
121
+ const uint e_offset = row_idx + sub * ne01 + expert_id * num_blocks * ne01;
122
+ const float blk_scale = 0.5f * e8m0_to_fp32(src0_e[e_offset]);
123
+
124
+ // repack this WI's 32 weight nibbles into 8 dp4a uints
125
+ const uint qoff0 = row + ((ne01 * step) >> 3) + ((expert_id * ne00 * ne01) >> 3);
126
+ const uint qoff1 = row + ((ne01 * (step + 16)) >> 3) + ((expert_id * ne00 * ne01) >> 3);
127
+ const uint r0 = read_imageui(src0_q, qoff0 + lid).x;
128
+ const uint r1 = read_imageui(src0_q, qoff0 + lid + ne01).x;
129
+ const uint r2 = read_imageui(src0_q, qoff1 + lid).x;
130
+ const uint r3 = read_imageui(src0_q, qoff1 + lid + ne01).x;
131
+ uint qw[8];
132
+ qw[0] = mxfp4_pack((ushort)(r0)); qw[1] = mxfp4_pack((ushort)(r0 >> 16));
133
+ qw[2] = mxfp4_pack((ushort)(r1)); qw[3] = mxfp4_pack((ushort)(r1 >> 16));
134
+ qw[4] = mxfp4_pack((ushort)(r2)); qw[5] = mxfp4_pack((ushort)(r2 >> 16));
135
+ qw[6] = mxfp4_pack((ushort)(r3)); qw[7] = mxfp4_pack((ushort)(r3 >> 16));
136
+
137
+ // cooperatively stage the n_real-token x 32-K int8 activations
138
+ // Stage each token's 8 activation uints as two 128-bit uint4 loads/stores.
139
+ const uint vlim = (uint)n_real * 2;
140
+ for (uint idx = lid; idx < vlim; idx += 64) {
141
+ const uint t = idx >> 1;
142
+ const uint h = (idx & 1) << 2; // 0 or 4
143
+ uint4 v = vload4(0, &src1_qa[(col + t) * ne00_u + (step >> 2) + h]);
144
+ vstore4(v, 0, &sh_qa[t][h]);
145
+ }
146
+ if (lid < (uint)n_real) {
147
+ sh_d[lid] = src1_da[(col + lid) * num_blocks + sub];
148
+ }
149
+ barrier(CLK_LOCAL_MEM_FENCE);
150
+
151
+ // Full tiles keep the fully-unrolled 32-wide loop; partial tiles run only n_real
152
+ if (n_real == TILESIZE_N) {
153
+ #pragma unroll
154
+ for (int t = 0; t < TILESIZE_N; ++t) { MOE_MXFP4_DP4A_T(t); }
155
+ } else {
156
+ #pragma unroll 4
157
+ for (int t = 0; t < n_real; ++t) { MOE_MXFP4_DP4A_T(t); }
158
+ }
159
+ barrier(CLK_LOCAL_MEM_FENCE);
160
+ }
161
+
162
+ if (row_idx >= ne01) {
163
+ return;
164
+ }
165
+
166
+ // scatter results to original output rows (reuse sh_src2 from the top)
167
+ __local uint out_idx[TILESIZE_N];
168
+ if (lid < TILESIZE_N) {
169
+ uint idx = sh_src2[lid];
170
+ if (idx == 0xFFFFFFFF) {
171
+ idx = sh_src2[0];
172
+ }
173
+ out_idx[lid] = idx * ne01;
174
+ }
175
+ barrier(CLK_LOCAL_MEM_FENCE);
176
+
177
+ const uint m_offset = row + lid;
178
+ if (n_real == TILESIZE_N) {
179
+ #pragma unroll
180
+ for (int t = 1; t < TILESIZE_N; ++t) {
181
+ write_imagef(dst, out_idx[t] + m_offset, acc[t]);
182
+ }
183
+ barrier(CLK_GLOBAL_MEM_FENCE);
184
+ write_imagef(dst, out_idx[0] + m_offset, acc[0]);
185
+ } else {
186
+ for (int t = 0; t < n_real; ++t) {
187
+ write_imagef(dst, out_idx[t] + m_offset, acc[t]);
188
+ }
189
+ }
190
+ }
ggml/src/ggml-opencl/kernels/gemm_moe_q4_0_f32_ns.cl ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+ #pragma OPENCL EXTENSION cl_khr_subgroups : enable
3
+ #pragma OPENCL EXTENSION cl_qcom_subgroup_uniform_load: enable
4
+ #pragma OPENCL EXTENSION cl_qcom_subgroup_constant_load: enable
5
+ #pragma OPENCL EXTENSION cl_qcom_extra_vector_types : enable
6
+
7
+ #define TILESIZE_K 16
8
+ #define TILESIZE_M 64
9
+ #define TILESIZE_N 32
10
+
11
+
12
+ #define dequantize_q4_0(q4, a_f16, scale) \
13
+ a_f16.s0 = (half)((q4.s0 & 0x000F) - 8) * scale; \
14
+ a_f16.s1 = (half)(((q4.s0 & 0x00F0) >> 4) - 8) * scale; \
15
+ a_f16.s2 = (half)(((q4.s0 & 0x0F00) >> 8) - 8) * scale; \
16
+ a_f16.s3 = (half)(((q4.s0 & 0xF000) >> 12) - 8) * scale; \
17
+ a_f16.s4 = (half)((q4.s1 & 0x000F) - 8) * scale; \
18
+ a_f16.s5 = (half)(((q4.s1 & 0x00F0) >> 4) - 8) * scale; \
19
+ a_f16.s6 = (half)(((q4.s1 & 0x0F00) >> 8) - 8) * scale; \
20
+ a_f16.s7 = (half)(((q4.s1 & 0xF000) >> 12) - 8) * scale; \
21
+ a_f16.s8 = (half)((q4.s2 & 0x000F) - 8) * scale; \
22
+ a_f16.s9 = (half)(((q4.s2 & 0x00F0) >> 4) - 8) * scale; \
23
+ a_f16.sa = (half)(((q4.s2 & 0x0F00) >> 8) - 8) * scale; \
24
+ a_f16.sb = (half)(((q4.s2 & 0xF000) >> 12) - 8) * scale; \
25
+ a_f16.sc = (half)((q4.s3 & 0x000F) - 8) * scale; \
26
+ a_f16.sd = (half)(((q4.s3 & 0x00F0) >> 4) - 8) * scale; \
27
+ a_f16.se = (half)(((q4.s3 & 0x0F00) >> 8) - 8) * scale; \
28
+ a_f16.sf = (half)(((q4.s3 & 0xF000) >> 12) - 8) * scale; \
29
+
30
+
31
+ #define dotx16_reduce8(a_reg, b_lm, c_reg, lm_offset) \
32
+ acc.s0 = dot(a_reg.s0123, b_lm[lm_offset + 0]); \
33
+ acc.s1 = dot(a_reg.s0123, b_lm[lm_offset + 1]); \
34
+ acc.s2 = dot(a_reg.s0123, b_lm[lm_offset + 2]); \
35
+ acc.s3 = dot(a_reg.s0123, b_lm[lm_offset + 3]); \
36
+ acc.s4 = dot(a_reg.s0123, b_lm[lm_offset + 4]); \
37
+ acc.s5 = dot(a_reg.s0123, b_lm[lm_offset + 5]); \
38
+ acc.s6 = dot(a_reg.s0123, b_lm[lm_offset + 6]); \
39
+ acc.s7 = dot(a_reg.s0123, b_lm[lm_offset + 7]); \
40
+ acc.s8 = dot(a_reg.s0123, b_lm[lm_offset + 8]); \
41
+ acc.s9 = dot(a_reg.s0123, b_lm[lm_offset + 9]); \
42
+ acc.sa = dot(a_reg.s0123, b_lm[lm_offset + 10]); \
43
+ acc.sb = dot(a_reg.s0123, b_lm[lm_offset + 11]); \
44
+ acc.sc = dot(a_reg.s0123, b_lm[lm_offset + 12]); \
45
+ acc.sd = dot(a_reg.s0123, b_lm[lm_offset + 13]); \
46
+ acc.se = dot(a_reg.s0123, b_lm[lm_offset + 14]); \
47
+ acc.sf = dot(a_reg.s0123, b_lm[lm_offset + 15]); \
48
+ acc.s0 += dot(a_reg.s4567, b_lm[lm_offset + 32]); \
49
+ acc.s1 += dot(a_reg.s4567, b_lm[lm_offset + 33]); \
50
+ acc.s2 += dot(a_reg.s4567, b_lm[lm_offset + 34]); \
51
+ acc.s3 += dot(a_reg.s4567, b_lm[lm_offset + 35]); \
52
+ acc.s4 += dot(a_reg.s4567, b_lm[lm_offset + 36]); \
53
+ acc.s5 += dot(a_reg.s4567, b_lm[lm_offset + 37]); \
54
+ acc.s6 += dot(a_reg.s4567, b_lm[lm_offset + 38]); \
55
+ acc.s7 += dot(a_reg.s4567, b_lm[lm_offset + 39]); \
56
+ acc.s8 += dot(a_reg.s4567, b_lm[lm_offset + 40]); \
57
+ acc.s9 += dot(a_reg.s4567, b_lm[lm_offset + 41]); \
58
+ acc.sa += dot(a_reg.s4567, b_lm[lm_offset + 42]); \
59
+ acc.sb += dot(a_reg.s4567, b_lm[lm_offset + 43]); \
60
+ acc.sc += dot(a_reg.s4567, b_lm[lm_offset + 44]); \
61
+ acc.sd += dot(a_reg.s4567, b_lm[lm_offset + 45]); \
62
+ acc.se += dot(a_reg.s4567, b_lm[lm_offset + 46]); \
63
+ acc.sf += dot(a_reg.s4567, b_lm[lm_offset + 47]); \
64
+ c_reg.lo += convert_float8(acc.lo); \
65
+ c_reg.hi += convert_float8(acc.hi); \
66
+ acc.s0 = dot(a_reg.s89ab, b_lm[lm_offset + 64]); \
67
+ acc.s1 = dot(a_reg.s89ab, b_lm[lm_offset + 65]); \
68
+ acc.s2 = dot(a_reg.s89ab, b_lm[lm_offset + 66]); \
69
+ acc.s3 = dot(a_reg.s89ab, b_lm[lm_offset + 67]); \
70
+ acc.s4 = dot(a_reg.s89ab, b_lm[lm_offset + 68]); \
71
+ acc.s5 = dot(a_reg.s89ab, b_lm[lm_offset + 69]); \
72
+ acc.s6 = dot(a_reg.s89ab, b_lm[lm_offset + 70]); \
73
+ acc.s7 = dot(a_reg.s89ab, b_lm[lm_offset + 71]); \
74
+ acc.s8 = dot(a_reg.s89ab, b_lm[lm_offset + 72]); \
75
+ acc.s9 = dot(a_reg.s89ab, b_lm[lm_offset + 73]); \
76
+ acc.sa = dot(a_reg.s89ab, b_lm[lm_offset + 74]); \
77
+ acc.sb = dot(a_reg.s89ab, b_lm[lm_offset + 75]); \
78
+ acc.sc = dot(a_reg.s89ab, b_lm[lm_offset + 76]); \
79
+ acc.sd = dot(a_reg.s89ab, b_lm[lm_offset + 77]); \
80
+ acc.se = dot(a_reg.s89ab, b_lm[lm_offset + 78]); \
81
+ acc.sf = dot(a_reg.s89ab, b_lm[lm_offset + 79]); \
82
+ acc.s0 += dot(a_reg.scdef, b_lm[lm_offset + 96]); \
83
+ acc.s1 += dot(a_reg.scdef, b_lm[lm_offset + 97]); \
84
+ acc.s2 += dot(a_reg.scdef, b_lm[lm_offset + 98]); \
85
+ acc.s3 += dot(a_reg.scdef, b_lm[lm_offset + 99]); \
86
+ acc.s4 += dot(a_reg.scdef, b_lm[lm_offset + 100]); \
87
+ acc.s5 += dot(a_reg.scdef, b_lm[lm_offset + 101]); \
88
+ acc.s6 += dot(a_reg.scdef, b_lm[lm_offset + 102]); \
89
+ acc.s7 += dot(a_reg.scdef, b_lm[lm_offset + 103]); \
90
+ acc.s8 += dot(a_reg.scdef, b_lm[lm_offset + 104]); \
91
+ acc.s9 += dot(a_reg.scdef, b_lm[lm_offset + 105]); \
92
+ acc.sa += dot(a_reg.scdef, b_lm[lm_offset + 106]); \
93
+ acc.sb += dot(a_reg.scdef, b_lm[lm_offset + 107]); \
94
+ acc.sc += dot(a_reg.scdef, b_lm[lm_offset + 108]); \
95
+ acc.sd += dot(a_reg.scdef, b_lm[lm_offset + 109]); \
96
+ acc.se += dot(a_reg.scdef, b_lm[lm_offset + 110]); \
97
+ acc.sf += dot(a_reg.scdef, b_lm[lm_offset + 111]); \
98
+ c_reg.lo += convert_float8(acc.lo); \
99
+ c_reg.hi += convert_float8(acc.hi); \
100
+
101
+ // Quarter-tile variant: computes 8 output columns (one skip-group) into a float8
102
+ // accumulator. Same reduction order / flush cadence as dotx16_reduce8, so the
103
+ // non-skipped path is byte-identical; it just lets the caller skip empty
104
+ // 8-column groups at finer granularity. Uses a private half8 `acc8`.
105
+ #define dotx8_reduce4(a_reg, b_lm, c_reg, lm_offset) \
106
+ acc8.s0 = dot(a_reg.s0123, b_lm[lm_offset + 0]); \
107
+ acc8.s1 = dot(a_reg.s0123, b_lm[lm_offset + 1]); \
108
+ acc8.s2 = dot(a_reg.s0123, b_lm[lm_offset + 2]); \
109
+ acc8.s3 = dot(a_reg.s0123, b_lm[lm_offset + 3]); \
110
+ acc8.s4 = dot(a_reg.s0123, b_lm[lm_offset + 4]); \
111
+ acc8.s5 = dot(a_reg.s0123, b_lm[lm_offset + 5]); \
112
+ acc8.s6 = dot(a_reg.s0123, b_lm[lm_offset + 6]); \
113
+ acc8.s7 = dot(a_reg.s0123, b_lm[lm_offset + 7]); \
114
+ acc8.s0 += dot(a_reg.s4567, b_lm[lm_offset + 32]); \
115
+ acc8.s1 += dot(a_reg.s4567, b_lm[lm_offset + 33]); \
116
+ acc8.s2 += dot(a_reg.s4567, b_lm[lm_offset + 34]); \
117
+ acc8.s3 += dot(a_reg.s4567, b_lm[lm_offset + 35]); \
118
+ acc8.s4 += dot(a_reg.s4567, b_lm[lm_offset + 36]); \
119
+ acc8.s5 += dot(a_reg.s4567, b_lm[lm_offset + 37]); \
120
+ acc8.s6 += dot(a_reg.s4567, b_lm[lm_offset + 38]); \
121
+ acc8.s7 += dot(a_reg.s4567, b_lm[lm_offset + 39]); \
122
+ c_reg += convert_float8(acc8); \
123
+ acc8.s0 = dot(a_reg.s89ab, b_lm[lm_offset + 64]); \
124
+ acc8.s1 = dot(a_reg.s89ab, b_lm[lm_offset + 65]); \
125
+ acc8.s2 = dot(a_reg.s89ab, b_lm[lm_offset + 66]); \
126
+ acc8.s3 = dot(a_reg.s89ab, b_lm[lm_offset + 67]); \
127
+ acc8.s4 = dot(a_reg.s89ab, b_lm[lm_offset + 68]); \
128
+ acc8.s5 = dot(a_reg.s89ab, b_lm[lm_offset + 69]); \
129
+ acc8.s6 = dot(a_reg.s89ab, b_lm[lm_offset + 70]); \
130
+ acc8.s7 = dot(a_reg.s89ab, b_lm[lm_offset + 71]); \
131
+ acc8.s0 += dot(a_reg.scdef, b_lm[lm_offset + 96]); \
132
+ acc8.s1 += dot(a_reg.scdef, b_lm[lm_offset + 97]); \
133
+ acc8.s2 += dot(a_reg.scdef, b_lm[lm_offset + 98]); \
134
+ acc8.s3 += dot(a_reg.scdef, b_lm[lm_offset + 99]); \
135
+ acc8.s4 += dot(a_reg.scdef, b_lm[lm_offset + 100]); \
136
+ acc8.s5 += dot(a_reg.scdef, b_lm[lm_offset + 101]); \
137
+ acc8.s6 += dot(a_reg.scdef, b_lm[lm_offset + 102]); \
138
+ acc8.s7 += dot(a_reg.scdef, b_lm[lm_offset + 103]); \
139
+ c_reg += convert_float8(acc8); \
140
+
141
+
142
+ __attribute__((qcom_wave_pair_mode(1))) // 1=force single 2=force pair
143
+ kernel void kernel_gemm_moe_q4_0_f32_ns(
144
+ __read_only image1d_buffer_t src0_q,
145
+ __global half * src0_d,
146
+ __read_only image1d_buffer_t src1,
147
+ __global uint * src2,
148
+ __global ushort * src2_emap,
149
+ __write_only image1d_buffer_t dst,
150
+ __global int * total_tiles,
151
+ uint ne00,
152
+ uint ne01,
153
+ uint is_ragged,
154
+ uint skip_gran
155
+ ) {
156
+ uint block_id_m = get_global_id(1); // m_tile
157
+ uint block_id_n = get_global_id(2); // n_tile
158
+
159
+ // Boundary check
160
+ if (block_id_n >= total_tiles[0]) {
161
+ return;
162
+ }
163
+
164
+ // Ragged tile-skip: when is_ragged and the upper 16 token-slots of this tile are all
165
+ // padding (router 0xFFFFFFFF), skip the second (reg_c.hi) dotx16_reduce8 half -> ~half
166
+ // the GEMM dot for sparse tiles. Numerically identical (the skipped lanes are padding).
167
+ // Ragged tile-skip: tokens are packed contiguously per expert (moe_scatter fills
168
+ // lanes 0..V-1, moe_fill pre-pads the rest), so router padding (0xFFFFFFFF) is always
169
+ // trailing. Find the valid-token count V and round it UP to the skip granularity
170
+ // skip_gran (columns per skip-group: 8 = quarter, 16 = half/legacy, 32 = disabled).
171
+ // A 8-column group g is all-padding iff its first column (8*g) >= n_active, so its
172
+ // dotx8_reduce4 is skipped. Numerically identical (skipped lanes are padding).
173
+ uint n_active = TILESIZE_N;
174
+ if (is_ragged && skip_gran < TILESIZE_N) {
175
+ uint n_valid = TILESIZE_N;
176
+ for (uint _t = 0; _t < TILESIZE_N; ++_t) {
177
+ if (src2[block_id_n * TILESIZE_N + _t] == 0xFFFFFFFFu) { n_valid = _t; break; }
178
+ }
179
+ n_active = min((uint)TILESIZE_N, ((n_valid + skip_gran - 1) / skip_gran) * skip_gran);
180
+ }
181
+ // Group 0 (cols 0-7) always runs; groups 1-3 skip when fully padding.
182
+ bool skip_g1 = (8u >= n_active);
183
+ bool skip_g2 = (16u >= n_active);
184
+ bool skip_g3 = (24u >= n_active);
185
+
186
+ __private half16 reg_a;
187
+ __private float32 reg_c = (float32)(0);
188
+ __local half4 shared_b[128];
189
+
190
+ const ushort expert_id = src2_emap[block_id_n];
191
+
192
+ const uint row = block_id_m * TILESIZE_M;
193
+ const uint col = block_id_n * TILESIZE_N;
194
+
195
+ uint sub_block_id_m = get_local_id(0);
196
+ uint2 b_global_offset;
197
+ b_global_offset.x = ((sub_block_id_m & 3) << 2) + (sub_block_id_m >> 2) * ne00;
198
+ b_global_offset.y = b_global_offset.x + (16 * ne00);
199
+ uint2 b_local_offset;
200
+ b_local_offset.x = (sub_block_id_m & 3) * 32 + (sub_block_id_m >> 2);
201
+ b_local_offset.y = b_local_offset.x + 16;
202
+
203
+ // Loop along K axis, 32 elements (one block) for each iteration, divided into 2 sub-blocks
204
+ for (uint step = 0; step < ne00; step += TILESIZE_K * 2) {
205
+ // First sub-block
206
+ uint q_sub_offset = row + ((ne01 * step) >> 3) + ((expert_id * ne00 * ne01) >> 3);
207
+ uint s_sub_offset = row + ((ne01 * step) >> 5) + ((expert_id * ne00 * ne01) >> 5);
208
+ uint b_sub_offset = col * ne00 + step;
209
+
210
+ // Load scale for current Q4_0 block
211
+ uint s_offset = s_sub_offset + get_global_id(0);
212
+ half s = src0_d[s_offset];
213
+
214
+ // Load 16 q (64-bits) in transposed layout
215
+ uint2 q4x16;
216
+ q4x16.x = read_imageui(src0_q, q_sub_offset + sub_block_id_m).x;
217
+ q4x16.y = read_imageui(src0_q, q_sub_offset + sub_block_id_m + ne01).x;
218
+
219
+ // Load 16x32 floats from matrix B, each fiber out of 64 in a sub-group loads 8 elements
220
+ float8 bx8_f32;
221
+ bx8_f32.lo = read_imagef(src1, (b_sub_offset + b_global_offset.x) / 4);
222
+ bx8_f32.hi = read_imagef(src1, (b_sub_offset + b_global_offset.y) / 4);
223
+ // Convert to half and store to LM to share within the subgroup
224
+ half8 bx8_f16 = convert_half8(bx8_f32);
225
+ shared_b[b_local_offset.x] = bx8_f16.lo;
226
+ shared_b[b_local_offset.y] = bx8_f16.hi;
227
+
228
+ // Dequantization
229
+ dequantize_q4_0(as_ushort4(q4x16), reg_a, s);
230
+
231
+ sub_group_barrier(CLK_LOCAL_MEM_FENCE);
232
+
233
+ // 32 16x16 fp16 dot product with 8 elements reduction for better precision
234
+ half8 acc8;
235
+ dotx8_reduce4(reg_a, shared_b, reg_c.lo.lo, 0);
236
+ if (!skip_g1) { dotx8_reduce4(reg_a, shared_b, reg_c.lo.hi, 8); }
237
+ if (!skip_g2) { dotx8_reduce4(reg_a, shared_b, reg_c.hi.lo, 16); }
238
+ if (!skip_g3) { dotx8_reduce4(reg_a, shared_b, reg_c.hi.hi, 24); }
239
+
240
+ // Repeat for second sub-block
241
+ uint half_step = step + TILESIZE_K;
242
+ q_sub_offset = row + ((ne01 * half_step) >> 3) + ((expert_id * ne00 * ne01) >> 3);
243
+ b_sub_offset = col * ne00 + half_step;
244
+
245
+ // Load next 16 q (64-bits) in transposed layout
246
+ q4x16.x = read_imageui(src0_q, q_sub_offset + sub_block_id_m).x;
247
+ q4x16.y = read_imageui(src0_q, q_sub_offset + sub_block_id_m + ne01).x;
248
+
249
+ // Load 16x32 floats from matrix B, each fiber out of 64 in a sub-group loads 8 elements
250
+ bx8_f32.lo = read_imagef(src1, (b_sub_offset + b_global_offset.x) / 4);
251
+ bx8_f32.hi = read_imagef(src1, (b_sub_offset + b_global_offset.y) / 4);
252
+ // Convert to half and store to LM to share within the subgroup
253
+ bx8_f16 = convert_half8(bx8_f32);
254
+ shared_b[b_local_offset.x] = bx8_f16.lo;
255
+ shared_b[b_local_offset.y] = bx8_f16.hi;
256
+
257
+ // Dequantization
258
+ dequantize_q4_0(as_ushort4(q4x16), reg_a, s);
259
+
260
+ sub_group_barrier(CLK_LOCAL_MEM_FENCE);
261
+
262
+ // 32 16x16 fp16 dot product with 3-levels reduction for better precision
263
+ dotx8_reduce4(reg_a, shared_b, reg_c.lo.lo, 0);
264
+ if (!skip_g1) { dotx8_reduce4(reg_a, shared_b, reg_c.lo.hi, 8); }
265
+ if (!skip_g2) { dotx8_reduce4(reg_a, shared_b, reg_c.hi.lo, 16); }
266
+ if (!skip_g3) { dotx8_reduce4(reg_a, shared_b, reg_c.hi.hi, 24); }
267
+ }
268
+
269
+ if ((get_global_id(0) + block_id_m * TILESIZE_M) >= ne01) {
270
+ return;
271
+ }
272
+
273
+ // Load poster router and share in LM
274
+ __local uint out_idx[TILESIZE_N];
275
+
276
+ if (get_local_id(0) < TILESIZE_N) {
277
+ uint idx = src2[block_id_n * TILESIZE_N + get_local_id(0)];
278
+ if (idx == 0xFFFFFFFF) {
279
+ idx = src2[block_id_n * TILESIZE_N + 0];
280
+ }
281
+ out_idx[get_local_id(0)] = idx * ne01;
282
+ }
283
+
284
+ barrier(CLK_LOCAL_MEM_FENCE);
285
+
286
+ // Scatter results back to original position in output grid
287
+ uint m_offset = row + get_local_id(0);
288
+
289
+ write_imagef(dst, out_idx[1] + m_offset, (reg_c.s1));
290
+ write_imagef(dst, out_idx[2] + m_offset, (reg_c.s2));
291
+ write_imagef(dst, out_idx[3] + m_offset, (reg_c.s3));
292
+ write_imagef(dst, out_idx[4] + m_offset, (reg_c.s4));
293
+ write_imagef(dst, out_idx[5] + m_offset, (reg_c.s5));
294
+ write_imagef(dst, out_idx[6] + m_offset, (reg_c.s6));
295
+ write_imagef(dst, out_idx[7] + m_offset, (reg_c.s7));
296
+ write_imagef(dst, out_idx[8] + m_offset, (reg_c.s8));
297
+ write_imagef(dst, out_idx[9] + m_offset, (reg_c.s9));
298
+ write_imagef(dst, out_idx[10] + m_offset, (reg_c.sa));
299
+ write_imagef(dst, out_idx[11] + m_offset, (reg_c.sb));
300
+ write_imagef(dst, out_idx[12] + m_offset, (reg_c.sc));
301
+ write_imagef(dst, out_idx[13] + m_offset, (reg_c.sd));
302
+ write_imagef(dst, out_idx[14] + m_offset, (reg_c.se));
303
+ write_imagef(dst, out_idx[15] + m_offset, (reg_c.sf));
304
+ write_imagef(dst, out_idx[16] + m_offset, (reg_c.sg));
305
+ write_imagef(dst, out_idx[17] + m_offset, (reg_c.sh));
306
+ write_imagef(dst, out_idx[18] + m_offset, (reg_c.si));
307
+ write_imagef(dst, out_idx[19] + m_offset, (reg_c.sj));
308
+ write_imagef(dst, out_idx[20] + m_offset, (reg_c.sk));
309
+ write_imagef(dst, out_idx[21] + m_offset, (reg_c.sl));
310
+ write_imagef(dst, out_idx[22] + m_offset, (reg_c.sm));
311
+ write_imagef(dst, out_idx[23] + m_offset, (reg_c.sn));
312
+ write_imagef(dst, out_idx[24] + m_offset, (reg_c.so));
313
+ write_imagef(dst, out_idx[25] + m_offset, (reg_c.sp));
314
+ write_imagef(dst, out_idx[26] + m_offset, (reg_c.sq));
315
+ write_imagef(dst, out_idx[27] + m_offset, (reg_c.sr));
316
+ write_imagef(dst, out_idx[28] + m_offset, (reg_c.ss));
317
+ write_imagef(dst, out_idx[29] + m_offset, (reg_c.st));
318
+ write_imagef(dst, out_idx[30] + m_offset, (reg_c.su));
319
+ write_imagef(dst, out_idx[31] + m_offset, (reg_c.sv));
320
+
321
+ // Store zero padding parts to the index of first output in tile, override correct result in the end
322
+ barrier(CLK_GLOBAL_MEM_FENCE);
323
+ write_imagef(dst, out_idx[0] + m_offset, (reg_c.s0));
324
+ }
ggml/src/ggml-opencl/kernels/gemm_moe_q4_0_q8_1_dp4a.cl ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
2
+ #pragma OPENCL EXTENSION cl_khr_subgroups : enable
3
+ #ifdef cl_khr_integer_dot_product
4
+ #pragma OPENCL EXTENSION cl_khr_integer_dot_product : enable
5
+ #endif
6
+
7
+ #define TILESIZE_M 64
8
+ #define TILESIZE_N 32
9
+
10
+ // Expand the 4 nibbles held in the low 16 bits of `u` into 4 bytes (one nibble
11
+ // per byte, value 0..15), packed for the int8 dp4a. The -8 zero-point is applied
12
+ // in the epilogue via the activation sum term (cheaper than biasing every byte).
13
+ #define EXP4(u) ( ((uint)((u) & 0x000Fu)) | \
14
+ (((uint)((u) & 0x00F0u)) << 4) | \
15
+ (((uint)((u) & 0x0F00u)) << 8) | \
16
+ (((uint)((u) & 0xF000u)) << 12) )
17
+
18
+ // One token's dp4a dot (8 uints = 32 K elems) + q4_0 scale/zero-point epilogue.
19
+ #define MOE_Q40_DP4A_T(t) do { \
20
+ uint4 a0 = vload4(0, &sh_qa[t][0]); \
21
+ uint4 a1 = vload4(0, &sh_qa[t][4]); \
22
+ int raw = 0; \
23
+ raw = dot_acc_sat_4x8packed_ss_int(qw[0], a0.s0, raw); \
24
+ raw = dot_acc_sat_4x8packed_ss_int(qw[1], a0.s1, raw); \
25
+ raw = dot_acc_sat_4x8packed_ss_int(qw[2], a0.s2, raw); \
26
+ raw = dot_acc_sat_4x8packed_ss_int(qw[3], a0.s3, raw); \
27
+ raw = dot_acc_sat_4x8packed_ss_int(qw[4], a1.s0, raw); \
28
+ raw = dot_acc_sat_4x8packed_ss_int(qw[5], a1.s1, raw); \
29
+ raw = dot_acc_sat_4x8packed_ss_int(qw[6], a1.s2, raw); \
30
+ raw = dot_acc_sat_4x8packed_ss_int(qw[7], a1.s3, raw); \
31
+ acc[t] += d_val * ((float)sh_d[t] * (float)raw - 8.0f * (float)sh_s[t]); \
32
+ } while (0)
33
+
34
+ __attribute__((qcom_wave_pair_mode(1)))
35
+ kernel void kernel_gemm_moe_q4_0_q8_1_dp4a(
36
+ __read_only image1d_buffer_t src0_q, // q4_0 weights (transposed, packed nibbles)
37
+ __global half * src0_d, // per-32-block scale
38
+ __global uint * src1_qa, // q8_1 activations: int8 quants (as uint, 4/elem)
39
+ __global half * src1_da, // q8_1 per-block scale [tok_slot * ne00/32]
40
+ __global half * src1_sa, // q8_1 per-block sum*d [tok_slot * ne00/32]
41
+ __global uint * src2, // post-router (orig out positions)
42
+ __global ushort * src2_emap,// tile -> expert id
43
+ __write_only image1d_buffer_t dst,
44
+ __global int * total_tiles,
45
+ uint ne00,
46
+ uint ne01,
47
+ int is_ragged // 1: compute only real tokens per tile
48
+ ) {
49
+ const uint block_id_m = get_global_id(1); // m_tile
50
+ const uint block_id_n = get_global_id(2); // n_tile
51
+
52
+ if (block_id_n >= total_tiles[0]) {
53
+ return;
54
+ }
55
+
56
+ const uint lid = get_local_id(0); // 0..63, == this WI's output row in the M-tile
57
+
58
+ const ushort expert_id = src2_emap[block_id_n];
59
+ const uint row = block_id_m * TILESIZE_M;
60
+ const uint col = block_id_n * TILESIZE_N;
61
+
62
+ const uint num_blocks = ne00 >> 5; // blocks-of-32 per token
63
+ const uint row_idx = row + lid;
64
+
65
+ const uint ne00_u = ne00 >> 2; // ne00 in uint (int8x4) units
66
+
67
+ __local uint sh_qa[TILESIZE_N][8]; // 32 tokens x 8 uints (32 int8) = 1 KiB
68
+ __local half sh_d[TILESIZE_N];
69
+ __local half sh_s[TILESIZE_N];
70
+
71
+ // Real-token count for this tile
72
+ __local uint sh_src2[TILESIZE_N];
73
+ __local int sh_nreal;
74
+ if (lid < TILESIZE_N) {
75
+ sh_src2[lid] = src2[col + lid];
76
+ }
77
+ barrier(CLK_LOCAL_MEM_FENCE);
78
+ if (lid == 0) {
79
+ int nr = TILESIZE_N;
80
+ if (is_ragged) {
81
+ nr = 0;
82
+ #pragma unroll
83
+ for (int t = 0; t < TILESIZE_N; ++t) {
84
+ if (sh_src2[t] != 0xFFFFFFFFu) ++nr;
85
+ }
86
+ }
87
+ sh_nreal = nr;
88
+ }
89
+ barrier(CLK_LOCAL_MEM_FENCE);
90
+ const int n_real = sh_nreal;
91
+
92
+ float acc[TILESIZE_N];
93
+ #pragma unroll
94
+ for (int t = 0; t < TILESIZE_N; ++t) acc[t] = 0.0f;
95
+
96
+ for (uint step = 0; step < ne00; step += 32) {
97
+ const uint sub = step >> 5; // 32-block index along K
98
+
99
+ // per-32-block scale for this WI's row
100
+ const uint d_offset = row_idx + sub * ne01 + expert_id * num_blocks * ne01;
101
+ const float d_val = (float)src0_d[d_offset];
102
+
103
+ // repack this WI's 32 weight nibbles into 8 dp4a uints
104
+ const uint qoff0 = row + ((ne01 * step) >> 3) + ((expert_id * ne00 * ne01) >> 3);
105
+ const uint qoff1 = row + ((ne01 * (step + 16)) >> 3) + ((expert_id * ne00 * ne01) >> 3);
106
+ const uint r0 = read_imageui(src0_q, qoff0 + lid).x;
107
+ const uint r1 = read_imageui(src0_q, qoff0 + lid + ne01).x;
108
+ const uint r2 = read_imageui(src0_q, qoff1 + lid).x;
109
+ const uint r3 = read_imageui(src0_q, qoff1 + lid + ne01).x;
110
+ uint qw[8];
111
+ qw[0] = EXP4(r0); qw[1] = EXP4(r0 >> 16);
112
+ qw[2] = EXP4(r1); qw[3] = EXP4(r1 >> 16);
113
+ qw[4] = EXP4(r2); qw[5] = EXP4(r2 >> 16);
114
+ qw[6] = EXP4(r3); qw[7] = EXP4(r3 >> 16);
115
+
116
+ // cooperatively stage the n_real-token x 32-K int8 activations
117
+ // Stage each token's 8 activation uints as two 128-bit uint4 loads/stores.
118
+ const uint vlim = (uint)n_real * 2;
119
+ for (uint idx = lid; idx < vlim; idx += 64) {
120
+ const uint t = idx >> 1;
121
+ const uint h = (idx & 1) << 2; // 0 or 4
122
+ uint4 v = vload4(0, &src1_qa[(col + t) * ne00_u + (step >> 2) + h]);
123
+ vstore4(v, 0, &sh_qa[t][h]);
124
+ }
125
+ if (lid < (uint)n_real) {
126
+ sh_d[lid] = src1_da[(col + lid) * num_blocks + sub];
127
+ sh_s[lid] = src1_sa[(col + lid) * num_blocks + sub];
128
+ }
129
+ barrier(CLK_LOCAL_MEM_FENCE);
130
+
131
+ if (n_real == TILESIZE_N) {
132
+ #pragma unroll
133
+ for (int t = 0; t < TILESIZE_N; ++t) { MOE_Q40_DP4A_T(t); }
134
+ } else {
135
+ #pragma unroll 4
136
+ for (int t = 0; t < n_real; ++t) { MOE_Q40_DP4A_T(t); }
137
+ }
138
+ barrier(CLK_LOCAL_MEM_FENCE);
139
+ }
140
+
141
+ if (row_idx >= ne01) {
142
+ return;
143
+ }
144
+
145
+ // scatter results to original output rows (reuse sh_src2 from the top)
146
+ __local uint out_idx[TILESIZE_N];
147
+ if (lid < TILESIZE_N) {
148
+ uint idx = sh_src2[lid];
149
+ if (idx == 0xFFFFFFFF) {
150
+ idx = sh_src2[0];
151
+ }
152
+ out_idx[lid] = idx * ne01;
153
+ }
154
+ barrier(CLK_LOCAL_MEM_FENCE);
155
+
156
+ const uint m_offset = row + lid;
157
+ if (n_real == TILESIZE_N) {
158
+ #pragma unroll
159
+ for (int t = 1; t < TILESIZE_N; ++t) {
160
+ write_imagef(dst, out_idx[t] + m_offset, acc[t]);
161
+ }
162
+ barrier(CLK_GLOBAL_MEM_FENCE);
163
+ write_imagef(dst, out_idx[0] + m_offset, acc[0]);
164
+ } else {
165
+ for (int t = 0; t < n_real; ++t) {
166
+ write_imagef(dst, out_idx[t] + m_offset, acc[t]);
167
+ }
168
+ }
169
+ }