MODULE 3.2

🧬 Custom and Proprietary Models

When it makes sense to have your own model—and when it's just expensive vanity. The customization ladder, open models, LoRA, continued pretraining, distillation, proprietary data as an advantage, and the real cost of maintaining a model that's live in production.

7
Topics
~60
Minutes
Advanced
Level
Strategy
Type
0%
0 of 0 topics read · Section 1 of 7

Detailed content

1

🪜 The customization ladder

“Having your own model” has become a boardroom phrase. In practice, there are six levels of customization, and each level up costs more money, people, and maintenance. The rule that protects your budget is simple: move up one level only when the previous one has demonstrably failed to solve the problem — and “demonstrably” means an evaluation with numbers, not an impression from a meeting.

The levels: prompt engineering (instructions and examples in the request); RAG (retrieve your own documents and add them to the context); parameter-efficient fine-tuning such as LoRA (training a small part of the model with your examples); continued pretraining (keep training the base model on a large corpus from your domain); distillation (teach a small model to imitate a large one) and, at the top, training from scratch.

What it is

The customization ladder orders the ways to adapt AI to your business from the cheapest and most reversible (prompt) to the most expensive and permanent (a model from scratch). Each rung solves a different kind of problem: prompts and RAG change what the model knows right away; fine-tuning changes how it behaves; pretraining and training from scratch change what it is.

1 · Prompthours · reversible 2 · RAGdays · documents 3 · LoRAweeks · examples 4 · Pretrainingongoing · corpus 5 · Distillationlarge → small 6 · From scratchmonths · cluster ↗ cost, data, people, and maintenance start at the bottom · move up only with evidence
How to read: from left to right, each rung requires more investment and is harder to undo. The dashed line has no numeric scale—it shows the direction. Most business use cases stop at rungs 1 to 3; rungs 4 to 6 pay off only with high volume, a very specific domain, or sovereignty requirements.
SymptomRung that usually solves it
Responds in the wrong format or ignores rulesPrompt with examples; then LoRA
Doesn't know the company's policies, products, and pricesRAG (knowledge changes; training gets outdated)
Inconsistent tone, style, or classification at high volumeLoRA with curated examples
Domain vocabulary that the model doesn't even tokenize wellContinuous pretraining
A large model works, but the cost and latency don't add upDistillation to a smaller model

Why learn

The question "do we need our own model?" comes up in every planning process. With the ladder, you replace an opinion-based answer with a diagnosis: which symptom, which rung, and which test proves the rung below isn't enough. This helps avoid six-month projects that good RAG could solve in two weeks.

Key concepts

Step
customization level
Knowledge × behavior
RAG × fine-tuning
Reversibility
how much it costs to undo
Proof of need
evaluation before moving up
2

🔓 Open models as a starting point

Almost nobody trains a language model from scratch. The realistic path to a model of "your own" is to start with a model with open weights (open weights: you download the file with the parameters and run it wherever you want) and adapt it. Model families such as Llama (Meta), Qwen (Alibaba), Mistral, Gemma (Google), and DeepSeek publish models in various sizes on Hugging Face, and new versions come out frequently—always check the official page before choosing.

Pay attention to the difference between open weights e open source in the strict sense. Many models release their weights, but not their training data or full code, and come with their own licenses that may limit commercial use above a certain scale, require attribution, or prohibit specific uses. Others are released under permissive licenses such as Apache 2.0 or MIT. The license is part of the architecture: anyone who doesn't read it inherits a legal risk.

What it is

An open model is one whose weights you can download, run on your infrastructure, and adjust. It is the foundation of nearly every proprietary business model: you inherit general capabilities and add what is specific to your business.

CriterionQuestion to askWhere to check
LicenseCan I use it commercially, at my scale, for this use?LICENSE file and model card
SizeWill it fit on the GPU I have, with the latency I need?Local test with quantization
LanguageDoes it perform well in Brazilian Portuguese in my domain?Your evaluation set, not the leaderboard
ContextCan the context window fit my typical documents?Model card + real-world test
EcosystemIs it supported in vLLM, Ollama, PEFT, Unsloth?Tool documentation
ProvenanceWho published it? Is the file official? Is there a hash?Verified organization on Hugging Face

📌 New term

Quantization means storing the weights with fewer bits (for example, 4 bits instead of 16) so the model fits in less memory, with some loss of quality that you need to measure. Model card (model card) is the page that describes training, limitations, license, and intended use.

