DocsGPT icon indicating copy to clipboard operation
DocsGPT copied to clipboard

🐛 Bug Report: Worker needs ~10 GB of RAM to ingest an 80 MB text file (chunker tokenizes the whole document at once)

Open linghengqian opened this issue 1 month ago • 2 comments

📜 Description

I was checking how much RAM ingestion needs on a small server and found that one big plain-text file is enough to blow it up. An 80 MiB .txt (31.5M characters of Chinese text) took the Celery worker from 406 MiB to a peak of 10,316 MiB. The task ran for six minutes, and the worker was back at about 380 MiB shortly after it finished.

What matters is how much text a single document has, not the file size. The chunker hands the whole document to the token counter in one call, and the tokenizer builds its per-token data for all of it at once. With either tokenizer I tried (bge-m3, which I use, and the granite one the standalone compose defaults to) that is roughly 400 bytes of RAM per Chinese character. English text is less, about 180 per character with bge-m3. Normal documents are fine, a long Chinese report of a few hundred pages is around 1M characters and costs about 400 MiB extra while chunking. Big CSV, log or book-dump style text files are the problem: 6M characters, which is a ~16 MiB .txt, already adds 2.2 GiB.

Tested on DocsGPT 1.0.0.

👟 Reproduction steps

The first part needs nothing but the official image.

  1. Save the script below as chunk_mem.py.
  2. Run it (3M characters, about 1.7M tokens):
docker run --rm -v "$PWD/chunk_mem.py:/chunk_mem.py:ro" -w /app -e PYTHONPATH=/app \
  --entrypoint python arc53/docsgpt:1.0.0 /chunk_mem.py 3000000
  1. Try 1000000 and 6000000 as well. The script uses the bge-m3 tokenizer unless EMBEDDINGS_NAME is set, so add -e EMBEDDINGS_NAME=ibm-granite/granite-embedding-311m-multilingual-r2 for the compose default. Add -e HF_HUB_OFFLINE=1 to get the tiktoken fallback, or pass en as a second argument for English text.

To see it in the real worker, start deployment/docker-compose-standalone.yaml with remote embeddings configured, upload a big text file and watch docker stats for the worker container:

curl -X POST http://localhost:7091/api/upload -F user=local -F name=big -F [email protected]

I used an 80 MiB file with 31.5M characters of Chinese sentences, one per line. Any large text file does the same.

chunk_mem.py
"""Peak memory of DocsGPT's default chunker (classic_chunk) for one document of N characters.

Run it inside the official image, no other service is needed:

  docker run --rm -v "$PWD/chunk_mem.py:/chunk_mem.py:ro" -w /app -e PYTHONPATH=/app \
    --entrypoint python arc53/docsgpt:1.0.0 /chunk_mem.py 3000000

Optional second argument "en" uses English text instead of Chinese.
Add -e HF_HUB_OFFLINE=1 to the docker command to get the tiktoken fallback.
"""
import os
import resource
import sys
import time

os.environ.setdefault("EMBEDDINGS_NAME", "BAAI/bge-m3")
from docsgpt.parser.chunking import Chunker
from docsgpt.parser.schema.base import Document
from docsgpt.parser.tokenization import get_token_counter

SENTENCES = {
    "zh": [
        "甲方与乙方本着平等互利的原则,经友好协商,就办公设备采购及维护事宜达成如下协议。",
        "乙方应于合同签订后十五个工作日内完成全部设备的交付、安装与调试,并提供书面验收报告。",
        "合同总价款为人民币壹佰贰拾叁万肆仟伍佰元整,含税价,分三期支付。",
        "首期款为合同总价的百分之三十,于合同生效后七日内支付;二期款于设备验收合格后支付。",
        "质保期自验收合格之日起计算,为期三十六个月,质保期内乙方免费提供上门维修服务。",
        "如乙方逾期交付,每逾期一日,应按合同总价的千分之五向甲方支付违约金。",
    ],
    "en": [
        "The supplier shall deliver and install all equipment within fifteen working days of signing this agreement.",
        "The total price is one million two hundred thousand yuan including tax, payable in three instalments.",
        "The first instalment is thirty percent of the total price and is due within seven days of the agreement taking effect.",
        "The warranty period is thirty-six months from the date of acceptance and covers on-site repairs at no charge.",
        "For each day of late delivery the supplier shall pay a penalty of five per thousand of the total price.",
        "Any dispute arising from this agreement shall first be settled through friendly consultation between both parties.",
    ],
}


