Dev.to AI 🤖 Ai 👁 0 📖 7 min read

How can a model actually learn?

Part 2: test scenarios and training pairs Welcome to the second part! In case you missed the first one, here is the link, where we got our data and kept only the useful parts. Now we have to make our model "learn". Th

Part 2: test scenarios and training pairs

Welcome to the second part! In case you missed the first one, here is the link, where we got our data and kept only the useful parts.

Now we have to make our model "learn". The idea is simple and follows the rule "practice makes perfect": we show the model what a correct answer looks like and repeat it hundreds of times across many different scenarios. This part is very important, because we want our model to be smart enough to handle scenarios it has never seen before.

But before we teach anything, we need a way to know if it actually learned. That's why we start with the exam.

3 Test scenarios

Here we get hands on. We have to write test scenarios for every topic our AWS solutions architect will cover: serverless APIs, highly available databases, global content delivery, messaging, streaming, data lakes, hybrid networking, disaster recovery, cost optimization and security. I went with 5 per topic, so 50 in total. I wrote some of them myself, used an AI to draft the rest following mine as a reference, and then reviewed every single one.

Think of these as the final exam. The model never sees them during training. If it did, it would just memorize the answers and we wouldn't know if it really learned anything.

Every scenario follows the same format. This is how one of my serverless ones looks:

{
  "scenario": "we are a energy company that needs notifications about the weather since we rely on eco alternatives, we need them in real time but our budget is not too big, so we would like to get notifications about the weather on a daily basic and trigger alarm in case there is a huge drastic change in the weather",
  "answer": {
    "category": "serverless-api",
    "services": [
      {"name": "Amazon EventBridge Scheduler", "role": "Invoke the weather-check function daily to fetch forecasts and send the regular weather summary."},
      {"name": "Amazon API Gateway", "role": "Receive authenticated weather-provider webhooks and invoke the alert function when live updates arrive."},
      {"name": "AWS Lambda", "role": "Validate weather updates, compare readings against agreed drastic-change thresholds and publish daily summaries or urgent alerts."},
      {"name": "Amazon DynamoDB", "role": "Store the latest readings and processed event identifiers using on-demand capacity to support comparisons and suppress duplicate alerts."},
      {"name": "Amazon SNS", "role": "Deliver daily weather summaries and urgent weather-change notifications to subscribed operators."}
    ],
    "why": "Scheduled daily summaries and provider-triggered alerts cover routine weather updates and sudden changes that affect renewable energy operations. Request-driven functions and on-demand storage avoid idle server costs for the limited budget.",
    "tradeoffs": [
      "Real-time alerts depend on the weather provider offering timely push updates; daily polling alone cannot detect changes as they happen.",
      "Weather-data subscriptions and notification delivery add costs; define alert thresholds to avoid noisy, repeated notifications.",
      "Webhook retries require duplicate handling, and provider outages or failed deliveries need monitoring."
    ],
    "rejected": [
      {"name": "Amazon EC2", "reason": "An always-running weather polling server adds idle compute costs and maintenance for a budget-constrained notification workload."}
    ],
    "pillars": ["cost-optimization", "operational-excellence", "reliability"]
  }
}

Look at how the answer is built:

  • scenario: the business problem, written like a real customer would say it (typos included 😅). No hints about which technology to use.
  • category: what kind of problem this is. It's the first decision a solutions architect makes, and if the model gets it wrong, the rest of the answer usually goes wrong too.
  • services: what to use, and the role each one plays.
  • why: the reason, tied to the constraints in the scenario (here: tight budget, daily summaries plus sudden alerts).
  • tradeoffs: what we give up with this design.
  • rejected: what we should NOT use and why.

Together this covers everything the model needs to understand the reasoning of a solutions architect: not only which services, but why these exact ones.

Why the category matters so much. Language models work with probabilities: they write the answer one word at a time, and each word depends on everything written before it. Since category is the first field in the answer, the model classifies the problem before anything else. Once it has written "serverless-api", services like Lambda and API Gateway become much more likely, and something like Direct Connect becomes very unlikely. So a good classification narrows the search, and the rest of the answer gets easier to get right. It's the same thing a human architect does: first figure out what kind of problem it is, then pick the tools.

