{"slug": "how-to-deploy-hugging-face-models-in-production", "title": "How to Deploy Hugging Face Models in Production", "summary": "A developer's deployment playbook lays out four ways to serve Hugging Face models in production—HF Inference Endpoints, Text Generation Inference (TGI), vLLM, and bare Transformers behind FastAPI—and argues that wrapping AutoModelForCausalLM in FastAPI with per-request generate() yields roughly 1/20th the throughput of vLLM and OOMs under load. The key difference is continuous (iteration-level) batching, which inserts new requests at every token step, combined with PagedAttention for KV-cache management; the author reports vLLM delivering roughly 100x the throughput of naive generate() for Llama-3-8B on a single A10G under load.", "body_md": "There's a moment every ML engineer hits the first time they try to put a Hugging Face model behind a real API. You grab `transformers`, you wrap it in FastAPI, you `pipeline(\"text-generation\", model=...)`, you curl it once, it works, you push to prod, and at peak traffic your GPU OOMs and the latency goes to 30 seconds. That's the moment you learn that **serving a model is not the same as running a model.**\n\nThis article is the deployment playbook. We'll go through the four real options (Inference Endpoints, TGI, vLLM, and bare Transformers), when to pick each, and the production plumbing around them. I'll skip the marketing and focus on the stuff that bites you at 3am.\n\nYou have four ways to serve a Hugging Face model in production. Each has a clear use case.\n\n| Option | Best for | Throughput | Cost | Operational burden | \n|---|---|---|---|---|\n| HF Inference Endpoints | Prototyping, low-traffic prod | Medium-high | $0.06-3/hr/GPU | Very low | \n| TGI (Text Generation Inference) | Production LLM serving | High | Compute + your infra | Medium | \n| vLLM | Max throughput LLM serving | Highest | Compute + your infra | Medium | \n| Bare `transformers` + FastAPI | Embeddings, small models, custom pipelines | Low | Compute + your infra | High | \n\nThe rule of thumb: if it's an LLM doing text generation, use vLLM or TGI. If it's embeddings or a small classification model, bare transformers behind FastAPI is fine. If you don't want to operate infra, Inference Endpoints.\n\nNever serve an LLM by wrapping `AutoModelForCausalLM` in FastAPI and calling `model.generate()` per request. You will get 1/20th the throughput of vLLM and OOM under load. The reason is **batching**: vanilla `generate()` processes one request at a time, while vLLM and TGI do continuous batching, which is the single biggest LLM serving optimization of the last three years.\n\nNaive batching waits to collect N requests, processes them together, returns all results, then starts the next batch. If one request takes 10x longer (long output), the other 9 wait. Throughput collapses.\n\nContinuous batching (also called iteration-level batching or in-flight batching) inserts new requests into the batch at every token step. A short request finishes, frees its slot, a new request slides in. GPU utilization stays near 100% even when request lengths vary wildly.\n\nThe performance difference is not subtle. For Llama-3-8B on a single A10G:\n\n`model.generate()` per request: ~5 tokens/sec/req, batch 1\nThat's not a typo. vLLM is roughly 100x the throughput for the same model on the same GPU under load. The win comes from continuous batching + PagedAttention (which handles the KV cache like virtual memory, eliminating fragmentation).\n\nIf you don't want to operate GPUs, this is the path. You click through a UI, pick a model, pick a GPU, and you get an [OpenAI](https://mangodeveloper.com/articles/cisco-openai-shirudo-ebpf-shields-patch-without-reboot)-compatible endpoint in 5-10 minutes.\n\n```\nBashCopy\n```\n\npip install huggingface_hub\n\nfrom huggingface_hub import HfApi\n\napi = HfApi(token=\"hf_xxx\")\n\nhuggingface-cli inference-endpoints create \\\n\n --name \"llama-3-8b-prod\" \\\n\n --namespace \"your-org\" \\\n\n --repository \"meta-llama/Llama-3.1-8B-Instruct\" \\\n\n --accelerator \"gpu\" \\\n\n --instance-size \"x1\" \\\n\n --instance-type \"nvidia-a10g\" \\\n\n --region \"us-east-1\" \\\n\n --type \"protected\"\n\nCall it like OpenAI:\n\n```\nPythonCopy\n```\n\npython\n\nfrom openai import OpenAI\n\nclient = OpenAI(\n\n base_url=\"[https://xxx.us-east-1.aws.endpoints.huggingface.cloud/v1](https://xxx.us-east-1.aws.endpoints.huggingface.cloud/v1)\",\n\n api_key=\"hf_xxx\"\n\n)\n\nresponse = client.chat.completions.create(\n\n model=\"tgi\",\n\n messages=[{\"role\": \"user\", \"content\": \"Explain PagedAttention in one sentence.\"}],\n\n max_tokens=100,\n\n)\n\nmarkdown\n\n**When to use**: prototypes, internal tools, low-traffic prod (<10 req/sec), or when you don't have a platform team.\n\n**When not to use**: high-traffic prod where the per-token markup adds up, regulated environments needing on-prem, or when you need custom inference logic.\n\nPricing is the cloud GPU rate plus a markup, billed per second. An A10G endpoint runs roughly $1.20-1.50/hr. Compare to a self-managed A10G on AWS at ~$1.00/hr-the markup is the operational simplicity tax.\n\nTGI is Hugging Face's production LLM server. It's what powers Inference Endpoints internally, and you can run the same Docker image yourself.\n\n```\nBashCopy\n```\n\nshell\n\ndocker pull ghcr.io/huggingface/text-generation-inference:latest\n\ndocker run --gpus all --shm-size 1g \\\n\n -p 8080:80 \\\n\n -v /data/models:/data \\\n\n ghcr.io/huggingface/text-generation-inference:latest \\\n\n --model-id meta-llama/Llama-3.1-8B-Instruct \\\n\n --max-batch-prefill-tokens 4096 \\\n\n --max-total-tokens 8192 \\\n\n --quantize awq \\\n\n --num-shard 1\n\nplaintext\n\nKey flags you'll actually tune:\n\n`--max-total-tokens`: max sequence length per request. Higher = more memory.`--max-batch-prefill-tokens`: how many tokens to process during prefill per batch. Higher = better throughput, more memory.`--quantize`: `awq`, `gptq`, `bitsandbytes`, `eetq`, or unset. AWQ is the current sweet spot for 7B-70B models.`--num-shard`: tensor parallel degree. Set to the number of GPUs for multi-GPU serving.`--max-concurrent-requests`: backpressure. Set this or you'll OOM under load.\nCall it:\n\n```\nPythonCopy\n```\n\npython\n\nimport requests\n\nresp = requests.post(\"[http://localhost:8080/generate](http://localhost:8080/generate)\", json={\n\n \"inputs\": \"Explain PagedAttention.\",\n\n \"parameters\": {\n\n \"max_new_tokens\": 200,\n\n \"temperature\": 0.7,\n\n \"top_p\": 0.9,\n\n \"do_sample\": True,\n\n }\n\n})\n\nprint(resp.json()[\"generated_text\"])\n\nOr use the OpenAI-compatible endpoint at `/v1/chat/completions`:\n\n```\nPythonCopy\n```\n\nclient = OpenAI(base_url=\"[http://localhost:8080/v1](http://localhost:8080/v1)\", api_key=\"dummy\")\n\nresp = client.chat.completions.create(\n\n model=\"tgi\",\n\n messages=[{\"role\": \"user\", \"content\": \"Explain PagedAttention.\"}],\n\n)\n\nvLLM is the [open-source](https://mangodeveloper.com/category/dev) throughput king. Same use case as TGI, generally 1.2-2x faster on the same hardware, larger community, faster-moving. The trade-off is less polish on the deployment story and occasional instability on the latest models.\n\n```\nBashCopy\n```\n\nshell\n\npip install vllm\n\nvllm serve meta-llama/Llama-3.1-8B-Instruct \\\n\n --port 8000 \\\n\n --tensor-parallel-size 1 \\\n\n --max-model-len 8192 \\\n\n --gpu-memory-utilization 0.9 \\\n\n --quantization awq \\\n\n --enable-chunked-prefill\n\nUseful flags:\n\n`--gpu-memory-utilization`: fraction of GPU memory vLLM claims. 0.9 leaves room for the rest of your stack. 1.0 = OOM risk.`--max-model-len`: context window. Higher uses more KV cache.`--enable-chunked-prefill`: process prefill in chunks so short requests don't get blocked behind long prefills. Big throughput win for mixed workloads.`--tensor-parallel-size`: split model across N GPUs.`--swap-space`: CPU memory for KV cache spillover. Use sparingly; it's slow.\n\n```\nPythonCopy\n```\n\nclient = OpenAI(base_url=\"[http://localhost:8000/v1](http://localhost:8000/v1)\", api_key=\"dummy\")\n\nresp = client.chat.completions.create(\n\n model=\"meta-llama/Llama-3.1-8B-Instruct\",\n\n messages=[{\"role\": \"user\", \"content\": \"Explain PagedAttention.\"}],\n\n stream=True,\n\n)\n\nfor chunk in resp:\n\n if chunk.choices[0].delta.content:\n\n print(chunk.choices[0].delta.content, end=\"\", flush=True)\n\nUse TGI when:\n\nUse vLLM when:\n\nIn practice, both are good. Pick one based on operational fit, not benchmarks. The 20% throughput difference won't matter if your team can't operate the thing.\n\nFor embeddings, classification, or small seq2seq models, you don't need TGI/vLLM. A simple FastAPI server with the model loaded once at startup works fine.\n\n```\nPythonCopy\n```\n\npython\n\nfrom fastapi import FastAPI, HTTPException\n\nfrom pydantic import BaseModel\n\nfrom contextlib import asynccontextmanager\n\nfrom sentence_transformers import SentenceTransformer\n\nimport torch, os\n\nMODEL_NAME = os.getenv(\"MODEL_NAME\", \"BAAI/bge-large-en-v1.5\")\n\nDEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\nstate = {}\n\n@asynccontextmanager\n\nasync def lifespan(app: FastAPI):\n\n state[\"model\"] = SentenceTransformer(MODEL_NAME, device=DEVICE)\n\n yield\n\n state.clear()\n\napp = FastAPI(lifespan=lifespan)\n\nclass EmbedRequest(BaseModel):\n\n texts: list[str]\n\n@app.post(\"/embed\")\n\ndef embed(req: EmbedRequest):\n\n if not req.texts:\n\n raise HTTPException(400, \"texts must be non-empty\")\n\n model = state[\"model\"]\n\n with torch.inference_mode():\n\n emb = model.encode(req.texts, normalize_embeddings=True, batch_size=32)\n\n return {\"embeddings\": emb.tolist()}\n\n```\nDockerfileCopy\n```\n\ndocker\n\nFROM python:3.11-slim\n\nRUN apt-get update && apt-get install -y --no-install-recommends \\\n\n build-essential && rm -rf /var/lib/apt/lists/*\n\nWORKDIR /app\n\nCOPY requirements.txt .\n\nRUN pip install --no-cache-dir -r requirements.txt\n\nCOPY server.py .\n\nENV MODEL_NAME=BAAI/bge-large-en-v1.5\n\nEXPOSE 8000\n\nCMD [\"uvicorn\", \"server:app\", \"--host\", \"0.0.0.0\", \"--port\", \"8000\", \"--workers\", \"1\"]\n\nRun with `--workers 1` because the model is in GPU memory; multiple workers would each load a copy. For throughput, batch within a single worker (the `batch_size=32` in `encode()`).\n\nBefore you pick a GPU, do the math. A 7B model in bfloat16 needs:\n\nSo a 7B in bf16 fits on a 24GB GPU (A10G, 3090, 4090) with room for moderate batching. A 70B in bf16 needs 140GB for weights alone-you need 2×80GB (A100 80GB) with tensor parallelism, or you quantize.\n\nQuantization options:\n\n| Format | Bits | Size (7B) | Quality loss | Speed | \n|---|---|---|---|---|\n| fp32 | 32 | 28 GB | none | baseline | \n| bf16/fp16 | 16 | 14 GB | none | baseline | \n| 8-bit (int8) | 8 | 7 GB | ~1% | faster | \n| AWQ 4-bit | 4 | 4 GB | ~2-3% | faster | \n| GPTQ 4-bit | 4 | 4 GB | ~2-3% | comparable | \n| bitsandbytes 4-bit | 4 | 5 GB | ~3-5% | slower | \n\nAWQ is the current production sweet spot for LLMs. GPTQ is comparable. bitsandbytes is easiest to set up but slowest. For embeddings, stay in fp16 or bf16-quantizing embedding models tends to wreck retrieval quality.\n\nA real production setup looks like this:\n\n```\nCodeCopy\n```\n\nplaintext\n\n ┌─────────────┐\n\n │ Cloudflare │\n\n │ / nginx │\n\n └──────┬──────┘\n\n │\n\n ┌──────▼──────┐\n\n │ API gateway│\n\n │ (rate limit,│\n\n │ auth, logs)│\n\n └──────┬──────┘\n\n │\n\n ┌────────────┼────────────┐\n\n │ │ │\n\n ┌──────▼───┐ ┌──────▼───┐ ┌──────▼───┐\n\n │ vLLM pod │ │ vLLM pod │ │ vLLM pod │\n\n │ (GPU 1) │ │ (GPU 2) │ │ (GPU 3) │\n\n └──────────┘ └──────────┘ └──────────┘\n\n │ │ │\n\n └────────────┼────────────┘\n\n │\n\n ┌──────▼──────┐\n\n │ Redis │\n\n │ (cache, kv) │\n\n └─────────────┘\n\nKey principles:\n\nCPU-based autoscaling doesn't work for LLMs. A pod at 0 req/sec and a pod at 50 req/sec both show 5% CPU because the GPU is doing the work. You need GPU-aware metrics.\n\nPrometheus + DCGM exporter gives you:\n\n`DCGM_FI_DEV_GPU_UTIL` (0-100%)`DCGM_FI_DEV_MEM_COPY_UTIL`` DCGM_FI_DEV_FB_USED` (frame buffer memory used)\nScale on `DCGM_FI_DEV_GPU_UTIL > 80` for scale-up, `< 30` for scale-down. Set a longer stabilization window (5-10 min) because pods take 2-5 minutes to load a model.\n\nFor KEDA ([Kubernetes](https://mangodeveloper.com/category/devops) Event-Driven Autoscaling) on a custom metric like queue depth:\n\n```\nYAMLCopy\n```\n\nyaml\n\napiVersion: keda.sh/v1alpha1\n\nkind: ScaledObject\n\nmetadata:\n\n name: vllm-scaler\n\nspec:\n\n scaleTargetRef:\n\n name: vllm-deployment\n\n minReplicaCount: 2\n\n maxReplicaCount: 10\n\n cooldownPeriod: 300\n\n triggers:\n\nCold starts are the killer here. A new pod takes 2-5 minutes to pull the model into GPU memory. Keep `minReplicaCount` at your baseline traffic level. Never scale to zero in production unless you can afford 5-minute startup latency.\n\nSemantic caching (cache similar prompts, not just identical ones) is the biggest cost lever for LLM serving. Tools like RedisVL, GPTCache, or a simple embedding-similarity cache work.\n\n```\nPythonCopy\n```\n\npython\n\nimport redis, numpy as np\n\nfrom sentence_transformers import SentenceTransformer\n\nr = redis.Redis(host=\"redis\", port=6379)\n\nembedder = SentenceTransformer(\"BAAI/bge-small-en-v1.5\")\n\ndef cached_generate(prompt: str, generate_fn, threshold: float = 0.95):\n\n q_emb = embedder.encode([prompt], normalize_embeddings=True)[0]\n\n # Search cache\n\n results = r.execute_command(\n\n \"FT.SEARCH\", \"cache_idx\",\n\n f\"*=>[KNN 1 @emb $query_vec]\",\n\n \"PARAMS\", 2, \"query_vec\", q_emb.tobytes(),\n\n \"RETURN\", 1, \"__emb_score\",\n\n \"DIALECT\", 2\n\n )\n\n if results and results[0] > 0:\n\n score = results[2][1]\n\n if float(score) >= threshold:\n\n cached = r.get(f\"response:{results[2][3]}\")\n\n if cached:\n\n return cached.decode()\n\n # Cache miss\n\n response = generate_fn(prompt)\n\n r.setex(f\"prompt:{hash(prompt)}\", 3600, response)\n\n # ... index embedding\n\n return response\n\nCache hit rates of 20-40% are typical for support/chat workloads. That's a 25-65% cost reduction for free.\n\nThe metrics that matter:\n\nGrafana dashboard with vLLM's built-in Prometheus metrics + DCGM exporter covers most of this.\n\n**Serving LLMs with bare `transformers.generate()`**: 100x slower than vLLM. Stop doing this in production.\n\n**Setting `--gpu-memory-utilization 1.0`**: OOMs on the first long request. Leave 5-10% headroom.\n\n**Pulling models from HF Hub at pod startup**: 2-3 minute startup tax, fails if HF is down. Cache models on a shared volume.\n\n**No backpressure**: clients pile up, pods OOM, you get a thundering herd. Set `--max-concurrent-requests` and return 429 above it.\n\n**Ignoring first-token latency**: users perceive streaming responses as 3x faster than buffered ones, even at the same total time. Always stream.\n\n**Forgetting to set CUDA_VISIBLE_DEVICES on multi-GPU boxes**: vLLM grabs GPU 0 by default and ignores the others. Use `--tensor-parallel-size N` or set the env var.\n\n**Mixing quantization formats**: load an AWQ model with `--quantization gptq` and you get garbage output. Match the format.\n\n**No model warmup**: the first request after startup takes 30+ seconds because CUDA kernels compile. Hit the endpoint with a dummy request in your readiness probe.\n\n**Symptom**: First request after deploy takes 30 seconds.\n\n**Cause**: CUDA kernel compilation + lazy initialization.\n\n**Fix**: warm up in the Docker entrypoint or readiness probe:\n\n```\nPythonCopy\n```\n\npython\n\nimport requests\n\ndef warmup():\n\n try:\n\n requests.post(\"[http://localhost:8000/v1/chat/completions](http://localhost:8000/v1/chat/completions)\",\n\n json={\"model\": \"x\", \"messages\": [{\"role\": \"user\", \"content\": \"hi\"}], \"max_tokens\": 1},\n\n timeout=60)\n\n except Exception:\n\n pass\n\n**Symptom**: p99 latency spikes to 30s every few hours.\n\n**Cause**: Long prefill requests blocking the batch.\n\n**Fix**: enable `--enable-chunked-prefill` (vLLM) or `--max-batch-prefill-tokens` (TGI) and cap `--max-input-length`.\n\n**Symptom**: OOM errors under load despite low utilization.\n\n**Cause**: KV cache exhausted from long-context requests.\n\n**Fix**: lower `--max-model-len`, set `--max-num-seqs` explicitly, add backpressure.\n\n**Symptom**: Throughput halves after a deploy.\n\n**Cause**: Quantization disabled by config drift, or a different dtype loaded.\n\n**Fix**: check startup logs for `quantization` and `dtype` lines. Pin everything in config, not CLI flags.\n\nRough monthly cost for serving Llama-3-8B at moderate traffic (50 req/sec avg, 500 tokens per request):\n\nA 70B in 4-bit on 2×A100 80GB self-managed runs ~$5,500/mo on AWS, or ~$3,500/mo on Lambda Labs. The Inference Endpoint equivalent is ~$4,500-5,000/mo. The operational savings may justify the markup if you don't have a platform team.\n\nIf you take one thing from this article: don't serve LLMs with bare transformers. Pick vLLM or TGI, learn its flags, and instrument it properly. The model is 20% of the work; the serving infrastructure is 80%, and it's where your production fires will be.\n\nOriginally published on [Mango Developer](https://mangodeveloper.com/articles/deploy-huggingface-models).", "url": "https://wpnews.pro/news/how-to-deploy-hugging-face-models-in-production", "canonical_source": "https://dev.to/mango7777/how-to-deploy-hugging-face-models-in-production-412a", "published_at": "2026-11-27 17:30:00+00:00", "updated_at": "2026-11-27 17:44:37.558610+00:00", "lang": "en", "topics": ["large-language-models", "ai-infrastructure", "mlops", "ai-tools"], "entities": ["Hugging Face", "vLLM", "Text Generation Inference", "FastAPI", "Llama-3-8B", "NVIDIA A10G", "Transformers"], "also_reported_by": [], "takeaway": "Serve LLMs with continuous batching engines like vLLM or TGI rather than per-request model.generate(), which runs about 5 tokens/sec/request at batch 1 versus roughly 100x throughput for Llama-3-8B on one A10G under load.", "recommendation": {"advice": "Use vLLM or TGI for any LLM text generation instead of wrapping generate() in FastAPI; continuous batching and PagedAttention delivered roughly 100x throughput on Llama-3-8B over a single A10G.", "playbook": "inference-serving", "playbook_url": "https://wpnews.pro/playbooks/inference-serving"}, "alternates": {"html": "https://wpnews.pro/news/how-to-deploy-hugging-face-models-in-production", "markdown": "https://wpnews.pro/news/how-to-deploy-hugging-face-models-in-production.md", "text": "https://wpnews.pro/news/how-to-deploy-hugging-face-models-in-production.txt", "jsonld": "https://wpnews.pro/news/how-to-deploy-hugging-face-models-in-production.jsonld"}}