Archived
radiance 1.13.0
New models: - Tencent Hy-Memory (HYV3) from its BF16, FP8 and GGUF checkpoints, with its native tool calls - M2XFP4: metadata-augmented MXFP4 weights for Qwen3.8-27B and its DFlash2 drafter (top-1 89.1% -> 92.4% against plain MXFP4), its quantiser and recipe, and ParoQuant's M2XFP4 checkpoints - Gemma 4 E2B/E4B audio input; NVIDIA-Nemotron-3.5-Bolt-E4B in int8 and 4-bit, on two cards by default; Ornith-1.5-122B compose files Speed: - Weight reads beside the decode all-reduces (qwen35_fp8, gemma3; --weight-prefetch, on by default): the 27B MXFP4 with DFlash2 61.2 -> 67.9 tok/s at c1, TranslateGemma 27B +13% - Head-256 split-KV decode attention at 256 workgroups and without bank conflicts (27B: +3-5% a step at 25-41K context), and the prefill KV split for small launches (a short turn over a long context decodes the other sequences 27% faster in that step) - MXFP4 decode gate_up, activation and fp8 quantiser in one launch (27B, Gemma 3 up to 64 rows: TranslateGemma +2-5% at 2-8 streams) - ParoQuant int4/int5 tiled GEMMs 6-9% faster - Speculation: a step's tokens are sent before the drafter's passes end, no step waits behind one that ends its requests, and the MTP head's first draft no longer collapses after short chats in the prefix cache Features: - --kv-resident N: KV streaming for a context bigger than VRAM (qwen4exp_fp8, GLM-5.3) - MiniMax-H3: reference media and keyframe conditioning with the VAE encoders - Krea 2 rebalance presets balanced, detail and subtle - The dashboard's request history; a stall watch that reports a frozen step's thread and stack - rad-tune at the served configuration, collectives measured as the exchange; Gemma 4 E2B/E4B's per-layer embeddings read ahead off the step path - A GPTQ calibration tap and recipe for Gemma 4 31B's w4a8 container Fixes: - The two-rank all-reduce checks that a peer's push has landed before reducing it - z-lab's DFlash drafter on Gemma 4 31B keeps drafting after a prefix-cache hit - MiniMax-H3's modulation rows Changes: Plugin ABI 31: out-of-tree plugins must be rebuilt. RADIANCE_PREFETCH_BESIDE is --weight-prefetch now; RADIANCE_NO_HUGE_PAGES, RADIANCE_IDS_EARLY, RADIANCE_ATTN_BAND_SPLIT, R4D_PREFILL_SPLITS, RAD_PLE_TIMING and RAD_PLE_CACHE_ROWS are gone.
This commit is contained in:
commit
6645337f69
198 files changed
+20904
-3240
No files matched your search
+32
-6
@@ -49,6 +49,17 @@ set(RAD_TESTS_WITH_LEGACY chatparse_test chatparse_gemma4_test)
|
||||
# r4d_ar_links_test checks libr4d's header-only link reader, so it needs only the include path.
|
||||
set(RAD_TESTS_WITH_R4D_HOST relayout_parity_test r4d_ar_links_test)
|
||||
|
||||
# ref2va_pack_test checks the Ref2VA sequence packing (arch/minimaxh3/rad_ref2va_pack.cpp, a
|
||||
# device-free TU of the plugin) against golden vectors generated from the reference implementation
|
||||
# by tests/data/ref2va/gen_golden.py. It is pure host arithmetic, so like arch_test it links no
|
||||
# core; nlohmann comes straight from vendor/, which core reaches the same way.
|
||||
set(RAD_TESTS_WITH_PACK ref2va_pack_test)
|
||||
|
||||
# vae_geom_test checks the encode geometry (arch/minimaxh3/rad_vae_geom.cpp) the same way: golden
|
||||
# vectors generated by running the reference VAEs' own encoders on CPU
|
||||
# (tests/data/vae_geom/gen_golden.py). Also device-free, also links no core.
|
||||
set(RAD_TESTS_WITH_VAE_GEOM vae_geom_test)
|
||||
|
||||
# Chat templates (copied from the model repositories) and media samples, passed by absolute path so
|
||||
# test binaries can run from anywhere.
|
||||
set(RAD_CHAT_FIXTURES ${CMAKE_CURRENT_SOURCE_DIR}/data/chat)
|
||||
@@ -116,6 +127,7 @@ set(RAD_TEST_ENV ${RAD_TEST_CARD_ENV} "ROCR_VISIBLE_DEVICES=99")
|
||||
set(RAD_TEST_CPU_BUDGET_quant_ggml_test 25) # llama.cpp's iq1_s and iq2_* grid searches, ~13 s
|
||||
set(RAD_TEST_CPU_BUDGET_tokenizer_test 20) # the reference encoder over every corpus: ~3 s built by GCC 16, ~10.5 s by GCC 14 (the image's Ubuntu)
|
||||
set(RAD_TEST_CPU_BUDGET_arch_test 15) # every plugin's graph declared; ~10.8 s with the batched-tower case
|
||||
set(RAD_TEST_CPU_BUDGET_glm5next_test 20) # GLM-5.3-Flash's graphs and op schemas: ~4.8 s built by GCC 16, ~10.1 s by GCC 14 (the image's Ubuntu)
|
||||
|
||||
# Binaries whose OpenMP team is busy for most of their run, so a parallel ctest counts them as a
|
||||
# team's worth of slots rather than one.
|
||||
@@ -182,6 +194,18 @@ foreach(t ${RAD_TESTS})
|
||||
target_sources(${n} PRIVATE ${CMAKE_SOURCE_DIR}/tools/opshapes.cpp)
|
||||
target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/tools)
|
||||
endif()
|
||||
elseif(n IN_LIST RAD_TESTS_WITH_PACK)
|
||||
add_executable(${n} ${t} ${CMAKE_SOURCE_DIR}/arch/minimaxh3/rad_ref2va_pack.cpp)
|
||||
target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/arch/minimaxh3
|
||||
${CMAKE_SOURCE_DIR}/vendor)
|
||||
target_compile_definitions(${n} PRIVATE
|
||||
RAD_REF2VA_GOLDEN="${CMAKE_CURRENT_SOURCE_DIR}/data/ref2va")
|
||||
elseif(n IN_LIST RAD_TESTS_WITH_VAE_GEOM)
|
||||
add_executable(${n} ${t} ${CMAKE_SOURCE_DIR}/arch/minimaxh3/rad_vae_geom.cpp)
|
||||
target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/arch/minimaxh3
|
||||
${CMAKE_SOURCE_DIR}/vendor)
|
||||
target_compile_definitions(${n} PRIVATE
|
||||
RAD_VAE_GOLDEN="${CMAKE_CURRENT_SOURCE_DIR}/data/vae_geom")
|
||||
elseif(n IN_LIST RAD_TESTS_WHOLE_CORE)
|
||||
add_executable(${n} ${t})
|
||||
target_link_libraries(${n} PRIVATE stdc++ "$<LINK_LIBRARY:WHOLE_ARCHIVE,rad_core>")
|
||||
@@ -432,11 +456,12 @@ set(R4D_EMU_HIP ${R4D_DIR}/r4d_attn_paged_window.hip ${R4D_DIR}/r4d_pair_argmax_
|
||||
${R4D_DIR}/r4d_qsa_select_bf16.hip ${R4D_DIR}/r4d_lora_bf16.hip ${R4D_DIR}/r4d_glm.hip
|
||||
${R4D_DIR}/r4d_mhc.hip ${R4D_DIR}/r4d_fp8_f32scale.hip ${R4D_DIR}/r4d_kda.hip
|
||||
${R4D_DIR}/r4d_moe_mxfp4.hip ${R4D_DIR}/r4d_mla.hip ${R4D_DIR}/r4d_quant_act_fp8.hip
|
||||
${R4D_DIR}/r4d_dsa.hip
|
||||
${R4D_DIR}/r4d_kv_resolve.hip ${R4D_DIR}/r4d_dsa.hip
|
||||
${R4D_DIR}/r4d_gemm_m2xfp4a8_decode.hip ${R4D_DIR}/r4d_gemm_m2xfp4a8_tiled.hip)
|
||||
# The M2XFP4 units' plugin entries call two cfg readers that r4d_rows.cpp defines, which is not in
|
||||
# this build: cfg_stub.cpp defines them at their axis defaults, in both arms below.
|
||||
set(R4D_EMU_TESTS attn pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse dsa m2xfp4)
|
||||
set(R4D_EMU_TESTS attn pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse kvres
|
||||
dsa m2xfp4)
|
||||
set(R4D_EMU_BUILT OFF)
|
||||
if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$")
|
||||
# No fiber switch for this ISA.
|
||||
@@ -476,8 +501,8 @@ else()
|
||||
${R4D_EMU}/test_escale.cpp ${R4D_EMU}/test_qsa.cpp ${R4D_EMU}/test_lora.cpp
|
||||
${R4D_EMU}/test_f32.cpp ${R4D_EMU}/test_mhc.cpp ${R4D_EMU}/test_fp8f32.cpp
|
||||
${R4D_EMU}/test_kda.cpp ${R4D_EMU}/test_moemx.cpp ${R4D_EMU}/test_mla.cpp
|
||||
${R4D_EMU}/test_moefuse.cpp ${R4D_EMU}/test_dsa.cpp ${R4D_EMU}/test_m2xfp4.cpp
|
||||
${R4D_EMU}/cfg_stub.cpp)
|
||||
${R4D_EMU}/test_moefuse.cpp ${R4D_EMU}/test_kvres.cpp
|
||||
${R4D_EMU}/test_dsa.cpp ${R4D_EMU}/test_m2xfp4.cpp ${R4D_EMU}/cfg_stub.cpp)
|
||||
get_filename_component(stem ${src} NAME_WE)
|
||||
set(lang "")
|
||||
if(src MATCHES "\\.hip$")
|
||||
@@ -514,7 +539,7 @@ else()
|
||||
endif()
|
||||
endif()
|
||||
if(R4D_EMU_BUILT)
|
||||
foreach(t pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse dsa m2xfp4)
|
||||
foreach(t pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse kvres dsa m2xfp4)
|
||||
add_test(NAME r4d_emu_${t} COMMAND ${CMAKE_BINARY_DIR}/tests/r4d_emu_${t})
|
||||
endforeach()
|
||||
# The attention cases take about 11 s, 7 of them in the two long prefills on the WMMA kernel,
|
||||
@@ -586,7 +611,8 @@ if(RAD_HIP_FOUND AND TARGET libr4d)
|
||||
endif()
|
||||
add_test(NAME oot_plugins
|
||||
COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/oot_plugins.sh
|
||||
${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR}/oot ${RAD_OOT_HIP})
|
||||
${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR}/oot ${RAD_OOT_HIP}
|
||||
${CMAKE_CXX_COMPILER})
|
||||
# RESOURCE_LOCK kbench_memory: its replay holds operands in host memory as the kbench entries do.
|
||||
set_tests_properties(oot_plugins PROPERTIES
|
||||
LABELS "oot"
|
||||
|
||||
@@ -18,6 +18,7 @@ ABI_FIELD(RadArchProbe, gen_ctx)
|
||||
ABI_FIELD(RadArchProbe, gen_video)
|
||||
ABI_FIELD(RadArchProbe, kv_quant_ok)
|
||||
ABI_FIELD(RadArchProbe, chain_pays)
|
||||
ABI_FIELD(RadArchProbe, kv_stream_ok)
|
||||
ABI_FIELD(RadArchProbe, control_vector_ok)
|
||||
ABI_FIELD(RadArchProbe, tp_attn_rows_ok)
|
||||
ABI_FIELD(RadArchProbe, state_f16_ok)
|
||||
@@ -109,10 +110,13 @@ ABI_FIELD(RadBuildCtx, max_audio_frames)
|
||||
ABI_FIELD(RadBuildCtx, max_mixed_tok)
|
||||
ABI_FIELD(RadBuildCtx, kv_quant)
|
||||
ABI_FIELD(RadBuildCtx, attn_prefill_fp8)
|
||||
ABI_FIELD(RadBuildCtx, kv_resident_blocks)
|
||||
ABI_FIELD(RadBuildCtx, kv_stream_ok)
|
||||
ABI_FIELD(RadBuildCtx, cvec)
|
||||
ABI_FIELD(RadBuildCtx, tp_attn_rows)
|
||||
ABI_FIELD(RadBuildCtx, state_dtype)
|
||||
ABI_FIELD(RadBuildCtx, draft_coupling)
|
||||
ABI_FIELD(RadBuildCtx, weight_prefetch_off)
|
||||
ABI_STRUCT(RadAudioGenBatch)
|
||||
ABI_FIELD(RadAudioGenBatch, n_lane)
|
||||
ABI_FIELD(RadAudioGenBatch, lane)
|
||||
@@ -476,6 +480,7 @@ ABI_FIELD(RadKVGroupBatch, state_index)
|
||||
ABI_FIELD(RadKVGroupBatch, state_index_pitch)
|
||||
ABI_FIELD(RadKVGroupBatch, block_size)
|
||||
ABI_FIELD(RadKVGroupBatch, max_blocks)
|
||||
ABI_FIELD(RadKVGroupBatch, stream)
|
||||
ABI_STRUCT(RadKVGroupDecl)
|
||||
ABI_FIELD(RadKVGroupDecl, kind)
|
||||
ABI_FIELD(RadKVGroupDecl, dtype)
|
||||
@@ -484,6 +489,16 @@ ABI_FIELD(RadKVGroupDecl, n_head_kv)
|
||||
ABI_FIELD(RadKVGroupDecl, head_dim)
|
||||
ABI_FIELD(RadKVGroupDecl, state_dim)
|
||||
ABI_FIELD(RadKVGroupDecl, conv_width)
|
||||
ABI_STRUCT(RadKVStream)
|
||||
ABI_FIELD(RadKVStream, host)
|
||||
ABI_FIELD(RadKVStream, res)
|
||||
ABI_FIELD(RadKVStream, slot_block)
|
||||
ABI_FIELD(RadKVStream, slot_state)
|
||||
ABI_FIELD(RadKVStream, ctl)
|
||||
ABI_FIELD(RadKVStream, block_bytes)
|
||||
ABI_FIELD(RadKVStream, host_layer_stride)
|
||||
ABI_FIELD(RadKVStream, slots)
|
||||
ABI_FIELD(RadKVStream, host_bytes)
|
||||
ABI_STRUCT(RadKernelInfo)
|
||||
ABI_FIELD(RadKernelInfo, name)
|
||||
ABI_FIELD(RadKernelInfo, op)
|
||||
@@ -705,6 +720,19 @@ ABI_FIELD(RadVideoGenBatch, image)
|
||||
ABI_FIELD(RadVideoGenBatch, has_image)
|
||||
ABI_FIELD(RadVideoGenBatch, guidance)
|
||||
ABI_FIELD(RadVideoGenBatch, decoder)
|
||||
ABI_FIELD(RadVideoGenBatch, sampler)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_pixels)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_frames)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_height)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_width)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_samples)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_n_samples)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_channels)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_geom_d)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_kind)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_slot)
|
||||
ABI_FIELD(RadVideoGenBatch, ref_tab)
|
||||
ABI_FIELD(RadVideoGenBatch, mod_cu)
|
||||
ABI_STRUCT(RadVideoGenDecl)
|
||||
ABI_FIELD(RadVideoGenDecl, name)
|
||||
ABI_FIELD(RadVideoGenDecl, tmpl)
|
||||
@@ -767,6 +795,14 @@ ABI_FIELD(RadVideoGenDecl, duration_max)
|
||||
ABI_FIELD(RadVideoGenDecl, duration_dtype)
|
||||
ABI_FIELD(RadVideoGenDecl, decoders)
|
||||
ABI_FIELD(RadVideoGenDecl, decoder_max_area)
|
||||
ABI_FIELD(RadVideoGenDecl, max_ref_images)
|
||||
ABI_FIELD(RadVideoGenDecl, max_ref_videos)
|
||||
ABI_FIELD(RadVideoGenDecl, max_ref_audios)
|
||||
ABI_FIELD(RadVideoGenDecl, max_enc_frames)
|
||||
ABI_FIELD(RadVideoGenDecl, max_enc_side)
|
||||
ABI_FIELD(RadVideoGenDecl, max_enc_samples)
|
||||
ABI_FIELD(RadVideoGenDecl, enc_ratio)
|
||||
ABI_FIELD(RadVideoGenDecl, max_mod_cells)
|
||||
ABI_STRUCT(RadVideoGeom)
|
||||
ABI_FIELD(RadVideoGeom, n_text)
|
||||
ABI_FIELD(RadVideoGeom, frames)
|
||||
|
||||
+49
-13
@@ -1,8 +1,8 @@
|
||||
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 27 and
|
||||
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 31 and
|
||||
* RAD_FORMAT_VER 2, as { type, field, offset, size } rows ("" is the struct itself). A snapshot
|
||||
* of the headers on x86-64 Linux, which abi_layout_test.cpp holds the layout to; regenerate it
|
||||
* from the test's printout only together with a version bump. */
|
||||
{ "RadArchProbe", "", 0, 88 },
|
||||
{ "RadArchProbe", "", 0, 96 },
|
||||
{ "RadArchProbe", "draft_depth", 0, 4 },
|
||||
{ "RadArchProbe", "draft_depth_fixed", 4, 4 },
|
||||
{ "RadArchProbe", "shape_probe_ok", 8, 4 },
|
||||
@@ -15,9 +15,10 @@
|
||||
{ "RadArchProbe", "gen_video", 64, 4 },
|
||||
{ "RadArchProbe", "kv_quant_ok", 68, 4 },
|
||||
{ "RadArchProbe", "chain_pays", 72, 4 },
|
||||
{ "RadArchProbe", "control_vector_ok", 76, 4 },
|
||||
{ "RadArchProbe", "tp_attn_rows_ok", 80, 4 },
|
||||
{ "RadArchProbe", "state_f16_ok", 84, 4 },
|
||||
{ "RadArchProbe", "kv_stream_ok", 76, 4 },
|
||||
{ "RadArchProbe", "control_vector_ok", 80, 4 },
|
||||
{ "RadArchProbe", "tp_attn_rows_ok", 84, 4 },
|
||||
{ "RadArchProbe", "state_f16_ok", 88, 4 },
|
||||
{ "RadArgs", "", 0, 64 },
|
||||
{ "RadArgs", "t", 0, 8 },
|
||||
{ "RadArgs", "n_t", 8, 4 },
|
||||
@@ -87,7 +88,7 @@
|
||||
{ "RadBufDecl", "domain", 60, 4 },
|
||||
{ "RadBufDecl", "derive", 64, 8 },
|
||||
{ "RadBufDecl", "kv", 72, 4 },
|
||||
{ "RadBuildCtx", "", 0, 136 },
|
||||
{ "RadBuildCtx", "", 0, 152 },
|
||||
{ "RadBuildCtx", "rank", 0, 4 },
|
||||
{ "RadBuildCtx", "world_size", 4, 4 },
|
||||
{ "RadBuildCtx", "max_tok", 8, 8 },
|
||||
@@ -106,10 +107,13 @@
|
||||
{ "RadBuildCtx", "max_mixed_tok", 96, 8 },
|
||||
{ "RadBuildCtx", "kv_quant", 104, 4 },
|
||||
{ "RadBuildCtx", "attn_prefill_fp8", 108, 4 },
|
||||
{ "RadBuildCtx", "cvec", 112, 8 },
|
||||
{ "RadBuildCtx", "tp_attn_rows", 120, 4 },
|
||||
{ "RadBuildCtx", "state_dtype", 124, 4 },
|
||||
{ "RadBuildCtx", "draft_coupling", 128, 4 },
|
||||
{ "RadBuildCtx", "kv_resident_blocks", 112, 8 },
|
||||
{ "RadBuildCtx", "kv_stream_ok", 120, 4 },
|
||||
{ "RadBuildCtx", "cvec", 128, 8 },
|
||||
{ "RadBuildCtx", "tp_attn_rows", 136, 4 },
|
||||
{ "RadBuildCtx", "state_dtype", 140, 4 },
|
||||
{ "RadBuildCtx", "draft_coupling", 144, 4 },
|
||||
{ "RadBuildCtx", "weight_prefetch_off", 148, 4 },
|
||||
{ "RadAudioGenBatch", "", 0, 344 },
|
||||
{ "RadAudioGenBatch", "n_lane", 0, 8 },
|
||||
{ "RadAudioGenBatch", "lane", 8, 8 },
|
||||
@@ -463,7 +467,7 @@
|
||||
{ "RadGeneratorDecl", "chunk_bos", 364, 4 },
|
||||
{ "RadGeneratorDecl", "chunk_eos", 368, 4 },
|
||||
{ "RadGeneratorDecl", "cond_opts", 372, 4 },
|
||||
{ "RadKVGroupBatch", "", 0, 72 },
|
||||
{ "RadKVGroupBatch", "", 0, 80 },
|
||||
{ "RadKVGroupBatch", "group", 0, 4 },
|
||||
{ "RadKVGroupBatch", "slot_mapping", 8, 8 },
|
||||
{ "RadKVGroupBatch", "block_table", 16, 8 },
|
||||
@@ -473,6 +477,7 @@
|
||||
{ "RadKVGroupBatch", "state_index_pitch", 48, 8 },
|
||||
{ "RadKVGroupBatch", "block_size", 56, 8 },
|
||||
{ "RadKVGroupBatch", "max_blocks", 64, 8 },
|
||||
{ "RadKVGroupBatch", "stream", 72, 8 },
|
||||
{ "RadKVGroupDecl", "", 0, 56 },
|
||||
{ "RadKVGroupDecl", "kind", 0, 4 },
|
||||
{ "RadKVGroupDecl", "dtype", 4, 4 },
|
||||
@@ -481,6 +486,16 @@
|
||||
{ "RadKVGroupDecl", "head_dim", 24, 8 },
|
||||
{ "RadKVGroupDecl", "state_dim", 32, 16 },
|
||||
{ "RadKVGroupDecl", "conv_width", 48, 8 },
|
||||
{ "RadKVStream", "", 0, 72 },
|
||||
{ "RadKVStream", "host", 0, 8 },
|
||||
{ "RadKVStream", "res", 8, 8 },
|
||||
{ "RadKVStream", "slot_block", 16, 8 },
|
||||
{ "RadKVStream", "slot_state", 24, 8 },
|
||||
{ "RadKVStream", "ctl", 32, 8 },
|
||||
{ "RadKVStream", "block_bytes", 40, 8 },
|
||||
{ "RadKVStream", "host_layer_stride", 48, 8 },
|
||||
{ "RadKVStream", "slots", 56, 8 },
|
||||
{ "RadKVStream", "host_bytes", 64, 8 },
|
||||
{ "RadKernelInfo", "", 0, 168 },
|
||||
{ "RadKernelInfo", "name", 0, 8 },
|
||||
{ "RadKernelInfo", "op", 8, 8 },
|
||||
@@ -674,7 +689,7 @@
|
||||
{ "RadTunable", "n_values", 16, 4 },
|
||||
{ "RadTunable", "deflt", 24, 8 },
|
||||
{ "RadTunable", "doc", 32, 8 },
|
||||
{ "RadVideoGenBatch", "", 0, 240 },
|
||||
{ "RadVideoGenBatch", "", 0, 320 },
|
||||
{ "RadVideoGenBatch", "lane", 0, 4 },
|
||||
{ "RadVideoGenBatch", "geom", 4, 24 },
|
||||
{ "RadVideoGenBatch", "geom_d", 32, 8 },
|
||||
@@ -702,7 +717,20 @@
|
||||
{ "RadVideoGenBatch", "has_image", 216, 4 },
|
||||
{ "RadVideoGenBatch", "guidance", 224, 8 },
|
||||
{ "RadVideoGenBatch", "decoder", 232, 4 },
|
||||
{ "RadVideoGenDecl", "", 0, 512 },
|
||||
{ "RadVideoGenBatch", "sampler", 236, 4 },
|
||||
{ "RadVideoGenBatch", "enc_pixels", 240, 8 },
|
||||
{ "RadVideoGenBatch", "enc_frames", 248, 4 },
|
||||
{ "RadVideoGenBatch", "enc_height", 252, 4 },
|
||||
{ "RadVideoGenBatch", "enc_width", 256, 4 },
|
||||
{ "RadVideoGenBatch", "enc_samples", 264, 8 },
|
||||
{ "RadVideoGenBatch", "enc_n_samples", 272, 8 },
|
||||
{ "RadVideoGenBatch", "enc_channels", 280, 4 },
|
||||
{ "RadVideoGenBatch", "enc_geom_d", 288, 8 },
|
||||
{ "RadVideoGenBatch", "enc_kind", 296, 4 },
|
||||
{ "RadVideoGenBatch", "enc_slot", 300, 4 },
|
||||
{ "RadVideoGenBatch", "ref_tab", 304, 8 },
|
||||
{ "RadVideoGenBatch", "mod_cu", 312, 8 },
|
||||
{ "RadVideoGenDecl", "", 0, 568 },
|
||||
{ "RadVideoGenDecl", "name", 0, 8 },
|
||||
{ "RadVideoGenDecl", "tmpl", 8, 8 },
|
||||
{ "RadVideoGenDecl", "max_text", 16, 8 },
|
||||
@@ -764,6 +792,14 @@
|
||||
{ "RadVideoGenDecl", "duration_dtype", 488, 4 },
|
||||
{ "RadVideoGenDecl", "decoders", 496, 8 },
|
||||
{ "RadVideoGenDecl", "decoder_max_area", 504, 8 },
|
||||
{ "RadVideoGenDecl", "max_ref_images", 512, 8 },
|
||||
{ "RadVideoGenDecl", "max_ref_videos", 520, 8 },
|
||||
{ "RadVideoGenDecl", "max_ref_audios", 528, 8 },
|
||||
{ "RadVideoGenDecl", "max_enc_frames", 536, 8 },
|
||||
{ "RadVideoGenDecl", "max_enc_side", 544, 8 },
|
||||
{ "RadVideoGenDecl", "max_enc_samples", 552, 8 },
|
||||
{ "RadVideoGenDecl", "enc_ratio", 560, 4 },
|
||||
{ "RadVideoGenDecl", "max_mod_cells", 564, 4 },
|
||||
{ "RadVideoGeom", "", 0, 24 },
|
||||
{ "RadVideoGeom", "n_text", 0, 4 },
|
||||
{ "RadVideoGeom", "frames", 4, 4 },
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
*
|
||||
* Checked: a C translation unit (abi_c_test.c, strict C11) lays every struct out as C++ does; every
|
||||
* struct's listed fields account for its size, so the list in abi_layout_rows.h is complete; and
|
||||
* the layout agrees with the table below, taken at RAD_ABI_VERSION 27 and RAD_FORMAT_VER 2. Under
|
||||
* the layout agrees with the table below, taken at RAD_ABI_VERSION 31 and RAD_FORMAT_VER 2. Under
|
||||
* those versions a listed field may not move or change size, an ABI struct may only grow by fields
|
||||
* past its old end, and an on-disk struct may not change at all. The table is a snapshot of the
|
||||
* headers: nothing else states the layout. When it disagrees the test prints the live table.
|
||||
@@ -58,8 +58,8 @@ std::vector<Row> cpp_rows() {
|
||||
};
|
||||
}
|
||||
|
||||
/* The layout at RAD_ABI_VERSION 27 / RAD_FORMAT_VER 2 (see the file header). */
|
||||
constexpr uint32_t kTableAbi = 27, kTableFormat = 2;
|
||||
/* The layout at RAD_ABI_VERSION 31 / RAD_FORMAT_VER 2 (see the file header). */
|
||||
constexpr uint32_t kTableAbi = 31, kTableFormat = 2;
|
||||
const AbiRow kTable[] = {
|
||||
#include "abi_layout_table.h"
|
||||
};
|
||||
|
||||
@@ -360,8 +360,8 @@ TEST(a_history_pass_keeps_the_hosts_rows_and_repeats_the_last_committed_one) {
|
||||
* So on every pass the card stages, the last row of a run -- round 1's input on a history pass,
|
||||
* the only row whose output the head goes on with -- must sit exactly at its own position, and no
|
||||
* row may count past its own: a key past it is a position the head's layer has not written for
|
||||
* this sequence. A history pass that accepted acc < n_spec drafts used to put its last row
|
||||
* n_spec - acc positions too far, and MTP round 1 read whatever those slots held. */
|
||||
* this sequence. (After a verify that accepted acc < n_spec drafts, a history pass's whole run
|
||||
* length would put its last row n_spec - acc positions too far.) */
|
||||
TEST(no_draft_pass_row_reads_keys_past_its_own_position) {
|
||||
const int n_spec = 3;
|
||||
for (int aux = 0; aux <= 2; ++aux)
|
||||
|
||||
+54
-1
@@ -71,7 +71,8 @@ struct RecMap {
|
||||
std::vector<std::string> src;
|
||||
int concat_dim = 0;
|
||||
};
|
||||
struct RecKV { std::string name; RadKVGroupDecl d{}; bool zero = false; bool replicated = false; };
|
||||
struct RecKV { std::string name; RadKVGroupDecl d{}; bool zero = false; bool replicated = false;
|
||||
bool dense = false; };
|
||||
struct RecIssue {
|
||||
rad_op op = 0;
|
||||
std::vector<RadOperand> opd;
|
||||
@@ -147,6 +148,11 @@ struct RadBuilder {
|
||||
const RecOp* op_of(rad_op h) const { return h ? &ops[h - 1] : nullptr; }
|
||||
};
|
||||
|
||||
struct StageRec {
|
||||
size_t issue = 0; /* the issue count when the stage copy was issued */
|
||||
int layer = -1;
|
||||
};
|
||||
|
||||
struct RadCtx {
|
||||
RadBuilder* b = nullptr;
|
||||
const RadBatch* batch = nullptr;
|
||||
@@ -160,6 +166,13 @@ struct RadCtx {
|
||||
/* Device copies into a buffer (rad_memcpy_async to a rad_buf_ptr address): the buffer and the
|
||||
* issue number the copy came before. The step lint counts each as a write there. */
|
||||
std::vector<std::pair<size_t, rad_buf>> copies;
|
||||
/* The prefill-stage test: a stage call is recorded at the current issue index so the test can
|
||||
* assert it sits between the layer's store and its attention. */
|
||||
bool stage_on = false;
|
||||
int stage_last = -1;
|
||||
std::vector<StageRec> stages;
|
||||
/* kv_stage_next: after which issue index the next layer's copy was handed over. */
|
||||
std::vector<StageRec> stages_next;
|
||||
};
|
||||
|
||||
/* -------------------------------------------------------------------- the declare-side ABI */
|
||||
@@ -237,6 +250,14 @@ extern "C" rad_kvgroup rad_decl_kv_group(RadBuilder* b, const char* name,
|
||||
|
||||
extern "C" int64_t rad_kv_block_size(RadBuilder* b, rad_kvgroup g) { (void)g; return b->kv_block; }
|
||||
|
||||
extern "C" int64_t rad_kv_layer_bytes(RadBuilder* b, rad_kvgroup g) {
|
||||
if (!b || !g || g > b->kv_groups.size()) return 0;
|
||||
const RadKVGroupDecl& d = b->kv_groups[g - 1].d;
|
||||
if (d.kind != RAD_KV_FULL && d.kind != RAD_KV_WINDOW) return 0;
|
||||
const int64_t nh = d.n_head_kv > 0 ? d.n_head_kv : 1;
|
||||
return rad_dtype_bytes(d.dtype, 2 * b->kv_block * nh * d.head_dim);
|
||||
}
|
||||
|
||||
extern "C" int rad_bind_layer_kv(RadBuilder* b, int layer, rad_kvgroup g) {
|
||||
b->binds.push_back({layer, g});
|
||||
return RAD_OK;
|
||||
@@ -346,6 +367,15 @@ extern "C" int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g) {
|
||||
b->kv_groups[g - 1].zero = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
/* Recorded like zero, and like the real builder refused on a non-full group. Not part of
|
||||
* graph_hash(): the flag changes how much of the group the carve funds, not the graph, so the
|
||||
* pinned graphs stand. */
|
||||
extern "C" int rad_kv_group_dense_read(RadBuilder* b, rad_kvgroup g) {
|
||||
if (!b || g == 0 || g > b->kv_groups.size()) return RAD_E_INVAL;
|
||||
if (b->kv_groups[g - 1].d.kind != RAD_KV_FULL) return RAD_E_INVAL;
|
||||
b->kv_groups[g - 1].dense = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
/* Recorded like zero, and like the real builder refused on a zero or unpaged group. Not part of
|
||||
* graph_hash(): the flag changes what a host tier slot holds, not the graph, so the pinned
|
||||
* graphs stand. */
|
||||
@@ -435,6 +465,29 @@ extern "C" int rad_lane_join(RadCtx* c, int from, int to) {
|
||||
c->joins.push_back({ c->issues.size(), from, to });
|
||||
return RAD_OK;
|
||||
}
|
||||
/* No pool binding here, so a layer is at the index it names: the arch test uses layer 0 where it
|
||||
* checks the mirror offset. */
|
||||
extern "C" int rad_kv_layer_index(RadCtx* c, rad_kvgroup g, int layer) {
|
||||
(void)c; (void)g;
|
||||
return layer;
|
||||
}
|
||||
/* The prefill stage: no device here, so record the first call for a layer at its place in the
|
||||
* issue stream, which is before the layer's store. Off unless a test selects the stage view. */
|
||||
extern "C" int rad_kv_stage_layer(RadCtx* c, rad_kvgroup g, const RadKVGroupBatch* kvb, int layer) {
|
||||
(void)g;
|
||||
if (!c || !kvb || !kvb->stream || !c->stage_on) return 0;
|
||||
if (layer == c->stage_last) return 1;
|
||||
c->stage_last = layer;
|
||||
c->stages.push_back(StageRec{ c->issues.size(), layer });
|
||||
return 1;
|
||||
}
|
||||
/* The next layer's copy is handed to the DMA engine after this layer's attention. */
|
||||
extern "C" int rad_kv_stage_next(RadCtx* c, rad_kvgroup g, int layer) {
|
||||
(void)g;
|
||||
if (!c || !c->stage_on) return 0;
|
||||
c->stages_next.push_back(StageRec{ c->issues.size(), layer });
|
||||
return 0;
|
||||
}
|
||||
/* A block that refuses the batch records the reason for the tests. */
|
||||
extern "C" int rad_step_fail(RadCtx* c, const char* what) {
|
||||
c->step_fail = what ? what : "";
|
||||
|
||||
+678
-225
File diff suppressed because it is too large.
Load diff
+31
-1
@@ -422,13 +422,14 @@ const std::map<std::string, std::vector<std::string>>& legal_values() {
|
||||
{ "--model", { "/m/y.rad" } }, { "--download-dir", { "/d" } },
|
||||
{ "--radiance-home", { "/h1:/h2" } }, { "--kernels", { "libref" } },
|
||||
{ "--tp", { "2" } }, { "--tp-wire", { "wht6" } }, { "--tp-wire-min-kb", { "64" } },
|
||||
{ "--tp-attn-split", { "rows" } },
|
||||
{ "--tp-attn-split", { "rows" } }, { "--weight-prefetch", { "off" } },
|
||||
{ "--p2p", { "off" } }, { "--max-num-batched-tokens", { "512" } },
|
||||
{ "--busy-prefill-chunk", { "256" } }, { "--prefill-interleave", { "2" } },
|
||||
{ "--max-num-seqs", { "4" } },
|
||||
{ "--max-model-len", { "4096" } }, { "--rope-scaling", { "yarn:4" } },
|
||||
{ "--gpu-headroom-mib", { "128" } }, { "--kv-cache-dtype", { "fp8" } },
|
||||
{ "--state-cache-dtype", { "f16" } }, { "--attn-prefill-fp8", { "both" } },
|
||||
{ "--kv-resident", { "65536" } },
|
||||
{ "--host-pool-mib", { "1024" } }, { "--host-headroom-mib", { "2048" } },
|
||||
{ "--embedding-placement", { "vram" } },
|
||||
{ "--vision-tower-placement", { "ram" } }, { "--ngram-placement", { "disk" } },
|
||||
@@ -656,6 +657,19 @@ TEST(the_attention_split_is_one_of_two_names) {
|
||||
CHECK_EQ(parse({ "--tp-attn-split", "ROWS" }, &c), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
/* The weight reads beside the collectives are on unless a deployment turns them off; anything but
|
||||
* the two names stops the server. */
|
||||
TEST(weight_prefetch_is_on_or_off) {
|
||||
Config c;
|
||||
CHECK(c.weight_prefetch);
|
||||
CHECK_EQ(parse({ "--weight-prefetch", "off" }, &c), RAD_OK);
|
||||
CHECK(!c.weight_prefetch);
|
||||
CHECK_EQ(parse({ "--weight-prefetch", "on" }, &c), RAD_OK);
|
||||
CHECK(c.weight_prefetch);
|
||||
CHECK_EQ(parse({ "--weight-prefetch", "0" }, &c), RAD_E_INVAL);
|
||||
CHECK_EQ(parse({ "--weight-prefetch", "" }, &c), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
/* The prefill attention's e4m3 legs are lossy, so the default is off and anything but the four
|
||||
* names stops the server. */
|
||||
TEST(the_attention_fp8_mode_is_one_of_four_names) {
|
||||
@@ -726,6 +740,22 @@ TEST(the_kv_cache_dtype_is_one_of_four_names) {
|
||||
CHECK_EQ(d.kv_cache_dtype, std::string("bf16"));
|
||||
}
|
||||
|
||||
/* --kv-resident is the whole switch: absent or 0 and nothing streams, and it is whole tokens
|
||||
* rounded up to the group's page at startup. The mode flag is gone, and a launch line that still
|
||||
* passes it is refused by name rather than silently served without streaming. */
|
||||
TEST(kv_resident_is_the_whole_switch_and_its_ring_is_whole_tokens) {
|
||||
Config d;
|
||||
CHECK_EQ(parse({}, &d), RAD_OK);
|
||||
CHECK_EQ(d.kv_resident, 0ll); /* nothing streams */
|
||||
CHECK(!d.kv_streams); /* derived: no group streams either */
|
||||
Config c;
|
||||
CHECK_EQ(parse({ "--kv-resident", "262144" }, &c), RAD_OK);
|
||||
CHECK_EQ(c.kv_resident, 262144ll);
|
||||
CHECK_EQ(parse({ "--kv-resident", "0" }, &c), RAD_OK);
|
||||
CHECK_EQ(c.kv_resident, 0ll);
|
||||
CHECK_EQ(parse({ "--kv-resident", "-1" }, &c), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
/* The embedding takes ram (default) or vram; the n-gram table takes auto (default), vram, ram or
|
||||
* disk. The parser records whether the embedding placement was named and leaves resolution to
|
||||
* Engine::plan, which can refuse a placement with the model in hand. */
|
||||
|
||||
@@ -326,6 +326,293 @@ TEST(changed_is_refused_without_reuse_or_for_a_tensor_nothing_reads) {
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== --lora */
|
||||
|
||||
namespace {
|
||||
|
||||
/* A PEFT adapter file: `<module>.lora_A.weight` [r,K] of 0.25 and `<module>.lora_B.weight`
|
||||
* [N,r] of 0.5 -- so B @ A is 0.25 * r everywhere -- and, when `alpha` is given, a rank-0
|
||||
* `<module>.alpha` scalar. */
|
||||
bool write_lora(const std::string& path, const std::string& module, int64_t N, int64_t K,
|
||||
int64_t r, const float* alpha) {
|
||||
std::vector<tiny::Tensor> ts;
|
||||
tiny::Tensor A{ module + ".lora_A.weight", "F32", { r, K }, {} };
|
||||
A.bytes.resize((size_t)(r * K) * 4);
|
||||
for (int64_t i = 0; i < r * K; ++i) rad_store_f32(A.bytes.data(), RAD_F32, i, 0.25f);
|
||||
tiny::Tensor B{ module + ".lora_B.weight", "F32", { N, r }, {} };
|
||||
B.bytes.resize((size_t)(N * r) * 4);
|
||||
for (int64_t i = 0; i < N * r; ++i) rad_store_f32(B.bytes.data(), RAD_F32, i, 0.5f);
|
||||
ts.push_back(std::move(A));
|
||||
ts.push_back(std::move(B));
|
||||
if (alpha) {
|
||||
tiny::Tensor s{ module + ".alpha", "F32", {}, std::vector<uint8_t>(4, 0) };
|
||||
rad_store_f32(s.bytes.data(), RAD_F32, 0, *alpha);
|
||||
ts.push_back(std::move(s));
|
||||
}
|
||||
return tiny::write_safetensors(path, ts);
|
||||
}
|
||||
|
||||
/* A copy of the world's checkpoint with each named tensor raised everywhere by its delta, in
|
||||
* the same f32 arithmetic add_lora does. */
|
||||
bool copy_ckpt_bumped(World& w, const std::string& ck,
|
||||
const std::vector<std::pair<std::string, float>>& bumps) {
|
||||
if (mkdir(ck.c_str(), 0755) != 0) return false;
|
||||
for (const char* f : { "config.json", "tokenizer.json" })
|
||||
if (!copy_file(w.ckpt + "/" + f, ck + "/" + f)) return false;
|
||||
std::vector<tiny::Tensor> ts = tiny::read_safetensors(w.ckpt + "/model.safetensors");
|
||||
size_t hits = 0;
|
||||
for (tiny::Tensor& t : ts)
|
||||
for (const std::pair<std::string, float>& b : bumps)
|
||||
if (t.name == b.first) {
|
||||
++hits;
|
||||
for (size_t i = 0; i < t.bytes.size() / 2; ++i)
|
||||
rad_store_f32(t.bytes.data(), RAD_BF16, (int64_t)i,
|
||||
rad_load_f32(t.bytes.data(), RAD_BF16, (int64_t)i) + b.second);
|
||||
}
|
||||
return hits == bumps.size() && tiny::write_safetensors(ck + "/model.safetensors", ts);
|
||||
}
|
||||
|
||||
bool copy_ckpt_raised(World& w, const std::string& ck, const std::string& target, float delta) {
|
||||
return copy_ckpt_bumped(w, ck, { { target, delta } });
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* --lora merges W + B @ A into the tensor the module names, and the merge marks that tensor
|
||||
* changed: --reuse converts the weights reading it and copies the rest untouched. The merged
|
||||
* container is byte-identical to one converted from a hand-raised checkpoint -- same f32
|
||||
* arithmetic, same recipe. */
|
||||
TEST(lora_merges_into_its_target_and_reconverts_the_weights_that_read_it) {
|
||||
World& w = world();
|
||||
REQUIRE(w.ok);
|
||||
const std::string target = "model.layers.0.mlp.down_proj.weight";
|
||||
const auto it = w.src.find(target);
|
||||
REQUIRE(it != w.src.end());
|
||||
REQUIRE_EQ(it->second.dtype, std::string("BF16"));
|
||||
REQUIRE_EQ(it->second.shape.size(), (size_t)2);
|
||||
const int64_t N = it->second.shape[0], K = it->second.shape[1];
|
||||
|
||||
/* PEFT names the module, without the target's `.weight`. */
|
||||
const std::string mod = target.substr(0, target.size() - 7);
|
||||
tiny::TempDir d("convert_l");
|
||||
REQUIRE(write_lora(d / "lora.safetensors", mod, N, K, 2, nullptr));
|
||||
std::string log;
|
||||
REQUIRE_EQ(convert(w.ckpt, { "-o", d / "merged.rad", "--recipe", w.recipe, "--reuse", w.base,
|
||||
"--lora", d / "lora.safetensors" }, &log), 0);
|
||||
CHECK(has(log, "merged at strength 1"));
|
||||
RadFile m;
|
||||
REQUIRE_EQ(m.open((d / "merged.rad").c_str()), RAD_OK);
|
||||
RadFile base;
|
||||
REQUIRE_EQ(base.open(w.base.c_str()), RAD_OK);
|
||||
const std::vector<std::string> diff = differing_weights(base, m);
|
||||
CHECK_EQ(diff.size(), (size_t)1);
|
||||
CHECK(!diff.empty() && diff[0] == "blk.0.ffn_down.weight");
|
||||
|
||||
REQUIRE(copy_ckpt_raised(w, d / "ref", target, 0.5f * 0.25f * 2.f));
|
||||
REQUIRE_EQ(convert(d / "ref", { "-o", d / "ref.rad", "--recipe", w.recipe }, nullptr), 0);
|
||||
RadFile rf;
|
||||
REQUIRE_EQ(rf.open((d / "ref.rad").c_str()), RAD_OK);
|
||||
const RadFileEntry* a = m.find("blk.0.ffn_down.weight");
|
||||
const RadFileEntry* b = rf.find("blk.0.ffn_down.weight");
|
||||
REQUIRE(a && b);
|
||||
CHECK(entry_bytes(m, *a) == entry_bytes(rf, *b));
|
||||
}
|
||||
|
||||
/* A module spelled under a wrapper prefix resolves to the checkpoint's tensor, and an .alpha
|
||||
* states the scale: alpha 4 at rank 2 doubles the merge. */
|
||||
TEST(lora_strips_wrapper_prefixes_and_scales_by_alpha) {
|
||||
World& w = world();
|
||||
REQUIRE(w.ok);
|
||||
const std::string target = "model.layers.0.mlp.down_proj.weight";
|
||||
const auto it = w.src.find(target);
|
||||
REQUIRE(it != w.src.end());
|
||||
const int64_t N = it->second.shape[0], K = it->second.shape[1];
|
||||
|
||||
tiny::TempDir d("convert_lp");
|
||||
const std::string mod = target.substr(0, target.size() - 7);
|
||||
const float alpha = 4.f;
|
||||
REQUIRE(write_lora(d / "lora.safetensors", "diffusion_model." + mod, N, K, 2, &alpha));
|
||||
std::string log;
|
||||
REQUIRE_EQ(convert(w.ckpt, { "-o", d / "merged.rad", "--recipe", w.recipe,
|
||||
"--lora", d / "lora.safetensors" }, &log), 0);
|
||||
REQUIRE(copy_ckpt_raised(w, d / "ref", target, 0.5f * 0.25f * 2.f * 2.f));
|
||||
REQUIRE_EQ(convert(d / "ref", { "-o", d / "ref.rad", "--recipe", w.recipe }, nullptr), 0);
|
||||
RadFile m, rf;
|
||||
REQUIRE_EQ(m.open((d / "merged.rad").c_str()), RAD_OK);
|
||||
REQUIRE_EQ(rf.open((d / "ref.rad").c_str()), RAD_OK);
|
||||
const RadFileEntry* a = m.find("blk.0.ffn_down.weight");
|
||||
const RadFileEntry* b = rf.find("blk.0.ffn_down.weight");
|
||||
REQUIRE(a && b);
|
||||
CHECK(entry_bytes(m, *a) == entry_bytes(rf, *b));
|
||||
/* And --lora-strength scales the whole merge: 0.5 of an alpha/r of 2 is a scale of 1. */
|
||||
REQUIRE_EQ(convert(w.ckpt, { "-o", d / "half.rad", "--recipe", w.recipe,
|
||||
"--lora", d / "lora.safetensors", "--lora-strength", "0.5" },
|
||||
nullptr), 0);
|
||||
REQUIRE(copy_ckpt_raised(w, d / "ref_half", target, 0.5f * 0.25f * 2.f));
|
||||
REQUIRE_EQ(convert(d / "ref_half", { "-o", d / "ref_half.rad", "--recipe", w.recipe },
|
||||
nullptr), 0);
|
||||
RadFile h, rh;
|
||||
REQUIRE_EQ(h.open((d / "half.rad").c_str()), RAD_OK);
|
||||
REQUIRE_EQ(rh.open((d / "ref_half.rad").c_str()), RAD_OK);
|
||||
const RadFileEntry* c = h.find("blk.0.ffn_down.weight");
|
||||
const RadFileEntry* e = rh.find("blk.0.ffn_down.weight");
|
||||
REQUIRE(c && e);
|
||||
CHECK(entry_bytes(h, *c) == entry_bytes(rh, *e));
|
||||
}
|
||||
|
||||
/* A module the checkpoint does not ship is refused by name; A and B that do not fit the target
|
||||
* are refused with the shapes; --lora with --in-place is refused where --changed is. */
|
||||
TEST(lora_refusals_name_the_module_the_shapes_or_the_flag) {
|
||||
World& w = world();
|
||||
REQUIRE(w.ok);
|
||||
const std::string target = "model.layers.0.mlp.down_proj.weight";
|
||||
const auto it = w.src.find(target);
|
||||
REQUIRE(it != w.src.end());
|
||||
const int64_t N = it->second.shape[0], K = it->second.shape[1];
|
||||
tiny::TempDir d("convert_lf");
|
||||
|
||||
std::string log;
|
||||
REQUIRE(write_lora(d / "nope.safetensors", "model.layers.0.mlp.nope_proj", N, K, 2, nullptr));
|
||||
CHECK(convert(w.ckpt, { "-o", d / "a.rad", "--recipe", w.recipe,
|
||||
"--lora", d / "nope.safetensors" }, &log) != 0);
|
||||
CHECK(has(log, "nope_proj"));
|
||||
CHECK(!exists(d / "a.rad"));
|
||||
|
||||
{
|
||||
std::vector<tiny::Tensor> ts;
|
||||
const std::string mod = target.substr(0, target.size() - 7);
|
||||
tiny::Tensor A{ mod + ".lora_A.weight", "F32", { 2, K + 3 }, {} };
|
||||
A.bytes.assign((size_t)(2 * (K + 3)) * 4, 0);
|
||||
tiny::Tensor B{ mod + ".lora_B.weight", "F32", { N + 1, 2 }, {} };
|
||||
B.bytes.assign((size_t)((N + 1) * 2) * 4, 0);
|
||||
ts.push_back(std::move(A));
|
||||
ts.push_back(std::move(B));
|
||||
REQUIRE(tiny::write_safetensors(d / "bad.safetensors", ts));
|
||||
}
|
||||
CHECK(convert(w.ckpt, { "-o", d / "b.rad", "--recipe", w.recipe,
|
||||
"--lora", d / "bad.safetensors" }, &log) != 0);
|
||||
CHECK(has(log, "does not fit"));
|
||||
CHECK(!exists(d / "b.rad"));
|
||||
|
||||
CHECK(convert(w.ckpt, { "--recipe", w.recipe, "--reuse", w.base, "--in-place",
|
||||
"--lora", d / "nope.safetensors" }, &log) != 0);
|
||||
CHECK(has(log, "--lora merges into the source"));
|
||||
}
|
||||
|
||||
/* A --lora-map rule lands one fused module on several checkpoint tensors: B's rows split
|
||||
* along the targets in the order listed, each taking its own row count, and every target
|
||||
* joins the changed set. */
|
||||
TEST(lora_map_fuses_one_module_into_several_targets_by_row_window) {
|
||||
World& w = world();
|
||||
REQUIRE(w.ok);
|
||||
const std::string q = "model.layers.0.self_attn.q_proj.weight";
|
||||
const std::string k = "model.layers.0.self_attn.k_proj.weight";
|
||||
const std::string v = "model.layers.0.self_attn.v_proj.weight";
|
||||
const auto qq = w.src.find(q), qk = w.src.find(k), qv = w.src.find(v);
|
||||
REQUIRE(qq != w.src.end() && qk != w.src.end() && qv != w.src.end());
|
||||
const int64_t Nq = qq->second.shape[0], Nk = qk->second.shape[0], Nv = qv->second.shape[0],
|
||||
K = qq->second.shape[1];
|
||||
REQUIRE(qk->second.shape[1] == K && qv->second.shape[1] == K);
|
||||
REQUIRE(Nq != Nk); /* an asymmetric split can only come from the targets' own row counts */
|
||||
|
||||
tiny::TempDir d("convert_lm");
|
||||
REQUIRE(tiny::write_text(d / "map.json",
|
||||
R"({"strip": ["diffusion_model."], "modules": {"layers.*.attn.qkv": [
|
||||
"model.layers.*.self_attn.q_proj.weight",
|
||||
"model.layers.*.self_attn.k_proj.weight",
|
||||
"model.layers.*.self_attn.v_proj.weight"]}})"));
|
||||
/* A [2,K] of 0.25; B's three windows read 0.5, 1.0 and 2.0 -- so with no .alpha the
|
||||
* merge must raise q, k and v by 0.25, 0.5 and 1.0 (r * b * 0.25 each). No other
|
||||
* attribution of B's rows -- one size for all, or the windows in another order --
|
||||
* produces those three deltas on those three tensors. */
|
||||
const int64_t r = 2, N = Nq + Nk + Nv;
|
||||
std::vector<tiny::Tensor> ts;
|
||||
tiny::Tensor A{ "diffusion_model.layers.0.attn.qkv.lora_A.weight", "F32", { r, K }, {} };
|
||||
A.bytes.resize((size_t)(r * K) * 4);
|
||||
for (int64_t i = 0; i < r * K; ++i) rad_store_f32(A.bytes.data(), RAD_F32, i, 0.25f);
|
||||
tiny::Tensor B{ "diffusion_model.layers.0.attn.qkv.lora_B.weight", "F32", { N, r }, {} };
|
||||
B.bytes.resize((size_t)(N * r) * 4);
|
||||
for (int64_t n = 0; n < N; ++n) {
|
||||
const float b = n < Nq ? 0.5f : n < Nq + Nk ? 1.0f : 2.0f;
|
||||
for (int64_t j = 0; j < r; ++j) rad_store_f32(B.bytes.data(), RAD_F32, n * r + j, b);
|
||||
}
|
||||
ts.push_back(std::move(A));
|
||||
ts.push_back(std::move(B));
|
||||
REQUIRE(tiny::write_safetensors(d / "qkv.safetensors", ts));
|
||||
|
||||
std::string log;
|
||||
REQUIRE_EQ(convert(w.ckpt, { "-o", d / "merged.rad", "--recipe", w.recipe, "--reuse", w.base,
|
||||
"--lora", d / "qkv.safetensors", "--lora-map", d / "map.json" },
|
||||
&log), 0);
|
||||
CHECK(has(log, "merged at strength 1"));
|
||||
RadFile m, base;
|
||||
REQUIRE_EQ(m.open((d / "merged.rad").c_str()), RAD_OK);
|
||||
REQUIRE_EQ(base.open(w.base.c_str()), RAD_OK);
|
||||
const std::vector<std::string> diff = differing_weights(base, m);
|
||||
CHECK_EQ(diff.size(), (size_t)1); /* all three merged, and only the weight reading them */
|
||||
CHECK(!diff.empty() && diff[0] == "blk.0.attn_qkv.weight");
|
||||
|
||||
REQUIRE(copy_ckpt_bumped(w, d / "ref", { { q, 0.25f }, { k, 0.5f }, { v, 1.0f } }));
|
||||
REQUIRE_EQ(convert(d / "ref", { "-o", d / "ref.rad", "--recipe", w.recipe }, nullptr), 0);
|
||||
RadFile rf;
|
||||
REQUIRE_EQ(rf.open((d / "ref.rad").c_str()), RAD_OK);
|
||||
const RadFileEntry* a = m.find("blk.0.attn_qkv.weight");
|
||||
const RadFileEntry* b = rf.find("blk.0.attn_qkv.weight");
|
||||
REQUIRE(a && b);
|
||||
CHECK(entry_bytes(m, *a) == entry_bytes(rf, *b));
|
||||
}
|
||||
|
||||
/* A rule whose target the checkpoint lacks is a refusal, not a miss; a B whose rows do not
|
||||
* sum to its targets' rows is a refusal; --lora-map without --lora is a refusal. */
|
||||
TEST(lora_map_refusals_name_the_target_the_sums_or_the_flag) {
|
||||
World& w = world();
|
||||
REQUIRE(w.ok);
|
||||
const int64_t Nq = w.src["model.layers.0.self_attn.q_proj.weight"].shape[0];
|
||||
const int64_t Nk = w.src["model.layers.0.self_attn.k_proj.weight"].shape[0];
|
||||
const int64_t K = w.src["model.layers.0.self_attn.q_proj.weight"].shape[1];
|
||||
tiny::TempDir d("convert_lmr");
|
||||
|
||||
/* One pair of the fused module's name, B of any row count. */
|
||||
const std::string mod = "diffusion_model.layers.0.attn.qkv";
|
||||
const auto pair = [&](int64_t rows) {
|
||||
std::vector<tiny::Tensor> ts;
|
||||
tiny::Tensor A{ mod + ".lora_A.weight", "F32", { 2, K }, {} };
|
||||
A.bytes.assign((size_t)(2 * K) * 4, 0);
|
||||
tiny::Tensor B{ mod + ".lora_B.weight", "F32", { rows, 2 }, {} };
|
||||
B.bytes.assign((size_t)(rows * 2) * 4, 0);
|
||||
ts.push_back(std::move(A));
|
||||
ts.push_back(std::move(B));
|
||||
return tiny::write_safetensors(d / "p.safetensors", ts);
|
||||
};
|
||||
|
||||
std::string log;
|
||||
REQUIRE(tiny::write_text(d / "ghost.json",
|
||||
R"({"strip": ["diffusion_model."], "modules": {"layers.*.attn.qkv": [
|
||||
"model.layers.*.self_attn.q_proj.weight",
|
||||
"model.layers.*.self_attn.ghost_proj.weight"]}})"));
|
||||
REQUIRE(pair(Nq + Nk));
|
||||
CHECK(convert(w.ckpt, { "-o", d / "a.rad", "--recipe", w.recipe, "--lora", d / "p.safetensors",
|
||||
"--lora-map", d / "ghost.json" }, &log) != 0);
|
||||
CHECK(has(log, "ghost_proj"));
|
||||
CHECK(has(log, "does not ship"));
|
||||
CHECK(!exists(d / "a.rad"));
|
||||
|
||||
REQUIRE(tiny::write_text(d / "ok.json",
|
||||
R"({"strip": ["diffusion_model."], "modules": {"layers.*.attn.qkv": [
|
||||
"model.layers.*.self_attn.q_proj.weight",
|
||||
"model.layers.*.self_attn.k_proj.weight"]}})"));
|
||||
REQUIRE(pair(Nq + Nk + 1)); /* one row past the two targets */
|
||||
CHECK(convert(w.ckpt, { "-o", d / "b.rad", "--recipe", w.recipe, "--lora", d / "p.safetensors",
|
||||
"--lora-map", d / "ok.json" }, &log) != 0);
|
||||
CHECK(has(log, "rows sum to"));
|
||||
CHECK(!exists(d / "b.rad"));
|
||||
|
||||
CHECK(convert(w.ckpt, { "-o", d / "c.rad", "--recipe", w.recipe,
|
||||
"--lora-map", d / "ok.json" }, &log) != 0);
|
||||
CHECK(has(log, "--lora-map renames"));
|
||||
CHECK(!exists(d / "c.rad"));
|
||||
}
|
||||
|
||||
/* ================================================================== --in-place */
|
||||
|
||||
/* Extending a container with nothing new keeps every weight at its offset, and the .pre-append
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regenerate golden.json -- the reference numbers arch/minimaxh3/rad_ref2va_pack.cpp is tested
|
||||
against (tests/ref2va_pack_test.cpp).
|
||||
|
||||
gen_golden.py /path/to/ComfyUI/comfy/ldm/minimax/model.py [out.json]
|
||||
|
||||
The reference implementation lives in the ComfyUI tree; importing its package pulls the whole
|
||||
device stack, so this extracts exactly the layout's source -- the four constants, the grid helpers
|
||||
and the PackedLayout class -- with `ast`, execs them on torch alone, and runs the cases below.
|
||||
Nothing here is a re-derivation: every number in golden.json is computed by the reference code
|
||||
itself, at float64, from the file it is given. When a new version of the reference changes
|
||||
golden.json, the port changes with it.
|
||||
"""
|
||||
|
||||
import ast
|
||||
import json
|
||||
import sys
|
||||
|
||||
NEED = ["_axis_from_sqrt_area", "_frame_grid", "_video_t_spans", "_video_t_grid", "_ref_t_span",
|
||||
"_audio_grid", "_video_grid", "PackedLayout"]
|
||||
NEED_ASSIGN = ["FRAME_PER_TOKEN", "FRAME_RESCALE", "VISUAL_COND_TIMESTEP", "AUDIO_COND_TIMESTEP"]
|
||||
|
||||
|
||||
def dump(v, f, ind=0):
|
||||
"""JSON with an object a key a line and every list on one line, so a golden diffs by key."""
|
||||
if isinstance(v, dict) and v:
|
||||
pad = " " * (ind + 1)
|
||||
items = list(v.items())
|
||||
f.write("{\n")
|
||||
for i, (k, x) in enumerate(items):
|
||||
f.write(pad + json.dumps(k) + ": ")
|
||||
dump(x, f, ind + 1)
|
||||
f.write(",\n" if i + 1 < len(items) else "\n")
|
||||
f.write(" " * ind + "}")
|
||||
else:
|
||||
f.write(json.dumps(v, separators=(", ", ": ")))
|
||||
|
||||
|
||||
def extract(path):
|
||||
"""The reference's layout source, exec'd with torch/math only."""
|
||||
import math
|
||||
import torch
|
||||
with open(path) as f:
|
||||
src = f.read()
|
||||
tree = ast.parse(src)
|
||||
picked, got = [], set()
|
||||
for node in tree.body:
|
||||
names = ([t.id for t in node.targets if isinstance(t, ast.Name)]
|
||||
if isinstance(node, ast.Assign) else
|
||||
[node.name] if isinstance(node, (ast.FunctionDef, ast.ClassDef)) else [])
|
||||
if any(n in NEED or n in NEED_ASSIGN for n in names):
|
||||
picked.append(ast.get_source_segment(src, node))
|
||||
got.update(names)
|
||||
missing = (set(NEED) | set(NEED_ASSIGN)) - got
|
||||
if missing:
|
||||
sys.exit(f"{path} does not define: {sorted(missing)} -- reference moved?")
|
||||
ns = {"math": math, "torch": torch}
|
||||
exec("\n\n".join(picked), ns)
|
||||
return ns
|
||||
|
||||
|
||||
CASES = {
|
||||
# plain t2va: the pack keeps the three segments [text | audio | video] exactly
|
||||
"t2va": dict(text_len=5, target=(3, 8, 10, 4), keyframes=[], refs=[]),
|
||||
# fl2va keyframes at frame 0 (shares the target origin) and mid-timeline, video-only and both
|
||||
"fl2va": dict(text_len=4, target=(3, 8, 8, 3),
|
||||
keyframes=[dict(frame=0, video_t=1, audio_t=2), dict(frame=7, video_t=2, audio_t=0)],
|
||||
refs=[]),
|
||||
# every reference kind in one request: a photo, a standalone soundtrack, a silent clip, and a
|
||||
# clip with sound (its audio packs before its video, at the clip's own width extremes); a
|
||||
# second photo after them; audio_t=0 targets the silent-video edge
|
||||
"ref2va_all": dict(text_len=6, target=(2, 8, 8, 0),
|
||||
keyframes=[],
|
||||
refs=[dict(kind="image", latent_h=6, latent_w=10, latent_t=0, ref_audio_t=0),
|
||||
dict(kind="audio", latent_h=0, latent_w=0, latent_t=0, ref_audio_t=3),
|
||||
dict(kind="video", latent_h=4, latent_w=6, latent_t=2, ref_audio_t=0),
|
||||
dict(kind="video_audio", latent_h=5, latent_w=7, latent_t=3,
|
||||
ref_audio_t=4),
|
||||
dict(kind="image", latent_h=4, latent_w=4, latent_t=0, ref_audio_t=0)]),
|
||||
# a request at plausible sizes: a keyframe, a large photo and a clip with sound
|
||||
"chain": dict(text_len=32, target=(7, 16, 24, 6),
|
||||
keyframes=[dict(frame=0, video_t=1, audio_t=2)],
|
||||
refs=[dict(kind="image", latent_h=8, latent_w=12, latent_t=0, ref_audio_t=0),
|
||||
dict(kind="video_audio", latent_h=4, latent_w=6, latent_t=5,
|
||||
ref_audio_t=20)]),
|
||||
# degenerate prompt: text_len 0, nothing but targets
|
||||
"no_text": dict(text_len=0, target=(2, 4, 6, 1), keyframes=[], refs=[]),
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
import torch
|
||||
model_py = sys.argv[1]
|
||||
out = sys.argv[2] if len(sys.argv) > 2 else "golden.json"
|
||||
ns = extract(model_py)
|
||||
PackedLayout = ns["PackedLayout"]
|
||||
golden = {}
|
||||
for name, c in CASES.items():
|
||||
t, ah, aw, at = c["target"]
|
||||
refs = [dict(kind=r["kind"], latent_h=r["latent_h"], latent_w=r["latent_w"],
|
||||
latent_t=r["latent_t"], ref_audio_t=r["ref_audio_t"]) for r in c["refs"]]
|
||||
# the class reads only the latents' shapes (video .shape[2], audio .shape[-1]); zeros do
|
||||
kfs = [dict(resolved_frame_index=k["frame"],
|
||||
latent=torch.zeros(1, 24, k["video_t"], ah, aw) if k["video_t"] else None,
|
||||
audio_latent=torch.zeros(1, 32, 2, k["audio_t"]) if k["audio_t"] else None)
|
||||
for k in c["keyframes"]]
|
||||
lay = PackedLayout(c["text_len"], t, ah, aw, at, keyframes=kfs or None, refs=refs or None)
|
||||
golden[name] = {
|
||||
"text_len": c["text_len"], "latent_t": t, "latent_h": ah, "latent_w": aw,
|
||||
"audio_t": at,
|
||||
"keyframes": c["keyframes"], "refs": c["refs"],
|
||||
"seq_len": lay.seq_len,
|
||||
"segments": [[s, e, k] for (s, e, k) in lay.segments],
|
||||
"positions": [[float(x) for x in row] for row in lay.position_ids.tolist()],
|
||||
"img_update": [bool(b) for b in lay.img_update.tolist()],
|
||||
"audio_update": [bool(b) for b in lay.audio_update.tolist()],
|
||||
"img_pos": [int(i) for i in lay.img_pos.tolist()],
|
||||
"audio_pos": [int(i) for i in lay.audio_pos.tolist()],
|
||||
}
|
||||
with open(out, "w") as f:
|
||||
dump(golden, f)
|
||||
f.write("\n")
|
||||
print(f"{out}: " + ", ".join(f"{n} {g['seq_len']} rows" for n, g in golden.items()))
|
||||
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,82 @@
|
||||
{
|
||||
"t2va": {
|
||||
"text_len": 5,
|
||||
"latent_t": 3,
|
||||
"latent_h": 8,
|
||||
"latent_w": 10,
|
||||
"audio_t": 4,
|
||||
"keyframes": [],
|
||||
"refs": [],
|
||||
"seq_len": 73,
|
||||
"segments": [[0, 5, "text"], [5, 13, "audio"], [13, 73, "video"]],
|
||||
"positions": [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0], [3.0, 0.0, 0.0], [4.0, 0.0, 0.0], [5.0, 0.0, -1.8885438199983184], [6.0, 0.0, -1.8885438199983184], [7.0, 0.0, -1.8885438199983184], [8.0, 0.0, -1.8885438199983184], [5.0, 0.0, 26.733126291998992], [6.0, 0.0, 26.733126291998992], [7.0, 0.0, 26.733126291998992], [8.0, 0.0, 26.733126291998992], [5.0, 1.6891649440013463, -1.8885438199983184], [5.0, 1.6891649440013463, 5.266873708001009], [5.0, 1.6891649440013463, 12.422291236000337], [5.0, 1.6891649440013463, 19.577708763999667], [5.0, 1.6891649440013463, 26.733126291998992], [5.0, 8.844582472000674, -1.8885438199983184], [5.0, 8.844582472000674, 5.266873708001009], [5.0, 8.844582472000674, 12.422291236000337], [5.0, 8.844582472000674, 19.577708763999667], [5.0, 8.844582472000674, 26.733126291998992], [5.0, 16.0, -1.8885438199983184], [5.0, 16.0, 5.266873708001009], [5.0, 16.0, 12.422291236000337], [5.0, 16.0, 19.577708763999667], [5.0, 16.0, 26.733126291998992], [5.0, 23.155417527999326, -1.8885438199983184], [5.0, 23.155417527999326, 5.266873708001009], [5.0, 23.155417527999326, 12.422291236000337], [5.0, 23.155417527999326, 19.577708763999667], [5.0, 23.155417527999326, 26.733126291998992], [6.666666666666667, 1.6891649440013463, -1.8885438199983184], [6.666666666666667, 1.6891649440013463, 5.266873708001009], [6.666666666666667, 1.6891649440013463, 12.422291236000337], [6.666666666666667, 1.6891649440013463, 19.577708763999667], [6.666666666666667, 1.6891649440013463, 26.733126291998992], [6.666666666666667, 8.844582472000674, -1.8885438199983184], [6.666666666666667, 8.844582472000674, 5.266873708001009], [6.666666666666667, 8.844582472000674, 12.422291236000337], [6.666666666666667, 8.844582472000674, 19.577708763999667], [6.666666666666667, 8.844582472000674, 26.733126291998992], [6.666666666666667, 16.0, -1.8885438199983184], [6.666666666666667, 16.0, 5.266873708001009], [6.666666666666667, 16.0, 12.422291236000337], [6.666666666666667, 16.0, 19.577708763999667], [6.666666666666667, 16.0, 26.733126291998992], [6.666666666666667, 23.155417527999326, -1.8885438199983184], [6.666666666666667, 23.155417527999326, 5.266873708001009], [6.666666666666667, 23.155417527999326, 12.422291236000337], [6.666666666666667, 23.155417527999326, 19.577708763999667], [6.666666666666667, 23.155417527999326, 26.733126291998992], [13.333333333333334, 1.6891649440013463, -1.8885438199983184], [13.333333333333334, 1.6891649440013463, 5.266873708001009], [13.333333333333334, 1.6891649440013463, 12.422291236000337], [13.333333333333334, 1.6891649440013463, 19.577708763999667], [13.333333333333334, 1.6891649440013463, 26.733126291998992], [13.333333333333334, 8.844582472000674, -1.8885438199983184], [13.333333333333334, 8.844582472000674, 5.266873708001009], [13.333333333333334, 8.844582472000674, 12.422291236000337], [13.333333333333334, 8.844582472000674, 19.577708763999667], [13.333333333333334, 8.844582472000674, 26.733126291998992], [13.333333333333334, 16.0, -1.8885438199983184], [13.333333333333334, 16.0, 5.266873708001009], [13.333333333333334, 16.0, 12.422291236000337], [13.333333333333334, 16.0, 19.577708763999667], [13.333333333333334, 16.0, 26.733126291998992], [13.333333333333334, 23.155417527999326, -1.8885438199983184], [13.333333333333334, 23.155417527999326, 5.266873708001009], [13.333333333333334, 23.155417527999326, 12.422291236000337], [13.333333333333334, 23.155417527999326, 19.577708763999667], [13.333333333333334, 23.155417527999326, 26.733126291998992]],
|
||||
"img_update": [true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true],
|
||||
"audio_update": [true, true, true, true, true, true, true, true],
|
||||
"img_pos": [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72],
|
||||
"audio_pos": [5, 6, 7, 8, 9, 10, 11, 12]
|
||||
},
|
||||
"fl2va": {
|
||||
"text_len": 4,
|
||||
"latent_t": 3,
|
||||
"latent_h": 8,
|
||||
"latent_w": 8,
|
||||
"audio_t": 3,
|
||||
"keyframes": [{"frame": 0, "video_t": 1, "audio_t": 2}, {"frame": 7, "video_t": 2, "audio_t": 0}],
|
||||
"refs": [],
|
||||
"seq_len": 110,
|
||||
"segments": [[0, 4, "text"], [4, 20, "cond"], [20, 24, "cond_audio"], [24, 56, "cond"], [56, 62, "audio"], [62, 110, "video"]],
|
||||
"positions": [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0], [3.0, 0.0, 0.0], [4.0, 0.0, 0.0], [4.0, 0.0, 8.0], [4.0, 0.0, 16.0], [4.0, 0.0, 24.0], [4.0, 8.0, 0.0], [4.0, 8.0, 8.0], [4.0, 8.0, 16.0], [4.0, 8.0, 24.0], [4.0, 16.0, 0.0], [4.0, 16.0, 8.0], [4.0, 16.0, 16.0], [4.0, 16.0, 24.0], [4.0, 24.0, 0.0], [4.0, 24.0, 8.0], [4.0, 24.0, 16.0], [4.0, 24.0, 24.0], [4.0, 0.0, 0.0], [5.0, 0.0, 0.0], [4.0, 0.0, 24.0], [5.0, 0.0, 24.0], [15.666666666666668, 0.0, 0.0], [15.666666666666668, 0.0, 8.0], [15.666666666666668, 0.0, 16.0], [15.666666666666668, 0.0, 24.0], [15.666666666666668, 8.0, 0.0], [15.666666666666668, 8.0, 8.0], [15.666666666666668, 8.0, 16.0], [15.666666666666668, 8.0, 24.0], [15.666666666666668, 16.0, 0.0], [15.666666666666668, 16.0, 8.0], [15.666666666666668, 16.0, 16.0], [15.666666666666668, 16.0, 24.0], [15.666666666666668, 24.0, 0.0], [15.666666666666668, 24.0, 8.0], [15.666666666666668, 24.0, 16.0], [15.666666666666668, 24.0, 24.0], [17.333333333333336, 0.0, 0.0], [17.333333333333336, 0.0, 8.0], [17.333333333333336, 0.0, 16.0], [17.333333333333336, 0.0, 24.0], [17.333333333333336, 8.0, 0.0], [17.333333333333336, 8.0, 8.0], [17.333333333333336, 8.0, 16.0], [17.333333333333336, 8.0, 24.0], [17.333333333333336, 16.0, 0.0], [17.333333333333336, 16.0, 8.0], [17.333333333333336, 16.0, 16.0], [17.333333333333336, 16.0, 24.0], [17.333333333333336, 24.0, 0.0], [17.333333333333336, 24.0, 8.0], [17.333333333333336, 24.0, 16.0], [17.333333333333336, 24.0, 24.0], [4.0, 0.0, 0.0], [5.0, 0.0, 0.0], [6.0, 0.0, 0.0], [4.0, 0.0, 24.0], [5.0, 0.0, 24.0], [6.0, 0.0, 24.0], [4.0, 0.0, 0.0], [4.0, 0.0, 8.0], [4.0, 0.0, 16.0], [4.0, 0.0, 24.0], [4.0, 8.0, 0.0], [4.0, 8.0, 8.0], [4.0, 8.0, 16.0], [4.0, 8.0, 24.0], [4.0, 16.0, 0.0], [4.0, 16.0, 8.0], [4.0, 16.0, 16.0], [4.0, 16.0, 24.0], [4.0, 24.0, 0.0], [4.0, 24.0, 8.0], [4.0, 24.0, 16.0], [4.0, 24.0, 24.0], [5.666666666666667, 0.0, 0.0], [5.666666666666667, 0.0, 8.0], [5.666666666666667, 0.0, 16.0], [5.666666666666667, 0.0, 24.0], [5.666666666666667, 8.0, 0.0], [5.666666666666667, 8.0, 8.0], [5.666666666666667, 8.0, 16.0], [5.666666666666667, 8.0, 24.0], [5.666666666666667, 16.0, 0.0], [5.666666666666667, 16.0, 8.0], [5.666666666666667, 16.0, 16.0], [5.666666666666667, 16.0, 24.0], [5.666666666666667, 24.0, 0.0], [5.666666666666667, 24.0, 8.0], [5.666666666666667, 24.0, 16.0], [5.666666666666667, 24.0, 24.0], [12.333333333333334, 0.0, 0.0], [12.333333333333334, 0.0, 8.0], [12.333333333333334, 0.0, 16.0], [12.333333333333334, 0.0, 24.0], [12.333333333333334, 8.0, 0.0], [12.333333333333334, 8.0, 8.0], [12.333333333333334, 8.0, 16.0], [12.333333333333334, 8.0, 24.0], [12.333333333333334, 16.0, 0.0], [12.333333333333334, 16.0, 8.0], [12.333333333333334, 16.0, 16.0], [12.333333333333334, 16.0, 24.0], [12.333333333333334, 24.0, 0.0], [12.333333333333334, 24.0, 8.0], [12.333333333333334, 24.0, 16.0], [12.333333333333334, 24.0, 24.0]],
|
||||
"img_update": [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true],
|
||||
"audio_update": [false, false, false, false, true, true, true, true, true, true],
|
||||
"img_pos": [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109],
|
||||
"audio_pos": [20, 21, 22, 23, 56, 57, 58, 59, 60, 61]
|
||||
},
|
||||
"ref2va_all": {
|
||||
"text_len": 6,
|
||||
"latent_t": 2,
|
||||
"latent_h": 8,
|
||||
"latent_w": 8,
|
||||
"audio_t": 0,
|
||||
"keyframes": [],
|
||||
"refs": [{"kind": "image", "latent_h": 6, "latent_w": 10, "latent_t": 0, "ref_audio_t": 0}, {"kind": "audio", "latent_h": 0, "latent_w": 0, "latent_t": 0, "ref_audio_t": 3}, {"kind": "video", "latent_h": 4, "latent_w": 6, "latent_t": 2, "ref_audio_t": 0}, {"kind": "video_audio", "latent_h": 5, "latent_w": 7, "latent_t": 3, "ref_audio_t": 4}, {"kind": "image", "latent_h": 4, "latent_w": 4, "latent_t": 0, "ref_audio_t": 0}],
|
||||
"seq_len": 101,
|
||||
"segments": [[0, 6, "text"], [6, 21, "ref_img"], [21, 27, "ref_audio"], [27, 39, "ref_img"], [39, 47, "ref_audio"], [47, 65, "ref_img"], [65, 69, "ref_img"], [69, 69, "audio"], [69, 101, "video"]],
|
||||
"positions": [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0], [3.0, 0.0, 0.0], [4.0, 0.0, 0.0], [5.0, 0.0, 0.0], [6.0, 3.6064532921362655, -4.65591117977289], [6.0, 3.6064532921362655, 3.6064532921362655], [6.0, 3.6064532921362655, 11.86881776404542], [6.0, 3.6064532921362655, 20.131182235954576], [6.0, 3.6064532921362655, 28.39354670786373], [6.0, 11.868817764045422, -4.65591117977289], [6.0, 11.868817764045422, 3.6064532921362655], [6.0, 11.868817764045422, 11.86881776404542], [6.0, 11.868817764045422, 20.131182235954576], [6.0, 11.868817764045422, 28.39354670786373], [6.0, 20.13118223595458, -4.65591117977289], [6.0, 20.13118223595458, 3.6064532921362655], [6.0, 20.13118223595458, 11.86881776404542], [6.0, 20.13118223595458, 20.131182235954576], [6.0, 20.13118223595458, 28.39354670786373], [7.0, 0.0, 0.0], [8.0, 0.0, 0.0], [9.0, 0.0, 0.0], [7.0, 0.0, 24.0], [8.0, 0.0, 24.0], [9.0, 0.0, 24.0], [10.0, 2.9360547051563817, -3.5959179422654266], [10.0, 2.9360547051563817, 9.468027352578192], [10.0, 2.9360547051563817, 22.53197264742181], [10.0, 16.0, -3.5959179422654266], [10.0, 16.0, 9.468027352578192], [10.0, 16.0, 22.53197264742181], [11.666666666666666, 2.9360547051563817, -3.5959179422654266], [11.666666666666666, 2.9360547051563817, 9.468027352578192], [11.666666666666666, 2.9360547051563817, 22.53197264742181], [11.666666666666666, 16.0, -3.5959179422654266], [11.666666666666666, 16.0, 9.468027352578192], [11.666666666666666, 16.0, 22.53197264742181], [18.333333333333336, 0.0, -2.931455305918771], [19.333333333333336, 0.0, -2.931455305918771], [20.333333333333336, 0.0, -2.931455305918771], [21.333333333333336, 0.0, -2.931455305918771], [18.333333333333336, 0.0, 22.310485101972922], [19.333333333333336, 0.0, 22.310485101972922], [20.333333333333336, 0.0, 22.310485101972922], [21.333333333333336, 0.0, 22.310485101972922], [18.333333333333336, 2.477531924343735, -2.931455305918771], [18.333333333333336, 2.477531924343735, 9.689514898027076], [18.333333333333336, 2.477531924343735, 22.310485101972922], [18.333333333333336, 16.0, -2.931455305918771], [18.333333333333336, 16.0, 9.689514898027076], [18.333333333333336, 16.0, 22.310485101972922], [20.000000000000004, 2.477531924343735, -2.931455305918771], [20.000000000000004, 2.477531924343735, 9.689514898027076], [20.000000000000004, 2.477531924343735, 22.310485101972922], [20.000000000000004, 16.0, -2.931455305918771], [20.000000000000004, 16.0, 9.689514898027076], [20.000000000000004, 16.0, 22.310485101972922], [26.66666666666667, 2.477531924343735, -2.931455305918771], [26.66666666666667, 2.477531924343735, 9.689514898027076], [26.66666666666667, 2.477531924343735, 22.310485101972922], [26.66666666666667, 16.0, -2.931455305918771], [26.66666666666667, 16.0, 9.689514898027076], [26.66666666666667, 16.0, 22.310485101972922], [33.333333333333336, 0.0, 0.0], [33.333333333333336, 0.0, 16.0], [33.333333333333336, 16.0, 0.0], [33.333333333333336, 16.0, 16.0], [34.333333333333336, 0.0, 0.0], [34.333333333333336, 0.0, 8.0], [34.333333333333336, 0.0, 16.0], [34.333333333333336, 0.0, 24.0], [34.333333333333336, 8.0, 0.0], [34.333333333333336, 8.0, 8.0], [34.333333333333336, 8.0, 16.0], [34.333333333333336, 8.0, 24.0], [34.333333333333336, 16.0, 0.0], [34.333333333333336, 16.0, 8.0], [34.333333333333336, 16.0, 16.0], [34.333333333333336, 16.0, 24.0], [34.333333333333336, 24.0, 0.0], [34.333333333333336, 24.0, 8.0], [34.333333333333336, 24.0, 16.0], [34.333333333333336, 24.0, 24.0], [36.0, 0.0, 0.0], [36.0, 0.0, 8.0], [36.0, 0.0, 16.0], [36.0, 0.0, 24.0], [36.0, 8.0, 0.0], [36.0, 8.0, 8.0], [36.0, 8.0, 16.0], [36.0, 8.0, 24.0], [36.0, 16.0, 0.0], [36.0, 16.0, 8.0], [36.0, 16.0, 16.0], [36.0, 16.0, 24.0], [36.0, 24.0, 0.0], [36.0, 24.0, 8.0], [36.0, 24.0, 16.0], [36.0, 24.0, 24.0]],
|
||||
"img_update": [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true],
|
||||
"audio_update": [false, false, false, false, false, false, false, false, false, false, false, false, false, false],
|
||||
"img_pos": [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100],
|
||||
"audio_pos": [21, 22, 23, 24, 25, 26, 39, 40, 41, 42, 43, 44, 45, 46]
|
||||
},
|
||||
"chain": {
|
||||
"text_len": 32,
|
||||
"latent_t": 7,
|
||||
"latent_h": 16,
|
||||
"latent_w": 24,
|
||||
"audio_t": 6,
|
||||
"keyframes": [{"frame": 0, "video_t": 1, "audio_t": 2}],
|
||||
"refs": [{"kind": "image", "latent_h": 8, "latent_w": 12, "latent_t": 0, "ref_audio_t": 0}, {"kind": "video_audio", "latent_h": 4, "latent_w": 6, "latent_t": 5, "ref_audio_t": 20}],
|
||||
"seq_len": 910,
|
||||
"segments": [[0, 32, "text"], [32, 128, "cond"], [128, 132, "cond_audio"], [132, 156, "ref_img"], [156, 196, "ref_audio"], [196, 226, "ref_img"], [226, 238, "audio"], [238, 910, "video"]],
|
||||
"positions": [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0], [3.0, 0.0, 0.0], [4.0, 0.0, 0.0], [5.0, 0.0, 0.0], [6.0, 0.0, 0.0], [7.0, 0.0, 0.0], [8.0, 0.0, 0.0], [9.0, 0.0, 0.0], [10.0, 0.0, 0.0], [11.0, 0.0, 0.0], [12.0, 0.0, 0.0], [13.0, 0.0, 0.0], [14.0, 0.0, 0.0], [15.0, 0.0, 0.0], [16.0, 0.0, 0.0], [17.0, 0.0, 0.0], [18.0, 0.0, 0.0], [19.0, 0.0, 0.0], [20.0, 0.0, 0.0], [21.0, 0.0, 0.0], [22.0, 0.0, 0.0], [23.0, 0.0, 0.0], [24.0, 0.0, 0.0], [25.0, 0.0, 0.0], [26.0, 0.0, 0.0], [27.0, 0.0, 0.0], [28.0, 0.0, 0.0], [29.0, 0.0, 0.0], [30.0, 0.0, 0.0], [31.0, 0.0, 0.0], [61.333333333333336, 2.9360547051563817, -3.5959179422654266], [61.333333333333336, 2.9360547051563817, -0.329931618554522], [61.333333333333336, 2.9360547051563817, 2.9360547051563826], [61.333333333333336, 2.9360547051563817, 6.202041028867287], [61.333333333333336, 2.9360547051563817, 9.468027352578192], [61.333333333333336, 2.9360547051563817, 12.734013676289095], [61.333333333333336, 2.9360547051563817, 16.0], [61.333333333333336, 2.9360547051563817, 19.265986323710905], [61.333333333333336, 2.9360547051563817, 22.53197264742181], [61.333333333333336, 2.9360547051563817, 25.797958971132715], [61.333333333333336, 2.9360547051563817, 29.063945294843617], [61.333333333333336, 2.9360547051563817, 32.329931618554525], [61.333333333333336, 6.202041028867287, -3.5959179422654266], [61.333333333333336, 6.202041028867287, -0.329931618554522], [61.333333333333336, 6.202041028867287, 2.9360547051563826], [61.333333333333336, 6.202041028867287, 6.202041028867287], [61.333333333333336, 6.202041028867287, 9.468027352578192], [61.333333333333336, 6.202041028867287, 12.734013676289095], [61.333333333333336, 6.202041028867287, 16.0], [61.333333333333336, 6.202041028867287, 19.265986323710905], [61.333333333333336, 6.202041028867287, 22.53197264742181], [61.333333333333336, 6.202041028867287, 25.797958971132715], [61.333333333333336, 6.202041028867287, 29.063945294843617], [61.333333333333336, 6.202041028867287, 32.329931618554525], [61.333333333333336, 9.46802735257819, -3.5959179422654266], [61.333333333333336, 9.46802735257819, -0.329931618554522], [61.333333333333336, 9.46802735257819, 2.9360547051563826], [61.333333333333336, 9.46802735257819, 6.202041028867287], [61.333333333333336, 9.46802735257819, 9.468027352578192], [61.333333333333336, 9.46802735257819, 12.734013676289095], [61.333333333333336, 9.46802735257819, 16.0], [61.333333333333336, 9.46802735257819, 19.265986323710905], [61.333333333333336, 9.46802735257819, 22.53197264742181], [61.333333333333336, 9.46802735257819, 25.797958971132715], [61.333333333333336, 9.46802735257819, 29.063945294843617], [61.333333333333336, 9.46802735257819, 32.329931618554525], [61.333333333333336, 12.734013676289095, -3.5959179422654266], [61.333333333333336, 12.734013676289095, -0.329931618554522], [61.333333333333336, 12.734013676289095, 2.9360547051563826], [61.333333333333336, 12.734013676289095, 6.202041028867287], [61.333333333333336, 12.734013676289095, 9.468027352578192], [61.333333333333336, 12.734013676289095, 12.734013676289095], [61.333333333333336, 12.734013676289095, 16.0], [61.333333333333336, 12.734013676289095, 19.265986323710905], [61.333333333333336, 12.734013676289095, 22.53197264742181], [61.333333333333336, 12.734013676289095, 25.797958971132715], [61.333333333333336, 12.734013676289095, 29.063945294843617], [61.333333333333336, 12.734013676289095, 32.329931618554525], [61.333333333333336, 16.0, -3.5959179422654266], [61.333333333333336, 16.0, -0.329931618554522], [61.333333333333336, 16.0, 2.9360547051563826], [61.333333333333336, 16.0, 6.202041028867287], [61.333333333333336, 16.0, 9.468027352578192], [61.333333333333336, 16.0, 12.734013676289095], [61.333333333333336, 16.0, 16.0], [61.333333333333336, 16.0, 19.265986323710905], [61.333333333333336, 16.0, 22.53197264742181], [61.333333333333336, 16.0, 25.797958971132715], [61.333333333333336, 16.0, 29.063945294843617], [61.333333333333336, 16.0, 32.329931618554525], [61.333333333333336, 19.265986323710905, -3.5959179422654266], [61.333333333333336, 19.265986323710905, -0.329931618554522], [61.333333333333336, 19.265986323710905, 2.9360547051563826], [61.333333333333336, 19.265986323710905, 6.202041028867287], [61.333333333333336, 19.265986323710905, 9.468027352578192], [61.333333333333336, 19.265986323710905, 12.734013676289095], [61.333333333333336, 19.265986323710905, 16.0], [61.333333333333336, 19.265986323710905, 19.265986323710905], [61.333333333333336, 19.265986323710905, 22.53197264742181], [61.333333333333336, 19.265986323710905, 25.797958971132715], [61.333333333333336, 19.265986323710905, 29.063945294843617], [61.333333333333336, 19.265986323710905, 32.329931618554525], [61.333333333333336, 22.53197264742181, -3.5959179422654266], [61.333333333333336, 22.53197264742181, -0.329931618554522], [61.333333333333336, 22.53197264742181, 2.9360547051563826], [61.333333333333336, 22.53197264742181, 6.202041028867287], [61.33333Line truncated
|
||||
"img_update": [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, trLine truncated
|
||||
"audio_update": [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true],
|
||||
"img_pos": [32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847, 848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 902, 903, 904, 905, 906, 907, 908, 909],
|
||||
"audio_pos": [128, 129, 130, 131, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237]
|
||||
},
|
||||
"no_text": {
|
||||
"text_len": 0,
|
||||
"latent_t": 2,
|
||||
"latent_h": 4,
|
||||
"latent_w": 6,
|
||||
"audio_t": 1,
|
||||
"keyframes": [],
|
||||
"refs": [],
|
||||
"seq_len": 14,
|
||||
"segments": [[0, 0, "text"], [0, 2, "audio"], [2, 14, "video"]],
|
||||
"positions": [[0.0, 0.0, -3.5959179422654266], [0.0, 0.0, 22.53197264742181], [0.0, 2.9360547051563817, -3.5959179422654266], [0.0, 2.9360547051563817, 9.468027352578192], [0.0, 2.9360547051563817, 22.53197264742181], [0.0, 16.0, -3.5959179422654266], [0.0, 16.0, 9.468027352578192], [0.0, 16.0, 22.53197264742181], [1.6666666666666667, 2.9360547051563817, -3.5959179422654266], [1.6666666666666667, 2.9360547051563817, 9.468027352578192], [1.6666666666666667, 2.9360547051563817, 22.53197264742181], [1.6666666666666667, 16.0, -3.5959179422654266], [1.6666666666666667, 16.0, 9.468027352578192], [1.6666666666666667, 16.0, 22.53197264742181]],
|
||||
"img_update": [true, true, true, true, true, true, true, true, true, true, true, true],
|
||||
"audio_update": [true, true],
|
||||
"img_pos": [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
|
||||
"audio_pos": [0, 1]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate tests/data/vae_geom/golden.json from the reference VAEs themselves.
|
||||
|
||||
As tests/data/ref2va/gen_golden.py does, the module source is AST-parsed and only the classes and
|
||||
helpers needed are extracted and run on torch alone, without importing the comfy package and the
|
||||
runtime it brings. Unlike the pack golden this one runs the networks on CPU, so the expectations
|
||||
are the encoders' own output shapes:
|
||||
|
||||
* the video encoder (EncoderFCN3D with the reference's constructor arguments) and the
|
||||
reference's own encode()/encode_temporal()/tiled_encode() methods bound to a stand-in self:
|
||||
the latent count of each frame count, and the moments' shape a tiled encode keeps;
|
||||
* the audio DAC encoder: the latent frames of a sweep of sample counts. Its posterior head
|
||||
(AttnProjection and a 1x1 mean_proj) has no strided op, so the encoder alone fixes the count.
|
||||
|
||||
Two stand-ins are needed: comfy.quant_ops must exist without `ck` (the fused-pad fast path then
|
||||
disables itself and the CPU path is plain torch), and Conv3d must take the reference's `autopad`
|
||||
keyword. On CPU its one use is the single-frame causal case, "causal_zero": kernel_t - 1 zero
|
||||
frames in front, which is what dropping the pad's taps comes to for a causal convolution.
|
||||
|
||||
Usage: python gen_golden.py <ComfyUI>/comfy/ldm/minimax/vae.py <...>/audio_vae.py golden.json
|
||||
"""
|
||||
import ast
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
import types
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
|
||||
def dump(v, f, ind=0):
|
||||
"""JSON with an object a key a line and every list on one line, so a golden diffs by key."""
|
||||
if isinstance(v, dict) and v:
|
||||
pad = " " * (ind + 1)
|
||||
items = list(v.items())
|
||||
f.write("{\n")
|
||||
for i, (k, x) in enumerate(items):
|
||||
f.write(pad + json.dumps(k) + ": ")
|
||||
dump(x, f, ind + 1)
|
||||
f.write(",\n" if i + 1 < len(items) else "\n")
|
||||
f.write(" " * ind + "}")
|
||||
else:
|
||||
f.write(json.dumps(v, separators=(", ", ": ")))
|
||||
|
||||
|
||||
torch.manual_seed(0)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- shims
|
||||
|
||||
class _Ops:
|
||||
class Conv3d(nn.Conv3d):
|
||||
def forward(self, x, autopad=None, **kw):
|
||||
if autopad == "causal_zero":
|
||||
k = self.kernel_size[0]
|
||||
x = F.pad(x, (0, 0, 0, 0, k - 1, 0))
|
||||
return super().forward(x)
|
||||
|
||||
Conv1d = nn.Conv1d
|
||||
ConvTranspose1d = nn.ConvTranspose1d
|
||||
GroupNorm = nn.GroupNorm
|
||||
LayerNorm = nn.LayerNorm
|
||||
Linear = nn.Linear
|
||||
|
||||
|
||||
class _QuantOps:
|
||||
pass
|
||||
|
||||
|
||||
def _cast_to_input(w, x):
|
||||
return w.to(device=x.device, dtype=x.dtype)
|
||||
|
||||
|
||||
class _ComfyOpsNs:
|
||||
"""what the extracted code reaches for as bare `comfy.ops.*`: cast_to_input is the real
|
||||
semantics (a plain device/dtype cast); the kitchen fast paths are never reached on CPU, so
|
||||
placeholders are enough there"""
|
||||
cast_bias_weight = None
|
||||
uncast_bias_weight = None
|
||||
cast_to_input = staticmethod(_cast_to_input)
|
||||
|
||||
|
||||
comfy = types.ModuleType("comfy")
|
||||
comfy.quant_ops = _QuantOps()
|
||||
comfy.ops = _ComfyOpsNs()
|
||||
ops = _Ops
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- extract
|
||||
|
||||
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
|
||||
|
||||
|
||||
def class_methods(path, cls_name, method_names):
|
||||
src = open(path).read()
|
||||
tree = ast.parse(src)
|
||||
for node in tree.body:
|
||||
if isinstance(node, ast.ClassDef) and node.name == cls_name:
|
||||
found = {m.name: ast.get_source_segment(src, m) for m in node.body
|
||||
if isinstance(m, ast.FunctionDef) and m.name in method_names}
|
||||
missing = set(method_names) - set(found)
|
||||
if missing:
|
||||
raise SystemExit(f"{cls_name} methods not found: {sorted(missing)}")
|
||||
return found
|
||||
raise SystemExit(f"class {cls_name} not found in {path}")
|
||||
|
||||
|
||||
ns = dict(torch=torch, nn=nn, F=F, math=math, comfy=comfy, ops=ops)
|
||||
|
||||
# --- video: the encoder chain classes + module constants
|
||||
VIDEO_NEED = [
|
||||
"IMAGENET_MEAN", "IMAGENET_STD", "LATENTS_MEAN", "LATENTS_STD",
|
||||
"_kitchen_ndhwc", "_fused_norm_pad", "_fp16_accum_conv",
|
||||
"CausalConv3d", "TemporalIsolatedGroupNorm", "group_norm_3d",
|
||||
"Downsample3D", "ResnetBlock3D", "EncoderFCN3D",
|
||||
]
|
||||
_vsrc = top_level(sys.argv[1], VIDEO_NEED)
|
||||
for name in VIDEO_NEED:
|
||||
exec(_vsrc[name], ns)
|
||||
|
||||
# --- video: the wrapper methods, bound to a shim self (no decoder, no checkpoint)
|
||||
VIDEO_METHODS = ["_encode_moments", "_normalize_pixels", "split_tiles", "blend",
|
||||
"tiled_encode", "_adaptive_encode", "encode_temporal", "encode"]
|
||||
mns = dict(ns)
|
||||
for name, code in class_methods(sys.argv[1], "MiniMaxH3VideoVAE", VIDEO_METHODS).items():
|
||||
exec(code, mns)
|
||||
|
||||
|
||||
def make_video_vae():
|
||||
self = types.SimpleNamespace()
|
||||
self.vae_ratio = 16
|
||||
self.vae_ratio_t = 8
|
||||
self.clip_length = 17
|
||||
self.token_drop = 3
|
||||
self.tile_size = 256
|
||||
self.tile_overlap_min = 64
|
||||
self.tiling = True
|
||||
self.encoder = ns["EncoderFCN3D"](
|
||||
ch=128, ch_mult=[1, 2, 2, 4, 4, 8], space_down=[2, 2, 2, 2, 1, 1],
|
||||
time_down=[1, 2, 2, 1, 1, 1], num_res_blocks=2, in_channels=3, z_channels=24,
|
||||
double_z=True)
|
||||
self.quant_conv = nn.Conv3d(48, 48, 1)
|
||||
self.latents_mean = torch.tensor(ns["LATENTS_MEAN"])
|
||||
self.latents_std = torch.tensor(ns["LATENTS_STD"])
|
||||
self.pixel_mean = torch.tensor(ns["IMAGENET_MEAN"]).view(1, 3, 1, 1, 1)
|
||||
self.pixel_std = torch.tensor(ns["IMAGENET_STD"]).view(1, 3, 1, 1, 1)
|
||||
for name in VIDEO_METHODS:
|
||||
setattr(self, name, types.MethodType(mns[name], self))
|
||||
return self
|
||||
|
||||
|
||||
golden = {"video": {}, "audio": {}}
|
||||
golden["video"]["constants"] = {
|
||||
"latents_mean": list(ns["LATENTS_MEAN"]), "latents_std": list(ns["LATENTS_STD"]),
|
||||
"pixel_mean": list(ns["IMAGENET_MEAN"]), "pixel_std": list(ns["IMAGENET_STD"]),
|
||||
}
|
||||
|
||||
vae = make_video_vae()
|
||||
|
||||
# --- 1. latent count per frame count, from the reference encode() end to end
|
||||
FRAME_COUNTS = [1, 2, 3, 5, 8, 16, 17, 18, 22, 34, 39, 40, 56, 72, 73, 90]
|
||||
cases = []
|
||||
with torch.no_grad():
|
||||
for t in FRAME_COUNTS:
|
||||
x = torch.zeros(1, 3, t, 32, 32)
|
||||
z = vae.encode(x)
|
||||
cases.append({"T": t, "z_shape": list(z.shape)})
|
||||
print(f"video encode T={t:3d} -> z {list(z.shape)}", file=sys.stderr)
|
||||
golden["video"]["encode"] = cases
|
||||
|
||||
# --- 2. the tile grid end to end: the blend/cut keeps the moments at exactly ratio-reduced size
|
||||
with torch.no_grad():
|
||||
tiled = []
|
||||
for x_shape in [(1, 3, 5, 320, 320), (1, 3, 2, 512, 256), (1, 3, 17, 288, 192)]:
|
||||
moments = vae.tiled_encode(torch.zeros(*x_shape))
|
||||
tiled.append({"x_shape": list(x_shape), "moments_shape": list(moments.shape)})
|
||||
print(f"video tiled {list(x_shape)} -> moments {list(moments.shape)}", file=sys.stderr)
|
||||
golden["video"]["tiled_encode"] = tiled
|
||||
|
||||
# --- 3. audio DAC encoder: latent frames for a sweep of (padded) sample counts
|
||||
AUDIO_NEED = ["snake", "Snake1d", "ResidualUnit", "EncoderBlock", "Encoder"]
|
||||
ans = dict(torch=torch, nn=nn, F=F, math=math, comfy=comfy, ops=ops)
|
||||
for name in AUDIO_NEED:
|
||||
exec(top_level(sys.argv[2], [name])[name], ans)
|
||||
with torch.no_grad():
|
||||
enc = ans["Encoder"](64, (2, 4, 4, 5, 5), 2048)
|
||||
samples_cases = []
|
||||
for s in [1, 2, 400, 799, 800, 801, 1599, 1600, 1601, 4000, 32000, 32001, 96000]:
|
||||
hop = 800
|
||||
padded = math.ceil(s / hop) * hop
|
||||
out = enc(torch.zeros(2, 1, padded)) # b*s = 2 stereo streams, mono encoder
|
||||
samples_cases.append({"samples": s, "padded": padded, "T": out.shape[2]})
|
||||
print(f"audio encode {s:6d} (pad {padded}) -> T {out.shape[2]}", file=sys.stderr)
|
||||
golden["audio"]["latents"] = samples_cases
|
||||
|
||||
with open(sys.argv[3], "w") as f:
|
||||
dump(golden, f)
|
||||
f.write("\n")
|
||||
print(f"wrote {sys.argv[3]}", file=sys.stderr)
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"video": {
|
||||
"constants": {
|
||||
"latents_mean": [0.858090341091156, -0.9606591463088989, 1.0661640167236328, -0.5090325474739075, -0.2727581858634949, -1.3675414323806763, -0.2553254961967468, -0.26907554268836975, -0.5376840829849243, -0.0464097298681736, 0.6657370328903198, 0.19690127670764923, -0.5460608005523682, -0.4035342037677765, -0.23683024942874908, 0.25928452610969543, -0.30133944749832153, 0.211341992020607, -1.1206848621368408, 0.3581933379173279, -0.04225143790245056, 0.2604829967021942, 0.22864092886447906, 0.7056031823158264],
|
||||
"latents_std": [1.2223774194717407, 1.2767263650894165, 1.6831774711608887, 1.7549455165863037, 1.5636216402053833, 2.194143533706665, 0.9653137922286987, 1.0569885969161987, 0.841948926448822, 0.7729952931404114, 1.8955937623977661, 0.946841835975647, 0.7996809482574463, 0.44988900423049927, 0.7197399735450745, 0.6936293244361877, 2.961095094680786, 2.7694199085235596, 3.0496184825897217, 2.1088054180145264, 3.276226282119751, 3.1627357006073, 2.2816812992095947, 2.6127843856811523],
|
||||
"pixel_mean": [0.485, 0.456, 0.406],
|
||||
"pixel_std": [0.229, 0.224, 0.225]
|
||||
},
|
||||
"encode": [{"T": 1, "z_shape": [1, 24, 1, 2, 2]}, {"T": 2, "z_shape": [1, 24, 2, 2, 2]}, {"T": 3, "z_shape": [1, 24, 2, 2, 2]}, {"T": 5, "z_shape": [1, 24, 2, 2, 2]}, {"T": 8, "z_shape": [1, 24, 2, 2, 2]}, {"T": 16, "z_shape": [1, 24, 2, 2, 2]}, {"T": 17, "z_shape": [1, 24, 2, 2, 2]}, {"T": 18, "z_shape": [1, 24, 7, 2, 2]}, {"T": 22, "z_shape": [1, 24, 7, 2, 2]}, {"T": 34, "z_shape": [1, 24, 7, 2, 2]}, {"T": 39, "z_shape": [1, 24, 12, 2, 2]}, {"T": 40, "z_shape": [1, 24, 12, 2, 2]}, {"T": 56, "z_shape": [1, 24, 17, 2, 2]}, {"T": 72, "z_shape": [1, 24, 22, 2, 2]}, {"T": 73, "z_shape": [1, 24, 22, 2, 2]}, {"T": 90, "z_shape": [1, 24, 27, 2, 2]}],
|
||||
"tiled_encode": [{"x_shape": [1, 3, 5, 320, 320], "moments_shape": [1, 48, 2, 20, 20]}, {"x_shape": [1, 3, 2, 512, 256], "moments_shape": [1, 48, 1, 32, 16]}, {"x_shape": [1, 3, 17, 288, 192], "moments_shape": [1, 48, 5, 18, 12]}]
|
||||
},
|
||||
"audio": {
|
||||
"latents": [{"samples": 1, "padded": 800, "T": 1}, {"samples": 2, "padded": 800, "T": 1}, {"samples": 400, "padded": 800, "T": 1}, {"samples": 799, "padded": 800, "T": 1}, {"samples": 800, "padded": 800, "T": 1}, {"samples": 801, "padded": 1600, "T": 2}, {"samples": 1599, "padded": 1600, "T": 2}, {"samples": 1600, "padded": 1600, "T": 2}, {"samples": 1601, "padded": 2400, "T": 3}, {"samples": 4000, "padded": 4000, "T": 5}, {"samples": 32000, "padded": 32000, "T": 40}, {"samples": 32001, "padded": 32800, "T": 41}, {"samples": 96000, "padded": 96000, "T": 120}]
|
||||
}
|
||||
}
|
||||
@@ -1898,7 +1898,7 @@ TEST(decoding_without_a_drafter_issues_steps_ahead) {
|
||||
|
||||
/* The step that emits a request's last token issues nothing behind it: a step issued ahead for a
|
||||
* request the commit then finishes verifies nothing, and the next request would wait out its
|
||||
* forward pass (#225). A reply of 32 tokens is the prefill's token and 31 decode steps, each
|
||||
* forward pass. A reply of 32 tokens is the prefill's token and 31 decode steps, each
|
||||
* issued ahead of the one before it, and no 32nd. Twice, so the second request starts behind the
|
||||
* first's last step. */
|
||||
TEST(a_requests_last_step_issues_no_step_ahead) {
|
||||
|
||||
+192
-3
@@ -1611,9 +1611,11 @@ TEST(glm53_is_the_pinned_graph_and_steps) {
|
||||
uint64_t graph, steps;
|
||||
bool heads_only = false; /* the default: the graph before the row form */
|
||||
};
|
||||
const Case cases[] = { { 1, 0x906897570034f5f5ull, 0x68ffc03d2b640d51ull },
|
||||
{ 8, 0x1d378152c40f8834ull, 0x82ed1094dbf4b637ull },
|
||||
{ 8, 0x9f39f6f7a04dc4d3ull, 0x3818eedb4ac10d1bull, true } };
|
||||
/* Pins from this test's own `pin:` printout: the head form (heads_only, which declares the
|
||||
* streamed ops) and the row form, at one and eight ranks. */
|
||||
const Case cases[] = { { 1, 0x8e12725b3ed3548dull, 0x68ffc03d2b640d51ull },
|
||||
{ 8, 0xe4ba21765f690f70ull, 0x82ed1094dbf4b637ull },
|
||||
{ 8, 0xf404ab12440b389full, 0x3818eedb4ac10d1bull, true } };
|
||||
for (const Case& cs : cases) {
|
||||
RadBuilder b;
|
||||
b.kv_block = 4;
|
||||
@@ -2020,6 +2022,193 @@ TEST(glm53_sizing_declares_with_the_vision_tower_match_the_real_graph) {
|
||||
}
|
||||
}
|
||||
|
||||
TEST(glm53_declaring_without_streamed_ops_ignores_the_flag) {
|
||||
const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts",
|
||||
"index_topk" };
|
||||
const char* vals[] = { "1", "4", "288", "2048" };
|
||||
RadModelMeta meta{};
|
||||
meta.n_layers = 45;
|
||||
meta.n_embd = 4096;
|
||||
meta.n_vocab = 154880;
|
||||
meta.rms_eps = 1e-5f;
|
||||
meta.n_kv = 4;
|
||||
meta.kv_key = keys;
|
||||
meta.kv_val = vals;
|
||||
const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32);
|
||||
const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128);
|
||||
RadBuilder b;
|
||||
b.kv_block = 4;
|
||||
b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, { "mtp.blk.45.ffn_down_exps", fp8 },
|
||||
{ "ffn_gate_up_exps", mx }, { "ffn_down_exps", mx },
|
||||
{ "ffn_gate_up_shexp", mx }, { "ffn_down_shexp", mx },
|
||||
{ "ffn_gate_up.weight", fp8 }, { "ffn_down.weight", fp8 } };
|
||||
b.undeclared = { "kv_resolve", "kv_store_streamed" };
|
||||
RadBuildCtx build{};
|
||||
build.rank = 0;
|
||||
build.world_size = 1;
|
||||
build.max_tok = 512;
|
||||
build.max_seqs = 2;
|
||||
build.max_ctx = 4096;
|
||||
build.max_spec = 0;
|
||||
build.kv_resident_blocks = 32768; /* the ring floor: 8 192 blocks. This fixture toggles the ops,
|
||||
* not the ring; the undeclared list is the gate it tests. */
|
||||
REQUIRE_EQ(glm5next::declare(&b, &meta, &build), RAD_OK);
|
||||
CHECK_EQ(count_op(b, "kv_resolve"), 0);
|
||||
CHECK_EQ(count_op(b, "kv_store_streamed"), 0);
|
||||
/* The base store is still there: the zeros are the gate, not a layer that never stores. */
|
||||
CHECK(count_op(b, "kv_store") > 0);
|
||||
}
|
||||
|
||||
TEST(glm53_streamed_decode_resolves_after_select_and_before_attention_with_the_entry_count) {
|
||||
const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts",
|
||||
"index_topk" };
|
||||
const char* vals[] = { "1", "4", "288", "2048" };
|
||||
RadModelMeta meta{};
|
||||
meta.n_layers = 45;
|
||||
meta.n_embd = 4096;
|
||||
meta.n_vocab = 154880;
|
||||
meta.rms_eps = 1e-5f;
|
||||
meta.n_kv = 4;
|
||||
meta.kv_key = keys;
|
||||
meta.kv_val = vals;
|
||||
const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32);
|
||||
const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128);
|
||||
RadBuilder b;
|
||||
b.kv_block = 4;
|
||||
b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, { "mtp.blk.45.ffn_down_exps", fp8 },
|
||||
{ "ffn_gate_up_exps", mx }, { "ffn_down_exps", mx },
|
||||
{ "ffn_gate_up_shexp", mx }, { "ffn_down_shexp", mx },
|
||||
{ "ffn_gate_up.weight", fp8 }, { "ffn_down.weight", fp8 } };
|
||||
RadBuildCtx build{};
|
||||
build.rank = 0;
|
||||
build.world_size = 1;
|
||||
build.max_tok = 512;
|
||||
build.max_seqs = 2;
|
||||
build.max_ctx = 4096;
|
||||
build.max_spec = 3; /* so the drafter's layer 45 is the twelfth full layer */
|
||||
build.kv_resident_blocks = 32768; /* the ring floor, 8 192 blocks: above this fixture's spec-3
|
||||
* raise of 2 x 4 x 513 = 4 104 blocks, so the engine raises
|
||||
* nothing. The declared slots are the context's 2048 blocks
|
||||
* either way, which is what the fake stream mirrors. */
|
||||
REQUIRE_EQ(glm5next::declare(&b, &meta, &build), RAD_OK);
|
||||
const auto& m = *glm5next::models[0];
|
||||
REQUIRE_EQ(m.latent, (rad_kvgroup)1);
|
||||
REQUIRE_EQ(count_op(b, "kv_resolve"), 12);
|
||||
|
||||
/* A zeroed stream with the figures bring-up fixes: 4096 B a block (12 layers of 2 x 4 x
|
||||
* 256 x bf16), a 2048-block mirror, and the ring the declaration states -- the context's
|
||||
* 2048 blocks, because a 32 768-token ring is clamped to `blocks` for this 4096-token
|
||||
* context. Only the latent group streams. */
|
||||
const int64_t blocks = 2048, slots = 2048;
|
||||
std::vector<uint8_t> host((size_t)blocks * 4096);
|
||||
std::vector<int32_t> res(blocks), slot_block(slots), slot_state(slots * 2), ctl(16);
|
||||
RadKVStream st{};
|
||||
st.host = host.data();
|
||||
st.res = res.data();
|
||||
st.slot_block = slot_block.data();
|
||||
st.slot_state = slot_state.data();
|
||||
st.ctl = ctl.data();
|
||||
st.block_bytes = 4096;
|
||||
st.host_layer_stride = 4096 * blocks;
|
||||
st.slots = slots;
|
||||
st.host_bytes = (int64_t)host.size() * 12;
|
||||
|
||||
int32_t cu[] = { 0, 1, 2 }, positions[] = { 0, 1 }, ctxlens[] = { 1, 1 },
|
||||
ids[] = { 7, 9 }, slots_map[] = { 0, 1 }, out[] = { 1 };
|
||||
int32_t sidx[] = { 0, 0, 0, 1, 1, 1 }, ci[] = { 0 }, tables[64]{};
|
||||
std::vector<RadKVGroupBatch> kv(b.kv_groups.size());
|
||||
for (size_t i = 0; i < kv.size(); ++i) {
|
||||
kv[i].group = (rad_kvgroup)i + 1;
|
||||
kv[i].slot_mapping = slots_map;
|
||||
kv[i].block_table = tables;
|
||||
kv[i].block_table_pitch = 32;
|
||||
kv[i].state_index = b.kv_groups[i].d.kind == RAD_KV_CONV ? ci : sidx;
|
||||
kv[i].state_index_pitch = b.kv_groups[i].d.kind == RAD_KV_CONV ? 1 : 6;
|
||||
}
|
||||
kv[m.latent - 1].stream = &st;
|
||||
|
||||
RadBatch batch{};
|
||||
batch.phase = RAD_PHASE_DECODE;
|
||||
batch.n_tok = 2;
|
||||
batch.n_seq = 2;
|
||||
batch.token_ids = ids;
|
||||
batch.positions = positions;
|
||||
batch.cu_seqlens = cu;
|
||||
batch.ctx_lens = ctxlens;
|
||||
batch.kv = kv.data();
|
||||
batch.n_kv_groups = (int)kv.size();
|
||||
batch.n_out = 1;
|
||||
batch.out_ids = out;
|
||||
batch.max_ctx_len = 1;
|
||||
batch.max_q_len = 1;
|
||||
RadCtx ctx;
|
||||
ctx.b = &b;
|
||||
ctx.rank = 0;
|
||||
ctx.world = 1;
|
||||
ctx.batch = &batch;
|
||||
|
||||
auto resolve_count = [&] {
|
||||
int n = 0;
|
||||
for (const auto& issue : ctx.issues)
|
||||
if (issue.op >= 1 && (size_t)issue.op <= b.ops.size() &&
|
||||
b.ops[issue.op - 1].op == "kv_resolve")
|
||||
++n;
|
||||
return n;
|
||||
};
|
||||
auto find_issue = [&](rad_op op) -> size_t {
|
||||
for (size_t i = 0; i < ctx.issues.size(); ++i)
|
||||
if (ctx.issues[i].op == op) return i;
|
||||
return SIZE_MAX;
|
||||
};
|
||||
auto check_layer_order = [&](const glm5next::Layer& l) {
|
||||
const size_t store = find_issue(l.mla.op_store_stream);
|
||||
const size_t sel = find_issue(l.index.cache.op_select);
|
||||
const size_t res_i = find_issue(l.mla.op_resolve);
|
||||
const size_t attn = find_issue(l.mla.core.op_attn);
|
||||
REQUIRE(store != SIZE_MAX);
|
||||
REQUIRE(sel != SIZE_MAX);
|
||||
REQUIRE(res_i != SIZE_MAX);
|
||||
REQUIRE(attn != SIZE_MAX);
|
||||
CHECK(store < sel);
|
||||
CHECK(sel < res_i);
|
||||
CHECK(res_i < attn);
|
||||
/* §2: the count is `selected_count`, never the token count. */
|
||||
CHECK_EQ(ctx.issues[res_i].opd[1].handle, m.aw.core.nsel);
|
||||
CHECK(ctx.issues[res_i].opd[1].handle != m.aw.core.length);
|
||||
CHECK_EQ(ctx.issues[res_i].n, (int64_t)2);
|
||||
};
|
||||
|
||||
/* A decode pass: 11 trunk full layers resolve, and the draft layer does too. */
|
||||
glm5next::step(&ctx, &batch);
|
||||
CHECK(ctx.step_fail.empty());
|
||||
CHECK_EQ(resolve_count(), 11);
|
||||
for (const auto& l : m.layers)
|
||||
if (l.full) check_layer_order(l);
|
||||
|
||||
ctx.issues.clear();
|
||||
batch.draft_pass = 2;
|
||||
glm5next::step(&ctx, &batch);
|
||||
CHECK(ctx.step_fail.empty());
|
||||
CHECK_EQ(resolve_count(), 1);
|
||||
check_layer_order(m.draft);
|
||||
|
||||
/* A staged pass (prefill, or the stage view chosen for it) must not resolve: the selection
|
||||
* keeps the block ids the identity stage addresses directly. */
|
||||
ctx.issues.clear();
|
||||
ctx.stages.clear();
|
||||
ctx.stage_on = true;
|
||||
batch.draft_pass = 0;
|
||||
batch.phase = RAD_PHASE_PREFILL;
|
||||
batch.n_tok = 4;
|
||||
int32_t cu4[] = { 0, 2, 4 };
|
||||
batch.cu_seqlens = cu4;
|
||||
batch.max_q_len = 2;
|
||||
glm5next::step(&ctx, &batch);
|
||||
CHECK(ctx.step_fail.empty());
|
||||
CHECK_EQ(resolve_count(), 0);
|
||||
CHECK(!ctx.stages.empty());
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
|
||||
/* ==================================================================== the row rule */
|
||||
|
||||
@@ -7,6 +7,9 @@
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "mem/kv.h"
|
||||
#include "kvstream/bringup.h"
|
||||
#include "kvstream/bind.h"
|
||||
#include "kvstream/plan.h"
|
||||
#include "mem/pools.h"
|
||||
#include "mem/prefix.h"
|
||||
#include "mem/vram_budget.h"
|
||||
@@ -116,6 +119,45 @@ struct Fixture {
|
||||
}
|
||||
};
|
||||
|
||||
/* The streamed path a plugin declares for `g`, as the builder records it: a kv_resolve stating the
|
||||
* group's per-layer block pitch and selection pitch, and a kv_store_streamed stating its page.
|
||||
* `with_resolve`/`with_store` build a model that declares one or neither (as the DSA-index models
|
||||
* do). `store_resolved` false is the packed-cache shape: the store declared with no kernel row, so
|
||||
* the builder keeps it with one band and both domains null. */
|
||||
static KernelRow& a_resolved_row() {
|
||||
/* Static, as a plugin table's rows are: a Resolved points at one. Nothing in this test issues
|
||||
* the op, so the row carries no kernel. */
|
||||
static KernelRow row;
|
||||
return row;
|
||||
}
|
||||
|
||||
static Program stream_program(const KVGroupInfo& g, int64_t sel_pitch, bool with_resolve = true,
|
||||
bool with_store = true, bool store_resolved = true) {
|
||||
Program p;
|
||||
p.meta.arch_id = "test-arch";
|
||||
const int64_t n_bound = g.layers.empty() ? 1 : (int64_t)g.layers.size();
|
||||
const int64_t layer_bytes = g.bytes_per_block > 0 ? g.bytes_per_block / n_bound : 0;
|
||||
if (with_resolve) {
|
||||
OpInfo oi;
|
||||
oi.op = "kv_resolve";
|
||||
oi.bands.resize(1); /* resolved: the builder records one band per domain */
|
||||
oi.bands[0].dom[RAD_DOMAIN_DEVICE].row = &a_resolved_row();
|
||||
oi.base.set_i("block_bytes", layer_bytes);
|
||||
oi.base.set_i("sel_pitch", sel_pitch);
|
||||
p.ops.push_back(std::move(oi));
|
||||
}
|
||||
if (with_store) {
|
||||
OpInfo oi;
|
||||
oi.op = "kv_store_streamed";
|
||||
oi.bands.resize(1);
|
||||
if (store_resolved) oi.bands[0].dom[RAD_DOMAIN_DEVICE].row = &a_resolved_row();
|
||||
else oi.bands[0].miss[RAD_DOMAIN_DEVICE] = "kv_dtype in {fp8_e4m3}, have fp8_v4";
|
||||
oi.base.set_i("block_size", g.block_size);
|
||||
p.ops.push_back(std::move(oi));
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
static std::vector<int32_t> tok_run(int32_t base, int n) {
|
||||
std::vector<int32_t> v;
|
||||
for (int i = 0; i < n; ++i) v.push_back(base + i);
|
||||
@@ -776,6 +818,54 @@ static KVGroupInfo paged_group(const char* name, int kind, int64_t heads, int64_
|
||||
return k;
|
||||
}
|
||||
|
||||
/* The streamed group is the widest full group with a declared streamed path, never a dense-read
|
||||
* one. GLM-5.3's two full groups show the difference: kv_latent (49 152 B a block) streams;
|
||||
* kv_dsa_index (1 632 B) is read over the whole history every step and stays resident. */
|
||||
TEST(kv_stream_group_picks_a_wired_full_group_not_merely_the_widest) {
|
||||
std::vector<KVGroupInfo> g;
|
||||
g.push_back(null_group());
|
||||
const std::vector<int32_t> full_layers = { 3, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43, 45 };
|
||||
KVGroupInfo latent = paged_group("kv_latent", RAD_KV_FULL, 1, 4, full_layers);
|
||||
latent.decl.dtype = RAD_BF16;
|
||||
latent.decl.head_dim = 256;
|
||||
latent.bytes_per_block = 49152; /* 12 layers x 4 tokens x 256 x bf16 */
|
||||
KVGroupInfo index = paged_group("kv_dsa_index", RAD_KV_FULL, 1, 4, full_layers);
|
||||
index.decl.dtype = RAD_U8;
|
||||
index.decl.head_dim = 17;
|
||||
index.bytes_per_block = 1632; /* 12 layers x 4 tokens x 17 x u8 */
|
||||
g.push_back(latent);
|
||||
g.push_back(index);
|
||||
|
||||
auto check_pick = [&](const Program& p, int32_t want) {
|
||||
Program prog = p;
|
||||
prog.kv_groups = g; /* index-aligned, as Engine's program is */
|
||||
CHECK_EQ(kv_stream_group(g, &prog), want);
|
||||
/* The cap probe and the carve must agree, so the plans overload takes the same rule. */
|
||||
Fixture f;
|
||||
f.cfg.checkpoint_slots = 0;
|
||||
f.cfg.max_ctx = 4096;
|
||||
f.cfg.max_seqs = 2;
|
||||
CHECK_OK(f.kv.plan_groups(g, f.cfg));
|
||||
CHECK_EQ(kv_stream_group(f.kv, &prog), want);
|
||||
};
|
||||
|
||||
/* Wired latent, narrower: it is picked. */
|
||||
check_pick(stream_program(g[1], 513), 1);
|
||||
/* The index group made wider is still not picked: it is not wired. This is the width
|
||||
* coincidence the rule removes. */
|
||||
g[2].bytes_per_block = 65536;
|
||||
check_pick(stream_program(g[1], 513), 1);
|
||||
g[2].bytes_per_block = 1632;
|
||||
/* A resolve that states the index group's pitch (136 B a layer) is the only wired path, so
|
||||
* the narrower group is the one that streams. */
|
||||
check_pick(stream_program(g[2], 513), 2);
|
||||
/* A dense-read group is never a candidate, even when its own path is declared. Nothing else
|
||||
* is wired here, so nothing streams. */
|
||||
g[2].dense_read = true;
|
||||
check_pick(stream_program(g[2], 513), -1);
|
||||
g[2].dense_read = false;
|
||||
}
|
||||
|
||||
/* A windowed group is capped at its window on both ranks, and the cap shifts the freed bytes to
|
||||
* the other groups, a kink in paged_split the inverse must cross exactly. The dear rank's count is
|
||||
* past the window, so the window group holds max_seqs x window_blocks on both ranks. */
|
||||
@@ -846,6 +936,668 @@ TEST(an_uneven_worlds_cheaper_rank_gives_its_saved_kv_to_its_weights_up_to_all_r
|
||||
CHECK_EQ(s.kv_mib, (int64_t)800);
|
||||
}
|
||||
|
||||
TEST(a_streamed_group_is_refused_at_carve_without_its_host_copy) {
|
||||
/* A streamed plan is refused unless something holds the blocks the pool does not back: a store
|
||||
* for block 40 of a four-block pool would write past the layer stride. Each variant removes
|
||||
* one of the three pieces the carve requires. */
|
||||
for (int variant = 0; variant < 3; ++variant) {
|
||||
Fixture f;
|
||||
f.cfg.checkpoint_slots = 0;
|
||||
f.cfg.max_ctx = 1024; /* the context the group will address, in host RAM */
|
||||
CHECK_OK(configure_pools(f.pools, f.cfg));
|
||||
f.kv.cap_resident_tokens(G_FULL, 64);
|
||||
CHECK_OK(f.kv.plan_groups(hybrid_groups(), f.cfg));
|
||||
/* How many blocks the group has is decided at carve; the host copy has to be there first,
|
||||
* so size it from the context the carve will compute: every sequence at full length. */
|
||||
const int64_t ctx_blocks = f.cfg.max_seqs * (f.cfg.max_ctx / 16);
|
||||
const int64_t page = f.kv.plan(G_FULL)->bytes_per_block;
|
||||
const int64_t need = ctx_blocks * page;
|
||||
std::vector<char> host((size_t)need, 0);
|
||||
std::vector<int32_t> res((size_t)ctx_blocks, -1);
|
||||
|
||||
KVManager::StreamMap m;
|
||||
m.host = variant == 0 ? nullptr : (uint8_t*)host.data(); /* 0: no copy at all */
|
||||
m.host_bytes = variant == 1 ? need - 1 : need; /* 1: a copy too small */
|
||||
m.res = variant == 2 ? nullptr : res.data(); /* 2: no map */
|
||||
f.kv.set_stream_map(G_FULL, m);
|
||||
CHECK_EQ(f.kv.carve(f.pools.kv()), RAD_E_INVAL);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(a_streamed_group_addresses_its_context_but_backs_only_the_resident_window) {
|
||||
/* A streamed group allocates block ids over its whole context while the pool backs only
|
||||
* --kv-resident of them. This pins the places that multiply by one of the two numbers: the
|
||||
* carve, the layer stride, the kernel's operand shape and the loan. A mistake there writes one
|
||||
* layer's block into the next. The split is decided at carve, which knows the budget. */
|
||||
Fixture f;
|
||||
f.cfg.checkpoint_slots = 0;
|
||||
f.cfg.max_ctx = 1024; /* the context the group addresses */
|
||||
CHECK_OK(configure_pools(f.pools, f.cfg));
|
||||
f.kv.cap_resident_tokens(G_FULL, 64); /* four blocks of 16 tokens */
|
||||
CHECK_OK(f.kv.plan_groups(hybrid_groups(), f.cfg));
|
||||
|
||||
/* Both numbers come from the carve: the context from --max-model-len and --max-num-seqs, the
|
||||
* window from --kv-resident. The host copy must already cover the context. */
|
||||
const int64_t ctx_blocks = f.cfg.max_seqs * (f.cfg.max_ctx / 16);
|
||||
const int64_t page = f.kv.plan(G_FULL)->bytes_per_block;
|
||||
CHECK(ctx_blocks > 4); /* the pool holds more than the window */
|
||||
std::vector<char> host((size_t)(ctx_blocks * page), 0);
|
||||
std::vector<int32_t> res((size_t)ctx_blocks, -1);
|
||||
KVManager::StreamMap sm_in;
|
||||
sm_in.host = (uint8_t*)host.data();
|
||||
sm_in.res = res.data();
|
||||
sm_in.host_bytes = (int64_t)host.size();
|
||||
f.kv.set_stream_map(G_FULL, sm_in);
|
||||
const KVManager::StreamMap* sm = f.kv.stream_map(G_FULL);
|
||||
CHECK(sm != nullptr && sm->host == (uint8_t*)host.data() && sm->res == res.data() &&
|
||||
sm->host_bytes >= ctx_blocks * page);
|
||||
CHECK_OK(f.kv.carve(f.pools.kv()));
|
||||
|
||||
const KVGroupPlan* p = f.kv.plan(G_FULL);
|
||||
CHECK_EQ(p->n_blocks, ctx_blocks);
|
||||
CHECK_EQ(p->n_slots, 4);
|
||||
CHECK(p->streamed());
|
||||
CHECK_EQ(p->pool_blocks(), 4);
|
||||
CHECK_EQ(p->layer_stride(), 4 * p->layer_bytes_per_block());
|
||||
/* The carve is one reservation of max(ring, stage): the ring's four blocks of every layer, or
|
||||
* the whole context one layer deep. Here the context's one layer is the larger, so the pool is
|
||||
* a stage and the ring fits inside it (docs/KV-STREAMING.md §4.1). */
|
||||
CHECK_EQ(f.kv.pool_bytes_carved(G_FULL),
|
||||
std::max(4 * page, ctx_blocks * p->layer_bytes_per_block()));
|
||||
CHECK_EQ(rad::kv_ceiling_bytes(*p, ctx_blocks, 4), ctx_blocks * p->layer_bytes_per_block());
|
||||
/* The startup report must not read as a pool that holds the whole context. */
|
||||
CHECK(f.kv.report().find("streaming:") != std::string::npos);
|
||||
|
||||
/* Not lendable: the window is what a residency map reads, and a block lent to the expert slab
|
||||
* is one the attention has nowhere to put. */
|
||||
CHECK(!f.kv.lendable(G_FULL));
|
||||
/* The linear group next to it is untouched. */
|
||||
CHECK_EQ(f.kv.plan(G_GDN)->n_slots, 0);
|
||||
CHECK(!f.kv.plan(G_GDN)->streamed());
|
||||
|
||||
/* Block ids still run over the context. A sequence longer than the window asks for more ids
|
||||
* than the pool backs and gets them, because its table names logical blocks -- which is exactly
|
||||
* why a streamed plan may not be carved without somewhere for them to live. */
|
||||
CHECK_OK(f.kv.add_sequence(1));
|
||||
CHECK_OK(f.kv.ensure(1, 16 * 8)); /* eight blocks, twice the window */
|
||||
const std::vector<int32_t>& bt = f.kv.block_table(1, G_FULL);
|
||||
CHECK(bt.size() >= 8);
|
||||
int32_t hi = 0;
|
||||
for (int32_t b : bt) hi = std::max(hi, b);
|
||||
CHECK(hi >= 4); /* an id past the window */
|
||||
|
||||
/* And a server that does not stream carves exactly what it did before the split: nothing
|
||||
* moves for a group with no cap_resident_tokens(). */
|
||||
Fixture plain;
|
||||
plain.cfg.checkpoint_slots = 0;
|
||||
CHECK_OK(plain.build());
|
||||
const KVGroupPlan* q = plain.kv.plan(G_FULL);
|
||||
CHECK(q->n_blocks > 0);
|
||||
CHECK_EQ(q->n_slots, q->n_blocks);
|
||||
CHECK(!q->streamed());
|
||||
CHECK_EQ(plain.kv.pool_bytes_carved(G_FULL), q->n_blocks * q->bytes_per_block);
|
||||
}
|
||||
|
||||
TEST(a_resident_window_that_does_not_fit_vram_kv_is_refused_by_its_own_flag) {
|
||||
/* A window wider than the pool is refused by name; left to the split, it would leave the other
|
||||
* groups zero blocks and point the operator at --host-pool-mib. */
|
||||
Fixture f;
|
||||
f.cfg.checkpoint_slots = 0;
|
||||
f.cfg.max_ctx = 1024;
|
||||
CHECK_OK(configure_pools(f.pools, f.cfg));
|
||||
f.kv.cap_resident_tokens(G_FULL, 100000); /* 6250 blocks against a 1 MiB pool */
|
||||
CHECK_OK(f.kv.plan_groups(hybrid_groups(), f.cfg));
|
||||
/* The host copy is the right size for the context; the window is what does not fit. */
|
||||
const int64_t ctx_blocks = f.cfg.max_seqs * (f.cfg.max_ctx / 16);
|
||||
std::vector<char> host((size_t)(ctx_blocks * f.kv.plan(G_FULL)->bytes_per_block), 0);
|
||||
std::vector<int32_t> res((size_t)ctx_blocks, -1);
|
||||
KVManager::StreamMap sm_in;
|
||||
sm_in.host = (uint8_t*)host.data();
|
||||
sm_in.res = res.data();
|
||||
sm_in.host_bytes = (int64_t)host.size();
|
||||
f.kv.set_stream_map(G_FULL, sm_in);
|
||||
CHECK_EQ(f.kv.carve(f.pools.kv()), RAD_E_NOMEM);
|
||||
}
|
||||
|
||||
TEST(a_streamed_window_group_is_refused_by_name) {
|
||||
/* A window group's ids are its window's, not its context's, so it cannot stream. */
|
||||
auto groups = hybrid_groups();
|
||||
groups[G_FULL].decl.kind = RAD_KV_WINDOW;
|
||||
groups[G_FULL].decl.window = 128; /* window_blocks = 128/16 + 1 */
|
||||
Fixture f;
|
||||
f.cfg.checkpoint_slots = 0;
|
||||
CHECK_OK(configure_pools(f.pools, f.cfg));
|
||||
f.kv.cap_resident_tokens(G_FULL, 64);
|
||||
CHECK_OK(f.kv.plan_groups(groups, f.cfg));
|
||||
CHECK_EQ(f.kv.carve(f.pools.kv()), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
/* The residency maps are device memory carved from the KV pool, which on a card is VRAM a host
|
||||
* load faults on; so a check copies them back on a stream first, as the engine reads `ctl`. Counts:
|
||||
* `res` is `n_layers * blocks`, `slot_block` `n_layers * slots`, `slot_state` twice that. */
|
||||
struct StreamMapsHost {
|
||||
std::vector<int32_t> res, slot_block, slot_state, ctl;
|
||||
};
|
||||
|
||||
static int read_stream_maps(const KVManager::StreamMap& m, const KVGroupPlan& p, RadStream st,
|
||||
StreamMapsHost* out) {
|
||||
const int64_t layers = p.n_layers > 0 ? p.n_layers : 1;
|
||||
out->res.assign((size_t)(layers * p.n_blocks), 0);
|
||||
out->slot_block.assign((size_t)(layers * m.slots), 0);
|
||||
out->slot_state.assign((size_t)(layers * m.slots * 2), 0);
|
||||
out->ctl.assign(16, 0);
|
||||
auto copy = [&](std::vector<int32_t>& dst, const int32_t* src) {
|
||||
return rad_memcpy_async(dst.data(), src,
|
||||
(int64_t)dst.size() * (int64_t)sizeof(int32_t), st);
|
||||
};
|
||||
int rc = copy(out->res, m.res);
|
||||
if (rc == RAD_OK) rc = copy(out->slot_block, m.slot_block);
|
||||
if (rc == RAD_OK) rc = copy(out->slot_state, m.slot_state);
|
||||
if (rc == RAD_OK) rc = copy(out->ctl, m.ctl);
|
||||
if (rc == RAD_OK) rc = rad_stream_sync(st);
|
||||
return rc;
|
||||
}
|
||||
|
||||
TEST(a_streamed_plan_allocates_reports_and_frees_its_mirror) {
|
||||
/* The host mirror and the ring's maps, end to end: what stream_cost() promises is what
|
||||
* alloc_stream() takes, the mirror is zeroed (a block nothing wrote yet must read as zeros, not
|
||||
* as a page's leftovers), the maps come out of the KV pool and hold the reset state a resolve
|
||||
* launch expects, the report shows both tiers, and free_stream() releases the mirror and is
|
||||
* safe to call twice. */
|
||||
Fixture f;
|
||||
f.cfg.checkpoint_slots = 0;
|
||||
f.cfg.max_ctx = 1024;
|
||||
CHECK_OK(configure_pools(f.pools, f.cfg));
|
||||
f.kv.cap_resident_tokens(G_FULL, 64); /* four blocks of 16 tokens */
|
||||
CHECK_OK(f.kv.plan_groups(hybrid_groups(), f.cfg));
|
||||
|
||||
const KVManager::StreamCost cost = f.kv.stream_cost();
|
||||
CHECK_EQ(cost.groups, (int64_t)1);
|
||||
CHECK_EQ(cost.host_bytes, f.cfg.max_seqs * (f.cfg.max_ctx / 16) *
|
||||
f.kv.plan(G_FULL)->bytes_per_block);
|
||||
CHECK(cost.map_bytes > 0);
|
||||
|
||||
const int64_t pool_used = f.pools.kv().used();
|
||||
CHECK_OK(f.kv.alloc_stream(rad_malloc_allocator(), f.pools.kv()));
|
||||
/* Every map byte is a reservation in the KV pool, so the paged split sees it. */
|
||||
CHECK_EQ(f.pools.kv().used() - pool_used, cost.map_bytes);
|
||||
|
||||
const KVManager::StreamMap* m = f.kv.stream_map(G_FULL);
|
||||
REQUIRE(m != nullptr);
|
||||
CHECK(m->host != nullptr && m->res != nullptr && m->ctl != nullptr);
|
||||
CHECK_EQ(m->host_bytes, cost.host_bytes);
|
||||
CHECK_EQ(m->block_bytes, f.kv.plan(G_FULL)->layer_bytes_per_block());
|
||||
CHECK_EQ(m->host_layer_stride, (f.cfg.max_seqs * (f.cfg.max_ctx / 16)) * m->block_bytes);
|
||||
/* Zeroed at allocation: a miss copies these bytes to the ring before attention reads them. */
|
||||
int64_t nonzero = 0;
|
||||
for (int64_t i = 0; i < m->host_bytes; ++i) nonzero += m->host[i] != 0;
|
||||
CHECK_EQ(nonzero, (int64_t)0);
|
||||
|
||||
CHECK_OK(f.kv.carve(f.pools.kv()));
|
||||
RadStream st = nullptr;
|
||||
REQUIRE_EQ(rad_stream_create(&st, 0), RAD_OK);
|
||||
CHECK_OK(f.kv.init_stream(st));
|
||||
CHECK_OK(rad_stream_sync(st));
|
||||
|
||||
/* The reset the reference contract states: both maps -1, state and control zero, in every
|
||||
* layer's slice (the maps are device memory; read_stream_maps copies them back). */
|
||||
const KVGroupPlan* p = f.kv.plan(G_FULL);
|
||||
StreamMapsHost got;
|
||||
CHECK_OK(read_stream_maps(*m, *p, st, &got));
|
||||
rad_stream_destroy(st);
|
||||
int64_t wrong = 0;
|
||||
for (int64_t b = 0; b < (int64_t)got.res.size(); ++b) wrong += got.res[(size_t)b] != -1;
|
||||
for (int64_t s = 0; s < (int64_t)got.slot_block.size(); ++s)
|
||||
wrong += got.slot_block[(size_t)s] != -1;
|
||||
for (int64_t i = 0; i < (int64_t)got.slot_state.size(); ++i)
|
||||
wrong += got.slot_state[(size_t)i] != 0;
|
||||
CHECK_EQ(wrong, (int64_t)0);
|
||||
for (int i = 0; i < 16; ++i) CHECK_EQ(got.ctl[(size_t)i], 0);
|
||||
CHECK_EQ(m->slots, p->pool_blocks());
|
||||
CHECK(f.kv.stream_view(G_FULL) == m);
|
||||
|
||||
const KVManager::StreamStats stats = f.kv.stream_stats();
|
||||
CHECK_EQ(stats.resident_blocks, p->pool_blocks());
|
||||
|
||||
/* Both tiers in one line, and the ring placed in the pool it was carved from. */
|
||||
CHECK(f.kv.report().find("streaming:") != std::string::npos);
|
||||
CHECK(f.kv.report().find("vram_kv") != std::string::npos);
|
||||
CHECK(f.kv.report().find("pinned host memory") != std::string::npos);
|
||||
|
||||
f.kv.free_stream(rad_malloc_allocator());
|
||||
CHECK(f.kv.stream_view(G_FULL) == nullptr);
|
||||
CHECK(f.kv.stream_map(G_FULL) == nullptr || f.kv.stream_map(G_FULL)->host == nullptr);
|
||||
f.kv.free_stream(rad_malloc_allocator()); /* teardown after a partial bring-up */
|
||||
}
|
||||
|
||||
TEST(a_streamed_plans_maps_are_device_memory_read_back_on_its_stream) {
|
||||
/* The maps come out of the KV pool, which on a card is VRAM: only the mirror may be read with a
|
||||
* host load. Their reset contents are checked by
|
||||
* `a_streamed_groups_maps_are_charged_before_the_pool_is_sized`. */
|
||||
Fixture f;
|
||||
f.cfg.checkpoint_slots = 0;
|
||||
f.cfg.max_ctx = 1024;
|
||||
CHECK_OK(configure_pools(f.pools, f.cfg));
|
||||
f.kv.cap_resident_tokens(G_FULL, 64);
|
||||
CHECK_OK(f.kv.plan_groups(hybrid_groups(), f.cfg));
|
||||
CHECK_OK(f.kv.alloc_stream(rad_malloc_allocator(), f.pools.kv()));
|
||||
CHECK_OK(f.kv.carve(f.pools.kv()));
|
||||
|
||||
const KVManager::StreamMap* m = f.kv.stream_map(G_FULL);
|
||||
REQUIRE(m != nullptr);
|
||||
/* Every map array is a reservation of this pool, and the pool is what the card backs: the
|
||||
* mirror is the only thing here the host may read with a load. */
|
||||
const char* lo = (const char*)f.pools.kv().base();
|
||||
const char* hi = lo + f.pools.kv().bytes();
|
||||
CHECK((const char*)m->res >= lo && (const char*)m->res < hi);
|
||||
CHECK(m->host < (const uint8_t*)lo || m->host >= (const uint8_t*)hi);
|
||||
if (!device_is_host()) CHECK(rad_dev_host_ptr(m->res) == nullptr);
|
||||
|
||||
f.kv.free_stream(rad_malloc_allocator());
|
||||
}
|
||||
|
||||
TEST(a_plan_that_does_not_stream_allocates_and_reports_nothing) {
|
||||
/* The inert case every existing server runs: no cap_resident_tokens(), so stream_cost() is
|
||||
* zero, alloc_stream() takes nothing, the ABI view is null (every group fully resident) and
|
||||
* the report has no streaming line. */
|
||||
Fixture f;
|
||||
CHECK_OK(f.build());
|
||||
const KVManager::StreamCost cost = f.kv.stream_cost();
|
||||
CHECK_EQ(cost.groups, (int64_t)0);
|
||||
CHECK_EQ(cost.host_bytes, (int64_t)0);
|
||||
CHECK_EQ(cost.map_bytes, (int64_t)0);
|
||||
|
||||
const int64_t pool_used = f.pools.kv().used();
|
||||
CHECK_OK(f.kv.alloc_stream(rad_malloc_allocator(), f.pools.kv()));
|
||||
CHECK_EQ(f.pools.kv().used(), pool_used);
|
||||
CHECK(f.kv.stream_view(G_FULL) == nullptr);
|
||||
CHECK(f.kv.stream_map(G_FULL) == nullptr);
|
||||
|
||||
const KVManager::StreamStats stats = f.kv.stream_stats();
|
||||
CHECK_EQ(stats.resident_blocks, (int64_t)0);
|
||||
|
||||
CHECK(f.kv.report().find("streaming:") == std::string::npos);
|
||||
f.kv.free_stream(rad_malloc_allocator());
|
||||
CHECK_EQ(f.pools.kv().used(), pool_used);
|
||||
}
|
||||
|
||||
TEST(a_ring_that_covers_the_context_streams_nothing_and_the_engine_pays_nothing) {
|
||||
/* --kv-resident absent or 0 streams nothing, and neither does a ring that covers the group's
|
||||
* context: such a group keeps the resident path, with no mirror, maps or stage and a null
|
||||
* RadKVStream, so no kv_resolve can be issued (docs/KV-STREAMING.md §3.1). */
|
||||
Fixture f;
|
||||
f.cfg.checkpoint_slots = 0;
|
||||
f.cfg.max_ctx = 1024;
|
||||
f.cfg.max_seqs = 2; /* context: 2 sequences x 1024 tokens */
|
||||
std::vector<KVGroupInfo> groups = hybrid_groups();
|
||||
groups[G_FULL].bytes_per_block = 2048; /* 16 tokens x 128 B, as declare sets it */
|
||||
const int64_t ctx_blocks = 2 * (1024 / 16); /* 128 blocks of 16 tokens */
|
||||
/* A ring that covers the context. The group is bf16 here on purpose: a configuration that fits
|
||||
* is never refused for a cache the streamed store has no row for, because nothing streams. */
|
||||
f.cfg.kv_resident = 1024 * 2;
|
||||
KVStreamSetup s;
|
||||
CHECK_OK(kvstream_configure(f.cfg, 1024, groups, stream_program(groups[G_FULL], 513), &s));
|
||||
CHECK_EQ(s.group, -1);
|
||||
CHECK_EQ(s.asked_tokens, (int64_t)2048);
|
||||
CHECK_EQ(s.ctx_blocks, ctx_blocks);
|
||||
CHECK_EQ(s.ring_blocks, ctx_blocks);
|
||||
CHECK_EQ(s.stage_blocks, (int64_t)0); /* no stage view is declared */
|
||||
CHECK_EQ(s.group_name, std::string("full"));
|
||||
|
||||
/* And the engine applies that decision: configure_kv caps only a group that streams, so the
|
||||
* manager is never told about a window, alloc_stream() takes nothing and the carve is the
|
||||
* ordinary one-view pool. */
|
||||
CHECK_OK(configure_pools(f.pools, f.cfg));
|
||||
CHECK_OK(f.kv.plan_groups(groups, f.cfg));
|
||||
const KVManager::StreamCost cost = f.kv.stream_cost();
|
||||
CHECK_EQ(cost.groups, (int64_t)0);
|
||||
CHECK_EQ(cost.host_bytes, (int64_t)0);
|
||||
CHECK_EQ(cost.map_bytes, (int64_t)0);
|
||||
const int64_t pool_used = f.pools.kv().used();
|
||||
CHECK_OK(f.kv.alloc_stream(rad_malloc_allocator(), f.pools.kv()));
|
||||
CHECK_EQ(f.pools.kv().used(), pool_used); /* no mirror and no maps were taken */
|
||||
CHECK_OK(f.kv.carve(f.pools.kv()));
|
||||
const KVGroupPlan* p = f.kv.plan(G_FULL);
|
||||
CHECK_EQ(p->n_slots, p->n_blocks); /* every block has its own slot */
|
||||
CHECK(!p->streamed());
|
||||
CHECK_EQ(p->depth, (int64_t)0); /* the arch sees no stage view */
|
||||
CHECK_EQ(f.kv.pool_bytes_carved(G_FULL), p->n_blocks * p->bytes_per_block);
|
||||
CHECK(f.kv.stream_view(G_FULL) == nullptr); /* so no kv_resolve can be issued */
|
||||
CHECK(f.kv.stream_map(G_FULL) == nullptr);
|
||||
CHECK(f.kv.report().find("streaming:") == std::string::npos);
|
||||
f.kv.free_stream(rad_malloc_allocator());
|
||||
|
||||
/* Absent (the parser's default) and 0 are the same: nothing is asked for, nothing is decided,
|
||||
* nothing is capped. */
|
||||
{
|
||||
Fixture g;
|
||||
g.cfg.checkpoint_slots = 0;
|
||||
g.cfg.max_ctx = 1024;
|
||||
g.cfg.max_seqs = 2;
|
||||
g.cfg.kv_resident = 0;
|
||||
KVStreamSetup o;
|
||||
CHECK_OK(kvstream_configure(g.cfg, 1024, groups, stream_program(groups[G_FULL], 513), &o));
|
||||
CHECK_EQ(o.group, -1);
|
||||
CHECK_EQ(o.asked_tokens, (int64_t)0);
|
||||
CHECK_EQ(o.ring_blocks, (int64_t)0);
|
||||
CHECK_EQ(o.stage_blocks, (int64_t)0);
|
||||
CHECK_OK(g.build_groups(groups));
|
||||
CHECK_EQ(g.kv.stream_cost().groups, (int64_t)0);
|
||||
CHECK(g.kv.stream_view(G_FULL) == nullptr);
|
||||
CHECK(!g.kv.plan(G_FULL)->streamed());
|
||||
CHECK_EQ(g.kv.plan(G_FULL)->depth, (int64_t)0);
|
||||
}
|
||||
}
|
||||
|
||||
/* The prefix cache's host tier is turned off when --kv-resident really streams, and only then.
|
||||
* The three cases that must leave it on are the ones an operator hits without meaning to: the flag
|
||||
* absent or 0, a ring that covers the group's context (nothing streams), and a flag on a model the
|
||||
* tier does not stream. `cfg.kv_streams` is the one answer to all three (kvstream_cap_probe). */
|
||||
TEST(the_prefix_cache_host_tier_is_off_only_when_streaming_is_really_on) {
|
||||
std::vector<KVGroupInfo> groups = hybrid_groups();
|
||||
groups[G_FULL].bytes_per_block = 2048; /* 16 tokens x 128 B, as declare sets it */
|
||||
/* A pitch of 513 blocks is this fixture's resolve; the ceiling is max_seqs x (1 + n_spec) x
|
||||
* pitch, so a ring under a 128-block context needs a small pitch: 8 x 2 = 16 blocks. */
|
||||
const Program wide = stream_program(groups[G_FULL], 513);
|
||||
const Program narrow = stream_program(groups[G_FULL], 8);
|
||||
|
||||
struct Case {
|
||||
const char* what;
|
||||
int64_t resident; /* --kv-resident */
|
||||
bool streams;
|
||||
int64_t tier_after; /* --prefix-cache-mib once bring-up has had its say */
|
||||
};
|
||||
const Case cases[] = {
|
||||
{ "the flag absent", 0, false, 2048 },
|
||||
{ "a ring covering the ctx", 2 * 65536, false, 2048 },
|
||||
{ "a ring under the ctx", 256, true, 0 },
|
||||
};
|
||||
for (const Case& c : cases) {
|
||||
Fixture f;
|
||||
f.cfg.checkpoint_slots = 0;
|
||||
f.cfg.max_ctx = 65536; /* clears the 32 768-token floor */
|
||||
f.cfg.max_seqs = 2;
|
||||
f.cfg.kv_resident = c.resident;
|
||||
f.cfg.prefix_cache_mib = 2048;
|
||||
CHECK_OK(f.kv.plan_groups(groups, f.cfg));
|
||||
CHECK_OK(kvstream_cap_probe(f.kv, f.cfg, c.streams ? narrow : wide, f.cfg.max_ctx));
|
||||
CHECK_EQ(f.cfg.kv_streams, c.streams);
|
||||
const int64_t off = kvstream_prefix_host_off(f.cfg);
|
||||
CHECK_EQ(f.cfg.prefix_cache_mib, c.tier_after);
|
||||
CHECK_EQ(off, c.streams ? 2048ll : 0ll);
|
||||
CHECK_EQ(kvstream_prefix_host_off(f.cfg), 0ll); /* idempotent: a second rank says nothing */
|
||||
f.kv.free_stream(rad_malloc_allocator());
|
||||
}
|
||||
}
|
||||
|
||||
TEST(a_decode_pass_wider_than_a_verify_stages_instead_of_resolving_the_ring) {
|
||||
/* The serial drafter's history pass is RAD_PHASE_DECODE, but after a prefill chunk it carries
|
||||
* the chunk's tokens of every sequence: more rows a sequence than a decode step can select for
|
||||
* (1 + n_spec). Its selection is the union of the histories it spans, not one row a selection,
|
||||
* so it reads the one-layer stage -- identity-addressed over the whole context -- and cannot
|
||||
* overflow the ring. A verify or a history pass over the verified window stays on the ring:
|
||||
* routing those to the stage would stage every decode step. */
|
||||
using rad::KVView;
|
||||
CHECK(kv_pass_view(RAD_PHASE_PREFILL, 2048, 4, 3) == KVView::Stage);
|
||||
CHECK(kv_pass_view(RAD_PHASE_MIXED, 900, 3, 3) == KVView::Stage);
|
||||
/* The ring's passes: a verify step (4 rows a sequence with n_spec 3), one row a sequence, and
|
||||
* the history pass that redoes the verified positions. */
|
||||
CHECK(kv_pass_view(RAD_PHASE_DECODE, 16, 4, 3) == KVView::Ring);
|
||||
CHECK(kv_pass_view(RAD_PHASE_DECODE, 4, 4, 3) == KVView::Ring);
|
||||
CHECK(kv_pass_view(RAD_PHASE_DECODE, 12, 3, 3) == KVView::Ring);
|
||||
CHECK(kv_pass_view(RAD_PHASE_DECODE, 4, 4, 0) == KVView::Ring);
|
||||
/* The history pass over a prefill chunk, and every prefill-shaped decode pass. */
|
||||
CHECK(kv_pass_view(RAD_PHASE_DECODE, 2048, 4, 3) == KVView::Stage);
|
||||
CHECK(kv_pass_view(RAD_PHASE_DECODE, 2039, 3, 3) == KVView::Stage);
|
||||
CHECK(kv_pass_view(RAD_PHASE_DECODE, 2048, 4, 0) == KVView::Stage);
|
||||
}
|
||||
|
||||
TEST(a_ring_below_one_decode_step_s_selection_is_raised_to_the_ceiling) {
|
||||
/* A ring under one decode step's selection, max_seqs x (1 + n_spec) x sel_pitch blocks, would
|
||||
* serve a table that no longer addresses the pool, so the flag is raised to it with one
|
||||
* warning and the carve takes the raised ring. */
|
||||
Fixture f;
|
||||
f.cfg.checkpoint_slots = 0;
|
||||
/* The context must clear the shipped floor (kStreamFloorTokens, 32 768 tokens) for the step
|
||||
* ceiling to be the binding bound: 2 x 65 536 tokens = 8192 blocks of 16. */
|
||||
f.cfg.max_ctx = 65536;
|
||||
f.cfg.max_seqs = 2;
|
||||
f.cfg.n_spec = 0;
|
||||
f.cfg.vram_kv_mib = 64;
|
||||
std::vector<KVGroupInfo> groups = hybrid_groups();
|
||||
groups[G_FULL].decl.dtype = RAD_F8E4M3; /* the streamed store's one row */
|
||||
groups[G_FULL].bytes_per_block = 2048; /* as declare sets it */
|
||||
const int64_t sel_pitch = 2048; /* a synthetic indexer's topk + 1 */
|
||||
const int64_t ctx_blocks = 2 * (65536 / 16); /* 8192 blocks of 16 tokens */
|
||||
const Program prog = stream_program(groups[G_FULL], sel_pitch);
|
||||
CHECK_OK(configure_pools(f.pools, f.cfg));
|
||||
CHECK_OK(f.kv.plan_groups(groups, f.cfg));
|
||||
/* The ceiling is 2 sequences x 1 row x sel_pitch = 4096 blocks = 65 536 tokens, above the
|
||||
* shipped floor of 2048 blocks (32 768 tokens) and under the 8192-block context. */
|
||||
f.cfg.kv_resident = 128; /* 8 blocks: far under it */
|
||||
KVStreamSetup s;
|
||||
const std::string log = stderr_of([&] {
|
||||
/* The budget probe prices the ring the carve will take, both of them raised. */
|
||||
CHECK_OK(kvstream_cap_probe(f.kv, f.cfg, prog, 65536));
|
||||
CHECK_OK(kvstream_configure(f.cfg, 65536, groups, prog, &s));
|
||||
});
|
||||
CHECK(has(log, "--kv-resident 128 raised to 65536 tokens"));
|
||||
CHECK(has(log, "one decode step can select 4096 blocks of 16 tokens"));
|
||||
CHECK(has(log, "(--max-num-seqs 2 x 1 rows x 2048)"));
|
||||
/* Raised, not refused: the flag is as the operator left it and the plan is the ceiling. */
|
||||
CHECK_EQ(f.cfg.kv_resident, (int64_t)128);
|
||||
CHECK_EQ(s.group, (int32_t)G_FULL);
|
||||
CHECK_EQ(s.asked_tokens, (int64_t)128);
|
||||
CHECK_EQ(s.raised_tokens, (int64_t)65536);
|
||||
CHECK_EQ(s.ring_blocks, (int64_t)4096);
|
||||
CHECK_EQ(s.ring_tokens, (int64_t)65536);
|
||||
CHECK_EQ(s.ctx_blocks, ctx_blocks);
|
||||
CHECK_EQ(s.stage_blocks, ctx_blocks); /* one layer, the whole context */
|
||||
|
||||
/* The carve takes the ceiling, not the flag's 8 blocks: cap_resident_tokens is handed the
|
||||
* raised ring, and the residency map, the pool and the resolve's slot ceiling are that depth. */
|
||||
CHECK_OK(f.kv.alloc_stream(rad_malloc_allocator(), f.pools.kv()));
|
||||
CHECK_OK(f.kv.carve(f.pools.kv()));
|
||||
const KVGroupPlan* p = f.kv.plan(G_FULL);
|
||||
CHECK(p->streamed());
|
||||
CHECK_EQ(p->n_blocks, ctx_blocks);
|
||||
CHECK_EQ(p->n_slots, (int64_t)4096); /* the ceiling */
|
||||
CHECK_EQ(p->n_slots, s.ring_blocks);
|
||||
CHECK_EQ(f.kv.stream_map(G_FULL)->slots, (int64_t)4096);
|
||||
CHECK_EQ(f.kv.stream_stats().resident_blocks, (int64_t)4096);
|
||||
|
||||
/* And the startup report says so in the ring's own line, not only in the warning: the ring is
|
||||
* no longer what the operator typed, and the report is what people read afterwards. */
|
||||
KVStreamHostUse use;
|
||||
kvstream_host_add(&use, f.kv);
|
||||
const std::string rep = stderr_of([&] { kvstream_report(s, use, 1); });
|
||||
CHECK(has(rep, "--kv-resident 128 became 65536 tokens"));
|
||||
CHECK(has(rep, "(8 -> 4096 blocks of 16 tokens)"));
|
||||
CHECK(has(rep, "ring 4096 blocks")); /* the staging line quotes the ring */
|
||||
f.kv.free_stream(rad_malloc_allocator());
|
||||
|
||||
/* Under speculation a verify step runs the drafts beside the accepted position, so the rows --
|
||||
* and the ceiling -- scale by 1 + n_spec: 2 x 4 x 512 = 4096 blocks = 65 536 tokens. */
|
||||
{
|
||||
const Program spec = stream_program(groups[G_FULL], 512);
|
||||
Fixture g;
|
||||
g.cfg.checkpoint_slots = 0;
|
||||
g.cfg.max_ctx = 65536;
|
||||
g.cfg.max_seqs = 2;
|
||||
g.cfg.n_spec = 3;
|
||||
g.cfg.vram_kv_mib = 64;
|
||||
g.cfg.kv_resident = 512; /* 32 blocks: far under the ceiling */
|
||||
KVStreamSetup o;
|
||||
const std::string l = stderr_of([&] {
|
||||
CHECK_OK(kvstream_configure(g.cfg, 65536, groups, spec, &o));
|
||||
});
|
||||
CHECK(has(l, "(--max-num-seqs 2 x 4 rows x 512)"));
|
||||
CHECK_EQ(o.group, (int32_t)G_FULL);
|
||||
CHECK_EQ(o.ring_blocks, (int64_t)4096);
|
||||
CHECK_EQ(o.raised_tokens, (int64_t)65536);
|
||||
}
|
||||
/* At or above the ceiling nothing is raised and the ring is the flag's own number. */
|
||||
{
|
||||
Fixture g;
|
||||
g.cfg.checkpoint_slots = 0;
|
||||
g.cfg.max_ctx = 65536;
|
||||
g.cfg.max_seqs = 2;
|
||||
g.cfg.n_spec = 0;
|
||||
g.cfg.kv_resident = 65536; /* exactly 2 x 1 x 2048 blocks of 16 */
|
||||
KVStreamSetup o;
|
||||
const std::string l = stderr_of([&] {
|
||||
CHECK_OK(kvstream_configure(g.cfg, 65536, groups, prog, &o));
|
||||
});
|
||||
CHECK(!has(l, "raised"));
|
||||
CHECK_EQ(o.raised_tokens, (int64_t)0);
|
||||
CHECK_EQ(o.ring_blocks, (int64_t)4096);
|
||||
CHECK_EQ(o.ring_tokens, (int64_t)65536);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(a_model_whose_architecture_declares_no_streamed_ops_ignores_the_flag) {
|
||||
/* An architecture with no streamed path ignores the flag with one line (docs/KV-STREAMING.md
|
||||
* §4.5): without the resolve the attention would read block ids past the ring, and without the
|
||||
* streamed store a miss would read zeros. */
|
||||
Fixture f;
|
||||
f.cfg.checkpoint_slots = 0;
|
||||
f.cfg.max_ctx = 65536; /* above the 32 768-token ring floor */
|
||||
f.cfg.max_seqs = 2;
|
||||
f.cfg.kv_resident = 256; /* under the ring floor, so it is raised */
|
||||
std::vector<KVGroupInfo> groups = hybrid_groups();
|
||||
groups[G_FULL].bytes_per_block = 2048; /* 16 tokens x 2 kv heads x 8 x 2 B x 2 layers */
|
||||
const Program none =
|
||||
stream_program(groups[G_FULL], 8, /*with_resolve=*/false, /*with_store=*/false);
|
||||
KVStreamSetup s;
|
||||
int st = RAD_OK;
|
||||
const std::string log = stderr_of([&] { st = kvstream_configure(f.cfg, 65536, groups, none, &s); });
|
||||
CHECK_OK(st); /* ignored, not refused */
|
||||
CHECK_EQ(s.group, -1);
|
||||
CHECK_EQ(s.asked_tokens, (int64_t)0); /* nothing is claimed, so nothing is reported */
|
||||
CHECK_EQ(s.ring_blocks, (int64_t)0);
|
||||
CHECK_EQ(s.stage_blocks, (int64_t)0);
|
||||
CHECK(has(log, "ignored"));
|
||||
CHECK(has(log, "test-arch")); /* the architecture, not just the group */
|
||||
CHECK(has(log, "kv_resolve")); /* the op that is missing, by name */
|
||||
CHECK(!has(log, "raised to")); /* that is the other message: this model cannot stream at all */
|
||||
|
||||
/* Half a path is no path: the resolve with no streamed store would leave the mirror unwritten
|
||||
* and the miss list meaningless, so the warning names that op instead. */
|
||||
KVStreamSetup half;
|
||||
const std::string log2 = stderr_of([&] {
|
||||
CHECK_OK(kvstream_configure(f.cfg, 65536, groups,
|
||||
stream_program(groups[G_FULL], 8, true, false), &half));
|
||||
});
|
||||
CHECK_EQ(half.group, -1);
|
||||
CHECK(has(log2, "kv_store_streamed"));
|
||||
|
||||
/* And the fail-safe never turns a working architecture off: the same configuration with both
|
||||
* ops declared streams the ring it was sized for. */
|
||||
KVStreamSetup ok;
|
||||
CHECK_OK(kvstream_configure(f.cfg, 65536, groups, stream_program(groups[G_FULL], 8), &ok));
|
||||
CHECK_EQ(ok.group, (int32_t)G_FULL);
|
||||
CHECK_EQ(ok.ring_blocks, (int64_t)2048); /* raised to the 32 768-token floor */
|
||||
CHECK_EQ(ok.stage_blocks, ok.ctx_blocks);
|
||||
}
|
||||
|
||||
TEST(a_declared_streamed_store_with_no_kernel_is_not_a_streamed_path) {
|
||||
/* A declaration with no kernel is not a streamed path: the builder keeps the op with one band
|
||||
* and no domain bound, and counting it would stream a group whose store never runs. */
|
||||
Fixture f;
|
||||
f.cfg.checkpoint_slots = 0;
|
||||
f.cfg.max_ctx = 65536; /* above the 32 768-token ring floor */
|
||||
f.cfg.max_seqs = 2;
|
||||
f.cfg.kv_resident = 256; /* under the ring floor, so it is raised */
|
||||
std::vector<KVGroupInfo> groups = hybrid_groups();
|
||||
groups[G_FULL].decl.dtype = RAD_F8E4M3;
|
||||
groups[G_FULL].bytes_per_block = 2048;
|
||||
/* The resolve resolves; the store is declared with no row (both domains null). */
|
||||
const Program unresolved = stream_program(groups[G_FULL], 8, true, true, /*store_resolved=*/false);
|
||||
REQUIRE_EQ(unresolved.ops.size(), (size_t)2);
|
||||
REQUIRE_EQ(unresolved.ops[1].bands.size(), (size_t)1);
|
||||
CHECK(unresolved.ops[1].bands[0].dom[RAD_DOMAIN_DEVICE].row == nullptr);
|
||||
|
||||
const KVStreamOps ops = kvstream_ops(unresolved, &groups[G_FULL]);
|
||||
CHECK(ops.resolve);
|
||||
CHECK(!ops.store);
|
||||
CHECK(!ops.folded);
|
||||
CHECK(!ops.streams()); /* no writer, so no streamed path */
|
||||
|
||||
KVStreamSetup s;
|
||||
int st = RAD_OK;
|
||||
const std::string log =
|
||||
stderr_of([&] { st = kvstream_configure(f.cfg, 65536, groups, unresolved, &s); });
|
||||
CHECK_OK(st); /* ignored, not carved */
|
||||
CHECK_EQ(s.group, -1);
|
||||
CHECK_EQ(s.asked_tokens, (int64_t)0);
|
||||
CHECK_EQ(s.ring_blocks, (int64_t)0);
|
||||
CHECK_EQ(s.stage_blocks, (int64_t)0);
|
||||
CHECK(has(log, "ignored"));
|
||||
CHECK(has(log, "kv_store_streamed")); /* the op that is missing, by name */
|
||||
|
||||
}
|
||||
|
||||
TEST(a_packed_cache_warns_that_the_layout_has_no_writer_and_serves_non_streamed) {
|
||||
/* --kv-cache-dtype fp8_v4 / k6_v4: the architecture declares the resolve and no streamed store,
|
||||
* because libr4d's streamed rows are E4M3 and bf16 and a packed cache has base-store rows only
|
||||
* (arch/common/rad_block_attn_gated_fp8.h). The group is declared to the core as plain E4M3, so
|
||||
* no dtype gate downstream can see the layout: the operator has to be told the *layout* has no
|
||||
* writer, not that the architecture cannot stream -- and the group must run the base path.
|
||||
* Before this the op was declared against a table with no row for it, which is a weightless
|
||||
* device hole: startup refused with or without --kv-resident, naming a kernel band and never the
|
||||
* flag. */
|
||||
for (const char* dtype : { "fp8_v4", "k6_v4" }) {
|
||||
Fixture f;
|
||||
f.cfg.checkpoint_slots = 0;
|
||||
f.cfg.max_ctx = 65536; /* above the 32 768-token ring floor */
|
||||
f.cfg.max_seqs = 2;
|
||||
f.cfg.kv_resident = 256; /* under the ring floor, so it is raised */
|
||||
f.cfg.kv_cache_dtype = dtype;
|
||||
std::vector<KVGroupInfo> groups = hybrid_groups();
|
||||
groups[G_FULL].decl.dtype = RAD_F8E4M3; /* what declare gives the core, packed or not */
|
||||
groups[G_FULL].bytes_per_block = 2048;
|
||||
/* What the gated plugin emits for a packed cache: the layout-blind resolve, no store. */
|
||||
const Program packed = stream_program(groups[G_FULL], 8, true, /*with_store=*/false);
|
||||
KVStreamSetup s;
|
||||
int st = RAD_OK;
|
||||
const std::string log = stderr_of([&] {
|
||||
st = kvstream_configure(f.cfg, 65536, groups, packed, &s);
|
||||
});
|
||||
CHECK_OK(st); /* started, not refused */
|
||||
CHECK_EQ(s.group, -1);
|
||||
CHECK_EQ(s.asked_tokens, (int64_t)0);
|
||||
CHECK_EQ(s.stage_blocks, (int64_t)0);
|
||||
CHECK(has(log, "ignored"));
|
||||
CHECK(has(log, std::string("group 'full' has a ") + dtype + " cache"));
|
||||
CHECK(has(log, "has no writer for that layout (E4M3 and bf16 only)"));
|
||||
CHECK(!has(log, "declares no")); /* not that sentence: the arch declared it */
|
||||
CHECK(!has(log, "raised to")); /* and not the ring's */
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
TEST(a_resolve_declared_for_another_group_does_not_enable_streaming) {
|
||||
/* The check is per group, not per program: the resolve states the layer-bytes pitch of the
|
||||
* group it was emitted for, so one declared for a narrower full group cannot make streaming
|
||||
* of the widest group look wired. That is the difference between "some group resolves" and
|
||||
* "the group the plan streams resolves", and only the second is safe. */
|
||||
Fixture f;
|
||||
f.cfg.checkpoint_slots = 0;
|
||||
f.cfg.max_ctx = 65536; /* above the 32 768-token ring floor */
|
||||
f.cfg.max_seqs = 2;
|
||||
f.cfg.kv_resident = 256;
|
||||
std::vector<KVGroupInfo> groups = hybrid_groups();
|
||||
groups[G_FULL].bytes_per_block = 2048; /* 1024 B a layer */
|
||||
Program other = stream_program(groups[G_FULL], 8);
|
||||
other.ops[0].base.set_i("block_bytes", 4096); /* a wider group's pitch, not this one's */
|
||||
KVStreamSetup s;
|
||||
int st = RAD_OK;
|
||||
const std::string log = stderr_of([&] { st = kvstream_configure(f.cfg, 65536, groups, other, &s); });
|
||||
CHECK_OK(st);
|
||||
CHECK_EQ(s.group, -1);
|
||||
CHECK(has(log, "kv_resolve"));
|
||||
}
|
||||
|
||||
TEST(kv_refuses_a_group_with_no_block_size) {
|
||||
/* Block size comes from the resolved attention kernel; zero means it did not resolve, and the
|
||||
* manager refuses rather than inventing one. */
|
||||
@@ -6669,4 +7421,150 @@ TEST(a_tier_transfer_gives_back_every_event_and_device_byte) {
|
||||
CHECK_EQ(vram1, vram0);
|
||||
}
|
||||
|
||||
/* The streamed group's residency maps are reserved from the KV pool before the carve, so the
|
||||
* budget probe must charge them before it sizes the pool. Left out, the pool it names is short by
|
||||
* their bytes and the group that stays resident is carved below one full-length conversation --
|
||||
* the target shape's `kv_qsa_bkey` at 47 185 of the 51 200 blocks it needed (188 740 tokens
|
||||
* against --max-model-len 204800). The probe has no pool and cannot reserve them; the carve has
|
||||
* already taken them. paged_split() charges them and carve_into() adds back what was reserved, so
|
||||
* both paths see the same bytes (kvstream/carve.h). */
|
||||
TEST(a_streamed_groups_maps_are_charged_before_the_pool_is_sized) {
|
||||
Fixture f;
|
||||
f.cfg.checkpoint_slots = 0;
|
||||
f.cfg.max_seqs = 4;
|
||||
f.cfg.max_ctx = 65536; /* the maps are more than the MiB rounding */
|
||||
std::vector<KVGroupInfo> groups = hybrid_groups();
|
||||
groups.push_back(paged_group("bkey", RAD_KV_FULL, 2, 4, { 6, 7 }));
|
||||
CHECK_OK(f.kv.plan_groups(groups, f.cfg));
|
||||
f.kv.cap_resident_tokens(G_FULL, 64); /* four blocks of 16 tokens */
|
||||
const int64_t need = f.kv.pool_mib_for_tokens(f.cfg.max_ctx, 256);
|
||||
REQUIRE(need > 0);
|
||||
f.cfg.vram_kv_mib = need;
|
||||
CHECK_OK(configure_pools(f.pools, f.cfg));
|
||||
CHECK_OK(f.kv.alloc_stream(rad_malloc_allocator(), f.pools.kv()));
|
||||
CHECK_OK(f.kv.carve(f.pools.kv()));
|
||||
/* The group that stays resident holds one whole conversation, not the pool's remainder. */
|
||||
const KVGroupPlan* bkey = f.kv.plan(3);
|
||||
REQUIRE(bkey != nullptr);
|
||||
CHECK(!bkey->streamed());
|
||||
CHECK(bkey->n_blocks * bkey->block_size >= f.cfg.max_ctx);
|
||||
}
|
||||
|
||||
/* A dense-read group is read over its whole live history every decode step, so it cannot stream.
|
||||
* While a sibling does, its carve is a floor of max_seqs full contexts: the host mirror next to it
|
||||
* is sized for max_seqs sequences, and an indexer funded for one makes the advertised capacity a
|
||||
* promise the engine cannot keep. The probe sizes the pool for the floor before the carve spends
|
||||
* it (kvstream/carve.h). */
|
||||
TEST(a_dense_read_groups_floor_holds_every_sequence_while_a_sibling_streams) {
|
||||
Fixture f;
|
||||
f.cfg.checkpoint_slots = 0;
|
||||
f.cfg.max_seqs = 4;
|
||||
f.cfg.max_ctx = 65536;
|
||||
std::vector<KVGroupInfo> groups = hybrid_groups();
|
||||
groups.push_back(paged_group("bkey", RAD_KV_FULL, 2, 4, { 6, 7 }));
|
||||
groups.back().dense_read = true;
|
||||
CHECK_OK(f.kv.plan_groups(groups, f.cfg));
|
||||
f.kv.cap_resident_tokens(G_FULL, 64); /* four blocks of 16 tokens */
|
||||
const int64_t need = f.kv.pool_mib_for_tokens(f.cfg.max_ctx, 512);
|
||||
REQUIRE(need > 0);
|
||||
f.cfg.vram_kv_mib = need;
|
||||
CHECK_OK(configure_pools(f.pools, f.cfg));
|
||||
CHECK_OK(f.kv.alloc_stream(rad_malloc_allocator(), f.pools.kv()));
|
||||
CHECK_OK(f.kv.carve(f.pools.kv()));
|
||||
const KVGroupPlan* bkey = f.kv.plan(3);
|
||||
REQUIRE(bkey != nullptr);
|
||||
CHECK(!bkey->streamed());
|
||||
CHECK_EQ(bkey->n_blocks, f.cfg.max_seqs * ((f.cfg.max_ctx + 3) / 4));
|
||||
CHECK_EQ(bkey->n_slots, bkey->n_blocks);
|
||||
}
|
||||
|
||||
/* A prefix entry covers every cached group, the streamed one included: a hit re-adopts its block
|
||||
* ids, and the mirror behind them is that group's tier. A streamed group's rows are addressed by
|
||||
* the block id the sequence used, so its ids cannot be given up for a host slot: an entry that
|
||||
* contains one stays in VRAM, the tiers are never told about it, and an eviction takes every
|
||||
* group's ids with it. */
|
||||
TEST(an_entry_with_a_streamed_group_is_never_demoted) {
|
||||
if (!host_backend_or_skip("the tier restore")) return;
|
||||
Fixture f;
|
||||
f.cfg.checkpoint_slots = 0;
|
||||
f.cfg.max_seqs = 1;
|
||||
f.cfg.max_ctx = 1024;
|
||||
std::vector<KVGroupInfo> groups = hybrid_groups();
|
||||
groups.push_back(paged_group("bkey", RAD_KV_FULL, 2, 16, { 6, 7 }));
|
||||
CHECK_OK(f.kv.plan_groups(groups, f.cfg));
|
||||
f.kv.cap_resident_tokens(G_FULL, 64); /* four blocks of 16 tokens */
|
||||
const int64_t need = f.kv.pool_mib_for_tokens(f.cfg.max_ctx, 256);
|
||||
REQUIRE(need > 0);
|
||||
f.cfg.vram_kv_mib = need;
|
||||
CHECK_OK(configure_pools(f.pools, f.cfg));
|
||||
CHECK_OK(f.kv.alloc_stream(rad_malloc_allocator(), f.pools.kv()));
|
||||
CHECK_OK(f.kv.carve(f.pools.kv()));
|
||||
|
||||
const std::vector<int32_t>& cg = f.pc.cached_groups();
|
||||
IdleTiers t;
|
||||
REQUIRE_EQ(t.configure(tier_config(4096 * 1024, 4096 * 1024)), RAD_OK);
|
||||
f.pc.set_tiers(&t);
|
||||
REQUIRE_EQ(f.pc.configure(f.cfg, &f.kv, f.cfg.checkpoint_interval), RAD_OK);
|
||||
REQUIRE_EQ(cg.size(), 2u);
|
||||
CHECK(f.kv.plan(cg[0])->streamed());
|
||||
/* The one fact the tier path depends on: a slot cannot hold this cache's entries, so no
|
||||
* write-back is planned, nothing is queued, and nothing can be dropped to the host. */
|
||||
CHECK(!f.pc.demotable());
|
||||
|
||||
const auto tokens = tok_run(5000, 64);
|
||||
publish(f, 1, tokens, 64);
|
||||
f.kv.free_sequence(1);
|
||||
const std::vector<BlockHash> hs = chain_of(tokens);
|
||||
REQUIRE_EQ(hs.size(), 4u);
|
||||
|
||||
std::vector<TierJob> wb;
|
||||
t.plan_writeback(64, &wb);
|
||||
CHECK_EQ(wb.size(), 0u); /* the streamed entry is never copied */
|
||||
CHECK_EQ(f.pc.drop_clean(), 0ll); /* so it is never demoted */
|
||||
CHECK(!t.droppable(hs[0]));
|
||||
|
||||
/* The trim still frees it: an entry the tier cannot hold must not be skipped as though its
|
||||
* copy were in flight. All four blocks are at refcount one and the trim takes them. */
|
||||
CHECK_EQ(f.pc.trim(4), 4ll);
|
||||
CHECK_EQ(f.pc.size(), 0ll);
|
||||
CHECK_EQ(f.kv.block_refcount(cg[0], 0), 0);
|
||||
CHECK_EQ(f.kv.block_refcount(cg[1], 0), 0);
|
||||
f.pc.set_tiers(nullptr);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
|
||||
/* A streamed-only op exists only when the architecture's capability table says it can stream AND
|
||||
* the deployment asked for a ring (core/kvstream/bringup.cpp, consulted from rad_op_declared). One
|
||||
* binary serves both runs, so this is the only place the two questions meet; no model file carries
|
||||
* the flag, and an architecture that cannot stream keeps the graph it had before streaming existed. */
|
||||
TEST(a_streamed_op_exists_only_for_a_capable_architecture_and_a_ring) {
|
||||
RadBuildCtx ctx{};
|
||||
ctx.kv_stream_ok = 1;
|
||||
ctx.kv_resident_blocks = 32768;
|
||||
/* capable and asked: the ops declare as they always did */
|
||||
CHECK(!kvstream_op_gated(ctx, "kv_store_streamed"));
|
||||
CHECK(!kvstream_op_gated(ctx, "qk_norm_rope_gate_kv_store_streamed"));
|
||||
CHECK(!kvstream_op_gated(ctx, "kv_resolve"));
|
||||
/* nothing that works without a ring is ever gated */
|
||||
CHECK(!kvstream_op_gated(ctx, "kv_store"));
|
||||
CHECK(!kvstream_op_gated(ctx, "qk_norm_rope_gate_kv_store"));
|
||||
CHECK(!kvstream_op_gated(ctx, "attn_paged"));
|
||||
CHECK(!kvstream_op_gated(ctx, "qsa_select"));
|
||||
CHECK(!kvstream_op_gated(ctx, nullptr));
|
||||
|
||||
/* no flag: the ops that exist only for a ring are gone */
|
||||
ctx.kv_resident_blocks = 0;
|
||||
CHECK(kvstream_op_gated(ctx, "kv_store_streamed"));
|
||||
CHECK(kvstream_op_gated(ctx, "kv_resolve"));
|
||||
CHECK(!kvstream_op_gated(ctx, "kv_store"));
|
||||
|
||||
/* an architecture with no streamed path declares none even when the flag asks */
|
||||
ctx.kv_resident_blocks = 32768;
|
||||
ctx.kv_stream_ok = 0;
|
||||
CHECK(kvstream_op_gated(ctx, "kv_store_streamed"));
|
||||
CHECK(kvstream_op_gated(ctx, "qk_norm_rope_gate_kv_store_streamed"));
|
||||
CHECK(kvstream_op_gated(ctx, "kv_resolve"));
|
||||
CHECK(!kvstream_op_gated(ctx, "kv_store"));
|
||||
CHECK(!kvstream_op_gated(ctx, "attn_paged"));
|
||||
}
|
||||
+14
-5
@@ -1,5 +1,5 @@
|
||||
#!/bin/sh
|
||||
# oot_plugins.sh BUILD SOURCE WORK [HIP_COMPILER HIP_TARGETS [VOPD_REPEATABLE]]
|
||||
# oot_plugins.sh BUILD SOURCE WORK [HIP_COMPILER HIP_TARGETS [VOPD_REPEATABLE [CXX_COMPILER]]]
|
||||
#
|
||||
# THE PLUGINS RADIANCE SHIPS, BUILT THE WAY A THIRD PARTY BUILDS THEIRS. The tree's build is
|
||||
# installed into a prefix; then every plugin directory -- the kernel libraries, the quantisers,
|
||||
@@ -26,7 +26,11 @@
|
||||
# has already checked what the out-of-tree build produced.
|
||||
set -eu
|
||||
B=$1; S=$2; W=$3
|
||||
HIPC=${4:-}; HIPT=${5:-}; VOPD=${6:-OFF}
|
||||
HIPC=${4:-}; HIPT=${5:-}; VOPD=${6:-OFF}; CXXC=${7:-}
|
||||
# The tree's own C++ compiler, so the out-of-tree build does not depend on the host's default
|
||||
# (`c++` may be a different GCC than the one the installed ABI headers require).
|
||||
CCXX=""
|
||||
[ -n "$CXXC" ] && CCXX="-DCMAKE_CXX_COMPILER=$CXXC"
|
||||
GEN=${CMAKE_GENERATOR:-Ninja}
|
||||
J=${CMAKE_BUILD_PARALLEL_LEVEL:-$(nproc 2>/dev/null || echo 4)}
|
||||
|
||||
@@ -64,8 +68,8 @@ is_dev() { case " $devlibs " in *" $1 "*) return 0 ;; esac; return 1; }
|
||||
for d in $dirs; do
|
||||
n=$(basename "$d")
|
||||
say "building $d against the installed package"
|
||||
extra=""
|
||||
is_dev "$n" && extra="-DCMAKE_HIP_COMPILER=$HIPC -DRAD_GPU_TARGETS=$HIPT
|
||||
extra="$CCXX"
|
||||
is_dev "$n" && extra="$extra -DCMAKE_HIP_COMPILER=$HIPC -DRAD_GPU_TARGETS=$HIPT
|
||||
-DRAD_HIP_VOPD_REPEATABLE=$VOPD"
|
||||
# A bundled plugin under plugin/ may carry device rows beside its host ones; it gets the tree's
|
||||
# HIP compiler as a third party would pass theirs.
|
||||
@@ -74,7 +78,12 @@ for d in $dirs; do
|
||||
run "$W/logs/$n.configure.log" cmake -S "$S/$d" -B "$W/b/$n" -G "$GEN" \
|
||||
-DCMAKE_PREFIX_PATH="$P" -DCMAKE_INSTALL_PREFIX="$P" -DRAD_PLUGIN_INSTALL_HOME="$H" $extra
|
||||
run "$W/logs/$n.build.log" cmake --build "$W/b/$n" -j "$J"
|
||||
run "$W/logs/$n.install.log" cmake --install "$W/b/$n"
|
||||
# --prefix for the same reason as the tree install above: a plugin's own CMakeLists may install
|
||||
# companions (libr4d ships r4d_selftest) to relative destinations under CMAKE_INSTALL_PREFIX, and
|
||||
# the test must not need root. The plugins themselves ignore the prefix -- rad_add_plugin installs
|
||||
# them under the absolute RAD_PLUGIN_INSTALL_HOME given at configure time -- so the checks below,
|
||||
# which look in $H, are unaffected.
|
||||
run "$W/logs/$n.install.log" cmake --install "$W/b/$n" --prefix "$W/i"
|
||||
done
|
||||
|
||||
# 1. The same plugins, file for file.
|
||||
|
||||
@@ -124,6 +124,8 @@ template <class T>
|
||||
inline T atomicMax(T* p, T v) { const T o = *p; if (v > o) *p = v; return o; }
|
||||
template <class T>
|
||||
inline T atomicCAS(T* p, T expect, T v) { const T o = *p; if (o == expect) *p = v; return o; }
|
||||
template <class T>
|
||||
inline T atomicExch(T* p, T v) { const T o = *p; *p = v; return o; }
|
||||
/* v_wmma_f32_16x16x16_bf16 (gfx12, wave32): A[M][K] lane M + 16 * (K / 8) element K % 8; B[K][N]
|
||||
* lane N + 16 * (K / 8) element K % 8; D[M][N] lane N + 16 * (M / 8) element M % 8 */
|
||||
typedef short emu_v8s __attribute__((ext_vector_type(8)));
|
||||
|
||||
@@ -0,0 +1,507 @@
|
||||
/* tests/r4d_emu: kv_resolve (libr4d/r4d_kv_resolve.hip) on the host SIMT emulator, every operand
|
||||
* held to a port of libref's ref_kv_resolve (libref/ref_kvstream.cpp) byte for byte: the rewritten
|
||||
* selection, both residency maps, the slot epochs and heat counters, the control block, the mirror
|
||||
* (untouched) and every byte of the ring.
|
||||
*
|
||||
* The fixtures are the shapes the claim list has to survive:
|
||||
*
|
||||
* - a partly resident pool, an eviction, a second chance: the ordinary decode call;
|
||||
* - identity placement and its two exits: ids that fit the ring and take their own slot, an id
|
||||
* whose slot is occupied by a different block (a clash, which walks from the hand without
|
||||
* evicting), ids past the ring, and a full ring of clashes (which is CLOCK, unchanged);
|
||||
* - 2052 claims (four rows of 513, what `--max-num-seqs 4` selects) and 8000 claims at a launch
|
||||
* wide enough to derive a list of 8192 ids;
|
||||
* - 12 claims into 8 slots: more claims than the ring holds, so the unplaceable ones revert
|
||||
* through the selection and the overflow latch is set;
|
||||
* - the two-bit heat counter: a slot hit twice surviving two sweep passes where the one-bit
|
||||
* CLOCK would evict it, a saturated counter halving 3 -> 1 on a pass, and a saturated counter
|
||||
* outlasting a slot that was only placed last call;
|
||||
* - one bump a slot a call however many rows name it, which is the one place the device's
|
||||
* `atomicExch` and a per-entry reference would part company;
|
||||
* - 8200 claims at a launch whose bound (32 rows x 513) exceeds the workgroup's LDS room, so the
|
||||
* claims are gathered into the row's scratch and sorted there; the slots must still be
|
||||
* libref's.
|
||||
*
|
||||
* A claim count is bounded by the launch's entries, `sum_q nsel[q] <= M * sel_pitch`, so every
|
||||
* fixture's claim count is a number the kernel derives rather than one it assumes. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
extern "C" int r4d_rad_kv_resolve(const RadArgs* a, RadStream stream);
|
||||
|
||||
namespace {
|
||||
|
||||
enum { kNOB = 0xEE };
|
||||
|
||||
RadTensor tens(void* p, uint32_t dt, std::vector<int64_t> shape) {
|
||||
RadTensor t{};
|
||||
t.data = p;
|
||||
t.dtype = dt;
|
||||
t.rank = (uint32_t)shape.size();
|
||||
int64_t st = 1;
|
||||
for (int i = (int)shape.size() - 1; i >= 0; --i) {
|
||||
t.shape[i] = shape[i];
|
||||
t.stride[i] = st;
|
||||
st *= shape[i];
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
/* Block `b`'s bytes: a pattern whose block digit is recoverable, so a copy that landed in the wrong
|
||||
* slot shows up in the ring's bytes. */
|
||||
uint8_t block_byte(int64_t b, int64_t i) { return (uint8_t)((29 * b + i) & 0xff); }
|
||||
|
||||
struct Fix {
|
||||
int64_t M = 1, blocks = 1, slots = 1, pitch = 1, bbytes = 8;
|
||||
std::vector<int32_t> sel, nsel, res, sblk, sst, ctl;
|
||||
std::vector<uint8_t> host, pool;
|
||||
|
||||
/* A fresh pool: the maps say what is resident, a free slot holds the marker. */
|
||||
void shape(int64_t M_, int64_t blocks_, int64_t slots_, int64_t pitch_, int64_t bbytes_) {
|
||||
M = M_; blocks = blocks_; slots = slots_; pitch = pitch_; bbytes = bbytes_;
|
||||
sel.assign((size_t)(M * pitch), -1);
|
||||
nsel.assign((size_t)M, 0);
|
||||
res.assign((size_t)blocks, -1);
|
||||
sblk.assign((size_t)slots, -1);
|
||||
sst.assign((size_t)(slots * 2), 0);
|
||||
ctl.assign(16, 0);
|
||||
host.assign((size_t)(blocks * bbytes), 0);
|
||||
pool.assign((size_t)(slots * bbytes), (uint8_t)kNOB);
|
||||
for (int64_t b = 0; b < blocks; ++b)
|
||||
for (int64_t i = 0; i < bbytes; ++i) host[(size_t)(b * bbytes + i)] = block_byte(b, i);
|
||||
}
|
||||
/* Make slot `s` hold block `b`: the map and the bytes, as a resident block leaves them. */
|
||||
void resident(int64_t s, int64_t b) {
|
||||
sblk[(size_t)s] = (int32_t)b;
|
||||
res[(size_t)b] = (int32_t)s;
|
||||
for (int64_t i = 0; i < bbytes; ++i) pool[(size_t)(s * bbytes + i)] = block_byte(b, i);
|
||||
}
|
||||
};
|
||||
|
||||
/* The heat counter's two writes, copied from libref: a use bumps by one and saturates at 3, a
|
||||
* sweep pass halves, and a negative value reads as cold. */
|
||||
int32_t heat_up(int32_t h) { return h < 0 ? 1 : (h < 3 ? h + 1 : 3); }
|
||||
int32_t heat_down(int32_t h) { return h > 0 ? (h >> 1) : 0; }
|
||||
|
||||
/* libref's ref_kv_resolve over a fixture, step for step (libref/ref_kvstream.cpp): the same epoch,
|
||||
* the same one claim per distinct block, the same sorted miss list, the same free-slot-then-CLOCK
|
||||
* sweep over the same two-bit heat counter, the same revert of what it could not place, the same
|
||||
* copies and rewrite. The fixtures are legal calls, so the refusals are not repeated here. */
|
||||
void ref_resolve(Fix& f) {
|
||||
const int64_t M = f.M, blocks = f.blocks, slots = f.slots, pitch = f.pitch, bbytes = f.bbytes;
|
||||
int32_t* const R = f.res.data();
|
||||
int32_t* const SB = f.sblk.data();
|
||||
int32_t* const ST = f.sst.data();
|
||||
int32_t* const C = f.ctl.data();
|
||||
const int64_t stp = 2;
|
||||
|
||||
std::vector<int64_t> off, ent;
|
||||
for (int64_t q = 0; q < M; ++q)
|
||||
for (int64_t i = 0; i < f.nsel[(size_t)q]; ++i) {
|
||||
off.push_back(q * pitch + i);
|
||||
ent.push_back(f.sel[(size_t)(q * pitch + i)]);
|
||||
}
|
||||
|
||||
const int32_t epoch = (int32_t)((uint32_t)C[0] + 1u);
|
||||
|
||||
std::vector<int32_t> miss;
|
||||
for (size_t e = 0; e < ent.size(); ++e) {
|
||||
const int32_t b = (int32_t)ent[e];
|
||||
const int32_t s = R[b];
|
||||
if (s >= 0) {
|
||||
/* One bump a slot a call, not one an entry (libref's step 2). */
|
||||
if (ST[(size_t)s * stp] != epoch) {
|
||||
ST[(size_t)s * stp] = epoch;
|
||||
ST[(size_t)s * stp + 1] = heat_up(ST[(size_t)s * stp + 1]);
|
||||
}
|
||||
} else if (s == -1) {
|
||||
R[b] = -2;
|
||||
miss.push_back(b);
|
||||
}
|
||||
}
|
||||
const int64_t lookups = (int64_t)ent.size();
|
||||
std::sort(miss.begin(), miss.end());
|
||||
|
||||
int64_t free_left = 0;
|
||||
for (int64_t s = 0; s < slots; ++s)
|
||||
if (SB[s] < 0 && ST[(size_t)s * stp] != epoch) ++free_left;
|
||||
int64_t hand = C[1];
|
||||
int64_t placed = 0;
|
||||
bool overflow = false;
|
||||
for (size_t k = 0; k < miss.size(); ++k) {
|
||||
const int32_t b = miss[k];
|
||||
int64_t victim = -1;
|
||||
/* Identity first: the block's own slot if the id fits the ring and that slot is free (or
|
||||
* already holds it), hand untouched (libref's step 4). */
|
||||
if ((int64_t)b < slots && ST[(int64_t)b * stp] != epoch && (SB[b] < 0 || SB[b] == b))
|
||||
victim = b;
|
||||
if (victim < 0 && free_left > 0) {
|
||||
int64_t h = hand;
|
||||
for (int64_t scanned = 0; scanned < slots; ++scanned) {
|
||||
const int64_t s = h;
|
||||
h = h + 1 == slots ? 0 : h + 1;
|
||||
if (ST[(size_t)s * stp] == epoch) continue;
|
||||
if (SB[s] >= 0) continue;
|
||||
victim = s;
|
||||
hand = h;
|
||||
break;
|
||||
}
|
||||
if (victim < 0) free_left = 0;
|
||||
}
|
||||
if (victim < 0) {
|
||||
for (int64_t scanned = 0; scanned < 3 * slots; ++scanned) {
|
||||
const int64_t s = hand;
|
||||
hand = hand + 1 == slots ? 0 : hand + 1;
|
||||
if (ST[(size_t)s * stp] == epoch) continue;
|
||||
if (SB[s] >= 0 && ST[(size_t)s * stp + 1] > 0) {
|
||||
ST[(size_t)s * stp + 1] = heat_down(ST[(size_t)s * stp + 1]);
|
||||
continue;
|
||||
}
|
||||
victim = s;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (victim < 0) { overflow = true; break; }
|
||||
if (SB[victim] < 0 && free_left > 0) --free_left;
|
||||
if (SB[victim] >= 0) R[SB[victim]] = -1;
|
||||
SB[victim] = b;
|
||||
ST[(size_t)victim * stp] = epoch;
|
||||
ST[(size_t)victim * stp + 1] = heat_up(ST[(size_t)victim * stp + 1]);
|
||||
R[b] = (int32_t)victim;
|
||||
++placed;
|
||||
}
|
||||
for (size_t k = (size_t)placed; k < miss.size(); ++k) R[miss[k]] = -1;
|
||||
|
||||
for (int64_t k = 0; k < placed; ++k) {
|
||||
const int32_t b = miss[(size_t)k];
|
||||
std::memcpy(f.pool.data() + (int64_t)R[b] * bbytes, f.host.data() + (int64_t)b * bbytes,
|
||||
(size_t)bbytes);
|
||||
}
|
||||
for (size_t e = 0; e < ent.size(); ++e) {
|
||||
const int32_t s = R[ent[e]];
|
||||
f.sel[(size_t)off[e]] = s >= 0 ? s : 0;
|
||||
}
|
||||
|
||||
int64_t used = 0;
|
||||
for (int64_t s = 0; s < slots; ++s)
|
||||
if (ST[(size_t)s * stp] == epoch) ++used;
|
||||
const int64_t uni = used + (int64_t)miss.size() - placed;
|
||||
C[0] = epoch;
|
||||
C[1] = (int32_t)hand;
|
||||
C[2] = (int32_t)placed;
|
||||
if (overflow) C[3] = 1;
|
||||
if (uni > C[10]) C[10] = (int32_t)uni;
|
||||
if (placed > C[11]) C[11] = (int32_t)placed;
|
||||
if ((int64_t)miss.size() > C[12]) C[12] = (int32_t)miss.size();
|
||||
uint64_t* const ctr = (uint64_t*)(C + 4);
|
||||
ctr[0] += (uint64_t)placed;
|
||||
ctr[1] += (uint64_t)lookups;
|
||||
ctr[2] += 1u;
|
||||
}
|
||||
|
||||
/* The device entry point over a fixture. Its scratch is the row's `next_pow2(slots)` miss-list ids
|
||||
* (the list is sorted there when a launch is too wide for the shared claim list) then `slots`
|
||||
* slots. */
|
||||
int dev_resolve(Fix& f) {
|
||||
int64_t nlist = 1;
|
||||
while (nlist < f.slots) nlist <<= 1;
|
||||
std::vector<int32_t> scratch((size_t)(nlist + f.slots), 0);
|
||||
RadTensor t[8] = { tens(f.sel.data(), RAD_I32, { f.M, f.pitch }),
|
||||
tens(f.nsel.data(), RAD_I32, { f.M }),
|
||||
tens(f.res.data(), RAD_I32, { f.blocks }),
|
||||
tens(f.sblk.data(), RAD_I32, { f.slots }),
|
||||
tens(f.sst.data(), RAD_I32, { f.slots, 2 }),
|
||||
tens(f.ctl.data(), RAD_I32, { 16 }),
|
||||
tens(f.host.data(), RAD_U8, { f.blocks, f.bbytes }),
|
||||
tens(f.pool.data(), RAD_U8, { f.slots, f.bbytes }) };
|
||||
RadParam p[5]{};
|
||||
p[0] = { "M", RAD_P_INT, f.M };
|
||||
p[1] = { "blocks", RAD_P_INT, f.blocks };
|
||||
p[2] = { "slots", RAD_P_INT, f.slots };
|
||||
p[3] = { "sel_pitch", RAD_P_INT, f.pitch };
|
||||
p[4] = { "block_bytes", RAD_P_INT, f.bbytes };
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 8;
|
||||
a.p = p;
|
||||
a.n_p = 5;
|
||||
a.scratch = scratch.data();
|
||||
a.scratch_bytes = (int64_t)scratch.size() * 4;
|
||||
return r4d_rad_kv_resolve(&a, nullptr);
|
||||
}
|
||||
|
||||
size_t mismatch(const std::vector<int32_t>& a, const std::vector<int32_t>& b, const char* what,
|
||||
const char* name) {
|
||||
size_t bad = 0;
|
||||
for (size_t i = 0; i < a.size(); ++i)
|
||||
if (a[i] != b[i]) {
|
||||
if (!bad)
|
||||
std::printf(" FAIL %-42s %s[%zu]: %d, libref %d\n", name, what, i, a[i], b[i]);
|
||||
++bad;
|
||||
}
|
||||
return bad;
|
||||
}
|
||||
|
||||
size_t mismatch_bytes(const std::vector<uint8_t>& a, const std::vector<uint8_t>& b,
|
||||
const char* what, const char* name) {
|
||||
size_t bad = 0;
|
||||
for (size_t i = 0; i < a.size(); ++i)
|
||||
if (a[i] != b[i]) {
|
||||
if (!bad)
|
||||
std::printf(" FAIL %-42s %s[%zu]: %u, libref %u\n", name, what, i, a[i], b[i]);
|
||||
++bad;
|
||||
}
|
||||
return bad;
|
||||
}
|
||||
|
||||
/* One fixture, both ways, every operand compared. */
|
||||
int check(const char* name, Fix f) {
|
||||
std::printf(" .. %s\n", name);
|
||||
std::fflush(stdout);
|
||||
Fix ref = f;
|
||||
ref_resolve(ref);
|
||||
const int rc = dev_resolve(f);
|
||||
if (rc != RAD_OK) {
|
||||
std::printf(" FAIL %-42s refused (%d)\n", name, rc);
|
||||
return 1;
|
||||
}
|
||||
size_t bad = 0;
|
||||
bad += mismatch(f.sel, ref.sel, "sel", name);
|
||||
bad += mismatch(f.res, ref.res, "res", name);
|
||||
bad += mismatch(f.sblk, ref.sblk, "slot_block", name);
|
||||
bad += mismatch(f.sst, ref.sst, "slot_state", name);
|
||||
bad += mismatch(f.ctl, ref.ctl, "ctl", name);
|
||||
bad += mismatch_bytes(f.pool, ref.pool, "kv_cache", name);
|
||||
bad += mismatch_bytes(f.host, ref.host, "host", name);
|
||||
if (bad) return 1;
|
||||
std::printf(" ok %-42s %lld claims, %lld placed\n", name, (long long)ref.ctl[12],
|
||||
(long long)ref.ctl[2]);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* `n` distinct block ids across `M` rows of `pitch` entries, contiguously from `first`. Each row
|
||||
* declares exactly the entries this fills, since `nsel` is what says an entry is valid -- and a
|
||||
* declared entry holding -1 is a state fault, not padding. */
|
||||
void fill_claims(Fix& f, int64_t first, int64_t n, int64_t per_row) {
|
||||
int64_t k = 0;
|
||||
for (int64_t q = 0; q < f.M; ++q) {
|
||||
int64_t take = per_row;
|
||||
if (take > n - k) take = n - k;
|
||||
if (take < 0) take = 0;
|
||||
f.nsel[(size_t)q] = (int32_t)take;
|
||||
for (int64_t i = 0; i < take; ++i, ++k) f.sel[(size_t)(q * f.pitch + i)] = (int32_t)(first + k);
|
||||
}
|
||||
}
|
||||
|
||||
int run_all() {
|
||||
int fails = 0, cases = 0;
|
||||
++cases;
|
||||
{
|
||||
Fix f;
|
||||
f.shape(2, 8, 4, 4, 8);
|
||||
f.resident(0, 2);
|
||||
f.resident(3, 5);
|
||||
f.sel = { 2, 5, 6, -1, 2, 4, -1, -1 };
|
||||
f.nsel = { 3, 2 };
|
||||
f.sst = { 0, 1, 0, 0, 0, 0, 0, 0 };
|
||||
fails += check("a decode call: two hits, two misses, ascending", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* Every slot resident and referenced: the sweep clears four bits and takes the slot the
|
||||
* hand started on, one full turn later. */
|
||||
Fix f;
|
||||
f.shape(1, 8, 4, 2, 4);
|
||||
for (int64_t s = 0; s < 4; ++s) f.resident(s, s + 4);
|
||||
f.sel = { 0, 1 };
|
||||
f.nsel = { 2 };
|
||||
f.sst = { 0, 1, 0, 1, 0, 1, 0, 1 };
|
||||
fails += check("second chance: a full ring clears and wraps", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* 2052 claims, the four-sequence decode shape. */
|
||||
Fix f;
|
||||
f.shape(4, 4096, 2100, 513, 8);
|
||||
fill_claims(f, 100, 2052, 513);
|
||||
fails += check("2052 claims, every slot free", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* A launch wide enough that the list is 8192 ids (32 x 513 = 16416 is past the workgroup's
|
||||
* LDS room), with 8000 claims inside it. */
|
||||
Fix f;
|
||||
f.shape(32, 12000, 8100, 513, 8);
|
||||
fill_claims(f, 200, 8000, 250);
|
||||
fails += check("8000 claims inside a derived 8192-id list", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* More claims than the ring: the eight smallest ids take the eight free slots, the rest
|
||||
* revert through the selection and the overflow latches. */
|
||||
Fix f;
|
||||
f.shape(1, 4096, 8, 12, 8);
|
||||
f.sel = { 4090, 3, 2000, 7, 1, 4000, 5, 9, 11, 2, 100, 500 };
|
||||
f.nsel = { 12 };
|
||||
fails += check("12 claims into 8 slots: the smallest eight", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* 8200 claims against a list of 8192: the launch's bound is past the workgroup's LDS room, so
|
||||
* the kernel gathers the claims from the selection into the row's scratch and sorts them
|
||||
* there. Same slots as libref's sort of all 8200, and no walk of `blocks`. */
|
||||
Fix f;
|
||||
f.shape(32, 12000, 8300, 513, 8);
|
||||
fill_claims(f, 0, 8200, 257);
|
||||
fails += check("8200 claims: sorted in the scratch above the list", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* Identity's two ways out in one call. Block 1's own slot holds block 6, so it is a clash
|
||||
* and takes the first free slot after the hand (0) -- never an eviction. Block 2's slot is
|
||||
* free, so it takes slot 2 even though the hand has moved to 1. */
|
||||
Fix f;
|
||||
f.shape(1, 12, 4, 4, 8);
|
||||
f.resident(1, 6);
|
||||
f.sel = { 1, 2, 8, -1 };
|
||||
f.nsel = { 3 };
|
||||
f.sst = { 0, 1, 0, 0, 0, 0, 0, 0 };
|
||||
fails += check("identity clash falls back to a free slot, then identity again", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* Ids past the ring, the depth case: nothing can be identity, every miss walks from the
|
||||
* hand. */
|
||||
Fix f;
|
||||
f.shape(1, 16, 4, 5, 8);
|
||||
f.sel = { 9, 10, 11, 12, 13 };
|
||||
f.nsel = { 5 };
|
||||
fails += check("ids past the ring: the old free-slot walk, unchanged", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* A full ring of clashing slots: identity has nowhere to go and CLOCK picks the victim the
|
||||
* hand walks to, halving one counter on the way. */
|
||||
Fix f;
|
||||
f.shape(1, 12, 3, 2, 8);
|
||||
f.resident(0, 5);
|
||||
f.resident(1, 6);
|
||||
f.resident(2, 7);
|
||||
f.sel = { 0, 1 };
|
||||
f.nsel = { 2 };
|
||||
f.sst = { 0, 1, 0, 1, 0, 1 };
|
||||
fails += check("identity clash on a full ring: CLOCK, unchanged", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* A ring wider than one thread's chunk with its free slots far from the hand: the sweep
|
||||
* walks the chunk summaries (2100 slots is 3 a thread) and must still name the first free
|
||||
* slot from the hand. Slots 0..2048 hold blocks, 2049 and 2050 are free, and the misses
|
||||
* are ids past the ring, so identity cannot place them. */
|
||||
Fix f;
|
||||
f.shape(1, 6000, 2100, 3, 8);
|
||||
for (int64_t s = 0; s < 2049; ++s) f.resident(s, s);
|
||||
f.sel = { 4000, 4001, 4002 };
|
||||
f.nsel = { 3 };
|
||||
fails += check("free slots in the last chunk, hand at 0", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* The same ring with the hand past the free region: the walk wraps through the chunk
|
||||
* summaries to slots 0 and 1, in that order, and leaves the hand at 2. */
|
||||
Fix f;
|
||||
f.shape(1, 6000, 2100, 3, 8);
|
||||
for (int64_t s = 2; s < 2100; ++s) f.resident(s, s);
|
||||
f.sel = { 4000, 4001, 4002 };
|
||||
f.nsel = { 3 };
|
||||
f.ctl[1] = 2099;
|
||||
fails += check("free slots at slot 0, hand at the end: the walk wraps", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* Heat, the discriminating case: slot 0 was hit twice (counter 2), slots 1 and 2 once each.
|
||||
* A one-bit CLOCK clears all three and evicts slot 0 on the second pass; the counter halves
|
||||
* 2 -> 1 -> 0, so slot 0 survives two passes and slot 1 is the victim. */
|
||||
Fix f;
|
||||
f.shape(1, 32, 3, 1, 8);
|
||||
f.resident(0, 10);
|
||||
f.resident(1, 11);
|
||||
f.resident(2, 12);
|
||||
f.sst = { 0, 2, 0, 1, 0, 1 };
|
||||
f.sel = { 20 };
|
||||
f.nsel = { 1 };
|
||||
fails += check("heat: a slot hit twice survives two passes, CLOCK would take it", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* The halving: a saturated 3 is 1 after one pass, not 0, and the cold slot behind it is the
|
||||
* victim. A one-bit CLOCK clears slot 0 and evicts it. */
|
||||
Fix f;
|
||||
f.shape(1, 32, 3, 1, 8);
|
||||
f.resident(0, 10);
|
||||
f.resident(1, 11);
|
||||
f.resident(2, 12);
|
||||
f.sst = { 0, 3, 0, 0, 0, 0 };
|
||||
f.sel = { 20 };
|
||||
f.nsel = { 1 };
|
||||
fails += check("heat: a saturated counter halves 3 -> 1 on one pass", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* A saturated counter outlasts a slot that was only placed last call: {3,1,1,1} walks two
|
||||
* full laps, leaving the 3 at 1 then 0, and takes slot 1 (counter 1 -> 0 -> victim). Earning
|
||||
* the same state from placements is what test/kvstream's multi-call case does. */
|
||||
Fix f;
|
||||
f.shape(1, 32, 4, 1, 8);
|
||||
for (int64_t s = 0; s < 4; ++s) f.resident(s, 10 + s);
|
||||
f.sst = { 0, 3, 0, 1, 0, 1, 0, 1 };
|
||||
f.sel = { 20 };
|
||||
f.nsel = { 1 };
|
||||
fails += check("heat: a saturated counter outlasts a fresh placement", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* One bump a slot a call: block 10 is resident and named by both entries, so its counter
|
||||
* gains one step (1 -> 2), not two, where a per-entry bump would disagree with the device's
|
||||
* first-stamp `atomicExch`. */
|
||||
Fix f;
|
||||
f.shape(1, 32, 3, 2, 8);
|
||||
f.resident(0, 10);
|
||||
f.resident(1, 11);
|
||||
f.resident(2, 12);
|
||||
f.sst = { 0, 1, 0, 0, 0, 0 };
|
||||
f.sel = { 10, 10 };
|
||||
f.nsel = { 2 };
|
||||
fails += check("heat: a block two entries name gains one step, not two", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* Every miss takes its own slot with a hit and a hand that is not at 0 in play: the
|
||||
* identity fast path must leave the hand exactly where it was and still stamp its slots,
|
||||
* because the fallback never runs. */
|
||||
Fix f;
|
||||
f.shape(1, 12, 8, 6, 8);
|
||||
f.resident(3, 9); /* a resident block the selection does not name */
|
||||
f.ctl[1] = 5;
|
||||
f.sel = { 0, 2, 4, 6, 7 };
|
||||
f.nsel = { 5 };
|
||||
fails += check("identity for every miss, hand untouched", f);
|
||||
}
|
||||
std::printf("%d of %d fixtures match libref\n", cases - fails, cases);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int main() {
|
||||
const int fails = run_all();
|
||||
return fails;
|
||||
}
|
||||
@@ -0,0 +1,411 @@
|
||||
/* ref2va_pack_test.cpp -- the Ref2VA packing against golden vectors produced by the reference
|
||||
* implementation itself.
|
||||
*
|
||||
* arch/minimaxh3/rad_ref2va_pack.cpp is pure host arithmetic, so it is compiled straight in here --
|
||||
* no rad_core, no device. tests/data/ref2va/golden.json is generated by gen_golden.py, which runs
|
||||
* the reference PackedLayout (from the MiniMax-H3 model file of a ComfyUI install) over the cases;
|
||||
* every expectation below is the reference's own output, not a re-derivation. The positions are
|
||||
* compared after a float64 -> float cast, bit for bit: both sides run the same IEEE double
|
||||
* operations, so an exact match is the contract -- a ULP drift would mean the port reordered the
|
||||
* arithmetic.
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
#include "rad_ref2va_pack.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
|
||||
using namespace minimaxh3;
|
||||
|
||||
namespace {
|
||||
|
||||
nlohmann::json& golden() {
|
||||
static nlohmann::json g = [] {
|
||||
std::ifstream f(std::string(RAD_REF2VA_GOLDEN) + "/golden.json");
|
||||
if (!f.is_open()) {
|
||||
fprintf(stderr, " FAIL golden.json missing -- regenerate with "
|
||||
"tests/data/ref2va/gen_golden.py\n");
|
||||
std::exit(1);
|
||||
}
|
||||
return nlohmann::json::parse(f);
|
||||
}();
|
||||
return g;
|
||||
}
|
||||
|
||||
/* The reference's names for the segment kinds. */
|
||||
const char* kind_name(int kind) {
|
||||
static const char* const kNames[kR2VKinds] = { "text", "cond", "cond_audio", "ref_img",
|
||||
"ref_audio", "audio", "video" };
|
||||
return kind >= 0 && kind < kR2VKinds ? kNames[kind] : "?";
|
||||
}
|
||||
|
||||
int ref_kind(const std::string& s) {
|
||||
if (s == "image") return kR2VRefImage;
|
||||
if (s == "audio") return kR2VRefAudioOnly;
|
||||
if (s == "video") return kR2VRefVideo;
|
||||
if (s == "video_audio") return kR2VRefVideoAudio;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* The pack `name`'s case asks for, built. */
|
||||
Ref2VAPack build_case(const nlohmann::json& c) {
|
||||
Ref2VAGeom g{ c["latent_t"], c["latent_h"], c["latent_w"], c["audio_t"] };
|
||||
std::vector<Ref2VAKeyframe> kfs;
|
||||
for (const auto& k : c["keyframes"])
|
||||
kfs.push_back({ k["frame"], k["video_t"], k["audio_t"] });
|
||||
std::vector<Ref2VARef> refs;
|
||||
for (const auto& r : c["refs"])
|
||||
refs.push_back({ ref_kind(r["kind"].get<std::string>()), r["latent_h"], r["latent_w"],
|
||||
r["latent_t"], r["ref_audio_t"] });
|
||||
Ref2VAPack p;
|
||||
CHECK_EQ(ref2va_build(c["text_len"], g, kfs, refs, &p), 0);
|
||||
return p;
|
||||
}
|
||||
|
||||
void check_case(const std::string& name) {
|
||||
const nlohmann::json& c = golden()[name];
|
||||
const Ref2VAPack p = build_case(c);
|
||||
|
||||
CHECK_EQ(p.rows, c["seq_len"].get<int64_t>());
|
||||
CHECK_EQ((int64_t)p.pos.size(), p.rows * 3);
|
||||
|
||||
const auto& segs = c["segments"];
|
||||
CHECK_EQ(p.segs.size(), segs.size());
|
||||
for (size_t i = 0; i < p.segs.size() && i < segs.size(); ++i) {
|
||||
CHECK_EQ(p.segs[i].start, segs[i][0].get<int64_t>());
|
||||
CHECK_EQ(p.segs[i].end, segs[i][1].get<int64_t>());
|
||||
CHECK(std::string(kind_name(p.segs[i].kind)) == segs[i][2].get<std::string>());
|
||||
const std::string kind = segs[i][2].get<std::string>();
|
||||
CHECK_EQ(p.segs[i].update, kind == "audio" || kind == "video" ? 1 : 0);
|
||||
}
|
||||
|
||||
/* Positions, bit for bit after the float cast: a coordinate drawn a different way in double
|
||||
* can round to the same f32 and still bend a rotary the next latent over. */
|
||||
const auto& gp = c["positions"];
|
||||
for (size_t i = 0; i < gp.size(); ++i)
|
||||
for (int j = 0; j < 3; ++j) {
|
||||
const float want = (float)gp[i][j].get<double>();
|
||||
if (p.pos[(int64_t)j * p.rows + i] != want) {
|
||||
::radtest::fail(__FILE__, __LINE__,
|
||||
std::string(name) + ": row " + std::to_string(i) + " axis "
|
||||
+ std::to_string(j) + " is "
|
||||
+ std::to_string(p.pos[(int64_t)j * p.rows + i])
|
||||
+ ", want " + std::to_string(want));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/* The two latent spaces' row index lists and their update flags, rebuilt from the pack's
|
||||
* segments the way the sampler scatters them, against the reference's concatenated lists. */
|
||||
std::vector<int64_t> img_pos, audio_pos;
|
||||
std::vector<int> img_up, audio_up;
|
||||
for (const Ref2VASeg& s : p.segs) {
|
||||
for (int64_t r = s.start; r < s.end; ++r) {
|
||||
if (ref2va_is_img(s.kind)) { img_pos.push_back(r); img_up.push_back(s.update); }
|
||||
if (ref2va_is_audio(s.kind)) { audio_pos.push_back(r); audio_up.push_back(s.update); }
|
||||
}
|
||||
}
|
||||
CHECK(img_pos == c["img_pos"].get<std::vector<int64_t>>());
|
||||
CHECK(audio_pos == c["audio_pos"].get<std::vector<int64_t>>());
|
||||
std::vector<int> giu, gau;
|
||||
for (const auto& b : c["img_update"]) giu.push_back(b.get<int>());
|
||||
for (const auto& b : c["audio_update"]) gau.push_back(b.get<int>());
|
||||
CHECK(img_up == giu);
|
||||
CHECK(audio_up == gau);
|
||||
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
TEST(pack_golden_t2va) { check_case("t2va"); }
|
||||
TEST(pack_golden_fl2va) { check_case("fl2va"); }
|
||||
TEST(pack_golden_ref2va_all) { check_case("ref2va_all"); }
|
||||
TEST(pack_golden_chain) { check_case("chain"); }
|
||||
TEST(pack_golden_no_text) { check_case("no_text"); }
|
||||
|
||||
TEST(pack_rejects_negative_dims) {
|
||||
Ref2VAPack p;
|
||||
Ref2VAGeom g{ 2, 4, 4, 1 };
|
||||
CHECK_EQ(ref2va_build(-1, g, {}, {}, &p), -1);
|
||||
CHECK_EQ(ref2va_build(0, Ref2VAGeom{ -1, 4, 4, 1 }, {}, {}, &p), -1);
|
||||
CHECK_EQ(ref2va_build(0, g, { { -1, 1, 0 } }, {}, &p), -1);
|
||||
CHECK_EQ(ref2va_build(0, g, {}, { { kR2VRefImage, -4, 4, 0, 0 } }, &p), -1);
|
||||
CHECK_EQ(ref2va_build(0, g, {}, { { 7, 4, 4, 0, 0 } }, &p), -1);
|
||||
}
|
||||
|
||||
TEST(pack_plain_matches_the_three_segment_order) {
|
||||
/* With no references the pack is the text-to-video sequence [text | audio | video], the
|
||||
* sampler owning the audio and video rows and nothing owning the prompt. */
|
||||
Ref2VAPack p;
|
||||
Ref2VAGeom g{ 3, 8, 10, 4 };
|
||||
CHECK_EQ(ref2va_build(5, g, {}, {}, &p), 0);
|
||||
CHECK_EQ(p.segs.size(), 3u);
|
||||
CHECK_EQ(p.segs[0].kind, kR2VText);
|
||||
CHECK_EQ(p.segs[1].kind, kR2VAudio);
|
||||
CHECK_EQ(p.segs[2].kind, kR2VVideo);
|
||||
CHECK_EQ(p.segs[0].update, 0);
|
||||
CHECK_EQ(p.segs[1].update, 1);
|
||||
CHECK_EQ(p.segs[2].update, 1);
|
||||
CHECK_EQ(p.segs[0].start, 0);
|
||||
CHECK_EQ(p.segs[0].end, 5); /* the prompt */
|
||||
CHECK_EQ(p.segs[1].start, 5); /* 2 channels x 4 audio latents */
|
||||
CHECK_EQ(p.segs[1].end, 5 + 8);
|
||||
CHECK_EQ(p.segs[2].start, 5 + 8); /* 3 latents x (8/2)(10/2) patches */
|
||||
CHECK_EQ(p.segs[2].end, 5 + 8 + 60);
|
||||
CHECK_EQ(p.rows, 5 + 8 + 60);
|
||||
CHECK_EQ(p.pos.size(), (size_t)(3 * p.rows)); /* planar, the shape R_ROPE stages */
|
||||
/* The rows' positions, axis by axis: the prompt counts up on time and ignores space; the
|
||||
* soundtrack runs channel-major (all of the left, then the right) at height 0 on the width
|
||||
* axis' two ends; every video row carries its frame's time. */
|
||||
const int64_t rows = p.rows;
|
||||
for (int64_t i = 0; i < 5; ++i) {
|
||||
CHECK_EQ(p.pos[(size_t)i], (float)i);
|
||||
CHECK_EQ(p.pos[(size_t)rows + i], 0.0f);
|
||||
CHECK_EQ(p.pos[(size_t)(2 * rows) + i], 0.0f);
|
||||
}
|
||||
for (int ch = 0; ch < 2; ++ch)
|
||||
for (int k = 0; k < 4; ++k) {
|
||||
const size_t r = (size_t)(5 + ch * 4 + k);
|
||||
CHECK_EQ(p.pos[r], (float)(5 + k)); /* time counts per channel, not per row */
|
||||
CHECK_EQ(p.pos[rows + r], 0.0f);
|
||||
}
|
||||
/* The channels sit at the opposite ends of the width axis, and they are different. */
|
||||
CHECK(p.pos[2 * rows + 5] != p.pos[2 * rows + 9]);
|
||||
/* Video rows: the first frame's time is the timeline origin (text_len + all reference
|
||||
* spans -- none here); 20 rows (4x5 patches) per frame, h-major; and frame k+1's time is
|
||||
* frame k's plus 5/3 * kPattern[k % 5]. */
|
||||
const size_t v0 = 5 + 8;
|
||||
const int64_t fpp = 4 * 5;
|
||||
CHECK_EQ(p.pos[v0], 5.0f);
|
||||
CHECK_EQ(p.pos[v0 + 1], 5.0f); /* still frame 0 */
|
||||
CHECK_EQ(p.pos[v0 + fpp], (float)(5.0 + 5.0 / 3.0)); /* frame 1, span 1 · 5/3 */
|
||||
CHECK_EQ(p.pos[(size_t)(rows + v0)], p.pos[(size_t)(rows + v0 + 1)]); /* same patch row */
|
||||
CHECK(p.pos[(size_t)(rows + v0)] != p.pos[(size_t)(rows + v0 + 5)]); /* y = 1 begins */
|
||||
}
|
||||
|
||||
TEST(pack_ref_kinds_predicates) {
|
||||
CHECK_EQ(ref2va_seg_tag(kR2VText), 1);
|
||||
CHECK_EQ(ref2va_seg_tag(kR2VVideo), 0);
|
||||
CHECK_EQ(ref2va_seg_tag(kR2VAudio), 2);
|
||||
CHECK_EQ(ref2va_seg_tag(kR2VCond), 0);
|
||||
CHECK_EQ(ref2va_seg_tag(kR2VCondAudio), 2);
|
||||
CHECK_EQ(ref2va_is_img(kR2VText), 0);
|
||||
CHECK(ref2va_is_img(kR2VCond) && ref2va_is_img(kR2VRefImg) && ref2va_is_img(kR2VVideo));
|
||||
CHECK(ref2va_is_audio(kR2VCondAudio) && ref2va_is_audio(kR2VRefAudio)
|
||||
&& ref2va_is_audio(kR2VAudio));
|
||||
CHECK(!ref2va_is_audio(kR2VRefImg) && !ref2va_is_img(kR2VRefAudio));
|
||||
}
|
||||
|
||||
TEST(pack_mod_groups_images_collapse_to_four) {
|
||||
/* Nine reference photos, the most a request carries. Every photo is a video-pinned block
|
||||
* reading the same modulation cell, so the nine merge into one group and the sequence has
|
||||
* four (prompt, photos, soundtrack, video) whatever the photo count. The merge is what fits
|
||||
* the request's twelve segments into the plugin's kMaxSegs modulation groups. */
|
||||
Ref2VAGeom g{ 2, 8, 8, 3 };
|
||||
std::vector<Ref2VARef> refs(9, Ref2VARef{ kR2VRefImage, 6, 6, 1, 0 });
|
||||
Ref2VAPack p;
|
||||
CHECK_EQ(ref2va_build(7, g, {}, refs, &p), 0);
|
||||
CHECK_EQ(p.segs.size(), 12u); /* text + 9 photos + audio + video */
|
||||
|
||||
const int64_t S = 24;
|
||||
Ref2VAModGroups grp;
|
||||
ref2va_mod_groups(p, S, {}, &grp);
|
||||
CHECK_EQ(grp.md.size(), 4u);
|
||||
CHECK(grp.md == std::vector<int>({ 1, 0, 2, 0 })); /* text, photos, audio, video */
|
||||
/* Cells: text and the video target read the video schedule (r0 = 0), the photos the
|
||||
* video-pinned block (2S), the soundtrack the audio schedule (S). */
|
||||
CHECK(grp.r0 == std::vector<int64_t>({ 0, 2 * S, S, 0 }));
|
||||
CHECK_EQ(grp.bound.size(), 5u);
|
||||
CHECK_EQ(grp.bound.front(), 0);
|
||||
CHECK_EQ(grp.bound.back(), p.rows);
|
||||
/* The photo group spans the whole run of reference rows, from the prompt's end to the
|
||||
* soundtrack's start: the two segment boundaries that survive the merge. */
|
||||
const int64_t text_end = p.segs[0].end, audio_start = p.segs[p.segs.size() - 2].start;
|
||||
CHECK_EQ(grp.bound[1], text_end);
|
||||
CHECK_EQ(grp.bound[2], audio_start);
|
||||
}
|
||||
|
||||
TEST(pack_mod_groups_pin_each_stream_at_its_own_block) {
|
||||
/* A picture and a standalone soundtrack: each reads its own stream's pinned embeddings, the
|
||||
* video's at 2S and the soundtrack's at 3S. */
|
||||
Ref2VAGeom g{ 2, 8, 8, 3 };
|
||||
const std::vector<Ref2VARef> refs = { { kR2VRefImage, 4, 4, 1, 0 },
|
||||
{ kR2VRefAudioOnly, 0, 0, 0, 2 } };
|
||||
Ref2VAPack p;
|
||||
CHECK_EQ(ref2va_build(5, g, {}, refs, &p), 0);
|
||||
const int64_t S = 10;
|
||||
Ref2VAModGroups grp;
|
||||
ref2va_mod_groups(p, S, {}, &grp);
|
||||
CHECK(grp.md == std::vector<int>({ 1, 0, 2, 2, 0 }));
|
||||
CHECK(grp.r0 == std::vector<int64_t>({ 0, 2 * S, 3 * S, S, 0 }));
|
||||
}
|
||||
|
||||
TEST(pack_mod_groups_invariants_over_the_goldens) {
|
||||
/* For every golden pack: the group boundaries span the sequence and are a strictly increasing
|
||||
* subset of the segment boundaries, so no segment is split; every segment lies inside one
|
||||
* group of its own modality; no two adjacent groups share a cell, so the merge is maximal; and
|
||||
* the groups do not depend on the step count S. rad_arch_video_pack derives them at S = 1 and
|
||||
* the step at the model's S, and the two tables must line up. */
|
||||
for (const char* name : { "t2va", "fl2va", "ref2va_all", "chain", "no_text" }) {
|
||||
const Ref2VAPack p = build_case(golden()[name]);
|
||||
Ref2VAModGroups a, b;
|
||||
ref2va_mod_groups(p, 1, {}, &a);
|
||||
ref2va_mod_groups(p, 64, {}, &b);
|
||||
CHECK(a.bound == b.bound);
|
||||
CHECK(!a.bound.empty());
|
||||
CHECK_EQ(a.bound.front(), 0);
|
||||
CHECK_EQ(a.bound.back(), p.rows);
|
||||
for (size_t i = 0; i + 1 < a.bound.size(); ++i)
|
||||
CHECK(a.bound[i] < a.bound[i + 1]);
|
||||
/* every boundary is a fine boundary (a segment start, or the closing rows count) */
|
||||
for (int64_t x : a.bound) {
|
||||
bool found = (x == p.rows);
|
||||
for (const Ref2VASeg& s : p.segs) if (s.start == x) found = true;
|
||||
CHECK(found);
|
||||
}
|
||||
/* every fine segment sits whole in a group carrying its own modality */
|
||||
for (const Ref2VASeg& s : p.segs) {
|
||||
if (s.end <= s.start) continue;
|
||||
size_t g = 0;
|
||||
while (g + 1 < a.bound.size() && a.bound[g + 1] <= s.start) ++g;
|
||||
CHECK(a.bound[g] <= s.start && s.end <= a.bound[g + 1]);
|
||||
CHECK_EQ(a.md[a.col[g]], ref2va_seg_tag(s.kind));
|
||||
}
|
||||
/* Adjacent groups differ in cell, and two groups share a column exactly when they read the
|
||||
* same cell: a cond photo and a ref photo separated by a soundtrack are two groups on one
|
||||
* column. Mirrors the pack's cell_of_kind at a's S. */
|
||||
const int64_t S = 1;
|
||||
auto cell = [S](int kind) -> std::pair<int, int64_t> {
|
||||
switch (kind) {
|
||||
case kR2VAudio: return { 2, S }; break; /* audio schedule */
|
||||
case kR2VCondAudio:
|
||||
case kR2VRefAudio: return { 2, 3 * S }; break; /* audio-pinned block */
|
||||
case kR2VText: return { 1, 0 }; break; /* video schedule */
|
||||
case kR2VCond:
|
||||
case kR2VRefImg: return { 0, 2 * S }; break; /* video-pinned block */
|
||||
default: return { 0, 0 }; break; /* video target */
|
||||
}
|
||||
};
|
||||
auto kind_at = [&p](int64_t row) {
|
||||
for (const Ref2VASeg& s : p.segs)
|
||||
if (s.start <= row && row < s.end) return s.kind;
|
||||
return -1;
|
||||
};
|
||||
for (size_t i = 0; i + 1 < a.col.size(); ++i) CHECK(a.col[i] != a.col[i + 1]);
|
||||
std::vector<char> used(a.md.size(), 0);
|
||||
for (size_t i = 0; i < a.col.size(); ++i) {
|
||||
CHECK(a.col[i] >= 0 && (size_t)a.col[i] < a.md.size());
|
||||
used[a.col[i]] = 1;
|
||||
const std::pair<int, int64_t> c = cell(kind_at(a.bound[i]));
|
||||
CHECK_EQ(a.md[a.col[i]], c.first);
|
||||
CHECK_EQ(a.r0[a.col[i]], c.second);
|
||||
for (size_t j = 0; j < i; ++j)
|
||||
CHECK_EQ((int)(a.col[i] == a.col[j]),
|
||||
(int)(cell(kind_at(a.bound[i])) == cell(kind_at(a.bound[j]))));
|
||||
}
|
||||
for (char u : used) CHECK(u); /* every column is addressed */
|
||||
}
|
||||
}
|
||||
|
||||
TEST(pack_mod_groups_plain_equals_the_fine_table) {
|
||||
/* A plain [text | audio | video] pack has three distinct cells, so its groups are its three
|
||||
* segments with the same boundaries: text-to-video modulates exactly as without the merge. */
|
||||
Ref2VAPack p;
|
||||
Ref2VAGeom g{ 3, 8, 10, 4 };
|
||||
CHECK_EQ(ref2va_build(5, g, {}, {}, &p), 0);
|
||||
Ref2VAModGroups grp;
|
||||
ref2va_mod_groups(p, 32, {}, &grp);
|
||||
CHECK_EQ(grp.md.size(), 3u);
|
||||
CHECK(grp.md == std::vector<int>({ 1, 2, 0 })); /* text, audio, video */
|
||||
CHECK(grp.r0 == std::vector<int64_t>({ 0, 32, 0 })); /* video sched, audio sched, video */
|
||||
CHECK_EQ(grp.bound.size(), 4u);
|
||||
CHECK(grp.bound == std::vector<int64_t>({ 0, 5, 13, 5 + 8 + 60 }));
|
||||
}
|
||||
|
||||
TEST(pack_mod_groups_pad_run_cuts_the_prompt) {
|
||||
/* One vision-pad run inside the prompt: ComfyUI tags those rows video, so they form a group
|
||||
* reading the video projection on the prompt's timestep block. The text pieces before and
|
||||
* after the pad share one cell, and the pad shares the video target's: three cells for five
|
||||
* groups. */
|
||||
Ref2VAPack p;
|
||||
Ref2VAGeom g{ 3, 8, 10, 4 };
|
||||
CHECK_EQ(ref2va_build(5, g, {}, {}, &p), 0);
|
||||
const int64_t S = 32;
|
||||
Ref2VAModGroups grp;
|
||||
ref2va_mod_groups(p, S, { Ref2VATagRun{ 1, 3, 0 } }, &grp);
|
||||
CHECK(grp.bound == std::vector<int64_t>({ 0, 1, 3, 5, 13, 5 + 8 + 60 }));
|
||||
CHECK(grp.col == std::vector<int>({ 0, 1, 0, 2, 1 })); /* text, pad, text, audio, video */
|
||||
CHECK(grp.md == std::vector<int>({ 1, 0, 2 }));
|
||||
CHECK(grp.r0 == std::vector<int64_t>({ 0, 0, S })); /* pad on the video schedule */
|
||||
}
|
||||
|
||||
TEST(pack_mod_groups_many_pads_stay_few_cells) {
|
||||
/* Nine reference photos, each with its pad run and prompt text between: the groups multiply
|
||||
* (text and pad alternate), the DISTINCT CELLS do not -- four: text, pad/video, the photos'
|
||||
* pinned video cell, the soundtrack. This is the merge the fixed modulation table rides. */
|
||||
Ref2VAGeom g{ 2, 8, 8, 3 };
|
||||
std::vector<Ref2VARef> refs(9, Ref2VARef{ kR2VRefImage, 6, 6, 1, 0 });
|
||||
Ref2VAPack p;
|
||||
CHECK_EQ(ref2va_build(100, g, {}, refs, &p), 0);
|
||||
std::vector<Ref2VATagRun> runs;
|
||||
for (int i = 0; i < 9; ++i) runs.push_back({ (int64_t)i * 10 + 1, (int64_t)i * 10 + 3, 0 });
|
||||
const int64_t S = 24;
|
||||
Ref2VAModGroups grp;
|
||||
ref2va_mod_groups(p, S, runs, &grp);
|
||||
CHECK_EQ(grp.col.size(), 22u); /* 19 prompt pieces + photos + soundtrack + video */
|
||||
CHECK_EQ(grp.md.size(), 4u); /* ... over four cells */
|
||||
CHECK(grp.md == std::vector<int>({ 1, 0, 0, 2 })); /* text, pad, photo-pinned, audio */
|
||||
CHECK(grp.r0 == std::vector<int64_t>({ 0, 0, 2 * S, S }));
|
||||
/* The video target shares the pad's cell and column; the photo group shares the pad's
|
||||
* projection but not its block. */
|
||||
CHECK_EQ(grp.col.front(), 0);
|
||||
CHECK_EQ(grp.col[1], 1);
|
||||
CHECK_EQ(grp.col.back(), 1);
|
||||
CHECK_EQ(grp.bound.front(), 0);
|
||||
CHECK_EQ(grp.bound.back(), p.rows);
|
||||
}
|
||||
|
||||
TEST(pack_mod_groups_runs_are_normalised) {
|
||||
/* Runs arrive as the driver staged them: unsorted, partly outside the prompt, even empty. The
|
||||
* merge clamps each to the text segment, drops what falls outside, and the result is the same
|
||||
* cut as hand-placed in-range runs. A run covering the whole prompt leaves one pad group and
|
||||
* NO text group; an out-of-range run cuts nothing at all. */
|
||||
Ref2VAPack p;
|
||||
Ref2VAGeom g{ 3, 8, 10, 4 };
|
||||
CHECK_EQ(ref2va_build(5, g, {}, {}, &p), 0);
|
||||
const int64_t S = 32;
|
||||
Ref2VAModGroups one, a, b;
|
||||
ref2va_mod_groups(p, S, { Ref2VATagRun{ 1, 5, 0 } }, &one);
|
||||
/* Same cut: out-of-range tails, an empty run, a run starting before the prompt and one ending
|
||||
* at its start, in scrambled order. The two in-range fragments meet and merge into one pad
|
||||
* group [1,5), exactly the single-run table. */
|
||||
ref2va_mod_groups(p, S,
|
||||
{ Ref2VATagRun{ 4, 9, 0 }, Ref2VATagRun{ 3, 6, 0 }, Ref2VATagRun{ 1, 3, 0 },
|
||||
Ref2VATagRun{ 2, 2, 0 }, Ref2VATagRun{ -4, 0, 0 } },
|
||||
&a);
|
||||
CHECK(a.bound == one.bound);
|
||||
CHECK(a.col == one.col);
|
||||
ref2va_mod_groups(p, S, { Ref2VATagRun{ 5, 9, 0 } }, &b); /* starts at the segment end */
|
||||
CHECK_EQ(b.col.size(), 3u); /* untouched: the plain three groups */
|
||||
CHECK(b.col == std::vector<int>({ 0, 1, 2 }));
|
||||
}
|
||||
|
||||
TEST(pack_mod_groups_pad_tag_audio_reads_the_audio_projection) {
|
||||
/* A run carries its tag: a tag-2 (audio) run on the prompt opens the (2, 0) cell, distinct
|
||||
* from the text's and from the audio target's (2, S). The driver emits only tag 0 runs. */
|
||||
Ref2VAPack p;
|
||||
Ref2VAGeom g{ 3, 8, 10, 4 };
|
||||
CHECK_EQ(ref2va_build(5, g, {}, {}, &p), 0);
|
||||
Ref2VAModGroups grp;
|
||||
ref2va_mod_groups(p, 16, { Ref2VATagRun{ 0, 5, 2 } }, &grp);
|
||||
/* The run covers the whole prompt, so the text group is entirely pad: three groups over three
|
||||
* distinct cells -- (2,0) pad, (2,16) audio target, (0,0) video target. */
|
||||
CHECK(grp.bound == std::vector<int64_t>({ 0, 5, 13, 73 }));
|
||||
CHECK(grp.md == std::vector<int>({ 2, 2, 0 }));
|
||||
CHECK(grp.r0 == std::vector<int64_t>({ 0, 16, 0 }));
|
||||
CHECK(grp.col == std::vector<int>({ 0, 1, 2 }));
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
+1117
-6
File diff suppressed because it is too large.
Load diff
@@ -18,6 +18,9 @@
|
||||
#include "runtime/ctx.h"
|
||||
#include "runtime/kvbind.h"
|
||||
#include "mem/kv.h"
|
||||
#include "kvstream/bind.h"
|
||||
#include "kvstream/plan.h"
|
||||
#include "kvstream/stage.h"
|
||||
#include "runtime/rank_barrier.h"
|
||||
#include "runtime/residency.h"
|
||||
#include "runtime/wtab.h"
|
||||
@@ -1696,6 +1699,9 @@ TEST(too_many_operands_or_an_unknown_handle_is_refused) {
|
||||
/* ================================================================== KV operands */
|
||||
namespace {
|
||||
alignas(64) uint16_t g_kv_pool[4 * 2048];
|
||||
/* One layer of a 13-layer group's context: [8 blocks, 2 heads, 4 tokens, 2*4] fp8 = 512 B. A
|
||||
* prefill pool for a streamed group is this deep, not 13 of these. */
|
||||
alignas(64) uint8_t g_alias_pool[8 * 2 * 4 * 2 * 4];
|
||||
|
||||
/* Group 1: full attention over layers 3, 7 and 11, rank 4. Group 2: a conv state, rank 3, over
|
||||
* layer 0. Group 0 is the sentinel every handle table carries, with no pool. */
|
||||
@@ -1802,6 +1808,132 @@ TEST(kv_pools_bind_each_layer_to_its_place_in_the_group) {
|
||||
CHECK_EQ(b[3].layer_slot[2], 0);
|
||||
}
|
||||
|
||||
/* A streamed group's prefill pool is ONE layer deep and every layer of the group addresses it.
|
||||
*
|
||||
* Above `qsa_exact_to` one prefill launch selects 70-100% of the live history (docs/KV-STREAMING.md
|
||||
* §3.5), so a decode-sized ring overflows and the prefill path stages one layer's history into an
|
||||
* identity-layout buffer instead. Layer L is staged into that buffer, read, and then overwritten by
|
||||
* layer L+1, so the buffer is one layer deep rather than `n_layers` deep: 128 MiB at 262K fp8 on
|
||||
* two ranks, against 1.66 GiB.
|
||||
*
|
||||
* The operand resolution accepts it, and the depth is the whole arithmetic: `layer_slot` is a
|
||||
* lookup and the only bound is `off + layer_stride <= bytes` (runtime/issue.cpp:781-789), which a
|
||||
* one-layer-deep pool satisfies at `off == 0` for every layer. This case pins that, pins that an
|
||||
* identity table over the same pool is refused (so the depth is not silently tolerated), and pins
|
||||
* the two facts that make aliasing a *binding* change rather than a hand-built layer table: the
|
||||
* same table is the host mirror's row (`rad_kv_layer_index`, arch/common/rad_arch.h:1028-1032), so
|
||||
* mapping every layer to 0 collapses the mirror; and bind_kv_pools derives the table from each
|
||||
* layer's position in the group, so an aliased table cannot come from it. */
|
||||
TEST(a_streamed_groups_layers_may_all_alias_one_pool_slot) {
|
||||
const int64_t n_blocks = 8, heads = 2, block = 4, hd = 4;
|
||||
const int64_t lbpb = heads * block * 2 * hd; /* one block of ONE layer */
|
||||
const int64_t stride = n_blocks * lbpb; /* one whole layer: the stage's depth */
|
||||
const int64_t shape[4] = { n_blocks, heads, block, 2 * hd };
|
||||
const int64_t st[4] = { heads * block * 2 * hd, block * 2 * hd, 2 * hd, 1 };
|
||||
|
||||
Fixture f;
|
||||
f.kv.assign(2, rad::KVPoolBinding{});
|
||||
rad::KVPoolBinding& alias = f.kv[1];
|
||||
alias.base = g_alias_pool;
|
||||
alias.layer_stride = stride;
|
||||
alias.bytes = stride; /* 13 layers share these bytes */
|
||||
alias.depth = 1; /* every layer resolves to offset 0 */
|
||||
alias.dtype = RAD_F8E4M3;
|
||||
alias.layer_slot.assign(13, 0);
|
||||
for (int l = 0; l < 13; ++l) alias.layer_slot[(size_t)l] = l; /* the MIRROR row */
|
||||
alias.rank = 4;
|
||||
for (int d = 0; d < 4; ++d) alias.shape[d] = shape[d];
|
||||
rad_op op = loose_op(f, "attn_paged");
|
||||
CHECK_OK(f.start());
|
||||
|
||||
/* The recorder keeps eight operands, so the 13 layers go in two issues. Every layer reads the
|
||||
* same pool base because `depth` is 1, and the operand's shape follows the stage view. */
|
||||
for (int first = 0; first < 13; first += 8) {
|
||||
const int last = first + 8 < 13 ? first + 8 : 13;
|
||||
std::vector<RadOperand> some;
|
||||
for (int l = first; l < last; ++l) some.push_back(RAD_KV(1, l));
|
||||
CHECK_OK(issue_once(f, first, op, some));
|
||||
REQUIRE_EQ(g_rec.size(), (size_t)1);
|
||||
REQUIRE_EQ(g_rec[0].n_t, last - first);
|
||||
for (int l = first; l < last; ++l) {
|
||||
const RadTensor& t = g_rec[0].t[l - first];
|
||||
CHECK(t.data == (void*)g_alias_pool);
|
||||
CHECK_EQ((int)t.rank, 4);
|
||||
CHECK_EQ((int)t.dtype, (int)RAD_F8E4M3);
|
||||
for (int d = 0; d < 4; ++d) {
|
||||
CHECK_EQ(t.shape[d], shape[d]);
|
||||
CHECK_EQ(t.stride[d], st[d]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* The mirror's row comes from the same lookup, which is why aliasing has to be a depth of the
|
||||
* binding and not a rewritten layer_slot: with depth 1 every layer would read layer 0's mirror
|
||||
* row. The lookup itself is untouched and still positional. */
|
||||
for (int l = 0; l < 13; ++l) CHECK_EQ(f.ctx.kv_layer_index(1, l), (int64_t)l);
|
||||
|
||||
/* The same one-layer-deep pool with depth 0 is a positional table, and `bytes` is the only
|
||||
* bound: it serves exactly layer 0 and refuses the rest. This is what makes the aliasing a
|
||||
* deliberate depth rather than something issue.cpp silently tolerates. */
|
||||
Fixture g;
|
||||
g.kv.assign(2, rad::KVPoolBinding{});
|
||||
g.kv[1] = alias;
|
||||
g.kv[1].depth = 0;
|
||||
for (int l = 0; l < 13; ++l) g.kv[1].layer_slot[(size_t)l] = l;
|
||||
rad_op op_g = loose_op(g, "attn_paged");
|
||||
CHECK_OK(g.start());
|
||||
refused(g, issue_once(g, 0, op_g, { RAD_KV(1, 1) }), RAD_E_INVAL, "outside the");
|
||||
next_step_clean(g, 1, op_g, { RAD_KV(1, 0) });
|
||||
|
||||
/* The plan's arithmetic: the ring is n_slots blocks of every layer, the stage is the context
|
||||
* one layer deep, and the carve is their maximum, never their sum. */
|
||||
rad::KVGroupPlan p;
|
||||
p.kind = RAD_KV_FULL;
|
||||
p.n_layers = 13;
|
||||
p.n_blocks = n_blocks;
|
||||
p.n_slots = 2; /* a decode-sized ring, smaller than the context */
|
||||
p.depth = 1;
|
||||
p.block_size = block;
|
||||
p.bytes_per_block = 13 * lbpb;
|
||||
CHECK_EQ(p.layer_stride(), 2 * lbpb);
|
||||
CHECK_EQ(p.streamed(), true);
|
||||
CHECK_EQ(p.n_blocks * p.layer_bytes_per_block(), stride); /* one layer, not 13 */
|
||||
CHECK_EQ(rad::kv_ring_bytes(p, 2), 2 * 13 * lbpb);
|
||||
CHECK_EQ(rad::kv_pool_bytes(p), 2 * 13 * lbpb); /* ring wins here */
|
||||
CHECK_EQ(rad::kv_ceiling_bytes(p, 200, 2), 200 * lbpb); /* stage wins at context */
|
||||
|
||||
/* The engine's own builder places each bound layer at its position in the group and keeps the
|
||||
* pool alias a view, so both views are fixed from bring-up and the ring is active first. */
|
||||
Program P;
|
||||
P.kv_groups.resize(2);
|
||||
P.kv_groups[1].decl.kind = RAD_KV_FULL;
|
||||
P.kv_groups[1].decl.n_head_kv = heads;
|
||||
P.kv_groups[1].decl.head_dim = hd;
|
||||
for (int l = 0; l < 13; ++l) P.kv_groups[1].layers.push_back(l);
|
||||
std::vector<rad::KVGroupPlan> plans(2);
|
||||
plans[1] = p;
|
||||
plans[1].base = g_alias_pool;
|
||||
plans[1].pool_bytes = rad::kv_pool_bytes(p);
|
||||
std::vector<rad::KVPoolBinding> b;
|
||||
rad::bind_kv_pools(P, [&](int32_t x) -> const rad::KVGroupPlan* {
|
||||
return x == 0 ? nullptr : &plans[(size_t)x];
|
||||
}, &b);
|
||||
REQUIRE_EQ(b.size(), (size_t)2);
|
||||
REQUIRE_EQ(b[1].layer_slot.size(), (size_t)13);
|
||||
for (int l = 0; l < 13; ++l) CHECK_EQ(b[1].layer_slot[(size_t)l], l);
|
||||
REQUIRE(b[1].has_stage);
|
||||
CHECK_EQ(b[1].depth, 0); /* the ring is the active view */
|
||||
CHECK_EQ(b[1].layer_stride, 2 * lbpb);
|
||||
CHECK_EQ(b[1].shape[0], 2);
|
||||
CHECK_EQ(b[1].stage.layer_stride, stride);
|
||||
CHECK_EQ(b[1].stage.shape0, n_blocks);
|
||||
rad::kv_binding_enter(b[1], rad::KVView::Stage);
|
||||
CHECK_EQ(b[1].depth, 1);
|
||||
CHECK_EQ(b[1].layer_stride, stride);
|
||||
CHECK_EQ(b[1].shape[0], n_blocks);
|
||||
for (int l = 0; l < 13; ++l) CHECK_EQ(rad::kv_binding_offset(b[1], l), 0);
|
||||
}
|
||||
|
||||
/* ================================================================== arena levels */
|
||||
/* A level packs the transient buffers for smaller steps at new offsets with smaller shapes; the
|
||||
* active level decides every buffer's address and the extent an operand is checked against, so a
|
||||
@@ -2219,6 +2351,65 @@ TEST(the_pass_key_changes_with_the_arena_level) {
|
||||
CHECK_EQ(f.ctx.pass_key(&b), k0);
|
||||
}
|
||||
|
||||
/* A streamed pass's key names the memory its view reads, not the address of the struct that
|
||||
* carries it, which rotates through the builder's Out slots: keyed on that, no streamed decode pass
|
||||
* would ever replay. Two views with the same bytes must agree, a view that hands a kernel different
|
||||
* memory must not, and on a card the same streamed pass twice must play. The host backend records
|
||||
* no tape, so only the key is checked there. */
|
||||
TEST(a_streamed_pass_is_keyed_by_its_view_and_replays) {
|
||||
Fixture f;
|
||||
rad_buf x = f.add_buffer("x", RAD_BF16, 64, 4, 0);
|
||||
rad_op op = loose_op(f);
|
||||
CHECK_OK(f.start(nullptr, false, /*record=*/true));
|
||||
|
||||
std::vector<int32_t> res(64, -1), sblk(64, -1), sst(128, 0), ctl(16, 0);
|
||||
std::vector<uint8_t> host(1024, 0);
|
||||
RadKVStream view{};
|
||||
view.host = host.data(); view.res = res.data(); view.slot_block = sblk.data();
|
||||
view.slot_state = sst.data(); view.ctl = ctl.data();
|
||||
view.block_bytes = 16; view.host_layer_stride = 1024; view.slots = 64;
|
||||
view.host_bytes = 2048;
|
||||
|
||||
RadKVGroupBatch kg[1]{};
|
||||
f.batch.kv = kg;
|
||||
f.batch.n_kv_groups = 1;
|
||||
f.batch.phase = RAD_PHASE_DECODE;
|
||||
f.batch.n_tok = 1; f.batch.n_seq = 1;
|
||||
|
||||
kg[0].stream = &view;
|
||||
const uint64_t k0 = f.ctx.pass_key(&f.batch);
|
||||
CHECK(k0 != 0);
|
||||
/* The Out slot moves; the bytes a kernel reads do not. */
|
||||
RadKVStream copy = view;
|
||||
kg[0].stream = ©
|
||||
CHECK_EQ(f.ctx.pass_key(&f.batch), k0);
|
||||
/* A different ring or a different map is a different pass. */
|
||||
copy.slots = view.slots + 1;
|
||||
CHECK(f.ctx.pass_key(&f.batch) != k0);
|
||||
copy = view;
|
||||
copy.res = res.data() + 1;
|
||||
CHECK(f.ctx.pass_key(&f.batch) != k0);
|
||||
|
||||
kg[0].stream = &view;
|
||||
const auto body = [&](Ctx& c) {
|
||||
const RadOperand o[1] = { RAD_B(x) };
|
||||
CHECK_OK(c.issue(op, o, 1, RAD_N_BATCH));
|
||||
};
|
||||
/* First sighting records, the second is the audit every recording gets before its first play,
|
||||
* the third is the play. A key that moved each step would never get past the first. */
|
||||
/* The first pass settles the runtime state the key also names (the host-touch and scratch
|
||||
* flags a pass leaves behind), then: one sighting records, the next is the audit every
|
||||
* recording gets before its first play, the third is the play. A key that moved with the view
|
||||
* slot would never get past the first. */
|
||||
for (int i = 0; i < 4; ++i) CHECK_OK(f.step(1, i, body));
|
||||
if (f.ctx.records_passes()) {
|
||||
const Ctx::PassCounts pc = f.ctx.pass_counts();
|
||||
CHECK(pc.recorded > 0);
|
||||
CHECK(pc.audited > 0);
|
||||
CHECK(pc.played > 0); /* the streamed pass replayed, not reissued */
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== the op oracle */
|
||||
namespace {
|
||||
std::string radiance_home() {
|
||||
|
||||
+9
-2
@@ -339,11 +339,18 @@ struct FakeKV : IKVManager {
|
||||
const KVGeom::G& gg = geom.g[(size_t)g];
|
||||
return gg.paged ? gg.block_size : 0;
|
||||
}
|
||||
/* A streamed group's view, as KVManager::stream_view returns it. Tests install fake
|
||||
* addresses to check that the builder rebases them into each rank's pool; with `streams`
|
||||
* false the fake has none, which is every other scheduler test. */
|
||||
RadKVStream stream{};
|
||||
bool streams = false;
|
||||
const RadKVStream* stream_view(int32_t g) const override {
|
||||
return streams && g == 0 ? &stream : nullptr;
|
||||
}
|
||||
/* Groups a test says the window snapshot carries (KVGroupPlan::win_snap): a checkpoint slot
|
||||
* then holds their window, and a hit at a snapshot seeds them (nothing to copy here). */
|
||||
std::vector<int32_t> snap;
|
||||
/* False: the snapshot is taken but its groups are not reported, as before
|
||||
* IKVManager::window_snapshot existed. */
|
||||
/* False: the snapshot is taken but window_snapshot() does not report its groups. */
|
||||
bool snap_reported = true;
|
||||
bool window_snapshot(int32_t g) const override {
|
||||
return snap_reported && std::find(snap.begin(), snap.end(), g) != snap.end();
|
||||
|
||||
+75
-3
@@ -1584,8 +1584,8 @@ TEST(a_prefix_hit_with_no_checkpoint_near_the_cap_is_kept_whole) {
|
||||
/* z-lab's DFlash on the Gemma 4 31B: a full-attention block drafter (no window), whose own group the
|
||||
* prefix cache indexes like the trunk's full layers. A hit resumes the trunk's window from the
|
||||
* window snapshot, so no paged group is left with a hole and the drafter drafts from the first
|
||||
* decode. Counting the trunk's window as a hole, as before the snapshot was counted, put the
|
||||
* drafter's floor at the hit, and a drafter with no window to slide never drafted again that turn. */
|
||||
* decode. Counting the trunk's window as a hole would put the drafter's floor at the hit, and a
|
||||
* drafter with no window to slide would not draft again that turn. */
|
||||
TEST(a_full_attention_drafter_drafts_at_once_after_a_hit_the_window_snapshot_resumes) {
|
||||
for (int counted = 0; counted < 2; ++counted) {
|
||||
Fixture f;
|
||||
@@ -3385,6 +3385,78 @@ TEST(the_cards_block_tables_match_the_manager_after_every_build) {
|
||||
CHECK(checked > 100);
|
||||
}
|
||||
|
||||
/* A streamed group's residency map and ring bookkeeping live in each rank's KV pool,
|
||||
* but the manager the builder is given is rank 0's, so its pointers are rank 0's addresses. A
|
||||
* two-rank batch must name rank r's own copies or device r resolves through device 0's memory
|
||||
* (a page-not-present fault at --tp 2). The host mirror is the exception: RAD_MEM_HOST_MAPPED's
|
||||
* device view is its host address on every card, so it is the same pointer on both ranks.
|
||||
*
|
||||
* The bases are fake and no map is dereferenced: what is under test is the rebasing arithmetic,
|
||||
* not two cards. Both ranks use device 0 so the test runs on the host backend. */
|
||||
TEST(a_two_rank_batch_rebases_stream_maps_into_each_ranks_pool_and_shares_the_mirror) {
|
||||
Fixture f;
|
||||
f.build();
|
||||
ChunkGeometry geo;
|
||||
CHECK_OK(chunk_geometry_resolve(f.prog, f.cfg, &geo));
|
||||
KVGeom kvg = KVGeom::of(f.prog.kv_groups);
|
||||
for (size_t i = 0; i < kvg.g.size(); ++i) {
|
||||
const int64_t w = f.kv.state_index_width((int32_t)i);
|
||||
if (w > 0) kvg.g[i].sidx_width = w;
|
||||
}
|
||||
|
||||
/* Two pools' worth of address space, only ever differenced, never dereferenced. */
|
||||
alignas(16) char pool0[0x200], pool1[0x200];
|
||||
char* const base[2] = { pool0, pool1 };
|
||||
const int64_t res_off = 0x40, sblk_off = 0x80, sst_off = 0xc0, ctl_off = 0x100;
|
||||
alignas(16) uint8_t mirror[0x100];
|
||||
f.kv.streams = true;
|
||||
f.kv.stream.host = mirror;
|
||||
f.kv.stream.res = (int32_t*)(base[0] + res_off);
|
||||
f.kv.stream.slot_block = (int32_t*)(base[0] + sblk_off);
|
||||
f.kv.stream.slot_state = (int32_t*)(base[0] + sst_off);
|
||||
f.kv.stream.ctl = (int32_t*)(base[0] + ctl_off);
|
||||
f.kv.stream.block_bytes = 64;
|
||||
f.kv.stream.slots = 8;
|
||||
|
||||
BatchBuilder bb;
|
||||
std::vector<BatchBuilder::RankIO> rio;
|
||||
rio.push_back({ 0, nullptr, &f.prog, base[0] });
|
||||
rio.push_back({ 0, nullptr, &f.prog, base[1] });
|
||||
CHECK_OK(bb.init(f.prog, f.cfg, geo, kvg, rio));
|
||||
|
||||
CHECK_OK(f.kv.add_sequence(1));
|
||||
CHECK_OK(f.kv.ensure(1, 80));
|
||||
StepPlan p;
|
||||
p.reset();
|
||||
StepEntry e;
|
||||
e.seq = 1;
|
||||
e.card = 0;
|
||||
e.n_tokens = 1;
|
||||
e.ctx_len = 79;
|
||||
p.e.push_back(e);
|
||||
p.n_tok = 1;
|
||||
REQUIRE(bb.build(p, f.kv, 0) != nullptr);
|
||||
|
||||
for (int r = 0; r < 2; ++r) {
|
||||
const RadBatch* b = bb.batch_for(r);
|
||||
REQUIRE(b != nullptr);
|
||||
const RadKVStream* s = b->kv[0].stream;
|
||||
REQUIRE(s != nullptr);
|
||||
CHECK_EQ((void*)s->res, (void*)(base[r] + res_off));
|
||||
CHECK_EQ((void*)s->slot_block, (void*)(base[r] + sblk_off));
|
||||
CHECK_EQ((void*)s->slot_state, (void*)(base[r] + sst_off));
|
||||
CHECK_EQ((void*)s->ctl, (void*)(base[r] + ctl_off));
|
||||
/* Same mirror address, and the geometry is rank-independent. */
|
||||
CHECK_EQ((void*)s->host, (void*)mirror);
|
||||
CHECK_EQ(s->block_bytes, (int64_t)64);
|
||||
CHECK_EQ(s->slots, (int64_t)8);
|
||||
/* Groups that do not stream keep a null view. */
|
||||
for (int gi = 1; gi < b->n_kv_groups; ++gi)
|
||||
CHECK(b->kv[gi].stream == nullptr);
|
||||
}
|
||||
bb.fini();
|
||||
}
|
||||
|
||||
/* A sequence that leaves a row and returns to it is restaged whole. Its change marks are taken
|
||||
* wherever it is written, so the old row's copy goes stale; restaging only later changes would
|
||||
* keep entries a rollback replaced earlier. The scheduler's own passes reorder rows, so this
|
||||
@@ -4061,7 +4133,7 @@ TEST(a_step_is_issued_ahead_only_once_the_requests_speculation_is_fixed) {
|
||||
CHECK(f.sch.step_next() != nullptr);
|
||||
}
|
||||
|
||||
/* No step is issued ahead behind one that ends every request it carries (#225): its rows would
|
||||
/* No step is issued ahead behind one that ends every request it carries: its rows would
|
||||
* belong to finished requests, and a request arriving after the last token would wait out its
|
||||
* forward pass. The verify ends a request most likely when its drafts hold an end-of-generation
|
||||
* id, certainly when its first token is the request's last (max_tokens), and possibly when that
|
||||
|
||||
@@ -433,6 +433,63 @@ struct FakeMultimodal : IMultimodal {
|
||||
*out = std::move(it);
|
||||
return RAD_OK;
|
||||
}
|
||||
/* The keyframe path shows the tower the canvas frame itself, not the file: counted, with each
|
||||
* frame's side, so a test can confirm the tower saw the very pixels the VAE was handed. */
|
||||
int n_pframe = 0;
|
||||
std::vector<std::pair<int32_t, int32_t>> pframe_wh;
|
||||
int prepare_frame(const mm::Frame& f, std::shared_ptr<mm::Item>* out, std::string*) override {
|
||||
++n_pframe;
|
||||
pframe_wh.emplace_back(f.w, f.h);
|
||||
auto it = std::make_shared<mm::Item>();
|
||||
it->expand = expand;
|
||||
*out = std::move(it);
|
||||
return RAD_OK;
|
||||
}
|
||||
/* The VAE encoders' form, which the server fills for a generator that declares the encoders.
|
||||
* 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 media's own (a short
|
||||
* clip, a sample count that is not a whole hop), since padding is the driver's. */
|
||||
int32_t enc_frames = 5, enc_side = 16;
|
||||
int64_t enc_n = 850;
|
||||
int n_ienc = 0, n_venc = 0, n_aenc = 0, n_cenc = 0;
|
||||
/* The canvas a keyframe was resized to and the centre-crop flags: cenc_cover is the last
|
||||
* call's, cenc_covers every call's in order (first frame, then last). */
|
||||
int32_t cenc_w = 0, cenc_h = 0;
|
||||
bool cenc_cover = false;
|
||||
std::vector<bool> cenc_covers;
|
||||
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_image_canvas(const uint8_t*, size_t, int32_t w, int32_t h, bool cover,
|
||||
mm::Frame* out, std::string*) override {
|
||||
++n_cenc;
|
||||
cenc_w = w; cenc_h = h; cenc_cover = cover;
|
||||
cenc_covers.push_back(cover);
|
||||
out->w = w; out->h = h;
|
||||
out->rgb.assign((size_t)w * h * 3, 100);
|
||||
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. */
|
||||
|
||||
@@ -2359,6 +2359,11 @@ TEST(metrics_is_valid_prometheus_text_with_vllm_names) {
|
||||
CHECK_EQ(d.type["radiance:draft_acceptance_ratio"], std::string("gauge"));
|
||||
CHECK_EQ(d.type["radiance:decode_tokens_per_second"], std::string("gauge"));
|
||||
CHECK_EQ(d.type["radiance:http_admission_rejected_total"], std::string("counter"));
|
||||
/* KV streaming (docs/KV-STREAMING.md §4.2), present even when no group streams so a dashboard
|
||||
* can query the names before the feature is turned on. The bytes counter carries `dir`. */
|
||||
CHECK_EQ(d.type["radiance:kv_resident_blocks"], std::string("gauge"));
|
||||
CHECK_EQ(d.type["radiance:kv_stream_misses_total"], std::string("counter"));
|
||||
CHECK_EQ(d.type["radiance:kv_stream_bytes_total"], std::string("counter"));
|
||||
|
||||
/* The scheduler's numbers reached the gauges. */
|
||||
auto find_one = [&](const std::string& prefix) -> double {
|
||||
@@ -2371,6 +2376,10 @@ TEST(metrics_is_valid_prometheus_text_with_vllm_names) {
|
||||
CHECK_NEAR(find_one("vllm:gpu_cache_usage_perc{"), 0.42, 1e-9);
|
||||
CHECK_NEAR(find_one("radiance:draft_acceptance_ratio{"), 0.61, 1e-9);
|
||||
CHECK_NEAR(find_one("vllm:generation_tokens_total{"), 5.0, 1e-9);
|
||||
/* This server streams nothing, so every streaming number is zero. */
|
||||
CHECK_NEAR(find_one("radiance:kv_resident_blocks{"), 0.0, 1e-9);
|
||||
CHECK_NEAR(find_one("radiance:kv_stream_misses_total{"), 0.0, 1e-9);
|
||||
CHECK_NEAR(find_one("radiance:kv_stream_bytes_total{"), 0.0, 1e-9);
|
||||
|
||||
/* An unmeasured decode floor is absent, not 0, which a scrape would plot as the fastest step
|
||||
* ever. This fixture completes no single-stream window, so neither series appears. */
|
||||
|
||||
@@ -521,4 +521,16 @@ TEST(a_phase_that_logs_is_never_reported) {
|
||||
CHECK(out.find("probe: step 59") != std::string::npos);
|
||||
}
|
||||
|
||||
/* Progress marked without a log line keeps a phase from being reported the same way. */
|
||||
TEST(a_phase_that_marks_progress_is_never_reported) {
|
||||
const std::string out = stderr_of([] {
|
||||
StallWatch w("probe", 150);
|
||||
for (int i = 0; i < 60; ++i) {
|
||||
w.progress();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(5));
|
||||
}
|
||||
});
|
||||
CHECK(out.find("nothing has been logged") == std::string::npos);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -0,0 +1,110 @@
|
||||
/* vae_geom_test.cpp -- the encode geometry (arch/minimaxh3/rad_vae_geom.cpp) against golden vectors
|
||||
* produced by the reference VAEs themselves.
|
||||
*
|
||||
* The TU is pure host arithmetic, so it is compiled straight in here -- no rad_core, no device.
|
||||
* tests/data/vae_geom/golden.json comes from gen_golden.py, which runs the reference's encoders on
|
||||
* CPU (video: EncoderFCN3D and the wrapper's own encode(), encode_temporal() and tiled_encode()
|
||||
* with the reference's constructor arguments; audio: the DAC encoder). The latent counts below are
|
||||
* the networks' own output shapes and the constants the reference's own tables, so a mismatch is
|
||||
* the port disagreeing with the model.
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
#include "rad_vae_geom.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace minimaxh3;
|
||||
|
||||
namespace {
|
||||
|
||||
nlohmann::json& golden() {
|
||||
static nlohmann::json g = [] {
|
||||
std::ifstream f(std::string(RAD_VAE_GOLDEN) + "/golden.json");
|
||||
if (!f.is_open()) {
|
||||
fprintf(stderr, " FAIL golden.json missing -- regenerate with "
|
||||
"tests/data/vae_geom/gen_golden.py\n");
|
||||
std::exit(1);
|
||||
}
|
||||
return nlohmann::json::parse(f);
|
||||
}();
|
||||
return g;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
TEST(vae_encode_latent_counts) {
|
||||
/* Every frame count goes through the reference encode() end to end: chunking, the padded last
|
||||
* clip, the trailing drop. The spatial entries pin the ratio (generated at 32x32) and the
|
||||
* latent width pins z_channels. */
|
||||
for (const auto& c : golden()["video"]["encode"]) {
|
||||
const int64_t t = c["T"];
|
||||
const auto& z = c["z_shape"];
|
||||
CHECK_EQ(vae_latent_frames(t), z[2].get<int64_t>());
|
||||
CHECK_EQ(z[1].get<int64_t>(), 24);
|
||||
CHECK_EQ(z[3].get<int64_t>() * kVaeRatio, 32);
|
||||
CHECK_EQ(z[4].get<int64_t>() * kVaeRatio, 32);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(vae_clip_chain_composes_with_encode) {
|
||||
/* A full clip's latents times the clip count, less the drop, is the encode count; and a raw
|
||||
* clip through the causal chain (the golden's tiled_encode cases: no chunking, no drop) has
|
||||
* vae_clip_latents of its pixel frames. */
|
||||
for (const auto& c : golden()["video"]["encode"]) {
|
||||
const int64_t t = c["T"];
|
||||
if (t < 2) continue;
|
||||
const int64_t clips = (t + kVaeClipLength - 1) / kVaeClipLength;
|
||||
CHECK_EQ(clips * vae_clip_latents(kVaeClipLength) - kVaeTokenDrop, c["z_shape"][2].get<int64_t>());
|
||||
}
|
||||
for (const auto& c : golden()["video"]["tiled_encode"])
|
||||
CHECK_EQ(vae_clip_latents(c["x_shape"][2].get<int64_t>()), c["moments_shape"][2].get<int64_t>());
|
||||
/* A single frame truncates its temporal taps instead of padding them. */
|
||||
CHECK_EQ(vae_clip_latents(1), 1);
|
||||
}
|
||||
|
||||
TEST(vae_audio_latents_match_encoder) {
|
||||
/* The wrapper right-pads to the hop and the stride chain divides exactly: the reference
|
||||
* encoder's own frame count is ceil(samples / 800). */
|
||||
for (const auto& c : golden()["audio"]["latents"]) {
|
||||
const int64_t s = c["samples"];
|
||||
CHECK_EQ(vae_audio_latents(s), c["T"].get<int64_t>());
|
||||
CHECK_EQ(vae_audio_latents(s) * kAudioHop, c["padded"].get<int64_t>());
|
||||
}
|
||||
}
|
||||
|
||||
TEST(vae_constants_are_the_reference_tables) {
|
||||
/* The de-normalization the latents carry: doubles compare bit for bit, since the golden
|
||||
* carries the same decimal literals. */
|
||||
const auto& k = golden()["video"]["constants"];
|
||||
const auto mean = k["latents_mean"].get<std::vector<double>>();
|
||||
const auto stdv = k["latents_std"].get<std::vector<double>>();
|
||||
CHECK_EQ(mean.size(), 24u);
|
||||
CHECK_EQ(stdv.size(), 24u);
|
||||
for (size_t i = 0; i < mean.size() && i < 24; ++i) {
|
||||
CHECK(kVaeLatentsMean[i] == mean[i]);
|
||||
CHECK(kVaeLatentsStd[i] == stdv[i]);
|
||||
}
|
||||
const auto pm = k["pixel_mean"].get<std::vector<double>>();
|
||||
const auto ps = k["pixel_std"].get<std::vector<double>>();
|
||||
for (size_t i = 0; i < 3; ++i) {
|
||||
CHECK(kVaePixelMean[i] == pm[i]);
|
||||
CHECK(kVaePixelStd[i] == ps[i]);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(vae_geom_rejects_nonsense) {
|
||||
CHECK_EQ(vae_latent_frames(0), -1);
|
||||
CHECK_EQ(vae_latent_frames(-5), -1);
|
||||
CHECK_EQ(vae_clip_latents(0), -1);
|
||||
CHECK_EQ(vae_audio_latents(-1), -1);
|
||||
CHECK_EQ(vae_audio_latents(0), 0);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -74,6 +74,62 @@ int64_t fake_positions(int which, const RadVideoGeom* g, float* pos, int64_t cap
|
||||
return rows;
|
||||
}
|
||||
|
||||
/* A reference pack for this fake's layout: [text | 2 rows a keyframe | 4 a reference | the
|
||||
* soundtrack | the video], its modulation groups the segments themselves, each its own cell, and
|
||||
* the positions 1000 c + i in channel c. Not the real arithmetic: the shape the driver stages. */
|
||||
int64_t fake_pack(const RadVideoGeom* g, const int32_t* ref_tab, int32_t* seg, int32_t* n_seg,
|
||||
int32_t* mod, int32_t* n_mod, float* pos, int64_t cap_pos) {
|
||||
const int32_t nr = ref_tab[0], nk = ref_tab[1];
|
||||
const int64_t audio = 2 * (int64_t)g->n_audio;
|
||||
const int64_t video = (int64_t)g->lat_frames * (g->lat_h / 2) * (g->lat_w / 2);
|
||||
const int64_t rows = g->n_text + 2 * (int64_t)nk + 4 * (int64_t)nr + audio + video;
|
||||
const int32_t ns = nk + nr + 4;
|
||||
std::vector<int32_t> b = { 0 };
|
||||
int64_t cur = g->n_text;
|
||||
for (int32_t k = 0; k < nk; ++k, cur += 2) b.push_back((int32_t)cur);
|
||||
for (int32_t r = 0; r < nr; ++r, cur += 4) b.push_back((int32_t)cur);
|
||||
b.push_back((int32_t)cur);
|
||||
b.push_back((int32_t)(cur + audio));
|
||||
b.push_back((int32_t)rows);
|
||||
if (seg && *n_seg < ns) return RAD_E_INVAL;
|
||||
if (seg) std::copy(b.begin(), b.end(), seg);
|
||||
if (n_seg) *n_seg = ns;
|
||||
const int32_t nm = 2 * ns - 1;
|
||||
if (mod && *n_mod < nm) return RAD_E_INVAL;
|
||||
if (mod) {
|
||||
std::copy(b.begin(), b.end(), mod);
|
||||
for (int32_t k = 0; k + 1 < ns; ++k) mod[ns + k] = k;
|
||||
}
|
||||
if (n_mod) *n_mod = nm;
|
||||
if (pos) {
|
||||
if (cap_pos < 3 * rows) return RAD_E_INVAL;
|
||||
for (int64_t c = 0; c < 3; ++c)
|
||||
for (int64_t i = 0; i < rows; ++i) pos[c * rows + i] = (float)(c * 1000 + i);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/* The real encoders' geometry where the driver reads it: a video of T frames pads to whole
|
||||
* 17-frame clips (entry 23) of 5 latents less 3 (entry 24), a picture stays one frame; a
|
||||
* soundtrack pads to whole 800-sample hops (entry 0) of a latent each (entry 12). */
|
||||
int64_t fake_encode_geom(int32_t kind, const int64_t* in, int32_t* gd, int64_t cap) {
|
||||
const int64_t need = kind == RAD_GEN_PASS_AENCODE ? 13 : 25;
|
||||
if (!gd) return need;
|
||||
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;
|
||||
gd[0] = (int32_t)(lat * 800);
|
||||
gd[12] = (int32_t)lat;
|
||||
} else {
|
||||
const int64_t clips = (in[0] + 16) / 17;
|
||||
gd[22] = (int32_t)clips;
|
||||
gd[23] = in[0] == 1 ? 1 : (int32_t)(clips * 17);
|
||||
gd[24] = in[0] == 1 ? 1 : (int32_t)(clips * 5 - 3);
|
||||
}
|
||||
return need;
|
||||
}
|
||||
|
||||
struct VideoFixture {
|
||||
Program prog;
|
||||
gen::VideoDriver drv;
|
||||
@@ -85,6 +141,21 @@ struct VideoFixture {
|
||||
prog.ctx.max_seqs = 1;
|
||||
}
|
||||
int start() { return drv.init(prog, fake_positions, { gen::VideoDriver::RankIO{} }); }
|
||||
/* With the reference conditioning of a container with the video VAE's encoder, and the audio
|
||||
* VAE's too when `audio`. */
|
||||
int start_refs(bool audio = true) {
|
||||
RadVideoGenDecl& d = prog.video_gen;
|
||||
d.max_ref_images = 9;
|
||||
d.max_ref_videos = 3;
|
||||
d.max_ref_audios = audio ? 3 : 0;
|
||||
d.max_enc_frames = 289;
|
||||
d.max_enc_side = 256;
|
||||
d.max_enc_samples = audio ? 500000 : 0;
|
||||
d.enc_ratio = 16;
|
||||
d.max_mod_cells = 8;
|
||||
return drv.init(prog, fake_positions, { gen::VideoDriver::RankIO{} }, fake_pack,
|
||||
fake_encode_geom);
|
||||
}
|
||||
std::unique_ptr<gen::VideoRequest> req(int32_t chunks = 2, int32_t steps = 0) {
|
||||
auto r = std::make_unique<gen::VideoRequest>();
|
||||
r->tokens = { 1, 2, 3 };
|
||||
@@ -171,6 +242,21 @@ TEST(the_schedule_counts_grid_points_and_shifts_each_modality) {
|
||||
CHECK_EQ(gen::video_schedule(d, 2).steps, 1);
|
||||
}
|
||||
|
||||
/* A request's shift re-shapes ONLY the stream it names; the stream it leaves at 0 keeps the
|
||||
* declaration's trained shift (decl_small is video 12, audio 3). */
|
||||
TEST(a_request_shift_overrides_the_declaration_per_stream) {
|
||||
const RadVideoGenDecl d = decl_small();
|
||||
const gen::VideoSchedule base = gen::video_schedule(d, 50);
|
||||
const gen::VideoSchedule s = gen::video_schedule(d, 50, 0, false, 6.0, 0.0); /* video -> 6, audio keep 3 */
|
||||
REQUIRE_EQ(s.sig_v.size(), base.sig_v.size());
|
||||
REQUIRE_EQ(s.sig_a.size(), base.sig_a.size());
|
||||
const double b = 1.0 - 30.0 / 49.0;
|
||||
CHECK(std::fabs(s.sig_v[30] - 6.0 * b / (1.0 + 5.0 * b)) < 1e-6); /* re-shifted by 6 */
|
||||
CHECK(std::fabs(s.sig_a[30] - 3.0 * b / (1.0 + 2.0 * b)) < 1e-6); /* still the decl's 3 */
|
||||
CHECK(s.sig_v[30] != base.sig_v[30]); /* video actually moved */
|
||||
CHECK(std::fabs(s.sig_a[30] - base.sig_a[30]) < 1e-9); /* audio untouched */
|
||||
}
|
||||
|
||||
/* A trained schedule (a distilled checkpoint's): its rungs in f32, each modality's shift applied
|
||||
* as the reference's tensor arithmetic does (f32 throughout), then the terminal 0; one evaluation a
|
||||
* rung, and no other step count. */
|
||||
@@ -835,4 +921,316 @@ TEST(left_padded_prompts_one_audio_stream_and_an_exact_upscaler) {
|
||||
g_audio_streams = 2;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* A picture as the processor hands one to the vision tower: eight patches merged into two rows,
|
||||
* on the two placeholder tokens 700 and 701. */
|
||||
std::shared_ptr<mm::Item> synthetic_picture(int64_t patch_dim) {
|
||||
auto it = std::make_shared<mm::Item>();
|
||||
it->kind = mm::Kind::Image;
|
||||
it->grid_t = 1;
|
||||
it->grid_h = 2;
|
||||
it->grid_w = 4;
|
||||
it->n_patch = 8;
|
||||
it->patch_dim = patch_dim;
|
||||
it->pixels.resize((size_t)(it->n_patch * patch_dim));
|
||||
for (size_t i = 0; i < it->pixels.size(); ++i) it->pixels[i] = (uint16_t)i;
|
||||
it->n_seg = 1;
|
||||
it->seg_rows = 2;
|
||||
it->rows_h = 1;
|
||||
it->rows_w = 2;
|
||||
it->expand = { 700, 701 };
|
||||
it->seg_at = { 0 };
|
||||
return it;
|
||||
}
|
||||
|
||||
/* The picture placed at prompt token `tok`. */
|
||||
std::shared_ptr<mm::PromptMedia> picture_media(int64_t patch_dim, int32_t tok) {
|
||||
auto pm = std::make_shared<mm::PromptMedia>();
|
||||
mm::Placed pl;
|
||||
pl.item = synthetic_picture(patch_dim);
|
||||
pl.tok = tok;
|
||||
pm->items.push_back(std::move(pl));
|
||||
pm->layout();
|
||||
return pm;
|
||||
}
|
||||
|
||||
void with_tower(VideoFixture& f, int64_t max_enc) {
|
||||
f.prog.encoder.modalities = RAD_MM_IMAGE;
|
||||
f.prog.encoder.patch_dim = 6;
|
||||
f.prog.ctx.max_enc_patches = max_enc;
|
||||
}
|
||||
|
||||
/* A reference picture or keyframe of w x h, or a video of `frames` frames, in the encoder's form;
|
||||
* a soundtrack of `samples` samples a channel. */
|
||||
gen::VideoRefMedia picture(gen::VideoRefMedia::Kind kind, const char* name, int32_t index,
|
||||
int32_t w = 16, int32_t h = 16, int32_t frames = 1) {
|
||||
gen::VideoRefMedia m;
|
||||
m.kind = kind;
|
||||
m.index = index;
|
||||
m.name = name;
|
||||
m.enc_frames = frames;
|
||||
m.enc_w = w;
|
||||
m.enc_h = h;
|
||||
m.enc_pixels.assign((size_t)frames * w * h * 3, 1.0f);
|
||||
return m;
|
||||
}
|
||||
gen::VideoRefMedia sound(gen::VideoRefMedia::Kind kind, const char* name, int32_t index,
|
||||
int64_t samples) {
|
||||
gen::VideoRefMedia m;
|
||||
m.kind = kind;
|
||||
m.index = index;
|
||||
m.name = name;
|
||||
m.enc_n = samples;
|
||||
m.enc_channels = 2;
|
||||
m.enc_samples.assign((size_t)(2 * samples), 0.5f);
|
||||
return m;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* A reference picture: encoded first, then shown to the tower in the prompt pass, then laid by the
|
||||
* plugin between the prompt and the latents of every step; the sampler steps the latents alone. */
|
||||
TEST(a_reference_picture_is_encoded_shown_and_laid_into_the_step) {
|
||||
VideoFixture f;
|
||||
f.build();
|
||||
with_tower(f, 16);
|
||||
CHECK_OK(f.start_refs());
|
||||
std::string why;
|
||||
auto r = f.req(2);
|
||||
r->tokens = { 1, 700, 701, 2, 3 };
|
||||
r->refs.push_back(picture(gen::VideoRefMedia::IMAGE, "ref_image_1", 1));
|
||||
r->media = picture_media(6, 1);
|
||||
CHECK_OK(f.drv.submit(std::move(r), &why));
|
||||
|
||||
std::string kinds;
|
||||
for (int i = 0; i < 12; ++i) {
|
||||
const RadBatch* b = f.drv.next(i);
|
||||
if (!b) break;
|
||||
const RadVideoGenBatch* V = b->vgen_b;
|
||||
REQUIRE(V != nullptr);
|
||||
kinds += b->gen == RAD_GEN_PASS_VENCODE ? 'E' : kind_of(b->gen);
|
||||
if (b->gen == RAD_GEN_PASS_VENCODE) {
|
||||
CHECK_EQ(V->enc_kind, (int32_t)RAD_ENC_IMAGE);
|
||||
CHECK_EQ(V->enc_slot, 1);
|
||||
CHECK_EQ(V->enc_frames, 1);
|
||||
/* {references, keyframes}, then the picture: its kind, slot, 1 x 1 latent grid, one
|
||||
* latent frame and no soundtrack. */
|
||||
const int32_t want[8] = { 1, 0, RAD_VREF_PICTURE, 1, 1, 1, 1, 0 };
|
||||
for (int k = 0; k < 8; ++k) CHECK_EQ(V->ref_tab[k], want[k]);
|
||||
} else if (b->gen == RAD_GEN_PASS_VCOND) {
|
||||
CHECK_EQ(b->rope_mixed, 1);
|
||||
CHECK_EQ(b->n_mm_rows, (int64_t)2);
|
||||
CHECK_EQ(b->enc_n_patch, (int64_t)8);
|
||||
CHECK_EQ(b->enc_n_seg, 1);
|
||||
CHECK_EQ(b->enc_max_seg, 8);
|
||||
} else if (b->gen == RAD_GEN_PASS_VSTEP) {
|
||||
CHECK_EQ(b->enc_n_patch, (int64_t)0);
|
||||
CHECK_EQ(b->n_tok, (int64_t)(5 + 4 + 100 + 6));
|
||||
const int32_t seg[5] = { 0, 5, 9, 109, 115 };
|
||||
for (int k = 0; k < 5; ++k) {
|
||||
CHECK_EQ(V->seg_cu[k], seg[k]);
|
||||
CHECK_EQ(V->mod_cu[k], seg[k]);
|
||||
}
|
||||
CHECK_EQ(V->lat_cu[1], 6);
|
||||
CHECK_EQ(V->lat_cu[3], 100);
|
||||
CHECK_EQ(V->pos[3 * 115 - 1], (float)(2000 + 114));
|
||||
}
|
||||
f.answer(0);
|
||||
CHECK_OK(f.drv.done());
|
||||
}
|
||||
CHECK_EQ(kinds, std::string("ECSSADD"));
|
||||
}
|
||||
|
||||
/* A first and a last frame at the video's size: one Vencode pass each, the keyframe table pinning
|
||||
* frame 0 and the last frame, and their blocks ahead of the latents. */
|
||||
TEST(a_keyframe_pair_is_encoded_and_pins_both_ends) {
|
||||
VideoFixture f;
|
||||
f.build();
|
||||
with_tower(f, 16);
|
||||
CHECK_OK(f.start_refs());
|
||||
std::string why;
|
||||
auto r = f.req(2);
|
||||
r->refs.push_back(picture(gen::VideoRefMedia::FIRST_FRAME, "first_frame", 1, 64, 32));
|
||||
r->refs.push_back(picture(gen::VideoRefMedia::LAST_FRAME, "last_frame", 2, 64, 32));
|
||||
CHECK_OK(f.drv.submit(std::move(r), &why));
|
||||
const int32_t frames = gen::video_shape(f.prog.video_gen, 64, 32, 2).frames;
|
||||
|
||||
int encodes = 0;
|
||||
bool stepped = false;
|
||||
for (int i = 0; i < 12; ++i) {
|
||||
const RadBatch* b = f.drv.next(i);
|
||||
if (!b) break;
|
||||
const RadVideoGenBatch* V = b->vgen_b;
|
||||
if (b->gen == RAD_GEN_PASS_VENCODE) {
|
||||
CHECK_EQ(V->enc_kind, (int32_t)RAD_ENC_KEYFRAME);
|
||||
CHECK_EQ(V->enc_slot, ++encodes);
|
||||
} else if (b->gen == RAD_GEN_PASS_VSTEP) {
|
||||
stepped = true;
|
||||
CHECK_EQ(b->n_tok, (int64_t)(3 + 2 * 2 + 100 + 6));
|
||||
const int32_t seg[6] = { 0, 3, 5, 7, 107, 113 };
|
||||
for (int k = 0; k < 6; ++k) CHECK_EQ(V->seg_cu[k], seg[k]);
|
||||
const int32_t want[8] = { 0, 2, 0, 1, 0, frames - 1, 1, 0 };
|
||||
for (int k = 0; k < 8; ++k) CHECK_EQ(V->ref_tab[k], want[k]);
|
||||
}
|
||||
f.answer(0);
|
||||
CHECK_OK(f.drv.done());
|
||||
}
|
||||
CHECK_EQ(encodes, 2);
|
||||
CHECK(stepped);
|
||||
}
|
||||
|
||||
/* References ride a latent upscale, laid out again at the small size for the steps before it; a
|
||||
* keyframe, pinned on the video's own grid, does not. */
|
||||
TEST(references_are_laid_out_again_at_an_upscales_small_size) {
|
||||
VideoFixture f;
|
||||
f.build();
|
||||
f.prog.video_gen.upscale_max = 4.0;
|
||||
f.prog.video_gen.upscale_refine = 1;
|
||||
with_tower(f, 16);
|
||||
CHECK_OK(f.start_refs());
|
||||
std::string why;
|
||||
auto r = f.req(1, 4);
|
||||
r->tokens = { 1, 700, 701, 2, 3 };
|
||||
r->width = 64;
|
||||
r->height = 64;
|
||||
r->upscale = 2.0;
|
||||
r->refs.push_back(picture(gen::VideoRefMedia::IMAGE, "ref_image_1", 1));
|
||||
r->media = picture_media(6, 1);
|
||||
CHECK_OK(f.drv.submit(std::move(r), &why));
|
||||
|
||||
/* 5 prompt rows, 4 reference rows, 60 soundtrack rows, then a video of 2 rows small, 8 full. */
|
||||
std::string kinds;
|
||||
int steps = 0;
|
||||
for (int i = 0; i < 20; ++i) {
|
||||
const RadBatch* b = f.drv.next(i);
|
||||
if (!b) break;
|
||||
const RadVideoGenBatch* V = b->vgen_b;
|
||||
kinds += b->gen == RAD_GEN_PASS_VENCODE ? 'E' : kind_of(b->gen);
|
||||
if (b->gen == RAD_GEN_PASS_VSTEP) {
|
||||
const int64_t rows = 5 + 4 + 60 + (steps++ < 2 ? 2 : 8);
|
||||
CHECK_EQ(b->n_tok, rows);
|
||||
CHECK_EQ(V->seg_cu[3], 69);
|
||||
CHECK_EQ(V->seg_cu[4], (int32_t)rows);
|
||||
CHECK_EQ(V->pos[3 * rows - 1], (float)(2000 + rows - 1));
|
||||
} else if (b->gen == RAD_GEN_PASS_VUPSCALE) {
|
||||
CHECK_EQ(V->seg_cu[3], 5 + 60 + 8);
|
||||
}
|
||||
f.answer(10 * i);
|
||||
CHECK_OK(f.drv.done());
|
||||
}
|
||||
CHECK_EQ(kinds, std::string("ECSSUSAD"));
|
||||
|
||||
VideoFixture g;
|
||||
g.build();
|
||||
g.prog.video_gen.upscale_max = 4.0;
|
||||
g.prog.video_gen.upscale_refine = 1;
|
||||
CHECK_OK(g.start_refs());
|
||||
r = g.req(1, 4);
|
||||
r->width = 64;
|
||||
r->height = 64;
|
||||
r->upscale = 2.0;
|
||||
r->refs.push_back(picture(gen::VideoRefMedia::FIRST_FRAME, "first_frame", 1, 64, 64));
|
||||
CHECK_EQ(g.drv.submit(std::move(r), &why), (int)RAD_E_INVAL);
|
||||
CHECK(has(why, "latent_upscale"));
|
||||
}
|
||||
|
||||
/* A reference video with its soundtrack and a standalone soundtrack: one encode pass each, the
|
||||
* soundtrack first and under the video's number, each media padded to the encoder's clips and
|
||||
* hops; the video and its soundtrack are one row of the table. */
|
||||
TEST(reference_videos_and_soundtracks_are_encoded_into_the_table) {
|
||||
VideoFixture f;
|
||||
f.build();
|
||||
CHECK_OK(f.start_refs());
|
||||
std::string why;
|
||||
auto r = f.req(2, 2);
|
||||
r->refs.push_back(picture(gen::VideoRefMedia::VIDEO, "ref_video_1", 1, 16, 16, 5));
|
||||
r->refs.push_back(sound(gen::VideoRefMedia::VIDEO_AUDIO, "ref_video_audio_1", 1, 1600));
|
||||
r->refs.push_back(sound(gen::VideoRefMedia::AUDIO, "ref_audio_2", 2, 850));
|
||||
CHECK_OK(f.drv.submit(std::move(r), &why));
|
||||
|
||||
std::string passes;
|
||||
std::vector<int32_t> tab;
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
const RadBatch* b = f.drv.next(i);
|
||||
REQUIRE(b != nullptr);
|
||||
const RadVideoGenBatch* V = b->vgen_b;
|
||||
if (b->gen == RAD_GEN_PASS_VENCODE) {
|
||||
passes += "V";
|
||||
CHECK_EQ(V->enc_kind, (int32_t)RAD_ENC_VIDEO);
|
||||
CHECK_EQ(V->enc_frames, 17);
|
||||
} else {
|
||||
REQUIRE_EQ(b->gen, (int)RAD_GEN_PASS_AENCODE);
|
||||
passes += V->enc_kind == RAD_ENC_VAUDIO ? "s" : "a";
|
||||
CHECK_EQ(V->enc_slot, V->enc_kind == RAD_ENC_VAUDIO ? 1 : 2);
|
||||
CHECK_EQ(V->enc_n_samples, (int64_t)1600);
|
||||
}
|
||||
tab.assign(V->ref_tab, V->ref_tab + 14);
|
||||
f.answer(0);
|
||||
CHECK_OK(f.drv.done());
|
||||
}
|
||||
CHECK_EQ(passes, std::string("sVa"));
|
||||
/* The video: 1 x 1 grid, 5 frames to 2 latent frames, a soundtrack of 2 latents; the
|
||||
* standalone soundtrack: 850 samples to 2 latents. */
|
||||
const std::vector<int32_t> want = { 2, 0, RAD_VREF_VIDEO, 1, 1, 1, 2, 2,
|
||||
RAD_VREF_AUDIO, 2, 0, 0, 0, 2 };
|
||||
CHECK(tab == want);
|
||||
}
|
||||
|
||||
/* Media the model cannot condition on are refused at submit, by name. */
|
||||
TEST(references_the_model_cannot_take_are_refused) {
|
||||
std::string why;
|
||||
auto refused = [&](VideoFixture& f, std::unique_ptr<gen::VideoRequest> r, const char* what) {
|
||||
why.clear();
|
||||
CHECK_EQ(f.drv.submit(std::move(r), &why), (int)RAD_E_INVAL);
|
||||
CHECK(has(why, what));
|
||||
};
|
||||
VideoFixture plain;
|
||||
plain.build();
|
||||
CHECK_OK(plain.start());
|
||||
auto r = plain.req();
|
||||
r->refs.push_back(picture(gen::VideoRefMedia::VIDEO, "ref_video_1", 1));
|
||||
refused(plain, std::move(r), "conditions on no reference media");
|
||||
|
||||
VideoFixture f;
|
||||
f.build();
|
||||
with_tower(f, 16);
|
||||
CHECK_OK(f.start_refs());
|
||||
r = f.req();
|
||||
r->refs.push_back(picture(gen::VideoRefMedia::IMAGE, "ref_image_1", 1));
|
||||
refused(f, std::move(r), "does not show it");
|
||||
r = f.req();
|
||||
r->tokens = { 1, 2, 3 };
|
||||
r->refs.push_back(picture(gen::VideoRefMedia::IMAGE, "ref_image_1", 1));
|
||||
r->media = picture_media(6, 3);
|
||||
refused(f, std::move(r), "past the end");
|
||||
r = f.req();
|
||||
r->refs.push_back(picture(gen::VideoRefMedia::VIDEO, "ref_video_4", 4));
|
||||
refused(f, std::move(r), "takes 3");
|
||||
r = f.req();
|
||||
r->refs.push_back(picture(gen::VideoRefMedia::IMAGE, "ref_image_1", 1, 24, 16));
|
||||
r->media = picture_media(6, 0);
|
||||
refused(f, std::move(r), "ref_image_1");
|
||||
r = f.req(2);
|
||||
r->refs.push_back(picture(gen::VideoRefMedia::LAST_FRAME, "last_frame", 2));
|
||||
refused(f, std::move(r), "not the video's size");
|
||||
|
||||
VideoFixture g;
|
||||
g.build();
|
||||
CHECK_OK(g.start_refs(false));
|
||||
r = g.req();
|
||||
r->refs.push_back(sound(gen::VideoRefMedia::AUDIO, "ref_audio_1", 1, 800));
|
||||
refused(g, std::move(r), "ref_audio_1");
|
||||
|
||||
VideoFixture h;
|
||||
h.build();
|
||||
with_tower(h, 4);
|
||||
CHECK_OK(h.start_refs());
|
||||
r = h.req();
|
||||
r->tokens = { 1, 700, 701, 2, 3 };
|
||||
r->refs.push_back(picture(gen::VideoRefMedia::IMAGE, "ref_image_1", 1));
|
||||
r->media = picture_media(6, 1);
|
||||
refused(h, std::move(r), "at most 4");
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -46,6 +46,11 @@ struct FakeVideoGen : IVideoGen {
|
||||
inf.default_steps = 50;
|
||||
inf.max_steps = 65;
|
||||
inf.max_lanes = 2;
|
||||
inf.max_ref_images = 9;
|
||||
inf.max_ref_videos = 3;
|
||||
inf.max_ref_audios = 3;
|
||||
inf.shift_video = 12.0;
|
||||
inf.shift_audio = 3.0;
|
||||
}
|
||||
const VideoGenInfo& info() const override { return inf; }
|
||||
int submit(std::unique_ptr<gen::VideoRequest> r, std::string*) override {
|
||||
@@ -159,9 +164,21 @@ TEST(a_video_request_that_cannot_be_served_names_its_field) {
|
||||
std::string("num_inference_steps"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "input_reference", "file-1" } })),
|
||||
std::string("input_reference"));
|
||||
/* The output is always an MP4: `format` is not a field, so it is refused as an unknown one,
|
||||
* by name. */
|
||||
CHECK_EQ(v.refused(Videos::body({ { "format", "avi" } })), std::string("format"));
|
||||
/* The keyframe tasks belong to a model with a video encoder; this one has none, so the name
|
||||
* is refused as a task. A model with the encoder takes the task and refuses a missing frame by
|
||||
* its field instead (a_keyframe_task_refuses_a_missing_frame). */
|
||||
CHECK_EQ(v.refused(Videos::body({ { "task", "fl2va" } })), std::string("task"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "conditions", json::array({ json::object() }) } })),
|
||||
std::string("conditions"));
|
||||
/* The shift: (0, 100], a number; 0 / negative / over the cap / non-numeric are refused. */
|
||||
CHECK_EQ(v.refused(Videos::body({ { "shift", 0 } })), std::string("shift"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "shift", -1 } })), std::string("shift"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "shift", 200 } })), std::string("shift"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "shift", "hot" } })), std::string("shift"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "audio_shift", 0 } })), std::string("audio_shift"));
|
||||
CHECK_EQ(v.refused({ { "prompt", "p" }, { "target", { { "aspect_ratio", "wide" } } } }),
|
||||
std::string("target"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "target", { { "aspect_ratio", "16:9" } } } })),
|
||||
@@ -217,6 +234,30 @@ TEST(the_generator_gets_the_size_the_chunks_and_the_steps) {
|
||||
v.wait(str_at(json::parse(r.body, nullptr, false), "id"));
|
||||
}
|
||||
|
||||
/* `shift`/`audio_shift` thread to the request and echo back; omitted, the request carries 0 (the
|
||||
* driver keeps the model's trained shift) and the echo adds neither field. */
|
||||
TEST(the_shift_threads_to_the_request_and_echoes) {
|
||||
Videos v;
|
||||
HttpResponse r = v.create(Videos::body({ { "shift", 6 }, { "audio_shift", 2 } }));
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
CHECK_EQ(v.gen.last().shift_video, 6.0);
|
||||
CHECK_EQ(v.gen.last().shift_audio, 2.0);
|
||||
json o = json::parse(r.body, nullptr, false);
|
||||
CHECK(o.contains("shift"));
|
||||
CHECK_EQ(o["shift"].get<double>(), 6.0);
|
||||
CHECK_EQ(o["audio_shift"].get<double>(), 2.0);
|
||||
v.wait(str_at(o, "id"));
|
||||
|
||||
r = v.create(Videos::body());
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
CHECK_EQ(v.gen.last().shift_video, 0.0);
|
||||
CHECK_EQ(v.gen.last().shift_audio, 0.0);
|
||||
o = json::parse(r.body, nullptr, false);
|
||||
CHECK(!o.contains("shift"));
|
||||
CHECK(!o.contains("audio_shift"));
|
||||
v.wait(str_at(o, "id"));
|
||||
}
|
||||
|
||||
/* A model with a length head chooses the length of a request that names none or says "auto": the
|
||||
* generator gets 0 chunks, the video object says "auto" until the model has chosen and then the
|
||||
* length chosen. A length named is as for any model; without a head, none named is the default. */
|
||||
@@ -339,6 +380,10 @@ TEST(a_video_job_completes_and_serves_its_file) {
|
||||
SKIP("this build has no libavcodec to write the MP4 with");
|
||||
REQUIRE_EQ(str_at(o, "status"), std::string("completed"));
|
||||
CHECK_EQ(o["progress"].get<int>(), 100);
|
||||
/* The step tally rides in the object (the fake generator lands 2 steps): a waiting client
|
||||
* reads steps_done/steps_total while in_progress, and they survive into the finished object. */
|
||||
CHECK_EQ(o["steps_done"].get<int>(), 2);
|
||||
CHECK_EQ(o["steps_total"].get<int>(), 2);
|
||||
CHECK(o["completed_at"].is_number());
|
||||
CHECK(o["expires_at"].get<int64_t>() > o["completed_at"].get<int64_t>());
|
||||
CHECK(o["error"].is_null());
|
||||
@@ -387,6 +432,11 @@ TEST(a_failed_generation_is_a_failed_job_with_its_reason) {
|
||||
HttpResponse r = v.create(Videos::body());
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
json o = v.wait(str_at(json::parse(r.body, nullptr, false), "id"));
|
||||
/* The job's thread opens the MP4 writer before it draws a step, so without a codec it fails
|
||||
* the write before the generator is asked to fail -- the reason under test is unreachable.
|
||||
* Same guard as the completion case above. */
|
||||
if (str_at(o, "status") == "failed" && has(str_at(o["error"], "message"), "no libavcodec"))
|
||||
SKIP("this build has no libavcodec to reach the generator with");
|
||||
CHECK_EQ(str_at(o, "status"), std::string("failed"));
|
||||
CHECK_EQ(str_at(o["error"], "code"), std::string("generation_failed"));
|
||||
CHECK(has(str_at(o["error"], "message"), "the engine stopped"));
|
||||
@@ -399,6 +449,490 @@ TEST(the_video_routes_are_501_without_a_video_model) {
|
||||
CHECK_EQ(f.get("/v1/videos").status, 501);
|
||||
}
|
||||
|
||||
/* ref2va: the reference file parts are read from the form, and the generator gets them bounded,
|
||||
* numbered and paired — sorted by (kind, number), images first, a soundtrack after its video. */
|
||||
TEST(ref2va_reference_media_reach_the_generator) {
|
||||
Videos v;
|
||||
HttpRequest q;
|
||||
q.method = "POST";
|
||||
q.path = "/v1/videos";
|
||||
q.form = { FormPart{ "prompt", "", "", "a fox in the snow" },
|
||||
FormPart{ "size", "", "", "256x256" },
|
||||
FormPart{ "task", "", "", "ref2va" },
|
||||
FormPart{ "ref_video_audio_1", "tail.wav", "audio/wav", "RIFF" },
|
||||
FormPart{ "ref_image_2", "b.jpg", "image/jpeg", "JPEG" },
|
||||
FormPart{ "ref_audio_1", "song.mp3", "audio/mpeg", "ID3" },
|
||||
FormPart{ "ref_video_1", "tail.mp4", "video/mp4", "ftyp" },
|
||||
FormPart{ "ref_image_1", "a.png", "image/png", "png" } };
|
||||
HttpResponse r = v.f->srv->router().dispatch(q);
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
const gen::VideoRequest& g = v.gen.last();
|
||||
REQUIRE_EQ(g.refs.size(), (size_t)5);
|
||||
CHECK_EQ((int)g.refs[0].kind, (int)gen::VideoRefMedia::IMAGE);
|
||||
CHECK_EQ(g.refs[0].index, 1);
|
||||
CHECK_EQ(g.refs[0].name, std::string("ref_image_1"));
|
||||
CHECK_EQ(g.refs[0].data, std::string("png"));
|
||||
CHECK_EQ((int)g.refs[1].kind, (int)gen::VideoRefMedia::IMAGE);
|
||||
CHECK_EQ(g.refs[1].index, 2);
|
||||
CHECK_EQ((int)g.refs[2].kind, (int)gen::VideoRefMedia::VIDEO);
|
||||
CHECK_EQ(g.refs[2].filename, std::string("tail.mp4"));
|
||||
CHECK_EQ(g.refs[2].data, std::string("ftyp"));
|
||||
CHECK_EQ((int)g.refs[3].kind, (int)gen::VideoRefMedia::VIDEO_AUDIO);
|
||||
CHECK_EQ(g.refs[3].index, 1);
|
||||
CHECK_EQ((int)g.refs[4].kind, (int)gen::VideoRefMedia::AUDIO);
|
||||
CHECK_EQ(g.refs[4].filename, std::string("song.mp3"));
|
||||
json o = json::parse(r.body, nullptr, false);
|
||||
CHECK_EQ(str_at(o, "task"), std::string("ref2va"));
|
||||
REQUIRE(o["refs"].is_array());
|
||||
REQUIRE_EQ(o["refs"].size(), (size_t)5);
|
||||
CHECK_EQ(o["refs"][0].get<std::string>(), std::string("ref_image_1"));
|
||||
CHECK_EQ(o["refs"][4].get<std::string>(), std::string("ref_audio_1"));
|
||||
v.wait(str_at(o, "id"));
|
||||
}
|
||||
|
||||
/* ref2va with a vision encoder loaded: the pictures are decoded and processed, then presented
|
||||
* between the template's head and the prompt, each `<Picture k>: ` label (its own tokenised
|
||||
* string) followed by the picture's token run, in part order; the placed media go with the
|
||||
* request to the generator. */
|
||||
TEST(ref2va_pictures_are_presented_before_the_prompt) {
|
||||
FakeMultimodal mm;
|
||||
mm.expand = { 900, 901, 902 };
|
||||
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;
|
||||
} }));
|
||||
HttpRequest q;
|
||||
q.method = "POST";
|
||||
q.path = "/v1/videos";
|
||||
q.form = { FormPart{ "prompt", "", "", "a fox" },
|
||||
FormPart{ "size", "", "", "256x256" },
|
||||
FormPart{ "task", "", "", "ref2va" },
|
||||
FormPart{ "ref_image_2", "b.png", "image/png", "PB" },
|
||||
FormPart{ "ref_image_1", "a.png", "image/png", "PA" } };
|
||||
HttpResponse r = f->srv->router().dispatch(q);
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
/* Both parts were decoded as images, in presentation order. */
|
||||
REQUIRE_EQ(mm.got.size(), (size_t)2);
|
||||
CHECK(mm.got[0].first == MediaKind::Image);
|
||||
CHECK(mm.got[0].second == std::vector<uint8_t>({ 'P', 'A' }));
|
||||
CHECK(mm.got[1].second == std::vector<uint8_t>({ 'P', 'B' }));
|
||||
const gen::VideoRequest& g = gen.last();
|
||||
REQUIRE(g.media != nullptr);
|
||||
REQUIRE_EQ(g.media->items.size(), (size_t)2);
|
||||
CHECK_EQ(g.media->items[0].tok, 16); /* "<v>" + "<Picture 1>: " */
|
||||
CHECK_EQ(g.media->items[1].tok, 32); /* + the first run + "<Picture 2>: " */
|
||||
/* The token stream exactly: head, label and run per picture in part order, the prompt last.
|
||||
* The fake tokenizer turns a character into its code and leaves other ids as sent. */
|
||||
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("<Picture 2>: ");
|
||||
want.insert(want.end(), mm.expand.begin(), mm.expand.end());
|
||||
chars("a fox");
|
||||
CHECK(g.tokens == want);
|
||||
}
|
||||
|
||||
/* A generator with the VAE encoders: the picture, the video and both audios are decoded into the
|
||||
* encoders' form, each audio's mono tone spread across the encoder's channels, and every reference
|
||||
* is named before the prompt in the reference's order: the picture's label and run, a 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.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);
|
||||
}
|
||||
|
||||
/* Keyframes (task fl2va): a first and a last frame reach the generator as FIRST_FRAME and
|
||||
* LAST_FRAME references, each resized to the output canvas exactly. A keyframe pins frames of the
|
||||
* output, so its latent grid is the target's, not one snapped to its own aspect as a reference's
|
||||
* is. As in the reference (clip.tokenize and vae.encode), a keyframe reaches the transformer twice:
|
||||
* as the VAE's latents and, when the container has a vision tower, as a <Picture k> block in the
|
||||
* prompt. This is the server half; the keyframe rows are tests/video_gen_test.cpp's. */
|
||||
TEST(fl2va_keyframes_feed_the_tower_and_pin_the_output_ends) {
|
||||
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.enc_ratio = 16;
|
||||
gen.inf.max_enc_side = 512;
|
||||
} }));
|
||||
HttpRequest q;
|
||||
q.method = "POST";
|
||||
q.path = "/v1/videos";
|
||||
q.form = { FormPart{ "prompt", "", "", "fox" },
|
||||
FormPart{ "size", "", "", "256x256" },
|
||||
FormPart{ "task", "", "", "fl2va" },
|
||||
FormPart{ "first_frame", "f.png", "image/png", "PF" },
|
||||
FormPart{ "last_frame", "l.png", "image/png", "PL" } };
|
||||
HttpResponse r = f->srv->router().dispatch(q);
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
/* Both keyframes reach the vision tower as their canvas frames, the pixels the VAE is handed,
|
||||
* not as the files: one canvas resize a frame serves both. */
|
||||
CHECK(mm.got.empty());
|
||||
REQUIRE_EQ(mm.n_pframe, 2);
|
||||
REQUIRE_EQ(mm.pframe_wh.size(), (size_t)2);
|
||||
CHECK(mm.pframe_wh[0] == std::make_pair((int32_t)256, (int32_t)256));
|
||||
CHECK(mm.pframe_wh[1] == std::make_pair((int32_t)256, (int32_t)256));
|
||||
CHECK_EQ(mm.n_cenc, 2);
|
||||
CHECK_EQ(mm.n_ienc, 0); /* a keyframe is never snapped like a reference */
|
||||
CHECK_EQ(mm.cenc_w, 256);
|
||||
CHECK_EQ(mm.cenc_h, 256);
|
||||
CHECK(mm.cenc_cover); /* the last call was the last frame's centre crop */
|
||||
REQUIRE_EQ(mm.cenc_covers.size(), (size_t)2);
|
||||
CHECK(!mm.cenc_covers[0]); /* default first frame: the reference's stretch */
|
||||
CHECK(mm.cenc_covers[1]); /* the last frame: always the centre crop */
|
||||
const gen::VideoRequest& g = gen.last();
|
||||
REQUIRE_EQ(g.refs.size(), (size_t)2);
|
||||
CHECK_EQ((int)g.refs[0].kind, (int)gen::VideoRefMedia::FIRST_FRAME);
|
||||
CHECK_EQ(g.refs[0].index, 1); /* <Picture 1> = first */
|
||||
CHECK_EQ((int)g.refs[1].kind, (int)gen::VideoRefMedia::LAST_FRAME);
|
||||
CHECK_EQ(g.refs[1].index, 2); /* <Picture 2> = last */
|
||||
CHECK_EQ(g.refs[0].enc_frames, 1);
|
||||
CHECK_EQ(g.refs[0].enc_h, 256); /* the target canvas, exactly */
|
||||
CHECK_EQ(g.refs[0].enc_w, 256);
|
||||
CHECK_EQ(g.refs[0].enc_pixels.size(), (size_t)256 * 256 * 3);
|
||||
/* The keyframes reach the text encoder too: a <Picture 1> and a <Picture 2> block before the
|
||||
* prompt. */
|
||||
REQUIRE(g.media != nullptr);
|
||||
REQUIRE_EQ(g.media->items.size(), (size_t)2);
|
||||
CHECK(g.media->items[0].tok < g.media->items[1].tok);
|
||||
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("<Picture 2>: ");
|
||||
want.insert(want.end(), mm.expand.begin(), mm.expand.end());
|
||||
chars("fox");
|
||||
CHECK(g.tokens == want);
|
||||
}
|
||||
|
||||
/* A last frame alone is <Picture 1>: the number counts the pictures present, as ComfyUI's does.
|
||||
* fl2va (both ends) keeps first = 1, last = 2. */
|
||||
TEST(l2va_presents_its_sole_frame_as_picture_1) {
|
||||
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.enc_ratio = 16;
|
||||
gen.inf.max_enc_side = 512;
|
||||
} }));
|
||||
HttpRequest q;
|
||||
q.method = "POST";
|
||||
q.path = "/v1/videos";
|
||||
q.form = { FormPart{ "prompt", "", "", "fox" },
|
||||
FormPart{ "size", "", "", "256x256" },
|
||||
FormPart{ "task", "", "", "l2va" },
|
||||
FormPart{ "last_frame", "l.png", "image/png", "PL" } };
|
||||
HttpResponse r = f->srv->router().dispatch(q);
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
REQUIRE_EQ(gen.last().refs.size(), (size_t)1);
|
||||
CHECK_EQ((int)gen.last().refs[0].kind, (int)gen::VideoRefMedia::LAST_FRAME);
|
||||
CHECK_EQ(gen.last().refs[0].index, 1); /* the sole picture: <Picture 1>, not the role's 2 */
|
||||
CHECK(mm.cenc_cover); /* it still takes the last frame's centre crop */
|
||||
CHECK(mm.got.empty()); /* the tower reads the canvas frame, not the file */
|
||||
CHECK_EQ(mm.n_pframe, 1);
|
||||
REQUIRE(gen.last().media != nullptr);
|
||||
REQUIRE_EQ(gen.last().media->items.size(), (size_t)1);
|
||||
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("fox");
|
||||
CHECK(gen.last().tokens == want);
|
||||
}
|
||||
|
||||
/* first_frame_mode=center: the first keyframe is scaled to cover the canvas and centre-cropped
|
||||
* instead of stretched, so a portrait photo pinned into a landscape output is not distorted. The
|
||||
* flag reaches encoder_image_canvas on the first call; the last frame is centre-cropped either way. */
|
||||
TEST(first_frame_mode_center_cover_crops_the_first_anchor) {
|
||||
FakeMultimodal mm;
|
||||
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.enc_ratio = 16;
|
||||
gen.inf.max_enc_side = 512;
|
||||
} }));
|
||||
HttpRequest q;
|
||||
q.method = "POST";
|
||||
q.path = "/v1/videos";
|
||||
q.form = { FormPart{ "prompt", "", "", "fox" },
|
||||
FormPart{ "size", "", "", "256x256" },
|
||||
FormPart{ "task", "", "", "fl2va" },
|
||||
FormPart{ "first_frame", "f.png", "image/png", "PF" },
|
||||
FormPart{ "last_frame", "l.png", "image/png", "PL" },
|
||||
FormPart{ "first_frame_mode", "", "", "center" } };
|
||||
HttpResponse r = f->srv->router().dispatch(q);
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
REQUIRE_EQ(mm.cenc_covers.size(), (size_t)2);
|
||||
CHECK(mm.cenc_covers[0]); /* the first keyframe: centre crop, not stretch */
|
||||
CHECK(mm.cenc_covers[1]); /* the last: unchanged */
|
||||
CHECK_EQ(mm.cenc_w, 256);
|
||||
CHECK_EQ(mm.cenc_h, 256); /* still the canvas exactly: a pin needs its grid */
|
||||
}
|
||||
|
||||
/* first_frame_mode takes two values; anything else is refused naming the field, and an explicit
|
||||
* "stretch" (or empty form field) keeps the reference's default. */
|
||||
TEST(first_frame_mode_refuses_a_mode_it_does_not_know) {
|
||||
FakeMultimodal mm;
|
||||
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.enc_ratio = 16;
|
||||
gen.inf.max_enc_side = 512;
|
||||
} }));
|
||||
auto post = [&](const char* mode) {
|
||||
HttpRequest q;
|
||||
q.method = "POST";
|
||||
q.path = "/v1/videos";
|
||||
q.form = { FormPart{ "prompt", "", "", "fox" }, FormPart{ "size", "", "", "256x256" },
|
||||
FormPart{ "first_frame", "f.png", "image/png", "PF" } };
|
||||
if (mode) q.form.push_back(FormPart{ "first_frame_mode", "", "", mode });
|
||||
return f->srv->router().dispatch(q);
|
||||
};
|
||||
{
|
||||
HttpResponse r = post("warp");
|
||||
CHECK(r.status >= 400);
|
||||
CHECK(r.body.find("first_frame_mode") != std::string::npos);
|
||||
}
|
||||
mm.cenc_covers.clear();
|
||||
{
|
||||
HttpResponse r = post("stretch");
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
REQUIRE_EQ(mm.cenc_covers.size(), (size_t)1);
|
||||
CHECK(!mm.cenc_covers[0]);
|
||||
}
|
||||
mm.cenc_covers.clear();
|
||||
{
|
||||
HttpResponse r = post(""); /* an empty form field is "not set" */
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
REQUIRE_EQ(mm.cenc_covers.size(), (size_t)1);
|
||||
CHECK(!mm.cenc_covers[0]);
|
||||
}
|
||||
}
|
||||
|
||||
/* Without a vision tower a keyframe request still renders: the keyframes keep their VAE latents and
|
||||
* add no prompt media. */
|
||||
TEST(fl2va_without_a_tower_pins_only) {
|
||||
FakeMultimodal mm;
|
||||
mm.accept_image = false; /* a container converted without its vision tower */
|
||||
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.enc_ratio = 16;
|
||||
gen.inf.max_enc_side = 512;
|
||||
} }));
|
||||
HttpRequest q;
|
||||
q.method = "POST";
|
||||
q.path = "/v1/videos";
|
||||
q.form = { FormPart{ "prompt", "", "", "fox" },
|
||||
FormPart{ "size", "", "", "256x256" },
|
||||
FormPart{ "task", "", "", "fl2va" },
|
||||
FormPart{ "first_frame", "f.png", "image/png", "PF" },
|
||||
FormPart{ "last_frame", "l.png", "image/png", "PL" } };
|
||||
HttpResponse r = f->srv->router().dispatch(q);
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
CHECK_EQ(mm.got.size(), (size_t)0); /* nothing reached the absent tower */
|
||||
CHECK_EQ(mm.n_cenc, 2); /* both keyframes still resized for the VAE */
|
||||
const gen::VideoRequest& g = gen.last();
|
||||
CHECK(g.media == nullptr); /* no prompt media */
|
||||
CHECK_EQ(g.refs[0].enc_pixels.size(), (size_t)256 * 256 * 3);
|
||||
CHECK_EQ(g.refs[1].enc_pixels.size(), (size_t)256 * 256 * 3);
|
||||
}
|
||||
|
||||
/* A named keyframe task must carry its frame: fl2va wants both ends. */
|
||||
TEST(a_keyframe_task_refuses_a_missing_frame) {
|
||||
FakeVideoGen gen;
|
||||
std::unique_ptr<Fixture> f(new Fixture(Fixture::Tweak{ [&](ServerOptions& o, Deps& d) {
|
||||
d.videos = &gen;
|
||||
o.video_model = true;
|
||||
gen.inf.enc_ratio = 16;
|
||||
gen.inf.max_enc_side = 256;
|
||||
} }));
|
||||
/* fl2va with a first but no last -> names last_frame. */
|
||||
HttpRequest q;
|
||||
q.method = "POST";
|
||||
q.path = "/v1/videos";
|
||||
q.form = { FormPart{ "prompt", "", "", "fox" }, FormPart{ "size", "", "", "256x256" },
|
||||
FormPart{ "task", "", "", "fl2va" },
|
||||
FormPart{ "first_frame", "f.png", "image/png", "PF" } };
|
||||
HttpResponse r = f->srv->router().dispatch(q);
|
||||
CHECK(r.status >= 400);
|
||||
CHECK(r.body.find("last_frame") != std::string::npos);
|
||||
}
|
||||
|
||||
/* 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) {
|
||||
Videos v;
|
||||
auto refused = [&](const std::vector<FormPart>& media, const std::string& param) {
|
||||
HttpRequest q;
|
||||
q.method = "POST";
|
||||
q.path = "/v1/videos";
|
||||
q.form = { FormPart{ "prompt", "", "", "a fox" }, FormPart{ "size", "", "", "256x256" },
|
||||
FormPart{ "task", "", "", "ref2va" } };
|
||||
for (const FormPart& m : media) q.form.push_back(m);
|
||||
HttpResponse r = v.f->srv->router().dispatch(q);
|
||||
CHECK_EQ(r.status, 400);
|
||||
CHECK_EQ(str_at(json::parse(r.body, nullptr, false)["error"], "param"), param);
|
||||
};
|
||||
/* The task without any media (and JSON alone cannot carry the bytes). */
|
||||
refused({}, "task");
|
||||
CHECK_EQ(v.refused(Videos::body({ { "task", "ref2va" } })), std::string("task"));
|
||||
/* Empty bytes. */
|
||||
refused({ FormPart{ "ref_image_1", "a.png", "image/png", "" } }, "ref_image_1");
|
||||
/* Numbering with a gap or a repeat. */
|
||||
refused({ FormPart{ "ref_image_1", "a.png", "image/png", "x" },
|
||||
FormPart{ "ref_image_3", "b.png", "image/png", "x" } }, "ref_image_2");
|
||||
refused({ FormPart{ "ref_image_1", "a.png", "image/png", "x" },
|
||||
FormPart{ "ref_image_1", "b.png", "image/png", "y" } }, "ref_image_1");
|
||||
/* A soundtrack with no video of its number; ten images over the API's nine. */
|
||||
refused({ FormPart{ "ref_video_audio_1", "s.wav", "audio/wav", "x" } }, "ref_video_audio_1");
|
||||
{
|
||||
std::vector<FormPart> ten;
|
||||
for (int i = 1; i <= 10; ++i)
|
||||
ten.push_back(FormPart{ "ref_image_" + std::to_string(i), "p.png", "image/png", "x" });
|
||||
refused(ten, "ref_image_10");
|
||||
}
|
||||
/* Reference files with no task, and with t2va: the task is the mistake. */
|
||||
for (const char* task : { (const char*)nullptr, "t2va" }) {
|
||||
HttpRequest q;
|
||||
q.method = "POST";
|
||||
q.path = "/v1/videos";
|
||||
q.form = { FormPart{ "prompt", "", "", "a fox" }, FormPart{ "size", "", "", "256x256" } };
|
||||
if (task) q.form.push_back(FormPart{ "task", "", "", task });
|
||||
q.form.push_back(FormPart{ "ref_image_1", "a.png", "image/png", "x" });
|
||||
HttpResponse r = v.f->srv->router().dispatch(q);
|
||||
CHECK_EQ(r.status, 400);
|
||||
CHECK_EQ(str_at(json::parse(r.body, nullptr, false)["error"], "param"),
|
||||
std::string("task"));
|
||||
}
|
||||
/* The caps ride the capability block /v1/models and /server_info share, so a client can
|
||||
* gate on them without probing a refusal. This fake declares 9/3/3 and a 64-token prompt,
|
||||
* all at or under the API's caps, so the declaration shows through. */
|
||||
auto caps = [&](json* out) {
|
||||
HttpRequest mq;
|
||||
mq.method = "GET";
|
||||
mq.path = "/v1/models";
|
||||
HttpResponse mr = v.f->srv->router().dispatch(mq);
|
||||
CHECK_EQ(mr.status, 200);
|
||||
*out = json::parse(mr.body, nullptr, false)["data"][0]["capabilities"];
|
||||
};
|
||||
json c;
|
||||
caps(&c);
|
||||
CHECK_EQ(c["video_generation"], true);
|
||||
CHECK_EQ(c["video_max_text"], 64);
|
||||
CHECK_EQ(c["video_max_ref_images"], 9);
|
||||
CHECK_EQ(c["video_max_ref_videos"], 3);
|
||||
CHECK_EQ(c["video_max_ref_audios"], 3);
|
||||
/* A model that declares no reference media does not take the task at all. */
|
||||
v.gen.inf.max_ref_images = v.gen.inf.max_ref_videos = v.gen.inf.max_ref_audios = 0;
|
||||
HttpRequest q;
|
||||
q.method = "POST";
|
||||
q.path = "/v1/videos";
|
||||
q.form = { FormPart{ "prompt", "", "", "a fox" }, FormPart{ "size", "", "", "256x256" },
|
||||
FormPart{ "task", "", "", "ref2va" },
|
||||
FormPart{ "ref_image_1", "a.png", "image/png", "x" } };
|
||||
HttpResponse r = v.f->srv->router().dispatch(q);
|
||||
CHECK_EQ(r.status, 400);
|
||||
CHECK_EQ(str_at(json::parse(r.body, nullptr, false)["error"], "param"), std::string("task"));
|
||||
CHECK_EQ(v.gen.got.size(), (size_t)0); /* nothing was ever queued */
|
||||
/* And the caps the model reports match what it refuses: the zero counts say what the refusal
|
||||
* does, before a client spends a request on it. */
|
||||
caps(&c);
|
||||
CHECK_EQ(c["video_max_ref_images"], 0);
|
||||
CHECK_EQ(c["video_max_ref_videos"], 0);
|
||||
CHECK_EQ(c["video_max_ref_audios"], 0);
|
||||
CHECK_EQ(c["video_max_text"], 64);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* A PNG of w x h, every pixel (r, g, b). */
|
||||
|
||||
Reference in new issue
Block a user