Docs: hardware sizing omits the local knowledge-bank embedder (~3.7 GB resident, ~5.3 GB peak on PDF ingest)

Abierto Apto para principiantes
#7,233 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
78/100
Tipo de issue
Documentación
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
docker, helm, python

Línea de trabajo

Empieza con hindsight-docs/docs/developer/installation.md, knowledge-banks.mdx y configuration.mdx; compara sus indicaciones sobre memoria con las mediciones reportadas y el límite de la API de 4Gi en helm/hindsight/values.yaml. Documenta las necesidades de memoria residente y máxima del embedder local y aclara si las implementaciones que usan la configuración predeterminada requieren un límite más alto. El trabajo estará terminado cuando los lectores puedan dimensionar contenedores e implementaciones de Helm a partir de las indicaciones actualizadas.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

core
Bug Description

The documented memory sizing does not account for the local knowledge-bank embedder, which is the default (HINDSIGHT_API_KB_EMBEDDINGS_PROVIDER=local, EmbeddingGemma 2 in-process) now that knowledge banks are enabled by default.

  • hindsight-docs/docs/developer/installation.md → Hardware lists API — Full image at 1.5 GB minimum / 2 GB recommended ("Idle RSS settles around 0.8–1.0 GB; expect 1.2–1.5 GB under load"), counting the BGE embedder (~130 MB) and the MiniLM cross-encoder (~90 MB).
  • The image table on the same page mentions the knowledge banks' EmbeddingGemma 2 model only as "~1.5 GB" bundled in the image.
  • knowledge-banks.mdx and the HINDSIGHT_API_KB_* rows in configuration.mdx give no memory guidance for the embedder.
  • helm/hindsight/values.yaml defaults the API to a 4Gi memory limit.

Measured on 1.3.1, the model alone is about 3.7 GB resident once loaded, and embedding PDF pages peaks at about 5.3 GB, before counting the rest of the server. A deployment sized from the docs runs out of memory on PDF ingest.

This is not a leak: memory plateaus. The model loads on first knowledge-bank use and stays resident.

Steps to Reproduce
  1. Save the script below as repro.py in an empty directory.
  2. Run it in the stock full image, with no server or database:
docker run --rm -m 8g --network none \
  -e HF_HUB_OFFLINE=1 -e TRANSFORMERS_OFFLINE=1 \
  -v "$PWD":/repro:ro \
  --entrypoint /app/api/.venv/bin/python \
  ghcr.io/vectorize-io/hindsight:1.3.1 /repro/repro.py
  1. Read the RSS printed after the model loads and after each document.

The script calls LocalGemmaEmbedder.embed_documents() with batch_size=4 on three documents of 24 synthetic page images (1187×1536 PNG, 560 image tokens, the PDF page recipe in knowledge/media.py), in rounds of 8 with up to 4 in flight. It takes about 16 minutes on CPU.

repro.py
"""RSS of the local knowledge embedder across batches of PDF-page-sized images, called the way the service
calls it: embed_documents() (asyncio.to_thread), several rounds in flight, batch_size 4, 560 image tokens."""
import asyncio, ctypes, gc, io, random, time
from PIL import Image, ImageDraw
from hindsight_api.knowledge.embedders import EmbedInput, LocalGemmaEmbedder

DOCS, PAGES, ROUND, IN_FLIGHT = 3, 24, 8, 4
T0 = time.time()

def log(label):
    s = dict(l.split(":", 1) for l in open("/proc/self/status") if ":" in l)
    mb = lambda k: int(s[k].split()[0]) // 1024
    print(f"{time.time()-T0:7.1f}s {label:<28} rss={mb('VmRSS'):5d}MB peak={mb('VmHWM'):5d}MB threads={int(s['Threads'])}", flush=True)

def page(seed):
    r = random.Random(seed)
    img = Image.new("RGB", (1187, 1536), "white")
    d = ImageDraw.Draw(img)
    for y in range(40, 1500, 22):
        words = ("".join(r.choice("abcdefghijklmnopqrstuvwxyz") for _ in range(r.randint(2, 9))) for _ in range(16))
        d.text((50, y), " ".join(words), fill="black")
    b = io.BytesIO()
    img.save(b, "PNG")
    return b.getvalue()

emb = LocalGemmaEmbedder("google/embeddinggemma-2", dimensions=None, device=None, batch_size=4, image_tokens=280)

async def ingest(doc):
    items = [EmbedInput(modality="image", data=page(doc * 1000 + p), mime="image/png", image_tokens=560) for p in range(PAGES)]
    sem = asyncio.Semaphore(IN_FLIGHT)
    async def one(chunk):
        async with sem:
            return await emb.embed_documents(chunk)
    await asyncio.gather(*(one(items[i:i + ROUND]) for i in range(0, len(items), ROUND)))

async def main():
    log("start")
    emb.ensure_loaded(); log("model loaded")
    for doc in range(DOCS):
        await ingest(doc); log(f"doc {doc + 1} done ({PAGES} pages)")
        time.sleep(15)
    gc.collect(); log("after gc.collect()")
    ctypes.CDLL("libc.so.6").malloc_trim(0); log("after malloc_trim(0)")

asyncio.run(main())
Expected Behavior

The Hardware table and the Knowledge Banks page state what the default local knowledge embedder needs in memory, so a container or Helm limit can be sized for it. The default Helm limit either fits a deployment that uses the default embedder, or the docs say it must be raised.

Actual Behavior

Isolated run (the steps above), ghcr.io/vectorize-io/hindsight:1.3.1, CPU, torch 2.13.0+cpu, 8 GiB limit:

Point RSS
Process start 128 MB
Model loaded 3,653 MB
After document 1 4,125 MB
After document 2 4,249 MB
After document 3 4,247 MB
After malloc_trim(0) 3,726 MB
Peak (VmHWM) 5,346 MB

In a real deployment of the same image under an 8 GiB container limit:

  • The server idled at about 2.5 GiB until its first PDF. The log then showed Knowledge embedder loaded: google/embeddinggemma-2 on cpu (768 dims), and it has idled at about 6.05 GiB RSS since.
  • Ingesting one 1.3 MB PDF (27 passages) peaked at 7.6 GiB.
  • On 1.3.0, submitting 19 PDFs (14 KB to 12.7 MB) within a few seconds failed 15 of them with MediaError: ... the PDF renderer crashed on this file, and the kernel then OOM-killed hindsight-api (Memory cgroup out of memory, anon-rss 8,123,236 kB). The same files ingested without error one or two at a time.

The memory guard added in https://github.com/hindsightai/hindsight/pull/6735 kills the biggest worker process, so it does not help when the memory is held by the server process itself. That PR's description assumes "a 2–3 GB server"; with the local knowledge embedder loaded the server here is about 6 GiB.

Version

1.3.1 (ghcr.io/vectorize-io/hindsight:1.3.1; the OOM kill was on 1.3.0). Docker on Linux x86_64 (kernel 6.12, 20 CPU threads), Python 3.11.18 as shipped in the image, CPU only.

LLM Provider

Other (not involved: knowledge-bank ingest makes no LLM calls)

Lenguaje dominante
Python
Estrellas
45.2k
Forks
5.9k
Métricas de merge de PR
Sin PR fusionados en 30 d

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de vectorize-io/hindsight

Todos los issues de vectorize-io/hindsight

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.