diff --git a/src/core/cpu/conv2d.cpp b/src/core/cpu/conv2d.cpp new file mode 100644 index 000000000..780a0b39d --- /dev/null +++ b/src/core/cpu/conv2d.cpp @@ -0,0 +1,754 @@ +#include "core/cpu/registration.h" +#include "core/ggml_extensions.h" + +#ifndef SD_USE_UPSTREAM_GGML +#include "ggml.h" +#include "ggml-cpu.h" +#include "ggml-ext.h" + +#if defined(__x86_64__) || defined(_M_X64) +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// The backend compiles ops.cpp without -march=native on some toolchains, so the +// intrinsics in this file need an explicit target attribute. The runtime gate in +// conv2d_supports keeps this code unreachable on non-AVX2 machines. +#if defined(__GNUC__) && !defined(__clang__) +#pragma GCC push_options +#pragma GCC target("avx2,fma,f16c") +#elif defined(__clang__) +#pragma clang attribute push(__attribute__((target("avx2,fma,f16c"))), apply_to = function) +#endif + +// AVX2 6x16 implicit-GEMM conv2d for the CPU VAE decoder (v1). +// +// Registered as an extension kernel for GGML_OP_CONV_2D. Those nodes are only +// created by ggml_conv_2d_direct(), which sd's CPU path selects only when the +// user asks for it (--conv-direct vae=on); the default auto probe still reports +// "off (no implicit GEMM path)" on CPU, so nothing changes unless enabled. +// +// Dispatch gate (zero-regression): the kernel only claims shapes it was +// measured to win on; everything else declines and runs ggml's native +// CONV_2D (F32 im2col in wdata + mul_mat): +// * AVX2 + FMA present, F16 weights, F32 activation, contiguous, 4-D +// * stride 1, dilation 1 (all decoder convs), pad 1 for 3x3 / pad 0 for 1x1 +// * (oh*ow >= 128*128 and K = IC*KH*KW >= 1024) or +// (oc <= 16 and oh*ow >= 64*64) -- up.1/up.0 and conv_out +// up.3 (32x32), up.2 (64x64), conv_in 512<-16 and small 1x1 shortcuts +// therefore fall back. +// +// Kernel design (same as test/conv_v1.cpp): +// * implicit GEMM: the 16-pixel patch window is gathered on the fly, no +// materialised im2col tensor (at full 896x1152 that tensor is 4.4 GB) +// * MR=6 output channels x NR=16 pixels, 12 ymm accumulators; per k step +// 2 pixel loads + 6 broadcast weight loads + 12 FMAs +// * weights pre-packed once as F16->F32 [oc_block][k][6] and cached, so the +// 48 tiles of a tiled VAE decode reuse one pack (LRU, 512 MB budget, +// pointer+shape/nb+content-fingerprint key so recycled buffers cannot hit) +// * loop order y -> x0 -> ob keeps the input window hot in L1/L2 for all +// output-channel blocks +// * output written directly in ggml's WHCN layout, no permute pass +// * threading: ggml's own pool via ggml_ext_cpu_parallel_v1 (ith/nth), tasks +// stolen from a shared atomic counter over (batch x y-band x oc-group). +// No nested OpenMP. + +namespace sd_cpu { + namespace { + constexpr int NR = 16; // output pixels per micro-kernel + constexpr int MR = 6; // output channels per micro-kernel + constexpr int YCH = 16; // output rows per task band + constexpr int OB_GROUP = 16; // target number of oc groups + constexpr int TASK_TARGET = 16; // target tasks per thread + constexpr size_t CACHE_BUDGET = size_t(300) << 20; + constexpr size_t CACHE_MAX_ENTRY = size_t(128) << 20; + constexpr size_t CACHE_MAX_ENTRIES = 128; + constexpr int K_MIN = 1024; + constexpr int64_t SPATIAL_BIG = 128 * 128; + constexpr int64_t SPATIAL_SMALL = 64 * 64; + constexpr int OC_SMALL = 16; + + enum class PackKind : int { kImplicit = 0, kWino = 1 }; + + struct PackedWeights { + std::vector data; // implicit: [oc_pad/6][k][6]; winograd: [oc_pad/6][16][ic][6] + int ic = 0, oc = 0, kw = 0, kh = 0, k = 0, oc_pad = 0; + PackKind kind = PackKind::kImplicit; + size_t bytes() const { return data.size() * sizeof(float); } + }; + + struct CacheKey { + const void* ptr; + int64_t ne[4]; + size_t nb[4]; + uint64_t fingerprint; + int kind; + }; + + bool cache_key_equal(const CacheKey& a, const CacheKey& b) { + return a.ptr == b.ptr && a.fingerprint == b.fingerprint && a.kind == b.kind && + a.ne[0] == b.ne[0] && a.ne[1] == b.ne[1] && a.ne[2] == b.ne[2] && a.ne[3] == b.ne[3] && + a.nb[0] == b.nb[0] && a.nb[1] == b.nb[1] && a.nb[2] == b.nb[2] && a.nb[3] == b.nb[3]; + } + + // FNV-1a over a fixed sample of 256-byte chunks: cheap (~16 KB) but + // enough that a recycled allocation cannot alias a stale entry. + uint64_t weight_fingerprint(const void* data, size_t bytes) { + const auto* base = static_cast(data); + uint64_t h = 1469598103934665603ull ^ uint64_t(bytes); + constexpr size_t chunk_n = 256; + if (bytes <= 4 * chunk_n) { + for (size_t i = 0; i < bytes; ++i) { + h = (h ^ base[i]) * 1099511628211ull; + } + return h; + } + constexpr size_t samples = 64; + for (size_t s = 0; s < samples; ++s) { + const size_t off = (bytes - chunk_n) * s / (samples - 1); + for (size_t i = 0; i < chunk_n; ++i) { + h = (h ^ base[off + i]) * 1099511628211ull; + } + } + return h; + } + + // Winograd F(2x2,3x3) weight transform U = G*g*G^T. + // g is row-major 3x3 (ky*3+kx), U row-major 4x4. + static const float kWinoG[12] = { + 1.f, 0.f, 0.f, + 0.5f, 0.5f, 0.5f, + 0.5f,-0.5f, 0.5f, + 0.f, 0.f, 1.f, + }; + void wino_weight(const float* g, float* U) { + float t[12]; + for (int r = 0; r < 4; ++r) + for (int c = 0; c < 3; ++c) { + float sum = 0.f; + for (int k = 0; k < 3; ++k) sum += kWinoG[r * 3 + k] * g[k * 3 + c]; + t[r * 3 + c] = sum; + } + for (int r = 0; r < 4; ++r) + for (int c = 0; c < 4; ++c) { + float sum = 0.f; + for (int k = 0; k < 3; ++k) sum += t[r * 3 + k] * kWinoG[c * 3 + k]; + U[r * 4 + c] = sum; + } + } + + void pack_implicit(const ggml_fp16_t* src, PackedWeights& packed) { + packed.data.assign(size_t(packed.oc_pad) * size_t(packed.k) * MR, 0.0f); + for (int o = 0; o < packed.oc; ++o) { + const int ob = o / MR, i = o % MR; + for (int c = 0; c < packed.ic; ++c) + for (int ky = 0; ky < packed.kh; ++ky) + for (int kx = 0; kx < packed.kw; ++kx) { + const size_t si = (((size_t)o * packed.ic + c) * packed.kh + ky) * packed.kw + kx; + const int kk = (c * packed.kh + ky) * packed.kw + kx; + packed.data[((size_t(ob) * packed.k + kk) * MR) + i] = ggml_fp16_to_fp32(src[si]); + } + } + } + + void pack_wino(const ggml_fp16_t* src, PackedWeights& packed) { + // [oc_pad/6][16][ic][6]; exactly the layout consumed by gemm6x16_wino. + packed.data.assign((size_t)(packed.oc_pad / MR) * 16 * packed.ic * MR, 0.0f); + std::vector g(9), U(16); + for (int o = 0; o < packed.oc; ++o) { + const int ob = o / MR, i = o % MR; + for (int c = 0; c < packed.ic; ++c) { + for (int ky = 0; ky < 3; ++ky) + for (int kx = 0; kx < 3; ++kx) + g[ky * 3 + kx] = ggml_fp16_to_fp32(src[(((size_t)o * packed.ic + c) * 3 + ky) * 3 + kx]); + wino_weight(g.data(), U.data()); + for (int m = 0; m < 16; ++m) + packed.data[((size_t)ob * 16 + m) * packed.ic * MR + (size_t)c * MR + i] = U[m]; + } + } + } + + class WeightCache { + struct Entry { + CacheKey key; + std::shared_ptr packed; + size_t bytes; + }; + + std::mutex mutex_; + std::list lru_; // front = most recently used + size_t bytes_ = 0; + + public: + std::shared_ptr get(const ggml_tensor* weight, PackKind kind) { + const size_t nbytes = ggml_nbytes(weight); + if (nbytes == 0 || nbytes > CACHE_MAX_ENTRY || weight->type != GGML_TYPE_F16 || + !ggml_is_contiguous(weight)) { + return nullptr; + } + CacheKey key = {}; + key.ptr = weight->data; + for (int i = 0; i < 4; ++i) { + key.ne[i] = weight->ne[i]; + key.nb[i] = weight->nb[i]; + } + key.fingerprint = weight_fingerprint(weight->data, nbytes); + key.kind = int(kind); + { + std::lock_guard lock(mutex_); + for (auto it = lru_.begin(); it != lru_.end(); ++it) { + if (cache_key_equal(it->key, key)) { + lru_.splice(lru_.begin(), lru_, it); + return it->packed; + } + } + } + + auto packed = std::make_shared(); + packed->kind = kind; + packed->kw = int(weight->ne[0]); + packed->kh = int(weight->ne[1]); + packed->ic = int(weight->ne[2]); + packed->oc = int(weight->ne[3]); + packed->k = packed->ic * packed->kh * packed->kw; + packed->oc_pad = (packed->oc + MR - 1) / MR * MR; + const auto* src = static_cast(weight->data); + if (kind == PackKind::kImplicit) { + pack_implicit(src, *packed); + } else { + pack_wino(src, *packed); + } + + { + std::lock_guard lock(mutex_); + for (auto it = lru_.begin(); it != lru_.end(); ++it) { + if (cache_key_equal(it->key, key)) { // packed concurrently + lru_.splice(lru_.begin(), lru_, it); + return it->packed; + } + } + const size_t bytes = packed->bytes(); + while (!lru_.empty() && + (bytes_ + bytes > CACHE_BUDGET || lru_.size() >= CACHE_MAX_ENTRIES)) { + bytes_ -= lru_.back().bytes; + lru_.pop_back(); + } + lru_.push_front({key, packed, bytes}); + bytes_ += bytes; + } + return packed; + } + }; + + WeightCache& weight_cache() { + static WeightCache cache; + return cache; + } + + inline void fma6(__m256 acc[MR][2], const float* wk, __m256 b0, __m256 b1) { + for (int i = 0; i < MR; ++i) { + const __m256 a = _mm256_broadcast_ss(wk + i); + acc[i][0] = _mm256_fmadd_ps(a, b0, acc[i][0]); + acc[i][1] = _mm256_fmadd_ps(a, b1, acc[i][1]); + } + } + + // zero-padded load of 16 consecutive floats starting at row[sx] + inline void load_pair(const float* row, int w, int sx, __m256& b0, __m256& b1) { + if (sx >= 0 && sx + NR <= w) { + b0 = _mm256_loadu_ps(row + sx); + b1 = _mm256_loadu_ps(row + sx + 8); + return; + } + if (sx >= 0 && sx < w) { + const __m256i idx = _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7); + const int n0 = w - sx; + b0 = _mm256_maskload_ps(row + sx, _mm256_cmpgt_epi32(_mm256_set1_epi32(n0), idx)); + b1 = _mm256_maskload_ps(row + sx + 8, _mm256_cmpgt_epi32(_mm256_set1_epi32(n0 - 8), idx)); + return; + } + alignas(32) float tmp[NR] = {0}; + const int lo = std::max(0, -sx), hi = std::min(NR, w - sx); + for (int j = lo; j < hi; ++j) { + tmp[j] = row[sx + j]; + } + b0 = _mm256_load_ps(tmp); + b1 = _mm256_load_ps(tmp + 8); + } + + // generic (stride > 1) tile: gather 16 pixels of one k into buf + inline void gather_px(const float* row, int sx, int w, int stride, float* buf) { + for (int j = 0; j < NR; ++j) { + const int xx = sx + j * stride; + buf[j] = unsigned(xx) < unsigned(w) ? row[xx] : 0.0f; + } + } + + // MR=6 x NR=16 tile over one y-row chunk and one group of oc blocks. + template + void run_rows(const float* src, int ic, int w, int h, int stride, int pad, const float* wp, int k, float* dst, + int m, int ow, int oh, int oc, int ob_begin, int ob_end, int y0, int y1) { + for (int y = y0; y < y1; ++y) { + const int sy0 = y * stride - pad; + const bool row_ok = sy0 >= 0 && sy0 + (KH - 1) < h; + for (int x0 = 0; x0 < ow; x0 += NR) { + const int nx = std::min(NR, ow - x0); + const int sxmin = x0 * stride - pad; + const int sxmax = sxmin + (NR - 1) * stride + (KW - 1); + const bool fast = row_ok && sxmin >= 0 && sxmax < w; + + for (int ob = ob_begin; ob < ob_end; ++ob) { + const int obc = ob * MR; + const float* wpob = wp + size_t(ob) * size_t(k) * MR; + __m256 acc[MR][2]; + for (int i = 0; i < MR; ++i) { + acc[i][0] = _mm256_setzero_ps(); + acc[i][1] = _mm256_setzero_ps(); + } + int kk = 0; + if (fast) { + for (int c = 0; c < ic; ++c) { + const float* rc = src + size_t(c) * size_t(h) * size_t(w); + for (int ky = 0; ky < KH; ++ky) { + const float* r = rc + size_t(sy0 + ky) * w + sxmin; + for (int kx = 0; kx < KW; ++kx) { + const __m256 b0 = _mm256_loadu_ps(r + kx); + const __m256 b1 = _mm256_loadu_ps(r + kx + 8); + fma6(acc, wpob + size_t(kk) * MR, b0, b1); + ++kk; + } + } + } + } else { + alignas(32) float buf[NR]; + for (int c = 0; c < ic; ++c) { + const float* rc = src + size_t(c) * size_t(h) * size_t(w); + for (int ky = 0; ky < KH; ++ky) { + const int sy = sy0 + ky; + const bool ok = unsigned(sy) < unsigned(h); + for (int kx = 0; kx < KW; ++kx) { + const int sx = x0 * stride + kx - pad; + __m256 b0, b1; + if (ok) { + gather_px(rc + size_t(sy) * w, sx, w, stride, buf); + b0 = _mm256_load_ps(buf); + b1 = _mm256_load_ps(buf + 8); + } else { + b0 = _mm256_setzero_ps(); + b1 = _mm256_setzero_ps(); + } + fma6(acc, wpob + size_t(kk) * MR, b0, b1); + ++kk; + } + } + } + } + + const size_t row_off = size_t(y) * ow + x0; + if (nx == NR) { + for (int i = 0; i < MR; ++i) { + const int o = obc + i; + if (o >= oc) break; + float* out = dst + size_t(o) * m + row_off; + _mm256_storeu_ps(out, acc[i][0]); + _mm256_storeu_ps(out + 8, acc[i][1]); + } + } else { + alignas(32) float tmp[NR]; + for (int i = 0; i < MR; ++i) { + const int o = obc + i; + if (o >= oc) break; + _mm256_store_ps(tmp, acc[i][0]); + _mm256_store_ps(tmp + 8, acc[i][1]); + std::memcpy(dst + size_t(o) * m + row_off, tmp, size_t(nx) * sizeof(float)); + } + } + } + } + } + (void) load_pair; + (void) oh; + } + + // Winograd F(2x2,3x3) fast transforms. B/A entries are only 0,+/-1,+/-2, + // so these are add/shift only (verified to ~1e-15 vs float64). + inline void wino_input_tile(const float* d, float* V) { + float t[4][4]; + for (int c = 0; c < 4; ++c) { + t[0][c] = d[0 * 4 + c] - d[2 * 4 + c]; + t[1][c] = d[1 * 4 + c] + d[2 * 4 + c]; + t[2][c] = -d[1 * 4 + c] + d[2 * 4 + c]; + t[3][c] = d[1 * 4 + c] - d[3 * 4 + c]; + } + for (int r = 0; r < 4; ++r) { + V[r * 4 + 0] = t[r][0] - t[r][2]; + V[r * 4 + 1] = t[r][1] + t[r][2]; + V[r * 4 + 2] = -t[r][1] + t[r][2]; + V[r * 4 + 3] = t[r][1] - t[r][3]; + } + } + inline void wino_output_tile(const float* M, float* Y) { + float s0[4], s1[4]; + for (int k = 0; k < 4; ++k) { + s0[k] = M[0 * 4 + k] + M[1 * 4 + k] + M[2 * 4 + k]; + s1[k] = M[1 * 4 + k] - M[2 * 4 + k] - M[3 * 4 + k]; + } + Y[0] = s0[0] + s0[1] + s0[2]; + Y[1] = s0[1] - s0[2] - s0[3]; + Y[2] = s1[0] + s1[1] + s1[2]; + Y[3] = s1[1] - s1[2] - s1[3]; + } + // 6x16 pointwise GEMM: w6[c*6+i], b[k*c + j] where k stride = ldb. + inline void gemm6x16_wino(const float* w6, const float* b, __m256 acc[MR][2], int K, int ldb) { + for (int c = 0; c < K; ++c) { + const __m256 bv0 = _mm256_loadu_ps(b + size_t(c) * ldb); + const __m256 bv1 = _mm256_loadu_ps(b + size_t(c) * ldb + 8); + const float* wk = w6 + size_t(c) * MR; + for (int i = 0; i < MR; ++i) { + const __m256 a = _mm256_broadcast_ss(wk + i); + acc[i][0] = _mm256_fmadd_ps(a, bv0, acc[i][0]); + acc[i][1] = _mm256_fmadd_ps(a, bv1, acc[i][1]); + } + } + } + + struct WinoExecution { + const float* src; + float* dst; + const PackedWeights* packed; + int w, h, ic, oc, ow, oh; + int ntx, nty, ntiles, n_ob, n_tg, n_og, total_tasks; + std::atomic next{0}; + }; + + void build_wino_tasks(WinoExecution& e, int nth) { + (void) nth; + e.ntx = (e.ow + 1) / 2; + e.nty = (e.oh + 1) / 2; + e.ntiles = e.ntx * e.nty; + e.n_ob = e.packed->oc_pad / MR; + constexpr int B = 16; + constexpr int OB_GROUP = 16; + e.n_tg = (e.ntiles + B - 1) / B; + e.n_og = (e.n_ob + OB_GROUP - 1) / OB_GROUP; + e.total_tasks = e.n_tg * e.n_og; + } + + void wino_worker(ggml_tensor*, int ith, int nth, void* user_data) { + auto& e = *static_cast(user_data); + constexpr int B = 16; + constexpr int OB_GROUP = 16; + std::vector Vbuf((size_t)e.ic * 16 * B); + alignas(32) float Mbuf[MR * 16 * B]; + (void) ith; + (void) nth; + for (;;) { + const int task = e.next.fetch_add(1, std::memory_order_relaxed); + if (task >= e.total_tasks) break; + const int tg = task / e.n_og, og = task % e.n_og; + const int t0 = tg * B, t1 = std::min(e.ntiles, t0 + B); + const int nb = t1 - t0; + const int ob0 = og * OB_GROUP, ob1 = std::min(e.n_ob, ob0 + OB_GROUP); + + for (int j = 0; j < nb; ++j) { + const int ty = (t0 + j) / e.ntx, tx = (t0 + j) % e.ntx; + const int iy0 = ty * 2 - 1, ix0 = tx * 2 - 1; + for (int c = 0; c < e.ic; ++c) { + float d[16]; + for (int r = 0; r < 4; ++r) { + const int sy = iy0 + r; + for (int cc = 0; cc < 4; ++cc) { + const int sx = ix0 + cc; + d[r * 4 + cc] = (unsigned(sy) < unsigned(e.h) && unsigned(sx) < unsigned(e.w)) + ? e.src[(size_t)c * e.h * e.w + (size_t)sy * e.w + sx] : 0.f; + } + } + float V[16]; + wino_input_tile(d, V); + for (int m = 0; m < 16; ++m) + Vbuf[((size_t)m * e.ic + c) * B + j] = V[m]; + } + } + for (int ob = ob0; ob < ob1; ++ob) { + __m256 acc[MR][2]; + for (int m = 0; m < 16; ++m) { + for (int i = 0; i < MR; ++i) { acc[i][0] = _mm256_setzero_ps(); acc[i][1] = _mm256_setzero_ps(); } + const float* w6 = e.packed->data.data() + ((size_t)ob * 16 + m) * e.ic * MR; + gemm6x16_wino(w6, Vbuf.data() + (size_t)m * e.ic * B, acc, e.ic, B); + for (int i = 0; i < MR; ++i) { + _mm256_store_ps(Mbuf + (size_t)i * 16 * B + m * B, acc[i][0]); + _mm256_store_ps(Mbuf + (size_t)i * 16 * B + m * B + 8, acc[i][1]); + } + } + for (int i = 0; i < MR; ++i) { + const int o = ob * MR + i; + if (o >= e.oc) break; + for (int j = 0; j < nb; ++j) { + float Mtile[16]; + for (int m = 0; m < 16; ++m) Mtile[m] = Mbuf[(size_t)i * 16 * B + m * B + j]; + float Y[4]; + wino_output_tile(Mtile, Y); + const int ty = (t0 + j) / e.ntx, tx = (t0 + j) % e.ntx; + for (int ry = 0; ry < 2; ++ry) + for (int rx = 0; rx < 2; ++rx) { + const int dy = ty * 2 + ry, dx = tx * 2 + rx; + if (dy < e.oh && dx < e.ow) + e.dst[(size_t)o * e.ow * e.oh + (size_t)dy * e.ow + dx] = Y[ry * 2 + rx]; + } + } + } + } + } + } + + struct Job { + int src_off = 0; // elements to the first input pixel of this batch + int dst_off = 0; // elements to the first output pixel of this batch + int y0, y1; + int ob_begin, ob_end; + }; + + struct Execution { + const float* src; + float* dst; + const PackedWeights* packed; + int w, h, ow, oh, pad, m; + int n_ob, n_yc, n_batch; + std::vector jobs; + std::once_flag jobs_built; + std::atomic next{0}; + }; + + void build_jobs(Execution& e, int nth) { + const int tmax = TASK_TARGET * nth; + const int ng = std::max(1, std::min(std::min(e.n_ob, OB_GROUP), std::max(1, tmax / e.n_yc))); + const int g = (e.n_ob + ng - 1) / ng; + const int n_og = (e.n_ob + g - 1) / g; + e.jobs.reserve(size_t(e.n_batch) * size_t(n_og) * size_t(e.n_yc)); + for (int batch = 0; batch < e.n_batch; ++batch) { + for (int yc = 0; yc < e.n_yc; ++yc) { + const int y0 = yc * YCH, y1 = std::min(e.oh, y0 + YCH); + for (int og = 0; og < n_og; ++og) { + const int ob0 = og * g, ob1 = std::min(e.n_ob, ob0 + g); + Job job = {}; + job.src_off = int(size_t(batch) * size_t(e.packed->ic) * size_t(e.w) * size_t(e.h)); + job.dst_off = int(size_t(batch) * size_t(e.packed->oc) * size_t(e.m)); + job.y0 = y0; + job.y1 = y1; + job.ob_begin = ob0; + job.ob_end = ob1; + e.jobs.push_back(job); + } + } + } + } + + void conv2d_worker(ggml_tensor*, int ith, int nth, void* user_data) { + auto& e = *static_cast(user_data); + const auto& p = *e.packed; + std::call_once(e.jobs_built, build_jobs, std::ref(e), std::max(1, nth)); + const int total = int(e.jobs.size()); + for (int t = e.next.fetch_add(1, std::memory_order_relaxed); t < total; + t = e.next.fetch_add(1, std::memory_order_relaxed)) { + const auto& job = e.jobs[size_t(t)]; + if (p.kw == 3 && p.kh == 3) { + run_rows<3, 3>(e.src + job.src_off, p.ic, e.w, e.h, 1, e.pad, p.data.data(), p.k, e.dst + job.dst_off, + e.m, e.ow, e.oh, p.oc, job.ob_begin, job.ob_end, job.y0, job.y1); + } else if (p.kw == 1 && p.kh == 1) { + run_rows<1, 1>(e.src + job.src_off, p.ic, e.w, e.h, 1, e.pad, p.data.data(), p.k, e.dst + job.dst_off, + e.m, e.ow, e.oh, p.oc, job.ob_begin, job.ob_end, job.y0, job.y1); + } + } + (void) ith; + } + + bool conv2d_shape(const ggml_tensor* node, int& w, int& h, int& ic, int& oc, int& kw, int& kh, int& stride, + int& pad) { + const ggml_tensor* kernel = node->src[0]; + const ggml_tensor* input = node->src[1]; + if (kernel == nullptr || input == nullptr || node->type != GGML_TYPE_F32) { + return false; + } + if (kernel->type != GGML_TYPE_F16 || input->type != GGML_TYPE_F32) { + return false; + } + // Weights are always 4-D; activations may be 3-D (single-image VAE decode, + // implicit batch) or 4-D. Trailing singleton dims are not stored in ne[]. + if (ggml_n_dims(kernel) != 4 || ggml_n_dims(input) < 3 || ggml_n_dims(input) > 4 || + ggml_n_dims(node) < 3 || ggml_n_dims(node) > 4) { + return false; + } + if (!ggml_is_contiguous(kernel) || !ggml_is_contiguous(input) || !ggml_is_contiguous(node)) { + return false; + } + int32_t params[6]; + std::memcpy(params, node->op_params, sizeof(params)); + const int s0 = params[0], s1 = params[1], p0 = params[2], p1 = params[3]; + const int d0 = params[4], d1 = params[5]; + if (s0 != 1 || s1 != 1 || d0 != 1 || d1 != 1 || p0 != p1) { + return false; + } + kw = int(kernel->ne[0]); + kh = int(kernel->ne[1]); + ic = int(kernel->ne[2]); + oc = int(kernel->ne[3]); + if (!((kw == 3 && kh == 3 && p0 <= 1) || (kw == 1 && kh == 1 && p0 == 0))) { + return false; + } + if (input->ne[2] != ic || node->ne[2] != oc || node->ne[3] != input->ne[3]) { + return false; + } + w = int(input->ne[0]); + h = int(input->ne[1]); + stride = s0; + pad = p0; + return true; + } + + // Three-way mutually exclusive dispatch, all via the same extension kernel: + // wino : 3x3 / stride1 / pad1 / dil1 / F16+F32 / ic,oc>=256 / spatial>=32^2 + // v1 : up.0 (oc=128 && spatial>=128^2) or conv_out (oc<=16 && spatial>=64^2) + // else : native ggml (decline the node) + enum class ConvRoute { kNone, kV1, kWino }; + ConvRoute conv2d_route(const ggml_tensor* node) { + if (getenv("SD_CONV2D_DISABLE")) return ConvRoute::kNone; + if (!ggml_cpu_has_avx2() || !ggml_cpu_has_fma()) return ConvRoute::kNone; + int w, h, ic, oc, kw, kh, stride, pad; + if (!conv2d_shape(node, w, h, ic, oc, kw, kh, stride, pad)) return ConvRoute::kNone; + const int64_t spatial = node->ne[0] * node->ne[1]; + const int64_t k = int64_t(ic) * kh * kw; + const bool wino = kw == 3 && kh == 3 && pad == 1 && ic >= 256 && oc >= 256 && + spatial >= 32 * 32 && !getenv("SD_CONV2D_NO_WINOGRAD"); + const bool v1 = (spatial >= SPATIAL_BIG && k >= K_MIN) || + (oc <= OC_SMALL && spatial >= SPATIAL_SMALL); + if (getenv("SD_CONV2D_TRACE")) { + fprintf(stderr, "conv2d_v2 supports: oc=%d %dx%d k=%dx%d spatial=%lld route=%d\n", oc, w, h, + kw, kh, (long long)spatial, int(wino ? ConvRoute::kWino : v1 ? ConvRoute::kV1 : ConvRoute::kNone)); + } + return wino ? ConvRoute::kWino : v1 ? ConvRoute::kV1 : ConvRoute::kNone; + } + + bool conv2d_supports(ggml_backend_dev_t, const ggml_tensor* node, void*) { + return conv2d_route(node) != ConvRoute::kNone; + } + + bool conv2d_preferred(ggml_backend_dev_t device, const ggml_tensor* node, void* user_data) { + return conv2d_supports(device, node, user_data); + } + + ggml_status conv2d_execute(const ggml_ext_execution_context* context, ggml_tensor* const* nodes, int, + void*, void*) { + auto* dst = nodes[0]; + const ggml_tensor* kernel = dst->src[0]; + const ggml_tensor* input = dst->src[1]; + int w, h, ic, oc, kw, kh, stride, pad; + if (!conv2d_shape(dst, w, h, ic, oc, kw, kh, stride, pad)) { + return GGML_STATUS_FAILED; + } + const ConvRoute route = conv2d_route(dst); + if (route == ConvRoute::kNone) { + return GGML_STATUS_FAILED; + } + if (getenv("SD_CONV2D_TRACE")) { + fprintf(stderr, "conv2d_v2: ic=%d oc=%d %dx%d k=%dx%d pad=%d route=%d\n", ic, oc, w, h, kw, kh, pad, int(route)); + } + auto packed = weight_cache().get(kernel, route == ConvRoute::kWino ? PackKind::kWino : PackKind::kImplicit); + if (!packed) { + return GGML_STATUS_FAILED; + } + auto reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(context->backend)); + auto run = reinterpret_cast( + ggml_backend_reg_get_proc_address(reg, "ggml_ext_cpu_parallel_v1")); + if (!run) { + return GGML_STATUS_FAILED; + } + const int ow = int(dst->ne[0]), oh = int(dst->ne[1]); + + // The ggml CPU planner never aliases a fresh CONV_2D output with its inputs. + const uintptr_t d0 = reinterpret_cast(dst->data); + const uintptr_t s0 = reinterpret_cast(input->data); + if (d0 < s0 + ggml_nbytes(input) && s0 < d0 + ggml_nbytes(dst)) { + return GGML_STATUS_FAILED; + } + + if (route == ConvRoute::kWino) { + WinoExecution e = {}; + e.src = static_cast(input->data); + e.dst = static_cast(dst->data); + e.packed = packed.get(); + e.w = w; + e.h = h; + e.ic = ic; + e.oc = oc; + e.ow = ow; + e.oh = oh; + build_wino_tasks(e, 1); + return run(context->backend, dst, wino_worker, &e); + } + + Execution e = {}; + e.src = static_cast(input->data); + e.dst = static_cast(dst->data); + e.packed = packed.get(); + e.w = w; + e.h = h; + e.ow = ow; + e.oh = oh; + e.pad = pad; + e.m = ow * oh; + e.n_ob = packed->oc_pad / MR; + e.n_yc = (oh + YCH - 1) / YCH; + e.n_batch = int(dst->ne[3]); + return run(context->backend, dst, conv2d_worker, &e); + } + + void register_conv2d(ggml_backend_dev_t device) { + // A device may be visited by both the init-time registration and a lazy + // per-op registration; registering the same name twice returns false, so + // make it idempotent instead of asserting. + static std::mutex reg_mutex; + static std::vector registered; + { + std::lock_guard lock(reg_mutex); + if (std::find(registered.begin(), registered.end(), device) != registered.end()) { + return; + } + registered.push_back(device); + } + ggml_ext_kernel_desc desc = {}; + desc.abi_version = GGML_EXT_ABI_VERSION; + desc.name = "sd.conv2d_avx2_v1.cpu"; + desc.op = GGML_OP_CONV_2D; + desc.priority = 100; + desc.supports = conv2d_supports; + desc.preferred = conv2d_preferred; + desc.execute = conv2d_execute; + GGML_ASSERT(ggml_ext_register_kernel(device, &desc)); + } + + } // namespace + + void register_conv2d_avx2(ggml_backend_dev_t device) { + if (getenv("SD_CONV2D_TRACE")) { + fprintf(stderr, "conv2d_v1 register: device=%p\n", (void*) device); + } + register_conv2d(device); + } +} // namespace sd_cpu + +#if defined(__GNUC__) && !defined(__clang__) +#pragma GCC pop_options +#elif defined(__clang__) +#pragma clang attribute pop +#endif +#endif // avx2 enabled build guard +#endif // !SD_USE_UPSTREAM_GGML diff --git a/src/core/cpu/registration.cpp b/src/core/cpu/registration.cpp index 16e13dfe2..e8ea25bd9 100644 --- a/src/core/cpu/registration.cpp +++ b/src/core/cpu/registration.cpp @@ -8,6 +8,7 @@ namespace sd_cpu { register_w4(device); register_rope(device); register_modulate(device); + register_conv2d_avx2(device); } } diff --git a/src/core/cpu/registration.h b/src/core/cpu/registration.h index 77f4bacfb..805b7ee47 100644 --- a/src/core/cpu/registration.h +++ b/src/core/cpu/registration.h @@ -10,6 +10,7 @@ namespace sd_cpu { void register_modulate(ggml_backend_dev_t device); void register_i8(ggml_backend_dev_t device); void register_w4(ggml_backend_dev_t device); + void register_conv2d_avx2(ggml_backend_dev_t device); } #endif