跳到正文
DEV Community· vianel·· 36 分鐘前AI 評分61

如何用 MLX 和 LoRA 微調 Qwen3,並評估離線 AWS 架構建議助手

Wax on, wax off, and repeat

AI 導讀

作者使用 MLX 和 LoRA 微調 Qwen3-1.7B 與 Qwen3-4B-4bit,並以 50 個未見測試情境評估 AWS 架構建議模型。微調後的 Qwen3-4B-4bit schema valid 為 80%、服務重疊分數為 0.31、虛構服務率為 3%;微調後的 Qwen3-1.7B 則分別為 64%、0.26 和 3%。

正文

Part 3: training and evaluating our model

As the title says, it's time to repeat, repeat and repeat. This is the last part of the series and the fun one: training. In the previous article we generated 773 flashcards, and now we're going to show them to our model one by one. Each time, we compare its answer with the flashcard, measure how wrong it was, and adjust the weights a little so next time it's a bit closer. We do that over all our flashcards, a few times over.

Once the training finishes, we give the model the exam: the 50 test scenarios from the previous article, which it has never seen. Then we compare it against the untrained model to see how much it actually learned. So let's dig in.

5 Training

For the training I'm using MLX, Apple's library for running and training models on Apple Silicon. Install it with:

pip install mlx-lm

One important thing: we are not retraining the whole model. That would need way more memory than my laptop has. Instead we use LoRA, which freezes the original model and trains a small add on on top of it. In my case that's only 2.5 million parameters out of 1.7 billion (0.145%). That's why this runs on a MacBook

This is my config:

model: Qwen/Qwen3-1.7B
train: true
data: data/pairs              # reads train.jsonl + valid.jsonl
adapter_path: out/adapters/1p7b
seed: 42

fine_tune_type: lora
num_layers: 8                 # LoRA only on the last 8 layers
lora_parameters:
  rank: 8                     # size of the small trainable matrices
  scale: 20.0
  dropout: 0.0

mask_prompt: true             # only learn from the answer, not from the question

batch_size: 4                 # 4 flashcards at a time
iters: 600                    # 694 flashcards / 4 = ~174 steps per round -> ~3.5 rounds
learning_rate: 1e-5           # how big each adjustment is

steps_per_report: 10
steps_per_eval: 50            # check the validation flashcards every 50 steps
val_batches: -1
save_every: 100               # save a checkpoint every 100 steps
max_seq_length: 2048

And to run it:

mlx_lm.lora -c configs/lora_1p7b.yaml

It took about 1 hour and 20 minutes. While it runs you'll see two numbers: the train loss and the val loss. Loss is basically "how wrong the model is", so lower is better. The train loss is measured on the flashcards it's studying, and the val loss on the 79 flashcards we kept aside, which it never studies. The val loss is the one that matters, because it tells you if the model is really learning or just memorizing.

iter   val loss
   1   3.232
  50   1.361
 100   1.276
 200   1.213
 300   1.186
 400   1.175
 500   1.164
 600   1.161

You can see it learns a lot in the first 50 steps and then the improvements get smaller and smaller. By the end it barely moves, which means it's done.

6 Evaluation

Now the exam. The script sends each of the 50 test scenarios to the model, reads the JSON it answers, and compares it with my answer. This is the important part (trimmed):

from mlx_lm import generate, load

model, tok = load("Qwen/Qwen3-1.7B", adapter_path="out/adapters/1p7b")
for t in tests:
    prompt = tok.apply_chat_template(build_messages(t["scenario"]), tokenize=False,
                                     add_generation_prompt=True, enable_thinking=False)
    out = generate(model, tok, prompt=prompt, max_tokens=512)
    score(parse(out), t["answer"])

For a fair fight, the untrained model gets one full example in the prompt so it knows the format we expect. The fine tuned one gets nothing, it has to know it already.

And this is what we measure:

  • Schema valid: the answer follows all our rules (a valid category, the right fields, no more than 2 sentences of "why", real service names).
  • Category: did it classify the problem right?
  • Service overlap: how many of the services it picked match mine (0 = none, 1 = exactly the same).
  • Made-up services: how many services it invented, like "AWS Super Database".

