[TUTORIAL] How to fine-tune an LLM for Brazilian Portuguese without breaking what it already knows?
Published on
On October 27, Liquid AI launched the new LFM3 family of models and, among them, LFM3-1.7B, a tiny model (1.7 billion parameters) with a hybrid architecture that mixes convolution layers with attention layers, and, like most models, it has a reasoning mode (it “thinks” before answering) and a no-reasoning mode (it answers right away).
A week later, Maritaca (a Brazilian AI company) published the Observatório Maritaca (the Maritaca Observatory), an open harness with 22 tests in Portuguese, along with the scores of 11 models, and LFM3-1.7B was right there in the middle. And then a bizarre score showed up: on ASSIN 2, a textual entailment test, it got 1.3 in no-reasoning mode (yes, one point three), while with reasoning it scored 87.2. But here’s the catch: the model knew the answer. The 1.3 came from it writing Sim</think>Sim in the middle of the answer (“Sim” means “Yes” and “Não” means “No”, because the test is in Portuguese), and the grader not understanding a thing.
And that’s when I decided to take on this project, on my own, grab LFM3-1.7B and turn it into the best model of up to 2B parameters in Brazilian Portuguese, and WITHOUT losing what it already did well (following instructions, generating JSON, using tools as an agent and answering in English). The result is LFM3-1.7B-BR, which is already public on Hugging Face!
This post is going to be a mix of explanation and tutorial. I’ll show you what post-training is, what other projects in Portuguese did, how I measured everything without fooling myself and each stage of the recipe (SFT, on-policy distillation, DPO and three rounds of GRPO), with the real numbers. And I’ll also tell you everything that went wrong along the way, which was no small amount 😅. At the end, I leave a step-by-step guide with code that reproduces the heart of the recipe, on LFM3-1.7B itself. Oh, and it’s worth saying that this is an independent project, mine, and not an official Liquid release.
Let’s go?