💡 Tip

Choose two or three candidates from different model families and run the same set of 50 to 200 questions from your business through all of them before adjusting anything. Public leaderboards measure general tasks; your use case is what decides.

Why learn

Choosing the base model sets the ceiling for your customized model, the hardware you’ll need, and the legal risk. Switching bases later means redoing fine-tuning, evaluation, and integration. Making the decision with written criteria saves months.

Key concepts

Open weights
download it and run it wherever you want
License
what you're allowed to do
Quantization
fewer bits, less memory
Base model
the ceiling of what you can adjust
3

🎛️ Efficient fine-tuning: LoRA and QLoRA

LoRA (Low-Rank Adaptation) freezes the original model and trains only small matrices attached to some layers. The result is an adapter: a small file that is added to the base model. QLoRA does the same with the base model quantized to 4 bits, which makes it possible to fine-tune medium-sized models on a single GPU. Common tools: Hugging Face PEFT and TRL, Unsloth, and Axolotl.

What determines the result isn't the hyperparameter—it's the dataset. A few hundred to a few thousand clean, consistent, representative examples are usually worth more than tens of thousands of noisy examples. Duplicate examples teach the model to memorize; examples with personal data create an LGPD problem inside the weights, where it's very difficult to remove later.

What it is

Parameter-efficient fine-tuning (PEFT) means training a tiny fraction of the parameters to change the model's behavior—format, tone, classification, tool use—without the cost of training everything. Multiple adapters can share the same base model in production.

✓ LoRA works well

  • ✓High-volume, rigid output formats (JSON, reports, forms).
  • ✓Consistent brand voice and style.
  • ✓Classification and extraction using company categories.
  • ✓Shorten long prompts that are repeated in every call.

✗ LoRA handles this poorly

  • ✗Teach facts that change every week (prices, inventory).
  • ✗Give the model reasoning abilities it doesn’t have in its base version.
  • ✗Fix bad data with more training epochs.
  • ✗Guarantee source citations (that’s what RAG is for).

Goal: clean and split a JSONL dataset before any fine-tuning (Python 3 only, no libraries).

# prepare_dataset.py — usage: python3 prepare_dataset.py <input.jsonl>
# Each line: {"question": "...", "answer": "..."}
import hashlib, json, random, re, sys

MIN_CHARS, MAX_CHARS, FRACAO_AVAL = 20, 8000, 0.1
PII = {
    "cpf": re.compile(r"\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b"),
    "email": re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.-]+\b"),
    "telefone": re.compile(r"(?:\(?\d{2}\)?\s?)?9?\d{4}-?\d{4}\b"),
}

def mascara(texto, contagem):
    for nome, rx in PII.items():
        texto, n = rx.subn(f"[{nome.upper()}]", texto)
        contagem[nome] += n
    return texto

entrada = sys.argv[1]
vistos, limpos = set(), []
stats = {"lidas": 0, "invalidas": 0, "curtas_longas": 0, "duplicadas": 0}
pii = {k: 0 for k in PII}
with open(entrada, encoding="utf-8") as f:
    for linha in f:
        if not linha.strip():
            continue
        stats["lidas"] += 1
        try:
            reg = json.loads(linha)
            p, r = reg["pergunta"].strip(), reg["resposta"].strip()
        except (json.JSONDecodeError, KeyError, AttributeError):
            stats["invalidas"] += 1
            continue
        if not (MIN_CHARS <= len(p) + len(r) <= MAX_CHARS):
            stats["curtas_longas"] += 1
            continue
        p, r = mascara(p, pii), mascara(r, pii)
        chave = hashlib.sha256(" ".join(p.lower().split()).encode()).hexdigest()
        if chave in vistos:
            stats["duplicadas"] += 1
            continue
        vistos.add(chave)
        limpos.append({"pergunta": p, "resposta": r})

random.Random(42).shuffle(limpos)
n_aval = max(1, int(len(limpos) * FRACAO_AVAL))
for nome, parte in (("avaliacao.jsonl", limpos[:n_aval]), ("treino.jsonl", limpos[n_aval:])):
    with open(nome, "w", encoding="utf-8") as f:
        for reg in parte:
            f.write(json.dumps(reg, ensure_ascii=False) + "\n")