The results:

                   schema valid   category   service overlap   made-up services
untrained 1.7B          30%           6%           0.17               19%
fine-tuned 1.7B         64%          68%           0.26                3%

That's a big jump! Remember the weather scenario from the previous article? This is what the untrained model answered:

{"category": "serverless-notifications",
 "services": [{"name": "Amazon SNS"}, {"name": "Amazon CloudWatch Alarms"},
              {"name": "Amazon S3"}, {"name": "Amazon CloudFront"}], ...}

It invented a category that doesn't exist, added CloudFront (a CDN, for weather alerts?), and later in the answer it rejected "Amazon Lambda", which isn't even the right name. And the fine tuned one:

{"category": "cost-optimization",
 "services": [{"name": "Amazon SNS"}, {"name": "AWS Lambda"}, {"name": "Amazon S3"}], ...}

Not perfect (the expected answer says serverless-api), but cost is a reasonable read for a tight budget scenario, the services make sense, and the format is exactly what we asked for.

One honest note: the untrained model's category score is a bit unfair. My system prompt never lists the 10 categories, so it had to guess the names. Still, the fine tuned model learned them just from the flashcards.

Can we do better?

The results don't look bad, but not great either. So let's do it again with a bigger model: 4 billion parameters. But first, let's understand what a parameter is.

The parameters are the numbers inside the model, the weights we've been adjusting during training. Everything the model "knows" is stored in those numbers. Our first model has 1.7 billion of them, and the new one has 4 billion, which means more room to store patterns, so the model should be "smarter".

To make it fit on my laptop I used a 4bit version of the model (mlx-community/Qwen3-4B-4bit). That means each number is squeezed into half a byte instead of two bytes. It loses a little precision, but it uses way less memory. Same config, I only changed the model and the adapter path:

mlx_lm.lora -c configs/lora_4b.yaml

This one took about 2 hours and 50 minutes. And look at the val loss:

iter   val loss
   1   2.609
 100   1.178
 300   1.101
 500   1.085   <- the best one
 600   1.093   <- going up again

After step 500 the val loss starts going up. That's overfitting: the model stopped learning the general skill and started memorizing the training flashcards. That's why we save a checkpoint every 100 steps. I used the one from step 500 instead of the last one.

So, the final results:

                   schema valid   category   service overlap   made-up services
untrained 1.7B          30%           6%           0.17               19%
untrained 4B             0%           2%           0.24               26%
fine-tuned 1.7B         64%          68%           0.26                3%
fine-tuned 4B           80%          70%           0.31                3%

A few things I learned here:

  • Fine tuning made the biggest difference, not the size. The untrained 4B is worse than the fine tuned 1.7B in almost everything. Its 0% schema score is because it invented its own category names every single time.
  • The bigger model mostly got more reliable. Schema valid went from 64% to 80%, so fewer broken answers. But the quality of the advice only improved a little (0.26 to 0.31), and the category barely moved.
  • More parameters can't fix the data. The categories in my flashcards were assigned automatically by the filter in part 1, and some are probably wrong. A bigger model can't learn past wrong labels. If I want a smarter model, the next step is better data, not a bigger model.

And a nice surprise: the 4 bit 4B model is actually smaller and faster than the 1.7B one. It uses 2.7GB of memory vs 3.7GB and generates 31 tokens per second vs 23. Generating text is mostly limited by how fast the computer can read the weights from memory, and the 4bit weights are just fewer bytes. So the best model is also the cheapest one to run.

7 Using it offline

The whole point of this was to have my own personal offline assistant, so let's actually use it.

First, the good news: what we trained is just the adapter, a 14MB file. The base model was already downloaded during training, so it's sitting in your Hugging Face cache. To make sure nothing goes to the internet, set this before running anything:

export HF_HUB_OFFLINE=1

Now you can turn off the wifi and it still works.

Lesson learned: mlx-lm has a fuse command that merges the adapter into the model to make a single file. I tried it on the 4bit model and it broke everything: 0 out of 10 valid answers, against 7 out of 10 with the adapter. When the merged weights get squeezed back into 4 bits, our small adjustments are too small to survive the rounding, and they just disappear. So keep the base model plus the adapter, it works great.