def rss_mib():
    with open("/proc/self/status") as f:
        for line in f:
            if line.startswith("VmRSS:"):
                return int(line.split()[1]) / 1024


chars = int(sys.argv[1])
lang = sys.argv[2] if len(sys.argv) > 2 else "zh"
counter = get_token_counter()  # loads the tokenizer, like the worker does on its first ingest

lines, size, i = [], 0, 0
while size < chars:
    line = f"{SENTENCES[lang][i % len(SENTENCES[lang])]} (no. {i:08d})\n"
    lines.append(line)
    size += len(line)
    i += 1
text = "".join(lines)
del lines

before = rss_mib()
start = time.time()
chunks = Chunker(max_tokens=1250, min_tokens=150).chunk([Document(text=text)])
seconds = time.time() - start
peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024
print(f"{type(counter).__name__}, {lang}: {len(text):,} chars -> {len(chunks)} chunks in {seconds:.1f} s, "
      f"RSS {before:.0f} -> {peak:.0f} MiB (+{peak - before:.0f} MiB, {(peak - before) * 1048576 / len(text):.0f} bytes/char)")

👍 Expected behavior

Memory while chunking shouldn't grow with the length of the document by hundreds of bytes per character. Splitting the text on blank lines or newlines into windows first, and tokenizing one window at a time, would probably keep it flat. I haven't tried a patch.

👎 Actual Behavior with Screenshots

Output of chunk_mem.py with the commands above (RSS is measured after the tokenizer is loaded, then the peak while chunking).

