From 65daec54ce19ea2e8bbfd234fe3149f2c1f88d41 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 1 Dec 2026 21:42:19 -0800 Subject: [PATCH 1/3] MiniMax-H3 VAE encoder: per-frame GroupNorm on backends whose GroupNorm covers one dim-3 slice The batched encoder fallback from #110 folds frames x batch into ggml dim 3 and issues one GROUP_NORM. The pinned ggml SYCL and OpenCL GroupNorm kernels launch num_groups work groups over ne0*ne1*ne2 elements, so every frame after the first is left unwritten (the OpenCL GroupNorm+mul+add fusion also takes its group size from the whole tensor). Fold only on backends whose GroupNorm handles every dim-3 slice (CPU, CUDA, ROCm, MUSA, Metal, Vulkan); elsewhere issue one GROUP_NORM per frame and batch item. The CPU / CUDA / ROCm / Metal / Vulkan graphs are unchanged. --- scripts/minimax_h3_frame_group_norm_test.cpp | 291 +++++++++++++++++++ src/core/ggml_extend.cpp | 22 ++ src/core/ggml_extend.h | 5 + src/model/vae/minimax_h3_vae.hpp | 26 ++ 4 files changed, 344 insertions(+) create mode 100644 scripts/minimax_h3_frame_group_norm_test.cpp diff --git a/scripts/minimax_h3_frame_group_norm_test.cpp b/scripts/minimax_h3_frame_group_norm_test.cpp new file mode 100644 index 0000000000..93e12b71d3 --- /dev/null +++ b/scripts/minimax_h3_frame_group_norm_test.cpp @@ -0,0 +1,291 @@ +// MiniMax-H3 VAE encoder TemporalGroupNorm: every frame must be its own GroupNorm item on every backend. +// +// Build (after `cmake -B build-cpu -DSD_WEBP=OFF -DSD_WEBM=OFF && cmake --build build-cpu`), then run the binary: +// g++ -std=c++17 -O1 -DGGML_MAX_NAME=160 -DGGML_USE_CPU -DSD_GGML_FUSED_ROPE_ATTN -DSD_GGML_H3_FUSED_OPS \ +// -DSD_GGML_H3_FUSED_QK_NORM -I src -I include -I ggml/include -I ggml/src -I thirdparty \ +// scripts/minimax_h3_frame_group_norm_test.cpp build-cpu/libstable-diffusion.a build-cpu/ggml/src/libggml.a \ +// build-cpu/ggml/src/libggml-cpu.a build-cpu/ggml/src/libggml-base.a -fopenmp -lpthread -ldl \ +// -o build-cpu/minimax_h3_frame_group_norm_test +// +// The batched path folds frames x batch into ggml dim 3 and issues one GROUP_NORM. That is only valid where the +// backend normalises every dim-3 slice. The pinned ggml SYCL and OpenCL GroupNorm kernels launch num_groups work +// groups over ne0*ne1*ne2 elements (one slice), so on them every slice after the first is left unwritten. +// emulate_single_slice_group_norm() below reproduces that launch on the host. +#include +#include +#include +#include +#include +#include + +#include "ggml-backend-impl.h" +#include "ggml-cpu.h" +#include "model/vae/minimax_h3_vae.hpp" + +static int failures = 0; +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL %s:%d %s\n", __FILE__, __LINE__, #cond); \ + failures++; \ + } \ + } while (0) + +// A backend object that only answers "which ggml backend registry is this", which is all graph building reads. +struct NamedBackend { + ggml_backend_reg reg{}; + ggml_backend_device dev{}; + ggml_backend backend{}; + const char* name; + + explicit NamedBackend(const char* n) + : name(n) { + reg.context = this; + reg.iface.get_name = [](ggml_backend_reg_t r) { return static_cast(r->context)->name; }; + dev.reg = ® + backend.device = &dev; + } +}; + +struct Case { + int64_t w, h, frames, channels, batch; +}; + +static void fill(ggml_tensor* t, std::mt19937& rng, float lo, float hi) { + std::uniform_real_distribution dist(lo, hi); + auto* p = (float*)t->data; + for (int64_t i = 0; i < ggml_nelements(t); i++) { + p[i] = dist(rng); + } +} + +// FP64 oracle: x is [w, h, frames, channels * batch]; groups of channels per (frame, batch item). +static std::vector oracle(const Case& c, const float* x, const float* wt, const float* bs, int groups, float eps) { + std::vector y((size_t)(c.w * c.h * c.frames * c.channels * c.batch)); + const int64_t cpg = c.channels / groups; + const int64_t plane = c.w * c.h; + auto idx = [&](int64_t b, int64_t ch, int64_t f, int64_t p) { + return (size_t)(((b * c.channels + ch) * c.frames + f) * plane + p); + }; + for (int64_t b = 0; b < c.batch; b++) { + for (int64_t f = 0; f < c.frames; f++) { + for (int64_t g = 0; g < groups; g++) { + double sum = 0, sq = 0; + for (int64_t ch = g * cpg; ch < (g + 1) * cpg; ch++) { + for (int64_t p = 0; p < plane; p++) { + sum += x[idx(b, ch, f, p)]; + } + } + const double n = (double)(cpg * plane); + const double mean = sum / n; + for (int64_t ch = g * cpg; ch < (g + 1) * cpg; ch++) { + for (int64_t p = 0; p < plane; p++) { + const double d = x[idx(b, ch, f, p)] - mean; + sq += d * d; + } + } + const double inv = 1.0 / std::sqrt(sq / n + eps); + for (int64_t ch = g * cpg; ch < (g + 1) * cpg; ch++) { + for (int64_t p = 0; p < plane; p++) { + const size_t i = idx(b, ch, f, p); + y[i] = (float)((x[i] - mean) * inv * wt[ch] + bs[ch]); + } + } + } + } + } + return y; +} + +// Host replay of the pinned ggml SYCL / OpenCL GROUP_NORM launch: num_groups work groups over ne0*ne1*ne2 elements. +static size_t emulate_single_slice_group_norm(const ggml_tensor* src, int groups, std::vector& out) { + const int64_t ne = src->ne[0] * src->ne[1] * src->ne[2]; + const int64_t group_size = src->ne[0] * src->ne[1] * ((src->ne[2] + groups - 1) / groups); + out.assign((size_t)ggml_nelements(src), std::numeric_limits::quiet_NaN()); + const float* x = (const float*)src->data; + for (int g = 0; g < groups; g++) { + const int64_t start = g * group_size, end = std::min(start + group_size, ne); + double mean = 0, var = 0; + for (int64_t j = start; j < end; j++) + mean += x[j]; + mean /= group_size; + for (int64_t j = start; j < end; j++) + var += (x[j] - mean) * (x[j] - mean); + const double inv = 1.0 / std::sqrt(var / group_size + 1e-6); + for (int64_t j = start; j < end; j++) + out[(size_t)j] = (float)((x[j] - mean) * inv); + } + size_t unwritten = 0; + for (float v : out) + unwritten += std::isnan(v) ? 1 : 0; + return unwritten; +} + +struct Built { + ggml_context* ctx = nullptr; + ggml_tensor* x = nullptr; + ggml_tensor* y = nullptr; + ggml_cgraph* gf = nullptr; +}; + +static Built build(const Case& c, ggml_backend_t backend, MiniMaxH3VAE::TemporalGroupNorm& norm, uint32_t seed) { + Built b; + ggml_init_params ip{(size_t)1 << 30, nullptr, false}; + b.ctx = ggml_init(ip); + norm.init(b.ctx); + std::mt19937 rng(seed); + std::map params; + norm.get_param_tensors(params, ""); + fill(params.at("weight"), rng, 0.5f, 1.5f); + fill(params.at("bias"), rng, -0.5f, 0.5f); + b.x = ggml_new_tensor_4d(b.ctx, GGML_TYPE_F32, c.w, c.h, c.frames, c.channels * c.batch); + // Per-frame offsets, so a GroupNorm that mixes or skips frames cannot pass by accident. + std::uniform_real_distribution dist(-1.f, 1.f); + auto* p = (float*)b.x->data; + for (int64_t i = 0; i < ggml_nelements(b.x); i++) { + const int64_t f = (i / (c.w * c.h)) % c.frames; + p[i] = dist(rng) * (1.f + f) + 3.f * f; + } + GGMLRunnerContext rc; + rc.ggml_ctx = b.ctx; + rc.backend = backend; + b.y = norm.forward(&rc, b.x); + b.gf = ggml_new_graph_custom(b.ctx, 8192, false); + ggml_build_forward_expand(b.gf, b.y); + return b; +} + +// Largest dim-3 extent any GROUP_NORM node in the graph sees. +static int64_t max_group_norm_ne3(ggml_cgraph* gf, int* count) { + int64_t m = 0; + *count = 0; + for (int i = 0; i < ggml_graph_n_nodes(gf); i++) { + ggml_tensor* n = ggml_graph_node(gf, i); + if (n->op == GGML_OP_GROUP_NORM) { + (*count)++; + m = std::max(m, n->src[0]->ne[3]); + } + } + return m; +} + +static void check_numerics(const char* label, const Case& c, Built& b, MiniMaxH3VAE::TemporalGroupNorm& norm) { + std::map params; + norm.get_param_tensors(params, ""); + ggml_graph_compute_with_ctx(b.ctx, b.gf, 4); + auto ref = oracle(c, (const float*)b.x->data, (const float*)params.at("weight")->data, + (const float*)params.at("bias")->data, 32, 1e-6f); + const float* y = (const float*)b.y->data; + double max_err = 0; + for (size_t i = 0; i < ref.size(); i++) { + const double e = std::fabs((double)y[i] - ref[i]); + max_err = std::isnan(e) ? INFINITY : std::max(max_err, e); + } + uint64_t hash = 1469598103934665603ull; // FNV-1a of the output bytes, to compare builds + for (size_t i = 0; i < ggml_nbytes(b.y); i++) { + hash = (hash ^ ((const uint8_t*)b.y->data)[i]) * 1099511628211ull; + } + std::printf(" %-8s numerics vs fp64 per-frame oracle: max abs err %.3g, output fnv1a %016llx\n", label, max_err, + (unsigned long long)hash); + CHECK(max_err < 1e-4); +} + +int main() { + ggml_backend_t cpu = ggml_backend_cpu_init(); + NamedBackend sycl("SYCL"), opencl("OpenCL"), unknown("SomeFutureBackend"); + NamedBackend cuda("CUDA"), rocm("ROCm"), musa("MUSA"), metal("MTL"), vulkan("Vulkan"); + + const Case cases[] = { + {8, 6, 5, 64, 1}, // ordinary single-clip video chunk + {7, 5, 3, 64, 2}, // batch two + {9, 4, 1, 64, 1}, // single frame keeps one GroupNorm on every backend + }; + for (const auto& c : cases) { + std::printf("case w=%lld h=%lld frames=%lld channels=%lld batch=%lld\n", (long long)c.w, (long long)c.h, + (long long)c.frames, (long long)c.channels, (long long)c.batch); + + // 1. Backends whose GroupNorm is per-slice keep the single batched node (byte-identical to the merged path). + struct { + const char* label; + ggml_backend_t be; + } batched[] = { + {"CPU", cpu}, + {"CUDA", &cuda.backend}, + {"ROCm", &rocm.backend}, + {"MUSA", &musa.backend}, + {"MTL", &metal.backend}, + {"Vulkan", &vulkan.backend}, + }; + for (auto& k : batched) { + MiniMaxH3VAE::TemporalGroupNorm norm(c.channels); + Built b = build(c, k.be, norm, 1234); + int n = 0; + const int64_t ne3 = max_group_norm_ne3(b.gf, &n); + std::printf(" %-8s GROUP_NORM nodes=%d max ne3=%lld\n", k.label, n, (long long)ne3); + CHECK(n == 1); + CHECK(ne3 == c.frames * c.batch); + if (k.be == cpu) { + // CPU really runs it here: the batched node is correct on the pinned ggml CPU backend. + check_numerics(k.label, c, b, norm); + } + ggml_free(b.ctx); + } + + // 2. Backends whose GroupNorm only covers dim-3 slice 0 must never see a folded tensor. + struct { + const char* label; + ggml_backend_t be; + } per_frame[] = { + {"SYCL", &sycl.backend}, + {"OpenCL", &opencl.backend}, + {"unknown", &unknown.backend}, + }; + for (auto& k : per_frame) { + MiniMaxH3VAE::TemporalGroupNorm norm(c.channels); + Built b = build(c, k.be, norm, 1234); + int n = 0; + const int64_t ne3 = max_group_norm_ne3(b.gf, &n); + std::printf(" %-8s GROUP_NORM nodes=%d max ne3=%lld\n", k.label, n, (long long)ne3); + CHECK(ne3 == 1); + CHECK(n == (int)(c.frames * c.batch)); + // Every GROUP_NORM node this backend receives is fully written by its single-slice launch. + for (int i = 0; i < ggml_graph_n_nodes(b.gf); i++) { + ggml_tensor* node = ggml_graph_node(b.gf, i); + if (node->op == GGML_OP_GROUP_NORM) { + std::vector out; + // shapes only: emulate on a zero-filled stand-in of the node's shape + ggml_init_params ip{(size_t)ggml_nbytes(node->src[0]) + 1024, nullptr, false}; + ggml_context* tmp = ggml_init(ip); + ggml_tensor* s = ggml_new_tensor(tmp, GGML_TYPE_F32, 4, node->src[0]->ne); + std::memset(s->data, 0, ggml_nbytes(s)); + CHECK(emulate_single_slice_group_norm(s, 32, out) == 0); + ggml_free(tmp); + } + } + // The per-frame graph is numerically right too (computed on CPU). + check_numerics(k.label, c, b, norm); + ggml_free(b.ctx); + } + + // 3. The emulated single-slice launch on the folded layout leaves every frame after the first unwritten. + if (c.frames * c.batch > 1) { + ggml_init_params ip{(size_t)64 << 20, nullptr, false}; + ggml_context* tmp = ggml_init(ip); + ggml_tensor* s = ggml_new_tensor_4d(tmp, GGML_TYPE_F32, c.w, c.h, c.channels, c.frames * c.batch); + std::memset(s->data, 0, ggml_nbytes(s)); + std::vector out; + const size_t unwritten = emulate_single_slice_group_norm(s, 32, out); + std::printf(" folded layout on a single-slice GroupNorm: %zu of %lld elements unwritten\n", unwritten, + (long long)ggml_nelements(s)); + CHECK(unwritten == (size_t)(c.w * c.h * c.channels * (c.frames * c.batch - 1))); + ggml_free(tmp); + } + } + ggml_backend_free(cpu); + if (failures) { + std::fprintf(stderr, "%d check(s) failed\n", failures); + return 1; + } + std::printf("all checks passed\n"); + return 0; +} diff --git a/src/core/ggml_extend.cpp b/src/core/ggml_extend.cpp index 9a119f9eb9..a60af1b018 100644 --- a/src/core/ggml_extend.cpp +++ b/src/core/ggml_extend.cpp @@ -1,6 +1,7 @@ #include "core/ggml_extend.h" #include +#include #include #include #include @@ -914,6 +915,27 @@ ggml_tensor* ggml_ext_group_norm(GGMLRunnerContext* runner_ctx, return x; } +bool ggml_ext_group_norm_batches_dim3(ggml_backend_t backend) { + if (backend == nullptr) { + return false; + } + auto device = ggml_backend_get_device(backend); + auto reg = device != nullptr ? ggml_backend_dev_backend_reg(device) : nullptr; + if (reg == nullptr) { + return false; + } + // CPU loops over dim 3; CUDA / ROCm / MUSA and Vulkan launch num_groups * ne3 groups; Metal dispatches + // (num_groups, ne3) threadgroups since leejet/ggml a70d9e12. + static const char* const per_slice[] = {"CPU", "CUDA", "ROCm", "MUSA", "MTL", "Vulkan"}; + const char* name = ggml_backend_reg_name(reg); + for (const char* ok : per_slice) { + if (name != nullptr && std::strcmp(name, ok) == 0) { + return true; + } + } + return false; +} + ggml_tensor* ggml_ext_timestep_embedding(GGMLRunnerContext* runner_ctx, ggml_tensor* timesteps, int dim, diff --git a/src/core/ggml_extend.h b/src/core/ggml_extend.h index c3d1c42fb9..60e2064a0f 100644 --- a/src/core/ggml_extend.h +++ b/src/core/ggml_extend.h @@ -220,6 +220,11 @@ ggml_tensor* ggml_ext_group_norm(GGMLRunnerContext* runner_ctx, int num_groups = 32, float eps = 1e-6f); +// True when the backend's GROUP_NORM normalises every dim-3 slice on its own, so independent items (frames, +// batch) may be folded into dim 3 and normalised in one op. The pinned ggml SYCL and OpenCL kernels cover only +// slice 0, and backends not listed here are unverified, so they get one GROUP_NORM per item instead. +bool ggml_ext_group_norm_batches_dim3(ggml_backend_t backend); + ggml_tensor* ggml_ext_timestep_embedding(GGMLRunnerContext* runner_ctx, ggml_tensor* timesteps, int dim, diff --git a/src/model/vae/minimax_h3_vae.hpp b/src/model/vae/minimax_h3_vae.hpp index 1adefbfad3..8c5121c640 100644 --- a/src/model/vae/minimax_h3_vae.hpp +++ b/src/model/vae/minimax_h3_vae.hpp @@ -178,6 +178,9 @@ namespace MiniMaxH3VAE { const int64_t planes = x->ne[3]; GGML_ASSERT(planes % num_channels == 0); const int64_t batch = planes / num_channels; + if (!ggml_ext_group_norm_batches_dim3(ctx->backend)) { + return forward_per_item(ctx, x, batch); + } if (frames == 1) { x = ggml_reshape_4d(c, ggml_ext_cont(ctx, x), width, height, num_channels, batch); x = GroupNorm::forward(ctx, x); @@ -192,6 +195,29 @@ namespace MiniMaxH3VAE { x = ggml_cont(c, ggml_permute(c, x, 0, 2, 1, 3)); return ggml_reshape_4d(c, x, width, height, frames, planes); } + + private: + // One GROUP_NORM per frame and batch item, for backends whose GroupNorm covers only dim-3 slice 0. + ggml_tensor* forward_per_item(GGMLRunnerContext* ctx, ggml_tensor* x, int64_t batch) { + auto c = ctx->ggml_ctx; + ggml_tensor* result = nullptr; + for (int64_t t = 0; t < x->ne[2]; ++t) { + auto frame = ggml_ext_slice(ctx, x, 2, t, t + 1); + frame = ggml_cont(c, frame); + frame = ggml_reshape_4d(c, frame, frame->ne[0], frame->ne[1], num_channels, batch); + ggml_tensor* normed = nullptr; + for (int64_t b = 0; b < batch; ++b) { + auto item = batch == 1 ? frame + : ggml_view_4d(c, frame, frame->ne[0], frame->ne[1], frame->ne[2], 1, + frame->nb[1], frame->nb[2], frame->nb[3], b * frame->nb[3]); + item = GroupNorm::forward(ctx, item); + normed = normed == nullptr ? item : ggml_concat(c, normed, item, 3); + } + frame = ggml_reshape_4d(c, normed, frame->ne[0], frame->ne[1], 1, num_channels * batch); + result = result == nullptr ? frame : ggml_concat(c, result, frame, 2); + } + return result; + } }; struct Downsample3D : public GGMLBlock { From 43ebb25159e9719149a0dbe041bc87662c386364 Mon Sep 17 00:00:00 2001 From: Daniel Han <23090290+danielhanchen@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:45:57 -0800 Subject: [PATCH 2/3] Keep the GroupNorm regression test local, per CONTRIBUTING --- scripts/minimax_h3_frame_group_norm_test.cpp | 291 ------------------- 1 file changed, 291 deletions(-) delete mode 100644 scripts/minimax_h3_frame_group_norm_test.cpp diff --git a/scripts/minimax_h3_frame_group_norm_test.cpp b/scripts/minimax_h3_frame_group_norm_test.cpp deleted file mode 100644 index 93e12b71d3..0000000000 --- a/scripts/minimax_h3_frame_group_norm_test.cpp +++ /dev/null @@ -1,291 +0,0 @@ -// MiniMax-H3 VAE encoder TemporalGroupNorm: every frame must be its own GroupNorm item on every backend. -// -// Build (after `cmake -B build-cpu -DSD_WEBP=OFF -DSD_WEBM=OFF && cmake --build build-cpu`), then run the binary: -// g++ -std=c++17 -O1 -DGGML_MAX_NAME=160 -DGGML_USE_CPU -DSD_GGML_FUSED_ROPE_ATTN -DSD_GGML_H3_FUSED_OPS \ -// -DSD_GGML_H3_FUSED_QK_NORM -I src -I include -I ggml/include -I ggml/src -I thirdparty \ -// scripts/minimax_h3_frame_group_norm_test.cpp build-cpu/libstable-diffusion.a build-cpu/ggml/src/libggml.a \ -// build-cpu/ggml/src/libggml-cpu.a build-cpu/ggml/src/libggml-base.a -fopenmp -lpthread -ldl \ -// -o build-cpu/minimax_h3_frame_group_norm_test -// -// The batched path folds frames x batch into ggml dim 3 and issues one GROUP_NORM. That is only valid where the -// backend normalises every dim-3 slice. The pinned ggml SYCL and OpenCL GroupNorm kernels launch num_groups work -// groups over ne0*ne1*ne2 elements (one slice), so on them every slice after the first is left unwritten. -// emulate_single_slice_group_norm() below reproduces that launch on the host. -#include -#include -#include -#include -#include -#include - -#include "ggml-backend-impl.h" -#include "ggml-cpu.h" -#include "model/vae/minimax_h3_vae.hpp" - -static int failures = 0; -#define CHECK(cond) \ - do { \ - if (!(cond)) { \ - std::fprintf(stderr, "FAIL %s:%d %s\n", __FILE__, __LINE__, #cond); \ - failures++; \ - } \ - } while (0) - -// A backend object that only answers "which ggml backend registry is this", which is all graph building reads. -struct NamedBackend { - ggml_backend_reg reg{}; - ggml_backend_device dev{}; - ggml_backend backend{}; - const char* name; - - explicit NamedBackend(const char* n) - : name(n) { - reg.context = this; - reg.iface.get_name = [](ggml_backend_reg_t r) { return static_cast(r->context)->name; }; - dev.reg = ® - backend.device = &dev; - } -}; - -struct Case { - int64_t w, h, frames, channels, batch; -}; - -static void fill(ggml_tensor* t, std::mt19937& rng, float lo, float hi) { - std::uniform_real_distribution dist(lo, hi); - auto* p = (float*)t->data; - for (int64_t i = 0; i < ggml_nelements(t); i++) { - p[i] = dist(rng); - } -} - -// FP64 oracle: x is [w, h, frames, channels * batch]; groups of channels per (frame, batch item). -static std::vector oracle(const Case& c, const float* x, const float* wt, const float* bs, int groups, float eps) { - std::vector y((size_t)(c.w * c.h * c.frames * c.channels * c.batch)); - const int64_t cpg = c.channels / groups; - const int64_t plane = c.w * c.h; - auto idx = [&](int64_t b, int64_t ch, int64_t f, int64_t p) { - return (size_t)(((b * c.channels + ch) * c.frames + f) * plane + p); - }; - for (int64_t b = 0; b < c.batch; b++) { - for (int64_t f = 0; f < c.frames; f++) { - for (int64_t g = 0; g < groups; g++) { - double sum = 0, sq = 0; - for (int64_t ch = g * cpg; ch < (g + 1) * cpg; ch++) { - for (int64_t p = 0; p < plane; p++) { - sum += x[idx(b, ch, f, p)]; - } - } - const double n = (double)(cpg * plane); - const double mean = sum / n; - for (int64_t ch = g * cpg; ch < (g + 1) * cpg; ch++) { - for (int64_t p = 0; p < plane; p++) { - const double d = x[idx(b, ch, f, p)] - mean; - sq += d * d; - } - } - const double inv = 1.0 / std::sqrt(sq / n + eps); - for (int64_t ch = g * cpg; ch < (g + 1) * cpg; ch++) { - for (int64_t p = 0; p < plane; p++) { - const size_t i = idx(b, ch, f, p); - y[i] = (float)((x[i] - mean) * inv * wt[ch] + bs[ch]); - } - } - } - } - } - return y; -} - -// Host replay of the pinned ggml SYCL / OpenCL GROUP_NORM launch: num_groups work groups over ne0*ne1*ne2 elements. -static size_t emulate_single_slice_group_norm(const ggml_tensor* src, int groups, std::vector& out) { - const int64_t ne = src->ne[0] * src->ne[1] * src->ne[2]; - const int64_t group_size = src->ne[0] * src->ne[1] * ((src->ne[2] + groups - 1) / groups); - out.assign((size_t)ggml_nelements(src), std::numeric_limits::quiet_NaN()); - const float* x = (const float*)src->data; - for (int g = 0; g < groups; g++) { - const int64_t start = g * group_size, end = std::min(start + group_size, ne); - double mean = 0, var = 0; - for (int64_t j = start; j < end; j++) - mean += x[j]; - mean /= group_size; - for (int64_t j = start; j < end; j++) - var += (x[j] - mean) * (x[j] - mean); - const double inv = 1.0 / std::sqrt(var / group_size + 1e-6); - for (int64_t j = start; j < end; j++) - out[(size_t)j] = (float)((x[j] - mean) * inv); - } - size_t unwritten = 0; - for (float v : out) - unwritten += std::isnan(v) ? 1 : 0; - return unwritten; -} - -struct Built { - ggml_context* ctx = nullptr; - ggml_tensor* x = nullptr; - ggml_tensor* y = nullptr; - ggml_cgraph* gf = nullptr; -}; - -static Built build(const Case& c, ggml_backend_t backend, MiniMaxH3VAE::TemporalGroupNorm& norm, uint32_t seed) { - Built b; - ggml_init_params ip{(size_t)1 << 30, nullptr, false}; - b.ctx = ggml_init(ip); - norm.init(b.ctx); - std::mt19937 rng(seed); - std::map params; - norm.get_param_tensors(params, ""); - fill(params.at("weight"), rng, 0.5f, 1.5f); - fill(params.at("bias"), rng, -0.5f, 0.5f); - b.x = ggml_new_tensor_4d(b.ctx, GGML_TYPE_F32, c.w, c.h, c.frames, c.channels * c.batch); - // Per-frame offsets, so a GroupNorm that mixes or skips frames cannot pass by accident. - std::uniform_real_distribution dist(-1.f, 1.f); - auto* p = (float*)b.x->data; - for (int64_t i = 0; i < ggml_nelements(b.x); i++) { - const int64_t f = (i / (c.w * c.h)) % c.frames; - p[i] = dist(rng) * (1.f + f) + 3.f * f; - } - GGMLRunnerContext rc; - rc.ggml_ctx = b.ctx; - rc.backend = backend; - b.y = norm.forward(&rc, b.x); - b.gf = ggml_new_graph_custom(b.ctx, 8192, false); - ggml_build_forward_expand(b.gf, b.y); - return b; -} - -// Largest dim-3 extent any GROUP_NORM node in the graph sees. -static int64_t max_group_norm_ne3(ggml_cgraph* gf, int* count) { - int64_t m = 0; - *count = 0; - for (int i = 0; i < ggml_graph_n_nodes(gf); i++) { - ggml_tensor* n = ggml_graph_node(gf, i); - if (n->op == GGML_OP_GROUP_NORM) { - (*count)++; - m = std::max(m, n->src[0]->ne[3]); - } - } - return m; -} - -static void check_numerics(const char* label, const Case& c, Built& b, MiniMaxH3VAE::TemporalGroupNorm& norm) { - std::map params; - norm.get_param_tensors(params, ""); - ggml_graph_compute_with_ctx(b.ctx, b.gf, 4); - auto ref = oracle(c, (const float*)b.x->data, (const float*)params.at("weight")->data, - (const float*)params.at("bias")->data, 32, 1e-6f); - const float* y = (const float*)b.y->data; - double max_err = 0; - for (size_t i = 0; i < ref.size(); i++) { - const double e = std::fabs((double)y[i] - ref[i]); - max_err = std::isnan(e) ? INFINITY : std::max(max_err, e); - } - uint64_t hash = 1469598103934665603ull; // FNV-1a of the output bytes, to compare builds - for (size_t i = 0; i < ggml_nbytes(b.y); i++) { - hash = (hash ^ ((const uint8_t*)b.y->data)[i]) * 1099511628211ull; - } - std::printf(" %-8s numerics vs fp64 per-frame oracle: max abs err %.3g, output fnv1a %016llx\n", label, max_err, - (unsigned long long)hash); - CHECK(max_err < 1e-4); -} - -int main() { - ggml_backend_t cpu = ggml_backend_cpu_init(); - NamedBackend sycl("SYCL"), opencl("OpenCL"), unknown("SomeFutureBackend"); - NamedBackend cuda("CUDA"), rocm("ROCm"), musa("MUSA"), metal("MTL"), vulkan("Vulkan"); - - const Case cases[] = { - {8, 6, 5, 64, 1}, // ordinary single-clip video chunk - {7, 5, 3, 64, 2}, // batch two - {9, 4, 1, 64, 1}, // single frame keeps one GroupNorm on every backend - }; - for (const auto& c : cases) { - std::printf("case w=%lld h=%lld frames=%lld channels=%lld batch=%lld\n", (long long)c.w, (long long)c.h, - (long long)c.frames, (long long)c.channels, (long long)c.batch); - - // 1. Backends whose GroupNorm is per-slice keep the single batched node (byte-identical to the merged path). - struct { - const char* label; - ggml_backend_t be; - } batched[] = { - {"CPU", cpu}, - {"CUDA", &cuda.backend}, - {"ROCm", &rocm.backend}, - {"MUSA", &musa.backend}, - {"MTL", &metal.backend}, - {"Vulkan", &vulkan.backend}, - }; - for (auto& k : batched) { - MiniMaxH3VAE::TemporalGroupNorm norm(c.channels); - Built b = build(c, k.be, norm, 1234); - int n = 0; - const int64_t ne3 = max_group_norm_ne3(b.gf, &n); - std::printf(" %-8s GROUP_NORM nodes=%d max ne3=%lld\n", k.label, n, (long long)ne3); - CHECK(n == 1); - CHECK(ne3 == c.frames * c.batch); - if (k.be == cpu) { - // CPU really runs it here: the batched node is correct on the pinned ggml CPU backend. - check_numerics(k.label, c, b, norm); - } - ggml_free(b.ctx); - } - - // 2. Backends whose GroupNorm only covers dim-3 slice 0 must never see a folded tensor. - struct { - const char* label; - ggml_backend_t be; - } per_frame[] = { - {"SYCL", &sycl.backend}, - {"OpenCL", &opencl.backend}, - {"unknown", &unknown.backend}, - }; - for (auto& k : per_frame) { - MiniMaxH3VAE::TemporalGroupNorm norm(c.channels); - Built b = build(c, k.be, norm, 1234); - int n = 0; - const int64_t ne3 = max_group_norm_ne3(b.gf, &n); - std::printf(" %-8s GROUP_NORM nodes=%d max ne3=%lld\n", k.label, n, (long long)ne3); - CHECK(ne3 == 1); - CHECK(n == (int)(c.frames * c.batch)); - // Every GROUP_NORM node this backend receives is fully written by its single-slice launch. - for (int i = 0; i < ggml_graph_n_nodes(b.gf); i++) { - ggml_tensor* node = ggml_graph_node(b.gf, i); - if (node->op == GGML_OP_GROUP_NORM) { - std::vector out; - // shapes only: emulate on a zero-filled stand-in of the node's shape - ggml_init_params ip{(size_t)ggml_nbytes(node->src[0]) + 1024, nullptr, false}; - ggml_context* tmp = ggml_init(ip); - ggml_tensor* s = ggml_new_tensor(tmp, GGML_TYPE_F32, 4, node->src[0]->ne); - std::memset(s->data, 0, ggml_nbytes(s)); - CHECK(emulate_single_slice_group_norm(s, 32, out) == 0); - ggml_free(tmp); - } - } - // The per-frame graph is numerically right too (computed on CPU). - check_numerics(k.label, c, b, norm); - ggml_free(b.ctx); - } - - // 3. The emulated single-slice launch on the folded layout leaves every frame after the first unwritten. - if (c.frames * c.batch > 1) { - ggml_init_params ip{(size_t)64 << 20, nullptr, false}; - ggml_context* tmp = ggml_init(ip); - ggml_tensor* s = ggml_new_tensor_4d(tmp, GGML_TYPE_F32, c.w, c.h, c.channels, c.frames * c.batch); - std::memset(s->data, 0, ggml_nbytes(s)); - std::vector out; - const size_t unwritten = emulate_single_slice_group_norm(s, 32, out); - std::printf(" folded layout on a single-slice GroupNorm: %zu of %lld elements unwritten\n", unwritten, - (long long)ggml_nelements(s)); - CHECK(unwritten == (size_t)(c.w * c.h * c.channels * (c.frames * c.batch - 1))); - ggml_free(tmp); - } - } - ggml_backend_free(cpu); - if (failures) { - std::fprintf(stderr, "%d check(s) failed\n", failures); - return 1; - } - std::printf("all checks passed\n"); - return 0; -} From aa0bb1554e6b6b96a46d8285922b3094a980f57a Mon Sep 17 00:00:00 2001 From: Daniel Han <23090290+danielhanchen@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:46:02 -0800 Subject: [PATCH 3/3] Tighten ggml_ext_group_norm_batches_dim3 comment --- src/core/ggml_extend.h | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/core/ggml_extend.h b/src/core/ggml_extend.h index 60e2064a0f..dab70b53b6 100644 --- a/src/core/ggml_extend.h +++ b/src/core/ggml_extend.h @@ -220,9 +220,8 @@ ggml_tensor* ggml_ext_group_norm(GGMLRunnerContext* runner_ctx, int num_groups = 32, float eps = 1e-6f); -// True when the backend's GROUP_NORM normalises every dim-3 slice on its own, so independent items (frames, -// batch) may be folded into dim 3 and normalised in one op. The pinned ggml SYCL and OpenCL kernels cover only -// slice 0, and backends not listed here are unverified, so they get one GROUP_NORM per item instead. +// True when GROUP_NORM normalises every dim-3 slice, so frames / batch items may share one op. SYCL, OpenCL +// and unverified backends cover only slice 0. bool ggml_ext_group_norm_batches_dim3(ggml_backend_t backend); ggml_tensor* ggml_ext_timestep_embedding(GGMLRunnerContext* runner_ctx,