Asking questions from the terminal

mlx_lm.generate \
  --model mlx-community/Qwen3-4B-4bit \
  --adapter-path out/adapters/4b-best \
  --system-prompt "$(cat prompts/system.txt)" \
  --chat-template-config '{"enable_thinking": false}' \
  --temp 0 --max-tokens 512 \
  -p "We run a small online shop. Orders spike 10x on Black Friday and our single database server fell over last year. We need checkout to keep working even if one data center goes down, and we are only 2 developers."

enable_thinking: false has to match how we trained. --temp 0 makes the answer the same every time you ask the same thing.

Running it as a local API

This is my favorite. mlx-lm comes with a server that speaks the same API as OpenAI, so any tool or script that works with OpenAI can talk to our model instead:

mlx_lm.server \
  --model mlx-community/Qwen3-4B-4bit \
  --adapter-path out/adapters/4b-best \
  --chat-template-args '{"enable_thinking": false}' \
  --temp 0 --port 8080

And now you can call it from anywhere on your laptop:

curl -s localhost:8080/v1/chat/completions -H 'Content-Type: application/json' -d '{
  "messages": [
    {"role": "system", "content": "You are an AWS solutions architect. ..."},
    {"role": "user", "content": "Our team ships a Python API to EC2 by hand every Friday. Deploys take 2 hours and last month a bad deploy took the site down for 40 minutes. We want deploys under 10 minutes and a way to roll back fast."}
  ],
  "max_tokens": 512, "temperature": 0
}' | jq -r '.choices[0].message.content' | jq .

I ran exactly that in offline mode and got:

{
  "category": "serverless-api",
  "services": [
    {"name": "AWS CodePipeline", "role": "Automates the deployment process, ensuring consistent and repeatable deployments"},
    {"name": "AWS CodeDeploy", "role": "Automates the deployment of applications to EC2 instances, reducing manual intervention and deployment time"},
    {"name": "AWS CodeBuild", "role": "Compiles and packages the application, ensuring that only tested and verified code is deployed"},
    {"name": "AWS CloudFormation", "role": "Manages infrastructure as code, ensuring consistent environment setup across different stages"}
  ],
  "rejected": [
    {"name": "AWS Elastic Beanstalk", "reason": "While it simplifies deployment, it may not provide the same level of control as CodePipeline and CodeDeploy for custom EC2 instances."},
    {"name": "AWS Lambda", "reason": "Not suitable for long-running processes like deploying a Python API to EC2 instances."}
  ], ...
}

The services are right on. The category is not (CI/CD isn't one of my 10 topics, so it picked the closest one it knew). A good reminder that the model only knows what we taught it.

Small automations

Since the answer is always JSON, it's easy to plug into scripts. For example, a tiny ask command in your ~/.zshrc:

ask() {
  jq -n --arg s "$(cat ~/coach/prompts/system.txt)" --arg u "$*" \
    '{messages:[{role:"system",content:$s},{role:"user",content:$u}],max_tokens:512,temperature:0}' |
  curl -s localhost:8080/v1/chat/completions -H 'Content-Type: application/json' -d @- |
  jq -r '.choices[0].message.content' | jq -r '.services[].name'
}
$ ask "we need to store 5TB of logs for 7 years but almost never read them"

And the same idea works in CI. If you run a self-hosted runner on your Mac, a job can send the design doc of every pull request to the model and post the suggested services as a comment, without the doc ever leaving your machine. GitHub's macOS runners also run on Apple Silicon, so MLX works there too.

Wrapping up

So that's it! We went from scraping the AWS docs to a small model running on a laptop that answers architecture questions in our exact format, with no API costs and no data leaving the machine.

Is it as good as a real solutions architect? No. But a 4B model trained overnight on a MacBook Air went from inventing services and categories to giving structured, mostly sensible answers 80% of the time. And the same recipe works for your own use case: collect, filter, write an exam, generate flashcards, train, evaluate.

Thanks for following the series!

來源:DEV Community · dev.to