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-cpu / kleidiai / kleidiai.cpp

1917 lines · 78638 bytes Raw Blame History
1// SPDX-FileCopyrightText: Copyright 2025-2026 Arm Limited and/or its affiliates <open-source-office@arm.com>
2// SPDX-License-Identifier: MIT
3//
4#include <arm_neon.h>
5#include <cassert>
6#include <cstdio>
7#include <cstdlib>
8#include <atomic>
9#include <cfloat>
10#include <cctype>
11#include <algorithm>
12#include <cmath>
13#include <stdexcept>
14#include <stdint.h>
15#include <string.h>
16#include <string>
17#include <vector>
18#include <array>
19#include <cstddef>
20#include <cstdint>
21#include <fstream>
22#include <map>
23#include <iostream>
24#include <climits>
25#include <charconv>
26#include <system_error>
27#if defined(__linux__)
28#include <asm/hwcap.h>
29#include <dirent.h>
30#include <sys/auxv.h>
31#include <sys/types.h>
32#include <sys/stat.h>
33#include <unistd.h>
34#elif defined(__APPLE__)
35#include <sys/sysctl.h>
36#include <sys/types.h>
37#endif
38
39#include "kleidiai.h"
40
41#include "ggml-cpu.h"
42#include "ggml-cpu-impl.h"
43#include "ggml-impl.h"
44#include "ggml-feats.h"
45#include "ggml-backend-impl.h"
46#include "ggml-quants.h"
47#include "ggml-threading.h"
48#include "traits.h"
49
50#include "kernels.h"
51
52#include "kai/kai_common.h"
53
54#define GGML_COMMON_DECL_CPP
55#include "ggml-common.h"
56
57static constexpr int GGML_KLEIDIAI_MAX_KERNEL_SLOTS = 2;
58static constexpr uint32_t GGML_KLEIDIAI_PACK_MAGIC = 0x4b4c4149; // "KLAI"
59static constexpr uint16_t GGML_KLEIDIAI_PACK_VERSION = 1;
60static constexpr size_t GGML_KLEIDIAI_PACK_ALIGN = 64;
61static constexpr size_t GGML_KLEIDIAI_Q4_K_BL = QK_K / 8;
62
63static_assert(QK_K == 256, "KleidiAI Q4_K kernels require 256-value super-blocks");
64
65struct ggml_kleidiai_context {
66 cpu_feature features;
67 ggml_kleidiai_kernels * kernels_q4;
68 ggml_kleidiai_kernels * kernels_q4k;
69 ggml_kleidiai_kernels * kernels_q8;
70 ggml_kleidiai_kernels * kernels_f32;
71 int sme_thread_cap; // <= 0 means "SME disabled/unknown"
72 int thread_hint; // <= 0 means "no hint"
73 int chunk_multiplier;
74} static ctx = { CPU_FEATURE_NONE, nullptr, nullptr, nullptr, nullptr, 0, -1, 4 };
75
76static inline bool is_sme_family(cpu_feature f) {
77 return (f & (CPU_FEATURE_SME | CPU_FEATURE_SME2)) != CPU_FEATURE_NONE;
78}
79
80static const char* cpu_feature_to_string(cpu_feature f) {
81 if (f == CPU_FEATURE_NONE) {
82 return "NONE";
83 } else if ((f & CPU_FEATURE_SME2) == CPU_FEATURE_SME2) {
84 return "SME2";
85 } else if ((f & CPU_FEATURE_SME) == CPU_FEATURE_SME) {
86 return "SME";
87 } else if ((f & CPU_FEATURE_SVE) == CPU_FEATURE_SVE) {
88 return "SVE";
89 }
90 else if ((f & CPU_FEATURE_I8MM) == CPU_FEATURE_I8MM) {
91 return "I8MM";
92 } else if ((f & CPU_FEATURE_DOTPROD) == CPU_FEATURE_DOTPROD) {
93 return "DOTPROD";
94 }
95 else {
96 return "UNKNOWN";
97 }
98}
99
100#if defined(__linux__) && defined(__aarch64__)
101static bool parse_cpu_dir_name(const char* name, size_t* cpu) {
102 if (strncmp(name, "cpu", 3) != 0 ||
103 name[3] < '0' || name[3] > '9') {
104 return false;
105 }
106
107 const char* first = name + 3;
108 const char* last = name + strlen(name);
109
110 size_t value = 0;
111 const auto [end, ec] = std::from_chars(first, last, value, 10);
112
113 if (ec != std::errc{} || end != last) {
114 return false;
115 }
116
117 *cpu = value;
118 return true;
119}
120
121static std::vector<size_t> detect_cpu_ids() {
122 std::vector<size_t> cpus;
123
124 DIR * dir = opendir("/sys/devices/system/cpu");
125 if (dir == nullptr) {
126 return cpus;
127 }
128
129 while (dirent * entry = readdir(dir)) {
130 size_t cpu = 0;
131 if (parse_cpu_dir_name(entry->d_name, &cpu)) {
132 cpus.push_back(cpu);
133 }
134 }
135 closedir(dir);
136
137 std::sort(cpus.begin(), cpus.end());
138 cpus.erase(std::unique(cpus.begin(), cpus.end()), cpus.end());
139 return cpus;
140}
141#endif
142
143#if defined(__APPLE__) && defined(__aarch64__)
144static bool apple_sme_counted_perf_level(std::string name) {
145 for (std::string::size_type i = 0; i < name.size(); ++i) {
146 name[i] = (char) std::tolower((unsigned char) name[i]);
147 }
148
149 // Conservative ceiling: only count perf-level names observed to provide full SME throughput.
150 // Future names should be calibrated here before they raise the automatic SME thread cap.
151 return name.find("super") != std::string::npos ||
152 name.find("performance") != std::string::npos;
153}
154#endif
155
156static void add_smcus_from_smidr(uint64_t smidr, size_t & num_private, std::map<uint32_t, size_t> & shared_counts) {
157 // Arm ARM: SMIDR_EL1. SH==0 is implementation-defined; keep the existing
158 // conservative policy and only treat zero affinity as private.
159 const uint32_t sh = (uint32_t)((smidr >> 13) & 0x3);
160 const uint32_t nsmc = (uint32_t)((smidr >> 56) & 0xF);
161 const size_t shared_count = nsmc == 0xF ? 1 : (size_t)nsmc + 1;
162 const uint32_t affinity = (uint32_t)(smidr & 0xFFFu);
163 const uint32_t affinity2 = (uint32_t)((smidr >> 32) & 0xFFFFFu);
164 const uint32_t id = (affinity2 << 12) | affinity;
165
166 if (nsmc == 0xF) {
167 GGML_LOG_WARN("kleidiai: NSMC detected as 0xF indicating reseved value, setting min safe shared SMCU count to 1");
168 }
169
170 switch (sh) {
171 case 2: // private SMCU
172 ++num_private;
173 break;
174 case 3: // shared SMCU
175 if (shared_counts[id] < shared_count) {
176 shared_counts[id] = shared_count;
177 }
178 break;
179 case 0:
180 if (id == 0) {
181 ++num_private;
182 } else if (shared_counts[id] < shared_count) {
183 shared_counts[id] = shared_count;
184 }
185 break;
186 default:
187 break;
188 }
189}
190
191static size_t detect_num_smcus() {
192 const auto runtime_feat = ggml_feats_get_arch64_runtime();
193 if (!runtime_feat.has_sme) {
194 return 0;
195 }
196
197#if defined(__linux__) && defined(__aarch64__)
198 // Linux/aarch64: Best-effort count of Streaming Mode Compute Units (SMCUs) via SMIDR_EL1 sysfs.
199 size_t num_private = 0;
200 std::map<uint32_t, size_t> shared_counts;
201
202 const std::vector<size_t> cpus = detect_cpu_ids();
203 for (const size_t cpu : cpus) {
204 const std::string path =
205 "/sys/devices/system/cpu/cpu" + std::to_string(cpu) +
206 "/regs/identification/smidr_el1";
207
208 std::ifstream file(path);
209 if (!file.is_open()) {
210 continue;
211 }
212
213 uint64_t smidr = 0;
214 if (!(file >> std::hex >> smidr)) {
215 continue;
216 }
217
218 add_smcus_from_smidr(smidr, num_private, shared_counts);
219 }
220
221 size_t total = num_private;
222 for (const auto & entry : shared_counts) {
223 total += entry.second;
224 }
225 return total;
226
227#elif defined(__APPLE__) && defined(__aarch64__)
228 int perf_levels = 0;
229 size_t size = sizeof(perf_levels);
230 if (sysctlbyname("hw.nperflevels", &perf_levels, &size, nullptr, 0) != 0 ||
231 size != sizeof(perf_levels) || perf_levels <= 0) {
232 return 0;
233 }
234
235 size_t units = 0;
236 for (int i = 0; i < perf_levels; ++i) {
237 char key[64] = {};
238 int physical_cpus = 0;
239 int cpus_per_l2 = 0;
240
241 snprintf(key, sizeof(key), "hw.perflevel%d.physicalcpu", i);
242 size = sizeof(physical_cpus);
243 if (sysctlbyname(key, &physical_cpus, &size, nullptr, 0) != 0 ||
244 size != sizeof(physical_cpus) || physical_cpus <= 0) {
245 continue;
246 }
247
248 snprintf(key, sizeof(key), "hw.perflevel%d.cpusperl2", i);
249 size = sizeof(cpus_per_l2);
250 if (sysctlbyname(key, &cpus_per_l2, &size, nullptr, 0) != 0 ||
251 size != sizeof(cpus_per_l2) || cpus_per_l2 <= 0) {
252 continue;
253 }
254
255 snprintf(key, sizeof(key), "hw.perflevel%d.name", i);
256 size = 0;
257 if (sysctlbyname(key, nullptr, &size, nullptr, 0) != 0 || size == 0) {
258 continue;
259 }
260
261 std::string name(size, '\0');
262 if (sysctlbyname(key, &name[0], &size, nullptr, 0) != 0) {
263 continue;
264 }
265 name.resize(size);
266 while (!name.empty() && name.back() == '\0') {
267 name.pop_back();
268 }
269
270 if (apple_sme_counted_perf_level(name)) {
271 units += (size_t) ((physical_cpus + cpus_per_l2 - 1) / cpus_per_l2);
272 }
273 }
274
275 return units;
276
277#elif defined(_WIN32) && (defined(_M_ARM64) || defined(__aarch64__))
278 // No verified Windows arm64 SMCU detection path yet. Return unknown and use
279 // GGML_KLEIDIAI_SME=N as a diagnostics/debug override for SME thread cap
280 // calibration until a detection mechanism is verified on real hardware.
281 return 0;
282
283#else
284 return 0;
285#endif
286}
287
288static int parse_uint_env(const char *s, const char *name, bool *ok) {
289 if (!s) { *ok = false; return 0; }
290 char *end = nullptr;
291 long v = strtol(s, &end, 10);
292 if (end == s || *end != '\0') {
293 GGML_LOG_WARN("kleidiai: invalid %s='%s' (expected integer)\n", name, s);
294 *ok = false;
295 return 0;
296 }
297 if (v < 0 || v > INT_MAX) {
298 GGML_LOG_WARN("kleidiai: out-of-range %s='%s'\n", name, s);
299 *ok = false;
300 return 0;
301 }
302 *ok = true;
303 return (int)v;
304}
305
306static void init_kleidiai_context(void) {
307 ggml_critical_section_start();
308 static bool initialized = false;
309
310 if (!initialized) {
311 initialized = true;
312
313 // Optional diagnostics/debug overrides; production defaults come from runtime detection.
314 const char *env_sme = getenv("GGML_KLEIDIAI_SME");
315 const char *env_threads = getenv("GGML_TOTAL_THREADS");
316 const char *env_chunk_mult = getenv("GGML_KLEIDIAI_CHUNK_MULTIPLIER");
317
318 const auto runtime_feat = ggml_feats_get_arch64_runtime();
319
320 size_t detected_smcus = 0;
321
322 // The fixed-width SVE kernels require 32-byte vectors, including the Q8 shared RHS layout.
323 ctx.features = (runtime_feat.has_dotprod ? CPU_FEATURE_DOTPROD : CPU_FEATURE_NONE) |
324 (runtime_feat.has_i8mm ? CPU_FEATURE_I8MM : CPU_FEATURE_NONE) |
325 (runtime_feat.has_svei8mm ? CPU_FEATURE_SVEI8MM : CPU_FEATURE_NONE) |
326 (runtime_feat.has_fp16 ? CPU_FEATURE_FP16 : CPU_FEATURE_NONE) |
327 (runtime_feat.sve_cnt == QK8_0 ? CPU_FEATURE_SVE : CPU_FEATURE_NONE);
328
329 if (env_threads) {
330 bool ok = false;
331 int hint = parse_uint_env(env_threads, "GGML_TOTAL_THREADS", &ok);
332 if (ok && hint > 0) {
333 ctx.thread_hint = hint;
334 }
335 }
336
337 if (env_chunk_mult) {
338 bool ok = false;
339 int multiplier = parse_uint_env(env_chunk_mult, "GGML_KLEIDIAI_CHUNK_MULTIPLIER", &ok);
340 if (ok && multiplier > 0) {
341 ctx.chunk_multiplier = multiplier;
342 }
343 }
344
345 int sme_cores = 0;
346 bool sme_env_ok = false;
347 bool sme_env_set = (env_sme != nullptr);
348
349 const bool has_supported_sme_family = runtime_feat.has_sme;
350 bool sme_cap_detected = false;
351
352 if (has_supported_sme_family) {
353 detected_smcus = detect_num_smcus();
354 sme_cap_detected = detected_smcus > 0;
355 // Some platforms expose SME without exposing a calibrated SMCU count.
356 // Use one SME thread as the conservative default; add platform SMCU detection to raise it.
357 sme_cores = sme_cap_detected ? (int)detected_smcus : 1;
358
359 if (!sme_env_set && !sme_cap_detected) {
360 GGML_LOG_INFO("kleidiai: SME detected; SMCU count unavailable, using conservative SME thread cap=1\n");
361 }
362 }
363
364 // Runtime-detect SME support and available SMCUs first. The detected SMCU
365 // count is used as the SME thread cap, and GGML_KLEIDIAI_SME can debug-override that:
366 // - unset: use runtime detection.
367 // - 0: disable SME-family kernels.
368 // - N > 0: use N as the SME thread cap, if an SME-family kernel is selectable.
369 if (sme_env_set) {
370 bool ok = false;
371 int v = parse_uint_env(env_sme, "GGML_KLEIDIAI_SME", &ok);
372 sme_env_ok = ok;
373
374 if (ok) {
375 if (has_supported_sme_family) {
376 sme_cores = v;
377 } else {
378 if (v > 0) {
379 GGML_LOG_WARN("kleidiai: GGML_KLEIDIAI_SME=%d but SME is not supported on this CPU; disabling SME-family kernels\n", v);
380 }
381 sme_cores = 0;
382 }
383 } else {
384 GGML_LOG_WARN("kleidiai: GGML_KLEIDIAI_SME set but parsing failed; using automatic SME thread cap\n");
385 }
386 }
387
388 if (sme_cores > 0 && has_supported_sme_family) {
389 ctx.features |= CPU_FEATURE_SME;
390 if (runtime_feat.has_sme2) {
391 ctx.features |= CPU_FEATURE_SME2;
392 }
393 }
394
395 // Kernel selection
396 ctx.kernels_q4 = ggml_kleidiai_select_kernels_q4_0(ctx.features);
397 ctx.kernels_q4k = ggml_kleidiai_select_kernels_q4_k(ctx.features);
398 ctx.kernels_q8 = ggml_kleidiai_select_kernels_q8_0(ctx.features);
399 ctx.kernels_f32 = ggml_kleidiai_select_kernels_f32(ctx.features);
400
401 if (!ctx.kernels_q4) {
402 GGML_LOG_INFO("kleidiai: no compatible q4 kernels found for CPU features mask %d\n", (int)ctx.features);
403 } else {
404 GGML_LOG_INFO("kleidiai: primary q4 kernel feature %s\n", cpu_feature_to_string(ctx.kernels_q4->required_cpu));
405 }
406
407 if (!ctx.kernels_q8) {
408 GGML_LOG_INFO("kleidiai: no compatible q8 kernels found for CPU features mask %d\n", (int)ctx.features);
409 } else {
410 GGML_LOG_INFO("kleidiai: primary q8 kernel feature %s\n", cpu_feature_to_string(ctx.kernels_q8->required_cpu));
411 }
412
413 if (!ctx.kernels_q4k) {
414 GGML_LOG_INFO("kleidiai: no compatible q4_k kernels found for CPU features mask %d\n", (int) ctx.features);
415 } else {
416 GGML_LOG_INFO("kleidiai: primary q4_k kernel feature %s\n", cpu_feature_to_string(ctx.kernels_q4k->required_cpu));
417 }
418
419 if (!ctx.kernels_f32) {
420 GGML_LOG_INFO("kleidiai: no compatible f32 kernels found for CPU features mask %d\n", (int)ctx.features);
421 } else {
422 GGML_LOG_INFO("kleidiai: primary f32 kernel feature %s\n", cpu_feature_to_string(ctx.kernels_f32->required_cpu));
423 }
424
425 const bool has_selected_sme_family_kernel =
426 (ctx.kernels_q4 && is_sme_family(ctx.kernels_q4->required_cpu)) ||
427 (ctx.kernels_q4k && is_sme_family(ctx.kernels_q4k->required_cpu)) ||
428 (ctx.kernels_q8 && is_sme_family(ctx.kernels_q8->required_cpu)) ||
429 (ctx.kernels_f32 && is_sme_family(ctx.kernels_f32->required_cpu));
430 ctx.sme_thread_cap = has_selected_sme_family_kernel ? sme_cores : 0;
431
432 if (has_selected_sme_family_kernel) {
433 if (sme_env_set && sme_env_ok && sme_cores > 0) {
434 GGML_LOG_INFO("kleidiai: SME enabled (GGML_KLEIDIAI_SME=%d debug override)\n", sme_cores);
435 } else if (sme_cap_detected) {
436 GGML_LOG_INFO("kleidiai: SME enabled (runtime-detected SME thread cap=%d)\n", sme_cores);
437 } else {
438 GGML_LOG_INFO("kleidiai: SME enabled (runtime SME detected, conservative thread cap=%d)\n", sme_cores);
439 }
440 } else {
441 GGML_LOG_INFO("kleidiai: SME disabled\n");
442 }
443 }
444
445 ggml_critical_section_end();
446}
447
448static inline int kleidiai_sme_thread_cap() {
449 return ctx.sme_thread_cap;
450}
451
452static inline size_t align_up(size_t value, size_t alignment) {
453 if (alignment == 0) {
454 return value;
455 }
456 const size_t remainder = value % alignment;
457 return remainder == 0 ? value : value + (alignment - remainder);
458}
459
460static inline size_t gcd_size(size_t a, size_t b) {
461 while (b != 0) {
462 const size_t t = a % b;
463 a = b;
464 b = t;
465 }
466 return a;
467}
468
469static inline bool lcm_size(size_t a, size_t b, size_t & result) {
470 if (a == 0 || b == 0) {
471 result = 0;
472 return false;
473 }
474 const size_t g = gcd_size(a, b);
475 const size_t q = a / g;
476 if (q > SIZE_MAX / b) {
477 return false;
478 }
479 result = q * b;
480 return true;
481}
482
483static inline size_t ceil_div_size(size_t a, size_t b) {
484 return b == 0 ? 0 : (a + b - 1) / b;
485}
486
487static inline size_t kleidiai_chunk_cols(size_t n, int nth_total, bool disable_chunking, size_t n_step) {
488 const size_t multiplier = (nth_total == 1 || disable_chunking) ? 1 : std::max<size_t>(1, (size_t) ctx.chunk_multiplier);
489 const size_t divisor = std::max<size_t>(1, (size_t) nth_total * multiplier);
490 const size_t chunk_cols = align_up(std::max<size_t>(1, ceil_div_size(n, divisor)), n_step);
491 return chunk_cols ? chunk_cols : n_step;
492}
493
494struct kleidiai_block_args {
495 size_t lhs_bl;
496 size_t rhs_bl;
497 size_t pack_bl;
498};
499
500static inline kleidiai_block_args kleidiai_get_block_args(ggml_type rhs_type) {
501 switch (rhs_type) {
502 case GGML_TYPE_Q4_0:
503 return { QK4_0, QK4_0, QK4_0 };
504 case GGML_TYPE_Q4_K:
505 return { GGML_KLEIDIAI_Q4_K_BL, GGML_KLEIDIAI_Q4_K_BL, GGML_KLEIDIAI_Q4_K_BL };
506 case GGML_TYPE_Q8_0:
507 return { 0, 0, QK8_0 };
508 default:
509 return { 0, 0, 0 };
510 }
511}
512
513static inline bool kleidiai_pack_fallback_allowed() {
514 if (ctx.sme_thread_cap <= 0) {
515 return false;
516 }
517 if (ctx.thread_hint <= 0) {
518 return true;
519 }
520 return ctx.thread_hint > ctx.sme_thread_cap;
521}
522
523struct kleidiai_weight_header {
524 uint32_t magic;
525 uint16_t version;
526 uint16_t slot_count;
527 uint64_t offsets[GGML_KLEIDIAI_MAX_KERNEL_SLOTS];
528 uint64_t sizes[GGML_KLEIDIAI_MAX_KERNEL_SLOTS];
529};
530
531static inline kleidiai_weight_header * kleidiai_weight_header_from_ptr(void * data) {
532 return reinterpret_cast<kleidiai_weight_header *>(data);
533}
534
535static inline const kleidiai_weight_header * kleidiai_weight_header_from_ptr(const void * data) {
536 return reinterpret_cast<const kleidiai_weight_header *>(data);
537}
538
539static inline bool kleidiai_is_weight_header_valid(const kleidiai_weight_header * header) {
540 if (!header) {
541 return false;
542 }
543 if (header->magic != GGML_KLEIDIAI_PACK_MAGIC || header->version != GGML_KLEIDIAI_PACK_VERSION) {
544 return false;
545 }
546 if (header->slot_count == 0 || header->slot_count > GGML_KLEIDIAI_MAX_KERNEL_SLOTS) {
547 return false;
548 }
549 return true;
550}
551
552static inline uint8_t * kleidiai_weight_slot_ptr(kleidiai_weight_header * header, int slot) {
553 if (!kleidiai_is_weight_header_valid(header)) {
554 return nullptr;
555 }
556 if (slot < 0 || slot >= header->slot_count) {
557 return nullptr;
558 }
559 return reinterpret_cast<uint8_t *>(header) + header->offsets[slot];
560}
561
562static inline const uint8_t * kleidiai_weight_slot_ptr(const kleidiai_weight_header * header, int slot) {
563 if (!kleidiai_is_weight_header_valid(header)) {
564 return nullptr;
565 }
566 if (slot < 0 || slot >= header->slot_count) {
567 return nullptr;
568 }
569 return reinterpret_cast<const uint8_t *>(header) + header->offsets[slot];
570}
571
572static inline ggml_kleidiai_kernels * kleidiai_primary_kernel_q4() {
573 return ctx.kernels_q4;
574}
575
576static inline ggml_kleidiai_kernels * kleidiai_primary_kernel_q4k() {
577 return ctx.kernels_q4k;
578}
579
580static inline ggml_kleidiai_kernels * kleidiai_primary_kernel_q8() {
581 return ctx.kernels_q8;
582}
583
584static inline ggml_kleidiai_kernels * kleidiai_primary_kernel_f32() {
585 return ctx.kernels_f32;
586}
587
588template <typename SelectFallback>
589static int kleidiai_collect_kernel_chain_common(
590 ggml_kleidiai_kernels * primary,
591 cpu_feature features,
592 std::array<ggml_kleidiai_kernels *, GGML_KLEIDIAI_MAX_KERNEL_SLOTS> & out,
593 SelectFallback select_fallback) {
594 int count = 0;
595 if (!primary) {
596 return 0;
597 }
598 out[count++] = primary;
599
600 if (primary->rhs_info.repack_mode == RHS_REPACK_SINGLE_ONLY) {
601 return count;
602 }
603
604 if (is_sme_family(primary->required_cpu)) {
605 const cpu_feature fallback_mask = static_cast<cpu_feature>(features & ~(CPU_FEATURE_SME | CPU_FEATURE_SME2));
606 if (fallback_mask != CPU_FEATURE_NONE) {
607 ggml_kleidiai_kernels * fallback = select_fallback(fallback_mask);
608 if (fallback && fallback != primary &&
609 fallback->rhs_info.repack_mode != RHS_REPACK_SINGLE_ONLY &&
610 fallback->lhs_type == primary->lhs_type &&
611 fallback->rhs_type == primary->rhs_type &&
612 fallback->op_type == primary->op_type) {
613 out[count++] = fallback;
614 }
615 }
616 }
617
618 return count;
619}
620
621static int kleidiai_collect_kernel_chain(const struct ggml_tensor * op,
622 std::array<ggml_kleidiai_kernels *, GGML_KLEIDIAI_MAX_KERNEL_SLOTS> & out) {
623 ggml_kleidiai_kernels * primary = ggml_kleidiai_select_kernels(ctx.features, op);
624 return kleidiai_collect_kernel_chain_common(primary, ctx.features, out,
625 [&](cpu_feature mask) { return ggml_kleidiai_select_kernels(mask, op); });
626}
627
628static int kleidiai_collect_q4_chain(std::array<ggml_kleidiai_kernels *, GGML_KLEIDIAI_MAX_KERNEL_SLOTS> & out) {
629 ggml_kleidiai_kernels * primary = kleidiai_primary_kernel_q4();
630 return kleidiai_collect_kernel_chain_common(primary, ctx.features, out,
631 [&](cpu_feature mask) { return ggml_kleidiai_select_kernels_q4_0(mask); });
632}
633
634static int kleidiai_collect_q4k_chain(std::array<ggml_kleidiai_kernels *, GGML_KLEIDIAI_MAX_KERNEL_SLOTS> & out) {
635 ggml_kleidiai_kernels * primary = kleidiai_primary_kernel_q4k();
636 return kleidiai_collect_kernel_chain_common(primary, ctx.features, out,
637 [&](cpu_feature mask) { return ggml_kleidiai_select_kernels_q4_k(mask); });
638}
639
640static int kleidiai_collect_q8_chain(std::array<ggml_kleidiai_kernels *, GGML_KLEIDIAI_MAX_KERNEL_SLOTS> & out) {
641 ggml_kleidiai_kernels * primary = kleidiai_primary_kernel_q8();
642 return kleidiai_collect_kernel_chain_common(primary, ctx.features, out,
643 [&](cpu_feature mask) { return ggml_kleidiai_select_kernels_q8_0(mask); });
644}
645
646static int kleidiai_collect_f32_chain(std::array<ggml_kleidiai_kernels *, GGML_KLEIDIAI_MAX_KERNEL_SLOTS> & out) {
647 ggml_kleidiai_kernels * primary = kleidiai_primary_kernel_f32();
648 return kleidiai_collect_kernel_chain_common(primary, ctx.features, out,
649 [&](cpu_feature mask) { return ggml_kleidiai_select_kernels_f32(mask); });
650}
651
652static inline int64_t ggml_ne(const ggml_tensor * tensor, int dim) {
653 GGML_ASSERT(dim >= 0 && dim < GGML_MAX_DIMS);
654 return tensor->ne[dim];
655}
656
657namespace ggml::cpu::kleidiai {
658
659static size_t round_down(size_t x, size_t y) {
660 return y == 0 ? x : x - (x % y);
661}
662
663static void transpose_f32kxn_f16nxk(size_t n, size_t k, float * dst, const uint16_t * src, size_t rhs_stride) {
664 size_t src_stride = rhs_stride / sizeof(uint16_t);
665 size_t dst_stride = n;
666
667 for (size_t k_idx = 0; k_idx < k; ++k_idx) {
668 for (size_t n_idx = 0; n_idx < n; ++n_idx) {
669 uint16_t v = *(src + k_idx + n_idx * src_stride);
670 *(dst + n_idx + k_idx * dst_stride) = kai_cast_f32_f16(v);
671 }
672 }
673}
674
675class tensor_traits : public ggml::cpu::tensor_traits {
676 bool work_size(int /* n_threads */, const struct ggml_tensor * op, size_t & size) override {
677 if (op->op != GGML_OP_MUL_MAT) {
678 return false;
679 }
680
681 std::array<ggml_kleidiai_kernels *, GGML_KLEIDIAI_MAX_KERNEL_SLOTS> kernel_chain;
682 const int slot_count = kleidiai_collect_kernel_chain(op, kernel_chain);
683 if (slot_count == 0) {
684 return false;
685 }
686
687 const bool is_gemv = op->src[1]->ne[1] == 1;
688 const size_t k = op->src[0]->ne[0];
689 const size_t n = op->src[0]->ne[1];
690 const size_t m = op->src[1]->ne[1];
691
692 if (op->src[0]->type == GGML_TYPE_Q4_0 || op->src[0]->type == GGML_TYPE_Q4_K ||
693 op->src[0]->type == GGML_TYPE_Q8_0 || op->src[0]->type == GGML_TYPE_Q6_K) {
694 const kleidiai_block_args block_args = kleidiai_get_block_args(kernel_chain[0]->rhs_type);
695 const size_t qk = block_args.pack_bl;
696
697 size_t cursor = 0;
698 bool any_slot = false;
699
700 for (int slot = 0; slot < slot_count; ++slot) {
701 ggml_kleidiai_kernels * kernels = kernel_chain[slot];
702 lhs_packing_info * lhs_info = is_gemv ? &kernels->gemv_lhs_info : &kernels->gemm_lhs_info;
703 kernel_info * kernel = is_gemv ? &kernels->gemv : &kernels->gemm;
704
705 if (!lhs_info || !lhs_info->packed_size_ex || !kernel) {
706 return false;
707 }
708
709 const size_t mr = kernel->get_mr();
710 const size_t kr = kernel->get_kr();
711 const size_t sr = kernel->get_sr();
712
713 const size_t packed = lhs_info->packed_size_ex(m, k, qk, mr, kr, sr);
714
715 cursor = align_up(cursor, GGML_KLEIDIAI_PACK_ALIGN);
716 cursor += packed;
717 any_slot = true;
718 }
719
720 if (!any_slot) {
721 return false;
722 }
723
724 size = cursor;
725 return true;
726 }
727
728 if (op->src[0]->type == GGML_TYPE_F32) {
729 ggml_kleidiai_kernels * primary = kernel_chain[0];
730 kernel_info * gemv_kernel = primary ? &primary->gemv : nullptr;
731 if (is_gemv && op->src[1]->nb[0] == (int64_t) sizeof(float) && gemv_kernel &&
732 gemv_kernel->get_lhs_offset_ex && gemv_kernel->get_rhs_packed_offset_ex &&
733 gemv_kernel->run_kernel_ex && gemv_kernel->get_dst_offset) {
734 size = 0;
735 return true;
736 }
737
738 size_t cursor = 0;
739 bool any_slot = false;
740
741 for (int slot = 0; slot < slot_count; ++slot) {
742 ggml_kleidiai_kernels * kernels = kernel_chain[slot];
743 lhs_packing_info * lhs_info = &kernels->gemm_lhs_info;
744 kernel_info * kernel = &kernels->gemm;
745
746 if (!lhs_info || !lhs_info->packed_size_ex || !kernel) {
747 return false;
748 }
749
750 const size_t mr = kernel->get_mr();
751 const size_t kr = kernel->get_kr();
752 const size_t sr = kernel->get_sr();
753
754 cursor = align_up(cursor, GGML_KLEIDIAI_PACK_ALIGN);
755 cursor += lhs_info->packed_size_ex(m, k, 0, mr, kr, sr);
756 any_slot = true;
757 }
758
759 if (!any_slot) {
760 return false;
761 }
762
763 size = cursor;
764 return true;
765 }
766
767 if (op->src[0]->type == GGML_TYPE_F16) {
768 const int64_t lhs_batch_size0 = op->src[1]->ne[2];
769 const int64_t rhs_batch_size0 = op->src[0]->ne[2];
770 GGML_ASSERT(rhs_batch_size0 > 0);
771 const int64_t r = lhs_batch_size0 / rhs_batch_size0;
772
773 size_t cursor = 0;
774 bool any_slot = false;
775
776 for (int slot = 0; slot < slot_count; ++slot) {
777 ggml_kleidiai_kernels * kernels = kernel_chain[slot];
778 lhs_packing_info * lhs_info = is_gemv ? &kernels->gemv_lhs_info : &kernels->gemm_lhs_info;
779 kernel_info * kernel = is_gemv ? &kernels->gemv : &kernels->gemm;
780 if (!lhs_info || !lhs_info->packed_size_ex || !kernels->rhs_info.packed_size_ex || !kernel) {
781 return false;
782 }
783
784 const size_t mr = kernel->get_mr();
785 const size_t kr = kernel->get_kr();
786 const size_t sr = kernel->get_sr();
787
788 cursor = align_up(cursor, GGML_KLEIDIAI_PACK_ALIGN);
789 cursor += lhs_info->packed_size_ex(m * r, k, 0, mr, kr, sr);
790 any_slot = true;
791 }
792
793 for (int slot = 0; slot < slot_count; ++slot) {
794 ggml_kleidiai_kernels * kernels = kernel_chain[slot];
795 kernel_info * kernel = is_gemv ? &kernels->gemv : &kernels->gemm;
796 if (!kernel || !kernels->rhs_info.packed_size_ex) {
797 return false;
798 }
799 cursor = align_up(cursor, GGML_KLEIDIAI_PACK_ALIGN);
800 cursor += kernels->rhs_info.packed_size_ex(n, k, kernel->get_nr(), kernel->get_kr(), 0);
801 }
802
803 cursor = align_up(cursor, GGML_KLEIDIAI_PACK_ALIGN);
804 cursor += k * n * sizeof(float);
805 cursor = align_up(cursor, GGML_KLEIDIAI_PACK_ALIGN);
806 cursor += n * sizeof(float);
807
808 if (!any_slot) {
809 return false;
810 }
811
812 size = cursor;
813 return true;
814 }
815
816 return false;
817 }
818
819 bool compute_forward(struct ggml_compute_params * params, struct ggml_tensor * dst) override {
820 if (dst->op == GGML_OP_MUL_MAT) {
821 if (dst->src[0]->type == GGML_TYPE_Q4_0 || dst->src[0]->type == GGML_TYPE_Q4_K ||
822 dst->src[0]->type == GGML_TYPE_Q8_0 || dst->src[0]->type == GGML_TYPE_Q6_K) {
823 return compute_forward_qx(params, dst);
824 } else if (dst->src[0]->type == GGML_TYPE_F32) {
825 return compute_forward_f32(params, dst);
826 } else if (dst->src[0]->type == GGML_TYPE_F16) {
827 return compute_forward_fp16(params, dst);
828 }
829 }
830 return false;
831 }
832
833 bool compute_forward_f32(ggml_compute_params * params, struct ggml_tensor * dst) {
834 GGML_ASSERT(dst->src[0]->type == GGML_TYPE_F32);
835
836 const ggml_tensor * src0 = dst->src[0];
837 const ggml_tensor * src1 = dst->src[1];
838
839 GGML_TENSOR_BINARY_OP_LOCALS
840
841 if (src1->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) {
842 return false;
843 }
844
845 ggml_kleidiai_kernels * kernels = kleidiai_primary_kernel_f32();
846 if (!kernels) {
847 return false;
848 }
849
850 const size_t k = ne00;
851 const size_t m = ne11;
852 const size_t n = ne01;
853 const bool use_gemv = m == 1 && src1->nb[0] == (int64_t) sizeof(float) &&
854 kernels->gemv.get_lhs_offset_ex &&
855 kernels->gemv.get_rhs_packed_offset_ex &&
856 kernels->gemv.run_kernel_ex &&
857 kernels->gemv.get_dst_offset;
858
859 kernel_info * kernel = use_gemv ? &kernels->gemv : &kernels->gemm;
860 lhs_packing_info * lhs_info = &kernels->gemm_lhs_info;
861
862 if (!kernel || !kernel->get_lhs_offset_ex ||
863 !kernel->get_rhs_packed_offset_ex || !kernel->run_kernel_ex || !kernel->get_dst_offset) {
864 return false;
865 }
866
867 if (!use_gemv && (!lhs_info || !lhs_info->get_offset || !lhs_info->get_packed_offset_ex ||
868 !lhs_info->packed_size_ex || !lhs_info->pack_func_ex)) {
869 return false;
870 }
871
872 const kleidiai_weight_header * header = kleidiai_weight_header_from_ptr(src0->data);
873 const bool has_header = kleidiai_is_weight_header_valid(header);
874
875 const uint8_t * rhs_base = has_header ? kleidiai_weight_slot_ptr(header, 0)
876 : static_cast<const uint8_t *>(src0->data);
877 if (!rhs_base) {
878 return false;
879 }
880
881 const int nth = params->nth > 0 ? params->nth : 1;
882 const int ith = params->ith;
883
884 const size_t mr = kernel->get_mr();
885 const size_t kr = kernel->get_kr();
886 const size_t sr = kernel->get_sr();
887
888 const size_t lhs_packed_size = use_gemv ? 0 : lhs_info->packed_size_ex(m, k, 0, mr, kr, sr);
889 if (!use_gemv) {
890 GGML_ASSERT(lhs_packed_size <= params->wsize);
891 }
892
893 uint8_t * lhs_packed = static_cast<uint8_t *>(params->wdata);
894 const size_t dst_stride = dst->nb[1];
895 const size_t n_step = kernel->get_n_step() ? kernel->get_n_step() : 1;
896 const bool disable_chunking = ggml_is_numa();
897 GGML_ASSERT(n <= (size_t) INT_MAX);
898
899 const int64_t batch_size = ne12 * ne13;
900 for (int64_t batch_idx = 0; batch_idx < batch_size; ++batch_idx) {
901 const int64_t i12 = batch_idx % ne12;
902 const int64_t i13 = batch_idx / ne12;
903 const uint8_t * lhs_batch_base = static_cast<const uint8_t *>(src1->data) + i12 * src1->nb[2] + i13 * src1->nb[3];
904 uint8_t * dst_batch_base = static_cast<uint8_t *>(dst->data) + i12 * dst->nb[2] + i13 * dst->nb[3];
905
906 if (!use_gemv) {
907 const int64_t m_roundup_mr = kai_roundup((int64_t)m, (int64_t)mr);
908 int64_t max_threads = mr ? (m_roundup_mr / (int64_t)mr) : nth;
909 max_threads = std::max<int64_t>(1, max_threads);
910 const int64_t use_threads = std::min<int64_t>(nth, max_threads);
911
912 if (ith < use_threads) {
913 const int64_t num_m_per_thread0 = round_down((size_t)(m_roundup_mr / use_threads), mr);
914 const int64_t num_m_per_threadN_1 = (int64_t)m - (use_threads - 1) * num_m_per_thread0;
915
916 const int64_t m_start = (int64_t)ith * num_m_per_thread0;
917 const int64_t m_count = (ith == use_threads - 1) ? num_m_per_threadN_1 : num_m_per_thread0;
918
919 const size_t base_packed_off = lhs_info->get_packed_offset_ex(m_start, k, 0, mr, kr, sr);
920 const size_t next_block_off = lhs_info->get_packed_offset_ex(m_start + mr, k, 0, mr, kr, sr);
921 const size_t row_stride_bytes = mr ? (next_block_off - base_packed_off) / mr : 0;
922
923 int64_t remaining = m_count;
924 int64_t cur = m_start;
925
926 while (remaining > 0) {
927 const int64_t take = std::min<int64_t>((int64_t)m - cur, remaining);
928 const size_t src_off = lhs_info->get_offset(cur, src1->nb[1]);
929 const void * src_ptr = lhs_batch_base + src_off;
930 const size_t dst_off = base_packed_off + (size_t)(cur - m_start) * row_stride_bytes;
931 void * dst_ptr = lhs_packed + dst_off;
932
933 lhs_info->pack_func_ex(take, k, 0, mr, kr, sr, 0, src_ptr, src1->nb[1], dst_ptr);
934
935 cur += take;
936 remaining -= take;
937 }
938 }
939 }
940
941 if (ith == 0) {
942 ggml_threadpool_chunk_set(params->threadpool, 0);
943 }
944
945 ggml_barrier(params->threadpool);
946
947 const size_t chunk_cols = kleidiai_chunk_cols(n, nth, disable_chunking, n_step);
948 GGML_ASSERT(chunk_cols <= (size_t) INT_MAX);
949
950 int current_col = ggml_threadpool_chunk_add(params->threadpool, (int) chunk_cols);
951 while ((size_t) current_col < n) {
952 const size_t n_start = (size_t) current_col;
953 const size_t n_to_process = std::min(chunk_cols, n - n_start);
954
955 if (n_to_process > 0) {
956 const size_t lhs_offset = use_gemv ? kernel->get_lhs_offset_ex(0, k, 0)
957 : lhs_info->get_packed_offset_ex(0, k, 0, mr, kr, sr);
958 const size_t rhs_packed_offset = kernel->get_rhs_packed_offset_ex(n_start, k, 0);
959 const size_t dst_offset = kernel->get_dst_offset(0, n_start, dst_stride);
960
961 const void * lhs_ptr = use_gemv ? lhs_batch_base + lhs_offset
962 : lhs_packed + lhs_offset;
963 const void * rhs_ptr = rhs_base + rhs_packed_offset;
964 float * dst_ptr = reinterpret_cast<float *>(dst_batch_base + dst_offset);
965
966 kernel->run_kernel_ex(m, n_to_process, k, use_gemv ? src1->nb[1] : 0,
967 lhs_ptr,
968 rhs_ptr,
969 dst_ptr,
970 dst_stride,
971 sizeof(float),
972 -FLT_MAX,
973 FLT_MAX);
974 }
975
976 current_col = ggml_threadpool_chunk_add(params->threadpool, (int) chunk_cols);
977 }
978
979 if (batch_idx != batch_size - 1) {
980 ggml_barrier(params->threadpool);
981 }
982 }
983
984 return true;
985 }
986
987 bool compute_forward_fp16(ggml_compute_params * params, struct ggml_tensor * dst) {
988 const ggml_tensor * src0 = dst->src[0];
989 const ggml_tensor * src1 = dst->src[1];
990
991 GGML_TENSOR_BINARY_OP_LOCALS
992
993 ggml_kleidiai_kernels *kernels = ggml_kleidiai_select_kernels(ctx.features, dst);
994 if (!kernels) {
995 return false;
996 }
997
998 const bool is_gemv = src1->ne[1] == 1;
999 kernel_info * kernel = is_gemv ? &kernels->gemv : &kernels->gemm;
1000 lhs_packing_info * lhs_info = is_gemv ? &kernels->gemv_lhs_info : &kernels->gemm_lhs_info;
1001 GGML_ASSERT(kernel);
1002 if (!kernels->rhs_info.pack_func_ex ||
1003 !kernel->get_lhs_offset_ex || !kernel->get_rhs_packed_offset_ex || !kernel->run_kernel_ex) {
1004 return false;
1005 }
1006
1007 const int nth = params->nth;
1008 const int ith = params->ith;
1009
1010 const int64_t lhs_batch_size0 = ne12;
1011 const int64_t rhs_batch_size0 = ne02;
1012 const int64_t batch_size = lhs_batch_size0;
1013
1014 GGML_ASSERT(rhs_batch_size0 > 0);
1015 GGML_ASSERT(lhs_batch_size0 % rhs_batch_size0 == 0);
1016 const int64_t r = lhs_batch_size0 / rhs_batch_size0;
1017
1018 const int64_t m_group = ne11;
1019 const int64_t m = m_group;
1020 const int64_t n = ne01;
1021 const int64_t k = ne00;
1022
1023 const size_t lhs_stride = src1->nb[1];
1024 const size_t rhs_stride = src0->nb[1];
1025 const size_t dst_stride = dst->nb[1];
1026
1027 const int64_t mr = (int64_t) kernel->get_mr();
1028 const int64_t nr = (int64_t) kernel->get_nr();
1029 const int64_t kr = (int64_t) kernel->get_kr();
1030 const int64_t sr = (int64_t) kernel->get_sr();
1031
1032 const size_t lhs_packed_size = lhs_info->packed_size_ex(m, k, 0, mr, kr, sr);
1033 const size_t rhs_packed_size = kernels->rhs_info.packed_size_ex(n, k, nr, kr, 0);
1034 const size_t kxn_size = k * n * sizeof(float);
1035 const size_t bias_size = n * sizeof(float);
1036
1037 const size_t wsize_required = lhs_packed_size + rhs_packed_size + kxn_size + bias_size;
1038 GGML_ASSERT(wsize_required <= params->wsize);
1039
1040 uint8_t * lhs_packed = static_cast<uint8_t *>(params->wdata);
1041 uint8_t * rhs_packed = lhs_packed + lhs_packed_size;
1042 uint8_t * rhs_kxn = rhs_packed + rhs_packed_size;
1043 uint8_t * bias = rhs_kxn + kxn_size;
1044
1045 for (int64_t batch_idx = 0; batch_idx < batch_size; ++batch_idx) {
1046 const int64_t rhs_batch_idx = batch_idx / r;
1047 const uint8_t * rhs_batch_base = static_cast<const uint8_t *>(src0->data) + rhs_batch_idx * src0->nb[2];
1048 uint8_t * dst_batch_base = static_cast<uint8_t *>(dst->data) + batch_idx * dst->nb[2];
1049
1050 // LHS packing (threaded over m, honoring mr alignment and KV groups)
1051 {
1052 const int64_t m_roundup_mr = kai_roundup(m, mr);
1053 const int64_t num_threads = KAI_MIN(m_roundup_mr / mr, nth);
1054
1055 if (ith < num_threads) {
1056 const int64_t num_m_per_thread0 = round_down((size_t)(m_roundup_mr / num_threads), (size_t)mr);
1057 const int64_t num_m_per_threadN_1 = m - (num_threads - 1) * num_m_per_thread0;
1058
1059 const int64_t m_start = ith * num_m_per_thread0;
1060 const int64_t m_count = (ith == num_threads - 1) ? num_m_per_threadN_1 : num_m_per_thread0;
1061
1062 // Base packed offset (aligned) and per-row stride in bytes
1063 const size_t base_packed_off = lhs_info->get_packed_offset_ex(m_start, k, 0, mr, kr, sr);
1064 const size_t next_block_off = lhs_info->get_packed_offset_ex(m_start + mr, k, 0, mr, kr, sr);
1065 const size_t row_stride_bytes = (next_block_off - base_packed_off) / (size_t)mr;
1066
1067 int64_t remaining = m_count;
1068 int64_t cur = m_start;
1069
1070 while (remaining > 0) {
1071 const int64_t row_in_group = cur;
1072 const int64_t avail = m_group - row_in_group;
1073 const int64_t take = std::min(avail, remaining);
1074
1075 const uint8_t * lhs_batch_base = static_cast<const uint8_t *>(src1->data) + batch_idx * src1->nb[2];
1076 const void * src_ptr = lhs_batch_base + (size_t)row_in_group * lhs_stride;
1077 const size_t dst_off = base_packed_off + (size_t)(cur - m_start) * row_stride_bytes;
1078 void * dst_ptr = lhs_packed + dst_off;
1079
1080 lhs_info->pack_func_ex(take, k, 0, mr, kr, sr, 0, src_ptr, lhs_stride, dst_ptr);
1081
1082 cur += take;
1083 remaining -= take;
1084 }
1085 }
1086 }
1087
1088 // RHS packing (single thread), then synchronize
1089 if (ith == 0) {
1090 memset(bias, 0, (size_t)n * sizeof(float));
1091 transpose_f32kxn_f16nxk((size_t)n, (size_t)k,
1092 reinterpret_cast<float *>(rhs_kxn),
1093 reinterpret_cast<const uint16_t *>(rhs_batch_base),
1094 rhs_stride);
1095
1096 kernels->rhs_info.pack_func_ex(1, n, k, nr, kr, sr, 0, n * sizeof(float),
1097 rhs_kxn, bias, nullptr, rhs_packed, 0, nullptr);
1098 }
1099
1100 ggml_barrier(params->threadpool);
1101
1102 // Matmul (threaded over n)
1103 {
1104 const int64_t n_step = (int64_t) kernel->get_n_step();
1105 int64_t num_threads_n = KAI_MIN(n / n_step, nth);
1106 if (num_threads_n <= 0) {
1107 num_threads_n = 1;
1108 }
1109
1110 if (ith < num_threads_n) {
1111 const int64_t num_n_per_thread0 = round_down((size_t)(n / num_threads_n), (size_t)n_step);
1112 const int64_t num_n_per_threadN_1 = n - (num_threads_n - 1) * num_n_per_thread0;
1113
1114 const int64_t n_start = ith * num_n_per_thread0;
1115 const int64_t n_to_process = (ith == num_threads_n - 1) ? num_n_per_threadN_1 : num_n_per_thread0;
1116
1117 // LHS packed base at row 0 (consistent with packing above)
1118 const size_t lhs_packed_offset0 = lhs_info->get_packed_offset_ex(0, k, 0, mr, kr, sr);
1119 const size_t rhs_packed_offset = kernel->get_rhs_packed_offset_ex(n_start, k, 0);
1120 const size_t dst_offset = kernel->get_dst_offset((size_t)0, (size_t)n_start, dst_stride);
1121
1122 const void * lhs_ptr = lhs_packed + lhs_packed_offset0;
1123 const void * rhs_ptr = rhs_packed + rhs_packed_offset;
1124 float * dst_ptr = reinterpret_cast<float *>(dst_batch_base + dst_offset);
1125
1126 kernel->run_kernel_ex(m, n_to_process, k, 0, lhs_ptr, rhs_ptr, dst_ptr, dst_stride, sizeof(float), -FLT_MAX, FLT_MAX);
1127 }
1128 }
1129
1130 if (batch_idx != batch_size - 1) {
1131 ggml_barrier(params->threadpool);
1132 }
1133 }
1134
1135 return true;
1136 }
1137
1138 bool compute_forward_qx(struct ggml_compute_params * params, struct ggml_tensor * dst) {
1139 GGML_ASSERT(dst->src[0]->type == GGML_TYPE_Q4_0 || dst->src[0]->type == GGML_TYPE_Q4_K ||
1140 dst->src[0]->type == GGML_TYPE_Q8_0 || dst->src[0]->type == GGML_TYPE_Q6_K);
1141
1142 const ggml_tensor * src0 = dst->src[0];
1143 const ggml_tensor * src1 = dst->src[1];
1144
1145 GGML_TENSOR_BINARY_OP_LOCALS
1146
1147 const kleidiai_weight_header * header = kleidiai_weight_header_from_ptr(src0->data);
1148 const bool has_header = kleidiai_is_weight_header_valid(header);
1149 const bool is_gemv = src1->ne[1] == 1;
1150 std::array<ggml_kleidiai_kernels *, GGML_KLEIDIAI_MAX_KERNEL_SLOTS> kernel_chain;
1151 const int slot_total = kleidiai_collect_kernel_chain(dst, kernel_chain);
1152
1153 auto weight_for_slot = [&](int slot_index, size_t & size_out) -> const uint8_t * {
1154 if (slot_index < 0 || slot_index >= slot_total) {
1155 return nullptr;
1156 }
1157 if (has_header) {
1158 if (slot_index < header->slot_count) {
1159 size_out = static_cast<size_t>(header->sizes[slot_index]);
1160 return kleidiai_weight_slot_ptr(header, slot_index);
1161 }
1162 return nullptr;
1163 }
1164 if (slot_index == 0) {
1165 size_out = ggml_nbytes(src0);
1166 return static_cast<const uint8_t *>(src0->data);
1167 }
1168 return nullptr;
1169 };
1170
1171 struct runtime_slot {
1172 int slot_index;
1173 ggml_kleidiai_kernels * kernels;
1174 kernel_info * kernel;
1175 lhs_packing_info * lhs_info;
1176 size_t mr;
1177 size_t nr;
1178 size_t kr;
1179 size_t sr;
1180 size_t n_step;
1181 size_t lhs_packed_size;
1182 size_t lhs_offset;
1183 size_t lhs_bl;
1184 size_t rhs_bl;
1185 size_t pack_bl;
1186 size_t lhs_packed_offset0;
1187 int assigned_threads;
1188 int thread_begin;
1189 int thread_end;
1190 const uint8_t * rhs_base;
1191 };
1192
1193 std::array<runtime_slot, GGML_KLEIDIAI_MAX_KERNEL_SLOTS> runtime{};
1194 int runtime_count = 0;
1195
1196 for (int slot = 0; slot < slot_total && runtime_count < GGML_KLEIDIAI_MAX_KERNEL_SLOTS; ++slot) {
1197 ggml_kleidiai_kernels * kernels = kernel_chain[slot];
1198 kernel_info * kinfo = is_gemv ? &kernels->gemv : &kernels->gemm;
1199 lhs_packing_info * linfo = is_gemv ? &kernels->gemv_lhs_info : &kernels->gemm_lhs_info;
1200 if (!kinfo || !linfo || !linfo->packed_size_ex || !linfo->pack_func_ex || !linfo->get_offset ||
1201 !kinfo->get_rhs_packed_offset_ex || !kinfo->run_kernel_ex || !kinfo->get_dst_offset) {
1202 continue;
1203 }
1204
1205 size_t rhs_size = 0;
1206 const uint8_t * rhs_ptr = weight_for_slot(slot, rhs_size);
1207 if (!rhs_ptr || rhs_size == 0) {
1208 continue;
1209 }
1210
1211 const kleidiai_block_args block_args = kleidiai_get_block_args(kernels->rhs_type);
1212
1213 runtime[runtime_count] = {
1214 slot,
1215 kernels,
1216 kinfo,
1217 linfo,
1218 kinfo->get_mr(),
1219 kinfo->get_nr(),
1220 kinfo->get_kr(),
1221 kinfo->get_sr(),
1222 kinfo->get_n_step(),
1223 0,
1224 0,
1225 block_args.lhs_bl,
1226 block_args.rhs_bl,
1227 block_args.pack_bl,
1228 0,
1229 0,
1230 0,
1231 0,
1232 rhs_ptr
1233 };
1234 ++runtime_count;
1235 }
1236
1237 if (runtime_count == 0) {
1238 GGML_LOG_WARN("kleidiai: no runtime kernel slot available for supported op %s\n", dst->name);
1239 return false;
1240 }
1241
1242 const int nth_total = params->nth > 0 ? params->nth : 1;
1243 const int ith_total = params->ith;
1244
1245 int sme_slot = -1;
1246 int non_sme_slot = -1;
1247 for (int i = 0; i < runtime_count; ++i) {
1248 if (is_sme_family(runtime[i].kernels->required_cpu)) {
1249 sme_slot = i;
1250 break;
1251 }
1252 }
1253
1254 for (int i = 0; i < runtime_count; ++i) {
1255 if (!is_sme_family(runtime[i].kernels->required_cpu)) {
1256 non_sme_slot = i;
1257 break;
1258 }
1259 }
1260
1261 const int sme_cap_limit = ctx.sme_thread_cap;
1262 const bool use_hybrid = sme_cap_limit > 0 &&
1263 runtime_count > 1 &&
1264 nth_total > sme_cap_limit;
1265 // Heuristic: disable hybrid for very small workloads where per-slot overhead dominates.
1266 // If rows are small or average columns per thread are small, keep single-slot.
1267 size_t min_cols_per_thread = 0;
1268 if (runtime_count > 0 && nth_total > 0) {
1269 min_cols_per_thread = (size_t) std::max<int64_t>(1, (int64_t)ne01 / (int64_t)nth_total);
1270 }
1271 const bool too_small_for_hybrid = (min_cols_per_thread < 2) || (ne11 < 128);
1272
1273 const bool hybrid_enabled = use_hybrid && !too_small_for_hybrid;
1274
1275 if (!hybrid_enabled) {
1276 int chosen_slot = 0;
1277 if (too_small_for_hybrid && sme_slot != -1) {
1278 chosen_slot = nth_total > sme_cap_limit && non_sme_slot != -1 ? non_sme_slot : sme_slot;
1279 } else if (runtime_count > 1 && ctx.sme_thread_cap > 0 && nth_total > ctx.sme_thread_cap) {
1280 chosen_slot = 1;
1281 }
1282 if (chosen_slot != 0 && chosen_slot < runtime_count) {
1283 runtime[0] = runtime[chosen_slot];
1284 runtime[0].assigned_threads = 0;
1285 runtime[0].thread_begin = 0;
1286 runtime[0].thread_end = 0;
1287 }
1288 runtime_count = runtime_count > 0 ? 1 : 0;
1289
1290 // Recompute SME slot based on the collapsed runtime[0]
1291 sme_slot = -1;
1292 if (runtime_count > 0 &&
1293 is_sme_family(runtime[0].kernels->required_cpu)) {
1294 sme_slot = 0;
1295 }
1296 }
1297
1298 const bool sme_single_only = sme_slot != -1 &&
1299 runtime[sme_slot].kernels->rhs_info.repack_mode == RHS_REPACK_SINGLE_ONLY;
1300 int sme_cap = sme_single_only ? nth_total : kleidiai_sme_thread_cap();
1301 if (sme_cap < 0) {
1302 sme_cap = nth_total;
1303 }
1304 sme_cap = std::min(sme_cap, nth_total);
1305
1306 int threads_remaining = nth_total;
1307 if (sme_slot != -1) {
1308 int sme_threads = std::min(std::max(sme_cap, 0), threads_remaining);
1309 runtime[sme_slot].assigned_threads = sme_threads;
1310 threads_remaining -= sme_threads;
1311 }
1312
1313 int fallback_indices[GGML_KLEIDIAI_MAX_KERNEL_SLOTS];
1314 int fallback_count = 0;
1315 // The current hybrid chain is bounded to SME + one non-SME fallback slot.
1316 GGML_ASSERT(GGML_KLEIDIAI_MAX_KERNEL_SLOTS == 2);
1317 for (int i = 0; i < runtime_count; ++i) {
1318 if (i == sme_slot) {
1319 continue;
1320 }
1321 fallback_indices[fallback_count++] = i;
1322 }
1323
1324 for (int fi = 0; fi < fallback_count; ++fi) {
1325 if (threads_remaining <= 0) {
1326 break;
1327 }
1328 const int slot_index = fallback_indices[fi];
1329 const int slots_left = fallback_count - fi;
1330 int share = (threads_remaining + slots_left - 1) / slots_left;
1331 share = std::min(share, threads_remaining);
1332 runtime[slot_index].assigned_threads = share;
1333 threads_remaining -= share;
1334 }
1335
1336 int thread_cursor = 0;
1337 for (int i = 0; i < runtime_count; ++i) {
1338 runtime[i].thread_begin = thread_cursor;
1339 thread_cursor += runtime[i].assigned_threads;
1340 runtime[i].thread_end = thread_cursor;
1341 }
1342 GGML_ASSERT(thread_cursor > 0);
1343 const int active_threads = thread_cursor;
1344
1345 int local_slot = -1;
1346 int local_ith = 0;
1347 for (int i = 0; i < runtime_count; ++i) {
1348 if (ith_total >= runtime[i].thread_begin && ith_total < runtime[i].thread_end) {
1349 local_slot = i;
1350 local_ith = ith_total - runtime[i].thread_begin;
1351 break;
1352 }
1353 }
1354 const size_t k = ne00;
1355 const size_t m = ne11;
1356 const size_t n = ne01;
1357
1358 size_t cursor = 0;
1359 for (int i = 0; i < runtime_count; ++i) {
1360 runtime[i].lhs_packed_size = runtime[i].lhs_info->packed_size_ex(m, k, runtime[i].pack_bl, runtime[i].mr, runtime[i].kr, runtime[i].sr);
1361 cursor = align_up(cursor, GGML_KLEIDIAI_PACK_ALIGN);
1362 runtime[i].lhs_offset = cursor;
1363 runtime[i].lhs_packed_offset0 = runtime[i].lhs_info->get_packed_offset_ex(0, k, runtime[i].lhs_bl, runtime[i].mr, runtime[i].kr, runtime[i].sr);
1364 cursor += runtime[i].lhs_packed_size;
1365 }
1366
1367 GGML_ASSERT(cursor <= params->wsize);
1368 uint8_t * scratch = static_cast<uint8_t *>(params->wdata);
1369
1370 size_t common_step = 1;
1371 for (int i = 0; i < runtime_count; ++i) {
1372 if (runtime[i].assigned_threads == 0) {
1373 continue;
1374 }
1375 size_t next_step = 0;
1376 if (!lcm_size(common_step, runtime[i].n_step ? runtime[i].n_step : 1, next_step)) {
1377 return false;
1378 }
1379 common_step = next_step;
1380 }
1381 GGML_ASSERT(common_step > 0);
1382
1383 const bool disable_chunking = ggml_is_numa();
1384 const size_t chunk_multiplier = std::max(1, ctx.chunk_multiplier);
1385 const size_t chunk_divisor = (active_threads == 1 || disable_chunking) ? (size_t) active_threads : (size_t) active_threads * chunk_multiplier;
1386 size_t chunk_cols = align_up(std::max<size_t>(1, ceil_div_size(n, chunk_divisor)), common_step);
1387 if (chunk_cols == 0) {
1388 chunk_cols = common_step;
1389 }
1390 // If common_step is larger than n, the loop below runs one valid tail chunk
1391 // with cols == n.
1392 const size_t nchunk_size = std::max<size_t>(1, ceil_div_size(n, chunk_cols));
1393 GGML_ASSERT(nchunk_size <= (size_t)INT_MAX);
1394 const int nchunk = (int)nchunk_size;
1395 const size_t dst_stride = dst->nb[1];
1396
1397 auto run_chunk = [&](runtime_slot & slot, size_t global_start, size_t cols, uint8_t * dst_batch_base) {
1398 const size_t rhs_packed_offset = slot.kernel->get_rhs_packed_offset_ex(global_start, k, slot.rhs_bl);
1399 const size_t dst_offset = slot.kernel->get_dst_offset(0, global_start, dst_stride);
1400
1401 const uint8_t * lhs_ptr = scratch + slot.lhs_offset + slot.lhs_packed_offset0;
1402 const uint8_t * rhs_ptr = slot.rhs_base + rhs_packed_offset;
1403 float * dst_ptr = reinterpret_cast<float *>(dst_batch_base + dst_offset);
1404
1405 slot.kernel->run_kernel_ex(m, cols, k, slot.rhs_bl,
1406 lhs_ptr,
1407 rhs_ptr,
1408 dst_ptr,
1409 dst_stride,
1410 sizeof(float),
1411 -FLT_MAX,
1412 FLT_MAX);
1413 };
1414
1415 for (int64_t batch_idx = 0; batch_idx < ne12; ++batch_idx) {
1416 const uint8_t * lhs_batch_base = static_cast<const uint8_t *>(src1->data) + batch_idx * src1->nb[2];
1417 uint8_t * dst_batch_base = static_cast<uint8_t *>(dst->data) + batch_idx * dst->nb[2];
1418
1419 if (local_slot != -1) {
1420 runtime_slot & slot = runtime[local_slot];
1421 const int64_t m_roundup_mr = kai_roundup((int64_t)m, (int64_t)slot.mr);
1422 int64_t max_threads = slot.mr ? (m_roundup_mr / (int64_t)slot.mr) : slot.assigned_threads;
1423 max_threads = std::max<int64_t>(1, max_threads);
1424 const int64_t use_threads = std::min<int64_t>(slot.assigned_threads, max_threads);
1425
1426 if (local_ith < use_threads) {
1427 const int64_t num_m_per_thread0 = round_down((size_t)(m_roundup_mr / use_threads), slot.mr);
1428 const int64_t num_m_per_threadN_1 = (int64_t)m - (use_threads - 1) * num_m_per_thread0;
1429
1430 const int64_t m_start = (int64_t)local_ith * num_m_per_thread0;
1431 const int64_t m_count = (local_ith == use_threads - 1) ? num_m_per_threadN_1 : num_m_per_thread0;
1432
1433 const size_t base_packed_off = slot.lhs_info->get_packed_offset_ex(m_start, k, slot.lhs_bl, slot.mr, slot.kr, slot.sr);
1434 const size_t next_block_off = slot.lhs_info->get_packed_offset_ex(m_start + slot.mr, k, slot.lhs_bl, slot.mr, slot.kr, slot.sr);
1435 const size_t row_stride_bytes = slot.mr ? (next_block_off - base_packed_off) / slot.mr : 0;
1436
1437 int64_t remaining = m_count;
1438 int64_t cur = m_start;
1439
1440 uint8_t * lhs_packed = scratch + slot.lhs_offset;
1441 while (remaining > 0) {
1442 const int64_t row_in_group = cur;
1443 const int64_t avail = (int64_t)m - row_in_group;
1444 const int64_t take = std::min(avail, remaining);
1445
1446 const size_t src_off = slot.lhs_info->get_offset(row_in_group, src1->nb[1]);
1447 const void * src_ptr = lhs_batch_base + src_off;
1448 const size_t dst_off = base_packed_off + (size_t)(cur - m_start) * row_stride_bytes;
1449 void * dst_ptr = lhs_packed + dst_off;
1450
1451 slot.lhs_info->pack_func_ex(take, k, slot.lhs_bl, slot.mr, slot.kr, slot.sr, 0, src_ptr, src1->nb[1], dst_ptr);
1452
1453 cur += take;
1454 remaining -= take;
1455 }
1456 }
1457 }
1458
1459 if (ith_total == 0) {
1460 ggml_threadpool_chunk_set(params->threadpool, active_threads);
1461 }
1462
1463 // Publishes both LHS packing and the initialized dynamic chunk queue.
1464 ggml_barrier(params->threadpool);
1465
1466 if (local_slot != -1) {
1467 runtime_slot & slot = runtime[local_slot];
1468 int current_chunk = ith_total;
1469 while (current_chunk < nchunk) {
1470 const size_t global_start = (size_t)current_chunk * chunk_cols;
1471 if (global_start >= n) {
1472 break;
1473 }
1474
1475 const size_t cols = std::min(chunk_cols, n - global_start);
1476 if (cols > 0) {
1477 // KleidiAI GEMM/GEMV kernels accept arbitrary final tail widths;
1478 // only non-tail chunks are guaranteed to be n_step-aligned.
1479 run_chunk(slot, global_start, cols, dst_batch_base);
1480 }
1481
1482 current_chunk = ggml_threadpool_chunk_add(params->threadpool, 1);
1483 }
1484 }
1485
1486 if (batch_idx != ne12 - 1) {
1487 ggml_barrier(params->threadpool);
1488 }
1489 }
1490
1491 return true;
1492 }
1493
1494public:
1495 int repack(struct ggml_tensor * tensor, const void * data, size_t data_size) {
1496 GGML_ASSERT(tensor->type == GGML_TYPE_Q4_0 || tensor->type == GGML_TYPE_Q4_K ||
1497 tensor->type == GGML_TYPE_Q8_0 || tensor->type == GGML_TYPE_Q6_K ||
1498 tensor->type == GGML_TYPE_F32);
1499 const size_t n = tensor->ne[1];
1500 const size_t k = tensor->ne[0];
1501
1502 kleidiai_weight_header * header = kleidiai_weight_header_from_ptr(tensor->data);
1503 if (!header) {
1504 return -1;
1505 }
1506
1507 header->magic = GGML_KLEIDIAI_PACK_MAGIC;
1508 header->version = GGML_KLEIDIAI_PACK_VERSION;
1509 header->slot_count = 0;
1510
1511 uint8_t * base_ptr = static_cast<uint8_t *>(tensor->data);
1512 size_t cursor = sizeof(kleidiai_weight_header);
1513 cursor = align_up(cursor, GGML_KLEIDIAI_PACK_ALIGN);
1514
1515 std::array<ggml_kleidiai_kernels *, GGML_KLEIDIAI_MAX_KERNEL_SLOTS> kernel_chain;
1516 const bool want_q4k = tensor->type == GGML_TYPE_Q4_K;
1517 const bool want_q8 = tensor->type == GGML_TYPE_Q8_0 || tensor->type == GGML_TYPE_Q6_K;
1518 const bool want_f32 = tensor->type == GGML_TYPE_F32;
1519 const int slot_total = want_f32 ? kleidiai_collect_f32_chain(kernel_chain)
1520 : want_q8 ? kleidiai_collect_q8_chain(kernel_chain)
1521 : want_q4k ? kleidiai_collect_q4k_chain(kernel_chain)
1522 : kleidiai_collect_q4_chain(kernel_chain);
1523 const bool allow_fallback = kleidiai_pack_fallback_allowed();
1524
1525 std::vector<int8_t> qdata;
1526 std::vector<float> scales;
1527 std::vector<float> bias;
1528 std::vector<float> row_f32;
1529
1530 if (want_q8 && slot_total > 0) {
1531 qdata.resize(n * k, 0);
1532 scales.resize(n, 0.0f);
1533
1534 const size_t row_stride = tensor->nb[1];
1535 const size_t k_blocks = (k + QK8_0 - 1) / QK8_0;
1536
1537 if (tensor->type == GGML_TYPE_Q6_K) {
1538 if (k % QK_K != 0 || k % QK8_0 != 0) {
1539 return -1;
1540 }
1541 row_f32.resize(k);
1542 }
1543
1544 for (size_t row = 0; row < n; ++row) {
1545 const uint8_t * row_data = static_cast<const uint8_t *>(data) + row * row_stride;
1546
1547 if (tensor->type == GGML_TYPE_Q6_K) {
1548 dequantize_row_q6_K(reinterpret_cast<const block_q6_K *>(row_data), row_f32.data(), k);
1549 }
1550
1551 float max_abs = 0.0f;
1552 if (tensor->type == GGML_TYPE_Q6_K) {
1553 for (size_t linear_idx = 0; linear_idx < k; ++linear_idx) {
1554 max_abs = std::max(max_abs, std::fabs(row_f32[linear_idx]));
1555 }
1556 } else {
1557 const block_q8_0 * row_blocks = reinterpret_cast<const block_q8_0 *>(row_data);
1558 for (size_t block = 0; block < k_blocks; ++block) {
1559 const block_q8_0 & blk = row_blocks[block];
1560 const float d = GGML_FP16_TO_FP32(blk.d);
1561 for (size_t l = 0; l < QK8_0; ++l) {
1562 const size_t linear_idx = block * QK8_0 + l;
1563 if (linear_idx >= k) {
1564 break;
1565 }
1566 const float value = d * static_cast<float>(blk.qs[l]);
1567 max_abs = std::max(max_abs, std::fabs(value));
1568 }
1569 }
1570 }
1571
1572 float scale = max_abs > 0.0f ? max_abs / 127.0f : 0.0f;
1573 scales[row] = scale;
1574 const float inv_scale = scale > 0.0f ? 1.0f / scale : 0.0f;
1575
1576 if (tensor->type == GGML_TYPE_Q6_K) {
1577 for (size_t linear_idx = 0; linear_idx < k; ++linear_idx) {
1578 int32_t q = scale > 0.0f ? static_cast<int32_t>(std::lround(row_f32[linear_idx] * inv_scale)) : 0;
1579 q = std::clamp(q, -127, 127);
1580 qdata[row * k + linear_idx] = static_cast<int8_t>(q);
1581 }
1582 } else {
1583 const block_q8_0 * row_blocks = reinterpret_cast<const block_q8_0 *>(row_data);
1584 for (size_t block = 0; block < k_blocks; ++block) {
1585 const block_q8_0 & blk = row_blocks[block];
1586 const float d = GGML_FP16_TO_FP32(blk.d);
1587 for (size_t l = 0; l < QK8_0; ++l) {
1588 const size_t linear_idx = block * QK8_0 + l;
1589 if (linear_idx >= k) {
1590 break;
1591 }
1592 const float value = d * static_cast<float>(blk.qs[l]);
1593 int32_t q = scale > 0.0f ? static_cast<int32_t>(std::lround(value * inv_scale)) : 0;
1594 q = std::clamp(q, -127, 127);
1595 qdata[row * k + linear_idx] = static_cast<int8_t>(q);
1596 }
1597 }
1598 }
1599 }
1600 }
1601
1602 if (want_f32 && slot_total > 0) {
1603 bias.resize(n, 0.0f);
1604 }
1605
1606 for (int slot = 0; slot < slot_total && slot < GGML_KLEIDIAI_MAX_KERNEL_SLOTS; ++slot) {
1607 if (!allow_fallback && slot > 0) {
1608 break;
1609 }
1610 ggml_kleidiai_kernels * kernels = kernel_chain[slot];
1611 kernel_info * kernel = &kernels->gemm;
1612 rhs_packing_info * rhs_info = &kernels->rhs_info;
1613 if (!rhs_info || !rhs_info->pack_func_ex || !rhs_info->packed_size_ex || !kernel) {
1614 continue;
1615 }
1616
1617 const size_t nr = kernel->get_nr();
1618 const size_t kr = kernel->get_kr();
1619 const size_t sr = kernel->get_sr();
1620 const ggml_type rhs_type = kernels->rhs_type;
1621 if (rhs_type == GGML_TYPE_Q8_0 && (kernels->required_cpu & CPU_FEATURE_SVE)) {
1622 GGML_ASSERT(nr == kernels->gemv.get_nr());
1623 GGML_ASSERT(kr == kernels->gemv.get_kr());
1624 GGML_ASSERT(sr == kernels->gemv.get_sr());
1625 }
1626 const size_t block_len = rhs_type == GGML_TYPE_Q8_0 ? QK8_0 :
1627 rhs_type == GGML_TYPE_Q4_0 ? QK4_0 :
1628 rhs_type == GGML_TYPE_Q4_K ? GGML_KLEIDIAI_Q4_K_BL :
1629 rhs_type == GGML_TYPE_F32 ? 0 : SIZE_MAX;
1630 if (block_len == SIZE_MAX) {
1631 continue;
1632 }
1633
1634 const size_t packed_size = rhs_info->packed_size_ex(n, k, nr, kr, block_len);
1635 const size_t aligned_cursor = align_up(cursor, GGML_KLEIDIAI_PACK_ALIGN);
1636
1637 uint8_t * dst_ptr = base_ptr + aligned_cursor;
1638
1639 if (rhs_type == GGML_TYPE_Q4_0) {
1640 struct kai_rhs_pack_qs4cxs1s0_param params;
1641 params.lhs_zero_point = 1;
1642 params.rhs_zero_point = 8;
1643 rhs_info->pack_func_ex(1, n, k, nr, kr, sr, QK4_0, 0,
1644 static_cast<const uint8_t *>(data), nullptr, nullptr,
1645 dst_ptr, 0, &params);
1646 } else if (rhs_type == GGML_TYPE_Q4_K) {
1647 rhs_info->pack_func_ex(1, n, k, nr, kr, sr, GGML_KLEIDIAI_Q4_K_BL, tensor->nb[1],
1648 data, nullptr, nullptr, dst_ptr, 0, nullptr);
1649 } else if (rhs_type == GGML_TYPE_Q8_0) {
1650 struct kai_rhs_pack_qsi8cx_params params;
1651 params.lhs_zero_point = 1;
1652 params.scale_multiplier = 1.0f;
1653 rhs_info->pack_func_ex(1, n, k, nr, kr, sr, 0, 0,
1654 qdata.data(), nullptr, scales.data(),
1655 dst_ptr, 0, &params);
1656 } else if (rhs_type == GGML_TYPE_F32) {
1657 rhs_info->pack_func_ex(1, n, k, nr, kr, sr, 0, tensor->nb[1],
1658 data, bias.data(), nullptr,
1659 dst_ptr, 0, nullptr);
1660 } else {
1661 continue;
1662 }
1663
1664 header->offsets[header->slot_count] = aligned_cursor;
1665 header->sizes[header->slot_count] = packed_size;
1666 ++header->slot_count;
1667
1668 cursor = aligned_cursor + packed_size;
1669 }
1670
1671 if (header->slot_count == 0) {
1672 header->magic = 0;
1673 header->version = 0;
1674 memcpy(tensor->data, data, data_size);
1675 }
1676
1677 return 0;
1678 }
1679};
1680
1681static ggml::cpu::tensor_traits * get_tensor_traits(ggml_backend_buffer_t, struct ggml_tensor *) {
1682 static tensor_traits traits;
1683 return &traits;
1684}
1685} // namespace ggml::cpu::kleidiai
1686
1687static enum ggml_status ggml_backend_cpu_kleidiai_buffer_init_tensor(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor) {
1688 tensor->extra = (void *) ggml::cpu::kleidiai::get_tensor_traits(buffer, tensor);
1689
1690 return GGML_STATUS_SUCCESS;
1691}
1692
1693static void ggml_backend_cpu_kleidiai_buffer_set_tensor(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor,
1694 const void * data, size_t offset, size_t size) {
1695 GGML_ASSERT(offset == 0);
1696 GGML_ASSERT(size == ggml_nbytes(tensor));
1697
1698 auto tensor_traits = (ggml::cpu::kleidiai::tensor_traits *) tensor->extra;
1699 auto OK = tensor_traits->repack(tensor, data, size);
1700
1701 GGML_ASSERT(OK == 0);
1702 GGML_UNUSED(buffer);
1703}
1704
1705static const char * ggml_backend_cpu_kleidiai_buffer_type_get_name(ggml_backend_buffer_type_t buft) {
1706 GGML_UNUSED(buft);
1707 return "CPU_KLEIDIAI";
1708}
1709
1710static ggml_backend_buffer_t ggml_backend_cpu_kleidiai_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
1711 ggml_backend_buffer_t buffer = ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
1712
1713 if (buffer == nullptr) {
1714 return nullptr;
1715 }
1716
1717 buffer->buft = buft;
1718 buffer->iface.init_tensor = ggml_backend_cpu_kleidiai_buffer_init_tensor;
1719 buffer->iface.set_tensor = ggml_backend_cpu_kleidiai_buffer_set_tensor;
1720 buffer->iface.get_tensor = nullptr;
1721 buffer->iface.cpy_tensor = nullptr;
1722 return buffer;
1723}
1724
1725static size_t ggml_backend_cpu_kleidiai_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
1726 GGML_UNUSED(buft);
1727 return TENSOR_ALIGNMENT;
1728}
1729
1730static size_t ggml_backend_cpu_kleidiai_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const struct ggml_tensor * tensor) {
1731 GGML_UNUSED(buft);
1732
1733 if (tensor->type != GGML_TYPE_Q4_0 && tensor->type != GGML_TYPE_Q4_K &&
1734 tensor->type != GGML_TYPE_Q8_0 && tensor->type != GGML_TYPE_Q6_K &&
1735 tensor->type != GGML_TYPE_F32) {
1736 return ggml_nbytes(tensor);
1737 }
1738
1739 const size_t n = tensor->ne[1];
1740 const size_t k = tensor->ne[0];
1741
1742 size_t cursor = sizeof(kleidiai_weight_header);
1743 cursor = align_up(cursor, GGML_KLEIDIAI_PACK_ALIGN);
1744
1745 std::array<ggml_kleidiai_kernels *, GGML_KLEIDIAI_MAX_KERNEL_SLOTS> kernel_chain;
1746 const bool want_q4k = tensor->type == GGML_TYPE_Q4_K;
1747 const bool want_q8 = tensor->type == GGML_TYPE_Q8_0 || tensor->type == GGML_TYPE_Q6_K;
1748 const bool want_f32 = tensor->type == GGML_TYPE_F32;
1749 const int slot_total = want_f32 ? kleidiai_collect_f32_chain(kernel_chain)
1750 : want_q8 ? kleidiai_collect_q8_chain(kernel_chain)
1751 : want_q4k ? kleidiai_collect_q4k_chain(kernel_chain)
1752 : kleidiai_collect_q4_chain(kernel_chain);
1753 const bool allow_fallback = kleidiai_pack_fallback_allowed();
1754
1755 size_t slot_count = 0;
1756 for (int slot = 0; slot < slot_total; ++slot) {
1757 if (!allow_fallback && slot > 0) {
1758 break;
1759 }
1760 ggml_kleidiai_kernels * kernels = kernel_chain[slot];
1761 if (!kernels) {
1762 continue;
1763 }
1764 kernel_info * kernel = &kernels->gemm;
1765 rhs_packing_info * rhs_info = &kernels->rhs_info;
1766 if (!kernel || !rhs_info || !rhs_info->packed_size_ex) {
1767 continue;
1768 }
1769
1770 const ggml_type rhs_type = kernels->rhs_type;
1771 const size_t block_len = rhs_type == GGML_TYPE_Q4_0 ? QK4_0 :
1772 rhs_type == GGML_TYPE_Q4_K ? GGML_KLEIDIAI_Q4_K_BL :
1773 rhs_type == GGML_TYPE_Q8_0 ? QK8_0 :
1774 rhs_type == GGML_TYPE_F32 ? 0 : SIZE_MAX;
1775 if (block_len == SIZE_MAX) {
1776 continue;
1777 }
1778
1779 cursor = align_up(cursor, GGML_KLEIDIAI_PACK_ALIGN);
1780 cursor += rhs_info->packed_size_ex(n, k, kernel->get_nr(), kernel->get_kr(), block_len);
1781 ++slot_count;
1782 }
1783
1784 if (slot_count == 0) {
1785 return ggml_nbytes(tensor);
1786 }
1787
1788 return std::max(cursor, ggml_nbytes(tensor));
1789}
1790
1791namespace ggml::cpu::kleidiai {
1792class extra_buffer_type : ggml::cpu::extra_buffer_type {
1793 bool supports_op(ggml_backend_dev_t, const struct ggml_tensor * op) override {
1794 // GET_ROWS needs the original weights in a native buffer.
1795 if (op->op != GGML_OP_MUL_MAT) {
1796 return false;
1797 }
1798
1799 std::array<ggml_kleidiai_kernels *, GGML_KLEIDIAI_MAX_KERNEL_SLOTS> kernel_chain;
1800 const int slot_total = kleidiai_collect_kernel_chain(op, kernel_chain);
1801 const bool src0_is_kleidiai =
1802 op->src[0]->buffer &&
1803 (ggml_n_dims(op->src[0]) == 2) &&
1804 op->src[0]->buffer->buft->context == this &&
1805 slot_total > 0;
1806
1807 if ((op->src[0]->type == GGML_TYPE_Q4_0 || op->src[0]->type == GGML_TYPE_Q4_K ||
1808 op->src[0]->type == GGML_TYPE_Q8_0 || op->src[0]->type == GGML_TYPE_Q6_K ||
1809 op->src[0]->type == GGML_TYPE_F32) &&
1810 src0_is_kleidiai) {
1811 if (op->src[0]->type == GGML_TYPE_Q4_0 && ctx.kernels_q4 == nullptr) {
1812 return false;
1813 }
1814 if (op->src[0]->type == GGML_TYPE_Q8_0 && ctx.kernels_q8 == nullptr) {
1815 return false;
1816 }
1817 if (op->src[0]->type == GGML_TYPE_Q6_K && ctx.kernels_q8 == nullptr) {
1818 return false;
1819 }
1820 if (op->src[0]->type == GGML_TYPE_Q4_K && ctx.kernels_q4k == nullptr) {
1821 return false;
1822 }
1823 if (op->src[0]->type == GGML_TYPE_F32 && ctx.kernels_f32 == nullptr) {
1824 return false;
1825 }
1826 if (op->src[1]->buffer && !ggml_backend_buft_is_host(op->src[1]->buffer->buft)) {
1827 return false;
1828 }
1829
1830 if (op->src[0]->type == GGML_TYPE_Q4_K) {
1831 if (op->op != GGML_OP_MUL_MAT || op->src[1]->type != GGML_TYPE_F32 || op->type != GGML_TYPE_F32) {
1832 return false;
1833 }
1834 return ggml_ne(op->src[1], 2) == 1 && ggml_ne(op->src[1], 3) == 1 &&
1835 op->src[1]->nb[0] == sizeof(float) &&
1836 (op->src[1]->ne[1] == 1 || op->src[1]->nb[1] == op->src[1]->ne[0] * sizeof(float));
1837 }
1838
1839 if (op->src[0]->type == GGML_TYPE_Q4_0 || op->src[0]->type == GGML_TYPE_Q8_0 ||
1840 op->src[0]->type == GGML_TYPE_Q6_K) {
1841 if (op->src[1]->type == GGML_TYPE_F32 &&
1842 ggml_ne(op->src[1], 3) == 1) {
1843 return true;
1844 }
1845 return false;
1846 }
1847
1848 if (op->op != GGML_OP_MUL_MAT || op->src[1]->type != GGML_TYPE_F32 || op->type != GGML_TYPE_F32) {
1849 return false;
1850 }
1851
1852 return true;
1853 }
1854
1855 return false;
1856 }
1857
1858 ggml::cpu::tensor_traits * get_tensor_traits(const struct ggml_tensor * op) override {
1859 if (op->op == GGML_OP_MUL_MAT) {
1860 if (op->src[0]->buffer && op->src[0]->buffer->buft->context == this) {
1861 return (ggml::cpu::tensor_traits *) op->src[0]->extra;
1862 } else {
1863 // KleidiAI only has kernels for Q4_0, Q4_K, Q8_0 and Q6_K. For a quantized weight of any
1864 // other type (K-quants, IQ) it declines the op and returns nullptr below, so
1865 // KleidiAI does not accelerate it. Another CPU backend may still take the op,
1866 // and this can run during graph planning, so the message says what KleidiAI
1867 // did rather than what ends up executing. Warn once per process.
1868 if (ggml_is_quantized(op->src[0]->type) &&
1869 op->src[0]->type != GGML_TYPE_Q4_0 && op->src[0]->type != GGML_TYPE_Q4_K &&
1870 op->src[0]->type != GGML_TYPE_Q8_0 && op->src[0]->type != GGML_TYPE_Q6_K) {
1871 static std::atomic<bool> warned(false);
1872 if (!warned.exchange(true)) {
1873 GGML_LOG_WARN("kleidiai: no kernel for tensor type %s, not accelerated by KleidiAI "
1874 "(kernels available for Q4_0, Q4_K, Q8_0 and Q6_K)\n",
1875 ggml_type_name(op->src[0]->type));
1876 }
1877 }
1878 if (op->src[0]->type != GGML_TYPE_F16) {
1879 return nullptr;
1880 }
1881 std::array<ggml_kleidiai_kernels *, GGML_KLEIDIAI_MAX_KERNEL_SLOTS> kernel_chain;
1882 const int slot_total = kleidiai_collect_kernel_chain(op, kernel_chain);
1883 if (slot_total > 0 && op->src[1]->ne[1] > 1) {
1884 if ((op->src[0]->nb[1] * op->src[0]->ne[1] != op->src[0]->nb[2]) ||
1885 (op->src[1]->nb[1] * op->src[1]->ne[1] != op->src[1]->nb[2])) {
1886 return nullptr;
1887 }
1888 return ggml::cpu::kleidiai::get_tensor_traits(NULL, NULL);
1889 }
1890 }
1891 }
1892 return nullptr;
1893 }
1894};
1895} // namespace ggml::cpu::kleidiai
1896
1897ggml_backend_buffer_type_t ggml_backend_cpu_kleidiai_buffer_type(void) {
1898 static ggml::cpu::kleidiai::extra_buffer_type ctx;
1899 static struct ggml_backend_buffer_type ggml_backend_cpu_buffer_type_kleidiai = {
1900 /* .iface = */ {
1901 /* .get_name = */ ggml_backend_cpu_kleidiai_buffer_type_get_name,
1902 /* .alloc_buffer = */ ggml_backend_cpu_kleidiai_buffer_type_alloc_buffer,
1903 /* .alloc_buffer_n = */ nullptr,
1904 /* .get_alignment = */ ggml_backend_cpu_kleidiai_buffer_type_get_alignment,
1905 /* .get_max_size = */ nullptr, // defaults to SIZE_MAX
1906 /* .get_alloc_size = */ ggml_backend_cpu_kleidiai_buffer_type_get_alloc_size,
1907 /* .get_alloc_size_n = */ NULL,
1908 /* .is_host = */ nullptr,
1909 },
1910 /* .device = */ ggml_backend_reg_dev_get(ggml_backend_cpu_reg(), 0),
1911 /* .context = */ &ctx,
1912 };
1913
1914 init_kleidiai_context();
1915
1916 return &ggml_backend_cpu_buffer_type_kleidiai;
1917}