Module 5 · Evaluation & deployment

Model merging and quantization (GGUF, AWQ, GPTQ)

6 min read

Between the end of training and production, two operations transform the model: merging (folding the adapter into the weights, or combining several fine-tunings) and quantization (reducing weight precision to save memory and speed). Each can change the model's answers. This lesson applies them to Forge's triage model and measures what they cost in quality.

Merging a LoRA adapter

A LoRA adapter adds (α/r)·B·A to each targeted layer. Merging computes W' = W + (α/r)·B·A once and for all: the adapter disappears, the model becomes a standard model again, with no inference overhead.

def merge_lora(model_name: str, adapter_dir: str, output_dir: str, dtype=torch.float32):
    """W = W_base + (α/r)·B·A : l'adaptateur disparaît, l'inférence ne coûte plus rien de plus."""
    from peft import PeftModel
    from transformers import AutoModelForCausalLM, AutoTokenizer

    model = AutoModelForCausalLM.from_pretrained(model_name, dtype=dtype)
    merged = PeftModel.from_pretrained(model, adapter_dir).merge_and_unload()
    merged.save_pretrained(output_dir)
    AutoTokenizer.from_pretrained(adapter_dir).save_pretrained(output_dir)
    return merged

Two precautions: merge into the base model in full precision (never into a quantized version, even if the adapter was trained with QLoRA), and check that the merged model answers like the model with the adapter.

Combining several fine-tunings

A fine-tuning defines a task vector: the difference between the fine-tuned weights and the base weights. These vectors can be combined:

  • Linear: W = W_base + Σ λᵢ·Δᵢ, a weighted average.
  • TIES (Yadav et al., 2023): to reduce interference between tasks, small modifications are pruned, the majority sign is elected for each parameter, then only the modifications with that sign are averaged.
def merge_ties(base: dict[str, torch.Tensor], vectors: list[dict[str, torch.Tensor]],
               density: float = 0.2, scale: float = 1.0) -> dict[str, torch.Tensor]:
    """TIES-merging (Yadav et al., 2023) : Trim, Elect sign, disjoint merge."""
    out = {}
    for k in base:
        stacked = torch.stack([v[k] for v in vectors])                       # [tâches, ...]
        flat = stacked.reshape(len(vectors), -1)
        keep = max(1, int(density * flat.shape[1]))
        threshold = flat.abs().kthvalue(flat.shape[1] - keep + 1, dim=1, keepdim=True).values
        trimmed = torch.where(flat.abs() >= threshold, flat, torch.zeros_like(flat))  # 1. élagage
        sign = torch.sign(trimmed.sum(dim=0))                                         # 2. signe élu
        agree = (torch.sign(trimmed) == sign) & (trimmed != 0)
        merged = (trimmed * agree).sum(0) / agree.sum(0).clamp(min=1)          # 3. moyenne disjointe
        out[k] = base[k].float() + scale * merged.reshape(base[k].shape)
    return out

(The three numbered comments: pruning, sign election, disjoint average.) Model merging makes it possible to bring together skills trained separately (Forge's triage and replies, for example) without retraining. The reference tool is mergekit, which implements these methods and others (SLERP, DARE) on full models. The result of a merge is never guaranteed: it is evaluated like a new model, on every task concerned.

Quantizing for inference

Quantization stores weights on fewer bits. For inference, several families coexist:

FormatPrincipleTool / engineCalibration
bitsandbytes 8-bit (LLM.int8)Int8 with separate handling of outlier valuesTransformersNo
bitsandbytes 4-bit (NF4)QLoRA's formatTransformersNo
GPTQLayer-by-layer quantization that minimizes output errorvLLM, TransformersYes (a few hundred examples)
AWQProtects the most important weights based on activationsvLLM, TransformersYes
GGUF (2 to 8 bits)llama.cpp's format, many levels (Q4_K_M, Q8_0…)llama.cpp, OllamaOptional
FP88-bit floats, recent hardwarevLLM, recent GPUsLight

Formats with calibration (GPTQ, AWQ) use representative examples to decide how to round: use examples from your task, not generic text. GGUF is produced with llama.cpp's conversion and quantization scripts; GPTQ and AWQ with dedicated libraries (for example llm-compressor, from the vLLM ecosystem).

Measurements on Forge

examples/08_merge_quantize.py merges the triage LoRA adapter, then evaluates the merged model in full precision, 8 bits and 4 bits, on the 300 test messages:

VersionWeights in memoryExact matchValid JSONLatency (GTX 1060)
Base + adapter—0.651.00258 ms/message
Merged, fp321,885 MB0.651.00284 to 301 ms/message
Merged, 8-bit (LLM.int8)861 MB0.661.00948 ms/message
Merged, 4-bit (NF4)690 MB0.541.00396 ms/message

The merge is exact: 300 identical outputs out of 300 before and after. On a model this small, it brings no measurable latency gain — the gaps between the first two rows are measurement noise; the gain appears with expensive adapters (DoRA, lesson 3.2) or at scale.

Quantization reads along two axes. 8-bit divides memory by 2.2 with no loss of quality — but triples latency on this GPU: LLM.int8 converts activations to fp16, which Pascal cards compute very slowly. 4-bit divides memory by 2.7 (not by 8: embeddings and normalizations stay in full precision), but exact match drops by 11 points, well beyond measurement noise. A small model has little redundancy: each lost bit costs it more than it would a 70 B model, which generally tolerates 4 bits very well.

The practical lesson: a memory gain implies neither a speed gain nor the absence of loss. Each format is measured on the production hardware, on the task's test set.

The order of operations

  1. Train (LoRA or QLoRA).
  2. Merge into the base model in full precision.
  3. Evaluate the merged model: it is the new reference.
  4. Quantize the merged model, with calibration data from the task if the format requires it.
  5. Re-evaluate the quantized model on the test set and the safeguards (lessons 5.1 and 5.2): quantization can degrade rare cases more than the average.

Key takeaways

  • Merging an adapter = W + (α/r)·B·A: same behavior, no inference overhead; merge in full precision.
  • Task vectors can be combined (linear, TIES); mergekit does it on full models; every merge is re-evaluated.
  • GPTQ and AWQ calibrate on examples: use those of your task; GGUF serves llama.cpp and Ollama.
  • Measure memory, speed and quality of each format: a memory gain does not imply a speed gain.
  • Order: train, merge, evaluate, quantize, re-evaluate.

Practice

  1. Run examples/08_merge_quantize.py and compare the outputs before and after merging.
  2. Merge with TIES the triage adapter and the DPO replies adapter, then evaluate the resulting model on both tasks.
  3. With llama.cpp, convert the merged model to GGUF Q4_K_M and compare its size and answers with bitsandbytes 4-bit.

Resources