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-hexagon / ggml-hexagon.cpp

3748 lines · 147639 bytes Raw Blame History
1#define _USE_MATH_DEFINES
2
3#include <assert.h>
4#include <inttypes.h>
5#include <stdio.h>
6#include <stdlib.h>
7#include <string.h>
8#include <time.h>
9
10#include <atomic>
11#include <memory>
12#include <chrono>
13#include <mutex>
14#include <thread>
15#include <cstddef>
16#include <stdexcept>
17#include <string>
18#include <sstream>
19#include <iomanip>
20#include <unordered_set>
21#include <unordered_map>
22#include <regex>
23#include <queue>
24#include <deque>
25#include <algorithm>
26#include <cmath>
27#include <initializer_list>
28
29#ifdef _WIN32
30# define WIN32_LEAN_AND_MEAN
31# ifndef NOMINMAX
32# define NOMINMAX
33# endif
34# include <windows.h>
35# include <sal.h>
36#else
37# include <semaphore.h>
38# include <unistd.h>
39#endif
40
41#pragma clang diagnostic ignored "-Wnested-anon-types"
42#pragma clang diagnostic ignored "-Wlanguage-extension-token"
43#pragma clang diagnostic ignored "-Wgnu-anonymous-struct"
44#pragma clang diagnostic ignored "-Wmicrosoft-enum-value"
45
46#include <AEEStdErr.h>
47#include <dspqueue.h>
48#include <rpcmem.h>
49
50#define GGML_COMMON_IMPL_CPP
51#include "ggml-backend-impl.h"
52#include "ggml-alloc.h"
53#include "ggml-common.h"
54#include "ggml-hexagon.h"
55#include "ggml-impl.h"
56#include "ggml-quants.h"
57#include "htp-opnode.h"
58#include "htp/htp-ops.h"
59#include "htp_iface.h"
60#include "htp-drv.h"
61#include "htp-repack.h"
62#include "htp-common.h"
63#include "htp-kparams.h"
64#include "htp-fusion.h"
65
66using intvec = std::vector<int>;
67using uintvec = std::vector<unsigned int>;
68using u32vec = std::vector<uint32_t>;
69
70#define GGML_HEXAGON_MAX_SESSIONS 16
71
72struct ggml_hexagon_device_config {
73 int physical_idx = 0;
74 int virtual_idx = 0;
75 int domain_id = 0;
76 std::string domain_name;
77 std::string name;
78
79 std::vector<ggml_hexagon_device_config> mdev_group;
80};
81
82static ggml_hexagon_device_config opt_device_configs[GGML_HEXAGON_MAX_SESSIONS];
83
84int opt_arch = 0; // autodetect
85size_t opt_ndev = 1;
86size_t opt_nhvx = 0; // use all
87int opt_nhmx = 1; // when set, enable HMX; when 0, use HVX only
88size_t opt_vtcm_size = 0; // VTCM size override in bytes; 0 = auto-detect
89size_t opt_vmem = HTP_OP_MAX_VMEM_DEFAULT; // max available va space for buffer mappings
90int opt_etm = 0;
91int opt_verbose = 0;
92int opt_profile = 0; // profiling mode (0-disabled, 1-basic, 2-pmu)
93bool opt_hostbuf = false;
94bool opt_dma64 = false;
95int opt_power_mode = HTP_POWER_MODE_BURST; // DCVS/HMX power profile requested at session start
96
97static const std::pair<const char *, int> htp_power_mode_names[] = {
98 { "low_power_saver", HTP_POWER_MODE_LOW_POWER_SAVER },
99 { "power_saver", HTP_POWER_MODE_POWER_SAVER },
100 { "high_power_saver", HTP_POWER_MODE_HIGH_POWER_SAVER },
101 { "low_balanced", HTP_POWER_MODE_LOW_BALANCED },
102 { "balanced", HTP_POWER_MODE_BALANCED },
103 { "high_performance", HTP_POWER_MODE_HIGH_PERFORMANCE },
104 { "sustained_high_performance", HTP_POWER_MODE_SUSTAINED_HIGH_PERFORMANCE },
105 { "burst", HTP_POWER_MODE_BURST },
106 { "default", HTP_POWER_MODE_BURST }, // flip this to change the default mode
107};
108
109static int htp_power_mode_from_str(const char * s) {
110 for (auto & e : htp_power_mode_names) {
111#if defined(_MSC_VER)
112 if (_stricmp(s, e.first) == 0) {
113#else
114 if (strcasecmp(s, e.first) == 0) {
115#endif
116 return e.second;
117 }
118 }
119 return -1;
120}
121
122static const char * htp_power_mode_to_str(int mode) {
123 for (auto & e : htp_power_mode_names) {
124 if (e.second == mode) {
125 return e.first;
126 }
127 }
128 return "unknown";
129}
130
131size_t opt_mbuf_dyn = 512ul * 1024 * 1024; // max dynamic (compute) buffer size
132size_t opt_mbuf_static = 1ul * 1024 * 1024 * 1024; // max static (weight/KV) buffer size
133size_t opt_mbuf_total = 0; // total buffer space limit (0 = unconstrained)
134
135int opt_mm_select = 2; // 2 = HMX -> HVX -> CPU, 1 = HVX -> CPU, 0 = CPU (unsupported)
136int opt_fa_select = 2; // 2 = HMX -> HVX -> CPU, 1 = HVX -> CPU, 0 = CPU (unsupported)
137int opt_fa_split = 1; // 1 = head-split + team-split when n_kv_heads < N_cores (default), 0 = off
138int opt_li_select = 2; // 2 = HMX -> HVX, 1 = HVX, 0 = CPU (unsupported)
139int opt_gdn_select = 2; // 2 = HMX -> HVX, 1 = HVX, 0 = CPU (unsupported)
140int opt_ar_select = 2; // 2 = fused ALLREDUCE+ADD (default), 1 = unfused ALLREDUCE, 0 = fallback to CPY+FENCE
141int opt_ar_scatter = 1; // 1 = reduce-scatter the fused ALLREDUCE+ADD (default), 0 = full reduction
142
143// Default PMU events, if profiling with PMU (mode=2) is enabled
144// See https://docs.qualcomm.com/doc/80-N2040-60/topic/pmu-events.html
145// https://docs.qualcomm.com/doc/80-N2040-61/topic/hvx-pmu-events.html
146static u32vec opt_pmu_evt { 0x3, 0x111, 0x100, 0x105, 0x240, 0x256, 0x7D, 0x8C };
147
148int opt_opbatch = 2048; // max number of ops in a batch
149int opt_opqueue = 8; // max number of pending batches
150int opt_optrace = 0; // trace buffer size per thread (0 means default)
151int opt_oppoll = 0; // polling for batch completions
152int opt_opfusion = 1; // enable/disable op fusion
153int opt_rt_repack = 1; // runtime repacking: 0 = disabled, 1 = quantized only (default), 2 = always
154
155static std::regex* opt_opfilter = NULL; // regex of ops to not claim
156
157static const char * status_to_str(uint32_t status) {
158 switch (status) {
159 case HTP_STATUS_OK:
160 return "OK";
161 case HTP_STATUS_NO_SUPPORT:
162 return "NO-SUPPORT";
163 case HTP_STATUS_INVAL_PARAMS:
164 return "INVAL-PARAMS";
165 case HTP_STATUS_VTCM_TOO_SMALL:
166 return "VTCM-TOO-SMALL";
167 case HTP_STATUS_INTERNAL_ERR:
168 return "INTERNAL-ERROR";
169 default:
170 return "UNKNOWN";
171 }
172}
173
174// ** debug helpers
175
176static void ggml_hexagon_dump_op_exec(const char * sess_name, const htp_opnode & node, const uint32_t req_flags) {
177 if (!opt_verbose) return;
178
179 GGML_LOG_DEBUG("ggml-hex: %s execute-op %s|flags 0x%x\n",
180 sess_name, htp_format_op(node, HTP_OPFMT_EXEC).c_str(), req_flags);
181}
182
183static void ggml_hexagon_dump_op_supp(const char * sess_name, const struct ggml_tensor * op, bool supp) {
184 if (!opt_verbose) return;
185
186 GGML_LOG_DEBUG("ggml-hex: %s supports-op %s|%s\n",
187 sess_name, htp_format_op(op, HTP_OPFMT_SUPP).c_str(), supp ? "yes" : "no");
188}
189
190static const char * htp_event_name(uint16_t id) {
191 switch (id) {
192 case HTP_TRACE_EVT_DMA: return "DMA";
193 case HTP_TRACE_EVT_HVX_COMP: return "HVX_COMP";
194 case HTP_TRACE_EVT_HVX_A_QUANT: return "HVX_A_QUANT";
195 case HTP_TRACE_EVT_HVX_A_PREP: return "HVX_A_PREP";
196 case HTP_TRACE_EVT_HVX_W_DEQUANT: return "HVX_W_DEQUANT";
197 case HTP_TRACE_EVT_HVX_W_PREP: return "HVX_W_PREP";
198 case HTP_TRACE_EVT_HVX_O_PROC: return "HVX_O_PROC";
199 case HTP_TRACE_EVT_HVX_FA_QK: return "HVX_QK_FA";
200 case HTP_TRACE_EVT_HVX_FA_SFM: return "HVX_SFM_FA";
201 case HTP_TRACE_EVT_HVX_FA_Q_PREP: return "HVX_Q_PREP";
202 case HTP_TRACE_EVT_HVX_FA_K_PREP: return "HVX_K_PREP";
203 case HTP_TRACE_EVT_HVX_FA_V_PREP: return "HVX_V_PREP";
204 case HTP_TRACE_EVT_HVX_GDN_PREP: return "HVX_GDN_PREP";
205 case HTP_TRACE_EVT_HVX_GDN_SOLVE: return "HVX_GDN_SOLVE";
206 case HTP_TRACE_EVT_HVX_GDN_V_PREP: return "HVX_GDN_V_PREP";
207 case HTP_TRACE_EVT_HVX_GDN_D_PREP: return "HVX_GDN_D_PREP";
208 case HTP_TRACE_EVT_HVX_GDN_OUT: return "HVX_GDN_OUT";
209 case HTP_TRACE_EVT_HVX_GDN_STATE: return "HVX_GDN_STATE";
210 case HTP_TRACE_EVT_HVX_GDN_REM: return "HVX_GDN_REM";
211 case HTP_TRACE_EVT_HMX_COMP: return "HMX_COMP";
212 case HTP_TRACE_EVT_L2FLUSH: return "L2FLUSH";
213 case HTP_TRACE_EVT_INIT: return "INIT";
214 case HTP_TRACE_EVT_BUFF: return "BUFF";
215 case HTP_TRACE_EVT_FENCE: return "FENCE";
216 default: return "UNKNOWN";
217 }
218}
219
220static void ggml_hexagon_dump_op_prof(const char * sess_name, const htp_opnode & node, const htp_prof_desc & pd) {
221 if (!opt_profile) return;
222
223 uint32_t op_usec = pd.usecs;
224 uint32_t op_cycles = pd.cycles_stop - pd.cycles_start;
225 const uint32_t * pmu = pd.pmu;
226
227 char pmu_str[256] = "";
228 if (opt_profile == 2) {
229 static_assert(HTP_PROF_PMU_NCNT == 8, "current implementation assumes 8 PMU counters");
230 snprintf(pmu_str, sizeof(pmu_str), " pmu [%u,%u,%u,%u,%u,%u,%u,%u]",
231 pmu[0], pmu[1], pmu[2], pmu[3], pmu[4], pmu[5], pmu[6], pmu[7]);
232 }
233
234 float mhz = op_usec > 0 ? (float) op_cycles / op_usec : 0.0f;
235 GGML_LOG_DEBUG("ggml-hex: %s profile-op %s|usec %u cycles %u start %u mhz %.1f%s\n",
236 sess_name, htp_format_op(node, HTP_OPFMT_PROF).c_str(), op_usec, op_cycles, pd.cycles_start, mhz, pmu_str);
237}
238
239static void ggml_hexagon_dump_batch_prof(const char * sess_name, const htp_opbatch_rsp & rsp) {
240 uint64_t batch_cycles = rsp.cycles_stop - rsp.cycles_start;
241 float batch_mhz = rsp.usecs > 0 ? (float) batch_cycles / rsp.usecs : 0.0f;
242
243 char evt_str[256] = "----";
244 if (opt_profile == 3) {
245 snprintf(evt_str, sizeof(evt_str), "evt-cnt %u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u",
246 rsp.n_traces[0], rsp.n_traces[1], rsp.n_traces[2], rsp.n_traces[3],
247 rsp.n_traces[4], rsp.n_traces[5], rsp.n_traces[6], rsp.n_traces[7],
248 rsp.n_traces[8], rsp.n_traces[9], rsp.n_traces[10]);
249 }
250
251 GGML_LOG_DEBUG("ggml-hex: %s profile-op OPBATCH|----|n-ops %u|%s|----|----|usec %u cycles %llu start %llu mhz %.1f\n",
252 sess_name, rsp.n_ops, evt_str, rsp.usecs, (unsigned long long) batch_cycles, (unsigned long long) rsp.cycles_start, batch_mhz);
253}
254
255static void ggml_hexagon_dump_trace_events(const char * sess_name, const htp_opbatch_rsp & rsp,
256 const htp_trace_desc * trace_events, uint32_t n_traces) {
257 if (opt_profile == 3 && trace_events) {
258 uint32_t valid_cnt[HTP_MAX_NTHREADS + 1] = {0};
259 for (uint32_t t = 0; t <= HTP_MAX_NTHREADS; t++) {
260 uint32_t count = rsp.n_traces[t];
261 valid_cnt[t] = count > n_traces ? n_traces : count;
262 }
263
264 for (uint32_t t = 0; t <= HTP_MAX_NTHREADS; t++) {
265 for (uint32_t idx = 0; idx < valid_cnt[t]; idx++) {
266 const auto & e = trace_events[t * n_traces + idx];
267 bool is_stop = (e.info & 0x8000) != 0;
268 uint16_t info = e.info & 0x7FFF;
269 GGML_LOG_DEBUG("ggml-hex: %s trace-evt %s: thread %u info %u %s %u\n",
270 sess_name, htp_event_name(e.id), t, info, is_stop ? "stop" : "start", e.cycles);
271 }
272 }
273 }
274}
275
276// ** backend sessions
277
278struct ggml_hexagon_opbatch;
279struct ggml_hexagon_opqueue;
280struct ggml_hexagon_shared_buffer;
281struct ggml_hexagon_fence_buffer;
282struct ggml_hexagon_session;
283struct ggml_backend_hexagon_device_context;
284
285struct ggml_hexagon_mdev_group {
286 uint32_t idx = 0;
287 uint32_t count = 1;
288 std::vector<std::unique_ptr<ggml_hexagon_session>> sessions;
289};
290
291struct ggml_backend_hexagon_comm_context {
292 std::vector<ggml_backend_t> backends;
293 size_t n_backends = 0;
294 volatile uint32_t * fence_slots[GGML_HEXAGON_MAX_SESSIONS] = {};
295 ggml_tensor fence_tensors[GGML_HEXAGON_MAX_SESSIONS] = {};
296};
297
298struct ggml_hexagon_event {
299 ggml_hexagon_session * sess = nullptr;
300 ggml_hexagon_session * fence_sess = nullptr;
301 volatile uint32_t * fence_slot = nullptr;
302 ggml_tensor fence_tensor = {};
303 uint32_t seq = 0;
304};
305
306struct ggml_hexagon_session {
307 std::string name;
308 remote_handle64 handle;
309 dspqueue_t queue;
310 uint32_t session_id;
311 uint32_t domain_id;
312 uint64_t queue_id;
313 int phys_idx;
314 int virt_idx;
315 bool valid_session;
316 bool valid_handle;
317 bool valid_queue;
318 bool valid_iface;
319
320 ggml_hexagon_opbatch* op_batch;
321 ggml_hexagon_opqueue* op_queue;
322
323 std::unordered_map<int, std::unique_ptr<ggml_hexagon_shared_buffer>> cloned_buffers;
324 std::unordered_set<ggml_hexagon_session *> virt_peers;
325 std::unordered_set<ggml_hexagon_session *> phys_peers;
326
327 uint32_t n_threads = 0;
328 uint32_t n_hvx = 0;
329 uint32_t n_hmx = 0;
330 uint64_t vtcm_size = 0;
331 size_t max_vmem = 0;
332 uint32_t fence_seq = 0;
333
334 std::atomic<uint64_t> batch_req_seq{0};
335 std::atomic<uint64_t> batch_rsp_seq{0};
336 std::atomic<uint32_t> last_error{HTP_STATUS_OK};
337
338 uint64_t cached_uid = 0;
339 std::vector<htp_opnode> cached_nodes;
340
341 ggml_hexagon_mdev_group mdev;
342 ggml_backend_dev_t dev = nullptr;
343 ggml_backend_hexagon_device_context * dev_ctx = nullptr;
344 ggml_hexagon_fence_buffer * fence_buf = nullptr;
345
346 ggml_hexagon_session(const ggml_hexagon_device_config & config, ggml_backend_dev_t dev = nullptr, uint32_t mdev_idx = 0, uint32_t mdev_count = 0) noexcept(false);
347 ~ggml_hexagon_session() noexcept(true);
348
349 const char* c_name() const { return name.c_str(); }
350
351 void allocate(const ggml_hexagon_device_config & config) noexcept(false);
352 void release() noexcept(true);
353
354 uint8_t * alloc_fence(uint32_t n_slots = 1);
355 void free_fence(void * ptr, uint32_t n_slots = 1);
356 ggml_tensor make_fence_tensor(const volatile void * slot, uint32_t n_slots = 1) const;
357 uint32_t next_fence_seq() {
358 if (++fence_seq == 0) fence_seq = 1;
359 return fence_seq;
360 }
361
362 uint8_t * mdev_fence_slot = nullptr;
363 std::unordered_map<uint64_t, volatile uint32_t *> cpy_fence_slots;
364
365 void enqueue_mdev_group();
366 void enqueue_op(const htp_opnode & node);
367 void enqueue_cpy(const ggml_tensor * src, ggml_tensor * dst, const ggml_tensor * sync_tensor = nullptr, uint32_t fence_seq = 0);
368 void enqueue_fence(const ggml_tensor * sync_tensor, uint32_t fence_seq = 0, bool wait = true);
369 void enqueue_allreduce(const ggml_tensor * dst, const std::vector<const ggml_tensor *> & src_tensors,
370 const std::vector<const ggml_tensor *> & sync_tensors, uint32_t rank, uint32_t n_ranks,
371 uint32_t fence_seq_entry = 0, uint32_t fence_seq_exit = 0);
372
373 void start_batch();
374 void flush_sync(bool all = true);
375 void flush_async();
376 void flush_batch(size_t min_ops = 1);
377 void flush_peers();
378 void flush_pending(bool all = true);
379
380 ggml_hexagon_shared_buffer * mmap_tensor(const ggml_tensor * t);
381 bool clone_buffer(const ggml_hexagon_shared_buffer*);
382 void release_buffer(const ggml_hexagon_shared_buffer*);
383 void unclone_buffer(const ggml_hexagon_shared_buffer*);
384
385 void add_peer(ggml_hexagon_session * peer) {
386 if (this->phys_idx == peer->phys_idx) {
387 virt_peers.insert(peer);
388 } else {
389 phys_peers.insert(peer);
390 }
391 }
392};
393
394const char * htp_session_name(const struct ggml_hexagon_session * sess) { return sess->c_name(); }
395size_t htp_session_vtcm_size(const struct ggml_hexagon_session * sess) { return sess->vtcm_size; }
396uint32_t htp_session_n_threads(const struct ggml_hexagon_session * sess) { return sess->n_threads; }
397uint32_t htp_session_n_hmx(const struct ggml_hexagon_session * sess) { return sess->n_hmx; }
398uint32_t htp_session_mdev_count(const struct ggml_hexagon_session * sess) { return sess->mdev.count; }
399
400// ** backend buffers
401
402struct ggml_backend_hexagon_device_context {
403 int dev_id;
404 ggml_hexagon_device_config config;
405 ggml_backend_dev_t dev = nullptr;
406
407 ggml_backend_buffer_type buffer_type = {};
408 ggml_backend_buffer_type host_buffer_type = {};
409 ggml_backend_buffer_type fence_buffer_type = {};
410
411 std::unique_ptr<ggml_hexagon_session> sess;
412
413 ggml_backend_hexagon_device_context(int dev_id, const ggml_hexagon_device_config & config, ggml_backend_dev_t dev);
414 ~ggml_backend_hexagon_device_context();
415
416 const char * c_name() const { return config.name.c_str(); }
417
418 ggml_hexagon_session * session() {
419 if (!sess) {
420 sess = std::make_unique<ggml_hexagon_session>(config, dev);
421 }
422 return sess.get();
423 }
424};
425
426struct ggml_backend_hexagon_buffer_type_context {
427 ggml_backend_hexagon_buffer_type_context(const std::string & name, ggml_backend_hexagon_device_context * dev_ctx) {
428 this->dev_ctx = dev_ctx;
429 this->name = name;
430 }
431
432 ggml_backend_hexagon_device_context * dev_ctx;
433 std::string name;
434};
435
436struct ggml_hexagon_rpcmem_block {
437 uint8_t * base = nullptr;
438 int fd = -1;
439 size_t size = 0;
440
441 std::unordered_set<ggml_hexagon_session *> mapped_clones;
442
443 ggml_hexagon_rpcmem_block(size_t size) {
444 base = (uint8_t *) rpcmem_alloc2(RPCMEM_HEAP_ID_SYSTEM, RPCMEM_DEFAULT_FLAGS, size);
445 if (!base) {
446 throw std::runtime_error("ggml-hex: rpcmem_alloc failed");
447 }
448 fd = rpcmem_to_fd(base);
449 if (fd < 0) {
450 rpcmem_free(base);
451 throw std::runtime_error("ggml-hex: rpcmem_to_fd failed");
452 }
453 this->size = size;
454 }
455
456 ~ggml_hexagon_rpcmem_block() {
457 if (base) {
458 rpcmem_free(base);
459 }
460 }
461};
462
463struct ggml_hexagon_shared_buffer {
464 ggml_hexagon_session * sess;
465 std::shared_ptr<ggml_hexagon_rpcmem_block> mem;
466 std::vector<htp_tensor_extra *> tensor_extra;
467 bool mapped;
468 bool pinned;
469 bool extended;
470
471 const char * c_name() const { return sess->c_name(); }
472 uint8_t * base() const { return mem ? mem->base : nullptr; }
473 size_t size() const { return mem ? mem->size : 0; }
474 int fd() const { return mem ? mem->fd : -1; }
475
476 void mmap(bool extended = false) {
477 if (!this->mem) return;
478 if (this->mapped) return;
479
480 GGML_ASSERT(!this->pinned || !extended);
481
482 this->extended = extended;
483 fastrpc_map_flags flags = this->pinned ? FASTRPC_MAP_FD : (extended ? FASTRPC_MAP_FD_DELAYED_EXTENDED : FASTRPC_MAP_FD_DELAYED);
484
485 int err = fastrpc_mmap(sess->domain_id, fd(), (void *) base(), 0, size(), flags);
486 if (err != 0) {
487 GGML_LOG_ERROR("ggml-hex: %s buffer mapping failed : domain_id %d size %zu fd %d error 0x%08x\n", sess->c_name(),
488 sess->domain_id, size(), fd(), (unsigned) err);
489 throw std::runtime_error("ggml-hex: fastrpc_mmap failed (see log for details)");
490 }
491
492 HEX_VERBOSE("ggml-hex: %s mapped buffer: base %p size %zu fd %d pinned %u extended %u\n",
493 sess->c_name(), (void *) base(), size(), fd(), pinned, extended);
494
495 this->mapped = true;
496 }
497
498 void unmap() {
499 if (!this->mapped) return;
500
501 if (!this->pinned && mem) {
502 // HTP might still hold a reference, tell it drop it
503 htp_iface_munmap(sess->handle, fd());
504 }
505
506 if (mem) {
507 fastrpc_munmap(sess->domain_id, fd(), (void *) base(), size());
508 }
509
510 HEX_VERBOSE("ggml-hex: %s unmapped buffer: base %p size %zu fd %d\n", sess->c_name(),
511 (void *) base(), size(), fd());
512
513 this->mapped = false;
514 }
515
516 void alloc(size_t size) {
517 if (this->mem) return;
518
519 this->mem = std::make_shared<ggml_hexagon_rpcmem_block>(size);
520
521 HEX_VERBOSE("ggml-hex: %s allocated buffer: base %p size %zu fd %d pinned %d\n", sess->c_name(),
522 (void *) base(), this->size(), fd(), (int) pinned);
523 if (this->pinned) {
524 mmap();
525 }
526 }
527
528 void free() {
529 unmap();
530 // The memory is freed when the shared_ptr refcount drops to 0.
531 HEX_VERBOSE("ggml-hex: %s release ref on buffer: base %p size %zu fd %d\n", sess->c_name(),
532 (void *) base(), size(), fd());
533 this->mem = nullptr;
534 }
535
536 ggml_hexagon_shared_buffer(ggml_hexagon_session * sess, size_t size, bool pinned = false) {
537 this->sess = sess;
538 this->mapped = false;
539 this->pinned = pinned;
540 this->extended = false;
541
542 // Size adjustment inside the buffer class: 4K aligned data size + 4K guard page
543 size_t guard_offset = (size + 4095) & ~4095;
544 size_t total_size = guard_offset + 4096;
545 if (!pinned && opt_dma64) {
546 constexpr size_t extended_align = 2 * 1024 * 1024;
547 total_size = (total_size + extended_align - 1) & ~(extended_align - 1);
548 }
549
550 alloc(total_size);
551 }
552
553 // Clone constructor for cross-session mapping
554 ggml_hexagon_shared_buffer(ggml_hexagon_session * sess, const ggml_hexagon_shared_buffer & other) {
555 this->sess = sess;
556 this->mem = other.mem;
557 this->mapped = false;
558 this->pinned = other.pinned;
559 this->extended = other.extended;
560 }
561
562 ~ggml_hexagon_shared_buffer() {
563 free();
564 for (auto * extra : tensor_extra) {
565 delete extra;
566 }
567 }
568};
569
570struct ggml_hexagon_fence_buffer : public ggml_hexagon_shared_buffer {
571 uint32_t slot_count = 0;
572 uint32_t slot_head = 0;
573 std::vector<uint32_t> free_slots;
574 ggml_backend_buffer backend_buffer{};
575
576 ggml_hexagon_fence_buffer(ggml_hexagon_session * sess, ggml_backend_buffer_type_t buft, size_t size)
577 : ggml_hexagon_shared_buffer(sess, size, false /* pinned */),
578 slot_count(size / HTP_FENCE_SLOT_SIZE),
579 slot_head(0) {
580 backend_buffer.buft = buft;
581 backend_buffer.context = static_cast<ggml_hexagon_shared_buffer *>(this);
582 backend_buffer.size = size;
583 mmap(false);
584 }
585
586 uint8_t * alloc_slot(uint32_t n_slots = 1) {
587 uint8_t * ptr = nullptr;
588 if (n_slots == 1 && !free_slots.empty()) {
589 uint32_t slot = free_slots.back();
590 free_slots.pop_back();
591 ptr = base() + (size_t) slot * HTP_FENCE_SLOT_SIZE;
592 } else if (slot_head + n_slots <= slot_count) {
593 uint32_t slot = slot_head;
594 slot_head += n_slots;
595 ptr = base() + (size_t) slot * HTP_FENCE_SLOT_SIZE;
596 }
597 if (ptr) {
598 memset(ptr, 0, (size_t) n_slots * HTP_FENCE_SLOT_SIZE);
599 }
600 return ptr;
601 }
602
603 void free_slot(void * ptr, uint32_t n_slots = 1) {
604 if (!ptr) return;
605 uint32_t slot = ((uint8_t *) ptr - base()) / HTP_FENCE_SLOT_SIZE;
606 for (uint32_t i = 0; i < n_slots; i++) {
607 free_slots.push_back(slot + i);
608 }
609 }
610};
611
612inline uint8_t * ggml_hexagon_session::alloc_fence(uint32_t n_slots) {
613 uint8_t * ptr = fence_buf->alloc_slot(n_slots);
614 GGML_ASSERT(ptr);
615 return ptr;
616}
617
618inline void ggml_hexagon_session::free_fence(void * ptr, uint32_t n_slots) {
619 if (fence_buf) {
620 fence_buf->free_slot(ptr, n_slots);
621 }
622}
623
624inline ggml_tensor ggml_hexagon_session::make_fence_tensor(const volatile void * slot, uint32_t n_slots) const {
625 static htp_tensor_extra fence_extra { {}, 0, HTP_TENSOR_FENCE };
626
627 ggml_tensor t {};
628 t.buffer = &this->fence_buf->backend_buffer;
629 t.extra = &fence_extra;
630 t.data = const_cast<void *>(slot);
631 t.type = GGML_TYPE_I8;
632 t.ne[0] = HTP_FENCE_SLOT_SIZE;
633 t.ne[1] = (int64_t) n_slots;
634 t.ne[2] = 1;
635 t.ne[3] = 1;
636 t.nb[0] = 1;
637 t.nb[1] = HTP_FENCE_SLOT_SIZE;
638 t.nb[2] = t.nb[1] * t.ne[1];
639 t.nb[3] = t.nb[2];
640 t.op = GGML_OP_NONE;
641 return t;
642}
643
644static void ggml_backend_hexagon_buffer_free_buffer(ggml_backend_buffer_t buffer) {
645 auto sbuf = static_cast<ggml_hexagon_shared_buffer *>(buffer->context);
646 sbuf->sess->unclone_buffer(sbuf);
647 delete sbuf;
648}
649
650static void * ggml_backend_hexagon_buffer_get_base(ggml_backend_buffer_t buffer) {
651 auto sbuf = static_cast<ggml_hexagon_shared_buffer *>(buffer->context);
652 return sbuf->base();
653}
654
655static enum ggml_status ggml_backend_hexagon_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
656 auto sbuf = static_cast<ggml_hexagon_shared_buffer *>(buffer->context);
657 auto sess = sbuf->sess;
658
659 HEX_VERBOSE("ggml-hex: %s init-tensor %s : base %p data %p nbytes %zu\n", sess->c_name(),
660 tensor->name, (void *) sbuf->base(), tensor->data, ggml_nbytes(tensor));
661
662 auto extra = new htp_tensor_extra();
663 sbuf->tensor_extra.push_back(extra);
664
665 tensor->extra = extra;
666
667 return GGML_STATUS_SUCCESS;
668}
669
670static void ggml_backend_hexagon_buffer_set_tensor(ggml_backend_buffer_t buffer,
671 ggml_tensor * tensor,
672 const void * data,
673 size_t offset,
674 size_t size) {
675 auto extra = (htp_tensor_extra *) tensor->extra;
676 auto sbuf = (ggml_hexagon_shared_buffer *) buffer->context;
677 auto sess = sbuf->sess;
678
679 if (ggml_backend_buffer_get_usage(buffer) == GGML_BACKEND_BUFFER_USAGE_WEIGHTS) {
680 extra->flags |= HTP_TENSOR_WEIGHT;
681 if (htp_is_tiled_weight_tensor(tensor)) {
682 extra->flags |= HTP_TENSOR_TILED;
683 }
684 }
685
686 HEX_VERBOSE("ggml-hex: %s set-tensor %s : data %p offset %zu size %zu usage %d flags 0x%x\n",
687 sess->c_name(), tensor->name, data, offset, size, (int) buffer->usage, extra->flags);
688
689 if ((extra->flags & HTP_TENSOR_TILED) == 0) {
690 memcpy((char *) tensor->data + offset, data, size);
691 return;
692 }
693
694 if (offset == 0 && size == ggml_nbytes(tensor) && extra->shadow_buf.empty()) {
695 htp_repack_tensor_tiled(tensor, data, size);
696 return;
697 }
698
699 if (extra->shadow_buf.size() < ggml_nbytes(tensor)) {
700 extra->shadow_buf.resize(ggml_nbytes(tensor));
701 }
702 memcpy(extra->shadow_buf.data() + offset, data, size);
703 extra->shadow_size += size;
704
705 if (extra->shadow_size >= ggml_nbytes(tensor)) {
706 htp_repack_tensor_tiled(tensor, extra->shadow_buf.data(), extra->shadow_buf.size());
707 extra->shadow_buf.clear();
708 extra->shadow_buf.shrink_to_fit();
709 extra->shadow_size = 0;
710 }
711}
712
713static void ggml_backend_hexagon_buffer_get_tensor(ggml_backend_buffer_t buffer,
714 const ggml_tensor * tensor,
715 void * data,
716 size_t offset,
717 size_t size) {
718 auto extra = (htp_tensor_extra *) tensor->extra;
719 auto sbuf = (ggml_hexagon_shared_buffer *) buffer->context;
720 auto sess = sbuf->sess;
721
722 HEX_VERBOSE("ggml-hex: %s get-tensor %s : data %p offset %zu size %zu usage %d flags 0x%x\n",
723 sess->c_name(), tensor->name, data, offset, size, (int) buffer->usage, extra->flags);
724
725 if ((extra->flags & HTP_TENSOR_TILED) == 0) {
726 memcpy(data, (const char *) tensor->data + offset, size);
727 return;
728 }
729
730 htp_unpack_tensor_tiled(data, tensor, offset, size);
731}
732
733static bool ggml_backend_hexagon_buffer_cpy_tensor(ggml_backend_buffer_t buffer,
734 const struct ggml_tensor * src,
735 struct ggml_tensor * dst) {
736 // we might optimize this later, for now take the slow path (ie get/set_tensor)
737 return false;
738
739 GGML_UNUSED(buffer);
740 GGML_UNUSED(src);
741 GGML_UNUSED(dst);
742}
743
744static void ggml_backend_hexagon_buffer_set_tensor_2d(ggml_backend_buffer_t buffer,
745 ggml_tensor * tensor,
746 const void * data,
747 size_t offset,
748 size_t size,
749 size_t n_copies,
750 size_t stride_tensor,
751 size_t stride_data) {
752 auto extra = (htp_tensor_extra *) tensor->extra;
753 auto sbuf = (ggml_hexagon_shared_buffer *) buffer->context;
754 auto sess = sbuf->sess;
755
756 if (ggml_backend_buffer_get_usage(buffer) == GGML_BACKEND_BUFFER_USAGE_WEIGHTS) {
757 extra->flags |= HTP_TENSOR_WEIGHT;
758 if (htp_is_tiled_weight_tensor(tensor)) {
759 extra->flags |= HTP_TENSOR_TILED;
760 }
761 }
762
763 HEX_VERBOSE("ggml-hex: %s set-tensor-2d %s : data %p offset %zu size %zu n_copies %zu stride_tensor %zu stride_data %zu usage %d flags 0x%x\n",
764 sess->c_name(), tensor->name, data, offset, size, n_copies, stride_tensor, stride_data, (int) buffer->usage, extra->flags);
765
766 if ((extra->flags & HTP_TENSOR_TILED) == 0) {
767 for (size_t i = 0; i < n_copies; i++) {
768 memcpy((uint8_t *) tensor->data + offset + i * stride_tensor, (const uint8_t *) data + i * stride_data, size);
769 }
770 return;
771 }
772
773 if (extra->shadow_buf.size() < ggml_nbytes(tensor)) {
774 extra->shadow_buf.resize(ggml_nbytes(tensor));
775 }
776 for (size_t i = 0; i < n_copies; i++) {
777 memcpy(extra->shadow_buf.data() + offset + i * stride_tensor, (const uint8_t *) data + i * stride_data, size);
778 }
779 extra->shadow_size += n_copies * size;
780
781 if (extra->shadow_size >= ggml_nbytes(tensor)) {
782 htp_repack_tensor_tiled(tensor, extra->shadow_buf.data(), extra->shadow_buf.size());
783 extra->shadow_buf.clear();
784 extra->shadow_buf.shrink_to_fit();
785 extra->shadow_size = 0;
786 }
787}
788
789static void ggml_backend_hexagon_buffer_get_tensor_2d(ggml_backend_buffer_t buffer,
790 const ggml_tensor * tensor,
791 void * data,
792 size_t offset,
793 size_t size,
794 size_t n_copies,
795 size_t stride_tensor,
796 size_t stride_data) {
797 auto extra = (htp_tensor_extra *) tensor->extra;
798 auto sbuf = (ggml_hexagon_shared_buffer *) buffer->context;
799 auto sess = sbuf->sess;
800
801 HEX_VERBOSE("ggml-hex: %s get-tensor-2d %s : data %p offset %zu size %zu n_copies %zu stride_tensor %zu stride_data %zu usage %d\n",
802 sess->c_name(), tensor->name, data, offset, size, n_copies, stride_tensor, stride_data, (int) buffer->usage);
803
804 if ((extra->flags & HTP_TENSOR_TILED) == 0) {
805 for (size_t i = 0; i < n_copies; i++) {
806 memcpy((uint8_t *)data + i * stride_data, (const uint8_t *)tensor->data + offset + i * stride_tensor, size);
807 }
808 return;
809 }
810
811 size_t temp_size = n_copies > 0 ? (n_copies - 1) * stride_tensor + size : 0;
812 size_t slice_size = tensor->ne[1] * ggml_row_size(tensor->type, tensor->ne[0]);
813 size_t slice_offset = offset % slice_size;
814 size_t row_size_bytes = ggml_row_size(tensor->type, tensor->ne[0]);
815
816 GGML_ASSERT((slice_offset % row_size_bytes) == 0 && "offset must be aligned to row boundary");
817 GGML_ASSERT((temp_size % row_size_bytes) == 0 && "temp_size must be a multiple of row size");
818 GGML_ASSERT((offset + temp_size) <= ggml_nbytes(tensor));
819
820 std::vector<uint8_t> temp_buf(temp_size);
821 htp_unpack_tensor_tiled(temp_buf.data(), tensor, offset, temp_size);
822
823 for (size_t i = 0; i < n_copies; i++) {
824 memcpy((uint8_t *) data + i * stride_data, temp_buf.data() + i * stride_tensor, size);
825 }
826}
827
828static void ggml_backend_hexagon_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
829 auto sbuf = (ggml_hexagon_shared_buffer *) buffer->context;
830 auto sess = sbuf->sess;
831 HEX_VERBOSE("ggml-hex: %s clear-buff base %p size %zu\n", sess->c_name(), (void *) sbuf->base(), sbuf->size());
832 memset(sbuf->base(), value, sbuf->size());
833}
834
835static ggml_backend_buffer_i ggml_backend_hexagon_buffer_interface = {
836 /* .free_buffer = */ ggml_backend_hexagon_buffer_free_buffer,
837 /* .get_base = */ ggml_backend_hexagon_buffer_get_base,
838 /* .init_tensor = */ ggml_backend_hexagon_buffer_init_tensor,
839 /* .memset_tensor = */ NULL,
840 /* .set_tensor = */ ggml_backend_hexagon_buffer_set_tensor,
841 /* .get_tensor = */ ggml_backend_hexagon_buffer_get_tensor,
842 /* .set_tensor_2d = */ ggml_backend_hexagon_buffer_set_tensor_2d,
843 /* .get_tensor_2d = */ ggml_backend_hexagon_buffer_get_tensor_2d,
844 /* .cpy_tensor = */ ggml_backend_hexagon_buffer_cpy_tensor,
845 /* .clear = */ ggml_backend_hexagon_buffer_clear,
846 /* .reset = */ NULL,
847 /* .set_tensor_n = */ NULL,
848 /* .get_tensor_n = */ NULL,
849 /* .cpy_tensor_n = */ NULL,
850};
851
852// ** backend buffer type
853
854static void ggml_backend_hexagon_host_buffer_set_tensor(ggml_backend_buffer_t buffer,
855 ggml_tensor * tensor,
856 const void * data,
857 size_t offset,
858 size_t size) {
859 memcpy((char *) tensor->data + offset, data, size);
860 GGML_UNUSED(buffer);
861}
862
863static void ggml_backend_hexagon_host_buffer_get_tensor(ggml_backend_buffer_t buffer,
864 const ggml_tensor * tensor,
865 void * data,
866 size_t offset,
867 size_t size) {
868 memcpy(data, (const char *) tensor->data + offset, size);
869 GGML_UNUSED(buffer);
870}
871
872static ggml_backend_buffer_i ggml_backend_hexagon_host_buffer_interface = {
873 /* .free_buffer = */ ggml_backend_hexagon_buffer_free_buffer,
874 /* .get_base = */ ggml_backend_hexagon_buffer_get_base,
875 /* .init_tensor = */ ggml_backend_hexagon_buffer_init_tensor,
876 /* .memset_tensor = */ NULL,
877 /* .set_tensor = */ ggml_backend_hexagon_host_buffer_set_tensor,
878 /* .get_tensor = */ ggml_backend_hexagon_host_buffer_get_tensor,
879 /* .set_tensor_2d = */ NULL,
880 /* .get_tensor_2d = */ NULL,
881 /* .cpy_tensor = */ ggml_backend_hexagon_buffer_cpy_tensor,
882 /* .clear = */ ggml_backend_hexagon_buffer_clear,
883 /* .reset = */ NULL,
884 /* .set_tensor_n = */ NULL,
885 /* .get_tensor_n = */ NULL,
886 /* .cpy_tensor_n = */ NULL,
887};
888
889// ** backend buffer type
890
891static const char * ggml_backend_hexagon_buffer_type_name(ggml_backend_buffer_type_t buffer_type) {
892 return static_cast<ggml_backend_hexagon_buffer_type_context *>(buffer_type->context)->name.c_str();
893}
894
895static ggml_backend_buffer_t ggml_backend_hexagon_buffer_type_alloc_buffer(
896 ggml_backend_buffer_type_t buffer_type, size_t size) {
897 auto dev_ctx = static_cast<ggml_backend_hexagon_buffer_type_context *>(buffer_type->context)->dev_ctx;
898 auto sess = dev_ctx->session();
899 if (sess && sess->max_vmem && size > sess->max_vmem) {
900 GGML_LOG_ERROR("ggml-hex: %s buffer size %zu exceeds max_vmem %zu\n",
901 dev_ctx->c_name(), size, sess->max_vmem);
902 return nullptr;
903 }
904 try {
905 ggml_hexagon_shared_buffer * sbuf = new ggml_hexagon_shared_buffer(sess, size, false);
906 return ggml_backend_buffer_init(buffer_type, ggml_backend_hexagon_buffer_interface, sbuf, size);
907 } catch (const std::exception & exc) {
908 GGML_LOG_ERROR("ggml-hex: %s failed to allocate device buffer context: %s\n", dev_ctx->c_name(), exc.what());
909 return nullptr;
910 }
911}
912
913static ggml_backend_buffer_t ggml_backend_hexagon_host_buffer_type_alloc_buffer(
914 ggml_backend_buffer_type_t buffer_type, size_t size) {
915 auto dev_ctx = static_cast<ggml_backend_hexagon_buffer_type_context *>(buffer_type->context)->dev_ctx;
916 auto sess = dev_ctx->session();
917 if (sess && sess->max_vmem && size > sess->max_vmem) {
918 GGML_LOG_ERROR("ggml-hex: %s host buffer size %zu exceeds max_vmem %zu\n",
919 dev_ctx->c_name(), size, sess->max_vmem);
920 return nullptr;
921 }
922 try {
923 ggml_hexagon_shared_buffer * sbuf = new ggml_hexagon_shared_buffer(sess, size, false);
924 return ggml_backend_buffer_init(buffer_type, ggml_backend_hexagon_host_buffer_interface, sbuf, size);
925 } catch (const std::exception & exc) {
926 GGML_LOG_ERROR("ggml-hex: %s failed to allocate host buffer context: %s\n", dev_ctx->c_name(), exc.what());
927 return nullptr;
928 }
929}
930
931static size_t ggml_backend_hexagon_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
932 return 128; // HVX alignment
933 GGML_UNUSED(buft);
934}
935
936static size_t ggml_backend_hexagon_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const struct ggml_tensor * t) {
937 if (!ggml_backend_buft_is_host(buft) && htp_is_tiled_weight_tensor(t)) {
938 int64_t ne0 = hex_round_up(t->ne[0], 32);
939 int64_t ne1 = hex_round_up(t->ne[1], 32);
940 int64_t ne2 = t->ne[2];
941 int64_t ne3 = t->ne[3];
942 size_t tiled_size = htp_tiled_row_size(t->type, ne0) * ne1 * ne2 * ne3;
943 return std::max(tiled_size, ggml_nbytes(t));
944 }
945 return ggml_nbytes(t);
946}
947
948static size_t parse_size(const char * str, size_t default_unit = 1024 * 1024) {
949 if (!str || str[0] == '\0') {
950 return 0;
951 }
952 char * end = NULL;
953 double val = strtod(str, &end);
954 if (val < 0) {
955 return 0;
956 }
957 if (end && *end) {
958 while (*end == ' ') end++;
959 if (*end == 'k' || *end == 'K') {
960 return (size_t) (val * 1024);
961 } else if (*end == 'm' || *end == 'M') {
962 return (size_t) (val * 1024 * 1024);
963 } else if (*end == 'g' || *end == 'G') {
964 return (size_t) (val * 1024 * 1024 * 1024);
965 }
966 }
967 return (size_t) (val * default_unit);
968}
969
970static size_t ggml_backend_hexagon_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
971 return opt_mbuf_dyn;
972 GGML_UNUSED(buft);
973}
974
975static bool ggml_backend_hexagon_buffer_type_is_host(ggml_backend_buffer_type_t buft) {
976 return false;
977 GGML_UNUSED(buft);
978}
979
980static bool ggml_backend_hexagon_host_buffer_type_is_host(ggml_backend_buffer_type_t buft) {
981 return true;
982 GGML_UNUSED(buft);
983}
984
985struct ggml_backend_hexagon_alloc_buffer_n_plan_item {
986 size_t size;
987 int first;
988 int last;
989};
990
991using ggml_backend_hexagon_alloc_buffer_n_plan_t = std::vector<ggml_backend_hexagon_alloc_buffer_n_plan_item>;
992
993static const char * ggml_hexagon_kv_layer_suffix(const struct ggml_tensor * t) {
994 if (strncmp(t->name, "cache_", 6) != 0) {
995 return NULL;
996 }
997 const char * p = strstr(t->name, "_l");
998 if (!p || !isdigit((unsigned char)p[2])) {
999 return NULL;
1000 }
1001 return p;
1002}
1003
1004struct ggml_backend_hexagon_alloc_unit {
1005 size_t size;
1006 int first;
1007 int last;
1008};
1009
1010static ggml_backend_hexagon_alloc_buffer_n_plan_t ggml_backend_hexagon_alloc_buffer_n_plan(
1011 ggml_backend_buffer_type_t buft, struct ggml_tensor ** tensors, int n_tensors) {
1012 ggml_backend_hexagon_alloc_buffer_n_plan_t plan;
1013
1014 const size_t alignment = ggml_backend_buft_get_alignment(buft);
1015 const size_t max_size = opt_mbuf_static > 0 ? opt_mbuf_static : SIZE_MAX;
1016
1017 std::vector<ggml_backend_hexagon_alloc_unit> units;
1018
1019 int i = 0;
1020 while (i < n_tensors) {
1021 struct ggml_tensor * t = tensors[i];
1022 size_t unit_size = 0;
1023 int unit_first = i;
1024 int unit_last = i + 1;
1025
1026 if (t->data == NULL && t->view_src == NULL) {
1027 unit_size += GGML_PAD(ggml_backend_buft_get_alloc_size(buft, t), alignment);
1028 }
1029
1030 const char * layer_suffix = ggml_hexagon_kv_layer_suffix(t);
1031
1032 while (unit_last < n_tensors) {
1033 struct ggml_tensor * next = tensors[unit_last];
1034
1035 if (next->view_src != NULL) {
1036 unit_last++;
1037 continue;
1038 }
1039
1040 if (layer_suffix != NULL) {
1041 const char * next_suffix = ggml_hexagon_kv_layer_suffix(next);
1042 if (next_suffix != NULL && strcmp(layer_suffix, next_suffix) == 0) {
1043 if (next->data == NULL) {
1044 unit_size += GGML_PAD(ggml_backend_buft_get_alloc_size(buft, next), alignment);
1045 }
1046 unit_last++;
1047 continue;
1048 }
1049 }
1050
1051 break;
1052 }
1053
1054 units.push_back({ unit_size, unit_first, unit_last });
1055 i = unit_last;
1056 }
1057
1058 size_t cur_buf_size = 0;
1059 int cur_buf_first = 0;
1060
1061 for (const auto & unit : units) {
1062 if (unit.size == 0) {
1063 continue;
1064 }
1065
1066 if (cur_buf_size > 0 && (cur_buf_size + unit.size) > max_size) {
1067 plan.push_back({ cur_buf_size, cur_buf_first, unit.first });
1068 cur_buf_size = 0;
1069 cur_buf_first = unit.first;
1070 }
1071
1072 cur_buf_size += unit.size;
1073 }
1074
1075 if (cur_buf_size > 0) {
1076 plan.push_back({ cur_buf_size, cur_buf_first, n_tensors });
1077 }
1078
1079 return plan;
1080}
1081
1082static ggml_backend_buffer_t ggml_backend_hexagon_buffer_type_alloc_buffer_n(
1083 ggml_backend_buffer_type_t buft, struct ggml_tensor ** tensors, int n_tensors) {
1084 const ggml_backend_hexagon_alloc_buffer_n_plan_t plan = ggml_backend_hexagon_alloc_buffer_n_plan(buft, tensors, n_tensors);
1085
1086 std::vector<ggml_backend_buffer_t> buffers;
1087 buffers.reserve(plan.size());
1088
1089 for (const auto & item : plan) {
1090 ggml_backend_buffer_t buffer = ggml_backend_buft_alloc_buffer(buft, item.size);
1091 if (buffer == NULL) {
1092 GGML_LOG_ERROR("%s: failed to allocate %s buffer of size %zu\n", __func__, ggml_backend_buft_name(buft), item.size);
1093 for (ggml_backend_buffer_t b : buffers) {
1094 ggml_backend_buffer_free(b);
1095 }
1096 return NULL;
1097 }
1098
1099 struct ggml_tallocr tallocr = ggml_tallocr_new(buffer);
1100
1101 struct ggml_tensor * t_failed = NULL;
1102 for (int j = item.first; j < item.last; j++) {
1103 struct ggml_tensor * t = tensors[j];
1104 if (t->data == NULL) {
1105 if (t->view_src == NULL) {
1106 if (ggml_tallocr_alloc(&tallocr, t) != GGML_STATUS_SUCCESS) {
1107 t_failed = t;
1108 break;
1109 }
1110 } else if (t->buffer == NULL) {
1111 if (ggml_backend_view_init(t) != GGML_STATUS_SUCCESS) {
1112 t_failed = t;
1113 break;
1114 }
1115 }
1116 } else {
1117 if (t->view_src != NULL && t->buffer == NULL) {
1118 if (ggml_backend_view_init(t) != GGML_STATUS_SUCCESS) {
1119 t_failed = t;
1120 break;
1121 }
1122 }
1123 }
1124 }
1125 if (t_failed != NULL) {
1126 GGML_LOG_ERROR("%s: failed to initialize tensor %s\n", __func__, t_failed->name);
1127 for (ggml_backend_buffer_t b : buffers) {
1128 ggml_backend_buffer_free(b);
1129 }
1130 ggml_backend_buffer_free(buffer);
1131 return NULL;
1132 }
1133
1134 buffers.push_back(buffer);
1135 }
1136
1137 if (buffers.empty()) {
1138 return NULL;
1139 }
1140
1141 if (buffers.size() == 1) {
1142 return buffers[0];
1143 }
1144
1145 return ggml_backend_multi_buffer_alloc_buffer(buffers.data(), buffers.size());
1146}
1147
1148static size_t ggml_backend_hexagon_buffer_type_get_alloc_size_n(
1149 ggml_backend_buffer_type_t buft, struct ggml_tensor ** tensors, int n_tensors) {
1150 const ggml_backend_hexagon_alloc_buffer_n_plan_t plan = ggml_backend_hexagon_alloc_buffer_n_plan(buft, tensors, n_tensors);
1151
1152 size_t total = 0;
1153 for (const auto & item : plan) {
1154 total += item.size;
1155 }
1156 return total;
1157}
1158
1159static ggml_backend_buffer_type_i ggml_backend_hexagon_buffer_type_interface = {
1160 /* .get_name = */ ggml_backend_hexagon_buffer_type_name,
1161 /* .alloc_buffer = */ ggml_backend_hexagon_buffer_type_alloc_buffer,
1162 /* .alloc_buffer_n = */ ggml_backend_hexagon_buffer_type_alloc_buffer_n,
1163 /* .get_alignment = */ ggml_backend_hexagon_buffer_type_get_alignment,
1164 /* .get_max_size = */ ggml_backend_hexagon_buffer_type_get_max_size,
1165 /* .get_alloc_size = */ ggml_backend_hexagon_buffer_type_get_alloc_size,
1166 /* .get_alloc_size_n = */ ggml_backend_hexagon_buffer_type_get_alloc_size_n,
1167 /* .is_host = */ ggml_backend_hexagon_buffer_type_is_host,
1168};
1169
1170static ggml_backend_buffer_type_i ggml_backend_hexagon_host_buffer_type_interface = {
1171 /* .get_name = */ ggml_backend_hexagon_buffer_type_name,
1172 /* .alloc_buffer = */ ggml_backend_hexagon_host_buffer_type_alloc_buffer,
1173 /* .alloc_buffer_n = */ ggml_backend_hexagon_buffer_type_alloc_buffer_n,
1174 /* .get_alignment = */ ggml_backend_hexagon_buffer_type_get_alignment,
1175 /* .get_max_size = */ ggml_backend_hexagon_buffer_type_get_max_size,
1176 /* .get_alloc_size = */ ggml_backend_hexagon_buffer_type_get_alloc_size,
1177 /* .get_alloc_size_n = */ ggml_backend_hexagon_buffer_type_get_alloc_size_n,
1178 /* .is_host = */ ggml_backend_hexagon_host_buffer_type_is_host,
1179};
1180
1181ggml_backend_hexagon_device_context::ggml_backend_hexagon_device_context(int dev_id, const ggml_hexagon_device_config & config, ggml_backend_dev_t dev)
1182 : dev_id(dev_id), config(config), dev(dev) {
1183 buffer_type.device = dev;
1184 buffer_type.iface = ggml_backend_hexagon_buffer_type_interface;
1185 buffer_type.context = new ggml_backend_hexagon_buffer_type_context(config.name, this);
1186
1187 host_buffer_type.device = dev;
1188 host_buffer_type.iface = ggml_backend_hexagon_host_buffer_type_interface;
1189 host_buffer_type.context = new ggml_backend_hexagon_buffer_type_context(config.name + "-HOST", this);
1190
1191 fence_buffer_type.device = dev;
1192 fence_buffer_type.iface = ggml_backend_hexagon_buffer_type_interface;
1193 fence_buffer_type.context = new ggml_backend_hexagon_buffer_type_context(config.name + "-FENCE", this);
1194}
1195
1196ggml_backend_hexagon_device_context::~ggml_backend_hexagon_device_context() {
1197 delete static_cast<ggml_backend_hexagon_buffer_type_context *>(buffer_type.context);
1198 delete static_cast<ggml_backend_hexagon_buffer_type_context *>(host_buffer_type.context);
1199 delete static_cast<ggml_backend_hexagon_buffer_type_context *>(fence_buffer_type.context);
1200}
1201
1202static bool ggml_backend_buffer_is_hexagon(const struct ggml_backend_buffer * b) {
1203 return b->buft->iface.get_alignment == ggml_backend_hexagon_buffer_type_get_alignment;
1204}
1205
1206struct ggml_hexagon_opbatch {
1207 ggml_hexagon_session* sess;
1208
1209 std::vector<htp_opnode> ops; // htp_opnode of ops
1210
1211 std::vector<htp_buf_desc> h_bufs; // htp buffer descriptors
1212 std::vector<htp_tensor> h_tens; // htp tensor descriptors
1213 std::vector<htp_op_desc> h_ops; // htp op descriptors
1214
1215 std::unordered_map<const ggml_tensor*, int> t_map; // tensor ptr to index
1216 std::unordered_multimap<void*, int> d_map; // tensor data to index
1217
1218 unsigned int n_bufs; // num buffers in the batch
1219 unsigned int n_tens; // num tensors ...
1220 unsigned int n_ops; // num ops ...
1221 size_t b_vmem; // sum of non-extended buffer sizes
1222
1223 unsigned int n_bufs_max;
1224 unsigned int n_tens_max;
1225 unsigned int n_ops_max;
1226 size_t b_vmem_max;
1227
1228 void reset() {
1229 n_bufs = 0;
1230 n_tens = 0;
1231 n_ops = 0;
1232 b_vmem = 0;
1233
1234 t_map.clear();
1235 d_map.clear();
1236 ops.resize(n_ops_max);
1237 }
1238
1239 ggml_hexagon_opbatch(ggml_hexagon_session *sess, size_t batch_size, size_t max_vmem) {
1240 this->sess = sess;
1241
1242 n_bufs_max = HTP_OP_MAX_BUFS;
1243 n_ops_max = batch_size;
1244 n_tens_max = std::min<size_t>(n_ops_max * 4 + HTP_OP_MAX_INPUTS + HTP_OP_MAX_OUTPUTS, HTP_OP_MAX_TENSORS);
1245
1246 b_vmem_max = max_vmem;
1247
1248 ops.resize(n_ops_max);
1249
1250 h_bufs.resize(n_bufs_max);
1251 h_tens.resize(n_tens_max);
1252 h_ops.resize(n_ops_max);
1253
1254 t_map.reserve(n_tens_max);
1255 d_map.reserve(n_tens_max);
1256
1257 GGML_LOG_INFO("ggml-hex: %s op batching: n-bufs %u n-tensors %u n-ops %u vmem %zu\n",
1258 sess->c_name(), n_bufs_max, n_tens_max, n_ops_max, b_vmem_max);
1259
1260 reset();
1261 }
1262
1263 bool empty() const { return n_ops == 0; }
1264 bool full() const { return n_ops >= n_ops_max; }
1265
1266 int find_buffer(int fd) const {
1267 for (unsigned int i = 0; i < n_bufs; i++) {
1268 if ((int) h_bufs[i].fd == fd) {
1269 return (int) i;
1270 }
1271 }
1272 return -1;
1273 }
1274
1275 // add buffer and return its index
1276 int add_buffer(ggml_hexagon_shared_buffer * sbuf) {
1277 // Lookup by fd
1278 int bi = find_buffer(sbuf->fd());
1279 if (bi >= 0) { return bi; }
1280
1281 // Add new buffer to the batch
1282 GGML_ASSERT(n_bufs < HTP_OP_MAX_BUFS);
1283 bi = n_bufs++;
1284
1285 htp_buf_desc &b = h_bufs[bi];
1286 b.base = (uint64_t) sbuf->base();
1287 b.fd = sbuf->fd();
1288 b.size = sbuf->size();
1289 b.flags = sbuf->extended ? HTP_BUF_EXTENDED : 0;
1290
1291 if (!sbuf->extended) {
1292 b_vmem += b.size;
1293 }
1294
1295 HEX_VERBOSE("ggml-hex: %s add-buffer #%u : fd %d base %p size %zu : vmem %zu\n", sess->c_name(), bi, b.fd, (void*) sbuf->base(), (size_t) b.size, b_vmem);
1296
1297 return bi;
1298 }
1299
1300 static void init_tensor_shape(htp_tensor & h, const ggml_tensor * t) {
1301 auto extra = (htp_tensor_extra *) t->extra;
1302
1303 h.type = t->type;
1304 h.ne[0] = t->ne[0];
1305 h.ne[1] = t->ne[1];
1306 h.ne[2] = t->ne[2];
1307 h.ne[3] = t->ne[3];
1308
1309 if (extra->flags & HTP_TENSOR_TILED) {
1310 if (t->type == GGML_TYPE_F32 || t->type == GGML_TYPE_BF16) {
1311 h.type = GGML_TYPE_F16;
1312 h.nb[0] = sizeof(ggml_fp16_t);
1313 } else {
1314 h.nb[0] = t->nb[0];
1315 }
1316 const int64_t ne0_padded = hex_round_up(t->ne[0], 32);
1317 const int64_t ne1_padded = hex_round_up(t->ne[1], 32);
1318 h.nb[1] = htp_tiled_row_size(t->type, ne0_padded);
1319 h.nb[2] = h.nb[1] * ne1_padded;
1320 h.nb[3] = h.nb[2] * h.ne[2];
1321 h.size = h.nb[3] * h.ne[3];
1322 } else {
1323 h.nb[0] = t->nb[0];
1324 h.nb[1] = t->nb[1];
1325 h.nb[2] = t->nb[2];
1326 h.nb[3] = t->nb[3];
1327 h.size = ggml_nbytes(t);
1328 }
1329
1330 h.flags = extra->flags & (HTP_TENSOR_WEIGHT | HTP_TENSOR_TILED | HTP_TENSOR_FENCE);
1331 }
1332
1333 static bool same_shape(const htp_tensor & a, const htp_tensor & b) {
1334 return (a.type == b.type) &&
1335 (a.ne[0] == b.ne[0]) && (a.ne[1] == b.ne[1]) && (a.ne[2] == b.ne[2]) && (a.ne[3] == b.ne[3]) &&
1336 (a.nb[0] == b.nb[0]) && (a.nb[1] == b.nb[1]) && (a.nb[2] == b.nb[2]) && (a.nb[3] == b.nb[3]);
1337 }
1338
1339 // add tensor and return its index
1340 int add_tensor(const ggml_tensor * t) {
1341 // Lookup by tensor ptr
1342 auto it = t_map.find(t);
1343 if (it != t_map.end()) { return it->second; }
1344
1345 htp_tensor shape {};
1346 init_tensor_shape(shape, t);
1347
1348 // Lookup by tensor data and shape
1349 auto range = d_map.equal_range(t->data);
1350 for (auto dit = range.first; dit != range.second; ++dit) {
1351 if (same_shape(h_tens[dit->second], shape)) {
1352 t_map.insert({t, dit->second});
1353 return dit->second;
1354 }
1355 }
1356
1357 auto sbuf = static_cast<ggml_hexagon_shared_buffer *>(t->buffer->context);
1358
1359 // Add new tensor to the batch
1360 int ti = n_tens++;
1361 GGML_ASSERT(n_tens <= n_tens_max);
1362
1363 t_map.insert({t, ti});
1364 d_map.insert({t->data, ti});
1365
1366 uint64_t t_offset = (uint8_t *) t->data - sbuf->base();
1367
1368 htp_tensor & h = h_tens[ti];
1369 h = shape;
1370 h.bi = add_buffer(sbuf);
1371 h.ti = ti;
1372 h.data = t_offset;
1373
1374 HEX_VERBOSE("ggml-hex: %s add-tensor #%u %s : bi %d data %p offset %zu size %zu flags 0x%x : %zu:%zu:%zu:%zu\n", sess->c_name(),
1375 ti, t->name, h.bi, (void*) t->data, (size_t) t_offset, (size_t) h.size, h.flags,
1376 (size_t) h.ne[0], (size_t) h.ne[1], (size_t) h.ne[2], (size_t) h.ne[3]);
1377
1378 return ti;
1379 }
1380
1381 bool fit_tensors(const htp_opnode & node) const {
1382 // check how much extras we will need
1383 size_t extra_bufs = 0;
1384 size_t extra_vmem = 0;
1385 size_t extra_tens = 0;
1386
1387 const bool check_tens = (n_tens + node.inputs.size() + node.outputs.size()) > n_tens_max;
1388
1389 int seen_bufs[HTP_OP_MAX_BUFS];
1390 int n_seen_bufs = 0;
1391
1392 auto fit_tensor = [&](const ggml_tensor * t) {
1393 if (!t) return;
1394 if (check_tens) {
1395 if (t_map.count(t)) return;
1396 extra_tens++;
1397 }
1398
1399 auto sbuf = static_cast<ggml_hexagon_shared_buffer *>(t->buffer->context);
1400 int fd = sbuf->fd();
1401 if (find_buffer(fd) < 0) {
1402 for (int i = 0; i < n_seen_bufs; i++) {
1403 if (seen_bufs[i] == fd) return;
1404 }
1405 if (n_seen_bufs < HTP_OP_MAX_BUFS) {
1406 seen_bufs[n_seen_bufs++] = fd;
1407 }
1408 if (!sbuf->extended) {
1409 extra_vmem += sbuf->size();
1410 }
1411 extra_bufs += 1;
1412 }
1413 };
1414
1415 for (const auto * src : node.get_inputs()) {
1416 fit_tensor(src);
1417 }
1418 for (const auto * output : node.get_outputs()) {
1419 fit_tensor(output);
1420 }
1421
1422 if ((extra_bufs + n_bufs) > n_bufs_max) return false;
1423 if (check_tens && (extra_tens + n_tens) > n_tens_max) return false;
1424 if ((extra_vmem + b_vmem) > b_vmem_max) return false;
1425
1426 return true;
1427 }
1428
1429 void sync_op_desc(unsigned int n) {
1430 const htp_opnode & node = ops[n];
1431 htp_op_desc & o = h_ops[n];
1432
1433 memcpy(o.params, node.params, sizeof(o.params));
1434 memcpy(o.kernel_params, node.kernel_params, sizeof(o.kernel_params));
1435 o.opcode = node.opcode;
1436
1437 const auto & inputs = node.get_inputs();
1438 for (unsigned int i = 0; i < HTP_OP_MAX_INPUTS; i++) {
1439 o.src[i] = (i < inputs.size() && inputs[i]) ? add_tensor(inputs[i]) : 0xffff;
1440 }
1441
1442 const auto & outputs = node.get_outputs();
1443 for (unsigned int i = 0; i < HTP_OP_MAX_OUTPUTS; i++) {
1444 o.dst[i] = (i < outputs.size() && outputs[i]) ? add_tensor(outputs[i]) : 0xffff;
1445 }
1446 }
1447
1448 // caller must ensure the op fits
1449 void add_op(const htp_opnode & node) {
1450 unsigned int n = n_ops++;
1451 GGML_ASSERT(n_ops <= n_ops_max);
1452
1453 ops[n] = node;
1454 h_ops[n].flags = 0;
1455
1456 ggml_hexagon_dump_op_exec(sess->c_name(), ops[n], h_ops[n].flags);
1457 sync_op_desc(n);
1458 }
1459
1460 void sort_buffers() {
1461 if (n_bufs <= 1) return;
1462
1463 std::vector<int> order(n_bufs);
1464 for (unsigned int i = 0; i < n_bufs; i++) { order[i] = (int) i; }
1465
1466 std::stable_sort(order.begin(), order.end(), [&](int a, int b) {
1467 return h_bufs[a].size > h_bufs[b].size;
1468 });
1469
1470 bool already_sorted = true;
1471 for (unsigned int i = 0; i < n_bufs; i++) {
1472 if (order[i] != (int) i) {
1473 already_sorted = false;
1474 break;
1475 }
1476 }
1477 if (already_sorted) return;
1478
1479 std::vector<uint16_t> remap(n_bufs);
1480 std::vector<htp_buf_desc> sorted_bufs(n_bufs);
1481 for (unsigned int new_bi = 0; new_bi < n_bufs; new_bi++) {
1482 int old_bi = order[new_bi];
1483 remap[old_bi] = (uint16_t) new_bi;
1484 sorted_bufs[new_bi] = h_bufs[old_bi];
1485 }
1486
1487 for (unsigned int i = 0; i < n_bufs; i++) {
1488 h_bufs[i] = sorted_bufs[i];
1489 }
1490
1491 for (unsigned int i = 0; i < n_tens; i++) {
1492 h_tens[i].bi = remap[h_tens[i].bi];
1493 }
1494 }
1495
1496 void update_mdev_group(uint32_t mdev_idx) {
1497 if (n_ops > 0 && h_ops[0].opcode == HTP_OP_MDEV_GROUP) {
1498 h_ops[0].params[0] = (int32_t) mdev_idx;
1499 }
1500 }
1501
1502 bool try_fuse(const htp_opnode & node) {
1503 if (n_ops == 0) {
1504 return false;
1505 }
1506
1507 htp_opnode & last_node = ops[n_ops - 1];
1508 if (!htp_fusion_try_fuse(sess, last_node, node)) {
1509 return false;
1510 }
1511
1512 sync_op_desc(n_ops - 1);
1513 HEX_VERBOSE("ggml-hex: %s fused %s (N=%zu, #%u)\n",
1514 sess->c_name(), last_node.name().c_str(), last_node.fused.size() + 1, n_ops - 1);
1515 return true;
1516 }
1517};
1518
1519struct ggml_hexagon_registry {
1520 ggml_hexagon_registry(ggml_backend_reg_t reg);
1521 ~ggml_hexagon_registry();
1522
1523 ggml_backend_device devices[GGML_HEXAGON_MAX_SESSIONS];
1524};
1525
1526struct ggml_hexagon_opqueue {
1527 // Shared buffer for storing batches
1528 ggml_hexagon_shared_buffer *shm_buf;
1529 size_t shm_blk_size;
1530 size_t depth;
1531
1532 using opvec = std::vector<htp_opnode>;
1533
1534 std::vector<opvec> op_cache; // per batch op cache
1535
1536 ggml_hexagon_opqueue(ggml_hexagon_session *sess, size_t batch_size, size_t depth) : depth(depth) {
1537 size_t n_bufs = HTP_OP_MAX_BUFS;
1538 size_t n_ops = batch_size;
1539 size_t n_tensors = std::min<size_t>(n_ops * 4 + HTP_OP_MAX_INPUTS + HTP_OP_MAX_OUTPUTS, HTP_OP_MAX_TENSORS);
1540
1541 size_t tr_size = 0;
1542 if (opt_profile == 3) {
1543 tr_size = (HTP_MAX_NTHREADS + 1) * opt_optrace * sizeof(htp_trace_desc);
1544 }
1545
1546 shm_blk_size = sizeof(htp_buf_desc) * n_bufs +
1547 sizeof(htp_tensor) * n_tensors +
1548 sizeof(htp_op_desc) * n_ops +
1549 sizeof(htp_prof_desc) * n_ops +
1550 tr_size;
1551
1552 shm_buf = new ggml_hexagon_shared_buffer(sess, shm_blk_size * depth, true /* pinned */);
1553
1554 op_cache.resize(depth);
1555
1556 if (opt_verbose) {
1557 GGML_LOG_INFO("ggml-hex: %s allocated opqueue : batch-size %zu depth %zu shm-size %zu shm-block-size %zu\n",
1558 sess->c_name(), batch_size, depth, shm_buf->size(), shm_blk_size);
1559 }
1560 }
1561
1562 ~ggml_hexagon_opqueue() {
1563 delete shm_buf;
1564 }
1565
1566 size_t shm_size() const { return shm_buf ? shm_buf->size() : 0; }
1567
1568 // push new batch
1569 bool push(htp_opbatch_req& req, dspqueue_buffer& dbuf, const ggml_hexagon_opbatch* op_batch, uint64_t seq) {
1570 static_assert(sizeof(htp_opbatch_req) % 8 == 0, "sizeof(htp_opbatch_req) must be multiple of 8");
1571 static_assert(sizeof(htp_opbatch_rsp) % 8 == 0, "sizeof(htp_opbatch_rsp) must be multiple of 8");
1572 static_assert(sizeof(htp_buf_desc) % 8 == 0, "sizeof(htp_buf_desc) must be multiple of 8");
1573 static_assert(sizeof(htp_tensor) % 8 == 0, "sizeof(htp_tensor) must be multiple of 8");
1574 static_assert(sizeof(htp_op_desc) % 8 == 0, "sizeof(htp_op_desc) must be multiple of 8");
1575 static_assert(sizeof(htp_prof_desc) % 8 == 0, "sizeof(htp_prof_desc) must be multiple of 8");
1576
1577 if (seq - shm_buf->sess->batch_rsp_seq > depth) { return false; }
1578
1579 const uint32_t slot = (uint32_t) ((seq - 1) % depth);
1580
1581 req.seq = seq;
1582 req.n_bufs = op_batch->n_bufs;
1583 req.n_tensors = op_batch->n_tens;
1584 req.n_ops = op_batch->n_ops;
1585
1586 if (opt_profile) {
1587 op_cache[slot].assign(op_batch->ops.begin(), op_batch->ops.begin() + req.n_ops);
1588 }
1589
1590 const size_t b_size = sizeof(htp_buf_desc) * req.n_bufs;
1591 const size_t t_size = sizeof(htp_tensor) * req.n_tensors;
1592 const size_t o_size = sizeof(htp_op_desc) * req.n_ops;
1593 const size_t p_size = sizeof(htp_prof_desc) * req.n_ops;
1594
1595 size_t tr_size = 0;
1596 if (opt_profile == 3) {
1597 req.n_traces = opt_optrace;
1598 tr_size = (HTP_MAX_NTHREADS + 1) * req.n_traces * sizeof(htp_trace_desc);
1599 } else {
1600 req.n_traces = 0;
1601 }
1602
1603 dbuf.ptr = shm_buf->base() + ((size_t) slot * shm_blk_size);
1604 dbuf.fd = shm_buf->fd();
1605 dbuf.flags = DSPQUEUE_BUFFER_FLAG_FLUSH_SENDER | DSPQUEUE_BUFFER_FLAG_INVALIDATE_RECIPIENT;
1606 dbuf.offset = (uint8_t*) dbuf.ptr - (uint8_t*) shm_buf->base();
1607 dbuf.size = b_size + t_size + o_size + p_size + tr_size;
1608
1609 GGML_ASSERT(dbuf.size <= shm_blk_size);
1610
1611 uint8_t * m_ptr = (uint8_t*) dbuf.ptr;
1612 uint8_t * b_ptr = m_ptr; m_ptr += b_size;
1613 uint8_t * t_ptr = m_ptr; m_ptr += t_size;
1614 uint8_t * o_ptr = m_ptr;
1615
1616 memcpy(b_ptr, (void *) op_batch->h_bufs.data(), b_size);
1617 memcpy(t_ptr, (void *) op_batch->h_tens.data(), t_size);
1618 memcpy(o_ptr, (void *) op_batch->h_ops.data(), o_size);
1619
1620 HEX_VERBOSE("ggml-hex: %s opqueue-push batch #%llu : n-bufs %u n-tensors %u n-ops %u vmem %zu : b-size %zu t-size %zu o-size %zu m-size %zu\n",
1621 shm_buf->sess->c_name(), (unsigned long long) req.seq, req.n_bufs, req.n_tensors, req.n_ops, op_batch->b_vmem,
1622 b_size, t_size, o_size, (size_t) dbuf.size);
1623
1624 if (opt_verbose > 1) {
1625 htp_buf_desc *b = (htp_buf_desc*) b_ptr;
1626 for (unsigned int i=0; i < req.n_bufs; i++) {
1627 GGML_LOG_DEBUG("ggml-hex: %s htp-buf #%u : fd %d base %p size %zu\n", shm_buf->sess->c_name(), i,
1628 b[i].fd, (void *) b[i].base, (size_t) b[i].size);
1629 }
1630 htp_tensor *t = (htp_tensor*) t_ptr;
1631 for (unsigned int i=0; i < req.n_tensors; i++) {
1632 GGML_LOG_DEBUG("ggml-hex: %s htp-tensor #%u : bi %u offset %llu size %u : %zu:%zu:%zu:%zu\n",
1633 shm_buf->sess->c_name(), i, t[i].bi, (unsigned long long) t[i].data, t[i].size,
1634 (size_t) t[i].ne[0], (size_t) t[i].ne[1], (size_t) t[i].ne[2], (size_t) t[i].ne[3]);
1635 }
1636 }
1637
1638 return true;
1639 }
1640
1641 void pop(htp_opbatch_rsp rsp, dspqueue_buffer dbuf) {
1642 const uint32_t slot = (uint32_t) ((rsp.seq - 1) % depth);
1643
1644 const size_t b_size = sizeof(htp_buf_desc) * rsp.n_bufs;
1645 const size_t t_size = sizeof(htp_tensor) * rsp.n_tensors;
1646 const size_t o_size = sizeof(htp_op_desc) * rsp.n_ops;
1647 const size_t p_size = sizeof(htp_prof_desc) * rsp.n_ops;
1648
1649 size_t tr_size = 0;
1650 uint32_t n_traces = 0;
1651 if (opt_profile == 3) {
1652 n_traces = opt_optrace;
1653 tr_size = (HTP_MAX_NTHREADS + 1) * n_traces * sizeof(htp_trace_desc);
1654 }
1655
1656 const size_t m_size = b_size + t_size + o_size + p_size + tr_size;
1657 GGML_ASSERT(m_size <= shm_blk_size);
1658
1659 HEX_VERBOSE("ggml-hex: %s opqueue-pop batch #%llu : n-bufs %u n-tensors %u n-ops %u : m-size %zu b-size %zu t-size %zu o-size %zu\n",
1660 shm_buf->sess->c_name(), (unsigned long long) rsp.seq, rsp.n_bufs, rsp.n_tensors, rsp.n_ops,
1661 (size_t) dbuf.size, b_size, t_size, o_size);
1662
1663 uint8_t * m_ptr = (uint8_t*) dbuf.ptr;
1664 uint8_t * p_ptr = m_ptr + (b_size + t_size + o_size);
1665
1666 if (rsp.n_ops > 0 && opt_profile) {
1667 auto & ops = op_cache[slot];
1668 GGML_ASSERT(rsp.n_ops <= ops.size());
1669
1670 const htp_prof_desc * pd = (const htp_prof_desc *) p_ptr;
1671 const htp_trace_desc * trace_events = nullptr;
1672 if (opt_profile == 3) {
1673 trace_events = (const htp_trace_desc *) (p_ptr + p_size);
1674 }
1675
1676 ggml_hexagon_dump_batch_prof(shm_buf->sess->c_name(), rsp);
1677
1678 for (uint32_t i = 0; i < rsp.n_ops; i++) {
1679 ggml_hexagon_dump_op_prof(shm_buf->sess->c_name(), ops[i], pd[i]);
1680 }
1681
1682 ggml_hexagon_dump_trace_events(shm_buf->sess->c_name(), rsp, trace_events, n_traces);
1683 }
1684 }
1685};
1686
1687void ggml_hexagon_session::flush_peers() {
1688 auto vpeers = std::move(virt_peers);
1689 virt_peers.clear();
1690 for (auto * peer : vpeers) {
1691 peer->flush_sync();
1692 }
1693
1694 auto ppeers = std::move(phys_peers);
1695 phys_peers.clear();
1696 for (auto * peer : ppeers) {
1697 peer->flush_async();
1698 }
1699
1700 for (auto & sub : this->mdev.sessions) {
1701 sub->flush_peers();
1702 }
1703}
1704
1705void ggml_hexagon_session::flush_async() {
1706 flush_peers();
1707 flush_batch();
1708}
1709
1710void ggml_hexagon_session::flush_pending(bool all) {
1711 for (auto & sub : this->mdev.sessions) {
1712 sub->flush_pending(all);
1713 if (sub->last_error > HTP_STATUS_OK) {
1714 this->last_error = sub->last_error.load();
1715 }
1716 }
1717
1718 while (this->batch_rsp_seq < this->batch_req_seq) {
1719 struct htp_opbatch_rsp rsp;
1720 uint32_t rsp_size;
1721 uint32_t flags;
1722
1723 struct dspqueue_buffer dbuf;
1724 uint32_t n_dbufs;
1725
1726 // Read response packet from queue
1727 const uint32_t timeo = opt_oppoll ? 0 : DSPQUEUE_TIMEOUT;
1728
1729 int err = dspqueue_read(this->queue, &flags, 1, &n_dbufs, &dbuf, sizeof(rsp), &rsp_size, (uint8_t *) &rsp, timeo);
1730 if (err == AEE_EEXPIRED || err == AEE_EWOULDBLOCK) {
1731 continue;
1732 }
1733
1734 if (err != 0) {
1735 GGML_ABORT("ggml-hex: dspqueue_read failed: 0x%08x\n", (unsigned) err);
1736 }
1737
1738 // Basic sanity checks
1739 if (rsp_size != sizeof(rsp) || n_dbufs != 1) {
1740 GGML_ABORT("ggml-hex: %s dspcall : bad response : size %u dspbufs %u\n", this->c_name(), rsp_size, n_dbufs);
1741 }
1742
1743 if (rsp.status > HTP_STATUS_OK) {
1744 GGML_LOG_ERROR("ggml-hex: %s dspcall : dsp-rsp %s\n", this->c_name(), status_to_str(rsp.status));
1745 this->last_error = rsp.status;
1746 for (auto & sub : this->mdev.sessions) {
1747 sub->last_error = rsp.status;
1748 }
1749 }
1750
1751 op_queue->pop(rsp, dbuf);
1752
1753 GGML_ASSERT(rsp.seq == this->batch_rsp_seq + 1);
1754 this->batch_rsp_seq = rsp.seq;
1755
1756 if (!all) break;
1757 }
1758}
1759
1760void ggml_hexagon_session::flush_sync(bool all) {
1761 flush_async();
1762 flush_pending(all);
1763}
1764
1765void ggml_hexagon_session::start_batch() {
1766 if (this->mdev.count > 1) {
1767 enqueue_mdev_group();
1768 }
1769}
1770
1771void ggml_hexagon_session::flush_batch(size_t min_ops) {
1772 if (op_batch->n_ops < min_ops) { return; }
1773
1774 op_batch->sort_buffers();
1775
1776 htp_opbatch_req req {};
1777 dspqueue_buffer dbuf{};
1778
1779 const uint64_t seq = ++this->batch_req_seq;
1780
1781 op_batch->update_mdev_group(this->mdev.idx);
1782
1783 if (!op_queue->push(req, dbuf, op_batch, seq)) {
1784 flush_pending(false);
1785 op_queue->push(req, dbuf, op_batch, seq);
1786 }
1787
1788 for (auto & sub : this->mdev.sessions) {
1789 htp_opbatch_req sub_req {};
1790 dspqueue_buffer sub_dbuf{};
1791
1792 sub->batch_req_seq = seq;
1793 op_batch->update_mdev_group(sub->mdev.idx);
1794
1795 if (!sub->op_queue->push(sub_req, sub_dbuf, op_batch, seq)) {
1796 sub->flush_pending(false);
1797 sub->op_queue->push(sub_req, sub_dbuf, op_batch, seq);
1798 }
1799
1800 HEX_VERBOSE("ggml-hex: %s queue-opbatch: %p size %u\n", sub->c_name(), sub_dbuf.ptr, sub_dbuf.size);
1801
1802 int err = dspqueue_write(sub->queue, 0, 1, &sub_dbuf, sizeof(sub_req), (const uint8_t*) &sub_req, DSPQUEUE_TIMEOUT);
1803 if (err != 0) {
1804 GGML_ABORT("ggml-hex: %s dspqueue_write failed: 0x%08x\n", sub->c_name(), (unsigned) err);
1805 }
1806 }
1807
1808 HEX_VERBOSE("ggml-hex: %s queue-opbatch: %p size %u\n", this->c_name(), dbuf.ptr, dbuf.size);
1809
1810 int err = dspqueue_write(this->queue, 0, 1, &dbuf, sizeof(req), (const uint8_t*) &req, DSPQUEUE_TIMEOUT);
1811 if (err != 0) {
1812 GGML_ABORT("ggml-hex: %s dspqueue_write failed: 0x%08x\n", this->c_name(), (unsigned) err);
1813 }
1814
1815 op_batch->reset();
1816}
1817
1818void ggml_hexagon_session::enqueue_op(const htp_opnode & node) {
1819 auto clone_tensor_buffer = [this](const ggml_tensor * t) {
1820 auto sbuf = this->mmap_tensor(t);
1821 if (!sbuf) return;
1822 if (sbuf->sess != this) {
1823 this->clone_buffer(sbuf);
1824 }
1825 for (auto & sub : this->mdev.sessions) {
1826 sub->clone_buffer(sbuf);
1827 }
1828 };
1829
1830 for (auto t : node.get_inputs()) {
1831 clone_tensor_buffer(t);
1832 }
1833 for (auto t : node.get_outputs()) {
1834 clone_tensor_buffer(t);
1835 }
1836
1837 const bool fits_tensors = op_batch->fit_tensors(node);
1838 if (opt_opfusion && fits_tensors && op_batch->try_fuse(node)) {
1839 return;
1840 }
1841
1842 if (op_batch->full() || !fits_tensors) {
1843 flush_async();
1844 }
1845
1846 if (op_batch->empty()) {
1847 start_batch();
1848 if (!op_batch->fit_tensors(node)) {
1849 GGML_ABORT("ggml-hex: %s op does not fit into empty batch (vmem/tensor/buffer limit exceeded)\n", c_name());
1850 }
1851 }
1852
1853 op_batch->add_op(node);
1854}
1855
1856void ggml_hexagon_session::enqueue_mdev_group() {
1857 htp_opnode group_node(HTP_OP_MDEV_GROUP);
1858
1859 ggml_tensor dummy_t = make_fence_tensor(this->mdev_fence_slot, this->mdev.count);
1860 dummy_t.op_params[0] = (int32_t) this->mdev.idx;
1861
1862 ggml_tensor * node = group_node.add_dummy(dummy_t);
1863 node->src[0] = node;
1864 group_node.init(node);
1865 group_node.outputs.clear();
1866
1867 for (auto & sub : this->mdev.sessions) {
1868 sub->clone_buffer(this->fence_buf);
1869 }
1870
1871 op_batch->add_op(group_node);
1872}
1873
1874void ggml_hexagon_session::enqueue_cpy(const ggml_tensor * src, ggml_tensor * dst, const ggml_tensor * sync_tensor, uint32_t fence_seq) {
1875 const bool with_fence = sync_tensor != nullptr;
1876 htp_opnode cpy_node(with_fence ? HTP_OP_CPY_FENCE : HTP_OP_CPY);
1877
1878 ggml_tensor* node = cpy_node.add_dummy(*dst);
1879 node->op = GGML_OP_CPY;
1880 node->src[0] = const_cast<ggml_tensor *>(src);
1881 node->src[1] = with_fence ? cpy_node.add_dummy(*sync_tensor) : nullptr;
1882 if (with_fence) {
1883 node->op_params[0] = (int32_t) fence_seq;
1884 }
1885
1886 cpy_node.init(node);
1887 const bool ok = htp_kparams_solve(this, node, cpy_node.kernel_params);
1888 if (ok && !with_fence && cpy_node.kparams<htp_copy_kernel_params>()->total_elems == 0) {
1889 return;
1890 }
1891 this->enqueue_op(cpy_node);
1892}
1893
1894void ggml_hexagon_session::enqueue_fence(const ggml_tensor * sync_tensor, uint32_t fence_seq, bool wait) {
1895 htp_opnode sync_node(HTP_OP_FENCE);
1896
1897 ggml_tensor* node = sync_node.add_dummy(*sync_tensor);
1898 node->op = GGML_OP_NONE;
1899 node->src[0] = node;
1900 node->op_params[0] = (int32_t) fence_seq;
1901 node->op_params[1] = wait ? 0 : 1;
1902
1903 sync_node.init(node);
1904 this->enqueue_op(sync_node);
1905}
1906
1907void ggml_hexagon_session::enqueue_allreduce(
1908 const ggml_tensor * dst,
1909 const std::vector<const ggml_tensor *> & src_tensors,
1910 const std::vector<const ggml_tensor *> & sync_tensors,
1911 uint32_t rank,
1912 uint32_t n_ranks,
1913 uint32_t fence_seq_entry,
1914 uint32_t fence_seq_exit
1915) {
1916 htp_opnode ar_node(HTP_OP_ALLREDUCE);
1917
1918 ggml_tensor* node = ar_node.add_dummy(*dst);
1919 node->op = GGML_OP_NONE;
1920 node->op_params[0] = (int32_t) fence_seq_entry;
1921 node->op_params[1] = (int32_t) fence_seq_exit;
1922
1923 ar_node.init(node);
1924
1925 ar_node.inputs.clear();
1926 for (size_t i = 0; i < src_tensors.size(); i++) {
1927 ar_node.inputs.push_back(src_tensors[i]);
1928 }
1929 for (size_t i = 0; i < sync_tensors.size(); i++) {
1930 ar_node.inputs.push_back(ar_node.add_dummy(*sync_tensors[i]));
1931 }
1932
1933 ar_node.outputs.clear();
1934 for (size_t i = 0; i < src_tensors.size(); i++) {
1935 ar_node.outputs.push_back(src_tensors[i]);
1936 }
1937
1938 htp_kparams_solve_allreduce(
1939 this, dst, rank, n_ranks, false, false, /*is_shard_ok=*/ false,
1940 ar_node.kparams<htp_allreduce_kernel_params>());
1941
1942 this->enqueue_op(ar_node);
1943}
1944
1945ggml_hexagon_shared_buffer * ggml_hexagon_session::mmap_tensor(const ggml_tensor * t) {
1946 if (!t) return nullptr;
1947
1948 auto sbuf = static_cast<ggml_hexagon_shared_buffer *>(t->buffer->context);
1949 if (!sbuf->mapped) {
1950 const bool is_weight = ggml_backend_buffer_get_usage(t->buffer) == GGML_BACKEND_BUFFER_USAGE_WEIGHTS;
1951 const bool extended = opt_dma64 && is_weight;
1952 sbuf->mmap(extended);
1953 }
1954 return sbuf;
1955}
1956
1957bool ggml_hexagon_session::clone_buffer(const ggml_hexagon_shared_buffer * sbuf)
1958{
1959 GGML_ASSERT(sbuf && sbuf->mem);
1960 if (sbuf->sess == this) return true;
1961
1962 auto mem = sbuf->mem;
1963 int fd = mem->fd;
1964
1965 GGML_ASSERT(fd >= 0);
1966
1967 if (this->cloned_buffers.find(fd) != this->cloned_buffers.end()) return true;
1968
1969 GGML_ASSERT(sbuf->mapped);
1970
1971 HEX_VERBOSE("ggml-hex: %s clone-buffer: %s base %p size %zu fd %d\n", this->name.c_str(),
1972 sbuf->c_name(), sbuf->base(), sbuf->size(), fd);
1973
1974 auto clone = std::make_unique<ggml_hexagon_shared_buffer>(this, *sbuf);
1975 try {
1976 clone->mmap(sbuf->extended);
1977 } catch (const std::exception & exc) {
1978 GGML_LOG_ERROR("ggml-hex: %s lazy mapping of buffer context failed: %s\n", this->c_name(), exc.what());
1979 return false;
1980 }
1981
1982 this->cloned_buffers[fd] = std::move(clone);
1983 mem->mapped_clones.insert(this);
1984 return true;
1985}
1986
1987void ggml_hexagon_session::release_buffer(const ggml_hexagon_shared_buffer * sbuf) {
1988 GGML_ASSERT(sbuf && sbuf->mem);
1989
1990 auto mem = sbuf->mem;
1991 int fd = mem->fd;
1992
1993 GGML_ASSERT(fd >= 0);
1994
1995 auto it = this->cloned_buffers.find(fd);
1996 if (it != this->cloned_buffers.end()) {
1997 auto clone = std::move(it->second);
1998 this->cloned_buffers.erase(it);
1999 }
2000 mem->mapped_clones.erase(this);
2001}
2002
2003void ggml_hexagon_session::unclone_buffer(const ggml_hexagon_shared_buffer * sbuf) {
2004 GGML_ASSERT(sbuf && sbuf->mem);
2005
2006 auto mem = sbuf->mem;
2007 std::vector<ggml_hexagon_session *> sessions(mem->mapped_clones.begin(), mem->mapped_clones.end());
2008
2009 for (auto * sess : sessions) {
2010 sess->release_buffer(sbuf);
2011 }
2012}
2013
2014static size_t ggml_hexagon_measure_max_vmem(ggml_hexagon_session *sess) {
2015 // Allocate a bunch pinned buffers till failure.
2016 // This is kind of expensive but handy for figuring out exactly how much we can mmap on a specific device.
2017 // Typically we're going to allocate all/most of these buffers anyway for the model weights.
2018
2019 std::vector<ggml_hexagon_shared_buffer *> sbufs;
2020
2021 const size_t MiB = 1024 * 1024;
2022 const size_t GiB = MiB * 1024;
2023
2024 size_t vmem = 0;
2025 size_t step = 256u * MiB;
2026
2027 try {
2028 sbufs.push_back(new ggml_hexagon_shared_buffer(sess, GiB, true)); vmem += GiB;
2029 sbufs.push_back(new ggml_hexagon_shared_buffer(sess, GiB, true)); vmem += GiB;
2030 sbufs.push_back(new ggml_hexagon_shared_buffer(sess, GiB, true)); vmem += GiB;
2031
2032 while (1) {
2033 sbufs.push_back(new ggml_hexagon_shared_buffer(sess, step, true));
2034 vmem += step;
2035 }
2036 } catch (...) { }
2037
2038 for (auto b : sbufs) { delete b; }
2039
2040 return vmem - step; // backoff to account for overhead from internal mappings
2041}
2042
2043void ggml_hexagon_session::allocate(const ggml_hexagon_device_config & config) noexcept(false) {
2044 int phys_idx = config.physical_idx;
2045 int virt_idx = config.virtual_idx;
2046
2047 this->valid_session = false;
2048 this->valid_handle = false;
2049 this->valid_queue = false;
2050 this->valid_iface = false;
2051
2052 this->name = config.name;
2053 this->phys_idx = phys_idx;
2054 this->virt_idx = virt_idx;
2055 this->domain_id = config.domain_id;
2056 this->session_id = 0;
2057 this->batch_req_seq = 0;
2058 this->batch_rsp_seq = 0;
2059 this->last_error = HTP_STATUS_OK;
2060
2061 GGML_LOG_DEBUG("ggml-hex: %s allocating new session : domain %u phys-idx %u virt-idx %u\n", this->name.c_str(), this->domain_id, phys_idx, virt_idx);
2062
2063 if (config.domain_id < 0 || config.domain_name.empty()) {
2064 GGML_LOG_ERROR("ggml-hex: %s: invalid physical CDSP core %d\n", config.name.c_str(), config.physical_idx);
2065 throw std::runtime_error("ggml-hex: invalid physical CDSP core");
2066 }
2067
2068 const std::string & dom_name = config.domain_name;
2069
2070 // Create new session if virtual_idx > 0
2071 if (virt_idx > 0) {
2072 struct remote_rpc_reserve_new_session n {};
2073 n.domain_name_len = dom_name.size();
2074 n.domain_name = const_cast<char *>(dom_name.c_str());
2075 n.session_name = const_cast<char *>(this->name.c_str());
2076 n.session_name_len = this->name.size();
2077 n.session_id = virt_idx;
2078
2079 int err = remote_session_control(FASTRPC_RESERVE_NEW_SESSION, (void *) &n, sizeof(n));
2080 if (err != AEE_SUCCESS) {
2081 GGML_LOG_ERROR("ggml-hex: %s failed to reserve new session (physical %d, virtual %d) : error 0x%x\n",
2082 this->c_name(), phys_idx, virt_idx, err);
2083 throw std::runtime_error("ggml-hex: remote_session_control(new-sess) failed (see log for details)");
2084 }
2085
2086 // Save the IDs
2087 this->session_id = n.session_id;
2088 this->domain_id = n.effective_domain_id;
2089 this->valid_session = true;
2090 } else {
2091 struct remote_rpc_effective_domain_id eff {};
2092 eff.domain_name = const_cast<char *>(dom_name.c_str());
2093 eff.domain_name_len = dom_name.size();
2094 eff.session_id = 0;
2095
2096 int err = remote_session_control(FASTRPC_GET_EFFECTIVE_DOMAIN_ID, (void *) &eff, sizeof(eff));
2097 if (err == AEE_SUCCESS) {
2098 this->domain_id = eff.effective_domain_id;
2099 } else {
2100 GGML_LOG_DEBUG("ggml-hex: %s FASTRPC_GET_EFFECTIVE_DOMAIN_ID returned 0x%x, using domain_id %d\n",
2101 this->name.c_str(), err, this->domain_id);
2102 }
2103 }
2104
2105 // Enable unsigned modules
2106 {
2107 struct remote_rpc_control_unsigned_module u;
2108 u.domain = this->domain_id;
2109 u.enable = 1;
2110 int err = remote_session_control(DSPRPC_CONTROL_UNSIGNED_MODULE, (void *) &u, sizeof(u));
2111 if (err != AEE_SUCCESS) {
2112 GGML_LOG_ERROR("ggml-hex: %s failed to enable unsigned PD : error 0x%x\n", this->c_name(), err);
2113 throw std::runtime_error("ggml-hex: remote_session_control(unsign) failed (see log for details)");
2114 }
2115 }
2116
2117 char session_uri[256];
2118 {
2119 char htp_uri[256];
2120 snprintf(htp_uri, sizeof(htp_uri), "file:///libggml-htp-v%u.so?htp_iface_skel_handle_invoke&_modver=1.0", opt_arch);
2121
2122 struct remote_rpc_get_uri u = {};
2123 u.session_id = this->session_id;
2124 u.domain_name = const_cast<char *>(dom_name.c_str());
2125 u.domain_name_len = dom_name.size();
2126 u.module_uri = const_cast<char *>(htp_uri);
2127 u.module_uri_len = strlen(htp_uri);
2128 u.uri = session_uri;
2129 u.uri_len = sizeof(session_uri);
2130
2131 int err = remote_session_control(FASTRPC_GET_URI, (void *) &u, sizeof(u));
2132 if (err != AEE_SUCCESS) {
2133 snprintf(session_uri, sizeof(session_uri), "%s&_dom=%s&_session=%u",
2134 htp_uri, dom_name.c_str(), this->session_id);
2135
2136 GGML_LOG_WARN("ggml-hex: %s failed to get URI (physical %d, virtual %d) : error 0x%x. Falling back to single session URI: %s\n",
2137 this->c_name(), phys_idx, virt_idx, err, session_uri);
2138 }
2139 }
2140
2141 // Open session
2142 int err = htp_iface_open(session_uri, &this->handle);
2143 if (err != AEE_SUCCESS) {
2144 GGML_LOG_ERROR("ggml-hex: %s failed to open session : uri %s error 0x%x\n", this->c_name(), session_uri, err);
2145 throw std::runtime_error("ggml-hex: failed to open session (see log for details)");
2146 }
2147
2148 this->valid_handle = true;
2149
2150 // Query HW info and resolve session options
2151 {
2152 unsigned int hw_n_threads = 0;
2153 unsigned int hw_n_hvx = 0;
2154 unsigned int hw_n_hmx = 0;
2155 unsigned long long hw_vtcm_size = 0;
2156 int hw_err = htp_iface_hwinfo(this->handle, &hw_n_threads, &hw_n_hvx, &hw_n_hmx, &hw_vtcm_size);
2157 if (hw_err == 0) {
2158 const uint32_t max_n_threads = (std::min)((uint32_t) HTP_MAX_NTHREADS, (uint32_t) hw_n_threads);
2159 this->n_threads = opt_nhvx > 0 ? (uint32_t) (std::min)(opt_nhvx, (size_t) max_n_threads) : max_n_threads;
2160 this->n_hvx = this->n_threads;
2161 this->n_hmx = (opt_nhmx != 0) ? (uint32_t)hw_n_hmx : 0;
2162 this->vtcm_size = (uint64_t)hw_vtcm_size;
2163 if (opt_vtcm_size > 0) {
2164 if (opt_vtcm_size > hw_vtcm_size) {
2165 GGML_LOG_WARN("ggml-hex: %s VTCM override %zu exceeds HW size %llu\n", this->c_name(), opt_vtcm_size, hw_vtcm_size);
2166 }
2167 this->vtcm_size = opt_vtcm_size;
2168 }
2169 GGML_LOG_INFO("ggml-hex: %s hwinfo: threads %u, hvx %u, hmx %u, vtcm %llu MB\n",
2170 this->c_name(), this->n_threads, this->n_hvx, this->n_hmx,
2171 (unsigned long long)(this->vtcm_size / (1024 * 1024)));
2172 } else {
2173 GGML_LOG_WARN("ggml-hex: %s failed to query hwinfo (0x%x), using defaults\n", this->c_name(), hw_err);
2174 const uint32_t default_n_threads = (std::min)(8u, (uint32_t) HTP_MAX_NTHREADS);
2175 this->n_threads = opt_nhvx > 0 ? (uint32_t) (std::min)(opt_nhvx, (size_t) HTP_MAX_NTHREADS) : default_n_threads;
2176 this->n_hvx = this->n_threads;
2177 this->n_hmx = (opt_nhmx != 0) ? 1 : 0;
2178 this->vtcm_size = opt_vtcm_size > 0 ? opt_vtcm_size : 8 * 1024 * 1024;
2179 }
2180 }
2181
2182 // Enable FastRPC QoS mode
2183 {
2184 struct remote_rpc_control_latency l;
2185 l.enable = 1;
2186
2187 int err = remote_handle64_control(this->handle, DSPRPC_CONTROL_LATENCY, (void *) &l, sizeof(l));
2188 if (err != 0) {
2189 GGML_LOG_WARN("ggml-hex: failed to enable fastrpc QOS mode: 0x%08x\n", (unsigned) err);
2190 }
2191 }
2192
2193 GGML_LOG_INFO("ggml-hex: %s new session : session-id %d domain-id %d uri %s handle 0x%lx\n", this->c_name(),
2194 this->session_id, this->domain_id, session_uri, (unsigned long) this->handle);
2195
2196 const size_t req_q_size = (sizeof(htp_opbatch_req) * opt_opqueue * 2) + 1024;
2197 const size_t rsp_q_size = (sizeof(htp_opbatch_rsp) * opt_opqueue * 2) + 1024;
2198
2199 // Now let's setup the DSP queue
2200 err = dspqueue_create(this->domain_id,
2201 0, // Flags
2202 req_q_size, // Request queue size (in bytes)
2203 rsp_q_size, // Response queue size (in bytes)
2204 nullptr, // Read packet callback (we handle reads explicitly)
2205 nullptr, // Error callback (we handle errors during reads)
2206 (void *) this, // Callback context
2207 &queue);
2208 if (err != 0) {
2209 GGML_LOG_ERROR("ggml-hex: %s dspqueue_create failed: 0x%08x\n", this->name.c_str(), (unsigned) err);
2210 throw std::runtime_error("ggml-hex: failed to create dspqueue (see log for details)");
2211 }
2212
2213 this->valid_queue = true;
2214
2215 // Export queue for use on the DSP
2216 err = dspqueue_export(queue, &this->queue_id);
2217 if (err != 0) {
2218 GGML_LOG_ERROR("ggml-hex: dspqueue_export failed: 0x%08x\n", (unsigned) err);
2219 throw std::runtime_error("ggml-hex: dspqueue export failed (see log for details)");
2220 }
2221
2222 if (opt_etm) {
2223 err = htp_iface_etm(this->handle, 1);
2224 if (err != 0) {
2225 GGML_LOG_ERROR("ggml-hex: failed to enable ETM tracing: 0x%08x\n", (unsigned) err);
2226 }
2227 }
2228
2229 // Allocate buffers and state for op batching
2230 this->op_queue = new ggml_hexagon_opqueue(this, opt_opbatch, opt_opqueue);
2231
2232 this->fence_buf = new ggml_hexagon_fence_buffer(this, &dev_ctx->fence_buffer_type, 64 * 1024);
2233 if (this->mdev.count > 1) {
2234 this->mdev_fence_slot = this->alloc_fence(this->mdev.count);
2235 }
2236
2237 if (!opt_vmem) {
2238 opt_vmem = ggml_hexagon_measure_max_vmem(this);
2239 GGML_LOG_INFO("ggml-hex: %s measured max vmem %zu\n", this->c_name(), opt_vmem);
2240 }
2241 const size_t shm_size = this->op_queue->shm_size();
2242 this->max_vmem = (opt_vmem > shm_size) ? (opt_vmem - shm_size) : opt_vmem;
2243
2244 this->op_batch = new ggml_hexagon_opbatch(this, opt_opbatch, this->max_vmem);
2245
2246 // Start dspqueue/opbatch processing
2247 err = htp_iface_start(this->handle, this->session_id, this->queue_id, this->n_threads, opt_nhmx, opt_vtcm_size, this->max_vmem,
2248 (uint32_t) opt_power_mode);
2249 if (err != 0) {
2250 GGML_LOG_ERROR("ggml-hex: %s failed to start session: 0x%08x\n", this->c_name(), (unsigned) err);
2251 throw std::runtime_error("ggml-hex: iface start failed (see log for details)");
2252 }
2253 this->valid_iface = true;
2254 GGML_LOG_INFO("ggml-hex: %s power mode: %s\n", this->c_name(), htp_power_mode_to_str(opt_power_mode));
2255
2256 if (opt_profile) {
2257 htp_iface_pmu_conf pmu_conf{};
2258 std::copy(opt_pmu_evt.begin(), opt_pmu_evt.end(), pmu_conf.events);
2259
2260 err = htp_iface_profiler(this->handle, opt_profile, &pmu_conf);
2261 if (err != 0) {
2262 GGML_LOG_ERROR("ggml-hex: failed to enable profiling: 0x%08x\n", (unsigned) err);
2263 }
2264 }
2265}
2266
2267void ggml_hexagon_session::release() noexcept(true) {
2268 GGML_LOG_INFO("ggml-hex: releasing session: %s\n", this->name.c_str());
2269
2270 this->mdev.sessions.clear();
2271
2272 int err;
2273
2274 if (this->valid_iface) {
2275 // Stop dspqueue/opbatch processing
2276 err = htp_iface_stop(this->handle);
2277 if (err != 0) {
2278 GGML_ABORT("ggml-hex: htp_iface_stop failed: 0x%08x\n", (unsigned) err);
2279 }
2280 }
2281
2282 delete this->op_batch;
2283 delete this->op_queue;
2284 for (auto & it : this->cpy_fence_slots) {
2285 free_fence((void *) it.second, 1);
2286 }
2287 this->cpy_fence_slots.clear();
2288
2289 if (this->fence_buf) {
2290 unclone_buffer(this->fence_buf);
2291 delete this->fence_buf;
2292 this->fence_buf = nullptr;
2293 }
2294 while (!this->cloned_buffers.empty()) {
2295 release_buffer(this->cloned_buffers.begin()->second.get());
2296 }
2297
2298 if (opt_etm) {
2299 err = htp_iface_etm(this->handle, 0);
2300 if (err != 0) {
2301 GGML_LOG_ERROR("ggml-hex: warn : failed to disable ETM tracing: 0x%08x\n", (unsigned) err);
2302 }
2303 }
2304
2305 if (opt_profile) {
2306 htp_iface_pmu_conf pmu_conf{};
2307 err = htp_iface_profiler(this->handle, 0, &pmu_conf);
2308 if (err != 0) {
2309 GGML_LOG_ERROR("ggml-hex: warn : failed to disable profiling: 0x%08x\n", (unsigned) err);
2310 }
2311 }
2312
2313 if (this->valid_queue) {
2314 err = dspqueue_close(queue);
2315 if (err != 0) {
2316 GGML_ABORT("ggml-hex: dspqueue_close failed: 0x%08x\n", (unsigned) err);
2317 }
2318 }
2319
2320 if (this->valid_handle) {
2321 htp_iface_close(this->handle);
2322 }
2323}
2324
2325ggml_hexagon_session::ggml_hexagon_session(const ggml_hexagon_device_config & config, ggml_backend_dev_t dev, uint32_t mdev_idx, uint32_t mdev_count) noexcept(false) {
2326 this->dev = dev;
2327 this->dev_ctx = static_cast<ggml_backend_hexagon_device_context *>(dev->context);
2328 this->mdev.idx = mdev_idx;
2329 this->mdev.count = mdev_count > 0 ? mdev_count : (uint32_t) (1 + config.mdev_group.size());
2330 op_batch = nullptr;
2331 op_queue = nullptr;
2332 fence_buf = nullptr;
2333 fence_seq = ((uintptr_t)this) & 0xFFFF;
2334
2335 try {
2336 allocate(config);
2337 if (this->mdev.idx == 0 && !config.mdev_group.empty()) {
2338 for (size_t i = 0; i < config.mdev_group.size(); i++) {
2339 this->mdev.sessions.push_back(std::make_unique<ggml_hexagon_session>(
2340 config.mdev_group[i], this->dev, (uint32_t) (i + 1), this->mdev.count));
2341 }
2342 }
2343 } catch (const std::exception & exc) {
2344 release();
2345 throw;
2346 }
2347}
2348
2349ggml_hexagon_session::~ggml_hexagon_session() noexcept(true) {
2350 release();
2351}
2352
2353// ** backend interface
2354
2355static const char * ggml_backend_hexagon_name(ggml_backend_t backend) {
2356 auto sess = static_cast<ggml_hexagon_session *>(backend->context);
2357 return sess->c_name();
2358}
2359
2360static void ggml_backend_hexagon_free(ggml_backend_t backend) {
2361 // we just need to delete the backend here
2362 // the sessions are allocated & freed as part of the registry
2363 delete backend;
2364}
2365
2366static inline bool op_is_compute(ggml_tensor *node)
2367{
2368 return !ggml_op_is_empty(node->op) && !ggml_is_empty(node) && (node->flags & GGML_TENSOR_FLAG_COMPUTE);
2369}
2370
2371static ggml_status ggml_backend_hexagon_graph_compute(ggml_backend_t backend, ggml_cgraph * graph) {
2372 auto sess = static_cast<ggml_hexagon_session *>(backend->context);
2373
2374 if (sess->last_error > HTP_STATUS_OK) {
2375 return GGML_STATUS_FAILED;
2376 }
2377
2378 HEX_VERBOSE("ggml-hex: %s graph-compute n_nodes %d\n", sess->c_name(), graph->n_nodes);
2379
2380 const std::vector<htp_opnode> * nodes_ptr = nullptr;
2381 std::vector<htp_opnode> computed_nodes;
2382
2383 bool cache_hit = (graph->uid != 0 && sess->cached_uid == graph->uid);
2384 if (cache_hit) {
2385 nodes_ptr = &sess->cached_nodes;
2386 } else {
2387 htp_fusion_tag_graph(graph);
2388
2389 computed_nodes.reserve(graph->n_nodes);
2390
2391 for (int i = 0; i < graph->n_nodes; ++i) {
2392 ggml_tensor * n = graph->nodes[i];
2393 if (!op_is_compute(n)) {
2394 continue;
2395 }
2396
2397 const htp_op_code opcode = htp_op_remap(n);
2398 if (opcode == HTP_OP_INVALID) {
2399 GGML_ABORT("\nggml-hex: graph-compute %s is not supported\n", ggml_op_desc(n));
2400 }
2401
2402 htp_opnode node(opcode, n);
2403 if (node.opcode == HTP_OP_MUL_MAT || node.opcode == HTP_OP_MUL_MAT_ID || node.opcode == HTP_OP_GET_ROWS) {
2404 ggml_tensor * src0 = node.node->src[0];
2405 if (htp_needs_repack(src0)) {
2406 HEX_VERBOSE("ggml-hex: %s rt-repack %s|size %zu\n", sess->c_name(), htp_format_tensor(src0, HTP_OPFMT_TENSOR).c_str(), ggml_nbytes(src0));
2407 std::vector<uint8_t> raw(ggml_nbytes(src0));
2408 memcpy(raw.data(), src0->data, raw.size());
2409 htp_repack_tensor_tiled(src0, raw.data(), raw.size());
2410 auto * extra = (htp_tensor_extra *) src0->extra;
2411 extra->flags |= HTP_TENSOR_TILED;
2412 }
2413 }
2414
2415 GGML_ASSERT(htp_kparams_solve(sess, node));
2416 if (node.opcode == HTP_OP_CPY && node.kparams<htp_copy_kernel_params>()->total_elems == 0) {
2417 continue;
2418 }
2419
2420 computed_nodes.push_back(std::move(node));
2421 }
2422
2423 if (graph->uid != 0) {
2424 sess->cached_uid = graph->uid;
2425 sess->cached_nodes = std::move(computed_nodes);
2426 nodes_ptr = &sess->cached_nodes;
2427 } else {
2428 nodes_ptr = &computed_nodes;
2429 }
2430 }
2431
2432 for (const auto & node : *nodes_ptr) {
2433 sess->enqueue_op(node);
2434 }
2435
2436 if (sess->last_error > HTP_STATUS_OK) {
2437 return GGML_STATUS_FAILED;
2438 }
2439
2440 return GGML_STATUS_SUCCESS;
2441}
2442
2443static void ggml_backend_hexagon_synchronize(ggml_backend_t backend) {
2444 auto sess = static_cast<ggml_hexagon_session *>(backend->context);
2445
2446 HEX_VERBOSE("ggml-hex: %s synchronize\n", sess->c_name());
2447
2448 // Wait until all pending ops complete
2449 sess->flush_sync();
2450 if (sess->last_error > HTP_STATUS_OK) {
2451 GGML_ABORT("ggml-hex: %s synchronize failed : dsp-error %s\n", sess->c_name(), status_to_str(sess->last_error));
2452 }
2453}
2454
2455enum ggml_hexagon_mem_range_type {
2456 HEXAGON_MEM_RANGE_TYPE_SRC,
2457 HEXAGON_MEM_RANGE_TYPE_DST,
2458};
2459
2460struct ggml_hexagon_mem_range {
2461 uint64_t pb;
2462 uint64_t p0;
2463 uint64_t p1;
2464 ggml_hexagon_mem_range_type pt;
2465};
2466
2467struct ggml_hexagon_mem_ranges {
2468 std::vector<ggml_hexagon_mem_range> ranges;
2469
2470 void reset() {
2471 ranges.clear();
2472 }
2473
2474 void add(const ggml_hexagon_mem_range & mr) {
2475 ranges.push_back(mr);
2476 }
2477
2478 bool check(const ggml_hexagon_mem_range & mr) const {
2479 for (const auto & cmp : ranges) {
2480 if (mr.pb != cmp.pb) {
2481 continue;
2482 }
2483 if (mr.pt == HEXAGON_MEM_RANGE_TYPE_SRC && cmp.pt == HEXAGON_MEM_RANGE_TYPE_SRC) {
2484 continue;
2485 }
2486 if (mr.p0 < cmp.p1 && mr.p1 > cmp.p0) {
2487 return false;
2488 }
2489 }
2490 return true;
2491 }
2492};
2493
2494static ggml_hexagon_mem_range ggml_hexagon_mem_range_from_tensor(const ggml_tensor * tensor, ggml_hexagon_mem_range_type pt) {
2495 const ggml_tensor * base = tensor->view_src ? tensor->view_src : tensor;
2496 ggml_hexagon_mem_range mr;
2497 if (tensor->buffer) {
2498 mr = {
2499 /*.pb =*/ (uint64_t) tensor->buffer,
2500 /*.p0 =*/ (uint64_t) tensor->data,
2501 /*.p1 =*/ (uint64_t) tensor->data + ggml_backend_buft_get_alloc_size(tensor->buffer->buft, tensor),
2502 /*.pt =*/ pt,
2503 };
2504 } else {
2505 mr = {
2506 /*.pb =*/ (uint64_t) base,
2507 /*.p0 =*/ 0,
2508 /*.p1 =*/ 1024,
2509 /*.pt =*/ pt,
2510 };
2511 }
2512 return mr;
2513}
2514
2515struct node_info {
2516 ggml_tensor * node;
2517 htp_opvec<ggml_tensor *, HTP_OP_MAX_FUSED> fused;
2518
2519 const ggml_tensor * dst() const { return fused.empty() ? node : fused.back(); }
2520
2521 bool is_empty() const {
2522 return ggml_op_is_empty(node->op);
2523 }
2524
2525 void add_fused(ggml_tensor * t) {
2526 fused.push_back(t);
2527 }
2528};
2529
2530static void ggml_hexagon_mem_ranges_add_node(ggml_hexagon_mem_ranges & mrs, const node_info & node) {
2531 if (node.is_empty()) return;
2532
2533 for (int i = 0; i < GGML_MAX_SRC; i++) {
2534 if (node.node->src[i]) {
2535 mrs.add(ggml_hexagon_mem_range_from_tensor(node.node->src[i], HEXAGON_MEM_RANGE_TYPE_SRC));
2536 }
2537 }
2538 for (const auto * fused : node.fused) {
2539 for (int i = 0; i < GGML_MAX_SRC; i++) {
2540 if (fused->src[i]) {
2541 mrs.add(ggml_hexagon_mem_range_from_tensor(fused->src[i], HEXAGON_MEM_RANGE_TYPE_SRC));
2542 }
2543 }
2544 }
2545 mrs.add(ggml_hexagon_mem_range_from_tensor(node.dst(), HEXAGON_MEM_RANGE_TYPE_DST));
2546}
2547
2548static bool ggml_hexagon_mem_ranges_check_node(const ggml_hexagon_mem_ranges & mrs, const node_info & node) {
2549 if (node.is_empty()) return true;
2550
2551 for (int i = 0; i < GGML_MAX_SRC; i++) {
2552 if (node.node->src[i]) {
2553 if (!mrs.check(ggml_hexagon_mem_range_from_tensor(node.node->src[i], HEXAGON_MEM_RANGE_TYPE_SRC))) {
2554 return false;
2555 }
2556 }
2557 }
2558 for (const auto * fused : node.fused) {
2559 for (int i = 0; i < GGML_MAX_SRC; i++) {
2560 if (fused->src[i]) {
2561 if (!mrs.check(ggml_hexagon_mem_range_from_tensor(fused->src[i], HEXAGON_MEM_RANGE_TYPE_SRC))) {
2562 return false;
2563 }
2564 }
2565 }
2566 }
2567 return mrs.check(ggml_hexagon_mem_range_from_tensor(node.dst(), HEXAGON_MEM_RANGE_TYPE_DST));
2568}
2569
2570static std::vector<int> ggml_hexagon_graph_optimize_reorder(const std::vector<node_info> & nodes) {
2571 const int n = nodes.size();
2572
2573 std::vector<int> res;
2574 res.reserve(n);
2575
2576 std::vector<bool> used(n, false);
2577
2578 ggml_hexagon_mem_ranges mrs;
2579
2580 // The main goal here is to stack the MUL_MAT ops with the same src1 input.
2581 // This allows us to reuse dynamically quantized src1 in VTCM.
2582
2583 for (int i0 = 0; i0 < n; i0++) {
2584 if (used[i0]) {
2585 continue;
2586 }
2587
2588 const auto & node0 = nodes[i0];
2589
2590 if (!htp_fusion_can_stack(node0.node)) {
2591 res.push_back(i0);
2592 used[i0] = true;
2593 continue;
2594 }
2595
2596 // that many nodes forward to search for stackable nodes that can reuse VTCM
2597 constexpr int N_FORWARD = 64;
2598
2599 htp_opvec<int, N_FORWARD> stack;
2600 stack.push_back(i0);
2601
2602 mrs.reset();
2603
2604 for (int i1 = i0 + 1; i1 < i0 + N_FORWARD && i1 < n; i1++) {
2605 if (used[i1]) {
2606 continue;
2607 }
2608
2609 const auto & node1 = nodes[i1];
2610
2611 if (htp_fusion_can_stack(node0.node, node1.node) && ggml_hexagon_mem_ranges_check_node(mrs, node1)) {
2612 stack.push_back(i1);
2613 } else {
2614 ggml_hexagon_mem_ranges_add_node(mrs, node1);
2615 }
2616 }
2617
2618 for (int idx : stack) {
2619 res.push_back(idx);
2620 used[idx] = true;
2621 }
2622 }
2623
2624 return res;
2625}
2626
2627static void ggml_backend_hexagon_graph_optimize(ggml_backend_t backend, ggml_cgraph * gf, ggml_backend_graph_optimize_params * params) {
2628 GGML_UNUSED(params);
2629
2630 const int n = gf->n_nodes;
2631
2632 std::vector<node_info> nodes;
2633 nodes.reserve(gf->n_nodes);
2634
2635 // Pack nodes for reordering
2636 for (int i = 0; i < n; i++) {
2637 node_info node = { gf->nodes[i], {} };
2638
2639 const int f = htp_fusion_max(gf, i);
2640 for (int k = 1; k < f; k++) {
2641 node.add_fused(gf->nodes[++i]);
2642 }
2643
2644 nodes.push_back(std::move(node));
2645 }
2646
2647 const auto order = ggml_hexagon_graph_optimize_reorder(nodes);
2648
2649 // unfuse
2650 {
2651 int j = 0;
2652 for (const auto i : order) {
2653 const auto & node = nodes[i];
2654
2655 gf->nodes[j++] = node.node;
2656
2657 for (auto * fused : node.fused) {
2658 gf->nodes[j++] = fused;
2659 }
2660 }
2661 }
2662
2663 GGML_UNUSED(backend);
2664}
2665
2666static uint64_t ggml_hexagon_session_key(const ggml_hexagon_session * sess) {
2667 return ((uint64_t) (uint32_t) sess->phys_idx << 32) | (uint32_t) sess->virt_idx;
2668}
2669
2670static bool ggml_hexagon_cpy_tensor_async_phys(ggml_backend_t backend_src, ggml_backend_t backend_dst, const ggml_tensor * src, ggml_tensor * dst) {
2671 auto sess_src = static_cast<ggml_hexagon_session *>(backend_src->context);
2672 auto sess_dst = static_cast<ggml_hexagon_session *>(backend_dst->context);
2673
2674 sess_src->mmap_tensor(src);
2675 auto sbuf_dst = sess_dst->mmap_tensor(dst);
2676
2677 if (!sess_src->clone_buffer(sbuf_dst)) { return false; }
2678
2679 const uint64_t src_key = ggml_hexagon_session_key(sess_src);
2680 auto & fence_slot = sess_dst->cpy_fence_slots[src_key];
2681 if (!fence_slot) {
2682 fence_slot = (volatile uint32_t *) sess_dst->alloc_fence(1);
2683 }
2684
2685 if (!sess_src->clone_buffer(sess_dst->fence_buf)) { return false; }
2686
2687 uint32_t fence_seq = sess_dst->next_fence_seq();
2688
2689 HEX_VERBOSE("ggml-hex: %s cpy-tensor-async %s -> %s size %zu : seq 0x%x\n",
2690 sess_dst->name.c_str(), src->name, dst->name, ggml_nbytes(src), fence_seq);
2691
2692 ggml_tensor fence_tensor = sess_dst->make_fence_tensor(fence_slot);
2693
2694 sess_src->enqueue_cpy(src, dst, &fence_tensor, fence_seq);
2695 sess_dst->enqueue_fence(&fence_tensor, fence_seq, /* wait = */ true);
2696
2697 sess_dst->add_peer(sess_src);
2698
2699 return true;
2700}
2701
2702static bool ggml_hexagon_cpy_tensor_async_virt(ggml_backend_t backend_src, ggml_backend_t backend_dst, const ggml_tensor * src, ggml_tensor * dst) {
2703 auto sess_src = static_cast<ggml_hexagon_session *>(backend_src->context);
2704 auto sess_dst = static_cast<ggml_hexagon_session *>(backend_dst->context);
2705
2706 auto sbuf_src = sess_src->mmap_tensor(src);
2707 sess_dst->mmap_tensor(dst);
2708
2709 if (!sess_dst->clone_buffer(sbuf_src)) { return false; }
2710
2711 HEX_VERBOSE("ggml-hex: %s cpy-tensor-async %s -> %s size %zu\n",
2712 sess_dst->name.c_str(), src->name, dst->name, ggml_nbytes(src));
2713
2714 sess_dst->enqueue_cpy(src, dst);
2715 sess_dst->add_peer(sess_src);
2716
2717 return true;
2718}
2719
2720static bool ggml_backend_hexagon_cpy_tensor_async(ggml_backend_t backend_src, ggml_backend_t backend_dst, const ggml_tensor * src, ggml_tensor * dst) {
2721 if (!ggml_backend_is_hexagon(backend_src) || !ggml_backend_is_hexagon(backend_dst)) {
2722 return false;
2723 }
2724
2725 // FIXME: ggml-meta needs to call init_tensor on auxiliary tensors
2726 if (!dst->extra) {
2727 ggml_backend_buffer_init_tensor(dst->buffer, dst);
2728 }
2729
2730 auto * dst_extra = static_cast<htp_tensor_extra *>(dst->extra);
2731 const auto * src_extra = static_cast<const htp_tensor_extra *>(src->extra);
2732 dst_extra->flags = src_extra->flags & ~HTP_TENSOR_FUSEABLE;
2733
2734 auto sess_src = static_cast<ggml_hexagon_session *>(backend_src->context);
2735 auto sess_dst = static_cast<ggml_hexagon_session *>(backend_dst->context);
2736
2737 if (sess_src == sess_dst) {
2738 HEX_VERBOSE("ggml-hex: %s cpy-tensor-async %s -> %s size %zu\n", sess_dst->name.c_str(), src->name, dst->name, ggml_nbytes(src));
2739 sess_src->enqueue_cpy(src, dst);
2740 return true;
2741 }
2742
2743 if (sess_src->phys_idx != sess_dst->phys_idx)
2744 return ggml_hexagon_cpy_tensor_async_phys(backend_src, backend_dst, src, dst);
2745
2746 return ggml_hexagon_cpy_tensor_async_virt(backend_src, backend_dst, src, dst);
2747}
2748
2749static ggml_backend_event_t ggml_backend_hexagon_device_event_new(ggml_backend_dev_t dev) {
2750 auto dev_ctx = static_cast<ggml_backend_hexagon_device_context *>(dev->context);
2751 auto sess = dev_ctx->session();
2752
2753 ggml_hexagon_event * hex_event = new ggml_hexagon_event();
2754 hex_event->fence_sess = sess;
2755 hex_event->sess = sess;
2756 hex_event->fence_slot = (volatile uint32_t *) sess->alloc_fence(1);
2757 hex_event->fence_tensor = sess->make_fence_tensor(hex_event->fence_slot);
2758
2759 HEX_VERBOSE("ggml-hex: %s event-new : event %p fence %p\n", ggml_backend_dev_name(dev), (void *)hex_event, (void *)hex_event->fence_slot);
2760
2761 return new ggml_backend_event {
2762 /* .device = */ dev,
2763 /* .context = */ hex_event,
2764 };
2765}
2766
2767static void ggml_hexagon_event_synchronize(ggml_backend_dev_t dev, ggml_hexagon_event * hex_event) {
2768 if (hex_event->seq == 0) {
2769 return;
2770 }
2771
2772 HEX_VERBOSE("ggml-hex: %s event-synchronize : event %p seq 0x%x fence %p\n",
2773 ggml_backend_dev_name(dev), (void *)hex_event, hex_event->seq, (void *)hex_event->fence_slot);
2774
2775 auto * fence = reinterpret_cast<const volatile std::atomic<uint32_t> *>(hex_event->fence_slot);
2776
2777 if ((int32_t)(fence[0].load(std::memory_order_relaxed) - hex_event->seq) < 0) {
2778 hex_event->sess->flush_async();
2779 }
2780
2781 while (true) {
2782 if ((int32_t)(fence[0].load(std::memory_order_acquire) - hex_event->seq) >= 0) {
2783 uint32_t status = fence[1].load(std::memory_order_acquire);
2784 if (status > HTP_STATUS_OK) {
2785 GGML_ABORT("ggml-hex: %s event-synchronize failed : dsp-error %s\n",
2786 hex_event->sess->c_name(), status_to_str(status));
2787 }
2788 break;
2789 }
2790 std::this_thread::yield();
2791 }
2792}
2793
2794static void ggml_backend_hexagon_device_event_free(ggml_backend_dev_t dev, ggml_backend_event_t event) {
2795 auto * hex_event = static_cast<ggml_hexagon_event *>(event->context);
2796 ggml_hexagon_event_synchronize(dev, hex_event);
2797 HEX_VERBOSE("ggml-hex: %s event-free : event %p\n", ggml_backend_dev_name(dev), (void *)hex_event);
2798 hex_event->fence_sess->free_fence((void *) hex_event->fence_slot, 1);
2799 delete hex_event;
2800 delete event;
2801}
2802
2803static void ggml_backend_hexagon_device_event_synchronize(ggml_backend_dev_t dev, ggml_backend_event_t event) {
2804 auto * hex_event = static_cast<ggml_hexagon_event *>(event->context);
2805 ggml_hexagon_event_synchronize(dev, hex_event);
2806}
2807
2808static void ggml_backend_hexagon_event_record(ggml_backend_t backend, ggml_backend_event_t event) {
2809 auto sess = static_cast<ggml_hexagon_session *>(backend->context);
2810 auto hex_event = static_cast<ggml_hexagon_event *>(event->context);
2811
2812 hex_event->sess = sess;
2813 hex_event->seq = sess->next_fence_seq();
2814
2815 sess->enqueue_fence(&hex_event->fence_tensor, hex_event->seq, /* wait = */ false);
2816
2817 HEX_VERBOSE("ggml-hex: %s event-record : event %p seq 0x%x fence %p\n",
2818 sess->c_name(), (void *)hex_event, hex_event->seq, (void *)hex_event->fence_slot);
2819}
2820
2821static void ggml_backend_hexagon_event_wait(ggml_backend_t backend, ggml_backend_event_t event) {
2822 auto sess = static_cast<ggml_hexagon_session *>(backend->context);
2823 auto hex_event = static_cast<ggml_hexagon_event *>(event->context);
2824
2825 if (hex_event->seq == 0) {
2826 return;
2827 }
2828
2829 HEX_VERBOSE("ggml-hex: %s event-wait : event %p seq 0x%x fence %p\n",
2830 sess->c_name(), (void *)hex_event, hex_event->seq, (void *)hex_event->fence_slot);
2831
2832 // same physical NPU runs sequentially in FIFO order
2833 if (sess->phys_idx == hex_event->sess->phys_idx) {
2834 if (sess != hex_event->sess) {
2835 sess->add_peer(hex_event->sess);
2836 }
2837 return;
2838 }
2839
2840 sess->clone_buffer(hex_event->fence_sess->fence_buf);
2841 sess->add_peer(hex_event->sess);
2842 sess->enqueue_fence(&hex_event->fence_tensor, hex_event->seq, /* wait = */ true);
2843}
2844
2845static void ggml_backend_hexagon_set_tensor_async(ggml_backend_t backend, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
2846 auto sess = static_cast<ggml_hexagon_session *>(backend->context);
2847 HEX_VERBOSE("ggml-hex: %s set-tensor-async %s : data %p offset %zu size %zu usage %d\n",
2848 sess->c_name(), tensor->name, data, offset, size, tensor->buffer ? (int) tensor->buffer->usage : -1);
2849 ggml_backend_tensor_set(tensor, data, offset, size);
2850}
2851
2852static void ggml_backend_hexagon_get_tensor_async(ggml_backend_t backend, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size) {
2853 auto sess = static_cast<ggml_hexagon_session *>(backend->context);
2854 HEX_VERBOSE("ggml-hex: %s get-tensor-async %s : data %p offset %zu size %zu usage %d\n",
2855 sess->c_name(), tensor->name, data, offset, size, tensor->buffer ? (int) tensor->buffer->usage : -1);
2856 sess->flush_sync();
2857 if (sess->last_error > HTP_STATUS_OK) {
2858 GGML_ABORT("ggml-hex: %s get-tensor-async failed : dsp-error %s\n", sess->c_name(), status_to_str(sess->last_error));
2859 }
2860 ggml_backend_tensor_get(tensor, data, offset, size);
2861}
2862
2863static void ggml_backend_hexagon_set_tensor_2d_async(ggml_backend_t backend,
2864 struct ggml_tensor * tensor,
2865 const void * data,
2866 size_t offset,
2867 size_t size,
2868 size_t n_copies,
2869 size_t stride_tensor,
2870 size_t stride_data) {
2871 auto sess = static_cast<ggml_hexagon_session *>(backend->context);
2872 HEX_VERBOSE("ggml-hex: %s set-tensor-2d-async %s : data %p offset %zu size %zu n_copies %zu stride_tensor %zu stride_data %zu usage %d\n",
2873 sess->c_name(), tensor->name, data, offset, size, n_copies, stride_tensor, stride_data, tensor->buffer ? (int) tensor->buffer->usage : -1);
2874 ggml_backend_tensor_set_2d(tensor, data, offset, size, n_copies, stride_tensor, stride_data);
2875}
2876
2877static void ggml_backend_hexagon_get_tensor_2d_async(ggml_backend_t backend,
2878 const struct ggml_tensor * tensor,
2879 void * data,
2880 size_t offset,
2881 size_t size,
2882 size_t n_copies,
2883 size_t stride_tensor,
2884 size_t stride_data) {
2885 auto sess = static_cast<ggml_hexagon_session *>(backend->context);
2886 HEX_VERBOSE("ggml-hex: %s get-tensor-2d-async %s : data %p offset %zu size %zu n_copies %zu stride_tensor %zu stride_data %zu usage %d\n",
2887 sess->c_name(), tensor->name, data, offset, size, n_copies, stride_tensor, stride_data, tensor->buffer ? (int) tensor->buffer->usage : -1);
2888 sess->flush_sync();
2889 if (sess->last_error > HTP_STATUS_OK) {
2890 GGML_ABORT("ggml-hex: %s get-tensor-2d-async failed : dsp-error %s\n", sess->c_name(), status_to_str(sess->last_error));
2891 }
2892 ggml_backend_tensor_get_2d(tensor, data, offset, size, n_copies, stride_tensor, stride_data);
2893}
2894
2895static struct ggml_backend_i hexagon_backend_i = {
2896 /* .get_name = */ ggml_backend_hexagon_name,
2897 /* .free = */ ggml_backend_hexagon_free,
2898 /* .set_tensor_async = */ ggml_backend_hexagon_set_tensor_async,
2899 /* .get_tensor_async = */ ggml_backend_hexagon_get_tensor_async,
2900 /* .set_tensor_2d_async = */ ggml_backend_hexagon_set_tensor_2d_async,
2901 /* .get_tensor_2d_async = */ ggml_backend_hexagon_get_tensor_2d_async,
2902 /* .cpy_tensor_async = */ ggml_backend_hexagon_cpy_tensor_async,
2903 /* .synchronize = */ ggml_backend_hexagon_synchronize,
2904 /* .graph_plan_create = */ NULL,
2905 /* .graph_plan_free = */ NULL,
2906 /* .graph_plan_update = */ NULL,
2907 /* .graph_plan_compute = */ NULL,
2908 /* .graph_compute = */ ggml_backend_hexagon_graph_compute,
2909 /* .event_record = */ ggml_backend_hexagon_event_record,
2910 /* .event_wait = */ ggml_backend_hexagon_event_wait,
2911 /* .graph_optimize = */ ggml_backend_hexagon_graph_optimize,
2912};
2913
2914static ggml_guid_t ggml_backend_hexagon_guid() {
2915 static ggml_guid guid = { 0x7b, 0x57, 0xdc, 0xaf, 0xde, 0x12, 0x1d, 0x49,
2916 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11 };
2917 return &guid;
2918}
2919
2920bool ggml_backend_is_hexagon(ggml_backend_t backend) {
2921 return backend && backend->iface.get_name == ggml_backend_hexagon_name;
2922}
2923
2924// device interface
2925
2926static ggml_backend_t ggml_backend_hexagon_device_init(ggml_backend_dev_t dev, const char * params) {
2927 auto dev_ctx = static_cast<ggml_backend_hexagon_device_context *>(dev->context);
2928 auto sess = dev_ctx->session();
2929
2930 return new ggml_backend{
2931 /* .guid = */ ggml_backend_hexagon_guid(),
2932 /* .interface = */ hexagon_backend_i,
2933 /* .device = */ dev,
2934 /* .context = */ sess,
2935 };
2936
2937 GGML_UNUSED(params);
2938}
2939
2940static const char * ggml_backend_hexagon_device_get_name(ggml_backend_dev_t dev) {
2941 auto dev_ctx = static_cast<ggml_backend_hexagon_device_context *>(dev->context);
2942 return dev_ctx->c_name();
2943
2944 GGML_UNUSED(dev);
2945}
2946
2947static const char * ggml_backend_hexagon_device_get_description(ggml_backend_dev_t dev) {
2948 return "Hexagon";
2949 GGML_UNUSED(dev);
2950}
2951
2952static void ggml_backend_hexagon_device_get_memory(ggml_backend_dev_t dev, size_t * free, size_t * total) {
2953 *free = opt_mbuf_total;
2954 *total = opt_mbuf_total;
2955
2956 GGML_UNUSED(dev);
2957}
2958
2959static enum ggml_backend_dev_type ggml_backend_hexagon_device_get_type(ggml_backend_dev_t dev) {
2960 return GGML_BACKEND_DEVICE_TYPE_GPU;
2961
2962 GGML_UNUSED(dev);
2963}
2964
2965static void ggml_backend_hexagon_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) {
2966 props->name = ggml_backend_hexagon_device_get_name(dev);
2967 props->description = ggml_backend_hexagon_device_get_description(dev);
2968 props->type = ggml_backend_hexagon_device_get_type(dev);
2969 ggml_backend_hexagon_device_get_memory(dev, &props->memory_free, &props->memory_total);
2970 props->caps = {
2971 /* .async = */ true,
2972 /* .host_buffer = */ false,
2973 /* .buffer_from_host_ptr = */ false,
2974 /* .events = */ true,
2975 /* .mmap_support = */ false,
2976 };
2977}
2978
2979static ggml_backend_buffer_type_t ggml_backend_hexagon_device_get_buffer_type(ggml_backend_dev_t dev) {
2980 auto dev_ctx = static_cast<ggml_backend_hexagon_device_context *>(dev->context);
2981 return &dev_ctx->buffer_type;
2982}
2983
2984static ggml_backend_buffer_type_t ggml_backend_hexagon_device_get_host_buffer_type(ggml_backend_dev_t dev) {
2985 if (!opt_hostbuf) {
2986 return NULL;
2987 }
2988 auto dev_ctx = static_cast<ggml_backend_hexagon_device_context *>(dev->context);
2989 return &dev_ctx->host_buffer_type;
2990}
2991
2992// IMPORTANT: supports_op runs before buffer allocation and before tensor data is populated.
2993// Never check buffer usage, buffer properties, or repacking state (is_tiled) here.
2994// Support must depend only on static tensor properties (shape, type, strides).
2995static bool ggml_backend_hexagon_device_supports_op(ggml_backend_dev_t dev, const struct ggml_tensor * op) {
2996 auto dev_ctx = static_cast<ggml_backend_hexagon_device_context *>(dev->context);
2997 auto sess = dev_ctx->session();
2998
2999 // reject ops that match the filter
3000 if (opt_opfilter && std::regex_match(ggml_op_desc(op), *opt_opfilter)) {
3001 return false;
3002 }
3003
3004 bool supp = false;
3005 switch (op->op) {
3006 case GGML_OP_NONE:
3007 case GGML_OP_RESHAPE:
3008 case GGML_OP_VIEW:
3009 case GGML_OP_PERMUTE:
3010 case GGML_OP_TRANSPOSE:
3011 supp = true;
3012 break;
3013
3014 default:
3015 supp = htp_kparams_check(sess, op);
3016 break;
3017 }
3018
3019 ggml_hexagon_dump_op_supp(sess->c_name(), op, supp);
3020 return supp;
3021}
3022
3023static bool ggml_backend_hexagon_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
3024 auto dev_ctx = static_cast<ggml_backend_hexagon_device_context *>(dev->context);
3025
3026 bool supp = (buft == &dev_ctx->host_buffer_type) || (buft == &dev_ctx->buffer_type);
3027
3028 HEX_VERBOSE("ggml-hex: %s device-supports-buft %s %s\n", dev_ctx->c_name(), ggml_backend_buft_name(buft), supp ? "yes" : "no");
3029 return supp;
3030}
3031
3032static const struct ggml_backend_device_i ggml_backend_hexagon_device_i = {
3033 /* .get_name = */ ggml_backend_hexagon_device_get_name,
3034 /* .get_description = */ ggml_backend_hexagon_device_get_description,
3035 /* .get_memory = */ ggml_backend_hexagon_device_get_memory,
3036 /* .get_type = */ ggml_backend_hexagon_device_get_type,
3037 /* .get_props = */ ggml_backend_hexagon_device_get_props,
3038 /* .init_backend = */ ggml_backend_hexagon_device_init,
3039 /* .get_buffer_type = */ ggml_backend_hexagon_device_get_buffer_type,
3040 /* .get_host_buffer_type = */ ggml_backend_hexagon_device_get_host_buffer_type,
3041 /* .buffer_from_host_ptr = */ NULL, // ggml_backend_hexagon_device_buffer_from_ptr,
3042 /* .supports_op = */ ggml_backend_hexagon_device_supports_op,
3043 /* .supports_buft = */ ggml_backend_hexagon_device_supports_buft,
3044 /* .offload_op = */ NULL, // ggml_backend_hexagon_device_offload_op,
3045 /* .event_new = */ ggml_backend_hexagon_device_event_new,
3046 /* .event_free = */ ggml_backend_hexagon_device_event_free,
3047 /* .event_synchronize = */ ggml_backend_hexagon_device_event_synchronize,
3048};
3049
3050//** backend registry
3051
3052ggml_hexagon_registry::ggml_hexagon_registry(ggml_backend_reg_t reg) {
3053 GGML_LOG_INFO("ggml-hex: Hexagon backend (experimental) : allocating new registry : ndev %zu\n", opt_ndev);
3054
3055 GGML_LOG_INFO("ggml-hex: Hexagon Arch version v%d, DMA64 %s\n", opt_arch, opt_dma64 ? "enabled" : "disabled");
3056
3057 // Create devices
3058 for (size_t i = 0; i < opt_ndev; i++) {
3059 const auto & cfg = opt_device_configs[i];
3060 if (cfg.mdev_group.empty()) {
3061 GGML_LOG_INFO("ggml-hex: device %zu: %s (phys=%d, virt=%d, domain=%s:%d)\n",
3062 i, cfg.name.c_str(), cfg.physical_idx, cfg.virtual_idx, cfg.domain_name.c_str(), cfg.domain_id);
3063 } else {
3064 std::string peers_str;
3065 for (const auto & p : cfg.mdev_group) {
3066 if (!peers_str.empty()) peers_str += ", ";
3067 peers_str += p.name + " (phys=" + std::to_string(p.physical_idx) + ")";
3068 }
3069 GGML_LOG_INFO("ggml-hex: device %zu: %s (phys=%d, virt=%d, domain=%s:%d) [mdev peers: %s]\n",
3070 i, cfg.name.c_str(), cfg.physical_idx, cfg.virtual_idx, cfg.domain_name.c_str(), cfg.domain_id, peers_str.c_str());
3071 }
3072 devices[i].iface = ggml_backend_hexagon_device_i;
3073 devices[i].reg = reg;
3074 devices[i].context = new ggml_backend_hexagon_device_context(i, opt_device_configs[i], &devices[i]);
3075 }
3076
3077}
3078
3079ggml_hexagon_registry::~ggml_hexagon_registry() {
3080 GGML_LOG_INFO("ggml-hex: releasing registry\n");
3081
3082 // Release devices
3083 for (size_t i = 0; i < opt_ndev; i++) {
3084 auto dev_ctx = static_cast<ggml_backend_hexagon_device_context *>(devices[i].context);
3085 delete dev_ctx;
3086 }
3087}
3088
3089static const char * ggml_backend_hexagon_reg_get_name(ggml_backend_reg_t reg) {
3090 return "HTP";
3091 GGML_UNUSED(reg);
3092}
3093
3094static size_t ggml_backend_hexagon_reg_get_device_count(ggml_backend_reg_t reg) {
3095 return opt_ndev;
3096 GGML_UNUSED(reg);
3097}
3098
3099static ggml_backend_dev_t ggml_backend_hexagon_reg_get_device(ggml_backend_reg_t reg, size_t index) {
3100 auto hreg = static_cast<ggml_hexagon_registry *>(reg->context);
3101
3102 if (index >= opt_ndev || !hreg->devices[index].context) {
3103 return nullptr;
3104 }
3105
3106 return &hreg->devices[index];
3107}
3108
3109// ** communication context for tensor-split allreduce
3110
3111static void * ggml_backend_hexagon_comm_init(ggml_backend_t * backends, size_t n_backends) {
3112 if (n_backends < 2 || n_backends > 4) {
3113 return nullptr;
3114 }
3115
3116 for (size_t i = 0; i < n_backends; ++i) {
3117 if (!ggml_backend_is_hexagon(backends[i])) {
3118 return nullptr;
3119 }
3120 }
3121
3122 for (size_t i = 0; i < n_backends; i++) {
3123 auto sess_i = static_cast<ggml_hexagon_session *>(backends[i]->context);
3124 for (size_t j = i + 1; j < n_backends; j++) {
3125 auto sess_j = static_cast<ggml_hexagon_session *>(backends[j]->context);
3126 if (sess_i->phys_idx == sess_j->phys_idx) {
3127 return nullptr;
3128 }
3129 }
3130 }
3131
3132 auto * ctx = new ggml_backend_hexagon_comm_context();
3133 ctx->backends.assign(backends, backends + n_backends);
3134 ctx->n_backends = n_backends;
3135
3136 for (size_t i = 0; i < n_backends; i++) {
3137 auto sess_i = static_cast<ggml_hexagon_session *>(backends[i]->context);
3138 ctx->fence_slots[i] = (volatile uint32_t *) sess_i->alloc_fence(1);
3139 ctx->fence_tensors[i] = sess_i->make_fence_tensor(ctx->fence_slots[i]);
3140 }
3141
3142 return ctx;
3143}
3144
3145static void ggml_backend_hexagon_comm_free(void * comm_ctx_v) {
3146 if (!comm_ctx_v) return;
3147 auto * ctx = static_cast<ggml_backend_hexagon_comm_context *>(comm_ctx_v);
3148 for (size_t i = 0; i < ctx->n_backends; i++) {
3149 auto sess_i = static_cast<ggml_hexagon_session *>(ctx->backends[i]->context);
3150 sess_i->free_fence((void *) ctx->fence_slots[i], 1);
3151 }
3152 delete ctx;
3153}
3154
3155static bool ggml_backend_hexagon_comm_allreduce_tensor(void * comm_ctx_v, struct ggml_tensor ** tensors) {
3156 if (opt_ar_select == 0 || !comm_ctx_v) return false;
3157 auto * comm_ctx = static_cast<ggml_backend_hexagon_comm_context *>(comm_ctx_v);
3158 const size_t n_backends = comm_ctx->n_backends;
3159
3160 if (n_backends < 2 || n_backends > 4) return false;
3161
3162 for (size_t i = 0; i < n_backends; i++) {
3163 auto sess_i = static_cast<ggml_hexagon_session *>(comm_ctx->backends[i]->context);
3164 for (size_t j = i + 1; j < n_backends; j++) {
3165 auto sess_j = static_cast<ggml_hexagon_session *>(comm_ctx->backends[j]->context);
3166 if (sess_i->phys_idx == sess_j->phys_idx) {
3167 return false;
3168 }
3169 }
3170 }
3171
3172 for (size_t i = 0; i < n_backends; i++) {
3173 if (!tensors[i] || !tensors[i]->buffer || !ggml_backend_buffer_is_hexagon(tensors[i]->buffer)) {
3174 return false;
3175 }
3176 if (tensors[i]->type != tensors[0]->type) {
3177 return false;
3178 }
3179 if (!ggml_is_contiguous(tensors[i])) {
3180 return false;
3181 }
3182 if (ggml_nelements(tensors[i]) != ggml_nelements(tensors[0])) {
3183 return false;
3184 }
3185 }
3186
3187 if (tensors[0]->type != GGML_TYPE_F16 && tensors[0]->type != GGML_TYPE_F32) {
3188 return false;
3189 }
3190
3191 for (size_t r = 0; r < n_backends; r++) {
3192 auto sess = static_cast<ggml_hexagon_session *>(comm_ctx->backends[r]->context);
3193 if (!htp_kparams_check<htp_kparams_solve_allreduce>(sess, tensors[r], (uint32_t) r, (uint32_t) n_backends, false, false, false)) {
3194 return false;
3195 }
3196 }
3197
3198 uint32_t max_seq = static_cast<ggml_hexagon_session *>(comm_ctx->backends[0]->context)->fence_seq;
3199 for (size_t i = 1; i < n_backends; i++) {
3200 auto sess_i = static_cast<ggml_hexagon_session *>(comm_ctx->backends[i]->context);
3201 if ((int32_t)(sess_i->fence_seq - max_seq) > 0) {
3202 max_seq = sess_i->fence_seq;
3203 }
3204 }
3205 if (++max_seq == 0) max_seq = 1;
3206 uint32_t fence_seq_entry = max_seq;
3207 if (++max_seq == 0) max_seq = 1;
3208 uint32_t fence_seq_exit = max_seq;
3209
3210 for (size_t i = 0; i < n_backends; i++) {
3211 auto sess_i = static_cast<ggml_hexagon_session *>(comm_ctx->backends[i]->context);
3212 sess_i->fence_seq = max_seq;
3213 }
3214
3215 std::vector<const ggml_tensor *> data_tensors(n_backends);
3216 std::vector<const ggml_tensor *> sync_tensors(n_backends);
3217 for (size_t i = 0; i < n_backends; i++) {
3218 data_tensors[i] = tensors[i];
3219 sync_tensors[i] = &comm_ctx->fence_tensors[i];
3220 }
3221
3222 for (size_t r = 0; r < n_backends; r++) {
3223 auto sess = static_cast<ggml_hexagon_session *>(comm_ctx->backends[r]->context);
3224 sess->enqueue_allreduce(tensors[r], data_tensors, sync_tensors, (uint32_t) r, (uint32_t) n_backends, fence_seq_entry, fence_seq_exit);
3225 for (size_t j = 0; j < n_backends; j++) {
3226 if (r != j) {
3227 sess->add_peer(static_cast<ggml_hexagon_session *>(comm_ctx->backends[j]->context));
3228 }
3229 }
3230 }
3231
3232 return true;
3233}
3234
3235static ggml_backend_buffer_type_t ggml_backend_hexagon_split_buffer_type(int main_device, const float * tensor_split) {
3236 GGML_UNUSED(tensor_split);
3237 auto reg = ggml_backend_hexagon_reg();
3238 auto dev = ggml_backend_reg_dev_get(reg, main_device);
3239 if (!dev) {
3240 dev = ggml_backend_reg_dev_get(reg, 0);
3241 }
3242 if (!dev) return nullptr;
3243 auto dev_ctx = static_cast<ggml_backend_hexagon_device_context *>(dev->context);
3244 return &dev_ctx->buffer_type;
3245}
3246
3247static void * ggml_backend_hexagon_get_proc_address(ggml_backend_reg_t reg, const char * name) {
3248 GGML_UNUSED(reg);
3249 if (strcmp(name, "ggml_backend_split_buffer_type") == 0) {
3250 return (void *) ggml_backend_hexagon_split_buffer_type;
3251 }
3252 if (strcmp(name, "ggml_backend_comm_init") == 0) {
3253 return (void *) ggml_backend_hexagon_comm_init;
3254 }
3255 if (strcmp(name, "ggml_backend_comm_free") == 0) {
3256 return (void *) ggml_backend_hexagon_comm_free;
3257 }
3258 if (strcmp(name, "ggml_backend_comm_allreduce_tensor") == 0) {
3259 return (void *) ggml_backend_hexagon_comm_allreduce_tensor;
3260 }
3261 return NULL;
3262}
3263
3264template<typename T> std::vector<T> str_to_vec(const char* str) {
3265 std::stringstream ss(str);
3266 std::vector<T> v;
3267 std::string t;
3268
3269 while (std::getline(ss, t, ',')) {
3270 v.push_back(std::stoul(t, nullptr, 0));
3271 }
3272
3273 return v;
3274}
3275
3276template<typename T, int BASE=10> std::string vec_to_str(std::vector<T> v) {
3277 std::stringstream ss;
3278 ss << std::setbase(BASE) << std::showbase;
3279 for (auto i : v) { ss << i << ','; }
3280 auto str = ss.str(); str.pop_back(); // drop last comma
3281 return str;
3282}
3283
3284static void ggml_hexagon_resolve_device_domain(ggml_hexagon_device_config & cfg, bool discovery_supported, const std::unordered_map<int, fastrpc_domain> & cdsp_map) {
3285 if (discovery_supported) {
3286 auto it = cdsp_map.find(cfg.physical_idx);
3287 if (it != cdsp_map.end()) {
3288 cfg.domain_id = it->second.id;
3289 cfg.domain_name = it->second.name;
3290 } else {
3291 GGML_LOG_ERROR("ggml-hex: physical CDSP core %d not found on device (%zu CDSP core(s) available)\n",
3292 cfg.physical_idx, cdsp_map.size());
3293 cfg.domain_id = -1;
3294 cfg.domain_name = "";
3295 }
3296 } else {
3297 switch (cfg.physical_idx) {
3298 case 0:
3299 cfg.domain_id = 3;
3300 cfg.domain_name = CDSP_DOMAIN_NAME;
3301 break;
3302 case 1:
3303 cfg.domain_id = 4;
3304 cfg.domain_name = "cdsp1";
3305 break;
3306 default:
3307 GGML_LOG_ERROR("ggml-hex: physical CDSP core %d not supported without dynamic discovery\n",
3308 cfg.physical_idx);
3309 cfg.domain_id = -1;
3310 cfg.domain_name = "";
3311 break;
3312 }
3313 }
3314 for (auto & sub_cfg : cfg.mdev_group) {
3315 ggml_hexagon_resolve_device_domain(sub_cfg, discovery_supported, cdsp_map);
3316 }
3317}
3318
3319// Enumerate NPU (aka CDSP) domains via FASTRPC_GET_DOMAINS if supported,
3320// and populate domain_id and domain_name for all configured devices.
3321static void ggml_hexagon_discover_devices() {
3322 std::unordered_map<int, fastrpc_domain> cdsp_map;
3323 bool discovery_supported = false;
3324
3325 system_req_payload domain_info = {};
3326 domain_info.id = FASTRPC_GET_DOMAINS;
3327 domain_info.sys.domains = nullptr;
3328 domain_info.sys.max_domains = 0;
3329 domain_info.sys.flags = DOMAINS_LIST_FLAGS_SET_TYPE(0, FASTRPC_NSP);
3330
3331 int err = remote_system_request(&domain_info);
3332 if (err == AEE_SUCCESS && domain_info.sys.num_domains > 0) {
3333 std::vector<fastrpc_domain> domains(domain_info.sys.num_domains);
3334 domain_info.sys.domains = domains.data();
3335 domain_info.sys.max_domains = (int) domains.size();
3336
3337 err = remote_system_request(&domain_info);
3338 if (err == AEE_SUCCESS) {
3339 discovery_supported = true;
3340 const int n_domains = std::min(domain_info.sys.num_domains, (int) domains.size());
3341 for (int i = 0; i < n_domains; i++) {
3342 GGML_LOG_INFO("ggml-hex: FASTRPC_GET_DOMAINS[%d]: type %d id %d name '%s' status %d instance-id %d\n",
3343 i, (int) domains[i].type, domains[i].id, domains[i].name, domains[i].status, domains[i].instance_id);
3344 if (domains[i].type != FASTRPC_NSP) {
3345 GGML_LOG_DEBUG("ggml-hex: skipping non-CDSP domain (type=%d)\n", (int) domains[i].type);
3346 continue;
3347 }
3348 if (!domains[i].status) {
3349 GGML_LOG_WARN("ggml-hex: skipping CDSP domain id=%d (status=down)\n", domains[i].id);
3350 continue;
3351 }
3352 cdsp_map[domains[i].instance_id] = domains[i];
3353 GGML_LOG_INFO("ggml-hex: using CDSP domain: instance-id %d id %d name '%s'\n",
3354 domains[i].instance_id, domains[i].id, domains[i].name);
3355 }
3356 } else {
3357 GGML_LOG_WARN("ggml-hex: FASTRPC_GET_DOMAINS fetch failed (0x%x), using static CDSP domains\n", (unsigned) err);
3358 }
3359 } else if (err != AEE_SUCCESS) {
3360 GGML_LOG_DEBUG("ggml-hex: FASTRPC_GET_DOMAINS query failed (0x%x), using static CDSP domains\n", (unsigned) err);
3361 }
3362
3363 // Populate domain IDs and names for all configured devices
3364 for (size_t i = 0; i < opt_ndev; i++) {
3365 ggml_hexagon_resolve_device_domain(opt_device_configs[i], discovery_supported, cdsp_map);
3366 }
3367}
3368
3369static void ggml_hexagon_init(ggml_backend_reg * reg) {
3370 // Basic sanity checks to make sure definitions match
3371 static_assert((unsigned int) HTP_TYPE_Q4_0 == (unsigned int) GGML_TYPE_Q4_0,
3372 "please update hexagon_type to match ggml_type");
3373 static_assert((unsigned int) HTP_TYPE_Q4_1 == (unsigned int) GGML_TYPE_Q4_1,
3374 "please update hexagon_type to match ggml_type");
3375 static_assert((unsigned int) HTP_TYPE_Q8_0 == (unsigned int) GGML_TYPE_Q8_0,
3376 "please update hexagon_type to match ggml_type");
3377 static_assert((unsigned int) HTP_TYPE_MXFP4 == (unsigned int) GGML_TYPE_MXFP4,
3378 "please update hexagon_type to match ggml_type");
3379 static_assert((unsigned int) HTP_TYPE_IQ4_NL == (unsigned int) GGML_TYPE_IQ4_NL,
3380 "please update hexagon_type to match ggml_type");
3381 static_assert((unsigned int) HTP_TYPE_Q4_K == (unsigned int) GGML_TYPE_Q4_K,
3382 "please update hexagon_type to match ggml_type");
3383 static_assert((unsigned int) HTP_TYPE_Q5_K == (unsigned int) GGML_TYPE_Q5_K,
3384 "please update hexagon_type to match ggml_type");
3385 static_assert((unsigned int) HTP_TYPE_Q6_K == (unsigned int) GGML_TYPE_Q6_K,
3386 "please update hexagon_type to match ggml_type");
3387 static_assert((unsigned int) HTP_TYPE_Q3_K == (unsigned int) GGML_TYPE_Q3_K,
3388 "please update hexagon_type to match ggml_type");
3389 static_assert((unsigned int) HTP_TYPE_Q2_K == (unsigned int) GGML_TYPE_Q2_K,
3390 "please update hexagon_type to match ggml_type");
3391 static_assert((unsigned int) HTP_TYPE_Q1_0 == (unsigned int) GGML_TYPE_Q1_0,
3392 "please update hexagon_type to match ggml_type");
3393 static_assert((unsigned int) HTP_TYPE_Q2_0 == (unsigned int) GGML_TYPE_Q2_0,
3394 "please update hexagon_type to match ggml_type");
3395 static_assert((unsigned int) HTP_TYPE_BF16 == (unsigned int) GGML_TYPE_BF16,
3396 "please update hexagon_type to match ggml_type");
3397
3398 const char * str_verbose = getenv("GGML_HEXAGON_VERBOSE");
3399 const char * str_opbatch = getenv("GGML_HEXAGON_OPBATCH");
3400 const char * str_opqueue = getenv("GGML_HEXAGON_OPQUEUE");
3401 const char * str_oppoll = getenv("GGML_HEXAGON_OPPOLL");
3402 const char * str_opfusion = getenv("GGML_HEXAGON_OPFUSION");
3403 const char * str_rt_repack = getenv("GGML_HEXAGON_RT_REPACK");
3404 const char * str_opfilter = getenv("GGML_HEXAGON_OPFILTER");
3405 const char * str_profile = getenv("GGML_HEXAGON_PROFILE");
3406 const char * str_etm = getenv("GGML_HEXAGON_ETM");
3407 const char * str_nhvx = getenv("GGML_HEXAGON_NHVX");
3408 const char * str_nhmx = getenv("GGML_HEXAGON_NHMX");
3409 const char * str_vtcm_size = getenv("GGML_HEXAGON_VTCM_SIZE");
3410 const char * str_mm_select = getenv("GGML_HEXAGON_MM_SELECT");
3411 const char * str_fa_select = getenv("GGML_HEXAGON_FA_SELECT");
3412 const char * str_fa_split = getenv("GGML_HEXAGON_FA_SPLIT");
3413 const char * str_li_select = getenv("GGML_HEXAGON_LI_SELECT");
3414 const char * str_gdn_select = getenv("GGML_HEXAGON_GDN_SELECT");
3415 const char * str_ar_select = getenv("GGML_HEXAGON_AR_SELECT");
3416 const char * str_ar_scatter = getenv("GGML_HEXAGON_AR_SCATTER");
3417 const char * str_ndev = getenv("GGML_HEXAGON_NDEV");
3418 const char * str_arch = getenv("GGML_HEXAGON_ARCH");
3419 const char * str_vmem = getenv("GGML_HEXAGON_VMEM");
3420 const char * str_mbuf = getenv("GGML_HEXAGON_MBUF");
3421 const char * str_optrace = getenv("GGML_HEXAGON_OPTRACE");
3422 const char * str_hostbuf = getenv("GGML_HEXAGON_HOSTBUF");
3423 const char * str_dma64 = getenv("GGML_HEXAGON_DMA64");
3424 const char * str_power_mode = getenv("GGML_HEXAGON_POWER_MODE");
3425
3426 // Init Arch first since it affects other defaults
3427 if (!str_arch) {
3428 int err = htpdrv_get_arch(CDSP_DOMAIN_ID, &opt_arch);
3429 if (err != 0) {
3430 GGML_LOG_ERROR("ggml-hex: failed to query HTP version (err %d) defaulting to v73\n", err);
3431 opt_arch = 73;
3432 } else {
3433 if (opt_arch < 73) {
3434 GGML_LOG_WARN("ggml-hex: Hexagon arch v%d is under supported range, capping at v73\n", opt_arch);
3435 opt_arch = 73;
3436 } else if (opt_arch > 85) {
3437 GGML_LOG_WARN("ggml-hex: Hexagon arch v%d is over supported range, capping at v85\n", opt_arch);
3438 opt_arch = 85;
3439 }
3440 }
3441 } else {
3442 if (str_arch[0] == 'v' || str_arch[0] == 'V') {
3443 str_arch++;
3444 }
3445 opt_arch = strtoul(str_arch, NULL, 0);
3446 }
3447
3448 size_t MiB = 1024 * 1024;
3449
3450 // Update vmem default
3451 opt_vmem = opt_arch >= 75 ? HTP_OP_MAX_VMEM_DEFAULT : 3000 * MiB;
3452 opt_dma64 = opt_arch > 79 && (!str_dma64 || atoi(str_dma64) != 0);
3453
3454 auto RE_ICASE = std::regex_constants::icase;
3455
3456 opt_opfilter = str_opfilter ? new std::regex(str_opfilter, RE_ICASE) : NULL;
3457 opt_verbose = str_verbose ? atoi(str_verbose) : 0;
3458 opt_opbatch = str_opbatch ? strtoul(str_opbatch, NULL, 0) : opt_opbatch;
3459 opt_opqueue = str_opqueue ? strtoul(str_opqueue, NULL, 0) : opt_opqueue;
3460 opt_optrace = str_optrace ? strtoul(str_optrace, NULL, 0) : (opt_opbatch * HTP_TRACE_MAX_EVENTS + 131072);
3461 opt_oppoll = str_oppoll ? strtoul(str_oppoll, NULL, 0) : opt_oppoll;
3462 opt_opfusion = str_opfusion ? atoi(str_opfusion) : opt_opfusion;
3463 opt_rt_repack = str_rt_repack ? atoi(str_rt_repack) : opt_rt_repack;
3464 opt_profile = str_profile ? atoi(str_profile) : 0;
3465 opt_etm = str_etm ? atoi(str_etm) : 0;
3466 if (str_power_mode) {
3467 int m = htp_power_mode_from_str(str_power_mode);
3468 if (m < 0) {
3469 GGML_LOG_WARN("ggml-hex: unknown GGML_HEXAGON_POWER_MODE '%s', falling back to 'burst'\n", str_power_mode);
3470 } else {
3471 opt_power_mode = m;
3472 }
3473 }
3474 opt_nhvx = str_nhvx ? strtoul(str_nhvx, NULL, 0) : opt_nhvx;
3475 opt_nhmx = str_nhmx ? atoi(str_nhmx) : opt_nhmx;
3476 opt_vtcm_size = str_vtcm_size ? parse_size(str_vtcm_size) : opt_vtcm_size;
3477 opt_mm_select = str_mm_select ? atoi(str_mm_select) : opt_mm_select;
3478 opt_fa_select = str_fa_select ? atoi(str_fa_select) : opt_fa_select;
3479 opt_fa_split = str_fa_split ? atoi(str_fa_split) : opt_fa_split;
3480 opt_li_select = str_li_select ? atoi(str_li_select) : opt_li_select;
3481 opt_gdn_select = str_gdn_select ? atoi(str_gdn_select) : opt_gdn_select;
3482 opt_ar_select = str_ar_select ? atoi(str_ar_select) : opt_ar_select;
3483 opt_ar_scatter = str_ar_scatter ? atoi(str_ar_scatter) : opt_ar_scatter;
3484
3485 if (str_mbuf) {
3486 const char * p = str_mbuf;
3487 for (int idx = 0; idx < 3 && p && *p; idx++) {
3488 while (*p == ' ') p++;
3489 const char * comma = strchr(p, ',');
3490 size_t len = comma ? (size_t)(comma - p) : strlen(p);
3491 while (len > 0 && p[len - 1] == ' ') len--;
3492 if (len > 0) {
3493 std::string token(p, len);
3494 if (idx == 0) opt_mbuf_dyn = parse_size(token.c_str());
3495 if (idx == 1) opt_mbuf_static = parse_size(token.c_str());
3496 if (idx == 2) opt_mbuf_total = parse_size(token.c_str());
3497 }
3498 if (!comma) break;
3499 p = comma + 1;
3500 }
3501 }
3502 opt_vmem = str_vmem ? parse_size(str_vmem) : opt_vmem;
3503 opt_hostbuf = str_hostbuf ? atoi(str_hostbuf) != 0 : opt_hostbuf;
3504
3505 // Parse device configuration
3506 const char * str_devices = getenv("GGML_HEXAGON_DEVICES");
3507 if (!str_devices && str_ndev && str_ndev[0] != '\0') {
3508 GGML_LOG_WARN("DEPRECATED: GGML_HEXAGON_NDEV is deprecated. use GGML_HEXAGON_DEVICES instead\n");
3509 str_devices = str_ndev;
3510 }
3511
3512 if (str_devices && str_devices[0] != '\0') {
3513 bool is_single_number = true;
3514 for (int i = 0; str_devices[i] != '\0'; i++) {
3515 if (!isdigit((unsigned char)str_devices[i])) {
3516 is_single_number = false;
3517 break;
3518 }
3519 }
3520 if (is_single_number) {
3521 int n = atoi(str_devices);
3522 if (n < 1) n = 1;
3523 if (n > GGML_HEXAGON_MAX_SESSIONS) n = GGML_HEXAGON_MAX_SESSIONS;
3524 opt_ndev = n;
3525 for (size_t i = 0; i < opt_ndev; i++) {
3526 opt_device_configs[i].physical_idx = 0;
3527 opt_device_configs[i].virtual_idx = (int)i;
3528 opt_device_configs[i].name = "HTP" + std::to_string(i);
3529 opt_device_configs[i].mdev_group.clear();
3530 }
3531 } else {
3532 std::string s_devices(str_devices);
3533 std::vector<std::string> items;
3534 std::string curr_item;
3535 int bracket_depth = 0;
3536 for (char ch : s_devices) {
3537 if (ch == '[') {
3538 bracket_depth++;
3539 curr_item += ch;
3540 } else if (ch == ']') {
3541 if (bracket_depth > 0) bracket_depth--;
3542 curr_item += ch;
3543 } else if (ch == ',' && bracket_depth == 0) {
3544 size_t s = curr_item.find_first_not_of(" \t\r\n");
3545 size_t e = curr_item.find_last_not_of(" \t\r\n");
3546 if (s != std::string::npos) {
3547 items.push_back(curr_item.substr(s, e - s + 1));
3548 }
3549 curr_item.clear();
3550 } else {
3551 curr_item += ch;
3552 }
3553 }
3554 size_t s = curr_item.find_first_not_of(" \t\r\n");
3555 size_t e = curr_item.find_last_not_of(" \t\r\n");
3556 if (s != std::string::npos) {
3557 items.push_back(curr_item.substr(s, e - s + 1));
3558 }
3559
3560 opt_ndev = 0;
3561 for (const auto & item : items) {
3562 size_t b_open = item.find('[');
3563 size_t b_close = item.rfind(']');
3564
3565 if (b_open != std::string::npos && b_close != std::string::npos && b_close > b_open) {
3566 // Grouped / composite syntax: Name[phys_spec:virt] or Name[phys_spec]
3567 std::string dev_name = item.substr(0, b_open);
3568 std::string content = item.substr(b_open + 1, b_close - b_open - 1);
3569
3570 int virt = 0;
3571 std::string phys_spec = content;
3572 size_t colon_pos = content.find(':');
3573 if (colon_pos != std::string::npos) {
3574 phys_spec = content.substr(0, colon_pos);
3575 try {
3576 virt = std::stoi(content.substr(colon_pos + 1));
3577 } catch (...) {
3578 virt = 0;
3579 }
3580 } else {
3581 size_t dev_colon = dev_name.find(':');
3582 if (dev_colon != std::string::npos) {
3583 try {
3584 virt = std::stoi(dev_name.substr(dev_colon + 1));
3585 } catch (...) {
3586 virt = 0;
3587 }
3588 }
3589 }
3590
3591 // Parse physical indices from phys_spec (e.g. 0-1, 0,1, 0-3, etc.)
3592 std::vector<int> phys_list;
3593 std::stringstream pss(phys_spec);
3594 std::string p_part;
3595 while (std::getline(pss, p_part, ',')) {
3596 size_t ps = p_part.find_first_not_of(" \t\r\n");
3597 size_t pe = p_part.find_last_not_of(" \t\r\n");
3598 if (ps == std::string::npos) continue;
3599 p_part = p_part.substr(ps, pe - ps + 1);
3600
3601 size_t dash_pos = p_part.find('-');
3602 if (dash_pos != std::string::npos) {
3603 try {
3604 int p_start = std::stoi(p_part.substr(0, dash_pos));
3605 int p_end = std::stoi(p_part.substr(dash_pos + 1));
3606 for (int p = p_start; p <= p_end; p++) {
3607 if (std::find(phys_list.begin(), phys_list.end(), p) == phys_list.end()) {
3608 phys_list.push_back(p);
3609 }
3610 }
3611 } catch (...) {
3612 GGML_LOG_WARN("ggml-hex: failed to parse physical range in '%s'\n", p_part.c_str());
3613 }
3614 } else {
3615 try {
3616 int p = std::stoi(p_part);
3617 if (std::find(phys_list.begin(), phys_list.end(), p) == phys_list.end()) {
3618 phys_list.push_back(p);
3619 }
3620 } catch (...) {
3621 GGML_LOG_WARN("ggml-hex: failed to parse physical index in '%s'\n", p_part.c_str());
3622 }
3623 }
3624 }
3625
3626 if (phys_list.empty()) {
3627 phys_list.push_back(0);
3628 }
3629
3630 if (opt_ndev < GGML_HEXAGON_MAX_SESSIONS) {
3631 auto & cfg = opt_device_configs[opt_ndev];
3632 cfg.name = dev_name;
3633 cfg.physical_idx = phys_list[0];
3634 cfg.virtual_idx = virt;
3635 cfg.mdev_group.clear();
3636
3637 for (size_t k = 1; k < phys_list.size(); k++) {
3638 ggml_hexagon_device_config sub_cfg;
3639 sub_cfg.physical_idx = phys_list[k];
3640 sub_cfg.virtual_idx = virt;
3641 sub_cfg.name = "HTP" + std::to_string(phys_list[k]) + ":" + std::to_string(virt);
3642 cfg.mdev_group.push_back(sub_cfg);
3643 }
3644 opt_ndev++;
3645 } else {
3646 GGML_LOG_WARN("ggml-hex: max sessions limit reached (%d), ignoring device %s\n", GGML_HEXAGON_MAX_SESSIONS, item.c_str());
3647 }
3648 } else if (item.rfind("HTP", 0) == 0) {
3649 std::string rest = item.substr(3);
3650 size_t colon_pos = rest.find(':');
3651 int phys = 0;
3652 int virt = 0;
3653 try {
3654 if (colon_pos == std::string::npos) {
3655 phys = std::stoi(rest);
3656 virt = 0;
3657 } else {
3658 phys = std::stoi(rest.substr(0, colon_pos));
3659 virt = std::stoi(rest.substr(colon_pos + 1));
3660 }
3661 } catch (...) {
3662 GGML_LOG_WARN("ggml-hex: failed to parse device index in '%s'\n", item.c_str());
3663 continue;
3664 }
3665
3666 if (opt_ndev < GGML_HEXAGON_MAX_SESSIONS) {
3667 opt_device_configs[opt_ndev].physical_idx = phys;
3668 opt_device_configs[opt_ndev].virtual_idx = virt;
3669 opt_device_configs[opt_ndev].name = colon_pos == std::string::npos
3670 ? "HTP" + std::to_string(phys)
3671 : "HTP" + std::to_string(phys) + ":" + std::to_string(virt);
3672 opt_device_configs[opt_ndev].mdev_group.clear();
3673 opt_ndev++;
3674 } else {
3675 GGML_LOG_WARN("ggml-hex: max sessions limit reached (%d), ignoring device %s\n", GGML_HEXAGON_MAX_SESSIONS, item.c_str());
3676 }
3677 } else {
3678 GGML_LOG_WARN("ggml-hex: invalid device name format '%s', must start with HTP\n", item.c_str());
3679 }
3680 }
3681 }
3682 } else {
3683 opt_ndev = 1;
3684 opt_device_configs[0].physical_idx = 0;
3685 opt_device_configs[0].virtual_idx = 0;
3686 opt_device_configs[0].name = "HTP0";
3687 opt_device_configs[0].mdev_group.clear();
3688 }
3689
3690#if defined(__ANDROID__)
3691 if (opt_arch < 75) {
3692 opt_ndev = 1;
3693 GGML_LOG_WARN("ggml-hex: forcing ndev to 1 for SoCs archs lower than v75.\n");
3694 }
3695#endif
3696
3697 // Resolve domain info for all configured devices
3698 ggml_hexagon_discover_devices();
3699
3700 if (str_profile) {
3701 opt_pmu_evt = [&]() -> std::vector<uint32_t> {
3702 auto v = str_to_vec<uint32_t>(str_profile);
3703 switch (v.size()) {
3704 case 1: opt_profile = v[0]; return opt_pmu_evt; // mode with default pmu events
3705 case 8: opt_profile = 2; return v; // mode with custom pmu events
3706 default: opt_profile = 0; return {}; // garbage input
3707 }}();
3708 if (opt_profile == 1) opt_pmu_evt = {};
3709 GGML_LOG_INFO("ggml-hex: Profiling mode %u : pmu-evt [ %s ]\n", opt_profile,
3710 vec_to_str<uint32_t, 16>(opt_pmu_evt).c_str());
3711 }
3712
3713 reg->context = new ggml_hexagon_registry(reg);
3714}
3715
3716static const struct ggml_backend_reg_i ggml_backend_hexagon_reg_i = {
3717 /* .get_name = */ ggml_backend_hexagon_reg_get_name,
3718 /* .get_device_count = */ ggml_backend_hexagon_reg_get_device_count,
3719 /* .get_device = */ ggml_backend_hexagon_reg_get_device,
3720 /* .get_proc_address = */ ggml_backend_hexagon_get_proc_address,
3721};
3722
3723ggml_backend_reg_t ggml_backend_hexagon_reg(void) {
3724 static bool initialized = false;
3725
3726 static ggml_backend_reg reg = { /* .api_version = */ GGML_BACKEND_API_VERSION,
3727 /* .iface = */ ggml_backend_hexagon_reg_i,
3728 /* .context = */ NULL };
3729
3730 {
3731 static std::mutex mutex;
3732 std::lock_guard<std::mutex> lock(mutex);
3733 if (!initialized) {
3734 auto nErr = htpdrv_init();
3735 if (nErr != AEE_SUCCESS) {
3736 return NULL;
3737 }
3738
3739 ggml_hexagon_init(&reg);
3740 }
3741
3742 initialized = true;
3743 }
3744
3745 return &reg;
3746}
3747
3748GGML_BACKEND_DL_IMPL(ggml_backend_hexagon_reg)