{"slug": "hugging-face-tei-batching-p95-and-single-gpu-trade-offs", "title": "Hugging Face TEI: Batching, p95, and Single-GPU Trade-offs", "summary": "A developer evaluated Hugging Face Text Embeddings Inference (TEI) as a dedicated serving layer for embedding and reranking, concluding that single-GPU co-serving of both workloads requires workload-specific load testing before approval. The assessment is explicitly conditional: the review environment could not launch Docker or fetch model artifacts, so no execution, GPU latency sweep, OOM reproduction, or cold-start measurement was completed, and the published commands are framed as a reproducible deployment and acceptance harness rather than captured results.", "body_md": "We wanted to remove embedding and reranking from the application process without replacing a vendor invoice with an unpredictable GPU queue.\n\nBatching requires workload-specific validation\n\nTEI offers token-based batching and admission control, but single-GPU co-serving needs simultaneous-load testing before its latency and capacity trade-offs can be approved.\n\nThose are different workloads. Document ingestion wants sustained throughput. Query embedding wants a short, predictable response. Reranking evaluates a query against every candidate document; a top-50 request creates 50 cross-encoder pairs, not one reusable vector. Mixing all three behind an unrestricted queue is how a cheap retrieval service becomes an expensive latency problem.\n\nHugging Face Text Embeddings Inference—TEI—addresses the serving layer: tokenization, token-based dynamic batching, admission control, model execution, and HTTP responses. We evaluate it here as infrastructure, not as a recommendation to change embedding models. Our [chunking review](https://dev.to/articles/chonkie-token-semantic-chunking-production-2026) covers another variable that directly changes its workload: sequence length.\n\n**Our assessment is conditional: TEI is a credible dedicated serving engine, but single-GPU embedding-plus-reranking needs workload-specific approval.**\n\nAn important evidence boundary: our review environment could not launch Docker or fetch model artifacts. We therefore did not complete a TEI execution, GPU latency sweep, OOM reproduction, or cold-start measurement. The commands below are a reproducible deployment and acceptance harness—not a retrospective account of successful runs. We will not turn capacity estimates into measurements.\n\nTwo corrections also matter before deployment:\n\n`text-embeddings-router``--api-key`; authentication is Those distinctions are more useful than a confident but unsupported performance score.\n\nWe would start with the official [TEI repository](https://github.com/huggingface/text-embeddings-inference/) and [Quick Tour](https://huggingface.co/docs/text-embeddings-inference/quick_tour), using separate embedder and reranker containers.\n\nFor the CPU smoke test, our deployment recipe uses the CPU image family. For NVIDIA execution, it uses `cuda-1.10`, NVIDIA Container Toolkit, and drivers compatible with CUDA 12.2 or later. Check the supported hardware matrix before selecting an image for a particular GPU.\n\n```\nset -eu\nmkdir -p data\n\nexport MODEL_ID=BAAI/bge-base-en-v1.5\nexport MODEL_REVISION=\"$(\n  curl -fsSL \"https://huggingface.co/api/models/$MODEL_ID\" |\n    python3 -c 'import json,sys; print(json.load(sys.stdin)[\"sha\"])'\n)\"\n\n# CPU smoke test. On an unsupported laptop architecture, use a supported\n# host or the project's native installation path instead.\nexport IMAGE=ghcr.io/huggingface/text-embeddings-inference:cpu-1.10\ndocker pull \"$IMAGE\"\ndocker image inspect \"$IMAGE\" --format '{{json .RepoDigests}}'\n\ndocker run -d --name tei-embed \\\n  -p 127.0.0.1:8080:80 \\\n  -v \"$PWD/data:/data\" \\\n  \"$IMAGE\" \\\n  --model-id \"$MODEL_ID\" \\\n  --revision \"$MODEL_REVISION\" \\\n  --max-batch-tokens 4096 \\\n  --max-concurrent-requests 32\n\nuntil curl -fsS http://127.0.0.1:8080/health >/dev/null; do\n  sleep 1\ndone\n\ncurl -fsS http://127.0.0.1:8080/embed \\\n  -H 'Content-Type: application/json' \\\n  -d '{\"inputs\":[\"What is deep learning?\",\"A neural network example.\"],\n       \"truncate\":false,\"normalize\":true}' |\n  python3 -c '\nimport json, sys\nvectors = json.load(sys.stdin)\nprint(json.dumps({\n    \"vectors\": len(vectors),\n    \"dimensions\": [len(v) for v in vectors]\n}))\n'\n```\n\n**Illustrative output, not captured execution:**\n\n```\n{\"vectors\": 2, \"dimensions\": [768, 768]}\n```\n\nFor a GPU run, replace the image with `ghcr.io/huggingface/text-embeddings-inference:cuda-1.10` and add `--gpus all`. Record the resolved image digest and model commit; a mutable tag alone is not a benchmark identity.\n\nFor a native installation, we would follow the repository’s backend-specific local build instructions, then inspect and launch the actual executable:\n\n```\ntext-embeddings-router --help\ntext-embeddings-router \\\n  --model-id BAAI/bge-base-en-v1.5 \\\n  --revision \"$MODEL_REVISION\" \\\n  --port 8080 \\\n  --max-batch-tokens 4096 \\\n  --max-concurrent-requests 32\n```\n\nWe would not substitute an unrelated Python package merely because its name resembles the project.\n\nOur `/embed` request uses:\n\n```\n{\n  \"inputs\": [\"first text\", \"second text\"],\n  \"truncate\": false,\n  \"normalize\": true\n}\n```\n\n`inputs` also accepts a single string. The response is a JSON array of vectors, in input order:\n\n```\nnumber[][]\n```\n\nEven a single input returns an outer array. There is no OpenAI-style `data` envelope on this native route.\n\nPooling is a **server/model configuration**, not a field in this request. Without an override, TEI reads the model’s pooling configuration. `--pooling cls`, `mean`, or `last-token` changes aggregation; `splade` requires a compatible masked-language-model architecture and is not interchangeable with ordinary dense pooling.\n\nFor reranking, we would start another container on port 8081 with `--model-id BAAI/bge-reranker-base`, its own pinned revision, and independent limits:\n\n```\ncurl -fsS http://127.0.0.1:8081/rerank \\\n  -H 'Content-Type: application/json' \\\n  -d '{\n    \"query\":\"What is deep learning?\",\n    \"texts\":[\"A bread recipe.\",\"A method using layered neural networks.\"],\n    \"truncate\":false,\n    \"raw_scores\":true,\n    \"return_text\":true\n  }'\n```\n\nThe native response is an array of ranked objects containing `index` and `score`; requesting returned text adds `text`. `index` refers to the original candidate position. We would preserve that index rather than assuming response order matches request order.\n\nWe intentionally specify truncation instead of depending on defaults. We configure truncation explicitly: the current interface defaults to automatic truncation, unlike the behavior used in the 2023 deployment example. We have not verified that default in a local execution. For reranking, the relevant length is the tokenized **query-document pair**, including special tokens.\n\nOur harness below measures client-visible latency, successful-request throughput, and locally counted input tokens. Save it as `bench.py`; install `httpx` and `transformers`. It performs real requests and does not generate synthetic timing results.\n\n``` python\nimport asyncio\nimport json\nimport math\nimport os\nimport time\n\nimport httpx\nfrom transformers import AutoTokenizer\n\nmodel = os.environ[\"MODEL_ID\"]\nrevision = os.environ[\"MODEL_REVISION\"]\nurl = os.getenv(\"URL\", \"http://127.0.0.1:8080/embed\")\nmode = os.getenv(\"MODE\", \"embed\")\nbatch = int(os.getenv(\"CLIENT_BATCH\", \"1\"))\ncount = int(os.getenv(\"REQUESTS\", \"1000\"))\ntok = AutoTokenizer.from_pretrained(model, revision=revision)\n\nquery = \"How does token-based batching affect retrieval latency?\"\ndoc = \"Inference servers group independent inputs into batches. \" * 20\ntexts = [doc] * batch\npayload = (\n    {\"inputs\": texts, \"truncate\": False, \"normalize\": True}\n    if mode == \"embed\"\n    else {\"query\": query, \"texts\": texts,\n          \"truncate\": False, \"raw_scores\": True}\n)\ntokens_per_request = sum(\n    len(tok(t)[\"input_ids\"]) if mode == \"embed\"\n    else len(tok(query, t)[\"input_ids\"])\n    for t in texts\n)\n\ndef percentile(values, p):\n    values = sorted(values)\n    return values[max(0, math.ceil(len(values) * p) - 1)]\n\nasync def run(concurrency):\n    latencies, errors = [], {}\n    next_request = 0\n    async with httpx.AsyncClient(timeout=60) as client:\n        for _ in range(20):\n            r = await client.post(url, json=payload)\n            r.raise_for_status()\n\n        async def worker():\n            nonlocal next_request\n            while next_request < count:\n                next_request += 1\n                start = time.perf_counter()\n                try:\n                    r = await client.post(url, json=payload)\n                    r.raise_for_status()\n                    r.json()\n                    latencies.append((time.perf_counter() - start) * 1000)\n                except Exception as exc:\n                    key = (\n                        str(exc.response.status_code)\n                        if isinstance(exc, httpx.HTTPStatusError)\n                        else type(exc).__name__\n                    )\n                    errors[key] = errors.get(key, 0) + 1\n\n        start = time.perf_counter()\n        await asyncio.gather(*(worker() for _ in range(concurrency)))\n        elapsed = time.perf_counter() - start\n\n    result = {\n        \"budget\": os.getenv(\"BUDGET\"),\n        \"concurrency\": concurrency,\n        \"client_batch\": batch,\n        \"successes\": len(latencies),\n        \"errors\": errors,\n        \"requests_s\": len(latencies) / elapsed,\n        \"input_tokens_s\": len(latencies) * tokens_per_request / elapsed,\n        \"p50_ms\": percentile(latencies, 0.50) if latencies else None,\n        \"p95_ms\": percentile(latencies, 0.95) if latencies else None,\n    }\n    print(json.dumps(result), flush=True)\n\nfor concurrency in (1, 4, 16, 32, 64):\n    asyncio.run(run(concurrency))\n```\n\nWe would restart the server at batch-token budgets **4096, 8192, and 16384**, repeating each sweep with client batches **1, 8, and 32**. `BUDGET` is a result label; it does not reconfigure a running server. Keep model revision, input corpus, precision, and admission limit fixed.\n\nThis is a closed-loop saturation test, not a realistic arrival distribution. Our final gate would add paced traffic, bursts, variable lengths, and repeated runs. We would collect server metrics/traces for queueing and inference time: client p95 includes transport, tokenization, queueing, execution, and serialization, so it is not a per-request GPU inference measurement.\n\nOur immediate roadblock was the unavailable runtime. That prevented us from validating the following failure modes experimentally. We treat them as acceptance tests, not incidents we can claim to have reproduced.\n\n`--max-batch-tokens` defaults to 16384 in the supplied interface. It limits potential tokens per batch, not total process memory. TEI cannot automatically infer the safe ceiling.\n\nOur mitigation would be to increase the budget only while monitoring device memory, rejection counts, and p95. Concurrency supplies enough queued work to fill larger batches; it does not necessarily create one parallel GPU execution per HTTP request.\n\nOn a shared GPU, two individually safe configurations can still exceed the combined memory envelope. We would test long-input mixtures and simultaneous bursts, then retain headroom. We cannot supply a universal OOM threshold.\n\nWe would also keep the budget large enough for accepted sequences. Current startup validation with automatic truncation disabled can reject configurations where the model maximum exceeds the budget. We would not present older long-request-stall behavior as a verified current-version bug.\n\nOverriding CLS pooling with mean pooling can still return the expected vector dimensions. A shape-only health check will not catch semantic incompatibility with an existing index.\n\nOur check would compare fixed texts against a trusted model implementation, then run retrieval-quality tests. We would compare cosine similarity, L2 distance, and ranking changes—not invent a divergence percentage. Model revision, pooling, normalization, and prompt policy belong in the index version.\n\nFor a single-output reranker, `raw_scores:true` exposes logits; normalized scores use sigmoid. That monotonic transformation should preserve ordering, but thresholds change.\n\nWe would request both modes on identical candidates and verify the relationship. We would not carry a hosted provider’s relevance threshold into TEI merely because both responses contain a field called `score`. We have no matched hosted-versus-local experiment establishing a particular discrepancy.\n\nWe would measure image acquisition, empty-cache startup, cached-weight startup, readiness, and first inference separately. No measured seconds-to-ready figure is available here.\n\nFor security, the important distinction is **default-open**, not “authentication impossible.” We would enable `--api-key` or `API_KEY`, keep the service private, and terminate TLS at the ingress. A Hub token downloads models; it does not authenticate inference clients.\n\nShared-key auth also does not replace tenant quotas or rate limits. Our [Docker MCP boundary review](https://dev.to/articles/docker-mcp-gateway-security-boundary-hands-on-2026) applies the same principle: containerization alone is not an access-control boundary.\n\nWe would not choose a batch-token budget by maximizing tokens per second alone. Our production objective is maximum **successful throughput inside the latency target**.\n\n| Option | What we gain | What we must operate or validate | \n|---|---|---|\n| TEI on CPU | Dedicated serving without a GPU; useful smoke-test path | CPU capacity, backend compatibility, actual online p95 | \n| TEI on a dedicated GPU | Token-based batching and independent admission control | GPU cost, safe batch budget, quality parity | \n| Two TEI containers sharing one GPU | Potentially better utilization of one device | Memory competition and cross-workload tail latency | \n| Application-local encoding | Minimal initial deployment machinery | Batching across processes, model duplication, backpressure | \n| Managed embedding/rerank API | Less infrastructure ownership | Current pricing, quotas, data policy, score/model differences | \n| Managed TEI endpoint | Managed lifecycle around the serving engine | Instance utilization, cold starts, service configuration | \n\nFor scale context, we evaluated a [historical managed-endpoint benchmark](https://huggingface.co/blog/inference-endpoints-embeddings): **450+ requests/s for BAAI/bge-base-en-v1.5 at 512 tokens and batch size 32 on an NVIDIA A10G Inference Endpoint**. We retain its October 2023 conditions; we did not reproduce it locally, and we do not use it as a self-hosted result, a p95 promise, or a 2026 price quote.\n\nIn our illustrative batching calculation, we use a fixed cost of 4 ms and a marginal cost of 0.5 ms per sequence, following this [batching model](https://blog.lo0.es/en/posts/serving-embeddings-rerankers-tei-production/). We calculate approximately 222 sequences/s at batch 1 and 1,600 sequences/s at batch 32—about 7.2× throughput. These are assumed-cost calculations, not measured TEI performance.\n\nWe would run embedding alone, reranking alone, and both simultaneously at the intended traffic mix. Then we would compare each workload’s p95, errors, throughput, and peak memory.\n\nTwo containers provide independent queues, not GPU scheduling isolation. We would cap rerank candidates and pair lengths, protect online embedding capacity, and move bulk ingestion elsewhere before assuming shared-device economics work.\n\nLet hourly all-in infrastructure cost be (H), and sustained successful throughput be (T) input tokens/s:\n\n[\n\n\\text{cost per million tokens}\n\n=\\frac{H \\times 1{,}000{,}000}{3600T}\n\n]\n\nFor an **illustrative assumption**, $0.80/hour at 20,000 tokens/s gives approximately **$0.0111 per million tokens**. Averaging only 2,000 tokens/s raises it to **$0.111**. Neither throughput is a TEI measurement.\n\nAt $0.80/hour, a 730-hour month costs $584 before engineering and ancillary infrastructure. Against a hypothetical vendor price of $0.10 per million tokens, infrastructure-only break-even is **5.84 billion tokens/month**.\n\nWe would use current vendor quotes and measured utilization before approving a migration. Reranking needs separate accounting per search or per candidate pair; combining it with embeddings in one tokens-per-dollar headline hides the actual workload.\n\n**We would deploy TEI when:**\n\n**We would hold off on single-GPU co-serving when:**\n\nOur conclusion is not “TEI is slow” or “TEI is cheaper.” It is that TEI exposes the right controls for a serious serving evaluation, while leaving capacity planning and workload isolation with us.\n\nWe would start from the [official deployment path](https://huggingface.co/docs/text-embeddings-inference/quick_tour), run the sweep, and approve co-serving only after simultaneous-load results pass. Until then, single-GPU savings remain a hypothesis—not a production commitment.", "url": "https://wpnews.pro/news/hugging-face-tei-batching-p95-and-single-gpu-trade-offs", "canonical_source": "https://dev.to/jangwook_kim_e31e7291ad98/hugging-face-tei-batching-p95-and-single-gpu-trade-offs-53k4", "published_at": "2026-12-02 00:37:31+00:00", "updated_at": "2026-12-02 00:44:27.021506+00:00", "lang": "en", "topics": ["ai-infrastructure", "mlops", "ai-tools", "large-language-models"], "entities": ["Hugging Face", "Text Embeddings Inference", "BAAI", "bge-base-en-v1.5", "Docker", "NVIDIA Container Toolkit"], "also_reported_by": [], "takeaway": "Separate embedder and reranker containers and validate token-based batching under simultaneous load, since a top-50 rerank request creates 50 cross-encoder pairs rather than one reusable vector.", "recommendation": {"advice": "Run separate TEI embedder and reranker containers and load-test them together before approving single-GPU co-serving, since reranking a top-50 request means 50 cross-encoder pairs, not one vector.", "playbook": "inference-serving", "playbook_url": "https://wpnews.pro/playbooks/inference-serving"}, "alternates": {"html": "https://wpnews.pro/news/hugging-face-tei-batching-p95-and-single-gpu-trade-offs", "markdown": "https://wpnews.pro/news/hugging-face-tei-batching-p95-and-single-gpu-trade-offs.md", "text": "https://wpnews.pro/news/hugging-face-tei-batching-p95-and-single-gpu-trade-offs.txt", "jsonld": "https://wpnews.pro/news/hugging-face-tei-batching-p95-and-single-gpu-trade-offs.jsonld"}}