diff --git a/CMakeLists.txt b/CMakeLists.txt index 1eb31cdb..80dda3fc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,7 @@ cmake_minimum_required(VERSION 3.21) # VERSION is the server release that /version reports. The plugin ABI version is separate and is # read from abi/rad_abi.h below. -project(radiance VERSION 1.8.0 LANGUAGES C CXX) +project(radiance VERSION 1.8.1 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) diff --git a/README.md b/README.md index 8f6744c5..b31cc68f 100644 --- a/README.md +++ b/README.md @@ -70,8 +70,10 @@ license, which is non-commercial. The MiniMax-H3 containers serve OpenAI's video jobs (`/v1/videos`): a video with its stereo soundtrack from a prompt, 5 to 14 s, up to 1344x768. On two R9700s a 5.17 s clip at 1344x768 takes about 68 s with FastH3 and 8.8 minutes at MiniMax-H3's 50 steps; both read about 39 GiB of pinned -host memory. MiniMax-H3's license, which FastH3 carries, does not cover the EU, the UK, the Republic -of Korea or the USA. +host memory. With LBH-123-AI's latent upscaler in the container, `"latent_upscale": 2` runs the first +steps at half the size and refines at the full size: MiniMax-H3's clip then takes 3.4 minutes +(docs/GUIDE.md ยง5.16). MiniMax-H3's license, which FastH3 carries, does not cover the EU, the UK, +the Republic of Korea or the USA. MiniMax-Music3 and Breeze-TTS-2 answer `/v1/audio/speech`, whole or streamed as they are made: a song from lyrics and a description, 44.1 kHz stereo, made at about the speed it plays on two cards; and diff --git a/abi/rad_abi.h b/abi/rad_abi.h index 115f52c7..834efdd1 100644 --- a/abi/rad_abi.h +++ b/abi/rad_abi.h @@ -17,7 +17,7 @@ extern "C" { * kind of plugin reports it, and a plugin that does not report exactly this version is refused at * load with both versions printed. A new optional export (e.g. rad_plugin_reference) is not a * change of shape: a plugin without it gets the default. */ -#define RAD_ABI_VERSION 21u +#define RAD_ABI_VERSION 22u /* ================================================================== plugin identity */ /* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin: diff --git a/abi/rad_builder.h b/abi/rad_builder.h index a57fe122..e91eb808 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -837,9 +837,25 @@ int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d); * the base times it was trained on (`rungs`, below): s = rungs then 0, each taken to f32, the same * shifts applied, and the step count fixed at n_rungs + 1. * + * Latent upscaling, for a plugin with a network that enlarges a video latent (`upscale_max` > 1): + * a request with a factor f > 1 is denoised at a smaller size first. Its video is W x H; each side + * divided by f and rounded to the nearest multiple of `size_multiple` (at least one multiple, at + * most the side) gives the small size W' x H'. The request's evaluations but its last `refine` run + * at W' x H', the last of them stepping to sigma 0 (its clean estimate) instead of the next grid + * point. Then one pass: + * + * RAD_GEN_PASS_VUPSCALE the lane's video latent from W' x H' to W x H through the plugin's + * network, told the factor (W / W' + H / H') / 2; then both latents + * re-noised to the sigmas of the first evaluation at W x H, each with a + * stream of its own seed other than the one its first step drew. + * + * The last `refine` evaluations run at W x H, and the decodes follow as for any request. Every + * pass carries the geometry its latent has at that point: a step before the VUPSCALE pass is at + * W' x H'. The schedule is the request's own, whatever size each evaluation runs at. + * * A program declares exactly one of this, the other generators, logits or pooled vectors. */ enum { RAD_GEN_PASS_VCOND = 8, RAD_GEN_PASS_VSTEP = 9, RAD_GEN_PASS_ADECODE = 10, - RAD_GEN_PASS_VDECODE = 11 }; + RAD_GEN_PASS_VDECODE = 11, RAD_GEN_PASS_VUPSCALE = 12 }; typedef struct RadVideoGenDecl { const char* name; /* "minimax-h3" -- the served model id and messages */ @@ -880,6 +896,12 @@ typedef struct RadVideoGenDecl { * count. 0 is the linspace schedule. */ int32_t n_rungs; const double* rungs; + + /* Latent upscaling (above): the largest factor a request may ask for, 0 when the plugin has no + * upscaler; and the evaluations at the full size a request that names none runs, at least 1 + * and fewer than the default schedule's. */ + double upscale_max; + int32_t upscale_refine; } RadVideoGenDecl; int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d); diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index ff3c20d8..c7694a95 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -423,6 +423,7 @@ enum { * patches. No token ids. * ADECODE no rows of the pass's own. * VDECODE `dec_rows` rows of the decoder's own (rad_arch_video_positions, RAD_VPOS_DECODE). + * VUPSCALE no rows of the pass's own: the lane's video latent from `geom_from` to `geom`. * * Every pointer is device memory unless the name ends in _h. */ typedef struct RadVideoGenBatch { @@ -460,6 +461,13 @@ typedef struct RadVideoGenBatch { /* ---- ADECODE */ int64_t n_samples; /* samples a channel the pass writes to audio_out */ + + /* ---- VUPSCALE (rad_builder.h, "Latent upscaling"). `geom` is the geometry the video latent + * is enlarged to and `geom_from` the one it has; `geom_d` carries both (RAD_VGEOM_UP_*). + * `sched` is the first full-size step's, whose sigmas (sched[1] the video's, sched[4] the + * soundtrack's) the latents are re-noised to; `seed` is a step's. */ + RadVideoGeom geom_from; + const float* upscale; /* f32 [1]: the factor the network is told */ } RadVideoGenBatch; /* RadVideoGenBatch::geom_d. The request's latent geometry, then a VDECODE pass's chunk: the latent @@ -471,7 +479,11 @@ enum { RAD_VGEOM_CHUNK_FRAMES = 6, RAD_VGEOM_CHUNK_H = 7, RAD_VGEOM_CHUNK_W = 8, RAD_VGEOM_CHUNK_FIRST = 9, RAD_VGEOM_CHUNK_LAST = 10, RAD_VGEOM_PATCH_FRAMES = 11, RAD_VGEOM_PATCH_H = 12, RAD_VGEOM_PATCH_W = 13, - RAD_VGEOM_N = 16 + /* A VUPSCALE pass's: (frames, h, w, H, W), the latent's grid before and after, of which the + * first three are also the source volume; (frames, H, W) the target volume; then both in + * patches, (frames, h / patch, w / patch) and (frames, H / patch, W / patch). */ + RAD_VGEOM_UP_SRC = 16, RAD_VGEOM_UP_DST = 21, RAD_VGEOM_UP_PSRC = 24, RAD_VGEOM_UP_PDST = 27, + RAD_VGEOM_N = 32 }; /* ================================================================== operands */ diff --git a/arch/minimaxh3/minimaxh3.cpp b/arch/minimaxh3/minimaxh3.cpp index 3f8d9e52..75c310e8 100644 --- a/arch/minimaxh3/minimaxh3.cpp +++ b/arch/minimaxh3/minimaxh3.cpp @@ -40,6 +40,18 @@ * and v (`to_gate_compress`) gates in an attention over the tiles' means. Everything else is the * base model's. * + * ============================== LATENT UPSCALING ============================== + * + * A container may also carry LBH-123-AI's latent upscaler (LatentResizer3D, the pipeline + * directory's latent_upscaler/ folder): a 3D-convolution network that enlarges a video latent's + * frames by a factor from 1 to 4, told the factor through a small embedding. With it a request can + * be denoised at a smaller size for its first steps (abi/rad_builder.h, "Latent upscaling"): the + * upscale pass unfolds the clean small latent into voxels, normalises it with the upscaler's own + * statistics, runs `conv_in`, 18 blocks at the small size (12 residual blocks conditioned on the + * factor, a temporal block after every second), a bilinear resize of each frame, 18 blocks at the + * full size, GroupNorm, SiLU and `conv_out`; then denormalises, folds the voxels back into patch + * rows and re-noises both latents for the remaining steps. Every rank runs it whole. + * * ============================== ONCE A REQUEST ============================== * * The conditioning pass runs the text encoder and the refiner, and also every step's modulation: @@ -332,6 +344,17 @@ struct AStage { int64_t ch = 0, rate = 0, k = 0; }; +/* A latent upscaler block: a residual block (GroupNorm, SiLU, conv; GroupNorm modulated by the + * factor's embedding, SiLU, conv; the residual added) or a temporal block (GroupNorm, SiLU, a + * depthwise convolution over frames, a pointwise one with the residual). */ +struct UpsBlock { + bool temporal = false; + int64_t emb = -1; /* a residual block's row of the factor's embeddings */ + rad_weight n1w = 0, n1b = 0, c1w = 0, c1b = 0, n2w = 0, n2b = 0, c2w = 0, c2b = 0; + rad_weight ew = 0, eb = 0; /* the embedding's projection to (scale, shift) */ + rad_op op_e = 0, op_n1 = 0, op_c1 = 0, op_n2 = 0, op_c2 = 0; +}; + /* Weight groups (movement units) by network: the text encoder's layers 0.., the refiner, the * timestep MLP with norm_out's projection, the DiT's model-level weights and its blocks after * them, each block's modulation projections, the decoders. A unit takes the strongest access class @@ -344,8 +367,13 @@ enum : int { kGrpAda = 2200, kGrpVae = 3000, kGrpAudio = 3100, + kGrpUps = 3200, }; +/* The evaluations a request runs at the full size after a latent upscale, by default: of a + * distilled release's eight, and of the base model's 49. */ +enum { kUpsRefineDistilled = 3, kUpsRefineBase = 12 }; + struct Model { Names nm{""}; Geom gt{}, gd{}, gr{}; /* text encoder, DiT (step rows), refiner (prompt rows) */ @@ -424,6 +452,23 @@ struct Model { rad_buf b_vqkv = 0, b_vattn = 0, b_vo = 0, b_vt = 0, b_vup = 0, b_vact = 0; rad_buf b_vpix = 0, b_vpix_all = 0, b_frames = 0; std::vector vit; + + /* ---- the latent upscaler, when the container carries one */ + bool ups = false; + double ups_max = 0.0; /* the largest factor it was trained on */ + int64_t uC = 0, uE = 0; /* its width and its embedding's */ + std::string u_inv_mul, u_inv_add, u_std, u_mean; /* its normalisation, both ways */ + rad_weight u_e0w = 0, u_e0b = 0, u_e2w = 0, u_e2b = 0; + rad_weight u_cinw = 0, u_cinb = 0, u_now = 0, u_nob = 0, u_coutw = 0, u_coutb = 0; + rad_op op_uunf = 0, op_ucast = 0, op_ufac = 0, op_ue0 = 0, op_ues0 = 0, op_ue2 = 0; + rad_op op_ues2 = 0, op_ucin = 0, op_ursz = 0, op_unout = 0, op_ucout = 0, op_ufold = 0; + rad_op op_urnv = 0, op_urna = 0; + /* The voxels in and out, three activations of the network's width (each the residual stream + * or a temporary in turn), GroupNorm's statistics, and the factor's embedding: the factor less + * one, the MLP's two layers, then every residual block's (scale, shift) row. */ + rad_buf b_uin32 = 0, b_uin = 0, b_ua = 0, b_ub = 0, b_uc = 0, b_uout = 0, b_ust = 0; + rad_buf b_ufac = 0, b_ue0 = 0, b_ue0s = 0, b_ue1 = 0, b_ue1s = 0, b_uemb = 0; + std::vector u_in, u_out; }; static Model g_model[MAX_RANKS]; @@ -1514,6 +1559,259 @@ static int declare_video(RadBuilder* b, const RadModelMeta* meta, Model& m) { return m.op_stitch ? RAD_OK : RAD_E_INVAL; } +/* ================================================================== the latent upscaler */ +/* LatentResizer3D (the companion folder latent_upscaler/, its config.json and weights), declared + * when the container carries it. Its architecture is the ComfyUI node's, which infers it from the + * weights; the config states the same numbers and they are checked here. Weights are bf16 but the + * factor's embedding MLP, f32 (the recipe casts it) so that its first layer, one input wide, is an + * f32 GEMM. Activations are bf16 voxel rows of the network's width, statistics and accumulation + * f32. */ +static int declare_ups(RadBuilder* b, const RadModelMeta* meta, Model& m) { + const char* cls = rad_meta_gets(meta, "latent_upscaler._class_name", nullptr); + if (!cls) return RAD_OK; + Names& nm = m.nm; + auto geti = [&](const char* k, long long def) { + return (int64_t)rad_meta_geti(meta, nm.ckpt("latent_upscaler.%s", k), def); + }; + const int64_t C = geti("channels", 512), E = geti("embed_dim", 64), G = geti("norm_num_groups", 32); + const int64_t nin = geti("in_blocks", 12), nout = geti("out_blocks", 12); + const int64_t every = geti("temporal_every", 2), tk = geti("temporal_kernel", 5); + const int64_t K = geti("conv_kernel_size", 3); + const std::vector mean = meta_list(meta, "latent_upscaler.latent_normalization.mean"); + const std::vector sd = meta_list(meta, "latent_upscaler.latent_normalization.std"); + const std::vector range = meta_list(meta, "latent_upscaler.scale_range"); + const char* mode = rad_meta_gets(meta, "latent_upscaler.upsample_mode", "trilinear"); + if (std::strcmp(cls, "LatentResizer3D") || geti("in_channels", kC) != kC || + geti("out_channels", kC) != kC || K != 3 || geti("attn", 0) != 0 || C % G || C % 8 || + every < 0 || tk < 1 || tk % 2 == 0 || std::strcmp(mode, "trilinear") || + geti("upsample_align_corners", 0) != 0 || (int64_t)mean.size() != kC || + (int64_t)sd.size() != kC || range.size() != 2 || !(range[1] > 1.0)) { + fprintf(stderr, "radiance: minimaxh3: latent_upscaler/ is a '%s' this plugin does not run: " + "it runs LatentResizer3D over %d channels, 3x3x3 convolutions, odd " + "temporal kernels, no attention, a trilinear resize without aligned " + "corners and a scale range\n", cls, (int)kC); + return RAD_E_UNSUPPORTED; + } + m.ups = true; + m.ups_max = range[1]; + m.uC = C; + m.uE = E; + /* patch_unfold normalises as x * mul + add: (x - mean) / std is x / std - mean / std. */ + std::vector im(kC), ia(kC); + for (int64_t c = 0; c < kC; ++c) { + im[(size_t)c] = 1.0 / sd[(size_t)c]; + ia[(size_t)c] = -mean[(size_t)c] / sd[(size_t)c]; + } + m.u_inv_mul = join_list(im); + m.u_inv_add = join_list(ia); + m.u_std = join_list(sd); + m.u_mean = join_list(mean); + + /* The most voxels a frame of latents and a video hold, before or after: the small size is + * never larger than the full one. */ + const int64_t V = max_lat_frames() * ((int64_t)kMaxArea / (kScale * kScale)); + const int64_t P = m.maxV; + const int acc = RAD_ACCESS_PER_TOKEN; + auto wt = [&](const char* name, uint32_t dt, std::initializer_list shape) { + return wcopy(b, nm.f("ups.%s", name), nm.ckpt("latent_upscaler.%s", name), dt, shape, acc, + kGrpUps); + }; + auto conv = [&](rad_weight w, rad_weight bias, int64_t cin, int64_t cout, rad_buf x, rad_buf res, + rad_buf y) -> rad_op { + if (!w || !bias) return 0; + const rad_op op = RAD_OP(b, "conv3d_ndhwc", + RAD_PARAMS(RAD_RANGE("M", 1, V), RAD_INT("cin", cin), + RAD_INT("cout", cout), RAD_INT("k", K), RAD_INT("kt", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bias)); + return res ? rw(b, op, { x, res }, { y }) : rw(b, op, { x }, { y }); + }; + auto gnorm = [&](rad_weight w, rad_weight bias, bool mod, rad_buf x, rad_buf y) -> rad_op { + if (!w || !bias) return 0; + const rad_op op = RAD_OP(b, "group_norm", + RAD_PARAMS(RAD_RANGE("M", 1, V), RAD_INT("n", C), + RAD_INT("groups", G), RAD_F64("eps", 1e-5), + RAD_STR("act", "silu"), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bias)); + return mod ? rw(b, op, { x, m.b_uemb, m.b_ust }, { y, m.b_ust }) + : rw(b, op, { x, m.b_ust }, { y, m.b_ust }); + }; + auto gemm32 = [&](rad_weight w, rad_weight bias, int64_t N, int64_t Kd, rad_buf x, + rad_buf y) -> rad_op { + if (!w || !bias) return 0; + return rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("N", N), RAD_INT("K", Kd), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(w, bias)), + { x }, { y }); + }; + + /* ---- the latent in: unfolded and normalised in f32, then bf16 */ + m.b_uin32 = decl_b(b, nm.f("ups.in32"), RAD_F32, { V, kC }); + m.op_uunf = rw(b, RAD_OP(b, "patch_unfold", + RAD_PARAMS(RAD_RANGE("M", 1, V), RAD_INT("C", kC), RAD_INT("pt", 1), + RAD_INT("ph", kPatch), RAD_INT("pw", kPatch), + RAD_STR("mul", m.u_inv_mul.c_str()), + RAD_STR("add", m.u_inv_add.c_str()), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { m.b_vstate }, { m.b_uin32 }); + m.b_uin = decl_b(b, nm.f("ups.in"), RAD_BF16, { V, kC }); + m.op_ucast = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, V), RAD_INT("n", kC), + RAD_STR("from", "f32"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + { m.b_uin32 }, { m.b_uin }); + + /* ---- the factor's embedding: Linear(1, E), SiLU, Linear(E, E), then every residual block's + * SiLU and Linear(E, 2C), each into its own row */ + m.b_ufac = decl_b(b, nm.f("ups.fac"), RAD_F32, { 1, 1 }); + m.op_ufac = rw(b, RAD_OP(b, "chan_affine", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", 1), RAD_STR("mul", "1"), + RAD_STR("add", "-1"), RAD_STR("mode", "fma"), + RAD_INT("round", 0), RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {}, { m.b_ufac }); + m.b_ue0 = decl_b(b, nm.f("ups.e0"), RAD_F32, { 1, E }); + m.b_ue0s = decl_b(b, nm.f("ups.e0s"), RAD_F32, { 1, E }); + m.b_ue1 = decl_b(b, nm.f("ups.e1"), RAD_F32, { 1, E }); + m.b_ue1s = decl_b(b, nm.f("ups.e1s"), RAD_F32, { 1, E }); + m.u_e0w = wt("embed.0.weight", RAD_F32, { E, 1 }); + m.u_e0b = wt("embed.0.bias", RAD_F32, { E }); + m.u_e2w = wt("embed.2.weight", RAD_F32, { E, E }); + m.u_e2b = wt("embed.2.bias", RAD_F32, { E }); + m.op_ue0 = gemm32(m.u_e0w, m.u_e0b, E, 1, m.b_ufac, m.b_ue0); + m.op_ues0 = unary(b, "silu", 1, E, "f32", m.b_ue0, m.b_ue0s); + m.op_ue2 = gemm32(m.u_e2w, m.u_e2b, E, E, m.b_ue0s, m.b_ue1); + m.op_ues2 = unary(b, "silu", 1, E, "f32", m.b_ue1, m.b_ue1s); + if (!m.op_uunf || !m.op_ucast || !m.op_ufac || !m.op_ue0 || !m.op_ues0 || !m.op_ue2 || + !m.op_ues2) + return RAD_E_INVAL; + + /* The checkpoint's block lists: a residual block per index, a temporal block after the b-th + * when b % every == 0, numbered in one sequence. */ + auto layout = [&](int64_t n, std::vector* out) { + for (int64_t i = 0; i < n; ++i) { + out->emplace_back(); + if (every > 0 && i % every == 0) { + out->emplace_back(); + out->back().temporal = true; + } + } + }; + layout(nin, &m.u_in); + layout(nout, &m.u_out); + int64_t n_res = 0; + for (auto* list : { &m.u_in, &m.u_out }) + for (UpsBlock& B : *list) if (!B.temporal) B.emb = n_res++; + m.b_uemb = decl_b(b, nm.f("ups.emb"), RAD_F32, { n_res, 2 * C }); + for (const char* side : { "in_blocks", "out_blocks" }) { + std::vector& list = !std::strcmp(side, "in_blocks") ? m.u_in : m.u_out; + for (size_t i = 0; i < list.size(); ++i) { + UpsBlock& B = list[i]; + if (B.temporal) continue; + B.ew = wt(nm.ckpt("%s.%zu.emb_layers.1.weight", side, i), RAD_F32, { 2 * C, E }); + B.eb = wt(nm.ckpt("%s.%zu.emb_layers.1.bias", side, i), RAD_F32, { 2 * C }); + if (!B.ew || !B.eb) return RAD_E_INVAL; + B.op_e = rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("N", 2 * C), + RAD_INT("K", E), RAD_STR("dtype", "f32")), + RAD_WEIGHTS(B.ew, B.eb)), + { m.b_ue1s }, { m.b_uemb }); + if (!B.op_e) return RAD_E_INVAL; + } + } + + /* ---- conv_in, the blocks before the resize, the resize, the blocks after it: the residual + * stream is A before the resize and B after it, the other two the blocks' temporaries */ + m.b_ua = decl_b(b, nm.f("ups.a"), RAD_BF16, { V, C }); + m.b_ub = decl_b(b, nm.f("ups.b"), RAD_BF16, { V, C }); + m.b_uc = decl_b(b, nm.f("ups.c"), RAD_BF16, { V, C }); + m.b_ust = decl_b(b, nm.f("ups.gn_stats"), RAD_F32, { G * (2 + 3 * 1024) }); + m.u_cinw = wt("conv_in.weight", RAD_BF16, { C, kC, K, K, K }); + m.u_cinb = wt("conv_in.bias", RAD_BF16, { C }); + m.op_ucin = conv(m.u_cinw, m.u_cinb, kC, C, m.b_uin, 0, m.b_ua); + if (!m.op_ucin) return RAD_E_INVAL; + auto blocks = [&](const char* side, std::vector& list, rad_buf X, rad_buf T, + rad_buf H) -> int { + for (size_t i = 0; i < list.size(); ++i) { + UpsBlock& B = list[i]; + if (B.temporal) { + B.n1w = wt(nm.ckpt("%s.%zu.norm.weight", side, i), RAD_BF16, { C }); + B.n1b = wt(nm.ckpt("%s.%zu.norm.bias", side, i), RAD_BF16, { C }); + B.c1w = wt(nm.ckpt("%s.%zu.dwconv.weight", side, i), RAD_BF16, { C, 1, tk, 1, 1 }); + B.c1b = wt(nm.ckpt("%s.%zu.dwconv.bias", side, i), RAD_BF16, { C }); + B.c2w = wt(nm.ckpt("%s.%zu.pwconv.weight", side, i), RAD_BF16, { C, C, 1, 1, 1 }); + B.c2b = wt(nm.ckpt("%s.%zu.pwconv.bias", side, i), RAD_BF16, { C }); + if (!B.c1w || !B.c1b || !B.c2w || !B.c2b) return RAD_E_INVAL; + B.op_n1 = gnorm(B.n1w, B.n1b, false, X, T); + B.op_c1 = rw(b, RAD_OP(b, "tconv_dw", + RAD_PARAMS(RAD_RANGE("M", 1, V), RAD_INT("n", C), + RAD_INT("k", tk), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(B.c1w, B.c1b)), + { T }, { H }); + B.op_c2 = rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, V), RAD_INT("N", C), + RAD_INT("K", C), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(B.c2w, B.c2b)), + { H, X }, { X }); + if (!B.op_n1 || !B.op_c1 || !B.op_c2) return RAD_E_INVAL; + } else { + B.n1w = wt(nm.ckpt("%s.%zu.in_layers.0.weight", side, i), RAD_BF16, { C }); + B.n1b = wt(nm.ckpt("%s.%zu.in_layers.0.bias", side, i), RAD_BF16, { C }); + B.c1w = wt(nm.ckpt("%s.%zu.in_layers.2.weight", side, i), RAD_BF16, { C, C, K, K, K }); + B.c1b = wt(nm.ckpt("%s.%zu.in_layers.2.bias", side, i), RAD_BF16, { C }); + B.n2w = wt(nm.ckpt("%s.%zu.out_norm.weight", side, i), RAD_BF16, { C }); + B.n2b = wt(nm.ckpt("%s.%zu.out_norm.bias", side, i), RAD_BF16, { C }); + B.c2w = wt(nm.ckpt("%s.%zu.out_layers.2.weight", side, i), RAD_BF16, { C, C, K, K, K }); + B.c2b = wt(nm.ckpt("%s.%zu.out_layers.2.bias", side, i), RAD_BF16, { C }); + B.op_n1 = gnorm(B.n1w, B.n1b, false, X, T); + B.op_c1 = conv(B.c1w, B.c1b, C, C, T, 0, H); + B.op_n2 = gnorm(B.n2w, B.n2b, true, H, T); + B.op_c2 = conv(B.c2w, B.c2b, C, C, T, X, X); + if (!B.op_n1 || !B.op_c1 || !B.op_n2 || !B.op_c2) return RAD_E_INVAL; + } + } + return RAD_OK; + }; + RAD_ARCH_TRY(blocks("in_blocks", m.u_in, m.b_ua, m.b_ub, m.b_uc)); + m.op_ursz = rw(b, RAD_OP(b, "resize_bilinear", + RAD_PARAMS(RAD_RANGE("M", 1, V), RAD_INT("n", C), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_ua }, { m.b_ub }); + if (!m.op_ursz) return RAD_E_INVAL; + RAD_ARCH_TRY(blocks("out_blocks", m.u_out, m.b_ub, m.b_ua, m.b_uc)); + + /* ---- GroupNorm, SiLU, conv_out, then back to the lane: denormalised, folded into patch rows + * and re-noised, the soundtrack with it */ + m.u_now = wt("norm_out.weight", RAD_BF16, { C }); + m.u_nob = wt("norm_out.bias", RAD_BF16, { C }); + m.op_unout = gnorm(m.u_now, m.u_nob, false, m.b_ub, m.b_ua); + m.b_uout = decl_b(b, nm.f("ups.out"), RAD_BF16, { V, kC }); + m.u_coutw = wt("conv_out.weight", RAD_BF16, { kC, C, K, K, K }); + m.u_coutb = wt("conv_out.bias", RAD_BF16, { kC }); + m.op_ucout = conv(m.u_coutw, m.u_coutb, C, kC, m.b_ua, 0, m.b_uout); + m.op_ufold = rw(b, RAD_OP(b, "patch_fold", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("C", kC), RAD_INT("pt", 1), + RAD_INT("ph", kPatch), RAD_INT("pw", kPatch), + RAD_STR("mul", m.u_std.c_str()), + RAD_STR("add", m.u_mean.c_str()), RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { m.b_uout }, { m.b_vstate }); + auto renoise = [&](int64_t rows, int64_t n, rad_buf x) { + return rw(b, RAD_OP(b, "flow_renoise", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_INT("stream", 1), RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { x }, { x }); + }; + m.op_urnv = renoise(P, kPatchVals, m.b_vstate); + m.op_urna = renoise(m.maxA, kAudioC, m.b_astate); + if (!m.op_unout || !m.op_ucout || !m.op_ufold || !m.op_urnv || !m.op_urna) return RAD_E_INVAL; + return RAD_OK; +} + /* ================================================================== declare */ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { if (!b || !meta || !ctx) return RAD_E_INVAL; @@ -1635,6 +1933,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c "block-fp8 container (data/recipes/minimax-h3-fp8.recipe)\n"); return RAD_E_UNSUPPORTED; } + RAD_ARCH_TRY(declare_ups(b, meta, m)); RAD_ARCH_TRY(declare_audio(b, meta, m)); RAD_ARCH_TRY(declare_video(b, meta, m)); @@ -1685,6 +1984,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c d.max_lanes = kMaxLanes; d.frames_out = m.b_frames; d.audio_out = m.b_audio; + if (m.ups) { + d.upscale_max = m.ups_max; + d.upscale_refine = m.rungs.empty() ? kUpsRefineBase : kUpsRefineDistilled; + } RAD_ARCH_TRY(rad_declare_video_generator(b, &d)); } @@ -1694,6 +1997,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c m.gt.rank, m.gt.world, (long long)m.gt.n_layer, (long long)m.gt.n_head, (long long)gd.n_layer, (long long)gd.n_head, (long long)gd.n_ff, (long long)m.Ws, (long long)m.D, (long long)m.tiles, (long long)m.tpr); + if (m.ups) + rad_note(b, "rank %d/%d: latent upscaler LatentResizer3D -- %zu + %zu blocks of %lld " + "channels, factors up to %g, whole on every rank", m.gt.rank, m.gt.world, + m.u_in.size(), m.u_out.size(), (long long)m.uC, m.ups_max); return RAD_OK; } @@ -1764,7 +2071,10 @@ static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) { RAD_ISSUE_N(c, m.op_t2, S2, brows(m.b_te1s, S2), RAD_W(m.w_t2), RAD_W(m.b_t2), RAD_NONE, brows(m.b_temb, S2)); RAD_ISSUE_N(c, m.op_ts2, S2, brows(m.b_temb, S2), brows(m.a_temb.x, S2)); - m.q_temb.step(c, S2); + /* At its own rows: QuantFP8::step bands by the batch's tokens, which here are the prompt's, + * and the quantiser is declared for the 2 S rows of the steps' embeddings. */ + RAD_ISSUE_N(c, m.q_temb.op, S2, brows(m.a_temb.x, S2), brows(m.a_temb.cq(), S2), + brows(m.a_temb.cs(), S2)); /* ---- the modulation table: block l, segment e from its modality's projection of its * timestep's rows, at the table's column block (l, e) */ @@ -2052,6 +2362,74 @@ static void step_video(RadCtx* c, const RadBatch* batch, const Model& m) { brows(m.b_frames, n)); } +/* The latent upscale: the lane's clean small latent through the upscaler to the full size, then + * both latents re-noised to the next step's sigmas with streams of their own (stream 1 of each + * seed; the first step drew stream 0). */ +static void step_upscale(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadVideoGenBatch* V = batch->vgen_b; + const RadVideoGeom& s = V->geom_from; + const RadVideoGeom& d = V->geom; + const int64_t lane = V->lane, F = d.lat_frames, C = m.uC; + const int64_t vs = F * s.lat_h * s.lat_w, vd = F * d.lat_h * d.lat_w; + const int64_t pd = vd / (kPatch * kPatch), ps = vs / (kPatch * kPatch); + const int64_t arows = (int64_t)kAudioCh * d.n_audio; + const int32_t* gd = V->geom_d; + const RadOperand gsrc = praw(gd + RAD_VGEOM_UP_SRC, RAD_I32, 3); + const RadOperand gdst = praw(gd + RAD_VGEOM_UP_DST, RAD_I32, 3); + const RadOperand st = RAD_B(m.b_ust); + + RAD_ISSUE_N(c, m.op_uunf, vs, brow_slice(m.b_vstate, lane * m.maxV, ps, kPatchVals), + praw(gd + RAD_VGEOM_UP_PSRC, RAD_I32, 3), brows(m.b_uin32, vs)); + RAD_ISSUE_N(c, m.op_ucast, vs, brows(m.b_uin32, vs), brows(m.b_uin, vs)); + RAD_ISSUE_N(c, m.op_ufac, 1, praw(V->upscale, RAD_F32, 1), brows(m.b_ufac, 1)); + RAD_ISSUE_N(c, m.op_ue0, 1, brows(m.b_ufac, 1), RAD_W(m.u_e0w), RAD_W(m.u_e0b), RAD_NONE, + brows(m.b_ue0, 1)); + RAD_ISSUE_N(c, m.op_ues0, 1, brows(m.b_ue0, 1), brows(m.b_ue0s, 1)); + RAD_ISSUE_N(c, m.op_ue2, 1, brows(m.b_ue0s, 1), RAD_W(m.u_e2w), RAD_W(m.u_e2b), RAD_NONE, + brows(m.b_ue1, 1)); + RAD_ISSUE_N(c, m.op_ues2, 1, brows(m.b_ue1, 1), brows(m.b_ue1s, 1)); + for (const auto* list : { &m.u_in, &m.u_out }) + for (const UpsBlock& B : *list) + if (!B.temporal) + RAD_ISSUE_N(c, B.op_e, 1, brows(m.b_ue1s, 1), RAD_W(B.ew), RAD_W(B.eb), RAD_NONE, + brow_slice(m.b_uemb, B.emb, 1, 2 * C)); + RAD_ISSUE_N(c, m.op_ucin, vs, brows(m.b_uin, vs), RAD_W(m.u_cinw), RAD_W(m.u_cinb), gsrc, + RAD_NONE, brows(m.b_ua, vs)); + auto blocks = [&](const std::vector& list, rad_buf X, rad_buf T, rad_buf H, + int64_t v, const RadOperand& g) { + for (const UpsBlock& B : list) { + RAD_ISSUE_N(c, B.op_n1, v, brows(X, v), RAD_W(B.n1w), RAD_W(B.n1b), RAD_NONE, st, + brows(T, v)); + if (B.temporal) { + RAD_ISSUE_N(c, B.op_c1, v, brows(T, v), RAD_W(B.c1w), RAD_W(B.c1b), g, brows(H, v)); + RAD_ISSUE_N(c, B.op_c2, v, brows(H, v), RAD_W(B.c2w), RAD_W(B.c2b), brows(X, v), + brows(X, v)); + continue; + } + RAD_ISSUE_N(c, B.op_c1, v, brows(T, v), RAD_W(B.c1w), RAD_W(B.c1b), g, RAD_NONE, + brows(H, v)); + RAD_ISSUE_N(c, B.op_n2, v, brows(H, v), RAD_W(B.n2w), RAD_W(B.n2b), + brow_slice(m.b_uemb, B.emb, 1, 2 * C), st, brows(T, v)); + RAD_ISSUE_N(c, B.op_c2, v, brows(T, v), RAD_W(B.c2w), RAD_W(B.c2b), g, brows(X, v), + brows(X, v)); + } + }; + blocks(m.u_in, m.b_ua, m.b_ub, m.b_uc, vs, gsrc); + RAD_ISSUE_N(c, m.op_ursz, vd, brows(m.b_ua, vs), praw(gd + RAD_VGEOM_UP_SRC, RAD_I32, 5), + brows(m.b_ub, vd)); + blocks(m.u_out, m.b_ub, m.b_ua, m.b_uc, vd, gdst); + RAD_ISSUE_N(c, m.op_unout, vd, brows(m.b_ub, vd), RAD_W(m.u_now), RAD_W(m.u_nob), RAD_NONE, st, + brows(m.b_ua, vd)); + RAD_ISSUE_N(c, m.op_ucout, vd, brows(m.b_ua, vd), RAD_W(m.u_coutw), RAD_W(m.u_coutb), gdst, + RAD_NONE, brows(m.b_uout, vd)); + RAD_ISSUE_N(c, m.op_ufold, pd, brows(m.b_uout, vd), praw(gd + RAD_VGEOM_UP_PDST, RAD_I32, 3), + brow_slice(m.b_vstate, lane * m.maxV, pd, kPatchVals)); + RAD_ISSUE_N(c, m.op_urnv, pd, praw(V->sched + 1, RAD_F32, 1), praw(V->seed, RAD_U32, 2), + brow_slice(m.b_vstate, lane * m.maxV, pd, kPatchVals)); + RAD_ISSUE_N(c, m.op_urna, arows, praw(V->sched + 4, RAD_F32, 1), praw(V->seed + 2, RAD_U32, 2), + brow_slice(m.b_astate, lane * m.maxA, arows, kAudioC)); +} + static void step(RadCtx* c, const RadBatch* batch) { const Model& m = g_model[rad_rank(c)]; if (!batch->gen || !batch->vgen_b) { @@ -2063,6 +2441,14 @@ static void step(RadCtx* c, const RadBatch* batch) { case RAD_GEN_PASS_VSTEP: step_dit(c, batch, m); return; case RAD_GEN_PASS_ADECODE: step_audio(c, batch, m); return; case RAD_GEN_PASS_VDECODE: step_video(c, batch, m); return; + case RAD_GEN_PASS_VUPSCALE: + if (!m.ups) { + rad_step_fail(c, "minimaxh3: an upscale pass, and this container has no latent " + "upscaler"); + return; + } + step_upscale(c, batch, m); + return; default: rad_step_fail(c, "minimaxh3: a generator pass of a kind this plugin does not know"); } diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index e7c877f2..d3bf0fa8 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -1484,6 +1484,17 @@ int Builder::declare_video_generator(const RadVideoGenDecl* d) { "below the one before it", nm, i, d->rungs[i]); return RAD_E_INVAL; } + /* An upscaler needs a schedule it can split: one evaluation at the small size at least, and + * `upscale_refine` of them after it by default. */ + const int64_t def_evals = d->n_rungs > 0 ? d->n_rungs : d->default_steps - 1; + if (d->upscale_max != 0.0 && + (!(d->upscale_max > 1.0) || d->upscale_refine < 1 || d->upscale_refine >= def_evals)) { + err(RAD_E_INVAL, "declare_video_generator '%s': a latent upscaler of factor %g at most, " + "refining %d evaluations of %lld by default; the factor must be above 1 " + "and the refinement 1 to %lld", nm, d->upscale_max, (int)d->upscale_refine, + (long long)def_evals, (long long)(def_evals - 1)); + return RAD_E_INVAL; + } auto buf_ok = [&](rad_buf h, uint32_t dtype, int64_t numel, const char* what) { if (h == RAD_NULL_HANDLE || (size_t)h >= prog_.buffers.size()) { err(RAD_E_INVAL, "declare_video_generator '%s': %s %u is not a declared buffer", nm, diff --git a/core/engine.cpp b/core/engine.cpp index 9a2eee65..9f40fcc5 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -2495,6 +2495,8 @@ int Engine::run_server() { in.default_steps = vd.default_steps; in.max_steps = vd.max_steps; in.fixed_steps = vd.n_rungs > 0; + in.upscale_max = vd.upscale_max; + in.upscale_refine = vd.upscale_refine; in.max_lanes = vd.max_lanes; video_bridge.drv = vid_gen_; d.videos = &video_bridge; @@ -2510,6 +2512,9 @@ int Engine::run_server() { (double)(in.frames_per_chunk * in.min_chunks + in.frames_tail) / fps, (double)(in.frames_per_chunk * in.max_chunks + in.frames_tail) / fps, fps, (long long)in.sample_rate, (long long)in.channels, (long long)in.default_steps); + if (in.upscale_max > 0.0) + RAD_INFO("video: latent upscaling up to %gx, the last %lld evaluations at the full size " + "by default", in.upscale_max, (long long)in.upscale_refine); } if (encd.modalities == 0 && aend.modalities == 0 && cfg_.media_flags_set()) diff --git a/core/engine_gen.cpp b/core/engine_gen.cpp index 1ac45b97..f1a6daf0 100644 --- a/core/engine_gen.cpp +++ b/core/engine_gen.cpp @@ -28,6 +28,7 @@ static const char* pass_name(int gen) { case RAD_GEN_PASS_VSTEP: return "vstep"; case RAD_GEN_PASS_ADECODE: return "adecode"; case RAD_GEN_PASS_VDECODE: return "vdecode"; + case RAD_GEN_PASS_VUPSCALE: return "vupscale"; default: return ""; } } diff --git a/core/gen/video.h b/core/gen/video.h index 31b16b25..efd4928b 100644 --- a/core/gen/video.h +++ b/core/gen/video.h @@ -53,10 +53,14 @@ public: int32_t frames = 0, width = 0, height = 0, steps = 0; int64_t sample_rate = 0, channels = 0; double fps = 0.0; + /* With latent upscaling, the size the first evaluations run at and the evaluations after the + * upscale; zero without. */ + int32_t small_width = 0, small_height = 0, refine = 0; /* Usage, written by the driver before finish(): prompt tokens, rows a step and per-phase - * times. */ + * times (t_small_ns the last small step done, t_upscaled_ns the upscale; zero without). */ int64_t in_tokens = 0, rows = 0; - int64_t t_submit_ns = 0, t_cond_ns = 0, t_denoised_ns = 0, t_done_ns = 0; + int64_t t_submit_ns = 0, t_cond_ns = 0, t_small_ns = 0, t_upscaled_ns = 0, t_denoised_ns = 0, + t_done_ns = 0; private: mutable std::mutex mu_; @@ -72,6 +76,10 @@ struct VideoRequest { int32_t width = 0, height = 0; /* pixels, within the declaration's limits */ int32_t chunks = 0; /* the length in chunks (RadVideoGenDecl) */ int32_t steps = 0; /* sigma grid points; 0: the model's default */ + /* Latent upscaling (abi/rad_builder.h, RadVideoGenDecl): the factor, 0 for none, and the + * evaluations at the full size after it, 0 for the model's default. */ + double upscale = 0.0; + int32_t refine = 0; uint64_t seed = 0; std::shared_ptr ticket; }; @@ -84,6 +92,12 @@ struct VideoShape { }; VideoShape video_shape(const RadVideoGenDecl& d, int32_t width, int32_t height, int32_t chunks); +/* The small size a request's first evaluations run at under latent upscaling by `factor`: each + * side divided by it and rounded to the nearest multiple of the size multiple, at least one + * multiple and at most the side. */ +void video_small_size(const RadVideoGenDecl& d, int32_t width, int32_t height, double factor, + int32_t* small_w, int32_t* small_h); + /* The two schedules a request of `steps` grid points runs (RadVideoGenDecl, "The sampler"): each * the f32 sigmas, last 0, and the model evaluations it takes, the shorter of the two. With a * trained schedule any other step count than n_rungs + 1 gives no steps. */ diff --git a/core/gen/video_driver.cpp b/core/gen/video_driver.cpp index 6cd179b8..08f28d25 100644 --- a/core/gen/video_driver.cpp +++ b/core/gen/video_driver.cpp @@ -1,9 +1,11 @@ /* video_driver.cpp -- the video generator's pass driver (video_driver.h), the ticket a caller * waits on, and a request's shape and schedule (video.h). */ #include "video_driver.h" +#include "rad_internal.h" #include #include +#include #include namespace rad { @@ -77,6 +79,17 @@ VideoShape video_shape(const RadVideoGenDecl& d, int32_t width, int32_t height, return s; } +void video_small_size(const RadVideoGenDecl& d, int32_t width, int32_t height, double factor, + int32_t* small_w, int32_t* small_h) { + const int64_t m = d.size_multiple; + auto side = [&](int32_t full) { + const int64_t k = (int64_t)std::floor((double)full / factor / (double)m + 0.5); + return (int32_t)(std::min(std::max(k, 1), full / m) * m); + }; + *small_w = side(width); + *small_h = side(height); +} + /* The shift of one base time, in f32 as the reference's tensor arithmetic. */ static float shift_sigma(double shift, float b) { const float sh = (float)shift, sh1 = (float)(shift - 1.0); @@ -147,6 +160,7 @@ int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t (*bytes)[2], in 4, /* R_FIRST */ 4 * 4, /* R_SEG */ 4 * 4, /* R_LAT */ + 4, /* R_UP */ }; int64_t off = 0; for (int r = 0; r < n; ++r) { @@ -304,6 +318,43 @@ int VideoDriver::submit(std::unique_ptr r, std::string* why) { return no("the model could not lay this video out"); j->sched = video_schedule(d, steps); if (j->sched.steps < 1) return no("the schedule has no steps"); + if (r->upscale > 1.0) { + if (!(d.upscale_max > 1.0)) return no("this model has no latent upscaler"); + if (r->upscale > d.upscale_max) + return no("latent_upscale is at most " + fmt("%g", d.upscale_max) + " for this model"); + int32_t sw = 0, sh = 0; + video_small_size(d, r->width, r->height, r->upscale, &sw, &sh); + if (sw == r->width && sh == r->height) + return no("latent_upscale " + fmt("%g", r->upscale) + " leaves " + + std::to_string(r->width) + "x" + std::to_string(r->height) + " as it is: " + "the small size is each side over the factor, rounded to a multiple of " + + std::to_string(d.size_multiple)); + const int32_t evals = j->sched.steps; + int32_t refine = r->refine; + if (refine == 0) refine = std::min(d.upscale_refine, evals - 1); + if (refine < 1 || refine >= evals) + return no("upscale_refine_steps must be 1.." + std::to_string(evals - 1) + ": the " + "schedule takes " + std::to_string(evals) + " evaluations and the small " + "size at least one of them"); + const VideoShape ss = video_shape(d, sw, sh, r->chunks); + j->geom_small = j->geom; + j->geom_small.lat_h = ss.lat_h; + j->geom_small.lat_w = ss.lat_w; + j->rows_small = T + ss.audio_rows + ss.video_rows; + const int64_t ns = positions_(RAD_VPOS_STEP, &j->geom_small, nullptr, 0); + if (ns != j->rows_small) + return no("the model lays the small size " + std::to_string(sw) + "x" + + std::to_string(sh) + " out in " + std::to_string(ns) + " step rows, which " + "this server cannot run"); + j->pos_small.assign((size_t)(3 * ns), 0.0f); + if (positions_(RAD_VPOS_STEP, &j->geom_small, j->pos_small.data(), ns) != ns) + return no("the model could not lay the small size out"); + j->split = evals - refine; + j->factor = (float)(((double)r->width / sw + (double)r->height / sh) / 2.0); + r->ticket->small_width = sw; + r->ticket->small_height = sh; + r->ticket->refine = refine; + } j->n_chunks = r->chunks; j->n_samples = (int64_t)s.n_audio * (d.sample_rate / d.audio_rate); @@ -391,35 +442,46 @@ int VideoDriver::upload() { return RAD_OK; } -/* The geometry a pass's ops read off the device (RAD_VGEOM_*), with chunk `chunk`'s span when it - * is a decode's. */ -void VideoDriver::stage_geom(const Job& j, int32_t chunk) { +/* The geometry a pass's ops read off the device (RAD_VGEOM_*) for a pass at geometry `g` of + * `rows` step rows, with chunk `chunk`'s span when it is a decode's and both grids when the job + * upscales. */ +void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows, int32_t chunk) { int32_t* g = hptr(R_GEOM); std::memset(g, 0, RAD_VGEOM_N * 4); - g[RAD_VGEOM_LAT_FRAMES] = j.geom.lat_frames; - g[RAD_VGEOM_LAT_H] = j.geom.lat_h; - g[RAD_VGEOM_LAT_W] = j.geom.lat_w; - g[RAD_VGEOM_N_TEXT] = j.geom.n_text; - g[RAD_VGEOM_N_AUDIO] = j.geom.n_audio; + g[RAD_VGEOM_LAT_FRAMES] = g0.lat_frames; + g[RAD_VGEOM_LAT_H] = g0.lat_h; + g[RAD_VGEOM_LAT_W] = g0.lat_w; + g[RAD_VGEOM_N_TEXT] = g0.n_text; + g[RAD_VGEOM_N_AUDIO] = g0.n_audio; g[RAD_VGEOM_CHUNK_LAT0] = (int32_t)(decl_.latents_per_chunk * chunk); g[RAD_VGEOM_CHUNK_FRAMES] = (int32_t)decl_.dec_latents; - g[RAD_VGEOM_CHUNK_H] = j.geom.lat_h; - g[RAD_VGEOM_CHUNK_W] = j.geom.lat_w; + g[RAD_VGEOM_CHUNK_H] = g0.lat_h; + g[RAD_VGEOM_CHUNK_W] = g0.lat_w; g[RAD_VGEOM_CHUNK_FIRST] = chunk == 0; g[RAD_VGEOM_CHUNK_LAST] = chunk == j.n_chunks - 1; g[RAD_VGEOM_PATCH_FRAMES] = (int32_t)decl_.dec_latents; - g[RAD_VGEOM_PATCH_H] = (int32_t)(j.geom.lat_h / decl_.patch); - g[RAD_VGEOM_PATCH_W] = (int32_t)(j.geom.lat_w / decl_.patch); + g[RAD_VGEOM_PATCH_H] = (int32_t)(g0.lat_h / decl_.patch); + g[RAD_VGEOM_PATCH_W] = (int32_t)(g0.lat_w / decl_.patch); + if (j.split > 0) { + const RadVideoGeom& a = j.geom_small; + const RadVideoGeom& b = j.geom; + const int32_t p = (int32_t)decl_.patch; + const int32_t up[] = { a.lat_frames, a.lat_h, a.lat_w, b.lat_h, b.lat_w, + b.lat_frames, b.lat_h, b.lat_w, + a.lat_frames, a.lat_h / p, a.lat_w / p, + b.lat_frames, b.lat_h / p, b.lat_w / p }; + std::memcpy(g + RAD_VGEOM_UP_SRC, up, sizeof up); + } reg_[R_GEOM].used = RAD_VGEOM_N * 4; - const int64_t audio_rows = decl_.audio_channels * (int64_t)j.geom.n_audio; - const int64_t video_rows = j.rows - j.geom.n_text - audio_rows; + const int64_t audio_rows = decl_.audio_channels * (int64_t)g0.n_audio; + const int64_t video_rows = rows - g0.n_text - audio_rows; *hptr(R_LANE) = j.lane; *hptr(R_FIRST) = j.step == 0; int32_t* seg = hptr(R_SEG); seg[0] = 0; - seg[1] = j.geom.n_text; - seg[2] = (int32_t)(j.geom.n_text + audio_rows); - seg[3] = (int32_t)j.rows; + seg[1] = g0.n_text; + seg[2] = (int32_t)(g0.n_text + audio_rows); + seg[3] = (int32_t)rows; int32_t* lat = hptr(R_LAT); lat[0] = 0; lat[1] = (int32_t)video_rows; @@ -431,7 +493,7 @@ void VideoDriver::stage_geom(const Job& j, int32_t chunk) { reg_[R_LAT].used = 4 * 4; } -void VideoDriver::base_batches(const Job& j, int64_t n_tok, int step) { +void VideoDriver::base_batches(const Job& j, const RadVideoGeom& g, int64_t n_tok, int step) { for (size_t r = 0; r < ranks_.size(); ++r) { RadBatch& B = out_[r]; RadVideoGenBatch& V = vout_[r]; @@ -448,7 +510,8 @@ void VideoDriver::base_batches(const Job& j, int64_t n_tok, int step) { B.cu_seqlens = dptr(ri, R_CU); V = RadVideoGenBatch{}; V.lane = j.lane; - V.geom = j.geom; + V.geom = g; + V.geom_from = j.geom_small; V.geom_d = dptr(ri, R_GEOM); V.lane_d = dptr(ri, R_LANE); V.first_d = dptr(ri, R_FIRST); @@ -465,6 +528,7 @@ void VideoDriver::base_batches(const Job& j, int64_t n_tok, int step) { V.n_chunks = j.n_chunks; V.dec_rows = j.dec_rows; V.n_samples = j.n_samples; + V.upscale = dptr(ri, R_UP); B.vgen_b = &V; } } @@ -500,11 +564,12 @@ const RadBatch* VideoDriver::next(int step) { Job& j = *jp; if (j.admitted && !j.failed && !j.cond_done) return build_cond(j, step); } - /* 3. The oldest lane's next step. */ + /* 3. The oldest lane's next step, or its upscale once its small steps are done. */ for (auto& jp : jobs_) { Job& j = *jp; - if (j.admitted && !j.failed && j.cond_done && j.step < j.sched.steps) - return build_step(j, step); + if (!j.admitted || j.failed || !j.cond_done || j.step >= j.sched.steps) continue; + if (small_now(j) && j.step == j.split) return build_upscale(j, step); + return build_step(j, step); } return nullptr; } @@ -535,30 +600,32 @@ const RadBatch* VideoDriver::build_cond(Job& j, int step) { reg_[R_CU].used = 2 * 4; reg_[R_TV].used = j.sched.steps * 4; reg_[R_TA].used = j.sched.steps * 4; - stage_geom(j, 0); + const RadVideoGeom& g = small_now(j) ? j.geom_small : j.geom; + stage_geom(j, g, small_now(j) ? j.rows_small : j.rows, 0); if (upload() < 0) return nullptr; - base_batches(j, T, step); + base_batches(j, g, T, step); for (auto& B : out_) B.gen = RAD_GEN_PASS_VCOND; pass_.kind = RAD_GEN_PASS_VCOND; pass_.job = j.id; return &out_[0]; } -const RadBatch* VideoDriver::build_step(Job& j, int step) { - for (int g = 0; g < R_N; ++g) reg_[g].used = 0; - const int32_t i = j.step; +/* Step i's timesteps and sigmas, the video's then the soundtrack's (RadVideoGenBatch::sched); + * with `to_clean` the next sigmas are 0, so the step lands on its clean estimate. */ +void VideoDriver::stage_sched(const Job& j, int32_t i, bool to_clean) { float* s = hptr(R_SCHED); s[0] = 1.0f - j.sched.sig_v[(size_t)i]; s[1] = j.sched.sig_v[(size_t)i]; - s[2] = j.sched.sig_v[(size_t)i + 1]; + s[2] = to_clean ? 0.0f : j.sched.sig_v[(size_t)i + 1]; s[3] = 1.0f - j.sched.sig_a[(size_t)i]; s[4] = j.sched.sig_a[(size_t)i]; - s[5] = j.sched.sig_a[(size_t)i + 1]; + s[5] = to_clean ? 0.0f : j.sched.sig_a[(size_t)i + 1]; reg_[R_SCHED].used = 6 * 4; - std::memcpy(hptr(R_ROPE), j.pos.data(), j.pos.size() * 4); - reg_[R_ROPE].used = (int64_t)j.pos.size() * 4; - /* The video's noise seed is the request's; the soundtrack's the same with its top bit flipped, - * so the two streams never coincide. */ +} + +/* The video's noise seed is the request's; the soundtrack's the same with its top bit flipped, so + * the two streams never coincide. */ +void VideoDriver::stage_seed(const Job& j) { uint32_t* sd = hptr(R_SEED); const uint64_t seed = j.req->seed; sd[0] = (uint32_t)seed; @@ -566,25 +633,54 @@ const RadBatch* VideoDriver::build_step(Job& j, int step) { sd[2] = (uint32_t)seed; sd[3] = (uint32_t)(seed >> 32) ^ 0x80000000u; reg_[R_SEED].used = 4 * 4; +} + +const RadBatch* VideoDriver::build_step(Job& j, int step) { + for (int g = 0; g < R_N; ++g) reg_[g].used = 0; + const bool small = small_now(j); + const RadVideoGeom& g = small ? j.geom_small : j.geom; + const int64_t rows = small ? j.rows_small : j.rows; + const std::vector& pos = small ? j.pos_small : j.pos; + stage_sched(j, j.step, small && j.step == j.split - 1); + std::memcpy(hptr(R_ROPE), pos.data(), pos.size() * 4); + reg_[R_ROPE].used = (int64_t)pos.size() * 4; + stage_seed(j); /* The packed sequence is one attention document. */ int32_t* cu = hptr(R_CU); cu[0] = 0; - cu[1] = (int32_t)j.rows; + cu[1] = (int32_t)rows; reg_[R_CU].used = 2 * 4; - stage_geom(j, 0); + stage_geom(j, g, rows, 0); if (upload() < 0) return nullptr; - base_batches(j, j.rows, step); + base_batches(j, g, rows, step); for (auto& B : out_) B.gen = RAD_GEN_PASS_VSTEP; pass_.kind = RAD_GEN_PASS_VSTEP; pass_.job = j.id; return &out_[0]; } +/* The small latent to the full size, both latents re-noised to the first full-size step's + * sigmas. */ +const RadBatch* VideoDriver::build_upscale(Job& j, int step) { + for (int g = 0; g < R_N; ++g) reg_[g].used = 0; + stage_sched(j, j.split, false); + stage_seed(j); + *hptr(R_UP) = j.factor; + reg_[R_UP].used = 4; + stage_geom(j, j.geom, j.rows, 0); + if (upload() < 0) return nullptr; + base_batches(j, j.geom, 0, step); + for (auto& B : out_) B.gen = RAD_GEN_PASS_VUPSCALE; + pass_.kind = RAD_GEN_PASS_VUPSCALE; + pass_.job = j.id; + return &out_[0]; +} + const RadBatch* VideoDriver::build_audio(Job& j, int step) { for (int g = 0; g < R_N; ++g) reg_[g].used = 0; - stage_geom(j, 0); + stage_geom(j, j.geom, j.rows, 0); if (upload() < 0) return nullptr; - base_batches(j, 0, step); + base_batches(j, j.geom, 0, step); for (auto& B : out_) B.gen = RAD_GEN_PASS_ADECODE; rb_.assign(1, Readback{ decl_.audio_out, j.n_samples * decl_.audio_channels * 4, audio_host_ }); pass_.kind = RAD_GEN_PASS_ADECODE; @@ -594,9 +690,9 @@ const RadBatch* VideoDriver::build_audio(Job& j, int step) { const RadBatch* VideoDriver::build_chunk(Job& j, int step) { for (int g = 0; g < R_N; ++g) reg_[g].used = 0; - stage_geom(j, j.chunk); + stage_geom(j, j.geom, j.rows, j.chunk); if (upload() < 0) return nullptr; - base_batches(j, j.dec_rows, step); + base_batches(j, j.geom, j.dec_rows, step); const bool last = j.chunk == j.n_chunks - 1; const int32_t n = (int32_t)(decl_.frames_per_chunk + (last ? decl_.frames_tail : 0)); for (size_t r = 0; r < out_.size(); ++r) { @@ -626,9 +722,14 @@ int VideoDriver::done() { e.kind = VideoEvent::STEP; e.steps_done = j->step; j->req->ticket->push(std::move(e)); + if (j->split > 0 && j->step == j->split) j->req->ticket->t_small_ns = now; if (j->step >= j->sched.steps) j->req->ticket->t_denoised_ns = now; break; } + case RAD_GEN_PASS_VUPSCALE: + j->upscaled = true; + j->req->ticket->t_upscaled_ns = now; + break; case RAD_GEN_PASS_ADECODE: { VideoEvent e; e.kind = VideoEvent::AUDIO; diff --git a/core/gen/video_driver.h b/core/gen/video_driver.h index ce97876f..c1dd0da6 100644 --- a/core/gen/video_driver.h +++ b/core/gen/video_driver.h @@ -13,8 +13,9 @@ * 1. ADECODE, then each VDECODE chunk in order, of a lane whose denoising is done: they finish * a request and free its lane. * 2. VCOND of an admitted request, so its steps can follow the current request's without a gap. - * 3. VSTEP of the oldest lane with steps left. Requests are denoised one after another, not in - * turns: a pass is one request's whole sequence, so taking turns would only delay the first. + * 3. VSTEP of the oldest lane with steps left, or its VUPSCALE once its small steps are done. + * Requests are denoised one after another, not in turns: a pass is one request's whole + * sequence, so taking turns would only delay the first. */ #pragma once #include "video.h" @@ -67,6 +68,14 @@ private: int64_t n_samples = 0; /* the soundtrack's samples a channel */ VideoSchedule sched; std::vector pos; /* [3, rows] */ + /* Latent upscaling: the evaluations at the small size (0: none), its geometry, rows and + * positions, the factor the network is told, and whether the upscale has run. */ + int32_t split = 0; + RadVideoGeom geom_small{}; + int64_t rows_small = 0; + std::vector pos_small; + float factor = 0.0f; + bool upscaled = false; int32_t lane = -1; bool admitted = false; bool cond_done = false; @@ -87,15 +96,19 @@ private: /* Staging regions: their offsets in the host span and every rank's slab. */ struct Region { int64_t off = 0, bytes = 0, used = 0; }; enum { R_TOK, R_POS, R_CU, R_ROPE, R_GEOM, R_SCHED, R_TV, R_TA, R_SEED, R_LANE, R_FIRST, - R_SEG, R_LAT, R_N }; + R_SEG, R_LAT, R_UP, R_N }; template T* hptr(int r) const { return reinterpret_cast(host_ + reg_[r].off); } template T* dptr(int rank, int r) const { return reinterpret_cast((char*)dev_[(size_t)rank] + reg_[r].off); } int upload(); - void base_batches(const Job& j, int64_t n_tok, int step); - void stage_geom(const Job& j, int32_t chunk); + /* The geometry and rows of the job's next step: the small ones before its upscale. */ + bool small_now(const Job& j) const { return j.split > 0 && !j.upscaled; } + void base_batches(const Job& j, const RadVideoGeom& g, int64_t n_tok, int step); + void stage_geom(const Job& j, const RadVideoGeom& g, int64_t rows, int32_t chunk); + void stage_sched(const Job& j, int32_t i, bool to_clean); + void stage_seed(const Job& j); void admit_locked(); void release_locked(Job& j); @@ -104,6 +117,7 @@ private: const RadBatch* build_cond(Job& j, int step); const RadBatch* build_step(Job& j, int step); + const RadBatch* build_upscale(Job& j, int step); const RadBatch* build_audio(Job& j, int step); const RadBatch* build_chunk(Job& j, int step); diff --git a/core/server/iface.h b/core/server/iface.h index a91cd094..04db5e67 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -641,6 +641,9 @@ struct VideoGenInfo { int64_t sample_rate = 0, channels = 0; int64_t default_steps = 0, max_steps = 0, max_lanes = 1; bool fixed_steps = false; /* a trained schedule: max_steps grid points and no other */ + /* A latent upscaler: the largest factor (0: none) and the full-size evaluations by default. */ + double upscale_max = 0.0; + int64_t upscale_refine = 0; }; class IVideoGen { diff --git a/core/server/videos.cpp b/core/server/videos.cpp index d086c7ab..94f48633 100644 --- a/core/server/videos.cpp +++ b/core/server/videos.cpp @@ -18,6 +18,12 @@ * Nothing that conditions on media is served: `input_reference` and non-empty `conditions` are * refused. * + * A model with a latent upscaler also takes `latent_upscale`, a factor from 1 to its largest: the + * first steps run at `size` divided by it and the latent is enlarged to `size` for the last + * `upscale_refine_steps` (the model's default when absent; abi/rad_builder.h, RadVideoGenDecl). + * The video object of an upscaled video says how it was made: the factor, the refine steps and the + * small size (`upscale_from`). + * * The prompt is the model's template with `{prompt}` filled; the template is tokenised with its * special tokens and the prompt without, so a caller cannot write control tokens into it. */ @@ -55,6 +61,11 @@ struct Server::VideoJob { std::string err_code, err_message; std::string mp4; std::vector first; /* the first frame, RGB, for the thumbnail */ + /* Latent upscaling, as the generator resolved it: the factor, the evaluations after it and the + * small size; refine 0 when the video is not upscaled. */ + double upscale = 0.0; + int32_t refine = 0; + std::string upscale_from; int32_t w = 0, h = 0; bool worker_done = false; /* its thread has nothing left to do but return */ }; @@ -142,7 +153,7 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { } static const char* kKnown[] = { "model", "prompt", "seconds", "size", "input_reference", "seed", "num_inference_steps", - "task", "target", "conditions", "user", + "task", "target", "conditions", "user", "latent_upscale", "upscale_refine_steps", }; for (auto it = body.begin(); it != body.end(); ++it) { bool known = false; @@ -272,6 +283,25 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { " (sigma grid points, the last one 0)"); r->steps = (int32_t)v; } + if (has(body, "latent_upscale")) { + double v = 0; + if (!(info.upscale_max > 0.0)) + return error_response(err_unsupported("latent_upscale", "this model has no latent " + "upscaler"), req.peer); + if (!number(body["latent_upscale"], &v) || !(v >= 1.0) || v > info.upscale_max) + return bad("latent_upscale", "expected a factor from 1 to " + + rad::fmt("%g", info.upscale_max)); + r->upscale = v > 1.0 ? v : 0.0; + } + if (has(body, "upscale_refine_steps")) { + double v = 0; + if (r->upscale <= 1.0) + return bad("upscale_refine_steps", "counts the steps after a latent upscale; give " + "latent_upscale above 1 with it"); + if (!number(body["upscale_refine_steps"], &v) || v != std::floor(v) || v < 1 || v > 1e6) + return bad("upscale_refine_steps", "expected a positive integer"); + r->refine = (int32_t)v; + } bool seed_given = false; if (has(body, "seed")) { double v = 0; @@ -318,6 +348,7 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { r->ticket = j->ticket; const int64_t n_tok = (int64_t)r->tokens.size(); const int32_t steps = r->steps; + const double upscale = r->upscale; { std::string w; const int s = deps_.videos->submit(std::move(r), &w); @@ -328,9 +359,19 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { return error_response(e, req.peer); } } - RAD_INFO("video %s: %s, %lld frames (%s s), %lld prompt tokens, %d steps, seed=%llu", + const gen::VideoTicket& tk = *j->ticket; + if (tk.refine > 0) { + j->upscale = upscale; + j->refine = tk.refine; + j->upscale_from = std::to_string(tk.small_width) + "x" + std::to_string(tk.small_height); + } + RAD_INFO("video %s: %s, %lld frames (%s s), %lld prompt tokens, %d steps%s, seed=%llu", j->id.c_str(), j->size.c_str(), (long long)frames, j->seconds.c_str(), - (long long)n_tok, steps > 0 ? steps : (int)j->ticket->steps, + (long long)n_tok, steps > 0 ? steps : (int)tk.steps, + tk.refine > 0 ? rad::fmt(" (the first %d at %dx%d, upscaled for the last %d)", + (int)(tk.steps - tk.refine), (int)tk.small_width, + (int)tk.small_height, (int)tk.refine).c_str() + : "", (unsigned long long)j->seed); std::lock_guard lk(videos_m_); sweep_videos_locked(unix_now()); @@ -395,9 +436,16 @@ void Server::video_work(std::shared_ptr j) { j->completed_at = now; j->expires_at = now + opt_.video_ttl_s; j->mp4 = std::move(file); - RAD_INFO("video %s: completed, %.1f MB (%s), %.1f s", j->id.c_str(), - (double)j->mp4.size() / 1e6, mp4.video_encoder().c_str(), - (double)(t.t_done_ns - t.t_submit_ns) / 1e9); + auto sec = [](int64_t a, int64_t b) { return (double)(b - a) / 1e9; }; + const std::string steps = t.t_upscaled_ns > 0 + ? rad::fmt("small steps %.1f s, upscale %.2f s, full steps %.1f s", + sec(t.t_cond_ns, t.t_small_ns), sec(t.t_small_ns, t.t_upscaled_ns), + sec(t.t_upscaled_ns, t.t_denoised_ns)) + : rad::fmt("steps %.1f s", sec(t.t_cond_ns, t.t_denoised_ns)); + RAD_INFO("video %s: completed, %.1f MB (%s), %.1f s: queue and prompt %.1f s, %s, " + "decode %.1f s", j->id.c_str(), (double)j->mp4.size() / 1e6, + mp4.video_encoder().c_str(), sec(t.t_submit_ns, t.t_done_ns), + sec(t.t_submit_ns, t.t_cond_ns), steps.c_str(), sec(t.t_denoised_ns, t.t_done_ns)); } else { j->status = "failed"; j->failed = true; @@ -477,6 +525,11 @@ json Server::video_json(const VideoJob& j) { o["seconds"] = j.seconds; o["size"] = j.size; o["seed"] = j.seed; + if (j.refine > 0) { + o["latent_upscale"] = j.upscale; + o["upscale_refine_steps"] = j.refine; + o["upscale_from"] = j.upscale_from; + } o["remixed_from_video_id"] = nullptr; if (j.failed) { json e; diff --git a/data/recipes/minimax-h3-fp8.recipe b/data/recipes/minimax-h3-fp8.recipe index bf1eb7b1..cb06baa3 100644 --- a/data/recipes/minimax-h3-fp8.recipe +++ b/data/recipes/minimax-h3-fp8.recipe @@ -15,6 +15,15 @@ # --reuse minimax-h3-fp8.rad --changed \ # -o fasth3-8step-fp8.rad # +# LBH-123-AI's latent upscaler (Minimax_h3_latent_Upscaler, Apache-2.0) is a companion folder: +# put its config.json (minimax_h3_latent_upscaler_3d_conv_v1/config.json) and its bf16 weights, +# named diffusion_pytorch_model.safetensors, in latent_upscaler/ of the pipeline directory. It +# converts with the rest, or is appended to a container converted without it, which keeps every +# weight the container holds where it is: +# +# rad-convert --recipe data/recipes/minimax-h3-fp8.recipe \ +# --reuse minimax-h3-fp8.rad --in-place +# # Every linear of the text encoder's first 50 layers, of the token refiner and of the DiT's 50 # blocks, and the per-modality modulation projections, become E4M3 codes with a bf16 scale a # 128 x 128 block, read by the fp8a8 GEMMs. What keeps the checkpoint's precision is read once a @@ -44,3 +53,5 @@ vae.blk.*.ffn_up.weight cast dtype=bf16 vae.blk.*.ffn_down.weight cast dtype=bf16 vae.proj_out.* cast dtype=bf16 aud.*.weight cast dtype=f32 +ups.embed.* cast dtype=f32 +ups.*.emb_layers.* cast dtype=f32 diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index bf5cdad2..04a4b4ad 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -898,3 +898,33 @@ model supplies them (`--reuse`, the transformer's tensors listed as `--changed`; header). The distilled model's first evaluation moves 21-23% under any perturbation (the reference itself between bf16 and emulated fp8, or with the fp8 text encoder's conditioning), so its per-step numbers against the reference say little; radiance's frames and the reference's agree by eye. + +## The latent upscaler + +LBH-123-AI's `Minimax_h3_latent_Upscaler` (v1, `LatentResizer3D`, 345M parameters, Apache-2.0) is +read as a companion folder of either pipeline, `latent_upscaler/` (its config.json and bf16 +weights), and declared when the container carries it (RadVideoGenDecl::upscale_max is then its +largest factor). The architecture is the ComfyUI node's; the config states the same numbers: + +``` +input the clean small latent's voxels (patch rows unfolded), normalised a second time with the + upscaler's own per-channel mean and deviation (the node's (x - mean) / std on ComfyUI's + already-normalised latent), bf16 +factor (W / W' + H / H') / 2; Linear(1, 64) of (factor - 1), SiLU, Linear(64, 64), in f32; + each residual block's SiLU and Linear(64, 1024) gives its (scale, shift) +network conv_in 3x3x3 24 -> 512; 18 blocks at the small size; F.interpolate(trilinear, + align_corners=False) to the full size with the frame count kept, which is bilinear on + each frame (resize_bilinear); 18 blocks at the full size; GroupNorm(32), SiLU, + conv_out 3x3x3 512 -> 24. A block list is 12 residual blocks, a temporal block after + the 1st, 3rd, .. 11th +residual GroupNorm(32) SiLU conv3d; GroupNorm(32) * (1 + scale) + shift, SiLU, conv3d; + x + (group_norm, conv3d_ndhwc with the residual added in its store) +temporal GroupNorm(32) SiLU, a depthwise (5, 1, 1) convolution over frames (tconv_dw), a 1x1x1 + one (gemm_nt_bias with the residual) +output denormalised, folded back into patch rows (patch_fold), then the video latent and the + soundtrack's re-noised to the first full-size step's sigmas with stream 1 of their seeds + (flow_renoise) +``` + +The node runs the network on whole clips here (its temporal chunking is off in the example +workflows); every rank runs it whole, its weights in VRAM on each. diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 91076db6..c6fffd4a 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -2320,6 +2320,21 @@ encoder and decoders taken from a MiniMax-H3 container (`data/recipes/minimax-h3 how), served the same way and named `fastvideo-fasth3-8-step-v2`. Its card notes that difficult motion, fine detail and some audio may fall below the base model's; it serves text to video only. +**Latent upscaling.** A container that carries LBH-123-AI's latent upscaler +(`LBH-123-AI/Minimax_h3_latent_Upscaler`, Apache-2.0; the recipe says how to add it to a container, +in place) takes **`latent_upscale`**, a factor from 1 to 4: the first steps run at `size` divided +by it (each side rounded to a multiple of 32), the clean small latent is enlarged to `size` by the +upscaler, re-noised, and the last **`upscale_refine_steps`** run at the full size (3 of FastH3's 8 +and 12 of the base model's 49 by default). The steps at the small size cost a fraction of a +full-size step's, so most of the time goes to the refinement. The video object of an upscaled +video carries `latent_upscale`, the `upscale_refine_steps` it ran and `upscale_from`, the small +size. + +```sh +curl -s http://localhost:8000/v1/videos -H 'Content-Type: application/json' -d '{ + "prompt": "...", "size": "1344x768", "seed": 7, "latent_upscale": 2}' +``` + On two R9700s (`--tp 2`, 300 W) a 5.17 s clip at 1344x768 takes about 68 s with FastH3 and about 8.8 minutes with MiniMax-H3's default 50 steps. Both attentions run their scores in int8 and P.V in fp8 (docs/ARCHITECTURES.md); a step's cost grows with the square of the rows, so a longer @@ -2513,7 +2528,7 @@ is the part of a log to paste into an issue. Its sections: warning is also printed as a `W` line of its own. ``` -I STARTUP REPORT -- radiance 1.8.0 +I STARTUP REPORT -- radiance 1.8.1 I CONFIGURATION -- every option, the value in force, and where it came from I --model /models/flashnext.rad [command line] I --tp 2 [command line] diff --git a/docs/OPS.md b/docs/OPS.md index 60f04fa7..74571720 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -1073,7 +1073,8 @@ is [video sparse attention](#video-sparse-attention)) and its gated residual `gate_add` `act` none; the soundtrack's vocoder is `conv_t1d`, `snake_aa` and `conv1d` `clamp` ([Audio generation](#audio-generation)). Each op rounds where the reference model materialises a bf16 tensor and keeps f32 where it computes in f32; the libref function says which -(`libref/ref_gen.cpp`, `libref/ref_video.cpp`). +(`libref/ref_gen.cpp`, `libref/ref_video.cpp`). Its latent upscaler's ops are +[below](#the-latent-upscaler). | op | params | operands | |---|---|---| @@ -1245,6 +1246,81 @@ fp8 P.V form (`v` E4M3 codes, `v_scale` `[n_head * head_dim]`), before the epilo MiniMax-H3: `tile_t`, `tile_h` and `tile_w` 4, `patch` 2, `sparsity` 0.8, `head_dim` 128, the default `scale` `1 / sqrt(head_dim)`. +### The latent upscaler + +MiniMax-H3's latent upscaler (`LatentResizer3D`) is a 3-D convolutional network over the video +latent: its 24 channels to 512 by a 3 x 3 x 3 convolution, residual blocks +(`t = silu(GN(x)); h = conv3(t); t = silu(GN(h) (1 + scale) + shift); x = x + conv3(t)`, the +scale and shift from the upscale factor's embedding) and temporal blocks +(`t = silu(GN(x)); t = dwconv_t5(t); x = x + pwconv(t)`, the 1 x 1 x 1 `pwconv` a `gemm_nt_bias`) +at the source size, a spatial bilinear resize, the same blocks at the target size, and +`GroupNorm(32)`, SiLU and a 3 x 3 x 3 convolution back to 24 channels. `patch_fold` turns its output +back into the transformer's patch rows and `flow_renoise` takes them to the noise level a refining +pass starts from. Each op rounds once into its output (`libref/ref_video.cpp`). + +| op | params | operands | +|---|---|---| +| `conv3d_ndhwc` | `M`(range) `cin` `cout` `k` `kt` `dtype` | `x`, `w`w, `b`w, `geom`, `res`? โ†’ `y` | +| `group_norm` | `M`(range) `n` `groups` `eps`:f64 `act` `dtype` | `x`, `w`w, `b`w, `mod`?, `stats`:inout โ†’ `y` | +| `tconv_dw` | `M`(range) `n` `k` `dtype` | `x`, `w`w, `b`w, `geom` โ†’ `y` | +| `resize_bilinear` | `M`(range) `n` `dtype` | `x`, `geom` โ†’ `y` | +| `patch_fold` | `M`(range) `C` `pt` `ph` `pw` `mul` `add` `dtype` | `x`, `geom` โ†’ `y` | +| `flow_renoise` | `M`(range) `n` `stream` `dtype` | `sigma`, `seed`, `x`:inout | + +Activations are voxel rows: row `(t, i, j)` of a `T x H x W` volume is `(t H + i) W + j`, channels +innermost (NDHWC). `geom` is the request's volume, i32 on the device (the parameters are fixed at +declare). An output holds at least the rows the volume writes; rows past them are not written. +Every op honours its activation operands' row pitches. `rd` is a rounding into the output's dtype. + +- `conv3d_ndhwc`: `x [>= T H W, cin]`, `y` and `res` `[>= T H W, cout]`, `geom = (T, H, W)`; `w` is + PyTorch's Conv3d weight `[cout, cin, kt, k, k]` (a kernel may relayout it at load, as + `conv2d_nhwc`'s layout hook does) and `b [cout]`. Stride 1, zero padding `kt/2` frames and `k/2` + rows and columns on each side (`same`; `k` and `kt` odd): + `y[(t,i,j), o] = rd(f32(sum over (dt, kh, kw, ci) of w[o, ci, dt, kh, kw] + x[(t+dt-kt/2, i+kh-k/2, j+kw-k/2), ci]) + b[o])`, terms outside the volume zero, f32 accumulation + in an order of the implementation's (libref: the taps in `(dt, kh, kw)` order, each tap's + channels ascending). With `res`, `y = rd(rd(acc + b) + res)`: the convolution's output rounded, + then the residual added and rounded, as a block's `skip(x) + h` in bf16. `res` may be the same + memory as `y` (the residual added in place); `x` never aliases `y`. x, y, res and w bf16 (also + f32), b bf16 or f32. MiniMax-H3: `k` = `kt` = 3, `(cin, cout)` `(24, 512)`, `(512, 512)`, + `(512, 24)`. +- `group_norm` is PyTorch's `nn.GroupNorm(groups, n)` on `[1, n, T, H, W]`: `x` and `y` + `[>= M, n]` (`M` is `y`'s rows), group `g` the channels `[g n/groups, (g+1) n/groups)` of all + `M` rows. `mean_g` and the biased `var_g` are over the group's `M n/groups` values, accumulated in + f32 or better (libref: f64, two passes, row-major); `rstd_g = 1 / sqrt(f32(var_g) + eps)` in f32. + Then, in f32, `v = (x - mean_g) rstd_g w[c] + b[c]`; with `mod` (`[>= 2n]`, f32 or bf16, one row: + `scale = mod[0:n]`, `shift = mod[n:2n]`) `v = v (1 + scale[c]) + shift[c]`; `act` `none` or + `silu` (`v / (1 + exp(-v))`); one rounding into `y`. `stats` is f32 of at least + `groups (2 + 3 1024)` values: afterwards `stats[2g]` and `stats[2g+1]` hold group `g`'s `mean_g` + and `rstd_g`, and the rest is the implementation's scratch (partial sums of up to 1024 parts a + group; libref leaves it untouched). A kernel may take several launches but must be deterministic, + a fixed reduction order with no float atomics. `y` may be the same memory as `x`. `w` and `b` + `[n]`, bf16 or f32. MiniMax-H3: `n` 512, `groups` 32, `eps` 1e-5. +- `tconv_dw`: a depthwise convolution along the frames (a Conv3d of kernel `(k, 1, 1)`, one group a + channel): `geom = (T, H, W)`, `P = H W` rows a frame, `w` PyTorch's `[n, 1, k, 1, 1]` (tap `j` of + channel `c` at `c k + j`), `b [n]`, `k` odd: + `y[(t, p), c] = rd(f32(sum_j w[c, j] x[(t + j - k/2, p), c]) + b[c])`, frames outside `[0, T)` + zero, the sum f32 in ascending `j`. `x` never aliases `y`. MiniMax-H3: `n` 512, `k` 5. +- `resize_bilinear`: `geom = (T, h, w, H, W)`, `x [>= T h w, n]`, `y [>= T H W, n]`; each frame + resized on its own, as torch's `upsample_bilinear2d` with `align_corners=False` computes it for an + output size (not a scale factor): `sh = f32(h) / f32(H)`, `src = max(sh (f32(i) + 0.5) - 0.5, 0)` + in f32, `i0 = (int)src`, `i1 = i0 + (i0 < h - 1)`, `l1 = src - i0`, `l0 = 1 - l1`, the same for + columns, then + `v = l0y (l0x x[i0,j0] + l1x x[i0,j1]) + l1y (l0x x[i1,j0] + l1x x[i1,j1])` in f32 (each product + and sum one rounding), rounded once into `y`. Any sizes, shrinking too. The upscaler's + `F.interpolate(mode="trilinear")` at an unchanged frame count weighs each frame by exactly 1 and + its neighbour by 0, so this is that resize. `x` never aliases `y`. +- `patch_fold` is `patch_unfold`'s inverse, normalising: voxel rows + `x [(F pt) (Hp ph) (Wp pw), C]` to patch rows `y [F Hp Wp, C pt ph pw]`, `geom = (F, Hp, Wp)`, + `y[(f,i,j), c pt ph pw + a ph pw + b pw + d] = f32(f32(x[(f pt + a, i ph + b, j pw + d), c] + mul[c]) + add[c])`, `mul` and `add` lists of `C` values kept in f32. `x` bf16 or f32, `y` f32. + `M` is `y`'s rows. MiniMax-H3: `C` 24, `pt` 1, `ph` = `pw` = 2. +- `flow_renoise` re-noises a clean latent to noise level `s` with a fresh stream, over `x`'s rows: + `x[k, c] = f32(f32(f32(1 - s) x[k, c]) + f32(s z(k n + c)))`, `s` = `sigma` (f32 `[1]`), + `z(e) = rad_philox_normal_s(seed, stream, e)` (`abi/rad_philox.h`), `seed` u32 `[2]` low word + first, `stream` the parameter. `x` f32 `[M, n]` at its row pitch. MiniMax-H3: `n` 96 (the video's + patch rows) and 32 (the soundtrack's), `stream` 1. + ## Mixture of experts | op | params | operands | diff --git a/libavx/README.md b/libavx/README.md index 24816d51..5c54742e 100644 --- a/libavx/README.md +++ b/libavx/README.md @@ -3,7 +3,7 @@ The conventional op vocabulary in hand-written x86 SIMD, dispatched at run time by CPU feature. libavx is a kernel plugin beside `libref` and `libr4d`. libref is the only other host -implementation, and it is a slow reference. libavx implements all 150 of libref's ops with the +implementation, and it is a slow reference. libavx implements all 161 of libref's ops with the same schemas and the same answers to a tolerance, the image generator's included (below). cmake -S libavx -B build-avx -DCMAKE_PREFIX_PATH= && cmake --build build-avx -j4 @@ -639,6 +639,19 @@ per (head, query tile), 64 keys of a visible tile packed at a time for broadcast online softmax, as `attn_prefix_self`'s f32 form; a prefix query tile sees every tile, so the tasks are scheduled dynamically. +Its latent upscaler adds six (`avx_video.cpp`). `conv3d_ndhwc` is GEMMs over bands of patch rows, as +`conv2d_nhwc`: the weight re-laid once a launch as `[cout][dt][kh][kw][cin]`, an output voxel's +patch its 27 input voxels' channel runs (zeros outside the volume), each band one `gemm_nt_into` +into f32 rows; a row is then rounded once, or with `res` rounded, its residual added and rounded +again, the residual read before the row is written so it may be y. `group_norm` sums its +statistics in f64 over fixed 64-row blocks combined in block order, so its bytes do not depend on +the thread count, and keeps those sums in its own memory: only `stats[0, 2 groups)` is written. +Both are held to the tolerance table. `tconv_dw` (each tap's product rounded before its add, in +libref's order), `resize_bilinear` (the source rows and weights taken once a launch in libref's +f32 steps), `patch_fold` and `flow_renoise` (`rad_philox_normal_s` a Philox block at a time) are +libref's bit for bit and held to zero error by the hand-built cases. The convolution has not been +tuned: MiniMax-H3 is not served on the CPU. + ## Design choices Each choice below was measured on the platform above. The variants that did not pay are recorded @@ -701,7 +714,8 @@ and spills a 16-register file, costing more than the FMA saves, so the AVX and A avx_{elementwise,norm,hc,quant,gemm,attn,qsa,moe,gdn,sample,misc}.cpp the kernels; compiled 4x avx_gen.cpp the image generator's norms, sampler, lanes and decoder ops; compiled 4x avx_gen_attn.cpp attn_prefix_self, the generator's attention; compiled 4x - avx_video.cpp the video decoder's patch unfold, tiles, stitch and positions; compiled 4x + avx_video.cpp the video decoder's patch unfold, tiles, stitch and positions, and the + latent upscaler's convolutions, norm, resize, fold and re-noise; compiled 4x avx_vsa.cpp video sparse attention: the tile selection and the attention; compiled 4x avx_audio.cpp the audio generator's vocoder, sampler, embeddings and window ops; compiled 4x avx_harness.h plugin loading, row selection, the operand draw, guarded buffers, the diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index a36dbb2b..b9f8d505 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -748,6 +748,42 @@ std::vector build_cases() { add("grid_pos3", { HI("M", 40), HI("T", 2), HI("H", 3), HI("W", 4), HI("period", 27), HF("scale", 6.283185307179586) }); + /* The latent upscaler over libref's cube volumes (c x c x c, the largest M holds; every geom + * entry c, so the resize is the identity here): the 3-D convolution at odd channel counts, + * kernels 3 x 3 x 3 and 3 x 1 x 1, with the residual (a separate buffer), and at MiniMax-H3's + * widths 24 -> 512, 512 -> 512 and 512 -> 24 in bf16; the modulated group norm over a few rows + * and over three of avx's 64-row blocks; the temporal convolution with taps past both ends. + * Real resizes, an in-place residual, an unmodulated norm over y = x, uneven volumes and views + * of wider planes are avx_check_hand.cpp's. */ + for (const char* dt : { "f32", "bf16" }) { + struct Conv3 { int M, cin, cout, k, kt; }; + static const Conv3 kConv3[] = { { 27, 5, 13, 3, 3 }, { 64, 20, 52, 3, 3 }, + { 27, 24, 16, 1, 3 } }; + for (const Conv3& v : kConv3) + add("conv3d_ndhwc", { HI("M", v.M), HI("cin", v.cin), HI("cout", v.cout), + HI("k", v.k), HI("kt", v.kt), HS("dtype", dt) }, + 0, 2.0 * v.M * v.cout * v.cin * v.k * v.k * v.kt); + for (const char* act : { "silu", "none" }) + add("group_norm", { HI("M", 7), HI("n", 640), HI("groups", 32), HF("eps", 1e-5), + HS("act", act), HS("dtype", dt) }); + add("group_norm", { HI("M", 150), HI("n", 96), HI("groups", 4), HF("eps", 1e-5), + HS("act", "silu"), HS("dtype", dt) }); + add("tconv_dw", { HI("M", 27), HI("n", 645), HI("k", 5), HS("dtype", dt) }); + add("tconv_dw", { HI("M", 64), HI("n", 37), HI("k", 3), HS("dtype", dt) }); + add("resize_bilinear", { HI("M", 27), HI("n", 645), HS("dtype", dt) }); + for (int pt : { 1, 4 }) + add("patch_fold", { HI("M", 8), HI("C", 24), HI("pt", pt), HI("ph", 2), HI("pw", 2), + HS("mul", kStd24.c_str()), HS("add", kMean24.c_str()), + HS("dtype", dt) }); + } + struct Wide { int cin, cout; }; + for (const Wide v : { Wide{ 24, 512 }, Wide{ 512, 512 }, Wide{ 512, 24 } }) + add("conv3d_ndhwc", { HI("M", 27), HI("cin", v.cin), HI("cout", v.cout), HI("k", 3), + HI("kt", 3), HS("dtype", "bf16") }, + 0, 2.0 * 27 * v.cin * v.cout * 27); + add("flow_renoise", { HI("M", 9), HI("n", 96), HI("stream", 1), HS("dtype", "f32") }); + add("flow_renoise", { HI("M", 5), HI("n", 645), HI("stream", 7), HS("dtype", "f32") }); + /* Video sparse attention over the cubes libref describes: a 3 x 3 x 3 grid in boxes of 2 * after two dense segments of as many rows (P 8, V 8; sparsity 0.8 keeps 2), with and without * the coarse operands; and MiniMax-H3's boxes of 4 at patch 2 over a 10 x 5 x 5 grid after diff --git a/libavx/avx_check_hand.cpp b/libavx/avx_check_hand.cpp index 9d4b12c0..e1fa8986 100644 --- a/libavx/avx_check_hand.cpp +++ b/libavx/avx_check_hand.cpp @@ -2211,6 +2211,150 @@ void video_cases(std::vector& hs) { } } +/* ================================================================== the latent upscaler */ +/* Forms libref's cube descriptions do not draw: volumes of a different extent on every axis, an + * activation at a wider row pitch, the residual in place (res = y), a group norm in place (y = x) + * without its modulation and with a modulation row of the other dtype, statistics over several + * of avx's 64-row blocks and a part of one, kernels of other shapes, real resizes (MiniMax-H3's + * x2 and 4.2 x 4 ratios, and shrinking), output rows past the volume, the soundtrack's and the + * video's re-noise widths. tconv_dw, resize_bilinear, patch_fold and flow_renoise are held to + * zero error, libref's arithmetic bit for bit; the convolution's GEMM and the norm's statistics + * sum in another order and are held to the tolerance table. */ +void upscaler_cases(std::vector& hs) { + const auto zero = [](int64_t) { return 0.0f; }; + for (const uint32_t dt : { (uint32_t)RAD_F32, (uint32_t)RAD_BF16 }) { + const char* dn = dt == RAD_F32 ? "f32" : "bf16"; + const uint32_t other = dt == RAD_F32 ? (uint32_t)RAD_BF16 : (uint32_t)RAD_F32; + const std::string sfx = std::string(", ") + dn; + const double tol = dt == RAD_F32 ? 1e-5 : 6e-3; + + /* ---- conv3d_ndhwc ------------------------------------------------------------------ */ + { + const int64_t T = 2, H = 3, W = 4, R = T * H * W, ci = 7, co = 11; + Hand h(("2 x 3 x 4, x at a pitch, the residual in place, f32 bias" + sfx).c_str(), + "conv3d_ndhwc", tol); + h.view(dt, { R, ci }, { ci + 3, 1 }, R * (ci + 3), hfill(450)) + .dense(dt, { co, ci, 3, 3, 3 }, hfill(451, 0.3f)) + .dense(RAD_F32, { co }, hfill(452, 0.5f)) + .idx({ T, H, W }) + .dense(dt, { R, co }, hfill(453), true) + .alias(4) + .pi("M", R).pi("cin", ci).pi("cout", co).pi("k", 3).pi("kt", 3).ps("dtype", dn); + hs.push_back(std::move(h)); + + /* A temporal-only kernel over six frames of 2 x 3, two output rows past the volume. */ + const int64_t R2 = 6 * 2 * 3, ci2 = 9, co2 = 50; + Hand g(("6 x 2 x 3 at kernel 5 x 1 x 1, rows past the volume" + sfx).c_str(), + "conv3d_ndhwc", tol); + g.dense(dt, { R2, ci2 }, hfill(454)) + .dense(dt, { co2, ci2, 5, 1, 1 }, hfill(455, 0.3f)) + .dense(dt, { co2 }, hfill(456, 0.5f)) + .idx({ 6, 2, 3 }) + .none() + .dense(dt, { R2 + 2, co2 }, hfill(457), true) + .pi("M", R2 + 2).pi("cin", ci2).pi("cout", co2).pi("k", 1).pi("kt", 5) + .ps("dtype", dn); + hs.push_back(std::move(g)); + + Hand e(("an even kernel is refused" + sfx).c_str(), "conv3d_ndhwc", tol); + e.dense(dt, { R, ci }, hfill(458)) + .dense(dt, { co, ci, 3, 2, 2 }, hfill(459)) + .dense(dt, { co }, hfill(459)) + .idx({ T, H, W }) + .none() + .dense(dt, { R, co }, zero, true) + .pi("M", R).pi("cin", ci).pi("cout", co).pi("k", 2).pi("kt", 3).ps("dtype", dn) + .refuses(RAD_E_SHAPE); + hs.push_back(std::move(e)); + } + + /* ---- group_norm: stats f32 of exactly groups (2 + 3 1024) values --------------------- */ + { + const int64_t R = 200, n = 48, G = 6; + const auto offset = [](int64_t i) { return 2.5f + 3.0f * hfill(460)(i); }; + Hand h(("200 rows in 6 groups, y = x at a pitch, unmodulated" + sfx).c_str(), + "group_norm", tol); + h.view(dt, { R, n }, { n + 5, 1 }, R * (n + 5), offset) + .dense(dt, { n }, hfill(461)) + .dense(dt, { n }, hfill(462)) + .none() + .dense(RAD_F32, { G * (2 + 3 * 1024) }, zero, true) + .alias(0) + .pi("M", R).pi("n", n).pi("groups", G).pf("eps", 1e-5).ps("act", "none") + .ps("dtype", dn); + hs.push_back(std::move(h)); + + const int64_t R2 = 150, n2 = 96, G2 = 32; + Hand g(("150 rows in 32 groups of 3, a modulation row of the other dtype, silu" + + sfx).c_str(), "group_norm", tol); + g.dense(dt, { R2, n2 }, hfill(463, 2.0f)) + .dense(dt, { n2 }, hfill(464)) + .dense(dt, { n2 }, hfill(465)) + .dense(other, { 2 * n2 }, hfill(466, 0.5f)) + .dense(RAD_F32, { G2 * (2 + 3 * 1024) }, zero, true) + .dense(dt, { R2, n2 }, zero, true) + .pi("M", R2).pi("n", n2).pi("groups", G2).pf("eps", 1e-5).ps("act", "silu") + .ps("dtype", dn); + hs.push_back(std::move(g)); + } + + /* ---- tconv_dw: seven frames of 2 x 3, x at a pitch, rows past the volume ------------ */ + { + const int64_t R = 7 * 2 * 3, n = 37; + Hand h(("7 x 2 x 3 at k 5, x at a pitch, rows past the volume" + sfx).c_str(), + "tconv_dw", 0.0); + h.view(dt, { R, n }, { n + 3, 1 }, R * (n + 3), hfill(470)) + .dense(dt, { n, 1, 5, 1, 1 }, hfill(471, 0.5f)) + .dense(RAD_F32, { n }, hfill(472, 0.5f)) + .idx({ 7, 2, 3 }) + .dense(dt, { R + 2, n }, hfill(473), true) + .pi("M", R + 2).pi("n", n).pi("k", 5).ps("dtype", dn); + hs.push_back(std::move(h)); + } + + /* ---- resize_bilinear: up and down at once, H3's ratios, shrinking ------------------- */ + { + struct Rs { int64_t T, h, w, H, W, n; const char* what; }; + static const Rs kRs[] = { { 2, 3, 5, 7, 4, 37, "3 x 5 to 7 x 4" }, + { 2, 5, 3, 10, 6, 16, "5 x 3 to 10 x 6 (x2)" }, + { 1, 5, 3, 21, 12, 16, "5 x 3 to 21 x 12 (4.2 x 4)" }, + { 3, 6, 7, 4, 2, 20, "6 x 7 to 4 x 2" } }; + for (const Rs& v : kRs) { + const int64_t rin = v.T * v.h * v.w, rout = v.T * v.H * v.W; + Hand h((std::string(v.what) + ", x at a pitch, rows past" + sfx).c_str(), + "resize_bilinear", 0.0); + h.view(dt, { rin, v.n }, { v.n + 2, 1 }, rin * (v.n + 2), hfill(480 + v.h)) + .idx({ v.T, v.h, v.w, v.H, v.W }) + .dense(dt, { rout + 3, v.n }, hfill(481), true) + .pi("M", rout + 3).pi("n", v.n).ps("dtype", dn); + hs.push_back(std::move(h)); + } + } + + /* ---- patch_fold: 2 x 3 x 2 patches of 2 x 2 x 2, x at a pitch, rows past ------------ */ + { + Hand h(("2 x 3 x 2 patches of 2 x 2 x 2, x at a pitch, rows past" + sfx).c_str(), + "patch_fold", 0.0); + h.view(dt, { 96, 5 }, { 8, 1 }, 96 * 8, hfill(490, 3.0f)) + .idx({ 2, 3, 2 }) + .dense(RAD_F32, { 14, 40 }, hfill(491), true) + .pi("M", 14).pi("C", 5).pi("pt", 2).pi("ph", 2).pi("pw", 2) + .ps("mul", "0.5 1.25 -2 0.3 1.7").ps("add", "0.1 -0.2 0.3 0 2.5").ps("dtype", dn); + hs.push_back(std::move(h)); + } + } + + /* ---- flow_renoise: the video's 96 and the soundtrack's 32, rows at a wider pitch --------- */ + for (const int64_t n : { 96, 32 }) { + Hand h(("n " + std::to_string(n) + ", rows at a wider pitch").c_str(), "flow_renoise", 0.0); + h.dense(RAD_F32, { 1 }, [](int64_t) { return 0.37f; }) + .idx({ 12345, 81 }) + .view(RAD_F32, { 7, n }, { n + 5, 1 }, 7 * (n + 5), hfill(495, 2.0f), true) + .pi("M", 7).pi("n", n).pi("stream", 1).ps("dtype", "f32"); + hs.push_back(std::move(h)); + } +} + /* ================================================================== video sparse attention * What libref's descriptions cannot draw: uneven dense segments (13 and 14 rows: a tile each in * boxes of 4, two each in boxes of 2) before a 6 x 5 x 7 grid (a 10 x 14 latent at patch 2) with @@ -3892,6 +4036,7 @@ bool hand_cases(const Check& ck) { packed_cases(hs); gen_cases(hs); video_cases(hs); + upscaler_cases(hs); vsa_cases(hs); qsa_cases(hs); encoder_cases(hs); diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index 85ad14cc..25a08142 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -111,7 +111,8 @@ int avx_par_force(int threads); /* ---- video generation */ \ X(rms_mod) X(rms_mod_quant_fp8) X(flow_x0_step) X(patch_unfold) \ X(vtile_gather) X(vtile_stitch) X(grid_pos3) X(vsa_select) \ - X(attn_vsa) \ + X(attn_vsa) X(conv3d_ndhwc) X(group_norm) X(tconv_dw) \ + X(resize_bilinear) X(patch_fold) X(flow_renoise) \ /* ---- audio generation */ \ X(conv1d) X(conv_t1d) X(snake) X(cfg_topk_sample) \ X(rvq_embed) X(frame_mix_store) X(end_status) X(frame_store) \ diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 832f2127..d984c394 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -551,6 +551,22 @@ static const RadOperandSpec oAttnVsa[] = { OPD("q"), OPD("k"), OPD("v"), OPD("se OPD("geom"), OPD("sel"), OPD_O("coarse"), OPD_O("gate"), OUT("out"), OPD_O("k_i8"), OPD_O("k_scale"), OPD_O("v_scale") }; +/* ---- the latent upscaler (avx_video.cpp), as libref declares it; patch_fold takes + * patch_unfold's parameters and operands ------------------------------------------------------ */ +static const RadParamSpec pConv3d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"), + P_INT("kt"), P_STR("dtype") }; +static const RadOperandSpec oConv3d[] = { OPD("x"), WGT("w"), WGT("b"), OPD("geom"), + OPD_O("res"), OUT("y") }; +static const RadParamSpec pGroupNorm[] = { P_INT("M"), P_INT("n"), P_INT("groups"), P_F64("eps"), + P_STR("act"), P_STR("dtype") }; +static const RadOperandSpec oGroupNorm[] = { OPD("x"), WGT("w"), WGT("b"), OPD_O("mod"), + INOUT("stats"), OUT("y") }; +static const RadParamSpec pTconvDw[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_STR("dtype") }; +static const RadOperandSpec oTconvDw[] = { OPD("x"), WGT("w"), WGT("b"), OPD("geom"), OUT("y") }; +static const RadOperandSpec oResize[] = { OPD("x"), OPD("geom"), OUT("y") }; +static const RadParamSpec pFlowRenoise[] = { P_INT("M"), P_INT("n"), P_INT("stream"), + P_STR("dtype") }; +static const RadOperandSpec oFlowRenoise[] = { OPD("sigma"), OPD("seed"), INOUT("x") }; /* ---- audio generation (avx_audio.cpp), as libref declares it ------------------------------ */ static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"), @@ -935,6 +951,24 @@ static const RadOpSchema kSchemas[] = { "video sparse attention over libref's tiles: prefix queries dense, video queries the prefix " "and their `sel` tiles, blocked online softmax; the gated coarse term on the output rounded " "to its dtype." }, +{ "conv3d_ndhwc", ARR(pConv3d), ARR(oConv3d), + "a 3-D convolution over voxel rows, `same` zero padding, PyTorch's [cout, cin, kt, k, k] " + "weight, as GEMMs over bands of patch rows; with `res` (possibly y) rd(rd(acc + b) + res)." }, +{ "group_norm", ARR(pGroupNorm), ARR(oGroupNorm), + "a group norm over all rows, its statistics in f64 over fixed row blocks combined in order, " + "then the optional [scale | shift] row and silu, one rounding; stats[0, 2 groups) the mean " + "and rstd." }, +{ "tconv_dw", ARR(pTconvDw), ARR(oTconvDw), + "a depthwise convolution along a volume's frames, PyTorch's [n, 1, k, 1, 1] weight, zero " + "frames outside the volume." }, +{ "resize_bilinear", ARR(pMnD), ARR(oResize), + "each frame of a volume resized as torch's align_corners=False bilinear at a size, bit for bit " + "libref's." }, +{ "patch_fold", ARR(pPatchUnfold), ARR(oPatchUnfold), + "voxel rows to normalised patch rows, f32(f32(x * mul) + add), bit for bit libref's." }, +{ "flow_renoise", ARR(pFlowRenoise), ARR(oFlowRenoise), + "x = f32(f32(1 - s) x) + f32(s z), z the (seed, stream) normal stream at k n + c, bit for bit " + "libref's." }, { "conv1d", ARR(pConv1d), ARR(oConv1d), "a 1-D convolution over the sequences `cu_seqlens` bounds, channels innermost, PyTorch's " "[cout, cin, k] weight, dilation `dil`, centred or (`causal`) all on the left, zeros outside " @@ -1390,6 +1424,19 @@ SIMPLE("avx_vsa_select", "vsa_select", "attn", SIMPLE("avx_attn_vsa", "attn_vsa", "attn", "block-sparse attention over the prefix and selected video tiles, the gated coarse term", "float q, k, v, coarse, gate and out; i32 segs, geom and sel", L(attn_vsa)), +SIMPLE("avx_conv3d_ndhwc", "conv3d_ndhwc", "conv", + "a 3-D convolution over voxel rows, as GEMMs over patch rows", DT_FLOAT, L(conv3d_ndhwc)), +SIMPLE("avx_group_norm", "group_norm", "norm", + "a group norm over all rows, optionally modulated, then an activation", DT_FLOAT, + L(group_norm)), +SIMPLE("avx_tconv_dw", "tconv_dw", "conv", "a depthwise convolution along a volume's frames", + DT_FLOAT, L(tconv_dw)), +SIMPLE("avx_resize_bilinear", "resize_bilinear", "elem", + "each frame of a volume resized bilinearly", DT_FLOAT, L(resize_bilinear)), +SIMPLE("avx_patch_fold", "patch_fold", "elem", "voxel rows to normalised patch rows", DT_FLOAT, + L(patch_fold)), +SIMPLE("avx_flow_renoise", "flow_renoise", "elem", "a clean latent re-noised to a sigma", + DT_FLOAT, L(flow_renoise)), SIMPLE("avx_conv1d", "conv1d", "conv", "a 1-D convolution over sequences, as GEMMs over patch rows", DT_FLOAT, L(conv1d)), diff --git a/libavx/avx_video.cpp b/libavx/avx_video.cpp index 0ad422c9..431fe8c1 100644 --- a/libavx/avx_video.cpp +++ b/libavx/avx_video.cpp @@ -1,22 +1,36 @@ /* avx_video.cpp -- the video generator's ops around its decoder (docs/OPS.md, "Video * generation"): the latent's patch rows unfolded to voxels, the tiles a video decoder runs over, * gathered from the latent and stitched back into frames, and the rotary positions of a tile's - * tokens. + * tokens; and its latent upscaler's (docs/OPS.md, "The latent upscaler"): the 3-D convolution, + * the group norm, the temporal depthwise convolution, the per-frame resize, the fold back into + * patch rows and the re-noising. * - * Bit-exact with libref (libref/ref_video.cpp): they are copies and roundings, and a seed must - * give the same video bytes on both host libraries. Where libref multiplies and then adds in two - * roundings, `keep` stops the compiler from fusing the pair (this plugin is built with - * -ffp-contract=fast, libref without contraction); the stitch's bf16 blends are passes of whole - * rows through x's dtype (`narrow_row`), so a product is rounded before the sum reads it. + * Bit-exact with libref (libref/ref_video.cpp) but for conv3d_ndhwc and group_norm: they are + * copies, roundings and short sums in libref's order, and a seed must give the same video bytes + * on both host libraries. Where libref multiplies and then adds in two roundings, `keep` stops the + * compiler from fusing the pair (this plugin is built with -ffp-contract=fast, libref without + * contraction); the stitch's bf16 blends are passes of whole rows through x's dtype + * (`narrow_row`), so a product is rounded before the sum reads it. conv3d_ndhwc is GEMMs over + * patch rows and group_norm sums its statistics over fixed row blocks; both are held to the + * tolerance table. */ #include "avx_vec.h" #include "avx_common.h" +#include "rad_philox.h" #include #include using namespace avx; +namespace avx { +inline namespace AVX_SUFFIX { +/* gemm_nt's product over operands assembled by a composite kernel (avx_gemm.cpp). */ +int gemm_nt_into(const RadTensor* A, const RadTensor* B, const RadTensor* bias, const RadTensor* Y, + int64_t M, int64_t N, int64_t K); +} /* inline namespace AVX_SUFFIX */ +} /* namespace avx */ + namespace { inline int64_t at(const RadTensor* t, int64_t i) { return ldi(t, offlin(t, i)); } @@ -29,15 +43,51 @@ inline void narrow_row(uint32_t dt, float* v, int64_t n, float* tmp) { row_to_f32(dt, tmp, v, n); } -/* A value the compiler may not fuse into the next add. */ +/* A value the compiler may not fuse into the next add. At the scalar level a vector is a float. */ #if AVX_LEVEL == 0 inline float keep(float x) { __asm__("" : "+x"(x)); return x; } #elif AVX_LEVEL == 3 inline float keep(float x) { __asm__("" : "+v"(x)); return x; } +inline vf keep(vf x) { __asm__("" : "+v"(x)); return x; } #else inline float keep(float x) { __asm__("" : "+x"(x)); return x; } +inline vf keep(vf x) { __asm__("" : "+x"(x)); return x; } #endif +/* A dense rank-2 view of `rows` x `cols` elements of dtype `dt` at `data`. */ +inline RadTensor mat_view(void* data, uint32_t dt, int64_t rows, int64_t cols) { + RadTensor t{}; + t.data = data; + t.dtype = dt; + t.rank = 2; + t.shape[0] = rows; t.shape[1] = cols; + t.stride[0] = cols; t.stride[1] = 1; + return t; +} + +/* Elements [e0, e0 + cnt) of the normal stream (seed, stream) into out (abi/rad_philox.h): the same + * arithmetic as rad_philox_normal_s, with one Philox block and one log per element pair instead of + * one each per element (avx_audio.cpp's). */ +void philox_normals_s(uint64_t seed, uint64_t stream, uint64_t e0, int64_t cnt, float* out) { + uint64_t e = e0; + int64_t i = 0; + while (i < cnt) { + const uint64_t g = e >> 2; + uint32_t c[4] = { (uint32_t)g, (uint32_t)(g >> 32), (uint32_t)stream, + (uint32_t)(stream >> 32) }; + rad_philox4x32_10(c, (uint32_t)seed, (uint32_t)(seed >> 32)); + for (int pair = (int)((e & 3u) >> 1); pair < 2 && i < cnt; ++pair) { + const uint32_t wa = c[pair * 2], wb = c[pair * 2 + 1]; + const float ua = ((float)(wa >> 8) + 0.5f) * (1.0f / 16777216.0f); + const float ub = ((float)(wb >> 8) + 0.5f) * (1.0f / 16777216.0f); + const float r = sqrtf(-2.0f * logf(ua)); + const float t = 6.28318530717958647692f * ub; + if ((e & 1u) == 0) { out[i++] = r * cosf(t); ++e; } + if (i < cnt) { out[i++] = r * sinf(t); ++e; } + } + } +} + /* The f32 values of a space-separated list (libref's parse_f32_list): up to `cap` into out, the * count returned whatever it is. */ int64_t parse_f32(const char* s, float* out, int64_t cap) { @@ -143,6 +193,44 @@ AVX_KERNEL(patch_unfold) { return RAD_OK; } +/* ------------------------------------------------------------------ patch_fold */ +/* Voxel rows folded into normalised patch rows, f32(f32(x * mul[c]) + add[c]) (libref): a task + * is a patch, its pt ph pw voxel rows read once each and dealt into its row. */ +AVX_KERNEL(patch_fold) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *G = &a->t[1], *Y = &a->t[2]; + const int64_t C = p_int(a, "C", 0), pt = p_int(a, "pt", 0); + const int64_t ph = p_int(a, "ph", 0), pw = p_int(a, "pw", 0); + const char* ms = p_str(a, "mul", ""), *as = p_str(a, "add", ""); + /* Each number takes at least two characters but the last, so this bounds the count. */ + const int64_t cap = (int64_t)((std::strlen(ms) + std::strlen(as)) / 2 + 2); + float* lists = (float*)scratch_raw((size_t)(2 * cap + 16) * sizeof(float)); + float *mul = lists, *add = lists + cap; + if (C <= 0 || pt <= 0 || ph <= 0 || pw <= 0 || parse_f32(ms, mul, cap) != C || + parse_f32(as, add, cap) != C || numel(G) < 3) + return RAD_E_SHAPE; + const int64_t F = at(G, 0), Hp = at(G, 1), Wp = at(G, 2); + if (F <= 0 || Hp <= 0 || Wp <= 0) return RAD_E_SHAPE; + const int64_t vol = pt * ph * pw, Hv = Hp * ph, Wv = Wp * pw, K = C * vol; + const int64_t rows = F * Hp * Wp; + if (rows_of(Y, K) < rows || rows_of(X, C) < F * pt * Hv * Wv) return RAD_E_SHAPE; + + AVX_PARALLEL_FOR_IF(rows * K >= AVX_PAR_MIN) + for (int64_t pi = 0; pi < rows; ++pi) { + float* buf = scratch_f32((size_t)(K + C + 32)); + float *row = buf, *xs = buf + K + 16; + const int64_t f = pi / (Hp * Wp), i = (pi / Wp) % Hp, j = pi % Wp; + for (int64_t sub = 0; sub < vol; ++sub) { + const int64_t ta = sub / (ph * pw), tb = (sub / pw) % ph, td = sub % pw; + const int64_t r = ((f * pt + ta) * Hv + i * ph + tb) * Wv + j * pw + td; + const float* xr = in_row(X, rowoff(X, r, C), C, xs); + for (int64_t c = 0; c < C; ++c) row[c * vol + sub] = keep(xr[c] * mul[c]) + add[c]; + } + out_row(Y, rowoff(Y, pi, K), K, row); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ grid_pos3 */ /* A tile's rotary positions, f32(scale) g(c, n), g(c, n) = f32(f32(2 f32((c + 0.5) / n)) - 1) * (libref): one value an axis index, taken once a launch. */ @@ -351,3 +439,351 @@ AVX_KERNEL(vtile_stitch) { } return RAD_OK; } + +/* ================================================================== the latent upscaler + * Voxel rows (t, i, j) of a T x H x W volume, channels innermost, the volume in `geom`. */ + +/* ------------------------------------------------------------------ conv3d_ndhwc */ +/* A 3-D convolution as GEMMs over bands of patch rows, as conv2d_nhwc and conv1d take theirs. The + * weight [cout, cin, kt, k, k] is re-laid once a launch as [cout][dt][kh][kw][cin] (bf16 copies + * when it is bf16, f32 otherwise), so an output voxel's patch row is its kt k k input voxels' + * channel runs back to back, zeros outside the volume: bf16 copies when x is bf16 with dense + * rows, f32 otherwise. A band is one gemm_nt_into into f32 rows, the bias added there; each row + * is then rounded once into y, or with `res` rounded to y's dtype, its residual row added and + * rounded again. A band's residual rows are read before its rows of y are written, row by row, + * so `res` may be y. The patches and the weight live in thread_local vectors that keep their + * high-water size, leaving the GEMM's scratch arenas to it. */ +AVX_KERNEL(conv3d_ndhwc) { + if (a->n_t < 6 || !rad_args_have(a, 4) || !rad_arg_in(a, 5)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *W = &a->t[1], *B = &a->t[2], *G = &a->t[3]; + const RadTensor *R = rad_arg_in(a, 4), *Y = &a->t[5]; + const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0); + const int64_t k = p_int(a, "k", 0), kt = p_int(a, "kt", 0); + if (cin <= 0 || cout <= 0 || k <= 0 || kt <= 0 || !(k & 1) || !(kt & 1) || numel(G) < 3) + return RAD_E_SHAPE; + const int64_t T = at(G, 0), H = at(G, 1), Wd = at(G, 2); + if (T <= 0 || H <= 0 || Wd <= 0) return RAD_E_SHAPE; + const int64_t rows = T * H * Wd, taps = kt * k * k, KK = taps * cin; + if (rows_of(Y, cout) < rows || rows_of(X, cin) < rows || (R && rows_of(R, cout) < rows) || + numel(W) < cout * KK || numel(B) < cout) + return RAD_E_SHAPE; + static thread_local std::vector wbuf, pbuf; + static thread_local std::vector ybuf; + + /* ---- the weight, [cout][dt][kh][kw][cin] */ + const bool w16 = W->dtype == RAD_BF16; + wbuf.resize((size_t)(cout * KK) * (w16 ? 2 : 4) + 64); + uint8_t* wp = wbuf.data(); + AVX_PARALLEL_FOR_IF(cout * KK >= AVX_PAR_MIN) + for (int64_t co = 0; co < cout; ++co) + for (int64_t ci = 0; ci < cin; ++ci) + for (int64_t tp = 0; tp < taps; ++tp) { + const int64_t src = (co * cin + ci) * taps + tp, dst = co * KK + tp * cin + ci; + if (w16) ((uint16_t*)wp)[dst] = ((const uint16_t*)W->data)[src]; + else ((float*)wp)[dst] = ld_elem(W->data, W->dtype, src); + } + const RadTensor wt = mat_view(wp, w16 ? (uint32_t)RAD_BF16 : (uint32_t)RAD_F32, cout, KK); + + /* ---- bands of patch rows: at least 8 Mi elements and eight times the weight, so the GEMM's + * per-call weight pack is amortised, at most 32 Mi (64 MiB of bf16 kept after the call) */ + const bool x16 = X->dtype == RAD_BF16 && laststride(X) == 1; + const size_t ael = x16 ? 2 : 4; + const int64_t want = std::min((int64_t)1 << 25, + std::max((int64_t)1 << 23, 8 * cout * KK)); + const int64_t band = std::max(1, std::min(rows, want / KK)); + pbuf.resize((size_t)(band * KK) * ael + 64); + ybuf.resize((size_t)(band * cout) + 16); + char* pp = (char*)pbuf.data(); + float* yp = ybuf.data(); + const int64_t pz = kt / 2, ps = k / 2; + for (int64_t r0 = 0; r0 < rows; r0 += band) { + const int64_t nb = std::min(band, rows - r0); + AVX_PARALLEL_FOR_IF(nb * KK >= AVX_PAR_MIN) + for (int64_t pr = 0; pr < nb; ++pr) { + const int64_t r = r0 + pr, t = r / (H * Wd), i = (r / Wd) % H, j = r % Wd; + char* d = pp + (size_t)(pr * KK) * ael; + for (int64_t dz = 0; dz < kt; ++dz) + for (int64_t kh = 0; kh < k; ++kh) + for (int64_t kw = 0; kw < k; ++kw, d += (size_t)cin * ael) { + const int64_t tz = t + dz - pz, iy = i + kh - ps, ix = j + kw - ps; + if (tz < 0 || tz >= T || iy < 0 || iy >= H || ix < 0 || ix >= Wd) { + std::memset(d, 0, (size_t)cin * ael); + continue; + } + const int64_t xo = rowoff(X, (tz * H + iy) * Wd + ix, cin); + if (x16) { + std::memcpy(d, (const uint16_t*)X->data + xo, (size_t)cin * 2); + } else { + const float* s = in_row(X, xo, cin, (float*)d); + if (s != (const float*)d) std::memcpy(d, s, (size_t)cin * 4); + } + } + } + const RadTensor pt = mat_view(pp, x16 ? (uint32_t)RAD_BF16 : (uint32_t)RAD_F32, nb, KK); + const RadTensor yt = mat_view(yp, RAD_F32, nb, cout); + const int st = gemm_nt_into(&pt, &wt, B, &yt, nb, cout, KK); + if (st < 0) return st; + AVX_PARALLEL_FOR_IF(nb * cout >= AVX_PAR_MIN) + for (int64_t pr = 0; pr < nb; ++pr) { + float* row = yp + pr * cout; + if (R) { + float* buf = scratch_f32((size_t)(2 * cout + 32)); + float *tmp = buf, *rs = buf + cout + 16; + narrow_row(Y->dtype, row, cout, tmp); + const float* rr = in_row(R, rowoff(R, r0 + pr, cout), cout, rs); + for (int64_t c = 0; c < cout; ++c) row[c] += rr[c]; + } + out_row(Y, rowoff(Y, r0 + pr, cout), cout, row); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ group_norm */ +/* A group norm over all rows (libref's definition). The statistics are f64 sums over fixed blocks + * of 64 rows, each block's per-group sums in row-major order and the blocks combined in block + * order, so the bytes do not depend on the thread count; two passes, the variance about the f64 + * mean. The rows are then normalised in f32 from per-channel tables (the group's mean and rstd, + * w, b, 1 + scale and shift), each product kept apart from the add after it as libref rounds + * them, and rounded once. stats[0, 2 groups) gets the mean and rstd; the rest of `stats` is not + * touched, the block sums being kept in this plugin's own memory. */ +AVX_KERNEL(group_norm) { + if (a->n_t < 6 || !rad_args_have(a, 3) || !rad_arg_in(a, 4) || !rad_arg_in(a, 5)) + return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *W = &a->t[1], *B = &a->t[2], *MD = rad_arg_in(a, 3); + const RadTensor *ST = &a->t[4], *Y = &a->t[5]; + const int64_t n = p_int(a, "n", 0), G = p_int(a, "groups", 0); + const float eps = p_f32(a, "eps", 1e-5f); + static const char* const kActs[] = { "none", "silu" }; + const int act = p_enum(a, "act", kActs, 2, 0); + if (act < 0 || act > 1) return RAD_E_INVAL; + if (n <= 0 || G <= 0 || n % G || numel(W) < n || numel(B) < n || + (MD && numel(MD) < 2 * n) || numel(ST) < G * (2 + 3 * 1024)) + return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n), cg = n / G; + if (rows <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE; + constexpr int64_t kBlock = 64; + const int64_t nblk = (rows + kBlock - 1) / kBlock; + const double cnt = (double)rows * (double)cg; + static thread_local std::vector part; + part.assign((size_t)(nblk * G + 2 * G), 0.0); + double *ps = part.data(), *mu = ps + nblk * G, *var = mu + G; + + /* Block bk's per-group sums of x, or with `dev` of (x - mu)^2, into ps[bk G, (bk + 1) G). */ + for (const bool dev : { false, true }) { + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t bk = 0; bk < nblk; ++bk) { + float* xs = scratch_f32((size_t)n + 16); + double* s = ps + bk * G; + const int64_t r1 = std::min(rows, (bk + 1) * kBlock); + for (int64_t r = bk * kBlock; r < r1; ++r) { + const float* x = in_row(X, rowoff(X, r, n), n, xs); + for (int64_t g = 0; g < G; ++g) { + const float* xg = x + g * cg; + double acc = s[g]; + if (dev) { + for (int64_t c = 0; c < cg; ++c) { + const double d = (double)xg[c] - mu[g]; + acc += d * d; + } + } else { + for (int64_t c = 0; c < cg; ++c) acc += (double)xg[c]; + } + s[g] = acc; + } + } + } + for (int64_t g = 0; g < G; ++g) { + double tot = 0.0; + for (int64_t bk = 0; bk < nblk; ++bk) { + tot += ps[bk * G + g]; + ps[bk * G + g] = 0.0; + } + (dev ? var : mu)[g] = tot / cnt; + } + } + + /* Per-channel tables: mean, rstd, w, b, 1 + scale and shift. */ + float* tab = (float*)scratch_raw((size_t)(6 * n + 16) * sizeof(float)); + float *mc = tab, *rc = mc + n, *wc = rc + n, *bc = wc + n, *sc = bc + n, *sh = sc + n; + for (int64_t g = 0; g < G; ++g) { + const float m = (float)mu[g], rs = 1.0f / std::sqrt((float)var[g] + eps); + stt(ST, offlin(ST, 2 * g), m); + stt(ST, offlin(ST, 2 * g + 1), rs); + for (int64_t c = g * cg; c < (g + 1) * cg; ++c) { mc[c] = m; rc[c] = rs; } + } + for (int64_t c = 0; c < n; ++c) { + wc[c] = ld_elem(W->data, W->dtype, c); + bc[c] = ld_elem(B->data, B->dtype, c); + sc[c] = MD ? 1.0f + ldt(MD, offlin(MD, c)) : 1.0f; + sh[c] = MD ? ldt(MD, offlin(MD, n + c)) : 0.0f; + } + const bool modded = MD != nullptr; + + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* buf = scratch_f32((size_t)(2 * n + 32)); + float *xs = buf, *v = buf + n + 16; + const float* x = in_row(X, rowoff(X, r, n), n, xs); + const vf one = vf_set1(1.0f); + int64_t c = 0; + for (; c + VF_N <= n; c += VF_N) { + vf t = vf_mul(vf_sub(vf_loadu(x + c), vf_loadu(mc + c)), vf_loadu(rc + c)); + t = vf_add(keep(vf_mul(t, vf_loadu(wc + c))), vf_loadu(bc + c)); + if (modded) t = vf_add(keep(vf_mul(t, vf_loadu(sc + c))), vf_loadu(sh + c)); + if (act) t = vf_div(t, vf_add(one, vf_exp(vf_sub(vf_zero(), t)))); + vf_storeu(v + c, t); + } + for (; c < n; ++c) { + float t = (x[c] - mc[c]) * rc[c]; + t = keep(t * wc[c]) + bc[c]; + if (modded) t = keep(t * sc[c]) + sh[c]; + if (act) t = t / (1.0f + sc_exp(-t)); + v[c] = t; + } + out_row(Y, rowoff(Y, r, n), n, v); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ tconv_dw */ +/* A depthwise convolution along the frames, libref's sum bit for bit: each output row adds its + * in-volume taps in ascending order, every product rounded before its add, then the bias, a + * vector across the channels. The taps are re-laid once a launch as [k][n] f32 beside the bias. */ +AVX_KERNEL(tconv_dw) { + if (!rad_args_have(a, 5)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *W = &a->t[1], *B = &a->t[2], *G = &a->t[3], *Y = &a->t[4]; + const int64_t n = p_int(a, "n", 0), k = p_int(a, "k", 0); + if (n <= 0 || k <= 0 || !(k & 1) || numel(G) < 3 || numel(W) < n * k || numel(B) < n) + return RAD_E_SHAPE; + const int64_t T = at(G, 0), H = at(G, 1), Wd = at(G, 2); + if (T <= 0 || H <= 0 || Wd <= 0) return RAD_E_SHAPE; + const int64_t P = H * Wd, rows = T * P; + if (rows_of(Y, n) < rows || rows_of(X, n) < rows) return RAD_E_SHAPE; + float* tab = (float*)scratch_raw((size_t)((k + 1) * n + 16) * sizeof(float)); + for (int64_t c = 0; c < n; ++c) { + for (int64_t j = 0; j < k; ++j) tab[j * n + c] = ld_elem(W->data, W->dtype, c * k + j); + tab[k * n + c] = ld_elem(B->data, B->dtype, c); + } + const float* bias = tab + k * n; + + AVX_PARALLEL_FOR_IF(rows * n * k >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* buf = scratch_f32((size_t)(2 * n + 32)); + float *xs = buf, *acc = buf + n + 16; + const int64_t t = r / P, p = r % P; + for (int64_t c = 0; c < n; ++c) acc[c] = 0.0f; + for (int64_t j = 0; j < k; ++j) { + const int64_t tz = t + j - k / 2; + if (tz < 0 || tz >= T) continue; + const float* x = in_row(X, rowoff(X, tz * P + p, n), n, xs); + const float* w = tab + j * n; + int64_t c = 0; + for (; c + VF_N <= n; c += VF_N) + vf_storeu(acc + c, vf_add(vf_loadu(acc + c), + keep(vf_mul(vf_loadu(w + c), vf_loadu(x + c))))); + for (; c < n; ++c) acc[c] = acc[c] + keep(w[c] * x[c]); + } + int64_t c = 0; + for (; c + VF_N <= n; c += VF_N) + vf_storeu(acc + c, vf_add(vf_loadu(acc + c), vf_loadu(bias + c))); + for (; c < n; ++c) acc[c] = acc[c] + bias[c]; + out_row(Y, rowoff(Y, r, n), n, acc); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ resize_bilinear */ +/* Each frame resized as torch's align_corners=False bilinear at a size, libref's arithmetic bit + * for bit: the source rows, columns and weights of every output row and column are taken once a + * launch (libref's f32 steps, the product before the subtraction kept apart), and an output row + * is its four source rows blended, a vector across the channels, each product kept apart from + * the add after it. */ +AVX_KERNEL(resize_bilinear) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *G = &a->t[1], *Y = &a->t[2]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0 || numel(G) < 5) return RAD_E_SHAPE; + const int64_t T = at(G, 0), h = at(G, 1), w = at(G, 2), H = at(G, 3), Wd = at(G, 4); + if (T <= 0 || h <= 0 || w <= 0 || H <= 0 || Wd <= 0) return RAD_E_SHAPE; + const int64_t rows = T * H * Wd; + if (rows_of(Y, n) < rows || rows_of(X, n) < T * h * w) return RAD_E_SHAPE; + /* Per output index of each axis: two source indices, then two weights. */ + const int64_t E = H + Wd; + int64_t* idx = + (int64_t*)scratch_raw((size_t)E * (2 * sizeof(int64_t) + 2 * sizeof(float)) + 64); + float* lam = (float*)(idx + 2 * E); + auto axis = [&](int64_t e, int64_t o, int64_t in, int64_t out) { + const float s = (float)in / (float)out; + float src = keep(s * ((float)o + 0.5f)) - 0.5f; + if (src < 0.0f) src = 0.0f; + const int64_t i0 = (int64_t)src; + idx[2 * e] = i0; + idx[2 * e + 1] = i0 + (i0 < in - 1 ? 1 : 0); + lam[2 * e + 1] = src - (float)i0; + lam[2 * e] = 1.0f - lam[2 * e + 1]; + }; + for (int64_t i = 0; i < H; ++i) axis(i, i, h, H); + for (int64_t j = 0; j < Wd; ++j) axis(H + j, j, w, Wd); + + AVX_PARALLEL_FOR_IF(rows * n * 4 >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + const int64_t t = r / (H * Wd), i = (r / Wd) % H, j = r % Wd; + const int64_t i0 = idx[2 * i], i1 = idx[2 * i + 1]; + const int64_t j0 = idx[2 * (H + j)], j1 = idx[2 * (H + j) + 1]; + const float l0y = lam[2 * i], l1y = lam[2 * i + 1]; + const float l0x = lam[2 * (H + j)], l1x = lam[2 * (H + j) + 1]; + float* buf = scratch_f32((size_t)(5 * n + 80)); + float *s0 = buf, *s1 = s0 + n + 16, *s2 = s1 + n + 16, *s3 = s2 + n + 16, *v = s3 + n + 16; + const float* x00 = in_row(X, rowoff(X, (t * h + i0) * w + j0, n), n, s0); + const float* x01 = in_row(X, rowoff(X, (t * h + i0) * w + j1, n), n, s1); + const float* x10 = in_row(X, rowoff(X, (t * h + i1) * w + j0, n), n, s2); + const float* x11 = in_row(X, rowoff(X, (t * h + i1) * w + j1, n), n, s3); + const vf a0 = vf_set1(l0x), a1 = vf_set1(l1x), b0 = vf_set1(l0y), b1 = vf_set1(l1y); + int64_t c = 0; + for (; c + VF_N <= n; c += VF_N) { + const vf top = vf_add(keep(vf_mul(a0, vf_loadu(x00 + c))), + keep(vf_mul(a1, vf_loadu(x01 + c)))); + const vf bot = vf_add(keep(vf_mul(a0, vf_loadu(x10 + c))), + keep(vf_mul(a1, vf_loadu(x11 + c)))); + vf_storeu(v + c, vf_add(keep(vf_mul(b0, top)), keep(vf_mul(b1, bot)))); + } + for (; c < n; ++c) { + const float top = keep(l0x * x00[c]) + keep(l1x * x01[c]); + const float bot = keep(l0x * x10[c]) + keep(l1x * x11[c]); + v[c] = keep(l0y * top) + keep(l1y * bot); + } + out_row(Y, rowoff(Y, r, n), n, v); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ flow_renoise */ +/* x = f32(f32(f32(1 - s) x) + f32(s z)) over x's rows, z the (seed, stream) normal stream at + * k n + c (libref's, bit for bit): a row's draws come a Philox block at a time. */ +AVX_KERNEL(flow_renoise) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *SG = &a->t[0], *SD = &a->t[1], *X = &a->t[2]; + const int64_t n = p_int(a, "n", 0), sm = p_int(a, "stream", 0); + if (n <= 0 || sm < 0 || numel(SG) < 1 || numel(SD) < 2) return RAD_E_SHAPE; + const int64_t rows = rows_of(X, n); + if (rows <= 0) return RAD_E_SHAPE; + const float s = ldt(SG, offlin(SG, 0)), oms = 1.0f - s; + const uint64_t sd = (uint64_t)(uint32_t)at(SD, 0) | ((uint64_t)(uint32_t)at(SD, 1) << 32); + + AVX_PARALLEL_FOR_IF(rows * n * 8 >= AVX_PAR_MIN) + for (int64_t k = 0; k < rows; ++k) { + float* buf = scratch_f32((size_t)(3 * n + 48)); + float *xs = buf, *z = xs + n + 16, *o = z + n + 16; + const float* x = in_row(X, rowoff(X, k, n), n, xs); + philox_normals_s(sd, (uint64_t)sm, (uint64_t)(k * n), n, z); + const vf vo = vf_set1(oms), vs = vf_set1(s); + int64_t c = 0; + for (; c + VF_N <= n; c += VF_N) + vf_storeu(o + c, vf_add(keep(vf_mul(vo, vf_loadu(x + c))), + keep(vf_mul(vs, vf_loadu(z + c))))); + for (; c < n; ++c) o[c] = keep(oms * x[c]) + keep(s * z[c]); + out_row(X, rowoff(X, k, n), n, o); + } + return RAD_OK; +} diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index 5cd62ee7..05afe635 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -79,6 +79,10 @@ set(R4D_UNITS # decoder's patch unfold, tiles, stitch and rotary positions, and the soundtrack decoder's # alias-free SnakeBeta. "r4d_video|" + # A video latent upscaler: the 3x3x3 convolution as an implicit GEMM over voxel rows, the group + # norm, the temporal depthwise convolution, the per-frame bilinear resize, the patch fold and the + # re-noise. + "r4d_upscaler|" # Video sparse attention: the tile selection a distilled video transformer was trained with and # the block-sparse attention over it. "r4d_vsa|" diff --git a/libr4d/r4d_encoder_bf16.hip b/libr4d/r4d_encoder_bf16.hip index e8c28402..7fc9a5ef 100644 --- a/libr4d/r4d_encoder_bf16.hip +++ b/libr4d/r4d_encoder_bf16.hip @@ -359,6 +359,17 @@ __global__ __launch_bounds__(kThreads) void narrow_f16_kernel( __builtin_bit_cast(uint16_t, (_Float16)bf2f(x[(size_t)m * x_ld + i])); } +// ---------------------------------------------------------------------------- cast f32 -> bf16 +// ref_cast: the value rounded to nearest even once. +__global__ __launch_bounds__(kThreads) void narrow_bf16_kernel( + const float* __restrict__ x, uint16_t* __restrict__ y, uint32_t n, uint32_t x_ld, + uint32_t y_ld, uint32_t M) { + const uint32_t i = blockIdx.x * kThreads + threadIdx.x; + if (i >= n) return; + for (uint32_t m = blockIdx.y; m < M; m += gridDim.y) + y[(size_t)m * y_ld + i] = f32_to_bf16(x[(size_t)m * x_ld + i]); +} + // ---------------------------------------------------------------------------- the audio tower // Gemma 4's USM conformer: elementwise rectifier and clamp, the subsampler's segment-wise // convolution, the light-conv block's causal depthwise convolution, the relative-position table, @@ -866,6 +877,17 @@ extern "C" int r4d_narrow_bf16_f16(long x, long y, int M, int n, int x_ld, int y return hipGetLastError() == hipSuccess ? 0 : -4; } +extern "C" int r4d_narrow_f32_bf16(long x, long y, int M, int n, int x_ld, int y_ld, + long stream) { + if (!x || !y) return -1; + if (M <= 0 || n <= 0) return -2; + hipLaunchKernelGGL(narrow_bf16_kernel, + dim3((uint32_t)((n + kThreads - 1) / kThreads), grid_rows(M)), + dim3(kThreads), 0, (hipStream_t)stream, (const float*)x, (uint16_t*)y, + (uint32_t)n, (uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)M); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + extern "C" int r4d_relu_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream) { if (!x || !y) return -1; if (M <= 0 || n <= 0) return -2; @@ -1216,6 +1238,24 @@ extern "C" int r4d_rad_cast_f16(const RadArgs* a, RadStream s) { (int)y_ld, (long)(uintptr_t)s)); } +/* ------------------------------------------------------------------ cast f32 -> bf16 */ +extern "C" int r4d_rad_cast_bf16(const RadArgs* a, RadStream s) { + const RadTensor* x = r4d_opt(a, 0); + const RadTensor* y = r4d_opt(a, 1); + if (!x || !y) return R4D_NO(RAD_E_INVAL); + if (x->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); + R4D_NEED(dt_bf16(y)); + const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1)); + if (n <= 0) return R4D_NO(RAD_E_SHAPE); + long long M = 0, Mx = 0; + const long long y_ld = r4d_rows_pitch(y, n, &M); + const long long x_ld = r4d_rows_pitch(x, n, &Mx); + if (y_ld < 0 || x_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (M <= 0 || Mx < M) return R4D_NO(RAD_E_SHAPE); + return enc_status(r4d_narrow_f32_bf16(r4d_addr(x), r4d_addr(y), (int)M, (int)n, (int)x_ld, + (int)y_ld, (long)(uintptr_t)s)); +} + /* ------------------------------------------------------------------ the audio tower */ extern "C" int r4d_rad_relu(const RadArgs* a, RadStream s) { diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index 1cc610eb..88b34adb 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -1290,6 +1290,78 @@ extern "C" int r4d_rad_unrelayout_conv_tap(const RadParam* p, int n_p, int opera return RAD_OK; } +/* ---- conv3d_ndhwc: PyTorch's [cout][cin][kt][k][k] stored tap-major, [cout][kt][k][k][cin]. + * + * conv2d_nhwc's reordering with the frame tap outermost: the implicit GEMM (r4d_upscaler.hip) + * contracts over K = (tap, channel), tap = (dt k + dy) k + dx, the channel innermost, so a 16-byte + * read of a voxel row is eight consecutive K. Operand 1 of conv3d_ndhwc; the bias is read as + * stored. */ +namespace { +int conv3d_geom(const RadParam* p, int n_p, const RadTensor* pl, int n, long long* cout, + long long* cin, long long* taps) { + *cout = r4d_pgeti_or(p, n_p, "cout", 0); + *cin = r4d_pgeti_or(p, n_p, "cin", 0); + const long long k = r4d_pgeti_or(p, n_p, "k", 0), kt = r4d_pgeti_or(p, n_p, "kt", 0); + if (n != 1 || !pl || *cout <= 0 || *cin <= 0 || k <= 0 || kt <= 0) return RAD_E_SHAPE; + *taps = kt * k * k; + if (pl[0].dtype != RAD_BF16 || rad_tensor_numel(&pl[0]) != *cout * *cin * *taps) + return RAD_E_SHAPE; + return RAD_OK; +} +} /* namespace */ + +extern "C" int r4d_rad_layout_conv3d_tap(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, RadLayout* out) { + (void)sel; + if (!out) return RAD_E_INVAL; + if (operand != CONV_W_OPERAND) return RAD_E_UNSUPPORTED; + if (!enc || !rad_enc_is(enc, "plain")) return RAD_E_DTYPE; + long long co, ci, taps; + const int rc = conv3d_geom(p, n_p, pl, n, &co, &ci, &taps); + if (rc != RAD_OK) return rc; + fill(out, "r4d.conv3d.tap_major", RAD_BF16, co, taps * ci, co * taps * ci * 2); + return RAD_OK; +} + +extern "C" int r4d_rad_relayout_conv3d_tap(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, void* dst, + int64_t dst_bytes) { + RadLayout L; + const int rc = r4d_rad_layout_conv3d_tap(p, n_p, operand, enc, sel, pl, n, &L); + if (rc != RAD_OK) return rc; + if (dst_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE; + long long co, ci, taps; + conv3d_geom(p, n_p, pl, n, &co, &ci, &taps); + const uint16_t* s = (const uint16_t*)pl[0].data; + uint16_t* d = (uint16_t*)dst; + for (long long o = 0; o < co; ++o) + for (long long c = 0; c < ci; ++c) + for (long long t = 0; t < taps; ++t) + d[(o * taps + t) * ci + c] = s[(o * ci + c) * taps + t]; + return RAD_OK; +} + +extern "C" int r4d_rad_unrelayout_conv3d_tap(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const void* src, int64_t src_bytes, + const RadTensor* pl, int n) { + RadLayout L; + const int rc = r4d_rad_layout_conv3d_tap(p, n_p, operand, enc, sel, pl, n, &L); + if (rc != RAD_OK) return rc; + if (src_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE; + long long co, ci, taps; + conv3d_geom(p, n_p, pl, n, &co, &ci, &taps); + const uint16_t* s = (const uint16_t*)src; + uint16_t* d = (uint16_t*)pl[0].data; + for (long long o = 0; o < co; ++o) + for (long long c = 0; c < ci; ++c) + for (long long t = 0; t < taps; ++t) + d[(o * ci + c) * taps + t] = s[(o * taps + t) * ci + c]; + return RAD_OK; +} + /* ---- conv1d and conv_t1d: a vocoder's 1-D weights, reordered so K runs over (tap, channel) with * the channel innermost, as conv2d_nhwc's (r4d_audio.hip). Operand 1 of both. * diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 3d6a36ce..b6a81f1c 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -200,6 +200,14 @@ int r4d_rad_vtile_gather (const RadArgs*, RadStream); int r4d_rad_vtile_stitch (const RadArgs*, RadStream); int r4d_rad_grid_pos3 (const RadArgs*, RadStream); int r4d_rad_snake_aa (const RadArgs*, RadStream); +/* r4d_upscaler.hip: a video latent upscaler's 3D convolution, group norm, temporal depthwise + * convolution and resize, the patch fold and the re-noise. */ +int r4d_rad_conv3d_ndhwc (const RadArgs*, RadStream); +int r4d_rad_group_norm (const RadArgs*, RadStream); +int r4d_rad_tconv_dw (const RadArgs*, RadStream); +int r4d_rad_resize_bilinear (const RadArgs*, RadStream); +int r4d_rad_patch_fold (const RadArgs*, RadStream); +int r4d_rad_flow_renoise (const RadArgs*, RadStream); /* r4d_vsa.hip: video sparse attention's selection (scratch for the tile means) and attention. */ int r4d_rad_vsa_select (const RadArgs*, RadStream); int64_t r4d_rad_vsa_select_scratch (const RadArgs*); @@ -491,6 +499,14 @@ int r4d_rad_relayout_conv_tap(const RadParam*, int, int, const RadEncoding*, con const RadTensor*, int, void*, int64_t); int r4d_rad_unrelayout_conv_tap(const RadParam*, int, int, const RadEncoding*, const int*, const void*, int64_t, const RadTensor*, int); +/* conv3d_ndhwc's weight, PyTorch's [cout][cin][kt][k][k] stored tap-major [cout][kt][k][k][cin] + * (r4d_layout.cpp). */ +int r4d_rad_layout_conv3d_tap(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, RadLayout*); +int r4d_rad_relayout_conv3d_tap(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, void*, int64_t); +int r4d_rad_unrelayout_conv3d_tap(const RadParam*, int, int, const RadEncoding*, const int*, + const void*, int64_t, const RadTensor*, int); /* conv1d's weight, PyTorch's [cout][cin][k] stored [cout][k][cin], and conv_t1d's, PyTorch's * [cin][cout][2s] stored [s][cout][2][cin] (r4d_layout.cpp). */ int r4d_rad_layout_conv1d_tap(const RadParam*, int, int, const RadEncoding*, const int*, @@ -557,6 +573,7 @@ int r4d_rad_seg_mean (const RadArgs*, RadStream); int r4d_rad_qk_norm_rope (const RadArgs*, RadStream); int r4d_rad_cast_widen (const RadArgs*, RadStream); int r4d_rad_cast_f16 (const RadArgs*, RadStream); +int r4d_rad_cast_bf16 (const RadArgs*, RadStream); int r4d_rad_pool_rows (const RadArgs*, RadStream); int r4d_rad_relu (const RadArgs*, RadStream); int r4d_rad_silu (const RadArgs*, RadStream); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index aab24411..43345363 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -2331,6 +2331,34 @@ static const RadParamSpec pGridPos3[] = { P_INT("M"), P_INT("T"), P_INT("H"), P_ P_INT("period"), P_F64("scale") }; static const RadOperandSpec oGridPos3[] = { { "y", RAD_OPD_OUT, 0 } }; +/* ---- a video latent upscaler (r4d_upscaler.hip); the same specs as libref's. `geom` is the + * request's volume, i32 on the device; patch_fold takes patch_unfold's specs. */ +static const RadParamSpec pConv3d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"), + P_INT("kt"), P_STR("dtype") }; +static const RadOperandSpec oConv3d[] = { + { "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "b", RAD_OPD_WEIGHT, 0 }, + { "geom", RAD_OPD_IN, 0 }, { "res", RAD_OPD_IN, 1 }, { "y", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pGroupNorm[] = { P_INT("M"), P_INT("n"), P_INT("groups"), P_F64("eps"), + P_STR("act"), P_STR("dtype") }; +static const RadOperandSpec oGroupNorm[] = { + { "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "b", RAD_OPD_WEIGHT, 0 }, + { "mod", RAD_OPD_IN, 1 }, { "stats", RAD_OPD_INOUT, 0 }, { "y", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pTconvDw[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_STR("dtype") }; +static const RadOperandSpec oTconvDw[] = { + { "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "b", RAD_OPD_WEIGHT, 0 }, + { "geom", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 }, +}; +static const RadOperandSpec oResizeBil[] = { + { "x", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pFlowRenoise[] = { P_INT("M"), P_INT("n"), P_INT("stream"), + P_STR("dtype") }; +static const RadOperandSpec oFlowRenoise[] = { + { "sigma", RAD_OPD_IN, 0 }, { "seed", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 }, +}; + /* ---- video sparse attention (r4d_vsa.hip); the same specs as libref's. `segs` cuts the packed * rows into dense segments and the video grid, `geom` is the request's latent geometry; `sel` is * vsa_select's output and attn_vsa's input. `v` of vsa_select is read only for `coarse`. */ @@ -3017,6 +3045,25 @@ static const RadOpSchema kSchemas[] = { "tail."), SCHEMA("grid_pos3", pGridPos3, oGridPos3, "a video decoder's rotary positions over tiles of `period` rows, f32 [3, M]."), + SCHEMA("conv3d_ndhwc", pConv3d, oConv3d, + "a stride-1 `same` 3D convolution over NDHWC voxel rows of the device volume geom = " + "(T, H, W), PyTorch's [cout, cin, kt, k, k] weight, f32 accumulation; with `res`, " + "y = rd(rd(acc + b) + res), res may alias y."), + SCHEMA("group_norm", pGroupNorm, oGroupNorm, + "nn.GroupNorm over all of y's rows (biased variance, rstd in f32), then the optional " + "modulation v (1 + mod[0:n]) + mod[n:2n] and `act` (none or silu), one rounding; " + "stats[2g], stats[2g + 1] hold group g's mean and rstd, the rest is scratch."), + SCHEMA("tconv_dw", pTconvDw, oTconvDw, + "a depthwise convolution along the frames of the device volume geom = (T, H, W), " + "frames outside zero, taps in ascending order in f32, one rounding after the bias."), + SCHEMA("resize_bilinear", pGenMn, oResizeBil, + "each frame resized as torch's bilinear interpolation at a size, align_corners=False, " + "geom = (T, h, w, H, W), f32 and one rounding."), + SCHEMA("patch_fold", pPatchUnfold, oPatchUnfold, + "patch_unfold's inverse: voxel rows to f32 patch rows, x mul + add per channel."), + SCHEMA("flow_renoise", pFlowRenoise, oFlowRenoise, + "x = (1 - sigma) x + sigma z, z the (seed, stream) normal stream at element k n + c, " + "each step one f32 rounding."), SCHEMA("vsa_select", pVsa, oVsaSelect, "video sparse attention's selection over tiles of at most 64 rows (dense segments in " "chunks, the video grid in tile_t x tile_h x tile_w boxes): f32 tile means of q and k, " @@ -3312,6 +3359,11 @@ static const RadConstraint cCastWiden[] = { static const RadConstraint cCastF16[] = { C_IN("from", "bf16"), C_IN("to", "f16"), }; +/* `cast` narrowing f32 -> bf16, rounded to nearest even: an f32 latent into a bf16 network (the + * MiniMax-H3 latent upscaler's input voxels). */ +static const RadConstraint cCastNarrow[] = { + C_IN("from", "f32"), C_IN("to", "bf16"), +}; /* The encoder's dense attention: bidirectional, any window, at the (head_dim, gqa) pairs * r4d_attn_dense_bf16.hip compiles. */ /* Causal or not at head_dim 64: a vision tower's heads, and a codec's sliding causal layers. */ @@ -4196,6 +4248,18 @@ static const RadConstraint cGenF32[] = { C_IN("dtype", "f32") }; static const RadConstraint cPatchUnfold[] = { C_IN("dtype", "f32"), C_LE("C", 64) }; static const RadConstraint cGenAnyFloat[] = { C_IN("dtype", "bf16 f32") }; static const RadConstraint cSnakeAa[] = { C_IN("dtype", "f32"), C_LE("k", 32) }; +/* ---- a video latent upscaler (r4d_upscaler.hip). The convolution decodes 3 x 3 x 3 taps as + * constants and reads 16-byte chunks of a voxel row; the group norm puts a thread on an 8-channel + * chunk inside one group, a row's chunks a power of two dividing the 256-thread block (the shim + * checks that and n / groups % 8), and merges at most 256 groups; the temporal convolution keeps + * its 5-frame window in registers; the fold's lists are kernel arguments, 64 floats at most. */ +static const RadConstraint cConv3d[] = { C_IN("dtype", "bf16"), C_EQ("k", 3), C_EQ("kt", 3), + C_DIV("cin", 8) }; +static const RadConstraint cGroupNorm[] = { C_IN("dtype", "bf16 f32"), C_DIV("n", 8), + C_LE("n", 2048), C_LE("groups", 256) }; +static const RadConstraint cTconvDw[] = { C_IN("dtype", "bf16"), C_EQ("k", 5), C_DIV("n", 8) }; +static const RadConstraint cResizeBil[] = { C_IN("dtype", "bf16 f32"), C_DIV("n", 8) }; +static const RadConstraint cPatchFold[] = { C_IN("dtype", "bf16 f32"), C_LE("C", 64) }; static const RadConstraint cLnModQ[] = { C_IN("dtype", "bf16"), C_DIV("n", 128), C_LE("n", 8192), C_EQ("group", 128) }; /* The lane copies move 32-bit words, so any row of whole words: bf16 latents and an f32 mask. */ @@ -4356,6 +4420,15 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_cast_f16, nullptr, nullptr, nullptr, r4d_shape_cast }, +{ "cast_f32_bf16", "cast", "elem", + "y = x, f32 narrowed to bf16", + "any M and n; both row pitches are read off the operands", + "f32 in, bf16 out, rounded to nearest even", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cCastNarrow), NOTUNE, + nullptr, nullptr, r4d_rad_cast_bf16, nullptr, nullptr, nullptr, + r4d_shape_cast }, + { "act_mul_bf16", "act_mul", "elem", "gated activation over two operands: act(a) rounded, times b", "any n; a, b and y each at their own row pitch, so both may be column slices of one buffer", @@ -7224,6 +7297,57 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cSnakeAa), NOTUNE, nullptr, nullptr, r4d_rad_snake_aa }, + +/* ------------------------------------------------------------------- a video latent upscaler */ +{ "conv3d_ndhwc_bf16", "conv3d_ndhwc", "conv", + "a 3 x 3 x 3 video convolution as an implicit GEMM over (tap, cin): the weight stored tap-major " + "and read into registers, the voxels' tap neighbours staged through LDS", + "128 voxels x 128 output channels a block, 64 K a stage; k = kt = 3, cin % 8 == 0 (a multiple " + "of 64 decodes the tap once per cin / 64 stages); row pitches honoured, res may alias y", + "bf16 voxels, weight and residual, bf16 or f32 bias, fp32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cConv3d), NOTUNE, + nullptr, nullptr, r4d_rad_conv3d_ndhwc, nullptr, r4d_rad_layout_conv3d_tap, + r4d_rad_relayout_conv3d_tap, nullptr, r4d_rad_unrelayout_conv3d_tap }, + +{ "group_norm", "group_norm", "norm", + "GroupNorm over all rows in three launches: per-part (count, mean, M2), their merge to mean and " + "rstd, then the affine, modulation and SiLU a thread an 8-channel chunk", + "n % 8 == 0 with n / 8 a power of two up to 256, n / groups % 8 == 0, groups <= 256, M n / " + "groups < 2^24; row pitches honoured, y may alias x", + "bf16 or f32 rows, bf16 or f32 gain, bias and modulation, f32 statistics", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGroupNorm), NOTUNE, + nullptr, nullptr, r4d_rad_group_norm }, + +{ "tconv_dw_bf16", "tconv_dw", "conv", + "a depthwise convolution along the frames: a thread an 8-channel chunk of a frame position, the " + "5-frame window in registers over every frame", + "k = 5, n % 8 == 0, row pitches honoured", "bf16 voxels, weight and bias, fp32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cTconvDw), NOTUNE, + nullptr, nullptr, r4d_rad_tconv_dw }, + +{ "resize_bilinear", "resize_bilinear", "elem", + "torch's per-frame bilinear resize at a size: a thread an 8-channel chunk of an output voxel", + "n % 8 == 0, any sizes, row pitches honoured", "bf16 or f32 voxels, f32 arithmetic", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cResizeBil), NOTUNE, + nullptr, nullptr, r4d_rad_resize_bilinear }, + +{ "patch_fold_f32", "patch_fold", "elem", + "voxel rows folded to normalised patch rows, the geometry read on the device", + "C <= 64, row pitches honoured", "bf16 or f32 voxels, f32 patch rows", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cPatchFold), NOTUNE, + nullptr, nullptr, r4d_rad_patch_fold }, + +{ "flow_renoise_f32", "flow_renoise", "elem", + "a clean latent re-noised to sigma from a fresh normal stream: a thread a value", + "any M and n, row pitches honoured", "f32 latent and sigma, u32 seed words", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenF32), NOTUNE, + nullptr, nullptr, r4d_rad_flow_renoise }, }; /* ================================================================================== the exports */ diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 26c2907c..34bf4e0c 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -6421,6 +6421,643 @@ void snake_aa_cases(const Plugin& pl) { } /* namespace vid */ +/* ---- a video latent upscaler's ops, at MiniMax-H3's shapes --------------------------------------- + * + * The upscaler runs a 37-frame clip at its 42 x 24 latent (the source) and at 84 x 48 (the + * target), 512 channels, 24 at its two ends; a 15 s clip is 102 frames. Each case compares with + * the host port of its libref function (libref/ref_video.cpp): the temporal convolution, the + * resize and the fold bit for bit, since the kernels keep the reference's order; the 3D + * convolution to a relative L2 over sampled output rows (its f32 sum runs in its own order), every + * face voxel of the first and last frames among them; the group norm to a relative L2 against f64 + * statistics, its own bytes identical over two runs; the noise through the device's log, sin and + * cos. Rows and columns an op must not write are filled with a marker and checked after. */ +namespace ups { + +using namespace au; + +/* f(i) for i in [0, n), strided over the host's cores. */ +template void par_for(int64_t n, F&& f) { + const unsigned hc = std::thread::hardware_concurrency(); + const int nt = (int)std::max(1u, std::min(32u, hc ? hc : 1u)); + std::vector th; + for (int k = 0; k < nt; ++k) + th.emplace_back([&, k]() { for (int64_t i = k; i < n; i += nt) f(i); }); + for (std::thread& t : th) t.join(); +} + +constexpr uint16_t kMark = 0x7f7fu; /* a bf16 marker no kernel here writes: 3.39e38 */ + +/* A bf16 operand of `rows` rows at pitch `ld`: its first `fill` rows' first n columns from `v` + * (rounded in place), every other element the marker. */ +void* up_rows(std::vector& v, int64_t rows, int64_t n, int64_t ld, int64_t fill) { + std::vector b((size_t)(rows * ld), kMark); + for (int64_t r = 0; r < fill; ++r) + for (int64_t c = 0; c < n; ++c) { + const uint16_t h = h_to_bf16(v[(size_t)(r * n + c)]); + b[(size_t)(r * ld + c)] = h; + v[(size_t)(r * n + c)] = h_bf16(h); + } + void* d = dalloc(b.size() * 2); + if (d) st_memcpy(d, b.data(), b.size() * 2, hipMemcpyHostToDevice); + return d; +} +std::vector down_u16(void* d, size_t n) { + std::vector b(n); + st_memcpy(b.data(), d, n * 2, hipMemcpyDeviceToHost); + return b; +} +/* Markers an op overwrote: columns [n, ld) of the first `used` rows, and every row from `used`. */ +int64_t marks_moved(const std::vector& b, int64_t rows, int64_t n, int64_t ld, + int64_t used) { + int64_t bad = 0; + for (int64_t r = 0; r < rows; ++r) + for (int64_t c = r < used ? n : 0; c < ld; ++c) bad += b[(size_t)(r * ld + c)] != kMark; + return bad; +} +RadTensor pitched(void* d, uint32_t dt, int64_t rows, int64_t n, int64_t ld) { + RadTensor t = T(d, dt, { rows, n }); + t.stride[0] = ld; + return t; +} + +/* ------------------------------------------------------------------ conv3d_ndhwc */ +struct Vol { int64_t T, H, W; }; + +/* Every voxel on a face of the first and last frames, and a hashed sample of the rest of about + * `want` rows. */ +std::vector conv_rows(const Vol& v, int64_t M, int64_t want) { + std::vector rows; + const int64_t HW = v.H * v.W; + const uint32_t every = (uint32_t)std::max(1, M / want); + for (int64_t r = 0; r < M; ++r) { + const int64_t t = r / HW, y = (r / v.W) % v.H, x = r % v.W; + const bool face = (t == 0 || t == v.T - 1) && + (y == 0 || y == v.H - 1 || x == 0 || x == v.W - 1); + if (face || st_mix32((uint32_t)r * 2654435761u) % every == 0) rows.push_back(r); + } + return rows; +} + +/* libref's conv3d_ndhwc at output row r: the products (exact in f32) summed in f64, rounded to f32, + * the bias added in f32 and rounded; with a residual, that plus the residual, rounded. `wt` is the + * weight tap-major, as the row stores it. */ +void conv3d_row(const std::vector& x, int64_t cin, const std::vector& wt, + const std::vector& b, const float* res, const Vol& v, int64_t cout, + int64_t r, float* out) { + const int64_t HW = v.H * v.W, t = r / HW, y = (r / v.W) % v.H, xx = r % v.W; + std::vector acc((size_t)cout, 0.0); + for (int64_t tap = 0; tap < 27; ++tap) { + const int64_t nt = t + tap / 9 - 1, ny = y + (tap / 3) % 3 - 1, nx = xx + tap % 3 - 1; + if (nt < 0 || nt >= v.T || ny < 0 || ny >= v.H || nx < 0 || nx >= v.W) continue; + const float* xr = &x[(size_t)((nt * HW + ny * v.W + nx) * cin)]; + for (int64_t o = 0; o < cout; ++o) { + const float* wr = &wt[(size_t)((o * 27 + tap) * cin)]; + double s = 0.0; + for (int64_t c = 0; c < cin; ++c) s += (double)(wr[c] * xr[c]); + acc[(size_t)o] += s; + } + } + for (int64_t o = 0; o < cout; ++o) { + float f = bfr((float)acc[(size_t)o] + b[(size_t)o]); + if (res) f = bfr(f + res[o]); + out[o] = f; + } +} + +struct ConvCase { + const char* what; + Vol v; + int64_t cin, cout; + int res; /* 0 none, 1 its own operand, 2 the output itself */ + bool bf32; /* an f32 bias */ + int64_t xpad, ypad, yextra; /* pitch padding, output rows past the volume */ + int64_t mshort; /* the M parameter this short of T H W: the volume's rows are written */ + int64_t sample; /* rows checked besides the faces; 0 every row */ +}; + +void conv3d_case(const RadKernelInfo* r, const ConvCase& c) { + const Vol& v = c.v; + const int64_t vol = v.T * v.H * v.W, M = vol, K = 27 * c.cin; + const int64_t ldx = c.cin + c.xpad, ldy = c.cout + c.ypad, yrows = M + c.yextra; + const std::string nm = fmt("conv3d_ndhwc_bf16 %s: %lld -> %lld at %lld x %lld, %lld frames%s%s%s", + c.what, (long long)c.cin, (long long)c.cout, (long long)v.H, + (long long)v.W, (long long)v.T, + c.res == 2 ? ", res in place" : c.res ? ", res" : "", + c.bf32 ? ", f32 bias" : "", + c.xpad || c.ypad || c.yextra || c.mshort ? ", pitched" : ""); + g_seed = 0xc03dull + (uint64_t)(c.cin * 131 + c.cout * 7 + v.T); + std::vector x = randv((size_t)(vol * c.cin), 1.0f); + std::vector w = randv((size_t)(c.cout * K), 1.5f / std::sqrt((float)K)); + std::vector b = randv((size_t)c.cout, 0.5f); + std::vector res = c.res ? randv((size_t)(M * c.cout), 1.0f) : std::vector(); + for (auto& e : w) e = bfr(e); + if (!c.bf32) for (auto& e : b) e = bfr(e); + std::vector wt((size_t)(c.cout * K)); + for (int64_t o = 0; o < c.cout; ++o) + for (int64_t ci = 0; ci < c.cin; ++ci) + for (int64_t t = 0; t < 27; ++t) + wt[(size_t)((o * 27 + t) * c.cin + ci)] = w[(size_t)((o * c.cin + ci) * 27 + t)]; + std::vector ps = { PI("M", M - c.mshort), PI("cin", c.cin), PI("cout", c.cout), + PI("k", 3), PI("kt", 3), PS("dtype", "bf16") }; + void* dw = stored_weight(r, ps, w, c.cout, K, nm.c_str()); + void* dx = up_rows(x, vol, c.cin, ldx, vol); + std::vector bb = b; + void* db = c.bf32 ? up_f32(b) : up_bf16(bb); + void* dres = c.res == 1 ? up_rows(res, M, c.cout, c.cout, M) : nullptr; + /* In place, y starts as the residual. */ + void* dy = up_rows(res, yrows, c.cout, ldy, c.res == 2 ? M : 0); + if (!dw || !dx || !db || !dy || (c.res == 1 && !dres)) { + ok(nm.c_str(), false, "hipMalloc failed"); + return; + } + RadTensor tres = c.res == 1 ? T(dres, RAD_BF16, { M, c.cout }) + : c.res == 2 ? pitched(dy, RAD_BF16, M, c.cout, ldy) + : T(nullptr, RAD_BF16, { 1 }); + if (!c.res) absent(tres); + const int rc = launch(r, { pitched(dx, RAD_BF16, vol, c.cin, ldx), T(dw, RAD_BF16, { c.cout, K }), + T(db, c.bf32 ? RAD_F32 : RAD_BF16, { c.cout }), + TI32({ 3 }, { (int32_t)v.T, (int32_t)v.H, (int32_t)v.W }), tres, + pitched(dy, RAD_BF16, yrows, c.cout, ldy) }, + ps); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); return; } + const std::vector yb = down_u16(dy, (size_t)(yrows * ldy)); + std::vector rows; + if (c.sample) { + rows = conv_rows(v, M, c.sample); + } else { + for (int64_t i = 0; i < M; ++i) rows.push_back(i); + } + std::vector want(rows.size() * (size_t)c.cout), got(want.size()); + par_for((int64_t)rows.size(), [&](int64_t i) { + const int64_t rr = rows[(size_t)i]; + conv3d_row(x, c.cin, wt, b, c.res ? &res[(size_t)(rr * c.cout)] : nullptr, v, c.cout, rr, + &want[(size_t)i * c.cout]); + for (int64_t o = 0; o < c.cout; ++o) + got[(size_t)i * c.cout + o] = h_bf16(yb[(size_t)(rr * ldy + o)]); + }); + check(fmt("%s, %zu rows", nm.c_str(), rows.size()), got, want, 5e-4); + const int64_t moved = marks_moved(yb, yrows, c.cout, ldy, M); + ok((nm + ": columns past cout and rows past the volume untouched").c_str(), moved == 0, + fmt("%lld marker values written", (long long)moved)); +} + +void conv3d_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "conv3d_ndhwc_bf16"); + if (!r) { ok("conv3d_ndhwc_bf16", false, "row absent"); return; } + const Vol src{ 37, 42, 24 }, dst{ 37, 84, 48 }; + for (const ConvCase& c : { + /* The model's four convolutions at its two sizes. */ + ConvCase{ "conv_in", src, 24, 512, 0, false, 0, 0, 0, 0, 3000 }, + ConvCase{ "source block", src, 512, 512, 2, false, 0, 0, 0, 0, 3000 }, + ConvCase{ "target block", dst, 512, 512, 0, true, 0, 0, 0, 0, 3000 }, + ConvCase{ "conv_out", dst, 512, 24, 0, false, 0, 0, 0, 0, 3000 }, + /* Edges, every row checked: an odd volume (no block or tile fills) with pitched + * operands, rows past the volume and a declared M short of it, into 40 channels (a + * partial tile); one frame (no temporal neighbour); one row of voxels; two channel + * tiles a tap into 136 channels. */ + ConvCase{ "odd volume", Vol{ 3, 5, 7 }, 64, 40, 1, false, 8, 16, 5, 3, 0 }, + ConvCase{ "one frame", Vol{ 1, 9, 13 }, 16, 24, 2, true, 0, 8, 2, 0, 0 }, + ConvCase{ "one row", Vol{ 4, 1, 21 }, 8, 8, 0, false, 8, 0, 0, 0, 0 }, + ConvCase{ "two tiles a tap", Vol{ 2, 11, 6 }, 128, 136, 2, false, 0, 0, 7, 0, 0 }, + }) + conv3d_case(r, c); + /* A 15 s clip at the target size: 411264 rows, the largest volume the model runs. */ + conv3d_case(r, ConvCase{ "102 frames", Vol{ 102, 84, 48 }, 512, 512, 2, false, 0, 0, 0, 0, 2000 }); + + /* Refusals: a 5-wide kernel, a channel count off the 16-byte chunk. */ + ok("conv3d_ndhwc_bf16 refuses k 5", + launch(r, { TA(RAD_BF16, { 8, 8 }), TA(RAD_BF16, { 8, 1000 }), TA(RAD_BF16, { 8 }), + TI32({ 3 }, { 2, 2, 2 }), TA(RAD_BF16, { 8, 8 }), TA(RAD_BF16, { 8, 8 }) }, + { PI("M", 8), PI("cin", 8), PI("cout", 8), PI("k", 5), PI("kt", 3), + PS("dtype", "bf16") }) == RAD_E_SHAPE); + ok("conv3d_ndhwc_bf16 refuses cin 12", + launch(r, { TA(RAD_BF16, { 8, 12 }), TA(RAD_BF16, { 8, 324 }), TA(RAD_BF16, { 8 }), + TI32({ 3 }, { 2, 2, 2 }), TA(RAD_BF16, { 8, 8 }), TA(RAD_BF16, { 8, 8 }) }, + { PI("M", 8), PI("cin", 12), PI("cout", 8), PI("k", 3), PI("kt", 3), + PS("dtype", "bf16") }) == RAD_E_SHAPE); +} + +/* ------------------------------------------------------------------ group_norm */ +/* libref's group_norm: the statistics in f64, rstd = 1 / sqrt(var + eps) in f32, the rest in f32 + * and one rounding, to bf16 when `bf`. */ +void gn_ref(const std::vector& x, int64_t M, int64_t n, int64_t groups, + const std::vector& w, const std::vector& b, + const std::vector* mod, bool silu, float eps, bool bf, std::vector* y, + std::vector* mean, std::vector* rstd) { + const int64_t gs = n / groups; + mean->assign((size_t)groups, 0.0f); + rstd->assign((size_t)groups, 0.0f); + par_for(groups, [&](int64_t g) { + double s = 0.0; + for (int64_t r = 0; r < M; ++r) + for (int64_t c = g * gs; c < (g + 1) * gs; ++c) s += x[(size_t)(r * n + c)]; + const double mu = s / (double)(M * gs); + double q = 0.0; + for (int64_t r = 0; r < M; ++r) + for (int64_t c = g * gs; c < (g + 1) * gs; ++c) { + const double d = x[(size_t)(r * n + c)] - mu; + q += d * d; + } + (*mean)[(size_t)g] = (float)mu; + (*rstd)[(size_t)g] = 1.0f / std::sqrt((float)(q / (double)(M * gs)) + eps); + }); + y->assign((size_t)(M * n), 0.0f); + par_for(M, [&](int64_t r) { + for (int64_t c = 0; c < n; ++c) { + const int64_t g = c / gs; + float v = (x[(size_t)(r * n + c)] - (*mean)[(size_t)g]) * (*rstd)[(size_t)g] * + w[(size_t)c] + b[(size_t)c]; + if (mod) v = v * (1.0f + (*mod)[(size_t)c]) + (*mod)[(size_t)(n + c)]; + if (silu) v = v / (1.0f + std::exp(-v)); + (*y)[(size_t)(r * n + c)] = bf ? bfr(v) : v; + } + }); +} + +void group_norm_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "group_norm"); + if (!r) { ok("group_norm", false, "row absent"); return; } + struct G { + const char* what; + int64_t M, n, groups; + bool xf, yf, wf; /* f32 rows in, out; an f32 gain and bias */ + int mod; /* 0 none, 1 bf16, 2 f32 */ + bool silu, inplace; + float offset; /* added to every value: a mean far from zero */ + int64_t pad; + }; + for (const G& g : { + /* The target size modulated with SiLU (a block's second norm), then plain with SiLU + * in place (its first); the source size over a large mean. */ + G{ "target, modulated", 37 * 84 * 48, 512, 32, false, false, false, 1, true, false, 0.0f, 0 }, + G{ "target, in place", 37 * 84 * 48, 512, 32, false, false, true, 0, true, true, 0.0f, 0 }, + G{ "source, mean 40", 37 * 42 * 24, 512, 32, false, false, false, 2, false, false, 40.0f, 0 }, + /* Edges: f32 rows both ways, pitched; one row; 64 channels in 8 groups. */ + G{ "f32 rows", 37, 512, 32, true, true, true, 2, true, false, 1.0f, 8 }, + G{ "f32 in, bf16 out", 101, 512, 32, true, false, false, 0, false, false, -3.0f, 16 }, + G{ "one row", 1, 512, 32, false, false, false, 1, true, false, 0.0f, 0 }, + G{ "64 channels", 1000, 64, 8, false, true, false, 0, true, false, 0.0f, 8 }, + }) { + const int64_t M = g.M, n = g.n, ld = n + g.pad, rows = M + 2; + const std::string nm = fmt("group_norm %s: %lld x %lld in %lld groups", g.what, + (long long)M, (long long)n, (long long)g.groups); + g_seed = 0x6a0ull + (uint64_t)M; + std::vector x = randv((size_t)(M * n), 2.0f); + for (auto& e : x) e += g.offset; + std::vector w = randv((size_t)n, 1.0f), b = randv((size_t)n, 0.5f); + std::vector mod = randv((size_t)(2 * n), 0.5f); + if (!g.wf) { for (auto& e : w) e = bfr(e); for (auto& e : b) e = bfr(e); } + if (g.mod == 1) for (auto& e : mod) e = bfr(e); + /* x at its pitch and two rows longer than y, rows the statistics must not read (huge + * values); in place, y is the same buffer and both views M rows. */ + void* dx = nullptr; + if (g.xf) { + std::vector h((size_t)(rows * ld), 1e30f); + for (int64_t i = 0; i < M; ++i) + for (int64_t c = 0; c < n; ++c) h[(size_t)(i * ld + c)] = x[(size_t)(i * n + c)]; + dx = up_f32(h); + } else { + dx = up_rows(x, rows, n, ld, M); + } + std::vector none; + void* dy = g.inplace ? dx : g.yf ? dalloc((size_t)(rows * ld) * 4) : up_rows(none, rows, n, ld, 0); + void* dw = g.wf ? up_f32(w) : up_bf16(w); + void* db = g.wf ? up_f32(b) : up_bf16(b); + void* dm = g.mod == 2 ? up_f32(mod) : g.mod == 1 ? up_bf16(mod) : nullptr; + void* ds = dalloc((size_t)(g.groups * (2 + 3 * 1024)) * 4); + if (!dx || !dy || !dw || !db || !ds) { ok(nm.c_str(), false, "hipMalloc failed"); continue; } + RadTensor tm = T(dm, g.mod == 2 ? RAD_F32 : RAD_BF16, { 2 * n }); + if (!g.mod) absent(tm); + const uint32_t xdt = g.xf ? RAD_F32 : RAD_BF16, ydt = g.yf ? RAD_F32 : RAD_BF16; + const std::vector ts = { + pitched(dx, xdt, g.inplace ? M : rows, n, ld), T(dw, g.wf ? RAD_F32 : RAD_BF16, { n }), + T(db, g.wf ? RAD_F32 : RAD_BF16, { n }), tm, + T(ds, RAD_F32, { g.groups * (2 + 3 * 1024) }), pitched(dy, ydt, M, n, ld) }; + const std::vector ps = { PI("M", M), PI("n", n), PI("groups", g.groups), + PF("eps", 1e-5), PS("act", g.silu ? "silu" : "none"), + PS("dtype", g.xf ? "f32" : "bf16") }; + const int rc = launch(r, ts, ps); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want, mean, rstd; + gn_ref(x, M, n, g.groups, w, b, g.mod ? &mod : nullptr, g.silu, 1e-5f, !g.yf, &want, + &mean, &rstd); + const size_t yel = (size_t)(rows * ld); + const std::vector yall = g.yf ? down_f32(dy, yel) : down_bf16(dy, yel); + std::vector got((size_t)(M * n)); + for (int64_t i = 0; i < M; ++i) + for (int64_t c = 0; c < n; ++c) got[(size_t)(i * n + c)] = yall[(size_t)(i * ld + c)]; + if (g.yf) { + double e = 0, q = 0; + for (size_t i = 0; i < want.size(); ++i) { + e += (double)(got[i] - want[i]) * (got[i] - want[i]); + q += (double)want[i] * want[i]; + } + const double rl = std::sqrt(e / q); + ok(fmt("%s numerics (rel_l2 %.3g, bound 1e-5)", nm.c_str(), rl).c_str(), rl <= 1e-5); + } else { + check(nm + " numerics", got, want, 1e-3); + } + const std::vector st = down_f32(ds, (size_t)(2 * g.groups)); + double dmean = 0, drstd = 0; + for (int64_t k = 0; k < g.groups; ++k) { + dmean = std::max(dmean, std::fabs((double)st[(size_t)(2 * k)] - mean[(size_t)k]) * + (double)rstd[(size_t)k]); + drstd = std::max(drstd, std::fabs((double)st[(size_t)(2 * k + 1)] / rstd[(size_t)k] - 1.0)); + } + ok(fmt("%s statistics (mean off by %.2g std, rstd by %.2g; bound 1e-5)", nm.c_str(), dmean, + drstd).c_str(), + dmean <= 1e-5 && drstd <= 1e-5); + if (!g.yf && !g.inplace) { + const int64_t moved = marks_moved(down_u16(dy, yel), rows, n, ld, M); + ok((nm + ": pitch columns and the buffer past y's rows untouched").c_str(), moved == 0, + fmt("%lld marker values written", (long long)moved)); + } + if (!g.inplace) { + /* A second run: the same bytes, output and statistics. */ + std::vector y1(yel * (g.yf ? 4 : 2)), y2(y1.size()); + st_memcpy(y1.data(), dy, y1.size(), hipMemcpyDeviceToHost); + const std::vector s1 = down_f32(ds, (size_t)(2 * g.groups)); + const int rc2 = launch(r, ts, ps); + st_memcpy(y2.data(), dy, y2.size(), hipMemcpyDeviceToHost); + const std::vector s2 = down_f32(ds, (size_t)(2 * g.groups)); + ok((nm + ": a second run gives the same bytes").c_str(), + rc2 == RAD_OK && y1 == y2 && differ(s1, s2) == 0); + } + } + RadTensor nomod = T(nullptr, RAD_BF16, { 1 }); + absent(nomod); + ok("group_norm refuses 12 channels a group", + launch(r, { TA(RAD_BF16, { 4, 96 }), TA(RAD_BF16, { 96 }), TA(RAD_BF16, { 96 }), nomod, + TA(RAD_F32, { 8 * 3074 }), TA(RAD_BF16, { 4, 96 }) }, + { PI("M", 4), PI("n", 96), PI("groups", 8), PF("eps", 1e-5), PS("act", "none"), + PS("dtype", "bf16") }) == RAD_E_SHAPE); +} + +/* ------------------------------------------------------------------ tconv_dw */ +void tconv_dw_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "tconv_dw_bf16"); + if (!r) { ok("tconv_dw_bf16", false, "row absent"); return; } + /* `mshort`: the M parameter this short of the volume, whose rows are written regardless. */ + struct C { const char* what; Vol v; int64_t n, xpad, ypad, mshort; }; + for (const C& c : { C{ "target", Vol{ 37, 84, 48 }, 512, 0, 0, 0 }, + C{ "source", Vol{ 37, 42, 24 }, 512, 0, 0, 0 }, + C{ "102 frames", Vol{ 102, 42, 24 }, 512, 0, 0, 0 }, + C{ "two frames, pitched", Vol{ 2, 3, 7 }, 64, 8, 16, 0 }, + C{ "one frame, M declared short", Vol{ 1, 5, 5 }, 32, 0, 8, 4 }, + C{ "six frames, M declared short", Vol{ 6, 1, 3 }, 8, 8, 0, 1 } }) { + const int64_t P = c.v.H * c.v.W, vol = c.v.T * P, M = vol, n = c.n, k = 5; + const int64_t ldx = n + c.xpad, ldy = n + c.ypad, yrows = M + 3; + const std::string nm = fmt("tconv_dw_bf16 %s: %lld frames of %lld x %lld x %lld", c.what, + (long long)c.v.T, (long long)c.v.H, (long long)c.v.W, + (long long)n); + g_seed = 0x7d0ull + (uint64_t)vol; + std::vector x = randv((size_t)(vol * n), 2.0f), w = randv((size_t)(n * k), 0.6f); + std::vector b = randv((size_t)n, 0.4f), none; + void* dx = up_rows(x, vol, n, ldx, vol); + void* dw = up_bf16(w); + void* db = up_bf16(b); + void* dy = up_rows(none, yrows, n, ldy, 0); + if (!dx || !dw || !db || !dy) { ok(nm.c_str(), false, "hipMalloc failed"); continue; } + const int rc = launch(r, { pitched(dx, RAD_BF16, vol, n, ldx), + T(dw, RAD_BF16, { n, 1, k, 1, 1 }), T(db, RAD_BF16, { n }), + TI32({ 3 }, { (int32_t)c.v.T, (int32_t)c.v.H, (int32_t)c.v.W }), + pitched(dy, RAD_BF16, yrows, n, ldy) }, + { PI("M", M - c.mshort), PI("n", n), PI("k", k), PS("dtype", "bf16") }); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + const std::vector yb = down_u16(dy, (size_t)(yrows * ldy)); + std::vector got((size_t)(M * n)), want((size_t)(M * n)); + par_for(M, [&](int64_t row) { + const int64_t t = row / P, p = row % P; + for (int64_t ch = 0; ch < n; ++ch) { + float acc = 0.0f; + for (int64_t j = 0; j < k; ++j) { + const int64_t f = t + j - k / 2; + if (f < 0 || f >= c.v.T) continue; + acc = acc + w[(size_t)(ch * k + j)] * x[(size_t)((f * P + p) * n + ch)]; + } + acc = acc + b[(size_t)ch]; + want[(size_t)(row * n + ch)] = bfr(acc); + got[(size_t)(row * n + ch)] = h_bf16(yb[(size_t)(row * ldy + ch)]); + } + }); + const int64_t bad = differ(got, want), moved = marks_moved(yb, yrows, n, ldy, M); + ok((nm + " exact, pitch columns and rows past the volume untouched").c_str(), bad == 0 && moved == 0, + fmt("%lld values differ, %lld markers written", (long long)bad, (long long)moved)); + } +} + +/* ------------------------------------------------------------------ resize_bilinear */ +/* upsample_bilinear2d's source index and lambdas at a size, align_corners=False, in f32. */ +void bil_axis_h(int64_t o, int64_t in, int64_t out, int64_t* i0, int64_t* i1, float* l0, + float* l1) { + const float s = (float)in / (float)out; + float src = s * ((float)o + 0.5f) - 0.5f; + src = src < 0.0f ? 0.0f : src; + *i0 = (int64_t)src; + *i1 = *i0 + (*i0 < in - 1 ? 1 : 0); + *l1 = src - (float)*i0; + *l0 = 1.0f - *l1; +} + +void resize_bilinear_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "resize_bilinear"); + if (!r) { ok("resize_bilinear", false, "row absent"); return; } + struct C { const char* what; int64_t T, h, w, H, W, n; bool f32; int64_t pad; }; + for (const C& c : { C{ "x2 to the target", 37, 42, 24, 84, 48, 512, false, 0 }, + C{ "x4 to the target", 37, 20, 12, 84, 48, 512, false, 0 }, + C{ "shrink", 3, 84, 48, 42, 24, 512, false, 0 }, + C{ "odd sizes, pitched", 2, 7, 5, 13, 11, 64, true, 8 }, + C{ "one voxel to 3 x 2", 2, 1, 1, 3, 2, 16, false, 8 }, + C{ "uneven, pitched", 5, 9, 4, 5, 10, 32, false, 16 } }) { + const int64_t xr = c.T * c.h * c.w, M = c.T * c.H * c.W, n = c.n, ld = n + c.pad; + const int64_t yrows = M + 2; + const std::string nm = fmt("resize_bilinear %s: %lld x %lld -> %lld x %lld, %lld frames, %s", + c.what, (long long)c.h, (long long)c.w, (long long)c.H, + (long long)c.W, (long long)c.T, c.f32 ? "f32" : "bf16"); + g_seed = 0x2e5ull + (uint64_t)(xr + M); + std::vector x = randv((size_t)(xr * n), 3.0f), none; + void* dx = nullptr; + void* dy = nullptr; + if (c.f32) { + std::vector h((size_t)(xr * ld), 0.0f); + for (int64_t i = 0; i < xr; ++i) + for (int64_t ch = 0; ch < n; ++ch) h[(size_t)(i * ld + ch)] = x[(size_t)(i * n + ch)]; + dx = up_f32(h); + dy = up_f32(std::vector((size_t)(yrows * ld), -7.0f)); + } else { + dx = up_rows(x, xr, n, ld, xr); + dy = up_rows(none, yrows, n, ld, 0); + } + if (!dx || !dy) { ok(nm.c_str(), false, "hipMalloc failed"); continue; } + const uint32_t dt = c.f32 ? RAD_F32 : RAD_BF16; + const int rc = launch(r, { pitched(dx, dt, xr, n, ld), + TI32({ 5 }, { (int32_t)c.T, (int32_t)c.h, (int32_t)c.w, + (int32_t)c.H, (int32_t)c.W }), + pitched(dy, dt, yrows, n, ld) }, + { PI("M", M), PI("n", n), PS("dtype", c.f32 ? "f32" : "bf16") }); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + const size_t yel = (size_t)(yrows * ld); + const std::vector yall = c.f32 ? down_f32(dy, yel) : down_bf16(dy, yel); + std::vector got((size_t)(M * n)), want((size_t)(M * n)); + par_for(M, [&](int64_t row) { + const int64_t t = row / (c.H * c.W), i = (row / c.W) % c.H, j = row % c.W; + int64_t i0, i1, j0, j1; + float ly0, ly1, lx0, lx1; + bil_axis_h(i, c.h, c.H, &i0, &i1, &ly0, &ly1); + bil_axis_h(j, c.w, c.W, &j0, &j1, &lx0, &lx1); + auto X = [&](int64_t a, int64_t bb, int64_t ch) { + return x[(size_t)(((t * c.h + a) * c.w + bb) * n + ch)]; + }; + for (int64_t ch = 0; ch < n; ++ch) { + const float v = ly0 * (lx0 * X(i0, j0, ch) + lx1 * X(i0, j1, ch)) + + ly1 * (lx0 * X(i1, j0, ch) + lx1 * X(i1, j1, ch)); + want[(size_t)(row * n + ch)] = c.f32 ? v : bfr(v); + got[(size_t)(row * n + ch)] = yall[(size_t)(row * ld + ch)]; + } + }); + int64_t moved = 0; + if (c.f32) { + for (int64_t row = 0; row < yrows; ++row) + for (int64_t ch = row < M ? n : 0; ch < ld; ++ch) + moved += yall[(size_t)(row * ld + ch)] != -7.0f; + } else { + moved = marks_moved(down_u16(dy, yel), yrows, n, ld, M); + } + const int64_t bad = differ(got, want); + ok((nm + " exact, pitch columns and rows past the volume untouched").c_str(), bad == 0 && moved == 0, + fmt("%lld values differ, %lld markers written", (long long)bad, (long long)moved)); + } +} + +/* ------------------------------------------------------------------ patch_fold */ +void patch_fold_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "patch_fold_f32"); + if (!r) { ok("patch_fold_f32", false, "row absent"); return; } + struct C { const char* what; int64_t F, Hp, Wp, C, pt, ph, pw; bool bf; int64_t pad; }; + for (const C& c : { C{ "the target latent, bf16", 37, 42, 24, 24, 1, 2, 2, true, 0 }, + C{ "the target latent, f32", 37, 42, 24, 24, 1, 2, 2, false, 0 }, + C{ "two frames a patch, pitched", 3, 4, 5, 24, 2, 2, 2, false, 8 }, + C{ "3 x 1 patches, bf16, pitched", 2, 3, 7, 16, 1, 3, 1, true, 8 } }) { + const int64_t K = c.C * c.pt * c.ph * c.pw, rows = c.F * c.Hp * c.Wp; + const int64_t Hv = c.Hp * c.ph, Wv = c.Wp * c.pw, vox = c.F * c.pt * Hv * Wv; + const int64_t ldx = c.C + c.pad, ldy = K + c.pad, yrows = rows + 2; + const std::string nm = fmt("patch_fold_f32 %s: %lld x %lld x %lld patches of %lld x %lld x %lld", + c.what, (long long)c.F, (long long)c.Hp, (long long)c.Wp, + (long long)c.pt, (long long)c.ph, (long long)c.pw); + g_seed = 0xf01dull + (uint64_t)vox; + std::vector x = randv((size_t)(vox * c.C), 2.0f); + std::vector mul = randv((size_t)c.C, 1.3f), add = randv((size_t)c.C, 0.7f); + const std::string smul = vid::list_of(mul), sadd = vid::list_of(add); + void* dx = nullptr; + if (c.bf) { + dx = up_rows(x, vox, c.C, ldx, vox); + } else { + std::vector h((size_t)(vox * ldx), 0.0f); + for (int64_t i = 0; i < vox; ++i) + for (int64_t ch = 0; ch < c.C; ++ch) h[(size_t)(i * ldx + ch)] = x[(size_t)(i * c.C + ch)]; + dx = up_f32(h); + } + void* dy = up_f32(std::vector((size_t)(yrows * ldy), -7.0f)); + if (!dx || !dy) { ok(nm.c_str(), false, "hipMalloc failed"); continue; } + const int rc = launch(r, { pitched(dx, c.bf ? RAD_BF16 : RAD_F32, vox, c.C, ldx), + TI32({ 3 }, { (int32_t)c.F, (int32_t)c.Hp, (int32_t)c.Wp }), + pitched(dy, RAD_F32, yrows, K, ldy) }, + { PI("M", rows), PI("C", c.C), PI("pt", c.pt), PI("ph", c.ph), + PI("pw", c.pw), PS("mul", smul.c_str()), PS("add", sadd.c_str()), + PS("dtype", c.bf ? "bf16" : "f32") }); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + const std::vector yall = down_f32(dy, (size_t)(yrows * ldy)); + std::vector got((size_t)(rows * K)), want((size_t)(rows * K)); + int64_t moved = 0; + for (int64_t pr = 0; pr < yrows; ++pr) + for (int64_t col = 0; col < ldy; ++col) { + const float g = yall[(size_t)(pr * ldy + col)]; + if (pr >= rows || col >= K) { moved += g != -7.0f; continue; } + const int64_t f = pr / (c.Hp * c.Wp), i = (pr / c.Wp) % c.Hp, j = pr % c.Wp; + const int64_t ch = col / (c.pt * c.ph * c.pw), sub = col % (c.pt * c.ph * c.pw); + const int64_t a = sub / (c.ph * c.pw), bb = (sub / c.pw) % c.ph, d = sub % c.pw; + const int64_t v = ((f * c.pt + a) * Hv + i * c.ph + bb) * Wv + j * c.pw + d; + const float p = x[(size_t)(v * c.C + ch)] * mul[(size_t)ch]; + want[(size_t)(pr * K + col)] = p + add[(size_t)ch]; + got[(size_t)(pr * K + col)] = g; + } + const int64_t bad = differ(got, want); + ok((nm + " exact, pitch columns and rows past the patches untouched").c_str(), bad == 0 && moved == 0, + fmt("%lld values differ, %lld markers written", (long long)bad, (long long)moved)); + } + /* The round trip: patch rows unfolded to voxels and folded back, both lists the identity. */ + const RadKernelInfo* ru = find(pl, "patch_unfold_f32"); + if (!ru) { ok("patch_fold_f32 round trip", false, "patch_unfold_f32 absent"); return; } + for (const int64_t pt : { (int64_t)1, (int64_t)2 }) { + const int64_t C = 24, F = 3, Hp = 4, Wp = 5, ph = 2, pw = 2, K = C * pt * ph * pw; + const int64_t rows = F * Hp * Wp, vox = rows * pt * ph * pw; + std::vector p = randv((size_t)(rows * K), 2.0f); + const std::vector ones((size_t)C, 1.0f), zeros((size_t)C, 0.0f); + const std::string s1 = vid::list_of(ones), s0 = vid::list_of(zeros); + void* dp = up_f32(p); + void* dv = dalloc((size_t)(vox * C) * 4); + void* dq = dalloc((size_t)(rows * K) * 4); + std::vector ps = { PI("M", vox), PI("C", C), PI("pt", pt), PI("ph", ph), + PI("pw", pw), PS("mul", s1.c_str()), PS("add", s0.c_str()), + PS("dtype", "f32") }; + const RadTensor geom = TI32({ 3 }, { (int32_t)F, (int32_t)Hp, (int32_t)Wp }); + const int rc1 = launch(ru, { T(dp, RAD_F32, { rows, K }), geom, T(dv, RAD_F32, { vox, C }) }, ps); + ps[0] = PI("M", rows); + const int rc2 = launch(r, { T(dv, RAD_F32, { vox, C }), geom, T(dq, RAD_F32, { rows, K }) }, ps); + const int64_t bad = rc1 == RAD_OK && rc2 == RAD_OK ? differ(down_f32(dq, p.size()), p) : -1; + ok(fmt("patch_fold_f32 undoes patch_unfold_f32 at pt %lld", (long long)pt).c_str(), bad == 0, + fmt("rc %d / %d, %lld values differ", rc1, rc2, (long long)bad)); + } +} + +/* ------------------------------------------------------------------ flow_renoise */ +void flow_renoise_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "flow_renoise_f32"); + if (!r) { ok("flow_renoise_f32", false, "row absent"); return; } + struct C { const char* what; int64_t M, n, ld, extra; float sigma; uint64_t seed; }; + for (const C& c : { C{ "the video's patch rows", 37 * 42 * 24, 96, 96, 0, 0.37f, 0x123456789abcdefull }, + C{ "the soundtrack's rows, pitched", 1152, 32, 40, 3, 0.8f, 42ull } }) { + const std::string nm = fmt("flow_renoise_f32 %s: %lld x %lld, sigma %.2f", c.what, + (long long)c.M, (long long)c.n, (double)c.sigma); + const int64_t rows = c.M + c.extra; + g_seed = 0x5eedull + (uint64_t)c.M; + const std::vector x = randv((size_t)(rows * c.ld), 1.5f); + void* dx = up_f32(x); + void* ds = up_f32(std::vector{ c.sigma }); + void* dk = dalloc(8); + const uint32_t words[2] = { (uint32_t)c.seed, (uint32_t)(c.seed >> 32) }; + if (!dx || !ds || !dk) { ok(nm.c_str(), false, "hipMalloc failed"); continue; } + st_memcpy(dk, words, 8, hipMemcpyHostToDevice); + /* x is a view of the buffer's first M rows; the rows after it are not x's. */ + const int rc = launch(r, { T(ds, RAD_F32, { 1 }), T(dk, RAD_U32, { 2 }), + pitched(dx, RAD_F32, c.M, c.n, c.ld) }, + { PI("M", c.M), PI("n", c.n), PI("stream", 1), PS("dtype", "f32") }); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + const std::vector got = down_f32(dx, x.size()); + double e = 0, q = 0, worst = 0; + int64_t moved = 0; + for (int64_t k = 0; k < rows; ++k) + for (int64_t ch = 0; ch < c.ld; ++ch) { + const size_t i = (size_t)(k * c.ld + ch); + if (k >= c.M || ch >= c.n) { moved += got[i] != x[i]; continue; } + const float z = rad_philox_normal_s(c.seed, 1, (uint64_t)(k * c.n + ch)); + const float a = (1.0f - c.sigma) * x[i]; + const float bz = c.sigma * z; + const float want = a + bz; + e += (double)(got[i] - want) * (got[i] - want); + q += (double)want * want; + worst = std::max(worst, (double)std::fabs(got[i] - want)); + } + const double rl = std::sqrt(e / q); + ok(fmt("%s (rel_l2 %.3g, worst %.3g; bounds 1e-6, 1e-5), the rest untouched", nm.c_str(), + rl, worst).c_str(), + rl <= 1e-6 && worst <= 1e-5 && moved == 0, + fmt("%lld values outside written", (long long)moved)); + } +} + +} /* namespace ups */ + /* ---- a video generator's f32 forms, its biased GEMMs and its rotary, against libref's arithmetic * * A diffusion transformer's patch projections and heads, its timestep MLP and a video decoder's @@ -11040,6 +11677,133 @@ static void video_perf(const Plugin& pl, int iters, const char* only) { } } + if (want("upscaler")) { + std::printf("\nconv3d_ndhwc (conv3d_ndhwc_bf16) beside gemm_nt_bias at bf16 " + "(gemm_bf16_nt_bias_tiled) at the same M, N and K = 27 cin: a video latent " + "upscaler's 3 x 3 x 3 convolutions, %d launches each\n", iters); + const RadKernelInfo* cv = find(pl, "conv3d_ndhwc_bf16"); + const RadKernelInfo* gb = find(pl, "gemm_bf16_nt_bias_tiled"); + struct V { const char* what; int64_t T, H, W, cin, cout; bool gemm; }; + for (const V& v : { V{ "target block", 37, 84, 48, 512, 512, true }, + V{ "source block", 37, 42, 24, 512, 512, true }, + V{ "conv_in", 37, 42, 24, 24, 512, false }, + V{ "conv_out", 37, 84, 48, 512, 24, false }, + V{ "target block, 102 frames", 102, 84, 48, 512, 512, false } }) { + const int64_t M = v.T * v.H * v.W, K = 27 * v.cin, N = v.cout; + const double flop = 2.0 * (double)M * N * K; + if (v.gemm && gb) { + void* da = dalloc((size_t)(M * K) * 2); + void* dw = dalloc((size_t)(N * K) * 2); + void* db = dalloc((size_t)N * 4); + void* dy = dalloc((size_t)(M * N) * 2); + if (!da || !dw || !db || !dy) { std::printf(" %s: hipMalloc failed\n", v.what); dfree_all(); continue; } + rand_fill(da, (size_t)(M * K) * 2); + rand_fill(dw, (size_t)(N * K) * 2); + RadTensor tr = T(nullptr, RAD_BF16, { 1 }); + absent(tr); + const double us = time_row(gb, { T(da, RAD_BF16, { M, K }), T(dw, RAD_BF16, { N, K }), + T(db, RAD_F32, { N }), tr, T(dy, RAD_BF16, { M, N }) }, + { PI("M", M), PI("N", N), PI("K", K), PS("dtype", "bf16") }, + iters); + if (us < 0) std::printf(" %-26s gemm_nt_bias rc %d\n", v.what, (int)us); + else std::printf(" %-26s gemm_nt_bias M %6lld N %4lld K %5lld %9.1f us %6.1f TFLOP/s\n", + v.what, (long long)M, (long long)N, (long long)K, us, flop / (us * 1e6)); + dfree_all(); + } + if (!cv) { std::printf(" conv3d_ndhwc_bf16 absent\n"); break; } + void* dx = dalloc((size_t)(M * v.cin) * 2); + void* dw = dalloc((size_t)(N * K) * 2); + void* db = dalloc((size_t)N * 2); + void* dy = dalloc((size_t)(M * N) * 2); + if (!dx || !dw || !db || !dy) { std::printf(" %s: hipMalloc failed\n", v.what); dfree_all(); continue; } + rand_fill(dx, (size_t)(M * v.cin) * 2); + rand_fill(dw, (size_t)(N * K) * 2); + RadTensor tr = T(nullptr, RAD_BF16, { 1 }); + absent(tr); + const double us = time_row(cv, { T(dx, RAD_BF16, { M, v.cin }), T(dw, RAD_BF16, { N, K }), + T(db, RAD_BF16, { N }), + TI32({ 3 }, { (int32_t)v.T, (int32_t)v.H, (int32_t)v.W }), tr, + T(dy, RAD_BF16, { M, N }) }, + { PI("M", M), PI("cin", v.cin), PI("cout", N), PI("k", 3), + PI("kt", 3), PS("dtype", "bf16") }, + iters); + if (us < 0) std::printf(" %-26s conv3d rc %d\n", v.what, (int)us); + else std::printf(" %-26s conv3d M %6lld N %4lld K %5lld %9.1f us %6.1f TFLOP/s\n", + v.what, (long long)M, (long long)N, (long long)K, us, flop / (us * 1e6)); + dfree_all(); + } + + /* The rest of a block at the target size, 512 channels: what each moves through memory. */ + [&] { + std::printf(" the norm and elementwise ops at 84 x 48 x 37 x 512, %d launches each\n", iters); + const int64_t T_ = 37, H = 84, W = 48, n = 512, M = T_ * H * W, Ms = T_ * 42 * 24; + void* dx = dalloc((size_t)(M * n) * 2); + void* dy = dalloc((size_t)(M * n) * 2); + void* dw = dalloc((size_t)n * 5 * 2); + void* db = dalloc((size_t)n * 2); + void* dm = dalloc((size_t)(2 * n) * 2); + void* ds = dalloc((size_t)(32 * (2 + 3 * 1024)) * 4); + void* dp = dalloc((size_t)(Ms * 96) * 4); + void* dsig = dalloc(4); + void* dseed = dalloc(8); + if (!dx || !dy || !dw || !db || !dm || !ds || !dp || !dsig || !dseed) { + std::printf(" hipMalloc failed\n"); + dfree_all(); + return; + } + rand_fill(dx, (size_t)(M * n) * 2); + rand_fill(dw, (size_t)n * 5 * 2); + rand_fill(db, (size_t)n * 2); + rand_fill(dm, (size_t)(2 * n) * 2); + { + const float sg = 0.4f; + st_memcpy(dsig, &sg, 4, hipMemcpyHostToDevice); + } + const std::string ones = [&] { + std::string s; + for (int i = 0; i < 24; ++i) s += i ? " 1" : "1"; + return s; + }(); + const RadTensor geom = TI32({ 3 }, { (int32_t)T_, (int32_t)H, (int32_t)W }); + struct E { const char* what; const char* row; std::vector ts; + std::vector ps; double bytes; }; + for (const E& e : { + E{ "group_norm, modulated, SiLU (x read twice)", "group_norm", + { T(dx, RAD_BF16, { M, n }), T(db, RAD_BF16, { n }), T(db, RAD_BF16, { n }), + T(dm, RAD_BF16, { 2 * n }), T(ds, RAD_F32, { 32 * (2 + 3 * 1024) }), + T(dy, RAD_BF16, { M, n }) }, + { PI("M", M), PI("n", n), PI("groups", 32), PF("eps", 1e-5), PS("act", "silu"), + PS("dtype", "bf16") }, + (double)M * n * 6 }, + E{ "tconv_dw, 5 frames", "tconv_dw_bf16", + { T(dx, RAD_BF16, { M, n }), T(dw, RAD_BF16, { n, 1, 5, 1, 1 }), T(db, RAD_BF16, { n }), + geom, T(dy, RAD_BF16, { M, n }) }, + { PI("M", M), PI("n", n), PI("k", 5), PS("dtype", "bf16") }, (double)M * n * 4 }, + E{ "resize_bilinear, 42 x 24 -> 84 x 48", "resize_bilinear", + { T(dx, RAD_BF16, { Ms, n }), + TI32({ 5 }, { (int32_t)T_, 42, 24, (int32_t)H, (int32_t)W }), + T(dy, RAD_BF16, { M, n }) }, + { PI("M", M), PI("n", n), PS("dtype", "bf16") }, (double)(M + Ms) * n * 2 }, + E{ "patch_fold, 24 channels to 96-wide f32", "patch_fold_f32", + { T(dx, RAD_BF16, { M, 24 }), TI32({ 3 }, { (int32_t)T_, 42, 24 }), + T(dp, RAD_F32, { Ms, 96 }) }, + { PI("M", Ms), PI("C", 24), PI("pt", 1), PI("ph", 2), PI("pw", 2), + PS("mul", ones.c_str()), PS("add", ones.c_str()), PS("dtype", "bf16") }, + (double)M * 24 * 2 + (double)Ms * 96 * 4 }, + E{ "flow_renoise, 96-wide f32 rows", "flow_renoise_f32", + { T(dsig, RAD_F32, { 1 }), T(dseed, RAD_U32, { 2 }), T(dp, RAD_F32, { Ms, 96 }) }, + { PI("M", Ms), PI("n", 96), PI("stream", 1), PS("dtype", "f32") }, + (double)Ms * 96 * 8 } }) { + const RadKernelInfo* r = find(pl, e.row); + if (!r) { std::printf(" %s: row absent\n", e.row); continue; } + const double us = time_row(r, e.ts, e.ps, iters); + if (us < 0) std::printf(" %-44s rc %d\n", e.what, (int)us); + else std::printf(" %-44s %9.1f us %6.1f GB/s\n", e.what, us, e.bytes / (us * 1e3)); + } + dfree_all(); + }(); + } + if (want("mod")) { std::printf("\ngemm_nt_q_bias at fp8a8 (gemm_fp8a8_bias_nt_m16): a modulation projection, its " "50 timesteps into a column block of the table\n"); @@ -18503,6 +19267,13 @@ static void device_phase(const Plugin& pl) { if (sel("flow_x0_step_f32")) vid::flow_x0_cases(pl); if (sel("grid_pos3")) vid::grid_pos3_cases(pl); if (sel("snake_aa_f32")) vid::snake_aa_cases(pl); + /* A video latent upscaler's ops, at its source and target sizes. */ + if (sel("conv3d_ndhwc_bf16")) ups::conv3d_cases(pl); + if (sel("group_norm")) ups::group_norm_cases(pl); + if (sel("tconv_dw_bf16")) ups::tconv_dw_cases(pl); + if (sel("resize_bilinear")) ups::resize_bilinear_cases(pl); + if (sel("patch_fold_f32")) ups::patch_fold_cases(pl); + if (sel("flow_renoise_f32")) ups::flow_renoise_cases(pl); if (sel("vsa_select_h128_bf16")) vsa::select_cases(pl); if (sel("attn_vsa_h128_bf16")) vsa::attn_cases(pl); if (sel("quant_cols_fp8_bf16")) vsa::quant_cols_cases(pl); @@ -19052,7 +19823,9 @@ static void usage(void) { " (the video decoder's bf16 linears), f32 (the f32 GEMMs), conv (the\n" " audio decoder's convolutions), mod (the fp8 modulation projection),\n" " attn and attn64 (dense attention at 3K to 106K rows, and over the\n" - " decoder's tiles); every section without one.\n" + " decoder's tiles), upscaler (a latent upscaler's 3D convolutions\n" + " beside the bf16 GEMM at the same M, N and K, then its norm and\n" + " elementwise ops); every section without one.\n" " --perfvsa [iters] [local]: vsa_select and attn_vsa at 1344 x 768 (38010\n" " rows, 28 heads), sparsity 0.8 and 0, beside attn_dense over the same\n" " rows. `local` gives q and k features of the row's grid position, so a\n" diff --git a/libr4d/r4d_upscaler.hip b/libr4d/r4d_upscaler.hip new file mode 100644 index 00000000..361dc46e --- /dev/null +++ b/libr4d/r4d_upscaler.hip @@ -0,0 +1,942 @@ +// R4D -- a video latent upscaler's ops (docs/OPS.md, "The latent upscaler"): MiniMax-H3's 3D-conv +// latent resizer, a stack of 3x3x3 convolutions over 512-channel voxel rows with group norms, +// depthwise temporal convolutions and one spatial resize between two resolutions, plus the patch +// fold back to the latent's own rows and the re-noising of a clean latent. +// +// Activations are voxel rows: row (t, y, x) row-major over (frames, rows, columns), channels +// innermost. A request's volume is a device operand (`geom`, i32), never a parameter, so every +// kernel reads it on the device; one the operands cannot hold writes nothing, and rows past what +// the volume and the output hold are left alone. +// +// Each kernel rounds where its libref function does (libref/ref_video.cpp), under the library's +// -ffp-contract=off: the convolutions accumulate in f32 in their own order and round once (twice +// with the residual), the group norm's statistics are f32 merges in a fixed order, and the resize, +// the fold and the re-noise are the reference's arithmetic in its order (the noise through the +// device's log, sin and cos). +#include "r4d.h" +#include "r4d_args.h" +#include "r4d_emit.h" +#include "r4d_common.h" +#include "r4d_gdn_wmma.h" +#include "rad_philox.h" + +#include +#include +#include +#include + +namespace { + +constexpr int kT = 256; + +// Eight consecutive values of a bf16 or f32 row as floats, and a store rounded to its dtype. +__device__ __forceinline__ void ld8(const uint16_t* p, float* f) { + const uint4 u = *(const uint4*)p; + f[0] = bf16w_lo(u.x); f[1] = bf16w_hi(u.x); f[2] = bf16w_lo(u.y); f[3] = bf16w_hi(u.y); + f[4] = bf16w_lo(u.z); f[5] = bf16w_hi(u.z); f[6] = bf16w_lo(u.w); f[7] = bf16w_hi(u.w); +} +__device__ __forceinline__ void ld8(const float* p, float* f) { + const float4 a = *(const float4*)p, b = *(const float4*)(p + 4); + f[0] = a.x; f[1] = a.y; f[2] = a.z; f[3] = a.w; f[4] = b.x; f[5] = b.y; f[6] = b.z; f[7] = b.w; +} +__device__ __forceinline__ void st8(uint16_t* p, const float* f) { + uint4 u; + u.x = bf16x2_rne(f[0], f[1]); + u.y = bf16x2_rne(f[2], f[3]); + u.z = bf16x2_rne(f[4], f[5]); + u.w = bf16x2_rne(f[6], f[7]); + *(uint4*)p = u; +} +__device__ __forceinline__ void st8(float* p, const float* f) { + *(float4*)p = make_float4(f[0], f[1], f[2], f[3]); + *(float4*)(p + 4) = make_float4(f[4], f[5], f[6], f[7]); +} +// Eight per-channel values of an f32 or bf16 vector, its dtype known only at run time. +__device__ __forceinline__ void ld8w(const void* p, bool f32, int c, float* f) { + if (f32) ld8((const float*)p + c, f); + else ld8((const uint16_t*)p + c, f); +} + +// The volume a request runs at: (T, H, W) and its row count, or false for a geometry the operands +// cannot hold (`rows` rows of the input). +__device__ __forceinline__ bool volume_of(const int* geom, long long rows, int* T, int* H, int* W, + long long* vol) { + *T = geom[0]; + *H = geom[1]; + *W = geom[2]; + if (*T <= 0 || *H <= 0 || *W <= 0) return false; + *vol = (long long)*T * *H * *W; + return *vol <= rows; +} + +// ---------------------------------------------------------------------------- conv3d_ndhwc +// An implicit GEMM over voxel rows: y[voxel][cout] = sum over (tap, cin) of x[voxel's tap +// neighbour][cin] * w[cout][tap][cin], the weight stored tap-major (r4d_layout.cpp relayouts +// PyTorch's [cout][cin][3][3][3] at load), so K = 27 cin runs over taps then channels and a 64-wide +// K tile of a voxel is eight 16-byte reads of one neighbour row. No im2col buffer. +// +// The block is gemm_nt_bias's large-grid tile (vit_gemm_wa_kernel, r4d_vit_bf16.hip): 128 output +// channels x 128 voxels, eight waves as 4 (weight) x 2 (voxels), a wave 2 x 4 WMMA tiles. The +// weight is the WMMA's A operand, read from global straight into registers; the voxels are its B +// operand, staged through LDS (double-buffered, one barrier a tile) and read by the four waves that +// share their rows. Staging both operands through LDS would take all of gfx1201's LDS bandwidth +// (64 bytes a clock per CU) at one WMMA every 16 clocks per SIMD; this costs 256 bytes of fragment +// reads and 64 of stores per WMMA, the weight's bytes coming through the vector cache. A lane's +// accumulator is eight consecutive output channels of one voxel, so the bias, the residual and the +// store are 16-byte accesses. +// +// K is relabelled inside a staged tile as gemm_nt_bias does (lane half h, k step s and element e +// hold k = 32h + 8s + e of the tile, in both operands), so a lane's weight fragments for a tile are +// one 64-byte run of its row and its voxel fragment one 16-byte LDS read; the summation order is +// that permutation's. +// +// The gather reads x as a raw buffer, whose reads at or past its size return zeros, so a neighbour +// outside the volume is the offset kOob and is staged with no select. A thread stages one 16-byte +// chunk column of four voxel rows, so it decomposes its four voxels into (t, y, x) once. With cin a +// multiple of 64 (C64) a K tile lies inside one tap: the four neighbours' byte offsets are +// recomputed only when the tap changes, every cin / 64 tiles, from a block-uniform (dt, dy, dx), +// and the tile's channel offset rides in the load's scalar offset. Otherwise (the 24-channel input) +// each chunk's tap follows its own K, every tile. The weight is a raw buffer too, the tile's K in +// the load's scalar offset and a chunk's in its immediate (the 24-channel input reads it through a +// guarded load instead, its last tile running past K), so neither operand's addresses cost vector +// arithmetic per tile. +// +// Measured on the R9700 at 300 W, warm, against gemm_nt_bias at bf16 at the same M, N and K = 27 +// cin: 512 -> 512 at 84 x 48 x 37 148 TFLOP/s (the GEMM 146), at 42 x 24 x 37 149 (145). The +// select-and-pointer form of the gather this replaces ran 136 and 134: its loop issued twice the +// GEMM's vector instructions. The weight through global loads at a uniform base is 0.2-1% slower; +// raster groups of 4 or 16 bands are within noise of 8. 512 -> 24 (the output convolution) runs at +// 30 with 13/16 of its 128-wide channel tile idle, a few milliseconds of a whole upscale. +constexpr uint32_t kCTW = 2, kCTA = 4, kCWW = 4, kCWA = 2; +constexpr uint32_t kCBN = kCWW * kCTW * 16, kCBM = kCWA * kCTA * 16; // channels x voxels +constexpr uint32_t kCThreads = kCWW * kCWA * 32; +constexpr uint32_t kCFK = 64; // K a staged tile +constexpr uint32_t kCPB = kCFK * 2 + 16; // LDS row pitch, bytes +constexpr uint32_t kCCPR = kCFK * 2 / 16; // 16-byte chunks a row +constexpr uint32_t kCRS = kCThreads / kCCPR; // rows one staging pass +constexpr uint32_t kCSPT = kCBM / kCRS; // rows a thread stages +constexpr uint32_t kCWC = kCFK / 16; // a lane's weight chunks +constexpr uint32_t kCGroup = 8; // voxel bands a raster group +constexpr int kTaps = 27; +static_assert(kCBM % kCRS == 0, "whole rows a thread"); +constexpr uint32_t kOob = 0xFFFF0000u; // past every x the shim accepts, after any added offset +// gfx12's raw-buffer descriptor word 3 (composable_kernel's for gfx11 and gfx12): offsets checked +// against the size, reads out of range returning zero. +constexpr int kBufWord3 = 0x31004000; + +template +__device__ __forceinline__ unsigned short conv_finish(float acc, float bv, unsigned short r) { + unsigned short t = f32_to_bf16(acc + bv); + if constexpr (RES) t = f32_to_bf16(bf2f(r) + bf2f(t)); + return t; +} + +/* `vec` (host-checked): y, res and the bias take 16-byte accesses at every eight-column boundary. + * `xrows` bounds the volume the device geometry may name, `xbytes` is x's extent (at most kOob) + * and `Mcap` bounds the rows written. */ +template +__global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel( + const unsigned short* __restrict__ X, const unsigned short* __restrict__ Wt, + const void* __restrict__ bias, const unsigned short* R, unsigned short* C, + const int* __restrict__ geom, unsigned ldx, unsigned ldr, unsigned ldc, int Mcap, int xrows, + unsigned xbytes, int cin, int N, unsigned vec) { + typedef r4d_u32x4 U4; + __shared__ __attribute__((aligned(16))) unsigned char s_a[2][kCBM * kCPB]; + + int gT, gH, gW; + long long vol; + if (!volume_of(geom, xrows, &gT, &gH, &gW, &vol)) return; + const int HW = gH * gW; + const int Mv = vol < (long long)Mcap ? (int)vol : Mcap; + + const uint32_t tid = threadIdx.x, lane = tid & 31u; + const uint32_t wave = __builtin_amdgcn_readfirstlane(tid >> 5); + const uint32_t ww = wave % kCWW, wa = wave / kCWW; + + // Grouped raster, as gemm_nt_bias's: kCGroup voxel bands sweep the channels together, so the + // bands' shared halo rows and a channel slice's weight stay in L2 between them. + uint32_t bm = blockIdx.x, bn = blockIdx.y; + if (gridDim.x > kCGroup) { + const uint32_t per = kCGroup * gridDim.y; + const uint32_t lin = blockIdx.y * gridDim.x + blockIdx.x; + const uint32_t first = (lin / per) * kCGroup, r = lin % per; + const uint32_t gm = min(gridDim.x - first, kCGroup); + bm = first + r % gm; + bn = r / gm; + } + const uint32_t m0 = bm * kCBM, n0 = bn * kCBN; + if (m0 >= (uint32_t)Mv) return; + + // This thread's staged rows and their voxels; a row past the volume sits outside every frame. + const uint32_t ch = tid % kCCPR; + int vm[kCSPT], vt[kCSPT], vy[kCSPT], vx[kCSPT]; + uint32_t adst[kCSPT]; +#pragma unroll + for (uint32_t i = 0; i < kCSPT; ++i) { + const uint32_t r = tid / kCCPR + kCRS * i; + const int m = (int)(m0 + r); + adst[i] = r * kCPB + ch * 16u; + vm[i] = m; + vt[i] = -4; + vy[i] = 0; + vx[i] = 0; + if (m < Mv) { + vt[i] = m / HW; + const int rem = m - vt[i] * HW; + vy[i] = rem / gW; + vx[i] = rem - vy[i] * gW; + } + } + // The four neighbours' byte offsets at a tap, kOob outside the volume; with C64 they include + // the thread's chunk column. + const __amdgpu_buffer_rsrc_t xr = + __builtin_amdgcn_make_buffer_rsrc(const_cast(X), 0, (int)xbytes, kBufWord3); + uint32_t off[kCSPT]; + auto at_tap = [&](int tap) { + const int dt = tap / 9 - 1, dy = (tap / 3) % 3 - 1, dx = tap % 3 - 1; + const int delta = dt * HW + dy * gW + dx; +#pragma unroll + for (uint32_t i = 0; i < kCSPT; ++i) { + const bool ok = tap < kTaps && (unsigned)(vt[i] + dt) < (unsigned)gT && + (unsigned)(vy[i] + dy) < (unsigned)gH && + (unsigned)(vx[i] + dx) < (unsigned)gW; + off[i] = ok ? (uint32_t)(vm[i] + delta) * ldx * 2u + (C64 ? ch * 16u : 0u) : kOob; + } + }; + + // Weight: lane row (l & 15) of each tile, elements [32h, 32h + 32) of the staged tile, as byte + // offsets to which a tile adds its K. Rows past N re-read row N-1; nothing past N is stored. + const uint32_t K = (uint32_t)kTaps * (uint32_t)cin; + const __amdgpu_buffer_rsrc_t wr = __builtin_amdgcn_make_buffer_rsrc( + const_cast(Wt), 0, (int)((uint32_t)N * K * 2u), kBufWord3); + uint32_t woff[kCTW]; +#pragma unroll + for (uint32_t i = 0; i < kCTW; ++i) + woff[i] = min(n0 + (ww * kCTW + i) * 16u + (lane & 15u), (uint32_t)N - 1u) * K * 2u + + (lane >> 4) * kCFK; + const uint32_t frow = (wa * kCTA * 16u + (lane & 15u)) * kCPB + (lane >> 4) * kCFK; + + v8f acc[kCTW][kCTA]; +#pragma unroll + for (uint32_t i = 0; i < kCTW; ++i) +#pragma unroll + for (uint32_t j = 0; j < kCTA; ++j) acc[i][j] = (v8f)(0.f); + + auto mma_tile = [&](const unsigned char* sa, const U4 (&cur)[kCTW][kCWC]) { +#pragma unroll + for (uint32_t s = 0; s < kCWC; ++s) { + v8bf bfr_[kCTA]; +#pragma unroll + for (uint32_t j = 0; j < kCTA; ++j) + bfr_[j] = __builtin_bit_cast(v8bf, *(const U4*)(sa + frow + j * 16u * kCPB + s * 16u)); +#pragma unroll + for (uint32_t i = 0; i < kCTW; ++i) { + const v8bf af = __builtin_bit_cast(v8bf, cur[i][s]); +#pragma unroll + for (uint32_t j = 0; j < kCTA; ++j) acc[i][j] = mma(af, bfr_[j], acc[i][j]); + } + } + }; + + // The K walk: C64 counts a tap's channel tiles (uniform); otherwise each thread follows its + // chunk's (tap, channel) and the last tile may run past K, its weight chunks zeroed there. + const uint32_t nk = (K + kCFK - 1u) / kCFK; + const uint32_t ctiles = (uint32_t)cin / kCFK; + int tap = 0; + uint32_t cc = 0, ci = 0; + if constexpr (C64) { + at_tap(0); + } else { + tap = (int)(ch * 8u / (uint32_t)cin); + ci = ch * 8u - (uint32_t)tap * (uint32_t)cin; + at_tap(tap); + } + auto advance = [&]() { + if constexpr (C64) { + if (++cc == ctiles) { + cc = 0; + at_tap(++tap); + } + } else { + ci += kCFK; + while (ci >= (uint32_t)cin) { ci -= (uint32_t)cin; ++tap; } + at_tap(tap); + } + }; + + U4 pa[kCSPT], w0[kCTW][kCWC], w1[kCTW][kCWC]; + const U4 zero = (U4)(0u); + /* Every load is issued unconditionally (the last tile's prefetch re-reads the last tile), so + * the loop's waits count exactly. */ + auto load = [&](uint32_t k0, U4 (&w)[kCTW][kCWC]) { +#pragma unroll + for (uint32_t i = 0; i < kCSPT; ++i) { + if constexpr (C64) + pa[i] = __builtin_amdgcn_raw_buffer_load_b128(xr, (int)off[i], (int)(cc * kCFK * 2u), 0); + else + pa[i] = __builtin_amdgcn_raw_buffer_load_b128(xr, (int)(off[i] + ci * 2u), 0, 0); + } + const unsigned char* const wb = (const unsigned char*)Wt + (size_t)k0 * 2u; +#pragma unroll + for (uint32_t i = 0; i < kCTW; ++i) +#pragma unroll + for (uint32_t c = 0; c < kCWC; ++c) { + if constexpr (C64) { + w[i][c] = __builtin_amdgcn_raw_buffer_load_b128(wr, (int)(woff[i] + c * 16u), + (int)(k0 * 2u), 0); + } else { + const bool in = k0 + (lane >> 4) * (kCFK / 2u) + c * 8u < K; + w[i][c] = in ? *(const U4*)(wb + (in ? woff[i] + c * 16u : 0u)) : zero; + } + } + }; + auto stage = [&](uint32_t buf) { + unsigned char* const sa = s_a[buf]; +#pragma unroll + for (uint32_t i = 0; i < kCSPT; ++i) *(U4*)(sa + adst[i]) = pa[i]; + }; + auto tile = [&](uint32_t t, uint32_t buf, U4 (&cur)[kCTW][kCWC], U4 (&nxt)[kCTW][kCWC]) { + stage(buf); + lds_barrier(); + if (t + 1u < nk) advance(); + load(min(t + 1u, nk - 1u) * kCFK, nxt); + mma_tile(s_a[buf], cur); + }; + load(0, w0); + uint32_t t = 0; + for (; t + 1u < nk; t += 2u) { + tile(t, 0, w0, w1); + tile(t + 1u, 1, w1, w0); + } + if (t < nk) tile(t, 0, w0, w1); + + // D is [channel][voxel]: eight consecutive channels of one output row a lane a tile. The + // residual is read by the thread that stores the same element, so it may alias y. +#pragma unroll + for (uint32_t i = 0; i < kCTW; ++i) +#pragma unroll + for (uint32_t j = 0; j < kCTA; ++j) { + const uint32_t m = m0 + (wa * kCTA + j) * 16u + (lane & 15u); + const uint32_t n = n0 + (ww * kCTW + i) * 16u + (lane >> 4) * 8u; + if (m >= (uint32_t)Mv) continue; + const v8f v = acc[i][j]; + if (vec && n + 8u <= (uint32_t)N) { + float bv[8]; + if constexpr (BF32) { + const float4 b0 = *(const float4*)((const float*)bias + n); + const float4 b1 = *(const float4*)((const float*)bias + n + 4); + bv[0] = b0.x; bv[1] = b0.y; bv[2] = b0.z; bv[3] = b0.w; + bv[4] = b1.x; bv[5] = b1.y; bv[6] = b1.z; bv[7] = b1.w; + } else { + const uint4 b = *(const uint4*)((const unsigned short*)bias + n); + const uint32_t d[4] = { b.x, b.y, b.z, b.w }; +#pragma unroll + for (uint32_t e = 0; e < 8; ++e) bv[e] = bf2f((unsigned short)(d[e / 2] >> (16 * (e % 2)))); + } + uint32_t rr[4] = { 0u, 0u, 0u, 0u }; + if constexpr (RES) { + const uint4 r4 = *(const uint4*)(R + (size_t)m * ldr + n); + rr[0] = r4.x; rr[1] = r4.y; rr[2] = r4.z; rr[3] = r4.w; + } + uint32_t o[4]; +#pragma unroll + for (uint32_t e = 0; e < 8; e += 2) + o[e / 2] = (uint32_t)conv_finish(v[e], bv[e], (unsigned short)rr[e / 2]) | + ((uint32_t)conv_finish(v[e + 1], bv[e + 1], + (unsigned short)(rr[e / 2] >> 16)) << 16); + *(uint4*)(C + (size_t)m * ldc + n) = make_uint4(o[0], o[1], o[2], o[3]); + } else { +#pragma unroll + for (uint32_t e = 0; e < 8; ++e) { + if (n + e >= (uint32_t)N) continue; + const float bv = BF32 ? ((const float*)bias)[n + e] + : bf2f(((const unsigned short*)bias)[n + e]); + const unsigned short r = RES ? R[(size_t)m * ldr + n + e] : (unsigned short)0; + C[(size_t)m * ldc + n + e] = conv_finish(v[e], bv, r); + } + } + } +} + +// ---------------------------------------------------------------------------- group_norm +// nn.GroupNorm over all of y's rows in three launches, every reduction in a fixed order so two runs +// give the same bytes: +// +// 1. parts: block p takes rows [p rpp, (p + 1) rpp) and writes each group's (count, mean, M2) +// of them to the scratch. A thread keeps one 8-channel chunk of one group over every +// `slots`-th row, summing deviations from its first value (the shift keeps the f32 sums of +// squares from cancelling against a large mean); the block merges its threads' triples per +// group in thread order (Chan's parallel update). +// 2. final: block g merges group g's parts, 256 strided runs then a fixed tree, and writes +// stats[2g] = mean and stats[2g + 1] = rstd = 1 / sqrt(M2 / count + eps). +// 3. apply: a thread an 8-channel chunk, v = (x - mean) rstd w + b, the modulation and SiLU in +// f32, one rounding. +// +// The scratch beyond the 2 groups leading values holds part p of group g at 3 (g kGnParts + p). +constexpr int kGnParts = 1024; + +__device__ __forceinline__ void chan_merge(float& n, float& mean, float& m2, float nb, float mb, + float m2b) { + if (nb == 0.0f) return; + if (n == 0.0f) { n = nb; mean = mb; m2 = m2b; return; } + const float nab = n + nb; + const float f = nb / nab; + const float d = mb - mean; + mean = mean + d * f; + m2 = m2 + m2b + d * d * n * f; + n = nab; +} + +/* `cpr_log`: log2 of the chunks a row (n / 8, a power of two dividing the block); `gs8` the chunks + * a group. */ +template +__global__ __launch_bounds__(kT) void gn_part_kernel(const TX* __restrict__ x, + float* __restrict__ stats, int M, int groups, + int cpr_log, int gs8, int ldx, int rpp) { + __shared__ float sh[3][kT]; + const int tid = threadIdx.x; + const int cpr = 1 << cpr_log, slots = kT >> cpr_log; + const int c = tid & (cpr - 1), slot = tid >> cpr_log; + const int p = blockIdx.x; + const int r0 = p * rpp, r1 = min(M, r0 + rpp); + float cnt = 0.0f, s1 = 0.0f, s2 = 0.0f, shift = 0.0f; + for (int r = r0 + slot; r < r1; r += slots) { + float v[8]; + ld8(x + (size_t)r * ldx + c * 8, v); + if (cnt == 0.0f) shift = v[0]; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const float d = v[j] - shift; + s1 += d; + s2 += d * d; + } + cnt += 8.0f; + } + float mean = 0.0f, m2 = 0.0f; + if (cnt > 0.0f) { + const float q = s1 / cnt; + mean = shift + q; + m2 = fmaxf(s2 - s1 * q, 0.0f); + } + sh[0][tid] = cnt; + sh[1][tid] = mean; + sh[2][tid] = m2; + __syncthreads(); + for (int g = tid; g < groups; g += kT) { + float N = 0.0f, Mn = 0.0f, Q = 0.0f; + for (int s = 0; s < slots; ++s) + for (int k = 0; k < gs8; ++k) { + const int t = (s << cpr_log) + g * gs8 + k; + chan_merge(N, Mn, Q, sh[0][t], sh[1][t], sh[2][t]); + } + float* o = stats + 2 * groups + ((size_t)g * kGnParts + p) * 3; + o[0] = N; + o[1] = Mn; + o[2] = Q; + } +} + +__global__ __launch_bounds__(kT) void gn_final_kernel(float* __restrict__ stats, int groups, + int parts, float eps) { + __shared__ float sh[3][kT]; + const int g = blockIdx.x, tid = threadIdx.x; + const float* P = stats + 2 * groups + (size_t)g * kGnParts * 3; + float N = 0.0f, Mn = 0.0f, Q = 0.0f; + for (int p = tid; p < parts; p += kT) chan_merge(N, Mn, Q, P[3 * p], P[3 * p + 1], P[3 * p + 2]); + sh[0][tid] = N; + sh[1][tid] = Mn; + sh[2][tid] = Q; + __syncthreads(); + for (int s = kT / 2; s > 0; s >>= 1) { + if (tid < s) { + float a = sh[0][tid], b = sh[1][tid], q = sh[2][tid]; + chan_merge(a, b, q, sh[0][tid + s], sh[1][tid + s], sh[2][tid + s]); + sh[0][tid] = a; + sh[1][tid] = b; + sh[2][tid] = q; + } + __syncthreads(); + } + if (tid == 0) { + const float var = sh[2][0] / sh[0][0]; + stats[2 * g] = sh[1][0]; + stats[2 * g + 1] = 1.0f / sqrtf(var + eps); + } +} + +/* `wf`, `bf`: the gain's and bias's dtype is f32; `modk` 0 no modulation, 1 a bf16 row, 2 an f32 + * one. x and y may be the same memory: a thread reads its chunk before it writes it. */ +template +__global__ __launch_bounds__(kT) void gn_apply_kernel( + const TX* x, TY* y, const void* __restrict__ w, const void* __restrict__ b, + const void* __restrict__ mod, const float* __restrict__ stats, int M, int n, int cpr_log, + int gs8, int ldx, int ldy, int wf, int bf, int modk, int silu) { + const int slots = kT >> cpr_log; + const int tid = threadIdx.x; + const int r = blockIdx.x * slots + (tid >> cpr_log); + if (r >= M) return; + const int ck = tid & ((1 << cpr_log) - 1), c = ck * 8; + const int g = ck / gs8; + const float mean = stats[2 * g], rstd = stats[2 * g + 1]; + float v[8], wv[8], bv[8]; + ld8(x + (size_t)r * ldx + c, v); + ld8w(w, wf != 0, c, wv); + ld8w(b, bf != 0, c, bv); +#pragma unroll + for (int j = 0; j < 8; ++j) v[j] = (v[j] - mean) * rstd * wv[j] + bv[j]; + if (modk) { + float sc[8], sf[8]; + ld8w(mod, modk == 2, c, sc); + ld8w(mod, modk == 2, n + c, sf); +#pragma unroll + for (int j = 0; j < 8; ++j) v[j] = v[j] * (1.0f + sc[j]) + sf[j]; + } + if (silu) { +#pragma unroll + for (int j = 0; j < 8; ++j) v[j] = v[j] / (1.0f + expf(-v[j])); + } + st8(y + (size_t)r * ldy + c, v); +} + +// ---------------------------------------------------------------------------- tconv_dw +// A depthwise convolution along the frames: a thread one 8-channel chunk of one frame position, +// walking every frame with the k-frame window in registers, so each input row is read once. +// kTdFB frames a step: their loads are issued together, then the step's outputs, each the taps in +// ascending order in f32 and one rounding after the bias. The grid strides over (position, chunk). +constexpr int kTdK = 5; +constexpr int kTdFB = 4; + +__global__ __launch_bounds__(kT) void tconv_dw_kernel( + const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, const uint16_t* __restrict__ b, + uint16_t* __restrict__ y, const int* __restrict__ geom, int Mcap, int xrows, int n, int ldx, + int ldy) { + int gT, gH, gW; + long long vol; + if (!volume_of(geom, xrows, &gT, &gH, &gW, &vol)) return; + const int Mv = vol < (long long)Mcap ? (int)vol : Mcap; + const int P = gH * gW, cpr = n / 8; + const long long pairs = (long long)P * cpr; + constexpr int H = kTdK / 2, WIN = kTdFB + kTdK - 1; + for (long long q = (long long)blockIdx.x * kT + threadIdx.x; q < pairs; + q += (long long)gridDim.x * kT) { + const int p = (int)(q / cpr), c = (int)(q % cpr) * 8; + float wv[8][kTdK], bv[8]; +#pragma unroll + for (int e = 0; e < 8; ++e) { +#pragma unroll + for (int j = 0; j < kTdK; ++j) wv[e][j] = bf2f(w[(size_t)(c + e) * kTdK + j]); + } + ld8(b + c, bv); + // win[i] holds frame t0 - H + i; frames outside [0, T) stay zero and add nothing. + uint4 win[WIN]; +#pragma unroll + for (int i = 0; i < WIN; ++i) win[i] = make_uint4(0u, 0u, 0u, 0u); +#pragma unroll + for (int i = H; i < kTdK - 1; ++i) + if (i - H < gT) win[i] = *(const uint4*)(x + ((size_t)(i - H) * P + p) * ldx + c); + for (int t0 = 0; t0 < gT; t0 += kTdFB) { +#pragma unroll + for (int i = kTdK - 1; i < WIN; ++i) { + const int f = t0 - H + i; + win[i] = f < gT ? *(const uint4*)(x + ((size_t)f * P + p) * ldx + c) + : make_uint4(0u, 0u, 0u, 0u); + } +#pragma unroll + for (int s = 0; s < kTdFB; ++s) { + const int t = t0 + s; + const long long row = (long long)t * P + p; + if (t >= gT || row >= Mv) break; + float acc[8]; +#pragma unroll + for (int e = 0; e < 8; ++e) acc[e] = 0.0f; +#pragma unroll + for (int j = 0; j < kTdK; ++j) { + const int f = t + j - H; + if (f < 0 || f >= gT) continue; + float xv[8]; + const uint4 u = win[s + j]; + xv[0] = bf16w_lo(u.x); xv[1] = bf16w_hi(u.x); xv[2] = bf16w_lo(u.y); + xv[3] = bf16w_hi(u.y); xv[4] = bf16w_lo(u.z); xv[5] = bf16w_hi(u.z); + xv[6] = bf16w_lo(u.w); xv[7] = bf16w_hi(u.w); +#pragma unroll + for (int e = 0; e < 8; ++e) acc[e] = acc[e] + wv[e][j] * xv[e]; + } +#pragma unroll + for (int e = 0; e < 8; ++e) acc[e] = acc[e] + bv[e]; + st8(y + (size_t)row * ldy + c, acc); + } +#pragma unroll + for (int i = 0; i < kTdK - 1; ++i) win[i] = win[i + kTdFB]; + } + } +} + +// ---------------------------------------------------------------------------- resize_bilinear +// torch's bilinear resize of each frame, align_corners=False at a given size (upsample_bilinear2d's +// source index and lambdas, in f32): a thread one 8-channel chunk of one output voxel, its two +// rows' and two columns' taps recomputed from its indices. +__device__ __forceinline__ void bil_axis(int o, int in, int out, int* i0, int* i1, float* l0, + float* l1) { + const float s = (float)in / (float)out; + float src = s * ((float)o + 0.5f) - 0.5f; + src = src < 0.0f ? 0.0f : src; + *i0 = (int)src; + *i1 = *i0 + (*i0 < in - 1 ? 1 : 0); + *l1 = src - (float)*i0; + *l0 = 1.0f - *l1; +} + +template +__global__ __launch_bounds__(kT) void resize_bilinear_kernel( + const TV* __restrict__ x, TV* __restrict__ y, const int* __restrict__ geom, long long cap, + long long xrows, int cpr, int ldx, int ldy) { + const int T = geom[0], h = geom[1], w = geom[2], H = geom[3], W = geom[4]; + if (T <= 0 || h <= 0 || w <= 0 || H <= 0 || W <= 0) return; + if ((long long)T * h * w > xrows) return; + const long long rows = (long long)T * H * W; + const long long id = (long long)blockIdx.x * kT + threadIdx.x; + const long long r = id / cpr; + if (r >= rows || r >= cap) return; + const int c = (int)(id % cpr) * 8; + const int t = (int)(r / ((long long)H * W)); + const int rem = (int)(r - (long long)t * H * W); + const int oi = rem / W, oj = rem - oi * W; + int i0, i1, j0, j1; + float ly0, ly1, lx0, lx1; + bil_axis(oi, h, H, &i0, &i1, &ly0, &ly1); + bil_axis(oj, w, W, &j0, &j1, &lx0, &lx1); + const size_t f0 = (size_t)t * h * w; + float a[8], b[8], d[8], e[8], o[8]; + ld8(x + (f0 + (size_t)i0 * w + j0) * ldx + c, a); + ld8(x + (f0 + (size_t)i0 * w + j1) * ldx + c, b); + ld8(x + (f0 + (size_t)i1 * w + j0) * ldx + c, d); + ld8(x + (f0 + (size_t)i1 * w + j1) * ldx + c, e); +#pragma unroll + for (int k = 0; k < 8; ++k) + o[k] = ly0 * (lx0 * a[k] + lx1 * b[k]) + ly1 * (lx0 * d[k] + lx1 * e[k]); + st8(y + (size_t)r * ldy + c, o); +} + +// ---------------------------------------------------------------------------- patch_fold +// patch_unfold's inverse: voxel rows to patch rows, f32, a thread an output value. The two lists +// are f32 kernel arguments. +constexpr int kMaxChan = 64; +struct ChanList { float v[kMaxChan]; }; + +template +__global__ __launch_bounds__(kT) void patch_fold_kernel( + const TX* __restrict__ x, const int* __restrict__ geom, float* __restrict__ y, ChanList mul, + ChanList add, int C, int pt, int ph, int pw, int ldx, int ldy, long long cap, long long xrows) { + const int F = geom[0], Hp = geom[1], Wp = geom[2]; + if (F <= 0 || Hp <= 0 || Wp <= 0) return; + const long long Hv = (long long)Hp * ph, Wv = (long long)Wp * pw; + if ((long long)F * pt * Hv * Wv > xrows) return; + const int K = C * pt * ph * pw; + const long long rows = (long long)F * Hp * Wp; + const long long id = (long long)blockIdx.x * kT + threadIdx.x; + const long long r = id / K; + if (r >= rows || r >= cap) return; + const int col = (int)(id % K); + const int c = col / (pt * ph * pw), sub = col % (pt * ph * pw); + const int a = sub / (ph * pw), bb = (sub / pw) % ph, d = sub % pw; + const long long f = r / ((long long)Hp * Wp), i = (r / Wp) % Hp, j = r % Wp; + const long long vox = ((f * pt + a) * Hv + i * ph + bb) * Wv + j * pw + d; + float v; + if constexpr (sizeof(TX) == 2) v = bf2f(x[vox * ldx + c]); + else v = x[vox * ldx + c]; + y[r * ldy + col] = v * mul.v[c] + add.v[c]; +} + +// ---------------------------------------------------------------------------- flow_renoise +// x = (1 - s) x + s z, z element k n + c of the (seed, stream) normal stream: a thread a value, +// each product and the sum one f32 rounding. +__global__ __launch_bounds__(kT) void flow_renoise_kernel( + const float* __restrict__ sigma, const uint32_t* __restrict__ seed, float* __restrict__ x, + int n, int ldx, long long total, unsigned long long stream) { + const long long id = (long long)blockIdx.x * kT + threadIdx.x; + if (id >= total) return; + const long long k = id / n; + const int c = (int)(id % n); + const float s = sigma[0]; + const uint64_t sd = (uint64_t)seed[0] | ((uint64_t)seed[1] << 32); + const float z = rad_philox_normal_s(sd, stream, (uint64_t)id); + float* p = x + k * ldx + c; + const float a = (1.0f - s) * *p; + const float bz = s * z; + *p = a + bz; +} + +inline bool is_bf16(const RadTensor* t) { return t && t->dtype == RAD_BF16; } +inline bool is_f32(const RadTensor* t) { return t && t->dtype == RAD_F32; } +inline bool is_i32(const RadTensor* t) { return t && t->dtype == RAD_I32; } + +// A row-major operand's row count and pitch, the pitch a multiple of eight elements and the base +// 16-byte aligned, so a row's eight-element chunks are 16- or 32-byte accesses. +inline bool rows8(const RadTensor* t, long long n, long long* rows, long long* ld) { + if (!t || n <= 0 || (n & 7)) return false; + *ld = r4d_rows_pitch(t, n, rows); + return *ld >= 0 && !(*ld & 7) && !((uintptr_t)t->data & 15); +} + +// A space-separated list of floats kept in f32, as libref's parse_f32_list. +int parse_f32_list(const char* s, float* out, int max) { + int n = 0; + while (s && *s) { + char* end = nullptr; + const double v = std::strtod(s, &end); + if (end == s) break; + if (n == max) return max + 1; + out[n++] = (float)v; + s = end; + } + return n; +} + +inline int log2_exact(long long v) { + int l = 0; + while ((1ll << l) < v) ++l; + return (1ll << l) == v ? l : -1; +} + +} // namespace + +// ============================================================== the plugin ABI entry points + +/* ------------------------------------------------------------------ conv3d_ndhwc */ +enum { C3_X = 0, C3_W, C3_B, C3_GEOM, C3_RES, C3_Y }; + +extern "C" int r4d_rad_conv3d_ndhwc(const RadArgs* a, RadStream stream) { + const RadTensor *x = r4d_opt(a, C3_X), *w = r4d_opt(a, C3_W), *b = r4d_opt(a, C3_B); + const RadTensor *geom = r4d_opt(a, C3_GEOM), *res = r4d_opt(a, C3_RES), *y = r4d_opt(a, C3_Y); + if (!x || !w || !b || !geom || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(x) || !is_bf16(w) || !is_bf16(y) || (!is_bf16(b) && !is_f32(b)) || + !is_i32(geom) || (res && !is_bf16(res))) + return R4D_NO(RAD_E_DTYPE); + const long long cin = r4d_geti_or(a, "cin", 0), cout = r4d_geti_or(a, "cout", 0); + /* 3 x 3 x 3 only: the tap decode is the kernel's constant. */ + if (r4d_geti_or(a, "k", 3) != 3 || r4d_geti_or(a, "kt", 3) != 3) return R4D_NO(RAD_E_SHAPE); + if (cin <= 0 || cout <= 0 || (cin & 7)) return R4D_NO(RAD_E_SHAPE); + const long long K = (long long)kTaps * cin; + if (r4d_numel(w) < cout * K || r4d_numel(b) < cout || r4d_numel(geom) < 3) + return R4D_NO(RAD_E_SHAPE); + if (!r4d_contig(w) || !r4d_contig(b) || !r4d_contig(geom)) return R4D_NO(RAD_E_STRIDE); + long long rx = 0, ldx = 0, ry = 0, rr = 0; + if (!rows8(x, cin, &rx, &ldx) || !r4d_aligned(r4d_p(w), 16)) return R4D_NO(RAD_E_STRIDE); + const long long ldy = r4d_rows_pitch(y, cout, &ry); + const long long ldr = res ? r4d_rows_pitch(res, cout, &rr) : 0; + if (ldy < 0 || ldr < 0) return R4D_NO(RAD_E_STRIDE); + /* The rows written are the device volume's, as libref's; the outputs bound them (and the + * grid), M is not read. */ + long long Mcap = ry; + if (res && Mcap > rr) Mcap = rr; + /* Byte offsets into x and the weight are 32-bit; x's extent (its last row ends at cin) is + * the gather's buffer size, below the out-of-range offset. */ + const long long xbytes = ((rx - 1) * ldx + cin) * 2; + if (Mcap <= 0 || rx <= 0 || xbytes > (long long)kOob || cout * K * 2 >= (1ll << 32) || + Mcap >= (1ll << 31) || cin > 16384) + return R4D_NO(RAD_E_SHAPE); + auto Xp = (const unsigned short*)r4d_p(x); + auto Wp = (const unsigned short*)r4d_p(w); + auto Rp = (const unsigned short*)r4d_p(res); + auto Cp = (unsigned short*)r4d_wp(y); + const void* Bp = r4d_p(b); + const unsigned vec = (ldy % 8) == 0 && r4d_aligned(Cp, 16) && r4d_aligned(Bp, 16) && + (!res || ((ldr % 8) == 0 && r4d_aligned(Rp, 16))); + const dim3 grid((unsigned)((Mcap + kCBM - 1) / kCBM), (unsigned)((cout + kCBN - 1) / kCBN)); + const bool c64 = cin % kCFK == 0, bf32 = is_f32(b); +#define C3_L(C6, RS, BF) \ + return R4D_EMIT(stream, (conv3d_kernel), grid, dim3(kCThreads), 0, Xp, Wp, Bp, Rp, \ + Cp, (const int*)r4d_p(geom), (unsigned)ldx, (unsigned)ldr, (unsigned)ldy, \ + (int)Mcap, (int)rx, (unsigned)xbytes, (int)cin, (int)cout, vec) +#define C3_RES(C6, BF) do { if (res) C3_L(C6, true, BF); C3_L(C6, false, BF); } while (0) +#define C3_BF(C6) do { if (bf32) C3_RES(C6, true); C3_RES(C6, false); } while (0) + if (c64) C3_BF(true); + C3_BF(false); +#undef C3_BF +#undef C3_RES +#undef C3_L +} + +/* ------------------------------------------------------------------ group_norm */ +enum { GN_X = 0, GN_W, GN_B, GN_MOD, GN_STATS, GN_Y }; + +extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) { + const RadTensor *x = r4d_opt(a, GN_X), *w = r4d_opt(a, GN_W), *b = r4d_opt(a, GN_B); + const RadTensor *mod = r4d_opt(a, GN_MOD), *st = r4d_opt(a, GN_STATS), *y = r4d_opt(a, GN_Y); + if (!x || !w || !b || !st || !y) return R4D_NO(RAD_E_INVAL); + if ((!is_bf16(x) && !is_f32(x)) || (!is_bf16(y) && !is_f32(y)) || (!is_bf16(w) && !is_f32(w)) || + (!is_bf16(b) && !is_f32(b)) || (mod && !is_bf16(mod) && !is_f32(mod)) || !is_f32(st)) + return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0), groups = r4d_geti_or(a, "groups", 0); + const char* act = r4d_gets(a, "act"); + int silu = 0; + if (act && *act) { + if (!std::strcmp(act, "silu")) silu = 1; + else if (std::strcmp(act, "none")) return R4D_NO(RAD_E_INVAL); + } + /* A thread an 8-channel chunk inside one group, a row's chunks a power of two dividing the + * 256-thread block. */ + const int cpr_log = (n > 0 && !(n & 7)) ? log2_exact(n / 8) : -1; + if (cpr_log < 0 || n / 8 > kT || groups <= 0 || groups > kT || n % groups || + (n / groups) % 8) + return R4D_NO(RAD_E_SHAPE); + if (r4d_numel(w) < n || r4d_numel(b) < n || (mod && r4d_numel(mod) < 2 * n) || + r4d_numel(st) < groups * (2 + 3 * kGnParts)) + return R4D_NO(RAD_E_SHAPE); + if (!r4d_contig(w) || !r4d_contig(b) || (mod && !r4d_contig(mod)) || !r4d_contig(st) || + !r4d_aligned(r4d_p(w), 16) || !r4d_aligned(r4d_p(b), 16) || !r4d_aligned(r4d_p(mod), 16)) + return R4D_NO(RAD_E_STRIDE); + long long rx = 0, ldx = 0, ry = 0, ldy = 0; + if (!rows8(x, n, &rx, &ldx) || !rows8(y, n, &ry, &ldy)) return R4D_NO(RAD_E_STRIDE); + /* Over y's rows, as libref's (x may hold more); M is not read. Counts are f32 sums: exact + * while a group's M n / groups values stay under 2^24. */ + const long long M = ry; + if (M <= 0 || M > rx || M > ry || M * (n / groups) >= (1ll << 24)) return R4D_NO(RAD_E_SHAPE); + const int slots = kT >> cpr_log; + /* Whole passes of the block a part, as few parts as fill the scratch. */ + long long rpp = (M + kGnParts - 1) / kGnParts; + rpp = (rpp + slots - 1) / slots * slots; + const int parts = (int)((M + rpp - 1) / rpp); + const int gs8 = (int)(n / groups / 8); + float* S = (float*)r4d_wp(st); + const float eps = (float)r4d_getf(a, "eps", 1e-5); + int rc; + if (is_f32(x)) + rc = R4D_EMIT(stream, gn_part_kernel, dim3((unsigned)parts), dim3(kT), 0, + (const float*)r4d_p(x), S, (int)M, (int)groups, cpr_log, gs8, (int)ldx, + (int)rpp); + else + rc = R4D_EMIT(stream, gn_part_kernel, dim3((unsigned)parts), dim3(kT), 0, + (const uint16_t*)r4d_p(x), S, (int)M, (int)groups, cpr_log, gs8, (int)ldx, + (int)rpp); + if (rc != RAD_OK) return R4D_NO(rc); + rc = R4D_EMIT(stream, gn_final_kernel, dim3((unsigned)groups), dim3(kT), 0, S, (int)groups, + parts, eps); + if (rc != RAD_OK) return R4D_NO(rc); + const int modk = !mod ? 0 : is_f32(mod) ? 2 : 1; + const dim3 grid((unsigned)((M + slots - 1) / slots)); +#define GN_A(TX, TY) \ + return R4D_EMIT(stream, (gn_apply_kernel), grid, dim3(kT), 0, (const TX*)r4d_p(x), \ + (TY*)r4d_wp(y), r4d_p(w), r4d_p(b), r4d_p(mod), (const float*)S, (int)M, \ + (int)n, cpr_log, gs8, (int)ldx, (int)ldy, (int)is_f32(w), (int)is_f32(b), \ + modk, silu) + if (is_f32(x)) { + if (is_f32(y)) GN_A(float, float); + GN_A(float, uint16_t); + } + if (is_f32(y)) GN_A(uint16_t, float); + GN_A(uint16_t, uint16_t); +#undef GN_A +} + +/* ------------------------------------------------------------------ tconv_dw */ +enum { TD_X = 0, TD_W, TD_B, TD_GEOM, TD_Y }; + +extern "C" int r4d_rad_tconv_dw(const RadArgs* a, RadStream stream) { + const RadTensor *x = r4d_opt(a, TD_X), *w = r4d_opt(a, TD_W), *b = r4d_opt(a, TD_B); + const RadTensor *geom = r4d_opt(a, TD_GEOM), *y = r4d_opt(a, TD_Y); + if (!x || !w || !b || !geom || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(x) || !is_bf16(w) || !is_bf16(b) || !is_bf16(y) || !is_i32(geom)) + return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0), k = r4d_geti_or(a, "k", 0); + if (n <= 0 || (n & 7) || k != kTdK || r4d_numel(w) < n * k || r4d_numel(b) < n || + r4d_numel(geom) < 3) + return R4D_NO(RAD_E_SHAPE); + if (!r4d_contig(w) || !r4d_contig(b) || !r4d_contig(geom) || !r4d_aligned(r4d_p(b), 16)) + return R4D_NO(RAD_E_STRIDE); + long long rx = 0, ldx = 0, ry = 0, ldy = 0; + if (!rows8(x, n, &rx, &ldx) || !rows8(y, n, &ry, &ldy)) return R4D_NO(RAD_E_STRIDE); + /* The device volume's rows, at most y's; M is not read. */ + const long long M = ry; + if (M <= 0 || rx * ldx >= (1ll << 40)) return R4D_NO(RAD_E_SHAPE); + /* One frame position's chunks a thread, at most the rows' worth; the kernel strides over the + * device geometry's (position, chunk) pairs. */ + const long long pairs = M * (n / 8); + const unsigned blocks = (unsigned)std::min((pairs + kT - 1) / kT, 2048); + return R4D_EMIT(stream, tconv_dw_kernel, dim3(blocks), dim3(kT), 0, + (const uint16_t*)r4d_p(x), (const uint16_t*)r4d_p(w), + (const uint16_t*)r4d_p(b), (uint16_t*)r4d_wp(y), (const int*)r4d_p(geom), + (int)M, (int)std::min(rx, (1ll << 31) - 1), (int)n, (int)ldx, + (int)ldy); +} + +/* ------------------------------------------------------------------ resize_bilinear */ +enum { RB_X = 0, RB_GEOM, RB_Y }; + +extern "C" int r4d_rad_resize_bilinear(const RadArgs* a, RadStream stream) { + const RadTensor *x = r4d_opt(a, RB_X), *geom = r4d_opt(a, RB_GEOM), *y = r4d_opt(a, RB_Y); + if (!x || !geom || !y) return R4D_NO(RAD_E_INVAL); + if ((!is_bf16(x) && !is_f32(x)) || x->dtype != y->dtype || !is_i32(geom)) + return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0); + if (n <= 0 || (n & 7) || r4d_numel(geom) < 5) return R4D_NO(RAD_E_SHAPE); + if (!r4d_contig(geom)) return R4D_NO(RAD_E_STRIDE); + long long rx = 0, ldx = 0, ry = 0, ldy = 0; + if (!rows8(x, n, &rx, &ldx) || !rows8(y, n, &ry, &ldy)) return R4D_NO(RAD_E_STRIDE); + /* The device volume's rows, at most y's; M is not read. */ + const long long M = ry; + if (M <= 0) return R4D_NO(RAD_E_SHAPE); + const long long total = M * (n / 8); + const dim3 grid((unsigned)((total + kT - 1) / kT)); + if (is_f32(x)) + return R4D_EMIT(stream, resize_bilinear_kernel, grid, dim3(kT), 0, + (const float*)r4d_p(x), (float*)r4d_wp(y), (const int*)r4d_p(geom), M, rx, + (int)(n / 8), (int)ldx, (int)ldy); + return R4D_EMIT(stream, resize_bilinear_kernel, grid, dim3(kT), 0, + (const uint16_t*)r4d_p(x), (uint16_t*)r4d_wp(y), (const int*)r4d_p(geom), M, + rx, (int)(n / 8), (int)ldx, (int)ldy); +} + +/* ------------------------------------------------------------------ patch_fold */ +enum { PF_X = 0, PF_GEOM, PF_Y }; + +extern "C" int r4d_rad_patch_fold(const RadArgs* a, RadStream stream) { + const RadTensor *x = r4d_opt(a, PF_X), *geom = r4d_opt(a, PF_GEOM), *y = r4d_opt(a, PF_Y); + if (!x || !geom || !y) return R4D_NO(RAD_E_INVAL); + if ((!is_f32(x) && !is_bf16(x)) || !is_f32(y) || !is_i32(geom)) return R4D_NO(RAD_E_DTYPE); + const long long C = r4d_geti_or(a, "C", 0), pt = r4d_geti_or(a, "pt", 0); + const long long ph = r4d_geti_or(a, "ph", 0), pw = r4d_geti_or(a, "pw", 0); + ChanList mul{}, add{}; + if (C <= 0 || C > kMaxChan || pt <= 0 || ph <= 0 || pw <= 0 || + parse_f32_list(r4d_gets(a, "mul"), mul.v, kMaxChan) != C || + parse_f32_list(r4d_gets(a, "add"), add.v, kMaxChan) != C || r4d_numel(geom) < 3) + return R4D_NO(RAD_E_SHAPE); + const long long K = C * pt * ph * pw; + long long rx = 0, ry = 0; + const long long ldx = r4d_rows_pitch(x, C, &rx), ldy = r4d_rows_pitch(y, K, &ry); + if (ldx < 0 || ldy < 0 || !r4d_contig(geom)) return R4D_NO(RAD_E_STRIDE); + /* The device geometry's patches, at most y's rows; M is not read. */ + const long long M = ry; + if (M <= 0 || rx <= 0) return R4D_NO(RAD_E_SHAPE); + const long long total = M * K; + const dim3 grid((unsigned)((total + kT - 1) / kT)); + if (is_f32(x)) + return R4D_EMIT(stream, patch_fold_kernel, grid, dim3(kT), 0, + (const float*)r4d_p(x), (const int*)r4d_p(geom), (float*)r4d_wp(y), mul, + add, (int)C, (int)pt, (int)ph, (int)pw, (int)ldx, (int)ldy, M, rx); + return R4D_EMIT(stream, patch_fold_kernel, grid, dim3(kT), 0, + (const uint16_t*)r4d_p(x), (const int*)r4d_p(geom), (float*)r4d_wp(y), mul, + add, (int)C, (int)pt, (int)ph, (int)pw, (int)ldx, (int)ldy, M, rx); +} + +/* ------------------------------------------------------------------ flow_renoise */ +enum { FR_SIGMA = 0, FR_SEED, FR_X }; + +extern "C" int r4d_rad_flow_renoise(const RadArgs* a, RadStream stream) { + const RadTensor *sg = r4d_opt(a, FR_SIGMA), *seed = r4d_opt(a, FR_SEED), *x = r4d_opt(a, FR_X); + if (!sg || !seed || !x) return R4D_NO(RAD_E_INVAL); + if (!is_f32(sg) || !is_f32(x) || (seed->dtype != RAD_U32 && seed->dtype != RAD_I32)) + return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0), sm = r4d_geti_or(a, "stream", 0); + if (n <= 0 || sm < 0 || r4d_numel(sg) < 1 || r4d_numel(seed) < 2) return R4D_NO(RAD_E_SHAPE); + long long rx = 0; + const long long ldx = r4d_rows_pitch(x, n, &rx); + if (ldx < 0 || !r4d_contig(seed)) return R4D_NO(RAD_E_STRIDE); + /* Every row of x, as libref's; M is not read. */ + const long long M = rx; + if (M <= 0) return R4D_NO(RAD_E_SHAPE); + const long long total = M * n; + return R4D_EMIT(stream, flow_renoise_kernel, dim3((unsigned)((total + kT - 1) / kT)), dim3(kT), + 0, (const float*)r4d_p(sg), (const uint32_t*)r4d_p(seed), (float*)r4d_wp(x), + (int)n, (int)ldx, total, (unsigned long long)sm); +} diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 6b0d1d3b..572eb574 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -151,6 +151,12 @@ int ref_patch_unfold(const RadArgs*, RadStream); int ref_vtile_gather(const RadArgs*, RadStream); int ref_vtile_stitch(const RadArgs*, RadStream); int ref_grid_pos3(const RadArgs*, RadStream); +int ref_patch_fold(const RadArgs*, RadStream); +int ref_conv3d_ndhwc(const RadArgs*, RadStream); +int ref_group_norm(const RadArgs*, RadStream); +int ref_tconv_dw(const RadArgs*, RadStream); +int ref_resize_bilinear(const RadArgs*, RadStream); +int ref_flow_renoise(const RadArgs*, RadStream); /* ref_vsa.cpp */ int ref_vsa_select(const RadArgs*, RadStream); int ref_attn_vsa(const RadArgs*, RadStream); @@ -346,6 +352,12 @@ REF_SHAPE_FN(ref_patch_unfold); REF_SHAPE_FN(ref_vtile_gather); REF_SHAPE_FN(ref_vtile_stitch); REF_SHAPE_FN(ref_grid_pos3); +REF_SHAPE_FN(ref_patch_fold); +REF_SHAPE_FN(ref_conv3d_ndhwc); +REF_SHAPE_FN(ref_group_norm); +REF_SHAPE_FN(ref_tconv_dw); +REF_SHAPE_FN(ref_resize_bilinear); +REF_SHAPE_FN(ref_flow_renoise); REF_SHAPE_FN(ref_vsa_select); REF_SHAPE_FN(ref_attn_vsa); REF_SHAPE_FN(ref_conv1d); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 27a3829f..6b6a55d9 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -750,6 +750,25 @@ static const RadOperandSpec oAttnVsa[] = { OPD("q"), OPD("k"), OPD("v"), OPD("se OPD("geom"), OPD("sel"), OPD_O("coarse"), OPD_O("gate"), OUT("out"), OPD_O("k_i8"), OPD_O("k_scale"), OPD_O("v_scale") }; +/* ---- the latent upscaler (ref_video.cpp). `geom` is the request's volume, i32 on the device: + * (T, H, W) for conv3d_ndhwc and tconv_dw, (T, h, w, H, W) for resize_bilinear and (F, Hp, Wp) + * for patch_fold, which shares patch_unfold's parameters and operands. */ +static const RadParamSpec pConv3d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"), + P_INT("kt"), P_STR("dtype") }; +static const RadOperandSpec oConv3d[] = { OPD("x"), WGT("w"), WGT("b"), OPD("geom"), + OPD_O("res"), OUT("y") }; +/* `mod` is one row [scale | shift]; `stats` the per-group mean and rstd, then scratch. */ +static const RadParamSpec pGroupNorm[] = { P_INT("M"), P_INT("n"), P_INT("groups"), P_F64("eps"), + P_STR("act"), P_STR("dtype") }; +static const RadOperandSpec oGroupNorm[] = { OPD("x"), WGT("w"), WGT("b"), OPD_O("mod"), + INOUT("stats"), OUT("y") }; +static const RadParamSpec pTconvDw[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_STR("dtype") }; +static const RadOperandSpec oTconvDw[] = { OPD("x"), WGT("w"), WGT("b"), OPD("geom"), OUT("y") }; +static const RadOperandSpec oResize[] = { OPD("x"), OPD("geom"), OUT("y") }; +/* `sigma` is one f32 value, `seed` two u32 words, low first. */ +static const RadParamSpec pFlowRenoise[] = { P_INT("M"), P_INT("n"), P_INT("stream"), + P_STR("dtype") }; +static const RadOperandSpec oFlowRenoise[] = { OPD("sigma"), OPD("seed"), INOUT("x") }; /* ---- audio generation (ref_audio.cpp) */ static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"), @@ -1443,6 +1462,32 @@ static const RadOpSchema kSchemas[] = { "its k tiles of `sel` (k ascending video tiles, RAD_E_INVAL otherwise); f32 softmax with the " "max subtracted. With `coarse` and `gate`: out = rd(rd(o) + coarse[h][tile] gate), rd the " "output's dtype." }, +{ "conv3d_ndhwc", ARR(pConv3d), ARR(oConv3d), + "a 3-D convolution over voxel rows [T H W, cin] -> [T H W, cout] (geom = (T, H, W)): " + "PyTorch's Conv3d weight [cout, cin, kt, k, k] and bias, stride 1, `same` zero padding (kt/2 " + "frames, k/2 rows and columns a side; k and kt odd), f32 accumulation, rd(acc + b); with `res`, " + "rd(rd(acc + b) + res), `res` possibly y itself." }, +{ "group_norm", ARR(pGroupNorm), ARR(oGroupNorm), + "PyTorch's GroupNorm over all M rows: group g is channels [g n/groups, (g+1) n/groups), its " + "biased mean and variance in f64, rstd = 1 / sqrt(var + eps) in f32; v = (x - mean) rstd w + b, " + "with `mod` (one row [scale | shift]) v (1 + scale) + shift, `act` none or silu, one rounding. " + "stats[2g], stats[2g+1] get the mean and rstd; stats holds groups (2 + 3 1024) f32, the rest " + "scratch. y may be x." }, +{ "tconv_dw", ARR(pTconvDw), ARR(oTconvDw), + "a depthwise convolution along the frames of voxel rows (geom = (T, H, W)): PyTorch's " + "[n, 1, k, 1, 1] weight and bias, k odd, zero frames outside [0, T), the sum f32 in tap order, " + "rd(acc + b)." }, +{ "resize_bilinear", ARR(pMnD), ARR(oResize), + "each frame of voxel rows [T h w, n] resized to [T H W, n] (geom = (T, h, w, H, W)) as torch's " + "bilinear with align_corners=False at a size: src = max(f32(h / H) (i + 0.5) - 0.5, 0), its " + "floor and the next row clamped, weights in f32, rounded once." }, +{ "patch_fold", ARR(pPatchUnfold), ARR(oPatchUnfold), + "patch_unfold's inverse: voxel rows [(F pt) (Hp ph) (Wp pw), C] folded to patch rows " + "[F Hp Wp, C pt ph pw] (geom = (F, Hp, Wp)) and normalised, f32(f32(x * mul[c]) + add[c]) with " + "`mul` and `add` lists of C f32 values." }, +{ "flow_renoise", ARR(pFlowRenoise), ARR(oFlowRenoise), + "a clean latent re-noised to sigma s: x = f32(f32(f32(1 - s) x) + f32(s z)), z element " + "k n + c of the normal stream (seed, `stream`) (abi/rad_philox.h)." }, { "conv1d", ARR(pConv1d), ARR(oConv1d), "a 1-D convolution over the sequences `cu_seqlens` bounds, channels innermost: x [rows, cin], " "y [rows, cout], PyTorch's [cout, cin, k] weight and an optional bias, dilation `dil` and padding " @@ -1943,6 +1988,19 @@ SIMPLE("ref_vsa_select", "vsa_select", "attn", SIMPLE("ref_attn_vsa", "attn_vsa", "attn", "block-sparse attention over the prefix and selected video tiles, the gated coarse term", "float q, k, v, coarse, gate and out; i32 segs, geom and sel", ref_attn_vsa), +SIMPLE("ref_conv3d_ndhwc", "conv3d_ndhwc", "conv", + "a 3-D convolution over voxel rows, channels innermost", DT_FLOAT, ref_conv3d_ndhwc), +SIMPLE("ref_group_norm", "group_norm", "norm", + "a group norm over all rows, optionally modulated, then an activation", DT_FLOAT, + ref_group_norm), +SIMPLE("ref_tconv_dw", "tconv_dw", "conv", "a depthwise convolution along a volume's frames", + DT_FLOAT, ref_tconv_dw), +SIMPLE("ref_resize_bilinear", "resize_bilinear", "elem", + "each frame of a volume resized bilinearly", DT_FLOAT, ref_resize_bilinear), +SIMPLE("ref_patch_fold", "patch_fold", "elem", "voxel rows to normalised patch rows", DT_FLOAT, + ref_patch_fold), +SIMPLE("ref_flow_renoise", "flow_renoise", "elem", "a clean latent re-noised to a sigma", DT_FLOAT, + ref_flow_renoise), SIMPLE("ref_conv1d", "conv1d", "conv", "a 1-D convolution over sequences, channels innermost", DT_FLOAT, ref_conv1d), SIMPLE("ref_conv_t1d", "conv_t1d", "conv", "a transposed 1-D convolution growing each sequence", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index a495d0a3..4ba50cac 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -2568,6 +2568,97 @@ int ref_grid_pos3_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out return o.finish("grid_pos3", operand, out); } +/* ---- the latent upscaler. A volume is c x c x c voxels, c the largest whose cube M holds (the + * ranged M is the output's rows), so a 3 x 3 x 3 volume and up has an interior voxel. Every geom + * entry being c, resize_bilinear's description is the identity resize; its hand cases resize. */ +static int64_t cube_side(int64_t M) { + int64_t c = 0; + while ((c + 1) * (c + 1) * (c + 1) <= M) ++c; + return c; +} + +int ref_conv3d_ndhwc_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), cin = gi(p, n_p, "cin", 0), cout = gi(p, n_p, "cout", 0); + const int64_t k = gi(p, n_p, "k", 0), kt = gi(p, n_p, "kt", 0), c = cube_side(M); + if (c <= 0 || cin <= 0 || cout <= 0 || k <= 0 || kt <= 0 || !(k & 1) || !(kt & 1)) + return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { c * c * c, cin }); /* x: voxel rows */ + o.t(D, { cout, cin, kt, k, k }); /* w */ + o.t(D, { cout }); /* b */ + o.t_idx({ 3 }, 0, c, 0); /* geom: (T, H, W) */ + o.t(D, { M, cout }); /* res */ + o.t(D, { M, cout }); /* y */ + return o.finish("conv3d_ndhwc", operand, out); +} + +/* The modulated form; `stats` at the size the op requires. */ +int ref_group_norm_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), G = gi(p, n_p, "groups", 0); + if (M <= 0 || n <= 0 || G <= 0 || n % G) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M, n }); /* x */ + o.t(D, { n }); /* w */ + o.t(D, { n }); /* b */ + o.t(D, { 2 * n }); /* mod: [scale | shift] */ + o.t((uint32_t)RAD_F32, { G * (2 + 3 * 1024) }); /* stats, INOUT */ + o.t(D, { M, n }); /* y */ + return o.finish("group_norm", operand, out); +} + +int ref_tconv_dw_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), k = gi(p, n_p, "k", 0); + const int64_t c = cube_side(M); + if (c <= 0 || n <= 0 || k <= 0 || !(k & 1)) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { c * c * c, n }); /* x */ + o.t(D, { n, 1, k, 1, 1 }); /* w */ + o.t(D, { n }); /* b */ + o.t_idx({ 3 }, 0, c, 0); /* geom: (T, H, W) */ + o.t(D, { M, n }); /* y */ + return o.finish("tconv_dw", operand, out); +} + +int ref_resize_bilinear_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), c = cube_side(M); + if (c <= 0 || n <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { c * c * c, n }); /* x */ + o.t_idx({ 5 }, 0, c, 0); /* geom: (T, h, w, H, W) */ + o.t(D, { M, n }); /* y */ + return o.finish("resize_bilinear", operand, out); +} + +/* patch_unfold's 2 x 2 x 2 grid of patches, folded. */ +int ref_patch_fold_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), C = gi(p, n_p, "C", 0); + const int64_t pt = gi(p, n_p, "pt", 0), ph = gi(p, n_p, "ph", 0), pw = gi(p, n_p, "pw", 0); + const int64_t c = 2, vol = pt * ph * pw; + if (C <= 0 || pt <= 0 || ph <= 0 || pw <= 0 || M < c * c * c) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { c * c * c * vol, C }); /* x: voxel rows */ + o.t_idx({ 3 }, 0, c, 0); /* geom: (F, Hp, Wp) */ + o.t((uint32_t)RAD_F32, { M, C * vol }); /* y: patch rows */ + return o.finish("patch_fold", operand, out); +} + +/* sigma in (0, 1); the latent f32. */ +int ref_flow_renoise_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED; + const uint32_t F = (uint32_t)RAD_F32; + Opd o; + o.t_fill(F, { 1 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* sigma */ + o.t_idx({ 2 }, (int64_t)1 << 30, -1, 0); /* seed: two words */ + o.t(F, { M, n }); /* x, INOUT */ + return o.finish("flow_renoise", operand, out); +} + /* ================================================================== video sparse attention * * The tiles come from the values of `segs` and `geom`, which a description draws only as diff --git a/libref/ref_video.cpp b/libref/ref_video.cpp index a690f687..e6a2b35e 100644 --- a/libref/ref_video.cpp +++ b/libref/ref_video.cpp @@ -1,15 +1,18 @@ /* ref_video.cpp -- the video generator's ops around its decoder (docs/OPS.md, "Video * generation"): the denoised latent's patch rows unfolded to voxels, the tiles a video decoder * runs over, gathered from the latent and stitched back into frames, and the rotary positions of - * a tile's tokens. + * a tile's tokens; and the latent upscaler's (docs/OPS.md, "The latent upscaler"): voxel rows + * folded back into patch rows, the 3-D and temporal depthwise convolutions, the group norm, the + * per-frame bilinear resize and the re-noising of the upscaled latent. * * Per-request geometry (a video's frames, height and width) comes from a `geom` operand the run * phase writes on the device, never from the parameters, which are fixed at declare. The tiles * are diffusers' AutoencoderKLMiniMaxH3 tiling in latent units, and the stitch rounds where its - * bf16 blends round. + * bf16 blends round. The upscaler's ops round once into their output, where a fused kernel would. */ #include "ref_common.h" #include "ref_ops.h" +#include "rad_philox.h" #include #include @@ -101,6 +104,44 @@ int ref_patch_unfold(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ patch_fold */ +/* patch_unfold's inverse, normalising instead of denormalising: voxel rows + * x [(F pt) (Hp ph) (Wp pw), C] folded into patch rows y [F Hp Wp, C pt ph pw], column + * (c, a, b, d) of patch (f, i, j) at c pt ph pw + a ph pw + b pw + d: + * + * y[(f, i, j), (c, a, b, d)] = f32(f32(x[(f pt + a, i ph + b, j pw + d), c] * mul[c]) + add[c]) + * + * `geom` is (F, Hp, Wp); `mul` and `add` are C values each, kept in f32. y holds at least the + * patches' rows; rows past them are not written. */ +int ref_patch_fold(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *geom = &a->t[1], *y = &a->t[2]; + const int64_t C = p_int(a, "C", 0), pt = p_int(a, "pt", 0); + const int64_t ph = p_int(a, "ph", 0), pw = p_int(a, "pw", 0); + std::vector mul, add; + if (C <= 0 || pt <= 0 || ph <= 0 || pw <= 0 || parse_f32_list(p_str(a, "mul", ""), &mul) != C || + parse_f32_list(p_str(a, "add", ""), &add) != C || numel(geom) < 3) + return RAD_E_SHAPE; + const int64_t F = ldi(geom, 0), Hp = ldi(geom, 1), Wp = ldi(geom, 2); + if (F <= 0 || Hp <= 0 || Wp <= 0) return RAD_E_SHAPE; + const int64_t vol = pt * ph * pw, Hv = Hp * ph, Wv = Wp * pw, K = C * vol, rows = F * Hp * Wp; + if (rows_of(y, K) < rows || rows_of(x, C) < F * pt * Hv * Wv) return RAD_E_SHAPE; + REF_PAR_FOR(rows * K) + for (int64_t r = 0; r < rows; ++r) { + const int64_t f = r / (Hp * Wp), i = (r / Wp) % Hp, j = r % Wp; + const int64_t yb = rowoff(y, r, K), ys = laststride(y), xs = laststride(x); + for (int64_t sub = 0; sub < vol; ++sub) { + const int64_t ta = sub / (ph * pw), tb = (sub / pw) % ph, td = sub % pw; + const int64_t vox = ((f * pt + ta) * Hv + i * ph + tb) * Wv + j * pw + td; + const int64_t xb = rowoff(x, vox, C); + for (int64_t c = 0; c < C; ++c) + stt(y, yb + (c * vol + sub) * ys, + ldt(x, xb + c * xs) * mul[(size_t)c] + add[(size_t)c]); + } + } + return RAD_OK; +} + /* ------------------------------------------------------------------ grid_pos3 */ /* A video decoder's rotary positions over consecutive tiles: row m is token k = m % period of its * tile, the tile's T x H x W tokens first ((t, i, j) row-major) and the period's remaining rows @@ -298,3 +339,264 @@ int ref_vtile_stitch(const RadArgs* a, RadStream) { } return RAD_OK; } + +/* ================================================================== the latent upscaler + * A 3-D convolutional network over a video latent's voxel rows: row (t, i, j) of a T x H x W + * volume is (t H + i) W + j, channels innermost (NDHWC), every operand at its own row pitch. + * `geom` carries the request's volume; an output holds at least the rows the volume writes. */ + +/* ------------------------------------------------------------------ conv3d_ndhwc */ +/* A 3-D convolution, stride 1 with `same` zero padding: kt / 2 frames and k / 2 rows and columns + * on each side (kt and k odd). x [>= T H W, cin], y and `res` [>= T H W, cout], geom = (T, H, W); + * w is PyTorch's Conv3d weight [cout, cin, kt, k, k] and b [cout]: + * + * acc = sum over (dt, kh, kw, ci) of w[o, ci, dt, kh, kw] x[(t + dt - kt/2, i + kh - k/2, + * j + kw - k/2), ci] + * y[(t, i, j), o] = rd(acc + b[o]) rd(rd(acc + b[o]) + res) with `res` + * + * terms outside the volume zero. acc is f32, the taps in (dt, kh, kw) order and each tap's + * channels ascending; rd is y's dtype. With `res` the convolution's output is rounded before the + * residual is added, as a residual block's skip(x) + h adds two bf16 tensors. `res` may be y + * itself: each output element reads its own residual before its write, and no other. */ +int ref_conv3d_ndhwc(const RadArgs* a, RadStream) { + if (a->n_t < 6 || !have(a, 4) || !t_in(a, 5)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *w = &a->t[1], *b = &a->t[2], *geom = &a->t[3]; + const RadTensor *res = t_in(a, 4), *y = &a->t[5]; + const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0); + const int64_t k = p_int(a, "k", 0), kt = p_int(a, "kt", 0); + if (cin <= 0 || cout <= 0 || k <= 0 || kt <= 0 || !(k & 1) || !(kt & 1) || numel(geom) < 3) + return RAD_E_SHAPE; + const int64_t T = ldi(geom, 0), H = ldi(geom, 1), W = ldi(geom, 2); + if (T <= 0 || H <= 0 || W <= 0) return RAD_E_SHAPE; + const int64_t rows = T * H * W, taps = kt * k * k; + if (rows_of(y, cout) < rows || rows_of(x, cin) < rows || (res && rows_of(res, cout) < rows) || + numel(w) < cout * cin * taps || numel(b) < cout) + return RAD_E_SHAPE; + const int64_t pz = kt / 2, ps = k / 2, xs = laststride(x), ys = laststride(y); + const int64_t rs = res ? laststride(res) : 0; + const uint32_t dt = y->dtype; + REF_PAR_FOR(rows * cout * cin * taps) + for (int64_t r = 0; r < rows; ++r) { + const int64_t t = r / (H * W), i = (r / W) % H, j = r % W; + const int64_t yb = rowoff(y, r, cout), rb = res ? rowoff(res, r, cout) : 0; + for (int64_t o = 0; o < cout; ++o) { + float acc = 0.0f; + for (int64_t dz = 0; dz < kt; ++dz) { + const int64_t tz = t + dz - pz; + if (tz < 0 || tz >= T) continue; + for (int64_t kh = 0; kh < k; ++kh) { + const int64_t iy = i + kh - ps; + if (iy < 0 || iy >= H) continue; + for (int64_t kw = 0; kw < k; ++kw) { + const int64_t ix = j + kw - ps; + if (ix < 0 || ix >= W) continue; + const int64_t xb = rowoff(x, (tz * H + iy) * W + ix, cin); + const int64_t wb = o * cin * taps + (dz * k + kh) * k + kw; + for (int64_t ci = 0; ci < cin; ++ci) + acc += ldt(w, wb + ci * taps) * ldt(x, xb + ci * xs); + } + } + } + const float v = acc + ldt(b, o); + stt(y, yb + o * ys, res ? round_dt(dt, v) + ldt(res, rb + o * rs) : v); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ group_norm */ +/* PyTorch's nn.GroupNorm(groups, n) over [1, n, rows]: group g is channels + * [g n / groups, (g + 1) n / groups) of every row, rows being y's. Its mean and biased variance + * are over the group's rows n / groups values, summed in f64 in row-major order (two passes, the + * variance about the f64 mean); then, in f32, + * + * mean_g = f32(mean) rstd_g = 1 / sqrt(f32(var) + eps) + * v = (x - mean_g) rstd_g w[c] + b[c] each product and sum one f32 rounding + * v = v (1 + scale[c]) + shift[c] with `mod`, one row [scale | shift] of 2n + * v = v / (1 + exp(-v)) with `act` silu + * + * and v is rounded once into y. stats[2g] and stats[2g + 1] receive mean_g and rstd_g; `stats` + * must hold groups (2 + 3 1024) values, the rest being a device kernel's scratch (partial sums of + * up to 1024 parts a group), which this implementation does not touch. y may be x: the statistics + * are complete before any row is written, and each element is read before its own write. */ +int ref_group_norm(const RadArgs* a, RadStream) { + if (a->n_t < 6 || !have(a, 3) || !t_in(a, 4) || !t_in(a, 5)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *w = &a->t[1], *b = &a->t[2], *mod = t_in(a, 3); + const RadTensor *st = &a->t[4], *y = &a->t[5]; + const int64_t n = p_int(a, "n", 0), G = p_int(a, "groups", 0); + const float eps = p_f32(a, "eps", 1e-5f); + static const char* const kActs[] = { "none", "silu" }; + const int act = p_enum(a, "act", kActs, 2, 0); + if (act < 0 || act > 1) return RAD_E_INVAL; + if (n <= 0 || G <= 0 || n % G || numel(w) < n || numel(b) < n || + (mod && numel(mod) < 2 * n) || numel(st) < G * (2 + 3 * 1024)) + return RAD_E_SHAPE; + const int64_t rows = rows_of(y, n), cg = n / G; + if (rows <= 0 || rows_of(x, n) < rows) return RAD_E_SHAPE; + const int64_t xs = laststride(x), ys = laststride(y); + const double cnt = (double)rows * (double)cg; + std::vector mean((size_t)G), rstd((size_t)G); + REF_PAR_FOR(rows * n * 2) + for (int64_t g = 0; g < G; ++g) { + double s = 0.0; + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(x, r, n) + g * cg * xs; + for (int64_t c = 0; c < cg; ++c) s += (double)ldt(x, xb + c * xs); + } + const double mu = s / cnt; + double q = 0.0; + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(x, r, n) + g * cg * xs; + for (int64_t c = 0; c < cg; ++c) { + const double d = (double)ldt(x, xb + c * xs) - mu; + q += d * d; + } + } + mean[(size_t)g] = (float)mu; + rstd[(size_t)g] = 1.0f / std::sqrt((float)(q / cnt) + eps); + } + for (int64_t g = 0; g < G; ++g) { + stt(st, offlin(st, 2 * g), mean[(size_t)g]); + stt(st, offlin(st, 2 * g + 1), rstd[(size_t)g]); + } + REF_PAR_FOR(rows * n * 4) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(x, r, n), yb = rowoff(y, r, n); + for (int64_t c = 0; c < n; ++c) { + const size_t g = (size_t)(c / cg); + float v = (ldt(x, xb + c * xs) - mean[g]) * rstd[g]; + v = v * ldt(w, c) + ldt(b, c); + if (mod) { + const float sc = 1.0f + ldt(mod, offlin(mod, c)); + v = v * sc + ldt(mod, offlin(mod, n + c)); + } + if (act) v = v / (1.0f + ref_exp(-v)); + stt(y, yb + c * ys, v); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ tconv_dw */ +/* A depthwise convolution along a volume's frames (a Conv3d of kernel (k, 1, 1), padding k / 2 + * frames, one group a channel): geom = (T, H, W), P = H W rows a frame, x and y [>= T P, n], w + * PyTorch's [n, 1, k, 1, 1] (tap j of channel c at c k + j) and b [n], k odd: + * + * y[(t, p), c] = rd(f32(sum_j w[c, j] x[(t + j - k/2, p), c]) + b[c]) + * + * frames outside [0, T) zero, the sum f32 in ascending j. */ +int ref_tconv_dw(const RadArgs* a, RadStream) { + if (!have(a, 5)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *w = &a->t[1], *b = &a->t[2], *geom = &a->t[3], *y = &a->t[4]; + const int64_t n = p_int(a, "n", 0), k = p_int(a, "k", 0); + if (n <= 0 || k <= 0 || !(k & 1) || numel(geom) < 3 || numel(w) < n * k || numel(b) < n) + return RAD_E_SHAPE; + const int64_t T = ldi(geom, 0), H = ldi(geom, 1), W = ldi(geom, 2); + if (T <= 0 || H <= 0 || W <= 0) return RAD_E_SHAPE; + const int64_t P = H * W, rows = T * P; + if (rows_of(y, n) < rows || rows_of(x, n) < rows) return RAD_E_SHAPE; + const int64_t xs = laststride(x), ys = laststride(y); + REF_PAR_FOR(rows * n * k) + for (int64_t r = 0; r < rows; ++r) { + const int64_t t = r / P, p = r % P, yb = rowoff(y, r, n); + for (int64_t c = 0; c < n; ++c) { + float acc = 0.0f; + for (int64_t j = 0; j < k; ++j) { + const int64_t tz = t + j - k / 2; + if (tz < 0 || tz >= T) continue; + acc += ldt(w, c * k + j) * ldt(x, rowoff(x, tz * P + p, n) + c * xs); + } + stt(y, yb + c * ys, acc + ldt(b, c)); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ resize_bilinear */ +/* Each frame of a volume resized on its own (the frame axis kept), as torch's + * upsample_bilinear2d computes align_corners=False for an output size (not a scale factor): + * geom = (T, h, w, H, W), x [>= T h w, n] and y [>= T H W, n]. For output row i of H, in f32, + * + * sh = h / H src = max(sh (i + 0.5) - 0.5, 0) i0 = floor(src) i1 = i0 + (i0 < h - 1) + * l1 = src - i0 l0 = 1 - l1 + * + * and likewise for column j of W against w; then, every product and sum one f32 rounding and the + * result rounded once into y, + * + * v = l0y (l0x x[i0, j0] + l1x x[i0, j1]) + l1y (l0x x[i1, j0] + l1x x[i1, j1]) + * + * MiniMax-H3's upscaler resizes trilinearly at an unchanged frame count, whose temporal weights + * are exactly 1 and 0, so this is that resize. Any sizes, shrinking included. */ +int ref_resize_bilinear(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *geom = &a->t[1], *y = &a->t[2]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0 || numel(geom) < 5) return RAD_E_SHAPE; + const int64_t T = ldi(geom, 0), h = ldi(geom, 1), w = ldi(geom, 2); + const int64_t H = ldi(geom, 3), W = ldi(geom, 4); + if (T <= 0 || h <= 0 || w <= 0 || H <= 0 || W <= 0) return RAD_E_SHAPE; + const int64_t rows = T * H * W; + if (rows_of(y, n) < rows || rows_of(x, n) < T * h * w) return RAD_E_SHAPE; + /* Output index `o` of an axis resized from `in` to `out`: its two source indices and + * weights. */ + auto axis = [](int64_t o, int64_t in, int64_t out, int64_t* i0, int64_t* i1, float* l0, + float* l1) { + const float s = (float)in / (float)out; + float src = s * ((float)o + 0.5f) - 0.5f; + if (src < 0.0f) src = 0.0f; + *i0 = (int64_t)src; + *i1 = *i0 + (*i0 < in - 1 ? 1 : 0); + *l1 = src - (float)*i0; + *l0 = 1.0f - *l1; + }; + const int64_t xs = laststride(x), ys = laststride(y); + REF_PAR_FOR(rows * n * 8) + for (int64_t r = 0; r < rows; ++r) { + const int64_t t = r / (H * W), i = (r / W) % H, j = r % W; + int64_t i0, i1, j0, j1; + float l0y, l1y, l0x, l1x; + axis(i, h, H, &i0, &i1, &l0y, &l1y); + axis(j, w, W, &j0, &j1, &l0x, &l1x); + const int64_t b00 = rowoff(x, (t * h + i0) * w + j0, n); + const int64_t b01 = rowoff(x, (t * h + i0) * w + j1, n); + const int64_t b10 = rowoff(x, (t * h + i1) * w + j0, n); + const int64_t b11 = rowoff(x, (t * h + i1) * w + j1, n); + const int64_t yb = rowoff(y, r, n); + for (int64_t c = 0; c < n; ++c) { + const float top = l0x * ldt(x, b00 + c * xs) + l1x * ldt(x, b01 + c * xs); + const float bot = l0x * ldt(x, b10 + c * xs) + l1x * ldt(x, b11 + c * xs); + stt(y, yb + c * ys, l0y * top + l1y * bot); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ flow_renoise */ +/* A clean latent taken back to noise level s with a fresh stream, as a sampler restarts from an + * upscaled latent: over x's rows, in f32, + * + * x[k, c] = f32(f32(f32(1 - s) x[k, c]) + f32(s z(k n + c))) + * + * z(e) = rad_philox_normal_s(seed, stream, e) (abi/rad_philox.h), `seed` two u32 words low first, + * `stream` the parameter, s = sigma (one f32 value). x is stored at its own dtype (f32 in + * MiniMax-H3) and row pitch. */ +int ref_flow_renoise(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *sg = &a->t[0], *seed = &a->t[1], *x = &a->t[2]; + const int64_t n = p_int(a, "n", 0), stream = p_int(a, "stream", 0); + if (n <= 0 || stream < 0 || numel(sg) < 1 || numel(seed) < 2) return RAD_E_SHAPE; + const int64_t rows = rows_of(x, n); + if (rows <= 0) return RAD_E_SHAPE; + const float s = ldt(sg, offlin(sg, 0)), oms = 1.0f - s; + const uint64_t sd = (uint64_t)(uint32_t)ldi(seed, 0) | ((uint64_t)(uint32_t)ldi(seed, 1) << 32); + const int64_t xs = laststride(x); + REF_PAR_FOR(rows * n * 8) + for (int64_t k = 0; k < rows; ++k) { + const int64_t xb = rowoff(x, k, n); + for (int64_t c = 0; c < n; ++c) { + const float z = rad_philox_normal_s(sd, (uint64_t)stream, (uint64_t)(k * n + c)); + stt(x, xb + c * xs, oms * ldt(x, xb + c * xs) + s * z); + } + } + return RAD_OK; +} diff --git a/tests/abi_layout_rows.h b/tests/abi_layout_rows.h index fd992bc1..26fac72c 100644 --- a/tests/abi_layout_rows.h +++ b/tests/abi_layout_rows.h @@ -611,6 +611,8 @@ ABI_FIELD(RadVideoGenBatch, n_chunks) ABI_FIELD(RadVideoGenBatch, dec_rows) ABI_FIELD(RadVideoGenBatch, n_frames_out) ABI_FIELD(RadVideoGenBatch, n_samples) +ABI_FIELD(RadVideoGenBatch, geom_from) +ABI_FIELD(RadVideoGenBatch, upscale) ABI_STRUCT(RadVideoGenDecl) ABI_FIELD(RadVideoGenDecl, name) ABI_FIELD(RadVideoGenDecl, tmpl) @@ -647,6 +649,8 @@ ABI_FIELD(RadVideoGenDecl, frames_out) ABI_FIELD(RadVideoGenDecl, audio_out) ABI_FIELD(RadVideoGenDecl, n_rungs) ABI_FIELD(RadVideoGenDecl, rungs) +ABI_FIELD(RadVideoGenDecl, upscale_max) +ABI_FIELD(RadVideoGenDecl, upscale_refine) ABI_STRUCT(RadVideoGeom) ABI_FIELD(RadVideoGeom, n_text) ABI_FIELD(RadVideoGeom, frames) diff --git a/tests/abi_layout_table.h b/tests/abi_layout_table.h index c945536b..1217e181 100644 --- a/tests/abi_layout_table.h +++ b/tests/abi_layout_table.h @@ -588,7 +588,7 @@ { "RadTunable", "n_values", 16, 4 }, { "RadTunable", "deflt", 24, 8 }, { "RadTunable", "doc", 32, 8 }, -{ "RadVideoGenBatch", "", 0, 160 }, +{ "RadVideoGenBatch", "", 0, 192 }, { "RadVideoGenBatch", "lane", 0, 4 }, { "RadVideoGenBatch", "geom", 4, 24 }, { "RadVideoGenBatch", "geom_d", 32, 8 }, @@ -608,7 +608,9 @@ { "RadVideoGenBatch", "dec_rows", 136, 8 }, { "RadVideoGenBatch", "n_frames_out", 144, 4 }, { "RadVideoGenBatch", "n_samples", 152, 8 }, -{ "RadVideoGenDecl", "", 0, 272 }, +{ "RadVideoGenBatch", "geom_from", 160, 24 }, +{ "RadVideoGenBatch", "upscale", 184, 8 }, +{ "RadVideoGenDecl", "", 0, 288 }, { "RadVideoGenDecl", "name", 0, 8 }, { "RadVideoGenDecl", "tmpl", 8, 8 }, { "RadVideoGenDecl", "max_text", 16, 8 }, @@ -644,6 +646,8 @@ { "RadVideoGenDecl", "audio_out", 252, 4 }, { "RadVideoGenDecl", "n_rungs", 256, 4 }, { "RadVideoGenDecl", "rungs", 264, 8 }, +{ "RadVideoGenDecl", "upscale_max", 272, 8 }, +{ "RadVideoGenDecl", "upscale_refine", 280, 4 }, { "RadVideoGeom", "", 0, 24 }, { "RadVideoGeom", "n_text", 0, 4 }, { "RadVideoGeom", "frames", 4, 4 }, diff --git a/tests/abi_layout_test.cpp b/tests/abi_layout_test.cpp index 0a8be4e2..eae119e5 100644 --- a/tests/abi_layout_test.cpp +++ b/tests/abi_layout_test.cpp @@ -8,7 +8,7 @@ * * Checked: a C translation unit (abi_c_test.c, strict C11) lays every struct out as C++ does; every * struct's listed fields account for its size, so the list in abi_layout_rows.h is complete; and - * the layout agrees with the table below, taken at RAD_ABI_VERSION 21 and RAD_FORMAT_VER 2. Under + * the layout agrees with the table below, taken at RAD_ABI_VERSION 22 and RAD_FORMAT_VER 2. Under * those versions a listed field may not move or change size, an ABI struct may only grow by fields * past its old end, and an on-disk struct may not change at all. The table is a snapshot of the * headers: nothing else states the layout. When it disagrees the test prints the live table. @@ -57,8 +57,8 @@ std::vector cpp_rows() { }; } -/* The layout at RAD_ABI_VERSION 21 / RAD_FORMAT_VER 2 (see the file header). */ -constexpr uint32_t kTableAbi = 21, kTableFormat = 2; +/* The layout at RAD_ABI_VERSION 22 / RAD_FORMAT_VER 2 (see the file header). */ +constexpr uint32_t kTableAbi = 22, kTableFormat = 2; const AbiRow kTable[] = { #include "abi_layout_table.h" }; diff --git a/tests/convert_test.cpp b/tests/convert_test.cpp index db94cbf7..883ba7df 100644 --- a/tests/convert_test.cpp +++ b/tests/convert_test.cpp @@ -14,6 +14,7 @@ #include +#include #include using namespace rad; @@ -360,6 +361,41 @@ TEST(in_place_keeps_every_weight_where_it_was_and_can_be_undone) { CHECK(file == tiny::read_text(w.base)); } +/* A weight the container holds in another movement group than the plugin now declares (a plugin + * that regrouped it after the conversion) is kept in place, its entry taking the declared group: + * the group places no bytes of a dense weight. */ +TEST(in_place_keeps_a_weight_the_plugin_has_regrouped) { + World& w = world(); + REQUIRE(w.ok); + tiny::TempDir d("convert_ipg"); + const std::string ip = d / "ip.rad"; + REQUIRE(copy_file(w.base, ip)); + RadFile a; + REQUIRE_EQ(a.open(w.base.c_str()), RAD_OK); + REQUIRE(a.entry_count() > 0); + const RadFileEntry& e0 = a.entry(0); + REQUIRE(e0.expert < 0); + const std::string name = a.str(e0.name); + const int32_t layer = e0.layer; + const uint64_t off = e0.offset; + { + std::string file = tiny::read_text(ip); + const size_t at = (size_t)a.header().dir_off + offsetof(RadFileEntry, layer); + const int32_t other = layer + 7; + std::memcpy(&file[at], &other, sizeof other); + REQUIRE(tiny::write_text(ip, file)); + } + a.close(); + std::string log; + REQUIRE_EQ(convert(w.ckpt, { "--recipe", w.recipe, "--reuse", ip, "--in-place" }, &log), 0); + RadFile b; + REQUIRE_EQ(b.open(ip.c_str()), RAD_OK); + const RadFileEntry* e = b.find(name.c_str()); + REQUIRE(e != nullptr); + CHECK_EQ(e->layer, layer); + CHECK_EQ(e->offset, off); +} + /* In place, a weight cannot be replaced: a rule that would write one differently is refused and * the file is left as it was. Without --in-place, -o may not name the --reuse container, whose * weights the run reads while it truncates the output. */ diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index dc5c466c..6c654797 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -309,6 +309,10 @@ TEST(op_vocabulary) { /* Its step-distilled form's video sparse attention: the tile selection and the * block-sparse attention over it. */ "vsa_select", "attn_vsa", + /* Its latent upscaler: the 3-D and temporal convolutions, the group norm, the resize, + * the fold back into patch rows and the re-noising. */ + "conv3d_ndhwc", "group_norm", "tconv_dw", "resize_bilinear", "patch_fold", + "flow_renoise", }; for (const char* op : kOps) { if (!kern(op)) fprintf(stderr, " missing op '%s'\n", op); @@ -5441,6 +5445,277 @@ TEST(grid_pos3_places_each_tile_token_and_zeroes_the_rest) { CHECK_EQ(at3(2, 29), 1.5f); } +/* ================================================================== the latent upscaler + * docs/OPS.md "The latent upscaler": voxel rows (t, i, j) of a T x H x W volume, channels + * innermost, the volume in `geom`. */ + +/* conv3d_ndhwc's `same` padding: an all-ones 3 x 3 x 3 kernel over a 3 x 3 x 3 volume of ones + * counts each voxel's in-volume neighbours, 2 on an axis at an edge and 3 inside, plus the bias: + * a corner 8.5, the centre 27.5, a face's middle 18.5, an edge's middle 12.5. Refused: an even + * kernel, and y short of the volume's rows. */ +TEST(conv3d_ndhwc_pads_each_axis_with_zeros) { + T x(RAD_F32, {27, 1}); x.f(std::vector(27, 1.0f)); + T w(RAD_F32, {1, 1, 3, 3, 3}); w.f(std::vector(27, 1.0f)); + T b(RAD_F32, {1}); b.f({0.5f}); + T geom(RAD_I32, {3}); geom.n({3, 3, 3}); + T y(RAD_F32, {27, 1}); + A a; a.t(x).t(w).t(b).t(geom).tnull().t(y).i("M", 27).i("cin", 1).i("cout", 1).i("k", 3) + .i("kt", 3).s("dtype", "f32"); + CHECK_OK(run("conv3d_ndhwc", a)); + CHECK_EQ(y.at(0), 8.5f); /* (0, 0, 0) */ + CHECK_EQ(y.at(13), 27.5f); /* (1, 1, 1) */ + CHECK_EQ(y.at(4), 18.5f); /* (0, 1, 1): the first frame's centre */ + CHECK_EQ(y.at(10), 18.5f); /* (1, 0, 1): the middle frame's top edge */ + CHECK_EQ(y.at(1), 12.5f); /* (0, 0, 1) */ + CHECK_EQ(y.at(26), 8.5f); /* (2, 2, 2) */ + + A e; e.t(x).t(w).t(b).t(geom).tnull().t(y).i("M", 27).i("cin", 1).i("cout", 1).i("k", 2) + .i("kt", 3).s("dtype", "f32"); + CHECK_EQ(run("conv3d_ndhwc", e), RAD_E_SHAPE); + T y2(RAD_F32, {26, 1}); + A s; s.t(x).t(w).t(b).t(geom).tnull().t(y2).i("M", 26).i("cin", 1).i("cout", 1).i("k", 3) + .i("kt", 3).s("dtype", "f32"); + CHECK_EQ(run("conv3d_ndhwc", s), RAD_E_SHAPE); +} + +/* The weight is PyTorch's [cout, cin, kt, k, k] and tap (dt, kh, kw) reads voxel + * (t + dt - 1, i + kh - 1, j + kw - 1). Two frames of 1 x 3, two channels holding r + 1 at row r; + * only w[1, 0, 2, 1, 0] = 1 (frame t + 1, column j - 1) and w[1, 1, 0, 1, 2] = 10 (frame t - 1, + * column j + 1) are set, so output channel 1 at (t, 0, j) is x[(t + 1, j - 1), 0] + + * 10 x[(t - 1, j + 1), 1] + b[1] and channel 0 is its bias. */ +TEST(conv3d_ndhwc_reads_the_weight_as_pytorch_lays_it_out) { + T x(RAD_F32, {6, 2}); x.f({1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6}); + std::vector wv(2 * 2 * 27, 0.0f); + wv[75] = 1.0f; /* ((1 * 2 + 0) * 3 + 2) * 9 + 1 * 3 + 0 */ + wv[86] = 10.0f; /* ((1 * 2 + 1) * 3 + 0) * 9 + 1 * 3 + 2 */ + T w(RAD_F32, {2, 2, 3, 3, 3}); w.f(wv); + T b(RAD_F32, {2}); b.f({0.5f, -1.0f}); + T geom(RAD_I32, {3}); geom.n({2, 1, 3}); + T y(RAD_F32, {6, 2}); + A a; a.t(x).t(w).t(b).t(geom).tnull().t(y).i("M", 6).i("cin", 2).i("cout", 2).i("k", 3) + .i("kt", 3).s("dtype", "f32"); + CHECK_OK(run("conv3d_ndhwc", a)); + const float want[6] = { -1, 3, 4, 19, 29, -1 }; + for (int r = 0; r < 6; ++r) { + CHECK_EQ(y.at(2 * r), 0.5f); + CHECK_EQ(y.at(2 * r + 1), want[r]); + } +} + +/* With `res`, y = bf16(bf16(acc + b) + res): 1 + 0.0087890625 rounds to 1.0078125 first, and + * 1.0078125 + 2 = 3.0078125 is a tie that goes to 3, where the unrounded sum 3.0087890625 would + * give 3.015625. -1 + 0.0087890625 rounds to -0.9921875, plus 0.5 is -0.4921875. The residual may + * be y itself, and adds in place. */ +TEST(conv3d_ndhwc_rounds_the_conv_before_the_residual_in_place) { + T x(RAD_BF16, {2, 1}); x.f({1.0f, -1.0f}); + T w(RAD_BF16, {1, 1, 1, 1, 1}); w.f({1.0f}); + T b(RAD_F32, {1}); b.f({0.0087890625f}); + T geom(RAD_I32, {3}); geom.n({1, 1, 2}); + T y(RAD_BF16, {2, 1}); y.f({2.0f, 0.5f}); + A a; a.t(x).t(w).t(b).t(geom).t(y).t(y).i("M", 2).i("cin", 1).i("cout", 1).i("k", 1) + .i("kt", 1).s("dtype", "bf16"); + CHECK_OK(run("conv3d_ndhwc", a)); + CHECK_EQ(y.at(0), 3.0f); + CHECK_EQ(y.at(1), -0.4921875f); + + T res(RAD_BF16, {2, 1}); res.f({2.0f, 0.5f}); + T y2(RAD_BF16, {2, 1}); + A c; c.t(x).t(w).t(b).t(geom).t(res).t(y2).i("M", 2).i("cin", 1).i("cout", 1).i("k", 1) + .i("kt", 1).s("dtype", "bf16"); + CHECK_OK(run("conv3d_ndhwc", c)); + CHECK(y2.mem == y.mem); + /* Without a residual, the one rounding: 1.0078125. */ + A d; d.t(x).t(w).t(b).t(geom).tnull().t(y2).i("M", 2).i("cin", 1).i("cout", 1).i("k", 1) + .i("kt", 1).s("dtype", "bf16"); + CHECK_OK(run("conv3d_ndhwc", d)); + CHECK_EQ(y2.at(0), 1.0078125f); +} + +/* group_norm's statistics are over every row of a group's channels. Two rows of four channels in + * two groups: group 0 (channels 0 and 1) holds 1, 1, 3, 3, so mean 2 and var 1 (a per-row mean + * would make row 0 constant); group 1 holds 8, 12, 12, 8, mean 10 and var 4, rstd 0.5 (eps 0). + * Normalised, row 0 is (-1, -1, -1, 1) and row 1 (1, 1, 1, -1); times w (1, 2, 3, 4) plus + * b (0, 0.5, -1, 0). stats gets (2, 1, 10, 0.5) and the rest of it is not written. */ +TEST(group_norm_takes_each_group_over_all_rows) { + T x(RAD_F32, {2, 4}); x.f({1, 1, 8, 12, 3, 3, 12, 8}); + T w(RAD_F32, {4}); w.f({1, 2, 3, 4}); + T b(RAD_F32, {4}); b.f({0, 0.5f, -1, 0}); + T st(RAD_F32, {2 * (2 + 3 * 1024)}); st.f(std::vector(2 * (2 + 3 * 1024), -7.0f)); + T y(RAD_F32, {2, 4}); + A a; a.t(x).t(w).t(b).tnull().t(st).t(y).i("M", 2).i("n", 4).i("groups", 2).d("eps", 0.0) + .s("act", "none").s("dtype", "f32"); + CHECK_OK(run("group_norm", a)); + const float want[8] = { -1, -1.5f, -4, 4, 1, 2.5f, 2, -4 }; + for (int i = 0; i < 8; ++i) CHECK_EQ(y.at(i), want[i]); + CHECK_EQ(st.at(0), 2.0f); CHECK_EQ(st.at(1), 1.0f); + CHECK_EQ(st.at(2), 10.0f); CHECK_EQ(st.at(3), 0.5f); + CHECK_EQ(st.at(4), -7.0f); CHECK_EQ(st.at(2 * (2 + 3 * 1024) - 1), -7.0f); + + /* Modulated by one row [scale | shift], then silu, in place: v (1 + scale) + shift is + * (-2, -0.5, -2, 4.25) and (2, 3.5, 1, -3.75), and silu(v) = v / (1 + e^-v). */ + T mod(RAD_F32, {8}); mod.f({1, 0, -0.5f, 0, 0, 1, 0, 0.25f}); + A m; m.t(x).t(w).t(b).t(mod).t(st).t(x).i("M", 2).i("n", 4).i("groups", 2).d("eps", 0.0) + .s("act", "silu").s("dtype", "f32"); + CHECK_OK(run("group_norm", m)); + const double v[8] = { -2, -0.5, -2, 4.25, 2, 3.5, 1, -3.75 }; + for (int i = 0; i < 8; ++i) CHECK_NEAR(x.at(i), v[i] / (1.0 + std::exp(-v[i])), 1e-5); + + /* Refused: a stats short of groups (2 + 3 1024), groups not dividing n, an unknown act. */ + T sm(RAD_F32, {2 * (2 + 3 * 1024) - 1}); + A r1; r1.t(x).t(w).t(b).tnull().t(sm).t(y).i("M", 2).i("n", 4).i("groups", 2).d("eps", 0.0) + .s("act", "none").s("dtype", "f32"); + CHECK_EQ(run("group_norm", r1), RAD_E_SHAPE); + A r2; r2.t(x).t(w).t(b).tnull().t(st).t(y).i("M", 2).i("n", 4).i("groups", 3).d("eps", 0.0) + .s("act", "none").s("dtype", "f32"); + CHECK_EQ(run("group_norm", r2), RAD_E_SHAPE); + A r3; r3.t(x).t(w).t(b).tnull().t(st).t(y).i("M", 2).i("n", 4).i("groups", 2).d("eps", 0.0) + .s("act", "gelu").s("dtype", "f32"); + CHECK_EQ(run("group_norm", r3), RAD_E_INVAL); +} + +/* The variance is taken about the mean, not as E[x^2] - mean^2: 4095 and 4097 have mean 4096 and + * var 1, where an f32 sum of squares (4 4096^2 + 4 = 67108868, 8 apart from its neighbours in + * f32) cancels to 0. */ +TEST(group_norm_keeps_a_small_variance_under_a_large_mean) { + T x(RAD_F32, {2, 2}); x.f({4095, 4097, 4097, 4095}); + T w(RAD_F32, {2}); w.f({1, 1}); + T b(RAD_F32, {2}); b.f({0, 0}); + T st(RAD_F32, {2 + 3 * 1024}); + T y(RAD_F32, {2, 2}); + A a; a.t(x).t(w).t(b).tnull().t(st).t(y).i("M", 2).i("n", 2).i("groups", 1).d("eps", 0.0) + .s("act", "none").s("dtype", "f32"); + CHECK_OK(run("group_norm", a)); + const float want[4] = { -1, 1, 1, -1 }; + for (int i = 0; i < 4; ++i) CHECK_EQ(y.at(i), want[i]); + CHECK_EQ(st.at(0), 4096.0f); CHECK_EQ(st.at(1), 1.0f); +} + +/* tconv_dw along the frames: three frames of two rows, channel 0's taps (1, 10, 100) on frames + * t - 1, t, t + 1 (w[c k + j]) over x = 1..6, channel 1's (0, 1, 0) over -(1..6); frames outside + * the volume are zero, and each row reads its own position in the other frames. */ +TEST(tconv_dw_convolves_each_position_across_frames) { + T x(RAD_F32, {6, 2}); x.f({1, -1, 2, -2, 3, -3, 4, -4, 5, -5, 6, -6}); + T w(RAD_F32, {2, 1, 3, 1, 1}); w.f({1, 10, 100, 0, 1, 0}); + T b(RAD_F32, {2}); b.f({0.5f, 2}); + T geom(RAD_I32, {3}); geom.n({3, 1, 2}); + T y(RAD_F32, {6, 2}); + A a; a.t(x).t(w).t(b).t(geom).t(y).i("M", 6).i("n", 2).i("k", 3).s("dtype", "f32"); + CHECK_OK(run("tconv_dw", a)); + const float c0[6] = { 310.5f, 420.5f, 531.5f, 642.5f, 53.5f, 64.5f }; + for (int r = 0; r < 6; ++r) { + CHECK_EQ(y.at(2 * r), c0[r]); + CHECK_EQ(y.at(2 * r + 1), (float)(1 - r)); + } +} + +/* resize_bilinear as torch's align_corners=False at a size: 2 x 2 to 4 x 4 gives the familiar + * [[1, 1.25, 1.75, 2], [1.5, 1.75, 2.25, 2.5], [2.5, 2.75, 3.25, 3.5], [3, 3.25, 3.75, 4]]. The + * first row's source clamps to 0; the last's is 1.25, whose neighbour is clamped to row 1, so it + * is row 1. Channel 1 holds the negatives. */ +TEST(resize_bilinear_matches_torch_and_clamps_at_the_border) { + T x(RAD_F32, {4, 2}); x.f({1, -1, 2, -2, 3, -3, 4, -4}); + T geom(RAD_I32, {5}); geom.n({1, 2, 2, 4, 4}); + T y(RAD_F32, {16, 2}); + A a; a.t(x).t(geom).t(y).i("M", 16).i("n", 2).s("dtype", "f32"); + CHECK_OK(run("resize_bilinear", a)); + const float want[16] = { 1, 1.25f, 1.75f, 2, 1.5f, 1.75f, 2.25f, 2.5f, + 2.5f, 2.75f, 3.25f, 3.5f, 3, 3.25f, 3.75f, 4 }; + for (int r = 0; r < 16; ++r) { + CHECK_EQ(y.at(2 * r), want[r]); + CHECK_EQ(y.at(2 * r + 1), -want[r]); + } +} + +/* Frames resize on their own, and shrinking averages: two frames of 4 x 1 to 2 x 1 read source + * rows 0.5 and 2.5. 3 to 5 at a ratio f32 cannot hold exactly: row 0's source clamps to 0, row + * 4's (2.2) has its neighbour clamped onto row 2, and rows 1 and 3 read 0.4 and 1.6. */ +TEST(resize_bilinear_resizes_each_frame_and_shrinks) { + T x(RAD_F32, {8, 1}); x.f({1, 2, 4, 8, 10, 20, 40, 80}); + T geom(RAD_I32, {5}); geom.n({2, 4, 1, 2, 1}); + T y(RAD_F32, {4, 1}); + A a; a.t(x).t(geom).t(y).i("M", 4).i("n", 1).s("dtype", "f32"); + CHECK_OK(run("resize_bilinear", a)); + CHECK_EQ(y.at(0), 1.5f); CHECK_EQ(y.at(1), 6.0f); + CHECK_EQ(y.at(2), 15.0f); CHECK_EQ(y.at(3), 60.0f); + + T x3(RAD_F32, {3, 1}); x3.f({0, 10, 20}); + T g3(RAD_I32, {5}); g3.n({1, 3, 1, 5, 1}); + T y5(RAD_F32, {5, 1}); + A c; c.t(x3).t(g3).t(y5).i("M", 5).i("n", 1).s("dtype", "f32"); + CHECK_OK(run("resize_bilinear", c)); + CHECK_EQ(y5.at(0), 0.0f); + CHECK_NEAR(y5.at(1), 4.0, 1e-5); + CHECK_NEAR(y5.at(3), 16.0, 1e-5); + CHECK_NEAR(y5.at(4), 20.0, 1e-5); +} + +/* patch_fold deals voxel rows (yy, xx) of x [8, 2] (x[r, c] = 10 r + c) into the 1 x 2 x 2 patches + * side by side (geom (1, 1, 2)): patch j's column c 4 + b 2 + d is voxel (b, 2 j + d), times mul + * plus add, f32. Row 2 is past the patches and keeps its value. */ +TEST(patch_fold_gathers_voxels_into_patches_and_normalises) { + std::vector xv(16); + for (int r = 0; r < 8; ++r) + for (int c = 0; c < 2; ++c) xv[(size_t)(r * 2 + c)] = (float)(10 * r + c); + T x(RAD_F32, {8, 2}); x.f(xv); + T geom(RAD_I32, {3}); geom.n({1, 1, 2}); + T y(RAD_F32, {3, 8}); y.f(std::vector(24, -9.0f)); + A a; a.t(x).t(geom).t(y).i("M", 3).i("C", 2).i("pt", 1).i("ph", 2).i("pw", 2) + .s("mul", "1 2").s("add", "0 0.5").s("dtype", "f32"); + CHECK_OK(run("patch_fold", a)); + const float want[16] = { 0, 10, 40, 50, 2.5f, 22.5f, 82.5f, 102.5f, + 20, 30, 60, 70, 42.5f, 62.5f, 122.5f, 142.5f }; + for (int i = 0; i < 16; ++i) CHECK_EQ(y.at(i), want[i]); + for (int i = 16; i < 24; ++i) CHECK_EQ(y.at(i), -9.0f); +} + +/* patch_fold undoes patch_unfold: two frames of 1 x 2 patches of 2 x 1 x 2 with three channels, + * unfolded through (x 2 + 1, x 4 - 2, x 0.5 + 3) and folded back through their inverses, exact + * in f32 at these integers. */ +TEST(patch_fold_inverts_patch_unfold) { + std::vector pv(4 * 12); + for (size_t i = 0; i < pv.size(); ++i) pv[i] = (float)((int)i * 7 % 23 - 11); + T p(RAD_F32, {4, 12}); p.f(pv); + T geom(RAD_I32, {3}); geom.n({2, 1, 2}); + T vox(RAD_F32, {16, 3}); + A u; u.t(p).t(geom).t(vox).i("M", 16).i("C", 3).i("pt", 2).i("ph", 1).i("pw", 2) + .s("mul", "2 4 0.5").s("add", "1 -2 3").s("dtype", "f32"); + CHECK_OK(run("patch_unfold", u)); + T back(RAD_F32, {4, 12}); + A f; f.t(vox).t(geom).t(back).i("M", 4).i("C", 3).i("pt", 2).i("ph", 1).i("pw", 2) + .s("mul", "0.5 0.25 2").s("add", "-0.5 0.5 -6").s("dtype", "f32"); + CHECK_OK(run("patch_fold", f)); + for (int i = 0; i < 48; ++i) CHECK_EQ(back.at(i), pv[(size_t)i]); +} + +/* flow_renoise: x = f32(f32(0.75 x) + f32(0.25 z(k n + c))) with z the (seed, 1) normal stream, + * indexed by the row's position k n + c, not its pitch: x is [2, 3] at a pitch of 5, whose last + * two columns are not written. Both products are exact here, so the expectation has one + * rounding. Stream 0 (rad_philox_normal) is a different draw. */ +TEST(flow_renoise_draws_its_own_stream_by_element) { + const uint64_t seed = 0x0123456789abcdefull; + T sg(RAD_F32, {1}); sg.f({0.25f}); + T sd(RAD_U32, {2}); sd.n({(int64_t)(seed & 0xffffffffu), (int64_t)(seed >> 32)}); + const float xv[6] = { 2, 4, -8, 6, 0, 10 }; + T x(RAD_F32, {2, 5}); + x.f({ xv[0], xv[1], xv[2], -9, -9, xv[3], xv[4], xv[5], -9, -9 }); + x.t.shape[1] = 3; + A a; a.t(sg).t(sd).t(x).i("M", 2).i("n", 3).i("stream", 1).s("dtype", "f32"); + CHECK_OK(run("flow_renoise", a)); + bool differs = false; + for (int k = 0; k < 2; ++k) { + for (int c = 0; c < 3; ++c) { + const uint64_t e = (uint64_t)(k * 3 + c); + const float z = rad_philox_normal_s(seed, 1, e); + const float want = 0.75f * xv[k * 3 + c] + 0.25f * z; + CHECK_EQ(x.at(k * 5 + c), want); + differs = differs || want != 0.75f * xv[k * 3 + c] + 0.25f * rad_philox_normal(seed, e); + } + CHECK_EQ(x.at(k * 5 + 3), -9.0f); + CHECK_EQ(x.at(k * 5 + 4), -9.0f); + } + CHECK(differs); +} + /* ================================================================== video sparse attention * docs/OPS.md "Video sparse attention": the tiles over a packed sequence of dense segments and a * video grid, vsa_select's top-k of pooled scores and its coarse branch, attn_vsa's block-sparse @@ -6798,6 +7073,15 @@ std::vector geometries() { G("attn_vsa", "M", 81, a.i("M", R).i("head_dim", 8).i("tile_t", 2).i("tile_h", 2) .i("tile_w", 2).i("patch", 1).d("sparsity", 0.9) .s("dtype", "f32")), + G("conv3d_ndhwc", "M", 27, a.i("M", R).i("cin", 3).i("cout", 5).i("k", 3).i("kt", 3) + .s("dtype", "f32")), + G("group_norm", "M", 4, a.i("M", R).i("n", 8).i("groups", 2).d("eps", 1e-5) + .s("act", "silu").s("dtype", "f32")), + G("tconv_dw", "M", 8, a.i("M", R).i("n", 8).i("k", 5).s("dtype", "f32")), + G("resize_bilinear", "M", 8, a.i("M", R).i("n", 8).s("dtype", "f32")), + G("patch_fold", "M", 8, a.i("M", R).i("C", 3).i("pt", 1).i("ph", 2).i("pw", 2) + .s("mul", "1 2 3").s("add", "0 1 2").s("dtype", "f32")), + G("flow_renoise", "M", 3, a.i("M", R).i("n", 8).i("stream", 1).s("dtype", "f32")), }; } #undef G diff --git a/tests/video_gen_test.cpp b/tests/video_gen_test.cpp index 138cb426..c1380d4e 100644 --- a/tests/video_gen_test.cpp +++ b/tests/video_gen_test.cpp @@ -110,6 +110,7 @@ char kind_of(int gen) { case RAD_GEN_PASS_VSTEP: return 'S'; case RAD_GEN_PASS_ADECODE: return 'A'; case RAD_GEN_PASS_VDECODE: return 'D'; + case RAD_GEN_PASS_VUPSCALE: return 'U'; default: return '?'; } } @@ -279,6 +280,133 @@ TEST(a_second_request_is_conditioned_early_and_denoised_after_the_first) { CHECK_EQ(kinds, std::string("CCSADSAD")); } +/* Latent upscaling's small size: each side over the factor, rounded half up to the size multiple, + * at least one multiple and at most the side. */ +TEST(the_small_size_is_each_side_over_the_factor_at_the_multiple) { + const RadVideoGenDecl d = decl_small(); + int32_t w = 0, h = 0; + gen::video_small_size(d, 1344, 768, 2.0, &w, &h); + CHECK_EQ(w, 672); + CHECK_EQ(h, 384); + gen::video_small_size(d, 1344, 768, 4.0, &w, &h); + CHECK_EQ(w, 352); /* 336 is 10.5 multiples, rounded up */ + CHECK_EQ(h, 192); + gen::video_small_size(d, 1280, 768, 4.0, &w, &h); + CHECK_EQ(w, 320); + CHECK_EQ(h, 192); + gen::video_small_size(d, 64, 32, 4.0, &w, &h); + CHECK_EQ(w, 32); /* never below one multiple */ + CHECK_EQ(h, 32); + gen::video_small_size(d, 64, 64, 1.2, &w, &h); + CHECK_EQ(w, 64); /* 1.67 multiples round back to the side */ + CHECK_EQ(h, 64); +} + +/* An upscaled request: its first evaluations at the small size, the last of them stepping to the + * clean estimate, then the upscale pass with both geometries, the factor and the first full-size + * step's sigmas, then the full-size steps and the decodes at the full size. */ +TEST(an_upscaled_request_runs_small_steps_then_the_upscale_then_full_steps) { + VideoFixture f; + f.build(); + f.prog.video_gen.upscale_max = 4.0; + f.prog.video_gen.upscale_refine = 1; + CHECK_OK(f.start()); + const gen::VideoSchedule sc = gen::video_schedule(f.prog.video_gen, 4); + REQUIRE_EQ(sc.steps, 3); + std::string why; + auto r = f.req(1, 4); + r->width = 64; + r->height = 64; + r->upscale = 2.0; + auto t = r->ticket; + CHECK_OK(f.drv.submit(std::move(r), &why)); + CHECK_EQ(t->small_width, 32); + CHECK_EQ(t->small_height, 32); + CHECK_EQ(t->refine, 1); + CHECK_EQ(t->steps, 3); + /* 3 frames: 2 latent frames, 30 soundtrack latents a channel. Small: 1 x 1 patches a frame; + * full: 2 x 2. */ + const int64_t small_rows = 3 + 60 + 2 * 1, full_rows = 3 + 60 + 2 * 4; + std::string kinds; + int steps_seen = 0; + for (int i = 0; i < 20; ++i) { + const RadBatch* b = f.drv.next(i); + if (!b) break; + const RadVideoGenBatch* V = b->vgen_b; + REQUIRE(V != nullptr); + kinds += kind_of(b->gen); + if (b->gen == RAD_GEN_PASS_VSTEP) { + const bool small = steps_seen < 2; + CHECK_EQ(b->n_tok, small ? small_rows : full_rows); + CHECK_EQ(V->geom.lat_h, small ? 2 : 4); + CHECK_EQ(V->geom.lat_w, small ? 2 : 4); + CHECK_EQ(V->geom_d[RAD_VGEOM_LAT_H], small ? 2 : 4); + CHECK_EQ(V->seg_cu[3], (int32_t)(small ? small_rows : full_rows)); + CHECK_EQ(V->sched[1], sc.sig_v[(size_t)steps_seen]); + /* The last small step lands on the clean estimate. */ + CHECK_EQ(V->sched[2], steps_seen == 1 ? 0.0f : sc.sig_v[(size_t)steps_seen + 1]); + CHECK_EQ(V->sched[5], steps_seen == 1 ? 0.0f : sc.sig_a[(size_t)steps_seen + 1]); + ++steps_seen; + } else if (b->gen == RAD_GEN_PASS_VUPSCALE) { + CHECK_EQ(b->n_tok, (int64_t)0); + CHECK_EQ(V->geom.lat_h, 4); + CHECK_EQ(V->geom_from.lat_h, 2); + CHECK_EQ(V->geom_from.lat_w, 2); + CHECK_EQ(V->upscale[0], 2.0f); + CHECK_EQ(V->sched[1], sc.sig_v[2]); + CHECK_EQ(V->sched[4], sc.sig_a[2]); + const int32_t* g = V->geom_d; + CHECK(std::vector(g + RAD_VGEOM_UP_SRC, g + RAD_VGEOM_UP_SRC + 14) == + std::vector({ 2, 2, 2, 4, 4, 2, 4, 4, 2, 1, 1, 2, 2, 2 })); + } else if (b->gen == RAD_GEN_PASS_VDECODE) { + CHECK_EQ(V->geom.lat_h, 4); + } + f.answer(0); + CHECK_OK(f.drv.done()); + } + CHECK_EQ(kinds, std::string("CSSUSAD")); + CHECK(t->t_small_ns > 0 && t->t_upscaled_ns >= t->t_small_ns); + CHECK_EQ(t->status(), (int)RAD_OK); +} + +/* Upscaling is refused when the model has none, past its largest factor, when the factor leaves + * the size as it is, and when the refinement leaves no small step or takes none. */ +TEST(an_upscale_that_cannot_run_is_refused_at_submit) { + VideoFixture f; + f.build(); + CHECK_OK(f.start()); + std::string why; + auto r = f.req(1, 4); + r->upscale = 2.0; + CHECK_EQ(f.drv.submit(std::move(r), &why), (int)RAD_E_INVAL); + CHECK(has(why, "no latent upscaler")); + + VideoFixture g; + g.build(); + g.prog.video_gen.upscale_max = 4.0; + g.prog.video_gen.upscale_refine = 1; + CHECK_OK(g.start()); + auto refused = [&](double factor, int32_t refine, const char* what) { + auto q = g.req(1, 4); + q->width = 64; + q->height = 64; + q->upscale = factor; + q->refine = refine; + why.clear(); + CHECK_EQ(g.drv.submit(std::move(q), &why), (int)RAD_E_INVAL); + CHECK(has(why, what)); + }; + refused(5.0, 0, "at most 4"); + refused(1.2, 0, "leaves 64x64"); + refused(2.0, 3, "1..2"); + auto ok = g.req(1, 4); + ok->width = 64; + ok->height = 64; + ok->upscale = 2.0; + ok->refine = 2; + CHECK_OK(g.drv.submit(std::move(ok), &why)); +} + /* What can never run is refused at submit: an empty or long prompt, a size off the multiple, * below the least side, over the area or the aspect, a length outside the chunks, steps outside * 2..max. */ diff --git a/tests/videos_test.cpp b/tests/videos_test.cpp index 5e6f1d4c..76ba6905 100644 --- a/tests/videos_test.cpp +++ b/tests/videos_test.cpp @@ -59,6 +59,11 @@ struct FakeVideoGen : IVideoGen { t.sample_rate = 32000; t.channels = 2; t.fps = 24.0; + if (r->upscale > 1.0) { + t.small_width = (int32_t)(r->width / r->upscale) / 32 * 32; + t.small_height = (int32_t)(r->height / r->upscale) / 32 * 32; + t.refine = r->refine > 0 ? r->refine : (int32_t)inf.upscale_refine; + } if (finish_status == RAD_OK) { for (int s = 1; s <= 2; ++s) { gen::VideoEvent e; @@ -204,6 +209,47 @@ TEST(the_generator_gets_the_size_the_chunks_and_the_steps) { v.wait(str_at(json::parse(r.body, nullptr, false), "id")); } +/* Latent upscaling: refused by a model without an upscaler; with one, the factor and the refine + * steps reach the generator, a factor of 1 is none, and the refine steps need a factor. */ +TEST(latent_upscale_reaches_the_generator_where_the_model_has_an_upscaler) { + Videos v; + CHECK_EQ(v.refused(Videos::body({ { "latent_upscale", 2 } })), std::string("latent_upscale")); + v.gen.inf.upscale_max = 4.0; + v.gen.inf.upscale_refine = 3; + CHECK_EQ(v.refused(Videos::body({ { "latent_upscale", 4.5 } })), std::string("latent_upscale")); + CHECK_EQ(v.refused(Videos::body({ { "latent_upscale", 0.5 } })), std::string("latent_upscale")); + CHECK_EQ(v.refused(Videos::body({ { "upscale_refine_steps", 2 } })), + std::string("upscale_refine_steps")); + CHECK_EQ(v.refused(Videos::body({ { "latent_upscale", 2 }, { "upscale_refine_steps", 1.5 } })), + std::string("upscale_refine_steps")); + HttpResponse r = v.create(Videos::body({ { "size", "512x512" }, { "latent_upscale", "2" }, + { "upscale_refine_steps", 4 } })); + REQUIRE_EQ(r.status, 200); + CHECK_EQ(v.gen.last().upscale, 2.0); + CHECK_EQ(v.gen.last().refine, 4); + /* The video object says how it was made, at creation and when it is fetched. */ + json o = json::parse(r.body, nullptr, false); + CHECK_EQ(o["latent_upscale"].get(), 2.0); + CHECK_EQ(o["upscale_refine_steps"].get(), 4); + CHECK_EQ(str_at(o, "upscale_from"), std::string("256x256")); + json done = v.wait(str_at(o, "id")); + CHECK_EQ(str_at(done, "upscale_from"), std::string("256x256")); + /* Without refine steps named, the generator's default is what the object reports. */ + r = v.create(Videos::body({ { "size", "512x512" }, { "latent_upscale", 2 } })); + REQUIRE_EQ(r.status, 200); + o = json::parse(r.body, nullptr, false); + CHECK_EQ(o["upscale_refine_steps"].get(), 3); + v.wait(str_at(o, "id")); + r = v.create(Videos::body({ { "latent_upscale", 1 } })); + REQUIRE_EQ(r.status, 200); + CHECK_EQ(v.gen.last().upscale, 0.0); + CHECK_EQ(v.gen.last().refine, 0); + o = json::parse(r.body, nullptr, false); + CHECK(!o.contains("latent_upscale") && !o.contains("upscale_refine_steps") && + !o.contains("upscale_from")); + v.wait(str_at(o, "id")); +} + /* A form is read as JSON's fields are (OpenAI's clients send the create call as one). */ TEST(a_form_creates_a_video_too) { Videos v; diff --git a/tools/rad_convert.cpp b/tools/rad_convert.cpp index ff63336a..b56b93ca 100644 --- a/tools/rad_convert.cpp +++ b/tools/rad_convert.cpp @@ -812,10 +812,15 @@ int main(int argc, char** argv) { ++n_changed; } if (re) { + /* The movement group is the declaration's either way (add_weight and add_existing + * record ww's), so a plugin that regroups a weight still reuses its planes; only an + * expert's layer, index and slot say where its planes sit in a stride table. */ + const bool expert = ww.expert >= 0 || re->expert >= 0; bool same = rad_enc_equal(&reuse.encoding(*re), &ww.enc) && ww.quantizer == reuse.str(re->quantizer) && ww.options == reuse.str(re->options) && re->rank == ww.rank && - re->layer == ww.layer && re->expert == ww.expert && re->slot == ww.slot; + (!expert || (re->layer == ww.layer && re->expert == ww.expert && + re->slot == ww.slot)); for (uint32_t i = 0; same && i < RAD_MAX_RANK; ++i) if (re->shape[i] != ww.shape[i]) same = false; if (in_place) {