olnnn commited on
Commit
8d7ee7b
·
verified ·
1 Parent(s): 9962822

Update links and patch to v0.1.1-emeans (metadata-stub GGUF loader + full Windows ROCm runtime)

Browse files
README.md CHANGED
@@ -26,7 +26,7 @@ Experimental mixed-precision `e-means` quantizations of [Inkling-2-Mini](https:/
26
 
27
  > **Requires the `llama.cpp-emeans` Loader (Won't Open Directly in LM Studio / Ollama / Stock `llama.cpp`):**
28
  > `.emns` is a custom low-bit quant format, so standard GGUF loaders cannot read it natively.
29
- > - **Safe & open-source loader:** Grab a GitHub-Actions-built zip from [**`olsn-bit/llama.cpp-emeans` (`v0.1.0-emeans`)**](https://github.com/olsn-bit/llama.cpp-emeans/releases/tag/v0.1.0-emeans), or audit and compile it yourself from the full repo or [`0001-ggml-cuda-add-e-means-.emns-HIP-CUDA-kernels-WMMA-pr.patch`](patches/0001-ggml-cuda-add-e-means-.emns-HIP-CUDA-kernels-WMMA-pr.patch) (applies cleanly on `llama.cpp` `b2236cb39`).
30
  > - **Use any UI, harness, or CLI you want:** The loader only serves the model — once running on any `--port` you pick, it exposes a standard OpenAI-compatible API (`http://127.0.0.1:<PORT>/v1`) that plugs into **any** client (Open WebUI, OpenCode, Cline, `pi`, SillyTavern, Python, etc.), or run directly in terminal with `llama-cli`.
31
 
32
  ---
@@ -144,14 +144,14 @@ hf download olnnn/Inkling-2-Mini-EMEANS \
144
 
145
  ### 2. Get Patched `llama-server`
146
 
147
- Download the prebuilt release for your GPU from [**GitHub Releases (`v0.1.0-emeans`)**](https://github.com/olsn-bit/llama.cpp-emeans/releases/tag/v0.1.0-emeans):
148
 
149
  | Platform | GPU Backend | Archive |
150
  |---|---|---|
151
- | Windows (x64) | NVIDIA CUDA 12.4 | `llama-emeans-v0.1.0-emeans-win-cuda-12.4-x64.zip` |
152
- | Windows (x64) | AMD ROCm / HIP | `llama-emeans-v0.1.0-emeans-win-rocm-x64.zip` |
153
- | Linux (x64) | NVIDIA CUDA 12.8 | `llama-emeans-v0.1.0-emeans-ubuntu-cuda-12.8-x64.tar.gz` |
154
- | Linux (x64) | AMD ROCm / HIP | `llama-emeans-v0.1.0-emeans-ubuntu-rocm-x64.tar.gz` |
155
 
156
  <details>
157
  <summary>Or build from source (NVIDIA CUDA or AMD ROCm/HIP)</summary>
@@ -179,7 +179,7 @@ cmake --build build --target llama-server llama-bench -j
179
  Change `--port 8080` to any free port you prefer, then point your client at `http://127.0.0.1:<PORT>/v1` (or open it in a browser):
180
 
181
  ```bash
182
- # Linux / macOS bash (Windows PowerShell: $env:EMEANS_MODEL = "./inkling2/Inkling-2-Mini-3.04bpw.emns")
183
  export EMEANS_MODEL=./inkling2/Inkling-2-Mini-3.04bpw.emns
184
 
185
  ./llama-server \
 
26
 
27
  > **Requires the `llama.cpp-emeans` Loader (Won't Open Directly in LM Studio / Ollama / Stock `llama.cpp`):**
28
  > `.emns` is a custom low-bit quant format, so standard GGUF loaders cannot read it natively.
29
+ > - **Safe & open-source loader:** Grab a GitHub-Actions-built zip from [**`olsn-bit/llama.cpp-emeans` (`v0.1.1-emeans`)**](https://github.com/olsn-bit/llama.cpp-emeans/releases/tag/v0.1.1-emeans), or audit and compile it yourself from the full repo or [`0001-ggml-cuda-add-e-means-.emns-HIP-CUDA-kernels-WMMA-pr.patch`](patches/0001-ggml-cuda-add-e-means-.emns-HIP-CUDA-kernels-WMMA-pr.patch) (applies cleanly on `llama.cpp` `b2236cb39`).
30
  > - **Use any UI, harness, or CLI you want:** The loader only serves the model — once running on any `--port` you pick, it exposes a standard OpenAI-compatible API (`http://127.0.0.1:<PORT>/v1`) that plugs into **any** client (Open WebUI, OpenCode, Cline, `pi`, SillyTavern, Python, etc.), or run directly in terminal with `llama-cli`.
31
 
32
  ---
 
144
 
145
  ### 2. Get Patched `llama-server`
146
 
147
+ Download the prebuilt release for your GPU from [**GitHub Releases (`v0.1.1-emeans`)**](https://github.com/olsn-bit/llama.cpp-emeans/releases/tag/v0.1.1-emeans):
148
 
149
  | Platform | GPU Backend | Archive |
150
  |---|---|---|
151
+ | Windows (x64) | NVIDIA CUDA 12.4 | `llama-emeans-v0.1.1-emeans-win-cuda-12.4-x64.zip` |
152
+ | Windows (x64) | AMD ROCm / HIP | `llama-emeans-v0.1.1-emeans-win-rocm-x64.zip` |
153
+ | Linux (x64) | NVIDIA CUDA 12.8 | `llama-emeans-v0.1.1-emeans-ubuntu-cuda-12.8-x64.tar.gz` |
154
+ | Linux (x64) | AMD ROCm / HIP | `llama-emeans-v0.1.1-emeans-ubuntu-rocm-x64.tar.gz` |
155
 
156
  <details>
157
  <summary>Or build from source (NVIDIA CUDA or AMD ROCm/HIP)</summary>
 
179
  Change `--port 8080` to any free port you prefer, then point your client at `http://127.0.0.1:<PORT>/v1` (or open it in a browser):
180
 
181
  ```bash
182
+ # Linux / macOS bash (Windows PowerShell: $env:EMEANS_MODEL = "./inkling2/Inkling-2-Mini-3.04bpw.emns"; on Windows ROCm run .\bin\llama-server.exe)
183
  export EMEANS_MODEL=./inkling2/Inkling-2-Mini-3.04bpw.emns
184
 
185
  ./llama-server \
SHA256SUMS CHANGED
@@ -10,4 +10,4 @@ bf09342d285139fd37ce10c70878af1d52cb390e9901e10248654293a80ee636 tokenizer_conf
10
  53a9035f3255945704b5857657cfb00c1165090c0641c4f782a0cbf268cc16dc chat_template.jinja
11
  edbc4b020c75126e817d8c2a7c9860ef5d3bba52a0911d0df456cb63a21c84fb LICENSE
12
  23736eb340c036d7121f138ed34253976e40443fe6c05157ec7f8816b815d0e9 NOTICE
13
- dad8c2fd58af63b2ef0abe2efc106639f4a36e64605a2621fe7a35613bbe2509 patches/0001-ggml-cuda-add-e-means-.emns-HIP-CUDA-kernels-WMMA-pr.patch
 
10
  53a9035f3255945704b5857657cfb00c1165090c0641c4f782a0cbf268cc16dc chat_template.jinja
11
  edbc4b020c75126e817d8c2a7c9860ef5d3bba52a0911d0df456cb63a21c84fb LICENSE
12
  23736eb340c036d7121f138ed34253976e40443fe6c05157ec7f8816b815d0e9 NOTICE
13
+ 9dc129964451ae74c922e04610f315bb9c0149946bd5c4c97d7850555c831072 patches/0001-ggml-cuda-add-e-means-.emns-HIP-CUDA-kernels-WMMA-pr.patch
patches/0001-ggml-cuda-add-e-means-.emns-HIP-CUDA-kernels-WMMA-pr.patch CHANGED
@@ -1,32 +1,8 @@
1
- From d1055df207b3531d02ae2ccb86e0098be6a12ab6 Mon Sep 17 00:00:00 2001
2
- From: Oln <oln@local>
3
- Date: Wed, 25 Nov 2026 10:38:45 +0100
4
- Subject: [PATCH] ggml-cuda: add e-means (.emns) HIP+CUDA kernels, WMMA
5
- prefill, and 4-bit vision loader
6
-
7
- ---
8
- ggml/include/ggml-cuda.h | 6 +
9
- ggml/src/ggml-alloc.c | 6 +
10
- ggml/src/ggml-cuda/depth-mix.cu | 8 +
11
- ggml/src/ggml-cuda/emeans.cu | 1904 +++++++++++++++++++++++++++++++
12
- ggml/src/ggml-cuda/emeans.cuh | 8 +
13
- ggml/src/ggml-cuda/fattn-rel.cu | 4 +
14
- ggml/src/ggml-cuda/ggml-cuda.cu | 15 +-
15
- ggml/src/ggml-cuda/pad.cu | 33 +
16
- src/llama-emeans-hook.h | 78 ++
17
- src/llama-model-loader.cpp | 7 +
18
- src/llama-model.cpp | 42 +-
19
- tools/mtmd/mtmd-model.cpp | 252 +++-
20
- 12 files changed, 2360 insertions(+), 3 deletions(-)
21
- create mode 100644 ggml/src/ggml-cuda/emeans.cu
22
- create mode 100644 ggml/src/ggml-cuda/emeans.cuh
23
- create mode 100644 src/llama-emeans-hook.h
24
-
25
  diff --git a/ggml/include/ggml-cuda.h b/ggml/include/ggml-cuda.h
26
- index 1cd81eeae..dc43d062c 100644
27
  --- a/ggml/include/ggml-cuda.h
28
  +++ b/ggml/include/ggml-cuda.h
29
- @@ -42,6 +42,12 @@ GGML_BACKEND_API void ggml_backend_cuda_unregister_host_buffer(void * buffer);
30
 
31
  GGML_BACKEND_API ggml_backend_reg_t ggml_backend_cuda_reg(void);
32
 
@@ -35,6 +11,7 @@ index 1cd81eeae..dc43d062c 100644
35
  +GGML_BACKEND_API ggml_backend_buffer_t ggml_cuda_emeans_get_stub_buffer(ggml_backend_buffer_type_t buft);
36
  +GGML_BACKEND_API void * ggml_cuda_emeans_bind_tensor(const char * gguf_name, int64_t ne0, int64_t ne1, int64_t ne2);
37
  +GGML_BACKEND_API bool ggml_cuda_emeans_is_stub(const void * ptr);
 
38
  +
39
  #ifdef __cplusplus
40
  }
@@ -93,10 +70,10 @@ index 69bd00f80..67a273795 100644
93
  __shared__ float red_mm[nq][DEPTH_MIX_BLOCK / WARP_SIZE];
94
  diff --git a/ggml/src/ggml-cuda/emeans.cu b/ggml/src/ggml-cuda/emeans.cu
95
  new file mode 100644
96
- index 000000000..a68b333b6
97
  --- /dev/null
98
  +++ b/ggml/src/ggml-cuda/emeans.cu
99
- @@ -0,0 +1,1904 @@
100
  +#include "emeans.cuh"
101
  +#include "ggml-cuda.h"
102
  +
@@ -120,6 +97,7 @@ index 000000000..a68b333b6
120
  +#define hipFree cudaFree
121
  +#define hipMemcpy cudaMemcpy
122
  +#define hipMemcpyHostToDevice cudaMemcpyHostToDevice
 
123
  +#define hipGetErrorString cudaGetErrorString
124
  +#define EM_LAUNCH_BOUNDS __launch_bounds__(256)
125
  +#define EM_LAUNCH_BOUNDS_GEMV __launch_bounds__(256)
@@ -147,6 +125,7 @@ index 000000000..a68b333b6
147
  + EM_FMT_EM1D_Q4_G64 = 3,
148
  + EM_FMT_EM1D_Q3_G64 = 4,
149
  + EM_FMT_EM2D_K32_G128 = 5,
 
150
  +};
151
  +
152
  +struct EmPlane {
@@ -375,6 +354,7 @@ index 000000000..a68b333b6
375
  +
376
  +bool ggml_cuda_emeans_init(const char * emns_path) {
377
  + if (!emns_path || !emns_path[0]) return false;
 
378
  + auto & st = emns_state();
379
  + std::lock_guard<std::mutex> lock(st.mtx);
380
  + if (st.loaded && st.loaded_path == emns_path) {
@@ -389,7 +369,7 @@ index 000000000..a68b333b6
389
  + char magic[8];
390
  + uint64_t manifest_len = 0;
391
  + if (fread(magic, 1, 8, f) != 8 || memcmp(magic, EMNS_MAGIC, 8) != 0 ||
392
- + fread(&manifest_len, 8, 1, f) != 1) {
393
  + fprintf(stderr, "[emeans] ERROR: invalid .emns header in '%s'\n", emns_path);
394
  + fclose(f);
395
  + return false;
@@ -403,21 +383,41 @@ index 000000000..a68b333b6
403
  + uint64_t data_base = (hdr_end + 63ULL) & ~63ULL;
404
  +#if defined(_WIN32)
405
  + _fseeki64(f, 0, SEEK_END);
406
- + uint64_t file_size = (uint64_t)_ftelli64(f);
407
  + _fseeki64(f, (long long)data_base, SEEK_SET);
408
  +#else
409
  + fseeko(f, 0, SEEK_END);
410
- + uint64_t file_size = (uint64_t)ftello(f);
411
  + fseeko(f, (off_t)data_base, SEEK_SET);
412
  +#endif
413
- + uint64_t data_bytes = file_size - data_base;
 
 
 
 
 
414
  +
415
- + st.tensors.clear();
416
- + if (!em_parse_manifest(mjson, st.tensors)) {
417
  + fprintf(stderr, "[emeans] ERROR: failed to parse manifest\n");
418
  + fclose(f);
419
  + return false;
420
  + }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
421
  +
422
  + if (st.d_blob) { hipFree(st.d_blob); st.d_blob = nullptr; }
423
  + hipError_t err = hipMalloc(&st.d_blob, data_bytes);
@@ -466,6 +466,10 @@ index 000000000..a68b333b6
466
  + fprintf(stderr, "[emeans] Loaded '%s': %.4f GiB (%zu tensors) into contiguous HIP VRAM\n",
467
  + emns_path, data_bytes / 1073741824.0, st.tensors.size());
468
  + return true;
 
 
 
 
469
  +}
470
  +
471
  +#ifdef _WIN32
@@ -473,6 +477,7 @@ index 000000000..a68b333b6
473
  +#endif
474
  +bool ggml_cuda_emeans_init_extra(const char * emns_path) {
475
  + if (!emns_path || !emns_path[0]) return false;
 
476
  + auto & st = emns_state();
477
  + std::lock_guard<std::mutex> lock(st.mtx);
478
  + for (const auto & p : st.extra_paths) {
@@ -487,7 +492,7 @@ index 000000000..a68b333b6
487
  + char magic[8];
488
  + uint64_t manifest_len = 0;
489
  + if (fread(magic, 1, 8, f) != 8 || memcmp(magic, EMNS_MAGIC, 8) != 0 ||
490
- + fread(&manifest_len, 8, 1, f) != 1) {
491
  + fprintf(stderr, "[emeans] ERROR: invalid .emns header in '%s'\n", emns_path);
492
  + fclose(f);
493
  + return false;
@@ -501,14 +506,19 @@ index 000000000..a68b333b6
501
  + uint64_t data_base = (hdr_end + 63ULL) & ~63ULL;
502
  +#if defined(_WIN32)
503
  + _fseeki64(f, 0, SEEK_END);
504
- + uint64_t file_size = (uint64_t)_ftelli64(f);
505
  + _fseeki64(f, (long long)data_base, SEEK_SET);
506
  +#else
507
  + fseeko(f, 0, SEEK_END);
508
- + uint64_t file_size = (uint64_t)ftello(f);
509
  + fseeko(f, (off_t)data_base, SEEK_SET);
510
  +#endif
511
- + uint64_t data_bytes = file_size - data_base;
 
 
 
 
 
512
  +
513
  + std::unordered_map<std::string, EmTensor> extra_tensors;
514
  + if (!em_parse_manifest(mjson, extra_tensors)) {
@@ -516,6 +526,16 @@ index 000000000..a68b333b6
516
  + fclose(f);
517
  + return false;
518
  + }
 
 
 
 
 
 
 
 
 
 
519
  +
520
  + uint8_t * d_extra = nullptr;
521
  + hipError_t err = hipMalloc(&d_extra, data_bytes);
@@ -549,7 +569,8 @@ index 000000000..a68b333b6
549
  +
550
  + size_t n_added = 0;
551
  + for (auto & kv : extra_tensors) {
552
- + if (kv.second.fmt != EM_FMT_EM1D_Q4_G64 && kv.second.fmt != EM_FMT_EM1D_Q3_G64 && kv.second.fmt != EM_FMT_EM2D_K32_G128) {
 
553
  + continue;
554
  + }
555
  + for (auto & pk : kv.second.planes) {
@@ -565,6 +586,10 @@ index 000000000..a68b333b6
565
  + fprintf(stderr, "[emeans] Loaded extra '%s': %.2f MiB (%zu quantized tensors) into HIP VRAM\n",
566
  + emns_path, data_bytes / 1048576.0, n_added);
567
  + return true;
 
 
 
 
568
  +}
569
  +
570
  +ggml_backend_buffer_t ggml_cuda_emeans_get_stub_buffer(ggml_backend_buffer_type_t buft) {
@@ -593,8 +618,52 @@ index 000000000..a68b333b6
593
  + if (it == st.tensors.end()) return nullptr;
594
  + const EmTensor & em = it->second;
595
  +
596
- + // Only bind quantized formats (EM1D_Q4_G64, EM1D_Q3_G64, EM2D_K32_G128)
597
- + if (em.fmt != EM_FMT_EM1D_Q4_G64 && em.fmt != EM_FMT_EM1D_Q3_G64 && em.fmt != EM_FMT_EM2D_K32_G128) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
598
  + return nullptr;
599
  + }
600
  + // Verify shape match (GGML [K, N, E] vs EMNS [N, K] or [E, N, K])
@@ -630,6 +699,150 @@ index 000000000..a68b333b6
630
  + return p >= st.stub_base && p < st.stub_base + EmnsState::MAX_STUBS * EmnsState::STUB_STRIDE;
631
  +}
632
  +
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
633
  +} // extern "C"
634
  +
635
  +static inline const EmTensor * emns_lookup(const ggml_tensor * src0) {
@@ -655,10 +868,14 @@ index 000000000..a68b333b6
655
  +static __device__ __forceinline__ em_gacc_t em_gacc_zero() { return 0.0f; }
656
  +static __device__ __forceinline__ em_gacc_t em_gacc_fdot2(uint32_t a_bits, uint32_t b_bits, em_gacc_t acc) {
657
  + union { uint32_t u; em_f16x2_t v; } ua{a_bits}, ub{b_bits};
 
658
  + return __builtin_amdgcn_fdot2(ua.v, ub.v, acc, false);
 
 
 
659
  +}
660
  +static __device__ __forceinline__ float em_gacc_to_f32(em_gacc_t acc) { return acc; }
661
- +#else
662
  +typedef __half2 em_gacc_t;
663
  +static __device__ __forceinline__ em_gacc_t em_gacc_zero() { return __float2half2_rn(0.0f); }
664
  +static __device__ __forceinline__ em_gacc_t em_gacc_fdot2(uint32_t a_bits, uint32_t b_bits, em_gacc_t acc) {
@@ -671,6 +888,18 @@ index 000000000..a68b333b6
671
  + float2 f2 = __half22float2(acc);
672
  + return f2.x + f2.y;
673
  +}
 
 
 
 
 
 
 
 
 
 
 
 
674
  +#endif
675
  +
676
  +static __device__ __forceinline__ uint32_t em_pack_h16(uint32_t lo16, uint32_t hi16) {
@@ -1080,6 +1309,79 @@ index 000000000..a68b333b6
1080
  + }
1081
  +}
1082
  +
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1083
  +// --- 4. Single-Launch Zero-Sync GPU-Grouped BT=8 MoE Prefill/Verify Kernels ---
1084
  +__global__ void em_moe_build_tiles_kernel(
1085
  + const int32_t * __restrict__ ids,
@@ -1229,14 +1531,17 @@ index 000000000..a68b333b6
1229
  + wh2[p] = em_pack_h16(EM_SHFL(my_lut, i0, 32), EM_SHFL(my_lut, i1, 32));
1230
  + }
1231
  + if (valid) {
1232
- + for (int b = 0; b < cnt; ++b) {
1233
- + const uint4 xw = x_u4[s_xbase[b] + xb + w];
1234
- + em_gacc_t gb = gv[b];
1235
- + gb = em_gacc_fdot2(wh2[0], xw.x, gb);
1236
- + gb = em_gacc_fdot2(wh2[1], xw.y, gb);
1237
- + gb = em_gacc_fdot2(wh2[2], xw.z, gb);
1238
- + gb = em_gacc_fdot2(wh2[3], xw.w, gb);
1239
- + gv[b] = gb;
 
 
 
1240
  + }
1241
  + }
1242
  + }
@@ -1343,14 +1648,128 @@ index 000000000..a68b333b6
1343
  + wh2[p] = EM_SHFL(my_lut, idx, 32);
1344
  + }
1345
  + if (valid) {
1346
- + for (int b = 0; b < cnt; ++b) {
1347
- + const uint4 xw = x_u4[s_xbase[b] + xb + w];
1348
- + em_gacc_t gb = gv[b];
1349
- + gb = em_gacc_fdot2(wh2[0], xw.x, gb);
1350
- + gb = em_gacc_fdot2(wh2[1], xw.y, gb);
1351
- + gb = em_gacc_fdot2(wh2[2], xw.z, gb);
1352
- + gb = em_gacc_fdot2(wh2[3], xw.w, gb);
1353
- + gv[b] = gb;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1354
  + }
1355
  + }
1356
  + }
@@ -1469,11 +1888,11 @@ index 000000000..a68b333b6
1469
  +
1470
  + __shared__ uint32_t s_pairs[16];
1471
  + __shared__ size_t s_xbase[16];
1472
- + alignas(16) __shared__ union {
1473
  + uint16_t w[128][40];
1474
  + float c[8][256];
1475
  + } s_mem;
1476
- + alignas(16) __shared__ uint16_t s_X[16][40];
1477
  +
1478
  + if (tid < cnt) {
1479
  + const uint32_t pr = sorted_pairs[pstart + tid];
@@ -1608,11 +2027,11 @@ index 000000000..a68b333b6
1608
  +
1609
  + __shared__ uint32_t s_pairs[16];
1610
  + __shared__ size_t s_xbase[16];
1611
- + alignas(16) __shared__ union {
1612
  + uint16_t w[128][40];
1613
  + float c[8][256];
1614
  + } s_mem;
1615
- + alignas(16) __shared__ uint16_t s_X[16][40];
1616
  +
1617
  + if (tid < cnt) {
1618
  + const uint32_t pr = sorted_pairs[pstart + tid];
@@ -1716,6 +2135,139 @@ index 000000000..a68b333b6
1716
  + }
1717
  +#endif
1718
  +}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1719
  +#endif // !GGML_USE_HIP
1720
  +
1721
  +// ============================================================================
@@ -1857,6 +2409,15 @@ index 000000000..a68b333b6
1857
  + reinterpret_cast<const uint32_t *>(x_f16.get()),
1858
  + (float *)dst->data,
1859
  + N, K, ne11, em->is_w13 ? 1 : 0, ids_nb1_i32, y_nb1_f32, y_nb2_f32);
 
 
 
 
 
 
 
 
 
1860
  + } else {
1861
  + GGML_ABORT("[emeans] unsupported MoE format %u", em->fmt);
1862
  + }
@@ -1906,6 +2467,17 @@ index 000000000..a68b333b6
1906
  + reinterpret_cast<const uint32_t *>(x_f16.get()),
1907
  + (float *)dst->data,
1908
  + N, K, ne11, em->is_w13 ? 1 : 0, y_nb1_f32, y_nb2_f32);
 
 
 
 
 
 
 
 
 
 
 
1909
  + } else {
1910
  + GGML_ABORT("[emeans] unsupported MoE format %u", em->fmt);
1911
  + }
@@ -1954,6 +2526,17 @@ index 000000000..a68b333b6
1954
  + reinterpret_cast<const uint32_t *>(x_f16.get()),
1955
  + (float *)dst->data,
1956
  + N, K, ne11, em->is_w13 ? 1 : 0, y_nb1_f32, y_nb2_f32);
 
 
 
 
 
 
 
 
 
 
 
1957
  + } else {
1958
  + GGML_ABORT("[emeans] unsupported MoE format %u", em->fmt);
1959
  + }
@@ -1994,6 +2577,7 @@ index 000000000..a68b333b6
1994
  +ggml_backend_buffer_t ggml_cuda_emeans_get_stub_buffer(ggml_backend_buffer_type_t) { return nullptr; }
1995
  +void * ggml_cuda_emeans_bind_tensor(const char *, int64_t, int64_t, int64_t) { return nullptr; }
1996
  +bool ggml_cuda_emeans_is_stub(const void *) { return false; }
 
1997
  +}
1998
  +bool ggml_cuda_emeans_has(const ggml_tensor *) { return false; }
1999
  +bool ggml_cuda_emeans_try_mul_mat(ggml_backend_cuda_context &, const ggml_tensor *, const ggml_tensor *, ggml_tensor *) { return false; }
@@ -2031,7 +2615,7 @@ index 5dfeedf87..e22dd8768 100644
2031
 
2032
  return false;
2033
  diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu
2034
- index 93f8b35ea..8b9652e8b 100644
2035
  --- a/ggml/src/ggml-cuda/ggml-cuda.cu
2036
  +++ b/ggml/src/ggml-cuda/ggml-cuda.cu
2037
  @@ -27,6 +27,7 @@
@@ -2042,7 +2626,39 @@ index 93f8b35ea..8b9652e8b 100644
2042
  #include "ggml-cuda/diffusion-sampling.cuh"
2043
  #include "ggml-cuda/fattn.cuh"
2044
  #include "ggml-cuda/fattn-banded.cuh"
2045
- @@ -2586,6 +2587,10 @@ static bool ggml_cuda_should_fuse_mul_mat_q(const ggml_tensor * up, const ggml_t
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2046
  static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
2047
  GGML_TENSOR_BINARY_OP_LOCALS
2048
 
@@ -2053,7 +2669,7 @@ index 93f8b35ea..8b9652e8b 100644
2053
  if (ggml_cuda_op_mul_mat_use_fwht(dst) && ggml_cuda_op_fwht(ctx, src1, dst)) {
2054
  return;
2055
  }
2056
- @@ -2654,6 +2659,9 @@ static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor
2057
  // [TAG_MUL_MAT_ID_CUDA_GRAPHS]
2058
  static bool ggml_cuda_mul_mat_id_needs_sync(const ggml_tensor * dst, const int cc) {
2059
  const ggml_tensor * src0 = dst->src[0];
@@ -2063,7 +2679,7 @@ index 93f8b35ea..8b9652e8b 100644
2063
  const ggml_tensor * src1 = dst->src[1];
2064
  const bool f32_pedantic = src0->type == GGML_TYPE_F32 &&
2065
  ggml_prec(dst->op_params[0]) == GGML_PREC_F32_PEDANTIC;
2066
- @@ -2693,6 +2701,9 @@ static bool ggml_cuda_mul_mat_id_needs_sync(const ggml_tensor * dst, const int c
2067
  }
2068
 
2069
  static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
@@ -2073,7 +2689,7 @@ index 93f8b35ea..8b9652e8b 100644
2073
  const ggml_tensor * src0 = dst->src[0];
2074
  const ggml_tensor * src1 = dst->src[1];
2075
  const ggml_tensor * ids = dst->src[2];
2076
- @@ -2923,7 +2934,9 @@ static bool ggml_cuda_compute_forward(ggml_backend_cuda_context & ctx, struct gg
2077
  ggml_cuda_op_repeat_back(ctx, dst);
2078
  break;
2079
  case GGML_OP_GET_ROWS:
@@ -2084,6 +2700,18 @@ index 93f8b35ea..8b9652e8b 100644
2084
  break;
2085
  case GGML_OP_GET_ROWS_BACK:
2086
  ggml_cuda_op_get_rows_back(ctx, dst);
 
 
 
 
 
 
 
 
 
 
 
 
2087
  diff --git a/ggml/src/ggml-cuda/pad.cu b/ggml/src/ggml-cuda/pad.cu
2088
  index ac078b449..5f60c070e 100644
2089
  --- a/ggml/src/ggml-cuda/pad.cu
@@ -2135,10 +2763,10 @@ index ac078b449..5f60c070e 100644
2135
  pad_f32<<<gridDim, CUDA_PAD_BLOCK_SIZE, 0, stream>>>(src, s00, s01, s02, s03, dst,
2136
  diff --git a/src/llama-emeans-hook.h b/src/llama-emeans-hook.h
2137
  new file mode 100644
2138
- index 000000000..511183707
2139
  --- /dev/null
2140
  +++ b/src/llama-emeans-hook.h
2141
- @@ -0,0 +1,78 @@
2142
  +#pragma once
2143
  +
2144
  +#include "ggml.h"
@@ -2159,11 +2787,13 @@ index 000000000..511183707
2159
  + using get_buf_fn = ggml_backend_buffer_t (*)(ggml_backend_buffer_type_t);
2160
  + using bind_fn = void * (*)(const char *, int64_t, int64_t, int64_t);
2161
  + using is_stub_fn = bool (*)(const void *);
 
2162
  +
2163
- + init_fn init = nullptr;
2164
- + get_buf_fn get_buf = nullptr;
2165
- + bind_fn bind = nullptr;
2166
- + is_stub_fn is_stub = nullptr;
 
2167
  + bool resolved = false;
2168
  +
2169
  + static llama_emeans_api & get() {
@@ -2173,10 +2803,11 @@ index 000000000..511183707
2173
  + HMODULE mod = GetModuleHandleA("ggml-hip.dll");
2174
  + if (!mod) mod = GetModuleHandleA("ggml-cuda.dll");
2175
  + if (mod) {
2176
- + api.init = reinterpret_cast<init_fn>(GetProcAddress(mod, "ggml_cuda_emeans_init"));
2177
- + api.get_buf = reinterpret_cast<get_buf_fn>(GetProcAddress(mod, "ggml_cuda_emeans_get_stub_buffer"));
2178
- + api.bind = reinterpret_cast<bind_fn>(GetProcAddress(mod, "ggml_cuda_emeans_bind_tensor"));
2179
- + api.is_stub = reinterpret_cast<is_stub_fn>(GetProcAddress(mod, "ggml_cuda_emeans_is_stub"));
 
2180
  + }
2181
  + }
2182
  + return api;
@@ -2192,11 +2823,13 @@ index 000000000..511183707
2192
  + using get_buf_fn = ggml_backend_buffer_t (*)(ggml_backend_buffer_type_t);
2193
  + using bind_fn = void * (*)(const char *, int64_t, int64_t, int64_t);
2194
  + using is_stub_fn = bool (*)(const void *);
 
2195
  +
2196
- + init_fn init = nullptr;
2197
- + get_buf_fn get_buf = nullptr;
2198
- + bind_fn bind = nullptr;
2199
- + is_stub_fn is_stub = nullptr;
 
2200
  + bool resolved = false;
2201
  +
2202
  + static llama_emeans_api & get() {
@@ -2206,10 +2839,11 @@ index 000000000..511183707
2206
  + void * mod = dlopen("libggml-cuda.so", RTLD_LAZY | RTLD_NOLOAD);
2207
  + if (!mod) mod = dlopen("libggml-hip.so", RTLD_LAZY | RTLD_NOLOAD);
2208
  + void * handle = mod ? mod : RTLD_DEFAULT;
2209
- + api.init = reinterpret_cast<init_fn>(dlsym(handle, "ggml_cuda_emeans_init"));
2210
- + api.get_buf = reinterpret_cast<get_buf_fn>(dlsym(handle, "ggml_cuda_emeans_get_stub_buffer"));
2211
- + api.bind = reinterpret_cast<bind_fn>(dlsym(handle, "ggml_cuda_emeans_bind_tensor"));
2212
- + api.is_stub = reinterpret_cast<is_stub_fn>(dlsym(handle, "ggml_cuda_emeans_is_stub"));
 
2213
  + }
2214
  + return api;
2215
  + }
@@ -2218,7 +2852,7 @@ index 000000000..511183707
2218
  +};
2219
  +#endif
2220
  diff --git a/src/llama-model-loader.cpp b/src/llama-model-loader.cpp
2221
- index 6c3324f4d..365929dcb 100644
2222
  --- a/src/llama-model-loader.cpp
2223
  +++ b/src/llama-model-loader.cpp
2224
  @@ -1,4 +1,5 @@
@@ -2227,9 +2861,78 @@ index 6c3324f4d..365929dcb 100644
2227
 
2228
  #include "ggml-alloc.h"
2229
  #include "ggml.h"
2230
- @@ -1883,6 +1884,12 @@ bool llama_model_loader::load_all_data(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2231
  // allocated from the CPU buffer type, which uses vm_allocate on Apple platforms, so freeing it returns its pages to the OS right away
2232
  ggml_backend_buffer_ptr read_buf;
 
 
 
 
 
 
 
 
 
 
2233
  for (struct ggml_tensor * cur : tensors) {
2234
  + if (cur->data != nullptr) {
2235
  + auto & em_api = llama_emeans_api::get();
@@ -2240,8 +2943,113 @@ index 6c3324f4d..365929dcb 100644
2240
  const auto * weight = get_weight(ggml_get_name(cur));
2241
  if (weight == nullptr) {
2242
  // this can happen with split experts models
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2243
  diff --git a/src/llama-model.cpp b/src/llama-model.cpp
2244
- index cd5cd601c..3ddde34bc 100644
2245
  --- a/src/llama-model.cpp
2246
  +++ b/src/llama-model.cpp
2247
  @@ -1,4 +1,5 @@
@@ -2250,17 +3058,35 @@ index cd5cd601c..3ddde34bc 100644
2250
 
2251
  #include "llama-arch.h"
2252
  #include "llama-ext.h"
2253
- @@ -2263,7 +2264,34 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {
2254
  t->buffer = buf; // set dummy buffer for weights so that the backend scheduler won't try to allocate them
2255
  }
2256
  } else {
2257
  - buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft); // real buffer
2258
  + const char * emns_env = std::getenv("EMEANS_MODEL");
2259
  + bool emns_bound_any = false;
2260
- + if (emns_env && emns_env[0] && arch != LLM_ARCH_DFLASH && !ggml_backend_buft_is_host(buft)) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2261
  + auto & em_api = llama_emeans_api::get();
2262
  + if (em_api.ok() && em_api.init(emns_env)) {
2263
- + ggml_backend_buffer_t stub_buf = em_api.get_buf(buft);
2264
  + if (stub_buf) {
2265
  + int n_bound = 0;
2266
  + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) {
@@ -2286,18 +3112,39 @@ index cd5cd601c..3ddde34bc 100644
2286
  }
2287
  if (buf == nullptr) {
2288
  throw std::runtime_error(format("unable to allocate %s buffer", ggml_backend_buft_name(buft)));
2289
- @@ -2358,6 +2386,18 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {
 
 
 
 
 
 
 
 
 
2290
 
2291
  load_tensors_hadamard();
2292
 
2293
  + {
2294
  + const char * emns_env_sc = std::getenv("EMEANS_MODEL");
2295
  + if (emns_env_sc && emns_env_sc[0]) {
2296
- + w_scales.clear();
2297
- + for (auto & l : layers) {
2298
- + l.ffn_gate_exps_s = nullptr;
2299
- + l.ffn_down_exps_s = nullptr;
2300
- + l.ffn_up_exps_s = nullptr;
 
 
 
 
 
 
 
 
 
 
 
 
2301
  + }
2302
  + }
2303
  + }
@@ -2306,10 +3153,10 @@ index cd5cd601c..3ddde34bc 100644
2306
 
2307
  return true;
2308
  diff --git a/tools/mtmd/mtmd-model.cpp b/tools/mtmd/mtmd-model.cpp
2309
- index 157c6959b..d04955728 100644
2310
  --- a/tools/mtmd/mtmd-model.cpp
2311
  +++ b/tools/mtmd/mtmd-model.cpp
2312
- @@ -25,6 +25,151 @@
2313
  #include <functional>
2314
  #include <float.h>
2315
 
@@ -2321,6 +3168,8 @@ index 157c6959b..d04955728 100644
2321
  +#define NOMINMAX
2322
  +#endif
2323
  +#include <windows.h>
 
 
2324
  +#endif
2325
  +
2326
  +// --- Minimal E-Means Vision (.emns) Loader Helpers (GPU stub-bind + CPU 4-bit dequant) ---
@@ -2345,6 +3194,13 @@ index 157c6959b..d04955728 100644
2345
  + api.get_buf = reinterpret_cast<get_buf_fn>(GetProcAddress(mod, "ggml_cuda_emeans_get_stub_buffer"));
2346
  + api.bind = reinterpret_cast<bind_fn>(GetProcAddress(mod, "ggml_cuda_emeans_bind_tensor"));
2347
  + }
 
 
 
 
 
 
 
2348
  +#endif
2349
  + return api;
2350
  + }
@@ -2461,7 +3317,7 @@ index 157c6959b..d04955728 100644
2461
  //
2462
  // mtmd_model_loader
2463
  //
2464
- @@ -4472,15 +4617,114 @@ struct mtmd_model_loader {
2465
  total_data_size += ggml_nbytes(t);
2466
  }
2467
 
@@ -2577,7 +3433,7 @@ index 157c6959b..d04955728 100644
2577
  auto it_off = tensor_offset.find(t->name);
2578
  GGML_ASSERT(it_off != tensor_offset.end() && "no offset for tensor");
2579
  const size_t offset = it_off->second;
2580
- @@ -4506,6 +4750,12 @@ struct mtmd_model_loader {
2581
  }
2582
  }
2583
  }
@@ -2590,6 +3446,3 @@ index 157c6959b..d04955728 100644
2590
  LOG_DBG("%s: loaded %zu tensors from %s\n", __func__, tensors_to_load.size(), fname.c_str());
2591
  } else {
2592
  LOG_DBG("%s: no_alloc is set, skipping tensor data loading (%zu tensors)\n", __func__, tensors_to_load.size());
2593
- --
2594
- 2.55.0.windows.3
2595
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  diff --git a/ggml/include/ggml-cuda.h b/ggml/include/ggml-cuda.h
2
+ index 1cd81eeae..fd160c9e6 100644
3
  --- a/ggml/include/ggml-cuda.h
4
  +++ b/ggml/include/ggml-cuda.h
5
+ @@ -42,6 +42,13 @@ GGML_BACKEND_API void ggml_backend_cuda_unregister_host_buffer(void * buffer);
6
 
7
  GGML_BACKEND_API ggml_backend_reg_t ggml_backend_cuda_reg(void);
8
 
 
11
  +GGML_BACKEND_API ggml_backend_buffer_t ggml_cuda_emeans_get_stub_buffer(ggml_backend_buffer_type_t buft);
12
  +GGML_BACKEND_API void * ggml_cuda_emeans_bind_tensor(const char * gguf_name, int64_t ne0, int64_t ne1, int64_t ne2);
13
  +GGML_BACKEND_API bool ggml_cuda_emeans_is_stub(const void * ptr);
14
+ +GGML_BACKEND_API size_t ggml_cuda_emeans_copy_raw_tensor(const char * gguf_name, float * dst_f32, size_t max_elems, int loop_start);
15
  +
16
  #ifdef __cplusplus
17
  }
 
70
  __shared__ float red_mm[nq][DEPTH_MIX_BLOCK / WARP_SIZE];
71
  diff --git a/ggml/src/ggml-cuda/emeans.cu b/ggml/src/ggml-cuda/emeans.cu
72
  new file mode 100644
73
+ index 000000000..c20ee91d9
74
  --- /dev/null
75
  +++ b/ggml/src/ggml-cuda/emeans.cu
76
+ @@ -0,0 +1,2511 @@
77
  +#include "emeans.cuh"
78
  +#include "ggml-cuda.h"
79
  +
 
97
  +#define hipFree cudaFree
98
  +#define hipMemcpy cudaMemcpy
99
  +#define hipMemcpyHostToDevice cudaMemcpyHostToDevice
100
+ +#define hipMemcpyDeviceToHost cudaMemcpyDeviceToHost
101
  +#define hipGetErrorString cudaGetErrorString
102
  +#define EM_LAUNCH_BOUNDS __launch_bounds__(256)
103
  +#define EM_LAUNCH_BOUNDS_GEMV __launch_bounds__(256)
 
125
  + EM_FMT_EM1D_Q4_G64 = 3,
126
  + EM_FMT_EM1D_Q3_G64 = 4,
127
  + EM_FMT_EM2D_K32_G128 = 5,
128
+ + EM_FMT_EM2D_K16_G128 = 6,
129
  +};
130
  +
131
  +struct EmPlane {
 
354
  +
355
  +bool ggml_cuda_emeans_init(const char * emns_path) {
356
  + if (!emns_path || !emns_path[0]) return false;
357
+ + try {
358
  + auto & st = emns_state();
359
  + std::lock_guard<std::mutex> lock(st.mtx);
360
  + if (st.loaded && st.loaded_path == emns_path) {
 
369
  + char magic[8];
370
  + uint64_t manifest_len = 0;
371
  + if (fread(magic, 1, 8, f) != 8 || memcmp(magic, EMNS_MAGIC, 8) != 0 ||
372
+ + fread(&manifest_len, 8, 1, f) != 1 || manifest_len == 0 || manifest_len > (64ULL << 20)) {
373
  + fprintf(stderr, "[emeans] ERROR: invalid .emns header in '%s'\n", emns_path);
374
  + fclose(f);
375
  + return false;
 
383
  + uint64_t data_base = (hdr_end + 63ULL) & ~63ULL;
384
  +#if defined(_WIN32)
385
  + _fseeki64(f, 0, SEEK_END);
386
+ + int64_t raw_size = _ftelli64(f);
387
  + _fseeki64(f, (long long)data_base, SEEK_SET);
388
  +#else
389
  + fseeko(f, 0, SEEK_END);
390
+ + int64_t raw_size = (int64_t)ftello(f);
391
  + fseeko(f, (off_t)data_base, SEEK_SET);
392
  +#endif
393
+ + if (raw_size <= 0 || (uint64_t)raw_size <= data_base) {
394
+ + fprintf(stderr, "[emeans] ERROR: truncated .emns file '%s'\n", emns_path);
395
+ + fclose(f);
396
+ + return false;
397
+ + }
398
+ + uint64_t data_bytes = (uint64_t)raw_size - data_base;
399
  +
400
+ + std::unordered_map<std::string, EmTensor> parsed_tensors;
401
+ + if (!em_parse_manifest(mjson, parsed_tensors)) {
402
  + fprintf(stderr, "[emeans] ERROR: failed to parse manifest\n");
403
  + fclose(f);
404
  + return false;
405
  + }
406
+ + for (const auto & kv : parsed_tensors) {
407
+ + for (const auto & pk : kv.second.planes) {
408
+ + if (pk.second.offset > data_bytes || pk.second.nbytes > data_bytes - pk.second.offset) {
409
+ + fprintf(stderr, "[emeans] ERROR: plane '%s.%s' out of bounds (off=%llu, nbytes=%llu, data=%llu)\n",
410
+ + kv.first.c_str(), pk.first.c_str(),
411
+ + (unsigned long long)pk.second.offset,
412
+ + (unsigned long long)pk.second.nbytes,
413
+ + (unsigned long long)data_bytes);
414
+ + fclose(f);
415
+ + return false;
416
+ + }
417
+ + }
418
+ + }
419
+ +
420
+ + st.tensors = std::move(parsed_tensors);
421
  +
422
  + if (st.d_blob) { hipFree(st.d_blob); st.d_blob = nullptr; }
423
  + hipError_t err = hipMalloc(&st.d_blob, data_bytes);
 
466
  + fprintf(stderr, "[emeans] Loaded '%s': %.4f GiB (%zu tensors) into contiguous HIP VRAM\n",
467
  + emns_path, data_bytes / 1073741824.0, st.tensors.size());
468
  + return true;
469
+ + } catch (...) {
470
+ + fprintf(stderr, "[emeans] ERROR: unexpected exception in ggml_cuda_emeans_init\n");
471
+ + return false;
472
+ + }
473
  +}
474
  +
475
  +#ifdef _WIN32
 
477
  +#endif
478
  +bool ggml_cuda_emeans_init_extra(const char * emns_path) {
479
  + if (!emns_path || !emns_path[0]) return false;
480
+ + try {
481
  + auto & st = emns_state();
482
  + std::lock_guard<std::mutex> lock(st.mtx);
483
  + for (const auto & p : st.extra_paths) {
 
492
  + char magic[8];
493
  + uint64_t manifest_len = 0;
494
  + if (fread(magic, 1, 8, f) != 8 || memcmp(magic, EMNS_MAGIC, 8) != 0 ||
495
+ + fread(&manifest_len, 8, 1, f) != 1 || manifest_len == 0 || manifest_len > (64ULL << 20)) {
496
  + fprintf(stderr, "[emeans] ERROR: invalid .emns header in '%s'\n", emns_path);
497
  + fclose(f);
498
  + return false;
 
506
  + uint64_t data_base = (hdr_end + 63ULL) & ~63ULL;
507
  +#if defined(_WIN32)
508
  + _fseeki64(f, 0, SEEK_END);
509
+ + int64_t raw_size = _ftelli64(f);
510
  + _fseeki64(f, (long long)data_base, SEEK_SET);
511
  +#else
512
  + fseeko(f, 0, SEEK_END);
513
+ + int64_t raw_size = (int64_t)ftello(f);
514
  + fseeko(f, (off_t)data_base, SEEK_SET);
515
  +#endif
516
+ + if (raw_size <= 0 || (uint64_t)raw_size <= data_base) {
517
+ + fprintf(stderr, "[emeans] ERROR: truncated extra .emns file '%s'\n", emns_path);
518
+ + fclose(f);
519
+ + return false;
520
+ + }
521
+ + uint64_t data_bytes = (uint64_t)raw_size - data_base;
522
  +
523
  + std::unordered_map<std::string, EmTensor> extra_tensors;
524
  + if (!em_parse_manifest(mjson, extra_tensors)) {
 
526
  + fclose(f);
527
  + return false;
528
  + }
529
+ + for (const auto & kv : extra_tensors) {
530
+ + for (const auto & pk : kv.second.planes) {
531
+ + if (pk.second.offset > data_bytes || pk.second.nbytes > data_bytes - pk.second.offset) {
532
+ + fprintf(stderr, "[emeans] ERROR: extra plane '%s.%s' out of bounds\n",
533
+ + kv.first.c_str(), pk.first.c_str());
534
+ + fclose(f);
535
+ + return false;
536
+ + }
537
+ + }
538
+ + }
539
  +
540
  + uint8_t * d_extra = nullptr;
541
  + hipError_t err = hipMalloc(&d_extra, data_bytes);
 
569
  +
570
  + size_t n_added = 0;
571
  + for (auto & kv : extra_tensors) {
572
+ + if (kv.second.fmt != EM_FMT_EM1D_Q4_G64 && kv.second.fmt != EM_FMT_EM1D_Q3_G64 &&
573
+ + kv.second.fmt != EM_FMT_EM2D_K32_G128 && kv.second.fmt != EM_FMT_EM2D_K16_G128) {
574
  + continue;
575
  + }
576
  + for (auto & pk : kv.second.planes) {
 
586
  + fprintf(stderr, "[emeans] Loaded extra '%s': %.2f MiB (%zu quantized tensors) into HIP VRAM\n",
587
  + emns_path, data_bytes / 1048576.0, n_added);
588
  + return true;
589
+ + } catch (...) {
590
+ + fprintf(stderr, "[emeans] ERROR: unexpected exception in ggml_cuda_emeans_init_extra\n");
591
+ + return false;
592
+ + }
593
  +}
594
  +
595
  +ggml_backend_buffer_t ggml_cuda_emeans_get_stub_buffer(ggml_backend_buffer_type_t buft) {
 
618
  + if (it == st.tensors.end()) return nullptr;
619
  + const EmTensor & em = it->second;
620
  +
621
+ + // Only bind quantized formats (EM1D_Q4_G64, EM1D_Q3_G64, EM2D_K32_G128, EM2D_K16_G128)
622
+ + if (em.fmt != EM_FMT_EM1D_Q4_G64 && em.fmt != EM_FMT_EM1D_Q3_G64 &&
623
+ + em.fmt != EM_FMT_EM2D_K32_G128 && em.fmt != EM_FMT_EM2D_K16_G128) {
624
+ + return nullptr;
625
+ + }
626
+ + // 2D matmul path only implements EM1D_Q4_G64
627
+ + if (em.shape.size() == 2 && em.fmt != EM_FMT_EM1D_Q4_G64) {
628
+ + fprintf(stderr, "[emeans] WARN: unsupported 2D fmt=%u for %s\n", em.fmt, gguf_name);
629
+ + return nullptr;
630
+ + }
631
+ + // Verify K divisibility required by kernels (64 for 1D, 128 for 2D)
632
+ + const int64_t k_align = (em.fmt == EM_FMT_EM1D_Q4_G64 || em.fmt == EM_FMT_EM1D_Q3_G64) ? 64 : 128;
633
+ + if (ne0 <= 0 || (ne0 % k_align) != 0) {
634
+ + fprintf(stderr, "[emeans] WARN: K=%lld not divisible by %lld for %s\n",
635
+ + (long long)ne0, (long long)k_align, gguf_name);
636
+ + return nullptr;
637
+ + }
638
+ + // Verify required planes exist and are non-null
639
+ + auto has_plane = [&](const char * pname, uint64_t min_bytes) -> bool {
640
+ + auto pit = em.planes.find(pname);
641
+ + return pit != em.planes.end() && pit->second.d_ptr != nullptr && pit->second.nbytes >= min_bytes;
642
+ + };
643
+ + const uint64_t n_rows_total = (uint64_t)ne1 * (uint64_t)ne2;
644
+ + const uint64_t k_u64 = (uint64_t)ne0;
645
+ + bool planes_ok = false;
646
+ + if (em.fmt == EM_FMT_EM1D_Q4_G64) {
647
+ + planes_ok = has_plane("lo4", n_rows_total * (k_u64 / 2)) &&
648
+ + has_plane("scales", n_rows_total * (k_u64 / 64) * 2) &&
649
+ + has_plane("lut", (uint64_t)ne2 * 16 * 2);
650
+ + } else if (em.fmt == EM_FMT_EM1D_Q3_G64) {
651
+ + planes_ok = has_plane("lo2", n_rows_total * (k_u64 / 4)) &&
652
+ + has_plane("hi1", n_rows_total * (k_u64 / 8)) &&
653
+ + has_plane("scales", n_rows_total * (k_u64 / 64) * 2) &&
654
+ + has_plane("lut", (uint64_t)ne2 * 8 * 2);
655
+ + } else if (em.fmt == EM_FMT_EM2D_K32_G128) {
656
+ + planes_ok = has_plane("lo4", n_rows_total * (k_u64 / 4)) &&
657
+ + has_plane("hi1", n_rows_total * (k_u64 / 16)) &&
658
+ + has_plane("scales", n_rows_total * (k_u64 / 128) * 2) &&
659
+ + has_plane("lut", (uint64_t)ne2 * 32 * 4);
660
+ + } else if (em.fmt == EM_FMT_EM2D_K16_G128) {
661
+ + planes_ok = has_plane("lo4", n_rows_total * (k_u64 / 4)) &&
662
+ + has_plane("scales", n_rows_total * (k_u64 / 128) * 2) &&
663
+ + has_plane("lut", (uint64_t)ne2 * 16 * 4);
664
+ + }
665
+ + if (!planes_ok) {
666
+ + fprintf(stderr, "[emeans] WARN: missing/truncated planes for %s (fmt=%u)\n", gguf_name, em.fmt);
667
  + return nullptr;
668
  + }
669
  + // Verify shape match (GGML [K, N, E] vs EMNS [N, K] or [E, N, K])
 
699
  + return p >= st.stub_base && p < st.stub_base + EmnsState::MAX_STUBS * EmnsState::STUB_STRIDE;
700
  +}
701
  +
702
+ +size_t ggml_cuda_emeans_copy_raw_tensor(const char * gguf_name, float * dst_f32, size_t max_elems, int loop_start) {
703
+ + if (!gguf_name || !dst_f32 || max_elems == 0) return 0;
704
+ + auto & st = emns_state();
705
+ + std::lock_guard<std::mutex> lock(st.mtx);
706
+ + if (!st.loaded) return 0;
707
+ +
708
+ + auto get_raw_plane = [&](const std::string & ename, const EmTensor ** out_em, const EmPlane ** out_plane) -> bool {
709
+ + auto it = st.tensors.find(ename);
710
+ + if (it == st.tensors.end()) return false;
711
+ + const EmTensor & em = it->second;
712
+ + if (em.fmt != EM_FMT_FP32) return false;
713
+ + auto pit = em.planes.find("data");
714
+ + if (pit == em.planes.end() || !pit->second.d_ptr || pit->second.nbytes == 0 || (pit->second.nbytes % sizeof(float)) != 0) {
715
+ + return false;
716
+ + }
717
+ + *out_em = &em;
718
+ + *out_plane = &pit->second;
719
+ + return true;
720
+ + };
721
+ +
722
+ + auto copy_direct = [&](const std::string & ename) -> size_t {
723
+ + const EmTensor * em = nullptr;
724
+ + const EmPlane * pl = nullptr;
725
+ + if (!get_raw_plane(ename, &em, &pl)) return 0;
726
+ + const size_t n_elems = (size_t)(pl->nbytes / sizeof(float));
727
+ + if (n_elems > max_elems) return 0;
728
+ + if (hipMemcpy(dst_f32, pl->d_ptr, pl->nbytes, hipMemcpyDeviceToHost) != hipSuccess) return 0;
729
+ + return n_elems;
730
+ + };
731
+ +
732
+ + std::string g(gguf_name);
733
+ + if (g == "output_norm.weight") return copy_direct("model.llm.norm.weight");
734
+ + if (g == "output_res_query.weight") return copy_direct("model.llm.attn_res.output_query");
735
+ + if (g == "token_embd_norm.weight") return copy_direct("model.llm.embed_norm.weight");
736
+ +
737
+ + if (g.rfind("blk.", 0) == 0) {
738
+ + size_t dot2 = g.find('.', 4);
739
+ + if (dot2 != std::string::npos) {
740
+ + std::string idx_str = g.substr(4, dot2 - 4);
741
+ + std::string suf = g.substr(dot2 + 1);
742
+ + int bid = -1;
743
+ + try { bid = std::stoi(idx_str); } catch (...) { bid = -1; }
744
+ + std::string pfx = "model.llm.layers." + idx_str + ".";
745
+ +
746
+ + if (suf == "loop_msg_query.weight") {
747
+ + if (bid < 0 || loop_start < 0 || bid < loop_start) return 0;
748
+ + const EmTensor * em_q = nullptr, * em_kv = nullptr;
749
+ + const EmPlane * pl_q = nullptr, * pl_kv = nullptr;
750
+ + if (!get_raw_plane("model.llm.middle_cycle_cross_pass_queries", &em_q, &pl_q) ||
751
+ + !get_raw_plane("model.llm.middle_cycle_cross_pass_kv_queries", &em_kv, &pl_kv)) {
752
+ + return 0;
753
+ + }
754
+ + if (em_q->shape.size() != 2 || em_kv->shape.size() != 2 ||
755
+ + em_q->shape[0] != em_kv->shape[0] || em_q->shape[1] != em_kv->shape[1]) {
756
+ + return 0;
757
+ + }
758
+ + const int64_t i = (int64_t)(bid - loop_start);
759
+ + if (2 * i + 1 >= em_q->shape[0]) return 0;
760
+ + const size_t D = (size_t)em_q->shape[1];
761
+ + if (4 * D > max_elems || (size_t)(2 * i + 2) * D * sizeof(float) > pl_q->nbytes ||
762
+ + (size_t)(2 * i + 2) * D * sizeof(float) > pl_kv->nbytes) {
763
+ + return 0;
764
+ + }
765
+ + const size_t row_bytes = D * sizeof(float);
766
+ + const uint8_t * q_base = (const uint8_t *)pl_q->d_ptr;
767
+ + const uint8_t * kv_base = (const uint8_t *)pl_kv->d_ptr;
768
+ + if (hipMemcpy(dst_f32 + 0 * D, q_base + (2 * i) * row_bytes, row_bytes, hipMemcpyDeviceToHost) != hipSuccess ||
769
+ + hipMemcpy(dst_f32 + 1 * D, kv_base + (2 * i) * row_bytes, row_bytes, hipMemcpyDeviceToHost) != hipSuccess ||
770
+ + hipMemcpy(dst_f32 + 2 * D, kv_base + (2 * i + 1) * row_bytes, row_bytes, hipMemcpyDeviceToHost) != hipSuccess ||
771
+ + hipMemcpy(dst_f32 + 3 * D, q_base + (2 * i + 1) * row_bytes, row_bytes, hipMemcpyDeviceToHost) != hipSuccess) {
772
+ + return 0;
773
+ + }
774
+ + return 4 * D;
775
+ + }
776
+ +
777
+ + if (suf == "attn_k_conv.weight" || suf == "attn_v_conv.weight") {
778
+ + const char * kv_c = (suf == "attn_k_conv.weight") ? "k" : "v";
779
+ + size_t got = copy_direct(pfx + "attn." + kv_c + "_sconv.weight");
780
+ + if (got > 0) return got;
781
+ + const EmTensor * em = nullptr;
782
+ + const EmPlane * pl = nullptr;
783
+ + if (!get_raw_plane(pfx + "attn." + kv_c + "_sconv.static_w", &em, &pl)) return 0;
784
+ + if (em->shape.size() != 2) return 0;
785
+ + const size_t K = (size_t)em->shape[0];
786
+ + const size_t C = (size_t)em->shape[1];
787
+ + const size_t n_elems = K * C;
788
+ + if (n_elems == 0 || n_elems > max_elems || n_elems * sizeof(float) != pl->nbytes) return 0;
789
+ + std::vector<float> tmp(n_elems);
790
+ + if (hipMemcpy(tmp.data(), pl->d_ptr, pl->nbytes, hipMemcpyDeviceToHost) != hipSuccess) return 0;
791
+ + // flip(0).T.contiguous(): dst[c, k] = tmp[K - 1 - k, c]
792
+ + for (size_t c = 0; c < C; ++c) {
793
+ + for (size_t k = 0; k < K; ++k) {
794
+ + dst_f32[c * K + k] = tmp[(K - 1 - k) * C + c];
795
+ + }
796
+ + }
797
+ + return n_elems;
798
+ + }
799
+ +
800
+ + if (suf == "attn_rel_bias.weight") {
801
+ + const EmTensor * em = nullptr;
802
+ + const EmPlane * pl = nullptr;
803
+ + if (!get_raw_plane(pfx + "attn.rel_logits_proj.proj", &em, &pl)) return 0;
804
+ + if (em->shape.size() != 2) return 0;
805
+ + const size_t R = (size_t)em->shape[0];
806
+ + const size_t C = (size_t)em->shape[1];
807
+ + const size_t n_elems = R * C;
808
+ + if (n_elems == 0 || n_elems > max_elems || n_elems * sizeof(float) != pl->nbytes) return 0;
809
+ + std::vector<float> tmp(n_elems);
810
+ + if (hipMemcpy(tmp.data(), pl->d_ptr, pl->nbytes, hipMemcpyDeviceToHost) != hipSuccess) return 0;
811
+ + // .T.contiguous(): dst[c, r] = tmp[r, c]
812
+ + for (size_t c = 0; c < C; ++c) {
813
+ + for (size_t r = 0; r < R; ++r) {
814
+ + dst_f32[c * R + r] = tmp[r * C + c];
815
+ + }
816
+ + }
817
+ + return n_elems;
818
+ + }
819
+ +
820
+ + if (suf == "attn_res_query.weight") {
821
+ + if (bid < 1) return 0;
822
+ + return copy_direct("model.llm.attn_res.attn_queries." + std::to_string(bid - 1));
823
+ + }
824
+ + if (suf == "ffn_res_query.weight") return copy_direct("model.llm.attn_res.mlp_queries." + idx_str);
825
+ + if (suf == "attn_norm.weight") return copy_direct(pfx + "attn_norm.weight");
826
+ + if (suf == "attn_q_inp_norm.weight") return copy_direct(pfx + "q_input_norm.weight");
827
+ + if (suf == "attn_k_inp_norm.weight") return copy_direct(pfx + "k_input_norm.weight");
828
+ + if (suf == "attn_v_inp_norm.weight") return copy_direct(pfx + "v_input_norm.weight");
829
+ + if (suf == "ffn_norm.weight") return copy_direct(pfx + "mlp_norm.weight");
830
+ + if (suf == "exp_probs_b.bias") return copy_direct(pfx + "mlp.gate.bias");
831
+ + if (suf == "ffn_gate_inp.weight") return copy_direct(pfx + "mlp.gate.weight");
832
+ + if (suf == "attn_post_conv.weight") return copy_direct(pfx + "attn_sconv.weight");
833
+ + if (suf == "ffn_post_conv.weight") return copy_direct(pfx + "mlp_sconv.weight");
834
+ + if (suf == "attn_q_clip.weight") return copy_direct(pfx + "attn.q_l2_clip.scale");
835
+ + if (suf == "attn_rel_clip.weight") return copy_direct(pfx + "attn.rel_l2_clip.scale");
836
+ + if (suf == "attn_sink_proj.weight") return copy_direct(pfx + "attn.attn_sink_proj.weight");
837
+ + if (suf == "attn_k_conv_proj.weight") return copy_direct(pfx + "attn.k_sconv.weight_proj");
838
+ + if (suf == "attn_v_conv_proj.weight") return copy_direct(pfx + "attn.v_sconv.weight_proj");
839
+ + }
840
+ + }
841
+ +
842
+ + // Fallback: direct GGUF tensor name lookup in .emns
843
+ + return copy_direct(g);
844
+ +}
845
+ +
846
  +} // extern "C"
847
  +
848
  +static inline const EmTensor * emns_lookup(const ggml_tensor * src0) {
 
868
  +static __device__ __forceinline__ em_gacc_t em_gacc_zero() { return 0.0f; }
869
  +static __device__ __forceinline__ em_gacc_t em_gacc_fdot2(uint32_t a_bits, uint32_t b_bits, em_gacc_t acc) {
870
  + union { uint32_t u; em_f16x2_t v; } ua{a_bits}, ub{b_bits};
871
+ +#if !defined(__gfx1010__) && !defined(__gfx1011__) && !defined(__gfx1012__) && !defined(__gfx900__) && !defined(__gfx906__)
872
  + return __builtin_amdgcn_fdot2(ua.v, ub.v, acc, false);
873
+ +#else
874
+ + return fmaf((float)ua.v[0], (float)ub.v[0], fmaf((float)ua.v[1], (float)ub.v[1], acc));
875
+ +#endif
876
  +}
877
  +static __device__ __forceinline__ float em_gacc_to_f32(em_gacc_t acc) { return acc; }
878
+ +#elif defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530
879
  +typedef __half2 em_gacc_t;
880
  +static __device__ __forceinline__ em_gacc_t em_gacc_zero() { return __float2half2_rn(0.0f); }
881
  +static __device__ __forceinline__ em_gacc_t em_gacc_fdot2(uint32_t a_bits, uint32_t b_bits, em_gacc_t acc) {
 
888
  + float2 f2 = __half22float2(acc);
889
  + return f2.x + f2.y;
890
  +}
891
+ +#else
892
+ +typedef float em_gacc_t;
893
+ +static __device__ __forceinline__ em_gacc_t em_gacc_zero() { return 0.0f; }
894
+ +static __device__ __forceinline__ em_gacc_t em_gacc_fdot2(uint32_t a_bits, uint32_t b_bits, em_gacc_t acc) {
895
+ + __half2 ha, hb;
896
+ + memcpy(&ha, &a_bits, sizeof(ha));
897
+ + memcpy(&hb, &b_bits, sizeof(hb));
898
+ + float2 fa = __half22float2(ha);
899
+ + float2 fb = __half22float2(hb);
900
+ + return fmaf(fa.x, fb.x, fmaf(fa.y, fb.y, acc));
901
+ +}
902
+ +static __device__ __forceinline__ float em_gacc_to_f32(em_gacc_t acc) { return acc; }
903
  +#endif
904
  +
905
  +static __device__ __forceinline__ uint32_t em_pack_h16(uint32_t lo16, uint32_t hi16) {
 
1309
  + }
1310
  +}
1311
  +
1312
+ +// --- 3b. EM2D_K16_G128 MoE GEMV (2.125 bpw, NO hi1 plane, 8 GB tier) ---
1313
+ +__global__ EM_LAUNCH_BOUNDS_GEMV
1314
+ +void em_gemv_2d_k16_g128_moe_kernel(
1315
+ + const uint32_t * __restrict__ lo4_all,
1316
+ + const __half * __restrict__ scales_all,
1317
+ + const uint32_t * __restrict__ lut_h2_all,
1318
+ + const int32_t * __restrict__ ids,
1319
+ + const uint32_t * __restrict__ x_h2_all,
1320
+ + float * __restrict__ y_all,
1321
+ + int N, int K, int ne11, int is_w13, int64_t ids_nb1_i32, int64_t y_nb1_f32, int64_t y_nb2_f32)
1322
+ +{
1323
+ + const int tid = threadIdx.x;
1324
+ + const int wave_id = tid >> 5;
1325
+ + const int lane = tid & 31;
1326
+ + const int slot = blockIdx.y;
1327
+ + const int tok = blockIdx.z;
1328
+ + const int e = ids[(size_t)tok * ids_nb1_i32 + slot];
1329
+ +
1330
+ + const uint32_t my_lut = lut_h2_all[(size_t)e * 16 + (lane & 15)];
1331
+ +
1332
+ + const int row = blockIdx.x * 8 + wave_id;
1333
+ + const int stride_c = K >> 5;
1334
+ + const int stride_sc = K >> 7;
1335
+ + const int n_iters = (stride_c + 31) >> 5;
1336
+ +
1337
+ + const size_t exp_c_off = (size_t)e * N * stride_c;
1338
+ + const size_t exp_sc_off = (size_t)e * N * stride_sc;
1339
+ + const uint2 * lo4_u2 = reinterpret_cast<const uint2 *>(lo4_all) + exp_c_off;
1340
+ + const __half * sc_ptr = scales_all + exp_sc_off;
1341
+ +
1342
+ + const int x_slot = (ne11 == 1) ? 0 : slot;
1343
+ + const uint4 * x_u4 = reinterpret_cast<const uint4 *>(x_h2_all + ((size_t)tok * ne11 + x_slot) * (K >> 1));
1344
+ +
1345
+ + float acc = 0.0f;
1346
+ + for (int it = 0; it < n_iters; ++it) {
1347
+ + const int c = (it << 5) + lane;
1348
+ + const bool valid = (c < stride_c);
1349
+ + const int g = c >> 2;
1350
+ + const int xb = c << 2;
1351
+ +
1352
+ + uint2 lo_row = make_uint2(0, 0);
1353
+ + float sc_row = 0.0f;
1354
+ + if (valid && row < N) {
1355
+ + const size_t idx_c = (size_t)row * stride_c + c;
1356
+ + lo_row = lo4_u2[idx_c];
1357
+ + sc_row = __half2float(sc_ptr[(size_t)row * stride_sc + g]);
1358
+ + }
1359
+ +
1360
+ + em_gacc_t gacc = em_gacc_zero();
1361
+ + #pragma unroll
1362
+ + for (int w = 0; w < 4; ++w) {
1363
+ + const uint4 xw = valid ? x_u4[xb + w] : make_uint4(0, 0, 0, 0);
1364
+ + const uint32_t xv[4] = {xw.x, xw.y, xw.z, xw.w};
1365
+ + const int lo_shift_base = (w & 1) * 16;
1366
+ + const uint32_t lo_w = (w < 2) ? lo_row.x : lo_row.y;
1367
+ + #pragma unroll
1368
+ + for (int p = 0; p < 4; ++p) {
1369
+ + const uint32_t idx = (lo_w >> (lo_shift_base + p * 4)) & 0xFu;
1370
+ + gacc = em_gacc_fdot2(EM_SHFL(my_lut, idx, 32), xv[p], gacc);
1371
+ + }
1372
+ + }
1373
+ + acc = fmaf(em_gacc_to_f32(gacc), sc_row, acc);
1374
+ + }
1375
+ +
1376
+ + if (row < N) {
1377
+ + float s = em_wave32_sum(acc);
1378
+ + if (lane == 0) {
1379
+ + const int out_row = is_w13 ? ((row & 1) ? ((N >> 1) + (row >> 1)) : (row >> 1)) : row;
1380
+ + y_all[(size_t)tok * y_nb2_f32 + (size_t)slot * y_nb1_f32 + out_row] = s;
1381
+ + }
1382
+ + }
1383
+ +}
1384
+ +
1385
  +// --- 4. Single-Launch Zero-Sync GPU-Grouped BT=8 MoE Prefill/Verify Kernels ---
1386
  +__global__ void em_moe_build_tiles_kernel(
1387
  + const int32_t * __restrict__ ids,
 
1531
  + wh2[p] = em_pack_h16(EM_SHFL(my_lut, i0, 32), EM_SHFL(my_lut, i1, 32));
1532
  + }
1533
  + if (valid) {
1534
+ + #pragma unroll
1535
+ + for (int b = 0; b < 8; ++b) {
1536
+ + if (b < cnt) {
1537
+ + const uint4 xw = x_u4[s_xbase[b] + xb + w];
1538
+ + em_gacc_t gb = gv[b];
1539
+ + gb = em_gacc_fdot2(wh2[0], xw.x, gb);
1540
+ + gb = em_gacc_fdot2(wh2[1], xw.y, gb);
1541
+ + gb = em_gacc_fdot2(wh2[2], xw.z, gb);
1542
+ + gb = em_gacc_fdot2(wh2[3], xw.w, gb);
1543
+ + gv[b] = gb;
1544
+ + }
1545
  + }
1546
  + }
1547
  + }
 
1648
  + wh2[p] = EM_SHFL(my_lut, idx, 32);
1649
  + }
1650
  + if (valid) {
1651
+ + #pragma unroll
1652
+ + for (int b = 0; b < 8; ++b) {
1653
+ + if (b < cnt) {
1654
+ + const uint4 xw = x_u4[s_xbase[b] + xb + w];
1655
+ + em_gacc_t gb = gv[b];
1656
+ + gb = em_gacc_fdot2(wh2[0], xw.x, gb);
1657
+ + gb = em_gacc_fdot2(wh2[1], xw.y, gb);
1658
+ + gb = em_gacc_fdot2(wh2[2], xw.z, gb);
1659
+ + gb = em_gacc_fdot2(wh2[3], xw.w, gb);
1660
+ + gv[b] = gb;
1661
+ + }
1662
+ + }
1663
+ + }
1664
+ + }
1665
+ + #pragma unroll
1666
+ + for (int b = 0; b < 8; ++b) {
1667
+ + if (b < cnt) acc[b] = fmaf(em_gacc_to_f32(gv[b]), sc_row, acc[b]);
1668
+ + }
1669
+ + }
1670
+ +
1671
+ + if (row < N) {
1672
+ + const int out_row = is_w13 ? ((row & 1) ? ((N >> 1) + (row >> 1)) : (row >> 1)) : row;
1673
+ + for (int b = 0; b < cnt; ++b) {
1674
+ + const float sb = em_wave32_sum(acc[b]);
1675
+ + if (lane == 0) {
1676
+ + const uint32_t pr = s_pairs[b];
1677
+ + const int tok = (int)(pr >> 8);
1678
+ + const int slot = (int)(pr & 0xFFu);
1679
+ + y_all[(size_t)tok * y_nb2_f32 + (size_t)slot * y_nb1_f32 + out_row] = sb;
1680
+ + }
1681
+ + }
1682
+ + }
1683
+ +}
1684
+ +
1685
+ +__global__ EM_LAUNCH_BOUNDS
1686
+ +void em_gemm8_2d_k16_g128_moe_kernel(
1687
+ + const uint32_t * __restrict__ lo4_all,
1688
+ + const __half * __restrict__ scales_all,
1689
+ + const uint32_t * __restrict__ lut_h2_all,
1690
+ + const uint32_t * __restrict__ sorted_pairs,
1691
+ + const uint2 * __restrict__ tiles,
1692
+ + const int32_t * __restrict__ d_num_tiles,
1693
+ + const uint32_t * __restrict__ x_h2_all,
1694
+ + float * __restrict__ y_all,
1695
+ + int N, int K, int ne11, int is_w13, int64_t y_nb1_f32, int64_t y_nb2_f32)
1696
+ +{
1697
+ + const int tile_id = blockIdx.y;
1698
+ + if (tile_id >= d_num_tiles[0]) return;
1699
+ +
1700
+ + const int tid = threadIdx.x;
1701
+ + const int wave_id = tid >> 5;
1702
+ + const int lane = tid & 31;
1703
+ +
1704
+ + const uint2 ti = tiles[tile_id];
1705
+ + const int e = (int)(ti.x >> 4);
1706
+ + const int cnt = (int)(ti.x & 0xFu);
1707
+ + const int pstart = (int)ti.y;
1708
+ +
1709
+ + __shared__ uint32_t s_pairs[8];
1710
+ + __shared__ size_t s_xbase[8];
1711
+ + if (tid < cnt) {
1712
+ + const uint32_t pr = sorted_pairs[pstart + tid];
1713
+ + s_pairs[tid] = pr;
1714
+ + const int tok = (int)(pr >> 8);
1715
+ + const int slot = (int)(pr & 0xFFu);
1716
+ + s_xbase[tid] = ((size_t)tok * ne11 + ((ne11 == 1) ? 0 : slot)) * (size_t)(K >> 3);
1717
+ + }
1718
+ + __syncthreads();
1719
+ +
1720
+ + const uint32_t my_lut = lut_h2_all[(size_t)e * 16 + (lane & 15)];
1721
+ +
1722
+ + const int row = blockIdx.x * 8 + wave_id;
1723
+ + const int stride_c = K >> 5;
1724
+ + const int stride_sc = K >> 7;
1725
+ + const int n_iters = (stride_c + 31) >> 5;
1726
+ +
1727
+ + const size_t exp_c_off = (size_t)e * N * stride_c;
1728
+ + const size_t exp_sc_off = (size_t)e * N * stride_sc;
1729
+ + const uint2 * lo4_u2 = reinterpret_cast<const uint2 *>(lo4_all) + exp_c_off;
1730
+ + const __half * sc_ptr = scales_all + exp_sc_off;
1731
+ + const uint4 * x_u4 = reinterpret_cast<const uint4 *>(x_h2_all);
1732
+ +
1733
+ + float acc[8] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
1734
+ + for (int it = 0; it < n_iters; ++it) {
1735
+ + const int c = (it << 5) + lane;
1736
+ + const bool valid = (c < stride_c);
1737
+ + const int g = c >> 2;
1738
+ + const int xb = c << 2;
1739
+ +
1740
+ + uint2 lo_row = make_uint2(0, 0);
1741
+ + float sc_row = 0.0f;
1742
+ + if (valid && row < N) {
1743
+ + const size_t idx_c = (size_t)row * stride_c + c;
1744
+ + lo_row = lo4_u2[idx_c];
1745
+ + sc_row = __half2float(sc_ptr[(size_t)row * stride_sc + g]);
1746
+ + }
1747
+ +
1748
+ + em_gacc_t gv[8];
1749
+ + #pragma unroll
1750
+ + for (int b = 0; b < 8; ++b) gv[b] = em_gacc_zero();
1751
+ + #pragma unroll
1752
+ + for (int w = 0; w < 4; ++w) {
1753
+ + const int lo_shift_base = (w & 1) * 16;
1754
+ + const uint32_t lo_w = (w < 2) ? lo_row.x : lo_row.y;
1755
+ + uint32_t wh2[4];
1756
+ + #pragma unroll
1757
+ + for (int p = 0; p < 4; ++p) {
1758
+ + const uint32_t idx = (lo_w >> (lo_shift_base + p * 4)) & 0xFu;
1759
+ + wh2[p] = EM_SHFL(my_lut, idx, 32);
1760
+ + }
1761
+ + if (valid) {
1762
+ + #pragma unroll
1763
+ + for (int b = 0; b < 8; ++b) {
1764
+ + if (b < cnt) {
1765
+ + const uint4 xw = x_u4[s_xbase[b] + xb + w];
1766
+ + em_gacc_t gb = gv[b];
1767
+ + gb = em_gacc_fdot2(wh2[0], xw.x, gb);
1768
+ + gb = em_gacc_fdot2(wh2[1], xw.y, gb);
1769
+ + gb = em_gacc_fdot2(wh2[2], xw.z, gb);
1770
+ + gb = em_gacc_fdot2(wh2[3], xw.w, gb);
1771
+ + gv[b] = gb;
1772
+ + }
1773
  + }
1774
  + }
1775
  + }
 
1888
  +
1889
  + __shared__ uint32_t s_pairs[16];
1890
  + __shared__ size_t s_xbase[16];
1891
+ + alignas(32) __shared__ union {
1892
  + uint16_t w[128][40];
1893
  + float c[8][256];
1894
  + } s_mem;
1895
+ + alignas(32) __shared__ uint16_t s_X[16][40];
1896
  +
1897
  + if (tid < cnt) {
1898
  + const uint32_t pr = sorted_pairs[pstart + tid];
 
2027
  +
2028
  + __shared__ uint32_t s_pairs[16];
2029
  + __shared__ size_t s_xbase[16];
2030
+ + alignas(32) __shared__ union {
2031
  + uint16_t w[128][40];
2032
  + float c[8][256];
2033
  + } s_mem;
2034
+ + alignas(32) __shared__ uint16_t s_X[16][40];
2035
  +
2036
  + if (tid < cnt) {
2037
  + const uint32_t pr = sorted_pairs[pstart + tid];
 
2135
  + }
2136
  +#endif
2137
  +}
2138
+ +
2139
+ +__global__ __launch_bounds__(256, 2)
2140
+ +void em_gemm16_wmma_2d_k16_g128_moe_kernel(
2141
+ + const uint32_t * __restrict__ lo4_all,
2142
+ + const __half * __restrict__ scales_all,
2143
+ + const uint32_t * __restrict__ lut_h2_all,
2144
+ + const uint32_t * __restrict__ sorted_pairs,
2145
+ + const uint2 * __restrict__ tiles,
2146
+ + const int32_t * __restrict__ d_num_tiles,
2147
+ + const uint32_t * __restrict__ x_h2_all,
2148
+ + float * __restrict__ y_all,
2149
+ + int N, int K, int ne11, int is_w13, int64_t y_nb1_f32, int64_t y_nb2_f32)
2150
+ +{
2151
+ +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 750
2152
+ + using namespace nvcuda;
2153
+ + const int tile_id = blockIdx.y;
2154
+ + if (tile_id >= d_num_tiles[0]) return;
2155
+ +
2156
+ + const int tid = threadIdx.x;
2157
+ + const int warp_id = tid >> 5;
2158
+ + const int lane = tid & 31;
2159
+ +
2160
+ + const uint2 ti = tiles[tile_id];
2161
+ + const int e = (int)(ti.x >> 5);
2162
+ + const int cnt = (int)(ti.x & 0x1Fu);
2163
+ + const int pstart = (int)ti.y;
2164
+ +
2165
+ + __shared__ uint32_t s_pairs[16];
2166
+ + __shared__ size_t s_xbase[16];
2167
+ + alignas(32) __shared__ union {
2168
+ + uint16_t w[128][40];
2169
+ + float c[8][256];
2170
+ + } s_mem;
2171
+ + alignas(32) __shared__ uint16_t s_X[16][40];
2172
+ +
2173
+ + if (tid < cnt) {
2174
+ + const uint32_t pr = sorted_pairs[pstart + tid];
2175
+ + s_pairs[tid] = pr;
2176
+ + const int tok = (int)(pr >> 8);
2177
+ + const int slot = (int)(pr & 0xFFu);
2178
+ + s_xbase[tid] = ((size_t)tok * ne11 + ((ne11 == 1) ? 0 : slot)) * (size_t)(K >> 3);
2179
+ + }
2180
+ + __syncthreads();
2181
+ +
2182
+ + const uint32_t my_lut = lut_h2_all[(size_t)e * 16 + (lane & 15)];
2183
+ +
2184
+ + const int warp_row_base = blockIdx.x * 128 + warp_id * 16;
2185
+ + const int r_in_warp = lane >> 1;
2186
+ + const int half_sel = lane & 1;
2187
+ + const int row = warp_row_base + r_in_warp;
2188
+ +
2189
+ + const int stride_c = K >> 5;
2190
+ + const int stride_sc = K >> 7;
2191
+ +
2192
+ + const size_t exp_c_off = (size_t)e * N * stride_c;
2193
+ + const size_t exp_sc_off = (size_t)e * N * stride_sc;
2194
+ + const uint2 * lo4_u2 = reinterpret_cast<const uint2 *>(lo4_all) + exp_c_off;
2195
+ + const __half * sc_ptr = scales_all + exp_sc_off;
2196
+ + const uint4 * x_u4 = reinterpret_cast<const uint4 *>(x_h2_all);
2197
+ +
2198
+ + wmma::fragment<wmma::accumulator, 16, 16, 16, float> c_frag;
2199
+ + wmma::fill_fragment(c_frag, 0.0f);
2200
+ +
2201
+ + const uint4 zero_u4 = make_uint4(0, 0, 0, 0);
2202
+ +
2203
+ + for (int c = 0; c < stride_c; ++c) {
2204
+ + if (tid < 64) {
2205
+ + const int b = tid >> 2;
2206
+ + const int v = tid & 3;
2207
+ + const uint4 xw = (b < cnt) ? x_u4[s_xbase[b] + (c << 2) + v] : zero_u4;
2208
+ + *reinterpret_cast<uint4 *>(&s_X[b][v << 3]) = xw;
2209
+ + }
2210
+ +
2211
+ + uint32_t lo_w = 0u;
2212
+ + __half2 sc_h2 = __float2half2_rn(0.0f);
2213
+ + if (row < N) {
2214
+ + const size_t idx_c = (size_t)row * stride_c + c;
2215
+ + const uint2 lo_row = lo4_u2[idx_c];
2216
+ + lo_w = half_sel ? lo_row.y : lo_row.x;
2217
+ + sc_h2 = __half2half2(sc_ptr[(size_t)row * stride_sc + (c >> 2)]);
2218
+ + }
2219
+ +
2220
+ + __half2 * w_dst = reinterpret_cast<__half2 *>(&s_mem.w[warp_id * 16 + r_in_warp][half_sel * 16]);
2221
+ + #pragma unroll
2222
+ + for (int w = 0; w < 2; ++w) {
2223
+ + const int lo_shift_base = w * 16;
2224
+ + #pragma unroll
2225
+ + for (int p = 0; p < 4; ++p) {
2226
+ + const uint32_t idx = (lo_w >> (lo_shift_base + p * 4)) & 0xFu;
2227
+ + const uint32_t wh2_u = EM_SHFL(my_lut, idx, 32);
2228
+ + __half2 wh2;
2229
+ + memcpy(&wh2, &wh2_u, sizeof(wh2));
2230
+ + w_dst[w * 4 + p] = __hmul2(wh2, sc_h2);
2231
+ + }
2232
+ + }
2233
+ +
2234
+ + __syncthreads();
2235
+ +
2236
+ + wmma::fragment<wmma::matrix_a, 16, 16, 16, __half, wmma::row_major> a_frag;
2237
+ + wmma::fragment<wmma::matrix_b, 16, 16, 16, __half, wmma::col_major> b_frag;
2238
+ +
2239
+ + const __half * w_ptr = reinterpret_cast<const __half *>(&s_mem.w[warp_id * 16][0]);
2240
+ + const __half * x_ptr = reinterpret_cast<const __half *>(&s_X[0][0]);
2241
+ +
2242
+ + wmma::load_matrix_sync(a_frag, w_ptr, 40);
2243
+ + wmma::load_matrix_sync(b_frag, x_ptr, 40);
2244
+ + wmma::mma_sync(c_frag, a_frag, b_frag, c_frag);
2245
+ +
2246
+ + wmma::load_matrix_sync(a_frag, w_ptr + 16, 40);
2247
+ + wmma::load_matrix_sync(b_frag, x_ptr + 16, 40);
2248
+ + wmma::mma_sync(c_frag, a_frag, b_frag, c_frag);
2249
+ +
2250
+ + __syncthreads();
2251
+ + }
2252
+ +
2253
+ + wmma::store_matrix_sync(s_mem.c[warp_id], c_frag, 16, wmma::mem_row_major);
2254
+ + __syncwarp();
2255
+ +
2256
+ + #pragma unroll
2257
+ + for (int idx = lane; idx < 256; idx += 32) {
2258
+ + const int r = idx >> 4;
2259
+ + const int b = idx & 15;
2260
+ + const int cur_row = warp_row_base + r;
2261
+ + if (b < cnt && cur_row < N) {
2262
+ + const int out_row = is_w13 ? ((cur_row & 1) ? ((N >> 1) + (cur_row >> 1)) : (cur_row >> 1)) : cur_row;
2263
+ + const uint32_t pr = s_pairs[b];
2264
+ + const int tok = (int)(pr >> 8);
2265
+ + const int slot = (int)(pr & 0xFFu);
2266
+ + y_all[(size_t)tok * y_nb2_f32 + (size_t)slot * y_nb1_f32 + out_row] = s_mem.c[warp_id][idx];
2267
+ + }
2268
+ + }
2269
+ +#endif
2270
+ +}
2271
  +#endif // !GGML_USE_HIP
2272
  +
2273
  +// ============================================================================
 
2409
  + reinterpret_cast<const uint32_t *>(x_f16.get()),
2410
  + (float *)dst->data,
2411
  + N, K, ne11, em->is_w13 ? 1 : 0, ids_nb1_i32, y_nb1_f32, y_nb2_f32);
2412
+ + } else if (em->fmt == EM_FMT_EM2D_K16_G128) {
2413
+ + em_gemv_2d_k16_g128_moe_kernel<<<grid, block, 0, stream>>>(
2414
+ + em->ptr<uint32_t>("lo4"),
2415
+ + em->ptr<__half>("scales"),
2416
+ + em->ptr<uint32_t>("lut"),
2417
+ + (const int32_t *)ids->data,
2418
+ + reinterpret_cast<const uint32_t *>(x_f16.get()),
2419
+ + (float *)dst->data,
2420
+ + N, K, ne11, em->is_w13 ? 1 : 0, ids_nb1_i32, y_nb1_f32, y_nb2_f32);
2421
  + } else {
2422
  + GGML_ABORT("[emeans] unsupported MoE format %u", em->fmt);
2423
  + }
 
2467
  + reinterpret_cast<const uint32_t *>(x_f16.get()),
2468
  + (float *)dst->data,
2469
  + N, K, ne11, em->is_w13 ? 1 : 0, y_nb1_f32, y_nb2_f32);
2470
+ + } else if (em->fmt == EM_FMT_EM2D_K16_G128) {
2471
+ + em_gemm16_wmma_2d_k16_g128_moe_kernel<<<grid, block, 0, stream>>>(
2472
+ + em->ptr<uint32_t>("lo4"),
2473
+ + em->ptr<__half>("scales"),
2474
+ + em->ptr<uint32_t>("lut"),
2475
+ + d_sorted_pairs.get(),
2476
+ + d_tiles.get(),
2477
+ + d_num_tiles.get(),
2478
+ + reinterpret_cast<const uint32_t *>(x_f16.get()),
2479
+ + (float *)dst->data,
2480
+ + N, K, ne11, em->is_w13 ? 1 : 0, y_nb1_f32, y_nb2_f32);
2481
  + } else {
2482
  + GGML_ABORT("[emeans] unsupported MoE format %u", em->fmt);
2483
  + }
 
2526
  + reinterpret_cast<const uint32_t *>(x_f16.get()),
2527
  + (float *)dst->data,
2528
  + N, K, ne11, em->is_w13 ? 1 : 0, y_nb1_f32, y_nb2_f32);
2529
+ + } else if (em->fmt == EM_FMT_EM2D_K16_G128) {
2530
+ + em_gemm8_2d_k16_g128_moe_kernel<<<grid, block, 0, stream>>>(
2531
+ + em->ptr<uint32_t>("lo4"),
2532
+ + em->ptr<__half>("scales"),
2533
+ + em->ptr<uint32_t>("lut"),
2534
+ + d_sorted_pairs.get(),
2535
+ + d_tiles.get(),
2536
+ + d_num_tiles.get(),
2537
+ + reinterpret_cast<const uint32_t *>(x_f16.get()),
2538
+ + (float *)dst->data,
2539
+ + N, K, ne11, em->is_w13 ? 1 : 0, y_nb1_f32, y_nb2_f32);
2540
  + } else {
2541
  + GGML_ABORT("[emeans] unsupported MoE format %u", em->fmt);
2542
  + }
 
2577
  +ggml_backend_buffer_t ggml_cuda_emeans_get_stub_buffer(ggml_backend_buffer_type_t) { return nullptr; }
2578
  +void * ggml_cuda_emeans_bind_tensor(const char *, int64_t, int64_t, int64_t) { return nullptr; }
2579
  +bool ggml_cuda_emeans_is_stub(const void *) { return false; }
2580
+ +size_t ggml_cuda_emeans_copy_raw_tensor(const char *, float *, size_t, int) { return 0; }
2581
  +}
2582
  +bool ggml_cuda_emeans_has(const ggml_tensor *) { return false; }
2583
  +bool ggml_cuda_emeans_try_mul_mat(ggml_backend_cuda_context &, const ggml_tensor *, const ggml_tensor *, ggml_tensor *) { return false; }
 
2615
 
2616
  return false;
2617
  diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu
2618
+ index 93f8b35ea..5f5651931 100644
2619
  --- a/ggml/src/ggml-cuda/ggml-cuda.cu
2620
  +++ b/ggml/src/ggml-cuda/ggml-cuda.cu
2621
  @@ -27,6 +27,7 @@
 
2626
  #include "ggml-cuda/diffusion-sampling.cuh"
2627
  #include "ggml-cuda/fattn.cuh"
2628
  #include "ggml-cuda/fattn-banded.cuh"
2629
+ @@ -2356,6 +2357,10 @@ static bool ggml_cuda_should_fuse_mul_mat_vec_f(const ggml_tensor * tensor, cons
2630
+ ggml_tensor * src1 = tensor->src[1];
2631
+ const ggml_tensor * dst = tensor;
2632
+
2633
+ + if (ggml_cuda_emeans_has(src0) || (gate && ggml_cuda_emeans_has(gate->src[0]))) {
2634
+ + return false;
2635
+ + }
2636
+ +
2637
+ const bool is_mul_mat_id = tensor->op == GGML_OP_MUL_MAT_ID;
2638
+
2639
+ bool use_mul_mat_vec_f =
2640
+ @@ -2389,6 +2394,10 @@ static bool ggml_cuda_should_fuse_mul_mat_vec_q(const ggml_tensor * tensor) {
2641
+ ggml_tensor * src1 = tensor->src[1];
2642
+ const ggml_tensor * dst = tensor;
2643
+
2644
+ + if (ggml_cuda_emeans_has(src0)) {
2645
+ + return false;
2646
+ + }
2647
+ +
2648
+ const bool bad_padding_clear = ggml_backend_buffer_get_usage(src0->buffer) == GGML_BACKEND_BUFFER_USAGE_COMPUTE &&
2649
+ ggml_nbytes(src0) != ggml_backend_buffer_get_alloc_size(src0->buffer, src0) &&
2650
+ src0->view_src;
2651
+ @@ -2546,6 +2555,9 @@ static bool ggml_cuda_mul_mat_q_fusion_matches(const ggml_tensor * up, const ggm
2652
+
2653
+ static bool ggml_cuda_should_fuse_mul_mat_q(const ggml_tensor * up, const ggml_tensor * gate, const ggml_tensor * glu,
2654
+ const ggml_tensor * up_scale = nullptr, const ggml_tensor * gate_scale = nullptr) {
2655
+ + if (ggml_cuda_emeans_has(up->src[0]) || ggml_cuda_emeans_has(gate->src[0])) {
2656
+ + return false;
2657
+ + }
2658
+ // A hinted matmul can be fused, but its unfused path may be faster (e.g. FWHT for GGML_HINT_SRC0_IS_HADAMARD).
2659
+ if (ggml_get_op_params_i32(up, 1) != GGML_HINT_NONE || ggml_get_op_params_i32(gate, 1) != GGML_HINT_NONE) {
2660
+ return false;
2661
+ @@ -2586,6 +2598,10 @@ static bool ggml_cuda_should_fuse_mul_mat_q(const ggml_tensor * up, const ggml_t
2662
  static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
2663
  GGML_TENSOR_BINARY_OP_LOCALS
2664
 
 
2669
  if (ggml_cuda_op_mul_mat_use_fwht(dst) && ggml_cuda_op_fwht(ctx, src1, dst)) {
2670
  return;
2671
  }
2672
+ @@ -2654,6 +2670,9 @@ static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor
2673
  // [TAG_MUL_MAT_ID_CUDA_GRAPHS]
2674
  static bool ggml_cuda_mul_mat_id_needs_sync(const ggml_tensor * dst, const int cc) {
2675
  const ggml_tensor * src0 = dst->src[0];
 
2679
  const ggml_tensor * src1 = dst->src[1];
2680
  const bool f32_pedantic = src0->type == GGML_TYPE_F32 &&
2681
  ggml_prec(dst->op_params[0]) == GGML_PREC_F32_PEDANTIC;
2682
+ @@ -2693,6 +2712,9 @@ static bool ggml_cuda_mul_mat_id_needs_sync(const ggml_tensor * dst, const int c
2683
  }
2684
 
2685
  static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
 
2689
  const ggml_tensor * src0 = dst->src[0];
2690
  const ggml_tensor * src1 = dst->src[1];
2691
  const ggml_tensor * ids = dst->src[2];
2692
+ @@ -2923,7 +2945,9 @@ static bool ggml_cuda_compute_forward(ggml_backend_cuda_context & ctx, struct gg
2693
  ggml_cuda_op_repeat_back(ctx, dst);
2694
  break;
2695
  case GGML_OP_GET_ROWS:
 
2700
  break;
2701
  case GGML_OP_GET_ROWS_BACK:
2702
  ggml_cuda_op_get_rows_back(ctx, dst);
2703
+ @@ -4785,7 +4809,10 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph
2704
+
2705
+ if (node->op == GGML_OP_MUL_MAT_ID && cuda_ctx->stream_context().concurrent_events.empty() &&
2706
+ ggml_cuda_match_shared_expert(cgraph, i, i + 3) &&
2707
+ - ggml_cuda_should_fuse_mul_mat_vec_q(cgraph->nodes[i + 2]->src[1])) {
2708
+ + ggml_cuda_should_fuse_mul_mat_vec_q(cgraph->nodes[i + 2]->src[1]) &&
2709
+ + !ggml_cuda_emeans_has(cgraph->nodes[i + 2]->src[0]->src[0]) &&
2710
+ + !ggml_cuda_emeans_has(cgraph->nodes[i + 5]->src[1]->src[0]) &&
2711
+ + !ggml_cuda_emeans_has(cgraph->nodes[i + 5]->src[0]->src[0])) {
2712
+ const int outputs[] = { i + 2, i + 5 };
2713
+ if (ggml_cuda_check_fusion_memory_ranges(cgraph, i, 6, outputs, 2)) {
2714
+ ggml_tensor * routed = cgraph->nodes[i + 2];
2715
  diff --git a/ggml/src/ggml-cuda/pad.cu b/ggml/src/ggml-cuda/pad.cu
2716
  index ac078b449..5f60c070e 100644
2717
  --- a/ggml/src/ggml-cuda/pad.cu
 
2763
  pad_f32<<<gridDim, CUDA_PAD_BLOCK_SIZE, 0, stream>>>(src, s00, s01, s02, s03, dst,
2764
  diff --git a/src/llama-emeans-hook.h b/src/llama-emeans-hook.h
2765
  new file mode 100644
2766
+ index 000000000..de91a7272
2767
  --- /dev/null
2768
  +++ b/src/llama-emeans-hook.h
2769
+ @@ -0,0 +1,84 @@
2770
  +#pragma once
2771
  +
2772
  +#include "ggml.h"
 
2787
  + using get_buf_fn = ggml_backend_buffer_t (*)(ggml_backend_buffer_type_t);
2788
  + using bind_fn = void * (*)(const char *, int64_t, int64_t, int64_t);
2789
  + using is_stub_fn = bool (*)(const void *);
2790
+ + using copy_raw_fn = size_t (*)(const char *, float *, size_t, int);
2791
  +
2792
+ + init_fn init = nullptr;
2793
+ + get_buf_fn get_buf = nullptr;
2794
+ + bind_fn bind = nullptr;
2795
+ + is_stub_fn is_stub = nullptr;
2796
+ + copy_raw_fn copy_raw = nullptr;
2797
  + bool resolved = false;
2798
  +
2799
  + static llama_emeans_api & get() {
 
2803
  + HMODULE mod = GetModuleHandleA("ggml-hip.dll");
2804
  + if (!mod) mod = GetModuleHandleA("ggml-cuda.dll");
2805
  + if (mod) {
2806
+ + api.init = reinterpret_cast<init_fn>(GetProcAddress(mod, "ggml_cuda_emeans_init"));
2807
+ + api.get_buf = reinterpret_cast<get_buf_fn>(GetProcAddress(mod, "ggml_cuda_emeans_get_stub_buffer"));
2808
+ + api.bind = reinterpret_cast<bind_fn>(GetProcAddress(mod, "ggml_cuda_emeans_bind_tensor"));
2809
+ + api.is_stub = reinterpret_cast<is_stub_fn>(GetProcAddress(mod, "ggml_cuda_emeans_is_stub"));
2810
+ + api.copy_raw = reinterpret_cast<copy_raw_fn>(GetProcAddress(mod, "ggml_cuda_emeans_copy_raw_tensor"));
2811
  + }
2812
  + }
2813
  + return api;
 
2823
  + using get_buf_fn = ggml_backend_buffer_t (*)(ggml_backend_buffer_type_t);
2824
  + using bind_fn = void * (*)(const char *, int64_t, int64_t, int64_t);
2825
  + using is_stub_fn = bool (*)(const void *);
2826
+ + using copy_raw_fn = size_t (*)(const char *, float *, size_t, int);
2827
  +
2828
+ + init_fn init = nullptr;
2829
+ + get_buf_fn get_buf = nullptr;
2830
+ + bind_fn bind = nullptr;
2831
+ + is_stub_fn is_stub = nullptr;
2832
+ + copy_raw_fn copy_raw = nullptr;
2833
  + bool resolved = false;
2834
  +
2835
  + static llama_emeans_api & get() {
 
2839
  + void * mod = dlopen("libggml-cuda.so", RTLD_LAZY | RTLD_NOLOAD);
2840
  + if (!mod) mod = dlopen("libggml-hip.so", RTLD_LAZY | RTLD_NOLOAD);
2841
  + void * handle = mod ? mod : RTLD_DEFAULT;
2842
+ + api.init = reinterpret_cast<init_fn>(dlsym(handle, "ggml_cuda_emeans_init"));
2843
+ + api.get_buf = reinterpret_cast<get_buf_fn>(dlsym(handle, "ggml_cuda_emeans_get_stub_buffer"));
2844
+ + api.bind = reinterpret_cast<bind_fn>(dlsym(handle, "ggml_cuda_emeans_bind_tensor"));
2845
+ + api.is_stub = reinterpret_cast<is_stub_fn>(dlsym(handle, "ggml_cuda_emeans_is_stub"));
2846
+ + api.copy_raw = reinterpret_cast<copy_raw_fn>(dlsym(handle, "ggml_cuda_emeans_copy_raw_tensor"));
2847
  + }
2848
  + return api;
2849
  + }
 
2852
  +};
2853
  +#endif
2854
  diff --git a/src/llama-model-loader.cpp b/src/llama-model-loader.cpp
2855
+ index 6c3324f4d..cba2b65b9 100644
2856
  --- a/src/llama-model-loader.cpp
2857
  +++ b/src/llama-model-loader.cpp
2858
  @@ -1,4 +1,5 @@
 
2861
 
2862
  #include "ggml-alloc.h"
2863
  #include "ggml.h"
2864
+ @@ -571,6 +572,9 @@ llama_model_loader::llama_model_loader(
2865
+ this->use_mmap = load_mode == LLAMA_LOAD_MODE_MMAP || load_mode == LLAMA_LOAD_MODE_MMAP_MLOCK || load_mode == LLAMA_LOAD_MODE_AUTO;
2866
+ this->use_direct_io = load_mode == LLAMA_LOAD_MODE_DIRECT_IO;
2867
+
2868
+ + const char * emns_env = std::getenv("EMEANS_MODEL");
2869
+ + const bool allow_oob = (emns_env != nullptr && emns_env[0] != '\0');
2870
+ +
2871
+ if (!fname.empty()) {
2872
+ // Load the main GGUF
2873
+ struct ggml_context * ctx = NULL;
2874
+ @@ -602,7 +606,10 @@ llama_model_loader::llama_model_loader(
2875
+ }
2876
+ n_elements += ggml_nelements(cur);
2877
+ n_bytes += ggml_nbytes(cur);
2878
+ - weights_map.emplace(tensor_name, llama_tensor_weight(files.back().get(), 0, metadata, cur));
2879
+ + auto [it_w, _] = weights_map.emplace(tensor_name, llama_tensor_weight(files.back().get(), 0, metadata, cur, allow_oob));
2880
+ + if (it_w->second.is_oob) {
2881
+ + has_oob_weights = true;
2882
+ + }
2883
+ }
2884
+ auto paths = splits;
2885
+ uint16_t n_split = 0;
2886
+ @@ -741,7 +748,10 @@ llama_model_loader::llama_model_loader(
2887
+ }
2888
+ n_elements += ggml_nelements(cur);
2889
+ n_bytes += ggml_nbytes(cur);
2890
+ - weights_map.emplace(tensor_name, llama_tensor_weight(files.back().get(), file_idx, ctx_gguf.get(), cur));
2891
+ + auto [it_w, _] = weights_map.emplace(tensor_name, llama_tensor_weight(files.back().get(), file_idx, ctx_gguf.get(), cur, allow_oob));
2892
+ + if (it_w->second.is_oob) {
2893
+ + has_oob_weights = true;
2894
+ + }
2895
+ }
2896
+ }
2897
+
2898
+ @@ -801,13 +811,22 @@ llama_model_loader::llama_model_loader(
2899
+ }
2900
+ n_elements += ggml_nelements(cur);
2901
+ n_bytes += ggml_nbytes(cur);
2902
+ - weights_map.emplace(tensor_name, llama_tensor_weight(files.back().get(), 0, metadata, cur));
2903
+ + auto [it_w, _] = weights_map.emplace(tensor_name, llama_tensor_weight(files.back().get(), 0, metadata, cur, allow_oob));
2904
+ + if (it_w->second.is_oob) {
2905
+ + has_oob_weights = true;
2906
+ + }
2907
+ }
2908
+ } else {
2909
+ get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
2910
+ llm_kv = LLM_KV(llm_arch_from_string(arch_name), nullptr, arch_name.c_str());
2911
+ }
2912
+
2913
+ + if (has_oob_weights) {
2914
+ + LLAMA_LOG_INFO("%s: [emeans] metadata-stub GGUF detected (weights outside file bounds); disabling mmap/direct_io\n", __func__);
2915
+ + use_mmap = false;
2916
+ + use_direct_io = false;
2917
+ + }
2918
+ +
2919
+ n_kv = gguf_get_n_kv(metadata);
2920
+ n_tensors = weights_map.size();
2921
+
2922
+ @@ -1882,7 +1901,23 @@ bool llama_model_loader::load_all_data(
2923
+ // staging buffer for non-host buffers without async uploads, reused because a fresh allocation per tensor page faults on every load
2924
  // allocated from the CPU buffer type, which uses vm_allocate on Apple platforms, so freeing it returns its pages to the OS right away
2925
  ggml_backend_buffer_ptr read_buf;
2926
+ +
2927
+ + int emns_loop_start = -1;
2928
+ + int n_emns_raw = 0;
2929
+ + if (has_oob_weights) {
2930
+ + uint32_t loop_start_u32 = 0;
2931
+ + if (get_key(LLM_KV_LOOP_START, loop_start_u32, false)) {
2932
+ + emns_loop_start = (int) loop_start_u32;
2933
+ + }
2934
+ + }
2935
+ +
2936
  for (struct ggml_tensor * cur : tensors) {
2937
  + if (cur->data != nullptr) {
2938
  + auto & em_api = llama_emeans_api::get();
 
2943
  const auto * weight = get_weight(ggml_get_name(cur));
2944
  if (weight == nullptr) {
2945
  // this can happen with split experts models
2946
+ @@ -1897,6 +1932,52 @@ bool llama_model_loader::load_all_data(
2947
+
2948
+ size_t n_size = ggml_nbytes(cur);
2949
+
2950
+ + if (weight->is_oob) {
2951
+ + const char * tname = ggml_get_name(cur);
2952
+ + auto & em_api = llama_emeans_api::get();
2953
+ + const char * emns_env = std::getenv("EMEANS_MODEL");
2954
+ + if (em_api.ok() && em_api.copy_raw && emns_env && emns_env[0] && em_api.init(emns_env)) {
2955
+ + const size_t n_elems = (size_t) ggml_nelements(cur);
2956
+ + std::vector<float> tmp_f32(n_elems);
2957
+ + const size_t got = em_api.copy_raw(tname, tmp_f32.data(), n_elems, emns_loop_start);
2958
+ + if (got == n_elems) {
2959
+ + if (cur->type == GGML_TYPE_F32) {
2960
+ + if (check_tensors && !ggml_validate_row_data(cur->type, tmp_f32.data(), n_size)) {
2961
+ + throw std::runtime_error(format("tensor '%s' has invalid data", tname));
2962
+ + }
2963
+ + ggml_backend_tensor_set(cur, tmp_f32.data(), 0, n_size);
2964
+ + } else if (cur->type == GGML_TYPE_BF16) {
2965
+ + std::vector<ggml_bf16_t> tmp_bf16(n_elems);
2966
+ + ggml_fp32_to_bf16_row(tmp_f32.data(), tmp_bf16.data(), (int64_t) n_elems);
2967
+ + if (check_tensors && !ggml_validate_row_data(cur->type, tmp_bf16.data(), n_size)) {
2968
+ + throw std::runtime_error(format("tensor '%s' has invalid data", tname));
2969
+ + }
2970
+ + ggml_backend_tensor_set(cur, tmp_bf16.data(), 0, n_size);
2971
+ + } else if (cur->type == GGML_TYPE_F16) {
2972
+ + std::vector<ggml_fp16_t> tmp_f16(n_elems);
2973
+ + ggml_fp32_to_fp16_row(tmp_f32.data(), tmp_f16.data(), (int64_t) n_elems);
2974
+ + if (check_tensors && !ggml_validate_row_data(cur->type, tmp_f16.data(), n_size)) {
2975
+ + throw std::runtime_error(format("tensor '%s' has invalid data", tname));
2976
+ + }
2977
+ + ggml_backend_tensor_set(cur, tmp_f16.data(), 0, n_size);
2978
+ + } else {
2979
+ + throw std::runtime_error(format("unsupported ggml type %s for .emns raw tensor '%s'", ggml_type_name(cur->type), tname));
2980
+ + }
2981
+ + n_emns_raw++;
2982
+ + size_done += n_size;
2983
+ + continue;
2984
+ + }
2985
+ + }
2986
+ + const size_t name_len = std::strlen(tname);
2987
+ + if (name_len > 6 && std::strcmp(tname + name_len - 6, ".scale") == 0) {
2988
+ + std::vector<uint8_t> zeros(n_size, 0);
2989
+ + ggml_backend_tensor_set(cur, zeros.data(), 0, n_size);
2990
+ + size_done += n_size;
2991
+ + continue;
2992
+ + }
2993
+ + throw std::runtime_error(format("tensor '%s' is outside metadata-stub GGUF file bounds and was not found in EMEANS_MODEL", tname));
2994
+ + }
2995
+ +
2996
+ const bool from_mapping = use_mmap || lazy.has(cur);
2997
+
2998
+ if (from_mapping) {
2999
+ @@ -2034,6 +2115,10 @@ bool llama_model_loader::load_all_data(
3000
+ size_done += n_size;
3001
+ }
3002
+
3003
+ + if (n_emns_raw > 0) {
3004
+ + LLAMA_LOG_INFO("%s: [emeans] loaded %d raw FP32/BF16 tensors from .emns VRAM\n", __func__, n_emns_raw);
3005
+ + }
3006
+ +
3007
+ // free temporary resources used for async uploads
3008
+ for (auto * event : events) {
3009
+ ggml_backend_event_synchronize(event);
3010
+ diff --git a/src/llama-model-loader.h b/src/llama-model-loader.h
3011
+ index ed59079a4..340e02fa1 100644
3012
+ --- a/src/llama-model-loader.h
3013
+ +++ b/src/llama-model-loader.h
3014
+ @@ -32,18 +32,25 @@ struct llama_model_loader {
3015
+ struct llama_tensor_weight {
3016
+ uint16_t idx; // source file index
3017
+ size_t offs; // tensor data offset in the original file
3018
+ + bool is_oob = false; // true when tensor data lies beyond file bounds (e.g. metadata-stub GGUF with EMEANS_MODEL)
3019
+
3020
+ ggml_tensor * tensor;
3021
+
3022
+ - llama_tensor_weight(const llama_file * file, uint16_t idx, const struct gguf_context * gguf_ctx, ggml_tensor * tensor) : idx(idx), tensor(tensor) {
3023
+ + llama_tensor_weight(const llama_file * file, uint16_t idx, const struct gguf_context * gguf_ctx, ggml_tensor * tensor, bool allow_oob = false) : idx(idx), tensor(tensor) {
3024
+ const int tensor_idx = gguf_find_tensor(gguf_ctx, ggml_get_name(tensor));
3025
+ if (tensor_idx < 0) {
3026
+ throw std::runtime_error(format("tensor '%s' not found in the model", ggml_get_name(tensor)));
3027
+ }
3028
+
3029
+ offs = gguf_get_data_offset(gguf_ctx) + gguf_get_tensor_offset(gguf_ctx, tensor_idx);
3030
+ - if (offs + ggml_nbytes(tensor) < offs || offs + ggml_nbytes(tensor) > file->size()) {
3031
+ - throw std::runtime_error(format("tensor '%s' data is not within the file bounds, model is corrupted or incomplete", ggml_get_name(tensor)));
3032
+ + if (offs + ggml_nbytes(tensor) < offs) {
3033
+ + throw std::runtime_error(format("tensor '%s' data offset overflow, model is corrupted or incomplete", ggml_get_name(tensor)));
3034
+ + }
3035
+ + if (offs + ggml_nbytes(tensor) > file->size()) {
3036
+ + if (!allow_oob) {
3037
+ + throw std::runtime_error(format("tensor '%s' data is not within the file bounds, model is corrupted or incomplete", ggml_get_name(tensor)));
3038
+ + }
3039
+ + is_oob = true;
3040
+ }
3041
+ }
3042
+ };
3043
+ @@ -81,6 +88,7 @@ struct llama_model_loader {
3044
+ bool check_tensors;
3045
+ bool no_alloc;
3046
+ bool load_mtp;
3047
+ + bool has_oob_weights = false;
3048
+
3049
+ // handle TENSOR_READ_LAZY
3050
+ // use case: keep PLE / engrams embd tensors on disk, read them on demand
3051
  diff --git a/src/llama-model.cpp b/src/llama-model.cpp
3052
+ index cd5cd601c..69fb8708d 100644
3053
  --- a/src/llama-model.cpp
3054
  +++ b/src/llama-model.cpp
3055
  @@ -1,4 +1,5 @@
 
3058
 
3059
  #include "llama-arch.h"
3060
  #include "llama-ext.h"
3061
+ @@ -2263,7 +2264,52 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {
3062
  t->buffer = buf; // set dummy buffer for weights so that the backend scheduler won't try to allocate them
3063
  }
3064
  } else {
3065
  - buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft); // real buffer
3066
  + const char * emns_env = std::getenv("EMEANS_MODEL");
3067
  + bool emns_bound_any = false;
3068
+ + ggml_backend_buffer_type_t emns_gpu_buft = !ggml_backend_buft_is_host(buft) ? buft : nullptr;
3069
+ + if (emns_gpu_buft == nullptr && ml.has_oob_weights && n_gpu_layers > 0) {
3070
+ + ggml_backend_dev_t gpu_dev = (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_GPU) ? dev : nullptr;
3071
+ + if (!gpu_dev) {
3072
+ + for (const auto & d : devices) {
3073
+ + if (d.dev && ggml_backend_dev_type(d.dev) == GGML_BACKEND_DEVICE_TYPE_GPU) {
3074
+ + gpu_dev = d.dev;
3075
+ + break;
3076
+ + }
3077
+ + }
3078
+ + }
3079
+ + if (!gpu_dev) {
3080
+ + gpu_dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_GPU);
3081
+ + }
3082
+ + if (gpu_dev) {
3083
+ + emns_gpu_buft = ggml_backend_dev_buffer_type(gpu_dev);
3084
+ + }
3085
+ + }
3086
+ + if (emns_env && emns_env[0] && arch != LLM_ARCH_DFLASH && emns_gpu_buft != nullptr) {
3087
  + auto & em_api = llama_emeans_api::get();
3088
  + if (em_api.ok() && em_api.init(emns_env)) {
3089
+ + ggml_backend_buffer_t stub_buf = em_api.get_buf(emns_gpu_buft);
3090
  + if (stub_buf) {
3091
  + int n_bound = 0;
3092
  + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) {
 
3112
  }
3113
  if (buf == nullptr) {
3114
  throw std::runtime_error(format("unable to allocate %s buffer", ggml_backend_buft_name(buft)));
3115
+ @@ -2272,7 +2318,7 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {
3116
+ if (use_mlock && !ml.no_alloc && ggml_backend_buffer_is_host(buf)) {
3117
+ std::vector<ggml_backend_buffer_t> lock_bufs;
3118
+ for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) {
3119
+ - if (t->buffer != nullptr && std::find(lock_bufs.begin(), lock_bufs.end(), t->buffer) == lock_bufs.end()) {
3120
+ + if (t->buffer != nullptr && ggml_backend_buffer_is_host(t->buffer) && std::find(lock_bufs.begin(), lock_bufs.end(), t->buffer) == lock_bufs.end()) {
3121
+ lock_bufs.push_back(t->buffer);
3122
+ }
3123
+ }
3124
+ @@ -2358,6 +2404,30 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {
3125
 
3126
  load_tensors_hadamard();
3127
 
3128
  + {
3129
  + const char * emns_env_sc = std::getenv("EMEANS_MODEL");
3130
  + if (emns_env_sc && emns_env_sc[0]) {
3131
+ + auto & em_api = llama_emeans_api::get();
3132
+ + if (em_api.ok()) {
3133
+ + bool any_stub = false;
3134
+ + for (auto & l : layers) {
3135
+ + if (l.ffn_gate_exps && em_api.is_stub(l.ffn_gate_exps->data)) { l.ffn_gate_exps_s = nullptr; any_stub = true; }
3136
+ + if (l.ffn_down_exps && em_api.is_stub(l.ffn_down_exps->data)) { l.ffn_down_exps_s = nullptr; any_stub = true; }
3137
+ + if (l.ffn_up_exps && em_api.is_stub(l.ffn_up_exps->data)) { l.ffn_up_exps_s = nullptr; any_stub = true; }
3138
+ + }
3139
+ + if (any_stub) {
3140
+ + for (auto it = w_scales.begin(); it != w_scales.end(); ) {
3141
+ + if (it->first && em_api.is_stub(it->first->data)) {
3142
+ + it = w_scales.erase(it);
3143
+ + } else {
3144
+ + ++it;
3145
+ + }
3146
+ + }
3147
+ + }
3148
  + }
3149
  + }
3150
  + }
 
3153
 
3154
  return true;
3155
  diff --git a/tools/mtmd/mtmd-model.cpp b/tools/mtmd/mtmd-model.cpp
3156
+ index 157c6959b..c0ef88bea 100644
3157
  --- a/tools/mtmd/mtmd-model.cpp
3158
  +++ b/tools/mtmd/mtmd-model.cpp
3159
+ @@ -25,6 +25,160 @@
3160
  #include <functional>
3161
  #include <float.h>
3162
 
 
3168
  +#define NOMINMAX
3169
  +#endif
3170
  +#include <windows.h>
3171
+ +#else
3172
+ +#include <dlfcn.h>
3173
  +#endif
3174
  +
3175
  +// --- Minimal E-Means Vision (.emns) Loader Helpers (GPU stub-bind + CPU 4-bit dequant) ---
 
3194
  + api.get_buf = reinterpret_cast<get_buf_fn>(GetProcAddress(mod, "ggml_cuda_emeans_get_stub_buffer"));
3195
  + api.bind = reinterpret_cast<bind_fn>(GetProcAddress(mod, "ggml_cuda_emeans_bind_tensor"));
3196
  + }
3197
+ +#else
3198
+ + void * mod = dlopen("libggml-cuda.so", RTLD_LAZY | RTLD_NOLOAD);
3199
+ + if (!mod) mod = dlopen("libggml-hip.so", RTLD_LAZY | RTLD_NOLOAD);
3200
+ + void * handle = mod ? mod : RTLD_DEFAULT;
3201
+ + api.init_extra = reinterpret_cast<init_extra_fn>(dlsym(handle, "ggml_cuda_emeans_init_extra"));
3202
+ + api.get_buf = reinterpret_cast<get_buf_fn>(dlsym(handle, "ggml_cuda_emeans_get_stub_buffer"));
3203
+ + api.bind = reinterpret_cast<bind_fn>(dlsym(handle, "ggml_cuda_emeans_bind_tensor"));
3204
  +#endif
3205
  + return api;
3206
  + }
 
3317
  //
3318
  // mtmd_model_loader
3319
  //
3320
+ @@ -4472,15 +4626,114 @@ struct mtmd_model_loader {
3321
  total_data_size += ggml_nbytes(t);
3322
  }
3323
 
 
3433
  auto it_off = tensor_offset.find(t->name);
3434
  GGML_ASSERT(it_off != tensor_offset.end() && "no offset for tensor");
3435
  const size_t offset = it_off->second;
3436
+ @@ -4506,6 +4759,12 @@ struct mtmd_model_loader {
3437
  }
3438
  }
3439
  }
 
3446
  LOG_DBG("%s: loaded %zu tensors from %s\n", __func__, tensors_to_load.size(), fname.c_str());
3447
  } else {
3448
  LOG_DBG("%s: no_alloc is set, skipping tensor data loading (%zu tensors)\n", __func__, tensors_to_load.size());