How to train and create your own model for your custom purpose
Have you ever wondered if you can train your own model? If so, you don't need your own datacenter or to spend thousands of dollars on GPUs. I did it with a MacBook with 24GB of RAM. It's possible (slow, but possible). S
Have you ever wondered if you can train your own model? If so, you don't need your own datacenter or to spend thousands of dollars on GPUs. I did it with a MacBook with 24GB of RAM. It's possible (slow, but possible).
So in this case we're gonna fine-tune our own model to be our personal AWS solutions architect. Why? Well, why not. We get unlimited tokens, and we can use the same methodology for different use cases like triaging support tickets, answering questions about your internal docs, or turning plain English into SQL for your own database.
There are a lot of real world scenarios where you don't need big and complex models like Opus 5.5 to answer some questions. The main problem here is we have to remove unnecessary data, or let's say it this way: train our model to answer the way we want. Additionally, if your data doesn't vary that much, this fits perfectly for you. It also brings security in case you don't want to expose your private docs to the web, send that information to a third party, or end up feeding other models with your private data.
Another perk of smaller models is that they can be very fast, which reduces the latency of your app and improves your UX. And again, you have unlimited tokens here, so no need to worry about API usage π
This is how I did it and what we're gonna do:
- Get data In this case we're gonna scrape around 1.5k sections from the AWS docs. 1.5k isn't a magic number: it's simply what 61 hand-picked AWS guides gave us after dropping the short sections. For a narrow task like ours that's enough, because we only need a few hundred good examples.
- Keep the useful ones We create another script to filter the useful ones for us. In this case we kept 774.
- Test scenarios Now we have to write test scenarios for our AWS solutions architect. I started with 10 but ended up with 50, 5 per topic: serverless, relational databases, streaming ingest, security... Make sure to cover each of the scenarios your model will need.
- Generate the training pairs For this step, think of flashcards. We're gonna use a bigger, smarter model to create a ton of flashcards (773 in my case) so we can use them to train our small model.
- Training This is the fun part. Now we use the flashcards to make our smaller model try to answer, and if it gets it wrong we adjust the weights a little. We do that over all our flashcards until the answers are good enough.
- Evaluate Now it's time to test our AWS solutions architect. We send the same questions to our fine-tuned model and to the untrained one to see which one gets them right, so we can measure how much our model learned.
Setup
- We're gonna use the Qwen3 model, which is under an open-source license (Apache 2.0)
- A computer (in my case an M3 MacBook Air with 24GB of RAM)
- Python
1 Get data
Alright, so let's start by writing a scraper script that takes the data from docs.aws.amazon.com (Well-Architected Framework, whitepapers and Prescriptive Guidance) and stores it locally. The AWS docs are licensed CC-BY-SA 4.0, so we're allowed to reuse them, but let's be nice and respect robots.txt
This is how my script looks (trimmed to the important parts):
import hashlib, json, re, time, urllib.robotparser
import requests
from bs4 import BeautifulSoup
BASE = "https://docs.aws.amazon.com"
UA = "archcoach-dataset-builder/0.1 (educational, non-commercial; respects robots.txt)"
DELAY = 5 # seconds between requests (the docs robots.txt asks for 5)
MIN_CHARS = 800 # sections shorter than this are too thin to learn from
session = requests.Session()
session.headers["User-Agent"] = UA
robots = urllib.robotparser.RobotFileParser(f"{BASE}/robots.txt")
robots.read()
_last = 0.0
def fetch(url):
"""GET with a disk cache and a rate limit."""
global _last
path = CACHE / (hashlib.sha1(url.encode()).hexdigest() + ".html")
if path.exists():
return path.read_text() or None
if not robots.can_fetch(UA, url):
return None
time.sleep(max(0, DELAY - (time.time() - _last)))
r = session.get(url, timeout=30)
_last = time.time()
r.raise_for_status()
path.write_text(r.text)
return r.text
def sections(html):
"""Split a docs page into (heading, text) chunks on h1/h2."""
main = BeautifulSoup(html, "html.parser").select_one("#main-col-body")
for h in main.find_all(["h1", "h2"]):
h.insert_before(f"\n\x00{h.get_text(' ', strip=True)}\x01\n")
h.decompose()
out = []
for chunk in main.get_text("").split("\x00"):
head, _, body = chunk.partition("\x01")
if len(body.strip()) >= MIN_CHARS:
out.append((head.strip(), body.strip()))
return out
# Each guide publishes a sitemap.xml, which gives us every page URL in it.
for slug in GUIDES:
sitemap = fetch(f"{BASE}/wellarchitected/latest/{slug}/sitemap.xml")
for url in re.findall(r"<loc>([^<]+)</loc>", sitemap):
for head, text in sections(fetch(url)):
out.write(json.dumps({"url": url, "section": head, "text": text,
"license": "CC-BY-SA-4.0"}) + "\n")
To run it I do:
python scripts/collect.py
It took about 2 hours (1,380 pages Γ 5 seconds), and this is what we got:
pages sections too short kept
well-architected 847 1,979 1,043 936
whitepapers 332 460 191 269
prescriptive-guidance 201 582 246 336
total 1,380 3,021 1,480 1,541
You can see now we have a lot of data, yay!! Each line in data/raw/docs.jsonl is one section of the AWS docs with its URL and license.
2 Filter
Now let's keep the useful ones. Since we're making an AWS solutions architect, a lot of the content might not be useful for us: API references, pricing tables, changelogs, "click here, then click there" console steps. We want sections that explain how to decide something.
The filter has two stages. First, some simple rules drop code, pricing and boilerplate. Then the smart part: for every topic I wrote 2 "good" example sentences (design advice) and 2 "bad" ones (same topic, but reference-doc style), and we measure whether each section looks more like the good ones or the bad ones:
score = similarity to the closest good example β similarity to the closest bad example
This is how my script looks (the scoring part):
from sentence_transformers import SentenceTransformer
THRESHOLD = 0.10 # keep sections that look clearly more "good" than "bad"
CAP = 120 # max sections per topic, so no topic dominates
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
enc = lambda xs: model.encode(xs, normalize_embeddings=True)
pos = enc([s for c in names for s in cats[c]["positive"]])
neg = enc([s for c in names for s in cats[c]["negative"]])
pos_cat = [c for c in names for _ in cats[c]["positive"]]
emb = enc([f'{d["title"]}. {d["section"]}. {d["text"]}' for d in docs])
# normalized vectors, so a dot product is the cosine similarity
pos_sim, neg_sim = emb @ pos.T, emb @ neg.T
scores = pos_sim.max(1) - neg_sim.max(1)
categories = [pos_cat[i] for i in pos_sim.argmax(1)] # free bonus: the topic
kept = [d for d, s in zip(docs, scores) if s > THRESHOLD]
And these are my example sentences for one topic:
serverless-api:
positive:
- "Put API Gateway in front of Lambda functions so the API scales to zero when idle and absorbs traffic spikes without capacity planning or servers to patch."
negative:
- "The CreateFunction action accepts the parameters FunctionName, Runtime, Role, Handler and MemorySize; MemorySize must be between 128 and 10240 MB."
This is how I run it:
python scripts/filter.py
in: 1,541
dropped by rules: 44 (code 9, pricing 4, boilerplate 27, console steps 4)
below threshold: 465
over the topic cap: 258
kept: 774
And you can see it kept 774 sections. Two things surprised me here:
- The rules barely did anything. The AWS docs are already clean prose, so the semantic score did almost all the work.
- The topics are uneven. Security and hybrid networking had 200+ good sections each, while messaging only had 29. The cap stops the big topics from taking over, but it can't create data for the small ones.
The most important part here is that the filter has to make sense for what we want. If it doesn't, our model will be trained with the wrong data.
Well, that's it for now. Stay tuned, because next we'll cover how to write the test scenarios.
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.