Support DeepSeek V4 Flash Vision Experimental
This commit is contained in:
1 parent
7c18e738cd
commit
9bbe12e6b3
52 files changed
+4988
-100
No files matched your search
+1
-1
@@ -25,7 +25,7 @@ impl ModelPreferences {
|
||||
reasoning_mode: model.default_reasoning_mode(),
|
||||
speculative: SpeculativePreferences {
|
||||
glm_mtp: model == ModelChoice::Qwen38FlashNext,
|
||||
dspark_enabled: model == ModelChoice::DeepSeekV4Flash0731,
|
||||
dspark_enabled: model.supports_dspark(),
|
||||
..SpeculativePreferences::default()
|
||||
},
|
||||
ssd: SsdPreferences::default(),
|
||||
|
||||
+20
-1
@@ -964,6 +964,14 @@ mod tests {
|
||||
crate::model::ModelChoice::DeepSeekV4Flash0731,
|
||||
)
|
||||
.unwrap();
|
||||
let vision = database
|
||||
.create_session(
|
||||
project.id,
|
||||
"Vision",
|
||||
PermissionMode::Ai,
|
||||
crate::model::ModelChoice::DeepSeekV4FlashVision,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
database
|
||||
.connection
|
||||
@@ -973,10 +981,21 @@ mod tests {
|
||||
.connection
|
||||
.run_pending_migrations(MIGRATIONS)
|
||||
.unwrap();
|
||||
let sessions = &database.load_projects().unwrap()[0].sessions;
|
||||
assert_eq!(
|
||||
database.load_projects().unwrap()[0].sessions[0].model(),
|
||||
sessions
|
||||
.iter()
|
||||
.find(|session| session.id == existing.id)
|
||||
.unwrap()
|
||||
.model(),
|
||||
existing.model()
|
||||
);
|
||||
let downgraded = sessions
|
||||
.iter()
|
||||
.find(|session| session.id == vision.id)
|
||||
.unwrap();
|
||||
assert_eq!(downgraded.title, "Vision");
|
||||
assert_eq!(downgraded.model(), None);
|
||||
|
||||
for model in crate::model::MODEL_CHOICES {
|
||||
let session = database
|
||||
|
||||
+90
-10
@@ -1,3 +1,4 @@
|
||||
mod deepseek_vision;
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
mod ds4_sampling;
|
||||
mod gguf;
|
||||
@@ -216,6 +217,12 @@ const PRO: Shape = Shape {
|
||||
..DEEPSEEK_BASE
|
||||
};
|
||||
|
||||
const FLASH_VISION: Shape = Shape {
|
||||
model: ModelChoice::DeepSeekV4FlashVision,
|
||||
rms_epsilon: 1e-20,
|
||||
..FLASH_0731
|
||||
};
|
||||
|
||||
const GLM: Shape = Shape {
|
||||
model: ModelChoice::Glm52,
|
||||
family: ModelFamily::Glm,
|
||||
@@ -619,8 +626,13 @@ impl Model {
|
||||
messages: &[ChatTurn],
|
||||
reasoning: ReasoningMode,
|
||||
) -> Vec<i32> {
|
||||
self.tokenizer
|
||||
.encode_conversation(system, messages, reasoning)
|
||||
if self.shape.model == ModelChoice::DeepSeekV4FlashVision {
|
||||
self.tokenizer
|
||||
.encode_deepseek_vision_conversation(system, messages, reasoning)
|
||||
} else {
|
||||
self.tokenizer
|
||||
.encode_conversation(system, messages, reasoning)
|
||||
}
|
||||
}
|
||||
|
||||
fn render_history(
|
||||
@@ -1594,13 +1606,63 @@ impl Generator {
|
||||
if encoded_images.next().is_some() {
|
||||
return Err("vision encoder returned too many embeddings".into());
|
||||
}
|
||||
let tokens = self
|
||||
.executor
|
||||
.model()
|
||||
.render_conversation(system, &rendered, reasoning);
|
||||
// DS4 retains the generated token frontier when an authenticated
|
||||
// conversation appends a turn. Re-tokenizing the assistant's visible
|
||||
// text can change BPE boundaries and shift historical image blocks.
|
||||
let continuation = match (&self.executor, messages.split_last()) {
|
||||
(metal::Executor::DeepSeek(executor), Some((latest, history)))
|
||||
if executor.model().shape.model == ModelChoice::DeepSeekV4FlashVision
|
||||
&& (latest.user || latest.tool)
|
||||
&& !history.is_empty()
|
||||
&& self.executor.checkpoint_tag()
|
||||
== conversation_tag(ModelFamily::DeepSeek, system, reasoning, history) =>
|
||||
{
|
||||
let old_count = messages[..history.len()]
|
||||
.iter()
|
||||
.map(|turn| turn.content.matches(VISION_DATA_START).count())
|
||||
.sum::<usize>();
|
||||
executor
|
||||
.cached_vision_positions(&embeddings[..old_count])
|
||||
.map(|positions| {
|
||||
let mut tokens = self.executor.tokens().to_vec();
|
||||
let cursor = tokens.len();
|
||||
let latest = rendered.last().expect("latest turn exists");
|
||||
let tokenizer = &executor.model().tokenizer;
|
||||
tokens.extend(if latest.tool {
|
||||
tokenizer.encode_deepseek_vision_tool_continuation(latest, reasoning)
|
||||
} else {
|
||||
tokenizer.encode_deepseek_vision_continuation(
|
||||
&latest.content,
|
||||
reasoning,
|
||||
latest.skip_previous_eos,
|
||||
)
|
||||
});
|
||||
(tokens, cursor, positions)
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let (mut tokens, mut cursor, old_positions) = continuation.unwrap_or_else(|| {
|
||||
(
|
||||
self.executor
|
||||
.model()
|
||||
.render_conversation(system, &rendered, reasoning),
|
||||
0,
|
||||
Vec::new(),
|
||||
)
|
||||
});
|
||||
let mut overlays = Vec::with_capacity(embeddings.len());
|
||||
let mut cursor = 0_usize;
|
||||
for embedding in embeddings {
|
||||
for (index, mut embedding) in embeddings.into_iter().enumerate() {
|
||||
if let Some(&(start, count)) = old_positions.get(index)
|
||||
&& let metal::Executor::DeepSeek(executor) = &self.executor
|
||||
{
|
||||
let block = executor.layout_vision(&mut embedding, start)?;
|
||||
if tokens.get(start as usize..(start + count) as usize) != Some(block.as_slice()) {
|
||||
return Err("cached DeepSeek image token layout is invalid".into());
|
||||
}
|
||||
overlays.push((start, embedding));
|
||||
continue;
|
||||
}
|
||||
let count = embedding.tokens as usize;
|
||||
let relative = tokens[cursor..]
|
||||
.windows(count + 2)
|
||||
@@ -1612,6 +1674,17 @@ impl Generator {
|
||||
.all(|token| *token == VISION_IMAGE_TOKEN)
|
||||
})
|
||||
.ok_or("rendered prompt lost an image placeholder")?;
|
||||
if let metal::Executor::DeepSeek(executor) = &self.executor {
|
||||
let start = cursor + relative;
|
||||
let position =
|
||||
u32::try_from(start).map_err(|_| "image prompt position overflow")?;
|
||||
let block = executor.layout_vision(&mut embedding, position)?;
|
||||
let block_len = block.len();
|
||||
tokens.splice(start..start + count + 2, block);
|
||||
overlays.push((position, embedding));
|
||||
cursor = start + block_len;
|
||||
continue;
|
||||
}
|
||||
let start = cursor + relative + 1;
|
||||
overlays.push((
|
||||
u32::try_from(start).map_err(|_| "image prompt position overflow")?,
|
||||
@@ -1662,8 +1735,15 @@ impl Generator {
|
||||
tokens.len()
|
||||
));
|
||||
}
|
||||
let reused = self.executor.align_prompt(&tokens)?;
|
||||
self.executor.set_vision_overlays(overlays)?;
|
||||
let reused = if matches!(&self.executor, metal::Executor::DeepSeek(e) if e.model().shape.model == ModelChoice::DeepSeekV4FlashVision)
|
||||
{
|
||||
self.executor.set_vision_overlays(overlays)?;
|
||||
self.executor.align_prompt(&tokens)?
|
||||
} else {
|
||||
let reused = self.executor.align_prompt(&tokens)?;
|
||||
self.executor.set_vision_overlays(overlays)?;
|
||||
reused
|
||||
};
|
||||
self.metrics.kv_prefix_reused(reused);
|
||||
progress(self.executor.position(), self.executor.context(), None);
|
||||
let seed = settings.seed.unwrap_or(0x4453_3453_4552_5645);
|
||||
|
||||
@@ -0,0 +1,454 @@
|
||||
//! DeepSeek V4 Flash Vision-Exp image layout and prefill masks.
|
||||
//! Behavioral reference: DS4 0aaea5a238fb41a35106a551e73c8409dfb751ac.
|
||||
use image::{DynamicImage, ImageDecoder, ImageReader};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::io::Cursor;
|
||||
|
||||
pub(super) const SOURCE_REVISION: &[u8] = b"e46e16bf6035c6f317eb2ac7458eb0362926d402";
|
||||
pub(super) const START: i32 = 0;
|
||||
pub(super) const PAD: i32 = 1;
|
||||
pub(super) const IMAGE: i32 = 2;
|
||||
pub(super) const NEWLINE: i32 = 3;
|
||||
pub(super) const END: i32 = 4;
|
||||
|
||||
pub(super) struct Patches {
|
||||
pub values: Vec<f32>,
|
||||
pub fingerprint: [u8; 32],
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub content_width: u32,
|
||||
pub content_height: u32,
|
||||
pub grid_width: u32,
|
||||
pub grid_height: u32,
|
||||
}
|
||||
|
||||
pub(super) fn decode(encoded: &[u8]) -> Result<Patches, String> {
|
||||
if encoded.is_empty() || encoded.len() > 64 * 1024 * 1024 {
|
||||
return Err("image is empty or exceeds the 64 MiB encoded limit".into());
|
||||
}
|
||||
let reader = ImageReader::new(Cursor::new(encoded))
|
||||
.with_guessed_format()
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut decoder = reader.into_decoder().map_err(|e| e.to_string())?;
|
||||
let (width, height) = decoder.dimensions();
|
||||
if width == 0
|
||||
|| height == 0
|
||||
|| width > 16384
|
||||
|| height > 16384
|
||||
|| u64::from(width) * u64::from(height) > 64 * 1024 * 1024
|
||||
{
|
||||
return Err("invalid DeepSeek image dimensions".into());
|
||||
}
|
||||
let orientation = decoder.orientation().map_err(|e| e.to_string())?;
|
||||
let mut image = DynamicImage::from_decoder(decoder).map_err(|e| e.to_string())?;
|
||||
image.apply_orientation(orientation);
|
||||
let rgb = image.into_rgb8();
|
||||
preprocess(rgb.as_raw(), rgb.width(), rgb.height())
|
||||
}
|
||||
|
||||
fn grid_tokens(height: u32, width: u32) -> u32 {
|
||||
let h = (height / 14).div_ceil(3);
|
||||
let w = (width / 14).div_ceil(3);
|
||||
(h + h % 2) * (w + 1) + 2 + (h.div_ceil(2) * (w + 1) % 2) * 2
|
||||
}
|
||||
|
||||
fn resize_shape(height: u32, width: u32) -> Result<(u32, u32), String> {
|
||||
let mut pw = width.min(height * 8);
|
||||
let mut ph = height;
|
||||
if u64::from(pw) * u64::from(ph) < 147456 {
|
||||
let scale = (147456.0 / (f64::from(pw) * f64::from(ph))).sqrt();
|
||||
pw = ((f64::from(pw) * scale) as u32).max(1);
|
||||
ph = ((f64::from(ph) * scale) as u32).max(1);
|
||||
}
|
||||
let mut bw = pw.div_ceil(14) * 14;
|
||||
let mut bh = ph.div_ceil(14) * 14;
|
||||
let mut budget = 381;
|
||||
while grid_tokens(bh, bw) > 381 {
|
||||
if budget <= 4 {
|
||||
return Err("image cannot fit the DeepSeek vision token budget".into());
|
||||
}
|
||||
let ratio = f64::from(ph) / f64::from(pw);
|
||||
let mw = ((f64::from(budget) - 2.0) / ratio + 0.25).sqrt() - 0.5;
|
||||
let mh = mw * ratio;
|
||||
if mw < 1.0 {
|
||||
bw = 42;
|
||||
bh = (((budget - 2) / 2) & !1) * 42;
|
||||
} else if mh < 2.0 {
|
||||
bh = 84;
|
||||
bw = ((budget - 2) / 2 - 1) * 42;
|
||||
if bw <= 42 {
|
||||
return Err("image cannot fit the DeepSeek vision token budget".into());
|
||||
}
|
||||
} else {
|
||||
let mw = mw.floor() as u32;
|
||||
let mh = mh.floor() as u32 & !1;
|
||||
let scale =
|
||||
(f64::from(mw) * 42.0 / f64::from(pw)).min(f64::from(mh) * 42.0 / f64::from(ph));
|
||||
bw = (f64::from(pw) * scale / 14.0).floor() as u32 * 14;
|
||||
bh = (f64::from(ph) * scale / 14.0).floor() as u32 * 14;
|
||||
}
|
||||
if bw == 0 || bh == 0 {
|
||||
return Err("invalid DeepSeek resized image dimensions".into());
|
||||
}
|
||||
budget -= 1;
|
||||
}
|
||||
Ok((bh, bw))
|
||||
}
|
||||
|
||||
pub(super) fn preprocess(rgb: &[u8], width: u32, height: u32) -> Result<Patches, String> {
|
||||
if width == 0
|
||||
|| height == 0
|
||||
|| width > 16384
|
||||
|| height > 16384
|
||||
|| u64::from(width) * u64::from(height) > 64 * 1024 * 1024
|
||||
|| rgb.len() != width as usize * height as usize * 3
|
||||
{
|
||||
return Err("invalid DeepSeek image dimensions".into());
|
||||
}
|
||||
let (bh, bw) = resize_shape(height, width)?;
|
||||
if bw > 16384 || bh > 16384 || u64::from(bw) * u64::from(bh) > 64 * 1024 * 1024 {
|
||||
return Err("resized DeepSeek image exceeds the decoded image limits".into());
|
||||
}
|
||||
let (cw, ch, ox, oy) = if width >= height * 8 {
|
||||
(bw, bh, 0, 0)
|
||||
} else {
|
||||
let scale = (f64::from(bw) / f64::from(width)).min(f64::from(bh) / f64::from(height));
|
||||
let cw = (f64::from(width) * scale)
|
||||
.round_ties_even()
|
||||
.clamp(1.0, f64::from(bw)) as u32;
|
||||
let ch = (f64::from(height) * scale)
|
||||
.round_ties_even()
|
||||
.clamp(1.0, f64::from(bh)) as u32;
|
||||
(
|
||||
cw,
|
||||
ch,
|
||||
(f64::from(bw - cw) * 0.5).round_ties_even() as u32,
|
||||
(f64::from(bh - ch) * 0.5).round_ties_even() as u32,
|
||||
)
|
||||
};
|
||||
let mut canvas = vec![127.0_f32; bw as usize * bh as usize * 3];
|
||||
let offset = (oy as usize * bw as usize + ox as usize) * 3;
|
||||
super::metal::vision::resize_bicubic(rgb, width, height, &mut canvas[offset..], cw, ch, bw);
|
||||
for value in &mut canvas {
|
||||
*value = *value / 127.5 - 1.0;
|
||||
}
|
||||
let gw = bw / 14;
|
||||
let gh = bh / 14;
|
||||
let mut values = Vec::with_capacity(gw as usize * gh as usize * 588);
|
||||
for py in 0..gh {
|
||||
for px in 0..gw {
|
||||
for c in 0..3 {
|
||||
for y in 0..14 {
|
||||
for x in 0..14 {
|
||||
values.push(
|
||||
canvas[((py * 14 + y) as usize * bw as usize + (px * 14 + x) as usize)
|
||||
* 3
|
||||
+ c],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut hash = Sha256::new();
|
||||
hash.update(width.to_le_bytes());
|
||||
hash.update(height.to_le_bytes());
|
||||
hash.update(rgb);
|
||||
Ok(Patches {
|
||||
fingerprint: hash.finalize().into(),
|
||||
values,
|
||||
width,
|
||||
height,
|
||||
content_width: cw,
|
||||
content_height: ch,
|
||||
grid_width: gw,
|
||||
grid_height: gh,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) struct Layout {
|
||||
pub types: Vec<i32>,
|
||||
pub permutation: Vec<usize>,
|
||||
}
|
||||
|
||||
pub(super) fn layout(height: u32, width: u32, position: u32) -> Result<Layout, String> {
|
||||
if height == 0 || width == 0 {
|
||||
return Err("invalid DeepSeek image token grid".into());
|
||||
}
|
||||
let rows = u64::from(height) + u64::from(height % 2);
|
||||
let row_length = u64::from(width) + 1;
|
||||
let leading = 3 - position % 4;
|
||||
let trailing = ((rows / 2 * row_length) % 2) * 2;
|
||||
let count = u64::from(leading) + 2 + rows * row_length + trailing;
|
||||
if count > 384 {
|
||||
return Err("DeepSeek image token layout exceeds its model limit".into());
|
||||
}
|
||||
let mut types = vec![PAD; leading as usize];
|
||||
let mut permutation = Vec::with_capacity(height as usize * width as usize);
|
||||
types.push(START);
|
||||
for pair in 0..rows / 2 {
|
||||
for column in 0..row_length {
|
||||
for row in pair * 2..pair * 2 + 2 {
|
||||
if row < u64::from(height) && column < u64::from(width) {
|
||||
types.push(IMAGE);
|
||||
permutation.push((row * u64::from(width) + column) as usize);
|
||||
} else {
|
||||
types.push(if row < u64::from(height) {
|
||||
NEWLINE
|
||||
} else {
|
||||
PAD
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
types.extend(std::iter::repeat_n(PAD, trailing as usize));
|
||||
types.push(END);
|
||||
Ok(Layout { types, permutation })
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub(super) struct Span {
|
||||
pub block: usize,
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
}
|
||||
|
||||
pub(super) fn spans(tokens: &[i32], vocab: i32) -> Result<Vec<Span>, String> {
|
||||
let mut result = Vec::new();
|
||||
let mut cursor = 0;
|
||||
while cursor < tokens.len() {
|
||||
if (0..vocab).contains(&tokens[cursor]) {
|
||||
cursor += 1;
|
||||
continue;
|
||||
}
|
||||
let block = cursor;
|
||||
while cursor < tokens.len() && tokens[cursor] == vocab + PAD {
|
||||
cursor += 1;
|
||||
}
|
||||
if tokens.get(cursor) != Some(&(vocab + START)) {
|
||||
return Err("malformed DeepSeek image block".into());
|
||||
}
|
||||
let start = cursor;
|
||||
cursor += 1;
|
||||
loop {
|
||||
let token = *tokens
|
||||
.get(cursor)
|
||||
.ok_or("unterminated DeepSeek image block")?;
|
||||
if token <= vocab + START || token > vocab + END {
|
||||
return Err("malformed DeepSeek image block".into());
|
||||
}
|
||||
if token == vocab + END {
|
||||
break;
|
||||
}
|
||||
cursor += 1;
|
||||
}
|
||||
result.push(Span {
|
||||
block,
|
||||
start,
|
||||
end: cursor,
|
||||
});
|
||||
cursor += 1;
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub(super) fn prefill_chunk(tokens: &[i32], vocab: i32, cap: u32) -> Result<usize, String> {
|
||||
let mut limit = tokens.len().min(cap as usize);
|
||||
if limit == 0 {
|
||||
return Err("empty DeepSeek prefill chunk".into());
|
||||
}
|
||||
for span in spans(tokens, vocab)? {
|
||||
if span.block >= limit {
|
||||
break;
|
||||
}
|
||||
if span.end + 1 > limit {
|
||||
if span.end + 1 > cap as usize {
|
||||
if span.block == 0 {
|
||||
return Err("DeepSeek image block exceeds prefill capacity".into());
|
||||
}
|
||||
limit = span.block;
|
||||
break;
|
||||
}
|
||||
limit = span.end + 1;
|
||||
}
|
||||
}
|
||||
Ok(limit)
|
||||
}
|
||||
|
||||
pub(super) fn attention_bounds(
|
||||
tokens: &[i32],
|
||||
vocab: i32,
|
||||
pos: u32,
|
||||
n_raw: u32,
|
||||
window: u32,
|
||||
) -> Result<Vec<u32>, String> {
|
||||
let end = pos
|
||||
.checked_add(
|
||||
tokens
|
||||
.len()
|
||||
.try_into()
|
||||
.map_err(|_| "vision attention length overflow")?,
|
||||
)
|
||||
.ok_or("vision attention position overflow")?;
|
||||
if tokens.is_empty() || n_raw == 0 || n_raw > end {
|
||||
return Err("invalid DeepSeek vision attention extent".into());
|
||||
}
|
||||
let first = end - n_raw;
|
||||
let mut bounds = Vec::with_capacity(tokens.len() * 2);
|
||||
for q in 0..tokens.len() as u32 {
|
||||
let p = pos + q;
|
||||
bounds.extend([
|
||||
first.max(if window == 0 {
|
||||
0
|
||||
} else {
|
||||
(p + 1).saturating_sub(window)
|
||||
}),
|
||||
p.min(end - 1),
|
||||
]);
|
||||
}
|
||||
for span in spans(tokens, vocab)? {
|
||||
for q in span.start..=span.end {
|
||||
let p = pos + q as u32;
|
||||
let left = (q - span.start).min(383) as u32;
|
||||
let right = (span.end - q).min(384) as u32;
|
||||
let add = if window != 0 && left >= window {
|
||||
left - (window - 1)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
bounds[2 * q] = first.max(if window == 0 {
|
||||
0
|
||||
} else {
|
||||
p.saturating_sub(window - 1 + add)
|
||||
});
|
||||
bounds[2 * q + 1] = (p + right).min(end - 1);
|
||||
}
|
||||
}
|
||||
Ok(bounds)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn issue100_ds4_image_layout_and_attention_vectors() {
|
||||
for (h, w, p, types, perm) in [
|
||||
(
|
||||
2,
|
||||
3,
|
||||
0,
|
||||
vec![1, 1, 1, 0, 2, 2, 2, 2, 2, 2, 3, 3, 4],
|
||||
vec![0, 3, 1, 4, 2, 5],
|
||||
),
|
||||
(
|
||||
3,
|
||||
2,
|
||||
5,
|
||||
vec![1, 1, 0, 2, 2, 2, 2, 3, 3, 2, 1, 2, 1, 3, 1, 4],
|
||||
vec![0, 2, 1, 3, 4, 5],
|
||||
),
|
||||
(1, 1, 3, vec![0, 2, 1, 3, 1, 4], vec![0]),
|
||||
] {
|
||||
let actual = layout(h, w, p).unwrap();
|
||||
assert_eq!(actual.types, types);
|
||||
assert_eq!(actual.permutation, perm);
|
||||
}
|
||||
let tokens = [7, 101, 101, 100, 102, 103, 104, 8, 100, 101, 104, 9];
|
||||
assert_eq!(
|
||||
spans(&tokens, 100).unwrap(),
|
||||
vec![
|
||||
Span {
|
||||
block: 1,
|
||||
start: 3,
|
||||
end: 6
|
||||
},
|
||||
Span {
|
||||
block: 8,
|
||||
start: 8,
|
||||
end: 10
|
||||
}
|
||||
]
|
||||
);
|
||||
assert_eq!(prefill_chunk(&tokens, 100, 5).unwrap(), 1);
|
||||
assert_eq!(prefill_chunk(&tokens[1..], 100, 6).unwrap(), 6);
|
||||
assert!(prefill_chunk(&tokens[1..], 100, 5).is_err());
|
||||
assert!(prefill_chunk(&tokens[4..], 100, 8).is_err());
|
||||
for malformed in [
|
||||
[101, 4, 5, 6],
|
||||
[100, 4, 104, 6],
|
||||
[100, 100, 104, 6],
|
||||
[100, 102, 6, 7],
|
||||
[100, 105, 6, 7],
|
||||
[-1, 100, 104, 6],
|
||||
] {
|
||||
assert!(spans(&malformed, 100).is_err());
|
||||
}
|
||||
assert_eq!(
|
||||
attention_bounds(
|
||||
&[7, 101, 100, 102, 102, 102, 102, 102, 104, 8],
|
||||
100,
|
||||
10,
|
||||
20,
|
||||
4
|
||||
)
|
||||
.unwrap(),
|
||||
vec![
|
||||
7, 10, 8, 11, 9, 18, 10, 18, 11, 18, 12, 18, 12, 18, 12, 18, 12, 18, 16, 19
|
||||
]
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn issue100_ds4_preprocess_dimensions_and_limits() {
|
||||
let mut rgb = Vec::new();
|
||||
for y in 0..9 {
|
||||
for x in 0..17 {
|
||||
rgb.extend([
|
||||
(x * 13 + y * 3) as u8,
|
||||
(x * 5 + y * 17) as u8,
|
||||
(x * 7 + y * 11) as u8,
|
||||
]);
|
||||
}
|
||||
}
|
||||
let p = preprocess(&rgb, 17, 9).unwrap();
|
||||
assert_eq!(
|
||||
(
|
||||
p.grid_width,
|
||||
p.grid_height,
|
||||
p.content_width,
|
||||
p.content_height
|
||||
),
|
||||
(38, 20, 529, 280)
|
||||
);
|
||||
assert_eq!(p.values.len(), 760 * 588);
|
||||
assert!(
|
||||
p.values
|
||||
.iter()
|
||||
.all(|v| v.is_finite() && (-1.0..=1.0).contains(v))
|
||||
);
|
||||
for (h, w) in [
|
||||
(1, 1),
|
||||
(1, 8),
|
||||
(1, 16384),
|
||||
(16384, 1),
|
||||
(384, 384),
|
||||
(1024, 1024),
|
||||
(1080, 1920),
|
||||
(4096, 4096),
|
||||
] {
|
||||
let (bh, bw) = resize_shape(h, w).unwrap();
|
||||
assert!(grid_tokens(bh, bw) <= 381);
|
||||
for start in 0..4 {
|
||||
assert!(
|
||||
layout((bh / 14).div_ceil(3), (bw / 14).div_ceil(3), start)
|
||||
.unwrap()
|
||||
.types
|
||||
.len()
|
||||
<= 384
|
||||
);
|
||||
}
|
||||
}
|
||||
assert!(preprocess(&[], 0, 1).is_err());
|
||||
assert!(layout(384, 384, 0).is_err());
|
||||
}
|
||||
}
|
||||
+236
-47
@@ -1,4 +1,5 @@
|
||||
mod checkpoint;
|
||||
mod deepseek_vision;
|
||||
mod glm;
|
||||
mod gpu;
|
||||
mod hotlist;
|
||||
@@ -9,7 +10,7 @@ mod qwen;
|
||||
mod qwen_mtplx_tests;
|
||||
// Whole-turn BF16 backend; never mix its state with legacy FP32 scratch.
|
||||
mod qwen_mtplx;
|
||||
mod vision;
|
||||
pub(super) mod vision;
|
||||
pub(super) use vision::VisionEmbedding;
|
||||
|
||||
use glm::GlmExecutor;
|
||||
@@ -108,7 +109,7 @@ fn environment_present(name: &CStr) -> bool {
|
||||
!unsafe { getenv(name.as_ptr()) }.is_null()
|
||||
}
|
||||
|
||||
const SOURCES: [(&str, &str); 25] = [
|
||||
const SOURCES: [(&str, &str); 26] = [
|
||||
("DS4_METAL_FLASH_ATTN_SOURCE", "flash_attn.metal"),
|
||||
("DS4_METAL_DENSE_SOURCE", "dense.metal"),
|
||||
("DS4_METAL_MOE_SOURCE", "moe.metal"),
|
||||
@@ -130,6 +131,10 @@ const SOURCES: [(&str, &str); 25] = [
|
||||
("DS4_METAL_SET_ROWS_SOURCE", "set_rows.metal"),
|
||||
("DS4_METAL_GLM53_BF16_SOURCE", "glm53_bf16.metal"),
|
||||
("DS4_METAL_GLM53_VISION_SOURCE", "glm53_vision.metal"),
|
||||
(
|
||||
"DS4_METAL_DEEPSEEK4_VISION_SOURCE",
|
||||
"deepseek4_vision.metal",
|
||||
),
|
||||
("DS4_METAL_GLM53_KDA_SOURCE", "glm53_kda.metal"),
|
||||
("DS4_METAL_QWEN38_SOURCE", "qwen38.metal"),
|
||||
("DS4_METAL_MTPLX_QWEN_SOURCE", "mtplx_qwen.metal"),
|
||||
@@ -2409,7 +2414,7 @@ impl SsdPlan {
|
||||
}
|
||||
let mut loaded = 0_u32;
|
||||
let hotlist = match model.shape.model {
|
||||
ModelChoice::DeepSeekV4Flash0731 => hotlist::FLASH,
|
||||
ModelChoice::DeepSeekV4Flash0731 | ModelChoice::DeepSeekV4FlashVision => hotlist::FLASH,
|
||||
ModelChoice::DeepSeekV4Pro => hotlist::PRO,
|
||||
ModelChoice::Glm52 | ModelChoice::Glm53Flash => {
|
||||
unreachable!("GLM uses its dedicated executor")
|
||||
@@ -2766,7 +2771,7 @@ fn resident_deepseek_admission_bytes(
|
||||
prefill: u32,
|
||||
) -> Result<u64, String> {
|
||||
resident_deepseek_admission_for_weights(
|
||||
model.main.len() - model.main.data_offset(),
|
||||
model.main.len() - model.main.data_offset() + model.vision.as_ref().map_or(0, Gguf::len),
|
||||
model.shape,
|
||||
context,
|
||||
prefill,
|
||||
@@ -3228,6 +3233,10 @@ pub(super) struct ExecutionStats {
|
||||
}
|
||||
|
||||
pub(super) struct DeepSeekExecutor {
|
||||
vision: Option<deepseek_vision::Encoder>,
|
||||
visual_bias: Vec<Buffer>,
|
||||
vision_overlays: Vec<deepseek_vision::Overlay>,
|
||||
vision_identities: Vec<deepseek_vision::Identity>,
|
||||
weights: Weights,
|
||||
session: Session,
|
||||
dspark: Option<Dspark>,
|
||||
@@ -3255,6 +3264,7 @@ pub(super) struct DeepSeekExecutor {
|
||||
}
|
||||
|
||||
pub(super) struct DeepSeekResidentState {
|
||||
vision_identities: Vec<deepseek_vision::Identity>,
|
||||
session: Session,
|
||||
dspark: Option<Dspark>,
|
||||
logits: Vec<f32>,
|
||||
@@ -3314,10 +3324,34 @@ impl DeepSeekExecutor {
|
||||
.map(|spans| (spans.ranges.as_slice(), spans.max_tensor_bytes));
|
||||
let admission = if let Some(plan) = &ssd_plan {
|
||||
plan.admission_bytes
|
||||
.checked_add(model.vision.as_ref().map_or(0, Gguf::len))
|
||||
.ok_or("DeepSeek runtime memory size overflow")?
|
||||
} else {
|
||||
resident_deepseek_admission_bytes(&model, context, prefill_chunk)?
|
||||
};
|
||||
let context_handle = Context::open(&model, quality, ssd.enabled, admission, spans, false)?;
|
||||
let context_handle = Context::open(
|
||||
&model,
|
||||
quality,
|
||||
ssd.enabled,
|
||||
admission,
|
||||
spans,
|
||||
speculative.keep_vision_loaded,
|
||||
)?;
|
||||
let vision = model
|
||||
.vision
|
||||
.as_ref()
|
||||
.map(deepseek_vision::Encoder::bind)
|
||||
.transpose()?;
|
||||
let visual_bias = model
|
||||
.vision
|
||||
.as_ref()
|
||||
.map(|v| {
|
||||
(0..43)
|
||||
.map(|i| deepseek_vision::buffer(v, &format!("layers.{i}.ffn.gate.bias_vl")))
|
||||
.collect::<Result<Vec<_>, String>>()
|
||||
})
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
let mxfp4_decode_fast_lookup =
|
||||
mxfp4_decode_fast_lookup_allowed(&model, &weights, quality, ssd.enabled);
|
||||
let steering = Steering::load(&model, steering)?;
|
||||
@@ -3369,6 +3403,10 @@ impl DeepSeekExecutor {
|
||||
model.shape.experts_used,
|
||||
)?;
|
||||
Ok(Self {
|
||||
vision,
|
||||
visual_bias,
|
||||
vision_overlays: Vec::new(),
|
||||
vision_identities: Vec::new(),
|
||||
weights,
|
||||
session,
|
||||
dspark,
|
||||
@@ -4036,6 +4074,9 @@ impl DeepSeekExecutor {
|
||||
&& !self.quality
|
||||
&& !tokens.is_empty()
|
||||
&& tokens.len() <= streaming_decode_cap
|
||||
&& !tokens
|
||||
.iter()
|
||||
.any(|token| *token >= self.model.shape.vocab as i32)
|
||||
{
|
||||
for (index, &token) in tokens.iter().enumerate() {
|
||||
if !progress(self.session.position) {
|
||||
@@ -4045,7 +4086,12 @@ impl DeepSeekExecutor {
|
||||
}
|
||||
return Ok(tokens.len());
|
||||
}
|
||||
if tokens.len() < 4 && self.session.position != 0 {
|
||||
if tokens.len() < 4
|
||||
&& self.session.position != 0
|
||||
&& !tokens
|
||||
.iter()
|
||||
.any(|token| *token >= self.model.shape.vocab as i32)
|
||||
{
|
||||
for (index, &token) in tokens.iter().enumerate() {
|
||||
self.eval(token)?;
|
||||
if !progress(self.session.position) {
|
||||
@@ -4066,6 +4112,7 @@ impl DeepSeekExecutor {
|
||||
self.session.context
|
||||
));
|
||||
}
|
||||
let resumed = self.session.position != 0;
|
||||
let mut consumed = 0_usize;
|
||||
while consumed < tokens.len() {
|
||||
if !progress(self.session.position) {
|
||||
@@ -4073,14 +4120,29 @@ impl DeepSeekExecutor {
|
||||
}
|
||||
let pos = self.session.position;
|
||||
let mut cap = self.session.prefill_cap;
|
||||
if pos != 0 {
|
||||
if pos != 0 && (self.vision.is_none() || resumed) {
|
||||
cap = cap.min(self.session.raw_cap);
|
||||
let offset = pos % self.session.prefill_cap;
|
||||
if offset != 0 {
|
||||
cap = cap.min(self.session.prefill_cap - offset);
|
||||
}
|
||||
}
|
||||
let rows = (tokens.len() - consumed).min(cap as usize);
|
||||
let rows = if self.vision.is_some() {
|
||||
if tokens[consumed] >= self.model.shape.vocab as i32 {
|
||||
cap = if resumed {
|
||||
self.session.prefill_cap.min(self.session.raw_cap)
|
||||
} else {
|
||||
self.session.prefill_cap
|
||||
};
|
||||
}
|
||||
crate::engine::deepseek_vision::prefill_chunk(
|
||||
&tokens[consumed..],
|
||||
self.model.shape.vocab as i32,
|
||||
cap,
|
||||
)?
|
||||
} else {
|
||||
(tokens.len() - consumed).min(cap as usize)
|
||||
};
|
||||
self.eval_batch(&tokens[consumed..consumed + rows])?;
|
||||
consumed += rows;
|
||||
if !progress(self.session.position) {
|
||||
@@ -4107,12 +4169,29 @@ impl DeepSeekExecutor {
|
||||
if rows == 0 || rows > self.session.prefill_cap {
|
||||
return Err("prefill batch exceeds the configured prefill workspace".into());
|
||||
}
|
||||
if tokens
|
||||
.iter()
|
||||
.any(|token| *token < 0 || *token as u64 >= self.model.shape.vocab)
|
||||
{
|
||||
let visual_tokens =
|
||||
self.vision.is_some() && tokens.iter().any(|t| *t >= self.model.shape.vocab as i32);
|
||||
if visual_tokens {
|
||||
crate::engine::deepseek_vision::spans(tokens, self.model.shape.vocab as i32)?;
|
||||
}
|
||||
if tokens.iter().any(|token| {
|
||||
*token < 0
|
||||
|| *token as u64
|
||||
>= self.model.shape.vocab + if self.vision.is_some() { 5 } else { 0 }
|
||||
}) {
|
||||
return Err("prefill contains a token outside the vocabulary".into());
|
||||
}
|
||||
if visual_tokens
|
||||
&& tokens.iter().enumerate().any(|(row, t)| {
|
||||
*t >= self.model.shape.vocab as i32
|
||||
&& !self.vision_overlays.iter().any(|o| {
|
||||
let pos = self.session.position + row as u32;
|
||||
pos >= o.identity.start && pos < o.identity.start + o.identity.count
|
||||
})
|
||||
})
|
||||
{
|
||||
return Err("DeepSeek image token has no embedding overlay".into());
|
||||
}
|
||||
let prepend_seed = collect_tops
|
||||
&& self.session.position > 0
|
||||
&& rows < self.session.prefill_cap
|
||||
@@ -4184,12 +4263,24 @@ impl DeepSeekExecutor {
|
||||
None
|
||||
};
|
||||
let pipelined_verifier = collect_tops && self.ssd.is_none() && self.profile.is_none();
|
||||
let embedding_tokens = if visual_tokens {
|
||||
let buffer = Buffer::bytes(u64::from(rows) * 4)?;
|
||||
buffer.write_i32(
|
||||
&tokens
|
||||
.iter()
|
||||
.map(|t| if *t >= shape.vocab as i32 { 0 } else { *t })
|
||||
.collect::<Vec<_>>(),
|
||||
)?;
|
||||
Some(buffer)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut commands = Some(Commands::begin()?);
|
||||
call(
|
||||
unsafe {
|
||||
ds4_gpu_embed_tokens_hc_tensor(
|
||||
batch.current_hc.raw(),
|
||||
batch.tokens.raw(),
|
||||
embedding_tokens.as_ref().unwrap_or(&batch.tokens).raw(),
|
||||
map,
|
||||
size,
|
||||
self.weights.token_embedding.offset,
|
||||
@@ -4201,6 +4292,29 @@ impl DeepSeekExecutor {
|
||||
},
|
||||
"batch token embedding",
|
||||
)?;
|
||||
if visual_tokens {
|
||||
for overlay in &self.vision_overlays {
|
||||
let start = overlay.identity.start.max(pos);
|
||||
let end = (overlay.identity.start + overlay.identity.count).min(pos + rows);
|
||||
if start < end {
|
||||
call(
|
||||
unsafe {
|
||||
ds4_gpu_glm53_scatter_image_hc(
|
||||
batch.current_hc.raw(),
|
||||
overlay.embedding.raw(),
|
||||
start - pos,
|
||||
start - overlay.identity.start,
|
||||
end - start,
|
||||
rows,
|
||||
shape.embd as u32,
|
||||
shape.hc as u32,
|
||||
)
|
||||
},
|
||||
"DeepSeek image embedding overlay",
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !pipelined_verifier {
|
||||
commands
|
||||
.take()
|
||||
@@ -4261,6 +4375,12 @@ impl DeepSeekExecutor {
|
||||
self.session.raw_cap,
|
||||
self.steering.as_ref(),
|
||||
collect_tops.then_some(prefixes.as_mut_slice()),
|
||||
visual_tokens.then_some(tokens),
|
||||
if visual_tokens {
|
||||
self.visual_bias.get(index)
|
||||
} else {
|
||||
None
|
||||
},
|
||||
)?;
|
||||
if let Some(profile) = &mut self.profile {
|
||||
profile.record(
|
||||
@@ -4401,6 +4521,14 @@ impl DeepSeekExecutor {
|
||||
};
|
||||
self.session.position += rows;
|
||||
self.tokens.extend_from_slice(tokens);
|
||||
if !self.vision_overlays.is_empty() {
|
||||
self.vision_identities = self
|
||||
.vision_overlays
|
||||
.iter()
|
||||
.filter(|o| o.identity.start + o.identity.count <= self.session.position)
|
||||
.map(|o| o.identity.clone())
|
||||
.collect();
|
||||
}
|
||||
if let Some(dspark) = &mut self.dspark {
|
||||
// Keep the captured target rows until DS4's next proposal needs them.
|
||||
dspark.pending_seed = Some((
|
||||
@@ -4499,6 +4627,8 @@ impl DeepSeekExecutor {
|
||||
dspark.reset_cache();
|
||||
}
|
||||
self.tokens.clear();
|
||||
self.vision_identities.clear();
|
||||
self.vision_overlays.clear();
|
||||
self.checkpoint_tag = [0; 32];
|
||||
Ok(())
|
||||
}
|
||||
@@ -4520,6 +4650,7 @@ impl DeepSeekExecutor {
|
||||
_ => None,
|
||||
};
|
||||
Ok(DeepSeekResidentState {
|
||||
vision_identities: Vec::new(),
|
||||
session,
|
||||
dspark,
|
||||
logits: vec![0.0; self.model.shape.vocab as usize],
|
||||
@@ -4535,6 +4666,8 @@ impl DeepSeekExecutor {
|
||||
let mut incoming = state
|
||||
.take()
|
||||
.map_or_else(|| self.blank_resident_state(), Ok)?;
|
||||
std::mem::swap(&mut self.vision_identities, &mut incoming.vision_identities);
|
||||
self.vision_overlays.clear();
|
||||
std::mem::swap(&mut self.session, &mut incoming.session);
|
||||
std::mem::swap(&mut self.dspark, &mut incoming.dspark);
|
||||
std::mem::swap(&mut self.logits, &mut incoming.logits);
|
||||
@@ -4549,7 +4682,9 @@ impl DeepSeekExecutor {
|
||||
dspark.begin_request();
|
||||
}
|
||||
if !tokens.starts_with(&self.tokens) {
|
||||
let overlays = std::mem::take(&mut self.vision_overlays);
|
||||
self.reset()?;
|
||||
self.vision_overlays = overlays;
|
||||
}
|
||||
Ok(self.tokens.len())
|
||||
}
|
||||
@@ -4900,8 +5035,9 @@ impl Executor {
|
||||
) -> Result<Vec<vision::VisionEmbedding>, String> {
|
||||
match self {
|
||||
Self::Glm(executor) => executor.encode_visions(encoded),
|
||||
Self::DeepSeek(_) | Self::Qwen(_) | Self::QwenMtplx(_) => {
|
||||
Err("vision input requires GLM 5.3 Flash".into())
|
||||
Self::DeepSeek(executor) => executor.encode_visions(encoded),
|
||||
Self::Qwen(_) | Self::QwenMtplx(_) => {
|
||||
Err("vision input requires a supported vision model".into())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4912,10 +5048,10 @@ impl Executor {
|
||||
) -> Result<(), String> {
|
||||
match self {
|
||||
Self::Glm(executor) => executor.set_vision_overlays(overlays),
|
||||
Self::DeepSeek(_) if overlays.is_empty() => Ok(()),
|
||||
Self::DeepSeek(executor) => executor.set_vision_overlays(overlays),
|
||||
Self::Qwen(_) | Self::QwenMtplx(_) if overlays.is_empty() => Ok(()),
|
||||
Self::DeepSeek(_) | Self::Qwen(_) | Self::QwenMtplx(_) => {
|
||||
Err("vision input requires GLM 5.3 Flash".into())
|
||||
Self::Qwen(_) | Self::QwenMtplx(_) => {
|
||||
Err("vision input requires a supported vision model".into())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5574,6 +5710,8 @@ fn encode_batch_layer(
|
||||
raw_cap: u32,
|
||||
steering: Option<&Steering>,
|
||||
mut prefixes: Option<&mut [SpecPrefixFrontier]>,
|
||||
visual_tokens: Option<&[i32]>,
|
||||
visual_bias: Option<&Buffer>,
|
||||
) -> Result<(), String> {
|
||||
let hc_dim = shape.hc * shape.embd;
|
||||
let mix_hc = 2 * shape.hc + shape.hc * shape.hc;
|
||||
@@ -5944,7 +6082,21 @@ fn encode_batch_layer(
|
||||
)?;
|
||||
}
|
||||
|
||||
if pos == 0 && compressed_rows == 0 {
|
||||
if let Some(tokens) = visual_tokens {
|
||||
deepseek_vision::attention(
|
||||
s,
|
||||
state,
|
||||
w,
|
||||
shape,
|
||||
map,
|
||||
size,
|
||||
tokens,
|
||||
pos,
|
||||
raw_cap,
|
||||
compressed_rows,
|
||||
ratio,
|
||||
)?;
|
||||
} else if pos == 0 && compressed_rows == 0 {
|
||||
call(
|
||||
unsafe {
|
||||
ds4_gpu_attention_prefill_raw_heads_tensor(
|
||||
@@ -6324,31 +6476,61 @@ fn encode_batch_layer(
|
||||
map,
|
||||
size,
|
||||
)?;
|
||||
call(
|
||||
unsafe {
|
||||
ds4_gpu_router_select_batch_tensor(
|
||||
s.router_selected.raw(),
|
||||
s.router_weights.raw(),
|
||||
s.router_probs.raw(),
|
||||
map,
|
||||
size,
|
||||
w.router_bias.map_or(0, |value| value.offset),
|
||||
w.router_hash.map_or(0, |value| value.offset),
|
||||
w.router_hash.map_or(0, |value| value.dims[1] as u32),
|
||||
0,
|
||||
0,
|
||||
w.router_bias.is_some(),
|
||||
w.router_hash.is_some(),
|
||||
s.router_logits.raw(),
|
||||
s.tokens.raw(),
|
||||
shape.experts as u32,
|
||||
shape.experts_used as u32,
|
||||
shape.expert_weight_scale,
|
||||
rows,
|
||||
)
|
||||
},
|
||||
"batch expert routing",
|
||||
)?;
|
||||
if let Some(bias) = visual_bias {
|
||||
call(
|
||||
unsafe {
|
||||
ds4_gpu_router_select_visual_batch_tensor(
|
||||
s.router_selected.raw(),
|
||||
s.router_weights.raw(),
|
||||
s.router_probs.raw(),
|
||||
map,
|
||||
size,
|
||||
w.router_bias.map_or(0, |value| value.offset),
|
||||
w.router_hash.map_or(0, |value| value.offset),
|
||||
w.router_hash.map_or(0, |value| value.dims[1] as u32),
|
||||
0,
|
||||
0,
|
||||
w.router_bias.is_some(),
|
||||
w.router_hash.is_some(),
|
||||
s.router_logits.raw(),
|
||||
s.tokens.raw(),
|
||||
shape.experts as u32,
|
||||
shape.experts_used as u32,
|
||||
shape.expert_weight_scale,
|
||||
rows,
|
||||
bias.raw(),
|
||||
shape.vocab as u32,
|
||||
)
|
||||
},
|
||||
"batch expert routing",
|
||||
)?;
|
||||
} else {
|
||||
call(
|
||||
unsafe {
|
||||
ds4_gpu_router_select_batch_tensor(
|
||||
s.router_selected.raw(),
|
||||
s.router_weights.raw(),
|
||||
s.router_probs.raw(),
|
||||
map,
|
||||
size,
|
||||
w.router_bias.map_or(0, |value| value.offset),
|
||||
w.router_hash.map_or(0, |value| value.offset),
|
||||
w.router_hash.map_or(0, |value| value.dims[1] as u32),
|
||||
0,
|
||||
0,
|
||||
w.router_bias.is_some(),
|
||||
w.router_hash.is_some(),
|
||||
s.router_logits.raw(),
|
||||
s.tokens.raw(),
|
||||
shape.experts as u32,
|
||||
shape.experts_used as u32,
|
||||
shape.expert_weight_scale,
|
||||
rows,
|
||||
)
|
||||
},
|
||||
"batch expert routing",
|
||||
)?;
|
||||
}
|
||||
let gate_row = w.expert_gate.bytes / (w.expert_gate.dims[1] * w.expert_gate.dims[2]);
|
||||
let down_row = w.expert_down.bytes / (w.expert_down.dims[1] * w.expert_down.dims[2]);
|
||||
let mut mid_f16 = false;
|
||||
@@ -8141,15 +8323,22 @@ fn update_compressor_stage(
|
||||
|
||||
fn compression_ratio(shape: super::Shape, layer: u32) -> u32 {
|
||||
match shape.model {
|
||||
crate::model::ModelChoice::DeepSeekV4Flash0731 if layer < 2 => 0,
|
||||
crate::model::ModelChoice::DeepSeekV4FlashVision
|
||||
| crate::model::ModelChoice::DeepSeekV4Flash0731
|
||||
if layer < 2 =>
|
||||
{
|
||||
0
|
||||
}
|
||||
crate::model::ModelChoice::DeepSeekV4Pro if layer < 2 => 128,
|
||||
crate::model::ModelChoice::DeepSeekV4Flash0731
|
||||
crate::model::ModelChoice::DeepSeekV4FlashVision
|
||||
| crate::model::ModelChoice::DeepSeekV4Flash0731
|
||||
| crate::model::ModelChoice::DeepSeekV4Pro
|
||||
if layer.is_multiple_of(2) =>
|
||||
{
|
||||
4
|
||||
}
|
||||
crate::model::ModelChoice::DeepSeekV4Flash0731
|
||||
crate::model::ModelChoice::DeepSeekV4FlashVision
|
||||
| crate::model::ModelChoice::DeepSeekV4Flash0731
|
||||
| crate::model::ModelChoice::DeepSeekV4Pro => 128,
|
||||
crate::model::ModelChoice::Glm52
|
||||
| crate::model::ModelChoice::Glm53Flash
|
||||
|
||||
@@ -97,6 +97,15 @@ impl DeepSeekExecutor {
|
||||
for &token in &self.tokens {
|
||||
write_u32(file, token as u32)?;
|
||||
}
|
||||
if shape.model == ModelChoice::DeepSeekV4FlashVision {
|
||||
write_u32(file, self.vision_identities.len() as u32)?;
|
||||
for image in &self.vision_identities {
|
||||
write_u32(file, image.start)?;
|
||||
write_u32(file, image.count)?;
|
||||
file.write_all(&image.fingerprint)
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
for &logit in &self.logits {
|
||||
write_u32(file, logit.to_bits())?;
|
||||
}
|
||||
@@ -212,11 +221,44 @@ impl DeepSeekExecutor {
|
||||
let mut tokens = Vec::with_capacity(token_count as usize);
|
||||
for _ in 0..token_count {
|
||||
let token = read_u32(file)?;
|
||||
if u64::from(token) >= shape.vocab {
|
||||
if u64::from(token)
|
||||
>= shape.vocab
|
||||
+ if shape.model == ModelChoice::DeepSeekV4FlashVision {
|
||||
5
|
||||
} else {
|
||||
0
|
||||
}
|
||||
{
|
||||
return Err("KV checkpoint contains an invalid token".into());
|
||||
}
|
||||
tokens.push(token as i32);
|
||||
}
|
||||
let mut vision_identities = Vec::new();
|
||||
if shape.model == ModelChoice::DeepSeekV4FlashVision {
|
||||
let spans = crate::engine::deepseek_vision::spans(&tokens, shape.vocab as i32)?;
|
||||
let count = read_u32(file)?;
|
||||
if count as usize != spans.len() || count > 16 {
|
||||
return Err("KV checkpoint image count is invalid".into());
|
||||
}
|
||||
for span in spans {
|
||||
let start = read_u32(file)?;
|
||||
let count = read_u32(file)?;
|
||||
if start as usize != span.block
|
||||
|| count as usize != span.end + 1 - span.block
|
||||
|| count > 384
|
||||
{
|
||||
return Err("KV checkpoint image layout is invalid".into());
|
||||
}
|
||||
let mut fingerprint = [0; 32];
|
||||
file.read_exact(&mut fingerprint)
|
||||
.map_err(|e| e.to_string())?;
|
||||
vision_identities.push(deepseek_vision::Identity {
|
||||
start,
|
||||
count,
|
||||
fingerprint,
|
||||
});
|
||||
}
|
||||
}
|
||||
let mut logits = Vec::with_capacity(shape.vocab as usize);
|
||||
for _ in 0..shape.vocab {
|
||||
logits.push(f32::from_bits(read_u32(file)?));
|
||||
@@ -299,6 +341,8 @@ impl DeepSeekExecutor {
|
||||
}
|
||||
self.session.position = token_count;
|
||||
self.tokens = tokens;
|
||||
self.vision_identities = vision_identities;
|
||||
self.vision_overlays.clear();
|
||||
self.logits = logits;
|
||||
self.checkpoint_tag = checkpoint_tag;
|
||||
if let Some(dspark) = &mut self.dspark {
|
||||
|
||||
@@ -0,0 +1,617 @@
|
||||
//! Native Rust execution of DS4's Vision-Exp encoder, using the shared BF16
|
||||
//! matmul and attention primitives and the checkpoint's exact rounding points.
|
||||
use super::{Buffer, Commands, Gguf, call, gpu::*};
|
||||
use crate::engine::deepseek_vision::{self as image, END, IMAGE, NEWLINE, PAD, START};
|
||||
use std::ffi::CStr;
|
||||
|
||||
struct Layer {
|
||||
norm1: Buffer,
|
||||
qkv: u64,
|
||||
qkv_bias: Buffer,
|
||||
out: u64,
|
||||
out_bias: Buffer,
|
||||
norm2: Buffer,
|
||||
up: u64,
|
||||
down: u64,
|
||||
}
|
||||
|
||||
pub(super) struct Encoder {
|
||||
patch: u64,
|
||||
patch_bias: Buffer,
|
||||
norm: Buffer,
|
||||
align1: u64,
|
||||
align1_bias: Buffer,
|
||||
align2: u64,
|
||||
align2_bias: Buffer,
|
||||
layers: Vec<Layer>,
|
||||
sentinels: [Vec<f32>; 5],
|
||||
}
|
||||
|
||||
pub(super) fn buffer(model: &Gguf, name: &str) -> Result<Buffer, String> {
|
||||
let bytes = model.tensor_data(name)?;
|
||||
let result = Buffer::bytes(bytes.len() as u64)?;
|
||||
result.write(0, bytes)?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn dispatch<T>(
|
||||
kernel: &CStr,
|
||||
args: &T,
|
||||
buffers: &[&Buffer],
|
||||
grid: [u32; 3],
|
||||
threads: [u32; 3],
|
||||
individual: bool,
|
||||
shared: u32,
|
||||
) -> Result<(), String> {
|
||||
let mut bindings = vec![MetalBinding {
|
||||
tensor: std::ptr::null(),
|
||||
bytes: (args as *const T).cast(),
|
||||
size: size_of::<T>() as u32,
|
||||
index: 0,
|
||||
offset: 0,
|
||||
}];
|
||||
bindings.extend(buffers.iter().enumerate().map(|(i, b)| MetalBinding {
|
||||
tensor: b.raw(),
|
||||
bytes: std::ptr::null(),
|
||||
size: 0,
|
||||
index: i as u32 + 1,
|
||||
offset: 0,
|
||||
}));
|
||||
call(
|
||||
unsafe {
|
||||
ds4_gpu_deepseek_vision_dispatch(
|
||||
kernel.as_ptr(),
|
||||
bindings.as_ptr(),
|
||||
bindings.len() as u32,
|
||||
grid.as_ptr(),
|
||||
threads.as_ptr(),
|
||||
u32::from(individual),
|
||||
shared,
|
||||
)
|
||||
},
|
||||
"DeepSeek vision kernel",
|
||||
)
|
||||
}
|
||||
|
||||
fn rows(kernel: &CStr, width: u32, rows: u32, buffers: &[&Buffer]) -> Result<(), String> {
|
||||
dispatch(
|
||||
kernel,
|
||||
&[width, rows],
|
||||
buffers,
|
||||
[width, rows, 1],
|
||||
[width.min(256), 1, 1],
|
||||
true,
|
||||
0,
|
||||
)
|
||||
}
|
||||
fn round(x: &Buffer, width: u32, n: u32) -> Result<(), String> {
|
||||
rows(c"kernel_deepseek4_vision_round_bf16", width, n, &[x])
|
||||
}
|
||||
fn norm(out: &Buffer, x: &Buffer, weight: &Buffer, n: u32) -> Result<(), String> {
|
||||
dispatch(
|
||||
c"kernel_glm53_vision_rms_bf16",
|
||||
&[1024, n, 1e-6_f32.to_bits()],
|
||||
&[x, weight, out],
|
||||
[n, 1, 1],
|
||||
[256, 1, 1],
|
||||
false,
|
||||
32,
|
||||
)?;
|
||||
round(out, 1024, n)
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn matmul(
|
||||
model: &Gguf,
|
||||
out: &Buffer,
|
||||
weight: u64,
|
||||
input: &Buffer,
|
||||
dim: u32,
|
||||
width: u32,
|
||||
n: u32,
|
||||
) -> Result<(), String> {
|
||||
call(
|
||||
unsafe {
|
||||
ds4_gpu_glm53_matmul_bf16(
|
||||
out.raw(),
|
||||
model.map_ptr().cast(),
|
||||
model.len(),
|
||||
weight,
|
||||
dim,
|
||||
width,
|
||||
input.raw(),
|
||||
n,
|
||||
)
|
||||
},
|
||||
"DeepSeek vision BF16 projection",
|
||||
)
|
||||
}
|
||||
|
||||
impl Encoder {
|
||||
pub(super) fn bind(model: &Gguf) -> Result<Self, String> {
|
||||
let offset = |name: &str| model.tensor(name).map(|t| t.offset);
|
||||
let mut layers = Vec::with_capacity(32);
|
||||
for i in 0..32 {
|
||||
let b = |suffix: &str| buffer(model, &format!("vision.blocks.{i}.{suffix}"));
|
||||
let o = |suffix: &str| offset(&format!("vision.blocks.{i}.{suffix}"));
|
||||
layers.push(Layer {
|
||||
norm1: b("norm1.weight")?,
|
||||
qkv: o("attn.wqkv.weight")?,
|
||||
qkv_bias: b("attn.wqkv.bias")?,
|
||||
out: o("attn.wo.weight")?,
|
||||
out_bias: b("attn.wo.bias")?,
|
||||
norm2: b("norm2.weight")?,
|
||||
up: o("mlp.w1.weight")?,
|
||||
down: o("mlp.w2.weight")?,
|
||||
});
|
||||
}
|
||||
let mut sentinels = std::array::from_fn(|_| Vec::new());
|
||||
for (i, name) in [
|
||||
(START, "image_start"),
|
||||
(PAD, "image_pad"),
|
||||
(NEWLINE, "image_newline"),
|
||||
(END, "image_end"),
|
||||
] {
|
||||
sentinels[i as usize] = model
|
||||
.tensor_data(name)?
|
||||
.chunks_exact(2)
|
||||
.map(|b| f32::from_bits(u32::from(u16::from_le_bytes([b[0], b[1]])) << 16))
|
||||
.collect();
|
||||
}
|
||||
Ok(Self {
|
||||
patch: offset("vision.patch_embed.proj.weight")?,
|
||||
patch_bias: buffer(model, "vision.patch_embed.proj.bias")?,
|
||||
norm: buffer(model, "vision.norm.weight")?,
|
||||
align1: offset("aligner.w1.weight")?,
|
||||
align1_bias: buffer(model, "aligner.w1.bias")?,
|
||||
align2: offset("aligner.w2.weight")?,
|
||||
align2_bias: buffer(model, "aligner.w2.bias")?,
|
||||
layers,
|
||||
sentinels,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn encode(
|
||||
&self,
|
||||
model: &Gguf,
|
||||
encoded: &[u8],
|
||||
) -> Result<super::VisionEmbedding, String> {
|
||||
let p = image::decode(encoded)?;
|
||||
let n = p.grid_height * p.grid_width;
|
||||
let aligned = p.grid_height.div_ceil(3) * p.grid_width.div_ceil(3);
|
||||
let alloc = |width: u64| Buffer::floats(u64::from(n) * width);
|
||||
let patch = alloc(588)?;
|
||||
patch.write_f32(&p.values)?;
|
||||
let mut cur = alloc(1024)?;
|
||||
let mut tmp = alloc(1024)?;
|
||||
let qkv = alloc(3072)?;
|
||||
let q = alloc(1024)?;
|
||||
let k = alloc(1024)?;
|
||||
let v = alloc(1024)?;
|
||||
let attn = alloc(1024)?;
|
||||
let up = alloc(5632)?;
|
||||
let mid = alloc(2816)?;
|
||||
let aligned_input = Buffer::floats(u64::from(aligned) * 9216)?;
|
||||
let aa = Buffer::floats(u64::from(aligned) * 4096)?;
|
||||
let ab = Buffer::floats(u64::from(aligned) * 4096)?;
|
||||
let commands = Commands::begin()?;
|
||||
matmul(model, &cur, self.patch, &patch, 588, 1024, n)?;
|
||||
rows(
|
||||
c"kernel_glm53_vision_add_bias",
|
||||
1024,
|
||||
n,
|
||||
&[&cur, &self.patch_bias],
|
||||
)?;
|
||||
round(&cur, 1024, n)?;
|
||||
for layer in &self.layers {
|
||||
norm(&tmp, &cur, &layer.norm1, n)?;
|
||||
matmul(model, &qkv, layer.qkv, &tmp, 1024, 3072, n)?;
|
||||
dispatch(
|
||||
c"kernel_deepseek4_vision_qkv_rope",
|
||||
&[n, p.grid_width],
|
||||
&[&qkv, &layer.qkv_bias, &q, &k, &v],
|
||||
[n, 16, 1],
|
||||
[32, 1, 1],
|
||||
false,
|
||||
0,
|
||||
)?;
|
||||
dispatch(
|
||||
c"kernel_glm53_vision_attention",
|
||||
&[n, 0.125_f32.to_bits()],
|
||||
&[&q, &k, &v, &attn],
|
||||
[n, 16, 1],
|
||||
[32, 1, 1],
|
||||
false,
|
||||
0,
|
||||
)?;
|
||||
round(&attn, 1024, n)?;
|
||||
matmul(model, &tmp, layer.out, &attn, 1024, 1024, n)?;
|
||||
rows(
|
||||
c"kernel_glm53_vision_bias_residual",
|
||||
1024,
|
||||
n,
|
||||
&[&tmp, &layer.out_bias, &cur],
|
||||
)?;
|
||||
round(&tmp, 1024, n)?;
|
||||
std::mem::swap(&mut cur, &mut tmp);
|
||||
norm(&tmp, &cur, &layer.norm2, n)?;
|
||||
matmul(model, &up, layer.up, &tmp, 1024, 5632, n)?;
|
||||
round(&up, 5632, n)?;
|
||||
rows(
|
||||
c"kernel_deepseek4_vision_swiglu_split",
|
||||
2816,
|
||||
n,
|
||||
&[&up, &mid],
|
||||
)?;
|
||||
matmul(model, &tmp, layer.down, &mid, 2816, 1024, n)?;
|
||||
round(&tmp, 1024, n)?;
|
||||
rows(
|
||||
c"kernel_deepseek4_vision_add_residual",
|
||||
1024,
|
||||
n,
|
||||
&[&tmp, &cur],
|
||||
)?;
|
||||
std::mem::swap(&mut cur, &mut tmp);
|
||||
}
|
||||
norm(&tmp, &cur, &self.norm, n)?;
|
||||
dispatch(
|
||||
c"kernel_deepseek4_vision_aligner_reorder",
|
||||
&[p.grid_height, p.grid_width, aligned],
|
||||
&[&tmp, &aligned_input],
|
||||
[9216, aligned, 1],
|
||||
[256, 1, 1],
|
||||
true,
|
||||
0,
|
||||
)?;
|
||||
matmul(model, &aa, self.align1, &aligned_input, 9216, 4096, aligned)?;
|
||||
rows(
|
||||
c"kernel_deepseek4_vision_gelu_bias",
|
||||
4096,
|
||||
aligned,
|
||||
&[&aa, &self.align1_bias, &ab],
|
||||
)?;
|
||||
matmul(model, &aa, self.align2, &ab, 4096, 4096, aligned)?;
|
||||
rows(
|
||||
c"kernel_glm53_vision_add_bias",
|
||||
4096,
|
||||
aligned,
|
||||
&[&aa, &self.align2_bias],
|
||||
)?;
|
||||
round(&aa, 4096, aligned)?;
|
||||
commands.finish()?;
|
||||
let mut values = vec![0.0; aligned as usize * 4096];
|
||||
aa.read_f32(&mut values)?;
|
||||
Ok(super::VisionEmbedding {
|
||||
fingerprint: p.fingerprint,
|
||||
values,
|
||||
tokens: aligned,
|
||||
width: p.width,
|
||||
height: p.height,
|
||||
content_width: p.content_width,
|
||||
content_height: p.content_height,
|
||||
grid_width: p.grid_width.div_ceil(3),
|
||||
grid_height: p.grid_height.div_ceil(3),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn layout(
|
||||
&self,
|
||||
embedding: &mut super::VisionEmbedding,
|
||||
position: u32,
|
||||
vocab: i32,
|
||||
) -> Result<Vec<i32>, String> {
|
||||
let layout = image::layout(embedding.grid_height, embedding.grid_width, position)?;
|
||||
if embedding.tokens as usize != layout.permutation.len()
|
||||
|| embedding.values.len() != layout.permutation.len() * 4096
|
||||
{
|
||||
return Err("invalid DeepSeek natural image embedding".into());
|
||||
}
|
||||
let mut values = Vec::with_capacity(layout.types.len() * 4096);
|
||||
let mut images = layout.permutation.iter();
|
||||
for &kind in &layout.types {
|
||||
if kind == IMAGE {
|
||||
let row = *images.next().ok_or("invalid DeepSeek image permutation")?;
|
||||
values.extend_from_slice(&embedding.values[row * 4096..(row + 1) * 4096]);
|
||||
} else {
|
||||
values.extend_from_slice(&self.sentinels[kind as usize]);
|
||||
}
|
||||
}
|
||||
embedding.values = values;
|
||||
embedding.tokens = layout.types.len() as u32;
|
||||
embedding.grid_height = 0;
|
||||
embedding.grid_width = 0;
|
||||
Ok(layout.types.into_iter().map(|t| t + vocab).collect())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(super) struct Identity {
|
||||
pub start: u32,
|
||||
pub count: u32,
|
||||
pub fingerprint: [u8; 32],
|
||||
}
|
||||
pub(super) struct Overlay {
|
||||
pub identity: Identity,
|
||||
pub embedding: Buffer,
|
||||
}
|
||||
|
||||
impl super::DeepSeekExecutor {
|
||||
pub(in crate::engine) fn cached_vision_positions(
|
||||
&self,
|
||||
images: &[super::VisionEmbedding],
|
||||
) -> Option<Vec<(u32, u32)>> {
|
||||
(images.len() == self.vision_identities.len()
|
||||
&& images
|
||||
.iter()
|
||||
.zip(&self.vision_identities)
|
||||
.all(|(image, old)| {
|
||||
image.fingerprint == old.fingerprint
|
||||
&& image::layout(image.grid_height, image.grid_width, old.start)
|
||||
.is_ok_and(|layout| layout.types.len() == old.count as usize)
|
||||
}))
|
||||
.then(|| {
|
||||
self.vision_identities
|
||||
.iter()
|
||||
.map(|old| (old.start, old.count))
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::engine) fn layout_vision(
|
||||
&self,
|
||||
embedding: &mut super::VisionEmbedding,
|
||||
position: u32,
|
||||
) -> Result<Vec<i32>, String> {
|
||||
self.vision
|
||||
.as_ref()
|
||||
.ok_or("DeepSeek vision encoder is not loaded")?
|
||||
.layout(embedding, position, self.model.shape.vocab as i32)
|
||||
}
|
||||
pub(super) fn encode_visions(
|
||||
&self,
|
||||
encoded: &[Vec<u8>],
|
||||
) -> Result<Vec<super::VisionEmbedding>, String> {
|
||||
let encoder = self
|
||||
.vision
|
||||
.as_ref()
|
||||
.ok_or("DeepSeek vision encoder is not loaded")?;
|
||||
let model = self
|
||||
.model
|
||||
.vision
|
||||
.as_ref()
|
||||
.ok_or("DeepSeek vision sidecar is not loaded")?;
|
||||
if !self.speculative.keep_vision_loaded {
|
||||
call(
|
||||
unsafe {
|
||||
ds4_gpu_set_transient_model_map_range(
|
||||
model.map_ptr().cast(),
|
||||
model.len(),
|
||||
model.data_offset(),
|
||||
model.len() - model.data_offset(),
|
||||
model.max_tensor_bytes(),
|
||||
)
|
||||
},
|
||||
"mapping DeepSeek vision weights",
|
||||
)?;
|
||||
}
|
||||
let result = encoded
|
||||
.iter()
|
||||
.map(|bytes| encoder.encode(model, bytes))
|
||||
.collect();
|
||||
let released = if self.speculative.keep_vision_loaded {
|
||||
Ok(())
|
||||
} else {
|
||||
call(
|
||||
unsafe { ds4_gpu_release_transient_model_map(model.map_ptr().cast(), model.len()) },
|
||||
"releasing DeepSeek vision weights",
|
||||
)
|
||||
};
|
||||
match (result, released) {
|
||||
(Ok(result), Ok(())) => Ok(result),
|
||||
(Err(e), _) | (_, Err(e)) => Err(e),
|
||||
}
|
||||
}
|
||||
pub(super) fn set_vision_overlays(
|
||||
&mut self,
|
||||
overlays: Vec<(u32, super::VisionEmbedding)>,
|
||||
) -> Result<(), String> {
|
||||
if self.vision.is_none() && !overlays.is_empty() {
|
||||
return Err("DeepSeek vision encoder is not loaded".into());
|
||||
}
|
||||
let mut next = Vec::with_capacity(overlays.len());
|
||||
let mut end = 0;
|
||||
for (start, image) in overlays {
|
||||
if image.tokens == 0
|
||||
|| image.tokens > 384
|
||||
|| image.values.len() != image.tokens as usize * 4096
|
||||
|| start < end
|
||||
{
|
||||
return Err("invalid DeepSeek image overlay".into());
|
||||
}
|
||||
end = start
|
||||
.checked_add(image.tokens)
|
||||
.ok_or("DeepSeek image position overflow")?;
|
||||
if end > self.session.context {
|
||||
return Err("DeepSeek image exceeds the session context".into());
|
||||
}
|
||||
let embedding = Buffer::floats(image.values.len() as u64)?;
|
||||
embedding.write_f32(&image.values)?;
|
||||
next.push(Overlay {
|
||||
identity: Identity {
|
||||
start,
|
||||
count: image.tokens,
|
||||
fingerprint: image.fingerprint,
|
||||
},
|
||||
embedding,
|
||||
});
|
||||
}
|
||||
let matches = self.vision_identities.len() <= next.len()
|
||||
&& self
|
||||
.vision_identities
|
||||
.iter()
|
||||
.zip(&next)
|
||||
.all(|(old, new)| old == &new.identity)
|
||||
&& next
|
||||
.get(self.vision_identities.len())
|
||||
.is_none_or(|image| image.identity.start >= self.session.position);
|
||||
if !matches {
|
||||
self.reset()?;
|
||||
}
|
||||
self.vision_overlays = next;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn attention(
|
||||
s: &super::BatchScratch,
|
||||
state: &super::LayerState,
|
||||
w: &super::Layer,
|
||||
shape: crate::engine::Shape,
|
||||
map: *const std::ffi::c_void,
|
||||
size: u64,
|
||||
tokens: &[i32],
|
||||
pos: u32,
|
||||
raw_cap: u32,
|
||||
n_comp: u32,
|
||||
ratio: u32,
|
||||
) -> Result<(), String> {
|
||||
let n = tokens.len() as u32;
|
||||
let (n_raw, raw_start) = if pos == 0 {
|
||||
(n, 0)
|
||||
} else {
|
||||
super::raw_batch_span(pos, n, raw_cap, shape.sliding_window as u32)
|
||||
};
|
||||
let bounds = image::attention_bounds(
|
||||
tokens,
|
||||
shape.vocab as i32,
|
||||
pos,
|
||||
n_raw,
|
||||
shape.sliding_window as u32,
|
||||
)?;
|
||||
let mut mask = Vec::with_capacity(n as usize * (n_raw + n_comp) as usize);
|
||||
let first = pos + n - n_raw;
|
||||
for row in 0..n {
|
||||
for key in 0..n_raw {
|
||||
mask.push(
|
||||
if (bounds[row as usize * 2]..=bounds[row as usize * 2 + 1])
|
||||
.contains(&(first + key))
|
||||
{
|
||||
0
|
||||
} else {
|
||||
0xfc00
|
||||
},
|
||||
);
|
||||
}
|
||||
let visible = (pos + row + 1).checked_div(ratio).unwrap_or(0);
|
||||
mask.extend((0..n_comp).map(|key| if key < visible { 0 } else { 0xfc00 }));
|
||||
}
|
||||
let indexed = ratio == 4 && n_comp > shape.indexer_top_k as u32;
|
||||
let comp_mask = if indexed {
|
||||
let indexer = state
|
||||
.indexer
|
||||
.as_ref()
|
||||
.ok_or("DeepSeek visual indexer state is missing")?;
|
||||
let scale = ((shape.indexer_heads * shape.indexer_head_dim) as f32)
|
||||
.sqrt()
|
||||
.recip();
|
||||
call(
|
||||
unsafe {
|
||||
if pos == 0 {
|
||||
ds4_gpu_indexer_scores_prefill_tensor(
|
||||
s.indexer_scores.raw(),
|
||||
s.indexer_q.raw(),
|
||||
s.indexer_weights.raw(),
|
||||
indexer.cache.raw(),
|
||||
n_comp,
|
||||
n,
|
||||
shape.indexer_heads as u32,
|
||||
shape.indexer_head_dim as u32,
|
||||
ratio,
|
||||
scale,
|
||||
)
|
||||
} else {
|
||||
ds4_gpu_indexer_scores_decode_batch_tensor(
|
||||
s.indexer_scores.raw(),
|
||||
s.indexer_q.raw(),
|
||||
s.indexer_weights.raw(),
|
||||
indexer.cache.raw(),
|
||||
n_comp,
|
||||
n,
|
||||
pos,
|
||||
shape.indexer_heads as u32,
|
||||
shape.indexer_head_dim as u32,
|
||||
ratio,
|
||||
scale,
|
||||
)
|
||||
}
|
||||
},
|
||||
"DeepSeek visual indexer scores",
|
||||
)?;
|
||||
call(
|
||||
unsafe {
|
||||
ds4_gpu_indexer_topk_tensor(
|
||||
s.indexer_selected.raw(),
|
||||
s.indexer_scores.raw(),
|
||||
n_comp,
|
||||
n,
|
||||
shape.indexer_top_k as u32,
|
||||
)
|
||||
},
|
||||
"DeepSeek visual indexer top-k",
|
||||
)?;
|
||||
let mask = Buffer::floats(u64::from(n) * u64::from(n_comp))?;
|
||||
call(
|
||||
unsafe {
|
||||
ds4_gpu_dsv4_topk_mask_tensor(
|
||||
mask.raw(),
|
||||
s.indexer_selected.raw(),
|
||||
n_comp,
|
||||
n,
|
||||
shape.indexer_top_k as u32,
|
||||
)
|
||||
},
|
||||
"DeepSeek visual compressed mask",
|
||||
)?;
|
||||
Some(mask)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
call(
|
||||
unsafe {
|
||||
ds4_gpu_attention_visual_batch_tensor(
|
||||
s.heads.raw(),
|
||||
map,
|
||||
size,
|
||||
w.attn_sinks.offset,
|
||||
s.q.raw(),
|
||||
state.raw_cache.raw(),
|
||||
state
|
||||
.compression
|
||||
.as_ref()
|
||||
.map_or(std::ptr::null(), |c| c.cache.raw()),
|
||||
comp_mask
|
||||
.as_ref()
|
||||
.map_or(std::ptr::null(), |b| b.raw().cast_const()),
|
||||
u32::from(indexed),
|
||||
n,
|
||||
pos,
|
||||
n_raw,
|
||||
raw_cap,
|
||||
raw_start,
|
||||
n_comp,
|
||||
shape.sliding_window as u32,
|
||||
ratio,
|
||||
shape.heads as u32,
|
||||
shape.head_dim as u32,
|
||||
mask.as_ptr(),
|
||||
mask.len() as u64,
|
||||
)
|
||||
},
|
||||
"DeepSeek visual attention",
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "issue100.rs"]
|
||||
mod tests;
|
||||
@@ -7196,6 +7196,9 @@ mod tests {
|
||||
let prefill_tps = prompt.len() as f64 / prefill_started.elapsed().as_secs_f64();
|
||||
let image_logits = executor.logits().to_vec();
|
||||
let make_embedding = |values| crate::engine::metal::vision::VisionEmbedding {
|
||||
fingerprint: [0; 32],
|
||||
grid_width: 0,
|
||||
grid_height: 0,
|
||||
values,
|
||||
tokens: embedding_shape.0,
|
||||
width: embedding_shape.1,
|
||||
|
||||
@@ -125,6 +125,48 @@ pub(super) struct GpuBusyStats {
|
||||
}
|
||||
|
||||
unsafe extern "C" {
|
||||
pub(super) fn ds4_gpu_dsv4_topk_mask_tensor(
|
||||
mask: *mut GpuTensor,
|
||||
topk: *const GpuTensor,
|
||||
n_comp: u32,
|
||||
n_tokens: u32,
|
||||
top_k: u32,
|
||||
) -> i32;
|
||||
|
||||
pub(super) fn ds4_gpu_attention_visual_batch_tensor(
|
||||
heads: *mut GpuTensor,
|
||||
map: *const c_void,
|
||||
size: u64,
|
||||
sinks: u64,
|
||||
q: *const GpuTensor,
|
||||
raw: *const GpuTensor,
|
||||
comp: *const GpuTensor,
|
||||
comp_mask: *const GpuTensor,
|
||||
use_mask: u32,
|
||||
rows: u32,
|
||||
pos: u32,
|
||||
n_raw: u32,
|
||||
raw_cap: u32,
|
||||
raw_start: u32,
|
||||
n_comp: u32,
|
||||
window: u32,
|
||||
ratio: u32,
|
||||
n_head: u32,
|
||||
head_dim: u32,
|
||||
mask: *const u16,
|
||||
mask_elements: u64,
|
||||
) -> i32;
|
||||
|
||||
pub(super) fn ds4_gpu_deepseek_vision_dispatch(
|
||||
kernel: *const c_char,
|
||||
bindings: *const MetalBinding,
|
||||
count: u32,
|
||||
grid: *const u32,
|
||||
threads: *const u32,
|
||||
individual_threads: u32,
|
||||
shared_bytes: u32,
|
||||
) -> i32;
|
||||
|
||||
pub(super) fn ds4_gpu_init() -> i32;
|
||||
pub(super) fn ds4_gpu_cleanup();
|
||||
pub(super) fn ds4_gpu_metal4_tensor_api_enabled() -> i32;
|
||||
@@ -1703,6 +1745,28 @@ unsafe extern "C" {
|
||||
scale: f32,
|
||||
rows: u32,
|
||||
) -> i32;
|
||||
pub(super) fn ds4_gpu_router_select_visual_batch_tensor(
|
||||
selected: *mut GpuTensor,
|
||||
weights: *mut GpuTensor,
|
||||
probs: *mut GpuTensor,
|
||||
map: *const c_void,
|
||||
size: u64,
|
||||
bias: u64,
|
||||
hash: u64,
|
||||
hash_rows: u32,
|
||||
expert_groups: u32,
|
||||
groups_used: u32,
|
||||
has_bias: bool,
|
||||
hash_mode: bool,
|
||||
logits: *const GpuTensor,
|
||||
tokens: *const GpuTensor,
|
||||
experts: u32,
|
||||
experts_used: u32,
|
||||
scale: f32,
|
||||
rows: u32,
|
||||
visual_bias: *const GpuTensor,
|
||||
vocab_size: u32,
|
||||
) -> i32;
|
||||
pub(super) fn ds4_gpu_routed_moe_batch_tensor(
|
||||
out: *mut GpuTensor,
|
||||
gate: *mut GpuTensor,
|
||||
|
||||
@@ -0,0 +1,585 @@
|
||||
use super::*;
|
||||
#[test]
|
||||
#[ignore = "requires the pinned Vision-Exp sidecar and Apple Metal"]
|
||||
fn issue100_encoder_real_weights() {
|
||||
super::super::configure_sources().unwrap();
|
||||
let root = std::env::var_os("DS4_ISSUE100_ARTIFACTS")
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_else(|| std::path::PathBuf::from("local-eval-results/issue100-artifacts"));
|
||||
let path = root.join("DeepSeek-V4-Flash-Vision-Encoder.gguf");
|
||||
crate::engine::validation::validate_vision_artifact(&path).unwrap();
|
||||
let model = Gguf::open(&path).unwrap();
|
||||
call(unsafe { ds4_gpu_init() }, "initializing vision test").unwrap();
|
||||
call(
|
||||
unsafe {
|
||||
ds4_gpu_set_model_map_range(
|
||||
model.map_ptr().cast(),
|
||||
model.len(),
|
||||
model.data_offset(),
|
||||
model.len() - model.data_offset(),
|
||||
model.max_tensor_bytes(),
|
||||
)
|
||||
},
|
||||
"mapping vision test weights",
|
||||
)
|
||||
.unwrap();
|
||||
let encoder = Encoder::bind(&model).unwrap();
|
||||
let image_path = std::env::var_os("DS4_ISSUE100_IMAGE").expect("DS4_ISSUE100_IMAGE");
|
||||
let encoded = std::fs::read(image_path).unwrap();
|
||||
let patches = image::decode(&encoded).unwrap();
|
||||
let embedding = encoder.encode(&model, &encoded).unwrap();
|
||||
assert_eq!(embedding.values.len(), embedding.tokens as usize * 4096);
|
||||
assert!(embedding.values.iter().all(|x| x.is_finite()));
|
||||
let prefix = std::env::var_os("DS4_ISSUE100_ENCODER_OUTPUT")
|
||||
.map(std::path::PathBuf::from)
|
||||
.expect("DS4_ISSUE100_ENCODER_OUTPUT");
|
||||
for (suffix, values) in [
|
||||
("patches", &patches.values),
|
||||
("embedding", &embedding.values),
|
||||
] {
|
||||
let bytes = values
|
||||
.iter()
|
||||
.flat_map(|v| v.to_le_bytes())
|
||||
.collect::<Vec<_>>();
|
||||
std::fs::write(prefix.with_extension(format!("{suffix}.f32")), bytes).unwrap();
|
||||
}
|
||||
let info = serde_json::json!({"grid":[patches.grid_height,patches.grid_width],"aligned_grid":[embedding.grid_height,embedding.grid_width],"tokens":embedding.tokens,"width":embedding.width,"height":embedding.height,"values":embedding.values.len()});
|
||||
std::fs::write(
|
||||
prefix.with_extension("json"),
|
||||
serde_json::to_vec_pretty(&info).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
eprintln!("{info}");
|
||||
drop(encoder);
|
||||
unsafe { ds4_gpu_cleanup() };
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires Apple Metal; isolated visual routing and attention primitives"]
|
||||
fn issue100_visual_routing_and_attention() {
|
||||
use crate::engine::deepseek_vision::attention_bounds;
|
||||
super::super::configure_sources().unwrap();
|
||||
call(unsafe { ds4_gpu_init() }, "initializing visual primitives").unwrap();
|
||||
let mut map = memmap2::MmapMut::map_anon(16384).unwrap();
|
||||
let hash_offset = 1024;
|
||||
for expert in 0..256 {
|
||||
let bias = if (30..36).contains(&expert) {
|
||||
100.0 + expert as f32
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
map[expert * 4..expert * 4 + 4].copy_from_slice(&bias.to_le_bytes());
|
||||
}
|
||||
for token in 0..4 {
|
||||
for expert in 0..6 {
|
||||
let id = 60 + (token * 6 + expert) as i32;
|
||||
let offset = hash_offset + (token * 6 + expert) * 4;
|
||||
map[offset..offset + 4].copy_from_slice(&id.to_le_bytes());
|
||||
}
|
||||
}
|
||||
call(
|
||||
unsafe {
|
||||
ds4_gpu_set_model_map_range(
|
||||
map.as_ptr().cast(),
|
||||
map.len() as u64,
|
||||
0,
|
||||
map.len() as u64,
|
||||
1024,
|
||||
)
|
||||
},
|
||||
"mapping routing fixture",
|
||||
)
|
||||
.unwrap();
|
||||
let logits = Buffer::floats(4 * 256).unwrap();
|
||||
let input = (0..4 * 256)
|
||||
.map(|i| ((i % 256) as f32 - 128.0) / 128.0)
|
||||
.collect::<Vec<_>>();
|
||||
logits.write_f32(&input).unwrap();
|
||||
let tokens = Buffer::bytes(16).unwrap();
|
||||
tokens.write_i32(&[1, 1000, 1002, 2]).unwrap();
|
||||
let selected = Buffer::bytes(4 * 6 * 4).unwrap();
|
||||
let weights = Buffer::floats(4 * 6).unwrap();
|
||||
let probs = Buffer::floats(4 * 256).unwrap();
|
||||
let bias = Buffer::floats(256).unwrap();
|
||||
bias.write_f32(
|
||||
&(0..256)
|
||||
.map(|i| {
|
||||
if (200..206).contains(&i) {
|
||||
100.0 + i as f32
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
.unwrap();
|
||||
for hash_mode in [false, true] {
|
||||
let commands = Commands::begin().unwrap();
|
||||
call(
|
||||
unsafe {
|
||||
ds4_gpu_router_select_visual_batch_tensor(
|
||||
selected.raw(),
|
||||
weights.raw(),
|
||||
probs.raw(),
|
||||
map.as_ptr().cast(),
|
||||
map.len() as u64,
|
||||
0,
|
||||
hash_offset as u64,
|
||||
4,
|
||||
0,
|
||||
0,
|
||||
true,
|
||||
hash_mode,
|
||||
logits.raw(),
|
||||
tokens.raw(),
|
||||
256,
|
||||
6,
|
||||
1.5,
|
||||
4,
|
||||
bias.raw(),
|
||||
1000,
|
||||
)
|
||||
},
|
||||
"visual router fixture",
|
||||
)
|
||||
.unwrap();
|
||||
commands.finish().unwrap();
|
||||
let mut ids = vec![0; 24];
|
||||
selected.read_i32(&mut ids).unwrap();
|
||||
let mut actual_weights = vec![0.0; 24];
|
||||
weights.read_f32(&mut actual_weights).unwrap();
|
||||
for row in 0..4 {
|
||||
let expected = if row == 1 || row == 2 {
|
||||
vec![205, 204, 203, 202, 201, 200]
|
||||
} else if hash_mode {
|
||||
let token = if row == 0 { 1 } else { 2 };
|
||||
(0..6).map(|e| 60 + token * 6 + e).collect()
|
||||
} else {
|
||||
vec![35, 34, 33, 32, 31, 30]
|
||||
};
|
||||
assert_eq!(&ids[row * 6..row * 6 + 6], expected);
|
||||
let probability = expected
|
||||
.iter()
|
||||
.map(|&id| input[row * 256 + id as usize].exp().ln_1p().sqrt())
|
||||
.collect::<Vec<_>>();
|
||||
let sum = probability.iter().sum::<f32>().max(6.1035156e-5);
|
||||
for i in 0..6 {
|
||||
assert!((actual_weights[row * 6 + i] - probability[i] / sum * 1.5).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Zero queries make the independent expected result the visible-key mean
|
||||
// with one additional denominator term for the zero attention sink.
|
||||
map[..8].fill(0);
|
||||
let rows = 8_u32;
|
||||
let heads = 2_u32;
|
||||
let dim = 512_u32;
|
||||
let pos = 10_u32;
|
||||
let raw_cap = 32_u32;
|
||||
let raw_start = 25_u32;
|
||||
let n_raw = 18_u32;
|
||||
let q = Buffer::floats(u64::from(rows * heads * dim)).unwrap();
|
||||
q.write_f32(&vec![0.0; (rows * heads * dim) as usize])
|
||||
.unwrap();
|
||||
let raw = Buffer::floats(u64::from(raw_cap * dim)).unwrap();
|
||||
let mut data = vec![0.0; (raw_cap * dim) as usize];
|
||||
for key in 0..n_raw {
|
||||
let physical = (raw_start + key) % raw_cap;
|
||||
data[(physical * dim) as usize..((physical + 1) * dim) as usize].fill(key as f32 / 64.0);
|
||||
}
|
||||
raw.write_f32(&data).unwrap();
|
||||
let comp = Buffer::bytes(4 * 512 * 2).unwrap();
|
||||
// Exactly representable half values: 0.25, 0.5, 0.75, 1.0.
|
||||
let mut comp_bytes = Vec::new();
|
||||
for value in [0x3400_u16, 0x3800, 0x3a00, 0x3c00] {
|
||||
for _ in 0..512 {
|
||||
comp_bytes.extend(value.to_le_bytes());
|
||||
}
|
||||
}
|
||||
comp.write(0, &comp_bytes).unwrap();
|
||||
let out = Buffer::floats(u64::from(rows * heads * dim)).unwrap();
|
||||
let ids = [1, 1000, 1002, 1002, 1004, 2, 3, 4];
|
||||
let bounds = attention_bounds(&ids, 1000, pos, n_raw, 3).unwrap();
|
||||
let comp_mask = Buffer::floats(u64::from(rows) * 4).unwrap();
|
||||
comp_mask
|
||||
.write_f32(
|
||||
&(0..rows)
|
||||
.flat_map(|row| {
|
||||
(0..4).map(move |key| {
|
||||
if key < (pos + row + 1) / 4 && key % 2 == 0 {
|
||||
0.0
|
||||
} else {
|
||||
f32::NEG_INFINITY
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
.unwrap();
|
||||
for (n_comp, indexed) in [(0_u32, false), (4, false), (4, true)] {
|
||||
let mut mask = Vec::new();
|
||||
let mut expected = Vec::new();
|
||||
for row in 0..rows {
|
||||
let mut values = Vec::new();
|
||||
for key in 0..n_raw {
|
||||
let visible =
|
||||
(bounds[row as usize * 2]..=bounds[row as usize * 2 + 1]).contains(&key);
|
||||
mask.push(if visible { 0_u16 } else { 0xfc00 });
|
||||
if visible {
|
||||
values.push(key as f32 / 64.0);
|
||||
}
|
||||
}
|
||||
for key in 0..n_comp {
|
||||
let visible = key < (pos + row + 1) / 4 && (!indexed || key % 2 == 0);
|
||||
mask.push(if visible { 0 } else { 0xfc00 });
|
||||
if visible {
|
||||
values.push((key + 1) as f32 / 4.0);
|
||||
}
|
||||
}
|
||||
expected.push(values.iter().sum::<f32>() / (values.len() + 1) as f32);
|
||||
}
|
||||
let commands = Commands::begin().unwrap();
|
||||
call(
|
||||
unsafe {
|
||||
ds4_gpu_attention_visual_batch_tensor(
|
||||
out.raw(),
|
||||
map.as_ptr().cast(),
|
||||
map.len() as u64,
|
||||
0,
|
||||
q.raw(),
|
||||
raw.raw(),
|
||||
comp.raw(),
|
||||
if indexed {
|
||||
comp_mask.raw().cast_const()
|
||||
} else {
|
||||
std::ptr::null()
|
||||
},
|
||||
u32::from(indexed),
|
||||
rows,
|
||||
pos,
|
||||
n_raw,
|
||||
raw_cap,
|
||||
raw_start,
|
||||
n_comp,
|
||||
3,
|
||||
if n_comp == 0 { 0 } else { 4 },
|
||||
heads,
|
||||
dim,
|
||||
mask.as_ptr(),
|
||||
mask.len() as u64,
|
||||
)
|
||||
},
|
||||
"visual attention fixture",
|
||||
)
|
||||
.unwrap();
|
||||
commands.finish().unwrap();
|
||||
let mut actual = vec![0.0; (rows * heads * dim) as usize];
|
||||
out.read_f32(&mut actual).unwrap();
|
||||
for (row, expected) in expected.iter().enumerate() {
|
||||
for value in &actual[row * (heads * dim) as usize..(row + 1) * (heads * dim) as usize] {
|
||||
assert!(
|
||||
(value - expected).abs() < 0.0005,
|
||||
"row {row}: {value} != {expected}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!(
|
||||
"issue100 visual routing: hash/text/image rows and weights pass; raw/mixed/index-masked visual attention with wrapped KV passes"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires the verified Vision-Exp managed artifacts and 110 GiB of Apple unified memory"]
|
||||
fn issue100_full_model_images_cache_and_dspark() {
|
||||
use crate::engine::{ChatTurn, Generator, metal::Executor, vision_data_marker};
|
||||
use crate::metrics::Metrics;
|
||||
use crate::model::ModelChoice;
|
||||
use crate::settings::{
|
||||
GenerationPreferences, ReasoningMode, RuntimePreferences, effective_settings,
|
||||
};
|
||||
use base64::Engine as _;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, atomic::AtomicBool};
|
||||
super::super::configure_sources().unwrap();
|
||||
let root = Path::new("local-eval-results/issue100-managed");
|
||||
let cache = Path::new("local-eval-results/issue100-full-model");
|
||||
std::fs::create_dir_all(cache).unwrap();
|
||||
let generation = GenerationPreferences {
|
||||
context_tokens: 1024,
|
||||
max_generated_tokens: 32,
|
||||
system_prompt: String::new(),
|
||||
temperature: Some(0.0),
|
||||
reasoning_mode: ReasoningMode::Direct,
|
||||
..Default::default()
|
||||
};
|
||||
let mut runtime = RuntimePreferences::default();
|
||||
runtime.execution.prefill_chunk = Some(384);
|
||||
runtime.execution.power_percent = Some(100);
|
||||
if std::env::var_os("DS4_ISSUE100_SSD").is_some() {
|
||||
runtime.ssd.enabled = true;
|
||||
runtime.ssd.cache = Some(crate::settings::StreamingCacheBudget::Experts(4096));
|
||||
runtime.ssd.preload_experts = Some(4096);
|
||||
}
|
||||
runtime.speculative.dspark_enabled = true;
|
||||
runtime.speculative.dspark_confidence_threshold = Some(0.0);
|
||||
runtime.speculative.keep_vision_loaded = std::env::var_os("DS4_ISSUE100_KEEP_VISION").is_some();
|
||||
let settings = effective_settings(
|
||||
ModelChoice::DeepSeekV4FlashVision,
|
||||
&generation,
|
||||
&runtime,
|
||||
root,
|
||||
)
|
||||
.unwrap();
|
||||
let mut generator = Generator::open(&settings.engine, Arc::new(Metrics::new(cache))).unwrap();
|
||||
let image_marker = |name: &str| {
|
||||
let bytes = std::fs::read(format!("docs/issue100-vision/images/{name}.png")).unwrap();
|
||||
vision_data_marker(&format!(
|
||||
"data:image/png;base64,{}",
|
||||
base64::engine::general_purpose::STANDARD.encode(bytes)
|
||||
))
|
||||
};
|
||||
let turn = |content: String, tool: bool| ChatTurn {
|
||||
user: !tool,
|
||||
tool,
|
||||
system: false,
|
||||
skip_previous_eos: false,
|
||||
reasoning: None,
|
||||
reasoning_complete: true,
|
||||
content,
|
||||
};
|
||||
let red = turn(
|
||||
format!(
|
||||
"Describe the color and shape in this image in one sentence. {}",
|
||||
image_marker("red-square")
|
||||
),
|
||||
false,
|
||||
);
|
||||
let blue = turn(
|
||||
red.content
|
||||
.replace(&image_marker("red-square"), &image_marker("blue-circle")),
|
||||
false,
|
||||
);
|
||||
let (red_tokens, red_overlays) = generator
|
||||
.render_multimodal_conversation("", std::slice::from_ref(&red), ReasoningMode::Direct)
|
||||
.unwrap();
|
||||
let (blue_tokens, blue_overlays) = generator
|
||||
.render_multimodal_conversation("", std::slice::from_ref(&blue), ReasoningMode::Direct)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
red_tokens, blue_tokens,
|
||||
"same-size images intentionally have identical synthetic tokens"
|
||||
);
|
||||
assert_eq!(red_overlays.len(), 1);
|
||||
assert_eq!(blue_overlays.len(), 1);
|
||||
let prompt_checkpoint = cache.join("prompt.kv");
|
||||
let restored_checkpoint = cache.join("restored.kv");
|
||||
let Executor::DeepSeek(executor) = &mut generator.executor else {
|
||||
panic!("wrong executor")
|
||||
};
|
||||
executor.set_vision_overlays(red_overlays).unwrap();
|
||||
executor.prefill(&red_tokens, |_| true).unwrap();
|
||||
assert_eq!(executor.vision_identities.len(), 1);
|
||||
let image_identity = executor.vision_identities.clone();
|
||||
let prompt_logits = executor.logits.clone();
|
||||
executor
|
||||
.save_checkpoint(&prompt_checkpoint, [100; 32], &mut |_| {})
|
||||
.unwrap();
|
||||
executor.reset().unwrap();
|
||||
assert!(
|
||||
executor
|
||||
.load_checkpoint(&prompt_checkpoint, &mut |_| {})
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(executor.logits, prompt_logits);
|
||||
assert_eq!(executor.vision_identities, image_identity);
|
||||
assert!(executor.vision_overlays.is_empty());
|
||||
// Verifier-sized text batches after disk restoration must retain image
|
||||
// identities even though no image embeddings are needed for this suffix.
|
||||
executor.prefill(&[19923, 14, 2058, 3], |_| true).unwrap();
|
||||
assert_eq!(executor.vision_identities, image_identity);
|
||||
executor
|
||||
.save_checkpoint(&restored_checkpoint, [100; 32], &mut |_| {})
|
||||
.unwrap();
|
||||
executor.reset().unwrap();
|
||||
assert!(
|
||||
executor
|
||||
.load_checkpoint(&restored_checkpoint, &mut |_| {})
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(executor.vision_identities, image_identity);
|
||||
executor.set_vision_overlays(blue_overlays).unwrap();
|
||||
assert_eq!(
|
||||
executor.session.position, 0,
|
||||
"changed image must invalidate equal token prefix"
|
||||
);
|
||||
let cancelled = AtomicBool::new(false);
|
||||
let run = |g: &mut Generator, messages: &[ChatTurn], checkpoint: &Path| {
|
||||
g.generate(
|
||||
checkpoint,
|
||||
None,
|
||||
messages,
|
||||
&settings.turn,
|
||||
&cancelled,
|
||||
|_, _| {},
|
||||
|_, _, _| {},
|
||||
|_| {},
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
let first = run(
|
||||
&mut generator,
|
||||
std::slice::from_ref(&red),
|
||||
&cache.join("red.kv"),
|
||||
);
|
||||
eprintln!("red: {}", first.message.content);
|
||||
assert!(first.message.content.to_lowercase().contains("red"));
|
||||
assert!(first.message.content.to_lowercase().contains("square"));
|
||||
let stats = generator.executor.execution_stats();
|
||||
assert!(
|
||||
stats.drafted_tokens > 0,
|
||||
"the matching DSpark must actually draft"
|
||||
);
|
||||
eprintln!(
|
||||
"DSpark drafted={} accepted={}",
|
||||
stats.drafted_tokens, stats.accepted_draft_tokens
|
||||
);
|
||||
let Executor::DeepSeek(executor) = &mut generator.executor else {
|
||||
unreachable!()
|
||||
};
|
||||
executor.reset().unwrap();
|
||||
executor.dspark.as_mut().unwrap().strict = true;
|
||||
let plain = run(
|
||||
&mut generator,
|
||||
std::slice::from_ref(&red),
|
||||
&cache.join("red-target.kv"),
|
||||
);
|
||||
assert_eq!(
|
||||
plain.message.content, first.message.content,
|
||||
"DSpark and target-only output"
|
||||
);
|
||||
std::fs::copy(cache.join("red-target.kv"), cache.join("red-disk.kv")).unwrap();
|
||||
let history = [
|
||||
red.clone(),
|
||||
plain.message.clone(),
|
||||
turn(
|
||||
"What color was the shape? Answer with one word.".into(),
|
||||
false,
|
||||
),
|
||||
];
|
||||
let warm = run(&mut generator, &history, &cache.join("red-target.kv"));
|
||||
assert!(
|
||||
warm.cached_tokens > 0,
|
||||
"warm image history must reuse its KV prefix"
|
||||
);
|
||||
assert!(warm.message.content.to_lowercase().contains("red"));
|
||||
generator.executor.reset().unwrap();
|
||||
generator.checkpoint = None;
|
||||
let restored = run(&mut generator, &history, &cache.join("red-disk.kv"));
|
||||
assert!(
|
||||
restored.cached_tokens > 0,
|
||||
"disk image history must reuse its KV prefix"
|
||||
);
|
||||
assert_eq!(restored.message.content, warm.message.content);
|
||||
let mut append_history = history.to_vec();
|
||||
append_history.push(restored.message.clone());
|
||||
append_history.push(turn(
|
||||
format!(
|
||||
"Name the color in this new image. {}",
|
||||
image_marker("blue-circle")
|
||||
),
|
||||
false,
|
||||
));
|
||||
let appended = run(&mut generator, &append_history, &cache.join("red-disk.kv"));
|
||||
assert!(
|
||||
appended.cached_tokens > 0,
|
||||
"appending an image must retain the previous image/text frontier"
|
||||
);
|
||||
assert!(appended.message.content.to_lowercase().contains("blue"));
|
||||
append_history.push(appended.message.clone());
|
||||
append_history.push(turn(
|
||||
format!(
|
||||
"The tool returned this image. Describe its color. {}",
|
||||
image_marker("red-square")
|
||||
),
|
||||
true,
|
||||
));
|
||||
let appended_tool = run(&mut generator, &append_history, &cache.join("red-disk.kv"));
|
||||
assert!(
|
||||
appended_tool.cached_tokens > 0,
|
||||
"tool image append must retain the live frontier"
|
||||
);
|
||||
assert!(appended_tool.message.content.to_lowercase().contains("red"));
|
||||
|
||||
let changed = run(
|
||||
&mut generator,
|
||||
std::slice::from_ref(&blue),
|
||||
&cache.join("blue.kv"),
|
||||
);
|
||||
eprintln!("blue: {}", changed.message.content);
|
||||
assert!(changed.message.content.to_lowercase().contains("blue"));
|
||||
assert!(changed.message.content.to_lowercase().contains("circle"));
|
||||
let pair = turn(
|
||||
format!(
|
||||
"Name the color of the first shape, then the second shape. {} {}",
|
||||
image_marker("red-square"),
|
||||
image_marker("blue-circle")
|
||||
),
|
||||
false,
|
||||
);
|
||||
let both = run(&mut generator, &[pair], &cache.join("pair.kv"));
|
||||
eprintln!("pair: {}", both.message.content);
|
||||
let answer = both.message.content.to_lowercase();
|
||||
assert!(answer.contains("red") && answer.contains("blue"));
|
||||
assert!(answer.find("red").unwrap() < answer.find("blue").unwrap());
|
||||
let swapped = turn(
|
||||
format!(
|
||||
"Name the color of the first shape, then the second shape. {} {}",
|
||||
image_marker("blue-circle"),
|
||||
image_marker("red-square")
|
||||
),
|
||||
false,
|
||||
);
|
||||
let (swapped_tokens, swapped_overlays) = generator
|
||||
.render_multimodal_conversation("", std::slice::from_ref(&swapped), ReasoningMode::Direct)
|
||||
.unwrap();
|
||||
let Executor::DeepSeek(executor) = &mut generator.executor else {
|
||||
unreachable!()
|
||||
};
|
||||
assert!(
|
||||
executor.tokens.starts_with(&swapped_tokens),
|
||||
"swapping equal-sized images preserves the prompt IDs"
|
||||
);
|
||||
executor.set_vision_overlays(swapped_overlays).unwrap();
|
||||
assert_eq!(
|
||||
executor.session.position, 0,
|
||||
"reordered images must invalidate cached KV"
|
||||
);
|
||||
|
||||
let tool = [
|
||||
turn(
|
||||
"Name the color in the image returned by the tool.".into(),
|
||||
false,
|
||||
),
|
||||
turn(image_marker("blue-circle"), true),
|
||||
];
|
||||
let tool_output = run(&mut generator, &tool, &cache.join("tool.kv"));
|
||||
eprintln!("tool image: {}", tool_output.message.content);
|
||||
assert!(tool_output.message.content.to_lowercase().contains("blue"));
|
||||
let text_only = run(
|
||||
&mut generator,
|
||||
&[turn(
|
||||
"What is 2 + 2? Reply with just the number.".into(),
|
||||
false,
|
||||
)],
|
||||
&cache.join("text.kv"),
|
||||
);
|
||||
assert!(text_only.message.content.contains('4'));
|
||||
let Executor::DeepSeek(executor) = &generator.executor else {
|
||||
unreachable!()
|
||||
};
|
||||
assert!(executor.vision_identities.is_empty());
|
||||
eprintln!(
|
||||
"issue100: production rendering, image recognition, multi-image/tool input, same-layout image invalidation, disk/warm KV and DSpark target equivalence passed"
|
||||
);
|
||||
}
|
||||
@@ -15,7 +15,10 @@ pub(super) struct VisionEncoder {
|
||||
|
||||
pub(in crate::engine) struct VisionEmbedding {
|
||||
pub(in crate::engine) values: Vec<f32>,
|
||||
pub(in crate::engine) fingerprint: [u8; 32],
|
||||
pub(in crate::engine) tokens: u32,
|
||||
pub(in crate::engine) grid_width: u32,
|
||||
pub(in crate::engine) grid_height: u32,
|
||||
pub(in crate::engine) width: u32,
|
||||
pub(in crate::engine) height: u32,
|
||||
pub(in crate::engine) content_width: u32,
|
||||
@@ -100,6 +103,9 @@ impl VisionEncoder {
|
||||
"encoding a GLM 5.3 image",
|
||||
)?;
|
||||
Ok(VisionEmbedding {
|
||||
fingerprint: [0; 32],
|
||||
grid_width: 0,
|
||||
grid_height: 0,
|
||||
values,
|
||||
tokens,
|
||||
width,
|
||||
@@ -241,7 +247,7 @@ fn smart_resize(height: u32, width: u32) -> Result<(u32, u32), String> {
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn resize_bicubic(
|
||||
pub(in crate::engine) fn resize_bicubic(
|
||||
source: &[u8],
|
||||
source_width: u32,
|
||||
source_height: u32,
|
||||
|
||||
+191
-9
@@ -433,6 +433,32 @@ impl Tokenizer {
|
||||
messages: &[ChatTurn],
|
||||
reasoning: ReasoningMode,
|
||||
continue_assistant: bool,
|
||||
) -> Vec<i32> {
|
||||
self.encode_messages_inner(
|
||||
system_prompt,
|
||||
messages,
|
||||
reasoning,
|
||||
continue_assistant,
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn encode_deepseek_vision_conversation(
|
||||
&self,
|
||||
system: &str,
|
||||
messages: &[ChatTurn],
|
||||
reasoning: ReasoningMode,
|
||||
) -> Vec<i32> {
|
||||
self.encode_messages_inner(system, messages, reasoning, true, true)
|
||||
}
|
||||
|
||||
fn encode_messages_inner(
|
||||
&self,
|
||||
system_prompt: &str,
|
||||
messages: &[ChatTurn],
|
||||
reasoning: ReasoningMode,
|
||||
continue_assistant: bool,
|
||||
vision: bool,
|
||||
) -> Vec<i32> {
|
||||
if self.family == ModelFamily::Qwen {
|
||||
return self.encode_qwen_messages(
|
||||
@@ -481,13 +507,14 @@ impl Tokenizer {
|
||||
} else {
|
||||
output.push(self.user);
|
||||
output.extend(self.tokenize("<tool_result>"));
|
||||
output.extend(
|
||||
self.tokenize(
|
||||
&message
|
||||
.content
|
||||
.replace("</tool_result>", "</tool_result>"),
|
||||
),
|
||||
);
|
||||
let content = message
|
||||
.content
|
||||
.replace("</tool_result>", "</tool_result>");
|
||||
if vision && content.contains(VISION_TOKEN_START) {
|
||||
self.tokenize_vision_text(&content, &mut output);
|
||||
} else {
|
||||
output.extend(self.tokenize(&content));
|
||||
}
|
||||
output.extend(self.tokenize("</tool_result>"));
|
||||
}
|
||||
continue;
|
||||
@@ -510,7 +537,11 @@ impl Tokenizer {
|
||||
output.push(self.think_end);
|
||||
}
|
||||
}
|
||||
output.extend(self.tokenize_rendered(&message.content));
|
||||
if vision && message.user && message.content.contains(VISION_TOKEN_START) {
|
||||
self.tokenize_vision_text(&message.content, &mut output);
|
||||
} else {
|
||||
output.extend(self.tokenize_rendered(&message.content));
|
||||
}
|
||||
if !message.user
|
||||
&& self.family == ModelFamily::DeepSeek
|
||||
&& (continue_assistant || index + 1 < messages.len())
|
||||
@@ -531,6 +562,28 @@ impl Tokenizer {
|
||||
output
|
||||
}
|
||||
|
||||
fn tokenize_vision_text(&self, text: &str, output: &mut Vec<i32>) {
|
||||
let mut rest = text;
|
||||
while let Some(start) = rest.find(VISION_TOKEN_START) {
|
||||
let tail = &rest[start + VISION_TOKEN_START.len()..];
|
||||
let Some(end) = tail.find(VISION_TOKEN_END) else {
|
||||
break;
|
||||
};
|
||||
let Ok(count) = tail[..end].parse::<usize>() else {
|
||||
break;
|
||||
};
|
||||
if count > 384 {
|
||||
break;
|
||||
}
|
||||
output.extend(self.tokenize(&rest[..start]));
|
||||
output.push(VISION_START_TOKEN);
|
||||
output.extend(std::iter::repeat_n(VISION_IMAGE_TOKEN, count));
|
||||
output.push(VISION_END_TOKEN);
|
||||
rest = &tail[end + VISION_TOKEN_END.len()..];
|
||||
}
|
||||
output.extend(self.tokenize(rest));
|
||||
}
|
||||
|
||||
fn encode_qwen_messages(
|
||||
&self,
|
||||
system_prompt: Option<&str>,
|
||||
@@ -646,6 +699,42 @@ impl Tokenizer {
|
||||
prompt: &str,
|
||||
reasoning: ReasoningMode,
|
||||
skip_previous_eos: bool,
|
||||
) -> Vec<i32> {
|
||||
self.encode_continuation_inner(prompt, reasoning, skip_previous_eos, false)
|
||||
}
|
||||
|
||||
pub(super) fn encode_deepseek_vision_continuation(
|
||||
&self,
|
||||
prompt: &str,
|
||||
reasoning: ReasoningMode,
|
||||
skip_previous_eos: bool,
|
||||
) -> Vec<i32> {
|
||||
self.encode_continuation_inner(prompt, reasoning, skip_previous_eos, true)
|
||||
}
|
||||
|
||||
pub(super) fn encode_deepseek_vision_tool_continuation(
|
||||
&self,
|
||||
message: &ChatTurn,
|
||||
reasoning: ReasoningMode,
|
||||
) -> Vec<i32> {
|
||||
let mut output =
|
||||
self.encode_deepseek_vision_conversation("", std::slice::from_ref(message), reasoning);
|
||||
// A standalone conversation starts with BOS. The live frontier instead
|
||||
// needs the preceding assistant's EOS, just like a user continuation.
|
||||
if message.skip_previous_eos {
|
||||
output.remove(0);
|
||||
} else {
|
||||
output[0] = self.eos;
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
fn encode_continuation_inner(
|
||||
&self,
|
||||
prompt: &str,
|
||||
reasoning: ReasoningMode,
|
||||
skip_previous_eos: bool,
|
||||
vision: bool,
|
||||
) -> Vec<i32> {
|
||||
if self.family == ModelFamily::Qwen {
|
||||
let messages = [ChatTurn {
|
||||
@@ -664,7 +753,11 @@ impl Tokenizer {
|
||||
output.push(self.eos);
|
||||
}
|
||||
output.push(self.user);
|
||||
output.extend(self.tokenize_rendered(prompt));
|
||||
if vision && prompt.contains(VISION_TOKEN_START) {
|
||||
self.tokenize_vision_text(prompt, &mut output);
|
||||
} else {
|
||||
output.extend(self.tokenize_rendered(prompt));
|
||||
}
|
||||
output.push(self.assistant);
|
||||
if reasoning != ReasoningMode::Direct {
|
||||
output.push(self.think_start);
|
||||
@@ -1238,6 +1331,95 @@ fn unicode_punctuation(cp: u32) -> bool {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
#[ignore = "CPU-only; requires the installed 0731 tokenizer shared with Vision-Exp"]
|
||||
fn issue100_visual_text_preserves_image_boundaries() {
|
||||
use super::super::Model;
|
||||
use crate::model::ModelChoice;
|
||||
let path = crate::model::engine_artifacts(
|
||||
ModelChoice::DeepSeekV4Flash0731,
|
||||
false,
|
||||
&crate::app::models_path(),
|
||||
)
|
||||
.model;
|
||||
let model = Model::open_main(&path, ModelChoice::DeepSeekV4Flash0731).unwrap();
|
||||
let tokenizer = &model.tokenizer;
|
||||
let marker = format!("{VISION_TOKEN_START}2{VISION_TOKEN_END}");
|
||||
let prompt = format!("before{marker}after");
|
||||
for reasoning in ModelChoice::DeepSeekV4FlashVision.reasoning_modes() {
|
||||
for skip_eos in [false, true] {
|
||||
let mut expected = Vec::new();
|
||||
if !skip_eos {
|
||||
expected.push(tokenizer.eos);
|
||||
}
|
||||
expected.push(tokenizer.user);
|
||||
expected.extend(tokenizer.tokenize("before"));
|
||||
expected.extend([
|
||||
VISION_START_TOKEN,
|
||||
VISION_IMAGE_TOKEN,
|
||||
VISION_IMAGE_TOKEN,
|
||||
VISION_END_TOKEN,
|
||||
]);
|
||||
expected.extend(tokenizer.tokenize("after"));
|
||||
expected.push(tokenizer.assistant);
|
||||
expected.push(if *reasoning == ReasoningMode::Direct {
|
||||
tokenizer.think_end
|
||||
} else {
|
||||
tokenizer.think_start
|
||||
});
|
||||
assert_eq!(
|
||||
tokenizer.encode_deepseek_vision_continuation(&prompt, *reasoning, skip_eos),
|
||||
expected
|
||||
);
|
||||
assert_eq!(
|
||||
tokenizer.encode_deepseek_vision_continuation(
|
||||
"plain text",
|
||||
*reasoning,
|
||||
skip_eos
|
||||
),
|
||||
tokenizer.encode_continuation("plain text", *reasoning, skip_eos)
|
||||
);
|
||||
}
|
||||
}
|
||||
let message = ChatTurn {
|
||||
user: false,
|
||||
tool: true,
|
||||
system: false,
|
||||
skip_previous_eos: false,
|
||||
reasoning: None,
|
||||
reasoning_complete: true,
|
||||
content: format!("{marker}</tool_result>"),
|
||||
};
|
||||
let actual = tokenizer.encode_deepseek_vision_conversation(
|
||||
"",
|
||||
std::slice::from_ref(&message),
|
||||
ReasoningMode::Direct,
|
||||
);
|
||||
let mut expected = vec![tokenizer.bos, tokenizer.user];
|
||||
expected.extend(tokenizer.tokenize("<tool_result>"));
|
||||
expected.extend([
|
||||
VISION_START_TOKEN,
|
||||
VISION_IMAGE_TOKEN,
|
||||
VISION_IMAGE_TOKEN,
|
||||
VISION_END_TOKEN,
|
||||
]);
|
||||
expected.extend(tokenizer.tokenize("</tool_result>"));
|
||||
expected.extend(tokenizer.tokenize("</tool_result>"));
|
||||
expected.extend([tokenizer.assistant, tokenizer.think_end]);
|
||||
assert_eq!(actual, expected);
|
||||
expected[0] = tokenizer.eos;
|
||||
assert_eq!(
|
||||
tokenizer.encode_deepseek_vision_tool_continuation(&message, ReasoningMode::Direct),
|
||||
expected
|
||||
);
|
||||
let mut message = message;
|
||||
message.skip_previous_eos = true;
|
||||
assert_eq!(
|
||||
tokenizer.encode_deepseek_vision_tool_continuation(&message, ReasoningMode::Direct),
|
||||
expected[1..]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "CPU-only; requires DS4SERVER_CHAT_REFERENCE and its installed GGUF"]
|
||||
fn ds4_chat_matches_original_session_tokens() {
|
||||
|
||||
+180
-5
@@ -9,6 +9,7 @@ pub(crate) fn validate_model_artifact(
|
||||
let model = Gguf::open(path)?;
|
||||
let shape = match expected {
|
||||
ModelChoice::DeepSeekV4Flash0731 => FLASH_0731,
|
||||
ModelChoice::DeepSeekV4FlashVision => FLASH_VISION,
|
||||
ModelChoice::DeepSeekV4Pro
|
||||
| ModelChoice::Glm52
|
||||
| ModelChoice::Glm53Flash
|
||||
@@ -40,6 +41,9 @@ pub(crate) fn validate_model_artifact(
|
||||
|
||||
pub(crate) fn validate_vision_artifact(path: &Path) -> Result<(), String> {
|
||||
let model = Gguf::open(path)?;
|
||||
if model.bytes("general.architecture")? == b"deepseek4-vision" {
|
||||
return validate_deepseek_vision(&model);
|
||||
}
|
||||
if model.bytes("general.architecture")? != b"glm5-next-vision" {
|
||||
return Err("vision GGUF architecture is not glm5-next-vision".into());
|
||||
}
|
||||
@@ -193,11 +197,21 @@ pub(super) fn validate_support(model: &Gguf, shape: &Shape) -> Result<SupportKin
|
||||
|
||||
pub(super) fn validate_main(model: &Gguf, expected: ModelChoice) -> Result<Shape, String> {
|
||||
let architecture = model.bytes("general.architecture")?;
|
||||
let variant = model.metadata.contains_key("deepseek4.checkpoint_variant");
|
||||
if variant && (architecture != b"deepseek4" || model.u32("deepseek4.block_count")? != 43) {
|
||||
return Err("Vision-Exp metadata requires a DeepSeek V4 Flash checkpoint".into());
|
||||
}
|
||||
let shape = match architecture {
|
||||
b"glm-dsa" => GLM,
|
||||
b"glm5-next" => GLM53_FLASH,
|
||||
_ => match (model.u32("deepseek4.block_count")?, expected) {
|
||||
(43, ModelChoice::DeepSeekV4Flash0731) => FLASH_0731,
|
||||
(43, _) if variant => {
|
||||
validate_vision_checkpoint(model)?;
|
||||
if !model.boolean("deepseek4.vision.sidecar_required")? {
|
||||
return Err("DeepSeek Vision-Exp requires its sidecar metadata".into());
|
||||
}
|
||||
FLASH_VISION
|
||||
}
|
||||
(43, _) => FLASH_0731,
|
||||
(61, _) => PRO,
|
||||
(layers, _) => return Err(format!("unsupported DeepSeek layer count: {layers}")),
|
||||
@@ -210,6 +224,14 @@ pub(super) fn validate_main(model: &Gguf, expected: ModelChoice) -> Result<Shape
|
||||
shape.model
|
||||
));
|
||||
}
|
||||
if shape.model == ModelChoice::DeepSeekV4FlashVision
|
||||
&& model
|
||||
.f32("deepseek4.attention.layer_norm_rms_epsilon")?
|
||||
.to_bits()
|
||||
!= shape.rms_epsilon.to_bits()
|
||||
{
|
||||
return Err("DeepSeek Vision-Exp RMS epsilon must be 1e-20".into());
|
||||
}
|
||||
validate_metadata(model, &shape)?;
|
||||
validate_tensors(model, &shape)?;
|
||||
Ok(shape)
|
||||
@@ -825,9 +847,14 @@ fn validate_glm_tensors(model: &Gguf, shape: &Shape) -> Result<(), String> {
|
||||
}
|
||||
|
||||
pub(super) fn validate_dspark(model: &Gguf, shape: &Shape) -> Result<(), String> {
|
||||
if !matches!(shape.model, ModelChoice::DeepSeekV4Flash0731) {
|
||||
if !shape.model.supports_dspark() {
|
||||
return Err("DSpark support is available only for DeepSeek V4 Flash".into());
|
||||
}
|
||||
if shape.model == ModelChoice::DeepSeekV4FlashVision {
|
||||
validate_vision_checkpoint(model)?;
|
||||
} else if model.metadata.contains_key("deepseek4.checkpoint_variant") {
|
||||
return Err("Vision-Exp DSpark support cannot be used with another checkpoint".into());
|
||||
}
|
||||
let DsparkConfig {
|
||||
block_size,
|
||||
markov_rank,
|
||||
@@ -1060,14 +1087,18 @@ fn float_eq(actual: f32, expected: f32) -> bool {
|
||||
|
||||
fn compression_ratio(shape: &Shape, layer: u32) -> u32 {
|
||||
match shape.model {
|
||||
ModelChoice::DeepSeekV4Flash0731 if layer < 2 => 0,
|
||||
ModelChoice::DeepSeekV4FlashVision | ModelChoice::DeepSeekV4Flash0731 if layer < 2 => 0,
|
||||
ModelChoice::DeepSeekV4Pro if layer < 2 => 128,
|
||||
ModelChoice::DeepSeekV4Flash0731 | ModelChoice::DeepSeekV4Pro
|
||||
ModelChoice::DeepSeekV4FlashVision
|
||||
| ModelChoice::DeepSeekV4Flash0731
|
||||
| ModelChoice::DeepSeekV4Pro
|
||||
if layer.is_multiple_of(2) =>
|
||||
{
|
||||
4
|
||||
}
|
||||
ModelChoice::DeepSeekV4Flash0731 | ModelChoice::DeepSeekV4Pro => 128,
|
||||
ModelChoice::DeepSeekV4FlashVision
|
||||
| ModelChoice::DeepSeekV4Flash0731
|
||||
| ModelChoice::DeepSeekV4Pro => 128,
|
||||
ModelChoice::Glm52 | ModelChoice::Glm53Flash | ModelChoice::Qwen38FlashNext => 0,
|
||||
}
|
||||
}
|
||||
@@ -1084,10 +1115,154 @@ fn first_u32s<'a>(model: &'a Gguf, keys: &[&str]) -> Result<&'a [u32], String> {
|
||||
.ok_or_else(|| format!("required DSpark metadata is missing: {}", keys[0]))
|
||||
}
|
||||
|
||||
fn validate_vision_checkpoint(model: &Gguf) -> Result<(), String> {
|
||||
if model.bytes("deepseek4.checkpoint_variant")? != b"vision-exp"
|
||||
|| model.bytes("general.source.revision")? != deepseek_vision::SOURCE_REVISION
|
||||
{
|
||||
return Err(
|
||||
"DeepSeek Vision-Exp checkpoint does not match the pinned source revision".into(),
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_deepseek_vision(model: &Gguf) -> Result<(), String> {
|
||||
if model.bytes("deepseek4-vision.checkpoint_variant")? != b"vision-exp"
|
||||
|| model.bytes("general.source.revision")? != deepseek_vision::SOURCE_REVISION
|
||||
{
|
||||
return Err("DeepSeek vision encoder does not match the pinned checkpoint".into());
|
||||
}
|
||||
if model.tensors.len() != 316 {
|
||||
return Err(format!(
|
||||
"DeepSeek vision encoder has {} tensors, expected 316",
|
||||
model.tensors.len()
|
||||
));
|
||||
}
|
||||
for (key, value) in [
|
||||
("block_count", 32),
|
||||
("embedding_length", 1024),
|
||||
("feed_forward_length", 2816),
|
||||
("attention.head_count", 16),
|
||||
("projection_length", 4096),
|
||||
("patch_size", 14),
|
||||
("downsample_ratio", 3),
|
||||
("image.max_tokens", 384),
|
||||
("image.min_pixels", 147456),
|
||||
("image.max_width_height_ratio", 8),
|
||||
("language.block_count", 43),
|
||||
("language.expert_count", 256),
|
||||
] {
|
||||
expect_u64(model, &format!("deepseek4-vision.{key}"), value)?;
|
||||
}
|
||||
expect_float(
|
||||
model,
|
||||
"deepseek4-vision.attention.layer_norm_rms_epsilon",
|
||||
1e-6,
|
||||
)?;
|
||||
expect_float(model, "deepseek4-vision.rope.freq_base", 10000.0)?;
|
||||
for (name, dims) in [
|
||||
("vision.patch_embed.proj.weight", vec![588, 1024]),
|
||||
("vision.patch_embed.proj.bias", vec![1024]),
|
||||
("vision.norm.weight", vec![1024]),
|
||||
("aligner.w1.weight", vec![9216, 4096]),
|
||||
("aligner.w1.bias", vec![4096]),
|
||||
("aligner.w2.weight", vec![4096, 4096]),
|
||||
("aligner.w2.bias", vec![4096]),
|
||||
("image_start", vec![4096]),
|
||||
("image_pad", vec![4096]),
|
||||
("image_newline", vec![4096]),
|
||||
("image_end", vec![4096]),
|
||||
] {
|
||||
expect(model, name, &[BF16], &dims)?;
|
||||
}
|
||||
for layer in 0..32 {
|
||||
for (suffix, dims) in [
|
||||
("norm1.weight", vec![1024]),
|
||||
("attn.wqkv.weight", vec![1024, 3072]),
|
||||
("attn.wqkv.bias", vec![3072]),
|
||||
("attn.wo.weight", vec![1024, 1024]),
|
||||
("attn.wo.bias", vec![1024]),
|
||||
("norm2.weight", vec![1024]),
|
||||
("mlp.w1.weight", vec![1024, 5632]),
|
||||
("mlp.w2.weight", vec![2816, 1024]),
|
||||
] {
|
||||
expect(
|
||||
model,
|
||||
&format!("vision.blocks.{layer}.{suffix}"),
|
||||
&[BF16],
|
||||
&dims,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
for layer in 0..43 {
|
||||
expect(
|
||||
model,
|
||||
&format!("layers.{layer}.ffn.gate.bias_vl"),
|
||||
&[F32],
|
||||
&[256],
|
||||
)?;
|
||||
}
|
||||
for stage in 0..3 {
|
||||
expect(
|
||||
model,
|
||||
&format!("mtp.{stage}.ffn.gate.bias_vl"),
|
||||
&[F32],
|
||||
&[256],
|
||||
)?;
|
||||
expect(
|
||||
model,
|
||||
&format!("layers.{stage}.ffn.gate.bias"),
|
||||
&[F32],
|
||||
&[256],
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires the pinned Vision-Exp encoder and DSpark support GGUFs"]
|
||||
fn issue100_checkpoint_metadata_is_strict() {
|
||||
let root = Path::new("local-eval-results/issue100-artifacts");
|
||||
let mut sidecar = Gguf::open(&root.join("DeepSeek-V4-Flash-Vision-Encoder.gguf")).unwrap();
|
||||
validate_deepseek_vision(&sidecar).unwrap();
|
||||
let revision = sidecar
|
||||
.metadata
|
||||
.insert(
|
||||
"general.source.revision".into(),
|
||||
Value::Bytes(b"wrong".to_vec()),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(validate_deepseek_vision(&sidecar).is_err());
|
||||
sidecar
|
||||
.metadata
|
||||
.insert("general.source.revision".into(), revision);
|
||||
sidecar.tensors.remove("layers.42.ffn.gate.bias_vl");
|
||||
assert!(validate_deepseek_vision(&sidecar).is_err());
|
||||
let mut support =
|
||||
Gguf::open(&root.join("DeepSeek-V4-Flash-Vision-Exp-DSpark-support.gguf")).unwrap();
|
||||
assert!(matches!(
|
||||
validate_support(&support, &FLASH_VISION).unwrap(),
|
||||
SupportKind::DSpark
|
||||
));
|
||||
assert!(validate_support(&support, &FLASH_0731).is_err());
|
||||
support.metadata.remove("deepseek4.checkpoint_variant");
|
||||
assert!(validate_support(&support, &FLASH_VISION).is_err());
|
||||
let old = crate::model::engine_artifacts(
|
||||
ModelChoice::DeepSeekV4Flash0731,
|
||||
true,
|
||||
&crate::app::models_path(),
|
||||
)
|
||||
.support
|
||||
.unwrap();
|
||||
if old.exists() {
|
||||
assert!(validate_support(&Gguf::open(&old).unwrap(), &FLASH_VISION).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mxfp4_is_limited_to_routed_experts() {
|
||||
let tensor = Tensor {
|
||||
|
||||
@@ -938,6 +938,7 @@ fn model_code(model: ModelChoice) -> u8 {
|
||||
ModelChoice::DeepSeekV4Flash0731 => 4,
|
||||
ModelChoice::Glm53Flash => 5,
|
||||
ModelChoice::Qwen38FlashNext => 6,
|
||||
ModelChoice::DeepSeekV4FlashVision => 7,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -949,6 +950,7 @@ fn model_name(value: u8) -> &'static str {
|
||||
4 => "DeepSeek V4 Flash 0731",
|
||||
5 => "GLM 5.3 Flash Q2",
|
||||
6 => "Qwen 3.8 Flash Next",
|
||||
7 => "DeepSeek V4 Flash Vision Experimental",
|
||||
_ => "No model loaded",
|
||||
}
|
||||
}
|
||||
|
||||
+66
-5
@@ -10,16 +10,20 @@ use std::fmt;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub(crate) const MODEL_CHOICES: [ModelChoice; 5] = [
|
||||
pub(crate) const MODEL_CHOICES: [ModelChoice; 6] = [
|
||||
ModelChoice::DeepSeekV4Flash0731,
|
||||
ModelChoice::DeepSeekV4FlashVision,
|
||||
ModelChoice::DeepSeekV4Pro,
|
||||
ModelChoice::Glm52,
|
||||
ModelChoice::Glm53Flash,
|
||||
ModelChoice::Qwen38FlashNext,
|
||||
];
|
||||
pub(crate) const MANAGED_ARTIFACTS: [ManagedArtifactId; 8] = [
|
||||
pub(crate) const MANAGED_ARTIFACTS: [ManagedArtifactId; 11] = [
|
||||
ManagedArtifactId::DeepSeekV4Flash0731,
|
||||
ManagedArtifactId::DeepSeekV4Flash0731Dspark,
|
||||
ManagedArtifactId::DeepSeekV4FlashVision,
|
||||
ManagedArtifactId::DeepSeekV4FlashVisionEncoder,
|
||||
ManagedArtifactId::DeepSeekV4FlashVisionDspark,
|
||||
ManagedArtifactId::DeepSeekV4Pro,
|
||||
ManagedArtifactId::Glm52,
|
||||
ManagedArtifactId::Glm53Flash,
|
||||
@@ -50,6 +54,33 @@ const FLASH_0731_DSPARK: Artifact = Artifact {
|
||||
support: Some(true),
|
||||
vision: false,
|
||||
};
|
||||
const FLASH_VISION: Artifact = Artifact {
|
||||
label: "DeepSeek V4 Flash Vision Experimental model",
|
||||
file_name: "DeepSeek-V4-Flash-Vision-Exp-IQ2XXS-w2Q2K-AProjQ8-SExpQ8-OutQ8.gguf",
|
||||
repository: DEEPSEEK_REPOSITORY,
|
||||
size: 86_720_111_776,
|
||||
sha256: "8f2d42c0071ccf8a98f391cc2b835fd123f12330690b3059dbb7707920e5ad9e",
|
||||
support: Some(false),
|
||||
vision: false,
|
||||
};
|
||||
const FLASH_VISION_ENCODER: Artifact = Artifact {
|
||||
label: "DeepSeek V4 Flash Vision Experimental encoder",
|
||||
file_name: "DeepSeek-V4-Flash-Vision-Encoder.gguf",
|
||||
repository: DEEPSEEK_REPOSITORY,
|
||||
size: 932_857_760,
|
||||
sha256: "00cd4d81a435364967400a95c42703343e11da6b6f18c5143fe76e1d94d5035f",
|
||||
support: None,
|
||||
vision: true,
|
||||
};
|
||||
const FLASH_VISION_DSPARK: Artifact = Artifact {
|
||||
label: "DeepSeek V4 Flash Vision Experimental DSpark support",
|
||||
file_name: "DeepSeek-V4-Flash-Vision-Exp-DSpark-support.gguf",
|
||||
repository: DEEPSEEK_REPOSITORY,
|
||||
size: 5_989_114_528,
|
||||
sha256: "0807a67fd9ce5874bfc60d8d2461f50e11657e3dd94913d3473f85aa679bc877",
|
||||
support: Some(true),
|
||||
vision: false,
|
||||
};
|
||||
const PRO: Artifact = Artifact {
|
||||
label: "DeepSeek V4 Pro 0813 model",
|
||||
file_name: "DeepSeek-V4-Pro-IQ2XXS-w2Q2K-AProjQ8-SExpQ8-OutQ8-Instruct-imatrix-0813.gguf",
|
||||
@@ -92,6 +123,8 @@ pub(crate) enum ModelChoice {
|
||||
#[default]
|
||||
#[serde(rename = "deepseek-v4-flash-0731")]
|
||||
DeepSeekV4Flash0731,
|
||||
#[serde(rename = "deepseek-v4-flash-vision-exp")]
|
||||
DeepSeekV4FlashVision,
|
||||
#[serde(rename = "deepseek-v4-pro")]
|
||||
DeepSeekV4Pro,
|
||||
#[serde(rename = "glm-5.2")]
|
||||
@@ -106,6 +139,7 @@ impl ModelChoice {
|
||||
pub(crate) fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::DeepSeekV4Flash0731 => "deepseek-v4-flash-0731",
|
||||
Self::DeepSeekV4FlashVision => "deepseek-v4-flash-vision-exp",
|
||||
Self::DeepSeekV4Pro => "deepseek-v4-pro",
|
||||
Self::Glm52 => "glm-5.2",
|
||||
Self::Glm53Flash => "glm-5.3-flash",
|
||||
@@ -118,7 +152,10 @@ impl ModelChoice {
|
||||
}
|
||||
|
||||
pub(crate) fn supports_dspark(self) -> bool {
|
||||
self == Self::DeepSeekV4Flash0731
|
||||
matches!(
|
||||
self,
|
||||
Self::DeepSeekV4Flash0731 | Self::DeepSeekV4FlashVision
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn is_glm(self) -> bool {
|
||||
@@ -130,7 +167,10 @@ impl ModelChoice {
|
||||
}
|
||||
|
||||
pub(crate) fn supports_vision(self) -> bool {
|
||||
matches!(self, Self::Glm53Flash | Self::Qwen38FlashNext)
|
||||
matches!(
|
||||
self,
|
||||
Self::DeepSeekV4FlashVision | Self::Glm53Flash | Self::Qwen38FlashNext
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn supports_integrated_mtp(self) -> bool {
|
||||
@@ -148,6 +188,7 @@ impl ModelChoice {
|
||||
fn main_artifact(self) -> &'static Artifact {
|
||||
match self {
|
||||
Self::DeepSeekV4Flash0731 => &FLASH_0731,
|
||||
Self::DeepSeekV4FlashVision => &FLASH_VISION,
|
||||
Self::DeepSeekV4Pro => &PRO,
|
||||
Self::Glm52 => &GLM,
|
||||
Self::Glm53Flash => &GLM53_FLASH,
|
||||
@@ -158,12 +199,17 @@ impl ModelChoice {
|
||||
fn dspark_artifact(self) -> Option<&'static Artifact> {
|
||||
match self {
|
||||
Self::DeepSeekV4Flash0731 => Some(&FLASH_0731_DSPARK),
|
||||
Self::DeepSeekV4FlashVision => Some(&FLASH_VISION_DSPARK),
|
||||
Self::DeepSeekV4Pro | Self::Glm52 | Self::Glm53Flash | Self::Qwen38FlashNext => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn vision_artifact(self) -> Option<&'static Artifact> {
|
||||
(self == Self::Glm53Flash).then_some(&GLM53_FLASH_VISION)
|
||||
match self {
|
||||
Self::DeepSeekV4FlashVision => Some(&FLASH_VISION_ENCODER),
|
||||
Self::Glm53Flash => Some(&GLM53_FLASH_VISION),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -252,6 +298,9 @@ pub(crate) fn validate_engine_artifacts(
|
||||
path.display()
|
||||
)),
|
||||
}?;
|
||||
if model == ModelChoice::DeepSeekV4FlashVision && artifacts.vision.is_none() {
|
||||
return Err(format!("{model} requires its vision encoder sidecar"));
|
||||
}
|
||||
if let Some(path) = artifacts.vision.as_deref() {
|
||||
model
|
||||
.vision_artifact()
|
||||
@@ -263,6 +312,9 @@ pub(crate) fn validate_engine_artifacts(
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum ManagedArtifactId {
|
||||
DeepSeekV4FlashVision,
|
||||
DeepSeekV4FlashVisionEncoder,
|
||||
DeepSeekV4FlashVisionDspark,
|
||||
DeepSeekV4Flash0731,
|
||||
DeepSeekV4Flash0731Dspark,
|
||||
DeepSeekV4Pro,
|
||||
@@ -283,6 +335,9 @@ impl ManagedArtifactId {
|
||||
Self::DeepSeekV4Flash0731 | Self::DeepSeekV4Flash0731Dspark => {
|
||||
ModelChoice::DeepSeekV4Flash0731
|
||||
}
|
||||
Self::DeepSeekV4FlashVision
|
||||
| Self::DeepSeekV4FlashVisionEncoder
|
||||
| Self::DeepSeekV4FlashVisionDspark => ModelChoice::DeepSeekV4FlashVision,
|
||||
Self::DeepSeekV4Pro => ModelChoice::DeepSeekV4Pro,
|
||||
Self::Glm52 => ModelChoice::Glm52,
|
||||
Self::Glm53Flash | Self::Glm53FlashVision => ModelChoice::Glm53Flash,
|
||||
@@ -293,7 +348,10 @@ impl ManagedArtifactId {
|
||||
fn artifact(self) -> &'static Artifact {
|
||||
match self {
|
||||
Self::DeepSeekV4Flash0731 => &FLASH_0731,
|
||||
Self::DeepSeekV4FlashVision => &FLASH_VISION,
|
||||
Self::DeepSeekV4Flash0731Dspark => &FLASH_0731_DSPARK,
|
||||
Self::DeepSeekV4FlashVisionEncoder => &FLASH_VISION_ENCODER,
|
||||
Self::DeepSeekV4FlashVisionDspark => &FLASH_VISION_DSPARK,
|
||||
Self::DeepSeekV4Pro => &PRO,
|
||||
Self::Glm52 => &GLM,
|
||||
Self::Glm53Flash => &GLM53_FLASH,
|
||||
@@ -397,6 +455,7 @@ impl fmt::Display for ModelChoice {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(match self {
|
||||
Self::DeepSeekV4Flash0731 => "DeepSeek V4 Flash 0731",
|
||||
Self::DeepSeekV4FlashVision => "DeepSeek V4 Flash Vision Experimental",
|
||||
Self::DeepSeekV4Pro => "DeepSeek V4 Pro 0813",
|
||||
Self::Glm52 => "GLM 5.2",
|
||||
Self::Glm53Flash => "GLM 5.3 Flash Q2",
|
||||
@@ -537,6 +596,8 @@ pub(crate) fn installed_models(models_path: &Path) -> Vec<ModelChoice> {
|
||||
qwen::is_installed(&qwen::root(models_path))
|
||||
} else {
|
||||
model.main_artifact().is_installed(*model, models_path)
|
||||
&& (*model != ModelChoice::DeepSeekV4FlashVision
|
||||
|| FLASH_VISION_ENCODER.is_installed(*model, models_path))
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
|
||||
+95
-2
@@ -492,8 +492,8 @@ mod tests {
|
||||
Some(ModelChoice::DeepSeekV4Flash0731)
|
||||
);
|
||||
assert!(ModelChoice::from_id("unknown").is_none());
|
||||
assert_eq!(MODEL_CHOICES.len(), 5);
|
||||
assert_eq!(MANAGED_ARTIFACTS.len(), 8);
|
||||
assert_eq!(MODEL_CHOICES.len(), 6);
|
||||
assert_eq!(MANAGED_ARTIFACTS.len(), 11);
|
||||
assert_eq!(
|
||||
ModelChoice::from_id("qwen3.8-flash-next"),
|
||||
Some(ModelChoice::Qwen38FlashNext)
|
||||
@@ -642,6 +642,99 @@ mod tests {
|
||||
fs::remove_dir_all(models).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn issue100_catalog_keeps_vision_and_dspark_checkpoint_specific() {
|
||||
let model = ModelChoice::DeepSeekV4FlashVision;
|
||||
assert_eq!(ModelChoice::from_id(model.id()), Some(model));
|
||||
assert_eq!(
|
||||
serde_json::from_str::<ModelChoice>(&serde_json::to_string(&model).unwrap()).unwrap(),
|
||||
model
|
||||
);
|
||||
assert!(model.supports_vision() && model.supports_dspark());
|
||||
assert!(!model.supports_integrated_mtp());
|
||||
assert_eq!(model.artifacts(true).count(), 3);
|
||||
assert_eq!(model.artifacts(false).count(), 2);
|
||||
assert_ne!(
|
||||
model.dspark_artifact().unwrap().sha256,
|
||||
FLASH_0731_DSPARK.sha256
|
||||
);
|
||||
let defaults = crate::config::ModelPreferences::defaults_for(model);
|
||||
assert!(defaults.speculative.dspark_enabled);
|
||||
assert!(defaults.speculative.validate(model).is_ok());
|
||||
let root = std::env::temp_dir().join(format!("issue100-catalog-{}", std::process::id()));
|
||||
fs::create_dir_all(root.join(model.id())).unwrap();
|
||||
// Sparse files exercise catalog and marker bookkeeping only. Real GGUF
|
||||
// content and hashes are checked by the separate managed-intake test.
|
||||
for artifact in [&FLASH_VISION, &FLASH_VISION_DSPARK] {
|
||||
File::create(artifact.path(model, &root))
|
||||
.unwrap()
|
||||
.set_len(artifact.size)
|
||||
.unwrap();
|
||||
mark_verified(model, artifact, &root).unwrap();
|
||||
}
|
||||
assert!(!installed_models(&root).contains(&model));
|
||||
let missing = engine_artifacts(model, true, &root);
|
||||
assert!(
|
||||
validate_engine_artifacts(model, true, &missing)
|
||||
.unwrap_err()
|
||||
.contains("requires its vision encoder")
|
||||
);
|
||||
File::create(FLASH_VISION_ENCODER.path(model, &root))
|
||||
.unwrap()
|
||||
.set_len(FLASH_VISION_ENCODER.size)
|
||||
.unwrap();
|
||||
mark_verified(model, &FLASH_VISION_ENCODER, &root).unwrap();
|
||||
assert_eq!(installed_models(&root), [model]);
|
||||
let mut artifacts = engine_artifacts(model, true, &root);
|
||||
validate_engine_artifacts(model, true, &artifacts).unwrap();
|
||||
artifacts.support = Some(FLASH_0731_DSPARK.path(ModelChoice::DeepSeekV4Flash0731, &root));
|
||||
assert!(
|
||||
validate_engine_artifacts(model, true, &artifacts)
|
||||
.unwrap_err()
|
||||
.contains("not the expected")
|
||||
);
|
||||
artifacts = engine_artifacts(model, false, &root);
|
||||
artifacts.vision = Some(GLM53_FLASH_VISION.path(ModelChoice::Glm53Flash, &root));
|
||||
assert!(
|
||||
validate_engine_artifacts(model, false, &artifacts)
|
||||
.unwrap_err()
|
||||
.contains("not the expected")
|
||||
);
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires all three pinned Vision-Exp GGUF artifacts; performs full SHA256 and intake validation"]
|
||||
fn issue100_managed_intake() {
|
||||
let source = Path::new("local-eval-results/issue100-artifacts");
|
||||
let root = Path::new("local-eval-results/issue100-managed");
|
||||
let model = ModelChoice::DeepSeekV4FlashVision;
|
||||
fs::create_dir_all(root.join(model.id())).unwrap();
|
||||
for id in [
|
||||
ManagedArtifactId::DeepSeekV4FlashVisionEncoder,
|
||||
ManagedArtifactId::DeepSeekV4FlashVisionDspark,
|
||||
ManagedArtifactId::DeepSeekV4FlashVision,
|
||||
] {
|
||||
let artifact = id.artifact();
|
||||
let destination = artifact.path(model, root);
|
||||
if !destination.exists() {
|
||||
fs::hard_link(source.join(artifact.file_name), &destination).unwrap();
|
||||
}
|
||||
let verified = AtomicU64::new(0);
|
||||
assert_eq!(
|
||||
validate_managed_artifact(id, root, &AtomicBool::new(false), &verified).unwrap(),
|
||||
DownloadOutcome::Complete
|
||||
);
|
||||
assert_eq!(verified.load(Ordering::Relaxed), artifact.size);
|
||||
eprintln!("verified {} {} bytes", artifact.file_name, artifact.size);
|
||||
}
|
||||
assert_eq!(installed_models(root), [model]);
|
||||
for dspark in [false, true] {
|
||||
validate_engine_artifacts(model, dspark, &engine_artifacts(model, dspark, root))
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verification_reports_bytes_read() {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
|
||||
+1
-1
@@ -249,7 +249,7 @@ fn print_usage() {
|
||||
println!(
|
||||
"Headless model evaluation\n\n\
|
||||
Usage: ds4-server model-eval --model MODEL [OPTIONS]\n\n\
|
||||
Models: deepseek-v4-flash-0731, deepseek-v4-pro, glm-5.2, glm-5.3-flash, qwen3.8-flash-next\n\n\
|
||||
Models: deepseek-v4-flash-0731, deepseek-v4-flash-vision-exp, deepseek-v4-pro, glm-5.2, glm-5.3-flash, qwen3.8-flash-next\n\n\
|
||||
Options:\n\
|
||||
--prompt TEXT Chat turn; repeat for one ongoing conversation\n\
|
||||
(default: autonomous short story)\n\
|
||||
|
||||
+7
-3
@@ -52,7 +52,7 @@ impl SpeculativePreferences {
|
||||
return Err("Integrated MTP is unavailable for the selected model.".into());
|
||||
}
|
||||
if self.keep_vision_loaded && !model.supports_vision() {
|
||||
return Err("Persistent vision weights are available only for GLM 5.3 Flash and Qwen 3.8 Flash Next.".into());
|
||||
return Err("Persistent vision weights require a supported vision model.".into());
|
||||
}
|
||||
if self.dspark_enabled && !model.supports_dspark() {
|
||||
return Err("DSpark is not available for the selected model.".into());
|
||||
@@ -543,7 +543,9 @@ impl ReasoningMode {
|
||||
impl ModelChoice {
|
||||
pub(crate) fn reasoning_modes(self) -> &'static [ReasoningMode] {
|
||||
match self {
|
||||
Self::DeepSeekV4Flash0731 | Self::DeepSeekV4Pro => &DEEPSEEK_REASONING_MODES,
|
||||
Self::DeepSeekV4Flash0731 | Self::DeepSeekV4FlashVision | Self::DeepSeekV4Pro => {
|
||||
&DEEPSEEK_REASONING_MODES
|
||||
}
|
||||
Self::Glm52 => &GLM_52_REASONING_MODES,
|
||||
Self::Glm53Flash => &GLM_53_REASONING_MODES,
|
||||
Self::Qwen38FlashNext => &QWEN_REASONING_MODES,
|
||||
@@ -552,7 +554,9 @@ impl ModelChoice {
|
||||
|
||||
pub(crate) fn default_reasoning_mode(self) -> ReasoningMode {
|
||||
match self {
|
||||
Self::DeepSeekV4Flash0731 | Self::DeepSeekV4Pro => ReasoningMode::Low,
|
||||
Self::DeepSeekV4Flash0731 | Self::DeepSeekV4FlashVision | Self::DeepSeekV4Pro => {
|
||||
ReasoningMode::Low
|
||||
}
|
||||
Self::Glm52 | Self::Glm53Flash => ReasoningMode::Max,
|
||||
Self::Qwen38FlashNext => ReasoningMode::Low,
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user