18.1 · Why "platform thinking" beats "another model deployment"
One team can ship one model. A national / enterprise programme has to expose AI as a standardised platform service consumed by dozens of ministries, business units, or vendors. The constraints flip:
| Single product | Platform |
|---|---|
| One tenant | Dozens of tenants — isolation by design |
| One model | A catalog of models routed by policy |
| One SDK | OpenAI-compatible APIs so any consumer drops in |
| Trust the dev | Audit every prompt, output, and tool call |
| "It works locally" | SLO-backed, observable, rollback-ready |
| Cloud lock-in OK | Cloud-agnostic patterns; bring-your-own GPU |
18.2 · The reference architecture in one picture
Read this picture top-down: consumers hit one gateway; the gateway routes to the right serving backend; serving may call the knowledge plane; the control plane governs everything (registry, eval, policy, observability); all of it sits on cloud-agnostic infrastructure.
18.3 · The AI Inference Gateway
Definition. A reverse-proxy + policy engine that all consumers hit instead of calling models directly. Speaks an OpenAI-compatible API (so any SDK works), enforces tenant policy, routes to backends, and emits telemetry.
| Feature | Definition | Example |
|---|---|---|
| OpenAI-compatible surface | Endpoints like POST /v1/chat/completions, /v1/embeddings, /v1/responses. | Any client written for OpenAI / Anthropic / vLLM drops in with one base-URL change. |
| Auth & tenancy | Bearer keys / OIDC tokens carry tenant + scopes; every request is labelled and quota-checked. | Ministry A's key cannot read Ministry B's vector store. |
| Routing | Pick the backend by model name, region, cost tier, or capacity. | cognitive/general-fast → small model; cognitive/general-deep → frontier. |
| Fallback | If the primary model 5xx's or times out, retry on a secondary backend within the SLA. | Frontier down → fall back to open-weight Llama on vLLM with same schema. |
| Prompt cache | Hash the stable prefix; replay the prefill from cache. | 50–90% prefill cost cut on long system prompts. |
| Batching | Coalesce concurrent requests into one GPU batch for throughput. | vLLM continuous batching → 5–20× throughput. |
| Safety filters | Input + output classifiers (PII, toxicity, jailbreak signatures) inline. | Llama Guard / Azure Content Safety call at ingress + egress. |
| SLA enforcement | Drop / queue / shed load by tenant priority when capacity is tight. | Premium tenant keeps p95 < 2s; free tier gets queued. |
| Telemetry hook | OTel spans for each call: tokens, latency, cost, tenant, model, prompt hash. | Datadog / Dynatrace / Tempo dashboards. |
18.4 · Model serving backends
Behind the gateway sit one or more serving engines that actually run the forward pass. You choose by model size, throughput needs, latency target, and hardware.
vLLM
Open-source LLM inference engine with PagedAttention and continuous batching. Maximum throughput on GPUs for open-weight LLMs.
NVIDIA Triton
General-purpose inference server (TensorRT, ONNX, PyTorch, Python backends). Mixed model types behind one HTTP/gRPC surface.
NVIDIA NIM
Pre-packaged, optimised inference microservices from NVIDIA for popular models. Zero-tuning, vendor-backed.
KServe
Kubernetes-native model serving CRDs (InferenceService) on top of Knative. Declarative, autoscaling, scale-to-zero.
Ray Serve
Python-first serving on top of Ray. Great for compositional graphs of models + tools.
TGI / TensorRT-LLM
Alternative high-performance LLM serving engines from Hugging Face / NVIDIA.
Performance levers
| Lever | Definition | Effect |
|---|---|---|
| Continuous batching | Add new requests into a running batch as soon as a slot frees. | 5–20× throughput vs static batching. |
| PagedAttention | Manages the KV cache in fixed-size pages like virtual memory. | Higher concurrency on the same GPU. |
| KV / prompt caching | Reuse hidden states for repeated prefixes. | Slashes prefill cost; lowers TTFT. |
| Speculative decoding | Tiny draft model proposes N tokens; big model verifies. | 1.5–3× faster generation. |
| Quantization | Lower-precision weights and/or activations. | Bigger models fit; throughput up. |
| Tensor / pipeline parallelism | Split a single model across multiple GPUs. | Lets you run 70B+ on commodity nodes. |
| Autoscaling | Scale replicas on QPS / queue depth / GPU util. | Match cost to demand. |
18.5 · Multi-tenant AI patterns
| Pattern | Definition | When |
|---|---|---|
| Shared pool, soft isolation | All tenants hit the same model replicas; logical separation by API key + quotas. | Default for the general-purpose models — cheapest. |
| Per-tenant endpoint | Dedicated URL / key namespace, still shared compute under the hood. | Tenants need their own SLA or vanity URL. |
| Dedicated GPU pool | A pool of GPUs reserved to a tenant. | Regulated tenant or noisy-neighbour problems. |
| Tenant-fine-tuned LoRA | One base model; load per-tenant LoRA adapters per request. | Tenant-specific behaviour without forking the base. |
| Tenant-owned data plane | Tenant brings their own vector store, S3 bucket, KMS key. | Hard data-residency requirements. |
Isolation rules you can't break
- Every request carries a verified
tenant_idclaim from auth. - Every vector / SQL / blob query filters on
tenant_idat the lowest layer. - Per-tenant quotas (TPM, RPM, $/day) enforced at the gateway.
- Per-tenant data boundary — logs and traces also segmented.
- Cross-tenant incident drills run quarterly.
18.6 · RAG as a knowledge service
| Concern | Platform answer |
|---|---|
| Ingestion at scale | Event-driven; idempotent jobs; per-source connectors; backfill replay. |
| Embedding rotation | Embeddings are versioned; re-embedding is a background job with feature flags. |
| Chunk hygiene | Heading-aware splitter; overlap; tagged with source_id, page, section. |
| Retrieval policy | Hybrid (dense + BM25) + metadata filter; configurable per knowledge base. |
| Grounding contract | LLM must cite passage IDs; ungrounded answers are rejected. |
| Provenance | Response carries trace: which chunks, which doc versions, which model — for audit. |
18.7 · Fine-tuning pipelines — LoRA & PEFT
Definition. Fine-tuning adjusts a pre-trained model on your data. Full fine-tuning updates every weight (expensive, copy-per-tenant). Parameter-Efficient Fine-Tuning (PEFT) trains only a tiny add-on — typically a few million parameters — that plugs onto the frozen base model.
LoRA
Replace a weight update $\Delta W$ with a low-rank product $A B$ where $A, B$ are tiny. 0.1–1% of the parameters; swap-in / swap-out per tenant.
QLoRA
Quantise the frozen base to 4-bit, train LoRA on top. Fine-tunes 65B models on a single 48 GB GPU.
Adapter / IA³ / Prefix tuning
Other PEFT variants — bottleneck adapters, scaling vectors, learned prefixes.
Continued pre-training
More self-supervised training of the base on your domain corpus before any SFT.
SFT (instruction tuning)
Train on (prompt, ideal answer) pairs. Shapes format, tone, task adherence.
DPO / KTO / ORPO
Preference optimisation from ranked (chosen, rejected) pairs.
The pipeline, end to end
18.8 · Model registry & lifecycle
A model registry is the source of truth for every model artefact, version, and approval.
| Concept | Definition |
|---|---|
| Model card | Document for each model: intended use, training data summary, evals, limitations. |
| Dataset card | Same idea for the training/eval dataset: source, licence, demographics. |
| Artefact | Immutable blob (weights, tokenizer, config) referenced by SHA. |
| Stage | staging → canary → production → archived. |
| Provenance | Training run, code commit, dataset version, evaluator used. |
| Attestation | Signed metadata proving who built the model. |
| Rollback | Promotion is reversible in one command; previous stage is always warm. |
Common tools: MLflow Model Registry, Weights & Biases Artefacts, Hugging Face Hub (private), Vertex AI Model Registry, SageMaker Model Registry.
18.9 · MLOps on Kubernetes
| Layer | Tool examples | What it does |
|---|---|---|
| Orchestration | Airflow, Prefect, Dagster, Argo Workflows | Schedule + version pipelines. |
| Distributed training | Ray Train, PyTorch DDP / FSDP, DeepSpeed | Scale training across GPUs. |
| Distributed compute | Ray, Spark, Dask | ETL, embedding generation, batch inference. |
| Serving | KServe, Ray Serve, vLLM, Triton, NIM | Deploy + autoscale models. |
| Experiment tracking | MLflow, W&B, Comet | Log runs, params, metrics, artefacts. |
| Feature store | Feast, Tecton | Consistent feature serving for ML. |
| CI/CD & GitOps | GitHub Actions, ArgoCD, Flux | Promote artefacts and configs by PR. |
| Secrets / KMS | Vault, AWS KMS, GCP KMS | Manage keys, tokens, encryption. |
18.10 · Observability — five pillars
| Pillar | What you capture | Tools |
|---|---|---|
| Metrics | Latency p50/p95/p99, TPM, $/req, GPU util, KV-cache hit, queue depth. | Prometheus, OTel metrics, Datadog. |
| Logs | Structured request/response logs with tenant + prompt hash. | Loki, Splunk, ELK. |
| Traces | End-to-end spans across gateway → model → tools → DB. | OpenTelemetry, Tempo, Jaeger, Langfuse. |
| Audits | Append-only record of every action. | Object storage + tamper-evident hash chain. |
| HLEM | Human-in-the-Loop Eval / Monitoring — human review of sampled outputs. | Argilla, Label Studio, custom queues. |
Anomaly & drift signals to alert on
- Eval score drop > 3% on canary vs baseline.
- Refusal rate spike (jailbreak attempt or guardrail mis-fire).
- Tool error rate > 1%.
- Cost / request > 2× moving average.
- Hallucination flag rate climbing week over week.
- Latency p95 above SLO for 5 minutes.
18.11 · Safety, governance & policy-as-code
| Control | Definition |
|---|---|
| Prompt governance | Reviewed library of system prompts with owners, versions, change history. |
| PII redaction | Inline regex / NER pipeline that masks emails, IDs, phones before the LLM. |
| Content filters | Classifier-based input/output checks (Llama Guard, Azure Content Safety). |
| Policy-as-code | Rules expressed as code (OPA / Rego) enforced at the gateway and CI gates. |
| SBOM & attestation | Software Bill of Materials for the model + serving stack; signed. |
| Approval workflow | Model promotion needs sign-off from a risk owner, evaluator, and security. |
| Incident response | Playbook for: prompt injection, jailbreak, data leak, biased output. |
18.12 · GPU / accelerator infrastructure
| Accelerator | Notes | Typical role |
|---|---|---|
| NVIDIA A100 / H100 / H200 / B200 | FP16 / FP8 / NVLink; most LLM kernels target these. | Training + serving anything from 7B to 700B. |
| NVIDIA L40S / L4 | Lower TDP; great inference / cost. | High-throughput serving for < 70B models. |
| AMD MI300X | Big HBM; ROCm-supported. | Cost-effective alternative to H100. |
| Google TPU v5e / v5p | Pod-scale training; XLA toolchain. | Frontier training; GCP-only. |
| AWS Trainium / Inferentia | Custom silicon, AWS-native. | AWS-locked workloads with strong $/token. |
Capacity terms you'll be quoted on
- GPU-hour — one GPU running for one hour.
- vRAM — accelerator memory; hard ceiling on model size at a given precision.
- NVLink / NVSwitch — high-bandwidth GPU-GPU interconnect; required for tensor-parallel serving.
- MIG — Multi-Instance GPU; split one A100/H100 into smaller slices for many small tenants.
18.13 · Cost engineering
- Right-size the model. Cascade: small first, big on low-confidence.
- Prompt caching — the cheapest single lever.
- Batch API — for offline jobs, 50% provider discount.
- Quantisation — same GPU serves a bigger model or more replicas.
- Reserved capacity for floor demand, spot/on-demand for bursts.
- Per-tenant budgets at the gateway — hard caps avoid horror stories.
- Showback / chargeback dashboards — tenants who see their cost optimise voluntarily.
18.14 · SLAs / SLOs / production-readiness gates
| Concept | Definition | Example |
|---|---|---|
| SLI | A measurable signal of service quality. | p95 TTFT, success rate, RAG faithfulness. |
| SLO | The target value of an SLI over a window. | p95 TTFT < 1.5s over 30 days. |
| SLA | The customer-facing contract with consequences if SLO is missed. | Credits if availability < 99.5%. |
| Error budget | 1 − SLO. The bad-time allowance before deploys are frozen. | 0.5% per month → ~3.6 hours. |
The production-readiness checklist
- Eval suite green; safety eval green; both reproducible.
- Model + dataset cards published; risk sign-off recorded.
- Canary plan + auto-rollback wired.
- Per-tenant quotas, budgets, and isolation tested.
- Observability: metrics, logs, traces, audit, HLEM all live.
- Runbooks: outage, drift, incident, data deletion.
- Capacity plan and cost model approved.
- Compliance review (residency, privacy, sector rules) signed.
18.15 · Vendor & design assurance
- Publish reference architectures; vendors map their design to them.
- Run design reviews at three gates: concept, detailed, pre-launch.
- Define acceptance criteria: functional, performance, safety, observability, security.
- Demand performance test plans (load, soak, chaos) before sign-off.
- Use PoCs to de-risk: 2-week timeboxed, scored against a rubric.
18.16 · The "golden path" developer experience
- SDKs wrapping the OpenAI-compatible API + retries + tenancy headers.
- Templates / starters: "RAG service", "agent with tools", "fine-tune job".
- Sample apps showing best practices end-to-end.
- Onboarding docs: setup → first call → first eval → first deploy → first alert.
- Office hours + a public roadmap.