diff --git a/docs/models.md b/docs/models.md index 9c6ffd0229..24b00eab55 100644 --- a/docs/models.md +++ b/docs/models.md @@ -21,6 +21,7 @@ for them; other checkpoints of the same architectures work too. | MiniMax-M3 | [nvidia/MiniMax-M3-NVFP4](https://huggingface.co/nvidia/MiniMax-M3-NVFP4) | | Muse-Glimmer | [meta-models/Muse-Glimmer-30B](https://huggingface.co/meta-models/Muse-Glimmer-30B), [RedHatAI/Muse-Glimmer-30B-NVFP4](https://huggingface.co/RedHatAI/Muse-Glimmer-30B-NVFP4) | | Flint | [FutureMLS-Lab/flint-nvfp4-coldgptq](https://huggingface.co/FutureMLS-Lab/flint-nvfp4-coldgptq), [RecursiveSI/flint-nvfp4-gguf](https://huggingface.co/RecursiveSI/flint-nvfp4-gguf) | +| Inkling 2 Mini | [thinkingmachines/Inkling-2-Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini) | | Ripple-65B Preview | [ricursiveAI/Ripple-65B-Preview](https://huggingface.co/ricursiveAI/Ripple-65B-Preview), [ricursiveAI/Ripple-65B-Preview-NVFP4](https://huggingface.co/ricursiveAI/Ripple-65B-Preview-NVFP4), [AtomicChat/Ripple-65B-Preview-GGUF](https://huggingface.co/AtomicChat/Ripple-65B-Preview-GGUF) | ### GGUF @@ -60,6 +61,7 @@ These families accept image input by default; pass `--text-model-only` to skip t | GLM-5.3-Flash (`glm5_next`: ViT tower, streamed under `--mm-encoder-weights host`) | one token per 28x28 pixels of the resized image, dynamic resolution on a canvas zero-padded to a 28-multiple | token counts, passed through as the processor's `min_image_tokens` / `max_image_tokens`; checkpoint defaults 16 to 8000 tokens | `{"max_image_tokens": 2048}` | | Muse-Glimmer-30B (windowed ViT tower, streamed under `--mm-encoder-weights host`) | one token per 28x28 pixels of the resized image, aspect ratio kept under a token cap; checkpoint default 4096 tokens | the maximum is the cap (`max_image_tokens`); the minimum has no effect | `{"max_image_tokens": 1024}` | | MiniMax-M3 (`minimax_m3`: CLIP-style ViT tower, streamed under `--mm-encoder-weights host`) | one token per 28x28 pixels of the resized image, dynamic resolution | pixel areas in `size.shortest_edge` / `longest_edge`; checkpoint defaults 4 to 576 tokens | `{"size": {"longest_edge": 1048576}}` | +| Inkling 2 Mini (`inkling2_loop`: ViT tower, streamed under `--mm-encoder-weights host`) | one token per 40x40-pixel tile of the image at its own resolution, padded to whole tiles | the maximum refuses a larger image instead of resizing it (default 16384 tokens); the minimum has no effect | not read | | DeepSeek-V4-Flash-Vision (`deepseek_v4`: native-resolution ViT tower, streamed under `--mm-encoder-weights host`) | one token per 3x3 grid of 14x14 patches, against a per-image cap; the block carries sentinel tokens and lead pads that align it to a 4-token compression stride, so its length depends on where it lands in the prompt | the maximum is a cap on the block (`vision_max_n_token`, checkpoint default 384) and lowers it, the minimum is read as the checkpoint's upscale floor and has no effect | not read | A GGUF model takes image input from a separate llama.cpp mmproj file, found in the model file's own folder or passed with `--mmproj` (see the @@ -196,5 +198,16 @@ unset on PCIe GPUs: wider grids add no bandwidth there. template kwargs with thinking on, `"chat_template_kwargs": {"enable_thinking": true, "reasoning_effort": 37}`, and the checkpoint's encoder validates it. Runtime window-cache controls use 128-token pages. +- Inkling 2 Mini runs its layers 6-17 three times per token; every run keeps its own KV and + short-convolution state, so the KV pool holds 48 layers (40 sliding, 8 global). Its prefix cache is + off: a cached prefix would need the convolution windows at the cut, which nothing snapshots yet, so + `--cache-type radix` serves as `naive`. The naive cache reserves each running request the window KV of + one window plus one prefill chunk on all 40 sliding layers (about 1.4 GiB at the default + `--max-extend-length 8192`); lower `--max-extend-length` to run many requests at once. The NVFP4 + experts (layers 0-19) run W4A16, since the checkpoint declares only per-token activation scales; the + MXFP8 experts (layers 20-23) run W8A16 from their stored blocks. Speculative decoding uses the + checkpoint's DSpark draft (`mtp.safetensors`). On a 16 GB card start with `--memory-ratio 0.85`: the + prefill activations are not in the memory budget, and at the default 0.9 a 4K-token prompt runs out of + memory in the expert GEMM. - Qwen3.8-Flash-Next keeps a 47.7 GiB PLE n-gram table pinned in host RAM. - Gemma-4 serves MTP speculative decoding from an assistant sidecar: unsloth's GGUF repos ship `mtp-*.gguf` files for it; upstream's `google/gemma-4-*-it-assistant` HF release must first go through llama.cpp's `convert_hf_to_gguf.py`, then pass the resulting GGUF with `--spec-draft-model`, see [CLI reference](cli.md#speculative-decoding). diff --git a/python/freetoken/engine/engine.py b/python/freetoken/engine/engine.py index ae8eb48be4..c96a5d15fb 100644 --- a/python/freetoken/engine/engine.py +++ b/python/freetoken/engine/engine.py @@ -28,7 +28,7 @@ from freetoken.moe.host_banks import PinFailed from freetoken.moe.locked_fetch import attach_locked_fetch, check_locked_fetch_config, locked_pool_tags, settle_banks, staging_reserve from freetoken.moe.offload_cache import OffloadMoeCache, attach_offload_moe_cache, bank_layouts -from freetoken.moe.pool_policy import group_layers, make_pools, pool_of_layer, resolve_profile, split_slots +from freetoken.moe.pool_policy import group_layers, make_pools, pool_of_layer, pool_row_bytes, resolve_profile, split_slots, staging_slots from freetoken.utils import align_ceil, init_logger, is_sm90_family, is_sm100_family, mem_GB, torch_dtype from .config import EngineConfig @@ -243,6 +243,12 @@ def _adjust_spec_config(config, override, windowed_kv: bool) -> None: def _validate_kv_format(config, model_config) -> None: kv_format = getattr(config, "kv_format", NONE) + own = getattr(model_config, "kv_formats", None) + if own is not None and kv_format.name not in own: + raise ValueError( + f"--kv-cache-dtype {kv_format.name}: {getattr(model_config, 'model_type', 'this model')} attends with its own " + f"kernel, which reads only {sorted(own)} KV" + ) if not kv_format.quantized: return pool_cls = resolve_pool_class(model_config) @@ -624,7 +630,7 @@ def __init__(self, config: EngineConfig): # ======================= Linear (GatedDeltaNet) state initialization ======================== linear_group = config.model_config.linear_attention_group() - if linear_group is not None: + if linear_group is not None or config.model_config.slot_states: from freetoken.kvcache.linear_state_pool import LinearStatePool self.linear_state_pool = LinearStatePool( @@ -849,10 +855,10 @@ def _init_offload_moe_cache(self, config: EngineConfig) -> OffloadMoeCache: layer_methods = offload_layer_methods(self.model) if not is_mixed(layer_methods): layer_methods = None - elif config.moe_strategy == "cpu" or config.moe_cpu_layers: + elif config.moe_cpu_layers: raise ValueError( "this model's experts come in several formats, which are served from per-format GPU slot pools; " - "they do not combine with --moe-strategy cpu or --moe-cpu-layers (use offload or hybrid)" + "they do not combine with --moe-cpu-layers (use offload, hybrid or cpu)" ) # Fast path: an FTW checkpoint loads its repacked banks directly. # Slow path: load_expert_banks auto-picks parallel vs serial baseline by @@ -916,7 +922,8 @@ def _init_offload_moe_cache(self, config: EngineConfig) -> OffloadMoeCache: if locked_fetch: # a locked refill costs a staged copy: place the locked pools after the pinned ones, which hold the prefill staging when they are big enough self._moe_pool_groups.sort(key=lambda layers: layers[0] in cpu_layer_ids) - if len(self._moe_pool_groups) > 1 and cpu_layer_ids and not locked_fetch: + # --moe-strategy cpu decodes no layer from the slots, which only back the prefill staging (sized below) + if len(self._moe_pool_groups) > 1 and cpu_layer_ids and not locked_fetch and config.moe_strategy != "cpu": raise ValueError( "several MoE slot pools (--moe-cache-scope per-layer, or experts in several quant formats) need every MoE " "layer to decode from the GPU slot cache; they combine with --moe-cpu-layers only for locked layers under " @@ -962,8 +969,17 @@ def _init_offload_moe_cache(self, config: EngineConfig) -> OffloadMoeCache: f"--moe-cache-mem {mem_GB(config.moe_cache_mem)} resolved moe_cache_size={size} " f"({per_slot / 2**20:.2f} MiB per slot, prefill_overlap={overlap})" ) - _require_offload_cache_size(config.moe_cache_size, config.model_config.num_experts) - pool_sizes = split_slots(config.moe_cache_size, pools, self._moe_expert_counts) + if config.moe_strategy == "cpu" and len(pools) > 1: + # the fixed two-layer buffer is sized for one format; give each bank two layers of its widest one instead + pool_sizes = staging_slots(*pool_row_bytes(banks.sources, banks.row_tail_bytes, pools), config.model_config.num_experts) + object.__setattr__(config, "moe_cache_size", sum(pool_sizes)) + logger.info_rank0( + f"MoE backend 'cpu': {len(pools)} expert formats; prefill staging pools of {pool_sizes} slots " + f"(moe_cache_size={config.moe_cache_size})" + ) + else: + _require_offload_cache_size(config.moe_cache_size, config.model_config.num_experts) + pool_sizes = split_slots(config.moe_cache_size, pools, self._moe_expert_counts) if len(pools) > 1: logger.info_rank0( f"MoE slot pools: {config.moe_cache_scope}, {len(pools)} pools of {min(pool_sizes)}-{max(pool_sizes)} " @@ -1009,6 +1025,8 @@ def _init_offload_moe_cache(self, config: EngineConfig) -> OffloadMoeCache: pool_of_layer=pool_of_layer(pools, config.model_config.num_moe_layers), pool_sizes=pool_sizes, ) + # a looped model runs some MoE layers more than once per forward; the overlap prefill follows its order + cache.set_layer_order(getattr(self.model, "moe_layer_order", None)) # before set_bank_sources: the residency validation and the copy plan's skip of non-pinned layers key on the CPU-layer set cache.cpu_layer_ids = cpu_layer_ids if locked_fetch: @@ -1428,7 +1446,7 @@ def _prepare_verify_batch(self, batch: Batch) -> None: def commit_verify(self, reqs, counts, out: torch.Tensor) -> None: """Commit each verified request's first ``counts`` tokens (row i of ``out`` is reqs[i]) to the target's per-request state.""" - if self.linear_state_pool is not None and self.linear_state_pool.verify_scratch is not None: + if self.linear_state_pool is not None and self.linear_state_pool.verifies: self.linear_state_pool.commit_verify([gdn_slot(r) for r in reqs], counts) for req, n, tokens in zip(reqs, counts, out): if req.output_token_counts is not None: @@ -1759,7 +1777,7 @@ def _decode_target(config: EngineConfig) -> str: # expert activations the CPU MoE executor supports (csrc ActKind) _CPU_MOE_ACTS = ( "silu", "swish", "gelu", "gelu_tanh", "gelu_pytorch_tanh", "swigluoai", - "swiglu_clamp", + "swiglu_clamp", "swiglu_softcap", ) @@ -2056,6 +2074,10 @@ def override(attr: str, value: Any): # this is dangerous, use with caution _resolve_cache_type(True, getattr(config, "cache_type", "radix")), ) + if (reason := getattr(model_config, "no_prefix_reuse", None)) is not None and getattr(config, "cache_type", "radix") != "naive": + logger.warning_rank0(f"prefix cache off for {getattr(model_config, 'model_type', 'this model')}: {reason}") + override("cache_type", "naive") + # Type x backend capability matrix: resolve auto from the per-type priority # lists, then validate whatever is now selected (explicit or auto) -- every # comma part must serve every required type, with packages/arch available. diff --git a/python/freetoken/kernel/aot_models.py b/python/freetoken/kernel/aot_models.py index 67e0279da4..7897ea421c 100644 --- a/python/freetoken/kernel/aot_models.py +++ b/python/freetoken/kernel/aot_models.py @@ -115,6 +115,14 @@ def expert_bank_row_bytes(fmt: str, hidden_size: int, moe_intermediate_size: int "down_scales": (I // 32) * H, "down_bias": H * 2, } + if fmt == "mxfp8": + # layers/quantization/moe/mxfp8.py: e4m3 weights + one e8m0 code per 32 inputs of a row + return { + "gate_up": 2 * I * H, + "gate_up_scale": 2 * I * (H // 32), + "down": H * I, + "down_scale": H * (I // 32), + } if fmt == "ds_fp4": # deepseek_v4/weight.py load_dsfp4_expert_sources: packed e2m1 + e8m0 per-32 scales return { @@ -392,6 +400,16 @@ def expert_bank_row_bytes(fmt: str, hidden_size: int, moe_intermediate_size: int aliases=("RedHatAI/Muse-Glimmer-30B-NVFP4",), arch_aliases=("MuseGlimmerGGUFForCausalLM",), ), + AotModel( + name="thinkingmachines/Inkling-2-Mini", + architecture="Inkling2LoopForConditionalGeneration", + hidden_size=2304, + kv_groups=((8, 128),), # sliding and global layers share the same geometry + top_k=8, + moe_intermediate_size=1152, + # NVFP4 experts on layers 0-19, MXFP8 on layers 20-23 + expert_formats=_NVFP4_FORMATS + ("mxfp8",), + ), AotModel( name="ricursiveAI/Ripple-65B-Preview", architecture="RicursiveForCausalLM", diff --git a/python/freetoken/kernel/csrc/cpu_moe/common.h b/python/freetoken/kernel/csrc/cpu_moe/common.h index 0edee0150a..9d7685113a 100644 --- a/python/freetoken/kernel/csrc/cpu_moe/common.h +++ b/python/freetoken/kernel/csrc/cpu_moe/common.h @@ -66,12 +66,15 @@ inline bf16_t f32_to_bf16(float f) { // the mxfp4 kernel additionally fuses its own copy of the same math). // ACT_SWIGLU_CLAMP (GLM-5.3 "swiglu_limit") is the same clamped form WITHOUT // the (up + 1) bias: clamp(gate, max=lim) * sigmoid(alpha*gate) * clamp(up, +-lim). +// ACT_SWIGLU_SOFTCAP (Inkling 2) caps with tanh instead and the sigmoid sees the raw gate: +// alpha*tanh(gate/alpha) * sigmoid(gate) * lim*tanh(up/lim). enum ActKind { ACT_SILU = 0, ACT_GELU = 1, ACT_GELU_TANH = 2, ACT_SWIGLUOAI = 3, ACT_SWIGLU_CLAMP = 4, + ACT_SWIGLU_SOFTCAP = 5, }; inline float act_apply(int act, float x) { diff --git a/python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp b/python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp index 31d5224923..1d25cc7d5b 100644 --- a/python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp +++ b/python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp @@ -645,7 +645,7 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { // accepts id 3 without error and silently computes the wrong activation // (act_apply falls through to gelu_tanh); the probe turns a stale extension // into a loud rebuild instruction instead of wrong model outputs. - m.def("max_generic_act_id", []() { return static_cast(freetoken::cpu_moe::ACT_SWIGLU_CLAMP); }); + m.def("max_generic_act_id", []() { return static_cast(freetoken::cpu_moe::ACT_SWIGLU_SOFTCAP); }); // The ggml-cpu variant the gguf format calls: the kernel table address that freetoken.kernel.ggml_cpu.select() returns. m.def("set_ggml_cpu", &freetoken::cpu_moe::set_ggml_cpu, py::arg("api")); m.def("weight_formats", []() { diff --git a/python/freetoken/kernel/csrc/cpu_moe/format.h b/python/freetoken/kernel/csrc/cpu_moe/format.h index 1c4ffa41a0..2c5be7e2db 100644 --- a/python/freetoken/kernel/csrc/cpu_moe/format.h +++ b/python/freetoken/kernel/csrc/cpu_moe/format.h @@ -76,7 +76,7 @@ struct DownRoute { }; // g[i] for i in [i0, i1) from the gate row i and the up row I + i; dot(row) is the row's GEMV. -// ACT_SWIGLUOAI and ACT_SWIGLU_CLAMP clamp both inputs; the other kinds go through act_apply. +// ACT_SWIGLUOAI and ACT_SWIGLU_CLAMP clamp both inputs, ACT_SWIGLU_SOFTCAP tanh-caps them; the other kinds go through act_apply. template inline void gated_rows(const MoeParams& p, int i0, int i1, float w_in, bf16_t* g, RowDot dot) { const bool clamped = p.act == ACT_SWIGLUOAI || p.act == ACT_SWIGLU_CLAMP; @@ -86,7 +86,11 @@ inline void gated_rows(const MoeParams& p, int i0, int i1, float w_in, bf16_t* g // gate = row i, up = row I+i float gate = dot(i) * w_in; float up = dot(p.I + i) * w_in; - if (clamped) { + if (p.act == ACT_SWIGLU_SOFTCAP) { + // lim == +inf leaves up uncapped (lim * tanh(up / lim) would be inf * 0) + const float capped_up = std::isinf(lim) ? up : lim * std::tanh(up / lim); + g[i] = f32_to_bf16(alpha * std::tanh(gate / alpha) / (1.0f + std::exp(-gate)) * capped_up); + } else if (clamped) { // clamp(gate, max=lim) * sigmoid(alpha * gate) * (clamp(up, +-lim) + up_bias) // -- swigluoai carries the +1 up bias (gpt-oss/MiniMax); swiglu_clamp // (GLM-5.3) does not. lim == +inf: no clamp. diff --git a/python/freetoken/kernel/triton/activation.py b/python/freetoken/kernel/triton/activation.py index 9645960d11..d3781e9e4f 100644 --- a/python/freetoken/kernel/triton/activation.py +++ b/python/freetoken/kernel/triton/activation.py @@ -34,6 +34,9 @@ SWIGLUOAI = 3 # GLM-5.3 "swiglu_limit": swigluoai's clamped form WITHOUT the (up + 1) bias. SWIGLU_CLAMP = 4 +# Inkling 2: softcap(gate, alpha) * sigmoid(gate) * softcap(up, limit), softcap(x, c) = c * tanh(x / c); +# the sigmoid sees the raw gate. +SWIGLU_SOFTCAP = 5 _SQRT_2_OVER_PI = 0.7978845608028654 # sqrt(2/pi) _GELU_C = 0.044715 @@ -117,6 +120,9 @@ def _act_and_mul_kernel( up = tl.minimum(tl.maximum(up, -limit), limit) act = gate / (1.0 + _fast_ex2(-gate * alpha * _LOG2E)) y = act * up + elif ACT == 5: # SWIGLU_SOFTCAP (Inkling 2): libdevice tanh/exp, the caps saturate where tanh.approx loses digits + act = alpha * libdevice.tanh(gate / alpha) / (1.0 + libdevice.exp(-gate)) + y = act * (limit * libdevice.tanh(up / limit)) else: # GELU (erf) act = 0.5 * gate * (1.0 + libdevice.erf(gate * 0.7071067811865476)) y = act * up @@ -190,10 +196,22 @@ def swiglu_clamp_and_mul( return _act_and_mul(SWIGLU_CLAMP, x, out, alpha=alpha, limit=limit) +def swiglu_softcap_and_mul( + x: torch.Tensor, + out: torch.Tensor | None = None, + *, + alpha: float = 4.0, + limit: float = 25.0, +) -> torch.Tensor: + """Inkling 2 softcapped SwiGLU over UNINTERLEAVED halves: ``alpha*tanh(gate/alpha) * sigmoid(gate) * limit*tanh(up/limit)``.""" + return _act_and_mul(SWIGLU_SOFTCAP, x, out, alpha=alpha, limit=limit) + + __all__ = [ "silu_and_mul", "gelu_and_mul", "gelu_tanh_and_mul", "swigluoai_and_mul", "swiglu_clamp_and_mul", + "swiglu_softcap_and_mul", ] diff --git a/python/freetoken/kernel/triton/inkling2_attention.py b/python/freetoken/kernel/triton/inkling2_attention.py new file mode 100644 index 0000000000..5c08810719 --- /dev/null +++ b/python/freetoken/kernel/triton/inkling2_attention.py @@ -0,0 +1,151 @@ +"""Paged attention with Inkling 2's data-dependent relative position bias and per-token sink logit. + +One kernel serves prefill (any number of query rows per request, keys = the cached prefix plus this +chunk, all read back from the pool after the store) and decode / verify (a few rows per request). +The score of query row ``i`` (position ``p_i``) against key ``j`` (position ``j``, its index in the +request) is ``scale * q_i.k_j + bias_i(p_i - j)`` with ``bias_i(d) = sum_r rel_i[r] * table[r, d]`` +for ``0 <= d < extent`` and 0 beyond; each row also sees one extra logit ``sink_i`` with a zero value. +A sliding layer keeps keys with ``p_i - j < window``. +""" + +from __future__ import annotations + +import torch +import triton +import triton.language as tl + + +@triton.jit +def _inkling2_attn_kernel( + q_ptr, k_ptr, v_ptr, o_ptr, rel_ptr, table_ptr, sink_ptr, + qo_indptr_ptr, kv_indptr_ptr, kv_indices_ptr, q_pos_ptr, + sm_scale, + stride_qt, stride_qh, + stride_kt, stride_kh, + stride_vt, stride_vh, + stride_ot, stride_oh, + stride_rt, stride_rh, + stride_st, stride_sh, + GROUP: tl.constexpr, HEAD_DIM: tl.constexpr, REL_DIM: tl.constexpr, EXTENT: tl.constexpr, + WINDOW: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, +): + req = tl.program_id(0) + m_block = tl.program_id(1) + head = tl.program_id(2) + kv_head = head // GROUP + + q_start = tl.load(qo_indptr_ptr + req) + q_end = tl.load(qo_indptr_ptr + req + 1) + m0 = q_start + m_block * BLOCK_M + if m0 >= q_end: + return + rows = m0 + tl.arange(0, BLOCK_M) + row_mask = rows < q_end + rows64 = rows.to(tl.int64) + q_pos = tl.load(q_pos_ptr + rows64, mask=row_mask, other=0).to(tl.int32) + + kv_start = tl.load(kv_indptr_ptr + req) + kv_len = tl.load(kv_indptr_ptr + req + 1) - kv_start + + d = tl.arange(0, HEAD_DIM) + q = tl.load(q_ptr + rows64[:, None] * stride_qt + head * stride_qh + d[None, :], mask=row_mask[:, None], other=0.0) + sink = tl.load(sink_ptr + rows64 * stride_st + head * stride_sh, mask=row_mask, other=0.0).to(tl.float32) + + # the sink is a key with logit `sink` and value 0: it seeds the running max and denominator + m_i = sink + l_i = tl.full((BLOCK_M,), 1.0, tl.float32) + acc = tl.zeros((BLOCK_M, HEAD_DIM), tl.float32) + + pos_max = tl.max(tl.where(row_mask, q_pos, 0), axis=0) + hi = tl.minimum(pos_max + 1, kv_len) + lo = 0 + if WINDOW > 0: + pos_min = tl.min(tl.where(row_mask, q_pos, pos_max), axis=0) + lo = tl.maximum(pos_min - WINDOW + 1, 0) + + for n0 in range(lo, hi, BLOCK_N): + cols = n0 + tl.arange(0, BLOCK_N) + col_mask = cols < hi + slots = tl.load(kv_indices_ptr + kv_start + cols, mask=col_mask, other=0).to(tl.int64) + k = tl.load(k_ptr + slots[:, None] * stride_kt + kv_head * stride_kh + d[None, :], mask=col_mask[:, None], other=0.0) + s = tl.dot(q, tl.trans(k)) * sm_scale + + dist = q_pos[:, None] - cols[None, :] + in_extent = (dist >= 0) & (dist < EXTENT) + idx = tl.minimum(tl.maximum(dist, 0), EXTENT - 1) + bias = tl.zeros((BLOCK_M, BLOCK_N), tl.float32) + for r in tl.static_range(REL_DIM): + rel_r = tl.load(rel_ptr + rows64 * stride_rt + head * stride_rh + r, mask=row_mask, other=0.0).to(tl.float32) + prof = tl.load(table_ptr + r * EXTENT + idx).to(tl.float32) + bias += rel_r[:, None] * prof + s += tl.where(in_extent, bias, 0.0) + + valid = (dist >= 0) & col_mask[None, :] & row_mask[:, None] + if WINDOW > 0: + valid = valid & (dist < WINDOW) + s = tl.where(valid, s, float("-inf")) + + m_new = tl.maximum(m_i, tl.max(s, axis=1)) + alpha = tl.exp(m_i - m_new) + p = tl.exp(s - m_new[:, None]) + l_i = l_i * alpha + tl.sum(p, axis=1) + v = tl.load(v_ptr + slots[:, None] * stride_vt + kv_head * stride_vh + d[None, :], mask=col_mask[:, None], other=0.0) + acc = acc * alpha[:, None] + tl.dot(p.to(v.dtype), v) + m_i = m_new + + out = acc / l_i[:, None] + tl.store(o_ptr + rows64[:, None] * stride_ot + head * stride_oh + d[None, :], out.to(o_ptr.dtype.element_ty), mask=row_mask[:, None]) + + +def inkling2_paged_attention( + q: torch.Tensor, + k_cache: torch.Tensor, + v_cache: torch.Tensor, + *, + qo_indptr: torch.Tensor, + kv_indptr: torch.Tensor, + kv_indices: torch.Tensor, + q_positions: torch.Tensor, + max_q_len: int, + rel: torch.Tensor, + table: torch.Tensor, + sinks: torch.Tensor, + sm_scale: float, + sliding_window: int | None, + out: torch.Tensor | None = None, +) -> torch.Tensor: + """``q`` [T, H, D]; ``k_cache`` / ``v_cache`` [slots, KVH, D]; request ``b`` owns query rows + ``qo_indptr[b]:qo_indptr[b+1]`` and keys ``kv_indices[kv_indptr[b]:kv_indptr[b+1]]`` (key ``j`` at + position ``j``); ``rel`` [T, H, R], ``table`` [R, E], ``sinks`` [T, H]. Returns [T, H, D] in q's dtype.""" + T, H, D = q.shape + kvh = k_cache.shape[1] + assert H % kvh == 0 and k_cache.shape[-1] == D and q.stride(-1) == 1 and k_cache.stride(-1) == 1 + R, E = table.shape + assert rel.shape == (T, H, R) and rel.stride(-1) == 1 and sinks.shape == (T, H) + table = table.contiguous() + if out is None: + out = torch.empty_like(q) + bs = qo_indptr.numel() - 1 + if T == 0 or bs == 0: + return out + block_m = 16 if max_q_len <= 16 else 64 + block_n = 64 + grid = (bs, triton.cdiv(max_q_len, block_m), H) + _inkling2_attn_kernel[grid]( + q, k_cache, v_cache, out, rel, table, sinks, + qo_indptr, kv_indptr, kv_indices, q_positions, + float(sm_scale), + q.stride(0), q.stride(1), + k_cache.stride(0), k_cache.stride(1), + v_cache.stride(0), v_cache.stride(1), + out.stride(0), out.stride(1), + rel.stride(0), rel.stride(1), + sinks.stride(0), sinks.stride(1), + GROUP=H // kvh, HEAD_DIM=D, REL_DIM=R, EXTENT=E, + WINDOW=int(sliding_window or 0), BLOCK_M=block_m, BLOCK_N=block_n, + num_warps=4, num_stages=2, + ) + return out + + +__all__ = ["inkling2_paged_attention"] diff --git a/python/freetoken/kvcache/__init__.py b/python/freetoken/kvcache/__init__.py index 5a043a28e2..a1b877b8f1 100644 --- a/python/freetoken/kvcache/__init__.py +++ b/python/freetoken/kvcache/__init__.py @@ -158,7 +158,7 @@ def create_kvcache_pool( return HybridSWAKVCache( groups=model_config.kv_cache_group_specs(), - num_layers=model_config.num_layers, + num_layers=getattr(model_config, "num_kv_layers", None) or model_config.num_layers, num_full_pages=num_pages, page_size=page_size, num_swa_tokens=num_swa_tokens, diff --git a/python/freetoken/kvcache/linear_state_pool.py b/python/freetoken/kvcache/linear_state_pool.py index 767349862c..5b8b04ef97 100644 --- a/python/freetoken/kvcache/linear_state_pool.py +++ b/python/freetoken/kvcache/linear_state_pool.py @@ -35,6 +35,8 @@ def _linear_local_dims( class LinearStatePool: """Per-request recurrent state (conv + SSM) for GatedDeltaNet layers. + A model without GatedDeltaNet layers (``group`` None) gets a pool of its ``slot_states`` alone. + Indexed by ``Req.table_idx`` (0..max_running_req), the same per-request slot the page table uses, so the scheduler's existing admit/free of ``table_idx`` covers the state's lifetime. One fixed slot per running request; no paging, no eviction. @@ -47,7 +49,7 @@ class LinearStatePool: def __init__( self, - group: LinearGatedDeltaGroupConfig, + group: LinearGatedDeltaGroupConfig | None, num_slots: int, dtype: torch.dtype, device: torch.device, @@ -62,22 +64,27 @@ def __init__( self._device = device self._conv_dtype = dtype - n_layers, local_conv_dim, local_v_heads, self._local_k_heads = _linear_local_dims(group, tp_size) + if group is not None: + n_layers, local_conv_dim, local_v_heads, self._local_k_heads = _linear_local_dims(group, tp_size) + km1, k_dim, v_dim = group.conv_kernel_dim - 1, group.key_head_dim, group.value_head_dim + else: + # zero-layer GDN tensors: every whole-pool op below stays valid and moves no bytes + n_layers = local_conv_dim = local_v_heads = self._local_k_heads = km1 = k_dim = v_dim = 0 # conv left-context: the last (kernel-1) timesteps of the conv input stream. self.conv_states = torch.zeros( - (n_layers, num_slots, local_conv_dim, group.conv_kernel_dim - 1), + (n_layers, num_slots, local_conv_dim, km1), dtype=dtype, device=device, ) # SSM recurrent state. fp32 by default (matches HF mamba_ssm_dtype); the dtype is # overridable via FREETOKEN_MAMBA_SSM_DTYPE (see ssm_state_dtype). self.recurrent_states = torch.zeros( - (n_layers, num_slots, local_v_heads, group.key_head_dim, group.value_head_dim), + (n_layers, num_slots, local_v_heads, k_dim, v_dim), dtype=ssm_state_dtype(), device=device, ) - self._local_index = {layer_id: i for i, layer_id in enumerate(group.layer_ids)} + self._local_index = {} if group is None else {layer_id: i for i, layer_id in enumerate(group.layer_ids)} self._slot_specs = tuple(slot_states) names = [spec.name for spec in self._slot_specs] @@ -233,20 +240,26 @@ def device(self) -> torch.device: def attach_verify_scratch(self, max_bs: int, rows_per_req: int) -> None: """Build the scratch for verify batches of up to ``max_bs`` requests with ``rows_per_req`` rows each, and the verify handler of every slot state; build_fla_metadata hands the GDN scratch to the GDN layers.""" - self.verify_scratch = LinearVerifyScratch(self, max_bs, rows_per_req) + self.verify_scratch = LinearVerifyScratch(self, max_bs, rows_per_req) if self._group is not None else None self._verify_handlers = { spec.name: spec.verify(spec, max_bs, rows_per_req, self._device, self._state_dtype(spec)) for spec in self._slot_specs if spec.verify is not None } + @property + def verifies(self) -> bool: + """Whether verify batches leave state for ``commit_verify`` to roll forward (set by ``attach_verify_scratch``).""" + return self.verify_scratch is not None or bool(self._verify_handlers) + def verify_handler(self, name: str) -> SlotVerify: """The verify handler of slot state ``name``, for its owner's verify forward.""" return self._verify_handlers[name] def commit_verify(self, slots: List[int], counts: List[int]) -> None: """Advance live slot slots[i] over verify row i's first counts[i] tokens.""" - self.verify_scratch.commit(self, slots, counts) + if self.verify_scratch is not None: + self.verify_scratch.commit(self, slots, counts) if slots and self._verify_handlers: index = torch.tensor([slots, counts], dtype=torch.int64, pin_memory=self._device.type == "cuda") index = index.to(self._device, non_blocking=True) @@ -305,20 +318,21 @@ def commit(self, pool: LinearStatePool, slots: List[int], counts: List[int]) -> def linear_state_bytes_per_req( - group: LinearGatedDeltaGroupConfig, + group: LinearGatedDeltaGroupConfig | None, tp_size: int, dtype: torch.dtype, slot_states: tuple[SlotStateSpec, ...] = (), ) -> int: """Linear-state bytes for one request across all linear layers (TP-local), plus any declared slot_states.""" - n_layers, local_conv_dim, local_v_heads, _ = _linear_local_dims(group, tp_size) - - conv_elems = local_conv_dim * (group.conv_kernel_dim - 1) - rec_elems = local_v_heads * group.key_head_dim * group.value_head_dim - conv_bytes = conv_elems * dtype.itemsize # conv state in model dtype - rec_bytes = rec_elems * ssm_state_dtype().itemsize # recurrent state (default fp32) - total = n_layers * (conv_bytes + rec_bytes) + total = 0 + if group is not None: + n_layers, local_conv_dim, local_v_heads, _ = _linear_local_dims(group, tp_size) + conv_elems = local_conv_dim * (group.conv_kernel_dim - 1) + rec_elems = local_v_heads * group.key_head_dim * group.value_head_dim + conv_bytes = conv_elems * dtype.itemsize # conv state in model dtype + rec_bytes = rec_elems * ssm_state_dtype().itemsize # recurrent state (default fp32) + total = n_layers * (conv_bytes + rec_bytes) for spec in slot_states: item = (spec.dtype if spec.dtype is not None else dtype).itemsize @@ -335,9 +349,7 @@ def state_pool_bytes(config, num_slots: int | None = None) -> int: the state pool is a sibling pool, not a KV tier.""" linear_group = config.model_config.linear_attention_group() slot_states = getattr(config, "slot_states", ()) - if linear_group is None: - if slot_states: - raise ValueError("slot_states ride the linear-state slots; model has no linear group") + if linear_group is None and not slot_states: return 0 slots = num_slots if num_slots is not None else _linear_pool_num_slots(config) per_req = linear_state_bytes_per_req( @@ -349,12 +361,14 @@ def state_pool_bytes(config, num_slots: int | None = None) -> int: def verify_scratch_bytes(config, rows_per_req: int) -> int: """Bytes of the LinearVerifyScratch the engine builds for verify batches of ``rows_per_req`` rows per request (0 when it is 1).""" group = config.model_config.linear_attention_group() - if group is None or rows_per_req <= 1: + if rows_per_req <= 1 or (group is None and not getattr(config, "slot_states", ())): return 0 - n_layers, conv_dim, hv, hk = _linear_local_dims(group, config.tp_info.size) - rows = n_layers * config.max_running_req * rows_per_req - stash = rows * (hk * group.key_head_dim + hv * group.value_head_dim + 2 * hv) * 4 - window = rows * conv_dim * (group.conv_kernel_dim - 1) * config.dtype.itemsize + stash = window = 0 + if group is not None: + n_layers, conv_dim, hv, hk = _linear_local_dims(group, config.tp_info.size) + rows = n_layers * config.max_running_req * rows_per_req + stash = rows * (hk * group.key_head_dim + hv * group.value_head_dim + 2 * hv) * 4 + window = rows * conv_dim * (group.conv_kernel_dim - 1) * config.dtype.itemsize handlers = sum( spec.verify.nbytes(spec, config.max_running_req, rows_per_req, spec.dtype if spec.dtype is not None else config.dtype) for spec in getattr(config, "slot_states", ()) diff --git a/python/freetoken/layers/activation.py b/python/freetoken/layers/activation.py index e38a6caebc..0e7ef2c73e 100644 --- a/python/freetoken/layers/activation.py +++ b/python/freetoken/layers/activation.py @@ -68,7 +68,14 @@ def swiglu_clamp_and_mul( return swiglu_clamp_and_mul(x, out=out, alpha=alpha, limit=limit) -GATED_ACTIVATIONS = ("silu", "gelu", "gelu_tanh", "swigluoai", "swiglu_clamp") +def swiglu_softcap_and_mul(x, out=None, *, alpha: float = 4.0, limit: float = 25.0): + """Inkling 2 softcapped SwiGLU over UNINTERLEAVED halves: ``alpha*tanh(gate/alpha) * sigmoid(gate) * limit*tanh(up/limit)``.""" + from freetoken.kernel.triton.activation import swiglu_softcap_and_mul + + return swiglu_softcap_and_mul(x, out=out, alpha=alpha, limit=limit) + + +GATED_ACTIVATIONS = ("silu", "gelu", "gelu_tanh", "swigluoai", "swiglu_clamp", "swiglu_softcap") def gated_act_and_mul(activation: str, x, out, *, alpha: float = 1.0, limit: float = float("inf")): @@ -83,6 +90,8 @@ def gated_act_and_mul(activation: str, x, out, *, alpha: float = 1.0, limit: flo return swigluoai_and_mul(x, out, alpha=alpha, limit=limit) if activation == "swiglu_clamp": return swiglu_clamp_and_mul(x, out, alpha=alpha, limit=limit) + if activation == "swiglu_softcap": + return swiglu_softcap_and_mul(x, out, alpha=alpha, limit=limit) raise ValueError(f"no gated activation {activation!r}; known: {GATED_ACTIVATIONS}") @@ -92,6 +101,7 @@ def gated_act_and_mul(activation: str, x, out, *, alpha: float = 1.0, limit: flo "gelu_tanh_and_mul", "swigluoai_and_mul", "swiglu_clamp_and_mul", + "swiglu_softcap_and_mul", "gated_act_and_mul", "GATED_ACTIVATIONS", ] diff --git a/python/freetoken/layers/moe.py b/python/freetoken/layers/moe.py index 598bd1193f..477b40f373 100644 --- a/python/freetoken/layers/moe.py +++ b/python/freetoken/layers/moe.py @@ -354,6 +354,7 @@ def _prefill_routed( pass through unmapped.""" cache = self.offload_cache assert cache is not None + cache.start_prefill_call(self.layer_id) if cache.prefill_overlap: views = self._wait_prefill_overlap(cache) out = self._expert_gemm( @@ -389,11 +390,10 @@ def _wait_prefill_overlap(self, cache: OffloadMoeCache) -> tuple[torch.Tensor, . bank registration order; buffer position == expert id, so routing ids pass through unmapped). The caller runs ``release_prefill_layer`` after its GEMMs. """ - if self.layer_id == 0: - cache.begin_prefill() - cache.prefetch_prefill_layer(self.layer_id) - cache.prefetch_prefill_layer(self.layer_id + 1) - return cache.wait_prefill_layer(self.layer_id) + step = cache.prefill_step(self.layer_id) + cache.prefetch_prefill_layer(self.layer_id, step) + cache.prefetch_prefill_layer(cache.next_prefill_layer(self.layer_id), step + 1) + return cache.wait_prefill_layer(self.layer_id, step) # ------------------------------------------------------------------ # Kernel dispatch: ``views`` are the bank tensors the movement step produced (in bank registration order) and ``topk_ids`` already index their rows. diff --git a/python/freetoken/mm/processor.py b/python/freetoken/mm/processor.py index 7872b7db8d..c3703cbcc5 100644 --- a/python/freetoken/mm/processor.py +++ b/python/freetoken/mm/processor.py @@ -109,10 +109,14 @@ def positions(self, length: int, items: list[MMItem]) -> tuple[torch.Tensor, int def dummy_items(self, dtype: torch.dtype, device: torch.device) -> list[MMItem]: """The smallest encodable item of each modality the family serves, for warming the encoders.""" - def apply(self, input_ids: torch.Tensor, images: list[bytes]) -> MMResult: - """Swap each image placeholder for its replacement sequence and precompute rope positions.""" + def decode_image(self, raw: bytes) -> Any: + """One request image as the PIL image process() takes; families that composite alpha themselves keep the mode.""" from PIL import Image + return Image.open(io.BytesIO(raw)).convert("RGB") + + def apply(self, input_ids: torch.Tensor, images: list[bytes]) -> MMResult: + """Swap each image placeholder for its replacement sequence and precompute rope positions.""" ids = input_ids.tolist() target = self.placeholder slots = _find_all(ids, target) @@ -122,7 +126,7 @@ def apply(self, input_ids: torch.Tensor, images: list[bytes]) -> MMResult: f"carries {len(images)} images" ) - pils = [Image.open(io.BytesIO(raw)).convert("RGB") for raw in images] + pils = [self.decode_image(raw) for raw in images] items = self.process(pils) out: list[int] = [] cursor = 0 diff --git a/python/freetoken/mm/processors/inkling2.py b/python/freetoken/mm/processors/inkling2.py new file mode 100644 index 0000000000..6a53107ab9 --- /dev/null +++ b/python/freetoken/mm/processors/inkling2.py @@ -0,0 +1,136 @@ +"""Inkling 2 image processor: no resize, the image is padded to whole 40-pixel tiles and every tile is one image token. + +Mirrors transformers' Inkling2ImageProcessor (the checkpoint's processor_config.json): transparent pixels are +composited onto an 8-pixel checkerboard, the pad value is -1 on the 0-255 scale, and the chat template renders one +``<|unused_200054|>`` per image that expands to rows * cols copies. +""" + +from __future__ import annotations + +import io +import math +import struct +from typing import Any + +import torch + +from freetoken.message import MMItem +from freetoken.mm import mm_pad_value +from freetoken.mm.config import MultimodalConfig +from freetoken.mm.processor import MMProcessor, PromptReplacement, content_hash + +# the config class default; the checkpoint's config.json leaves it out +IMAGE_TOKEN_ID = 200054 +# processor_config.json: rescale by 1/255, then normalize with mean = std = 0.5 +_RESCALE = 0.00392156862745098 +_MEAN_STD = 0.5 +# 0-255 value of the padding, before normalization +_PAD_FILL = -1.0 +_CHECKER = 8 +_CHECKER_LIGHT, _CHECKER_DARK = 204, 153 +# one image's token cap without --image-max-tokens (a 5120x5120 image); the tower attends over all its patches at once +DEFAULT_MAX_IMAGE_TOKENS = 16384 + + +def _section(config: Any, *names: str) -> Any: + for name in names: + value = getattr(config, name, None) + if value is not None: + return value + raise AttributeError(f"vision_config has none of {names}") + + +def _to_rgb_uint8(image: Any) -> torch.Tensor: + """[3, H, W] uint8; alpha is composited onto a checkerboard of 8-pixel squares, light at the origin.""" + import numpy as np + + rgba = image.has_transparency_data + pixels = torch.from_numpy(np.array(image.convert("RGBA" if rgba else "RGB"), dtype=np.uint8)).permute(2, 0, 1) + if not rgba: + return pixels.contiguous() + height, width = pixels.shape[-2:] + rows = torch.arange(height)[:, None] // _CHECKER + columns = torch.arange(width)[None, :] // _CHECKER + background = torch.where((rows + columns) % 2 == 0, _CHECKER_LIGHT, _CHECKER_DARK) + pixels = pixels.to(torch.int32) + alpha = pixels[3:4] + return ((pixels[:3] * alpha + background * (255 - alpha) + 127) // 255).to(torch.uint8) + + +def preprocess(image: Any, tile: int) -> tuple[torch.Tensor, int, int]: + """fp32 [rows * cols, tile, tile, 3] tiles in raster order, and the tile grid rows, cols.""" + pixels = _to_rgb_uint8(image) + channels, height, width = pixels.shape + rows, cols = math.ceil(height / tile), math.ceil(width / tile) + padded = torch.full((channels, rows * tile, cols * tile), _PAD_FILL, dtype=torch.float32) + padded[:, :height, :width] = pixels + # the reference folds the rescale into the mean and std: (x - 127.5) / 127.5 in fp32 + scale = torch.tensor([_MEAN_STD] * channels) * (1.0 / _RESCALE) + padded = (padded - scale[:, None, None]) / scale[:, None, None] + tiles = padded.reshape(channels, rows, tile, cols, tile).permute(1, 3, 2, 4, 0) + return tiles.reshape(rows * cols, tile, tile, channels), rows, cols + + +class Inkling2MMProcessor(MMProcessor): + def __init__(self, hf_config: Any, model_path: str, mm: MultimodalConfig) -> None: + super().__init__(model_path, mm) + vc = hf_config.vision_config + # the checkpoint's raw config names them native_patch_size / adapter_merge_size + self.tile = int(_section(vc, "patch_size", "native_patch_size")) * int(_section(vc, "spatial_merge_size", "adapter_merge_size")) + self.image_token_id = getattr(hf_config, "image_token_id", None) or IMAGE_TOKEN_ID + self.placeholder = [self.image_token_id] + self.max_tokens = mm.image_max_tokens if mm.image_max_tokens is not None else DEFAULT_MAX_IMAGE_TOKENS + + def decode_image(self, raw: bytes) -> Any: + from PIL import Image + + return Image.open(io.BytesIO(raw)) + + def process(self, images: list[Any]) -> list[MMItem]: + items: list[MMItem] = [] + for image in images: + width, height = image.size + rows, cols = math.ceil(height / self.tile), math.ceil(width / self.tile) + if rows * cols > self.max_tokens: + # the reference never resizes, so an image past the cap is refused rather than scaled down + raise ValueError( + f"a {width}x{height} image takes {rows * cols} image tokens ({rows}x{cols} tiles of {self.tile} pixels), " + f"above the limit of {self.max_tokens}; Inkling 2 does not resize images, so send a smaller image " + "or raise --image-max-tokens" + ) + tiles, rows, cols = preprocess(image, self.tile) + # the tower casts the pixels to its bf16 weights first, so bf16 on the wire loses nothing + feature = tiles.to(torch.bfloat16) + item_hash = content_hash(feature, struct.pack("<3i", 1, rows, cols)) + items.append( + MMItem( + modality="image", + hash=item_hash, + pad_value=mm_pad_value(item_hash), + offsets=[], + feature=feature, + model_specific_data={"grid_thw": [1, rows, cols]}, + ) + ) + return items + + def prompt_replacement(self, item: MMItem) -> PromptReplacement: + _, rows, cols = item.grid_thw + return PromptReplacement([self.image_token_id] * (rows * cols)) + + def _image_processor(self) -> None: + """None: the preprocessing is local (:func:`preprocess`); released transformers has no Inkling2ImageProcessor.""" + return None + + def dummy_items(self, dtype: torch.dtype, device: torch.device) -> list[MMItem]: + return [MMItem( + modality="image", + hash=0, + pad_value=0, + offsets=[[0, 1]], + feature=torch.zeros(1, self.tile, self.tile, 3, dtype=dtype, device=device), + model_specific_data={"grid_thw": [1, 1, 1]}, + )] + + +__all__ = ["IMAGE_TOKEN_ID", "Inkling2MMProcessor", "preprocess"] diff --git a/python/freetoken/models/config.py b/python/freetoken/models/config.py index 26700d3092..766db30a33 100644 --- a/python/freetoken/models/config.py +++ b/python/freetoken/models/config.py @@ -388,8 +388,18 @@ class ModelConfig: # (layer, source) pairs: the layer attends over the KV the source layer stored and stores none kv_shared_layers: Tuple[Tuple[int, int], ...] = () # Extra per-request tensors riding the LinearStatePool slots (see SlotStateSpec); - # () for models without any. Requires a linear-attention group to ride on. + # () for models without any. A model without linear-attention layers gets a pool of these alone. slot_states: Tuple[SlotStateSpec, ...] = () + # KV layers when some layers run more than once per forward with their own KV each (looped + # models): the attention groups then list cache-layer ids in [0, num_kv_layers). None = num_layers. + num_kv_layers: int | None = None + # why this model cannot resume from a cached prefix (forces --cache-type naive), or None + no_prefix_reuse: str | None = None + # KV formats the model's own attention kernel reads (--kv-cache-dtype names); None = what the pool and backend take + kv_formats: frozenset[str] | None = None + # Inkling 2 Mini (inkling2_loop) payload (Inkling2LoopArgs): the loop schedule and the attention / + # MoE scalars. Opaque to model-agnostic engine code; None for every other model. + inkling2_args: Any | None = None @property def is_moe(self) -> bool: diff --git a/python/freetoken/models/inkling2_loop/__init__.py b/python/freetoken/models/inkling2_loop/__init__.py new file mode 100644 index 0000000000..2632fa04b4 --- /dev/null +++ b/python/freetoken/models/inkling2_loop/__init__.py @@ -0,0 +1,14 @@ +from .config import Inkling2LoopArgs, parse_config, quant_config +from .model import Inkling2LoopForCausalLM, Inkling2LoopForConditionalGeneration +from .weight import iter_expert_pieces, iter_vision_weights, iter_weights + +__all__ = [ + "Inkling2LoopArgs", + "Inkling2LoopForCausalLM", + "Inkling2LoopForConditionalGeneration", + "iter_expert_pieces", + "iter_vision_weights", + "iter_weights", + "parse_config", + "quant_config", +] diff --git a/python/freetoken/models/inkling2_loop/attention.py b/python/freetoken/models/inkling2_loop/attention.py new file mode 100644 index 0000000000..2ca6b17ef9 --- /dev/null +++ b/python/freetoken/models/inkling2_loop/attention.py @@ -0,0 +1,139 @@ +"""Inkling 2 attention: L2-clipped q / k, unweighted-RMS v, short convolutions on k and v (dynamic taps on the +global layers), a data-dependent relative position bias, one sink logit per head and a sigmoid output gate. + +The global layers also scale q and the relative states by ``1 + alpha * ln(max((pos + 1) / n_floor, 1))``. +Every run of a layer reads and writes its own cache layer (``cache_layer``); the weights are shared. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch + +from freetoken.core import get_global_ctx +from freetoken.layers import BaseOP, LinearReplicated +from freetoken.utils import nvtx_annotate + +from .config import CONV_STATES, Inkling2LoopArgs +from .conv import ConvMetadata, short_conv + +if TYPE_CHECKING: + from freetoken.models.config import ModelConfig + + +def l2_clip(x: torch.Tensor, threshold: float, scale: torch.Tensor | None = None) -> torch.Tensor: + """Each head vector (last dim) scaled down to ``threshold`` when longer; fp32 in, fp32 out.""" + if scale is not None: + x = x * scale + norm = torch.linalg.vector_norm(x, dim=-1, keepdim=True) + return x * (threshold / (norm + 1e-6)).clamp(max=1.0) + + +def log_scale(positions: torch.Tensor, n_floor: int, alpha: float) -> torch.Tensor: + """``[T, 1, 1]`` fp32 ``1 + alpha * ln(max((pos + 1) / n_floor, 1))``.""" + tau = 1.0 + alpha * torch.log(((positions.float() + 1.0) / n_floor).clamp(min=1.0)) + return tau.view(-1, 1, 1) + + +def unweighted_rms_norm(x: torch.Tensor, eps: float) -> torch.Tensor: + x = x.float() + return x * torch.rsqrt(x.square().mean(-1, keepdim=True) + eps) + + +class Inkling2Attention(BaseOP): + def __init__(self, config: ModelConfig, layer_id: int, *, prefix: str = ""): + args: Inkling2LoopArgs = config.inkling2_args + self._args = args + self.layer_id = layer_id + self.is_sliding = args.is_sliding(layer_id) + self.num_heads = args.swa_num_heads if self.is_sliding else args.num_heads + self.num_kv_heads = args.swa_num_kv_heads if self.is_sliding else args.num_kv_heads + self.head_dim = args.swa_head_dim if self.is_sliding else args.head_dim + H, q_dim, kv_dim = args.hidden_size, self.num_heads * self.head_dim, self.num_kv_heads * self.head_dim + K = args.conv_kernel + quant = config.quant + self.q_proj = LinearReplicated(H, q_dim, has_bias=False, quant_config=quant, prefix=f"{prefix}.q_proj") + self.k_proj = LinearReplicated(H, kv_dim, has_bias=False, quant_config=quant, prefix=f"{prefix}.k_proj") + self.v_proj = LinearReplicated(H, kv_dim, has_bias=False, quant_config=quant, prefix=f"{prefix}.v_proj") + self.rel_proj = LinearReplicated(H, self.num_heads * args.d_rel, has_bias=False, quant_config=quant, prefix=f"{prefix}.rel_proj") + self.sink_proj = LinearReplicated(H, self.num_heads, has_bias=False, quant_config=quant, prefix=f"{prefix}.sink_proj") + self.gate_proj = LinearReplicated(H, q_dim, has_bias=False, quant_config=quant, prefix=f"{prefix}.gate_proj") + self.o_proj = LinearReplicated(q_dim, H, has_bias=False, quant_config=quant, prefix=f"{prefix}.o_proj") + self.q_scale = torch.empty(self.num_heads, self.head_dim, dtype=torch.float32) + self.rel_scale = torch.empty(self.num_heads, args.d_rel, dtype=torch.float32) + self.rel_table = torch.empty(args.d_rel, args.rel_extent) + # taps by lag: [0] weights the current token + if self.is_sliding: + self.k_conv = torch.empty(K, kv_dim, dtype=torch.float32) + self.v_conv = torch.empty(K, kv_dim, dtype=torch.float32) + else: + self.k_conv = torch.empty(K, kv_dim) + self.v_conv = torch.empty(K, kv_dim) + self.k_conv_proj = LinearReplicated(H, self.num_kv_heads * K, has_bias=False, quant_config=quant, prefix=f"{prefix}.k_conv_proj") + self.v_conv_proj = LinearReplicated(H, self.num_kv_heads * K, has_bias=False, quant_config=quant, prefix=f"{prefix}.v_conv_proj") + self._scale = self.head_dim**-0.5 + + def _kv(self, x: torch.Tensor, proj, conv: torch.Tensor, conv_proj, state: torch.Tensor, meta: ConvMetadata, stash) -> torch.Tensor: + T = x.shape[0] + y = proj.forward(x) + dynamic = None if conv_proj is None else conv_proj.forward(x).float().view(T, self.num_kv_heads, -1) + return short_conv(y, conv.float(), state, meta, dynamic=dynamic, head_dim=self.head_dim, verify_stash=stash) + + @nvtx_annotate("MHA") + def forward(self, xq: torch.Tensor, xk: torch.Tensor, xv: torch.Tensor, cache_layer: int, meta: ConvMetadata) -> torch.Tensor: + """``xq`` feeds q, the relative states, the sinks and the output gate; ``xk`` / ``xv`` the keys / values.""" + ctx = get_global_ctx() + batch = ctx.batch + args = self._args + pool = ctx.linear_state_pool + T, dt = xq.shape[0], xq.dtype + H, D = self.num_heads, self.head_dim + positions = batch.positions + + def stash(name: str): + return pool.verify_handler(name).stash(cache_layer) if meta.verify else None + + q = l2_clip(self.q_proj.forward(xq).view(T, H, D).float(), args.qk_clip, self.q_scale).to(dt) + rel = l2_clip(self.rel_proj.forward(xq).view(T, H, args.d_rel).float(), args.rel_clip, self.rel_scale).to(dt) + if not self.is_sliding: + tau = log_scale(positions, args.log_n_floor, args.log_alpha) + q = (q.float() * tau).to(dt) + rel = (rel.float() * tau).to(dt) + dyn = not self.is_sliding + k = self._kv(xk, self.k_proj, self.k_conv, self.k_conv_proj if dyn else None, + pool.slot_state(CONV_STATES[0], cache_layer), meta, stash(CONV_STATES[0])) + v = self._kv(xv, self.v_proj, self.v_conv, self.v_conv_proj if dyn else None, + pool.slot_state(CONV_STATES[1], cache_layer), meta, stash(CONV_STATES[1])) + k = l2_clip(k.view(T, self.num_kv_heads, D).float(), args.qk_clip).to(dt) + v = unweighted_rms_norm(v.view(T, self.num_kv_heads, D), args.rms_norm_eps).to(dt) + sinks = self.sink_proj.forward(xq) + + o = self._attend(q, k, v, rel, sinks, cache_layer) + gate = torch.sigmoid(self.gate_proj.forward(xq).float()) + o = (o.view(T, H * D).float() * gate).to(dt) + return self.o_proj.forward(o) + + def _attend(self, q, k, v, rel, sinks, cache_layer: int) -> torch.Tensor: + from freetoken.kernel.triton.inkling2_attention import inkling2_paged_attention + + ctx = get_global_ctx() + batch = ctx.batch + kv = ctx.kv_cache + md = batch.attn_metadata + kv.store_kv(k.reshape(k.shape[0], -1), v.reshape(v.shape[0], -1), batch.out_loc, cache_layer) + k_cache = kv.k_cache(cache_layer) + v_cache = kv.v_cache(cache_layer) + k_cache = k_cache.view(-1, k_cache.shape[-2], k_cache.shape[-1]) + v_cache = v_cache.view(-1, v_cache.shape[-2], v_cache.shape[-1]) + indices = md.swa_indices if (self.is_sliding and md.swa_indices is not None) else md.indices + return inkling2_paged_attention( + q, k_cache, v_cache, + qo_indptr=md.cu_seqlens_q_gpu, kv_indptr=md.indptr, kv_indices=indices, + q_positions=md.q_positions, max_q_len=md.max_q_len, + rel=rel, table=self.rel_table, sinks=sinks, sm_scale=self._scale, + sliding_window=self._args.sliding_window if self.is_sliding else None, + ) + + +__all__ = ["Inkling2Attention", "l2_clip", "log_scale", "unweighted_rms_norm"] diff --git a/python/freetoken/models/inkling2_loop/config.py b/python/freetoken/models/inkling2_loop/config.py new file mode 100644 index 0000000000..4a673b3de5 --- /dev/null +++ b/python/freetoken/models/inkling2_loop/config.py @@ -0,0 +1,290 @@ +"""Inkling 2 Mini (model_type ``inkling2_loop``): config parsing, the loop schedule and the checkpoint's expert quantization. + +Layers ``loop_start:loop_end`` run ``num_passes`` times per token with shared weights. Every run of a layer +("access") keeps its own KV and convolution state, so the KV pool and the state pool hold one cache layer +per access: weight layer ``L`` on pass 0 uses cache layer ``L``, later passes of a loop layer use cache +layers after the weight layers (pass ``p``: ``num_layers + (p - 1) * num_loop_layers + L - loop_start``). +""" + +from __future__ import annotations + +import json +import re +from dataclasses import dataclass +from typing import Any, Tuple + +from freetoken.models.config import ( + FullAttentionGroupConfig, + ModelConfig, + RotaryConfig, + SlotStateSpec, + SWAAttentionGroupConfig, +) + +# per-request convolution windows riding the linear-state slots, one tensor per convolution of a cache layer +CONV_STATES = ("inkling2_conv_k", "inkling2_conv_v", "inkling2_conv_attn", "inkling2_conv_mlp") + + +@dataclass(frozen=True) +class Inkling2LoopArgs: + num_layers: int + sliding_layers: frozenset[int] + loop_start: int + loop_end: int + num_passes: int + gate_rank: int + block_size: int + hidden_size: int + num_heads: int + num_kv_heads: int + head_dim: int + swa_num_heads: int + swa_num_kv_heads: int + swa_head_dim: int + sliding_window: int + d_rel: int + rel_extent: int + log_n_floor: int + log_alpha: float + qk_clip: float + rel_clip: float + conv_kernel: int + gate_softcap: float + up_softcap: float + route_scale: float + unpadded_vocab_size: int + rms_norm_eps: float + + @property + def num_loop_layers(self) -> int: + return self.loop_end - self.loop_start + + @property + def num_cache_layers(self) -> int: + return self.num_layers + (self.num_passes - 1) * self.num_loop_layers + + @property + def num_accesses(self) -> int: + return self.num_cache_layers + + def is_loop_layer(self, layer: int) -> bool: + return self.loop_start <= layer < self.loop_end + + def is_sliding(self, layer: int) -> bool: + return layer in self.sliding_layers + + def cache_layer(self, layer: int, pass_idx: int) -> int: + if pass_idx == 0: + return layer + assert self.is_loop_layer(layer) and pass_idx < self.num_passes, (layer, pass_idx) + return self.num_layers + (pass_idx - 1) * self.num_loop_layers + layer - self.loop_start + + def access(self, layer: int, pass_idx: int) -> int: + """Execution-order index of one run of ``layer``: 0.. for the prelude, then the passes, then the coda.""" + if layer < self.loop_start: + return layer + if layer >= self.loop_end: + return layer + (self.num_passes - 1) * self.num_loop_layers + return self.loop_start + pass_idx * self.num_loop_layers + layer - self.loop_start + + def schedule(self) -> Tuple[Tuple[int, int], ...]: + """``(weight layer, pass)`` of every access, in execution order.""" + prelude = [(layer, 0) for layer in range(self.loop_start)] + passes = [(layer, p) for p in range(self.num_passes) for layer in range(self.loop_start, self.loop_end)] + coda = [(layer, 0) for layer in range(self.loop_end, self.num_layers)] + return tuple(prelude + passes + coda) + + def cache_layers_of(self, sliding: bool) -> Tuple[int, ...]: + return tuple(sorted(self.cache_layer(layer, p) for layer, p in self.schedule() if self.is_sliding(layer) == sliding)) + + def kv_dim(self, layer: int) -> int: + return (self.swa_num_kv_heads * self.swa_head_dim) if self.is_sliding(layer) else (self.num_kv_heads * self.head_dim) + + def conv_widths(self) -> Tuple[int, int, int, int]: + """Channels of the k, v, post-attention and post-MLP convolutions; the state pool sizes one width per cache layer.""" + kv = max(self.kv_dim(layer) for layer in range(self.num_layers)) + return kv, kv, self.hidden_size, self.hidden_size + + +def _get(cfg: Any, *names: str, default: Any = None) -> Any: + for name in names: + value = cfg.get(name) if isinstance(cfg, dict) else getattr(cfg, name, None) + if value is not None: + return value + return default + + +def _loop_section(text: Any) -> dict: + loop = _get(text, "loop_config") + if loop is None: + # a transformers build that knows the model flattens loop_config into the text config + return { + "core_start": _get(text, "loop_layer_index_start"), + "core_end": _get(text, "loop_layer_index_end"), + "num_passes": _get(text, "loop_num_passes"), + "gate_rank": _get(text, "loop_gate_rank"), + } + return loop if isinstance(loop, dict) else (loop.to_dict() if hasattr(loop, "to_dict") else dict(vars(loop).get("_data", {}))) + + +def parse_args(text: Any) -> Inkling2LoopArgs: + num_layers = int(_get(text, "num_hidden_layers")) + local = _get(text, "local_layer_ids") + if local is None: + layer_types = _get(text, "layer_types") + local = [i for i, t in enumerate(layer_types) if t == "hybrid_sliding"] + loop = _loop_section(text) + if loop.get("is_varloop"): + raise NotImplementedError("variable-loop Inkling 2 checkpoints are not served; this build runs a fixed number of passes") + args = Inkling2LoopArgs( + num_layers=num_layers, + sliding_layers=frozenset(int(i) for i in local), + loop_start=int(loop["core_start"]), + loop_end=int(loop["core_end"]), + num_passes=int(loop["num_passes"]), + gate_rank=int(loop["gate_rank"]), + block_size=int(_get(text, "n_layers_per_attn_res_block", default=6)), + hidden_size=int(_get(text, "hidden_size")), + num_heads=int(_get(text, "num_attention_heads")), + num_kv_heads=int(_get(text, "num_key_value_heads")), + head_dim=int(_get(text, "head_dim")), + swa_num_heads=int(_get(text, "swa_num_attention_heads")), + swa_num_kv_heads=int(_get(text, "swa_num_key_value_heads")), + swa_head_dim=int(_get(text, "swa_head_dim")), + sliding_window=int(_get(text, "sliding_window_size", "sliding_window")), + d_rel=int(_get(text, "d_rel")), + rel_extent=int(_get(text, "rel_extent")), + log_n_floor=int(_get(text, "log_scaling_n_floor")), + log_alpha=float(_get(text, "log_scaling_alpha")), + qk_clip=float(_get(text, "qk_l2_clip_threshold")), + rel_clip=float(_get(text, "rel_l2_clip_threshold")), + conv_kernel=int(_get(text, "sconv_kernel_size", "conv_kernel_size", default=4)), + gate_softcap=float(_get(text, "mlp_gate_softcap")), + up_softcap=float(_get(text, "mlp_up_softcap")), + route_scale=float(_get(text, "route_scale", "routed_scaling_factor")), + unpadded_vocab_size=int(_get(text, "unpadded_vocab_size")), + rms_norm_eps=float(_get(text, "rms_norm_eps", default=1e-6)), + ) + if args.loop_start <= 0 or args.loop_start % args.block_size or args.loop_end % args.block_size: + raise ValueError(f"loop layers {args.loop_start}:{args.loop_end} must start and end on attention-residual block boundaries") + if args.swa_num_heads != args.num_heads or args.swa_head_dim != args.head_dim: + raise NotImplementedError("Inkling 2 checkpoints whose sliding and global layers differ in query heads or head size are not served") + if _get(text, "n_shared_experts", default=0): + raise NotImplementedError("Inkling 2 checkpoints with shared experts are not served") + return args + + +def conv_slot_states(args: Inkling2LoopArgs) -> Tuple[SlotStateSpec, ...]: + from .conv import ConvWindowVerify # conv imports this module + + layers = tuple(range(args.num_cache_layers)) + return tuple( + SlotStateSpec(name=name, shape=(args.conv_kernel - 1, width), layer_ids=layers, verify=ConvWindowVerify) + for name, width in zip(CONV_STATES, args.conv_widths()) + ) + + +def parse_config(hf_config: Any) -> ModelConfig: + from .vision import parse_vision_config # vision imports the layers + + text = _get(hf_config, "text_config", default=hf_config) + args = parse_args(text) + # no rope: positions only size the page table; the attention reads them as relative distances + rotary = RotaryConfig( + head_dim=args.head_dim, + rotary_dim=args.head_dim, + max_position=int(_get(text, "model_max_length", "max_position_embeddings", default=1 << 20)), + base=1.0, + scaling=None, + ) + architectures = list(_get(hf_config, "architectures", default=None) or ["Inkling2LoopForConditionalGeneration"]) + return ModelConfig( + num_layers=args.num_layers, + num_qo_heads=args.num_heads, + num_kv_heads=args.num_kv_heads, + head_dim=args.head_dim, + hidden_size=args.hidden_size, + vocab_size=int(_get(text, "vocab_size")), + intermediate_size=int(_get(text, "moe_intermediate_size", "intermediate_size")), + rms_norm_eps=args.rms_norm_eps, + rotary_config=rotary, + hidden_act="swiglu_softcap", + tie_word_embeddings=False, + num_experts=int(_get(text, "n_routed_experts", "num_local_experts")), + num_experts_per_tok=int(_get(text, "num_experts_per_tok")), + moe_intermediate_size=int(_get(text, "moe_intermediate_size", "intermediate_size")), + norm_topk_prob=True, + model_type="inkling2_loop", + architectures=architectures, + moe_enabled=True, + expert_quant="nvfp4" if _get(hf_config, "quantization_config") is not None else "none", + has_router_bias=True, + routed_scaling_factor=args.route_scale, + final_logit_softcapping=float(_get(text, "final_logit_softcapping")), + vision_config=parse_vision_config(hf_config), + image_token_id=int(_get(hf_config, "image_token_id", default=200054)), + attention_groups=( + FullAttentionGroupConfig( + name="full", + layer_ids=args.cache_layers_of(sliding=False), + num_kv_heads=args.num_kv_heads, + head_dim=args.head_dim, + rotary_config=rotary, + ), + SWAAttentionGroupConfig( + name="swa", + layer_ids=args.cache_layers_of(sliding=True), + num_kv_heads=args.swa_num_kv_heads, + head_dim=args.swa_head_dim, + rotary_config=rotary, + sliding_window=args.sliding_window, + ), + ), + num_kv_layers=args.num_cache_layers, + slot_states=conv_slot_states(args), + no_prefix_reuse=( + "the convolution windows of each cache layer are not snapshotted at prefix boundaries, " + "so a cached prefix cannot be resumed" + ), + # the relative-bias kernel reads bf16 K and V and no row scales + kv_formats=frozenset({"none"}), + inkling2_args=args, + ) + + +_EXPERT_TENSOR = re.compile(r"^(?P.+\.mlp\.experts)\.w(13|2)_weight$") +# hf_quant_config.json compute dtype -> the ModelOpt algo FreeToken serves it as +_SERVED_ALGOS = {"nvfp4": "W4A16_NVFP4", "mxfp8": "MXFP8"} + + +def quant_config(model_path: str, hf_config: Any, *, name_map, unquantized): + """The checkpoint's expert formats as a ModelOpt MIXED_PRECISION config. + + The config.json says ``modelopt`` / ``NVFP4`` for the whole model, but only the routed experts are quantized, + NVFP4 on most layers and MXFP8 on the last ones; ``hf_quant_config.json`` lists the tensors of each format. The + activation quantization it declares for the experts is not applied (W4A16 / W8A16), as in the reference.""" + from freetoken.layers.quantization import ModelOptConfig, QuantConfig + from freetoken.utils.hf import optional_hf_file + + path = optional_hf_file(model_path, "hf_quant_config.json") + if path is None: + return QuantConfig.from_hf(hf_config, name_map=name_map, unquantized=unquantized) + with open(path, encoding="utf-8") as f: + groups = (json.load(f).get("model") or {}).get("parameter_groups") or [] + layers: dict[str, dict] = {} + for group in groups: + algo = _SERVED_ALGOS.get(str(group.get("compute_dtype"))) + if algo is None: + continue + for tensor in group.get("tensors") or (): + if (m := _EXPERT_TENSOR.match(tensor)) is not None: + layers[m.group("module")] = {"quant_algo": algo} + q = {"quant_method": "modelopt", "quant_algo": "MIXED_PRECISION", "quantized_layers": layers} + if not layers: + from freetoken.layers.quantization import NoQuantConfig + + return NoQuantConfig(name_map, unquantized) + return ModelOptConfig(q, hf_config, name_map=name_map, unquantized=unquantized) + + +__all__ = ["CONV_STATES", "Inkling2LoopArgs", "conv_slot_states", "parse_args", "parse_config", "quant_config"] diff --git a/python/freetoken/models/inkling2_loop/conv.py b/python/freetoken/models/inkling2_loop/conv.py new file mode 100644 index 0000000000..70ee6ebec7 --- /dev/null +++ b/python/freetoken/models/inkling2_loop/conv.py @@ -0,0 +1,158 @@ +"""Inkling 2 short causal convolutions over a per-request window of the last ``K - 1`` inputs. + +Each cache layer convolves four streams (key, value, attention output, MLP output); their windows live in +the linear-state pool as the ``CONV_STATES`` slot states, one row per cache layer. Prefill packs every +request's window in front of its rows, decode appends its rows to the window. A verify forward reads the +live window only and stages ``window + rows`` for ``ConvWindowVerify.commit``, as the GDN verify does. +The convolution inputs are bf16 activations, so a bf16 window is exact. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass +from typing import List + +import torch + +from freetoken.core import Batch, get_global_ctx + +from .config import CONV_STATES + + +@dataclass +class ConvMetadata: + """Indices every convolution of one forward shares.""" + + slots: torch.Tensor # [B] int64 state slot of each request + kernel: int + # prefill: the packed history holds each request's window, then its rows + x_index: torch.Tensor | None = None # [T] history row of each input row + state_index: torch.Tensor | None = None # [B * (K-1)] history rows the windows fill + next_index: torch.Tensor | None = None # [B * (K-1)] history rows that become the windows + rows_per_req: int = 1 + verify: bool = False + + @property + def prefill(self) -> bool: + return self.x_index is not None + + +def prefill_indices(lens: List[int], kernel: int, device: torch.device): + """``(x_index, state_index, next_index)`` of the packed history for requests of ``lens`` rows.""" + km1 = kernel - 1 + counts = torch.tensor(lens, dtype=torch.int64) + cu = torch.cat([counts.new_zeros(1), counts.cumsum(0)]) + pad = torch.arange(len(lens), dtype=torch.int64) * km1 + base = cu[:-1] + pad + x_index = torch.arange(int(cu[-1])) + torch.repeat_interleave(pad + km1, counts) + span = torch.arange(km1, dtype=torch.int64) + state_index = (base.unsqueeze(1) + span).reshape(-1) + next_index = ((base + counts).unsqueeze(1) + span).reshape(-1) + packed = torch.cat([x_index, state_index, next_index]) + if torch.cuda.is_available() and device.type == "cuda": + packed = packed.pin_memory() + packed = packed.to(device, non_blocking=True) + n_x, n_s = x_index.numel(), state_index.numel() + return packed[:n_x], packed[n_x : n_x + n_s], packed[n_x + n_s :] + + +def build_conv_metadata(batch: Batch, kernel: int, device: torch.device) -> ConvMetadata: + """From ``batch.fla_metadata`` (state slots, fresh windows); zeroes the windows of fresh requests.""" + ctx = get_global_ctx() + pool = ctx.linear_state_pool + assert pool is not None, "Inkling 2 keeps its convolution windows in the linear-state pool" + fla = batch.fla_metadata + if fla is None: + from freetoken.attention.linear import build_fla_metadata + + fla = batch.fla_metadata = build_fla_metadata(batch, device, pool) + slots = fla.cache_indices.long() + if batch.is_prefill: + if fla.fresh_state_indices is not None: + for name in CONV_STATES: + pool.slot_states[name][:, fla.fresh_state_indices] = 0 + x_index, state_index, next_index = prefill_indices([r.extend_len for r in batch.padded_reqs], kernel, device) + return ConvMetadata(slots, kernel, x_index, state_index, next_index) + return ConvMetadata(slots, kernel, rows_per_req=int(batch.rows_per_req or 1), verify=batch.phase == "verify") + + +def _windowed_sum(lagged, weight: torch.Tensor, dynamic: torch.Tensor | None, head_dim: int) -> torch.Tensor: + """``sum_lag (weight[lag] + dynamic[..., lag]) * lagged(lag)``, fp32; ``dynamic`` [T, heads, K] repeats over each head's channels.""" + acc = None + for lag in range(weight.shape[0]): + w = weight[lag] + if dynamic is not None: + w = w + dynamic[:, :, lag].repeat_interleave(head_dim, dim=1) + term = lagged(lag).float() * w + acc = term if acc is None else acc + term + return acc + + +def short_conv( + x: torch.Tensor, + weight: torch.Tensor, + state: torch.Tensor, + meta: ConvMetadata, + *, + dynamic: torch.Tensor | None = None, + head_dim: int = 1, + verify_stash: torch.Tensor | None = None, +) -> torch.Tensor: + """``(x + conv(window ++ x)) / sqrt(K + 1)`` (``sqrt(2K + 1)`` with ``dynamic`` taps) in x's dtype. + + ``weight`` [K, C] fp32, tap ``lag`` weighting the input ``lag`` steps back; ``state`` [slots, K-1, C], the + window of each slot, oldest first, advanced in place (prefill, decode) or staged in ``verify_stash`` + [max_bs, K-1+R, C] (verify).""" + T, C = x.shape + K = meta.kernel + km1 = K - 1 + if meta.prefill: + hist = x.new_empty(T + meta.slots.numel() * km1, C) + hist.index_copy_(0, meta.state_index, state.index_select(0, meta.slots).reshape(-1, C).to(x.dtype)) + hist.index_copy_(0, meta.x_index, x) + state.index_copy_(0, meta.slots, hist.index_select(0, meta.next_index).view(-1, km1, C).to(state.dtype)) + acc = _windowed_sum(lambda lag: hist.index_select(0, meta.x_index - lag), weight, dynamic, head_dim) + else: + R = meta.rows_per_req + B = T // R + hist = torch.cat([state.index_select(0, meta.slots).to(x.dtype), x.view(B, R, C)], dim=1) + if meta.verify: + assert verify_stash is not None, "a verify forward stages its windows for the commit" + verify_stash[:B].copy_(hist) + else: + state.index_copy_(0, meta.slots, hist[:, R:].to(state.dtype)) + acc = _windowed_sum(lambda lag: hist[:, km1 - lag : km1 - lag + R].reshape(T, C), weight, dynamic, head_dim) + scale = 1.0 / math.sqrt((2 * K + 1) if dynamic is not None else (K + 1)) + return ((acc + x.float()) * scale).to(x.dtype) + + +class ConvWindowVerify: + """``SlotVerify`` of one convolution stream: per cache layer and verify row, the live window then every verify input.""" + + def __init__(self, spec, max_bs: int, rows_per_req: int, device: torch.device, dtype: torch.dtype) -> None: + self.name = spec.name + self.km1, width = spec.shape + self.history = { + layer_id: torch.zeros(max_bs, self.km1 + rows_per_req, width, dtype=dtype, device=device) + for layer_id in spec.layer_ids + } + + @staticmethod + def nbytes(spec, max_bs: int, rows_per_req: int, dtype: torch.dtype) -> int: + km1, width = spec.shape + return len(spec.layer_ids) * max_bs * (km1 + rows_per_req) * width * dtype.itemsize + + def stash(self, layer_id: int) -> torch.Tensor: + return self.history[layer_id] + + def commit(self, pool, slots: torch.Tensor, counts: torch.Tensor) -> None: + # after n accepted rows the window is history rows n .. n + K - 2 + rows = (counts.unsqueeze(1) + torch.arange(self.km1, device=counts.device)).unsqueeze(2) + for layer_id, history in self.history.items(): + states = pool.slot_state(self.name, layer_id) + window = history[: slots.numel()].gather(1, rows.expand(-1, -1, history.shape[2])) + states.index_copy_(0, slots, window.to(states.dtype)) + + +__all__ = ["ConvMetadata", "ConvWindowVerify", "build_conv_metadata", "prefill_indices", "short_conv"] diff --git a/python/freetoken/models/inkling2_loop/dspark.py b/python/freetoken/models/inkling2_loop/dspark.py new file mode 100644 index 0000000000..33c9b3f034 --- /dev/null +++ b/python/freetoken/models/inkling2_loop/dspark.py @@ -0,0 +1,430 @@ +"""Inkling 2 DSpark draft (the checkpoint's ``mtp.safetensors``), after vLLM ``models/inkling2/nvidia/dspark.py`` and sglang ``models/inkling2_mtp.py``. + +One forward drafts the block ``[anchor, mask x (block-1)]`` at positions ``p .. p+block-1``, ``p`` the anchor's: three dense layers whose +attention is bidirectional over the block and reads context K/V below ``p`` (local layers only the ``window`` positions before ``p``). +Context K/V of position ``q`` come from the target's features of the token at ``q``: the inputs of the tapped layer visits and the +final-norm output, mixed per layer by ``softmax(fuse_weight)``, normalized and projected through the layer's ``k/v_proj_ctx``. +A recurrent Markov head turns each mask row into a token in order: its rank-``r`` state reads the previous token and biases the +target head's logits, which are softcapped like the target's. +""" + +from __future__ import annotations + +import itertools +import os +from dataclasses import dataclass +from typing import Any, Callable, Iterable + +import torch +import torch.nn.functional as F + +# the draft's own tensors; ``mtp.safetensors`` holds exactly these, the first group under ``layers.{i}.`` +_LAYER_TENSORS = ( + "dflare_norm.weight", "input_layernorm.weight", "post_attention_layernorm.weight", + "self_attn.q_proj.weight", "self_attn.k_proj.weight", "self_attn.v_proj.weight", "self_attn.o_proj.weight", + "self_attn.q_norm.weight", "self_attn.k_norm.weight", + "self_attn.k_proj_ctx.weight", "self_attn.v_proj_ctx.weight", "self_attn.k_norm_ctx.weight", + "mlp.gate_proj.weight", "mlp.up_proj.weight", "mlp.down_proj.weight", +) +_HEAD_TENSORS = ( + "fuse_weight", "mask_embed", "norm.weight", + "markov_head.dflare_norm.weight", "markov_head.markov_w1.weight", + "markov_head.rnn_proj.weight", "markov_head.rnn_proj.bias", + "markov_head.hidden_out.weight", "markov_head.hidden_out.bias", +) +MTP_FILE = "mtp.safetensors" + + +def _section(obj: Any) -> dict: + """A config section (dict, PretrainedConfig or RawConfigShim) as a plain dict.""" + if obj is None: + return {} + if isinstance(obj, dict): + return obj + return obj.to_dict() + + +@dataclass(frozen=True) +class DSparkConfig: + hidden_size: int + num_layers: int + num_heads: int + num_kv_heads: int + head_dim: int + intermediate_size: int + rms_norm_eps: float + rope_theta: float + local_layer_ids: tuple[int, ...] + window: int + block_size: int + markov_rank: int + # target layer visits (loop passes counted) whose INPUT feeds tap i; the last, num_layer_visits, is the final-norm output + target_layer_ids: tuple[int, ...] + num_layer_visits: int + # visits that restart the loop core from the prelude's state: their input is the prelude's output, not the visit before + pass_start_visits: tuple[int, ...] + loop_core_start: int + vocab_size: int # unpadded: logits past it are never drafted + target_rms_norm_eps: float + softcap: float + max_position: int + + @property + def num_taps(self) -> int: + return len(self.target_layer_ids) + + def output_taps(self) -> dict[int, list[int]]: + """Target visit -> the feature columns its OUTPUT fills; the final-norm sentinel is not in it (``final_hidden`` fills the last column).""" + taps: dict[int, list[int]] = {} + for col, visit in enumerate(self.target_layer_ids[:-1]): + # the input of a pass-restart visit is the prelude's output; any other visit reads the one before it + src = self.loop_core_start - 1 if visit in self.pass_start_visits else visit - 1 + taps.setdefault(src, []).append(col) + return taps + + +def parse_dspark_config(hf_config: Any) -> DSparkConfig: + """The draft config from the target checkpoint's ``mtp_config``; only the shape the checkpoint ships (rnn_hidden head, BF16, no attention bias) is served.""" + draft = dict(_section(getattr(hf_config, "mtp_config", None))) + if not draft: + raise ValueError("the checkpoint has no mtp_config, so it ships no DSpark draft") + text = _section(getattr(hf_config, "text_config", None)) or _section(hf_config) + required = ("hidden_size", "num_hidden_layers", "num_attention_heads", "num_key_value_heads", "head_dim", "intermediate_size", + "rms_norm_eps", "rope_theta", "local_layer_ids", "sliding_window_size", "block_size", "markov_rank", + "markov_head_type", "target_layer_ids") + if missing := [key for key in required if key not in draft]: + raise ValueError(f"mtp_config lacks {missing}") + if draft["markov_head_type"] != "rnn_hidden": + raise ValueError(f"only the rnn_hidden DSpark Markov head is supported, got {draft['markov_head_type']!r}") + if draft.get("q_bias") or draft.get("o_bias"): + raise ValueError("DSpark drafts with attention projection biases are not supported") + if any(draft.get(key, "bfloat16") != "bfloat16" for key in ("dtype", "torch_dtype")): + raise ValueError("the DSpark draft must be bfloat16") + hidden = int(draft["hidden_size"]) + if hidden != int(text["hidden_size"]): + raise ValueError(f"the DSpark draft's hidden size {hidden} is not the target's {text['hidden_size']}") + num_layers, heads, kv_heads = int(draft["num_hidden_layers"]), int(draft["num_attention_heads"]), int(draft["num_key_value_heads"]) + local = tuple(int(i) for i in draft["local_layer_ids"]) + if len(set(local)) != len(local) or any(not 0 <= i < num_layers for i in local): + raise ValueError(f"mtp_config local_layer_ids {list(local)} must be distinct layers below {num_layers}") + if heads % kv_heads: + raise ValueError(f"{heads} query heads do not group over {kv_heads} KV heads") + block, rank = int(draft["block_size"]), int(draft["markov_rank"]) + if block < 2 or rank <= 0: + raise ValueError(f"DSpark needs block_size >= 2 and markov_rank > 0, got {block} and {rank}") + + layers = int(text["num_hidden_layers"]) + loop = _section(text.get("loop_config")) + if loop: + start, end, passes = int(loop["core_start"]), int(loop["core_end"]), int(loop["num_passes"]) + if loop.get("is_varloop"): + raise ValueError("DSpark taps fixed layer visits, so variable-loop checkpoints are not supported") + visits = layers + (passes - 1) * (end - start) + restarts = tuple(start + p * (end - start) for p in range(1, passes)) + else: + start, visits, restarts = 0, layers, () + taps = tuple(int(i) for i in draft["target_layer_ids"]) + # the input of visit 0 is the embedding, which no layer outputs + if len(taps) < 2 or list(taps) != sorted(set(taps)) or taps[0] < 1 or taps[-1] != visits: + raise ValueError(f"mtp_config target_layer_ids {list(taps)} must be sorted distinct layer visits in [1, {visits}) followed by {visits}, the final-norm output") + softcap = text.get("final_logit_softcapping") + vocab = int(text.get("unpadded_vocab_size") or text["vocab_size"]) + return DSparkConfig( + hidden_size=hidden, num_layers=num_layers, num_heads=heads, num_kv_heads=kv_heads, head_dim=int(draft["head_dim"]), + intermediate_size=int(draft["intermediate_size"]), rms_norm_eps=float(draft["rms_norm_eps"]), + rope_theta=float(draft["rope_theta"]), local_layer_ids=local, window=int(draft["sliding_window_size"]), + block_size=block, markov_rank=rank, target_layer_ids=taps, num_layer_visits=visits, pass_start_visits=restarts, + loop_core_start=start, vocab_size=vocab, target_rms_norm_eps=float(text.get("rms_norm_eps", 1e-6)), softcap=float(softcap) if softcap else 0.0, + max_position=int(draft.get("max_position_embeddings") or text.get("model_max_length") or 1 << 20), + ) + + +def mtp_file(path: str) -> str: + """Local path of the draft's safetensors for a checkpoint dir, a Hub repo id or the file itself.""" + if path.endswith(".safetensors"): + if not os.path.isfile(path): + raise ValueError(f"{path} does not exist") + return path + from freetoken.utils.hf import optional_hf_file + + found = optional_hf_file(path, MTP_FILE) + if found is None: + raise ValueError(f"{path} has no {MTP_FILE}, the DSpark draft") + return found + + +def rms_norm(x: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor: + """fp32 RMSNorm rounded once to ``x``'s dtype.""" + xf = x.float() + return (xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + eps) * weight.float()).to(x.dtype) + + +def add_rms_norm(x: torch.Tensor, residual: torch.Tensor, weight: torch.Tensor, eps: float) -> tuple[torch.Tensor, torch.Tensor]: + """``residual + x`` (rounded, the new residual) and the RMSNorm of the unrounded sum.""" + s = residual.float() + x.float() + return (s * torch.rsqrt(s.pow(2).mean(-1, keepdim=True) + eps) * weight.float()).to(x.dtype), s.to(residual.dtype) + + +def rope_inv_freq(theta: float, head_dim: int, device) -> torch.Tensor: + """fp32 NeoX inverse frequencies over the whole head, as the reference's rope cache builds them.""" + return 1.0 / (theta ** (torch.arange(0, head_dim, 2, dtype=torch.float32, device=device) / head_dim)) + + +def apply_rope(x: torch.Tensor, positions: torch.Tensor, inv_freq: torch.Tensor) -> torch.Tensor: + """NeoX rotary of ``x [n, heads, d]`` at ``positions [n]`` in fp32, rounded to ``x``'s dtype.""" + half = x.shape[-1] // 2 + freqs = positions.float()[:, None] * inv_freq[None, :] + cos, sin = freqs.cos()[:, None], freqs.sin()[:, None] + x1, x2 = x[..., :half].float(), x[..., half:].float() + return torch.cat((x1 * cos - x2 * sin, x2 * cos + x1 * sin), dim=-1).to(x.dtype) + + +def mixture_weights(fuse_weight: torch.Tensor) -> torch.Tensor: + return torch.softmax(fuse_weight.float(), dim=-1).to(fuse_weight.dtype) + + +class Inkling2DSparkDraft: + """The draft's weights and math; the proposer owns the context K/V, the per-request state and the verify.""" + + def __init__(self, config: DSparkConfig, weights: dict[str, torch.Tensor], embed: Callable[[torch.Tensor], torch.Tensor], + lm_head_weight: torch.Tensor, dtype: torch.dtype = torch.bfloat16) -> None: + c = self.config = config + self.device, self.dtype = lm_head_weight.device, dtype + if lm_head_weight.dtype != torch.bfloat16: + raise ValueError(f"the DSpark draft reads the target's LM head as stored, in bf16; got {lm_head_weight.dtype}") + if lm_head_weight.shape[0] < c.vocab_size or lm_head_weight.shape[1] != c.hidden_size: + raise ValueError(f"target LM head {tuple(lm_head_weight.shape)} does not cover vocab {c.vocab_size} x hidden {c.hidden_size}") + # serving shares the target's bf16 head; an fp32 draft (tests pin the math with one) copies it + self.embed, self.lm_head_weight = embed, lm_head_weight.to(dtype) + weights = {name: t.to(dtype) for name, t in weights.items()} + q, kv = c.num_heads * c.head_dim, c.num_kv_heads * c.head_dim + self.q_size, self.kv_size = q, kv + self.layers = [] + for i in range(c.num_layers): + p = f"layers.{i}." + w = lambda name: weights[p + name] # noqa: E731 + self.layers.append({ + "qkv": torch.cat([w("self_attn.q_proj.weight"), w("self_attn.k_proj.weight"), w("self_attn.v_proj.weight")]), + "kv_ctx": torch.cat([w("self_attn.k_proj_ctx.weight"), w("self_attn.v_proj_ctx.weight")]), + "o": w("self_attn.o_proj.weight"), + "gate_up": torch.cat([w("mlp.gate_proj.weight"), w("mlp.up_proj.weight")]), + "down": w("mlp.down_proj.weight"), + "q_norm": w("self_attn.q_norm.weight"), "k_norm": w("self_attn.k_norm.weight"), + "k_norm_ctx": w("self_attn.k_norm_ctx.weight"), + "input_ln": w("input_layernorm.weight"), "post_ln": w("post_attention_layernorm.weight"), + "dflare_norm": w("dflare_norm.weight"), + }) + self.norm, self.mask_embed = weights["norm.weight"], weights["mask_embed"] + # rounded to the draft dtype like the reference's mixture buffer; row i mixes the taps for layer i, the last row for the Markov head + self.fuse_alpha = mixture_weights(weights["fuse_weight"]) + r = c.markov_rank + self.markov_norm = weights["markov_head.dflare_norm.weight"] + self.markov_w1 = weights["markov_head.markov_w1.weight"] + rnn_w = weights["markov_head.rnn_proj.weight"] + # rnn_proj reads [state, emb(prev), hidden, f_rnn]: the first two change every step, the last two once per block + self.rnn_w_step, self.rnn_w_ctx = rnn_w[:, : 2 * r].contiguous(), rnn_w[:, 2 * r :].contiguous() + self.rnn_bias = weights["markov_head.rnn_proj.bias"].float() + self.fold_weight, self.fold_bias = self._fold(weights["markov_head.hidden_out.weight"], weights["markov_head.hidden_out.bias"]) + self.inv_freq = rope_inv_freq(c.rope_theta, c.head_dim, self.device) + + @torch.no_grad() + def _fold(self, out_w: torch.Tensor, out_b: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """``hidden_out`` folded into the LM head rows in fp64: the Markov bias over the vocab is ``latent @ W^T + b``.""" + head = self.lm_head_weight[: self.config.vocab_size] + weight = torch.empty(head.shape[0], self.config.markov_rank, dtype=self.dtype, device=self.device) + bias = torch.empty(head.shape[0], dtype=self.dtype, device=self.device) + proj, b = out_w.double(), out_b.double() + for start in range(0, head.shape[0], 8192): + rows = head[start : start + 8192].double() + weight[start : start + 8192] = rows @ proj + bias[start : start + 8192] = rows @ b + return weight, bias + + @classmethod + def load(cls, config: DSparkConfig, target_model, model_path: str, device: torch.device, dtype: torch.dtype) -> Inkling2DSparkDraft: + """Read ``mtp.safetensors`` next to the target's weights; the anchor embedding and the LM head are the target's.""" + import safetensors + + if dtype not in (torch.bfloat16, torch.float32): + raise ValueError(f"the DSpark draft runs in bf16 (or fp32 to check its math), not {dtype}") + path = mtp_file(model_path) + weights = {} + expected = set(_HEAD_TENSORS) | {f"layers.{i}.{name}" for i in range(config.num_layers) for name in _LAYER_TENSORS} + with safetensors.safe_open(path, framework="pt", device=str(device)) as f: + for name in f.keys(): + if name not in expected: + raise ValueError(f"{path}: unexpected DSpark tensor {name!r}") + tensor = f.get_tensor(name) + if tensor.dtype != torch.bfloat16: + raise ValueError(f"{path}: {name} is {tensor.dtype}, the DSpark draft is bf16") + weights[name] = tensor + if missing := sorted(expected - set(weights)): + raise ValueError(f"{path}: DSpark tensors missing: {missing}") + cls._check_shapes(config, weights, path) + embed, head = target_parts(target_model, config.target_rms_norm_eps) + return cls(config, weights, embed, head, dtype) + + @staticmethod + def _check_shapes(c: DSparkConfig, w: dict[str, torch.Tensor], path: str) -> None: + H, q, kv, r = c.hidden_size, c.num_heads * c.head_dim, c.num_kv_heads * c.head_dim, c.markov_rank + shapes = {"fuse_weight": (c.num_layers + 1, c.num_taps), "mask_embed": (H,), "norm.weight": (H,), + "markov_head.dflare_norm.weight": (H,), "markov_head.rnn_proj.weight": (3 * r, 2 * r + 2 * H), + "markov_head.rnn_proj.bias": (3 * r,), "markov_head.hidden_out.weight": (H, r), "markov_head.hidden_out.bias": (H,)} + for i in range(c.num_layers): + p = f"layers.{i}." + shapes.update({p + "self_attn.q_proj.weight": (q, H), p + "self_attn.k_proj.weight": (kv, H), p + "self_attn.v_proj.weight": (kv, H), + p + "self_attn.o_proj.weight": (H, q), p + "self_attn.k_proj_ctx.weight": (kv, H), p + "self_attn.v_proj_ctx.weight": (kv, H), + p + "mlp.gate_proj.weight": (c.intermediate_size, H), p + "mlp.up_proj.weight": (c.intermediate_size, H), + p + "mlp.down_proj.weight": (H, c.intermediate_size)}) + for name, shape in shapes.items(): + if tuple(w[name].shape) != shape: + raise ValueError(f"{path}: {name} is {tuple(w[name].shape)}, expected {shape}") + if w["markov_head.markov_w1.weight"].shape[1] != r or w["markov_head.markov_w1.weight"].shape[0] < c.vocab_size: + raise ValueError(f"{path}: markov_w1 {tuple(w['markov_head.markov_w1.weight'].shape)} does not cover vocab {c.vocab_size} x rank {r}") + + # ---------------------------------------------------------------- target features + + def mix(self, features: torch.Tensor, row: int, weight: torch.Tensor) -> torch.Tensor: + """RMSNorm of the ``fuse_alpha[row]``-weighted sum of the taps in ``features [n, taps*H]`` (fp32 math).""" + c = self.config + taps = features.view(features.shape[0], c.num_taps, c.hidden_size).float() + mixed = (taps * self.fuse_alpha[row].float()[None, :, None]).sum(1) + return (mixed * torch.rsqrt(mixed.pow(2).mean(-1, keepdim=True) + c.rms_norm_eps) * weight.float()).to(self.dtype) + + def context_kv(self, features: torch.Tensor, positions: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """Every layer's context K/V ``[layers, n, kv_heads, d]`` of the target features at ``positions``.""" + c, n = self.config, features.shape[0] + ks, vs = [], [] + for i, layer in enumerate(self.layers): + kv = F.linear(self.mix(features, i, layer["dflare_norm"]), layer["kv_ctx"]) + k = rms_norm(kv[:, : self.kv_size].reshape(n, c.num_kv_heads, c.head_dim), layer["k_norm_ctx"], c.rms_norm_eps) + ks.append(apply_rope(k, positions, self.inv_freq)) + vs.append(kv[:, self.kv_size :].reshape(n, c.num_kv_heads, c.head_dim)) + return torch.stack(ks), torch.stack(vs) + + def f_rnn(self, features: torch.Tensor) -> torch.Tensor: + """The Markov head's context from the features of the last committed token, ``[n, H]``.""" + return self.mix(features, -1, self.markov_norm) + + # ---------------------------------------------------------------- block forward + + def forward_block(self, anchor: torch.Tensor, starts: torch.Tensor, context: Callable[[int], Iterable[tuple[torch.Tensor, torch.Tensor, torch.Tensor]]]) -> torch.Tensor: + """Final hidden ``[bs, block, H]`` of the blocks ``[anchor, mask x (block-1)]`` at positions ``starts + j``. + + ``context(layer)`` yields that layer's context in chunks ``k, v [bs, C, kv_heads, d]`` and ``valid [bs, C]``, the columns a query of the block may read; chunks bound the memory of a long context. + """ + c = self.config + bs, block = anchor.shape[0], c.block_size + x = self.mask_embed.expand(bs, block, -1).clone() + x[:, 0] = self.embed(anchor).to(x.dtype) + x = x.view(bs * block, -1) + positions = (starts.view(-1, 1) + torch.arange(block, device=anchor.device)).view(-1) + residual = None + for i, layer in enumerate(self.layers): + if residual is None: + residual, h = x, rms_norm(x, layer["input_ln"], c.rms_norm_eps) + else: + h, residual = add_rms_norm(x, residual, layer["input_ln"], c.rms_norm_eps) + qkv = F.linear(h, layer["qkv"]) + q = rms_norm(qkv[:, : self.q_size].reshape(-1, c.num_heads, c.head_dim), layer["q_norm"], c.rms_norm_eps) + k = rms_norm(qkv[:, self.q_size : self.q_size + self.kv_size].reshape(-1, c.num_kv_heads, c.head_dim), layer["k_norm"], c.rms_norm_eps) + q, k = apply_rope(q, positions, self.inv_freq), apply_rope(k, positions, self.inv_freq) + v = qkv[:, self.q_size + self.kv_size :].reshape(-1, c.num_kv_heads, c.head_dim) + # bidirectional over the block, which every query reads in full; it goes first so every row has a finite max + own = (k.view(bs, block, c.num_kv_heads, c.head_dim), v.view(bs, block, c.num_kv_heads, c.head_dim), + torch.ones(bs, block, dtype=torch.bool, device=k.device)) + o = self._attend(q.view(bs, block, c.num_heads, c.head_dim), itertools.chain([own], context(i))) + o = F.linear(o.to(h.dtype).reshape(bs * block, self.q_size), layer["o"]) + h, residual = add_rms_norm(o, residual, layer["post_ln"], c.rms_norm_eps) + gate, up = F.linear(h, layer["gate_up"]).float().chunk(2, dim=-1) + x = F.linear((F.silu(gate) * up).to(h.dtype), layer["down"]) + out, _ = add_rms_norm(x, residual, self.norm, c.rms_norm_eps) + return out.view(bs, block, -1) + + def _attend(self, q: torch.Tensor, chunks: Iterable[tuple[torch.Tensor, torch.Tensor, torch.Tensor]]) -> torch.Tensor: + """fp32 softmax attention of ``q [bs, block, heads, d]`` over the key chunks, merged by their running max and sum; ``[bs, block, heads, d]``.""" + c = self.config + bs, block, heads, d = q.shape + group = heads // c.num_kv_heads + # GQA as [bs, kv_heads, group*block, d] against [bs, kv_heads, C, d]: no repeated keys + qf = q.float().view(bs, block, c.num_kv_heads, group, d).permute(0, 2, 3, 1, 4).reshape(bs, c.num_kv_heads, group * block, d) * d**-0.5 + m = acc = total = None + for k, v, valid in chunks: + s = qf @ k.float().permute(0, 2, 3, 1) + s = s.masked_fill(~valid[:, None, None, :], float("-inf")) + m_new = s.amax(-1, keepdim=True) if m is None else torch.maximum(m, s.amax(-1, keepdim=True)) + p = torch.exp(s - m_new) + pv = p @ v.float().transpose(1, 2) + if m is None: + acc, total = pv, p.sum(-1, keepdim=True) + else: + scale = torch.exp(m - m_new) + acc, total = acc * scale + pv, total * scale + p.sum(-1, keepdim=True) + m = m_new + out = (acc / total).view(bs, c.num_kv_heads, group, block, d) + return out.permute(0, 3, 1, 2, 4).reshape(bs, block, heads, d) + + # ---------------------------------------------------------------- Markov head + + def markov_context(self, hidden: torch.Tensor, f_rnn: torch.Tensor) -> torch.Tensor: + """fp32 ``rnn_proj`` bias plus its ``[hidden, f_rnn]`` term, ``[bs, steps, 3r]`` for ``hidden [bs, steps, H]``.""" + inputs = torch.cat([hidden, f_rnn[:, None].expand_as(hidden)], dim=-1) + return (inputs.float() @ self.rnn_w_ctx.float().T) + self.rnn_bias + + def markov_step(self, state: torch.Tensor, prev: torch.Tensor, context: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """One recurrence step from ``state [bs, r]`` and the previous token ``prev [bs]``: the new state and the bf16 vocab bias.""" + r = self.config.markov_rank + inputs = torch.cat([state, self.markov_w1[prev.long()]], dim=-1) + raw = (context + inputs.float() @ self.rnn_w_step.float().T).to(self.dtype).float() + # each op rounds to bf16 like the reference's bf16 torch ops + rnd = lambda t: t.to(self.dtype).float() # noqa: E731 + gate, cand, out = raw[:, :r], raw[:, r : 2 * r], raw[:, 2 * r :] + gate, cand = rnd(torch.sigmoid(gate)), rnd(torch.tanh(cand)) + new_state = (rnd(gate * state.float()) + rnd(rnd(1.0 - gate) * cand)).to(self.dtype) + latent = torch.tanh(out).to(self.dtype) + bias = torch.addmm(self.fold_bias, latent, self.fold_weight.T) + return new_state, bias + + def step_logits(self, base: torch.Tensor, bias: torch.Tensor) -> torch.Tensor: + """bf16 ``softcap * tanh(bf16(base + bias) / softcap)`` over the unpadded vocab.""" + x = (base.float() + bias.float()).to(self.dtype).float() + if self.config.softcap: + x = torch.tanh(x / self.config.softcap) * self.config.softcap + return x.to(self.dtype) + + def base_logits(self, hidden: torch.Tensor) -> torch.Tensor: + """bf16 GEMM of the draft's hidden with the target head's rows of the unpadded vocab.""" + return F.linear(hidden, self.lm_head_weight[: self.config.vocab_size]) + + def walk(self, hidden: torch.Tensor, anchor: torch.Tensor, f_rnn: torch.Tensor, pick: Callable[[int, torch.Tensor], torch.Tensor]) -> torch.Tensor: + """Tokens ``[bs, steps]`` from the mask rows' ``hidden [bs, steps, H]``: step j's logits read the token picked at j-1 (the anchor at 0); ``pick(j, logits)`` chooses.""" + bs, steps, _ = hidden.shape + base = self.base_logits(hidden) + context = self.markov_context(hidden, f_rnn) + state = hidden.new_zeros(bs, self.config.markov_rank) + prev, tokens = anchor, [] + for j in range(steps): + state, bias = self.markov_step(state, prev, context[:, j]) + prev = pick(j, self.step_logits(base[:, j], bias)) + tokens.append(prev) + return torch.stack(tokens, dim=1) + + +def target_parts(target_model, eps: float) -> tuple[Callable[[torch.Tensor], torch.Tensor], torch.Tensor]: + """What the draft shares with the target: its first layer's input of a token (``embed_norm(embed(ids))``) and its bf16 LM head weight ``[padded vocab, H]``, as stored.""" + model = getattr(target_model, "model", None) + embed_tokens, embed_norm = getattr(model, "embed_tokens", None), getattr(model, "embed_norm", None) + head = getattr(getattr(target_model, "lm_head", None), "weight", None) + if embed_tokens is None or embed_norm is None or head is None: + raise ValueError(f"{type(target_model).__name__} lacks model.embed_tokens, model.embed_norm or lm_head.weight, which the DSpark draft shares") + + def embed(ids: torch.Tensor) -> torch.Tensor: + # the target's own order: fp32 weight times the normalized row, rounded once + x = embed_tokens.forward(ids) + xf = x.float() + return (embed_norm.float() * (xf * torch.rsqrt(xf.square().mean(-1, keepdim=True) + eps))).to(x.dtype) + + return embed, head + + +__all__ = ["DSparkConfig", "Inkling2DSparkDraft", "MTP_FILE", "mtp_file", "parse_dspark_config", "target_parts"] diff --git a/python/freetoken/models/inkling2_loop/model.py b/python/freetoken/models/inkling2_loop/model.py new file mode 100644 index 0000000000..e5324d7665 --- /dev/null +++ b/python/freetoken/models/inkling2_loop/model.py @@ -0,0 +1,265 @@ +"""Inkling 2 Mini decoder: block attention residuals, the three-pass loop over layers 6-17 and the fp32 softcapped head. + +Residual stream (as the reference): a layer returns the running sum of its block; at a block boundary (every +``block_size`` layers) the finished sum becomes a block state. Each sublayer input is a softmax over depth of +the RMS-normalized block states plus the running sum, with learned fp32 queries (three on the global layers, +for q, k and v). Pass 2 and 3 of the loop restart from the prelude's states; each loop layer first mixes in four +messages read from the previous pass by learned queries, through low-rank fp32 gates. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, List + +import torch +import torch.nn.functional as F + +from freetoken.core import get_global_ctx +from freetoken.layers import BaseOP, LinearReplicated, OPList, ParallelLMHead, VocabParallelEmbedding +from freetoken.models.blocks import BaseLLMModel +from freetoken.utils import nvtx_annotate + +from .attention import Inkling2Attention, unweighted_rms_norm +from .config import CONV_STATES, Inkling2LoopArgs +from .conv import ConvMetadata, build_conv_metadata, short_conv +from .moe import Inkling2MoE + +if TYPE_CHECKING: + from freetoken.message import MMItem + from freetoken.models.config import ModelConfig + +# the reference's depth-attention norm uses its own default eps, not the config's +_DEPTH_EPS = 1e-6 + + +def rms_norm(x: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor: + """Weighted RMSNorm computed in fp32; the caller picks the output dtype.""" + x = x.float() + return weight * (x * torch.rsqrt(x.square().mean(-1, keepdim=True) + eps)) + + +def depth_attention(sources: List[torch.Tensor], queries: torch.Tensor) -> torch.Tensor: + """``[T, Q, H]`` fp32: per token, softmax over the RMS-normalized ``sources`` [T, H] (fp32, already normalized) + of ``query . source / sqrt(H)``, the weighted sum of the normalized sources.""" + hidden = sources[0].shape[-1] + logits = torch.stack([s @ queries.t() for s in sources], dim=-1) * hidden**-0.5 # [T, Q, N] + p = torch.softmax(logits, dim=-1) + out = p[..., 0, None] * sources[0][:, None, :] + for j in range(1, len(sources)): + out = out + p[..., j, None] * sources[j][:, None, :] + return out + + +def normalized(x: torch.Tensor) -> torch.Tensor: + return unweighted_rms_norm(x, _DEPTH_EPS) + + +class MessageGate(BaseOP): + """``(1 - tanh(f)) * h + tanh(g) * m`` with ``f``, ``g`` fp32 projections of a bf16 low-rank mix of norm(h), norm(m).""" + + def __init__(self, config: ModelConfig, *, prefix: str = ""): + args: Inkling2LoopArgs = config.inkling2_args + H, rank = args.hidden_size, args.gate_rank + self.down_proj = LinearReplicated(2 * H, rank, has_bias=False, quant_config=config.quant, prefix=f"{prefix}.down_proj") + self.forget_proj = torch.empty(H, rank, dtype=torch.float32) + self.message_proj = torch.empty(H, rank, dtype=torch.float32) + self._eps = args.rms_norm_eps + + def forward(self, h: torch.Tensor, m: torch.Tensor) -> torch.Tensor: + h, m = h.float(), m.float() + mix = torch.cat([unweighted_rms_norm(h, self._eps), unweighted_rms_norm(m, self._eps)], dim=-1) + mix = self.down_proj.forward(mix.to(self.down_proj.weight.dtype)).float() + forget = torch.tanh(F.linear(mix, self.forget_proj)) + gain = torch.tanh(F.linear(mix, self.message_proj)) + return (1 - forget) * h + gain * m + + +class Inkling2DecoderLayer(BaseOP): + def __init__(self, config: ModelConfig, layer_id: int, *, prefix: str = ""): + args: Inkling2LoopArgs = config.inkling2_args + self._args = args + self.layer_id = layer_id + self.is_sliding = args.is_sliding(layer_id) + self.is_block_boundary = layer_id % args.block_size == 0 + H, K = args.hidden_size, args.conv_kernel + # layer 0 reads the embeddings directly + self.attention_query = None if layer_id == 0 else torch.empty(1 if self.is_sliding else 3, H, dtype=torch.float32) + self.mlp_query = torch.empty(1, H, dtype=torch.float32) + if self.is_sliding: + self.input_layernorm = torch.empty(H, dtype=torch.float32) + else: + self.q_input_layernorm = torch.empty(H, dtype=torch.float32) + self.k_input_layernorm = torch.empty(H, dtype=torch.float32) + self.v_input_layernorm = torch.empty(H, dtype=torch.float32) + self.post_attention_layernorm = torch.empty(H, dtype=torch.float32) + self.attn_conv = torch.empty(K, H, dtype=torch.float32) + self.mlp_conv = torch.empty(K, H, dtype=torch.float32) + self.self_attn = Inkling2Attention(config, layer_id, prefix=f"{prefix}.self_attn") + self.mlp = Inkling2MoE(config, layer_id, prefix=f"{prefix}.mlp") + if args.is_loop_layer(layer_id): + self.q_message_gate = MessageGate(config, prefix=f"{prefix}.q_message_gate") + self.k_message_gate = MessageGate(config, prefix=f"{prefix}.k_message_gate") + self.v_message_gate = MessageGate(config, prefix=f"{prefix}.v_message_gate") + self.mlp_message_gate = MessageGate(config, prefix=f"{prefix}.mlp_message_gate") + + def _attn_inputs(self, h: torch.Tensor, blocks: List[torch.Tensor], messages: torch.Tensor | None): + eps, dt = self._args.rms_norm_eps, h.dtype + if self.attention_query is None: + heads = [h] * (1 if self.is_sliding else 3) + else: + mixed = depth_attention(blocks + [normalized(h)], self.attention_query) + heads = list(mixed.unbind(1)) + if self.is_sliding: + if messages is None: + x = rms_norm(heads[0], self.input_layernorm, eps).to(dt) + return x, x, x + gates = (self.q_message_gate, self.k_message_gate, self.v_message_gate) + return tuple(rms_norm(g.forward(heads[0], messages[:, i]), self.input_layernorm, eps).to(dt) for i, g in enumerate(gates)) + if messages is not None: + gates = (self.q_message_gate, self.k_message_gate, self.v_message_gate) + heads = [g.forward(x, messages[:, i]) for i, (g, x) in enumerate(zip(gates, heads))] + norms = (self.q_input_layernorm, self.k_input_layernorm, self.v_input_layernorm) + return tuple(rms_norm(x, w, eps).to(dt) for x, w in zip(heads, norms)) + + @nvtx_annotate("Layer_{}", layer_id_field="layer_id") + def forward( + self, h: torch.Tensor, blocks: List[torch.Tensor], messages: torch.Tensor | None, cache_layer: int, meta: ConvMetadata + ) -> torch.Tensor: + """``h`` [T, H] the running block sum (bf16), ``blocks`` the normalized block states; returns the new running sum.""" + pool = get_global_ctx().linear_state_pool + args, dt = self._args, h.dtype + + def stash(name: str): + return pool.verify_handler(name).stash(cache_layer) if meta.verify else None + + xq, xk, xv = self._attn_inputs(h, blocks, messages) + a = self.self_attn.forward(xq, xk, xv, cache_layer, meta) + a = short_conv(a, self.attn_conv, pool.slot_state(CONV_STATES[2], cache_layer), meta, verify_stash=stash(CONV_STATES[2])) + residual = a.float() + if self.is_block_boundary: + blocks = blocks + [normalized(h)] + else: + residual = h.float() + residual + m = depth_attention(blocks + [normalized(residual)], self.mlp_query)[:, 0] + if messages is not None: + m = self.mlp_message_gate.forward(m, messages[:, 3]) + y = self.mlp.forward(rms_norm(m, self.post_attention_layernorm, args.rms_norm_eps).to(dt)) + y = short_conv(y, self.mlp_conv, pool.slot_state(CONV_STATES[3], cache_layer), meta, verify_stash=stash(CONV_STATES[3])) + return (residual + y.float()).to(dt) + + +class Inkling2LoopModel(BaseOP): + def __init__(self, config: ModelConfig, *, prefix: str = "model"): + args: Inkling2LoopArgs = config.inkling2_args + self._args = args + H = args.hidden_size + self.embed_tokens = VocabParallelEmbedding( + num_embeddings=config.vocab_size, embedding_dim=H, quant_config=config.quant, prefix=f"{prefix}.embed_tokens" + ) + self.embed_norm = torch.empty(H, dtype=torch.float32) + self.layers = OPList([Inkling2DecoderLayer(config, i, prefix=f"{prefix}.layers.{i}") for i in range(args.num_layers)]) + # per loop layer: the query, key, value and MLP message queries + self.message_queries = torch.empty(args.num_loop_layers, 4, H, dtype=torch.float32) + self.final_query = torch.empty(1, H, dtype=torch.float32) + self.norm = torch.empty(H, dtype=torch.float32) + + def embed(self, input_ids: torch.Tensor) -> torch.Tensor: + batch = get_global_ctx().batch + ids = input_ids if batch.mm_embeds is None else input_ids.clamp(max=self.embed_tokens.num_embeddings - 1) + x = self.embed_tokens.forward(ids) + x = rms_norm(x, self.embed_norm, self._args.rms_norm_eps).to(x.dtype) + if batch.mm_embeds is not None: + # the image features replace the normalized token embeddings, as in the reference + x.index_copy_(0, batch.mm_rows, batch.mm_embeds[:, : x.shape[1]].to(x.dtype)) + return x + + def forward(self, input_ids: torch.Tensor) -> torch.Tensor: + args = self._args + batch = get_global_ctx().batch + meta = build_conv_metadata(batch, args.conv_kernel, input_ids.device) + features = batch.features + wanted = features.wanted_layers if features is not None else frozenset() + layers = self.layers.op_list + + def run(layer_id: int, pass_idx: int, h, blocks, messages=None): + layer = layers[layer_id] + out = layer.forward(h, blocks, messages, args.cache_layer(layer_id, pass_idx), meta) + if layer.is_block_boundary: + blocks = blocks + [normalized(h)] + access = args.access(layer_id, pass_idx) + if access in wanted: + features.layer_output(access, out) + return out, blocks + + h = self.embed(input_ids) + blocks: List[torch.Tensor] = [] + for i in range(args.loop_start): + h, blocks = run(i, 0, h, blocks) + pre_h, pre_blocks = h, blocks + for i in range(args.loop_start, args.loop_end): + h, blocks = run(i, 0, h, blocks) + for p in range(1, args.num_passes): + # the previous pass's states: the blocks it closed after the first loop boundary, then its running sum + previous = blocks[len(pre_blocks) + 1 :] + [normalized(h)] + h, blocks = pre_h, pre_blocks + for j, i in enumerate(range(args.loop_start, args.loop_end)): + messages = depth_attention(previous, self.message_queries[j]) + h, blocks = run(i, p, h, blocks, messages) + for i in range(args.loop_end, args.num_layers): + h, blocks = run(i, 0, h, blocks) + out = depth_attention(blocks + [normalized(h)], self.final_query)[:, 0] + return rms_norm(out, self.norm, args.rms_norm_eps).to(h.dtype) + + +class Inkling2LoopForCausalLM(BaseLLMModel): + def __init__(self, config: ModelConfig): + args: Inkling2LoopArgs = config.inkling2_args + self.model = Inkling2LoopModel(config) + # the checkpoint pads the unembedding past the tokenizer; those rows never sample + self.lm_head = ParallelLMHead( + num_embeddings=config.vocab_size, embedding_dim=args.hidden_size, quant_config=config.quant, prefix="lm_head" + ) + self._softcap = config.final_logit_softcapping + self._unpadded = args.unpadded_vocab_size + # the offload prefill streams experts in this order: each MoE layer is keyed by its weight layer + self.moe_layer_order = tuple(layer for layer, _ in args.schedule()) + super().__init__() + + @nvtx_annotate("Inkling2Loop") + def forward(self) -> torch.Tensor: + h = self.model.forward(get_global_ctx().batch.input_ids) + logits = self.lm_head.forward(h).float() + logits = torch.tanh(logits / self._softcap) * self._softcap + logits[:, self._unpadded :] = float("-inf") + return logits + + +class Inkling2LoopForConditionalGeneration(Inkling2LoopForCausalLM): + """Text decoder plus the vision tower (``visual``); the tower's features replace the image-token embeddings.""" + + def __init__(self, config: ModelConfig): + super().__init__(config) + if config.is_multimodal: + from .vision import Inkling2VisionModel + + # state-dict names visual.*, the checkpoint's model.visual.* (weight.iter_weights renames) + self.visual = Inkling2VisionModel(config.vision_config) + + def place_encoder_weights(self, mode: str) -> None: + self.visual.place_weights(mode) + + def encode(self, item: MMItem) -> torch.Tensor: + """``[rows * cols, hidden]`` image features, one per image token (``item.grid_thw`` is ``[1, rows, cols]``).""" + feature = item.feature.to(self.visual.proj_in.weight.device, non_blocking=True) + return self.visual.forward(feature, item.grid_thw) + + +__all__ = [ + "Inkling2DecoderLayer", + "Inkling2LoopForCausalLM", + "Inkling2LoopForConditionalGeneration", + "Inkling2LoopModel", + "MessageGate", + "depth_attention", + "rms_norm", +] diff --git a/python/freetoken/models/inkling2_loop/moe.py b/python/freetoken/models/inkling2_loop/moe.py new file mode 100644 index 0000000000..43d590057b --- /dev/null +++ b/python/freetoken/models/inkling2_loop/moe.py @@ -0,0 +1,50 @@ +"""Inkling 2 sparse MoE: fp32 sigmoid router with a selection bias, top-k weights renormalized and scaled by +``route_scale``, no shared expert, softcapped SwiGLU experts behind FreeToken's MoE layer (resident or offload).""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch +import torch.nn.functional as F + +from freetoken.layers import BaseOP, make_moe_layer +from freetoken.utils import nvtx_annotate + +if TYPE_CHECKING: + from freetoken.models.config import ModelConfig + + +def route(x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor, top_k: int, scale: float) -> tuple[torch.Tensor, torch.Tensor]: + """``(topk_weights fp32, topk_ids int32)``: sigmoid scores pick by ``score + bias``, weigh by ``score``.""" + scores = torch.sigmoid(F.linear(x.float(), weight)) + ids = torch.topk(scores + bias, top_k, dim=-1, sorted=False).indices + w = scores.gather(1, ids) + w = w / (w.sum(dim=-1, keepdim=True) + 1e-20) * scale + return w, ids.to(torch.int32) + + +class Inkling2MoE(BaseOP): + def __init__(self, config: ModelConfig, layer_id: int, *, prefix: str = ""): + args = config.inkling2_args + self.gate_weight = torch.empty(config.num_experts, config.hidden_size, dtype=torch.float32) + self.gate_bias = torch.empty(config.num_experts, dtype=torch.float32) + self._top_k = config.num_experts_per_tok + self._scale = args.route_scale + self.experts = make_moe_layer( + config, + layer_id=layer_id, + activation="swiglu_softcap", + alpha=args.gate_softcap, + limit=args.up_softcap, + quant_config=config.quant, + prefix=f"{prefix}.experts", + ) + + @nvtx_annotate("MoE") + def forward(self, x: torch.Tensor) -> torch.Tensor: + w, ids = route(x, self.gate_weight, self.gate_bias, self._top_k, self._scale) + return self.experts.routed_forward(x, w, ids) + + +__all__ = ["Inkling2MoE", "route"] diff --git a/python/freetoken/models/inkling2_loop/vision.py b/python/freetoken/models/inkling2_loop/vision.py new file mode 100644 index 0000000000..1333a6faf7 --- /dev/null +++ b/python/freetoken/models/inkling2_loop/vision.py @@ -0,0 +1,246 @@ +"""Inkling 2 vision tower: a pre-LayerNorm ViT over 20-pixel patches with a class token, a bilinearly resampled +32x32 position table, axial 2-D rope and layer scale, then a 2x2 patch merge MLP into the text width. + +Attribute paths follow the checkpoint under ``model.visual`` (``backbone.layers.N.ls_1.gamma``, ``proj_in``), so +its tensors load by name. The math follows transformers' Inkling2VisionModel, including where it computes in fp32. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, List + +import torch +import torch.nn.functional as F + +from freetoken.layers import BaseOP, LayerNorm, LinearReplicated, OPList +from freetoken.models.weight_stream import BlockWeightStreamer + + +@dataclass(frozen=True) +class VisionConfig: + hidden_size: int + num_layers: int + num_heads: int + intermediate_size: int + num_channels: int + patch_size: int + merge_size: int + posemb_grid_size: int + layer_norm_eps: float + rope_theta: float + projection_hidden_dim: int + projector_bias: bool + text_hidden_size: int + + +def _first(section: Any, *names: str, default: Any = None) -> Any: + for name in names: + value = getattr(section, name, None) + if value is not None: + return value + return default + + +def parse_vision_config(hf_config: Any) -> VisionConfig | None: + """None when the checkpoint carries no vision section. Reads both the raw config.json names + (native_patch_size, adapter_merge_size, mlp_ratio) and the transformers config class names.""" + vc = getattr(hf_config, "vision_config", None) + if vc is None: + return None + act = _first(vc, "hidden_act", default="gelu") + if act != "gelu": + raise NotImplementedError(f"inkling2 vision tower activation {act!r}; only gelu is implemented") + rope = _first(vc, "rope_parameters", default=None) or {} + hidden = int(vc.hidden_size) + return VisionConfig( + hidden_size=hidden, + num_layers=int(vc.num_hidden_layers), + num_heads=int(vc.num_attention_heads), + intermediate_size=int(_first(vc, "intermediate_size", default=None) or hidden * float(_first(vc, "mlp_ratio", default=4.0))), + num_channels=int(_first(vc, "num_channels", default=3)), + patch_size=int(_first(vc, "patch_size", "native_patch_size")), + merge_size=int(_first(vc, "spatial_merge_size", "adapter_merge_size")), + posemb_grid_size=int(_first(vc, "posemb_grid_size", default=32)), + layer_norm_eps=float(_first(vc, "layer_norm_eps", default=1e-5)), + # the config class leaves rope_theta to RotaryEmbeddingConfigMixin.default_theta + rope_theta=float(rope.get("rope_theta", 10000.0)), + projection_hidden_dim=int(_first(vc, "projection_hidden_dim", default=4096)), + projector_bias=bool(_first(vc, "projector_bias", default=False)), + text_hidden_size=int(vc.text_hidden_size), + ) + + +def patch_grid(rows: int, cols: int, merge: int) -> tuple[torch.Tensor, torch.Tensor]: + """(row, col) of every patch, in the order the processor tiles them: tokens in raster order, each token's + merge x merge patches in raster order inside it.""" + k = torch.arange(rows * cols * merge * merge) + token, inner = k // (merge * merge), k % (merge * merge) + row = (token // cols) * merge + inner // merge + col = (token % cols) * merge + inner % merge + return row, col + + +def _bilinear_taps(index: torch.Tensor, size: int, side: int) -> tuple[torch.Tensor, torch.Tensor]: + """F.interpolate(bilinear, align_corners=False) of a side-long table to size, as 2 taps and weights per index.""" + src = (index.to(torch.float32) + 0.5) * side / size - 0.5 + floor = torch.floor(src) + offsets = torch.arange(0, 2) + taps = (floor.long()[:, None] + offsets).clamp(0, side - 1) + weights = (1 - (src[:, None] - floor[:, None] - offsets).abs()).clamp(min=0) + return taps, weights + + +def position_taps(row: torch.Tensor, col: torch.Tensor, height: int, width: int, side: int) -> tuple[torch.Tensor, torch.Tensor]: + """[P, 4] indices into the flattened side x side table and their fp32 weights.""" + h_taps, h_weights = _bilinear_taps(row, height, side) + w_taps, w_weights = _bilinear_taps(col, width, side) + indices = (h_taps[:, :, None] * side + w_taps[:, None, :]).reshape(-1, 4) + weights = (h_weights[:, :, None] * w_weights[:, None, :]).reshape(-1, 4) + return indices, weights + + +def _rotate_pairwise(x: torch.Tensor) -> torch.Tensor: + x1, x2 = x.unflatten(-1, (-1, 2)).unbind(-1) + return torch.stack((-x2, x1), dim=-1).flatten(-2) + + +class _LayerScale(BaseOP): + def __init__(self, size: int): + self.gamma = torch.empty(size) + + forward = None + + +class Inkling2VisionEmbeddings(BaseOP): + def __init__(self, vc: VisionConfig): + self.patch_embedding = LinearReplicated(vc.num_channels * vc.patch_size**2, vc.hidden_size, has_bias=False) + self.position_embedding = torch.empty(vc.posemb_grid_size**2, vc.hidden_size) + self.class_embedding = torch.empty(vc.hidden_size) + self.cls_position_embedding = torch.empty(vc.hidden_size) + self._vc = vc + + def forward(self, pixel_values: torch.Tensor, rows: int, cols: int) -> torch.Tensor: + """[1 + patches, hidden]: the class token, then the patches in processor order.""" + vc = self._vc + m, p = vc.merge_size, vc.patch_size + weight = self.patch_embedding.weight + # each token's tile -> its m x m patches, each flattened (row, col, channel) as the checkpoint's projection reads it + x = pixel_values.to(weight.device, weight.dtype).reshape(-1, m, p, m, p, vc.num_channels).transpose(2, 3) + patches = self.patch_embedding.forward(x.reshape(-1, vc.num_channels * p * p)) + row, col = patch_grid(rows, cols, m) + indices, weights = position_taps(row, col, rows * m, cols * m, vc.posemb_grid_size) + indices, weights = indices.to(weight.device), weights.to(weight.device) + # bf16 table rows times fp32 weights, summed in fp32 and rounded once, as the reference does + position = (self.position_embedding[indices] * weights[:, :, None]).sum(1) + patches = patches + position.to(patches.dtype) + cls = (self.class_embedding + self.cls_position_embedding).to(patches.dtype) + return torch.cat([cls[None], patches]) + + +class Inkling2VisionAttention(BaseOP): + def __init__(self, vc: VisionConfig): + self.num_heads = vc.num_heads + self.head_dim = vc.hidden_size // vc.num_heads + self.q_proj = LinearReplicated(vc.hidden_size, vc.hidden_size, has_bias=True) + self.k_proj = LinearReplicated(vc.hidden_size, vc.hidden_size, has_bias=True) + self.v_proj = LinearReplicated(vc.hidden_size, vc.hidden_size, has_bias=True) + self.out_proj = LinearReplicated(vc.hidden_size, vc.hidden_size, has_bias=True) + + def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: + S, H, D = x.shape[0], self.num_heads, self.head_dim + q, k, v = (proj.forward(x).view(S, H, D) for proj in (self.q_proj, self.k_proj, self.v_proj)) + # rope on interleaved channel pairs, in fp32 and rounded back + q = (q.float() * cos + _rotate_pairwise(q.float()) * sin).to(x.dtype) + k = (k.float() * cos + _rotate_pairwise(k.float()) * sin).to(x.dtype) + # the fused SDPA kernels want a batch dim; 3-D inputs fall back to the O(S^2) math path + q, k, v = (t.transpose(0, 1).unsqueeze(0) for t in (q, k, v)) + o = F.scaled_dot_product_attention(q, k, v, scale=D**-0.5) + return self.out_proj.forward(o[0].transpose(0, 1).reshape(S, H * D)) + + +class Inkling2VisionMLP(BaseOP): + def __init__(self, vc: VisionConfig): + self.c_fc = LinearReplicated(vc.hidden_size, vc.intermediate_size, has_bias=True) + self.c_proj = LinearReplicated(vc.intermediate_size, vc.hidden_size, has_bias=True) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.c_proj.forward(F.gelu(self.c_fc.forward(x))) + + +class Inkling2VisionLayer(BaseOP): + def __init__(self, vc: VisionConfig): + self.ln_1 = LayerNorm(vc.hidden_size, vc.layer_norm_eps) + self.self_attn = Inkling2VisionAttention(vc) + self.ls_1 = _LayerScale(vc.hidden_size) + self.ln_2 = LayerNorm(vc.hidden_size, vc.layer_norm_eps) + self.mlp = Inkling2VisionMLP(vc) + self.ls_2 = _LayerScale(vc.hidden_size) + + def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: + x = x + self.ls_1.gamma * self.self_attn.forward(self.ln_1.forward(x), cos, sin) + return x + self.ls_2.gamma * self.mlp.forward(self.ln_2.forward(x)) + + +class Inkling2VisionBackbone(BaseOP): + def __init__(self, vc: VisionConfig): + self.embeddings = Inkling2VisionEmbeddings(vc) + self.ln_pre = LayerNorm(vc.hidden_size, vc.layer_norm_eps) + self.layers = OPList([Inkling2VisionLayer(vc) for _ in range(vc.num_layers)]) + + forward = None + + +class Inkling2VisionModel(BaseOP): + """Tiles of one image ([rows * cols, tile, tile, 3], as the processor emits them) -> [rows * cols, text_hidden].""" + + def __init__(self, vc: VisionConfig): + self.backbone = Inkling2VisionBackbone(vc) + self.proj_in = LinearReplicated(vc.merge_size**2 * vc.hidden_size, vc.projection_hidden_dim, has_bias=vc.projector_bias) + self.proj_out = LinearReplicated(vc.projection_hidden_dim, vc.text_hidden_size, has_bias=vc.projector_bias) + head_dim = vc.hidden_size // vc.num_heads + # one rope band per axis over head_dim / 2 channels, built on the CPU as the reference builds it + band = torch.arange(0, head_dim // 2, 2, dtype=torch.float32, device="cpu") / (head_dim // 2) + self._inv_freq = 1.0 / (vc.rope_theta ** band) + self._vc = vc + self._streamer: BlockWeightStreamer | None = None + + def place_weights(self, mode: str) -> None: + """gpu: every tensor resident; host: the layer tensors in pinned banks streamed two layers at a time.""" + layers = self.backbone.layers.op_list + if mode == "host" and self._streamer is None: + self._streamer = BlockWeightStreamer(layers, self.proj_in.weight.device) + elif mode == "gpu" and self._streamer is not None: + self._streamer.unstream() + self._streamer = None + elif mode not in ("gpu", "host"): + raise ValueError(f"unknown vision weight placement {mode!r}") + + def _layers(self): + layers = self.backbone.layers.op_list + return enumerate(layers) if self._streamer is None else self._streamer.blocks(layers) + + def _rope(self, rows: int, cols: int, device: torch.device) -> tuple[torch.Tensor, torch.Tensor]: + """[1 + patches, 1, head_dim] cos and sin: patches at their 1-based (row, col), the class token at (0, 0).""" + row, col = patch_grid(rows, cols, self._vc.merge_size) + pos = torch.cat([torch.zeros(1, 2, dtype=torch.long), torch.stack([row, col], -1) + 1]).to(device) + freqs = pos[..., None].float() * self._inv_freq.to(device) + cos, sin = (torch.cat([f[:, 1], f[:, 0]], -1).repeat_interleave(2, -1)[:, None] for f in (freqs.cos(), freqs.sin())) + return cos, sin + + @torch.inference_mode() + def forward(self, pixel_values: torch.Tensor, grid_thw: List[int]) -> torch.Tensor: + t, rows, cols = grid_thw + if t != 1: + raise ValueError("inkling2 vision takes images only (grid t == 1)") + x = self.backbone.embeddings.forward(pixel_values, rows, cols) + x = self.backbone.ln_pre.forward(x) + cos, sin = self._rope(rows, cols, x.device) + for _, layer in self._layers(): + x = layer.forward(x, cos, sin) + # drop the class token; each run of merge^2 patches is one text token + merged = x[1:].reshape(rows * cols, -1) + return self.proj_out.forward(F.gelu(self.proj_in.forward(merged))) + + +__all__ = ["Inkling2VisionModel", "VisionConfig", "parse_vision_config", "patch_grid", "position_taps"] diff --git a/python/freetoken/models/inkling2_loop/weight.py b/python/freetoken/models/inkling2_loop/weight.py new file mode 100644 index 0000000000..6d3044a0e5 --- /dev/null +++ b/python/freetoken/models/inkling2_loop/weight.py @@ -0,0 +1,248 @@ +"""Inkling 2 Mini checkpoint reader: the original ``model.llm.*`` names, renamed to the FreeToken modules. + +Routed experts are stacked per layer (``mlp.experts.w13_weight`` [E, 2I, ...] with gate and up rows +interleaved, ``w2_weight`` [E, H, ...]). NVFP4 layers carry fp8 block scales and a per-expert global scale +``w*_weight_amax / w*_weight_outer_scale_denominator``; MXFP8 layers carry one e8m0 code per 32 inputs of a row. +Both are served as stored, with gate and up de-interleaved. +""" + +from __future__ import annotations + +import re +from typing import Collection, Iterator + +import torch + +from freetoken.layers.quantization import QuantKind + +_LLM = "model.llm." +_VISUAL = "model.visual." +_LAYER = re.compile(r"^layers\.(\d+)\.(.+)$") +_EXPERT = re.compile(r"^model\.llm\.layers\.(\d+)\.mlp\.experts\.(w13|w2)_weight(?:_(scale|amax|outer_scale_denominator))?$") +_E2M1 = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0) + +# layer-relative checkpoint suffix -> FreeToken suffix, for tensors that only change name +_LAYER_RENAMES = { + "attn_norm.weight": "input_layernorm", + "q_input_norm.weight": "q_input_layernorm", + "k_input_norm.weight": "k_input_layernorm", + "v_input_norm.weight": "v_input_layernorm", + "mlp_norm.weight": "post_attention_layernorm", + "attn.wq_du.weight": "self_attn.q_proj.weight", + "attn.wk_dv.weight": "self_attn.k_proj.weight", + "attn.wv_dv.weight": "self_attn.v_proj.weight", + "attn.wo_ud.weight": "self_attn.o_proj.weight", + "attn.wr_du.weight": "self_attn.rel_proj.weight", + "attn.gate_attn.weight": "self_attn.gate_proj.weight", + "attn.attn_sink_proj.weight": "self_attn.sink_proj.weight", + "attn.q_l2_clip.scale": "self_attn.q_scale", + "attn.rel_l2_clip.scale": "self_attn.rel_scale", + "attn.rel_logits_proj.proj": "self_attn.rel_table", + "attn.k_sconv.static_w": "self_attn.k_conv", + "attn.v_sconv.static_w": "self_attn.v_conv", + "attn.k_sconv.weight_proj": "self_attn.k_conv_proj.weight", + "attn.v_sconv.weight_proj": "self_attn.v_conv_proj.weight", + "mlp.gate.weight": "mlp.gate_weight", + "mlp.gate.bias": "mlp.gate_bias", +} +# static depthwise convolutions are stored as conv1d [C, 1, K] weights (cross-correlation): taps by lag are the flip +_CONV_RENAMES = { + "attn.k_sconv.weight": "self_attn.k_conv", + "attn.v_sconv.weight": "self_attn.v_conv", + "attn_sconv.weight": "attn_conv", + "mlp_sconv.weight": "mlp_conv", +} +_GATES = {"attn": "q_message_gate", "k": "k_message_gate", "v": "v_message_gate", "mlp": "mlp_message_gate"} +_GATE_LEAVES = {"down_weight": "down_proj.weight", "forget_weight": "forget_proj", "gain_weight": "message_proj"} + + +def _conv_taps(weight: torch.Tensor) -> torch.Tensor: + """conv1d [C, 1, K] -> [K, C] taps by lag (row 0 weights the current token).""" + return weight[:, 0, :].flip(-1).t().contiguous() + + +def rename(raw: str, tensor: torch.Tensor) -> tuple[str, torch.Tensor] | None: + """One text-tower tensor in FreeToken naming, or None for the experts and the message queries (merged elsewhere).""" + if raw == "model.llm.unembed.weight": + return "lm_head.weight", tensor + if not raw.startswith(_LLM): + return None + name = raw[len(_LLM):] + simple = {"embed.weight": "model.embed_tokens.weight", "embed_norm.weight": "model.embed_norm", "norm.weight": "model.norm"} + if name in simple: + return simple[name], tensor + if name == "attn_res.output_query": + return "model.final_query", tensor.view(1, -1) + if m := re.fullmatch(r"attn_res\.attn_queries\.(\d+)", name): + # the attention queries start at layer 1: layer 0 reads the embeddings directly + return f"model.layers.{int(m.group(1)) + 1}.attention_query", tensor.view(-1, tensor.shape[-1]) + if m := re.fullmatch(r"attn_res\.mlp_queries\.(\d+)", name): + return f"model.layers.{m.group(1)}.mlp_query", tensor.view(1, -1) + m = _LAYER.match(name) + if m is None: + return None + layer, leaf = m.group(1), m.group(2) + prefix = f"model.layers.{layer}." + if leaf in _LAYER_RENAMES: + return prefix + _LAYER_RENAMES[leaf], tensor + if leaf in _CONV_RENAMES: + return prefix + _CONV_RENAMES[leaf], _conv_taps(tensor) + if gm := re.fullmatch(r"controllers\.(attn|k|v|mlp)\.(down_weight|forget_weight|gain_weight)", leaf): + return f"{prefix}{_GATES[gm.group(1)]}.{_GATE_LEAVES[gm.group(2)]}", tensor + if leaf.startswith("mlp.experts."): + return None + raise ValueError(f"unexpected Inkling 2 tensor {raw}") + + +def merge_message_queries(queries: torch.Tensor, kv_queries: torch.Tensor) -> torch.Tensor: + """The two [2 * loop layers, H] checkpoint tensors ([query, mlp] and [key, value] per loop layer) -> [loop layers, 4, H] (q, k, v, mlp).""" + q = queries.unflatten(0, (-1, 2)) + kv = kv_queries.unflatten(0, (-1, 2)) + return torch.cat([q[:, :1], kv, q[:, 1:]], dim=1).contiguous() + + +def iter_weights( + model_path: str, + device: torch.device, + *, + include_moe_experts: bool, + include_non_moe: bool, + include_vision: bool = False, +) -> Iterator[tuple[str, torch.Tensor]]: + import safetensors + + from freetoken.distributed import get_tp_info + from freetoken.models.loader import iter_weight_files + + if get_tp_info().size > 1: + raise NotImplementedError("Inkling 2 Mini weight loading supports TP=1 only") + if include_moe_experts: + raise NotImplementedError("Inkling 2 experts load as expert banks (iter_expert_pieces), not as dense weights") + if not include_non_moe: + return + queries: dict[str, torch.Tensor] = {} + for file in iter_weight_files(model_path): + with safetensors.safe_open(file, framework="pt", device=str(device)) as f: + for raw in f.keys(): + if raw.startswith(_VISUAL): + if include_vision: + yield "visual." + raw[len(_VISUAL):], f.get_tensor(raw) + continue + if _EXPERT.match(raw): + continue + if raw.endswith(("middle_cycle_cross_pass_queries", "middle_cycle_cross_pass_kv_queries")): + queries[raw.rsplit(".", 1)[-1]] = f.get_tensor(raw) + continue + out = rename(raw, f.get_tensor(raw)) + if out is not None: + yield out + if set(queries) != {"middle_cycle_cross_pass_queries", "middle_cycle_cross_pass_kv_queries"}: + raise ValueError(f"{model_path}: missing the loop message queries (found {sorted(queries)})") + yield "model.message_queries", merge_message_queries( + queries["middle_cycle_cross_pass_queries"], queries["middle_cycle_cross_pass_kv_queries"] + ) + + +def iter_vision_weights(model_path: str, device: torch.device) -> Iterator[tuple[str, torch.Tensor]]: + """The vision tower alone, named as iter_weights names it.""" + import safetensors + + from freetoken.models.loader import iter_weight_files + + for file in iter_weight_files(model_path): + with safetensors.safe_open(file, framework="pt", device=str(device)) as f: + for raw in f.keys(): + if raw.startswith(_VISUAL): + yield "visual." + raw[len(_VISUAL):], f.get_tensor(raw) + + +def deinterleave_rows(t: torch.Tensor) -> torch.Tensor: + """[E, 2I, ...] with gate and up rows alternating -> [gate rows; up rows].""" + raw = t.view(torch.uint8) if t.element_size() == 1 else t + return torch.cat([raw[:, 0::2], raw[:, 1::2]], dim=1).view(t.dtype) + + +def dequant_nvfp4(packed: torch.Tensor, scale: torch.Tensor, global_scale: torch.Tensor) -> torch.Tensor: + """[E, R, C/2] e2m1 pairs (low nibble first), [E, R, C/16] fp8 scales, [E] globals -> [E, R, C] fp32.""" + lut = torch.tensor(_E2M1, dtype=torch.float32, device=packed.device) + codes = packed.to(torch.int64) + vals = torch.stack([lut[codes & 0xF], lut[codes >> 4]], dim=-1).flatten(-2) + vals = vals.unflatten(-1, (-1, 16)) * scale.float()[..., None] + return vals.flatten(-2) * global_scale.float()[:, None, None] + + +def dequant_mxfp8(weight: torch.Tensor, scale: torch.Tensor) -> torch.Tensor: + """[E, R, C] e4m3 with [E, R, C/32] e8m0 exponents -> [E, R, C] fp32.""" + vals = weight.float().unflatten(-1, (-1, 32)) * torch.exp2(scale.float() - 127)[..., None] + return vals.flatten(-2) + + +def _layer_tensors(f, layer: int) -> dict[str, torch.Tensor]: + base = f"{_LLM}layers.{layer}.mlp.experts." + return {name[len(base):]: f.get_tensor(name) for name in f.keys() if name.startswith(base)} + + +def iter_expert_pieces(model_path, config, kind: QuantKind, *, layers: Collection[int] | None = None, parallel=False, workers=8, chunk=8 << 20): + """``(layer, 0, E, {role: tensor})`` per MoE layer whose experts are served as ``kind``: NVFP4 and MXFP8 rows as + stored (gate / up de-interleaved, the NVFP4 per-expert global from amax / denominator), dequantized to bf16 for ``NONE``.""" + import safetensors + + from freetoken.models.loader import iter_weight_files + + if kind not in (QuantKind.NVFP4, QuantKind.MXFP8, QuantKind.NONE): + return None + want = set(range(config.num_moe_layers)) if layers is None else set(layers) + + def pieces(): + seen: set[int] = set() + for file in iter_weight_files(model_path): + with safetensors.safe_open(file, framework="pt", device="cpu") as f: + found = sorted({int(m.group(1)) for name in f.keys() if (m := _EXPERT.match(name))}) + for layer in found: + if layer not in want: + continue + t = _layer_tensors(f, layer) + nvfp4 = "w13_weight_amax" in t + if kind is not QuantKind.NONE and (kind is QuantKind.NVFP4) != nvfp4: + raise ValueError(f"layer {layer} experts are {'NVFP4' if nvfp4 else 'not NVFP4'}; the quant config serves them as {kind.name}") + if nvfp4: + g13 = t["w13_weight_amax"].float() / t["w13_weight_outer_scale_denominator"].float() + g2 = t["w2_weight_amax"].float() / t["w2_weight_outer_scale_denominator"].float() + if kind is QuantKind.NVFP4: + piece = { + "gate_up": deinterleave_rows(t["w13_weight"]), + "gate_up_scale": deinterleave_rows(t["w13_weight_scale"]), + "gate_up_global": g13.view(-1, 1), + "down": t["w2_weight"], + "down_scale": t["w2_weight_scale"], + "down_global": g2.view(-1, 1), + } + else: + piece = { + "gate_up": deinterleave_rows(dequant_nvfp4(t["w13_weight"], t["w13_weight_scale"], g13)).to(torch.bfloat16), + "down": dequant_nvfp4(t["w2_weight"], t["w2_weight_scale"], g2).to(torch.bfloat16), + } + else: + if t["w13_weight"].dtype != torch.float8_e4m3fn: + raise ValueError(f"layer {layer} experts are neither NVFP4 nor MXFP8 ({t['w13_weight'].dtype})") + if kind is QuantKind.MXFP8: + piece = { + "gate_up": deinterleave_rows(t["w13_weight"]), + "gate_up_scale": deinterleave_rows(t["w13_weight_scale"]), + "down": t["w2_weight"], + "down_scale": t["w2_weight_scale"], + } + else: + piece = { + "gate_up": deinterleave_rows(dequant_mxfp8(t["w13_weight"], t["w13_weight_scale"])).to(torch.bfloat16), + "down": dequant_mxfp8(t["w2_weight"], t["w2_weight_scale"]).to(torch.bfloat16), + } + seen.add(layer) + yield layer, 0, config.num_experts, piece + if missing := sorted(want - seen): + raise ValueError(f"{model_path}: no routed experts for MoE layers {missing}") + + return pieces() + + +__all__ = ["dequant_mxfp8", "dequant_nvfp4", "deinterleave_rows", "iter_expert_pieces", "iter_vision_weights", "iter_weights", "merge_message_queries", "rename"] diff --git a/python/freetoken/models/register.py b/python/freetoken/models/register.py index e7ec15683c..d73036c9b1 100644 --- a/python/freetoken/models/register.py +++ b/python/freetoken/models/register.py @@ -36,6 +36,9 @@ class ModelSpec: encoders: tuple[EncoderSpec, ...] = () # speculative method -> "module:Class" of the family's draft for it spec_drafts: tuple[tuple[str, str], ...] = () + # "module:function" building the QuantConfig when the checkpoint's quantization_config does not describe its tensors; + # called as function(model_path, hf_config, name_map=, unquantized=) + quant_config: str | None = None # Multimodal wrappers store the text tower under model.language_model. @@ -110,6 +113,9 @@ def _gemma4_vision_unserved(section: Any) -> str | None: _DSV4_PROCESSOR = "freetoken.mm.processors.deepseek_v4:DSV4MMProcessor" _DSV4_ENCODERS = (EncoderSpec("vision", "vision_n_layers", ("image",)),) +# Inkling 2 Mini keeps the original checkpoint names (model.llm.*); hf_quant_config.json lists each format's tensors. +_INKLING2_LOOP_ROOTS = (("model", "model.llm"), ("lm_head", "model.llm.unembed")) + _MODEL_REGISTRY: dict[str, ModelSpec] = { "FlintGGUFForCausalLM": ModelSpec( "freetoken.models.flint", "FlintForCausalLM", @@ -564,6 +570,19 @@ def _gemma4_vision_unserved(section: Any) -> str | None: # dynamic quants (unsloth UD); the reader dequantizes and fuses them into the dense module unquantized_modules=("*.self_attn.kv_b_proj",), ), + # Inkling 2 Mini (model_type inkling2_loop): 24 decoder layers, layers 6-17 run three times with their own + # KV and convolution state per pass; relative-bias attention with sinks, short convolutions, block attention + # residuals, sigmoid-routed experts (NVFP4 on layers 0-19, MXFP8 on 20-23); the ViT + # tower under model.visual serves image input. + "Inkling2LoopForConditionalGeneration": ModelSpec( + "freetoken.models.inkling2_loop", + "Inkling2LoopForConditionalGeneration", + checkpoint_roots=_INKLING2_LOOP_ROOTS, + quant_config="freetoken.models.inkling2_loop.config:quant_config", + mm_processor="freetoken.mm.processors.inkling2:Inkling2MMProcessor", + encoders=(EncoderSpec("vision", "vision_config", ("image",)),), + spec_drafts=(("dspark_mtp", "freetoken.models.inkling2_loop.dspark:Inkling2DSparkDraft"),), + ), } @@ -594,6 +613,9 @@ def checkpoint_quant_config( types = {name: info.ggml_type for name, info in gguf_tensor_index(hf_config.model_path).items()} quant = GGUFConfig(types, to_gguf, name_map=name_map, unquantized=spec.unquantized_modules) + elif spec.quant_config is not None: + build = _load_attr(*spec.quant_config.split(":")) + quant = build(model_path, hf_config, name_map=name_map, unquantized=spec.unquantized_modules) else: quant = QuantConfig.from_hf(hf_config, name_map=name_map, unquantized=spec.unquantized_modules) return quant.with_online(QuantKind(online), online_modules) if online else quant diff --git a/python/freetoken/moe/cpu_executor.py b/python/freetoken/moe/cpu_executor.py index a168256678..10b14d11f4 100644 --- a/python/freetoken/moe/cpu_executor.py +++ b/python/freetoken/moe/cpu_executor.py @@ -65,6 +65,7 @@ "gpt_oss_swiglu": 3, "swigluoai": 3, "swiglu_clamp": 4, + "swiglu_softcap": 5, } @@ -208,6 +209,9 @@ def __init__( raise NotImplementedError(f"CPU MoE backend: unsupported activation {activation!r}") if apply_router_weight_on_input and (output_only := {"mxfp4_triton", "ds_fp4"} & set(names)): raise NotImplementedError(f"CPU MoE backend: {sorted(output_only)} experts apply the router weight on the output only") + # these kernels fuse their own activation and never read the act id + if activation == "swiglu_softcap" and (fixed := {"mxfp4_triton", "ds_fp4"} & set(names)): + raise NotImplementedError(f"CPU MoE backend: {sorted(fixed)} experts have no swiglu_softcap epilogue") # ABI probe: a stale prebuilt _cpu_moe.so accepts newer act ids without # error and silently computes the wrong activation in the generic # epilogue -- fail loudly with the rebuild instruction instead. (mxfp4 diff --git a/python/freetoken/moe/expert_banks.py b/python/freetoken/moe/expert_banks.py index 197dbb9b04..59eee3e7f8 100644 --- a/python/freetoken/moe/expert_banks.py +++ b/python/freetoken/moe/expert_banks.py @@ -214,7 +214,7 @@ def merge_expert_banks(parts: list[ExpertBanks], layer_methods, num_experts: int ) -def _mixed_expert_banks(model_path, model_config, layer_methods, device, dummy, parallel, workers, chunk, layer_sink=None) -> ExpertBanks: +def _mixed_expert_banks(model_path, model_config, layer_methods, device, dummy, parallel, workers, chunk, layer_sink=None, resident=False) -> ExpertBanks: from freetoken.moe.expert_pieces import iter_expert_pieces num_layers = model_config.num_moe_layers @@ -230,7 +230,7 @@ def _mixed_expert_banks(model_path, model_config, layer_methods, device, dummy, parts = [] for (method, layers), pieces in zip(groups, readers): parts.append(build_expert_banks( - method, num_layers, pieces, device=device, layer_sink=layer_sink, dummy=dummy, layers=layers, + method, num_layers, pieces, device=device, layer_sink=layer_sink, dummy=dummy, resident=resident, layers=layers, )) logger.info_rank0(f"expert banks: {method.kind} / {method.kernel.name} on {len(layers)} of {num_layers} MoE layers") return merge_expert_banks(parts, layer_methods, model_config.num_experts) @@ -370,8 +370,8 @@ def load_expert_banks( from freetoken.checkpoint.ftw import is_ftw_checkpoint, load_ftw_banks, load_ftw_banks_to_device mixed = is_mixed(layer_methods) - if mixed and (resident or layer_residency is not None): - raise ValueError("experts of several formats are served from the offload slot cache only (no resident experts, no --moe-cpu-layers)") + if mixed and layer_residency is not None: + raise ValueError("experts of several formats do not combine with --moe-cpu-layers") if resident: assert method is not None and layer_sink is None and layer_residency is None if model_path and is_ftw_checkpoint(model_path) and not dummy: @@ -418,7 +418,7 @@ def load_expert_banks( def _build(par: bool) -> ExpertBanks: if mixed: - return _mixed_expert_banks(model_path, model_config, layer_methods, device, dummy, par, workers, chunk, layer_sink) + return _mixed_expert_banks(model_path, model_config, layer_methods, device, dummy, par, workers, chunk, layer_sink, resident) if method is not None and method.kind is QuantKind.GGUF: from freetoken.models.gguf.experts import load_gguf_expert_banks @@ -513,11 +513,13 @@ def attach_resident_banks(layers, banks: ExpertBanks) -> None: num_layers = len(next(iter(banks.sources.values()))) if ids != list(range(num_layers)) or len(ids) != len(layers): raise ValueError(f"resident MoE layer ids {ids} do not cover the {num_layers} expert bank layers") + mixed = banks.layer_formats is not None for layer in layers: i, e = layer.layer_id, layer.num_experts layout = layer.quant_method.layout() rows = {role: (e, *spec.shape) for role, spec in layout.items() if not spec.resident} - if set(banks.sources) != set(rows): + # experts of several formats: the banks are the union of the formats' roles, each layer reads its own + if (not set(rows) <= set(banks.sources)) if mixed else set(banks.sources) != set(rows): raise ValueError(f"expert banks hold {sorted(banks.sources)}, the {layer.quant_method.kernel.name} kernel reads {sorted(rows)}") for role, shape in rows.items(): bank = banks.sources[role][i] @@ -533,5 +535,5 @@ def attach_resident_banks(layers, banks: ExpertBanks) -> None: if a is None or a.numel() != num_layers * e or a.dtype != layout[role].dtype: raise ValueError(f"the {layer.quant_method.kernel.name} kernel needs {num_layers * e} {layout[role].dtype} {role} values, the expert banks carry {None if a is None else (a.numel(), a.dtype)}") alphas.append(a) - layer._expert_banks = {role: per_layer[i] for role, per_layer in banks.sources.items()} + layer._expert_banks = {role: banks.sources[role][i] for role in rows} layer._expert_alphas = tuple(a[i * e : (i + 1) * e] for a in alphas) or None diff --git a/python/freetoken/moe/offload_cache.py b/python/freetoken/moe/offload_cache.py index 84c2deb7b4..bfbf87c0d0 100644 --- a/python/freetoken/moe/offload_cache.py +++ b/python/freetoken/moe/offload_cache.py @@ -174,8 +174,12 @@ class OffloadMoeCache: # Each layer belongs to one pool: a contiguous slot range with its own LRU scope; pool p owns slots [sum(pool_sizes[:p]), +pool_sizes[p]). Slot ids in slot_for_id are local to the pool. None = one pool for all layers. pool_of_layer: list[int] | None = None pool_sizes: list[int] | None = None + # MoE layers in the order one forward runs them, when that is not 0..num_layers-1 once each (looped models run + # some layers several times); the overlap prefill prefetches the next entry. None = ascending, each once. + layer_order: tuple[int, ...] | None = None def __post_init__(self) -> None: + self._prefill_cursor = 0 policy_ids = {"lru": 0} assert self.cache_policy in policy_ids assert self.decode_target in ("gpu", "cpu", "hybrid"), self.decode_target @@ -863,7 +867,50 @@ def _invalidate_prefill_buffer(self, buffer_id: int, layer_id: int) -> None: for tail in self._stage_tails[self.layer_layout[layer_id]][buffer_id]: tail.zero_() + def set_layer_order(self, order) -> None: + """Declare the order one forward runs its MoE layers in (None: ascending, each once). The first entry runs once, + because its call is what marks a new forward.""" + if order is not None: + order = tuple(int(layer) for layer in order) + if not order or not all(0 <= layer < self.num_layers for layer in order): + raise ValueError(f"MoE layer order {order} is empty or leaves [0, {self.num_layers})") + if order.count(order[0]) != 1: + raise ValueError(f"MoE layer order starts with layer {order[0]} and runs it again; its call has to mark a new forward") + self.layer_order = order + self._prefill_cursor = 0 + + def start_prefill_call(self, layer_id: int) -> None: + """Every prefill MoE call enters here; the forward's first call restarts the order cursor and the overlap buffers, + so a forward that stopped midway (an OOM) leaves nothing behind for the next one.""" + if layer_id == (self.layer_order[0] if self.layer_order is not None else 0): + self.begin_prefill() + + def prefill_step(self, layer_id: int) -> int: + """This call's position in the forward: its index in ``layer_order``, else the layer id. Its parity picks the overlap buffer.""" + if self.layer_order is None: + return layer_id + cursor = self._prefill_cursor + assert self.layer_order[cursor] == layer_id, f"MoE layer {layer_id} ran out of the declared order at step {cursor}" + return cursor + + def next_prefill_layer(self, layer_id: int) -> int: + """The MoE layer the forward runs after this call of ``layer_id`` (``num_layers`` after the last).""" + if self.layer_order is None: + return layer_id + 1 + cursor = self.prefill_step(layer_id) + return self.layer_order[cursor + 1] if cursor + 1 < len(self.layer_order) else self.num_layers + + def _ends_prefill_forward(self, layer_id: int) -> bool: + """Whether this released call of ``layer_id`` is the forward's last MoE call; steps the ``layer_order`` cursor, which wraps for the next forward.""" + if self.layer_order is None: + return layer_id == self.num_layers - 1 + cursor = self.prefill_step(layer_id) + last = cursor + 1 == len(self.layer_order) + self._prefill_cursor = 0 if last else cursor + 1 + return last + def begin_prefill(self) -> None: + self._prefill_cursor = 0 if not self.prefill_overlap: return self._prefill_buffer_layer = [None, None] @@ -886,7 +933,8 @@ def begin_prefill(self) -> None: self._prefill_slot_snapshot.copy_(self.slot_for_id, non_blocking=True) self.prefill_copy_stream.synchronize() - def prefetch_prefill_layer(self, layer_id: int) -> None: + def prefetch_prefill_layer(self, layer_id: int, step: int | None = None) -> None: + """Stage ``layer_id`` in the overlap buffer of the forward's ``step`` (``prefill_step``; the layer id by default).""" if not self.prefill_overlap or layer_id >= self.num_layers: return if layer_id < 0: @@ -894,7 +942,7 @@ def prefetch_prefill_layer(self, layer_id: int) -> None: assert self.banks and self._stage_views - buffer_id = layer_id % 2 + buffer_id = (layer_id if step is None else step) % 2 if self._prefill_buffer_layer[buffer_id] == layer_id: return if self._prefill_buffer_layer[buffer_id] is not None: @@ -1041,22 +1089,23 @@ def _prefetch_split(self, layer_id: int, buffer_id: int) -> None: ) self.prefill_ready_events[buffer_id].record(self.prefill_copy_stream) - def wait_prefill_layer(self, layer_id: int) -> tuple[torch.Tensor, ...]: + def wait_prefill_layer(self, layer_id: int, step: int | None = None) -> tuple[torch.Tensor, ...]: """Full-layer ``[num_experts, ...]`` bank views for ``layer_id``, one per registered bank in registration order: bf16 ``(gate_up, down)``; nvfp4 marlin/b12x ``(gate_up_packed, gate_up_scale, down_packed, down_scale)``; nvfp4 native adds the two global banks after each scale bank.""" assert self.prefill_overlap assert self._stage_views - self.prefetch_prefill_layer(layer_id) - buffer_id = layer_id % 2 + self.prefetch_prefill_layer(layer_id, step) + buffer_id = (layer_id if step is None else step) % 2 assert self._prefill_buffer_layer[buffer_id] == layer_id if self.prefill_ready_events: torch.cuda.current_stream(self.device).wait_event(self.prefill_ready_events[buffer_id]) return self.stage_views(layer_id, buffer_id) def release_prefill_layer(self, layer_id: int) -> None: - if layer_id == self.num_layers - 1: + step = self.prefill_step(layer_id) + if self._ends_prefill_forward(layer_id): # the staged slots were invalidated and nothing registers them within the forward, so their bytes are free to clear for b in range(2): if self._stage_dirty[b]: @@ -1066,7 +1115,7 @@ def release_prefill_layer(self, layer_id: int) -> None: self._stage_dirty[b] = False if not self.prefill_overlap: return - buffer_id = layer_id % 2 + buffer_id = step % 2 if self._prefill_buffer_layer[buffer_id] != layer_id: return if self.prefill_release_events: diff --git a/python/freetoken/moe/pool_policy.py b/python/freetoken/moe/pool_policy.py index 990c18ade2..7eb819c670 100644 --- a/python/freetoken/moe/pool_policy.py +++ b/python/freetoken/moe/pool_policy.py @@ -11,6 +11,7 @@ from __future__ import annotations import json +import math from dataclasses import dataclass from pathlib import Path @@ -80,6 +81,43 @@ def split_slots(total: int, pools: list[PoolSpec], counts: torch.Tensor | None = return _split_equal(total, pools) if counts is None else _split_hot(total, pools, counts) +def pool_row_bytes(sources: dict, row_tail_bytes: dict | None, pools: list[PoolSpec]) -> tuple[list[list[int]], list[list[int]]]: + """Bytes of one slot of each pool in each bank of ``sources``, and the zeroed pad after its rows, as ``OffloadMoeCache`` lays them out.""" + from freetoken.moe.legacy_format import canonical_role + + tails = {canonical_role(name): per_layer for name, per_layer in (row_tail_bytes or {}).items()} + rows, pads = [], [] + for pool in pools: + first = pool.layers[0] + rows.append([math.prod(per_layer[first].shape[1:]) * per_layer[first].element_size() for per_layer in sources.values()]) + pads.append([ + max(-(-tails[role][layer] // 16) * 16 for layer in pool.layers) if (role := canonical_role(name)) in tails else 0 + for name in sources + ]) + return rows, pads + + +def staging_slots(row_bytes: list[list[int]], pad_bytes: list[list[int]], num_experts: int, buffers: int = 2) -> list[int]: + """Slots per pool for a cache that only backs the prefill staging (``--moe-strategy cpu``). + + ``row_bytes[p][k]`` / ``pad_bytes[p][k]`` are one slot of pool p and its pad in bank k. A staging buffer of bank k is + ``num_experts`` rows of the widest layout plus the largest pad and sits at the start of the bank's bytes, whichever + pools they belong to, so each bank must hold ``buffers`` of them; the pool with the widest rows of a short bank grows. + """ + sizes = [1] * len(row_bytes) + # banks that fewer pools fill go first: the slots they force count toward the shared banks + for k in sorted(range(len(row_bytes[0])), key=lambda k: sum(1 for rows in row_bytes if rows[k])): + widest = max(range(len(row_bytes)), key=lambda p: row_bytes[p][k]) + if row_bytes[widest][k] == 0: + continue + max_pad = max(pads[k] for pads in pad_bytes) + need = buffers * (num_experts * row_bytes[widest][k] + max_pad) + have = sum(s * rows[k] + pads[k] for s, rows, pads in zip(sizes, row_bytes, pad_bytes)) + max_pad + if have < need: + sizes[widest] += -(-(need - have) // row_bytes[widest][k]) + return sizes + + def _check_budget(total: int, pools: list[PoolSpec]) -> None: need = sum(p.min_num_slots for p in pools) room = sum(p.max_num_slots for p in pools) diff --git a/python/freetoken/server/args.py b/python/freetoken/server/args.py index 1896fe1c60..de8ccdb86e 100644 --- a/python/freetoken/server/args.py +++ b/python/freetoken/server/args.py @@ -220,6 +220,8 @@ def _infer_tool_call_parser(model_path: str) -> str: # off the checkpoint only: the HF org name ricursiveAI would match other models' paths if "ricursive" in " ".join(candidates[1:]).lower(): return "ricursive" + if "inkling2" in " ".join(candidates[1:]).lower(): + return "inkling2" if "flint" in marker: return "glm47" if "gpt_oss" in marker or "gpt-oss" in marker or "gptoss" in marker: @@ -275,6 +277,8 @@ def _infer_reasoning_parser(model_path: str) -> str | None: marker = " ".join(candidates).lower() if "ricursive" in " ".join(candidates[1:]).lower(): return "ricursive" + if "inkling2" in " ".join(candidates[1:]).lower(): + return "inkling2" if "flint" in marker: return "flint" if "gpt_oss" in marker or "gpt-oss" in marker or "gptoss" in marker: diff --git a/python/freetoken/server/function_call_parser.py b/python/freetoken/server/function_call_parser.py index a07d37c2e2..cc27e7ae9f 100644 --- a/python/freetoken/server/function_call_parser.py +++ b/python/freetoken/server/function_call_parser.py @@ -34,8 +34,13 @@ ATEM_MESSAGE, ATEM_RECIPIENT_RE, ATEM_START, + TML_END_MESSAGE, + TML_HEADER_SPAN, + TML_MESSAGE_MODEL, + TML_TOOL_JSON, atem_hold_len, atem_marker_inside, + tml_hold_len, ) try: @@ -81,6 +86,7 @@ def _should_forward_unknown_tool(name: Any) -> bool: "<|DSML| calls>", "<|DSML| invoke", "", + TML_TOOL_JSON, ] @@ -3570,6 +3576,236 @@ class DeepSeekV41Detector(DeepSeekV32Detector): param_tag = " parameter" +class Inkling2Detector(BaseFormatDetector): + """Inkling 2's TMLv0 calls, one message each, as ``chat_template.jinja`` renders them and the checkpoint's + response_template reads them: ``<|message_model|>NAME<|content_invoke_tool_json|>{"name":NAME,"args":{...}}<|end_message|>``. + + The ``args`` value streams as the raw text the model writes, so the fragments are a prefix of the final + arguments; a call whose JSON does not open with ``name`` then ``args`` is parsed whole at its end marker. + """ + + toolcall_opener = TML_TOOL_JSON + _HEAD_RE = re.compile(r'\s*\{\s*"name"\s*:\s*("(?:[^"\\]|\\.)*")\s*,\s*"args"\s*:\s*') + _CALL_RE = re.compile( + rf"(?:{re.escape(TML_MESSAGE_MODEL)}([^<]*))?{re.escape(TML_TOOL_JSON)}(.*?)(?:{re.escape(TML_END_MESSAGE)}|$)", + re.DOTALL, + ) + # a call head longer than this without the name/args prefix is parsed whole + _HEAD_SPAN = 512 + + def __init__(self): + super().__init__() + self.bot_token = TML_TOOL_JSON + self.eot_token = TML_END_MESSAGE + self.tool_call_separator = "" + self._reset() + + def _reset(self) -> None: + self._mode = "text" # text | header | head | args | tail | whole | swallow + self._header_name = "" + self._sent = 0 # chars of the args value already emitted + self._scan = 0 # chars of the args value already scanned + self._depth = 0 + self._in_str = False + self._esc = False + + def has_tool_call(self, text: str) -> bool: + return self.bot_token in text + + def _call_items(self, header_name: str, body: str, tools: List[Tool]) -> List[ToolCallItem]: + try: + obj = json.loads(body) + except (json.JSONDecodeError, ValueError): + logger.warning(f"Failed to parse Inkling 2 tool call JSON: {body!r}") + return [] + if not isinstance(obj, dict): + return [] + name = obj.get("name") or header_name.strip() + if name not in self._get_tool_indices(tools) and not _should_forward_unknown_tool(name): + logger.warning(f"Model attempted to call undefined function: {name}") + return [] + args = obj.get("args", obj.get("arguments", {})) + return [ToolCallItem(tool_index=-1, name=name, parameters=json.dumps(args, ensure_ascii=False))] + + def detect_and_parse(self, text: str, tools: List[Tool]) -> StreamingParseResult: + matches = list(self._CALL_RE.finditer(text)) + if not matches: + return StreamingParseResult(normal_text=text) + calls: List[ToolCallItem] = [] + for m in matches: + calls.extend(self._call_items(m.group(1) or "", m.group(2), tools)) + for i, call in enumerate(calls): + call.tool_index = i + return StreamingParseResult(normal_text=text[: matches[0].start()], calls=calls) + + def _value_end(self, buf: str) -> int | None: + """End of the JSON value at the start of ``buf``, or None while it is still arriving.""" + i = self._scan + while i < len(buf): + ch = buf[i] + if self._in_str: + if self._esc: + self._esc = False + elif ch == "\\": + self._esc = True + elif ch == '"': + self._in_str = False + if self._depth == 0: + return i + 1 + elif ch == '"': + self._in_str = True + elif ch in "{[": + self._depth += 1 + elif ch in "}]" and self._depth > 0: + self._depth -= 1 + if self._depth == 0: + return i + 1 + elif self._depth == 0 and i > 0 and (ch in ",}]" or ch.isspace()): + return i # a bare number, boolean or null + i += 1 + self._scan = i + return None + + def _open_call(self, name: str, tools: List[Tool], calls: List[ToolCallItem]) -> bool: + if not hasattr(self, "_tool_indices"): + self._tool_indices = self._get_tool_indices(tools) + if name not in self._tool_indices and not _should_forward_unknown_tool(name): + logger.warning(f"Model attempted to call undefined function: {name}") + return False + self.current_tool_id = max(self.current_tool_id, 0) + while len(self.prev_tool_call_arr) <= self.current_tool_id: + self.prev_tool_call_arr.append({}) + while len(self.streamed_args_for_tool) <= self.current_tool_id: + self.streamed_args_for_tool.append("") + self.prev_tool_call_arr[self.current_tool_id] = {"name": name, "arguments": {}} + calls.append(ToolCallItem(tool_index=self.current_tool_id, name=name, parameters="")) + return True + + def _emit_args(self, fragment: str, calls: List[ToolCallItem]) -> None: + if not fragment: + return + tid = self.current_tool_id + self.streamed_args_for_tool[tid] += fragment + calls.append(ToolCallItem(tool_index=tid, name=None, parameters=fragment)) + try: + parsed, _ = _partial_json_loads(self.streamed_args_for_tool[tid], Allow.ALL) + except (MalformedJSON, ValueError): + return + if isinstance(parsed, dict): + self.prev_tool_call_arr[tid]["arguments"] = parsed + + def _close_call(self) -> None: + self.current_tool_id += 1 + self._sent = self._scan = self._depth = 0 + self._in_str = self._esc = False + + def parse_streaming_increment(self, new_text: str, tools: List[Tool]) -> StreamingParseResult: + self._buffer += new_text + normal: List[str] = [] + calls: List[ToolCallItem] = [] + while self._buffer: + buf = self._buffer + if self._mode == "text": + if calls: + break # text after a call goes out on the next step, in wire order + hits = [(buf.find(tok), tok) for tok in (TML_MESSAGE_MODEL, TML_TOOL_JSON) if tok in buf] + if not hits: + hold = tml_hold_len(buf, (TML_MESSAGE_MODEL, TML_TOOL_JSON)) + normal.append(buf[: len(buf) - hold]) + self._buffer = buf[len(buf) - hold:] + break + pos, tok = min(hits) + if pos > 0: + normal.append(buf[:pos]) + self._buffer = buf[pos:] + continue + if tok == TML_MESSAGE_MODEL: + self._mode = "header" + else: + self._buffer, self._header_name, self._mode = buf[len(tok):], "", "head" + continue + + if self._mode == "header": + rest = buf[len(TML_MESSAGE_MODEL):] + lt = rest.find("<") + if lt == -1: + if len(rest) <= TML_HEADER_SPAN: + break + elif rest[lt:].startswith(TML_TOOL_JSON): + self._header_name = rest[:lt] + self._buffer, self._mode = rest[lt + len(TML_TOOL_JSON):], "head" + continue + elif TML_TOOL_JSON.startswith(rest[lt:]): + break + # another message's header: not a call, leave it to the content + cut = len(rest) if lt == -1 else lt + normal.append(TML_MESSAGE_MODEL + rest[:cut]) + self._buffer, self._mode = rest[cut:], "text" + continue + + if self._mode == "head": + m = self._HEAD_RE.match(buf) + if m is not None: + self._buffer = buf[m.end():] + self._mode = "args" if self._open_call(json.loads(m.group(1)), tools, calls) else "swallow" + continue + if TML_END_MESSAGE in buf or len(buf) > self._HEAD_SPAN: + self._mode = "whole" + continue + break + + if self._mode == "args": + if self._sent == 0 and buf[:1].isspace(): + self._buffer = buf.lstrip() + continue + end = self._value_end(buf) + if end is None: + stop = buf.find(TML_END_MESSAGE) + if stop == -1: + self._emit_args(buf[self._sent:], calls) + self._sent = len(buf) + break + # the end marker before the value closed: what streamed is all the call has + self._emit_args(buf[self._sent:stop], calls) + self._buffer, self._mode = buf[stop + len(TML_END_MESSAGE):], "text" + self._close_call() + continue + self._emit_args(buf[self._sent:end], calls) + self._buffer, self._mode = buf[end:], "tail" + self._close_call() + continue + + if self._mode == "whole": + stop = buf.find(TML_END_MESSAGE) + if stop == -1: + break + for item in self._call_items(self._header_name, buf[:stop], tools): + if self._open_call(item.name, tools, calls): + self._emit_args(item.parameters, calls) + self._close_call() + self._buffer, self._mode = buf[stop + len(TML_END_MESSAGE):], "text" + continue + + # tail (the outer brace after the args) or swallow (a call to an unknown tool): skip to the end + # marker, or to the next message when the model left this one without it + hits = [(buf.find(tok), tok) for tok in (TML_END_MESSAGE, TML_MESSAGE_MODEL) if tok in buf] + if not hits: + hold = tml_hold_len(buf, (TML_END_MESSAGE, TML_MESSAGE_MODEL)) + self._buffer = buf[len(buf) - hold:] + break + pos, tok = min(hits) + self._buffer = buf[pos + len(tok):] if tok == TML_END_MESSAGE else buf[pos:] + self._mode = "text" + return StreamingParseResult(normal_text="".join(normal), calls=calls) + + def finish_streaming(self) -> str: + residual, mode = self._buffer, self._mode + self._buffer = "" + self._reset() + # an unfinished call's markup never reaches the content + return residual if mode in ("text", "header") else "" + + class FunctionCallParser: """ Parser for function/tool calls in model outputs. @@ -3586,6 +3822,7 @@ class FunctionCallParser: "gpt-oss": GptOssDetector, "gpt_oss": GptOssDetector, "glm47": Glm47Detector, + "inkling2": Inkling2Detector, "llama3": Llama32Detector, "minimax": MiniMaxDetector, "minimax_m3": MiniMaxM3Detector, diff --git a/python/freetoken/server/generation.py b/python/freetoken/server/generation.py index 147f3dbd15..b755e75061 100644 --- a/python/freetoken/server/generation.py +++ b/python/freetoken/server/generation.py @@ -464,7 +464,7 @@ def _make_reasoning_parser(spec: GenSpec, state: Any) -> ReasoningParser | None: or bool(ctk.get("enable_thinking")) or bool(ctk.get("thinking")) ) - elif parser_name in ("flint", "ricursive"): + elif parser_name in ("flint", "ricursive", "inkling2"): # These families open their own optional think block, including when tools are present. force_reasoning = False elif parser_name == "minimax_m3": diff --git a/python/freetoken/server/reasoning_parser.py b/python/freetoken/server/reasoning_parser.py index 44ba71f284..f8192ffb18 100644 --- a/python/freetoken/server/reasoning_parser.py +++ b/python/freetoken/server/reasoning_parser.py @@ -639,6 +639,125 @@ def flush(self) -> ReasoningParseResult: return super().flush() +TML_MESSAGE_MODEL = "<|message_model|>" +TML_END_MESSAGE = "<|end_message|>" +TML_END_SAMPLING = "<|content_model_end_sampling|>" +TML_THINKING = "<|content_thinking|>" +TML_TOOL_JSON = "<|content_invoke_tool_json|>" +# content kinds the checkpoint's tokenizer_config.json response_template reads as visible text +TML_TEXT_KINDS = ("<|content_text|>", "<|content_tool_error|>", "<|content_invoke_tool_text|>") +TML_KINDS = (TML_THINKING, TML_TOOL_JSON) + TML_TEXT_KINDS +# a header is <|message_model|> plus an optional name (a tool's, for calls) up to the content marker +TML_HEADER_SPAN = 256 + + +def tml_hold_len(text: str, tokens: Tuple[str, ...]) -> int: + """Length of the longest suffix of ``text`` that is a proper prefix of one of ``tokens``.""" + return max((_partial_suffix(text, tok) for tok in tokens), default=0) + + +class Inkling2ReasoningParser(BaseReasoningParser): + """Inkling 2's TMLv0 output, as the checkpoint's ``tokenizer_config.json`` response_template reads it. + + A turn is a run of messages, each ``<|message_model|>[name]<|content_KIND|>body<|end_message|>``, closed by + ``<|content_model_end_sampling|>`` (the stop token). Thinking bodies go to reasoning; text, tool-error and + text-tool bodies go to content, unwrapped; a ``content_invoke_tool_json`` message is passed through to content + verbatim, header and end marker included, for the ``inkling2`` tool parser. The model opens its own turn and + its own thinking message, so there is nothing to force. ``chat_template.jinja`` renders an assistant turn back + in exactly this layout. + """ + + def __init__(self, force_reasoning: bool = False, stream_reasoning: bool = True) -> None: + super().__init__(think_start_token="", think_end_token="", stream_reasoning=stream_reasoning) + self._mode = "seek" # seek (between messages) | header | body + self._kind = "" + + def detect_and_parse(self, text: str) -> ReasoningParseResult: + clone = type(self)() + first = clone.parse_streaming_increment(text) + rest = clone.flush() + return ReasoningParseResult( + reasoning_text=first.reasoning_text + rest.reasoning_text, + normal_text=first.normal_text + rest.normal_text, + ) + + def parse_streaming_increment(self, new_text: str) -> ReasoningParseResult: + self._buffer += new_text + return self._drain(final=False) + + def flush(self) -> ReasoningParseResult: + return self._drain(final=True) + + def _drain(self, *, final: bool) -> ReasoningParseResult: + reasoning: List[str] = [] + content: List[str] = [] + + def emit(kind: str, piece: str) -> None: + if piece: + (reasoning if kind == TML_THINKING else content).append(piece) + + while self._buffer: + buf = self._buffer + if self._mode == "seek": + markers = (TML_MESSAGE_MODEL, TML_END_SAMPLING, TML_END_MESSAGE) + TML_KINDS + hits = [(buf.find(tok), tok) for tok in markers if tok in buf] + if not hits: + hold = 0 if final else tml_hold_len(buf, markers) + content.append(buf[: len(buf) - hold]) + self._buffer = buf[len(buf) - hold:] + break + pos, tok = min(hits) + content.append(buf[:pos]) + if tok == TML_MESSAGE_MODEL: + self._buffer, self._mode = buf[pos:], "header" + elif tok in TML_KINDS: # a message without its header + self._buffer = buf[pos + len(tok):] + self._open(tok, "", content) + else: # the stop token or a stray end marker carries nothing + self._buffer = buf[pos + len(tok):] + continue + + if self._mode == "header": + rest = buf[len(TML_MESSAGE_MODEL):] + lt = rest.find("<") + if lt == -1 and not final and len(rest) <= TML_HEADER_SPAN: + break # the name is still arriving + tail = rest[lt:] if lt != -1 else "" + kind = next((k for k in TML_KINDS if tail.startswith(k)), None) + if kind is not None: + self._buffer = tail[len(kind):] + self._open(kind, TML_MESSAGE_MODEL + rest[:lt], content) + continue + if not final and lt != -1 and any(k.startswith(tail) for k in TML_KINDS): + break # the content marker is still arriving + # no content marker follows: the bare header is protocol debris, its text stays content + self._buffer, self._mode = rest, "seek" + continue + + # body: ends at its end marker, or where the next message or the stop token starts without one + ends = (TML_END_MESSAGE, TML_MESSAGE_MODEL, TML_END_SAMPLING) + hits = [(buf.find(tok), tok) for tok in ends if tok in buf] + if not hits: + if self._kind == TML_THINKING and not self.stream_reasoning and not final: + break + hold = 0 if final else tml_hold_len(buf, ends) + emit(self._kind, buf[: len(buf) - hold]) + self._buffer = buf[len(buf) - hold:] + break + pos, tok = min(hits) + emit(self._kind, buf[:pos]) + if self._kind == TML_TOOL_JSON: + content.append(TML_END_MESSAGE) + self._buffer = buf[pos + len(tok):] if tok == TML_END_MESSAGE else buf[pos:] + self._mode = "seek" + return ReasoningParseResult(reasoning_text="".join(reasoning), normal_text="".join(content)) + + def _open(self, kind: str, header: str, content: List[str]) -> None: + self._mode, self._kind = "body", kind + if kind == TML_TOOL_JSON: + content.append(header + kind) + + class GemmaThoughtReasoningParser(BaseReasoningParser): """Reasoning parser for Gemma-4's thought channel: the model emits its thought, then a closing ```` marker, then the visible answer. The opening @@ -991,6 +1110,7 @@ class ReasoningParser: "minimax_m3": MiniMaxM3ReasoningParser, "muse_glimmer": MuseGlimmerReasoningParser, "gemma4": GemmaThoughtReasoningParser, + "inkling2": Inkling2ReasoningParser, } def __init__( diff --git a/python/freetoken/spec/__init__.py b/python/freetoken/spec/__init__.py index d2091a5a8c..ed58eaed73 100644 --- a/python/freetoken/spec/__init__.py +++ b/python/freetoken/spec/__init__.py @@ -9,6 +9,9 @@ # draft method name -> "module:Class" of the proposer it selects behind the CLI algorithm. A family # opts in through its spec_drafts, so these are not --spec-algo names and carry no user-facing validation -DRAFT_PROPOSERS = {"shared_kv_mtp": "freetoken.spec.mtp.shared_proposer:SharedKVMTPProposer"} +DRAFT_PROPOSERS = { + "shared_kv_mtp": "freetoken.spec.mtp.shared_proposer:SharedKVMTPProposer", + "dspark_mtp": "freetoken.spec.dspark.proposer:DSparkProposer", +} __all__ = ["DRAFT_PROPOSERS", "PROPOSERS"] diff --git a/python/freetoken/spec/dspark/__init__.py b/python/freetoken/spec/dspark/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/python/freetoken/spec/dspark/proposer.py b/python/freetoken/spec/dspark/proposer.py new file mode 100644 index 0000000000..fe821d333a --- /dev/null +++ b/python/freetoken/spec/dspark/proposer.py @@ -0,0 +1,244 @@ +"""DSparkProposer: drafts one block of k tokens per step with a DSpark draft over the target's tapped layer visits. A family selects it through its spec_drafts behind the mtp CLI algorithm; it is never a --spec-algo name. + +The draft's context K/V live in a pool of its own on the target's full-attention slot ids, written from the target's features of every prefill row and every verify row; context K/V of a position depend on the tokens up to it only, so a prefix-cache hit finds them where the target's KV is and no lookahead key is needed. +A verify writes every row, rejected ones included: rows past the accepted ones sit at or after the next block's start, which reads only positions below it, and the next verify rewrites them. +The Markov head's context is the features of each request's last committed token, kept per table row. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, ClassVar, List + +import torch + +from freetoken.spec.proposer import DraftContext, Proposer, SpecProposal, check_draft_path +from freetoken.utils import init_logger + +if TYPE_CHECKING: + from freetoken.core import Batch, Req + from freetoken.models.inkling2_loop.dspark import DSparkConfig, Inkling2DSparkDraft + +logger = init_logger(__name__) + +DRAFT_METHOD = "dspark_mtp" + + +def _write_taps(dst: torch.Tensor, cols: list[int], x: torch.Tensor, residual: torch.Tensor | None, hidden: int) -> None: + rows = x.shape[0] + src = x if residual is None else x + residual + for col in cols: + dst[:rows, col * hidden : (col + 1) * hidden].copy_(src) + + +class DSparkFeatureSink: + """The tapped visits' outputs and the final-norm output of every row, side by side in ``buffer [rows, taps*H]``; the column of a visit is the tap whose input it is.""" + + def __init__(self, config: DSparkConfig, buffer: torch.Tensor) -> None: + self.cols = config.output_taps() + self.wanted_layers = frozenset(self.cols) + self.final_col, self.hidden, self.buffer = config.num_taps - 1, config.hidden_size, buffer + self.got: set[int] = set() + + def final_hidden(self, x: torch.Tensor) -> None: + self.got.add(-1) + _write_taps(self.buffer, [self.final_col], x, None, self.hidden) + + def layer_output(self, layer_id: int, x: torch.Tensor, residual: torch.Tensor | None = None, num_streams: int = 1) -> None: + assert num_streams == 1, "Inkling 2 has one residual stream" + self.got.add(layer_id) + _write_taps(self.buffer, self.cols[layer_id], x, residual, self.hidden) + + +def _draft_entry(config) -> str: + drafts = dict(config.model_spec.spec_drafts) + if DRAFT_METHOD not in drafts: + raise ValueError(f"DSpark is not supported for {config.hf_config.architectures[0]}") + return drafts[DRAFT_METHOD] + + +class DSparkProposer(Proposer): + # context K/V of position i read tokens up to i only + radix_lookahead = False + # support of a sampled draft: the step's top logits, renormalized at the request's temperature + SAMPLE_TOP_K: ClassVar[int] = 64 + # request-positions of a full layer's context gathered at once: about 12 KiB each with the fp32 copies + CONTEXT_CHUNK_ROWS: ClassVar[int] = 16384 + + @classmethod + def _draft_config(cls, config) -> DSparkConfig: + from freetoken.models.inkling2_loop.dspark import parse_dspark_config + + return parse_dspark_config(config.hf_config) + + @classmethod + def num_steps(cls, config) -> tuple[int, int]: + # one forward drafts the checkpoint's whole block [anchor, mask x (block-1)]; a smaller k keeps its first drafts + k = cls._draft_config(config).block_size - 1 + return k, k + + @classmethod + def adjust_config(cls, config, override) -> None: + from freetoken.models.inkling2_loop.dspark import mtp_file + + super().adjust_config(config, override) + _draft_entry(config) + if config.speculative_token_map: + raise ValueError("--speculative-token-map does not apply to DSpark drafts, whose Markov head biases the whole vocabulary") + if config.use_dummy_weight: + raise ValueError("DSpark reads its draft from the checkpoint, so it cannot run with --dummy-weight") + path = config.speculative_draft_model_path or config.model_path + if config.speculative_draft_model_path: + check_draft_path(path) + # checked here because a draft that cannot load otherwise fails only after the whole target has loaded + mtp_file(path) + draft = cls._draft_config(config) + if config.max_seq_len > draft.max_position: + raise ValueError(f"the DSpark draft runs positions below {draft.max_position}; lower --max-seq-len-override") + + @classmethod + def budget(cls, config) -> tuple[int, int]: + c = cls._draft_config(config) + item, block = 2, config.speculative_num_steps + 1 + aux = config.max_running_req * block * c.num_taps * c.hidden_size * item + f_rnn = (config.max_running_req + 1) * c.hidden_size * item + return aux + f_rnn, 2 * c.num_layers * c.num_kv_heads * c.head_dim * item + + @classmethod + def target_may_be_windowed(cls, config) -> bool: + from freetoken.kvcache import resolve_pool_class + from freetoken.kvcache.hybrid_swa_pool import HybridSWAKVCache + + # the draft reads its own pool on the full-attention slot ids, which the window frees never release + return resolve_pool_class(config.model_config) is HybridSWAKVCache + + def __init__(self, config, target_model) -> None: + from freetoken.models.register import _load_attr + + super().__init__(config, target_model) + self.device = torch.device("cuda", torch.cuda.current_device()) if torch.cuda.is_available() else torch.device("cpu") + path = config.speculative_draft_model_path or config.model_path + self.draft_config = c = self._draft_config(config) + self.draft: Inkling2DSparkDraft = _load_attr(*_draft_entry(config).split(":")).load(c, target_model, path, self.device, config.dtype) + # rows of a request in a verify batch + self.width = self.k + 1 + self.k_cache = self.v_cache = self.aux_buf = self.f_rnn = None + self._prefill: tuple[DSparkFeatureSink, list[tuple[int, int, int]]] | None = None + logger.info_rank0( + f"speculative decoding: DSpark draft {c.num_layers} layers (local {list(c.local_layer_ids)}, window {c.window}), " + f"block {c.block_size}, {self.k} drafts per step, features of target visits {list(c.target_layer_ids)} (the last is the final norm)" + ) + + # ------------------------------------------------------------------ lifecycle + + def attach(self, ctx: DraftContext) -> None: + super().attach(ctx) + c, mr = self.draft_config, self.config.max_running_req + # a rebuild that keeps the target KV pool keeps this one, which the prefix cache still indexes + if self.k_cache is None: + slots = (ctx.num_pages + 1) * self.config.page_size + shape = (c.num_layers, slots, c.num_kv_heads, c.head_dim) + self.k_cache = torch.zeros(shape, dtype=self.draft.dtype, device=ctx.device) + self.v_cache = torch.zeros(shape, dtype=self.draft.dtype, device=ctx.device) + self.aux_buf = torch.zeros(mr * self.width, c.num_taps * c.hidden_size, dtype=self.draft.dtype, device=ctx.device) + self.f_rnn = torch.zeros(mr + 1, c.hidden_size, dtype=self.draft.dtype, device=ctx.device) + + def detach(self, *, keep_kv: bool) -> None: + if not keep_kv: + self.k_cache = self.v_cache = None + self.aux_buf = self.f_rnn = None + self._prefill = None + super().detach(keep_kv=keep_kv) + + # ------------------------------------------------------------------ target features + + def feature_sink(self, batch: Batch) -> DSparkFeatureSink: + if batch.phase == "verify": + return DSparkFeatureSink(self.draft_config, self.aux_buf) + c = self.draft_config + spans = [(req.table_idx, req.cached_len, req.device_len) for req in batch.reqs] + rows = sum(e - s for _, s, e in spans) + sink = DSparkFeatureSink(c, torch.empty(rows, c.num_taps * c.hidden_size, dtype=self.draft.dtype, device=self.device)) + self._prefill = sink, spans + return sink + + def _store_context(self, features: torch.Tensor, positions: torch.Tensor, slots: torch.Tensor) -> None: + # chunked: the per-layer mixtures of a long prefill chunk are fp32 [rows, taps, H] + for lo in range(0, features.shape[0], 4096): + hi = lo + 4096 + k, v = self.draft.context_kv(features[lo:hi], positions[lo:hi]) + self.k_cache[:, slots[lo:hi]] = k + self.v_cache[:, slots[lo:hi]] = v + + def on_prefill(self, batch: Batch, next_tokens_gpu: torch.Tensor) -> None: + """Context K/V of every chunk row, and each request's Markov context from its last row.""" + (sink, spans), self._prefill = self._prefill, None + wanted = set(sink.wanted_layers) | {-1} + if sink.got != wanted: + raise RuntimeError( + f"the target handed the DSpark draft visits {sorted(sink.got - {-1})} and final hidden {-1 in sink.got}, " + f"not visits {sorted(sink.wanted_layers)} and the final hidden: its forward does not export every tap to the feature sink" + ) + n = sink.buffer.shape[0] + self._store_context(sink.buffer, batch.positions[:n], batch.out_loc[:n].long()) + ends = torch.tensor([e - s for _, s, e in spans]).cumsum(0) - 1 + table = torch.tensor([row for row, _, _ in spans]) + self.f_rnn[table.to(self.device)] = self.draft.f_rnn(sink.buffer[ends.to(self.device)]) + + def post_verify(self, batch: Batch, out: torch.Tensor, emitted: torch.Tensor) -> None: + """Context K/V of every verify row, and each request's Markov context from its last accepted row.""" + bs = batch.size + n = bs * self.width + features = self.aux_buf[:n] + self._store_context(features, batch.positions[:n], batch.out_loc[:n].long()) + pick = torch.arange(bs, device=self.device) * self.width + emitted[:bs].to(self.device) + table = torch.tensor([r.table_idx for r in batch.reqs], device=self.device) + self.f_rnn[table] = self.draft.f_rnn(features[pick]) + + # ------------------------------------------------------------------ draft step + + def _context(self, rows: torch.Tensor, starts: torch.Tensor, longest: int): + """``context(layer)`` for the draft's block forward, read from the slots each request's page-table row maps: a local layer's window right-aligned below each start, a full layer's positions in chunks.""" + c, bs = self.draft_config, rows.shape[0] + table = self.ctx.page_table + + def gather(layer: int, pos: torch.Tensor, valid: torch.Tensor): + slots = table[rows[:, None], pos.clamp(min=0)].long() + return self.k_cache[layer][slots], self.v_cache[layer][slots], valid + + def context(layer: int): + if layer in c.local_layer_ids: + width = min(longest, c.window) + pos = starts[:, None] - width + torch.arange(width, device=starts.device) + yield gather(layer, pos, pos >= (starts[:, None] - c.window).clamp(min=0)) + return + chunk = max(1, self.CONTEXT_CHUNK_ROWS // bs) + for lo in range(0, longest, chunk): + pos = (lo + torch.arange(min(chunk, longest - lo), device=starts.device)).expand(bs, -1) + yield gather(layer, pos, pos < starts[:, None]) + + return context + + def propose(self, reqs: List[Req], rows: torch.Tensor, pending: torch.Tensor) -> SpecProposal: + greedy = [r.sampling_params.is_greedy for r in reqs] + starts = torch.tensor([r.cached_len for r in reqs], dtype=torch.int64, device=self.device) + anchor = pending.to(torch.int64) + hidden = self.draft.forward_block(anchor, starts, self._context(rows.to(self.device), starts, max(r.cached_len for r in reqs))) + f_rnn = self.f_rnn[rows] + if all(greedy): + return SpecProposal(self.draft.walk(hidden[:, 1 : self.width], anchor, f_rnn, lambda j, logits: logits.argmax(-1))) + temps = torch.tensor([1.0 if g else max(r.sampling_params.temperature, 1e-5) for r, g in zip(reqs, greedy)], device=self.device) + is_greedy = torch.tensor(greedy, device=self.device) + support, probs = [], [] + + def pick(j: int, logits: torch.Tensor) -> torch.Tensor: + vals, ids = logits.float().topk(self.SAMPLE_TOP_K, dim=-1) + q = torch.softmax(vals / temps[:, None], dim=-1) + # greedy rows verify one-hot; their q is ignored, so give them the argmax, which topk puts first + q = torch.where(is_greedy[:, None], torch.nn.functional.one_hot(torch.zeros_like(ids[:, 0]), q.shape[1]).float(), q) + idx = (q.cumsum(-1) < torch.rand(q.shape[0], 1, device=q.device)).sum(-1, keepdim=True).clamp(max=q.shape[1] - 1) + support.append(ids) + probs.append(q) + return ids.gather(1, idx).squeeze(1) + + tokens = self.draft.walk(hidden[:, 1 : self.width], anchor, f_rnn, pick) + return SpecProposal(tokens, torch.stack(support, dim=1), torch.stack(probs, dim=1)) diff --git a/tests/engine/test_attention_backend_matrix.py b/tests/engine/test_attention_backend_matrix.py index 135aa59665..515291d56d 100644 --- a/tests/engine/test_attention_backend_matrix.py +++ b/tests/engine/test_attention_backend_matrix.py @@ -411,7 +411,7 @@ def test_linear_attention_defaults_to_hybrid_radix(): # Speculative decoding x windowed KV: engine.py refuses a windowed target unless the proposer -# passes target_may_be_windowed (shared-KV admits hybrid SWA; mtp/dflash never reach it). +# passes target_may_be_windowed (shared-KV and DSpark admit hybrid SWA; mtp/dflash never reach it). class _Draft: @@ -420,12 +420,26 @@ def check_source(path, target_path): pass +def _dspark_config(): + from freetoken.models.inkling2_loop.dspark import DSparkConfig + + return DSparkConfig( + hidden_size=64, num_layers=3, num_heads=2, num_kv_heads=1, head_dim=32, intermediate_size=128, rms_norm_eps=1e-6, + rope_theta=1e6, local_layer_ids=(0, 2), window=128, block_size=4, markov_rank=8, target_layer_ids=(1, 2, 4), + num_layer_visits=4, pass_start_visits=(), loop_core_start=0, vocab_size=64, target_rms_norm_eps=1e-6, softcap=30.0, + max_position=1 << 20, + ) + + def _spec_config(kind, backend, method, monkeypatch): + from freetoken.spec.dspark.proposer import DSparkProposer from freetoken.spec.mtp.proposer import MTPProposer from freetoken.spec.mtp.shared_proposer import SharedKVMTPProposer monkeypatch.setattr(MTPProposer, "_draft_class", classmethod(lambda cls, config: _Draft)) monkeypatch.setattr(SharedKVMTPProposer, "_draft_class", classmethod(lambda cls, config: _Draft)) + monkeypatch.setattr(DSparkProposer, "_draft_config", classmethod(lambda cls, config: _dspark_config())) + monkeypatch.setattr("freetoken.models.inkling2_loop.dspark.mtp_file", lambda path: path) config = _config(kind, attention_backend=backend, speculative_algorithm="mtp") object.__setattr__(config, "hf_config", SimpleNamespace(architectures=["Gemma4ForCausalLM"])) object.__setattr__(config, "model_spec", SimpleNamespace(spec_drafts={method: "freetoken.test:draft"})) @@ -441,9 +455,12 @@ def _spec_config(kind, backend, method, monkeypatch): ("swa", "triton", "mtp", False), # the DSV4 window tiers keep the refusal even for the shared assistant ("dsv4", "dsv4_sparse", "shared_kv_mtp", False), + # DSpark keeps its own KV, but on the full-attention slot ids, which the window frees never release + ("swa", "triton", "dspark_mtp", True), + ("dsv4", "dsv4_sparse", "dspark_mtp", False), ], ) -def test_windowed_target_admits_only_read_only_drafts(monkeypatch, kind, backend, method, allowed): +def test_windowed_target_admits_only_window_safe_drafts(monkeypatch, kind, backend, method, allowed): from freetoken.engine.engine import _adjust_config _patch_env(monkeypatch) @@ -468,8 +485,11 @@ def spec_cfg(arch): hf_config=SimpleNamespace(architectures=[arch]), tp_info=SimpleNamespace(size=1), ) + from freetoken.spec.dspark.proposer import DSparkProposer + assert proposer_class(spec_cfg("Gemma4ForCausalLM")) is SharedKVMTPProposer assert proposer_class(spec_cfg("Qwen3_5ForCausalLM")) is MTPProposer + assert proposer_class(spec_cfg("Inkling2LoopForConditionalGeneration")) is DSparkProposer # gpt-oss resolves the hybrid pool but declares no draft: dispatch, not the gate, keeps it off the # shared proposer and its MTP refusal verbatim draft_less = spec_cfg("GptOssForCausalLM") diff --git a/tests/kvcache/test_linear_state_pool_alloc.py b/tests/kvcache/test_linear_state_pool_alloc.py index b05fa7528b..d17046f4ff 100644 --- a/tests/kvcache/test_linear_state_pool_alloc.py +++ b/tests/kvcache/test_linear_state_pool_alloc.py @@ -177,10 +177,15 @@ def test_slot_state_in_the_byte_account(): config.slot_states = () assert state_pool_bytes(config, num_slots=4) == gdn_only * 4 + # a model without GDN layers (Inkling 2's convolution windows) gets a pool of its slot states alone config.slot_states = _SPECS mc.linear_attention_group = lambda: None - with pytest.raises(ValueError, match="slot_states"): - state_pool_bytes(config, num_slots=4) + assert state_pool_bytes(config, num_slots=4) == (with_state - gdn_only) * 4 + pool = LinearStatePool(None, 4, torch.bfloat16, torch.device("cpu"), tp_size=1, slot_states=_SPECS) + assert pool.bytes_per_slot() == with_state - gdn_only + pool.slot_states["ple_conv"].fill_(1.0) + pool.clear_slots([2]) + assert pool.slot_state("ple_conv", 1)[2].abs().sum().item() == 0.0 def test_slot_state_bytes_for_the_real_geometry(): diff --git a/tests/models/inkling2_loop/__init__.py b/tests/models/inkling2_loop/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/models/inkling2_loop/reference.py b/tests/models/inkling2_loop/reference.py new file mode 100644 index 0000000000..d4a6038c06 --- /dev/null +++ b/tests/models/inkling2_loop/reference.py @@ -0,0 +1,66 @@ +"""Dense fp32 references for the Inkling 2 kernels, written from transformers #51050 (head 6173a2f679, +``modeling_inkling2_loop.py``) with no FreeToken import, so they also run next to the HF classes.""" + +from __future__ import annotations + +import math + +import torch + + +def attention(q, k, v, rel, table, sinks, q_pos, k_pos, sm_scale, sliding_window): + """One request: q [Tq, H, D], k / v [Tk, KVH, D], rel [Tq, H, R], table [R, E], sinks [Tq, H] -> [Tq, H, D] fp32. + + ``eager_attention_forward`` with ``Inkling2LoopRelativePositionBias``: the bias of distance ``d`` is + ``rel @ table`` gathered at ``d`` for ``0 <= d < E``, the sink is one more logit with a zero value.""" + H, kvh = q.shape[1], k.shape[1] + k = k.float().repeat_interleave(H // kvh, dim=1) + v = v.float().repeat_interleave(H // kvh, dim=1) + s = torch.einsum("qhd,khd->hqk", q.float(), k) * sm_scale + dist = q_pos[:, None] - k_pos[None, :] + E = table.shape[1] + prof = (rel.float() @ table.float()).permute(1, 0, 2) # [H, Tq, E] + bias = prof.gather(2, dist.clamp(0, E - 1).expand(H, -1, -1)) + s = s + torch.where((dist >= 0) & (dist < E), bias, 0.0) + valid = dist >= 0 + if sliding_window is not None: + valid = valid & (dist < sliding_window) + s = s.masked_fill(~valid, float("-inf")) + s = torch.cat([s, sinks.float().t().unsqueeze(-1)], dim=-1) + p = torch.softmax(s, dim=-1)[..., :-1] + return torch.einsum("hqk,khd->qhd", p, v) + + +def short_conv(x, conv1d_weight=None, static_weight=None, dynamic=None): + """Whole sequence from a zero window: x [T, C]. Either ``conv1d_weight`` [C, 1, K] (``Inkling2LoopShortConvolution``, + out / sqrt(K + 1)) or ``static_weight`` [K, C] plus ``dynamic`` [T, heads, K] per-token taps + (``Inkling2LoopDynamicShortConvolution``, out / sqrt(2K + 1)). fp32 out.""" + T, C = x.shape + xf = x.float() + if conv1d_weight is not None: + K = conv1d_weight.shape[-1] + out = torch.nn.functional.conv1d(xf.t()[None], conv1d_weight.float(), padding=K - 1, groups=C)[0, :, :T].t() + return (out + xf) / math.sqrt(K + 1) + K = static_weight.shape[0] + heads = dynamic.shape[1] + weights = static_weight.float().t().reshape(heads, -1, K)[None] + dynamic.float()[:, :, None, :] # [T, heads, C/heads, K] + ctx = torch.nn.functional.pad(xf.t(), (K - 1, 0)) + windows = ctx.unfold(-1, K, 1).flip(-1).permute(1, 0, 2).reshape(T, heads, -1, K) + out = (windows * weights).sum(-1).reshape(T, C) + return (out + xf) / math.sqrt(2 * K + 1) + + +def softcap_swiglu(gate, up, gate_cap, up_cap): + """``Inkling2LoopSoftcappedSwiGLU``: fp32 math, the sigmoid sees the raw gate.""" + gate, up = gate.float(), up.float() + return torch.tanh(gate / gate_cap) * gate_cap * torch.sigmoid(gate) * torch.tanh(up / up_cap) * up_cap + + +def route(x, weight, bias, top_k, scale): + """``Inkling2LoopTopKRouter``: returns (weights [T, k], ids [T, k]) sorted by id for comparison.""" + scores = torch.sigmoid(torch.nn.functional.linear(x.float(), weight.float())) + ids = torch.topk(scores + bias, top_k, dim=-1, sorted=False).indices + w = scores.gather(1, ids) + w = w / (w.sum(-1, keepdim=True) + 1e-20) * scale + order = ids.argsort(-1) + return w.gather(1, order), ids.gather(1, order) diff --git a/tests/models/inkling2_loop/test_attention.py b/tests/models/inkling2_loop/test_attention.py new file mode 100644 index 0000000000..37c98b38a6 --- /dev/null +++ b/tests/models/inkling2_loop/test_attention.py @@ -0,0 +1,88 @@ +"""Paged relative-bias attention kernel against the dense reference (``reference.attention``, checked against +transformers #51050's ``eager_attention_forward`` + ``Inkling2LoopRelativePositionBias``). + +Covers a cached prefix plus a chunk (keys read back from scattered pool slots), distances past the 1024-token bias +extent, the sliding-window edge, decode and multi-row verify batches, and the sink logit.""" + +from __future__ import annotations + +import pytest +import torch + +from .reference import attention as ref_attention + +requires_cuda = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA (Triton)") + +H, KVH, D, R, E = 24, 8, 128, 16, 1024 + + +def _case(lens, seed): + """Per request ``(prefix, rows)``: a pool with every key in a shuffled slot, the metadata the backend builds, and inputs.""" + g = torch.Generator().manual_seed(seed) + total_kv = sum(p + r for p, r in lens) + slots = torch.randperm(total_kv + 7, generator=g)[:total_kv] + 1 # slot 0 stays a sentinel + k_cache = torch.randn(total_kv + 8, KVH, D, generator=g) * 0.4 + v_cache = torch.randn(total_kv + 8, KVH, D, generator=g) + T = sum(r for _, r in lens) + q = torch.randn(T, H, D, generator=g) * 0.4 + rel = torch.randn(T, H, R, generator=g) + table = torch.randn(R, E, generator=g) * 0.5 + sinks = torch.randn(T, H, generator=g) * 2 + qo, kv, pos = [0], [0], [] + for p, r in lens: + qo.append(qo[-1] + r) + kv.append(kv[-1] + p + r) + pos.extend(range(p, p + r)) + return dict( + k_cache=k_cache, v_cache=v_cache, q=q, rel=rel, table=table, sinks=sinks, slots=slots, lens=lens, + qo=torch.tensor(qo, dtype=torch.int32), kv=torch.tensor(kv, dtype=torch.int32), pos=torch.tensor(pos, dtype=torch.int32), + ) + + +def _run(case, window, dtype=torch.bfloat16): + from freetoken.kernel.triton.inkling2_attention import inkling2_paged_attention + + dev = "cuda" + c = {k: (v.to(dev) if isinstance(v, torch.Tensor) else v) for k, v in case.items()} + out = inkling2_paged_attention( + c["q"].to(dtype), c["k_cache"].to(dtype), c["v_cache"].to(dtype), + qo_indptr=c["qo"], kv_indptr=c["kv"], kv_indices=c["slots"].to(torch.int32), q_positions=c["pos"], + max_q_len=max(r for _, r in case["lens"]), rel=c["rel"].to(dtype), table=c["table"].to(dtype), + sinks=c["sinks"].to(dtype), sm_scale=D**-0.5, sliding_window=window, + ) + errs = [] + for b, (p, r) in enumerate(case["lens"]): + q0, k0 = int(case["qo"][b]), int(case["kv"][b]) + keys = case["slots"][k0 : k0 + p + r] + cast = lambda t: t.to(dtype).float() # the kernel sees bf16 inputs + ref = ref_attention( + cast(case["q"][q0 : q0 + r]), cast(case["k_cache"][keys]), cast(case["v_cache"][keys]), + cast(case["rel"][q0 : q0 + r]), cast(case["table"]), cast(case["sinks"][q0 : q0 + r]), + case["pos"][q0 : q0 + r].long(), torch.arange(p + r), D**-0.5, window, + ) + got = out[q0 : q0 + r].float().cpu() + errs.append(((got - ref).abs().max() / ref.abs().max()).item()) + return max(errs) + + +@requires_cuda +@pytest.mark.parametrize("window", [None, 1024]) +@pytest.mark.parametrize( + "lens", + [ + [(0, 300)], # fresh prefill + [(1100, 77), (0, 5), (3000, 130)], # prefix + chunk past the extent and the window + [(0, 1), (1500, 1), (1023, 1), (1024, 1)], # decode at the window edge + [(2047, 4), (17, 4)], # verify rows + ], +) +def test_matches_reference(lens, window): + assert _run(_case(lens, seed=len(lens)), window) < 2e-2 + + +@requires_cuda +def test_sink_absorbs_mass(): + # a large sink takes most of the mass: the kernel must treat it as a zero-value key, not a skipped one + case = _case([(40, 9)], seed=3) + case["sinks"] = torch.full_like(case["sinks"], 6.0) + assert _run(case, None) < 2e-2 diff --git a/tests/models/inkling2_loop/test_conv.py b/tests/models/inkling2_loop/test_conv.py new file mode 100644 index 0000000000..11a030d75d --- /dev/null +++ b/tests/models/inkling2_loop/test_conv.py @@ -0,0 +1,108 @@ +"""Short-convolution windows against the whole-sequence reference (``reference.short_conv``, checked against +transformers #51050's ``Inkling2LoopShortConvolution`` / ``Inkling2LoopDynamicShortConvolution``). + +A chunked prefill, decode steps and a verify committed at every accepted count must each reproduce the +convolution of the whole sequence, which only holds when the window carries exactly the last K - 1 inputs.""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest +import torch + +from .reference import short_conv as ref_conv + +K, C, HEADS = 4, 64, 4 + + +def _meta(lens, slots): + from freetoken.models.inkling2_loop.conv import ConvMetadata, prefill_indices + + x_index, state_index, next_index = prefill_indices(lens, K, torch.device("cpu")) + return ConvMetadata(torch.tensor(slots), K, x_index, state_index, next_index) + + +def _taps(conv1d_weight): + return conv1d_weight[:, 0, :].flip(-1).t().contiguous() + + +def _streams(seed, lens, dynamic): + g = torch.Generator().manual_seed(seed) + xs = [torch.randn(n, C, generator=g).to(torch.bfloat16) for n in lens] + if dynamic: + static = torch.randn(K, C, generator=g) + dyns = [torch.randn(n, HEADS, K, generator=g) for n in lens] + refs = [ref_conv(x, static_weight=static, dynamic=d) for x, d in zip(xs, dyns)] + return xs, static, dyns, refs + w = torch.randn(C, 1, K, generator=g) + return xs, _taps(w), None, [ref_conv(x, conv1d_weight=w) for x in xs] + + +def _conv(x, taps, state, meta, dyn, **kw): + from freetoken.models.inkling2_loop.conv import short_conv + + return short_conv(x, taps, state, meta, dynamic=dyn, head_dim=C // HEADS, **kw) + + +def _close(got, ref): + # outputs are bf16, as in the reference's layer + return (got.float() - ref).abs().max().item() < 3e-2 * ref.abs().max().item() + + +@pytest.mark.parametrize("dynamic", [False, True]) +def test_chunked_prefill_then_decode(dynamic): + from freetoken.models.inkling2_loop.conv import ConvMetadata + + lens = [23, 1, 40] + xs, taps, dyns, refs = _streams(0, lens, dynamic) + state = torch.zeros(5, K - 1, C, dtype=torch.bfloat16) + slots = [3, 1, 4] + # prefill chunk boundaries per request; every chunk reads the window the previous one left, then decode + bounds = [[0, 7, 8, 20], [0, 1], [0, 2, 33]] + for step in range(max(len(b) for b in bounds) - 1): + live = [i for i, b in enumerate(bounds) if step + 1 < len(b)] + spans = [(bounds[i][step], bounds[i][step + 1]) for i in live] + meta = _meta([e - s for s, e in spans], [slots[i] for i in live]) + x = torch.cat([xs[i][s:e] for i, (s, e) in zip(live, spans)]) + dyn = torch.cat([dyns[i][s:e] for i, (s, e) in zip(live, spans)]) if dynamic else None + out = _conv(x, taps, state, meta, dyn) + off = 0 + for i, (s, e) in zip(live, spans): + assert _close(out[off : off + e - s], refs[i][s:e]) + off += e - s + done = [b[-1] for b in bounds] + while any(d < n for d, n in zip(done, lens)): + live = [i for i in range(len(lens)) if done[i] < lens[i]] + meta = ConvMetadata(torch.tensor([slots[i] for i in live]), K) + x = torch.cat([xs[i][done[i] : done[i] + 1] for i in live]) + dyn = torch.cat([dyns[i][done[i] : done[i] + 1] for i in live]) if dynamic else None + out = _conv(x, taps, state, meta, dyn) + for row, i in enumerate(live): + assert _close(out[row : row + 1], refs[i][done[i] : done[i] + 1]) + done[i] += 1 + for i, n in enumerate(lens): + tail = xs[i][max(0, n - (K - 1)) :] + assert torch.equal(state[slots[i], K - 1 - tail.shape[0] :], tail) + + +def test_verify_commit_matches_decode(): + from freetoken.models.inkling2_loop.conv import ConvMetadata, ConvWindowVerify + + R, n_prefix = 5, 9 + xs, taps, _, refs = _streams(1, [n_prefix + R], False) + x = xs[0] + spec = SimpleNamespace(name="w", shape=(K - 1, C), layer_ids=(0,)) + handler = ConvWindowVerify(spec, max_bs=2, rows_per_req=R, device=torch.device("cpu"), dtype=torch.bfloat16) + for accepted in range(1, R + 1): + state = torch.zeros(2, K - 1, C, dtype=torch.bfloat16) + _conv(x[:n_prefix], taps, state, _meta([n_prefix], [1]), None) + live = state.clone() + meta = ConvMetadata(torch.tensor([1]), K, rows_per_req=R, verify=True) + out = _conv(x[n_prefix:], taps, state, meta, None, verify_stash=handler.stash(0)) + assert torch.equal(state, live), "a verify forward must not move the live window" + assert _close(out, refs[0][n_prefix:]) + pool = SimpleNamespace(slot_state=lambda name, layer_id: state) + handler.commit(pool, torch.tensor([1]), torch.tensor([accepted])) + end = n_prefix + accepted + assert torch.equal(state[1], x[end - (K - 1) : end]) diff --git a/tests/models/inkling2_loop/test_dspark.py b/tests/models/inkling2_loop/test_dspark.py new file mode 100644 index 0000000000..9c42ee46a8 --- /dev/null +++ b/tests/models/inkling2_loop/test_dspark.py @@ -0,0 +1,459 @@ +"""Inkling 2 DSpark draft against an fp32 torch reference of the vLLM / sglang definition, and DSparkProposer's bookkeeping against a from-scratch draft. + +The reference runs one request at a time: standard pre-norm layers over ``[anchor, mask x 7]``, dense attention with explicit window masks, the +Markov head with ``hidden_out`` unfolded. A tiny synthetic draft covers every path; ``FREETOKEN_INKLING2_MINI_MODEL`` repeats the parity at the +checkpoint's own weights and dimensions. The proposer test drives a toy looped target through chunked prefill and verify steps with every +accept count on a scattered page table; after each step its drafts must equal a draft recomputed from the committed tokens alone, with the +features captured the way vLLM and sglang capture them (at the inputs of the tapped visits). +""" + +from __future__ import annotations + +import json +import os +from types import SimpleNamespace + +import pytest +import torch +import torch.nn.functional as F +from safetensors import safe_open +from safetensors.torch import save_file + +DEV = torch.device("cuda" if torch.cuda.is_available() else "cpu") +REAL_MODEL = os.environ.get("FREETOKEN_INKLING2_MINI_MODEL", "") + +# a looped toy target: 4 layers, core [1, 3) run 3 times -> 8 visits; tap 5 restarts the core, tap 8 is the final norm +TOY = dict(hidden=256, layers=3, heads=4, kv_heads=2, head_dim=64, inter=512, vocab=512, padded_vocab=528, window=16, block=8, + rank=32, local=(0, 2), taps=(2, 5, 7, 8), target_layers=4, core=(1, 3), passes=3) + + +def _hf_config(t: dict) -> dict: + """The target checkpoint's config.json as far as the draft reads it.""" + return { + "architectures": ["Inkling2LoopForConditionalGeneration"], "model_type": "inkling2_loop", + "text_config": {"hidden_size": t["hidden"], "num_hidden_layers": t["target_layers"], "vocab_size": t["padded_vocab"], + "unpadded_vocab_size": t["vocab"], "final_logit_softcapping": 30.0, "rms_norm_eps": 1e-6, + "loop_config": {"core_start": t["core"][0], "core_end": t["core"][1], "num_passes": t["passes"], + "gate_rank": 8, "is_varloop": False}}, + "mtp_config": {"hidden_size": t["hidden"], "num_hidden_layers": t["layers"], "num_attention_heads": t["heads"], + "num_key_value_heads": t["kv_heads"], "head_dim": t["head_dim"], "intermediate_size": t["inter"], + "max_position_embeddings": 1 << 20, "torch_dtype": "bfloat16", "q_bias": False, "o_bias": False, + "rms_norm_eps": 1e-6, "rope_theta": 1e6, "local_layer_ids": list(t["local"]), "sliding_window_size": t["window"], + "block_size": t["block"], "markov_rank": t["rank"], "markov_head_type": "rnn_hidden", + "target_layer_ids": list(t["taps"])}, + } + + +def _toy_weights(t: dict, seed: int = 0) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]: + """Fan-in scaled bf16 draft tensors under the checkpoint's names, and the target's embedding, embedding norm and head.""" + g = torch.Generator().manual_seed(seed) + H, q, kv, r = t["hidden"], t["heads"] * t["head_dim"], t["kv_heads"] * t["head_dim"], t["rank"] + + def mat(*shape): + return (torch.randn(*shape, generator=g) * shape[-1] ** -0.5).to(torch.bfloat16) + + def gain(n): + return (1 + 0.1 * torch.randn(n, generator=g)).to(torch.bfloat16) + + w = {"fuse_weight": torch.randn(t["layers"] + 1, len(t["taps"]), generator=g).to(torch.bfloat16), + "mask_embed": torch.randn(H, generator=g).to(torch.bfloat16), "norm.weight": gain(H), + "markov_head.dflare_norm.weight": gain(H), "markov_head.markov_w1.weight": mat(t["padded_vocab"], r), + "markov_head.rnn_proj.weight": mat(3 * r, 2 * r + 2 * H), "markov_head.rnn_proj.bias": (0.1 * torch.randn(3 * r, generator=g)).to(torch.bfloat16), + "markov_head.hidden_out.weight": mat(H, r), "markov_head.hidden_out.bias": (0.1 * torch.randn(H, generator=g)).to(torch.bfloat16)} + for i in range(t["layers"]): + p = f"layers.{i}." + w.update({p + "dflare_norm.weight": gain(H), p + "input_layernorm.weight": gain(H), p + "post_attention_layernorm.weight": gain(H), + p + "self_attn.q_proj.weight": mat(q, H), p + "self_attn.k_proj.weight": mat(kv, H), p + "self_attn.v_proj.weight": mat(kv, H), + p + "self_attn.o_proj.weight": mat(H, q), p + "self_attn.q_norm.weight": gain(t["head_dim"]), + p + "self_attn.k_norm.weight": gain(t["head_dim"]), p + "self_attn.k_norm_ctx.weight": gain(t["head_dim"]), + p + "self_attn.k_proj_ctx.weight": mat(kv, H), p + "self_attn.v_proj_ctx.weight": mat(kv, H), + p + "mlp.gate_proj.weight": mat(t["inter"], H), p + "mlp.up_proj.weight": mat(t["inter"], H), p + "mlp.down_proj.weight": mat(H, t["inter"])}) + target = {"embed": torch.randn(t["padded_vocab"], H, generator=g).to(torch.bfloat16), "embed_norm": gain(H), + "head": (torch.randn(t["padded_vocab"], H, generator=g) * 0.3).to(torch.bfloat16)} + return w, target + + +def _target(parts: dict[str, torch.Tensor]): + """The modules the draft shares with the target, as FreeToken's Inkling target names them: the token embedding, its fp32 norm and the bf16 head.""" + embed, norm, head = (parts[n].to(DEV) for n in ("embed", "embed_norm", "head")) + embed_tokens = SimpleNamespace(forward=lambda ids: embed[ids.long()]) + return SimpleNamespace(model=SimpleNamespace(embed_tokens=embed_tokens, embed_norm=norm.float()), lm_head=SimpleNamespace(weight=head)) + + +def _toy_checkpoint(tmp_path, t: dict = TOY, seed: int = 0): + path = tmp_path / "ckpt" + path.mkdir(parents=True, exist_ok=True) + w, target = _toy_weights(t, seed) + (path / "config.json").write_text(json.dumps(_hf_config(t))) + save_file(w, str(path / "mtp.safetensors")) + return str(path), w, target + + +def _load(path: str, target_parts: dict[str, torch.Tensor], dtype=torch.bfloat16): + from freetoken.models.inkling2_loop.dspark import Inkling2DSparkDraft, parse_dspark_config + from freetoken.utils import cached_load_hf_config + + config = parse_dspark_config(cached_load_hf_config(path)) + return Inkling2DSparkDraft.load(config, _target(target_parts), path, DEV, dtype) + + +class _Reference: + """The draft in fp32 for one request; ``features [n, taps*H]`` are the target's at positions ``0 .. n-1``.""" + + def __init__(self, w: dict[str, torch.Tensor], target: dict[str, torch.Tensor], c) -> None: + self.w = {name: t.to(DEV, torch.float32) for name, t in w.items()} + self.t = {name: t.to(DEV, torch.float32) for name, t in target.items()} + self.c = c + self.alpha = torch.softmax(self.w["fuse_weight"], -1) + + def rms(self, x, weight): + return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + 1e-6) * weight + + def rope(self, x, pos): + d = self.c.head_dim + inv = 1.0 / (self.c.rope_theta ** (torch.arange(0, d, 2, device=DEV, dtype=torch.float64) / d)) + freqs = pos.double()[:, None] * inv[None, :] + cos, sin = freqs.cos().float()[:, None], freqs.sin().float()[:, None] + x1, x2 = x[..., : d // 2], x[..., d // 2 :] + return torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin], -1) + + def mixed(self, features, row, norm_name): + taps = features.float().view(features.shape[0], self.c.num_taps, -1) + return self.rms((taps * self.alpha[row][None, :, None]).sum(1), self.w[norm_name]) + + def context_kv(self, layer, features): + c, p = self.c, f"layers.{layer}." + ctx = self.mixed(features, layer, p + "dflare_norm.weight") + k = self.rms((ctx @ self.w[p + "self_attn.k_proj_ctx.weight"].T).view(-1, c.num_kv_heads, c.head_dim), self.w[p + "self_attn.k_norm_ctx.weight"]) + v = (ctx @ self.w[p + "self_attn.v_proj_ctx.weight"].T).view(-1, c.num_kv_heads, c.head_dim) + return self.rope(k, torch.arange(features.shape[0], device=DEV)), v + + def block(self, features, anchor: int): + """Final hidden ``[block, H]`` of ``[anchor, mask x 7]`` at positions ``n .. n+7`` after the ``n`` context rows.""" + c, w = self.c, self.w + n, B = features.shape[0], c.block_size + # the target hands over its first layer's input, a bf16 row + e = self.rms(self.t["embed"][anchor], self.t["embed_norm"]).to(torch.bfloat16).float() + x = torch.cat([e[None], w["mask_embed"][None].expand(B - 1, -1)]) + pos = n + torch.arange(B, device=DEV) + for i in range(c.num_layers): + p = f"layers.{i}.self_attn." + h = self.rms(x, w[f"layers.{i}.input_layernorm.weight"]) + q = self.rope(self.rms((h @ w[p + "q_proj.weight"].T).view(B, c.num_heads, c.head_dim), w[p + "q_norm.weight"]), pos) + k = self.rope(self.rms((h @ w[p + "k_proj.weight"].T).view(B, c.num_kv_heads, c.head_dim), w[p + "k_norm.weight"]), pos) + v = (h @ w[p + "v_proj.weight"].T).view(B, c.num_kv_heads, c.head_dim) + ck, cv = self.context_kv(i, features) + # a local layer reads the window of positions before the block start; every layer reads the whole block + lo = max(0, n - c.window) if i in c.local_layer_ids else 0 + keys, values = torch.cat([ck[lo:], k]), torch.cat([cv[lo:], v]) + group = c.num_heads // c.num_kv_heads + out = torch.empty(B, c.num_heads, c.head_dim, device=DEV) + for head in range(c.num_heads): + scores = q[:, head] @ keys[:, head // group].T * c.head_dim**-0.5 + out[:, head] = torch.softmax(scores, -1) @ values[:, head // group] + x = x + out.reshape(B, -1) @ w[p + "o_proj.weight"].T + h = self.rms(x, w[f"layers.{i}.post_attention_layernorm.weight"]) + m = F.silu(h @ w[f"layers.{i}.mlp.gate_proj.weight"].T) * (h @ w[f"layers.{i}.mlp.up_proj.weight"].T) + x = x + m @ w[f"layers.{i}.mlp.down_proj.weight"].T + return self.rms(x, w["norm.weight"]) + + def path_logits(self, hidden, last_features, anchor: int, tokens): + """Each mask row's logits ``[steps, vocab]`` with the Markov state advanced over ``tokens`` (teacher forced): ``softcap(head @ (h + hidden_out(latent)))``.""" + w, r, V = self.w, self.c.markov_rank, self.c.vocab_size + f_rnn = self.mixed(last_features[None], -1, "markov_head.dflare_norm.weight")[0] + head = self.t["head"][:V] + state, prev, out = torch.zeros(r, device=DEV), anchor, [] + for j in range(hidden.shape[0]): + z = torch.cat([state, w["markov_head.markov_w1.weight"][prev], hidden[j], f_rnn]) + gate, cand, o = (z @ w["markov_head.rnn_proj.weight"].T + w["markov_head.rnn_proj.bias"]).split(r) + gate = torch.sigmoid(gate) + state = gate * state + (1 - gate) * torch.tanh(cand) + bias = torch.tanh(o) @ w["markov_head.hidden_out.weight"].T + w["markov_head.hidden_out.bias"] + logits = head @ hidden[j] + head @ bias + out.append(torch.tanh(logits / 30.0) * 30.0) + prev = int(tokens[j]) + return torch.stack(out) + + +def _check_draft(draft, ref, features_by_req, anchors, kv_tol, hidden_tol, logit_tol): + """Context K/V, block hidden and each drafted token of a batch of requests against the reference; a draft may differ from the reference's argmax only within ``logit_tol``.""" + c = draft.config + starts = torch.tensor([f.shape[0] for f in features_by_req], device=DEV) + kvs = [draft.context_kv(f, torch.arange(f.shape[0], device=DEV)) for f in features_by_req] + for f, (k, v) in zip(features_by_req, kvs): + for i in range(c.num_layers): + # bf16 rounds the mixed context and the projection, about 2^-8 of each head row's norm + for got, want in zip((k[i], v[i]), ref.context_kv(i, f)): + err = (got.float() - want).norm(dim=-1) / want.norm(dim=-1) + assert err.max() < kv_tol, f"layer {i} context K/V off by {err.max():.3g} of a head row" + width = int(starts.max()) + + def context(layer): + # right-aligned dense context; a local layer keeps only the window before each start + k = torch.zeros(len(kvs), width, c.num_kv_heads, c.head_dim, dtype=draft.dtype, device=DEV) + v, valid = torch.zeros_like(k), torch.zeros(len(kvs), width, dtype=torch.bool, device=DEV) + for b, (kk, vv) in enumerate(kvs): + n = kk.shape[1] + lo = max(0, n - c.window) if layer in c.local_layer_ids else 0 + k[b, width - n + lo :], v[b, width - n + lo :] = kk[layer, lo:], vv[layer, lo:] + valid[b, width - n + lo :] = True + return [(k, v, valid)] + + anchor = torch.tensor(anchors, device=DEV) + hidden = draft.forward_block(anchor, starts, context) + f_rnn = draft.f_rnn(torch.stack([f[-1] for f in features_by_req])) + steps = [] + + def pick(j, logits): + steps.append(logits.float()) + return logits.argmax(-1) + + tokens = draft.walk(hidden[:, 1:], anchor, f_rnn, pick) + for b, f in enumerate(features_by_req): + want = ref.block(f, anchors[b]) + err = (hidden[b].float() - want).norm(dim=-1) / want.norm(dim=-1) + assert err.max() < hidden_tol, f"request {b}: block hidden off by {err.max():.3g} (relative)" + # the Markov head alone: the reference walks the draft's own hidden and tokens + logits = ref.path_logits(hidden[b, 1:].float(), f[-1], anchors[b], tokens[b]) + got = torch.stack([s[b] for s in steps]) + assert (got - logits).abs().max() < logit_tol, f"request {b}: step logits off by {(got - logits).abs().max():.3g}" + picked = logits.gather(1, tokens[b, :, None].long())[:, 0] + # a draft may differ from the fp32 argmax only at a near tie + assert (picked >= logits.max(-1).values - logit_tol).all(), f"request {b}: drafts {tokens[b].tolist()} miss the reference argmax {logits.argmax(-1).tolist()}" + + +# (dtype, context K/V, block hidden, logit) tolerances: fp32 pins the math (its rope runs in fp32, the reference's in fp64); +# bf16, the serving dtype, is held to bf16 noise: 2^-8 of a row per rounding, through three layers for the hidden +TOLERANCES = [(torch.float32, 1e-4, 2e-4, 1e-3), (torch.bfloat16, 1e-2, 5e-2, 0.5)] + + +@pytest.mark.parametrize("dtype, kv_tol, hidden_tol, logit_tol", TOLERANCES) +def test_toy_draft_matches_reference(tmp_path, dtype, kv_tol, hidden_tol, logit_tol): + """A short context (no window cut) and a long one (local layers cut at the window) in one batch, on the tiny draft.""" + path, w, target = _toy_checkpoint(tmp_path) + draft = _load(path, target, dtype) + ref = _Reference(w, target, draft.config) + g = torch.Generator().manual_seed(1) + feats = [torch.randn(n, draft.config.num_taps * draft.config.hidden_size, generator=g).to(DEV, torch.bfloat16) for n in (5, 40)] + _check_draft(draft, ref, feats, [7, 300], kv_tol, hidden_tol, logit_tol) + + +@pytest.mark.needs_weights +@pytest.mark.skipif(not os.path.isfile(os.path.join(REAL_MODEL, "config.json")), reason="FREETOKEN_INKLING2_MINI_MODEL not set") +@pytest.mark.parametrize("dtype, kv_tol, hidden_tol, logit_tol", TOLERANCES) +def test_checkpoint_draft_matches_reference(dtype, kv_tol, hidden_tol, logit_tol): + """The checkpoint's draft at its own dimensions, with the target's real embedding and head; contexts below and past the 1024 window.""" + from freetoken.models.loader import safetensors_weight_map + + names = {"embed": "model.llm.embed.weight", "embed_norm": "model.llm.embed_norm.weight", "head": "model.llm.unembed.weight"} + shards = safetensors_weight_map(REAL_MODEL) + target = {} + for key, name in names.items(): + with safe_open(os.path.join(REAL_MODEL, shards[name]), framework="pt") as f: + target[key] = f.get_tensor(name) + draft = _load(REAL_MODEL, target, dtype) + with safe_open(os.path.join(REAL_MODEL, "mtp.safetensors"), framework="pt") as f: + w = {name: f.get_tensor(name) for name in f.keys()} + ref = _Reference(w, target, draft.config) + g = torch.Generator().manual_seed(1) + # target features are O(1) residual-stream rows; the final-norm column is too + feats = [torch.randn(n, draft.config.num_taps * draft.config.hidden_size, generator=g).to(DEV, torch.bfloat16) for n in (37, 1100)] + _check_draft(draft, ref, feats, [1000, 4242], kv_tol, hidden_tol, logit_tol) + + +# ---------------------------------------------------------------------- proposer + + +class _ToyLoopTarget: + """Per-row stand-in for the target's residual stream: visit v maps its input through layer ``layer_of[v]``; a core pass after the first restarts from the prelude's output.""" + + def __init__(self, t: dict, H: int, seed: int = 3) -> None: + g = torch.Generator().manual_seed(seed) + start, end = t["core"] + self.visits = list(range(start)) + [i for _ in range(t["passes"]) for i in range(start, end)] + list(range(end, t["target_layers"])) + self.restarts = {start + p * (end - start) for p in range(1, t["passes"])} + self.core_start = start + # elementwise, so a row's features do not depend on which rows share its forward + self.layers = [(torch.randn(H, generator=g), torch.randn(H, generator=g)) for _ in range(t["target_layers"])] + self.table = torch.randn(t["padded_vocab"], H, generator=g) + self.taps = t["taps"] + + def run(self, tokens: torch.Tensor, positions: torch.Tensor, sink=None) -> torch.Tensor: + """Features ``[n, taps*H]`` captured at the tapped visits' inputs (vLLM / sglang); hands every visit output to ``sink`` the way a FreeToken target does.""" + x = self.table[tokens.long().cpu()] + 0.01 * positions.float().cpu()[:, None] + captured, prelude = {}, None + for v, layer in enumerate(self.visits): + if v == self.core_start: + prelude = x + if v in self.restarts: + x = prelude + if v in self.taps: + captured[v] = x + a, b = self.layers[layer] + x = torch.tanh(x * a + b) + x + if sink is not None and v in sink.wanted_layers: + sink.layer_output(v, x.to(DEV, torch.bfloat16)) + final = torch.tanh(x) + if sink is not None: + sink.final_hidden(final.to(DEV, torch.bfloat16)) + cols = [captured[v] for v in self.taps[:-1]] + [final] + return torch.cat(cols, dim=-1).to(DEV, torch.bfloat16) + + +def _proposer(path: str, target_parts, k: int, page_table, num_pages: int, page_size: int, max_running_req: int, dtype=torch.bfloat16): + from freetoken.core import Req, SamplingParams + from freetoken.spec.dspark.proposer import DSparkProposer + from freetoken.spec.proposer import DraftContext + from freetoken.utils import cached_load_hf_config + + config = SimpleNamespace( + speculative_num_steps=k, speculative_draft_model_path=None, model_path=path, hf_config=cached_load_hf_config(path), + model_spec=SimpleNamespace(spec_drafts=(("dspark_mtp", "freetoken.models.inkling2_loop.dspark:Inkling2DSparkDraft"),)), + dtype=dtype, max_running_req=max_running_req, page_size=page_size, + ) + proposer = DSparkProposer(config, _target(target_parts)) + dummy = Req(input_ids=torch.zeros(1, dtype=torch.int32), table_idx=max_running_req, cached_len=0, output_len=1, uid=-1, + sampling_params=SamplingParams(), cache_handle=None) + proposer.attach(DraftContext(page_table=page_table, num_pages=num_pages, device=DEV, stream=None, dummy_req=dummy, + slot_states={}, kv_cache=None)) + return proposer + + +def _from_scratch(draft, target: _ToyLoopTarget, seq: list[int], k: int, pick=None): + """The draft for ``seq`` (its last token pending) from features recomputed over the committed tokens alone.""" + c = draft.config + p = len(seq) - 1 + feats = target.run(torch.tensor(seq[:p]), torch.arange(p)) + ck, cv = draft.context_kv(feats, torch.arange(p, device=DEV)) + + def context(layer): + lo = max(0, p - c.window) if layer in c.local_layer_ids else 0 + valid = torch.zeros(1, p, dtype=torch.bool, device=DEV) + valid[:, lo:] = True + return [(ck[layer][None], cv[layer][None], valid)] + + anchor = torch.tensor([seq[-1]], device=DEV) + hidden = draft.forward_block(anchor, torch.tensor([p], device=DEV), context) + return draft.walk(hidden[:, 1 : k + 1], anchor, draft.f_rnn(feats[-1:]), pick or (lambda j, logits: logits.argmax(-1)))[0] + + +# the second case reads the full layer's context 7 positions at a time, so the softmax merges many chunks, some masked out for one request +@pytest.mark.parametrize("k, chunk_rows", [(7, 16384), (3, 14)]) +def test_proposer_tracks_committed_tokens(tmp_path, monkeypatch, k, chunk_rows): + """Chunked prefill, then verify steps with every accept count: the pool rows past the accepted ones and the Markov context's row must never show in the next drafts.""" + from freetoken.spec.dspark.proposer import DSparkProposer + from freetoken.core import Batch, Req, SamplingParams + + monkeypatch.setattr(DSparkProposer, "CONTEXT_CHUNK_ROWS", chunk_rows) + path, _, target_parts = _toy_checkpoint(tmp_path) + H, page_size, num_pages, mr = TOY["hidden"], 4, 64, 2 + g = torch.Generator().manual_seed(5) + # scattered pages: positions of one request land on unrelated slots + pages = torch.randperm(num_pages, generator=g).view(mr, -1) + cols = torch.arange(pages.shape[1] * page_size) + page_table = torch.full((mr + 1, cols.numel()), num_pages * page_size, dtype=torch.int32) + page_table[:mr] = (pages[:, cols // page_size] * page_size + cols % page_size).int() + page_table = page_table.to(DEV) + # fp32: the from-scratch draft runs other batch shapes, whose GEMMs round differently; bf16 would flip near ties + proposer = _proposer(path, target_parts, k, page_table, num_pages, page_size, mr, torch.float32) + toy = _ToyLoopTarget(TOY, H) + greedy = SamplingParams() + width = k + 1 + + def forward(reqs, phase, tokens, positions, rows_per_req=None): + batch = Batch(reqs=reqs, phase=phase, rows_per_req=rows_per_req) + batch.padded_reqs = reqs + batch.positions = positions.to(DEV) + rows = torch.cat([torch.full((len(p),), r.table_idx) for r, p in zip(reqs, positions.split([len(x) for x in tokens]))]) + batch.out_loc = page_table[rows.to(DEV), batch.positions.long()] + sink = proposer.feature_sink(batch) + toy.run(torch.cat(tokens), positions, sink) + return batch + + # request 0 prefills in two chunks past the window, request 1 in one chunk inside it + seqs = [torch.randint(0, TOY["vocab"], (37,), generator=g).tolist(), torch.randint(0, TOY["vocab"], (9,), generator=g).tolist()] + chunks = [[(0, 20), (20, 37)], [(0, 9)]] + for step in range(2): + reqs, toks, pos = [], [], [] + for row, seq in enumerate(seqs): + if step < len(chunks[row]): + s, e = chunks[row][step] + reqs.append(Req(input_ids=torch.tensor(seq[:e], dtype=torch.int32), table_idx=row, cached_len=s, output_len=64, uid=row, + sampling_params=greedy, cache_handle=None)) + toks.append(torch.tensor(seq[s:e])) + pos.append(torch.arange(s, e)) + batch = forward(reqs, "prefill", toks, torch.cat(pos)) + proposer.on_prefill(batch, None) + for seq in seqs: + seq.append(int(torch.randint(0, TOY["vocab"], (1,), generator=g))) + + seen = set() + for step in range(10): + reqs = [Req(input_ids=torch.tensor(seq, dtype=torch.int32), table_idx=row, cached_len=len(seq) - 1, output_len=64, uid=row, + sampling_params=greedy, cache_handle=None) for row, seq in enumerate(seqs)] + rows = torch.tensor([0, 1], device=DEV) + pending = torch.tensor([seq[-1] for seq in seqs], device=DEV) + drafts = proposer.propose(reqs, rows, pending).draft_token_ids + for row, seq in enumerate(seqs): + steps = [] + want = _from_scratch(proposer.draft, toy, seq, k, pick=lambda j, logits: (steps.append(logits[0]), logits.argmax(-1))[1]).tolist() + got = drafts[row].tolist() + # the two may part only where the from-scratch step has a near tie, and nothing after it is comparable + j = next((i for i, (a, b) in enumerate(zip(got, want)) if a != b), None) + assert j is None or steps[j][want[j]] - steps[j][got[j]] < 1e-4, f"step {step}, request {row}: drafts {got}, from scratch {want}" + # the target takes n drafts, then a token of its own + emitted = torch.tensor([(step + 3 * row) % width for row in range(2)]) + seen.update(emitted.tolist()) + toks = [torch.tensor([seq[-1]] + drafts[row].tolist()) for row, seq in enumerate(seqs)] + pos = torch.cat([torch.arange(len(seq) - 1, len(seq) - 1 + width) for seq in seqs]) + batch = forward(reqs, "verify", toks, pos, rows_per_req=width) + out = torch.cat([drafts.cpu(), drafts.cpu()[:, :1]], dim=1) + proposer.post_verify(batch, out.to(DEV), emitted.to(DEV)) + for row, seq in enumerate(seqs): + n = int(emitted[row]) + seq.extend(drafts[row, :n].tolist()) + seq.append((int(drafts[row, n]) + 1) % TOY["vocab"] if n < k else int(torch.randint(0, TOY["vocab"], (1,), generator=g))) + assert seen == set(range(width)) + + +def test_sampled_drafts_report_their_distribution(tmp_path): + """A greedy and a sampled request in one batch: the greedy one drafts what it drafts alone, the sampled one reports the reference's tempered softmax over its step's top logits along the path it drew. fp32, so q compares tightly.""" + from freetoken.core import Req, SamplingParams + + path, w, target_parts = _toy_checkpoint(tmp_path) + mr, page_size, num_pages, temperature = 2, 4, 32, 0.8 + page_table = torch.arange((mr + 1) * 40, dtype=torch.int32).view(mr + 1, 40).to(DEV) + proposer = _proposer(path, target_parts, 7, page_table, num_pages, page_size, mr, torch.float32) + ref = _Reference(w, target_parts, proposer.draft_config) + toy = _ToyLoopTarget(TOY, TOY["hidden"]) + g = torch.Generator().manual_seed(9) + seqs = [torch.randint(0, TOY["vocab"], (12,), generator=g).tolist() for _ in range(2)] + # the pool as a prefill leaves it + feats = [toy.run(torch.tensor(seq[:-1]), torch.arange(len(seq) - 1)) for seq in seqs] + for row, (seq, f) in enumerate(zip(seqs, feats)): + proposer._store_context(f, torch.arange(len(seq) - 1, device=DEV), page_table[row, : len(seq) - 1].long()) + proposer.f_rnn[row] = proposer.draft.f_rnn(f[-1:])[0] + params = [SamplingParams(), SamplingParams(temperature=temperature)] + reqs = [Req(input_ids=torch.tensor(seq, dtype=torch.int32), table_idx=row, cached_len=len(seq) - 1, output_len=8, uid=row, + sampling_params=params[row], cache_handle=None) for row, seq in enumerate(seqs)] + torch.manual_seed(0) + proposal = proposer.propose(reqs, torch.tensor([0, 1], device=DEV), torch.tensor([s[-1] for s in seqs], device=DEV)) + assert proposal.draft_token_ids[0].tolist() == _from_scratch(proposer.draft, toy, seqs[0], 7).tolist() + tokens, support, q = proposal.draft_token_ids[1], proposal.draft_support_ids[1], proposal.draft_support_probs[1] + torch.testing.assert_close(q.sum(-1), torch.ones(7, device=DEV)) + hits = (support == tokens[:, None]).float() + assert (hits.sum(-1) == 1).all() and ((q * hits).sum(-1) > 0).all() + anchor = seqs[1][-1] + logits = ref.path_logits(ref.block(feats[1].float(), anchor)[1:], feats[1][-1], anchor, tokens) + top = logits.topk(proposer.SAMPLE_TOP_K, dim=-1).values + for j in range(7): + vals = logits[j].gather(0, support[j]) + # the support is the step's top K (up to a tie at its edge), and q their softmax at the request's temperature + assert vals.min() >= top[j, -1] - 1e-3 + torch.testing.assert_close(q[j], torch.softmax(vals / temperature, -1), atol=1e-4, rtol=1e-3) + # the drafts are drawn from that q: many copies of the sampled request, the first draft's frequencies against q at 4 sigma + n = 4096 + many = proposer.propose([reqs[1]] * n, torch.ones(n, dtype=torch.int64, device=DEV), torch.full((n,), anchor, device=DEV)) + q0, ids0 = many.draft_support_probs[0, 0], many.draft_support_ids[0, 0] + freq = (many.draft_token_ids[:, :1] == ids0[None]).float().mean(0) + assert ((freq - q0).abs() <= 4 * (q0 * (1 - q0) / n).sqrt() + 1e-3).all(), (freq - q0).abs().max() diff --git a/tests/models/inkling2_loop/test_image_limit.py b/tests/models/inkling2_loop/test_image_limit.py new file mode 100644 index 0000000000..15160a265c --- /dev/null +++ b/tests/models/inkling2_loop/test_image_limit.py @@ -0,0 +1,41 @@ +"""The image processor refuses an image past the token cap: the reference never resizes, and the tower attends over +every patch of an image in one pass, so an unbounded image would take the engine's memory.""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + + +def _processor(**mm): + from freetoken.mm.config import MultimodalConfig + from freetoken.mm.processors.inkling2 import Inkling2MMProcessor + + hf_config = SimpleNamespace(vision_config=SimpleNamespace(native_patch_size=20, adapter_merge_size=2)) + return Inkling2MMProcessor(hf_config, "/unused", MultimodalConfig(**mm)) + + +def _image(width, height): + from PIL import Image + + return Image.new("RGB", (width, height), (10, 20, 30)) + + +def test_images_past_the_token_limit_are_refused(): + processor = _processor(image_max_tokens=4) + # 80x80 is 2x2 tiles of 40 pixels; one more pixel of width starts a third column + (item,) = processor.process([_image(80, 80)]) + assert item.grid_thw == [1, 2, 2] + with pytest.raises(ValueError, match="takes 6 image tokens .* above the limit of 4"): + processor.process([_image(81, 80)]) + + +def test_the_default_limit_holds_without_the_flag(): + from freetoken.mm.processors.inkling2 import DEFAULT_MAX_IMAGE_TOKENS + + processor = _processor() + assert processor.max_tokens == DEFAULT_MAX_IMAGE_TOKENS + side = 40 * 129 # 129 x 129 tiles = 16641 > 16384 + with pytest.raises(ValueError, match="above the limit of 16384"): + processor.process([_image(side, side)]) diff --git a/tests/models/inkling2_loop/test_inkling2_parsers.py b/tests/models/inkling2_loop/test_inkling2_parsers.py new file mode 100644 index 0000000000..400434a6fa --- /dev/null +++ b/tests/models/inkling2_loop/test_inkling2_parsers.py @@ -0,0 +1,99 @@ +"""Inkling 2's reasoning and tool-call parsers against the checkpoint's chat_template.jinja: a turn the template +renders, served back through the parsers streamed or not, renders to the same text again.""" + +from __future__ import annotations + +import os +from types import SimpleNamespace + +import pytest + +CHECKPOINT = os.environ.get("FREETOKEN_INKLING2_MODEL", "") +END_SAMPLING = "<|content_model_end_sampling|>" + +TOOLS = [ + {"type": "function", "function": {"name": "read", "description": "Read a file.", "parameters": { + "type": "object", "properties": {"path": {"type": "string"}}}}}, + {"type": "function", "function": {"name": "write", "parameters": { + "type": "object", "properties": {"path": {"type": "string"}, "lines": {"type": "array"}, "opts": {"type": "object"}}}}}, +] + + +def _call(name: str, arguments: dict) -> dict: + return {"type": "function", "function": {"name": name, "arguments": arguments}} + + +# assistant turns as a client sends them back; the template renders each part as its own message +_TURNS = ( + {"content": "Plain answer."}, + {"reasoning_content": "Think about a < b first.", "content": "Use bold and a<|tag here.\n\nBye."}, + {"reasoning_content": "Read it first.", "content": "", "tool_calls": [_call("read", {"path": "a.py"})]}, + { + "reasoning_content": "Both, then write.\nTwo lines.", + "content": "Let me check.\n", + "tool_calls": [ + _call("read", {"path": "a.py"}), + _call("write", {"path": "b \"q\".py", "lines": [1, 2.5, None], "opts": {"z": True, "a": {"x": "日本 \\ }"}}}), + ], + }, + {"content": "", "tool_calls": [_call("read", {})]}, +) + + +def _serve(text: str, chunk: int | None): + """(reasoning, content, calls) the server returns for ``text``, streamed in ``chunk``-char deltas or not.""" + import asyncio + + from freetoken.message.frontend import UserReply + from freetoken.server.generation import ( + ContentDelta, GenSpec, ReasoningDelta, ToolCallsDelta, generate_events, generate_full, + ) + + pieces = [text] if chunk is None else [text[i:i + chunk] for i in range(0, len(text), chunk)] + + class State: + config = SimpleNamespace(tool_call_parser="inkling2", reasoning_parser="inkling2") + + async def wait_for_ack(self, uid): + for i, piece in enumerate(pieces): + yield UserReply(uid=uid, incremental_output=piece, finished=i == len(pieces) - 1, finish_reason=None, + prompt_tokens_delta=0, completion_tokens_delta=1) + + spec = GenSpec(messages=[], sampling_params=None, parser_tools=TOOLS, template_tools=TOOLS) + if chunk is None: + r = asyncio.run(generate_full(0, spec, State())) + return r.reasoning, r.content, [(c.name, c.parameters) for c in r.tool_calls] + + async def events(): + return [ev async for ev in generate_events(0, spec, State())] + + evs = asyncio.run(events()) + return ( + "".join(ev.text for ev in evs if isinstance(ev, ReasoningDelta)), + "".join(ev.text for ev in evs if isinstance(ev, ContentDelta)), + [(c.name, c.parameters) for ev in evs if isinstance(ev, ToolCallsDelta) for c in ev.calls], + ) + + +@pytest.mark.needs_weights +@pytest.mark.parametrize("chunk", [None, 1, 3]) +def test_a_parsed_turn_sent_back_renders_to_the_generated_text(chunk): + from transformers import AutoTokenizer + + from freetoken.server.generation import render_messages + + if not os.path.exists(os.path.join(CHECKPOINT, "chat_template.jinja")): + pytest.skip("set FREETOKEN_INKLING2_MODEL") + tokenizer = AutoTokenizer.from_pretrained(CHECKPOINT) + user = {"role": "user", "content": "Hi."} + prompt = tokenizer.apply_chat_template([user], tools=TOOLS, tokenize=False) + for turn in _TURNS: + full = tokenizer.apply_chat_template([user, {"role": "assistant", **turn}], tools=TOOLS, tokenize=False) + assert full.startswith(prompt) and full.endswith(END_SAMPLING) + # the model opens its own turn after the prompt; the detokenizer drops the stop token + generated = full[len(prompt):-len(END_SAMPLING)] + reasoning, content, calls = _serve(generated, chunk) + back = {"role": "assistant", "content": content, "reasoning_content": reasoning or None, + "tool_calls": [{"type": "function", "function": {"name": n, "arguments": a}} for n, a in calls] or None} + rendered = tokenizer.apply_chat_template(render_messages([user, back]), tools=TOOLS, tokenize=False) + assert rendered == full, (generated, reasoning, content, calls) diff --git a/tests/models/inkling2_loop/test_inkling2_vision.py b/tests/models/inkling2_loop/test_inkling2_vision.py new file mode 100644 index 0000000000..04617ce0de --- /dev/null +++ b/tests/models/inkling2_loop/test_inkling2_vision.py @@ -0,0 +1,224 @@ +"""Inkling 2 image processor and vision tower against transformers' Inkling2ImageProcessor and Inkling2VisionModel +(huggingface/transformers#51050), on random weights and on the Inkling-2-Mini checkpoint.""" + +from __future__ import annotations + +import io +import json +import os +import re +from types import SimpleNamespace + +import numpy as np +import pytest +import torch + +pytest.importorskip("transformers.models.inkling2", reason="needs transformers with Inkling 2 (huggingface/transformers#51050)") +from transformers.models.inkling2.image_processing_inkling2 import Inkling2ImageProcessor # noqa: E402 + +from freetoken.mm import restore_placeholder # noqa: E402 +from freetoken.mm.config import MultimodalConfig # noqa: E402 +from freetoken.mm.processors.inkling2 import IMAGE_TOKEN_ID, Inkling2MMProcessor, preprocess # noqa: E402 + +CHECKPOINT = os.environ.get("FREETOKEN_INKLING2_MODEL", "") +needs_checkpoint = pytest.mark.skipif( + not os.path.exists(os.path.join(CHECKPOINT, "config.json")), reason="FREETOKEN_INKLING2_MODEL not set" +) +needs_cuda = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA") + + +def _image(mode: str, width: int, height: int, seed: int = 0): + from PIL import Image + + rng = np.random.default_rng(seed) + if mode == "P": + image = Image.fromarray(rng.integers(0, 256, (height, width, 3), dtype=np.uint8)).quantize(16) + image.info["transparency"] = 3 + return image + channels = {"L": 1, "LA": 2, "RGB": 3, "RGBA": 4}[mode] + pixels = rng.integers(0, 256, (height, width, channels), dtype=np.uint8) + return Image.fromarray(pixels[..., 0] if channels == 1 else pixels, mode) + + +def _png(image) -> bytes: + buf = io.BytesIO() + image.save(buf, format="PNG") + return buf.getvalue() + + +# odd sizes pad both edges; alpha and palette transparency take the checkerboard composite +@pytest.mark.parametrize( + "mode, width, height", + [("RGB", 123, 77), ("RGB", 120, 80), ("RGB", 7, 5), ("L", 90, 50), ("RGBA", 83, 61), ("LA", 45, 45), ("P", 64, 48)], +) +def test_tiles_match_the_reference_processor_pixel_for_pixel(mode, width, height): + image = _image(mode, width, height) + want = Inkling2ImageProcessor()(images=image, return_tensors="pt") + tiles, rows, cols = preprocess(image, 40) + assert [1, rows, cols] == want["image_grid_thw"][0].tolist() + assert torch.equal(tiles, want["pixel_values"]) + + +def test_each_placeholder_expands_to_one_token_per_tile_of_its_own_image(): + """Two images through apply: the request bytes keep their alpha, and each span is the image's own tile count.""" + hf_config = SimpleNamespace(vision_config=SimpleNamespace(native_patch_size=20, adapter_merge_size=2)) + processor = Inkling2MMProcessor(hf_config, "/unused", MultimodalConfig()) + images = [_image("RGBA", 83, 61, seed=1), _image("RGB", 200, 41, seed=2)] + ids = torch.tensor([5, IMAGE_TOKEN_ID, 6, 7, IMAGE_TOKEN_ID, 8]) + result = processor.apply(ids, [_png(im) for im in images]) + reference = Inkling2ImageProcessor() + expected = [5] + for item, image, tail in zip(result.mm_items, images, ([6, 7], [8])): + want = reference(images=image, return_tensors="pt") + n = int(want["image_grid_thw"][0].prod()) + assert torch.equal(item.feature, want["pixel_values"].to(torch.bfloat16)) + assert item.offsets == [[len(expected), len(expected) + n]] + expected += [IMAGE_TOKEN_ID] * n + tail + assert restore_placeholder(result.input_ids, IMAGE_TOKEN_ID).tolist() == expected + assert result.mrope_positions is None + + +@needs_checkpoint +def test_prompt_matches_the_reference_processor_on_the_checkpoint(): + """The chat template's placeholder, expanded by us, gives the ids transformers' Inkling2Processor gives.""" + from transformers import AutoProcessor, AutoTokenizer + + from freetoken.utils import cached_load_hf_config + + image = _image("RGBA", 161, 95, seed=3) + messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is this?"}]}] + hf = AutoProcessor.from_pretrained(CHECKPOINT) + text = hf.apply_chat_template(messages, tokenize=False) + want = hf(text=text, images=[image], return_tensors="pt")["input_ids"][0] + ids = torch.tensor(AutoTokenizer.from_pretrained(CHECKPOINT)(text, add_special_tokens=False)["input_ids"]) + ours = Inkling2MMProcessor(cached_load_hf_config(CHECKPOINT), CHECKPOINT, MultimodalConfig()) + got = ours.apply(ids, [_png(image)]).input_ids + assert restore_placeholder(got, ours.image_token_id).tolist() == want.tolist() + + +# ---------------------------------------------------------------------------- tower + + +@pytest.fixture +def _single_rank(): + from freetoken.distributed import set_tp_info, try_get_tp_info + + if try_get_tp_info() is None: + set_tp_info(rank=0, size=1) + + +def _hf_names(state: dict) -> dict: + """Our tower's tensors under the names transformers loads the checkpoint's model.visual.* into.""" + from transformers.conversion_mapping import get_checkpoint_conversion_mapping + + renames = [ + (src, dst) + for rule in get_checkpoint_conversion_mapping("inkling2") + if type(rule).__name__ == "WeightRenaming" + for src, dst in zip(rule.source_patterns, rule.target_patterns) + ] + out = {} + for key, value in state.items(): + name = f"model.visual.{key}" + for src, dst in renames: + name = re.sub(src, dst, name) + assert name.startswith("model.vision_tower."), name + out[name[len("model.vision_tower."):]] = value + return out + + +def _reference_tower(config, state: dict, dtype: torch.dtype): + from transformers.models.inkling2.modeling_inkling2 import Inkling2VisionModel as HFVision + + config._attn_implementation = "sdpa" + tower = HFVision(config).to("cuda", dtype).eval() + missing, unexpected = tower.load_state_dict({k: v.to("cuda", dtype) for k, v in _hf_names(state).items()}, strict=False) + # the rope tables are buffers the reference builds itself + assert not unexpected and all("rotary_emb" in k for k in missing), (missing, unexpected) + return tower + + +def _build(vc, dtype): + from freetoken.models.inkling2_loop.vision import Inkling2VisionModel + + torch.set_default_dtype(dtype) + try: + with torch.device("cuda"): + return Inkling2VisionModel(vc) + finally: + torch.set_default_dtype(torch.float32) + + +@needs_cuda +@pytest.mark.parametrize("placement", ["gpu", "host"]) +def test_tower_matches_the_reference_on_random_weights(_single_rank, placement): + """A 4x4 position table resampled up and down, two images of different grids encoded one at a time against the + reference's packed batch.""" + from transformers.models.inkling2.configuration_inkling2 import Inkling2VisionConfig + + from freetoken.models.inkling2_loop.vision import parse_vision_config + + config = Inkling2VisionConfig( + hidden_size=64, num_hidden_layers=3, num_attention_heads=4, patch_size=4, spatial_merge_size=2, + posemb_grid_size=4, projection_hidden_dim=96, text_hidden_size=48, + ) + vc = parse_vision_config(SimpleNamespace(vision_config=config)) + tower = _build(vc, torch.float32) + torch.manual_seed(0) + for value in tower.state_dict().values(): + value.normal_(0, 0.1) + reference = _reference_tower(config, tower.state_dict(), torch.float32) + tower.place_weights(placement) + + grids = [(2, 3), (3, 1)] + pixels = [torch.rand(r * c, 8, 8, 3) * 2 - 1 for r, c in grids] + with torch.no_grad(): + want = reference( + pixel_values=torch.cat(pixels).cuda(), image_grid_thw=torch.tensor([[1, r, c] for r, c in grids]) + ).pooler_output + got = torch.cat([tower.forward(p, [1, r, c]) for p, (r, c) in zip(pixels, grids)]) + assert got.shape == (sum(r * c for r, c in grids), 48) + torch.testing.assert_close(got, want, rtol=1e-5, atol=1e-5) + + +def _visual_tensors(path: str) -> dict: + from safetensors import safe_open + + with open(os.path.join(path, "model.safetensors.index.json")) as f: + shards = {v for k, v in json.load(f)["weight_map"].items() if k.startswith("model.visual.")} + out = {} + for shard in shards: + with safe_open(os.path.join(path, shard), framework="pt") as f: + for key in f.keys(): + if key.startswith("model.visual."): + out[key[len("model.visual."):]] = f.get_tensor(key) + return out + + +@needs_checkpoint +@needs_cuda +def test_tower_matches_the_reference_on_the_checkpoint(_single_rank): + """bf16 like the engine; the bar is the reference's own bf16 error against its fp32 run.""" + from transformers import AutoConfig + + from freetoken.models.inkling2_loop.vision import parse_vision_config + from freetoken.utils import cached_load_hf_config + + stored = _visual_tensors(CHECKPOINT) + tower = _build(parse_vision_config(cached_load_hf_config(CHECKPOINT)), torch.bfloat16) + # every checkpoint tensor under model.visual loads by its own name, none left over or missing + tower.load_state_dict({k: v.cuda() for k, v in stored.items()}) + + config = AutoConfig.from_pretrained(CHECKPOINT).vision_config + tiles, rows, cols = preprocess(_image("RGB", 333, 217, seed=4), 40) + grid = torch.tensor([[1, rows, cols]]) + with torch.no_grad(): + want32 = _reference_tower(config, stored, torch.float32)(pixel_values=tiles.cuda(), image_grid_thw=grid).pooler_output + want16 = _reference_tower(config, stored, torch.bfloat16)(pixel_values=tiles.cuda(), image_grid_thw=grid).pooler_output + got = tower.forward(tiles.to(torch.bfloat16), [1, rows, cols]) + assert got.shape == (rows * cols, 2304) and got.dtype == torch.bfloat16 + + def rel(x): + return ((x.float() - want32).norm() / want32.norm()).item() + + assert rel(got) <= 1.25 * rel(want16), (rel(got), rel(want16)) diff --git a/tests/models/inkling2_loop/test_moe.py b/tests/models/inkling2_loop/test_moe.py new file mode 100644 index 0000000000..63678aca9b --- /dev/null +++ b/tests/models/inkling2_loop/test_moe.py @@ -0,0 +1,39 @@ +"""Router and expert activation against the references checked against transformers #51050 +(``Inkling2LoopTopKRouter``, ``Inkling2LoopSoftcappedSwiGLU``).""" + +from __future__ import annotations + +import pytest +import torch + +from .reference import route as ref_route +from .reference import softcap_swiglu as ref_swiglu + + +def test_route_matches_reference(): + from freetoken.models.inkling2_loop.moe import route + + g = torch.Generator().manual_seed(0) + x = torch.randn(97, 2304, generator=g).to(torch.bfloat16) + weight = torch.randn(128, 2304, generator=g) * 0.02 + # a bias large enough to change the pick: selection uses score + bias, the weights the bare score + bias = torch.randn(128, generator=g) * 0.2 + w, ids = route(x, weight, bias, 8, 8.0) + order = ids.long().argsort(-1) + w_ref, ids_ref = ref_route(x, weight, bias, 8, 8.0) + assert torch.equal(ids.long().gather(1, order), ids_ref) + assert torch.allclose(w.gather(1, order), w_ref, atol=1e-6) + assert not torch.equal(ids_ref, ref_route(x, weight, torch.zeros_like(bias), 8, 8.0)[1]) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA (Triton)") +def test_softcap_swiglu_kernel(): + from freetoken.layers import gated_act_and_mul + + g = torch.Generator().manual_seed(1) + # gate past its cap of 4 and up past 25 on many elements, where the caps bend the result + x = (torch.randn(257, 2 * 1152, generator=g) * torch.tensor([8.0] * 1152 + [40.0] * 1152)).to("cuda", torch.bfloat16) + out = torch.empty(257, 1152, device="cuda", dtype=torch.bfloat16) + gated_act_and_mul("swiglu_softcap", x, out, alpha=4.0, limit=25.0) + ref = ref_swiglu(x[:, :1152], x[:, 1152:], 4.0, 25.0) + assert ((out.float() - ref).abs() / ref.abs().clamp(min=1.0)).max().item() < 1e-2 diff --git a/tests/models/inkling2_loop/test_weight.py b/tests/models/inkling2_loop/test_weight.py new file mode 100644 index 0000000000..0a5995252d --- /dev/null +++ b/tests/models/inkling2_loop/test_weight.py @@ -0,0 +1,173 @@ +"""Checkpoint transforms against the transformers #51050 conversion ops (``core_model_loading.py`` at 6173a2f679: +``Inkling2LoopDequantizeExperts``, ``Interleave(dim=1)``, ``Inkling2LoopMergeMessageQueries``), and the loop's +cache-layer numbering against ``Inkling2LoopTextModel.forward``'s ``cache_offset``.""" + +from __future__ import annotations + +from types import SimpleNamespace + +import torch + +E2M1 = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0) + + +def _hf_dequant_nvfp4(weight, scale, amax, denominator): + e2m1 = torch.tensor(E2M1) + byte = torch.arange(256) + byte_to_values = torch.stack((e2m1[byte & 0xF], e2m1[byte >> 4]), dim=-1) + values = byte_to_values[weight.long()].view(*scale.shape, 16) * scale.float()[..., None] + values = values * (amax.float() / denominator.float())[:, None, None, None] + return values.reshape(weight.shape[0], weight.shape[1], -1) + + +def _hf_interleave(t): + shape = list(t.shape) + shape[1:2] = [shape[1] // 2, 2] + return t.reshape(shape).transpose(1, 2).reshape(t.shape) + + +def test_nvfp4_experts_match_reference(): + from freetoken.models.inkling2_loop.weight import deinterleave_rows, dequant_nvfp4 + + g = torch.Generator().manual_seed(0) + E, rows, cols = 3, 8, 64 + weight = torch.randint(0, 256, (E, rows, cols // 2), generator=g, dtype=torch.uint8) + scale = (torch.rand(E, rows, cols // 16, generator=g) * 400 + 1).to(torch.float8_e4m3fn) + amax = torch.rand(E, generator=g) + 0.1 + denominator = torch.tensor([2688.0]) + ref = _hf_interleave(_hf_dequant_nvfp4(weight, scale, amax, denominator)) + # the reader keeps the packed rows: de-interleave codes and scales, then dequantize as the kernel does + got = dequant_nvfp4(deinterleave_rows(weight), deinterleave_rows(scale), amax / denominator) + assert torch.equal(got, ref) + + +def test_mxfp8_experts_match_reference(): + from freetoken.models.inkling2_loop.weight import deinterleave_rows, dequant_mxfp8 + + g = torch.Generator().manual_seed(1) + weight = (torch.randn(2, 6, 64, generator=g) * 100).to(torch.float8_e4m3fn) + scale = torch.randint(110, 120, (2, 6, 2), generator=g, dtype=torch.uint8) + ref = (weight.float().view(2, 6, 2, 32) * torch.exp2(scale.float() - 127)[..., None]).reshape(2, 6, 64) + assert torch.equal(dequant_mxfp8(deinterleave_rows(weight), deinterleave_rows(scale)), _hf_interleave(ref)) + + +def test_each_layer_is_served_in_its_stored_format(tmp_path): + """hf_quant_config.json's groups pick each layer's expert kind, and the reader hands MXFP8 rows over as stored.""" + import json + + import pytest + import safetensors.torch + + from freetoken.layers.quantization import QuantKind + from freetoken.models.inkling2_loop.config import quant_config + from freetoken.models.inkling2_loop.weight import deinterleave_rows, iter_expert_pieces + + g = torch.Generator().manual_seed(2) + E, I, H = 2, 32, 64 + base = "model.llm.layers.{}.mlp.experts." + nvfp4 = { + "w13_weight": torch.randint(0, 256, (E, 2 * I, H // 2), generator=g, dtype=torch.uint8), + "w13_weight_scale": torch.ones(E, 2 * I, H // 16).to(torch.float8_e4m3fn), + "w13_weight_amax": torch.ones(E), "w13_weight_outer_scale_denominator": torch.ones(1), + "w2_weight": torch.randint(0, 256, (E, H, I // 2), generator=g, dtype=torch.uint8), + "w2_weight_scale": torch.ones(E, H, I // 16).to(torch.float8_e4m3fn), + "w2_weight_amax": torch.ones(E), "w2_weight_outer_scale_denominator": torch.ones(1), + } + mxfp8 = { + "w13_weight": torch.randn(E, 2 * I, H, generator=g).to(torch.float8_e4m3fn), + "w13_weight_scale": torch.randint(110, 130, (E, 2 * I, H // 32), generator=g, dtype=torch.uint8), + "w2_weight": torch.randn(E, H, I, generator=g).to(torch.float8_e4m3fn), + "w2_weight_scale": torch.randint(110, 130, (E, H, I // 32), generator=g, dtype=torch.uint8), + } + tensors = {base.format(0) + k: v for k, v in nvfp4.items()} | {base.format(1) + k: v for k, v in mxfp8.items()} + safetensors.torch.save_file(tensors, str(tmp_path / "model.safetensors")) + groups = [ + {"compute_dtype": dtype, "tensors": [base.format(layer) + "w13_weight", base.format(layer) + "w2_weight"]} + for layer, dtype in ((0, "nvfp4"), (1, "mxfp8")) + ] + (tmp_path / "hf_quant_config.json").write_text(json.dumps({"model": {"parameter_groups": groups}})) + + config = quant_config(str(tmp_path), None, name_map=None, unquantized=()) + assert [config.scheme_for_name(f"model.llm.layers.{layer}.mlp.experts").kind for layer in (0, 1)] == [QuantKind.NVFP4, QuantKind.MXFP8] + + model = SimpleNamespace(num_moe_layers=2, num_experts=E) + ((layer, _, _, piece),) = iter_expert_pieces(str(tmp_path), model, QuantKind.MXFP8, layers=[1]) + assert layer == 1 and set(piece) == {"gate_up", "gate_up_scale", "down", "down_scale"} + for role, name in (("gate_up", "w13_weight"), ("gate_up_scale", "w13_weight_scale")): + assert piece[role].dtype == mxfp8[name].dtype + assert torch.equal(piece[role].view(torch.uint8), deinterleave_rows(mxfp8[name]).view(torch.uint8)) + assert torch.equal(piece["down"].view(torch.uint8), mxfp8["w2_weight"].view(torch.uint8)) + assert torch.equal(piece["down_scale"], mxfp8["w2_weight_scale"]) + with pytest.raises(ValueError, match="layer 0 experts are NVFP4; the quant config serves them as MXFP8"): + list(iter_expert_pieces(str(tmp_path), model, QuantKind.MXFP8, layers=[0])) + + +def test_message_queries_merge(): + from freetoken.models.inkling2_loop.weight import merge_message_queries + + q = torch.arange(24 * 3, dtype=torch.float32).view(24, 3) + kv = -q + merged = merge_message_queries(q, kv) + # per loop layer l: [query, key, value, mlp] = q[2l], kv[2l], kv[2l + 1], q[2l + 1] + for layer in range(12): + assert torch.equal(merged[layer], torch.stack([q[2 * layer], kv[2 * layer], kv[2 * layer + 1], q[2 * layer + 1]])) + + +def test_conv_taps_reverse_conv1d(): + from freetoken.models.inkling2_loop.weight import rename + + w = torch.randn(5, 1, 4) + name, taps = rename("model.llm.layers.3.attn_sconv.weight", w) + assert name == "model.layers.3.attn_conv" + x = torch.randn(5, 9) + out = torch.nn.functional.conv1d(x[None], w, padding=3, groups=5)[0, :, :9] + xp = torch.nn.functional.pad(x, (3, 0)) + by_lag = sum(taps[lag][:, None] * xp[:, 3 - lag : 3 - lag + 9] for lag in range(4)) + assert torch.allclose(out, by_lag, atol=1e-6) + + +def _text_config(): + """The checkpoint's text_config fields (config.json at 6e7c8248) the parser reads.""" + return SimpleNamespace( + num_hidden_layers=24, local_layer_ids=[i for i in range(24) if (i + 1) % 6], hidden_size=2304, + loop_config={"core_start": 6, "core_end": 18, "num_passes": 3, "gate_rank": 64, "is_varloop": False}, + num_attention_heads=24, num_key_value_heads=8, head_dim=128, swa_num_attention_heads=24, + swa_num_key_value_heads=8, swa_head_dim=128, sliding_window_size=1024, d_rel=16, rel_extent=1024, + log_scaling_n_floor=8192, log_scaling_alpha=0.1, qk_l2_clip_threshold=22.6, rel_l2_clip_threshold=8.0, + sconv_kernel_size=4, mlp_gate_softcap=4.0, mlp_up_softcap=25.0, route_scale=8.0, unpadded_vocab_size=200058, + n_layers_per_attn_res_block=6, vocab_size=201024, model_max_length=1048576, rms_norm_eps=1e-6, + intermediate_size=1152, n_routed_experts=128, num_experts_per_tok=8, final_logit_softcapping=30.0, + ) + + +def test_quantized_kv_is_refused_at_config_time(): + import pytest + + from freetoken.engine.engine import _validate_kv_format + from freetoken.kvcache.format import FP8_PER_TOKEN_HEAD, INT8_PER_TOKEN_HEAD, NONE + from freetoken.models.inkling2_loop.config import parse_config + + model_config = parse_config(SimpleNamespace(architectures=["Inkling2LoopForConditionalGeneration"], text_config=_text_config())) + engine = SimpleNamespace(dtype=torch.bfloat16, tp_info=SimpleNamespace(size=1)) + # the pool and the triton backend both store these, but the relative-bias kernel reads no row scales + for fmt in (FP8_PER_TOKEN_HEAD, INT8_PER_TOKEN_HEAD): + with pytest.raises(ValueError, match="reads only"): + _validate_kv_format(SimpleNamespace(kv_format=fmt, **vars(engine)), model_config) + _validate_kv_format(SimpleNamespace(kv_format=NONE, **vars(engine)), model_config) + + +def test_cache_layers_follow_reference_offsets(): + from freetoken.models.inkling2_loop.config import parse_args + + args = parse_args(_text_config()) + # the reference's call order: prelude, pass 1 at the layer's own cache layer, passes 2.. at layer + cache_offset, coda + calls = [(i, i) for i in range(6)] + [(i, i) for i in range(6, 18)] + for loop_idx in (1, 2): + cache_offset = 24 + (loop_idx - 1) * 12 - 6 + calls += [(i, i + cache_offset) for i in range(6, 18)] + calls += [(i, i) for i in range(18, 24)] + sched = args.schedule() + assert [layer for layer, _ in sched] == [layer for layer, _ in calls] + assert [args.cache_layer(layer, p) for layer, p in sched] == [c for _, c in calls] + assert [args.access(layer, p) for layer, p in sched] == list(range(48)) + assert sorted(args.cache_layers_of(True) + args.cache_layers_of(False)) == list(range(48)) diff --git a/tests/moe/test_gpt_oss.py b/tests/moe/test_gpt_oss.py index 1dbf1f16b6..f8989d0839 100644 --- a/tests/moe/test_gpt_oss.py +++ b/tests/moe/test_gpt_oss.py @@ -260,7 +260,7 @@ def test_offload_prefill_overlap_matches_reference(M, tp1): E, H, tk = c.num_experts, c.hidden_size, c.num_experts_per_tok cache = _make_offload_cache(c, dev, prefill_overlap=True) - # layer_id=0 is mandatory: _wait_prefill_overlap gates begin_prefill() on layer_id==0, + # layer_id=0 is mandatory: the prefill's first MoE call (layer 0) runs begin_prefill(), # so only layer 0 exercises the previously-crashing code path. layer = _offload_layer(c, 0, cache) diff --git a/tests/moe/test_mixed_expert_formats.py b/tests/moe/test_mixed_expert_formats.py index f8c32065c1..e183e61d1a 100644 --- a/tests/moe/test_mixed_expert_formats.py +++ b/tests/moe/test_mixed_expert_formats.py @@ -1,8 +1,9 @@ """Experts of several formats in one model: bf16 and MXFP8 layers next to NVFP4 layers. A checkpoint may leave some MoE layers unquantized (Muse Spark keeps its first and last layer's -experts bf16) or store them in another format (Inkling-2 keeps its last layers' experts MXFP8). Each format fills its own layers' banks, the banks merge over the union of roles with -zero-byte placeholders, the slot cache keeps one pool per format, the FTW stores each layer's own +experts bf16) or store them in another format (Inkling-2 keeps its last layers' experts MXFP8). Each format +fills its own layers' banks, the banks merge over the union of roles with zero-byte placeholders, the slot +cache keeps one pool per format, resident layers each take their own roles, the FTW stores each layer's own banks, and the CPU executor computes each layer in its format. """ @@ -20,6 +21,8 @@ E, H, I, TOPK = 8, 256, 128, 2 FORMATS = ["bf16", "nvfp4", "nvfp4", "nvfp4", "bf16", "mxfp8"] L = len(FORMATS) +# (activation, alpha, limit); swiglu_softcap is Inkling 2's form, with caps the test inputs reach +ACTS = {"silu": ("silu", 1.0, None), "swiglu_softcap": ("swiglu_softcap", 1.5, 6.0)} _E2M1 = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0]) @@ -29,7 +32,7 @@ def _init_tp(): set_tp_info(rank=0, size=1) -def _layer(layer_id: int, fmt: str): +def _layer(layer_id: int, fmt: str, act: str = "silu"): from freetoken.layers.moe import OffloadMoELayer from freetoken.layers.quantization import NoQuantConfig, QuantBackend, QuantConfig, set_quant_backend @@ -41,7 +44,9 @@ def _layer(layer_id: int, fmt: str): else: set_quant_backend(QuantBackend.parse("moe.nvfp4=triton")) quant = QuantConfig.from_hf({"quantization_config": {"quant_method": "modelopt", "quant_algo": "NVFP4", "ignore": ["lm_head"]}}) - return OffloadMoELayer(layer_id, E, TOPK, H, I, quant_config=quant, prefix=f"model.layers.{layer_id}.mlp.experts") + activation, alpha, limit = ACTS[act] + return OffloadMoELayer(layer_id, E, TOPK, H, I, activation=activation, alpha=alpha, limit=limit, quant_config=quant, + prefix=f"model.layers.{layer_id}.mlp.experts") def _dequant(packed, scale, row_global): @@ -102,15 +107,22 @@ def _weights(pieces, layer): return gu, dn -def _reference(pieces, layer, hidden, weights, ids): +def _gated(h, act): + gate, up = h[:I], h[I:] + if act == "silu": + return torch.nn.functional.silu(gate) * up + _, alpha, limit = ACTS[act] + return alpha * torch.tanh(gate / alpha) * torch.sigmoid(gate) * limit * torch.tanh(up / limit) + + +def _reference(pieces, layer, hidden, weights, ids, act="silu"): gu, dn = _weights(pieces, layer) out = torch.zeros(hidden.shape, dtype=torch.float32) x = hidden.float().cpu() for t in range(hidden.shape[0]): for k in range(ids.shape[1]): e = int(ids[t, k]) - h = gu[e] @ x[t] - out[t] += float(weights[t, k]) * (dn[e] @ (torch.nn.functional.silu(h[:I]) * h[I:])) + out[t] += float(weights[t, k]) * (dn[e] @ _gated(gu[e] @ x[t], act).bfloat16().float()) return out @@ -118,10 +130,10 @@ def _assert_close(out, ref): torch.testing.assert_close(out.float().cpu(), ref, rtol=3e-2, atol=0.03 * float(ref.abs().max())) -def _mixed_banks(pieces, device, layer_sink=None): +def _mixed_banks(pieces, device, layer_sink=None, act="silu"): from freetoken.moe.expert_banks import build_expert_banks, merge_expert_banks, method_groups - methods = [_layer(layer, fmt).quant_method for layer, fmt in enumerate(FORMATS)] + methods = [_layer(layer, fmt, act).quant_method for layer, fmt in enumerate(FORMATS)] parts = [ build_expert_banks(method, L, _reader(pieces, method.kind), device=device, layer_sink=layer_sink, layers=layers) for method, layers in method_groups(methods) @@ -129,16 +141,17 @@ def _mixed_banks(pieces, device, layer_sink=None): return merge_expert_banks(parts, methods, E), methods -def _mixed_cache(device, pieces, *, decode_target="gpu", prefill_overlap=False): +def _mixed_cache(device, pieces, *, decode_target="gpu", prefill_overlap=False, act="silu", staging_only=False): from freetoken.moe.offload_cache import OffloadMoeCache, bank_layouts - from freetoken.moe.pool_policy import group_layers, make_pools, pool_of_layer, split_slots + from freetoken.moe.pool_policy import group_layers, make_pools, pool_of_layer, pool_row_bytes, split_slots, staging_slots from freetoken.engine.cache_budget import layer_slot_bytes - banks, methods = _mixed_banks(pieces, device) + banks, methods = _mixed_banks(pieces, device, act=act) slot_bytes = layer_slot_bytes(banks.sources) groups = group_layers("unified", bank_layouts(banks.sources, banks.layer_tags), slot_bytes) pools = make_pools(groups, E, TOPK, None) - sizes = split_slots(6 * E, pools) + # staging_only: the engine's --moe-strategy cpu sizing, where the slots only back the prefill double buffer + sizes = staging_slots(*pool_row_bytes(banks.sources, banks.row_tail_bytes, pools), E) if staging_only else split_slots(6 * E, pools) cache = OffloadMoeCache( num_layers=L, num_experts=E, cache_size=sum(sizes), device=device, quant_format=banks.quant_format, decode_target=decode_target, hybrid_max_fetch=1, prefill_overlap=prefill_overlap, @@ -146,7 +159,7 @@ def _mixed_cache(device, pieces, *, decode_target="gpu", prefill_overlap=False): ) cache.set_bank_sources(banks.sources, layer_tags=banks.layer_tags) cache.reset() - layers = [_layer(layer, fmt) for layer, fmt in enumerate(FORMATS)] + layers = [_layer(layer, fmt, act) for layer, fmt in enumerate(FORMATS)] for layer in layers: layer.offload_cache = cache return cache, layers, banks @@ -252,32 +265,169 @@ def test_mixed_layers_decode_and_prefill_through_their_pools(): _assert_close(out, _reference(pieces, layer.layer_id, hidden[:1], weights[:1], ids)) +def _prefill_batch(device, seed): + g = torch.Generator().manual_seed(seed) + M = 16 + hidden = (torch.randn(M, H, generator=g) / 4).to(device, torch.bfloat16) + ids = torch.stack([torch.randperm(E, generator=g)[:TOPK] for _ in range(M)]).to(torch.int32) + weights = torch.rand(M, TOPK, generator=g).to(device) + return hidden, ids, weights + + +# a looped model runs layers 2-3 twice, steps 4 -> 2 at the same layer parity and ends on layer 3, not the last layer +LOOPED_ORDER = (0, 1, 2, 3, 4, 2, 3) + + @cuda -def test_cpu_executor_computes_each_layer_in_its_format(): - pytest.importorskip("freetoken.kernel._cpu_moe") - from freetoken.moe.cpu_executor import CpuMoeExecutor +@pytest.mark.parametrize("prefill_overlap", [False, True]) +def test_looped_order_prefills_and_clears_the_staging(prefill_overlap): + device = torch.device("cuda") + pieces = _pieces() + cache, layers, _ = _mixed_cache(device, pieces, prefill_overlap=prefill_overlap) + cache.set_layer_order(LOOPED_ORDER) + assert cache.prefill_overlap == prefill_overlap + hidden, ids, weights = _prefill_batch(device, 1) + for _ in range(2): # the order's cursor wraps for the next forward + for layer_id in LOOPED_ORDER: + out = layers[layer_id]._prefill_routed(hidden.clone(), weights, ids.to(device)) + _assert_close(out, _reference(pieces, layer_id, hidden, weights, ids)) + assert not any(cache._stage_dirty), "staged rows left after the forward's last MoE call" - torch.manual_seed(1) + +@cuda +@pytest.mark.parametrize("prefill_overlap", [False, True]) +def test_prefill_after_a_forward_that_stopped_midway(prefill_overlap): device = torch.device("cuda") - pieces = _pieces(seed=1) - cache, layers, _ = _mixed_cache(device, pieces, decode_target="hybrid") + pieces = _pieces() + cache, layers, _ = _mixed_cache(device, pieces, prefill_overlap=prefill_overlap) + cache.set_layer_order(LOOPED_ORDER) + hidden, ids, weights = _prefill_batch(device, 2) + # a forward that dies after its fourth MoE call (an OOM in the next layer) never reaches the end of the order + for layer_id in LOOPED_ORDER[:4]: + layers[layer_id]._prefill_routed(hidden.clone(), weights, ids.to(device)) + for layer_id in LOOPED_ORDER: + out = layers[layer_id]._prefill_routed(hidden.clone(), weights, ids.to(device)) + _assert_close(out, _reference(pieces, layer_id, hidden, weights, ids)) + assert not any(cache._stage_dirty) + + +def test_layer_order_refuses_a_repeated_first_layer(): + from freetoken.moe.offload_cache import OffloadMoeCache + + cache = OffloadMoeCache.__new__(OffloadMoeCache) + cache.num_layers = L + with pytest.raises(ValueError, match="runs it again"): + cache.set_layer_order((0, 1, 0)) + with pytest.raises(ValueError, match="leaves"): + cache.set_layer_order((0, L)) + + +@cuda +def test_resident_layers_each_read_their_own_format(monkeypatch): + from freetoken.layers.moe import MoELayer + from freetoken.layers.quantization import NoQuantConfig, QuantBackend, QuantConfig, set_quant_backend + from freetoken.moe import expert_pieces + from freetoken.moe.expert_banks import attach_resident_banks, load_expert_banks + + from freetoken.utils.torch_utils import torch_dtype + + _init_tp() + set_quant_backend(QuantBackend.parse("moe.nvfp4=triton")) + quants = {"bf16": NoQuantConfig()} | { + fmt: QuantConfig.from_hf({"quantization_config": {"quant_method": "modelopt", "quant_algo": algo, "ignore": ["lm_head"]}}) + for fmt, algo in (("nvfp4", "NVFP4"), ("mxfp8", "MXFP8")) + } + # resident experts compute in the model dtype the engine builds them under + with torch_dtype(torch.bfloat16): + layers = [ + MoELayer(E, TOPK, H, I, layer_id=layer, quant_config=quants[fmt], prefix=f"model.layers.{layer}.mlp.experts") + for layer, fmt in enumerate(FORMATS) + ] + pieces = _pieces(seed=3) + monkeypatch.setattr(expert_pieces, "iter_expert_pieces", lambda path, config, kind, *, layers=None, **kw: ( + p for p in _reader(pieces, kind) if p[0] in layers)) + config = SimpleNamespace(num_moe_layers=L, num_experts=E) + device = torch.device("cuda") + banks = load_expert_banks("", config, method=layers[1].quant_method, device=device, parallel=False, resident=True, + layer_methods=[layer.quant_method for layer in layers]) + attach_resident_banks(layers, banks) + M = 16 + hidden = torch.randn(M, H, dtype=torch.bfloat16, device=device) / 4 + ids = torch.stack([torch.randperm(E)[:TOPK] for _ in range(M)]).to(torch.int32) + weights = torch.rand(M, TOPK, device=device) + for layer in layers: + assert all(t.device.type == "cuda" for t in layer._expert_banks.values()) + method = layer.quant_method + out = method.apply(hidden.clone(), weights, ids.to(device), method.resident_view(layer), layer=layer, is_prefill=True) + _assert_close(out, _reference(pieces, layer.layer_id, hidden, weights, ids)) + + +def _executor(cache, act, device): + from freetoken.moe.cpu_executor import CpuMoeExecutor + + activation, alpha, limit = ACTS[act] ex = CpuMoeExecutor( - cache, top_k=TOPK, activation="silu", apply_router_weight_on_input=False, num_threads=2, - max_tokens=4, device=device, layer_formats=[(f, {}) for f in FORMATS], + cache, top_k=TOPK, activation=activation, apply_router_weight_on_input=False, num_threads=2, + max_tokens=4, device=device, swiglu_alpha=alpha, swiglu_limit=limit, layer_formats=[(f, {}) for f in FORMATS], ) cache.set_cpu_executor(ex) + return ex + + +@cuda +@pytest.mark.parametrize("act", list(ACTS)) +def test_cpu_executor_computes_each_layer_in_its_format(act, monkeypatch): + pytest.importorskip("freetoken.kernel._cpu_moe") + # the fp32 NVFP4 dots: the W4A8 int8 activations would hide an epilogue error behind their rounding + monkeypatch.setenv("FREETOKEN_CPU_MOE_NO_VNNI", "1") + torch.manual_seed(1) + device = torch.device("cuda") + pieces = _pieces(seed=1) + cache, layers, _ = _mixed_cache(device, pieces, decode_target="hybrid", act=act) + ex = _executor(cache, act, device) bs = 3 - hidden = torch.randn(bs, H, dtype=torch.bfloat16, device=device) / 4 + # gate and up spread past the softcaps + hidden = torch.randn(bs, H, dtype=torch.bfloat16, device=device) * 4 weights = torch.rand(bs, TOPK, device=device) for layer in range(L): ids = torch.stack([torch.randperm(E)[:TOPK] for _ in range(bs)]).to(torch.int32) - _assert_close(ex.decode(layer, hidden, weights, ids.to(device)), _reference(pieces, layer, hidden, weights, ids)) + out = ex.decode(layer, hidden, weights, ids.to(device)).float().cpu() + ref = _reference(pieces, layer, hidden, weights, ids, act) + # bf16 output rounding is ~4e-3 of the largest value; a misplaced cap or sigmoid argument is several times that + assert (out - ref).abs().max() <= 1e-2 * ref.abs().max(), (FORMATS[layer], act) # hybrid: capped PCIe fetch on the GPU, the overflow misses on the CPU, per layer format for _ in range(3): for layer in layers: ids = torch.stack([torch.randperm(E)[:TOPK] for _ in range(bs)]).to(torch.int32) out = layer._decode_routed(hidden, weights, ids.clone().to(device)) - _assert_close(out, _reference(pieces, layer.layer_id, hidden, weights, ids)) + _assert_close(out, _reference(pieces, layer.layer_id, hidden, weights, ids, act)) + + +@cuda +def test_cpu_strategy_stages_every_format_twice(): + """--moe-strategy cpu: the slots only back the prefill double buffer, two layers of each format's widest bank rows. + + Goes red if the staging sizing undercounts a bank: overlap is then turned off or a layer stages into another's bytes.""" + pytest.importorskip("freetoken.kernel._cpu_moe") + torch.manual_seed(3) + device = torch.device("cuda") + pieces = _pieces(seed=3) + cache, layers, _ = _mixed_cache(device, pieces, decode_target="cpu", prefill_overlap=True, staging_only=True) + assert cache.prefill_overlap and len(cache.pool_sizes) == len(set(FORMATS)) + cache.cpu_layer_ids = frozenset(range(L)) + _executor(cache, "silu", device) + M = 16 + hidden = torch.randn(M, H, dtype=torch.bfloat16, device=device) / 4 + ids = torch.stack([torch.randperm(E)[:TOPK] for _ in range(M)]).to(torch.int32) + weights = torch.rand(M, TOPK, device=device) + cache.begin_prefill() + for layer in layers: + out = layer._prefill_routed(hidden.clone(), weights, ids.to(device)) + _assert_close(out, _reference(pieces, layer.layer_id, hidden, weights, ids)) + for layer in layers: + ids = torch.randperm(E)[:TOPK].to(torch.int32).view(1, TOPK) + out = layer._decode_routed(hidden[:1], weights[:1], ids.clone().to(device)) + _assert_close(out, _reference(pieces, layer.layer_id, hidden[:1], weights[:1], ids)) @cuda diff --git a/tests/server/test_streaming_model_matrix.py b/tests/server/test_streaming_model_matrix.py index d6c84e1ce3..c108d3cecc 100644 --- a/tests/server/test_streaming_model_matrix.py +++ b/tests/server/test_streaming_model_matrix.py @@ -105,6 +105,10 @@ "/tmp/test_calc.py\n" "\n<|eot|>" ), + "inkling2": ( + "<|message_model|>read<|content_invoke_tool_json|>" + '{"name":"read","args":{"filePath":"/tmp/test_calc.py"}}<|end_message|>' + ), } # Substrings that must never leak into user-visible content. @@ -122,6 +126,7 @@ "llama3": ["<|python_tag|>"], "gpt_oss": ["<|channel|>", "to=functions."], "muse_glimmer": ["", "<|eot|>"], + "inkling2": ["<|message_model|>", "<|content_invoke_tool_json|>", "<|end_message|>"], } # (tool_call_parser, reasoning_parser, think_open, think_close) per reasoning-capable @@ -142,6 +147,7 @@ "gemma4": ("gemma4", "gemma4", "<|channel>thought\n", ""), "gpt-oss": ("gpt_oss", "gpt_oss", None, None), # harmony channels; custom fixture "muse-glimmer": ("muse_glimmer", "muse_glimmer", None, None), # ATEM channels; custom fixture + "inkling2": ("inkling2", "inkling2", None, None), # TMLv0 messages; custom fixture } @@ -302,6 +308,13 @@ def _reasoning_fixture(name): + CALL_BLOCKS[tool] ) return tool, reasoning, text + if name == "inkling2": + # one message per part: thinking, visible text, then the call + text = ( + f"<|message_model|><|content_thinking|>{THINKING}<|end_message|>" + f"<|message_model|><|content_text|>{ANSWER}<|end_message|>" + CALL_BLOCKS[tool] + ) + return tool, reasoning, text text = f"{think_open}{THINKING}{think_close}{ANSWER} {CALL_BLOCKS[tool]}" return tool, reasoning, text @@ -475,6 +488,10 @@ def test_reasoning_chat_entrypoint(name): f"{LONG_VALUE}\n" "\n<|eot|>" ), + "inkling2": ( + '<|message_model|>read<|content_invoke_tool_json|>{"name":"read","args":' + f'{json.dumps({"filePath": LONG_VALUE}, separators=(",", ":"))}}}<|end_message|>' + ), } @@ -586,6 +603,11 @@ def test_two_calls_get_output_ordinals(): ["Checking. ", "read\n", "filePath/a\n"], {"filePath": "/a"}, ), + ( # raw-args family: the args object cut off before it closes + "inkling2", + ["Checking. ", "<|message_model|>read<|content_invoke_tool_json|>", '{"name":"read","args":{"filePath":"/a"'], + {"filePath": "/a"}, + ), ], ) def test_truncated_call_recovers_arguments(tool, chunks, expected_args): @@ -697,7 +719,7 @@ def test_empty_arguments_call_emitted_exactly_once(tool, block): @pytest.mark.parametrize( "family", ["qwen25", "qwen3_coder", "glm47", "gemma4", "minimax", "minimax_m3", - "deepseekv32", "gpt_oss", "muse_glimmer"], + "deepseekv32", "gpt_oss", "muse_glimmer", "inkling2"], ) def test_call_then_trailing_text_in_one_chunk_keeps_order(family): # Worst case: the whole generation arrives as ONE chunk. Text after the call