4 Generate the training pairs

Now the training pairs, or as I like to call them, the flashcards. 50 scenarios is enough for an exam, but nowhere near enough to teach a model. The whole point here is to use a smarter model to generate tons of flashcards so our small model has enough to practice with. In my case that's one flashcard for each of the 774 useful sections we got in the previous article.

Here you can use any smarter model you have available: Gemini, Claude, OpenAI... or if you don't want to spend any tokens or you want to keep everything offline, you can do it like me and use Qwen2.5 7B running locally. For that you need Ollama:

ollama serve
ollama pull qwen2.5:7b

Make sure you have enough disk space, the model takes about 5GB.

The recipe for each flashcard is simple: we give the big model one section of the AWS docs plus one worked example, and we ask it to write a customer scenario that section would solve, and then answer it. This is my prompt:

You are an AWS solutions architect writing practice cases for junior architects.

Read the documentation section below. Write one realistic customer scenario
that this section would help solve, then answer it.

Scenario rules:
- Always write from the business problem perspective
- Do not give hints about what technology to use
- Explain clearly what the problem is. Include 2-4 concrete constraints with numbers that match the documentation section
- The scenario must not mention the solution, like "we need a shared VPC"

Answer rules:
- Follow the JSON schema. category must be {category}
- "why" must reference the scenario constraints

Example:
{example}

Documentation section:
{section}

Return JSON only, with two keys: "scenario" and "answer".

And this is how my script looks (trimmed to the important parts):

import json
import ollama

# constrained decoding: the model can only pick service names from our list,
# so it can't invent things like "AWS Super Database"
for field in ("services", "rejected"):
    schema["properties"][field]["items"]["properties"]["name"] = {"enum": sorted(CANON)}
fmt = {"type": "object", "required": ["scenario", "answer"],
       "properties": {"scenario": {"type": "string"}, "answer": schema}}

for n, d in enumerate(docs, 1):
    prompt = (template.replace("{category}", d["category"])
              .replace("{example}", json.dumps(golds[n % len(golds)], indent=2))
              .replace("{section}", d["text"][:6000]))
    r = ollama.chat(model="qwen2.5:7b", messages=[{"role": "user", "content": prompt}],
                    format=fmt, options={"temperature": 0.7, "seed": 42, "num_ctx": 8192})
    f.write(json.dumps({"id": d["id"], "category": d["category"], "raw": r.message.content}) + "\n")
    f.flush()  # save every flashcard right away, so we can resume if it crashes
    print(f"  {n}/{len(docs)} {d['category']}")

Two tricks here that saved me a lot of pain:

  • format=fmt forces the model to answer with valid JSON following our schema, and the service names can only come from our list. A 7B model loves to invent AWS services otherwise.
  • The cache. Every flashcard is written to disk right away, so if your laptop goes to sleep at 3am you just run it again and it continues where it stopped.

After generating, the script also cleans up: it trims answers that are too long, drops near duplicates, throws away any flashcard that looks too similar to one of our 50 test scenarios (remember, no cheating on the exam), and finally splits them 90/10 into training and validation.

Now be ready: depending on your computer, this can take a while. I recommend running it overnight with only one terminal open and no other apps. For me it took about 9 hours to generate all of them. So let's do it:

python scripts/pairs.py

As long as you saved it under the scripts directory, it should do the work for you. You should see something like this:

0 cached, generating 774
  1/774 hybrid-connectivity
  2/774 security-compliance
  3/774 hybrid-connectivity
  ...

That means it's working! 🚀🙌🏻

Once it's done, it prints a summary:

generated:   774
duplicates:    1
kept:        773
train:       694
valid:        79

And you can double check with:

wc -l data/pairs/train.jsonl data/pairs/valid.jsonl

Before moving on, open a few of them and read them. If the flashcards are bad, the model will learn bad answers, no matter how good the training is.

That's it for today. Stay tuned, because in the next article we'll cover the fun part: training!

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.