print(json.dumps({**stats, "pii_mascarada": pii,
                  "treino": len(limpos) - n_aval, "avaliacao": n_aval}, indent=2))

How to check: create a test file with 5 lines, two of them identical and one containing a fictional email and CPF. Run the script: the summary should show "duplicated": 1, a PII count greater than zero, and the files train.jsonl e evaluation.jsonl with no visible email (grep -c @ train.jsonl should return 0). Regex catches the obvious, not everything: proper names and addresses require human review or a dedicated PII detection tool.

Why learn

LoRA is the most cost-effective customization step when the problem is behavior. Knowing that it depends almost entirely on data quality and cleanliness changes where the technical lead assigns the team: to curation, not the search for the perfect hyperparameter.

Key concepts

Adapter
small file added to the base
QLoRA
LoRA on a 4-bit base model
Curation
a few good examples
Evaluation split
data the model doesn't see during training
4

📚 Continued pretraining

O continued pretraining (continued pretraining) takes an already-trained base model and continues training it on the same next-token prediction task, but now on a large corpus from your domain: case law, technical standards, engineering manuals, anonymized medical records. Unlike LoRA, which teaches behavior using question-answer pairs, here the model absorbs the domain’s vocabulary, style, and relationships from raw text.

The main risk has a name: catastrophic forgetting — as it learns the domain, the model loses general capabilities, such as following instructions or writing well in Portuguese. The classic defense is a data mixture: a portion of high-quality general text is added alongside the domain corpus, and after pretraining, instruction tuning helps restore assistant behavior. You find the right proportion by measuring, not by copying a recipe.

What it is

It means continuing the pretraining of an open model on a large corpus from a specific domain, followed by instruction tuning and dual evaluation: gains in the domain and preservation of general capabilities.

Domain corpus clean, with no PII General text prevents forgetting mixture Pretraining on the base model Instruction tuning Domain eval improved? General eval how much did it drop? if general performance drops too much, adjust the mixture and repeat
How to read: follow from left to right. The mixture circle is the most important decision in the pipeline: domain corpus alone leads to forgetting; too much general text dilutes the gains. Read the two evaluations at the end together—improving in the domain while plummeting in general performance makes the model worse for the user.

💡 Tip

Before approving ongoing pretraining, ask the team to answer three questions: how many tokens of clean, proprietary corpus do you have today, which eval proves that RAG + LoRA aren’t enough, and who will maintain the model when a better new base model comes out. If any question goes unanswered, the project isn’t ready yet.

Why learn

It’s the step that separates adaptation from true specialization. For domains with highly specialized language, it may be the only path to high quality—but it requires a volume of data, GPU resources, and evaluation discipline that few companies have. Knowing this helps you say yes to the right cases and no to the rest.

Key concepts

Corpus
raw domain text
Catastrophic forgetting
loses what it knew
Data mixing
domain + general
Dual evaluation
improvement and retention
5

🧪 Distillation: teacher and student

Distillation means training a small model (the student) to imitate a large model (the teacher) on a specific task. In the most common approach today, the teacher generates high-quality answers for thousands of real inputs, those answers are filtered, and the student is fine-tuned on them. The student doesn’t become the teacher—it gets good at that narrow range of tasks while running more cheaply and quickly.

One legal issue can sink projects: the terms of use for many commercial providers restrict using their model’s outputs to train a competing model. Before distilling from a paid API, review the provider’s current terms with your legal team. Using an open model whose license allows this as the teacher removes the uncertainty.

What it is

Distillation transfers a large model’s ability on a defined task to a smaller model that costs less per call and responds faster—trading generality for efficiency.

Real inputs anonymized Teacher large model license allows it? Filter quality Student small model production cheaper answers rejected by the filter aren’t included in training
How to read: The larger box is the teacher and the smaller one is the student—the visual size indicates the model’s scale. The funnel in the middle is where quality is decided: the student also learns the teacher’s mistakes if nothing is filtered out. The licensing question appears inside the teacher because that’s where the legal risk comes from.

Step 1. Define a narrow task and measure the teacher on it using your evaluation set.

Step 2. Generate teacher answers for real, anonymized inputs that are separate from the evaluation inputs.

Step 3. Filter using rules (valid format, no inappropriate refusals) and sample-based human review.

Step 4. Fine-tune the student with LoRA and compare the student × teacher on the same eval, including cost and latency.

