OpenViking icon indicating copy to clipboard operation
OpenViking copied to clipboard

[Bug]: embedding.max_input_tokens assumes 4 chars/token, so text truncated to "4096 tokens" arrives with up to 6090

Open godxxs opened this issue 1 month ago • 3 comments

Issue Origin

Observed or reproduced in a real environment

Bug Description

embedding.max_input_tokens bounds the text sent to the embedding provider using a character-based estimate of four characters per token for everything that is not CJK (openviking/utils/embedding_input.py:12-24):

def estimate_embedding_input_tokens(text: str) -> int:
    cjk_chars = sum(1 for char in text if ...)
    other_chars = len(text) - cjk_chars
    return max(1, cjk_chars + math.ceil(other_chars / 4))

Counting CJK at one token per character is reasonable. Assuming four characters per token for everything else holds for English prose and fails for other scripts: Cyrillic costs roughly 2-3 characters per token, and source code is denser still.

So a document truncated to "4096 tokens" can arrive with up to 6090 real tokens and be rejected by a provider whose per-slot context is 4096 — and the whole session_commit task fails, so that session's memory is never written.

Steps to Reproduce

  1. Configure embedding.max_input_tokens: 4096 and an embedding backend with a 4096-token per-slot context.
  2. Commit a session whose documents are Russian or source code.
  3. Observe session_commit tasks failing while the provider reports inputs of 4202-5819 tokens.

Measurement against the tokenizer of the configured model (llama-server /tokenize):

sample chars estimate real real/estimate real tokens when estimate = 4096
Russian markdown 10 571 2 643 3 547 1.34 5 497
English markdown 25 595 6 403 8 107 1.27 5 186
PowerShell 4 139 1 035 1 488 1.44 5 889
Python 15 731 3 933 4 005 1.02 4 171
Russian markdown 6 655 1 664 2 474 1.49 6 090

The real input at the configured bound therefore lies in 4 171-6 090 tokens.

Expected Behavior

Text truncated to max_input_tokens carries at most max_input_tokens real tokens, so a provider configured for that bound accepts it. Meeting the bound should not fail the task.

Actual Behavior

Nine session_commit tasks failed in one day with reported inputs of 4 202, 4 475, 4 673, 5 040, 5 322, 5 703, 5 730, 5 747, 5 819 tokens — every one inside the band the estimate predicts — while max_input_tokens was 4096. Each failure loses that session's extracted memory.

Minimal Reproducible Example

import math

def estimate(text):
    cjk = sum(1 for c in text if "\u4e00" <= c <= "\u9fff")
    return max(1, cjk + math.ceil((len(text) - cjk) / 4))

with open("MEMORY-STACK.md", encoding="utf-8") as fh:
    text = fh.read()

truncated = text
if estimate(text) > 4096:
    # this is what truncate_embedding_input does
    lo, hi = 0, len(text)
    while lo < hi:
        mid = (lo + hi + 1) // 2
        if estimate(text[:mid]) <= 4096:
            lo = mid
        else:
            hi = mid - 1
    truncated = text[:lo].rstrip() + "\n...(truncated for embedding)"

print("estimate:", estimate(truncated), "chars:", len(truncated))
# now send `truncated` to the tokenizer of the configured embedding model:
# a Russian markdown file truncated this way carries 5743 real tokens

Error Logs

Failed to generate embedding: OpenAI API error: Error code: 500 -
  {'error': {'code': 500, 'message': 'input (5730 tokens) is too large to process.
   increase the physical batch size (current batch size: 4096)', 'type': 'server_error'}

OpenViking Version

0.5.0

Python Version

3.13.15

Operating System

Windows

Model Backend

Other

Additional Context

Model Backend Other — local llama-server (llama.cpp) behind an OpenAI-compatible endpoint

Suggested fix.

  1. Count what the tokenizer counts. Where the provider is known, call its tokenizer. Where it is not, at least treat Cyrillic separately from Latin — two characters per token is much closer than four — and give code its own factor.
  2. Make the default conservative. Dividing by four assumes the best case. If the estimate cannot be trusted, size the truncation from the worst observed ratio.
  3. Do not let an oversized input fail the whole task. The changelog mentions classifying oversized input as input_too_large to avoid retrying it forever; the same classification should let the commit succeed by embedding a truncated document instead of losing the whole session's memory.
  4. Document the interaction. max_input_tokens and the serving stack's per-slot context are configured in different files by different people. A bound of 4096 needs a slot of at least 4096 real tokens, which the current estimate does not guarantee.

Operator-side mitigation (what we run): raising the embedding server's per-slot context above the worst real input removes the failure without touching the estimate. On llama-server, --ctx-size 32768 --parallel 4 gives n_ctx_slot = 8192, and --batch-size 8192 --ubatch-size 8192 keeps a document in one physical pass. Verified: an input truncated exactly as OpenViking truncates it carries 5 743 real tokens and returns HTTP 200 with 768 dimensions and no NaN, where it previously failed.

Suggested area / owners (from CONTRIBUTING.md): the estimate lives in openviking/utils/embedding_input.py and is consumed by the embedding queue. Routing is my guess — possibly Retrieval → @zhoujh01, @t0saki.

godxxs avatar Oct 15 '26 12:10 godxxs

Confirmed the root cause: openviking/utils/embedding_input.py (estimate_embedding_input_tokens, currently lines ~12-24) charges ceil(other_chars / 4) for every non-CJK character, and truncate_embedding_input bisects with the same estimator, so the bias propagates straight into the truncation point — Cyrillic (~2-3 chars/token) and source code get truncated to "4096 estimate tokens" that are 4100-6100 real tokens.

Working on a fix: making the chars-per-token divisor configurable with a script-class-aware default (CJK=1 char/token, Cyrillic ~0.4 token/char, other ~0.25), plus a regression test asserting truncated input stays within the real-token bound using a mock tokenizer.

Note: this fix is prepared with AI assistance (Claude), submitted by @akushonkamen.

akushonkamen avatar Oct 15 '26 12:10 akushonkamen

Thanks for reporting this. Different models use different tokenizers, so a general character-based estimate is inherently approximate and cannot guarantee that inputs stay within every model's actual token limit.

qin-ctx avatar Oct 15 '26 12:10 qin-ctx

PR 已开:#6140 —— 截断计费按脚本分级(CJK 1.0 / 西里尔 0.5 / 其余 0.4 token/字符)并为截断标记预留预算;实测费率 E2E 截断后 3140/3686/3687 真实 token,均 ≤ 4096。已 rebase 到当前 main(与 #6134 的估算函数清理合并协调)。

akushonkamen avatar Oct 15 '26 14:10 akushonkamen