Training, Fine-Tuning and Deploying Open-Weight LLMs: A Technical Learning Guide
A vendor-neutral learning guide to adapting and running open-weight language models, from data and fine-tuning methods to memory planning, distributed training, serving and governance.
Published: November 2026
This guide is written for learning. It explains, in technical terms, how teams adapt and run open-weight language models: choosing an adaptation method, the training lifecycle, fine-tuning techniques, memory arithmetic, distributed training, serving, inference optimization, architecture and security.
It focuses on concepts and methods. It does not describe, compare, rank or evaluate any specific model, product, company or service, and it does not interpret any license. Where it names models, hardware, tools or providers, it gives names only, so you know what to look up, with links to their official pages in the further-reading section. Always rely on those official sources for current details. Nothing here is legal, licensing, regulatory, medical, financial or purchasing advice.
Choosing the right adaptation method
Prompting, retrieval-augmented generation (RAG), fine-tuning, continued pretraining and training from scratch solve different problems.
Prompting changes behavior for a single request. It needs no training, so it is the natural first step. RAG changes what the model can draw on at answer time by retrieving documents into the prompt. It suits knowledge that changes often, answers that must cite sources and information whose visibility depends on who is asking. Fine-tuning changes the model's weights. It suits consistent output format, tone or domain behavior, and cases where long instructions would otherwise be repeated on every request. Continued pretraining feeds large volumes of domain text into a base model before instruction tuning, to strengthen its command of a specialized vocabulary or language. Training from scratch builds a model from random initialization and requires data, compute and research capacity at a very different scale.
A simple way to remember it: missing knowledge points to RAG, unwanted behavior points to prompting and then fine-tuning, and weak command of a domain's language points to continued pretraining. Many systems combine methods, serving facts through retrieval and learning behavior in the weights.
Open weight, open source and proprietary
An open-weight model makes its weights available for download under terms set by its publisher. An open-source AI model, as defined in the Open Source Initiative's Open Source AI Definition 1.0, is made available under terms that grant the freedoms to use, study, modify and share it, together with the preferred form for making modifications: detailed information about the training data, sufficient for a skilled person to build a substantially equivalent system, the complete code used to train and run it, and the model parameters [20]. The definition does not require every raw training dataset to be published. A proprietary model is one whose terms do not grant these freedoms; it may be offered only as a hosted service, or its weights may be downloadable under restrictive terms. The categories therefore overlap, and an open-weight model is not necessarily open source under this definition.
Being able to download weights does not by itself mean that use is unrestricted, that commercial use is permitted or that the license is an open-source license. Licenses differ from model to model and from version to version, and terms can cover, for example, commercial use, redistribution and hosting for others, naming and attribution of derivative models, acceptable-use policies and the use of outputs. This guide does not summarize any specific license. Before you use, modify, fine-tune or redistribute any model or its outputs, read its full license, acceptable-use policy and model card in the official repository and have them reviewed by qualified counsel.
It also helps to keep five things apart: the license for the weights; the terms of service of any provider through which you use a model; any terms that address model outputs; third-party copyrighted material that may appear in outputs; and the copyright law of the jurisdiction concerned. A weight license does not by itself settle the legal status of every output, and whether outputs are protected by copyright, and who may use them and how, are legal questions whose answers vary by jurisdiction and circumstances [24].
Model families to explore
Open-weight model families are published by labs in several countries. The names below are given only so you can find them; their sizes, architectures, context lengths, capabilities and licenses differ by version and change often, so read each official model card and license. The list is alphabetical, not exhaustive and not a ranking or recommendation.
Baichuan, DeepSeek, Falcon, Gemma, GLM, InternLM and Intern-S, Kimi, Llama, MiniMax, Mistral, OLMo, Phi, Qwen.
When you compare candidates for a project, use your own criteria: license review by counsel, required languages and modalities, context length, whether the model fits your hardware at the precision you plan to use, support in your training and serving frameworks, and results on your own evaluation set.
Two architecture terms will come up often. A dense model uses all of its parameters for every token. A Mixture-of-Experts (MoE) model contains many expert sub-networks but routes each token to only a few of them, so its total parameter count sets the memory needed to hold it, while its activated parameter count sets the compute per token.
The training lifecycle, step by step
1. Problem framing. Define the task, the success metric, the latency and cost budgets and the deployment constraints before choosing a model. Starting with the smallest model that could plausibly meet them keeps tuning, serving and evaluation cheaper.
2. Dataset collection. Collect examples of the target behavior, such as questions with ideal answers, approved documents, expert-written responses and tool-call traces. For fine-tuning, a smaller set of clean, representative examples can matter more than a large noisy one. Use only data you have the right to use for this purpose: check copyright, database rights, website terms, contracts and licenses for every source. If you generate synthetic examples with another model, filter and review them, and check that model's terms of use, which may restrict how its outputs can be used. The law on training with copyrighted material, and on the status of AI-generated output, is still developing and differs between jurisdictions; the U.S. Copyright Office's multi-part report on copyright and AI is one example of official work on these questions [24].
3. Licensing and governance. Record the source, terms and sensitivity of every dataset, and confirm with counsel that both the data and the base model may be used as you intend, including for derivative weights, hosting for others, redistribution and any notice or attribution the license requires.
4. Cleaning and deduplication. Remove boilerplate, encoding errors, near-duplicates and anything that overlaps with your evaluation sets.
5. Personal and sensitive data. Detect and redact or tokenize personal data before training, because a fine-tuned model can reproduce text it was trained on. Redaction reduces risk but does not by itself make data anonymous or make its use lawful: under the GDPR, for example, pseudonymised data that could be attributed to a person by the use of additional information is still considered information on an identifiable person, and therefore personal data (Recital 26) [25]; the EDPB's draft guidelines on pseudonymisation discuss this in more detail [23]. Where data-protection law applies, you will typically also need a lawful basis, a defined purpose, retention limits and, for higher-risk processing, an impact assessment. Requirements differ by jurisdiction, so confirm them with your data-protection adviser.
6. Tokenization. Use the base model's tokenizer and check how efficiently it encodes your languages and domain terms; inefficient tokenization raises cost and shortens effective context.
7. Formatting. Convert examples into the model's chat template, with system, user, assistant and tool roles exactly as its documentation specifies. Template errors are a frequent reason a fine-tune underperforms.
8. Pretraining and continued pretraining. Pretraining learns language from very large corpora. Continued pretraining extends an existing base model on domain text; because it can weaken general ability, mix in general data and evaluate both.
9. Supervised fine-tuning (SFT). Train on pairs of inputs and ideal outputs to teach format, tone, domain behavior and tool use.
10. Parameter-efficient fine-tuning (PEFT). Train a small set of added parameters instead of all weights, which reduces memory and lets several adapters share one base model.
11. LoRA and QLoRA. LoRA freezes the base weights and trains low-rank update matrices [1]. QLoRA applies the same idea to a base model quantized to 4 bits; its paper reports fine-tuning a 65-billion-parameter model on a single 48 GB GPU [2].
12. Preference optimization. After SFT, train on comparisons between better and worse answers to shape helpfulness, safety and style.
13. RLHF, DPO and GRPO. RLHF trains a reward model from human preferences and optimizes the policy against it with reinforcement learning [7]. DPO optimizes directly on preference pairs without a separate reward model or reinforcement learning loop [5]. GRPO, introduced in the DeepSeekMath paper, is a variant of PPO designed to reduce PPO's memory use [6].
14. Evaluation. Build a task-specific evaluation set before training, keep it out of the training data, and compare each candidate with the base model and with the version currently in use. Include safety and regression tests.
15. Quantization and optimization. Reduce numeric precision for serving, for example with the GPTQ [12] or AWQ [11] methods or with lower-precision floating-point formats where your hardware and software support them, and re-run your evaluation after each change.
16. Packaging and deployment. Export weights and adapters in the format your serving software expects, register them with their dataset version and training configuration, and deploy behind an API gateway.
17. Monitoring and improvement. Prompts and outputs can contain personal or confidential data, so decide what is logged, who can access it and how long it is kept. Log request metadata, model and version information, execution outcomes and reviewed feedback under appropriate access and retention controls. Retain actual prompt and output content only where necessary, with data minimization and redaction. Monitor for drift and regressions, and feed reviewed failure cases into the next training round.
Fine-tuning techniques compared
| Technique | What it changes | When it fits | Main limitations |
|---|---|---|---|
| Full fine-tuning | All weights | Large, high-quality datasets; deep adaptation | Highest memory and compute; risk of forgetting; one full copy per variant |
| LoRA [1] | Low-rank adapters on a frozen base | Many SFT tasks | Less expressive than full tuning for very large shifts |
| QLoRA [2] | LoRA on a 4-bit quantized base | Limited GPU memory | Quantization noise; can be slower per step |
| AdaLoRA [3] | LoRA with adaptive allocation of rank across weights | Uneven capacity needs across layers | More hyperparameters |
| DoRA [4] | Weights split into magnitude and direction, with LoRA on direction | When LoRA underfits | Some extra compute |
| SFT | Behavior learned from demonstrations | Format, tone, tools, domain answers | Does not capture preferences well |
| Continued pretraining | Domain language knowledge | Specialized vocabulary or languages | Large data and compute; can weaken general ability |
| RLHF [7] | Policy optimized against a learned reward model | Optimizing subjective quality | Complex; several models in memory |
| DPO [5] | Policy learned from preference pairs | Preference tuning without RL infrastructure | Needs good preference data |
| GRPO [6] | Policy optimized with advantages computed relative to a group of sampled answers | Tasks where rewards can be computed automatically | Reward design; risk of reward hacking |
| Knowledge distillation [13] | A small student trained to imitate a large teacher | Lower serving cost for narrow tasks | Inherits teacher errors; check the teacher's terms on use of its outputs |
Memory arithmetic
These figures are arithmetic, not measurements, and GB here means 10^9 bytes. They cover model states only and exclude activations, batch size, sequence length, KV cache and framework overhead, which can add substantially. Use them to understand orders of magnitude, then test on real hardware.
Weight memory is the parameter count multiplied by the bytes per parameter: 2 bytes for 16-bit formats such as BF16, 1 byte for 8-bit formats and about 0.5 bytes for 4-bit formats.
| Parameters | 16-bit weights | 8-bit weights | 4-bit weights | Full fine-tuning model states (mixed-precision Adam, ~16 bytes/param) |
|---|---|---|---|---|
| 7B | ~14 GB | ~7 GB | ~3.5 GB | ~112 GB |
| 14B | ~28 GB | ~14 GB | ~7 GB | ~224 GB |
| 32B | ~64 GB | ~32 GB | ~16 GB | ~512 GB |
| 70B | ~140 GB | ~70 GB | ~35 GB | ~1,120 GB |
These 4-bit figures represent packed weight values only; actual quantized model storage can be higher because of quantization metadata, scales, zero-points and alignment.
The last column uses the figure from the ZeRO paper for mixed-precision training with the Adam optimizer: about 16 bytes per parameter for weights, gradients, full-precision master weights and optimizer states [8]. That figure is specific to this configuration; actual memory varies with the optimizer implementation, the precision of parameters, gradients and optimizer states, the sharding strategy and the framework configuration. This is why full fine-tuning can exceed the memory of a single GPU even for small models, while LoRA and QLoRA, which keep the base frozen, need far less.
At inference, the KV cache adds memory that grows with context length and with the number of concurrent requests. For models using standard multi-head or grouped-query attention, its size per token is 2 (keys and values) × layers × KV heads × head dimension × bytes per value; some architectures compress the cache differently. For an illustrative model with 32 layers, 8 KV heads of dimension 128 and 16-bit values, that is 2 × 32 × 8 × 128 × 2 = 131,072 bytes per token, so 100 concurrent requests of 8,000 tokens each need about 98 GiB for the cache alone. Long contexts and high concurrency are therefore memory problems first.
Hardware concepts
Training needs memory for weights, gradients, optimizer states and activations, plus high-bandwidth links between GPUs. Inference needs memory for weights and the KV cache, and memory bandwidth to generate tokens quickly. Plan the two separately.
The terms you will meet most often: GPU memory capacity (how much fits), memory bandwidth (how fast weights and cache can be read, which matters for token generation), tensor cores or matrix engines (specialized units for matrix math), NVLink and NVSwitch or equivalent scale-up fabrics (high-bandwidth links between GPUs in a server or rack), PCIe (the general expansion bus, slower than dedicated GPU links), InfiniBand or RDMA-capable Ethernet (low-latency networking between nodes), and the software stack each accelerator family uses, such as CUDA or ROCm.
Accelerator names you may encounter include NVIDIA H100, H200, B200, GB200 NVL72 and GB300 NVL72, and AMD Instinct MI300X, MI325X and MI355X. Specifications differ by model, form factor and configuration; read the vendor's current specification sheet, and confirm that every framework feature and numeric format you need is supported on your target platform and software version.
Size CPU memory and local NVMe storage for data loading and checkpoint writes so storage does not stall training.
Distributed training
Data parallelism replicates the model on every GPU and splits each batch among them. Tensor parallelism splits individual layers across GPUs and needs very fast links, so it usually stays within one server or scale-up domain. Pipeline parallelism assigns groups of layers to different GPUs or nodes and keeps them busy with micro-batches. Expert parallelism places MoE experts on different GPUs. Context parallelism splits long sequences across GPUs. The Megatron-LM papers describe combining these approaches on large clusters [14][15].
Sharding removes the duplication of plain data parallelism. In ZeRO, stage 1 shards optimizer states, stage 2 also shards gradients and stage 3 also shards the parameters [8]. Fully sharded data parallelism in PyTorch applies the same idea. Gradient accumulation simulates larger batches with limited memory, and gradient checkpointing trades extra compute for lower activation memory.
Mixed precision is standard. BF16 keeps the numeric range of FP32 with half the memory, which makes it a common training choice. Lower-precision formats such as FP8 can reduce memory and increase speed, but support depends on hardware and library versions; when you adopt one, compare training loss against a BF16 run.
Checkpoint frequently to durable storage and test that jobs can resume. On large clusters, plan for hardware failures, since a job that cannot restart can lose days of work.
Software you will encounter
The ecosystem changes quickly, so these are names to look up rather than descriptions to rely on. Read each project's documentation for its current features, supported hardware and maintenance status.
- Languages: Python for training, data and evaluation; C++ and CUDA for kernels and engines; Triton for writing GPU kernels; Rust in some performance-sensitive tooling.
- Training libraries: PyTorch, Hugging Face Transformers, TRL, PEFT, DeepSpeed, Megatron-LM, Axolotl, LLaMA-Factory, Unsloth, torchtune.
- Data processing: Apache Spark, Ray, Apache Arrow, Parquet, WebDataset, Hugging Face Datasets.
- Experiment tracking and pipelines: MLflow, Weights & Biases, Kubeflow, Metaflow, ClearML.
- Serving software: vLLM, SGLang, NVIDIA Triton Inference Server, NVIDIA NIM, TensorRT-LLM, llama.cpp, Ollama, Hugging Face Text Generation Inference.
A typical pipeline connects them like this: raw data lands in object storage, a distributed processing job cleans and deduplicates it into a versioned snapshot, a training job reads that snapshot with a distributed training library, metrics go to an experiment tracker, the chosen checkpoint is registered with its dataset version, and an automated job evaluates it before deployment.
Where training and serving can run
| Category | What you manage | Typical uses |
|---|---|---|
| Your own hardware (bare metal or on-premises) | Hardware, network, software and data | Workloads needing maximum control or data that must stay on-site |
| Schedulers on your infrastructure (Kubernetes, Slurm, containers) | Scheduling, images, data | Shared GPU clusters for many teams and jobs |
| Cloud GPU infrastructure | Instances or clusters and your software stack | Flexible capacity without owning hardware |
| Managed model platforms | Data and job configuration; the provider runs infrastructure | Faster setup with less operations work |
| Serverless GPU services | Code or model and scaling settings | Bursty or low-volume workloads, with cold starts to consider |
Providers you may come across include Amazon Web Services, CoreWeave, Fireworks AI, Google Cloud, Hugging Face, Lambda, Microsoft Azure, Modal, Oracle Cloud, Replicate, RunPod, Together AI and Vast.ai. The list is alphabetical, not exhaustive, and not a classification, comparison or endorsement; what each offers, for which models and in which regions, is described in its own documentation and terms, which change over time.
Deploying on managed platforms
Managed platforms run the serving infrastructure for you, so your team works on the model, its configuration and the integration rather than on GPUs, drivers and scaling. In general they come in a few forms:
- Shared endpoints for catalog models. You call a model the platform already hosts and typically pay per token. This is the quickest start, with the least control over versions and capacity.
- Dedicated deployments. The platform reserves GPU capacity for your model, often billed by time. Latency is more predictable and you control scaling, but you also pay while capacity is idle.
- Bring your own weights or adapters. You upload a fine-tuned model or adapter and the platform serves it. Check which architectures, file formats and adapter types are supported.
- Serverless GPU functions. Your code and model run only when requests arrive, which suits bursty traffic; plan for cold starts while weights load.
Before choosing one, look for these points in the platform's own documentation and terms: where data is processed and stored, including logs, backups and support access, whether it is transferred across borders, and whether prompts or outputs are retained or used for training; available regions and private networking options; how the model and its serving software are versioned and how changes are announced; autoscaling limits, rate limits and quotas; which metrics and logs you can see; and how you would move the same model to another platform or to your own infrastructure if needed. Run your own evaluation set and latency tests on the platform before production, because outputs can differ between serving stacks.
Inference optimization concepts
An LLM request has two phases. Prefill processes the prompt and builds the KV cache, the stored attention keys and values for every token; it is compute-heavy and determines time to first token (TTFT). Decode then generates one token per step, rereading the weights and cache each time; it is memory-bandwidth-heavy and determines time per output token (TPOT).
PagedAttention manages KV cache memory in fixed-size pages to reduce fragmentation and waste [16]. Continuous batching adds and removes requests from a running batch at each step rather than waiting for a whole batch to finish. Prefix caching reuses the cache for prompts that share a common beginning. Chunked prefill splits long prompts so they do not stall token generation for other requests. Disaggregated prefill and decode runs the two phases on separate GPU pools so each can be configured independently, at the cost of transferring the cache between them. Speculative decoding lets a small draft model propose several tokens that the main model verifies in one pass; its paper shows the outputs follow the same distribution as the main model alone [10]. FlashAttention reorganizes the attention computation to cut data movement between the GPU's fast on-chip memory and its main memory [9].
Quantization reduces numeric precision to save memory and often increase throughput. GPTQ [12] and AWQ [11] are published weight-quantization methods; GGUF is a file format used by some local runtimes for quantized models. Measure quality on your evaluation set after every precision change.
Measure what users experience and what you pay for: TTFT, TPOT and end-to-end latency at the 50th, 95th and 99th percentiles, tokens per second, and cost per million tokens. Cost per million tokens can be estimated as the hourly cost of the GPUs divided by the tokens they generate per hour, multiplied by one million, using your own measured throughput at your latency target and your own actual costs. Larger batches usually raise throughput and latency together, so set the latency target first and maximize throughput within it.
Reference architecture: from data to production traffic
Data sources feed ingestion, where schema and quality checks reject bad batches. Processing cleans, deduplicates and redacts, then writes immutable dataset versions. Training jobs read a specific version, log to the tracker and write checkpoints. An evaluation gate compares each candidate with the version in use on task, safety and latency tests, and only passing models enter the registry with their lineage. Optimization produces the serving artifact. The gateway authenticates and authorizes callers and applies quotas, then hands requests to a router that selects a model pool and falls back when one is unavailable.
Treat models like software releases. Continuous integration runs evaluation on every candidate. Continuous delivery deploys to a canary pool that receives a small share of traffic, and promotion follows only if quality, latency and error metrics hold. Blue-green deployment keeps the previous version ready for rollback. Pin the serving software version together with the model version, because software upgrades can change outputs.
Run inference pools on a container orchestrator with GPU node pools, and scale on signals such as queue depth, concurrent requests or KV cache usage rather than CPU. Spread replicas across zones, keep a second region with replicated registries and datasets for disaster recovery, and rehearse failover. Pre-stage model weights close to where they run so new replicas start quickly.
Security and governance
Treat training data as sensitive by default: restrict access, redact personal data before training and keep lineage. Treat model weights as part of your software supply chain: download them only from official sources, verify checksums or signatures where published, prefer file formats that do not execute code when loaded, scan dependencies and store approved artifacts in a private registry. Test tuned models with adversarial and red-team cases for poisoning and backdoor behavior, not just for accuracy.
At inference time, the OWASP Top 10 for LLM Applications describes risk categories including prompt injection, sensitive information disclosure, data and model poisoning, excessive agency and unbounded consumption [17]. Authenticate endpoints, apply rate limits and quotas, keep secrets in a secrets manager, encrypt data in transit and at rest, and keep audit logs that support incident investigation without storing more than necessary. Record request metadata and caller identity, the model and model version that answered, authorization and policy decisions, and execution outcomes and security events. Retain the actual prompt and output content only where it is needed, subject to data minimization, redaction, access controls and retention limits. When you self-host, check the network and telemetry behavior of every component. If data must stay in a jurisdiction, remember that hosting the model in the required region alone does not guarantee data residency: prompts and inputs, outputs, application and infrastructure logs, backups and checkpoints, telemetry and monitoring, control-plane services, support and administrator access, subprocessors, and external APIs or integrations can each process or store data elsewhere, and cross-border transfers can be subject to their own legal rules.
For governance, the NIST AI Risk Management Framework is a voluntary framework for managing AI risk [18], and NIST has published a companion profile for generative AI [22].
In the European Union, the AI Act, Regulation (EU) 2024/1689, takes a risk-based approach: obligations depend on an organization's role, such as provider or deployer, and on the risk category and intended purpose of the AI system. According to the European Commission, the Act entered into force on 1 August 2024 and applies in stages: rules on prohibited practices and AI literacy from 2 February 2025, obligations for providers of general-purpose AI models from 2 August 2025, most other provisions from 2 August 2026, and, after the 2026 amending Regulation (EU) 2026/1744, known as the Digital Omnibus on AI, high-risk rules for the use cases in Annex III from 2 December 2027 and for AI in products covered by Annex I from 2 August 2028 [19]. The Commission's guidelines on general-purpose AI models indicate that only significant modifications make the modifier a provider of the modified model [21]. The open-source exemption is limited: under Article 53(2), the obligations in Article 53(1)(a) and (b), covering technical documentation and information for downstream providers, do not apply to providers of models released under a free and open-source licence whose parameters, architecture information and usage information are publicly available. The obligations to put in place a copyright policy and to publish a summary of the content used for training still apply, and the exemption does not apply to general-purpose AI models with systemic risk [19]. Whether a particular model or provider qualifies, and whether and how the Act applies at all, depends on the facts, your role, where the system is placed on the market or used, and what it is for; the Act does not apply to every model or deployment in the same way.
Outside the AI Act, personal data processing may fall under the GDPR in the EU, the UK GDPR in the United Kingdom and other national laws elsewhere, and hardware, software, data and model access can be subject to export-control, sanctions, intellectual-property, cybercrime and data-protection rules. Identify the ones that apply to you with qualified counsel; technical controls support compliance work but do not establish it on their own.
Five illustrative scenarios
These are hypothetical scenarios for learning. They describe no real organization, name no specific model and are not recommendations. Validate every choice on your own data, hardware and requirements.
1. A small model for customer support. Goal: consistent answers in a defined style, in several languages, with low latency, keeping tickets in-house. Approach: a small dense model whose license your counsel has approved, LoRA SFT on cleaned and redacted example answers plus tool-call examples, then DPO on ranked answer pairs. Facts that change often stay in RAG rather than in the weights. Risks: stale knowledge and over-fitting to past phrasing.
2. A mid-size model for text-to-SQL analytics. Goal: correct queries against a known schema, with explanations. Approach: SFT on question, query and result examples validated by analysts, then reinforcement learning such as GRPO with a reward based on whether the query runs and returns the expected result. Enforce data permissions in the database, not in the prompt, and show the generated query with each answer. Run generated SQL with read-only, least-privilege credentials; parse and validate it, for example at the syntax-tree level, to block destructive or unauthorized statements; apply query timeouts, resource limits, row limits and pagination; enforce tenant-level authorization and data isolation; and audit both the generated and the executed queries. Risk: confident but wrong results.
3. Document processing in healthcare or legal settings. This scenario covers extraction and draft summaries to support professionals; it is not clinical decision-making or legal advice. Approach: de-identified documents labeled by qualified experts under a documented legal basis, optional continued pretraining on domain text, then SFT, deployed on private infrastructure in the required jurisdiction, with risk-proportionate audit trails, role-based access control, redaction of sensitive data in logs where appropriate, defined retention limits, and review by a qualified professional before any output is relied on professionally. Health information is subject to stricter rules in many jurisdictions, including as a special category of personal data under the GDPR, and depending on its intended purpose such a system may also fall under medical-device rules or the high-risk categories of the EU AI Act, so it requires legal review before deployment. Risks: incorrect content and privacy exposure, which is why automation stops at drafting.
4. A large model at high request volume. Goal: serve many concurrent users. Approach: use the memory arithmetic above to size weights and KV cache for your precision and context length, run many replicas on a container orchestrator, use continuous batching and prefix caching, and consider speculative decoding or disaggregated prefill and decode only when measurements justify them. Scale on queue depth, spread across zones and regions, and canary every model or software change. The main cost lever is tokens per GPU-hour at your latency target.
5. Several models with routing and failover. Goal: different models per task, automatic failover and policy controls. Approach: a router classifies each request by task, language, data sensitivity and region, and policy rules, informed by license review and internal requirements, decide which models may process which data. Each model pool has its own software version, evaluation set and canary process, and outputs are validated against schemas. Risks: inconsistent behavior between models and operational complexity, so keep the number of models as small as the requirements allow.
Choosing an approach: a technical decision matrix
| Option | Technically suited when | Less suited when | Main engineering effort |
|---|---|---|---|
| Hosted model service | Fast delivery, moderate volume, data may be shared under contract | Strict residency, need for weight-level control | Integration and evaluation |
| Self-hosted open-weight model | Data control or residency is required and a suitable base model exists | No capacity to operate GPU infrastructure | Serving platform and on-call |
| Fine-tuning | Consistent format, tone or domain behavior; long repeated prompts | The problem is missing or changing knowledge | Data preparation, evaluation, training runs |
| Continued pretraining | Specialized vocabulary or language | Limited domain text | Large-scale training and research effort |
| Training from scratch | Unique data at very large scale and a dedicated research team | Nearly all other cases | Large clusters and long timelines |
Closing notes
Three engineering capabilities tend to matter more than any single model choice: a task-specific evaluation set that can decide between candidates, a reproducible pipeline from versioned data to registered models, and a serving platform that can change models safely with canaries and rollback. With those in place, a model becomes a component you can replace as your needs change.
About the author. Asif Ali is a Principal AI & Enterprise Architect who writes about production-grade AI architecture and AI security.
This guide is provided for educational and technical information purposes only. It does not constitute legal, licensing, regulatory, medical, financial or purchasing advice, and it does not describe, rank, endorse or criticize any model, company, product or service. Model, hardware, software and provider names are used only to identify them; all names, trademarks, research papers and linked materials remain the property of their respective owners, and no affiliation, sponsorship or endorsement is implied. References and links do not grant any permission to reproduce, redistribute or commercially use third-party content. Technical specifications, provider terms, licenses and legal requirements change over time, and figures here are illustrative arithmetic based on stated assumptions, not measurements, quotes or guarantees. The author makes no representation that the information is complete, current or suitable for any particular purpose. Readers are responsible for independently verifying technical details, license conditions, provider terms, rights in model outputs and regulatory obligations, and should seek qualified professional advice, before relying on or implementing anything in this guide. Nothing in this notice limits any rights or obligations that cannot be limited under applicable law. If you believe any statement here is inaccurate, please get in touch through the contact options on this site so it can be reviewed and corrected.
FAQ
When should I fine-tune instead of using RAG?
Fine-tune when the problem is behavior: consistent format, tone, domain style or tool use, or long instructions repeated on every request. Use RAG when the problem is knowledge that changes, must be cited or depends on the caller's permissions. Many systems combine both, keeping facts in retrieval and behavior in the weights.
What is the difference between open-source and open-weight models?
Open-weight models make their weights available for download under terms set by the publisher. Open-source AI, as defined by the Open Source Initiative, also grants the freedoms to use, study, modify and share, and provides detailed training-data information, the complete training and inference code and the parameters, though not necessarily every raw training dataset [20]. Proprietary models do not grant these freedoms; some are hosted-only and some offer downloadable weights under restrictive terms. Downloadable weights do not by themselves mean unrestricted or commercial use is allowed, so always read the specific license and terms.
How do I estimate the memory needed to fine-tune a model?
Multiply the parameter count by the bytes per parameter: about 2 bytes in 16-bit formats, 1 byte in 8-bit and 0.5 bytes in 4-bit. Full fine-tuning in the mixed-precision Adam setup described in the ZeRO paper needs roughly 16 bytes per parameter for model states [8]; other optimizers, precisions and sharding strategies change this figure. Activations, sequence length and overhead come on top, so test on real hardware.
What is the difference between LoRA and QLoRA?
LoRA freezes the base model and trains small low-rank adapter matrices [1]. QLoRA applies LoRA to a base model quantized to 4 bits, which reduces memory further; its paper reports fine-tuning a 65-billion-parameter model on a single 48 GB GPU [2].
What are DPO and GRPO?
Both are typically applied after supervised fine-tuning. DPO trains directly on pairs of preferred and rejected answers without a separate reward model or reinforcement learning loop [5]. GRPO is a variant of PPO introduced in the DeepSeekMath paper and designed to reduce PPO's memory use [6].
What do TTFT and TPOT measure?
Time to first token (TTFT) is the wait before the first output token and is driven by the prefill phase. Time per output token (TPOT) is the pace of generation afterward and is driven by the decode phase. Track both at the 50th, 95th and 99th percentiles, because averages hide slow requests.
Why does the KV cache limit concurrency?
The KV cache stores attention keys and values for every token of every active request, so it grows with context length and the number of concurrent requests. For standard multi-head or grouped-query attention, its size per token is 2 × layers × KV heads × head dimension × bytes per value, and long contexts quickly consume memory that could otherwise serve more requests.
How do Mixture-of-Experts models affect hardware planning?
In a Mixture-of-Experts model, all experts must be held in memory, so the total parameter count sets the memory requirement, while only the activated experts compute for each token. This can lower compute per token compared with a dense model of the same total size, provided the software handles expert parallelism for that model.
How should model weights be checked before deployment?
Download only from the publisher's official source, verify checksums or signatures where published, prefer file formats that do not execute code when loaded, scan dependencies, test the model with adversarial and red-team cases, and store approved artifacts in a private registry with their license and version recorded.
When does a managed platform make more sense than self-hosting?
A managed platform suits teams that want to deploy quickly without operating GPU infrastructure, or whose traffic is low or bursty. Self-hosting suits teams that need full control over data location, model and software versions, or networking, and that can run a serving platform. Either way, review the platform's data-handling terms and test with your own evaluation set.
When does training a model from scratch make sense?
Rarely. It requires unique data at very large scale, large GPU clusters, a dedicated research team and long timelines. For most needs, an existing open-weight model combined with RAG, fine-tuning or continued pretraining can reach the goal with less cost and risk.
References
Research papers are cited for the findings their authors report. Legal and regulatory sources were checked on 26 November 2026 and may since have changed.
- Hu et al., LoRA: Low-Rank Adaptation of Large Language Models, 2021.
- Dettmers et al., QLoRA: Efficient Finetuning of Quantized LLMs, 2023.
- Zhang et al., AdaLoRA: Adaptive Budget Allocation for Parameter-Efficient Fine-Tuning, 2023.
- Liu et al., DoRA: Weight-Decomposed Low-Rank Adaptation, 2024.
- Rafailov et al., Direct Preference Optimization: Your Language Model is Secretly a Reward Model, 2023.
- Shao et al., DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models, 2024.
- Ouyang et al., Training language models to follow instructions with human feedback, 2022.
- Rajbhandari et al., ZeRO: Memory Optimizations Toward Training Trillion Parameter Models, 2019.
- Dao et al., FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness, 2022.
- Leviathan et al., Fast Inference from Transformers via Speculative Decoding, 2022.
- Lin et al., AWQ: Activation-aware Weight Quantization for LLM Compression and Acceleration, 2023.
- Frantar et al., GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers, 2022.
- Hinton et al., Distilling the Knowledge in a Neural Network, 2015.
- Shoeybi et al., Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism, 2019.
- Narayanan et al., Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM, 2021.
- Kwon et al., Efficient Memory Management for Large Language Model Serving with PagedAttention, 2023.
- OWASP GenAI Security Project, OWASP Top 10 for LLM Applications 2025.
- NIST, AI Risk Management Framework.
- European Commission, Regulatory framework for AI (the AI Act, Regulation (EU) 2024/1689), including the application timeline. Official text: Regulation (EU) 2024/1689 on EUR-Lex; amending act: Regulation (EU) 2026/1744 (Digital Omnibus on AI).
- Open Source Initiative, The Open Source AI Definition 1.0.
- European Commission, Guidelines for providers of general-purpose AI models.
- NIST, Artificial Intelligence Risk Management Framework: Generative Artificial Intelligence Profile (NIST AI 600-1), 2024.
- European Data Protection Board, Guidelines 01/2025 on Pseudonymisation, version for public consultation, adopted on 16 January 2025.
- U.S. Copyright Office, Copyright and Artificial Intelligence.
- Regulation (EU) 2016/679 (General Data Protection Regulation), Recital 26.
Further reading: official pages for names mentioned
These links point to each owner's own pages so readers can check current details there, including licenses and terms. They are listed for identification only, imply no endorsement or affiliation, and grant no rights in the linked material. Names without a link here can be found through their owners' official websites.
- Model families (publishers' official Hugging Face accounts; each model has its own card and license): Baichuan, DeepSeek, Falcon, Gemma, GLM, InternLM and Intern-S, Kimi, Llama, MiniMax, Mistral, OLMo, Phi, Qwen.
- Accelerators (vendor pages): NVIDIA H100, NVIDIA H200, NVIDIA DGX B200, NVIDIA GB200 NVL72, NVIDIA GB300 NVL72, AMD Instinct MI300X, AMD Instinct MI325X, AMD Instinct MI355X.
- Training libraries: TRL, PEFT, DeepSpeed, Megatron-LM, Axolotl, LLaMA-Factory, Unsloth, torchtune.
- Serving software: vLLM, SGLang, NVIDIA Triton Inference Server, NVIDIA NIM, TensorRT-LLM, llama.cpp, Ollama, Text Generation Inference.
- Providers (official documentation or product pages): Amazon Web Services, CoreWeave, Fireworks AI, Google Cloud, Hugging Face, Lambda, Microsoft Azure, Modal, Oracle Cloud, Replicate, RunPod, Together AI, Vast.ai.
Planning to fine-tune or deploy open-weight models?
If you are working through model adaptation, GPU sizing, serving architecture or AI governance, I am glad to compare notes on the trade-offs or talk through a production-readiness review.