Step 5. In production, send cases where the student has low confidence to the teacher.

Why learn

Distillation is the most direct way to reduce the unit cost of AI at high volumes without losing much quality on the task that matters. It’s also a common legal trap. A leader who knows both sides can approve the right project with the right teacher model.

Key concepts

Teacher
large reference model
Student
trained small model
Synthetic data
generated by a model
Terms of use
may prohibit distillation
6

🏰 Proprietary data as a moat

A moat (moat) is an advantage that’s hard to copy. Your model’s weights are rarely that moat: a better open base model can come out in a few months, and a competitor can repeat the fine-tuning. What’s hard to copy are three things— data only you generate, an evaluation set that captures what “good” means in your business, and the cycle that turns usage into continuous improvement.

That cycle is the data flywheel: people use the product, their corrections and evaluations are recorded, they become curated examples, and they improve the model, which improves the product and attracts more use. It only turns within the bounds of the LGPD (Brazil’s data protection law): a legal basis for using the data, the purpose disclosed to the data subject, anonymization before training, and the ability to honor deletion requests—which is much easier with RAG than with weights that have already been trained.

What it is

A data moat is a competitive advantage built on exclusive data that can legally be used and is continually renewed through product use, combined with an in-house evaluation set that shows whether each model version is actually better.

✓ Real moat

  • ✓Expert corrections to model outputs, recorded in the workflow.
  • ✓Business outcomes tied to each answer (the customer came back, the report was accepted).
  • ✓An in-house, versioned eval with difficult cases from your domain.
  • ✓Documented consent and legal basis for use in training.

✗ Fake moat

  • ✗“Our fine-tuned model” based on public data anyone can download.
  • ✗A mountain of logs with no labels, no quality, and no legal basis.
  • ✗A long prompt treated as a trade secret.
  • ✗A lead on a public leaderboard that the next base model surpasses.

Try this: Compare the base model with your fine-tuned model on your own eval, locally with Ollama.

# compara_modelos.py — usage:
#   python3 compara_modelos.py avaliacao.jsonl <modelo_base> <modelo_ajustado>
# Ex.: python3 compara_modelos.py avaliacao.jsonl qwen2.5 qwen2.5-empresa
# Each JSONL line: {"pergunta": "...", "esperado": ["termo1", "termo2"]}
# Requires Ollama to be running (ollama serve). A paid API works the same way if you swap the URL and key.
import json, sys, time, urllib.request

URL = "http://localhost:11434/api/generate"

def gerar(modelo, prompt):
    corpo = json.dumps({"model": modelo, "prompt": prompt, "stream": False,
                        "options": {"temperature": 0}}).encode()
    req = urllib.request.Request(URL, data=corpo, headers={"Content-Type": "application/json"})
    t0 = time.time()
    with urllib.request.urlopen(req, timeout=300) as r:
        resp = json.loads(r.read())["response"]
    return resp, time.time() - t0

def acerto(resposta, esperado):
    texto = resposta.lower()
    return all(termo.lower() in texto for termo in esperado)

arquivo, modelos = sys.argv[1], sys.argv[2:4]
casos = [json.loads(l) for l in open(arquivo, encoding="utf-8") if l.strip()]
placar = {m: {"acertos": 0, "segundos": 0.0} for m in modelos}
for i, caso in enumerate(casos, 1):
    linha = [f"#{i:03d}"]
    for m in modelos:
        resp, seg = gerar(m, caso["pergunta"])
        ok = acerto(resp, caso["esperado"])
        placar[m]["acertos"] += ok
        placar[m]["segundos"] += seg
        linha.append(f"{m}={'OK' if ok else 'erro'}")
    print("  ".join(linha))

print("\nResumo")
for m, p in placar.items():
    print(f"{m:30s} acertos {p['acertos']}/{len(casos)}  "
          f"tempo médio {p['segundos'] / len(casos):.1f}s")

How to check: run it first with the same model in both positions (qwen2.5 qwen2.5): the number of correct answers should match, which shows that the script and zero temperature are stable. Then run base × fine-tuned on the evaluation.jsonl generated in Topic 3, which the training process did not see. The expected-term criterion is deliberately simple; for open-ended responses, replace acerto() with human review or an evaluator model using a rubric.

Why learn

Investing in your own model without a data moat is like buying an asset that depreciates with every release. Investing in the data cycle and your own eval creates an asset that appreciates and works with any future base model—including switching providers without losing quality.

