From b068190326fbf1ff60b2316c43d144bdc0350552 Mon Sep 17 00:00:00 2001 From: Deadcode Date: Wed, 14 Oct 2026 14:03:59 +0200 Subject: [PATCH] radiance 1.6.0 - Qwen-Image 2.1 and 2.1 Turbo: text to image and image edits over OpenAI's images API, /v1/images/generations and /v1/images/edits. An edit takes up to ten pictures and an optional mask, outside which the picture comes back exactly as it was; `background: transparent`, png, jpeg and webp output, `n` pictures from one prompt, streamed previews (`partial_images`), and vLLM-Omni's seed, negative_prompt with true_cfg_scale, num_inference_steps, width and height. arch/qwenimage21 serves the diffusers pipeline directory, converted with data/recipes/qwen-image-2.1-fp8.recipe (block fp8) or qwen-image-2.1-bf16.recipe. deploy/compose/qwen-image-2.1.yaml and qwen-image-2.1-turbo.yaml serve the fp8 containers on two cards. Two R9700s make a 2048x2048 picture in 61 s at the base model's 40 steps and in 13 s with Turbo (56 and 12 s with --tp-wire wht6), a 1024x1024 one in 6.0 and 2.6 s. The models are under Qwen's research license, which is non-commercial - an image generator is a program kind of its own (core/gen): an architecture declares its conditioning, denoising and decoding passes, and the driver runs the schedule, the pictures of a batch and the conditioning cache. An image model's /v1/models entry is its generator's name (qwen-image-2.1, qwen-image-2.1-turbo), and its capabilities and startup banner list only the images endpoints - the tiled prefill GEMMs run their tiles in groups of activation bands, 16 for fp8 and 8 for bf16, so an operand larger than the 64 MB cache is read once a group instead of once a band. A bf16 GEMM with more than 64 MB of weight runs up to twice as fast - fixed: a second lane opened in the middle of a step started beside work lane 0 had not finished. Gemma 4 26B-A4B opens its lane that way, so its first step after startup could read rows not yet written - startup no longer warns about --checkpoint-slots when it was not passed, nor about an expert floor on a model with no experts - the image's FFmpeg writes png, jpeg and webp (libwebp) - for out-of-tree plugins: RAD_ABI_VERSION is 16. The op vocabulary gains the image generator's ops (conv2d_nhwc, ln_mod, ln_mod_quant_fp8, flow_euler, attn_prefix_self and others; docs/OPS.md, "Image generation"), and all_reduce takes an optional `overlap`. Plugins built against 1.5.0 must be rebuilt --- CMakeLists.txt | 2 +- Dockerfile | 20 +- README.md | 23 +- abi/rad_abi.h | 2 +- abi/rad_builder.h | 109 ++ abi/rad_philox.h | 49 + abi/rad_runtime.h | 87 ++ arch/common/rad_block_vit.h | 80 +- arch/qwenimage21/CMakeLists.txt | 11 + arch/qwenimage21/qwenimage21.cpp | 1567 ++++++++++++++++++++++ core/CMakeLists.txt | 2 +- core/build/rad_build.h | 1 + core/build/rad_builder.cpp | 114 ++ core/build/startup.cpp | 6 +- core/engine.cpp | 111 +- core/engine.h | 6 + core/engine_bringup.cpp | 49 +- core/engine_gen.cpp | 72 + core/format/checkpoint.cpp | 94 ++ core/format/checkpoint.h | 6 +- core/gen/driver.cpp | 916 +++++++++++++ core/gen/driver.h | 186 +++ core/gen/gen.cpp | 213 +++ core/gen/gen.h | 145 ++ core/mem/kv.cpp | 6 +- core/mem/vram_budget.cpp | 2 +- core/mm/imaging.cpp | 167 +++ core/mm/imaging.h | 25 + core/mm/media.cpp | 179 +++ core/mm/media.h | 17 + core/rad_core.h | 10 + core/runtime/ctx.cpp | 15 +- core/server/admin.cpp | 11 +- core/server/http.cpp | 23 +- core/server/http.h | 7 + core/server/iface.h | 31 + core/server/images.cpp | 731 ++++++++++ core/server/server.cpp | 33 +- core/server/server.h | 6 + data/recipes/qwen-image-2.1-bf16.recipe | 9 + data/recipes/qwen-image-2.1-fp8.recipe | 20 + deploy/compose/qwen-image-2.1-turbo.yaml | 13 + deploy/compose/qwen-image-2.1.yaml | 16 + docs/ARCHITECTURES.md | 56 + docs/DOCKER.md | 2 + docs/GUIDE.md | 76 +- docs/OPS.md | 94 +- libavx/avx_attn.cpp | 6 +- libavx/avx_check.cpp | 28 +- libavx/avx_registry.cpp | 3 +- libr4d/CMakeLists.txt | 5 + libr4d/r4d_attn_gen.hip | 770 +++++++++++ libr4d/r4d_encoder_bf16.hip | 70 +- libr4d/r4d_gemm_bf16_nt_tiled.hip | 13 +- libr4d/r4d_gemm_fp8a8.hip | 23 +- libr4d/r4d_gen.hip | 1049 +++++++++++++++ libr4d/r4d_layout.cpp | 77 ++ libr4d/r4d_plugin.h | 32 + libr4d/r4d_rows.cpp | 372 +++++ libref/ref_attn.cpp | 36 +- libref/ref_gen.cpp | 759 +++++++++++ libref/ref_ops.h | 37 + libref/ref_registry.cpp | 139 +- libref/ref_shapes.cpp | 273 ++++ tests/ref_test.cpp | 6 + tools/rad_convert.cpp | 4 +- 66 files changed, 9035 insertions(+), 87 deletions(-) create mode 100644 abi/rad_philox.h create mode 100644 arch/qwenimage21/CMakeLists.txt create mode 100644 arch/qwenimage21/qwenimage21.cpp create mode 100644 core/engine_gen.cpp create mode 100644 core/gen/driver.cpp create mode 100644 core/gen/driver.h create mode 100644 core/gen/gen.cpp create mode 100644 core/gen/gen.h create mode 100644 core/mm/imaging.cpp create mode 100644 core/mm/imaging.h create mode 100644 core/server/images.cpp create mode 100644 data/recipes/qwen-image-2.1-bf16.recipe create mode 100644 data/recipes/qwen-image-2.1-fp8.recipe create mode 100644 deploy/compose/qwen-image-2.1-turbo.yaml create mode 100644 deploy/compose/qwen-image-2.1.yaml create mode 100644 libr4d/r4d_attn_gen.hip create mode 100644 libr4d/r4d_gen.hip create mode 100644 libref/ref_gen.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 48da6d79..60168c13 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.21) # VERSION is what /version reports and what a client checks compatibility against. It is NOT the # ABI version -- that lives in abi/rad_abi.h and is read out of the header below, because # a plugin contract and a server release do not move together. -project(radiance VERSION 1.5.0 LANGUAGES C CXX) +project(radiance VERSION 1.6.0 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) diff --git a/Dockerfile b/Dockerfile index 33ab2b78..3bf52f67 100644 --- a/Dockerfile +++ b/Dockerfile @@ -11,8 +11,9 @@ # # Stages: # ffmpeg FFmpeg built with only the demuxers core/mm/media.cpp admits and the decoders their -# streams need (pictures, video, and audio with swresample); the distribution's build -# brings ~200 packages of encoders, filters and display libraries the engine never calls +# streams need (pictures, video, and audio with swresample), and the three encoders the +# images API writes (png, mjpeg, libwebp); the distribution's build brings ~200 +# packages of encoders, filters and display libraries the engine never calls # llvm ROCm's libLLVM rebuilt from ROCm's own llvm-project at the commit the image's clang # reports, with docker/llvm-vopd-pairing.patch -- the fix that makes LLVM 24's device # code repeatable from build to build (cmake/RadAddPlugin.cmake, rad_hip_repeatable) @@ -53,13 +54,15 @@ ARG JOBS= RUN apt-get update \ && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ build-essential nasm pkg-config ca-certificates curl xz-utils zlib1g-dev libdav1d-dev \ + libwebp-dev \ && rm -rf /var/lib/apt/lists/* WORKDIR /tmp # The demuxers are media.cpp's kFormats whitelist, the only containers it opens. The decoders are # what those containers carry: still images, H.264 and HEVC (MP4, MOV, HEIF), VP8 and VP9 (WebM, # WebP), AV1 through dav1d (WebM, MP4, AVIF), MPEG-1/2/4, Theora and the FLV/H.263 family. JPEG XL -# is recognised and refused by name: its only decoder is libjxl's. No protocols: media.cpp reads -# from memory through its own I/O context. +# is recognised and refused by name: its only decoder is libjxl's. The encoders are an image +# model's output formats (media.cpp encode_image): png, jpeg as mjpeg, webp through libwebp. No +# protocols: media.cpp reads from memory through its own I/O context. RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ curl -fsSL "https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz" -o ffmpeg.tar.xz \ && echo "${FFMPEG_SHA256} ffmpeg.tar.xz" | sha256sum -c - \ @@ -67,9 +70,10 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ && ./configure --prefix=/opt/ffmpeg --enable-shared --disable-static --disable-debug \ --disable-programs --disable-doc --disable-network --disable-autodetect --disable-everything \ --disable-avdevice --disable-avfilter --enable-swresample \ - --enable-zlib --enable-libdav1d \ + --enable-zlib --enable-libdav1d --enable-libwebp \ --enable-demuxer=mov,matroska,avi,mpegts,flv,ogg,gif,apng,image2pipe,image_png_pipe,image_jpeg_pipe,image_jpegls_pipe,image_jpegxl_pipe,image_webp_pipe,image_bmp_pipe,image_tiff_pipe,image_qoi_pipe,image_pgm_pipe,image_ppm_pipe,image_pbm_pipe,image_pam_pipe,image_gif_pipe,wav,w64,mp3,flac,aac,aiff \ --enable-decoder=h264,hevc,vp8,vp9,libdav1d,mpeg4,mpeg1video,mpeg2video,mjpeg,jpegls,png,apng,gif,webp,bmp,tiff,qoi,pgm,ppm,pbm,pam,pgmyuv,theora,vp3,flv,h263,pcm_u8,pcm_s16le,pcm_s16be,pcm_s24le,pcm_s24be,pcm_s32le,pcm_s32be,pcm_f32le,pcm_f32be,pcm_f64le,pcm_alaw,pcm_mulaw,mp3float,mp2float,flac,vorbis,opus,aac \ + --enable-encoder=png,mjpeg,libwebp \ --enable-parser=h264,hevc,vp8,vp9,av1,mpeg4video,mpegvideo,mjpeg,png,gif,bmp,webp,vp3,qoi,pnm,h263,jpegxl,mpegaudio,flac,aac,vorbis,opus \ && make -j"${JOBS:-$(nproc)}" \ && make install \ @@ -136,11 +140,11 @@ ARG JOBS= # g++-14 rather than the image's default 13: its libstdc++ is the one hipcc then compiles the # device-side translation units against too, and it is the runtime image's libstdc++ as well. # gawk because tools/ops_doc_check.sh uses gensub, which Ubuntu's default awk (mawk) lacks. -# libdav1d7 is the runtime half of the AV1 decoder the ffmpeg stage linked; busybox-static goes -# into the runtime image. +# libdav1d7 and libwebp7 are the runtime halves of the AV1 decoder and the WebP encoder the ffmpeg +# stage linked; busybox-static goes into the runtime image. RUN apt-get update \ && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ - cmake ninja-build pkg-config g++-14 gawk libdav1d7 busybox-static \ + cmake ninja-build pkg-config g++-14 gawk libdav1d7 libwebp7 busybox-static \ && rm -rf /var/lib/apt/lists/* COPY --from=ffmpeg /opt/ffmpeg /opt/ffmpeg diff --git a/README.md b/README.md index 1a939c3b..f2b683e9 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # radiance -An LLM inference server for AMD GPUs, in C++ and HIP. Its HTTP API speaks OpenAI's chat, completions -and Responses APIs, Anthropic's Messages API and llama-server's native one, so their clients and -SDKs work unchanged. Model architectures, kernel libraries and quantisers are `.so` plugins; the ones in this tree are built +An LLM and image-generation inference server for AMD GPUs, in C++ and HIP. Its HTTP API speaks OpenAI's +chat, completions, Responses and images APIs, Anthropic's Messages API and llama-server's native one, +so their clients and SDKs work unchanged. Model architectures, kernel libraries and quantisers are `.so` plugins; the ones in this tree are built and loaded the same way a third party's are ([`docs/PLUGIN.md`](docs/PLUGIN.md)). The bundled device kernels (`libr4d`) target **AMD RDNA4** (`gfx1200`, `gfx1201`). The serve flags @@ -23,6 +23,8 @@ If you wish to support the developement of the radiance engine you can do so [he | MiniCPM5-2B FP8, DSpark drafter | `minicpm5-2b-fp8.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-fp8) | `minicpm5-2b.yaml` | | MiniCPM5-2B bf16, DSpark drafter | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | `minicpm5-2b-bf16.yaml` | | Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | `gemma4-31b-w4a8.yaml` | +| Qwen-Image 2.1 FP8: text to image and image edits | `qwen-image-2.1-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-fp8) | `qwen-image-2.1.yaml` | +| Qwen-Image 2.1 Turbo FP8: the same in 8 steps | `qwen-image-2.1-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-fp8) | `qwen-image-2.1-turbo.yaml` | | Qwen3.8-27B ParoQuant int4, int5 or MXFP4 (learned rotations), DFlash2 drafter, vision | `qwen3.8-27b-paro-int4.rad` (19 GiB; int5 22 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-paro.yaml` | | Qwen3.8-27B bf16 | `qwen3.8-27b-bf16.rad` (50 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-bf16.yaml` | | Qwen3.8-Flash-Next bf16, a disk-streamed reference | `qwen3.8-flash-next-bf16.rad` (335 GiB) | [convert](#convert-a-checkpoint) | `flashnext-bf16.yaml` | @@ -51,6 +53,12 @@ Givens rotations it was trained in. Convert int4 from `z-lab/Qwen3.8-27B-PARO`, before 1.5.0 is refused at startup. Convert it again and pass the old one as `--reuse` to copy every tensor that did not change. +The Qwen-Image containers serve OpenAI's images API (`/v1/images/generations`, `/v1/images/edits`): +pictures from a prompt, and edits of up to ten pictures with an optional mask, 2048x2048 by default. +On two R9700s a 2048x2048 picture takes 61 s at the base model's 40 steps and 13 s with Turbo (56 and +12 s with `--tp-wire wht6`); 1024x1024 takes 6 s and 2.6 s. Qwen-Image 2.1 is under Qwen's research +license, which is non-commercial. + ## Run with Docker The host needs Docker and an `amdgpu` driver that supports ROCm 10.1; it does not need ROCm. The @@ -121,6 +129,7 @@ prefix-cache tiers: | Qwen3.8-27B bf16 | `--tp 2 --max-num-seqs 8 --max-model-len 200000 --kv-cache-dtype fp8` | | MiniCPM5-2B FP8 and bf16 | `--tp 2 --max-num-seqs 32 --max-model-len 131072 --kv-cache-dtype fp8 --gpu-headroom-mib 160 --max-num-batched-tokens 512` | | Qwen3.8-Flash-Next bf16 | `--tp 2 --max-model-len 32768 --placement expert_tiered --weights-disk-tier --host-pool-mib 12288 --gpu-headroom-mib 768 --deterministic --max-num-seqs 32 --max-num-batched-tokens 32768 --num-speculative-tokens 0` | +| Qwen-Image 2.1 and 2.1 Turbo | `--tp 2 --tp-wire wht6` | Every model serves up to 32 sequences a step. Two rows keep 8, because on a hybrid model each sequence holds its own recurrent state, and 32 of them take that memory from the attention cache @@ -154,6 +163,14 @@ curl -s localhost:8000/v1/chat/completions -H 'Content-Type: application/json' \ -d '{"model":"m","messages":[{"role":"user","content":"hi"}],"max_tokens":50}' ``` +An image model answers OpenAI's images API instead, with base64 pictures: + +```sh +curl -s localhost:8000/v1/images/generations -H 'Content-Type: application/json' \ + -d '{"prompt":"a lighthouse on a cliff at sunset, oil painting","size":"1024x1024"}' \ + | python3 -c 'import sys,json,base64; open("out.png","wb").write(base64.b64decode(json.load(sys.stdin)["data"][0]["b64_json"]))' +``` + `http://localhost:8000/` is the dashboard. [`docs/GUIDE.md`](docs/GUIDE.md) covers the API, memory budgets, long context, speculative decoding and operating a server. diff --git a/abi/rad_abi.h b/abi/rad_abi.h index fd37c252..2870bb0d 100644 --- a/abi/rad_abi.h +++ b/abi/rad_abi.h @@ -19,7 +19,7 @@ extern "C" { * name, with both versions printed. An OPTIONAL export added beside the existing ones * (rad_plugin_reference, say) is not a change of shape: a plugin without it is read as answering * the default. */ -#define RAD_ABI_VERSION 15u +#define RAD_ABI_VERSION 16u /* ================================================================== plugin identity */ /* RAD_PLUGIN_QUANT is a quantiser plugin: rad_quant.h is its whole contract. */ diff --git a/abi/rad_builder.h b/abi/rad_builder.h index d07e5d34..30a5a571 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -615,6 +615,106 @@ typedef struct RadEncoderDecl { int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d); +/* ================================================================== the image generator */ +/* A PROGRAM THAT MAKES IMAGES: a conditioning network that reads a prompt (and pictures), a + * denoiser that turns a latent from noise into an image's latent over a number of steps, and a + * decoder that turns the latent into pixels. Declared for the reason the logits buffer is: the + * core drives the passes, so it has to be told what it is driving, and only the plugin knows. + * + * DECLARING ONE MAKES THE PROGRAM A GENERATOR, and a generator is driven by passes rather than by + * token steps (RadBatch::gen): + * + * RAD_GEN_PASS_COND one conditioning sequence -- the prompt, and any reference pictures -- + * encoded into the generator's KV group. Read once per request (twice + * with guidance: the negative prompt is a sequence of its own). + * RAD_GEN_PASS_DENOISE one step of every image in flight that the pass carries: each image's + * latent rows, read from and written back to the plugin's own state at the + * image's lane, against its conditioning's KV. + * RAD_GEN_PASS_DECODE one image's latent to pixels, in `image_out`, which the core reads back. + * + * A program declares this, logits or pooled vectors -- one of the three. + * + * WHAT IS HERE IS THE MODEL'S CONTRACT WITH A CLIENT: the prompt it was trained on, the sizes it + * makes, the schedule its sampler follows. The core turns a request into passes with it and + * nothing in the core names a model. */ +enum { RAD_GEN_PASS_COND = 1, RAD_GEN_PASS_DENOISE = 2, RAD_GEN_PASS_DECODE = 3 }; + +/* HOW THE GENERATOR'S SEQUENCE IS LAID OUT, which the core builds from the conditioning prompt. + * + * JOINT_GRID the prompt's rows after `drop_prefix`, each media slot standing for `slot_rows` + * rows that a reference picture's latent tokens take in raster order, then the + * image being made. Rotary positions are three components: a text row counts up + * in all three; a picture of h x w tokens holds the count in the first, and its row + * and column, centred on zero (-(n - n/2) .. n/2 - 1), in the other two, after which + * the count moves on by max(h, w). Text rows attend causally, a picture's rows to + * each other both ways, every row to every row before it. */ +enum { RAD_GEN_LAYOUT_JOINT_GRID = 1 }; + +typedef struct RadGeneratorDecl { + const char* name; /* "qwen-image" -- for messages */ + int32_t layout; /* RAD_GEN_LAYOUT_* */ + + /* THE CONDITIONING PROMPT, as text the core tokenises. `{prompt}` is replaced by the user's + * prompt; in `tmpl_edit`, `{images}` by one `tmpl_image` for each reference picture, joined by + * `tmpl_image_sep`. In `tmpl_image`, `{n}` is the picture's 1-based number and `{image}` where + * the picture's own tokens go -- the run the media processor makes of it, its markers + * included. */ + const char* tmpl_text; + const char* tmpl_edit; + const char* tmpl_image; + const char* tmpl_image_sep; + /* The tokens this text tokenises to at the start of the prompt are ENCODED but not handed to + * the generator: the conditioning starts after them (a fixed system turn, say). */ + const char* drop_prefix; + /* A TRANSPARENT IMAGE, asked for in the words the model was trained on: `{prompt}` is the + * user's description. Empty when the model makes no alpha. */ + const char* tmpl_transparent; + + /* GEOMETRY. One latent token covers `latent_scale` x `latent_scale` pixels and holds + * `latent_channels` values; a side is a multiple of `size_multiple` pixels; an image has + * `pixel_channels` channels (4: RGBA). A media slot of the conditioning prompt -- one + * encoder output row -- stands for `slot_rows` rows of the generator's sequence. */ + int64_t latent_channels; + int64_t latent_scale; + int64_t size_multiple; + int64_t pixel_channels; + int64_t slot_rows; + /* The largest image, in latent tokens: every buffer the plugin sized for one image. */ + int64_t max_tokens; + /* Reference pictures: at most `max_refs` a request, each resized to `ref_area` pixels. */ + int64_t max_refs; + int64_t ref_area; + /* The size a request that names none is made at. */ + int64_t default_width, default_height; + + /* THE SAMPLER: flow matching, an Euler step from sigma 1 towards 0. + * A FIXED SCHEDULE: `n_sigmas` values, the terminal 0 implied; a request may not change the + * step count. Otherwise `default_steps` sigmas from 1 to 1/steps, shifted: + * dyn_shift 0 sigma' = shift * s / (1 + (shift - 1) * s) + * dyn_shift 1 mu linear in the image's token count, 256 -> base_shift .. max_seq -> + * max_shift; shift_exp 1: exp(mu) / (exp(mu) + (1/s - 1)), 0: mu / (mu + ...) + * then, with shift_terminal > 0, stretched so the last sigma is shift_terminal. */ + int64_t default_steps; + int32_t n_sigmas; + const double* sigmas; + double shift; + int32_t dyn_shift; + int32_t shift_exp; + double base_shift, max_shift; + int64_t base_seq, max_seq; + double shift_terminal; + /* Guidance a request gets when it names none; 1 is off. */ + double default_cfg; + + /* WHERE THINGS ARE. `max_lanes` images may be in flight at once, each in a lane of the + * plugin's own state; `image_out` is [max_tokens * latent_scale^2, pixel_channels] u8 on the + * device, row-major pixels of the image a decode pass made. */ + int64_t max_lanes; + rad_buf image_out; +} RadGeneratorDecl; + +int rad_declare_generator(RadBuilder* b, const RadGeneratorDecl* d); + /* ================================================================== diagnostics */ /* A plugin may annotate the graph dump. Free-form, printed under --debug-graph. */ void rad_note(RadBuilder* b, const char* fmt, ...); @@ -687,6 +787,15 @@ typedef struct RadArchProbe { * number of its merge), when it declares one: the engine sizes the audio pass with it * (RadBuildCtx::max_audio_frames). 0 is no audio. */ int64_t audio_frames; + + /* AN IMAGE GENERATOR (rad_declare_generator), and the rows its largest pass carries: the + * engine sizes the step for it before declare -- a denoise pass carries an image's every + * latent row at once, twice with guidance -- and turns off what a generator has no use for. + * 0 is a program that generates text or embeds. */ + int64_t gen_rows; + /* ...and the patches its conditioning pass encodes at most: every reference picture a request + * may carry, at the size the model resizes them to. The encoder's pass size (max_enc_patches). */ + int64_t gen_patches; } RadArchProbe; int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out); diff --git a/abi/rad_philox.h b/abi/rad_philox.h new file mode 100644 index 00000000..dc9f9c36 --- /dev/null +++ b/abi/rad_philox.h @@ -0,0 +1,49 @@ +#ifndef RAD_PHILOX_H +#define RAD_PHILOX_H + +/* Counter-based Gaussian noise, the one definition every kernel library computes it by, so an + * image's starting latent is a function of its seed and of nothing else: not the batch it shares a + * pass with, not the rank count, not the order its rows are visited in. + * + * Element e of a seed's stream is Philox4x32-10 at counter (e / 4, 0) keyed by the 64-bit seed, + * its four words made uniform in (0, 1) as ((w >> 8) + 0.5) * 2^-24 and paired by Box-Muller -- + * words 0 and 1 give elements 4g and 4g+1 (r cos t, r sin t), words 2 and 3 give 4g+2 and 4g+3. + * f32 throughout. A library's libm may differ from another's in the last place of log, cos and + * sin, so two libraries agree to a tolerance and each agrees with itself exactly. */ +#include +#include + +#if defined(__HIPCC__) +#define RAD_PHILOX_HD __host__ __device__ __forceinline__ +#else +#define RAD_PHILOX_HD static inline +#endif + +RAD_PHILOX_HD void rad_philox4x32_10(uint32_t c[4], uint32_t k0, uint32_t k1) { + const uint32_t M0 = 0xD2511F53u, M1 = 0xCD9E8D57u, W0 = 0x9E3779B9u, W1 = 0xBB67AE85u; + for (int r = 0; r < 10; ++r) { + const uint64_t p0 = (uint64_t)M0 * c[0], p1 = (uint64_t)M1 * c[2]; + const uint32_t hi0 = (uint32_t)(p0 >> 32), lo0 = (uint32_t)p0; + const uint32_t hi1 = (uint32_t)(p1 >> 32), lo1 = (uint32_t)p1; + const uint32_t n0 = hi1 ^ c[1] ^ k0, n2 = hi0 ^ c[3] ^ k1; + c[0] = n0; c[1] = lo1; c[2] = n2; c[3] = lo0; + k0 += W0; + k1 += W1; + } +} + +/* Element `e` of the standard-normal stream of `seed`. */ +RAD_PHILOX_HD float rad_philox_normal(uint64_t seed, uint64_t e) { + const uint64_t g = e >> 2; + uint32_t c[4] = { (uint32_t)g, (uint32_t)(g >> 32), 0u, 0u }; + rad_philox4x32_10(c, (uint32_t)seed, (uint32_t)(seed >> 32)); + const int j = (int)(e & 3u); + const uint32_t wa = c[(j >> 1) * 2], wb = c[(j >> 1) * 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; + return (j & 1) ? r * sinf(t) : r * cosf(t); +} + +#endif /* RAD_PHILOX_H */ diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index b168cb98..d8782386 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -229,8 +229,95 @@ typedef struct RadBatch { int64_t enc_n_seg; const int32_t* enc_cu; /* [enc_n_seg + 1] device: segment boundaries in patches */ int32_t enc_max_seg; /* host: the longest segment, which bands the attention */ + + /* ================================================ image generation */ + + /* A GENERATOR PASS (rad_declare_generator): RAD_GEN_PASS_*, and `gen_b` what it carries. 0 on + * every step of a program that declared no generator. */ + int32_t gen; + const struct RadGenBatch* gen_b; } RadBatch; +/* WHAT A GENERATOR PASS CARRIES beside the step batch's own fields, which keep their meanings: + * + * COND ONE sequence. `token_ids`, `positions` and `rope_pos` are its conditioning prompt, the + * encoder's input (`enc_*`) is the prompt's reference pictures and `mm_rows` the prompt + * rows the encoder's output rows replace, as on any media step. What is here lays out + * the generator's sequence over those rows and writes it into the KV group. + * DENOISE one entry per (image, conditioning): `cu_seqlens` bounds each entry's latent rows, + * and the KV group's `block_table` and `seqused` name its conditioning's sequence. + * DECODE one image. + * + * Every pointer is device memory unless the name ends in _h. */ +typedef struct RadGenBatch { + /* ---- COND */ + int64_t rows; /* the generator's rows for this sequence */ + /* Where each row comes from: >= 0 the prompt row of that index (the conditioning network's + * output there), < 0 the reference latent row -(1 + src). [rows] */ + const int32_t* src; + /* Rotary positions, three components a row. On a COND pass they are laid out SEGMENT BY + * SEGMENT: segment s's [3, length] component-major block starts at element 3 * seg_h[s], so a + * segment's positions are one dense operand. On a DENOISE pass, [3, n_tok] component-major, + * the latent rows'. */ + const int32_t* rope; + /* The sequence in SEGMENTS: rows [seg_h[s], seg_h[s+1]), each a picture (`seg_bidi_h` 1, its + * rows attend to each other both ways) or a run of text (0, causal). A segment is never split + * and attends to every segment before it. `seg` is the same offsets on the device; `seg_cu` + * is [n_seg, 2], segment s's own cu_seqlens {0, length}, and `seg_start` [n_seg] its first + * row -- the keys before it, which is its `seqused` when it is run on its own. */ + int64_t n_seg; + const int32_t* seg; + const int32_t* seg_h; + const int32_t* seg_bidi_h; + const int32_t* seg_cu; + const int32_t* seg_start; + /* [rows] the KV slot each row is stored at. */ + const int32_t* slot_mapping; + /* PIXELS the decoder's encoder takes: `n_px` blocks of `px` [*, pixel_channels] bf16 in + * [-1, 1], block b at pixel px_h[3b], px_h[3b+1] high and px_h[3b+2] wide. The reference + * pictures, in prompt order, and -- with `inpaint` -- a last block that is no reference but + * the picture being repainted, at the size being made: its latents go to the lanes below. */ + int64_t n_px; + const void* px; + const int32_t* px_h; + /* [n_px, 2] each block's own cu_seqlens over its latent tokens: {0, (h / scale) (w / scale)}. */ + const int32_t* px_cu; + int32_t inpaint; + /* [image tokens] f32: 1 where the image is repainted, 0 where the picture is kept. */ + const float* inp_mask; + /* The lanes this conditioning's images run in, which take the repainted picture's latents. */ + int64_t n_lane; + const int32_t* lane_h; + + /* ---- DENOISE, one value per entry ([n_seq]); on a COND pass `sigma` is one 0, the time + * the conditioning is modulated at */ + const float* sigma; /* where the entry's latent is */ + const float* sigma_next; /* where this step takes it */ + const float* cfg; /* guidance: v = neg + cfg * (pos - neg); 1 without a pair */ + /* The entry holding this image's NEGATIVE conditioning, or -1 for none; -2 marks an entry + * that IS one, whose rows serve another entry's step and whose lane it does not move. */ + const int32_t* pair; + const int32_t* lane; /* the plugin's lane the image's latent lives in */ + const int32_t* lane_dh; /* ... the same, host */ + /* RAD_GEN_F_*. */ + const int32_t* flags; + /* [n_seq, 2] the image's noise seed, low word first. */ + const uint32_t* seed; + + /* ---- DECODE */ + int32_t dec_lane; + int32_t dec_height, dec_width; /* pixels */ + int32_t dec_preview; /* the lane's preview latent, not its state */ +} RadGenBatch; + +/* An entry's flags on a DENOISE pass. */ +enum { + RAD_GEN_F_FIRST = 1, /* the image's first step: its latent is the noise its seed draws */ + RAD_GEN_F_INPAINT = 2, /* repaint: after the step, the kept region goes back to the picture, + * noised to sigma_next with the image's own noise */ + RAD_GEN_F_PREVIEW = 4 /* write the step's estimate of the clean latent to the lane's preview */ +}; + /* ================================================================== operands */ /* RAD_OPK_KV names a KV group's pool rather than a buffer: attention and kv_store take the cache * as an operand, and RadKVGroupBatch carries the slot mapping and the block table but not the diff --git a/arch/common/rad_block_vit.h b/arch/common/rad_block_vit.h index 33199b01..217cb2de 100644 --- a/arch/common/rad_block_vit.h +++ b/arch/common/rad_block_vit.h @@ -14,8 +14,11 @@ * x += fc2(gelu_tanh(fc1(LN2(x)))) * out = fc2'(gelu(fc1'(LN(x) viewed [P/merge^2, merge^2 * width]))) the patch merger * - * which is transformers' Qwen3_5VisionModel with no deepstack taps (the checkpoints this tree - * serves list none, and one that did would be refused at declare). Every linear layer is + * which is transformers' Qwen3_5VisionModel. Qwen3-VL's DEEPSTACK taps -- the residual stream + * after named blocks, each through a merger of its own whose norm is taken AFTER the 2x2 view + * (over merge^2 * width), into rows added to the language model's hidden state after its first + * layers -- are declared only for a plugin that asks (declare's `deepstack`); one that does not is + * refused a tower with taps rather than served without them. Every linear layer is * `gemm_nt_bias` with its activation and residual in the epilogue, each rounded where the * reference's separate tensors are. * @@ -35,6 +38,7 @@ #include #include +#include #include #include @@ -61,6 +65,16 @@ struct VisionTower { rad_buf b_x = 0, b_h = 0, b_qkv = 0, b_att = 0, b_ff = 0, b_mh = 0, b_mf = 0, b_out = 0; char sec[48] = {}; + /* DEEPSTACK: tap t is the residual stream after block `ds_layer[t]`, merged into `b_ds[t]` + * ([P / merge^2, n_embd], one row a merged token, in the order `b_out` holds them). */ + enum { MAX_DS = 4 }; + int n_ds = 0; + int ds_layer[MAX_DS] = {}; + rad_weight ds_nw[MAX_DS] = {}, ds_nb[MAX_DS] = {}, ds_1w[MAX_DS] = {}, ds_1b[MAX_DS] = {}; + rad_weight ds_2w[MAX_DS] = {}, ds_2b[MAX_DS] = {}; + rad_op ds_ln[MAX_DS] = {}, ds_1[MAX_DS] = {}, ds_2[MAX_DS] = {}; + rad_buf b_ds[MAX_DS] = {}; + /* Is there a tower to declare: the container carries one and the deployment asked for media. * `why` is set when the container carries one this block cannot serve. */ static bool present(const RadModelMeta* m) { @@ -68,12 +82,12 @@ struct VisionTower { } int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm, - int64_t model_embd, int first_group); + int64_t model_embd, int first_group, bool deepstack = false); void step(RadCtx* c, const RadBatch* batch) const; }; inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, - Names& nm, int64_t model_embd, int first_group) { + Names& nm, int64_t model_embd, int first_group, bool deepstack) { on = false; if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK; @@ -105,14 +119,27 @@ inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadB return RAD_E_INVAL; } /* DEEPSTACK -- tower layers feeding the language model's early layers directly -- is a second - * input path this block does not carry. Refused by name rather than dropped. */ + * input path, and a plugin that does not consume it is refused the tower by name rather than + * served without it. */ const char* ds = rad_meta_gets(m, "vision_config.deepstack_visual_indexes", ""); - for (const char* q = ds; q && *q; ++q) - if (*q >= '0' && *q <= '9') { + n_ds = 0; + for (const char* q = ds; q && *q;) { + if (*q < '0' || *q > '9') { ++q; continue; } + char* e = nullptr; + const long v = std::strtol(q, &e, 10); + q = e; + if (!deepstack) { fprintf(stderr, "radiance: this vision tower has deepstack taps (%s), which this plugin " "does not serve\n", ds); return RAD_E_UNSUPPORTED; } + if (n_ds >= MAX_DS || v < 0 || v >= depth) { + fprintf(stderr, "radiance: deepstack taps '%s' do not fit a %lld-block tower\n", ds, + (long long)depth); + return RAD_E_INVAL; + } + ds_layer[n_ds++] = (int)v; + } const char* act = rad_meta_gets(m, "vision_config.hidden_act", "gelu_pytorch_tanh"); if (std::strcmp(act, "gelu_pytorch_tanh") && std::strcmp(act, "gelu")) { fprintf(stderr, "radiance: vision_config.hidden_act '%s' is not served\n", act); @@ -182,6 +209,17 @@ inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadB m2_b = bw(nm.f("v.merger.fc2.bias"), nm.ckpt("model.visual.merger.linear_fc2.bias"), RAD_BF16, { n_embd }, grp_model()); if (!w_patch || !b_patch || !w_pos || !mn_w || !mn_b || !m1_w || !m1_b || !m2_w || !m2_b) return RAD_E_INVAL; + for (int t = 0; t < n_ds; ++t) { + const char* pre = "model.visual.deepstack_merger_list"; + ds_nw[t] = bw(nm.f("v.ds.%d.norm.weight", t), nm.ckpt("%s.%d.norm.weight", pre, t), RAD_BF16, { mm * width }, grp_model()); + ds_nb[t] = bw(nm.f("v.ds.%d.norm.bias", t), nm.ckpt("%s.%d.norm.bias", pre, t), RAD_BF16, { mm * width }, grp_model()); + ds_1w[t] = bw(nm.f("v.ds.%d.fc1.weight", t), nm.ckpt("%s.%d.linear_fc1.weight", pre, t), RAD_BF16, { mm * width, mm * width }, grp_model()); + ds_1b[t] = bw(nm.f("v.ds.%d.fc1.bias", t), nm.ckpt("%s.%d.linear_fc1.bias", pre, t), RAD_BF16, { mm * width }, grp_model()); + ds_2w[t] = bw(nm.f("v.ds.%d.fc2.weight", t), nm.ckpt("%s.%d.linear_fc2.weight", pre, t), RAD_BF16, { n_embd, mm * width }, grp_model()); + ds_2b[t] = bw(nm.f("v.ds.%d.fc2.bias", t), nm.ckpt("%s.%d.linear_fc2.bias", pre, t), RAD_BF16, { n_embd }, grp_model()); + if (!ds_nw[t] || !ds_nb[t] || !ds_1w[t] || !ds_1b[t] || !ds_2w[t] || !ds_2b[t]) + return RAD_E_INVAL; + } /* ---- activations. `mh` is the merger's input, declared at the MERGED width: the norm writes * it as P rows of `width` and the first merger layer reads it as P/mm rows of mm * width, @@ -244,6 +282,22 @@ inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadB op_mln = rw(b, lnorm(P, mn_w, mn_b), { b_x }, { b_mh }); op_m1 = rw(b, gemm(R, mm * width, mm * width, "gelu", m1_w, m1_b), { b_mh }, { b_mf }); op_m2 = rw(b, gemm(R, n_embd, mm * width, "none", m2_w, m2_b), { b_mf }, { b_out }); + /* A deepstack merger normalises AFTER the view, over a merged row: the same bytes as P rows of + * `width`, read as R rows of merge^2 * width. Its ops are declared here, after the tower, and + * issued between its blocks; their working planes are consumed before the next block runs. + * Each tap's OUTPUT is not -- it waits for the language model while the remaining blocks + * overwrite the tower's planes -- so it is PERSIST, outside the planner's sharing. */ + for (int t = 0; t < n_ds; ++t) { + b_ds[t] = decl_b(b, nm.f("v.ds.%d.out", t), RAD_BF16, { R, n_embd }, RAD_BUF_PERSIST); + if (!b_ds[t]) return RAD_E_INVAL; + ds_ln[t] = rw(b, RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", mm * width), + RAD_F64("eps", eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(ds_nw[t], ds_nb[t])), + { b_x }, { b_mh }); + ds_1[t] = rw(b, gemm(R, mm * width, mm * width, "gelu", ds_1w[t], ds_1b[t]), { b_mh }, { b_mf }); + ds_2[t] = rw(b, gemm(R, n_embd, mm * width, "none", ds_2w[t], ds_2b[t]), { b_mf }, { b_ds[t] }); + } if (!ctx->shape_probe) { RadEncoderDecl e{}; @@ -282,7 +336,8 @@ inline void VisionTower::step(RadCtx* c, const RadBatch* batch) const { RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_patch), RAD_W(b_patch), RAD_NONE, brows(b_x, Pn)); RAD_ISSUE_N(c, op_pos, Pn, brows(b_x, Pn), RAD_W(w_pos), crd); - for (const Layer& l : L) { + for (size_t li = 0; li < L.size(); ++li) { + const Layer& l = L[li]; RAD_ISSUE_N(c, l.ln1, Pn, brows(b_x, Pn), RAD_W(l.n1w), RAD_W(l.n1b), brows(b_h, Pn)); RAD_ISSUE_N(c, l.qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv_w), RAD_W(l.qkv_b), RAD_NONE, brows(b_qkv, Pn)); @@ -297,6 +352,15 @@ inline void VisionTower::step(RadCtx* c, const RadBatch* batch) const { brows(b_ff, Pn)); RAD_ISSUE_N(c, l.down, Pn, brows(b_ff, Pn), RAD_W(l.down_w), RAD_W(l.down_b), brows(b_x, Pn), brows(b_x, Pn)); + for (int t = 0; t < n_ds; ++t) { + if (ds_layer[t] != (int)li) continue; + RAD_ISSUE_N(c, ds_ln[t], Rn, brows(b_x, Pn), RAD_W(ds_nw[t]), RAD_W(ds_nb[t]), + brows(b_mh, Rn)); + RAD_ISSUE_N(c, ds_1[t], Rn, brows(b_mh, Rn), RAD_W(ds_1w[t]), RAD_W(ds_1b[t]), RAD_NONE, + brows(b_mf, Rn)); + RAD_ISSUE_N(c, ds_2[t], Rn, brows(b_mf, Rn), RAD_W(ds_2w[t]), RAD_W(ds_2b[t]), RAD_NONE, + brows(b_ds[t], Rn)); + } } /* The merger norm writes P rows of `width` into a buffer declared at the merged width: the * same bytes the next layer reads as P/mm rows. */ diff --git a/arch/qwenimage21/CMakeLists.txt b/arch/qwenimage21/CMakeLists.txt new file mode 100644 index 00000000..47d8f45a --- /dev/null +++ b/arch/qwenimage21/CMakeLists.txt @@ -0,0 +1,11 @@ +# A plugin like any other: built here inside radiance's tree, or on its own against an installed +# radiance (`cmake -S arch/qwenimage21 -B build -DCMAKE_PREFIX_PATH=`) -- the same +# rad_add_plugin either way (cmake/RadAddPlugin.cmake). +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(qwenimage21 LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(qwenimage21 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/qwenimage21.cpp) diff --git a/arch/qwenimage21/qwenimage21.cpp b/arch/qwenimage21/qwenimage21.cpp new file mode 100644 index 00000000..c0082d67 --- /dev/null +++ b/arch/qwenimage21/qwenimage21.cpp @@ -0,0 +1,1567 @@ +/* qwenimage21 -- Qwen-Image 2.1 and 2.1-Turbo: text and reference pictures to an RGBA image. + * + * ============================== THE MODEL ============================== + * + * Three networks behind one prompt (diffusers' QwenImage21Pipeline): + * + * THE CONDITIONING NETWORK is Qwen3-VL-8B-Instruct, unchanged: its vision tower (with the three + * deepstack taps) reads the reference pictures, its 36-layer language model reads the prompt, + * and what the generator conditions on is the LAST LAYER'S OUTPUT BEFORE THE FINAL NORM, minus + * the fixed system turn the template starts with. + * + * THE DENOISER is a 7.1B single-stream diffusion transformer over one joint sequence: the + * conditioning's text rows (through `txt_in`), each reference picture's latent tokens in place of + * its vision slots (through `img_in`, four latent rows a slot), and the image being made. 32 + * blocks of `h += tanh(g1) attn(LN(h)(1 + s1)); h += tanh(g2) mlp(LN(h)(1 + s2))`, the four + * modulation rows from ONE projection of the timestep embedding shared by every block. Attention + * is block-causal: text causal, a picture's rows bidirectional, every row sees all earlier ones. + * The conditioning is modulated at t = 0, so its keys and values do not depend on the step -- + * they are computed once (a COND pass) and cached in this plugin's KV group, and each DENOISE + * pass runs only the image's rows against them. + * + * THE DECODER is a 2-D VAE: 64 latent channels, 16x down, RGBA in and out. Its encoder turns the + * reference pictures (and a picture being repainted) into latents on the COND pass; its decoder + * turns a finished latent into pixels on a DECODE pass. + * + * The passes, their batches and the lanes an image's latent lives in are the core's generator + * (abi/rad_builder.h, rad_declare_generator; core/gen). Turbo is the same graph with different + * DiT weights and a fixed 8-step schedule, which the container's `pipeline.sample_sigmas` says. + * + * ============================== WHAT IS QUANTISED ============================== + * + * One plugin serves a bf16 container and a block-fp8 one: every linear of the language model and + * of the DiT's blocks is a LinearFP8, which reads whatever the container holds (rad_fp8.h), and the + * model is bf16 throughout when the first DiT projection is plain. The small linears around them -- + * txt_in, img_in, the timestep MLP, the shared modulation, norm_out, proj_out -- and the vision + * tower and the VAE are bf16 in both: they are read once a pass or less, and the recipe keeps them. + * + * ============================== TENSOR PARALLEL ============================== + * + * The language model and the DiT blocks are split by heads and by feed-forward width, an + * all-reduce after each output projection. Everything else is replicated and runs on every rank: + * the embedding table, the vision tower, the small linears, the sampler and the VAE encoder -- + * each is once a pass and smaller than the collective a split would cost. The decoder is split + * after its mid-block, by rows (see `Vae::band_from`), and every rank ends with the same pixels; + * the core reads rank 0's. + */ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace qwenimage21 { + +using namespace rad::arch; + +/* ================================================================== the model's constants */ +/* The largest image: 2400 x 1792 pixels, the widest preset the model card lists, 16800 latent + * tokens. 2048 x 2048 (16384) is the native size and the default. */ +enum { kMaxImageTokens = 16800 }; +/* Reference pictures: at most ten a request, each resized to 1024 x 1024 pixels of area. */ +enum { kMaxRefs = 10, kRefArea = 1024 * 1024 }; +/* Images a request may ask for, and so the lanes of latent state. */ +enum { kMaxLanes = 16 }; +/* A reference picture's latent tokens at most: its area over 16 x 16, a little over for its sides' + * rounding (the driver's own bound, core/gen/driver.cpp). */ +static inline int64_t ref_tokens_max() { return (int64_t)kRefArea / 256 * 11 / 10 + 64; } + +static const char* kSysPrompt = "Comprehend and analyze the provided prompt."; + +/* ================================================================== the VAE as a recorded graph + * + * AN IMAGE'S SIZE IS A REQUEST'S, so the VAE's ops are declared once for the largest image and + * issued with the real one's extents: every image operand is a raw [height, width * channels] + * view of its buffer (docs/OPS.md, "Image generation"), and its extents follow from the pass's + * picture size and the stage's scale. `Vae` records each op with what it needs to rebuild its + * operands, so declare() and step() walk the same list and cannot disagree. + * + * EVERY OUTPUT IS A BUFFER OF ITS OWN, sized for its stage. The planner shares storage between + * the ones whose lives do not overlap, which is the whole of the memory plan: no buffer is reused + * by hand. The ops are issued in the order they were declared, which is what makes that sound. */ +struct VImg { + rad_buf buf = 0; + int64_t ch = 0; + int lvl = 0; /* the side is the pass's base side times 2^lvl (decoder) or / 2^lvl (encoder) */ +}; + +struct VOp { + enum Kind { CONV, NORM, ADD, D2S, S2D, ATTN } kind = CONV; + rad_op op = 0; + VImg x{}, y{}, z{}; /* inputs x (and z for ADD), output y */ + rad_weight w = 0, b = 0; + int k = 1, up = 1, stride = 1; + int64_t qkv_ch = 0; /* ATTN: x is the [*, 3C] qkv rows, y the [*, C] output */ +}; + +struct Vae { + std::vector ops; + Names* nm = nullptr; + RadBuilder* b = nullptr; + const char* scope = ""; /* "dec" or "enc" */ + bool down = false; /* an encoder: a level halves the side */ + int64_t base_px = 0; /* pixels at level 0, the largest any pass hands it */ + int n_buf = 0; + int first_group = 0; + /* THE BANDED TAIL. From op `band_from` on, every output pixel reads a bounded window of rows + * above and below it -- 3x3 convolutions, nearest upsampling, per-pixel norms and adds, the + * depth-to-space shortcuts -- so a rank can run the tail on its own band of level-0 rows plus + * `halo` rows a side and get its band's pixels bit for bit: the rows a conv's zero padding + * spoils at a band's edge never reach the band. The ops before it hold the mid-block's + * attention, which reads every pixel, and run whole. `whole` is what they wrote, which the + * tail reads at the band's row offset. -1: no tail. */ + int band_from = -1; + int64_t halo = 0; + std::vector whole; + + int64_t px_at(int lvl) const { + int64_t p = base_px; + for (int i = 0; i < lvl; ++i) p = down ? (p + 3) / 4 : p * 4; + return p; + } + VImg img(int64_t ch, int lvl) { + VImg v; + v.ch = ch; + v.lvl = lvl; + v.buf = decl_b(b, nm->f("%s.t%d", scope, n_buf++), RAD_BF16, { px_at(lvl), ch }); + return v; + } + rad_weight wt(const char* name, const char* src, std::initializer_list shape) { + if (map_copy(b, name, src) < 0) return 0; + return decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, + grp_layer(first_group)); + } + + /* y = conv(x): k x k, stride, `up` 2 reads x upsampled, `pad` same or down. */ + VImg conv(const VImg& x, int64_t cout, int k, int stride, int up, const char* pad, + const char* ckpt) { + VOp o; + o.kind = VOp::CONV; + o.x = x; + o.up = up; + o.stride = stride; + int lvl = x.lvl; + if (up == 2) lvl = down ? lvl - 1 : lvl + 1; + if (stride == 2) lvl = down ? lvl + 1 : lvl - 1; + o.y = img(cout, lvl); + o.k = k; + o.w = wt(nm->f("%s.weight", ckpt), nm->ckpt("%s.weight", ckpt), { cout, x.ch, k, k }); + o.b = wt(nm->f("%s.bias", ckpt), nm->ckpt("%s.bias", ckpt), { cout }); + o.op = RAD_OP(b, "conv2d_nhwc", + RAD_PARAMS(RAD_RANGE("M", 1, px_at(lvl)), RAD_INT("cin", x.ch), + RAD_INT("cout", cout), RAD_INT("k", k), + RAD_INT("stride", stride), RAD_STR("pad", pad), + RAD_INT("up", up), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(o.w, o.b)); + /* An input with no buffer is the picture the pass staged, read where it lies. */ + if (x.buf) rw(b, o.op, { x.buf }, { o.y.buf }); + else rw(b, o.op, {}, { o.y.buf }); + ops.push_back(o); + return o.y; + } + /* The channel norm, `silu` or not. `gamma` is [C, 1, 1(, 1)] in the checkpoint. */ + VImg norm(const VImg& x, bool silu, const char* ckpt, int gamma_rank) { + VOp o; + o.kind = VOp::NORM; + o.x = x; + o.y = img(x.ch, x.lvl); + const char* dn = nm->f("%s.gamma", ckpt); + if (map_copy(b, dn, nm->ckpt("%s.gamma", ckpt)) < 0) return VImg{}; + o.w = gamma_rank == 4 + ? decl_w(b, dn, RAD_BF16, { x.ch, 1, 1, 1 }, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_layer(first_group)) + : decl_w(b, dn, RAD_BF16, { x.ch, 1, 1 }, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_layer(first_group)); + o.op = rw(b, RAD_OP(b, "l2norm_chan", + RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch), + RAD_STR("act", silu ? "silu" : "none"), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(o.w)), + { x.buf }, { o.y.buf }); + ops.push_back(o); + return o.y; + } + VImg add(const VImg& x, const VImg& z) { + VOp o; + o.kind = VOp::ADD; + o.x = x; + o.z = z; + o.y = img(x.ch, x.lvl); + o.op = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { x.buf, z.buf }, { o.y.buf }); + ops.push_back(o); + return o.y; + } + /* y += the resampling shortcut of x (in place on y). */ + void shortcut(const VImg& x, const VImg& y, int ft) { + VOp o; + o.kind = down ? VOp::S2D : VOp::D2S; + o.x = x; + o.y = y; + o.up = ft; + o.op = rw(b, RAD_OP(b, down ? "s2d_avg_add" : "d2s_add", + RAD_PARAMS(RAD_RANGE("M", 1, px_at(y.lvl)), RAD_INT("cin", x.ch), + RAD_INT("cout", y.ch), RAD_INT("ft", ft), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { x.buf, y.buf }, { y.buf }); + ops.push_back(o); + } + /* A residual block, in -> out channels. */ + VImg resblock(const VImg& x, int64_t out, const char* ckpt) { + VImg h = x; + if (x.ch != out) h = conv(x, out, 1, 1, 1, "same", nm->f("%s.conv_shortcut", ckpt)); + VImg t = norm(x, true, nm->f("%s.norm1", ckpt), 4); + t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv1", ckpt)); + t = norm(t, true, nm->f("%s.norm2", ckpt), 4); + t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv2", ckpt)); + return add(t, h); + } + /* The mid-block's single-head attention over every pixel. */ + VImg attention(const VImg& x, const char* ckpt) { + const int64_t C = x.ch; + VImg t = norm(x, false, nm->f("%s.norm", ckpt), 3); + VImg qkv = conv(t, 3 * C, 1, 1, 1, "same", nm->f("%s.to_qkv", ckpt)); + VOp o; + o.kind = VOp::ATTN; + o.x = qkv; + o.y = img(C, x.lvl); + o.qkv_ch = 3 * C; + o.op = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("head_dim", C), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)C))), + RAD_NOWEIGHTS), + { qkv.buf }, { o.y.buf }); + ops.push_back(o); + VImg p = conv(o.y, C, 1, 1, 1, "same", nm->f("%s.proj", ckpt)); + return add(p, x); + } + + /* The operands of op `o` for a pass whose level-0 picture is H0 x W0 pixels (or latent tokens, + * for the decoder), in the op's schema order, and its ranged value. */ + static int64_t side(int64_t s0, int lvl, bool dn) { + int64_t s = s0; + for (int i = 0; i < lvl; ++i) s = dn ? s / 2 : s * 2; + return s; + } + /* `cu` is {0, pixels} at the attention's level -- the pass's latent tokens -- and `input` the + * level-0 picture when the first op reads one the pass staged. Ops [from, to) are issued; with + * `row0`, H0 is a band's rows and a `whole` buffer is read from its level-0 row `row0`. */ + void issue(RadCtx* c, int64_t H0, int64_t W0, const RadOperand& cu, const void* input, + size_t from = 0, size_t to = (size_t)-1, int64_t row0 = 0) const; + + bool is_whole(rad_buf v) const { + for (rad_buf w : whole) if (w == v) return true; + return false; + } + /* The tail's halo in level-0 rows: walked back from the last op, a buffer's margin is the most + * any reader of it needs, in its own rows -- a k x k conv adds k/2, reading through a 2x + * upsample halves it rounding up, and the depth-to-space shortcut halves it. -1 when the tail + * holds an op that is not row-local, or reads a whole buffer above level 0. */ + int64_t band_halo() const { + if (band_from < 0 || ops.empty()) return -1; + std::vector> need{ { ops.back().y.buf, 0 } }; + auto get = [&](rad_buf v) -> int64_t { + for (const auto& e : need) if (e.first == v) return e.second; + return 0; + }; + auto want = [&](rad_buf v, int64_t m) { + for (auto& e : need) if (e.first == v) { e.second = std::max(e.second, m); return; } + need.push_back({ v, m }); + }; + for (size_t i = ops.size(); i-- > (size_t)band_from;) { + const VOp& o = ops[i]; + const int64_t my = get(o.y.buf); + switch (o.kind) { + case VOp::CONV: { + if (o.stride != 1) return -1; + const int64_t m = my + o.k / 2; + want(o.x.buf, o.up == 2 ? (m + 1) / 2 : m); + break; + } + case VOp::NORM: want(o.x.buf, my); break; + case VOp::ADD: want(o.x.buf, my); want(o.z.buf, my); break; + case VOp::D2S: want(o.x.buf, (my + 1) / 2); break; + default: return -1; + } + } + int64_t h = 0; + for (size_t i = (size_t)band_from; i < ops.size(); ++i) { + const VOp& o = ops[i]; + for (const VImg* v : { &o.x, &o.z }) + if (v->buf && is_whole(v->buf)) { + if (v->lvl != 0) return -1; + h = std::max(h, get(v->buf)); + } + } + return h; + } +}; + +inline void Vae::issue(RadCtx* c, int64_t H0, int64_t W0, const RadOperand& cu, + const void* input, size_t from, size_t to, int64_t row0) const { + auto ptr = [&](const VImg& v) -> const void* { + if (!v.buf) return input; + const char* p = (const char*)rad_buf_ptr(c, v.buf); + return row0 && is_whole(v.buf) ? p + row0 * W0 * v.ch * (int64_t)sizeof(uint16_t) : p; + }; + auto view = [&](const VImg& v, int64_t* H, int64_t* W) { + *H = side(H0, v.lvl, down); + *W = side(W0, v.lvl, down); + return RAD_P_T2(ptr(v), RAD_BF16, *H, *W * v.ch); + }; + auto rows = [&](const VImg& v, int64_t cols) { + const int64_t H = side(H0, v.lvl, down), W = side(W0, v.lvl, down); + return RAD_P_T2(ptr(v), RAD_BF16, H * W * v.ch / cols, cols); + }; + for (size_t i = from; i < to && i < ops.size(); ++i) { + const VOp& o = ops[i]; + int64_t Hx, Wx, Hy, Wy; + switch (o.kind) { + case VOp::CONV: { + const RadOperand x = view(o.x, &Hx, &Wx), y = view(o.y, &Hy, &Wy); + RAD_ISSUE_N(c, o.op, Hy * Wy, x, RAD_W(o.w), RAD_W(o.b), y); + break; + } + case VOp::NORM: { + const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down); + RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), RAD_W(o.w), rows(o.y, o.y.ch)); + break; + } + case VOp::ADD: { + const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down); + RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), rows(o.z, o.z.ch), rows(o.y, o.y.ch)); + break; + } + case VOp::D2S: + case VOp::S2D: { + const RadOperand x = view(o.x, &Hx, &Wx), y = view(o.y, &Hy, &Wy); + RAD_ISSUE_N(c, o.op, Hy * Wy, x, y); + break; + } + case VOp::ATTN: { + /* q, k and v are column slices of the qkv rows, at its 3C pitch. */ + const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down); + const int64_t C = o.y.ch, n = H * W; + RAD_ISSUE_N(c, o.op, n, bcol(o.x.buf, 0, C, n), bcol(o.x.buf, C, C, n), + bcol(o.x.buf, 2 * C, C, n), cu, brows(o.y.buf, n)); + break; + } + } + } +} + +/* ================================================================== the model */ +struct TeLayer { + rad_weight w_n1 = 0, w_n2 = 0, w_qn = 0, w_kn = 0; + LinearFP8 qkv{}, o{}, gate_up{}, down{}; + QuantFP8 q_h{}, q_attn{}, q_h2{}; + GateQuantFP8 gq{}; + rad_op op_n1 = 0, op_qkr = 0, op_attn = 0, op_ar1 = 0, op_add1 = 0; + rad_op op_n2 = 0, op_ar2 = 0, op_add2 = 0; +}; + +struct DitLayer { + rad_weight w_qn = 0, w_kn = 0; + LinearFP8 qkv{}, o{}, gate_up{}, down{}; + QuantFP8 q_h{}, q_attn{}, q_h2{}; + GateQuantFP8 gq{}; + rad_op op_ln1 = 0, op_qkr = 0, op_kv = 0, op_attn_c = 0, op_attn_b = 0, op_ar1 = 0; + rad_op op_g1 = 0, op_ln2 = 0, op_ar2 = 0, op_g2 = 0; + /* The two all-reduces as a split pass issues them, on the second lane (step_blocks). */ + rad_op op_ar1h = 0, op_ar2h = 0; + /* The fp8 DiT's two norms with the gated residual in front of each folded in + * (ln_mod_quant_fp8): the first takes the previous block's MLP branch, the second this + * block's attention branch. */ + rad_op op_lnq1 = 0, op_lnq2 = 0; + /* The fp8 DiT's denoising attention in its int8 Q.K form, and the quantiser that gives it the + * keys. */ + rad_op op_kq = 0, op_attn_q = 0; +}; + +struct Model { + Names nm{""}; + Geom gt{}, gd{}; /* the language model's and the DiT's geometry, per rank */ + int64_t max_ref_rows = 0; /* every reference picture's latent tokens together */ + int64_t n_cond_max = 0; /* conditioning rows: the text, or one picture's latents */ + bool media = false; + VisionTower vit{}; + rad_kvgroup kv = 0; + + /* ---- the language model */ + rad_weight w_tok = 0; + rad_op op_embed = 0, op_mm = 0, op_ds[VisionTower::MAX_DS] = {}; + rad_buf b_tx = 0, b_tq = 0, b_tkv = 0, b_th2 = 0, b_tgu = 0; + ActFP8 a_th{}, a_tattn{}, a_tffn{}; + std::vector te; + + /* ---- txt_in: ZeroCenter RMSNorm (1 + w), a linear, gelu_tanh, a linear */ + rad_weight w_txn = 0, w_tx1 = 0, w_tx2 = 0; + rad_op op_txn = 0, op_tx1 = 0, op_txg = 0, op_tx2 = 0; + rad_buf b_txa = 0, b_txb = 0, b_txt = 0; + + /* ---- the timestep and the shared modulation */ + rad_weight w_t1 = 0, w_t2 = 0, w_mod = 0, w_nout = 0; + rad_op op_temb = 0, op_t1 = 0, op_ts = 0, op_t2 = 0, op_ts2 = 0, op_mod = 0, op_nout = 0; + rad_buf b_tproj = 0, b_te1 = 0, b_te1s = 0, b_temb = 0, b_tembs = 0, b_mod = 0, b_modo = 0; + + /* ---- the DiT's input */ + rad_weight w_imgin = 0; + rad_op op_gather = 0, op_imgin = 0, op_randn = 0, op_lgather = 0; + rad_buf b_lat = 0; + /* ---- the DiT */ + rad_buf b_h = 0, b_qkv = 0, b_ao = 0, b_gu = 0; + rad_buf b_k8 = 0, b_ks = 0; /* the keys at int8 codes and their per-head scales */ + ActFP8 a_hm{}, a_attn{}, a_ffn{}; + std::vector dit; + LinearFP8 qkv0{}; /* layer 0's qkv, as the probe that chose bf16 or fp8 mapped it */ + int64_t C = 64; /* latent channels */ + rad_weight w_pout = 0; + rad_op op_nout_ln = 0, op_pout = 0, op_euler = 0; + rad_buf b_v = 0; + + /* ---- the per-image state (PERSIST) and what crosses passes */ + rad_buf b_state = 0, b_prev = 0, b_inp = 0, b_mask = 0, b_img = 0, b_txt_keep = 0, b_reflat = 0; + rad_op op_lstore_lat = 0, op_lstore_mask = 0, op_enc_aff = 0, op_dec_aff = 0, op_rgba = 0; + /* More than one rank: the decoder's bands gathered, and the bytes made from the gather. */ + rad_op op_bands = 0, op_rgba_bands = 0; + + /* ---- the VAE */ + Vae enc{}, dec{}; + VImg enc_in{}, enc_q{}, dec_z{}, dec_out{}; + rad_buf b_encz = 0, b_decin = 0, b_rgbaf = 0; + std::string lat_mean, lat_std; +}; + +static Model g_model[MAX_RANKS]; + +/* A space-separated list off the container (rad-convert flattens arrays that way). */ +static std::vector meta_list(const RadModelMeta* m, const char* key) { + std::vector v; + const char* s = rad_meta_gets(m, key, nullptr); + while (s && *s) { + char* e = nullptr; + const double x = std::strtod(s, &e); + if (e == s) { ++s; continue; } + v.push_back(x); + s = e; + } + return v; +} + +/* A bf16 linear read whole on every rank: `gemm_nt`, no bias. */ +static rad_op dense(RadBuilder* b, Names& nm, const char* dn, const char* src, int64_t N, int64_t K, + int64_t rows, rad_buf in, rad_buf out, rad_weight* w, int group) { + if (map_copy(b, dn, src) < 0) return 0; + *w = decl_w(b, dn, RAD_BF16, { N, K }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(group)); + if (!*w) return 0; + (void)nm; + return rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(*w)), + { in }, { out }); +} + +static rad_op unary(RadBuilder* b, const char* op, int64_t rows, int64_t n, rad_buf in, rad_buf out) { + return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { in }, { out }); +} + +/* `overlap`: issued on the second lane beside compute, which picks a narrow launch. */ +static rad_op all_reduce(RadBuilder* b, const Geom& g, rad_buf x, int64_t rows, + bool overlap = false) { + if (g.world <= 1) return 0; + return rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", g.n_embd, rows * g.n_embd), + RAD_STR("dtype", "bf16"), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes), + RAD_INT("overlap", overlap ? 1 : 0)), + RAD_NOWEIGHTS), + { x }, { x }); +} + +/* ================================================================== check_format */ +static int check_format(const RadModelMeta* meta) { + const char* arch = rad_meta_gets(meta, "pipeline._class_name", ""); + if (std::strcmp(arch, "QwenImage21Pipeline") != 0) { + fprintf(stderr, "radiance: qwenimage21: the container's pipeline is '%s', not " + "QwenImage21Pipeline\n", arch); + return RAD_E_UNSUPPORTED; + } + if (rad_meta_geti(meta, "transformer.patch_size", 1) != 1 || + rad_meta_geti(meta, "transformer.causal_condition", 1) != 1 || + rad_meta_geti(meta, "vae.is_residual", 0) != 1 || + rad_meta_geti(meta, "vae.z_dim", 0) != 64) { + fprintf(stderr, "radiance: qwenimage21: the DiT must be patch 1 with causal conditioning and " + "the VAE the residual 64-channel one\n"); + return RAD_E_UNSUPPORTED; + } + return RAD_OK; +} + +/* ================================================================== declare */ +static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Geom& g = m.gt; + Names& nm = m.nm; + const int64_t T = g.max_tok; + const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(); + + /* The embedding is REPLICATED: a rank looks up every token itself, so no collective sums it, + * and the rows the vision tower replaces are overwritten on every rank alike. */ + RAD_ARCH_TRY(map_copy(b, nm.f("te.token_embd.weight"), + nm.ckpt("model.language_model.embed_tokens.weight"))); + m.w_tok = decl_w(b, nm.f("te.token_embd.weight"), RAD_BF16, { g.n_vocab_all, g.n_embd }, + RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model()); + m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, g.n_embd }); + m.a_th.x = decl_b(b, nm.f("te.h"), RAD_BF16, { T, g.n_embd }); + RAD_ARCH_TRY(m.a_th.declare_qs(b, nm, g, "te.h", g.n_embd)); + m.b_tkv = decl_b(b, nm.f("te.qkv"), RAD_BF16, { T, q_dim + 2 * kv_dim }); + m.a_tattn.x = decl_b(b, nm.f("te.attn"), RAD_BF16, { T, q_dim }); + RAD_ARCH_TRY(m.a_tattn.declare_qs(b, nm, g, "te.attn", q_dim)); + m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, g.n_embd }); + m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * g.n_ff }); + m.a_tffn.x = decl_b(b, nm.f("te.ffn"), RAD_BF16, { T, g.n_ff }); + RAD_ARCH_TRY(m.a_tffn.declare_qs(b, nm, g, "te.ffn", g.n_ff)); + + m.op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", g.n_embd), + RAD_INT("n_vocab", g.n_vocab_all), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", 0)), + RAD_WEIGHTS(m.w_tok)), + {}, { m.b_tx }); + if (m.media) { + m.op_mm = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.vit.b_out, m.b_tx }, { m.b_tx }); + for (int t = 0; t < m.vit.n_ds; ++t) + m.op_ds[t] = rw(b, RAD_OP(b, "scatter_add_rows", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.vit.b_ds[t], m.b_tx }, { m.b_tx }); + } + + /* Qwen3-VL's text attention: plain RMSNorm gains (no `1 +`), q/k head norms, interleaved + * M-RoPE over three position components. */ + const std::vector sec = meta_list(meta, "text_config.rope_scaling.mrope_section"); + char sections[48]; + if (sec.size() == 3) + std::snprintf(sections, sizeof sections, "%d %d %d", (int)sec[0], (int)sec[1], (int)sec[2]); + else + std::snprintf(sections, sizeof sections, "24 20 20"); + + m.te.resize((size_t)g.n_layer); + for (int64_t l = 0; l < g.n_layer; ++l) { + TeLayer& L = m.te[(size_t)l]; + const int li = (int)l; + const char* pre = "model.language_model.layers"; + RAD_ARCH_TRY(map_copy(b, nm.f("te.blk.%d.attn_norm.weight", li), + nm.ckpt("%s.%d.input_layernorm.weight", pre, li))); + L.w_n1 = decl_w(b, nm.f("te.blk.%d.attn_norm.weight", li), RAD_F32, { g.n_embd }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(li)); + RAD_ARCH_TRY(map_copy(b, nm.f("te.blk.%d.ffn_norm.weight", li), + nm.ckpt("%s.%d.post_attention_layernorm.weight", pre, li))); + L.w_n2 = decl_w(b, nm.f("te.blk.%d.ffn_norm.weight", li), RAD_F32, { g.n_embd }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(li)); + RAD_ARCH_TRY(map_copy(b, nm.f("te.blk.%d.q_norm.weight", li), + nm.ckpt("%s.%d.self_attn.q_norm.weight", pre, li))); + L.w_qn = decl_w(b, nm.f("te.blk.%d.q_norm.weight", li), RAD_BF16, { g.head_dim }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(li)); + RAD_ARCH_TRY(map_copy(b, nm.f("te.blk.%d.k_norm.weight", li), + nm.ckpt("%s.%d.self_attn.k_norm.weight", pre, li))); + L.w_kn = decl_w(b, nm.f("te.blk.%d.k_norm.weight", li), RAD_BF16, { g.head_dim }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(li)); + + L.op_n1 = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(L.w_n1)), + { m.b_tx }, { m.a_th.x }); + RAD_ARCH_TRY(L.q_h.declare(b, g, m.a_th, g.n_embd)); + RAD_ARCH_TRY(L.qkv.declare(b, nm, g, nm.f("te.blk.%d.attn_qkv", li), q_dim + 2 * kv_dim, + g.n_embd, RAD_SHARD_ROW, grp_layer(li), + { nm.ckpt("%s.%d.self_attn.q_proj.weight", pre, li), + nm.ckpt("%s.%d.self_attn.k_proj.weight", pre, li), + nm.ckpt("%s.%d.self_attn.v_proj.weight", pre, li) }, + m.a_th, m.b_tkv, 0, { q_dim, kv_dim, kv_dim })); + L.op_qkr = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", g.n_head), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_F64("theta", g.theta), RAD_F64("eps", g.eps), + RAD_STR("mode", "imrope"), + RAD_INT("rotary_dim", g.head_dim), + RAD_STR("sections", nm.f("%s", sections))), + RAD_WEIGHTS(L.w_qn, L.w_kn)), + { m.b_tkv }, { m.b_tkv }); + L.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim), + RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)g.head_dim)), + RAD_INT("max_seqlen", T)), + RAD_NOWEIGHTS), + { m.b_tkv }, { m.a_tattn.x }); + RAD_ARCH_TRY(L.q_attn.declare(b, g, m.a_tattn, q_dim)); + RAD_ARCH_TRY(L.o.declare(b, nm, g, nm.f("te.blk.%d.attn_output", li), g.n_embd, q_dim, + RAD_SHARD_COL, grp_layer(li), + { nm.ckpt("%s.%d.self_attn.o_proj.weight", pre, li) }, + m.a_tattn, m.b_th2)); + L.op_ar1 = all_reduce(b, g, m.b_th2, T); + L.op_add1 = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_tx, m.b_th2 }, { m.b_tx }); + L.op_n2 = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(L.w_n2)), + { m.b_tx }, { m.a_th.x }); + RAD_ARCH_TRY(L.q_h2.declare(b, g, m.a_th, g.n_embd)); + RAD_ARCH_TRY(L.gate_up.declare(b, nm, g, nm.f("te.blk.%d.ffn_gate_up", li), 2 * g.n_ff, + g.n_embd, RAD_SHARD_ROW, grp_layer(li), + { nm.ckpt("%s.%d.mlp.gate_proj.weight", pre, li), + nm.ckpt("%s.%d.mlp.up_proj.weight", pre, li) }, + m.a_th, m.b_tgu, 0, { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(L.gq.declare(b, g, m.b_tgu, m.a_tffn, g.n_ff, "silu", 0, true)); + RAD_ARCH_TRY(L.down.declare(b, nm, g, nm.f("te.blk.%d.ffn_down", li), g.n_embd, g.n_ff, + RAD_SHARD_COL, grp_layer(li), + { nm.ckpt("%s.%d.mlp.down_proj.weight", pre, li) }, + m.a_tffn, m.b_th2)); + L.op_ar2 = all_reduce(b, g, m.b_th2, T); + L.op_add2 = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_tx, m.b_th2 }, { m.b_tx }); + } + + /* ---- txt_in, over every prompt row. Its output crosses the conditioning's segments, each of + * which runs the DiT's blocks over the same buffers, so it is PERSIST. */ + const int gti = 1000; + const int64_t D = m.gd.n_embd; + m.b_txa = decl_b(b, nm.f("txt.a"), RAD_BF16, { T, D }); + m.b_txb = decl_b(b, nm.f("txt.b"), RAD_BF16, { T, D }); + m.b_txt = decl_b(b, nm.f("txt.out"), RAD_BF16, { T, D }, RAD_BUF_PERSIST); + RAD_ARCH_TRY(map_copy(b, nm.f("txt.norm.weight"), nm.ckpt("transformer.txt_in.text_norm.weight"))); + m.w_txn = decl_w(b, nm.f("txt.norm.weight"), RAD_F32, { g.n_embd }, RAD_ACCESS_PER_REQUEST, + RAD_SHARD_NONE, grp_layer(gti)); + /* ZeroCenterRMSNorm: the effective gain is 1 + w, in f32 -- rmsnorm's `wadd`. */ + m.op_txn = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd), + RAD_F64("eps", rad_meta_getf(meta, "transformer.eps", 1e-6)), + RAD_STR("dtype", "bf16"), RAD_F64("wadd", 1.0)), + RAD_WEIGHTS(m.w_txn)), + { m.b_tx }, { m.b_txa }); + m.op_tx1 = dense(b, nm, nm.f("txt.in.weight"), nm.ckpt("transformer.txt_in.in_layer.weight"), + D, g.n_embd, T, m.b_txa, m.b_txb, &m.w_tx1, gti); + m.op_txg = unary(b, "gelu_tanh", T, D, m.b_txb, m.b_txa); + m.op_tx2 = dense(b, nm, nm.f("txt.out.weight"), nm.ckpt("transformer.txt_in.out_layer.weight"), + D, D, T, m.b_txa, m.b_txt, &m.w_tx2, gti); + if (!m.op_tx1 || !m.op_txg || !m.op_tx2 || !m.op_txn) return RAD_E_INVAL; + return RAD_OK; +} + +/* The VAE encoder (Wan 2.2's residual one on a single frame) and the latent's normalisation. */ +static int declare_encoder(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Vae& v = m.enc; + v.nm = &m.nm; + v.b = b; + v.scope = "venc"; + v.down = true; + v.first_group = 1100; + /* The largest picture the encoder reads: a repainted one at the largest output size. */ + v.base_px = (int64_t)kMaxImageTokens * 256; + const int64_t base = rad_meta_geti(meta, "vae.base_dim", 96); + const std::vector mult = meta_list(meta, "vae.dim_mult"); + const std::vector td = meta_list(meta, "vae.temperal_downsample"); + const int64_t nres = rad_meta_geti(meta, "vae.num_res_blocks", 2); + const int64_t zd = rad_meta_geti(meta, "vae.z_dim", 64); + const int64_t cin = rad_meta_geti(meta, "vae.in_channels", 4); + if (mult.size() != 5 || td.size() != 4) { + fprintf(stderr, "radiance: qwenimage21: vae.dim_mult / vae.temperal_downsample are not the " + "five-level residual VAE's\n"); + return RAD_E_INVAL; + } + std::vector dims{ base }; + for (double u : mult) dims.push_back(base * (int64_t)u); + Names& nm = m.nm; + m.enc_in = VImg{ 0, cin, 0 }; + VImg x = v.conv(m.enc_in, dims[0], 3, 1, 1, "same", "vae.encoder.conv_in"); + for (int i = 0; i < 5; ++i) { + const VImg xc = x; + const bool dn = i != 4; + for (int r = 0; r < nres; ++r) + x = v.resblock(x, dims[(size_t)i + 1], nm.f("vae.encoder.down_blocks.%d.resnets.%d", i, r)); + if (dn) { + x = v.conv(x, dims[(size_t)i + 1], 3, 2, 1, "down", + nm.f("vae.encoder.down_blocks.%d.downsampler.resample.1", i)); + v.shortcut(xc, x, td[(size_t)i] != 0.0 ? 2 : 1); + } else { + x = v.add(x, xc); + } + } + x = v.resblock(x, dims[5], "vae.encoder.mid_block.resnets.0"); + x = v.attention(x, "vae.encoder.mid_block.attentions.0"); + x = v.resblock(x, dims[5], "vae.encoder.mid_block.resnets.1"); + x = v.norm(x, true, "vae.encoder.norm_out", 4); + x = v.conv(x, 2 * zd, 3, 1, 1, "same", "vae.encoder.conv_out"); + m.enc_q = v.conv(x, 2 * zd, 1, 1, 1, "same", "vae.quant_conv"); + /* The latent is the distribution's mode -- the first z channels -- normalised by the + * container's per-channel mean and deviation, into the persistent reference latents. */ + m.op_enc_aff = rw(b, RAD_OP(b, "chan_affine", + RAD_PARAMS(RAD_RANGE("M", 1, v.px_at(m.enc_q.lvl)), RAD_INT("n", zd), + RAD_STR("mul", m.lat_std.c_str()), + RAD_STR("add", m.lat_mean.c_str()), + RAD_STR("mode", "inv"), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.enc_q.buf }, { m.b_reflat, m.b_encz }); + /* A repainted picture's latent and its mask, into every lane its images run in. */ + m.op_lstore_lat = rw(b, RAD_OP(b, "lane_store", + RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)kMaxImageTokens), + RAD_INT("n", zd), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_encz, m.b_inp }, { m.b_inp }); + m.op_lstore_mask = rw(b, RAD_OP(b, "lane_store", + RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)kMaxImageTokens), + RAD_INT("n", 1), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { m.b_mask }, { m.b_mask }); + return m.op_enc_aff && m.op_lstore_lat && m.op_lstore_mask ? RAD_OK : RAD_E_INVAL; +} + +static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Vae& v = m.dec; + v.nm = &m.nm; + v.b = b; + v.scope = "vdec"; + v.down = false; + v.first_group = 1200; + v.base_px = kMaxImageTokens; + const int64_t base = rad_meta_geti(meta, "vae.decoder_base_dim", 144); + const std::vector mult = meta_list(meta, "vae.dim_mult"); + const std::vector td = meta_list(meta, "vae.temperal_downsample"); + const int64_t nres = rad_meta_geti(meta, "vae.num_res_blocks", 2); + const int64_t zd = rad_meta_geti(meta, "vae.z_dim", 64); + const int64_t cout = rad_meta_geti(meta, "vae.out_channels", 4); + if (mult.size() != 5 || td.size() != 4) return RAD_E_INVAL; + /* dims = base * [mult[-1]] + mult reversed; the temporal upsample flags are the downsample + * ones reversed, and on one frame they only choose the shortcut's frame (ft). */ + std::vector dims{ base * (int64_t)mult.back() }; + for (int i = 4; i >= 0; --i) dims.push_back(base * (int64_t)mult[(size_t)i]); + std::vector tu(td.rbegin(), td.rend()); + Names& nm = m.nm; + m.b_decin = decl_b(b, nm.f("vdec.lat"), RAD_BF16, { v.base_px, zd }); + m.op_dec_aff = rw(b, RAD_OP(b, "chan_affine", + RAD_PARAMS(RAD_RANGE("M", 1, v.base_px), RAD_INT("n", zd), + RAD_STR("mul", m.lat_std.c_str()), + RAD_STR("add", m.lat_mean.c_str()), + RAD_STR("mode", "fma"), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_state, m.b_prev }, { m.b_decin }); + m.dec_z = VImg{ m.b_decin, zd, 0 }; + VImg x = v.conv(m.dec_z, zd, 1, 1, 1, "same", "vae.post_quant_conv"); + x = v.conv(x, dims[0], 3, 1, 1, "same", "vae.decoder.conv_in"); + x = v.resblock(x, dims[0], "vae.decoder.mid_block.resnets.0"); + x = v.attention(x, "vae.decoder.mid_block.attentions.0"); + x = v.resblock(x, dims[0], "vae.decoder.mid_block.resnets.1"); + v.band_from = (int)v.ops.size(); + v.whole.push_back(m.b_decin); + for (const VOp& o : v.ops) v.whole.push_back(o.y.buf); + for (int i = 0; i < 5; ++i) { + const VImg xc = x; + const bool upf = i != 4; + for (int r = 0; r < nres + 1; ++r) + x = v.resblock(x, dims[(size_t)i + 1], nm.f("vae.decoder.up_blocks.%d.resnets.%d", i, r)); + if (upf) { + x = v.conv(x, dims[(size_t)i + 1], 3, 1, 2, "same", + nm.f("vae.decoder.up_blocks.%d.upsampler.resample.1", i)); + v.shortcut(xc, x, tu[(size_t)i] != 0.0 ? 2 : 1); + } + } + x = v.norm(x, true, "vae.decoder.norm_out", 4); + m.dec_out = v.conv(x, cout, 3, 1, 1, "same", "vae.decoder.conv_out"); + m.b_img = decl_b(b, nm.f("image_out"), RAD_U8, { (int64_t)kMaxImageTokens * 256 * cout }, + RAD_BUF_PERSIST); + m.op_rgba = rw(b, RAD_OP(b, "to_rgba8", + RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)kMaxImageTokens * 256), + RAD_INT("n", cout), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.dec_out.buf }, { m.b_img }); + if (!m.op_rgba) return RAD_E_INVAL; + v.halo = v.band_halo(); + if (v.halo <= 0) { + fprintf(stderr, "radiance: qwenimage21: the decoder after its mid-block is not row-local\n"); + return RAD_E_INVAL; + } + /* THE BANDS, GATHERED. A band is ceil(H / world) latent rows and the split is taken only where + * a band and its two halos are under the whole -- so H > 2 * halo, which bounds W and with it + * the largest band: under kMaxImageTokens / world + kMaxImageTokens / (2 * halo) tokens. */ + const int world = m.gt.world; + if (world > 1) { + const int64_t bpx = (kMaxImageTokens / world + kMaxImageTokens / (2 * v.halo) + 1) * 256; + m.b_rgbaf = decl_b(b, nm.f("vdec.bands"), RAD_BF16, { world * bpx, cout }); + m.op_bands = rw(b, RAD_OP(b, "all_gather", + RAD_PARAMS(RAD_INT("world_size", world), + RAD_RANGE("numel", 1, bpx * cout), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.dec_out.buf }, { m.b_rgbaf }); + m.op_rgba_bands = rw(b, RAD_OP(b, "to_rgba8", + RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)kMaxImageTokens * 256), + RAD_INT("n", cout), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_rgbaf }, { m.b_img }); + if (!m.op_bands || !m.op_rgba_bands) return RAD_E_INVAL; + } + return RAD_OK; +} + +static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Geom& g = m.gd; + Names& nm = m.nm; + const int64_t T = g.max_tok; + const int64_t D = g.n_embd, hd = g.head_dim, qd = g.q_dim(); + const int64_t C = rad_meta_geti(meta, "transformer.in_channels", 64); + const int gx = 2000; /* the DiT's model-level weights' group; its blocks are 2001.. */ + + /* ---- the timestep: [cos | sin] of t * 1000 over 256 channels, an MLP to D, then the shared + * modulation (four D-wide rows) and norm_out's scale, each through a silu. */ + const int64_t S = g.max_seqs; + m.b_tproj = decl_b(b, nm.f("dit.tproj"), RAD_BF16, { S, 256 }); + m.b_te1 = decl_b(b, nm.f("dit.te1"), RAD_BF16, { S, D }); + m.b_te1s = decl_b(b, nm.f("dit.te1s"), RAD_BF16, { S, D }); + m.b_temb = decl_b(b, nm.f("dit.temb"), RAD_BF16, { S, D }); + m.b_tembs = decl_b(b, nm.f("dit.tembs"), RAD_BF16, { S, D }); + m.b_mod = decl_b(b, nm.f("dit.mod"), RAD_BF16, { S, 4 * D }); + m.b_modo = decl_b(b, nm.f("dit.mod_out"), RAD_BF16, { S, D }); + m.op_temb = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", 256), + RAD_F64("scale", 1000.0), RAD_F64("max_period", 10000.0), + RAD_INT("round", 1), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {}, { m.b_tproj }); + m.op_t1 = dense(b, nm, nm.f("dit.t1.weight"), + nm.ckpt("transformer.time_text_embed.timestep_embedder.linear_1.weight"), D, 256, + S, m.b_tproj, m.b_te1, &m.w_t1, gx); + m.op_ts = unary(b, "silu", S, D, m.b_te1, m.b_te1s); + m.op_t2 = dense(b, nm, nm.f("dit.t2.weight"), + nm.ckpt("transformer.time_text_embed.timestep_embedder.linear_2.weight"), D, D, + S, m.b_te1s, m.b_temb, &m.w_t2, gx); + m.op_ts2 = unary(b, "silu", S, D, m.b_temb, m.b_tembs); + m.op_mod = dense(b, nm, nm.f("dit.mod.weight"), nm.ckpt("transformer.modulation.1.weight"), + 4 * D, D, S, m.b_tembs, m.b_mod, &m.w_mod, gx); + m.op_nout = dense(b, nm, nm.f("dit.nout.weight"), nm.ckpt("transformer.norm_out.linear.weight"), + D, D, S, m.b_tembs, m.b_modo, &m.w_nout, gx); + if (!m.op_temb || !m.op_t1 || !m.op_ts || !m.op_t2 || !m.op_ts2 || !m.op_mod || !m.op_nout) + return RAD_E_INVAL; + + /* ---- the input rows: a text segment gathered out of txt_in's output, a picture's latents + * (or the image's own, a lane at a time) through img_in. */ + m.b_h = decl_b(b, nm.f("dit.h"), RAD_BF16, { T, D }); + m.b_lat = decl_b(b, nm.f("dit.lat"), RAD_BF16, { T, C }); + m.op_gather = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_txt }, { m.b_h }); + m.op_randn = rw(b, RAD_OP(b, "randn_lanes", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", C), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_state }, { m.b_state }); + m.op_lgather = rw(b, RAD_OP(b, "lane_gather", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", C), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_state }, { m.b_lat }); + m.op_imgin = dense(b, nm, nm.f("dit.img_in.weight"), nm.ckpt("transformer.img_in.weight"), D, + C, T, m.b_lat, m.b_h, &m.w_imgin, gx); + if (!m.op_gather || !m.op_randn || !m.op_lgather || !m.op_imgin) return RAD_E_INVAL; + /* The reference pictures' latents go through img_in where they lie. */ + rw(b, m.op_imgin, { m.b_reflat }, {}); + + /* ---- the blocks */ + m.a_hm.x = decl_b(b, nm.f("dit.hm"), RAD_BF16, { T, D }); + RAD_ARCH_TRY(m.a_hm.declare_qs(b, nm, g, "dit.hm", D)); + m.b_qkv = decl_b(b, nm.f("dit.qkv"), RAD_BF16, { T, 3 * qd }); + m.a_attn.x = decl_b(b, nm.f("dit.attn"), RAD_BF16, { T, qd }); + RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "dit.attn", qd)); + m.b_ao = decl_b(b, nm.f("dit.ao"), RAD_BF16, { T, D }); + /* More than one rank: the all-reduces of b_ao's halves run on the second lane (step_blocks). */ + if (g.world > 1) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_ao)); + m.b_gu = decl_b(b, nm.f("dit.gate_up"), RAD_BF16, { T, 2 * g.n_ff }); + m.a_ffn.x = decl_b(b, nm.f("dit.ffn"), RAD_BF16, { T, g.n_ff }); + RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "dit.ffn", g.n_ff)); + + /* The rotary: three sections of adjacent pairs, (frame, row, column), each on its own ladder. */ + const std::vector ax = meta_list(meta, "transformer.axes_dims_rope"); + if (ax.size() != 3 || (int64_t)(ax[0] + ax[1] + ax[2]) != hd) { + fprintf(stderr, "radiance: qwenimage21: transformer.axes_dims_rope must be three widths " + "summing to the head\n"); + return RAD_E_INVAL; + } + const char* sections = nm.f("%d %d %d", (int)ax[0] / 2, (int)ax[1] / 2, (int)ax[2] / 2); + const double eps = rad_meta_getf(meta, "transformer.eps", 1e-6); + + auto ln_mod = [&](rad_buf x, rad_buf y) { + return rw(b, RAD_OP(b, "ln_mod", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), RAD_F64("eps", eps), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { x, m.b_mod, m.b_modo }, { y }); + }; + auto gate_add = [&](rad_buf y, rad_buf x) { + return rw(b, RAD_OP(b, "gate_add", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { y, m.b_mod, x }, { x }); + }; + /* gate_add, ln_mod and the quantiser as one op, where the linears are fp8: `delta` is the + * branch the norm adds in first, none for the first block's. */ + const bool fuse_norm = !g.w_bf16; + auto ln_mod_q = [&](rad_buf delta) { + rad_op op = RAD_OP(b, "ln_mod_quant_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), RAD_F64("eps", eps), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_INT("gated", delta ? 1 : 0), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS); + if (!op) return op; + rad_buf rd[3] = { m.b_mod, m.b_h, delta }; + rad_buf wr[3] = { m.a_hm.cq(), m.a_hm.cs(), m.b_h }; + rad_op_reads(b, op, rd, delta ? 3 : 2); + rad_op_writes(b, op, wr, 3); + return op; + }; + auto attn = [&](int causal, bool i8) { + rad_op op = RAD_OP(b, "attn_prefix_self", + RAD_PARAMS(RAD_INT("q_len", T), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("block_size", RAD_KV_BLOCK), + RAD_INT("causal", causal), RAD_STR("q_dtype", "bf16"), + RAD_STR("kv_dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)hd)), + RAD_INT("max_ctx", g.max_ctx), RAD_INT("n_head", g.n_head), + RAD_INT("max_seqs", g.max_seqs), + RAD_STR("qk", i8 ? "i8" : "bf16")), + RAD_NOWEIGHTS); + return i8 ? rw(b, op, { m.b_qkv, m.b_k8, m.b_ks }, { m.a_attn.x }) + : rw(b, op, { m.b_qkv }, { m.a_attn.x }); + }; + /* THE DENOISING ATTENTION'S SCORES IN INT8 where the linears are fp8: the keys quantised per + * (token, head) by quant_act_i8g, the query inside the op. The score product is about half the + * attention's issue and runs at twice the rate in int8; the picture moves by less than it moves + * between two exact attention implementations (Qwen-Image 2.1 at 1024^2 in diffusers, int8 + * scores against exact ones: 36.2 dB PSNR, where diffusers' own SDPA kernels differ from each + * other by 32.6 to 34.4). The conditioning pass, run once a request, keeps bf16, and so does a + * bf16 container. */ + const bool qk8 = !g.w_bf16; + if (qk8) { + m.b_k8 = decl_b(b, nm.f("dit.k8"), RAD_I8, { T, qd }); + m.b_ks = decl_b(b, nm.f("dit.ks"), RAD_F32, { T, qd / hd }); + } + + m.dit.resize((size_t)g.n_layer); + for (int64_t l = 0; l < g.n_layer; ++l) { + DitLayer& L = m.dit[(size_t)l]; + const int li = (int)l; + const int grp = 2001 + li; + const char* pre = "transformer.transformer_blocks"; + RAD_ARCH_TRY(rad_bind_layer_kv(b, li, m.kv)); + RAD_ARCH_TRY(map_copy(b, nm.f("dit.blk.%d.q_norm.weight", li), + nm.ckpt("%s.%d.attn.norm_q.weight", pre, li))); + L.w_qn = decl_w(b, nm.f("dit.blk.%d.q_norm.weight", li), RAD_BF16, { hd }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(grp)); + RAD_ARCH_TRY(map_copy(b, nm.f("dit.blk.%d.k_norm.weight", li), + nm.ckpt("%s.%d.attn.norm_k.weight", pre, li))); + L.w_kn = decl_w(b, nm.f("dit.blk.%d.k_norm.weight", li), RAD_BF16, { hd }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(grp)); + + if (fuse_norm) { + L.op_lnq1 = ln_mod_q(l > 0 ? m.b_ao : 0); + } else { + L.op_ln1 = ln_mod(m.b_h, m.a_hm.x); + RAD_ARCH_TRY(L.q_h.declare(b, g, m.a_hm, D)); + } + if (l == 0) L.qkv = m.qkv0; + RAD_ARCH_TRY(L.qkv.declare(b, nm, g, nm.f("dit.blk.%d.attn_qkv", li), 3 * qd, D, + RAD_SHARD_ROW, grp_layer(grp), + { nm.ckpt("%s.%d.attn.to_q.weight", pre, li), + nm.ckpt("%s.%d.attn.to_k.weight", pre, li), + nm.ckpt("%s.%d.attn.to_v.weight", pre, li) }, + m.a_hm, m.b_qkv, 0, { qd, qd, qd })); + L.op_qkr = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd), + RAD_INT("n_head", g.n_head), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_F64("theta", 10000.0), RAD_F64("eps", eps), + RAD_STR("mode", "gptj_blocks"), + RAD_INT("rotary_dim", hd), + RAD_STR("sections", sections)), + RAD_WEIGHTS(L.w_qn, L.w_kn)), + { m.b_qkv }, { m.b_qkv }); + /* The attention first: the KV group's block size is read off the op that consumes it. */ + L.op_attn_c = attn(1, false); + L.op_attn_b = attn(0, false); + if (qk8) { + L.op_attn_q = attn(0, true); + L.op_kq = rw(b, RAD_OP(b, "quant_act_i8g", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", qd), + RAD_INT("group", hd), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_qkv }, { m.b_k8, m.b_ks }); + if (!L.op_attn_q || !L.op_kq) return RAD_E_INVAL; + } + L.op_kv = rw(b, RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_INT("block_size", rad_kv_block_size(b, m.kv)), + RAD_STR("kv_dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_qkv }, {}); + RAD_ARCH_TRY(L.q_attn.declare(b, g, m.a_attn, qd)); + RAD_ARCH_TRY(L.o.declare(b, nm, g, nm.f("dit.blk.%d.attn_output", li), D, qd, + RAD_SHARD_COL, grp_layer(grp), + { nm.ckpt("%s.%d.attn.to_out.0.weight", pre, li) }, + m.a_attn, m.b_ao)); + L.op_ar1 = all_reduce(b, g, m.b_ao, T); + L.op_ar1h = all_reduce(b, g, m.b_ao, T, true); + if (fuse_norm) { + L.op_lnq2 = ln_mod_q(m.b_ao); + } else { + L.op_g1 = gate_add(m.b_ao, m.b_h); + L.op_ln2 = ln_mod(m.b_h, m.a_hm.x); + RAD_ARCH_TRY(L.q_h2.declare(b, g, m.a_hm, D)); + } + RAD_ARCH_TRY(L.gate_up.declare(b, nm, g, nm.f("dit.blk.%d.ffn_gate_up", li), 2 * g.n_ff, + D, RAD_SHARD_ROW, grp_layer(grp), + { nm.ckpt("%s.%d.img_mlp.gate_layer.weight", pre, li), + nm.ckpt("%s.%d.img_mlp.proj.weight", pre, li) }, + m.a_hm, m.b_gu, 0, { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(L.gq.declare(b, g, m.b_gu, m.a_ffn, g.n_ff, "silu", 0, true)); + RAD_ARCH_TRY(L.down.declare(b, nm, g, nm.f("dit.blk.%d.ffn_down", li), D, g.n_ff, + RAD_SHARD_COL, grp_layer(grp), + { nm.ckpt("%s.%d.img_mlp.out.weight", pre, li) }, + m.a_ffn, m.b_ao)); + L.op_ar2 = all_reduce(b, g, m.b_ao, T); + L.op_ar2h = all_reduce(b, g, m.b_ao, T, true); + /* Folded into the next block's first norm, except after the last block. */ + if (!fuse_norm || l + 1 == g.n_layer) L.op_g2 = gate_add(m.b_ao, m.b_h); + } + + /* ---- the output: norm_out's adaptive norm, proj_out, and the sampler's step */ + m.op_nout_ln = ln_mod(m.b_h, m.a_hm.x); + m.b_v = decl_b(b, nm.f("dit.v"), RAD_BF16, { T, C }); + m.op_pout = dense(b, nm, nm.f("dit.proj_out.weight"), nm.ckpt("transformer.proj_out.weight"), + C, D, T, m.a_hm.x, m.b_v, &m.w_pout, gx); + m.op_euler = rw(b, RAD_OP(b, "flow_euler", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", C), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_v, m.b_inp, m.b_mask, m.b_state, m.b_prev }, { m.b_state, m.b_prev }); + return m.op_pout && m.op_euler ? RAD_OK : RAD_E_INVAL; +} + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + Model& m = g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope); + RAD_ARCH_TRY(check_format(meta)); + RAD_ARCH_TRY(geom_from(m.gt, meta, ctx, "bf16", RAD_BF16)); + Names& nm = m.nm; + + /* ---- the DiT's geometry, off the transformer's own config */ + Geom& gd = m.gd; + gd = m.gt; + gd.n_layer = rad_meta_geti(meta, "transformer.num_layers", 32); + gd.head_dim = rad_meta_geti(meta, "transformer.attention_head_dim", 128); + gd.n_head_all = rad_meta_geti(meta, "transformer.num_attention_heads", 32); + gd.n_head_kv_all = gd.n_head_all; + gd.n_embd = gd.head_dim * gd.n_head_all; + gd.n_ff_all = gd.n_embd * rad_meta_geti(meta, "transformer.mlp_ratio", 3); + gd.eps = (float)rad_meta_getf(meta, "transformer.eps", 1e-6); + gd.theta = 10000.0f; + gd.rope_mc = false; + RAD_ARCH_TRY(divide_or_fail(gd.n_head_all, gd.world, "transformer.num_attention_heads", + &gd.n_head)); + gd.n_head_kv = gd.n_head; + gd.kv_off = 0; + RAD_ARCH_TRY(divide_or_fail(gd.n_ff_all, gd.world, "the DiT's feed-forward width", &gd.n_ff)); + if (rad_meta_geti(meta, "transformer.context_in_dim", 4096) != m.gt.n_embd) { + fprintf(stderr, "radiance: qwenimage21: the DiT reads %lld-wide conditioning and the text " + "encoder writes %lld\n", + (long long)rad_meta_geti(meta, "transformer.context_in_dim", 0), + (long long)m.gt.n_embd); + return RAD_E_INVAL; + } + + /* ---- bf16 or block fp8: what the container holds for the first DiT projection decides it + * for every linear of both networks (rad_fp8.h, Geom::w_bf16). */ + { + LinearFP8& probe = m.qkv0; + RAD_ARCH_TRY(probe.probe(b, nm, gd, "dit.blk.0.attn_qkv", + { "transformer.transformer_blocks.0.attn.to_q.weight", + "transformer.transformer_blocks.0.attn.to_k.weight", + "transformer.transformer_blocks.0.attn.to_v.weight" })); + RadEncoding e{}; + const bool plain = weight_enc(b, nm.f("dit.blk.0.attn_qkv.weight"), &e) && + rad_enc_is(&e, "plain"); + gd.w_bf16 = plain; + m.gt.w_bf16 = plain; + } + + /* ---- the latent's normalisation, rounded to bf16 by the ops that read it */ + { + const std::vector mean = meta_list(meta, "vae.latents_mean"); + const std::vector sd = meta_list(meta, "vae.latents_std"); + const int64_t zd = rad_meta_geti(meta, "vae.z_dim", 64); + if ((int64_t)mean.size() != zd || (int64_t)sd.size() != zd) { + fprintf(stderr, "radiance: qwenimage21: vae.latents_mean / latents_std are not %lld " + "values\n", (long long)zd); + return RAD_E_INVAL; + } + for (int64_t i = 0; i < zd; ++i) { + char t[64]; + std::snprintf(t, sizeof t, "%s%.9g", i ? " " : "", mean[(size_t)i]); + m.lat_mean += t; + std::snprintf(t, sizeof t, "%s%.9g", i ? " " : "", sd[(size_t)i]); + m.lat_std += t; + } + } + + /* ---- the conditioning KV group: the DiT's prefix keys and values, every block */ + { + RadKVGroupDecl fd{}; + fd.kind = RAD_KV_FULL; + fd.dtype = RAD_BF16; + fd.n_head_kv = gd.n_head_kv; + fd.head_dim = gd.head_dim; + m.kv = rad_decl_kv_group(b, nm.f("kv_cond"), &fd); + if (!m.kv) return RAD_E_INVAL; + } + + /* ---- the per-image state, a lane an image, and what the passes hand each other */ + const int64_t C = rad_meta_geti(meta, "transformer.in_channels", 64); + const int64_t lane_rows = (int64_t)kMaxLanes * kMaxImageTokens; + m.b_state = decl_b(b, nm.f("lat_state"), RAD_BF16, { lane_rows, C }, RAD_BUF_PERSIST); + m.b_prev = decl_b(b, nm.f("lat_preview"), RAD_BF16, { lane_rows, C }, RAD_BUF_PERSIST); + m.b_inp = decl_b(b, nm.f("lat_repaint"), RAD_BF16, { lane_rows, C }, RAD_BUF_PERSIST); + m.b_mask = decl_b(b, nm.f("lat_mask"), RAD_F32, { lane_rows, 1 }, RAD_BUF_PERSIST); + m.max_ref_rows = (int64_t)kMaxRefs * ref_tokens_max(); + m.b_reflat = decl_b(b, nm.f("ref_lat"), RAD_BF16, { m.max_ref_rows, C }, RAD_BUF_PERSIST); + m.b_encz = decl_b(b, nm.f("enc_lat"), RAD_BF16, { (int64_t)kMaxImageTokens, C }); + m.C = C; + + /* ---- in issue order: the tower, the language model, the encoder, the DiT, the decoder. + * (Vae says why the order matters.) */ + m.media = VisionTower::present(meta) && ctx->max_enc_patches > 0; + if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, m.gt.n_embd, 3000, true)); + RAD_ARCH_TRY(declare_te(b, meta, m)); + RAD_ARCH_TRY(declare_encoder(b, meta, m)); + RAD_ARCH_TRY(declare_dit(b, meta, m)); + RAD_ARCH_TRY(declare_decoder(b, meta, m)); + + /* ---- what the core drives */ + if (!ctx->shape_probe) { + static thread_local std::vector sig; + sig = meta_list(meta, "pipeline.sample_sigmas"); + static thread_local std::string tmpl_text, tmpl_edit, drop; + tmpl_text = std::string("<|im_start|>system\n") + kSysPrompt + + "<|im_end|>\n<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"; + tmpl_edit = std::string("<|im_start|>system\n") + kSysPrompt + + "<|im_end|>\n<|im_start|>user\n{images}{prompt}<|im_end|>\n<|im_start|>assistant\n"; + drop = std::string("<|im_start|>system\n") + kSysPrompt + "<|im_end|>\n"; + + RadGeneratorDecl d{}; + d.name = sig.empty() ? "qwen-image-2.1" : "qwen-image-2.1-turbo"; + d.layout = RAD_GEN_LAYOUT_JOINT_GRID; + d.tmpl_text = tmpl_text.c_str(); + d.tmpl_edit = tmpl_edit.c_str(); + /* `{image}` is the processor's <|vision_start|> <|image_pad|>... <|vision_end|> run. */ + d.tmpl_image = "{image}"; + d.tmpl_image_sep = " "; + d.drop_prefix = drop.c_str(); + d.tmpl_transparent = "This is an RGBA image with transparency. {prompt}. The image has alpha " + "channel and the background is transparent."; + d.latent_channels = C; + d.latent_scale = 16; + d.size_multiple = 32; + d.pixel_channels = rad_meta_geti(meta, "vae.out_channels", 4); + d.slot_rows = 4; + d.max_tokens = kMaxImageTokens; + d.max_refs = kMaxRefs; + d.ref_area = kRefArea; + d.default_width = 2048; + d.default_height = 2048; + d.default_steps = sig.empty() ? 40 : (int64_t)sig.size(); + d.n_sigmas = (int32_t)sig.size(); + d.sigmas = sig.empty() ? nullptr : sig.data(); + d.shift = rad_meta_getf(meta, "scheduler.shift", 1.0); + d.dyn_shift = (int32_t)rad_meta_geti(meta, "scheduler.use_dynamic_shifting", 0); + d.shift_exp = std::strcmp(rad_meta_gets(meta, "scheduler.time_shift_type", "exponential"), + "exponential") == 0; + d.base_shift = rad_meta_getf(meta, "scheduler.base_shift", 0.5); + d.max_shift = rad_meta_getf(meta, "scheduler.max_shift", 1.15); + d.base_seq = rad_meta_geti(meta, "scheduler.base_image_seq_len", 256); + d.max_seq = rad_meta_geti(meta, "scheduler.max_image_seq_len", 4096); + d.shift_terminal = rad_meta_getf(meta, "scheduler.shift_terminal", 0.0); + d.default_cfg = 1.0; + d.max_lanes = kMaxLanes; + d.image_out = m.b_img; + RAD_ARCH_TRY(rad_declare_generator(b, &d)); + } + + rad_note(b, "rank %d/%d: Qwen-Image 2.1%s -- text encoder %lld layers (%lld heads, %lld KV " + "heads a rank), DiT %lld blocks (%lld heads a rank, ff %lld), %s linears%s", + m.gt.rank, m.gt.world, meta_list(meta, "pipeline.sample_sigmas").empty() ? "" : " Turbo", + (long long)m.gt.n_layer, (long long)m.gt.n_head, (long long)m.gt.n_head_kv, + (long long)gd.n_layer, (long long)gd.n_head, (long long)gd.n_ff, + gd.w_bf16 ? "bf16" : "block-fp8", m.media ? ", vision tower with deepstack" : ""); + return RAD_OK; +} + +/* ================================================================== step */ +/* The language model over the prompt, the tower's rows in place of its vision slots and the + * deepstack rows added after the first layers. */ +static void step_te(RadCtx* c, const RadBatch* batch, const Model& m) { + const Geom& g = m.gt; + const int64_t T = batch->n_tok; + const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(); + RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_tx, T)); + const int64_t nmm = batch->n_mm_rows; + if (m.media && nmm > 0) + RAD_ISSUE_N(c, m.op_mm, nmm, brows(m.vit.b_out, nmm), praw(batch->mm_rows, RAD_I32, nmm), + brows(m.b_tx, T)); + const RadOperand pos = praw2(batch->rope_pos, RAD_I32, 3, T); + const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, 2); + for (int64_t l = 0; l < (int64_t)m.te.size(); ++l) { + const TeLayer& L = m.te[(size_t)l]; + RAD_ISSUE(c, L.op_n1, brows(m.b_tx, T), RAD_W(L.w_n1), brows(m.a_th.x, T)); + L.q_h.step(c, T); + L.qkv.step(c, m.a_th, m.b_tkv, T); + RAD_ISSUE(c, L.op_qkr, brows(m.b_tkv, T), pos, RAD_W(L.w_qn), RAD_W(L.w_kn)); + RAD_ISSUE_N(c, L.op_attn, T, bcol(m.b_tkv, 0, q_dim, T), bcol(m.b_tkv, q_dim, kv_dim, T), + bcol(m.b_tkv, q_dim + kv_dim, kv_dim, T), cu, brows(m.a_tattn.x, T)); + L.q_attn.step(c, T); + L.o.step(c, m.a_tattn, m.b_th2, T); + if (L.op_ar1) RAD_ISSUE_N(c, L.op_ar1, T * g.n_embd, brows(m.b_th2, T), RAD_NONE); + RAD_ISSUE(c, L.op_add1, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); + RAD_ISSUE(c, L.op_n2, brows(m.b_tx, T), RAD_W(L.w_n2), brows(m.a_th.x, T)); + L.q_h2.step(c, T); + L.gate_up.step(c, m.a_th, m.b_tgu, T); + L.gq.step(c, m.b_tgu, T); + L.down.step(c, m.a_tffn, m.b_th2, T); + if (L.op_ar2) RAD_ISSUE_N(c, L.op_ar2, T * g.n_embd, brows(m.b_th2, T), RAD_NONE); + RAD_ISSUE(c, L.op_add2, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); + /* DEEPSTACK: tap l's rows join the hidden state at the vision slots after layer l. */ + if (m.media && nmm > 0 && l < m.vit.n_ds) + RAD_ISSUE_N(c, m.op_ds[l], nmm, brows(m.vit.b_ds[l], nmm), + praw(batch->mm_rows, RAD_I32, nmm), brows(m.b_tx, T)); + } + RAD_ISSUE(c, m.op_txn, brows(m.b_tx, T), RAD_W(m.w_txn), brows(m.b_txa, T)); + RAD_ISSUE(c, m.op_tx1, brows(m.b_txa, T), RAD_W(m.w_tx1), brows(m.b_txb, T)); + RAD_ISSUE(c, m.op_txg, brows(m.b_txb, T), brows(m.b_txa, T)); + RAD_ISSUE(c, m.op_tx2, brows(m.b_txa, T), RAD_W(m.w_tx2), brows(m.b_txt, T)); +} + +/* The timestep embedding and the shared modulation for `S` entries at the sigmas in `t`. */ +static void step_temb(RadCtx* c, const Model& m, const float* t, int64_t S) { + RAD_ISSUE_N(c, m.op_temb, S, praw(t, RAD_F32, S), brows(m.b_tproj, S)); + RAD_ISSUE_N(c, m.op_t1, S, brows(m.b_tproj, S), RAD_W(m.w_t1), brows(m.b_te1, S)); + RAD_ISSUE_N(c, m.op_ts, S, brows(m.b_te1, S), brows(m.b_te1s, S)); + RAD_ISSUE_N(c, m.op_t2, S, brows(m.b_te1s, S), RAD_W(m.w_t2), brows(m.b_temb, S)); + RAD_ISSUE_N(c, m.op_ts2, S, brows(m.b_temb, S), brows(m.b_tembs, S)); + RAD_ISSUE_N(c, m.op_mod, S, brows(m.b_tembs, S), RAD_W(m.w_mod), brows(m.b_mod, S)); + RAD_ISSUE_N(c, m.op_nout, S, brows(m.b_tembs, S), RAD_W(m.w_nout), brows(m.b_modo, S)); +} + +/* The DiT's blocks over `R` rows in `b_h`: `S` entries bounded by `cu`, each against its prefix + * (`bt` / `used`) and its own rows, causal or not; the rows' keys and values stored at `slot` + * when it is given. + * + * TWO HALVES, THE ALL-REDUCES ON THE SECOND LANE. With more than one rank, a denoising pass of one + * entry runs everything after the attention -- the output projection, the norm, the feed-forward + * -- and the next block's norm and qkv projection over the rows in two halves, and each half's + * all-reduce goes to lane 1 while lane 0 computes the other half. Every op between two attentions + * is row-local, so a half computes exactly the bits the whole would. The attention stays whole: + * every query reads every key. One entry only, because the norms find a row's modulation by its + * entry, and with a single entry every row of either half is entry 0's; several entries run + * unsplit. Lane 0 waits for a half's all-reduce just before its first reader, and that wait is + * issued before the next all-reduce goes to lane 1 -- a join orders a lane behind everything + * issued on the other, so in the other order it would wait for both. */ +static void step_blocks(RadCtx* c, const Model& m, int64_t R, int64_t S, const RadOperand& cu, + const RadOperand& pos, const RadOperand& bt, const RadOperand& used, + const int32_t* slot, bool causal) { + const Geom& g = m.gd; + const int64_t D = g.n_embd, qd = g.q_dim(); + const RadOperand s1 = bcol(m.b_mod, 0, D, S), g1 = bcol(m.b_mod, D, D, S); + const RadOperand s2 = bcol(m.b_mod, 2 * D, D, S), g2 = bcol(m.b_mod, 3 * D, D, S); + const bool split = g.world > 1 && S == 1 && !slot && R >= 2; + const int64_t hr0[2] = { 0, split ? R / 2 : R }, hn[2] = { hr0[1], R - hr0[1] }; + const int nh = split ? 2 : 1; + const int64_t nD = D / RAD_FP8_BLOCK; + + /* A half's all-reduce: on lane 1 behind everything lane 0 has issued, when split. */ + auto all_reduce = [&](rad_op op, int64_t r0, int64_t n) { + if (!op) return; + if (split) { + rad_lane_join(c, 0, 1); + rad_lane(c, 1); + } + RAD_ISSUE_N(c, op, n * D, brow_slice(m.b_ao, r0, n, D), RAD_NONE); + if (split) rad_lane(c, 0); + }; + auto wait_ar = [&]() { if (split) rad_lane_join(c, 1, 0); }; + /* The block's first norm over a half: the previous block's MLP branch gated in, where folded. */ + auto norm1 = [&](const DitLayer& L, int64_t l, int64_t r0, int64_t n) { + if (L.op_lnq1) { + RAD_ISSUE_N(c, L.op_lnq1, n, l > 0 ? brow_slice(m.b_ao, r0, n, D) : RAD_NONE, + l > 0 ? g2 : RAD_NONE, s1, cu, brow_slice(m.b_h, r0, n, D), + brow_slice(m.a_hm.cq(), r0, n, D), brow_slice(m.a_hm.cs(), r0, n, nD), + RAD_NONE); + } else { + RAD_ISSUE_N(c, L.op_ln1, n, brow_slice(m.b_h, r0, n, D), s1, cu, + brow_slice(m.a_hm.x, r0, n, D)); + L.q_h.step(c, R, r0, n); + } + L.qkv.step(c, m.a_hm, m.b_qkv, R, r0, n); + }; + /* The second norm and the feed-forward over a half, after its attention branch is reduced. */ + auto mlp = [&](const DitLayer& L, int64_t r0, int64_t n) { + if (L.op_lnq2) { + RAD_ISSUE_N(c, L.op_lnq2, n, brow_slice(m.b_ao, r0, n, D), g1, s2, cu, + brow_slice(m.b_h, r0, n, D), brow_slice(m.a_hm.cq(), r0, n, D), + brow_slice(m.a_hm.cs(), r0, n, nD), RAD_NONE); + } else { + RAD_ISSUE_N(c, L.op_g1, n, brow_slice(m.b_ao, r0, n, D), g1, cu, + brow_slice(m.b_h, r0, n, D)); + RAD_ISSUE_N(c, L.op_ln2, n, brow_slice(m.b_h, r0, n, D), s2, cu, + brow_slice(m.a_hm.x, r0, n, D)); + L.q_h2.step(c, R, r0, n); + } + L.gate_up.step(c, m.a_hm, m.b_gu, R, r0, n); + L.gq.step(c, m.b_gu, R, r0, n); + L.down.step(c, m.a_ffn, m.b_ao, R, r0, n); + }; + + for (int64_t l = 0; l < (int64_t)m.dit.size(); ++l) { + const DitLayer& L = m.dit[(size_t)l]; + /* The first half's norm reads the all-reduce the previous block waited for last; the + * second half's waits here, so its reduction ran under the first half's norm and qkv. */ + for (int h = 0; h < nh; ++h) { + if (h > 0 && l > 0) wait_ar(); + norm1(L, l, hr0[h], hn[h]); + } + RAD_ISSUE_N(c, L.op_qkr, R, brows(m.b_qkv, R), pos, RAD_W(L.w_qn), RAD_W(L.w_kn)); + if (slot) + RAD_ISSUE_N(c, L.op_kv, R, bcol(m.b_qkv, qd, qd, R), bcol(m.b_qkv, 2 * qd, qd, R), + praw(slot, RAD_I32, R), kv_cache(m.kv, (int)l)); + if (!slot && L.op_attn_q) { + RAD_ISSUE_N(c, L.op_kq, R, bcol(m.b_qkv, qd, qd, R), brows(m.b_k8, R), + brows(m.b_ks, R)); + RAD_ISSUE(c, L.op_attn_q, bcol(m.b_qkv, 0, qd, R), bcol(m.b_qkv, qd, qd, R), + bcol(m.b_qkv, 2 * qd, qd, R), kv_cache(m.kv, (int)l), bt, used, cu, RAD_NONE, + RAD_NONE, brows(m.b_k8, R), brows(m.b_ks, R), brows(m.a_attn.x, R)); + } else { + RAD_ISSUE(c, causal ? L.op_attn_c : L.op_attn_b, bcol(m.b_qkv, 0, qd, R), + bcol(m.b_qkv, qd, qd, R), bcol(m.b_qkv, 2 * qd, qd, R), + kv_cache(m.kv, (int)l), bt, used, cu, RAD_NONE, RAD_NONE, RAD_NONE, RAD_NONE, + brows(m.a_attn.x, R)); + } + /* Each wait below is for the all-reduce lane 1 holds last, which is the one lane 0 reads + * next: the second half's projection runs under the first half's reduction, the first + * half's feed-forward under the second's, and so on. */ + for (int h = 0; h < nh; ++h) { + L.q_attn.step(c, R, hr0[h], hn[h]); + L.o.step(c, m.a_attn, m.b_ao, R, hr0[h], hn[h]); + if (h > 0) wait_ar(); + all_reduce(split ? L.op_ar1h : L.op_ar1, hr0[h], hn[h]); + } + for (int h = 0; h < nh; ++h) { + mlp(L, hr0[h], hn[h]); + wait_ar(); + all_reduce(split ? L.op_ar2h : L.op_ar2, hr0[h], hn[h]); + } + if (L.op_g2) { + wait_ar(); + RAD_ISSUE_N(c, L.op_g2, R, brows(m.b_ao, R), g2, cu, brows(m.b_h, R)); + } + } + wait_ar(); +} + +/* One picture through the VAE encoder: `px` [h, w * 4] bf16 pixels in [-1, 1] -> its normalised + * latents at rows `row0..` of `dst` (the reference latents, or a repainted picture's). `cu` is the + * picture's {0, latent tokens}. */ +static void step_encode(RadCtx* c, const Model& m, const uint16_t* px, int64_t h, int64_t w, + const RadOperand& cu, rad_buf dst, int64_t row0) { + m.enc.issue(c, h, w, cu, px); + const int64_t n = (h / 16) * (w / 16); + const int64_t zd = m.enc_q.ch / 2; + RAD_ISSUE_N(c, m.op_enc_aff, n, bcol(m.enc_q.buf, 0, zd, n), brow_slice(dst, row0, n, zd)); +} + +static void step(RadCtx* c, const RadBatch* batch) { + const Model& m = g_model[rad_rank(c)]; + const RadGenBatch* G = batch->gen_b; + if (!batch->gen || !G) { + rad_step_fail(c, "qwenimage21 is an image generator and runs generator passes only"); + return; + } + const RadKVGroupBatch* kvb = kv_batch(batch, m.kv); + const int64_t C = m.C; + + switch (batch->gen) { + case RAD_GEN_PASS_COND: { + if (!kvb) { rad_step_fail(c, "a conditioning pass with no KV for its sequence"); return; } + /* 1. the vision tower, when the prompt carries pictures */ + if (m.media && batch->enc_n_patch > 0) m.vit.step(c, batch); + /* 2. the language model and txt_in */ + step_te(c, batch, m); + /* 3. the pictures through the VAE encoder: the references into `ref_lat`, in prompt + * order, and a repainted picture into its images' lanes with its mask. */ + int64_t lat_row = 0; + const int64_t n_ref = G->n_px - (G->inpaint ? 1 : 0); + for (int64_t i = 0; i < G->n_px; ++i) { + const int32_t off = G->px_h[3 * i], ph = G->px_h[3 * i + 1], pw = G->px_h[3 * i + 2]; + const uint16_t* px = (const uint16_t*)G->px + (int64_t)off * m.enc_in.ch; + const int64_t n = (int64_t)(ph / 16) * (pw / 16); + const RadOperand pcu = praw(G->px_cu + 2 * i, RAD_I32, 2); + if (i < n_ref) { + step_encode(c, m, px, ph, pw, pcu, m.b_reflat, lat_row); + lat_row += n; + } else { + step_encode(c, m, px, ph, pw, pcu, m.b_encz, 0); + RAD_ISSUE_N(c, m.op_lstore_lat, n, brows(m.b_encz, n), + praw(G->lane, RAD_I32, G->n_lane), brows(m.b_inp, kMaxLanes * (int64_t)kMaxImageTokens)); + RAD_ISSUE_N(c, m.op_lstore_mask, n, praw2(G->inp_mask, RAD_F32, n, 1), + praw(G->lane, RAD_I32, G->n_lane), + brows(m.b_mask, kMaxLanes * (int64_t)kMaxImageTokens)); + } + } + /* 4. the modulation at t = 0, which every conditioning row reads */ + step_temb(c, m, G->sigma, 1); + /* 5. the prefix, a segment at a time: each sees the segments before it in the cache. */ + int64_t ref_row = 0; + const RadOperand bt = praw2(kvb->block_table, RAD_I32, 1, kvb->block_table_pitch); + for (int64_t s = 0; s < G->n_seg; ++s) { + const int64_t a = G->seg_h[s], len = G->seg_h[s + 1] - a; + if (len <= 0) continue; + const bool pic = G->seg_bidi_h[s] != 0; + if (pic) { + RAD_ISSUE_N(c, m.op_imgin, len, brow_slice(m.b_reflat, ref_row, len, C), + RAD_W(m.w_imgin), brows(m.b_h, len)); + ref_row += len; + } else { + RAD_ISSUE_N(c, m.op_gather, len, brows(m.b_txt, batch->n_tok), + praw(G->src + a, RAD_I32, len), brows(m.b_h, len)); + } + step_blocks(c, m, len, 1, praw(G->seg_cu + 2 * s, RAD_I32, 2), + praw2(G->rope + 3 * a, RAD_I32, 3, len), bt, + praw(G->seg_start + s, RAD_I32, 1), G->slot_mapping + a, !pic); + } + return; + } + case RAD_GEN_PASS_DENOISE: { + if (!kvb) { rad_step_fail(c, "a denoising pass with no KV for its conditioning"); return; } + const int64_t N = batch->n_tok, S = batch->n_seq; + const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, S + 1); + const RadOperand lanes = praw(G->lane, RAD_I32, S); + const int64_t L = (int64_t)kMaxLanes * kMaxImageTokens; + step_temb(c, m, G->sigma, S); + RAD_ISSUE_N(c, m.op_randn, N, praw(G->flags, RAD_I32, S), praw(G->seed, RAD_U32, 2 * S), + lanes, cu, brows(m.b_state, L)); + RAD_ISSUE_N(c, m.op_lgather, N, brows(m.b_state, L), lanes, cu, brows(m.b_lat, N)); + RAD_ISSUE_N(c, m.op_imgin, N, brows(m.b_lat, N), RAD_W(m.w_imgin), brows(m.b_h, N)); + step_blocks(c, m, N, S, cu, praw2(G->rope, RAD_I32, 3, N), + praw2(kvb->block_table, RAD_I32, S, kvb->block_table_pitch), + praw(kvb->seqused, RAD_I32, S), nullptr, false); + RAD_ISSUE_N(c, m.op_nout_ln, N, brows(m.b_h, N), brows(m.b_modo, S), cu, brows(m.a_hm.x, N)); + RAD_ISSUE_N(c, m.op_pout, N, brows(m.a_hm.x, N), RAD_W(m.w_pout), brows(m.b_v, N)); + RAD_ISSUE_N(c, m.op_euler, N, brows(m.b_v, N), praw(G->sigma, RAD_F32, S), + praw(G->sigma_next, RAD_F32, S), praw(G->cfg, RAD_F32, S), + praw(G->pair, RAD_I32, S), lanes, praw(G->flags, RAD_I32, S), + praw(G->seed, RAD_U32, 2 * S), cu, brows(m.b_inp, L), brows(m.b_mask, L), + brows(m.b_state, L), brows(m.b_prev, L)); + return; + } + case RAD_GEN_PASS_DECODE: { + const int64_t H = G->dec_height / 16, W = G->dec_width / 16, n = H * W; + const rad_buf src = G->dec_preview ? m.b_prev : m.b_state; + RAD_ISSUE_N(c, m.op_dec_aff, n, brow_slice(src, (int64_t)G->dec_lane * kMaxImageTokens, n, C), + brows(m.b_decin, n)); + const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, 2); + const int64_t npx = (int64_t)G->dec_height * G->dec_width, ch = m.dec_out.ch; + const int world = m.gt.world, rank = m.gt.rank; + const int64_t band = (H + world - 1) / world, halo = m.dec.halo; + if (!m.op_bands || band + 2 * halo >= H) { + m.dec.issue(c, H, W, cu, nullptr); + RAD_ISSUE_N(c, m.op_rgba, npx, RAD_P_T2(rad_buf_ptr(c, m.dec_out.buf), RAD_BF16, npx, ch), + RAD_P_T2(rad_buf_ptr(c, m.b_img), RAD_U8, npx, ch)); + return; + } + /* The mid-block whole, then this rank's band of latent rows [a, a + band) with `halo` rows + * a side; its pixels sit (a - lo) * 16 rows into the tail's output. The last band may be + * short, and what the gather moves past the picture's last row nobody reads. */ + m.dec.issue(c, H, W, cu, nullptr, 0, (size_t)m.dec.band_from); + const int64_t a = rank * band; + const int64_t lo = std::max(0, a - halo), hi = std::min(H, a + band + halo); + m.dec.issue(c, hi - lo, W, cu, nullptr, (size_t)m.dec.band_from, (size_t)-1, lo); + const int64_t bpx = band * 16 * W * 16; + const char* out = (const char*)rad_buf_ptr(c, m.dec_out.buf) + + (a - lo) * 16 * W * 16 * ch * (int64_t)sizeof(uint16_t); + RAD_ISSUE_N(c, m.op_bands, bpx * ch, RAD_P_T2(out, RAD_BF16, bpx, ch), + RAD_P_T2(rad_buf_ptr(c, m.b_rgbaf), RAD_BF16, world * bpx, ch)); + RAD_ISSUE_N(c, m.op_rgba_bands, npx, RAD_P_T2(rad_buf_ptr(c, m.b_rgbaf), RAD_BF16, npx, ch), + RAD_P_T2(rad_buf_ptr(c, m.b_img), RAD_U8, npx, ch)); + return; + } + default: + rad_step_fail(c, "qwenimage21: a generator pass of a kind this plugin does not know"); + } +} + +/* ================================================================== the probe */ +/* The rows a pass carries -- one image at the largest size with guidance, so two entries -- and + * the vision patches of ten reference pictures at 1024 x 1024 of area. */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + out->gen_rows = 2 * (int64_t)kMaxImageTokens; + out->gen_patches = (int64_t)kMaxRefs * (kRefArea / 256) * 11 / 10; + return RAD_OK; +} + +} /* namespace qwenimage21 */ + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PROBE(qwenimage21) +RAD_ARCH_PLUGIN(qwenimage21, "qwenimage21", "", "0.1.0", + "Qwen-Image 2.1 / 2.1-Turbo: Qwen3-VL-8B conditioning, a 7.1B single-stream " + "diffusion transformer over a cached block-causal prefix, and a 2-D RGBA VAE; " + "bf16 or block-fp8 linears") +#endif diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt index 8afcf8d7..738548ad 100644 --- a/core/CMakeLists.txt +++ b/core/CMakeLists.txt @@ -3,7 +3,7 @@ # # Sources are globbed per subdirectory with CONFIGURE_DEPENDS so that adding a file to a component # does not mean editing a file another component owns. Re-run cmake if a new file does not appear. -set(RAD_CORE_DIRS util device plugin build runtime mem sched place sample text server format mm diag) +set(RAD_CORE_DIRS util device plugin build runtime mem sched place sample text server format mm diag gen) set(RAD_CORE_SRC "") foreach(d ${RAD_CORE_DIRS}) diff --git a/core/build/rad_build.h b/core/build/rad_build.h index 2fc8d50f..06b723bc 100644 --- a/core/build/rad_build.h +++ b/core/build/rad_build.h @@ -137,6 +137,7 @@ public: int declare_drafter(const RadDrafterDecl* d); int drafter_shared_kv(int pos_offset); int declare_encoder(const RadEncoderDecl* d); + int declare_generator(const RadGeneratorDecl* d); void note_v (const char* f, va_list ap); /* The buffer operands of an op. diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index 6f48a91c..fcf3ed13 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -1067,6 +1067,11 @@ int Builder::declare_logits(rad_buf b) { prog_.buffers[prog_.pooled_buf].name.c_str()); return RAD_E_STATE; } + if (prog_.generator.layout != 0) { + err(RAD_E_STATE, "declare_logits: this program already declared the image generator '%s'", + prog_.gen_str.name.c_str()); + return RAD_E_STATE; + } prog_.logits_buf = b; return RAD_OK; } @@ -1093,6 +1098,11 @@ int Builder::declare_pooled(rad_buf b) { prog_.buffers[prog_.logits_buf].name.c_str()); return RAD_E_STATE; } + if (prog_.generator.layout != 0) { + err(RAD_E_STATE, "declare_pooled: this program already declared the image generator '%s'", + prog_.gen_str.name.c_str()); + return RAD_E_STATE; + } const RadBufDecl& d = prog_.buffers[b].decl; if (d.dtype != RAD_F32 || d.domain != RAD_DOMAIN_DEVICE || d.rank != 2 || d.shape[0] < prog_.ctx.max_seqs || d.shape[1] <= 0) { @@ -1173,6 +1183,105 @@ int Builder::declare_encoder(const RadEncoderDecl* d) { return RAD_OK; } +/* WHAT THE GENERATOR IS. Checked whole here: a generator's every request runs all three of its + * passes, so a declaration the core cannot drive fails the first request rather than a rare one, + * and the first request is the wrong place to learn that the plugin sized its image buffer for a + * smaller picture than it says it makes. The strings are copied: the plugin's storage is not the + * Program's, and the Program outlives a declare. */ +int Builder::declare_generator(const RadGeneratorDecl* d) { + if (finished_) { err(RAD_E_STATE, "declare_generator after declare finished"); return RAD_E_STATE; } + if (!d) { err(RAD_E_INVAL, "declare_generator: null declaration"); return RAD_E_INVAL; } + const char* nm = d->name && *d->name ? d->name : "(unnamed)"; + if (prog_.generator.layout != 0) { + err(RAD_E_STATE, "declare_generator: '%s' was already declared; '%s' is a second one", + prog_.gen_str.name.c_str(), nm); + return RAD_E_STATE; + } + if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE) { + err(RAD_E_STATE, "declare_generator '%s': this program already declared %s; a program " + "generates text, embeds or makes images -- one of the three", nm, + prog_.logits_buf != RAD_NULL_HANDLE ? "logits" : "a pooled output"); + return RAD_E_STATE; + } + if (d->layout != RAD_GEN_LAYOUT_JOINT_GRID) { + err(RAD_E_INVAL, "declare_generator '%s': layout %d is not one this engine builds", nm, + (int)d->layout); + return RAD_E_INVAL; + } + auto has = [](const char* t, const char* what) { return t && std::strstr(t, what); }; + if (!has(d->tmpl_text, "{prompt}") || !has(d->tmpl_edit, "{prompt}") || + !has(d->tmpl_edit, "{images}") || !has(d->tmpl_image, "{image}")) { + err(RAD_E_INVAL, "declare_generator '%s': tmpl_text needs {prompt}, tmpl_edit {images} and " + "{prompt}, and tmpl_image {image}, where the picture's tokens go", nm); + return RAD_E_INVAL; + } + if (d->latent_channels <= 0 || d->latent_scale <= 0 || d->size_multiple <= 0 || + d->size_multiple % d->latent_scale != 0 || d->pixel_channels <= 0 || + d->pixel_channels > 4 || d->slot_rows <= 0 || d->max_tokens <= 0 || d->max_refs < 0 || + d->ref_area <= 0 || d->default_width <= 0 || d->default_height <= 0 || + d->default_width % d->size_multiple != 0 || d->default_height % d->size_multiple != 0 || + (d->default_width / d->latent_scale) * (d->default_height / d->latent_scale) > d->max_tokens || + d->max_lanes <= 0) { + err(RAD_E_INVAL, "declare_generator '%s': a geometry field is out of range (latent %lld x " + "%lld px, multiple %lld, %lld channels, slot rows %lld, max %lld tokens, " + "default %lldx%lld, %lld lanes)", nm, (long long)d->latent_channels, + (long long)d->latent_scale, (long long)d->size_multiple, (long long)d->pixel_channels, + (long long)d->slot_rows, (long long)d->max_tokens, (long long)d->default_width, + (long long)d->default_height, (long long)d->max_lanes); + return RAD_E_INVAL; + } + if (d->n_sigmas < 0 || (d->n_sigmas > 0 && !d->sigmas) || + (d->n_sigmas == 0 && d->default_steps <= 0) || !(d->default_cfg >= 1.0) || + (d->dyn_shift && (d->max_seq <= d->base_seq || d->base_seq <= 0)) || + (!d->dyn_shift && !(d->shift > 0)) || d->shift_terminal < 0 || d->shift_terminal >= 1) { + err(RAD_E_INVAL, "declare_generator '%s': the sampler is incomplete (%d fixed sigmas, %lld " + "default steps, shift %g, dynamic %d over %lld..%lld, terminal %g, " + "guidance %g)", nm, (int)d->n_sigmas, (long long)d->default_steps, + d->shift, (int)d->dyn_shift, (long long)d->base_seq, (long long)d->max_seq, + d->shift_terminal, d->default_cfg); + return RAD_E_INVAL; + } + for (int i = 0; i < d->n_sigmas; ++i) + if (!(d->sigmas[i] > 0.0 && d->sigmas[i] <= 1.0) || + (i > 0 && !(d->sigmas[i] < d->sigmas[i - 1]))) { + err(RAD_E_INVAL, "declare_generator '%s': fixed sigma %d (%g) is not in (0, 1] below " + "the one before it", nm, i, d->sigmas[i]); + return RAD_E_INVAL; + } + if (d->image_out == RAD_NULL_HANDLE || (size_t)d->image_out >= prog_.buffers.size()) { + err(RAD_E_INVAL, "declare_generator '%s': image_out %u is not a declared buffer", nm, + (unsigned)d->image_out); + return RAD_E_INVAL; + } + const RadBufDecl& ob = prog_.buffers[d->image_out].decl; + int64_t numel = 1; + for (uint32_t i = 0; i < ob.rank; ++i) numel *= ob.shape[i]; + const int64_t px = d->max_tokens * d->latent_scale * d->latent_scale; + if (ob.dtype != RAD_U8 || ob.domain != RAD_DOMAIN_DEVICE || numel < px * d->pixel_channels) { + err(RAD_E_INVAL, "declare_generator '%s': image_out '%s' must be a device u8 buffer of at " + "least %lld x %lld -- the largest image", nm, + prog_.buffers[d->image_out].name.c_str(), (long long)px, (long long)d->pixel_channels); + return RAD_E_INVAL; + } + Program::GenStrings& g = prog_.gen_str; + g.name = nm; + g.tmpl_text = d->tmpl_text; + g.tmpl_edit = d->tmpl_edit; + g.tmpl_image = d->tmpl_image; + g.tmpl_image_sep = d->tmpl_image_sep ? d->tmpl_image_sep : ""; + g.drop_prefix = d->drop_prefix ? d->drop_prefix : ""; + g.tmpl_transparent = d->tmpl_transparent ? d->tmpl_transparent : ""; + g.sigmas.assign(d->sigmas, d->sigmas + d->n_sigmas); + prog_.generator = *d; + /* The Program is moved after declare, and a pointer into a moved string is a pointer into the + * old one's storage: nothing here may be read through the decl, only through gen_str. */ + RadGeneratorDecl& c = prog_.generator; + c.name = c.tmpl_text = c.tmpl_edit = c.tmpl_image = c.tmpl_image_sep = nullptr; + c.drop_prefix = c.tmpl_transparent = nullptr; + c.sigmas = nullptr; + return RAD_OK; +} + /* WHAT THE DRAFT HEAD IS. Every field is checked here rather than at the first draft pass: a * drafter is exercised only once a request is speculating, so a decl that is wrong in a way the * engine cannot act on would otherwise surface as acceptance that is quietly zero. @@ -1822,6 +1931,11 @@ int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) { return B(b)->declare_encoder(d); } +int rad_declare_generator(RadBuilder* b, const RadGeneratorDecl* d) { + if (!b) return RAD_E_INVAL; + return B(b)->declare_generator(d); +} + void rad_note(RadBuilder* b, const char* f, ...) { if (!b) return; va_list ap; diff --git a/core/build/startup.cpp b/core/build/startup.cpp index 116c5842..d8e9e0d3 100644 --- a/core/build/startup.cpp +++ b/core/build/startup.cpp @@ -386,9 +386,9 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R * the same resolution as the plugin's. A sampler op that does not resolve is deliberately NOT * a declare failure -- a deployment that never sends `typical_p` does not need a typical * kernel -- so this returning negative means something structural, not a miss. */ - /* NOT FOR AN EMBEDDING PROGRAM (rad_declare_pooled): it samples nothing, so a sampler chain - * in it would be ops and buffers no step ever issues. */ - if (also && b.program().pooled_buf == RAD_NULL_HANDLE) { + /* NOT FOR AN EMBEDDING PROGRAM (rad_declare_pooled) OR AN IMAGE GENERATOR: neither samples a + * token, so a sampler chain in it would be ops and buffers no step ever issues. */ + if (also && b.program().pooled_buf == RAD_NULL_HANDLE && !b.program().is_generator()) { /* THE WIDTH THE PLUGIN ACTUALLY DECLARED, handed over rather than re-derived. The sampler * needs to know how much vocabulary THIS RANK produces, and the one place that is a fact * is the logits buffer the plugin just named. Computing it a second time from n_vocab and diff --git a/core/engine.cpp b/core/engine.cpp index 160636c2..e5b3ce9c 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -5,6 +5,7 @@ * engine_priv.h for what the four share. */ #include "engine_priv.h" +#include "gen/driver.h" #include "kld.h" #include "mm/processor.h" @@ -321,7 +322,7 @@ void Engine::rank_loop(int index) { /* This rank's view of the step: the same numbers, pointed at this card's staging. * The upload that filled it was issued on THIS stream, so the ordering is an * ordinary same-stream dependency and no cross-rank fence is needed. */ - const RadBatch* mine = sched_.batch_for(index); + const RadBatch* mine = gen_ ? gen_->batch_for(index) : sched_.batch_for(index); if (!mine) { RAD_ERR("rank %d: the builder has no batch for this rank", index); step_status_.store(RAD_E_STATE, std::memory_order_release); @@ -1596,12 +1597,30 @@ int Engine::serve() { return RAD_E_STATE; } embedding_ = ranks_[0]->program.pooled_buf != RAD_NULL_HANDLE; - if (ranks_[0]->program.logits_buf == RAD_NULL_HANDLE && !embedding_) { - RAD_ERR("the '%s' plugin declared no logits buffer (rad_declare_logits) and no pooled " - "output (rad_declare_pooled), so a step produces nothing anyone can read. An " - "encoder-only plugin cannot serve.", plugins_.arch_plugin.c_str()); + const bool generator = ranks_[0]->program.is_generator(); + if (ranks_[0]->program.logits_buf == RAD_NULL_HANDLE && !embedding_ && !generator) { + RAD_ERR("the '%s' plugin declared no logits buffer (rad_declare_logits), no pooled output " + "(rad_declare_pooled) and no image generator (rad_declare_generator), so a step " + "produces nothing anyone can read. An encoder-only plugin cannot serve.", + plugins_.arch_plugin.c_str()); return RAD_E_UNSUPPORTED; } + if (generator) { + if (cfg_.kld() || cfg_.n_spec > 0) { + RAD_ERR("the '%s' plugin makes images: --kld and speculative decoding have no tokens to " + "work on", plugins_.arch_plugin.c_str()); + return RAD_E_UNSUPPORTED; + } + for (size_t i = 1; i < ranks_.size(); ++i) + if (!ranks_[i]->program.is_generator()) { + RAD_ERR("rank %zu declared no image generator and rank 0 did", i); + return RAD_E_STATE; + } + cfg_.prefix_cache = false; + prefix_off_why_ = "an image generator: a conditioning is read by its own request's images " + "and by nothing after them"; + decide("--no-prefix-cache", "prefix caching off", prefix_off_why_); + } if (embedding_) { if (cfg_.kld() || cfg_.n_spec > 0) { RAD_ERR("the '%s' plugin is an embedding model: it generates nothing, so --kld and " @@ -1747,6 +1766,16 @@ int Engine::serve() { rio.reserve(ranks_.size()); for (auto& rk : ranks_) rio.push_back({ rk->device, rk->ctx.stream(), &rk->program }); + if (generator) { + /* THE GENERATOR'S DRIVER IN PLACE OF THE SCHEDULER: the scheduler is never initialised, + * so its step staging -- sized for token steps the generator never runs -- is never + * allocated, and nothing calls it. */ + std::vector gio; + for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() }); + gen_ = std::make_unique(); + RAD_TRY(gen_->init(ranks_[0]->program, cfg_, kv_iface_.get(), gio)); + RAD_TRY(rad_dev_set(ranks_[0]->device)); + } else RAD_TRY(sched_.init(ranks_[0]->program, cfg_, kv_iface_.get(), pc_iface_.get(), rio, &geo_)); /* THE SMALLEST STEP THE PREFILL STAGER OVERLAPS. A prefill chunk the scheduler holds back for * other work in the step (--busy-prefill-chunk) is kept at or above it: under it every routed @@ -1769,7 +1798,7 @@ int Engine::serve() { rank_threads_.clear(); for (int i = 0; i < cfg_.tp; ++i) rank_threads_.emplace_back([this, i] { rank_loop(i); }); - std::thread stepper([this] { step_loop(); }); + std::thread stepper([this] { if (gen_) gen_loop(); else step_loop(); }); if (cfg_.kld()) print_startup_report(RAD_OK); int s = cfg_.kld() ? run_kld() : run_server(); @@ -2290,6 +2319,8 @@ int Engine::run_server() { chat_bridge.init(*vocab_, declared_format, plugins_.arch_plugin) >= 0 && chat_bridge.ready()) embed_info.tpl = &chat_bridge; + } else if (gen_) { + /* An image model's template is its conditioning network's; nothing is served as chat. */ } else if (vocab_ && !vocab_->chat_template().empty() && chat_bridge.init(*vocab_, declared_format, plugins_.arch_plugin) >= 0 && chat_bridge.ready()) { @@ -2301,6 +2332,7 @@ int Engine::run_server() { server::ServerOptions o{}; o.embedding_model = embedding_; + o.image_model = gen_ != nullptr; o.decision_type = rad_meta_gets(&meta_, "decision.type", ""); o.model_id = !cfg_.served_model_name.empty() ? cfg_.served_model_name : meta_.name && *meta_.name ? meta_.name : "radiance"; @@ -2536,6 +2568,68 @@ int Engine::run_server() { d.mm = mm_bridge.get(); } + /* AN IMAGE GENERATOR'S ENDPOINTS: the driver's queue, the model's declared prompts and sizes, + * and the processor for the conditioning network's view of a reference picture. */ + struct ImageBridge final : server::IImageGen { + gen::Driver* drv = nullptr; + const mm::Processor* proc = nullptr; + server::ImageGenInfo inf; + const server::ImageGenInfo& info() const override { return inf; } + int submit(std::unique_ptr r, std::string* why) override { + return drv->submit(std::move(r), why); + } + int picture(const mm::Frame& f, std::shared_ptr* out, std::string* why) override { + if (!proc) { + if (why) *why = "this model reads no pictures"; + return RAD_E_UNSUPPORTED; + } + return proc->image_from(f, out, why); + } + int64_t queued() const override { return drv->queued(); } + int64_t running() const override { return drv->running(); } + } image_bridge; + if (gen_) { + const Program& pg = ranks_[0]->program; + const RadGeneratorDecl& gd = pg.generator; + server::ImageGenInfo& in = image_bridge.inf; + in.name = pg.gen_str.name; + in.tmpl_text = pg.gen_str.tmpl_text; + in.tmpl_edit = pg.gen_str.tmpl_edit; + in.tmpl_image = pg.gen_str.tmpl_image; + in.tmpl_image_sep = pg.gen_str.tmpl_image_sep; + in.drop_prefix = pg.gen_str.drop_prefix; + in.tmpl_transparent = pg.gen_str.tmpl_transparent; + in.latent_scale = gd.latent_scale; + in.size_multiple = gd.size_multiple; + in.pixel_channels = gd.pixel_channels; + in.max_tokens = gd.max_tokens; + /* Edits need the conditioning network to read pictures. */ + in.max_refs = mm_proc ? gd.max_refs : 0; + in.ref_area = gd.ref_area; + in.default_width = gd.default_width; + in.default_height = gd.default_height; + in.default_steps = gd.default_steps; + in.max_lanes = gd.max_lanes; + in.max_cond_tokens = gen_->max_cond_tokens(); + in.fixed_schedule = !pg.gen_str.sigmas.empty(); + in.fixed_steps = (int64_t)pg.gen_str.sigmas.size(); + in.default_cfg = gd.default_cfg; + image_bridge.drv = gen_.get(); + image_bridge.proc = mm_proc.get(); + d.images = &image_bridge; + /* The model a client lists and names is the generator's own (qwen-image-2.1), not the + * architecture a diffusers pipeline's container is named after. */ + if (cfg_.served_model_name.empty() && !in.name.empty()) { + o.model_id = in.name; + decide("--served-model-name", o.model_id, "an image generator: its own name"); + } + RAD_INFO("images: '%s', %lldx%lld by default, up to %lld latent tokens, %lld picture(s) an " + "edit, %s", in.name.c_str(), (long long)in.default_width, + (long long)in.default_height, (long long)in.max_tokens, (long long)in.max_refs, + in.fixed_schedule ? (std::to_string(in.fixed_steps) + " fixed steps").c_str() + : (std::to_string(in.default_steps) + " steps by default").c_str()); + } + if (encd.modalities == 0 && aend.modalities == 0 && cfg_.media_flags_set()) RAD_WARN("media: the media flags do nothing here -- this model %s", cfg_.mm_max_patches == 0 ? "is served text only (--mm-max-patches 0)" @@ -2595,6 +2689,11 @@ int Engine::run_server() { if (embedding_) RAD_INFO("serving on http://%s:%d (/v1/embeddings; completions and chat are 501)%s", o.host.c_str(), o.port, o.api_key.empty() ? "" : " -- a bearer key is required"); + else if (gen_) + RAD_INFO("serving on http://%s:%d (/v1/images/generations%s; completions and chat are " + "501)%s", o.host.c_str(), o.port, + d.images && d.images->info().max_refs > 0 ? " and /v1/images/edits" : "", + o.api_key.empty() ? "" : " -- a bearer key is required"); else RAD_INFO("serving on http://%s:%d (/v1/completions%s)%s", o.host.c_str(), o.port, d.chat ? "; /v1/chat/completions with tools and reasoning" : "; chat is 501", diff --git a/core/engine.h b/core/engine.h index 7ce1fb4e..1acbd1d9 100644 --- a/core/engine.h +++ b/core/engine.h @@ -42,6 +42,7 @@ namespace rad { class Kld; +namespace gen { class Driver; } struct TierPump; struct TierJob; struct StepSlot; @@ -294,6 +295,11 @@ private: float* pooled_host_ = nullptr; int collect_pooled_issue(const RadBatch* b, StepOut& so); int collect_pooled(const RadBatch* b, StepOut& so); + /* AN IMAGE GENERATOR (rad_declare_generator): the driver that turns its requests into passes + * and the loop that runs them, in place of the scheduler and the step loop (engine_gen.cpp). + * Null for every other program. */ + std::unique_ptr gen_; + int gen_loop(); bool serial_drafting() const; int advance_all(int mode, int round, bool from_proposal, int rows = -1); int issue_serial_drafter(int step, const RadBatch* b, StepOut& so); diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index e1543557..b2bc70a3 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -8,6 +8,7 @@ * path and shares nothing with this but the Engine's fields. See engine_priv.h. */ #include "engine_priv.h" +#include "gen/driver.h" #include "build/startup.h" #include "build/rad_build.h" @@ -979,6 +980,40 @@ int Engine::declare() { "the KL mode: a prefix hit would start a document past positions the reference holds"; decide("--no-prefix-cache", "prefix caching off", prefix_off_why_); } + /* AN IMAGE GENERATOR SIZES THE STEP ITSELF (RadArchProbe::gen_rows): a denoise pass carries an + * image's every latent row at once -- twice with guidance -- and a conditioning pass encodes + * every reference picture a request may carry. What the operator named is kept; what they did + * not is the generator's. A generator samples no tokens, so it drafts none, and a conditioning + * is read only by its own request's images, so there is no prefix to cache. */ + { + RadArchProbe pb{}; + (void)rad_tools_probe(plugins_, meta_, &pb); + if (pb.gen_rows > 0) { + if (!cfg_.given.count("--max-num-batched-tokens")) { + cfg_.max_tok = pb.gen_rows; + decide("--max-num-batched-tokens", std::to_string(cfg_.max_tok), + "an image generator: a denoise pass carries the largest image's latent " + "rows twice (with guidance)"); + } + if (!cfg_.given.count("--max-num-seqs")) { + cfg_.max_seqs = 16; + decide("--max-num-seqs", "16", "an image generator: images in one pass"); + } + if (!cfg_.given.count("--max-model-len") && cfg_.max_ctx == 0) { + cfg_.max_ctx = pb.gen_rows; + decide("--max-model-len", std::to_string(cfg_.max_ctx), + "an image generator: the longest conditioning, a prompt and its pictures, " + "as the generator's rows"); + } + if (cfg_.mm_max_patches < 0 && pb.gen_patches > 0) { + cfg_.mm_max_patches = pb.gen_patches; + decide("--mm-max-patches", std::to_string(cfg_.mm_max_patches), + "an image generator: every reference picture of a request at once"); + } + if (cfg_.n_spec < 0) cfg_.n_spec = 0; + cfg_.prefix_cache = false; + } + } if (cfg_.n_spec < 0) { RadArchProbe pb{}; (void)rad_tools_probe(plugins_, meta_, &pb); @@ -1381,7 +1416,8 @@ int Engine::plan() { const int64_t w = probe.state_index_width((int32_t)i); if (w > 0) kg.g[i].sidx_width = w; } - f.staging = BatchBuilder::device_bytes(r->program, cfg_, kg); + f.staging = r->program.is_generator() ? gen::Driver::device_bytes(r->program, cfg_) + : BatchBuilder::device_bytes(r->program, cfg_, kg); if (f.staging < 0) return RAD_E_INVAL; late_step_bytes_ = std::max(late_step_bytes_, f.staging); int64_t lazy = r->program.scratch_regions > 1 ? f.queue_bytes : 0; @@ -3167,6 +3203,17 @@ int Engine::configure_kv() { * in vram_budget.cpp says it.) What is never acceptable is a pool that cannot * hold ONE max-length sequence: * that request is accepted by the API and can never complete, whatever the load. */ + /* An image generator's sequence is a conditioning, and its driver refuses one the + * cache can never hold by name at admission; the limit is the operator's to know, + * in its own terms, with nothing about experts the model does not have. */ + if (ranks_[0]->program.is_generator()) { + RAD_WARN("kv group '%s' holds %lld rows: a conditioning longer than that -- a " + "prompt with its pictures, up to %lld rows -- is refused. A picture " + "costs a latent row per 16x16 pixels of the reference area; more ranks " + "give the cache more room.", + p->name.c_str(), (long long)cap, (long long)want); + continue; + } RAD_WARN("kv group '%s' holds %lld tokens but the context limit is %lld: ONE request " "longer than %lld tokens is accepted by the API and then refused as too " "large to ever fit -- this is a hard limit, not a backing ratio. Give the " diff --git a/core/engine_gen.cpp b/core/engine_gen.cpp new file mode 100644 index 00000000..f95cdaeb --- /dev/null +++ b/core/engine_gen.cpp @@ -0,0 +1,72 @@ +/* engine_gen.cpp -- the image generator's loop: the driver's passes (core/gen/driver.h) run on the + * ranks the way the step loop runs token steps, one at a time and each drained before the next. + * + * WHY EACH PASS IS DRAINED. A generator pass is tens to thousands of milliseconds of device work, + * and what decides the next one -- which image finished, which preview a step marked -- is the + * driver's bookkeeping of the pass just run, not anything the card computes. Waiting for the card + * between passes costs the few microseconds the host takes to build the next one; issuing ahead + * would need a second staging region and a commit protocol, for nothing a client could measure. + */ +#include "engine_priv.h" +#include "gen/driver.h" + +#include +#include + +namespace rad { + +int Engine::gen_loop() { + if (rad_dev_set(ranks_[0]->device) < 0) + RAD_ERR("image generator loop: could not bind rank 0's device"); + int step = 0, idle = 0; + const rad_buf img = ranks_[0]->program.generator.image_out; + while (!stopping_.load(std::memory_order_acquire)) { + const RadBatch* b = gen_->next(step); + if (!b) { + step_batch_.store(nullptr, std::memory_order_release); + if (idle < 200) ++idle; + std::this_thread::sleep_for(std::chrono::microseconds(idle * 50)); + continue; + } + idle = 0; + if (const int ps = prepare_release(b); ps < 0) { + gen_->shutdown("the engine stopped on an error and is not serving", ps); + return fail_loop(ps); + } + issue_what_.store(kIssueModel, std::memory_order_release); + step_batch_.store(b, std::memory_order_release); + barrier_->arrive_and_wait(); /* release the ranks */ + barrier_->arrive_and_wait(); /* wait for them */ + int st = step_status_.load(std::memory_order_acquire); + if (st < 0) { + RAD_ERR("generator pass %d failed: %s -- the engine cannot continue", step, + rad_strerror(st)); + gen_->shutdown("the engine stopped on an error and is not serving", st); + return fail_loop(st); + } + /* A DECODE PASS'S IMAGE, behind it on rank 0's stream: every rank decodes the same pixels. */ + if (const int64_t n = gen_->decode_bytes(); n > 0) { + const void* src = ranks_[0]->ctx.buf_ptr(img); + if (!src) { + RAD_ERR("the generator's image buffer was declared but never planned"); + gen_->shutdown("the engine stopped on an error and is not serving", RAD_E_STATE); + return fail_loop(RAD_E_STATE); + } + st = rad_memcpy_async(gen_->host_image(), src, n, ranks_[0]->ctx.stream()); + } + for (auto& rk : ranks_) + if (st >= 0) st = rad_stream_sync(rk->ctx.stream()); + if (st < 0) { + RAD_ERR("generator pass %d: the device failed: %s", step, rad_strerror(st)); + gen_->shutdown("the engine stopped on an error and is not serving", st); + return fail_loop(st); + } + if ((int)log_level() >= (int)Log::Trace) + dump_buffers(ranks_[0]->ctx, step, std::getenv("RADIANCE_DUMP_BUF")); + gen_->done(); + ++step; + } + return RAD_OK; +} + +} /* namespace rad */ diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index f6cd90d7..000e42f3 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -5,6 +5,7 @@ #include #include +#include #include #include #include @@ -76,6 +77,7 @@ static void flatten_json(const nlohmann::json& j, const std::string& prefix, Met if (e.is_number_integer()) s += fmt("%lld", (long long)e.get()); else if (e.is_number()) s += fmt("%.17g", e.get()); else if (e.is_string()) s += e.get(); + else if (e.is_boolean()) s += e.get() ? "1" : "0"; else { ok = false; break; } } if (ok) out->kv(key, s); @@ -480,6 +482,95 @@ int shard_list(const std::string& dir, const std::string& index, bool index_give } /* namespace */ +/* A JSON file flattened under `prefix`; absent is not an error when `optional`. */ +static int meta_merge_json_file(const std::string& path, const std::string& prefix, bool optional, + MetaOwn* out) { + std::ifstream f(path); + if (!f) { + if (optional) return RAD_OK; + RAD_ERR("%s: cannot read it", path.c_str()); + return RAD_E_NOTFOUND; + } + nlohmann::json j; + try { f >> j; } + catch (const std::exception& e) { RAD_ERR("%s: %s", path.c_str(), e.what()); return RAD_E_FORMAT; } + if (!j.is_object()) { + RAD_ERR("%s: not a JSON object", path.c_str()); + return RAD_E_FORMAT; + } + flatten_json(j, prefix, out); + return RAD_OK; +} + +static bool path_exists(const std::string& p) { std::ifstream f(p); return (bool)f; } + +/* A DIFFUSERS PIPELINE: model_index.json at the top and one folder a component, each with its own + * config and weights. It is read as ONE checkpoint, because the components are one model to the + * architecture plugin that serves them: + * + * text_encoder/ its config.json is the container's model config -- the typed dimensions and + * the bare keys -- and its tensors keep their names; + * transformer/ tensors under `transformer.`, config.json under `transformer.` keys; + * vae/ tensors under `vae.`, config.json under `vae.` keys; + * scheduler/ scheduler_config.json under `scheduler.` keys; + * processor/ (or tokenizer/) the tokenizer, the chat template and the preprocessor configs. + * + * model_index.json itself goes under `pipeline.` keys, and its `_class_name` names the + * architecture: `QwenImage21Pipeline` is `qwenimage21`. A component folder may be a link to + * another pipeline's (a distilled release sharing its base's text encoder). */ +int Checkpoint::open_diffusers() { + kind_ = SafeT; + RAD_TRY(meta_merge_json_file(dir_ + "/model_index.json", "pipeline", false, &meta_)); + const std::string te = dir_ + "/text_encoder"; + if (path_exists(te + "/config.json")) { + std::vector shards; + std::unordered_map owner; + RAD_TRY(shard_list(te, te + "/model.safetensors.index.json", false, &shards, &owner)); + for (const auto& sh : shards) RAD_TRY(add_shard(sh, "", owner.empty() ? nullptr : &owner)); + RAD_TRY(meta_from_config_json(te, &meta_)); + RAD_TRY(meta_merge_generation_config(te, &meta_)); + } + for (const char* comp : { "transformer", "vae" }) { + const std::string d = dir_ + "/" + comp; + if (!path_exists(d + "/config.json")) continue; + const std::string idx = d + "/diffusion_pytorch_model.safetensors.index.json"; + std::vector shards; + std::unordered_map owner; + if (path_exists(idx)) { + RAD_TRY(shard_list(d, idx, true, &shards, &owner)); + } else { + shards.push_back(d + "/diffusion_pytorch_model.safetensors"); + } + for (const auto& sh : shards) + RAD_TRY(add_shard(sh, std::string(comp) + ".", owner.empty() ? nullptr : &owner)); + RAD_TRY(meta_merge_json_file(d + "/config.json", comp, false, &meta_)); + } + RAD_TRY(meta_merge_json_file(dir_ + "/scheduler/scheduler_config.json", "scheduler", true, + &meta_)); + for (const char* sub : { "processor", "tokenizer" }) { + const std::string d = dir_ + "/" + sub; + if (!path_exists(d + "/tokenizer.json")) continue; + tok_dir_ = d; + RAD_TRY(meta_merge_preprocessor_configs(d, &meta_)); + break; + } + /* The architecture is the pipeline's, whatever the text encoder calls itself. */ + if (const char* cn = meta_.get("pipeline._class_name")) { + std::string a = cn; + const std::string suf = "Pipeline"; + if (a.size() > suf.size() && a.compare(a.size() - suf.size(), suf.size(), suf) == 0) + a.resize(a.size() - suf.size()); + for (char& ch : a) ch = (char)std::tolower((unsigned char)ch); + meta_.arch = a; + } + if (tensors_.empty()) { + RAD_ERR("%s: a diffusers pipeline with no component weights", dir_.c_str()); + return RAD_E_NOTFOUND; + } + meta_.finish(); + return RAD_OK; +} + int Checkpoint::open_safetensors(const std::string& path) { kind_ = SafeT; /* One shard, an index, or the directory holding either: one namespace whichever it is. */ @@ -488,6 +579,9 @@ int Checkpoint::open_safetensors(const std::string& path) { const bool is_index = path.size() > 10 && path.compare(path.size() - 10, 10, "index.json") == 0; const bool is_file = path.size() > 12 && path.compare(path.size() - 12, 12, ".safetensors") == 0; + if (!is_file && !is_index && path_exists(dir_ + "/model_index.json") && + !path_exists(dir_ + "/config.json")) + return open_diffusers(); if (is_file) { shards.push_back(path); } else { diff --git a/core/format/checkpoint.h b/core/format/checkpoint.h index 956c4260..acbce471 100644 --- a/core/format/checkpoint.h +++ b/core/format/checkpoint.h @@ -125,6 +125,9 @@ public: GgufFile& gguf() { return gguf_; } const std::string& path() const { return path_; } const std::string& dir() const { return dir_; } /* where config.json and tokenizer.json sit */ + /* Where tokenizer.json, tokenizer_config.json and the chat template sit: dir() for a model + * repository, the `processor/` (or `tokenizer/`) folder of a diffusers pipeline. */ + const std::string& tok_dir() const { return tok_dir_.empty() ? dir_ : tok_dir_; } MetaOwn& meta() { return meta_; } const MetaOwn& meta() const { return meta_; } @@ -162,11 +165,12 @@ private: int add_shard(const std::string& p, const std::string& prefix = "", const std::unordered_map* owner = nullptr); int open_safetensors(const std::string& path); + int open_diffusers(); int open_gguf(const std::string& path); void detect_import(); enum Kind { None, Gguf, SafeT } kind_ = None; - std::string path_, dir_; + std::string path_, dir_, tok_dir_; GgufFile gguf_; MetaOwn meta_; std::vector> shards_; diff --git a/core/gen/driver.cpp b/core/gen/driver.cpp new file mode 100644 index 00000000..56806fcb --- /dev/null +++ b/core/gen/driver.cpp @@ -0,0 +1,916 @@ +/* driver.cpp -- the image generator's pass driver (driver.h). */ +#include "driver.h" +#include "sched/mem_iface.h" + +#include +#include +#include + +namespace rad { +namespace gen { + +namespace { + +constexpr int64_t kAlign = 256; + +int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; } + +/* A reference picture's latent tokens at most: its area, a little over for the rounding of its + * sides to the size multiple. */ +int64_t ref_tokens_max(const RadGeneratorDecl& d) { + const int64_t s2 = d.latent_scale * d.latent_scale; + return (d.ref_area + s2 - 1) / s2 * 11 / 10 + 64; +} + +struct Sizes { + int64_t T = 0, S = 0, EP = 0, PD = 0, R = 0, P = 0, PX = 0, NT = 0, NB = 0; +}; + +Sizes sizes_of(const Program& prog, int64_t block_size) { + const RadGeneratorDecl& d = prog.generator; + Sizes z; + z.T = prog.ctx.max_tok; + z.S = prog.ctx.max_seqs; + z.EP = prog.encoder.modalities ? prog.ctx.max_enc_patches : 0; + z.PD = prog.encoder.modalities ? prog.encoder.patch_dim : 0; + z.R = d.max_refs; + z.P = z.T + z.R * ref_tokens_max(d); + const int64_t s2 = d.latent_scale * d.latent_scale; + z.PX = z.R * (ref_tokens_max(d) * s2) + d.max_tokens * s2; + z.NT = d.max_tokens; + z.NB = block_size > 0 ? (z.P + block_size - 1) / block_size : 0; + return z; +} + +/* The regions, in order, and the total. One function for both the allocation and the budget's + * count of it, so the two cannot disagree. */ +int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) { + const int64_t I = 4, H = 2; + const int64_t rope_rows = std::max(z.P, z.T); + const int64_t want[][2] = { + { 0, z.T * I }, /* R_TOK */ + { 0, z.T * I }, /* R_POS */ + { 0, 3 * z.T * I }, /* R_ROPE */ + { 0, (z.S + 1) * I }, /* R_CU */ + { 0, z.T * I }, /* R_MMROW */ + { 0, z.EP * z.PD * H }, /* R_ENCPIX */ + { 0, 4 * z.EP * I }, /* R_ENCCRD */ + { 0, (z.R + 2) * I }, /* R_ENCCU */ + { 0, z.P * I }, /* R_SRC */ + { 0, 3 * rope_rows * I }, /* R_GROPE */ + { 0, (12 * z.R + 24) * I }, /* R_SEG: offsets, {0, length} and start a segment, {0, tokens} a picture */ + { 0, z.P * I }, /* R_SLOT */ + { 0, z.PX * pixel_ch * H }, /* R_PX */ + { 0, z.NT * 4 }, /* R_MASK */ + { 0, z.S * 4 }, /* R_SIG */ + { 0, z.S * 4 }, /* R_SIGN */ + { 0, z.S * 4 }, /* R_CFG */ + { 0, z.S * I }, /* R_PAIR */ + { 0, z.S * I }, /* R_LANE */ + { 0, z.S * I }, /* R_FLAGS */ + { 0, 2 * z.S * 4 }, /* R_SEED */ + { 0, z.S * z.NB * I }, /* R_BT */ + { 0, z.S * I }, /* R_USED */ + }; + int64_t off = 0; + for (int r = 0; r < n; ++r) { + bytes[r][0] = off; + bytes[r][1] = want[r][1]; + off = align_up(off + want[r][1]); + } + return off; +} + +} /* namespace */ + +int64_t Driver::device_bytes(const Program& prog, const Config& cfg) { + (void)cfg; + if (!prog.is_generator() || prog.kv_groups.size() < 2) return 0; + const Sizes z = sizes_of(prog, prog.kv_groups[1].block_size); + int64_t b[R_N][2]; + return carve(z, prog.generator.pixel_channels, b, R_N); +} + +int Driver::init(const Program& prog, const Config& cfg, IKVManager* kv, + const std::vector& ranks) { + (void)cfg; + fini(); + if (!prog.is_generator()) return RAD_E_STATE; + decl_ = prog.generator; + fixed_ = prog.gen_str.sigmas; + kv_ = kv; + ranks_ = ranks; + /* ONE KV GROUP, PAGED: the conditioning's keys and values. A generator with no conditioning + * cache, or two, is not a shape this driver stages. Group handles start at 1 -- the program's + * group 0 is the null handle -- and the KV manager and a batch both index by handle. */ + if (prog.kv_groups.size() != 2 || prog.kv_groups[1].decl.kind != RAD_KV_FULL || + prog.kv_groups[1].block_size <= 0) { + RAD_ERR("image generator: the program declares %zu KV group(s); the driver stages exactly " + "one full-attention group, the conditioning's", prog.kv_groups.size() - 1); + return RAD_E_UNSUPPORTED; + } + kv_group_ = 1; + block_size_ = prog.kv_groups[1].block_size; + const Sizes z = sizes_of(prog, block_size_); + max_tok_ = z.T; + max_seqs_ = z.S; + max_enc_ = z.EP; + patch_dim_ = z.PD; + max_rows_ = z.P; + max_px_ = z.PX; + max_blocks_ = z.NB; + int64_t b[R_N][2]; + bytes_ = carve(z, decl_.pixel_channels, b, R_N); + for (int r = 0; r < R_N; ++r) { reg_[r].off = b[r][0]; reg_[r].bytes = b[r][1]; reg_[r].used = 0; } + + host_ = static_cast(rad_dev_alloc(bytes_, RAD_MEM_HOST_PINNED)); + img_bytes_ = decl_.max_tokens * decl_.latent_scale * decl_.latent_scale * decl_.pixel_channels; + img_host_ = rad_dev_alloc(img_bytes_, RAD_MEM_HOST_PINNED); + if (!host_ || !img_host_) { + RAD_ERR("image generator: no pinned host memory for the pass staging (%lld + %lld bytes)", + (long long)bytes_, (long long)img_bytes_); + return RAD_E_NOMEM; + } + std::memset(host_, 0, (size_t)bytes_); + dev_.assign(ranks_.size(), nullptr); + for (size_t r = 0; r < ranks_.size(); ++r) { + RAD_TRY(rad_dev_set(ranks_[r].device)); + dev_[r] = rad_dev_alloc(bytes_, RAD_MEM_DEVICE); + if (!dev_[r]) { + RAD_ERR("image generator: rank %zu has no room for the pass staging (%lld bytes)", r, + (long long)bytes_); + return RAD_E_NOMEM; + } + } + if (!ranks_.empty()) RAD_TRY(rad_dev_set(ranks_[0].device)); + out_.assign(ranks_.size(), RadBatch{}); + gout_.assign(ranks_.size(), RadGenBatch{}); + kout_.assign(ranks_.size(), RadKVGroupBatch{}); + lanes_.assign((size_t)decl_.max_lanes, Lane{}); + free_lanes_.clear(); + for (int64_t i = decl_.max_lanes - 1; i >= 0; --i) free_lanes_.push_back((int32_t)i); + return RAD_OK; +} + +void Driver::fini() { + for (size_t r = 0; r < dev_.size(); ++r) + if (dev_[r]) { + if (r < ranks_.size()) rad_dev_set(ranks_[r].device); + rad_dev_free(dev_[r], RAD_MEM_DEVICE); + } + dev_.clear(); + if (!ranks_.empty()) rad_dev_set(ranks_[0].device); + if (host_) rad_dev_free(host_, RAD_MEM_HOST_PINNED); + if (img_host_) rad_dev_free(img_host_, RAD_MEM_HOST_PINNED); + host_ = nullptr; + img_host_ = nullptr; +} + +/* ================================================================== requests */ +int Driver::submit(std::unique_ptr r, std::string* why) { + if (!r || !r->ticket) return RAD_E_INVAL; + const RadGeneratorDecl& d = decl_; + auto no = [&](const std::string& w) { + if (why) *why = w; + return RAD_E_INVAL; + }; + if (r->width <= 0 || r->height <= 0 || r->width % d.size_multiple || r->height % d.size_multiple) + return no("the size must be whole multiples of " + std::to_string(d.size_multiple) + + " pixels"); + const int64_t tokens = (int64_t)(r->width / d.latent_scale) * (r->height / d.latent_scale); + const int nb = r->has_neg ? 2 : 1; + if (tokens > d.max_tokens) + return no("the image is " + std::to_string(r->width) + "x" + std::to_string(r->height) + + "; the largest this model makes is " + std::to_string(d.max_tokens) + + " latent tokens (" + std::to_string(d.max_tokens * d.latent_scale * d.latent_scale) + + " pixels)"); + if (tokens * nb > max_tok_) + return no("an image of this size with guidance needs " + std::to_string(tokens * nb) + + " rows a step and a step carries " + std::to_string(max_tok_) + + " (--max-num-batched-tokens)"); + if (r->n < 1 || r->n > d.max_lanes) + return no("n must be 1.." + std::to_string(d.max_lanes)); + if ((int64_t)r->refs.size() > d.max_refs) + return no("at most " + std::to_string(d.max_refs) + " pictures a request"); + for (const Branch* b : { &r->pos, &r->neg }) { + if (b == &r->neg && !r->has_neg) continue; + if ((int64_t)b->tokens.size() > max_tok_) + return no("the prompt is " + std::to_string(b->tokens.size()) + " tokens with its " + "pictures; a conditioning pass carries " + std::to_string(max_tok_)); + int64_t np = 0; + if (b->media) + for (const mm::Placed& p : b->media->items) np += p.item ? p.item->n_patch : 0; + if (np > max_enc_) + return no("the pictures are " + std::to_string(np) + " patches together and a " + "conditioning pass encodes " + std::to_string(max_enc_) + + " (--mm-max-patches)"); + } + int64_t px = 0; + for (const Pixels& p : r->refs) px += (int64_t)p.w * p.h; + if (r->inpaint) px += (int64_t)r->inp_src.w * r->inp_src.h; + if (px > max_px_) return no("the pictures are larger than the staging holds"); + if (r->inpaint && ((int64_t)r->inp_mask.size() != tokens || r->inp_src.w != r->width || + r->inp_src.h != r->height)) + return no("the mask's picture is not at the size being made"); + if (r->previews < 0 || r->previews > 3) return no("partial_images must be 0..3"); + r->ticket->t_submit_ns = (int64_t)rad_mono_ns(); + std::lock_guard lk(mu_); + if (closed_) { + if (why) *why = closed_why_; + return closed_status_; + } + auto j = std::make_unique(); + j->id = next_id_++; + j->n_branch = nb; + j->tokens = tokens; + j->h_lat = (int32_t)(r->height / d.latent_scale); + j->w_lat = (int32_t)(r->width / d.latent_scale); + j->req = std::move(r); + jobs_.push_back(std::move(j)); + return RAD_OK; +} + +void Driver::shutdown(const char* why, int status) { + std::lock_guard lk(mu_); + closed_ = true; + closed_why_ = why ? why : "the engine stopped"; + closed_status_ = status; + for (auto& j : jobs_) j->req->ticket->finish(status, closed_why_); +} + +int64_t Driver::queued() const { + std::lock_guard lk(mu_); + int64_t n = 0; + for (const auto& j : jobs_) if (!j->admitted) ++n; + return n; +} + +int64_t Driver::running() const { + std::lock_guard lk(mu_); + int64_t n = 0; + for (const auto& j : jobs_) if (j->admitted) ++n; + return n; +} + +bool Driver::busy() const { + std::lock_guard lk(mu_); + return !jobs_.empty(); +} + +Driver::Job* Driver::job_locked(uint64_t id) { + for (auto& j : jobs_) if (j->id == id) return j.get(); + return nullptr; +} + +void Driver::release_locked(Job& j) { + for (int b = 0; b < 2; ++b) + if (j.cond[b].have_kv) { + kv_->free_sequence(j.cond[b].seq); + j.cond[b].have_kv = false; + } + for (int32_t l : j.lanes) { + lanes_[(size_t)l] = Lane{}; + free_lanes_.push_back(l); + } + j.lanes.clear(); +} + +void Driver::fail_locked(Job& j, int status, const std::string& why) { + j.failed = true; + j.req->ticket->finish(status, why); +} + +/* IN ORDER, AND A REQUEST THAT DOES NOT FIT STOPS THE ONES BEHIND IT. */ +int Driver::admit_locked() { + for (auto& jp : jobs_) { + Job& j = *jp; + if (j.admitted || j.failed) continue; + Request& r = *j.req; + if ((int64_t)free_lanes_.size() < r.n) break; + /* The sequences, once: their length is what the KV has to hold. */ + if (j.cond[0].lay.rows == 0) { + j.ref_hw.clear(); + for (const Pixels& p : r.refs) + j.ref_hw.push_back({ (int32_t)(p.h / decl_.latent_scale), + (int32_t)(p.w / decl_.latent_scale) }); + for (int b = 0; b < j.n_branch; ++b) { + std::string why; + const int s = build_layout(b ? r.neg : r.pos, decl_.slot_rows, j.ref_hw, + &j.cond[b].lay, &why); + if (s < 0) { fail_locked(j, s, why); break; } + if (j.cond[b].lay.rows > max_rows_) { + fail_locked(j, RAD_E_INVAL, "the conditioning is " + + std::to_string(j.cond[b].lay.rows) + " rows; the driver stages " + + std::to_string(max_rows_)); + break; + } + } + if (j.failed) continue; + } + bool ok = true; + for (int b = 0; b < j.n_branch && ok; ++b) { + Cond& c = j.cond[b]; + if (c.have_kv) continue; + if (!kv_->can_ever_fit(c.lay.rows)) { + fail_locked(j, RAD_E_INVAL, "the conditioning's " + std::to_string(c.lay.rows) + + " rows do not fit the KV cache even when it is empty"); + ok = false; + break; + } + c.seq = ((uint64_t)1 << 62) | next_seq_++; + if (kv_->add_sequence(c.seq) < 0) { ok = false; break; } + const int s = kv_->ensure(c.seq, c.lay.rows); + if (s < 0) { + kv_->free_sequence(c.seq); + ok = false; + break; + } + c.have_kv = true; + } + if (j.failed) continue; + if (!ok) { + /* The KV is short now: give back what this one took and wait. */ + for (int b = 0; b < 2; ++b) + if (j.cond[b].have_kv) { kv_->free_sequence(j.cond[b].seq); j.cond[b].have_kv = false; } + break; + } + j.sigmas = schedule(decl_, fixed_, r.steps, j.tokens); + const int32_t n_steps = (int32_t)j.sigmas.size() - 1; + for (int b = 0; b < j.n_branch; ++b) { + Cond& c = j.cond[b]; + c.rope_img.assign((size_t)(3 * j.tokens), 0); + image_rope(c.lay.next_pos, j.h_lat, j.w_lat, c.rope_img.data(), j.tokens); + } + for (int32_t i = 0; i < r.n; ++i) { + const int32_t l = free_lanes_.back(); + free_lanes_.pop_back(); + Lane& ln = lanes_[(size_t)l]; + ln = Lane{}; + ln.job = 0; + ln.job_id = j.id; + ln.index = i; + ln.seed = r.seed + (uint64_t)i; + for (int32_t k = 1; k <= r.previews; ++k) { + const int32_t at = (int32_t)((int64_t)n_steps * k / (r.previews + 1)); + if (at >= 1 && at < n_steps && + (ln.preview_at.empty() || ln.preview_at.back() != at)) + ln.preview_at.push_back(at); + } + j.lanes.push_back(l); + } + r.ticket->steps = n_steps; + int64_t in_tok = (int64_t)r.pos.tokens.size(); + if (r.has_neg) in_tok += (int64_t)r.neg.tokens.size(); + r.ticket->in_tokens = in_tok; + r.ticket->out_tokens = j.tokens * r.n; + j.admitted = true; + } + return RAD_OK; +} + +/* ================================================================== staging */ +int Driver::upload() { + for (size_t r = 0; r < ranks_.size(); ++r) + for (int g = 0; g < R_N; ++g) { + if (reg_[g].used <= 0) continue; + RAD_TRY(rad_memcpy_async((char*)dev_[r] + reg_[g].off, host_ + reg_[g].off, + reg_[g].used, ranks_[r].stream)); + } + return RAD_OK; +} + +void Driver::finish_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int step) { + for (size_t r = 0; r < ranks_.size(); ++r) { + RadBatch& B = out_[r]; + RadGenBatch& G = gout_[r]; + RadKVGroupBatch& K = kout_[r]; + const int ri = (int)r; + B.step = step; + B.phase = RAD_PHASE_PREFILL; + B.n_tok = n_tok; + B.n_seq = n_seq; + B.max_q_len = max_q; + B.token_ids = dptr(ri, R_TOK); + B.positions = dptr(ri, R_POS); + B.cu_seqlens = dptr(ri, R_CU); + B.q_lens = nullptr; + B.ctx_lens = nullptr; + B.n_seq_decode = 0; + B.n_tok_decode = 0; + B.max_q_len_prefill = max_q; + K.group = (rad_kvgroup)kv_group_; + K.slot_mapping = reg_[R_SLOT].used > 0 ? dptr(ri, R_SLOT) : nullptr; + K.block_table = dptr(ri, R_BT); + K.seqused = dptr(ri, R_USED); + K.block_size = block_size_; + K.max_blocks = max_blocks_; + B.n_kv_groups = 1; + B.kv = &K; + B.gen_b = &G; + G.src = dptr(ri, R_SRC); + G.rope = dptr(ri, R_GROPE); + G.seg = dptr(ri, R_SEG); + G.seg_h = hptr(R_SEG); + G.slot_mapping = dptr(ri, R_SLOT); + G.px = dptr(ri, R_PX); + G.inp_mask = dptr(ri, R_MASK); + G.sigma = dptr(ri, R_SIG); + G.sigma_next = dptr(ri, R_SIGN); + G.cfg = dptr(ri, R_CFG); + G.pair = dptr(ri, R_PAIR); + G.lane = dptr(ri, R_LANE); + G.lane_dh = hptr(R_LANE); + G.flags = dptr(ri, R_FLAGS); + G.seed = dptr(ri, R_SEED); + } +} + +/* ================================================================== the passes */ +const RadBatch* Driver::next(int step) { + std::lock_guard lk(mu_); + pass_ = Pass{}; + dec_bytes_ = 0; + if (closed_) return nullptr; + /* What finished, failed or was given up on since the last pass leaves now: its KV and lanes + * go back before anything is admitted. Nothing is in flight -- next() runs between passes. */ + for (auto it = jobs_.begin(); it != jobs_.end();) { + Job& j = **it; + const bool gone = j.failed || j.req->ticket->cancel.load(std::memory_order_acquire) || + (j.admitted && j.images_done >= j.req->n); + if (!gone) { ++it; continue; } + if (j.req->ticket->cancel.load(std::memory_order_acquire) && !j.failed && + j.images_done < j.req->n) + j.req->ticket->finish(RAD_E_CANCELLED, "the request was cancelled"); + release_locked(j); + it = jobs_.erase(it); + } + admit_locked(); + + /* 1. A decode an image is owed. */ + for (int32_t l = 0; l < (int32_t)lanes_.size(); ++l) { + Lane& ln = lanes_[(size_t)l]; + if (ln.job < 0 || ln.finished) continue; + if (ln.preview_due) return build_decode(l, true, step); + if (ln.final_due) return build_decode(l, false, step); + } + /* 2. A conditioning an admitted request is owed. */ + for (auto& jp : jobs_) { + Job& j = *jp; + if (!j.admitted || j.failed) continue; + for (int b = 0; b < j.n_branch; ++b) + if (!j.cond[b].encoded) return build_cond(j, b, step); + } + /* 3. A denoise step over what is in flight, oldest request first. */ + std::vector take; + int64_t rows = 0, entries = 0; + for (auto& jp : jobs_) { + Job& j = *jp; + if (!j.admitted || j.failed) continue; + bool ready = true; + for (int b = 0; b < j.n_branch; ++b) ready = ready && j.cond[b].encoded; + if (!ready) continue; + const int32_t n_steps = (int32_t)j.sigmas.size() - 1; + for (int32_t l : j.lanes) { + const Lane& ln = lanes_[(size_t)l]; + if (ln.finished || ln.final_due || ln.preview_due || ln.step >= n_steps) continue; + const int64_t need = j.tokens * j.n_branch; + if (rows + need > max_tok_ || entries + j.n_branch > max_seqs_) break; + rows += need; + entries += j.n_branch; + take.push_back(l); + } + } + if (take.empty()) return nullptr; + return build_denoise(take, step); +} + +const RadBatch* Driver::batch_for(int rank) const { + if (rank < 0 || (size_t)rank >= out_.size() || pass_.kind == 0) return nullptr; + return &out_[(size_t)rank]; +} + +const RadBatch* Driver::build_cond(Job& j, int branch, int step) { + for (int g = 0; g < R_N; ++g) reg_[g].used = 0; + const Request& r = *j.req; + const Branch& br = branch ? r.neg : r.pos; + const Cond& c = j.cond[branch]; + const int64_t T = (int64_t)br.tokens.size(), P = c.lay.rows; + + int32_t* tok = hptr(R_TOK); + int32_t* pos = hptr(R_POS); + int32_t* rope = hptr(R_ROPE); + std::memcpy(tok, br.tokens.data(), (size_t)T * 4); + for (int64_t i = 0; i < T; ++i) pos[i] = (int32_t)i; + for (int64_t i = 0; i < T; ++i) { + int32_t p3[3] = { (int32_t)i, (int32_t)i, (int32_t)i }; + if (br.media) br.media->rope.at(i, p3); + rope[i] = p3[0]; + rope[T + i] = p3[1]; + rope[2 * T + i] = p3[2]; + } + int32_t* cu = hptr(R_CU); + cu[0] = 0; + cu[1] = (int32_t)T; + reg_[R_TOK].used = reg_[R_POS].used = T * 4; + reg_[R_ROPE].used = 3 * T * 4; + reg_[R_CU].used = 2 * 4; + + /* The pictures, for the conditioning network's encoder: every item's patches in prompt order, + * one segment an item, and the prompt rows the encoder's output rows replace. */ + int64_t n_patch = 0, n_seg = 0, n_mm = 0; + int32_t max_seg = 0; + if (br.media) { + uint16_t* pix = hptr(R_ENCPIX); + int32_t* crd = hptr(R_ENCCRD); + int32_t* ecu = hptr(R_ENCCU); + int64_t total = 0; + for (const mm::Placed& p : br.media->items) total += p.item->n_patch; + std::vector row0; + int64_t rows_at = 0; + ecu[0] = 0; + std::vector tmp; + for (const mm::Placed& p : br.media->items) { + const mm::Item& it = *p.item; + std::memcpy(pix + n_patch * patch_dim_, it.pixels.data(), + (size_t)(it.n_patch * patch_dim_) * 2); + tmp.resize((size_t)(4 * it.n_patch)); + it.coords(0, it.n_patch, tmp.data()); + for (int cc = 0; cc < 4; ++cc) + std::memcpy(crd + cc * total + n_patch, tmp.data() + cc * it.n_patch, + (size_t)it.n_patch * 4); + for (int32_t s = 0; s < it.n_seg; ++s) { + const int64_t a = it.patch_at(s), e = it.patch_at(s + 1); + ecu[n_seg + 1] = (int32_t)(n_patch + e); + max_seg = std::max(max_seg, (int32_t)(e - a)); + ++n_seg; + } + row0.push_back(rows_at); + rows_at += it.n_rows(); + n_patch += it.n_patch; + } + int32_t* mmr = hptr(R_MMROW); + for (const mm::RopeLayout::Run& run : br.media->rope.runs) { + const int64_t base = row0[(size_t)run.item] + run.row0; + (void)base; + for (int32_t k = 0; k < run.n; ++k) mmr[n_mm++] = run.tok + k; + } + reg_[R_ENCPIX].used = n_patch * patch_dim_ * 2; + reg_[R_ENCCRD].used = 4 * total * 4; + reg_[R_ENCCU].used = (n_seg + 1) * 4; + reg_[R_MMROW].used = n_mm * 4; + } + + /* The generator's sequence, which the plugin runs a segment at a time: each segment's rotary + * positions as one dense [3, length] block, its own {0, length} and its first row. */ + std::memcpy(hptr(R_SRC), c.lay.src.data(), (size_t)P * 4); + const int64_t nsg = (int64_t)c.lay.bidi.size(); + int32_t* grope = hptr(R_GROPE); + int32_t* segp = hptr(R_SEG); + std::memcpy(segp, c.lay.seg.data(), (size_t)(nsg + 1) * 4); + for (int64_t s = 0; s < nsg; ++s) { + const int32_t a = c.lay.seg[(size_t)s], len = c.lay.seg[(size_t)s + 1] - a; + for (int cc = 0; cc < 3; ++cc) + std::memcpy(grope + 3 * (int64_t)a + cc * (int64_t)len, + &c.lay.rope[(size_t)(cc * P + a)], (size_t)len * 4); + segp[nsg + 1 + 2 * s] = 0; + segp[nsg + 1 + 2 * s + 1] = len; + segp[nsg + 1 + 2 * nsg + s] = a; + } + reg_[R_SRC].used = P * 4; + reg_[R_GROPE].used = 3 * P * 4; + reg_[R_SEG].used = (4 * nsg + 1) * 4; + const std::vector& bt = kv_->block_table(c.seq, kv_group_); + int32_t* slot = hptr(R_SLOT); + for (int64_t p = 0; p < P; ++p) { + const int64_t bi = p / block_size_; + slot[p] = bi < (int64_t)bt.size() ? (int32_t)(bt[(size_t)bi] * block_size_ + p % block_size_) + : -1; + } + reg_[R_SLOT].used = P * 4; + int32_t* btab = hptr(R_BT); + for (size_t i = 0; i < bt.size(); ++i) btab[i] = bt[i]; + reg_[R_BT].used = (int64_t)bt.size() * 4; + hptr(R_USED)[0] = (int32_t)P; + reg_[R_USED].used = 4; + + /* The pictures again, for the generator's own encoder, and with a mask the picture being + * repainted -- only the positive conditioning's pass writes the lanes. */ + const int64_t ch = decl_.pixel_channels; + uint16_t* px = hptr(R_PX); + std::vector pxh; + int64_t at = 0; + for (const Pixels& p : r.refs) { + std::memcpy(px + at * ch, p.bf16.data(), (size_t)((int64_t)p.w * p.h * ch) * 2); + pxh.insert(pxh.end(), { (int32_t)at, p.h, p.w }); + at += (int64_t)p.w * p.h; + } + const bool inp = r.inpaint && branch == 0; + if (inp) { + const Pixels& p = r.inp_src; + std::memcpy(px + at * ch, p.bf16.data(), (size_t)((int64_t)p.w * p.h * ch) * 2); + pxh.insert(pxh.end(), { (int32_t)at, p.h, p.w }); + at += (int64_t)p.w * p.h; + std::memcpy(hptr(R_MASK), r.inp_mask.data(), r.inp_mask.size() * 4); + reg_[R_MASK].used = (int64_t)r.inp_mask.size() * 4; + } + reg_[R_PX].used = at * ch * 2; + /* Each picture's latent tokens as a cu pair, after the segments' arrays. */ + const int64_t npx = (int64_t)pxh.size() / 3; + int32_t* pxcu = hptr(R_SEG) + 4 * nsg + 1; + for (int64_t b = 0; b < npx; ++b) { + pxcu[2 * b] = 0; + pxcu[2 * b + 1] = (pxh[(size_t)(3 * b + 1)] / (int32_t)decl_.latent_scale) * + (pxh[(size_t)(3 * b + 2)] / (int32_t)decl_.latent_scale); + } + reg_[R_SEG].used = (4 * nsg + 1 + 2 * npx) * 4; + /* The conditioning is modulated at t = 0. */ + hptr(R_SIG)[0] = 0.0f; + reg_[R_SIG].used = 4; + /* The host arrays the plugin reads on the host: the segments' kinds, the pixel blocks and the + * lanes. Kept here, in the driver, for the life of the pass. */ + host_bidi_ = c.lay.bidi; + host_px_ = pxh; + host_lanes_ = inp ? j.lanes : std::vector{}; + /* ...and the lanes on the device too: the repainted picture's latent and mask are copied into + * each of them by an op. */ + if (!host_lanes_.empty()) { + std::memcpy(hptr(R_LANE), host_lanes_.data(), host_lanes_.size() * 4); + reg_[R_LANE].used = (int64_t)host_lanes_.size() * 4; + } + + if (upload() < 0) return nullptr; + finish_batches(T, 1, (int32_t)T, step); + for (size_t rr = 0; rr < ranks_.size(); ++rr) { + RadBatch& B = out_[rr]; + RadGenBatch& G = gout_[rr]; + const int ri = (int)rr; + B.max_ctx_len = (int32_t)P; + B.rope_pos = dptr(ri, R_ROPE); + B.rope_mixed = br.media ? 1 : 0; + B.n_mm_rows = n_mm; + B.mm_rows = n_mm ? dptr(ri, R_MMROW) : nullptr; + B.mm_embd = nullptr; + B.enc = 0; + B.enc_n_patch = n_patch; + B.enc_pixels = n_patch ? dptr(ri, R_ENCPIX) : nullptr; + B.enc_coord = n_patch ? dptr(ri, R_ENCCRD) : nullptr; + B.enc_n_seg = n_seg; + B.enc_cu = n_seg ? dptr(ri, R_ENCCU) : nullptr; + B.enc_max_seg = max_seg; + B.gen = RAD_GEN_PASS_COND; + kout_[rr].block_table_pitch = (int64_t)bt.size(); + G = RadGenBatch{}; + G.rows = P; + G.src = dptr(ri, R_SRC); + G.rope = dptr(ri, R_GROPE); + G.n_seg = nsg; + G.seg = dptr(ri, R_SEG); + G.seg_h = hptr(R_SEG); + G.seg_bidi_h = host_bidi_.data(); + G.seg_cu = dptr(ri, R_SEG) + nsg + 1; + G.seg_start = dptr(ri, R_SEG) + nsg + 1 + 2 * nsg; + G.slot_mapping = dptr(ri, R_SLOT); + G.n_px = (int64_t)pxh.size() / 3; + G.px = at ? dptr(ri, R_PX) : nullptr; + G.px_h = host_px_.data(); + G.px_cu = dptr(ri, R_SEG) + 4 * nsg + 1; + G.sigma = dptr(ri, R_SIG); + G.inpaint = inp ? 1 : 0; + G.inp_mask = inp ? dptr(ri, R_MASK) : nullptr; + G.n_lane = (int64_t)host_lanes_.size(); + G.lane_h = host_lanes_.data(); + G.lane = G.n_lane ? dptr(ri, R_LANE) : nullptr; + } + pass_.kind = RAD_GEN_PASS_COND; + pass_.job = j.id; + pass_.branch = branch; + return &out_[0]; +} + +const RadBatch* Driver::build_denoise(const std::vector& take, int step) { + for (int g = 0; g < R_N; ++g) reg_[g].used = 0; + /* Two passes over the images: the entries and their rows, then the per-entry arrays. */ + struct E { const Job* j; int32_t lane; int branch; }; + std::vector es; + for (int32_t l : take) { + const Job* j = nullptr; + for (auto& jp : jobs_) if (jp->id == lanes_[(size_t)l].job_id) { j = jp.get(); break; } + if (!j) continue; + for (int b = 0; b < j->n_branch; ++b) es.push_back({ j, l, b }); + } + const int64_t S = (int64_t)es.size(); + int64_t n_tok = 0; + int32_t max_q = 0, max_ctx = 0; + int64_t pitch = 1; + for (const E& e : es) { + n_tok += e.j->tokens; + max_q = std::max(max_q, (int32_t)e.j->tokens); + max_ctx = std::max(max_ctx, (int32_t)e.j->cond[e.branch].lay.rows); + pitch = std::max(pitch, (int64_t)kv_->block_table(e.j->cond[e.branch].seq, kv_group_).size()); + } + int32_t* cu = hptr(R_CU); + int32_t* pos = hptr(R_POS); + int32_t* tok = hptr(R_TOK); + int32_t* grope = hptr(R_GROPE); + float* sig = hptr(R_SIG); + float* sign = hptr(R_SIGN); + float* cfg = hptr(R_CFG); + int32_t* pair = hptr(R_PAIR); + int32_t* lane = hptr(R_LANE); + int32_t* flags = hptr(R_FLAGS); + uint32_t* seed = hptr(R_SEED); + int32_t* btab = hptr(R_BT); + int32_t* used = hptr(R_USED); + int64_t row = 0; + cu[0] = 0; + pass_.lanes.clear(); + pass_.marks.clear(); + for (int64_t i = 0; i < S; ++i) { + const E& e = es[(size_t)i]; + const Job& j = *e.j; + const Lane& ln = lanes_[(size_t)e.lane]; + const Cond& c = j.cond[e.branch]; + const int64_t N = j.tokens; + for (int64_t k = 0; k < N; ++k) { pos[row + k] = (int32_t)k; tok[row + k] = 0; } + for (int cc = 0; cc < 3; ++cc) + std::memcpy(grope + cc * n_tok + row, c.rope_img.data() + cc * N, (size_t)N * 4); + row += N; + cu[i + 1] = (int32_t)row; + sig[i] = j.sigmas[(size_t)ln.step]; + sign[i] = j.sigmas[(size_t)ln.step + 1]; + const bool neg = e.branch == 1; + cfg[i] = neg ? 0.0f : (j.n_branch > 1 ? j.req->cfg : 1.0f); + pair[i] = neg ? -2 : (j.n_branch > 1 ? (int32_t)(i + 1) : -1); + lane[i] = e.lane; + int32_t f = 0; + bool mark = false; + if (!neg) { + if (ln.step == 0) f |= RAD_GEN_F_FIRST; + if (j.req->inpaint) f |= RAD_GEN_F_INPAINT; + if (ln.previews_done < (int32_t)ln.preview_at.size() && + ln.step + 1 == ln.preview_at[(size_t)ln.previews_done]) { + f |= RAD_GEN_F_PREVIEW; + mark = true; + } + pass_.lanes.push_back(e.lane); + pass_.marks.push_back(mark ? 1 : 0); + } + flags[i] = f; + seed[2 * i] = (uint32_t)(ln.seed & 0xffffffffu); + seed[2 * i + 1] = (uint32_t)(ln.seed >> 32); + const std::vector& bt = kv_->block_table(c.seq, kv_group_); + for (int64_t b = 0; b < pitch; ++b) + btab[i * pitch + b] = b < (int64_t)bt.size() ? bt[(size_t)b] : -1; + used[i] = (int32_t)c.lay.rows; + } + reg_[R_CU].used = (S + 1) * 4; + reg_[R_POS].used = reg_[R_TOK].used = n_tok * 4; + reg_[R_GROPE].used = 3 * n_tok * 4; + reg_[R_SIG].used = reg_[R_SIGN].used = reg_[R_CFG].used = S * 4; + reg_[R_PAIR].used = reg_[R_LANE].used = reg_[R_FLAGS].used = S * 4; + reg_[R_SEED].used = 2 * S * 4; + reg_[R_BT].used = S * pitch * 4; + reg_[R_USED].used = S * 4; + if (upload() < 0) return nullptr; + finish_batches(n_tok, S, max_q, step); + for (size_t rr = 0; rr < ranks_.size(); ++rr) { + RadBatch& B = out_[rr]; + const int ri = (int)rr; + B.max_ctx_len = max_ctx; + B.rope_pos = nullptr; + B.rope_mixed = 0; + B.n_mm_rows = 0; + B.mm_rows = nullptr; + B.enc_n_patch = 0; + B.enc_pixels = nullptr; + B.enc_coord = nullptr; + B.enc_n_seg = 0; + B.enc_cu = nullptr; + B.gen = RAD_GEN_PASS_DENOISE; + kout_[rr].block_table_pitch = pitch; + kout_[rr].slot_mapping = nullptr; + RadGenBatch& G = gout_[rr]; + G.rows = 0; + G.n_seg = 0; + G.seg_bidi_h = nullptr; + G.n_px = 0; + G.px_h = nullptr; + G.inpaint = 0; + G.n_lane = 0; + G.lane_h = nullptr; + G.rope = dptr(ri, R_GROPE); + G.lane_dh = hptr(R_LANE); + } + pass_.kind = RAD_GEN_PASS_DENOISE; + return &out_[0]; +} + +const RadBatch* Driver::build_decode(int32_t l, bool preview, int step) { + for (int g = 0; g < R_N; ++g) reg_[g].used = 0; + const Lane& ln = lanes_[(size_t)l]; + const Job* j = nullptr; + for (auto& jp : jobs_) if (jp->id == ln.job_id) { j = jp.get(); break; } + if (!j) return nullptr; + int32_t* cu = hptr(R_CU); + cu[0] = 0; + cu[1] = (int32_t)j->tokens; + reg_[R_CU].used = 2 * 4; + if (upload() < 0) return nullptr; + finish_batches(j->tokens, 1, (int32_t)j->tokens, step); + for (size_t rr = 0; rr < ranks_.size(); ++rr) { + RadBatch& B = out_[rr]; + B.max_ctx_len = 0; + B.rope_pos = nullptr; + B.rope_mixed = 0; + B.n_mm_rows = 0; + B.mm_rows = nullptr; + B.enc_n_patch = 0; + B.enc_pixels = nullptr; + B.enc_coord = nullptr; + B.enc_n_seg = 0; + B.enc_cu = nullptr; + B.gen = RAD_GEN_PASS_DECODE; + B.n_kv_groups = 0; + B.kv = nullptr; + RadGenBatch& G = gout_[rr]; + G = RadGenBatch{}; + G.dec_lane = l; + G.dec_height = j->req->height; + G.dec_width = j->req->width; + G.dec_preview = preview ? 1 : 0; + } + dec_bytes_ = (int64_t)j->req->width * j->req->height * decl_.pixel_channels; + pass_.kind = RAD_GEN_PASS_DECODE; + pass_.job = j->id; + pass_.lane = l; + pass_.preview = preview; + return &out_[0]; +} + +int Driver::done() { + std::lock_guard lk(mu_); + const uint64_t now = rad_mono_ns(); + switch (pass_.kind) { + case RAD_GEN_PASS_COND: { + Job* j = job_locked(pass_.job); + if (!j) break; + j->cond[pass_.branch].encoded = true; + bool all = true; + for (int b = 0; b < j->n_branch; ++b) all = all && j->cond[b].encoded; + if (all) j->req->ticket->t_cond_ns = (int64_t)now; + break; + } + case RAD_GEN_PASS_DENOISE: + for (size_t i = 0; i < pass_.lanes.size(); ++i) { + Lane& ln = lanes_[(size_t)pass_.lanes[i]]; + Job* j = job_locked(ln.job_id); + if (!j) continue; + if (ln.step == 0 && j->req->ticket->t_first_step_ns == 0) + j->req->ticket->t_first_step_ns = (int64_t)now; + ++ln.step; + const int32_t n_steps = (int32_t)j->sigmas.size() - 1; + if (pass_.marks[i]) ln.preview_due = true; + if (ln.step >= n_steps) { + ln.final_due = true; + j->req->ticket->t_denoised_ns = (int64_t)now; + } + } + break; + case RAD_GEN_PASS_DECODE: { + Lane& ln = lanes_[(size_t)pass_.lane]; + Job* j = job_locked(pass_.job); + if (!j) break; + Image im; + im.index = ln.index; + im.w = j->req->width; + im.h = j->req->height; + im.ch = (int32_t)decl_.pixel_channels; + im.seed = ln.seed; + im.px.assign((const uint8_t*)img_host_, (const uint8_t*)img_host_ + dec_bytes_); + if (pass_.preview) { + im.preview = true; + im.preview_no = ln.previews_done; + ln.preview_due = false; + ++ln.previews_done; + } else { + ln.final_due = false; + ln.finished = true; + ++j->images_done; + } + j->req->ticket->push(std::move(im)); + if (j->images_done >= j->req->n) { + j->req->ticket->t_done_ns = (int64_t)now; + j->req->ticket->finish(RAD_OK); + } + break; + } + default: + break; + } + pass_ = Pass{}; + dec_bytes_ = 0; + return RAD_OK; +} + +} /* namespace gen */ +} /* namespace rad */ diff --git a/core/gen/driver.h b/core/gen/driver.h new file mode 100644 index 00000000..13246d1d --- /dev/null +++ b/core/gen/driver.h @@ -0,0 +1,186 @@ +/* driver.h -- the image generator's pass driver (gen.h says what the passes are). + * + * ONE THREAD DRIVES IT, the engine's, and it asks two things a pass: `next()` decides what runs + * and stages it, `done()` folds the result back once every rank has run it. Requests arrive from + * HTTP threads through `submit()` and leave through their Ticket; the queue is the only thing the + * two kinds of thread share, behind one mutex. + * + * WHAT RUNS NEXT, in this order, one pass at a time: + * + * 1. a DECODE an image is owed -- a finished image, or a preview its last step marked. First, + * because a finished image frees its lane and answers its caller, and a preview must be read + * before the lane's next step writes the preview latent again. + * 2. a COND an admitted request is owed: its conditioning, so its images can join the next + * denoise pass. + * 3. a DENOISE over as many images in flight as fit the step's rows, oldest request first, each + * at its own step. + * + * A request is ADMITTED when it can get lanes for every image and KV for every conditioning + * sequence; until then it waits, in order -- a request that does not fit blocks the ones behind + * it, so a large request is not starved by a stream of small ones. + * + * THE STAGING is one region per rank on its card and one pinned host region with the same layout. + * Every pass is synchronised before the next is built (Engine::gen_loop), so one host region is + * enough: an image pass is tens of milliseconds and more, and the host work between two is + * microseconds. + */ +#pragma once +#include "gen.h" +#include "device/device.h" + +#include +#include + +namespace rad { +namespace gen { + +class Driver { +public: + struct RankIO { + int device = 0; + RadStream stream = nullptr; + }; + + /* `kv` is rank 0's KV manager: one block table serves every rank. */ + int init(const Program& prog, const Config& cfg, IKVManager* kv, const std::vector& ranks); + void fini(); + ~Driver() { fini(); } + + /* The bytes init() allocates on each rank's card, for the VRAM budget. */ + static int64_t device_bytes(const Program& prog, const Config& cfg); + + /* ---------------------------------------------------------- HTTP threads */ + /* Queue a request. Refused at once -- with `why` -- when it can never run: a size past the + * largest image, more pictures than the model takes, a conditioning longer than a pass. */ + int submit(std::unique_ptr r, std::string* why); + /* What a request may ask for: the model's own limits, for the server to check before it does + * the expensive part of preparing one. */ + const RadGeneratorDecl& decl() const { return decl_; } + const std::vector& fixed_sigmas() const { return fixed_; } + int64_t max_cond_tokens() const { return max_tok_; } + /* Fail every request queued or in flight, and refuse new ones. */ + void shutdown(const char* why, int status); + + /* ---------------------------------------------------------- the engine thread */ + /* The next pass, staged on every rank's stream, or null when there is nothing to run. + * `step` is the engine's pass counter, carried into RadBatch::step. */ + const RadBatch* next(int step); + const RadBatch* batch_for(int rank) const; + /* The bytes of the generator's image buffer the pass just staged makes, 0 for a pass that + * makes none: the engine copies them to `host()` behind the pass. */ + int64_t decode_bytes() const { return dec_bytes_; } + void* host_image() const { return img_host_; } + /* The pass has run on every rank and its streams are drained. */ + int done(); + bool busy() const; + + /* For /health, /stats and the dashboard. */ + int64_t queued() const; + int64_t running() const; + +private: + struct Cond { + Layout lay; + uint64_t seq = 0; /* the KV manager's key */ + bool have_kv = false; + bool encoded = false; + std::vector rope_img; /* [3, image tokens]: the image's rows at this sequence */ + }; + struct Job { + uint64_t id = 0; + std::unique_ptr req; + int n_branch = 1; + Cond cond[2]; + int32_t h_lat = 0, w_lat = 0; + int64_t tokens = 0; + std::vector sigmas; + std::vector lanes; + std::vector> ref_hw; + int32_t images_done = 0; + bool admitted = false; + bool failed = false; + }; + struct Lane { + int64_t job = -1; /* index into jobs_ by id; -1 free */ + uint64_t job_id = 0; + int32_t index = 0; + int32_t step = 0; + uint64_t seed = 0; + std::vector preview_at; /* the steps after which a preview is decoded */ + int32_t previews_done = 0; + bool preview_due = false; + bool final_due = false; + bool finished = false; + }; + /* What the pass being run is, for done(). */ + struct Pass { + int kind = 0; + uint64_t job = 0; + int branch = 0; + int32_t lane = -1; + bool preview = false; + std::vector lanes; /* DENOISE: the lanes it stepped, one per image */ + std::vector marks; /* ... and whether each was marked for a preview */ + }; + + /* 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_ROPE, R_CU, R_MMROW, R_ENCPIX, R_ENCCRD, R_ENCCU, R_SRC, R_GROPE, + R_SEG, R_SLOT, R_PX, R_MASK, R_SIG, R_SIGN, R_CFG, R_PAIR, R_LANE, R_FLAGS, R_SEED, + R_BT, R_USED, R_N }; + + int layout_regions(); + 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 finish_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int step); + + int admit_locked(); + void release_locked(Job& j); + void fail_locked(Job& j, int status, const std::string& why); + Job* job_locked(uint64_t id); + + const RadBatch* build_cond(Job& j, int branch, int step); + const RadBatch* build_denoise(const std::vector& lanes, int step); + const RadBatch* build_decode(int32_t lane, bool preview, int step); + + RadGeneratorDecl decl_{}; + std::vector fixed_; + int64_t max_tok_ = 0, max_seqs_ = 0, max_enc_ = 0, patch_dim_ = 0; + int64_t max_rows_ = 0; /* the longest conditioning sequence */ + int64_t max_px_ = 0; /* pixels the staging holds */ + int64_t block_size_ = 0, max_blocks_ = 0; + int32_t kv_group_ = 0; + std::vector ranks_; + IKVManager* kv_ = nullptr; + + char* host_ = nullptr; /* pinned, same layout as each slab */ + int64_t bytes_ = 0; + std::vector dev_; + Region reg_[R_N]; + void* img_host_ = nullptr; + int64_t img_bytes_ = 0; + int64_t dec_bytes_ = 0; + + std::vector out_; /* one per rank */ + std::vector gout_; + std::vector kout_; + Pass pass_; + /* The host arrays a COND pass's plugin reads on the host (RadGenBatch's _h fields). */ + std::vector host_bidi_, host_px_, host_lanes_; + + mutable std::mutex mu_; + std::deque> jobs_; /* arrival order */ + std::vector lanes_; + std::vector free_lanes_; + uint64_t next_id_ = 1; + uint64_t next_seq_ = 1; + bool closed_ = false; + std::string closed_why_; + int closed_status_ = RAD_E_STATE; +}; + +} /* namespace gen */ +} /* namespace rad */ diff --git a/core/gen/gen.cpp b/core/gen/gen.cpp new file mode 100644 index 00000000..6215d304 --- /dev/null +++ b/core/gen/gen.cpp @@ -0,0 +1,213 @@ +/* gen.cpp -- the request side of image generation: the ticket a caller waits on, the sampler's + * schedule, and the generator's sequence built from a conditioning prompt (gen.h). */ +#include "gen.h" + +#include +#include +#include + +namespace rad { +namespace gen { + +/* ================================================================== the ticket */ +void Ticket::push(Image&& im) { + { + std::lock_guard lk(mu_); + q_.push_back(std::move(im)); + } + cv_.notify_all(); +} + +void Ticket::finish(int status, const std::string& why) { + { + std::lock_guard lk(mu_); + if (done_) return; + done_ = true; + status_ = status; + why_ = why; + } + cv_.notify_all(); +} + +void Ticket::step(int32_t done, int32_t total) { + (void)done; + (void)total; +} + +bool Ticket::next(Image* out, int ms, bool* timed_out) { + std::unique_lock lk(mu_); + if (timed_out) *timed_out = false; + if (q_.empty() && !done_) + cv_.wait_for(lk, std::chrono::milliseconds(ms), [this] { return !q_.empty() || done_; }); + if (!q_.empty()) { + *out = std::move(q_.front()); + q_.pop_front(); + return true; + } + if (!done_ && timed_out) *timed_out = true; + return false; +} + +bool Ticket::finished() const { + std::lock_guard lk(mu_); + return done_ && q_.empty(); +} + +int Ticket::status() const { + std::lock_guard lk(mu_); + return status_; +} + +std::string Ticket::why() const { + std::lock_guard lk(mu_); + return why_; +} + +/* ================================================================== the schedule */ +/* diffusers' FlowMatchEulerDiscreteScheduler.set_timesteps with explicit sigmas, as the pipeline + * calls it, in the precision it runs at: the sigmas are an f32 array and every shift is numpy f32 + * arithmetic, the Python floats in it (exp(mu), the shift, the terminal) taking the array's type. */ +std::vector schedule(const RadGeneratorDecl& d, const std::vector& fixed, + int32_t steps, int64_t tokens) { + std::vector s; + if (!fixed.empty()) { + for (double v : fixed) s.push_back((float)v); + } else { + const int32_t n = steps > 0 ? steps : (int32_t)d.default_steps; + /* np.linspace(1.0, 1 / n, n) in f64, then astype(f32). */ + const double lo = 1.0 / (double)n; + for (int32_t i = 0; i < n; ++i) { + const double v = n == 1 ? 1.0 : 1.0 + (lo - 1.0) * (double)i / (double)(n - 1); + s.push_back((float)v); + } + } + if (d.dyn_shift) { + const double m = (d.max_shift - d.base_shift) / (double)(d.max_seq - d.base_seq); + const double b = d.base_shift - m * (double)d.base_seq; + const double mu = (double)tokens * m + b; + const float e = d.shift_exp ? (float)std::exp(mu) : (float)mu; + for (float& t : s) t = e / (e + (1.0f / t - 1.0f)); + } else { + const float sh = (float)d.shift; + for (float& t : s) t = sh * t / (1.0f + (sh - 1.0f) * t); + } + if (d.shift_terminal > 0 && !s.empty()) { + const float scale = (1.0f - s.back()) / (float)(1.0 - d.shift_terminal); + for (float& t : s) t = 1.0f - ((1.0f - t) / scale); + } + s.push_back(0.0f); + return s; +} + +/* ================================================================== the sequence */ +void image_rope(int32_t pos, int32_t h, int32_t w, int32_t* planes, int64_t n_total) { + const int32_t h0 = -(h - h / 2), w0 = -(w - w / 2); + int64_t k = 0; + for (int32_t r = 0; r < h; ++r) + for (int32_t c = 0; c < w; ++c, ++k) { + planes[k] = pos; + planes[n_total + k] = h0 + r; + planes[2 * n_total + k] = w0 + c; + } +} + +int build_layout(const Branch& b, int64_t slot_rows, + const std::vector>& ref_hw, Layout* out, + std::string* why) { + *out = Layout{}; + const int64_t T = (int64_t)b.tokens.size(); + if (b.n_drop < 0 || b.n_drop >= T) { + if (why) *why = "the conditioning prompt is no longer than its fixed prefix"; + return RAD_E_INVAL; + } + /* The media runs, in prompt order: [tok, tok + n) placeholder rows of item `item`. */ + struct Run { int64_t tok, n; int32_t item; }; + std::vector runs; + if (b.media) + for (const mm::RopeLayout::Run& r : b.media->rope.runs) + runs.push_back({ r.tok, r.n, r.item }); + if (runs.size() != ref_hw.size()) { + if (why) *why = "the prompt places " + std::to_string(runs.size()) + " picture(s) and " + + std::to_string(ref_hw.size()) + " were encoded for it"; + return RAD_E_INVAL; + } + /* Each picture's rows and where its latent rows start among all the references'. */ + std::vector lat0(ref_hw.size() + 1, 0); + for (size_t i = 0; i < ref_hw.size(); ++i) + lat0[i + 1] = lat0[i] + (int64_t)ref_hw[i].first * ref_hw[i].second; + int64_t rows = 0; + { + int64_t text = T - b.n_drop; + for (const Run& r : runs) { + if (r.tok < b.n_drop) { + if (why) *why = "a picture sits inside the prompt's fixed prefix"; + return RAD_E_INVAL; + } + text -= r.n; + } + rows = text; + for (size_t i = 0; i < runs.size(); ++i) { + const int64_t lat = (int64_t)ref_hw[i].first * ref_hw[i].second; + if (runs[i].n * slot_rows != lat) { + if (why) *why = "picture " + std::to_string(i + 1) + " has " + + std::to_string(runs[i].n) + " encoder rows, which do not tile its " + + std::to_string(ref_hw[i].first) + " x " + + std::to_string(ref_hw[i].second) + " latent grid"; + return RAD_E_INVAL; + } + rows += lat; + } + } + out->rows = rows; + out->src.assign((size_t)rows, 0); + out->rope.assign((size_t)rows * 3, 0); + out->seg.push_back(0); + int32_t pos = 0; + int64_t row = 0; + size_t ri = 0; + int64_t t = b.n_drop; + bool in_text = false; + auto close_text = [&]() { + if (in_text) { + out->seg.push_back((int32_t)row); + out->bidi.push_back(0); + in_text = false; + } + }; + while (t < T) { + if (ri < runs.size() && t == runs[ri].tok) { + close_text(); + const int32_t h = ref_hw[ri].first, w = ref_hw[ri].second; + const int64_t n = (int64_t)h * w; + for (int64_t k = 0; k < n; ++k) out->src[(size_t)(row + k)] = -(int32_t)(1 + lat0[ri] + k); + std::vector pl((size_t)n * 3); + image_rope(pos, h, w, pl.data(), n); + for (int c = 0; c < 3; ++c) + std::memcpy(&out->rope[(size_t)(c * rows + row)], &pl[(size_t)(c * n)], + (size_t)n * sizeof(int32_t)); + pos += h > w ? h : w; + row += n; + out->seg.push_back((int32_t)row); + out->bidi.push_back(1); + t += runs[ri].n; + ++ri; + continue; + } + in_text = true; + out->src[(size_t)row] = (int32_t)t; + for (int c = 0; c < 3; ++c) out->rope[(size_t)(c * rows + row)] = pos; + ++pos; + ++row; + ++t; + } + close_text(); + out->next_pos = pos; + if (row != rows) { + if (why) *why = "the generator's sequence did not come out at the length it was sized for"; + return RAD_E_STATE; + } + return RAD_OK; +} + +} /* namespace gen */ +} /* namespace rad */ diff --git a/core/gen/gen.h b/core/gen/gen.h new file mode 100644 index 00000000..cdb3f309 --- /dev/null +++ b/core/gen/gen.h @@ -0,0 +1,145 @@ +/* gen.h -- image generation: what a request is, what comes back, and the driver that turns one + * into the passes an image generator declares (rad_declare_generator, abi/rad_builder.h). + * + * A GENERATOR IS NOT DRIVEN BY TOKEN STEPS. Its work is three kinds of pass -- conditioning, + * denoising, decoding -- and an image is tens of denoising passes over thousands of latent rows, + * every one of them read whole, none of them sampled. The scheduler that serves text owns token + * positions, prefix reuse, preemption and speculation, and none of that has a meaning here, so the + * generator gets a driver of its own (this file) and shares everything below the step with the rest + * of the engine: the ranks, the plugin's step function, the KV manager the conditioning lives in. + * + * THE PASSES, as the driver runs them: + * + * COND once for every conditioning sequence a request has -- its prompt, and with guidance + * its negative prompt -- the prompt (and its reference pictures) encoded into the + * generator's KV group. A request is admitted once its lanes and its KV are free. + * DENOISE one step for each image in flight that fits the pass, any mix of requests, sizes and + * step counts: each image carries its own sigma. With guidance an image is two entries, + * its positive and its negative conditioning, which the plugin combines. + * DECODE one image's latent to pixels, read back and handed to its request. + * + * A request's images run in LANES -- the plugin's own latent state, `max_lanes` of them -- so one + * request of n images takes n lanes and shares one conditioning. + */ +#pragma once +#include "rad_core.h" +#include "mm/processor.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace rad { +struct IKVManager; +namespace gen { + +/* A picture as the generator's own encoder reads it: RGBA (or `ch` channels), row-major, each value + * bf16 in [-1, 1]. */ +struct Pixels { + int32_t w = 0, h = 0, ch = 4; + std::vector bf16; +}; + +/* ONE CONDITIONING SEQUENCE: the prompt as tokens, with the media it carries placed, and how many + * of its first tokens the generator does not see (RadGeneratorDecl::drop_prefix). */ +struct Branch { + std::vector tokens; + std::shared_ptr media; /* null for a prompt with no pictures */ + int32_t n_drop = 0; +}; + +/* ONE IMAGE, or one preview of one, on its way back. */ +struct Image { + int32_t index = 0; /* which of the request's n */ + int32_t w = 0, h = 0, ch = 4; + std::vector px; /* [h, w, ch] */ + bool preview = false; + int32_t preview_no = 0; + uint64_t seed = 0; +}; + +/* THE CHANNEL BACK TO THE CALLER: images as they finish, then the end. The driver's thread writes, + * the caller's reads; a mutex is enough -- an image is megabytes and there are a handful a + * request. `cancel` is the caller's, read by the driver at its next pass. */ +class Ticket { +public: + /* driver side */ + void push(Image&& im); + void finish(int status, const std::string& why = std::string()); + void step(int32_t done, int32_t total); + + /* caller side: the next image, or false once the request has ended and every image was taken. + * Waits at most `ms` milliseconds; `*timed_out` says a false was a timeout, not the end. */ + bool next(Image* out, int ms, bool* timed_out); + bool finished() const; + int status() const; + std::string why() const; + + std::atomic cancel{false}; + + /* What the request cost, for the response: the conditioning's tokens, the latent rows made, and + * the time each phase took. Written by the driver before finish(). */ + int64_t in_tokens = 0, out_tokens = 0; + int64_t t_submit_ns = 0, t_cond_ns = 0, t_first_step_ns = 0, t_denoised_ns = 0, t_done_ns = 0; + int32_t steps = 0; + +private: + mutable std::mutex mu_; + std::condition_variable cv_; + std::deque q_; + bool done_ = false; + int status_ = RAD_OK; + std::string why_; +}; + +struct Request { + Branch pos, neg; + bool has_neg = false; + float cfg = 1.0f; + int32_t width = 0, height = 0; /* pixels, whole multiples of the declared multiple */ + int32_t steps = 0; /* 0: the model's default (or its fixed schedule) */ + int32_t n = 1; + uint64_t seed = 0; /* image i draws its noise from seed + i */ + int32_t previews = 0; /* partial images per image, 0..3 */ + /* The reference pictures' encoder view, one per media item of `pos`, in order. */ + std::vector refs; + /* REPAINTING (an edit with a mask): the picture at the size being made, and per latent token + * how much of it is repainted (1) and how much kept (0). */ + bool inpaint = false; + Pixels inp_src; + std::vector inp_mask; + std::shared_ptr ticket; +}; + +/* ================================================================== the sampler's schedule */ +/* The sigmas a request steps through, n + 1 of them, the last 0: the decl's fixed schedule, or + * `steps` (0: the default) shifted the way the decl says. `tokens` is the image's latent token + * count, which a dynamic shift reads. f32, as the reference holds them. */ +std::vector schedule(const RadGeneratorDecl& d, const std::vector& fixed, + int32_t steps, int64_t tokens); + +/* ================================================================== the generator's sequence */ +/* ONE CONDITIONING SEQUENCE AS THE GENERATOR SEES IT (RadGeneratorDecl::layout): which prompt row + * or reference latent row each of its rows is, its rotary positions, its segments, and where the + * image being made starts. */ +struct Layout { + int64_t rows = 0; + std::vector src; /* [rows] */ + std::vector rope; /* [3, rows] component-major */ + std::vector seg; /* [n_seg + 1] */ + std::vector bidi; /* [n_seg] */ + int32_t next_pos = 0; /* the rotary count after the last row: the image's frame */ +}; +/* `ref_hw` is each reference's latent grid (h, w), in media order. RAD_E_INVAL with `why` when the + * prompt does not start with its drop prefix or a picture's slots do not tile its latent grid. */ +int build_layout(const Branch& b, int64_t slot_rows, const std::vector>& ref_hw, + Layout* out, std::string* why); +/* The rotary positions of an h x w image at frame `pos`: [3, h * w] component-major. */ +void image_rope(int32_t pos, int32_t h, int32_t w, int32_t* planes, int64_t n_total); + +} /* namespace gen */ +} /* namespace rad */ diff --git a/core/mem/kv.cpp b/core/mem/kv.cpp index c84467cb..3e534398 100644 --- a/core/mem/kv.cpp +++ b/core/mem/kv.cpp @@ -101,8 +101,10 @@ int KVManager::configure(const std::vector& groups, const Config& c int KVManager::plan_groups(const std::vector& groups, const Config& cfg) { /* Only to say it is ignored on a model with no recurrent state: the slots are host memory and - * the engine opens them (set_checkpoint_store). */ - const int64_t budget_ckpts = cfg.checkpoint_slots > 0 ? cfg.checkpoint_slots : 0; + * the engine opens them (set_checkpoint_store). The operator's own flag, not the default -- + * every model without such state would otherwise warn about a flag nobody passed. */ + const int64_t budget_ckpts = cfg.given.count("--checkpoint-slots") && cfg.checkpoint_slots > 0 + ? cfg.checkpoint_slots : 0; forget(); max_seqs_ = cfg.max_seqs > 0 ? cfg.max_seqs : 1; diff --git a/core/mem/vram_budget.cpp b/core/mem/vram_budget.cpp index 85852af8..e302b801 100644 --- a/core/mem/vram_budget.cpp +++ b/core/mem/vram_budget.cpp @@ -173,7 +173,7 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg exp = std::min(std::max(b.expert_ceiling, b.expert_floor), b.elastic - kv); /* THE ONE SEQUENCE WINS, and the experts it pushes off the card have no tier: the * planner refuses them by name. Said here too, with what moves it. */ - if (log && exp < b.expert_floor) + if (log && b.expert_floor > 0 && exp < b.expert_floor) RAD_WARN("one --max-model-len sequence's cache (%s) leaves the experts %s, short of " "the %s the pinned host pool cannot hold: raise --host-pool-mib or lower " "--max-model-len", diff --git a/core/mm/imaging.cpp b/core/mm/imaging.cpp new file mode 100644 index 00000000..49942406 --- /dev/null +++ b/core/mm/imaging.cpp @@ -0,0 +1,167 @@ +/* imaging.cpp -- PIL's Lanczos resize and alpha paste (imaging.h). The constants and the order of + * every operation are Pillow's (src/libImaging/Resample.c, Convert.c, Paste.c). */ +#include "mm/imaging.h" + +#include +#include +#include +#include + +namespace rad { +namespace mm { + +namespace { + +constexpr int kPrecision = 32 - 8 - 2; + +double sinc(double x) { + if (x == 0.0) return 1.0; + x *= M_PI; + return std::sin(x) / x; +} + +double lanczos(double x) { return (-3.0 <= x && x < 3.0) ? sinc(x) * sinc(x / 3.0) : 0.0; } + +/* One axis: for each output index its first input index, its tap count, and `ksize` fixed-point + * coefficients. */ +struct Axis { + int ksize = 0; + std::vector bounds; /* [out, 2]: xmin, count */ + std::vector kk; /* [out, ksize] */ +}; + +Axis coeffs(int in_size, int out_size) { + Axis a; + const double scale = (double)in_size / (double)out_size; + double filterscale = scale < 1.0 ? 1.0 : scale; + const double support = 3.0 * filterscale; + a.ksize = (int)std::ceil(support) * 2 + 1; + a.bounds.assign((size_t)out_size * 2, 0); + a.kk.assign((size_t)out_size * a.ksize, 0); + std::vector k((size_t)a.ksize); + for (int xx = 0; xx < out_size; ++xx) { + const double center = (xx + 0.5) * scale; + double ww = 0.0; + const double ss = 1.0 / filterscale; + int xmin = (int)(center - support + 0.5); + if (xmin < 0) xmin = 0; + int xmax = (int)(center + support + 0.5); + if (xmax > in_size) xmax = in_size; + xmax -= xmin; + int x = 0; + for (; x < xmax; ++x) { + const double w = lanczos((x + xmin - center + 0.5) * ss); + k[(size_t)x] = w; + ww += w; + } + for (x = 0; x < xmax; ++x) + if (ww != 0.0) k[(size_t)x] /= ww; + for (; x < a.ksize; ++x) k[(size_t)x] = 0.0; + a.bounds[(size_t)xx * 2] = xmin; + a.bounds[(size_t)xx * 2 + 1] = xmax; + for (x = 0; x < a.ksize; ++x) { + const double v = k[(size_t)x] * (double)(1 << kPrecision); + a.kk[(size_t)xx * a.ksize + x] = v < 0 ? (int)(-0.5 + v) : (int)(0.5 + v); + } + } + return a; +} + +inline uint8_t clip8(int v) { + if (v >= (1 << kPrecision << 8)) return 255; + if (v <= 0) return 0; + return (uint8_t)(v >> kPrecision); +} + +inline unsigned muldiv255(unsigned a, unsigned b) { + const unsigned t = a * b + 128; + return ((t >> 8) + t) >> 8; +} + +} /* namespace */ + +void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out) { + const int iw = src.w, ih = src.h; + /* RGBA -> RGBa: the colour premultiplied by the alpha */ + std::vector pre((size_t)iw * ih * 4); + for (size_t i = 0; i < (size_t)iw * ih; ++i) { + const unsigned al = src.rgba[i * 4 + 3]; + for (int c = 0; c < 3; ++c) pre[i * 4 + c] = (uint8_t)muldiv255(src.rgba[i * 4 + c], al); + pre[i * 4 + 3] = (uint8_t)al; + } + const bool horiz = w != iw, vert = h != ih; + const Axis ax = coeffs(iw, w), ay = coeffs(ih, h); + /* the rows the vertical pass reads */ + const int y_first = ay.bounds[0]; + const int y_last = ay.bounds[(size_t)(h - 1) * 2] + ay.bounds[(size_t)(h - 1) * 2 + 1]; + std::vector tmp; + const uint8_t* rows = pre.data(); + int rw = iw, row0 = 0; + if (horiz) { + const int th = vert ? y_last - y_first : ih; + const int off = vert ? y_first : 0; + tmp.assign((size_t)w * th * 4, 0); + for (int yy = 0; yy < th; ++yy) + for (int xx = 0; xx < w; ++xx) { + const int xmin = ax.bounds[(size_t)xx * 2], xn = ax.bounds[(size_t)xx * 2 + 1]; + const int* k = &ax.kk[(size_t)xx * ax.ksize]; + int s[4] = { 1 << (kPrecision - 1), 1 << (kPrecision - 1), 1 << (kPrecision - 1), + 1 << (kPrecision - 1) }; + const uint8_t* p = pre.data() + ((size_t)(yy + off) * iw + xmin) * 4; + for (int x = 0; x < xn; ++x) + for (int c = 0; c < 4; ++c) s[c] += (int)p[(size_t)x * 4 + c] * k[x]; + for (int c = 0; c < 4; ++c) tmp[((size_t)yy * w + xx) * 4 + c] = clip8(s[c]); + } + rows = tmp.data(); + rw = w; + row0 = vert ? y_first : 0; + } + std::vector res; + if (vert) { + res.assign((size_t)rw * h * 4, 0); + for (int yy = 0; yy < h; ++yy) { + const int ymin = ay.bounds[(size_t)yy * 2] - row0, yn = ay.bounds[(size_t)yy * 2 + 1]; + const int* k = &ay.kk[(size_t)yy * ay.ksize]; + for (int xx = 0; xx < rw; ++xx) { + int s[4] = { 1 << (kPrecision - 1), 1 << (kPrecision - 1), 1 << (kPrecision - 1), + 1 << (kPrecision - 1) }; + for (int y = 0; y < yn; ++y) { + const uint8_t* p = rows + ((size_t)(y + ymin) * rw + xx) * 4; + for (int c = 0; c < 4; ++c) s[c] += (int)p[c] * k[y]; + } + for (int c = 0; c < 4; ++c) res[((size_t)yy * rw + xx) * 4 + c] = clip8(s[c]); + } + } + } else { + res.assign(rows, rows + (size_t)rw * (horiz ? h : ih) * 4); + } + /* RGBa -> RGBA */ + out->w = w; + out->h = h; + out->rgba.resize((size_t)w * h * 4); + for (size_t i = 0; i < (size_t)w * h; ++i) { + const unsigned al = res[i * 4 + 3]; + for (int c = 0; c < 3; ++c) { + const unsigned v = res[i * 4 + c]; + out->rgba[i * 4 + c] = + (al == 255 || al == 0) ? (uint8_t)v : (uint8_t)std::min(255u, (255u * v) / al); + } + out->rgba[i * 4 + 3] = (uint8_t)al; + } +} + +void composite_white(const FrameRGBA& src, Frame* out) { + out->w = src.w; + out->h = src.h; + out->rgb.resize((size_t)src.w * src.h * 3); + for (size_t i = 0; i < (size_t)src.w * src.h; ++i) { + const unsigned a = src.rgba[i * 4 + 3]; + for (int c = 0; c < 3; ++c) { + const unsigned t = src.rgba[i * 4 + c] * a + 255u * (255u - a) + 128u; + out->rgb[i * 3 + c] = (uint8_t)(((t >> 8) + t) >> 8); + } + } +} + +} /* namespace mm */ +} /* namespace rad */ diff --git a/core/mm/imaging.h b/core/mm/imaging.h new file mode 100644 index 00000000..212da477 --- /dev/null +++ b/core/mm/imaging.h @@ -0,0 +1,25 @@ +/* imaging.h -- the picture arithmetic an image generator's reference pipeline does in PIL, done the + * way PIL does it, so a picture reaches the model as the reference's would. + * + * THE RESIZE IS PIL's Image.resize WITH LANCZOS, bit for bit: per-axis filter coefficients + * computed in double (support 3 times the downscale, normalised to sum one), turned into 22-bit + * fixed point, a horizontal pass then a vertical one over 8-bit values, each output rounded and + * clipped -- and an RGBA picture premultiplied by its alpha first and divided back after, which is + * what PIL's resize does to RGBA. Diffusers' VaeImageProcessor resizes a picture exactly this way. + * + * THE COMPOSITE is Image.paste(picture, mask=alpha) onto white: each channel + * (c * a + 255 * (255 - a)) / 255 in PIL's rounding -- how the reference flattens a transparent + * picture for a text encoder that reads RGB. */ +#pragma once +#include "mm/media.h" + +namespace rad { +namespace mm { + +/* `src` resized to w x h. */ +void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out); +/* `src` over an opaque white ground. */ +void composite_white(const FrameRGBA& src, Frame* out); + +} /* namespace mm */ +} /* namespace rad */ diff --git a/core/mm/media.cpp b/core/mm/media.cpp index 0a16bc0c..85343792 100644 --- a/core/mm/media.cpp +++ b/core/mm/media.cpp @@ -34,6 +34,13 @@ static int no_decoder(std::string* why) { int decode_image(const uint8_t*, size_t, int64_t, Frame*, std::string* why) { return no_decoder(why); } +int decode_image_rgba(const uint8_t*, size_t, int64_t, FrameRGBA*, std::string* why) { + return no_decoder(why); +} +int encode_image(const uint8_t*, int32_t, int32_t, int32_t, const std::string&, int32_t, + std::vector*, std::string* why) { + return no_decoder(why); +} int decode_video(const uint8_t*, size_t, SampleFn, const void*, int64_t, Video*, std::string* why) { return no_decoder(why); @@ -211,6 +218,46 @@ int to_rgb(const AVFrame* f, SwsContext** sws, Frame* out, std::string* why) { return RAD_OK; } +/* The same conversion to packed RGBA, for a picture whose alpha is kept. */ +int to_rgba(const AVFrame* f, SwsContext** sws, FrameRGBA* out, std::string* why) { + const AVPixelFormat src = (AVPixelFormat)f->format; + *sws = sws_getCachedContext(*sws, f->width, f->height, src, f->width, f->height, + AV_PIX_FMT_RGBA, SWS_BILINEAR, nullptr, nullptr, nullptr); + if (!*sws) { *why = "no colour conversion from this pixel format"; return RAD_E_UNSUPPORTED; } + int cs = f->colorspace; + if (cs == AVCOL_SPC_UNSPECIFIED || cs == AVCOL_SPC_RGB) cs = AVCOL_SPC_BT470BG; + const int src_full = f->color_range == AVCOL_RANGE_JPEG || + src == AV_PIX_FMT_YUVJ420P || src == AV_PIX_FMT_YUVJ422P || + src == AV_PIX_FMT_YUVJ444P || src == AV_PIX_FMT_YUVJ440P; + sws_setColorspaceDetails(*sws, sws_getCoefficients(cs), src_full, + sws_getCoefficients(SWS_CS_DEFAULT), 1, 0, 1 << 16, 1 << 16); + AVFrame* dst = av_frame_alloc(); + if (!dst) { *why = "out of memory"; return RAD_E_NOMEM; } + dst->format = AV_PIX_FMT_RGBA; + dst->width = f->width; + dst->height = f->height; + if (av_frame_get_buffer(dst, 0) < 0) { + av_frame_free(&dst); + *why = "out of memory"; + return RAD_E_NOMEM; + } + const int e = sws_scale(*sws, f->data, f->linesize, 0, f->height, dst->data, dst->linesize); + if (e != f->height) { + av_frame_free(&dst); + *why = "colour conversion failed"; + return RAD_E_INVAL; + } + out->w = f->width; + out->h = f->height; + const size_t row = (size_t)f->width * 4; + out->rgba.resize(row * (size_t)f->height); + for (int y = 0; y < f->height; ++y) + std::memcpy(out->rgba.data() + (size_t)y * row, dst->data[0] + (ptrdiff_t)y * dst->linesize[0], + row); + av_frame_free(&dst); + return RAD_OK; +} + /* THE DECODE LOOP, for both kinds: every frame in presentation order, `keep(i, frame)` told the * index of each and whether to stop. * @@ -313,6 +360,138 @@ int decode_image(const uint8_t* data, size_t n, int64_t max_pixels, Frame* out, return RAD_OK; } +int decode_image_rgba(const uint8_t* data, size_t n, int64_t max_pixels, FrameRGBA* out, + std::string* why) { + std::string w; + if (!why) why = &w; + if (!data || n == 0) { *why = "empty"; return RAD_E_INVAL; } + Input in; + RAD_TRY(in.open(data, n, true, why)); + const AVCodecParameters* cp = in.fmt->streams[in.stream]->codecpar; + if (cp->width <= 0 || cp->height <= 0) { *why = "the image has no size"; return RAD_E_INVAL; } + if ((int64_t)cp->width * cp->height > max_pixels) { + *why = "the image is " + std::to_string(cp->width) + "x" + std::to_string(cp->height) + + ", over the server's " + std::to_string(max_pixels) + "-pixel limit for a source"; + return RAD_E_INVAL; + } + SwsContext* sws = nullptr; + bool got = false; + const int s = decode_frames(in, [&](int64_t, const AVFrame* f) -> int { + const int c = to_rgba(f, &sws, out, why); + if (c < 0) return c; + got = true; + return 1; + }, why); + sws_freeContext(sws); + if (s < 0) return s; + if (!got) { *why = "the image decoded to no frame"; return RAD_E_INVAL; } + return RAD_OK; +} + +/* ONE PICTURE THROUGH ONE ENCODER. The pixels are converted to the pixel format the encoder takes + * (swscale, full-range BT.601 for jpeg's YUV, as PIL writes it), sent as one frame, and the one + * packet that comes back is the file: png, mjpeg and libwebp all write a complete image file a + * packet. */ +int encode_image(const uint8_t* px, int32_t w, int32_t h, int32_t ch, const std::string& format, + int32_t quality, std::vector* out, std::string* why) { + std::string wy; + if (!why) why = &wy; + if (!px || w <= 0 || h <= 0 || (ch != 3 && ch != 4) || !out) { + *why = "no picture to encode"; + return RAD_E_INVAL; + } + const AVCodec* codec = nullptr; + AVPixelFormat pf = AV_PIX_FMT_NONE; + if (format == "png") { + codec = avcodec_find_encoder(AV_CODEC_ID_PNG); + pf = ch == 4 ? AV_PIX_FMT_RGBA : AV_PIX_FMT_RGB24; + } else if (format == "jpeg") { + if (ch == 4) { *why = "jpeg carries no alpha"; return RAD_E_INVAL; } + codec = avcodec_find_encoder(AV_CODEC_ID_MJPEG); + pf = AV_PIX_FMT_YUVJ420P; + } else if (format == "webp") { + codec = avcodec_find_encoder_by_name("libwebp"); + pf = AV_PIX_FMT_BGRA; + } else { + *why = "'" + format + "' is not an image format this server writes (png, jpeg, webp)"; + return RAD_E_INVAL; + } + if (!codec) { + *why = "this build has no " + format + " encoder"; + return RAD_E_UNSUPPORTED; + } + AVCodecContext* cx = avcodec_alloc_context3(codec); + AVFrame* fr = av_frame_alloc(); + AVPacket* pk = av_packet_alloc(); + SwsContext* sws = nullptr; + int st = RAD_OK; + auto fail = [&](const std::string& m, int code) { *why = m; st = code; }; + do { + if (!cx || !fr || !pk) { fail("out of memory", RAD_E_NOMEM); break; } + cx->width = w; + cx->height = h; + cx->pix_fmt = pf; + cx->time_base = AVRational{ 1, 25 }; + cx->color_range = format == "jpeg" ? AVCOL_RANGE_JPEG : AVCOL_RANGE_UNSPECIFIED; + if (format == "jpeg") { + const int q = quality > 0 && quality <= 100 ? quality : 90; + /* qscale 2 (best) .. 31 (worst), linear in the quality */ + const int qs = 2 + (100 - q) * 29 / 100; + cx->flags |= AV_CODEC_FLAG_QSCALE; + cx->global_quality = FF_QP2LAMBDA * qs; + } + /* PNG AT zlib LEVEL 1 WITH PER-ROW PREDICTION: a 2048^2 picture in 0.16 s and 5.9 MB, where + * the encoder's default (level 6) takes 1.0 s for 5.3 MB -- a second of a few-step image + * model's request, on one core, for a tenth of the bytes. */ + if (format == "png") { + cx->compression_level = 1; + av_opt_set(cx->priv_data, "pred", "mixed", 0); + } + if (format == "webp") { + const int q = quality > 0 && quality <= 100 ? quality : 90; + if (q >= 100) av_opt_set_int(cx->priv_data, "lossless", 1, 0); + else av_opt_set_double(cx->priv_data, "quality", (double)q, 0); + } + int r = avcodec_open2(cx, codec, nullptr); + if (r < 0) { fail("the " + format + " encoder would not open (" + averr(r) + ")", RAD_E_INVAL); break; } + fr->format = pf; + fr->width = w; + fr->height = h; + if (av_frame_get_buffer(fr, 0) < 0) { fail("out of memory", RAD_E_NOMEM); break; } + const AVPixelFormat src = ch == 4 ? AV_PIX_FMT_RGBA : AV_PIX_FMT_RGB24; + sws = sws_getContext(w, h, src, w, h, pf, SWS_BILINEAR | SWS_ACCURATE_RND, nullptr, + nullptr, nullptr); + if (!sws) { fail("no colour conversion to the encoder's format", RAD_E_UNSUPPORTED); break; } + if (format == "jpeg") + sws_setColorspaceDetails(sws, sws_getCoefficients(SWS_CS_DEFAULT), 1, + sws_getCoefficients(SWS_CS_ITU601), 1, 0, 1 << 16, 1 << 16); + const uint8_t* sp[1] = { px }; + const int sl[1] = { w * ch }; + if (sws_scale(sws, sp, sl, 0, h, fr->data, fr->linesize) != h) { + fail("colour conversion failed", RAD_E_INVAL); + break; + } + fr->pts = 0; + r = avcodec_send_frame(cx, fr); + if (r >= 0) r = avcodec_send_frame(cx, nullptr); + if (r < 0) { fail("encoding failed (" + averr(r) + ")", RAD_E_INVAL); break; } + out->clear(); + for (;;) { + r = avcodec_receive_packet(cx, pk); + if (r == AVERROR_EOF || r == AVERROR(EAGAIN)) break; + if (r < 0) { fail("encoding failed (" + averr(r) + ")", RAD_E_INVAL); break; } + out->insert(out->end(), pk->data, pk->data + pk->size); + av_packet_unref(pk); + } + if (st == RAD_OK && out->empty()) fail("the encoder wrote nothing", RAD_E_INVAL); + } while (false); + sws_freeContext(sws); + av_packet_free(&pk); + av_frame_free(&fr); + avcodec_free_context(&cx); + return st; +} + int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* user, int64_t max_pixels, Video* out, std::string* why) { std::string w; diff --git a/core/mm/media.h b/core/mm/media.h index ba7614f9..98af3a2c 100644 --- a/core/mm/media.h +++ b/core/mm/media.h @@ -27,6 +27,13 @@ struct Frame { std::vector rgb; /* [h, w, 3] */ }; +/* A picture with its alpha: packed 8-bit RGBA, row-major, no padding -- what an image generator + * reads and writes. A source without alpha comes back opaque. */ +struct FrameRGBA { + int32_t w = 0, h = 0; + std::vector rgba; /* [h, w, 4] */ +}; + /* Is there a decoder in this build. */ bool decoder_available(); @@ -34,6 +41,16 @@ bool decoder_available(); * `max_pixels` in the SOURCE, which is what bounds the memory a request can make the server * allocate before any resize happens. */ int decode_image(const uint8_t* data, size_t n, int64_t max_pixels, Frame* out, std::string* why); +/* The same, keeping the alpha channel. */ +int decode_image_rgba(const uint8_t* data, size_t n, int64_t max_pixels, FrameRGBA* out, + std::string* why); + +/* A PICTURE TO A FILE: `px` is [h, w, ch] 8-bit, ch 3 (RGB) or 4 (RGBA), and `format` one of png, + * jpeg and webp. `quality` 0..100 is jpeg's and lossy webp's (0 or above 100: the format's own + * default); png is lossless and webp is lossless at 100. jpeg has no alpha and is refused one. + * RAD_E_UNSUPPORTED, with the reason, for a format this build has no encoder for. */ +int encode_image(const uint8_t* px, int32_t w, int32_t h, int32_t ch, const std::string& format, + int32_t quality, std::vector* out, std::string* why); /* HOW A VIDEO IS SAMPLED, and it happens INSIDE the decode rather than after it: a minute of 1080p * is 10 GB of RGB, so frames that are not sampled are never converted or kept. The choice of which diff --git a/core/rad_core.h b/core/rad_core.h index 8ce4da1f..7642efb1 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -380,6 +380,16 @@ public: /* ...and the audio encoder, the second a program may declare (RAD_MM_AUDIO). */ RadEncoderDecl audio_encoder{}; std::string audio_encoder_name; + /* THE IMAGE GENERATOR THIS PLUGIN DECLARED (rad_declare_generator); `layout` 0 when it declared + * none. The strings and the fixed schedule it points at are the copies below, not the plugin's + * storage. A generator program has no logits and no pooled vectors. */ + RadGeneratorDecl generator{}; + struct GenStrings { + std::string name, tmpl_text, tmpl_edit, tmpl_image, tmpl_image_sep, drop_prefix, + tmpl_transparent; + std::vector sigmas; + } gen_str; + bool is_generator() const { return generator.layout != 0; } /* Two arenas, because a host-site activation cannot index device memory. The buffer plan * colours the domains SEPARATELY -- a transient may share storage only with a transient in the diff --git a/core/runtime/ctx.cpp b/core/runtime/ctx.cpp index 3ec3afb8..83dd451b 100644 --- a/core/runtime/ctx.cpp +++ b/core/runtime/ctx.cpp @@ -994,6 +994,14 @@ int Ctx::lane_init() { /* Local: a lane join orders one card's two queues and nothing else reads through it. */ for (int i = 0; i < 2; ++i) if (!lane_ev_[i]) RAD_TRY(rad_event_create_local(&lane_ev_[i])); + /* A NEW LANE STARTS BEHIND EVERYTHING LANE 0 HAS ISSUED. Its first use is mid-step, and the + * join an architecture puts in front of it -- rad_lane_join(0, 1), then rad_lane(1) -- found no + * lane 1 to order and returned without doing anything. Unordered, the first op on the new + * stream reads lane 0's output before lane 0 has written it: on Qwen-Image's two-rank pass + * the first picture after startup took its first all-reduce of stale rows and came out a + * different picture, every later one the right one. */ + RAD_TRY(rad_event_record(lane_ev_[0], stream_)); + RAD_TRY(rad_event_wait(lane1_, lane_ev_[0])); return RAD_OK; } @@ -1008,8 +1016,9 @@ int Ctx::set_lane(int lane) { int Ctx::lane_join(int from, int to) { if (from == to) return RAD_OK; if (from < 0 || from > 1 || to < 0 || to > 1) return RAD_E_INVAL; - /* Nothing was ever issued on lane 1, so there is nothing to order against. This is the arm - * every unpipelined step takes at the end of run_step, and it must not build a stream. */ + /* Nothing was ever issued on lane 1, so there is nothing to order against -- and a lane 1 + * built later starts behind lane 0 (lane_init). This is the arm every unpipelined step takes + * at the end of run_step, and it must not build a stream. */ if (!lane1_) return RAD_OK; RadStream fs = from ? lane1_ : stream_, ts = to ? lane1_ : stream_; RAD_TRY(rad_event_record(lane_ev_[from], fs)); @@ -1025,6 +1034,8 @@ uint64_t Ctx::pass_key(const RadBatch* b) const { /* An encoder pass is shaped by its media, and a pass that carries encoder rows issues the * scatter that puts them in place only when it has some: neither repeats as a tape would. */ if (b->enc || b->n_mm_rows > 0) return 0; + /* A generator pass is shaped by what RadBatch::gen_b carries, which no key below reads. */ + if (b->gen) return 0; uint64_t h = 0x9e3779b97f4a7c15ull; auto mix = [&](uint64_t v) { h ^= v + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2); diff --git a/core/server/admin.cpp b/core/server/admin.cpp index 0eeec990..505450f8 100644 --- a/core/server/admin.cpp +++ b/core/server/admin.cpp @@ -429,12 +429,17 @@ json Server::capabilities() const { caps["chat"] = deps_.chat != nullptr; caps["tools"] = deps_.chat && deps_.chat->supports_tools(); caps["reasoning"] = deps_.chat && deps_.chat->supports_reasoning(); - caps["grammar"] = deps_.grammar != nullptr; + /* An image model reads pictures for its edits and nothing else, and writes no text a grammar + * could constrain -- whatever its conditioning network's processor would take. */ + const bool img = opt_.image_model; + caps["grammar"] = !img && deps_.grammar != nullptr; caps["embedding"] = deps_.embed != nullptr; caps["image"] = deps_.mm && deps_.mm->accepts(MediaKind::Image); - caps["video"] = deps_.mm && deps_.mm->accepts(MediaKind::Video); - caps["audio"] = deps_.mm && deps_.mm->accepts(MediaKind::Audio); + caps["video"] = !img && deps_.mm && deps_.mm->accepts(MediaKind::Video); + caps["audio"] = !img && deps_.mm && deps_.mm->accepts(MediaKind::Audio); caps["logprobs"] = opt_.supports_logprobs; + caps["image_generation"] = deps_.images != nullptr; + caps["image_edit"] = deps_.images != nullptr && deps_.images->info().max_refs > 0; /* THE EFFORTS A CHAT REQUEST MAY SEND, as probed from the template at startup: null when it * takes any word. "none" and "minimal" are this server's, and turn thinking off. */ if (lim_.reasoning_efforts.empty()) { diff --git a/core/server/http.cpp b/core/server/http.cpp index 164ab3a5..e44a09e1 100644 --- a/core/server/http.cpp +++ b/core/server/http.cpp @@ -406,11 +406,12 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) { }; auto bridge = [&router](const httplib::Request& hreq, std::string body, - httplib::Response& hres) { + httplib::Response& hres, std::vector form = {}) { HttpRequest req; req.method = hreq.method; req.path = hreq.path; req.body = std::move(body); + req.form = std::move(form); req.peer = hreq.remote_addr + ":" + std::to_string(hreq.remote_port); req.t_received_ns = std::chrono::duration_cast( std::chrono::steady_clock::now().time_since_epoch()).count(); @@ -459,14 +460,24 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) { /* A POST BODY IS READ STRAIGHT INTO THE STRING THE HANDLER PARSES. Left to httplib it * lands in its own Request first, which only hands it out const, so it would be copied * into ours: a body at the size limit held twice before a byte of it is looked at. A - * multipart body is not read at all -- no endpoint takes one, and httplib discards what a - * handler leaves unread -- so the handler sees an empty body and refuses it. */ + * multipart body (an image upload) is read as its parts, each straight into its own + * string, under the same size limit. */ svr.Post(path, [gate, bridge](const httplib::Request& q, httplib::Response& s, const httplib::ContentReader& read) { if (!gate(q, s)) return; std::string body; - if (!q.is_multipart_form_data() && - !read([&body](const char* p, size_t n) { body.append(p, n); return true; })) { + std::vector form; + const bool ok = q.is_multipart_form_data() + ? read([&form](const httplib::FormData& f) { + form.push_back(FormPart{ f.name, f.filename, f.content_type, {} }); + return true; + }, + [&form](const char* p, size_t n) { + if (!form.empty()) form.back().data.append(p, n); + return true; + }) + : read([&body](const char* p, size_t n) { body.append(p, n); return true; }); + if (!ok) { /* httplib has already set 413 for a body over the limit; anything else is a peer * that stopped sending partway, which has to be answered as something. */ if (s.status < 0) { @@ -477,7 +488,7 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) { } return; } - bridge(q, std::move(body), s); + bridge(q, std::move(body), s, std::move(form)); }); } /* THE PREFLIGHT ALLOWS WHATEVER HEADERS IT IS ASKED ABOUT. A browser client sends more than diff --git a/core/server/http.h b/core/server/http.h index cc694f72..c6f11ff1 100644 --- a/core/server/http.h +++ b/core/server/http.h @@ -24,10 +24,17 @@ struct CiLess { bool operator()(const std::string& a, const std::string& b) const; }; +/* One part of a multipart/form-data body: a field's value, or an uploaded file's bytes. */ +struct FormPart { + std::string name, filename, content_type, data; +}; + struct HttpRequest { std::string method = "GET"; std::string path; /* no query string */ std::string body; + /* A multipart/form-data body arrives as its parts, in order, and `body` is empty. */ + std::vector form; std::map headers; std::map query; std::map params; /* from a ":name" route segment */ diff --git a/core/server/iface.h b/core/server/iface.h index e1bba8ac..6f952663 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -23,6 +23,8 @@ #include namespace rad { +namespace gen { struct Request; } +namespace mm { struct Frame; struct Item; } namespace server { /* ordered_json, not json, and the reason is not cosmetic: a tool's parameter schema is rendered @@ -594,5 +596,34 @@ public: }; +/* THE IMAGE GENERATOR (core/gen), for a model that makes pictures rather than text: what the + * model declared about its prompts and sizes, and the queue a request goes into. The server turns + * an OpenAI images request into a gen::Request -- the prompt rendered and tokenised, the reference + * pictures resized for both of the model's readers -- and reads the pictures back off its ticket. */ +struct ImageGenInfo { + std::string name, tmpl_text, tmpl_edit, tmpl_image, tmpl_image_sep, drop_prefix, + tmpl_transparent; + int64_t latent_scale = 16, size_multiple = 32, pixel_channels = 4, max_tokens = 0; + int64_t max_refs = 0, ref_area = 0, default_width = 0, default_height = 0; + int64_t default_steps = 0, max_lanes = 1, max_cond_tokens = 0; + /* The model samples on a schedule of its own and takes no step count (a distilled model). */ + bool fixed_schedule = false; + int64_t fixed_steps = 0; + double default_cfg = 1.0; +}; + +class IImageGen { +public: + virtual ~IImageGen() = default; + virtual const ImageGenInfo& info() const = 0; + /* Queue a request; refused at once, with `why`, when it can never run. */ + virtual int submit(std::unique_ptr r, std::string* why) = 0; + /* A reference picture as the conditioning network's encoder reads it: RGB at the size it was + * resized to, which the processor must not change. */ + virtual int picture(const mm::Frame& f, std::shared_ptr* out, std::string* why) = 0; + virtual int64_t queued() const = 0; + virtual int64_t running() const = 0; +}; + } /* namespace server */ } /* namespace rad */ diff --git a/core/server/images.cpp b/core/server/images.cpp new file mode 100644 index 00000000..e095e0d6 --- /dev/null +++ b/core/server/images.cpp @@ -0,0 +1,731 @@ +/* images.cpp -- OpenAI's images API over an image generator (core/gen): /v1/images/generations + * and /v1/images/edits. + * + * WHAT A REQUEST BECOMES. The prompt goes into the model's own template (ImageGenInfo), with the + * fixed system turn the generator drops; a transparent background asks for one in the words the + * model was trained on. An edit's pictures are each resized to the model's reference area at their + * own aspect -- with PIL's premultiplied Lanczos, as diffusers resizes them -- and read twice: as + * RGBA pixels by the generator's encoder, and composited on white by the conditioning network's. + * With a mask, the first picture is repainted: the mask's transparent pixels are where it may + * change, the rest is put back exactly after decoding. + * + * WHAT IS EXTENDED, beside OpenAI's fields, by vLLM-Omni's names: `seed`, `negative_prompt` with + * `true_cfg_scale` (guidance), `num_inference_steps`, and `width` / `height` in place of `size`. + * A model with a fixed schedule (a distilled one) takes no step count but its own. + * + * WHAT IS REFUSED: `response_format: url` -- nothing here stores an image to serve later, so the + * picture comes back in the response (b64_json) or not at all. + * + * STREAMING is OpenAI's: `image_generation.partial_image` (`image_edit.partial_image`) events + * for the `partial_images` previews -- the step's estimate of the finished latent, decoded -- and + * one `.completed` event an image. + */ +#include "server.h" +#include "oai.h" + +#include "gen/gen.h" +#include "mm/imaging.h" +#include "mm/media.h" +#include "mm/processor.h" +#include "rad_internal.h" + +#include + +#include +#include +#include +#include +#include +#include + +namespace rad { +namespace server { + +namespace { + +/* The largest picture a request may upload, before any resize. */ +constexpr int64_t kMaxSourcePixels = (int64_t)1 << 26; + +/* Below this alpha a pixel is transparent: where a mask lets the picture change, and what makes a + * picture one with transparency. A decoder's alpha is not exactly 255 on an opaque picture, so a + * picture this model made and is given back to edit stays opaque. */ +constexpr uint8_t kTransparentBelow = 128; + +struct ImgReq { + bool edit = false; + std::string prompt, negative; + bool has_neg = false; + double cfg = 1.0; + int32_t w = 0, h = 0, n = 1, steps = 0, previews = 0; + bool seed_given = false; + uint64_t seed = 0; + std::string background = "auto", format = "png", quality = "auto"; + int32_t compression = -1; + bool stream = false; + std::vector images; + bool has_mask = false; + mm::FrameRGBA mask; +}; + +/* A multipart field's text as the JSON value the same field takes in a JSON body. */ +json form_value(const std::string& key, const std::string& v) { + static const char* ints[] = { "n", "seed", "num_inference_steps", "partial_images", + "output_compression", "width", "height" }; + for (const char* k : ints) + if (key == k) { + char* e = nullptr; + const long long x = std::strtoll(v.c_str(), &e, 10); + if (e && *e == 0 && !v.empty()) return json(x); + return json(v); + } + if (key == "true_cfg_scale") { + char* e = nullptr; + const double x = std::strtod(v.c_str(), &e); + if (e && *e == 0 && !v.empty()) return json(x); + return json(v); + } + if (key == "stream") { + if (v == "true" || v == "1") return json(true); + if (v == "false" || v == "0") return json(false); + } + return json(v); +} + +/* diffusers' calculate_dimensions: a target area at an aspect, each side rounded to 32. */ +void dims_for(double area, double ratio, int32_t mult, int32_t* w, int32_t* h) { + const double wd = std::sqrt(area * ratio); + const double hd = wd / ratio; + *w = (int32_t)std::lround(wd / mult) * mult; + *h = (int32_t)std::lround(hd / mult) * mult; + if (*w < mult) *w = mult; + if (*h < mult) *h = mult; +} + +std::string replace_all(std::string s, const std::string& what, const std::string& with) { + for (size_t p = s.find(what); p != std::string::npos; p = s.find(what, p + with.size())) + s.replace(p, what.size(), with); + return s; +} + +uint16_t f32_bf16(float f) { + uint32_t u; + std::memcpy(&u, &f, 4); + u += 0x7FFFu + ((u >> 16) & 1u); + return (uint16_t)(u >> 16); +} + +/* A picture as the generator's encoder reads it: each channel u -> 2 * (u / 255) - 1 in f32, then + * bf16 -- VaeImageProcessor's preprocess, cast to the VAE's dtype. */ +gen::Pixels to_pixels(const mm::FrameRGBA& f) { + gen::Pixels p; + p.w = f.w; + p.h = f.h; + p.ch = 4; + p.bf16.resize(f.rgba.size()); + for (size_t i = 0; i < f.rgba.size(); ++i) + p.bf16[i] = f32_bf16(2.0f * ((float)f.rgba[i] / 255.0f) - 1.0f); + return p; +} + +/* The decoded RGBA flattened on white (no alpha), for a jpeg or an opaque background. */ +std::vector on_white(const std::vector& rgba, int32_t w, int32_t h) { + mm::FrameRGBA f; + f.w = w; + f.h = h; + f.rgba = rgba; + mm::Frame o; + mm::composite_white(f, &o); + return std::move(o.rgb); +} + +} /* namespace */ + +HttpResponse Server::handle_images(const HttpRequest& req, bool edit) { + if (!deps_.images || !deps_.tok) + return error_response(err_not_implemented( + "the images API requires an image generation model; this one generates text"), + req.peer); + const ImageGenInfo& info = deps_.images->info(); + const char* ep = edit ? "/v1/images/edits" : "/v1/images/generations"; + if (edit && info.max_refs <= 0) + return error_response(err_not_implemented("this model makes images from text only"), + req.peer); + + /* ---- the body, JSON or (an edit's usual form) multipart, as one JSON object */ + json body = json::object(); + std::vector> files; + std::vector mask_bytes; + bool have_mask = false; + if (!req.form.empty()) { + for (const FormPart& p : req.form) { + if (p.name == "image" || p.name == "image[]") { + files.emplace_back(p.data.begin(), p.data.end()); + } else if (p.name == "mask") { + mask_bytes.assign(p.data.begin(), p.data.end()); + have_mask = true; + } else { + body[p.name] = form_value(p.name, p.data); + } + } + } else { + try { + body = json::parse(req.body); + } catch (const std::exception& e) { + return error_response(err_bad("", std::string("the body is not JSON: ") + e.what()), + req.peer); + } + if (!body.is_object()) return error_response(err_bad("", "the body is not a JSON object"), req.peer); + /* An edit's pictures as JSON: `images: [{image_url: "data:..."}]` and `mask: {image_url}`, + * the newer form of the API, or `image` as one data URL or a list of them. */ + auto url_of = [](const json& v, std::string* u) { + if (v.is_string()) { *u = v.get(); return true; } + if (v.is_object() && v.contains("image_url") && v["image_url"].is_string()) { + *u = v["image_url"].get(); + return true; + } + if (v.is_object() && v.contains("image_url") && v["image_url"].is_object() && + v["image_url"].contains("url") && v["image_url"]["url"].is_string()) { + *u = v["image_url"]["url"].get(); + return true; + } + return false; + }; + for (const char* key : { "images", "image" }) { + if (!body.contains(key)) continue; + const json v = body[key]; + body.erase(key); + std::vector list; + if (v.is_array()) list.assign(v.begin(), v.end()); + else list.push_back(v); + for (const json& e : list) { + std::string u; + if (!url_of(e, &u)) + return error_response(err_bad(key, "a picture is a data: URL, or an object " + "with an image_url"), req.peer); + std::vector bytes; + ApiError err; + if (decode_media_url(u, key, &bytes, &err) < 0) return error_response(err, req.peer); + files.push_back(std::move(bytes)); + } + } + if (body.contains("mask")) { + std::string u; + if (!url_of(body["mask"], &u)) + return error_response(err_bad("mask", "the mask is a data: URL, or an object with " + "an image_url"), req.peer); + body.erase("mask"); + ApiError err; + if (decode_media_url(u, "mask", &mask_bytes, &err) < 0) + return error_response(err, req.peer); + have_mask = true; + } + } + + /* ---- the fields */ + ImgReq r; + r.edit = edit; + static const char* kKnown[] = { + "prompt", "model", "n", "size", "quality", "background", "output_format", + "output_compression", "response_format", "stream", "partial_images", "moderation", + "style", "user", "input_fidelity", "seed", "negative_prompt", "true_cfg_scale", + "num_inference_steps", "width", "height", + }; + for (auto it = body.begin(); it != body.end(); ++it) { + bool known = false; + for (const char* k : kKnown) known = known || it.key() == k; + if (!known) + return error_response(err_bad(it.key(), "'" + it.key() + "' is not a field of " + + std::string(ep)), req.peer); + } + auto str = [&](const char* k, std::string* out) -> int { + if (!body.contains(k) || body[k].is_null()) return 0; + if (!body[k].is_string()) return -1; + *out = body[k].get(); + return 1; + }; + auto num = [&](const char* k, int64_t lo, int64_t hi, int64_t* out) -> int { + if (!body.contains(k) || body[k].is_null()) return 0; + if (!body[k].is_number_integer()) return -1; + const int64_t v = body[k].get(); + if (v < lo || v > hi) return -1; + *out = v; + return 1; + }; + if (str("prompt", &r.prompt) < 0) + return error_response(err_bad("prompt", "a string"), req.peer); + if (!body.contains("prompt")) + return error_response(err_bad("prompt", "the prompt is required"), req.peer); + if (r.prompt.empty()) r.prompt = " "; + std::string rf; + if (str("response_format", &rf) < 0 || (!rf.empty() && rf != "b64_json" && rf != "url")) + return error_response(err_bad("response_format", "b64_json"), req.peer); + if (rf == "url") { + ApiError e = err_unsupported("response_format", + "url is not served: this server keeps no image to serve " + "later; ask for b64_json"); + e.supported = { "b64_json" }; + return error_response(e, req.peer); + } + int64_t v = 0; + if (num("n", 1, info.max_lanes, &v) < 0) + return error_response(err_bad("n", "1.." + std::to_string(info.max_lanes)), req.peer); + r.n = body.contains("n") && !body["n"].is_null() ? (int32_t)v : 1; + if (str("background", &r.background) < 0 || + (r.background != "auto" && r.background != "transparent" && r.background != "opaque")) { + ApiError e = err_bad("background", "auto, transparent or opaque"); + e.supported = { "auto", "transparent", "opaque" }; + return error_response(e, req.peer); + } + if (str("output_format", &r.format) < 0 || + (r.format != "png" && r.format != "jpeg" && r.format != "webp")) { + ApiError e = err_bad("output_format", "png, jpeg or webp"); + e.supported = { "png", "jpeg", "webp" }; + return error_response(e, req.peer); + } + if (r.background == "transparent" && r.format == "jpeg") + return error_response(err_bad("background", "jpeg has no transparency; ask for png or " + "webp"), req.peer); + if (num("output_compression", 0, 100, &v) < 0) + return error_response(err_bad("output_compression", "0..100"), req.peer); + if (body.contains("output_compression")) r.compression = (int32_t)v; + if (body.contains("stream") && !body["stream"].is_null()) { + if (!body["stream"].is_boolean()) return error_response(err_bad("stream", "a boolean"), req.peer); + r.stream = body["stream"].get(); + } + if (num("partial_images", 0, 3, &v) < 0) + return error_response(err_bad("partial_images", "0..3"), req.peer); + if (body.contains("partial_images")) r.previews = (int32_t)v; + if (r.previews > 0 && !r.stream) + return error_response(err_bad("partial_images", "partial images are sent on a stream; " + "set stream"), req.peer); + if (str("quality", &r.quality) < 0 || + (r.quality != "auto" && r.quality != "low" && r.quality != "medium" && + r.quality != "high" && r.quality != "standard" && r.quality != "hd")) { + ApiError e = err_bad("quality", "auto, low, medium, high (standard, hd)"); + e.supported = { "auto", "low", "medium", "high", "standard", "hd" }; + return error_response(e, req.peer); + } + /* The step count: the request's, or what its quality asks for, or the model's. */ + int64_t steps = 0; + if (num("num_inference_steps", 1, 200, &steps) < 0) + return error_response(err_bad("num_inference_steps", "1..200"), req.peer); + if (info.fixed_schedule) { + if (steps != 0 && steps != info.fixed_steps) + return error_response(err_unsupported("num_inference_steps", + "this model samples on its own " + + std::to_string(info.fixed_steps) + + "-step schedule and takes no other"), + req.peer); + steps = 0; + } else if (steps == 0) { + if (r.quality == "low") steps = std::max(1, info.default_steps / 2); + else if (r.quality == "medium") steps = std::max(1, info.default_steps * 3 / 4); + } + r.steps = (int32_t)steps; + if (body.contains("seed") && !body["seed"].is_null()) { + if (!body["seed"].is_number_integer()) + return error_response(err_bad("seed", "an integer"), req.peer); + r.seed = (uint64_t)body["seed"].get(); + r.seed_given = true; + } + if (str("negative_prompt", &r.negative) < 0) + return error_response(err_bad("negative_prompt", "a string"), req.peer); + if (body.contains("true_cfg_scale") && !body["true_cfg_scale"].is_null()) { + if (!body["true_cfg_scale"].is_number()) + return error_response(err_bad("true_cfg_scale", "a number"), req.peer); + r.cfg = body["true_cfg_scale"].get(); + if (!(r.cfg >= 1.0 && r.cfg <= 30.0)) + return error_response(err_bad("true_cfg_scale", "1..30"), req.peer); + } + /* Guidance needs both halves, as the reference pipeline does: a scale above one and a + * negative prompt (an empty one is " "). */ + r.has_neg = r.cfg > 1.0 && body.contains("negative_prompt"); + if (r.has_neg && r.negative.empty()) r.negative = " "; + if (r.cfg > 1.0 && !r.has_neg) + return error_response(err_bad("true_cfg_scale", "guidance needs a negative_prompt"), + req.peer); + + /* ---- the pictures */ + if (edit) { + if (files.empty()) + return error_response(err_bad("image", "an edit needs at least one picture"), req.peer); + if ((int64_t)files.size() > info.max_refs) + return error_response(err_bad("image", "at most " + std::to_string(info.max_refs) + + " pictures"), req.peer); + for (size_t i = 0; i < files.size(); ++i) { + mm::FrameRGBA f; + std::string why; + if (mm::decode_image_rgba(files[i].data(), files[i].size(), kMaxSourcePixels, &f, + &why) < 0) + return error_response(err_bad("image", "picture " + std::to_string(i + 1) + + ": " + why), req.peer); + r.images.push_back(std::move(f)); + } + if (have_mask) { + std::string why; + if (mm::decode_image_rgba(mask_bytes.data(), mask_bytes.size(), kMaxSourcePixels, + &r.mask, &why) < 0) + return error_response(err_bad("mask", why), req.peer); + if (r.mask.w != r.images[0].w || r.mask.h != r.images[0].h) + return error_response(err_bad("mask", "the mask must be the first picture's " + "size"), req.peer); + r.has_mask = true; + } + } else if (!files.empty() || have_mask) { + return error_response(err_bad("image", "pictures go to /v1/images/edits"), req.peer); + } + /* `auto` is decided by what was sent: an edit of a picture with transparency keeps it, and + * anything else is opaque -- a picture made without asking for transparency carries only the + * decoder's noise in its alpha. */ + if (r.background == "auto") { + bool alpha = false; + if (r.format != "jpeg") + for (const mm::FrameRGBA& f : r.images) + for (size_t i = 3; i < f.rgba.size() && !alpha; i += 4) + alpha = f.rgba[i] < kTransparentBelow; + r.background = alpha ? "transparent" : "opaque"; + } + + /* ---- the size: `width`/`height`, or `size` "WxH", or auto -- the native size, at the last + * picture's aspect for an edit. Sides are rounded down to the model's multiple. */ + const int32_t mult = (int32_t)info.size_multiple; + std::string size = "auto"; + if (str("size", &size) < 0) return error_response(err_bad("size", "\"WxH\" or \"auto\""), req.peer); + int64_t bw = 0, bh = 0; + if (num("width", 1, 16384, &bw) < 0 || num("height", 1, 16384, &bh) < 0) + return error_response(err_bad("width", "1..16384"), req.peer); + if ((bw > 0) != (bh > 0)) + return error_response(err_bad(bw ? "height" : "width", "width and height go together"), + req.peer); + if (bw > 0) { + r.w = (int32_t)bw; + r.h = (int32_t)bh; + } else if (size != "auto") { + int a = 0, b = 0; + char x = 0; + if (std::sscanf(size.c_str(), "%d%c%d", &a, &x, &b) != 3 || x != 'x' || a <= 0 || b <= 0) + return error_response(err_bad("size", "\"WxH\" or \"auto\""), req.peer); + r.w = a; + r.h = b; + } else if (edit) { + const mm::FrameRGBA& last = r.images.back(); + dims_for((double)info.default_width * info.default_height, + (double)last.w / (double)last.h, mult, &r.w, &r.h); + } else { + r.w = (int32_t)info.default_width; + r.h = (int32_t)info.default_height; + } + r.w = r.w / mult * mult; + r.h = r.h / mult * mult; + if (r.w <= 0 || r.h <= 0) + return error_response(err_bad("size", "each side at least " + std::to_string(mult) + + " pixels"), req.peer); + const int64_t ls = info.latent_scale; + if ((r.w / ls) * (r.h / ls) > info.max_tokens) + return error_response(err_bad("size", std::to_string(r.w) + "x" + std::to_string(r.h) + + " is larger than this model makes (" + + std::to_string(info.max_tokens * ls * ls) + + " pixels)"), req.peer); + if (!r.seed_given) { + /* 53 bits: the seed goes back in the response to be sent again, and a JavaScript client + * reads a JSON number as a double -- a 64-bit seed would come back as another picture. */ + std::random_device rd; + r.seed = (((uint64_t)rd() << 32) ^ rd()) & (((uint64_t)1 << 53) - 1); + } + + /* ---- the request: prompts rendered and tokenised, pictures resized */ + auto g = std::make_unique(); + g->width = r.w; + g->height = r.h; + g->n = r.n; + g->steps = r.steps; + g->seed = r.seed; + g->previews = r.previews; + g->cfg = (float)r.cfg; + g->has_neg = r.has_neg; + g->ticket = std::make_shared(); + + std::vector> items; + for (const mm::FrameRGBA& f : r.images) { + int32_t rw = 0, rh = 0; + dims_for((double)info.ref_area, (double)f.w / (double)f.h, mult, &rw, &rh); + mm::FrameRGBA rs; + mm::resize_lanczos_rgba(f, rw, rh, &rs); + g->refs.push_back(to_pixels(rs)); + mm::Frame rgb; + mm::composite_white(rs, &rgb); + std::shared_ptr it; + std::string why; + if (deps_.images->picture(rgb, &it, &why) < 0 || !it) + return error_response(err_bad("image", "the picture could not be used: " + why), + req.peer); + items.push_back(std::move(it)); + } + /* Repainting: the first picture at the size being made, and per latent token the share of + * its 16 x 16 pixels the mask leaves transparent -- those are repainted, the rest kept. */ + std::vector keep_px, src_px; + if (r.has_mask) { + mm::FrameRGBA src, msk; + mm::resize_lanczos_rgba(r.images[0], r.w, r.h, &src); + mm::resize_lanczos_rgba(r.mask, r.w, r.h, &msk); + g->inpaint = true; + g->inp_src = to_pixels(src); + const int32_t lw = r.w / (int32_t)ls, lh = r.h / (int32_t)ls; + g->inp_mask.assign((size_t)lw * lh, 0.0f); + keep_px.assign((size_t)r.w * r.h, 0); + for (int32_t y = 0; y < r.h; ++y) + for (int32_t x = 0; x < r.w; ++x) { + const bool edit_px = msk.rgba[((size_t)y * r.w + x) * 4 + 3] < kTransparentBelow; + keep_px[(size_t)y * r.w + x] = edit_px ? 0 : 1; + if (edit_px) g->inp_mask[(size_t)(y / ls) * lw + x / ls] += 1.0f; + } + for (float& m : g->inp_mask) m /= (float)(ls * ls); + src_px = std::move(src.rgba); + } + + auto render = [&](const std::string& prompt, gen::Branch* out, ApiError* err) -> int { + std::string text = r.background == "transparent" && !info.tmpl_transparent.empty() + ? replace_all(info.tmpl_transparent, "{prompt}", prompt) + : prompt; + std::string tmpl = edit ? info.tmpl_edit : info.tmpl_text; + if (edit) { + std::string imgs; + for (size_t i = 0; i < items.size(); ++i) { + if (i) imgs += info.tmpl_image_sep; + imgs += replace_all(replace_all(info.tmpl_image, "{n}", std::to_string(i + 1)), + "{image}", RAD_MEDIA_MARKER); + } + tmpl = replace_all(tmpl, "{images}", imgs); + } + const std::string rendered = replace_all(tmpl, "{prompt}", text); + /* Tokenised piece by piece around the markers, each marker replaced by its picture's + * token run -- the chat path's tokenize_with_media, with pictures already processed. */ + auto pm = std::make_shared(); + size_t pos = 0, mi = 0; + for (;;) { + const size_t at = rendered.find(RAD_MEDIA_MARKER, pos); + const std::string seg = rendered.substr(pos, at == std::string::npos ? std::string::npos + : at - pos); + if (!seg.empty()) { + auto ids = deps_.tok->encode(seg, false, /*parse_special=*/true); + out->tokens.insert(out->tokens.end(), ids.begin(), ids.end()); + } + if (at == std::string::npos) break; + mm::Placed pl; + pl.item = items[mi++]; + pl.tok = (int32_t)out->tokens.size(); + out->tokens.insert(out->tokens.end(), pl.item->expand.begin(), pl.item->expand.end()); + pm->items.push_back(std::move(pl)); + pos = at + std::strlen(RAD_MEDIA_MARKER); + } + if (!pm->items.empty()) { + pm->layout(); + out->media = std::move(pm); + } + /* The fixed turn the generator does not see, which must be where the prompt starts. */ + const auto drop = deps_.tok->encode(info.drop_prefix, false, true); + if (drop.size() > out->tokens.size() || + !std::equal(drop.begin(), drop.end(), out->tokens.begin())) { + *err = err_bad("prompt", "the prompt does not start with the model's fixed turn"); + err->status = 500; + return RAD_E_STATE; + } + out->n_drop = (int32_t)drop.size(); + if ((int64_t)out->tokens.size() > info.max_cond_tokens) { + *err = err_bad("prompt", "the prompt is " + std::to_string(out->tokens.size()) + + " tokens with its pictures; this deployment conditions on " + "at most " + std::to_string(info.max_cond_tokens)); + return RAD_E_INVAL; + } + return RAD_OK; + }; + { + ApiError err; + if (render(r.prompt, &g->pos, &err) < 0) return error_response(err, req.peer); + if (r.has_neg && render(r.negative, &g->neg, &err) < 0) + return error_response(err, req.peer); + } + + /* ---- admitted and queued */ + sweep_abandoned(); + if (!admit(1)) { + metrics_.observe_rejected(); + return error_response(err_overloaded("the admission queue is full; retry after " + + std::to_string(opt_.retry_after_s) + "s"), req.peer); + } + std::shared_ptr ticket = g->ticket; + { + std::string why; + const int s = deps_.images->submit(std::move(g), &why); + if (s < 0) { + release(1); + ApiError e = err_bad("", why.empty() ? std::string(rad_strerror(s)) : why); + if (s != RAD_E_INVAL) { e.status = 503; e.type = "server_error"; } + return error_response(e, req.peer); + } + } + RAD_INFO("images: %s %dx%d n=%d steps=%d seed=%llu%s%s%s", edit ? "edit" : "generation", r.w, + r.h, r.n, r.steps, (unsigned long long)r.seed, r.has_neg ? " guided" : "", + r.has_mask ? " masked" : "", r.stream ? " streamed" : ""); + + /* ---- one finished picture to a file */ + const std::string size_s = std::to_string(r.w) + "x" + std::to_string(r.h); + const bool flatten = r.format == "jpeg" || r.background == "opaque"; + const std::string fmt = r.format; + const int32_t comp = r.compression; + auto encode = [fmt, comp, keep_px, src_px, flatten](gen::Image& im, std::string* b64, + std::string* why) -> int { + std::vector& px = im.px; + if (!keep_px.empty() && !im.preview) + for (size_t i = 0; i < keep_px.size(); ++i) + if (keep_px[i]) std::memcpy(&px[i * 4], &src_px[i * 4], 4); + std::vector file; + int s; + if (flatten) { + const std::vector rgb = on_white(px, im.w, im.h); + s = mm::encode_image(rgb.data(), im.w, im.h, 3, fmt, comp, &file, why); + } else { + s = mm::encode_image(px.data(), im.w, im.h, 4, fmt, comp, &file, why); + } + if (s < 0) return s; + *b64 = base64_encode(file.data(), file.size()); + return RAD_OK; + }; + const std::string bg_out = flatten ? "opaque" : "transparent"; + /* The pictures' share of the input: their token runs, in every branch that carries them. */ + int64_t image_tok = 0; + for (const auto& it : items) image_tok += (int64_t)it->expand.size(); + if (r.has_neg) image_tok *= 2; + auto usage = [ticket, image_tok]() { + json u; + const int64_t in = ticket->in_tokens, out = ticket->out_tokens; + u["total_tokens"] = in + out; + u["input_tokens"] = in; + u["output_tokens"] = out; + u["input_tokens_details"] = json{ { "text_tokens", in - image_tok }, + { "image_tokens", image_tok } }; + return u; + }; + const int64_t created = (int64_t)std::time(nullptr); + + if (!r.stream) { + std::vector done; + for (;;) { + gen::Image im; + bool to = false; + if (ticket->next(&im, 200, &to)) { + if (!im.preview) done.push_back(std::move(im)); + continue; + } + if (!to) break; + if (req.peer_gone()) { + ticket->cancel.store(true); + release(1); + metrics_.observe_http(499); + return HttpResponse::text(499, "client closed request\n"); + } + if (stopping_.load()) { + ticket->cancel.store(true); + release(1); + return error_response(err_overloaded("the server is shutting down"), req.peer); + } + } + release(1); + if (ticket->status() < 0 || (int32_t)done.size() != r.n) { + /* RAD_E_INVAL is the driver's refusal at admission -- a request this deployment can + * never serve, such as a conditioning longer than the cache -- and the client's to + * change; anything else failed while it ran. */ + ApiError e; + const bool client = ticket->status() == RAD_E_INVAL; + e.status = client ? 400 : 500; + e.type = client ? "invalid_request_error" : "server_error"; + e.message = ticket->why().empty() ? "the image generator failed" : ticket->why(); + return error_response(e, req.peer); + } + std::sort(done.begin(), done.end(), + [](const gen::Image& a, const gen::Image& b) { return a.index < b.index; }); + json out; + out["created"] = created; + json data = json::array(); + for (gen::Image& im : done) { + std::string b64, why; + if (encode(im, &b64, &why) < 0) { + ApiError e; + e.status = 500; + e.type = "server_error"; + e.message = "the picture could not be encoded: " + why; + return error_response(e, req.peer); + } + data.push_back(json{ { "b64_json", std::move(b64) }, { "revised_prompt", r.prompt }, + { "seed", im.seed } }); + } + out["data"] = std::move(data); + out["background"] = bg_out; + out["output_format"] = r.format; + out["quality"] = r.quality; + out["size"] = size_s; + out["usage"] = usage(); + metrics_.observe_http(200); + return HttpResponse::json_body(200, json_dump(out)); + } + + /* ---- streamed: partial images as the previews arrive, a completed event an image */ + HttpResponse res; + res.status = 200; + res.content_type = "text/event-stream"; + res.set_header("Cache-Control", "no-cache"); + const std::string kind = edit ? "image_edit" : "image_generation"; + auto finished = std::make_shared(false); + auto released = std::make_shared(false); + const std::string quality = r.quality; + res.next = [this, ticket, kind, encode, created, size_s, bg_out, fmt, quality, usage, finished, + released](std::string& chunk) mutable -> bool { + if (*finished) return false; + gen::Image im; + bool to = false; + if (ticket->next(&im, 100, &to)) { + std::string b64, why; + json ev; + if (encode(im, &b64, &why) < 0) { + ev["type"] = "error"; + ev["error"] = json{ { "message", "the picture could not be encoded: " + why } }; + } else { + ev["type"] = kind + (im.preview ? ".partial_image" : ".completed"); + ev["b64_json"] = std::move(b64); + ev["created_at"] = created; + ev["size"] = size_s; + ev["quality"] = quality; + ev["background"] = bg_out; + ev["output_format"] = fmt; + ev["index"] = im.index; + if (im.preview) ev["partial_image_index"] = im.preview_no; + else { ev["usage"] = usage(); ev["seed"] = im.seed; } + } + chunk = "event: " + ev["type"].get() + "\ndata: " + json_dump(ev) + "\n\n"; + return true; + } + if (to) { chunk.clear(); return !stopping_.load(); } + *finished = true; + if (!*released) { *released = true; release(1); } + if (ticket->status() < 0) { + json ev; + ev["type"] = "error"; + ev["error"] = json{ { "message", ticket->why() }, + { "type", ticket->status() == RAD_E_INVAL ? "invalid_request_error" + : "server_error" } }; + chunk = "event: error\ndata: " + json_dump(ev) + "\n\n"; + return true; + } + chunk.clear(); + return false; + }; + res.on_close = [this, ticket, released](bool ok) { + if (!ok) ticket->cancel.store(true); + if (!*released) { *released = true; release(1); } + }; + metrics_.observe_http(200); + return res; +} + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/server.cpp b/core/server/server.cpp index 35d78564..1eb81500 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -137,6 +137,8 @@ void Server::register_routes() { router_.post("/v1/chat/completions", [this](const HttpRequest& q) { return handle_chat(q); }); router_.post("/v1/completions", [this](const HttpRequest& q) { return handle_completion(q); }); router_.post("/v1/embeddings", [this](const HttpRequest& q) { return handle_embeddings(q); }); + router_.post("/v1/images/generations", [this](const HttpRequest& q) { return handle_images(q, false); }); + router_.post("/v1/images/edits", [this](const HttpRequest& q) { return handle_images(q, true); }); router_.post("/v1/systemone", [this](const HttpRequest& q) { return handle_systemone(q); }); router_.get ("/v1/models", [this](const HttpRequest& q) { return handle_models(q); }); router_.get ("/v1/models/:id", [this](const HttpRequest& q) { return handle_models(q); }); @@ -149,6 +151,8 @@ void Server::register_routes() { router_.post("/completions", [this](const HttpRequest& q) { return handle_native_completion(q); }); router_.post("/infill", [this](const HttpRequest& q) { return handle_infill(q); }); router_.post("/embeddings", [this](const HttpRequest& q) { return handle_embeddings(q); }); + router_.post("/images/generations", [this](const HttpRequest& q) { return handle_images(q, false); }); + router_.post("/images/edits", [this](const HttpRequest& q) { return handle_images(q, true); }); router_.get ("/models", [this](const HttpRequest& q) { return handle_models(q); }); /* llama-server's: the prompt a chat request renders to, and how many tokens it is. */ router_.post("/apply-template", [this](const HttpRequest& q) { return handle_apply_template(q); }); @@ -1268,6 +1272,11 @@ HttpResponse Server::handle_chat(const HttpRequest& req) { return error_response(err_not_implemented("this is an embedding model: it serves " "/v1/embeddings and generates no text"), req.peer); + if (opt_.image_model) + return error_response(err_not_implemented("this is an image model: it serves " + "/v1/images/generations and /v1/images/edits " + "and generates no text"), + req.peer); OaiRequest r; ApiError err; @@ -1329,6 +1338,11 @@ HttpResponse Server::handle_messages(const HttpRequest& req) { return error_response(err_not_implemented("this is an embedding model: it serves " "/v1/embeddings and generates no text"), req.peer, ApiShape::Anthropic); + if (opt_.image_model) + return error_response(err_not_implemented("this is an image model: it serves " + "/v1/images/generations and /v1/images/edits " + "and generates no text"), + req.peer, ApiShape::Anthropic); std::string chat, label; ApiError err; OaiRequest r; @@ -1363,6 +1377,11 @@ HttpResponse Server::handle_native_completion(const HttpRequest& req) { return error_response(err_not_implemented("this is an embedding model: it serves " "/v1/embeddings and generates no text"), req.peer); + if (opt_.image_model) + return error_response(err_not_implemented("this is an image model: it serves " + "/v1/images/generations and /v1/images/edits " + "and generates no text"), + req.peer); OaiRequest r; ApiError err; if (parse_completion_request(req.body, odeps_, lim_, &r, &err, /*native=*/true) < 0) @@ -1525,6 +1544,11 @@ HttpResponse Server::handle_responses(const HttpRequest& req) { return error_response(err_not_implemented("this is an embedding model: it serves " "/v1/embeddings and generates no text"), req.peer); + if (opt_.image_model) + return error_response(err_not_implemented("this is an image model: it serves " + "/v1/images/generations and /v1/images/edits " + "and generates no text"), + req.peer); std::string chat, echo; ApiError err; OaiRequest r; @@ -1578,6 +1602,11 @@ HttpResponse Server::handle_completion(const HttpRequest& req) { return error_response(err_not_implemented("this is an embedding model: it serves " "/v1/embeddings and generates no text"), req.peer); + if (opt_.image_model) + return error_response(err_not_implemented("this is an image model: it serves " + "/v1/images/generations and /v1/images/edits " + "and generates no text"), + req.peer); OaiRequest r; ApiError err; @@ -1602,7 +1631,9 @@ HttpResponse Server::handle_embeddings(const HttpRequest& req) { req.peer); if (!deps_.embed) return error_response(err_not_implemented( - "/v1/embeddings requires an embedding model; this one generates text"), req.peer); + opt_.image_model ? "/v1/embeddings requires an embedding model; this one makes images" + : "/v1/embeddings requires an embedding model; this one generates " + "text"), req.peer); OaiRequest r; ApiError err; diff --git a/core/server/server.h b/core/server/server.h index 9ff2a2a2..cd33d41d 100644 --- a/core/server/server.h +++ b/core/server/server.h @@ -40,6 +40,7 @@ struct Deps { IGrammarCompiler* grammar = nullptr; /* absent -> response_format is 501 */ IEmbedder* embed = nullptr; /* absent -> /v1/embeddings is 501 */ IMultimodal* mm = nullptr; /* absent -> image and audio parts are 501 */ + IImageGen* images = nullptr; /* absent -> the images endpoints are 501 */ /* WHAT ONLY THE ENGINE CAN SEE: per-card VRAM, the expert plane. The server holds interfaces * and no device handle, so this dependency is a function rather than an object -- there is @@ -57,6 +58,9 @@ struct ServerOptions { * /v1/completions answer 501 naming /v1/embeddings, rather than queueing a request the engine * would finish after one step with no text. */ bool embedding_model = false; + /* AN IMAGE GENERATOR (rad_declare_generator) GENERATES NO TEXT either: the text endpoints + * answer 501 naming /v1/images/generations and /v1/images/edits. */ + bool image_model = false; /* WHICH DECISION PROTOCOL THE MODEL WAS TRAINED ON, from the container's `decision.type`: * "d1" serves /v1/systemone (systemone.h); empty answers it 501. Never inferred from a name. */ std::string decision_type; @@ -197,6 +201,8 @@ private: HttpResponse handle_chat(const HttpRequest& req); HttpResponse handle_completion(const HttpRequest& req); HttpResponse handle_embeddings(const HttpRequest& req); + /* ------------------------------------------------------------------ images.cpp */ + HttpResponse handle_images(const HttpRequest& req, bool edit); HttpResponse handle_systemone(const HttpRequest& req); HttpResponse handle_models(const HttpRequest& req); HttpResponse handle_metrics(const HttpRequest& req); diff --git a/data/recipes/qwen-image-2.1-bf16.recipe b/data/recipes/qwen-image-2.1-bf16.recipe new file mode 100644 index 00000000..f7fd6e7e --- /dev/null +++ b/data/recipes/qwen-image-2.1-bf16.recipe @@ -0,0 +1,9 @@ +# qwen-image-2.1-bf16.recipe -- Qwen-Image 2.1 or 2.1-Turbo served at the checkpoint's precision. +# +# rad-convert --recipe data/recipes/qwen-image-2.1-bf16.recipe \ +# -o qwen-image-2.1-bf16.rad +# +# The text encoder and the DiT ship bf16 and are kept. The base model's VAE ships f32, which the +# plugin reads as bf16 -- the precision diffusers runs it at -- so the cast is done here, once. + +vae.* cast dtype=bf16 diff --git a/data/recipes/qwen-image-2.1-fp8.recipe b/data/recipes/qwen-image-2.1-fp8.recipe new file mode 100644 index 00000000..52028b67 --- /dev/null +++ b/data/recipes/qwen-image-2.1-fp8.recipe @@ -0,0 +1,20 @@ +# qwen-image-2.1-fp8.recipe -- Qwen-Image 2.1 or 2.1-Turbo with block-scaled fp8 linears. +# +# rad-convert --recipe data/recipes/qwen-image-2.1-fp8.recipe \ +# -o qwen-image-2.1-fp8.rad +# +# Every linear of the text encoder's language model and of the DiT's 32 blocks becomes E4M3 codes +# with a bf16 scale a 128 x 128 block, read by the fp8a8 GEMMs over activations quantised the same +# way. What stays bf16 is read once a pass or less: the embedding table, the vision tower, txt_in, +# img_in, the timestep MLP, the shared modulation, norm_out, proj_out and the VAE (cast from the +# base model's f32). + +te.blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +vae.* cast dtype=bf16 diff --git a/deploy/compose/qwen-image-2.1-turbo.yaml b/deploy/compose/qwen-image-2.1-turbo.yaml new file mode 100644 index 00000000..e1916d52 --- /dev/null +++ b/deploy/compose/qwen-image-2.1-turbo.yaml @@ -0,0 +1,13 @@ +# Qwen-Image 2.1 Turbo (Qwen/Qwen-Image-2.1-Turbo) as block fp8: the 8-step distillation of +# qwen-image-2.1.yaml's model, the same images API, 2048x2048 by default. It samples on its own +# 8-step schedule, so a request's num_inference_steps may only be 8. --tp-wire wht6 sends the DiT's +# all-reduces as 6-bit; drop it for the exact wire. +name: radiance-qwen-image-turbo +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-qwen-image-turbo + command: > + --model /models/qwen-image-2.1-turbo-fp8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 2 --tp-wire wht6 diff --git a/deploy/compose/qwen-image-2.1.yaml b/deploy/compose/qwen-image-2.1.yaml new file mode 100644 index 00000000..f81f6537 --- /dev/null +++ b/deploy/compose/qwen-image-2.1.yaml @@ -0,0 +1,16 @@ +# Qwen-Image 2.1 (Qwen/Qwen-Image-2.1) as block fp8: pictures from a prompt and edits of up to ten +# pictures on OpenAI's /v1/images/generations and /v1/images/edits, 2048x2048 by default. Two +# cards: the conditioning cache then holds all ten reference pictures, where one card holds four. +# 2.1-Turbo is qwen-image-2.1-turbo.yaml; the bf16 container needs both cards. The engine sizes +# the step, the batch and the context for an image generator itself (docs/GUIDE.md §5.6). --tp-wire +# wht6 sends the DiT's all-reduces as 6-bit: about 10% off every picture for a few tenths of a dB +# against diffusers; drop it for the exact wire. +name: radiance-qwen-image +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-qwen-image + command: > + --model /models/qwen-image-2.1-fp8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 2 --tp-wire wht6 diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index a79b58e0..324a5e64 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -16,6 +16,7 @@ into the id an architecture plugin claims. | `arch/embgemma2` | `embeddinggemma2` | *(empty)* | EmbeddingGemma 2: a bidirectional encoder with Gemma 4's vision tower and audio conformer, pooled to one vector | | `arch/gemma4_bf16` | `gemma4` | `compressed-tensors` | Gemma 4 31B dense (text): two attention classes — sliding-window and proportional-RoPE global (`attention_k_eq_v`) — over one GemmaRMSNorm stream, GELU ffn, two KV groups, softcapped logits, tied scaled embedding; served from a CT-INT4 (QAT w4a16) checkpoint as group-128 int4 codes with an f16 scale. Optional draft head: Google's assistant (`rad-convert --draft-model`), a serial head with no cache of its own (`rad_drafter_shared_kv`) | | `arch/gemma4` | `gemma4` | *(empty)* | Gemma 4 text from Google's bf16 checkpoint — the 26B-A4B MoE (a dense and a routed arm side by side) and the dense sizes without per-layer embeddings — with z-lab's DFlash drafter; routed experts bf16 or block fp8, as the recipe chose | +| `arch/qwenimage21` | `qwenimage21` | *(empty)* | Qwen-Image 2.1 and 2.1-Turbo, an image GENERATOR: a Qwen3-VL-8B text encoder, a 32-block single-stream DiT and an RGBA VAE, from the diffusers pipeline directory; the DiT and text encoder bf16 or block fp8, as the recipe chose | This document is the geometry of each, and the handful of readings that are **arithmetically silent** — wrong in a way that produces fluent output and no error anywhere. @@ -576,3 +577,58 @@ say so. arch_test holds the two live ranges to overlap. that carries one is served with `--mm-max-patches 0`. An fp8 attention or dense arm — under a tenth of the weight bytes, and the dense arm's 2112 is not whole 128-blocks either. +--- + +# `qwenimage21` — Qwen-Image 2.1 and 2.1-Turbo, an image generator + +`arch/qwenimage21` declares a GENERATOR (`rad_declare_generator`), which makes the program a +three-pass one the engine drives through `core/gen`: COND once a request (the text encoder over the +prompt and its pictures, then the DiT over that prefix into the KV cache), DENOISE once a step (the +image's latent rows against the cached prefix), DECODE once an image (the VAE). It is served on +`/v1/images/generations` and `/v1/images/edits` ([GUIDE §5.6](GUIDE.md)); fp8 on one or two cards, +bf16 on two. The checkpoint is the diffusers pipeline directory, read as one. + +``` +text Qwen3-VL-8B-Instruct as released: 36 layers of 4096 (32 x 128, 8 kv heads), interleaved + M-RoPE over (t, h, w) at 24, 20, 20 pairs, theta 5e6; the vision tower's 27 layers with + deepstack taps 8, 16, 24 added to text layers 0..2 at the picture rows + OUTPUT: the last layer BEFORE the final norm, without the 14 tokens of the system turn +DiT 32 single-stream blocks of 4096 (32 x 128, gqa 1), SwiGLU 12288, q and k RMS-normed, no + biases; ONE modulation linear for every block (scale1, gate1, scale2, gate2 -- no shift, + tanh gates) over a LayerNorm without affine; rope over (t, h, w) at 8, 28, 28 adjacent + pairs, theta 1e4, the picture grid centred on zero; txt_in = RMSNorm (gain 1 + w), + linear, gelu-tanh, linear; timestep embedding at t * 1000, rounded + THE CONDITION IS A CAUSAL PREFIX: text and reference latents, modulated at t = 0, + block-causal (text causal, a picture bidirectional within itself); written to the KV + cache once, and a step runs only the image's rows, non-causal over prefix and self +VAE Wan 2.2's on one frame: RGBA in and out, 64 latent channels, 16x down, decoder widths + 1152..144, one single-head 1152-wide attention in each middle block +schedule flow-matching Euler, exponential dynamic shift (0.5 at 256 tokens to 0.9 at 8192), + shift_terminal 0.02, 40 steps; Turbo: the 8 sigmas model_index.json lists, no guidance +``` + +The traps: + +- **The noise is radiance's, not torch's.** A seed is a Philox stream (`abi/rad_philox.h`), element + (k, c) of image row k drawn at k * 64 + c, identical on every card count. Parity against diffusers + means handing diffusers the same latents; a NumPy port of the stream does. +- **The conditioning is modulated at t = 0**, not at the step's timestep: the prefix is written once, + and a step that re-modulated it would differ from the reference at every step after the first. +- **The text encoder's output skips the final norm.** Taking the normed output scales every row by + the norm's gain and leaves a picture that is plausible and wrong. +- **A reference picture is read twice**: by the VAE as RGBA in [-1, 1], and by the vision tower + composited on white, both after PIL's premultiplied Lanczos resize to the 1024x1024 area at its + own aspect, sides rounded to 32. A different resampler changes every token the picture becomes. +- **The Euler step rounds where diffusers does**: x' = bf16(x + bf16(bf16(sigma_next - sigma) * v)), + and guidance bf16(neg + bf16(cfg * bf16(pos - neg))). Unrounded is not more accurate here; it is a + different trajectory. +- **The VAE config's `temperal_downsample` is a boolean array**; a reader that drops booleans makes + every level look unscaled. +- **Alpha off the decoder is never exactly 255** (243..255 on an opaque picture). Reading it as + transparency makes every picture the model made a transparent one when it is edited again; the + server's cutoff is alpha 128, the mask's. + +Measured against diffusers' own pipeline in bf16, from the same latents (1024x1024, 20 steps, PSNR): +bf16 TP2 33.9 dB for a prompt and 42.2 for an edit, where diffusers differs from itself by 32.6 to +34.4 dB across its own attention kernels; fp8 28.7 to 29.3 and 37.6 to 38.4; Turbo fp8 33.4 and +38.9 at its 8 steps. diff --git a/docs/DOCKER.md b/docs/DOCKER.md index b0cc3c43..35e08ae4 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -134,6 +134,8 @@ the cards the engine runs on. | `minicpm5-2b.yaml` | `minicpm5-2b-fp8.rad` | MiniCPM5-2B FP8 with its DSpark drafter | | `minicpm5-2b-bf16.yaml` | `minicpm5-2b-bf16.rad` | MiniCPM5-2B in bf16 with its DSpark drafter | | `embeddinggemma2.yaml` | `embeddinggemma2-bf16.rad` | EmbeddingGemma 2 in bf16: text, image, video and audio embeddings on one card | +| `qwen-image-2.1.yaml` | `qwen-image-2.1-fp8.rad` | Qwen-Image 2.1 as block fp8 on two cards: OpenAI's images API, generation and edits | +| `qwen-image-2.1-turbo.yaml` | `qwen-image-2.1-turbo-fp8.rad` | Qwen-Image 2.1 Turbo, the same in 8 steps | The container names are the files the README's model table downloads or converts. diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 75cae766..8c3ea6e2 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -340,6 +340,14 @@ rad-convert ~/models/ukisai/Swift-1.5-Qwen3.8-27b -o swift-27b-fp8.rad \ # arch/gemma4; docs/ARCHITECTURES.md says why down stays bf16 unless the experts were padded to 768) rad-convert ~/models/google/gemma-4-26B-A4B-it -o gemma4-26b-a4b-df.rad \ --draft-model ~/models/z-lab/gemma-4-26B-A4B-it-DFlash --recipe data/recipes/gemma4-26b-a4b-df.recipe + +# Qwen-Image 2.1 or 2.1-Turbo, an image model (§5.6): the diffusers pipeline directory is the +# checkpoint -- text encoder, DiT, VAE and the tokenizer together. fp8 blocks for the text encoder +# and the DiT (17 GB, one card or two), or the checkpoint's bf16 (31 GB, two cards) +rad-convert ~/models/Qwen/Qwen-Image-2.1 -o qwen-image-2.1-fp8.rad \ + --recipe data/recipes/qwen-image-2.1-fp8.recipe +rad-convert ~/models/Qwen/Qwen-Image-2.1-Turbo -o qwen-image-2.1-turbo-fp8.rad \ + --recipe data/recipes/qwen-image-2.1-fp8.recipe ``` A checkpoint directory's `model.safetensors.index.json` decides which shard each tensor is read @@ -1237,6 +1245,7 @@ for a model that takes no images or video. | `POST /v1/chat/completions` | chat, with tools, reasoning and streaming | | `POST /v1/completions` | raw text completion | | `POST /v1/embeddings` | needs a model with an embedding head, else 501 | +| `POST /v1/images/generations`, `POST /v1/images/edits` | OpenAI's images API, needs an image model (Qwen-Image 2.1), else 501 — §5.6 | | `POST /v1/systemone` | LiquidAI d1's decisions over a state: named yes/no, choice and score questions answered as probabilities, nothing generated; needs a container converted as d1, else 501 — §5.12 | | `POST /v1/messages`, `POST /v1/messages/count_tokens` | Anthropic's Messages API, for Claude Code and the Anthropic SDKs — §5.9 | | `POST /v1/responses`, `POST /v1/responses/input_tokens` | OpenAI's Responses API, for Codex and the OpenAI SDKs' `responses` client — §5.9 | @@ -1400,7 +1409,7 @@ refused, never dropped: an unconstrained 200 would leave you parsing free prose against a schema you were told was enforced. `/v1/completions` has no template in the way, so the same grammar works there — which is why the example above uses it. -### 5.6 Completions, embeddings, tokenising +### 5.6 Completions, embeddings, images, tokenising ```sh curl -s http://localhost:8000/v1/completions -H 'Content-Type: application/json' \ @@ -1466,6 +1475,69 @@ cut at 30 seconds. `prompt_name` takes the names the model's sentence-transforme states (`query`, `document`, `Retrieval-query`, `STS`, ...) and applies to text and content-part inputs; a model that states a default prompt applies it when the request names none. +**An image model** (Qwen-Image 2.1 or 2.1-Turbo) serves OpenAI's images API and nothing else; +completions, chat and embeddings answer 501. Clients written against OpenAI's images endpoints +(Open WebUI, the OpenAI SDKs) work as they are; the picture always comes back in the response. + +```sh +# a picture from a prompt: b64_json, 2048x2048 unless `size` says otherwise +curl -s http://localhost:8000/v1/images/generations -H 'Content-Type: application/json' \ + -d '{"prompt":"a lighthouse at dusk, oil painting","size":"1536x1024","seed":7}' + +# an edit: one picture or up to ten (`image[]`), multipart as OpenAI's SDKs send it +curl -s http://localhost:8000/v1/images/edits -F 'prompt=put a red scarf on the fox' \ + -F 'image[]=@fox.png' + +# repaint only where the mask is transparent; the rest comes back exactly as it was +curl -s http://localhost:8000/v1/images/edits -F 'prompt=a green wool hat' \ + -F 'image=@fox.png' -F 'mask=@mask.png' + +# progress as server-sent events: `partial_images` previews, then the picture +curl -sN http://localhost:8000/v1/images/generations -H 'Content-Type: application/json' \ + -d '{"prompt":"a red apple, product shot","background":"transparent","stream":true, + "partial_images":2}' +``` + +| field | | +|---|---| +| `prompt` | required | +| `size` | `WxH` or `auto`; each side is rounded down to a multiple of 32. `auto` is the model's native 2048x2048, and for an edit the last picture's aspect at that area. Larger than the model makes (16800 latent tokens, about 2400x1792) is refused | +| `n` | pictures from one prompt, 1..16; picture i uses seed + i | +| `seed` | the noise; the same seed, prompt and size give the same picture | +| `quality` | `auto`/`high` the model's step count (40 for 2.1), `medium` three quarters, `low` half | +| `num_inference_steps` | the step count itself; refused by a model with a fixed schedule (Turbo: 8) | +| `negative_prompt`, `true_cfg_scale` | guidance against the negative prompt, at twice the cost of a step; `true_cfg_scale` above 1 needs a `negative_prompt` | +| `background` | `transparent` asks the model for one (png or webp), `opaque` flattens on white, `auto` keeps the transparency of an edit's input and is opaque otherwise | +| `output_format`, `output_compression` | `png` (default), `jpeg` or `webp`; compression 0..100 for jpeg and webp | +| `stream`, `partial_images` | OpenAI's `image_generation.partial_image` / `image_edit.partial_image` events, 0..3 previews of the clean picture the step predicts, then `.completed` | +| `image`, `image[]`, `mask` | an edit's pictures (png, jpeg, webp; up to ten) and the first picture's mask: alpha below 128 is where the picture may change | + +`response_format: url` is refused: nothing here stores a picture to serve later. The response +carries `usage` (input tokens: the prompt and the pictures' tokens; output: latent tokens) and +each picture's `seed` and `revised_prompt` (the prompt as given). + +On two cards the step's two all-reduces of the image's rows (128 MB each at 2048x2048, over the +cards' link) run on a second stream: the rows go through each block in two halves, and one half's +all-reduce travels while the card computes the other's. `--tp-wire wht6` sends them as 6-bit and +makes a picture about 9% faster still (2048x2048, 40 steps: 61 -> 56 s; Turbo 12.9 -> 11.9 s, at +1024x1024 2.6 -> 2.2 s), within a dB of the exact wire against diffusers. Exact is the default. +The VAE decoder is split by rows across the cards after its mid-block, with the same pixels. + +On an fp8 container the denoising attention computes its scores in int8 (about 16% faster +attention); a picture moves by less than switching between two exact attention implementations +moves it. A bf16 container keeps bf16 scores. + +Two cards (`--tp 2`) are the fastest picture; two servers of one card each make the most +pictures an hour (each takes 1.7x as long and there are two). A card runs these models at its +300 W limit, in the DiT's GEMMs and attention alike. + +A reference picture costs 4096 rows of the conditioning's KV cache at the model's 1024x1024 +reference area -- its latent rows, which take its vision tokens' places. One card holds the fp8 +container and a cache of 20256 rows: four pictures with their prompt. Two cards (`--tp 2`) hold +all ten the model takes, and the bf16 container. A request the cache can never hold is a 400 +that says how many rows it needed. The models are under Qwen's research license, +non-commercial. + ### 5.7 Request fields | field | notes | @@ -1957,7 +2029,7 @@ of a log to paste into an issue. fix. Every warning is also printed as a `W` line of its own. ``` -I STARTUP REPORT -- radiance 1.5.0 +I STARTUP REPORT -- radiance 1.6.0 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 b04690f1..a8f2829f 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -694,6 +694,95 @@ nearly cancel the ULP comes out as a few percent and the transcript moves after The kernel reproduces the reference's fold exactly: the widths above the head dim contribute zeros and adding 0.0f is exact, so a block sum over 8 wave partials and over 32 are the same number. +## Image generation + +The ops a diffusion image generator declares (`rad_declare_generator`, abi/rad_builder.h): a +single-stream diffusion transformer's adaptive norm and gated residual, the timestep embedding, the +per-image latent LANES and the flow-matching sampler over them, attention over a cached +conditioning prefix, and an image decoder's convolution, channel norm, resampling shortcuts and +pixel output. Each rounds where the reference model materialises a bf16 tensor; the libref +function says which (libref/ref_gen.cpp). + +| op | params | operands | +|---|---|---| +| `ln_mod` | `M`(range) `n` `eps`:f64 `dtype` | `x`, `s`, `cu_seqlens` → `y` | +| `gate_add` | `M`(range) `n` `dtype` | `y`, `g`, `cu_seqlens`, `x`:inout | +| `ln_mod_quant_fp8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` | `y`?, `g`?, `s`, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`? | +| `timestep_embed` | `M`(range) `n` `scale`:f64 `max_period`:f64 `round`/opt `dtype` | `t` → `y` | +| `gather_rows2` | `M`(range) `n` `dtype` | `a`, `b`, `idx` → `y` | +| `lane_gather` | `M`(range) `n` `stride` `dtype` | `src`, `lane`, `cu_seqlens` → `y` | +| `lane_store` | `M`(range) `n` `stride` `dtype` | `src`, `lane`, `dst`:inout | +| `randn_lanes` | `M`(range) `n` `stride` `dtype` | `flags`, `seed`, `lane`, `cu_seqlens`, `dst`:inout | +| `flow_euler` | `M`(range) `n` `stride` `dtype` | `v`, `sigma`, `sigma_next`, `cfg`, `pair`, `lane`, `flags`, `seed`, `cu_seqlens`, `inp_lat`?, `inp_mask`?, `state`:inout, `preview`:inout? | +| `chan_affine` | `M`(range) `n` `mul` `add` `mode` `dtype` | `x` → `y` | +| `conv2d_nhwc` | `M`(range) `cin` `cout` `k` `stride` `pad` `up` `dtype` | `x`, `w`w, `b`w → `y` | +| `l2norm_chan` | `M`(range) `n` `act` `dtype` | `x`, `gamma`w → `y` | +| `d2s_add` | `M`(range) `cin` `cout` `ft` `dtype` | `x`, `y`:inout | +| `s2d_avg_add` | `M`(range) `cin` `cout` `ft` `dtype` | `x`, `y`:inout | +| `to_rgba8` | `M`(range) `n` `dtype` | `x` → `y` | +| `gelu_tanh` | `M`(range) `n` `dtype` | `x` → `y` | +| `scatter_add_rows` | `M`(range) `n` `dtype` | `v`, `idx`, `x`:inout | +| `attn_prefix_self` | `q_len` `head_dim` `gqa` `block_size`/der `causal` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt `qk`/opt | `q`, `k`, `v`, `kv_cache`, `block_table`, `seqused`, `cu_seqlens`, `k_descale`?, `v_descale`?, `k_i8`?, `k_scale`? → `out` | + +**Sequences and lanes.** `cu_seqlens` partitions the rows into entries (`[n_seq+1]` i32, entry `e` +owning `[cu[e], cu[e+1])`; it need not start at 0). `ln_mod` and `gate_add` take each row's +modulation row from `s`/`g`, `[n_seq, >= n]` at its own row pitch -- a column slice of one shared +modulation projection. A LANE is one image's latent in a per-image state buffer, `stride` rows +apart: `lane_gather` copies entry `e`'s rows out of lane `lane[e]`, `lane_store` copies one +source into every listed lane (a repainted picture's latent into each of its images). + +- `ln_mod`: `y = bf16(bf16(LN(x)) * bf16(1 + s[seq]))`, a layer norm with no gain and no bias. +- `gate_add`: `x = bf16(x + bf16(bf16(tanh(g[seq])) * y))`. +- `ln_mod_quant_fp8`: with `gated` 1, `gate_add` first; then `z = ln_mod(x)` and + `(q, scale) = quant_act_fp8(z, group)`, `z` written when bound -- the three in one pass, each + rounded as its own store would round it, so the bytes are the three ops'. +- `timestep_embed`: `[cos | sin]` of `t' * f_i`, `f_i = exp(-ln(max_period) * i / (n/2))` in f32, + `t' = scale * t`; with `round` 1, `t' = scale * bf16(bf16(t * scale) / scale)` -- the value + diffusers' pipeline hands its transformer. `t` is f32 `[M]`. +- `gather_rows2`: `y[i] = idx[i] >= 0 ? a[idx[i]] : b[-1 - idx[i]]`, zeros past either source. +- `randn_lanes`: for entries whose `flags` carry 1, the lane's rows become the entry's seed's + standard-normal stream (abi/rad_philox.h), element `(k, c)` the stream's `k * n + c`. `seed` is + `[n_seq, 2]` u32, low word first. +- `flow_euler`: for every entry with `pair != -2` (an entry that IS a negative conditioning moves + no lane), `v' = pair >= 0 ? bf16(neg + bf16(cfg * bf16(v - neg))) : v`, `neg` the paired entry's + rows; flag 4 writes `bf16(x - sigma * v')` to the lane's `preview`; then + `x' = bf16(x + bf16(bf16(sigma_next - sigma) * v'))`; flag 2 restores the kept region, + `x' = bf16(m x' + (1 - m)((1 - sigma_next) src + sigma_next noise))` with `m` the lane's f32 + `inp_mask` row, `src` its `inp_lat` row and `noise` the seed's stream. + +**Images** are `[height, width * channels]`, dense, and the ops read both sizes off the operand +shapes: an image's size is a request's, and a parameter is fixed at declare. + +- `conv2d_nhwc`: `w` is PyTorch's `[cout, cin, k, k]` (a kernel may store it permuted through its + layout hook), `b` `[cout]`; `up` 2 reads the input upsampled 2x nearest-neighbour; `pad` `same` + is `k/2` zeros a side, `down` is none above and left and one below and right (`ZeroPad2d((0,1,0,1))` + before a stride-2 conv). f32 accumulation, the bias added, one rounding. +- `l2norm_chan`: each pixel's channels to unit L2 (eps 1e-12), times `sqrt(n)`, times `gamma` -- + three roundings -- then `act` `none` or `silu`. +- `chan_affine`: `mul` and `add` are space-separated lists of `n` values, each rounded to bf16; + `fma` is `bf16(bf16(x * mul) + add)`, `inv` is `bf16(bf16(x - add) / mul)`. +- `d2s_add` (Wan's DupUp3D on one frame): `y[2r+i, 2c+j, o] += x[r, c, (o F + off + 2i + j) / + rep]`, `F = 4 ft`, `off = 4` when `ft` is 2, `rep = cout F / cin`. +- `s2d_avg_add` (AvgDown3D on one frame): `y` gains the mean of each output channel's group of + `cin F / cout` dealt values, a dealt channel being `(c, t, i, j)` at `c F + 4t + 2i + j`; with + `ft` 2 the frame `t = 0` is the zero frame the reference pads in, which the mean still counts. +- `to_rgba8`: `round(clamp(bf16(bf16(clamp(x, -1, 1) / 2) + 0.5), 0, 1) * 255)`, u8 out. + +**`attn_prefix_self`** attends over two key sources: entry `s`'s first `seqused[s]` keys in the +paged cache, all visible, and the pass's own rows `k`/`v` beside `q` (dense, at their own pitch, +rows indexed as `q`'s), of which row `i` sees `j <= i` with `causal` and all of them without. It +is an image's latent rows against its conditioning, and one segment of a conditioning against the +segments before it. `qk` `"i8"` is the int8 score form and takes `k_i8` [tokens, kv_heads * +head_dim] and `k_scale` [tokens, kv_heads] f32, the own keys as `quant_act_i8g` writes them at +group `head_dim`; the query and every prefix key are quantised inside the op by the same rule +(scale `amax/127`, 1 for an all-zero row; code `rint(clamp(x * (1/scale), +-127))`) and a score is +the exact integer dot product times both scales. `k` is then not read for the own rows. + +`qk_norm_rope` takes two more `mode`s for these models: `gptj_blocks` is `blocks` with each +section's pairs ADJACENT, `(start + 2j, start + 2j + 1)` -- a 3-axis image rotary's complex form +-- and `imrope` is the interleaved M-RoPE of Qwen3-VL's text attention over NeoX pairs (`rope`'s +`imrope`), reading three position planes. + ## Mixture of experts | op | params | operands | @@ -977,7 +1066,7 @@ and the third is what needs the token stride carried separately. | op | params | operands | |---|---|---| -| `all_reduce` | `world_size` `numel`(range) `dtype` `exact` `min_bytes`/opt `hops`/opt | `x`:inout, `y`:out? | +| `all_reduce` | `world_size` `numel`(range) `dtype` `exact` `min_bytes`/opt `hops`/opt `overlap`/opt | `x`:inout, `y`:out? | | `all_gather` | `world_size` `numel` `dtype` `row`/opt | `x` → `y` | `exact` separates the exact sum from the quantised wire, and a caller has to say which it wants: a @@ -988,6 +1077,9 @@ libr4d separates one-shot from two-shot, at a width that has both, by message si rows start above 524288 elements, which makes that a band edge of the ranged `numel`, so a caller states nothing for it. `hops` is a caller's request for one or the other (1 or 2); libref accepts and ignores it, and no libr4d row reads it. Every all-reduce kernel serves `y` absent, in place. +`overlap` 1 says the caller issues the collective on its second lane, beside compute: libr4d then +serves it with rows whose launch is narrow (8 blocks of 256 threads at two ranks), which compute +the same bits and leave the CUs to the kernels running beside them; libref ignores it. libr4d serves these at **2, 3, 4 and 8 ranks**. Two ranks have their own kernels (one flag word a block, the rotated 6-bit wire, the fused norm-and-reduce forms). The wide family is one template on diff --git a/libavx/avx_attn.cpp b/libavx/avx_attn.cpp index d26fbfb7..40cfbf81 100644 --- a/libavx/avx_attn.cpp +++ b/libavx/avx_attn.cpp @@ -61,11 +61,11 @@ using namespace avx; -/* The widest head this accumulates in one frame. MLA's 576 is the widest in circulation and - * libr4d's widest is 256, so 1024 is headroom rather than a limit anyone meets; above it the op +/* The widest head this accumulates in one frame. The widest in circulation is an image VAE's + * single-head mid-block attention at 1152 (Qwen-Image 2.1), so 2048 is headroom; above it the op * says RAD_E_UNSUPPORTED by name instead of overflowing. Same number as libref's, so the two * refuse the same calls. */ -enum { AVX_HD_MAX = 1024 }; +enum { AVX_HD_MAX = 2048 }; /* Keys per online-softmax tile. Sized so a tile of scores and the key rows behind it stay in L1 * beside the query head and the accumulator: at head_dim 128 that is 64 keys x 128 floats = 32 KiB diff --git a/libavx/avx_check.cpp b/libavx/avx_check.cpp index a83ac685..f0ca0c10 100644 --- a/libavx/avx_check.cpp +++ b/libavx/avx_check.cpp @@ -937,18 +937,38 @@ int main(int argc, char** argv) { return 1; } - /* ---- 2. coverage */ - int missing = 0; + /* ---- 2. coverage + * + * OPS WITH NO CPU PATH BY DECISION, named one by one: the image generator's (arch/qwenimage21). + * A DiT step at 2048^2 is about 4e14 FLOP, minutes on a CPU, so the generator is a GPU program + * and libavx serves none of its ops. The list is what keeps the rule a rule -- an op missing + * from libavx and not named here is still a kernel built and never wired. */ + static const char* const kNoCpuPath[] = { + "ln_mod", "gate_add", "timestep_embed", "gather_rows2", "lane_gather", "lane_store", + "randn_lanes", "flow_euler", "chan_affine", "conv2d_nhwc", "l2norm_chan", "d2s_add", + "s2d_avg_add", "to_rgba8", "gelu_tanh", "scatter_add_rows", "attn_prefix_self", + "ln_mod_quant_fp8", + }; + auto no_cpu_path = [](const char* op) { + for (const char* o : kNoCpuPath) + if (!std::strcmp(o, op)) return true; + return false; + }; + int missing = 0, exempt = 0; for (int i = 0, n = ref.kernel_count(); i < n; ++i) { const RadKernelInfo* kr = ref.kernel_at(i); if (!kr || !kr->op) continue; + if (!avx.row(kr->op) && no_cpu_path(kr->op)) { + ++exempt; + continue; + } if (!avx.row(kr->op)) { std::printf("COVER %-24s libref implements it, libavx does not\n", kr->op); ++missing; } } - std::printf("coverage: libref %d rows, libavx %d rows, %d op(s) missing\n", - ref.kernel_count(), avx.kernel_count(), missing); + std::printf("coverage: libref %d rows, libavx %d rows, %d op(s) missing, %d with no CPU path " + "(the image generator's)\n", ref.kernel_count(), avx.kernel_count(), missing, exempt); /* ---- 3/4. the numbers, per ISA level */ const std::vector cases = build_cases(); diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index ded0eba6..769103c8 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -436,7 +436,8 @@ static const RadOperandSpec oGatedNorm[] = { OPD("x"), OPD("z"), WGT("w"), OUT(" /* ---- collectives -------------------------------------------------------------------------- */ static const RadParamSpec pAllReduce[] = { P_INT("world_size"), P_INT("numel"), P_STR("dtype"), - P_INT("exact"), P_INTO("min_bytes"), P_INTO("hops") }; + P_INT("exact"), P_INTO("min_bytes"), P_INTO("hops"), + P_INTO("overlap") }; static const RadOperandSpec oAllReduce[] = { INOUT("x"), OUT_O("y") }; static const RadParamSpec pAllGather[] = { P_INT("world_size"), P_INT("numel"), P_STR("dtype"), diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index a36599d7..decedb17 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -81,6 +81,11 @@ set(R4D_UNITS # the small ops around it: act_mul, seg_mean, qk_norm_rope with a v norm, the f32 widening. "r4d_attn_dense_bf16|" "r4d_encoder_bf16|" + # The image generator: attention over a paged prefix and the pass's own rows, the causal + # head_dim-128 dense form and the 1152-wide decoder head; and the sampler, adaptive norm, + # implicit-GEMM convolution and pixel ops around them. + "r4d_attn_gen|" + "r4d_gen|" # The vision tower's own small ops: layer norm, the learned-grid position embedding, and the # biased GEMM with a linear layer's activation and residual in its store. "r4d_vit_bf16|" diff --git a/libr4d/r4d_attn_gen.hip b/libr4d/r4d_attn_gen.hip new file mode 100644 index 00000000..9d746093 --- /dev/null +++ b/libr4d/r4d_attn_gen.hip @@ -0,0 +1,770 @@ +// R4D attention over a paged prefix and the pass's own rows (attn_prefix_self), and the causal +// dense attention a text encoder's prompt pass needs (attn_dense, causal 1, head_dim 128). +// +// THE KERNEL IS THE DENSE ONE (r4d_attn_dense_bf16.hip) WITH A SECOND KEY SOURCE. S^T = K.Q^T, so a +// lane owns one query row and its softmax state, the C fragment of S^T is the B fragment the P.V +// matmul wants, and P never goes through LDS. A workgroup owns one KV head and every query head +// that reads it. What is new: +// +// THE PREFIX. A sequence's first `used[s]` keys are in the paged cache -- [blocks, kv_heads, 16, +// 2 * HD], K then V in a slot -- and its own rows' keys are dense, beside the queries. The key +// loop walks the prefix tiles first and then the own tiles; a tile is one source or the other, +// and its rows are fetched through that source's address rule. Every prefix key is visible. +// +// CAUSAL OWN KEYS. With `causal` a query sees its own rows up to itself: a text segment of a +// conditioning sequence, and the text encoder's prompt. A tile wholly below every query of the +// workgroup pays no test. +// +// bf16 operands (DT16<0>): a diffusion transformer's values carry outliers an f16 operand could +// overflow, and the reference takes P to bf16 for its P.V product too (rounded there, truncated +// here -- see the softmax). +// +// THE INT8 Q.K FORM (`I8`, the op's `k_i8` operand present). The score product runs on +// v_wmma_i32_16x16x16_iu8, which issues in half the cycles of the bf16 one; P.V stays bf16. Every +// code is quant_act_i8g's: a scale per (row, head) of amax / 127 (1 for an all-zero row) and a code +// rint(x * (1 / scale)) clamped to +-127. The own rows' keys arrive quantised that way (k_i8 and +// k_scale, one op ahead of this one), the query is quantised here once a workgroup, and a prefix +// tile is quantised as it is staged -- the prefix is a picture's conditioning, a few hundred rows +// against the thousands of own rows. A score is (q . k) * qs * ks, the integer dot product exact. +// At a DiT's 16384 rows this takes the kernel from 38 to about 32 ms; against the bf16 form the +// picture moves by less than swapping between exact attention implementations moves it. +#include "r4d.h" +#include "r4d_args.h" +#include "r4d_common.h" +#include "r4d_dt16.h" + +#include +#include + +typedef int v2i_ps __attribute__((ext_vector_type(2))); +typedef int v8i_ps __attribute__((ext_vector_type(8))); + +/* quant_act_i8g's scale and codes for eight values against `inv` = 1 / scale. */ +__device__ __forceinline__ uint32_t ps_q8x4(float a, float b, float c, float d, float inv) { + auto q = [inv](float x) { + return (uint32_t)((int)rintf(fminf(fmaxf(x * inv, -127.0f), 127.0f)) & 0xff); + }; + return q(a) | (q(b) << 8) | (q(c) << 16) | (q(d) << 24); +} +__device__ __forceinline__ float ps_lo(uint32_t w) { return __builtin_bit_cast(float, w << 16); } +__device__ __forceinline__ float ps_hi(uint32_t w) { return __builtin_bit_cast(float, w & 0xffff0000u); } +__device__ __forceinline__ float ps_amax8(uint4 u) { + return fmaxf(fmaxf(fmaxf(fabsf(ps_lo(u.x)), fabsf(ps_hi(u.x))), + fmaxf(fabsf(ps_lo(u.y)), fabsf(ps_hi(u.y)))), + fmaxf(fmaxf(fabsf(ps_lo(u.z)), fabsf(ps_hi(u.z))), + fmaxf(fabsf(ps_lo(u.w)), fabsf(ps_hi(u.w))))); +} +__device__ __forceinline__ uint2 ps_q8x8(uint4 u, float inv) { + return make_uint2(ps_q8x4(ps_lo(u.x), ps_hi(u.x), ps_lo(u.y), ps_hi(u.y), inv), + ps_q8x4(ps_lo(u.z), ps_hi(u.z), ps_lo(u.w), ps_hi(u.w), inv)); +} + +template +__global__ __launch_bounds__(NQB * GQA * 32) +void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk, + const int8_t* __restrict__ gk8, const float* __restrict__ gks, + const uint16_t* __restrict__ gv, uint16_t* __restrict__ go, + const int* __restrict__ cu, int num_seqs, const int* __restrict__ used, + const int* __restrict__ bt, int bt_pitch, + const uint16_t* __restrict__ kvc, int kv_heads, + float scale, int causal, int q_ld, int k_ld, int k8_ld, int ks_ld, + int v_ld, int o_ld) +{ + typedef DT16<0> D; + typedef D::frag frag16; + typedef typename std::conditional::type qfrag; + + constexpr int NWARPS = NQB * GQA; + constexpr int NTHR = NWARPS * 32; + constexpr int BQ = NQB * 16; + constexpr int NKS = HD / 16; + constexpr int MT = TILE / 16; + constexpr int KSTR = HD + 8; + constexpr int VSTR = TILE + 8; + constexpr int DG = HD / 8; + constexpr int KGRP = TILE / 8; + constexpr int KITEMS = TILE * DG; + constexpr int KP = (KITEMS + NTHR - 1) / NTHR; + constexpr int NTR = KGRP * DG; + constexpr int LGRP = NTHR / 8; + constexpr int VP = (NTR + LGRP - 1) / LGRP; + constexpr float GROW = D::GROW; + constexpr int BS = 16; // the paged block, libr4d's (block_size == 16) + static_assert(HD % 16 == 0 && TILE % 16 == 0, "geometry"); + // THE INT8 KEY TILE: a key's row is HD bytes, padded by 8 so the sixteen rows a fragment read + // touches land on distinct bank pairs (34 dwords a row), and written as 8-byte halves because + // the padding leaves odd rows 8-byte aligned. A prefix tile's key is DG lanes of 8 dims each, + // which is why those lanes must sit in one half-wave for the row's absolute maximum. + constexpr int KSTR8 = HD + 8; + constexpr int K8G = HD / 16; // 16-byte pieces of an own key's row + constexpr int K8P = (TILE * K8G + NTHR - 1) / NTHR; + static_assert(!I8 || (DG == 16 && NTHR % 32 == 0), "an int8 prefix key is one half-wave"); + + __shared__ __align__(16) uint16_t sK[I8 ? 8 : TILE * KSTR]; + __shared__ __align__(16) int8_t sK8[I8 ? TILE * KSTR8 : 16]; + __shared__ __align__(16) float sKs[I8 ? TILE : 4]; + __shared__ __align__(16) uint16_t sV[HD * VSTR]; + + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + const int c = lane & 15, h = lane >> 4; + const int g = warp % GQA; + const int qbi = warp / GQA; + const int kvh = blockIdx.y; + const int hq = kvh * GQA + g; + + // THE GRID IS FLAT OVER THE SEQUENCES' QUERY BLOCKS: block b is the b-th BQ-row block counting + // through every sequence in order, so a pass of many equal sequences launches what it needs + // rather than (longest sequence) x (sequences). A handful of sequences, so a walk. + int seq = -1, q0 = 0; + for (int s = 0, b = blockIdx.x; s < num_seqs; ++s) { + const int nb = (cu[s + 1] - cu[s] + BQ - 1) / BQ; + if (b < nb) { seq = s; q0 = b * BQ; break; } + b -= nb; + } + if (seq < 0) return; + const int s0 = cu[seq], slen = cu[seq + 1] - s0; + if (slen <= 0 || q0 >= slen) return; + const int qlast = min(q0 + BQ, slen) - 1; + const int P = used ? used[seq] : 0; + const int ke = causal ? qlast + 1 : slen; // own keys any query here can see + + const float mul = scale * 1.44269504089f; + const int qpos = q0 + qbi * 16 + c; + const bool live = qpos < slen; + + // The query: bf16 fragments pre-multiplied by the softmax scale, or int8 codes against its + // row's absolute maximum -- a lane holds half the head's dims, the lane 16 away the other half + // -- with the scale carried in `qs` and applied to the integer score. + qfrag qf[NKS]; + float qs = mul; + { + const int qrow = live ? qpos : slen - 1; + const uint16_t* qp = gq + (long)(s0 + qrow) * q_ld + (long)hq * HD; + if constexpr (I8) { + uint4 qu[NKS]; + float am = 0.0f; + #pragma unroll + for (int t = 0; t < NKS; ++t) { + qu[t] = *(const uint4*)(qp + 16 * t + 8 * h); + am = fmaxf(am, ps_amax8(qu[t])); + } + am = fmaxf(am, swap16(am)); + const float sq = am > 0.0f ? am * (1.0f / 127.0f) : 1.0f; + const float inv = 1.0f / sq; + qs = sq * mul; + #pragma unroll + for (int t = 0; t < NKS; ++t) { + const uint2 w = ps_q8x8(qu[t], inv); + qf[t] = (v2i_ps){ (int)w.x, (int)w.y }; + } + } else { + #pragma unroll + for (int t = 0; t < NKS; ++t) { + const uint4 u = *(const uint4*)(qp + 16 * t + 8 * h); + auto cv = [&](uint32_t w) { + return D::pk(__builtin_bit_cast(float, w << 16) * mul, + __builtin_bit_cast(float, w & 0xffff0000u) * mul); + }; + qf[t] = D::mk(make_uint2(cv(u.x), cv(u.y)), make_uint2(cv(u.z), cv(u.w))); + } + } + } + + float m_ref = -3.0e38f, soff = 3.0e38f, l_i = 0.0f; + v8f acc[NKS]; + #pragma unroll + for (int t = 0; t < NKS; ++t) acc[t] = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; + + const int vj = tid & 7, lgi = tid >> 3; + const uint16_t* kbase = gk + (long)kvh * HD; + const uint16_t* vbase = gv + (long)kvh * HD; + const int* btrow = bt ? bt + (long)seq * bt_pitch : nullptr; + + // The K row of key `kk` of the current source; its V row is `vrow`. + auto krow = [&](bool pre, int kk) -> const uint16_t* { + if (!pre) return kbase + (long)(s0 + kk) * k_ld; + const int blk = btrow[kk / BS]; + return kvc + ((long)(blk * kv_heads + kvh) * BS + (kk % BS)) * (2 * HD); + }; + auto vrow = [&](bool pre, int kk) -> const uint16_t* { + if (!pre) return vbase + (long)(s0 + kk) * v_ld; + const int blk = btrow[kk / BS]; + return kvc + ((long)(blk * kv_heads + kvh) * BS + (kk % BS)) * (2 * HD) + HD; + }; + + const int ntp = (P + TILE - 1) / TILE, nts = (ke + TILE - 1) / TILE; + for (int ti = 0; ti < ntp + nts; ++ti) { + const bool pre = ti < ntp; + const int k0 = pre ? ti * TILE : (ti - ntp) * TILE; + const int klim = pre ? P : ke; + const bool mask = (k0 + TILE > klim) || (!pre && causal && k0 + TILE - 1 > q0); + + // An own tile in the int8 form is K8P 16-byte pieces a thread and a scale for the first + // TILE threads; anything else is the bf16 rows (a prefix tile quantised below). + const bool own8 = I8 && !pre; + uint4 kr[KP], vr[VP]; + float ksr = 0.0f; + if (own8) { + #pragma unroll + for (int p = 0; p < K8P; ++p) { + const int i = tid + p * NTHR; + if ((TILE * K8G) % NTHR == 0 || i < TILE * K8G) { + const int key = i / K8G, gg = i % K8G; + const int kk = (k0 + key < klim) ? k0 + key : klim - 1; + kr[p] = *(const uint4*)(gk8 + (long)(s0 + kk) * k8_ld + (long)kvh * HD + gg * 16); + } + } + if (tid < TILE) { + const int kk = (k0 + tid < klim) ? k0 + tid : klim - 1; + ksr = gks[(long)(s0 + kk) * ks_ld + kvh]; + } + } else { + #pragma unroll + for (int p = 0; p < KP; ++p) { + const int i = tid + p * NTHR; + if (KITEMS % NTHR == 0 || i < KITEMS) { + const int key = i / DG, gg = i % DG; + const int kk = (k0 + key < klim) ? k0 + key : klim - 1; + kr[p] = *(const uint4*)(krow(pre, kk) + gg * 8); + } + } + } + #pragma unroll + for (int r = 0; r < VP; ++r) { + const int u = lgi + r * LGRP; + if (NTR % LGRP == 0 || u < NTR) { + const int kg = u % KGRP, dg = u / KGRP; + const int kk0 = k0 + kg * 8 + vj; + const int kk = (kk0 < klim) ? kk0 : klim - 1; + vr[r] = __builtin_bit_cast(uint4, load_tr_b128(vrow(pre, kk) + dg * 8)); + } + } + // A prefix key in the int8 form: its row's maximum across the DG lanes that hold it (one + // half-wave, so a DPP butterfly), then its eight codes a lane. + uint2 kq[KP]; + float kqs[KP]; + if (I8 && pre) { + #pragma unroll + for (int p = 0; p < KP; ++p) { + float am = ps_amax8(kr[p]); + am = fmaxf(am, r4d_xor_lane<8>(am)); + am = fmaxf(am, r4d_xor_lane<4>(am)); + am = fmaxf(am, r4d_xor_lane<2>(am)); + am = fmaxf(am, r4d_xor_lane<1>(am)); + kqs[p] = am > 0.0f ? am * (1.0f / 127.0f) : 1.0f; + kq[p] = ps_q8x8(kr[p], 1.0f / kqs[p]); + } + } + + lds_barrier(); + #pragma unroll + for (int r = 0; r < VP; ++r) { + const int u = lgi + r * LGRP; + if (NTR % LGRP == 0 || u < NTR) { + const int kg = u % KGRP, dg = u / KGRP; + *(uint4*)&sV[(dg * 8 + vj) * VSTR + kg * 8] = vr[r]; + } + } + if constexpr (I8) { + if (!pre) { + #pragma unroll + for (int p = 0; p < K8P; ++p) { + const int i = tid + p * NTHR; + if ((TILE * K8G) % NTHR == 0 || i < TILE * K8G) { + int8_t* d = &sK8[(i / K8G) * KSTR8 + (i % K8G) * 16]; + *(uint2*)d = make_uint2(kr[p].x, kr[p].y); + *(uint2*)(d + 8) = make_uint2(kr[p].z, kr[p].w); + } + } + if (tid < TILE) sKs[tid] = ksr; + } else { + #pragma unroll + for (int p = 0; p < KP; ++p) { + const int i = tid + p * NTHR; + if (KITEMS % NTHR == 0 || i < KITEMS) { + *(uint2*)&sK8[(i / DG) * KSTR8 + (i % DG) * 8] = kq[p]; + if (i % DG == 0) sKs[i / DG] = kqs[p]; + } + } + } + } else { + #pragma unroll + for (int p = 0; p < KP; ++p) { + const int i = tid + p * NTHR; + if (KITEMS % NTHR == 0 || i < KITEMS) + *(uint4*)&sK[(i / DG) * KSTR + (i % DG) * 8] = kr[p]; + } + } + lds_barrier(); + + #pragma unroll 1 + for (int mt = 0; mt < MT; ++mt) { + // The scores of 16 keys, in log2 units once times `qs` (a no-op 1 for bf16, whose + // query carries the scale already). + float sc[8]; + if constexpr (I8) { + v8i_ps si = (v8i_ps){0, 0, 0, 0, 0, 0, 0, 0}; + const int8_t* kr2 = &sK8[(mt * 16 + c) * KSTR8] + 8 * h; + #pragma unroll + for (int t0 = 0; t0 < NKS; t0 += 4) { + v2i_ps kf[4]; + #pragma unroll + for (int j = 0; j < 4; ++j) + if (t0 + j < NKS) { + const uint2 u = *(const uint2*)(kr2 + 16 * (t0 + j)); + kf[j] = (v2i_ps){ (int)u.x, (int)u.y }; + } + sched_barrier(); + #pragma unroll + for (int j = 0; j < 4; ++j) + if (t0 + j < NKS) + si = __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, kf[j], true, + qf[t0 + j], si, false); + } + const float4 ka = *(const float4*)&sKs[mt * 16 + 8 * h]; + const float4 kb = *(const float4*)&sKs[mt * 16 + 8 * h + 4]; + const float ks[8] = { ka.x, ka.y, ka.z, ka.w, kb.x, kb.y, kb.z, kb.w }; + #pragma unroll + for (int e = 0; e < 8; ++e) sc[e] = (float)si[e] * ks[e]; + } else { + v8f s = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; + const uint16_t* kr2 = &sK[(mt * 16 + c) * KSTR] + 8 * h; + #pragma unroll + for (int t0 = 0; t0 < NKS; t0 += 4) { + frag16 kf[4]; + #pragma unroll + for (int j = 0; j < 4; ++j) + if (t0 + j < NKS) { + const uint4 u = *(const uint4*)(kr2 + 16 * (t0 + j)); + kf[j] = D::mk(make_uint2(u.x, u.y), make_uint2(u.z, u.w)); + } + sched_barrier(); + #pragma unroll + for (int j = 0; j < 4; ++j) + if (t0 + j < NKS) s = D::wmma(kf[j], qf[t0 + j], s); + } + #pragma unroll + for (int e = 0; e < 8; ++e) sc[e] = s[e]; + } + if (mask) { + const int kq0 = k0 + mt * 16 + 8 * h; + #pragma unroll + for (int e = 0; e < 8; ++e) { + const int key = kq0 + e; + const bool ok = key < klim && (pre || !causal || key <= qpos); + sc[e] = ok ? sc[e] : -INFINITY; + } + } + + // `qs` is positive, so the maximum of the scaled scores is the scaled maximum. + float smax = sc[0]; + #pragma unroll + for (int e = 1; e < 8; ++e) smax = fmaxf(smax, sc[e]); + if (I8) smax *= qs; + if (wave_any(smax > m_ref + GROW)) { + const float rmax = fmaxf(smax, swap16(smax)); + const float mnew = fmaxf(fmaxf(m_ref, rmax), -3.0e38f); + const float alpha = ex2(m_ref - mnew); + #pragma unroll + for (int t = 0; t < NKS; ++t) + #pragma unroll + for (int e = 0; e < 8; ++e) acc[t][e] *= alpha; + l_i *= alpha; + m_ref = mnew; + soff = -mnew; + } + + // P TO BF16 BY TRUNCATION: one v_perm a pair where gfx1201's software round-to-nearest + // is about six VALU a value, on a path where the WMMA and the VALU share the SIMD + // (4-7% of the kernel at a DiT's 16384 rows). Its error is the rounding's in size, and + // its downward bias cancels: the row sum below is taken off the same truncated values. + uint32_t pw[4]; + #pragma unroll + for (int e = 0; e < 8; e += 2) { + const float a0 = I8 ? __builtin_fmaf(sc[e], qs, soff) : sc[e] + soff; + const float a1 = I8 ? __builtin_fmaf(sc[e + 1], qs, soff) : sc[e + 1] + soff; + const uint32_t lo = __builtin_bit_cast(uint32_t, ex2(a0)); + const uint32_t hi = __builtin_bit_cast(uint32_t, ex2(a1)); + pw[e >> 1] = __builtin_amdgcn_perm(hi, lo, 0x07060302u); + } + // The row sum off the packed P, so the denominator is the values P.V used. + #pragma unroll + for (int e = 0; e < 4; ++e) + l_i += __builtin_bit_cast(float, pw[e] << 16) + + __builtin_bit_cast(float, pw[e] & 0xffff0000u); + const frag16 p16 = D::mk(make_uint2(pw[0], pw[1]), make_uint2(pw[2], pw[3])); + + { + const uint16_t* vr2 = &sV[c * VSTR + mt * 16] + 8 * h; + #pragma unroll + for (int t0 = 0; t0 < NKS; t0 += 4) { + frag16 vf[4]; + #pragma unroll + for (int j = 0; j < 4; ++j) + if (t0 + j < NKS) { + const uint4 u = *(const uint4*)(vr2 + (t0 + j) * 16 * VSTR); + vf[j] = D::mk(make_uint2(u.x, u.y), make_uint2(u.z, u.w)); + } + sched_barrier(); + #pragma unroll + for (int j = 0; j < 4; ++j) + if (t0 + j < NKS) acc[t0 + j] = D::wmma(vf[j], p16, acc[t0 + j]); + } + } + } + } + + if (!live) return; + const float ls = l_i + swap16(l_i); + const float inv = (ls > 0.0f) ? (1.0f / ls) : 0.0f; + uint16_t* op = go + (long)(s0 + qpos) * o_ld + (long)hq * HD; + #pragma unroll + for (int t = 0; t < NKS; ++t) { + uint32_t tw[4]; + #pragma unroll + for (int e = 0; e < 8; e += 2) + tw[e >> 1] = (uint32_t)f32_to_bf16(acc[t][e] * inv) + | ((uint32_t)f32_to_bf16(acc[t][e + 1] * inv) << 16); + *(uint4*)(op + t * 16 + 8 * h) = make_uint4(tw[0], tw[1], tw[2], tw[3]); + } +} + +template +static int r4d_attn_ps_launch(const void* q, const void* k, const void* k8, const float* ks, + const void* v, void* o, const int* cu, + const int* used, const int* bt, int bt_pitch, const void* kvc, + int num_seqs, int max_q, int n_head_kv, float scale, int causal, + int q_ld, int k_ld, int k8_ld, int ks_ld, int v_ld, int o_ld, + hipStream_t s) +{ + constexpr int BQ = NQB * 16; + // Every sequence's blocks: at most total / BQ, plus one partial block a sequence. + dim3 grid((max_q + BQ - 1) / BQ + num_seqs, n_head_kv, 1); + hipLaunchKernelGGL((r4d_attn_ps_kernel), grid, dim3(NQB * GQA * 32), 0, s, + (const uint16_t*)q, (const uint16_t*)k, (const int8_t*)k8, ks, + (const uint16_t*)v, (uint16_t*)o, cu, num_seqs, used, bt, bt_pitch, + (const uint16_t*)kvc, n_head_kv, scale, causal, q_ld, k_ld, k8_ld, ks_ld, + v_ld, o_ld); + const hipError_t e = hipGetLastError(); + return e == hipSuccess ? 0 : -100 - (int)e; +} + +/* head_dim 128 at gqa 1, 2, 4 and 8. `used`/`bt`/`kvc` null is no prefix: the dense form. `max_q` + * is the query rows of every sequence together, which bounds the flat grid. `k8` non-null is the + * int8 Q.K form -- the own keys as int8 codes (`k8_ld` bytes a row) with a scale per (row, head) + * in `ks` (`ks_ld` floats a row) -- at gqa 1, the only ratio a DiT has. */ +static int r4d_attn_ps(const void* q, const void* k, const void* k8, const float* ks, + const void* v, void* o, const int* cu, + const int* used, const int* bt, int bt_pitch, const void* kvc, + int num_seqs, int max_q, int n_head, int n_head_kv, int head_dim, + float scale, int causal, int q_ld, int k_ld, int k8_ld, int ks_ld, + int v_ld, int o_ld, hipStream_t s) +{ + if (n_head <= 0 || n_head_kv <= 0 || n_head % n_head_kv) return -2; + if ((q_ld | k_ld | v_ld | o_ld) & 7) return -3; + if (k8 && ((k8_ld & 15) || ((uintptr_t)k8 & 15) || !ks)) return -3; + if (num_seqs <= 0 || max_q <= 0) return 0; + const int gqa = n_head / n_head_kv; + if (head_dim != 128) return -1; +#define R4D_PS(G, NQB, T, I8) \ + return r4d_attn_ps_launch<128, G, NQB, T, I8>(q, k, k8, ks, v, o, cu, used, bt, bt_pitch, kvc, \ + num_seqs, max_q, n_head_kv, scale, causal, \ + q_ld, k_ld, k8_ld, ks_ld, v_ld, o_ld, s) + /* SIXTEEN QUERY TILES A WORKGROUP at gqa 1: a workgroup streams its head's whole K and V once, + * so the rows it serves divide that traffic. At a DiT's 16384 rows a head's K and V are 8 MB + * and fall out of L2; 128 rows a workgroup ran at 66 TFLOP/s, 256 at 111, 512 at 102. */ + if (k8) { + if (gqa != 1) return -1; + R4D_PS(1, 16, 64, true); + } + switch (gqa) { + case 1: R4D_PS(1, 16, 64, false); + case 2: R4D_PS(2, 4, 64, false); + case 4: R4D_PS(4, 2, 64, false); + case 8: R4D_PS(8, 1, 64, false); + default: return -1; + } +#undef R4D_PS +} + +// ============================================================== the plugin ABI entry points +/* [tokens, heads * head_dim] (or rank 3) at the operand's own row pitch. */ +static bool ps_rows(const RadTensor* t, long long head_dim, long long* n_tok, long long* n_head, + long long* ld) { + long long width = 1; + for (uint32_t i = 1; i < t->rank; ++i) width *= t->shape[i]; + if (t->rank < 2 || width % head_dim) return false; + *n_head = width / head_dim; + *ld = r4d_rows_pitch(t, width, n_tok); + return *ld >= 0; +} + +enum { PS_Q = 0, PS_K, PS_V, PS_KV, PS_BT, PS_USED, PS_CU, PS_KDES, PS_VDES, PS_K8, PS_KS, + PS_OUT }; + +extern "C" int r4d_rad_attn_prefix_self(const RadArgs* a, RadStream s) { + const RadTensor* q = r4d_opt(a, PS_Q); + const RadTensor* k = r4d_opt(a, PS_K); + const RadTensor* v = r4d_opt(a, PS_V); + const RadTensor* kv = r4d_opt(a, PS_KV); + const RadTensor* bt = r4d_opt(a, PS_BT); + const RadTensor* su = r4d_opt(a, PS_USED); + const RadTensor* cu = r4d_opt(a, PS_CU); + const RadTensor* o = r4d_opt(a, PS_OUT); + if (!q || !k || !v || !kv || !bt || !su || !cu || !o) return R4D_NO(RAD_E_INVAL); + if (r4d_opt(a, PS_KDES) || r4d_opt(a, PS_VDES)) return R4D_NO(RAD_E_UNSUPPORTED); + if (kv->dtype != RAD_BF16 || q->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); + const long long hd = r4d_geti_or(a, "head_dim", 0), gqa = r4d_geti_or(a, "gqa", 1); + if (hd != 128 || gqa <= 0) return R4D_NO(RAD_E_SHAPE); + if (kv->rank != 4 || kv->shape[2] != 16 || kv->shape[3] != 2 * hd) return R4D_NO(RAD_E_SHAPE); + if (!r4d_contig(cu) || !r4d_contig(su) || cu->rank != 1 || cu->shape[0] < 2) + return R4D_NO(RAD_E_SHAPE); + const int num_seqs = (int)(cu->shape[0] - 1); + if (r4d_numel(su) < num_seqs) return R4D_NO(RAD_E_SHAPE); + long long total = 0, nh = 0, q_ld = 0, tk = 0, hk = 0, k_ld = 0, tv = 0, hv = 0, v_ld = 0; + long long to = 0, ho = 0, o_ld = 0; + if (!ps_rows(q, hd, &total, &nh, &q_ld) || !ps_rows(k, hd, &tk, &hk, &k_ld) || + !ps_rows(v, hd, &tv, &hv, &v_ld) || !ps_rows(o, hd, &to, &ho, &o_ld)) + return R4D_NO(RAD_E_STRIDE); + if (hk != hv || ho != nh || hk * gqa != nh || hk != kv->shape[1]) return R4D_NO(RAD_E_SHAPE); + if (tk < total || tv < total || to < total) return R4D_NO(RAD_E_SHAPE); + const long long bt_pitch = bt->rank >= 2 ? bt->shape[1] : r4d_numel(bt) / num_seqs; + if (bt->rank >= 2 && bt->stride[1] != 1) return R4D_NO(RAD_E_STRIDE); + const long long mq = total; + /* THE INT8 Q.K FORM (`qk` "i8"): the own keys' codes [tokens, kv_heads * head_dim] and their + * scales [tokens, kv_heads], as quant_act_i8g writes them at group head_dim. */ + const RadTensor* k8 = r4d_opt(a, PS_K8); + const RadTensor* ks = r4d_opt(a, PS_KS); + const char* qk = r4d_gets(a, "qk"); + const bool i8 = qk && !std::strcmp(qk, "i8"); + if (qk && !i8 && std::strcmp(qk, "bf16")) return R4D_NO(RAD_E_INVAL); + if (i8 != (k8 != nullptr) || i8 != (ks != nullptr)) return R4D_NO(RAD_E_INVAL); + long long k8_ld = 0, ks_ld = 0; + if (k8) { + if (k8->dtype != RAD_I8 || ks->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); + long long t8 = 0, h8 = 0, ts = 0; + if (!ps_rows(k8, hd, &t8, &h8, &k8_ld)) return R4D_NO(RAD_E_STRIDE); + ks_ld = r4d_rows_pitch(ks, hk, &ts); + if (ks_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (h8 != hk || t8 < total || ts < total) return R4D_NO(RAD_E_SHAPE); + } + const float scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)hd)); + const int e = r4d_attn_ps(q->data, k->data, k8 ? k8->data : nullptr, + ks ? (const float*)ks->data : nullptr, v->data, o->data, + (const int*)cu->data, (const int*)su->data, (const int*)bt->data, + (int)bt_pitch, kv->data, num_seqs, (int)mq, (int)nh, (int)hk, (int)hd, + scale, (int)r4d_geti_or(a, "causal", 0), (int)q_ld, (int)k_ld, + (int)k8_ld, (int)ks_ld, (int)v_ld, (int)o_ld, (hipStream_t)s); + if (e == -1 || e == -2) return R4D_NO(RAD_E_SHAPE); + return e == 0 ? RAD_OK : R4D_NO(e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE); +} + +/* attn_dense at head_dim 128, causal or not: the same kernel with no prefix. */ +extern "C" int r4d_rad_attn_dense_h128(const RadArgs* a, RadStream s) { + const RadTensor* q = r4d_opt(a, 0); + const RadTensor* k = r4d_opt(a, 1); + const RadTensor* v = r4d_opt(a, 2); + const RadTensor* cu = r4d_opt(a, 3); + const RadTensor* o = r4d_opt(a, 4); + if (!q || !k || !v || !cu || !o) return R4D_NO(RAD_E_INVAL); + if (!r4d_contig(cu) || cu->rank != 1 || cu->shape[0] < 2) return R4D_NO(RAD_E_SHAPE); + const long long hd = r4d_geti_or(a, "head_dim", 0), gqa = r4d_geti_or(a, "gqa", 1); + if (hd != 128 || gqa <= 0) return R4D_NO(RAD_E_SHAPE); + if (r4d_geti_or(a, "window", 0) != 0) return R4D_NO(RAD_E_UNSUPPORTED); + long long total = 0, nh = 0, q_ld = 0, tk = 0, hk = 0, k_ld = 0, tv = 0, hv = 0, v_ld = 0; + long long to = 0, ho = 0, o_ld = 0; + if (!ps_rows(q, hd, &total, &nh, &q_ld) || !ps_rows(k, hd, &tk, &hk, &k_ld) || + !ps_rows(v, hd, &tv, &hv, &v_ld) || !ps_rows(o, hd, &to, &ho, &o_ld)) + return R4D_NO(RAD_E_STRIDE); + if (hk != hv || ho != nh || hk * gqa != nh) return R4D_NO(RAD_E_SHAPE); + if (tk < total || tv < total || to < total) return R4D_NO(RAD_E_SHAPE); + const int num_seqs = (int)(cu->shape[0] - 1); + const float scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)hd)); + const int e = r4d_attn_ps(q->data, k->data, nullptr, nullptr, v->data, o->data, + (const int*)cu->data, nullptr, nullptr, 0, nullptr, num_seqs, + (int)total, (int)nh, (int)hk, (int)hd, scale, + (int)r4d_geti_or(a, "causal", 0), (int)q_ld, (int)k_ld, 0, 0, + (int)v_ld, (int)o_ld, (hipStream_t)s); + if (e == -1 || e == -2) return R4D_NO(RAD_E_SHAPE); + return e == 0 ? RAD_OK : R4D_NO(e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE); +} + +// ============================================================== wide heads (attn_dense, h768 / h1152) +// AN IMAGE DECODER'S MID-BLOCK ATTENTION: one head 1152 wide over every latent pixel -- 16384 rows +// at 2048 x 2048. A lane cannot hold a 1152-wide output row (576 accumulator registers), so the +// head is split across the workgroup's eight waves instead of its rows: a wave owns HD/8 of the +// dims for the whole 16-query block. +// +// S = Q.K^T is contracted in eight pieces, a wave's dims each, and the partial score tiles are +// summed through LDS in wave order -- a fixed order, so the sum is the same every run. +// P is formed once, by sixteen threads (a query row each), rounded to bf16, and its row sum is +// taken off the rounded values, the denominator P.V uses. +// O += P.V is a wave's own dims: V^T fragments straight from global with the transposing load +// (no LDS), P^T from LDS. +// +// S^T = K.Q^T as in the dense kernel above, so a partial tile's C layout is (query = lane % 16, +// key = 8 (lane / 16) + e) and both the reduction and the P^T fragment index it the same way. +template +__global__ __launch_bounds__(256) +void r4d_attn_wide_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk, + const uint16_t* __restrict__ gv, uint16_t* __restrict__ go, + const int* __restrict__ cu, int num_seqs, float scale, int q_ld, + int k_ld, int v_ld, int o_ld) +{ + typedef DT16<0> D; + constexpr int DW = HD / 8; // dims a wave + constexpr int NS = DW / 16; // its 16-wide steps + constexpr int KT = 64; // keys a tile + constexpr int PP = KT + 8; // P's LDS row pitch, in bf16 + static_assert(HD % 128 == 0, "eight waves of whole 16-wide steps"); + + __shared__ float sPart[8 * KT * 16]; + __shared__ float sS[KT * 16]; + __shared__ __align__(16) uint16_t sP[16 * PP]; + __shared__ float sAlpha[16], sL[16]; + + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int c = lane & 15, h = lane >> 4; + const int head = blockIdx.y; + + int seq = -1, q0 = 0; + for (int s = 0, b = blockIdx.x; s < num_seqs; ++s) { + const int nb = (cu[s + 1] - cu[s] + 15) / 16; + if (b < nb) { seq = s; q0 = b * 16; break; } + b -= nb; + } + if (seq < 0) return; + const int s0 = cu[seq], slen = cu[seq + 1] - s0; + if (slen <= 0 || q0 >= slen) return; + + const int d0 = wave * DW; + const uint16_t* qb = gq + (long)head * HD + d0; + const uint16_t* kb = gk + (long)head * HD + d0; + const uint16_t* vb = gv + (long)head * HD + d0; + const float mul = scale * 1.44269504089f; + + D::frag qf[NS]; + { + const int qr = min(q0 + c, slen - 1); + const uint16_t* p = qb + (long)(s0 + qr) * q_ld + 4 * h; + #pragma unroll + for (int t = 0; t < NS; ++t) { + const uint2 lo = *(const uint2*)(p + 16 * t), hi = *(const uint2*)(p + 16 * t + 8); + qf[t] = D::mk(lo, hi); + } + } + v8f acc[NS]; + #pragma unroll + for (int t = 0; t < NS; ++t) acc[t] = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; + float m_run = -INFINITY, l_run = 0.0f; + + for (int k0 = 0; k0 < slen; k0 += KT) { + // ---- this wave's share of S^T for the tile's four 16-key blocks + #pragma unroll + for (int j = 0; j < KT / 16; ++j) { + v8f sp = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; + const int kr = min(k0 + 16 * j + c, slen - 1); + const uint16_t* p = kb + (long)(s0 + kr) * k_ld + 4 * h; + #pragma unroll + for (int t = 0; t < NS; ++t) { + const uint2 lo = *(const uint2*)(p + 16 * t), hi = *(const uint2*)(p + 16 * t + 8); + sp = D::wmma(D::mk(lo, hi), qf[t], sp); + } + #pragma unroll + for (int e = 0; e < 8; ++e) sPart[wave * KT * 16 + (16 * j + 8 * h + e) * 16 + c] = sp[e]; + } + __syncthreads(); + for (int u = tid; u < KT * 16; u += 256) { + float t = 0.0f; + #pragma unroll + for (int w = 0; w < 8; ++w) t += sPart[w * KT * 16 + u]; + sS[u] = t; + } + __syncthreads(); + // ---- the softmax, a thread a query row + if (tid < 16) { + const int nk = min(KT, slen - k0); + float mx = m_run; + for (int key = 0; key < nk; ++key) mx = fmaxf(mx, sS[key * 16 + tid] * mul); + const float alpha = ex2(m_run - mx); + float lsum = 0.0f; + for (int key = 0; key < KT; ++key) { + const uint16_t pb = key < nk ? f32_to_bf16(ex2(sS[key * 16 + tid] * mul - mx)) : 0; + sP[tid * PP + key] = pb; + lsum += __builtin_bit_cast(float, (uint32_t)pb << 16); + } + l_run = l_run * alpha + lsum; + m_run = mx; + sAlpha[tid] = alpha; + } + __syncthreads(); + // ---- O^T += V^T . P^T over the wave's dims + const float al = sAlpha[c]; + #pragma unroll + for (int t = 0; t < NS; ++t) + #pragma unroll + for (int e = 0; e < 8; ++e) acc[t][e] *= al; + #pragma unroll + for (int ks = 0; ks < KT / 16; ++ks) { + const uint4 pu = *(const uint4*)&sP[c * PP + 16 * ks + 8 * h]; + const D::frag pf = D::mk(make_uint2(pu.x, pu.y), make_uint2(pu.z, pu.w)); + const int kr = min(k0 + 16 * ks + 8 * h + (lane & 7), slen - 1); + const uint16_t* vp = vb + (long)(s0 + kr) * v_ld + 8 * ((lane >> 3) & 1); + #pragma unroll + for (int t = 0; t < NS; ++t) { + const uint4 u = __builtin_bit_cast(uint4, load_tr_b128(vp + 16 * t)); + acc[t] = D::wmma(D::mk(make_uint2(u.x, u.y), make_uint2(u.z, u.w)), pf, acc[t]); + } + } + } + if (tid < 16) sL[tid] = l_run; + __syncthreads(); + if (q0 + c >= slen) return; + const float inv = sL[c] > 0.0f ? 1.0f / sL[c] : 0.0f; + uint16_t* op = go + (long)(s0 + q0 + c) * o_ld + (long)head * HD + d0; + #pragma unroll + for (int t = 0; t < NS; ++t) { + uint32_t tw[4]; + #pragma unroll + for (int e = 0; e < 8; e += 2) + tw[e >> 1] = (uint32_t)f32_to_bf16(acc[t][e] * inv) + | ((uint32_t)f32_to_bf16(acc[t][e + 1] * inv) << 16); + *(uint4*)(op + 16 * t + 8 * h) = make_uint4(tw[0], tw[1], tw[2], tw[3]); + } +} + +/* attn_dense at head_dim 768 or 1152 (an image encoder's and decoder's mid block), one query head a + * KV head, bidirectional. */ +extern "C" int r4d_rad_attn_dense_wide(const RadArgs* a, RadStream s) { + const RadTensor* q = r4d_opt(a, 0); + const RadTensor* k = r4d_opt(a, 1); + const RadTensor* v = r4d_opt(a, 2); + const RadTensor* cu = r4d_opt(a, 3); + const RadTensor* o = r4d_opt(a, 4); + if (!q || !k || !v || !cu || !o) return R4D_NO(RAD_E_INVAL); + if (!r4d_contig(cu) || cu->rank != 1 || cu->shape[0] < 2) return R4D_NO(RAD_E_SHAPE); + const long long hd = r4d_geti_or(a, "head_dim", 0); + if ((hd != 768 && hd != 1152) || r4d_geti_or(a, "gqa", 1) != 1 || r4d_geti_or(a, "causal", 0) != 0 || + r4d_geti_or(a, "window", 0) != 0) + return R4D_NO(RAD_E_UNSUPPORTED); + long long total = 0, nh = 0, q_ld = 0, tk = 0, hk = 0, k_ld = 0, tv = 0, hv = 0, v_ld = 0; + long long to = 0, ho = 0, o_ld = 0; + if (!ps_rows(q, hd, &total, &nh, &q_ld) || !ps_rows(k, hd, &tk, &hk, &k_ld) || + !ps_rows(v, hd, &tv, &hv, &v_ld) || !ps_rows(o, hd, &to, &ho, &o_ld)) + return R4D_NO(RAD_E_STRIDE); + if (hk != nh || hv != nh || ho != nh) return R4D_NO(RAD_E_SHAPE); + if (tk < total || tv < total || to < total) return R4D_NO(RAD_E_SHAPE); + if ((q_ld | k_ld | v_ld | o_ld) & 7) return R4D_NO(RAD_E_STRIDE); + const int num_seqs = (int)(cu->shape[0] - 1); + const float scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)hd)); + dim3 grid((unsigned)((total + 15) / 16 + num_seqs), (unsigned)nh); +#define R4D_WIDE(HD) \ + hipLaunchKernelGGL((r4d_attn_wide_kernel), grid, dim3(256), 0, (hipStream_t)s, \ + (const uint16_t*)q->data, (const uint16_t*)k->data, \ + (const uint16_t*)v->data, (uint16_t*)o->data, (const int*)cu->data, \ + num_seqs, scale, (int)q_ld, (int)k_ld, (int)v_ld, (int)o_ld) + if (hd == 768) R4D_WIDE(768); + else R4D_WIDE(1152); +#undef R4D_WIDE + return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); +} diff --git a/libr4d/r4d_encoder_bf16.hip b/libr4d/r4d_encoder_bf16.hip index e44db1ea..20972e1f 100644 --- a/libr4d/r4d_encoder_bf16.hip +++ b/libr4d/r4d_encoder_bf16.hip @@ -222,11 +222,19 @@ __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_kernel( // rotated pair: the norm's sum of squares first, then each lane re-reads its pair, norms, gains, // rounds (the norm rounded before the rotation, as above) and rotates it. Channels past `rot` // are normed only; a v head (v_norm) is normed at unit gain. +// +// `pm` picks the pairing, which is all that separates three rotaries over the same table: +// 0 blocks a section's pairs are (start + j, start + sec + j), its own ladder +// 1 gptj_blocks a section's pairs are ADJACENT, (start + 2j, start + 2j + 1), its own ladder: +// the complex-number form of a 3-axis image rotary (Qwen-Image) +// 2 imrope NeoX pairs (i, i + rot/2) on one ladder theta^(-2i/rot), the position +// component interleaved: 1 where i % 3 == 1 and i < 3 * sec[1], 2 where +// i % 3 == 2 and i < 3 * sec[2], 0 elsewhere (Qwen3-VL's text attention) __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_any_kernel( uint16_t* __restrict__ qkv, const int* __restrict__ pos, const uint16_t* __restrict__ qw, const uint16_t* __restrict__ kw, uint32_t head_dim, uint32_t n_head, uint32_t n_head_kv, uint32_t rot, int v_norm, float theta, float eps, float rscale, float wadd, uint32_t ld, - QkBlocks blk, uint32_t pplane) { + QkBlocks blk, uint32_t pplane, int pm) { __shared__ float cs_s[kQkMaxHalf], sn_s[kQkMaxHalf]; __shared__ int pa_s[kQkMaxHalf], pb_s[kQkMaxHalf]; const uint32_t m = blockIdx.x; @@ -236,13 +244,29 @@ __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_any_kernel( uint16_t* row = qkv + (size_t)m * ld; const float div = rscale != 0.0f ? rscale : 1.0f; for (uint32_t i = threadIdx.x; i < half; i += kQkThreads) { + if (pm == 2) { + int c = 0; + if (i % 3 == 1 && (int)i < 3 * blk.sec[1]) c = 1; + else if (i % 3 == 2 && (int)i < 3 * blk.sec[2]) c = 2; + const float p = (float)pos[(size_t)c * pplane + m] / div; + const float inv = 1.0f / powf(theta, (float)(2 * i) / (float)rot); + sincosf(p * inv, &sn_s[i], &cs_s[i]); + pa_s[i] = (int)i; + pb_s[i] = (int)(i + half); + continue; + } int c = 0, s0 = 0; while (c + 1 < blk.n && (int)i >= s0 + blk.sec[c]) { s0 += blk.sec[c]; ++c; } const float p = (float)pos[(size_t)blk.comp[c] * pplane + m] / div; const float inv = 1.0f / powf(theta, (float)((int)i - s0) / (float)blk.sec[c]); sincosf(p * inv, &sn_s[i], &cs_s[i]); - pa_s[i] = 2 * s0 + ((int)i - s0); - pb_s[i] = pa_s[i] + blk.sec[c]; + if (pm == 1) { + pa_s[i] = 2 * (int)i; + pb_s[i] = 2 * (int)i + 1; + } else { + pa_s[i] = 2 * s0 + ((int)i - s0); + pb_s[i] = pa_s[i] + blk.sec[c]; + } } __syncthreads(); const uint32_t lane = threadIdx.x & 31, wave = threadIdx.x >> 5; @@ -589,15 +613,34 @@ extern "C" int r4d_seg_mean_bf16(long x, long cu, long y, int S, int n, int x_ld return hipGetLastError() == hipSuccess ? 0 : -4; } -// mode: 0 neox, 1 gptj, 2 blocks (`blk` and the position plane stride `pplane` used only there). +// mode: 0 neox, 1 gptj, 2 blocks, 3 gptj_blocks, 4 imrope (`blk` and the position plane stride +// `pplane` used only by the last three). extern "C" int r4d_qk_norm_rope_bf16(long qkv, long pos, long qw, long kw, int M, int head_dim, int n_head, int n_head_kv, int rot, int mode, int v_norm, float theta, float eps, float rscale, float wadd, int ld, const QkBlocks* blk, int pplane, long stream) { if (!qkv || !pos || !qw || !kw) return -1; if (M <= 0 || head_dim <= 0 || n_head <= 0 || n_head_kv <= 0 || rot <= 0 || rot > head_dim || - (rot & 1) || rot / 2 > (int)kQkMaxHalf || head_dim > 32 * kQkMaxE || mode < 0 || mode > 2) + (rot & 1) || rot / 2 > (int)kQkMaxHalf || head_dim > 32 * kQkMaxE || mode < 0 || mode > 4) return -2; + if (mode >= 3) { + /* The two forms only the general kernel takes: its pair table is built per mode. */ + if (!blk || blk->n <= 0 || blk->n > 8) return -2; + int total = 0; + for (int c = 0; c < blk->n; ++c) { + if (blk->sec[c] <= 0) return -2; + total += blk->sec[c]; + } + if (mode == 3 && 2 * total != rot) return -2; + if (mode == 4 && (blk->n < 3 || 2 * total != rot)) return -2; + hipLaunchKernelGGL(qk_norm_rope_any_kernel, dim3((uint32_t)M), dim3(kQkThreads), 0, + (hipStream_t)stream, (uint16_t*)qkv, (const int*)pos, + (const uint16_t*)qw, (const uint16_t*)kw, (uint32_t)head_dim, + (uint32_t)n_head, (uint32_t)n_head_kv, (uint32_t)rot, v_norm, theta, + eps, rscale, wadd, (uint32_t)ld, *blk, (uint32_t)pplane, + mode == 3 ? 1 : 2); + return hipGetLastError() == hipSuccess ? 0 : -4; + } if (mode != 2 && head_dim % 32) return -2; if (mode == 1 && head_dim % 64) return -2; if (mode == 0 && (rot / 2) % 32) return -2; @@ -620,7 +663,7 @@ extern "C" int r4d_qk_norm_rope_bf16(long qkv, long pos, long qw, long kw, int M (hipStream_t)stream, (uint16_t*)qkv, (const int*)pos, (const uint16_t*)qw, (const uint16_t*)kw, (uint32_t)head_dim, (uint32_t)n_head, (uint32_t)n_head_kv, (uint32_t)rot, v_norm, theta, - eps, rscale, wadd, (uint32_t)ld, b, (uint32_t)pplane); + eps, rscale, wadd, (uint32_t)ld, b, (uint32_t)pplane, 0); return hipGetLastError() == hipSuccess ? 0 : -4; } #define R4D_QN(MD) \ @@ -837,12 +880,21 @@ extern "C" int r4d_rad_qk_norm_rope(const RadArgs* a, RadStream s) { int md = 0; if (mode && !std::strcmp(mode, "gptj")) md = 1; else if (mode && !std::strcmp(mode, "blocks")) md = 2; + else if (mode && !std::strcmp(mode, "gptj_blocks")) md = 3; + else if (mode && !std::strcmp(mode, "imrope")) md = 4; else if (mode && std::strcmp(mode, "neox")) return R4D_NO(RAD_E_UNSUPPORTED); - /* Any head_dim in the blocks mode (qk_norm_rope_any_kernel); the others need multiples of 32. */ - if (md != 2 && hd % 32) return R4D_NO(RAD_E_SHAPE); + /* Any head_dim in the section modes (qk_norm_rope_any_kernel); the others need multiples of 32. */ + if (md < 2 && hd % 32) return R4D_NO(RAD_E_SHAPE); QkBlocks blk{}; long long M = 0, pplane = 0; - if (md == 2) { + if (md == 4) { + /* Interleaved M-RoPE reads three position planes, its sections only bound the + * interleave. */ + blk.n = parse_ints(r4d_gets(a, "sections"), blk.sec, 8); + if (blk.n < 3 || pos->rank != 2 || pos->shape[0] < 3) return R4D_NO(RAD_E_SHAPE); + M = pos->shape[1]; + pplane = pos->stride[0]; + } else if (md >= 2) { blk.n = parse_ints(r4d_gets(a, "sections"), blk.sec, 8); if (blk.n <= 0) return R4D_NO(RAD_E_SHAPE); for (int c = 0; c < blk.n; ++c) blk.comp[c] = c; diff --git a/libr4d/r4d_gemm_bf16_nt_tiled.hip b/libr4d/r4d_gemm_bf16_nt_tiled.hip index 7b53e41e..7e06cab0 100644 --- a/libr4d/r4d_gemm_bf16_nt_tiled.hip +++ b/libr4d/r4d_gemm_bf16_nt_tiled.hip @@ -58,7 +58,18 @@ __global__ __launch_bounds__(256) void r4d_gemm_bf16_nt_tiled_kernel( const int tid = threadIdx.x, wave = tid >> 5, lane = tid & 31; const int wm = wave / BT_WN, wn = wave % BT_WN; - const int m0 = blockIdx.y * BM, n0 = blockIdx.x * BN; + // THE GRID RUNS IN GROUPS OF 8 ACTIVATION BANDS, M fastest inside a group. Blocks are + // dispatched in flattened-id order, and the launch's x-fastest grid swept every weight band for + // each activation band, reading the whole weight once per 128 rows: free while it sits in the + // 64 MB MALL, and half the rate once it does not (N 12288 x K 4096, 96 MB, ran at 68 TFLOP/s + // where N 8192 ran at 118). A group keeps its bands' weight tiles shared by the blocks in + // flight and reads the weight once a group. Small grids take it too: with fewer bands than a + // group the order is plain M-fastest, which is what reads the weight once. + constexpr unsigned kGroupM = 8; + const unsigned per = kGroupM * gridDim.x, lin = blockIdx.y * gridDim.x + blockIdx.x; + const unsigned first = lin / per * kGroupM, r = lin % per; + const unsigned gm = min(gridDim.y - first, kGroupM); + const int m0 = (int)(first + r % gm) * BM, n0 = (int)(r / gm) * BN; // Staging: chunk c = tid + 256 i is row c / CPR, elements (c % CPR) * 8 of it. Eight threads // cover a row's 128 bytes, so a warp's loads are four whole lines. diff --git a/libr4d/r4d_gemm_fp8a8.hip b/libr4d/r4d_gemm_fp8a8.hip index 98fa1489..4197bfd3 100644 --- a/libr4d/r4d_gemm_fp8a8.hip +++ b/libr4d/r4d_gemm_fp8a8.hip @@ -98,6 +98,8 @@ constexpr uint32_t kFN = 128, kFK = 64; // kFK is BYTES per LDS row // alone. constexpr uint32_t kFKNarrow = 256; constexpr uint32_t kFWaves = 8; +// Activation bands a raster group of the prefill tile holds in cache -- see the kernel's grouping. +constexpr uint32_t kGroupM = 16; // 1 M tile x 8 N tiles a wave, so the 8 waves cover 8 DISTINCT row tiles. // // The register tile is the two of these together and it is a genuine knob -- the body takes it as a @@ -415,8 +417,25 @@ void gemm_fp8a8_kernel( const uint32_t kend = ck ? min(cols, kbeg + ck) : cols; if (kbeg >= kend) return; - const uint32_t m0 = blockIdx.x * FM; - const uint32_t n0 = blockIdx.y * FN; + // THE PREFILL TILE RUNS IN GROUPS OF kGroupM ACTIVATION BANDS. Blocks are dispatched in + // flattened-id order, so with the plain x-fastest grid every weight band sweeps ALL of the + // activation, and the activation is read once per 128 weight rows. That is free while it sits + // in the 64 MB MALL and is the whole cost once it does not: at M = 16384 x K = 4096 (64 MB) + // gate_up's 192 bands read 12 GB and ran at half the rate of M = 4096. Within a group the + // kGroupM bands stay cached across the full N sweep, and the weight is read once a group. + // With kGroupM bands or fewer the order is the plain one, and skipping the division keeps a + // short prefill chunk at its old rate (2% at M = 512). + uint32_t bm = blockIdx.x, bn = blockIdx.y; + if (!AW && gridDim.x > kGroupM) { + const uint32_t per = kGroupM * gridDim.y; + const uint32_t lin = blockIdx.y * gridDim.x + blockIdx.x; + const uint32_t first = (lin / per) * kGroupM, r = lin % per; + const uint32_t gm = min(gridDim.x - first, kGroupM); + bm = first + r % gm; + bn = r / gm; + } + const uint32_t m0 = bm * FM; + const uint32_t n0 = bn * FN; // Wave grid MW(M) x 1(N): a wave owns MT*16 A rows and all FN B rows. A 4x2 grid at the same // 128x128 tile -- 2x4 a wave, so 6 fragment reads per 8 WMMA rather than 9 -- is a WASH, which // says the fragment reads, which do not bank-conflict, are not the wall. There is no diff --git a/libr4d/r4d_gen.hip b/libr4d/r4d_gen.hip new file mode 100644 index 00000000..b68bfa47 --- /dev/null +++ b/libr4d/r4d_gen.hip @@ -0,0 +1,1049 @@ +// R4D -- the image generator's ops (docs/OPS.md, "Image generation"): a diffusion transformer's +// adaptive norm and gated residual, the timestep embedding, the per-image latent lanes and the +// flow-matching sampler over them, and the image decoder's convolution, channel norm, resampling +// shortcuts and pixel output. +// +// EACH KERNEL ROUNDS WHERE ITS libref FUNCTION DOES (libref/ref_gen.cpp), and libref rounds where +// the reference model materialises a bf16 tensor. A reduction's order differs -- a block sum here, +// a sequential one there -- so a sum can land one bf16 step apart; nothing else does. +// +// IMAGE GEOMETRY IS IN THE OPERANDS. An image operand is [height, width * channels], dense, and +// the shims read both off its shape: a parameter is fixed at declare and an image's size is a +// request's. +#include "r4d.h" +#include "r4d_args.h" +#include "r4d_common.h" +#include "r4d_gdn_wmma.h" +#include "r4d_q8.h" +#include "rad_philox.h" + +#include +#include +#include + +namespace { + +constexpr int kT = 256; + +__device__ __forceinline__ float bfr(float v) { return bf2f(f32_to_bf16(v)); } + +// Eight bf16 at a 16-byte-aligned address, widened, and the reverse. +__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 st8(uint16_t* p, const float* f) { + uint4 u; + u.x = (uint32_t)f32_to_bf16(f[0]) | ((uint32_t)f32_to_bf16(f[1]) << 16); + u.y = (uint32_t)f32_to_bf16(f[2]) | ((uint32_t)f32_to_bf16(f[3]) << 16); + u.z = (uint32_t)f32_to_bf16(f[4]) | ((uint32_t)f32_to_bf16(f[5]) << 16); + u.w = (uint32_t)f32_to_bf16(f[6]) | ((uint32_t)f32_to_bf16(f[7]) << 16); + *(uint4*)p = u; +} + +// The entry that owns row r of a cu_seqlens partition: linear, because there are a handful. +__device__ __forceinline__ int seq_of(const int* cu, int n_seq, int r) { + int s = 0; + while (s + 1 < n_seq && cu[s + 1] <= r) ++s; + return s; +} + +// A sum over the 256 threads, every thread receiving it. `sh` is 8 floats of LDS. +__device__ __forceinline__ float block_sum(float v, float* sh) { + v = r4d_wave_sum(v); + __syncthreads(); + if ((threadIdx.x & 31) == 0) sh[threadIdx.x >> 5] = v; + __syncthreads(); + float t = 0.0f; + #pragma unroll + for (int i = 0; i < kT / 32; ++i) t += sh[i]; + return t; +} + +// ---------------------------------------------------------------------------- ln_mod +// A workgroup a row; mean, then variance about it, in f32 over the bf16 row. +__global__ __launch_bounds__(kT) void ln_mod_kernel( + const uint16_t* __restrict__ x, const uint16_t* __restrict__ s, const int* __restrict__ cu, + uint16_t* __restrict__ y, int n, int n_seq, float eps, int x_ld, int s_ld, int y_ld) { + __shared__ float sh[kT / 32]; + const int r = blockIdx.x; + const uint16_t* xr = x + (size_t)r * x_ld; + float sum = 0.0f; + for (int i = threadIdx.x * 8; i < n; i += kT * 8) { + float f[8]; + ld8(xr + i, f); + #pragma unroll + for (int j = 0; j < 8; ++j) sum += f[j]; + } + const float mean = block_sum(sum, sh) / (float)n; + float var = 0.0f; + for (int i = threadIdx.x * 8; i < n; i += kT * 8) { + float f[8]; + ld8(xr + i, f); + #pragma unroll + for (int j = 0; j < 8; ++j) { const float d = f[j] - mean; var += d * d; } + } + const float rs = 1.0f / sqrtf(block_sum(var, sh) / (float)n + eps); + const uint16_t* sr = s + (size_t)seq_of(cu, n_seq, r) * s_ld; + uint16_t* yr = y + (size_t)r * y_ld; + for (int i = threadIdx.x * 8; i < n; i += kT * 8) { + float f[8], g[8]; + ld8(xr + i, f); + ld8(sr + i, g); + #pragma unroll + for (int j = 0; j < 8; ++j) f[j] = bfr((f[j] - mean) * rs) * bfr(1.0f + g[j]); + st8(yr + i, f); + } +} + +// ---------------------------------------------------------------------------- gate_add +__global__ __launch_bounds__(kT) void gate_add_kernel( + const uint16_t* __restrict__ y, const uint16_t* __restrict__ g, const int* __restrict__ cu, + uint16_t* __restrict__ x, int n, int n_seq, int y_ld, int g_ld, int x_ld) { + const int r = blockIdx.x; + const uint16_t* gr = g + (size_t)seq_of(cu, n_seq, r) * g_ld; + for (int i = threadIdx.x * 8; i < n; i += kT * 8) { + float a[8], b[8], c[8]; + ld8(y + (size_t)r * y_ld + i, a); + ld8(gr + i, b); + ld8(x + (size_t)r * x_ld + i, c); + #pragma unroll + for (int j = 0; j < 8; ++j) c[j] = c[j] + bfr(bfr(tanhf(b[j])) * a[j]); + st8(x + (size_t)r * x_ld + i, c); + } +} + +// ---------------------------------------------------------------------------- ln_mod_quant_fp8 +// gate_add, ln_mod and quant_act_fp8 in one pass over the row: the DiT block's norm in front of +// every quantised linear, with the gated residual of the branch before it folded in. Three passes +// over a 16384 x 4096 activation were ~0.9 GB of traffic a norm; this one reads the delta and the +// residual and writes the residual and the E4M3 pair. The bf16 norm output is written only when +// bound -- the fp8 linears read the codes. +// +// BIT-IDENTICAL TO THE THREE IT REPLACES, which the picture comparing equal across builds needs: +// the residual is the gate_add arithmetic rounded to bf16 as its store rounds it, the mean and the +// variance fold each thread's 8-wide chunks in ln_mod_kernel's order through the same block_sum, +// the norm output is rounded to bf16 before it is quantised as quant_act_fp8 reads it, and the +// codes are r4d_q8.h's. A 128-column group is sixteen consecutive chunks, so sixteen consecutive +// lanes, and its amax is a half-wave reduction. +constexpr int kLnqChunks = 4; // 8-wide chunks a thread keeps: n <= kT * 8 * 4 = 8192 + +template +__global__ __launch_bounds__(kT) void ln_mod_quant_kernel( + const uint16_t* __restrict__ yd, const uint16_t* __restrict__ g, const uint16_t* __restrict__ s, + const int* __restrict__ cu, uint16_t* __restrict__ x, uint8_t* __restrict__ q, + float* __restrict__ qs, uint16_t* __restrict__ z, int n, int n_seq, float eps, int y_ld, + int g_ld, int s_ld, int x_ld, int q_ld, int qs_ld, int z_ld) { + __shared__ float sh[kT / 32]; + const int r = blockIdx.x; + const int e = seq_of(cu, n_seq, r); + uint16_t* xr = x + (size_t)r * x_ld; + float v[kLnqChunks][8]; + float sum = 0.0f; + #pragma unroll + for (int k = 0; k < kLnqChunks; ++k) { + const int i = ((int)threadIdx.x + k * kT) * 8; + if (i < n) { + float f[8]; + ld8(xr + i, f); + if (GATED) { + float a[8], b[8]; + ld8(yd + (size_t)r * y_ld + i, a); + ld8(g + (size_t)e * g_ld + i, b); + #pragma unroll + for (int j = 0; j < 8; ++j) f[j] = f[j] + bfr(bfr(tanhf(b[j])) * a[j]); + st8(xr + i, f); + #pragma unroll + for (int j = 0; j < 8; ++j) f[j] = bfr(f[j]); + } + #pragma unroll + for (int j = 0; j < 8; ++j) { v[k][j] = f[j]; sum += f[j]; } + } + } + const float mean = block_sum(sum, sh) / (float)n; + float var = 0.0f; + #pragma unroll + for (int k = 0; k < kLnqChunks; ++k) + if (((int)threadIdx.x + k * kT) * 8 < n) { + #pragma unroll + for (int j = 0; j < 8; ++j) { const float d = v[k][j] - mean; var += d * d; } + } + const float rs = 1.0f / sqrtf(block_sum(var, sh) / (float)n + eps); + const uint16_t* sr = s + (size_t)e * s_ld; + #pragma unroll + for (int k = 0; k < kLnqChunks; ++k) { + const int i = ((int)threadIdx.x + k * kT) * 8; + if (i >= n) break; + float gs[8], o[8]; + ld8(sr + i, gs); + #pragma unroll + for (int j = 0; j < 8; ++j) o[j] = bfr(bfr((v[k][j] - mean) * rs) * bfr(1.0f + gs[j])); + if (z) st8(z + (size_t)r * z_ld + i, o); + float m = 0.0f; + #pragma unroll + for (int j = 0; j < 8; ++j) m = fmaxf(m, fabsf(o[j])); + m = fmaxf(m, r4d_xor_lane<8>(m)); + m = fmaxf(m, r4d_xor_lane<4>(m)); + m = fmaxf(m, r4d_xor_lane<2>(m)); + m = fmaxf(m, r4d_xor_lane<1>(m)); + const float sc = m > 0.0f ? m * (1.0f / q8_top()) : 1.0f; + const float inv = 1.0f / sc; + if ((threadIdx.x & 15) == 0) qs[(size_t)r * qs_ld + i / 128] = sc; + *(uint2*)(q + (size_t)r * q_ld + i) = + make_uint2(q8_pack4(o[0], o[1], o[2], o[3], inv), + q8_pack4(o[4], o[5], o[6], o[7], inv)); + } +} + +// ---------------------------------------------------------------------------- timestep_embed +__global__ __launch_bounds__(kT) void timestep_kernel( + const float* __restrict__ t, uint16_t* __restrict__ y, int h, float scale, float coef, + int round, int y_ld) { + const int m = blockIdx.x; + const float tv = t[m]; + const float tt = round ? scale * bfr(bfr(tv * scale) / scale) : scale * tv; + for (int i = threadIdx.x; i < h; i += kT) { + const float f = expf(coef * (float)i / (float)h); + const float arg = tt * f; + y[(size_t)m * y_ld + i] = f32_to_bf16(cosf(arg)); + y[(size_t)m * y_ld + h + i] = f32_to_bf16(sinf(arg)); + } +} + +// ---------------------------------------------------------------------------- row moves +__global__ __launch_bounds__(kT) void gather2_kernel( + const uint16_t* __restrict__ a, const uint16_t* __restrict__ b, const int* __restrict__ idx, + uint16_t* __restrict__ y, int n, int ra, int rb, int a_ld, int b_ld, int y_ld) { + const int r = blockIdx.x; + const int i = idx[r]; + const uint16_t* src = nullptr; + if (i >= 0 && i < ra) src = a + (size_t)i * a_ld; + if (i < 0 && -1 - i < rb) src = b + (size_t)(-1 - i) * b_ld; + for (int c = threadIdx.x * 8; c < n; c += kT * 8) + *(uint4*)(y + (size_t)r * y_ld + c) = src ? *(const uint4*)(src + c) : make_uint4(0, 0, 0, 0); +} + +// The lane copies move WORDS: a row is `words` 32-bit words (64 bf16 latent channels are 32, an f32 +// mask value is one), so one kernel serves every dtype the lanes hold. +__global__ __launch_bounds__(kT) void lane_gather_kernel( + const uint32_t* __restrict__ src, const int* __restrict__ lane, const int* __restrict__ cu, + uint32_t* __restrict__ y, int words, int n_seq, int stride, int s_ldw, int y_ldw, int64_t total) { + const int64_t t = (int64_t)blockIdx.x * kT + threadIdx.x; + if (t >= total) return; + const int r = cu[0] + (int)(t / words), w = (int)(t % words); + if (r >= cu[n_seq]) return; + const int e = seq_of(cu, n_seq, r); + const int k = r - cu[e]; + y[(size_t)r * y_ldw + w] = src[((size_t)lane[e] * stride + k) * s_ldw + w]; +} + +__global__ __launch_bounds__(kT) void lane_store_kernel( + const uint32_t* __restrict__ src, const int* __restrict__ lane, uint32_t* __restrict__ dst, + int words, int stride, int s_ldw, int d_ldw, int64_t total) { + const int64_t t = (int64_t)blockIdx.x * kT + threadIdx.x; + if (t >= total) return; + const int r = (int)(t / words), w = (int)(t % words); + dst[((size_t)lane[blockIdx.y] * stride + r) * d_ldw + w] = src[(size_t)r * s_ldw + w]; +} + +__global__ __launch_bounds__(kT) void scatter_add_kernel( + const uint16_t* __restrict__ v, const int* __restrict__ idx, uint16_t* __restrict__ x, int n, + int v_ld, int x_ld) { + const int m = blockIdx.x; + const int r = idx[m]; + if (r < 0) return; + for (int c = threadIdx.x * 8; c < n; c += kT * 8) { + float a[8], b[8]; + ld8(v + (size_t)m * v_ld + c, a); + ld8(x + (size_t)r * x_ld + c, b); + #pragma unroll + for (int j = 0; j < 8; ++j) b[j] += a[j]; + st8(x + (size_t)r * x_ld + c, b); + } +} + +// ---------------------------------------------------------------------------- the sampler +// The seed of entry e, low word first. +__device__ __forceinline__ uint64_t seed_of(const uint32_t* seed, int e) { + return (uint64_t)seed[2 * e] | ((uint64_t)seed[2 * e + 1] << 32); +} + +__global__ __launch_bounds__(kT) void randn_lanes_kernel( + const int* __restrict__ flags, const uint32_t* __restrict__ seed, const int* __restrict__ lane, + const int* __restrict__ cu, uint16_t* __restrict__ dst, int n, int stride, int d_ld) { + const int e = blockIdx.y; + if (!(flags[e] & 1)) return; + const int64_t i = (int64_t)blockIdx.x * kT + threadIdx.x; + const int64_t len = cu[e + 1] - cu[e]; + if (i >= len * n) return; + const int64_t k = i / n, c = i % n; + dst[((size_t)lane[e] * stride + k) * d_ld + c] = + f32_to_bf16(rad_philox_normal(seed_of(seed, e), (uint64_t)i)); +} + +__global__ __launch_bounds__(kT) void flow_euler_kernel( + const uint16_t* __restrict__ v, const float* __restrict__ sg, const float* __restrict__ sgn, + const float* __restrict__ cfg, const int* __restrict__ pair, const int* __restrict__ lane, + const int* __restrict__ flags, const uint32_t* __restrict__ seed, const int* __restrict__ cu, + const uint16_t* __restrict__ inp, const float* __restrict__ mask, uint16_t* __restrict__ st, + uint16_t* __restrict__ pv, int n, int stride, int v_ld, int i_ld, int st_ld, int pv_ld) { + const int e = blockIdx.y; + const int pr = pair[e]; + if (pr == -2) return; + const int b0 = cu[e]; + const int64_t len = cu[e + 1] - b0; + const int64_t i = (int64_t)blockIdx.x * kT + threadIdx.x; + if (i >= len * n) return; + const int64_t k = i / n, c = i % n; + const int L = lane[e], f = flags[e]; + const float s = sg[e], sn = sgn[e]; + float vv = bf2f(v[(size_t)(b0 + k) * v_ld + c]); + if (pr >= 0) { + const float vn = bf2f(v[(size_t)(cu[pr] + k) * v_ld + c]); + vv = bfr(vn + bfr(cfg[e] * bfr(vv - vn))); + } + const size_t so = ((size_t)L * stride + k) * st_ld + c; + const float x = bf2f(st[so]); + if ((f & 4) && pv) pv[((size_t)L * stride + k) * pv_ld + c] = f32_to_bf16(x - s * vv); + float xn = bfr(x + bfr(bfr(sn - s) * vv)); + if ((f & 2) && inp && mask) { + const float m = mask[(size_t)L * stride + k]; + const float src = bf2f(inp[((size_t)L * stride + k) * i_ld + c]); + const float nz = rad_philox_normal(seed_of(seed, e), (uint64_t)i); + xn = bfr(m * xn + (1.0f - m) * ((1.0f - sn) * src + sn * nz)); + } + st[so] = f32_to_bf16(xn); +} + +// ---------------------------------------------------------------------------- per-channel ops +// The two lists ride in the kernel's arguments, whose segment the backend caps at 768 bytes: 64 +// channels a list (a latent's) is 512 of them. +constexpr int kChanMax = 64; +struct ChanLists { float mul[kChanMax], add[kChanMax]; }; + +__global__ __launch_bounds__(kT) void chan_affine_kernel( + const uint16_t* __restrict__ x, uint16_t* __restrict__ y, int64_t total, int n, int x_ld, + int inv, ChanLists l) { + const int64_t i = (int64_t)blockIdx.x * kT + threadIdx.x; + if (i >= total) return; + const int c = (int)(i % n); + const float v = bf2f(x[(size_t)(i / n) * x_ld + c]); + y[i] = f32_to_bf16(inv ? bfr(v - l.add[c]) / l.mul[c] : bfr(v * l.mul[c]) + l.add[c]); +} + +// A wave a pixel: the sum of squares over its channels, then the three roundings. +__global__ __launch_bounds__(kT) void l2norm_kernel( + const uint16_t* __restrict__ x, const uint16_t* __restrict__ g, uint16_t* __restrict__ y, + int64_t rows, int n, float sq, int silu) { + const int64_t r = (int64_t)blockIdx.x * (kT / 32) + (threadIdx.x >> 5); + const int lane = threadIdx.x & 31; + if (r >= rows) return; + const uint16_t* xr = x + (size_t)r * n; + float ss = 0.0f; + for (int c = lane * 8; c < n; c += 256) { + float f[8]; + ld8(xr + c, f); + #pragma unroll + for (int j = 0; j < 8; ++j) ss += f[j] * f[j]; + } + const float nrm = fmaxf(sqrtf(r4d_wave_sum(ss)), 1e-12f); + uint16_t* yr = y + (size_t)r * n; + for (int c = lane * 8; c < n; c += 256) { + float f[8], gg[8]; + ld8(xr + c, f); + ld8(g + c, gg); + #pragma unroll + for (int j = 0; j < 8; ++j) { + float v = bfr(bfr(bfr(f[j] / nrm) * sq) * gg[j]); + if (silu) v = v / (1.0f + expf(-v)); + f[j] = v; + } + st8(yr + c, f); + } +} + +// y[2r+i, 2c+j, o] += x[r, c, (o * F + off + 2i + j) / rep] +__global__ __launch_bounds__(kT) void d2s_add_kernel( + const uint16_t* __restrict__ x, uint16_t* __restrict__ y, int H, int W, int cin, int cout, + int F, int off, int rep) { + const int64_t total = (int64_t)4 * H * W * cout; + const int64_t t = (int64_t)blockIdx.x * kT + threadIdx.x; + if (t >= total) return; + const int o = (int)(t % cout); + const int64_t px = t / cout; + const int oy = (int)(px / (2 * W)), ox = (int)(px % (2 * W)); + const int ci = (o * F + off + 2 * (oy & 1) + (ox & 1)) / rep; + const float a = bf2f(x[((size_t)(oy >> 1) * W + (ox >> 1)) * cin + ci]); + y[t] = f32_to_bf16(bf2f(y[t]) + a); +} + +// y[r, c, o] += mean over the group of the dealt 2x2 block (a zero frame counted with ft 2) +__global__ __launch_bounds__(kT) void s2d_avg_add_kernel( + const uint16_t* __restrict__ x, uint16_t* __restrict__ y, int H, int W, int cin, int cout, + int F, int gs, int ft) { + const int64_t total = (int64_t)H * W * cout; + const int64_t t = (int64_t)blockIdx.x * kT + threadIdx.x; + if (t >= total) return; + const int o = (int)(t % cout); + const int64_t px = t / cout; + const int oy = (int)(px / W), ox = (int)(px % W); + float acc = 0.0f; + for (int gg = 0; gg < gs; ++gg) { + const int g = o * gs + gg; + const int c = g / F, rem = g % F, tt = rem / 4, i = (rem % 4) / 2, j = rem % 2; + if (ft == 2 && tt == 0) continue; + acc += bf2f(x[((size_t)(2 * oy + i) * (2 * W) + (2 * ox + j)) * cin + c]); + } + y[t] = f32_to_bf16(bf2f(y[t]) + bfr(acc / (float)gs)); +} + +__global__ __launch_bounds__(kT) void to_rgba8_kernel(const uint16_t* __restrict__ x, + uint8_t* __restrict__ y, int64_t total) { + const int64_t i = (int64_t)blockIdx.x * kT + threadIdx.x; + if (i >= total) return; + float v = fminf(fmaxf(bf2f(x[i]), -1.0f), 1.0f); + float u = bfr(bfr(v * 0.5f) + 0.5f); + u = fminf(fmaxf(u, 0.0f), 1.0f); + y[i] = (uint8_t)rintf(u * 255.0f); +} + +__global__ __launch_bounds__(kT) void gelu_tanh_kernel( + const uint16_t* __restrict__ x, uint16_t* __restrict__ y, int n, int x_ld, int y_ld) { + const int r = blockIdx.x; + for (int c = threadIdx.x * 8; c < n; c += kT * 8) { + float f[8]; + ld8(x + (size_t)r * x_ld + c, f); + #pragma unroll + for (int j = 0; j < 8; ++j) { + const float v = f[j]; + f[j] = 0.5f * v * (1.0f + tanhf(0.7978845608028654f * (v + 0.044715f * v * v * v))); + } + st8(y + (size_t)r * y_ld + c, f); + } +} + +// ---------------------------------------------------------------------------- conv2d_nhwc +// AN IMPLICIT GEMM: y[pixel][cout] = sum over (tap, cin) of x_virtual[pixel's tap][cin] * +// w[cout][tap][cin], the weight stored TAP-MAJOR (r4d_layout.cpp relayouts PyTorch's +// [cout][cin][k][k] at load) so K runs over taps and then channels and a 64-wide K tile of the +// image is eight 16-byte reads of NHWC rows -- the im2col never exists. +// +// The block is r4d_gemm_bf16_nt_tiled's: eight waves, an activation tile of BP pixels and a weight +// tile of BC output channels staged through LDS 64 K a time, the next tile's loads in flight under +// the current one's WMMA. The weight is the WMMA's A operand and the pixels its B, so a lane's +// accumulator is eight CONSECUTIVE output channels of one pixel and the store is 16 bytes. +// +// An input chunk of eight channels never straddles a tap because cin is a multiple of eight (the +// shim sends anything else to the direct kernel below); a chunk past the image, past K or past the +// last pixel is zeros. +// +// THE KERNEL SIZE AND THE UPSAMPLING ARE TEMPLATE PARAMETERS (KS, UP; 0 reads the argument). A tap +// index over a runtime k and a source row over a runtime `up` are two integer divisions per staged +// chunk -- four chunks a thread a K tile, ~500 integer instructions beside 48 WMMA a wave -- and at +// 3 and 2 they are a multiply-shift and a shift. The arithmetic is unchanged. +#define CV_BK 64 +#define CV_PITCH (CV_BK + 8) + +template +__global__ __launch_bounds__(256) void conv_igemm_kernel( + const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, + const uint16_t* __restrict__ bias, uint16_t* __restrict__ y, int Hv, int Wv, int cin, int Wo, + int cout, int k, int stride, int up, int pt, int x_ld, int y_ld, int Mpx, int K) { + constexpr int BP = 2 * TP * 16, BC = 4 * TC * 16; + constexpr int CPR = CV_BK / 8; + constexpr int AL = BP * CPR / 256, WL = BC * CPR / 256; + static_assert(AL >= 1 && WL >= 1, "every thread stages whole chunks"); + __shared__ __attribute__((aligned(16))) uint16_t sA[BP * CV_PITCH]; + __shared__ __attribute__((aligned(16))) uint16_t sW[BC * CV_PITCH]; + + const int tid = threadIdx.x, wave = tid >> 5, lane = tid & 31; + const int wp = wave / 4, wc = wave % 4; + const int p0 = blockIdx.x * BP, c0 = blockIdx.y * BC; + const int kq = KS ? KS : k, kk2 = kq * kq; + + int a_oy[AL], a_ox[AL], a_t[AL], a_ci[AL]; + bool a_ok[AL]; + uint16_t* adst[AL]; + #pragma unroll + for (int i = 0; i < AL; ++i) { + const int c = tid + 256 * i, r = c / CPR, e = (c % CPR) * 8; + const int m = p0 + r; + a_ok[i] = m < Mpx; + const int mm = a_ok[i] ? m : 0; + a_oy[i] = mm / Wo; + a_ox[i] = mm % Wo; + a_t[i] = e / cin; + a_ci[i] = e % cin; + adst[i] = sA + r * CV_PITCH + e; + } + size_t w_off[WL]; + int w_e[WL]; + bool w_ok[WL]; + uint16_t* wdst[WL]; + #pragma unroll + for (int i = 0; i < WL; ++i) { + const int c = tid + 256 * i, r = c / CPR, e = (c % CPR) * 8; + const int co = c0 + r; + w_ok[i] = co < cout; + w_off[i] = (size_t)(w_ok[i] ? co : 0) * K + e; + w_e[i] = e; + wdst[i] = sW + r * CV_PITCH + e; + } + const r4d_u32x4 zero = {0u, 0u, 0u, 0u}; + auto loadA = [&](int i) -> r4d_u32x4 { + if (!a_ok[i] || a_t[i] >= kk2) return zero; + const int kh = a_t[i] / kq, kw = a_t[i] - kh * kq; + const int iy = a_oy[i] * stride + kh - pt, ix = a_ox[i] * stride + kw - pt; + if (iy < 0 || iy >= Hv || ix < 0 || ix >= Wv) return zero; + /* Both are non-negative here, so a halving is a shift. */ + const int sy = UP == 1 ? iy : UP == 2 ? (iy >> 1) : iy / up; + const int sx = UP == 1 ? ix : UP == 2 ? (ix >> 1) : ix / up; + return *(const r4d_u32x4*)(x + (size_t)sy * x_ld + (size_t)sx * cin + a_ci[i]); + }; + auto loadW = [&](int i, int kt) -> r4d_u32x4 { + if (!w_ok[i] || kt * CV_BK + w_e[i] >= K) return zero; + return *(const r4d_u32x4*)(w + w_off[i] + (size_t)kt * CV_BK); + }; + + const uint16_t* fa = sA + (wp * TP * 16 + (lane & 15)) * CV_PITCH + 4 * (lane >> 4); + const uint16_t* fw = sW + (wc * TC * 16 + (lane & 15)) * CV_PITCH + 4 * (lane >> 4); + + v8f acc[TC][TP]; + #pragma unroll + for (int j = 0; j < TC; ++j) + #pragma unroll + for (int i = 0; i < TP; ++i) acc[j][i] = (v8f)(0.f); + + r4d_u32x4 ra[AL], rw[WL]; + #pragma unroll + for (int i = 0; i < AL; ++i) ra[i] = loadA(i); + #pragma unroll + for (int i = 0; i < WL; ++i) rw[i] = loadW(i, 0); + + const int nk = (K + CV_BK - 1) / CV_BK; + for (int kt = 0; kt < nk; ++kt) { + __syncthreads(); + #pragma unroll + for (int i = 0; i < AL; ++i) *(r4d_u32x4*)adst[i] = ra[i]; + #pragma unroll + for (int i = 0; i < WL; ++i) *(r4d_u32x4*)wdst[i] = rw[i]; + __syncthreads(); + if (kt + 1 < nk) { + #pragma unroll + for (int i = 0; i < AL; ++i) { + a_ci[i] += CV_BK; + while (a_ci[i] >= cin) { a_ci[i] -= cin; ++a_t[i]; } + ra[i] = loadA(i); + } + #pragma unroll + for (int i = 0; i < WL; ++i) rw[i] = loadW(i, kt + 1); + } + #pragma unroll + for (int s = 0; s < CV_BK / 16; ++s) { + v8bf af[TP], wf[TC]; + #pragma unroll + for (int i = 0; i < TP; ++i) af[i] = fragP(fa + i * 16 * CV_PITCH + s * 16); + #pragma unroll + for (int j = 0; j < TC; ++j) wf[j] = fragP(fw + j * 16 * CV_PITCH + s * 16); + #pragma unroll + for (int j = 0; j < TC; ++j) + #pragma unroll + for (int i = 0; i < TP; ++i) acc[j][i] = mma(wf[j], af[i], acc[j][i]); + } + } + + #pragma unroll + for (int j = 0; j < TC; ++j) + #pragma unroll + for (int i = 0; i < TP; ++i) { + const int px = p0 + (wp * TP + i) * 16 + (lane & 15); + const int co = c0 + (wc * TC + j) * 16 + 8 * (lane >> 4); + if (px >= Mpx || co >= cout) continue; + const int oy = px / Wo, ox = px % Wo; + uint16_t* dst = y + (size_t)oy * y_ld + (size_t)ox * cout + co; + if (co + 8 <= cout && (cout & 7) == 0) { + float f[8], b[8]; + ld8(bias + co, b); + #pragma unroll + for (int e = 0; e < 8; ++e) f[e] = acc[j][i][e] + b[e]; + st8(dst, f); + } else { + #pragma unroll + for (int e = 0; e < 8; ++e) + if (co + e < cout) dst[e] = f32_to_bf16(acc[j][i][e] + bf2f(bias[co + e])); + } + } +} + +// The direct form, for an input whose channel count is not a multiple of eight (an RGBA image +// into the first layer): a thread an output element, f32 over (tap, cin), the same tap-major +// weight. +__global__ __launch_bounds__(kT) void conv_direct_kernel( + const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, + const uint16_t* __restrict__ bias, uint16_t* __restrict__ y, int Hv, int Wv, int cin, int Wo, + int cout, int k, int stride, int up, int pt, int x_ld, int y_ld, int64_t total) { + const int64_t t = (int64_t)blockIdx.x * kT + threadIdx.x; + if (t >= total) return; + const int co = (int)(t % cout); + const int64_t px = t / cout; + const int oy = (int)(px / Wo), ox = (int)(px % Wo); + const int K = k * k * cin; + float acc = 0.0f; + for (int kh = 0; kh < k; ++kh) { + const int iy = oy * stride + kh - pt; + if (iy < 0 || iy >= Hv) continue; + for (int kw = 0; kw < k; ++kw) { + const int ix = ox * stride + kw - pt; + if (ix < 0 || ix >= Wv) continue; + const uint16_t* xp = x + (size_t)(iy / up) * x_ld + (size_t)(ix / up) * cin; + const uint16_t* wp = w + (size_t)co * K + (size_t)(kh * k + kw) * cin; + for (int ci = 0; ci < cin; ++ci) acc += bf2f(wp[ci]) * bf2f(xp[ci]); + } + } + y[(size_t)oy * y_ld + (size_t)ox * cout + co] = f32_to_bf16(acc + bf2f(bias[co])); +} + +inline int st_of(hipError_t e) { return e == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); } + +inline unsigned blocks_for(int64_t n) { return (unsigned)((n + kT - 1) / kT); } + +inline bool is_bf16(const RadTensor* t) { return t && t->dtype == RAD_BF16; } + +// A row-major operand's row count and pitch, with the pitch a multiple of eight elements so a row +// is read 16 bytes at a time. +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 dense [H, W * c] image operand. +inline bool image_of(const RadTensor* t, long long c, long long* H, long long* W) { + if (!t || t->rank != 2 || c <= 0 || t->shape[1] % c || t->stride[1] != 1 || + t->stride[0] != t->shape[1]) + return false; + *H = t->shape[0]; + *W = t->shape[1] / c; + return true; +} + +// A parameter list of floats, each rounded to bf16 as the reference's bf16 tensor of it. +int parse_bf16_list(const char* s, float* out, int max) { + int n = 0; + while (s && *s && n < max) { + char* end = nullptr; + const double v = std::strtod(s, &end); + if (end == s) break; + float f = (float)v; + uint32_t u; + std::memcpy(&u, &f, 4); + u = (u + 0x7FFFu + ((u >> 16) & 1u)) & 0xFFFF0000u; + std::memcpy(&f, &u, 4); + out[n++] = f; + s = end; + } + return n; +} + +} // namespace + +// ============================================================== the plugin ABI entry points + +extern "C" int r4d_rad_ln_mod(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *sc = r4d_opt(a, 1), *cu = r4d_opt(a, 2), *y = r4d_opt(a, 3); + if (!x || !sc || !cu || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(x) || !is_bf16(sc) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0); + long long rx = 0, xl = 0, rs = 0, sl = 0, ry = 0, yl = 0; + if (!rows8(x, n, &rx, &xl) || !rows8(y, n, &ry, &yl) || !r4d_contig(cu)) + return R4D_NO(RAD_E_STRIDE); + sl = r4d_rows_pitch(sc, n, &rs); + if (sl < 0 || (sl & 7) || ((uintptr_t)sc->data & 15)) return R4D_NO(RAD_E_STRIDE); + const long long n_seq = r4d_numel(cu) - 1; + if (ry <= 0 || rx < ry || n_seq <= 0 || rs < n_seq) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(ln_mod_kernel, dim3((unsigned)ry), dim3(kT), 0, (hipStream_t)s, + (const uint16_t*)x->data, (const uint16_t*)sc->data, (const int*)cu->data, + (uint16_t*)y->data, (int)n, (int)n_seq, (float)r4d_getf(a, "eps", 1e-6), + (int)xl, (int)sl, (int)yl); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_ln_mod_quant_fp8(const RadArgs* a, RadStream s) { + const RadTensor *y = r4d_opt(a, 0), *g = r4d_opt(a, 1), *sc = r4d_opt(a, 2); + const RadTensor *cu = r4d_opt(a, 3), *x = r4d_opt(a, 4), *q = r4d_opt(a, 5); + const RadTensor *qs = r4d_opt(a, 6), *z = r4d_opt(a, 7); + if (!sc || !cu || !x || !q || !qs) return R4D_NO(RAD_E_INVAL); + const bool gated = r4d_geti_or(a, "gated", 0) != 0; + if (gated && (!y || !g)) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(x) || !is_bf16(sc) || (gated && (!is_bf16(y) || !is_bf16(g))) || + (z && !is_bf16(z)) || q->dtype != RAD_F8E4M3 || qs->dtype != RAD_F32) + return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0); + if (n <= 0 || n % 128 || r4d_geti_or(a, "group", 0) != 128 || + n > (long long)kT * 8 * kLnqChunks) + return R4D_NO(RAD_E_SHAPE); + long long rx = 0, xl = 0, ry = 0, yl = 0, rg = 0, gl = 0, rs = 0, sl = 0, rz = 0, zl = 0; + long long rq = 0, rqs = 0; + if (!rows8(x, n, &rx, &xl) || !rows8(sc, n, &rs, &sl) || !r4d_contig(cu) || + (gated && (!rows8(y, n, &ry, &yl) || !rows8(g, n, &rg, &gl))) || + (z && !rows8(z, n, &rz, &zl))) + return R4D_NO(RAD_E_STRIDE); + const long long ql = r4d_rows_pitch(q, n, &rq), qsl = r4d_rows_pitch(qs, n / 128, &rqs); + if (ql < 0 || (ql & 7) || ((uintptr_t)q->data & 7) || qsl < 0) return R4D_NO(RAD_E_STRIDE); + const long long n_seq = r4d_numel(cu) - 1, rows = rq; + if (rows <= 0 || n_seq <= 0 || rx < rows || rqs < rows || rs < n_seq || + (gated && (ry < rows || rg < n_seq)) || (z && rz < rows)) + return R4D_NO(RAD_E_SHAPE); + const float eps = (float)r4d_getf(a, "eps", 1e-6); +#define R4D_LNQ(G) \ + hipLaunchKernelGGL(ln_mod_quant_kernel, dim3((unsigned)rows), dim3(kT), 0, (hipStream_t)s, \ + G ? (const uint16_t*)y->data : nullptr, \ + G ? (const uint16_t*)g->data : nullptr, (const uint16_t*)sc->data, \ + (const int*)cu->data, (uint16_t*)x->data, (uint8_t*)q->data, \ + (float*)qs->data, z ? (uint16_t*)z->data : nullptr, (int)n, (int)n_seq, \ + eps, (int)yl, (int)gl, (int)sl, (int)xl, (int)ql, (int)qsl, (int)zl) + if (gated) R4D_LNQ(true); + else R4D_LNQ(false); +#undef R4D_LNQ + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_gate_add(const RadArgs* a, RadStream s) { + const RadTensor *y = r4d_opt(a, 0), *g = r4d_opt(a, 1), *cu = r4d_opt(a, 2), *x = r4d_opt(a, 3); + if (!y || !g || !cu || !x) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(x) || !is_bf16(g) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0); + long long ry = 0, yl = 0, rx = 0, xl = 0, rg = 0; + if (!rows8(y, n, &ry, &yl) || !rows8(x, n, &rx, &xl) || !r4d_contig(cu)) + return R4D_NO(RAD_E_STRIDE); + const long long gl = r4d_rows_pitch(g, n, &rg); + if (gl < 0 || (gl & 7) || ((uintptr_t)g->data & 15)) return R4D_NO(RAD_E_STRIDE); + const long long n_seq = r4d_numel(cu) - 1; + if (ry <= 0 || rx < ry || n_seq <= 0 || rg < n_seq) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(gate_add_kernel, dim3((unsigned)ry), dim3(kT), 0, (hipStream_t)s, + (const uint16_t*)y->data, (const uint16_t*)g->data, (const int*)cu->data, + (uint16_t*)x->data, (int)n, (int)n_seq, (int)yl, (int)gl, (int)xl); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_timestep_embed(const RadArgs* a, RadStream s) { + const RadTensor *t = r4d_opt(a, 0), *y = r4d_opt(a, 1); + if (!t || !y) return R4D_NO(RAD_E_INVAL); + if (t->dtype != RAD_F32 || !r4d_contig(t) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0); + if (n <= 0 || (n & 1)) return R4D_NO(RAD_E_SHAPE); + long long ry = 0; + const long long yl = r4d_rows_pitch(y, n, &ry); + if (yl < 0) return R4D_NO(RAD_E_STRIDE); + if (ry <= 0 || r4d_numel(t) < ry) return R4D_NO(RAD_E_SHAPE); + const float mp = (float)r4d_getf(a, "max_period", 10000.0); + const float coef = (float)(-std::log((double)mp)); + hipLaunchKernelGGL(timestep_kernel, dim3((unsigned)ry), dim3(kT), 0, (hipStream_t)s, + (const float*)t->data, (uint16_t*)y->data, (int)(n / 2), + (float)r4d_getf(a, "scale", 1000.0), coef, + (int)r4d_geti_or(a, "round", 0), (int)yl); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_gather_rows2(const RadArgs* a, RadStream s) { + const RadTensor *A = r4d_opt(a, 0), *B = r4d_opt(a, 1), *idx = r4d_opt(a, 2), *y = r4d_opt(a, 3); + if (!A || !B || !idx || !y) return R4D_NO(RAD_E_INVAL); + if (A->dtype != y->dtype || B->dtype != y->dtype || rad_dtype_bytes(y->dtype, 1) != 2 || + idx->dtype != RAD_I32) + return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0); + long long ra = 0, al = 0, rb = 0, bl = 0, ry = 0, yl = 0; + if (!rows8(A, n, &ra, &al) || !rows8(B, n, &rb, &bl) || !rows8(y, n, &ry, &yl) || + !r4d_contig(idx)) + return R4D_NO(RAD_E_STRIDE); + if (ry <= 0 || r4d_numel(idx) < ry) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(gather2_kernel, dim3((unsigned)ry), dim3(kT), 0, (hipStream_t)s, + (const uint16_t*)A->data, (const uint16_t*)B->data, (const int*)idx->data, + (uint16_t*)y->data, (int)n, (int)ra, (int)rb, (int)al, (int)bl, (int)yl); + return st_of(hipGetLastError()); +} + +// A lane operand's row in 32-bit words, and its pitch in words. +static bool lane_rows(const RadTensor* t, long long n, long long* rows, long long* ldw, + long long* words) { + if (!t || n <= 0) return false; + const long long eb = rad_dtype_bytes(t->dtype, 1); + if (eb <= 0 || (n * eb) % 4) return false; + const long long ld = r4d_rows_pitch(t, n, rows); + if (ld < 0 || (ld * eb) % 4 || ((uintptr_t)t->data & 3)) return false; + *ldw = ld * eb / 4; + *words = n * eb / 4; + return true; +} + +extern "C" int r4d_rad_lane_gather(const RadArgs* a, RadStream s) { + const RadTensor *src = r4d_opt(a, 0), *lane = r4d_opt(a, 1), *cu = r4d_opt(a, 2), *y = r4d_opt(a, 3); + if (!src || !lane || !cu || !y) return R4D_NO(RAD_E_INVAL); + if (src->dtype != y->dtype) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0), stride = r4d_geti_or(a, "stride", 0); + long long rs = 0, sw = 0, ry = 0, yw = 0, words = 0; + if (!lane_rows(src, n, &rs, &sw, &words) || !lane_rows(y, n, &ry, &yw, &words) || + !r4d_contig(lane) || !r4d_contig(cu)) + return R4D_NO(RAD_E_STRIDE); + const long long n_seq = r4d_numel(cu) - 1; + if (stride <= 0 || n_seq <= 0 || r4d_numel(lane) < n_seq || ry <= 0) return R4D_NO(RAD_E_SHAPE); + /* Every row from cu[0] up is an entry's, and the operand holds them all. */ + const long long total = ry * words; + hipLaunchKernelGGL(lane_gather_kernel, dim3(blocks_for(total)), dim3(kT), 0, (hipStream_t)s, + (const uint32_t*)src->data, (const int*)lane->data, (const int*)cu->data, + (uint32_t*)y->data, (int)words, (int)n_seq, (int)stride, (int)sw, (int)yw, + (int64_t)total); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_lane_store(const RadArgs* a, RadStream s) { + const RadTensor *src = r4d_opt(a, 0), *lane = r4d_opt(a, 1), *dst = r4d_opt(a, 2); + if (!src || !lane || !dst) return R4D_NO(RAD_E_INVAL); + if (src->dtype != dst->dtype) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0), stride = r4d_geti_or(a, "stride", 0); + long long rs = 0, sw = 0, rd = 0, dw = 0, words = 0; + if (!lane_rows(src, n, &rs, &sw, &words) || !lane_rows(dst, n, &rd, &dw, &words) || + !r4d_contig(lane)) + return R4D_NO(RAD_E_STRIDE); + const long long nl = r4d_numel(lane); + if (rs <= 0 || rs > stride || nl <= 0) return R4D_NO(RAD_E_SHAPE); + const long long total = rs * words; + hipLaunchKernelGGL(lane_store_kernel, dim3(blocks_for(total), (unsigned)nl), dim3(kT), 0, + (hipStream_t)s, (const uint32_t*)src->data, (const int*)lane->data, + (uint32_t*)dst->data, (int)words, (int)stride, (int)sw, (int)dw, + (int64_t)total); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_randn_lanes(const RadArgs* a, RadStream s) { + const RadTensor *fl = r4d_opt(a, 0), *seed = r4d_opt(a, 1), *lane = r4d_opt(a, 2); + const RadTensor *cu = r4d_opt(a, 3), *dst = r4d_opt(a, 4); + if (!fl || !seed || !lane || !cu || !dst) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(dst)) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0), stride = r4d_geti_or(a, "stride", 0); + long long rd = 0; + const long long dl = r4d_rows_pitch(dst, n, &rd); + if (dl < 0) return R4D_NO(RAD_E_STRIDE); + const long long n_seq = r4d_numel(cu) - 1; + if (n <= 0 || stride <= 0 || n_seq <= 0) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(randn_lanes_kernel, dim3(blocks_for(stride * n), (unsigned)n_seq), dim3(kT), + 0, (hipStream_t)s, (const int*)fl->data, (const uint32_t*)seed->data, + (const int*)lane->data, (const int*)cu->data, (uint16_t*)dst->data, (int)n, + (int)stride, (int)dl); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_flow_euler(const RadArgs* a, RadStream s) { + const RadTensor *v = r4d_opt(a, 0), *sg = r4d_opt(a, 1), *sgn = r4d_opt(a, 2), *cfg = r4d_opt(a, 3); + const RadTensor *pair = r4d_opt(a, 4), *lane = r4d_opt(a, 5), *fl = r4d_opt(a, 6); + const RadTensor *seed = r4d_opt(a, 7), *cu = r4d_opt(a, 8), *inp = r4d_opt(a, 9); + const RadTensor *mask = r4d_opt(a, 10), *st = r4d_opt(a, 11), *pv = r4d_opt(a, 12); + if (!v || !sg || !sgn || !cfg || !pair || !lane || !fl || !seed || !cu || !st) + return R4D_NO(RAD_E_INVAL); + if (!is_bf16(v) || !is_bf16(st) || (pv && !is_bf16(pv)) || (inp && !is_bf16(inp)) || + (mask && mask->dtype != RAD_F32)) + return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0), stride = r4d_geti_or(a, "stride", 0); + long long rv = 0, rst = 0, rp = 0, ri = 0; + const long long vl = r4d_rows_pitch(v, n, &rv), sl = r4d_rows_pitch(st, n, &rst); + const long long pl = pv ? r4d_rows_pitch(pv, n, &rp) : 0; + const long long il = inp ? r4d_rows_pitch(inp, n, &ri) : 0; + if (vl < 0 || sl < 0 || pl < 0 || il < 0) return R4D_NO(RAD_E_STRIDE); + const long long n_seq = r4d_numel(cu) - 1; + if (n <= 0 || stride <= 0 || n_seq <= 0) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(flow_euler_kernel, dim3(blocks_for(stride * n), (unsigned)n_seq), dim3(kT), 0, + (hipStream_t)s, (const uint16_t*)v->data, (const float*)sg->data, + (const float*)sgn->data, (const float*)cfg->data, (const int*)pair->data, + (const int*)lane->data, (const int*)fl->data, (const uint32_t*)seed->data, + (const int*)cu->data, inp ? (const uint16_t*)inp->data : nullptr, + mask ? (const float*)mask->data : nullptr, (uint16_t*)st->data, + pv ? (uint16_t*)pv->data : nullptr, (int)n, (int)stride, (int)vl, (int)il, + (int)sl, (int)pl); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_chan_affine(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1); + if (!x || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(x) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0); + long long rx = 0; + const long long xl = n > 0 ? r4d_rows_pitch(x, n, &rx) : -1; + if (xl < 0 || !r4d_contig(y)) return R4D_NO(RAD_E_STRIDE); + ChanLists l{}; + if (n <= 0 || n > kChanMax || parse_bf16_list(r4d_gets(a, "mul"), l.mul, kChanMax) != n || + parse_bf16_list(r4d_gets(a, "add"), l.add, kChanMax) != n) + return R4D_NO(RAD_E_SHAPE); + const char* mode = r4d_gets(a, "mode"); + const int inv = mode && !std::strcmp(mode, "inv"); + if (!inv && mode && std::strcmp(mode, "fma")) return R4D_NO(RAD_E_INVAL); + const long long total = r4d_numel(y); + if (total <= 0 || total % n || rx * n < total) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(chan_affine_kernel, dim3(blocks_for(total)), dim3(kT), 0, (hipStream_t)s, + (const uint16_t*)x->data, (uint16_t*)y->data, (int64_t)total, (int)n, + (int)xl, inv, l); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_conv2d_nhwc(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *w = r4d_opt(a, 1), *b = r4d_opt(a, 2), *y = r4d_opt(a, 3); + if (!x || !w || !b || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(x) || !is_bf16(w) || !is_bf16(b) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE); + const long long cin = r4d_geti_or(a, "cin", 0), cout = r4d_geti_or(a, "cout", 0); + const long long k = r4d_geti_or(a, "k", 0), stride = r4d_geti_or(a, "stride", 1); + const long long up = r4d_geti_or(a, "up", 1); + const char* pad = r4d_gets(a, "pad"); + const bool down = pad && !std::strcmp(pad, "down"); + if (pad && !down && std::strcmp(pad, "same")) return R4D_NO(RAD_E_INVAL); + if (cin <= 0 || cout <= 0 || k <= 0 || stride <= 0 || up <= 0) return R4D_NO(RAD_E_SHAPE); + long long Hin = 0, Win = 0, Ho = 0, Wo = 0; + if (!image_of(x, cin, &Hin, &Win) || !image_of(y, cout, &Ho, &Wo)) return R4D_NO(RAD_E_SHAPE); + const long long Hv = Hin * up, Wv = Win * up; + const long long pt = down ? 0 : k / 2, pb = down ? 1 : k / 2; + if ((Hv + pt + pb - k) / stride + 1 != Ho || (Wv + pt + pb - k) / stride + 1 != Wo) + return R4D_NO(RAD_E_SHAPE); + const long long K = k * k * cin; + if (r4d_numel(w) < cout * K || r4d_numel(b) < cout) return R4D_NO(RAD_E_SHAPE); + const long long Mpx = Ho * Wo; + if (Mpx <= 0 || Mpx >= (1ll << 31) || (long long)Ho * Wo * cout >= (1ll << 40)) + return R4D_NO(RAD_E_SHAPE); + hipStream_t st = (hipStream_t)s; + if (cin % 8 || ((uintptr_t)x->data & 15) || ((uintptr_t)w->data & 15)) { + const long long total = Mpx * cout; + hipLaunchKernelGGL(conv_direct_kernel, dim3(blocks_for(total)), dim3(kT), 0, st, + (const uint16_t*)x->data, (const uint16_t*)w->data, + (const uint16_t*)b->data, (uint16_t*)y->data, (int)Hv, (int)Wv, + (int)cin, (int)Wo, (int)cout, (int)k, (int)stride, (int)up, (int)pt, + (int)x->stride[0], (int)y->stride[0], (int64_t)total); + return st_of(hipGetLastError()); + } + // 128 pixels a block, and the widest channel tile -- 192, 128, then 64 -- that leaves under a + // third of its last block idle. A wider tile does twice or three times the WMMA a K step for + // the same two barriers, and that pays even with the last block partly empty: on Qwen-Image's + // decoder the 192 tile against the 64 one is 144 channels 39.7 -> 26.3 ms, 288 125.9 -> 95.2 + // (an upsampling layer), 576 109.9 -> 70.8, the same bytes out. 96 channels take 128. + auto fits = [cout](long long bc) { + const long long padded = (cout + bc - 1) / bc * bc; + return (padded - cout) * 3 < padded; + }; +#define R4D_CONV(TP, TC, KS, UP) \ + hipLaunchKernelGGL((conv_igemm_kernel), \ + dim3((unsigned)((Mpx + 2 * TP * 16 - 1) / (2 * TP * 16)), \ + (unsigned)((cout + 4 * TC * 16 - 1) / (4 * TC * 16))), \ + dim3(256), 0, st, (const uint16_t*)x->data, (const uint16_t*)w->data, \ + (const uint16_t*)b->data, (uint16_t*)y->data, (int)Hv, (int)Wv, (int)cin, \ + (int)Wo, (int)cout, (int)k, (int)stride, (int)up, (int)pt, \ + (int)x->stride[0], (int)y->stride[0], (int)Mpx, (int)K) + /* The decoder's two kernel sizes at its two sampling rates, and the generic form for the rest. */ +#define R4D_CONV_K(TP, TC) \ + if (k == 3 && up == 1) R4D_CONV(TP, TC, 3, 1); \ + else if (k == 3 && up == 2) R4D_CONV(TP, TC, 3, 2); \ + else if (k == 1 && up == 1) R4D_CONV(TP, TC, 1, 1); \ + else R4D_CONV(TP, TC, 0, 0) + if (fits(192)) { R4D_CONV_K(4, 3); } + else if (fits(128)) { R4D_CONV_K(4, 2); } + else { R4D_CONV_K(4, 1); } +#undef R4D_CONV_K +#undef R4D_CONV + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_l2norm_chan(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *g = r4d_opt(a, 1), *y = r4d_opt(a, 2); + if (!x || !g || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(x) || !is_bf16(g) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0); + const char* act = r4d_gets(a, "act"); + const int silu = act && !std::strcmp(act, "silu"); + if (!silu && act && std::strcmp(act, "none")) return R4D_NO(RAD_E_INVAL); + if (n <= 0 || (n & 7) || r4d_numel(g) < n) return R4D_NO(RAD_E_SHAPE); + if (!r4d_contig(x) || !r4d_contig(y) || ((uintptr_t)x->data & 15) || ((uintptr_t)y->data & 15) || + ((uintptr_t)g->data & 15)) + return R4D_NO(RAD_E_STRIDE); + const long long rows = r4d_numel(y) / n; + if (rows <= 0 || r4d_numel(x) < rows * n) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(l2norm_kernel, dim3((unsigned)((rows + kT / 32 - 1) / (kT / 32))), dim3(kT), + 0, (hipStream_t)s, (const uint16_t*)x->data, (const uint16_t*)g->data, + (uint16_t*)y->data, (int64_t)rows, (int)n, + (float)std::sqrt((double)n), silu); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_d2s_add(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1); + if (!x || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(x) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE); + const long long cin = r4d_geti_or(a, "cin", 0), cout = r4d_geti_or(a, "cout", 0); + const long long ft = r4d_geti_or(a, "ft", 1); + long long H = 0, W = 0, H2 = 0, W2 = 0; + if ((ft != 1 && ft != 2) || !image_of(x, cin, &H, &W) || !image_of(y, cout, &H2, &W2) || + H2 != 2 * H || W2 != 2 * W) + return R4D_NO(RAD_E_SHAPE); + const long long F = 4 * ft; + if ((cout * F) % cin) return R4D_NO(RAD_E_SHAPE); + const long long total = 4 * H * W * cout; + hipLaunchKernelGGL(d2s_add_kernel, dim3(blocks_for(total)), dim3(kT), 0, (hipStream_t)s, + (const uint16_t*)x->data, (uint16_t*)y->data, (int)H, (int)W, (int)cin, + (int)cout, (int)F, ft == 2 ? 4 : 0, (int)(cout * F / cin)); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_s2d_avg_add(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1); + if (!x || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(x) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE); + const long long cin = r4d_geti_or(a, "cin", 0), cout = r4d_geti_or(a, "cout", 0); + const long long ft = r4d_geti_or(a, "ft", 1); + long long H = 0, W = 0, H2 = 0, W2 = 0; + if ((ft != 1 && ft != 2) || !image_of(y, cout, &H, &W) || !image_of(x, cin, &H2, &W2) || + H2 != 2 * H || W2 != 2 * W) + return R4D_NO(RAD_E_SHAPE); + const long long F = 4 * ft; + if ((cin * F) % cout) return R4D_NO(RAD_E_SHAPE); + const long long total = H * W * cout; + hipLaunchKernelGGL(s2d_avg_add_kernel, dim3(blocks_for(total)), dim3(kT), 0, (hipStream_t)s, + (const uint16_t*)x->data, (uint16_t*)y->data, (int)H, (int)W, (int)cin, + (int)cout, (int)F, (int)(cin * F / cout), (int)ft); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_to_rgba8(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1); + if (!x || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(x) || y->dtype != RAD_U8) return R4D_NO(RAD_E_DTYPE); + if (!r4d_contig(x) || !r4d_contig(y)) return R4D_NO(RAD_E_STRIDE); + const long long total = r4d_numel(y); + if (total <= 0 || r4d_numel(x) < total) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(to_rgba8_kernel, dim3(blocks_for(total)), dim3(kT), 0, (hipStream_t)s, + (const uint16_t*)x->data, (uint8_t*)y->data, (int64_t)total); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_gelu_tanh(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1); + if (!x || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(x) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0); + long long rx = 0, xl = 0, ry = 0, yl = 0; + if (!rows8(x, n, &rx, &xl) || !rows8(y, n, &ry, &yl)) return R4D_NO(RAD_E_STRIDE); + if (ry <= 0 || rx < ry) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(gelu_tanh_kernel, dim3((unsigned)ry), dim3(kT), 0, (hipStream_t)s, + (const uint16_t*)x->data, (uint16_t*)y->data, (int)n, (int)xl, (int)yl); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_scatter_add_rows(const RadArgs* a, RadStream s) { + const RadTensor *v = r4d_opt(a, 0), *idx = r4d_opt(a, 1), *x = r4d_opt(a, 2); + if (!v || !idx || !x) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(v) || !is_bf16(x) || idx->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0); + long long rv = 0, vl = 0, rx = 0, xl = 0; + if (!rows8(v, n, &rv, &vl) || !rows8(x, n, &rx, &xl) || !r4d_contig(idx)) + return R4D_NO(RAD_E_STRIDE); + if (rv <= 0 || r4d_numel(idx) < rv) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(scatter_add_kernel, dim3((unsigned)rv), dim3(kT), 0, (hipStream_t)s, + (const uint16_t*)v->data, (const int*)idx->data, (uint16_t*)x->data, (int)n, + (int)vl, (int)xl); + return st_of(hipGetLastError()); +} diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index f77b7a47..30e0cebc 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -1232,3 +1232,80 @@ extern "C" int r4d_rad_layout_moe_fp8_mod4(const RadParam* p, int n_p, int opera return rc != RAD_OK ? rc : r4d_rad_layout_fp8_rowmajor(v.p, v.n, v.operand, enc, sel, pl, n, out); } + +/* ---- conv2d_nhwc: PyTorch's [cout][cin][k][k] stored TAP-MAJOR, [cout][k][k][cin]. + * + * The implicit-GEMM convolution (r4d_gen.hip) contracts over K = (tap, channel) with the channel + * innermost, so that eight consecutive K are eight channels of one input pixel -- one 16-byte read + * of an NHWC row. The weight's K has to run the same way, and PyTorch's runs channel-major. A + * permutation of a bf16 plane, so the inverse is the same loop backwards. Operand 1 of + * conv2d_nhwc; the bias is read as it is. */ +namespace { +constexpr int CONV_W_OPERAND = 1; + +int conv_geom(const RadParam* p, int n_p, const RadTensor* pl, int n, long long* cout, + long long* cin, long long* k) { + *cout = r4d_pgeti_or(p, n_p, "cout", 0); + *cin = r4d_pgeti_or(p, n_p, "cin", 0); + *k = r4d_pgeti_or(p, n_p, "k", 0); + if (n != 1 || !pl || *cout <= 0 || *cin <= 0 || *k <= 0) return RAD_E_SHAPE; + if (pl[0].dtype != RAD_BF16 || pl[0].rank != 2 || + pl[0].shape[0] * pl[0].shape[1] != *cout * *cin * *k * *k) + return RAD_E_SHAPE; + return RAD_OK; +} +} /* namespace */ + +extern "C" int r4d_rad_layout_conv_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, k; + const int rc = conv_geom(p, n_p, pl, n, &co, &ci, &k); + if (rc != RAD_OK) return rc; + fill(out, "r4d.conv.tap_major", RAD_BF16, co, k * k * ci, co * k * k * ci * 2); + return RAD_OK; +} + +extern "C" int r4d_rad_relayout_conv_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_conv_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, k; + conv_geom(p, n_p, pl, n, &co, &ci, &k); + const uint16_t* s = (const uint16_t*)pl[0].data; + uint16_t* d = (uint16_t*)dst; + const long long kk = k * k; + for (long long o = 0; o < co; ++o) + for (long long c = 0; c < ci; ++c) + for (long long t = 0; t < kk; ++t) + d[(o * kk + t) * ci + c] = s[(o * ci + c) * kk + t]; + return RAD_OK; +} + +extern "C" int r4d_rad_unrelayout_conv_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_conv_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, k; + conv_geom(p, n_p, pl, n, &co, &ci, &k); + const uint16_t* s = (const uint16_t*)src; + uint16_t* d = (uint16_t*)pl[0].data; + const long long kk = k * k; + for (long long o = 0; o < co; ++o) + for (long long c = 0; c < ci; ++c) + for (long long t = 0; t < kk; ++t) + d[(o * ci + c) * kk + t] = s[(o * kk + t) * ci + c]; + return RAD_OK; +} diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 9c4503af..1b410c23 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -138,6 +138,30 @@ int r4d_rad_join_add_scale_bf16 (const RadArgs*, RadStream); int r4d_rad_expert_scale_bf16 (const RadArgs*, RadStream); int r4d_rad_attn_vit (const RadArgs*, RadStream); int r4d_rad_attn_dense (const RadArgs*, RadStream); +/* The image generator's attention (r4d_attn_gen.hip): a paged prefix and the pass's own rows, the + * causal-capable dense form at head_dim 128 (a text encoder's prompt), and one 1152-wide head + * (an image decoder's mid block). */ +int r4d_rad_attn_prefix_self (const RadArgs*, RadStream); +int r4d_rad_attn_dense_h128 (const RadArgs*, RadStream); +int r4d_rad_attn_dense_wide (const RadArgs*, RadStream); +/* The image generator's other ops (r4d_gen.hip). */ +int r4d_rad_ln_mod (const RadArgs*, RadStream); +int r4d_rad_ln_mod_quant_fp8 (const RadArgs*, RadStream); +int r4d_rad_gate_add (const RadArgs*, RadStream); +int r4d_rad_timestep_embed (const RadArgs*, RadStream); +int r4d_rad_gather_rows2 (const RadArgs*, RadStream); +int r4d_rad_lane_gather (const RadArgs*, RadStream); +int r4d_rad_lane_store (const RadArgs*, RadStream); +int r4d_rad_randn_lanes (const RadArgs*, RadStream); +int r4d_rad_flow_euler (const RadArgs*, RadStream); +int r4d_rad_chan_affine (const RadArgs*, RadStream); +int r4d_rad_conv2d_nhwc (const RadArgs*, RadStream); +int r4d_rad_l2norm_chan (const RadArgs*, RadStream); +int r4d_rad_d2s_add (const RadArgs*, RadStream); +int r4d_rad_s2d_avg_add (const RadArgs*, RadStream); +int r4d_rad_to_rgba8 (const RadArgs*, RadStream); +int r4d_rad_gelu_tanh (const RadArgs*, RadStream); +int r4d_rad_scatter_add_rows (const RadArgs*, RadStream); /* Eight queries per KV head (r4d_attn_paged_gqa8.hip): the routed 35B-A3B at head_dim 256 * and MiniCPM5-2B at 128. A decode workgroup holds 64 rows of q_len*gqa, so the verify * width is 8 here against the gqa6 leg's 10 -- which is the row's constraint value. */ @@ -460,6 +484,14 @@ int r4d_rad_layout_gdense(const RadParam*, int, int, const RadEncoding*, const i const RadTensor*, int, RadLayout*); int r4d_rad_relayout_gdense(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, void*, int64_t); +/* conv2d_nhwc's weight, PyTorch's [cout][cin][k][k] stored tap-major [cout][k][k][cin] + * (r4d_layout.cpp). */ +int r4d_rad_layout_conv_tap(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, RadLayout*); +int r4d_rad_relayout_conv_tap(const RadParam*, int, int, const RadEncoding*, const int*, + 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); int r4d_rad_layout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, RadLayout*); int r4d_rad_relayout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*, diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 10d97add..c80af39e 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -660,6 +660,10 @@ static const RadParamSpec pAllReduce[] = { * plugin reads it, because the message size picks the two-shot (the all-reduce constraints * below). */ { "hops", RAD_P_INT, RAD_OPTIONAL }, + /* 1 when the caller issues this collective on its second lane, beside compute (rad_lane). It + * picks the rows whose launch is narrow -- see tArLane -- and changes nothing the kernel + * computes. */ + { "overlap", RAD_P_INT, RAD_OPTIONAL }, }; /* docs/OPS.md has `x` -> `x` (inout). Every kernel here is safe in place -- the thread that * overwrites a word of the input is the one that read it (r4d_ar_entry.hip says so per kernel) -- @@ -2186,6 +2190,82 @@ static const RadOperandSpec oExpertScale[] = { #define SCHEMA(op, p, o, doc) { (op), ROW(p), ROW(o), (doc) } +/* ---- image generation (r4d_gen.hip, r4d_attn_gen.hip) ------------------------------------- + * ref's spellings (libref/ref_registry.cpp), field for field: the first plugin to declare an op + * fixes its schema and the second is refused if it disagrees. */ +static const RadParamSpec pGenMn[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; +static const RadParamSpec pLnMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype") }; +static const RadOperandSpec oLnMod[] = { + { "x", RAD_OPD_IN, 0 }, { "s", RAD_OPD_IN, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pLnModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"), + P_INT("gated"), P_STR("dtype") }; +static const RadOperandSpec oLnModQ[] = { + { "y", RAD_OPD_IN, 1 }, { "g", RAD_OPD_IN, 1 }, { "s", RAD_OPD_IN, 0 }, + { "cu_seqlens", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 }, { "q", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 }, { "z", RAD_OPD_OUT, 1 }, +}; +static const RadOperandSpec oGateAdd[] = { + { "y", RAD_OPD_IN, 0 }, { "g", RAD_OPD_IN, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 }, + { "x", RAD_OPD_INOUT, 0 }, +}; +static const RadParamSpec pTimestep[] = { P_INT("M"), P_INT("n"), P_F64("scale"), + P_F64("max_period"), P_INTO("round"), P_STR("dtype") }; +static const RadOperandSpec oTimestep[] = { { "t", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } }; +static const RadOperandSpec oGather2[] = { + { "a", RAD_OPD_IN, 0 }, { "b", RAD_OPD_IN, 0 }, { "idx", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pLane[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_STR("dtype") }; +static const RadOperandSpec oLaneGather[] = { + { "src", RAD_OPD_IN, 0 }, { "lane", RAD_OPD_IN, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; +static const RadOperandSpec oLaneStore[] = { + { "src", RAD_OPD_IN, 0 }, { "lane", RAD_OPD_IN, 0 }, { "dst", RAD_OPD_INOUT, 0 }, +}; +static const RadOperandSpec oRandnLanes[] = { + { "flags", RAD_OPD_IN, 0 }, { "seed", RAD_OPD_IN, 0 }, { "lane", RAD_OPD_IN, 0 }, + { "cu_seqlens", RAD_OPD_IN, 0 }, { "dst", RAD_OPD_INOUT, 0 }, +}; +static const RadOperandSpec oFlowEuler[] = { + { "v", RAD_OPD_IN, 0 }, { "sigma", RAD_OPD_IN, 0 }, { "sigma_next", RAD_OPD_IN, 0 }, + { "cfg", RAD_OPD_IN, 0 }, { "pair", RAD_OPD_IN, 0 }, { "lane", RAD_OPD_IN, 0 }, + { "flags", RAD_OPD_IN, 0 }, { "seed", RAD_OPD_IN, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 }, + { "inp_lat", RAD_OPD_IN, 1 }, { "inp_mask", RAD_OPD_IN, 1 }, { "state", RAD_OPD_INOUT, 0 }, + { "preview", RAD_OPD_INOUT, 1 }, +}; +static const RadParamSpec pChanAffine[] = { P_INT("M"), P_INT("n"), P_STR("mul"), P_STR("add"), + P_STR("mode"), P_STR("dtype") }; +static const RadOperandSpec oGenUnary[] = { { "x", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pConvNhwc[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"), + P_INT("stride"), P_STR("pad"), P_INT("up"), + P_STR("dtype") }; +static const RadOperandSpec oConvNhwc[] = { + { "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "b", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pL2Norm[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") }; +static const RadOperandSpec oL2Norm[] = { + { "x", RAD_OPD_IN, 0 }, { "gamma", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pSpaceDepth[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("ft"), + P_STR("dtype") }; +static const RadOperandSpec oSpaceDepth[] = { { "x", RAD_OPD_IN, 0 }, { "y", RAD_OPD_INOUT, 0 } }; +static const RadOperandSpec oScatterAdd[] = { + { "v", RAD_OPD_IN, 0 }, { "idx", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 }, +}; +static const RadParamSpec pAttnPS[] = { P_INT("q_len"), P_INT("head_dim"), P_INT("gqa"), + P_INTD("block_size"), P_INT("causal"), P_STR("q_dtype"), + P_STR("kv_dtype"), P_F64O("scale"), P_INTO("max_ctx"), + P_INTO("n_head"), P_INTO("max_seqs"), P_STRO("qk") }; +static const RadOperandSpec oAttnPS[] = { + { "q", RAD_OPD_IN, 0 }, { "k", RAD_OPD_IN, 0 }, { "v", RAD_OPD_IN, 0 }, + { "kv_cache", RAD_OPD_IN, 0 }, { "block_table", RAD_OPD_IN, 0 }, { "seqused", RAD_OPD_IN, 0 }, + { "cu_seqlens", RAD_OPD_IN, 0 }, { "k_descale", RAD_OPD_IN, 1 }, { "v_descale", RAD_OPD_IN, 1 }, + { "k_i8", RAD_OPD_IN, 1 }, { "k_scale", RAD_OPD_IN, 1 }, { "out", RAD_OPD_OUT, 0 }, +}; + static const RadOpSchema kSchemas[] = { SCHEMA("rmsnorm", pRmsNorm, oRmsNorm, "y = x * rsqrt(mean(x^2) + eps) * (w + wadd). `wadd` is GemmaRMSNorm's `1 +`, added in " @@ -2718,6 +2798,40 @@ static const RadOpSchema kSchemas[] = { "ew[t, k] = ew[t, k] * w_e[ids[t, k]] over [M, top_k], w_e an [n_expert] table, an id " "outside it reading 0; one product rounded once, so the embed_lookup + mul pair's value " "bit for bit. Gemma 4's per_expert_scale on the renormalised routing weights."), + SCHEMA("ln_mod", pLnMod, oLnMod, + "y = bf16(bf16(LN(x)) * bf16(1 + s[seq])): a layer norm with no gain or bias, then the " + "row's sequence's modulation row of `s`."), + SCHEMA("ln_mod_quant_fp8", pLnModQ, oLnModQ, + "gated 1: x = bf16(x + bf16(bf16(tanh(g[seq])) * y)) first; then z = ln_mod(x) and " + "(q, scale) = quant_act_fp8(z, group), z written when bound."), + SCHEMA("gate_add", pGenMn, oGateAdd, + "x = bf16(x + bf16(bf16(tanh(g[seq])) * y)): a residual through its sequence's gate."), + SCHEMA("timestep_embed", pTimestep, oTimestep, + "the sinusoidal timestep embedding, [cos | sin] of t' * exp(-ln(max_period) * i / (n/2))."), + SCHEMA("gather_rows2", pGenMn, oGather2, + "y[i] = idx[i] >= 0 ? a[idx[i]] : b[-1 - idx[i]]."), + SCHEMA("lane_gather", pLane, oLaneGather, "y[cu[e] + k] = src[lane[e] * stride + k]."), + SCHEMA("lane_store", pLane, oLaneStore, "dst[l * stride + k] = src[k] for every lane listed."), + SCHEMA("randn_lanes", pLane, oRandnLanes, + "an image's first step: its lane's rows become its seed's normal stream."), + SCHEMA("flow_euler", pLane, oFlowEuler, + "one Euler step of a flow-matching sampler per entry that moves a lane."), + SCHEMA("chan_affine", pChanAffine, oGenUnary, + "a per-channel affine from two parameter lists of n values."), + SCHEMA("conv2d_nhwc", pConvNhwc, oConvNhwc, + "an image convolution, channels innermost, the sizes read off the operands."), + SCHEMA("l2norm_chan", pL2Norm, oL2Norm, + "unit-L2 per row, times sqrt(n), times gamma, then `act`: an image decoder's norm."), + SCHEMA("d2s_add", pSpaceDepth, oSpaceDepth, "an upsampling shortcut added in."), + SCHEMA("s2d_avg_add", pSpaceDepth, oSpaceDepth, "a downsampling shortcut added in."), + SCHEMA("to_rgba8", pGenMn, oGenUnary, "decoded pixels in [-1, 1] to bytes."), + SCHEMA("gelu_tanh", pGenMn, oGenUnary, "the tanh approximation of gelu."), + SCHEMA("scatter_add_rows", pGenMn, oScatterAdd, "x[idx[i]] += v[i]; a negative index adds nothing."), + SCHEMA("attn_prefix_self", pAttnPS, oAttnPS, + "attention over a paged prefix and the step's own rows, causal over the own rows or not. " + "`qk` \"i8\" with `k_i8` and `k_scale` selects the INT8 Q.K form: the own keys as quant_act_i8g " + "codes and scales at group head_dim, the query and the prefix keys quantised the same " + "way inside the op, the score product exact in integers and P.V as in the bf16 form."), }; /* ================================================================================ constraints @@ -3119,6 +3233,15 @@ static const RadConstraint cArWht6[] = { C_EQ("world_size", 2), C_EQ("exact", 0), C_IN("dtype", "bf16 fp16"), C_DIV("numel", 64), C_P2P, }; +/* The same two at `overlap` 1: the rows below whose launch defaults leave the CUs to compute. */ +static const RadConstraint cArExactLane[] = { + C_EQ("world_size", 2), C_EQ("exact", 1), C_IN("dtype", "bf16 fp16 fp32"), C_EQ("overlap", 1), + C_P2P, +}; +static const RadConstraint cArWht6Lane[] = { + C_EQ("world_size", 2), C_EQ("exact", 0), C_IN("dtype", "bf16 fp16"), C_DIV("numel", 64), + C_EQ("overlap", 1), C_P2P, +}; /* DIV 32, not 96: the three-rank split is uneven in whole groups (r4d_rad_ar_twoshot_3rank_ti8). */ static const RadConstraint cArTi8Ts3[] = { C_EQ("world_size", 3), C_EQ("exact", 0), C_IN("dtype", "bf16 fp16"), C_DIV("numel", 32), @@ -3783,6 +3906,19 @@ static const RadTunable tAr[] = { { "drain", kArDrain, NELEM(kArDrain), 3, "store-drain wait before the flag: 3 = s_wait_storecnt, 1 = vmcnt" }, { "acq", kArAcq, NELEM(kArAcq), 0, "acquire fence after the flag read" }, }; +/* THE SAME AXES WITH NARROW DEFAULTS, for a collective issued beside compute (`overlap` 1). The + * wide launch -- up to 24 blocks of 1024 threads, 768 waves pushing over the link and then + * spinning on peer flags -- is right when the all-reduce has the card to itself and wrong when a + * GEMM shares it: on Qwen-Image's two-rank pass the GEMMs that ran beside it took 1.45 to 2.1x + * their time alone, which ate the whole overlap. Eight blocks of 256 threads still keep the link + * busy, and the same picture went 13.8 -> 13.0 s at 2048^2, bit for bit the same; 8 x 512 and + * 24 x 256 were 13.4 and 13.5. */ +static const RadTunable tArLane[] = { + { "nblocks", kArNblocks, NELEM(kArNblocks), 8, "blocks in the grid. 0 = scale with the message and clamp" }, + { "nthreads", kArNthreads, NELEM(kArNthreads), 256, "threads per block" }, + { "drain", kArDrain, NELEM(kArDrain), 3, "store-drain wait before the flag: 3 = s_wait_storecnt, 1 = vmcnt" }, + { "acq", kArAcq, NELEM(kArAcq), 0, "acquire fence after the flag read" }, +}; /* --------------------------------------------------------------------------------- row top-k * NCH is a REQUEST -- libr4d rounds the chunk width up to a multiple of eight columns -- so the @@ -3892,6 +4028,33 @@ static const RadConstraint cLogitsGemmFp8[] = { C_DIV("n_embd", 128), C_IN("dtyp * reads no tuned key. */ #define NOTUNE nullptr, 0, nullptr +/* ---- image generation ------------------------------------------------------------------- */ +/* Rows read 16 bytes at a time, so the widths are whole eights. */ +static const RadConstraint cGenRows8[] = { C_IN("dtype", "bf16"), C_DIV("n", 8) }; +static const RadConstraint cGenBf16[] = { C_IN("dtype", "bf16") }; +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. */ +static const RadConstraint cGenLanes[] = { C_IN("dtype", "bf16 f32") }; +/* The two lists are kernel arguments, 64 floats each at most (r4d_gen.hip). */ +static const RadConstraint cGenAffine[] = { C_IN("dtype", "bf16"), C_LE("n", 64) }; +static const RadConstraint cGenTimestep[] = { C_IN("dtype", "bf16"), C_DIV("n", 2) }; +/* The paged prefix at libr4d's block of 16, both caches bf16, up to eight query heads a KV head + * (the shim takes 1, 2, 4 and 8). */ +static const RadConstraint cAttnPrefixSelf[] = { + C_EQ("head_dim", 128), C_LE("gqa", 8), C_EQ("block_size", 16), C_IN("q_dtype", "bf16"), + C_IN("kv_dtype", "bf16"), +}; +static const RadConstraint cAttnDenseH128[] = { + C_EQ("head_dim", 128), C_LE("gqa", 8), C_IN("dtype", "bf16"), +}; +static const RadConstraint cAttnDenseH768[] = { + C_EQ("head_dim", 768), C_EQ("gqa", 1), C_EQ("causal", 0), C_IN("dtype", "bf16"), +}; +static const RadConstraint cAttnDenseH1152[] = { + C_EQ("head_dim", 1152), C_EQ("gqa", 1), C_EQ("causal", 0), C_IN("dtype", "bf16"), +}; + static const RadKernelInfo kKernels[] = { /* ---------------------------------- the small model ops (r4d_model_bf16.hip) ---------------- * @@ -5137,6 +5300,27 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, r4d_rad_ar_init, r4d_rad_ar_fini, r4d_rad_ar_oneshot_2rank_wht6, nullptr, nullptr, nullptr, r4d_shape_all_reduce }, +/* The two above at `overlap` 1: the same entry points and the same arithmetic, a launch that + * leaves the CUs to the compute running beside it (tArLane). */ +{ "ar_oneshot_2rank_exact_lane", "all_reduce", "ar", + "all-reduce (sum), one-shot push over P2P IPC scratch, narrow launch beside compute", + "exactly 2 ranks, peer-accessible, overlap 1; scratch sized by the full message; cudagraph-safe", + "bf16 / fp16 / fp32 payload, fp32 accumulate, bit-identical across ranks and to the wide row", + RAD_DOMAIN_DEVICE, R4D_PRIO_AR_ONESHOT + 1, + ROW(cArExactLane), ROW(tArLane), nullptr, + r4d_rad_ar_init, r4d_rad_ar_fini, r4d_rad_ar_oneshot_2rank_exact, nullptr, nullptr, nullptr, + r4d_shape_all_reduce }, + +{ "ar_oneshot_2rank_wht6_lane", "all_reduce", "ar", + "all-reduce (sum) with a Walsh-Hadamard-rotated 6-bit wire payload -- lossy; narrow launch " + "beside compute", + "exactly 2 ranks, peer-accessible, overlap 1; groups of 64 elements; cudagraph-safe", + "bf16 / fp16 payload, 6 bits + bf16 scale per group on the wire, fp32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_AR_ONESHOT + 1, + ROW(cArWht6Lane), ROW(tArLane), nullptr, + r4d_rad_ar_init, r4d_rad_ar_fini, r4d_rad_ar_oneshot_2rank_wht6, nullptr, nullptr, nullptr, + r4d_shape_all_reduce }, + { "ar_gather_3rank", "all_gather", "ar", "all-gather, one-shot push over P2P IPC scratch, the wide family's per-block handshake", "exactly 3 ranks, all peer-accessible; y is [3 * numel] with rank r's input at r * numel, or " @@ -6325,6 +6509,194 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cExpertScale), NOTUNE, nullptr, nullptr, r4d_rad_expert_scale_bf16, nullptr, nullptr, nullptr, nullptr }, +{ "attn_prefix_self_h128_bf16", "attn_prefix_self", "attn", + "attention over a paged prefix and the pass's own rows, causal over the own rows or not", + "head_dim 128, 1/2/4/8 query heads a KV head, a flat grid over the sequences' query blocks; " + "the int8 Q.K form (k_i8 / k_scale) at 1 only", + "bf16 q/k/v/out and cache, bf16 operands, fp32 accumulate; or i8 Q.K codes, i32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cAttnPrefixSelf), NOTUNE, + nullptr, nullptr, r4d_rad_attn_prefix_self, nullptr, nullptr, nullptr, + nullptr }, + +{ "attn_dense_h128_bf16", "attn_dense", "attn", + "dense varlen attention over cu_seqlens, causal or bidirectional", + "head_dim 128, 1/2/4/8 query heads a KV head", + "bf16 query / key / value / out, bf16 operands, fp32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cAttnDenseH128), NOTUNE, + nullptr, nullptr, r4d_rad_attn_dense_h128, nullptr, nullptr, nullptr, + nullptr }, + +{ "attn_dense_h768_bf16", "attn_dense", "attn", + "one 768-wide head over every row of a segment: an image encoder's mid-block attention", + "head_dim 768 split across eight waves, 16 queries a workgroup", + "bf16 query / key / value / out, bf16 operands, fp32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cAttnDenseH768), NOTUNE, + nullptr, nullptr, r4d_rad_attn_dense_wide, nullptr, nullptr, nullptr, + nullptr }, + +{ "attn_dense_h1152_bf16", "attn_dense", "attn", + "one 1152-wide head over every row of a segment: an image decoder's mid-block attention", + "head_dim 1152 split across eight waves, 16 queries a workgroup", + "bf16 query / key / value / out, bf16 operands, fp32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cAttnDenseH1152), NOTUNE, + nullptr, nullptr, r4d_rad_attn_dense_wide, nullptr, nullptr, nullptr, + nullptr }, + +{ "ln_mod_quant_fp8_bf16", "ln_mod_quant_fp8", "norm", + "gate_add, ln_mod and quant_act_fp8 in one pass: a workgroup a row", + "any M, n a multiple of 128 up to 8192, group 128", + "bf16 in, E4M3 codes with f32 scales out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cLnModQ), NOTUNE, + nullptr, nullptr, r4d_rad_ln_mod_quant_fp8, nullptr, nullptr, nullptr, + nullptr }, +{ "ln_mod_bf16", "ln_mod", "norm", + "gainless layer norm times (1 + a sequence's scale row): a workgroup a row", + "any M, row pitches honoured", + "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenRows8), NOTUNE, + nullptr, nullptr, r4d_rad_ln_mod, nullptr, nullptr, nullptr, + nullptr }, + +{ "gate_add_bf16", "gate_add", "elem", + "x += tanh(gate row) * y, the reference's three roundings", + "any M, row pitches honoured", + "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenRows8), NOTUNE, + nullptr, nullptr, r4d_rad_gate_add, nullptr, nullptr, nullptr, + nullptr }, + +{ "timestep_embed_bf16", "timestep_embed", "elem", + "sinusoidal timestep embedding, f32 angles", + "any M, row pitches honoured", + "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenTimestep), NOTUNE, + nullptr, nullptr, r4d_rad_timestep_embed, nullptr, nullptr, nullptr, + nullptr }, + +{ "gather_rows2_bf16", "gather_rows2", "elem", + "rows from two sources by a signed index", + "any M, row pitches honoured", + "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenRows8), NOTUNE, + nullptr, nullptr, r4d_rad_gather_rows2, nullptr, nullptr, nullptr, + nullptr }, + +{ "lane_gather_w32", "lane_gather", "elem", + "each entry's rows out of its lane", + "any M, row pitches honoured", + "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenLanes), NOTUNE, + nullptr, nullptr, r4d_rad_lane_gather, nullptr, nullptr, nullptr, + nullptr }, + +{ "lane_store_w32", "lane_store", "elem", + "one source's rows into several lanes", + "any M, row pitches honoured", + "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenLanes), NOTUNE, + nullptr, nullptr, r4d_rad_lane_store, nullptr, nullptr, nullptr, + nullptr }, + +{ "randn_lanes_bf16", "randn_lanes", "elem", + "a lane's rows from its seed's Philox normal stream", + "any M, row pitches honoured", + "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenBf16), NOTUNE, + nullptr, nullptr, r4d_rad_randn_lanes, nullptr, nullptr, nullptr, + nullptr }, + +{ "flow_euler_bf16", "flow_euler", "elem", + "a flow-matching Euler step with guidance, preview and repaint", + "any M, row pitches honoured", + "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenBf16), NOTUNE, + nullptr, nullptr, r4d_rad_flow_euler, nullptr, nullptr, nullptr, + nullptr }, + +{ "chan_affine_bf16", "chan_affine", "elem", + "a per-channel affine from parameter lists", + "any M, row pitches honoured", + "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenAffine), NOTUNE, + nullptr, nullptr, r4d_rad_chan_affine, nullptr, nullptr, nullptr, + nullptr }, + +{ "l2norm_chan_bf16", "l2norm_chan", "norm", + "unit-L2 channel norm, scaled, optional silu: a wave a pixel", + "any M, row pitches honoured", + "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenRows8), NOTUNE, + nullptr, nullptr, r4d_rad_l2norm_chan, nullptr, nullptr, nullptr, + nullptr }, + +{ "d2s_add_bf16", "d2s_add", "elem", + "an upsampling shortcut added in", + "any M, row pitches honoured", + "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenBf16), NOTUNE, + nullptr, nullptr, r4d_rad_d2s_add, nullptr, nullptr, nullptr, + nullptr }, + +{ "s2d_avg_add_bf16", "s2d_avg_add", "elem", + "a downsampling shortcut added in", + "any M, row pitches honoured", + "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenBf16), NOTUNE, + nullptr, nullptr, r4d_rad_s2d_avg_add, nullptr, nullptr, nullptr, + nullptr }, + +{ "to_rgba8_bf16", "to_rgba8", "elem", + "decoded pixels to bytes", + "any M, row pitches honoured", + "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenBf16), NOTUNE, + nullptr, nullptr, r4d_rad_to_rgba8, nullptr, nullptr, nullptr, + nullptr }, + +{ "gelu_tanh_bf16", "gelu_tanh", "elem", + "tanh gelu", + "any M, row pitches honoured", + "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenRows8), NOTUNE, + nullptr, nullptr, r4d_rad_gelu_tanh, nullptr, nullptr, nullptr, + nullptr }, + +{ "scatter_add_rows_bf16", "scatter_add_rows", "elem", + "x[idx[i]] += v[i]", + "any M, row pitches honoured", + "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenRows8), NOTUNE, + nullptr, nullptr, r4d_rad_scatter_add_rows, nullptr, nullptr, nullptr, + nullptr }, + +{ "conv2d_nhwc_bf16", "conv2d_nhwc", "conv", + "an image convolution as an implicit GEMM over (tap, cin), the weight stored tap-major", + "128 pixels x 64 or 128 output channels a block, 64 K a stage; cin % 8 != 0 takes a direct kernel", + "bf16 image, weight and bias, fp32 accumulate, one rounding", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenBf16), NOTUNE, + nullptr, nullptr, r4d_rad_conv2d_nhwc, nullptr, r4d_rad_layout_conv_tap, r4d_rad_relayout_conv_tap, + nullptr, r4d_rad_unrelayout_conv_tap }, }; /* ================================================================================== the exports */ diff --git a/libref/ref_attn.cpp b/libref/ref_attn.cpp index 1d59a547..648589e1 100644 --- a/libref/ref_attn.cpp +++ b/libref/ref_attn.cpp @@ -40,10 +40,10 @@ using namespace ref; namespace { -/* The largest head this reference accumulates in one stack frame. MLA's 576 is the widest head in - * circulation and libr4d's widest is 256, so 1024 is headroom rather than a limit anyone will - * meet; above it the op says RAD_E_UNSUPPORTED by name instead of overflowing a frame. */ -enum { REF_HD_MAX = 1024 }; +/* The largest head this reference accumulates in one stack frame. The widest in circulation is an + * image VAE's single-head mid-block attention at 1152 (Qwen-Image 2.1), so 2048 is headroom; above + * it the op says RAD_E_UNSUPPORTED by name instead of overflowing a frame. */ +enum { REF_HD_MAX = 2048 }; struct KVView { const RadTensor* t; @@ -564,10 +564,15 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) { const float rscale = p_f32(a, "scale", 1.0f); const float wadd = p_f32(a, "wadd", 0.0f); const int v_norm = (int)p_int(a, "v_norm", 0); - static const char* kModes[] = { "neox", "gptj", "blocks" }; - const int mode = p_enum(a, "mode", kModes, 3, 0); + /* `gptj_blocks` is `blocks` with each section's pairs ADJACENT -- (start + 2j, start + 2j + 1), + * the complex-number form a 3-axis image rotary takes (Qwen-Image's). `imrope` is `rope`'s + * interleaved M-RoPE over NeoX pairs, after the norm (Qwen3-VL's text attention). */ + static const char* kModes[] = { "neox", "gptj", "blocks", "gptj_blocks", "imrope" }; + const int mode = p_enum(a, "mode", kModes, 5, 0); if (mode < 0) return RAD_E_UNSUPPORTED; - const bool blocks = mode == 2; + const bool blocks = mode == 2 || mode == 3; + const bool adjacent = mode == 3; + const bool im = mode == 4; int64_t rot = p_int(a, "rotary_dim", head_dim); if (head_dim <= 0 || n_head <= 0 || rot <= 0 || rot > head_dim || (rot & 1)) return RAD_E_SHAPE; if (numel(qw) < head_dim || numel(kw) < head_dim) return RAD_E_SHAPE; @@ -578,6 +583,10 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) { * fill the rotated prefix exactly. Positions are [C, M], component-major. */ int64_t sec[8] = {}, comp[8] = {}; int n_sec = 0; + if (im) { + n_sec = rope_sections(a, sec); + if (n_sec < 3) return RAD_E_SHAPE; + } if (blocks) { n_sec = rope_sections(a, sec); if (n_sec <= 0) return RAD_E_SHAPE; @@ -599,8 +608,9 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) { const bool multi = pos->rank >= 2; const int64_t n_comp = multi ? pos->shape[0] : 1; const int64_t M = multi ? pos->shape[1] : numel(pos); - if (multi && !blocks) return RAD_E_SHAPE; - for (int c = 0; c < n_sec; ++c) + if (multi && !blocks && !im) return RAD_E_SHAPE; + if (multi && im && n_comp < 3) return RAD_E_SHAPE; + for (int c = 0; blocks && c < n_sec; ++c) if (comp[c] < 0 || comp[c] >= n_comp) return RAD_E_SHAPE; const int64_t pcs = multi ? pos->stride[0] : 0, pms = multi ? pos->stride[1] : 0; @@ -610,7 +620,8 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) { const int64_t ds = laststride(qkv); RopeFreq f; /* No `ladder` on this row yet: the fused norm+rope measures by `rot`, as it always has. */ - RAD_REF_TRY(rope_freqs(mode, rot, rot, theta, nullptr, 0, &f)); + if (im) RAD_REF_TRY(rope_freqs(ROPE_IMROPE, rot, rot, theta, sec, multi ? n_sec : 0, &f)); + else RAD_REF_TRY(rope_freqs(blocks ? 0 : mode, rot, rot, theta, nullptr, 0, &f)); #pragma omp parallel for schedule(static) @@ -637,7 +648,7 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) { for (int64_t d = 0; d < head_dim; ++d) stt(qkv, base + d * ds, ldt(qkv, base + d * ds) * sc * (ldt(w, d * ws) + wadd)); if (!blocks) { - rope_head(qkv, base, ds, rot, mode, f, p); + rope_head(qkv, base, ds, rot, im ? ROPE_IMROPE : mode, f, p); continue; } int64_t start = 0; @@ -646,7 +657,8 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) { const float inv = 1.0f / std::pow(theta, (float)j / (float)sec[c]); const float ang = p[comp[c]] * inv; const float cs = std::cos(ang), sn = std::sin(ang); - const int64_t i0 = start + j, i1 = start + sec[c] + j; + const int64_t i0 = adjacent ? start + 2 * j : start + j; + const int64_t i1 = adjacent ? start + 2 * j + 1 : start + sec[c] + j; const float x0 = ldt(qkv, base + i0 * ds), x1 = ldt(qkv, base + i1 * ds); stt(qkv, base + i0 * ds, x0 * cs - x1 * sn); stt(qkv, base + i1 * ds, x0 * sn + x1 * cs); diff --git a/libref/ref_gen.cpp b/libref/ref_gen.cpp new file mode 100644 index 00000000..5bb0ba50 --- /dev/null +++ b/libref/ref_gen.cpp @@ -0,0 +1,759 @@ +/* ref_gen.cpp -- the image generator's ops (docs/OPS.md, "Image generation"). + * + * WHERE A ROUNDING IS WRITTEN OUT, IT IS THE REFERENCE MODEL'S. A diffusion transformer and its + * decoder are run in bf16 by the reference implementation, so every tensor it materialises is + * rounded there: `LN(x) * (1 + scale)` is three bf16 tensors, not one f32 expression, and the + * oracle rounds where the reference does so a kernel that fuses the chain can be held to it. + * + * Geometry a step decides -- an image's height and width -- arrives in the OPERANDS, never in the + * parameters: a 2-D image operand is [height, width * channels], dense, and the op reads both off + * its shape. A parameter is fixed at declare and an image's size is a request's. + */ +#include "ref_common.h" +#include "ref_gemm.h" +#include "ref_ops.h" +#include "rad_philox.h" + +#include +#include +#include + +using namespace ref; + +namespace { + +/* An entry's flags (docs/OPS.md, flow_euler): RadGenBatch's RAD_GEN_F_* values, restated because a + * kernel library compiles against rad_abi.h and not the run phase's header. */ +enum { kFirst = 1, kInpaint = 2, kPreview = 4 }; + +inline float rnd(uint32_t dt, float v) { + uint16_t h; + switch (dt) { + case RAD_BF16: h = f32_to_bf16(v); return bf16_to_f32(h); + case RAD_F16: h = f32_to_f16(v); return f16_to_f32(h); + default: return v; + } +} +inline float rbf(float v) { return bf16_to_f32(f32_to_bf16(v)); } + +inline int64_t cu_at(const RadTensor* cu, int64_t i) { + return ld_int(cu->dtype, cu->data, offlin(cu, i)); +} + +/* The sequence that owns dense row `r`: linear, because there are a handful. */ +inline int64_t seq_of(const RadTensor* cu, int64_t n_seq, int64_t r) { + int64_t s = 0; + while (s + 1 < n_seq && cu_at(cu, s + 1) <= r) ++s; + return s; +} + +inline int64_t rows_n(const RadTensor* t, int64_t n) { + if (!t || n <= 0) return 0; + if (t->rank >= 2 && t->shape[t->rank - 1] == n) { + int64_t r = 1; + for (uint32_t i = 0; i + 1 < t->rank; ++i) r *= t->shape[i]; + return r; + } + return numel(t) / n; +} + +/* A space-separated list of floats, each rounded to bf16 as the reference's bf16 tensor of it is. */ +int parse_list(const char* s, std::vector* out) { + out->clear(); + while (s && *s) { + char* end = nullptr; + const double v = std::strtod(s, &end); + if (end == s) break; + out->push_back(rbf((float)v)); + s = end; + } + return (int)out->size(); +} + +} /* namespace */ + +/* ------------------------------------------------------------------ ln_mod */ +/* y = bf16( bf16(LN(x)) * bf16(1 + s[seq]) ): a layer norm with no gain and no bias, then the + * modulation row of the row's sequence. `s` is [n_seq, >= n] at its own row pitch -- a column + * slice of the modulation projection. */ +int ref_ln_mod(const RadArgs* a, RadStream) { + if (!have(a, 4)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *s = &a->t[1], *cu = &a->t[2], *y = &a->t[3]; + const int64_t n = p_int(a, "n", 0); + const float eps = p_f32(a, "eps", 1e-6f); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_n(y, n), n_seq = numel(cu) - 1; + if (rows <= 0 || n_seq <= 0 || rows_n(x, n) < rows) return RAD_E_SHAPE; + const int64_t s_rs = row_stride(s, n), s_cs = laststride(s); + #pragma omp parallel for schedule(static) + for (int64_t r = 0; r < rows; ++r) { + const int64_t e = seq_of(cu, n_seq, r); + const int64_t xb = rowoff(x, r, n), xs = laststride(x); + const int64_t yb = rowoff(y, r, n), ys = laststride(y); + float sum = 0.0f; + for (int64_t i = 0; i < n; ++i) sum += ldt(x, xb + i * xs); + const float mean = sum / (float)n; + float var = 0.0f; + for (int64_t i = 0; i < n; ++i) { + const float d = ldt(x, xb + i * xs) - mean; + var += d * d; + } + const float rs = 1.0f / std::sqrt(var / (float)n + eps); + for (int64_t i = 0; i < n; ++i) { + const float ln = rnd(y->dtype, (ldt(x, xb + i * xs) - mean) * rs); + const float sc = rnd(y->dtype, 1.0f + ldt(s, e * s_rs + i * s_cs)); + stt(y, yb + i * ys, ln * sc); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ gate_add */ +/* x = bf16( x + bf16( bf16(tanh(g[seq])) * y ) ): a residual added through its sequence's gate. */ +int ref_gate_add(const RadArgs* a, RadStream) { + if (!have(a, 4)) return RAD_E_INVAL; + const RadTensor *y = &a->t[0], *g = &a->t[1], *cu = &a->t[2], *x = &a->t[3]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_n(y, n), n_seq = numel(cu) - 1; + if (rows <= 0 || n_seq <= 0 || rows_n(x, n) < rows) return RAD_E_SHAPE; + const int64_t g_rs = row_stride(g, n), g_cs = laststride(g); + #pragma omp parallel for schedule(static) + for (int64_t r = 0; r < rows; ++r) { + const int64_t e = seq_of(cu, n_seq, r); + const int64_t yb = rowoff(y, r, n), ys = laststride(y); + const int64_t xb = rowoff(x, r, n), xs = laststride(x); + for (int64_t i = 0; i < n; ++i) { + const float t = rnd(x->dtype, std::tanh(ldt(g, e * g_rs + i * g_cs))); + const float p = rnd(x->dtype, t * ldt(y, yb + i * ys)); + stt(x, xb + i * xs, ldt(x, xb + i * xs) + p); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ ln_mod_quant_fp8 */ +/* gate_add (with `gated` 1), ln_mod and quant_act_fp8 over each row, each step's output rounded + * to its stored dtype as the three ops would store it: the residual to x's, the norm to bf16, and + * the codes as ref_quant_act_fp8 writes them over that bf16 row. */ +int ref_ln_mod_quant_fp8(const RadArgs* a, RadStream) { + if (a->n_t < 8) return RAD_E_INVAL; + const RadTensor *y = t_in(a, 0), *g = t_in(a, 1), *s = &a->t[2], *cu = &a->t[3]; + const RadTensor *x = &a->t[4], *q = &a->t[5], *sc = &a->t[6], *z = t_in(a, 7); + const int64_t n = p_int(a, "n", 0), grp = p_int(a, "group", 0); + const bool gated = p_int(a, "gated", 0) != 0; + const float eps = p_f32(a, "eps", 1e-6f); + if (n <= 0 || grp <= 0 || n % grp || (gated && (!y || !g))) return RAD_E_SHAPE; + const int64_t rows = rows_n(q, n), n_seq = numel(cu) - 1, ngrp = n / grp; + if (rows <= 0 || n_seq <= 0 || rows_n(x, n) < rows || numel(sc) < rows * ngrp) + return RAD_E_SHAPE; + const int64_t s_rs = row_stride(s, n), s_cs = laststride(s); + const int64_t g_rs = gated ? row_stride(g, n) : 0, g_cs = gated ? laststride(g) : 0; + #pragma omp parallel for schedule(static) + for (int64_t r = 0; r < rows; ++r) { + const int64_t e = seq_of(cu, n_seq, r); + const int64_t xb = rowoff(x, r, n), xs = laststride(x); + std::vector v((size_t)n), o((size_t)n); + for (int64_t i = 0; i < n; ++i) { + float xv = ldt(x, xb + i * xs); + if (gated) { + const float t = rnd(x->dtype, std::tanh(ldt(g, e * g_rs + i * g_cs))); + const float d = ldt(y, rowoff(y, r, n) + i * laststride(y)); + xv = rnd(x->dtype, xv + rnd(x->dtype, t * d)); + stt(x, xb + i * xs, xv); + } + v[(size_t)i] = xv; + } + float sum = 0.0f; + for (int64_t i = 0; i < n; ++i) sum += v[(size_t)i]; + const float mean = sum / (float)n; + float var = 0.0f; + for (int64_t i = 0; i < n; ++i) { const float d = v[(size_t)i] - mean; var += d * d; } + const float rs = 1.0f / std::sqrt(var / (float)n + eps); + for (int64_t i = 0; i < n; ++i) { + const float ln = rnd(RAD_BF16, (v[(size_t)i] - mean) * rs); + const float sm = rnd(RAD_BF16, 1.0f + ldt(s, e * s_rs + i * s_cs)); + o[(size_t)i] = rnd(RAD_BF16, ln * sm); + if (z) stt(z, rowoff(z, r, n) + i * laststride(z), o[(size_t)i]); + } + const int64_t qb = rowoff(q, r, n), qs = laststride(q); + for (int64_t gi = 0; gi < ngrp; ++gi) { + float amax = 0.0f; + for (int64_t i = gi * grp; i < (gi + 1) * grp; ++i) + amax = std::max(amax, std::fabs(o[(size_t)i])); + const float scl = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f; + const float inv = 1.0f / scl; + for (int64_t i = gi * grp; i < (gi + 1) * grp; ++i) { + float w = o[(size_t)i] * inv; + if (w > 448.0f) w = 448.0f; + if (w < -448.0f) w = -448.0f; + st_dt(q->dtype, q->data, qb + i * qs, w); + } + stt(sc, rowoff(sc, r, ngrp) + gi * laststride(sc), scl); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ timestep_embed */ +/* y[m] = [cos(t' f_0) .. cos(t' f_{h-1}) | sin(t' f_0) .. sin(t' f_{h-1})], h = n / 2, where + * f_i = exp(-ln(max_period) * i / h) in f32 and t' = scale * t -- or, with `round` 1, the value + * diffusers' pipeline hands its transformer: t rounded to bf16 at scale, divided back and rounded + * again, then scaled: scale * bf16(bf16(t * scale) / scale). */ +int ref_timestep_embed(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *t = &a->t[0], *y = &a->t[1]; + const int64_t n = p_int(a, "n", 0); + const float scale = p_f32(a, "scale", 1000.0f); + const double mp = p_f32(a, "max_period", 10000.0f); + const int round = (int)p_int(a, "round", 0); + if (n <= 0 || (n & 1)) return RAD_E_SHAPE; + const int64_t rows = rows_n(y, n); + if (rows <= 0 || numel(t) < rows) return RAD_E_SHAPE; + const int64_t h = n / 2; + const float coef = (float)(-std::log(mp)); + for (int64_t m = 0; m < rows; ++m) { + const float tv = ldt(t, offlin(t, m)); + const float tt = round ? scale * rbf(rbf(tv * scale) / scale) : scale * tv; + const int64_t yb = rowoff(y, m, n), ys = laststride(y); + for (int64_t i = 0; i < h; ++i) { + const float f = std::exp(coef * (float)i / (float)h); + const float arg = tt * f; + stt(y, yb + i * ys, std::cos(arg)); + stt(y, yb + (h + i) * ys, std::sin(arg)); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ gather_rows2 */ +/* y[i] = idx[i] >= 0 ? a[idx[i]] : b[-1 - idx[i]] -- a sequence assembled from two sources. */ +int ref_gather_rows2(const RadArgs* a, RadStream) { + if (!have(a, 4)) return RAD_E_INVAL; + const RadTensor *A = &a->t[0], *B = &a->t[1], *idx = &a->t[2], *y = &a->t[3]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_n(y, n); + if (rows <= 0 || numel(idx) < rows) return RAD_E_SHAPE; + const int64_t ra = rows_n(A, n), rbn = rows_n(B, n); + #pragma omp parallel for schedule(static) + for (int64_t i = 0; i < rows; ++i) { + const int64_t r = ld_int(idx->dtype, idx->data, offlin(idx, i)); + const RadTensor* src = r >= 0 ? A : B; + const int64_t row = r >= 0 ? r : -1 - r; + const int64_t yb = rowoff(y, i, n), ys = laststride(y); + if (row >= (r >= 0 ? ra : rbn)) { + for (int64_t c = 0; c < n; ++c) stt(y, yb + c * ys, 0.0f); + continue; + } + const int64_t sb = rowoff(src, row, n), ss = laststride(src); + for (int64_t c = 0; c < n; ++c) stt(y, yb + c * ys, ldt(src, sb + c * ss)); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ lane_gather / lane_store */ +/* lane_gather: y[cu[e] + k] = src[lane[e] * stride + k] for the rows of each entry. */ +int ref_lane_gather(const RadArgs* a, RadStream) { + if (!have(a, 4)) return RAD_E_INVAL; + const RadTensor *src = &a->t[0], *lane = &a->t[1], *cu = &a->t[2], *y = &a->t[3]; + const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0); + if (n <= 0 || stride <= 0) return RAD_E_SHAPE; + const int64_t n_seq = numel(cu) - 1, src_rows = rows_n(src, n); + if (n_seq <= 0 || numel(lane) < n_seq) return RAD_E_SHAPE; + for (int64_t e = 0; e < n_seq; ++e) { + const int64_t L = ld_int(lane->dtype, lane->data, offlin(lane, e)); + const int64_t b0 = cu_at(cu, e), b1 = cu_at(cu, e + 1); + if (L < 0 || b1 - b0 > stride || (L + 1) * stride > src_rows) return RAD_E_SHAPE; + for (int64_t k = 0; k < b1 - b0; ++k) { + const int64_t sb = rowoff(src, L * stride + k, n), ss = laststride(src); + const int64_t yb = rowoff(y, b0 + k, n), ys = laststride(y); + for (int64_t c = 0; c < n; ++c) stt(y, yb + c * ys, ldt(src, sb + c * ss)); + } + } + return RAD_OK; +} + +/* lane_store: every listed lane's rows [0, rows) become src's rows. */ +int ref_lane_store(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *src = &a->t[0], *lane = &a->t[1], *dst = &a->t[2]; + const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0); + if (n <= 0 || stride <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_n(src, n), dst_rows = rows_n(dst, n), nl = numel(lane); + if (rows <= 0 || rows > stride) return RAD_E_SHAPE; + for (int64_t l = 0; l < nl; ++l) { + const int64_t L = ld_int(lane->dtype, lane->data, offlin(lane, l)); + if (L < 0 || (L + 1) * stride > dst_rows) return RAD_E_SHAPE; + for (int64_t k = 0; k < rows; ++k) { + const int64_t sb = rowoff(src, k, n), ss = laststride(src); + const int64_t db = rowoff(dst, L * stride + k, n), ds = laststride(dst); + for (int64_t c = 0; c < n; ++c) stt(dst, db + c * ds, ldt(src, sb + c * ss)); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ randn_lanes */ +/* The first step of an image: its lane's rows [0, cu[e+1] - cu[e]) become the seed's normal + * stream (abi/rad_philox.h), element (k, c) the stream's element k * n + c. Entries whose flags + * lack RAD_GEN_F_FIRST are left alone. */ +int ref_randn_lanes(const RadArgs* a, RadStream) { + if (!have(a, 5)) return RAD_E_INVAL; + const RadTensor *fl = &a->t[0], *seed = &a->t[1], *lane = &a->t[2], *cu = &a->t[3]; + const RadTensor *dst = &a->t[4]; + const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0); + if (n <= 0 || stride <= 0) return RAD_E_SHAPE; + const int64_t n_seq = numel(cu) - 1, dst_rows = rows_n(dst, n); + if (n_seq <= 0 || numel(fl) < n_seq || numel(lane) < n_seq || numel(seed) < 2 * n_seq) + return RAD_E_SHAPE; + for (int64_t e = 0; e < n_seq; ++e) { + if (!(ld_int(fl->dtype, fl->data, offlin(fl, e)) & kFirst)) continue; + const int64_t L = ld_int(lane->dtype, lane->data, offlin(lane, e)); + const int64_t len = cu_at(cu, e + 1) - cu_at(cu, e); + if (L < 0 || len > stride || (L + 1) * stride > dst_rows) return RAD_E_SHAPE; + const uint64_t sd = (uint64_t)(uint32_t)ld_int(seed->dtype, seed->data, offlin(seed, 2 * e)) | + ((uint64_t)(uint32_t)ld_int(seed->dtype, seed->data, offlin(seed, 2 * e + 1)) << 32); + #pragma omp parallel for schedule(static) + for (int64_t k = 0; k < len; ++k) { + const int64_t db = rowoff(dst, L * stride + k, n), ds = laststride(dst); + for (int64_t c = 0; c < n; ++c) + stt(dst, db + c * ds, rad_philox_normal(sd, (uint64_t)(k * n + c))); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ flow_euler */ +/* One Euler step of a flow-matching sampler for every entry that moves a lane (pair != -2): + * + * v' = pair >= 0 ? bf16(neg + bf16(cfg * bf16(pos - neg))) : pos the guided velocity + * x' = bf16(x + bf16(bf16(sigma_next - sigma) * v')) diffusers' step, its roundings + * + * and, by flag, kPreview writes bf16(x - sigma * v') -- the step's estimate of the clean + * latent -- to the lane's preview rows; kInpaint puts the kept region back afterwards: + * x' = bf16(m x' + (1 - m)((1 - sigma_next) src + sigma_next noise)), m the lane's mask row and + * noise the image's own stream (randn_lanes). At the last step sigma_next is 0 and the kept + * region is the picture's latent exactly. */ +int ref_flow_euler(const RadArgs* a, RadStream) { + if (!have(a, 13)) return RAD_E_INVAL; + const RadTensor *v = &a->t[0], *sg = &a->t[1], *sgn = &a->t[2], *cfg = &a->t[3]; + const RadTensor *pair = &a->t[4], *lane = &a->t[5], *fl = &a->t[6], *seed = &a->t[7]; + const RadTensor *cu = &a->t[8]; + const RadTensor *inp = t_in(a, 9), *mask = t_in(a, 10); + const RadTensor *st = &a->t[11]; + const RadTensor *pv = t_in(a, 12); + const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0); + if (n <= 0 || stride <= 0) return RAD_E_SHAPE; + const int64_t n_seq = numel(cu) - 1, st_rows = rows_n(st, n); + if (n_seq <= 0) return RAD_E_SHAPE; + const uint32_t dt = st->dtype; + for (int64_t e = 0; e < n_seq; ++e) { + const int64_t pr = ld_int(pair->dtype, pair->data, offlin(pair, e)); + if (pr == -2) continue; + const int64_t L = ld_int(lane->dtype, lane->data, offlin(lane, e)); + const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0; + const int64_t p0 = pr >= 0 ? cu_at(cu, pr) : 0; + if (L < 0 || len > stride || (L + 1) * stride > st_rows) return RAD_E_SHAPE; + if (pr >= 0 && cu_at(cu, pr + 1) - p0 != len) return RAD_E_SHAPE; + const float s = ldt(sg, offlin(sg, e)), sn = ldt(sgn, offlin(sgn, e)); + const float w = ldt(cfg, offlin(cfg, e)); + const int64_t f = ld_int(fl->dtype, fl->data, offlin(fl, e)); + const uint64_t sd = (uint64_t)(uint32_t)ld_int(seed->dtype, seed->data, offlin(seed, 2 * e)) | + ((uint64_t)(uint32_t)ld_int(seed->dtype, seed->data, offlin(seed, 2 * e + 1)) << 32); + const float dts = rnd(dt, sn - s); + if ((f & kInpaint) && (!inp || !mask)) return RAD_E_INVAL; + if ((f & kPreview) && !pv) return RAD_E_INVAL; + #pragma omp parallel for schedule(static) + for (int64_t k = 0; k < len; ++k) { + const int64_t vb = rowoff(v, b0 + k, n), vs = laststride(v); + const int64_t nb = pr >= 0 ? rowoff(v, p0 + k, n) : 0; + const int64_t sb = rowoff(st, L * stride + k, n), ss = laststride(st); + for (int64_t c = 0; c < n; ++c) { + float vv = ldt(v, vb + c * vs); + if (pr >= 0) { + const float vn = ldt(v, nb + c * vs); + vv = rnd(dt, vn + rnd(dt, w * rnd(dt, vv - vn))); + } + const float x = ldt(st, sb + c * ss); + if (f & kPreview) { + const int64_t pb = rowoff(pv, L * stride + k, n); + stt(pv, pb + c * laststride(pv), x - s * vv); + } + float xn = rnd(dt, x + rnd(dt, dts * vv)); + if (f & kInpaint) { + const float m = ldt(mask, offlin(mask, L * stride + k)); + const float src = ldt(inp, rowoff(inp, L * stride + k, n) + c * laststride(inp)); + const float nz = rad_philox_normal(sd, (uint64_t)(k * n + c)); + const float kept = (1.0f - sn) * src + sn * nz; + xn = rnd(dt, m * xn + (1.0f - m) * kept); + } + stt(st, sb + c * ss, xn); + } + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ chan_affine */ +/* A per-channel affine from two lists the PARAMETERS carry (a latent's mean and deviation are + * configuration, not weights), each value rounded to bf16 as the reference's bf16 tensor of it: + * mode `fma` is bf16(bf16(x * mul) + add), `inv` is bf16(bf16(x - add) / mul). */ +int ref_chan_affine(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *y = &a->t[1]; + const int64_t n = p_int(a, "n", 0); + std::vector mul, add; + if (n <= 0 || parse_list(p_str(a, "mul", ""), &mul) != n || + parse_list(p_str(a, "add", ""), &add) != n) + return RAD_E_SHAPE; + const char* mode = p_str(a, "mode", "fma"); + const bool inv = mode && !std::strcmp(mode, "inv"); + if (!inv && mode && std::strcmp(mode, "fma")) return RAD_E_INVAL; + const int64_t rows = rows_n(y, n); + if (rows <= 0 || rows_n(x, n) < rows) return RAD_E_SHAPE; + #pragma omp parallel for schedule(static) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(x, r, n), xs = laststride(x); + const int64_t yb = rowoff(y, r, n), ys = laststride(y); + for (int64_t c = 0; c < n; ++c) { + const float v = ldt(x, xb + c * xs); + stt(y, yb + c * ys, inv ? rnd(y->dtype, v - add[c]) / mul[c] + : rnd(y->dtype, v * mul[c]) + add[c]); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ conv2d_nhwc */ +/* An image convolution, channels innermost: x is [Hin, Win * cin], y [Hout, Wout * cout], both + * dense, and the sizes are read off them. w is PyTorch's [cout, cin, k, k] and b [cout]. + * + * up 2 the input is first upsampled 2x nearest-neighbour (`nearest-exact` at an exact + * factor of two is the same): the conv reads x[y / 2, x / 2] + * pad same k / 2 zeros on every side + * pad down no zeros above and left, one below and right -- ZeroPad2d((0, 1, 0, 1)) then the + * conv, a stride-2 downsample's + * + * f32 accumulation over (kh, kw, cin), the bias added, one rounding. */ +int ref_conv2d_nhwc(const RadArgs* a, RadStream) { + if (!have(a, 4)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *w = &a->t[1], *b = &a->t[2], *y = &a->t[3]; + const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0), k = p_int(a, "k", 0); + const int64_t stride = p_int(a, "stride", 1), up = p_int(a, "up", 1); + const char* pad = p_str(a, "pad", "same"); + const bool down = pad && !std::strcmp(pad, "down"); + if (cin <= 0 || cout <= 0 || k <= 0 || stride <= 0 || up <= 0) return RAD_E_SHAPE; + if (x->rank != 2 || y->rank != 2 || x->shape[1] % cin || y->shape[1] % cout) return RAD_E_SHAPE; + const int64_t Hin = x->shape[0], Win = x->shape[1] / cin; + const int64_t Ho = y->shape[0], Wo = y->shape[1] / cout; + const int64_t Hv = Hin * up, Wv = Win * up; + const int64_t pt = down ? 0 : k / 2, pb = down ? 1 : k / 2; + if ((Hv + pt + pb - k) / stride + 1 != Ho || (Wv + pt + pb - k) / stride + 1 != Wo) + return RAD_E_SHAPE; + if (numel(w) < cout * cin * k * k || numel(b) < cout) return RAD_E_SHAPE; + const int64_t xr = x->stride[0], yr = y->stride[0]; + #pragma omp parallel for schedule(static) + for (int64_t oy = 0; oy < Ho; ++oy) + for (int64_t ox = 0; ox < Wo; ++ox) + for (int64_t co = 0; co < cout; ++co) { + float acc = 0.0f; + for (int64_t kh = 0; kh < k; ++kh) { + const int64_t iy = oy * stride + kh - pt; + if (iy < 0 || iy >= Hv) continue; + for (int64_t kw = 0; kw < k; ++kw) { + const int64_t ix = ox * stride + kw - pt; + if (ix < 0 || ix >= Wv) continue; + const int64_t xb = (iy / up) * xr + (ix / up) * cin; + for (int64_t ci = 0; ci < cin; ++ci) + acc += ldt(w, ((co * cin + ci) * k + kh) * k + kw) * ldt(x, xb + ci); + } + } + stt(y, oy * yr + ox * cout + co, acc + ldt(b, co)); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ l2norm_chan */ +/* An image norm over the channels of each pixel, the reference's three bf16 tensors: + * n1 = bf16(x / max(||x||, 1e-12)), n2 = bf16(n1 * sqrt(n)), y = bf16(n2 * gamma), then `act` + * (none, or silu: bf16(y * sigmoid(y))). */ +int ref_l2norm_chan(const RadArgs* a, RadStream) { + if (!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) < n) return RAD_E_SHAPE; + const char* act = p_str(a, "act", "none"); + const bool silu = act && !std::strcmp(act, "silu"); + if (!silu && act && std::strcmp(act, "none")) return RAD_E_INVAL; + const int64_t rows = rows_n(y, n); + if (rows <= 0 || rows_n(x, n) < rows) return RAD_E_SHAPE; + const float sq = (float)std::sqrt((double)n); + const uint32_t dt = y->dtype; + #pragma omp parallel for schedule(static) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(x, r, n), xs = laststride(x); + const int64_t yb = rowoff(y, r, n), ys = laststride(y); + float ss = 0.0f; + for (int64_t c = 0; c < n; ++c) { const float v = ldt(x, xb + c * xs); ss += v * v; } + const float nrm = std::max(std::sqrt(ss), 1e-12f); + for (int64_t c = 0; c < n; ++c) { + const float n1 = rnd(dt, ldt(x, xb + c * xs) / nrm); + const float n2 = rnd(dt, n1 * sq); + float v = rnd(dt, n2 * ldt(g, c)); + if (silu) v = v / (1.0f + std::exp(-v)); + stt(y, yb + c * ys, v); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ d2s_add / s2d_avg_add */ +/* d2s_add, the decoder's upsampling shortcut (Wan's DupUp3D on one frame): x [H, W * cin] repeated + * `rep = cout * F / cin` times per channel and dealt into a 2x larger y [2H, 2W * cout], added: + * y[2r+i, 2c+j, o] += x[r, c, (o * F + off + 2i + j) / rep], F = 4 * ft, off = 4 when ft is 2 + * (the second of the two frames a temporal factor makes is the one a first chunk keeps). */ +int ref_d2s_add(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *y = &a->t[1]; + const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0), ft = p_int(a, "ft", 1); + if (cin <= 0 || cout <= 0 || (ft != 1 && ft != 2)) return RAD_E_SHAPE; + if (x->rank != 2 || y->rank != 2 || x->shape[1] % cin || y->shape[1] % cout) return RAD_E_SHAPE; + const int64_t H = x->shape[0], W = x->shape[1] / cin; + if (y->shape[0] != 2 * H || y->shape[1] / cout != 2 * W) return RAD_E_SHAPE; + const int64_t F = 4 * ft, off = ft == 2 ? 4 : 0; + if ((cout * F) % cin) return RAD_E_SHAPE; + const int64_t rep = cout * F / cin; + const int64_t xr = x->stride[0], yr = y->stride[0]; + #pragma omp parallel for schedule(static) + for (int64_t oy = 0; oy < 2 * H; ++oy) + for (int64_t ox = 0; ox < 2 * W; ++ox) + for (int64_t o = 0; o < cout; ++o) { + const int64_t i = oy & 1, j = ox & 1; + const int64_t ci = (o * F + off + 2 * i + j) / rep; + const int64_t yo = oy * yr + ox * cout + o; + stt(y, yo, ldt(y, yo) + ldt(x, (oy / 2) * xr + (ox / 2) * cin + ci)); + } + return RAD_OK; +} + +/* s2d_avg_add, the encoder's downsampling shortcut (Wan's AvgDown3D on one frame): each 2x2 block + * of x [2H, 2W * cin] dealt into channels and averaged in groups of gs = cin * F / cout into + * y [H, W * cout], added. A channel of the dealt row is (c, t, i, j) at c * F + 4t + 2i + j; with + * ft 2 the frame t == 0 is the zero frame the reference pads in front, which the mean still counts. */ +int ref_s2d_avg_add(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *y = &a->t[1]; + const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0), ft = p_int(a, "ft", 1); + if (cin <= 0 || cout <= 0 || (ft != 1 && ft != 2)) return RAD_E_SHAPE; + if (x->rank != 2 || y->rank != 2 || x->shape[1] % cin || y->shape[1] % cout) return RAD_E_SHAPE; + const int64_t H = y->shape[0], W = y->shape[1] / cout; + if (x->shape[0] != 2 * H || x->shape[1] / cin != 2 * W) return RAD_E_SHAPE; + const int64_t F = 4 * ft; + if ((cin * F) % cout) return RAD_E_SHAPE; + const int64_t gs = cin * F / cout; + const int64_t xr = x->stride[0], yr = y->stride[0]; + #pragma omp parallel for schedule(static) + for (int64_t oy = 0; oy < H; ++oy) + for (int64_t ox = 0; ox < W; ++ox) + for (int64_t o = 0; o < cout; ++o) { + float acc = 0.0f; + for (int64_t gg = 0; gg < gs; ++gg) { + const int64_t g = o * gs + gg; + const int64_t c = g / F, rem = g % F, t = rem / 4, i = (rem % 4) / 2, j = rem % 2; + if (ft == 2 && t == 0) continue; + acc += ldt(x, (2 * oy + i) * xr + (2 * ox + j) * cin + c); + } + const int64_t yo = oy * yr + ox * cout + o; + stt(y, yo, ldt(y, yo) + rnd(y->dtype, acc / (float)gs)); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ to_rgba8 */ +/* A decoded image to bytes the way diffusers' postprocess makes them: v = clamp(x, -1, 1), + * u = clamp(bf16(bf16(v / 2) + 0.5), 0, 1), byte = round-half-even(f32(u) * 255). */ +int ref_to_rgba8(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *y = &a->t[1]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_n(y, n); + if (rows <= 0 || rows_n(x, n) < rows || y->dtype != RAD_U8) return RAD_E_SHAPE; + #pragma omp parallel for schedule(static) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(x, r, n), xs = laststride(x); + const int64_t yb = rowoff(y, r, n), ys = laststride(y); + for (int64_t c = 0; c < n; ++c) { + float v = ldt(x, xb + c * xs); + v = v < -1.0f ? -1.0f : (v > 1.0f ? 1.0f : v); + float u = rbf(rbf(v * 0.5f) + 0.5f); + u = u < 0.0f ? 0.0f : (u > 1.0f ? 1.0f : u); + ((uint8_t*)y->data)[yb + c * ys] = (uint8_t)std::nearbyintf(u * 255.0f); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ gelu_tanh, scatter_add_rows */ +int ref_gelu_tanh(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *y = &a->t[1]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_n(y, n); + if (rows <= 0 || rows_n(x, n) < rows) return RAD_E_SHAPE; + #pragma omp parallel for schedule(static) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(x, r, n), xs = laststride(x); + const int64_t yb = rowoff(y, r, n), ys = laststride(y); + for (int64_t c = 0; c < n; ++c) { + const float v = ldt(x, xb + c * xs); + const float t = std::tanh(0.7978845608028654f * (v + 0.044715f * v * v * v)); + stt(y, yb + c * ys, 0.5f * v * (1.0f + t)); + } + } + return RAD_OK; +} + +/* x[idx[i]] = x[idx[i]] + v[i], rounded to x's dtype; a negative index is a skip. */ +int ref_scatter_add_rows(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *v = &a->t[0], *idx = &a->t[1], *x = &a->t[2]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + const int64_t M = rows_n(v, n), dst_rows = rows_n(x, n); + if (M <= 0 || numel(idx) < M) return RAD_E_SHAPE; + for (int64_t m = 0; m < M; ++m) + if (ld_int(idx->dtype, idx->data, offlin(idx, m)) >= dst_rows) return RAD_E_INVAL; + for (int64_t m = 0; m < M; ++m) { + const int64_t r = ld_int(idx->dtype, idx->data, offlin(idx, m)); + if (r < 0) continue; + const int64_t vb = rowoff(v, m, n), vs = laststride(v); + const int64_t xb = rowoff(x, r, n), xs = laststride(x); + for (int64_t i = 0; i < n; ++i) stt(x, xb + i * xs, ldt(x, xb + i * xs) + ldt(v, vb + i * vs)); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ attn_prefix_self */ +/* Attention over two key sources: the sequence's PREFIX, `seqused[s]` positions in the paged cache, + * and the step's OWN rows, `k` and `v` beside `q` and not in the cache. Self row i of a sequence + * sees every prefix key and, with `causal`, its own rows j <= i -- otherwise all of them. + * + * It is the attention of a sequence whose rows are recomputed each step against a prefix that is + * not: an image's latent rows against the conditioning, or one segment of the conditioning against + * the segments before it. */ +/* quant_act_i8g's rule for one row of `n`: the scale (amax/127, 1 for an all-zero row) and the + * codes rint(clamp(x * (1/scale), +-127)), in f32 as the device computes them. `code` may be `x`: + * each code is written after its value is read. */ +static float ref_q8_row(const float* x, int64_t n, float* code) { + float am = 0.0f; + for (int64_t d = 0; d < n; ++d) am = std::max(am, std::fabs(x[d])); + const float sc = am > 0.0f ? am * (1.0f / 127.0f) : 1.0f; + const float inv = 1.0f / sc; + for (int64_t d = 0; d < n; ++d) + code[d] = std::rint(std::min(std::max(x[d] * inv, -127.0f), 127.0f)); + return sc; +} + +int ref_attn_prefix_self(const RadArgs* a, RadStream) { + if (a->n_t < 12) return RAD_E_INVAL; + const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *kv = &a->t[3]; + const RadTensor *bt = &a->t[4], *su = &a->t[5], *cu = &a->t[6], *o = &a->t[11]; + const RadTensor *kdes = t_in(a, 7), *vdes = t_in(a, 8); + /* THE INT8 Q.K FORM: the own keys' codes and scales given, everything else quantised here. */ + const RadTensor *k8 = t_in(a, 9), *ks = t_in(a, 10); + const char* qk = p_str(a, "qk", "bf16"); + const bool i8 = std::strcmp(qk, "i8") == 0; + if (i8 != (k8 != nullptr) || i8 != (ks != nullptr)) return RAD_E_INVAL; + if (i8 && (kdes || vdes)) return RAD_E_UNSUPPORTED; + const int64_t head_dim = p_int(a, "head_dim", 0), gqa = p_int(a, "gqa", 1); + const int causal = (int)p_int(a, "causal", 0); + const int64_t block_size = kv->rank == 4 ? kv->shape[2] : p_int(a, "block_size", 0); + if (head_dim <= 0 || gqa <= 0 || block_size <= 0) return RAD_E_SHAPE; + if (head_dim > 1024) return RAD_E_UNSUPPORTED; + const int64_t kv_heads = kv->rank == 4 ? kv->shape[1] : 0; + if (kv_heads <= 0) return RAD_E_SHAPE; + const int64_t q_heads = kv_heads * gqa, n_seq = numel(cu) - 1; + if (n_seq <= 0 || numel(su) < n_seq) return RAD_E_SHAPE; + /* The rows are cu's own span, which need not start at 0: one segment of a longer sequence is + * passed as the two offsets that bound it. */ + const int64_t r_first = cu_at(cu, 0), rows = cu_at(cu, n_seq) - r_first; + const int64_t max_blocks = bt->rank >= 2 ? bt->shape[1] : numel(bt) / n_seq; + const int64_t bt_rs = bt->rank >= 2 ? bt->stride[0] : max_blocks; + const int64_t q_rs = row_stride(q, q_heads * head_dim), k_rs = row_stride(k, kv_heads * head_dim); + const int64_t v_rs = row_stride(v, kv_heads * head_dim), o_rs = row_stride(o, q_heads * head_dim); + const int64_t k8_rs = i8 ? row_stride(k8, kv_heads * head_dim) : 0; + const int64_t ks_rs = i8 ? row_stride(ks, kv_heads) : 0; + const int64_t sb = kv->stride[0], sh = kv->stride[1], so = kv->stride[2]; + const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim)); + #pragma omp parallel for schedule(dynamic) + for (int64_t idx = 0; idx < rows * q_heads; ++idx) { + const int64_t h = idx % q_heads, r = r_first + idx / q_heads, kh = h / gqa; + const int64_t s = seq_of(cu, n_seq, r), b0 = cu_at(cu, s), b1 = cu_at(cu, s + 1); + const int64_t i = r - b0, P = ld_int(su->dtype, su->data, offlin(su, s)); + const float kds = kdes ? ldt(kdes, s * kv_heads + kh) : 1.0f; + const float vds = vdes ? ldt(vdes, s * kv_heads + kh) : 1.0f; + const int64_t qb = r * q_rs + h * head_dim; + const int64_t nself = causal ? i + 1 : b1 - b0; + auto pkey = [&](int64_t j, int64_t d, bool val) -> float { + const int64_t blk = ld_int(bt->dtype, bt->data, s * bt_rs + j / block_size); + if (blk < 0) return 0.0f; + return ldt(kv, blk * sb + kh * sh + (j % block_size) * so + (val ? head_dim : 0) + d) * + (val ? vds : kds); + }; + float xq[1024], cq[1024], ck[1024]; + float sq = 1.0f; + if (i8) { + for (int64_t d = 0; d < head_dim; ++d) xq[d] = ldt(q, qb + d); + sq = ref_q8_row(xq, head_dim, cq); + } + auto dot = [&](int64_t j) -> float { + if (i8) { + float sk = 0.0f; + if (j < P) { + for (int64_t d = 0; d < head_dim; ++d) ck[d] = pkey(j, d, false); + sk = ref_q8_row(ck, head_dim, ck); + } else { + const int64_t row = b0 + j - P; + for (int64_t d = 0; d < head_dim; ++d) + ck[d] = ldt(k8, row * k8_rs + kh * head_dim + d); + sk = ldt(ks, row * ks_rs + kh); + } + /* Integers below 2^24 in magnitude: the f32 sum is exact. */ + float acc = 0.0f; + for (int64_t d = 0; d < head_dim; ++d) acc += cq[d] * ck[d]; + return acc * sq * sk * scale; + } + float acc = 0.0f; + if (j < P) { + for (int64_t d = 0; d < head_dim; ++d) acc += ldt(q, qb + d) * pkey(j, d, false); + } else { + const int64_t kb = (b0 + j - P) * k_rs + kh * head_dim; + for (int64_t d = 0; d < head_dim; ++d) acc += ldt(q, qb + d) * ldt(k, kb + d); + } + return acc * scale; + }; + const int64_t nk = P + nself; + float mx = -INFINITY; + for (int64_t j = 0; j < nk; ++j) mx = std::max(mx, dot(j)); + float acc[1024]; + for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f; + float sum = 0.0f; + for (int64_t j = 0; j < nk; ++j) { + const float wgt = ref_exp(dot(j) - mx); + sum += wgt; + if (j < P) { + for (int64_t d = 0; d < head_dim; ++d) acc[d] += wgt * pkey(j, d, true); + } else { + const int64_t vb = (b0 + j - P) * v_rs + kh * head_dim; + for (int64_t d = 0; d < head_dim; ++d) acc[d] += wgt * ldt(v, vb + d); + } + } + const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; + const int64_t ob = r * o_rs + h * head_dim; + for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d, acc[d] * inv); + } + return RAD_OK; +} diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 3117c0aa..cb613ce2 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -133,6 +133,25 @@ int ref_kv_store (const RadArgs*, RadStream); int ref_rope (const RadArgs*, RadStream); int ref_rope_table (const RadArgs*, RadStream); int ref_qk_norm_rope (const RadArgs*, RadStream); +/* image generation (ref_gen.cpp) */ +int ref_ln_mod(const RadArgs*, RadStream); +int ref_ln_mod_quant_fp8(const RadArgs*, RadStream); +int ref_gate_add(const RadArgs*, RadStream); +int ref_timestep_embed(const RadArgs*, RadStream); +int ref_gather_rows2(const RadArgs*, RadStream); +int ref_lane_gather(const RadArgs*, RadStream); +int ref_lane_store(const RadArgs*, RadStream); +int ref_randn_lanes(const RadArgs*, RadStream); +int ref_flow_euler(const RadArgs*, RadStream); +int ref_chan_affine(const RadArgs*, RadStream); +int ref_conv2d_nhwc(const RadArgs*, RadStream); +int ref_l2norm_chan(const RadArgs*, RadStream); +int ref_d2s_add(const RadArgs*, RadStream); +int ref_s2d_avg_add(const RadArgs*, RadStream); +int ref_to_rgba8(const RadArgs*, RadStream); +int ref_gelu_tanh(const RadArgs*, RadStream); +int ref_scatter_add_rows(const RadArgs*, RadStream); +int ref_attn_prefix_self(const RadArgs*, RadStream); int ref_qsa_block_key (const RadArgs*, RadStream); /* ---- mixture of experts */ @@ -268,6 +287,24 @@ REF_SHAPE_FN(ref_kv_store); REF_SHAPE_FN(ref_rope); REF_SHAPE_FN(ref_rope_table); REF_SHAPE_FN(ref_qk_norm_rope); +REF_SHAPE_FN(ref_ln_mod); +REF_SHAPE_FN(ref_ln_mod_quant_fp8); +REF_SHAPE_FN(ref_gate_add); +REF_SHAPE_FN(ref_timestep_embed); +REF_SHAPE_FN(ref_gather_rows2); +REF_SHAPE_FN(ref_lane_gather); +REF_SHAPE_FN(ref_lane_store); +REF_SHAPE_FN(ref_randn_lanes); +REF_SHAPE_FN(ref_flow_euler); +REF_SHAPE_FN(ref_chan_affine); +REF_SHAPE_FN(ref_conv2d_nhwc); +REF_SHAPE_FN(ref_l2norm_chan); +REF_SHAPE_FN(ref_d2s_add); +REF_SHAPE_FN(ref_s2d_avg_add); +REF_SHAPE_FN(ref_to_rgba8); +REF_SHAPE_FN(ref_gelu_tanh); +REF_SHAPE_FN(ref_scatter_add_rows); +REF_SHAPE_FN(ref_attn_prefix_self); REF_SHAPE_FN(ref_qsa_block_key); REF_SHAPE_FN(ref_router_topk); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index ab592e9d..5bbaac8c 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -544,7 +544,7 @@ static const RadOperandSpec oGatedNorm[] = { OPD("x"), OPD("z"), WGT("w"), OUT(" /* ---- collectives -------------------------------------------------------------------------- */ static const RadParamSpec pAllReduce[] = { P_INT("world_size"), P_INT("numel"), P_STR("dtype"), P_INT("exact"), P_INTO("min_bytes"), - P_INTO("hops") }; + P_INTO("hops"), P_INTO("overlap") }; /* `y` is an optional SECOND operand: absent means in place, which is what docs/OPS.md draws and * what every one-shot kernel does. libr4d's two-shot rows are not safe in place -- a rank gathers * into the output while its own input is still being read for the scatter -- so they need the @@ -642,6 +642,46 @@ static const RadOperandSpec oPick[] = { OPD("cand_idx"), OPD("cand_val"), O static const RadOperandSpec oMerge[] = { OPD("gathered"), OPD("params"), OUT("cand_idx"), OUT("cand_val") }; +/* ---- image generation (ref_gen.cpp) --------------------------------------------------------- */ +static const RadParamSpec pLnMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype") }; +static const RadOperandSpec oLnMod[] = { OPD("x"), OPD("s"), OPD("cu_seqlens"), OUT("y") }; +static const RadOperandSpec oGateAdd[] = { OPD("y"), OPD("g"), OPD("cu_seqlens"), INOUT("x") }; +static const RadParamSpec pLnModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"), + P_INT("gated"), P_STR("dtype") }; +static const RadOperandSpec oLnModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), OPD("cu_seqlens"), + INOUT("x"), OUT("q"), OUT("scale"), OUT_O("z") }; +static const RadParamSpec pTimestep[] = { P_INT("M"), P_INT("n"), P_F64("scale"), P_F64("max_period"), + P_INTO("round"), P_STR("dtype") }; +static const RadOperandSpec oTimestep[] = { OPD("t"), OUT("y") }; +static const RadOperandSpec oGather2[] = { OPD("a"), OPD("b"), OPD("idx"), OUT("y") }; +static const RadParamSpec pLane[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_STR("dtype") }; +static const RadOperandSpec oLaneGather[] = { OPD("src"), OPD("lane"), OPD("cu_seqlens"), OUT("y") }; +static const RadOperandSpec oLaneStore[] = { OPD("src"), OPD("lane"), INOUT("dst") }; +static const RadOperandSpec oRandnLanes[] = { OPD("flags"), OPD("seed"), OPD("lane"), + OPD("cu_seqlens"), INOUT("dst") }; +static const RadOperandSpec oFlowEuler[] = { OPD("v"), OPD("sigma"), OPD("sigma_next"), OPD("cfg"), + OPD("pair"), OPD("lane"), OPD("flags"), OPD("seed"), + OPD("cu_seqlens"), OPD_O("inp_lat"), OPD_O("inp_mask"), + INOUT("state"), INOUT_O("preview") }; +static const RadParamSpec pChanAffine[] = { P_INT("M"), P_INT("n"), P_STR("mul"), P_STR("add"), + P_STR("mode"), P_STR("dtype") }; +static const RadParamSpec pConvNhwc[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"), + P_INT("stride"), P_STR("pad"), P_INT("up"), P_STR("dtype") }; +static const RadOperandSpec oConvNhwc[] = { OPD("x"), WGT("w"), WGT("b"), OUT("y") }; +static const RadParamSpec pL2Norm[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") }; +static const RadOperandSpec oL2Norm[] = { OPD("x"), WGT("gamma"), OUT("y") }; +static const RadParamSpec pSpaceDepth[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("ft"), + P_STR("dtype") }; +static const RadOperandSpec oSpaceDepth[] = { OPD("x"), INOUT("y") }; +static const RadParamSpec pAttnPS[] = { P_INT("q_len"), P_INT("head_dim"), P_INT("gqa"), + P_INTD("block_size"), P_INT("causal"), P_STR("q_dtype"), + P_STR("kv_dtype"), P_F64O("scale"), P_INTO("max_ctx"), + P_INTO("n_head"), P_INTO("max_seqs"), P_STRO("qk") }; +static const RadOperandSpec oAttnPS[] = { OPD("q"), OPD("k"), OPD("v"), OPD("kv_cache"), + OPD("block_table"), OPD("seqused"), OPD("cu_seqlens"), + OPD_O("k_descale"), OPD_O("v_descale"), OPD_O("k_i8"), + OPD_O("k_scale"), OUT("out") }; + /* ================================================================== the schema table */ static const RadOpSchema kSchemas[] = { { "rmsnorm", ARR(pRmsnorm), ARR(oRmsnorm), @@ -1041,7 +1081,7 @@ static const RadOpSchema kSchemas[] = { "is a no-op. On the host backend the ranks are threads in one address space, so this is a " "rendezvous rather than a transfer. exact=0 is served exactly, so `min_bytes` -- the byte " "floor under which a lossy row must serve the message exactly anyway -- is accepted and " - "ignored, as is `hops`. " + "ignored, as is `hops`, and so is `overlap` (the caller issues it beside compute). " "`y` absent is the in-place form; present, the sum lands in y and x is left alone." }, { "all_gather", ARR(pAllGather), ARR(oAllGather), "y is [world_size * numel] with rank r's contribution at offset r * numel. `row` -- one row of " @@ -1111,6 +1151,67 @@ static const RadOpSchema kSchemas[] = { { "sample_logprobs", ARR(pLogprobs), ARR(oLogprobs), "For a row with RAD_SP_LOGPROBS: the raw logits' max, sum of exp(l - max) and k largest as (id, " "logit) pairs, descending, ties to the lower id. Other rows are not written." }, +/* ---- image generation -------------------------------------------------------------------- */ +{ "ln_mod_quant_fp8", ARR(pLnModQ), ARR(oLnModQ), + "the DiT block's norm in front of a quantised linear, in one pass: with `gated` 1 the branch " + "before it is added first, x = bf16(x + bf16(bf16(tanh(g[seq])) * y)); then z = ln_mod(x) and " + "(q, scale) = quant_act_fp8(z, group) -- written when bound, z." }, +{ "ln_mod", ARR(pLnMod), ARR(oLnMod), + "y = bf16(bf16(LN(x)) * bf16(1 + s[seq])): a layer norm with no gain or bias, then the row's " + "sequence's modulation row of `s` ([n_seq, >= n] at its own pitch). A diffusion transformer's " + "adaptive norm without a shift." }, +{ "gate_add", ARR(pMnD), ARR(oGateAdd), + "x = bf16(x + bf16(bf16(tanh(g[seq])) * y)): a residual added through its sequence's gate row." }, +{ "timestep_embed", ARR(pTimestep), ARR(oTimestep), + "the sinusoidal timestep embedding, [cos | sin] of t' * exp(-ln(max_period) * i / (n/2)) with " + "t' = scale * t; `round` 1 takes t through bf16 at scale and back first, as diffusers' " + "pipeline hands it to its transformer." }, +{ "gather_rows2", ARR(pMnD), ARR(oGather2), + "y[i] = idx[i] >= 0 ? a[idx[i]] : b[-1 - idx[i]]: a sequence assembled from two sources." }, +{ "lane_gather", ARR(pLane), ARR(oLaneGather), + "y[cu[e] + k] = src[lane[e] * stride + k]: each entry's rows out of its lane of a per-image " + "state." }, +{ "lane_store", ARR(pLane), ARR(oLaneStore), + "dst[l * stride + k] = src[k] for every lane l listed: one source's rows into several lanes." }, +{ "randn_lanes", ARR(pLane), ARR(oRandnLanes), + "an image's first step: its lane's rows become its seed's standard-normal stream " + "(abi/rad_philox.h), element (k, c) the stream's k * n + c; entries without flag 1 are left." }, +{ "flow_euler", ARR(pLane), ARR(oFlowEuler), + "one Euler step of a flow-matching sampler per entry that moves a lane: guidance against the " + "paired entry, x' = bf16(x + bf16(bf16(sigma_next - sigma) * v)), a preview of the clean " + "latent with flag 4, the kept region of a repaint restored with flag 2 (docs/OPS.md)." }, +{ "chan_affine", ARR(pChanAffine), ARR(oUnary), + "a per-channel affine from two parameter lists of n values (rounded to bf16): `fma` is " + "bf16(bf16(x * mul) + add), `inv` bf16(bf16(x - add) / mul)." }, +{ "conv2d_nhwc", ARR(pConvNhwc), ARR(oConvNhwc), + "an image convolution, channels innermost: x [Hin, Win * cin] and y [Hout, Wout * cout] dense, " + "the sizes read off them; PyTorch's [cout, cin, k, k] weight and a bias; `up` 2 reads the input " + "upsampled nearest-neighbour; `pad` same (k/2 a side) or down (0 above and left, 1 below and " + "right)." }, +{ "l2norm_chan", ARR(pL2Norm), ARR(oL2Norm), + "each row normalised to unit L2 (eps 1e-12), times sqrt(n), times gamma -- three bf16 roundings " + "-- then `act` none or silu: an image decoder's channel norm." }, +{ "d2s_add", ARR(pSpaceDepth), ARR(oSpaceDepth), + "y [2H, 2W * cout] += x [H, W * cin] repeated and dealt into 2x2 blocks: an upsampling " + "shortcut (Wan's DupUp3D on one frame; ft 2 keeps the second frame)." }, +{ "s2d_avg_add", ARR(pSpaceDepth), ARR(oSpaceDepth), + "y [H, W * cout] += the 2x2 blocks of x [2H, 2W * cin] dealt into channels and averaged in " + "groups: a downsampling shortcut (Wan's AvgDown3D on one frame; ft 2 counts the zero frame)." }, +{ "to_rgba8", ARR(pMnD), ARR(oUnary), + "decoded pixels in [-1, 1] to bytes as diffusers' postprocess makes them: " + "round(clamp(bf16(bf16(clamp(x) / 2) + 0.5), 0, 1) * 255), u8 out." }, +{ "gelu_tanh", ARR(pMnD), ARR(oUnary), "the tanh approximation of gelu." }, +{ "scatter_add_rows", ARR(pMnD), ARR(oScatterRows), + "x[idx[i]] += v[i], rounded to x's dtype; a negative index adds nothing." }, +{ "attn_prefix_self", ARR(pAttnPS), ARR(oAttnPS), + "attention over two key sources: `seqused[s]` prefix positions in the paged cache and the " + "step's own rows `k`/`v` beside `q`; self row i sees every prefix key and its own rows j <= i " + "with `causal`, all of them without. `qk` \"i8\" with `k_i8` [tokens, kv_heads * head_dim] and " + "`k_scale` [tokens, kv_heads] selects the int8 Q.K form: they are the own keys as quant_act_i8g " + "writes them at group head_dim (scale amax/127, 1 for an all-zero row; code " + "rint(clamp(x * (1/scale), +-127))), the query and each prefix key are quantised by the same " + "rule per (row, head), and a score is the exact integer dot product times both scales. `k` is " + "then not read for the own rows." }, }; /* ================================================================== the kernel table */ @@ -1361,6 +1462,40 @@ SIMPLE("ref_sample_xtc", "sample_xtc", "sample", "exclude-top-choices narrowing DT_FLOAT, ref_sample_xtc), SIMPLE("ref_sample_merge_topk", "sample_merge_topk", "sample", "vocab-parallel candidate merge", DT_FLOAT, ref_sample_merge_topk), +SIMPLE("ref_ln_mod", "ln_mod", "norm", "gainless layer norm times (1 + a sequence's scale row)", + DT_FLOAT, ref_ln_mod), +SIMPLE("ref_gate_add", "gate_add", "elem", "x += tanh(gate row) * y", DT_FLOAT, ref_gate_add), +SIMPLE("ref_ln_mod_quant_fp8", "ln_mod_quant_fp8", "norm", + "gated residual, gainless layer norm times (1 + scale row), block-scaled E4M3", + DT_FLOAT, ref_ln_mod_quant_fp8), +SIMPLE("ref_timestep_embed", "timestep_embed", "elem", "sinusoidal timestep embedding", + DT_FLOAT, ref_timestep_embed), +SIMPLE("ref_gather_rows2", "gather_rows2", "elem", "rows from two sources by a signed index", + DT_ANY, ref_gather_rows2), +SIMPLE("ref_lane_gather", "lane_gather", "elem", "each entry's rows out of its lane", DT_ANY, + ref_lane_gather), +SIMPLE("ref_lane_store", "lane_store", "elem", "one source's rows into several lanes", DT_ANY, + ref_lane_store), +SIMPLE("ref_randn_lanes", "randn_lanes", "elem", "a lane's rows from its seed's normal stream", + DT_FLOAT, ref_randn_lanes), +SIMPLE("ref_flow_euler", "flow_euler", "elem", "a flow-matching Euler step with guidance", + DT_FLOAT, ref_flow_euler), +SIMPLE("ref_chan_affine", "chan_affine", "elem", "a per-channel affine from parameter lists", + DT_FLOAT, ref_chan_affine), +SIMPLE("ref_conv2d_nhwc", "conv2d_nhwc", "elem", "an image convolution, channels innermost", + DT_FLOAT, ref_conv2d_nhwc), +SIMPLE("ref_l2norm_chan", "l2norm_chan", "norm", "unit-L2 channel norm, scaled, optional silu", + DT_FLOAT, ref_l2norm_chan), +SIMPLE("ref_d2s_add", "d2s_add", "elem", "an upsampling shortcut added in", DT_FLOAT, + ref_d2s_add), +SIMPLE("ref_s2d_avg_add", "s2d_avg_add", "elem", "a downsampling shortcut added in", DT_FLOAT, + ref_s2d_avg_add), +SIMPLE("ref_to_rgba8", "to_rgba8", "elem", "decoded pixels to bytes", DT_FLOAT, ref_to_rgba8), +SIMPLE("ref_gelu_tanh", "gelu_tanh", "elem", "tanh gelu", DT_FLOAT, ref_gelu_tanh), +SIMPLE("ref_scatter_add_rows", "scatter_add_rows", "elem", "x[idx[i]] += v[i]", DT_FLOAT, + ref_scatter_add_rows), +SIMPLE("ref_attn_prefix_self", "attn_prefix_self", "attn", + "attention over a paged prefix and the step's own rows", DT_FLOAT, ref_attn_prefix_self), }; /* ================================================================== plugin exports */ diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index cbd6bf6d..fb9532dd 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -89,6 +89,7 @@ #include "rad_plugin.h" #include "rad_sample.h" +#include #include #include #include @@ -2136,3 +2137,275 @@ int ref_sample_pick_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o int ref_sample_merge_topk_shape(const RadParam*, int, int, RadOpdDesc*) { return RAD_E_UNSUPPORTED; } + +/* ================================================================== image generation (ref_gen.cpp) + * + * The row-wise ones are described; the rest DECLINE. A lane op's indices are lanes of a state the + * case would have to size to match them, a flow step's entries pair across the batch, and an image + * op reads its height and width off its operands -- each a case a cold draw would make up, and a + * description that makes up a case tests the bounds handling and calls it correctness. */ +int ref_ln_mod_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); + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M, n }); /* x */ + o.t(D, { 1, n }); /* s: one sequence */ + o.t_idx({ 2 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ + o.t(D, { M, n }); /* y */ + return o.finish("ln_mod", operand, out); +} +int ref_ln_mod_quant_fp8_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); + const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0)); + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M, n }); /* y */ + o.t(D, { 1, n }); /* g: one sequence */ + o.t(D, { 1, n }); /* s */ + o.t_idx({ 2 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ + o.t(D, { M, n }); /* x, INOUT */ + o.t((uint32_t)RAD_F8E4M3, { M, n }); /* q */ + o.t((uint32_t)RAD_F32, { M, ng }); /* scale */ + o.t(D, { M, n }); /* z */ + return o.finish("ln_mod_quant_fp8", operand, out); +} +int ref_gate_add_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); + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M, n }); /* y */ + o.t(D, { 1, n }); /* g */ + o.t_idx({ 2 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ + o.t(D, { M, n }); /* x */ + return o.finish("gate_add", operand, out); +} +int ref_timestep_embed_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); + Opd o; + o.t_fill((uint32_t)RAD_F32, { M }, (uint32_t)RAD_FILL_SIGMOID, 0); /* t: a sigma in (0, 1) */ + o.t(act_dt(p, n_p), { M, n }); /* y */ + return o.finish("timestep_embed", operand, out); +} +int ref_gather_rows2_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + (void)p; (void)n_p; (void)operand; (void)out; + return RAD_E_UNSUPPORTED; /* a signed index: half its draw would have to be negative */ +} +/* ---- the image generator's per-lane ops. A LANE is one image's slot of a state buffer, `stride` + * rows apart; an entry of the step reads or writes its own lane. Four lanes is the smallest count + * that leaves lanes no entry touches, so a write into the wrong lane shows as a difference in + * one that should have kept its fill. The entries are as many as the rows need at `stride` a + * piece (one, unless M is longer than a lane), split by cu_seqlens. */ +enum { REF_LANES = 4 }; +static int64_t lane_entries(const RadParam* p, int n_p, int64_t M, int64_t stride) { + const int64_t s = n_seq_of(p, n_p), need = (M + stride - 1) / stride; + return std::min(std::max(s, need), REF_LANES); +} + +int ref_lane_gather_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), st = gi(p, n_p, "stride", 0); + if (M <= 0 || n <= 0 || st <= 0) return RAD_E_UNSUPPORTED; + const int64_t S = lane_entries(p, n_p, M, st); + if (M > S * st) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { REF_LANES * st, n }); /* src: every lane */ + o.t_idx({ S }, REF_LANES, -1, 0); /* lane: may repeat */ + o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ + o.t(D, { M, n }); /* y */ + return o.finish("lane_gather", operand, out); +} + +int ref_lane_store_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), st = gi(p, n_p, "stride", 0); + if (M <= 0 || n <= 0 || st <= 0 || M > st) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M, n }); /* src */ + /* Distinct, two of the four: one image stored to the lanes of its guided pair. */ + o.t_idx({ 2 }, REF_LANES, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* lane */ + o.t(D, { REF_LANES * st, n }); /* dst, INOUT */ + return o.finish("lane_store", operand, out); +} + +int ref_randn_lanes_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), st = gi(p, n_p, "stride", 0); + if (M <= 0 || n <= 0 || st <= 0) return RAD_E_UNSUPPORTED; + const int64_t S = lane_entries(p, n_p, M, st); + if (M > S * st) return RAD_E_UNSUPPORTED; + Opd o; + /* Flags drawn over all three bits, so some entries are first steps and some are left. */ + o.t_idx({ S }, 8, -1, 0); /* flags */ + o.t_idx({ 2 * S }, (int64_t)1 << 30, -1, 0); /* seed: two words an entry */ + /* Distinct: two first steps in one lane would be a race between their seeds. */ + o.t_idx({ S }, REF_LANES, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* lane */ + o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ + o.t((uint32_t)RAD_BF16, { REF_LANES * st, n }); /* dst, INOUT */ + return o.finish("randn_lanes", operand, out); +} + +int ref_flow_euler_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), st = gi(p, n_p, "stride", 0); + if (M <= 0 || n <= 0 || st <= 0) return RAD_E_UNSUPPORTED; + /* TWO ENTRIES OF EQUAL LENGTH where M allows, so a pair drawn from {0, 1} is always legal: + * an entry guided against the other, or against itself. -1 and -2 are not drawable, so the + * unguided and the parked entry are left to the engine's own tests. */ + const int64_t S = (M % 2 == 0 && M / 2 <= st) ? 2 : 1; + if (M > S * st) return RAD_E_UNSUPPORTED; + const uint32_t F = (uint32_t)RAD_F32, B = (uint32_t)RAD_BF16; + Opd o; + o.t(B, { M, n }); /* v */ + o.t(F, { S }); /* sigma */ + o.t(F, { S }); /* sigma_next */ + o.t(F, { S }); /* cfg */ + o.t_idx({ S }, S, -1, 0); /* pair */ + o.t_idx({ S }, REF_LANES, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* lane */ + o.t_idx({ S }, 8, -1, 0); /* flags: preview and repaint drawn */ + o.t_idx({ 2 * S }, (int64_t)1 << 30, -1, 0); /* seed */ + o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ + o.t(B, { REF_LANES * st, n }); /* inp_lat */ + o.t(F, { REF_LANES * st }); /* inp_mask */ + o.t(B, { REF_LANES * st, n }); /* state, INOUT */ + o.t(B, { REF_LANES * st, n }); /* preview, INOUT */ + return o.finish("flow_euler", operand, out); +} + +/* ---- an image decoder's convolutions and shortcuts. Both sizes are read off the operands, and + * M counts the OUTPUT's pixels, so the picture's shape is this description's to choose: eight + * columns where M allows -- a row then has both edges and an interior -- and the input whatever + * makes that output. A shape no input produces is declined rather than bent. */ +static int64_t cols_for(int64_t M, int64_t mult) { + for (int64_t w = 8; w >= 1; w /= 2) + if (w % mult == 0 && M % w == 0 && (M / w) % mult == 0) return w; + return 0; +} + +int ref_conv2d_nhwc_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), stride = gi(p, n_p, "stride", 1); + const int64_t up = gi(p, n_p, "up", 1); + const char* pad = gs(p, n_p, "pad"); + if (M <= 0 || cin <= 0 || cout <= 0 || k <= 0 || stride <= 0 || up <= 0) + return RAD_E_UNSUPPORTED; + const bool down = pad && !std::strcmp(pad, "down"); + const int64_t pads = down ? 1 : 2 * (k / 2); + const int64_t Wo = cols_for(M, 1), Ho = Wo ? M / Wo : 0; + if (!Wo) return RAD_E_UNSUPPORTED; + /* The smallest upsampled input the output needs, which must be a whole input at `up`. */ + const int64_t Hv = (Ho - 1) * stride + k - pads, Wv = (Wo - 1) * stride + k - pads; + if (Hv <= 0 || Wv <= 0 || Hv % up || Wv % up) return RAD_E_UNSUPPORTED; + if ((Hv + pads - k) / stride + 1 != Ho || (Wv + pads - k) / stride + 1 != Wo) + return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { Hv / up, (Wv / up) * cin }); /* x */ + o.t(D, { cout, cin, k, k }); /* w */ + o.t(D, { cout }); /* b */ + o.t(D, { Ho, Wo * cout }); /* y */ + return o.finish("conv2d_nhwc", operand, out); +} + +int ref_d2s_add_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); + if (M <= 0 || cin <= 0 || cout <= 0) return RAD_E_UNSUPPORTED; + const int64_t Wo = cols_for(M, 2); + if (!Wo) return RAD_E_UNSUPPORTED; + const int64_t Ho = M / Wo; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { Ho / 2, (Wo / 2) * cin }); /* x */ + o.t(D, { Ho, Wo * cout }); /* y, INOUT */ + return o.finish("d2s_add", operand, out); +} + +int ref_s2d_avg_add_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); + if (M <= 0 || cin <= 0 || cout <= 0) return RAD_E_UNSUPPORTED; + const int64_t Wo = cols_for(M, 1), Ho = Wo ? M / Wo : 0; + if (!Wo) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { 2 * Ho, 2 * Wo * cin }); /* x */ + o.t(D, { Ho, Wo * cout }); /* y, INOUT */ + return o.finish("s2d_avg_add", operand, out); +} + +/* ---- attention over a paged prefix and the step's own rows. The prefix is `ctx` deep when the + * harness sweeps depth and 37 otherwise: two whole blocks and a part of a third, so both the + * block-table walk and the partial block's bound run. */ +int ref_attn_prefix_self_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "q_len", 0); + const int64_t hd = gi(p, n_p, "head_dim", 0); + const int64_t bs = gi(p, n_p, "block_size", 16); + const int64_t gqa = gi(p, n_p, "gqa", 1); + const int64_t nh = gi(p, n_p, "n_head", gqa); + if (M <= 0 || hd <= 0 || bs <= 0 || gqa <= 0 || nh <= 0 || nh % gqa) return RAD_E_UNSUPPORTED; + const int64_t kvh = nh / gqa, S = n_seq_of(p, n_p); + int64_t P = gi(p, n_p, "ctx", 0); + if (P <= 0) P = 37; + const int64_t max_blocks = (P + bs - 1) / bs; + const uint32_t Q = act_dt(p, n_p); + const uint32_t kv = dt_parse(gs(p, n_p, "kv_dtype")); + const uint32_t KV = kv == (uint32_t)RAD_DT_INVALID ? Q : kv; + Opd o; + o.t(Q, { M, nh, hd }); /* q */ + o.t(Q, { M, kvh, hd }); /* k */ + o.t(Q, { M, kvh, hd }); /* v */ + o.t(KV, { S * max_blocks, kvh, bs, 2 * hd }); /* kv_cache */ + o.t_idx({ S, max_blocks }, S * max_blocks, -1, 0); /* block_table: may repeat */ + o.t_idx({ S }, 0, P, 0); /* seqused: the prefix depth */ + o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ + o.skip(); /* k_descale */ + o.skip(); /* v_descale */ + const char* qk = gs(p, n_p, "qk"); + if (qk && !std::strcmp(qk, "i8")) { + o.t((uint32_t)RAD_I8, { M, kvh, hd }); /* k_i8 */ + o.t((uint32_t)RAD_F32, { M, kvh }); /* k_scale */ + } else { + o.skip(); + o.skip(); + } + o.t(Q, { M, nh, hd }); /* out */ + return o.finish("attn_prefix_self", operand, out); +} + +int ref_chan_affine_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); + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M, n }); + o.t(D, { M, n }); + return o.finish("chan_affine", operand, out); +} +int ref_l2norm_chan_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); + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M, n }); /* x */ + o.t(D, { n }); /* gamma */ + o.t(D, { M, n }); /* y */ + return o.finish("l2norm_chan", operand, out); +} +int ref_to_rgba8_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); + Opd o; + o.t(act_dt(p, n_p), { M, n }); + o.t((uint32_t)RAD_U8, { M, n }); + return o.finish("to_rgba8", operand, out); +} +int ref_gelu_tanh_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); + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M, n }); + o.t(D, { M, n }); + return o.finish("gelu_tanh", operand, out); +} +int ref_scatter_add_rows_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + Opd o; + o.t(D, { M, n }); /* v */ + o.t_idx({ M }, 4 * M, -1, RAD_OPD_F_IDX_UNIQUE); /* idx, distinct destinations */ + o.t(D, { 4 * M, n }); /* x, inout */ + return o.finish("scatter_add_rows", operand, out); +} diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 8ed08605..7de932b4 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -283,6 +283,12 @@ TEST(op_vocabulary) { "sample_penalties", "sample_dry", "sample_temp", "sample_topk", "sample_topp", "sample_minp", "sample_typical", "sample_xtc", "sample_mask", "sample_pick", "sample_argmax", "sample_merge_topk", "sample_logprobs", + /* The image generator's (arch/qwenimage21): a DiT's modulation and gates, the per-lane + * sampler state, the VAE's convolutions and shortcuts, attention over a cached prefix. */ + "ln_mod", "gate_add", "timestep_embed", "gather_rows2", "lane_gather", "lane_store", + "randn_lanes", "flow_euler", "chan_affine", "conv2d_nhwc", "l2norm_chan", "d2s_add", + "s2d_avg_add", "to_rgba8", "gelu_tanh", "scatter_add_rows", "attn_prefix_self", + "ln_mod_quant_fp8", }; for (const char* op : kOps) { if (!kern(op)) fprintf(stderr, " missing op '%s'\n", op); diff --git a/tools/rad_convert.cpp b/tools/rad_convert.cpp index 9d697203..5bf39570 100644 --- a/tools/rad_convert.cpp +++ b/tools/rad_convert.cpp @@ -904,8 +904,8 @@ int main(int argc, char** argv) { w.abort(); return 1; } - } else if (file_exists(ck.dir() + "/tokenizer.json")) { - const std::string tj = ck.dir() + "/tokenizer.json"; + } else if (file_exists(ck.tok_dir() + "/tokenizer.json")) { + const std::string tj = ck.tok_dir() + "/tokenizer.json"; RAD_INFO("vocab %s", tj.c_str()); if (parse_tokenizer_json(tj.c_str(), vb) < 0) { w.abort(); return 1; } } else {