Archived
radiance 1.8.0
- video: MiniMax-H3 and FastVideo's FastH3 8-Step V2, a video with its stereo soundtrack from text on OpenAI's /v1/videos, block fp8 on two cards - music: MiniMax-Music3, songs from lyrics and a description on /v1/audio/speech - speech: Breeze-TTS-2 on /v1/audio/speech and vLLM-Omni's realtime WebSocket - runtime LoRA adapters beside the base model, picked per request by `model` (baKon, #105) - several agent streams keep their cached history: --checkpoint-slots auto, the new default, sizes the snapshot store by --max-num-seqs (#108) - the Swift 1.5 27B W4 releases convert and serve: compressed-tensors AWQ and GPTQ int4, AutoRound, ModelOpt NVFP4 (#110) - the image's host tests pass where perf_event_open is refused, as in BuildKit's sandbox (#106) - plugin ABI 21: out-of-tree plugins must be rebuilt
This commit is contained in:
1 parent
91127395ee
commit
7a7707a955
179 files changed
+37542
-1892
No files matched your search
@@ -13,6 +13,9 @@ ABI_FIELD(RadArchProbe, enc_merge)
|
||||
ABI_FIELD(RadArchProbe, audio_frames)
|
||||
ABI_FIELD(RadArchProbe, gen_rows)
|
||||
ABI_FIELD(RadArchProbe, gen_patches)
|
||||
ABI_FIELD(RadArchProbe, gen_audio)
|
||||
ABI_FIELD(RadArchProbe, gen_ctx)
|
||||
ABI_FIELD(RadArchProbe, gen_video)
|
||||
ABI_STRUCT(RadArgs)
|
||||
ABI_FIELD(RadArgs, t)
|
||||
ABI_FIELD(RadArgs, n_t)
|
||||
@@ -69,6 +72,8 @@ ABI_FIELD(RadBatch, enc_cu)
|
||||
ABI_FIELD(RadBatch, enc_max_seg)
|
||||
ABI_FIELD(RadBatch, gen)
|
||||
ABI_FIELD(RadBatch, gen_b)
|
||||
ABI_FIELD(RadBatch, agen_b)
|
||||
ABI_FIELD(RadBatch, vgen_b)
|
||||
ABI_STRUCT(RadBufDecl)
|
||||
ABI_FIELD(RadBufDecl, dtype)
|
||||
ABI_FIELD(RadBufDecl, rank)
|
||||
@@ -94,6 +99,74 @@ ABI_FIELD(RadBuildCtx, max_enc_patches)
|
||||
ABI_FIELD(RadBuildCtx, max_out_rows)
|
||||
ABI_FIELD(RadBuildCtx, max_audio_frames)
|
||||
ABI_FIELD(RadBuildCtx, max_mixed_tok)
|
||||
ABI_STRUCT(RadAudioGenBatch)
|
||||
ABI_FIELD(RadAudioGenBatch, n_lane)
|
||||
ABI_FIELD(RadAudioGenBatch, lane)
|
||||
ABI_FIELD(RadAudioGenBatch, lane_h)
|
||||
ABI_FIELD(RadAudioGenBatch, last)
|
||||
ABI_FIELD(RadAudioGenBatch, last_h)
|
||||
ABI_FIELD(RadAudioGenBatch, frame)
|
||||
ABI_FIELD(RadAudioGenBatch, frame_h)
|
||||
ABI_FIELD(RadAudioGenBatch, seed)
|
||||
ABI_FIELD(RadAudioGenBatch, slot)
|
||||
ABI_FIELD(RadAudioGenBatch, last_row)
|
||||
ABI_FIELD(RadAudioGenBatch, prefix)
|
||||
ABI_FIELD(RadAudioGenBatch, t)
|
||||
ABI_FIELD(RadAudioGenBatch, t_next)
|
||||
ABI_FIELD(RadAudioGenBatch, cfg)
|
||||
ABI_FIELD(RadAudioGenBatch, pair)
|
||||
ABI_FIELD(RadAudioGenBatch, win_lane)
|
||||
ABI_FIELD(RadAudioGenBatch, win_lane_h)
|
||||
ABI_FIELD(RadAudioGenBatch, flags)
|
||||
ABI_FIELD(RadAudioGenBatch, flags_h)
|
||||
ABI_FIELD(RadAudioGenBatch, win_index)
|
||||
ABI_FIELD(RadAudioGenBatch, win_index_h)
|
||||
ABI_FIELD(RadAudioGenBatch, win_frame0)
|
||||
ABI_FIELD(RadAudioGenBatch, win_frame0_h)
|
||||
ABI_FIELD(RadAudioGenBatch, win_frames)
|
||||
ABI_FIELD(RadAudioGenBatch, win_frames_h)
|
||||
ABI_FIELD(RadAudioGenBatch, lat_rows)
|
||||
ABI_FIELD(RadAudioGenBatch, lat_cu)
|
||||
ABI_FIELD(RadAudioGenBatch, lat_cu_h)
|
||||
ABI_FIELD(RadAudioGenBatch, lat_src)
|
||||
ABI_FIELD(RadAudioGenBatch, voc_lane)
|
||||
ABI_FIELD(RadAudioGenBatch, voc_window)
|
||||
ABI_FIELD(RadAudioGenBatch, voc_latents)
|
||||
ABI_FIELD(RadAudioGenBatch, voc_left)
|
||||
ABI_FIELD(RadAudioGenBatch, voc_right)
|
||||
ABI_FIELD(RadAudioGenBatch, voc_frame0)
|
||||
ABI_STRUCT(RadAudioGenDecl)
|
||||
ABI_FIELD(RadAudioGenDecl, name)
|
||||
ABI_FIELD(RadAudioGenDecl, tmpl)
|
||||
ABI_FIELD(RadAudioGenDecl, neg_token)
|
||||
ABI_FIELD(RadAudioGenDecl, neg_keep_head)
|
||||
ABI_FIELD(RadAudioGenDecl, neg_keep_tail)
|
||||
ABI_FIELD(RadAudioGenDecl, max_prompt)
|
||||
ABI_FIELD(RadAudioGenDecl, max_frames)
|
||||
ABI_FIELD(RadAudioGenDecl, frame_rate_num)
|
||||
ABI_FIELD(RadAudioGenDecl, frame_rate_den)
|
||||
ABI_FIELD(RadAudioGenDecl, win_frames)
|
||||
ABI_FIELD(RadAudioGenDecl, win_hop)
|
||||
ABI_FIELD(RadAudioGenDecl, win_lead)
|
||||
ABI_FIELD(RadAudioGenDecl, lat_num)
|
||||
ABI_FIELD(RadAudioGenDecl, lat_den)
|
||||
ABI_FIELD(RadAudioGenDecl, latent_channels)
|
||||
ABI_FIELD(RadAudioGenDecl, win_crop_left)
|
||||
ABI_FIELD(RadAudioGenDecl, win_crop_right)
|
||||
ABI_FIELD(RadAudioGenDecl, samples_per_latent)
|
||||
ABI_FIELD(RadAudioGenDecl, sample_rate)
|
||||
ABI_FIELD(RadAudioGenDecl, channels)
|
||||
ABI_FIELD(RadAudioGenDecl, default_steps)
|
||||
ABI_FIELD(RadAudioGenDecl, default_cfg)
|
||||
ABI_FIELD(RadAudioGenDecl, max_lanes)
|
||||
ABI_FIELD(RadAudioGenDecl, status)
|
||||
ABI_FIELD(RadAudioGenDecl, audio_out)
|
||||
ABI_FIELD(RadAudioGenDecl, tmpl_plain)
|
||||
ABI_FIELD(RadAudioGenDecl, neg_tmpl)
|
||||
ABI_FIELD(RadAudioGenDecl, prompt_whole)
|
||||
ABI_FIELD(RadAudioGenDecl, first_frame)
|
||||
ABI_FIELD(RadAudioGenDecl, voc_chunk)
|
||||
ABI_FIELD(RadAudioGenDecl, voc_context)
|
||||
ABI_STRUCT(RadAudioFormat)
|
||||
ABI_FIELD(RadAudioFormat, struct_size)
|
||||
ABI_FIELD(RadAudioFormat, audio_open)
|
||||
@@ -383,6 +456,7 @@ ABI_FIELD(RadNameMap, n_src)
|
||||
ABI_FIELD(RadNameMap, src)
|
||||
ABI_FIELD(RadNameMap, concat_dim)
|
||||
ABI_FIELD(RadNameMap, src_index)
|
||||
ABI_FIELD(RadNameMap, src_rows)
|
||||
ABI_STRUCT(RadOpSchema)
|
||||
ABI_FIELD(RadOpSchema, op)
|
||||
ABI_FIELD(RadOpSchema, params)
|
||||
@@ -517,6 +591,69 @@ ABI_FIELD(RadTunable, values)
|
||||
ABI_FIELD(RadTunable, n_values)
|
||||
ABI_FIELD(RadTunable, deflt)
|
||||
ABI_FIELD(RadTunable, doc)
|
||||
ABI_STRUCT(RadVideoGenBatch)
|
||||
ABI_FIELD(RadVideoGenBatch, lane)
|
||||
ABI_FIELD(RadVideoGenBatch, geom)
|
||||
ABI_FIELD(RadVideoGenBatch, geom_d)
|
||||
ABI_FIELD(RadVideoGenBatch, lane_d)
|
||||
ABI_FIELD(RadVideoGenBatch, first_d)
|
||||
ABI_FIELD(RadVideoGenBatch, seg_cu)
|
||||
ABI_FIELD(RadVideoGenBatch, lat_cu)
|
||||
ABI_FIELD(RadVideoGenBatch, n_steps)
|
||||
ABI_FIELD(RadVideoGenBatch, t_video)
|
||||
ABI_FIELD(RadVideoGenBatch, t_audio)
|
||||
ABI_FIELD(RadVideoGenBatch, step)
|
||||
ABI_FIELD(RadVideoGenBatch, sched)
|
||||
ABI_FIELD(RadVideoGenBatch, pos)
|
||||
ABI_FIELD(RadVideoGenBatch, seed)
|
||||
ABI_FIELD(RadVideoGenBatch, chunk)
|
||||
ABI_FIELD(RadVideoGenBatch, n_chunks)
|
||||
ABI_FIELD(RadVideoGenBatch, dec_rows)
|
||||
ABI_FIELD(RadVideoGenBatch, n_frames_out)
|
||||
ABI_FIELD(RadVideoGenBatch, n_samples)
|
||||
ABI_STRUCT(RadVideoGenDecl)
|
||||
ABI_FIELD(RadVideoGenDecl, name)
|
||||
ABI_FIELD(RadVideoGenDecl, tmpl)
|
||||
ABI_FIELD(RadVideoGenDecl, max_text)
|
||||
ABI_FIELD(RadVideoGenDecl, fps_num)
|
||||
ABI_FIELD(RadVideoGenDecl, fps_den)
|
||||
ABI_FIELD(RadVideoGenDecl, frames_per_chunk)
|
||||
ABI_FIELD(RadVideoGenDecl, frames_tail)
|
||||
ABI_FIELD(RadVideoGenDecl, latents_per_chunk)
|
||||
ABI_FIELD(RadVideoGenDecl, latents_tail)
|
||||
ABI_FIELD(RadVideoGenDecl, dec_latents)
|
||||
ABI_FIELD(RadVideoGenDecl, min_chunks)
|
||||
ABI_FIELD(RadVideoGenDecl, max_chunks)
|
||||
ABI_FIELD(RadVideoGenDecl, latent_scale)
|
||||
ABI_FIELD(RadVideoGenDecl, latent_channels)
|
||||
ABI_FIELD(RadVideoGenDecl, patch)
|
||||
ABI_FIELD(RadVideoGenDecl, size_multiple)
|
||||
ABI_FIELD(RadVideoGenDecl, min_side)
|
||||
ABI_FIELD(RadVideoGenDecl, max_area)
|
||||
ABI_FIELD(RadVideoGenDecl, max_aspect)
|
||||
ABI_FIELD(RadVideoGenDecl, default_width)
|
||||
ABI_FIELD(RadVideoGenDecl, default_height)
|
||||
ABI_FIELD(RadVideoGenDecl, default_chunks)
|
||||
ABI_FIELD(RadVideoGenDecl, sample_rate)
|
||||
ABI_FIELD(RadVideoGenDecl, audio_rate)
|
||||
ABI_FIELD(RadVideoGenDecl, audio_channels)
|
||||
ABI_FIELD(RadVideoGenDecl, audio_latent_channels)
|
||||
ABI_FIELD(RadVideoGenDecl, default_steps)
|
||||
ABI_FIELD(RadVideoGenDecl, max_steps)
|
||||
ABI_FIELD(RadVideoGenDecl, shift_video)
|
||||
ABI_FIELD(RadVideoGenDecl, shift_audio)
|
||||
ABI_FIELD(RadVideoGenDecl, max_lanes)
|
||||
ABI_FIELD(RadVideoGenDecl, frames_out)
|
||||
ABI_FIELD(RadVideoGenDecl, audio_out)
|
||||
ABI_FIELD(RadVideoGenDecl, n_rungs)
|
||||
ABI_FIELD(RadVideoGenDecl, rungs)
|
||||
ABI_STRUCT(RadVideoGeom)
|
||||
ABI_FIELD(RadVideoGeom, n_text)
|
||||
ABI_FIELD(RadVideoGeom, frames)
|
||||
ABI_FIELD(RadVideoGeom, lat_frames)
|
||||
ABI_FIELD(RadVideoGeom, lat_h)
|
||||
ABI_FIELD(RadVideoGeom, lat_w)
|
||||
ABI_FIELD(RadVideoGeom, n_audio)
|
||||
ABI_STRUCT(RadVocabHeader)
|
||||
ABI_FIELD(RadVocabHeader, kind)
|
||||
ABI_FIELD(RadVocabHeader, n_tokens)
|
||||
|
||||
+141
-4
@@ -1,8 +1,8 @@
|
||||
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 18 and
|
||||
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 21 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, 48 },
|
||||
{ "RadArchProbe", "", 0, 72 },
|
||||
{ "RadArchProbe", "draft_depth", 0, 4 },
|
||||
{ "RadArchProbe", "draft_depth_fixed", 4, 4 },
|
||||
{ "RadArchProbe", "shape_probe_ok", 8, 4 },
|
||||
@@ -10,6 +10,9 @@
|
||||
{ "RadArchProbe", "audio_frames", 24, 8 },
|
||||
{ "RadArchProbe", "gen_rows", 32, 8 },
|
||||
{ "RadArchProbe", "gen_patches", 40, 8 },
|
||||
{ "RadArchProbe", "gen_audio", 48, 4 },
|
||||
{ "RadArchProbe", "gen_ctx", 56, 8 },
|
||||
{ "RadArchProbe", "gen_video", 64, 4 },
|
||||
{ "RadArgs", "", 0, 64 },
|
||||
{ "RadArgs", "t", 0, 8 },
|
||||
{ "RadArgs", "n_t", 8, 4 },
|
||||
@@ -20,7 +23,7 @@
|
||||
{ "RadArgs", "instance", 48, 8 },
|
||||
{ "RadArgs", "rank", 56, 4 },
|
||||
{ "RadArgs", "world_size", 60, 4 },
|
||||
{ "RadBatch", "", 0, 320 },
|
||||
{ "RadBatch", "", 0, 336 },
|
||||
{ "RadBatch", "phase", 0, 4 },
|
||||
{ "RadBatch", "step", 4, 4 },
|
||||
{ "RadBatch", "n_tok", 8, 8 },
|
||||
@@ -66,6 +69,8 @@
|
||||
{ "RadBatch", "enc_max_seg", 304, 4 },
|
||||
{ "RadBatch", "gen", 308, 4 },
|
||||
{ "RadBatch", "gen_b", 312, 8 },
|
||||
{ "RadBatch", "agen_b", 320, 8 },
|
||||
{ "RadBatch", "vgen_b", 328, 8 },
|
||||
{ "RadBufDecl", "", 0, 80 },
|
||||
{ "RadBufDecl", "dtype", 0, 4 },
|
||||
{ "RadBufDecl", "rank", 4, 4 },
|
||||
@@ -91,6 +96,74 @@
|
||||
{ "RadBuildCtx", "max_out_rows", 80, 8 },
|
||||
{ "RadBuildCtx", "max_audio_frames", 88, 8 },
|
||||
{ "RadBuildCtx", "max_mixed_tok", 96, 8 },
|
||||
{ "RadAudioGenBatch", "", 0, 264 },
|
||||
{ "RadAudioGenBatch", "n_lane", 0, 8 },
|
||||
{ "RadAudioGenBatch", "lane", 8, 8 },
|
||||
{ "RadAudioGenBatch", "lane_h", 16, 8 },
|
||||
{ "RadAudioGenBatch", "last", 24, 8 },
|
||||
{ "RadAudioGenBatch", "last_h", 32, 8 },
|
||||
{ "RadAudioGenBatch", "frame", 40, 8 },
|
||||
{ "RadAudioGenBatch", "frame_h", 48, 8 },
|
||||
{ "RadAudioGenBatch", "seed", 56, 8 },
|
||||
{ "RadAudioGenBatch", "slot", 64, 8 },
|
||||
{ "RadAudioGenBatch", "last_row", 72, 8 },
|
||||
{ "RadAudioGenBatch", "prefix", 80, 8 },
|
||||
{ "RadAudioGenBatch", "t", 88, 8 },
|
||||
{ "RadAudioGenBatch", "t_next", 96, 8 },
|
||||
{ "RadAudioGenBatch", "cfg", 104, 8 },
|
||||
{ "RadAudioGenBatch", "pair", 112, 8 },
|
||||
{ "RadAudioGenBatch", "win_lane", 120, 8 },
|
||||
{ "RadAudioGenBatch", "win_lane_h", 128, 8 },
|
||||
{ "RadAudioGenBatch", "flags", 136, 8 },
|
||||
{ "RadAudioGenBatch", "flags_h", 144, 8 },
|
||||
{ "RadAudioGenBatch", "win_index", 152, 8 },
|
||||
{ "RadAudioGenBatch", "win_index_h", 160, 8 },
|
||||
{ "RadAudioGenBatch", "win_frame0", 168, 8 },
|
||||
{ "RadAudioGenBatch", "win_frame0_h", 176, 8 },
|
||||
{ "RadAudioGenBatch", "win_frames", 184, 8 },
|
||||
{ "RadAudioGenBatch", "win_frames_h", 192, 8 },
|
||||
{ "RadAudioGenBatch", "lat_rows", 200, 8 },
|
||||
{ "RadAudioGenBatch", "lat_cu", 208, 8 },
|
||||
{ "RadAudioGenBatch", "lat_cu_h", 216, 8 },
|
||||
{ "RadAudioGenBatch", "lat_src", 224, 8 },
|
||||
{ "RadAudioGenBatch", "voc_lane", 232, 4 },
|
||||
{ "RadAudioGenBatch", "voc_window", 236, 4 },
|
||||
{ "RadAudioGenBatch", "voc_latents", 240, 4 },
|
||||
{ "RadAudioGenBatch", "voc_left", 244, 4 },
|
||||
{ "RadAudioGenBatch", "voc_right", 248, 4 },
|
||||
{ "RadAudioGenBatch", "voc_frame0", 256, 8 },
|
||||
{ "RadAudioGenDecl", "", 0, 224 },
|
||||
{ "RadAudioGenDecl", "name", 0, 8 },
|
||||
{ "RadAudioGenDecl", "tmpl", 8, 8 },
|
||||
{ "RadAudioGenDecl", "neg_token", 16, 4 },
|
||||
{ "RadAudioGenDecl", "neg_keep_head", 20, 4 },
|
||||
{ "RadAudioGenDecl", "neg_keep_tail", 24, 4 },
|
||||
{ "RadAudioGenDecl", "max_prompt", 32, 8 },
|
||||
{ "RadAudioGenDecl", "max_frames", 40, 8 },
|
||||
{ "RadAudioGenDecl", "frame_rate_num", 48, 8 },
|
||||
{ "RadAudioGenDecl", "frame_rate_den", 56, 8 },
|
||||
{ "RadAudioGenDecl", "win_frames", 64, 8 },
|
||||
{ "RadAudioGenDecl", "win_hop", 72, 8 },
|
||||
{ "RadAudioGenDecl", "win_lead", 80, 8 },
|
||||
{ "RadAudioGenDecl", "lat_num", 88, 8 },
|
||||
{ "RadAudioGenDecl", "lat_den", 96, 8 },
|
||||
{ "RadAudioGenDecl", "latent_channels", 104, 8 },
|
||||
{ "RadAudioGenDecl", "win_crop_left", 112, 8 },
|
||||
{ "RadAudioGenDecl", "win_crop_right", 120, 8 },
|
||||
{ "RadAudioGenDecl", "samples_per_latent", 128, 8 },
|
||||
{ "RadAudioGenDecl", "sample_rate", 136, 8 },
|
||||
{ "RadAudioGenDecl", "channels", 144, 8 },
|
||||
{ "RadAudioGenDecl", "default_steps", 152, 8 },
|
||||
{ "RadAudioGenDecl", "default_cfg", 160, 8 },
|
||||
{ "RadAudioGenDecl", "max_lanes", 168, 8 },
|
||||
{ "RadAudioGenDecl", "status", 176, 4 },
|
||||
{ "RadAudioGenDecl", "audio_out", 180, 4 },
|
||||
{ "RadAudioGenDecl", "tmpl_plain", 184, 8 },
|
||||
{ "RadAudioGenDecl", "neg_tmpl", 192, 8 },
|
||||
{ "RadAudioGenDecl", "prompt_whole", 200, 4 },
|
||||
{ "RadAudioGenDecl", "first_frame", 204, 4 },
|
||||
{ "RadAudioGenDecl", "voc_chunk", 208, 8 },
|
||||
{ "RadAudioGenDecl", "voc_context", 216, 8 },
|
||||
{ "RadAudioFormat", "", 0, 72 },
|
||||
{ "RadAudioFormat", "struct_size", 0, 4 },
|
||||
{ "RadAudioFormat", "audio_open", 8, 8 },
|
||||
@@ -373,13 +446,14 @@
|
||||
{ "RadModelMeta", "n_kv", 124, 4 },
|
||||
{ "RadModelMeta", "kv_key", 128, 8 },
|
||||
{ "RadModelMeta", "kv_val", 136, 8 },
|
||||
{ "RadNameMap", "", 0, 120 },
|
||||
{ "RadNameMap", "", 0, 184 },
|
||||
{ "RadNameMap", "declared", 0, 8 },
|
||||
{ "RadNameMap", "mode", 8, 4 },
|
||||
{ "RadNameMap", "n_src", 12, 4 },
|
||||
{ "RadNameMap", "src", 16, 64 },
|
||||
{ "RadNameMap", "concat_dim", 80, 4 },
|
||||
{ "RadNameMap", "src_index", 84, 32 },
|
||||
{ "RadNameMap", "src_rows", 120, 64 },
|
||||
{ "RadOpSchema", "", 0, 48 },
|
||||
{ "RadOpSchema", "op", 0, 8 },
|
||||
{ "RadOpSchema", "params", 8, 8 },
|
||||
@@ -514,6 +588,69 @@
|
||||
{ "RadTunable", "n_values", 16, 4 },
|
||||
{ "RadTunable", "deflt", 24, 8 },
|
||||
{ "RadTunable", "doc", 32, 8 },
|
||||
{ "RadVideoGenBatch", "", 0, 160 },
|
||||
{ "RadVideoGenBatch", "lane", 0, 4 },
|
||||
{ "RadVideoGenBatch", "geom", 4, 24 },
|
||||
{ "RadVideoGenBatch", "geom_d", 32, 8 },
|
||||
{ "RadVideoGenBatch", "lane_d", 40, 8 },
|
||||
{ "RadVideoGenBatch", "first_d", 48, 8 },
|
||||
{ "RadVideoGenBatch", "seg_cu", 56, 8 },
|
||||
{ "RadVideoGenBatch", "lat_cu", 64, 8 },
|
||||
{ "RadVideoGenBatch", "n_steps", 72, 4 },
|
||||
{ "RadVideoGenBatch", "t_video", 80, 8 },
|
||||
{ "RadVideoGenBatch", "t_audio", 88, 8 },
|
||||
{ "RadVideoGenBatch", "step", 96, 4 },
|
||||
{ "RadVideoGenBatch", "sched", 104, 8 },
|
||||
{ "RadVideoGenBatch", "pos", 112, 8 },
|
||||
{ "RadVideoGenBatch", "seed", 120, 8 },
|
||||
{ "RadVideoGenBatch", "chunk", 128, 4 },
|
||||
{ "RadVideoGenBatch", "n_chunks", 132, 4 },
|
||||
{ "RadVideoGenBatch", "dec_rows", 136, 8 },
|
||||
{ "RadVideoGenBatch", "n_frames_out", 144, 4 },
|
||||
{ "RadVideoGenBatch", "n_samples", 152, 8 },
|
||||
{ "RadVideoGenDecl", "", 0, 272 },
|
||||
{ "RadVideoGenDecl", "name", 0, 8 },
|
||||
{ "RadVideoGenDecl", "tmpl", 8, 8 },
|
||||
{ "RadVideoGenDecl", "max_text", 16, 8 },
|
||||
{ "RadVideoGenDecl", "fps_num", 24, 8 },
|
||||
{ "RadVideoGenDecl", "fps_den", 32, 8 },
|
||||
{ "RadVideoGenDecl", "frames_per_chunk", 40, 8 },
|
||||
{ "RadVideoGenDecl", "frames_tail", 48, 8 },
|
||||
{ "RadVideoGenDecl", "latents_per_chunk", 56, 8 },
|
||||
{ "RadVideoGenDecl", "latents_tail", 64, 8 },
|
||||
{ "RadVideoGenDecl", "dec_latents", 72, 8 },
|
||||
{ "RadVideoGenDecl", "min_chunks", 80, 8 },
|
||||
{ "RadVideoGenDecl", "max_chunks", 88, 8 },
|
||||
{ "RadVideoGenDecl", "latent_scale", 96, 8 },
|
||||
{ "RadVideoGenDecl", "latent_channels", 104, 8 },
|
||||
{ "RadVideoGenDecl", "patch", 112, 8 },
|
||||
{ "RadVideoGenDecl", "size_multiple", 120, 8 },
|
||||
{ "RadVideoGenDecl", "min_side", 128, 8 },
|
||||
{ "RadVideoGenDecl", "max_area", 136, 8 },
|
||||
{ "RadVideoGenDecl", "max_aspect", 144, 8 },
|
||||
{ "RadVideoGenDecl", "default_width", 152, 8 },
|
||||
{ "RadVideoGenDecl", "default_height", 160, 8 },
|
||||
{ "RadVideoGenDecl", "default_chunks", 168, 8 },
|
||||
{ "RadVideoGenDecl", "sample_rate", 176, 8 },
|
||||
{ "RadVideoGenDecl", "audio_rate", 184, 8 },
|
||||
{ "RadVideoGenDecl", "audio_channels", 192, 8 },
|
||||
{ "RadVideoGenDecl", "audio_latent_channels", 200, 8 },
|
||||
{ "RadVideoGenDecl", "default_steps", 208, 8 },
|
||||
{ "RadVideoGenDecl", "max_steps", 216, 8 },
|
||||
{ "RadVideoGenDecl", "shift_video", 224, 8 },
|
||||
{ "RadVideoGenDecl", "shift_audio", 232, 8 },
|
||||
{ "RadVideoGenDecl", "max_lanes", 240, 8 },
|
||||
{ "RadVideoGenDecl", "frames_out", 248, 4 },
|
||||
{ "RadVideoGenDecl", "audio_out", 252, 4 },
|
||||
{ "RadVideoGenDecl", "n_rungs", 256, 4 },
|
||||
{ "RadVideoGenDecl", "rungs", 264, 8 },
|
||||
{ "RadVideoGeom", "", 0, 24 },
|
||||
{ "RadVideoGeom", "n_text", 0, 4 },
|
||||
{ "RadVideoGeom", "frames", 4, 4 },
|
||||
{ "RadVideoGeom", "lat_frames", 8, 4 },
|
||||
{ "RadVideoGeom", "lat_h", 12, 4 },
|
||||
{ "RadVideoGeom", "lat_w", 16, 4 },
|
||||
{ "RadVideoGeom", "n_audio", 20, 4 },
|
||||
{ "RadVocabHeader", "", 0, 128 },
|
||||
{ "RadVocabHeader", "kind", 0, 4 },
|
||||
{ "RadVocabHeader", "n_tokens", 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 18 and RAD_FORMAT_VER 2. Under
|
||||
* the layout agrees with the table below, taken at RAD_ABI_VERSION 21 and RAD_FORMAT_VER 2. Under
|
||||
* those versions a listed field may not move or change size, an ABI struct may only grow by fields
|
||||
* past its old end, and an on-disk struct may not change at all. The table is a snapshot of the
|
||||
* headers: nothing else states the layout. When it disagrees the test prints the live table.
|
||||
@@ -57,8 +57,8 @@ std::vector<Row> cpp_rows() {
|
||||
};
|
||||
}
|
||||
|
||||
/* The layout at RAD_ABI_VERSION 18 / RAD_FORMAT_VER 2 (see the file header). */
|
||||
constexpr uint32_t kTableAbi = 18, kTableFormat = 2;
|
||||
/* The layout at RAD_ABI_VERSION 21 / RAD_FORMAT_VER 2 (see the file header). */
|
||||
constexpr uint32_t kTableAbi = 21, kTableFormat = 2;
|
||||
const AbiRow kTable[] = {
|
||||
#include "abi_layout_table.h"
|
||||
};
|
||||
|
||||
@@ -5696,6 +5696,88 @@ TEST(qwen35_fp8_steps_lint_clean_with_its_mtp_head) {
|
||||
lint_qwen35_fp8_family(qwen35_fp8::declare, qwen35_fp8::step, mk.meta(), 3, false, 0);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* Every trunk and MTP linear of a qwen35 container in the 4-bit form an int4 W4A16 release
|
||||
* imports to: u4 codes, an f16 scale and a u4 zero point per 128 of K. */
|
||||
std::vector<std::pair<std::string, RadEncoding>> int4_linears() {
|
||||
RadEncoding w4 = rad_enc_affine(RAD_U4, RAD_F16, 1, 128);
|
||||
rad_enc_add_plane(&w4, "zero", RAD_U4, 1, 128);
|
||||
std::vector<std::pair<std::string, RadEncoding>> e;
|
||||
for (const char* k : { "attn_qg.weight", "attn_k.weight", "attn_v.weight",
|
||||
"attn_output.weight", "ssm_inz.weight", "ssm_out.weight",
|
||||
"ffn_gate_up.weight", "ffn_down.weight" })
|
||||
e.emplace_back(k, w4);
|
||||
return e;
|
||||
}
|
||||
|
||||
int qwen35_fp8_int4_declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* c) {
|
||||
b->encs = int4_linears();
|
||||
return qwen35_fp8::declare(b, m, c);
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* An int4 container's linears are read by the 4-bit GEMMs over their input's bf16 plane: at or
|
||||
* below 64 rows a `cast` to f16 and w4a16_asym, above that quant_act_i8g's int8 codes and
|
||||
* w4a8i8_asym, both over the codes and the joined (scale, zero) view. No linear keeps an fp8a8
|
||||
* GEMM, and the gated fold (an fp8a8 tile) is not declared over a 4-bit gate_up. */
|
||||
TEST(qwen35_fp8_reads_an_int4_container_with_the_4bit_gemms) {
|
||||
MetaKV mk = q35fp8_meta();
|
||||
RadBuilder b;
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
REQUIRE_EQ(qwen35_fp8_int4_declare(&b, mk.meta(), &ctx), RAD_OK);
|
||||
int f16 = 0, i8 = 0, other = 0;
|
||||
for (const auto& o : b.ops) {
|
||||
if (o.op != "gemm_nt_q") continue;
|
||||
const std::string dt = pstr(&o, "dtype");
|
||||
const RecParam* m = param(&o, "M");
|
||||
REQUIRE(m != nullptr);
|
||||
if (dt == "w4a16_asym") {
|
||||
++f16;
|
||||
CHECK_EQ(m->ival, 1LL);
|
||||
CHECK_EQ(m->ihi, 64LL);
|
||||
} else if (dt == "w4a8i8_asym") {
|
||||
++i8;
|
||||
CHECK_EQ(m->ival, 65LL);
|
||||
CHECK_EQ(m->ihi, 256LL);
|
||||
} else {
|
||||
++other;
|
||||
}
|
||||
CHECK_EQ(pint(&o, "group"), 128);
|
||||
}
|
||||
/* q|gate, k, v, o for 2 attention layers; qkv|z and out for 6 delta-net layers; gate_up and
|
||||
* down for 8 feed-forwards: 36 linears, each with both GEMMs, a cast and a quantiser. */
|
||||
CHECK_EQ(f16, 36);
|
||||
CHECK_EQ(i8, 36);
|
||||
CHECK_EQ(other, 0);
|
||||
int casts = 0;
|
||||
for (const auto& o : b.ops)
|
||||
if (o.op == "cast" && pstr(&o, "to") == "f16") {
|
||||
++casts;
|
||||
CHECK_EQ(pstr(&o, "from"), std::string("bf16"));
|
||||
CHECK_EQ(param(&o, "M")->ihi, 64LL);
|
||||
}
|
||||
CHECK_EQ(casts, 36);
|
||||
CHECK_EQ(count_op(b, "quant_act_i8g"), 36);
|
||||
CHECK_EQ(count_op(b, "gemm_nt_q_gated"), 0);
|
||||
int joined = 0;
|
||||
for (const RecWeight& w : b.weights)
|
||||
if (w.d.planes && std::string(w.d.planes) == "scale,zero") {
|
||||
++joined;
|
||||
CHECK_EQ(w.d.dtype, (uint32_t)RAD_F16);
|
||||
}
|
||||
CHECK_EQ(joined, 36);
|
||||
}
|
||||
|
||||
/* Every engine step an int4 container runs lints clean at one and two ranks, the MTP head's
|
||||
* history pass and rounds included: the 4-bit linears' row parts and shards are cut like the
|
||||
* block-fp8 ones. */
|
||||
TEST(qwen35_fp8_int4_steps_lint_clean_with_its_mtp_head) {
|
||||
MetaKV mk = q35fp8_meta();
|
||||
lint_qwen35_fp8_family(qwen35_fp8_int4_declare, qwen35_fp8::step, mk.meta(), 3, false, 0);
|
||||
}
|
||||
|
||||
/* The head is a serial drafter at the deployment's depth, declared after the trunk's lm_head:
|
||||
* the planner reads declaration order as liveness, and the head's passes run after the trunk. */
|
||||
TEST(qwen35_fp8_declares_its_mtp_head_after_the_trunk) {
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
/* audio_gen_test.cpp -- the audio generator's pass driver (core/gen/audio_driver.h) for a vocoder
|
||||
* that plays frames as they are made (RadAudioGenDecl::voc_chunk), against sched_fakes.h's KV
|
||||
* manager and device layer. The plugin's side of each pass is played by the test: it writes the
|
||||
* FRAME pass's status and the VOCODE pass's samples where the driver reads them back.
|
||||
*/
|
||||
#include "sched_fakes.h"
|
||||
|
||||
using namespace sched_fake;
|
||||
|
||||
#include "gen/audio_driver.h"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace rad;
|
||||
|
||||
namespace {
|
||||
|
||||
/* Two frames a chunk, three frames of context, at most five frames, every frame kept. */
|
||||
RadAudioGenDecl decl_chunked() {
|
||||
RadAudioGenDecl d{};
|
||||
d.max_prompt = 16;
|
||||
d.max_frames = 5;
|
||||
d.frame_rate_num = 25;
|
||||
d.frame_rate_den = 2;
|
||||
d.lat_num = 1;
|
||||
d.lat_den = 1;
|
||||
d.samples_per_latent = 4;
|
||||
d.sample_rate = 50;
|
||||
d.channels = 1;
|
||||
d.default_cfg = 1.0;
|
||||
d.max_lanes = 2;
|
||||
d.status = 1;
|
||||
d.audio_out = 2;
|
||||
d.prompt_whole = 1;
|
||||
d.first_frame = 0;
|
||||
d.voc_chunk = 2;
|
||||
d.voc_context = 3;
|
||||
return d;
|
||||
}
|
||||
|
||||
struct AudioFixture {
|
||||
Program prog;
|
||||
FakeKV kv;
|
||||
gen::AudioDriver drv;
|
||||
void build() {
|
||||
prog.audio_gen = decl_chunked();
|
||||
prog.agen_str.name = "test";
|
||||
prog.agen_str.neg_tmpl = "<n>{input}";
|
||||
prog.ctx.max_tok = 64;
|
||||
prog.ctx.max_seqs = 8;
|
||||
prog.kv_groups.emplace_back();
|
||||
KVGroupInfo g;
|
||||
g.name = "lm";
|
||||
g.decl.kind = RAD_KV_FULL;
|
||||
g.block_size = 16;
|
||||
prog.kv_groups.push_back(g);
|
||||
kv.setup(prog.kv_groups, 1 << 20, 256, 4);
|
||||
}
|
||||
int start() { return drv.init(prog, &kv, { gen::AudioDriver::RankIO{} }); }
|
||||
std::unique_ptr<gen::AudioRequest> req(float cfg, int64_t frames = 5) {
|
||||
auto r = std::make_unique<gen::AudioRequest>();
|
||||
r->tokens = { 1, 2, 3, 4 };
|
||||
r->neg_tokens = { 9, 9 };
|
||||
r->max_frames = frames;
|
||||
r->cfg = cfg;
|
||||
r->seed = 7;
|
||||
r->ticket = std::make_shared<gen::AudioTicket>();
|
||||
return r;
|
||||
}
|
||||
/* The plugin's answer to the pass in flight: each lane's FRAME status, or a VOCODE pass's
|
||||
* samples numbered from `sample0`. */
|
||||
void answer(const RadBatch* b, int32_t status, float sample0) {
|
||||
for (const gen::IPassDriver::Readback& rb : drv.readbacks()) {
|
||||
if (b->gen == RAD_GEN_PASS_FRAME) {
|
||||
int32_t* st = static_cast<int32_t*>(rb.host);
|
||||
for (int64_t i = 0; i < rb.bytes / 4; ++i) st[i] = status;
|
||||
} else {
|
||||
float* x = static_cast<float*>(rb.host);
|
||||
for (int64_t i = 0; i < rb.bytes / 4; ++i) x[i] = sample0 + (float)i;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* A request's passes: its whole prompt (both branches, of their own lengths), then frames, a chunk
|
||||
* vocoded as soon as two are kept (before the next frame), and the last frame vocoded on its own
|
||||
* once the length is reached. Each chunk reads up to three earlier frames again: it names its
|
||||
* first frame, the frames it reads and how many lead it, and the frames' positions in the piece
|
||||
* are the pass's positions. The samples come back in order and end the ticket. */
|
||||
TEST(a_chunked_request_vocodes_each_chunk_as_its_frames_are_made) {
|
||||
AudioFixture f;
|
||||
f.build();
|
||||
CHECK_OK(f.start());
|
||||
std::string why;
|
||||
auto r = f.req(3.0f);
|
||||
auto t = r->ticket;
|
||||
CHECK_OK(f.drv.submit(std::move(r), &why));
|
||||
std::string kinds;
|
||||
std::vector<std::vector<int32_t>> voc; /* frame0, frames, left per VOCODE */
|
||||
float next_sample = 0.0f;
|
||||
/* Until nothing is left to run: the ticket's samples are read after the loop. */
|
||||
for (int i = 0; i < 20; ++i) {
|
||||
const RadBatch* b = f.drv.next(i);
|
||||
if (!b) break;
|
||||
const RadAudioGenBatch* A = b->agen_b;
|
||||
REQUIRE(A != nullptr);
|
||||
switch (b->gen) {
|
||||
case RAD_GEN_PASS_PROMPT:
|
||||
kinds += 'P';
|
||||
/* Both branches whole: four conditional rows, two unconditional. */
|
||||
CHECK_EQ(b->n_tok, (int64_t)6);
|
||||
CHECK_EQ(b->n_seq, (int64_t)2);
|
||||
break;
|
||||
case RAD_GEN_PASS_FRAME:
|
||||
kinds += 'F';
|
||||
CHECK_EQ(b->n_tok, (int64_t)2);
|
||||
break;
|
||||
case RAD_GEN_PASS_VOCODE:
|
||||
kinds += 'V';
|
||||
voc.push_back({ (int32_t)A->voc_frame0, A->voc_latents, A->voc_left });
|
||||
CHECK_EQ(b->n_tok, (int64_t)A->voc_latents);
|
||||
break;
|
||||
default:
|
||||
kinds += '?';
|
||||
}
|
||||
f.answer(b, 0, next_sample);
|
||||
if (b->gen == RAD_GEN_PASS_VOCODE)
|
||||
next_sample += (float)((A->voc_latents - A->voc_left) * 4);
|
||||
CHECK_OK(f.drv.done());
|
||||
}
|
||||
CHECK_EQ(kinds, std::string("PFFVFFVFV"));
|
||||
REQUIRE_EQ(voc.size(), (size_t)3);
|
||||
CHECK(voc[0] == std::vector<int32_t>({ 0, 2, 0 })); /* frames 0, 1 */
|
||||
CHECK(voc[1] == std::vector<int32_t>({ 0, 4, 2 })); /* 0, 1 again, then 2, 3 */
|
||||
CHECK(voc[2] == std::vector<int32_t>({ 1, 4, 3 })); /* 1..3 again, then 4 */
|
||||
std::vector<float> all;
|
||||
gen::AudioChunk c;
|
||||
bool to = false;
|
||||
int32_t k = 0;
|
||||
while (t->next(&c, 0, &to)) {
|
||||
CHECK_EQ(c.window, k++);
|
||||
all.insert(all.end(), c.samples.begin(), c.samples.end());
|
||||
}
|
||||
REQUIRE_EQ(all.size(), (size_t)20); /* five frames of four samples */
|
||||
for (size_t i = 0; i < all.size(); ++i) CHECK_EQ(all[i], (float)i);
|
||||
CHECK_EQ(t->status(), (int)RAD_OK);
|
||||
CHECK_EQ(t->frames, (int64_t)5);
|
||||
CHECK_EQ(t->windows, (int64_t)3);
|
||||
}
|
||||
|
||||
/* The model ending the piece right after a chunk was played leaves nothing owed: the request ends
|
||||
* at that FRAME pass, with no empty vocode. Ending it before the first frame fails the request. */
|
||||
TEST(a_chunked_request_ends_with_the_model_and_fails_before_its_first_frame) {
|
||||
AudioFixture f;
|
||||
f.build();
|
||||
CHECK_OK(f.start());
|
||||
std::string why;
|
||||
auto r = f.req(1.0f);
|
||||
auto t = r->ticket;
|
||||
CHECK_OK(f.drv.submit(std::move(r), &why));
|
||||
std::string kinds;
|
||||
for (int i = 0; i < 20; ++i) {
|
||||
const RadBatch* b = f.drv.next(i);
|
||||
if (!b) break;
|
||||
kinds += b->gen == RAD_GEN_PASS_PROMPT ? 'P' : b->gen == RAD_GEN_PASS_FRAME ? 'F' : 'V';
|
||||
/* The third frame pass reports the model's end. */
|
||||
f.answer(b, kinds == "PFFVF" ? -1 : 0, 0.0f);
|
||||
CHECK_OK(f.drv.done());
|
||||
}
|
||||
CHECK_EQ(kinds, std::string("PFFVF"));
|
||||
CHECK(t->finished() || t->status() == RAD_OK);
|
||||
CHECK_EQ(t->status(), (int)RAD_OK);
|
||||
CHECK(t->model_ended);
|
||||
CHECK_EQ(t->frames, (int64_t)2);
|
||||
|
||||
auto e = f.req(1.0f);
|
||||
auto te = e->ticket;
|
||||
CHECK_OK(f.drv.submit(std::move(e), &why));
|
||||
for (int i = 0; i < 4 && !te->finished(); ++i) {
|
||||
const RadBatch* b = f.drv.next(100 + i);
|
||||
REQUIRE(b != nullptr);
|
||||
f.answer(b, b->gen == RAD_GEN_PASS_FRAME ? -1 : 0, 0.0f);
|
||||
CHECK_OK(f.drv.done());
|
||||
}
|
||||
CHECK(te->finished());
|
||||
CHECK_EQ(te->status(), (int)RAD_E_INVAL);
|
||||
CHECK(has(te->why(), "before its first frame"));
|
||||
}
|
||||
|
||||
/* Guidance 1 runs the conditional prompt in both branches; other guidance the request's own
|
||||
* unconditional prompt, at its own length and positions. */
|
||||
TEST(the_unconditional_branch_is_the_conditional_prompt_at_guidance_one) {
|
||||
for (float cfg : { 1.0f, 2.0f }) {
|
||||
AudioFixture f;
|
||||
f.build();
|
||||
CHECK_OK(f.start());
|
||||
std::string why;
|
||||
CHECK_OK(f.drv.submit(f.req(cfg), &why));
|
||||
const RadBatch* b = f.drv.next(0);
|
||||
REQUIRE(b != nullptr && b->gen == RAD_GEN_PASS_PROMPT);
|
||||
CHECK_EQ(b->n_tok, (int64_t)(cfg == 1.0f ? 8 : 6));
|
||||
f.answer(b, 0, 0.0f);
|
||||
CHECK_OK(f.drv.done());
|
||||
b = f.drv.next(1);
|
||||
REQUIRE(b != nullptr && b->gen == RAD_GEN_PASS_FRAME);
|
||||
}
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
+570
-4
@@ -757,8 +757,9 @@ TEST(a_ct_int4_weight_is_imported_as_its_signed_codes_and_scales) {
|
||||
CHECK(!w.imported);
|
||||
}
|
||||
|
||||
/* What is not read is refused, not misread: an asymmetric config, a zero point beside a weight
|
||||
* the config calls symmetric, and a scale plane that is not one per group. */
|
||||
/* What is not read is refused, not misread: a weight with no zero point under an asymmetric
|
||||
* config, a zero point beside a weight the config calls symmetric, and a scale plane that is not
|
||||
* one per group. */
|
||||
TEST(a_ct_int4_checkpoint_this_does_not_read_is_refused) {
|
||||
const Ct c = make_ct(4, 64, 32, 3);
|
||||
{
|
||||
@@ -767,8 +768,13 @@ TEST(a_ct_int4_checkpoint_this_does_not_read_is_refused) {
|
||||
const std::string dir = write_checkpoint(ts, ct_config("false", 32).c_str());
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
CHECK(ck.imports() == Checkpoint::Import::None);
|
||||
CHECK(ck.import_refusal().find("symmetric") != std::string::npos);
|
||||
CHECK(ck.imports() == Checkpoint::Import::CtInt4);
|
||||
Program prog;
|
||||
prog.name_map.push_back(map("p", RAD_MAP_COPY, { "p.weight" }));
|
||||
CkptWeight w;
|
||||
std::string why;
|
||||
CHECK(ckpt_resolve(ck, prog, "p", false, &w, &why) != RAD_OK);
|
||||
CHECK(why.find("p.weight_zero_point") != std::string::npos);
|
||||
}
|
||||
{
|
||||
std::vector<T> ts;
|
||||
@@ -838,6 +844,305 @@ T pack_awq(const std::string& name, const std::vector<int>& v, int64_t rows, int
|
||||
|
||||
} /* namespace */
|
||||
|
||||
namespace {
|
||||
|
||||
/* An asymmetric CT-INT4 weight as compressed-tensors' pack-quantized writes it (W4A16_ASYM, e.g.
|
||||
* llm-compressor's AWQ): the signed code q[n][k] stored as q + 8 in X.weight_packed as above, the
|
||||
* signed zero point zp[n][g] stored as zp + 8 in nibble n % 8 of int32 word [n / 8, g] of
|
||||
* X.weight_zero_point (packed along N, the last word's spare nibbles zero), and a bf16 scale per
|
||||
* group. compressed-tensors dequantises (q - zp) * scale. */
|
||||
struct CtAsym {
|
||||
Ct c; /* codes and scales */
|
||||
std::vector<std::vector<int>> zp; /* [N][G] signed, -8..7 */
|
||||
};
|
||||
|
||||
CtAsym make_ct_asym(int64_t N, int64_t K, int64_t group, int seed) {
|
||||
CtAsym a;
|
||||
a.c = make_ct(N, K, group, seed);
|
||||
a.zp.assign((size_t)N, std::vector<int>((size_t)(K / group)));
|
||||
for (int64_t n = 0; n < N; ++n)
|
||||
for (int64_t g = 0; g < K / group; ++g)
|
||||
a.zp[(size_t)n][(size_t)g] = (int)((n * 5 + g * 3 + seed) % 16) - 8;
|
||||
return a;
|
||||
}
|
||||
|
||||
void add_ct_asym(std::vector<T>* ts, const std::string& base, const CtAsym& a) {
|
||||
add_ct(ts, base, a.c);
|
||||
const int64_t N = a.c.N, G = a.c.K / a.c.group;
|
||||
T z{ base + ".weight_zero_point", "I32", { (N + 7) / 8, G }, {} };
|
||||
z.bytes.assign((size_t)((N + 7) / 8 * G * 4), 0);
|
||||
for (int64_t n = 0; n < N; ++n)
|
||||
for (int64_t g = 0; g < G; ++g) {
|
||||
uint32_t w;
|
||||
std::memcpy(&w, z.bytes.data() + ((n / 8) * G + g) * 4, 4);
|
||||
w |= (uint32_t)(a.zp[(size_t)n][(size_t)g] + 8) << (4 * (n % 8));
|
||||
std::memcpy(z.bytes.data() + ((n / 8) * G + g) * 4, &w, 4);
|
||||
}
|
||||
ts->push_back(z);
|
||||
}
|
||||
|
||||
std::string ct_config_ao(const char* symmetric, const char* actorder) {
|
||||
std::string s = ct_config(symmetric, 32);
|
||||
const std::string from = "\"actorder\":null";
|
||||
s.replace(s.find(from), from.size(), std::string("\"actorder\":") + actorder);
|
||||
return s;
|
||||
}
|
||||
|
||||
/* `w` decoded from the planes ckpt_plane_rows writes, through the core's decoder. */
|
||||
std::vector<float> decode_planes(const CkptWeight& w) {
|
||||
std::vector<std::vector<uint8_t>> pl((size_t)w.enc.n_planes);
|
||||
std::vector<const void*> data;
|
||||
std::string why;
|
||||
for (int k = 0; k < w.enc.n_planes; ++k) {
|
||||
int64_t pr = 0, pc = 0;
|
||||
rad_enc_plane_dims(&w.enc.plane[k], w.rows, w.cols, &pr, &pc);
|
||||
pl[(size_t)k].assign((size_t)(pr * rad_enc_row_bytes(w.enc.plane[k].dtype, pc)) + 8, 0);
|
||||
if (ckpt_plane_rows(w, k, 0, pr, pl[(size_t)k].data(), &why) != RAD_OK) return {};
|
||||
data.push_back(pl[(size_t)k].data());
|
||||
}
|
||||
EncodedView v;
|
||||
enc_view(w.enc, w.rows, w.cols, data.data(), &v);
|
||||
std::vector<float> out((size_t)(w.rows * w.cols));
|
||||
if (enc_decode_rows(v, 0, w.rows, out.data(), &why) != RAD_OK) return {};
|
||||
return out;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* An asymmetric CT-INT4 weight imports as `u4*bf16[1x32]-u4[1x32]`: the stored nibbles are the
|
||||
* codes and the stored zero points the zero plane, so (u - z) * s is compressed-tensors'
|
||||
* (q - zp) * scale bit for bit. Gate (twelve rows: the zero points' last word half full) and up
|
||||
* join along rows. */
|
||||
TEST(an_asymmetric_ct_int4_weight_is_its_codes_zero_points_and_scales) {
|
||||
const CtAsym gate = make_ct_asym(12, 64, 32, 1), up = make_ct_asym(8, 64, 32, 2);
|
||||
std::vector<T> ts;
|
||||
add_ct_asym(&ts, "g", gate);
|
||||
add_ct_asym(&ts, "u", up);
|
||||
const std::string dir = write_checkpoint(ts, ct_config("false", 32).c_str());
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
CHECK(ck.imports() == Checkpoint::Import::CtInt4);
|
||||
Program prog;
|
||||
prog.name_map.push_back(map("gu", RAD_MAP_CONCAT, { "g.weight", "u.weight" }));
|
||||
CkptWeight w;
|
||||
std::string why;
|
||||
REQUIRE_EQ(ckpt_resolve(ck, prog, "gu", false, &w, &why), RAD_OK);
|
||||
REQUIRE(w.imported);
|
||||
REQUIRE_EQ(w.enc.n_planes, 3);
|
||||
CHECK_EQ(w.enc.plane[0].dtype, (uint32_t)RAD_U4);
|
||||
CHECK_EQ(w.enc.plane[1].dtype, (uint32_t)RAD_BF16);
|
||||
CHECK_EQ(std::string(w.enc.plane[2].role), std::string("zero"));
|
||||
CHECK_EQ(w.enc.plane[2].dtype, (uint32_t)RAD_U4);
|
||||
CHECK_EQ(w.enc.plane[2].block[1], (int64_t)32);
|
||||
CHECK(rad_enc_valid(&w.enc));
|
||||
const auto pl = read_planes(w);
|
||||
REQUIRE_EQ(pl.size(), (size_t)3);
|
||||
std::vector<float> f((size_t)(20 * 64));
|
||||
REQUIRE_EQ(ckpt_rows_f32(w, 0, 20, f.data(), &why), RAD_OK);
|
||||
const std::vector<float> dec = decode_planes(w);
|
||||
REQUIRE_EQ(dec.size(), f.size());
|
||||
int bad_code = 0, bad_zero = 0, bad_f = 0, bad_dec = 0, negative = 0;
|
||||
for (int64_t r = 0; r < 20; ++r) {
|
||||
const CtAsym& a = r < 12 ? gate : up;
|
||||
const int64_t n = r < 12 ? r : r - 12;
|
||||
for (int64_t k = 0; k < 64; ++k) {
|
||||
const int q = a.c.q[(size_t)n][(size_t)k], z = a.zp[(size_t)n][(size_t)(k / 32)];
|
||||
const float want = (float)(q - z) * a.c.scale[(size_t)(n * 2 + k / 32)];
|
||||
negative += want < 0;
|
||||
if ((int)rad_load_f32(pl[0].data() + r * 32, RAD_U4, k) != q + 8) ++bad_code;
|
||||
if (f[(size_t)(r * 64 + k)] != want) ++bad_f;
|
||||
if (dec[(size_t)(r * 64 + k)] != want) ++bad_dec;
|
||||
}
|
||||
for (int64_t g = 0; g < 2; ++g)
|
||||
if ((int)rad_load_f32(pl[2].data() + r, RAD_U4, g) != a.zp[(size_t)n][(size_t)g] + 8)
|
||||
++bad_zero;
|
||||
}
|
||||
CHECK(negative > 0);
|
||||
CHECK_EQ(bad_code, 0);
|
||||
CHECK_EQ(bad_zero, 0);
|
||||
CHECK_EQ(bad_f, 0);
|
||||
CHECK_EQ(bad_dec, 0);
|
||||
}
|
||||
|
||||
/* Act-order `static` (alias `weight`) quantises in activation order but keeps each group's
|
||||
* columns together, so it reads as no act-order, and an in-order weight_g_idx is accepted;
|
||||
* `group` (alias `dynamic`) reorders the groups and is refused by name, as is a g_idx that moves
|
||||
* a column out of its group. */
|
||||
TEST(ct_int4_act_order_static_reads_in_order_and_group_is_refused) {
|
||||
const Ct c = make_ct(4, 64, 32, 4);
|
||||
for (const char* ao : { "\"static\"", "\"weight\"" }) {
|
||||
std::vector<T> ts;
|
||||
add_ct(&ts, "p", c);
|
||||
const std::string dir = write_checkpoint(ts, ct_config_ao("true", ao));
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
CHECK(ck.imports() == Checkpoint::Import::CtInt4);
|
||||
}
|
||||
for (const char* ao : { "\"group\"", "\"dynamic\"" }) {
|
||||
std::vector<T> ts;
|
||||
add_ct(&ts, "p", c);
|
||||
const std::string dir = write_checkpoint(ts, ct_config_ao("true", ao));
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
CHECK(ck.imports() == Checkpoint::Import::None);
|
||||
CHECK(ck.import_refusal().find("act-order") != std::string::npos);
|
||||
CHECK(ck.import_refusal().find(std::string(ao).substr(1, std::strlen(ao) - 2)) !=
|
||||
std::string::npos);
|
||||
}
|
||||
for (int moved : { 0, 1 }) {
|
||||
std::vector<T> ts;
|
||||
add_ct(&ts, "p", c);
|
||||
T gi{ "p.weight_g_idx", "I32", { 64 }, std::vector<uint8_t>(256, 0) };
|
||||
for (int k = 0; k < 64; ++k) ((int32_t*)gi.bytes.data())[k] = k / 32;
|
||||
if (moved) ((int32_t*)gi.bytes.data())[3] = 1;
|
||||
ts.push_back(gi);
|
||||
const std::string dir = write_checkpoint(ts, ct_config_ao("true", "\"static\""));
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
Program prog;
|
||||
prog.name_map.push_back(map("p", RAD_MAP_COPY, { "p.weight" }));
|
||||
CkptWeight w;
|
||||
std::string why;
|
||||
const int rc = ckpt_resolve(ck, prog, "p", false, &w, &why);
|
||||
if (moved) {
|
||||
CHECK(rc != RAD_OK);
|
||||
CHECK(why.find("act-order") != std::string::npos);
|
||||
} else {
|
||||
CHECK_EQ(rc, RAD_OK);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* An import rule writes a symmetric grid unsigned under a zero of 8 and its bf16 scales as f16:
|
||||
* every plane decodes, through the core's decoder, to the shipped value bit for bit, and with
|
||||
* every scale in f16's range nothing is counted as rounded. An asymmetric grid keeps its zero
|
||||
* points and changes only the scale's dtype. */
|
||||
TEST(an_import_rule_re_expresses_an_int4_grid_exactly) {
|
||||
const Ct sym = make_ct(6, 64, 32, 5);
|
||||
const CtAsym asym = make_ct_asym(9, 64, 32, 6);
|
||||
ImportForm f;
|
||||
f.codes = RAD_U4;
|
||||
f.zero = RAD_U4;
|
||||
f.scale = RAD_F16;
|
||||
for (int is_asym : { 0, 1 }) {
|
||||
std::vector<T> ts;
|
||||
if (is_asym) add_ct_asym(&ts, "p", asym);
|
||||
else add_ct(&ts, "p", sym);
|
||||
const std::string dir = write_checkpoint(ts, ct_config(is_asym ? "false" : "true", 32));
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
Program prog;
|
||||
prog.name_map.push_back(map("p", RAD_MAP_COPY, { "p.weight" }));
|
||||
CkptWeight w;
|
||||
std::string why;
|
||||
REQUIRE_EQ(ckpt_resolve(ck, prog, "p", false, &w, &why), RAD_OK);
|
||||
std::vector<float> want((size_t)(w.rows * w.cols));
|
||||
REQUIRE_EQ(ckpt_rows_f32(w, 0, w.rows, want.data(), &why), RAD_OK);
|
||||
REQUIRE_EQ(ckpt_import_form(&w, f, &why), RAD_OK);
|
||||
char en[96];
|
||||
rad_enc_format(&w.enc, en, sizeof en);
|
||||
CHECK_EQ(std::string(en), std::string("u4*f16[1x32]-u4[1x32]"));
|
||||
CHECK(w.imported && !w.trivial);
|
||||
CHECK_EQ(w.rounded, (int64_t)0);
|
||||
const std::vector<float> dec = decode_planes(w);
|
||||
REQUIRE_EQ(dec.size(), want.size());
|
||||
int bad = 0;
|
||||
for (size_t i = 0; i < dec.size(); ++i) bad += dec[i] != want[i];
|
||||
CHECK_EQ(bad, 0);
|
||||
/* a symmetric grid's zero plane is 8 throughout */
|
||||
if (!is_asym) {
|
||||
const auto pl = read_planes(w);
|
||||
REQUIRE_EQ(pl.size(), (size_t)3);
|
||||
for (int64_t r = 0; r < w.rows; ++r)
|
||||
for (int64_t g = 0; g < 2; ++g)
|
||||
CHECK_EQ((int)rad_load_f32(pl[2].data() + r, RAD_U4, g), 8);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* AutoRound's GPTQ export with an import rule: the codes unsigned under a zero of 8 and the
|
||||
* scales kept in their shipped f16, where the import alone rounds them to bf16 for the expert
|
||||
* GEMM. The decode is then the shipped value, code times f16 scale, bit for bit. */
|
||||
TEST(an_import_rule_keeps_gptq_scales_in_their_shipped_f16) {
|
||||
const Gptq g = make_gptq(8, 256, 128, 4, 7);
|
||||
std::vector<T> ts;
|
||||
add_gptq(&ts, "x", g);
|
||||
const std::string dir = write_checkpoint(ts, kAutoRound);
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
Program prog;
|
||||
prog.name_map.push_back(map("x", RAD_MAP_COPY, { "x.weight" }));
|
||||
CkptWeight w;
|
||||
std::string why;
|
||||
REQUIRE_EQ(ckpt_resolve(ck, prog, "x", false, &w, &why), RAD_OK);
|
||||
std::vector<float> want((size_t)(8 * 256));
|
||||
REQUIRE_EQ(ckpt_rows_f32(w, 0, 8, want.data(), &why), RAD_OK);
|
||||
const std::vector<float> as_bf16 = decode_planes(w);
|
||||
int differ = 0;
|
||||
for (size_t i = 0; i < want.size(); ++i) differ += as_bf16[i] != want[i];
|
||||
CHECK(differ > 0); /* the default import rounds the scales */
|
||||
ImportForm f;
|
||||
f.codes = RAD_U4;
|
||||
f.zero = RAD_U4;
|
||||
f.scale = RAD_F16;
|
||||
REQUIRE_EQ(ckpt_import_form(&w, f, &why), RAD_OK);
|
||||
char en[96];
|
||||
rad_enc_format(&w.enc, en, sizeof en);
|
||||
CHECK_EQ(std::string(en), std::string("u4*f16[1x128]-u4[1x128]"));
|
||||
CHECK_EQ(w.rounded, (int64_t)0);
|
||||
const std::vector<float> dec = decode_planes(w);
|
||||
REQUIRE_EQ(dec.size(), want.size());
|
||||
int bad = 0;
|
||||
for (size_t i = 0; i < dec.size(); ++i) bad += dec[i] != want[i];
|
||||
CHECK_EQ(bad, 0);
|
||||
}
|
||||
|
||||
/* A shipped scale the new dtype cannot hold (a bf16 scale below f16's normal range) is rounded,
|
||||
* counted, and its largest relative change reported; what the rule cannot express is refused by
|
||||
* name, and a plain weight is declined. */
|
||||
TEST(an_import_rule_counts_a_rounded_scale_and_refuses_what_it_cannot_express) {
|
||||
Ct c = make_ct(2, 64, 32, 8);
|
||||
c.scale[1] = rad_load_f32(std::vector<uint16_t>{ rad_f32_to_bf16(1.7e-6f) }.data(), RAD_BF16, 0);
|
||||
std::vector<T> ts;
|
||||
add_ct(&ts, "p", c);
|
||||
ts.push_back(bf16("n.weight", { 64 }, 1.0f));
|
||||
const std::string dir = write_checkpoint(ts, ct_config("true", 32));
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
Program prog;
|
||||
prog.name_map.push_back(map("p", RAD_MAP_COPY, { "p.weight" }));
|
||||
prog.name_map.push_back(map("n", RAD_MAP_COPY, { "n.weight" }));
|
||||
CkptWeight w;
|
||||
std::string why;
|
||||
ImportForm f;
|
||||
f.codes = RAD_U4;
|
||||
f.zero = RAD_U4;
|
||||
f.scale = RAD_F16;
|
||||
REQUIRE_EQ(ckpt_resolve(ck, prog, "p", false, &w, &why), RAD_OK);
|
||||
REQUIRE_EQ(ckpt_import_form(&w, f, &why), RAD_OK);
|
||||
CHECK_EQ(w.rounded, (int64_t)1);
|
||||
CHECK(w.max_rel > 0.0 && w.max_rel < 0.05);
|
||||
|
||||
ImportForm bad = f;
|
||||
bad.codes = RAD_U8;
|
||||
REQUIRE_EQ(ckpt_resolve(ck, prog, "p", false, &w, &why), RAD_OK);
|
||||
CHECK_EQ(ckpt_import_form(&w, bad, &why), (int)RAD_E_INVAL);
|
||||
CHECK(why.find("codes=u8") != std::string::npos);
|
||||
ImportForm no_zero;
|
||||
no_zero.codes = RAD_U4;
|
||||
REQUIRE_EQ(ckpt_resolve(ck, prog, "p", false, &w, &why), RAD_OK);
|
||||
CHECK_EQ(ckpt_import_form(&w, no_zero, &why), (int)RAD_E_INVAL);
|
||||
CHECK(why.find("zero=") != std::string::npos);
|
||||
ImportForm blk;
|
||||
blk.block[0] = blk.block[1] = 128;
|
||||
REQUIRE_EQ(ckpt_resolve(ck, prog, "p", false, &w, &why), RAD_OK);
|
||||
CHECK_EQ(ckpt_import_form(&w, blk, &why), (int)RAD_E_INVAL);
|
||||
CHECK(why.find("block=") != std::string::npos);
|
||||
REQUIRE_EQ(ckpt_resolve(ck, prog, "n", false, &w, &why), RAD_OK);
|
||||
CHECK_EQ(ckpt_import_form(&w, f, &why), (int)RAD_E_UNSUPPORTED);
|
||||
}
|
||||
|
||||
|
||||
/* ParoQuant MXFP4 is Quark's codes and exponents in a rotated basis plus the rotations: each
|
||||
* projection's pairs (group-local int16), theta and channel scales. Gate and up are two parts of
|
||||
* the fused weight, so the tables carry whole-row pairs, widened angles, inverted channel scales
|
||||
@@ -1877,6 +2182,180 @@ TEST(an_nvfp4_weight_missing_its_global_is_refused) {
|
||||
CHECK(why.find("divisor") != std::string::npos);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* NVIDIA ModelOpt's MIXED_PRECISION layout (as in the NVFP4 releases of Qwen3.8-27B): NVFP4 for
|
||||
* `g`, FP8 per tensor for `a` and `b`, every scale and every static input scale a rank-0 f32. */
|
||||
const char* kModelOptConfig =
|
||||
"{\"model_type\":\"qwen3_5\",\"quantization_config\":{\"quant_method\":\"modelopt\","
|
||||
"\"quant_algo\":\"MIXED_PRECISION\",\"quantized_layers\":{"
|
||||
"\"g\":{\"quant_algo\":\"NVFP4\",\"group_size\":16},"
|
||||
"\"a\":{\"quant_algo\":\"FP8\"},\"b\":{\"quant_algo\":\"FP8\"}}}}";
|
||||
|
||||
T f32_scalar(const std::string& name, float v) {
|
||||
T t{ name, "F32", {}, std::vector<uint8_t>(4) };
|
||||
std::memcpy(t.bytes.data(), &v, 4);
|
||||
return t;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ModelOpt's NVFP4 against values fixed independently of the importer: codes packed with element
|
||||
* 2j in the low nibble, e4m3 block scales 2 and 0.5, and a weight_scale_2 of 0.25 that multiplies
|
||||
* (ModelOpt's e2m1 * (float(weight_scale) * weight_scale_2)); read as compressed-tensors' divisor
|
||||
* the value would be 16 times too large. The static input scale is not read. */
|
||||
TEST(a_modelopt_nvfp4_weight_decodes_with_its_second_scale_multiplying) {
|
||||
static const float kMag[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f };
|
||||
const int64_t N = 2, K = 32;
|
||||
const float blk[2][2] = { { 2.0f, 0.5f }, { 0.5f, 2.0f } };
|
||||
const float s2 = 0.25f;
|
||||
std::vector<uint8_t> nib((size_t)(N * K));
|
||||
std::vector<float> want((size_t)(N * K));
|
||||
for (int64_t n = 0; n < N; ++n)
|
||||
for (int64_t k = 0; k < K; ++k) {
|
||||
const uint8_t c = (uint8_t)((n * 7 + k * 5) % 16);
|
||||
nib[(size_t)(n * K + k)] = c;
|
||||
want[(size_t)(n * K + k)] = (c & 8 ? -1.0f : 1.0f) * kMag[c & 7] * (blk[n][k / 16] * s2);
|
||||
}
|
||||
std::vector<T> ts;
|
||||
T p{ "g.weight", "U8", { N, K / 2 }, {} };
|
||||
for (int64_t i = 0; i < N * K; i += 2)
|
||||
p.bytes.push_back((uint8_t)(nib[(size_t)i] | (nib[(size_t)i + 1] << 4)));
|
||||
ts.push_back(p);
|
||||
T s{ "g.weight_scale", "F8_E4M3", { N, K / 16 }, {} };
|
||||
for (int64_t n = 0; n < N; ++n)
|
||||
for (int64_t b = 0; b < 2; ++b) s.bytes.push_back(blk[n][b] == 2.0f ? 0x40 : 0x30);
|
||||
ts.push_back(s);
|
||||
ts.push_back(f32_scalar("g.weight_scale_2", s2));
|
||||
ts.push_back(f32_scalar("g.input_scale", 3.0f));
|
||||
const std::string dir = write_checkpoint(ts, kModelOptConfig);
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
CHECK(ck.imports() == Checkpoint::Import::ModelOpt);
|
||||
CHECK(ck.import_refusal().empty());
|
||||
CHECK(ck.meta().get("imported_quantization_config.quant_method") != nullptr);
|
||||
Program prog;
|
||||
prog.name_map.push_back(map("g", RAD_MAP_COPY, { "g.weight" }));
|
||||
CkptWeight w;
|
||||
std::string why;
|
||||
REQUIRE_EQ(ckpt_resolve(ck, prog, "g", false, &w, &why), RAD_OK);
|
||||
CHECK(w.imported && !w.trivial);
|
||||
char en[96];
|
||||
rad_enc_format(&w.enc, en, sizeof en);
|
||||
CHECK_EQ(std::string(en), std::string("fp4_e2m1*f32[1x16]"));
|
||||
std::vector<float> f((size_t)(N * K));
|
||||
REQUIRE_EQ(ckpt_rows_f32(w, 0, N, f.data(), &why), RAD_OK);
|
||||
int bad = 0;
|
||||
for (size_t i = 0; i < f.size(); ++i) bad += f[i] != want[i];
|
||||
CHECK_EQ(bad, 0);
|
||||
CHECK_EQ(f[1], 3.0f * (2.0f * 0.25f)); /* k 1: code 5 (3.0), byte 0's high nibble */
|
||||
}
|
||||
|
||||
/* ModelOpt's FP8 is E4M3 codes with one f32 scale per tensor. Each piece's scale is written once
|
||||
* a row, so two projections with their own scales join (`fp8_e4m3*f32[1x*]`, imported: the plane
|
||||
* is not the file's bytes), and the value is code * scale. An import rule makes it the served
|
||||
* block fp8, each block's scale its piece's rounded to bf16 (counted when that changes it); a
|
||||
* piece that ends inside a block is refused. */
|
||||
TEST(a_modelopt_fp8_weight_reads_its_per_tensor_scale_once_a_row) {
|
||||
std::vector<T> ts;
|
||||
ts.push_back(fp8("a.weight", { 128, 128 }));
|
||||
ts.push_back(f32_scalar("a.weight_scale", 0.5f));
|
||||
ts.push_back(f32_scalar("a.input_scale", 2.0f));
|
||||
ts.push_back(fp8("b.weight", { 128, 128 }));
|
||||
ts.push_back(f32_scalar("b.weight_scale", 0.3f));
|
||||
ts.push_back(fp8("c.weight", { 64, 128 }));
|
||||
ts.push_back(f32_scalar("c.weight_scale", 0.25f));
|
||||
const std::string dir = write_checkpoint(ts, kModelOptConfig);
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
Program prog;
|
||||
prog.name_map.push_back(map("ab", RAD_MAP_CONCAT, { "a.weight", "b.weight" }));
|
||||
prog.name_map.push_back(map("ca", RAD_MAP_CONCAT, { "c.weight", "a.weight" }));
|
||||
CkptWeight w;
|
||||
std::string why;
|
||||
REQUIRE_EQ(ckpt_resolve(ck, prog, "ab", false, &w, &why), RAD_OK);
|
||||
CHECK(w.imported && !w.trivial);
|
||||
char en[96];
|
||||
rad_enc_format(&w.enc, en, sizeof en);
|
||||
CHECK_EQ(std::string(en), std::string("fp8_e4m3*f32[1x*]"));
|
||||
const auto pl = read_planes(w);
|
||||
REQUIRE_EQ(pl.size(), (size_t)2);
|
||||
CHECK_EQ(rad_load_f32(pl[1].data(), RAD_F32, 0), 0.5f);
|
||||
CHECK_EQ(rad_load_f32(pl[1].data(), RAD_F32, 127), 0.5f);
|
||||
CHECK_EQ(rad_load_f32(pl[1].data(), RAD_F32, 128), 0.3f);
|
||||
CHECK_EQ(rad_load_f32(pl[1].data(), RAD_F32, 255), 0.3f);
|
||||
std::vector<float> f((size_t)(256 * 128));
|
||||
REQUIRE_EQ(ckpt_rows_f32(w, 0, 256, f.data(), &why), RAD_OK);
|
||||
int bad = 0;
|
||||
for (int64_t r = 0; r < 256; ++r)
|
||||
for (int64_t k = 0; k < 128; ++k)
|
||||
bad += f[(size_t)(r * 128 + k)] !=
|
||||
(float)(((r % 128) * 128 + k) % 7 - 3) * (r < 128 ? 0.5f : 0.3f);
|
||||
CHECK_EQ(bad, 0);
|
||||
|
||||
ImportForm fb;
|
||||
fb.block[0] = fb.block[1] = 128;
|
||||
fb.scale = RAD_BF16;
|
||||
REQUIRE_EQ(ckpt_import_form(&w, fb, &why), RAD_OK);
|
||||
rad_enc_format(&w.enc, en, sizeof en);
|
||||
CHECK_EQ(std::string(en), std::string("fp8_e4m3*bf16[128x128]"));
|
||||
CHECK_EQ(w.rounded, (int64_t)1); /* 0.3 is not a bf16; 0.5 is */
|
||||
const std::vector<float> dec = decode_planes(w);
|
||||
REQUIRE_EQ(dec.size(), f.size());
|
||||
const float b3 = rad_load_f32(std::vector<uint16_t>{ rad_f32_to_bf16(0.3f) }.data(), RAD_BF16, 0);
|
||||
int bad_dec = 0;
|
||||
for (int64_t r = 0; r < 256; ++r)
|
||||
for (int64_t k = 0; k < 128; ++k)
|
||||
bad_dec += dec[(size_t)(r * 128 + k)] !=
|
||||
(float)(((r % 128) * 128 + k) % 7 - 3) * (r < 128 ? 0.5f : b3);
|
||||
CHECK_EQ(bad_dec, 0);
|
||||
|
||||
REQUIRE_EQ(ckpt_resolve(ck, prog, "ca", false, &w, &why), RAD_OK);
|
||||
CHECK_EQ(ckpt_import_form(&w, fb, &why), (int)RAD_E_SHAPE);
|
||||
CHECK(why.find("'c.weight'") != std::string::npos);
|
||||
}
|
||||
|
||||
/* A ModelOpt algorithm this does not read (AWQ-scaled, or NVFP4 in other groups) is refused by
|
||||
* name, as is an NVFP4 weight without its second scale. */
|
||||
TEST(a_modelopt_release_in_an_unread_form_is_refused_by_name) {
|
||||
{
|
||||
const std::string dir = write_checkpoint(
|
||||
{ bf16("x", { 2, 2 }, 0) },
|
||||
"{\"model_type\":\"qwen3_5\",\"quantization_config\":{\"quant_method\":\"modelopt\","
|
||||
"\"quant_algo\":\"W4A8_AWQ\"}}");
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
CHECK(ck.imports() == Checkpoint::Import::None);
|
||||
CHECK(ck.import_refusal().find("W4A8_AWQ") != std::string::npos);
|
||||
}
|
||||
{
|
||||
const std::string dir = write_checkpoint(
|
||||
{ bf16("x", { 2, 2 }, 0) },
|
||||
"{\"model_type\":\"qwen3_5\",\"quantization_config\":{\"quant_method\":\"modelopt\","
|
||||
"\"quant_algo\":\"MIXED_PRECISION\",\"quantized_layers\":{\"m.down\":{\"quant_algo\":"
|
||||
"\"NVFP4\",\"group_size\":32}}}}");
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
CHECK(ck.imports() == Checkpoint::Import::None);
|
||||
CHECK(ck.import_refusal().find("m.down") != std::string::npos);
|
||||
CHECK(ck.import_refusal().find("32") != std::string::npos);
|
||||
}
|
||||
{
|
||||
std::vector<T> ts;
|
||||
ts.push_back(T{ "g.weight", "U8", { 2, 16 }, std::vector<uint8_t>(32, 0x21) });
|
||||
ts.push_back(T{ "g.weight_scale", "F8_E4M3", { 2, 2 }, std::vector<uint8_t>(4, 0x38) });
|
||||
const std::string dir = write_checkpoint(ts, kModelOptConfig);
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
Program prog;
|
||||
prog.name_map.push_back(map("g", RAD_MAP_COPY, { "g.weight" }));
|
||||
CkptWeight w;
|
||||
std::string why;
|
||||
CHECK(ckpt_resolve(ck, prog, "g", false, &w, &why) < 0);
|
||||
CHECK(why.find("weight_scale_2") != std::string::npos);
|
||||
}
|
||||
}
|
||||
|
||||
/* An NVFP4 group whose weights are not 4-bit floats in groups of 16, and a compressed-tensors
|
||||
* format this does not read, are refused with the group or format named. */
|
||||
TEST(a_compressed_tensors_release_in_an_unread_form_is_refused_by_name) {
|
||||
@@ -2086,4 +2565,91 @@ TEST(a_fp8_weight_mixed_block_and_per_row_refuses_the_read) {
|
||||
CHECK(ckpt_rows_f32(w, 0, 1, f.data(), &why) < 0);
|
||||
}
|
||||
|
||||
/* ================================================================== derived weights */
|
||||
/* f32 values `v`, as an EMA codebook ships. */
|
||||
T f32(const std::string& name, std::vector<int64_t> shape, const std::vector<float>& v) {
|
||||
T t{ name, "F32", shape, {} };
|
||||
t.bytes.resize(v.size() * 4);
|
||||
std::memcpy(t.bytes.data(), v.data(), t.bytes.size());
|
||||
return t;
|
||||
}
|
||||
|
||||
/* A linear kept (in, out) is read (out, in): each leading slice transposed, the weight not
|
||||
* trivial (a recipe rule stores it). */
|
||||
TEST(a_transposed_weight_swaps_its_last_two_dimensions_in_each_slice) {
|
||||
const std::string dir = write_checkpoint({ bf16("head.weight", { 2, 3, 4 }, 0.0f) }, kConfig);
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
Program prog;
|
||||
prog.name_map.push_back(map("ht", RAD_MAP_TRANSPOSE, { "head.weight" }));
|
||||
CkptWeight w;
|
||||
std::string why;
|
||||
REQUIRE_EQ(ckpt_resolve(ck, prog, "ht", false, &w, &why), RAD_OK);
|
||||
CHECK(!w.trivial);
|
||||
REQUIRE_EQ(w.rank, (uint32_t)3);
|
||||
CHECK_EQ(w.shape[0], (int64_t)2);
|
||||
CHECK_EQ(w.shape[1], (int64_t)4);
|
||||
CHECK_EQ(w.shape[2], (int64_t)3);
|
||||
std::vector<float> f(2 * 4 * 3);
|
||||
REQUIRE_EQ(ckpt_rows_f32(w, 0, 8, f.data(), &why), RAD_OK);
|
||||
/* Element (s, j, i) is the source's (s, i, j), which bf16() made s * 12 + i * 4 + j. */
|
||||
for (int s = 0; s < 2; ++s)
|
||||
for (int j = 0; j < 4; ++j)
|
||||
for (int i = 0; i < 3; ++i)
|
||||
CHECK_EQ(f[(size_t)(s * 12 + j * 3 + i)], (float)(s * 12 + i * 4 + j));
|
||||
}
|
||||
|
||||
/* An EMA codebook is its sums over max(usage, 1e-5), row by row; codebooks declared in pieces
|
||||
* stack along dim 0. */
|
||||
TEST(an_ema_codebook_divides_its_sums_by_their_usage_and_stacks) {
|
||||
const std::string dir = write_checkpoint(
|
||||
{ f32("a.embedding_sum", { 2, 2 }, { 2.0f, 4.0f, 3.0f, 6.0f }),
|
||||
f32("a.cluster_usage", { 2 }, { 2.0f, 0.0f }),
|
||||
f32("b.embedding_sum", { 2, 2 }, { 8.0f, 1.0f, 5.0f, 5.0f }),
|
||||
f32("b.cluster_usage", { 2 }, { 4.0f, 5.0f }) },
|
||||
kConfig);
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
Program prog;
|
||||
prog.name_map.push_back(map("cb", RAD_MAP_EMA, { "a.embedding_sum", "a.cluster_usage" }));
|
||||
prog.name_map.push_back(map("cb", RAD_MAP_EMA, { "b.embedding_sum", "b.cluster_usage" }));
|
||||
prog.name_map.push_back(map("short", RAD_MAP_EMA, { "a.embedding_sum", "b.embedding_sum" }));
|
||||
CkptWeight w;
|
||||
std::string why;
|
||||
REQUIRE_EQ(ckpt_resolve(ck, prog, "cb", false, &w, &why), RAD_OK);
|
||||
CHECK(!w.trivial);
|
||||
CHECK_EQ(w.shape[0], (int64_t)4);
|
||||
CHECK_EQ(w.shape[1], (int64_t)2);
|
||||
std::vector<float> f(8);
|
||||
REQUIRE_EQ(ckpt_rows_f32(w, 0, 4, f.data(), &why), RAD_OK);
|
||||
const float want[8] = { 1.0f, 2.0f, 3.0f / 1e-5f, 6.0f / 1e-5f, 2.0f, 0.25f, 1.0f, 1.0f };
|
||||
for (int i = 0; i < 8; ++i) CHECK_EQ(f[(size_t)i], want[i]);
|
||||
/* Usage that is not one count a row is refused. */
|
||||
CHECK_EQ(ckpt_resolve(ck, prog, "short", false, &w, &why), (int)RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
/* A folder holding a model of its own beside the checkpoint's weights (a codec) is read as part
|
||||
* of it: its tensors and its config under the folder's name. */
|
||||
TEST(a_companion_folder_is_read_under_its_name) {
|
||||
const std::string dir = write_checkpoint({ bf16("w", { 2, 2 }, 1.0f) }, kConfig);
|
||||
const std::string sub = dir + "/codec";
|
||||
REQUIRE_EQ(mkdir(sub.c_str(), 0755), 0);
|
||||
write_shard(sub + "/model.safetensors", { bf16("decoder.x", { 2, 2 }, 5.0f) });
|
||||
write_file(sub + "/config.json", "{\"model_type\": \"tok\", \"decoder_config\": {\"dim\": 7}}");
|
||||
/* A folder without weights of its own is not a model. */
|
||||
REQUIRE_EQ(mkdir((dir + "/notes").c_str(), 0755), 0);
|
||||
write_file(dir + "/notes/config.json", "{}");
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
CHECK(ck.find("w") != nullptr);
|
||||
CHECK(ck.find("codec.decoder.x") != nullptr);
|
||||
CHECK(ck.find("decoder.x") == nullptr);
|
||||
auto mget = [&](const char* k) {
|
||||
const char* v = ck.meta().get(k);
|
||||
return std::string(v ? v : "");
|
||||
};
|
||||
CHECK_EQ(mget("codec.model_type"), std::string("tok"));
|
||||
CHECK_EQ(mget("codec.decoder_config.dim"), std::string("7"));
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
+83
-2
@@ -127,6 +127,48 @@ TEST(the_kl_mode_records_or_scores_and_says_which_input_it_lacks) {
|
||||
CHECK_EQ(parse({ "--kld-ref" }, &f), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
/* Runtime LoRA: the adapters reach their fields in order, the targets as sorted leaf names, and a
|
||||
* combination that would size slots no adapter uses, or name an adapter that is not served, is
|
||||
* refused by name. */
|
||||
TEST(the_lora_flags_reach_their_fields_and_refuse_what_serves_no_adapter) {
|
||||
Config c;
|
||||
CHECK_OK(parse({ "--lora", "b=/ad/b", "--lora", "a=/ad/a", "--max-loras", "3",
|
||||
"--max-lora-rank", "32", "--lora-target-modules", "v_proj, q_proj,v_proj" },
|
||||
&c));
|
||||
REQUIRE_EQ(c.lora.adapters.size(), (size_t)2);
|
||||
CHECK_EQ(c.lora.adapters[0].first, std::string("b"));
|
||||
CHECK_EQ(c.lora.adapters[1].second, std::string("/ad/a"));
|
||||
CHECK_EQ(c.lora.slots(), 3);
|
||||
CHECK_EQ(c.lora.max_rank, 32);
|
||||
CHECK(c.lora.targets == std::vector<std::string>({ "q_proj", "v_proj" }));
|
||||
Config d;
|
||||
CHECK_OK(parse({}, &d));
|
||||
CHECK(!d.lora.enabled());
|
||||
|
||||
auto refused = [](std::initializer_list<const char*> v, const char* why) {
|
||||
int st = RAD_OK;
|
||||
const std::string log = stderr_of([&] { st = parse_fresh(v); });
|
||||
if (st != RAD_E_INVAL || log.find(why) == std::string::npos)
|
||||
std::fprintf(stderr, " expected a refusal naming '%s', got %d: %s", why, st,
|
||||
log.c_str());
|
||||
CHECK_EQ(st, (int)RAD_E_INVAL);
|
||||
CHECK(log.find(why) != std::string::npos);
|
||||
};
|
||||
refused({ "--lora", "/ad/a" }, "NAME=PATH");
|
||||
refused({ "--lora", "a=" }, "NAME=PATH");
|
||||
refused({ "--lora", "a=/x", "--lora", "a=/y" }, "names the adapter 'a' twice");
|
||||
refused({ "--lora", "a=/x", "--lora", "b=/y", "--max-loras", "1" }, "fewer adapters");
|
||||
refused({ "--max-lora-rank", "32" }, "--max-lora-rank sizes runtime LoRA slots");
|
||||
refused({ "--lora-target-modules", "q_proj" }, "--lora-target-modules sizes");
|
||||
refused({ "--max-loras", "2" }, "names no module an adapter may target");
|
||||
refused({ "--lora", "a=/x", "--lora-target-modules", "self_attn.q_proj" }, "leaf names");
|
||||
refused({ "--lora", "a=/x", "--lora-target-modules", ".*proj" }, "leaf names");
|
||||
refused({ "--lora", "a=/x", "--lora-target-modules", " , " }, "names no module");
|
||||
refused({ "--lora", "a=/x", "--kld-lora", "a" }, "in KL mode");
|
||||
refused({ "--lora", "a=/x", "--kld-lora", "b", "--kld-ref", "/r" }, "'b' is not one of");
|
||||
refused({ "--lora", "a=/x", "--kld-ref", "/r", "--kld-lora-sources", "d" }, "give --kld-lora");
|
||||
}
|
||||
|
||||
TEST(the_model_is_required_and_nothing_else_is) {
|
||||
Config c;
|
||||
Argv none({});
|
||||
@@ -410,8 +452,10 @@ const std::map<std::string, std::vector<std::string>>& legal_values() {
|
||||
{ "--kld-record", { "/r", "--kld-corpus", "/c.jsonl" } }, { "--kld-ref", { "/r" } },
|
||||
{ "--kld-corpus", { "/c.jsonl", "--kld-record", "/r" } },
|
||||
{ "--kld-out", { "/o.json", "--kld-ref", "/r" } },
|
||||
{ "--lora", { "a=/adapters/a" } }, { "--max-loras", { "2" } },
|
||||
{ "--max-lora-rank", { "32" } }, { "--lora-target-modules", { "q_proj,v_proj" } },
|
||||
{ "--lora", { "a=/adapters/a" } },
|
||||
{ "--max-loras", { "2", "--lora-target-modules", "q_proj" } },
|
||||
{ "--max-lora-rank", { "32", "--lora", "a=/adapters/a" } },
|
||||
{ "--lora-target-modules", { "q_proj,v_proj", "--max-loras", "1" } },
|
||||
{ "--kld-lora", { "a", "--lora", "a=/adapters/a", "--kld-ref", "/r" } },
|
||||
{ "--kld-lora-sources", { "doc/", "--kld-lora", "a", "--lora", "a=/adapters/a",
|
||||
"--kld-ref", "/r" } },
|
||||
@@ -662,6 +706,43 @@ TEST(the_checkpoint_policy_is_one_of_the_three_that_exist) {
|
||||
CHECK_EQ(d.checkpoint_policy, std::string("geometric-backoff"));
|
||||
}
|
||||
|
||||
/* --checkpoint-slots is auto by default, resolved by the engine once a snapshot's size is known;
|
||||
* a count is taken as given, 0 included, and the report shows which. */
|
||||
TEST(the_checkpoint_slots_are_auto_or_a_count) {
|
||||
Config d;
|
||||
CHECK_EQ(parse({}, &d), RAD_OK);
|
||||
CHECK_EQ(d.checkpoint_slots, -1ll);
|
||||
auto row = [](const Config& c) {
|
||||
for (const diag::ConfigRow& r : diag::config_rows(c))
|
||||
if (r.flag == "--checkpoint-slots") return r;
|
||||
return diag::ConfigRow{};
|
||||
};
|
||||
CHECK_EQ(row(d).value, std::string("auto"));
|
||||
CHECK_EQ(row(d).source, std::string("default"));
|
||||
|
||||
Config a;
|
||||
CHECK_EQ(parse({ "--checkpoint-slots", "auto" }, &a), RAD_OK);
|
||||
CHECK_EQ(a.checkpoint_slots, -1ll);
|
||||
CHECK_EQ(row(a).value, std::string("auto"));
|
||||
CHECK_EQ(row(a).source, std::string("command line"));
|
||||
for (const auto& [arg, want] : std::vector<std::pair<const char*, long long>>{
|
||||
{ "0", 0 }, { "8", 8 }, { "96", 96 }, { "9223372036854775807", INT64_MAX } }) {
|
||||
Config c;
|
||||
CHECK_EQ(parse({ "--checkpoint-slots", arg }, &c), RAD_OK);
|
||||
CHECK_EQ(c.checkpoint_slots, want);
|
||||
CHECK_EQ(row(c).value, std::string(arg));
|
||||
}
|
||||
for (const char* bad : { "-1", "Auto", "auto8", "8 ", "", "0x10", "1e3",
|
||||
"9223372036854775808" }) {
|
||||
Config c;
|
||||
int st = RAD_OK;
|
||||
const std::string log = stderr_of([&] { st = parse({ "--checkpoint-slots", bad }, &c); });
|
||||
if (st != RAD_E_INVAL) std::fprintf(stderr, " '%s' was not refused\n", bad);
|
||||
CHECK_EQ(st, (int)RAD_E_INVAL);
|
||||
CHECK(has(log, "--checkpoint-slots"));
|
||||
}
|
||||
}
|
||||
|
||||
/* The request parser's ranges, enforced at startup: a default outside them would 400 every
|
||||
* request omitting the field, from a server that reports healthy. */
|
||||
TEST(the_sampler_defaults_are_range_checked_at_startup) {
|
||||
|
||||
@@ -433,6 +433,98 @@ TEST(a_recipe_or_flag_that_cannot_be_honoured_is_refused_before_writing) {
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== an int4 release */
|
||||
|
||||
namespace {
|
||||
|
||||
/* compressed-tensors' value of one packed linear of a tiny int4 release (tiny_model.h,
|
||||
* write_llama_ct_int4): (q - zero_point) * scale, f32 [N, K]. */
|
||||
std::vector<float> ct_values(const std::map<std::string, tiny::Tensor>& src, const std::string& b) {
|
||||
const tiny::Tensor& p = src.at(b + ".weight_packed");
|
||||
const tiny::Tensor& s = src.at(b + ".weight_scale");
|
||||
const auto z = src.find(b + ".weight_zero_point");
|
||||
const int64_t N = p.shape[0], K = p.shape[1] * 8, G = s.shape[1];
|
||||
std::vector<float> v((size_t)(N * K));
|
||||
for (int64_t n = 0; n < N; ++n)
|
||||
for (int64_t k = 0; k < K; ++k) {
|
||||
uint32_t w;
|
||||
std::memcpy(&w, p.bytes.data() + (n * (K / 8) + k / 8) * 4, 4);
|
||||
const int q = (int)((w >> (4 * (k % 8))) & 15) - 8;
|
||||
int zp = 0;
|
||||
if (z != src.end()) {
|
||||
std::memcpy(&w, z->second.bytes.data() + ((n / 8) * G + k / 128) * 4, 4);
|
||||
zp = (int)((w >> (4 * (n % 8))) & 15) - 8;
|
||||
}
|
||||
v[(size_t)(n * K + k)] =
|
||||
(float)(q - zp) * rad_load_f32(s.bytes.data(), RAD_BF16, n * G + k / 128);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* An int4 W4A16 release (compressed-tensors, asymmetric with zero points, and symmetric with
|
||||
* act-order static) converts with the import rule into the 4-bit GEMMs' form,
|
||||
* `u4*f16[1x128]-u4[1x128]`, each joined weight decoding to compressed-tensors' (q - zp) * scale
|
||||
* bit for bit, its rule recorded, and the run saying every shipped value is exact. Declaring it
|
||||
* resolves the cast, the f16 4-bit GEMM, the int8 quantiser and the int8 4-bit GEMM on the host
|
||||
* libraries. Without the rule the plugin refuses the shipped form by name. */
|
||||
TEST(an_int4_release_imports_exactly_through_the_import_rule) {
|
||||
for (const bool asym : { true, false }) {
|
||||
tiny::TempDir d(asym ? "convert_i4a" : "convert_i4s");
|
||||
REQUIRE(d.ok());
|
||||
const std::string ck = d / "llama-int4", recipe = d / "int4.recipe", out = d / "i4.rad";
|
||||
REQUIRE_EQ(mkdir(ck.c_str(), 0755), 0);
|
||||
REQUIRE(tiny::write_llama_ct_int4(ck, {}, asym));
|
||||
REQUIRE(tiny::write_text(recipe, tiny::kInt4ImportRecipe));
|
||||
std::map<std::string, tiny::Tensor> src;
|
||||
for (tiny::Tensor& t : tiny::read_safetensors(ck + "/model.safetensors"))
|
||||
src[t.name] = std::move(t);
|
||||
std::string log;
|
||||
const int st = convert(ck, { "-o", out, "--recipe", recipe }, &log);
|
||||
if (st != 0) fprintf(stderr, "%s\n", log.c_str());
|
||||
REQUIRE_EQ(st, 0);
|
||||
CHECK(has(log, "every shipped value exact"));
|
||||
RadFile f;
|
||||
REQUIRE_EQ(f.open(out.c_str()), RAD_OK);
|
||||
const struct { const char* weight; std::vector<std::string> parts; } kJoins[] = {
|
||||
{ "blk.0.attn_qkv.weight", { "model.layers.0.self_attn.q_proj",
|
||||
"model.layers.0.self_attn.k_proj",
|
||||
"model.layers.0.self_attn.v_proj" } },
|
||||
{ "blk.1.ffn_gate_up.weight", { "model.layers.1.mlp.gate_proj",
|
||||
"model.layers.1.mlp.up_proj" } },
|
||||
{ "blk.1.ffn_down.weight", { "model.layers.1.mlp.down_proj" } },
|
||||
{ "blk.0.attn_output.weight", { "model.layers.0.self_attn.o_proj" } },
|
||||
};
|
||||
for (const auto& j : kJoins) {
|
||||
const RadFileEntry* e = f.find(j.weight);
|
||||
REQUIRE(e != nullptr);
|
||||
CHECK_EQ(enc_name(f.encoding(*e)), std::string("u4*f16[1x128]-u4[1x128]"));
|
||||
CHECK_EQ(std::string(f.str(e->quantizer)), std::string("import"));
|
||||
CHECK_EQ(std::string(f.str(e->options)), std::string("codes=u4,scale=f16,zero=u4"));
|
||||
std::vector<float> want;
|
||||
for (const std::string& part : j.parts) {
|
||||
const std::vector<float> v = ct_values(src, part);
|
||||
want.insert(want.end(), v.begin(), v.end());
|
||||
}
|
||||
const std::vector<float> got = decode(f, *e);
|
||||
REQUIRE_EQ(got.size(), want.size());
|
||||
int64_t bad = 0;
|
||||
for (size_t i = 0; i < got.size(); ++i) bad += got[i] != want[i];
|
||||
CHECK_EQ(bad, (int64_t)0);
|
||||
}
|
||||
/* The head the release leaves bf16 stays so. */
|
||||
const RadFileEntry* head = f.find("output.weight");
|
||||
REQUIRE(head != nullptr);
|
||||
CHECK_EQ(enc_name(f.encoding(*head)), std::string("bf16"));
|
||||
|
||||
std::string log2;
|
||||
CHECK(convert(ck, { "-o", d / "none.rad" }, &log2) != 0);
|
||||
CHECK(has(log2, asym ? "u4*bf16[1x128]-u4[1x128]" : "i4*bf16[1x128]"));
|
||||
CHECK(has(log2, "import rule"));
|
||||
}
|
||||
}
|
||||
|
||||
/* A rule that matches nothing is almost always a typo, so it is named; the run goes on. */
|
||||
TEST(a_rule_that_matches_no_weight_is_warned_about) {
|
||||
World& w = world();
|
||||
|
||||
+404
-16
@@ -33,7 +33,9 @@
|
||||
#include <sys/socket.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include <cerrno>
|
||||
#include <condition_variable>
|
||||
#include <cstring>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
@@ -188,6 +190,10 @@ struct World {
|
||||
std::string qwen35, lfm2, gemma4, llama, llama_rad;
|
||||
/* llama.rad with its lm head block fp8, and int8 per (row, 128 of K). */
|
||||
std::string llama_fp8head, llama_i8head;
|
||||
/* The llama as an int4 W4A16 release with zero points (tiny_model.h, write_llama_ct_int4),
|
||||
* and its container through the import rule. */
|
||||
std::string llama_int4, llama_int4_rad;
|
||||
std::string llama_mxfp4; /* llama's trunk as OCP-MXFP4 */
|
||||
/* qwen35 and gemma4 with 4 KiB of KV a token (wider KV heads), for the preemption cases: a MiB
|
||||
* of device is then about 256 tokens of pool, fine enough for small_device() to land between
|
||||
* one request and four. */
|
||||
@@ -217,12 +223,15 @@ struct World {
|
||||
llama_rad = dir / "llama.rad";
|
||||
llama_fp8head = dir / "llama_fp8head.rad";
|
||||
llama_i8head = dir / "llama_i8head.rad";
|
||||
llama_int4 = dir / "llama_int4";
|
||||
llama_int4_rad = dir / "llama_int4.rad";
|
||||
llama_mxfp4 = dir / "llama_mxfp4.rad";
|
||||
qwen35_kv = dir / "qwen35_kv";
|
||||
gemma4_kv = dir / "gemma4_kv";
|
||||
qwen35_spec = dir / "qwen35_spec";
|
||||
qwen3asr = dir / "qwen3asr";
|
||||
for (const std::string* d : { &qwen35, &lfm2, &gemma4, &llama, &qwen35_kv, &gemma4_kv,
|
||||
&qwen35_spec, &qwen3asr })
|
||||
&qwen35_spec, &qwen3asr, &llama_int4 })
|
||||
if (mkdir(d->c_str(), 0755) != 0) return;
|
||||
tiny::Qwen35 qkv;
|
||||
qkv.head_dim = 128;
|
||||
@@ -241,7 +250,10 @@ struct World {
|
||||
!tiny::write_text(dir / "llama_fp8head.recipe",
|
||||
std::string(tiny::kLlamaFp8Recipe) + tiny::kLlamaFp8HeadRule) ||
|
||||
!tiny::write_text(dir / "llama_i8head.recipe",
|
||||
std::string(tiny::kLlamaFp8Recipe) + tiny::kLlamaI8HeadRule))
|
||||
std::string(tiny::kLlamaFp8Recipe) + tiny::kLlamaI8HeadRule) ||
|
||||
!tiny::write_llama_ct_int4(llama_int4, {}, true) ||
|
||||
!tiny::write_text(dir / "llama_int4.recipe", tiny::kInt4ImportRecipe) ||
|
||||
!tiny::write_text(dir / "llama_mxfp4.recipe", tiny::kLlamaMxfp4Recipe))
|
||||
return;
|
||||
|
||||
tiny::Rng r(11);
|
||||
@@ -259,11 +271,14 @@ struct World {
|
||||
!write_corpus(corpus_probe, { words(r, 40) }))
|
||||
return;
|
||||
|
||||
const std::pair<std::string, const char*> kConverts[] = {
|
||||
{ llama_rad, "llama.recipe" }, { llama_fp8head, "llama_fp8head.recipe" },
|
||||
{ llama_i8head, "llama_i8head.recipe" } };
|
||||
for (const auto& [out, recipe] : kConverts) {
|
||||
const int st = tiny::run({ RAD_E2E_CONVERT, llama, "-o", out, "--recipe",
|
||||
const struct { std::string out; const char* recipe; const std::string* ckpt; }
|
||||
kConverts[] = { { llama_rad, "llama.recipe", &llama },
|
||||
{ llama_fp8head, "llama_fp8head.recipe", &llama },
|
||||
{ llama_i8head, "llama_i8head.recipe", &llama },
|
||||
{ llama_int4_rad, "llama_int4.recipe", &llama_int4 },
|
||||
{ llama_mxfp4, "llama_mxfp4.recipe", &llama } };
|
||||
for (const auto& [out, recipe, ckpt] : kConverts) {
|
||||
const int st = tiny::run({ RAD_E2E_CONVERT, *ckpt, "-o", out, "--recipe",
|
||||
dir / recipe },
|
||||
engine_env(), &convert_log);
|
||||
if (st != 0) {
|
||||
@@ -460,23 +475,28 @@ struct Server {
|
||||
};
|
||||
|
||||
/* One request on its own loopback connection, sent and not yet read, so several can be in flight
|
||||
* at once. */
|
||||
* at once. A request that gets no response says why in `why`. */
|
||||
struct Call {
|
||||
int fd = -1;
|
||||
std::string why;
|
||||
bool fail(const char* what) {
|
||||
why = std::string(what) + ": " + std::strerror(errno);
|
||||
return false;
|
||||
}
|
||||
bool send(int port, const char* method, const std::string& path, const std::string& body) {
|
||||
fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
|
||||
if (fd < 0) return false;
|
||||
if (fd < 0) return fail("socket");
|
||||
sockaddr_in a{};
|
||||
a.sin_family = AF_INET;
|
||||
a.sin_port = htons((uint16_t)port);
|
||||
a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
if (connect(fd, (sockaddr*)&a, sizeof a) != 0) return false;
|
||||
if (connect(fd, (sockaddr*)&a, sizeof a) != 0) return fail("connect");
|
||||
std::string req = std::string(method) + " " + path + " HTTP/1.1\r\nHost: 127.0.0.1\r\n" +
|
||||
"Connection: close\r\nContent-Type: application/json\r\n" +
|
||||
"Content-Length: " + std::to_string(body.size()) + "\r\n\r\n" + body;
|
||||
for (size_t off = 0; off < req.size();) {
|
||||
const ssize_t n = ::send(fd, req.data() + off, req.size() - off, MSG_NOSIGNAL);
|
||||
if (n <= 0) return false;
|
||||
if (n <= 0) return fail("send");
|
||||
off += (size_t)n;
|
||||
}
|
||||
return true;
|
||||
@@ -485,16 +505,23 @@ struct Call {
|
||||
int read(std::string* body) {
|
||||
std::string raw;
|
||||
char buf[16384];
|
||||
int err = 0;
|
||||
for (;;) {
|
||||
const ssize_t n = ::recv(fd, buf, sizeof buf, 0);
|
||||
if (n < 0 && errno == EINTR) continue;
|
||||
if (n < 0) err = errno;
|
||||
if (n <= 0) break;
|
||||
raw.append(buf, (size_t)n);
|
||||
}
|
||||
close(fd);
|
||||
fd = -1;
|
||||
const size_t h = raw.find("\r\n\r\n");
|
||||
if (raw.compare(0, 9, "HTTP/1.1 ") != 0 || h == std::string::npos) return -1;
|
||||
if (raw.compare(0, 9, "HTTP/1.1 ") != 0 || h == std::string::npos) {
|
||||
why = "no response: " + std::to_string(raw.size()) + " byte(s) before the server " +
|
||||
(err ? std::string("reset the connection (") + std::strerror(err) + ")"
|
||||
: std::string("closed it"));
|
||||
return -1;
|
||||
}
|
||||
std::string head = raw.substr(0, h), rest = raw.substr(h + 4);
|
||||
for (char& c : head) c = (char)std::tolower((unsigned char)c);
|
||||
if (head.find("transfer-encoding: chunked") != std::string::npos) {
|
||||
@@ -515,11 +542,13 @@ struct Call {
|
||||
~Call() { if (fd >= 0) close(fd); }
|
||||
};
|
||||
|
||||
json post(int port, const std::string& path, const json& body, int* status = nullptr) {
|
||||
json post(int port, const std::string& path, const json& body, int* status = nullptr,
|
||||
std::string* why = nullptr) {
|
||||
Call c;
|
||||
std::string out;
|
||||
const int st = c.send(port, "POST", path, body.dump()) ? c.read(&out) : -1;
|
||||
if (status) *status = st;
|
||||
if (why) *why = c.why;
|
||||
return json::parse(out, nullptr, false);
|
||||
}
|
||||
|
||||
@@ -709,6 +738,265 @@ TEST(qwen35_two_ranks_agree_with_one_within_rounding) {
|
||||
{ "RADIANCE_HOST_DEVICES=2" }));
|
||||
}
|
||||
|
||||
/* ================================================================== runtime LoRA */
|
||||
|
||||
/* A PEFT adapter over the qwen35 checkpoint on every linear runtime LoRA follows (the gated
|
||||
* attention, the delta net's in_proj_qkv, in_proj_z and out_proj, the MLP), and the checkpoint with
|
||||
* it merged in. Written once, by the first case that needs them. */
|
||||
const std::vector<std::string> kLoraTargets = { "q_proj", "k_proj", "v_proj",
|
||||
"o_proj", "in_proj_qkv", "in_proj_z",
|
||||
"out_proj", "gate_proj", "up_proj",
|
||||
"down_proj" };
|
||||
struct LoraWorld {
|
||||
tiny::TempDir dir{ "e2e_lora" };
|
||||
std::string adapter, merged;
|
||||
bool ok = false;
|
||||
LoraWorld() {
|
||||
if (!dir.ok() || !world().ok) return;
|
||||
adapter = dir / "adapter";
|
||||
merged = dir / "merged";
|
||||
ok = tiny::write_lora(adapter, world().qwen35, kLoraTargets, 8, 16.0, 21, 0.25f, merged);
|
||||
}
|
||||
};
|
||||
LoraWorld& lora_world() {
|
||||
static LoraWorld l;
|
||||
return l;
|
||||
}
|
||||
|
||||
/* `mixed` against two recordings of the same corpus, document by document: those whose source
|
||||
* starts with `prefix` must be `a`'s rows byte for byte, the others `b`'s. */
|
||||
bool spliced_recording_matches(const std::string& mixed, const std::string& a,
|
||||
const std::string& b, const std::string& prefix, std::string* why) {
|
||||
const json m = json::parse(tiny::read_text(mixed + "/kld.json"), nullptr, false);
|
||||
if (!m.is_object() || !m.contains("docs")) { *why = "no manifest"; return false; }
|
||||
if (tiny::read_text(mixed + "/tokens.i32") != tiny::read_text(a + "/tokens.i32")) {
|
||||
*why = "tokens.i32 differs";
|
||||
return false;
|
||||
}
|
||||
const int64_t n_vocab = m["n_vocab"].get<int64_t>(), top = m["top"].get<int64_t>();
|
||||
const std::pair<const char*, int64_t> files[] = {
|
||||
{ "logp.f16", n_vocab * 2 }, { "top.bin", top * 8 }, { "rows.f32", 8 } };
|
||||
for (const auto& [f, row_bytes] : files) {
|
||||
const std::string x = tiny::read_text(mixed + "/" + f);
|
||||
const std::string ya = tiny::read_text(a + "/" + f), yb = tiny::read_text(b + "/" + f);
|
||||
if (x.empty() || x.size() != ya.size() || x.size() != yb.size()) {
|
||||
*why = std::string(f) + " is missing or of another size";
|
||||
return false;
|
||||
}
|
||||
for (const json& d : m["docs"]) {
|
||||
const std::string src = d["source"].get<std::string>();
|
||||
const int64_t row0 = d["row0"].get<int64_t>();
|
||||
const int64_t rows = d["tokens"].get<int64_t>() - 1 - d["score_from"].get<int64_t>();
|
||||
const std::string& want = src.rfind(prefix, 0) == 0 ? ya : yb;
|
||||
const size_t at = (size_t)(row0 * row_bytes), len = (size_t)(rows * row_bytes);
|
||||
if (x.compare(at, len, want, at, len) != 0) {
|
||||
*why = std::string(f) + ": document " + src + " is not " +
|
||||
(&want == &ya ? "the adapter" : "the base") + " recording's";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* The adapter served at runtime scores as the merged checkpoint does, within rounding, at one rank
|
||||
* and at two (where row-parallel GEMMs carry the delta through their all-reduce); the base model
|
||||
* against the same reference is well outside it, so a delta that went missing fails here. */
|
||||
TEST(runtime_lora_scores_as_the_merged_checkpoint_does) {
|
||||
World& w = world();
|
||||
LoraWorld& L = lora_world();
|
||||
REQUIRE(L.ok);
|
||||
tiny::TempDir d("e2e_lora_ref");
|
||||
const std::string ref = d / "merged";
|
||||
const std::vector<std::string> one = { "--max-num-batched-tokens", "512", "--max-num-seqs", "1" };
|
||||
std::vector<std::string> rec = { "--kld-record", ref, "--kld-corpus", w.corpus_short };
|
||||
rec.insert(rec.end(), one.begin(), one.end());
|
||||
const Ran merged = radiance(L.merged, rec);
|
||||
REQUIRE_RAN(merged);
|
||||
auto score = [&](const std::vector<std::string>& args, const std::vector<std::string>& env) {
|
||||
tiny::TempDir o("e2e_lora_kld");
|
||||
std::vector<std::string> a = { "--kld-ref", ref, "--kld-out", o / "kld.json" };
|
||||
a.insert(a.end(), one.begin(), one.end());
|
||||
a.insert(a.end(), args.begin(), args.end());
|
||||
const Ran r = radiance(w.qwen35, a, env);
|
||||
if (r.status != 0) {
|
||||
fprintf(stderr, " child exited %d:\n%s\n", r.status, tail(r.log).c_str());
|
||||
return json();
|
||||
}
|
||||
return json::parse(tiny::read_text(o / "kld.json"), nullptr, false);
|
||||
};
|
||||
const std::vector<std::string> ad = { "--lora", "ad=" + L.adapter, "--kld-lora", "ad" };
|
||||
check_within_rounding("runtime LoRA against the merged checkpoint", score(ad, {}));
|
||||
std::vector<std::string> tp2 = { "--tp", "2" };
|
||||
tp2.insert(tp2.end(), ad.begin(), ad.end());
|
||||
check_within_rounding("runtime LoRA at two ranks against the merged checkpoint",
|
||||
score(tp2, { "RADIANCE_HOST_DEVICES=2" }));
|
||||
#if defined(__x86_64__)
|
||||
/* libavx alone serves the adapter ops too, as it serves every other op. */
|
||||
if (::access(RAD_E2E_HOME "/kernels/libavx.so", R_OK) == 0) {
|
||||
std::vector<std::string> avx = { "--kernels", "libavx" };
|
||||
avx.insert(avx.end(), ad.begin(), ad.end());
|
||||
check_within_rounding("runtime LoRA on libavx against the merged checkpoint",
|
||||
score(avx, {}));
|
||||
}
|
||||
#endif
|
||||
const json base = score({}, {});
|
||||
REQUIRE(base.is_object() && base.contains("all"));
|
||||
const double kl = base["all"]["kld"]["mean"].get<double>();
|
||||
fprintf(stderr, " the base against the merged checkpoint: mean KL %.2g\n", kl);
|
||||
CHECK(kl > 0.05);
|
||||
}
|
||||
|
||||
/* An MXFP4 trunk: its GEMM's `group` is the weight's 32-wide exponent block, while the
|
||||
* activation it reads is scaled per 128, and the adapter's shrink reads that activation at the
|
||||
* activation's grid. Against the merged checkpoint, the adapter takes the container from the
|
||||
* adapter's whole effect down to the MXFP4 rounding, on libref and on libavx. (The tiny llama's
|
||||
* MXFP4 container declares at one rank only.) */
|
||||
TEST(runtime_lora_reads_an_mxfp4_trunks_activation_at_its_own_grid) {
|
||||
World& w = world();
|
||||
REQUIRE(w.ok);
|
||||
tiny::TempDir d("e2e_lora_mx");
|
||||
const std::string adapter = d / "adapter", merged = d / "merged", ref = d / "ref";
|
||||
const std::vector<std::string> targets = { "q_proj", "k_proj", "v_proj", "o_proj",
|
||||
"gate_proj", "up_proj", "down_proj" };
|
||||
REQUIRE(tiny::write_lora(adapter, w.llama, targets, 8, 16.0, 23, 0.25f, merged));
|
||||
const std::vector<std::string> one = { "--max-num-batched-tokens", "512", "--max-num-seqs", "1" };
|
||||
std::vector<std::string> rec = { "--kld-record", ref, "--kld-corpus", w.corpus_short };
|
||||
rec.insert(rec.end(), one.begin(), one.end());
|
||||
const Ran recorded = radiance(merged, rec);
|
||||
REQUIRE_RAN(recorded);
|
||||
auto score = [&](const std::vector<std::string>& args, const std::vector<std::string>& env) {
|
||||
tiny::TempDir o("e2e_lora_mx_kld");
|
||||
std::vector<std::string> a = { "--kld-ref", ref, "--kld-out", o / "kld.json" };
|
||||
a.insert(a.end(), one.begin(), one.end());
|
||||
a.insert(a.end(), args.begin(), args.end());
|
||||
const Ran r = radiance(w.llama_mxfp4, a, env);
|
||||
if (r.status != 0) {
|
||||
fprintf(stderr, " child exited %d:\n%s\n", r.status, tail(r.log).c_str());
|
||||
return -1.0;
|
||||
}
|
||||
const json j = json::parse(tiny::read_text(o / "kld.json"), nullptr, false);
|
||||
return j.is_object() && j.contains("all") ? j["all"]["kld"]["mean"].get<double>() : -1.0;
|
||||
};
|
||||
const double base = score({}, {});
|
||||
fprintf(stderr, " the MXFP4 base against the merged checkpoint: mean KL %.3g\n", base);
|
||||
REQUIRE(base > 0.05);
|
||||
const std::vector<std::string> ad = { "--lora", "ad=" + adapter, "--kld-lora", "ad" };
|
||||
struct Arm { const char* what; std::vector<std::string> args, env; };
|
||||
std::vector<Arm> arms = { { "libref", ad, {} } };
|
||||
#if defined(__x86_64__)
|
||||
if (::access(RAD_E2E_HOME "/kernels/libavx.so", R_OK) == 0) {
|
||||
std::vector<std::string> avx = { "--kernels", "libavx" };
|
||||
avx.insert(avx.end(), ad.begin(), ad.end());
|
||||
arms.push_back({ "libavx", avx, {} });
|
||||
}
|
||||
#endif
|
||||
for (const Arm& a : arms) {
|
||||
const double kl = score(a.args, a.env);
|
||||
fprintf(stderr, " the MXFP4 container with the adapter, %s: mean KL %.3g\n", a.what, kl);
|
||||
CHECK(kl >= 0);
|
||||
CHECK(kl < base / 4);
|
||||
}
|
||||
}
|
||||
|
||||
/* Off is off: without --lora or --max-loras the declared graph names no adapter op, buffer or
|
||||
* declined GEMM, and with an adapter it is the same graph plus the adapter ops and their buffers
|
||||
* over the same weights. */
|
||||
TEST(runtime_lora_off_declares_no_adapter_op) {
|
||||
World& w = world();
|
||||
LoraWorld& L = lora_world();
|
||||
REQUIRE(L.ok);
|
||||
const Ran off = radiance(w.qwen35, { "--debug-graph" });
|
||||
const Ran on = radiance(w.qwen35, { "--debug-graph", "--lora", "ad=" + L.adapter });
|
||||
REQUIRE_RAN(off);
|
||||
REQUIRE_RAN(on);
|
||||
/* The adapter ops, their buffers (`lora.<weight>.a`, `lora.t.r16.lane0`) and a declined fused
|
||||
* GEMM's reason; a path may well contain "lora". */
|
||||
for (const char* needle : { "lora_shrink", "lora_expand", "lora.", "runtime-LoRA" }) {
|
||||
if (has(off.log, needle)) fprintf(stderr, " the default graph names '%s'\n", needle);
|
||||
CHECK(!has(off.log, needle));
|
||||
}
|
||||
auto counts = [](const std::string& log, long long* ops, long long* weights,
|
||||
long long* buffers) {
|
||||
const size_t at = log.find("declare: ");
|
||||
return at != std::string::npos &&
|
||||
std::sscanf(log.c_str() + at, "declare: %lld ops, %lld weights, %lld buffers", ops,
|
||||
weights, buffers) == 3;
|
||||
};
|
||||
long long o0 = 0, w0 = 0, b0 = 0, o1 = 0, w1 = 0, b1 = 0;
|
||||
REQUIRE(counts(off.log, &o0, &w0, &b0));
|
||||
REQUIRE(counts(on.log, &o1, &w1, &b1));
|
||||
CHECK_EQ(w1, w0);
|
||||
CHECK(o1 > o0 && (o1 - o0) % 2 == 0);
|
||||
CHECK(b1 > b0);
|
||||
CHECK(has(on.log, "lora_shrink"));
|
||||
}
|
||||
|
||||
/* Base rows are exact: documents run as the base with the adapter loaded are byte for byte what an
|
||||
* engine without adapters writes. Mixed steps are exact: with one document through the adapter
|
||||
* and the rest as the base, batched four at a time, every document's rows equal those of the run
|
||||
* that served all documents its way. */
|
||||
TEST(runtime_lora_base_rows_and_mixed_steps_are_exact) {
|
||||
World& w = world();
|
||||
LoraWorld& L = lora_world();
|
||||
REQUIRE(L.ok);
|
||||
tiny::TempDir d("e2e_lora_mix");
|
||||
auto record = [&](const char* name, const std::vector<std::string>& args) {
|
||||
std::vector<std::string> a = { "--kld-record", d / name, "--kld-corpus", w.corpus_short,
|
||||
"--max-num-batched-tokens", "512", "--max-num-seqs", "4" };
|
||||
a.insert(a.end(), args.begin(), args.end());
|
||||
const Ran r = radiance(w.qwen35, a);
|
||||
if (r.status != 0) fprintf(stderr, " %s exited %d:\n%s\n", name, r.status,
|
||||
tail(r.log).c_str());
|
||||
return r.status == 0;
|
||||
};
|
||||
const std::string lora = "ad=" + L.adapter;
|
||||
REQUIRE(record("off", {}));
|
||||
REQUIRE(record("base", { "--lora", lora }));
|
||||
REQUIRE(record("adapter", { "--lora", lora, "--kld-lora", "ad" }));
|
||||
REQUIRE(record("mixed", { "--lora", lora, "--kld-lora", "ad", "--kld-lora-sources", "d1" }));
|
||||
std::string why;
|
||||
const bool base_exact = same_recording(d / "off", d / "base", &why);
|
||||
if (!base_exact) fprintf(stderr, " base with the adapter loaded: %s\n", why.c_str());
|
||||
CHECK(base_exact);
|
||||
CHECK(!same_recording(d / "off", d / "adapter", &why));
|
||||
const bool mixed_exact = spliced_recording_matches(d / "mixed", d / "adapter", d / "off",
|
||||
"d1", &why);
|
||||
if (!mixed_exact) fprintf(stderr, " mixed steps: %s\n", why.c_str());
|
||||
CHECK(mixed_exact);
|
||||
}
|
||||
|
||||
/* What would serve an adapter that cannot land, or one no request could reach, is refused at
|
||||
* startup by name: a target module the trunk does not have (or has only as the vocabulary head),
|
||||
* and an adapter that has the served model's own name. */
|
||||
TEST(runtime_lora_refuses_targets_it_cannot_serve_at_startup) {
|
||||
World& w = world();
|
||||
LoraWorld& L = lora_world();
|
||||
REQUIRE(L.ok);
|
||||
tiny::TempDir d("e2e_lora_no");
|
||||
const std::string lora = "ad=" + L.adapter;
|
||||
const struct { const char* targets; const char* why; } kCases[] = {
|
||||
{ "q_proj,qq_proj", "the target module 'qq_proj' is no trunk linear" },
|
||||
{ "q_proj,lm_head", "the target module 'lm_head' is no trunk linear" },
|
||||
};
|
||||
int k = 0;
|
||||
for (const auto& c : kCases) {
|
||||
const Ran r = radiance(w.qwen35, { "--lora", lora, "--lora-target-modules", c.targets,
|
||||
"--kld-record", d / ("r" + std::to_string(k++)),
|
||||
"--kld-corpus", w.corpus_probe }, {}, 120);
|
||||
if (r.status == 0 || !has(r.log, c.why))
|
||||
fprintf(stderr, " %s: exited %d:\n%s\n", c.targets, r.status, tail(r.log).c_str());
|
||||
CHECK(r.status != 0);
|
||||
CHECK(has(r.log, c.why));
|
||||
}
|
||||
const Ran s = radiance(w.qwen35, { "--served-model-name", "ad", "--lora", lora,
|
||||
"--host", "127.0.0.1", "--port", "0" }, {}, 120);
|
||||
if (s.status == 0 || !has(s.log, "the served model's own name"))
|
||||
fprintf(stderr, " served as 'ad': exited %d:\n%s\n", s.status, tail(s.log).c_str());
|
||||
CHECK(s.status != 0);
|
||||
CHECK(has(s.log, "has the served model's own name"));
|
||||
}
|
||||
|
||||
/* ================================================================== against transformers */
|
||||
|
||||
/* Each family's forward pass against transformers' own, run in float32 over the same weights
|
||||
@@ -1115,6 +1403,39 @@ TEST(libavx_alone_serves_a_quantised_head_within_rounding_of_libref) {
|
||||
{ "--kernels", "libavx", "--max-num-batched-tokens", "512", "--max-num-seqs", "1" }));
|
||||
}
|
||||
|
||||
/* An int4 W4A16 release with zero points, imported, runs its linears on the 4-bit GEMMs: at or
|
||||
* below 64 rows a step the f16 one over its cast input, above that the int8 one over
|
||||
* quant_act_i8g's codes. libavx alone agrees with libref within rounding on each: the prefill in
|
||||
* 512-row steps, and in 64-row steps against libref's own run in 64-row steps. */
|
||||
TEST(libavx_alone_serves_an_int4_release_within_rounding_of_libref) {
|
||||
#if defined(__x86_64__)
|
||||
NEED_ARTIFACT(RAD_E2E_HOME "/kernels/libavx.so");
|
||||
#else
|
||||
SKIP("libavx is x86-64 only");
|
||||
#endif
|
||||
REQUIRE(world().ok);
|
||||
World& w = world();
|
||||
check_within_rounding("int4 llama on libavx alone, steps of 512",
|
||||
score_against_reference(w.llama_int4_rad, w.corpus_tiny,
|
||||
{ "--kernels", "libavx",
|
||||
"--max-num-batched-tokens", "512",
|
||||
"--max-num-seqs", "1" }));
|
||||
tiny::TempDir d("e2e_int4");
|
||||
const std::vector<std::string> step64 = { "--max-num-batched-tokens", "64",
|
||||
"--max-num-seqs", "1" };
|
||||
std::vector<std::string> rec = { "--kld-record", d / "ref64", "--kld-corpus", w.corpus_tiny };
|
||||
rec.insert(rec.end(), step64.begin(), step64.end());
|
||||
const Ran r_ref = radiance(w.llama_int4_rad, rec);
|
||||
REQUIRE_RAN(r_ref);
|
||||
std::vector<std::string> sc = { "--kernels", "libavx", "--kld-ref", d / "ref64",
|
||||
"--kld-out", d / "kld.json" };
|
||||
sc.insert(sc.end(), step64.begin(), step64.end());
|
||||
const Ran r_avx = radiance(w.llama_int4_rad, sc);
|
||||
REQUIRE_RAN(r_avx);
|
||||
check_within_rounding("int4 llama on libavx alone, steps of 64",
|
||||
json::parse(tiny::read_text(d / "kld.json"), nullptr, false));
|
||||
}
|
||||
|
||||
/* ================================================================== HTTP */
|
||||
|
||||
namespace {
|
||||
@@ -1294,6 +1615,72 @@ TEST(a_prompt_resumed_from_the_prefix_cache_returns_what_a_cold_run_does) {
|
||||
CHECK_EQ(s.stop(), 0);
|
||||
}
|
||||
|
||||
/* The row a running server's /diagnostics reports for `option`, or null. */
|
||||
json config_row(int port, const std::string& option) {
|
||||
Call c;
|
||||
std::string out;
|
||||
if (!c.send(port, "GET", "/diagnostics", "") || c.read(&out) != 200) return json();
|
||||
const json d = json::parse(out, nullptr, false);
|
||||
if (!d.is_object() || !d.contains("configuration")) return json();
|
||||
for (const json& r : d["configuration"])
|
||||
if (r.value("option", "") == option) return r;
|
||||
return json();
|
||||
}
|
||||
|
||||
/* --checkpoint-slots auto, the default, sizes the snapshot store from --max-num-seqs and what the
|
||||
* retention policy keeps for a --max-model-len session (the tiny hybrid's 4096 tokens are two
|
||||
* 2048-token intervals: 2 snapshots, 3 a sequence), says so on its startup line and reports the
|
||||
* count it chose with the reason. A count given on the command line is taken as it stands; a model
|
||||
* with nothing to snapshot, or a server without a prefix cache, resolves to none. */
|
||||
TEST(the_snapshot_store_is_sized_by_auto_unless_a_count_is_given) {
|
||||
REQUIRE(world().ok);
|
||||
const struct Case {
|
||||
std::string World::*model;
|
||||
std::vector<std::string> args;
|
||||
const char* value;
|
||||
const char* source;
|
||||
const char* why;
|
||||
const char* line;
|
||||
} kCases[] = {
|
||||
{ &World::qwen35, {}, "768", "auto", "3 a sequence for --max-num-seqs 256",
|
||||
"checkpoint slots: auto: 768 linear-state snapshot(s) of " },
|
||||
{ &World::qwen35, { "--max-num-seqs", "4" }, "12", "auto",
|
||||
"geometric-backoff keeps 2 for a 4096-token session at a 2048-token interval",
|
||||
"checkpoint slots: auto: 12 linear-state snapshot(s) of " },
|
||||
{ &World::qwen35, { "--max-num-seqs", "4", "--checkpoint-slots", "auto" }, "12",
|
||||
"command line", "3 a sequence", "checkpoint slots: auto: 12 " },
|
||||
{ &World::qwen35,
|
||||
{ "--max-num-seqs", "4", "--checkpoint-policy", "keep-all", "--checkpoint-interval", "256" },
|
||||
"68", "auto", "keep-all keeps 16 for a 4096-token session at a 256-token interval",
|
||||
"checkpoint slots: auto: 68 " },
|
||||
{ &World::qwen35, { "--max-num-seqs", "4", "--checkpoint-slots", "5" }, "5", "command line",
|
||||
"", "checkpoint slots: 5 linear-state snapshot(s) of " },
|
||||
{ &World::qwen35, { "--max-num-seqs", "4", "--no-prefix-cache" }, "0", "auto",
|
||||
"prefix caching is off", "" },
|
||||
{ &World::llama, { "--max-num-seqs", "4" }, "0", "auto",
|
||||
"the model keeps no linear or sliding-window state", "" },
|
||||
{ &World::lfm2, { "--max-num-seqs", "4" }, "12", "auto", "3 a sequence for --max-num-seqs 4",
|
||||
"checkpoint slots: auto: 12 linear-state snapshot(s) of 512 B " },
|
||||
};
|
||||
for (const Case& k : kCases) {
|
||||
Server s;
|
||||
REQUIRE(s.start(world().*k.model, k.args));
|
||||
const json row = config_row(s.port, "--checkpoint-slots");
|
||||
const std::string log = s.output();
|
||||
std::string args;
|
||||
for (const std::string& a : k.args) args += " " + a;
|
||||
const bool ok = row.is_object() && row.value("value", "") == k.value &&
|
||||
row.value("source", "") == k.source &&
|
||||
row.value("why", "").find(k.why) != std::string::npos &&
|
||||
has(log, k.line);
|
||||
if (!ok)
|
||||
fprintf(stderr, " %s:%s\n row %s\n%s\n", (world().*k.model).c_str(), args.c_str(),
|
||||
row.dump().c_str(), tail(log, 12).c_str());
|
||||
CHECK(ok);
|
||||
CHECK_EQ(s.stop(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* A snapshot store that cannot be had stops the start, naming --checkpoint-slots, the size and
|
||||
* what to change; served without it, every prefix hit on a hybrid model would prefill from the
|
||||
* start. The largest count the flag takes is more bytes than a 64-bit size says, whatever a slot's
|
||||
@@ -1468,6 +1855,7 @@ const QwenImageContainers& qwen_image() {
|
||||
/* One picture through the images API, and its pixels. */
|
||||
struct Picture {
|
||||
int status = -1;
|
||||
std::string why;
|
||||
std::string png;
|
||||
std::vector<uint8_t> rgba;
|
||||
std::string log;
|
||||
@@ -1495,7 +1883,7 @@ Picture generate(const std::string& model, const std::vector<std::string>& kerne
|
||||
req["negative_prompt"] = "a dark river";
|
||||
req["true_cfg_scale"] = cfg;
|
||||
}
|
||||
const json r = post(s.port, "/v1/images/generations", req, &p.status);
|
||||
const json r = post(s.port, "/v1/images/generations", req, &p.status, &p.why);
|
||||
if (p.status == 200 && r.is_object() && r.contains("data") && r["data"].size() == 1) {
|
||||
std::vector<uint8_t> bytes;
|
||||
if (rad::server::base64_decode(r["data"][0].value("b64_json", std::string()), &bytes)) {
|
||||
@@ -1510,8 +1898,8 @@ Picture generate(const std::string& model, const std::vector<std::string>& kerne
|
||||
s.stop();
|
||||
p.log = s.output();
|
||||
if (p.status != 200 || p.rgba.empty())
|
||||
fprintf(stderr, " %s: status %d, %zu pixel bytes:\n%s\n", ks.c_str(), p.status,
|
||||
p.rgba.size(), tail(p.log, 20).c_str());
|
||||
fprintf(stderr, " %s: status %d%s%s, %zu pixel bytes:\n%s\n", ks.c_str(), p.status,
|
||||
p.why.empty() ? "" : " -- ", p.why.c_str(), p.rgba.size(), tail(p.log, 20).c_str());
|
||||
return p;
|
||||
}
|
||||
|
||||
|
||||
@@ -619,7 +619,9 @@ TEST(device_rows_are_timed_after_the_checks_and_host_rows_where_checked) {
|
||||
/* An in-place operand is restored from its pristine copy before every timed launch. The host
|
||||
* scatter refuses to write a row that already holds its value, so a second launch on an
|
||||
* unrestored operand would fail its timing; the device scatter's restores are timed and
|
||||
* subtracted, and their share named. */
|
||||
* subtracted, and their share named. On the host backend that kernel is a few row writes, no
|
||||
* longer than its restores, and on a loaded machine the restores' own batch can come out longer
|
||||
* than the timed one: the row is then reported restore-dominated, without a time or a share. */
|
||||
TEST(an_in_place_operand_is_restored_before_every_timed_launch) {
|
||||
REQUIRE(env().ok);
|
||||
Registry reg;
|
||||
@@ -646,8 +648,10 @@ TEST(an_in_place_operand_is_restored_before_every_timed_launch) {
|
||||
CHECK(!has(host[13], "failed"));
|
||||
const std::vector<std::string> dev = speed_row(md, "kbm_scatter_rows_device");
|
||||
REQUIRE(dev.size() >= 14);
|
||||
CHECK(num(dev[9]) >= 1);
|
||||
CHECK(has(dev[13], "restore "));
|
||||
if (!has(dev[13], "restore-dominated")) {
|
||||
CHECK(num(dev[9]) >= 1);
|
||||
CHECK(has(dev[13], "restore "));
|
||||
}
|
||||
}
|
||||
|
||||
/* --bench-flush 0 times warm: no rotation, and no read probe, which exists to check cold
|
||||
|
||||
+175
-61
@@ -1,23 +1,23 @@
|
||||
/* lora_test.cpp -- core/lora: sites from the declared Program, a PEFT adapter packed per rank, and
|
||||
* the adapter slots' bookkeeping (slots.h).
|
||||
/* lora_test.cpp -- core/lora: sites from the declared Program, a PEFT adapter packed per rank,
|
||||
* declare's refusals, and the adapter slots' bookkeeping (slots.h).
|
||||
*
|
||||
* HOST ONLY, AND IT NEVER REACHES THE DEVICE LAYER. No kernel plugin is loaded: a Registry that
|
||||
* loads one brackets the dlopen with the device backend's code mark, which in a HIP build starts the
|
||||
* AQL backend. The Programs here are made by the REAL core Builder, over an empty Registry, driven
|
||||
* by the REAL arch/common code that declares the weights -- LinearFP8::declare (rad_fp8.h) with the
|
||||
* Host only, and it never reaches the device layer: no kernel plugin is loaded, because a Registry
|
||||
* that loads one brackets the dlopen with the device backend's code mark, which in a HIP build
|
||||
* starts the AQL backend. The Programs are made by the core Builder over an empty Registry, driven
|
||||
* by the arch/common code that declares the weights: LinearFP8::declare (rad_fp8.h) with the
|
||||
* arguments the blocks pass (rad_block_attn_fp8.h, rad_block_mlp_fp8.h, rad_block_attn_gated_fp8.h,
|
||||
* rad_block_gdn_fp8.h), over a Geom from the real geom_from(), and the delta net's uneven head split
|
||||
* as qwen4exp_fp8.cpp computes it (remainder_place). With no schema in the Registry the GEMM ops
|
||||
* themselves do not resolve, so each is appended to the Program as decl_op would record it (op name,
|
||||
* parameters, weights, schema operand positions). Everything a LoRA site is read from -- the
|
||||
* WeightInfo, its row parts and spans, the name map -- is exactly what the builder records.
|
||||
* rad_block_gdn_fp8.h), over a Geom from geom_from(), and the delta net's uneven head split as
|
||||
* qwen4exp_fp8.cpp computes it (remainder_place). With no schema in the Registry the GEMM ops do
|
||||
* not resolve, so each is appended to the Program as decl_op would record it (op name, parameters,
|
||||
* weights, schema operand positions); everything a site is read from is what the builder records.
|
||||
*
|
||||
* The dense reference is the test's own: the full delta scale * B @ A of every module, placed by
|
||||
* MODEL SEMANTICS (which heads / which ff columns a rank owns), not by anything lora.cpp computes.
|
||||
* model semantics (which heads and ff columns a rank owns), not by anything lora.cpp computes.
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "build/rad_build.h"
|
||||
#include "lora/declare.h"
|
||||
#include "lora/lora.h"
|
||||
#include "lora/slots.h"
|
||||
#include "plugin/registry.h"
|
||||
@@ -33,12 +33,13 @@
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <atomic>
|
||||
#include <filesystem>
|
||||
#include <chrono>
|
||||
#include <fstream>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
@@ -55,19 +56,9 @@ Registry& empty_registry() {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ temp dirs */
|
||||
std::string g_tmp;
|
||||
std::string tmp_root() {
|
||||
if (g_tmp.empty()) {
|
||||
const char* t = std::getenv("TMPDIR");
|
||||
std::string tpl = std::string(t && *t ? t : "/tmp") + "/lora_test.XXXXXX";
|
||||
std::vector<char> buf(tpl.begin(), tpl.end());
|
||||
buf.push_back(0);
|
||||
if (mkdtemp(buf.data())) g_tmp = buf.data();
|
||||
}
|
||||
return g_tmp;
|
||||
}
|
||||
/* Under the harness's directory (radtest::tmpdir), which it removes when the binary passes. */
|
||||
std::string new_dir(const std::string& name) {
|
||||
const std::string d = tmp_root() + "/" + name;
|
||||
const std::string d = radtest::tmp_path(name);
|
||||
mkdir(d.c_str(), 0755);
|
||||
return d;
|
||||
}
|
||||
@@ -267,28 +258,28 @@ int build_llama(int rank, int world, RankProg* out) {
|
||||
const RadModelMeta meta = llama_meta();
|
||||
const RadBuildCtx ctx = ctx_for(rank, world);
|
||||
AR::Geom g{};
|
||||
RAD_ARCH_TRY(AR::geom_from(g, &meta, &ctx, "bf16", RAD_BF16)); /* llama_fp8.cpp:414 */
|
||||
RAD_ARCH_TRY(AR::geom_from(g, &meta, &ctx, "bf16", RAD_BF16)); /* llama_fp8.cpp */
|
||||
Builder b(empty_registry(), meta, ctx);
|
||||
AR::Names nm("");
|
||||
const char* pre = "model.layers"; /* llama_fp8.cpp:567 */
|
||||
const char* pre = "model.layers"; /* llama_fp8.cpp */
|
||||
const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim();
|
||||
const int64_t q_all = g.n_head_all * g.head_dim, kv_all = g.n_head_kv_all * g.head_dim;
|
||||
for (int l = 0; l < (int)meta.n_layers; ++l) {
|
||||
auto ck = [&](const char* leaf) { return nm.ckpt("%s.%d.%s.weight", pre, l, leaf); };
|
||||
/* rad_block_attn_fp8.h:120-122 */
|
||||
/* rad_block_attn_fp8.h */
|
||||
RAD_ARCH_TRY(linear(b, nm, g, nm.f("blk.%d.attn_qkv", l), q_dim + 2 * kv_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, l, { ck("self_attn.q_proj"), ck("self_attn.k_proj"),
|
||||
ck("self_attn.v_proj") },
|
||||
{ q_dim, kv_dim, kv_dim }));
|
||||
/* rad_block_attn_fp8.h:175-176 */
|
||||
/* rad_block_attn_fp8.h */
|
||||
RAD_ARCH_TRY(linear(b, nm, g, nm.f("blk.%d.attn_output", l), g.n_embd, q_dim,
|
||||
RAD_SHARD_COL, l, { ck("self_attn.o_proj") }));
|
||||
/* rad_block_mlp_fp8.h:115-117 */
|
||||
/* rad_block_mlp_fp8.h */
|
||||
AR::LinearFP8 gu{};
|
||||
RAD_ARCH_TRY(linear(b, nm, g, nm.f("blk.%d.ffn_gate_up", l), 2 * g.n_ff, g.n_embd,
|
||||
RAD_SHARD_ROW, l, { ck("mlp.gate_proj"), ck("mlp.up_proj") },
|
||||
{ g.n_ff, g.n_ff }, 0, 0, {}, &gu));
|
||||
/* rad_block_mlp_fp8.h:144-146 */
|
||||
/* rad_block_mlp_fp8.h */
|
||||
RAD_ARCH_TRY(linear(b, nm, g, nm.f("blk.%d.ffn_down", l), g.n_embd, g.n_ff, RAD_SHARD_COL,
|
||||
l, { ck("mlp.down_proj") }));
|
||||
|
||||
@@ -344,7 +335,7 @@ RadModelMeta hybrid_meta() {
|
||||
}
|
||||
|
||||
struct GdnSplit { int64_t nk, kf, nv, vf; bool uneven; };
|
||||
/* qwen4exp_fp8.cpp:419-444, verbatim in substance. */
|
||||
/* qwen4exp_fp8.cpp, verbatim in substance. */
|
||||
GdnSplit gdn_split(const AR::Geom& g) {
|
||||
GdnSplit s{ kNK, 0, kNV, 0, false };
|
||||
if (g.world > 1 && (kNK % g.world != 0 || kNV % g.world != 0)) {
|
||||
@@ -366,7 +357,7 @@ int build_hybrid(int rank, int world, RankProg* out, bool m1_on_inz = true) {
|
||||
const RadModelMeta meta = hybrid_meta();
|
||||
const RadBuildCtx ctx = ctx_for(rank, world);
|
||||
AR::Geom g{};
|
||||
/* qwen4exp_fp8.cpp:326 */
|
||||
/* qwen4exp_fp8.cpp */
|
||||
RAD_ARCH_TRY(AR::geom_from(g, &meta, &ctx, "bf16", RAD_BF16, true, true));
|
||||
Builder b(empty_registry(), meta, ctx);
|
||||
AR::Names nm("");
|
||||
@@ -375,7 +366,7 @@ int build_hybrid(int rank, int world, RankProg* out, bool m1_on_inz = true) {
|
||||
const GdnSplit sp = gdn_split(g);
|
||||
const int64_t k_dim = sp.nk * kHK, v_dim = sp.nv * kHV, k_all = kNK * kHK, v_all = kNV * kHV;
|
||||
|
||||
/* ---- layer 0: the gated delta net (rad_block_gdn_fp8.h:231-242, 276-299, 318-321, 405-408) */
|
||||
/* ---- layer 0: the gated delta net (rad_block_gdn_fp8.h) */
|
||||
{
|
||||
const int l = 0;
|
||||
auto ck = [&](const char* leaf) { return nm.ckpt("%s.%d.%s.weight", pre, l, leaf); };
|
||||
@@ -437,7 +428,7 @@ int build_hybrid(int rank, int world, RankProg* out, bool m1_on_inz = true) {
|
||||
out->truth["blk.0.ssm_out.weight"] = so;
|
||||
}
|
||||
|
||||
/* ---- layer 1: gated attention (rad_block_attn_gated_fp8.h:189-213, 270-278, 453-455) */
|
||||
/* ---- layer 1: gated attention (rad_block_attn_gated_fp8.h) */
|
||||
{
|
||||
const int l = 1;
|
||||
auto ck = [&](const char* leaf) { return nm.ckpt("%s.%d.%s.weight", pre, l, leaf); };
|
||||
@@ -461,7 +452,7 @@ int build_hybrid(int rank, int world, RankProg* out, bool m1_on_inz = true) {
|
||||
RAD_ARCH_TRY(linear(b, nm, g, nm.f("blk.%d.attn_output", l), g.n_embd, q_dim,
|
||||
RAD_SHARD_COL, l, { ck("self_attn.o_proj") }, {}, o_lo, o_hi));
|
||||
}
|
||||
/* MODEL SEMANTICS: this rank's query heads, and the KV head(s) those heads read. */
|
||||
/* Model semantics: this rank's query heads, and the KV head(s) those heads read. */
|
||||
const int ar = g.attn_rank;
|
||||
const int64_t qh0 = ar * g.n_head, group = g.n_head_all / g.n_head_kv_all;
|
||||
const int64_t kvh0 = qh0 / group;
|
||||
@@ -487,7 +478,7 @@ int build_hybrid(int rank, int world, RankProg* out, bool m1_on_inz = true) {
|
||||
out->truth["blk.1.attn_output.weight"] = o;
|
||||
}
|
||||
|
||||
/* ---- the dense MLP of both layers (rad_block_mlp_fp8.h:115-146) */
|
||||
/* ---- the dense MLP of both layers (rad_block_mlp_fp8.h) */
|
||||
for (int l = 0; l < 2; ++l) {
|
||||
auto ck = [&](const char* leaf) { return nm.ckpt("%s.%d.%s.weight", pre, l, leaf); };
|
||||
RAD_ARCH_TRY(linear(b, nm, g, nm.f("blk.%d.ffn_gate_up", l), 2 * g.n_ff, g.n_embd,
|
||||
@@ -690,7 +681,7 @@ void check_world(const char* label, int world,
|
||||
Adapter llama_adapter() {
|
||||
Adapter ad;
|
||||
uint32_t seed = 10;
|
||||
/* k_proj is NOT targeted: the fused qkv's middle source stays base-only. */
|
||||
/* k_proj is not targeted: the fused qkv's middle source stays base-only. */
|
||||
for (int l = 0; l < 2; ++l) {
|
||||
const std::string P = "model.layers." + std::to_string(l) + ".";
|
||||
ModSpec q{ P + "self_attn.q_proj", 16, 1536, 256, "F32", "BF16", seed++, false, 1.0f };
|
||||
@@ -945,7 +936,7 @@ TEST(non_capable_consumers_are_reported_never_skipped) {
|
||||
REQUIRE_EQ(linear(b, nm, g, "blk.0.ffn_gate_up", 2 * g.n_ff, g.n_embd, RAD_SHARD_ROW, 0,
|
||||
{ "model.layers.0.mlp.gate_proj.weight", "model.layers.0.mlp.up_proj.weight" },
|
||||
{ g.n_ff, g.n_ff }, 0, 0, {}, &gu), RAD_OK);
|
||||
/* the fused gated fold over the same views (rad_block_mlp_fp8.h:132-140): live -> reported */
|
||||
/* the fused gated fold over the same views (rad_block_mlp_fp8.h): live -> reported */
|
||||
OpInfo gated;
|
||||
gated.op = "gemm_nt_q_gated";
|
||||
gated.base.set_i("N", gu.N); gated.base.set_i("K", gu.K); gated.base.set_s("act", "silu");
|
||||
@@ -959,7 +950,7 @@ TEST(non_capable_consumers_are_reported_never_skipped) {
|
||||
CHECK_EQ(un[0].weight, std::string("blk.0.ffn_gate_up.weight"));
|
||||
CHECK(has(un[0].module, "model.layers.0.mlp.gate_proj"));
|
||||
CHECK_EQ(lora::find_unsupported_uses(b.program(), { "down_proj" }, nullptr), 0);
|
||||
/* ...and the same op left UNRESOLVED (the builder's fallback: it is recorded, never issued) */
|
||||
/* ...and the same op left unresolved (the builder's fallback: recorded, never issued) */
|
||||
Band dead;
|
||||
b.program().ops[gi].bands.push_back(dead);
|
||||
CHECK_EQ(lora::find_unsupported_uses(b.program(), t, nullptr), 0);
|
||||
@@ -967,7 +958,6 @@ TEST(non_capable_consumers_are_reported_never_skipped) {
|
||||
std::string err;
|
||||
REQUIRE_EQ(lora::build_sites(b.program(), t, 16, &s, &err), RAD_OK);
|
||||
CHECK_EQ(s.size(), (size_t)1);
|
||||
CHECK(lora::all_capable_targets(b.program()).count("gate_proj") == 1);
|
||||
|
||||
/* a routed expert (moe_gemm_q over a stacked slice): targeted, so reported */
|
||||
RadNameMap ex = AR::map_base("blk.0.ffn_gate_up_exps.3.weight", RAD_MAP_CONCAT);
|
||||
@@ -987,7 +977,6 @@ TEST(non_capable_consumers_are_reported_never_skipped) {
|
||||
un.clear();
|
||||
REQUIRE_EQ(lora::find_unsupported_uses(b.program(), t, &un), 1);
|
||||
CHECK_EQ(un[0].op, std::string("moe_gemm_q"));
|
||||
CHECK(lora::all_capable_targets(b.program()).count("gate_proj") == 0);
|
||||
}
|
||||
|
||||
TEST(a_transformed_or_rotated_weight_is_not_a_site) {
|
||||
@@ -1014,7 +1003,8 @@ TEST(a_transformed_or_rotated_weight_is_not_a_site) {
|
||||
const rad_weight wk = decl("blk.0.attn_k.weight", "model.layers.0.self_attn.k_proj.weight");
|
||||
const rad_weight wv = decl("blk.0.attn_v.weight", "model.layers.0.self_attn.v_proj.weight");
|
||||
const rad_weight wo = decl("blk.0.attn_o.weight", "model.layers.0.self_attn.o_proj.weight");
|
||||
REQUIRE(wq && wk && wv && wo);
|
||||
const rad_weight wu = decl("blk.0.ffn_up.weight", "model.layers.0.mlp.up_proj.weight");
|
||||
REQUIRE(wq && wk && wv && wo && wu);
|
||||
REQUIRE(b.program().weights[wq].enc_known);
|
||||
push_op(b, gemm_op("gemm_nt", 128, 256, "bf16", 1, 64, { wq }, { 1 }, false));
|
||||
OpInfo parts = gemm_op("gemm_nt_q", 128, 256, "mxfp4a8", 1, 64, { wk, wk }, { 2, 3 }, true);
|
||||
@@ -1024,15 +1014,17 @@ TEST(a_transformed_or_rotated_weight_is_not_a_site) {
|
||||
OpInfo act = gemm_op("gemm_nt_bias", 128, 256, "bf16", 1, 64, { wo, wo }, { 1, 2 }, false);
|
||||
act.base.set_s("act", "gelu");
|
||||
push_op(b, act);
|
||||
const lora::TargetSet t{ "q_proj", "k_proj", "v_proj", "o_proj" };
|
||||
push_op(b, gemm_op("gemm_nt_q", 128, 256, "w4a8", 1, 64, { wu, wu }, { 2, 3 }, true));
|
||||
const lora::TargetSet t{ "q_proj", "k_proj", "v_proj", "o_proj", "up_proj" };
|
||||
std::vector<lora::UnsupportedUse> un;
|
||||
REQUIRE_EQ(lora::find_unsupported_uses(b.program(), t, &un), 4);
|
||||
REQUIRE_EQ(lora::find_unsupported_uses(b.program(), t, &un), 5);
|
||||
CHECK(has(un[0].why, "perm"));
|
||||
CHECK_EQ(un[0].weight, std::string("blk.0.attn_q.weight"));
|
||||
CHECK(has(un[0].module, "q_proj"));
|
||||
CHECK(has(un[1].why, "pb1"));
|
||||
CHECK(has(un[2].why, "K=512"));
|
||||
CHECK(has(un[3].why, "act=gelu"));
|
||||
CHECK(has(un[4].why, "step order"));
|
||||
std::vector<lora::Site> s;
|
||||
std::string err;
|
||||
REQUIRE_EQ(lora::build_sites(b.program(), t, 16, &s, &err), RAD_OK);
|
||||
@@ -1040,6 +1032,36 @@ TEST(a_transformed_or_rotated_weight_is_not_a_site) {
|
||||
CHECK(has(lora::explain_module(b.program(), t, "model.layers.0.self_attn.q_proj"), "perm"));
|
||||
}
|
||||
|
||||
/* Adapters serve the token steps of a model that writes logits: declare refuses a generator, an
|
||||
* embedding model and a program with no logits by name, and lets a text model through. */
|
||||
TEST(declare_refuses_a_model_that_does_not_generate_text) {
|
||||
const RadModelMeta meta = llama_meta();
|
||||
const RadBuildCtx ctx = ctx_for(0, 1);
|
||||
LoraConfig cfg;
|
||||
cfg.max_loras = 1;
|
||||
cfg.targets = { "q_proj" };
|
||||
LoraDeclare d;
|
||||
d.cfg = &cfg;
|
||||
d.targets = { "q_proj" };
|
||||
const struct { const char* what; void (*set)(Program&); } kinds[] = {
|
||||
{ "is an image, audio or video generator",
|
||||
[](Program& p) { p.logits_buf = 1; p.generator.layout = 1; } },
|
||||
{ "makes embeddings", [](Program& p) { p.pooled_buf = 1; } },
|
||||
{ "declares no logits", [](Program&) {} },
|
||||
};
|
||||
for (const auto& k : kinds) {
|
||||
Builder b(empty_registry(), meta, ctx);
|
||||
k.set(b.program());
|
||||
int st = RAD_OK;
|
||||
const std::string log = stderr_of([&] { st = lora_declare(b, d); });
|
||||
CHECK_EQ(st, (int)RAD_E_UNSUPPORTED);
|
||||
CHECK(has(log, k.what));
|
||||
}
|
||||
Builder text(empty_registry(), meta, ctx);
|
||||
text.program().logits_buf = 1;
|
||||
CHECK_OK(lora_declare(text, d));
|
||||
}
|
||||
|
||||
/* ================================================================== load refusals */
|
||||
TEST(load_refusals_name_module_expected_and_found) {
|
||||
RankProg rp;
|
||||
@@ -1067,6 +1089,26 @@ TEST(load_refusals_name_module_expected_and_found) {
|
||||
expect_refusal(one("fifo", c, { good }), sites, 16, "fan_in_fan_out"); }
|
||||
{ ojson c = ok; c["alpha_pattern"] = { { "(?P<x>q_proj)", 4 } };
|
||||
expect_refusal(one("regex", c, { good }), sites, 16, "(?P<x>q_proj)"); }
|
||||
{ ojson c = ok; c["lora_alpha"] = 1e300;
|
||||
expect_refusal(one("alpha", c, { good }), sites, 16, "no finite f32 scale"); }
|
||||
{ ojson c = ok; c["rank_pattern"] = { { "q_proj", (int64_t)1 << 40 } };
|
||||
expect_refusal(one("bigrank", c, { good }), sites, 16, "rank_pattern[q_proj]"); }
|
||||
{ ojson c = ok; c["lora_bias"] = true;
|
||||
expect_refusal(one("lbias", c, { good }), sites, 16, "lora_bias"); }
|
||||
{ ojson c = ok; c["target_parameters"] = { "experts.gate_up_proj" };
|
||||
expect_refusal(one("tparams", c, { good }), sites, 16, "target_parameters"); }
|
||||
{ ojson c = ok; c["trainable_token_indices"] = { 1, 2 };
|
||||
expect_refusal(one("ttok", c, { good }), sites, 16, "trainable_token_indices"); }
|
||||
{ ojson c = ok; c["layer_replication"] = { { 0, 2 }, { 1, 2 } };
|
||||
expect_refusal(one("lrep", c, { good }), sites, 16, "layer_replication"); }
|
||||
{ ojson c = ok; c["use_qalora"] = true;
|
||||
expect_refusal(one("qalora", c, { good }), sites, 16, "use_qalora"); }
|
||||
{ ojson c = ok; c["alora_invocation_tokens"] = { 7, 8 };
|
||||
expect_refusal(one("alora", c, { good }), sites, 16, "alora_invocation_tokens"); }
|
||||
{ ojson c = ok; c["use_qalora"] = false; c["layer_replication"] = nullptr;
|
||||
Adapter ad; ad.mods = { good }; write_adapter(&ad, "plainopts", c);
|
||||
lora::AdapterInfo info; std::vector<lora::PackedSite> packed; std::string e;
|
||||
CHECK_OK(lora::load_adapter(ad.dir, sites, 16, &info, &packed, &e)); }
|
||||
/* tensors that are not linear LoRA pairs */
|
||||
{
|
||||
Adapter ad;
|
||||
@@ -1195,16 +1237,6 @@ TEST(adapter_info_and_scales) {
|
||||
CHECK_EQ(m.scale, s.scale);
|
||||
CHECK(m.pool >= 0);
|
||||
}
|
||||
/* the hash is the content's: same bytes in another directory, same hash */
|
||||
lora::AdapterInfo again;
|
||||
const std::string copy = new_dir("llama_copy");
|
||||
for (const char* f : { "/adapter_config.json", "/adapter_model.safetensors" }) {
|
||||
std::ifstream i(ad.dir + f, std::ios::binary);
|
||||
std::ofstream o(copy + f, std::ios::binary);
|
||||
o << i.rdbuf();
|
||||
}
|
||||
REQUIRE_EQ(lora::load_adapter(copy, sites, 16, &again, &packed, &err), RAD_OK);
|
||||
CHECK_EQ(again.content_hash, info.content_hash);
|
||||
/* rsLoRA: alpha / sqrt(r) */
|
||||
Adapter rs;
|
||||
rs.mods = { { "model.layers.0.self_attn.q_proj", 16, 1536, 256, "BF16", "BF16", 4, false, 4.f } };
|
||||
@@ -1215,7 +1247,44 @@ TEST(adapter_info_and_scales) {
|
||||
REQUIRE_EQ(lora::load_adapter(rs.dir, sites, 16, &ri, &packed, &err), RAD_OK);
|
||||
REQUIRE_EQ(ri.modules.size(), (size_t)1);
|
||||
CHECK_EQ(ri.modules[0].scale, 4.0f);
|
||||
CHECK(ri.content_hash != info.content_hash);
|
||||
}
|
||||
|
||||
/* rank_pattern and alpha_pattern keys match as PEFT's get_pattern_key does: the end of the
|
||||
* module's name on a dot boundary, the first matching key in the file winning. A key found only
|
||||
* inside the name, or not on a dot boundary, leaves the module at r and lora_alpha. */
|
||||
TEST(pattern_keys_match_the_end_of_the_module_name_as_peft_does) {
|
||||
RankProg rp;
|
||||
const std::vector<lora::Site> sites = llama_sites(0, 1, kLlamaTargets, &rp);
|
||||
const std::string q = "model.layers.0.self_attn.q_proj";
|
||||
const struct { const char* key; double alpha; float scale; } kCases[] = {
|
||||
{ "self_attn", 64.0, 2.0f },
|
||||
{ "_proj", 64.0, 2.0f },
|
||||
{ "q_proj", 64.0, 8.0f },
|
||||
{ "layers.0.self_attn.q_proj", 64.0, 8.0f },
|
||||
{ "layers.1.self_attn.q_proj", 64.0, 2.0f },
|
||||
{ "model.layers.0.self_attn.q_proj", 64.0, 8.0f },
|
||||
{ "k_proj|q_proj", 32.0, 4.0f },
|
||||
};
|
||||
int i = 0;
|
||||
for (const auto& c : kCases) {
|
||||
Adapter ad;
|
||||
ad.mods = { { q, 8, 1536, 256, "BF16", "BF16", 1, false, c.scale } };
|
||||
ojson cfg = base_cfg(8, 16.0, { "q_proj" });
|
||||
cfg["alpha_pattern"] = ojson::object();
|
||||
cfg["alpha_pattern"][c.key] = c.alpha;
|
||||
cfg["alpha_pattern"]["0.self_attn.q_proj"] = 128.0; /* matches too, but comes second */
|
||||
write_adapter(&ad, "pattern" + std::to_string(i++), cfg);
|
||||
lora::AdapterInfo info;
|
||||
std::vector<lora::PackedSite> packed;
|
||||
std::string err;
|
||||
REQUIRE_EQ(lora::load_adapter(ad.dir, sites, 16, &info, &packed, &err), RAD_OK);
|
||||
REQUIRE_EQ(info.modules.size(), (size_t)1);
|
||||
const float want = c.scale == 2.0f ? 16.0f : c.scale; /* no match: the second key's */
|
||||
if (info.modules[0].scale != want)
|
||||
fprintf(stderr, " alpha_pattern key '%s': scale %g, PEFT's %g\n", c.key,
|
||||
info.modules[0].scale, want);
|
||||
CHECK_EQ(info.modules[0].scale, want);
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== the slot table
|
||||
@@ -1303,12 +1372,57 @@ TEST(an_adapter_in_use_drains_and_its_last_request_frees_it) {
|
||||
CHECK(t.publish(slot, "a", "/a2") != u);
|
||||
}
|
||||
|
||||
TEST(zz_remove_the_temporary_adapters) {
|
||||
if (!g_tmp.empty()) {
|
||||
std::error_code ec;
|
||||
std::filesystem::remove_all(g_tmp, ec);
|
||||
CHECK(!ec);
|
||||
/* Requests take and drop holds on several threads while the adapter is unloaded and loaded again
|
||||
* in a loop: a load is never handed a slot a live hold still names, and a request only ever gets
|
||||
* the slot of a published adapter. The loop starts once the users hold the adapter and runs until
|
||||
* they have taken thousands of holds during it, at most 30 s: on a loaded machine its 3000 rounds
|
||||
* alone can end before a user thread is first scheduled. */
|
||||
TEST(a_slot_is_never_reloaded_under_a_live_hold) {
|
||||
std::atomic<uint64_t> epoch{0};
|
||||
lora::SlotTable t;
|
||||
t.reset(2, &epoch);
|
||||
int slot = -1;
|
||||
bool cooling = false;
|
||||
std::string err;
|
||||
REQUIRE_EQ(t.reserve("a", &slot, &cooling, &err), RAD_OK);
|
||||
t.publish(slot, "a", "/a");
|
||||
std::atomic<int> live[2] = { 0, 0 };
|
||||
std::atomic<bool> stop{ false };
|
||||
std::atomic<long> holds{ 0 };
|
||||
std::vector<std::thread> users;
|
||||
for (int i = 0; i < 4; ++i)
|
||||
users.emplace_back([&] {
|
||||
while (!stop.load()) {
|
||||
int32_t s = -1;
|
||||
uint64_t u = 0;
|
||||
std::shared_ptr<void> h;
|
||||
if (t.acquire("a", &s, &u, &h) != RAD_OK) { std::this_thread::yield(); continue; }
|
||||
++live[s];
|
||||
++holds;
|
||||
std::this_thread::yield();
|
||||
--live[s];
|
||||
h.reset();
|
||||
}
|
||||
});
|
||||
while (holds.load() == 0) std::this_thread::yield();
|
||||
const long before = holds.load();
|
||||
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30);
|
||||
int bad = 0, loads = 0;
|
||||
for (int round = 0; round < 3000 || (holds.load() - before < 3000 &&
|
||||
std::chrono::steady_clock::now() < deadline); ++round) {
|
||||
int n = 0;
|
||||
(void)t.unload("a", &n, &err);
|
||||
epoch += lora::kSlotCoolRounds;
|
||||
if (t.reserve("a", &slot, &cooling, &err) != RAD_OK) continue; /* still draining */
|
||||
if (live[slot].load() != 0) ++bad;
|
||||
t.publish(slot, "a", "/a");
|
||||
++loads;
|
||||
}
|
||||
stop.store(true);
|
||||
for (std::thread& u : users) u.join();
|
||||
CHECK_EQ(bad, 0);
|
||||
CHECK(loads > 0);
|
||||
CHECK(holds.load() > before);
|
||||
}
|
||||
|
||||
TEST(nothing_here_touches_a_device) {
|
||||
|
||||
+426
-3
@@ -1866,10 +1866,10 @@ static std::vector<RewriteTurn> rewrite_conversation(Fixture& f, int turns, int6
|
||||
RewriteTurn rt;
|
||||
rt.prompt = (int64_t)prompt.size();
|
||||
rt.diverge = (int64_t)hist.size();
|
||||
f.pc.begin_step();
|
||||
rt.resumed = f.pc.lookup(prompt, {}).n_linear_tokens;
|
||||
|
||||
const uint64_t id = (uint64_t)t + 1;
|
||||
f.pc.begin_step();
|
||||
rt.resumed = f.pc.lookup(prompt, {}, nullptr, nullptr, id).n_linear_tokens;
|
||||
|
||||
std::vector<int32_t> published = prompt;
|
||||
for (int64_t i = 0; i < grow / 2; ++i) published.push_back(fresh++); /* the reply */
|
||||
const std::vector<BlockHash> hs = chain_of(published);
|
||||
@@ -1927,6 +1927,397 @@ TEST(a_rewritten_last_message_keeps_its_anchor_over_the_tips_it_leaves) {
|
||||
check_rewrites_resume(turns, 256);
|
||||
}
|
||||
|
||||
/* ================================================================== agent sessions sharing the store
|
||||
*
|
||||
* Several agent conversations at once, as a coding client with subagents drives the server. Every
|
||||
* conversation starts from one system prompt. A parent grows turn by turn: a turn sends the whole
|
||||
* history plus a new message and publishes it with the reply. Every few turns a parent hands a
|
||||
* task to a subagent and waits for it: a short conversation from the same system prompt that runs
|
||||
* a few turns of its own. The conversations that are not waiting take their turns together: every
|
||||
* lookup first, then the checkpoints chunk by chunk across them, one step each, then the
|
||||
* publishes. Checkpoints go where Scheduler::plan_chunk puts them: every interval past the resume
|
||||
* point and the prompt's tail. Lookups name the request, as PCBinding does.
|
||||
*
|
||||
* Scaled from the shipped geometry: the 64-token interval stands for 2048, so a parent that stops
|
||||
* at 6272 tokens stands for a 200K-token conversation. */
|
||||
struct AgentLoad {
|
||||
int parents = 4;
|
||||
int64_t system = 384; /* the system prompt every conversation starts with */
|
||||
int64_t parent_len = 6272; /* a parent stops growing here */
|
||||
int64_t grow_lo = 32, grow_hi = 192; /* tokens a turn adds: the reply and the next message */
|
||||
int sub_every = 4; /* parent turns between subagents */
|
||||
int sub_turns = 5; /* turns a subagent runs */
|
||||
int64_t task = 64; /* the subagent's first message */
|
||||
bool rewrite = false; /* a parent's next turn drops the message this turn
|
||||
answered, as a client that rewrites it does */
|
||||
};
|
||||
|
||||
enum AgentTurn { kParent, kParentAfterSub, kSubFirst, kSubLater };
|
||||
|
||||
struct AgentTally {
|
||||
int64_t turns = 0;
|
||||
int64_t prompt = 0; /* prompt tokens sent */
|
||||
int64_t computed = 0; /* prompt tokens computed, past the resume point */
|
||||
std::vector<int64_t> resumed; /* per turn, in issue order */
|
||||
std::vector<AgentTurn> kind;
|
||||
};
|
||||
|
||||
static AgentTally run_agents(Fixture& f, const AgentLoad& L, uint32_t seed = 7) {
|
||||
const int64_t I = f.pc.checkpoint_interval(), bs = f.pc.block_size();
|
||||
uint64_t rng = 0x9e3779b97f4a7c15ull ^ seed;
|
||||
auto rnd = [&](int64_t lo, int64_t hi) {
|
||||
rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17;
|
||||
return lo + (int64_t)(rng % (uint64_t)(hi - lo + 1));
|
||||
};
|
||||
int32_t fresh = 1000000;
|
||||
auto add = [&](std::vector<int32_t>* v, int64_t n) {
|
||||
for (int64_t i = 0; i < n; ++i) v->push_back(fresh++);
|
||||
};
|
||||
const std::vector<int32_t> sys = tok_run(1, (int)L.system);
|
||||
|
||||
struct Conv {
|
||||
std::vector<int32_t> hist;
|
||||
int turns = 0; /* turns the parent has taken */
|
||||
int left = 0; /* the running subagent's turns to go; 0 when none runs */
|
||||
bool after_sub = false; /* the parent's next turn follows its subagent */
|
||||
bool done = false;
|
||||
std::vector<int32_t> sub; /* the running subagent's history */
|
||||
};
|
||||
std::vector<Conv> cs((size_t)L.parents);
|
||||
for (Conv& c : cs) { c.hist = sys; add(&c.hist, L.task); }
|
||||
|
||||
struct Turn {
|
||||
std::vector<int32_t> prompt;
|
||||
std::vector<int32_t>* hist = nullptr;
|
||||
uint64_t id = 0;
|
||||
int64_t grow = 0, resumed = 0, keep = -1;
|
||||
AgentTurn kind = kParent;
|
||||
std::vector<int64_t> at; /* checkpoint positions, in chunk order */
|
||||
std::vector<BlockHash> hs; /* the published chain */
|
||||
};
|
||||
AgentTally t;
|
||||
uint64_t next_id = 1;
|
||||
for (;;) {
|
||||
std::vector<Turn> turns;
|
||||
for (Conv& c : cs) {
|
||||
if (c.done) continue;
|
||||
Turn tn;
|
||||
tn.id = next_id++;
|
||||
tn.grow = rnd(L.grow_lo, L.grow_hi);
|
||||
if (c.left > 0) {
|
||||
tn.hist = &c.sub;
|
||||
tn.kind = c.left == L.sub_turns ? kSubFirst : kSubLater;
|
||||
} else {
|
||||
if ((int64_t)c.hist.size() >= L.parent_len) { c.done = true; continue; }
|
||||
tn.hist = &c.hist;
|
||||
tn.kind = c.after_sub ? kParentAfterSub : kParent;
|
||||
tn.keep = L.rewrite ? (int64_t)c.hist.size() : -1;
|
||||
c.after_sub = false;
|
||||
}
|
||||
tn.prompt = *tn.hist;
|
||||
add(&tn.prompt, tn.grow / 2);
|
||||
turns.push_back(std::move(tn));
|
||||
}
|
||||
if (turns.empty()) break;
|
||||
|
||||
f.pc.begin_step();
|
||||
for (Turn& tn : turns) {
|
||||
tn.resumed = f.pc.lookup(tn.prompt, {}, nullptr, nullptr, tn.id).n_linear_tokens;
|
||||
const int64_t n = (int64_t)tn.prompt.size();
|
||||
for (int64_t p = (tn.resumed / I + 1) * I; p < n; p += I) tn.at.push_back(p);
|
||||
const int64_t tail = n / bs * bs;
|
||||
if (tail > I && tail % I >= std::max(bs, I / 4)) tn.at.push_back(tail);
|
||||
t.turns++;
|
||||
t.prompt += n;
|
||||
t.computed += n - tn.resumed;
|
||||
t.resumed.push_back(tn.resumed);
|
||||
t.kind.push_back(tn.kind);
|
||||
}
|
||||
/* The reply comes after the prompt: no checkpoint lands in it. */
|
||||
for (Turn& tn : turns) {
|
||||
std::vector<int32_t> pub = tn.prompt;
|
||||
add(&pub, tn.grow - tn.grow / 2);
|
||||
tn.hs = chain_of(pub);
|
||||
*tn.hist = std::move(pub);
|
||||
}
|
||||
/* The first chunk is planned in the admitting step, so its reservation cannot take a
|
||||
* snapshot a lookup just handed out. */
|
||||
for (size_t k = 0;; ++k) {
|
||||
bool any = false;
|
||||
if (k > 0) f.pc.begin_step();
|
||||
for (Turn& tn : turns) {
|
||||
if (k >= tn.at.size()) continue;
|
||||
any = true;
|
||||
int32_t slot = -1;
|
||||
const BlockHash& key = tn.hs[(size_t)(tn.at[k] / bs - 1)];
|
||||
if (f.pc.reserve_checkpoint(tn.id, tn.at[k], key, &slot) == RAD_OK)
|
||||
f.pc.commit_checkpoint(key);
|
||||
}
|
||||
if (!any) break;
|
||||
}
|
||||
for (Turn& tn : turns) {
|
||||
publish(f, tn.id, *tn.hist, (int64_t)tn.hist->size() / bs * bs);
|
||||
f.kv.free_sequence(tn.id);
|
||||
/* A rewriting client sends the reply back without the message it answered. */
|
||||
if (tn.keep >= 0)
|
||||
tn.hist->erase(tn.hist->begin() + tn.keep,
|
||||
tn.hist->begin() + (int64_t)tn.prompt.size());
|
||||
}
|
||||
/* Subagents start and finish between rounds; a finished one's answer joins its parent. */
|
||||
for (Conv& c : cs) {
|
||||
if (c.done) continue;
|
||||
if (c.left > 0) {
|
||||
if (--c.left == 0) {
|
||||
add(&c.hist, rnd(L.grow_lo, L.grow_hi));
|
||||
c.after_sub = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (++c.turns % L.sub_every == 0) {
|
||||
c.sub = sys;
|
||||
add(&c.sub, L.task);
|
||||
c.left = L.sub_turns;
|
||||
}
|
||||
}
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
/* The same load against an unbounded keep-all store: every turn resumes as deep as checkpoints
|
||||
* were written. */
|
||||
static AgentTally agents_unbounded(const AgentLoad& L) {
|
||||
Fixture f;
|
||||
f.cfg.vram_kv_mib = 128;
|
||||
if (f.build(/*with_linear=*/true, /*ckpt_slots=*/8192) != RAD_OK) return {};
|
||||
f.pc.set_policy(std::make_unique<KeepAll>());
|
||||
return run_agents(f, L);
|
||||
}
|
||||
|
||||
/* The load against a store of `slots` under the default retention. */
|
||||
static AgentTally agents_in(const AgentLoad& L, int64_t slots) {
|
||||
Fixture f;
|
||||
f.cfg.vram_kv_mib = 128;
|
||||
if (f.build(/*with_linear=*/true, slots) != RAD_OK) return {};
|
||||
return run_agents(f, L);
|
||||
}
|
||||
|
||||
/* Turns of `kind` that resumed less than half as deep as the unbounded store let them: their
|
||||
* session's snapshots were gone. */
|
||||
static int64_t agents_lost(const AgentTally& a, const AgentTally& best, AgentTurn kind) {
|
||||
int64_t n = 0;
|
||||
for (size_t i = 0; i < a.resumed.size() && i < best.resumed.size(); ++i)
|
||||
if (a.kind[i] == kind && a.resumed[i] * 2 < best.resumed[i]) ++n;
|
||||
return n;
|
||||
}
|
||||
|
||||
/* Prompt tokens computed beyond the unbounded store's, as a fraction of all prompt tokens. */
|
||||
static double agents_excess(const AgentTally& a, const AgentTally& best) {
|
||||
return best.prompt > 0 ? (double)(a.computed - best.computed) / (double)best.prompt : 1.0;
|
||||
}
|
||||
|
||||
/* The store a configuration gives the load: its count, or under auto what the engine resolves for
|
||||
* one sequence a parent, with memory to spare. */
|
||||
static int64_t agents_store(const Config& c, const AgentLoad& L, int64_t interval) {
|
||||
if (c.checkpoint_slots >= 0) return c.checkpoint_slots;
|
||||
const auto pol = make_checkpoint_policy(c.checkpoint_policy, interval);
|
||||
return checkpoint_slots_auto(*pol, L.parents, L.parent_len, interval, 1, INT64_MAX, INT64_MAX)
|
||||
.slots;
|
||||
}
|
||||
|
||||
/* An admission takes over every snapshot on the chain it hit, so a conversation is one session
|
||||
* from the start of its turn, as it is after the publish. A snapshot past the hit stays where it
|
||||
* was; a lookup naming no request moves nothing. */
|
||||
TEST(an_admission_takes_over_the_snapshots_on_the_chain_it_hit) {
|
||||
Fixture f;
|
||||
CHECK_OK(f.build(/*with_linear=*/true, /*ckpt_slots=*/8));
|
||||
const auto p1 = tok_run(7000, 336);
|
||||
publish(f, 1, p1, 320);
|
||||
const std::vector<BlockHash> hs = chain_of(p1);
|
||||
ckpt_at(f, 1, hs, 128);
|
||||
ckpt_at(f, 1, hs, 256);
|
||||
|
||||
auto p2 = p1;
|
||||
for (size_t k = 200; k < p2.size(); ++k) p2[k] += 50000;
|
||||
f.pc.begin_step();
|
||||
CHECK_EQ(f.pc.lookup(p2, {}).n_linear_tokens, 128);
|
||||
CHECK(f.pc.checkpoints(1) == (std::vector<int64_t>{ 128, 256 }));
|
||||
f.pc.begin_step();
|
||||
CHECK_EQ(f.pc.lookup(p2, {}, nullptr, nullptr, 2).n_linear_tokens, 128);
|
||||
CHECK(f.pc.checkpoints(2) == (std::vector<int64_t>{ 128 }));
|
||||
CHECK(f.pc.checkpoints(1) == (std::vector<int64_t>{ 256 }));
|
||||
CHECK_EQ(f.pc.sessions_tracked(), 2ll);
|
||||
}
|
||||
|
||||
/* A running turn's checkpoints and its conversation's earlier ones are retained as one ladder, so
|
||||
* a full store does not take another conversation's snapshot for them. Conversation P holds one
|
||||
* snapshot, the oldest in the store; A holds seven and its next turn writes five more. As two
|
||||
* sessions (the turn before and the turn running) A keeps two ladders and the store evicts P's
|
||||
* snapshot; as one it keeps one ladder and P's survives. */
|
||||
TEST(a_running_turn_does_not_evict_a_waiting_conversations_snapshot) {
|
||||
for (const bool named : { false, true }) {
|
||||
Fixture f;
|
||||
CHECK_OK(f.build(/*with_linear=*/true, /*ckpt_slots=*/8));
|
||||
const auto p = tok_run(500000, 96);
|
||||
const std::vector<BlockHash> ph = chain_of(p);
|
||||
ckpt_at(f, 100, ph, 64);
|
||||
|
||||
const auto a = tok_run(1, 16 * 60);
|
||||
const std::vector<BlockHash> ah = chain_of(a);
|
||||
std::vector<int32_t> turn1(a.begin(), a.begin() + 464);
|
||||
publish(f, 1, turn1, 464);
|
||||
f.kv.free_sequence(1);
|
||||
for (int64_t pos = 64; pos <= 448; pos += 64) ckpt_at(f, 1, ah, pos);
|
||||
CHECK_EQ(f.kv.free_checkpoint_slots(), 0ll);
|
||||
|
||||
std::vector<int32_t> turn2(a.begin(), a.begin() + 800);
|
||||
f.pc.begin_step();
|
||||
REQUIRE_EQ(f.pc.lookup(turn2, {}, nullptr, nullptr, named ? 2 : 0).n_linear_tokens, 448);
|
||||
for (int64_t pos = 512; pos <= 768; pos += 64) {
|
||||
int32_t slot = -1;
|
||||
CHECK_OK(f.pc.reserve_checkpoint(2, pos, ah[(size_t)(pos / 16 - 1)], &slot));
|
||||
f.pc.commit_checkpoint(ah[(size_t)(pos / 16 - 1)]);
|
||||
f.pc.begin_step();
|
||||
}
|
||||
if (named) {
|
||||
CHECK(f.pc.checkpoints(100) == (std::vector<int64_t>{ 64 }));
|
||||
CHECK(f.pc.checkpoints(1).empty());
|
||||
CHECK(f.pc.checkpoints(2) ==
|
||||
(std::vector<int64_t>{ 64, 256, 512, 576, 640, 704, 768 }));
|
||||
CHECK_EQ(f.pc.stats().ckpt_lru, 0ll);
|
||||
} else {
|
||||
CHECK(f.pc.checkpoints(100).empty());
|
||||
CHECK_EQ(f.pc.stats().ckpt_lru, 1ll);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* What a session needs from the store, and that retention holds it to that: a 200K-token session
|
||||
* at a 2048-token interval keeps at most 9 snapshots under geometric backoff. The scaled session
|
||||
* (98 intervals of 64 tokens), checkpointed one interval at a time with a tail checkpoint half an
|
||||
* interval on after each and retention after every one, never holds more than its policy's figure
|
||||
* and reaches it. */
|
||||
TEST(a_sessions_standing_share_is_what_retention_keeps) {
|
||||
CHECK_EQ(GeometricBackoff(2048).held(200000, 2048), 9ll);
|
||||
CHECK_EQ(GeometricBackoff(2048).held(32768, 2048), 6ll);
|
||||
CHECK_EQ(GeometricBackoff(2048).held(1000, 2048), 1ll);
|
||||
CHECK_EQ(KeepTipOnly().held(200000, 2048), 1ll);
|
||||
CHECK_EQ(KeepAll().held(200000, 2048), 97ll);
|
||||
CHECK(std::string(make_checkpoint_policy("tip-only", 64)->name()) == "tip-only");
|
||||
CHECK(std::string(make_checkpoint_policy("keep-all", 64)->name()) == "keep-all");
|
||||
CHECK(std::string(make_checkpoint_policy("geometric-backoff", 64)->name()) ==
|
||||
"geometric-backoff");
|
||||
|
||||
Fixture f;
|
||||
CHECK_OK(f.build(/*with_linear=*/true, /*ckpt_slots=*/128));
|
||||
const auto s = tok_run(1, 6272 + 16);
|
||||
const std::vector<BlockHash> hs = chain_of(s);
|
||||
size_t most = 0;
|
||||
for (int64_t pos = 64; pos <= 6272; pos += 64) {
|
||||
for (const int64_t at : { pos, pos + 32 }) {
|
||||
if (at > 6272) continue;
|
||||
ckpt_at(f, 1, hs, at);
|
||||
f.pc.retain(1);
|
||||
most = std::max(most, f.pc.checkpoints(1).size());
|
||||
}
|
||||
}
|
||||
CHECK_EQ((int64_t)most, GeometricBackoff(64).held(6272, 64));
|
||||
CHECK_EQ((int64_t)most, 9ll);
|
||||
}
|
||||
|
||||
/* --checkpoint-slots auto: the policy's share plus one for each sequence, held to the share of
|
||||
* memory but not below the floor, and to the room the host has. */
|
||||
TEST(the_auto_store_gives_every_sequence_its_sessions_share) {
|
||||
const GeometricBackoff g(2048);
|
||||
const int64_t slot = 113 << 20, lots = INT64_MAX;
|
||||
CheckpointSlots c = checkpoint_slots_auto(g, 8, 200000, 2048, slot, lots, lots);
|
||||
CHECK_EQ(c.per_seq, 10ll);
|
||||
CHECK_EQ(c.want, 80ll);
|
||||
CHECK_EQ(c.slots, 80ll);
|
||||
CHECK(c.bound == CheckpointSlots::Bound::Want);
|
||||
|
||||
c = checkpoint_slots_auto(g, 8, 200000, 2048, slot, 40 * slot + slot / 2, lots);
|
||||
CHECK_EQ(c.slots, 40ll);
|
||||
CHECK(c.bound == CheckpointSlots::Bound::Share);
|
||||
c = checkpoint_slots_auto(g, 8, 200000, 2048, slot, 2 * slot, lots);
|
||||
CHECK_EQ(c.slots, kCheckpointSlotsFloor);
|
||||
CHECK(c.bound == CheckpointSlots::Bound::Share);
|
||||
c = checkpoint_slots_auto(g, 8, 200000, 2048, slot, lots, 5 * slot);
|
||||
CHECK_EQ(c.slots, 5ll);
|
||||
CHECK(c.bound == CheckpointSlots::Bound::Room);
|
||||
c = checkpoint_slots_auto(g, 8, 200000, 2048, slot, 2 * slot, 3 * slot);
|
||||
CHECK_EQ(c.slots, 3ll);
|
||||
CHECK(c.bound == CheckpointSlots::Bound::Room);
|
||||
c = checkpoint_slots_auto(g, 8, 200000, 2048, slot, lots, slot - 1);
|
||||
CHECK_EQ(c.slots, 0ll);
|
||||
|
||||
/* The floor never exceeds what the policy wants. */
|
||||
c = checkpoint_slots_auto(KeepTipOnly(), 1, 200000, 2048, slot, 0, lots);
|
||||
CHECK_EQ(c.want, 2ll);
|
||||
CHECK_EQ(c.slots, 2ll);
|
||||
c = checkpoint_slots_auto(KeepTipOnly(), 4, 200000, 2048, slot, lots, lots);
|
||||
CHECK_EQ(c.slots, 8ll);
|
||||
c = checkpoint_slots_auto(KeepAll(), 2, 200000, 2048, slot, lots, lots);
|
||||
CHECK_EQ(c.slots, 196ll);
|
||||
|
||||
/* --max-num-seqs's own default, 256, and no state to snapshot. */
|
||||
c = checkpoint_slots_auto(g, 256, 200000, 2048, slot, (int64_t)8 << 30, lots);
|
||||
CHECK_EQ(c.want, 2560ll);
|
||||
CHECK_EQ(c.slots, ((int64_t)8 << 30) / slot);
|
||||
c = checkpoint_slots_auto(g, INT64_MAX, 200000, 2048, slot, lots, lots);
|
||||
CHECK_EQ(c.want, INT64_MAX);
|
||||
CHECK_EQ(c.slots, INT64_MAX / slot);
|
||||
c = checkpoint_slots_auto(g, 8, 200000, 2048, 0, lots, lots);
|
||||
CHECK_EQ(c.slots, 0ll);
|
||||
}
|
||||
|
||||
/* Four agent conversations with subagents, scaled to 200K tokens each, in the store the default
|
||||
* configuration gives them. While a parent waits on its subagent, the subagent's snapshots fill
|
||||
* the store; in the fixed 8-slot store they evict all of the waiting parent's, and its next turn
|
||||
* prefills its whole history again. In the default store every continuing turn resumes where an
|
||||
* unbounded store would. What is left is the subagents' first turns: the system prompt they share
|
||||
* is past every snapshot the policy keeps. */
|
||||
TEST(agent_sessions_with_subagents_keep_their_snapshots_in_the_default_store) {
|
||||
const AgentLoad L;
|
||||
const AgentTally best = agents_unbounded(L);
|
||||
REQUIRE(best.turns > 300);
|
||||
|
||||
Config d;
|
||||
d.checkpoint_interval = 64;
|
||||
const int64_t slots = agents_store(d, L, 64);
|
||||
CHECK_EQ(slots, 40ll);
|
||||
const AgentTally a = agents_in(L, slots);
|
||||
const AgentTally fixed = agents_in(L, 8);
|
||||
fprintf(stderr, " %lld turns; prompt tokens computed past an unbounded store's: %.1f%% in %lld "
|
||||
"slots, %.1f%% in 8\n", (long long)a.turns, 100 * agents_excess(a, best),
|
||||
(long long)slots, 100 * agents_excess(fixed, best));
|
||||
CHECK_EQ(agents_lost(a, best, kParent), 0ll);
|
||||
CHECK_EQ(agents_lost(a, best, kParentAfterSub), 0ll);
|
||||
CHECK_EQ(agents_lost(a, best, kSubLater), 0ll);
|
||||
CHECK(agents_excess(a, best) < 0.03);
|
||||
|
||||
CHECK(agents_lost(fixed, best, kParentAfterSub) >= 30);
|
||||
CHECK(agents_excess(fixed, best) > 0.30);
|
||||
}
|
||||
|
||||
/* The same with a client that rewrites its last message every turn, so a turn diverges below the
|
||||
* previous turn's tip and needs a snapshot behind it: the ladder must survive beside the
|
||||
* subagents. */
|
||||
TEST(a_rewriting_client_with_subagents_resumes_in_the_default_store) {
|
||||
AgentLoad L;
|
||||
L.rewrite = true;
|
||||
const AgentTally best = agents_unbounded(L);
|
||||
REQUIRE(best.turns > 300);
|
||||
Config d;
|
||||
d.checkpoint_interval = 64;
|
||||
const AgentTally a = agents_in(L, agents_store(d, L, 64));
|
||||
fprintf(stderr, " %lld turns; %.1f%% computed past an unbounded store's\n",
|
||||
(long long)a.turns, 100 * agents_excess(a, best));
|
||||
const int64_t lost = agents_lost(a, best, kParent) + agents_lost(a, best, kParentAfterSub) +
|
||||
agents_lost(a, best, kSubLater);
|
||||
CHECK(lost <= 2);
|
||||
CHECK(agents_excess(a, best) < 0.03);
|
||||
}
|
||||
|
||||
/* ================================================================== the KV loan
|
||||
*
|
||||
* The cache and the expert plane share one card, split once at startup against a worst case.
|
||||
@@ -4885,6 +5276,38 @@ TEST(the_bindings_snapshot_key_carries_the_requests_pictures) {
|
||||
CHECK_EQ(text.checkpoint_slot, -1);
|
||||
}
|
||||
|
||||
/* Runtime LoRA: KV written under an adapter is keyed by its load's uid from the first block on, so
|
||||
* a base request and a request through another load (the same adapter reloaded included) share
|
||||
* nothing with it, and the base's own keys are those of an engine without adapters. */
|
||||
TEST(the_bindings_keys_carry_the_requests_adapter_load) {
|
||||
Fixture f;
|
||||
REQUIRE_EQ(f.build(/*with_linear=*/true, /*ckpt_slots=*/4), RAD_OK);
|
||||
PCBinding<PrefixCache> b(&f.pc);
|
||||
auto via = [](Request r, uint64_t uid) {
|
||||
r.lora_slot = uid ? 0 : -1;
|
||||
r.lora_uid = uid;
|
||||
return r;
|
||||
};
|
||||
const Request r = via(turn(7, tok_run(100, 300), tok_run(9000, 40)), 5);
|
||||
const int32_t slot = serve_turn(f, b, r, 320);
|
||||
REQUIRE(slot >= 0);
|
||||
const auto again = cat(cat(r.prompt, r.output), tok_run(20000, 50));
|
||||
const CacheHit same = b.lookup(via(turn(8, again, {}), 5), nullptr, nullptr);
|
||||
CHECK_EQ(same.n_attn_tokens, 336);
|
||||
CHECK_EQ(same.checkpoint_slot, slot);
|
||||
for (uint64_t other : { 0ull, 6ull }) {
|
||||
const CacheHit h = b.lookup(via(turn(9, again, {}), other), nullptr, nullptr);
|
||||
CHECK_EQ(h.n_attn_tokens, 0);
|
||||
CHECK_EQ(h.checkpoint_slot, -1);
|
||||
}
|
||||
/* The base's blocks are keyed as without adapters: a bare-prompt lookup finds them. */
|
||||
const Request base = turn(10, tok_run(40000, 300), tok_run(41000, 40));
|
||||
serve_turn(f, b, base, 320);
|
||||
const auto next = cat(cat(base.prompt, base.output), tok_run(42000, 50));
|
||||
CHECK_EQ(f.pc.lookup(next, {}).n_attn_tokens, 336);
|
||||
CHECK_EQ(b.lookup(via(turn(11, next, {}), 5), nullptr, nullptr).n_attn_tokens, 0);
|
||||
}
|
||||
|
||||
/* ================================================================== retention policies */
|
||||
|
||||
/* A retention policy is a documented extension point and nothing requires its keep set in any
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
* zero or a missing rotation all exceed.
|
||||
*/
|
||||
#include "quant_fixture.h"
|
||||
#include "format/checkpoint.h"
|
||||
#include "format/recipe.h"
|
||||
|
||||
#include <deque>
|
||||
@@ -330,6 +331,14 @@ TEST(every_shipped_recipe_compiles_and_its_grids_are_accepted) {
|
||||
std::deque<CompiledRule> compiled;
|
||||
for (const RecipeRule& rule : r.rules()) {
|
||||
++rules;
|
||||
/* rad-convert's own import rule: its options must parse. */
|
||||
if (rule.quantizer == kImportRule) {
|
||||
ImportForm f;
|
||||
const int ps = ckpt_import_form_parse(rule.options, &f, &why);
|
||||
if (ps != RAD_OK) std::fprintf(stderr, " %s: %s\n", rule.origin.c_str(), why.c_str());
|
||||
CHECK_EQ(ps, RAD_OK);
|
||||
continue;
|
||||
}
|
||||
compiled.emplace_back();
|
||||
CompiledRule& c = compiled.back();
|
||||
if (c.build(rule, reg(), &why) != RAD_OK) {
|
||||
|
||||
+11
-11
@@ -1,28 +1,28 @@
|
||||
/* lora_cases.h -- the runtime-LoRA case matrix and what every implementation is held to, shared by
|
||||
* tests/lora_ops_test.cpp (libref and libavx, at every ISA level the machine runs) and
|
||||
* tests/r4d_emu/test_lora.cpp (libr4d's source on the SIMT emulator, beside libref and the host
|
||||
* restatement in ref_host.cpp). One matrix and one checker, so "the same cases" is a fact and not
|
||||
* an intention.
|
||||
* restatement in ref_host.cpp). One matrix and one checker, so every implementation runs the same
|
||||
* cases.
|
||||
*
|
||||
* THE MATRIX. M in {1, 3, 17, 64, 130}, R in {16, 32, 48}, S = 4, K (and N) in {64, 256, 1000};
|
||||
* The matrix: M in {1, 3, 17, 64, 130}, R in {16, 32, 48}, S = 4, K (and N) in {64, 256, 1000};
|
||||
* `a` bf16, or E4M3 with an f32 scale every 128 columns (1000 leaves a partial group, 64 a row
|
||||
* narrower than one group); `y` bf16 and f32. Then the other dtypes once over a smaller grid: `a`
|
||||
* f16, f32, E5M2 and i8 (the last two with scales), `y` f16. `a`, its scale stream and `y` are
|
||||
* COLUMN SLICES of wider buffers. Slots cycle through -1, -5, 0..3 and 4 (= S): three spellings
|
||||
* of a base row beside the adapter rows, M = 1 once as an adapter row and twice as a base one.
|
||||
* column slices of wider buffers. Slots cycle through -1, -5, 0..3 and 4 (= S): three spellings of
|
||||
* a base row beside the adapter rows, M = 1 once as an adapter row and twice as a base one.
|
||||
*
|
||||
* WHAT IS CHECKED, per implementation, per case:
|
||||
* * BASE ROWS ARE UNTOUCHED, BY BYTES. Shrink leaves the sentinel NaN pattern `t` was filled
|
||||
* with; expand leaves `y` -- every third element a -0, which `y + 0` would turn into +0 -- and
|
||||
* Checked per implementation, per case:
|
||||
* - Base rows are untouched, by bytes. Shrink leaves the sentinel NaN pattern `t` was filled
|
||||
* with; expand leaves `y` (every third element a -0, which `y + 0` would turn into +0) and
|
||||
* every column outside the slice as they were.
|
||||
* * ADAPTER ROWS AGAINST A DOUBLE-PRECISION SUM of the same f32 terms (x(m, k) is the code times
|
||||
* - Adapter rows against a double-precision sum of the same f32 terms (x(m, k) is the code times
|
||||
* its scale rounded to f32, as the contract defines it). Shrink: |t - sum| <= (K + 2) 2^-24
|
||||
* sum|terms|, the worst case of an f32 dot in any summation order, so no implementation can
|
||||
* fail it by choosing an order and every one fails it by reading a wrong element. Expand:
|
||||
* |y - want| <= h (|want| + e) + 2 e with e = 4 (R + 2) 2^-24 (|y| + |scale| sum|terms|) and h
|
||||
* half an ulp of y's dtype relative (2^-8 bf16, 2^-11 f16, 0 f32).
|
||||
* * An implementation marked `ref_bytes` must also produce, for expand, exactly the bytes of the
|
||||
* first implementation in the list -- the claim libr4d's expand makes about libref's order.
|
||||
* - An implementation marked `ref_bytes` must also produce, for expand, exactly the bytes of the
|
||||
* first implementation in the list, the claim libr4d's expand makes about libref's order.
|
||||
*
|
||||
* A shrink row with a scratch hook (libr4d's WMMA row keeps its K split's partials there) is handed
|
||||
* the scratch the hook asks for, filled with a non-zero pattern, as the core would hand it a slice of
|
||||
|
||||
+13
-13
@@ -2,17 +2,17 @@
|
||||
*
|
||||
* The case matrix and every check are lora_cases.h's, shared with tests/lora_ops_test.cpp (libref and
|
||||
* libavx): base rows untouched by bytes, adapter rows against a double-precision sum within the
|
||||
* bounds stated there. Here the implementations are the emulated kernels -- the v1 scalar rows and
|
||||
* the tiled rows (WMMA shrink, LDS-staged expand) -- ref_host.cpp's restatement of libref's
|
||||
* arithmetic, and libref itself when $RADIANCE_HOME holds one (ctest sets it); every emulated
|
||||
* EXPAND is held to the first of those bit for bit, because its j-ascending sum and its roundings
|
||||
* are libref's. Shrink is held to the bound rather than to libref's bytes: v1 sums k in 32 lane
|
||||
* bounds stated there. Here the implementations are the emulated kernels (the scalar rows and the
|
||||
* tiled rows: WMMA shrink, LDS-staged expand), ref_host.cpp's restatement of libref's arithmetic,
|
||||
* and libref itself when $RADIANCE_HOME holds one (ctest sets it). Every emulated expand is held
|
||||
* to libref's restatement bit for bit, because its j-ascending sum and its roundings are libref's.
|
||||
* Shrink is held to the bound rather than to libref's bytes: the scalar row sums k in 32 lane
|
||||
* strides and a butterfly, the WMMA row in 32-wide steps over waves and a K split.
|
||||
*
|
||||
* Then what the tiled rows promise beyond the matrix, each proven here on the emulator:
|
||||
*
|
||||
* shapes the real ones -- K 2048 / 5120 / 6144 / 17408, R 16 / 48 / 64 / 192, N 256 ..
|
||||
* 12288, odd M, S 1..4, bf16 and E4M3 with a scale every 128 -- shrink to the f64
|
||||
* shapes the real ones (K 2048 / 5120 / 6144 / 17408, R 16 / 48 / 64 / 192, N 256 ..
|
||||
* 12288, odd M, S 1..4, bf16 and E4M3 with a scale every 128): shrink to the f64
|
||||
* bound (and its worst error printed against f64), expand to libref's bytes.
|
||||
* batch a row computed alone (M = 1) and as row p of M in {7, 16, 17, 37, 300}, the others
|
||||
* random slots and base rows: its t and y bits are the same. Every K split, z fan-out
|
||||
@@ -303,7 +303,7 @@ static std::vector<int32_t> rand_slots(std::mt19937& rng, int M, int S, int base
|
||||
return v;
|
||||
}
|
||||
|
||||
/* REAL SHAPES. Each pair is shrink -> expand, as the engine issues it: expand reads the t the
|
||||
/* Real shapes. Each pair is shrink -> expand, as the engine issues it: expand reads the t the
|
||||
* tiled shrink wrote, and is held to libref's bytes over that same t. */
|
||||
static void test_shapes(const Rows& R) {
|
||||
std::mt19937 rng(23);
|
||||
@@ -344,7 +344,7 @@ static void test_shapes(const Rows& R) {
|
||||
sizeof(shapes) / sizeof(shapes[0]), wb, wr, std::ldexp(1.0, -24));
|
||||
}
|
||||
|
||||
/* BATCH INVARIANCE: a row alone and inside batches of other slots and base rows. */
|
||||
/* Batch invariance: a row alone and inside batches of other slots and base rows. */
|
||||
static void test_invariance() {
|
||||
std::mt19937 rng(41);
|
||||
struct Sh { int K, R, N, S; uint32_t adt, ydt; };
|
||||
@@ -435,7 +435,7 @@ static void test_invariance() {
|
||||
"positions, aligned and unaligned)\n", compared);
|
||||
}
|
||||
|
||||
/* BASE ROWS ONLY: a prefill-sized launch of nothing but base rows touches no byte of t or y. */
|
||||
/* Base rows only: a prefill-sized launch of nothing but base rows touches no byte of t or y. */
|
||||
static void test_all_base() {
|
||||
std::mt19937 rng(5);
|
||||
std::vector<int32_t> slot((size_t)2048);
|
||||
@@ -453,9 +453,9 @@ static void test_all_base() {
|
||||
std::printf("lora base rows only: M 2048, t and y untouched\n");
|
||||
}
|
||||
|
||||
/* EVERY CODE through a one-hot pool: A[s, j, k] = (k == j), so t[m, j] = x(m, j) = code * scale
|
||||
* exactly -- one exact product, the rest +-0 -- and the WMMA row's code widening is checked code
|
||||
* by code. Codes whose value is NaN or Inf would turn every j's zero products into NaN, so they
|
||||
/* Every code through a one-hot pool: A[s, j, k] = (k == j), so t[m, j] = x(m, j) = code * scale
|
||||
* exactly (one exact product, the rest +-0), and the WMMA row's code widening is checked code by
|
||||
* code. Codes whose value is NaN or Inf would turn every j's zero products into NaN, so they
|
||||
* get rows of their own, where every t must be NaN as in the f64 sum. */
|
||||
static void test_codes() {
|
||||
int checked = 0;
|
||||
|
||||
+1032
-7
File diff suppressed because it is too large.
Load diff
@@ -914,6 +914,98 @@ TEST(raw_operand_carries_the_pointer_and_refuses_an_offset) {
|
||||
CHECK(std::strstr(f.ctx.step_error(), "no dtype") != nullptr);
|
||||
}
|
||||
|
||||
/* Runtime LoRA's issue chain (Ctx::issue_lora): a gemm that is a LoRA site is followed by
|
||||
* lora_shrink and lora_expand over its own activation, output and rows, but only on a step that
|
||||
* has an adapter row (RadBatch::lora_slot non-null). A step without one, or a draft pass, issues
|
||||
* the gemm alone, the pass an engine without adapters runs; an encoder pass reaching a site is
|
||||
* refused by name. */
|
||||
static int k_gemm (const RadArgs* a, RadStream s) { return record("gemm", a, s); }
|
||||
static int k_shrink(const RadArgs* a, RadStream s) { return record("shrink", a, s); }
|
||||
static int k_expand(const RadArgs* a, RadStream s) { return record("expand", a, s); }
|
||||
|
||||
TEST(adapter_ops_follow_a_lora_site_only_on_a_step_with_an_adapter_row) {
|
||||
Fixture f;
|
||||
const rad_weight w = f.add_weight("blk.0.w", RAD_BF16, 8, 4, g_weight_bytes);
|
||||
const rad_buf x = f.add_buffer("x", RAD_BF16, 16, 4, 0);
|
||||
const rad_buf y = f.add_buffer("y", RAD_BF16, 16, 8, 256);
|
||||
const rad_buf pa = f.add_buffer("lora.a", RAD_BF16, 2, 16, 1024); /* [S, R * K] */
|
||||
const rad_buf pb = f.add_buffer("lora.b", RAD_BF16, 2, 32, 1280); /* [S, N * R] */
|
||||
const rad_buf ps = f.add_buffer("lora.scale", RAD_F32, 2, 8, 1536);
|
||||
const rad_buf t0 = f.add_buffer("lora.t0", RAD_F32, 16, 4, 2048);
|
||||
const rad_buf t1 = f.add_buffer("lora.t1", RAD_F32, 16, 4, 2304);
|
||||
const rad_op g = f.add_op("gemm_nt", "M", { 64 }, { k_gemm }, { "gemm" }, &g_gemm_schema, { w });
|
||||
const rad_op sh = f.add_op("lora_shrink", "M", { 64 }, { k_shrink }, { "shrink" }, nullptr, {});
|
||||
const rad_op ex = f.add_op("lora_expand", "M", { 64 }, { k_expand }, { "expand" }, nullptr, {});
|
||||
f.P.ops[g].lora_site = 0;
|
||||
f.P.ops[sh].anchor = (int32_t)g;
|
||||
f.P.ops[ex].anchor = (int32_t)g;
|
||||
rad::LoraIssueSite site;
|
||||
site.gemm = g; site.shrink = sh; site.expand = ex;
|
||||
site.opd_a = 0; site.opd_y = 2;
|
||||
site.a_dtype = RAD_BF16; site.y_dtype = RAD_BF16;
|
||||
site.pool = 0; site.t = 0;
|
||||
site.R = 4; site.K = 4; site.N = 8;
|
||||
f.P.lora_sites.push_back(site);
|
||||
rad::LoraPool pool;
|
||||
pool.weight = "blk.0.w";
|
||||
pool.a = pa; pool.b = pb; pool.scale = ps;
|
||||
pool.R = 4; pool.K = 4; pool.N = 8; pool.S = 2;
|
||||
f.P.lora_pools.push_back(pool);
|
||||
rad::LoraScratch scr;
|
||||
scr.R = 4;
|
||||
scr.lane[0] = t0; scr.lane[1] = t1;
|
||||
f.P.lora_t.push_back(scr);
|
||||
CHECK_OK(f.start());
|
||||
|
||||
auto body = [&](Ctx& c) {
|
||||
RadOperand opd[3] = { RAD_B(x), RAD_W(w), RAD_B(y) };
|
||||
CHECK_OK(c.issue(g, opd, 3, RAD_N_BATCH));
|
||||
};
|
||||
auto names = [] {
|
||||
std::string s;
|
||||
for (const Rec& r : g_rec) s += std::string(s.empty() ? "" : " ") + r.kernel;
|
||||
return s;
|
||||
};
|
||||
|
||||
/* No adapter row: the gemm alone. */
|
||||
f.batch.lora_slot = nullptr;
|
||||
g_rec.clear();
|
||||
CHECK_OK(f.step(4, 0, body));
|
||||
CHECK_EQ(names(), std::string("gemm"));
|
||||
|
||||
/* An adapter row: the pair behind the gemm, over its activation and its output, each row's
|
||||
* slot read from the step batch. */
|
||||
int32_t slots[4] = { 1, -1, 0, -1 };
|
||||
f.batch.lora_slot = slots;
|
||||
g_rec.clear();
|
||||
CHECK_OK(f.step(4, 1, body));
|
||||
REQUIRE_EQ(names(), std::string("gemm shrink expand"));
|
||||
CHECK(g_rec[1].t[0].data == g_rec[0].t[0].data); /* shrink reads the gemm's x */
|
||||
CHECK(g_rec[1].t[2].data == (void*)slots);
|
||||
CHECK_EQ(g_rec[1].t[2].shape[0], (int64_t)4);
|
||||
CHECK(g_rec[2].t[4].data == g_rec[0].t[2].data); /* expand adds into the gemm's y */
|
||||
CHECK(g_rec[2].t[0].data == g_rec[1].t[4].data); /* over shrink's t */
|
||||
CHECK_EQ(g_rec[1].t[4].shape[0], (int64_t)4); /* t holds the step's rows */
|
||||
|
||||
/* A draft pass runs the base weights: the gemm alone. */
|
||||
f.batch.draft_pass = 1;
|
||||
g_rec.clear();
|
||||
CHECK_OK(f.step(4, 2, body));
|
||||
CHECK_EQ(names(), std::string("gemm"));
|
||||
f.batch.draft_pass = 0;
|
||||
|
||||
/* An encoder pass never reaches a site; one that does is refused, not run without its delta. */
|
||||
f.batch.enc = 1;
|
||||
g_rec.clear();
|
||||
const int s = f.step(4, 3, [&](Ctx& c) {
|
||||
RadOperand opd[3] = { RAD_B(x), RAD_W(w), RAD_B(y) };
|
||||
c.issue(g, opd, 3, RAD_N_BATCH);
|
||||
});
|
||||
CHECK_EQ(s, RAD_E_UNSUPPORTED);
|
||||
CHECK(std::strstr(f.ctx.step_error(), "encoder or generator pass") != nullptr);
|
||||
CHECK_EQ(names(), std::string("gemm"));
|
||||
}
|
||||
|
||||
/* Site is a property of the weights (spec §5.1). A domain with no kernel in some band is refused,
|
||||
* naming the op and band: the planner was told at declare which sites are unavailable, so asking
|
||||
* anyway is a planner bug. */
|
||||
|
||||
@@ -1122,13 +1122,21 @@ TEST(derived_metadata_is_computed_once_per_step_into_the_arena) {
|
||||
}
|
||||
|
||||
/* RadBatch::lora_slot: every row of a sequence carries its request's runtime LoRA slot, -1 for a
|
||||
* base request, in the step's row order (decode rows first). */
|
||||
* base request, in the step's row order (decode rows first). A step with no adapter row carries
|
||||
* none, so the core issues no adapter op on it. */
|
||||
TEST(the_step_batch_carries_each_rows_adapter_slot) {
|
||||
Fixture f;
|
||||
f.build();
|
||||
f.cfg.lora.max_loras = 2;
|
||||
CHECK_OK(f.start());
|
||||
|
||||
f.submit(16, 1);
|
||||
const RadBatch* base = f.sch.step();
|
||||
CHECK(base != nullptr);
|
||||
CHECK_EQ(base->n_tok, (int64_t)16);
|
||||
CHECK(base->lora_slot == nullptr);
|
||||
f.commit_plain();
|
||||
|
||||
auto r = f.request(100, 64);
|
||||
r->lora_slot = 1;
|
||||
r->lora_uid = 7;
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "gen/audio.h"
|
||||
#include "gen/gen.h"
|
||||
#include "mm/processor.h"
|
||||
#include "server/adapters.h"
|
||||
@@ -591,6 +592,90 @@ struct FakeImageGen : IImageGen {
|
||||
int64_t running() const override { return 0; }
|
||||
};
|
||||
|
||||
/* An audio generator that finishes every request on submit: `windows` windows of `per_window`
|
||||
* stereo samples, pushed in `order` (the driver may finish windows out of order), sample j of
|
||||
* window k at sample(k, j). Text containing "REFUSE" is refused by prepare(). With `hold` a
|
||||
* request is taken and left running, its ticket neither fed nor ended. A realtime session submits
|
||||
* from its own thread: read what was submitted through n_got() and request(). */
|
||||
struct FakeAudioGen : IAudioGen {
|
||||
AudioGenInfo inf;
|
||||
int submit_status = RAD_OK;
|
||||
std::string submit_why;
|
||||
int finish_status = RAD_OK;
|
||||
std::string finish_why;
|
||||
std::vector<int32_t> order = { 1, 0, 2 };
|
||||
int32_t per_window = 6;
|
||||
bool hold = false;
|
||||
std::vector<std::unique_ptr<gen::AudioRequest>> got;
|
||||
mutable std::mutex got_m;
|
||||
|
||||
FakeAudioGen() {
|
||||
inf.name = "fake-audio";
|
||||
inf.tmpl = "<s>{instructions}|{input}";
|
||||
inf.max_prompt = 64;
|
||||
inf.max_frames = 100;
|
||||
inf.frame_rate_num = 25;
|
||||
inf.frame_rate_den = 1;
|
||||
inf.sample_rate = 8000;
|
||||
inf.channels = 2;
|
||||
inf.default_steps = 30;
|
||||
inf.default_cfg = 1.7;
|
||||
inf.max_lanes = 4;
|
||||
}
|
||||
/* One sample past full scale (window 2's first), to show the clip. */
|
||||
static float sample(int32_t k, int32_t j) {
|
||||
return j == 0 && k == 2 ? 1.5f : (float)(k * 8 + j) / 37.0f - 0.4f;
|
||||
}
|
||||
const AudioGenInfo& info() const override { return inf; }
|
||||
int prepare(int, const std::string& in, std::string* out, std::string* why) const override {
|
||||
if (in.find("REFUSE") != std::string::npos) {
|
||||
*why = "the text was refused";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
*out = in;
|
||||
return RAD_OK;
|
||||
}
|
||||
size_t n_got() const {
|
||||
std::lock_guard<std::mutex> lk(got_m);
|
||||
return got.size();
|
||||
}
|
||||
/* Request i's prompt as text (the fake tokenizer's ids are bytes) and its ticket. */
|
||||
std::string prompt_of(size_t i) const {
|
||||
std::lock_guard<std::mutex> lk(got_m);
|
||||
std::string t;
|
||||
for (int32_t c : got[i]->tokens) t += (char)c;
|
||||
return t;
|
||||
}
|
||||
std::shared_ptr<gen::AudioTicket> ticket_of(size_t i) const {
|
||||
std::lock_guard<std::mutex> lk(got_m);
|
||||
return got[i]->ticket;
|
||||
}
|
||||
int submit(std::unique_ptr<gen::AudioRequest> r, std::string* why) override {
|
||||
std::lock_guard<std::mutex> lk(got_m);
|
||||
if (submit_status < 0) { *why = submit_why; return submit_status; }
|
||||
if (hold) {
|
||||
got.push_back(std::move(r));
|
||||
return RAD_OK;
|
||||
}
|
||||
gen::AudioTicket& t = *r->ticket;
|
||||
t.in_tokens = (int64_t)r->tokens.size();
|
||||
t.frames = r->max_frames;
|
||||
t.windows = (int64_t)order.size();
|
||||
if (finish_status == RAD_OK)
|
||||
for (int32_t k : order) {
|
||||
gen::AudioChunk c;
|
||||
c.window = k;
|
||||
for (int32_t j = 0; j < per_window; ++j) c.samples.push_back(sample(k, j));
|
||||
t.push(std::move(c));
|
||||
}
|
||||
t.finish(finish_status, finish_why);
|
||||
got.push_back(std::move(r));
|
||||
return RAD_OK;
|
||||
}
|
||||
int64_t queued() const override { return 0; }
|
||||
int64_t running() const override { return 0; }
|
||||
};
|
||||
|
||||
/* ================================================================== the scheduler */
|
||||
|
||||
struct FakeScheduler : IScheduler {
|
||||
|
||||
@@ -228,6 +228,40 @@ TEST(a_sharded_vector_is_a_slice_of_it) {
|
||||
CHECK_EQ(s[0].rects[0].bytes, (int64_t)(16 * 4));
|
||||
}
|
||||
|
||||
/* A rank-1 weight of stacked parts (a fused [value | gate] projection's bias) is cut like its
|
||||
* matrix: this rank's slice of each part. A contiguous slice would hand rank 0 every value bias
|
||||
* and rank 1 every gate bias. */
|
||||
TEST(a_stacked_vector_is_cut_in_every_part) {
|
||||
const RadEncoding e = rad_enc_plain(RAD_BF16);
|
||||
WeightInfo w;
|
||||
w.enc = e;
|
||||
w.enc_known = true;
|
||||
w.decl.shard = RAD_SHARD_ROW;
|
||||
w.decl.rank = 1;
|
||||
w.decl.shape[0] = 32;
|
||||
w.decl.n_row_parts = 2;
|
||||
w.decl.row_parts[0] = 16;
|
||||
w.decl.row_parts[1] = 16;
|
||||
w.n_sel = 1;
|
||||
w.sel[0] = 0;
|
||||
w.sel_rows[0] = 1;
|
||||
w.sel_cols[0] = 32;
|
||||
/* entry [64]: values 0..31, gates 32..63; rank 1 owns values 16..31 and gates 48..63 */
|
||||
const int64_t shape[1] = { 64 };
|
||||
PlaneShare s[RAD_ENC_MAX_PLANES];
|
||||
REQUIRE_EQ(weight_share(w, e, 1, shape, 2, 1, s, nullptr), RAD_OK);
|
||||
REQUIRE_EQ(s[0].rects.size(), (size_t)2);
|
||||
CHECK_EQ(s[0].rects[0].byte0, (int64_t)(16 * 2));
|
||||
CHECK_EQ(s[0].rects[0].bytes, (int64_t)(16 * 2));
|
||||
CHECK_EQ(s[0].rects[1].byte0, (int64_t)(48 * 2));
|
||||
CHECK_EQ(s[0].rects[1].bytes, (int64_t)(16 * 2));
|
||||
/* parts that do not sum to the rank's share are refused */
|
||||
w.decl.row_parts[1] = 8;
|
||||
std::string why;
|
||||
CHECK_EQ(weight_share(w, e, 1, shape, 2, 0, s, &why), RAD_E_SHAPE);
|
||||
CHECK(why.find("declared parts") != std::string::npos);
|
||||
}
|
||||
|
||||
/* A reshape: a conv kernel [O, C, T, H, W] declared as the [O, C*T*H*W] matrix it is. The bytes
|
||||
* do not move, so the share is the whole plane in the declared view; a shard of a reshape would
|
||||
* be a different cut, so it is refused. */
|
||||
|
||||
@@ -87,10 +87,11 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) {
|
||||
CHECK(keys.emplace(std::make_pair(p.arch_id, p.arch_quant), p.name).second);
|
||||
}
|
||||
const std::set<std::pair<std::string, std::string>> want = {
|
||||
{ "embeddinggemma2", "" }, { "gemma4", "" }, { "gemma4", "compressed-tensors" },
|
||||
{ "lfm2", "" }, { "llama", "" }, { "llama", "fp8_e4m3" }, { "qwen35", "" },
|
||||
{ "breeze", "" }, { "embeddinggemma2", "" }, { "gemma4", "" },
|
||||
{ "gemma4", "compressed-tensors" }, { "lfm2", "" }, { "llama", "" }, { "llama", "fp8_e4m3" },
|
||||
{ "qwen35", "" },
|
||||
{ "qwen35", "fp8_e4m3" }, { "qwen35moe", "fp8_e4m3" }, { "qwen3asr", "" },
|
||||
{ "qwen4exp", "" }, { "qwenimage21", "" } };
|
||||
{ "minimaxh3", "" }, { "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" } };
|
||||
std::set<std::pair<std::string, std::string>> got;
|
||||
for (const auto& [k, name] : keys) got.insert(k);
|
||||
if (got != want)
|
||||
|
||||
@@ -0,0 +1,367 @@
|
||||
/* tests/speech_stream_test.cpp -- vLLM-Omni's realtime speech session over a WebSocket
|
||||
* (core/server/speech_stream.cpp), against server_fakes.h's audio generator.
|
||||
*
|
||||
* These pin what the server owns: that text sent in pieces is spoken a sentence at a time in
|
||||
* order, each sentence's events around its audio, the audio the same bytes the POST route gives
|
||||
* for the same request, sent whole or as it is made and as PCM or WAV, the utterance's end, the
|
||||
* refusals that leave the session going, and a close that cancels the sentence being spoken.
|
||||
*/
|
||||
#include "server_fakes.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <cstring>
|
||||
#include <deque>
|
||||
#include <thread>
|
||||
|
||||
namespace {
|
||||
|
||||
/* A WebSocket the test plays the client of: what the session sends, text and binary, in order. */
|
||||
struct Conn : WsConn {
|
||||
std::mutex m;
|
||||
std::condition_variable cv;
|
||||
std::deque<std::string> in;
|
||||
bool hung_up = false;
|
||||
bool closed = false;
|
||||
int close_code = 0;
|
||||
std::vector<std::pair<std::string, bool>> out; /* (message, binary) */
|
||||
|
||||
bool read(std::string* msg, bool* binary) override {
|
||||
std::unique_lock<std::mutex> lk(m);
|
||||
cv.wait(lk, [&] { return !in.empty() || hung_up || closed; });
|
||||
if (in.empty()) return false;
|
||||
*msg = std::move(in.front());
|
||||
*binary = false;
|
||||
in.pop_front();
|
||||
return true;
|
||||
}
|
||||
bool send(const std::string& t) override { return put(t, false); }
|
||||
bool send_binary(const std::string& b) override { return put(b, true); }
|
||||
bool put(const std::string& t, bool binary) {
|
||||
std::lock_guard<std::mutex> lk(m);
|
||||
out.emplace_back(t, binary);
|
||||
cv.notify_all();
|
||||
return !closed;
|
||||
}
|
||||
void close(int code, const std::string&) override {
|
||||
std::lock_guard<std::mutex> lk(m);
|
||||
closed = true;
|
||||
close_code = code;
|
||||
cv.notify_all();
|
||||
}
|
||||
void client(const json& j) {
|
||||
std::lock_guard<std::mutex> lk(m);
|
||||
in.push_back(j.dump());
|
||||
cv.notify_all();
|
||||
}
|
||||
void hangup() {
|
||||
std::lock_guard<std::mutex> lk(m);
|
||||
hung_up = true;
|
||||
cv.notify_all();
|
||||
}
|
||||
/* The `nth` event of `type` (from 0), waiting for it; null when it does not come. */
|
||||
json wait_for(const std::string& type, size_t nth = 0, int timeout_ms = 10000) {
|
||||
std::unique_lock<std::mutex> lk(m);
|
||||
const auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms);
|
||||
for (;;) {
|
||||
size_t seen = 0;
|
||||
for (const auto& o : out) {
|
||||
if (o.second) continue;
|
||||
json j = json::parse(o.first);
|
||||
if (j.value("type", "") == type && seen++ == nth) return j;
|
||||
}
|
||||
if (cv.wait_until(lk, until) == std::cv_status::timeout) return json();
|
||||
}
|
||||
}
|
||||
bool wait_closed(int timeout_ms = 10000) {
|
||||
std::unique_lock<std::mutex> lk(m);
|
||||
return cv.wait_for(lk, std::chrono::milliseconds(timeout_ms), [&] { return closed; });
|
||||
}
|
||||
/* Every message so far: an event's type, or "#<bytes>" for a binary one. */
|
||||
std::vector<std::string> trace() {
|
||||
std::lock_guard<std::mutex> lk(m);
|
||||
std::vector<std::string> t;
|
||||
for (const auto& o : out)
|
||||
t.push_back(o.second ? "#" + std::to_string(o.first.size())
|
||||
: json::parse(o.first).value("type", ""));
|
||||
return t;
|
||||
}
|
||||
/* The binary messages between sentence `k`'s audio.start and audio.done, in order. */
|
||||
std::vector<std::string> frames(int64_t k) {
|
||||
std::lock_guard<std::mutex> lk(m);
|
||||
std::vector<std::string> f;
|
||||
bool in_k = false;
|
||||
for (const auto& o : out) {
|
||||
if (o.second) {
|
||||
if (in_k) f.push_back(o.first);
|
||||
continue;
|
||||
}
|
||||
const json j = json::parse(o.first);
|
||||
if (j.value("type", "") == "audio.start") in_k = j.value("sentence_index", -1) == k;
|
||||
if (j.value("type", "") == "audio.done") in_k = false;
|
||||
}
|
||||
return f;
|
||||
}
|
||||
};
|
||||
|
||||
/* A server over the fake generator with one session connected to it. */
|
||||
struct Stream {
|
||||
FakeAudioGen gen;
|
||||
std::unique_ptr<Fixture> f;
|
||||
Conn conn;
|
||||
std::thread route;
|
||||
Stream() {
|
||||
f.reset(new Fixture(Fixture::Tweak{ [this](ServerOptions& o, Deps& d) {
|
||||
d.audio = &gen;
|
||||
o.audio_model = true;
|
||||
} }));
|
||||
const SocketHandler* h = f->srv->router().socket_for("/v1/audio/speech/stream");
|
||||
REQUIRE(h != nullptr);
|
||||
route = std::thread([this, h] {
|
||||
HttpRequest q;
|
||||
q.method = "GET";
|
||||
q.path = "/v1/audio/speech/stream";
|
||||
(*h)(q, conn);
|
||||
});
|
||||
}
|
||||
~Stream() {
|
||||
conn.hangup();
|
||||
if (route.joinable()) route.join();
|
||||
}
|
||||
void config(json extra = json::object()) {
|
||||
json c = { { "type", "session.config" }, { "instructions", "calm" } };
|
||||
for (auto it = extra.begin(); it != extra.end(); ++it) c[it.key()] = it.value();
|
||||
conn.client(c);
|
||||
}
|
||||
void text(const std::string& t) { conn.client({ { "type", "input.text" }, { "text", t } }); }
|
||||
void done() { conn.client({ { "type", "input.done" } }); }
|
||||
/* The POST route's audio for the same request: the fake's samples, whatever the text. */
|
||||
std::string post_pcm() {
|
||||
json b = { { "input", "x" }, { "instructions", "calm" }, { "response_format", "pcm" } };
|
||||
HttpResponse r = f->post("/v1/audio/speech", b.dump());
|
||||
CHECK_EQ(r.status, 200);
|
||||
return r.body;
|
||||
}
|
||||
};
|
||||
|
||||
std::string joined(const std::vector<std::string>& v) {
|
||||
std::string s;
|
||||
for (const auto& x : v) s += x;
|
||||
return s;
|
||||
}
|
||||
|
||||
uint32_t le32(const std::string& s, size_t at) {
|
||||
uint32_t v = 0;
|
||||
std::memcpy(&v, s.data() + at, 4);
|
||||
return v;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* Text sent in pieces is spoken a sentence at a time, in order: each sentence an audio.start
|
||||
* naming it, its audio in one binary message (the bytes the POST route gives for the same
|
||||
* request), and an audio.done counting them; the utterance ends with session.done once its last
|
||||
* sentence, the text input.done flushed, is spoken. Each sentence is its own request, rendered
|
||||
* from the session's instructions. The session then takes the next utterance. */
|
||||
TEST(text_in_pieces_is_spoken_a_sentence_at_a_time) {
|
||||
Stream s;
|
||||
const std::string pcm = s.post_pcm();
|
||||
s.config();
|
||||
s.text("Hello wor");
|
||||
s.text("ld. How are ");
|
||||
s.text("you? Fine");
|
||||
s.done();
|
||||
const json end = s.conn.wait_for("session.done");
|
||||
REQUIRE(!end.is_null());
|
||||
CHECK_EQ(end.value("utterance_index", -1), 0);
|
||||
CHECK_EQ(end.value("total_sentences", -1), 3);
|
||||
const std::string n = "#" + std::to_string(pcm.size());
|
||||
CHECK(s.conn.trace() == std::vector<std::string>({ "audio.start", n, "audio.done",
|
||||
"audio.start", n, "audio.done",
|
||||
"audio.start", n, "audio.done",
|
||||
"session.done" }));
|
||||
const char* want[] = { "Hello world.", "How are you?", "Fine" };
|
||||
for (int k = 0; k < 3; ++k) {
|
||||
const json st = s.conn.wait_for("audio.start", (size_t)k);
|
||||
CHECK_EQ(st.value("sentence_index", -1), k);
|
||||
CHECK_EQ(st.value("sentence_text", ""), std::string(want[k]));
|
||||
CHECK_EQ(st.value("format", ""), std::string("pcm"));
|
||||
CHECK_EQ(st.value("sample_rate", 0), 8000);
|
||||
CHECK_EQ(st.value("channels", 0), 2);
|
||||
const json dn = s.conn.wait_for("audio.done", (size_t)k);
|
||||
CHECK_EQ(dn.value("total_bytes", -1), (int)pcm.size());
|
||||
CHECK_EQ(dn.value("error", true), false);
|
||||
CHECK(joined(s.conn.frames(k)) == pcm);
|
||||
}
|
||||
/* The POST request was the first; the sentences are the three after it. */
|
||||
REQUIRE_EQ(s.gen.n_got(), (size_t)4);
|
||||
CHECK_EQ(s.gen.prompt_of(1), std::string("<s>calm|Hello world."));
|
||||
CHECK_EQ(s.gen.prompt_of(2), std::string("<s>calm|How are you?"));
|
||||
CHECK_EQ(s.gen.prompt_of(3), std::string("<s>calm|Fine"));
|
||||
|
||||
s.text("Again.");
|
||||
s.done();
|
||||
const json next = s.conn.wait_for("session.done", 1);
|
||||
REQUIRE(!next.is_null());
|
||||
CHECK_EQ(next.value("utterance_index", -1), 1);
|
||||
CHECK_EQ(next.value("total_sentences", -1), 1);
|
||||
CHECK_EQ(s.conn.wait_for("audio.start", 3).value("sentence_index", -1), 0);
|
||||
CHECK(!s.conn.closed);
|
||||
}
|
||||
|
||||
/* With stream_audio the audio goes out as the generator makes it, in order however its pieces
|
||||
* arrive: here windows 1, 0, 2 become two messages, the first two windows and the third, which
|
||||
* together are the whole response's bytes. A WAV says its length in one message, and while it
|
||||
* streams opens with a header that states none. */
|
||||
TEST(audio_is_sent_whole_or_as_it_is_made_as_pcm_or_wav) {
|
||||
{
|
||||
Stream s;
|
||||
const std::string pcm = s.post_pcm();
|
||||
s.config({ { "stream_audio", true } });
|
||||
s.text("One.");
|
||||
s.done();
|
||||
REQUIRE(!s.conn.wait_for("session.done").is_null());
|
||||
const std::vector<std::string> f = s.conn.frames(0);
|
||||
CHECK_EQ(f.size(), (size_t)2);
|
||||
CHECK(joined(f) == pcm);
|
||||
CHECK_EQ(s.conn.wait_for("audio.done").value("total_bytes", -1), (int)pcm.size());
|
||||
}
|
||||
{
|
||||
Stream s;
|
||||
const std::string pcm = s.post_pcm();
|
||||
s.config({ { "response_format", "wav" } });
|
||||
s.text("One.");
|
||||
s.done();
|
||||
REQUIRE(!s.conn.wait_for("session.done").is_null());
|
||||
CHECK_EQ(s.conn.wait_for("audio.start").value("format", ""), std::string("wav"));
|
||||
const std::vector<std::string> f = s.conn.frames(0);
|
||||
REQUIRE_EQ(f.size(), (size_t)1);
|
||||
REQUIRE(f[0].size() == 44 + pcm.size());
|
||||
CHECK_EQ(f[0].substr(0, 4), std::string("RIFF"));
|
||||
CHECK_EQ(le32(f[0], 40), (uint32_t)pcm.size());
|
||||
CHECK(f[0].substr(44) == pcm);
|
||||
}
|
||||
{
|
||||
Stream s;
|
||||
const std::string pcm = s.post_pcm();
|
||||
s.config({ { "response_format", "wav" }, { "stream_audio", true } });
|
||||
s.text("One.");
|
||||
s.done();
|
||||
REQUIRE(!s.conn.wait_for("session.done").is_null());
|
||||
const std::vector<std::string> f = s.conn.frames(0);
|
||||
REQUIRE_EQ(f.size(), (size_t)3);
|
||||
CHECK_EQ(f[0].size(), (size_t)44);
|
||||
CHECK_EQ(le32(f[0], 40), 0xffffffffu);
|
||||
CHECK(f[1] + f[2] == pcm);
|
||||
CHECK_EQ(s.conn.wait_for("audio.done").value("total_bytes", -1), (int)(44 + pcm.size()));
|
||||
}
|
||||
}
|
||||
|
||||
/* A message the session cannot take is answered with an error naming it, and the session goes on:
|
||||
* text before any configuration, an unknown message type, the commitment text mode, a field the
|
||||
* configuration does not have (or the input in it), a bad granularity or format, a request field
|
||||
* the model refuses. A configuration refused is not applied; a later one is, and the text after it
|
||||
* is spoken. */
|
||||
TEST(a_speech_session_refuses_what_it_cannot_take_and_goes_on) {
|
||||
Stream s;
|
||||
size_t n = 0;
|
||||
auto refused = [&](const json& msg, const char* param, const char* says) {
|
||||
s.conn.client(msg);
|
||||
const json e = s.conn.wait_for("error", n++);
|
||||
REQUIRE(!e.is_null());
|
||||
if (param) CHECK_EQ(e.value("param", std::string()), std::string(param));
|
||||
const bool named = has(e.value("message", ""), says);
|
||||
CHECK(named);
|
||||
if (!named) std::fprintf(stderr, " error said: %s\n", e.value("message", "").c_str());
|
||||
};
|
||||
refused({ { "type", "input.text" }, { "text", "Hi." } }, nullptr, "session.config");
|
||||
refused({ { "type", "response.create" } }, "type", "response.create");
|
||||
refused({ { "type", "session.config" }, { "text_input_mode", "commitment" } },
|
||||
"text_input_mode", "commitment");
|
||||
refused({ { "type", "session.config" }, { "temperature", 0.5 } }, "temperature",
|
||||
"temperature");
|
||||
refused({ { "type", "session.config" }, { "input", "Hi." } }, "input", "input.text");
|
||||
refused({ { "type", "session.config" }, { "split_granularity", "word" } },
|
||||
"split_granularity", "clause");
|
||||
refused({ { "type", "session.config" }, { "response_format", "mp3" } }, "response_format",
|
||||
"pcm or wav");
|
||||
refused({ { "type", "session.config" }, { "instructions", "calm" }, { "guidance_scale", 0.5 } },
|
||||
"guidance_scale", "[1, 30]");
|
||||
refused({ { "type", "session.config" } }, "instructions", "instructions");
|
||||
/* None of it applied: text still waits for a configuration. */
|
||||
refused({ { "type", "input.done" } }, nullptr, "session.config");
|
||||
s.config({ { "split_granularity", "clause" } });
|
||||
s.text("Yes, no");
|
||||
s.done();
|
||||
REQUIRE(!s.conn.wait_for("session.done").is_null());
|
||||
CHECK_EQ(s.conn.wait_for("audio.start", 0).value("sentence_text", ""), std::string("Yes,"));
|
||||
CHECK_EQ(s.conn.wait_for("audio.start", 1).value("sentence_text", ""), std::string("no"));
|
||||
CHECK(!s.conn.closed);
|
||||
}
|
||||
|
||||
/* A sentence the generator refuses or fails is an error and an audio.done saying so; the next
|
||||
* sentence is spoken as usual. */
|
||||
TEST(a_failed_sentence_says_so_and_the_next_is_spoken) {
|
||||
Stream s;
|
||||
s.config();
|
||||
s.gen.finish_status = RAD_E_IO;
|
||||
s.gen.finish_why = "the vocoder ran out of memory";
|
||||
s.text("One. ");
|
||||
const json e = s.conn.wait_for("error");
|
||||
REQUIRE(!e.is_null());
|
||||
CHECK_EQ(e.value("message", ""), s.gen.finish_why);
|
||||
const json d = s.conn.wait_for("audio.done");
|
||||
REQUIRE(!d.is_null());
|
||||
CHECK_EQ(d.value("error", false), true);
|
||||
CHECK_EQ(d.value("total_bytes", -1), 0);
|
||||
s.gen.finish_status = RAD_OK;
|
||||
s.text("Two.");
|
||||
s.done();
|
||||
REQUIRE(!s.conn.wait_for("session.done").is_null());
|
||||
CHECK_EQ(s.conn.wait_for("audio.done", 1).value("error", true), false);
|
||||
/* A sentence too long for the model's prompt is refused by name before it runs. */
|
||||
s.text(std::string(80, 'a') + ".");
|
||||
s.done();
|
||||
const json e2 = s.conn.wait_for("error", 1);
|
||||
REQUIRE(!e2.is_null());
|
||||
CHECK_EQ(e2.value("param", std::string()), std::string("input"));
|
||||
CHECK(!s.conn.wait_for("session.done", 1).is_null());
|
||||
}
|
||||
|
||||
/* session.close ends the session at once: the sentence being spoken is cancelled and the socket
|
||||
* is closed normally. The admission place the session held comes back. */
|
||||
TEST(session_close_cancels_the_sentence_being_spoken) {
|
||||
Stream s;
|
||||
s.gen.hold = true;
|
||||
s.config();
|
||||
s.text("Hello there. More");
|
||||
REQUIRE(!s.conn.wait_for("audio.start").is_null());
|
||||
for (int i = 0; i < 1000 && s.gen.n_got() == 0; ++i)
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(2));
|
||||
REQUIRE_EQ(s.gen.n_got(), (size_t)1);
|
||||
CHECK_EQ(s.f->srv->in_flight(), (int64_t)1);
|
||||
s.conn.client({ { "type", "session.close" } });
|
||||
REQUIRE(s.conn.wait_closed());
|
||||
CHECK_EQ(s.conn.close_code, 1000);
|
||||
s.route.join();
|
||||
CHECK(s.gen.ticket_of(0)->cancel.load());
|
||||
CHECK_EQ(s.f->srv->in_flight(), (int64_t)0);
|
||||
CHECK(s.conn.wait_for("audio.done", 0, 100).is_null());
|
||||
}
|
||||
|
||||
/* A plain GET of the path is told it is a socket; a model that makes no audio refuses the session
|
||||
* and closes it. */
|
||||
TEST(the_speech_socket_wants_an_upgrade_and_an_audio_model) {
|
||||
Fixture text_model;
|
||||
CHECK_EQ(text_model.srv->router().call("GET", "/v1/audio/speech/stream").status, 426);
|
||||
Conn c;
|
||||
HttpRequest q;
|
||||
q.path = "/v1/audio/speech/stream";
|
||||
(*text_model.srv->router().socket_for("/v1/audio/speech/stream"))(q, c);
|
||||
CHECK(c.closed);
|
||||
CHECK_EQ(c.close_code, 1008);
|
||||
REQUIRE(!c.out.empty());
|
||||
CHECK(has(c.out.front().first, "audio generation model"));
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -0,0 +1,291 @@
|
||||
/* tests/speech_test.cpp -- OpenAI's speech API over an audio generator (core/server/audio_gen.cpp).
|
||||
*
|
||||
* The generator is faked (server_fakes.h: FakeAudioGen finishes every request on submit, its
|
||||
* windows out of order), so these pin what the server owns: which requests are refused and under
|
||||
* which field, the request it hands the generator (the prompt rendered from the template, the
|
||||
* length in frames, a seed a JavaScript client can read back), the samples as 16-bit PCM in a WAV
|
||||
* or raw, the windows put back in order, failures mapped to 400 or 500, and the two streamed forms
|
||||
* carrying the same samples as the whole response.
|
||||
*/
|
||||
#include "server_fakes.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
|
||||
struct Speech {
|
||||
FakeAudioGen gen;
|
||||
std::unique_ptr<Fixture> f;
|
||||
Speech() {
|
||||
f.reset(new Fixture(Fixture::Tweak{ [this](ServerOptions& o, Deps& d) {
|
||||
d.audio = &gen;
|
||||
o.audio_model = true;
|
||||
} }));
|
||||
}
|
||||
static json body(json extra = json::object()) {
|
||||
json b = { { "input", "la la" }, { "instructions", "pop" } };
|
||||
for (auto it = extra.begin(); it != extra.end(); ++it) b[it.key()] = it.value();
|
||||
return b;
|
||||
}
|
||||
HttpResponse post(const json& b) { return f->post("/v1/audio/speech", b.dump()); }
|
||||
/* A refusal's status and the field it names. */
|
||||
std::string refused(const json& b, int status = 400) {
|
||||
HttpResponse r = post(b);
|
||||
CHECK_EQ(r.status, status);
|
||||
return str_at(json::parse(r.body, nullptr, false)["error"], "param");
|
||||
}
|
||||
const gen::AudioRequest& last() const { return *gen.got.back(); }
|
||||
};
|
||||
|
||||
std::string header(const HttpResponse& r, const char* k) {
|
||||
for (const auto& [n, v] : r.headers)
|
||||
if (n == k) return v;
|
||||
return std::string();
|
||||
}
|
||||
|
||||
uint32_t le32(const std::string& s, size_t at) {
|
||||
uint32_t v = 0;
|
||||
std::memcpy(&v, s.data() + at, 4);
|
||||
return v;
|
||||
}
|
||||
|
||||
/* The PCM the fake's windows make, in window order: each sample clipped to [-1, 1], times 32767,
|
||||
* rounded to the nearest. */
|
||||
std::string expected_pcm(const FakeAudioGen& g) {
|
||||
std::string out;
|
||||
for (int32_t k = 0; k < (int32_t)g.order.size(); ++k)
|
||||
for (int32_t j = 0; j < g.per_window; ++j) {
|
||||
const float v = std::min(1.0f, std::max(-1.0f, FakeAudioGen::sample(k, j)));
|
||||
const int16_t q = (int16_t)std::lrint(v * 32767.0f);
|
||||
out.append((const char*)&q, 2);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ================================================================== refusals */
|
||||
|
||||
/* A request this deployment cannot serve is a 400 naming its field before anything is queued: an
|
||||
* unknown field, missing or blank lyrics or description, a format other than wav or pcm, a speed,
|
||||
* malformed stream fields, the two stream forms at once, events in a WAV, both lengths at once or
|
||||
* either out of range, steps or guidance out of range, a non-integer seed, a prompt over the
|
||||
* model's limit, and text the plugin refuses. */
|
||||
TEST(a_speech_request_that_cannot_be_served_names_its_field) {
|
||||
Speech s;
|
||||
CHECK_EQ(s.refused(Speech::body({ { "temperature", 1 } })), std::string("temperature"));
|
||||
CHECK_EQ(s.refused({ { "instructions", "pop" } }), std::string("input"));
|
||||
CHECK_EQ(s.refused(Speech::body({ { "input", " \n" } })), std::string("input"));
|
||||
CHECK_EQ(s.refused({ { "input", "la" } }), std::string("instructions"));
|
||||
CHECK_EQ(s.refused(Speech::body({ { "response_format", "mp3" } })),
|
||||
std::string("response_format"));
|
||||
CHECK_EQ(s.refused(Speech::body({ { "speed", 2.0 } })), std::string("speed"));
|
||||
CHECK_EQ(s.refused(Speech::body({ { "stream", "yes" } })), std::string("stream"));
|
||||
CHECK_EQ(s.refused(Speech::body({ { "stream_format", "ogg" } })), std::string("stream_format"));
|
||||
CHECK_EQ(s.refused(Speech::body({ { "stream", true }, { "stream_format", "audio" } })),
|
||||
std::string("stream"));
|
||||
CHECK_EQ(s.refused(Speech::body({ { "stream_format", "sse" }, { "response_format", "wav" } })),
|
||||
std::string("response_format"));
|
||||
CHECK_EQ(s.refused(Speech::body({ { "max_new_tokens", 10 }, { "duration", 1.0 } })),
|
||||
std::string("duration"));
|
||||
CHECK_EQ(s.refused(Speech::body({ { "max_new_tokens", 101 } })), std::string("max_new_tokens"));
|
||||
CHECK_EQ(s.refused(Speech::body({ { "max_new_tokens", 0 } })), std::string("max_new_tokens"));
|
||||
CHECK_EQ(s.refused(Speech::body({ { "duration", 4.5 } })), std::string("duration"));
|
||||
CHECK_EQ(s.refused(Speech::body({ { "num_inference_steps", 0 } })),
|
||||
std::string("num_inference_steps"));
|
||||
CHECK_EQ(s.refused(Speech::body({ { "guidance_scale", 0.5 } })), std::string("guidance_scale"));
|
||||
CHECK_EQ(s.refused(Speech::body({ { "seed", "7" } })), std::string("seed"));
|
||||
CHECK_EQ(s.refused(Speech::body({ { "input", std::string(80, 'a') } })), std::string("input"));
|
||||
CHECK_EQ(s.refused(Speech::body({ { "input", "REFUSE" } })), std::string("input"));
|
||||
CHECK_EQ(s.refused(Speech::body({ { "instructions", "REFUSE" } })),
|
||||
std::string("instructions"));
|
||||
CHECK(s.gen.got.empty());
|
||||
CHECK_EQ(s.f->srv->in_flight(), (int64_t)0);
|
||||
}
|
||||
|
||||
/* A model that makes no audio answers the route with a 501. */
|
||||
TEST(a_text_model_answers_the_speech_route_with_501) {
|
||||
Fixture f;
|
||||
CHECK_EQ(f.post("/v1/audio/speech", Speech::body().dump()).status, 501);
|
||||
}
|
||||
|
||||
/* ================================================================== the request */
|
||||
|
||||
/* The prompt is the template with each slot's text in it; the length is max_new_tokens frames, or
|
||||
* a duration rounded up to whole frames, or the model's longest; an absent or -1 seed is chosen
|
||||
* below 2^53 and read back in X-Seed. */
|
||||
TEST(the_generator_gets_the_rendered_prompt_the_length_and_a_readable_seed) {
|
||||
Speech s;
|
||||
HttpResponse r = s.post(Speech::body({ { "max_new_tokens", 40 }, { "seed", 9 },
|
||||
{ "num_inference_steps", 12 },
|
||||
{ "guidance_scale", 2.5 } }));
|
||||
CHECK_EQ(r.status, 200);
|
||||
const std::string want = "<s>pop|la la";
|
||||
REQUIRE(s.last().tokens.size() == want.size());
|
||||
for (size_t i = 0; i < want.size(); ++i)
|
||||
CHECK_EQ(s.last().tokens[i], (int32_t)(uint8_t)want[i]);
|
||||
CHECK_EQ(s.last().max_frames, (int64_t)40);
|
||||
CHECK_EQ(s.last().steps, 12);
|
||||
CHECK(std::fabs(s.last().cfg - 2.5f) < 1e-6f);
|
||||
CHECK_EQ(s.last().seed, (uint64_t)9);
|
||||
CHECK_EQ(header(r, "X-Seed"), std::string("9"));
|
||||
|
||||
CHECK_EQ(s.post(Speech::body({ { "duration", 1.01 } })).status, 200);
|
||||
CHECK_EQ(s.last().max_frames, (int64_t)26);
|
||||
CHECK_EQ(s.last().steps, 0);
|
||||
CHECK_EQ(s.post(Speech::body()).status, 200);
|
||||
CHECK_EQ(s.last().max_frames, (int64_t)100);
|
||||
for (const json& seed : { json(nullptr), json(-1) }) {
|
||||
HttpResponse q = s.post(Speech::body({ { "seed", seed } }));
|
||||
CHECK_EQ(q.status, 200);
|
||||
CHECK(s.last().seed < ((uint64_t)1 << 53));
|
||||
CHECK_EQ(header(q, "X-Seed"), std::to_string(s.last().seed));
|
||||
}
|
||||
CHECK_EQ(s.f->srv->in_flight(), (int64_t)0);
|
||||
}
|
||||
|
||||
/* A speech model declares a prompt without instructions and the unconditional branch's own
|
||||
* template: instructions become optional and pick the template, the unconditional prompt is
|
||||
* rendered from the same texts, and the denoiser's step count is refused (it has none). */
|
||||
TEST(a_speech_model_takes_optional_instructions_and_renders_its_unconditional_prompt) {
|
||||
Speech s;
|
||||
s.gen.inf.tmpl_plain = "<s>{input}";
|
||||
s.gen.inf.neg_tmpl = "<n>{input}";
|
||||
s.gen.inf.default_steps = 0;
|
||||
auto text = [](const std::vector<int32_t>& t) {
|
||||
std::string r;
|
||||
for (int32_t c : t) r += (char)c;
|
||||
return r;
|
||||
};
|
||||
CHECK_EQ(s.post({ { "input", "hi" } }).status, 200);
|
||||
CHECK_EQ(text(s.last().tokens), std::string("<s>hi"));
|
||||
CHECK_EQ(text(s.last().neg_tokens), std::string("<n>hi"));
|
||||
CHECK_EQ(s.post({ { "input", "hi" }, { "instructions", " " } }).status, 200);
|
||||
CHECK_EQ(text(s.last().tokens), std::string("<s>hi"));
|
||||
CHECK_EQ(s.post({ { "input", "hi" }, { "instructions", "calm" } }).status, 200);
|
||||
CHECK_EQ(text(s.last().tokens), std::string("<s>calm|hi"));
|
||||
CHECK_EQ(text(s.last().neg_tokens), std::string("<n>hi"));
|
||||
CHECK_EQ(s.refused({ { "input", "hi" }, { "num_inference_steps", 4 } }),
|
||||
std::string("num_inference_steps"));
|
||||
CHECK_EQ(s.refused({ { "input", "hi" }, { "instructions", 3 } }), std::string("instructions"));
|
||||
/* A music model's prompt has no unconditional template of its own. */
|
||||
Speech m;
|
||||
CHECK_EQ(m.post(Speech::body()).status, 200);
|
||||
CHECK(m.last().neg_tokens.empty());
|
||||
}
|
||||
|
||||
/* ================================================================== the response */
|
||||
|
||||
/* The whole piece: the windows in order whatever order they were played in, as a WAV whose header
|
||||
* states the rate, channels and length, or as the same samples raw. */
|
||||
TEST(the_whole_piece_is_a_wav_or_raw_pcm_in_window_order) {
|
||||
Speech s;
|
||||
const std::string pcm = expected_pcm(s.gen);
|
||||
HttpResponse r = s.post(Speech::body());
|
||||
CHECK_EQ(r.status, 200);
|
||||
CHECK_EQ(r.content_type, std::string("audio/wav"));
|
||||
REQUIRE(r.body.size() == 44 + pcm.size());
|
||||
CHECK_EQ(r.body.substr(0, 4), std::string("RIFF"));
|
||||
CHECK_EQ(le32(r.body, 4), (uint32_t)(36 + pcm.size()));
|
||||
CHECK_EQ(le32(r.body, 24), (uint32_t)8000);
|
||||
CHECK_EQ((int)(uint8_t)r.body[22], 2);
|
||||
CHECK_EQ(le32(r.body, 40), (uint32_t)pcm.size());
|
||||
CHECK(r.body.substr(44) == pcm);
|
||||
CHECK_EQ(header(r, "X-Audio-Sample-Rate"), std::string("8000"));
|
||||
CHECK_EQ(header(r, "X-Audio-Channels"), std::string("2"));
|
||||
|
||||
HttpResponse p = s.post(Speech::body({ { "response_format", "pcm" } }));
|
||||
CHECK_EQ(p.content_type, std::string("audio/pcm"));
|
||||
CHECK(p.body == pcm);
|
||||
}
|
||||
|
||||
/* stream_format audio sends a WAV header that states no length, then the samples; the bytes after
|
||||
* it are the whole response's. */
|
||||
TEST(a_raw_stream_carries_the_whole_responses_samples) {
|
||||
Speech s;
|
||||
const std::string pcm = expected_pcm(s.gen);
|
||||
HttpResponse r = s.post(Speech::body({ { "stream_format", "audio" } }));
|
||||
CHECK_EQ(r.status, 200);
|
||||
REQUIRE(r.streaming());
|
||||
CHECK_EQ(r.content_type, std::string("audio/wav"));
|
||||
const std::string all = drain(r);
|
||||
REQUIRE(all.size() == 44 + pcm.size());
|
||||
CHECK_EQ(le32(all, 4), 0xffffffffu);
|
||||
CHECK_EQ(le32(all, 40), 0xffffffffu);
|
||||
CHECK(all.substr(44) == pcm);
|
||||
CHECK_EQ(s.f->srv->in_flight(), (int64_t)0);
|
||||
|
||||
HttpResponse p = s.post(Speech::body({ { "stream_format", "audio" },
|
||||
{ "response_format", "pcm" } }));
|
||||
CHECK(drain(p) == pcm);
|
||||
}
|
||||
|
||||
/* stream true (or stream_format sse) sends speech.audio.delta events whose PCM, joined, is the
|
||||
* whole response's, then speech.audio.done with the prompt tokens in and the frames out. */
|
||||
TEST(an_event_stream_carries_the_samples_then_the_usage) {
|
||||
Speech s;
|
||||
const std::string pcm = expected_pcm(s.gen);
|
||||
for (const json& form : { json{ { "stream", true } }, json{ { "stream_format", "sse" } } }) {
|
||||
json b = Speech::body(form);
|
||||
b["max_new_tokens"] = 30;
|
||||
HttpResponse r = s.post(b);
|
||||
CHECK_EQ(r.status, 200);
|
||||
CHECK_EQ(r.content_type, std::string("text/event-stream"));
|
||||
const std::vector<json> ev = sse_events(drain(r));
|
||||
REQUIRE(ev.size() >= 2);
|
||||
std::string got;
|
||||
for (size_t i = 0; i + 1 < ev.size(); ++i) {
|
||||
CHECK_EQ(ev[i].value("type", ""), std::string("speech.audio.delta"));
|
||||
CHECK_EQ(ev[i].value("response_format", ""), std::string("pcm"));
|
||||
CHECK_EQ(ev[i].value("sample_rate", 0), 8000);
|
||||
CHECK_EQ(ev[i].value("channels", 0), 2);
|
||||
std::vector<uint8_t> b;
|
||||
CHECK(base64_decode(ev[i].value("audio", ""), &b));
|
||||
got.append(b.begin(), b.end());
|
||||
}
|
||||
CHECK(got == pcm);
|
||||
CHECK_EQ(ev.back().value("type", ""), std::string("speech.audio.done"));
|
||||
const json& u = ev.back()["usage"];
|
||||
CHECK_EQ(u.value("input_tokens", 0), (int)std::strlen("<s>pop|la la"));
|
||||
CHECK_EQ(u.value("output_tokens", 0), 30);
|
||||
CHECK_EQ(u.value("total_tokens", 0), (int)std::strlen("<s>pop|la la") + 30);
|
||||
}
|
||||
CHECK_EQ(s.f->srv->in_flight(), (int64_t)0);
|
||||
}
|
||||
|
||||
/* A refusal at submit is a 400 (the request can never run) or a 503; a failure while running is a
|
||||
* 400 or a 500 with the generator's reason, and on an event stream a speech.audio.error of the
|
||||
* same type. */
|
||||
TEST(a_generators_failure_is_a_400_or_a_500_streamed_or_not) {
|
||||
Speech s;
|
||||
s.gen.submit_status = RAD_E_INVAL;
|
||||
s.gen.submit_why = "too long for the cache";
|
||||
HttpResponse r = s.post(Speech::body());
|
||||
CHECK_EQ(r.status, 400);
|
||||
CHECK(has(r.body, "too long"));
|
||||
s.gen.submit_status = RAD_E_IO;
|
||||
CHECK_EQ(s.post(Speech::body()).status, 503);
|
||||
s.gen.submit_status = RAD_OK;
|
||||
CHECK_EQ(s.f->srv->in_flight(), (int64_t)0);
|
||||
|
||||
for (int st : { RAD_E_INVAL, RAD_E_IO }) {
|
||||
s.gen.finish_status = st;
|
||||
s.gen.finish_why = "the vocoder ran out of memory";
|
||||
HttpResponse q = s.post(Speech::body());
|
||||
CHECK_EQ(q.status, st == RAD_E_INVAL ? 400 : 500);
|
||||
const json e = json::parse(q.body, nullptr, false)["error"];
|
||||
CHECK_EQ(e.value("message", ""), s.gen.finish_why);
|
||||
const std::string type = st == RAD_E_INVAL ? "invalid_request_error" : "server_error";
|
||||
CHECK_EQ(e.value("type", ""), type);
|
||||
HttpResponse t = s.post(Speech::body({ { "stream", true } }));
|
||||
CHECK_EQ(t.status, 200);
|
||||
const std::vector<json> ev = sse_events(drain(t));
|
||||
REQUIRE(ev.size() == 1);
|
||||
CHECK_EQ(ev[0].value("type", ""), std::string("speech.audio.error"));
|
||||
CHECK_EQ(ev[0]["error"].value("type", ""), type);
|
||||
CHECK_EQ(ev[0]["error"].value("message", ""), s.gen.finish_why);
|
||||
}
|
||||
CHECK_EQ(s.f->srv->in_flight(), (int64_t)0);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -0,0 +1,113 @@
|
||||
/* tests/text_split_test.cpp -- sentences and clauses of text that arrives in pieces
|
||||
* (core/server/text_split.h), which the realtime speech session speaks one at a time.
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "server/text_split.h"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace rad::server;
|
||||
|
||||
namespace {
|
||||
|
||||
using Units = std::vector<std::string>;
|
||||
|
||||
/* The units of `text` given whole, the rest left pending (or taken too with `final`). */
|
||||
Units units(const std::string& text, TextSplit mode, bool final, std::string* rest = nullptr) {
|
||||
std::string p = text;
|
||||
Units u = take_text_units(&p, mode, final);
|
||||
if (rest) *rest = p;
|
||||
return u;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* A sentence ends at its stop once whitespace follows; the stop at the end of what has arrived
|
||||
* waits for the next piece, and the end of the input ends the last sentence however it ends. */
|
||||
TEST(a_sentence_ends_when_the_text_after_it_shows_it_did) {
|
||||
std::string rest;
|
||||
CHECK(units("Hello world. How are", TextSplit::Sentence, false, &rest) ==
|
||||
Units({ "Hello world." }));
|
||||
CHECK_EQ(rest, std::string("How are"));
|
||||
CHECK(units("Hello.", TextSplit::Sentence, false, &rest).empty());
|
||||
CHECK_EQ(rest, std::string("Hello."));
|
||||
CHECK(units("Hello. ", TextSplit::Sentence, false, &rest) == Units({ "Hello." }));
|
||||
CHECK(units("Hello world. How are", TextSplit::Sentence, true, &rest) ==
|
||||
Units({ "Hello world.", "How are" }));
|
||||
CHECK(rest.empty());
|
||||
CHECK(units("Wait! Is it?\nYes", TextSplit::Sentence, true) ==
|
||||
Units({ "Wait!", "Is it?", "Yes" }));
|
||||
}
|
||||
|
||||
/* What does not end a sentence: a decimal point, a common abbreviation, an initial. A run of
|
||||
* stops and closing quotes or brackets stays with its sentence. */
|
||||
TEST(decimals_abbreviations_and_initials_do_not_end_a_sentence) {
|
||||
CHECK(units("It costs 3.14 dollars. Then", TextSplit::Sentence, false) ==
|
||||
Units({ "It costs 3.14 dollars." }));
|
||||
CHECK(units("Dr. Smith and Mrs. Jones left. Then", TextSplit::Sentence, false) ==
|
||||
Units({ "Dr. Smith and Mrs. Jones left." }));
|
||||
CHECK(units("Fruit, e.g. apples, etc. is fine. Then", TextSplit::Sentence, false) ==
|
||||
Units({ "Fruit, e.g. apples, etc. is fine." }));
|
||||
CHECK(units("J.R. Tolkien and J. Smith wrote. Then", TextSplit::Sentence, false) ==
|
||||
Units({ "J.R. Tolkien and J. Smith wrote." }));
|
||||
CHECK(units("Really?! Yes... Fine.", TextSplit::Sentence, true) ==
|
||||
Units({ "Really?!", "Yes...", "Fine." }));
|
||||
CHECK(units("He said \"stop.\" Then (he left.) Done", TextSplit::Sentence, true) ==
|
||||
Units({ "He said \"stop.\"", "Then (he left.)", "Done" }));
|
||||
}
|
||||
|
||||
/* CJK, Indic and Arabic stops end a sentence at the next character, since those scripts put no
|
||||
* space after them; at the end of what has arrived they too wait. */
|
||||
TEST(cjk_indic_and_arabic_stops_need_no_space) {
|
||||
std::string rest;
|
||||
CHECK(units("你好。今天天气很好!我们", TextSplit::Sentence, false, &rest) ==
|
||||
Units({ "你好。", "今天天气很好!" }));
|
||||
CHECK_EQ(rest, std::string("我们"));
|
||||
CHECK(units("你好。", TextSplit::Sentence, false, &rest).empty());
|
||||
CHECK_EQ(rest, std::string("你好。"));
|
||||
CHECK(units("नमस्ते। आप कैसे हैं", TextSplit::Sentence, false) == Units({ "नमस्ते।" }));
|
||||
CHECK(units("مرحبا؟ كيف حالك", TextSplit::Sentence, false) == Units({ "مرحبا؟" }));
|
||||
CHECK(units("「好。」然后", TextSplit::Sentence, false) == Units({ "「好。」" }));
|
||||
}
|
||||
|
||||
/* Clauses also end at commas and semicolons, full-width and Arabic ones included; `none` never
|
||||
* cuts, and gives the whole text at the end. */
|
||||
TEST(clauses_cut_at_commas_and_none_never_cuts) {
|
||||
CHECK(units("one, two; three. four", TextSplit::Clause, true) ==
|
||||
Units({ "one,", "two;", "three.", "four" }));
|
||||
CHECK(units("one, two; three. four", TextSplit::Sentence, true) ==
|
||||
Units({ "one, two; three.", "four" }));
|
||||
CHECK(units("一,二;三", TextSplit::Clause, true) == Units({ "一,", "二;", "三" }));
|
||||
std::string rest;
|
||||
CHECK(units("One. Two. ", TextSplit::None, false, &rest).empty());
|
||||
CHECK_EQ(rest, std::string("One. Two. "));
|
||||
CHECK(units(" One. Two. ", TextSplit::None, true) == Units({ "One. Two." }));
|
||||
}
|
||||
|
||||
/* A unit with nothing to say is dropped, and blank input gives nothing. */
|
||||
TEST(a_unit_of_only_punctuation_is_dropped) {
|
||||
CHECK(units("... ok. !!", TextSplit::Sentence, true) == Units({ "ok." }));
|
||||
CHECK(units(" ", TextSplit::Sentence, true).empty());
|
||||
CHECK(units("", TextSplit::Clause, true).empty());
|
||||
}
|
||||
|
||||
/* Text fed a byte at a time (cutting UTF-8 sequences) gives the units it gives whole. */
|
||||
TEST(pieces_give_the_units_the_whole_text_gives) {
|
||||
const std::string text = "Dr. Who said 3.5 things. 你好。Then, \"yes!\" he left; ok. Done";
|
||||
for (TextSplit mode : { TextSplit::Sentence, TextSplit::Clause, TextSplit::None }) {
|
||||
const Units whole = units(text, mode, true);
|
||||
Units got;
|
||||
std::string p;
|
||||
for (char c : text) {
|
||||
p += c;
|
||||
for (std::string& u : take_text_units(&p, mode, false)) got.push_back(u);
|
||||
}
|
||||
for (std::string& u : take_text_units(&p, mode, true)) got.push_back(u);
|
||||
CHECK(got == whole);
|
||||
CHECK(!whole.empty());
|
||||
}
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -26,6 +26,7 @@
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cerrno>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
@@ -531,6 +532,81 @@ inline bool write_llama(const std::string& dir, const Llama& s) {
|
||||
return write_checkpoint(dir, c, ts);
|
||||
}
|
||||
|
||||
/* The tiny LLaMA as an int4 W4A16 release in compressed-tensors' pack-quantized form, as
|
||||
* llm-compressor writes it: every attention and MLP projection as X.weight_packed (the signed code
|
||||
* q plus 8, eight a word along K from the low bits), X.weight_scale (bf16, one per 128 of K) and,
|
||||
* with `asym`, X.weight_zero_point (the signed zero point plus 8, eight a word along N), the value
|
||||
* being (q - zero_point) * scale. Each scale is a power of two, so every value is exact in bf16 and
|
||||
* the release is the same numbers as a bf16 checkpoint of them. The head, the norms and the
|
||||
* embedding stay bf16, as such a release leaves them. */
|
||||
inline bool write_llama_ct_int4(const std::string& dir, const Llama& s, bool asym) {
|
||||
if (!write_llama(dir, s)) return false;
|
||||
std::vector<Tensor> in = read_safetensors(dir + "/model.safetensors"), out;
|
||||
const int64_t G = 128;
|
||||
for (Tensor& t : in) {
|
||||
const std::string sfx = "_proj.weight";
|
||||
if (t.name.size() < sfx.size() ||
|
||||
t.name.compare(t.name.size() - sfx.size(), sfx.size(), sfx) != 0) {
|
||||
out.push_back(std::move(t));
|
||||
continue;
|
||||
}
|
||||
const std::string base = t.name.substr(0, t.name.size() - 7);
|
||||
const int64_t N = t.shape[0], K = t.shape[1], ng = K / G;
|
||||
Tensor p{ base + ".weight_packed", "I32", { N, K / 8 }, {} };
|
||||
Tensor sc{ base + ".weight_scale", "BF16", { N, ng }, {} };
|
||||
Tensor zp{ base + ".weight_zero_point", "I32", { (N + 7) / 8, ng }, {} };
|
||||
p.bytes.assign((size_t)(N * K / 2), 0);
|
||||
sc.bytes.resize((size_t)(N * ng * 2));
|
||||
zp.bytes.assign((size_t)((N + 7) / 8 * ng * 4), 0);
|
||||
auto put = [](std::vector<uint8_t>& b, int64_t word, int nib, int v) {
|
||||
uint32_t w;
|
||||
std::memcpy(&w, b.data() + word * 4, 4);
|
||||
w |= (uint32_t)(v & 15) << (4 * nib);
|
||||
std::memcpy(b.data() + word * 4, &w, 4);
|
||||
};
|
||||
for (int64_t n = 0; n < N; ++n)
|
||||
for (int64_t g = 0; g < ng; ++g) {
|
||||
float lo = 0, hi = 0;
|
||||
for (int64_t k = g * G; k < (g + 1) * G; ++k) {
|
||||
const float v = rad_load_f32(t.bytes.data(), RAD_BF16, n * K + k);
|
||||
lo = std::min(lo, v);
|
||||
hi = std::max(hi, v);
|
||||
}
|
||||
const float span = asym ? (hi - lo) / 15.0f : std::max(-lo, hi) / 7.0f;
|
||||
const float scale = std::exp2(std::ceil(std::log2(std::max(span, 1e-20f))));
|
||||
const int z = asym ? std::clamp((int)std::lround(-lo / scale) - 8, -8, 7) : 0;
|
||||
rad_store_f32(sc.bytes.data(), RAD_BF16, n * ng + g, scale);
|
||||
if (asym) put(zp.bytes, (n / 8) * ng + g, (int)(n % 8), z + 8);
|
||||
for (int64_t k = g * G; k < (g + 1) * G; ++k) {
|
||||
const float v = rad_load_f32(t.bytes.data(), RAD_BF16, n * K + k);
|
||||
const int q = std::clamp((int)std::lround(v / scale) + z, -8, 7);
|
||||
put(p.bytes, n * (K / 8) + k / 8, (int)(k % 8), q + 8);
|
||||
}
|
||||
}
|
||||
out.push_back(std::move(p));
|
||||
out.push_back(std::move(sc));
|
||||
if (asym) out.push_back(std::move(zp));
|
||||
}
|
||||
nlohmann::ordered_json c = nlohmann::ordered_json::parse(read_text(dir + "/config.json"));
|
||||
c["quantization_config"] = {
|
||||
{ "quant_method", "compressed-tensors" }, { "format", "pack-quantized" },
|
||||
{ "config_groups",
|
||||
{ { "group_0",
|
||||
{ { "format", "pack-quantized" }, { "targets", { "Linear" } },
|
||||
{ "input_activations", nullptr },
|
||||
{ "weights",
|
||||
{ { "num_bits", 4 }, { "type", "int" }, { "symmetric", !asym },
|
||||
{ "strategy", "group" }, { "group_size", G }, { "dynamic", false },
|
||||
{ "actorder", asym ? nullptr : nlohmann::ordered_json("static") } } } } } } },
|
||||
{ "ignore", { "lm_head" } } };
|
||||
return write_text(dir + "/config.json", c.dump(2)) &&
|
||||
write_safetensors(dir + "/model.safetensors", out);
|
||||
}
|
||||
|
||||
/* The recipe that serves an int4 release on the 4-bit GEMMs: every imported grid unsigned with a
|
||||
* u4 zero plane and its scales in f16. */
|
||||
inline const char* kInt4ImportRecipe = "blk.*.weight import codes=u4 zero=u4 scale=f16\n";
|
||||
|
||||
/* ------------------------------------------------------------------ qwen3asr: speech to text */
|
||||
|
||||
/* Qwen3-ASR (`qwen3_asr`, served by qwen3asr_bf16 from the checkpoint as it ships): a Whisper-style
|
||||
@@ -635,6 +711,74 @@ inline bool write_qwen3asr(const std::string& dir, const Qwen3Asr& s) {
|
||||
write_text(dir + "/processor_config.json", fe.dump(2));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ PEFT LoRA adapters */
|
||||
|
||||
/* A PEFT LoRA adapter for the checkpoint a writer above put in `base`: every 2-D
|
||||
* `<module>.weight` whose leaf is in `targets` gets bf16 noise lora_A [r, in] and lora_B [out, r],
|
||||
* with adapter_config.json's `r` and `lora_alpha`. The delta (alpha / r) * B.A is about `gain`
|
||||
* times the weight's own spread. With `merged` set, the checkpoint with every delta folded in
|
||||
* (f32 sum, rounded to bf16) is written there too: what the adapter served at runtime must match
|
||||
* within rounding. */
|
||||
inline bool write_lora(const std::string& dir, const std::string& base,
|
||||
const std::vector<std::string>& targets, int64_t r, double alpha,
|
||||
uint64_t seed, float gain, const std::string& merged = "") {
|
||||
Rng rng(seed);
|
||||
std::vector<Tensor> ws = read_safetensors(base + "/model.safetensors");
|
||||
if (ws.empty()) return false;
|
||||
const float scale = (float)(alpha / (double)r);
|
||||
std::vector<Tensor> ad;
|
||||
nlohmann::ordered_json leaves = nlohmann::ordered_json::array();
|
||||
for (Tensor& w : ws) {
|
||||
const std::string sfx = ".weight";
|
||||
if (w.shape.size() != 2 || w.dtype != "BF16" || w.name.size() <= sfx.size() ||
|
||||
w.name.compare(w.name.size() - sfx.size(), sfx.size(), sfx) != 0)
|
||||
continue;
|
||||
const std::string module = w.name.substr(0, w.name.size() - sfx.size());
|
||||
const std::string leaf = module.substr(module.rfind('.') + 1);
|
||||
bool hit = false;
|
||||
for (const std::string& t : targets) hit = hit || t == leaf;
|
||||
if (!hit) continue;
|
||||
const int64_t n_out = w.shape[0], n_in = w.shape[1];
|
||||
Tensor A = noise("base_model.model." + module + ".lora_A.weight", { r, n_in }, rng,
|
||||
std::sqrt(3.0f / (float)n_in));
|
||||
Tensor B = noise("base_model.model." + module + ".lora_B.weight", { n_out, r }, rng,
|
||||
gain * std::sqrt(3.0f / (float)r) / scale);
|
||||
if (!merged.empty()) {
|
||||
for (int64_t o = 0; o < n_out; ++o)
|
||||
for (int64_t i = 0; i < n_in; ++i) {
|
||||
float d = 0.0f;
|
||||
for (int64_t j = 0; j < r; ++j)
|
||||
d += rad_load_f32(B.bytes.data(), RAD_BF16, o * r + j) *
|
||||
rad_load_f32(A.bytes.data(), RAD_BF16, j * n_in + i);
|
||||
const float v = rad_load_f32(w.bytes.data(), RAD_BF16, o * n_in + i);
|
||||
rad_store_f32(w.bytes.data(), RAD_BF16, o * n_in + i, v + scale * d);
|
||||
}
|
||||
}
|
||||
ad.push_back(std::move(A));
|
||||
ad.push_back(std::move(B));
|
||||
}
|
||||
for (const std::string& t : targets) leaves.push_back(t);
|
||||
nlohmann::ordered_json c;
|
||||
c["peft_type"] = "LORA";
|
||||
c["base_model_name_or_path"] = base;
|
||||
c["r"] = r;
|
||||
c["lora_alpha"] = alpha;
|
||||
c["target_modules"] = leaves;
|
||||
c["bias"] = "none";
|
||||
c["use_dora"] = false;
|
||||
c["use_rslora"] = false;
|
||||
c["modules_to_save"] = nullptr;
|
||||
if (ad.empty() || ::mkdir(dir.c_str(), 0755) != 0 ||
|
||||
!write_text(dir + "/adapter_config.json", c.dump(2)) ||
|
||||
!write_safetensors(dir + "/adapter_model.safetensors", ad))
|
||||
return false;
|
||||
if (merged.empty()) return true;
|
||||
return ::mkdir(merged.c_str(), 0755) == 0 &&
|
||||
write_text(merged + "/config.json", read_text(base + "/config.json")) &&
|
||||
write_text(merged + "/tokenizer.json", read_text(base + "/tokenizer.json")) &&
|
||||
write_safetensors(merged + "/model.safetensors", ws);
|
||||
}
|
||||
|
||||
/* The rad-convert recipe that makes llama_dense_fp8's linears block fp8, as
|
||||
* data/recipes/minicpm5-2b-dspark.recipe does for the trunk. */
|
||||
inline const char* kLlamaFp8Recipe =
|
||||
@@ -643,6 +787,14 @@ inline const char* kLlamaFp8Recipe =
|
||||
"blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16\n"
|
||||
"blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16\n";
|
||||
|
||||
/* The same trunk as OCP-MXFP4: e2m1 codes with an E8M0 exponent per 32 of K, read by gemm_nt_q at
|
||||
* mxfp4a8 against the E4M3 activation pair scaled per 128. */
|
||||
inline const char* kLlamaMxfp4Recipe =
|
||||
"blk.*.attn_qkv.weight rtn codes=fp4_e2m1 group=32 scale=e8m0\n"
|
||||
"blk.*.attn_output.weight rtn codes=fp4_e2m1 group=32 scale=e8m0\n"
|
||||
"blk.*.ffn_gate_up.weight rtn codes=fp4_e2m1 group=32 scale=e8m0\n"
|
||||
"blk.*.ffn_down.weight rtn codes=fp4_e2m1 group=32 scale=e8m0\n";
|
||||
|
||||
/* ------------------------------------------------------------------ Qwen-Image 2.1 */
|
||||
|
||||
/* Qwen-Image 2.1 (`QwenImage21Pipeline`, served by qwenimage21) as a diffusers pipeline directory:
|
||||
|
||||
@@ -101,10 +101,14 @@ double encode_seconds(const Tokenizer& t, const std::string& text, int runs = 5)
|
||||
}
|
||||
|
||||
/* The work of one encode, in radtest::Work's unit. Without an instruction counter the unit is CPU
|
||||
* time, which a busy machine inflates run to run, so the least of three runs is taken. */
|
||||
* time: a first, untimed run faults in the pages the encode uses (the counter does not count page
|
||||
* faults, see work_counter.h), and since a busy machine inflates CPU time run to run, the least of
|
||||
* three runs after it is taken. */
|
||||
uint64_t encode_work(const Tokenizer& t, const std::string& text) {
|
||||
std::vector<int32_t> ids;
|
||||
const int runs = radtest::work().exact() ? 1 : 3;
|
||||
const bool exact = radtest::work().exact();
|
||||
if (!exact) t.encode(text, ids, false, true);
|
||||
const int runs = exact ? 1 : 3;
|
||||
uint64_t best = UINT64_MAX;
|
||||
for (int r = 0; r < runs; ++r) {
|
||||
ids.clear();
|
||||
@@ -117,8 +121,9 @@ uint64_t encode_work(const Tokenizer& t, const std::string& text) {
|
||||
|
||||
/* Four times the text is about four times the work. The texts differ, so a cache of one cannot
|
||||
* help the other; the encoder's per-call word cache makes the larger one slightly cheaper per byte
|
||||
* (about x3.3). Counted in work, so the ratio does not depend on the machine's load or on where the
|
||||
* working set leaves the core's cache. */
|
||||
* (about x3.3). Counted in instructions, the ratio does not depend on the machine's load or on where
|
||||
* the working set leaves the core's cache. Counted in CPU time it does (about x4 with a 1 MiB L2,
|
||||
* more with less cache), so that bound is wider; both stay far below quadratic (x16). */
|
||||
TEST(encoding_work_is_linear_in_the_text) {
|
||||
auto v = vocab();
|
||||
REQUIRE(v != nullptr);
|
||||
@@ -130,14 +135,14 @@ TEST(encoding_work_is_linear_in_the_text) {
|
||||
std::fprintf(stderr, " 256 KB %llu, 1 MB %llu %s, ratio %.2f\n", (unsigned long long)a,
|
||||
(unsigned long long)b, radtest::work().unit(), (double)b / (double)a);
|
||||
CHECK((double)b / (double)a > 2.6);
|
||||
CHECK((double)b / (double)a < 4.6);
|
||||
CHECK((double)b / (double)a < (radtest::work().exact() ? 4.6 : 6.0));
|
||||
}
|
||||
|
||||
/* Inputs a splitter goes quadratic on. A backtracking `\s+(?!\S)` rescans a whitespace run from
|
||||
* every position in it, and a merge quadratic in word length shows on one huge word; both must
|
||||
* stay linear. 125 and 500 KB: linear is 4 (a whitespace run is x4.3), quadratic 16. Counted in CPU
|
||||
* time the larger text also pays for leaving the core's cache (x7.4 on a whitespace run with every
|
||||
* core busy), so that bound is wider; both stay far below quadratic. */
|
||||
* time the larger text also pays for leaving the core's cache (a whitespace run x4.6 to x5.5), so
|
||||
* that bound is wider; both stay far below quadratic. */
|
||||
TEST(pathological_inputs_stay_linear) {
|
||||
auto v = vocab();
|
||||
REQUIRE(v != nullptr);
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
/* video_gen_test.cpp -- the video generator's pass driver (core/gen/video_driver.h) and the
|
||||
* request shape and schedule it shares with the server (core/gen/video.h). The plugin's side of
|
||||
* each pass is played by the test: it writes the decode passes' outputs where the driver reads
|
||||
* them back, and a fake rad_arch_video_positions lays the rows out.
|
||||
*/
|
||||
#include "sched_fakes.h"
|
||||
|
||||
using namespace sched_fake;
|
||||
|
||||
#include "gen/video_driver.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace rad;
|
||||
|
||||
namespace {
|
||||
|
||||
/* Two frames a chunk and one more at the end, a latent frame a chunk and one more, two latent
|
||||
* frames a decode; 32-pixel sides to 64 x 64; 40 soundtrack latents a second at 800 Hz. */
|
||||
RadVideoGenDecl decl_small() {
|
||||
RadVideoGenDecl d{};
|
||||
d.max_text = 8;
|
||||
d.fps_num = 4;
|
||||
d.fps_den = 1;
|
||||
d.frames_per_chunk = 2;
|
||||
d.frames_tail = 1;
|
||||
d.latents_per_chunk = 1;
|
||||
d.latents_tail = 1;
|
||||
d.dec_latents = 2;
|
||||
d.min_chunks = 1;
|
||||
d.max_chunks = 3;
|
||||
d.latent_scale = 16;
|
||||
d.latent_channels = 4;
|
||||
d.patch = 2;
|
||||
d.size_multiple = 32;
|
||||
d.min_side = 32;
|
||||
d.max_area = 64 * 64;
|
||||
d.max_aspect = 2;
|
||||
d.default_width = 64;
|
||||
d.default_height = 32;
|
||||
d.default_chunks = 1;
|
||||
d.sample_rate = 800;
|
||||
d.audio_rate = 40;
|
||||
d.audio_channels = 2;
|
||||
d.audio_latent_channels = 4;
|
||||
d.default_steps = 3;
|
||||
d.max_steps = 5;
|
||||
d.shift_video = 12.0;
|
||||
d.shift_audio = 3.0;
|
||||
d.max_lanes = 2;
|
||||
d.frames_out = 1;
|
||||
d.audio_out = 2;
|
||||
return d;
|
||||
}
|
||||
|
||||
/* The packed layout's rows, each position the row's index; a decode pass, ten rows a frame. */
|
||||
int64_t fake_positions(int which, const RadVideoGeom* g, float* pos, int64_t cap) {
|
||||
const int64_t rows = g->n_text + 2 * (int64_t)g->n_audio +
|
||||
(int64_t)g->lat_frames * (g->lat_h / 2) * (g->lat_w / 2);
|
||||
if (which == RAD_VPOS_DECODE) return 10 * (int64_t)g->frames;
|
||||
if (pos) {
|
||||
if (cap < 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;
|
||||
}
|
||||
|
||||
struct VideoFixture {
|
||||
Program prog;
|
||||
gen::VideoDriver drv;
|
||||
void build() {
|
||||
prog.video_gen = decl_small();
|
||||
prog.vgen_str.name = "test";
|
||||
prog.vgen_str.tmpl = "{prompt}";
|
||||
prog.ctx.max_tok = 256;
|
||||
prog.ctx.max_seqs = 1;
|
||||
}
|
||||
int start() { return drv.init(prog, fake_positions, { gen::VideoDriver::RankIO{} }); }
|
||||
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 };
|
||||
r->width = 64;
|
||||
r->height = 32;
|
||||
r->chunks = chunks;
|
||||
r->steps = steps;
|
||||
r->seed = 7;
|
||||
r->ticket = std::make_shared<gen::VideoTicket>();
|
||||
return r;
|
||||
}
|
||||
/* The plugin's answer to a decode pass: each byte or sample its index plus `base`. */
|
||||
void answer(int base) {
|
||||
for (const gen::IPassDriver::Readback& rb : drv.readbacks()) {
|
||||
if (rb.buf == prog.video_gen.frames_out) {
|
||||
uint8_t* x = static_cast<uint8_t*>(rb.host);
|
||||
for (int64_t i = 0; i < rb.bytes; ++i) x[i] = (uint8_t)(base + i);
|
||||
} else {
|
||||
float* x = static_cast<float*>(rb.host);
|
||||
for (int64_t i = 0; i < rb.bytes / 4; ++i) x[i] = (float)(base + i);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
char kind_of(int gen) {
|
||||
switch (gen) {
|
||||
case RAD_GEN_PASS_VCOND: return 'C';
|
||||
case RAD_GEN_PASS_VSTEP: return 'S';
|
||||
case RAD_GEN_PASS_ADECODE: return 'A';
|
||||
case RAD_GEN_PASS_VDECODE: return 'D';
|
||||
default: return '?';
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* A request's shape: frames and latent frames from its chunks, the soundtrack's latents its length
|
||||
* at the soundtrack's rate (ties to even), the rows of a step. */
|
||||
TEST(a_request_shape_follows_the_declaration) {
|
||||
const RadVideoGenDecl d = decl_small();
|
||||
const gen::VideoShape s = gen::video_shape(d, 64, 32, 2);
|
||||
CHECK_EQ(s.frames, 5); /* 2 * 2 + 1 */
|
||||
CHECK_EQ(s.lat_frames, 3); /* 1 * 2 + 1 */
|
||||
CHECK_EQ(s.lat_h, 2);
|
||||
CHECK_EQ(s.lat_w, 4);
|
||||
CHECK_EQ(s.n_audio, 50); /* 5 frames at 4 a second, 40 latents a second */
|
||||
CHECK_EQ(s.video_rows, (int64_t)3 * 1 * 2);
|
||||
CHECK_EQ(s.audio_rows, (int64_t)100);
|
||||
/* MiniMax-H3's: 124 frames are 206.67 soundtrack latents, which round to 207. */
|
||||
RadVideoGenDecl h = d;
|
||||
h.fps_num = 24;
|
||||
h.frames_per_chunk = 17;
|
||||
h.frames_tail = 5;
|
||||
h.latents_per_chunk = 5;
|
||||
h.latents_tail = 2;
|
||||
const gen::VideoShape hs = gen::video_shape(h, 1344, 768, 7);
|
||||
CHECK_EQ(hs.frames, 124);
|
||||
CHECK_EQ(hs.lat_frames, 37);
|
||||
CHECK_EQ(hs.n_audio, 207);
|
||||
CHECK_EQ(hs.video_rows, (int64_t)37 * 24 * 42);
|
||||
}
|
||||
|
||||
/* The schedule: `steps` grid points from sigma 1 to 0, each shifted, one evaluation fewer; the
|
||||
* video's and the soundtrack's shifts give two schedules of the same length. */
|
||||
TEST(the_schedule_counts_grid_points_and_shifts_each_modality) {
|
||||
const RadVideoGenDecl d = decl_small();
|
||||
const gen::VideoSchedule s = gen::video_schedule(d, 50);
|
||||
REQUIRE_EQ(s.sig_v.size(), (size_t)50);
|
||||
REQUIRE_EQ(s.sig_a.size(), (size_t)50);
|
||||
CHECK_EQ(s.steps, 49);
|
||||
CHECK_EQ(s.sig_v.front(), 1.0f);
|
||||
CHECK_EQ(s.sig_v.back(), 0.0f);
|
||||
CHECK_EQ(s.sig_a.back(), 0.0f);
|
||||
for (size_t i = 1; i < s.sig_v.size(); ++i) {
|
||||
CHECK(s.sig_v[i] < s.sig_v[i - 1]);
|
||||
CHECK(s.sig_a[i] < s.sig_a[i - 1]);
|
||||
}
|
||||
/* A grid point past the middle is linspace's from the end: 1 - 30/49 there. */
|
||||
const double b = 1.0 - 30.0 / 49.0;
|
||||
CHECK(std::fabs(s.sig_v[30] - 12.0 * b / (1.0 + 11.0 * b)) < 1e-6);
|
||||
CHECK(std::fabs(s.sig_a[30] - 3.0 * b / (1.0 + 2.0 * b)) < 1e-6);
|
||||
CHECK_EQ(gen::video_schedule(d, 2).steps, 1);
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
TEST(a_trained_schedule_shifts_its_rungs_and_fixes_the_step_count) {
|
||||
static const double kRungs[] = { 0.999, 0.874, 0.749, 0.624, 0.5, 0.375, 0.25, 0.125 };
|
||||
RadVideoGenDecl d = decl_small();
|
||||
d.shift_video = 10.0;
|
||||
d.n_rungs = 8;
|
||||
d.rungs = kRungs;
|
||||
d.default_steps = d.max_steps = 9;
|
||||
const gen::VideoSchedule s = gen::video_schedule(d, 9);
|
||||
REQUIRE_EQ(s.sig_v.size(), (size_t)9);
|
||||
REQUIRE_EQ(s.sig_a.size(), (size_t)9);
|
||||
CHECK_EQ(s.steps, 8);
|
||||
CHECK_EQ(s.sig_v.back(), 0.0f);
|
||||
CHECK_EQ(s.sig_a.back(), 0.0f);
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
const float b = (float)kRungs[i];
|
||||
CHECK_EQ(s.sig_v[(size_t)i], (10.0f * b) / (1.0f + 9.0f * b));
|
||||
CHECK_EQ(s.sig_a[(size_t)i], (3.0f * b) / (1.0f + 2.0f * b));
|
||||
}
|
||||
CHECK_EQ(gen::video_schedule(d, 8).steps, 0);
|
||||
CHECK_EQ(gen::video_schedule(d, 50).steps, 0);
|
||||
|
||||
VideoFixture f;
|
||||
f.build();
|
||||
f.prog.video_gen = d;
|
||||
f.prog.video_gen.rungs = nullptr;
|
||||
f.prog.vgen_str.rungs.assign(kRungs, kRungs + 8);
|
||||
CHECK_OK(f.start());
|
||||
std::string why;
|
||||
CHECK_EQ(f.drv.submit(f.req(1, 5), &why), (int)RAD_E_INVAL);
|
||||
CHECK(has(why, "num_inference_steps must be 9"));
|
||||
why.clear();
|
||||
CHECK_OK(f.drv.submit(f.req(1, 0), &why));
|
||||
}
|
||||
|
||||
/* One request's passes: its prompt with the whole schedule, a step per evaluation (the first
|
||||
* naming itself the first, each with its two timesteps and sigmas and the packed rows' positions),
|
||||
* the soundtrack, then the chunks in order, the last one longer. The ticket carries the steps,
|
||||
* the soundtrack and the frames, in that order, then the end. */
|
||||
TEST(a_request_runs_prompt_steps_soundtrack_and_chunks_in_order) {
|
||||
VideoFixture f;
|
||||
f.build();
|
||||
CHECK_OK(f.start());
|
||||
std::string why;
|
||||
auto r = f.req(2);
|
||||
auto t = r->ticket;
|
||||
CHECK_OK(f.drv.submit(std::move(r), &why));
|
||||
CHECK_EQ(t->frames, 5);
|
||||
CHECK_EQ(t->steps, 2);
|
||||
std::string kinds;
|
||||
std::vector<int32_t> frames_out;
|
||||
for (int i = 0; i < 20; ++i) {
|
||||
const RadBatch* b = f.drv.next(i);
|
||||
if (!b) break;
|
||||
const RadVideoGenBatch* V = b->vgen_b;
|
||||
REQUIRE(V != nullptr);
|
||||
kinds += kind_of(b->gen);
|
||||
CHECK_EQ(V->geom.n_text, 3);
|
||||
CHECK_EQ(V->geom.frames, 5);
|
||||
if (b->gen == RAD_GEN_PASS_VCOND) {
|
||||
CHECK_EQ(b->n_tok, (int64_t)3);
|
||||
CHECK_EQ(V->n_steps, 2);
|
||||
} else if (b->gen == RAD_GEN_PASS_VSTEP) {
|
||||
CHECK_EQ(b->n_tok, (int64_t)(3 + 100 + 6));
|
||||
} else if (b->gen == RAD_GEN_PASS_VDECODE) {
|
||||
CHECK_EQ(b->n_tok, (int64_t)50);
|
||||
frames_out.push_back(V->n_frames_out);
|
||||
}
|
||||
f.answer(10 * i);
|
||||
CHECK_OK(f.drv.done());
|
||||
}
|
||||
CHECK_EQ(kinds, std::string("CSSADD"));
|
||||
CHECK(frames_out == std::vector<int32_t>({ 2, 3 }));
|
||||
std::string ev;
|
||||
gen::VideoEvent e;
|
||||
bool to = false;
|
||||
int32_t next_frame = 0;
|
||||
while (t->next(&e, 0, &to)) {
|
||||
ev += e.kind == gen::VideoEvent::STEP ? 's' : e.kind == gen::VideoEvent::AUDIO ? 'a' : 'f';
|
||||
if (e.kind == gen::VideoEvent::AUDIO) {
|
||||
CHECK_EQ(e.samples.size(), (size_t)(50 * 20 * 2));
|
||||
}
|
||||
if (e.kind == gen::VideoEvent::FRAMES) {
|
||||
CHECK_EQ(e.first, next_frame);
|
||||
CHECK_EQ(e.rgb.size(), (size_t)e.n * 64 * 32 * 3);
|
||||
next_frame += e.n;
|
||||
}
|
||||
}
|
||||
CHECK_EQ(ev, std::string("ssaff"));
|
||||
CHECK_EQ(next_frame, 5);
|
||||
CHECK_EQ(t->status(), (int)RAD_OK);
|
||||
}
|
||||
|
||||
/* A second request is conditioned while the first waits for its first step, and denoised once the
|
||||
* first has finished: requests are denoised one after another. */
|
||||
TEST(a_second_request_is_conditioned_early_and_denoised_after_the_first) {
|
||||
VideoFixture f;
|
||||
f.build();
|
||||
CHECK_OK(f.start());
|
||||
std::string why;
|
||||
CHECK_OK(f.drv.submit(f.req(1, 2), &why));
|
||||
CHECK_OK(f.drv.submit(f.req(1, 2), &why));
|
||||
std::string kinds;
|
||||
for (int i = 0; i < 20; ++i) {
|
||||
const RadBatch* b = f.drv.next(i);
|
||||
if (!b) break;
|
||||
kinds += kind_of(b->gen);
|
||||
f.answer(0);
|
||||
CHECK_OK(f.drv.done());
|
||||
}
|
||||
CHECK_EQ(kinds, std::string("CCSADSAD"));
|
||||
}
|
||||
|
||||
/* What can never run is refused at submit: an empty or long prompt, a size off the multiple,
|
||||
* below the least side, over the area or the aspect, a length outside the chunks, steps outside
|
||||
* 2..max. */
|
||||
TEST(a_request_that_cannot_run_is_refused_at_submit) {
|
||||
VideoFixture f;
|
||||
f.build();
|
||||
CHECK_OK(f.start());
|
||||
std::string why;
|
||||
auto refused = [&](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));
|
||||
};
|
||||
auto r = f.req();
|
||||
r->tokens.clear();
|
||||
refused(std::move(r), "prompt");
|
||||
r = f.req();
|
||||
r->tokens.assign(9, 1);
|
||||
refused(std::move(r), "1..8");
|
||||
r = f.req();
|
||||
r->width = 48;
|
||||
refused(std::move(r), "size");
|
||||
r = f.req();
|
||||
r->width = 96;
|
||||
r->height = 32;
|
||||
refused(std::move(r), "size");
|
||||
r = f.req();
|
||||
r->width = 64;
|
||||
r->height = 96;
|
||||
refused(std::move(r), "size");
|
||||
refused(f.req(4), "chunks");
|
||||
refused(f.req(0), "chunks");
|
||||
refused(f.req(1, 6), "num_inference_steps");
|
||||
refused(f.req(1, 1), "num_inference_steps");
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -0,0 +1,297 @@
|
||||
/* tests/videos_test.cpp -- OpenAI's video jobs over a video generator (core/server/videos.cpp).
|
||||
*
|
||||
* The generator is faked here: it finishes every request on submit with two steps, a soundtrack and
|
||||
* three small frames, so these pin what the server owns: which requests are refused and under which
|
||||
* field, the request it hands the generator (the prompt, the size from `size` or SGLang's
|
||||
* `target`, the length rounded up to whole chunks, the steps, a seed), the job's life seen through
|
||||
* the video object, the MP4 and thumbnail it serves, listing and deleting, and a failure reported
|
||||
* on the job.
|
||||
*/
|
||||
#include "server_fakes.h"
|
||||
|
||||
#include "gen/video.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
|
||||
namespace {
|
||||
|
||||
struct FakeVideoGen : IVideoGen {
|
||||
VideoGenInfo inf;
|
||||
int finish_status = RAD_OK;
|
||||
std::string finish_why;
|
||||
std::vector<std::unique_ptr<gen::VideoRequest>> got;
|
||||
mutable std::mutex got_m;
|
||||
|
||||
FakeVideoGen() {
|
||||
inf.name = "fake-video";
|
||||
inf.tmpl = "<v>{prompt}";
|
||||
inf.max_text = 64;
|
||||
inf.fps_num = 24;
|
||||
inf.fps_den = 1;
|
||||
inf.frames_per_chunk = 17;
|
||||
inf.frames_tail = 5;
|
||||
inf.min_chunks = 7;
|
||||
inf.max_chunks = 20;
|
||||
inf.size_multiple = 32;
|
||||
inf.min_side = 256;
|
||||
inf.max_area = 1344 * 768;
|
||||
inf.max_aspect = 4;
|
||||
inf.default_width = 1344;
|
||||
inf.default_height = 768;
|
||||
inf.default_chunks = 7;
|
||||
inf.sample_rate = 32000;
|
||||
inf.channels = 2;
|
||||
inf.default_steps = 50;
|
||||
inf.max_steps = 65;
|
||||
inf.max_lanes = 2;
|
||||
}
|
||||
const VideoGenInfo& info() const override { return inf; }
|
||||
int submit(std::unique_ptr<gen::VideoRequest> r, std::string*) override {
|
||||
std::lock_guard<std::mutex> lk(got_m);
|
||||
gen::VideoTicket& t = *r->ticket;
|
||||
/* Three frames of the request's size and a tenth of a second of sound, whatever it asked:
|
||||
* enough to make a file. */
|
||||
t.frames = 3;
|
||||
t.width = r->width;
|
||||
t.height = r->height;
|
||||
t.steps = 2;
|
||||
t.sample_rate = 32000;
|
||||
t.channels = 2;
|
||||
t.fps = 24.0;
|
||||
if (finish_status == RAD_OK) {
|
||||
for (int s = 1; s <= 2; ++s) {
|
||||
gen::VideoEvent e;
|
||||
e.kind = gen::VideoEvent::STEP;
|
||||
e.steps_done = s;
|
||||
t.push(std::move(e));
|
||||
}
|
||||
gen::VideoEvent a;
|
||||
a.kind = gen::VideoEvent::AUDIO;
|
||||
for (int i = 0; i < 3200; ++i) {
|
||||
a.samples.push_back(0.1f * (float)std::sin(i * 0.05));
|
||||
a.samples.push_back(-0.1f * (float)std::sin(i * 0.05));
|
||||
}
|
||||
t.push(std::move(a));
|
||||
gen::VideoEvent f;
|
||||
f.kind = gen::VideoEvent::FRAMES;
|
||||
f.first = 0;
|
||||
f.n = 3;
|
||||
f.rgb.resize((size_t)3 * r->width * r->height * 3);
|
||||
for (size_t i = 0; i < f.rgb.size(); ++i) f.rgb[i] = (uint8_t)(i * 7);
|
||||
t.push(std::move(f));
|
||||
}
|
||||
t.finish(finish_status, finish_why);
|
||||
got.push_back(std::move(r));
|
||||
return RAD_OK;
|
||||
}
|
||||
int64_t queued() const override { return 0; }
|
||||
int64_t running() const override { return 0; }
|
||||
const gen::VideoRequest& last() const {
|
||||
std::lock_guard<std::mutex> lk(got_m);
|
||||
return *got.back();
|
||||
}
|
||||
};
|
||||
|
||||
struct Videos {
|
||||
FakeVideoGen gen;
|
||||
std::unique_ptr<Fixture> f;
|
||||
Videos() {
|
||||
f.reset(new Fixture(Fixture::Tweak{ [this](ServerOptions& o, Deps& d) {
|
||||
d.videos = &gen;
|
||||
o.video_model = true;
|
||||
} }));
|
||||
}
|
||||
static json body(json extra = json::object()) {
|
||||
json b = { { "prompt", "a fox in the snow" }, { "size", "256x256" } };
|
||||
for (auto it = extra.begin(); it != extra.end(); ++it) b[it.key()] = it.value();
|
||||
return b;
|
||||
}
|
||||
HttpResponse create(const json& b) { return f->post("/v1/videos", b.dump()); }
|
||||
std::string refused(const json& b, int status = 400) {
|
||||
HttpResponse r = create(b);
|
||||
CHECK_EQ(r.status, status);
|
||||
return str_at(json::parse(r.body, nullptr, false)["error"], "param");
|
||||
}
|
||||
/* The job until it has finished, polled the way a client does. */
|
||||
json wait(const std::string& id) {
|
||||
json o;
|
||||
for (int i = 0; i < 400; ++i) {
|
||||
HttpResponse r = f->get(("/v1/videos/" + id).c_str());
|
||||
o = json::parse(r.body, nullptr, false);
|
||||
const std::string st = str_at(o, "status");
|
||||
if (st == "completed" || st == "failed") break;
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(25));
|
||||
}
|
||||
return o;
|
||||
}
|
||||
};
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* A request that cannot be served is a 400 naming its field before anything is queued. */
|
||||
TEST(a_video_request_that_cannot_be_served_names_its_field) {
|
||||
Videos v;
|
||||
CHECK_EQ(v.refused(Videos::body({ { "temperature", 1 } })), std::string("temperature"));
|
||||
CHECK_EQ(v.refused({ { "size", "256x256" } }), std::string("prompt"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "prompt", " \n" } })), std::string("prompt"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "size", "250x256" } })), std::string("size"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "size", "1344" } })), std::string("size"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "size", "4096x4096" } })), std::string("size"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "seconds", "16" } })), std::string("seconds"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "seconds", "-1" } })), std::string("seconds"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "num_inference_steps", 1 } })),
|
||||
std::string("num_inference_steps"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "num_inference_steps", 66 } })),
|
||||
std::string("num_inference_steps"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "input_reference", "file-1" } })),
|
||||
std::string("input_reference"));
|
||||
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"));
|
||||
CHECK_EQ(v.refused({ { "prompt", "p" }, { "target", { { "aspect_ratio", "wide" } } } }),
|
||||
std::string("target"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "target", { { "aspect_ratio", "16:9" } } } })),
|
||||
std::string("size"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "seconds", "5" },
|
||||
{ "target", { { "duration_seconds", 5 } } } })),
|
||||
std::string("seconds"));
|
||||
CHECK_EQ(v.gen.got.size(), (size_t)0);
|
||||
}
|
||||
|
||||
/* The request the generator gets: the prompt in the template (the template's text read with
|
||||
* special tokens, the prompt without), the size, the length in whole chunks rounded up from the
|
||||
* seconds asked, the steps and the seed. */
|
||||
TEST(the_generator_gets_the_size_the_chunks_and_the_steps) {
|
||||
Videos v;
|
||||
HttpResponse r = v.create(Videos::body({ { "seconds", "8" }, { "num_inference_steps", 20 },
|
||||
{ "seed", 11 } }));
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
const gen::VideoRequest& q = v.gen.last();
|
||||
std::string prompt;
|
||||
for (int32_t c : q.tokens) prompt += (char)c;
|
||||
CHECK_EQ(prompt, std::string("<v>a fox in the snow"));
|
||||
CHECK_EQ(q.width, 256);
|
||||
CHECK_EQ(q.height, 256);
|
||||
CHECK_EQ(q.chunks, 11); /* 8 s is 192 frames, 17 * 11 + 5 */
|
||||
CHECK_EQ(q.steps, 20);
|
||||
CHECK_EQ(q.seed, (uint64_t)11);
|
||||
json o = json::parse(r.body, nullptr, false);
|
||||
CHECK_EQ(str_at(o, "object"), std::string("video"));
|
||||
CHECK_EQ(str_at(o, "seconds"), std::string("8.00"));
|
||||
CHECK_EQ(str_at(o, "size"), std::string("256x256"));
|
||||
CHECK(str_at(o, "id").rfind("video_", 0) == 0);
|
||||
v.wait(str_at(o, "id"));
|
||||
|
||||
/* Five seconds is not a whole chunk: rounded up to 124 frames. Without a size, the canvas. */
|
||||
r = v.create({ { "prompt", "p" }, { "seconds", 5 } });
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
CHECK_EQ(v.gen.last().chunks, 7);
|
||||
CHECK_EQ(v.gen.last().width, 1344);
|
||||
CHECK_EQ(v.gen.last().height, 768);
|
||||
o = json::parse(r.body, nullptr, false);
|
||||
CHECK_EQ(str_at(o, "seconds"), std::string("5.17"));
|
||||
v.wait(str_at(o, "id"));
|
||||
|
||||
/* SGLang's target: the canvas over a ratio, its short edge and the length. */
|
||||
r = v.create({ { "prompt", "p" }, { "task", "t2va" }, { "conditions", json::array() },
|
||||
{ "target", { { "aspect_ratio", "9:16" }, { "short_edge", 768 },
|
||||
{ "duration_seconds", 10 } } } });
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
CHECK_EQ(v.gen.last().width, 768);
|
||||
CHECK_EQ(v.gen.last().height, 1344);
|
||||
CHECK_EQ(v.gen.last().chunks, 14); /* 240 frames: 17 * 14 + 5 = 243 */
|
||||
v.wait(str_at(json::parse(r.body, nullptr, false), "id"));
|
||||
}
|
||||
|
||||
/* A form is read as JSON's fields are (OpenAI's clients send the create call as one). */
|
||||
TEST(a_form_creates_a_video_too) {
|
||||
Videos v;
|
||||
HttpRequest q;
|
||||
q.method = "POST";
|
||||
q.path = "/v1/videos";
|
||||
q.form = { FormPart{ "prompt", "", "", "a boat" }, FormPart{ "size", "", "", "512x256" },
|
||||
FormPart{ "seconds", "", "", "6" } };
|
||||
HttpResponse r = v.f->srv->router().dispatch(q);
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
CHECK_EQ(v.gen.last().width, 512);
|
||||
CHECK_EQ(v.gen.last().height, 256);
|
||||
CHECK_EQ(v.gen.last().chunks, 9); /* 144 frames: 17 * 9 + 5 = 158 */
|
||||
v.wait(str_at(json::parse(r.body, nullptr, false), "id"));
|
||||
q.form.push_back(FormPart{ "input_reference", "cat.png", "image/png", "..." });
|
||||
CHECK_EQ(v.f->srv->router().dispatch(q).status, 400);
|
||||
}
|
||||
|
||||
/* The job's life: queued at once, completed with progress 100 and an expiry, the MP4 and its
|
||||
* first frame served; listing it, deleting it, and a 404 after. */
|
||||
TEST(a_video_job_completes_and_serves_its_file) {
|
||||
Videos v;
|
||||
HttpResponse r = v.create(Videos::body());
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
const std::string id = str_at(json::parse(r.body, nullptr, false), "id");
|
||||
json o = v.wait(id);
|
||||
if (str_at(o, "status") == "failed" && has(str_at(o["error"], "message"), "no libavcodec"))
|
||||
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);
|
||||
CHECK(o["completed_at"].is_number());
|
||||
CHECK(o["expires_at"].get<int64_t>() > o["completed_at"].get<int64_t>());
|
||||
CHECK(o["error"].is_null());
|
||||
HttpResponse c = v.f->get(("/v1/videos/" + id + "/content").c_str());
|
||||
REQUIRE_EQ(c.status, 200);
|
||||
CHECK_EQ(c.content_type, std::string("video/mp4"));
|
||||
REQUIRE(c.body.size() > 64);
|
||||
CHECK_EQ(c.body.substr(4, 4), std::string("ftyp"));
|
||||
/* The moov atom precedes the media data, so a player can start before the file has arrived. */
|
||||
CHECK(c.body.find("moov") < c.body.find("mdat"));
|
||||
HttpResponse th = v.f->get(("/v1/videos/" + id + "/content?variant=thumbnail").c_str());
|
||||
REQUIRE_EQ(th.status, 200);
|
||||
CHECK_EQ(th.content_type, std::string("image/webp"));
|
||||
CHECK_EQ(th.body.substr(0, 4), std::string("RIFF"));
|
||||
CHECK_EQ(v.f->get(("/v1/videos/" + id + "/content?variant=spritesheet").c_str()).status, 400);
|
||||
|
||||
HttpResponse r2 = v.create(Videos::body());
|
||||
const std::string id2 = str_at(json::parse(r2.body, nullptr, false), "id");
|
||||
v.wait(id2);
|
||||
json l = json::parse(v.f->get("/v1/videos").body, nullptr, false);
|
||||
CHECK_EQ(str_at(l, "object"), std::string("list"));
|
||||
REQUIRE_EQ(l["data"].size(), (size_t)2);
|
||||
CHECK_EQ(str_at(l["data"][0], "id"), id2); /* newest first */
|
||||
CHECK_EQ(str_at(l, "first_id"), id2);
|
||||
CHECK_EQ(str_at(l, "last_id"), id);
|
||||
l = json::parse(v.f->get(("/v1/videos?order=asc&limit=1&after=" + id).c_str()).body, nullptr,
|
||||
false);
|
||||
REQUIRE_EQ(l["data"].size(), (size_t)1);
|
||||
CHECK_EQ(str_at(l["data"][0], "id"), id2);
|
||||
CHECK(!l["has_more"].get<bool>());
|
||||
|
||||
HttpResponse d = v.f->srv->router().call("DELETE", "/v1/videos/" + id);
|
||||
REQUIRE_EQ(d.status, 200);
|
||||
json dj = json::parse(d.body, nullptr, false);
|
||||
CHECK_EQ(str_at(dj, "object"), std::string("video.deleted"));
|
||||
CHECK(dj["deleted"].get<bool>());
|
||||
CHECK_EQ(v.f->get(("/v1/videos/" + id).c_str()).status, 404);
|
||||
CHECK_EQ(v.f->get(("/v1/videos/" + id + "/content").c_str()).status, 404);
|
||||
}
|
||||
|
||||
/* A request the generator fails is a failed job carrying the reason. */
|
||||
TEST(a_failed_generation_is_a_failed_job_with_its_reason) {
|
||||
Videos v;
|
||||
v.gen.finish_status = RAD_E_STATE;
|
||||
v.gen.finish_why = "the engine stopped";
|
||||
HttpResponse r = v.create(Videos::body());
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
json o = v.wait(str_at(json::parse(r.body, nullptr, false), "id"));
|
||||
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"));
|
||||
}
|
||||
|
||||
/* Without a video model the routes are 501. */
|
||||
TEST(the_video_routes_are_501_without_a_video_model) {
|
||||
Fixture f;
|
||||
CHECK_EQ(f.post("/v1/videos", Videos::body().dump()).status, 501);
|
||||
CHECK_EQ(f.get("/v1/videos").status, 501);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
+17
-3
@@ -6,12 +6,20 @@
|
||||
* on it does not flake when other tests run beside it. Tests compare ratios of two counts, or a
|
||||
* count per item against a bound far from the failure it catches.
|
||||
*
|
||||
* Where the counter is refused (no PMU in a VM, perf_event_paranoid above 2), the fallback is the
|
||||
* thread's CPU time in nanoseconds, which still excludes time spent descheduled. exact() says
|
||||
* which is in use. A multiplexed counter is scaled by its enabled/running times.
|
||||
* Where the counter is refused (no PMU in a VM, perf_event_paranoid above 2, or a seccomp profile
|
||||
* that denies the call, as a container build's sandbox does), the fallback is the thread's CPU time
|
||||
* in nanoseconds, which still excludes time spent descheduled. exact() says which is in use. A
|
||||
* multiplexed counter is scaled by its enabled/running times.
|
||||
*
|
||||
* CPU time includes the kernel's, which the counter leaves out, and the largest kernel cost of a
|
||||
* run is faulting in fresh pages: by default the allocator hands a large freed block back to the
|
||||
* system, so every run of a big input pays for its pages again, several milliseconds on a
|
||||
* half-megabyte input. With the fallback in use the allocator keeps freed memory mapped, so a
|
||||
* repeated run reuses pages it already faulted in and its time is the work again.
|
||||
*/
|
||||
#pragma once
|
||||
#include <linux/perf_event.h>
|
||||
#include <malloc.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <time.h>
|
||||
@@ -36,6 +44,12 @@ public:
|
||||
a.exclude_hv = 1;
|
||||
a.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING;
|
||||
fd_ = (int)syscall(SYS_perf_event_open, &a, 0, -1, -1, 0);
|
||||
if (fd_ < 0) {
|
||||
/* Freed memory stays mapped: no trim of the heap's top, and blocks up to the largest
|
||||
* threshold glibc accepts (32 MiB) come from the heap rather than a fresh mapping. */
|
||||
mallopt(M_TRIM_THRESHOLD, 1 << 30);
|
||||
mallopt(M_MMAP_THRESHOLD, 32 << 20);
|
||||
}
|
||||
}
|
||||
~Work() {
|
||||
if (fd_ >= 0) close(fd_);
|
||||
|
||||
Reference in new issue
Block a user