Text Generation Inference

Also known as: TGI · Hugging Face TGI

On this page 7

Text Generation Inference (TGI) is an open-source serving toolkit from Hugging Face that turns a trained large language model into a production HTTP endpoint for text generation. Among AI frameworks & tools in artificial intelligence, it occupies the inference serving layer: it does not train models, but loads their weights onto GPUs or other accelerators and answers many concurrent requests with high throughput and low latency.

TGI combines a Rust router, a Python model server and optimized kernels such as FlashAttention and paged attention. It supports continuous batching, token streaming, tensor parallelism across several GPUs and many quantization formats, and it exposes both its own API and an OpenAI-compatible chat endpoint. It is often compared with vLLM, SGLang and TensorRT-LLM, which solve the same serving problem with different trade-offs.

How Text Generation Inference serves a model

TGI splits serving into three cooperating processes so that request handling never blocks GPU work. A launcher reads the configuration, downloads the weights and starts one model shard per GPU; a router written in Rust accepts HTTP requests, validates them and schedules batches; and model shards written in Python run the forward passes and communicate with the router over gRPC.

The decisive mechanism is continuous batching, also called in-flight batching. Instead of waiting for a fixed batch to finish, the router adds new requests at every decoding step and removes completed ones immediately. Because generation lengths vary widely, this keeps the GPU busy and can raise throughput several times over static batching on the same hardware.

Each request passes through two phases with very different costs. The table below shows how TGI treats them.

PhaseWhat happensLimiting resource
PrefillThe whole prompt is processed in one passCompute (matrix multiplication)
DecodeOne new token is produced per stepMemory bandwidth
KV cache managementAttention keys and values are stored in pagesGPU memory capacity
StreamingTokens are sent to the client as they appearNetwork and client handling
Phases of a generation request in TGI

The key-value (KV) cache holds the attention state of every active sequence. TGI stores it in fixed-size blocks, the idea popularized as paged attention, so memory is not reserved for the maximum length of every request. Newer releases add prefix caching and chunked prefill, which reuse the cached state of a repeated prompt prefix and split long prompts into smaller pieces.

Key configuration parameters

Most TGI deployments are tuned through a small set of launcher flags that bound memory use and concurrency. Setting them too high causes out-of-memory errors at startup or under load; setting them too low wastes hardware and rejects valid requests.

FlagControlsTypical consideration
--model-idModel repository or local pathMust match a supported architecture
--num-shardNumber of GPUs for tensor parallelismUsually 1, 2, 4 or 8
--quantizeWeight quantization methodReduces memory, may cost accuracy
--max-input-tokensLongest accepted promptLimited by model context window
--max-total-tokensPrompt plus generated tokensDrives KV cache size per request
--max-batch-prefill-tokensTokens processed in one prefillCaps peak memory during prefill
--max-concurrent-requestsRequests accepted at onceExcess requests receive an error
Common launcher flags and their effect

TGI supports several quantization schemes, including bitsandbytes, GPTQ, AWQ, EETQ, Marlin kernels and FP8 on recent NVIDIA GPUs. Moving from 16-bit weights to 4-bit weights cuts weight memory roughly by four, which can let a 70-billion-parameter model fit on fewer GPUs, but quality loss depends on the method and the model and should be measured on real tasks.

TGI compared with other serving engines

TGI is one of several specialized LLM servers, and the right choice depends on hardware, model coverage and operational habits more than on a single benchmark. Published throughput comparisons change with every release, so results on the target workload matter more than headline numbers.

EngineMain strengthTypical fit
TGITight Hugging Face Hub integrationTeams already using Hub models and endpoints
vLLMBroad model support and large communityGeneral-purpose high-throughput serving
SGLangStructured generation and prefix reuseAgent and multi-call workloads
TensorRT-LLMCompiled kernels for NVIDIA GPUsMaximum performance on NVIDIA hardware
Triton Inference ServerMulti-framework model servingMixed fleets of models and backends
OllamaSimple local setupSingle-user desktop use
TGI and related inference servers

TGI can also run on AMD GPUs through ROCm, Intel Gaudi accelerators and AWS Inferentia through dedicated builds, and it can use TensorRT-LLM or llama.cpp as alternative backends. Hugging Face has used TGI to power its own hosted inference products, which shaped its focus on operational features such as metrics and health checks.

Deploying and operating TGI

The usual deployment is the official Docker image, started with a model identifier, a mounted volume for cached weights and access to the GPUs. Gated models require a Hugging Face access token, which should be supplied as an environment variable and never placed in images or logs.

Clients call /generate for a single response, /generate_stream for server-sent events, or /v1/chat/completions, the Messages API that mirrors the OpenAI chat format so existing client libraries work without changes. TGI also offers guided generation with JSON schemas or regular expressions, which constrains output to a valid structure.

  • Prometheus metrics at /metrics report queue time, batch size and tokens per second.
  • OpenTelemetry tracing follows a request through router and shards.
  • Health and info endpoints support load balancers and Kubernetes probes.
  • Speculative decoding with Medusa heads or n-gram lookup can lower latency for suitable models.

The project license has changed over time. TGI moved to a custom Hugging Face license in 2023 and returned to Apache 2.0 in 2024. Hugging Face has since placed TGI in maintenance mode, recommending engines such as vLLM and SGLang for new projects, so teams should check the current status before committing to it.

Common problems and their causes

Most TGI incidents come from memory budgeting and mismatched expectations about latency, not from defects in the server. The table below links frequent symptoms to their usual cause and a practical fix.

SymptomLikely causeFix
Crash at startupToken limits exceed free GPU memoryLower total tokens or quantize
Requests rejectedConcurrency limit reachedRaise the limit or add replicas
Slow first tokenLong prompts in a busy prefillEnable chunked prefill or prefix caching
Garbled chat outputWrong chat templateUse the model’s own template
Lower quality after quantizationAggressive bit widthTest 8-bit or another method
Symptoms, causes and fixes

A frequent misconception is that more concurrency always means more throughput. Beyond a point, larger batches increase time to first token and per-token latency for every user, so interactive services need explicit latency targets alongside throughput goals.

The idea in brief

A language model on its own is just a large file of numbers. Text Generation Inference is the software that puts that model to work. It loads the model onto powerful graphics cards and answers questions sent over the network.

Think of a busy restaurant kitchen. A good chef does not cook one order at a time. New orders join the line as soon as space frees up. TGI works the same way. It mixes many requests together so the expensive hardware is never idle. It also sends words back as they are written, so users see the answer appear right away.

A practical scenario

A mid-sized insurance company wants an internal assistant that summarizes claim files without sending data to an outside provider. Its platform team runs TGI on two 80 GB GPUs with an open-weight model of about 70 billion parameters, quantized with AWQ to 4 bits and sharded with --num-shard 2. They set 8,192 total tokens per request, enable prefix caching for the shared system prompt, and expose the Messages API behind the company gateway.

The existing chat application, written for an OpenAI-style API, needs only a new base URL. Under a load of about 40 simultaneous claims handlers, Prometheus dashboards show stable queue times, and the first words of each summary appear in well under a second. The outcome is a private, self-hosted assistant whose cost is predictable and whose data never leaves the company network.