interplane.Get Omega
Read in your language

ggml

[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)

Brought by drakestapleton

branch master Branches Tags History

ggml / src / ggml-webgpu / ggml-webgpu.cpp

5005 lines · 250039 bytes Raw Blame History
1/*
2 WebGPU backend implementation.
3 Note: Use ClangFormat to format this file.
4*/
5
6#include "ggml-webgpu.h"
7
8#include "ggml-backend-impl.h"
9#include "ggml-impl.h"
10#include "ggml-webgpu-shader-lib.hpp"
11#include "ggml.h"
12
13#ifdef __EMSCRIPTEN__
14# include <emscripten/emscripten.h>
15#endif
16
17#include <webgpu/webgpu_cpp.h>
18
19#include <atomic>
20#include <cstdint>
21#include <cstring>
22#ifdef GGML_WEBGPU_GPU_PROFILE
23# include <iomanip>
24#endif
25#if defined(GGML_WEBGPU_DEBUG) || defined(GGML_WEBGPU_CPU_PROFILE) || defined(GGML_WEBGPU_GPU_PROFILE)
26# include <iostream>
27#endif
28#include <memory>
29#include <mutex>
30#include <optional>
31#include <string>
32#include <utility>
33#include <vector>
34
35#define ROUNDUP_POW2(x, pow2) (((x) + ((pow2) - 1)) & ~((pow2) - 1))
36#define CEIL_DIV(M, N) (((M) + (N) - 1) / (N))
37
38// Return a rectangular grid of workgroups with minimal over-provisioned workgroups.
39// Assumes that the total number of workgroups does not exceed max_per_dim^2.
40static inline void compute_2d_workgroups(uint32_t total_wg, uint32_t max_per_dim, uint32_t & wg_x, uint32_t & wg_y) {
41 wg_y = std::max(1u, CEIL_DIV(total_wg, max_per_dim));
42 wg_x = CEIL_DIV(total_wg, wg_y);
43}
44
45static inline uint32_t ggml_webgpu_u32_from_f32(float value) {
46 uint32_t bits;
47 memcpy(&bits, &value, sizeof(bits));
48 return bits;
49}
50
51#ifdef GGML_WEBGPU_DEBUG
52# define WEBGPU_LOG_DEBUG(msg) std::cout << msg << std::endl
53# define WEBGPU_DEBUG_BUF_ELEMS 512
54#else
55# define WEBGPU_LOG_DEBUG(msg) ((void) 0)
56#endif // GGML_WEBGPU_DEBUG
57
58#ifdef GGML_WEBGPU_CPU_PROFILE
59// total timing (aggregated)
60# define WEBGPU_CPU_PROFILE_TOTAL_START(id) auto cpu_total_start_##id = std::chrono::high_resolution_clock::now();
61
62# define WEBGPU_CPU_PROFILE_TOTAL_END(id, ctx) \
63 auto cpu_total_end_##id = std::chrono::high_resolution_clock::now(); \
64 double cpu_total_time_##id = \
65 std::chrono::duration<double, std::milli>(cpu_total_end_##id - cpu_total_start_##id).count(); \
66 (ctx)->cpu_time_ms[#id] += cpu_total_time_##id;
67// fine-grained timing (not included in totals)
68# define WEBGPU_CPU_PROFILE_DETAIL_START(id) auto cpu_detail_start_##id = std::chrono::high_resolution_clock::now();
69
70# define WEBGPU_CPU_PROFILE_DETAIL_END(id, ctx) \
71 auto cpu_detail_end_##id = std::chrono::high_resolution_clock::now(); \
72 double cpu_detail_time_##id = \
73 std::chrono::duration<double, std::milli>(cpu_detail_end_##id - cpu_detail_start_##id).count(); \
74 (ctx)->cpu_detail_ms[#id] += cpu_detail_time_##id;
75#else
76# define WEBGPU_CPU_PROFILE_TOTAL_START(id)
77# define WEBGPU_CPU_PROFILE_TOTAL_END(id, ctx)
78# define WEBGPU_CPU_PROFILE_DETAIL_START(id)
79# define WEBGPU_CPU_PROFILE_DETAIL_END(id, ctx)
80#endif // GGML_WEBGPU_CPU_PROFILE
81
82#ifdef GGML_WEBGPU_GPU_PROFILE
83# define WEBGPU_MAX_PROFILE_QUERY_COUNT 4096u
84# define WEBGPU_TIMESTAMP_QUERY_BUF_SIZE_BYTES (WEBGPU_MAX_PROFILE_QUERY_COUNT * sizeof(uint64_t))
85#endif
86
87/* Constants */
88
89#define WEBGPU_DEFAULT_COMMAND_SUBMIT_BATCH_SIZE 64u
90#define WEBGPU_NUM_PARAM_SLOT_SAFETY_MARGIN 10u
91#define WEBGPU_RUNTIME_WAIT_TIMEOUT_MS 30000u
92#define WEBGPU_RUNTIME_WAIT_TIMEOUT_NS (WEBGPU_RUNTIME_WAIT_TIMEOUT_MS * 1e6)
93#define WEBGPU_PARAMS_BUF_SIZE_BYTES 128 // enough for 32 parameters
94#define WEBGPU_SET_ROWS_ERROR_BUF_SIZE_BYTES 4
95#define WEBGPU_STORAGE_BUF_BINDING_MULT 4 // a storage buffer binding size must be a multiple of 4
96
97/* End Constants */
98
99// This is a "fake" base pointer, since WebGPU buffers do not have pointers to
100// their locations.
101static void * const webgpu_ptr_base = (void *) (uintptr_t) 0x1000; // NOLINT
102
103static size_t ggml_webgpu_tensor_offset(const ggml_tensor * tensor) {
104 const ggml_tensor * base_tensor = tensor->view_src ? tensor->view_src : tensor;
105 return (size_t) ((uintptr_t) base_tensor->data - (uintptr_t) webgpu_ptr_base) + tensor->view_offs;
106}
107
108/* Struct definitions */
109
110// Forward reference
111static void ggml_webgpu_create_buffer(wgpu::Device & device,
112 wgpu::Buffer & buffer,
113 size_t size,
114 wgpu::BufferUsage usage,
115 const char * label);
116
117// Slot-based parameter arena for compute graph encoding. Each encoded kernel
118// gets a unique uniform-buffer slice within the current batch, and the slot
119// cursor is reset immediately after that batch is submitted.
120struct webgpu_param_arena {
121 wgpu::Buffer buffer;
122 size_t slot_stride = 0;
123 size_t slot_size = 0;
124 uint32_t slot_count = 0;
125 uint32_t next_slot = 0;
126
127 void init(wgpu::Device device, size_t slot_size, uint32_t slot_count, size_t alignment) {
128 this->slot_stride = ROUNDUP_POW2(slot_size, alignment);
129 this->slot_size = slot_size;
130 this->slot_count = slot_count;
131 this->next_slot = 0;
132
133 ggml_webgpu_create_buffer(device, buffer, this->slot_stride * slot_count,
134 wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::Uniform, "ggml_webgpu_param_arena");
135 }
136
137 size_t alloc_slot(size_t size) {
138 GGML_ASSERT(size <= slot_size);
139 if (next_slot >= slot_count) {
140 GGML_ABORT("ggml_webgpu: parameter arena exhausted while encoding a batch");
141 }
142
143 return slot_stride * next_slot++;
144 }
145
146 void reset() { next_slot = 0; }
147
148 void cleanup() {
149 if (buffer) {
150 buffer.Destroy();
151 buffer = nullptr;
152 }
153 }
154
155 ~webgpu_param_arena() { this->cleanup(); }
156};
157
158struct webgpu_encoded_op {
159 uint32_t num_kernels = 0;
160#ifdef GGML_WEBGPU_GPU_PROFILE
161 std::vector<std::string> pipeline_names;
162#endif
163};
164
165struct webgpu_dispatch_desc {
166 webgpu_pipeline pipeline;
167 std::vector<uint32_t> params;
168 std::vector<wgpu::BindGroupEntry> bind_group_entries;
169 std::pair<uint32_t, uint32_t> workgroups = { 1, 1 };
170};
171
172struct webgpu_capabilities {
173 wgpu::Limits limits;
174 bool supports_subgroups = false;
175 bool supports_subgroup_matrix = false;
176 bool supports_dot_product = false;
177
178 uint32_t sg_mat_m = 0;
179 uint32_t sg_mat_n = 0;
180 uint32_t sg_mat_k = 0;
181
182 uint32_t subgroup_size = 0;
183 uint32_t min_subgroup_size = 0;
184 uint32_t max_subgroup_size = 0;
185 size_t memset_bytes_per_thread;
186};
187
188// Stores global webgpu members
189struct webgpu_global_context_struct {
190 wgpu::Instance instance;
191 wgpu::Adapter adapter;
192 wgpu::Device device;
193 wgpu::Queue queue;
194 uint32_t command_submit_batch_size = WEBGPU_DEFAULT_COMMAND_SUBMIT_BATCH_SIZE;
195 uint32_t max_inflight_batches = UINT32_MAX;
196
197 webgpu_capabilities capabilities;
198 // Shared buffer to move data from device to host
199 wgpu::Buffer get_tensor_staging_buf;
200 // Global mutex for get_tensor
201 std::recursive_mutex mutex;
202
203 wgpu::Buffer memset_params_buf;
204 webgpu_pipeline memset_pipeline;
205
206 std::string vendor;
207
208 // TODO: We should rework the CPU profiling time handling to make it more useful. ref: https://github.com/ggml-org/llama.cpp/pull/22050
209#ifdef GGML_WEBGPU_CPU_PROFILE
210 // Profiling: labeled CPU time in ms (total)
211 std::unordered_map<std::string, double> cpu_time_ms;
212 // Profiling: detailed CPU time in ms
213 std::unordered_map<std::string, double> cpu_detail_ms;
214#endif
215
216#ifdef GGML_WEBGPU_DEBUG
217 wgpu::Buffer debug_host_buf;
218 wgpu::Buffer debug_dev_buf;
219#endif
220
221 ~webgpu_global_context_struct() {
222 if (this->get_tensor_staging_buf) {
223 this->get_tensor_staging_buf.Destroy();
224 this->get_tensor_staging_buf = nullptr;
225 }
226 if (this->memset_params_buf) {
227 this->memset_params_buf.Destroy();
228 this->memset_params_buf = nullptr;
229 }
230#ifdef GGML_WEBGPU_DEBUG
231 if (this->debug_host_buf) {
232 this->debug_host_buf.Destroy();
233 this->debug_host_buf = nullptr;
234 }
235 if (this->debug_dev_buf) {
236 this->debug_dev_buf.Destroy();
237 this->debug_dev_buf = nullptr;
238 }
239#endif
240 }
241};
242
243typedef std::shared_ptr<webgpu_global_context_struct> webgpu_global_context;
244
245// All the base objects needed to run operations on a WebGPU device
246struct webgpu_context_struct {
247 // Points to global instances owned by ggml_backend_webgpu_reg_context
248 webgpu_global_context global_ctx;
249
250 std::unique_ptr<ggml_webgpu_shader_lib> shader_lib;
251
252 webgpu_param_arena param_arena;
253 wgpu::Buffer set_rows_dev_error_buf;
254 wgpu::Buffer set_rows_host_error_buf;
255 wgpu::CommandEncoder active_command_encoder;
256 wgpu::ComputePassEncoder active_compute_pass;
257 bool batch_compute_passes = true;
258
259 size_t memset_bytes_per_thread;
260
261#ifdef GGML_WEBGPU_GPU_PROFILE
262 // Profiling: per-shader GPU time in ms
263 std::unordered_map<std::string, double> shader_gpu_time_ms;
264 wgpu::Buffer profile_timestamp_dev_buf;
265 wgpu::Buffer profile_timestamp_host_buf;
266 wgpu::QuerySet profile_timestamp_query_set;
267 uint32_t profile_timestamp_query_count = 0;
268#endif
269
270 ~webgpu_context_struct() {
271#ifdef GGML_WEBGPU_GPU_PROFILE
272 if (this->profile_timestamp_host_buf) {
273 this->profile_timestamp_host_buf.Destroy();
274 this->profile_timestamp_host_buf = nullptr;
275 }
276 if (this->profile_timestamp_dev_buf) {
277 this->profile_timestamp_dev_buf.Destroy();
278 this->profile_timestamp_dev_buf = nullptr;
279 }
280 if (this->profile_timestamp_query_set) {
281 this->profile_timestamp_query_set.Destroy();
282 this->profile_timestamp_query_set = nullptr;
283 }
284#endif
285 if (this->set_rows_host_error_buf) {
286 this->set_rows_host_error_buf.Destroy();
287 this->set_rows_host_error_buf = nullptr;
288 }
289 if (this->set_rows_dev_error_buf) {
290 this->set_rows_dev_error_buf.Destroy();
291 this->set_rows_dev_error_buf = nullptr;
292 }
293 }
294};
295
296typedef std::shared_ptr<webgpu_context_struct> webgpu_context;
297
298// Metadata required for the ggml backend registration/discovery interface
299struct ggml_backend_webgpu_reg_context {
300 // Since the Instance is a global entrypoint into the WebGPU API, it lives here
301 webgpu_global_context webgpu_global_ctx;
302 size_t device_count;
303 const char * name;
304};
305
306// Per-device struct for the global logical device interface
307struct ggml_backend_webgpu_device_context {
308 webgpu_global_context webgpu_global_ctx;
309 std::string device_name;
310 std::string device_desc;
311};
312
313// Per-thread data required to actually run WebGPU operations in a backend instance
314struct ggml_backend_webgpu_context {
315 webgpu_context webgpu_ctx;
316 std::string name;
317};
318
319// Per-thread data related to buffers
320struct ggml_backend_webgpu_buffer_context {
321 wgpu::Buffer buffer;
322 std::string label;
323 webgpu_global_context global_ctx;
324
325 ggml_backend_webgpu_buffer_context(wgpu::Buffer buf, std::string lbl, webgpu_global_context global_ctx_) :
326 buffer(std::move(buf)),
327 label(std::move(lbl)),
328 global_ctx(std::move(global_ctx_)) {}
329};
330
331/* WebGPU object initializations */
332
333static webgpu_pipeline ggml_webgpu_create_pipeline(wgpu::Device & device,
334 const char * shader_code,
335 const char * label,
336 const std::vector<wgpu::ConstantEntry> & constants = {}) {
337 wgpu::ShaderSourceWGSL shader_source;
338 shader_source.code = shader_code;
339
340 wgpu::ShaderModuleDescriptor shader_desc;
341 shader_desc.nextInChain = &shader_source;
342
343 wgpu::ShaderModule shader_module = device.CreateShaderModule(&shader_desc);
344
345 wgpu::ComputePipelineDescriptor pipeline_desc;
346 pipeline_desc.label = label;
347 pipeline_desc.compute.module = shader_module;
348 pipeline_desc.compute.entryPoint = "main"; // Entry point in the WGSL code
349 pipeline_desc.layout = nullptr; // nullptr means auto layout
350 if (constants.size() > 0) {
351 pipeline_desc.compute.constants = constants.data();
352 pipeline_desc.compute.constantCount = constants.size();
353 }
354 return { device.CreateComputePipeline(&pipeline_desc), label };
355}
356
357static void ggml_webgpu_create_buffer(wgpu::Device & device,
358 wgpu::Buffer & buffer,
359 size_t size,
360 wgpu::BufferUsage usage,
361 const char * label) {
362 wgpu::BufferDescriptor buffer_desc;
363 buffer_desc.size = size;
364 buffer_desc.usage = usage;
365 buffer_desc.label = label;
366 buffer_desc.mappedAtCreation = false;
367
368 // TODO: error handling
369 buffer = device.CreateBuffer(&buffer_desc);
370}
371
372static wgpu::Buffer ggml_webgpu_tensor_buf(const ggml_tensor * tensor) {
373 ggml_backend_webgpu_buffer_context * ctx = (ggml_backend_webgpu_buffer_context *) tensor->buffer->context;
374 return ctx->buffer;
375}
376
377// Binding offset for a tensor: the largest aligned offset at or before the tensor whose
378// distance to the tensor is a whole number of type blocks, so shaders can index the
379// misalignment in elements even for block quantized types.
380static size_t ggml_webgpu_tensor_align_offset(const ggml_tensor * t, size_t alignment) {
381 const size_t offset = ggml_webgpu_tensor_offset(t);
382 const size_t type_size = ggml_type_size(t->type);
383 size_t aligned = offset & ~(alignment - 1);
384 while ((offset - aligned) % type_size != 0) {
385 GGML_ASSERT(aligned >= alignment);
386 aligned -= alignment;
387 }
388 return aligned;
389}
390
391static size_t ggml_webgpu_tensor_misalignment(const ggml_tensor * t, size_t alignment) {
392 return ggml_webgpu_tensor_offset(t) - ggml_webgpu_tensor_align_offset(t, alignment);
393}
394
395static size_t ggml_webgpu_tensor_misalignment(webgpu_context & ctx, const ggml_tensor * t) {
396 return ggml_webgpu_tensor_misalignment(t, ctx->global_ctx->capabilities.limits.minStorageBufferOffsetAlignment);
397}
398
399static size_t ggml_webgpu_tensor_align_offset(webgpu_context & ctx, const ggml_tensor * t) {
400 return ggml_webgpu_tensor_align_offset(t, ctx->global_ctx->capabilities.limits.minStorageBufferOffsetAlignment);
401}
402
403static size_t ggml_webgpu_tensor_binding_size(const ggml_tensor * t, size_t alignment) {
404 return ROUNDUP_POW2(ggml_nbytes(t) + ggml_webgpu_tensor_misalignment(t, alignment),
405 WEBGPU_STORAGE_BUF_BINDING_MULT);
406}
407
408static size_t ggml_webgpu_tensor_binding_size(webgpu_context & ctx, const ggml_tensor * t) {
409 return ggml_webgpu_tensor_binding_size(t, ctx->global_ctx->capabilities.limits.minStorageBufferOffsetAlignment);
410}
411
412static bool ggml_webgpu_tensor_binding_overlap(const webgpu_global_context & global_ctx,
413 const ggml_tensor * a,
414 const ggml_tensor * b) {
415 if (a->buffer != b->buffer) {
416 return false;
417 }
418
419 const size_t alignment = global_ctx->capabilities.limits.minStorageBufferOffsetAlignment;
420 const size_t a_offset = ggml_webgpu_tensor_align_offset(a, alignment);
421 const size_t b_offset = ggml_webgpu_tensor_align_offset(b, alignment);
422 return a_offset < b_offset + ggml_webgpu_tensor_binding_size(b, alignment) &&
423 b_offset < a_offset + ggml_webgpu_tensor_binding_size(a, alignment);
424}
425
426static bool ggml_webgpu_tensor_binding_overlap_range(const webgpu_global_context & global_ctx,
427 ggml_tensor * tensor,
428 ggml_backend_buffer_t buffer,
429 size_t offset,
430 size_t size) {
431 if (tensor->buffer != buffer) {
432 return false;
433 }
434
435 const size_t alignment = global_ctx->capabilities.limits.minStorageBufferOffsetAlignment;
436 const size_t tensor_offset = ggml_webgpu_tensor_align_offset(tensor, alignment);
437 return tensor_offset < offset + size && offset < tensor_offset + ggml_webgpu_tensor_binding_size(tensor, alignment);
438}
439
440struct ggml_webgpu_merged_binding_range {
441 size_t offset;
442 size_t size;
443};
444
445static ggml_webgpu_merged_binding_range ggml_webgpu_tensor_merged_binding_range(
446 webgpu_context & ctx,
447 std::initializer_list<ggml_tensor *> tensors) {
448 size_t merged_offset = SIZE_MAX;
449 size_t merged_end = 0;
450
451 for (ggml_tensor * tensor : tensors) {
452 const size_t bind_offset = ggml_webgpu_tensor_align_offset(ctx, tensor);
453 const size_t bind_end = bind_offset + ggml_webgpu_tensor_binding_size(ctx, tensor);
454
455 merged_offset = std::min(merged_offset, bind_offset);
456 merged_end = std::max(merged_end, bind_end);
457 }
458
459 return { merged_offset, merged_end - merged_offset };
460}
461
462static uint32_t ggml_webgpu_tensor_merged_element_offset(const ggml_tensor * tensor,
463 const ggml_webgpu_merged_binding_range & merged_range) {
464 return (uint32_t) ((ggml_webgpu_tensor_offset(tensor) - merged_range.offset) / ggml_type_size(tensor->type));
465}
466
467static wgpu::BindGroupEntry ggml_webgpu_make_bind_group_entry(uint32_t binding,
468 wgpu::Buffer buffer,
469 uint64_t offset,
470 uint64_t size) {
471 wgpu::BindGroupEntry entry = {};
472 entry.binding = binding;
473 entry.buffer = std::move(buffer);
474 entry.offset = offset;
475 entry.size = size;
476 return entry;
477}
478
479static wgpu::BindGroupEntry ggml_webgpu_make_tensor_bind_group_entry(webgpu_context & ctx,
480 uint32_t binding,
481 ggml_tensor * tensor) {
482 return ggml_webgpu_make_bind_group_entry(binding, ggml_webgpu_tensor_buf(tensor),
483 ggml_webgpu_tensor_align_offset(ctx, tensor),
484 ggml_webgpu_tensor_binding_size(ctx, tensor));
485}
486
487/** End WebGPU object initializations */
488
489/** WebGPU Actions */
490
491template <typename T>
492static void ggml_backend_webgpu_check_wait_status(wgpu::WaitStatus wait_status,
493 T callback_status,
494 T success_status,
495 const char * wait_name,
496 const char * failure_name,
497 const char * callback_message) {
498 if (wait_status == wgpu::WaitStatus::TimedOut) {
499 GGML_ABORT("ggml_webgpu: %s timed out after %u ms\n", wait_name, WEBGPU_RUNTIME_WAIT_TIMEOUT_MS);
500 }
501 if (wait_status == wgpu::WaitStatus::Error) {
502 GGML_ABORT("ggml_webgpu: %s failed\n", wait_name);
503 }
504 if (callback_status != success_status) {
505 GGML_ABORT("ggml_webgpu: %s failed with status %d: %s\n", failure_name, static_cast<int>(callback_status),
506 callback_message);
507 }
508}
509
510// TODO: these next two functions may want tuning across different platforms and workloads,
511static uint32_t ggml_backend_webgpu_get_max_inflight_batches() {
512 return UINT32_MAX;
513}
514
515static uint32_t ggml_backend_webgpu_get_command_submit_batch_size() {
516 return WEBGPU_DEFAULT_COMMAND_SUBMIT_BATCH_SIZE;
517}
518
519static void ggml_backend_webgpu_wait_queue(webgpu_global_context & ctx) {
520 wgpu::QueueWorkDoneStatus callback_status = wgpu::QueueWorkDoneStatus::Error;
521 std::string callback_message;
522
523 const wgpu::WaitStatus wait_status = ctx->instance.WaitAny(
524 ctx->queue.OnSubmittedWorkDone(
525 wgpu::CallbackMode::AllowSpontaneous,
526 [&callback_status, &callback_message](wgpu::QueueWorkDoneStatus status, wgpu::StringView message) {
527 callback_status = status;
528 callback_message = std::string(message);
529 }),
530 WEBGPU_RUNTIME_WAIT_TIMEOUT_NS);
531
532 ggml_backend_webgpu_check_wait_status(wait_status, callback_status, wgpu::QueueWorkDoneStatus::Success,
533 "Queue wait", "Queue work", callback_message.c_str());
534}
535
536static void ggml_backend_webgpu_map_buffer(webgpu_global_context & ctx,
537 wgpu::Buffer & buffer,
538 wgpu::MapMode mode,
539 size_t offset,
540 size_t size) {
541 wgpu::MapAsyncStatus callback_status = wgpu::MapAsyncStatus::Error;
542 std::string callback_message;
543
544 const wgpu::WaitStatus wait_status = ctx->instance.WaitAny(
545 buffer.MapAsync(mode, offset, size, wgpu::CallbackMode::AllowSpontaneous,
546 [&callback_status, &callback_message](wgpu::MapAsyncStatus status, wgpu::StringView message) {
547 callback_status = status;
548 callback_message = std::string(message);
549 }),
550 WEBGPU_RUNTIME_WAIT_TIMEOUT_NS);
551
552 ggml_backend_webgpu_check_wait_status(wait_status, callback_status, wgpu::MapAsyncStatus::Success,
553 "Buffer map wait", "Buffer map", callback_message.c_str());
554}
555
556static void ggml_backend_webgpu_submit_commands(webgpu_context & ctx,
557 const wgpu::CommandBuffer commands,
558 uint32_t & num_inflight_batches) {
559 if (num_inflight_batches >= ctx->global_ctx->max_inflight_batches) {
560 ggml_backend_webgpu_wait_queue(ctx->global_ctx);
561 num_inflight_batches = 0;
562 }
563
564 ctx->global_ctx->queue.Submit(1, &commands);
565 num_inflight_batches++;
566}
567
568#ifdef GGML_WEBGPU_DEBUG
569// This function adds debugging information to shaders, as WebGPU does not support printing directly.
570// To use, add a bind group entry to the setup for the shader you are debugging, add the buffer and
571// debug statements in the shader, and then call this function after encoding the commands and submitting them.
572static void ggml_backend_webgpu_debug(webgpu_global_context & ctx) {
573 wgpu::CommandEncoder encoder = ctx->device.CreateCommandEncoder();
574 encoder.CopyBufferToBuffer(ctx->debug_dev_buf, 0, ctx->debug_host_buf, 0, ctx->debug_host_buf.GetSize());
575 wgpu::CommandBuffer commands = encoder.Finish();
576 ctx->queue.Submit(1, &commands);
577 ggml_backend_webgpu_map_buffer(ctx, ctx->debug_host_buf, wgpu::MapMode::Read, 0, ctx->debug_host_buf.GetSize());
578 const float * debug_data = (const float *) ctx->debug_host_buf.GetConstMappedRange();
579 std::cout << "debug[0]: " << debug_data[0] << "\n";
580 ctx->debug_host_buf.Unmap();
581}
582#endif
583
584static webgpu_encoded_op ggml_backend_webgpu_build_multi(webgpu_context & ctx,
585 const std::vector<webgpu_dispatch_desc> & dispatches) {
586 webgpu_encoded_op result = {};
587 std::vector<wgpu::BindGroup> bind_groups;
588 std::vector<size_t> param_offsets;
589 result.num_kernels = dispatches.size();
590
591 for (size_t i = 0; i < dispatches.size(); i++) {
592 const webgpu_dispatch_desc & dispatch = dispatches[i];
593 const size_t param_size = dispatch.params.size() * sizeof(uint32_t);
594 const size_t param_offset = ctx->param_arena.alloc_slot(param_size);
595
596 std::vector<wgpu::BindGroupEntry> entries = dispatch.bind_group_entries;
597 uint32_t params_binding_num = entries.size();
598 entries.push_back(ggml_webgpu_make_bind_group_entry(params_binding_num, ctx->param_arena.buffer, param_offset,
599 ctx->param_arena.slot_size));
600
601 wgpu::BindGroupDescriptor bind_group_desc;
602 bind_group_desc.layout = dispatch.pipeline.pipeline.GetBindGroupLayout(0);
603 bind_group_desc.entryCount = entries.size();
604 bind_group_desc.entries = entries.data();
605 bind_group_desc.label = dispatch.pipeline.name.c_str();
606 bind_groups.push_back(ctx->global_ctx->device.CreateBindGroup(&bind_group_desc));
607 param_offsets.push_back(param_offset);
608 }
609
610 for (size_t i = 0; i < param_offsets.size(); i++) {
611 ctx->global_ctx->queue.WriteBuffer(ctx->param_arena.buffer, param_offsets[i], dispatches[i].params.data(),
612 dispatches[i].params.size() * sizeof(uint32_t));
613 }
614
615#ifdef GGML_WEBGPU_GPU_PROFILE
616 for (size_t i = 0; i < dispatches.size(); i++) {
617 GGML_ASSERT(ctx->profile_timestamp_query_count + 2 <= WEBGPU_MAX_PROFILE_QUERY_COUNT);
618 const uint32_t query_begin = ctx->profile_timestamp_query_count++;
619 const uint32_t query_end = ctx->profile_timestamp_query_count++;
620
621 wgpu::PassTimestampWrites ts_writes = {};
622 ts_writes.querySet = ctx->profile_timestamp_query_set;
623 ts_writes.beginningOfPassWriteIndex = query_begin;
624 ts_writes.endOfPassWriteIndex = query_end;
625 wgpu::ComputePassDescriptor pass_desc = {};
626 pass_desc.timestampWrites = &ts_writes;
627
628 wgpu::ComputePassEncoder pass = ctx->active_command_encoder.BeginComputePass(&pass_desc);
629
630 pass.SetPipeline(dispatches[i].pipeline.pipeline);
631 pass.SetBindGroup(0, bind_groups[i]);
632 pass.DispatchWorkgroups(dispatches[i].workgroups.first, dispatches[i].workgroups.second, 1);
633 pass.End();
634 result.pipeline_names.push_back(dispatches[i].pipeline.name);
635 }
636#else
637 for (size_t i = 0; i < dispatches.size(); i++) {
638 if (ctx->batch_compute_passes) {
639 ctx->active_compute_pass.SetPipeline(dispatches[i].pipeline.pipeline);
640 ctx->active_compute_pass.SetBindGroup(0, bind_groups[i]);
641 ctx->active_compute_pass.DispatchWorkgroups(dispatches[i].workgroups.first, dispatches[i].workgroups.second,
642 1);
643 } else {
644 wgpu::ComputePassEncoder pass = ctx->active_command_encoder.BeginComputePass();
645 pass.SetPipeline(dispatches[i].pipeline.pipeline);
646 pass.SetBindGroup(0, bind_groups[i]);
647 pass.DispatchWorkgroups(dispatches[i].workgroups.first, dispatches[i].workgroups.second, 1);
648 pass.End();
649 }
650 }
651#endif
652
653 return result;
654}
655
656static webgpu_encoded_op ggml_backend_webgpu_build(webgpu_context & ctx,
657 webgpu_pipeline & pipeline,
658 std::vector<uint32_t> params,
659 std::vector<wgpu::BindGroupEntry> bind_group_entries,
660 uint32_t wg_x,
661 uint32_t wg_y = 1) {
662 return ggml_backend_webgpu_build_multi(
663 ctx, {
664 { pipeline, std::move(params), std::move(bind_group_entries), { wg_x, wg_y } },
665 });
666}
667
668static void ggml_backend_webgpu_buffer_memset(webgpu_global_context & ctx,
669 wgpu::Buffer & buf,
670 uint32_t value,
671 size_t offset,
672 size_t size) {
673 std::lock_guard<std::recursive_mutex> lock(ctx->mutex);
674
675 std::vector<uint32_t> params = { (uint32_t) offset, (uint32_t) size, value };
676 std::vector<wgpu::BindGroupEntry> entries = { ggml_webgpu_make_bind_group_entry(0, buf, 0, buf.GetSize()) };
677 size_t bytes_per_wg =
678 ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup * ctx->capabilities.memset_bytes_per_thread;
679 uint32_t wg_x = CEIL_DIV(size + 3, bytes_per_wg);
680
681 ctx->queue.WriteBuffer(ctx->memset_params_buf, 0, params.data(), params.size() * sizeof(uint32_t));
682
683 wgpu::BindGroupEntry params_entry = {};
684 params_entry.binding = 1;
685 params_entry.buffer = ctx->memset_params_buf;
686 params_entry.offset = 0;
687 params_entry.size = WEBGPU_PARAMS_BUF_SIZE_BYTES;
688 entries.push_back(params_entry);
689
690 wgpu::BindGroupDescriptor bind_group_desc;
691 bind_group_desc.layout = ctx->memset_pipeline.pipeline.GetBindGroupLayout(0);
692 bind_group_desc.entryCount = entries.size();
693 bind_group_desc.entries = entries.data();
694 bind_group_desc.label = ctx->memset_pipeline.name.c_str();
695 wgpu::BindGroup bind_group = ctx->device.CreateBindGroup(&bind_group_desc);
696
697 wgpu::CommandEncoder encoder = ctx->device.CreateCommandEncoder();
698 wgpu::ComputePassEncoder pass = encoder.BeginComputePass();
699 pass.SetPipeline(ctx->memset_pipeline.pipeline);
700 pass.SetBindGroup(0, bind_group);
701 pass.DispatchWorkgroups(wg_x, 1, 1);
702 pass.End();
703
704 wgpu::CommandBuffer command = encoder.Finish();
705 std::vector<wgpu::CommandBuffer> commands = { command };
706 ctx->queue.Submit(commands.size(), commands.data());
707}
708
709/** End WebGPU Actions */
710
711/** GGML Backend Interface */
712
713static const char * ggml_backend_webgpu_name(ggml_backend_t backend) {
714 ggml_backend_webgpu_context * ctx = (ggml_backend_webgpu_context *) backend->context;
715 return ctx->name.c_str();
716}
717
718static void ggml_backend_webgpu_free(ggml_backend_t backend) {
719 ggml_backend_webgpu_context * ctx = (ggml_backend_webgpu_context *) backend->context;
720 WEBGPU_LOG_DEBUG("ggml_backend_webgpu_free(" << ctx->name << ")");
721
722#ifdef GGML_WEBGPU_CPU_PROFILE
723 std::cout << "\n[ggml_webgpu cpu profiling summary]\n";
724 double total_cpu = 0.0;
725 for (const auto & kv : ctx->webgpu_ctx->global_ctx->cpu_time_ms) {
726 total_cpu += kv.second;
727 }
728 std::cout << "ggml_webgpu: total cpu time: " << total_cpu << " ms\n";
729 std::cout << "ggml_webgpu: cpu breakdown:\n";
730 for (const auto & kv : ctx->webgpu_ctx->global_ctx->cpu_time_ms) {
731 double pct = (total_cpu > 0.0) ? (kv.second / total_cpu * 100.0) : 0.0;
732 std::cout << "ggml_webgpu: " << kv.first << ": " << kv.second << " ms (" << pct << "%)\n";
733 }
734 if (ctx->webgpu_ctx->global_ctx->cpu_detail_ms.size() > 0) {
735 std::cout << "ggml_webgpu: cpu detailed breakdown:\n";
736 }
737 for (const auto & kv : ctx->webgpu_ctx->global_ctx->cpu_detail_ms) {
738 double pct = (total_cpu > 0.0) ? (kv.second / total_cpu * 100.0) : 0.0;
739 std::cout << "ggml_webgpu: " << kv.first << ": " << kv.second << " ms (" << pct << "%)\n";
740 }
741#endif
742
743#ifdef GGML_WEBGPU_GPU_PROFILE
744 std::cout << "\n[ggml_webgpu gpu profiling summary]\n";
745 double total_gpu = 0.0;
746 for (const auto & kv : ctx->webgpu_ctx->shader_gpu_time_ms) {
747 total_gpu += kv.second;
748 }
749 std::cout << "ggml_webgpu: total gpu time (all shaders): " << total_gpu << " ms\n";
750 std::cout << "\nggml_webgpu: gpu breakdown:\n";
751 for (const auto & kv : ctx->webgpu_ctx->shader_gpu_time_ms) {
752 double pct = (total_gpu > 0.0) ? (kv.second / total_gpu * 100.0) : 0.0;
753 std::cout << "ggml_webgpu: " << kv.first << ": " << kv.second << " ms (" << std::fixed << std::setprecision(2)
754 << pct << "%)\n";
755 }
756#endif
757
758#if defined(GGML_WEBGPU_CPU_PROFILE) && defined(GGML_WEBGPU_GPU_PROFILE)
759 std::cout << "ggml_webgpu: gpu/cpu ratio: " << (total_cpu > 0.0 ? total_gpu / total_cpu : 0.0) << "\n";
760#endif
761
762 delete ctx;
763 delete backend;
764}
765
766static webgpu_encoded_op ggml_webgpu_cpy(webgpu_context & ctx, ggml_tensor * src, ggml_tensor * dst) {
767 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
768 shader_lib_ctx.src0 = src;
769 shader_lib_ctx.dst = dst;
770 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
771
772 webgpu_pipeline pipeline = ctx->shader_lib->get_cpy_pipeline(shader_lib_ctx);
773
774 auto * decisions = static_cast<ggml_webgpu_generic_shader_decisions *>(pipeline.context.get());
775
776 uint32_t ne = (uint32_t) ggml_nelements(dst);
777
778 std::vector<uint32_t> params = {
779 ne, (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src) / ggml_type_size(src->type)),
780 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
781 // Convert byte-strides to element-strides
782 (uint32_t) (src->nb[0] / ggml_type_size(src->type)), (uint32_t) (src->nb[1] / ggml_type_size(src->type)),
783 (uint32_t) (src->nb[2] / ggml_type_size(src->type)), (uint32_t) (src->nb[3] / ggml_type_size(src->type)),
784 (uint32_t) (dst->nb[0] / ggml_type_size(dst->type)), (uint32_t) (dst->nb[1] / ggml_type_size(dst->type)),
785 (uint32_t) (dst->nb[2] / ggml_type_size(dst->type)), (uint32_t) (dst->nb[3] / ggml_type_size(dst->type)),
786 // Logical shapes
787 (uint32_t) src->ne[0], (uint32_t) src->ne[1], (uint32_t) src->ne[2], (uint32_t) dst->ne[0],
788 (uint32_t) dst->ne[1], (uint32_t) dst->ne[2]
789 };
790
791 std::vector<wgpu::BindGroupEntry> entries = {
792 ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src),
793 ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, dst),
794 };
795
796 uint32_t wg_x;
797 uint32_t wg_y;
798 uint32_t total_wg = CEIL_DIV(ne, decisions->wg_size);
799 compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y);
800 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
801}
802
803static webgpu_encoded_op ggml_webgpu_set(webgpu_context & ctx,
804 ggml_tensor * src0,
805 ggml_tensor * src1,
806 ggml_tensor * dst) {
807 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
808 shader_lib_ctx.src0 = src0;
809 shader_lib_ctx.src1 = src1;
810 shader_lib_ctx.dst = dst;
811 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
812
813 webgpu_pipeline pipeline = ctx->shader_lib->get_set_pipeline(shader_lib_ctx);
814
815 auto * decisions = static_cast<ggml_webgpu_generic_shader_decisions *>(pipeline.context.get());
816 const bool inplace = decisions->inplace;
817
818 const uint32_t ne = inplace ? (uint32_t) ggml_nelements(src1) : (uint32_t) ggml_nelements(dst);
819 const uint32_t dst_type_size = (uint32_t) ggml_type_size(dst->type);
820
821 std::vector<uint32_t> params = {
822 ne,
823 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src0) / ggml_type_size(src0->type)),
824 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src1) / ggml_type_size(src1->type)),
825 (uint32_t) (((const int32_t *) dst->op_params)[3] / dst_type_size),
826
827 (uint32_t) (src1->nb[0] / ggml_type_size(src1->type)),
828 (uint32_t) (src1->nb[1] / ggml_type_size(src1->type)),
829 (uint32_t) (src1->nb[2] / ggml_type_size(src1->type)),
830 (uint32_t) (src1->nb[3] / ggml_type_size(src1->type)),
831
832 1u,
833 (uint32_t) (((const int32_t *) dst->op_params)[0] / dst_type_size),
834 (uint32_t) (((const int32_t *) dst->op_params)[1] / dst_type_size),
835 (uint32_t) (((const int32_t *) dst->op_params)[2] / dst_type_size),
836
837 (uint32_t) src1->ne[0],
838 (uint32_t) src1->ne[1],
839 (uint32_t) src1->ne[2],
840 (uint32_t) src1->ne[3],
841 };
842
843 std::vector<wgpu::BindGroupEntry> entries;
844 uint32_t binding_index = 0;
845 if (!inplace) {
846 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src0));
847 binding_index++;
848 }
849 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding_index, src1));
850 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding_index + 1, dst));
851
852 uint32_t wg_x;
853 uint32_t wg_y;
854 uint32_t total_wg = CEIL_DIV(ne, decisions->wg_size);
855 compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y);
856 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
857}
858
859static webgpu_encoded_op ggml_webgpu_arange(webgpu_context & ctx, ggml_tensor * dst) {
860 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
861 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
862
863 webgpu_pipeline pipeline = ctx->shader_lib->get_arange_pipeline(shader_lib_ctx);
864 auto * decisions = static_cast<ggml_webgpu_generic_shader_decisions *>(pipeline.context.get());
865
866 const uint32_t ne = (uint32_t) ggml_nelements(dst);
867 std::vector<uint32_t> params = {
868 ne,
869 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
870 ggml_webgpu_u32_from_f32(ggml_get_op_params_f32(dst, 0)),
871 ggml_webgpu_u32_from_f32(ggml_get_op_params_f32(dst, 2)),
872 };
873
874 std::vector<wgpu::BindGroupEntry> entries = {
875 ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, dst),
876 };
877
878 uint32_t wg_x;
879 uint32_t wg_y;
880 uint32_t total_wg = CEIL_DIV(ne, decisions->wg_size);
881 compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y);
882 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
883}
884
885static webgpu_encoded_op ggml_webgpu_pad(webgpu_context & ctx, ggml_tensor * src, ggml_tensor * dst) {
886 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
887 shader_lib_ctx.src0 = src;
888 shader_lib_ctx.dst = dst;
889 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
890
891 webgpu_pipeline pipeline = ctx->shader_lib->get_pad_pipeline(shader_lib_ctx);
892
893 auto * decisions = static_cast<ggml_webgpu_generic_shader_decisions *>(pipeline.context.get());
894
895 const uint32_t ne = (uint32_t) ggml_nelements(dst);
896
897 std::vector<uint32_t> params = {
898 ne,
899 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src) / ggml_type_size(src->type)),
900 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
901 // Strides (in elements)
902 (uint32_t) (src->nb[0] / ggml_type_size(src->type)),
903 (uint32_t) (src->nb[1] / ggml_type_size(src->type)),
904 (uint32_t) (src->nb[2] / ggml_type_size(src->type)),
905 (uint32_t) (src->nb[3] / ggml_type_size(src->type)),
906 // Shapes
907 (uint32_t) src->ne[0],
908 (uint32_t) src->ne[1],
909 (uint32_t) src->ne[2],
910 (uint32_t) src->ne[3],
911 (uint32_t) dst->ne[0],
912 (uint32_t) dst->ne[1],
913 (uint32_t) dst->ne[2],
914 (uint32_t) dst->ne[3],
915 // Pad sizes
916 (uint32_t) ggml_get_op_params_i32(dst, 0),
917 (uint32_t) ggml_get_op_params_i32(dst, 1),
918 (uint32_t) ggml_get_op_params_i32(dst, 2),
919 (uint32_t) ggml_get_op_params_i32(dst, 3),
920 (uint32_t) ggml_get_op_params_i32(dst, 4),
921 (uint32_t) ggml_get_op_params_i32(dst, 5),
922 (uint32_t) ggml_get_op_params_i32(dst, 6),
923 (uint32_t) ggml_get_op_params_i32(dst, 7),
924 };
925
926 std::vector<wgpu::BindGroupEntry> entries = {
927 ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src),
928 ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, dst),
929 };
930
931 uint32_t wg_x;
932 uint32_t wg_y;
933 uint32_t total_wg = CEIL_DIV(ne, decisions->wg_size);
934 compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y);
935 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
936}
937
938static webgpu_encoded_op ggml_webgpu_solve_tri(webgpu_context & ctx,
939 ggml_tensor * src0,
940 ggml_tensor * src1,
941 ggml_tensor * dst) {
942 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
943 shader_lib_ctx.src0 = src0;
944 shader_lib_ctx.src1 = src1;
945 shader_lib_ctx.dst = dst;
946 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
947 shader_lib_ctx.wg_mem_limit_bytes = ctx->global_ctx->capabilities.limits.maxComputeWorkgroupStorageSize;
948
949 webgpu_pipeline pipeline = ctx->shader_lib->get_solve_tri_pipeline(shader_lib_ctx);
950
951 auto * decisions = static_cast<ggml_webgpu_generic_shader_decisions *>(pipeline.context.get());
952
953 std::vector<uint32_t> params = {
954 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src0) / ggml_type_size(src0->type)),
955 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src1) / ggml_type_size(src1->type)),
956 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
957
958 (uint32_t) (src0->nb[0] / ggml_type_size(src0->type)),
959 (uint32_t) (src0->nb[1] / ggml_type_size(src0->type)),
960 (uint32_t) (src0->nb[2] / ggml_type_size(src0->type)),
961 (uint32_t) (src0->nb[3] / ggml_type_size(src0->type)),
962
963 (uint32_t) (src1->nb[0] / ggml_type_size(src1->type)),
964 (uint32_t) (src1->nb[1] / ggml_type_size(src1->type)),
965 (uint32_t) (src1->nb[2] / ggml_type_size(src1->type)),
966 (uint32_t) (src1->nb[3] / ggml_type_size(src1->type)),
967
968 (uint32_t) (dst->nb[0] / ggml_type_size(dst->type)),
969 (uint32_t) (dst->nb[1] / ggml_type_size(dst->type)),
970 (uint32_t) (dst->nb[2] / ggml_type_size(dst->type)),
971 (uint32_t) (dst->nb[3] / ggml_type_size(dst->type)),
972
973 (uint32_t) src1->ne[0],
974 (uint32_t) dst->ne[2],
975 };
976
977 std::vector<wgpu::BindGroupEntry> entries = {
978 ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src0),
979 ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, src1),
980 ggml_webgpu_make_tensor_bind_group_entry(ctx, 2, dst),
981 };
982
983 const uint32_t wg_x = CEIL_DIV((uint32_t) src1->ne[0], decisions->wg_size);
984 const uint32_t wg_y = (uint32_t) (dst->ne[2] * dst->ne[3]);
985 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
986}
987
988static webgpu_encoded_op ggml_webgpu_conv_2d(webgpu_context & ctx,
989 ggml_tensor * src0,
990 ggml_tensor * src1,
991 ggml_tensor * dst) {
992 const int32_t s0 = ggml_get_op_params_i32(dst, 0);
993 const int32_t s1 = ggml_get_op_params_i32(dst, 1);
994 const int32_t p0 = ggml_get_op_params_i32(dst, 2);
995 const int32_t p1 = ggml_get_op_params_i32(dst, 3);
996 const int32_t d0 = ggml_get_op_params_i32(dst, 4);
997 const int32_t d1 = ggml_get_op_params_i32(dst, 5);
998
999 std::vector<uint32_t> params = {
1000 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src0) / ggml_type_size(src0->type)),
1001 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src1) / ggml_type_size(src1->type)),
1002 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
1003
1004 (uint32_t) (src0->nb[0] / ggml_type_size(src0->type)),
1005 (uint32_t) (src0->nb[1] / ggml_type_size(src0->type)),
1006 (uint32_t) (src0->nb[2] / ggml_type_size(src0->type)),
1007 (uint32_t) (src0->nb[3] / ggml_type_size(src0->type)),
1008
1009 (uint32_t) (src1->nb[0] / ggml_type_size(src1->type)),
1010 (uint32_t) (src1->nb[1] / ggml_type_size(src1->type)),
1011 (uint32_t) (src1->nb[2] / ggml_type_size(src1->type)),
1012 (uint32_t) (src1->nb[3] / ggml_type_size(src1->type)),
1013
1014 (uint32_t) (dst->nb[0] / ggml_type_size(dst->type)),
1015 (uint32_t) (dst->nb[1] / ggml_type_size(dst->type)),
1016 (uint32_t) (dst->nb[2] / ggml_type_size(dst->type)),
1017 (uint32_t) (dst->nb[3] / ggml_type_size(dst->type)),
1018
1019 (uint32_t) src0->ne[0],
1020 (uint32_t) src0->ne[1],
1021 (uint32_t) src0->ne[2],
1022
1023 (uint32_t) src1->ne[0],
1024 (uint32_t) src1->ne[1],
1025
1026 (uint32_t) dst->ne[0],
1027 (uint32_t) dst->ne[1],
1028 (uint32_t) dst->ne[2],
1029 (uint32_t) dst->ne[3],
1030
1031 (uint32_t) s0,
1032 (uint32_t) s1,
1033 (uint32_t) p0,
1034 (uint32_t) p1,
1035 (uint32_t) d0,
1036 (uint32_t) d1,
1037 };
1038
1039 std::vector<wgpu::BindGroupEntry> entries = {
1040 ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src0),
1041 ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, src1),
1042 ggml_webgpu_make_tensor_bind_group_entry(ctx, 2, dst),
1043 };
1044
1045 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
1046 shader_lib_ctx.src0 = src0;
1047 shader_lib_ctx.src1 = src1;
1048 shader_lib_ctx.dst = dst;
1049 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
1050
1051 webgpu_pipeline pipeline = ctx->shader_lib->get_conv2d_pipeline(shader_lib_ctx);
1052
1053 auto * decisions = static_cast<ggml_webgpu_generic_shader_decisions *>(pipeline.context.get());
1054
1055 uint32_t wg_x;
1056 uint32_t wg_y;
1057 uint32_t total_wg = CEIL_DIV((uint32_t) ggml_nelements(dst), decisions->wg_size);
1058 compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y);
1059
1060 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
1061}
1062
1063// Same param/binding layout as conv_2d; the shader differs
1064static webgpu_encoded_op ggml_webgpu_conv_2d_dw(webgpu_context & ctx,
1065 ggml_tensor * src0,
1066 ggml_tensor * src1,
1067 ggml_tensor * dst) {
1068 const int32_t s0 = ggml_get_op_params_i32(dst, 0);
1069 const int32_t s1 = ggml_get_op_params_i32(dst, 1);
1070 const int32_t p0 = ggml_get_op_params_i32(dst, 2);
1071 const int32_t p1 = ggml_get_op_params_i32(dst, 3);
1072 const int32_t d0 = ggml_get_op_params_i32(dst, 4);
1073 const int32_t d1 = ggml_get_op_params_i32(dst, 5);
1074
1075 // Scalar params matching conv2d_dw.wgsl (weight src0 [KW,KH,1,C], input src1, output dst).
1076 std::vector<uint32_t> params = {
1077 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src0) / ggml_type_size(src0->type)),
1078 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src1) / ggml_type_size(src1->type)),
1079 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
1080
1081 (uint32_t) ggml_nelements(dst),
1082 (uint32_t) dst->ne[2],
1083 (uint32_t) dst->ne[0],
1084 (uint32_t) dst->ne[1],
1085 (uint32_t) src1->ne[0],
1086 (uint32_t) src1->ne[1],
1087 (uint32_t) src0->ne[0],
1088 (uint32_t) src0->ne[1],
1089
1090 (uint32_t) s0,
1091 (uint32_t) s1,
1092 (uint32_t) p0,
1093 (uint32_t) p1,
1094 (uint32_t) d0,
1095 (uint32_t) d1,
1096 };
1097
1098 std::vector<wgpu::BindGroupEntry> entries = {
1099 ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src0),
1100 ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, src1),
1101 ggml_webgpu_make_tensor_bind_group_entry(ctx, 2, dst),
1102 };
1103
1104 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
1105 shader_lib_ctx.src0 = src0;
1106 shader_lib_ctx.src1 = src1;
1107 shader_lib_ctx.dst = dst;
1108 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
1109
1110 // Input layout: contiguous -> WHCN, contiguous-channels -> CWHN
1111 const bool whcn = ggml_is_contiguous(src1);
1112 webgpu_pipeline pipeline = ctx->shader_lib->get_conv2d_dw_pipeline(shader_lib_ctx, whcn);
1113 auto * decisions = static_cast<ggml_webgpu_generic_shader_decisions *>(pipeline.context.get());
1114
1115 uint32_t wg_x;
1116 uint32_t wg_y;
1117 uint32_t total_wg = CEIL_DIV((uint32_t) ggml_nelements(dst), decisions->wg_size);
1118 compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y);
1119
1120 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
1121}
1122
1123static webgpu_encoded_op ggml_webgpu_im2col(webgpu_context & ctx,
1124 ggml_tensor * src0,
1125 ggml_tensor * src1,
1126 ggml_tensor * dst) {
1127 const int32_t s0 = ggml_get_op_params_i32(dst, 0);
1128 const int32_t s1 = ggml_get_op_params_i32(dst, 1);
1129 const int32_t p0 = ggml_get_op_params_i32(dst, 2);
1130 const int32_t p1 = ggml_get_op_params_i32(dst, 3);
1131 const int32_t d0 = ggml_get_op_params_i32(dst, 4);
1132 const int32_t d1 = ggml_get_op_params_i32(dst, 5);
1133 const bool is_2D = ggml_get_op_params_i32(dst, 6) == 1;
1134
1135 const uint32_t KW = src0->ne[0];
1136 const uint32_t KH = is_2D ? src0->ne[1] : 1;
1137 const uint32_t IC = is_2D ? src0->ne[2] : src0->ne[1];
1138
1139 const uint32_t IW = src1->ne[0];
1140 const uint32_t IH = is_2D ? src1->ne[1] : 1;
1141 const uint32_t N = is_2D ? src1->ne[3] : src1->ne[2];
1142
1143 const uint32_t OW = dst->ne[1];
1144 const uint32_t OH = is_2D ? dst->ne[2] : 1;
1145
1146 const uint32_t si0 = (uint32_t) (src1->nb[0] / ggml_type_size(src1->type));
1147 const uint32_t si1 = is_2D ? (uint32_t) (src1->nb[1] / ggml_type_size(src1->type)) : 0;
1148 const uint32_t si2 = is_2D ? (uint32_t) (src1->nb[2] / ggml_type_size(src1->type)) :
1149 (uint32_t) (src1->nb[1] / ggml_type_size(src1->type));
1150 const uint32_t si3 = is_2D ? (uint32_t) (src1->nb[3] / ggml_type_size(src1->type)) :
1151 (uint32_t) (src1->nb[2] / ggml_type_size(src1->type));
1152
1153 const uint32_t so0 = (uint32_t) (dst->nb[0] / ggml_type_size(dst->type));
1154 const uint32_t so1 = (uint32_t) (dst->nb[1] / ggml_type_size(dst->type));
1155 const uint32_t so2 = is_2D ? (uint32_t) (dst->nb[2] / ggml_type_size(dst->type)) : 0;
1156 const uint32_t so3 = is_2D ? (uint32_t) (dst->nb[3] / ggml_type_size(dst->type)) :
1157 (uint32_t) (dst->nb[2] / ggml_type_size(dst->type));
1158
1159 std::vector<uint32_t> params = {
1160 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src1) / ggml_type_size(src1->type)),
1161 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
1162
1163 si0,
1164 si1,
1165 si2,
1166 si3,
1167 so0,
1168 so1,
1169 so2,
1170 so3,
1171
1172 KW,
1173 KH,
1174 IC,
1175
1176 IW,
1177 IH,
1178 N,
1179
1180 OW,
1181 OH,
1182
1183 (uint32_t) s0,
1184 (uint32_t) s1,
1185 (uint32_t) p0,
1186 (uint32_t) p1,
1187 (uint32_t) d0,
1188 (uint32_t) d1,
1189 };
1190
1191 std::vector<wgpu::BindGroupEntry> entries = {
1192 ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src1),
1193 ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, dst),
1194 };
1195
1196 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
1197 shader_lib_ctx.src0 = src0;
1198 shader_lib_ctx.src1 = src1;
1199 shader_lib_ctx.dst = dst;
1200 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
1201
1202 webgpu_pipeline pipeline = ctx->shader_lib->get_im2col_pipeline(shader_lib_ctx);
1203
1204 auto * decisions = static_cast<ggml_webgpu_generic_shader_decisions *>(pipeline.context.get());
1205
1206 uint32_t wg_x;
1207 uint32_t wg_y;
1208 uint32_t total_wg = CEIL_DIV((uint32_t) ggml_nelements(dst), decisions->wg_size);
1209 compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y);
1210
1211 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
1212}
1213
1214static webgpu_encoded_op ggml_webgpu_ssm_conv(webgpu_context & ctx,
1215 ggml_tensor * src0,
1216 ggml_tensor * src1,
1217 ggml_tensor * dst) {
1218 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
1219 shader_lib_ctx.src0 = src0;
1220 shader_lib_ctx.src1 = src1;
1221 shader_lib_ctx.dst = dst;
1222 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
1223
1224 webgpu_pipeline pipeline = ctx->shader_lib->get_ssm_conv_pipeline(shader_lib_ctx);
1225 auto * decisions = static_cast<ggml_webgpu_ssm_conv_shader_decisions *>(pipeline.context.get());
1226
1227 const uint32_t token_tiles = CEIL_DIV((uint32_t) dst->ne[1], decisions->tokens_per_wg);
1228
1229 std::vector<uint32_t> params = {
1230 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src0) / ggml_type_size(src0->type)),
1231 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src1) / ggml_type_size(src1->type)),
1232 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
1233
1234 (uint32_t) (src0->nb[1] / ggml_type_size(src0->type)),
1235 (uint32_t) (src0->nb[2] / ggml_type_size(src0->type)),
1236 (uint32_t) (src1->nb[1] / ggml_type_size(src1->type)),
1237
1238 (uint32_t) (dst->nb[0] / ggml_type_size(dst->type)),
1239 (uint32_t) (dst->nb[1] / ggml_type_size(dst->type)),
1240 (uint32_t) (dst->nb[2] / ggml_type_size(dst->type)),
1241
1242 (uint32_t) src1->ne[0],
1243 (uint32_t) src0->ne[1],
1244 (uint32_t) dst->ne[1],
1245 (uint32_t) dst->ne[2],
1246 token_tiles,
1247 };
1248
1249 std::vector<wgpu::BindGroupEntry> entries = {
1250 ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src0),
1251 ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, src1),
1252 ggml_webgpu_make_tensor_bind_group_entry(ctx, 2, dst),
1253 };
1254
1255 const uint32_t wg_x = CEIL_DIV((uint32_t) src0->ne[1], decisions->block_size);
1256 const uint32_t wg_y = token_tiles * (uint32_t) dst->ne[2];
1257 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
1258}
1259
1260static webgpu_encoded_op ggml_webgpu_ssm_scan(webgpu_context & ctx,
1261 ggml_tensor * src0,
1262 ggml_tensor * src1,
1263 ggml_tensor * src2,
1264 ggml_tensor * src3,
1265 ggml_tensor * src4,
1266 ggml_tensor * src5,
1267 ggml_tensor * src6,
1268 ggml_tensor * dst) {
1269 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
1270 shader_lib_ctx.src0 = src0;
1271 shader_lib_ctx.src1 = src1;
1272 shader_lib_ctx.src2 = src2;
1273 shader_lib_ctx.src3 = src3;
1274 shader_lib_ctx.src4 = src4;
1275 shader_lib_ctx.src5 = src5;
1276 shader_lib_ctx.dst = dst;
1277 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
1278 shader_lib_ctx.supports_subgroups = ctx->global_ctx->capabilities.supports_subgroups;
1279
1280 uint8_t xbc_overlap = 0;
1281 if (ggml_webgpu_tensor_binding_overlap(ctx->global_ctx, src1, src4)) {
1282 xbc_overlap |= 0b110; // x/B
1283 }
1284 if (ggml_webgpu_tensor_binding_overlap(ctx->global_ctx, src1, src5)) {
1285 xbc_overlap |= 0b101; // x/C
1286 }
1287 if (ggml_webgpu_tensor_binding_overlap(ctx->global_ctx, src4, src5)) {
1288 xbc_overlap |= 0b011; // B/C
1289 }
1290
1291 webgpu_pipeline pipeline = ctx->shader_lib->get_ssm_scan_pipeline(shader_lib_ctx, xbc_overlap);
1292 auto * decisions = static_cast<ggml_webgpu_ssm_scan_shader_decisions *>(pipeline.context.get());
1293 xbc_overlap = decisions->xbc_overlap;
1294
1295 uint32_t offset_x = (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src1) / ggml_type_size(src1->type));
1296 uint32_t offset_dt = (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src2) / ggml_type_size(src2->type));
1297 uint32_t offset_A = (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src3) / ggml_type_size(src3->type));
1298 uint32_t offset_B = (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src4) / ggml_type_size(src4->type));
1299 uint32_t offset_C = (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src5) / ggml_type_size(src5->type));
1300 uint32_t offset_ids = (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src6) / ggml_type_size(src6->type));
1301
1302 ggml_webgpu_merged_binding_range xbc_merged_range = {};
1303
1304 if (xbc_overlap == 0b110) { // x/B
1305 xbc_merged_range = ggml_webgpu_tensor_merged_binding_range(ctx, { src1, src4 });
1306 offset_x = ggml_webgpu_tensor_merged_element_offset(src1, xbc_merged_range);
1307 offset_B = ggml_webgpu_tensor_merged_element_offset(src4, xbc_merged_range);
1308 } else if (xbc_overlap == 0b011) { // B/C
1309 xbc_merged_range = ggml_webgpu_tensor_merged_binding_range(ctx, { src4, src5 });
1310 offset_B = ggml_webgpu_tensor_merged_element_offset(src4, xbc_merged_range);
1311 offset_C = ggml_webgpu_tensor_merged_element_offset(src5, xbc_merged_range);
1312 } else if (xbc_overlap == 0b111) { // x/B/C
1313 xbc_merged_range = ggml_webgpu_tensor_merged_binding_range(ctx, { src1, src4, src5 });
1314 offset_x = ggml_webgpu_tensor_merged_element_offset(src1, xbc_merged_range);
1315 offset_B = ggml_webgpu_tensor_merged_element_offset(src4, xbc_merged_range);
1316 offset_C = ggml_webgpu_tensor_merged_element_offset(src5, xbc_merged_range);
1317 }
1318
1319 GGML_ASSERT(xbc_overlap == 0 || xbc_overlap == 0b110 || xbc_overlap == 0b011 || xbc_overlap == 0b111);
1320
1321 size_t xbc_bind_offset = 0;
1322 size_t xbc_bind_size = 0;
1323 if (xbc_overlap > 0) {
1324 xbc_bind_offset = xbc_merged_range.offset;
1325 xbc_bind_size = xbc_merged_range.size;
1326 }
1327
1328 std::vector<uint32_t> params = {
1329 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src0) / ggml_type_size(src0->type)),
1330 offset_x,
1331 offset_dt,
1332 offset_A,
1333 offset_B,
1334 offset_C,
1335 offset_ids,
1336 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
1337
1338 (uint32_t) (src0->nb[1] / ggml_type_size(src0->type)),
1339 (uint32_t) (src0->nb[2] / ggml_type_size(src0->type)),
1340 (uint32_t) (src0->nb[3] / ggml_type_size(src0->type)),
1341
1342 (uint32_t) (src1->nb[1] / ggml_type_size(src1->type)),
1343 (uint32_t) (src1->nb[2] / ggml_type_size(src1->type)),
1344 (uint32_t) (src1->nb[3] / ggml_type_size(src1->type)),
1345
1346 (uint32_t) (src2->nb[1] / ggml_type_size(src2->type)),
1347 (uint32_t) (src2->nb[2] / ggml_type_size(src2->type)),
1348
1349 (uint32_t) src3->ne[0],
1350 (uint32_t) (src3->nb[1] / ggml_type_size(src3->type)),
1351
1352 (uint32_t) (src4->nb[1] / ggml_type_size(src4->type)),
1353 (uint32_t) (src4->nb[2] / ggml_type_size(src4->type)),
1354 (uint32_t) (src4->nb[3] / ggml_type_size(src4->type)),
1355
1356 (uint32_t) (src5->nb[1] / ggml_type_size(src5->type)),
1357 (uint32_t) (src5->nb[2] / ggml_type_size(src5->type)),
1358 (uint32_t) (src5->nb[3] / ggml_type_size(src5->type)),
1359
1360 (uint32_t) src0->ne[0],
1361 (uint32_t) src0->ne[1],
1362 (uint32_t) src0->ne[2],
1363 (uint32_t) src4->ne[1],
1364 (uint32_t) src1->ne[2],
1365 (uint32_t) ggml_nelements(src1),
1366 (uint32_t) ggml_get_op_params_i32(dst, 0),
1367 };
1368
1369 uint32_t binding_num = 0;
1370
1371 std::vector<wgpu::BindGroupEntry> entries = {
1372 ggml_webgpu_make_tensor_bind_group_entry(ctx, binding_num++, src0),
1373 };
1374 // xbc_merged binding
1375 if (xbc_overlap > 0) {
1376 entries.push_back(ggml_webgpu_make_bind_group_entry(binding_num++, ggml_webgpu_tensor_buf(src1),
1377 xbc_bind_offset, xbc_bind_size));
1378 }
1379 // x
1380 if (!(xbc_overlap & 0b100)) {
1381 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding_num++, src1));
1382 }
1383 // B
1384 if (!(xbc_overlap & 0b010)) {
1385 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding_num++, src4));
1386 }
1387 // C
1388 if (!(xbc_overlap & 0b001)) {
1389 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding_num++, src5));
1390 }
1391
1392 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding_num++, src2));
1393 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding_num++, src3));
1394 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding_num++, src6));
1395 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding_num++, dst));
1396
1397 const uint32_t total_wg = (uint32_t) (src0->ne[1] * src0->ne[2] * src1->ne[3]);
1398 const uint32_t max_wg_per_dim = ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension;
1399 uint32_t wg_x;
1400 uint32_t wg_y;
1401 compute_2d_workgroups(total_wg, max_wg_per_dim, wg_x, wg_y);
1402
1403 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
1404}
1405
1406static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx,
1407 ggml_tensor * src0,
1408 ggml_tensor * src1,
1409 ggml_tensor * src2,
1410 ggml_tensor * src3,
1411 ggml_tensor * src4,
1412 ggml_tensor * src5,
1413 ggml_tensor * dst,
1414 ggml_tensor * dst_fuse) {
1415 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
1416 shader_lib_ctx.src0 = src0;
1417 shader_lib_ctx.src1 = src1;
1418 shader_lib_ctx.src2 = src2;
1419 shader_lib_ctx.src3 = src3;
1420 shader_lib_ctx.src4 = src4;
1421 shader_lib_ctx.dst = dst;
1422 shader_lib_ctx.dst_fuse = dst_fuse;
1423 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
1424
1425 webgpu_pipeline pipeline = ctx->shader_lib->get_gated_delta_net_pipeline(shader_lib_ctx);
1426
1427 const uint32_t s_v = (uint32_t) src2->ne[0];
1428 const uint32_t h = (uint32_t) src2->ne[1];
1429 const uint32_t n_tokens = (uint32_t) src2->ne[2];
1430 const uint32_t n_seqs = (uint32_t) src2->ne[3];
1431 const uint32_t K = (uint32_t) ggml_get_op_params_i32(dst, 0);
1432 const float scale = 1.0f / sqrtf((float) s_v);
1433 uint32_t scale_u32;
1434 memcpy(&scale_u32, &scale, sizeof(scale_u32));
1435
1436 std::vector<uint32_t> params = {
1437 h,
1438 n_tokens,
1439 n_seqs,
1440 s_v * h * n_tokens * n_seqs,
1441
1442 (uint32_t) (src0->nb[1] / ggml_type_size(src0->type)),
1443 (uint32_t) (src0->nb[2] / ggml_type_size(src0->type)),
1444 (uint32_t) (src0->nb[3] / ggml_type_size(src0->type)),
1445
1446 (uint32_t) (src2->nb[1] / ggml_type_size(src2->type)),
1447 (uint32_t) (src2->nb[2] / ggml_type_size(src2->type)),
1448 (uint32_t) (src2->nb[3] / ggml_type_size(src2->type)),
1449
1450 (uint32_t) (src4->nb[1] / ggml_type_size(src4->type)),
1451 (uint32_t) (src4->nb[2] / ggml_type_size(src4->type)),
1452 (uint32_t) (src4->nb[3] / ggml_type_size(src4->type)),
1453
1454 (uint32_t) src0->ne[1],
1455 (uint32_t) (src2->ne[3] / src0->ne[3]),
1456 K,
1457 scale_u32,
1458 dst_fuse ? (uint32_t) (dst_fuse->nb[2] / ggml_type_size(dst_fuse->type)) : 0,
1459 dst_fuse ? (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst_fuse) / ggml_type_size(dst_fuse->type)) : 0,
1460 };
1461
1462 std::vector<wgpu::BindGroupEntry> entries = {
1463 ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src0), ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, src1),
1464 ggml_webgpu_make_tensor_bind_group_entry(ctx, 2, src2), ggml_webgpu_make_tensor_bind_group_entry(ctx, 3, src3),
1465 ggml_webgpu_make_tensor_bind_group_entry(ctx, 4, src4), ggml_webgpu_make_tensor_bind_group_entry(ctx, 5, src5),
1466 ggml_webgpu_make_tensor_bind_group_entry(ctx, 6, dst),
1467 };
1468
1469 if (dst_fuse) {
1470 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 7, dst_fuse));
1471 }
1472
1473 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, h, n_seqs);
1474}
1475
1476static std::optional<webgpu_encoded_op> ggml_webgpu_set_rows(webgpu_context & ctx,
1477 ggml_tensor * src,
1478 ggml_tensor * idx,
1479 ggml_tensor * dst) {
1480 // For set rows specifically, we need to check if src and idx are empty
1481 // tensors.
1482 if (ggml_is_empty(src) || ggml_is_empty(idx)) {
1483 return std::nullopt;
1484 }
1485
1486 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
1487 shader_lib_ctx.src0 = src;
1488 shader_lib_ctx.src1 = idx;
1489 shader_lib_ctx.dst = dst;
1490 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
1491
1492 webgpu_pipeline pipeline = ctx->shader_lib->get_set_rows_pipeline(shader_lib_ctx);
1493
1494 auto * decisions = static_cast<ggml_webgpu_set_rows_shader_decisions *>(pipeline.context.get());
1495
1496 std::vector<uint32_t> params = {
1497 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src) / ggml_type_size(src->type)),
1498 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, idx) / ggml_type_size(idx->type)),
1499 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
1500 // Convert byte-strides to element-strides
1501 (uint32_t) (src->nb[1] / ggml_type_size(src->type)), (uint32_t) (src->nb[2] / ggml_type_size(src->type)),
1502 (uint32_t) (src->nb[3] / ggml_type_size(src->type)), (uint32_t) (idx->nb[0] / ggml_type_size(idx->type)),
1503 (uint32_t) (idx->nb[1] / ggml_type_size(idx->type)), (uint32_t) (idx->nb[2] / ggml_type_size(idx->type)),
1504 (uint32_t) (dst->nb[1] / ggml_type_size(dst->type)), (uint32_t) (dst->nb[2] / ggml_type_size(dst->type)),
1505 (uint32_t) (dst->nb[3] / ggml_type_size(dst->type)),
1506 // Shape of src
1507 (uint32_t) src->ne[0], (uint32_t) src->ne[1], (uint32_t) src->ne[2], (uint32_t) src->ne[3],
1508 // Shape of idx
1509 (uint32_t) (idx->ne[1]), (uint32_t) (idx->ne[2])
1510 };
1511
1512 std::vector<wgpu::BindGroupEntry> entries;
1513 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src));
1514 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, idx));
1515 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 2, dst));
1516
1517 if (decisions->i64_idx) {
1518 entries.push_back(ggml_webgpu_make_bind_group_entry(3, ctx->set_rows_dev_error_buf, 0,
1519 ctx->set_rows_dev_error_buf.GetSize()));
1520 }
1521
1522 uint32_t threads;
1523 if (ggml_is_quantized(dst->type)) {
1524 const uint32_t blocks_per_row = src->ne[0] / ggml_blck_size(dst->type);
1525 threads =
1526 (src->ne[1] * src->ne[2] * src->ne[3]) * (decisions->pair_blocks ? (blocks_per_row / 2) : blocks_per_row);
1527 } else if (decisions->vec4) {
1528 threads = (src->ne[1] * src->ne[2] * src->ne[3]) * (src->ne[0] / 4);
1529 } else {
1530 threads = src->ne[0] * src->ne[1] * src->ne[2] * src->ne[3];
1531 }
1532 uint32_t wg_x;
1533 uint32_t wg_y;
1534 uint32_t total_wg = CEIL_DIV(threads, decisions->wg_size);
1535 compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y);
1536 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
1537}
1538
1539// Workgroup size is a common constant
1540static std::vector<wgpu::ConstantEntry> ggml_webgpu_wg_size_entry(uint32_t wg_size) {
1541 std::vector<wgpu::ConstantEntry> constants(1);
1542 constants[0].key = "wg_size";
1543 constants[0].value = wg_size;
1544 return constants;
1545}
1546
1547static webgpu_encoded_op ggml_webgpu_get_rows(webgpu_context & ctx,
1548 ggml_tensor * src,
1549 ggml_tensor * idx,
1550 ggml_tensor * dst) {
1551 const bool float_parallel = src->type == GGML_TYPE_F32 || src->type == GGML_TYPE_F16 || src->type == GGML_TYPE_I32;
1552
1553 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
1554 shader_lib_ctx.src0 = src;
1555 shader_lib_ctx.src1 = nullptr;
1556 shader_lib_ctx.dst = dst;
1557 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
1558
1559 const uint32_t offset_src = (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src) / ggml_type_size(src->type));
1560 const uint32_t offset_dst = (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type));
1561 const uint32_t stride_src1 = (uint32_t) (src->nb[1] / ggml_type_size(src->type));
1562 const uint32_t stride_src2 = (uint32_t) (src->nb[2] / ggml_type_size(src->type));
1563 const uint32_t stride_src3 = (uint32_t) (src->nb[3] / ggml_type_size(src->type));
1564
1565 const bool vec4_aligned = offset_src % 4 == 0 && offset_dst % 4 == 0 && stride_src1 % 4 == 0 &&
1566 stride_src2 % 4 == 0 && stride_src3 % 4 == 0;
1567
1568 webgpu_pipeline pipeline = ctx->shader_lib->get_get_rows_pipeline(shader_lib_ctx, vec4_aligned);
1569 auto * decisions = static_cast<ggml_webgpu_get_rows_shader_decisions *>(pipeline.context.get());
1570
1571 std::vector<uint32_t> params = { offset_src,
1572 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, idx) / ggml_type_size(idx->type)),
1573 offset_dst,
1574 stride_src1,
1575 stride_src2,
1576 stride_src3,
1577 (uint32_t) (idx->nb[0] / ggml_type_size(idx->type)),
1578 (uint32_t) (idx->nb[1] / ggml_type_size(idx->type)),
1579 (uint32_t) (idx->nb[2] / ggml_type_size(idx->type)),
1580 (uint32_t) (dst->nb[1] / ggml_type_size(dst->type)),
1581 (uint32_t) (dst->nb[2] / ggml_type_size(dst->type)),
1582 (uint32_t) (dst->nb[3] / ggml_type_size(dst->type)),
1583 (uint32_t) dst->ne[0],
1584 (uint32_t) dst->ne[1],
1585 (uint32_t) dst->ne[2],
1586 (uint32_t) dst->ne[3],
1587 (uint32_t) (idx->ne[1]),
1588 (uint32_t) (idx->ne[2]) };
1589
1590 std::vector<wgpu::BindGroupEntry> entries = { ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src),
1591 ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, idx),
1592 ggml_webgpu_make_tensor_bind_group_entry(ctx, 2, dst) };
1593
1594 uint32_t blocks_per_row = (uint32_t) (dst->ne[0] / (decisions->vectorized ? 4 : 1));
1595 uint32_t total_rows = (uint32_t) (dst->ne[1] * dst->ne[2] * dst->ne[3]);
1596 uint32_t total_threads = float_parallel ? blocks_per_row * total_rows : total_rows;
1597 uint32_t wg_x;
1598 uint32_t wg_y;
1599 uint32_t total_wg = CEIL_DIV(total_threads, decisions->wg_size);
1600 compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y);
1601 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
1602}
1603
1604static void ggml_webgpu_quantize_q8_dispatch(webgpu_context & ctx,
1605 ggml_tensor * src0,
1606 ggml_tensor * src1,
1607 ggml_tensor * dst,
1608 std::vector<webgpu_dispatch_desc> & dispatches) {
1609 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
1610
1611 shader_lib_ctx.src0 = src0;
1612 shader_lib_ctx.src1 = src1;
1613 shader_lib_ctx.dst = dst;
1614 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
1615 shader_lib_ctx.supports_subgroups = ctx->global_ctx->capabilities.supports_subgroups;
1616
1617 webgpu_pipeline qq8_pipeline = ctx->shader_lib->get_quantize_q8_pipeline(shader_lib_ctx);
1618
1619 // quantize_q8 pipeline
1620 const size_t dst_offset = ggml_webgpu_tensor_offset(dst);
1621 const size_t q8_src1_align_offset = ROUNDUP_POW2(
1622 dst_offset + ggml_nbytes(dst), ctx->global_ctx->capabilities.limits.minStorageBufferOffsetAlignment);
1623 const size_t q8_src1_binding_size = ROUNDUP_POW2(
1624 src1->ne[3] * src1->ne[2] * src1->ne[1] * (36 /* sizeof(q8_1) */ * (src1->ne[0] / /* block_size */ 32)),
1625 WEBGPU_STORAGE_BUF_BINDING_MULT);
1626
1627 std::vector<uint32_t> q8_params = {
1628 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src1) / ggml_type_size(src1->type)),
1629 (uint32_t) (src1->nb[1] / ggml_type_size(src1->type)),
1630 (uint32_t) (src1->nb[2] / ggml_type_size(src1->type)),
1631 (uint32_t) (src1->nb[3] / ggml_type_size(src1->type)),
1632 (uint32_t) src1->ne[0],
1633 (uint32_t) src1->ne[1],
1634 (uint32_t) src1->ne[2],
1635 (uint32_t) src1->ne[3],
1636 };
1637
1638 std::vector<wgpu::BindGroupEntry> q8_entries = {
1639 ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src1),
1640 ggml_webgpu_make_bind_group_entry(1, ggml_webgpu_tensor_buf(dst), q8_src1_align_offset, q8_src1_binding_size)
1641 };
1642
1643 auto q8_decisions = static_cast<ggml_webgpu_generic_shader_decisions *>(qq8_pipeline.context.get());
1644
1645 uint32_t q8_wg_size = q8_decisions->wg_size;
1646 uint32_t q8_wg_x = 1;
1647 uint32_t q8_wg_y = 1;
1648 const uint32_t wg_per_vec = (src0->ne[0] / 4 + (q8_wg_size - 1)) / q8_wg_size;
1649 const uint32_t q8_total_wg = src1->ne[1] * src1->ne[2] * src1->ne[3] * wg_per_vec;
1650 const uint32_t max_wg_per_dim = ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension;
1651 compute_2d_workgroups(q8_total_wg, max_wg_per_dim, q8_wg_x, q8_wg_y);
1652
1653 dispatches.push_back({
1654 qq8_pipeline, std::move(q8_params), std::move(q8_entries), { q8_wg_x, q8_wg_y }
1655 });
1656}
1657
1658static webgpu_encoded_op ggml_webgpu_mul_mat(webgpu_context & ctx,
1659 ggml_tensor * src0,
1660 ggml_tensor * src1,
1661 ggml_tensor * dst) {
1662 // Determine if this is a mat-vec operation
1663 bool use_mat_vec = (dst->ne[1] <= GGML_WEBGPU_MUL_MAT_VEC_MAX_ROWS);
1664
1665 // use MMVQ path for mat-vec
1666 bool use_mmvq = ggml_webgpu_can_use_mmvq(
1667 src0, src1, src1->ne[1], ctx->global_ctx->capabilities.supports_dot_product, ctx->global_ctx->vendor);
1668
1669 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
1670
1671 shader_lib_ctx.src0 = src0;
1672 shader_lib_ctx.src1 = src1;
1673 shader_lib_ctx.dst = dst;
1674 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
1675 shader_lib_ctx.supports_subgroups = ctx->global_ctx->capabilities.supports_subgroups;
1676 shader_lib_ctx.supports_subgroup_matrix = ctx->global_ctx->capabilities.supports_subgroup_matrix;
1677 shader_lib_ctx.sg_mat_m = ctx->global_ctx->capabilities.sg_mat_m;
1678 shader_lib_ctx.sg_mat_n = ctx->global_ctx->capabilities.sg_mat_n;
1679 shader_lib_ctx.sg_mat_k = ctx->global_ctx->capabilities.sg_mat_k;
1680 shader_lib_ctx.min_subgroup_size = ctx->global_ctx->capabilities.min_subgroup_size;
1681 shader_lib_ctx.max_subgroup_size = ctx->global_ctx->capabilities.max_subgroup_size;
1682 shader_lib_ctx.supports_dot_product = ctx->global_ctx->capabilities.supports_dot_product;
1683 shader_lib_ctx.vendor = ctx->global_ctx->vendor;
1684
1685 // Get or create pipeline
1686 webgpu_pipeline pipeline;
1687 std::vector<webgpu_dispatch_desc> dispatches;
1688 const bool src_overlap = ggml_webgpu_tensor_binding_overlap(ctx->global_ctx, src0, src1) && !use_mmvq;
1689
1690 if (use_mat_vec) {
1691 if (use_mmvq) {
1692 ggml_webgpu_quantize_q8_dispatch(ctx, src0, src1, dst, dispatches);
1693 }
1694 pipeline = ctx->shader_lib->get_mul_mat_vec_pipeline(shader_lib_ctx, src_overlap);
1695 } else {
1696 pipeline = ctx->shader_lib->get_mul_mat_fast_pipeline(shader_lib_ctx, src_overlap);
1697 }
1698
1699 uint32_t offset_src0 = (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src0) / ggml_type_size(src0->type));
1700 uint32_t offset_src1 = (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src1) / ggml_type_size(src1->type));
1701 size_t merged_offset = 0;
1702 size_t merged_size = 0;
1703 if (src_overlap) {
1704 const ggml_webgpu_merged_binding_range merged_range =
1705 ggml_webgpu_tensor_merged_binding_range(ctx, { src0, src1 });
1706 merged_offset = merged_range.offset;
1707 merged_size = merged_range.size;
1708 offset_src0 = ggml_webgpu_tensor_merged_element_offset(src0, merged_range);
1709 offset_src1 = ggml_webgpu_tensor_merged_element_offset(src1, merged_range);
1710 }
1711
1712 // Build params
1713 std::vector<uint32_t> params = { offset_src0,
1714 offset_src1,
1715 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
1716 (uint32_t) dst->ne[0],
1717 (uint32_t) dst->ne[1],
1718 (uint32_t) src0->ne[0],
1719 (uint32_t) (src0->nb[1] / ggml_type_size(src0->type)),
1720 (uint32_t) (src1->nb[1] / ggml_type_size(src1->type)),
1721 (uint32_t) (src0->nb[2] / ggml_type_size(src0->type)),
1722 (uint32_t) (src1->nb[2] / ggml_type_size(src1->type)),
1723 (uint32_t) (src0->nb[3] / ggml_type_size(src0->type)),
1724 (uint32_t) (src1->nb[3] / ggml_type_size(src1->type)),
1725 (uint32_t) src0->ne[2],
1726 (uint32_t) src0->ne[3],
1727 (uint32_t) (src1->ne[2] / src0->ne[2]),
1728 (uint32_t) (src1->ne[3] / src0->ne[3]) };
1729
1730 // Build bind group entries
1731 std::vector<wgpu::BindGroupEntry> entries = {};
1732 if (use_mmvq) {
1733 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src0));
1734 auto & mmvq_qq8_entry = dispatches[0].bind_group_entries[1];
1735 entries.push_back(ggml_webgpu_make_bind_group_entry(1, ggml_webgpu_tensor_buf(dst), mmvq_qq8_entry.offset,
1736 mmvq_qq8_entry.size));
1737 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 2, dst));
1738 } else if (src_overlap) {
1739 entries.push_back(
1740 ggml_webgpu_make_bind_group_entry(0, ggml_webgpu_tensor_buf(src0), merged_offset, merged_size));
1741 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, dst));
1742 } else {
1743 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src0));
1744 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, src1));
1745 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 2, dst));
1746 }
1747
1748 // Calculate workgroup dimensions
1749 uint32_t wg_x = 1;
1750 uint32_t wg_y = 1;
1751 const uint32_t max_wg_per_dim = ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension;
1752
1753 if (use_mat_vec) {
1754 auto * decisions = static_cast<ggml_webgpu_mul_mat_vec_shader_decisions *>(pipeline.context.get());
1755
1756 uint32_t batches = dst->ne[2] * dst->ne[3];
1757 uint32_t output_groups = CEIL_DIV(dst->ne[0], decisions->outputs_per_wg);
1758 uint32_t total_wg = output_groups * batches;
1759 compute_2d_workgroups(total_wg, max_wg_per_dim, wg_x, wg_y);
1760 } else {
1761 auto * decisions = static_cast<ggml_webgpu_mul_mat_shader_decisions *>(pipeline.context.get());
1762
1763 // Fast-path tiled/subgroup calculations
1764 uint32_t wg_m;
1765 uint32_t wg_n;
1766 if (decisions->use_subgroup_matrix) {
1767 uint32_t wg_m_sg_tile =
1768 decisions->subgroup_m * decisions->subgroup_matrix_m * ctx->global_ctx->capabilities.sg_mat_m;
1769 wg_m = CEIL_DIV(dst->ne[0], wg_m_sg_tile);
1770 uint32_t wg_n_sg_tile =
1771 decisions->subgroup_n * decisions->subgroup_matrix_n * ctx->global_ctx->capabilities.sg_mat_n;
1772 wg_n = CEIL_DIV(dst->ne[1], wg_n_sg_tile);
1773 } else {
1774 uint32_t tile_m_s = decisions->tile_m * decisions->wg_size_m;
1775 uint32_t tile_n_s = decisions->tile_n * decisions->wg_size_n;
1776 wg_m = CEIL_DIV(dst->ne[0], tile_m_s);
1777 wg_n = CEIL_DIV(dst->ne[1], tile_n_s);
1778 }
1779 uint32_t total_wg = wg_m * wg_n * dst->ne[2] * dst->ne[3];
1780 compute_2d_workgroups(total_wg, max_wg_per_dim, wg_x, wg_y);
1781 }
1782
1783 dispatches.push_back({
1784 pipeline, std::move(params), std::move(entries), { wg_x, wg_y }
1785 });
1786
1787 return ggml_backend_webgpu_build_multi(ctx, dispatches);
1788}
1789
1790static webgpu_encoded_op ggml_webgpu_mul_mat_id_vec(webgpu_context & ctx,
1791 ggml_tensor * src0,
1792 ggml_tensor * src1,
1793 ggml_tensor * src2,
1794 ggml_tensor * dst) {
1795 const uint32_t param_n_expert = (uint32_t) src0->ne[2];
1796 const uint32_t param_n_expert_used = (uint32_t) dst->ne[1];
1797
1798 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
1799 shader_lib_ctx.src0 = src0;
1800 shader_lib_ctx.src1 = src1;
1801 shader_lib_ctx.src2 = src2;
1802 shader_lib_ctx.dst = dst;
1803 shader_lib_ctx.supports_subgroups = ctx->global_ctx->capabilities.supports_subgroups;
1804 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
1805
1806 webgpu_pipeline pipeline = ctx->shader_lib->get_mul_mat_id_vec_pipeline(shader_lib_ctx);
1807
1808 std::vector<uint32_t> params = {
1809 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src0) / ggml_type_size(src0->type)),
1810 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src1) / ggml_type_size(src1->type)),
1811 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src2) / ggml_type_size(src2->type)),
1812 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
1813 (uint32_t) src0->ne[0],
1814 (uint32_t) src0->ne[1],
1815 param_n_expert,
1816 param_n_expert_used,
1817 (uint32_t) src1->ne[1],
1818 (uint32_t) (src0->nb[1] / ggml_type_size(src0->type)),
1819 (uint32_t) (src1->nb[1] / ggml_type_size(src1->type)),
1820 (uint32_t) (src0->nb[2] / ggml_type_size(src0->type)),
1821 (uint32_t) (src1->nb[2] / ggml_type_size(src1->type)),
1822 };
1823
1824 std::vector<wgpu::BindGroupEntry> entries = {
1825 ggml_webgpu_make_bind_group_entry(0, ggml_webgpu_tensor_buf(src0), ggml_webgpu_tensor_align_offset(ctx, src0),
1826 ggml_webgpu_tensor_binding_size(ctx, src0)),
1827 ggml_webgpu_make_bind_group_entry(1, ggml_webgpu_tensor_buf(src1), ggml_webgpu_tensor_align_offset(ctx, src1),
1828 ggml_webgpu_tensor_binding_size(ctx, src1)),
1829 ggml_webgpu_make_bind_group_entry(2, ggml_webgpu_tensor_buf(src2), ggml_webgpu_tensor_align_offset(ctx, src2),
1830 ggml_webgpu_tensor_binding_size(ctx, src2)),
1831 ggml_webgpu_make_bind_group_entry(3, ggml_webgpu_tensor_buf(dst), ggml_webgpu_tensor_align_offset(ctx, dst),
1832 ggml_webgpu_tensor_binding_size(ctx, dst)),
1833 };
1834
1835 uint32_t wg_x = 1;
1836 uint32_t wg_y = 1;
1837
1838 auto * decisions = static_cast<ggml_webgpu_mul_mat_vec_shader_decisions *>(pipeline.context.get());
1839
1840 const uint32_t max_wg_per_dim = ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension;
1841 uint32_t output_groups = CEIL_DIV(dst->ne[0], decisions->outputs_per_wg);
1842 uint32_t total_wg = output_groups * param_n_expert_used;
1843 compute_2d_workgroups(total_wg, max_wg_per_dim, wg_x, wg_y);
1844
1845 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
1846}
1847
1848// upper bound on the number of slot tiles emitted by mul_mat_id_gather.wgsl
1849static uint32_t ggml_webgpu_mul_mat_id_max_tiles(const ggml_tensor * dst) {
1850 const uint32_t n_expert = (uint32_t) dst->src[0]->ne[2];
1851 const uint32_t n_slots = (uint32_t) (dst->ne[1] * dst->ne[2]); // n_expert_used * n_tokens
1852
1853 return CEIL_DIV(n_slots, WEBGPU_MUL_MAT_TILE_N * WEBGPU_MUL_MAT_WG_SIZE_N) + std::min(n_expert, n_slots);
1854}
1855
1856// tile count followed by (expert, first slot, n slots) per tile
1857static size_t ggml_webgpu_mul_mat_id_tiles_nbytes(const ggml_tensor * dst) {
1858 return (1 + 3 * (size_t) ggml_webgpu_mul_mat_id_max_tiles(dst)) * sizeof(uint32_t);
1859}
1860
1861static webgpu_encoded_op ggml_webgpu_mul_mat_id(webgpu_context & ctx,
1862 ggml_tensor * src0,
1863 ggml_tensor * src1,
1864 ggml_tensor * src2,
1865 ggml_tensor * dst) {
1866 // we can use mat-vec fast path
1867 if (dst->ne[2] == 1) {
1868 return ggml_webgpu_mul_mat_id_vec(ctx, src0, src1, src2, dst);
1869 }
1870
1871 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
1872 shader_lib_ctx.src0 = src0;
1873 shader_lib_ctx.src1 = src1;
1874 shader_lib_ctx.src2 = src2;
1875 shader_lib_ctx.dst = dst;
1876 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
1877
1878 // Get or create pipeline
1879 webgpu_pipeline gather_pipeline;
1880 webgpu_pipeline main_pipeline;
1881
1882 std::vector<webgpu_dispatch_desc> dispatches;
1883
1884 gather_pipeline = ctx->shader_lib->get_mul_mat_id_gather_pipeline(shader_lib_ctx);
1885 main_pipeline = ctx->shader_lib->get_mul_mat_id_pipeline(shader_lib_ctx);
1886
1887 const uint32_t param_n_expert = (uint32_t) src0->ne[2];
1888 const uint32_t param_n_expert_used = (uint32_t) dst->ne[1];
1889 const uint32_t param_n_tokens = (uint32_t) dst->ne[2];
1890
1891 // params for mul_mat_id_gather.wgsl
1892 std::vector<uint32_t> gather_params = {
1893 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src2) / ggml_type_size(src2->type)),
1894 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
1895 param_n_expert,
1896 param_n_expert_used,
1897 param_n_tokens,
1898 (uint32_t) (src2->nb[1] / ggml_type_size(src2->type)),
1899 (uint32_t) dst->ne[0],
1900 };
1901
1902 const size_t dst_offset = ggml_webgpu_tensor_offset(dst);
1903 const size_t ids_cache_nbytes = src2->ne[0] * src1->ne[2] * sizeof(uint32_t);
1904 const size_t ids_tiles_nbytes = ggml_webgpu_mul_mat_id_tiles_nbytes(dst);
1905
1906 const size_t ids_cache_align_offset = ROUNDUP_POW2(
1907 dst_offset + ggml_nbytes(dst), ctx->global_ctx->capabilities.limits.minStorageBufferOffsetAlignment);
1908 const size_t ids_tiles_align_offset =
1909 ROUNDUP_POW2(ids_cache_align_offset + ids_cache_nbytes,
1910 ctx->global_ctx->capabilities.limits.minStorageBufferOffsetAlignment);
1911
1912 const size_t ids_cache_bind_size = ROUNDUP_POW2(ids_cache_nbytes, WEBGPU_STORAGE_BUF_BINDING_MULT);
1913 const size_t ids_tiles_bind_size = ROUNDUP_POW2(ids_tiles_nbytes, WEBGPU_STORAGE_BUF_BINDING_MULT);
1914
1915 // bind group entries for mul_mat_id_gather.wgsl
1916 std::vector<wgpu::BindGroupEntry> gather_entries = {
1917 ggml_webgpu_make_bind_group_entry(0, ggml_webgpu_tensor_buf(src2), ggml_webgpu_tensor_align_offset(ctx, src2),
1918 ggml_webgpu_tensor_binding_size(ctx, src2)),
1919 ggml_webgpu_make_bind_group_entry(1, ggml_webgpu_tensor_buf(dst), ids_cache_align_offset, ids_cache_bind_size),
1920 ggml_webgpu_make_bind_group_entry(2, ggml_webgpu_tensor_buf(dst), ids_tiles_align_offset, ids_tiles_bind_size),
1921 ggml_webgpu_make_bind_group_entry(3, ggml_webgpu_tensor_buf(dst), ggml_webgpu_tensor_align_offset(ctx, dst),
1922 ggml_webgpu_tensor_binding_size(ctx, dst)),
1923 };
1924
1925 dispatches.push_back({
1926 gather_pipeline, std::move(gather_params), std::move(gather_entries), { 1, 1 }
1927 });
1928
1929 // params for mul_mat_id.wgsl
1930 std::vector<uint32_t> main_params = {
1931 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src0) / ggml_type_size(src0->type)),
1932 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src1) / ggml_type_size(src1->type)),
1933 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
1934 (uint32_t) src0->ne[0],
1935 (uint32_t) src0->ne[1],
1936 param_n_expert,
1937 param_n_expert_used,
1938 param_n_tokens,
1939 (uint32_t) src1->ne[1],
1940 (uint32_t) (src0->nb[1] / ggml_type_size(src0->type)),
1941 (uint32_t) (src1->nb[1] / ggml_type_size(src1->type)),
1942 (uint32_t) (src0->nb[2] / ggml_type_size(src0->type)),
1943 (uint32_t) (src1->nb[2] / ggml_type_size(src1->type)),
1944 };
1945
1946 // bind group entries for mul_mat_id.wgsl
1947 std::vector<wgpu::BindGroupEntry> main_entries = {
1948 ggml_webgpu_make_bind_group_entry(0, ggml_webgpu_tensor_buf(src0), ggml_webgpu_tensor_align_offset(ctx, src0),
1949 ggml_webgpu_tensor_binding_size(ctx, src0)),
1950 ggml_webgpu_make_bind_group_entry(1, ggml_webgpu_tensor_buf(src1), ggml_webgpu_tensor_align_offset(ctx, src1),
1951 ggml_webgpu_tensor_binding_size(ctx, src1)),
1952 ggml_webgpu_make_bind_group_entry(2, ggml_webgpu_tensor_buf(dst), ggml_webgpu_tensor_align_offset(ctx, dst),
1953 ggml_webgpu_tensor_binding_size(ctx, dst)),
1954 ggml_webgpu_make_bind_group_entry(3, ggml_webgpu_tensor_buf(dst), ids_cache_align_offset, ids_cache_bind_size),
1955 ggml_webgpu_make_bind_group_entry(4, ggml_webgpu_tensor_buf(dst), ids_tiles_align_offset, ids_tiles_bind_size),
1956 };
1957
1958 // Calculate workgroup dimensions
1959 uint32_t wg_x = 1;
1960 uint32_t wg_y = 1;
1961
1962 auto * main_decisions = static_cast<ggml_webgpu_mul_mat_shader_decisions *>(main_pipeline.context.get());
1963
1964 // must match `TILE_N_SLOTS` of mul_mat_id_gather.wgsl
1965 GGML_ASSERT(main_decisions->tile_n * main_decisions->wg_size_n == WEBGPU_MUL_MAT_TILE_N * WEBGPU_MUL_MAT_WG_SIZE_N);
1966
1967 const uint32_t tile_m_s = main_decisions->tile_m * main_decisions->wg_size_m;
1968 const uint32_t wg_m = CEIL_DIV(dst->ne[0], tile_m_s);
1969 const uint32_t total_wg = wg_m * ggml_webgpu_mul_mat_id_max_tiles(dst);
1970
1971 compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y);
1972
1973 dispatches.push_back({
1974 main_pipeline, std::move(main_params), std::move(main_entries), { wg_x, wg_y }
1975 });
1976
1977 return ggml_backend_webgpu_build_multi(ctx, dispatches);
1978}
1979
1980struct ggml_webgpu_flash_attn_op {
1981 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
1982 std::vector<uint32_t> params;
1983 std::vector<wgpu::BindGroupEntry> entries;
1984 size_t kv_bind_offset = 0;
1985 size_t kv_bind_size = 0;
1986 bool has_mask = false;
1987 bool has_sinks = false;
1988 bool kv_overlap = false;
1989};
1990
1991static bool ggml_webgpu_flash_attn_use_vec_path(const webgpu_global_context & global_ctx,
1992 const ggml_tensor * Q,
1993 const ggml_tensor * K,
1994 const ggml_tensor * V,
1995 int64_t n_q) {
1996 const size_t storage_offset_alignment = global_ctx->capabilities.limits.minStorageBufferOffsetAlignment;
1997
1998 const bool k_float_vec4_aligned = (K->type != GGML_TYPE_F16 && K->type != GGML_TYPE_F32) ||
1999 ggml_webgpu_flash_attn_float_vec4_aligned(K, storage_offset_alignment);
2000 const bool v_float_vec4_aligned = (V->type != GGML_TYPE_F16 && V->type != GGML_TYPE_F32) ||
2001 ggml_webgpu_flash_attn_float_vec4_aligned(V, storage_offset_alignment);
2002
2003 const uint32_t k_vec_head_align =
2004 ggml_is_quantized(K->type) ? ggml_blck_size(K->type) : GGML_WEBGPU_FLASH_ATTN_TILE_KV_VEC_WIDTH;
2005 const uint32_t v_vec_head_align =
2006 ggml_is_quantized(V->type) ? ggml_blck_size(V->type) : GGML_WEBGPU_FLASH_ATTN_TILE_KV_VEC_WIDTH;
2007 const bool kv_vec_head_dims_aligned = Q->ne[0] % k_vec_head_align == 0 && V->ne[0] % v_vec_head_align == 0;
2008
2009 return global_ctx->capabilities.supports_subgroups && (n_q < GGML_WEBGPU_FLASH_ATTN_VEC_MAX_SEQ_LEN) &&
2010 kv_vec_head_dims_aligned && k_float_vec4_aligned && v_float_vec4_aligned;
2011}
2012
2013static ggml_webgpu_flash_attn_op ggml_webgpu_flash_attn_prepare(webgpu_context & ctx,
2014 ggml_tensor * Q,
2015 ggml_tensor * K,
2016 ggml_tensor * V,
2017 ggml_tensor * mask,
2018 ggml_tensor * sinks,
2019 ggml_tensor * dst) {
2020 float scale = ggml_get_op_params_f32(dst, 0);
2021 float max_bias = ggml_get_op_params_f32(dst, 1);
2022 float logit_softcap = ggml_get_op_params_f32(dst, 2);
2023 if (logit_softcap != 0.0f) {
2024 scale /= logit_softcap;
2025 }
2026 float n_head_log2 = float(1u << (uint32_t) floor(log2(Q->ne[2])));
2027 float m0 = powf(2.0f, -(max_bias) / n_head_log2);
2028 float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
2029
2030 ggml_webgpu_flash_attn_op op = {};
2031 op.shader_lib_ctx.src0 = Q;
2032 op.shader_lib_ctx.src1 = K;
2033 op.shader_lib_ctx.src2 = V;
2034 op.shader_lib_ctx.src3 = mask;
2035 op.shader_lib_ctx.src4 = sinks;
2036 op.shader_lib_ctx.dst = dst;
2037 op.shader_lib_ctx.supports_subgroups = ctx->global_ctx->capabilities.supports_subgroups;
2038 op.shader_lib_ctx.supports_subgroup_matrix = ctx->global_ctx->capabilities.supports_subgroup_matrix;
2039 op.shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
2040 op.shader_lib_ctx.wg_mem_limit_bytes = ctx->global_ctx->capabilities.limits.maxComputeWorkgroupStorageSize;
2041 op.shader_lib_ctx.sg_mat_m = ctx->global_ctx->capabilities.sg_mat_m;
2042 op.shader_lib_ctx.sg_mat_n = ctx->global_ctx->capabilities.sg_mat_n;
2043 op.shader_lib_ctx.sg_mat_k = ctx->global_ctx->capabilities.sg_mat_k;
2044 op.shader_lib_ctx.min_subgroup_size = ctx->global_ctx->capabilities.min_subgroup_size;
2045 op.shader_lib_ctx.max_subgroup_size = ctx->global_ctx->capabilities.max_subgroup_size;
2046
2047 op.has_mask = mask != nullptr;
2048 op.has_sinks = sinks != nullptr;
2049 op.kv_overlap = ggml_webgpu_tensor_binding_overlap(ctx->global_ctx, K, V);
2050
2051 uint32_t offset_k = (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, K) / ggml_type_size(K->type));
2052 uint32_t offset_v = (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, V) / ggml_type_size(V->type));
2053 if (op.kv_overlap) {
2054 const ggml_webgpu_merged_binding_range merged_range = ggml_webgpu_tensor_merged_binding_range(ctx, { K, V });
2055 op.kv_bind_offset = merged_range.offset;
2056 op.kv_bind_size = merged_range.size;
2057 offset_k = ggml_webgpu_tensor_merged_element_offset(K, merged_range);
2058 offset_v = ggml_webgpu_tensor_merged_element_offset(V, merged_range);
2059 }
2060
2061 op.params = {
2062 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, Q) / ggml_type_size(Q->type)),
2063 offset_k,
2064 offset_v,
2065 op.has_mask ? (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, mask) / ggml_type_size(mask->type)) : 0,
2066 op.has_sinks ? (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, sinks) / ggml_type_size(sinks->type)) : 0,
2067 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
2068 (uint32_t) Q->ne[2], // number of heads
2069 (uint32_t) Q->ne[1], // sequence length (Q)
2070 (uint32_t) K->ne[1], // sequence length (K/V)
2071 (uint32_t) (Q->nb[1] / ggml_type_size(Q->type)), // stride (elements/blocks) of Q in dimension 1
2072 (uint32_t) (Q->nb[2] / ggml_type_size(Q->type)), // stride (elements/blocks) of Q in dimension 2
2073 (uint32_t) (Q->nb[3] / ggml_type_size(Q->type)), // stride (elements/blocks) of Q in dimension 3
2074 (uint32_t) (K->nb[1] / ggml_type_size(K->type)), // stride (elements/blocks) of K in dimension 1
2075 (uint32_t) (K->nb[2] / ggml_type_size(K->type)), // stride (elements/blocks) of K in dimension 2
2076 (uint32_t) (K->nb[3] / ggml_type_size(K->type)), // stride (elements/blocks) of K in dimension 3
2077 (uint32_t) (V->nb[1] / ggml_type_size(V->type)), // stride (elements/blocks) of V in dimension 1
2078 (uint32_t) (V->nb[2] / ggml_type_size(V->type)), // stride (elements/blocks) of V in dimension 2
2079 (uint32_t) (V->nb[3] / ggml_type_size(V->type)), // stride (elements/blocks) of V in dimension 3
2080 op.has_mask ? (uint32_t) (mask->nb[3] / ggml_type_size(mask->type)) : 0, // stride of mask dim 3
2081 (uint32_t) (Q->ne[2] / K->ne[2]), // repeat factor for K/V in dim 2 (MHA/MQA/GQA)
2082 ggml_webgpu_u32_from_f32(scale), // scale (possibly adjusted for logit softcap)
2083 ggml_webgpu_u32_from_f32(max_bias),
2084 ggml_webgpu_u32_from_f32(logit_softcap),
2085 ggml_webgpu_u32_from_f32(n_head_log2),
2086 ggml_webgpu_u32_from_f32(m0),
2087 ggml_webgpu_u32_from_f32(m1)
2088 };
2089 op.entries = {
2090 ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, Q),
2091 };
2092 if (op.kv_overlap) {
2093 op.entries.push_back(
2094 ggml_webgpu_make_bind_group_entry(1, ggml_webgpu_tensor_buf(K), op.kv_bind_offset, op.kv_bind_size));
2095 } else {
2096 op.entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, K));
2097 op.entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 2, V));
2098 }
2099 uint32_t binding_index = op.kv_overlap ? 2u : 3u;
2100 if (op.has_mask) {
2101 op.entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding_index++, mask));
2102 }
2103 if (op.has_sinks) {
2104 op.entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding_index++, sinks));
2105 }
2106 op.entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding_index++, dst));
2107
2108 return op;
2109}
2110
2111static uint32_t ggml_webgpu_flash_attn_vec_nwg(uint32_t vec_nwg_cap, uint32_t kv_tile, uint32_t seq_len_kv) {
2112 uint32_t nwg = 1u;
2113 const uint64_t kv_span = (uint64_t) kv_tile;
2114 while ((2u * nwg * kv_span) < (uint64_t) seq_len_kv && nwg < vec_nwg_cap) {
2115 nwg <<= 1;
2116 }
2117 return std::min(nwg, vec_nwg_cap);
2118}
2119
2120static webgpu_encoded_op ggml_webgpu_flash_attn_direct(webgpu_context & ctx, const ggml_webgpu_flash_attn_op & op) {
2121 webgpu_pipeline pipeline = ctx->shader_lib->get_flash_attn_pipeline(op.shader_lib_ctx, op.kv_overlap);
2122 auto * decisions = static_cast<ggml_webgpu_flash_attn_decisions *>(pipeline.context.get());
2123 uint32_t wg_per_head = CEIL_DIV(op.shader_lib_ctx.src0->ne[1], decisions->q_tile);
2124 uint32_t wg_x = wg_per_head * op.shader_lib_ctx.src0->ne[2] * op.shader_lib_ctx.src0->ne[3];
2125 return ggml_backend_webgpu_build(ctx, pipeline, op.params, op.entries, wg_x);
2126}
2127
2128static webgpu_encoded_op ggml_webgpu_flash_attn_vec(webgpu_context & ctx,
2129 ggml_tensor * Q,
2130 ggml_tensor * K,
2131 ggml_tensor * V,
2132 ggml_tensor * mask,
2133 ggml_tensor * sinks,
2134 ggml_tensor * dst,
2135 ggml_webgpu_flash_attn_op op) {
2136 webgpu_pipeline pipeline = ctx->shader_lib->get_flash_attn_vec_pipeline(op.shader_lib_ctx, op.kv_overlap);
2137 auto * decisions = static_cast<ggml_webgpu_flash_attn_vec_decisions *>(pipeline.context.get());
2138
2139 wgpu::Buffer blk_buf = {};
2140 uint64_t blk_size_bytes = 0;
2141 uint32_t blk_nblk0 = 0;
2142 uint32_t blk_nblk1 = 0;
2143 uint32_t blk_batch_count = 0;
2144
2145 const uint32_t vec_nwg_cap = ctx->global_ctx->capabilities.min_subgroup_size;
2146 uint32_t nwg = ggml_webgpu_flash_attn_vec_nwg(vec_nwg_cap, decisions->kv_tile, (uint32_t) K->ne[1]);
2147 const uint64_t nrows = (uint64_t) Q->ne[1] * Q->ne[2] * Q->ne[3];
2148 const bool use_vec_reduce = nwg > 1u;
2149 GGML_ASSERT(nrows <= UINT32_MAX);
2150
2151 uint64_t tmp_stats_base = 0;
2152 uint64_t tmp_size_bytes = 0;
2153 wgpu::Buffer tmp_buf = {};
2154 uint64_t tmp_bind_offset = 0;
2155 uint64_t tmp_bind_size = 0;
2156 const size_t align_bytes = ctx->global_ctx->capabilities.limits.minStorageBufferOffsetAlignment;
2157 const size_t dst_offset = ggml_webgpu_tensor_offset(dst);
2158 size_t scratch_offset = ROUNDUP_POW2(dst_offset + ggml_nbytes(dst), align_bytes);
2159
2160 if (use_vec_reduce) {
2161 const uint64_t tmp_data_elems = nrows * (uint64_t) V->ne[0] * nwg;
2162 const uint64_t tmp_stats_elems = nrows * 2u * nwg;
2163 tmp_stats_base = tmp_data_elems;
2164 tmp_size_bytes =
2165 ROUNDUP_POW2((tmp_data_elems + tmp_stats_elems) * sizeof(float), WEBGPU_STORAGE_BUF_BINDING_MULT);
2166 GGML_ASSERT(tmp_stats_base <= UINT32_MAX);
2167 tmp_buf = ggml_webgpu_tensor_buf(dst);
2168 tmp_bind_offset = scratch_offset;
2169 tmp_bind_size = tmp_size_bytes;
2170 scratch_offset = ROUNDUP_POW2(scratch_offset + tmp_size_bytes, align_bytes);
2171 } else {
2172 // nwg==1 writes final dst directly in vec-split; bind tmp to a tiny non-overlapping scratch region.
2173 tmp_size_bytes = WEBGPU_STORAGE_BUF_BINDING_MULT;
2174 tmp_buf = ggml_webgpu_tensor_buf(dst);
2175 tmp_bind_offset = scratch_offset;
2176 tmp_bind_size = tmp_size_bytes;
2177 scratch_offset = ROUNDUP_POW2(scratch_offset + tmp_size_bytes, align_bytes);
2178 }
2179
2180 webgpu_pipeline blk_pipeline;
2181 std::vector<uint32_t> blk_params;
2182 std::vector<wgpu::BindGroupEntry> blk_entries;
2183 if (op.has_mask) {
2184 blk_nblk0 = CEIL_DIV((uint32_t) K->ne[1], decisions->kv_tile);
2185 blk_nblk1 = (uint32_t) Q->ne[1];
2186 blk_buf = ggml_webgpu_tensor_buf(dst);
2187 const uint32_t stride_mask3 = (uint32_t) (mask->nb[3] / ggml_type_size(mask->type));
2188 blk_batch_count = stride_mask3 > 0 ? (uint32_t) Q->ne[3] : 1u;
2189 const uint64_t blk_elems = (uint64_t) blk_nblk0 * blk_nblk1 * blk_batch_count;
2190 blk_size_bytes = ROUNDUP_POW2(blk_elems * sizeof(uint32_t), WEBGPU_STORAGE_BUF_BINDING_MULT);
2191 const ggml_webgpu_shader_lib_context blk_shader_ctx = op.shader_lib_ctx;
2192 blk_pipeline = ctx->shader_lib->get_flash_attn_blk_pipeline(blk_shader_ctx, decisions->kv_tile);
2193
2194 blk_params = {
2195 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, mask) / ggml_type_size(mask->type)), // offset_mask
2196 (uint32_t) Q->ne[1], // seq_len_q
2197 (uint32_t) K->ne[1], // seq_len_kv
2198 stride_mask3, // stride_mask3
2199 blk_nblk0, // nblk0
2200 blk_nblk1, // nblk1
2201 };
2202 blk_entries = {
2203 ggml_webgpu_make_bind_group_entry(0, ggml_webgpu_tensor_buf(mask),
2204 ggml_webgpu_tensor_align_offset(ctx, mask),
2205 ggml_webgpu_tensor_binding_size(ctx, mask)),
2206 ggml_webgpu_make_bind_group_entry(1, blk_buf, scratch_offset, blk_size_bytes),
2207 };
2208 scratch_offset = ROUNDUP_POW2(scratch_offset + blk_size_bytes, align_bytes);
2209 }
2210
2211 std::vector<uint32_t> split_params = op.params;
2212 if (op.has_mask) {
2213 split_params.push_back(0u); // blk_base
2214 split_params.push_back(blk_nblk0); // blk_nblk0
2215 split_params.push_back(blk_nblk1); // blk_nblk1
2216 }
2217 split_params.push_back(0u); // tmp_data_base
2218 split_params.push_back((uint32_t) tmp_stats_base); // tmp_stats_base
2219 split_params.push_back(nwg); // nwg
2220
2221 std::vector<wgpu::BindGroupEntry> split_entries = {
2222 ggml_webgpu_make_bind_group_entry(0, ggml_webgpu_tensor_buf(Q), ggml_webgpu_tensor_align_offset(ctx, Q),
2223 ggml_webgpu_tensor_binding_size(ctx, Q)),
2224 };
2225 if (op.kv_overlap) {
2226 split_entries.push_back(
2227 ggml_webgpu_make_bind_group_entry(1, ggml_webgpu_tensor_buf(K), op.kv_bind_offset, op.kv_bind_size));
2228 } else {
2229 split_entries.push_back(ggml_webgpu_make_bind_group_entry(1, ggml_webgpu_tensor_buf(K),
2230 ggml_webgpu_tensor_align_offset(ctx, K),
2231 ggml_webgpu_tensor_binding_size(ctx, K)));
2232 split_entries.push_back(ggml_webgpu_make_bind_group_entry(2, ggml_webgpu_tensor_buf(V),
2233 ggml_webgpu_tensor_align_offset(ctx, V),
2234 ggml_webgpu_tensor_binding_size(ctx, V)));
2235 }
2236 uint32_t split_binding_index = op.kv_overlap ? 2u : 3u;
2237 if (op.has_mask) {
2238 split_entries.push_back(ggml_webgpu_make_bind_group_entry(split_binding_index++, ggml_webgpu_tensor_buf(mask),
2239 ggml_webgpu_tensor_align_offset(ctx, mask),
2240 ggml_webgpu_tensor_binding_size(ctx, mask)));
2241 }
2242 if (op.has_sinks) {
2243 split_entries.push_back(ggml_webgpu_make_bind_group_entry(split_binding_index++, ggml_webgpu_tensor_buf(sinks),
2244 ggml_webgpu_tensor_align_offset(ctx, sinks),
2245 ggml_webgpu_tensor_binding_size(ctx, sinks)));
2246 }
2247 if (op.has_mask) {
2248 split_entries.push_back(
2249 ggml_webgpu_make_bind_group_entry(split_binding_index++, blk_buf, blk_entries[1].offset, blk_size_bytes));
2250 }
2251 split_entries.push_back(
2252 ggml_webgpu_make_bind_group_entry(split_binding_index++, tmp_buf, tmp_bind_offset, tmp_bind_size));
2253 split_entries.push_back(ggml_webgpu_make_bind_group_entry(split_binding_index++, ggml_webgpu_tensor_buf(dst),
2254 ggml_webgpu_tensor_align_offset(ctx, dst),
2255 ggml_webgpu_tensor_binding_size(ctx, dst)));
2256
2257 webgpu_pipeline reduce_pipeline;
2258 std::vector<uint32_t> reduce_params;
2259 std::vector<wgpu::BindGroupEntry> reduce_entries;
2260 if (use_vec_reduce) {
2261 const uint32_t reduce_sg_size = ctx->global_ctx->capabilities.max_subgroup_size;
2262 const uint32_t reduce_wg_size = std::max(
2263 reduce_sg_size,
2264 (uint32_t) std::min<uint64_t>((uint64_t) nwg * reduce_sg_size,
2265 ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup));
2266 ggml_webgpu_shader_lib_context reduce_shader_ctx = op.shader_lib_ctx;
2267 reduce_shader_ctx.max_wg_size = reduce_wg_size;
2268 reduce_pipeline = ctx->shader_lib->get_flash_attn_vec_reduce_pipeline(reduce_shader_ctx);
2269
2270 reduce_params = {
2271 (uint32_t) nrows, // nrows
2272 (uint32_t) Q->ne[1], // seq_len_q
2273 (uint32_t) Q->ne[2], // n_heads
2274 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)), // offset_dst
2275 nwg, // nwg
2276 0u, // tmp_data_base
2277 (uint32_t) tmp_stats_base, // tmp_stats_base
2278 };
2279
2280 reduce_entries = {
2281 ggml_webgpu_make_bind_group_entry(0, tmp_buf, tmp_bind_offset, tmp_size_bytes),
2282 ggml_webgpu_make_bind_group_entry(1, ggml_webgpu_tensor_buf(dst), ggml_webgpu_tensor_align_offset(ctx, dst),
2283 ggml_webgpu_tensor_binding_size(ctx, dst)),
2284 };
2285 }
2286
2287 uint32_t wg_x = Q->ne[1] * Q->ne[2] * Q->ne[3];
2288 const uint64_t split_wg_total = (uint64_t) wg_x * nwg;
2289 GGML_ASSERT(split_wg_total <= UINT32_MAX);
2290
2291 std::vector<webgpu_dispatch_desc> dispatches;
2292
2293 if (op.has_mask) {
2294 dispatches.push_back({
2295 blk_pipeline, std::move(blk_params), std::move(blk_entries), { blk_nblk0, blk_nblk1 * blk_batch_count }
2296 });
2297 }
2298 dispatches.push_back({
2299 pipeline, std::move(split_params), std::move(split_entries), { (uint32_t) split_wg_total, 1u }
2300 });
2301 if (use_vec_reduce) {
2302 dispatches.push_back({
2303 reduce_pipeline, std::move(reduce_params), std::move(reduce_entries), { (uint32_t) nrows, 1u }
2304 });
2305 }
2306
2307 return ggml_backend_webgpu_build_multi(ctx, dispatches);
2308}
2309
2310static webgpu_encoded_op ggml_webgpu_flash_attn(webgpu_context & ctx,
2311 ggml_tensor * Q,
2312 ggml_tensor * K,
2313 ggml_tensor * V,
2314 ggml_tensor * mask,
2315 ggml_tensor * sinks,
2316 ggml_tensor * dst) {
2317 ggml_webgpu_flash_attn_op op = ggml_webgpu_flash_attn_prepare(ctx, Q, K, V, mask, sinks, dst);
2318 if (ggml_webgpu_flash_attn_use_vec_path(ctx->global_ctx, Q, K, V, Q->ne[1])) {
2319 return ggml_webgpu_flash_attn_vec(ctx, Q, K, V, mask, sinks, dst, std::move(op));
2320 }
2321 return ggml_webgpu_flash_attn_direct(ctx, op);
2322}
2323
2324static webgpu_encoded_op ggml_webgpu_unary_op(webgpu_context & ctx, ggml_tensor * src, ggml_tensor * dst) {
2325 bool is_unary = dst->op == GGML_OP_UNARY;
2326
2327 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
2328 shader_lib_ctx.src0 = src;
2329 shader_lib_ctx.src1 = nullptr;
2330 shader_lib_ctx.dst = dst;
2331 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
2332
2333 webgpu_pipeline pipeline = ctx->shader_lib->get_unary_pipeline(shader_lib_ctx);
2334
2335 auto * decisions = static_cast<ggml_webgpu_generic_shader_decisions *>(pipeline.context.get());
2336 const bool inplace = decisions->inplace;
2337
2338 uint32_t ne = (uint32_t) ggml_nelements(dst);
2339
2340 std::vector<uint32_t> params = { ne,
2341 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src) / ggml_type_size(src->type)),
2342 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
2343 (uint32_t) (src->nb[0] / ggml_type_size(src->type)),
2344 (uint32_t) (src->nb[1] / ggml_type_size(src->type)),
2345 (uint32_t) (src->nb[2] / ggml_type_size(src->type)),
2346 (uint32_t) (src->nb[3] / ggml_type_size(src->type)),
2347 (uint32_t) src->ne[0],
2348 (uint32_t) src->ne[1],
2349 (uint32_t) src->ne[2] };
2350
2351 ggml_tensor * effective_src = src;
2352 if (is_unary) {
2353 ggml_unary_op unary_op = ggml_get_unary_op(dst);
2354 switch (unary_op) {
2355 case GGML_UNARY_OP_XIELU:
2356 {
2357 // Get float parameters and reinterpret their bit patterns as uint32_t
2358 // for passing through the params buffer
2359 float alpha_n = ggml_get_op_params_f32(dst, 1);
2360 float alpha_p = ggml_get_op_params_f32(dst, 2);
2361 float beta = ggml_get_op_params_f32(dst, 3);
2362 float eps = ggml_get_op_params_f32(dst, 4);
2363 params.push_back(ggml_webgpu_u32_from_f32(alpha_n));
2364 params.push_back(ggml_webgpu_u32_from_f32(alpha_p));
2365 params.push_back(ggml_webgpu_u32_from_f32(beta));
2366 params.push_back(ggml_webgpu_u32_from_f32(eps));
2367 break;
2368 }
2369 default:
2370 break;
2371 }
2372 } else if (dst->op == GGML_OP_CLAMP) {
2373 float clamp_min = ggml_get_op_params_f32(dst, 0);
2374 float clamp_max = ggml_get_op_params_f32(dst, 1);
2375 params.push_back(ggml_webgpu_u32_from_f32(clamp_min));
2376 params.push_back(ggml_webgpu_u32_from_f32(clamp_max));
2377 } else if (dst->op == GGML_OP_FILL) {
2378 float fill_val = ggml_get_op_params_f32(dst, 0);
2379 params.push_back(ggml_webgpu_u32_from_f32(fill_val));
2380 effective_src = dst; // fill simply fills dst
2381 }
2382
2383 std::vector<wgpu::BindGroupEntry> entries = {
2384 ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, effective_src),
2385 };
2386 if (!inplace) {
2387 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, dst));
2388 }
2389
2390 uint32_t wg_x;
2391 uint32_t wg_y;
2392 uint32_t total_wg = CEIL_DIV(ggml_nelements(dst), decisions->wg_size);
2393 compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y);
2394 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
2395}
2396
2397static webgpu_encoded_op ggml_webgpu_binary_op(webgpu_context & ctx,
2398 ggml_tensor * src0,
2399 ggml_tensor * src1,
2400 ggml_tensor * dst) {
2401 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
2402 shader_lib_ctx.src0 = src0;
2403 shader_lib_ctx.src1 = src1;
2404 shader_lib_ctx.dst = dst;
2405 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
2406
2407 const bool src_overlap = ggml_webgpu_tensor_binding_overlap(ctx->global_ctx, src0, src1);
2408 webgpu_pipeline pipeline = ctx->shader_lib->get_binary_pipeline(shader_lib_ctx, src_overlap);
2409 auto * decisions = static_cast<ggml_webgpu_binary_shader_decisions *>(pipeline.context.get());
2410
2411 uint32_t ne = (uint32_t) ggml_nelements(dst);
2412
2413 size_t src0_webgpu_tensor_align_offset = ggml_webgpu_tensor_align_offset(ctx, src0);
2414 size_t src1_webgpu_tensor_align_offset = ggml_webgpu_tensor_align_offset(ctx, src1);
2415
2416 uint32_t offset_src0 = (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src0) / ggml_type_size(src0->type));
2417 uint32_t offset_src1 = (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src1) / ggml_type_size(src1->type));
2418 size_t merged_offset = 0;
2419 size_t merged_size = 0;
2420 if (decisions->src_overlap) {
2421 const ggml_webgpu_merged_binding_range merged_range =
2422 ggml_webgpu_tensor_merged_binding_range(ctx, { src0, src1 });
2423 merged_offset = merged_range.offset;
2424 merged_size = merged_range.size;
2425 offset_src0 = ggml_webgpu_tensor_merged_element_offset(src0, merged_range);
2426 offset_src1 = ggml_webgpu_tensor_merged_element_offset(src1, merged_range);
2427 }
2428
2429 std::vector<uint32_t> params = {
2430 ne,
2431 offset_src0,
2432 offset_src1,
2433 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
2434 (uint32_t) (src0->nb[0] / ggml_type_size(src0->type)),
2435 (uint32_t) (src0->nb[1] / ggml_type_size(src0->type)),
2436 (uint32_t) (src0->nb[2] / ggml_type_size(src0->type)),
2437 (uint32_t) (src0->nb[3] / ggml_type_size(src0->type)),
2438 (uint32_t) (src1->nb[0] / ggml_type_size(src1->type)),
2439 (uint32_t) (src1->nb[1] / ggml_type_size(src1->type)),
2440 (uint32_t) (src1->nb[2] / ggml_type_size(src1->type)),
2441 (uint32_t) (src1->nb[3] / ggml_type_size(src1->type)),
2442 (uint32_t) src0->ne[0],
2443 (uint32_t) src0->ne[1],
2444 (uint32_t) src0->ne[2],
2445 (uint32_t) src1->ne[0],
2446 (uint32_t) src1->ne[1],
2447 (uint32_t) src1->ne[2],
2448 (uint32_t) src1->ne[3],
2449 };
2450
2451 std::vector<wgpu::BindGroupEntry> entries;
2452
2453 if (decisions->src_overlap) {
2454 entries.push_back(
2455 ggml_webgpu_make_bind_group_entry(0, ggml_webgpu_tensor_buf(src0), merged_offset, merged_size));
2456 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, dst));
2457 } else {
2458 entries.push_back(ggml_webgpu_make_bind_group_entry(0, ggml_webgpu_tensor_buf(src0),
2459 src0_webgpu_tensor_align_offset,
2460 ggml_webgpu_tensor_binding_size(ctx, src0)));
2461 entries.push_back(ggml_webgpu_make_bind_group_entry(1, ggml_webgpu_tensor_buf(src1),
2462 src1_webgpu_tensor_align_offset,
2463 ggml_webgpu_tensor_binding_size(ctx, src1)));
2464 if (!decisions->inplace && !decisions->overlap) {
2465 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 2, dst));
2466 }
2467 }
2468
2469 uint32_t wg_x;
2470 uint32_t wg_y;
2471 uint32_t total_wg = CEIL_DIV(ggml_nelements(dst), decisions->wg_size);
2472 compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y);
2473 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
2474}
2475
2476static webgpu_encoded_op ggml_webgpu_add_id(webgpu_context & ctx,
2477 ggml_tensor * src0,
2478 ggml_tensor * src1,
2479 ggml_tensor * src2,
2480 ggml_tensor * dst) {
2481 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
2482 shader_lib_ctx.src0 = src0;
2483 shader_lib_ctx.src1 = src1;
2484 shader_lib_ctx.src2 = src2;
2485 shader_lib_ctx.dst = dst;
2486 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
2487
2488 webgpu_pipeline pipeline = ctx->shader_lib->get_add_id_pipeline(shader_lib_ctx);
2489
2490 auto * decisions = static_cast<ggml_webgpu_generic_shader_decisions *>(pipeline.context.get());
2491
2492 std::vector<uint32_t> params = {
2493 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src0) / ggml_type_size(src0->type)),
2494 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src1) / ggml_type_size(src1->type)),
2495 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src2) / ggml_type_size(src2->type)),
2496 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
2497 (uint32_t) (src0->nb[1] / ggml_type_size(src0->type)),
2498 (uint32_t) (src0->nb[2] / ggml_type_size(src0->type)),
2499 (uint32_t) (src1->nb[1] / ggml_type_size(src1->type)),
2500 (uint32_t) (src2->nb[0] / ggml_type_size(src2->type)),
2501 (uint32_t) (src2->nb[1] / ggml_type_size(src2->type)),
2502 (uint32_t) dst->ne[0],
2503 (uint32_t) dst->ne[1],
2504 (uint32_t) dst->ne[2],
2505 };
2506
2507 std::vector<wgpu::BindGroupEntry> entries;
2508
2509 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src0));
2510 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, src1));
2511 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 2, src2));
2512
2513 if (!decisions->inplace) {
2514 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 3, dst));
2515 }
2516
2517 uint32_t wg_x = 1;
2518 uint32_t wg_y = 1;
2519 uint32_t total_wg = ggml_nrows(dst);
2520 const uint32_t max_wg_per_dim = ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension;
2521 compute_2d_workgroups(total_wg, max_wg_per_dim, wg_x, wg_y);
2522
2523 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
2524}
2525
2526static webgpu_encoded_op ggml_webgpu_concat(webgpu_context & ctx,
2527 ggml_tensor * src0,
2528 ggml_tensor * src1,
2529 ggml_tensor * dst) {
2530 uint32_t ne = (uint32_t) ggml_nelements(dst);
2531 uint32_t dim = (uint32_t) dst->op_params[0];
2532 if (ggml_nbytes(src0) == 0 && ggml_nbytes(src1) == 0) {
2533 return {};
2534 }
2535
2536 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
2537 shader_lib_ctx.src0 = src0;
2538 shader_lib_ctx.src1 = src1;
2539 shader_lib_ctx.dst = dst;
2540 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
2541
2542 const bool src_overlap = ggml_webgpu_tensor_binding_overlap(ctx->global_ctx, src0, src1) ||
2543 ggml_nbytes(src0) == 0 || ggml_nbytes(src1) == 0;
2544 webgpu_pipeline pipeline = ctx->shader_lib->get_concat_pipeline(shader_lib_ctx, src_overlap);
2545 auto * decisions = static_cast<ggml_webgpu_binary_shader_decisions *>(pipeline.context.get());
2546
2547 uint32_t offset_src0 = (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src0) / ggml_type_size(src0->type));
2548 uint32_t offset_src1 = (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src1) / ggml_type_size(src1->type));
2549 size_t merged_offset = 0;
2550 size_t merged_size = 0;
2551 if (decisions->src_overlap) {
2552 if (ggml_nbytes(src0) == 0) {
2553 merged_offset = ggml_webgpu_tensor_align_offset(ctx, src1);
2554 merged_size = ggml_webgpu_tensor_binding_size(ctx, src1);
2555 offset_src0 = 0;
2556 offset_src1 = (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src1) / ggml_type_size(src1->type));
2557 } else if (ggml_nbytes(src1) == 0) {
2558 merged_offset = ggml_webgpu_tensor_align_offset(ctx, src0);
2559 merged_size = ggml_webgpu_tensor_binding_size(ctx, src0);
2560 offset_src0 = (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src0) / ggml_type_size(src0->type));
2561 offset_src1 = 0;
2562 } else {
2563 const ggml_webgpu_merged_binding_range merged_range =
2564 ggml_webgpu_tensor_merged_binding_range(ctx, { src0, src1 });
2565 merged_offset = merged_range.offset;
2566 merged_size = merged_range.size;
2567 offset_src0 = ggml_webgpu_tensor_merged_element_offset(src0, merged_range);
2568 offset_src1 = ggml_webgpu_tensor_merged_element_offset(src1, merged_range);
2569 }
2570 }
2571
2572 std::vector<uint32_t> params = { ne,
2573 offset_src0,
2574 offset_src1,
2575 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
2576 (uint32_t) (src0->nb[0] / ggml_type_size(src0->type)),
2577 (uint32_t) (src0->nb[1] / ggml_type_size(src0->type)),
2578 (uint32_t) (src0->nb[2] / ggml_type_size(src0->type)),
2579 (uint32_t) (src0->nb[3] / ggml_type_size(src0->type)),
2580 (uint32_t) (src1->nb[0] / ggml_type_size(src1->type)),
2581 (uint32_t) (src1->nb[1] / ggml_type_size(src1->type)),
2582 (uint32_t) (src1->nb[2] / ggml_type_size(src1->type)),
2583 (uint32_t) (src1->nb[3] / ggml_type_size(src1->type)),
2584 (uint32_t) dst->ne[0],
2585 (uint32_t) dst->ne[1],
2586 (uint32_t) dst->ne[2],
2587 dim,
2588 (uint32_t) src0->ne[dim] };
2589
2590 std::vector<wgpu::BindGroupEntry> entries = {};
2591 if (decisions->src_overlap) {
2592 entries.push_back(
2593 ggml_webgpu_make_bind_group_entry(0, ggml_webgpu_tensor_buf(src0), merged_offset, merged_size));
2594 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, dst));
2595 } else {
2596 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src0));
2597 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, src1));
2598 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 2, dst));
2599 }
2600
2601 uint32_t wg_x;
2602 uint32_t wg_y;
2603 uint32_t total_wg = CEIL_DIV(ne, decisions->wg_size);
2604 compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y);
2605 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
2606}
2607
2608static webgpu_encoded_op ggml_webgpu_repeat(webgpu_context & ctx, ggml_tensor * src0, ggml_tensor * dst) {
2609 uint32_t ne = (uint32_t) ggml_nelements(dst);
2610
2611 std::vector<uint32_t> params = { ne,
2612 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src0) /
2613 ggml_type_size(src0->type)),
2614 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
2615 (uint32_t) (src0->nb[0] / ggml_type_size(src0->type)),
2616 (uint32_t) (src0->nb[1] / ggml_type_size(src0->type)),
2617 (uint32_t) (src0->nb[2] / ggml_type_size(src0->type)),
2618 (uint32_t) (src0->nb[3] / ggml_type_size(src0->type)),
2619 (uint32_t) (src0->ne[0]),
2620 (uint32_t) (src0->ne[1]),
2621 (uint32_t) (src0->ne[2]),
2622 (uint32_t) (src0->ne[3]),
2623 (uint32_t) (dst->ne[0]),
2624 (uint32_t) (dst->ne[1]),
2625 (uint32_t) (dst->ne[2]) };
2626
2627 std::vector<wgpu::BindGroupEntry> entries = {
2628 ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src0),
2629 ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, dst),
2630 };
2631
2632 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
2633 shader_lib_ctx.src0 = src0;
2634 shader_lib_ctx.dst = dst;
2635 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
2636
2637 webgpu_pipeline pipeline = ctx->shader_lib->get_repeat_pipeline(shader_lib_ctx);
2638 auto * decisions = static_cast<ggml_webgpu_generic_shader_decisions *>(pipeline.context.get());
2639
2640 uint32_t wg_x;
2641 uint32_t wg_y;
2642 uint32_t total_wg = CEIL_DIV(ne, decisions->wg_size);
2643 compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y);
2644 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
2645}
2646
2647static std::optional<webgpu_encoded_op> ggml_webgpu_rms_norm_mul(webgpu_context & ctx,
2648 ggml_tensor * rn_src,
2649 ggml_tensor * rn_dst,
2650 ggml_tensor * mul_src0,
2651 ggml_tensor * mul_src1,
2652 ggml_tensor * dst) {
2653 ggml_tensor * mul_src;
2654
2655 if (ggml_webgpu_tensor_equal(rn_dst, mul_src0)) {
2656 mul_src = mul_src1;
2657 } else if (ggml_webgpu_tensor_equal(rn_dst, mul_src1)) {
2658 mul_src = mul_src0;
2659 } else {
2660 GGML_ABORT("rms_norm must be equal to the one of mul_src0 and mul_src1");
2661 }
2662
2663 uint32_t offset_rn_src = (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, rn_src) / ggml_type_size(rn_src->type));
2664 uint32_t offset_mul_src =
2665 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, mul_src) / ggml_type_size(mul_src->type));
2666 size_t merged_offset = 0;
2667 size_t merged_size = 0;
2668
2669 std::vector<uint32_t> params = {
2670 offset_rn_src,
2671 offset_mul_src,
2672 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
2673 (uint32_t) (rn_src->nb[1] / ggml_type_size(rn_src->type)),
2674 (uint32_t) (rn_src->nb[2] / ggml_type_size(rn_src->type)),
2675 (uint32_t) (rn_src->nb[3] / ggml_type_size(rn_src->type)),
2676 (uint32_t) (mul_src->nb[1] / ggml_type_size(mul_src->type)),
2677 (uint32_t) (mul_src->nb[2] / ggml_type_size(mul_src->type)),
2678 (uint32_t) (mul_src->nb[3] / ggml_type_size(mul_src->type)),
2679 (uint32_t) (dst->nb[1] / ggml_type_size(dst->type)),
2680 (uint32_t) (dst->nb[2] / ggml_type_size(dst->type)),
2681 (uint32_t) (dst->nb[3] / ggml_type_size(dst->type)),
2682 (uint32_t) mul_src->ne[0],
2683 (uint32_t) mul_src->ne[1],
2684 (uint32_t) mul_src->ne[2],
2685 (uint32_t) mul_src->ne[3],
2686 (uint32_t) dst->ne[0],
2687 (uint32_t) dst->ne[1],
2688 (uint32_t) dst->ne[2],
2689 (uint32_t) dst->ne[3],
2690 ggml_webgpu_u32_from_f32(ggml_get_op_params_f32(rn_dst, 0)) // epsilon, treated as f32 in the shader
2691 };
2692
2693 std::vector<wgpu::BindGroupEntry> entries;
2694
2695 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
2696 shader_lib_ctx.src0 = rn_src;
2697 shader_lib_ctx.src1 = mul_src;
2698 shader_lib_ctx.dst = dst;
2699 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
2700
2701 const bool src_overlap = ggml_webgpu_tensor_binding_overlap(ctx->global_ctx, rn_src, mul_src);
2702 webgpu_pipeline pipeline = ctx->shader_lib->get_rms_norm_mul_pipeline(shader_lib_ctx, src_overlap);
2703 auto * decisions = static_cast<ggml_webgpu_rms_norm_mul_shader_decisions *>(pipeline.context.get());
2704
2705 if (decisions->src_overlap) {
2706 const ggml_webgpu_merged_binding_range merged_range =
2707 ggml_webgpu_tensor_merged_binding_range(ctx, { rn_src, mul_src });
2708 merged_offset = merged_range.offset;
2709 merged_size = merged_range.size;
2710 offset_rn_src = ggml_webgpu_tensor_merged_element_offset(rn_src, merged_range);
2711 offset_mul_src = ggml_webgpu_tensor_merged_element_offset(mul_src, merged_range);
2712 params[0] = offset_rn_src;
2713 params[1] = offset_mul_src;
2714 }
2715
2716 if (decisions->inplace || decisions->overlap) {
2717 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, rn_src));
2718 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, mul_src));
2719 } else if (decisions->src_overlap) {
2720 entries.push_back(
2721 ggml_webgpu_make_bind_group_entry(0, ggml_webgpu_tensor_buf(rn_src), merged_offset, merged_size));
2722 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, dst));
2723 } else {
2724 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, rn_src));
2725 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, mul_src));
2726 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 2, dst));
2727 }
2728
2729 uint32_t wg_x;
2730 uint32_t wg_y;
2731 compute_2d_workgroups(ggml_nrows(dst), ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x,
2732 wg_y);
2733 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
2734}
2735
2736static webgpu_encoded_op ggml_webgpu_row_norm(webgpu_context & ctx, ggml_tensor * src, ggml_tensor * dst) {
2737 std::vector<uint32_t> params = {
2738 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src) / ggml_type_size(src->type)),
2739 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
2740 (uint32_t) (src->nb[1] / ggml_type_size(src->type)),
2741 (uint32_t) (src->nb[2] / ggml_type_size(src->type)),
2742 (uint32_t) (src->nb[3] / ggml_type_size(src->type)),
2743 (uint32_t) (dst->nb[1] / ggml_type_size(dst->type)),
2744 (uint32_t) (dst->nb[2] / ggml_type_size(dst->type)),
2745 (uint32_t) (dst->nb[3] / ggml_type_size(dst->type)),
2746 (uint32_t) src->ne[0],
2747 (uint32_t) src->ne[1],
2748 (uint32_t) src->ne[2],
2749 (uint32_t) src->ne[3],
2750 ggml_webgpu_u32_from_f32(ggml_get_op_params_f32(dst, 0)) // epsilon, treated as f32 in the shader
2751 };
2752
2753 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
2754 shader_lib_ctx.src0 = src;
2755 shader_lib_ctx.dst = dst;
2756 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
2757
2758 webgpu_pipeline pipeline = ctx->shader_lib->get_row_norm_pipeline(shader_lib_ctx);
2759 auto * decisions = static_cast<ggml_webgpu_generic_shader_decisions *>(pipeline.context.get());
2760
2761 std::vector<wgpu::BindGroupEntry> entries = { ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src) };
2762 if (!decisions->inplace) {
2763 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, dst));
2764 }
2765
2766 uint32_t wg_x;
2767 uint32_t wg_y;
2768 compute_2d_workgroups(ggml_nrows(src), ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x,
2769 wg_y);
2770 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
2771}
2772
2773static webgpu_encoded_op ggml_webgpu_rope(webgpu_context & ctx,
2774 ggml_tensor * src0,
2775 ggml_tensor * src1,
2776 ggml_tensor * src2,
2777 ggml_tensor * dst) {
2778 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
2779 shader_lib_ctx.src0 = src0;
2780 shader_lib_ctx.src1 = src1;
2781 shader_lib_ctx.src2 = src2;
2782 shader_lib_ctx.dst = dst;
2783 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
2784
2785 webgpu_pipeline pipeline = ctx->shader_lib->get_rope_pipeline(shader_lib_ctx);
2786
2787 auto * decisions = static_cast<ggml_webgpu_generic_shader_decisions *>(pipeline.context.get());
2788
2789 const bool inplace = decisions->inplace;
2790 const int has_freq_factor = (src2 != nullptr);
2791
2792 const int n_dims = ((int32_t *) dst->op_params)[1];
2793 const int mode = ((int32_t *) dst->op_params)[2];
2794 const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
2795 const int n_offs = ((int32_t *) dst->op_params)[15];
2796
2797 float freq_base;
2798 float freq_scale;
2799 float ext_factor;
2800 float attn_factor;
2801 float beta_fast;
2802 float beta_slow;
2803 memcpy(&freq_base, (int32_t *) dst->op_params + 5, sizeof(float));
2804 memcpy(&freq_scale, (int32_t *) dst->op_params + 6, sizeof(float));
2805 memcpy(&ext_factor, (int32_t *) dst->op_params + 7, sizeof(float));
2806 memcpy(&attn_factor, (int32_t *) dst->op_params + 8, sizeof(float));
2807 memcpy(&beta_fast, (int32_t *) dst->op_params + 9, sizeof(float));
2808 memcpy(&beta_slow, (int32_t *) dst->op_params + 10, sizeof(float));
2809
2810 int sections[4];
2811 memcpy(sections, (int32_t *) dst->op_params + 11, 4 * sizeof(int));
2812
2813 float theta_scale = powf(freq_base, -2.0f / n_dims);
2814
2815 float corr_dims[2];
2816 ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
2817
2818 std::vector<uint32_t> params = {
2819 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src0) / ggml_type_size(src0->type)),
2820 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src1) / ggml_type_size(src1->type)),
2821 src2 != nullptr ? (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src2) / ggml_type_size(src2->type)) : 0,
2822 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
2823 (uint32_t) (src0->nb[1] / ggml_type_size(src0->type)),
2824 (uint32_t) (src0->nb[2] / ggml_type_size(src0->type)),
2825 (uint32_t) (src0->nb[3] / ggml_type_size(src0->type)),
2826 (uint32_t) (dst->nb[1] / ggml_type_size(dst->type)),
2827 (uint32_t) (dst->nb[2] / ggml_type_size(dst->type)),
2828 (uint32_t) (dst->nb[3] / ggml_type_size(dst->type)),
2829 (uint32_t) ggml_nelements(src0) / 2,
2830 (uint32_t) src0->ne[0],
2831 (uint32_t) src0->ne[1],
2832 (uint32_t) src0->ne[2],
2833 (uint32_t) n_dims,
2834 (uint32_t) mode,
2835 ggml_webgpu_u32_from_f32(theta_scale),
2836 ggml_webgpu_u32_from_f32(attn_factor),
2837 ggml_webgpu_u32_from_f32(freq_scale),
2838 ggml_webgpu_u32_from_f32(ext_factor),
2839 ggml_webgpu_u32_from_f32(corr_dims[0]),
2840 ggml_webgpu_u32_from_f32(corr_dims[1]),
2841 (uint32_t) sections[0],
2842 (uint32_t) sections[1],
2843 (uint32_t) sections[2],
2844 (uint32_t) sections[3],
2845 (uint32_t) n_offs
2846 };
2847
2848 std::vector<wgpu::BindGroupEntry> entries = { ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src0),
2849 ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, src1) };
2850 uint32_t dst_binding = 2;
2851 if (has_freq_factor) {
2852 dst_binding = 3;
2853 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 2, src2));
2854 }
2855 if (!inplace) {
2856 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, dst_binding, dst));
2857 }
2858
2859 uint32_t wg_x;
2860 uint32_t wg_y;
2861 uint32_t total_wg = CEIL_DIV(ggml_nelements(dst), decisions->wg_size);
2862 compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y);
2863 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
2864}
2865
2866static webgpu_encoded_op ggml_webgpu_glu(webgpu_context & ctx,
2867 ggml_tensor * src0,
2868 ggml_tensor * src1,
2869 ggml_tensor * dst) {
2870 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
2871 shader_lib_ctx.src0 = src0;
2872 shader_lib_ctx.src1 = src1;
2873 shader_lib_ctx.dst = dst;
2874 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
2875
2876 const bool src_overlap = src1 != nullptr && ggml_webgpu_tensor_binding_overlap(ctx->global_ctx, src0, src1);
2877 webgpu_pipeline pipeline = ctx->shader_lib->get_glu_pipeline(shader_lib_ctx, src_overlap);
2878
2879 auto * decisions = static_cast<ggml_webgpu_glu_shader_decisions *>(pipeline.context.get());
2880
2881 const int split = (src1 != nullptr);
2882
2883 uint32_t offset_src0 = (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src0) / ggml_type_size(src0->type));
2884 uint32_t offset_src1 =
2885 src1 != nullptr ? (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src1) / ggml_type_size(src1->type)) : 0;
2886 size_t merged_offset = 0;
2887 size_t merged_size = 0;
2888 if (decisions->src_overlap) {
2889 const ggml_webgpu_merged_binding_range merged_range =
2890 ggml_webgpu_tensor_merged_binding_range(ctx, { src0, src1 });
2891 merged_offset = merged_range.offset;
2892 merged_size = merged_range.size;
2893 offset_src0 = ggml_webgpu_tensor_merged_element_offset(src0, merged_range);
2894 offset_src1 = ggml_webgpu_tensor_merged_element_offset(src1, merged_range);
2895 }
2896
2897 std::vector<uint32_t> params = {
2898 offset_src0,
2899 offset_src1,
2900 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
2901 (uint32_t) (src0->nb[1] / ggml_type_size(src0->type)),
2902 (uint32_t) (src0->nb[2] / ggml_type_size(src0->type)),
2903 (uint32_t) (src0->nb[3] / ggml_type_size(src0->type)),
2904 src1 != nullptr ? (uint32_t) (src1->nb[1] / ggml_type_size(src1->type)) :
2905 (uint32_t) (src0->nb[1] / ggml_type_size(src0->type)),
2906 src1 != nullptr ? (uint32_t) (src1->nb[2] / ggml_type_size(src1->type)) :
2907 (uint32_t) (src0->nb[2] / ggml_type_size(src0->type)),
2908 src1 != nullptr ? (uint32_t) (src1->nb[3] / ggml_type_size(src1->type)) :
2909 (uint32_t) (src0->nb[3] / ggml_type_size(src0->type)),
2910 (uint32_t) (dst->nb[1] / ggml_type_size(dst->type)),
2911 (uint32_t) (dst->nb[2] / ggml_type_size(dst->type)),
2912 (uint32_t) (dst->nb[3] / ggml_type_size(dst->type)),
2913 (uint32_t) ggml_nelements(dst),
2914 (uint32_t) dst->ne[0],
2915 (uint32_t) dst->ne[1],
2916 (uint32_t) dst->ne[2],
2917 (uint32_t) ((int32_t *) dst->op_params)[1], // swapped
2918 ggml_webgpu_u32_from_f32(ggml_get_op_params_f32(dst, 2)), // alpha, for swiglu_oai
2919 ggml_webgpu_u32_from_f32(ggml_get_op_params_f32(dst, 3)), // limit
2920 };
2921
2922 std::vector<wgpu::BindGroupEntry> entries;
2923 uint32_t dst_binding = 1;
2924 if (decisions->src_overlap) {
2925 entries.push_back(
2926 ggml_webgpu_make_bind_group_entry(0, ggml_webgpu_tensor_buf(src0), merged_offset, merged_size));
2927 } else {
2928 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src0));
2929 }
2930 if (split && !decisions->src_overlap) {
2931 dst_binding = 2;
2932 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, src1));
2933 }
2934 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, dst_binding, dst));
2935
2936 uint32_t wg_x;
2937 uint32_t wg_y;
2938 uint32_t total_wg = CEIL_DIV(ggml_nelements(dst), decisions->wg_size);
2939 compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y);
2940 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
2941}
2942
2943static webgpu_encoded_op ggml_webgpu_scale(webgpu_context & ctx, ggml_tensor * src, ggml_tensor * dst) {
2944 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
2945 shader_lib_ctx.src0 = src;
2946 shader_lib_ctx.src1 = nullptr;
2947 shader_lib_ctx.dst = dst;
2948 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
2949
2950 webgpu_pipeline pipeline = ctx->shader_lib->get_scale_pipeline(shader_lib_ctx);
2951 auto * decisions = static_cast<ggml_webgpu_generic_shader_decisions *>(pipeline.context.get());
2952
2953 // params unchanged
2954 std::vector<uint32_t> params = {
2955 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src) / ggml_type_size(src->type)),
2956 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
2957 (uint32_t) (src->nb[1] / ggml_type_size(src->type)),
2958 (uint32_t) (src->nb[2] / ggml_type_size(src->type)),
2959 (uint32_t) (src->nb[3] / ggml_type_size(src->type)),
2960 (uint32_t) (dst->nb[1] / ggml_type_size(dst->type)),
2961 (uint32_t) (dst->nb[2] / ggml_type_size(dst->type)),
2962 (uint32_t) (dst->nb[3] / ggml_type_size(dst->type)),
2963 (uint32_t) ggml_nelements(dst),
2964 (uint32_t) src->ne[0],
2965 (uint32_t) src->ne[1],
2966 (uint32_t) src->ne[2],
2967 ggml_webgpu_u32_from_f32(ggml_get_op_params_f32(dst, 0)), // scale
2968 ggml_webgpu_u32_from_f32(ggml_get_op_params_f32(dst, 1)) // bias
2969 };
2970
2971 // bindgroups unchanged
2972 std::vector<wgpu::BindGroupEntry> entries = { ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src) };
2973
2974 if (!decisions->inplace) {
2975 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, dst));
2976 }
2977
2978 uint32_t wg_x;
2979 uint32_t wg_y;
2980 uint32_t total_wg = CEIL_DIV(ggml_nelements(dst), decisions->wg_size);
2981 compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y);
2982 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
2983}
2984
2985static webgpu_encoded_op ggml_webgpu_soft_max(webgpu_context & ctx,
2986 ggml_tensor * src0,
2987 ggml_tensor * src1,
2988 ggml_tensor * src2,
2989 ggml_tensor * dst) {
2990 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
2991 shader_lib_ctx.src0 = src0;
2992 shader_lib_ctx.src1 = src1;
2993 shader_lib_ctx.src2 = src2;
2994 shader_lib_ctx.dst = dst;
2995 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
2996
2997 webgpu_pipeline pipeline = ctx->shader_lib->get_soft_max_pipeline(shader_lib_ctx);
2998 auto * decisions = static_cast<ggml_webgpu_generic_shader_decisions *>(pipeline.context.get());
2999
3000 const bool inplace = decisions->inplace;
3001 const int has_mask = (src1 != nullptr);
3002 const int has_sink = (src2 != nullptr);
3003 float max_bias = ggml_get_op_params_f32(dst, 1);
3004 float n_head_log2 = float(1u << (uint32_t) floor(log2(src0->ne[2])));
3005 float m0 = powf(2.0f, -(max_bias) / n_head_log2);
3006 float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
3007
3008 std::vector<uint32_t> params = {
3009 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src0) / ggml_type_size(src0->type)),
3010 has_mask ? (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src1) / ggml_type_size(src1->type)) : 0,
3011 has_sink ? (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src2) / ggml_type_size(src2->type)) : 0,
3012 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
3013 (uint32_t) (src0->nb[1] / ggml_type_size(src0->type)),
3014 (uint32_t) (src0->nb[2] / ggml_type_size(src0->type)),
3015 (uint32_t) (src0->nb[3] / ggml_type_size(src0->type)),
3016 has_mask ? (uint32_t) (src1->nb[1] / ggml_type_size(src1->type)) : 0,
3017 has_mask ? (uint32_t) (src1->nb[2] / ggml_type_size(src1->type)) : 0,
3018 has_mask ? (uint32_t) (src1->nb[3] / ggml_type_size(src1->type)) : 0,
3019 (uint32_t) (dst->nb[1] / ggml_type_size(dst->type)),
3020 (uint32_t) (dst->nb[2] / ggml_type_size(dst->type)),
3021 (uint32_t) (dst->nb[3] / ggml_type_size(dst->type)),
3022 (uint32_t) src0->ne[0],
3023 (uint32_t) src0->ne[1],
3024 (uint32_t) src0->ne[2],
3025 has_mask ? (uint32_t) src1->ne[2] : 0,
3026 has_mask ? (uint32_t) src1->ne[3] : 0,
3027 ggml_webgpu_u32_from_f32(ggml_get_op_params_f32(dst, 0)), // scale
3028 ggml_webgpu_u32_from_f32(max_bias),
3029 ggml_webgpu_u32_from_f32(n_head_log2),
3030 ggml_webgpu_u32_from_f32(m0),
3031 ggml_webgpu_u32_from_f32(m1)
3032 };
3033
3034 std::vector<wgpu::BindGroupEntry> entries = { ggml_webgpu_make_bind_group_entry(
3035 0, ggml_webgpu_tensor_buf(src0), ggml_webgpu_tensor_align_offset(ctx, src0),
3036 ggml_webgpu_tensor_binding_size(ctx, src0)) };
3037 uint32_t binding_num = 1;
3038 if (has_mask) {
3039 entries.push_back(ggml_webgpu_make_bind_group_entry(binding_num, ggml_webgpu_tensor_buf(src1),
3040 ggml_webgpu_tensor_align_offset(ctx, src1),
3041 ggml_webgpu_tensor_binding_size(ctx, src1)));
3042 binding_num++;
3043 }
3044 if (has_sink) {
3045 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding_num, src2));
3046 binding_num++;
3047 }
3048 if (!inplace) {
3049 entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding_num, dst));
3050 }
3051
3052 uint32_t wg_x;
3053 uint32_t wg_y;
3054 uint32_t total_wg = ggml_nrows(dst);
3055 compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y);
3056 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
3057}
3058
3059static webgpu_encoded_op ggml_webgpu_argmax(webgpu_context & ctx, ggml_tensor * src, ggml_tensor * dst) {
3060 std::vector<uint32_t> params = { (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src) / ggml_type_size(src->type)),
3061 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
3062 (uint32_t) src->ne[0] };
3063
3064 std::vector<wgpu::BindGroupEntry> entries = { ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src),
3065 ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, dst) };
3066
3067 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
3068 shader_lib_ctx.src0 = src;
3069 shader_lib_ctx.dst = dst;
3070 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
3071
3072 webgpu_pipeline pipeline = ctx->shader_lib->get_argmax_pipeline(shader_lib_ctx);
3073 uint32_t wg_x = ggml_nelements(dst);
3074 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x);
3075}
3076
3077static webgpu_encoded_op ggml_webgpu_argsort(webgpu_context & ctx, ggml_tensor * src, ggml_tensor * dst) {
3078 bool is_top_k = dst->op == GGML_OP_TOP_K;
3079
3080 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
3081 shader_lib_ctx.src0 = src;
3082 shader_lib_ctx.src1 = nullptr;
3083 shader_lib_ctx.dst = dst;
3084 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
3085 shader_lib_ctx.wg_mem_limit_bytes = ctx->global_ctx->capabilities.limits.maxComputeWorkgroupStorageSize;
3086
3087 webgpu_pipeline argsort_pipeline = ctx->shader_lib->get_argsort_pipeline(shader_lib_ctx);
3088 auto * argsort_decisions = static_cast<ggml_webgpu_generic_shader_decisions *>(argsort_pipeline.context.get());
3089
3090 webgpu_pipeline argsort_merge_pipeline = ctx->shader_lib->get_argsort_merge_pipeline(shader_lib_ctx);
3091
3092 const uint32_t src_ne0 = (uint32_t) src->ne[0];
3093 const uint32_t nrows = (uint32_t) ggml_nrows(src);
3094 const uint32_t npr = CEIL_DIV(src_ne0, argsort_decisions->wg_size);
3095 const uint32_t block_size =
3096 is_top_k ? std::min(argsort_decisions->wg_size, (uint32_t) dst->ne[0]) : argsort_decisions->wg_size;
3097 uint32_t out_ne0 = src_ne0;
3098 if (is_top_k) {
3099 if (npr > 1) {
3100 const uint32_t last_tile = src_ne0 - (npr - 1) * argsort_decisions->wg_size;
3101 out_ne0 = (npr - 1) * block_size + std::min(last_tile, block_size);
3102 } else {
3103 out_ne0 = block_size;
3104 }
3105 }
3106
3107 uint32_t merge_len = block_size;
3108 uint32_t merge_passes = 0;
3109 while (merge_len < out_ne0) {
3110 merge_len <<= 1;
3111 merge_passes++;
3112 }
3113
3114 const bool start_in_tmp = (merge_passes % 2) == 1;
3115
3116 const size_t dst_offset = ggml_webgpu_tensor_offset(dst);
3117 const size_t idx_nbytes = out_ne0 * ggml_nrows(dst) * sizeof(int32_t);
3118 const size_t tmp_offset =
3119 ROUNDUP_POW2(dst_offset + idx_nbytes, ctx->global_ctx->capabilities.limits.minStorageBufferOffsetAlignment);
3120 const size_t tmp_binding_size = ROUNDUP_POW2(idx_nbytes, WEBGPU_STORAGE_BUF_BINDING_MULT);
3121 const size_t dst_binding_size =
3122 ROUNDUP_POW2(idx_nbytes + ggml_webgpu_tensor_misalignment(ctx, dst), WEBGPU_STORAGE_BUF_BINDING_MULT);
3123
3124 const uint32_t offset_src = (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src) / ggml_type_size(src->type));
3125 const uint32_t offset_dst = (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type));
3126 const uint32_t offset_tmp = 0;
3127 const uint32_t stride_src1 = (uint32_t) (src->nb[1] / ggml_type_size(src->type));
3128 const uint32_t stride_src2 = (uint32_t) (src->nb[2] / ggml_type_size(src->type));
3129 const uint32_t stride_src3 = (uint32_t) (src->nb[3] / ggml_type_size(src->type));
3130 const uint32_t stride_idx1 = out_ne0;
3131 const uint32_t stride_idx2 = out_ne0 * (uint32_t) dst->ne[1];
3132 const uint32_t stride_idx3 = stride_idx2 * (uint32_t) dst->ne[2];
3133
3134 std::vector<webgpu_dispatch_desc> dispatches;
3135
3136 const uint32_t init_offset = start_in_tmp ? offset_tmp : offset_dst;
3137 const size_t init_align_offset = start_in_tmp ? tmp_offset : ggml_webgpu_tensor_align_offset(ctx, dst);
3138 const size_t init_binding_size = start_in_tmp ? tmp_binding_size : dst_binding_size;
3139
3140 std::vector<uint32_t> init_params = {
3141 offset_src, init_offset, stride_src1, stride_src2, stride_src3, stride_idx1,
3142 stride_idx2, stride_idx3, src_ne0, (uint32_t) src->ne[1], (uint32_t) src->ne[2], out_ne0,
3143 block_size, npr, nrows
3144 };
3145
3146 uint32_t wg_x_init;
3147 uint32_t wg_y_init;
3148 const uint32_t total_wg_init = npr * nrows;
3149 const uint32_t max_wg_per_dim = ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension;
3150 compute_2d_workgroups(total_wg_init, max_wg_per_dim, wg_x_init, wg_y_init);
3151
3152 std::vector<wgpu::BindGroupEntry> init_entries = {
3153 ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src),
3154 ggml_webgpu_make_bind_group_entry(1, ggml_webgpu_tensor_buf(dst), init_align_offset, init_binding_size)
3155 };
3156
3157 dispatches.push_back({
3158 argsort_pipeline, std::move(init_params), std::move(init_entries), { wg_x_init, wg_y_init }
3159 });
3160
3161 if (merge_passes == 0) {
3162 return ggml_backend_webgpu_build_multi(ctx, dispatches);
3163 }
3164
3165 bool in_is_tmp = start_in_tmp;
3166 uint32_t len = block_size;
3167 while (len < out_ne0) {
3168 const uint32_t nm = CEIL_DIV(out_ne0, 2 * len);
3169
3170 const bool out_is_tmp = !in_is_tmp;
3171 const uint32_t offset_in = in_is_tmp ? offset_tmp : offset_dst;
3172 const uint32_t offset_out = out_is_tmp ? offset_tmp : offset_dst;
3173 const size_t align_in = in_is_tmp ? tmp_offset : ggml_webgpu_tensor_align_offset(ctx, dst);
3174 const size_t align_out = out_is_tmp ? tmp_offset : ggml_webgpu_tensor_align_offset(ctx, dst);
3175 const size_t size_in = in_is_tmp ? tmp_binding_size : dst_binding_size;
3176 const size_t size_out = out_is_tmp ? tmp_binding_size : dst_binding_size;
3177 const uint32_t top_k_out = (is_top_k && nm == 1) ? (uint32_t) dst->ne[0] : out_ne0;
3178 const uint32_t stride_out1 = top_k_out;
3179 const uint32_t stride_out2 = top_k_out * (uint32_t) dst->ne[1];
3180 const uint32_t stride_out3 = stride_out2 * (uint32_t) dst->ne[2];
3181
3182 std::vector<uint32_t> merge_params = { offset_src,
3183 offset_in,
3184 offset_out,
3185 stride_src1,
3186 stride_src2,
3187 stride_src3,
3188 stride_idx1,
3189 stride_idx2,
3190 stride_idx3,
3191 stride_out1,
3192 stride_out2,
3193 stride_out3,
3194 out_ne0,
3195 (uint32_t) src->ne[1],
3196 (uint32_t) src->ne[2],
3197 top_k_out,
3198 len,
3199 nm,
3200 nrows };
3201
3202 std::vector<wgpu::BindGroupEntry> merge_entries = {
3203 ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src),
3204 ggml_webgpu_make_bind_group_entry(1, ggml_webgpu_tensor_buf(dst), align_in, size_in),
3205 ggml_webgpu_make_bind_group_entry(2, ggml_webgpu_tensor_buf(dst), align_out, size_out)
3206 };
3207
3208 uint32_t wg_x_merge;
3209 uint32_t wg_y_merge;
3210 const uint32_t total_wg_merge = nm * nrows;
3211 compute_2d_workgroups(total_wg_merge, max_wg_per_dim, wg_x_merge, wg_y_merge);
3212
3213 dispatches.push_back({
3214 argsort_merge_pipeline, std::move(merge_params), std::move(merge_entries), { wg_x_merge, wg_y_merge }
3215 });
3216
3217 len <<= 1;
3218 in_is_tmp = !in_is_tmp;
3219 }
3220
3221 return ggml_backend_webgpu_build_multi(ctx, dispatches);
3222}
3223
3224static webgpu_encoded_op ggml_webgpu_cumsum(webgpu_context & ctx, ggml_tensor * src, ggml_tensor * dst) {
3225 std::vector<uint32_t> params = { (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src) / ggml_type_size(src->type)),
3226 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
3227 (uint32_t) src->ne[0] };
3228
3229 std::vector<wgpu::BindGroupEntry> entries = { ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src),
3230 ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, dst) };
3231
3232 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
3233 shader_lib_ctx.src0 = src;
3234 shader_lib_ctx.src1 = nullptr;
3235 shader_lib_ctx.dst = dst;
3236 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
3237
3238 webgpu_pipeline pipeline = ctx->shader_lib->get_cumsum_pipeline(shader_lib_ctx);
3239 uint32_t wg_x;
3240 uint32_t wg_y;
3241 uint32_t total_wg = ggml_nrows(dst);
3242 compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y);
3243 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
3244}
3245
3246static webgpu_encoded_op ggml_webgpu_sum_rows(webgpu_context & ctx, ggml_tensor * src, ggml_tensor * dst) {
3247 bool total_sum = dst->op == GGML_OP_SUM;
3248 std::vector<uint32_t> params = { (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src) / ggml_type_size(src->type)),
3249 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
3250 total_sum ? 0 : (uint32_t) (src->nb[1] / ggml_type_size(src->type)),
3251 total_sum ? 0 : (uint32_t) (src->nb[2] / ggml_type_size(src->type)),
3252 total_sum ? 0 : (uint32_t) (src->nb[3] / ggml_type_size(src->type)),
3253 total_sum ? static_cast<uint32_t>(ggml_nelements(src)) : (uint32_t) src->ne[0],
3254 total_sum ? 1 : (uint32_t) src->ne[1],
3255 total_sum ? 1 : (uint32_t) src->ne[2] };
3256
3257 std::vector<wgpu::BindGroupEntry> entries = { ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src),
3258 ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, dst) };
3259
3260 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
3261 shader_lib_ctx.src0 = src;
3262 shader_lib_ctx.dst = dst;
3263 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
3264
3265 webgpu_pipeline pipeline = ctx->shader_lib->get_sum_rows_pipeline(shader_lib_ctx);
3266
3267 uint32_t wg_x;
3268 uint32_t wg_y;
3269 uint32_t total_wg = total_sum ? 1 : ggml_nrows(dst);
3270 compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y);
3271 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
3272}
3273
3274static bool ggml_webgpu_can_fuse_rms_norm_mul(const struct ggml_cgraph * cgraph, int node_idx) {
3275 if (!ggml_can_fuse(cgraph, node_idx, { GGML_OP_RMS_NORM, GGML_OP_MUL })) {
3276 return false;
3277 }
3278
3279 // additional constraints specific to this fusion
3280 const ggml_tensor * rms_norm = cgraph->nodes[node_idx];
3281 const ggml_tensor * mul = cgraph->nodes[node_idx + 1];
3282
3283 GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32);
3284 GGML_ASSERT(rms_norm->type == GGML_TYPE_F32);
3285 // rms_norm only supports f32
3286 if (mul->src[0]->type != GGML_TYPE_F32 || mul->src[1]->type != GGML_TYPE_F32 || mul->type != GGML_TYPE_F32) {
3287 return false;
3288 }
3289 // if rms_norm is the B operand, then we don't handle broadcast
3290 if (rms_norm == mul->src[1] && !ggml_are_same_shape(mul->src[0], rms_norm)) {
3291 return false;
3292 }
3293 // rms_norm shader assumes contiguous rows
3294 if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) {
3295 return false;
3296 }
3297
3298 return true;
3299}
3300
3301static bool ggml_webgpu_can_fuse_gdn_cache(const struct ggml_cgraph * cgraph, int node_idx, int & num_encoded_ops) {
3302 const ggml_tensor * gdn = cgraph->nodes[node_idx];
3303
3304 // the kernel skips the snapshot tail, so the gdn output must not be a graph output
3305 if (gdn->op != GGML_OP_GATED_DELTA_NET || gdn->type != GGML_TYPE_F32 || (gdn->flags & GGML_TENSOR_FLAG_OUTPUT)) {
3306 return false;
3307 }
3308
3309 const ggml_tensor * src_v = gdn->src[2];
3310 const int64_t S_v = src_v->ne[0];
3311 const int64_t H = src_v->ne[1];
3312 const int64_t n_tokens = src_v->ne[2];
3313 const int64_t n_seqs = src_v->ne[3];
3314 const int64_t D = S_v * S_v * H;
3315 const int64_t K = ggml_get_op_params_i32(gdn, 0); // snapshot slot count
3316 const int64_t n_written = std::min<int64_t>(n_tokens, K); // newest n_written slots are written
3317
3318 // snapshot tail starts right after the attention scores
3319 const size_t tail_off = ggml_row_size(GGML_TYPE_F32, S_v * H * n_tokens * n_seqs);
3320
3321 // snapshot cpy is the first real node after the gdn (skip views/no-ops)
3322 const ggml_tensor * cpy = nullptr;
3323 int cpy_idx = 0;
3324 for (int j = node_idx + 1; j < cgraph->n_nodes && cpy == nullptr; ++j) {
3325 const ggml_tensor * n = cgraph->nodes[j];
3326 if (ggml_op_is_empty(n->op) || ggml_is_empty(n)) {
3327 continue;
3328 }
3329 if (n->op != GGML_OP_CPY || (n->flags & GGML_TENSOR_FLAG_OUTPUT)) {
3330 return false;
3331 }
3332 cpy = n;
3333 cpy_idx = j;
3334 }
3335 if (cpy == nullptr) {
3336 return false;
3337 }
3338
3339 const ggml_tensor * cpy_src = cpy->src[0]; // view of the gdn snapshot tail
3340 const ggml_tensor * cpy_dst = cpy->src[1]; // cache view the kernel writes to
3341
3342 // src must be this gdn's snapshot tail (contiguous, at the tail offset)
3343 if (cpy_src->op != GGML_OP_VIEW || cpy_src->view_src != gdn || cpy_src->view_offs != tail_off ||
3344 !ggml_is_contiguous(cpy_src)) {
3345 return false;
3346 }
3347
3348 // dst is the [D, n_seqs, n_written] cache view; require nb[1] == D (the per-seq stride the kernel
3349 // assumes). ggml_cpy pins src to the same element count.
3350 const std::array<int64_t, GGML_MAX_DIMS> expected_ne = { D, n_seqs, n_written, 1 };
3351 if (cpy_dst->op != GGML_OP_VIEW || cpy_dst->type != GGML_TYPE_F32 || cpy_dst->data == nullptr ||
3352 !std::equal(expected_ne.begin(), expected_ne.end(), cpy_dst->ne) ||
3353 cpy_dst->nb[0] != ggml_type_size(GGML_TYPE_F32) || cpy_dst->nb[1] != (size_t) ggml_row_size(GGML_TYPE_F32, D)) {
3354 return false;
3355 }
3356
3357 num_encoded_ops = cpy_idx - node_idx + 1;
3358
3359 return true;
3360}
3361
3362static webgpu_encoded_op ggml_webgpu_upscale(webgpu_context ctx, ggml_tensor * src, ggml_tensor * dst) {
3363 const uint32_t mode_flags = (uint32_t) ggml_get_op_params_i32(dst, 0);
3364 std::vector<uint32_t> params = { (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src) / ggml_type_size(src->type)),
3365 (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
3366
3367 (uint32_t) (src->nb[0] / ggml_type_size(src->type)),
3368 (uint32_t) (src->nb[1] / ggml_type_size(src->type)),
3369 (uint32_t) (src->nb[2] / ggml_type_size(src->type)),
3370 (uint32_t) (src->nb[3] / ggml_type_size(src->type)),
3371
3372 (uint32_t) (dst->nb[0] / ggml_type_size(dst->type)),
3373 (uint32_t) (dst->nb[1] / ggml_type_size(dst->type)),
3374 (uint32_t) (dst->nb[2] / ggml_type_size(dst->type)),
3375 (uint32_t) (dst->nb[3] / ggml_type_size(dst->type)),
3376
3377 (uint32_t) src->ne[0],
3378 (uint32_t) src->ne[1],
3379 (uint32_t) src->ne[2],
3380 (uint32_t) src->ne[3],
3381
3382 (uint32_t) dst->ne[0],
3383 (uint32_t) dst->ne[1],
3384 (uint32_t) dst->ne[2],
3385 (uint32_t) dst->ne[3],
3386
3387 mode_flags };
3388
3389 std::vector<wgpu::BindGroupEntry> entries = { ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src),
3390 ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, dst) };
3391
3392 ggml_webgpu_shader_lib_context shader_lib_ctx = {};
3393 shader_lib_ctx.src0 = src;
3394 shader_lib_ctx.dst = dst;
3395 shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
3396
3397 webgpu_pipeline pipeline = ctx->shader_lib->get_upscale_pipeline(shader_lib_ctx);
3398 auto * decisions = static_cast<ggml_webgpu_generic_shader_decisions *>(pipeline.context.get());
3399
3400 uint32_t wg_x;
3401 uint32_t wg_y;
3402 uint32_t total_wg = CEIL_DIV((uint32_t) ggml_nelements(dst), decisions->wg_size);
3403 compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y);
3404
3405 return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
3406}
3407
3408// Returns the encoded command, or std::nullopt if the operation is a no-op
3409static std::optional<webgpu_encoded_op> ggml_webgpu_encode(webgpu_context ctx,
3410 ggml_cgraph * cgraph,
3411 int node_idx,
3412 int & num_encoded_ops) {
3413 ggml_tensor ** nodes = cgraph->nodes;
3414 ggml_tensor * node = nodes[node_idx];
3415
3416 if (ggml_is_empty(node)) {
3417 return std::nullopt;
3418 }
3419 if ((node->flags & GGML_TENSOR_FLAG_COMPUTE) == 0) {
3420 return std::nullopt;
3421 }
3422 WEBGPU_LOG_DEBUG("ggml_webgpu_encode(" << node << ", " << ggml_op_name(node->op) << ")");
3423
3424 ggml_tensor * src0 = node->src[0];
3425 ggml_tensor * src1 = node->src[1];
3426 ggml_tensor * src2 = node->src[2];
3427
3428 switch (node->op) {
3429 // no-ops
3430 case GGML_OP_NONE:
3431 case GGML_OP_VIEW:
3432 case GGML_OP_PERMUTE:
3433 case GGML_OP_TRANSPOSE:
3434 case GGML_OP_RESHAPE:
3435 return std::nullopt;
3436 case GGML_OP_DUP:
3437 case GGML_OP_CPY:
3438 case GGML_OP_CONT:
3439 return ggml_webgpu_cpy(ctx, src0, node);
3440 case GGML_OP_SET:
3441 return ggml_webgpu_set(ctx, src0, src1, node);
3442 case GGML_OP_SET_ROWS:
3443 return ggml_webgpu_set_rows(ctx, src0, src1, node);
3444 case GGML_OP_GET_ROWS:
3445 return ggml_webgpu_get_rows(ctx, src0, src1, node);
3446 case GGML_OP_MUL_MAT:
3447 return ggml_webgpu_mul_mat(ctx, src0, src1, node);
3448 case GGML_OP_MUL_MAT_ID:
3449 return ggml_webgpu_mul_mat_id(ctx, src0, src1, src2, node);
3450 case GGML_OP_FLASH_ATTN_EXT:
3451 return ggml_webgpu_flash_attn(ctx, src0, src1, src2, node->src[3], node->src[4], node);
3452 case GGML_OP_ADD:
3453 case GGML_OP_SUB:
3454 case GGML_OP_MUL:
3455 case GGML_OP_DIV:
3456 return ggml_webgpu_binary_op(ctx, src0, src1, node);
3457 case GGML_OP_ADD_ID:
3458 return ggml_webgpu_add_id(ctx, src0, src1, src2, node);
3459 case GGML_OP_CONCAT:
3460 return ggml_webgpu_concat(ctx, src0, src1, node);
3461 case GGML_OP_REPEAT:
3462 return ggml_webgpu_repeat(ctx, src0, node);
3463 case GGML_OP_RMS_NORM:
3464 if (ggml_webgpu_can_fuse_rms_norm_mul(cgraph, node_idx)) {
3465 num_encoded_ops = 2;
3466 ggml_tensor * mul_node = nodes[node_idx + 1];
3467 return ggml_webgpu_rms_norm_mul(ctx, src0, node, mul_node->src[0], mul_node->src[1], mul_node);
3468 } else {
3469 return ggml_webgpu_row_norm(ctx, src0, node);
3470 }
3471 case GGML_OP_NORM:
3472 case GGML_OP_L2_NORM:
3473 return ggml_webgpu_row_norm(ctx, src0, node);
3474 case GGML_OP_ROPE:
3475 return ggml_webgpu_rope(ctx, src0, src1, src2, node);
3476 case GGML_OP_GLU:
3477 return ggml_webgpu_glu(ctx, src0, src1, node);
3478 case GGML_OP_SCALE:
3479 return ggml_webgpu_scale(ctx, src0, node);
3480 case GGML_OP_SOFT_MAX:
3481 return ggml_webgpu_soft_max(ctx, src0, src1, src2, node);
3482 case GGML_OP_UNARY:
3483 case GGML_OP_CLAMP:
3484 case GGML_OP_FILL:
3485 case GGML_OP_LOG:
3486 case GGML_OP_SQR:
3487 case GGML_OP_SQRT:
3488 case GGML_OP_SIN:
3489 case GGML_OP_COS:
3490 case GGML_OP_DIAG:
3491 case GGML_OP_TRI:
3492 return ggml_webgpu_unary_op(ctx, src0, node);
3493 case GGML_OP_SOLVE_TRI:
3494 return ggml_webgpu_solve_tri(ctx, src0, src1, node);
3495 case GGML_OP_SSM_CONV:
3496 return ggml_webgpu_ssm_conv(ctx, src0, src1, node);
3497 case GGML_OP_SSM_SCAN:
3498 return ggml_webgpu_ssm_scan(ctx, src0, src1, src2, node->src[3], node->src[4], node->src[5], node->src[6],
3499 node);
3500 case GGML_OP_GATED_DELTA_NET:
3501 if (ggml_webgpu_can_fuse_gdn_cache(cgraph, node_idx, num_encoded_ops)) {
3502 ggml_tensor * dst_fuse = cgraph->nodes[node_idx + num_encoded_ops - 1]->src[1];
3503 return ggml_webgpu_gated_delta_net(ctx, src0, src1, src2, node->src[3], node->src[4], node->src[5],
3504 node, dst_fuse);
3505 } else {
3506 return ggml_webgpu_gated_delta_net(ctx, src0, src1, src2, node->src[3], node->src[4], node->src[5],
3507 node, nullptr);
3508 }
3509 case GGML_OP_ARANGE:
3510 return ggml_webgpu_arange(ctx, node);
3511 case GGML_OP_PAD:
3512 return ggml_webgpu_pad(ctx, src0, node);
3513 case GGML_OP_ARGMAX:
3514 return ggml_webgpu_argmax(ctx, src0, node);
3515 case GGML_OP_ARGSORT:
3516 case GGML_OP_TOP_K:
3517 // we reuse the same argsort implementation for top_k
3518 return ggml_webgpu_argsort(ctx, src0, node);
3519 case GGML_OP_CUMSUM:
3520 return ggml_webgpu_cumsum(ctx, src0, node);
3521 case GGML_OP_SUM:
3522 case GGML_OP_SUM_ROWS:
3523 return ggml_webgpu_sum_rows(ctx, src0, node);
3524 case GGML_OP_CONV_2D:
3525 return ggml_webgpu_conv_2d(ctx, src0, src1, node);
3526 case GGML_OP_CONV_2D_DW:
3527 return ggml_webgpu_conv_2d_dw(ctx, src0, src1, node);
3528 case GGML_OP_IM2COL:
3529 return ggml_webgpu_im2col(ctx, src0, src1, node);
3530 case GGML_OP_UPSCALE:
3531 return ggml_webgpu_upscale(ctx, src0, node);
3532 default:
3533 return std::nullopt;
3534 }
3535}
3536
3537#ifdef GGML_WEBGPU_GPU_PROFILE
3538static void ggml_backend_webgpu_collect_profile_results(webgpu_context & ctx,
3539 const std::vector<std::string> & pipeline_names,
3540 uint32_t & num_inflight_batches) {
3541 if (pipeline_names.empty()) {
3542 return;
3543 }
3544
3545 wgpu::CommandEncoder encoder = ctx->global_ctx->device.CreateCommandEncoder();
3546 encoder.ResolveQuerySet(ctx->profile_timestamp_query_set, 0, ctx->profile_timestamp_query_count,
3547 ctx->profile_timestamp_dev_buf, 0);
3548 encoder.CopyBufferToBuffer(ctx->profile_timestamp_dev_buf, 0, ctx->profile_timestamp_host_buf, 0,
3549 ctx->profile_timestamp_query_count * sizeof(uint64_t));
3550
3551 wgpu::CommandBuffer profile_commands = encoder.Finish();
3552 ggml_backend_webgpu_submit_commands(ctx, profile_commands, num_inflight_batches);
3553
3554 const size_t mapped_size = ctx->profile_timestamp_query_count * sizeof(uint64_t);
3555 GGML_ASSERT(ctx->profile_timestamp_query_count == 2 * pipeline_names.size());
3556
3557 ggml_backend_webgpu_map_buffer(ctx->global_ctx, ctx->profile_timestamp_host_buf, wgpu::MapMode::Read, 0,
3558 mapped_size);
3559 const uint64_t * ts_data = (const uint64_t *) ctx->profile_timestamp_host_buf.GetConstMappedRange(0, mapped_size);
3560
3561 for (size_t i = 0; i < pipeline_names.size(); ++i) {
3562 // WebGPU timestamps are in ns; convert to ms.
3563 const double elapsed_ms = double(ts_data[2 * i + 1] - ts_data[2 * i]) * 1e-6;
3564 ctx->shader_gpu_time_ms[pipeline_names[i]] += elapsed_ms;
3565 }
3566
3567 ctx->profile_timestamp_host_buf.Unmap();
3568}
3569#endif
3570
3571// Don't bother checking set_rows index overflow for now, since practically the WebGPU doesn't need to support
3572// models that would require it right now.
3573static void ggml_backend_webgpu_check_set_rows(webgpu_context & ctx, uint32_t & num_inflight_batches) {
3574#ifdef GGML_WEBGPU_CHECK_SET_ROWS
3575 wgpu::CommandEncoder encoder = ctx->global_ctx->device.CreateCommandEncoder();
3576 encoder.CopyBufferToBuffer(ctx->set_rows_dev_error_buf, 0, ctx->set_rows_host_error_buf, 0,
3577 ctx->set_rows_host_error_buf.GetSize());
3578 wgpu::CommandBuffer commands = encoder.Finish();
3579 ggml_backend_webgpu_submit_commands(ctx, commands, num_inflight_batches);
3580 ggml_backend_webgpu_map_buffer(ctx->global_ctx, ctx->set_rows_host_error_buf, wgpu::MapMode::Read, 0,
3581 ctx->set_rows_host_error_buf.GetSize());
3582 const uint32_t * error_data = (const uint32_t *) ctx->set_rows_host_error_buf.GetConstMappedRange();
3583 if (*error_data) {
3584 GGML_ABORT("ggml_webgpu: SET_ROWS index > 2^32, unsupported.");
3585 }
3586 ctx->set_rows_host_error_buf.Unmap();
3587#else
3588 GGML_UNUSED(ctx);
3589 GGML_UNUSED(num_inflight_batches);
3590#endif
3591}
3592
3593static ggml_status ggml_backend_webgpu_graph_compute(ggml_backend_t backend, struct ggml_cgraph * cgraph) {
3594 WEBGPU_LOG_DEBUG("ggml_backend_webgpu_graph_compute(" << cgraph->n_nodes << " nodes)");
3595
3596 ggml_backend_webgpu_context * backend_ctx = (ggml_backend_webgpu_context *) backend->context;
3597 webgpu_context ctx = backend_ctx->webgpu_ctx;
3598
3599 WEBGPU_CPU_PROFILE_TOTAL_START(graph_compute);
3600
3601 std::vector<webgpu_encoded_op> commands;
3602
3603 uint32_t num_batched_kernels = 0;
3604 uint32_t num_inflight_batches = 0;
3605 bool contains_set_rows = false;
3606 int num_encoded_ops = 1;
3607 int node_idx = 0;
3608
3609#ifdef GGML_WEBGPU_GPU_PROFILE
3610 ctx->profile_timestamp_query_count = 0;
3611 std::vector<std::string> profile_pipeline_names;
3612#endif
3613
3614 ctx->active_command_encoder = ctx->global_ctx->device.CreateCommandEncoder();
3615 if (ctx->batch_compute_passes) {
3616 ctx->active_compute_pass = ctx->active_command_encoder.BeginComputePass();
3617 }
3618
3619 while (node_idx < cgraph->n_nodes) {
3620 if (cgraph->nodes[node_idx]->op == GGML_OP_SET_ROWS) {
3621 contains_set_rows = true;
3622 }
3623 if (auto cmd = ggml_webgpu_encode(ctx, cgraph, node_idx, num_encoded_ops)) {
3624 commands.push_back(*cmd);
3625 num_batched_kernels += cmd.value().num_kernels;
3626#ifdef GGML_WEBGPU_GPU_PROFILE
3627 profile_pipeline_names.insert(profile_pipeline_names.end(), cmd->pipeline_names.begin(),
3628 cmd->pipeline_names.end());
3629#endif
3630 }
3631
3632 if (num_batched_kernels >= ctx->global_ctx->command_submit_batch_size) {
3633 if (ctx->active_compute_pass) {
3634 ctx->active_compute_pass.End();
3635 }
3636 num_batched_kernels = 0;
3637 wgpu::CommandBuffer batch_commands = ctx->active_command_encoder.Finish();
3638 ggml_backend_webgpu_submit_commands(ctx, batch_commands, num_inflight_batches);
3639
3640 // reset state for next batch
3641 ctx->active_command_encoder = ctx->global_ctx->device.CreateCommandEncoder();
3642 if (ctx->batch_compute_passes) {
3643 ctx->active_compute_pass = ctx->active_command_encoder.BeginComputePass();
3644 }
3645 ctx->param_arena.reset();
3646 commands.clear();
3647#ifdef GGML_WEBGPU_GPU_PROFILE
3648 // flush before the next batch can overflow the QuerySet
3649 if (ctx->profile_timestamp_query_count + 2 * ctx->global_ctx->command_submit_batch_size >=
3650 WEBGPU_MAX_PROFILE_QUERY_COUNT) {
3651 ggml_backend_webgpu_collect_profile_results(ctx, profile_pipeline_names, num_inflight_batches);
3652 // reset profile timestamp state
3653 ctx->profile_timestamp_query_count = 0;
3654 profile_pipeline_names.clear();
3655 }
3656#endif
3657 }
3658
3659 node_idx += num_encoded_ops;
3660 num_encoded_ops = 1;
3661 }
3662
3663 if (ctx->active_compute_pass) {
3664 ctx->active_compute_pass.End();
3665 ctx->active_compute_pass = nullptr;
3666 }
3667
3668 if (num_batched_kernels > 0) {
3669 wgpu::CommandBuffer batch_commands = ctx->active_command_encoder.Finish();
3670 ggml_backend_webgpu_submit_commands(ctx, batch_commands, num_inflight_batches);
3671 ctx->param_arena.reset();
3672 commands.clear();
3673 }
3674 ctx->active_command_encoder = nullptr;
3675
3676#ifdef GGML_WEBGPU_GPU_PROFILE
3677 ggml_backend_webgpu_collect_profile_results(ctx, profile_pipeline_names, num_inflight_batches);
3678#endif
3679
3680 if (contains_set_rows) {
3681 ggml_backend_webgpu_check_set_rows(ctx, num_inflight_batches);
3682 }
3683
3684 WEBGPU_CPU_PROFILE_TOTAL_END(graph_compute, ctx->global_ctx);
3685 return GGML_STATUS_SUCCESS;
3686}
3687
3688struct ggml_backend_webgpu_event_context {
3689 webgpu_global_context global_ctx;
3690 wgpu::Future future;
3691 bool recorded = false;
3692};
3693
3694static ggml_backend_event_t ggml_backend_webgpu_device_event_new(ggml_backend_dev_t device) {
3695 ggml_backend_webgpu_device_context * dev_ctx = (ggml_backend_webgpu_device_context *) device->context;
3696
3697 auto * event_ctx = new ggml_backend_webgpu_event_context();
3698 event_ctx->global_ctx = dev_ctx->webgpu_global_ctx;
3699
3700 auto * event = new ggml_backend_event;
3701 event->device = device;
3702 event->context = event_ctx;
3703 return event;
3704}
3705
3706static void ggml_backend_webgpu_device_event_free(ggml_backend_dev_t dev, ggml_backend_event_t event) {
3707 GGML_UNUSED(dev);
3708 delete static_cast<ggml_backend_webgpu_event_context *>(event->context);
3709 delete event;
3710}
3711
3712static void ggml_backend_webgpu_device_event_synchronize(ggml_backend_dev_t dev, ggml_backend_event_t event) {
3713 GGML_UNUSED(dev);
3714 ggml_backend_webgpu_event_context * event_ctx = (ggml_backend_webgpu_event_context *) event->context;
3715 if (!event_ctx->recorded) {
3716 return;
3717 }
3718 wgpu::WaitStatus status =
3719 event_ctx->global_ctx->instance.WaitAny(event_ctx->future, WEBGPU_RUNTIME_WAIT_TIMEOUT_NS);
3720 if (status == wgpu::WaitStatus::TimedOut) {
3721 GGML_ABORT("ggml_webgpu: event_synchronize timed out after %u ms\n", WEBGPU_RUNTIME_WAIT_TIMEOUT_MS);
3722 }
3723 event_ctx->recorded = false;
3724}
3725
3726static void ggml_backend_webgpu_event_record(ggml_backend_t backend, ggml_backend_event_t event) {
3727 ggml_backend_webgpu_context * backend_ctx = (ggml_backend_webgpu_context *) backend->context;
3728 ggml_backend_webgpu_event_context * event_ctx = (ggml_backend_webgpu_event_context *) event->context;
3729
3730 event_ctx->future = backend_ctx->webgpu_ctx->global_ctx->queue.OnSubmittedWorkDone(
3731 wgpu::CallbackMode::AllowSpontaneous, [](wgpu::QueueWorkDoneStatus, wgpu::StringView) {});
3732 event_ctx->recorded = true;
3733}
3734
3735static void ggml_backend_webgpu_event_wait(ggml_backend_t backend, ggml_backend_event_t event) {
3736 GGML_UNUSED(backend);
3737 ggml_backend_webgpu_device_event_synchronize(nullptr, event);
3738}
3739
3740static void ggml_backend_webgpu_set_tensor_async(ggml_backend_t backend,
3741 ggml_tensor * tensor,
3742 const void * data,
3743 size_t offset,
3744 size_t size) {
3745 GGML_UNUSED(backend);
3746 auto * buf_ctx = (ggml_backend_webgpu_buffer_context *) tensor->buffer->context;
3747 size_t total_offset = ggml_webgpu_tensor_offset(tensor) + offset;
3748
3749 // Write aligned portion
3750 buf_ctx->global_ctx->queue.WriteBuffer(buf_ctx->buffer, total_offset, data, (size / 4) * 4);
3751
3752 if (size % 4 != 0) {
3753 // If size is not a multiple of 4, we need to memset the remaining bytes
3754 size_t remaining_size = size % 4;
3755
3756 // pack the remaining bytes into a uint32_t
3757 uint32_t val32 = 0;
3758
3759 for (size_t i = 0; i < remaining_size; i++) {
3760 ((uint8_t *) &val32)[i] = ((const uint8_t *) data)[size - remaining_size + i];
3761 }
3762 // memset the remaining bytes
3763 ggml_backend_webgpu_buffer_memset(buf_ctx->global_ctx, buf_ctx->buffer, val32,
3764 total_offset + (size - remaining_size), remaining_size);
3765 }
3766}
3767
3768static void ggml_backend_webgpu_synchronize(ggml_backend_t backend) {
3769 ggml_backend_webgpu_context * backend_ctx = (ggml_backend_webgpu_context *) backend->context;
3770 ggml_backend_webgpu_wait_queue(backend_ctx->webgpu_ctx->global_ctx);
3771}
3772
3773static ggml_backend_i ggml_backend_webgpu_i = {
3774 /* .get_name = */ ggml_backend_webgpu_name,
3775 /* .free = */ ggml_backend_webgpu_free,
3776 /* .set_tensor_async = */ ggml_backend_webgpu_set_tensor_async,
3777 /* .get_tensor_async = */ NULL,
3778 /* .set_tensor_2d_async = */ NULL,
3779 /* .get_tensor_2d_async = */ NULL,
3780 /* .cpy_tensor_async = */ NULL,
3781 /* .synchronize = */ ggml_backend_webgpu_synchronize,
3782 /* .graph_plan_create = */ NULL,
3783 /* .graph_plan_free = */ NULL,
3784 /* .graph_plan_update = */ NULL,
3785 /* .graph_plan_compute = */ NULL,
3786 /* .graph_compute = */ ggml_backend_webgpu_graph_compute,
3787 /* .event_record = */ ggml_backend_webgpu_event_record,
3788 /* .event_wait = */ ggml_backend_webgpu_event_wait,
3789 /* .graph_optimize = */ NULL,
3790};
3791
3792/* End GGML Backend Interface */
3793
3794/* GGML Backend Buffer Interface */
3795
3796static void ggml_backend_webgpu_buffer_free_buffer(ggml_backend_buffer_t buffer) {
3797 ggml_backend_webgpu_buffer_context * ctx = static_cast<ggml_backend_webgpu_buffer_context *>(buffer->context);
3798 if (ctx != nullptr && ctx->buffer != nullptr) {
3799 ctx->buffer.Destroy();
3800 delete ctx;
3801 }
3802}
3803
3804// Returns the "fake" base pointer.
3805static void * ggml_backend_webgpu_buffer_get_base(ggml_backend_buffer_t buffer) {
3806 GGML_UNUSED(buffer);
3807 return webgpu_ptr_base;
3808}
3809
3810static void ggml_backend_webgpu_buffer_memset_tensor(ggml_backend_buffer_t buffer,
3811 ggml_tensor * tensor,
3812 uint8_t value,
3813 size_t offset,
3814 size_t size) {
3815 if (size == 0) {
3816 WEBGPU_LOG_DEBUG(
3817 "ggml_backend_webgpu_buffer_memset_tensor: size is zero, "
3818 "nothing to do.");
3819 return;
3820 }
3821
3822 WEBGPU_CPU_PROFILE_TOTAL_START(memset_tensor);
3823
3824 ggml_backend_webgpu_buffer_context * buf_ctx = (ggml_backend_webgpu_buffer_context *) buffer->context;
3825
3826 WEBGPU_LOG_DEBUG("ggml_backend_webgpu_buffer_memset_tensor(" << buf_ctx->label << ", " << tensor << ", " << value
3827 << ", " << offset << ", " << size << ")");
3828
3829 size_t total_offset = ggml_webgpu_tensor_offset(tensor) + offset;
3830
3831 // This is a trick to set all bytes of a u32 to the same 1 byte value.
3832 uint32_t val32 = (uint32_t) value * 0x01010101;
3833 ggml_backend_webgpu_buffer_memset(buf_ctx->global_ctx, buf_ctx->buffer, val32, total_offset, size);
3834 WEBGPU_CPU_PROFILE_TOTAL_END(memset_tensor, buf_ctx->global_ctx);
3835}
3836
3837static void ggml_backend_webgpu_buffer_set_tensor(ggml_backend_buffer_t buffer,
3838 ggml_tensor * tensor,
3839 const void * data,
3840 size_t offset,
3841 size_t size) {
3842 WEBGPU_CPU_PROFILE_TOTAL_START(set_tensor);
3843 ggml_backend_webgpu_buffer_context * buf_ctx = (ggml_backend_webgpu_buffer_context *) buffer->context;
3844
3845 WEBGPU_LOG_DEBUG("ggml_backend_webgpu_buffer_set_tensor(" << buf_ctx->label << ", " << tensor << ", " << data
3846 << ", " << offset << ", " << size << ")");
3847
3848 size_t total_offset = ggml_webgpu_tensor_offset(tensor) + offset;
3849
3850 // WriteBuffer needs the offset and the size to be multiples of 4.
3851 // Write the misaligned head bytes using compute memset, then increment total_offset
3852 // and data pointer so that they are 4-aligned.
3853 if (total_offset % 4 != 0) {
3854 size_t lane = total_offset % 4; // in-word lane the head starts at (the tail below always starts at 0)
3855 size_t head = std::min<size_t>(4 - lane, size);
3856
3857 // Pack head bytes into a uint32_t
3858 uint32_t head_val = 0;
3859 for (size_t i = 0; i < head; i++) {
3860 ((uint8_t *) &head_val)[lane + i] = ((const uint8_t *) data)[i];
3861 }
3862 ggml_backend_webgpu_buffer_memset(buf_ctx->global_ctx, buf_ctx->buffer, head_val, total_offset, head);
3863
3864 total_offset += head;
3865 size -= head;
3866 data = (const uint8_t *) data + head;
3867 }
3868
3869 if (size > 0) {
3870 buf_ctx->global_ctx->queue.WriteBuffer(buf_ctx->buffer, total_offset, data, (size / 4) * 4);
3871 }
3872
3873 if (size % 4 != 0) {
3874 // If size is not a multiple of 4, we need to memset the remaining bytes
3875 size_t remaining_size = size % 4;
3876
3877 // pack the remaining bytes into a uint32_t
3878 uint32_t val32 = 0;
3879
3880 for (size_t i = 0; i < remaining_size; i++) {
3881 ((uint8_t *) &val32)[i] = ((const uint8_t *) data)[size - remaining_size + i];
3882 }
3883 // memset the remaining bytes
3884 ggml_backend_webgpu_buffer_memset(buf_ctx->global_ctx, buf_ctx->buffer, val32,
3885 total_offset + (size - remaining_size), remaining_size);
3886 }
3887 WEBGPU_CPU_PROFILE_TOTAL_END(set_tensor, buf_ctx->global_ctx);
3888}
3889
3890static void ggml_backend_webgpu_buffer_get_tensor(ggml_backend_buffer_t buffer,
3891 const ggml_tensor * tensor,
3892 void * data,
3893 size_t offset,
3894 size_t size) {
3895 WEBGPU_CPU_PROFILE_TOTAL_START(get_tensor);
3896 ggml_backend_webgpu_buffer_context * buf_ctx = (ggml_backend_webgpu_buffer_context *) buffer->context;
3897 WEBGPU_LOG_DEBUG("ggml_backend_webgpu_buffer_get_tensor(" << buf_ctx->label << ", " << tensor << ", " << data
3898 << ", " << offset << ", " << size << ")");
3899 wgpu::Device device = buf_ctx->global_ctx->device;
3900
3901 size_t total_offset = ggml_webgpu_tensor_offset(tensor) + offset;
3902
3903 size_t local_offset = total_offset % 4;
3904 if (local_offset != 0) {
3905 // If offset is not a multiple of 4, we need to round it down to the previous
3906 // multiple of 4
3907 total_offset -= local_offset;
3908 }
3909
3910 size_t final_size = size + local_offset;
3911 if (final_size % 4 != 0) {
3912 // If size is not a multiple of 4, we need to round it up to the next
3913 // multiple of 4
3914 final_size += 4 - (final_size % 4);
3915 }
3916
3917 std::lock_guard<std::recursive_mutex> lock(buf_ctx->global_ctx->mutex);
3918
3919 if (buf_ctx->global_ctx->get_tensor_staging_buf == nullptr ||
3920 buf_ctx->global_ctx->get_tensor_staging_buf.GetSize() < final_size) {
3921 // Create a new staging buffer if it doesn't exist or is too small
3922 if (buf_ctx->global_ctx->get_tensor_staging_buf) {
3923 buf_ctx->global_ctx->get_tensor_staging_buf.Destroy();
3924 }
3925 ggml_webgpu_create_buffer(device, buf_ctx->global_ctx->get_tensor_staging_buf, final_size,
3926 wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::MapRead, "get_tensor_staging_buf");
3927 }
3928
3929 // Copy the data from the buffer to the staging buffer
3930 wgpu::CommandEncoder encoder = device.CreateCommandEncoder();
3931 encoder.CopyBufferToBuffer(buf_ctx->buffer, total_offset, buf_ctx->global_ctx->get_tensor_staging_buf, 0,
3932 final_size);
3933 wgpu::CommandBuffer commands = encoder.Finish();
3934
3935 // Submit the command buffer to the queue
3936 buf_ctx->global_ctx->queue.Submit(1, &commands);
3937
3938 // Map the staging buffer to read the data
3939 ggml_backend_webgpu_map_buffer(buf_ctx->global_ctx, buf_ctx->global_ctx->get_tensor_staging_buf,
3940 wgpu::MapMode::Read, 0, final_size);
3941 // Must specify size here since the staging buffer might be larger than the tensor size
3942 const void * mapped_range = buf_ctx->global_ctx->get_tensor_staging_buf.GetConstMappedRange(0, final_size);
3943
3944 // Copy the data from the mapped range to the output buffer
3945 std::memcpy(data, (const void *) ((const char *) mapped_range + local_offset), size);
3946 buf_ctx->global_ctx->get_tensor_staging_buf.Unmap();
3947 WEBGPU_CPU_PROFILE_TOTAL_END(get_tensor, buf_ctx->global_ctx);
3948}
3949
3950static void ggml_backend_webgpu_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
3951 WEBGPU_LOG_DEBUG("ggml_backend_webgpu_buffer_clear(" << buffer << ", " << (uint32_t) value << ")");
3952 WEBGPU_CPU_PROFILE_TOTAL_START(clear);
3953 ggml_backend_webgpu_buffer_context * buf_ctx = (ggml_backend_webgpu_buffer_context *) buffer->context;
3954 ggml_backend_webgpu_buffer_memset(buf_ctx->global_ctx, buf_ctx->buffer, value, 0, buffer->size);
3955 WEBGPU_CPU_PROFILE_TOTAL_END(clear, buf_ctx->global_ctx);
3956}
3957
3958static ggml_backend_buffer_i ggml_backend_webgpu_buffer_interface = {
3959 /* .free_buffer = */ ggml_backend_webgpu_buffer_free_buffer,
3960 /* .get_base = */ ggml_backend_webgpu_buffer_get_base,
3961 /* .init_tensor = */ NULL, // TODO: optional, needed?
3962 /* .memset_tensor = */ ggml_backend_webgpu_buffer_memset_tensor,
3963 /* .set_tensor = */ ggml_backend_webgpu_buffer_set_tensor,
3964 /* .get_tensor = */ ggml_backend_webgpu_buffer_get_tensor,
3965 /* .set_tensor_2d = */ NULL,
3966 /* .get_tensor_2d = */ NULL,
3967 /* .cpy_tensor = */ NULL, // TODO: optional, implement this
3968 /* .clear = */ ggml_backend_webgpu_buffer_clear,
3969 /* .reset = */ NULL, // TODO: optional, think it coordinates with
3970 /* .set_tensor_n = */ NULL,
3971 /* .get_tensor_n = */ NULL,
3972 /* .cpy_tensor_n = */ NULL,
3973};
3974
3975/* End GGML Backend Buffer Interface */
3976
3977/* GGML Backend Buffer Type Interface */
3978
3979static const char * ggml_backend_webgpu_buffer_type_get_name(ggml_backend_buffer_type_t buft) {
3980 ggml_backend_webgpu_device_context * ctx = static_cast<ggml_backend_webgpu_device_context *>(buft->device->context);
3981 return ctx->device_name.c_str();
3982}
3983
3984static ggml_backend_buffer_t ggml_backend_webgpu_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft,
3985 size_t size) {
3986 static std::atomic<int> buffer_count;
3987 int buffer_id = buffer_count++;
3988 std::string buf_name = "tensor_buf" + std::to_string(buffer_id);
3989 WEBGPU_LOG_DEBUG("ggml_backend_webgpu_buffer_type_alloc_buffer_" << buffer_id << ": " << size << " bytes");
3990
3991 ggml_backend_webgpu_device_context * ctx = static_cast<ggml_backend_webgpu_device_context *>(buft->device->context);
3992 wgpu::Buffer buf;
3993 ggml_webgpu_create_buffer(ctx->webgpu_global_ctx->device, buf, ROUNDUP_POW2(size, WEBGPU_STORAGE_BUF_BINDING_MULT),
3994 wgpu::BufferUsage::Storage | wgpu::BufferUsage::CopySrc | wgpu::BufferUsage::CopyDst,
3995 buf_name.c_str());
3996
3997 ggml_backend_webgpu_buffer_context * buf_ctx =
3998 new ggml_backend_webgpu_buffer_context(buf, buf_name, ctx->webgpu_global_ctx);
3999
4000 return ggml_backend_buffer_init(buft, ggml_backend_webgpu_buffer_interface, buf_ctx, size);
4001}
4002
4003static size_t ggml_backend_webgpu_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
4004 ggml_backend_webgpu_device_context * dev_ctx =
4005 static_cast<ggml_backend_webgpu_device_context *>(buft->device->context);
4006 return dev_ctx->webgpu_global_ctx->capabilities.limits.minStorageBufferOffsetAlignment;
4007}
4008
4009// maxBufferSize might be larger, but you can't bind more than
4010// maxStorageBufferBindingSize to a single binding.
4011static size_t ggml_backend_webgpu_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
4012 ggml_backend_webgpu_device_context * dev_ctx =
4013 static_cast<ggml_backend_webgpu_device_context *>(buft->device->context);
4014 return dev_ctx->webgpu_global_ctx->capabilities.limits.maxStorageBufferBindingSize;
4015}
4016
4017static size_t ggml_backend_webgpu_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft,
4018 const ggml_tensor * tensor) {
4019 ggml_backend_webgpu_device_context * ctx = static_cast<ggml_backend_webgpu_device_context *>(buft->device->context);
4020 size_t res = ggml_nbytes(tensor);
4021 switch (tensor->op) {
4022 case GGML_OP_ARGSORT:
4023 res = ROUNDUP_POW2(res * 2 + ctx->webgpu_global_ctx->capabilities.limits.minStorageBufferOffsetAlignment,
4024 WEBGPU_STORAGE_BUF_BINDING_MULT);
4025 break;
4026 case GGML_OP_TOP_K:
4027 {
4028 const ggml_tensor * src0 = tensor->src[0];
4029 if (src0) {
4030 const size_t full = sizeof(int32_t) * ggml_nelements(src0);
4031 res = ROUNDUP_POW2(
4032 full * 2 + ctx->webgpu_global_ctx->capabilities.limits.minStorageBufferOffsetAlignment,
4033 WEBGPU_STORAGE_BUF_BINDING_MULT);
4034 }
4035 }
4036 break;
4037 case GGML_OP_FLASH_ATTN_EXT:
4038 {
4039 const ggml_tensor * Q = tensor->src[0];
4040 const ggml_tensor * K = tensor->src[1];
4041 const ggml_tensor * V = tensor->src[2];
4042 const ggml_tensor * mask = tensor->src[3];
4043 const auto & capabilities = ctx->webgpu_global_ctx->capabilities;
4044 // the vec path scratch grows with the query rows, so a longer batch reserves the scratch of the
4045 // longest vec batch and the size stays monotonic in the batch length
4046 const int64_t n_q = std::min<int64_t>(Q->ne[1], GGML_WEBGPU_FLASH_ATTN_VEC_MAX_SEQ_LEN - 1);
4047 if (ggml_webgpu_flash_attn_use_vec_path(ctx->webgpu_global_ctx, Q, K, V, n_q)) {
4048 const bool kv_direct =
4049 ggml_webgpu_flash_attn_k_direct(Q, K, GGML_WEBGPU_FLASH_ATTN_TILE_KV_VEC_WIDTH) ||
4050 ggml_webgpu_flash_attn_v_direct(Q, V, GGML_WEBGPU_FLASH_ATTN_TILE_KV_VEC_WIDTH);
4051 const uint32_t kv_tile = ggml_webgpu_flash_attn_get_vec_kv_tile(
4052 capabilities.limits.maxComputeWorkgroupStorageSize, (uint32_t) Q->ne[0], (uint32_t) V->ne[0],
4053 mask != nullptr, kv_direct);
4054
4055 const uint32_t vec_nwg_cap = capabilities.min_subgroup_size;
4056 uint32_t nwg = ggml_webgpu_flash_attn_vec_nwg(vec_nwg_cap, kv_tile, (uint32_t) K->ne[1]);
4057
4058 const size_t align = capabilities.limits.minStorageBufferOffsetAlignment;
4059 const uint64_t nrows = (uint64_t) n_q * Q->ne[2] * Q->ne[3];
4060 if (nwg > 1u) {
4061 const uint64_t tmp_data_elems = nrows * (uint64_t) V->ne[0] * nwg;
4062 const uint64_t tmp_stats_elems = nrows * 2u * nwg;
4063 const size_t tmp_size_bytes = ROUNDUP_POW2((tmp_data_elems + tmp_stats_elems) * sizeof(float),
4064 WEBGPU_STORAGE_BUF_BINDING_MULT);
4065 res += tmp_size_bytes + align;
4066 } else {
4067 res += WEBGPU_STORAGE_BUF_BINDING_MULT + align;
4068 }
4069 if (mask != nullptr) {
4070 const uint32_t blk_nblk0 = CEIL_DIV((uint32_t) K->ne[1], kv_tile);
4071 const uint32_t blk_nblk1 = (uint32_t) n_q;
4072 const uint32_t stride_mask3 = (uint32_t) (mask->nb[3] / ggml_type_size(mask->type));
4073 const uint32_t blk_batch_count = stride_mask3 > 0 ? (uint32_t) Q->ne[3] : 1u;
4074 const uint64_t blk_elems = (uint64_t) blk_nblk0 * blk_nblk1 * blk_batch_count;
4075 const size_t blk_size_bytes =
4076 ROUNDUP_POW2(blk_elems * sizeof(uint32_t), WEBGPU_STORAGE_BUF_BINDING_MULT);
4077 res += blk_size_bytes + align;
4078 }
4079 res = ROUNDUP_POW2(res, WEBGPU_STORAGE_BUF_BINDING_MULT);
4080 }
4081 }
4082 break;
4083 case GGML_OP_MUL_MAT:
4084 {
4085 const ggml_tensor * src0 = tensor->src[0];
4086 const ggml_tensor * src1 = tensor->src[1];
4087
4088 // the q8 copy of src1 grows with its rows, so a longer batch reserves the copy of the longest
4089 // mmvq batch and the size stays monotonic in the batch length
4090 const int64_t n_rows = std::min<int64_t>(src1->ne[1], GGML_WEBGPU_MUL_MAT_VEC_MAX_ROWS);
4091 const bool use_mmvq = ggml_webgpu_can_use_mmvq(
4092 src0, src1, n_rows, ctx->webgpu_global_ctx->capabilities.supports_dot_product,
4093 ctx->webgpu_global_ctx->vendor);
4094 if (use_mmvq) {
4095 const size_t q8_src1_size = src1->ne[3] * src1->ne[2] * n_rows *
4096 (36 /* sizeof(q8_1) */ * (src1->ne[0] / /* block_size */ 32));
4097 res = ROUNDUP_POW2(res + q8_src1_size +
4098 ctx->webgpu_global_ctx->capabilities.limits.minStorageBufferOffsetAlignment,
4099 WEBGPU_STORAGE_BUF_BINDING_MULT);
4100 }
4101 }
4102 break;
4103 case GGML_OP_MUL_MAT_ID:
4104 {
4105 const ggml_tensor * src0 = tensor->src[0];
4106 const ggml_tensor * src1 = tensor->src[1];
4107 if (src0 && src1) {
4108 const size_t ids_cache_size = sizeof(uint32_t) * tensor->ne[1] * tensor->ne[2];
4109 const size_t ids_tiles_size = ggml_webgpu_mul_mat_id_tiles_nbytes(tensor);
4110 res = ROUNDUP_POW2(
4111 res + ids_cache_size + ids_tiles_size +
4112 ctx->webgpu_global_ctx->capabilities.limits.minStorageBufferOffsetAlignment * 2,
4113 WEBGPU_STORAGE_BUF_BINDING_MULT);
4114 }
4115 }
4116 break;
4117 default:
4118 break;
4119 }
4120 return res;
4121}
4122
4123/* End GGML Backend Buffer Type Interface */
4124
4125/* GGML Backend Device Interface */
4126
4127static const char * ggml_backend_webgpu_device_get_name(ggml_backend_dev_t dev) {
4128 ggml_backend_webgpu_device_context * ctx = static_cast<ggml_backend_webgpu_device_context *>(dev->context);
4129 return ctx->device_name.c_str();
4130}
4131
4132static const char * ggml_backend_webgpu_device_get_description(ggml_backend_dev_t dev) {
4133 ggml_backend_webgpu_device_context * ctx = static_cast<ggml_backend_webgpu_device_context *>(dev->context);
4134 return ctx->device_desc.c_str();
4135}
4136
4137static void ggml_backend_webgpu_device_get_memory(ggml_backend_dev_t dev, size_t * free, size_t * total) {
4138 ggml_backend_webgpu_device_context * ctx = static_cast<ggml_backend_webgpu_device_context *>(dev->context);
4139 // TODO: for now, return maxBufferSize as both free and total memory
4140 // Track https://github.com/gpuweb/gpuweb/issues/5505 for updates.
4141 uint64_t max_buffer_size = ctx->webgpu_global_ctx->capabilities.limits.maxBufferSize;
4142 // If we're on a 32-bit system, clamp to UINTPTR_MAX
4143#if UINTPTR_MAX < UINT64_MAX
4144 uint64_t max_ptr_size = static_cast<uint64_t>(UINTPTR_MAX);
4145 if (max_buffer_size > max_ptr_size) {
4146 max_buffer_size = max_ptr_size;
4147 }
4148#endif
4149 *free = static_cast<size_t>(max_buffer_size);
4150 *total = static_cast<size_t>(max_buffer_size);
4151}
4152
4153static enum ggml_backend_dev_type ggml_backend_webgpu_device_get_type(ggml_backend_dev_t dev) {
4154 GGML_UNUSED(dev);
4155 return GGML_BACKEND_DEVICE_TYPE_GPU;
4156}
4157
4158static void ggml_backend_webgpu_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) {
4159 props->name = ggml_backend_webgpu_device_get_name(dev);
4160 props->description = ggml_backend_webgpu_device_get_description(dev);
4161 props->type = ggml_backend_webgpu_device_get_type(dev);
4162 ggml_backend_webgpu_device_get_memory(dev, &props->memory_free, &props->memory_total);
4163 props->caps = {
4164 /* .async = */ false,
4165 /* .host_buffer = */ false,
4166 /* .buffer_from_host_ptr = */ false,
4167 /* .events = */ false,
4168 /* .mmap_support = */ true,
4169 };
4170}
4171
4172static ggml_guid_t ggml_backend_webgpu_guid(void) {
4173 static ggml_guid guid = { 0x67, 0xc7, 0xa4, 0xb1, 0x78, 0x74, 0x4f, 0x51,
4174 0x9d, 0x65, 0x44, 0x6d, 0xe4, 0x1b, 0x82, 0x9a };
4175 return &guid;
4176}
4177
4178static void ggml_webgpu_init_memset_pipeline(webgpu_global_context & ctx) {
4179 // we use the maximum workgroup size for the memset pipeline
4180 size_t max_threads = ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup *
4181 ctx->capabilities.limits.maxComputeWorkgroupsPerDimension;
4182 // Size the bytes_per_thread so that the largest buffer size can be handled
4183 ctx->capabilities.memset_bytes_per_thread =
4184 CEIL_DIV(ctx->capabilities.limits.maxStorageBufferBindingSize, max_threads);
4185 std::vector<wgpu::ConstantEntry> constants(2);
4186 constants[0].key = "wg_size";
4187 constants[0].value = ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
4188 constants[1].key = "bytes_per_thread";
4189 constants[1].value = ctx->capabilities.memset_bytes_per_thread;
4190 ctx->memset_pipeline = ggml_webgpu_create_pipeline(ctx->device, wgsl_memset, "memset", constants);
4191}
4192
4193static void ggml_backend_webgpu_request_adapter(wgpu::Instance & instance, wgpu::Adapter & adapter) {
4194 wgpu::RequestAdapterOptions options = {};
4195
4196#if !defined(__EMSCRIPTEN__) && !defined(__wasi__)
4197 // TODO: track need for these toggles: https://issues.chromium.org/issues/42251215
4198 const char * const adapterEnabledToggles[] = { "vulkan_enable_f16_on_nvidia", "use_vulkan_memory_model" };
4199 wgpu::DawnTogglesDescriptor adapterTogglesDesc;
4200 adapterTogglesDesc.enabledToggles = adapterEnabledToggles;
4201 adapterTogglesDesc.enabledToggleCount = 2;
4202 options.nextInChain = &adapterTogglesDesc;
4203#endif
4204
4205 instance.WaitAny(
4206 instance.RequestAdapter(
4207 &options, wgpu::CallbackMode::AllowSpontaneous,
4208 [&adapter](wgpu::RequestAdapterStatus status, wgpu::Adapter _adapter, wgpu::StringView message) {
4209 if (status != wgpu::RequestAdapterStatus::Success) {
4210 GGML_LOG_ERROR("ggml_webgpu: Failed to get an adapter: %s\n", std::string(message).c_str());
4211 return;
4212 }
4213 adapter = std::move(_adapter);
4214 }),
4215 UINT64_MAX);
4216}
4217
4218static void create_webgpu_device(ggml_backend_webgpu_reg_context * ctx) {
4219 ggml_backend_webgpu_request_adapter(ctx->webgpu_global_ctx->instance, ctx->webgpu_global_ctx->adapter);
4220 GGML_ASSERT(ctx->webgpu_global_ctx->adapter != nullptr);
4221
4222 ctx->webgpu_global_ctx->adapter.GetLimits(&ctx->webgpu_global_ctx->capabilities.limits);
4223
4224 wgpu::AdapterInfo info{};
4225#if !defined(__EMSCRIPTEN__) && !defined(__wasi__)
4226 wgpu::AdapterPropertiesSubgroupMatrixConfigs subgroup_matrix_configs{};
4227 if (ctx->webgpu_global_ctx->adapter.HasFeature(wgpu::FeatureName::ChromiumExperimentalSubgroupMatrix)) {
4228 info.nextInChain = &subgroup_matrix_configs;
4229 }
4230#endif
4231 ctx->webgpu_global_ctx->adapter.GetInfo(&info);
4232 ctx->webgpu_global_ctx->command_submit_batch_size = ggml_backend_webgpu_get_command_submit_batch_size();
4233 ctx->webgpu_global_ctx->max_inflight_batches = ggml_backend_webgpu_get_max_inflight_batches();
4234 ctx->webgpu_global_ctx->vendor = info.vendor;
4235 ctx->webgpu_global_ctx->capabilities.supports_subgroups =
4236 ctx->webgpu_global_ctx->adapter.HasFeature(wgpu::FeatureName::Subgroups);
4237 // for dot4I8packed
4238 ctx->webgpu_global_ctx->capabilities.supports_dot_product = ctx->webgpu_global_ctx->instance.HasWGSLLanguageFeature(
4239 wgpu::WGSLLanguageFeatureName::Packed4x8IntegerDotProduct);
4240
4241 bool valid_subgroup_matrix_config = false;
4242#if !defined(__EMSCRIPTEN__) && !defined(__wasi__)
4243 // Accept f16 subgroup matrix configurations (square or non-square).
4244 // NVIDIA GPUs typically report square configs (e.g. 16x16x16),
4245 // while Intel Xe2 GPUs report non-square configs (e.g. 8x16x16).
4246 // The shaders are already parameterized to handle any M/N/K dimensions.
4247 if (ctx->webgpu_global_ctx->adapter.HasFeature(wgpu::FeatureName::ChromiumExperimentalSubgroupMatrix)) {
4248 for (size_t i = 0; i < subgroup_matrix_configs.configCount; i++) {
4249 const wgpu::SubgroupMatrixConfig config = subgroup_matrix_configs.configs[i];
4250 if (config.componentType == wgpu::SubgroupMatrixComponentType::F16 &&
4251 config.resultComponentType == wgpu::SubgroupMatrixComponentType::F16) {
4252 ctx->webgpu_global_ctx->capabilities.sg_mat_m = config.M;
4253 ctx->webgpu_global_ctx->capabilities.sg_mat_n = config.N;
4254 ctx->webgpu_global_ctx->capabilities.sg_mat_k = config.K;
4255 valid_subgroup_matrix_config = true;
4256 break;
4257 }
4258 }
4259 }
4260#endif
4261 ctx->webgpu_global_ctx->capabilities.supports_subgroup_matrix = valid_subgroup_matrix_config;
4262
4263 // Runtime subgroup size can be any supported size in this range. Shaders
4264 // that allocate per-lane register arrays must size them for the minimum.
4265 ctx->webgpu_global_ctx->capabilities.min_subgroup_size = info.subgroupMinSize;
4266 ctx->webgpu_global_ctx->capabilities.max_subgroup_size = info.subgroupMaxSize;
4267 // Initialize device
4268 std::vector<wgpu::FeatureName> required_features = { wgpu::FeatureName::ShaderF16 };
4269
4270#if !defined(__EMSCRIPTEN__) && !defined(__wasi__)
4271 required_features.push_back(wgpu::FeatureName::ImplicitDeviceSynchronization);
4272 if (ctx->webgpu_global_ctx->capabilities.supports_subgroup_matrix) {
4273 required_features.push_back(wgpu::FeatureName::ChromiumExperimentalSubgroupMatrix);
4274 }
4275#endif
4276
4277 if (ctx->webgpu_global_ctx->capabilities.supports_subgroups) {
4278 required_features.push_back(wgpu::FeatureName::Subgroups);
4279 }
4280
4281#ifdef GGML_WEBGPU_GPU_PROFILE
4282 required_features.push_back(wgpu::FeatureName::TimestampQuery);
4283#endif
4284
4285 wgpu::DeviceDescriptor dev_desc;
4286 dev_desc.requiredLimits = &ctx->webgpu_global_ctx->capabilities.limits;
4287 dev_desc.requiredFeatures = required_features.data();
4288 dev_desc.requiredFeatureCount = required_features.size();
4289 dev_desc.SetDeviceLostCallback(
4290 wgpu::CallbackMode::AllowSpontaneous,
4291 [](const wgpu::Device & device, wgpu::DeviceLostReason reason, wgpu::StringView message) {
4292 if (reason == wgpu::DeviceLostReason::Destroyed) {
4293 return;
4294 }
4295 GGML_UNUSED(device);
4296 GGML_LOG_ERROR("ggml_webgpu: Device lost! Reason: %d, Message: %s\n", static_cast<int>(reason),
4297 std::string(message).c_str());
4298 });
4299 dev_desc.SetUncapturedErrorCallback(
4300 [](const wgpu::Device & device, wgpu::ErrorType reason, wgpu::StringView message) {
4301 GGML_UNUSED(device);
4302 GGML_ABORT("ggml_webgpu: Device error! Reason: %d, Message: %s\n", static_cast<int>(reason),
4303 std::string(message).c_str());
4304 });
4305
4306#if !defined(__EMSCRIPTEN__) && !defined(__wasi__)
4307 // Enable Dawn-specific toggles to increase native performance
4308 // TODO: Maybe WebGPU needs a "fast" mode where you can request compilers skip adding checks like these,
4309 // only for native performance?
4310 const char * const deviceEnabledToggles[] = { "disable_robustness", "disable_workgroup_init",
4311 "disable_polyfills_on_integer_div_and_mod" };
4312 const char * const deviceDisabledToggles[] = { "timestamp_quantization" };
4313 wgpu::DawnTogglesDescriptor deviceTogglesDesc;
4314 deviceTogglesDesc.enabledToggles = deviceEnabledToggles;
4315 deviceTogglesDesc.enabledToggleCount = 3;
4316 deviceTogglesDesc.disabledToggles = deviceDisabledToggles;
4317 deviceTogglesDesc.disabledToggleCount = 1;
4318
4319 dev_desc.nextInChain = &deviceTogglesDesc;
4320#endif
4321
4322 ctx->webgpu_global_ctx->instance.WaitAny(
4323 ctx->webgpu_global_ctx->adapter.RequestDevice(
4324 &dev_desc, wgpu::CallbackMode::AllowSpontaneous,
4325 [ctx](wgpu::RequestDeviceStatus status, wgpu::Device device, wgpu::StringView message) {
4326 if (status != wgpu::RequestDeviceStatus::Success) {
4327 GGML_LOG_ERROR("ggml_webgpu: Failed to get a device: %s\n", std::string(message).c_str());
4328 return;
4329 }
4330 ctx->webgpu_global_ctx->device = std::move(device);
4331 }),
4332 UINT64_MAX);
4333 GGML_ASSERT(ctx->webgpu_global_ctx->device != nullptr);
4334
4335 ggml_webgpu_init_memset_pipeline(ctx->webgpu_global_ctx);
4336 ggml_webgpu_create_buffer(ctx->webgpu_global_ctx->device, ctx->webgpu_global_ctx->memset_params_buf,
4337 WEBGPU_PARAMS_BUF_SIZE_BYTES, wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::Uniform,
4338 "memset_params_buf");
4339 ctx->webgpu_global_ctx->queue = ctx->webgpu_global_ctx->device.GetQueue();
4340
4341 GGML_LOG_INFO(
4342 "ggml_webgpu: adapter_info: vendor_id: %u | vendor: %s | architecture: %s | device_id: %u | name: %s | "
4343 "device_desc: %s\n",
4344 info.vendorID, std::string(info.vendor).c_str(), std::string(info.architecture).c_str(), info.deviceID,
4345 std::string(info.device).c_str(), std::string(info.description).c_str());
4346}
4347
4348static webgpu_context initialize_webgpu_context(ggml_backend_dev_t dev) {
4349 ggml_backend_webgpu_device_context * dev_ctx = (ggml_backend_webgpu_device_context *) dev->context;
4350 webgpu_context webgpu_ctx = std::make_shared<webgpu_context_struct>();
4351 webgpu_ctx->global_ctx = dev_ctx->webgpu_global_ctx;
4352 webgpu_ctx->shader_lib = std::make_unique<ggml_webgpu_shader_lib>(dev_ctx->webgpu_global_ctx->device);
4353 webgpu_ctx->param_arena.init(
4354 webgpu_ctx->global_ctx->device, WEBGPU_PARAMS_BUF_SIZE_BYTES,
4355 webgpu_ctx->global_ctx->command_submit_batch_size + WEBGPU_NUM_PARAM_SLOT_SAFETY_MARGIN,
4356 webgpu_ctx->global_ctx->capabilities.limits.minUniformBufferOffsetAlignment);
4357 ggml_webgpu_create_buffer(webgpu_ctx->global_ctx->device, webgpu_ctx->set_rows_dev_error_buf,
4358 WEBGPU_SET_ROWS_ERROR_BUF_SIZE_BYTES,
4359 wgpu::BufferUsage::Storage | wgpu::BufferUsage::CopySrc, "set_rows_dev_error_buf");
4360 ggml_webgpu_create_buffer(webgpu_ctx->global_ctx->device, webgpu_ctx->set_rows_host_error_buf,
4361 WEBGPU_SET_ROWS_ERROR_BUF_SIZE_BYTES,
4362 wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::MapRead, "set_rows_host_error_buf");
4363
4364#ifdef GGML_WEBGPU_GPU_PROFILE
4365 webgpu_ctx->batch_compute_passes = false;
4366 ggml_webgpu_create_buffer(
4367 webgpu_ctx->global_ctx->device, webgpu_ctx->profile_timestamp_dev_buf, WEBGPU_TIMESTAMP_QUERY_BUF_SIZE_BYTES,
4368 wgpu::BufferUsage::QueryResolve | wgpu::BufferUsage::CopySrc, "profile_timestamp_dev_buf");
4369 ggml_webgpu_create_buffer(webgpu_ctx->global_ctx->device, webgpu_ctx->profile_timestamp_host_buf,
4370 WEBGPU_TIMESTAMP_QUERY_BUF_SIZE_BYTES,
4371 wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::MapRead, "profile_timestamp_host_buf");
4372 wgpu::QuerySetDescriptor query_set_desc = {};
4373 query_set_desc.type = wgpu::QueryType::Timestamp;
4374 query_set_desc.count = WEBGPU_MAX_PROFILE_QUERY_COUNT;
4375 webgpu_ctx->profile_timestamp_query_set = webgpu_ctx->global_ctx->device.CreateQuerySet(&query_set_desc);
4376#endif
4377
4378#ifdef GGML_WEBGPU_DEBUG
4379 // Initialize debug buffers
4380 ggml_webgpu_create_buffer(webgpu_ctx->global_ctx->device, webgpu_ctx->global_ctx->debug_host_buf,
4381 WEBGPU_DEBUG_BUF_ELEMS * sizeof(uint32_t),
4382 wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::MapRead, "debug_host_buf");
4383 ggml_webgpu_create_buffer(webgpu_ctx->global_ctx->device, webgpu_ctx->global_ctx->debug_dev_buf,
4384 WEBGPU_DEBUG_BUF_ELEMS * sizeof(uint32_t),
4385 wgpu::BufferUsage::Storage | wgpu::BufferUsage::CopySrc, "debug_dev_buf");
4386#endif
4387 return webgpu_ctx;
4388}
4389
4390static ggml_backend_t ggml_backend_webgpu_backend_init(ggml_backend_dev_t dev, const char * params) {
4391 GGML_UNUSED(params);
4392
4393 WEBGPU_LOG_DEBUG("ggml_backend_webgpu_backend_init()");
4394
4395 ggml_backend_webgpu_device_context * dev_ctx = static_cast<ggml_backend_webgpu_device_context *>(dev->context);
4396
4397 auto * backend_ctx = new ggml_backend_webgpu_context();
4398 backend_ctx->name = GGML_WEBGPU_NAME + std::string(": ") + dev_ctx->device_name;
4399 backend_ctx->webgpu_ctx = initialize_webgpu_context(dev);
4400
4401 // See GGML Backend Interface section
4402 auto * backend = new ggml_backend();
4403 *backend = {
4404 /* .guid = */ ggml_backend_webgpu_guid(),
4405 /* .interface = */ ggml_backend_webgpu_i,
4406 /* .device = */ dev,
4407 /* .context = */ backend_ctx,
4408 };
4409 return backend;
4410}
4411
4412static ggml_backend_buffer_type_t ggml_backend_webgpu_device_get_buffer_type(ggml_backend_dev_t dev) {
4413 // See GGML Backend Buffer Type Interface section
4414
4415 static struct ggml_backend_buffer_type ggml_backend_webgpu_buffer_type = {
4416 /* .iface = */ {
4417 /* .get_name = */ ggml_backend_webgpu_buffer_type_get_name,
4418 /* .alloc_buffer = */ ggml_backend_webgpu_buffer_type_alloc_buffer,
4419 /* .alloc_buffer_n = */ NULL,
4420 /* .get_alignment = */ ggml_backend_webgpu_buffer_type_get_alignment,
4421 /* .get_max_size = */ ggml_backend_webgpu_buffer_type_get_max_size,
4422 /* .get_alloc_size = */ ggml_backend_webgpu_buffer_type_get_alloc_size,
4423 /* .get_alloc_size_n = */ NULL,
4424 /* .is_host = */ NULL, // defaults to false
4425 },
4426 /* .device = */
4427 dev,
4428 /* .context = */ NULL
4429 };
4430
4431 return &ggml_backend_webgpu_buffer_type;
4432}
4433
4434static bool ggml_backend_webgpu_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
4435 GGML_UNUSED(dev);
4436 return buft->iface.get_name == ggml_backend_webgpu_buffer_type_get_name;
4437}
4438
4439static bool ggml_webgpu_supported_qtype(ggml_type type) {
4440 switch (type) {
4441 case GGML_TYPE_Q1_0:
4442 case GGML_TYPE_Q2_0:
4443 case GGML_TYPE_Q4_0:
4444 case GGML_TYPE_Q4_1:
4445 case GGML_TYPE_Q5_0:
4446 case GGML_TYPE_Q5_1:
4447 case GGML_TYPE_Q8_0:
4448 case GGML_TYPE_Q2_K:
4449 case GGML_TYPE_Q3_K:
4450 case GGML_TYPE_Q4_K:
4451 case GGML_TYPE_Q5_K:
4452 case GGML_TYPE_Q6_K:
4453 case GGML_TYPE_IQ2_XXS:
4454 case GGML_TYPE_IQ2_XS:
4455 case GGML_TYPE_IQ2_S:
4456 case GGML_TYPE_IQ3_XXS:
4457 case GGML_TYPE_IQ3_S:
4458 case GGML_TYPE_IQ1_S:
4459 case GGML_TYPE_IQ1_M:
4460 case GGML_TYPE_IQ4_NL:
4461 case GGML_TYPE_IQ4_XS:
4462 case GGML_TYPE_MXFP4:
4463 case GGML_TYPE_NVFP4:
4464 return true;
4465 default:
4466 return false;
4467 }
4468}
4469
4470static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
4471 ggml_backend_webgpu_device_context * ctx = static_cast<ggml_backend_webgpu_device_context *>(dev->context);
4472
4473 ggml_tensor * src0 = op->src[0];
4474 ggml_tensor * src1 = op->src[1];
4475 ggml_tensor * src2 = op->src[2];
4476
4477 // on smaller devices (or CI), tensors may be larger than the max storage buffer size
4478 if (ggml_nbytes(op) > ctx->webgpu_global_ctx->capabilities.limits.maxStorageBufferBindingSize ||
4479 (src0 != nullptr &&
4480 ggml_nbytes(src0) > ctx->webgpu_global_ctx->capabilities.limits.maxStorageBufferBindingSize) ||
4481 (src1 != nullptr &&
4482 ggml_nbytes(src1) > ctx->webgpu_global_ctx->capabilities.limits.maxStorageBufferBindingSize)) {
4483 return false;
4484 }
4485
4486 bool supports_op = false;
4487 switch (op->op) {
4488 case GGML_OP_NONE:
4489 case GGML_OP_VIEW:
4490 case GGML_OP_PERMUTE:
4491 case GGML_OP_TRANSPOSE:
4492 case GGML_OP_RESHAPE:
4493 supports_op = true;
4494 break;
4495 case GGML_OP_ADD:
4496 case GGML_OP_SUB:
4497 case GGML_OP_MUL:
4498 case GGML_OP_DIV:
4499 supports_op = (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) && (src0->type == op->type) &&
4500 (src1->type == op->type);
4501 break;
4502 case GGML_OP_ADD_ID:
4503 supports_op = src0->type == GGML_TYPE_F32;
4504 break;
4505 case GGML_OP_CONCAT:
4506 supports_op = (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_I32);
4507 break;
4508 case GGML_OP_REPEAT:
4509 supports_op = (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_I32 ||
4510 src0->type == GGML_TYPE_I16);
4511 break;
4512 case GGML_OP_DUP:
4513 case GGML_OP_CPY:
4514 case GGML_OP_CONT:
4515 supports_op = (op->type == GGML_TYPE_F16 || op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_I32) &&
4516 (src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_I32);
4517 break;
4518 case GGML_OP_SET:
4519 supports_op = src0->type == src1->type && src0->type == op->type &&
4520 (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_I32);
4521 break;
4522 case GGML_OP_SET_ROWS:
4523 supports_op = ((op->type == GGML_TYPE_F16 || op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_Q8_0 ||
4524 op->type == GGML_TYPE_Q4_0) &&
4525 (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16) &&
4526 (src1->type == GGML_TYPE_I64 || src1->type == GGML_TYPE_I32));
4527 break;
4528 case GGML_OP_GET_ROWS:
4529 if (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 ||
4530 ggml_webgpu_supported_qtype(src0->type)) {
4531 supports_op = (op->type == GGML_TYPE_F32);
4532 } else if (src0->type == GGML_TYPE_I32) {
4533 supports_op = op->type == GGML_TYPE_I32;
4534 }
4535 break;
4536 case GGML_OP_MUL_MAT:
4537 {
4538 switch (src1->type) {
4539 case GGML_TYPE_F16:
4540 supports_op |= (src0->type == GGML_TYPE_F16);
4541 break;
4542 case GGML_TYPE_F32:
4543 switch (src0->type) {
4544 case GGML_TYPE_F32:
4545 case GGML_TYPE_F16:
4546 case GGML_TYPE_BF16:
4547 case GGML_TYPE_Q1_0:
4548 case GGML_TYPE_Q2_0:
4549 case GGML_TYPE_Q4_0:
4550 case GGML_TYPE_Q4_1:
4551 case GGML_TYPE_Q5_0:
4552 case GGML_TYPE_Q5_1:
4553 case GGML_TYPE_Q8_0:
4554 case GGML_TYPE_Q2_K:
4555 case GGML_TYPE_Q3_K:
4556 case GGML_TYPE_Q4_K:
4557 case GGML_TYPE_Q5_K:
4558 case GGML_TYPE_Q6_K:
4559 case GGML_TYPE_IQ2_XXS:
4560 case GGML_TYPE_IQ2_XS:
4561 case GGML_TYPE_IQ2_S:
4562 case GGML_TYPE_IQ3_XXS:
4563 case GGML_TYPE_IQ3_S:
4564 case GGML_TYPE_IQ1_S:
4565 case GGML_TYPE_IQ1_M:
4566 case GGML_TYPE_IQ4_NL:
4567 case GGML_TYPE_IQ4_XS:
4568 case GGML_TYPE_MXFP4:
4569 case GGML_TYPE_NVFP4:
4570 supports_op = true;
4571 break;
4572 default:
4573 break;
4574 }
4575 default:
4576 break;
4577 }
4578 break;
4579 }
4580 case GGML_OP_MUL_MAT_ID:
4581 switch (src1->type) {
4582 case GGML_TYPE_F16:
4583 supports_op |= (src0->type == GGML_TYPE_F16);
4584 break;
4585 case GGML_TYPE_F32:
4586 switch (src0->type) {
4587 case GGML_TYPE_F32:
4588 case GGML_TYPE_F16:
4589 case GGML_TYPE_BF16:
4590 case GGML_TYPE_Q1_0:
4591 case GGML_TYPE_Q4_0:
4592 case GGML_TYPE_Q4_1:
4593 case GGML_TYPE_Q5_0:
4594 case GGML_TYPE_Q5_1:
4595 case GGML_TYPE_Q8_0:
4596 case GGML_TYPE_Q2_K:
4597 case GGML_TYPE_Q3_K:
4598 case GGML_TYPE_Q4_K:
4599 case GGML_TYPE_Q5_K:
4600 case GGML_TYPE_Q6_K:
4601 case GGML_TYPE_IQ1_S:
4602 case GGML_TYPE_IQ1_M:
4603 case GGML_TYPE_IQ2_XXS:
4604 case GGML_TYPE_IQ2_XS:
4605 case GGML_TYPE_IQ2_S:
4606 case GGML_TYPE_IQ3_XXS:
4607 case GGML_TYPE_IQ3_S:
4608 case GGML_TYPE_IQ4_NL:
4609 case GGML_TYPE_IQ4_XS:
4610 case GGML_TYPE_MXFP4:
4611 case GGML_TYPE_NVFP4:
4612 supports_op = true;
4613 break;
4614 default:
4615 break;
4616 }
4617 break;
4618 default:
4619 break;
4620 }
4621 if (ggml_get_op_params_i32(op, 3) == GGML_PREC_F32) {
4622 supports_op = false;
4623 }
4624 break;
4625 case GGML_OP_FLASH_ATTN_EXT:
4626 {
4627 // conservative support checks for whether the more resource-intensive shader paths
4628 // can be used, to avoid cases where flash_attn is assigned to the CPU later on
4629 // K/V row lists (ggml_flash_attn_ext_rows) are not supported
4630 supports_op = op->src[5] == nullptr && src0->type == GGML_TYPE_F32 &&
4631 (src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16 ||
4632 src1->type == GGML_TYPE_Q4_0 || src1->type == GGML_TYPE_Q8_0) &&
4633 (src2->type == GGML_TYPE_F32 || src2->type == GGML_TYPE_F16 ||
4634 src2->type == GGML_TYPE_Q4_0 || src2->type == GGML_TYPE_Q8_0) &&
4635 op->type == GGML_TYPE_F32;
4636 if (!supports_op) {
4637 break;
4638 }
4639 if (ggml_webgpu_tensor_binding_overlap(ctx->webgpu_global_ctx, src1, src2) &&
4640 src1->type != src2->type && !(ggml_is_quantized(src1->type) && ggml_is_quantized(src2->type))) {
4641 supports_op = false;
4642 break;
4643 }
4644 const auto & capabilities = ctx->webgpu_global_ctx->capabilities;
4645 const size_t storage_offset_alignment = capabilities.limits.minStorageBufferOffsetAlignment;
4646
4647 // subgroup matrix path requirements
4648 const bool use_subgroup_matrix = ggml_webgpu_flash_attn_can_use_subgroup_matrix_path(
4649 capabilities.supports_subgroup_matrix, capabilities.sg_mat_k, capabilities.sg_mat_n, src0, src2);
4650
4651 // tile path requirements
4652 const bool float_vec4_aligned =
4653 ((src1->type != GGML_TYPE_F16 && src1->type != GGML_TYPE_F32) ||
4654 ggml_webgpu_flash_attn_float_vec4_aligned(src1, storage_offset_alignment)) &&
4655 ((src2->type != GGML_TYPE_F16 && src2->type != GGML_TYPE_F32) ||
4656 ggml_webgpu_flash_attn_float_vec4_aligned(src2, storage_offset_alignment));
4657 const uint32_t k_tile_head_align = (src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16) ?
4658 GGML_WEBGPU_FLASH_ATTN_TILE_KV_VEC_WIDTH :
4659 (uint32_t) ggml_blck_size(src1->type);
4660 const uint32_t v_tile_head_align = (src2->type == GGML_TYPE_F32 || src2->type == GGML_TYPE_F16) ?
4661 GGML_WEBGPU_FLASH_ATTN_TILE_KV_VEC_WIDTH :
4662 (uint32_t) ggml_blck_size(src2->type);
4663 const bool tile_kv_head_dims_aligned =
4664 src0->ne[0] % k_tile_head_align == 0 && src2->ne[0] % v_tile_head_align == 0;
4665 const bool tile_can_dispatch_all_q_rows =
4666 capabilities.limits.maxComputeInvocationsPerWorkgroup >=
4667 GGML_WEBGPU_FLASH_ATTN_TILE_Q_TILE * capabilities.max_subgroup_size;
4668 const bool use_tile = !use_subgroup_matrix && capabilities.supports_subgroups && float_vec4_aligned &&
4669 tile_kv_head_dims_aligned && tile_can_dispatch_all_q_rows;
4670
4671 if (!use_subgroup_matrix && !use_tile) {
4672 supports_op = false;
4673 break;
4674 }
4675 const uint32_t q_tile =
4676 use_subgroup_matrix ? capabilities.sg_mat_m : GGML_WEBGPU_FLASH_ATTN_TILE_Q_TILE;
4677 const uint32_t kv_granularity = use_subgroup_matrix ? capabilities.sg_mat_n : 1u;
4678 const bool kv_direct = use_subgroup_matrix ?
4679 ggml_webgpu_flash_attn_k_direct(src0, src1, capabilities.sg_mat_k) ||
4680 ggml_webgpu_flash_attn_v_direct(src0, src2, capabilities.sg_mat_k) :
4681 false;
4682 const uint32_t max_kv_tile = ggml_webgpu_flash_attn_max_kv_tile(
4683 capabilities.limits.maxComputeWorkgroupStorageSize, q_tile, kv_granularity, (uint32_t) src0->ne[0],
4684 (uint32_t) src2->ne[0], op->src[3] != nullptr, kv_direct);
4685 supports_op = max_kv_tile > 0;
4686 break;
4687 }
4688 case GGML_OP_RMS_NORM:
4689 case GGML_OP_NORM:
4690 case GGML_OP_L2_NORM:
4691 supports_op = (op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32) && ggml_is_contiguous_rows(src0);
4692 break;
4693 case GGML_OP_ROPE:
4694 supports_op = op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16;
4695 break;
4696 case GGML_OP_GLU:
4697 switch (ggml_get_glu_op(op)) {
4698 case GGML_GLU_OP_REGLU:
4699 case GGML_GLU_OP_GEGLU:
4700 case GGML_GLU_OP_SWIGLU:
4701 case GGML_GLU_OP_GEGLU_ERF:
4702 case GGML_GLU_OP_GEGLU_QUICK:
4703 case GGML_GLU_OP_SWIGLU_CLAMP:
4704 supports_op = op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16;
4705 break;
4706 case GGML_GLU_OP_SWIGLU_OAI:
4707 supports_op = op->type == GGML_TYPE_F32;
4708 break;
4709 default:
4710 break;
4711 }
4712 break;
4713 case GGML_OP_SCALE:
4714 supports_op = op->type == GGML_TYPE_F32;
4715 break;
4716 case GGML_OP_SOFT_MAX:
4717 supports_op = op->type == GGML_TYPE_F32;
4718 break;
4719 case GGML_OP_UNARY:
4720 {
4721 const ggml_unary_op UNARY_OP = ggml_get_unary_op(op);
4722
4723 switch (UNARY_OP) {
4724 case GGML_UNARY_OP_ABS:
4725 case GGML_UNARY_OP_SGN:
4726 case GGML_UNARY_OP_NEG:
4727 case GGML_UNARY_OP_STEP:
4728 case GGML_UNARY_OP_TANH:
4729 case GGML_UNARY_OP_ELU:
4730 case GGML_UNARY_OP_RELU:
4731 case GGML_UNARY_OP_SIGMOID:
4732 case GGML_UNARY_OP_GELU:
4733 case GGML_UNARY_OP_GELU_QUICK:
4734 case GGML_UNARY_OP_SILU:
4735 case GGML_UNARY_OP_HARDSWISH:
4736 case GGML_UNARY_OP_HARDSIGMOID:
4737 case GGML_UNARY_OP_EXP:
4738 case GGML_UNARY_OP_GELU_ERF:
4739 case GGML_UNARY_OP_SOFTPLUS:
4740 case GGML_UNARY_OP_EXPM1:
4741 case GGML_UNARY_OP_FLOOR:
4742 case GGML_UNARY_OP_CEIL:
4743 case GGML_UNARY_OP_ROUND:
4744 case GGML_UNARY_OP_TRUNC:
4745 case GGML_UNARY_OP_XIELU:
4746 supports_op =
4747 (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) && (src0->type == op->type);
4748 break;
4749 default:
4750 break;
4751 }
4752 }
4753 break;
4754 case GGML_OP_TRI:
4755 supports_op = op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32;
4756 break;
4757 case GGML_OP_DIAG:
4758 supports_op = op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32;
4759 break;
4760 case GGML_OP_SOLVE_TRI:
4761 supports_op = op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32;
4762 break;
4763 case GGML_OP_CONV_2D:
4764 supports_op = (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
4765 (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16) &&
4766 (src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16);
4767 break;
4768 case GGML_OP_CONV_2D_DW:
4769 supports_op = (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
4770 (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16) &&
4771 (src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16) &&
4772 (ggml_is_contiguous(src1) || ggml_is_contiguous_channels(src1));
4773 break;
4774 case GGML_OP_IM2COL:
4775 supports_op = (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
4776 (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
4777 break;
4778 case GGML_OP_SSM_CONV:
4779 supports_op = op->type == GGML_TYPE_F32;
4780 break;
4781 case GGML_OP_SSM_SCAN:
4782 supports_op = op->type == GGML_TYPE_F32 &&
4783 src0->ne[0] <= ctx->webgpu_global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
4784 break;
4785 case GGML_OP_GATED_DELTA_NET:
4786 {
4787 const uint32_t s_v = (uint32_t) src2->ne[0];
4788 supports_op = op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 &&
4789 src2->type == GGML_TYPE_F32 && op->src[3]->type == GGML_TYPE_F32 &&
4790 op->src[4]->type == GGML_TYPE_F32 && op->src[5]->type == GGML_TYPE_F32 &&
4791 s_v <= ctx->webgpu_global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
4792 }
4793 break;
4794 case GGML_OP_CLAMP:
4795 supports_op = (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) && (src0->type == op->type);
4796 break;
4797 case GGML_OP_FILL:
4798 supports_op = (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) && (src0->type == op->type);
4799 break;
4800 case GGML_OP_LOG:
4801 supports_op = (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) && (src0->type == op->type);
4802 break;
4803 case GGML_OP_SQR:
4804 supports_op = (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) && (src0->type == op->type);
4805 break;
4806 case GGML_OP_SQRT:
4807 supports_op = (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) && (src0->type == op->type);
4808 break;
4809 case GGML_OP_SIN:
4810 supports_op = (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) && (src0->type == op->type);
4811 break;
4812 case GGML_OP_COS:
4813 supports_op = (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) && (src0->type == op->type);
4814 break;
4815 case GGML_OP_ARANGE:
4816 supports_op = op->type == GGML_TYPE_F32 && ggml_is_contiguous(op);
4817 break;
4818 case GGML_OP_PAD:
4819 supports_op = op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32;
4820 break;
4821 case GGML_OP_ARGMAX:
4822 supports_op = op->type == GGML_TYPE_I32 && src0->type == GGML_TYPE_F32;
4823 break;
4824 case GGML_OP_ARGSORT:
4825 supports_op = op->type == GGML_TYPE_I32 && src0->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(src0);
4826 break;
4827 case GGML_OP_TOP_K:
4828 supports_op = op->type == GGML_TYPE_I32 && src0->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(src0);
4829 break;
4830 case GGML_OP_CUMSUM:
4831 supports_op = op->type == GGML_TYPE_F32 && src0->type == op->type;
4832 break;
4833 case GGML_OP_SUM:
4834 supports_op = op->type == GGML_TYPE_F32 && src0->type == op->type && ggml_is_contiguously_allocated(src0);
4835 break;
4836 case GGML_OP_SUM_ROWS:
4837 supports_op = op->type == GGML_TYPE_F32 && src0->type == op->type && ggml_is_contiguous_rows(src0);
4838 break;
4839 case GGML_OP_UPSCALE:
4840 supports_op = (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
4841 (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
4842 break;
4843 default:
4844 break;
4845 }
4846 if (ggml_nbytes(op) > ctx->webgpu_global_ctx->capabilities.limits.maxStorageBufferBindingSize ||
4847 (src0 != nullptr &&
4848 ggml_nbytes(src0) > ctx->webgpu_global_ctx->capabilities.limits.maxStorageBufferBindingSize) ||
4849 (src1 != nullptr &&
4850 ggml_nbytes(src1) > ctx->webgpu_global_ctx->capabilities.limits.maxStorageBufferBindingSize) ||
4851 (src2 != nullptr &&
4852 ggml_nbytes(src2) > ctx->webgpu_global_ctx->capabilities.limits.maxStorageBufferBindingSize)) {
4853 supports_op = false;
4854 WEBGPU_LOG_DEBUG("ggml_webgpu op not supported due to size: ");
4855 }
4856
4857 if (!supports_op) {
4858 WEBGPU_LOG_DEBUG("ggml_webgpu op not supported: "
4859 << ggml_op_name(op->op) << " with types dst: " << ggml_type_name(op->type)
4860 << ", src0: " << (op->src[0] ? ggml_type_name(op->src[0]->type) : "null")
4861 << ", src1: " << (op->src[1] ? ggml_type_name(op->src[1]->type) : "null"));
4862 } else {
4863 WEBGPU_LOG_DEBUG("ggml_webgpu op supported: "
4864 << ggml_op_name(op->op) << " with types dst: " << ggml_type_name(op->type)
4865 << ", src0: " << (op->src[0] ? ggml_type_name(op->src[0]->type) : "null")
4866 << ", src1: " << (op->src[1] ? ggml_type_name(op->src[1]->type) : "null"));
4867 }
4868 return supports_op;
4869}
4870
4871static struct ggml_backend_device_i ggml_backend_webgpu_device_i = {
4872 /* .get_name = */ ggml_backend_webgpu_device_get_name,
4873 /* .get_description = */ ggml_backend_webgpu_device_get_description,
4874 /* .get_memory = */ ggml_backend_webgpu_device_get_memory,
4875 /* .get_type = */ ggml_backend_webgpu_device_get_type,
4876 /* .get_props = */ ggml_backend_webgpu_device_get_props,
4877 /* .init_backend = */ ggml_backend_webgpu_backend_init,
4878 /* .get_buffer_type = */ ggml_backend_webgpu_device_get_buffer_type,
4879 /* .get_host_buffer_type = */ NULL,
4880 /* .buffer_from_host_ptr = */ NULL,
4881 /* .supports_op = */ ggml_backend_webgpu_device_supports_op,
4882 /* .supports_buft = */ ggml_backend_webgpu_device_supports_buft,
4883 /* .offload_op = */ NULL,
4884 /* .event_new = */ ggml_backend_webgpu_device_event_new,
4885 /* .event_free = */ ggml_backend_webgpu_device_event_free,
4886 /* .event_synchronize = */ ggml_backend_webgpu_device_event_synchronize,
4887};
4888
4889/* End GGML Backend Device Interface */
4890
4891/* GGML Backend Registration Interface */
4892
4893static const char * ggml_backend_webgpu_reg_get_name(ggml_backend_reg_t reg) {
4894 ggml_backend_webgpu_reg_context * ctx = static_cast<ggml_backend_webgpu_reg_context *>(reg->context);
4895 return ctx->name;
4896}
4897
4898static size_t ggml_backend_webgpu_reg_get_device_count(ggml_backend_reg_t reg) {
4899 ggml_backend_webgpu_reg_context * ctx = static_cast<ggml_backend_webgpu_reg_context *>(reg->context);
4900 return ctx->device_count;
4901}
4902
4903// Only one device is supported for now
4904static ggml_backend_dev_t ggml_backend_webgpu_reg_get_device(ggml_backend_reg_t reg, size_t index) {
4905 GGML_ASSERT(index == 0);
4906 WEBGPU_LOG_DEBUG("ggml_backend_reg_get_device()");
4907
4908 WEBGPU_CPU_PROFILE_TOTAL_START(reg_get_device);
4909
4910 ggml_backend_webgpu_reg_context * reg_ctx = static_cast<ggml_backend_webgpu_reg_context *>(reg->context);
4911
4912 create_webgpu_device(reg_ctx);
4913
4914 static ggml_backend_webgpu_device_context device_ctx;
4915 device_ctx.device_name = GGML_WEBGPU_NAME;
4916 device_ctx.device_desc = GGML_WEBGPU_NAME;
4917 device_ctx.webgpu_global_ctx = reg_ctx->webgpu_global_ctx;
4918 // See GGML Backend Device Interface section
4919 static ggml_backend_device device = {
4920 /* .iface = */ ggml_backend_webgpu_device_i,
4921 /* .reg = */ reg,
4922 /* .context = */ &device_ctx,
4923 };
4924
4925 WEBGPU_CPU_PROFILE_TOTAL_END(reg_get_device, reg_ctx->webgpu_global_ctx);
4926 return &device;
4927}
4928
4929static const struct ggml_backend_reg_i ggml_backend_webgpu_reg_i = {
4930 /* .get_name = */ ggml_backend_webgpu_reg_get_name,
4931 /* .get_device_count = */ ggml_backend_webgpu_reg_get_device_count,
4932 /* .get_device = */ ggml_backend_webgpu_reg_get_device,
4933 /* .get_proc_address = */ NULL,
4934};
4935
4936/* End GGML Backend Registration Interface */
4937
4938ggml_backend_reg_t ggml_backend_webgpu_reg() {
4939 WEBGPU_LOG_DEBUG("ggml_backend_webgpu_reg()");
4940
4941 // Intentionally leak the global registry context to avoid crashing inside
4942 // Dawn/Vulkan static teardown during process exit.
4943 static ggml_backend_webgpu_reg_context * ctx = new ggml_backend_webgpu_reg_context();
4944
4945 static ggml_backend_reg reg = {
4946 /* .api_version = */ GGML_BACKEND_API_VERSION,
4947 /* .iface = */ ggml_backend_webgpu_reg_i,
4948 /* .context = */ ctx,
4949 };
4950
4951 ctx->name = GGML_WEBGPU_NAME;
4952 ctx->device_count = 0;
4953
4954 // Keep one Dawn/WebGPU instance alive for the lifetime of the static backend
4955 // registry. Recreating it on repeated registry lookups can invalidate
4956 // adapter/device references that are still held by the backend/device layer.
4957 if (ctx->webgpu_global_ctx != nullptr && ctx->webgpu_global_ctx->instance != nullptr) {
4958 return &reg;
4959 }
4960
4961 wgpu::InstanceDescriptor instance_descriptor{};
4962 std::vector<wgpu::InstanceFeatureName> instance_features = { wgpu::InstanceFeatureName::TimedWaitAny };
4963 instance_descriptor.requiredFeatures = instance_features.data();
4964 instance_descriptor.requiredFeatureCount = instance_features.size();
4965
4966#if !defined(__EMSCRIPTEN__) && !defined(__wasi__)
4967 const char * const instanceEnabledToggles[] = { "allow_unsafe_apis" };
4968 wgpu::DawnTogglesDescriptor instanceTogglesDesc;
4969 instanceTogglesDesc.enabledToggles = instanceEnabledToggles;
4970 instanceTogglesDesc.enabledToggleCount = 1;
4971 instance_descriptor.nextInChain = &instanceTogglesDesc;
4972#endif
4973
4974 wgpu::Instance inst = wgpu::CreateInstance(&instance_descriptor);
4975 ctx->webgpu_global_ctx = webgpu_global_context(new webgpu_global_context_struct());
4976 ctx->webgpu_global_ctx->instance = std::move(inst);
4977
4978 // Probe for adapter support
4979 wgpu::Adapter adapter;
4980 if (ctx->webgpu_global_ctx->instance != nullptr) {
4981 ggml_backend_webgpu_request_adapter(ctx->webgpu_global_ctx->instance, adapter);
4982 }
4983
4984 // WebGPU backend requires f16 support and, on native, implicit device synchronization.
4985 if (adapter != nullptr && adapter.HasFeature(wgpu::FeatureName::ShaderF16)
4986#if !defined(__EMSCRIPTEN__) && !defined(__wasi__)
4987 && adapter.HasFeature(wgpu::FeatureName::ImplicitDeviceSynchronization)
4988#endif
4989 ) {
4990 ctx->device_count = 1;
4991 }
4992
4993 return &reg;
4994}
4995
4996ggml_backend_t ggml_backend_webgpu_init(void) {
4997 ggml_backend_reg_t reg = ggml_backend_webgpu_reg();
4998 if (ggml_backend_reg_dev_count(reg) == 0) {
4999 return nullptr;
5000 }
5001 ggml_backend_dev_t dev = ggml_backend_reg_dev_get(reg, 0);
5002 return ggml_backend_webgpu_backend_init(dev, nullptr);
5003}
5004
5005GGML_BACKEND_DL_IMPL(ggml_backend_webgpu_reg)