diff --git a/libopenbuenos/include/openbuenos.h b/libopenbuenos/include/openbuenos.h index ef4fcc6c..31e8562e 100644 --- a/libopenbuenos/include/openbuenos.h +++ b/libopenbuenos/include/openbuenos.h @@ -349,6 +349,23 @@ ob_status_t ob_context_buffer_pool_stats(const ob_context_t* ctx, uint64_t* out_pool_hits, uint64_t* out_pool_misses); +/* + * Maps an external Linux DMA-BUF file descriptor into ctx's grouped EdgeTPU + * IOMMU domain (shared PASID with ctx->tpu_fd) via EDGETPU_MAP_DMABUF. + * + * `flags` accepts OB_BUF_TO_DEVICE / OB_BUF_FROM_DEVICE / OB_BUF_BIDIRECTIONAL + * (defaulting to bidirectional 36-bit IOVA). In mock_mode, validates arguments + * and returns a deterministic non-zero 36-bit synthetic IOVA. + */ +ob_status_t ob_dmabuf_map(ob_context_t* ctx, + int dmabuf_fd, + uint64_t offset, + uint64_t size, + uint32_t flags, + uint64_t* out_iova); + +ob_status_t ob_dmabuf_unmap(ob_context_t* ctx, uint64_t iova); + /* ========================================================================= * Graph Registration (Persistent LRU Handle Cache) & Sync/Async Execution * ========================================================================= */ @@ -694,6 +711,29 @@ ob_status_t ob_gemm_unregister_immutable_weights(ob_context_t* ctx, const void* base, size_t size); +typedef struct ob_prepack_stats { + uint32_t tiles_checked; + uint32_t tiles_prepacked; + uint32_t tiles_already_cached; + uint32_t tiles_skipped_budget; + uint32_t graphs_precompiled; + uint64_t bytes_resident; +} ob_prepack_stats_t; + +/* + * Pre-packs a batched group of static quantized weights (e.g. Q+K+V or single projection) + * into ext[2] DMA-BUFs and pre-compiles their DIVE shape executables ONCE at model load + * time, eliminating runtime cache misses, weight packing, and first-token graph compile + * stalls. Stops cleanly without evicting resident entries if the weight-cache budget is full. + * Note: jobs[j].c_mn may be NULL during prepack. + */ +ob_status_t ob_gemm_prepack_quant_batch(ob_context_t* ctx, + uint32_t m_hint, + uint32_t k_dim, + const ob_gemm_f32_quant_job_t* jobs, + uint32_t num_jobs, + ob_prepack_stats_t* out_stats); + ob_status_t ob_gemm_swiglu_int8(ob_context_t* ctx, const int8_t* x_mk, const ob_swiglu_int8_desc_t* desc, diff --git a/libopenbuenos/src/ob_buffer_pool.cpp b/libopenbuenos/src/ob_buffer_pool.cpp index 09e4e8e2..921b2350 100644 --- a/libopenbuenos/src/ob_buffer_pool.cpp +++ b/libopenbuenos/src/ob_buffer_pool.cpp @@ -209,6 +209,27 @@ void buffer_pool_clear(ob_context* ctx) { ctx->pool_current_count = 0; } +void ext_dmabuf_clear(ob_context* ctx) { + if (!ctx) return; + std::lock_guard lk(ctx->pool_mu); +#if defined(__linux__) + if (!ctx->mock_mode && ctx->tpu_fd >= 0) { + for (const auto& kv : ctx->ext_dmabuf_maps) { + const ExternalDmabufMap& rec = kv.second; + struct edgetpu_map_dmabuf_ioctl u {}; + u.offset = rec.offset; + u.size = rec.size; + u.device_address = rec.iova; + u.dmabuf_fd = rec.dmabuf_fd; + u.flags = rec.map_flags; + u.die_index = rec.die_index; + ::ioctl(ctx->tpu_fd, EDGETPU_UNMAP_DMABUF, &u); + } + } +#endif + ctx->ext_dmabuf_maps.clear(); +} + ob_status_t buffer_sync_begin_read(ob_buffer* buf) { if (!buf || !buf->ctx) return OB_ERR_INVALID_ARG; if (buf->ctx->mock_mode) return OB_OK; @@ -543,4 +564,112 @@ ob_status_t ob_context_buffer_pool_stats(const ob_context_t* ctx, return OB_OK; } +ob_status_t ob_dmabuf_map(ob_context_t* ctx, + int dmabuf_fd, + uint64_t offset, + uint64_t size, + uint32_t flags, + uint64_t* out_iova) { + if (out_iova) *out_iova = 0u; + if (!ctx || dmabuf_fd < 0 || size == 0u || !out_iova) { + return OB_ERR_INVALID_ARG; + } + if (offset > (UINT64_MAX - size) || size > (UINT64_MAX - 4095ULL)) { + return OB_ERR_INVALID_ARG; + } + + const uint32_t map_flags = ob::map_flags_from_ob_flags(flags); + std::lock_guard lk(ctx->pool_mu); + + if (ctx->mock_mode) { + const uint64_t aligned = (size + 4095ULL) & ~4095ULL; + const uint64_t iova = ctx->next_mock_iova; + ctx->next_mock_iova += (aligned > 0u) ? aligned : 4096ULL; + ob::ExternalDmabufMap rec{}; + rec.dmabuf_fd = dmabuf_fd; + rec.offset = offset; + rec.size = size; + rec.iova = iova; + rec.map_flags = map_flags; + rec.die_index = 0xffffffffu; + ctx->ext_dmabuf_maps[iova] = rec; + *out_iova = iova; + return OB_OK; + } + +#if defined(__linux__) + if (ctx->tpu_fd < 0) { + ob::set_last_error(ctx, "ob_dmabuf_map: EdgeTPU device fd is not open"); + return OB_ERR_DEVICE; + } + struct edgetpu_map_dmabuf_ioctl m {}; + m.offset = offset; + m.size = size; + m.dmabuf_fd = dmabuf_fd; + m.flags = map_flags; + m.die_index = 0xffffffffu; + if (::ioctl(ctx->tpu_fd, EDGETPU_MAP_DMABUF, &m) != 0) { + const int e = errno; + ob::set_last_error(ctx, "EDGETPU_MAP_DMABUF failed errno=" + std::to_string(e)); + return OB_ERR_IOCTL; + } + ob::ExternalDmabufMap rec{}; + rec.dmabuf_fd = dmabuf_fd; + rec.offset = offset; + rec.size = size; + rec.iova = m.device_address; + rec.map_flags = map_flags; + rec.die_index = m.die_index; + ctx->ext_dmabuf_maps[m.device_address] = rec; + *out_iova = m.device_address; + return OB_OK; +#else + ob::set_last_error(ctx, "Non-mock DMA-BUF mapping requires Linux/Android"); + return OB_ERR_UNSUPPORTED; +#endif +} + +ob_status_t ob_dmabuf_unmap(ob_context_t* ctx, uint64_t iova) { + if (!ctx || iova == 0u) { + return OB_ERR_INVALID_ARG; + } + + std::lock_guard lk(ctx->pool_mu); + auto it = ctx->ext_dmabuf_maps.find(iova); + if (it == ctx->ext_dmabuf_maps.end()) { + return OB_ERR_NOT_FOUND; + } +#if defined(__linux__) + const ob::ExternalDmabufMap rec = it->second; +#endif + ctx->ext_dmabuf_maps.erase(it); + + if (ctx->mock_mode) { + return OB_OK; + } + +#if defined(__linux__) + if (ctx->tpu_fd < 0) { + ob::set_last_error(ctx, "ob_dmabuf_unmap: EdgeTPU device fd is not open"); + return OB_ERR_DEVICE; + } + struct edgetpu_map_dmabuf_ioctl u {}; + u.offset = rec.offset; + u.size = rec.size; + u.device_address = rec.iova; + u.dmabuf_fd = rec.dmabuf_fd; + u.flags = rec.map_flags; + u.die_index = rec.die_index; + if (::ioctl(ctx->tpu_fd, EDGETPU_UNMAP_DMABUF, &u) != 0) { + const int e = errno; + ob::set_last_error(ctx, "EDGETPU_UNMAP_DMABUF failed errno=" + std::to_string(e)); + return OB_ERR_IOCTL; + } + return OB_OK; +#else + ob::set_last_error(ctx, "Non-mock DMA-BUF unmapping requires Linux/Android"); + return OB_ERR_UNSUPPORTED; +#endif +} + } // extern "C" diff --git a/libopenbuenos/src/ob_device.cpp b/libopenbuenos/src/ob_device.cpp index cf374796..2cb98b85 100644 --- a/libopenbuenos/src/ob_device.cpp +++ b/libopenbuenos/src/ob_device.cpp @@ -1509,7 +1509,8 @@ void ob_context_destroy(ob_context_t* ctx) { "hw_us=%llu wall_us=%llu quant_us=%llu hash_us=%llu pack_us=%llu dma_sync_us=%llu " "submit_us=%llu wait_us=%llu dequant_us=%llu sat_retries=%llu spin_hits=%llu " "poll_waits=%llu pool_hits=%llu pool_misses=%llu w_hits=%llu w_misses=%llu " - "w_evict=%llu w_bytes=%llu w_peak_bytes=%llu w_budget_bytes=%llu\n", + "w_evict=%llu w_bytes=%llu w_peak_bytes=%llu w_budget_bytes=%llu " + "w_entries=%llu w_peak_entries=%llu\n", static_cast(ps.calls), static_cast(ps.tiles_dispatched), static_cast(ps.horiz_fusions), @@ -1536,7 +1537,9 @@ void ob_context_destroy(ob_context_t* ctx) { static_cast(ps.weight_cache_evictions), static_cast(ps.weight_cache_bytes), static_cast(ps.weight_cache_peak_bytes), - static_cast(ps.weight_cache_budget_bytes)); + static_cast(ps.weight_cache_budget_bytes), + static_cast(ctx->weight_cache_map.size()), + static_cast(ctx->weight_cache_peak_entries)); } } ctx->async_dequant.shutdown(); @@ -1544,6 +1547,7 @@ void ob_context_destroy(ob_context_t* ctx) { ctx->worker_pool.shutdown(); ob::graph_cache_clear(ctx); ob::shared_image_clear(ctx); + ob::ext_dmabuf_clear(ctx); ob::device_close(ctx); ob::buffer_pool_clear(ctx); delete ctx; diff --git a/libopenbuenos/src/ob_gemm.cpp b/libopenbuenos/src/ob_gemm.cpp index 74a54409..77f55878 100644 --- a/libopenbuenos/src/ob_gemm.cpp +++ b/libopenbuenos/src/ob_gemm.cpp @@ -446,12 +446,14 @@ bool read_system_mem_available_bytes(size_t* out_bytes) { size_t compute_weight_cache_budget_bytes_impl(ob_context* ctx) { if (!ctx) return 0u; size_t base_cap = 0u; + bool explicit_cap = false; const char* env = std::getenv("OPENBUENOS_WEIGHT_CACHE_MB"); if (env && env[0]) { unsigned long mb = std::strtoul(env, nullptr, 10); if (mb < 16ul) mb = 16ul; if (mb > 8192ul) mb = 8192ul; base_cap = static_cast(mb) * 1024u * 1024u; + explicit_cap = true; } else { // 256 MiB on host mock; up to 2048 MiB on live Android device (bounded below MemAvailable/3). base_cap = ctx->mock_mode @@ -472,10 +474,19 @@ size_t compute_weight_cache_budget_bytes_impl(ob_context* ctx) { } } if (have_mem_avail) { - // Android LMKD-safe ceiling: never let cached ext[2] DMA-BUFs exceed MemAvailable / 3. + // Auto mode uses LMKD-safe MemAvailable / 3 ceiling; explicit OPENBUENOS_WEIGHT_CACHE_MB + // honors higher budgets on Linux hosts while reserving >= 512 MiB OS/KV headroom (>= 450 MiB). const size_t lmkd_cap = mem_avail / 3u; - if (lmkd_cap < base_cap) { - base_cap = lmkd_cap; + size_t safe_cap = lmkd_cap; + if (explicit_cap) { + constexpr size_t kReserveBytes = 512u * 1024u * 1024u; + const size_t headroom_cap = (mem_avail > 640u * 1024u * 1024u) + ? (mem_avail - kReserveBytes) + : (mem_avail / 2u); + safe_cap = std::max(lmkd_cap, headroom_cap); + } + if (safe_cap < base_cap) { + base_cap = safe_cap; } } return std::max(base_cap, 1u * 1024u * 1024u); @@ -491,7 +502,7 @@ void ensure_weight_cache_budget(ob_context* ctx, bool refresh_meminfo = false) { if (env_e && env_e[0]) { unsigned long lim = std::strtoul(env_e, nullptr, 10); if (lim < 64ul) lim = 64ul; - if (lim > 16384ul) lim = 16384ul; + if (lim > 32768ul) lim = 32768ul; ctx->weight_cache_max_entries = static_cast(lim); } else { ctx->weight_cache_max_entries = ctx->weight_cache_default_max_entries; @@ -573,6 +584,9 @@ bool weight_cache_insert_locked(ob_context* ctx, CachedWeightTile* tile) { if (ctx->weight_cache_bytes > ctx->weight_cache_peak_bytes) { ctx->weight_cache_peak_bytes = ctx->weight_cache_bytes; } + if (ctx->weight_cache_map.size() > ctx->weight_cache_peak_entries) { + ctx->weight_cache_peak_entries = ctx->weight_cache_map.size(); + } return true; } @@ -2428,6 +2442,338 @@ void gemm_release_pipeline_buffers(ob_context* ctx) { ctx->immutable_weight_regions.clear(); } +bool compute_allow_lt_64x(uint32_t k_dim, + const ob_gemm_f32_quant_job_t* jobs, + uint32_t num_jobs, + uint32_t max_k, + uint32_t max_n, + bool builtin_active, + bool lt_enabled, + bool blt_enabled, + bool horiz_fusion, + std::vector* scratch_groups) { + bool allow_lt_64x = (k_dim >= 256u && max_k >= 512u && max_n >= 128u); + if (!allow_lt_64x) return false; + + bool all_ge_128 = true; + for (uint32_t j = 0u; j < num_jobs; ++j) { + if (jobs[j].n_dim < 128u) { + all_ge_128 = false; + break; + } + } + if (all_ge_128) return true; + if (!horiz_fusion || num_jobs < 2u || !builtin_active || !blt_enabled) { + return false; + } + build_scheduled_groups(64u, k_dim, jobs, num_jobs, max_k, max_n, + builtin_active, lt_enabled, blt_enabled, + horiz_fusion, scratch_groups); + if (scratch_groups->empty()) return false; + for (const ScheduledGroup& g : *scratch_groups) { + if (!is_lt_64x_shape(64u, g.hw_k, g.hw_n)) { + return false; + } + } + return true; +} + +void split_scheduled_group_subs(const ScheduledGroup& grp, + uint32_t hw_m, + uint32_t max_k, + uint32_t max_n, + bool builtin_active, + std::vector* out) { + out->clear(); + const uint32_t k0 = grp.k0; + const uint32_t tk = grp.tk; + const uint32_t k_cap = (hw_m == 64u) ? std::min(max_k, 1536u) + : std::min(max_k, 2048u); + const uint32_t n_cap = (hw_m == 64u) + ? std::max(128u, (std::min(max_n, 1536u) / 32u) * 32u) + : std::min(max_n, 2048u); + + for (uint32_t si = 0u; si < grp.num_subs; ++si) { + const FusedSubSlice& sub = grp.subs[si]; + std::vector rects; + uint32_t sh_k = 0u, sh_n = 0u; + if (hw_m == 64u) { + sh_k = ceil_lt_64x_k_dim(tk); + sh_n = std::max(128u, align_up_u32(sub.tn, 32u)); + if (sh_k > 0u && sh_k <= k_cap && sh_n <= n_cap && is_lt_64x_shape(64u, sh_k, sh_n)) { + rects.push_back({k0, tk, sub.n0, sub.tn, sh_k, sh_n}); + } + } else if (hw_m == 1u && try_lt_1x_hw_dims(tk, sub.tn, k_cap, n_cap, &sh_k, &sh_n)) { + rects.push_back({k0, tk, sub.n0, sub.tn, sh_k, sh_n}); + } + if (rects.empty()) { + append_small_tile_rects(hw_m, k0, tk, sub.n0, sub.tn, max_k, max_n, + OB_QK8_0, builtin_active, &rects); + } + for (const TileRect& r : rects) { + ScheduledGroup sg {}; + sg.k0 = r.k0; + sg.tk = r.tk; + sg.hw_k = r.hw_k; + sg.hw_n = r.hw_n; + sg.tn_total = r.tn; + sg.num_subs = 1u; + sg.subs[0] = {sub.job_idx, r.n0, r.tn, 0u}; + out->push_back(sg); + } + } +} + +WeightTileKey compute_quant_group_weight_key(const ob_context* ctx, + uint32_t k_dim, + const ob_gemm_f32_quant_job_t* jobs, + const ScheduledGroup& grp, + uint32_t pack_fmt, + bool strict_hash) { + WeightHash128 wh_st{}; + const uint32_t num_subs = grp.num_subs; + const uint32_t k0 = grp.k0; + const uint32_t tk = grp.tk; + const uint32_t hw_k = grp.hw_k; + const uint32_t hw_n = grp.hw_n; + + if (num_subs == 1u) { + const FusedSubSlice& sub = grp.subs[0]; + const ob_gemm_f32_quant_job_t& job = jobs[sub.job_idx]; + const ob_quant_type_t qtype = static_cast(job.is_q4_0); + const uint64_t tag = quant_tile_hash_tag(qtype); + uint32_t whdr[5] = {sub.tn, tk, hw_k, hw_n, pack_fmt}; + hash128_update(&wh_st, &tag, sizeof(tag)); + hash128_update(&wh_st, whdr, sizeof(whdr)); + const uint32_t qk = ob_quant_block_elements(qtype); + const size_t blk_sz = ob_quant_block_bytes(qtype); + const uint32_t nb_k_q = k_dim / qk; + const uint32_t blk_start = k0 / qk; + const uint32_t blk_end = (k0 + tk + qk - 1u) / qk; + const uint32_t blk_cnt_q = blk_end - blk_start; + if ((k0 % qk) != 0u || (tk % qk) != 0u) { + uint32_t sub_k[2] = {k0 % qk, tk}; + hash128_update(&wh_st, sub_k, sizeof(sub_k)); + } + const size_t row_blk_bytes = static_cast(blk_cnt_q) * blk_sz; + const size_t row_stride_bytes = static_cast(nb_k_q) * blk_sz; + const uint8_t* raw_base = static_cast(job.b_nk) + + (static_cast(sub.n0) * nb_k_q + blk_start) * blk_sz; + hash_weight_tile_for_ctx(ctx, &wh_st, raw_base, row_stride_bytes, sub.tn, + row_blk_bytes, strict_hash); + } else { + const uint64_t tag = 0x465553455F575431ULL; + uint32_t fhdr[5] = {num_subs, tk, hw_k, hw_n, pack_fmt}; + hash128_update(&wh_st, &tag, sizeof(tag)); + hash128_update(&wh_st, fhdr, sizeof(fhdr)); + for (uint32_t si = 0u; si < num_subs; ++si) { + const FusedSubSlice& sub = grp.subs[si]; + const ob_gemm_f32_quant_job_t& job = jobs[sub.job_idx]; + const ob_quant_type_t qtype = static_cast(job.is_q4_0); + uint32_t shdr[3] = {sub.tn, sub.out_off, static_cast(qtype)}; + hash128_update(&wh_st, shdr, sizeof(shdr)); + const uint32_t qk = ob_quant_block_elements(qtype); + const size_t blk_sz = ob_quant_block_bytes(qtype); + const uint32_t nb_k_q = k_dim / qk; + const uint32_t blk_start = k0 / qk; + const uint32_t blk_end = (k0 + tk + qk - 1u) / qk; + const uint32_t blk_cnt_q = blk_end - blk_start; + if ((k0 % qk) != 0u || (tk % qk) != 0u) { + uint32_t sub_k[2] = {k0 % qk, tk}; + hash128_update(&wh_st, sub_k, sizeof(sub_k)); + } + const size_t row_blk_bytes = static_cast(blk_cnt_q) * blk_sz; + const size_t row_stride_bytes = static_cast(nb_k_q) * blk_sz; + const uint8_t* raw_base = static_cast(job.b_nk) + + (static_cast(sub.n0) * nb_k_q + blk_start) * blk_sz; + hash_weight_tile_for_ctx(ctx, &wh_st, raw_base, row_stride_bytes, sub.tn, + row_blk_bytes, strict_hash); + } + } + return finalize_weight_key(wh_st); +} + +template +ob_status_t pack_quant_group_tile_locked(ob_context* ctx, + uint32_t k_dim, + const ob_gemm_f32_quant_job_t* jobs, + const ScheduledGroup& grp, + bool tile_use_w8a16, + bool is_lt64_tile, + bool grp_has_q4_k, + const WeightTileKey& wh, + bool abort_if_uncacheable, + WorkerPool* pack_pool, + std::vector* b_q_tile, + PrepareSpaceFn& prepare_space, + bool* out_rejected_fusion, + bool* out_skipped_budget, + uint32_t* out_scale_d, + CachedWeightTile** out_tile) { + *out_rejected_fusion = false; + *out_skipped_budget = false; + *out_tile = nullptr; + + const uint32_t k0 = grp.k0; + const uint32_t tk = grp.tk; + const uint32_t hw_k = grp.hw_k; + const uint32_t hw_n = grp.hw_n; + const uint32_t tn_total = grp.tn_total; + const uint32_t num_subs = grp.num_subs; + + const size_t ext2_sz = tile_use_w8a16 + ? pack_w8a16_ext2_size(hw_n, hw_k) + : (is_lt64_tile ? pack_ext2_size_for_lt_64x(hw_n, hw_k) + : pack_ext2_size_for_tile(hw_n, hw_k, false)); + const size_t ext2_slab_bytes = buffer_slab_size(ext2_sz); + + // When prepacking at load time (abort_if_uncacheable && single-sub), bail BEFORE unpacking if budget is full. + if (abort_if_uncacheable && num_subs == 1u) { + bool fit_precheck = false; + ob_status_t chk_st = prepare_space(ext2_slab_bytes, &fit_precheck); + if (chk_st != OB_OK) return chk_st; + if (!fit_precheck) { + *out_skipped_budget = true; + return OB_OK; + } + } + + b_q_tile->resize(static_cast(hw_n) * hw_k); + if (tn_total < hw_n) { + std::memset(b_q_tile->data() + static_cast(tn_total) * hw_k, 0, + static_cast(hw_n - tn_total) * hw_k); + } + std::vector sb_vec(tn_total, 0.0f); + std::vector offset_vec(grp_has_q4_k ? tn_total : 0u, 0.0f); + bool any_nonzero_offset = false; + std::vector row_stats(tile_use_w8a16 ? 0u : tn_total); + uint32_t min_sub_d = 0xFFFFFFFFu; + double all_max_l2 = 0.0; + uint64_t all_max_l1 = 0ULL; + uint64_t all_max_asum = 0ULL; + + for (uint32_t si = 0u; si < num_subs; ++si) { + const FusedSubSlice& sub = grp.subs[si]; + const ob_gemm_f32_quant_job_t& job = jobs[sub.job_idx]; + const ob_quant_type_t qtype = static_cast(job.is_q4_0); + int8_t* bq_dst = b_q_tile->data() + static_cast(sub.out_off) * hw_k; + float* sb_dst = sb_vec.data() + sub.out_off; + float* off_dst = grp_has_q4_k ? (offset_vec.data() + sub.out_off) : nullptr; + RowNormStats* st_dst = tile_use_w8a16 ? nullptr : (row_stats.data() + sub.out_off); + if (quant::requant_rows(qtype, job.b_nk, k_dim, sub.n0, sub.tn, k0, tk, hw_k, + bq_dst, sb_dst, off_dst, pack_pool, st_dst)) { + any_nonzero_offset = true; + } + if (!tile_use_w8a16) { + double sub_max_l2 = 0.0; + uint64_t sub_max_l1 = 0ULL; + uint64_t sub_max_asum = 0ULL; + for (uint32_t ni = 0u; ni < sub.tn; ++ni) { + if (st_dst[ni].l2 > sub_max_l2) sub_max_l2 = st_dst[ni].l2; + if (st_dst[ni].l1 > sub_max_l1) sub_max_l1 = st_dst[ni].l1; + if (st_dst[ni].asum > sub_max_asum) sub_max_asum = st_dst[ni].asum; + } + if (sub_max_l2 > all_max_l2) all_max_l2 = sub_max_l2; + if (sub_max_l1 > all_max_l1) all_max_l1 = sub_max_l1; + if (sub_max_asum > all_max_asum) all_max_asum = sub_max_asum; + if (num_subs >= 2u) { + uint32_t sd = compute_scale_D_from_maxima( + sub_max_l2, sub_max_l1, sub_max_asum, tk, 0); + if (sd < min_sub_d) min_sub_d = sd; + } + } + } + if (any_nonzero_offset) { + sb_vec.insert(sb_vec.end(), offset_vec.begin(), offset_vec.end()); + } + + uint32_t scale_d = 1u; + if (!tile_use_w8a16) { + scale_d = compute_scale_D_from_maxima( + all_max_l2, all_max_l1, all_max_asum, tk, 0); + + // Precision guard for horizontal fusion: if any sub-job's optimal D is + // > 1.5x smaller than the fused D (e.g. mixed sparse+dense synthetic test), + // cache a zero-byte split sentinel and run sub-jobs independently with exact D. + if (num_subs >= 2u && min_sub_d > 0u && (scale_d * 2u > min_sub_d * 3u)) { + bool sentinel_ok = false; + ob_status_t spst = prepare_space(0u, &sentinel_ok); + if (spst != OB_OK) return spst; + if (sentinel_ok) { + CachedWeightTile* sentinel = new (std::nothrow) CachedWeightTile(); + if (sentinel) { + sentinel->key = wh; + sentinel->scale_d = scale_d; + sentinel->hw_k = hw_k; + sentinel->hw_n = hw_n; + sentinel->ext2_buf = nullptr; + sentinel->ext2_bytes = 0u; + sentinel->rejected_fusion = true; + if (!weight_cache_insert_locked(ctx, sentinel)) { + delete sentinel; + } + } + } + *out_scale_d = scale_d; + *out_rejected_fusion = true; + return OB_OK; + } + } + + bool cacheable = false; + ob_status_t pst = prepare_space(ext2_slab_bytes, &cacheable); + if (pst != OB_OK) return pst; + if (abort_if_uncacheable && !cacheable) { + *out_skipped_budget = true; + return OB_OK; + } + + ob_buffer* wbuf = nullptr; + ob_status_t wst = ob_buffer_alloc( + ctx, ext2_sz, OB_BUF_BIDIRECTIONAL | OB_BUF_NO_POOL, &wbuf); + if (wst == OB_OK) { + wst = buffer_sync_begin_write(wbuf); + if (wst == OB_OK) { + uint8_t* dst_ext2 = static_cast(ob_buffer_data(wbuf)); + if (tile_use_w8a16) { + pack_w8a16_ext2_into(dst_ext2, hw_n, hw_k, b_q_tile->data()); + } else if (is_lt64_tile) { + pack_ext2_for_lt_64x_into( + dst_ext2, hw_n, hw_k, b_q_tile->data(), nullptr, pack_pool); + } else { + pack_ext2_for_tile_into( + dst_ext2, hw_n, hw_k, b_q_tile->data(), nullptr, false, pack_pool); + } + wst = buffer_sync_end_write(wbuf); + } + } + if (wst != OB_OK) { + if (wbuf) ob_buffer_free(wbuf); + return wst; + } + + CachedWeightTile* tile = new (std::nothrow) CachedWeightTile(); + if (!tile) { + ob_buffer_free(wbuf); + return OB_ERR_NO_MEMORY; + } + tile->key = wh; + tile->scale_d = scale_d; + tile->hw_k = hw_k; + tile->hw_n = hw_n; + tile->row_s_b = std::move(sb_vec); + tile->ext2_buf = wbuf; + tile->ext2_bytes = wbuf->slab.alloc_size; + if (cacheable) { + weight_cache_insert_locked(ctx, tile); + } else { + tile->in_cache = false; + } + *out_scale_d = scale_d; + *out_tile = tile; + return OB_OK; +} + } // namespace ob extern "C" { @@ -3752,35 +4098,9 @@ ob_status_t ob_gemm_matmul_f32_quant_batch(ob_context_t* ctx, std::vector packed_tile; std::vector groups; - bool allow_lt_64x = (k_dim >= 256u && max_k >= 512u && max_n >= 128u); - if (allow_lt_64x) { - bool all_ge_128 = true; - for (uint32_t j = 0u; j < num_jobs; ++j) { - if (jobs[j].n_dim < 128u) { - all_ge_128 = false; - break; - } - } - if (!all_ge_128) { - if (!horiz_fusion || num_jobs < 2u || !builtin_active || !blt_enabled) { - allow_lt_64x = false; - } else { - ob::build_scheduled_groups(64u, k_dim, jobs, num_jobs, max_k, max_n, - builtin_active, lt_enabled, blt_enabled, - horiz_fusion, &groups); - if (groups.empty()) { - allow_lt_64x = false; - } else { - for (const ob::ScheduledGroup& g : groups) { - if (!ob::is_lt_64x_shape(64u, g.hw_k, g.hw_n)) { - allow_lt_64x = false; - break; - } - } - } - } - } - } + const bool allow_lt_64x = ob::compute_allow_lt_64x( + k_dim, jobs, num_jobs, max_k, max_n, builtin_active, lt_enabled, blt_enabled, + horiz_fusion, &groups); std::vector m_slices = ob::build_m_slices( m_dim, max_m, builtin_active, true, allow_lt_64x, blt_enabled); @@ -3817,40 +4137,11 @@ ob_status_t ob_gemm_matmul_f32_quant_batch(ob_context_t* ctx, // Helper to split a rejected multi-sub horizontal fusion cleanly into 1-sub groups. auto fallback_split_subs = [&]() -> ob_status_t { - for (uint32_t si = 0u; si < num_subs; ++si) { - const ob::FusedSubSlice& sub = grp.subs[si]; - std::vector rects; - const uint32_t k_cap = (hw_m == 64u) ? std::min(max_k, 1536u) - : std::min(max_k, 2048u); - const uint32_t n_cap = (hw_m == 64u) - ? std::max(128u, (std::min(max_n, 1536u) / 32u) * 32u) - : std::min(max_n, 2048u); - uint32_t sh_k = 0u, sh_n = 0u; - if (hw_m == 64u) { - sh_k = ob::ceil_lt_64x_k_dim(tk); - sh_n = std::max(128u, ob::align_up_u32(sub.tn, 32u)); - if (sh_k > 0u && sh_k <= k_cap && sh_n <= n_cap && ob::is_lt_64x_shape(64u, sh_k, sh_n)) { - rects.push_back({k0, tk, sub.n0, sub.tn, sh_k, sh_n}); - } - } else if (hw_m == 1u && ob::try_lt_1x_hw_dims(tk, sub.tn, k_cap, n_cap, &sh_k, &sh_n)) { - rects.push_back({k0, tk, sub.n0, sub.tn, sh_k, sh_n}); - } - if (rects.empty()) { - ob::append_small_tile_rects(hw_m, k0, tk, sub.n0, sub.tn, max_k, max_n, - OB_QK8_0, builtin_active, &rects); - } - for (const ob::TileRect& r : rects) { - ob::ScheduledGroup sg {}; - sg.k0 = r.k0; - sg.tk = r.tk; - sg.hw_k = r.hw_k; - sg.hw_n = r.hw_n; - sg.tn_total = r.tn; - sg.num_subs = 1u; - sg.subs[0] = {sub.job_idx, r.n0, r.tn, 0u}; - ob_status_t sst = self_ref(sg, self_ref); - if (sst != OB_OK) return sst; - } + std::vector split_groups; + ob::split_scheduled_group_subs(grp, hw_m, max_k, max_n, builtin_active, &split_groups); + for (const ob::ScheduledGroup& sg : split_groups) { + ob_status_t sst = self_ref(sg, self_ref); + if (sst != OB_OK) return sst; } return OB_OK; }; @@ -4013,61 +4304,8 @@ ob_status_t ob_gemm_matmul_f32_quant_batch(ob_context_t* ctx, const bool is_lt64_tile = (!tile_use_w8a16) && ob::is_lt_64x_shape(hw_m, hw_k, hw_n); const uint32_t pack_fmt = tile_use_w8a16 ? 2u : (is_lt64_tile ? 1u : 0u); const uint64_t th0 = prof_on ? ob::monotonic_now_ns() : 0u; - ob::WeightHash128 wh_st{}; - if (num_subs == 1u) { - const ob::FusedSubSlice& sub = grp.subs[0]; - const ob_gemm_f32_quant_job_t& job = jobs[sub.job_idx]; - const ob_quant_type_t qtype = static_cast(job.is_q4_0); - const uint64_t tag = ob::quant_tile_hash_tag(qtype); - uint32_t whdr[5] = {sub.tn, tk, hw_k, hw_n, pack_fmt}; - ob::hash128_update(&wh_st, &tag, sizeof(tag)); - ob::hash128_update(&wh_st, whdr, sizeof(whdr)); - const uint32_t qk = ob_quant_block_elements(qtype); - const size_t blk_sz = ob_quant_block_bytes(qtype); - const uint32_t nb_k_q = k_dim / qk; - const uint32_t blk_start = k0 / qk; - const uint32_t blk_end = (k0 + tk + qk - 1u) / qk; - const uint32_t blk_cnt_q = blk_end - blk_start; - if ((k0 % qk) != 0u || (tk % qk) != 0u) { - uint32_t sub_k[2] = {k0 % qk, tk}; - ob::hash128_update(&wh_st, sub_k, sizeof(sub_k)); - } - const size_t row_blk_bytes = static_cast(blk_cnt_q) * blk_sz; - const size_t row_stride_bytes = static_cast(nb_k_q) * blk_sz; - const uint8_t* raw_base = static_cast(job.b_nk) + - (static_cast(sub.n0) * nb_k_q + blk_start) * blk_sz; - ob::hash_weight_tile_for_ctx(ctx, &wh_st, raw_base, row_stride_bytes, sub.tn, - row_blk_bytes, strict_hash); - } else { - const uint64_t tag = 0x465553455F575431ULL; - uint32_t fhdr[5] = {num_subs, tk, hw_k, hw_n, pack_fmt}; - ob::hash128_update(&wh_st, &tag, sizeof(tag)); - ob::hash128_update(&wh_st, fhdr, sizeof(fhdr)); - for (uint32_t si = 0u; si < num_subs; ++si) { - const ob::FusedSubSlice& sub = grp.subs[si]; - const ob_gemm_f32_quant_job_t& job = jobs[sub.job_idx]; - const ob_quant_type_t qtype = static_cast(job.is_q4_0); - uint32_t shdr[3] = {sub.tn, sub.out_off, static_cast(qtype)}; - ob::hash128_update(&wh_st, shdr, sizeof(shdr)); - const uint32_t qk = ob_quant_block_elements(qtype); - const size_t blk_sz = ob_quant_block_bytes(qtype); - const uint32_t nb_k_q = k_dim / qk; - const uint32_t blk_start = k0 / qk; - const uint32_t blk_end = (k0 + tk + qk - 1u) / qk; - const uint32_t blk_cnt_q = blk_end - blk_start; - if ((k0 % qk) != 0u || (tk % qk) != 0u) { - uint32_t sub_k[2] = {k0 % qk, tk}; - ob::hash128_update(&wh_st, sub_k, sizeof(sub_k)); - } - const size_t row_blk_bytes = static_cast(blk_cnt_q) * blk_sz; - const size_t row_stride_bytes = static_cast(nb_k_q) * blk_sz; - const uint8_t* raw_base = static_cast(job.b_nk) + - (static_cast(sub.n0) * nb_k_q + blk_start) * blk_sz; - ob::hash_weight_tile_for_ctx(ctx, &wh_st, raw_base, row_stride_bytes, sub.tn, - row_blk_bytes, strict_hash); - } - } - const ob::WeightTileKey wh = ob::finalize_weight_key(wh_st); + const ob::WeightTileKey wh = ob::compute_quant_group_weight_key( + ctx, k_dim, jobs, grp, pack_fmt, strict_hash); w_tile = ob::weight_cache_find_locked(ctx, wh); if (prof_on) ctx->prof.hash_ns += (ob::monotonic_now_ns() - th0); @@ -4077,144 +4315,19 @@ ob_status_t ob_gemm_matmul_f32_quant_batch(ob_context_t* ctx, if (!w_tile) { const uint64_t tp0 = prof_on ? ob::monotonic_now_ns() : 0u; - b_q_tile.resize(static_cast(hw_n) * hw_k); - if (tn_total < hw_n) { - std::memset(b_q_tile.data() + static_cast(tn_total) * hw_k, 0, - static_cast(hw_n - tn_total) * hw_k); - } - std::vector sb_vec(tn_total, 0.0f); - std::vector offset_vec(grp_has_q4_k ? tn_total : 0u, 0.0f); - bool any_nonzero_offset = false; - std::vector row_stats(tile_use_w8a16 ? 0u : tn_total); - uint32_t min_sub_d = 0xFFFFFFFFu; - double all_max_l2 = 0.0; - uint64_t all_max_l1 = 0ULL; - uint64_t all_max_asum = 0ULL; - - for (uint32_t si = 0u; si < num_subs; ++si) { - const ob::FusedSubSlice& sub = grp.subs[si]; - const ob_gemm_f32_quant_job_t& job = jobs[sub.job_idx]; - const ob_quant_type_t qtype = static_cast(job.is_q4_0); - int8_t* bq_dst = b_q_tile.data() + static_cast(sub.out_off) * hw_k; - float* sb_dst = sb_vec.data() + sub.out_off; - float* off_dst = grp_has_q4_k ? (offset_vec.data() + sub.out_off) : nullptr; - ob::RowNormStats* st_dst = - tile_use_w8a16 ? nullptr : (row_stats.data() + sub.out_off); - if (ob::quant::requant_rows(qtype, job.b_nk, k_dim, sub.n0, sub.tn, k0, tk, hw_k, - bq_dst, sb_dst, off_dst, &ctx->worker_pool, st_dst)) { - any_nonzero_offset = true; - } - if (!tile_use_w8a16) { - double sub_max_l2 = 0.0; - uint64_t sub_max_l1 = 0ULL; - uint64_t sub_max_asum = 0ULL; - for (uint32_t ni = 0u; ni < sub.tn; ++ni) { - if (st_dst[ni].l2 > sub_max_l2) sub_max_l2 = st_dst[ni].l2; - if (st_dst[ni].l1 > sub_max_l1) sub_max_l1 = st_dst[ni].l1; - if (st_dst[ni].asum > sub_max_asum) sub_max_asum = st_dst[ni].asum; - } - if (sub_max_l2 > all_max_l2) all_max_l2 = sub_max_l2; - if (sub_max_l1 > all_max_l1) all_max_l1 = sub_max_l1; - if (sub_max_asum > all_max_asum) all_max_asum = sub_max_asum; - if (num_subs >= 2u) { - uint32_t sd = ob::compute_scale_D_from_maxima( - sub_max_l2, sub_max_l1, sub_max_asum, tk, 0); - if (sd < min_sub_d) min_sub_d = sd; - } - } - } - if (any_nonzero_offset) { - sb_vec.insert(sb_vec.end(), offset_vec.begin(), offset_vec.end()); - } - - if (!tile_use_w8a16) { - scale_d = ob::compute_scale_D_from_maxima( - all_max_l2, all_max_l1, all_max_asum, tk, 0); - - // Precision guard for horizontal fusion: if any sub-job's optimal D is - // > 1.5x smaller than the fused D (e.g. mixed sparse+dense synthetic test), - // cache a zero-byte split sentinel and run sub-jobs independently with exact D. - if (num_subs >= 2u && min_sub_d > 0u && (scale_d * 2u > min_sub_d * 3u)) { - bool sentinel_ok = false; - ob_status_t spst = prepare_cache_space(0u, &sentinel_ok); - if (spst != OB_OK) { - drain_all_cleanup(); - return spst; - } - if (sentinel_ok) { - ob::CachedWeightTile* sentinel = new (std::nothrow) ob::CachedWeightTile(); - if (sentinel) { - sentinel->key = wh; - sentinel->scale_d = scale_d; - sentinel->hw_k = hw_k; - sentinel->hw_n = hw_n; - sentinel->ext2_buf = nullptr; - sentinel->ext2_bytes = 0u; - sentinel->rejected_fusion = true; - if (!ob::weight_cache_insert_locked(ctx, sentinel)) { - delete sentinel; - } - } - } - if (prof_on) ctx->prof.weight_pack_ns += (ob::monotonic_now_ns() - tp0); - return fallback_split_subs(); - } - } - - const size_t ext2_sz = tile_use_w8a16 - ? ob::pack_w8a16_ext2_size(hw_n, hw_k) - : (is_lt64_tile ? ob::pack_ext2_size_for_lt_64x(hw_n, hw_k) - : ob::pack_ext2_size_for_tile(hw_n, hw_k, false)); - bool cacheable = false; - const size_t ext2_slab_bytes = ob::buffer_slab_size(ext2_sz); - ob_status_t pst = prepare_cache_space(ext2_slab_bytes, &cacheable); + bool rejected_fusion = false; + bool skipped_budget = false; + ob_status_t pst = ob::pack_quant_group_tile_locked( + ctx, k_dim, jobs, grp, tile_use_w8a16, is_lt64_tile, grp_has_q4_k, wh, + false, &ctx->worker_pool, &b_q_tile, prepare_cache_space, + &rejected_fusion, &skipped_budget, &scale_d, &w_tile); + if (prof_on) ctx->prof.weight_pack_ns += (ob::monotonic_now_ns() - tp0); if (pst != OB_OK) { drain_all_cleanup(); return pst; } - - ob_buffer* wbuf = nullptr; - ob_status_t wst = ob_buffer_alloc( - ctx, ext2_sz, OB_BUF_BIDIRECTIONAL | OB_BUF_NO_POOL, &wbuf); - if (wst == OB_OK) { - wst = ob::buffer_sync_begin_write(wbuf); - if (wst == OB_OK) { - uint8_t* dst_ext2 = static_cast(ob_buffer_data(wbuf)); - if (tile_use_w8a16) { - ob::pack_w8a16_ext2_into(dst_ext2, hw_n, hw_k, b_q_tile.data()); - } else if (is_lt64_tile) { - ob::pack_ext2_for_lt_64x_into( - dst_ext2, hw_n, hw_k, b_q_tile.data(), nullptr, &ctx->worker_pool); - } else { - ob::pack_ext2_for_tile_into( - dst_ext2, hw_n, hw_k, b_q_tile.data(), nullptr, false, &ctx->worker_pool); - } - wst = ob::buffer_sync_end_write(wbuf); - } - } - if (prof_on) ctx->prof.weight_pack_ns += (ob::monotonic_now_ns() - tp0); - if (wst != OB_OK) { - if (wbuf) ob_buffer_free(wbuf); - drain_all_cleanup(); - return wst; - } - w_tile = new (std::nothrow) ob::CachedWeightTile(); - if (!w_tile) { - ob_buffer_free(wbuf); - drain_all_cleanup(); - return OB_ERR_NO_MEMORY; - } - w_tile->key = wh; - w_tile->scale_d = scale_d; - w_tile->hw_k = hw_k; - w_tile->hw_n = hw_n; - w_tile->row_s_b = std::move(sb_vec); - w_tile->ext2_buf = wbuf; - w_tile->ext2_bytes = wbuf->slab.alloc_size; - if (cacheable) { - ob::weight_cache_insert_locked(ctx, w_tile); - } else { - w_tile->in_cache = false; + if (rejected_fusion) { + return fallback_split_subs(); } } else { scale_d = w_tile->scale_d; @@ -4525,6 +4638,184 @@ ob_status_t ob_gemm_matmul_f32_q8_0(ob_context_t* ctx, return ob_gemm_matmul_f32_quant_batch(ctx, a_mk, m_dim, k_dim, &job, 1u, out_stats); } +ob_status_t ob_gemm_prepack_quant_batch(ob_context_t* ctx, + uint32_t m_hint, + uint32_t k_dim, + const ob_gemm_f32_quant_job_t* jobs, + uint32_t num_jobs, + ob_prepack_stats_t* out_stats) { + if (!ctx || !jobs || m_hint == 0u || k_dim == 0u || num_jobs == 0u || (k_dim % OB_QK8_0) != 0u) { + return OB_ERR_INVALID_ARG; + } + for (uint32_t j = 0u; j < num_jobs; ++j) { + if (!jobs[j].b_nk || jobs[j].n_dim == 0u || !ob::quant::is_valid_type(jobs[j].is_q4_0)) { + return OB_ERR_INVALID_ARG; + } + const ob_quant_type_t qt = static_cast(jobs[j].is_q4_0); + const uint32_t qk = ob_quant_block_elements(qt); + if (qk == 0u || (k_dim % qk) != 0u) { + return OB_ERR_INVALID_ARG; + } + } + + ob_prepack_stats_t local_stats{}; + std::lock_guard lk(ctx->gemm_mu); + + const uint32_t max_m = ctx->tile_max_m; + const uint32_t max_k = std::max(OB_QK8_0, (ctx->tile_max_k / OB_QK8_0) * OB_QK8_0); + const uint32_t max_n = ctx->tile_max_n; + const ob_gemm_emitter_fn emitter = ctx->gemm_emitter; + void* const emitter_ud = ctx->gemm_emitter_user_data; + const bool builtin_active = ctx->builtin_emitter_active; + const bool strict_hash = ctx->strict_weight_hash; + const bool lt_enabled = ctx->large_tiles_enabled; + const bool blt_enabled = ctx->batched_large_tiles_enabled; + const bool horiz_fusion = ctx->horiz_fusion_enabled; + const uint32_t w8a16_mode = ctx->w8a16_mode; + + if (!builtin_active || emitter == nullptr) { + local_stats.bytes_resident = static_cast(ctx->weight_cache_bytes); + if (out_stats) *out_stats = local_stats; + return OB_OK; + } + + ob::ensure_weight_cache_budget(ctx, true); + + ob::WorkerPool local_pool; + ob::WorkerPool* pack_pool = &ctx->worker_pool; + if (ctx->num_threads <= 1u) { + local_pool.init(4u); + pack_pool = &local_pool; + } + + auto check_budget_no_evict = [&](size_t incoming_bytes, bool* out_cacheable) -> ob_status_t { + *out_cacheable = + (ctx->weight_cache_bytes + incoming_bytes <= ctx->weight_cache_max_bytes) && + (ctx->weight_cache_map.size() < ctx->weight_cache_max_entries); + return OB_OK; + }; + + std::vector& b_q_tile = ctx->gemm_bq_scratch; + std::vector groups; + + const bool allow_lt_64x = ob::compute_allow_lt_64x( + k_dim, jobs, num_jobs, max_k, max_n, builtin_active, lt_enabled, blt_enabled, + horiz_fusion, &groups); + std::vector m_slices = ob::build_m_slices( + m_hint, max_m, builtin_active, true, allow_lt_64x, blt_enabled); + + std::vector seen_hw_m; + seen_hw_m.reserve(m_slices.size()); + + for (const ob::MSlice& ms : m_slices) { + const uint32_t hw_m = ms.hw_m; + if (std::find(seen_hw_m.begin(), seen_hw_m.end(), hw_m) != seen_hw_m.end()) { + continue; + } + seen_hw_m.push_back(hw_m); + + ob::build_scheduled_groups(hw_m, k_dim, jobs, num_jobs, max_k, max_n, + builtin_active, lt_enabled, blt_enabled, + horiz_fusion, &groups); + + auto prepack_group = [&](const ob::ScheduledGroup& grp, auto& self_ref) -> ob_status_t { + const uint32_t hw_k = grp.hw_k; + const uint32_t hw_n = grp.hw_n; + const uint32_t num_subs = grp.num_subs; + const bool tile_use_w8a16 = + !ctx->mock_mode && w8a16_mode == 1u && + hw_m == 1u && ob::is_w8a16_pt_1x_shape(1u, hw_k, hw_n); + const bool is_lt64_tile = (!tile_use_w8a16) && ob::is_lt_64x_shape(hw_m, hw_k, hw_n); + const uint32_t pack_fmt = tile_use_w8a16 ? 2u : (is_lt64_tile ? 1u : 0u); + + bool grp_has_q4_k = false; + for (uint32_t si = 0u; si < num_subs; ++si) { + if (jobs[grp.subs[si].job_idx].is_q4_0 == static_cast(OB_QUANT_Q4_K)) { + grp_has_q4_k = true; + break; + } + } + + const ob::WeightTileKey wh = ob::compute_quant_group_weight_key( + ctx, k_dim, jobs, grp, pack_fmt, strict_hash); + local_stats.tiles_checked += 1u; + + auto it = ctx->weight_cache_map.find(wh); + ob::CachedWeightTile* w_tile = (it != ctx->weight_cache_map.end()) ? it->second : nullptr; + if (w_tile && w_tile->rejected_fusion) { + std::vector split_groups; + ob::split_scheduled_group_subs(grp, hw_m, max_k, max_n, builtin_active, &split_groups); + for (const ob::ScheduledGroup& sg : split_groups) { + ob_status_t sst = self_ref(sg, self_ref); + if (sst != OB_OK) return sst; + } + return OB_OK; + } + + uint32_t scale_d = 1u; + if (w_tile) { + local_stats.tiles_already_cached += 1u; + scale_d = w_tile->scale_d; + } else { + bool rejected_fusion = false; + bool skipped_budget = false; + ob_status_t pst = ob::pack_quant_group_tile_locked( + ctx, k_dim, jobs, grp, tile_use_w8a16, is_lt64_tile, grp_has_q4_k, wh, + true, pack_pool, &b_q_tile, check_budget_no_evict, + &rejected_fusion, &skipped_budget, &scale_d, &w_tile); + if (pst != OB_OK) return pst; + if (rejected_fusion) { + std::vector split_groups; + ob::split_scheduled_group_subs(grp, hw_m, max_k, max_n, builtin_active, &split_groups); + for (const ob::ScheduledGroup& sg : split_groups) { + ob_status_t sst = self_ref(sg, self_ref); + if (sst != OB_OK) return sst; + } + return OB_OK; + } + if (skipped_budget || !w_tile) { + local_stats.tiles_skipped_budget += 1u; + return OB_OK; + } + local_stats.tiles_prepacked += 1u; + } + + if (!tile_use_w8a16) { + ob_gemm_desc_t desc {}; + desc.m_dim = hw_m; + desc.k_dim = hw_k; + desc.n_dim = hw_n; + desc.s_in = 1.0f; + desc.s_w = 1.0f; + desc.s_out = static_cast(scale_d); + desc.activation = OB_ACT_NONE; + desc.cache_key = ob::hash_shape_key( + hw_m, hw_k, hw_n, 0, 0, scale_d, 0u, ctx->freetile_enabled); + ob::CachedGraph* entry = nullptr; + bool was_hit = false; + if (ob::acquire_tile_entry(ctx, emitter, emitter_ud, desc, &entry, &was_hit) == OB_OK) { + if (!was_hit) local_stats.graphs_precompiled += 1u; + ob::release_tile_entry(ctx, entry); + } + } + return OB_OK; + }; + + for (const ob::ScheduledGroup& grp : groups) { + ob_status_t pst = prepack_group(grp, prepack_group); + if (pst != OB_OK) { + local_stats.bytes_resident = static_cast(ctx->weight_cache_bytes); + if (out_stats) *out_stats = local_stats; + return pst; + } + } + } + + local_stats.bytes_resident = static_cast(ctx->weight_cache_bytes); + if (out_stats) *out_stats = local_stats; + return OB_OK; +} + ob_status_t ob_gemm_swiglu_int8(ob_context_t* ctx, const int8_t* x_mk, const ob_swiglu_int8_desc_t* desc, diff --git a/libopenbuenos/src/ob_internal.h b/libopenbuenos/src/ob_internal.h index a3b8bf0a..ca7614f0 100644 --- a/libopenbuenos/src/ob_internal.h +++ b/libopenbuenos/src/ob_internal.h @@ -23,7 +23,7 @@ namespace ob { constexpr uint32_t kDefaultGraphCacheCapacity = 512u; constexpr size_t kDefaultBufferPoolMaxBytes = 64u * 1024u * 1024u; constexpr size_t kDefaultBufferPoolMaxCount = 256u; -constexpr size_t kDefaultWeightCacheMaxEntries = 4096u; +constexpr size_t kDefaultWeightCacheMaxEntries = 16384u; constexpr uint32_t kDefaultTimeoutMs = 5000u; constexpr uint32_t kDefaultTileMaxM = 64u; constexpr uint32_t kDefaultTileMaxK = 2048u; @@ -195,6 +195,15 @@ struct PooledSlab { bool iova_mapped = false; }; +struct ExternalDmabufMap { + int dmabuf_fd = -1; + uint64_t offset = 0; + uint64_t size = 0; + uint64_t iova = 0; + uint32_t map_flags = 0; + uint32_t die_index = 0xffffffffu; +}; + struct CachedGraph { CacheKey key{}; ob_context* ctx = nullptr; @@ -306,11 +315,12 @@ bool device_attach_inflight_buffers(ob_context* ctx, ob_exec_handle_t handle, std::initializer_list bufs); -// Buffer pool helpers (implemented in ob_buffer_pool.cpp) +// Buffer pool & external DMA-BUF helpers (implemented in ob_buffer_pool.cpp) size_t buffer_slab_size(size_t requested); void buffer_retain(ob_buffer* buf); void buffer_destroy_slab(ob_context* ctx, PooledSlab* slab); void buffer_pool_clear(ob_context* ctx); +void ext_dmabuf_clear(ob_context* ctx); ob_status_t buffer_sync_begin_read(ob_buffer* buf); ob_status_t buffer_sync_end_read(ob_buffer* buf); ob_status_t buffer_sync_begin_write(ob_buffer* buf); @@ -752,6 +762,8 @@ struct ob_context { // Ordered LRU of free slabs + bucket index by alloc_size std::list pool_lru; std::unordered_map::iterator>> pool_buckets; + // External DMA-BUFs mapped into ctx->tpu_fd's grouped IOMMU domain via ob_dmabuf_map + std::unordered_map ext_dmabuf_maps; // Persistent graph LRU cache std::mutex cache_mu; @@ -796,9 +808,10 @@ struct ob_context { std::list weight_cache_lru; size_t weight_cache_bytes = 0; size_t weight_cache_peak_bytes = 0; - size_t weight_cache_max_bytes = 0; // lazily initialized (min(2048 MiB, MemAvailable/3) on Android) + size_t weight_cache_peak_entries = 0; + size_t weight_cache_max_bytes = 0; // lazily initialized (auto up to 1536 MiB with 512 MiB reserve) size_t weight_cache_default_max_entries = ob::kDefaultWeightCacheMaxEntries; - size_t weight_cache_max_entries = 0; // FD-safe cap (default 4096, env OPENBUENOS_WEIGHT_CACHE_ENTRIES) + size_t weight_cache_max_entries = 0; // FD-safe cap (default 16384, env OPENBUENOS_WEIGHT_CACHE_ENTRIES) size_t outlier_cache_bytes = 0; // Separate tracked total of cached FP32 outlier columns std::vector immutable_weight_regions; uint64_t next_immutable_region_gen = 1u; diff --git a/libopenbuenos/tests/openbuenos_host_test.cpp b/libopenbuenos/tests/openbuenos_host_test.cpp index a37555cd..516ea577 100644 --- a/libopenbuenos/tests/openbuenos_host_test.cpp +++ b/libopenbuenos/tests/openbuenos_host_test.cpp @@ -6251,6 +6251,283 @@ void test_roundtable_s1_state_machine_hardening() { std::printf("[PASS] test_roundtable_s1_state_machine_hardening (1-credit mock reclaim, try_wait retired_bufs, wait_all timeout/fatal/concurrent-harvest, EAGAIN bound, EINTR+frac-ms poll, seq wrap, wakelock concurrency)\n"); } +void test_zero_repack_weight_cache_and_prepack() { + std::vector synth_interp = make_synthetic_dive_interp(0x63u); + TempBinaryFile interp_file; + CHECK(interp_file.write(synth_interp.data(), synth_interp.size())); + + ::unsetenv("OPENBUENOS_WEIGHT_CACHE_MB"); + ::unsetenv("OPENBUENOS_WEIGHT_CACHE_ENTRIES"); + ::unsetenv("OPENBUENOS_PROFILE"); + + // 1. Prepack Q/K/V horizontally-fused Q4_0 batch + Q8_0 batch, then verify ZERO runtime misses/packing/evictions. + { + ob_config_t cfg = ob_config_default(); + cfg.mock_mode = 1; + cfg.max_inflight = 16u; + cfg.graph_cache_capacity = 256u; + ob_context_t* ctx = nullptr; + CHECK(ob_context_create(&cfg, &ctx) == OB_OK); + CHECK(ob_gemm_register_builtin_emitter(ctx, interp_file.path()) == OB_OK); + CHECK(ob_gemm_set_tile_limits(ctx, 16u, 512u, 128u) == OB_OK); + CHECK(ctx->num_threads == 1u); + + constexpr uint32_t M = 1u, K = 512u; + constexpr uint32_t Nq = 256u, Nk = 128u, Nv = 128u; + const uint32_t nb_k4 = K / ob_quant_block_elements(OB_QUANT_Q4_0); + const uint32_t nb_k8 = K / OB_QK8_0; + const size_t q4_row_bytes = static_cast(nb_k4) * sizeof(ob_block_q4_0_t); + const size_t q8_row_bytes = static_cast(nb_k8) * sizeof(ob_block_q8_0_t); + const size_t total_w_bytes = + static_cast(Nq + Nk + Nv) * q4_row_bytes + + static_cast(Nk) * q8_row_bytes; + + std::vector w_arena(total_w_bytes, 0u); + auto* wq = reinterpret_cast(w_arena.data()); + auto* wk = reinterpret_cast(w_arena.data() + static_cast(Nq) * q4_row_bytes); + auto* wv = reinterpret_cast(w_arena.data() + static_cast(Nq + Nk) * q4_row_bytes); + auto* w8 = reinterpret_cast(w_arena.data() + static_cast(Nq + Nk + Nv) * q4_row_bytes); + + auto fill_q4 = [&](ob_block_q4_0_t* dst, uint32_t n_rows, uint32_t seed) { + for (uint32_t n = 0; n < n_rows; ++n) { + for (uint32_t bi = 0; bi < nb_k4; ++bi) { + ob_block_q4_0_t& blk = dst[static_cast(n) * nb_k4 + bi]; + blk.d = fp32_to_fp16(0.02f + 0.003f * static_cast((n + bi + seed) & 7u)); + for (uint32_t j = 0; j < 16u; ++j) { + const uint8_t lo = static_cast((n + bi + j + seed) & 0xFu); + const uint8_t hi = static_cast((n * 3u + bi + j + seed) & 0xFu); + blk.qs[j] = static_cast(lo | (hi << 4u)); + } + } + } + }; + fill_q4(wq, Nq, 1u); + fill_q4(wk, Nk, 5u); + fill_q4(wv, Nv, 9u); + for (uint32_t n = 0; n < Nk; ++n) { + for (uint32_t bi = 0; bi < nb_k8; ++bi) { + ob_block_q8_0_t& blk = w8[static_cast(n) * nb_k8 + bi]; + blk.d = fp32_to_fp16(0.015f + 0.002f * static_cast((n + bi) & 3u)); + for (uint32_t j = 0; j < OB_QK8_0; ++j) { + blk.qs[j] = static_cast(static_cast((n * 5u + bi + j) % 61u) - 30); + } + } + } + + CHECK(ob_gemm_register_immutable_weights(ctx, w_arena.data(), w_arena.size(), 1u) == OB_OK); + + std::vector a_f32(M * K); + for (uint32_t k = 0; k < K; ++k) { + a_f32[k] = static_cast(static_cast((k * 13u + 7u) % 31u) - 15) * 0.04f; + } + std::vector cq(M * Nq, 0.0f), ck(M * Nk, 0.0f), cv(M * Nv, 0.0f), c8(M * Nk, 0.0f); + + ob_gemm_f32_quant_job_t jobs[3]{}; + jobs[0].b_nk = wq; + jobs[0].c_mn = cq.data(); + jobs[0].n_dim = Nq; + ob_gemm_f32_quant_job_set_type(&jobs[0], OB_QUANT_Q4_0); + jobs[1].b_nk = wk; + jobs[1].c_mn = ck.data(); + jobs[1].n_dim = Nk; + ob_gemm_f32_quant_job_set_type(&jobs[1], OB_QUANT_Q4_0); + jobs[2].b_nk = wv; + jobs[2].c_mn = cv.data(); + jobs[2].n_dim = Nv; + ob_gemm_f32_quant_job_set_type(&jobs[2], OB_QUANT_Q4_0); + + ob_prepack_stats_t pst1{}; + CHECK(ob_gemm_prepack_quant_batch(ctx, M, K, jobs, 3u, &pst1) == OB_OK); + CHECK(pst1.tiles_checked > 0u); + CHECK(pst1.tiles_prepacked == pst1.tiles_checked); + CHECK(pst1.tiles_already_cached == 0u); + CHECK(pst1.tiles_skipped_budget == 0u); + CHECK(pst1.graphs_precompiled > 0u); + CHECK(pst1.bytes_resident > 0u); + + ob_gemm_f32_quant_job_t j8{}; + j8.b_nk = w8; + j8.c_mn = c8.data(); + j8.n_dim = Nk; + ob_gemm_f32_quant_job_set_type(&j8, OB_QUANT_Q8_0); + ob_prepack_stats_t pst_q8{}; + CHECK(ob_gemm_prepack_quant_batch(ctx, M, K, &j8, 1u, &pst_q8) == OB_OK); + CHECK(pst_q8.tiles_prepacked > 0u); + CHECK(pst_q8.tiles_skipped_budget == 0u); + + // Repeat prepack -> idempotent cache hit, 0 new tiles, 0 new graphs. + ob_prepack_stats_t pst2{}; + CHECK(ob_gemm_prepack_quant_batch(ctx, M, K, jobs, 3u, &pst2) == OB_OK); + CHECK(pst2.tiles_prepacked == 0u); + CHECK(pst2.tiles_already_cached == pst1.tiles_checked); + CHECK(pst2.graphs_precompiled == 0u); + + // Inference MUST have 0 weight misses, 0 evictions, and 0 us weight packing! + CHECK(ob_context_set_profile(ctx, 1) == OB_OK); + ob_profile_stats_t prof_before{}; + CHECK(ob_context_get_profile(ctx, &prof_before) == OB_OK); + + ob_invoke_stats_t ist1{}; + CHECK(ob_gemm_matmul_f32_quant_batch(ctx, a_f32.data(), M, K, jobs, 3u, &ist1) == OB_OK); + ob_invoke_stats_t ist2{}; + CHECK(ob_gemm_matmul_f32_quant_batch(ctx, a_f32.data(), M, K, &j8, 1u, &ist2) == OB_OK); + + ob_profile_stats_t prof_after{}; + CHECK(ob_context_get_profile(ctx, &prof_after) == OB_OK); + CHECK(prof_after.weight_cache_misses == prof_before.weight_cache_misses); + CHECK(prof_after.weight_cache_evictions == prof_before.weight_cache_evictions); + CHECK(prof_after.weight_pack_us == prof_before.weight_pack_us); + CHECK(prof_after.weight_cache_hits > prof_before.weight_cache_hits); + + // Numerical sanity vs CPU dequant reference for Q job. + std::vector ref_row(K); + for (uint32_t n = 0; n < 8u; ++n) { + CHECK(ob_quant_dequantize_row_f32(OB_QUANT_Q4_0, + reinterpret_cast(wq) + n * q4_row_bytes, + K, ref_row.data()) == OB_OK); + double acc = 0.0; + for (uint32_t k = 0; k < K; ++k) acc += static_cast(a_f32[k]) * ref_row[k]; + CHECK(std::fabs(static_cast(cq[n]) - acc) < 1e-2); + } + + CHECK(ob_gemm_unregister_immutable_weights(ctx, w_arena.data(), w_arena.size()) == OB_OK); + ob_context_destroy(ctx); + } + + // 2. Budget cap stops without evicting already-resident prepacked tiles, and honors simulated MemAvailable/3. + { + ::unsetenv("OPENBUENOS_WEIGHT_CACHE_MB"); + ob_config_t cfg = ob_config_default(); + cfg.mock_mode = 1; + ob_context_t* ctx = nullptr; + CHECK(ob_context_create(&cfg, &ctx) == OB_OK); + CHECK(ob_gemm_register_builtin_emitter(ctx, interp_file.path()) == OB_OK); + CHECK(ob_gemm_set_tile_limits(ctx, 16u, 512u, 128u) == OB_OK); + ctx->simulated_mem_available_set = true; + ctx->simulated_mem_available_bytes = 3ULL * 1024u * 1024u; // auto cap = MemAvailable/3 = 1 MiB + + constexpr uint32_t K = 1024u, N = 2048u; // 32 unique 64 KiB tiles = 2 MiB > 1 MiB cap + const uint32_t nb_k = K / ob_quant_block_elements(OB_QUANT_Q4_0); + const size_t n_blocks = static_cast(N) * nb_k; + std::vector big_w(n_blocks); + for (uint32_t n = 0; n < N; ++n) { + for (uint32_t bi = 0; bi < nb_k; ++bi) { + ob_block_q4_0_t& blk = big_w[static_cast(n) * nb_k + bi]; + const uint32_t h = (n * nb_k + bi) * 2654435761u; + blk.d = fp32_to_fp16(0.01f + 0.001f * static_cast((h >> 4) & 31u)); + for (uint32_t j = 0; j < 16u; ++j) { + blk.qs[j] = static_cast((h >> (j & 15u)) ^ (j * 29u + bi * 17u + n)); + } + } + } + ob_gemm_f32_quant_job_t bjob{}; + bjob.b_nk = big_w.data(); + bjob.n_dim = N; + ob_gemm_f32_quant_job_set_type(&bjob, OB_QUANT_Q4_0); + + ob_prepack_stats_t bpst{}; + CHECK(ob_gemm_prepack_quant_batch(ctx, 1u, K, &bjob, 1u, &bpst) == OB_OK); + CHECK(bpst.tiles_prepacked > 0u); + CHECK(bpst.tiles_skipped_budget > 0u); + CHECK(ctx->weight_cache_evictions == 0u); + CHECK(ctx->weight_cache_bytes <= ctx->weight_cache_max_bytes); + CHECK(ctx->weight_cache_max_bytes == 1u * 1024u * 1024u); + + ob_context_destroy(ctx); + } + + // 3. Budget guard & FD-entry cap: + // - auto uses LMKD-safe MemAvailable/3 (2200 MiB -> ~733 MiB) + // - explicit OPENBUENOS_WEIGHT_CACHE_MB=1200 is honored + // - oversized explicit OPENBUENOS_WEIGHT_CACHE_MB=2048 honors 512 MiB headroom reserve (2200 -> 1688 MiB) + // - default kDefaultWeightCacheMaxEntries = 16384 and OPENBUENOS_WEIGHT_CACHE_ENTRIES honors up to 32768 + { + CHECK(ob::kDefaultWeightCacheMaxEntries == 16384u); + + ob_config_t cfg = ob_config_default(); + cfg.mock_mode = 1; + ob_context_t* ctx = nullptr; + CHECK(ob_context_create(&cfg, &ctx) == OB_OK); + ctx->simulated_mem_available_set = true; + ctx->mock_mode = false; + + ::unsetenv("OPENBUENOS_WEIGHT_CACHE_MB"); + ctx->simulated_mem_available_bytes = 2200ULL * 1024u * 1024u; + CHECK(ob::compute_weight_cache_budget_bytes(ctx) == (2200ULL * 1024u * 1024u) / 3u); + + ::setenv("OPENBUENOS_WEIGHT_CACHE_MB", "1200", 1); + CHECK(ob::compute_weight_cache_budget_bytes(ctx) == 1200ULL * 1024u * 1024u); + + ::setenv("OPENBUENOS_WEIGHT_CACHE_MB", "2048", 1); + CHECK(ob::compute_weight_cache_budget_bytes(ctx) == (2200ULL - 512ULL) * 1024u * 1024u); + + ::unsetenv("OPENBUENOS_WEIGHT_CACHE_MB"); + ctx->simulated_mem_available_set = false; + ctx->simulated_mem_available_bytes = 0u; + ctx->mock_mode = true; + CHECK(ob_gemm_register_builtin_emitter(ctx, interp_file.path()) == OB_OK); + uint8_t dummy_q4[18]{}; + ob_gemm_f32_quant_job_t ejob{}; + ejob.b_nk = dummy_q4; + ejob.n_dim = 1u; + ob_gemm_f32_quant_job_set_type(&ejob, OB_QUANT_Q4_0); + ob_prepack_stats_t epst{}; + ::unsetenv("OPENBUENOS_WEIGHT_CACHE_ENTRIES"); + ctx->weight_cache_max_entries = 0u; + CHECK(ob_gemm_prepack_quant_batch(ctx, 1u, 32u, &ejob, 1u, &epst) == OB_OK); + CHECK(ctx->weight_cache_max_entries == ctx->weight_cache_default_max_entries); + + ::setenv("OPENBUENOS_WEIGHT_CACHE_ENTRIES", "32768", 1); + ctx->weight_cache_max_entries = 0u; + CHECK(ob_gemm_prepack_quant_batch(ctx, 1u, 32u, &ejob, 1u, &epst) == OB_OK); + CHECK(ctx->weight_cache_max_entries == 32768u); + + ::unsetenv("OPENBUENOS_WEIGHT_CACHE_ENTRIES"); + ob_context_destroy(ctx); + } + + std::printf("[PASS] test_zero_repack_weight_cache_and_prepack (Q4_0/Q8_0 load prepack -> 0 runtime misses/pack/evict, strict budget stop without eviction)\n"); +} + +void test_external_dmabuf_map_unmap() { + ob_config_t cfg = ob_config_default(); + cfg.mock_mode = 1; + ob_context_t* ctx = nullptr; + CHECK(ob_context_create(&cfg, &ctx) == OB_OK); + + uint64_t sentinel_iova = 123u; + CHECK(ob_dmabuf_map(nullptr, 3, 0u, 4096u, OB_BUF_BIDIRECTIONAL, &sentinel_iova) == + OB_ERR_INVALID_ARG); + CHECK(sentinel_iova == 0u); + CHECK(ob_dmabuf_map(ctx, -1, 0u, 4096u, OB_BUF_BIDIRECTIONAL, &sentinel_iova) == + OB_ERR_INVALID_ARG); + CHECK(ob_dmabuf_map(ctx, 3, 0u, 0u, OB_BUF_BIDIRECTIONAL, &sentinel_iova) == OB_ERR_INVALID_ARG); + CHECK(ob_dmabuf_map(ctx, 3, 0u, 4096u, OB_BUF_BIDIRECTIONAL, nullptr) == OB_ERR_INVALID_ARG); + CHECK(ob_dmabuf_map(ctx, 3, UINT64_MAX - 100u, 4096u, OB_BUF_BIDIRECTIONAL, &sentinel_iova) == + OB_ERR_INVALID_ARG); + CHECK(ob_dmabuf_unmap(nullptr, 0x100000000ULL) == OB_ERR_INVALID_ARG); + CHECK(ob_dmabuf_unmap(ctx, 0u) == OB_ERR_INVALID_ARG); + CHECK(ob_dmabuf_unmap(ctx, 0xdeadbeefULL) == OB_ERR_NOT_FOUND); + + uint64_t iova1 = 0u; + uint64_t iova2 = 0u; + CHECK(ob_dmabuf_map(ctx, 11, 0u, 4096u, OB_BUF_TO_DEVICE, &iova1) == OB_OK); + CHECK(iova1 != 0u); + CHECK((iova1 & 4095ULL) == 0u); + CHECK(ob_dmabuf_map(ctx, 12, 128u, 8192u, OB_BUF_FROM_DEVICE, &iova2) == OB_OK); + CHECK(iova2 != 0u && iova2 > iova1); + CHECK((iova2 & 4095ULL) == 0u); + + CHECK(ctx->ext_dmabuf_maps.size() == 2u); + CHECK(ob_dmabuf_unmap(ctx, iova1) == OB_OK); + CHECK(ob_dmabuf_unmap(ctx, iova1) == OB_ERR_NOT_FOUND); + CHECK(ctx->ext_dmabuf_maps.size() == 1u); + + // Leave iova2 active to verify ob_context_destroy clears ext_dmabuf_maps cleanly. + ob_context_destroy(ctx); + std::printf("[PASS] test_external_dmabuf_map_unmap\n"); +} + } // namespace int main() { @@ -6266,6 +6543,7 @@ int main() { "OPENBUENOS_SWIGLU_MAX_CREST", "OPENBUENOS_STRICT_WEIGHT_HASH", "OPENBUENOS_WEIGHT_CACHE_MB", + "OPENBUENOS_WEIGHT_CACHE_ENTRIES", "OPENBUENOS_PARAM_SWAP_SLOTS", "OPENBUENOS_SPIN_US", "OPENBUENOS_THREADS", @@ -6304,9 +6582,11 @@ int main() { test_dive_interp_xdg_probe(); test_freetile_buenos_wire_parity_and_fallback(); test_roundtable_s1_state_machine_hardening(); + test_zero_repack_weight_cache_and_prepack(); + test_external_dmabuf_map_unmap(); if (g_failures == 0) { - std::printf("ALL LIBOPENBUENOS HOST TESTS PASSED (25/25 suites)\n"); + std::printf("ALL LIBOPENBUENOS HOST TESTS PASSED (27/27 suites)\n"); return 0; } std::fprintf(stderr, "LIBOPENBUENOS HOST TESTS FAILED (%d failures)\n", g_failures); diff --git a/llama-cpp-edgetpu/ggml-edgetpu.cpp b/llama-cpp-edgetpu/ggml-edgetpu.cpp index 663e2b4a..1e38fdb2 100644 --- a/llama-cpp-edgetpu/ggml-edgetpu.cpp +++ b/llama-cpp-edgetpu/ggml-edgetpu.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #if defined(__linux__) || defined(__ANDROID__) #include @@ -31,10 +32,13 @@ namespace { -constexpr size_t EDGETPU_BUFFER_ALIGNMENT = 64; -constexpr uint32_t EDGETPU_DEFAULT_CACHE_CAP = 2048u; -constexpr uint32_t EDGETPU_DEFAULT_POOL_MAX_BYTES = 128u * 1024u * 1024u; -constexpr int64_t EDGETPU_DEFAULT_GLU_MAX_M = 64; +constexpr size_t EDGETPU_BUFFER_ALIGNMENT = 64; +constexpr uint32_t EDGETPU_DEFAULT_CACHE_CAP = 2048u; +constexpr uint32_t EDGETPU_DEFAULT_POOL_MAX_BYTES = 128u * 1024u * 1024u; +constexpr int64_t EDGETPU_DEFAULT_GLU_MAX_M = 64; +constexpr uint64_t EDGETPU_DEFAULT_MAX_N = 65536ULL; +constexpr uint64_t EDGETPU_DEFAULT_MIN_TILE_DIM = 128ULL; +constexpr uint64_t EDGETPU_DEFAULT_MUL_MAT_ID_MAX_MB = 64ULL; struct edgetpu_env_config { bool mock_mode = false; @@ -44,8 +48,14 @@ struct edgetpu_env_config { bool fuse_swiglu = true; bool enable_rope = true; bool enable_glu = true; + bool prepack_at_load = true; int64_t glu_max_m = EDGETPU_DEFAULT_GLU_MAX_M; uint64_t min_elements = 0; + uint64_t max_m = 0; + uint64_t max_n = EDGETPU_DEFAULT_MAX_N; + uint64_t min_tile_dim = EDGETPU_DEFAULT_MIN_TILE_DIM; + int mul_mat_id_mode = -1; // -1=auto (<= mul_mat_id_max_bytes), 0=off, 1=force on + uint64_t mul_mat_id_max_bytes = EDGETPU_DEFAULT_MUL_MAT_ID_MAX_MB * 1024ULL * 1024ULL; uint32_t cache_cap = EDGETPU_DEFAULT_CACHE_CAP; uint32_t pool_max_bytes = EDGETPU_DEFAULT_POOL_MAX_BYTES; uint32_t tile_max_m = 0; // 0 -> inherit libopenbuenos tuned silicon defaults @@ -121,6 +131,53 @@ static edgetpu_env_config load_env_config() { cfg.min_elements = static_cast(parsed); } } + if (const char * v = std::getenv("OPENBUENOS_PREPACK_AT_LOAD")) { + if (v[0] != '\0') { + cfg.prepack_at_load = (std::atoi(v) != 0); + } + } + if (const char * v = std::getenv("OPENBUENOS_EDGETPU_MAX_N")) { + if (v[0] != '\0') { + const long long parsed = std::atoll(v); + if (parsed >= 0) { + cfg.max_n = static_cast(parsed); + } + } + } + if (const char * v = std::getenv("OPENBUENOS_EDGETPU_MAX_M")) { + if (v[0] != '\0') { + const long long parsed = std::atoll(v); + if (parsed >= 0) { + cfg.max_m = static_cast(parsed); + } + } + } + if (const char * v = std::getenv("OPENBUENOS_MIN_TILE_DIM")) { + if (v[0] != '\0') { + const long long parsed = std::atoll(v); + if (parsed >= 0) { + cfg.min_tile_dim = static_cast(parsed); + } + } + } + if (const char * v = std::getenv("OPENBUENOS_EDGETPU_MUL_MAT_ID")) { + if (v[0] != '\0') { + if (std::strcmp(v, "auto") == 0 || std::strcmp(v, "AUTO") == 0) { + cfg.mul_mat_id_mode = -1; + } else { + const int parsed = std::atoi(v); + cfg.mul_mat_id_mode = (parsed < 0) ? -1 : ((parsed == 0) ? 0 : 1); + } + } + } + if (const char * v = std::getenv("OPENBUENOS_EDGETPU_MUL_MAT_ID_MAX_MB")) { + if (v[0] != '\0') { + const long long parsed = std::atoll(v); + if (parsed >= 0) { + cfg.mul_mat_id_max_bytes = static_cast(parsed) * 1024ULL * 1024ULL; + } + } + } if (const char * v = std::getenv("OPENBUENOS_CACHE_CAP")) { const long long parsed = std::atoll(v); if (parsed > 0 && parsed <= 1048576LL) { @@ -175,6 +232,12 @@ static edgetpu_env_config load_env_config() { struct edgetpu_hot_env_cache { std::atomic initialized{false}; std::atomic min_elements{0}; + std::atomic max_m{0}; + std::atomic max_n{EDGETPU_DEFAULT_MAX_N}; + std::atomic min_tile_dim{EDGETPU_DEFAULT_MIN_TILE_DIM}; + std::atomic mul_mat_id_mode{-1}; + std::atomic mul_mat_id_max_bytes{EDGETPU_DEFAULT_MUL_MAT_ID_MAX_MB * 1024ULL * 1024ULL}; + std::atomic prepack_at_load{true}; std::atomic packed_q8{false}; std::atomic verbose{0}; std::atomic enable_rope{true}; @@ -184,6 +247,12 @@ struct edgetpu_hot_env_cache { void store(const edgetpu_env_config & cfg) { min_elements.store(cfg.min_elements, std::memory_order_relaxed); + max_m.store(cfg.max_m, std::memory_order_relaxed); + max_n.store(cfg.max_n, std::memory_order_relaxed); + min_tile_dim.store(cfg.min_tile_dim, std::memory_order_relaxed); + mul_mat_id_mode.store(cfg.mul_mat_id_mode, std::memory_order_relaxed); + mul_mat_id_max_bytes.store(cfg.mul_mat_id_max_bytes, std::memory_order_relaxed); + prepack_at_load.store(cfg.prepack_at_load, std::memory_order_relaxed); packed_q8.store(cfg.packed_q8, std::memory_order_relaxed); verbose.store(cfg.verbose, std::memory_order_relaxed); enable_rope.store(cfg.enable_rope, std::memory_order_relaxed); @@ -335,10 +404,13 @@ static std::shared_ptr repack_q8_0_to_buenos(const block_q8_0 // EDGETPU Backend Buffer (64B-aligned host-accessible + Q8_0 repack cache) // ========================================================================= +static std::atomic g_next_buffer_version{1}; + struct ggml_backend_edgetpu_buffer_context { - void * data = nullptr; - size_t size = 0; - bool owns_memory = false; + void * data = nullptr; + size_t size = 0; + bool owns_memory = false; + std::atomic weight_version{g_next_buffer_version.fetch_add(1, std::memory_order_relaxed)}; std::atomic has_packed_entries{false}; std::mutex cache_mu; @@ -351,6 +423,24 @@ struct ggml_backend_edgetpu_buffer_context { } }; +static void invalidate_edgetpu_buffer_cache(ggml_backend_edgetpu_buffer_context * ctx, + const void * tensor_data) { + ctx->weight_version.store(g_next_buffer_version.fetch_add(1, std::memory_order_relaxed), + std::memory_order_release); + if (ctx->has_packed_entries.load(std::memory_order_acquire)) { + std::lock_guard lock(ctx->cache_mu); + if (tensor_data) { + ctx->packed_q8_cache.erase(tensor_data); + if (ctx->packed_q8_cache.empty()) { + ctx->has_packed_entries.store(false, std::memory_order_release); + } + } else { + ctx->packed_q8_cache.clear(); + ctx->has_packed_entries.store(false, std::memory_order_release); + } + } +} + static bool is_edgetpu_buffer(ggml_backend_buffer_t buffer) { return buffer != nullptr && buffer->buft == ggml_backend_edgetpu_buffer_type(); } @@ -372,14 +462,7 @@ static void ggml_backend_edgetpu_buffer_memset_tensor(ggml_backend_buffer_t buff size_t size) { auto * ctx = static_cast(buffer->context); std::memset(static_cast(tensor->data) + offset, value, size); - - if (ctx->has_packed_entries.load(std::memory_order_acquire)) { - std::lock_guard lock(ctx->cache_mu); - ctx->packed_q8_cache.erase(tensor->data); - if (ctx->packed_q8_cache.empty()) { - ctx->has_packed_entries.store(false, std::memory_order_release); - } - } + invalidate_edgetpu_buffer_cache(ctx, tensor->data); } static void ggml_backend_edgetpu_buffer_set_tensor(ggml_backend_buffer_t buffer, @@ -390,14 +473,8 @@ static void ggml_backend_edgetpu_buffer_set_tensor(ggml_backend_buffer_t buffer, auto * ctx = static_cast(buffer->context); std::memcpy(static_cast(tensor->data) + offset, data, size); - // Invalidate any stale repacked weight for this tensor address (lock-free skip in default zero-dup mode). - if (ctx->has_packed_entries.load(std::memory_order_acquire)) { - std::lock_guard lock(ctx->cache_mu); - ctx->packed_q8_cache.erase(tensor->data); - if (ctx->packed_q8_cache.empty()) { - ctx->has_packed_entries.store(false, std::memory_order_release); - } - } + // Bump immutable weight version and invalidate any stale repacked weight for this tensor address. + invalidate_edgetpu_buffer_cache(ctx, tensor->data); // Strictly zero-dup single-copy residency by default: only repack host weights if explicitly opted in via OPENBUENOS_PACKED_Q8=1. g_hot_env.ensure_initialized(); @@ -452,20 +529,12 @@ static void ggml_backend_edgetpu_buffer_clear(ggml_backend_buffer_t buffer, uint if (ctx->data && ctx->size > 0) { std::memset(ctx->data, value, ctx->size); } - if (ctx->has_packed_entries.load(std::memory_order_acquire)) { - std::lock_guard lock(ctx->cache_mu); - ctx->packed_q8_cache.clear(); - ctx->has_packed_entries.store(false, std::memory_order_release); - } + invalidate_edgetpu_buffer_cache(ctx, nullptr); } static void ggml_backend_edgetpu_buffer_reset(ggml_backend_buffer_t buffer) { auto * ctx = static_cast(buffer->context); - if (ctx->has_packed_entries.load(std::memory_order_acquire)) { - std::lock_guard lock(ctx->cache_mu); - ctx->packed_q8_cache.clear(); - ctx->has_packed_entries.store(false, std::memory_order_release); - } + invalidate_edgetpu_buffer_cache(ctx, nullptr); } static const struct ggml_backend_buffer_i ggml_backend_edgetpu_buffer_i = { @@ -597,6 +666,16 @@ struct ggml_backend_edgetpu_context { std::vector moe_in_f32; std::vector moe_out_f32; + struct registered_weight_region { + const void * base = nullptr; + size_t size = 0; + uint64_t version = 0; + }; + + // Tracks immutable weight buffers registered with libopenbuenos + prepacked (group, M) keys. + std::unordered_map registered_weight_buffers; + std::unordered_set prepacked_group_keys; + // Fallback repack cache for weights residing in non-EDGETPU host buffers (only when OPENBUENOS_PACKED_Q8=1) std::mutex fallback_cache_mu; std::unordered_map> fallback_packed_cache; @@ -620,6 +699,11 @@ struct ggml_backend_edgetpu_context { uint64_t total_rope_ops = 0; uint64_t total_glu_ops = 0; uint64_t total_swiglu_fused = 0; + uint64_t total_prepack_calls = 0; + uint64_t total_prepack_tiles = 0; + uint64_t total_prepack_cached = 0; + uint64_t total_prepack_skipped = 0; + uint64_t total_prepack_graphs = 0; ~ggml_backend_edgetpu_context() { if (ob_ctx) { @@ -648,6 +732,7 @@ struct ggml_backend_edgetpu_context { "ggml-edgetpu: summary mock=%d freetile=%d freetile_emits=%llu freetile_fallbacks=%llu " "evals=%llu calls=%llu mmid_calls=%llu slices=%llu emitter_slices=%llu cpu_fallback_slices=%llu " "batched_groups=%llu batched_ops=%llu batched_3=%llu batched_2=%llu swiglu_fused=%llu bias_adds=%llu rope_ops=%llu glu_ops=%llu " + "prepack_calls=%llu prepack_tiles=%llu prepack_cached=%llu prepack_skipped=%llu prepack_graphs=%llu reg_bufs=%zu " "tiles=%llu tile_hits=%llu hw_us=%llu wall_us=%llu " "cache_entries=%zu cache_hits=%llu cache_misses=%llu cache_evictions=%llu cache_hit_rate=%.2f%% " "pool_bytes=%zu pool_count=%zu pool_hits=%llu pool_misses=%llu\n", @@ -669,6 +754,12 @@ struct ggml_backend_edgetpu_context { static_cast(total_bias_adds), static_cast(total_rope_ops), static_cast(total_glu_ops), + static_cast(total_prepack_calls), + static_cast(total_prepack_tiles), + static_cast(total_prepack_cached), + static_cast(total_prepack_skipped), + static_cast(total_prepack_graphs), + registered_weight_buffers.size(), static_cast(total_tiles_dispatched), static_cast(total_tile_cache_hits), static_cast(total_hw_us), @@ -683,6 +774,10 @@ struct ggml_backend_edgetpu_context { static_cast(pool_hits), static_cast(pool_misses)); } + for (const auto & kv : registered_weight_buffers) { + ob_gemm_unregister_immutable_weights(ob_ctx, kv.second.base, kv.second.size); + } + registered_weight_buffers.clear(); ob_context_destroy(ob_ctx); ob_ctx = nullptr; } @@ -1807,21 +1902,34 @@ static bool is_view_or_noop(const struct ggml_tensor * t) { t->op == GGML_OP_TRANSPOSE; } +struct fused_swiglu_match { + struct ggml_tensor * gate_mm = nullptr; + struct ggml_tensor * up_mm = nullptr; + struct ggml_tensor * down_mm = nullptr; + const struct ggml_tensor * x = nullptr; + uint32_t M = 0; + uint32_t K = 0; + uint32_t H = 0; + uint32_t N = 0; + ob_quant_type_t gate_qt = OB_QUANT_Q8_0; + ob_quant_type_t up_qt = OB_QUANT_Q8_0; + ob_quant_type_t down_qt = OB_QUANT_Q8_0; + int end_idx = -1; +}; + // Attempts to match a whole-block SwiGLU FFN starting at cgraph->nodes[start_idx]: // Pattern A (GGML_OP_GLU): MUL_MAT(gate, x) + MUL_MAT(up, x) -> GLU(SWIGLU) -> MUL_MAT(down) // Pattern B (unfused): MUL_MAT(gate, x) -> SILU -> MUL(up) -> MUL_MAT(down) -// On match, executes via ob_gemm_swiglu_f32_quant (in-SRAM chained on Tensor G5) and stores -// the final consumed node index in *out_end_idx, returning 1 (0 = no match, -1 = error). -static int try_compute_fused_swiglu(ggml_backend_edgetpu_context * ctx, - struct ggml_cgraph * cgraph, - int start_idx, - int * out_end_idx) { - if (!ctx->env.fuse_swiglu || ctx->env.packed_q8) { - return 0; +static bool match_fused_swiglu(const ggml_backend_edgetpu_context * ctx, + struct ggml_cgraph * cgraph, + int start_idx, + fused_swiglu_match * out) { + if (!ctx->env.fuse_swiglu || ctx->env.packed_q8 || !out) { + return false; } struct ggml_tensor * n0 = cgraph->nodes[start_idx]; if (!is_fusible_swiglu_mul_mat(n0)) { - return 0; + return false; } // Collect the next up to 5 compute ops starting from start_idx. @@ -1838,7 +1946,7 @@ static int try_compute_fused_swiglu(ggml_backend_edgetpu_context * ctx, n_comp++; } if (n_comp < 4) { - return 0; + return false; } struct ggml_tensor * gate_mm = nullptr; @@ -1928,14 +2036,14 @@ static int try_compute_fused_swiglu(ggml_backend_edgetpu_context * ctx, } if (!down_mm || !gate_mm || !up_mm) { - return 0; + return false; } // Validate all 3 projections & shared activation shapes. if (!is_fusible_swiglu_mul_mat(gate_mm) || !is_fusible_swiglu_mul_mat(up_mm) || !is_fusible_swiglu_mul_mat(down_mm)) { - return 0; + return false; } const struct ggml_tensor * x = gate_mm->src[1]; @@ -1947,7 +2055,7 @@ static int try_compute_fused_swiglu(ggml_backend_edgetpu_context * ctx, up_mm->src[1]->ne[1] != x->ne[1] || x->ne[2] != 1 || x->ne[3] != 1 || up_mm->src[1]->ne[2] != 1 || up_mm->src[1]->ne[3] != 1) { - return 0; + return false; } const uint32_t M = static_cast(x->ne[1]); @@ -1960,13 +2068,13 @@ static int try_compute_fused_swiglu(ggml_backend_edgetpu_context * ctx, down_mm->src[0]->ne[0] != static_cast(H) || down_mm->src[1]->ne[0] != static_cast(H) || down_mm->src[1]->ne[1] != static_cast(M)) { - return 0; + return false; } if ((K % static_cast(ggml_blck_size(gate_mm->src[0]->type))) != 0u || (K % static_cast(ggml_blck_size(up_mm->src[0]->type))) != 0u || (H % static_cast(ggml_blck_size(down_mm->src[0]->type))) != 0u || M == 0u || N == 0u) { - return 0; + return false; } // Ensure no intermediate tensor is a graph output or consumed outside [start_idx, end_idx]. @@ -1974,16 +2082,16 @@ static int try_compute_fused_swiglu(ggml_backend_edgetpu_context * ctx, // from this split's cgraph->nodes. if (!cgraph->use_counts || cgraph->visited_hash_set.size == 0 || !cgraph->visited_hash_set.used || !cgraph->visited_hash_set.keys) { - return 0; + return false; } for (int k = start_idx; k < end_idx; ++k) { const struct ggml_tensor * t = cgraph->nodes[k]; if (!t || (t->flags & GGML_TENSOR_FLAG_OUTPUT) != 0) { - return 0; + return false; } const size_t hpos = ggml_hash_find(&cgraph->visited_hash_set, t); if (hpos == GGML_HASHSET_FULL || !ggml_bitset_get(cgraph->visited_hash_set.used, hpos)) { - return 0; + return false; } int32_t internal_uses = 0; for (int j = start_idx; j <= end_idx; ++j) { @@ -1998,7 +2106,7 @@ static int try_compute_fused_swiglu(ggml_backend_edgetpu_context * ctx, } } if (internal_uses <= 0 || cgraph->use_counts[hpos] != internal_uses) { - return 0; + return false; } } auto tensor_aliases_inter = [&](const struct ggml_tensor * t) -> bool { @@ -2022,12 +2130,12 @@ static int try_compute_fused_swiglu(ggml_backend_edgetpu_context * ctx, continue; } if (tensor_aliases_inter(other)) { - return 0; + return false; } for (int p = 0; p < n_inter; ++p) { for (int s = 0; s < GGML_MAX_SRC; ++s) { if (other->src[s] && unwrap_view_src(other->src[s]) == inter[p]) { - return 0; + return false; } } } @@ -2035,7 +2143,7 @@ static int try_compute_fused_swiglu(ggml_backend_edgetpu_context * ctx, if (cgraph->leafs) { for (int k = 0; k < cgraph->n_leafs; ++k) { if (tensor_aliases_inter(cgraph->leafs[k])) { - return 0; + return false; } } } @@ -2055,19 +2163,8 @@ static int try_compute_fused_swiglu(ggml_backend_edgetpu_context * ctx, continue; } if (tensor_aliases_inter(ht)) { - return 0; - } - } - - // Protect input activation if down_mm's output buffer aliases x. - const float * a_ptr = reinterpret_cast(x->data); - if (tensors_overlap(down_mm, x)) { - const size_t elems = static_cast(M) * static_cast(K); - if (ctx->f32_a.size() < elems) { - ctx->f32_a.resize(elems); + return false; } - std::memcpy(ctx->f32_a.data(), a_ptr, elems * sizeof(float)); - a_ptr = ctx->f32_a.data(); } ob_quant_type_t gate_qt = OB_QUANT_Q8_0; @@ -2076,25 +2173,60 @@ static int try_compute_fused_swiglu(ggml_backend_edgetpu_context * ctx, if (!ggml_type_to_ob_quant(gate_mm->src[0]->type, &gate_qt) || !ggml_type_to_ob_quant(up_mm->src[0]->type, &up_qt) || !ggml_type_to_ob_quant(down_mm->src[0]->type, &down_qt)) { + return false; + } + + out->gate_mm = gate_mm; + out->up_mm = up_mm; + out->down_mm = down_mm; + out->x = x; + out->M = M; + out->K = K; + out->H = H; + out->N = N; + out->gate_qt = gate_qt; + out->up_qt = up_qt; + out->down_qt = down_qt; + out->end_idx = end_idx; + return true; +} + +static int try_compute_fused_swiglu(ggml_backend_edgetpu_context * ctx, + struct ggml_cgraph * cgraph, + int start_idx, + int * out_end_idx) { + fused_swiglu_match m; + if (!match_fused_swiglu(ctx, cgraph, start_idx, &m)) { return 0; } + // Protect input activation if down_mm's output buffer aliases x. + const float * a_ptr = reinterpret_cast(m.x->data); + if (tensors_overlap(m.down_mm, m.x)) { + const size_t elems = static_cast(m.M) * static_cast(m.K); + if (ctx->f32_a.size() < elems) { + ctx->f32_a.resize(elems); + } + std::memcpy(ctx->f32_a.data(), a_ptr, elems * sizeof(float)); + a_ptr = ctx->f32_a.data(); + } + ob_gemm_swiglu_quant_desc_t sdesc {}; - sdesc.w_gate_hk = gate_mm->src[0]->data; - sdesc.w_up_hk = up_mm->src[0]->data; - sdesc.w_down_nh = down_mm->src[0]->data; - sdesc.m_dim = M; - sdesc.k_dim = K; - sdesc.h_dim = H; - sdesc.n_dim = N; - ob_gemm_swiglu_quant_desc_set_types(&sdesc, gate_qt, up_qt, down_qt); + sdesc.w_gate_hk = m.gate_mm->src[0]->data; + sdesc.w_up_hk = m.up_mm->src[0]->data; + sdesc.w_down_nh = m.down_mm->src[0]->data; + sdesc.m_dim = m.M; + sdesc.k_dim = m.K; + sdesc.h_dim = m.H; + sdesc.n_dim = m.N; + ob_gemm_swiglu_quant_desc_set_types(&sdesc, m.gate_qt, m.up_qt, m.down_qt); ob_invoke_stats_t sstats {}; const ob_status_t sst = ob_gemm_swiglu_f32_quant( - ctx->ob_ctx, a_ptr, &sdesc, reinterpret_cast(down_mm->data), &sstats); + ctx->ob_ctx, a_ptr, &sdesc, reinterpret_cast(m.down_mm->data), &sstats); if (sst != OB_OK) { GGML_LOG_ERROR("ggml-edgetpu: ob_gemm_swiglu_f32_quant(M=%u,K=%u,H=%u,N=%u) failed: %s\n", - M, K, H, N, ob_status_string(sst)); + m.M, m.K, m.H, m.N, ob_status_string(sst)); return -1; } @@ -2112,18 +2244,393 @@ static int try_compute_fused_swiglu(ggml_backend_edgetpu_context * ctx, ctx->total_cpu_fallback_slices += 3; if (!ctx->env.mock_mode && ctx->total_cpu_fallback_slices <= 8) { GGML_LOG_WARN("ggml-edgetpu: CPU fallback in fused SwiGLU(M=%u,K=%u,H=%u,N=%u,flags=0x%x)\n", - M, K, H, N, static_cast(sstats.flags)); + m.M, m.K, m.H, m.N, static_cast(sstats.flags)); } } - *out_end_idx = end_idx; + *out_end_idx = m.end_idx; return 1; } +static inline uint64_t edgetpu_mix64(uint64_t x) { + x += UINT64_C(0x9e3779b97f4a7c15); + x = (x ^ (x >> 30)) * UINT64_C(0xbf58476d1ce4e5b9); + x = (x ^ (x >> 27)) * UINT64_C(0x94d049bb133111eb); + return x ^ (x >> 31); +} + +static uint64_t ensure_weight_buffer_registered(ggml_backend_edgetpu_context * ctx, + const struct ggml_tensor * weight_tensor) { + if (!ctx || !ctx->ob_ctx || !weight_tensor) { + return 0; + } + const struct ggml_tensor * w_base = unwrap_view_src(weight_tensor); + ggml_backend_buffer_t buf = (w_base && w_base->buffer) ? w_base->buffer : weight_tensor->buffer; + if (!buf || buf->usage != GGML_BACKEND_BUFFER_USAGE_WEIGHTS) { + return 0; + } + + uint64_t version = 0; + if (is_edgetpu_buffer(buf)) { + const auto * bctx = static_cast(buf->context); + if (!bctx) { + return 0; + } + version = bctx->weight_version.load(std::memory_order_acquire); + } else if (buf->buft && buf->buft->iface.get_name) { + const char * bname = buf->buft->iface.get_name(buf->buft); + if (bname && std::strcmp(bname, "CPU_Mapped") == 0) { + version = 1; + } else { + return 0; + } + } else { + return 0; + } + + const void * base = ggml_backend_buffer_get_base(buf); + const size_t size = ggml_backend_buffer_get_size(buf); + if (!base || size == 0 || version == 0) { + return 0; + } + + auto it = ctx->registered_weight_buffers.find(base); + if (it != ctx->registered_weight_buffers.end() && + it->second.size == size && + it->second.version == version) { + return version; + } + + if (ob_gemm_register_immutable_weights(ctx->ob_ctx, base, size, version) != OB_OK) { + return 0; + } + ctx->registered_weight_buffers[base] = { base, size, version }; + return version; +} + +static void prepack_quant_jobs_once(ggml_backend_edgetpu_context * ctx, + uint32_t m_hint, + uint32_t k_dim, + const ob_gemm_f32_quant_job_t * jobs, + const uint64_t * versions, + uint32_t num_jobs, + ob_prepack_stats_t * eval_stats) { + if (!ctx || !ctx->ob_ctx || !ctx->env.prepack_at_load || !jobs || !versions || + m_hint == 0u || k_dim == 0u || num_jobs == 0u) { + return; + } + + uint64_t sig = edgetpu_mix64(static_cast(m_hint)); + sig ^= edgetpu_mix64((static_cast(k_dim) << 32) | num_jobs); + for (uint32_t k = 0; k < num_jobs; ++k) { + if (!jobs[k].b_nk || jobs[k].n_dim == 0u || versions[k] == 0u) { + return; + } + sig = edgetpu_mix64(sig ^ static_cast(reinterpret_cast(jobs[k].b_nk))); + sig = edgetpu_mix64(sig ^ ((static_cast(jobs[k].n_dim) << 8) | jobs[k].is_q4_0)); + sig = edgetpu_mix64(sig ^ versions[k]); + } + if (sig == 0u) { + sig = 1u; + } + + if (ctx->prepacked_group_keys.find(sig) != ctx->prepacked_group_keys.end()) { + return; + } + if (ctx->prepacked_group_keys.size() < 65536u) { + ctx->prepacked_group_keys.insert(sig); + } + + ob_prepack_stats_t pst {}; + if (ob_gemm_prepack_quant_batch(ctx->ob_ctx, m_hint, k_dim, jobs, num_jobs, &pst) != OB_OK) { + return; + } + + ctx->total_prepack_calls += 1u; + ctx->total_prepack_tiles += pst.tiles_prepacked; + ctx->total_prepack_cached += pst.tiles_already_cached; + ctx->total_prepack_skipped += pst.tiles_skipped_budget; + ctx->total_prepack_graphs += pst.graphs_precompiled; + + if (eval_stats) { + eval_stats->tiles_checked += pst.tiles_checked; + eval_stats->tiles_prepacked += pst.tiles_prepacked; + eval_stats->tiles_already_cached += pst.tiles_already_cached; + eval_stats->tiles_skipped_budget += pst.tiles_skipped_budget; + eval_stats->graphs_precompiled += pst.graphs_precompiled; + eval_stats->bytes_resident = pst.bytes_resident; + } +} + +struct sibling_mm_plan_item { + bool is_mm = false; + int mm_idx = -1; // valid when is_mm == true + struct ggml_tensor * op = nullptr; // valid when is_mm == false +}; + +struct sibling_mm_group { + static constexpr int MAX_SIBLINGS = 8; + static constexpr int MAX_PLAN = 24; + + struct ggml_tensor * mm_nodes[MAX_SIBLINGS] {}; + bool mm_needs_scratch[MAX_SIBLINGS] {}; + size_t mm_scratch_offs[MAX_SIBLINGS] {}; + sibling_mm_plan_item plan[MAX_PLAN] {}; + int n_mm = 0; + int n_plan = 0; + size_t total_scratch_elems = 0; + uint32_t M = 0; + uint32_t K = 0; + const struct ggml_tensor * shared_x = nullptr; + int next_node_idx = 0; +}; + +static void collect_sibling_mul_mat_group(struct ggml_cgraph * cgraph, + int start_idx, + sibling_mm_group * out) { + struct ggml_tensor * node = cgraph->nodes[start_idx]; + const struct ggml_tensor * shared_x = node->src[1]; + + out->n_mm = 0; + out->n_plan = 0; + out->total_scratch_elems = 0; + out->M = static_cast(shared_x->ne[1]); + out->K = static_cast(shared_x->ne[0]); + out->shared_x = shared_x; + out->mm_nodes[0] = node; + out->mm_needs_scratch[0] = false; + out->mm_scratch_offs[0] = 0; + out->plan[out->n_plan++] = { true, 0, nullptr }; + out->n_mm = 1; + + auto produced_by_group = [&](const struct ggml_tensor * t) -> bool { + const struct ggml_tensor * base = unwrap_view_src(t); + for (int k = 0; k < out->n_mm; ++k) { + if (base == out->mm_nodes[k]) { + return true; + } + } + for (int p = 0; p < out->n_plan; ++p) { + if (!out->plan[p].is_mm && base == out->plan[p].op) { + return true; + } + } + return false; + }; + + int j = start_idx + 1; + while (j < cgraph->n_nodes && out->n_plan < sibling_mm_group::MAX_PLAN) { + struct ggml_tensor * next = cgraph->nodes[j]; + if ((next->flags & GGML_TENSOR_FLAG_COMPUTE) == 0 || + next->op == GGML_OP_NONE || + next->op == GGML_OP_RESHAPE || + next->op == GGML_OP_VIEW || + next->op == GGML_OP_PERMUTE || + next->op == GGML_OP_TRANSPOSE) { + ++j; + continue; + } + if (next->op == GGML_OP_ADD || next->op == GGML_OP_ROPE) { + if (produced_by_group(next->src[0]) && !tensors_overlap(next, shared_x)) { + // Ensure deferred op does not overwrite weights of any already-queued sibling. + bool w_hazard = false; + for (int k = 0; k < out->n_mm; ++k) { + if (tensors_overlap(next, out->mm_nodes[k]->src[0])) { + w_hazard = true; + break; + } + } + if (!w_hazard) { + out->plan[out->n_plan++] = { false, -1, next }; + ++j; + continue; + } + } + break; + } + if (out->n_mm < sibling_mm_group::MAX_SIBLINGS && is_batchable_sibling_mul_mat(next, shared_x)) { + // Verify next's weights are untouched by all prior ops in plan. + bool w_hazard = false; + for (int p = 0; p < out->n_plan; ++p) { + const struct ggml_tensor * prior_dst = + out->plan[p].is_mm ? out->mm_nodes[out->plan[p].mm_idx] : out->plan[p].op; + if (tensors_overlap(next->src[0], prior_dst)) { + w_hazard = true; + break; + } + } + if (w_hazard) { + break; + } + // Check if next's output buffer aliases ANY prior plan tensor (e.g. ggml-alloc + // reusing dead Q_mm/Q_bias storage for V_mm or K_mm). If so, stage in sibling_scratch + // and commit at next's exact original timestamp. + bool dst_aliases = false; + for (int p = 0; p < out->n_plan; ++p) { + if (out->plan[p].is_mm) { + const struct ggml_tensor * pm = out->mm_nodes[out->plan[p].mm_idx]; + if (tensors_overlap(next, pm) || tensors_overlap(next, pm->src[0])) { + dst_aliases = true; + break; + } + } else { + const struct ggml_tensor * po = out->plan[p].op; + if (tensors_overlap(next, po) || + tensors_overlap(next, po->src[0]) || + tensors_overlap(next, po->src[1]) || + tensors_overlap(next, po->src[2])) { + dst_aliases = true; + break; + } + } + } + out->mm_nodes[out->n_mm] = next; + out->mm_needs_scratch[out->n_mm] = dst_aliases; + if (dst_aliases) { + out->mm_scratch_offs[out->n_mm] = out->total_scratch_elems; + out->total_scratch_elems += static_cast(out->M) * static_cast(next->src[0]->ne[1]); + } else { + out->mm_scratch_offs[out->n_mm] = 0; + } + out->plan[out->n_plan++] = { true, out->n_mm, nullptr }; + out->n_mm++; + ++j; + continue; + } + break; + } + out->next_node_idx = j - 1; +} + +static void prepack_cgraph_weights_once(ggml_backend_edgetpu_context * ctx, + struct ggml_cgraph * cgraph) { + if (!ctx || !ctx->ob_ctx || !cgraph) { + return; + } + + ob_prepack_stats_t eval_stats {}; + for (int i = 0; i < cgraph->n_nodes; ++i) { + struct ggml_tensor * node = cgraph->nodes[i]; + if (!node || (node->flags & GGML_TENSOR_FLAG_COMPUTE) == 0) { + continue; + } + + if (node->op == GGML_OP_MUL_MAT) { + fused_swiglu_match swiglu; + if (match_fused_swiglu(ctx, cgraph, i, &swiglu)) { + const uint64_t vg = ensure_weight_buffer_registered(ctx, swiglu.gate_mm->src[0]); + const uint64_t vu = ensure_weight_buffer_registered(ctx, swiglu.up_mm->src[0]); + const uint64_t vd = ensure_weight_buffer_registered(ctx, swiglu.down_mm->src[0]); + + const bool is_single_vii_chain = + ((swiglu.K == 576u && swiglu.N == 576u) || + (swiglu.K == 1536u && swiglu.N == 1536u)) && + swiglu.M <= 8u; + if (ctx->env.prepack_at_load && !is_single_vii_chain) { + const uint32_t m_hint = std::min(swiglu.M, 64u); + ob_gemm_f32_quant_job_t gu_jobs[2] {}; + gu_jobs[0].b_nk = swiglu.gate_mm->src[0]->data; + gu_jobs[0].n_dim = swiglu.H; + gu_jobs[0].activation = OB_ACT_NONE; + ob_gemm_f32_quant_job_set_type(&gu_jobs[0], swiglu.gate_qt); + + gu_jobs[1].b_nk = swiglu.up_mm->src[0]->data; + gu_jobs[1].n_dim = swiglu.H; + gu_jobs[1].activation = OB_ACT_NONE; + ob_gemm_f32_quant_job_set_type(&gu_jobs[1], swiglu.up_qt); + + const uint64_t gu_vers[2] = { vg, vu }; + prepack_quant_jobs_once(ctx, m_hint, swiglu.K, gu_jobs, gu_vers, 2u, &eval_stats); + + ob_gemm_f32_quant_job_t down_job {}; + down_job.b_nk = swiglu.down_mm->src[0]->data; + down_job.n_dim = swiglu.N; + down_job.activation = OB_ACT_NONE; + ob_gemm_f32_quant_job_set_type(&down_job, swiglu.down_qt); + prepack_quant_jobs_once(ctx, m_hint, swiglu.H, &down_job, &vd, 1u, &eval_stats); + } + i = swiglu.end_idx; + continue; + } + + if (ctx->env.batch_siblings && !ctx->env.packed_q8 && is_batchable_sibling_mul_mat(node, nullptr)) { + sibling_mm_group grp; + collect_sibling_mul_mat_group(cgraph, i, &grp); + if (grp.n_mm > 1) { + ob_gemm_f32_quant_job_t jobs[sibling_mm_group::MAX_SIBLINGS] {}; + uint64_t vers[sibling_mm_group::MAX_SIBLINGS] {}; + bool types_ok = true; + for (int k = 0; k < grp.n_mm; ++k) { + ob_quant_type_t qt = OB_QUANT_Q8_0; + if (!ggml_type_to_ob_quant(grp.mm_nodes[k]->src[0]->type, &qt)) { + types_ok = false; + break; + } + vers[k] = ensure_weight_buffer_registered(ctx, grp.mm_nodes[k]->src[0]); + jobs[k].b_nk = grp.mm_nodes[k]->src[0]->data; + jobs[k].n_dim = static_cast(grp.mm_nodes[k]->src[0]->ne[1]); + jobs[k].activation = OB_ACT_NONE; + ob_gemm_f32_quant_job_set_type(&jobs[k], qt); + } + if (types_ok && ctx->env.prepack_at_load) { + prepack_quant_jobs_once( + ctx, grp.M, grp.K, jobs, vers, static_cast(grp.n_mm), &eval_stats); + } + i = grp.next_node_idx; + continue; + } + } + + const struct ggml_tensor * src0 = node->src[0]; + const struct ggml_tensor * src1 = node->src[1]; + ob_quant_type_t qt = OB_QUANT_Q8_0; + if (src0 && src1 && + ggml_type_to_ob_quant(src0->type, &qt) && + (src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_Q8_0) && + !ctx->env.packed_q8) { + const uint64_t ver = ensure_weight_buffer_registered(ctx, src0); + if (ver != 0u && ctx->env.prepack_at_load) { + const uint32_t M = static_cast(src1->ne[1]); + const uint32_t K = static_cast(src0->ne[0]); + const uint32_t N = static_cast(src0->ne[1]); + for (int64_t i03 = 0; i03 < src0->ne[3]; ++i03) { + for (int64_t i02 = 0; i02 < src0->ne[2]; ++i02) { + ob_gemm_f32_quant_job_t job {}; + job.b_nk = static_cast(src0->data) + + static_cast(i02) * src0->nb[2] + + static_cast(i03) * src0->nb[3]; + job.n_dim = N; + job.activation = OB_ACT_NONE; + ob_gemm_f32_quant_job_set_type(&job, qt); + prepack_quant_jobs_once(ctx, M, K, &job, &ver, 1u, &eval_stats); + } + } + } + } + } else if (node->op == GGML_OP_MUL_MAT_ID) { + ensure_weight_buffer_registered(ctx, node->src[0]); + } + } + + if (eval_stats.tiles_prepacked > 0 || eval_stats.tiles_skipped_budget > 0 || + (ctx->env.verbose > 0 && eval_stats.tiles_checked > 0)) { + GGML_LOG_INFO( + "ggml-edgetpu: load-prepack checked=%u prepacked=%u already_cached=%u skipped_budget=%u graphs=%u resident_mib=%.2f\n", + eval_stats.tiles_checked, + eval_stats.tiles_prepacked, + eval_stats.tiles_already_cached, + eval_stats.tiles_skipped_budget, + eval_stats.graphs_precompiled, + static_cast(eval_stats.bytes_resident) / (1024.0 * 1024.0)); + } +} + static ggml_status ggml_backend_edgetpu_graph_compute(ggml_backend_t backend, struct ggml_cgraph * cgraph) { auto * ctx = static_cast(backend->context); ctx->total_graph_evals += 1; + prepack_cgraph_weights_once(ctx, cgraph); + for (int i = 0; i < cgraph->n_nodes; ++i) { struct ggml_tensor * node = cgraph->nodes[i]; @@ -2153,154 +2660,34 @@ static ggml_status ggml_backend_edgetpu_graph_compute(ggml_backend_t backend, st // Exact byte-range hazard tracking + scratch-buffer commit preserves exact sequential // semantics even when ggml-alloc reuses a dead Q buffer for V or K. if (ctx->env.batch_siblings && !ctx->env.packed_q8 && is_batchable_sibling_mul_mat(node, nullptr)) { - constexpr int MAX_SIBLINGS = 8; - constexpr int MAX_PLAN = 24; - - struct plan_item { - bool is_mm; - int mm_idx; // valid when is_mm == true - struct ggml_tensor * op; // valid when is_mm == false - }; - - struct ggml_tensor * mm_nodes[MAX_SIBLINGS]; - bool mm_needs_scratch[MAX_SIBLINGS]; - size_t mm_scratch_offs[MAX_SIBLINGS]; - plan_item plan[MAX_PLAN]; - int n_mm = 0; - int n_plan = 0; - - const struct ggml_tensor * shared_x = node->src[1]; - mm_nodes[n_mm] = node; - mm_needs_scratch[n_mm] = false; - mm_scratch_offs[n_mm] = 0; - plan[n_plan++] = { true, n_mm, nullptr }; - n_mm++; - - size_t total_scratch_elems = 0; - const uint32_t M = static_cast(shared_x->ne[1]); - const uint32_t K = static_cast(shared_x->ne[0]); - - auto produced_by_group = [&](const struct ggml_tensor * t) -> bool { - const struct ggml_tensor * base = unwrap_view_src(t); - for (int k = 0; k < n_mm; ++k) { - if (base == mm_nodes[k]) { - return true; - } - } - for (int p = 0; p < n_plan; ++p) { - if (!plan[p].is_mm && base == plan[p].op) { - return true; - } - } - return false; - }; - - int j = i + 1; - while (j < cgraph->n_nodes && n_plan < MAX_PLAN) { - struct ggml_tensor * next = cgraph->nodes[j]; - if ((next->flags & GGML_TENSOR_FLAG_COMPUTE) == 0 || - next->op == GGML_OP_NONE || - next->op == GGML_OP_RESHAPE || - next->op == GGML_OP_VIEW || - next->op == GGML_OP_PERMUTE || - next->op == GGML_OP_TRANSPOSE) { - ++j; - continue; - } - if (next->op == GGML_OP_ADD || next->op == GGML_OP_ROPE) { - if (produced_by_group(next->src[0]) && !tensors_overlap(next, shared_x)) { - // Ensure deferred op does not overwrite weights of any already-queued sibling. - bool w_hazard = false; - for (int k = 0; k < n_mm; ++k) { - if (tensors_overlap(next, mm_nodes[k]->src[0])) { - w_hazard = true; - break; - } - } - if (!w_hazard) { - plan[n_plan++] = { false, -1, next }; - ++j; - continue; - } - } - break; - } - if (n_mm < MAX_SIBLINGS && is_batchable_sibling_mul_mat(next, shared_x)) { - // Verify next's weights are untouched by all prior ops in plan. - bool w_hazard = false; - for (int p = 0; p < n_plan; ++p) { - const struct ggml_tensor * prior_dst = plan[p].is_mm ? mm_nodes[plan[p].mm_idx] : plan[p].op; - if (tensors_overlap(next->src[0], prior_dst)) { - w_hazard = true; - break; - } - } - if (w_hazard) { - break; - } - // Check if next's output buffer aliases ANY prior plan tensor (e.g. ggml-alloc - // reusing dead Q_mm/Q_bias storage for V_mm or K_mm). If so, stage in sibling_scratch - // and commit at next's exact original timestamp. - bool dst_aliases = false; - for (int p = 0; p < n_plan; ++p) { - if (plan[p].is_mm) { - const struct ggml_tensor * pm = mm_nodes[plan[p].mm_idx]; - if (tensors_overlap(next, pm) || tensors_overlap(next, pm->src[0])) { - dst_aliases = true; - break; - } - } else { - const struct ggml_tensor * po = plan[p].op; - if (tensors_overlap(next, po) || - tensors_overlap(next, po->src[0]) || - tensors_overlap(next, po->src[1]) || - tensors_overlap(next, po->src[2])) { - dst_aliases = true; - break; - } - } - } - mm_nodes[n_mm] = next; - mm_needs_scratch[n_mm] = dst_aliases; - if (dst_aliases) { - mm_scratch_offs[n_mm] = total_scratch_elems; - total_scratch_elems += static_cast(M) * static_cast(next->src[0]->ne[1]); - } else { - mm_scratch_offs[n_mm] = 0; - } - plan[n_plan++] = { true, n_mm, nullptr }; - n_mm++; - ++j; - continue; - } - break; - } + sibling_mm_group grp; + collect_sibling_mul_mat_group(cgraph, i, &grp); - if (n_mm > 1) { + if (grp.n_mm > 1) { ctx->total_batched_groups += 1; - ctx->total_batched_ops += static_cast(n_mm); - if (n_mm == 3) { + ctx->total_batched_ops += static_cast(grp.n_mm); + if (grp.n_mm == 3) { ctx->total_batched_3_groups += 1; - } else if (n_mm == 2) { + } else if (grp.n_mm == 2) { ctx->total_batched_2_groups += 1; } - if (total_scratch_elems > 0 && ctx->sibling_scratch.size() < total_scratch_elems) { - ctx->sibling_scratch.resize(total_scratch_elems); + if (grp.total_scratch_elems > 0 && ctx->sibling_scratch.size() < grp.total_scratch_elems) { + ctx->sibling_scratch.resize(grp.total_scratch_elems); } - ob_gemm_f32_quant_job_t jobs[MAX_SIBLINGS]; - for (int k = 0; k < n_mm; ++k) { + ob_gemm_f32_quant_job_t jobs[sibling_mm_group::MAX_SIBLINGS]; + for (int k = 0; k < grp.n_mm; ++k) { ob_quant_type_t qt = OB_QUANT_Q8_0; - if (!ggml_type_to_ob_quant(mm_nodes[k]->src[0]->type, &qt)) { + if (!ggml_type_to_ob_quant(grp.mm_nodes[k]->src[0]->type, &qt)) { return GGML_STATUS_FAILED; } jobs[k] = {}; - jobs[k].b_nk = mm_nodes[k]->src[0]->data; - jobs[k].c_mn = mm_needs_scratch[k] - ? (ctx->sibling_scratch.data() + mm_scratch_offs[k]) - : reinterpret_cast(mm_nodes[k]->data); - jobs[k].n_dim = static_cast(mm_nodes[k]->src[0]->ne[1]); + jobs[k].b_nk = grp.mm_nodes[k]->src[0]->data; + jobs[k].c_mn = grp.mm_needs_scratch[k] + ? (ctx->sibling_scratch.data() + grp.mm_scratch_offs[k]) + : reinterpret_cast(grp.mm_nodes[k]->data); + jobs[k].n_dim = static_cast(grp.mm_nodes[k]->src[0]->ne[1]); jobs[k].activation = OB_ACT_NONE; ob_gemm_f32_quant_job_set_type(&jobs[k], qt); } @@ -2308,58 +2695,58 @@ static ggml_status ggml_backend_edgetpu_graph_compute(ggml_backend_t backend, st ob_invoke_stats_t bstats {}; const ob_status_t bst = ob_gemm_matmul_f32_quant_batch( ctx->ob_ctx, - reinterpret_cast(shared_x->data), - M, K, + reinterpret_cast(grp.shared_x->data), + grp.M, grp.K, jobs, - static_cast(n_mm), + static_cast(grp.n_mm), &bstats); if (bst != OB_OK) { GGML_LOG_ERROR("ggml-edgetpu: ob_gemm_matmul_f32_quant_batch(n=%d,M=%u,K=%u) failed: %s (%s)\n", - n_mm, M, K, ob_status_string(bst), ob_context_last_error(ctx->ob_ctx)); + grp.n_mm, grp.M, grp.K, ob_status_string(bst), ob_context_last_error(ctx->ob_ctx)); return GGML_STATUS_FAILED; } - ctx->total_mul_mat_calls += static_cast(n_mm); - ctx->total_slice_calls += static_cast(n_mm); + ctx->total_mul_mat_calls += static_cast(grp.n_mm); + ctx->total_slice_calls += static_cast(grp.n_mm); ctx->total_tiles_dispatched += bstats.tiles_dispatched; ctx->total_tile_cache_hits += bstats.cache_hits; ctx->total_hw_us += bstats.hw_execution_us; ctx->total_wall_us += bstats.wall_time_us; if (bstats.flags & OB_STAT_FLAG_EMITTER_USED) { - ctx->total_emitter_slices += static_cast(n_mm); + ctx->total_emitter_slices += static_cast(grp.n_mm); } if (bstats.flags & OB_STAT_FLAG_CPU_FALLBACK) { - ctx->total_cpu_fallback_slices += static_cast(n_mm); + ctx->total_cpu_fallback_slices += static_cast(grp.n_mm); if (!ctx->env.mock_mode && ctx->total_cpu_fallback_slices <= 8) { GGML_LOG_WARN("ggml-edgetpu: CPU fallback in sibling batch(n=%d,M=%u,K=%u,flags=0x%x)\n", - n_mm, M, K, static_cast(bstats.flags)); + grp.n_mm, grp.M, grp.K, static_cast(bstats.flags)); } } // Replay deferred ADDs / ROPEs and commit any scratch-staged sibling outputs in exact original order. - for (int p = 0; p < n_plan; ++p) { - if (plan[p].is_mm) { - const int k = plan[p].mm_idx; - if (mm_needs_scratch[k]) { - const size_t elems = static_cast(M) * static_cast(mm_nodes[k]->src[0]->ne[1]); - std::memcpy(mm_nodes[k]->data, - ctx->sibling_scratch.data() + mm_scratch_offs[k], + for (int p = 0; p < grp.n_plan; ++p) { + if (grp.plan[p].is_mm) { + const int k = grp.plan[p].mm_idx; + if (grp.mm_needs_scratch[k]) { + const size_t elems = static_cast(grp.M) * static_cast(grp.mm_nodes[k]->src[0]->ne[1]); + std::memcpy(grp.mm_nodes[k]->data, + ctx->sibling_scratch.data() + grp.mm_scratch_offs[k], elems * sizeof(float)); } - } else if (plan[p].op->op == GGML_OP_ADD) { - const ggml_status st = ggml_edgetpu_compute_forward_add_bias(ctx, plan[p].op); + } else if (grp.plan[p].op->op == GGML_OP_ADD) { + const ggml_status st = ggml_edgetpu_compute_forward_add_bias(ctx, grp.plan[p].op); if (st != GGML_STATUS_SUCCESS) { return st; } - } else if (plan[p].op->op == GGML_OP_ROPE) { - const ggml_status st = ggml_edgetpu_compute_forward_rope(ctx, plan[p].op); + } else if (grp.plan[p].op->op == GGML_OP_ROPE) { + const ggml_status st = ggml_edgetpu_compute_forward_rope(ctx, grp.plan[p].op); if (st != GGML_STATUS_SUCCESS) { return st; } } } - i = j - 1; + i = grp.next_node_idx; break; } } @@ -2610,7 +2997,21 @@ static bool ggml_backend_edgetpu_device_supports_op(ggml_backend_dev_t dev, cons } g_hot_env.ensure_initialized(); + const uint64_t max_n = g_hot_env.max_n.load(std::memory_order_relaxed); + if (max_n > 0 && static_cast(N) > max_n) { + return false; + } + const uint64_t max_m = g_hot_env.max_m.load(std::memory_order_relaxed); + if (max_m > 0 && static_cast(M) > max_m) { + return false; + } const uint64_t min_elements = g_hot_env.min_elements.load(std::memory_order_relaxed); + const uint64_t min_tile_dim = g_hot_env.min_tile_dim.load(std::memory_order_relaxed); + if (min_tile_dim > 0 && + static_cast(std::min(K, N)) < min_tile_dim && + (static_cast(std::max(K, N)) >= 512ULL || min_elements > 0)) { + return false; + } if (min_elements > 0) { const uint64_t work = static_cast(M) * @@ -2688,7 +3089,29 @@ static bool ggml_backend_edgetpu_device_supports_op(ggml_backend_dev_t dev, cons } g_hot_env.ensure_initialized(); + const int mmid_mode = g_hot_env.mul_mat_id_mode.load(std::memory_order_relaxed); + if (mmid_mode == 0) { + return false; + } + if (mmid_mode < 0) { + const uint64_t max_bytes = g_hot_env.mul_mat_id_max_bytes.load(std::memory_order_relaxed); + const uint64_t kn = static_cast(K) * static_cast(N); + const uint64_t ex = static_cast(n_expert); + if (max_bytes == 0 || kn > max_bytes || ex > (UINT64_MAX / kn) || (kn * ex) > max_bytes) { + return false; + } + } + const uint64_t max_m = g_hot_env.max_m.load(std::memory_order_relaxed); + if (max_m > 0 && static_cast(n_tokens) > max_m) { + return false; + } const uint64_t min_elements = g_hot_env.min_elements.load(std::memory_order_relaxed); + const uint64_t min_tile_dim = g_hot_env.min_tile_dim.load(std::memory_order_relaxed); + if (min_tile_dim > 0 && + static_cast(std::min(K, N)) < min_tile_dim && + (static_cast(std::max(K, N)) >= 512ULL || min_elements > 0)) { + return false; + } if (min_elements > 0) { const uint64_t work = static_cast(n_tokens) * @@ -3049,7 +3472,7 @@ ggml_backend_t ggml_backend_edgetpu_init(void) { "ggml-edgetpu: initialized Pixel Tensor G5 (buenos_a0) " "[mock=%d, emitter=%d, freetile=%d, interp=%s, credits=%u, cache_cap=%u, pool_mb=%u, " "tile_limits=(%u,%u,%u), pwr=(perf=%u,core=0x%02x,mem=0x%02x,qos=0x%02x,prio=%u), " - "batch_siblings=%d, min_elements=%llu, packed_q8=%d, libopenbuenos=%d]\n", + "batch_siblings=%d, prepack=%d, mmid=%d, mmid_max_mb=%llu, max_m=%llu, max_n=%llu, min_tile_dim=%llu, min_elements=%llu, packed_q8=%d, libopenbuenos=%d]\n", ob_context_is_mock(ob_ctx), emitter_ok ? 1 : 0, ob_context_get_freetile(ob_ctx), @@ -3064,6 +3487,12 @@ ggml_backend_t ggml_backend_edgetpu_init(void) { static_cast(ob_cfg.qos_class), static_cast(ob_cfg.priority), env.batch_siblings ? 1 : 0, + env.prepack_at_load ? 1 : 0, + env.mul_mat_id_mode, + static_cast(env.mul_mat_id_max_bytes / (1024ULL * 1024ULL)), + static_cast(env.max_m), + static_cast(env.max_n), + static_cast(env.min_tile_dim), static_cast(env.min_elements), env.packed_q8 ? 1 : 0, GGML_EDGETPU_LINKED_LIBOPENBUENOS); diff --git a/llama-cpp-edgetpu/openbuenos_shim.c b/llama-cpp-edgetpu/openbuenos_shim.c index 105b1ce4..cf953739 100644 --- a/llama-cpp-edgetpu/openbuenos_shim.c +++ b/llama-cpp-edgetpu/openbuenos_shim.c @@ -621,6 +621,32 @@ ob_status_t ob_gemm_unregister_immutable_weights(ob_context_t * ctx, return OB_OK; } +ob_status_t ob_gemm_prepack_quant_batch(ob_context_t * ctx, + uint32_t m_hint, + uint32_t k_dim, + const ob_gemm_f32_quant_job_t * jobs, + uint32_t num_jobs, + ob_prepack_stats_t * out_stats) { + uint32_t j = 0u; + if (!ctx || !jobs || m_hint == 0u || k_dim == 0u || num_jobs == 0u) { + return OB_ERR_INVALID_ARG; + } + for (j = 0u; j < num_jobs; ++j) { + uint32_t qk = 0u; + if (!jobs[j].b_nk || jobs[j].n_dim == 0u || jobs[j].is_q4_0 > (uint8_t)OB_QUANT_IQ4_XS) { + return OB_ERR_INVALID_ARG; + } + qk = ob_quant_block_elements((ob_quant_type_t)jobs[j].is_q4_0); + if (qk == 0u || (k_dim % qk) != 0u) { + return OB_ERR_INVALID_ARG; + } + } + if (out_stats) { + memset(out_stats, 0, sizeof(*out_stats)); + } + return OB_OK; +} + ob_status_t ob_gemm_swiglu_f32_quant(ob_context_t * ctx, const float * a_mk, const ob_gemm_swiglu_quant_desc_t * desc, diff --git a/llama-cpp-edgetpu/tests/test_edgetpu_llm_shapes.cpp b/llama-cpp-edgetpu/tests/test_edgetpu_llm_shapes.cpp index 0626f8c2..83b3549b 100644 --- a/llama-cpp-edgetpu/tests/test_edgetpu_llm_shapes.cpp +++ b/llama-cpp-edgetpu/tests/test_edgetpu_llm_shapes.cpp @@ -225,6 +225,174 @@ static bool test_hybrid_scheduler_routing(ggml_backend_t b_tpu, ggml_backend_t b return routing_ok && val_ok; } +static bool test_zero_repack_and_auto_routing(ggml_backend_t b_tpu, ggml_backend_t b_cpu) { + std::printf("\n[Zero-Repack Prepack, Weight Mutation Invalidation, & Auto-Routing Gates]\n"); + bool ok = true; + + // 1. Verify MAX_N=65536, MIN_TILE_DIM=128 micro-tile bloat guard, and MUL_MAT_ID auto (>64 MiB). + { + const size_t ctx_size = ggml_tensor_overhead() * 48 + ggml_graph_overhead(); + ggml_init_params params { ctx_size, nullptr, true }; + ggml_context * ctx = ggml_init(params); + if (!ctx) return false; + + ggml_tensor * x_voc = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 64, 1); + ggml_tensor * w_big_n = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, 64, 70000); + ggml_tensor * mm_big = ggml_mul_mat(ctx, w_big_n, x_voc); + + if (ggml_backend_supports_op(b_tpu, mm_big)) { + std::fprintf(stderr, "FAIL: EDGETPU should reject N=70000 (> default MAX_N=65536)\n"); + ok = false; + } + + // Skinny micro-tile shapes (min(K,N) < 128 && max(K,N) >= 512) must stay on CPU + // to avoid thousands of 4 KiB (64,64) DMA-BUF FDs and cache entry thrashing. + ggml_tensor * x_64 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 64, 1); + ggml_tensor * w_ctrl_f = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 64, 2304); + ggml_tensor * mm_ctrl_f = ggml_mul_mat(ctx, w_ctrl_f, x_64); + if (ggml_backend_supports_op(b_tpu, mm_ctrl_f)) { + std::fprintf(stderr, "FAIL: EDGETPU should reject F32 skinny (64, 2304)\n"); + ok = false; + } + + ggml_tensor * x_4608 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 4608, 1); + ggml_tensor * w_ctrl_d = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 4608, 64); + ggml_tensor * mm_ctrl_d = ggml_mul_mat(ctx, w_ctrl_d, x_4608); + if (ggml_backend_supports_op(b_tpu, mm_ctrl_d)) { + std::fprintf(stderr, "FAIL: EDGETPU should reject F32 skinny (4608, 64)\n"); + ok = false; + } + + ggml_tensor * x_2304_pp = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 2304, 28); + ggml_tensor * w_sink = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, 2304, 24); + ggml_tensor * mm_sink = ggml_mul_mat(ctx, w_sink, x_2304_pp); + if (ggml_backend_supports_op(b_tpu, mm_sink)) { + std::fprintf(stderr, "FAIL: EDGETPU should reject Q4_0 prefill skinny (2304, 24)\n"); + ok = false; + } + + ggml_tensor * w_conv = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, 2304, 32); + ggml_tensor * mm_conv = ggml_mul_mat(ctx, w_conv, x_2304_pp); + if (ggml_backend_supports_op(b_tpu, mm_conv)) { + std::fprintf(stderr, "FAIL: EDGETPU should reject Q4_0 prefill skinny (2304, 32)\n"); + ok = false; + } + + ggml_tensor * w_rel = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, 2304, 384); + ggml_tensor * mm_rel = ggml_mul_mat(ctx, w_rel, x_2304_pp); + if (!ggml_backend_supports_op(b_tpu, mm_rel)) { + std::fprintf(stderr, "FAIL: EDGETPU should allow Q4_0 (2304, 384)\n"); + ok = false; + } + + ggml_tensor * w_huge_moe = ggml_new_tensor_3d(ctx, GGML_TYPE_Q4_0, 2304, 2560, 64); + ggml_tensor * x_moe = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, 2304, 1, 1); + ggml_tensor * ids_moe = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, 8, 1); + ggml_tensor * mmid_huge = ggml_mul_mat_id(ctx, w_huge_moe, x_moe, ids_moe); + if (ggml_backend_supports_op(b_tpu, mmid_huge)) { + std::fprintf(stderr, "FAIL: EDGETPU auto gate should reject 360 MiB MoE MUL_MAT_ID\n"); + ok = false; + } + + ggml_tensor * w_small_moe = ggml_new_tensor_3d(ctx, GGML_TYPE_Q4_0, 64, 64, 8); + ggml_tensor * x_small = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, 64, 1, 1); + ggml_tensor * ids_small = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, 2, 1); + ggml_tensor * mmid_small = ggml_mul_mat_id(ctx, w_small_moe, x_small, ids_small); + if (!ggml_backend_supports_op(b_tpu, mmid_small)) { + std::fprintf(stderr, "FAIL: EDGETPU should allow 32 KiB small MoE MUL_MAT_ID\n"); + ok = false; + } + + ggml_free(ctx); + } + + // 2. Sibling [Q, K, V] Q4_0 graph on USAGE_WEIGHTS EDGETPU buffer + mutation invalidation. + { + constexpr int64_t M = 1, K = 256, Nq = 256, Nk = 128; + const size_t ctx_size = ggml_tensor_overhead() * 16 + ggml_graph_overhead(); + ggml_init_params params { ctx_size, nullptr, true }; + ggml_context * ctx = ggml_init(params); + if (!ctx) return false; + + ggml_tensor * wq = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, K, Nq); + ggml_tensor * wk = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, K, Nk); + ggml_backend_buffer_t buf_w = ggml_backend_alloc_ctx_tensors_from_buft( + ctx, ggml_backend_edgetpu_buffer_type()); + ggml_backend_buffer_set_usage(buf_w, GGML_BACKEND_BUFFER_USAGE_WEIGHTS); + + ggml_tensor * x = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, K, M); + ggml_tensor * mq = ggml_mul_mat(ctx, wq, x); + ggml_tensor * mk = ggml_mul_mat(ctx, wk, x); + ggml_tensor * out_sum = ggml_add(ctx, ggml_repeat(ctx, mk, mq), mq); + + ggml_backend_t backends[2] = { b_tpu, b_cpu }; + ggml_backend_buffer_type_t bufts[2] = { + ggml_backend_edgetpu_buffer_type(), + ggml_backend_cpu_buffer_type(), + }; + ggml_backend_sched_t sched = ggml_backend_sched_new(backends, bufts, 2, 1024, false, true); + ggml_cgraph * gf = ggml_new_graph(ctx); + ggml_build_forward_expand(gf, out_sum); + if (!ggml_backend_sched_alloc_graph(sched, gf)) { + std::fprintf(stderr, "FAIL: alloc_graph failed in sibling prepack test\n"); + ggml_backend_sched_free(sched); + ggml_backend_buffer_free(buf_w); + ggml_free(ctx); + return false; + } + + std::mt19937 rng(777); + std::uniform_real_distribution dist(-0.5f, 0.5f); + std::vector x_vals(M * K, 0.5f); + std::vector wq_f1(Nq * K), wq_f2(Nq * K), wk_f(Nk * K); + for (float & v : wq_f1) v = dist(rng); + for (float & v : wq_f2) v = 1.0f; + for (float & v : wk_f) v = dist(rng); + + std::vector wq_q4(ggml_nbytes(wq)), wk_q4(ggml_nbytes(wk)); + ggml_quantize_chunk(GGML_TYPE_Q4_0, wq_f1.data(), wq_q4.data(), 0, Nq, K, nullptr); + ggml_quantize_chunk(GGML_TYPE_Q4_0, wk_f.data(), wk_q4.data(), 0, Nk, K, nullptr); + + ggml_backend_tensor_set(wq, wq_q4.data(), 0, wq_q4.size()); + ggml_backend_tensor_set(wk, wk_q4.data(), 0, wk_q4.size()); + ggml_backend_tensor_set(x, x_vals.data(), 0, x_vals.size() * sizeof(float)); + + ok &= (ggml_backend_sched_graph_compute(sched, gf) == GGML_STATUS_SUCCESS); + std::vector y1(M * Nq), y2(M * Nq), y3(M * Nq); + ggml_backend_tensor_get(out_sum, y1.data(), 0, y1.size() * sizeof(float)); + + // Second compute with same weights & input -> bit-exact match. + ok &= (ggml_backend_sched_graph_compute(sched, gf) == GGML_STATUS_SUCCESS); + ggml_backend_tensor_get(out_sum, y2.data(), 0, y2.size() * sizeof(float)); + for (size_t i = 0; i < y1.size(); ++i) { + if (std::fabs(y1[i] - y2[i]) > 1e-6f) { + ok = false; + break; + } + } + + // Mutate wq via buffer_set -> version bumps -> next eval MUST reflect updated weights. + ggml_quantize_chunk(GGML_TYPE_Q4_0, wq_f2.data(), wq_q4.data(), 0, Nq, K, nullptr); + ggml_backend_tensor_set(wq, wq_q4.data(), 0, wq_q4.size()); + ok &= (ggml_backend_sched_graph_compute(sched, gf) == GGML_STATUS_SUCCESS); + ggml_backend_tensor_get(out_sum, y3.data(), 0, y3.size() * sizeof(float)); + + double diff_sum = 0.0; + for (size_t i = 0; i < y1.size(); ++i) diff_sum += std::fabs(y3[i] - y1[i]); + if (diff_sum <= 1.0) { + std::fprintf(stderr, "FAIL: mutated EDGETPU weight buffer did not invalidate cached weights\n"); + ok = false; + } + + ggml_backend_sched_free(sched); + ggml_backend_buffer_free(buf_w); + ggml_free(ctx); + } + + std::printf(" Zero-repack & auto-routing gates -> %s\n", ok ? "PASS" : "FAIL"); + return ok; +} + int main() { ggml_backend_dev_t dev = ggml_backend_dev_by_name("EDGETPU"); if (!dev) { @@ -276,6 +444,7 @@ int main() { } all_ok &= test_hybrid_scheduler_routing(b_tpu, b_cpu); + all_ok &= test_zero_repack_and_auto_routing(b_tpu, b_cpu); ggml_backend_free(b_tpu); ggml_backend_free(b_cpu);