mirror of
https://github.com/FlashML-org/FreeToken.git
synced 2026-11-25 04:26:07 +08:00
* test(deepseek-v41): add independent text and vision reference * feat(quant): support block-32 and unrounded inference outputs * feat(attention): add csa2 packed cache and sparse backend * feat(deepseek-v41): serve text and images through shared runtime * perf(mhc): tune batch-stable reduction tiles * perf(moe): autotune fp4 decode launch geometry * perf(moe): admit recurring misses against actual lru victims * revert: perf(moe): admit recurring misses against actual lru victims This reverts commit 1652d200f0ebb825379cf44c28baf52971e3a461. * perf(mhc): derive the reduction tile from the width, not a timing * perf(moe): replace the ds_fp4 decode autotune with a fixed two-warp launch * fix(deepseek-v41): fence engram staging against in-flight lookups * fix(moe): return the cpu routed sum in fp32 and round it in python * fix(deepseek-v41): keep the vision tower and aligner unquantized * fix(scheduler): admit bounded-replay hits by the history their resume reads * refactor(deepseek-v41): name the attention family after the model, not csa2 * refactor(kvcache): import the dsv41 pool only for dsv41 models * refactor(deepseek-v41): name the replay switch --swa-decoder-replay * fix(server): keep reasoning_effort a string on the wire * refactor(models): keep the prefill replay hooks off BaseLLMModel * refactor(deepseek-v41): drop the fp32 routed sum and batch-invariant prefill * fix(moe): weight ds_fp4 routes in the down epilogue again * docs(models): anchor the v4.1 replay paragraph on the tech report * refactor(deepseek-v41): run the decoder source's narrowed prefill on Block * refactor(kvcache): let the dsv41 pool own the history a resume keeps live * refactor(deepseek-v41): resume bounded-replay hits by capping the prefix match * refactor(deepseek-v41): describe the attention group as a dsv4 variant and derive its geometry from the args * refactor(deepseek-v41): keep the engram table locator in the model package * refactor(deepseek-v41): drop the fp32 lm head output - return the head's bf16 logits, as DeepSeek-V4 does - revert ParallelLMHead(out_dtype=) and LinearKernel.apply_out_dtype, which only this call used - remove test_head_preserves_fp32_logit_margin - cast test_vision's prefill logits to fp32 before comparing, as the harness does * refactor(quant): carry the w4a8 activation block on MoEConfig - drop ActDesc and QuantScheme.act; the scheme only describes stored tensors - Fp8BlockConfig sets MoEConfig.act_block from weight_block_size for its fp4 experts via a layer_config hook - the ds_fp4 GPU kernel and CPU executor read the block from the layer config and require it * refactor(deepseek-v41): size the kv pool from the args, not a geometry copy - delete kvcache/dsv41_geometry.py; the pool and cost model read dsv41_args by attribute, as the DSV4 pool reads dsv4_args - source / ratio aliasing reads args.roles; the duplicated source and ratio validation is gone - the cost model owns the tier row formats, row bytes and the private window layers - the pool keeps the format and window/ratio checks, and exposes the formats and is_private_window to the attention backend * refactor(kvcache): move the dsv4 pool into kvcache/dsv4 * refactor(kvcache): move the dsv41 pool into kvcache/dsv4 * chore(benchmarks): drop the dsv41 selection and fp8 linear benchmarks * test(deepseek-v41): drop tests that repeat other coverage * test(deepseek-v41): load the tiny model's resident experts as banks * fix(server): parse deepseek-v4.1's space-led dsml tool calls --------- Co-authored-by: andy-yang-1 <andy_yang@berkeley.edu>
89 lines
4.4 KiB
Python
89 lines
4.4 KiB
Python
"""DeepSeek-V4.1 image resize/patch layout and learned image-span delimiters."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import math
|
|
import struct
|
|
|
|
import numpy as np
|
|
import torch
|
|
from PIL import ImageOps
|
|
|
|
from freetoken.message import MMItem
|
|
from freetoken.mm import mm_pad_value
|
|
from freetoken.mm.processor import MMProcessor, PromptReplacement, content_hash
|
|
|
|
|
|
def image_grid(width, height, patch, ratio, min_pixels, max_tokens, max_wh_ratio=None):
|
|
if max_wh_ratio is not None:
|
|
width = min(width, height * max_wh_ratio)
|
|
if width * height < min_pixels:
|
|
scale = (min_pixels / (width * height)) ** 0.5
|
|
width, height = int(width * scale), int(height * scale)
|
|
w, h = math.ceil(width / patch) * patch, math.ceil(height / patch) * patch
|
|
if math.ceil(h / (patch * ratio)) * (math.ceil(w / (patch * ratio)) + 1) + 2 > max_tokens:
|
|
aspect, cell = height / width, patch * ratio
|
|
wf = math.sqrt((max_tokens - 2) / aspect + 0.25) - 0.5
|
|
hf = wf * aspect
|
|
if wf < 1:
|
|
h, w = (max_tokens - 2) // 2 * cell, cell
|
|
elif hf < 1:
|
|
h, w = cell, (max_tokens - 3) * cell
|
|
else:
|
|
scale = min(math.floor(wf) * cell / width, math.floor(hf) * cell / height)
|
|
h, w = math.floor(height * scale / patch) * patch, math.floor(width * scale / patch) * patch
|
|
return h, w
|
|
|
|
|
|
class DeepseekV41MMProcessor(MMProcessor):
|
|
def __init__(self, hf_config, model_path, mm):
|
|
super().__init__(model_path, mm)
|
|
self.vc = hf_config.vision_config
|
|
self.placeholder = [hf_config.image_token_id]
|
|
self.min_pixels = self.vc.min_pixels
|
|
self.max_tokens = mm.image_max_tokens if mm.image_max_tokens is not None else self.vc.max_image_tokens
|
|
if mm.image_min_tokens is not None:
|
|
# Delimiters and row breaks count against the total span budget.
|
|
self.min_pixels = max(1, mm.image_min_tokens - 2) * (self.vc.patch_size * self.vc.downsample_ratio)**2
|
|
allowed = {"min_pixels", "max_image_tokens", "max_wh_ratio"}
|
|
unknown = set(mm.processor_kwargs) - allowed
|
|
if unknown:
|
|
raise ValueError(f"unsupported DeepSeek image processor options: {sorted(unknown)}")
|
|
self.min_pixels = mm.processor_kwargs.get("min_pixels", self.min_pixels)
|
|
self.max_tokens = mm.processor_kwargs.get("max_image_tokens", self.max_tokens)
|
|
self.max_wh_ratio = mm.processor_kwargs.get("max_wh_ratio", self.vc.max_wh_ratio)
|
|
if self.max_tokens < 4 or self.min_pixels < 0:
|
|
raise ValueError("image token budget must be >= 4 and min_pixels must be nonnegative")
|
|
if self.max_wh_ratio is not None and self.max_wh_ratio <= 0:
|
|
raise ValueError("max_wh_ratio must be positive")
|
|
|
|
def process(self, images):
|
|
p, r = self.vc.patch_size, self.vc.downsample_ratio
|
|
items = []
|
|
for image in images:
|
|
h, w = image_grid(image.width, image.height, p, r, self.min_pixels, self.max_tokens, self.max_wh_ratio)
|
|
if self.max_wh_ratio is not None and image.width >= self.max_wh_ratio * image.height:
|
|
image = image.resize((w, h))
|
|
else:
|
|
image = ImageOps.pad(image, (w, h), color=(127, 127, 127))
|
|
x = torch.from_numpy(np.asarray(image, dtype=np.float32)).permute(2, 0, 1) / 255
|
|
x = ((x - 0.5) / 0.5).to(torch.bfloat16)
|
|
nh, nw = h // p, w // p
|
|
patches = x.reshape(3, nh, p, nw, p).permute(1, 3, 0, 2, 4).reshape(nh * nw, 3, p, p).contiguous()
|
|
item_hash = content_hash(patches, struct.pack("<3i", 1, nh, nw))
|
|
items.append(MMItem(modality="image", hash=item_hash, pad_value=mm_pad_value(item_hash), offsets=[], feature=patches,
|
|
model_specific_data={"grid_thw": [1, nh, nw]}))
|
|
return items
|
|
|
|
def prompt_replacement(self, item):
|
|
_, h, w = item.grid_thw
|
|
r = self.vc.downsample_ratio
|
|
n = ((h + r - 1) // r) * ((w + r - 1) // r + 1) + 2
|
|
# Every span row, including delimiters/newlines, has a learned visual embedding.
|
|
return PromptReplacement([self.placeholder[0]] * n)
|
|
|
|
def dummy_items(self, dtype, device):
|
|
p = self.vc.patch_size
|
|
return [MMItem(modality="image", hash=0, pad_value=0, offsets=[[0, 4]],
|
|
feature=torch.zeros(1, 3, p, p, dtype=dtype, device=device), model_specific_data={"grid_thw": [1, 1, 1]})]
|