ref2va: wire video and audio reference conditioning end-to-end (all three ref kinds live on device)

Follows the merged-cell pin (c725a2d). That commit proved reference IMAGE
conditioning consumed on device; reference VIDEO and AUDIO were plumbed
through the pack and step but still refused at submit — only their decode
and encoder-enqueue were missing. This lands them.

Server (videos.cpp): `task ref2va` now decodes `ref_video_N` and
`ref_audio_N` (and a video's paired `ref_video_audio_N`) into encoder form
via the mm encoders and enqueues them as Vencode/Aencode passes, instead of
the old image-only decode loop that rejected them. A soundtrack is folded
into its video's row (the `audio` word), matching how the pack lays that
pair. Caps stay <=9 images / <=3 videos / <=3 audios.

Driver (video_driver.{h,cpp}): the encode queue `enc_q` now carries VIDEO,
VAUDIO and AUDIO items in presentation order; `ref_tab` stamps each
reference's latent counts straight from the encoder geometry (rad_arch_encode_geom:
a video's frame count eg[24]=its total latent frames, its soundtrack's eg[12]),
so the pack's ref segments are sized by the encoder, not hand arithmetic.
processor.{h,cpp}/iface.h/adapters.h gained the media decode entry points.

Arch (minimaxh3.cpp): step_dit scatters reference rows into the packed step —
picture/video via op_vin from b_evc, audio via op_ain from b_enca, at each
segment start, targets last. A bounds audit confirms the scatter reads exactly
the slot region the encode pass wrote this job (eg[24]=lat = the pass's
written row count = the pack's segment size; no stale-neighbor read).

DEVICE-VERIFIED on dual gfx1201 / TP2, warm server, fixed seed, comparing
DECODED stream md5 (never raw mp4 bytes — the muxer stamps a field): all three
reference kinds are DETERMINISTIC (a rerun of one reference is bit-identical,
including raw bytes) AND CONTENT-LIVE (a different reference at the same seed
gives different output video AND audio). Image (content tokens), audio
(tone/noise/880 distinct) and video (refv_a vs refv_b: both streams differ)
each steered the generation. An earlier "the video step is nondeterministic"
note was a measurement artifact — it compared raw mp4 bytes and straddled the
one-off cold-start outlier; the warm decoded-stream probe is bit-reproducible.

Debug scaffolding (R4D_ENC_DEBUG, 4 trailing RadVideoGenDecl fields + a pinned
driver slab + an FNV digest in done()) is entangled in these files. It is
env-gated and zero-touch when unset; STRIP IT BEFORE ANY PR.

tests: video_gen_test/videos_test/server_fakes cover the video/audio enqueue
paths; abi_layout_rows adds the new trailing rows; ref_audio_sensitivity.py is
a standalone host golden harness (audio reference separates 4/4), not a ctest
case. Host tier green (only mm_test's pre-existing webp demuxer gap fails, and
the GPU card/kbench tests fail solely on VRAM contention with a live server).

NOTE-REF2VA.md updated: continuity tail (#8) remains unimplemented; strict
numeric parity vs the ComfyUI CPU reference remains open.

PLACEHOLDER AUTHOR — repo has no git identity; re-author before any push.
DO NOT PUSH this branch.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
gearwave00001andClaude committed 2026-10-19 15:25:32 -05:00
1 parent 72624973ad
commit 658f7b7214
16 files changed
+1055 -162

No files matched your search

+6
View File
@@ -624,6 +624,7 @@ ABI_FIELD(RadVideoGenBatch, enc_slot)
ABI_FIELD(RadVideoGenBatch, enc_geom_d)
ABI_FIELD(RadVideoGenBatch, enc_kind)
ABI_FIELD(RadVideoGenBatch, ref_tab)
ABI_FIELD(RadVideoGenBatch, mod_cu)
ABI_STRUCT(RadVideoGenDecl)
ABI_FIELD(RadVideoGenDecl, name)
ABI_FIELD(RadVideoGenDecl, tmpl)
@@ -671,6 +672,11 @@ ABI_FIELD(RadVideoGenDecl, max_enc_side)
ABI_FIELD(RadVideoGenDecl, max_enc_samples)
ABI_FIELD(RadVideoGenDecl, enc_ratio)
ABI_FIELD(RadVideoGenDecl, ref_rows)
ABI_FIELD(RadVideoGenDecl, max_ref_segs)
ABI_FIELD(RadVideoGenDecl, dbg_enca)
ABI_FIELD(RadVideoGenDecl, dbg_enca_bytes)
ABI_FIELD(RadVideoGenDecl, dbg_evc)
ABI_FIELD(RadVideoGenDecl, dbg_evc_bytes)
ABI_STRUCT(RadVideoGeom)
ABI_FIELD(RadVideoGeom, n_text)
ABI_FIELD(RadVideoGeom, frames)
@@ -0,0 +1,234 @@
#!/usr/bin/env python3
"""#14 golden — reference-half integrity + content-sensitivity (audio encoder).
The device Aencode reportedly produces a content-INVARIANT latent (all sufficiently-nonzero
audio collapses to one vector, only silence separates) while the host scatter/staging provably
carry distinct content. #14 asks whether the DEVICE encoder MATH is wrong. This script builds the
REFERENCE half of that comparison on the CPU, in the ComfyUI venv's torch, using the reference
network classes themselves and the REAL HF weights -- no device, no shared kernels, read-only, so
it cannot regress the build.
What it establishes:
1. INTEGRITY -- the real `encoder.*` / `pre_block.*` / `mean_proj.*` checkpoint loads under
`load_state_dict(strict=True)` into the extracted classes. A clean load means the port's
`aenc.*` container names are name-consistent with the genuine model (a mapping typo would
surface here as a missing/unexpected key, exactly the class of bug that could masquerade as
"kernel math").
2. REFERENCE IS CONTENT-SENSITIVE, AT BOTH STAGES -- the reference, on the SAME synthetic
contents the on-device audio test used (a 440 Hz tone, an 880 Hz tone, white noise, silence),
gives pairwise-DISTINCT outputs at BOTH:
(a) the raw conv encoder stream `Encoder(x)` [1, 2048, T] -- the f32 conv chain, and
(b) the FULL latent `mean_proj(pre_block(Encoder(x)))` [1, 32, T] -- exactly the quantity
the device writes into `b_enca` (the per-channel latents_mean/std is a bijection and is
omitted; it cannot turn distinct latents into identical ones).
If both are distinct, the reference does not collapse the way the device does, so the
divergence is on the device side. The stage-(b) latent is the target a device dump compares
against once `b_enca` is read back.
Run: <comfyui-venv>/bin/python ref_audio_sensitivity.py [audio_vae.py] [audio_vae.safetensors]
"""
import ast
import hashlib
import math
import sys
import types
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.manual_seed(0)
VAE_PY = sys.argv[1] if len(sys.argv) > 1 else \
"/home/dustin/AI/ComfyUI/comfy/ldm/minimax/audio_vae.py"
WEIGHTS = sys.argv[2] if len(sys.argv) > 2 else \
"/home/dustin/AI/models/MiniMaxAI/MiniMax-H3/audio_vae/diffusion_pytorch_model.safetensors"
# ---- minimal comfy.ops shim (same discipline as gen_golden.py: CPU path only) ----
# The encode path reaches for these comfy.ops symbols:
# cast_to_input -- a plain dtype/device cast of a weight to the activation's dtype/device
# (faithful to comfy/ops.py on CPU: no offload, no requant).
# cast_bias_weight -- returns (weight, None, None) on CPU (no offload stream, no bias requant;
# CausalAttention re-supplies its own packed q/k/v bias below).
# uncast_bias_weight -- no-op on CPU (nothing to un-offload).
# scaled_dot_product_attention -- torch's SDPA (is_causal handled by torch).
# disable_weight_init is used by the module as `ops = comfy.ops.disable_weight_init` then
# `ops.Conv1d(...)`: it must be an OBJECT exposing the plain nn classes (init is irrelevant here,
# every weight is overwritten by load_state_dict).
class _DisableWeightInit:
Conv1d = nn.Conv1d
ConvTranspose1d = nn.ConvTranspose1d
LayerNorm = nn.LayerNorm
Linear = nn.Linear
class _Ops:
Conv1d = nn.Conv1d
ConvTranspose1d = nn.ConvTranspose1d
GroupNorm = nn.GroupNorm
LayerNorm = nn.LayerNorm
Linear = nn.Linear
disable_weight_init = _DisableWeightInit()
@staticmethod
def cast_to_input(weight, input, non_blocking=False, copy=True):
return weight.to(dtype=input.dtype, device=input.device)
@staticmethod
def cast_bias_weight(module, input, bias=None, offloadable=False, **kw):
return module.weight.to(dtype=input.dtype, device=input.device), None, None
@staticmethod
def uncast_bias_weight(module, weight, bias, offload_stream):
return None
@staticmethod
def scaled_dot_product_attention(query, key, value, is_causal=False, **kw):
return F.scaled_dot_product_attention(query, key, value, is_causal=is_causal)
comfy = types.ModuleType("comfy")
comfy.quant_ops = types.ModuleType("comfy.quant_ops")
comfy.ops = _Ops()
def top_level(path, names):
src = open(path).read()
tree = ast.parse(src)
out = {}
for node in tree.body:
key = getattr(node, "name", None)
if key is None and isinstance(node, ast.Assign):
key = [t.id for t in node.targets if isinstance(t, ast.Name)]
else:
key = [key]
for k in key:
if k in names:
out[k] = ast.get_source_segment(src, node)
missing = set(names) - set(out)
if missing:
raise SystemExit(f"not found in {path}: {sorted(missing)}")
return out
ans = dict(torch=torch, nn=nn, F=F, math=math, comfy=comfy, ops=_Ops.disable_weight_init)
for name in ["snake", "Snake1d", "ResidualUnit", "EncoderBlock", "Encoder",
"GeGluMlp", "CausalAttention", "AttnProjection"]:
exec(top_level(VAE_PY, [name])[name], ans)
class RefEncoder(nn.Module):
"""The encode-side half of MiniMaxH3AudioVAE -- encoder, pre_block, mean_proj -- without
constructing the BigVGAN decoder (whose alias-free / Kaiser classes this harness does not
need to run). Mirrors `MiniMaxH3AudioVAE.__init__`'s encoder fields exactly."""
def __init__(self):
super().__init__()
self.encoder = ans["Encoder"](64, (2, 4, 4, 5, 5), 2048)
self.pre_block = ans["AttnProjection"](2048, 32, num_heads=8)
self.mean_proj = nn.Conv1d(32, 32, 1)
def forward(self, x, full=True):
x = self.encoder(x) # [b, 2048, T]
if not full:
return x
x = self.pre_block(x.transpose(1, 2)).transpose(1, 2) # [b, 32, T]
return self.mean_proj(x) # [b, 32, T]
def load_encoder():
"""Reference encode chain with the REAL HF weights bound. strict=True is the integrity gate."""
enc = RefEncoder()
sd = _read_state(WEIGHTS)
enc.load_state_dict(sd, strict=True) # raises on any mismatch
return enc
def _read_state(path):
"""Pull the encode-side tensors out of the checkpoint as a bare state_dict, folding the
weight-norm parametrization (`weight_g`/`weight_v`) into the single plain `.weight` the
extracted Conv1d holds. The convert splits this the same way -- it stores `v` and a separate
per-output-row scale g[o]/||v[o]|| (core/format/checkpoint.cpp resolve_wnorm); folding into
.weight here reproduces the identical effective linear map, and a per-row scale cannot flatten
content (distinct inputs still give distinct dot products through any nonzero v), so this is
the faithful reference. Only the `encoder.*` convs are weight-norm; `pre_block.*` /
`mean_proj.*` Linears/Conv/LayerNorms load verbatim. latents_mean/std live in the container
meta, not here, and are a per-channel bijection omitted for the distinctness test."""
from safetensors import safe_open
raw = {}
with safe_open(path, framework="pt") as f:
for k in f.keys():
if k.startswith(("encoder.", "pre_block.", "mean_proj.")):
raw[k] = f.get_tensor(k)
out = {}
for k, g in raw.items():
if not k.endswith(".weight_g"):
continue
stem = k[: -len("weight_g")] # e.g. "encoder.block.1.block.0.block.1."
v = raw[stem + "weight_v"]
# classic weight_norm (dim=0): w[o] = g[o] * v[o] / ||v[o]|| over every non-output dim
norm = v.flatten(1).norm(dim=1).view([-1] + [1] * (v.dim() - 1))
out[stem + "weight"] = g / norm * v
for k, v in raw.items():
if k.endswith((".weight_g", ".weight_v")):
continue
out[k] = v
return out
def contents():
"""The same four contents the on-device audio differential used, same length, padded to the
encoder hop (800) exactly as the driver pads an audio tail to a whole hop. The reference
encode takes a stereo [B, 2, L] waveform; the port's encoder is mono and the server duplicates
the mono stream across the two channels, so a mono reference is stacked twice here."""
hop, n = 800, 800 * 40 # 32000 samples = 40 latent frames
def mono(x):
return torch.zeros(1, hop * math.ceil(n / hop)).scatter_(
1, torch.arange(n).view(1, n), x.view(1, n))
t = torch.arange(n, dtype=torch.float32) / 16000.0
def stereo(x):
m = mono(x)
return torch.stack([m, m], dim=1) # [1, 2, L] -- mono spread to both channels
return {
"silence": stereo(torch.zeros(n)),
"tone440": stereo(0.3 * torch.sin(2 * math.tau * 440 * t)),
"tone880": stereo(0.3 * torch.sin(2 * math.tau * 880 * t)),
"noise": stereo(0.3 * torch.randn(n)),
}
def digest(z):
b = z.detach().float().numpy().tobytes()
return hashlib.sha256(b).hexdigest()[:12], float(z.abs().max()), float(z.sum())
def run(enc, full, label):
sigs = {}
with torch.no_grad():
for name, x in contents().items():
# encode(): pad each channel to the hop and fold the two stereo channels into the batch
b, s, length = x.shape
pad = (hop := 800) * math.ceil(length / hop) - length
x = F.pad(x, (0, pad)).reshape(b * s, 1, -1)
z = enc(x, full=full)
sigs[name] = digest(z)
print(f" {name:8s} shape={list(z.shape)} sha={sigs[name][0]} "
f"maxabs={sigs[name][1]:.4f} sum={sigs[name][2]:.2f}", file=sys.stderr)
distinct = len({v[0] for v in sigs.values()}) == len(sigs)
n = len(set(v[0] for v in sigs.values()))
print(f" {label}: content-sensitive={distinct} ({n}/{len(sigs)} distinct)", file=sys.stderr)
return distinct
hop = 800
if __name__ == "__main__":
enc = load_encoder()
enc.eval()
print("integrity: encoder.* + pre_block.* + mean_proj.* loaded strict=True OK", file=sys.stderr)
a = run(enc, full=False, label="raw Encoder(x) [f32 conv stream, 2048xT]")
b = run(enc, full=True, label="FULL mean_proj(pre_block(Encoder(x))) [b_enca, 32xT]")
sys.exit(0 if (a and b) else 3)
+31
View File
@@ -399,6 +399,37 @@ struct FakeMultimodal : IMultimodal {
*out = std::move(it);
return RAD_OK;
}
/* The video/audio VAE form, which the server fills only when a generator declares `encodes`.
* Synthetic frames and a mono tone of a fixed length, each call counted, so a test can watch the
* server decode each reference, spread the mono tone across the encoder's channels and hand it to
* the generator. The sides are the encoder grid; the counts are the NATURAL ones (a short video
* clip, a sample count that is not a whole hop) — padding is the driver's, not the server's. */
int32_t enc_frames = 5, enc_side = 16;
int64_t enc_n = 850;
int n_ienc = 0, n_venc = 0, n_aenc = 0;
int encoder_image(const uint8_t*, size_t, int32_t, int32_t, mm::Frame* out,
std::string*) override {
++n_ienc;
out->w = out->h = enc_side;
out->rgb.assign((size_t)enc_side * enc_side * 3, 128);
return RAD_OK;
}
int encoder_video(const uint8_t*, size_t, int32_t, int32_t, int32_t, std::vector<mm::Frame>* out,
std::string*) override {
++n_venc;
out->assign((size_t)enc_frames, mm::Frame{});
for (mm::Frame& f : *out) {
f.w = f.h = enc_side;
f.rgb.assign((size_t)enc_side * enc_side * 3, 64);
}
return RAD_OK;
}
int encoder_audio(const uint8_t*, size_t, int32_t, int64_t, std::vector<float>* out,
std::string*) override {
++n_aenc;
out->assign((size_t)enc_n, 0.5f);
return RAD_OK;
}
};
/* An embedding model's vector width, input bound and named prompts. */
+110 -3
View File
@@ -195,6 +195,30 @@ int64_t fake_encode_geom(int32_t kind, const int64_t* in, int32_t* gd, int64_t c
return need;
}
/* The encode geometry of the real VAEs, so a video or audio reference gets its true padded volume
* and latent counts (fake_encode_geom above only echoes its input, which is enough for a still
* picture). A video of T frames runs ceil(T/17) clips, padded to clips*17 frames (gd[23]) and
* reporting clips*5-3 latent frames (gd[24]), one frame for a still; an audio of n samples is
* right-padded to a whole hop (gd[0]) and reports n/800 rounded up as its latent frames (gd[12]).
* The driver clip-pads / zero-pads to these figures and reads gd[24] / gd[12] for the table. */
int64_t fake_encode_vae(int32_t kind, const int64_t* in, int32_t* gd, int64_t cap) {
if (!gd) return kind == RAD_GEN_PASS_AENCODE ? 13 : 25;
const int64_t need = kind == RAD_GEN_PASS_AENCODE ? 13 : 25;
if (cap < need) return RAD_E_INVAL;
for (int64_t i = 0; i < need; ++i) gd[i] = 0;
if (kind == RAD_GEN_PASS_AENCODE) {
const int64_t lat = (in[0] + 799) / 800; /* vae_audio_latents: ceil(n / hop) */
gd[0] = (int32_t)(lat * 800); /* samples padded to a whole hop */
gd[12] = (int32_t)lat; /* latent frames */
} else {
const int64_t clips = (in[0] + 16) / 17; /* ceil(T / clip length) */
gd[22] = (int32_t)clips;
gd[23] = (int32_t)(clips * 17); /* frames padded to whole clips */
gd[24] = in[0] <= 1 ? 1 : (int32_t)(clips * 5 - 3); /* vae_latent_frames */
}
return need;
}
struct VideoFixture {
Program prog;
gen::VideoDriver drv;
@@ -868,8 +892,10 @@ TEST(a_reference_conditioned_step_widens_to_the_pack_layout) {
CHECK(saw_encode);
}
/* What the video path cannot consume is refused at submit, naming the part or the budget it
* breaks — never silently dropped into a weaker video. */
/* What the container cannot consume is refused at submit, naming the part or the budget it breaks —
* never silently dropped into a weaker video. A reference video, soundtrack or audio needs the VAE
* encoders; on a container converted without them (encodes 0) they are refused by name here, and on
* one that carries them they are encoded and consume — see the next test. */
TEST(reference_media_the_generator_cannot_consume_are_refused_naming_the_part) {
std::string why;
@@ -891,7 +917,8 @@ TEST(reference_media_the_generator_cannot_consume_are_refused_naming_the_part) {
CHECK_EQ(g.drv.submit(std::move(q), &why), (int)RAD_E_INVAL);
CHECK(has(why, what));
};
/* Videos and audios reach the model through the VAEs, which the video path does not run. */
/* This container carries the tower but not the VAEs (encodes 0): a reference that reaches the
* model only through them is refused by name rather than dropped. */
r = g.req();
r->refs.push_back(ref_part(gen::VideoRefMedia::VIDEO, "ref_video_1", 1));
refused(std::move(r), "ref_video_1");
@@ -924,4 +951,84 @@ TEST(reference_media_the_generator_cannot_consume_are_refused_naming_the_part) {
CHECK(has(why, "at most 4"));
}
/* The other half of the guard above: a container that DOES carry its VAE encoders consumes a
* reference video, its soundtrack and a standalone audio. Each queues an encode pass that folds its
* latents into a fixed slot and enters the pack's reference table. A video and its separately-given
* soundtrack are ONE row — the soundtrack folded into the video's `audio` word — encoded at the
* VIDEO's slot, audio first then video; a standalone audio is its own row. The request carries no
* `media` (only images feed the text encoder), and the driver hands each encoder its padded volume:
* a 5-frame clip repeated out to 17, an 850-sample audio zero-padded up to two 800-sample hops. */
TEST(reference_videos_and_audios_are_encoded_into_the_reference_table) {
VideoFixture f;
f.build();
with_tower(f, 16);
RadVideoGenDecl& d = f.prog.video_gen;
d.encodes = 1;
d.enc_ratio = 16;
d.max_enc_frames = 289;
d.max_enc_side = 256;
d.max_enc_samples = 500000;
CHECK_OK(f.start_with_encode_gen(fake_encode_vae));
std::string why;
auto r = f.req(2, 2); /* 2 steps keeps the walk short; the encodes all run before it */
/* A reference video: the 5-frame trimmed minimum at 16x16 (short final clip -> repeat frame). */
gen::VideoRefMedia v = ref_part(gen::VideoRefMedia::VIDEO, "ref_video_1", 1);
v.enc_frames = 5; v.enc_h = 16; v.enc_w = 16;
v.enc_pixels.assign(5 * 16 * 16 * 3, 1.0f);
/* Its soundtrack: 1600 samples over 2 channels — already whole hops, so unpadded. */
gen::VideoRefMedia a = ref_part(gen::VideoRefMedia::VIDEO_AUDIO, "ref_video_audio_1", 1);
a.enc_n = 1600; a.enc_channels = 2;
a.enc_samples.assign(2 * 1600, 0.25f);
/* A standalone audio: 850 samples, not a whole hop, so the driver zero-pads 750 onto it. */
gen::VideoRefMedia s = ref_part(gen::VideoRefMedia::AUDIO, "ref_audio_2", 2);
s.enc_n = 850; s.enc_channels = 2;
s.enc_samples.assign(2 * 850, -0.5f);
r->refs.push_back(v);
r->refs.push_back(a);
r->refs.push_back(s);
CHECK_OK(f.drv.submit(std::move(r), &why));
int saw_venc = 0, saw_vaudio = 0, saw_saudio = 0;
const int32_t* tab = nullptr;
for (int i = 0; i < 12 && saw_venc + saw_vaudio + saw_saudio < 3; ++i) {
const RadBatch* b = f.drv.next(0);
if (!b) break;
const RadVideoGenBatch* V = b->vgen_b;
if (b->gen == RAD_GEN_PASS_VENCODE || b->gen == RAD_GEN_PASS_AENCODE) {
REQUIRE(V != nullptr);
if (b->gen == RAD_GEN_PASS_VENCODE) {
CHECK_EQ(V->enc_kind, (int32_t)RAD_ENC_VIDEO);
CHECK_EQ(V->enc_slot, (int32_t)1);
CHECK_EQ(V->enc_frames, 17); /* 5 frames clip-padded to one whole clip */
++saw_venc;
} else if (V->enc_kind == RAD_ENC_VAUDIO) { /* the soundtrack, at the VIDEO's slot */
CHECK_EQ(V->enc_slot, (int32_t)1);
CHECK_EQ(V->enc_n_samples, 1600); /* whole hops: unpadded */
++saw_vaudio;
} else { /* the standalone audio, its own slot */
CHECK_EQ(V->enc_kind, (int32_t)RAD_ENC_AUDIO);
CHECK_EQ(V->enc_slot, (int32_t)2);
CHECK_EQ(V->enc_n_samples, 1600); /* 850 zero-padded up to two hops */
++saw_saudio;
}
}
if (V && V->ref_tab && !tab) tab = V->ref_tab;
f.answer(10 * i);
CHECK_OK(f.drv.done());
}
CHECK_EQ(saw_venc, 1);
CHECK_EQ(saw_vaudio, 1);
CHECK_EQ(saw_saudio, 1);
REQUIRE(tab != nullptr);
/* Two rows: the video (its soundtrack folded into the `audio` word) and the standalone audio. The
* VIDEO_AUDIO is not a row of its own. Video: kind 2, slot 1, 1x1 grid, 5 frames -> 2 latent
* frames, soundtrack 1600/800 = 2. Audio: kind 1, slot 2, no grid, 850 -> 2 latent frames. */
CHECK_EQ(tab[0], 2);
CHECK_EQ(tab[1], 0);
CHECK_EQ(tab[2], 2); CHECK_EQ(tab[3], 1); CHECK_EQ(tab[4], 1); CHECK_EQ(tab[5], 1);
CHECK_EQ(tab[6], 2); CHECK_EQ(tab[7], 2);
CHECK_EQ(tab[8], 1); CHECK_EQ(tab[9], 2); CHECK_EQ(tab[10], 0); CHECK_EQ(tab[11], 0);
CHECK_EQ(tab[12], 0); CHECK_EQ(tab[13], 2);
}
RAD_TEST_MAIN()
+75
View File
@@ -437,6 +437,81 @@ TEST(ref2va_pictures_are_presented_before_the_prompt) {
CHECK(g.tokens == want);
}
/* A generator that carries its VAE encoders (encodes 1): the reference parts are not merely passed
* as bytes — the picture, the video and both audios are decoded into the encoder's own form, the
* audio's mono tone spread across the encoder's channels — and every reference is spoken before the
* prompt in the reference's order: the picture's label and run, the soundtrack's `<Audio j>` right
* before its video's `<Video k>`, then the standalone `<Audio j>`. This is the server half; the
* driver half (padding, slots, the pack table) is tests/video_gen_test.cpp. */
TEST(ref2va_videos_and_audios_are_encoded_and_spoken) {
FakeMultimodal mm;
mm.expand = { 900, 901 };
mm.enc_frames = 5; mm.enc_side = 16; mm.enc_n = 850;
FakeVideoGen gen;
std::unique_ptr<Fixture> f(new Fixture(Fixture::Tweak{ [&](ServerOptions& o, Deps& d) {
d.videos = &gen;
d.mm = &mm;
o.video_model = true;
gen.inf.encodes = 1;
gen.inf.enc_ratio = 16;
gen.inf.max_enc_side = 256;
gen.inf.max_enc_frames = 289;
gen.inf.max_enc_samples = 500000;
} }));
HttpRequest q;
q.method = "POST";
q.path = "/v1/videos";
q.form = { FormPart{ "prompt", "", "", "fox" },
FormPart{ "size", "", "", "256x256" },
FormPart{ "task", "", "", "ref2va" },
FormPart{ "ref_image_1", "a.png", "image/png", "PA" },
FormPart{ "ref_video_1", "v.mp4", "video/mp4", "ftyp" },
FormPart{ "ref_video_audio_1", "s.wav", "audio/wav", "RIFF" },
FormPart{ "ref_audio_1", "b.mp3", "audio/mpeg", "ID3" } };
HttpResponse r = f->srv->router().dispatch(q);
REQUIRE_EQ(r.status, 200);
/* One image, one video and two audios (the video's soundtrack plus the standalone) reached the
* encoder each belongs to. */
CHECK_EQ(mm.n_ienc, 1);
CHECK_EQ(mm.n_venc, 1);
CHECK_EQ(mm.n_aenc, 2);
const gen::VideoRequest& g = gen.last();
REQUIRE_EQ(g.refs.size(), (size_t)4); /* sorted (kind, index): image, video, video_audio, audio */
/* The picture: one frame at the encoder grid, its pixels filled for the video VAE. */
CHECK_EQ((int)g.refs[0].kind, (int)gen::VideoRefMedia::IMAGE);
CHECK_EQ(g.refs[0].enc_frames, 1);
CHECK_EQ(g.refs[0].enc_h, 16);
CHECK_EQ(g.refs[0].enc_w, 16);
CHECK_EQ(g.refs[0].enc_pixels.size(), (size_t)16 * 16 * 3);
/* The video: the trimmed natural frame count, concatenated over the grid (the driver pads). */
CHECK_EQ((int)g.refs[1].kind, (int)gen::VideoRefMedia::VIDEO);
CHECK_EQ(g.refs[1].enc_frames, 5);
CHECK_EQ(g.refs[1].enc_pixels.size(), (size_t)5 * 16 * 16 * 3);
/* The soundtrack and the standalone audio: the mono tone spread across the generator's two
* channels, enc_n the natural (unpadded) count. */
CHECK_EQ((int)g.refs[2].kind, (int)gen::VideoRefMedia::VIDEO_AUDIO);
CHECK_EQ(g.refs[2].enc_channels, 2);
CHECK_EQ(g.refs[2].enc_n, (int64_t)850);
CHECK_EQ(g.refs[2].enc_samples.size(), (size_t)2 * 850);
CHECK_EQ(g.refs[2].enc_samples[0], g.refs[2].enc_samples[850]); /* both channels the same tone */
CHECK_EQ((int)g.refs[3].kind, (int)gen::VideoRefMedia::AUDIO);
CHECK_EQ(g.refs[3].enc_n, (int64_t)850);
/* The prompt speaks every reference before the words, in the reference's order. */
std::vector<int32_t> want;
auto chars = [&](const std::string& s) { for (unsigned char c : s) want.push_back((int32_t)c); };
chars("<v>");
chars("<Picture 1>: ");
want.insert(want.end(), mm.expand.begin(), mm.expand.end());
chars("<Audio 1>: ");
chars("<Video 1>: ");
chars("<Audio 2>: ");
chars("fox");
CHECK(g.tokens == want);
}
/* Everything about the parts that cannot be right is refused naming the part (or `task` when
* the media themselves are the question), before anything is queued. */
TEST(ref2va_requests_are_refused_naming_the_part) {