A self hosted post training pipeline gives teams control over how an open-weight language model is adapted, evaluated, and deployed. Instead of sending proprietary prompts, conversations, or preference data to a third-party API, you can run training infrastructure inside your own cloud account, data centre, or compliant private environment. This is especially valuable for Indian startups and enterprises handling sensitive customer, financial, healthcare, government, or multilingual data.
The challenge is that post-training is not simply a fine-tuning script. A reliable system must connect data governance, annotation, distributed GPU training, experiment tracking, safety testing, model packaging, and production inference. This guide explains the architecture, workflow, infrastructure choices, and operating practices needed to build one.
What Is a Self Hosted Post Training Pipeline?
A self hosted post training pipeline is an end-to-end workflow for improving a pretrained or instruction-tuned model using infrastructure that your organisation controls. “Post training” generally includes supervised fine-tuning and preference optimisation performed after pretraining.
Typical stages include:
- Collecting and validating instruction, conversation, or domain data
- Removing personal information, secrets, unsafe content, and duplicates
- Creating supervised fine-tuning examples
- Generating or collecting preference pairs
- Running LoRA, QLoRA, or full-parameter training
- Evaluating capabilities, factuality, safety, and regression risk
- Registering and packaging model checkpoints
- Deploying the approved model behind an internal or public API
- Monitoring quality, latency, cost, and abuse in production
Self hosting does not necessarily mean owning physical GPUs. You can run the stack on dedicated servers, a private Kubernetes cluster, or rented GPU instances while retaining control over networking, storage, credentials, and data movement.
Why Build the Pipeline Yourself?
A managed fine-tuning API can be convenient, but it may be unsuitable when training data contains confidential or regulated information. A self hosted approach offers several benefits:
- Data control: Raw examples and preference labels remain within approved storage and network boundaries.
- Reproducibility: Dataset versions, configurations, containers, and model commits can be pinned.
- Custom optimisation: You can choose the model, training objective, quantisation method, and evaluation suite.
- Cost visibility: GPU hours, storage, and inference expenses can be measured directly.
- Deployment flexibility: The resulting model can run in a VPC, on-premises, or at an Indian data centre.
- Domain adaptation: Regional languages, industry terminology, and organisation-specific workflows can be handled more precisely.
The trade-off is operational complexity. Teams must manage GPU scheduling, driver compatibility, checkpoint storage, security, observability, and failures. A good design therefore starts with a narrow use case and a measurable quality target rather than attempting to build a general-purpose model immediately.
Reference Architecture
A practical self hosted post training pipeline can be separated into six layers.
1. Data layer
Use object storage such as S3-compatible storage, MinIO, or a cloud bucket for immutable dataset versions and checkpoints. Store structured metadata in PostgreSQL or a data catalogue. Keep raw, cleaned, labelled, and release-ready datasets in separate locations with explicit access controls.
Recommended dataset metadata includes:
- Source and collection date
- Language and domain
- Licence or consent status
- PII and safety scan results
- Annotation guidelines and annotator version
- Train, validation, and test split membership
- Dataset hash and transformation history
2. Orchestration layer
Use a workflow engine or CI/CD system to execute repeatable jobs. Common choices include Argo Workflows, Kubeflow Pipelines, Flyte, Airflow, GitHub Actions, and GitLab CI. Each run should record the code commit, container digest, base model revision, dataset version, hyperparameters, GPU type, and output artefacts.
3. Training layer
The training layer contains the distributed launcher, framework, checkpointing logic, and GPU workers. PyTorch with Hugging Face Transformers, Accelerate, DeepSpeed, or Fully Sharded Data Parallel is a common foundation. For parameter-efficient adaptation, PEFT supports LoRA and related methods.
4. Evaluation layer
Evaluation should be a required pipeline stage, not a manual notebook. Combine automated benchmarks, domain test sets, structured human review, red-team prompts, and regression comparisons against the base model.
5. Registry and release layer
Store approved adapters, merged checkpoints, tokenizer files, configuration, evaluation reports, and licence information in a model registry. MLflow, a private Hugging Face Hub deployment, or an internal registry can work well.
6. Serving and monitoring layer
Deploy the selected model using vLLM, TGI, SGLang, or another production inference server. Expose an authenticated API through an API gateway and collect latency, throughput, error rates, token usage, safety events, and feedback.
Step 1: Define the Training Objective
Before selecting GPUs, write down the behaviour the model must improve. Examples include:
- Answering customer support questions using approved product documentation
- Extracting structured fields from Indian business documents
- Following a company-specific tool-calling schema
- Improving Hindi, Tamil, Bengali, or mixed-language instruction following
- Producing concise legal, financial, or healthcare summaries with citations
Define success using a test set that resembles production traffic. Useful metrics may include exact match, F1, JSON schema validity, citation precision, task completion rate, hallucination rate, refusal accuracy, and human preference scores.
A vague goal such as “make the model smarter” creates a pipeline with no reliable stopping condition. A specific target enables sensible data collection and prevents overfitting to benchmark scores.
Step 2: Build a High-Quality Dataset
Post-training quality is usually constrained more by data quality than by the number of GPUs. Begin with a small, carefully reviewed dataset and establish annotation rules before scaling.
For supervised fine-tuning, each record commonly contains:
{
"messages": [
{"role": "system", "content": "Follow the company support policy."},
{"role": "user", "content": "How do I change my billing address?"},
{"role": "assistant", "content": "You can update it from..."}
],
"language": "en-IN",
"domain": "support",
"source": "approved_kb"
}For preference optimisation, a record may contain a prompt, a preferred answer, and a rejected answer. Labelers should receive clear criteria covering correctness, relevance, style, safety, and policy compliance.
Implement automated checks for:
- Empty or malformed conversations
- Excessive prompt or completion length
- Duplicate and near-duplicate examples
- Invalid roles or unsupported message formats
- PII, API keys, passwords, and internal identifiers
- Toxic, discriminatory, or unsafe content
- Train-test contamination
- Language mismatch and encoding errors
For India-focused deployments, test Unicode handling carefully. Indic scripts, code-switching, transliteration, and inconsistent punctuation can reveal tokenisation and data-cleaning problems that English-only validation misses.
Step 3: Choose the Post-Training Method
Supervised fine-tuning
SFT teaches the model to imitate high-quality demonstrations. It is usually the first post-training stage because it is comparatively stable and easy to diagnose. Use it for formatting, tone, workflows, domain terminology, and instruction following.
LoRA and QLoRA
LoRA trains low-rank adapter matrices while keeping the base model frozen. QLoRA additionally loads the base model in lower precision, reducing VRAM requirements. These methods are attractive for self hosting because they lower GPU cost and make it easy to maintain multiple domain-specific adapters.
Preference optimisation
Methods such as DPO, ORPO, and related objectives learn from preferred and rejected responses without requiring a separate reward model in every setup. Preference training can improve helpfulness, style, and policy adherence, but noisy labels can cause regressions. Keep a fixed evaluation set and compare against the SFT checkpoint.
Full-parameter fine-tuning
Full fine-tuning may be justified for major domain shifts or larger infrastructure budgets. It demands substantially more memory, reliable distributed training, and careful checkpoint management. Most teams should first establish gains with SFT and parameter-efficient methods.
Step 4: Size the GPU Infrastructure
GPU sizing depends on model parameters, sequence length, batch size, precision, optimiser states, checkpoint strategy, and whether you train adapters or all parameters. A rough planning approach is:
- Start with LoRA or QLoRA for a 7B–14B model.
- Use gradient accumulation to reach the desired effective batch size.
- Enable activation checkpointing to reduce memory consumption.
- Use bf16 on supported hardware; use fp16 with loss scaling where necessary.
- Benchmark tokens per second before committing to a long run.
- Reserve capacity for evaluation and retry jobs.
For larger models, FSDP or DeepSpeed ZeRO can shard parameters, gradients, and optimiser states across GPUs. High-speed interconnects become increasingly important as the number of workers grows. A low-cost network may be acceptable for adapter training but can make full fine-tuning inefficient.
In India, compare GPU availability and egress pricing across providers rather than relying only on hourly rates. Data residency, support, persistent volume performance, power reliability, and the ability to reserve A100, H100, L40S, or equivalent capacity may matter more than the headline price.
Step 5: Make Experiments Reproducible
Every training run should be reconstructable. Track at least:
- Git commit and container image digest
- Base model identifier and licence
- Dataset and tokenizer hashes
- Random seeds and split definitions
- Learning rate, scheduler, epochs, warm-up, and batch settings
- Sequence length, precision, quantisation, and gradient configuration
- GPU model, worker count, and distributed settings
- Checkpoint location and evaluation results
Use experiment tracking to compare training loss with validation loss and task-level metrics. A lower loss is not proof of better production behaviour. Watch for memorisation, verbosity changes, format failures, and safety regressions.
Save checkpoints to durable storage at sensible intervals, and test resuming from a checkpoint. Preemption, node failures, driver issues, and storage timeouts are normal in GPU environments; the pipeline should recover without restarting from zero.
Step 6: Design a Serious Evaluation Gate
A release gate should combine multiple test categories:
- Capability: Does the model complete the target task accurately?
- Groundedness: Does it use provided context and avoid invented facts?
- Format: Does it produce valid JSON, SQL, tool calls, or citations?
- Safety: Does it refuse harmful requests and protect sensitive data?
- Robustness: Does it handle paraphrases, typos, long inputs, and prompt injection?
- Multilingual quality: Does performance remain acceptable across target Indian languages?
- Regression: Did general instruction following or coding quality deteriorate?
Maintain a hidden holdout set so training decisions cannot gradually overfit the public evaluation set. Add production-like adversarial tests for indirect prompt injection, data exfiltration, malicious documents, and instruction conflicts.
Human evaluation remains important for open-ended tasks. Use a blinded rubric, multiple reviewers for ambiguous cases, and inter-rater agreement tracking. Store evaluation artefacts beside the model version so release decisions are auditable.
Security and Governance Considerations
A self hosted pipeline is not automatically secure. Apply least-privilege IAM, private networking, encrypted storage, encrypted transport, secrets management, and separate credentials for training and production. Never place API keys or customer exports directly in notebooks or shell history.
Create retention policies for raw conversations and annotation data. Where applicable, de-identify personal information before it enters training storage and document consent, purpose limitation, and deletion processes. Indian organisations should assess obligations under the Digital Personal Data Protection Act, contractual requirements, sectoral rules, and customer data-residency commitments.
Also verify the base model and dataset licences. A model that permits research use may restrict commercial redistribution or hosted access. Keep a model card describing data sources, known limitations, intended use, prohibited use, evaluation results, and changes from the base checkpoint.
Serving the Fine-Tuned Model
For production inference, package the tokenizer, model or adapter, generation defaults, chat template, quantisation configuration, and safety policy together. Confirm that the serving engine applies the same chat template used during training; mismatches can significantly reduce quality.
Expose controls for:
- Authentication and tenant isolation
- Maximum input and output tokens
- Rate limits and quotas
- Request timeouts and cancellation
- Streaming responses
- Structured output validation
- Prompt and response redaction
- Fallback to a baseline model
Monitor time to first token, inter-token latency, tokens per second, GPU utilisation, queue depth, out-of-memory errors, and cost per request. Sample responses for quality review only under an approved privacy policy. Feedback loops should distinguish model failures from retrieval, tool, or application failures.
Common Failure Modes
Training on unfiltered logs
Raw chat logs often contain duplicated prompts, sensitive data, policy violations, and low-quality answers. Clean, classify, and sample before training.
Overfitting a small dataset
The model may memorise wording while failing on paraphrases. Use augmentation carefully, maintain a holdout set, and test on realistic traffic.
Ignoring the chat template
Different model families expect different role tokens and formatting. Use the official template and verify tokenised examples before training.
Evaluating only loss
Loss can improve while factuality, refusal behaviour, or structured output quality worsens. Use task-level and safety metrics.
Treating an adapter as a complete model
An adapter may depend on an exact base-model revision, tokenizer, and configuration. Record and package all dependencies.
No rollback path
Keep the previous production model available, define approval criteria, and support rapid rollback when monitoring detects regressions.
A Practical MVP Stack
A cost-conscious first version can use:
- Object storage with versioned datasets and checkpoints
- PostgreSQL for metadata
- Docker with pinned CUDA and framework versions
- PyTorch, Transformers, PEFT, and Accelerate
- MLflow or a private experiment tracker
- A single GPU for initial LoRA experiments
- vLLM or TGI for serving
- Prometheus and Grafana for infrastructure metrics
- A small, reviewed evaluation harness in CI
Once the workflow is stable, add Kubernetes scheduling, multi-node training, automated data quality checks, model registry approvals, canary releases, and continuous evaluation. Automate only after the manual process is understood; otherwise, the team may scale inconsistent data and unreliable metrics.
FAQ
Is self hosted post training cheaper than an API?
It can be cheaper at sufficient volume, especially with open-weight models and LoRA adapters. At low volume, GPU operations, storage, engineering time, and monitoring may outweigh API costs.
Can a startup run the pipeline without a large ML team?
Yes, if it starts with a focused task, a small open-weight model, parameter-efficient fine-tuning, managed GPU instances, and strong evaluation discipline. Avoid building distributed infrastructure before proving quality gains.
Should I fine-tune or use retrieval-augmented generation?
Use retrieval for changing facts and private knowledge that must remain updateable. Fine-tune behaviour, output formats, tone, and repeatable workflows. Many production systems use both.
How do I support Indian languages?
Use representative native-script and code-switched data, validate tokenisation, evaluate each target language separately, and include regional names, formats, units, and cultural context. Do not assume English metrics transfer to Indic languages.
What is the minimum evaluation set?
There is no universal number, but a useful MVP should include representative production tasks, edge cases, safety prompts, multilingual examples where relevant, and a hidden holdout set. Track both automated metrics and reviewed samples.
Apply for AI Grants India
Building a self hosted post training pipeline can unlock defensible, privacy-aware AI products for Indian markets. Apply for support from AI Grants India and share your technical approach, target users, and funding needs.