Archived
radiance 1.7.0
- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves every shipped container - Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime - /v1/messages works with Claude Code as it ships (gearwave00001) - a long agent conversation keeps its cached history when the client rewrites its last turn (manueloverride) - a stream's first event goes out with the first token, so llama-benchy measures prefill right - opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42) - four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b) - NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA adapters (baKon) - many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool arguments and the CPU's vision and audio encoders - plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
1 parent
b068190326
commit
1e968f6e1d
739 files changed
+128447
-84632
No files matched your search
@@ -82,6 +82,12 @@ inline unsigned muldiv255(unsigned a, unsigned b) {
|
||||
|
||||
void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out) {
|
||||
const int iw = src.w, ih = src.h;
|
||||
/* Image.resize returns a copy at the same size. The premultiplied round trip below is not
|
||||
* lossless where alpha is below 255. */
|
||||
if (w == iw && h == ih) {
|
||||
*out = src;
|
||||
return;
|
||||
}
|
||||
/* RGBA -> RGBa: the colour premultiplied by the alpha */
|
||||
std::vector<uint8_t> pre((size_t)iw * ih * 4);
|
||||
for (size_t i = 0; i < (size_t)iw * ih; ++i) {
|
||||
|
||||
+10
-10
@@ -1,15 +1,15 @@
|
||||
/* 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.
|
||||
/* imaging.h -- image arithmetic done the way PIL does it, so a picture reaches the model exactly
|
||||
* as the reference pipeline'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.
|
||||
* Resize: PIL's Image.resize with LANCZOS, bit for bit. Per-axis coefficients are computed in
|
||||
* double (support 3x the downscale, normalised to sum one) and converted to 22-bit fixed point;
|
||||
* a horizontal then a vertical pass run over 8-bit values, rounding and clipping each output.
|
||||
* RGBA is premultiplied by alpha first and divided back after, as PIL does. Diffusers'
|
||||
* VaeImageProcessor resizes 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. */
|
||||
* Composite: Image.paste(picture, mask=alpha) onto white, each channel
|
||||
* (c * a + 255 * (255 - a)) / 255 with PIL's rounding. The reference flattens a transparent
|
||||
* picture this way for an RGB text encoder. */
|
||||
#pragma once
|
||||
#include "mm/media.h"
|
||||
|
||||
|
||||
+9
-6
@@ -1,19 +1,22 @@
|
||||
/* item.cpp -- the parts of an Item the step path uses, in a unit of their own. The batch builder
|
||||
* links against this and nothing else in core/mm, so a test that fakes the device layer does not
|
||||
* pull the processor -- and through its metadata reader, the real device layer -- in with it. */
|
||||
/* item.cpp -- the parts of Item the step path uses. The batch builder links only this unit from
|
||||
* core/mm, so a test that fakes the device layer does not pull in the processor and, through its
|
||||
* metadata reader, the real device layer. */
|
||||
#include "mm/processor.h"
|
||||
|
||||
namespace rad {
|
||||
namespace mm {
|
||||
|
||||
void Item::coords(int64_t first, int64_t count, int32_t* planes) const {
|
||||
/* AN AUDIO CLIP IS 1-D (RadBatch::enc): the frame's index, whether it is real, the clip's real
|
||||
* frames and its staged ones. */
|
||||
/* An audio clip is 1-D (RadBatch::enc): frame index, whether the frame takes part in the
|
||||
* convolution, the clip's real frame count and its staged frame count. A clip staged in
|
||||
* chunks (AudioFamily::Qwen3ASR) reads each chunk's first `chunk_read` frames; the rest of the
|
||||
* chunk is alignment the encoder reads as zero. */
|
||||
if (kind == Kind::Audio) {
|
||||
for (int64_t k = 0; k < count; ++k) {
|
||||
const int64_t f = first + k;
|
||||
planes[k] = (int32_t)f;
|
||||
planes[count + k] = f < valid ? 1 : 0;
|
||||
planes[count + k] = chunk_staged > 0 ? (f % chunk_staged < chunk_read ? 1 : 0)
|
||||
: (f < valid ? 1 : 0);
|
||||
planes[2 * count + k] = valid;
|
||||
planes[3 * count + k] = grid_h;
|
||||
}
|
||||
|
||||
+58
-96
@@ -1,4 +1,5 @@
|
||||
/* media.cpp -- image and video decoding through libavformat / libavcodec / libswscale. */
|
||||
/* media.cpp -- image, video and audio decoding and image encoding through libavformat,
|
||||
* libavcodec, libswscale and libswresample. */
|
||||
#include "mm/media.h"
|
||||
|
||||
#include "rad_internal.h"
|
||||
@@ -56,10 +57,9 @@ bool decoder_available() { return true; }
|
||||
|
||||
namespace {
|
||||
|
||||
/* THE DEMUXERS A REQUEST MAY REACH, and nothing else. A container format that can name another
|
||||
* file -- a playlist, a concat script, an image sequence pattern -- would otherwise let a request
|
||||
* make the server open a path of its choosing, so the probe only ever considers these, and the
|
||||
* protocol list below is empty so none of them can open anything either. */
|
||||
/* The only demuxers a request may reach. A format that can name another file (a playlist, a
|
||||
* concat script, an image-sequence pattern) would let a request make the server open a path of
|
||||
* its choosing. The empty protocol whitelist also stops these from opening anything. */
|
||||
constexpr const char* kFormats =
|
||||
"mov,mp4,m4a,3gp,3g2,mj2,matroska,webm,avi,mpegts,flv,ogg,gif,apng,image2pipe,png_pipe,"
|
||||
"jpeg_pipe,jpegls_pipe,jpegxl_pipe,webp_pipe,bmp_pipe,tiff_pipe,qoi_pipe,pgm_pipe,ppm_pipe,"
|
||||
@@ -152,8 +152,8 @@ struct Input {
|
||||
if (!dec) { *why = "out of memory"; return RAD_E_NOMEM; }
|
||||
e = avcodec_parameters_to_context(dec, fmt->streams[stream]->codecpar);
|
||||
if (e < 0) { *why = "decoder setup failed (" + averr(e) + ")"; return RAD_E_INVAL; }
|
||||
/* A few threads a decode: this runs on a server worker, one per request in flight, so
|
||||
* handing each one every core would oversubscribe the machine the engine runs on. */
|
||||
/* Decodes run on server workers, one per request in flight; a few threads each avoids
|
||||
* oversubscribing the machine. */
|
||||
dec->thread_count = 4;
|
||||
e = avcodec_open2(dec, codec, nullptr);
|
||||
if (e < 0) { *why = std::string("no decoder for ") + codec->name + " (" + averr(e) + ")"; return RAD_E_UNSUPPORTED; }
|
||||
@@ -161,68 +161,19 @@ struct Input {
|
||||
}
|
||||
};
|
||||
|
||||
/* One decoded frame to packed RGB24 at its own size. The YUV coefficients and range are the
|
||||
* frame's own, so a BT.709 video and a full-range JPEG both come out with the colours they were
|
||||
* encoded with.
|
||||
/* One decoded frame to packed `fmt` (RGB24 or RGBA, `ch` bytes a pixel) at its own size, rows
|
||||
* tight. The YUV coefficients and range are the frame's own, so a BT.709 video and a full-range
|
||||
* JPEG keep the colours they were encoded with.
|
||||
*
|
||||
* THE SCALER FLAGS ARE THE REFERENCE PIPELINE'S: transformers decodes video through PyAV
|
||||
* (`to_ndarray(format="rgb24")`, its default backend), which converts with plain SWS_BILINEAR.
|
||||
* The flags decide how chroma is upsampled, and at a sharp colour edge two choices differ by up to
|
||||
* 70 levels: measured on an EmbeddingGemma 2 clip, SWS_BICUBIC | ACCURATE_RND | FULL_CHR_H_INT
|
||||
* left the embedding at cosine 0.9995 against the reference, these at 0.99998 with every patch
|
||||
* within one level. */
|
||||
int to_rgb(const AVFrame* f, SwsContext** sws, Frame* out, std::string* why) {
|
||||
* The scaler flags match the reference pipeline: transformers decodes video through PyAV
|
||||
* (`to_ndarray(format="rgb24")`), which converts with plain SWS_BILINEAR. The flags decide chroma
|
||||
* upsampling, which can differ by up to 70 levels at a sharp colour edge; with these flags every
|
||||
* patch lands within one level of the reference. */
|
||||
int to_packed(const AVFrame* f, SwsContext** sws, AVPixelFormat fmt, size_t ch,
|
||||
std::vector<uint8_t>* 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_RGB24,
|
||||
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* coef = sws_getCoefficients(cs);
|
||||
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, coef, src_full, sws_getCoefficients(SWS_CS_DEFAULT), 1, 0,
|
||||
1 << 16, 1 << 16);
|
||||
/* THE SCALER WRITES INTO A FRAME FFMPEG ALLOCATED, and the rows are copied out. Its SIMD paths
|
||||
* store whole vectors, so a row ends wherever the last vector does: a 4:2:0 or 4:2:2 picture
|
||||
* 1788 wide converted with these flags writes 12 bytes past 1788 x 3, and into a buffer of
|
||||
* exactly width x height x 3 those land on the next heap chunk's header -- the process aborts
|
||||
* at a later allocation ("malloc(): corrupted top size"). av_frame_get_buffer pads every line
|
||||
* and the end as the scaler expects. */
|
||||
AVFrame* rgb = av_frame_alloc();
|
||||
if (!rgb) { *why = "out of memory"; return RAD_E_NOMEM; }
|
||||
rgb->format = AV_PIX_FMT_RGB24;
|
||||
rgb->width = f->width;
|
||||
rgb->height = f->height;
|
||||
if (av_frame_get_buffer(rgb, 0) < 0) {
|
||||
av_frame_free(&rgb);
|
||||
*why = "out of memory";
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
const int e = sws_scale(*sws, f->data, f->linesize, 0, f->height, rgb->data, rgb->linesize);
|
||||
if (e != f->height) {
|
||||
av_frame_free(&rgb);
|
||||
*why = "colour conversion failed";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
out->w = f->width;
|
||||
out->h = f->height;
|
||||
const size_t row = (size_t)f->width * 3;
|
||||
out->rgb.resize(row * (size_t)f->height);
|
||||
for (int y = 0; y < f->height; ++y)
|
||||
std::memcpy(out->rgb.data() + (size_t)y * row, rgb->data[0] + (ptrdiff_t)y * rgb->linesize[0], row);
|
||||
av_frame_free(&rgb);
|
||||
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);
|
||||
*sws = sws_getCachedContext(*sws, f->width, f->height, src, f->width, f->height, fmt,
|
||||
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;
|
||||
@@ -231,9 +182,13 @@ int to_rgba(const AVFrame* f, SwsContext** sws, FrameRGBA* out, std::string* why
|
||||
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);
|
||||
/* Convert into an FFmpeg-allocated frame, then copy the rows out. The scaler's SIMD paths
|
||||
* store whole vectors and overrun a tight row (a 4:2:0 or 4:2:2 picture 1788 wide writes
|
||||
* 12 bytes past 1788 x 3), which corrupts the heap in a buffer of exactly w x h x 3.
|
||||
* av_frame_get_buffer pads every line and the end as the scaler expects. */
|
||||
AVFrame* dst = av_frame_alloc();
|
||||
if (!dst) { *why = "out of memory"; return RAD_E_NOMEM; }
|
||||
dst->format = AV_PIX_FMT_RGBA;
|
||||
dst->format = fmt;
|
||||
dst->width = f->width;
|
||||
dst->height = f->height;
|
||||
if (av_frame_get_buffer(dst, 0) < 0) {
|
||||
@@ -247,24 +202,34 @@ int to_rgba(const AVFrame* f, SwsContext** sws, FrameRGBA* out, std::string* why
|
||||
*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);
|
||||
const size_t row = (size_t)f->width * ch;
|
||||
out->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],
|
||||
std::memcpy(out->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.
|
||||
int to_rgb(const AVFrame* f, SwsContext** sws, Frame* out, std::string* why) {
|
||||
out->w = f->width;
|
||||
out->h = f->height;
|
||||
return to_packed(f, sws, AV_PIX_FMT_RGB24, 3, &out->rgb, why);
|
||||
}
|
||||
|
||||
/* As to_rgb, to packed RGBA, for a picture whose alpha is kept. */
|
||||
int to_rgba(const AVFrame* f, SwsContext** sws, FrameRGBA* out, std::string* why) {
|
||||
out->w = f->width;
|
||||
out->h = f->height;
|
||||
return to_packed(f, sws, AV_PIX_FMT_RGBA, 4, &out->rgba, why);
|
||||
}
|
||||
|
||||
/* The decode loop for images and video: every frame in presentation order goes to
|
||||
* `keep(i, frame)`, which returns < 0 to fail, > 0 to stop and 0 to continue.
|
||||
*
|
||||
* AN EMPTY PACKET REPEATS THE FRAME BEFORE IT: it is how Ogg Theora stores a frame that does not
|
||||
* change. Sent to a decoder, an empty packet would read as the end of the stream and the next one
|
||||
* would be refused; it is passed to `keep` as another copy of the last frame instead, so the
|
||||
* frame indices and the stream's length are the ones the frame count promised. */
|
||||
* An empty packet repeats the previous frame (Ogg Theora stores an unchanged frame this way).
|
||||
* The decoder would read it as end of stream, so it is passed to `keep` as another copy of the
|
||||
* last frame instead, keeping indices and length consistent with the stated frame count. */
|
||||
template <class Keep>
|
||||
int decode_frames(Input& in, Keep&& keep, std::string* why) {
|
||||
AVPacket* pkt = av_packet_alloc();
|
||||
@@ -388,10 +353,9 @@ int decode_image_rgba(const uint8_t* data, size_t n, int64_t max_pixels, FrameRG
|
||||
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. */
|
||||
/* One picture through one encoder: convert to the encoder's pixel format (swscale; full-range
|
||||
* BT.601 for jpeg's YUV, as PIL writes it) and send one frame. png, mjpeg and libwebp each write
|
||||
* a complete image file per packet, so the packet that comes back is the file. */
|
||||
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<uint8_t>* out, std::string* why) {
|
||||
std::string wy;
|
||||
@@ -440,9 +404,8 @@ int encode_image(const uint8_t* px, int32_t w, int32_t h, int32_t ch, const std:
|
||||
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. */
|
||||
/* zlib level 1 with per-row prediction: a 2048^2 picture takes 0.16 s for 5.9 MB, against
|
||||
* 1.0 s for 5.3 MB at the default level 6, on one core. */
|
||||
if (format == "png") {
|
||||
cx->compression_level = 1;
|
||||
av_opt_set(cx->priv_data, "pred", "mixed", 0);
|
||||
@@ -498,9 +461,9 @@ int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* use
|
||||
if (!why) why = &w;
|
||||
if (!data || n == 0) { *why = "empty"; return RAD_E_INVAL; }
|
||||
|
||||
/* THE FRAME COUNT FIRST, because which frames to keep depends on it. Many containers state it;
|
||||
* those that do not are demuxed once without decoding, which counts packets -- one a frame for
|
||||
* every codec a request is going to send -- at the cost of reading the bytes twice. */
|
||||
/* Frame count first, since the sample choice depends on it. A container that does not state
|
||||
* it is demuxed once without decoding to count packets (one per frame for the codecs requests
|
||||
* send), at the cost of reading the bytes twice. */
|
||||
VideoInfo info;
|
||||
{
|
||||
Input probe;
|
||||
@@ -547,8 +510,8 @@ int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* use
|
||||
*why = "a frame is larger than the server's pixel limit";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The same frame may be sampled twice when the stream is shorter than its own header
|
||||
* says; each slot that names this index takes a copy. */
|
||||
/* A frame may be sampled twice when the stream is shorter than its header says; each
|
||||
* slot naming this index takes a copy. */
|
||||
bool converted = false;
|
||||
while (next < out->index.size() && out->index[next] == i) {
|
||||
if (!converted) {
|
||||
@@ -566,9 +529,8 @@ int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* use
|
||||
sws_freeContext(sws);
|
||||
if (s < 0) return s;
|
||||
if (last_kept < 0) { *why = "the video decoded to no frame"; return RAD_E_INVAL; }
|
||||
/* A STREAM SHORTER THAN ITS HEADER leaves the last sampled indices unreached. They take the
|
||||
* last frame that was decoded, which is what a reader that clamps an index past the end
|
||||
* returns. */
|
||||
/* A stream shorter than its header leaves the last sampled indices unreached. They take the
|
||||
* last decoded frame, as a reader that clamps an index past the end would. */
|
||||
for (size_t k = next; k < out->index.size(); ++k) out->frames[k] = out->frames[(size_t)last_kept];
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -577,7 +539,7 @@ int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* use
|
||||
|
||||
namespace {
|
||||
|
||||
/* THE AUDIO DEMUXERS A REQUEST MAY REACH, chosen as the video list is: formats that hold one
|
||||
/* The only audio demuxers a request may reach, chosen as kFormats is: formats that hold one
|
||||
* stream of samples and cannot name another file. */
|
||||
constexpr const char* kAudioFormats = "wav,w64,mp3,flac,ogg,mov,mp4,m4a,matroska,webm,aac,aiff";
|
||||
|
||||
@@ -706,7 +668,7 @@ int decode_audio(const uint8_t* data, size_t n, int32_t rate, int64_t max_sample
|
||||
if (st < 0) break;
|
||||
if (e != AVERROR(EAGAIN) && e != AVERROR_EOF) { *why = "the audio would not decode (" + averr(e) + ")"; st = RAD_E_INVAL; break; }
|
||||
}
|
||||
/* What the resampler still holds. */
|
||||
/* Flush what the resampler still holds. */
|
||||
if (st == RAD_OK && (int64_t)out->size() < max_samples) st = take(nullptr, 0);
|
||||
av_packet_free(&pkt);
|
||||
av_frame_free(&f);
|
||||
|
||||
+29
-33
@@ -1,18 +1,17 @@
|
||||
/* media.h -- turning the bytes of an image or a video into RGB frames (spec §11).
|
||||
/* media.h -- image, video and audio decoding, and picture encoding (spec §11).
|
||||
*
|
||||
* ONE DECODER FOR BOTH, and it is libavformat/libavcodec. An image is a one-frame stream to it, so
|
||||
* PNG, JPEG, WebP, GIF, BMP and TIFF arrive through the same demuxer probe and the same decode loop
|
||||
* a video takes, and there is one colour conversion (libswscale) rather than one per format. A
|
||||
* build without the libraries has no decoder at all: every call here returns RAD_E_UNSUPPORTED
|
||||
* with the reason, and the server refuses a media part by name rather than guessing at its bytes.
|
||||
* One decoder for everything: libavformat/libavcodec. An image is a one-frame stream, so PNG,
|
||||
* JPEG, WebP, GIF, BMP and TIFF take the same demuxer probe, decode loop and colour conversion
|
||||
* (libswscale) as a video. In a build without the libraries every call returns
|
||||
* RAD_E_UNSUPPORTED with the reason, and the server refuses the media part by name.
|
||||
*
|
||||
* THE BYTES COME FROM THE REQUEST, never from a URL. The server accepts `data:` URLs only, so
|
||||
* nothing here opens a file or a network stream: the demuxer reads a memory buffer through its own
|
||||
* I/O context, and the protocol whitelist is empty.
|
||||
* Bytes come from the request only (`data:` URLs). Nothing here opens a file or a network
|
||||
* stream: the demuxer reads a memory buffer through its own I/O context, and the protocol
|
||||
* whitelist is empty.
|
||||
*
|
||||
* WHAT A FRAME IS: packed 8-bit RGB, row-major, no padding. An alpha channel is DROPPED, not
|
||||
* composited -- the reference processor converts with PIL's convert("RGB"), which does the same,
|
||||
* so a transparent PNG reaches the encoder with the colours under its alpha.
|
||||
* A Frame is packed 8-bit RGB, row-major, no padding. Alpha is dropped, not composited, as the
|
||||
* reference processor's PIL convert("RGB") does, so a transparent PNG reaches the encoder with
|
||||
* the colours under its alpha.
|
||||
*/
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
@@ -27,36 +26,34 @@ struct Frame {
|
||||
std::vector<uint8_t> 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. */
|
||||
/* Packed 8-bit RGBA, row-major, no padding; what an image generator reads and writes. A source
|
||||
* without alpha decodes as opaque. */
|
||||
struct FrameRGBA {
|
||||
int32_t w = 0, h = 0;
|
||||
std::vector<uint8_t> rgba; /* [h, w, 4] */
|
||||
};
|
||||
|
||||
/* Is there a decoder in this build. */
|
||||
/* Whether this build has a decoder. */
|
||||
bool decoder_available();
|
||||
|
||||
/* The first frame of an image (or of anything with a video stream). Refuses more than
|
||||
* `max_pixels` in the SOURCE, which is what bounds the memory a request can make the server
|
||||
* allocate before any resize happens. */
|
||||
/* The first frame of an image (or of anything with a video stream). Refuses a source over
|
||||
* `max_pixels`, which bounds what a request can make the server allocate before any resize. */
|
||||
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. */
|
||||
/* As decode_image, 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. */
|
||||
/* Encodes `px`, [h, w, ch] 8-bit with ch 3 (RGB) or 4 (RGBA), as an image file; `format` is png,
|
||||
* jpeg or webp. `quality` 0..100 applies to jpeg and lossy webp (0 or above 100 picks the
|
||||
* format's default); png is lossless and webp is lossless at 100. jpeg refuses alpha. Returns
|
||||
* RAD_E_UNSUPPORTED, with the reason, for a format this build cannot encode. */
|
||||
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<uint8_t>* 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
|
||||
* frames is the processor's (it depends on the stream's length and rate, which only the decoder
|
||||
* knows), so it is a callback: given the stream's frame count and rate, return the frame indices to
|
||||
* keep, ascending. */
|
||||
/* Video sampling happens inside the decode: a minute of 1080p is 10 GB of RGB, so unsampled
|
||||
* frames are never converted or kept. The processor picks the frames from the stream's length
|
||||
* and rate, which only the decoder knows, so the choice is a callback: given the frame count and
|
||||
* rate, return the frame indices to keep, ascending. */
|
||||
struct VideoInfo {
|
||||
int64_t n_frames = 0; /* frames in the stream; counted by demuxing when the header omits it */
|
||||
double fps = 0.0; /* the stream's average rate */
|
||||
@@ -73,11 +70,10 @@ struct Video {
|
||||
int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* user,
|
||||
int64_t max_pixels, Video* out, std::string* why);
|
||||
|
||||
/* AN AUDIO CLIP as mono float samples at `rate` Hz: the first audio stream, resampled with
|
||||
* libswresample at the source's channel layout and then averaged across channels -- the plain
|
||||
* mean every reference loader (librosa, torchaudio's to-mono) takes, where swresample's own
|
||||
* downmix would weight a stereo pair by 0.707. At most `max_samples` are kept: a longer clip is
|
||||
* cut there, as the reference feature extractor truncates. */
|
||||
/* The first audio stream as mono float samples at `rate` Hz. Resampled with libswresample at the
|
||||
* source's channel layout, then averaged across channels: the plain mean reference loaders
|
||||
* (librosa, torchaudio's to-mono) take, where swresample's downmix weights a stereo pair by
|
||||
* 0.707. A clip longer than `max_samples` is truncated, as the reference feature extractor does. */
|
||||
int decode_audio(const uint8_t* data, size_t n, int32_t rate, int64_t max_samples,
|
||||
std::vector<float>* out, std::string* why);
|
||||
|
||||
|
||||
+368
-140
@@ -150,9 +150,8 @@ int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) {
|
||||
"vision_start_token_id, vision_end_token_id)";
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
/* THE PROCESSOR-ONLY KEYS DEFAULT TO THE FAMILY'S VALUES. They come from the checkpoint's
|
||||
* preprocessor configs, which a container may not carry; the numbers below are what the
|
||||
* Qwen3.x checkpoints ship. */
|
||||
/* Processor-only keys come from the checkpoint's preprocessor configs, which a container may
|
||||
* not carry; the defaults are what the Qwen3.x checkpoints ship. */
|
||||
image_min_pixels = rad_meta_geti(&m, "preprocessor.size.shortest_edge",
|
||||
rad_meta_geti(&m, "preprocessor.min_pixels", 65536));
|
||||
image_max_pixels = rad_meta_geti(&m, "preprocessor.size.longest_edge",
|
||||
@@ -170,11 +169,6 @@ int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) {
|
||||
if (why) *why = "the container's preprocessor configuration is inconsistent: " + bad;
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (int c = 0; c < 3; ++c)
|
||||
if (!(stdv[c] > 0.0f)) {
|
||||
if (why) *why = "preprocessor.image_std must be positive";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -193,6 +187,8 @@ int VisionConfig::check(std::string* why) const {
|
||||
std::to_string(video_min_pixels));
|
||||
if (!(fps > 0.0)) return no("fps must be positive");
|
||||
if (min_frames < 1) return no("min_frames must be at least 1");
|
||||
for (int c = 0; c < 3; ++c)
|
||||
if (!(stdv[c] > 0.0f)) return no("image_std must be positive");
|
||||
if (max_frames < min_frames)
|
||||
return no("max_frames " + std::to_string(max_frames) + " is below min_frames " +
|
||||
std::to_string(min_frames));
|
||||
@@ -203,8 +199,6 @@ int VisionConfig::check(std::string* why) const {
|
||||
") is not a range of whole merged patches");
|
||||
if (!(max_pixels_tolerance > 0.0) || max_segment_patches <= 0)
|
||||
return no("max_pixels_tolerance and max_num_patches must be positive");
|
||||
for (int c = 0; c < 3; ++c)
|
||||
if (!(stdv[c] > 0.0f)) return no("image_std must be positive");
|
||||
}
|
||||
if (family == Family::Gemma4) {
|
||||
if (!soft_budget_ok(image_soft_tokens))
|
||||
@@ -219,10 +213,27 @@ int VisionConfig::check(std::string* why) const {
|
||||
|
||||
/* ================================================================== sizes and sampling */
|
||||
|
||||
/* Python's round(), which is round-half-to-even on the double -- the reference computes these in
|
||||
* Python, and a size that lands on .5 rounds the way it does there. */
|
||||
/* Python's round(): half-to-even on the double, so a size landing on .5 rounds as the Python
|
||||
* reference does. */
|
||||
static inline int64_t pyround(double x) { return (int64_t)std::nearbyint(x); }
|
||||
|
||||
/* The step the references share after rounding each side to `factor`: a size past `max_px`
|
||||
* shrinks by the area ratio and rounds down, one under `min_px` grows and rounds up. `t` frames
|
||||
* (rounded to `tb`) count toward the area; a picture passes 1 and 1. */
|
||||
static void fit_pixels(int64_t t, int64_t tb, int64_t h, int64_t w, int32_t factor,
|
||||
int64_t min_px, int64_t max_px, int64_t* hb, int64_t* wb) {
|
||||
const double f = factor;
|
||||
if (tb * *hb * *wb > max_px) {
|
||||
const double beta = std::sqrt((double)(t * h * w) / (double)max_px);
|
||||
*hb = std::max<int64_t>(factor, (int64_t)std::floor((double)h / beta / f) * factor);
|
||||
*wb = std::max<int64_t>(factor, (int64_t)std::floor((double)w / beta / f) * factor);
|
||||
} else if (tb * *hb * *wb < min_px) {
|
||||
const double beta = std::sqrt((double)min_px / (double)(t * h * w));
|
||||
*hb = (int64_t)std::ceil((double)h * beta / f) * factor;
|
||||
*wb = (int64_t)std::ceil((double)w * beta / f) * factor;
|
||||
}
|
||||
}
|
||||
|
||||
int smart_resize_image(int64_t h, int64_t w, int32_t factor, int64_t min_px, int64_t max_px,
|
||||
int64_t* oh, int64_t* ow, std::string* why) {
|
||||
if (h <= 0 || w <= 0) { if (why) *why = "the picture has no size"; return RAD_E_INVAL; }
|
||||
@@ -233,15 +244,7 @@ int smart_resize_image(int64_t h, int64_t w, int32_t factor, int64_t min_px, int
|
||||
const double f = factor;
|
||||
int64_t hb = pyround((double)h / f) * factor;
|
||||
int64_t wb = pyround((double)w / f) * factor;
|
||||
if (hb * wb > max_px) {
|
||||
const double beta = std::sqrt((double)(h * w) / (double)max_px);
|
||||
hb = std::max<int64_t>(factor, (int64_t)std::floor((double)h / beta / f) * factor);
|
||||
wb = std::max<int64_t>(factor, (int64_t)std::floor((double)w / beta / f) * factor);
|
||||
} else if (hb * wb < min_px) {
|
||||
const double beta = std::sqrt((double)min_px / (double)(h * w));
|
||||
hb = (int64_t)std::ceil((double)h * beta / f) * factor;
|
||||
wb = (int64_t)std::ceil((double)w * beta / f) * factor;
|
||||
}
|
||||
fit_pixels(1, 1, h, w, factor, min_px, max_px, &hb, &wb);
|
||||
*oh = hb;
|
||||
*ow = wb;
|
||||
return RAD_OK;
|
||||
@@ -264,23 +267,15 @@ int smart_resize_video(int64_t t, int64_t h, int64_t w, int32_t tfactor, int32_t
|
||||
int64_t hb = pyround((double)h / f) * factor;
|
||||
int64_t wb = pyround((double)w / f) * factor;
|
||||
const int64_t tb = pyround((double)t / (double)tfactor) * tfactor;
|
||||
if (tb * hb * wb > max_px) {
|
||||
const double beta = std::sqrt((double)(t * h * w) / (double)max_px);
|
||||
hb = std::max<int64_t>(factor, (int64_t)std::floor((double)h / beta / f) * factor);
|
||||
wb = std::max<int64_t>(factor, (int64_t)std::floor((double)w / beta / f) * factor);
|
||||
} else if (tb * hb * wb < min_px) {
|
||||
const double beta = std::sqrt((double)min_px / (double)(t * h * w));
|
||||
hb = (int64_t)std::ceil((double)h * beta / f) * factor;
|
||||
wb = (int64_t)std::ceil((double)w * beta / f) * factor;
|
||||
}
|
||||
fit_pixels(t, tb, h, w, factor, min_px, max_px, &hb, &wb);
|
||||
*oh = hb;
|
||||
*ow = wb;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* THE REFERENCE'S FRAME CHOICE: as many frames as `fps` gives over the clip's duration, clamped to
|
||||
* [min_frames, max_frames] and to what the stream has, spread evenly over it -- numpy's linspace,
|
||||
* rounded half-to-even. A stream that states no rate is taken at 24, as the reference does. */
|
||||
/* The reference's frame choice: as many frames as `fps` gives over the clip's duration, clamped to
|
||||
* [min_frames, max_frames] and to the stream's length, spread evenly (numpy's linspace, rounded
|
||||
* half-to-even). A stream with no stated rate is taken at 24 fps, as the reference does. */
|
||||
std::vector<int64_t> sample_frames(const VideoInfo& info, double fps, int32_t min_frames,
|
||||
int32_t max_frames) {
|
||||
const int64_t total = info.n_frames;
|
||||
@@ -358,11 +353,11 @@ std::vector<int64_t> sample_frames_gemma4(const VideoInfo& info, double fps, int
|
||||
|
||||
/* ================================================================== the resample
|
||||
*
|
||||
* Pillow's ImagingResample for an 8-bit RGB image, transcribed: the coefficient table in double,
|
||||
* normalised per output pixel and rounded to 22-bit fixed point; a horizontal pass over only the
|
||||
* source rows the vertical pass will read, into an 8-bit intermediate; then the vertical pass. The
|
||||
* rounding at the intermediate is part of the function -- a single-pass float resample is a
|
||||
* different (and slightly better) function, and not the one the model was trained against. */
|
||||
* Pillow's ImagingResample for 8-bit RGB: coefficients in double, normalised per output pixel and
|
||||
* rounded to 22-bit fixed point; a horizontal pass over only the source rows the vertical pass
|
||||
* reads, into an 8-bit intermediate; then the vertical pass. The intermediate rounding is part of
|
||||
* the function: a single-pass float resample is a different function from the one the model was
|
||||
* trained against. */
|
||||
namespace {
|
||||
|
||||
constexpr int kPrec = 32 - 8 - 2;
|
||||
@@ -380,9 +375,9 @@ inline uint8_t clip8(int32_t v, int prec) {
|
||||
return (uint8_t)(s < 0 ? 0 : (s > 255 ? 255 : s));
|
||||
}
|
||||
|
||||
/* One axis: `bounds` gets (first, count) per output pixel and `kk` its fixed-point weights, `ksize`
|
||||
* a row, `*prec` their fraction bits: PIL's fixed 22, or -- `torch` -- ATen's per-axis choice, the
|
||||
* most bits at which the largest weight still fits an int16. */
|
||||
/* One axis: `bounds` gets (first, count) per output pixel and `kk` its fixed-point weights,
|
||||
* `ksize` per row; `*prec` gets their fraction bits. PIL uses a fixed 22; with `torch`, ATen's
|
||||
* per-axis choice: the most bits at which the largest weight still fits an int16. */
|
||||
int coeffs(int32_t in_size, int32_t out_size, std::vector<int32_t>* bounds,
|
||||
std::vector<int32_t>* kk, bool torch, int* prec) {
|
||||
const double scale = (double)in_size / (double)out_size;
|
||||
@@ -521,15 +516,14 @@ inline uint64_t mix64(uint64_t x) {
|
||||
}
|
||||
|
||||
/* Two independent 64-bit lanes over the patch bytes and the grid. The prefix cache folds the key
|
||||
* into a chained 128-bit block identity; a collision would serve one picture's cache for another,
|
||||
* so both lanes are carried. */
|
||||
* into a chained 128-bit block identity, and a collision would serve one picture's cache for
|
||||
* another, so both lanes are kept. */
|
||||
void content_key(const Item& it, uint64_t* hi, uint64_t* lo) {
|
||||
uint64_t a = 0x6a09e667f3bcc908ull ^ mix64((uint64_t)it.grid_t << 42 ^
|
||||
(uint64_t)it.grid_h << 21 ^ (uint64_t)it.grid_w);
|
||||
uint64_t b = 0xbb67ae8584caa73bull ^
|
||||
mix64(it.kind == Kind::Image ? 1u : it.kind == Kind::Video ? 2u : 3u);
|
||||
/* The tiling, when the segments have sizes of their own: the same patches cut differently
|
||||
* are different encoder inputs. */
|
||||
/* The tiling: the same patches cut into different segments are different encoder inputs. */
|
||||
for (const Item::Segment& sg : it.segments)
|
||||
a = mix64(a ^ ((uint64_t)(uint32_t)sg.h << 32 | (uint32_t)sg.w)) + (uint64_t)sg.patch0;
|
||||
const uint8_t* p = reinterpret_cast<const uint8_t*>(it.pixels.data());
|
||||
@@ -547,17 +541,29 @@ void content_key(const Item& it, uint64_t* hi, uint64_t* lo) {
|
||||
*lo = mix64(b + (uint64_t)n);
|
||||
}
|
||||
|
||||
/* THE PATCH ROWS, in merge-block order, from `frames` (temporal * grid_t of them, already resized
|
||||
* to grid_h * patch by grid_w * patch). Each row is (channel, frame, y, x), each value normalised
|
||||
* as the reference does -- (x - 255 mean) / (255 std) in f32 -- and rounded to bf16. */
|
||||
/* After its content key, the item's expansion as one run of `rows` copies of `tok` between the
|
||||
* `start` and `end` markers. */
|
||||
static void one_run(Item* it, int32_t start, int64_t rows, int32_t tok, int32_t end) {
|
||||
content_key(*it, &it->key_hi, &it->key_lo);
|
||||
it->expand.reserve((size_t)rows + 2);
|
||||
it->expand.push_back(start);
|
||||
it->seg_at.push_back(1);
|
||||
it->expand.insert(it->expand.end(), (size_t)rows, tok);
|
||||
it->expand.push_back(end);
|
||||
}
|
||||
|
||||
/* The patch rows, in merge-block order, from `frames` (temporal * grid_t of them, already resized
|
||||
* to grid_h * patch by grid_w * patch). Each row is (channel, frame, y, x); each value is
|
||||
* normalised as the reference does, (x - 255 mean) / (255 std) in f32, and rounded to bf16. */
|
||||
void patchify(const VisionConfig& c, const std::vector<const Frame*>& frames, Item* it) {
|
||||
const int P = c.patch, T = c.temporal, M = c.merge;
|
||||
const int gh = it->grid_h, gw = it->grid_w;
|
||||
float m255[3], s255[3];
|
||||
for (int ch = 0; ch < 3; ++ch) {
|
||||
/* torch.tensor(mean) * (1 / rescale_factor), in f32: the fused rescale's own constants. */
|
||||
m255[ch] = c.mean[ch] * (float)(1.0 / (1.0 / 255.0));
|
||||
s255[ch] = c.stdv[ch] * (float)(1.0 / (1.0 / 255.0));
|
||||
/* torch.tensor(mean) * (1 / rescale_factor), in f32: the fused rescale's own constants.
|
||||
* 1 / (1 / 255) rounds to 255 in f32. */
|
||||
m255[ch] = c.mean[ch] * 255.0f;
|
||||
s255[ch] = c.stdv[ch] * 255.0f;
|
||||
}
|
||||
/* One lookup per (channel, byte): the normalisation is a function of the byte alone. */
|
||||
uint16_t lut[3][256];
|
||||
@@ -586,17 +592,22 @@ void patchify(const VisionConfig& c, const std::vector<const Frame*>& frames, It
|
||||
}
|
||||
}
|
||||
|
||||
/* Gemma 4's patch rows: merge-block order like patchify's (each pooling window's patches are
|
||||
* consecutive, which is what lets the pooler be a mean of k^2 consecutive rows; attention and the
|
||||
* position terms read each patch's own coordinates, so the order is free), each row (y, x,
|
||||
* channel), each value 2 * (u * (1/255)) - 1 in f32 -- the processor's rescale and then the
|
||||
* model's own input scaling -- rounded to bf16. One frame a segment. */
|
||||
void patchify_gemma4(const VisionConfig& c, const std::vector<const Frame*>& frames, Item* it) {
|
||||
/* Gemma 4's patch rows, in merge-block order like patchify's: each pooling window's patches are
|
||||
* consecutive, so the pooler is a mean of k^2 consecutive rows (attention and the position terms
|
||||
* read each patch's own coordinates, so the order is otherwise free). Each row is (y, x, channel);
|
||||
* each value is 2 * (p - 0.5) in f32 (the model's input scaling), rounded to bf16, where p is the
|
||||
* processor's rescale u * (1/255). The processors AutoProcessor loads take that product in f32 for
|
||||
* pictures (Gemma4ImageProcessor) and in double, rounded to f32, for video (Gemma 4's and
|
||||
* EmbeddingGemma 2's video processors); `video` picks which, and the two differ for u = 127. One
|
||||
* frame per segment. */
|
||||
void patchify_gemma4(const VisionConfig& c, const std::vector<const Frame*>& frames, bool video,
|
||||
Item* it) {
|
||||
const int P = c.patch, M = c.merge;
|
||||
const int gh = it->grid_h, gw = it->grid_w;
|
||||
uint16_t lut[256];
|
||||
for (int v = 0; v < 256; ++v) {
|
||||
const float p = (float)v * (float)(1.0 / 255.0);
|
||||
const float p = video ? (float)((double)v * (1.0 / 255.0))
|
||||
: (float)v * (float)(1.0 / 255.0);
|
||||
lut[v] = rad_f32_to_bf16(2.0f * (p - 0.5f));
|
||||
}
|
||||
const int64_t dim = it->patch_dim;
|
||||
@@ -637,8 +648,8 @@ int Processor::init(const VisionConfig& cfg,
|
||||
return RAD_E_INVAL;
|
||||
cfg_ = cfg;
|
||||
if (cfg.family == Family::Lfm2) {
|
||||
/* The markers are named, not numbered, in the config: resolved here, every one, so a
|
||||
* vocabulary missing one is refused at startup rather than on the first large picture. */
|
||||
/* The config names the markers rather than numbering them. Resolve all of them here so a
|
||||
* vocabulary missing one is refused at startup, not on the first large picture. */
|
||||
if (!token_id) return RAD_E_INVAL;
|
||||
cfg_.tok_start = token_id("<|image_start|>");
|
||||
cfg_.tok_end = token_id("<|image_end|>");
|
||||
@@ -652,7 +663,7 @@ int Processor::init(const VisionConfig& cfg,
|
||||
if (id < 0) return RAD_E_NOTFOUND;
|
||||
tok_tiles_[(size_t)(r - 1) * cfg.max_tiles + (c - 1)] = id;
|
||||
}
|
||||
/* A tile and the largest thumbnail are one segment each: of the tower and of a pass. */
|
||||
/* A tile and the largest thumbnail are each one segment, of the tower and of a pass. */
|
||||
const int64_t seg = std::max<int64_t>((int64_t)(cfg.tile / cfg.patch) * (cfg.tile / cfg.patch),
|
||||
cfg.image_max_pixels / ((int64_t)cfg.patch * cfg.patch));
|
||||
if (seg > cfg.max_patches || seg > cfg.max_segment_patches) return RAD_E_INVAL;
|
||||
@@ -667,8 +678,8 @@ int Processor::init(const VisionConfig& cfg,
|
||||
encode_text_ = std::move(encode_text);
|
||||
return RAD_OK;
|
||||
}
|
||||
/* The largest image the encoder takes in one pass, in pixels: the band's ceiling comes down to
|
||||
* it, so smart_resize itself keeps every image inside a pass. */
|
||||
/* The largest image one encoder pass takes, in pixels. Lowering the band's ceiling to it makes
|
||||
* smart_resize keep every image inside a pass. */
|
||||
const int64_t pass_px = cfg.max_patches * cfg.patch * cfg.patch;
|
||||
if (cfg_.image_max_pixels > pass_px) cfg_.image_max_pixels = pass_px;
|
||||
if (cfg_.image_min_pixels > cfg_.image_max_pixels) cfg_.image_min_pixels = cfg_.image_max_pixels;
|
||||
@@ -683,15 +694,7 @@ void lfm2_size(int64_t h, int64_t w, int32_t factor, int64_t min_px, int64_t max
|
||||
const double f = factor;
|
||||
int64_t hb = std::max<int64_t>(factor, pyround((double)h / f) * factor);
|
||||
int64_t wb = std::max<int64_t>(factor, pyround((double)w / f) * factor);
|
||||
if (hb * wb > max_px) {
|
||||
const double beta = std::sqrt((double)(h * w) / (double)max_px);
|
||||
hb = std::max<int64_t>(factor, (int64_t)std::floor((double)h / beta / f) * factor);
|
||||
wb = std::max<int64_t>(factor, (int64_t)std::floor((double)w / beta / f) * factor);
|
||||
} else if (hb * wb < min_px) {
|
||||
const double beta = std::sqrt((double)min_px / (double)(h * w));
|
||||
hb = (int64_t)std::ceil((double)h * beta / f) * factor;
|
||||
wb = (int64_t)std::ceil((double)w * beta / f) * factor;
|
||||
}
|
||||
fit_pixels(1, 1, h, w, factor, min_px, max_px, &hb, &wb);
|
||||
*oh = hb;
|
||||
*ow = wb;
|
||||
}
|
||||
@@ -703,9 +706,9 @@ bool lfm2_too_large(int64_t h, int64_t w, int32_t patch, int32_t factor, int64_t
|
||||
return (double)(hb * wb) > (double)max_px * tolerance;
|
||||
}
|
||||
|
||||
/* The reference walks the ratios sorted by tile count; within one count it orders them as a
|
||||
* Python set happens to, which this walks by columns. The two can differ only on an exact tie
|
||||
* between two grids of one count, both nearest. */
|
||||
/* The reference walks the ratios sorted by tile count, and within one count in Python set order;
|
||||
* this walks by columns. The two differ only on an exact tie between two nearest grids of one
|
||||
* count. */
|
||||
void lfm2_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32_t tile,
|
||||
int32_t* cols, int32_t* rows) {
|
||||
const double aspect = (double)w / (double)h;
|
||||
@@ -725,9 +728,9 @@ void lfm2_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32
|
||||
}
|
||||
|
||||
/* LFM2-VL's image processor (transformers' Lfm2VlImageProcessor), segment by segment: the tiles
|
||||
* in row-major order, then the thumbnail; within one, patches in merge-block order (each
|
||||
* merge x merge block's patches consecutive, dy then dx -- which is how the projector's pixel
|
||||
* unshuffle reads them, so its merge is a view), each patch (y, x, channel). */
|
||||
* in row-major order, then the thumbnail. Within a segment, patches are in merge-block order (each
|
||||
* merge x merge block consecutive, dy then dx, as the projector's pixel unshuffle reads them, so
|
||||
* its merge is a view); each patch is (y, x, channel). */
|
||||
int Processor::image_lfm2(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const {
|
||||
const VisionConfig& c = cfg_;
|
||||
const int32_t F = c.factor(), P = c.patch, M = c.merge;
|
||||
@@ -823,13 +826,7 @@ int Processor::image_from(const Frame& f, std::shared_ptr<Item>* out, std::strin
|
||||
/* An image fills the temporal depth by repetition. */
|
||||
std::vector<const Frame*> frames((size_t)c.temporal, &r);
|
||||
patchify(c, frames, it.get());
|
||||
content_key(*it, &it->key_hi, &it->key_lo);
|
||||
|
||||
it->expand.reserve((size_t)it->seg_rows + 2);
|
||||
it->expand.push_back(c.tok_start);
|
||||
it->seg_at.push_back(1);
|
||||
it->expand.insert(it->expand.end(), (size_t)it->seg_rows, c.tok_image);
|
||||
it->expand.push_back(c.tok_end);
|
||||
one_run(it.get(), c.tok_start, it->seg_rows, c.tok_image, c.tok_end);
|
||||
*out = std::move(it);
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -856,13 +853,8 @@ int Processor::image_gemma4(const Frame& f, int32_t soft, std::shared_ptr<Item>*
|
||||
if (why) *why = "the image's soft-token budget is more patches than one encoder pass holds";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
patchify_gemma4(c, { src }, it.get());
|
||||
content_key(*it, &it->key_hi, &it->key_lo);
|
||||
it->expand.reserve((size_t)it->seg_rows + 2);
|
||||
it->expand.push_back(c.tok_start);
|
||||
it->seg_at.push_back(1);
|
||||
it->expand.insert(it->expand.end(), (size_t)it->seg_rows, c.tok_image);
|
||||
it->expand.push_back(c.tok_end);
|
||||
patchify_gemma4(c, { src }, /*video=*/false, it.get());
|
||||
one_run(it.get(), c.tok_start, it->seg_rows, c.tok_image, c.tok_end);
|
||||
*out = std::move(it);
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -891,9 +883,9 @@ int Processor::video_gemma4(const Video& v, std::shared_ptr<Item>* out, std::str
|
||||
resize_bicubic(v.frames[i], (int32_t)w, (int32_t)h, &resized[i]);
|
||||
rf.push_back(&resized[i]);
|
||||
}
|
||||
patchify_gemma4(c, rf, it.get());
|
||||
patchify_gemma4(c, rf, /*video=*/true, it.get());
|
||||
content_key(*it, &it->key_hi, &it->key_lo);
|
||||
/* One <boi> placeholders <eoi> run a frame, back to back: the reference's visual-only form
|
||||
/* One <boi> placeholders <eoi> run per frame, back to back: the reference's visual-only form
|
||||
* (add_timestamps off). */
|
||||
for (int32_t g = 0; g < it->grid_t; ++g) {
|
||||
it->expand.push_back(c.tok_start);
|
||||
@@ -909,8 +901,8 @@ int Processor::video_from(const Video& v, std::shared_ptr<Item>* out, std::strin
|
||||
const VisionConfig& c = cfg_;
|
||||
if (c.family == Family::Gemma4) return video_gemma4(v, out, why);
|
||||
if (v.frames.empty()) { if (why) *why = "the video decoded to no frames"; return RAD_E_INVAL; }
|
||||
/* The frames and their indices, padded to whole temporal groups by repeating the last. A clip
|
||||
* shorter than one group is padded the same way, so a single-frame video is one group. */
|
||||
/* Pad the frames and their indices to whole temporal groups by repeating the last; a clip
|
||||
* shorter than one group becomes one group. */
|
||||
std::vector<const Frame*> frames;
|
||||
std::vector<int64_t> idx = v.index;
|
||||
for (const Frame& f : v.frames) frames.push_back(&f);
|
||||
@@ -921,8 +913,8 @@ int Processor::video_from(const Video& v, std::shared_ptr<Item>* out, std::strin
|
||||
const int64_t nf = (int64_t)v.frames.size() < c.temporal ? c.temporal
|
||||
: (int64_t)v.frames.size();
|
||||
|
||||
/* THE PER-FRAME CAP: at most `max_frame_rows` output rows' worth of pixels a frame, and the
|
||||
* video budget's even share, but never under the band's floor. */
|
||||
/* Per-frame cap: at most `max_frame_rows` output rows' worth of pixels per frame and at most
|
||||
* the video budget's even share, but never under the band's floor. */
|
||||
int64_t max_px = c.video_max_pixels;
|
||||
if (c.max_frame_rows > 0) {
|
||||
const int64_t f2 = (int64_t)c.factor() * c.factor();
|
||||
@@ -960,12 +952,11 @@ int Processor::video_from(const Video& v, std::shared_ptr<Item>* out, std::strin
|
||||
patchify(c, rframes, it.get());
|
||||
content_key(*it, &it->key_hi, &it->key_lo);
|
||||
|
||||
/* THE TIMESTAMPED EXPANSION: per temporal group, "<T seconds>" then a run of pads between
|
||||
* vision_start and vision_end, T being the mean of the group's first and last frame times.
|
||||
* It stands for the template's whole <|vision_start|><|video_pad|><|vision_end|>, as the
|
||||
* model's own processor wrote it (transformers 4.57, qwen-vl-utils). transformers 5.x swaps
|
||||
* only the pad and leaves that outer pair around the frames -- two tokens the model was not
|
||||
* trained with. */
|
||||
/* Timestamped expansion: per temporal group, "<T seconds>" then pads between vision_start and
|
||||
* vision_end, T being the mean of the group's first and last frame times. It replaces the
|
||||
* template's whole <|vision_start|><|video_pad|><|vision_end|>, as the model's own processor
|
||||
* does (transformers 4.57, qwen-vl-utils). transformers 5.x replaces only the pad and leaves
|
||||
* an outer start/end pair the model was not trained with. */
|
||||
const double vfps = v.info.fps > 0.0 ? v.info.fps : 24.0;
|
||||
for (int32_t g = 0; g < it->grid_t; ++g) {
|
||||
const double t0 = (double)idx[(size_t)g * c.temporal] / vfps;
|
||||
@@ -1050,11 +1041,51 @@ static std::vector<double> read_list(const RadModelMeta& m, const char* key) {
|
||||
return v;
|
||||
}
|
||||
|
||||
int64_t AudioConfig::chunk_rows(int64_t frames) {
|
||||
for (int i = 0; i < 3; ++i) frames = frames > 0 ? (frames - 1) / 2 + 1 : 0;
|
||||
return frames;
|
||||
}
|
||||
|
||||
/* Qwen3ASRFeatureExtractor's framing, from processor_config.json's `feature_extractor` and the
|
||||
* encoder's audio_config. The mel band (0 to 8000 Hz) is the extractor's own constant, not a
|
||||
* key. */
|
||||
static int qwen3asr_from_meta(const RadModelMeta& m, AudioConfig* c, std::string* why) {
|
||||
auto gi = [&](const char* k, int64_t d) {
|
||||
char key[128];
|
||||
std::snprintf(key, sizeof key, "processor.feature_extractor.%s", k);
|
||||
return rad_meta_geti(&m, key, d);
|
||||
};
|
||||
c->family = AudioFamily::Qwen3ASR;
|
||||
c->rate = (int32_t)gi("sampling_rate", 16000);
|
||||
c->hop = (int32_t)gi("hop_length", 160);
|
||||
c->fft = (int32_t)gi("n_fft", 400);
|
||||
c->frame_length = c->fft;
|
||||
c->n_mels = (int32_t)gi("feature_size", rad_meta_geti(&m, "audio_config.num_mel_bins", 128));
|
||||
c->min_samples = gi("min_length", 8000);
|
||||
c->chunk = (int32_t)(2 * gi("n_window", rad_meta_geti(&m, "audio_config.n_window", 50)));
|
||||
c->min_freq = 0.0;
|
||||
c->max_freq = 8000.0;
|
||||
c->tok_audio = (int32_t)rad_meta_geti(&m, "audio_token_id", -1);
|
||||
if (rad_meta_getf(&m, "processor.feature_extractor.dither", 0.0) != 0.0) {
|
||||
if (why) *why = "the feature extractor dithers its input (feature_extractor.dither), which "
|
||||
"no deterministic front end reproduces";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (c->rate <= 0 || c->hop <= 0 || c->fft < 2 || c->n_mels <= 0 || c->chunk <= 0 ||
|
||||
c->min_samples < 0 || c->tok_audio < 0 || 2.0 * c->max_freq > (double)c->rate) {
|
||||
if (why) *why = "the container's Qwen3-ASR feature configuration is incomplete or "
|
||||
"inconsistent (rate, hop, n_fft, mel bins, n_window, audio_token_id)";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int AudioConfig::from_meta(const RadModelMeta& m, std::string* why) {
|
||||
const char* mt = rad_meta_gets(&m, "audio_config.model_type", "");
|
||||
if (mt && !std::strcmp(mt, "qwen3_asr_encoder")) return qwen3asr_from_meta(m, this, why);
|
||||
if (!mt || std::strcmp(mt, "gemma4_audio")) {
|
||||
if (why) *why = "the container states no audio tower this processor knows (audio_config."
|
||||
"model_type gemma4_audio)";
|
||||
"model_type gemma4_audio or qwen3_asr_encoder)";
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
rate = (int32_t)rad_meta_geti(&m, "preprocessor.sampling_rate", 16000);
|
||||
@@ -1079,8 +1110,8 @@ int AudioConfig::from_meta(const RadModelMeta& m, std::string* why) {
|
||||
tok_audio = (int32_t)rad_meta_geti(&m, "audio_token_id", -1);
|
||||
tok_start = (int32_t)rad_meta_geti(&m, "boa_token_id", -1);
|
||||
tok_end = (int32_t)rad_meta_geti(&m, "eoa_token_id", rad_meta_geti(&m, "eoa_token_index", -1));
|
||||
/* DITHER IS NOISE: the reference adds Gaussian noise of this deviation to every sample, a
|
||||
* different draw each call, and no fixed input reproduces it. */
|
||||
/* Dither adds Gaussian noise of this deviation to every sample, a new draw each call, so no
|
||||
* deterministic front end can reproduce it. */
|
||||
if (rad_meta_getf(&m, "preprocessor.dither", 0.0) != 0.0) {
|
||||
if (why) *why = "the feature extractor dithers its input (preprocessor.dither), which no "
|
||||
"deterministic front end reproduces";
|
||||
@@ -1130,6 +1161,40 @@ void fft_inplace(std::vector<double>& re, std::vector<double>& im,
|
||||
}
|
||||
}
|
||||
|
||||
/* A mixed-radix complex FFT over any length (Whisper's 400 points are 2^4 * 5^2). Decimation in
|
||||
* time over `radix` (the length's prime factors, smallest first): n points at stride s
|
||||
* are p transforms of n / p points at stride s * p, combined by p-point DFTs with twiddles. `tw`
|
||||
* is exp(-2 pi i k / N) for k < N, N the outermost length, read at stride N / n by a level of n
|
||||
* points; `work` is scratch, 2n doubles a level, the levels below reusing what follows. */
|
||||
void fft_mixed(const double* in_re, const double* in_im, int64_t stride, int64_t n,
|
||||
double* out_re, double* out_im, const int32_t* radix,
|
||||
const std::vector<double>& tw_re, const std::vector<double>& tw_im, double* work) {
|
||||
if (n == 1) { out_re[0] = in_re[0]; out_im[0] = in_im[0]; return; }
|
||||
const int64_t p = radix[0], m = n / p;
|
||||
for (int64_t q = 0; q < p; ++q)
|
||||
fft_mixed(in_re + q * stride, in_im + q * stride, stride * p, m, out_re + q * m,
|
||||
out_im + q * m, radix + 1, tw_re, tw_im, work + 2 * n);
|
||||
/* X[k + s m] = sum_q W_n^(q (k + s m)) Y_q[k]: Y_q is periodic in m. */
|
||||
const int64_t step = (int64_t)tw_re.size() / n;
|
||||
double* t_re = work;
|
||||
double* t_im = work + n;
|
||||
for (int64_t k = 0; k < m; ++k)
|
||||
for (int64_t s = 0; s < p; ++s) {
|
||||
const int64_t at = k + s * m;
|
||||
double ar = 0.0, ai = 0.0;
|
||||
for (int64_t q = 0; q < p; ++q) {
|
||||
const int64_t e = (q * at) % n * step;
|
||||
const double yr = out_re[q * m + k], yi = out_im[q * m + k];
|
||||
ar += yr * tw_re[(size_t)e] - yi * tw_im[(size_t)e];
|
||||
ai += yr * tw_im[(size_t)e] + yi * tw_re[(size_t)e];
|
||||
}
|
||||
t_re[at] = ar;
|
||||
t_im[at] = ai;
|
||||
}
|
||||
std::memcpy(out_re, t_re, (size_t)n * sizeof(double));
|
||||
std::memcpy(out_im, t_im, (size_t)n * sizeof(double));
|
||||
}
|
||||
|
||||
/* numpy.linspace's values: start + i * step, the last exactly `stop`. */
|
||||
std::vector<double> linspace(double a, double b, int64_t n) {
|
||||
std::vector<double> v((size_t)n);
|
||||
@@ -1141,52 +1206,102 @@ std::vector<double> linspace(double a, double b, int64_t n) {
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int Processor::init_audio(const AudioConfig& cfg) {
|
||||
if (cfg.merge <= 0 || cfg.max_frames <= 0 || cfg.max_frames % cfg.merge) return RAD_E_INVAL;
|
||||
int Processor::init_audio(const AudioConfig& cfg, std::string* why) {
|
||||
auto refuse = [&](int rc, std::string w) {
|
||||
if (why) *why = std::move(w);
|
||||
return rc;
|
||||
};
|
||||
if (cfg.merge <= 0 || cfg.max_frames <= 0 || cfg.max_frames % cfg.merge)
|
||||
return refuse(RAD_E_INVAL, "the audio encoder's pass (" + std::to_string(cfg.max_frames) +
|
||||
" frames) is not whole rows of " +
|
||||
std::to_string(cfg.merge) + " frames");
|
||||
const bool qwen = cfg.family == AudioFamily::Qwen3ASR;
|
||||
/* Gemma 4's FFT is radix 2; Qwen3-ASR's runs mixed radix over any length. */
|
||||
if (!qwen && (cfg.fft < 2 || (cfg.fft & (cfg.fft - 1)) != 0))
|
||||
return refuse(RAD_E_UNSUPPORTED, "the feature extractor's " + std::to_string(cfg.fft) +
|
||||
"-point FFT is not a power of two, which this "
|
||||
"extractor's radix-2 transform needs");
|
||||
acfg_ = cfg;
|
||||
/* np.hanning(frame_length + 1)[:-1], the periodic window, stored as float32. */
|
||||
if (qwen) {
|
||||
/* A whole chunk is staged as merge * chunk_rows(chunk) frames, which must hold it; a
|
||||
* clip's longest is as many whole chunks as one pass takes. */
|
||||
const int64_t staged = (int64_t)cfg.merge * AudioConfig::chunk_rows(cfg.chunk);
|
||||
if (staged < cfg.chunk || cfg.max_frames < staged)
|
||||
return refuse(RAD_E_INVAL, "a whole " + std::to_string(cfg.chunk) + "-frame chunk is "
|
||||
"staged as " + std::to_string(staged) + " frames, which "
|
||||
"does not hold it or does not fit one " +
|
||||
std::to_string(cfg.max_frames) + "-frame encoder pass");
|
||||
if (cfg.tok_start < 0 || cfg.tok_end < 0)
|
||||
return refuse(RAD_E_INVAL, "the clip's opening or closing token is unresolved");
|
||||
acfg_.max_samples = cfg.max_frames / staged * cfg.chunk * cfg.hop;
|
||||
}
|
||||
/* np.hanning(frame_length + 1)[:-1] -- torch.hann_window's periodic window -- stored as
|
||||
* float32. */
|
||||
hann_.resize((size_t)cfg.frame_length);
|
||||
for (int32_t i = 0; i < cfg.frame_length; ++i)
|
||||
hann_[(size_t)i] = (float)(0.5 - 0.5 * std::cos(2.0 * M_PI * (double)i /
|
||||
(double)cfg.frame_length));
|
||||
/* transformers' mel_filter_bank(norm=None, mel_scale="htk"): triangles between consecutive
|
||||
* mel points, in Hz, over the FFT bins' frequencies. */
|
||||
/* transformers' mel_filter_bank: triangles between consecutive mel points, in Hz, over the
|
||||
* FFT bins' frequencies -- Gemma 4's on the HTK scale with no area normalisation, Qwen3-ASR's
|
||||
* (Whisper's) on the Slaney scale, each triangle scaled to unit area by 2 / (its width in
|
||||
* Hz). */
|
||||
const int64_t nb = cfg.fft / 2 + 1, nm = cfg.n_mels;
|
||||
auto hz2mel = [](double f) { return 2595.0 * std::log10(1.0 + f / 700.0); };
|
||||
auto mel2hz = [](double m) { return 700.0 * (std::pow(10.0, m / 2595.0) - 1.0); };
|
||||
auto htk2mel = [](double f) { return 2595.0 * std::log10(1.0 + f / 700.0); };
|
||||
auto mel2htk = [](double m) { return 700.0 * (std::pow(10.0, m / 2595.0) - 1.0); };
|
||||
const double slaney_step = 27.0 / std::log(6.4);
|
||||
auto slaney2mel = [&](double f) {
|
||||
return f >= 1000.0 ? 15.0 + std::log(f / 1000.0) * slaney_step : 3.0 * f / 200.0;
|
||||
};
|
||||
auto mel2slaney = [&](double m) {
|
||||
return m >= 15.0 ? 1000.0 * std::exp((m - 15.0) / slaney_step) : 200.0 * m / 3.0;
|
||||
};
|
||||
const std::vector<double> fft_f = linspace(0.0, (double)(cfg.rate / 2), nb);
|
||||
std::vector<double> filt = linspace(hz2mel(cfg.min_freq), hz2mel(cfg.max_freq), nm + 2);
|
||||
for (double& f : filt) f = mel2hz(f);
|
||||
std::vector<double> filt = qwen ? linspace(slaney2mel(cfg.min_freq), slaney2mel(cfg.max_freq), nm + 2)
|
||||
: linspace(htk2mel(cfg.min_freq), htk2mel(cfg.max_freq), nm + 2);
|
||||
for (double& f : filt) f = qwen ? mel2slaney(f) : mel2htk(f);
|
||||
mel_.assign((size_t)(nb * nm), 0.0);
|
||||
mel_lo_.assign((size_t)nm, 0);
|
||||
mel_hi_.assign((size_t)nm, 0);
|
||||
for (int64_t i = 0; i < nm; ++i) {
|
||||
const double enorm = qwen ? 2.0 / (filt[(size_t)i + 2] - filt[(size_t)i]) : 1.0;
|
||||
int32_t lo = -1, hi = 0;
|
||||
for (int64_t k = 0; k < nb; ++k) {
|
||||
const double down = -(filt[(size_t)i] - fft_f[(size_t)k]) /
|
||||
(filt[(size_t)i + 1] - filt[(size_t)i]);
|
||||
const double up = (filt[(size_t)i + 2] - fft_f[(size_t)k]) /
|
||||
(filt[(size_t)i + 2] - filt[(size_t)i + 1]);
|
||||
const double w = std::max(0.0, std::min(down, up));
|
||||
const double w = std::max(0.0, std::min(down, up)) * enorm;
|
||||
mel_[(size_t)(i * nb + k)] = w;
|
||||
if (w != 0.0) { if (lo < 0) lo = (int32_t)k; hi = (int32_t)k + 1; }
|
||||
}
|
||||
/* A triangle covers a few bins; the sum skips the zeros, which add nothing to it. */
|
||||
/* A triangle covers a few bins; the sum skips the zeros. */
|
||||
mel_lo_[(size_t)i] = lo < 0 ? 0 : lo;
|
||||
mel_hi_[(size_t)i] = hi;
|
||||
}
|
||||
/* The FFT's twiddles, once: a butterfly that evaluates its own sin and cos makes the
|
||||
* transform cost a 30 s clip over 100 ms. */
|
||||
brev_.assign((size_t)cfg.fft, 0);
|
||||
for (int32_t i = 1, j = 0; i < cfg.fft; ++i) {
|
||||
int32_t bit = cfg.fft >> 1;
|
||||
for (; j & bit; bit >>= 1) j ^= bit;
|
||||
j ^= bit;
|
||||
brev_[(size_t)i] = j;
|
||||
/* Precomputed twiddles: evaluating sin and cos per butterfly costs over 100 ms on a 30 s
|
||||
* clip. Gemma 4's power of two runs radix 2 over half a turn; Qwen3-ASR's FFT runs mixed
|
||||
* radix over the length's prime factors (a power of two included) and a whole turn. */
|
||||
radix_.clear();
|
||||
brev_.clear();
|
||||
const bool pow2 = !qwen;
|
||||
if (pow2) {
|
||||
brev_.assign((size_t)cfg.fft, 0);
|
||||
for (int32_t i = 1, j = 0; i < cfg.fft; ++i) {
|
||||
int32_t bit = cfg.fft >> 1;
|
||||
for (; j & bit; bit >>= 1) j ^= bit;
|
||||
j ^= bit;
|
||||
brev_[(size_t)i] = j;
|
||||
}
|
||||
} else {
|
||||
int32_t r = cfg.fft;
|
||||
for (int32_t f = 2; f * f <= r; ++f)
|
||||
while (r % f == 0) { radix_.push_back(f); r /= f; }
|
||||
if (r > 1) radix_.push_back(r);
|
||||
}
|
||||
tw_re_.resize((size_t)cfg.fft / 2);
|
||||
tw_im_.resize((size_t)cfg.fft / 2);
|
||||
for (int32_t k = 0; k < cfg.fft / 2; ++k) {
|
||||
const int32_t n_tw = pow2 ? cfg.fft / 2 : cfg.fft;
|
||||
tw_re_.resize((size_t)n_tw);
|
||||
tw_im_.resize((size_t)n_tw);
|
||||
for (int32_t k = 0; k < n_tw; ++k) {
|
||||
const double ang = -2.0 * M_PI * (double)k / (double)cfg.fft;
|
||||
tw_re_[(size_t)k] = std::cos(ang);
|
||||
tw_im_[(size_t)k] = std::sin(ang);
|
||||
@@ -1195,10 +1310,124 @@ int Processor::init_audio(const AudioConfig& cfg) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Qwen3-ASR's clip (AudioFamily::Qwen3ASR): Whisper's log-mel over the whole clip, then staged a
|
||||
* chunk at a time. The spectrum is computed in double, two real frames a complex transform as the
|
||||
* Gemma 4 path does; the reference computes in float32, and the difference is far below the bf16
|
||||
* the features are staged in. */
|
||||
int Processor::audio_qwen3asr(const std::vector<float>& samples, std::shared_ptr<Item>* out,
|
||||
std::string* why) const {
|
||||
const AudioConfig& c = acfg_;
|
||||
if ((int64_t)samples.size() > c.max_samples) {
|
||||
if (why) *why = "the clip is longer than one audio encoder pass holds (" +
|
||||
std::to_string(c.max_samples / c.rate) + " s)";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* A clip shorter than min_samples is zero-padded to it first; the reflected padding is of the
|
||||
* padded clip. */
|
||||
const int64_t n = std::max<int64_t>((int64_t)samples.size(), c.min_samples);
|
||||
const int64_t pad = c.fft / 2;
|
||||
if (n <= pad) {
|
||||
if (why) *why = "the clip is too short to frame";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* torch.stft(center=True) makes 1 + n / hop frames and the extractor drops the last. */
|
||||
const int64_t real = n / c.hop;
|
||||
const int64_t full = real / c.chunk, rem = real % c.chunk;
|
||||
const int64_t rows_full = AudioConfig::chunk_rows(c.chunk);
|
||||
const int64_t rows_rem = AudioConfig::chunk_rows(rem);
|
||||
const int64_t staged_full = (int64_t)c.merge * rows_full;
|
||||
const int64_t rows = full * rows_full + rows_rem;
|
||||
const int64_t frames = full * staged_full + (int64_t)c.merge * rows_rem;
|
||||
if (frames > c.max_frames) {
|
||||
if (why) *why = "the clip is more frames than one audio encoder pass holds";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* x[q] of the padded clip, reflected at both ends: torch's "reflect" leaves the edge sample
|
||||
* out, so x[-1] is x[1] and x[n] is x[n - 2]. */
|
||||
auto sample = [&](int64_t p) -> double {
|
||||
int64_t q = p - pad;
|
||||
if (q < 0) q = -q;
|
||||
if (q >= n) q = 2 * (n - 1) - q;
|
||||
return q < (int64_t)samples.size() ? (double)samples[(size_t)q] : 0.0;
|
||||
};
|
||||
const int64_t N = c.fft, nb = N / 2 + 1, nm = c.n_mels;
|
||||
std::vector<double> re((size_t)N), im((size_t)N), ore((size_t)N), oim((size_t)N);
|
||||
std::vector<double> work((size_t)(4 * N));
|
||||
std::vector<double> pw((size_t)nb), pw2((size_t)nb);
|
||||
auto window = [&](int64_t t, double* dst) {
|
||||
for (int64_t j = 0; j < N; ++j)
|
||||
dst[j] = (double)((float)sample(t * c.hop + j) * hann_[(size_t)j]);
|
||||
};
|
||||
std::vector<double> logmel((size_t)(real * nm));
|
||||
double top = -INFINITY;
|
||||
auto emit = [&](int64_t t, const double* p) {
|
||||
double* dst = logmel.data() + t * nm;
|
||||
for (int64_t b = 0; b < nm; ++b) {
|
||||
double s = 0.0;
|
||||
const double* w = mel_.data() + (size_t)b * nb;
|
||||
for (int32_t k = mel_lo_[(size_t)b]; k < mel_hi_[(size_t)b]; ++k) s += p[k] * w[k];
|
||||
const double v = std::log10(std::max(s, 1e-10));
|
||||
dst[b] = v;
|
||||
if (v > top) top = v;
|
||||
}
|
||||
};
|
||||
for (int64_t t = 0; t < real; t += 2) {
|
||||
const bool pair = t + 1 < real;
|
||||
window(t, re.data());
|
||||
if (pair) window(t + 1, im.data());
|
||||
else std::fill(im.begin(), im.end(), 0.0);
|
||||
fft_mixed(re.data(), im.data(), 1, N, ore.data(), oim.data(), radix_.data(), tw_re_,
|
||||
tw_im_, work.data());
|
||||
for (int64_t k = 0; k < nb; ++k) {
|
||||
const size_t a = (size_t)k, b = k ? (size_t)(N - k) : 0;
|
||||
const double ar = 0.5 * (ore[a] + ore[b]), ai = 0.5 * (oim[a] - oim[b]);
|
||||
const double br = 0.5 * (oim[a] + oim[b]), bi = -0.5 * (ore[a] - ore[b]);
|
||||
pw[a] = ar * ar + ai * ai;
|
||||
pw2[a] = br * br + bi * bi;
|
||||
}
|
||||
emit(t, pw.data());
|
||||
if (pair) emit(t + 1, pw2.data());
|
||||
}
|
||||
|
||||
auto it = std::make_shared<Item>();
|
||||
it->kind = Kind::Audio;
|
||||
it->grid_t = 1;
|
||||
it->grid_h = (int32_t)frames;
|
||||
it->grid_w = 1;
|
||||
it->patch_dim = nm;
|
||||
it->n_patch = frames;
|
||||
it->valid = (int32_t)real;
|
||||
it->chunk_staged = (int32_t)staged_full;
|
||||
it->chunk_read = c.chunk;
|
||||
it->rows_h = (int32_t)rows;
|
||||
it->rows_w = 1;
|
||||
it->seg_rows = (int32_t)rows;
|
||||
it->n_seg = rows > 0 ? 1 : 0;
|
||||
/* Chunk k's real frames at row k * staged_full; everything else stays zero -- the reference's
|
||||
* padding inside the last chunk, and the alignment past a whole one. */
|
||||
it->pixels.assign((size_t)(frames * nm), 0);
|
||||
const double floor_v = top - 8.0;
|
||||
for (int64_t t = 0; t < real; ++t) {
|
||||
uint16_t* dst = it->pixels.data() + ((t / c.chunk) * staged_full + t % c.chunk) * nm;
|
||||
const double* src = logmel.data() + t * nm;
|
||||
for (int64_t b = 0; b < nm; ++b)
|
||||
dst[b] = rad_f32_to_bf16((float)((std::max(src[b], floor_v) + 4.0) / 4.0));
|
||||
}
|
||||
content_key(*it, &it->key_hi, &it->key_lo);
|
||||
it->expand.push_back(c.tok_start);
|
||||
it->seg_at.push_back(1);
|
||||
it->expand.insert(it->expand.end(), (size_t)rows, c.tok_audio);
|
||||
it->expand.push_back(c.tok_end);
|
||||
*out = std::move(it);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Processor::audio_from(const std::vector<float>& samples, std::shared_ptr<Item>* out,
|
||||
std::string* why) const {
|
||||
if (!audio_on_) { if (why) *why = "this program declares no audio encoder"; return RAD_E_UNSUPPORTED; }
|
||||
const AudioConfig& c = acfg_;
|
||||
if (c.family == AudioFamily::Qwen3ASR) return audio_qwen3asr(samples, out, why);
|
||||
const int64_t n = std::min<int64_t>((int64_t)samples.size(), c.max_samples);
|
||||
const int64_t real = c.real_frames(n);
|
||||
const int64_t rows = (real + c.merge - 1) / c.merge;
|
||||
@@ -1258,11 +1487,11 @@ int Processor::audio_from(const std::vector<float>& samples, std::shared_ptr<Ite
|
||||
dst[b] = rad_f32_to_bf16((float)v);
|
||||
}
|
||||
};
|
||||
/* TWO REAL FRAMES A COMPLEX TRANSFORM: frame a in the real part, frame b in the imaginary,
|
||||
* and the two spectra separate by symmetry -- A[k] = (Z[k] + conj Z[n-k]) / 2 and
|
||||
* B[k] = (Z[k] - conj Z[n-k]) / 2i. Half the transforms; the magnitudes agree with one
|
||||
* transform a frame to a few ulps of double. |X| is sqrt(re^2 + im^2), within an ulp of
|
||||
* numpy's hypot and far below the float32 the features are rounded to. */
|
||||
/* Two real frames per complex transform: frame a in the real part, frame b in the imaginary,
|
||||
* separated by symmetry as A[k] = (Z[k] + conj Z[n-k]) / 2 and B[k] = (Z[k] - conj Z[n-k]) / 2i.
|
||||
* This halves the transforms; magnitudes match one transform per frame to a few ulps of double.
|
||||
* |X| is sqrt(re^2 + im^2), within an ulp of numpy's hypot and far below the float32 the
|
||||
* features are rounded to. */
|
||||
std::vector<double> mag2((size_t)nb);
|
||||
const int64_t N = c.fft;
|
||||
for (int64_t i = 0; i < real; i += 2) {
|
||||
@@ -1281,11 +1510,7 @@ int Processor::audio_from(const std::vector<float>& samples, std::shared_ptr<Ite
|
||||
emit(i, mag.data());
|
||||
if (pair) emit(i + 1, mag2.data());
|
||||
}
|
||||
content_key(*it, &it->key_hi, &it->key_lo);
|
||||
it->expand.push_back(c.tok_start);
|
||||
it->seg_at.push_back(1);
|
||||
it->expand.insert(it->expand.end(), (size_t)rows, c.tok_audio);
|
||||
it->expand.push_back(c.tok_end);
|
||||
one_run(it.get(), c.tok_start, rows, c.tok_audio, c.tok_end);
|
||||
/* A clip too short for one real frame is <boa><eoa> and nothing to encode. */
|
||||
if (rows == 0) it->encoded = true;
|
||||
*out = std::move(it);
|
||||
@@ -1296,7 +1521,10 @@ int Processor::audio(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out,
|
||||
std::string* why) const {
|
||||
if (!audio_on_) { if (why) *why = "this program declares no audio encoder"; return RAD_E_UNSUPPORTED; }
|
||||
std::vector<float> s;
|
||||
RAD_TRY(decode_audio(bytes, n, acfg_.rate, acfg_.max_samples, &s, why));
|
||||
/* Gemma 4's extractor truncates at max_samples; Qwen3-ASR's does not, so one sample more is
|
||||
* decoded and a clip past a pass is refused rather than cut. */
|
||||
const bool whole = acfg_.family == AudioFamily::Qwen3ASR;
|
||||
RAD_TRY(decode_audio(bytes, n, acfg_.rate, acfg_.max_samples + (whole ? 1 : 0), &s, why));
|
||||
return audio_from(s, out, why);
|
||||
}
|
||||
|
||||
|
||||
+117
-78
@@ -1,26 +1,26 @@
|
||||
/* processor.h -- what an image or a video becomes before an encoder sees it (spec §11).
|
||||
/* processor.h -- what an image, video or audio clip becomes before an encoder sees it (spec §11).
|
||||
*
|
||||
* THIS IS THE QWEN-VL PROCESSOR FAMILY (Qwen2-VL through Qwen3.x), and what is family-specific is
|
||||
* the arithmetic, not the numbers: every size, rate and token id comes from the container, which
|
||||
* carries the checkpoint's config.json and its two preprocessor configs (rad-convert writes them
|
||||
* under `vision_config.*`, `preprocessor.*` and `video_preprocessor.*`). What the family fixes:
|
||||
* The family fixes the arithmetic, not the numbers: every size, rate and token id comes from the
|
||||
* container, which carries the checkpoint's config.json and its two preprocessor configs
|
||||
* (rad-convert writes them under `vision_config.*`, `preprocessor.*` and `video_preprocessor.*`).
|
||||
* The Qwen-VL family (Qwen2-VL through Qwen3.x), the reference shape the others follow:
|
||||
*
|
||||
* - A picture is resized so both sides are multiples of patch * merge and its area falls in the
|
||||
* configured band, keeping the aspect ratio (smart_resize), with PIL's antialiased bicubic.
|
||||
* - It is cut into patch x patch squares, `temporal` frames deep -- an image is repeated to fill
|
||||
* the depth -- in MERGE-BLOCK ORDER: the merge x merge patches that become one output row are
|
||||
* - It is cut into patch x patch squares, `temporal` frames deep (an image is repeated to fill
|
||||
* the depth), in merge-block order: the merge x merge patches that become one output row are
|
||||
* consecutive. Each patch row is (channel, frame, y, x), normalised by the configured mean and
|
||||
* deviation, in bf16.
|
||||
* - The prompt gets `<vision_start> pad*N <vision_end>` where the template put the media, N
|
||||
* being the encoder's output rows. A video gets one such run per temporal group, each after
|
||||
* the text `<T seconds>` giving the group's time -- which is how the model knows when a frame
|
||||
* is, since the groups share one temporal rotary component.
|
||||
* - Rotary positions are three components (temporal, height, width): text counts up in all
|
||||
* being the encoder's output rows. A video gets one run per temporal group, each after the
|
||||
* text `<T seconds>`; the groups share one temporal rotary component, so the text is how the
|
||||
* model knows when a frame is.
|
||||
* - Rotary positions have three components (temporal, height, width). Text counts up in all
|
||||
* three; a media run holds its start in the first and adds its row and column to the other
|
||||
* two; the text after it continues from start + max(rows, cols). (RopeLayout below.)
|
||||
* two; the text after it continues from start + max(rows, cols). See RopeLayout.
|
||||
*
|
||||
* The encoder's input is patches plus each patch's (row, col) in its segment and the segment's
|
||||
* size, which is all a learned position table and a 2-D rotary embedding need; the processor
|
||||
* size, which is all a learned position table or a 2-D rotary embedding needs. The processor
|
||||
* produces those too, so the core stages them without knowing what they are for.
|
||||
*/
|
||||
#pragma once
|
||||
@@ -39,7 +39,7 @@ namespace mm {
|
||||
|
||||
enum class Kind { Image, Video, Audio };
|
||||
|
||||
/* THE PROCESSOR FAMILY, from the container's vision_config.model_type. The two differ in how a
|
||||
/* The processor family, from the container's vision_config.model_type. Families differ in how a
|
||||
* picture is sized, what a patch value is, and how a video is sampled and spelled in the prompt;
|
||||
* the Item they produce and everything after it is shared.
|
||||
*
|
||||
@@ -61,16 +61,16 @@ enum class Family { QwenVL, Gemma4, Lfm2 };
|
||||
struct VisionConfig {
|
||||
Family family = Family::QwenVL;
|
||||
int32_t patch = 0, temporal = 0, merge = 0;
|
||||
/* Gemma4: soft tokens (output rows) an image, and a video frame, may take. One of 70, 140,
|
||||
* 280, 560, 1120 -- the budgets the model was trained at. */
|
||||
/* Gemma4: soft tokens (output rows) an image and a video frame may take. One of 70, 140,
|
||||
* 280, 560, 1120, the budgets the model was trained at. */
|
||||
int32_t image_soft_tokens = 0, video_soft_tokens = 0;
|
||||
int64_t image_min_pixels = 0, image_max_pixels = 0;
|
||||
int64_t video_min_pixels = 0, video_max_pixels = 0;
|
||||
double fps = 2.0;
|
||||
int32_t min_frames = 4, max_frames = 768;
|
||||
/* The per-frame ceiling on a video's resolution, in output rows: a clip that samples few
|
||||
* frames does not spend the whole video budget on near-native frames, so the cost of a video
|
||||
* grows with its length (the reference processor's per-frame cap). 0 turns the cap off. */
|
||||
/* Per-frame ceiling on a video's resolution, in output rows (the reference processor's
|
||||
* per-frame cap). A clip with few frames does not spend the whole video budget on
|
||||
* near-native frames, so a video's cost grows with its length. 0 turns the cap off. */
|
||||
int32_t max_frame_rows = 768;
|
||||
float mean[3] = { 0.5f, 0.5f, 0.5f };
|
||||
float stdv[3] = { 0.5f, 0.5f, 0.5f };
|
||||
@@ -81,62 +81,97 @@ struct VisionConfig {
|
||||
double max_pixels_tolerance = 0.0;
|
||||
int64_t max_segment_patches = 0;
|
||||
|
||||
/* THE DEPLOYMENT'S BOUNDS, not the checkpoint's. `max_patches` is the encoder's pass size: an
|
||||
* image is one segment and a segment is never split, so no image may resize past it, and the
|
||||
* image band's ceiling is lowered to fit. `max_source_pixels` bounds what the decoder is asked
|
||||
* to hold before any resize. */
|
||||
/* Deployment bounds, not the checkpoint's. `max_patches` is the encoder's pass size: an image
|
||||
* is one segment and a segment is never split, so the image band's ceiling is lowered to fit
|
||||
* it. `max_source_pixels` bounds what the decoder may hold before any resize. */
|
||||
int64_t max_patches = 0;
|
||||
int64_t max_source_pixels = (int64_t)1 << 26;
|
||||
/* A whole video's patch budget, across all its passes. */
|
||||
int64_t max_video_patches = 0;
|
||||
|
||||
/* The pixel bands are non-empty and the frame counts and rate positive. RAD_OK, or
|
||||
* RAD_E_INVAL with the first one that is not in `why`. from_meta runs it on what the
|
||||
* container states, and the engine again after the command line has replaced some of it. */
|
||||
/* Checks the pixel bands are non-empty and the frame counts and rate positive; RAD_E_INVAL
|
||||
* names the first violation in `why`. from_meta runs it on the container's values, and the
|
||||
* engine again after command-line overrides. */
|
||||
int check(std::string* why) const;
|
||||
|
||||
int64_t patch_dim() const { return 3LL * temporal * patch * patch; }
|
||||
int32_t factor() const { return patch * merge; }
|
||||
|
||||
/* Read from the container. Refuses a container that states no vision tower; the defaults for
|
||||
* the processor-only keys are the family's, used only when the container omits them. */
|
||||
/* Read from the container; refuses one with no vision tower. Processor-only keys the
|
||||
* container omits take the family's defaults. */
|
||||
int from_meta(const RadModelMeta& m, std::string* why);
|
||||
};
|
||||
|
||||
/* WHAT AN AUDIO CLIP BECOMES: Gemma 4's feature extractor (Gemma4AudioFeatureExtractor), read
|
||||
* from the container's `preprocessor.*` (the checkpoint's preprocessor_config.json) and its
|
||||
* audio_config. The samples are mono at `rate`, cut at `max_samples`; `frame_length / 2` zeros go
|
||||
* in front; frame i is samples [i * hop, i * hop + frame_length) of that, pre-emphasised when the
|
||||
* config says so, times a periodic Hann window, through a `fft`-point real FFT; its magnitudes go
|
||||
* through an HTK mel bank (no area normalisation) and log(x + mel_floor), optionally standardised
|
||||
* per bin. A frame is real when its last sample is a real one -- the reference's mask -- so a clip
|
||||
* of n samples has floor((n - frame_length / 2 - 1) / hop) + 1 real frames and the reference's
|
||||
* output keeps ceil(real / merge) rows of it: that many placeholders, between <boa> and <eoa>.
|
||||
* The staged patches are the real frames then zero frames to a whole number of rows -- equal, for
|
||||
* every row the reference keeps, to the frames past the end the reference zeroes. */
|
||||
/* The audio feature extractor family, from the container's audio_config.model_type. The
|
||||
* families differ in the spectrogram and in how a clip's frames are laid out for the encoder;
|
||||
* the Item they produce is shared.
|
||||
*
|
||||
* Gemma4 Gemma4AudioFeatureExtractor: a frame_length / 2 zero lead, a periodic Hann window
|
||||
* through an fft-point FFT, magnitudes through an HTK mel bank, log(x + mel_floor).
|
||||
* The clip's real frames, then zero frames to whole output rows.
|
||||
*
|
||||
* Qwen3ASR Qwen3ASRFeatureExtractor (Whisper's): a clip shorter than `min_samples` is
|
||||
* zero-padded to it; frames are torch.stft's, centred with a reflected n_fft / 2 at
|
||||
* each end, a periodic Hann window and power spectra, the last frame dropped, so n
|
||||
* samples are n / hop frames; a Slaney mel bank with Slaney area normalisation;
|
||||
* log10(max(x, 1e-10)), floored at the clip's maximum less 8, then (x + 4) / 4.
|
||||
* The encoder convolves each `chunk` frames (one second) on its own, zero-padded to a
|
||||
* whole chunk, and keeps `chunk_rows(L)` rows of a chunk of L real frames. A chunk is
|
||||
* staged as merge * chunk_rows(L) frames: its real frames, the reference's zero
|
||||
* padding, and, where that exceeds a whole chunk, frames past it that the encoder
|
||||
* reads as zero. Plane 1 of the coordinates marks those (RadBatch::enc_coord), which
|
||||
* keeps one chunk's convolution from seeing the next. */
|
||||
enum class AudioFamily { Gemma4, Qwen3ASR };
|
||||
|
||||
/* Audio features, configured from the container: Gemma 4's framing from `preprocessor.*` (the
|
||||
* checkpoint's preprocessor_config.json), Qwen3-ASR's from `processor.feature_extractor.*`
|
||||
* (processor_config.json), and the encoder's own from audio_config.
|
||||
*
|
||||
* Gemma 4: samples are mono at `rate`, cut at `max_samples`, with `frame_length / 2` zeros in
|
||||
* front. Frame i is samples [i * hop, i * hop + frame_length), pre-emphasised when configured,
|
||||
* times a periodic Hann window, through an `fft`-point real FFT; magnitudes go through an HTK mel
|
||||
* bank (no area normalisation) and log(x + mel_floor), optionally standardised per bin.
|
||||
*
|
||||
* A frame is real when its last sample is (the reference's mask), so an n-sample clip has
|
||||
* floor((n - frame_length / 2 - 1) / hop) + 1 real frames and keeps ceil(real / merge) output
|
||||
* rows: that many placeholders between <boa> and <eoa>. The staged patches are the real frames
|
||||
* then zero frames up to a whole row, which matches the reference's zeroed frames past the end
|
||||
* for every row it keeps. */
|
||||
struct AudioConfig {
|
||||
AudioFamily family = AudioFamily::Gemma4;
|
||||
int32_t rate = 0, frame_length = 0, hop = 0, fft = 0, n_mels = 0;
|
||||
double min_freq = 0.0, max_freq = 0.0, mel_floor = 0.0;
|
||||
double preemphasis = 0.0, input_scale = 1.0;
|
||||
bool preemphasis_htk = true;
|
||||
std::vector<double> bin_mean, bin_std; /* empty: no per-bin standardisation */
|
||||
/* The longest clip in samples: Gemma 4's extractor truncates at 480000 (30 s at 16 kHz). */
|
||||
/* The longest clip in samples: Gemma 4's extractor truncates at 480000 (30 s at 16 kHz).
|
||||
* Qwen3-ASR's does not truncate, and its longest clip is what one encoder pass holds. */
|
||||
int64_t max_samples = 0;
|
||||
/* Qwen3ASR: a shorter clip is zero-padded to this many samples first (the reference's
|
||||
* min_length); the frames the encoder convolves on their own (2 * n_window). */
|
||||
int64_t min_samples = 0;
|
||||
int32_t chunk = 0;
|
||||
int32_t tok_audio = -1, tok_start = -1, tok_end = -1;
|
||||
|
||||
/* THE ENCODER'S: frames an output row, and the most frames a pass carries. */
|
||||
/* The encoder's: frames per output row, and the most frames a pass carries. */
|
||||
int32_t merge = 0;
|
||||
int64_t max_frames = 0;
|
||||
|
||||
/* Read from the container; refuses one that states no Gemma 4 audio tower. */
|
||||
/* Read from the container; refuses one that states no audio tower this processor knows.
|
||||
* Qwen3-ASR's config names no token around its placeholders, so tok_start and tok_end stay
|
||||
* -1 for the caller to resolve (the architecture plugin spells them; see
|
||||
* RadAudioFormat::audio_open). */
|
||||
int from_meta(const RadModelMeta& m, std::string* why);
|
||||
/* The real frames of an n-sample clip. */
|
||||
int64_t real_frames(int64_t n_samples) const;
|
||||
/* Qwen3ASR: the encoder rows a chunk of `frames` real frames keeps -- three convolutions of
|
||||
* kernel 3, stride 2 and padding 1, so a whole chunk of 100 is 13. */
|
||||
static int64_t chunk_rows(int64_t frames);
|
||||
};
|
||||
|
||||
/* One media part after processing: its patches, its place in the prompt's token stream, and --
|
||||
* once the encoder has run -- its rows. Shared between the request that owns it and the engine
|
||||
* thread that encodes it; the engine writes `embd` once and nothing reads it before then. */
|
||||
/* One media part after processing: its patches, its place in the prompt's token stream and, once
|
||||
* the encoder has run, its rows. Shared between the owning request and the engine thread that
|
||||
* encodes it; the engine writes `embd` once and nothing reads it before then. */
|
||||
struct Item {
|
||||
Kind kind = Kind::Image;
|
||||
int32_t grid_t = 0, grid_h = 0, grid_w = 0; /* in patches; grid_t temporal groups */
|
||||
@@ -147,14 +182,18 @@ struct Item {
|
||||
/* The encoder's output: n_seg segments of seg_rows rows, one segment per temporal group.
|
||||
* `rows_w` is a segment's width in output rows, which is where its rotary grid wraps. */
|
||||
int32_t n_seg = 0, seg_rows = 0, rows_w = 0, rows_h = 0;
|
||||
/* An audio clip's REAL feature frames; the rest of its `grid_h` are the zero frames that make
|
||||
* it whole output rows. 0 for a picture or a video. */
|
||||
/* An audio clip's real feature frames; the rest of `grid_h` are zero frames padding it to
|
||||
* whole output rows. 0 for a picture or a video. */
|
||||
int32_t valid = 0;
|
||||
/* An audio clip staged in chunks (AudioFamily::Qwen3ASR): each chunk but the last is
|
||||
* `chunk_staged` frames, of which the first `chunk_read` take part in the convolution and the
|
||||
* rest read as zero. 0 for a clip staged whole. */
|
||||
int32_t chunk_staged = 0, chunk_read = 0;
|
||||
|
||||
/* SEGMENTS OF THEIR OWN SIZE, when an item's segments differ -- an LFM2-VL picture is its
|
||||
* tiles and a thumbnail -- each `h` x `w` patches from patch `patch0` on. Empty, every segment
|
||||
* is grid_h x grid_w (a picture, a video's temporal groups, an audio clip). The accessors
|
||||
* below are the only way the rest of the engine reads a segment, so both forms look alike. */
|
||||
/* Per-segment sizes, when an item's segments differ (an LFM2-VL picture is its tiles plus a
|
||||
* thumbnail): each is `h` x `w` patches starting at patch `patch0`. Empty means every segment
|
||||
* is grid_h x grid_w. The rest of the engine reads segments only through the accessors below,
|
||||
* so both forms look alike. */
|
||||
struct Segment { int32_t h = 0, w = 0; int64_t patch0 = 0; };
|
||||
std::vector<Segment> segments;
|
||||
/* The model rotates this item's tokens at their token positions (LFM2-VL's 1-D rotary), not
|
||||
@@ -175,21 +214,21 @@ struct Item {
|
||||
}
|
||||
int64_t n_rows() const { return row_at(n_seg); }
|
||||
|
||||
/* THE TOKENS THAT REPLACE THE MEDIA MARKER, and where in them each segment's run of
|
||||
* placeholders starts. Placeholders are the checkpoint's own pad ids, not an arbitrary one:
|
||||
* an n-gram embedding hashes them like any other id. */
|
||||
/* The tokens that replace the media marker, and where in them each segment's placeholder run
|
||||
* starts. Placeholders are the checkpoint's own pad ids, because an n-gram embedding hashes
|
||||
* them like any other id. */
|
||||
std::vector<int32_t> expand;
|
||||
std::vector<int32_t> seg_at;
|
||||
|
||||
/* A CONTENT KEY over the patches and the grid. It is taken BEFORE the encoder runs, so a
|
||||
* prefix-cache hit over this item skips the encoder as well as the prefill: the patches are
|
||||
* what the encoder is a function of, and they already reflect every preprocessing choice. */
|
||||
/* Content key over the patches and the grid, taken before the encoder runs, so a prefix-cache
|
||||
* hit over this item skips the encoder as well as the prefill. The patches already reflect
|
||||
* every preprocessing choice, and the encoder is a function of them alone. */
|
||||
uint64_t key_hi = 0, key_lo = 0;
|
||||
|
||||
/* [n_rows, n_embd] bf16, written by the engine after the encoder pass. */
|
||||
std::vector<uint16_t> embd;
|
||||
bool encoded = false;
|
||||
/* Handed to the engine's encoder queue and not yet encoded -- the scheduler's thread only. */
|
||||
/* Handed to the engine's encoder queue and not yet encoded. Scheduler thread only. */
|
||||
bool queued = false;
|
||||
|
||||
/* The (row, col, rows, cols) of each patch in its segment, for the encoder: component-major,
|
||||
@@ -197,16 +236,16 @@ struct Item {
|
||||
void coords(int64_t first, int64_t count, int32_t* planes) const;
|
||||
};
|
||||
|
||||
/* THE ROTARY LAYOUT OF ONE PROMPT: which tokens are media and where each run's grid sits. Built
|
||||
* once when the prompt is tokenised; `at` is what the batch builder asks for every row of every
|
||||
* pass, so it is a binary search over runs rather than an array the length of the prompt. */
|
||||
/* The rotary layout of one prompt: which tokens are media and where each run's grid sits. Built
|
||||
* once when the prompt is tokenised. The batch builder calls `at` for every row of every pass,
|
||||
* so it is a binary search over runs rather than an array the length of the prompt. */
|
||||
struct RopeLayout {
|
||||
struct Run {
|
||||
int32_t tok = 0; /* first placeholder token of the run */
|
||||
int32_t n = 0; /* its length: rows_h * rows_w */
|
||||
int32_t w = 0; /* its width in rows */
|
||||
int32_t base = 0; /* the rotary position of its first token */
|
||||
int32_t shift = 0; /* rotary minus token index for the text AFTER the run */
|
||||
int32_t shift = 0; /* rotary minus token index for the text after the run */
|
||||
int32_t item = 0; /* which of PromptMedia::items the run belongs to */
|
||||
int32_t row0 = 0; /* the item's encoder row that its first token takes */
|
||||
bool flat = false; /* Item::rope_1d: the run's tokens rotate at their positions */
|
||||
@@ -215,8 +254,8 @@ struct RopeLayout {
|
||||
|
||||
bool empty() const { return runs.empty(); }
|
||||
|
||||
/* The last run starting at or before token i, or null. Inline and dependency-free, because
|
||||
* the batch builder asks it for every row of every pass. */
|
||||
/* The last run starting at or before token i, or null. Inline because the batch builder
|
||||
* calls it for every row of every pass. */
|
||||
const Run* last_at(int64_t i) const {
|
||||
size_t lo = 0, hi = runs.size();
|
||||
while (lo < hi) {
|
||||
@@ -238,11 +277,6 @@ struct RopeLayout {
|
||||
}
|
||||
out[0] = out[1] = out[2] = (int32_t)(i + r->shift);
|
||||
}
|
||||
/* Rotary minus index for text at or after token i -- the one number a decode row needs. */
|
||||
int32_t shift_at(int64_t i) const {
|
||||
const Run* r = last_at(i);
|
||||
return r ? r->shift : 0;
|
||||
}
|
||||
/* The run holding token i, or null when i is text. */
|
||||
const Run* run_at(int64_t i) const {
|
||||
const Run* r = last_at(i);
|
||||
@@ -250,7 +284,7 @@ struct RopeLayout {
|
||||
}
|
||||
};
|
||||
|
||||
/* THE MEDIA A PROMPT CARRIES, in prompt order, with where each item's expansion begins. */
|
||||
/* One media item of a prompt and where its expansion begins. */
|
||||
struct Placed {
|
||||
std::shared_ptr<Item> item;
|
||||
int32_t tok = 0; /* index of item->expand[0] in the prompt */
|
||||
@@ -266,30 +300,31 @@ struct PromptMedia {
|
||||
class Processor {
|
||||
public:
|
||||
/* `encode_text` tokenises the timestamp text between a video's groups: plain text, no
|
||||
* special tokens added and none parsed. `token_id` is the id of the vocabulary entry spelled
|
||||
* exactly so, or -1: how a family whose markers the config does not number (LFM2-VL's tile
|
||||
* and thumbnail markers) finds them. */
|
||||
* special tokens added or parsed. `token_id` returns the id of the vocabulary entry spelled
|
||||
* exactly so, or -1; it finds markers the config does not number (LFM2-VL's tile and
|
||||
* thumbnail markers). */
|
||||
int init(const VisionConfig& cfg, std::function<std::vector<int32_t>(const std::string&)> encode_text,
|
||||
std::function<int32_t(const std::string&)> token_id = {});
|
||||
const VisionConfig& config() const { return cfg_; }
|
||||
|
||||
/* `image_tokens` is a Gemma 4 soft-token budget for this image (0: the configured one); a
|
||||
* processor that sizes images by pixels refuses a non-zero one. `max_pixels`, when set, first
|
||||
* scales a larger picture down to that area (PIL's bicubic), as a caller's own pipeline may. */
|
||||
* scales a larger picture down to that area with PIL's bicubic. */
|
||||
int image(const uint8_t* bytes, size_t n, int32_t image_tokens, std::shared_ptr<Item>* out,
|
||||
std::string* why, int64_t max_pixels = 0) const;
|
||||
int video(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
|
||||
/* The pieces, exposed for the test suite: an already-decoded picture or frame list. */
|
||||
/* From an already-decoded picture or frame list; for tests. */
|
||||
int image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
int video_from(const Video& v, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
|
||||
/* AUDIO, when the program declared an audio encoder: `merge` and `max_frames` are its. */
|
||||
int init_audio(const AudioConfig& cfg);
|
||||
/* Audio, when the program declares an audio encoder; `merge` and `max_frames` are the
|
||||
* encoder's. */
|
||||
int init_audio(const AudioConfig& cfg, std::string* why = nullptr);
|
||||
bool has_audio() const { return audio_on_; }
|
||||
const AudioConfig& audio_config() const { return acfg_; }
|
||||
int audio(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
/* ...and from samples already decoded (mono at the configured rate), for the test suite. */
|
||||
/* From samples already decoded (mono at the configured rate); for tests. */
|
||||
int audio_from(const std::vector<float>& samples, std::shared_ptr<Item>* out,
|
||||
std::string* why) const;
|
||||
|
||||
@@ -305,11 +340,15 @@ private:
|
||||
VisionConfig cfg_{};
|
||||
AudioConfig acfg_{};
|
||||
bool audio_on_ = false;
|
||||
int audio_qwen3asr(const std::vector<float>& samples, std::shared_ptr<Item>* out,
|
||||
std::string* why) const;
|
||||
|
||||
std::vector<float> hann_; /* the window, float32 as the reference stores it */
|
||||
std::vector<double> mel_; /* [n_mels, fft/2 + 1]: filter b's weight on bin k */
|
||||
std::vector<int32_t> mel_lo_, mel_hi_; /* filter b's nonzero bins, [lo, hi) */
|
||||
std::vector<double> tw_re_, tw_im_; /* exp(-2 pi i k / fft), k < fft/2 */
|
||||
std::vector<int32_t> brev_; /* the FFT's bit-reversal permutation */
|
||||
std::vector<int32_t> radix_; /* a non-power-of-two FFT's factors, smallest first */
|
||||
std::function<std::vector<int32_t>(const std::string&)> encode_text_;
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
#include "mm/resample.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <iterator>
|
||||
#include <numeric>
|
||||
|
||||
namespace rad {
|
||||
namespace mm {
|
||||
|
||||
namespace {
|
||||
|
||||
const int32_t kRates[] = { 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000 };
|
||||
/* The sinc's zero crossings either side of an output sample, at the lower of the two rates. */
|
||||
constexpr double kLobes = 16.0;
|
||||
/* The cut-off as a fraction of the lower Nyquist frequency, and the Kaiser window's shape: about
|
||||
* 80 dB down past the transition band, which leaves nothing a 16-bit stream could show. */
|
||||
constexpr double kRolloff = 0.92;
|
||||
constexpr double kBeta = 8.0;
|
||||
/* Input the output has moved past is dropped once there is this much of it, not sample by
|
||||
* sample: dropping is a move of everything after it. */
|
||||
constexpr int64_t kDropAt = 8192;
|
||||
|
||||
double bessel_i0(double x) {
|
||||
double sum = 1.0, term = 1.0;
|
||||
for (int k = 1; k < 64; ++k) {
|
||||
term *= (x / (2.0 * k)) * (x / (2.0 * k));
|
||||
sum += term;
|
||||
if (term < 1e-15 * sum) break;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
bool Resampler::takes(int32_t rate) {
|
||||
return std::find(std::begin(kRates), std::end(kRates), rate) != std::end(kRates);
|
||||
}
|
||||
|
||||
std::string Resampler::rates() {
|
||||
std::string s;
|
||||
for (int32_t r : kRates) {
|
||||
if (!s.empty()) s += ", ";
|
||||
s += std::to_string(r);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
Resampler::Resampler(int32_t from, int32_t to) {
|
||||
const int32_t g = std::gcd(from, to);
|
||||
up_ = to / g;
|
||||
down_ = from / g;
|
||||
if (up_ != down_) {
|
||||
/* The cut-off in cycles an input sample, and the taps' reach: kLobes zero crossings of a
|
||||
* sinc that narrow, which is wider in input samples the further the rate comes down. */
|
||||
const double fc = 0.5 * kRolloff * std::min(1.0, (double)up_ / down_);
|
||||
half_ = (int32_t)std::ceil(kLobes / (2.0 * fc));
|
||||
taps_.assign((size_t)up_ * 2 * half_, 0.0f);
|
||||
const double i0b = bessel_i0(kBeta);
|
||||
for (int32_t p = 0; p < up_; ++p) {
|
||||
/* Phase p is an output sample p/up_ of an input sample past the input it is centred
|
||||
* on; tap k reads the input half_ - 1 - k before that one. */
|
||||
const double frac = (double)p / up_;
|
||||
float* h = &taps_[(size_t)p * 2 * half_];
|
||||
double sum = 0.0;
|
||||
for (int32_t k = 0; k < 2 * half_; ++k) {
|
||||
const double t = (double)(k - half_ + 1) - frac;
|
||||
const double x = 2.0 * fc * t;
|
||||
const double sinc = x == 0.0 ? 1.0 : std::sin(M_PI * x) / (M_PI * x);
|
||||
const double r = t / half_;
|
||||
const double w = std::fabs(r) >= 1.0
|
||||
? 0.0 : bessel_i0(kBeta * std::sqrt(1.0 - r * r)) / i0b;
|
||||
h[k] = (float)(sinc * w);
|
||||
sum += h[k];
|
||||
}
|
||||
/* Unity gain at DC, phase by phase, so a constant comes out the constant it went in. */
|
||||
for (int32_t k = 0; k < 2 * half_; ++k) h[k] = (float)(h[k] / sum);
|
||||
}
|
||||
}
|
||||
reset();
|
||||
}
|
||||
|
||||
void Resampler::reset() {
|
||||
/* The history before the first sample is silence. */
|
||||
in_.assign((size_t)std::max(half_ - 1, 0), 0.0f);
|
||||
base_ = -(int64_t)in_.size();
|
||||
next_ = 0;
|
||||
n_in_ = 0;
|
||||
}
|
||||
|
||||
void Resampler::push(const float* in, size_t n, std::vector<float>* out) {
|
||||
if (up_ == down_) {
|
||||
out->insert(out->end(), in, in + n);
|
||||
return;
|
||||
}
|
||||
in_.insert(in_.end(), in, in + n);
|
||||
n_in_ += (int64_t)n;
|
||||
for (;;) {
|
||||
const int64_t pos = next_ * down_;
|
||||
const int64_t c = pos / up_;
|
||||
if (c + half_ >= n_in_) break;
|
||||
const float* h = &taps_[(size_t)(pos % up_) * 2 * half_];
|
||||
const float* x = &in_[(size_t)(c - half_ + 1 - base_)];
|
||||
float acc = 0.0f;
|
||||
for (int32_t k = 0; k < 2 * half_; ++k) acc += x[k] * h[k];
|
||||
out->push_back(acc);
|
||||
++next_;
|
||||
}
|
||||
const int64_t keep = (next_ * down_) / up_ - half_ + 1;
|
||||
if (keep - base_ >= kDropAt) {
|
||||
in_.erase(in_.begin(), in_.begin() + (std::ptrdiff_t)(keep - base_));
|
||||
base_ = keep;
|
||||
}
|
||||
}
|
||||
|
||||
void Resampler::flush(std::vector<float>* out) {
|
||||
if (up_ != down_) {
|
||||
/* Every output sample the input spans, the last ones read against silence. */
|
||||
const int64_t total = (n_in_ * up_ + down_ - 1) / down_;
|
||||
const std::vector<float> silence((size_t)(2 * half_ + down_), 0.0f);
|
||||
std::vector<float> rest;
|
||||
push(silence.data(), silence.size(), &rest);
|
||||
const int64_t want = total - (next_ - (int64_t)rest.size());
|
||||
rest.resize((size_t)std::max<int64_t>(0, std::min<int64_t>(want, (int64_t)rest.size())));
|
||||
out->insert(out->end(), rest.begin(), rest.end());
|
||||
}
|
||||
reset();
|
||||
}
|
||||
|
||||
} /* namespace mm */
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,54 @@
|
||||
/* resample.h -- a streaming resampler for mono float audio, between the rates a client sends
|
||||
* and the rate an audio encoder takes.
|
||||
*
|
||||
* A file is resampled by libswresample as it is decoded (media.cpp). A stream arrives a few
|
||||
* milliseconds at a time over a socket, and each piece must continue the last with no edge at the
|
||||
* seam: this keeps the input it still needs between calls, so a stream pushed in pieces comes out
|
||||
* sample for sample as it would if pushed whole.
|
||||
*
|
||||
* The filter is a Kaiser-windowed sinc evaluated at each output sample's position in the input: a
|
||||
* polyphase low-pass with one phase per distinct position, the rate step being a ratio of
|
||||
* integers. The cut-off sits under the lower of the two Nyquist frequencies, so a 24 kHz stream
|
||||
* taken to 16 kHz loses 8-12 kHz rather than folding it onto the band a speech model reads. Only
|
||||
* the common rates are taken: the phase table grows with the ratio's terms, and an arbitrary rate
|
||||
* can make it megabytes. */
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace mm {
|
||||
|
||||
class Resampler {
|
||||
public:
|
||||
/* Whether a stream at `rate` can be taken to a common rate: 8, 11.025, 12, 16, 22.05, 24,
|
||||
* 32, 44.1 or 48 kHz. */
|
||||
static bool takes(int32_t rate);
|
||||
/* The rates takes() accepts, for a refusal to name. */
|
||||
static std::string rates();
|
||||
|
||||
/* From `from` Hz to `to` Hz, both rates takes() accepts. Equal rates pass samples through. */
|
||||
Resampler(int32_t from, int32_t to);
|
||||
|
||||
/* Appends to `out` every output sample the input so far determines; the rest waits for more
|
||||
* input or flush(). */
|
||||
void push(const float* in, size_t n, std::vector<float>* out);
|
||||
/* Appends the remaining output, as if the input went on in silence, and starts afresh. */
|
||||
void flush(std::vector<float>* out);
|
||||
|
||||
private:
|
||||
void reset();
|
||||
|
||||
int32_t up_ = 1, down_ = 1; /* out/in as a ratio in lowest terms */
|
||||
int32_t half_ = 0; /* taps either side of an output sample, in input samples */
|
||||
std::vector<float> taps_; /* up_ phases of 2 * half_ taps */
|
||||
std::vector<float> in_; /* input from index base_ on */
|
||||
int64_t base_ = 0; /* the input index of in_[0]; negative while the history is the
|
||||
* silence before the stream */
|
||||
int64_t next_ = 0; /* the next output sample's index */
|
||||
int64_t n_in_ = 0; /* input samples pushed since the start */
|
||||
};
|
||||
|
||||
} /* namespace mm */
|
||||
} /* namespace rad */
|
||||
Reference in new issue
Block a user