Key concepts

Moat
hard-to-copy advantage
Flywheel
usage that drives improvement
Your own eval
what “good” means for your business
Legal basis
LGPD before training
7

💰 The real cost of maintaining a model

The figure in the proposal is usually the training cost. The bill that comes later is the total cost of ownership (TCO, total cost of ownership): serving the model 24/7, monitoring quality, retraining when the data changes, migrating to a new base model, responding to incidents, and keeping the people who know how to do all of this. Your own model is a living product, not a deliverable.

The most often overlooked cost is the opportunity: while the team maintains the fine-tuned model from the previous generation, general models on the market keep improving. Often, the next generation of a general model with a good prompt reaches the custom model’s performance. That’s why the plan needs to include, from the start, how to reassess the decision with each relevant new base model.

What it is

It’s the sum of everything your own model requires over its useful life—infrastructure, data, evaluation, retraining, security, compliance, and staff—compared with the cost of using and adapting a third-party model.

Cost itemThird-party API + RAGYour own fine-tuned model
InfrastructureVariable, based on usageReserved or rented GPU, idle outside peak hours
TeamApplication engineering+ ML, MLOps, and inference on-call
UpdatesThe provider improves the modelRetraining and reevaluation with each new base model
DataRAG indexing and governance+ ongoing curation of examples
ComplianceContract and DPA with the providerPersonal data in the weights, difficult to remove
ControlSubject to price and version changesIn total: frozen version, data kept in-house

Goal: decision checklist + analysis prompt to take the “build or buy” decision to the committee.

You are a skeptical AI architect who protects the company’s budget.
Use case: <3-line description>
Expected volume: <calls per day> · Required latency: <e.g., 2 s>
Available data: <type, amount, whether it contains personal data>
Current team: <who we have in ML, MLOps, data>
Current eval results: <prompt + RAG gets X of Y cases right; target is Z>

Answer the checklist, one line per item, with YES / NO / NOT SURE and the reason:
[ ] 1. Have prompt + RAG been evaluated with our own eval and fallen short of the target?
[ ] 2. Is the problem about behavior (format, tone, class) rather than knowledge?
[ ] 3. Do we have exclusive, clean data and a legal basis (LGPD (Brazil’s data protection law)) for training?
[ ] 4. Does the volume make the cost per API call significant in the budget?
[ ] 5. Is there a requirement for data sovereignty, offline operation, or data that cannot leave our systems?
[ ] 6. Do we have someone to maintain the model and retrain it with each new dataset?
[ ] 7. Does the base model’s license allow our commercial use?
[ ] 8. Do we know how to handle a request to delete data that has already been used for training?

Then:
- Recommend the step (prompt, RAG, LoRA, continued pretraining, distillation, from scratch).
- List the 3 biggest risks and a 2-week test that confirms or overturns your recommendation.
- Say what would change your mind. Don’t make up numbers; mark [ESTIMATE] where data is missing.

How to check: The answer must address all 8 items, one per line, and no figure may appear unless it is marked [ESTIMATE] or comes from the data you provided. If item 1 is NO or NOT SURE, the right recommendation is to stick with prompt or RAG and build the eval first — if the model recommends training anyway, be skeptical of the analysis.

💡 Tip

Include a “reassessment date” in the proposal: when a relevant new dataset becomes available, run our own eval on it with prompt + RAG before any retraining. If the general-purpose model performs just as well, retire the custom model without hesitation — your data and eval remain your moat.

Why learn

Decisions to build your own model are among the most expensive AI decisions to reverse. Leaders who bring the full TCO, a completed checklist, and a reassessment criterion to the committee approve fewer projects—and the ones they approve deliver returns.

Key concepts

TCO
lifetime cost
Opportunity cost
the market never stops
Build × buy
checklist-based decision
Reassessment
with each new dataset

✅ Module summary

✓
Climb the ladder only with evidence — prompt and RAG first, evaluated with numbers.
✓
An open model is the starting point — and the license is part of the architecture.
✓
LoRA changes behavior; pretraining changes the domain; distillation changes the cost — each solves a different problem.
✓
Your moat is data and eval, not weights — under the LGPD.
✓
Count the full TCO — and set a reassessment date.

Next module:

3.3 — Advanced Multimodal AI 🎞️