bge-m3 tokenizer (the script's default), Chinese text:

HuggingFaceCounter, zh: 200,022 chars -> 105 chunks in 0.8 s, RSS 379 -> 449 MiB (+69 MiB, 364 bytes/char)
HuggingFaceCounter, zh: 1,000,026 chars -> 519 chunks in 5.8 s, RSS 379 -> 751 MiB (+372 MiB, 390 bytes/char)
HuggingFaceCounter, zh: 3,000,030 chars -> 1557 chunks in 16.4 s, RSS 379 -> 1605 MiB (+1227 MiB, 429 bytes/char)
HuggingFaceCounter, zh: 6,000,051 chars -> 3119 chunks in 31.5 s, RSS 379 -> 2632 MiB (+2253 MiB, 394 bytes/char)

With -e EMBEDDINGS_NAME=ibm-granite/granite-embedding-311m-multilingual-r2 (the compose default):

HuggingFaceCounter, zh: 200,022 chars -> 125 chunks in 0.8 s, RSS 340 -> 417 MiB (+77 MiB, 404 bytes/char)
HuggingFaceCounter, zh: 1,000,026 chars -> 623 chunks in 5.0 s, RSS 340 -> 619 MiB (+279 MiB, 292 bytes/char)
HuggingFaceCounter, zh: 3,000,030 chars -> 1867 chunks in 15.1 s, RSS 339 -> 1503 MiB (+1164 MiB, 407 bytes/char)
HuggingFaceCounter, zh: 6,000,051 chars -> 3734 chunks in 33.3 s, RSS 340 -> 2518 MiB (+2178 MiB, 381 bytes/char)

With -e HF_HUB_OFFLINE=1 (falls back to tiktoken):

TiktokenCounter, zh: 1,000,026 chars -> 754 chunks in 1.0 s, RSS 105 -> 297 MiB (+192 MiB, 202 bytes/char)
TiktokenCounter, zh: 3,000,030 chars -> 2260 chunks in 3.0 s, RSS 112 -> 696 MiB (+584 MiB, 204 bytes/char)
TiktokenCounter, zh: 6,000,051 chars -> 4519 chunks in 6.0 s, RSS 116 -> 1296 MiB (+1180 MiB, 206 bytes/char)

English text with the bge-m3 tokenizer:

HuggingFaceCounter, en: 3,000,098 chars -> 562 chunks in 7.5 s, RSS 378 -> 913 MiB (+535 MiB, 187 bytes/char)
HuggingFaceCounter, en: 6,000,082 chars -> 1124 chunks in 14.1 s, RSS 380 -> 1374 MiB (+994 MiB, 174 bytes/char)

In the real worker (standalone compose, one Celery child, EMBEDDINGS_NAME=BAAI/bge-m3 with embeddings from an OpenAI-compatible endpoint, the 80 MiB file above), memory of the worker container over time:

start         406 MiB
+20 s       3,579 MiB
+120 s      7,495 MiB
+270 s      9,390 MiB
+288 s     10,316 MiB (peak)
+369 s      task done, 16,816 chunks
+389 s        381 MiB

💻 Operating system

Linux

What browsers are you seeing the problem on?

No response

🤖 What development environment are you experiencing this bug on?

Docker

🔒 Did you set the correct environment variables in the right path? List the environment variable names (not values please!)

EMBEDDINGS_NAME, EMBEDDINGS_BASE_URL, EMBEDDINGS_KEY, INTERNAL_KEY, JWT_SECRET_KEY, ENCRYPTION_SECRET_KEY. I also had LLM, OCR and STT variables set for other tests, none of them matter here. chunk_mem.py only needs EMBEDDINGS_NAME and sets it itself.

📃 Provide any additional context for the Bug.

Where it comes from, in 1.0.0:

  • classic_chunk counts the whole document first (chunking.py#L131), and split_document then splits the whole body in one call (L97, L99).
  • HuggingFaceCounter.count encodes the full text and walks encoding.offsets (tokenization.py#L181-L184). split encodes it again to get .offsets, then calls self.count(text), which encodes it a second time while the first offsets list is still alive (L193-L194).
  • RecursiveChunker._recursive_split starts the same way, with _token_count(text) on the full text (chunking_strategies.py#L98).

I profiled the encode step on 3M characters (1.73M tokens). tokenizer.encode() alone adds about 440 MiB to RSS (roughly 265 bytes per token), and .offsets adds another ~210 MiB for the Python list of tuples.

It's still the same on main. split_to_token_limit() (added after 1.0.0) starts with counter.count(piece) and counter.split(piece, limit) on the full text (tokenization.py#L162-L166), and chunking.py now goes through it. I mounted main's tokenization.py and chunking.py (d6c81ad) over the 1.0.0 image and got +1081 MiB (378 bytes/char) for 3M Chinese characters, +583 MiB with the tiktoken fallback.

Two other things I saw while measuring. With a HF tokenizer loaded the process baseline is about 380 MiB for bge-m3 and 340 MiB for granite, against about 110 MiB with the tiktoken fallback, so the tokenizer alone is 230-270 MiB resident. And the tiktoken fallback is about 5x faster and uses about half the memory per character, but the only sign of it is one warning in the log.

Environment: Ubuntu 26.04 on WSL2, Docker 29.7.2 (rootless), 16 CPUs.

📖 Relevant log output

No response

👀 Have you spent some time to check if this bug has been raised before?

  • [x] I checked and didn't find similar issue

🔗 Are you willing to submit PR?

No

🧑‍⚖️ Code of Conduct

  • [x] I agree to follow this project's Code of Conduct

linghengqian avatar Oct 20 '26 20:10 linghengqian

I'll work on this.

sccalabr avatar Oct 20 '26 21:10 sccalabr

@sccalabr, you're assigned.

  • Open a PR or post progress within 14 days; otherwise the issue goes back to others.
  • Read CONTRIBUTING.md.
  • Include a screenshot or short recording of the before/after memory measurements in your PR.

Automated triage. A maintainer will follow up.

arc53-machine avatar Oct 20 '26 21:10 arc53-machine