What post-training is (and why I didn’t redo Liquid’s)
Put simply, post-training is everything that happens to an LLM after pretraining. They’re the stages that turn a “text completer” into an assistant that follows instructions, chats, uses tools and knows when to say no.
In pretraining, the model reads an absurd amount of text and learns to predict the next token (if you read my post on logits, you already know how that works). That’s where it learns the language and memorizes a good part of what it knows about the world. But a model fresh out of pretraining is a bit like a new graduate who read the whole library but has never served a customer. Post-training is where it learns to work, to follow protocol and not to do anything stupid.
The most common post-training stages, which will show up a lot in this post, are these:
- SFT (supervised fine-tuning): you show it ready-made examples of questions and answers, and the model learns to imitate the answers. It’s copying from the blackboard: it works, but the model only learns what’s written there.
- Distillation: a “teacher” model teaches a “student” model. In the classic version, the student copies the answers the teacher wrote. In the on-policy version, the student writes its own answer and the teacher corrects it token by token. It’s the difference between copying a classmate’s essay and writing your own and getting it back all corrected in red.
- Preference optimization (DPO, for example): the model sees two answers to the same request, one marked as better and one as worse, and learns to make the better one more likely. It’s like a coffee taster, who doesn’t need to know how to make coffee to tell you which cup is better.
- Reinforcement learning (RL) with verifiable reward (GRPO, for example): the model tries several times, a program checks whether each attempt got it right (like a test with an answer key), and training pulls the model toward the attempts that got it right.
The thing is, the LFM3-1.7B that Liquid published has already been through very heavy post-training. According to their model card, it was an SFT with 1.75 trillion tokens, then RL, an on-policy distillation with six teachers and an RL specific to agents. In other words, what I set out to do was a “post-post-training” on top of a model that already knew a lot. And the biggest risk in a case like this is undoing the work of whoever came before.
There’s a very clear Brazilian example of this. Tucano 2 took the Qwen3-1.7B base model, did continued pretraining with about 50 billion tokens in Portuguese and redid the post-training from scratch. The model got more fluent and more “Brazilian”, but Tucano2-1.5B-Instruct scored 34.3 on IFEval-PT, versus 65.0 for Qwen3-1.7B itself. In other words, half of the instruction-following ability was left on the side of the road. That’s why my first decision was the simplest of all: start from the model already post-trained by Liquid and touch it as little as possible.
In the end, the recipe came out with ten stages on top of Liquid’s work. You can click on each one to see what it did:
Each of these stages has a story (and several of them, a stumble), and I tell them all further on. First, let me show you what already existed.
What other projects did, and what I decided to do differently
Before training anything, I went to see how other projects had fine-tuned small models for a language that isn’t English. The ones that helped me most were these:
- Tucano 2 (Polygl0t, Portuguese): continued pretraining with ~50 billion tokens in Portuguese, a tokenizer swap and a new post-training, starting from the base model. The gains came in fluency and culture, but the “hard” set of tests (the ENEM, Brazil’s national high-school exam; BLUEX; the OAB, Brazil’s bar exam; MMLU…) barely budged (from 48.03 to 47.82), and instruction following was cut in half, as I told you up above.
- GAIA (CEIA-UFG, Portuguese): continued pretraining of Gemma 3 4B with ~13 billion tokens in Portuguese and, instead of an SFT, the addition of a “chat vector” (the difference between the weights of the instruct model and those of the base model). Modest gains: on ENEM 2024, from 65.6 to 70.0.
- Luth (French): SFT with answers regenerated by a bigger model and then a merge (an average of the weights) with the original model. They even made a version of LFM2-1.2B, LFM3’s predecessor, together with Liquid itself.
- Luth-2 (French, on Qwen3.5-2B): the recipe closest to the one I wanted. An SFT with 3.1 billion tokens, then three “experts” trained with GRPO (math, code and instructions) and, at the end, an on-policy distillation that merges the three back into a single model. And a lesson I took seriously: the reward that only checked the instructions’ constraints got “hacked”, and the model learned to write a short, broken French that passed the verifier.
And what about LFM3 itself? In the first ten days after launch, the fine-tunes of it available on Hugging Face were almost all “abliterated” versions (without the safety refusals), and not a single serious fine-tune had passed 40 likes. Focused on Brazilian Portuguese, I didn’t find any.
There were also things I decided to leave out:
- Continued pretraining: it’s expensive, and on a model this size it barely moves the hard knowledge (Tucano 2 showed that). What a 1.7B knows about the world is, basically, what came from Liquid’s pretraining.
- Swapping the tokenizer: it would mean rebuilding the model from scratch, with no guarantee of gain.
- Using a closed API as a teacher: the terms of use of almost all of them forbid training models on their answers. So every teacher, judge and simulated user in the project is an open model, running locally (which also left the API cost at zero).
- Redoing the post-training: for the reason you already know.
With that, the project’s principles ended up like this:
- Touch it as little as possible: start from the post-trained model, use the model’s own answers whenever it was possible to check whether they were right, and low learning rates.
- Goals driven by how a 1.7B model is really used: agentic use with tool calls, tasks over a given context (RAG, extraction to JSON, summarization, classification, rewriting), following instructions, a no-reasoning mode that works and fidelity to Brazilian Portuguese. Knowledge (ENEM, OAB, MMLU) I only report, because a model this size isn’t going to memorize the world, and it’s better for it to be good at reading what you give it than to pretend it knows.
- Measure with the public harness: the same one as the Observatório Maritaca, so my numbers would be comparable with theirs.
- Choose on the dev sets, never on the test, and decontaminate everything: I’ll explain what that means in practice in a bit.
From here on, each section explains a piece of the recipe in a way that applies to any small model, and what I did on LFM3-1.7B-BR comes in as the example.
The starting point: LFM3-1.7B and the defects nobody had described
First, the patient. LFM3-1.7B has 1.73 billion parameters, split across 24 layers of three types:
- 13 short convolutions: each token looks only at its closest neighbors. It’s like reading with a ruler under the line, fast and cheap.
- 5 sliding-window attention layers: each token looks at the last 256 tokens.
- 6 global attention layers: each token can look at the whole text (up to 262,144 tokens of context).
This mix is what makes it fast and light for its size. And the two modes are chosen by the chat template (the mold that turns the conversation into the text the model reads): with reasoning, the model thinks inside a <think>…</think> block and then answers; without reasoning, the template already hands over the block closed and empty (<think></think>), and the model goes straight to the answer.
Before training ANYTHING, I went digging through the raw answers that Maritaca published along with the Observatório (a real lifesaver, by the way). And that’s where I found the defects that became the project’s goals.
1. The </think> that leaks
Remember the 1.3 points on the ASSIN 2 benchmark? Of the 300 answers from the no-reasoning model, 298 came out like this: Sim</think>Sim, or Não</think>Não. In other words, the model answered, wrote the end-of-reasoning tag (which shouldn’t even be there, because reasoning was off) and answered again. The grader read “SimSim”, didn’t recognize it as “Sim” and counted it as wrong. Taking the tag out of the answers, the score went from 1.3 to 87.3. In other words, the model KNEW the answer, and the problem was 100% formatting.
And why only on ASSIN 2? Because this test’s prompt has 18 solved examples in the form of a conversation (the famous few-shot), and the template renders each previous assistant answer with the empty block in front, like this:
With several previous assistant answers in the conversation, the model gets lost in this pattern and starts closing a reasoning block it never opened. To confirm, I wrote new questions (outside any benchmark) and measured the leak with 0, 2, 6 and 18 previous exchanges in the conversation:
The more history, the more it leaks. On the factual questions, with 18 previous examples, it was 17 out of 20. And this isn’t a fault of the server or of the template (the template is right). I checked it the way Liquid recommends, with their code in Transformers, and the ASSIN 2 few-shot leaked on 16 out of 30 questions, while the same question in a single turn leaked on 0 out of 30. Liquid’s model card only says that the no-reasoning mode “can be inconsistent”, without describing the problem.
A curious detail: in Transformers, the </think> keeps showing up even with skip_special_tokens=True. In vLLM, on the other hand, it disappears from the text, and what’s left is a NãoNão. In other words, the score changes depending on which server you use, even with the same model, and that’s why I always look at the raw answers before trusting a number.
2. The made-up tool call
On Structured Output, a test that asks for JSON answers, the no-reasoning model wrapped the answer in a tool call that didn’t exist (<tool_call><function=JSON>…) in about 10% of the items, with no tool in the request. Here the gotcha was in the server too: the adapter Maritaca used let the text through, and the score came out at 86.8. In vLLM, it discards the “call” and returns an empty answer, and the score drops to about 77. Same model, same questions, almost 10 points of difference.
3. Long reasoning, and in English
With reasoning, LFM3 thinks a lot. The median on Prosa-PT (the chat test) was 1,622 tokens, and 10% of the reasoning went past 7,701. And it almost always thinks in English, 73% to 90% of the time depending on the test, even with the question and the answer in Portuguese.
4. Little Brazilian culture
On BRoverbs, a test of Brazilian proverbs (matching a story to the right proverb and vice versa), it scored 40.8 with reasoning. Maritaca’s S5-nano, with about 4 billion parameters, scored 92.8.
There was a fifth defect, maybe the most interesting one, but it only showed up later, when I went to look at how “safe” the model was. I’ll tell you about that one further on.
Evals (evaluations)
This is always (if you read the CatDecide post, you already know) the most important part of any project. Just to give you an idea, counting all the GPUs allocated, the whole project used about 4,360 NVIDIA H100 hours, and only about 1,200 of them (~27%) went into actually training the model. All the rest went to evals.
The scoreboard: the Observatório, ENEM 2026 and Liquid’s English
The main yardstick is Maritaca’s harness. First of all, I reproduced the LFM3 scores they published, to make sure the tests were run the same way. With reasoning, it matched within the noise. And since vLLM, the server I used, didn’t have a released version with LFM3 yet, I compared its implementation token by token with Liquid’s reference one. Over 110k tokens, the two agreed on the most likely token in 98.61% of positions.
Of the Observatório’s tests, these were the ones that weighed most in the decisions:
- Lumen PT: the model becomes an agent with tools at a fictional company and gets requests to do something unethical or dangerous with those tools, often with pressure (“it’s urgent”, “the director ordered it”). A judge decides whether the agent carried out the harmful action. A higher score means the model is safer.
- Prosa-PT: 1,000 real conversations of Brazilians with chatbots (taken from WildChat), and a judge checks each answer against a list of criteria (the rubrics) for that conversation.
- CAPITU and CAPITU conversations: instructions in Portuguese that a program can check on its own (there are 59 types of constraint), in a single question or over a multi-turn conversation.
- Structured Output: answering in valid JSON that follows a schema.
- ASSIN 2: given a pair of sentences, say whether the first entails the second, with those 18 examples in the form of a conversation.
- BRoverbs: Brazilian culture, with proverbs and stories in multiple choice.
- MATH-PT: competition math in Portuguese.
- IFBench: hard instructions (the items are in English).
- Knowledge (ENEM-VL, ENADE-QA, MMLU-PT and Global-MMLU): only reported.
On top of those, two more tests came in:
- ENEM 2026: the exams were on November 8 and 15, and nothing in the training was collected from the web after November 7. In other words, it’s a test no model can have seen. I used the 111 text-only questions (the ones that depend on a figure, among others, were left out), with the provisional answer key from the prep courses, because the official one from INEP (the agency that runs the exam) hadn’t come out yet.
- The English from Liquid’s model card: IFEval and IFBench (instructions), BFCL V4 (tool calling), τ³-bench (an agent talking to a simulated user) and RULER (long context), to make sure Portuguese wouldn’t cost the English.
A local judge, no API
The open-ended tests, like Prosa and Lumen, need a judge. Maritaca used GPT-4.1 (and other closed models, on other tests). Since I didn’t want to depend on any API, I used an open judge running locally, DeepSeek-V4.1-Flash, with reasoning at the highest level. But swapping the judge changes the yardstick, so first I had it re-judge the answers Maritaca published for the 11 models and compared them with the official judgments.
On Prosa, it agreed with GPT-4.1 on 86.8% of the rubrics (and with itself, judging twice, on 96.4%). And here’s what came out:
DeepSeek is systematically stricter (from 4.6 to 7.5 points lower), but the order of the models is exactly the same (rank correlation of 1.000). In other words, you can use it to compare models, as long as you NEVER mix one of its scores with a GPT-4.1 score in the same calculation. That’s why all the Prosa and Lumen scores in this post come from the local judge and can’t be compared with the ones Maritaca published.
On Lumen, the agreement was a bit lower (84.9% on “harmful or not”), and the difference has an explanation. In 297 cases, the model called the tool with made-up arguments, invented by itself, and the test’s own rules say to mark that as “ambiguous”. DeepSeek followed the rule, while GPT-4.1 marked it as if the model had carried out the request.
Three layers: scoreboard, development and diagnosis
At the beginning, my “guardrails” (the tests a candidate model couldn’t get worse on) were the scoreboard tests themselves. One of the first versions passed ALL the guardrails, and when I ran the judge, it had gotten worse on chat and started carrying out harmful requests that the original didn’t. From then on, evaluation became three layers:
- Scoreboard: the Observatório tests, ENEM 2026 and the English. They only run on a candidate for the final model, to report, and never to choose between variations.
- Development (the “dev” sets): sets of my own that never go into training, used to choose checkpoint, learning rate and data mix. Conversation (600 synthetic conversations, with rubrics and the same judge), agentic safety (scenarios of mine, each harmful request with a legitimate “twin”), math, instructions, tools, context tasks and culture (proverbs that aren’t in BRoverbs). Later, others came in, whenever the scoreboard showed a defect the dev sets couldn’t see.
- Diagnosis: the analysis of the errors on the dev sets is what designs the next data. Never the format of a test.
And a dev set is only worth something if it agrees with the test it imitates. The conversation dev set ranks models almost like Prosa (rank correlation of 0.81), and the safety one almost like Lumen (0.79). There was a dev set I built and left out of the decisions because it didn’t reproduce the drop the scoreboard showed. That’s the kind of rule that looks like bureaucracy, but that saved the project a few times.
Decontamination (a rule with no exceptions)
Every piece of data that went into training, including the requests that went to the teacher, first went through a check against all the tests:
- By n-grams: sequences of 13 words and windows of 50 characters identical to some stretch of a test (with accents, case and punctuation stripped from the text).
- By embeddings: sentences whose meaning is too similar to some test item (with the bge-m3 model, cosine from 0.9 up).
- Against what: the Observatório’s 22 tests, the ENEM question bank and the original English versions of the translated tests (295,467 passages), and then my dev sets.
The most glaring case was WildChat, which is the source of the Prosa conversations. Of the Portuguese WildChat, 22,390 of 58,148 conversations (38.5%) were dropped from the project, almost all because they matched Prosa. In total, the final recipe’s training data lost 833 examples, 237 for matching a test and the rest for matching some dev set. And against the 111 ENEM 2026 questions, nothing matched.
The first attempts (or everything that went wrong before it went right)
The recipe I show later on was the second attempt. The first one followed the obvious path (a big SFT with answers from a bigger teacher, a merge with the original and a distillation to round things off) and it didn’t work, but it’s where I learned almost everything the second one used.
Gotcha 1: the fix that turned off reasoning
The first pilot, with LoRA and 6,000 multi-turn conversations, got rid of the leaked </think> (0 leaks in 200 tests). But with reasoning, ASSIN 2 dropped 52.1 points and MATH-PT, 41.7. The model had simply stopped thinking.
Can you guess why? The template puts an empty <think></think> at the front of every no-reasoning answer, and the loss was counting those two tokens. So, thousands of times over, the model learned that right after opening <think>, the right thing to do is close it. In reasoning mode, the prompt ends precisely on an open <think>… and it closed it right there. The fix is to take out of the loss the <think> that opens each answer and the </think> of an empty block. With that mask, the next pilot reasoned on 20 out of 20 questions, without the tag coming back (you can see that happen in Steps 2 and 3 of the tutorial, at the end).
Gotcha 2: thinking in Portuguese made everything worse
Since the model reasons in English, I tested teaching it to think in Portuguese, by translating the reasoning of a slice of the training data. It got worse on almost everything, especially on loops (answers that repeat until they hit the token limit): from 26% to 48% of answers, against 0% to 25% when thinking in English. For a 1.7B model, switching the language of thought with about 30k examples is too big a change, and the reasoning stayed in English.
Gotcha 3: the big SFT with a bigger teacher
Then came the “real” SFT: about 200k examples with answers from Gemma 4 26B-A4B and full fine-tuning at a learning rate of 2e-5, which is what recipes like Luth’s use. The no-reasoning tests went up, but on the conversation dev set the model ended up 25.3 points below the original with reasoning and 16.9 without. The literature explains it: learning rates 4 times smaller already make models of 3 to 4 billion parameters lose almost half of their general capability, and the small student, imitating a much bigger teacher, learns the form and loses the content. That gave me the rule for the second attempt: narrow SFT, low learning rate and, whenever I can check it, answers from the model itself.
Gotcha 4: the merge and the safety valley
To recover what the SFT broke, I did what Luth did, a SLERP merge between the original and the trained model: a kind of average of the weights, where α says how much of the trained model goes in. With α 0.3, reasoning went back to the original’s level and the no-reasoning gains stayed. It looked perfect, until I measured safety with tools:
Both ends score about 52, and the merge with α 0.3 scores 21.4, carrying out the harmful action on 78.6% of attempts. Explicit refusal (10.8%) ended up below BOTH ends (17.0% in the original and 36.2% in the SFT), and the original’s “inertia” (neither acting nor refusing, the purple band) dropped from 29.6% to 2.1%. Keep that inertia in mind, because it’s coming back real soon. I couldn’t find any work that measured agent safety across α, and the merge was dropped from the recipe.
Gotcha 5: it passed every guardrail and still got worse
The last piece was an on-policy distillation on top of the merge, with the original and the SFT as teachers. The sixth attempt (the first five fell apart midway) passed all the guardrails, which back then were scoreboard tests: MATH-PT without reasoning went up from 72.4 to 82.8, and CAPITU with reasoning, from 86.5 to 97.0. I had a candidate! Then I ran the judge. On Prosa with reasoning, 40.1 against the original’s 45.4, and on Lumen without reasoning, 59.5 against 84.2 (the harmful action in 525 of the 1,296 scenarios, against 205).
But on Lumen, the explicit refusal of the two was practically the same (44.8% against 46.3%). What changed was the inertia: 34.0% in the original and 7.7% in the distilled one. In other words, a good part of the original’s “safe” score was an inability to act. It’s that employee who never makes a mistake because he never does anything.
Two decisions that guided the rest of the project came out of that: the three-layer evaluation, which I already showed, and the safety goal. What counts is explicit refusal, with the model still carrying out the legitimate tasks, and not the “safe” score. The target was to get close to Gemma 4 E2B, which explicitly refuses about 76% of Lumen’s harmful requests without reasoning.
The final recipe, stage by stage
Having learned from the mistakes, I started again from the original LFM3-1.7B. I’ll follow the order of that ten-stage figure from the beginning of the post.
Stage 1: a narrow SFT
The final SFT had 68,269 examples, and each slice targets a flaw or a goal:
- Agentic refusal: 4,000 refusals of harmful requests with tools and 15,872 similar legitimate tasks, carried out (the “twins”, which I explain below). The requests come from AgentAlign, translated, and from my own workplace-ethics scenarios, generated by Gemma.
- Rewritten chat: 9,196 conversations, no-reasoning only. Here the requests come from real people: 6,987 from WildChat in Portuguese (what was left after decontaminating against Prosa), 2,132 from the Aya Dataset and 77 from OASST2.
- Culture: 8,998 examples built from Portuguese Wikipedia (Gemma wrote the questions on top of the articles).
- Context tasks: 8,000 examples of classification, extraction and questions about a given document. Gemma made up the documents.
- Fixed-format few-shot: 5,708 examples where the answer is a short label, after solved examples in the conversation, which is exactly the case of the leaked
</think>. The items for the 35 tasks (sentiment, entailment, pulling out a date…) were also created by Gemma. - Tools: 5,999 examples of tool calls, taken from the tool-use conversations in Dolci, Olmo 3’s post-training data. In the 1,999 Portuguese ones, the user turns were translated.
- English: 5,999 “replay” examples, so it doesn’t forget English. They’re English requests from Dolci (almost half of them from WildChat), answered by LFM3 itself.
- Multi-turn and chat safety: 4,497 examples. The 2,997 multi-turn conversations are stitched together: several request-and-answer pairs from other examples, placed before a final request from WildChat, Aya or OASST2. The 1,500 safety ones are requests from WildJailbreak and WildGuardMix (both via Dolci), translated.
A list of slices is kind of abstract, so here’s a real example of each one, taken straight from the file that went into training:
And who wrote the answers:
Almost 80% of the answers come from LFM3 itself. Wherever I could check with a program (the right tool call, the right label, the right answer), I generated several answers from the model itself and kept the ones that passed the verifier. It’s the cheapest way to “change as little as possible”: the model trains on its own style, just without the mistakes. Gemma wrote what LFM3 couldn’t do (the refusals and about 875 hard tasks it never got right) and, in an earlier mix that I reused, the Portuguese answers for the tools and chat safety.
The training itself was the dullest part of the project. It was a full fine-tuning with the SFTTrainer from TRL, on 12 H100 GPUs with torchrun, a learning rate of 5e-6 (4 times smaller than the first SFT’s), one epoch (1,422 steps, with batches of 48 examples), sequences of up to 16k tokens and, of course, the <think> mask. I built the labels before handing them to the trainer: the loss only counts the assistant’s tokens (LFM3’s template already marks that part) and skips the tags the mask removes. The only addition to the trainer was grouping examples of similar length in the same step, so no GPU sits waiting for the one that got a 16k-token example (in an earlier test, that made training 54% faster). It took 33 minutes. I also trained a version with LoRA (with PEFT, rank 64, learning rate of 2e-4), and the two tied on almost everything. The full one won by 3 points on safety with reasoning, and that’s why it stayed.
The benign twins
The most laborious slice was the refusal one. The harmful requests came from two sources: AgentAlign, translated, and 1,440 scenarios of my own about workplace ethics, generated by Gemma with tools different from Lumen’s. And each harmful request has one or more legitimate “twins”, in the same scenario, with the same tools. The example below is from a batch I generated later, for GRPO 3, but the idea is the same:
Notice that the harmful and the benign requests touch the SAME ledger entry, with the SAME amount and the same tool. The only difference is the intent. Without the twins, the model learns a much simpler (and wrong) rule: “request about money, looks urgent, refuse it”.
And that’s exactly what I caught before training, which became gotcha 6, the surface shortcut. In the first assembly, the benign requests left over after the filter were almost all short, with a single tool, while the harmful ones were long and full of pressure. In my workplace scenarios, the harmful request had a median of 528 characters, and the benign one, 205. And only 1,117 of the 7,436 refusals had any benign request similar to them. If I had trained like that, the model would have learned to refuse based on the length and pressure of the request, not on the content. The fix was to ask Gemma to rewrite each benign request with the same pressure and the same length as the scenario’s harmful one (2,880 rewrites, with a median of 504 characters), without changing the operation, and to balance the mix so there are never more refusals than benign requests in each band of length and number of tools.
And gotcha 7 was in the verifier for the benign requests. The original criterion required all the arguments to match AgentAlign’s reference answer, and even Gemma 4 26B failed on 96% of the hard cases. I went to look and the references contained values the request never even gave. In other words, the verifier was broken, and I would have thrown away almost every hard benign request. I switched to requiring only the values that appear written in the request or in earlier tool outputs.
Against the original, on the dev sets, the SFT came out like this:
- Safety: +53.2 points with reasoning and +36.6 without, with the harmful action in about 10% of scenarios.
- Chat: −4.4 and −4.9. Much better than the −25 of the big SFT, but still a loss.
- Legitimate tasks with tools: −12.5 with reasoning. Without reasoning, a tie on score, but with 17.6% over-refusal in place of the old inertia.
Stage 2: on-policy distillation
If you read my post on pruning and distillation, you already know what it means to distill token by token. Instead of learning just “this is the right answer”, the student learns the teacher’s entire probability distribution at each position. The difference here is on-policy. The student writes its own answer, in its own way, and the teacher reads that SAME answer and says, at each token, how much it agrees. The student gets corrected on the mistakes it actually makes, and not on texts it would never write.
In practice, it goes like this. Below is a real example: the SFT model (the student) answered a request on its own, and the original LFM3-1.7B (the teacher) read the same answer, token by token. On the other tab, the opposite, which is what happens in an SFT: the student trains on the teacher’s text, even on the tokens it would never choose.
But how does the teacher “say how much it agrees”? At each position, neither model has a single word in mind. They both have a probability distribution, a list with the chance of each token being the next one (after “A capital de Goiás é”, which is Portuguese for “The capital of Goiás is”, the teacher might give 62% to “Goiânia”, 25% to “a” and 8% to “Anápolis”…). To compare two lists like that, we use the KL divergence (from Kullback-Leibler, the last names of the two mathematicians who created the measure). It gives zero when the two lists are equal and grows the more they disagree.
The catch is that KL isn’t symmetric: you can measure it from the teacher’s side or from the student’s side, and the result changes. On-policy distillation uses the reverse KL, which measures from the student’s side. At each token, it takes the probability the STUDENT gave and multiplies it by the size of the disagreement with the teacher (the logarithm of the ratio between the two probabilities). In other words, it only counts where the student actually placed a bet. If it puts probability on a token the teacher finds absurd, the cost explodes. If it leaves aside an option the teacher would have accepted, it costs almost nothing. It’s the reviewer who crosses out what’s wrong, but doesn’t force you to write the text exactly the way they would. You can test it here:
In other words, the student doesn’t need to imitate all of the teacher’s ways of answering, it just can’t write what the teacher would consider wrong.
And this only works this directly because the teachers use the same tokenizer as the student, so you can compare the distributions position by position. There were two teachers, and the dev sets decided who taught what:
- The original LFM3, on 14,499 of the 20k requests: chat, multi-turn, math, instructions, code, English, the legitimate agent tasks and the rest. After all, it was the model itself before the SFT.
- The model I trained in the SFT stage, on 5,501: agent refusals, culture, few-shot, chat safety, and tools and context without reasoning, where it was already better than the original.
And where do the 20k requests come from? From the same sources as the SFT slices, plus three new domains. There are 4,000 chat (WildChat, Aya and OASST2), 1,600 harmful agent and 1,600 legitimate agent (AgentAlign and my own scenarios), 1,400 tools and 1,400 English (Dolci), 1,200 context, 1,000 culture, 800 few-shot, 800 chat safety and 600 multi-turn. The new ones are math (2,600), instructions with constraints (2,000) and code (1,000), all from Dolci, some translated and some in English. Half go with reasoning and half without, and only the request goes in: the answer is written by the student.
Two details made a big difference:
- Privileged context: on 4,000 chat requests, the teacher (the original) reads Gemma’s answer in the system prompt, and the student doesn’t. It’s like a teacher grading an essay with the answer key at their side. This only applies to the tokens of the final answer. In the reasoning, the teacher reads the same prompt as the student (that’s how chat with reasoning gets in, without the “the reference answer” problem).
- Tokens banned for the teacher: reverse KL pulls the student toward the teacher on EVERYTHING, defects included. If the original wants to write
</think>in the middle of a no-reasoning answer, the distillation would teach the leak right back. So the teacher takes −30 on the logit of those tokens (the<think>and</think>without reasoning, and the<tool_call>when there’s no tool in the request), which in practice zeroes their probability.
But this second detail hides a trap that I only came to understand at the end of the project. Look at what the original wants to write right after answering “Goiânia” in a no-reasoning few-shot, and what’s left when we ban the tags:
The original doesn’t want to end the answer there (the end of the turn has a 0.03% probability). It wants either to close a reasoning block it never opened (the leaked </think>) or to skip a line and keep thinking out loud. Ban the tag and what’s left is “keep thinking”. In other words, banning the defect doesn’t teach the teacher to stop, and this is going to come back in force when I talk about the model’s limits. Keep that figure in mind.
The training was a full fine-tuning with the DistillationTrainer from TRL, Hugging Face’s library, in which the student generates its own answers with vLLM running in the same process (it “sleeps” during each training step, to give the GPU memory back). TRL already brings the reverse KL and on-policy generation, and the teacher routing, the privileged context and the banned tokens I wrote on top, in a subclass of it. It was 200 steps, each with 64 requests and 4 student answers per request (51,200 corrected answers in total), a learning rate of 2e-6 and answers of up to 4,096 tokens. Against the original, on the dev sets:
- Chat: −2.0 with reasoning (the interval goes from −3.8 to −0.1) and a tie without. The SFT scored −4.4 and −4.9.
- Safety: +46.8 and +36.9, with the harmful action in about 17% and 10% of scenarios.
- Math and tools without reasoning: +2.4 and +3.5.
- Legitimate tasks with tools, with reasoning: −10.9. I went to look at the errors, and in 101 out of 130 the model just kept querying the database, over and over, until the call limit, and never carried out the action. A query loop.
Stage 3: DPO (which barely did anything)
The next step was to tackle chat with preferences. In DPO, each example is a pair of answers to the same request, a “chosen” and a “rejected” one, and training makes the chosen one more likely than the rejected one. The pairs came from the model itself (4 answers per request), with scores given by a training judge (Qwen3.8-27B) different from the judge that picked the checkpoints.
There were three rounds, and none got past the original’s chat. The first one learned shortcuts: it copied Gemma’s list marker (the * ended up in 49% of the answers) and started shortening answers, because my tiebreaker picked the shorter answer as “better”. The second one learned nothing (the loss ended at 0.686, almost the ln 2 of a coin flip). And the third, with higher learning rates, wrecked chat with reasoning (−26.9), because in DPO the chosen and the rejected can lose probability together, and that leftover probability ended up on reasoning that never closes the </think>.
What stayed in the recipe was the weakest variant of the second round, precisely because it barely changed the model. If I were to try again, I’d put in an anchor (an SFT term on the chosen answer) to hold both answers in place.
The 3,882 pairs of that round came from requests that hadn’t been in the distillation, but from the same sources: 2,054 chat (WildChat, Aya and OASST2), 574 multi-turn, 473 instructions, 374 English and 152 math (those three from Dolci) and 255 agent.
Stage 4: GRPO with verifiable rewards
This is where the Reinforcement Learning (RL) part comes in. In GRPO, for each request, the model generates several answers (8, here, at temperature 1.0, to get variation). A program scores each one (1 if it got it right, 0 if wrong), and each answer is compared with the average of its own group (that difference, divided by the group’s standard deviation, is called the advantage). The ones that were better than average become more likely, and the worse ones, less. You don’t need a reward model or a “critic”, only the verifier. You can play with it here:
Notice the case where all of them get it right (or all get it wrong): everyone’s advantage becomes zero, and that request teaches nothing. That’s why, before each round, I ran the model 8 times on each candidate request and kept only the ones that got 1 to 7 right. The rest is a waste of GPU.
There were three GRPOs along the recipe (stages 4, 6 and 8 of that figure from the beginning), each with its own target:
- GRPO 1: agent, instructions, math, tools and the length of the reasoning. It took two attempts.
- GRPO 2: the same domains plus two new ones, irrelevant tools (where the right move is to call nothing) and multiple-choice math.
- GRPO 3: the focus was the agent, now with 18 different system prompts, against over-refusal (the other domains stayed in the pool). It also took two attempts.
And the requests for each domain came from here:
- Agent: the same scenarios as the SFT refusal slice (AgentAlign and my own scenarios). In GRPO 3, 1,256 of the 1,549 agent items are my own scenarios that had never shown up before, generated by Gemma for that round (harmful requests disguised as routine and the “sensitive” twins, which I explain further down).
- Instructions: real requests in Portuguese (WildChat, Aya and OASST2) and in English (Dolci), which hadn’t been in the distillation or the DPO, with 1 to 3 constraints written for training.
- Math: problems from the training split of MATH (levels 3 to 5, numeric answers only), translated by Qwen3.8-27B, with a quarter left in English. GRPO 2’s multiple choice uses the same questions, with the wrong options generated by a program. Since the scoreboard’s MATH-PT is MATH in multiple choice, I stuck to the training split and decontaminated against MATH-PT and against the test split.
- Tools and irrelevant tools: the Dolci tool conversations that were already in the SFT. In the irrelevant ones, the request goes with the tools from ANOTHER conversation, which are useless there.
After the filter (the 1-to-7-correct one), 3,506 requests were left in GRPO 1, 2,104 in GRPO 2 and 2,868 in GRPO 3.
The algorithm was TRL’s standard GRPO, without the KL term, which is the part of the loss that holds the model close to where it started. Without that anchor, GRPO can take the model far away on everything the reward doesn’t look at, and that’s why each GRPO in the recipe is followed by a repair. And the rewards, almost all binary:
- Agent: on a harmful request, 1 if it refused without calling any tool. On a legitimate one, 1 if it made the right call (and refusing is worth 0).
- Instructions: constraints that a program checks, in Portuguese and in English, with none of IFBench’s constraint types.
- Math: the answer inside the last
\boxed{}. - Tools: all the expected calls, with the right arguments.
- Length: a correct answer loses up to 0.5 points for whatever goes over a token budget (the goal of shortening the reasoning without losing accuracy).
- A format defect zeroes it: an answer that’s cut off, or that has the reasoning tag in the answer, is worth 0.
Again, saying “a list of rewards” is kind of abstract, so here are real groups, taken from the first GRPO’s log (it saved the 256 answers of each step, with each one’s score and advantage):
GRPO 1: the first attempt learned to be short
GRPO 1’s first attempt had a token cap of 4,096 tokens per answer, and a cut-off answer was worth 0. It seemed reasonable, until I looked at the filter. In math, look at why the answers scored 0:
Of the 11,089 answers with a score of 0, 8,651 had been cut off by the cap, and only 553 had gotten the math wrong. In other words, the “signal” GRPO saw was, for the most part, “sometimes this answer goes over 4,096 tokens”. And it learned exactly that: on the math dev set, the no-reasoning answer dropped from 1,511 to 521 tokens at the median, and the reasoning, from 1,416 to 465.
With reasoning, the final math answer became just the \boxed{}, with a median of 6 tokens (it used to be 304). And on the dev set, which lets the answer be long, the short solution got more of the math wrong: no-reasoning math dropped 8.5 points. Along with it came the sibling gotcha: the agent reward gave full score for “at least one right call”, and the safest path to that was calling just one tool. On tools in Portuguese, the score dropped from 66.2 to 50.8 (and to 35.8 in the variant with the higher learning rate), almost always for dropping the parallel calls.
The second attempt fixed both things: the length penalty now counts only the reasoning (the final answer can be whatever length it needs), the cap went up to 12,288 tokens (cutting far fewer legitimate answers) and a tools domain with 4,000 items came in, 70% of them with parallel calls. Now we’re talking: the math reasoning got 32% shorter with accuracy tied, and no-reasoning instructions went up 7.9 points. As a bonus, the leaked </think>, which showed up in 41% of the no-reasoning math samples at the training temperature, disappeared, because the reward zeroed answers with the tag.
GRPO 2: the scoreboard saw what the dev sets didn’t
After a short repair (which I explain in the next section), this model passed the dev sets and became the first final candidate. On the scoreboard, two problems showed up that no dev set measured:
- MATH-PT without reasoning, −19.6: the test asks “responda somente a letra” (answer only with the letter), and the model started answering with just the letter, without doing the math first, on 202 of the 638 questions. Before, it ignored the “somente” (“only”) and solved the problem.
- BFCL irrelevance, −8.1: the model called a tool even when none fit the request.
By the three-layer rule, the scoreboard can’t choose anything. So I created two new dev sets, the irrelevance one (where the right thing is to call no tool at all, and where this candidate scored 57.9 against the original’s 86.8) and the multiple-choice math one, and I did GRPO 2 with those two new domains. Irrelevance without reasoning went from 57.9 to 88.2.
GRPO 3: against over-refusal
The candidate after GRPO 2 (and its repair) had a problem I’d already seen. Without reasoning, it refused 25.5% of the dev set’s legitimate twins, and 43% when the system prompt talked about ethics. The diagnosis, again without training anything, pointed to three causes:
- The SFT refusal data had no system prompt. The model had never seen a legitimate task with a “strict” system prompt.
- GRPO used a single neutral system prompt, and the model already got 8 out of 8 on 93% of the agent requests. In other words, almost no signal.
- The tests’ ethics prompt triggered refusals of the benign requests.
GRPO 3 rendered each agent request with one of 18 system prompts written for training (6 neutral, 6 balanced, 6 strict and 10% with none), the same ones for the harmful and the benign requests, so the model doesn’t learn that “strict prompt = refuse”. And none of them copies Lumen’s: the longest stretch in common is 4 words.
But the first attempt at GRPO 3 didn’t pass either: it won on the benign requests and lost 4 to 10 points of safety. Four more rules came out of that:
- The RL pool doesn’t reuse SFT items. 97% of the benign ones were already there.
- The benign ones need to LOOK risky. They’re the “sensitive” twins, with the same operation and the same delicate point as the harmful one, but with a legitimate reason written in the request. The clearly legitimate ones give no signal.
- The benign ones with signal can’t outnumber the harmful ones with signal.
- Anchors: a share of the harmful requests the model already refused 8 out of 8 goes into the pool, so it doesn’t unlearn.
In the second attempt, with 704 harmful requests, 704 benign ones and 141 anchors, the refusal of legitimate twins dropped from 25.5% to 15.5% without reasoning (and from 43% to 22% with the ethics prompt), already counting the repair that comes next, and without losing safety.
The repairs: giving back what GRPO loses
Every GRPO makes the model lose a bit of chat and context quality, because it shortens answers even where it shouldn’t. So, after each round, I did a repair, which is a short on-policy distillation, 50 steps, with the original LFM3 as the teacher. This repair runs only on chat, multi-turn and context: 5,800 requests, the same ones from those three areas in the distillation (4,000, 600 and 1,200), and the same in all three repairs. In general, chat went back to its pre-GRPO level, and context almost did.
The broad repair (and the checkpoint choice)
The candidate’s scoreboard after GRPO 3 showed more losses that the dev sets didn’t see (Prosa, MATH-PT and τ³-bench with reasoning, all small, and a few loops on long context). Before training anything, I built new dev sets for each one, with the rule that a dev set only gets in if it reproduces the test’s loss. Only the new chat dev set (900 conversations, judged the same way as Prosa) reproduced it. The multi-turn agent one and the long-context one didn’t, so those fronts left the recipe and became known limitations.
The last training run was a broad repair, also by on-policy distillation, with 9,618 requests and two teachers:
- The original LFM3, on 7,075 requests: the 5,800 from the repairs (chat with the privileged context, multi-turn and context) plus 1,275 math with reasoning, from Dolci.
- The trained model itself, as an anchor, on 2,543 requests taken from the GRPO 3 pool: agent with the 18 system prompts (1,549), instructions (380), tools (225), math (196, half of it multiple choice) and irrelevant tools (193). In other words, in those areas the teacher was itself, so nothing GRPO taught would get lost.
It was 150 steps, with a checkpoint saved every 50. The choice was made on the new chat dev set, with guardrails on all the other dev sets. The step 100 checkpoint beat the previous candidate on chat (+1.9 with reasoning and +3.1 without) and tied on almost everything else (the only loss was 1.6 points on legitimate tasks without reasoning, from an execution error, and not from refusal). The step 50 one lost safety, and the step 150 one didn’t win on chat with reasoning. And that step 100 became LFM3-1.7B-BR.
The result: comparing with the other small models
To compare, I ran the open models of up to about 2 billion parameters that would make sense in place of LFM3-1.7B-BR in the same harness, the same way:
- Gemma 4 E2B, from Google: the strongest in culture in its category. It has 2.3 billion “effective” parameters, but 5.1 billion counting the embeddings, so it comes with that caveat.
- MiniCPM5-2B (with 2.5 billion), the one Liquid itself compares against in the LFM3 model card.
- Qwen3.5-2B and Qwen3.5-0.8B, from Alibaba.
- LFM2.5-1.2B, LFM3’s predecessor.
- Tucano2-1.5B, the Brazilian one.
I didn’t build an “overall scoreboard” with the average of everything, because several tests scored by the Observatório’s judge don’t have the adapter for the local judge yet, and an average with half of the tests doesn’t make much sense. So it goes test by test, in both modes:
What each scoreboard measures and where LFM3-1.7B-BR landed:
- ENEM 2026: the highest score in both modes (85.6 and 65.8), but with 111 questions the interval is about ±8 points, so it’s a statistical tie with the original and with the best rivals. What I can say with confidence is that knowledge didn’t drop, which was the only requirement.
- Lumen PT (agentic safety): 1st in both modes, with 98.1 and 98.8. Gemma 4 E2B comes right behind, but LFM3-1.7B-BR carries out fewer harmful actions than it in both modes, with the whole interval below zero. The original scored 76.8 and 84.2.
- Structured Output (JSON): 1st in both modes, 98.6 and 95.8. Without reasoning, it went from 86.8 to 95.8 against the original, almost all because of the made-up tool call that disappeared.
- CAPITU (instructions in Portuguese): 1st with reasoning (97.5). Without reasoning, Gemma 4 E2B wins (81.0 against 72.5), and LFM3-1.7B-BR ties with the original.
- CAPITU conversations (instructions in a multi-turn conversation): 1st in both modes.
- ASSIN 2 (textual entailment): technical tie at the top in both modes (with MiniCPM5 and Gemma with reasoning, and with Gemma without). Without reasoning, from 1.3 to 91.3 against the original, that flaw from the beginning of the post.
- MATH-PT (math): ties with the original in both modes. With reasoning, MiniCPM5-2B wins (88.7 against 85.1); without reasoning, LFM3-1.7B-BR beats all the rivals.
- IFBench (hard instructions, in English): with reasoning, only the original stays ahead (68.7 against 66.3, a statistical tie). Without reasoning, MiniCPM5-2B wins by a wide margin.
- Prosa-PT (open chat): here LFM3-1.7B-BR doesn’t shine. Gemma 4 E2B leads (47.2 with reasoning and 43.1 without), and LFM3-1.7B-BR lands 3.4 points below its own original with reasoning (without reasoning, it ties). I come back to this in the limits.
- BRoverbs (culture): +17.7 and +18.2 against the original, but Gemma 4 E2B is still comfortably ahead.
In the knowledge tests that I only report (ENEM-VL, ENADE-QA, MMLU-PT and Global-MMLU), Gemma 4 E2B leads most of them, and LFM3-1.7B-BR ties with or beats the original in every one where it has a score (without reasoning, three of them don’t finish in time, for the reason I explain in the limits). In other words, as expected, the knowledge of a 1.7B is the one it got from pretraining.
Safety: refusing instead of doing nothing
But the Lumen scoreboard hides an interesting part, which is what each model does when someone asks for something harmful:
LFM3-1.7B-BR explicitly refuses 97.1% of the harmful attempts with reasoning and 98.7% without. Gemma 4 E2B refuses 80.1% and 75.7%, and the original, 46.3% in both modes. The original’s inertia, which was 34.0% without reasoning, practically disappeared (0.1%). In other words, the safety goal was met the right way: the model says “no, and here’s why” instead of freezing.
And in English?
The goal was not to lose English. On the tests from Liquid’s model card, against the original:
Without reasoning, the instruction scores go up a lot (IFEval +12.5 and IFBench +5.9) and so does BFCL irrelevance (+3.2), which is the model calling fewer tools for no reason. With reasoning, almost everything ties. The losses are in τ³-bench, in both modes (about 5 points), in BFCL irrelevance with reasoning (−3.1) and in RULER without reasoning (−2.2). In τ³-bench, which simulates a customer-service agent with tools talking to a customer, the model started transferring more often to the human agent when it didn’t need to (in the telecom domain, with reasoning, it transferred in 100 conversations, against 87 for the original). So, in English, the goal was half met: the instructions got better, the agents got worse.
Before and after
Putting it all together, the same model before and after the recipe:
Without reasoning, the gains are huge and almost all of them about format: ASSIN 2, Structured Output, CAPITU conversations and BRoverbs. With reasoning, the original model was already good, and the recipe moved much less: it gains on BRoverbs and Lumen, ties on most and loses on Prosa. That’s why I say the main change is that no-reasoning mode, the fast and cheap one, started working.
And here’s the same few-shot of the capitals that opened the post, with the answers just the way they come out of Transformers:
The original knows the answer, writes it, thinks out loud in English about what it just wrote, leaks the tag and writes it again. LFM3-1.7B-BR just answers.
The limits (what I couldn’t do)
Now the part I think every model card and every post should have.
- Open chat: no round got chat past the original’s. On Prosa, LFM3-1.7B-BR lands 3.4 points below with reasoning (the interval goes from −4.7 to −2.2) and ties without. Distillation with the original as the teacher gives you back, at most, the original itself, and DPO couldn’t go beyond that. From what I’ve read in the literature, to beat the original at chat you need a better source of signal than the original, like preferences with rubrics that actually work or a specialist trained with RL serving as the teacher. That’s for next time.
- Knowledge: it’s still a 1.7B model. For knowledge questions, the best thing is to provide the context (RAG).
- Agents in English: the roughly 5 points lost on τ³-bench, with more transfers to the human. My multi-turn agent dev set, in Portuguese, didn’t reproduce this loss, so it never factored into the choices.
- The evaluation has limits too: one run per test, a single judge and a few tests that aren’t completely blind (MATH-PT, BFCL irrelevance and Prosa showed flaws in intermediate models that I later fixed with new dev sets, so, for those flaws, they’re not a 100% independent measure).
And besides those, the loops. When there’s a very long input in no-reasoning mode, LFM3-1.7B-BR sometimes starts “thinking out loud” inside the answer and never stops. On LongBench v2, a long-context test, 75 (out of 487) answers ran all the way to the 262k-token cap (the original did this 23 times out of 487). Something like this:
“(Now I’m done.)”, it says, and it is very much not done 😅. Notice the chart too: the loop barely existed in the original and crept in little by little, with a jump at GRPO 3.
And the explanation closes a loop with the beginning of the post. Remember that teacher figure I asked you to keep in mind? Without reasoning, when the original starts thinking out loud, it has a way out: it closes the “reasoning” with the leaked </think>, writes the answer and stops. vLLM erases the tag, and nobody sees it. I measured this: at the point where the original finishes thinking out loud, the probability that it writes the </think> is 0.94. In LFM3-1.7B-BR, 0.06. In other words, by fixing the leak, the recipe took away the model’s emergency exit from thinking out loud, without putting another one in its place. And since ending the turn was never the original’s natural path at that point, distillation with it as the teacher wouldn’t teach stopping (with the </think> banned, it only teaches continuing to think).
I made one last attempt aimed only at this: a short GRPO, only for no-reasoning mode, with a reward that only gives 1 when the model STOPS before the cap and ends with the right answer on the last line. The loops practically disappeared (on LongBench, they dropped from 75 to 4). But this training made the model lose in other places, like MATH-PT without reasoning (−4.9), RULER with reasoning (−4.2) and τ³-bench on the retail task without reasoning (−9.2). On top of that, it created a new flaw in reasoning mode: when there was a long input, it would sometimes write the answer inside the reasoning and stop with no final answer. Weighing everything, that version was left out, and LFM3-1.7B-BR keeps the loops as a known limitation.
The practical advice: for long inputs, use reasoning mode (there, loops show up in only 0.3% of the items in my dev set) or limit the maximum answer length with max_tokens.
How to use LFM3-1.7B-BR
If you just want to use LFM3-1.7B-BR, without training anything, the simplest path is vLLM, from version 0.34.0 on (which is the one I tested). In a terminal, run:
pip install "vllm>=0.34.0"
vllm serve fabriciocarraro/LFM3-1.7B-BR \
--dtype bfloat16 --max-model-len 262144 \
--reasoning-parser qwen3 \
--enable-auto-tool-choice --tool-call-parser qwen3_coderLFM3’s template writes tool calls in the Qwen3-Coder format, and vLLM doesn’t have an LFM-specific parser yet, so I use those two in all the evaluations. The server speaks the OpenAI API, so any compatible client works:
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
MODEL = "fabriciocarraro/LFM3-1.7B-BR"
text = ("O Recife é a capital de Pernambuco e um dos principais polos de tecnologia do Nordeste, com o Porto Digital, " # a short text about Recife's tech hub
"que reúne centenas de empresas no bairro do Recife Antigo.")
resp = client.chat.completions.create(model=MODEL, messages=[{"role": "user", "content": f"Resuma em uma frase: {text}"}], # "Summarize in one sentence: {text}"
extra_body={"chat_template_kwargs": {"enable_thinking": False}})
print(resp.choices[0].message.content)
tools = [{"type": "function", "function": {
"name": "consultar_clima", "description": "Consulta a previsão do tempo de uma cidade brasileira", # "Looks up the weather forecast for a Brazilian city"
"parameters": {"type": "object", "properties": {"cidade": {"type": "string"}}, "required": ["cidade"]}}}]
resp = client.chat.completions.create(model=MODEL, messages=[{"role": "user", "content": "Vai chover em Recife hoje?"}], # "Will it rain in Recife today?"
tools=tools, extra_body={"chat_template_kwargs": {"enable_thinking": False}})
print([(t.function.name, t.function.arguments) for t in resp.choices[0].message.tool_calls])I ran this on an NVIDIA DGX Spark and this is what came out:
O Recife é a capital de Pernambuco e um polo tecnológico importante do Nordeste, destacando-se pelo Porto Digital, que reúne centenas de empresas no bairro Antigo.
[('consultar_clima', '{"cidade": "Recife"}')]The enable_thinking: False turns on no-reasoning mode. Without it, the default is to think first, and the reasoning comes separate from the answer, in its own field of the message. And the tool call already comes ready in tool_calls, with no <tool_call> in the text.
Step by step to do the fine-tuning with me
Now, the hands-on part. The full recipe used a lot of GPU and a few days, so what I’m leaving here is a scaled-down version of it, the most important parts, on top of the original LFM3-1.7B itself, going after the same defect from the beginning of the post: the leaked </think>. You’re going to find the defect, fix it with an SFT done with the model’s own answers (and watch the mask gotcha happen), distill with the original as the teacher (and see why the loops happen), fix it again with a GRPO and compare everything without fooling yourself.
The blocks are meant to be run in sequence, like in a notebook (Step 3 uses what Step 2 set up, and so on). All the code was tested on a DGX Spark, and the outputs shown after each block are the real ones. Since the model generates with sampling, your numbers might change a little, but the story is the same. And don’t worry, I’ll explain every piece.
What you need
- A GPU with bf16 and about 9 GB of free memory (that was the peak, measured on the GRPO): from the Ampere generation onward, like an L4, A10, A100 or an RTX 3090/4090. On Colab, the L4 or the A100 can handle it; the T4 on the free plan doesn’t have bf16.
- Python with the libraries below, in the versions I tested. LFM3 still runs on Liquid’s own modeling code (that’s why there’s
trust_remote_code=Trueeverywhere):
pip install "transformers==5.20.2" "trl==1.16.0" "peft==0.21.2" datasets accelerate- Accept the license: LFM3 uses the LFM Open License v1.0, which allows commercial use only for companies with annual revenue under $10 million. Worth reading before you start.
Step 0: check the base
Before spending any GPU time, check the model: the license, the size, the layer types and, the most important thing here, what the template does with the conversation. No weights get downloaded in this step, just the metadata, the configuration and the tokenizer:
import torch
from collections import Counter
from huggingface_hub import HfApi, get_safetensors_metadata
from transformers import AutoConfig, AutoTokenizer
BASE = "LiquidAI/LFM3-1.7B"
info = HfApi().model_info(BASE)
print("license:", info.card_data.get("license_name"))
meta = get_safetensors_metadata(BASE) # just the metadata: no weights get downloaded
print(f"parameters: {sum(meta.parameter_count.values()) / 1e9:.2f} billion")
cfg = AutoConfig.from_pretrained(BASE, trust_remote_code=True)
print("layers:", dict(Counter(cfg.layer_types)), "| context:", cfg.max_position_embeddings)
tok = AutoTokenizer.from_pretrained(BASE, trust_remote_code=True)
conversation = [{"role": "user", "content": "Qual é a capital do Ceará?"}, # in Portuguese on purpose: "What is the capital of Ceará?"
{"role": "assistant", "content": "Fortaleza"},
{"role": "user", "content": "Qual é a capital do Pará?"}] # "What is the capital of Pará?"
print(tok.apply_chat_template(conversation, add_generation_prompt=True, tokenize=False, enable_thinking=False))With LFM3-1.7B, this is what you get:
license: lfm1.0
parameters: 1.73 billion
layers: {'conv': 13, 'full_attention': 6, 'sliding_attention': 5} | context: 262144
<|startoftext|><|im_start|>user
Qual é a capital do Ceará?<|im_end|>
<|im_start|>assistant
<think></think>Fortaleza<|im_end|>
<|im_start|>user
Qual é a capital do Pará?<|im_end|>
<|im_start|>assistant
<think></think>Look at the last line: the template already closes the empty reasoning block at the end of the prompt, and also in front of the previous answer (“Fortaleza”). That pattern is what the model gets lost in.
Step 1: find the defect before training
Now the defect test, with the capitals of Brazil’s states: six states become the few-shot examples, and the other 20 become the questions. For each question, I count three things: whether the answer leaked the </think>, whether it “thought out loud” without the tag (a line break followed by reasoning) and whether it’s exactly the name of the capital, clean and correct. The sampling is the one from the model’s own generation_config (temperature 0.1, as Liquid recommends for general use):
from transformers import AutoModelForCausalLM
CAPITALS = {
"Acre": "Rio Branco", "Alagoas": "Maceió", "Amapá": "Macapá", "Amazonas": "Manaus", "Bahia": "Salvador",
"Ceará": "Fortaleza", "Espírito Santo": "Vitória", "Goiás": "Goiânia", "Maranhão": "São Luís",
"Mato Grosso": "Cuiabá", "Mato Grosso do Sul": "Campo Grande", "Minas Gerais": "Belo Horizonte",
"Pará": "Belém", "Paraíba": "João Pessoa", "Paraná": "Curitiba", "Pernambuco": "Recife", "Piauí": "Teresina",
"Rio de Janeiro": "Rio de Janeiro", "Rio Grande do Norte": "Natal", "Rio Grande do Sul": "Porto Alegre",
"Rondônia": "Porto Velho", "Roraima": "Boa Vista", "Santa Catarina": "Florianópolis",
"São Paulo": "São Paulo", "Sergipe": "Aracaju", "Tocantins": "Palmas",
}
STATES = list(CAPITALS)
SHOTS, TEST = STATES[:6], STATES[6:] # 6 for the few-shot, 20 for the test
def build_conversation(state, n_shots):
conversation = []
# the prompt stays in Portuguese: "What is the capital of {state}? Answer only with the name."
for e in SHOTS[:n_shots]:
conversation += [{"role": "user", "content": f"Qual é a capital de {e}? Responda só com o nome."},
{"role": "assistant", "content": CAPITALS[e]}]
return conversation + [{"role": "user", "content": f"Qual é a capital de {state}? Responda só com o nome."}]
def generate_answers(model, conversations, think=False, max_new_tokens=256, raw=False):
tok.padding_side = "left"
texts = [tok.apply_chat_template(c, add_generation_prompt=True, tokenize=False, enable_thinking=think)
for c in conversations]
batch = tok(texts, return_tensors="pt", padding=True, add_special_tokens=False).to(model.device)
with torch.no_grad():
output = model.generate(**batch, max_new_tokens=max_new_tokens) # sampling from the model's generation_config
return [tok.decode(s[batch["input_ids"].shape[1]:], skip_special_tokens=not raw) for s in output]
def measure(model, name):
for n in (0, 2, 6):
torch.manual_seed(0)
answers = generate_answers(model, [build_conversation(e, n) for e in TEST])
leaked = [int("</think>" in r) for r in answers]
out_loud = [int("</think>" not in r and "\n" in r.strip()) for r in answers] # thought out loud, without the tag
correct = [int(r.strip().rstrip(".") == CAPITALS[e]) for e, r in zip(TEST, answers)]
print(f"{name} | {n} examples: leaked {sum(leaked)} | thinking out loud {sum(out_loud)}"
f" | clean and correct {sum(correct)} (out of 20)")
return answers, correct
model = AutoModelForCausalLM.from_pretrained(BASE, dtype=torch.bfloat16, trust_remote_code=True).to("cuda")
answers_original, correct_original = measure(model, "original")
print(repr(answers_original[1]))
print(repr(answers_original[2]))
br = AutoModelForCausalLM.from_pretrained("fabriciocarraro/LFM3-1.7B-BR", dtype=torch.bfloat16,
trust_remote_code=True).to("cuda")
answers_br, correct_br = measure(br, "LFM3-1.7B-BR")
print(repr(answers_br[1]))
del br; torch.cuda.empty_cache()Output:
original | 0 examples: leaked 14 | thinking out loud 3 | clean and correct 1 (out of 20)
original | 2 examples: leaked 19 | thinking out loud 1 | clean and correct 0 (out of 20)
original | 6 examples: leaked 17 | thinking out loud 2 | clean and correct 0 (out of 20)
'Goiânia\nWe need to answer the question: "Qual é a capital de Goiás? Responda só com o nome." The user has been asking about capitals of Brazilian states, and we\'ve answered each with just the name.\n\nFor Goiás (Goias), the capital is Goiânia.\n\nSo I should output only "Goiânia".</think>Goiânia'
"São Luís\nThe user asks for the capital of Maranhão, and I need to respond with only the name. The correct answer is São Luís.\n\nLet me confirm: Maranhão's capital is indeed São Luís. So I will output just that.</think>São Luís"
LFM3-1.7B-BR | 0 examples: leaked 0 | thinking out loud 0 | clean and correct 17 (out of 20)
LFM3-1.7B-BR | 2 examples: leaked 0 | thinking out loud 0 | clean and correct 17 (out of 20)
LFM3-1.7B-BR | 6 examples: leaked 0 | thinking out loud 0 | clean and correct 18 (out of 20)
'Goiânia'The original leaks the tag on the vast majority of the questions, with or without examples (on a prompt this short, even the question alone sets it off), and almost never returns just the name. And look at the Goiás answer: it gets it right, thinks out loud, in English, about what it just wrote, leaks the tag and answers again. LFM3-1.7B-BR, on the same questions, never leaks once. That’s your starting point and your finish line.
Step 2: the <think> mask
Before the training, the detail that cost me the most (gotcha 1). The function below turns a conversation into the training’s input_ids and labels. The -100 in the labels is PyTorch’s way of saying “don’t compute the loss here”. The return_assistant_tokens_mask=True marks which tokens belong to the assistant (the LFM3 template already ships with that marking), and the <think> mask removes from those the <think> that opens each answer and the </think> of an empty block:
THINK, END_THINK = tok.convert_tokens_to_ids(["<think>", "</think>"])
def tokenize_chat(conversation, think_mask=True):
o = tok.apply_chat_template(conversation, tokenize=True, return_dict=True, return_assistant_tokens_mask=True)
ids, in_loss = list(o["input_ids"]), list(o["assistant_masks"]) # in_loss = 1 on the assistant's tokens
if think_mask:
for i, t in enumerate(ids):
if in_loss[i] and t == THINK: # the <think> that opens each turn leaves the loss...
in_loss[i] = 0
if i + 1 < len(ids) and ids[i + 1] == END_THINK: # ...and so does the </think> of an empty block
in_loss[i + 1] = 0
return {"input_ids": ids, "labels": [t if c else -100 for t, c in zip(ids, in_loss)]}
example = [{"role": "user", "content": "Quanto é 17 + 25? Responda só com o número."}, # "How much is 17 + 25? Answer only with the number."
{"role": "assistant", "content": "42"}]
for m in (False, True):
ex = tokenize_chat(example, m)
print("with mask: " if m else "without mask: ", "".join(
f"[{tok.decode([t])}]" if l != -100 else tok.decode([t]) for t, l in zip(ex["input_ids"], ex["labels"])))The tokens in square brackets are the ones that go into the loss:
without mask: <|startoftext|><|im_start|>user
Quanto é 17 + 25? Responda só com o número.<|im_end|>
<|im_start|>assistant
[<think>][</think>][42][<|im_end|>][
]
with mask: <|startoftext|><|im_start|>user
Quanto é 17 + 25? Responda só com o número.<|im_end|>
<|im_start|>assistant
<think></think>[42][<|im_end|>][
]Without the mask, the <think> and the </think> are in the loss, which means the model is going to train itself to write </think> right after <think>. With the mask, only the “42” and the end of turn count.
Step 3: fix it with the model’s own answers
This is where the “touch it as little as possible” principle comes in. Instead of writing the right answers by hand or asking a bigger model, I ask LFM3 itself to answer simple math problems, without reasoning, and I use a verifier (Python, which knows how to do math) to keep only the right answers. And here’s the trick: even when it leaks the tag, what comes after the last </think> is usually the clean answer. In other words, the defect itself hands you the training data.
With those answers, I put together conversations of 1 to 7 turns (the same format that triggers the leak) and train a LoRA (the “post-its” stuck onto the weights that I explained in the CatDecide post) on the layers Liquid itself recommends: the attention ones, the convolution ones (in_proj and out_proj) and the MLP ones. Notice that the training is on math problems, and the Step 1 test is on capitals. In other words, the test measures whether the model learned the format, not the task:
import random
from datasets import Dataset
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer
THINK_MASK = True # switch to False to see gotcha 1
random.seed(0)
def math_question():
a, b = random.randint(2, 99), random.randint(2, 99)
op = random.choice(["+", "-", "vezes"]) # "vezes" = "times"
answer = a + b if op == "+" else a - b if op == "-" else a * b
# in Portuguese: "How much is {a} {op} {b}? Answer only with the number."
return f"Quanto é {a} {op} {b}? Responda só com o número.", str(answer)
# 1) the model itself answers, without reasoning; we keep only what comes after the last </think>, and only if it's right
torch.manual_seed(0)
questions, pool = [math_question() for _ in range(600)], []
for i in range(0, len(questions), 100):
batch = questions[i:i + 100]
for (p, answer), r in zip(batch, generate_answers(model, [[{"role": "user", "content": p}] for p, _ in batch])):
final = r.split("</think>")[-1].strip().rstrip(".")
if final == answer:
pool.append((p, final))
print(f"correct answers: {len(pool)} of {len(questions)}")
# 2) conversations of 1 to 7 turns, like a few-shot; the loss counts on all of the assistant's turns
conversations = []
for _ in range(400):
conversation = []
for p, r in random.sample(pool, random.randint(1, 7)):
conversation += [{"role": "user", "content": p}, {"role": "assistant", "content": r}]
conversations.append(conversation)
data = Dataset.from_list([tokenize_chat(c, THINK_MASK) for c in conversations])
lora = LoraConfig(r=16, lora_alpha=32, task_type="CAUSAL_LM",
target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "in_proj", "out_proj", "w1", "w2", "w3"])
args = SFTConfig(output_dir="lora-tag", per_device_train_batch_size=8, learning_rate=2e-4, num_train_epochs=1,
lr_scheduler_type="cosine", warmup_steps=0.03, bf16=True, logging_steps=10, save_strategy="no",
report_to="none", assistant_only_loss=False, packing=False) # the labels already come ready-made
trainer = SFTTrainer(model=model, args=args, train_dataset=data, processing_class=tok, peft_config=lora)
trainer.train()
student = trainer.model
def thinks_count(model):
conversations = [[{"role": "user", "content": f"Qual é a capital de {e}?"}] for e in TEST[:10]]
torch.manual_seed(0)
raw_answers = generate_answers(model, conversations, think=True, max_new_tokens=512, raw=True)
return sum(len(r.split("</think>")[0].strip()) > 30 for r in raw_answers)
student.eval()
answers_sft, correct_sft = measure(student, "after SFT")
print([r for r in answers_sft[:4]])
print("with reasoning, it thought in", thinks_count(student), "of 10")In my test, the training took about 40 seconds (50 steps), and this is what I got:
correct answers: 412 of 600
after SFT | 0 examples: leaked 0 | thinking out loud 0 | clean and correct 13 (out of 20)
after SFT | 2 examples: leaked 0 | thinking out loud 0 | clean and correct 13 (out of 20)
after SFT | 6 examples: leaked 0 | thinking out loud 0 | clean and correct 13 (out of 20)
['Vitória', 'Goiânia', 'São Luís', 'Cuiabá']
with reasoning, it thought in 10 of 10The leak went to zero on the capitals (which the training never even saw), and reasoning mode keeps thinking. The ones that aren’t “clean and correct” are knowledge errors from a 1.7B model, not format errors.
And now gotcha 1, live. If you swap the THINK_MASK = True for False and run Step 3 again (starting from a clean model, reloading the one from Step 1), the leak goes to zero too, but look at what happens to the reasoning:
after SFT | 0 examples: leaked 0 | thinking out loud 0 | clean and correct 10 (out of 20)
after SFT | 2 examples: leaked 0 | thinking out loud 0 | clean and correct 12 (out of 20)
after SFT | 6 examples: leaked 0 | thinking out loud 0 | clean and correct 13 (out of 20)
['Vitória', 'Goiânia', 'São Luís', 'Cuiabá']
with reasoning, it thought in 0 of 10It thought in 0 of 10. And to see why, you can print two answers from reasoning mode, with the special tokens:
print(generate_answers(student, [[{"role": "user", "content": f"Qual é a capital de {e}?"}] for e in TEST[:2]],
think=True, max_new_tokens=60, raw=True))['</think>A capital do estado de Espírito Santo, na Brasil, é **Vitória**.<|im_end|>', '</think>A capital do estado de Goiás é **Belo Horizonte**.<|im_end|><|pad|><|pad|><|pad|>']The model closes the </think> as soon as it opens it, which means it stopped thinking, and on top of that it even gets Goiás’s capital wrong. One True turning into False in the code, and the whole reasoning mode goes out the window.
Step 4: on-policy distillation, with the original as the teacher
The SFT changed the model, and not only on the math problems. To measure that, I use the reverse KL to the original on requests that have nothing to do with the training (“Explique a fotossíntese em duas frases”, which is “Explain photosynthesis in two sentences”). And to bring the model back close to the original, an on-policy distillation, exactly like the one in the recipe, just at toy scale: the student (the model with the LoRA) writes, the teacher (the SAME model, with the LoRA turned off, in other words the original) reads the student’s answer, and the loss is the reverse KL token by token, with the <think> and the </think> banned for the teacher.
Before the training, the code shows what the teacher wants after “Goiânia” in a few-shot (it’s the figure from the distillation section):
BANNED = [THINK, END_THINK]
prefix = tok.apply_chat_template(build_conversation("Goiás", 6), add_generation_prompt=True, tokenize=False,
enable_thinking=False) + "Goiânia"
ids = tok(prefix, return_tensors="pt", add_special_tokens=False).to("cuda")
with torch.no_grad(), student.disable_adapter(): # without the LoRA, the model is the original: the teacher
probs = student(**ids).logits[0, -1].float().softmax(-1)
print("the teacher, after 'Goiânia':", [(tok.decode([int(i)]), round(float(v), 4)) for v, i in zip(*probs.topk(6))])
TOPICS = ["a fotossíntese", "a inflação", "o ciclo da água", "a Proclamação da República", "o efeito estufa",
"a Lei Áurea", "o que é um algoritmo", "a diferença entre vírus e bactéria", "o Pix",
"a Semana de Arte Moderna de 1922", "o que faz o Banco Central", "a erosão do solo", "a tabela periódica",
"o SUS", "a energia solar", "o segundo turno de uma eleição", "a Amazônia Legal", "o samba", "a vacina",
"o imposto de renda", "a gravidade", "o Carnaval", "a reciclagem", "o cerrado", "a Lua",
"o voto obrigatório", "a febre amarela", "o café no Brasil", "a internet", "a Copa de 1970"] # in Portuguese on purpose: "photosynthesis", "inflation", "the water cycle"...
prompts = [[{"role": "user", "content": f"Explique {t} em duas frases."}] # "Explain {topic} in two sentences."
for t in TOPICS]
prompts_train, prompts_test = prompts[:22], prompts[22:]
def reverse_kl(conversations, training):
texts = [tok.apply_chat_template(c, add_generation_prompt=True, tokenize=False, enable_thinking=False)
for c in conversations]
batch = tok(texts, return_tensors="pt", padding=True, add_special_tokens=False).to("cuda")
P = batch["input_ids"].shape[1]
with torch.no_grad(): # 1) the student writes
output = student.generate(**batch, do_sample=True, temperature=1.0, top_k=0, max_new_tokens=128)
in_loss = torch.ones_like(output[:, P:], dtype=torch.bool)
for i, row in enumerate(output[:, P:]): # nothing after the first end of turn
end = (row == tok.eos_token_id).nonzero()
if len(end):
in_loss[i, end[0, 0] + 1:] = False
attention = torch.cat([batch["attention_mask"], in_loss.long()], 1)
with torch.set_grad_enabled(training): # 2) the two distributions, on the same tokens
log_s = student(input_ids=output, attention_mask=attention).logits[:, P - 1:-1].float().log_softmax(-1)
with torch.no_grad(), student.disable_adapter():
logits_t = student(input_ids=output, attention_mask=attention).logits[:, P - 1:-1].float()
logits_t[..., BANNED] -= 30 # the teacher can't suggest <think> or </think>
log_t = logits_t.log_softmax(-1)
kl = (log_s.exp() * (log_s - log_t)).sum(-1) # 3) reverse KL, token by token
return (kl * in_loss).sum() / in_loss.sum()
def mean_kl():
student.eval()
torch.manual_seed(0)
with torch.no_grad():
return sum(float(reverse_kl(prompts_test, False)) for _ in range(3)) / 3
print(f"KL to the original, before: {mean_kl():.4f}")
random.seed(1); torch.manual_seed(1)
optimizer = torch.optim.AdamW([p for p in student.parameters() if p.requires_grad], lr=5e-5)
student.train()
for step in range(30):
loss = reverse_kl(random.sample(prompts_train, 8), True)
loss.backward()
optimizer.step(); optimizer.zero_grad()
print(f"KL to the original, after: {mean_kl():.4f}")
student.eval()
answers_opd, correct_opd = measure(student, "after distillation")
print(repr(answers_opd[0][:200]))Output:
the teacher, after 'Goiânia': [('</think>', 0.4696), ('\n', 0.4696), ('.', 0.0561), ('\n\n', 0.0032), (' (', 0.0006), ('<|im_end|>', 0.0003)]
KL to the original, before: 0.0794
KL to the original, after: 0.0081
after distillation | 0 examples: leaked 0 | thinking out loud 2 | clean and correct 10 (out of 20)
after distillation | 2 examples: leaked 0 | thinking out loud 4 | clean and correct 11 (out of 20)
after distillation | 6 examples: leaked 0 | thinking out loud 3 | clean and correct 9 (out of 20)
"Vitória\n\nWait, let me double-check: The user asked for the capital of Espírito Santo. I need to recall correctly. Actually, the capital of Espírito Santo state in Brazil is Vitória. Yes, that's correc"The KL to the original dropped almost 10 times, and the </think> didn’t come back, because it was banned for the teacher. But look at the “thinking out loud” and the “clean and correct”: after the SFT, nobody was thinking out loud, and now the student went back to doing it on 2 to 4 of the 20 questions, after the name of the capital and without the tag (“Vitória”, and right after it “Wait, let me double-check…”). That’s exactly what that figure predicted: with the </think> banned, the teacher’s probability goes to the line break, and the student learns to keep thinking. In miniature, it’s the seed of the loops I told you about in the limits, and it shows up in 30 steps.
Step 5: a verifiable reward and GRPO
Now the same fix, but through RL, starting from the original again. The reward is a verifier of just a few lines: it’s worth 1 if the answer is exactly the right number, and 0 if it’s wrong, if it leaks the tag or if it thinks out loud (because then it’s not “exactly the number”). A format defect zeroes the reward even when the math is right, like in the recipe. The prompts are math conversations with 0 to 4 previous turns, already rendered without reasoning, and TRL’s GRPO does the rest (8 answers per prompt, temperature 1.0 and no KL term):
from trl import GRPOConfig, GRPOTrainer
random.seed(2)
rows = []
for _ in range(256):
conversation = []
for p, r in [math_question() for _ in range(random.randint(0, 4))]:
conversation += [{"role": "user", "content": p}, {"role": "assistant", "content": r}]
p, answer = math_question()
conversation.append({"role": "user", "content": p})
text = tok.apply_chat_template(conversation, add_generation_prompt=True, tokenize=False, enable_thinking=False)
rows.append({"prompt": text, "answer": answer}) # the prompt goes in already rendered, without reasoning
def reward(completions, answer, **kwargs):
scores = []
for completion, expected in zip(completions, answer):
if "<think>" in completion or "</think>" in completion: # a format defect zeroes the reward, even with the right math
scores.append(0.0)
else:
scores.append(1.0 if completion.strip().rstrip(".") == expected else 0.0)
return scores
args = GRPOConfig(output_dir="grpo-tag", per_device_train_batch_size=16, num_generations=8,
max_completion_length=128, temperature=1.0, beta=0.0, learning_rate=5e-5, max_steps=40,
logging_steps=5, bf16=True, save_strategy="no", report_to="none")
new_model = AutoModelForCausalLM.from_pretrained(BASE, dtype=torch.bfloat16, trust_remote_code=True)
grpo = GRPOTrainer(model=new_model, reward_funcs=reward, args=args, train_dataset=Dataset.from_list(rows),
processing_class=tok, peft_config=lora)
grpo.train()
for h in grpo.state.log_history:
if "reward" in h:
print(f"step {h['step']:>2}: reward {h['reward']:.2f} | length {h['completions/mean_length']:.1f} tokens"
f" | zero-signal groups {h['frac_reward_zero_std']:.0%}")
grpo.model.eval()
answers_grpo, correct_grpo = measure(grpo.model, "after GRPO")
print([r for r in answers_grpo[:4]])
print("with reasoning, it thought in", thinks_count(grpo.model), "of 10")Output:
step 5: reward 0.17 | length 35.8 tokens | zero-signal groups 90%
step 10: reward 0.07 | length 19.4 tokens | zero-signal groups 80%
step 15: reward 0.76 | length 12.1 tokens | zero-signal groups 50%
step 20: reward 0.81 | length 3.9 tokens | zero-signal groups 60%
step 25: reward 0.85 | length 4.0 tokens | zero-signal groups 90%
step 30: reward 1.00 | length 2.6 tokens | zero-signal groups 100%
step 35: reward 1.00 | length 2.4 tokens | zero-signal groups 100%
step 40: reward 1.00 | length 2.5 tokens | zero-signal groups 100%
after GRPO | 0 examples: leaked 0 | thinking out loud 2 | clean and correct 11 (out of 20)
after GRPO | 2 examples: leaked 0 | thinking out loud 1 | clean and correct 10 (out of 20)
after GRPO | 6 examples: leaked 2 | thinking out loud 1 | clean and correct 11 (out of 20)
['Vitória', 'Goiânia', 'Sete Laranjeiras', 'Cuiabá']
with reasoning, it thought in 10 of 10Notice three things. The first is the “zero-signal groups” column: at the start, on 90% of the prompts the 8 answers got the same score (almost always 0), and those groups don’t teach anything, which is the reason for the filter of 1 to 7 correct answers in the real recipe. The second is that the reward goes up from 0.17 to 1.00 in 30 steps, and the answer length drops from about 36 tokens to about 2.5. Here, getting shorter is exactly right (the answer is a number), but it’s the same mechanism that, in the recipe, taught the model to get shorter where it shouldn’t have. And the third: at the end, all the groups go back to being “zero-signal”, because the model gets everything right and has nothing left to learn.
And on the capitals, which it never saw in this training? The leak almost went to zero (2 out of 20 were left with 6 examples, more history than the training prompts had), a bit of thinking out loud is left, and the reasoning is still on. The errors that remain are real knowledge errors (Maranhão got itself a brand-new capital, “Sete Laranjeiras” 😅).
Step 6: compare without fooling yourself
With 20 questions, you can celebrate anything. The paired bootstrap below draws the SAME questions for both models, 10,000 times, and returns the difference with the 95% interval. Here, I compare the “clean and correct” with 6 examples of each stage against the original:
import numpy as np
def paired_bootstrap(a, b, n=10_000, seed=0):
a, b = np.asarray(a, float), np.asarray(b, float)
rng = np.random.default_rng(seed)
idx = rng.integers(0, len(a), size=(n, len(a))) # draws the SAME items for both sides
diffs = (b[idx] - a[idx]).mean(1) * 100
return (b.mean() - a.mean()) * 100, np.percentile(diffs, [2.5, 97.5])
for name, correct in [("SFT", correct_sft), ("distillation", correct_opd), ("GRPO", correct_grpo)]:
d, (lo, hi) = paired_bootstrap(correct_original, correct)
print(f"{name} vs. the original: {d:+.1f} points [{lo:+.1f}; {hi:+.1f}]")Output:
SFT vs. the original: +65.0 points [+45.0; +85.0]
distillation vs. the original: +45.0 points [+25.0; +65.0]
GRPO vs. the original: +55.0 points [+35.0; +75.0]All three fixes beat the original, with the whole interval above zero. But look at the size of the interval: about ±20 points. With 20 questions, a 10-point difference between the SFT and the GRPO doesn’t mean anything. That’s why the real recipe’s dev sets have hundreds of items, and even so I always look at the interval before making any decision.
And that’s basically it!
Next steps
LFM3-1.7B-BR is already on Hugging Face, with the full model card!
And that’s more or less it! :) I hope I’ve shown that yes, you can fine-tune a small model, already post-trained by a big lab, for Brazilian Portuguese, without ruining what it already knew, as long as you touch as little as possible and take LOTS of measurements. And what I take away from the project is that training is the easy part. The real work is always in the data, and in knowing how to evaluate well and not let your own numbers fool you, even when they look great.
Happy studying!