← All writing

Reinforcement Learning worklog - 2

I wanna see it! Show me your data

Well in the previous worklog we saw how our Qwen 1.5B parameter LM was performing on the puzzle task that we generated. It scored ~10% on pass@1 and ~38% on pass@8. Before we jump into RL a basic question we can ask to ourselves is that

what if we showed our LM some examples of the puzzles so that it learns how to solve them and test it on other unseen examples?

That is what Supervised Fine-Tuning is all about. Now we will feed the model with (puzzle, solution) and train it with Cross-Entropy Loss - which is kinda standard when it comes to next token prediction and then measure pass@1 and pass@8.

Basic googling about SFT - where to use it and where not to use it revealed this:

What SFT Is Good For

• Consistent formatting and tone: Teaching a model to follow strict schemas, specific structures, or a distinct brand voice. • Nuanced or repetitive tasks: Handling classification, extraction, or decision logic that is hard to capture with simple prompt rules alone. • Pushing accuracy on narrow workflows: Squeezing out extra reliability or lower latency on a well-defined task, sometimes allowing you to use a smaller, cheaper model. • Domain terminology and edge cases: Helping models handle specialized jargon or uncommon scenarios shown in your examples.

Where Not to Use SFT

• Frequently changing or searchable facts: Use retrieval-augmented generation (RAG) or tool calls instead of baking live or rapidly updating knowledge into model weights. • Problems solvable by prompting or model choice: Start with clear instructions, examples in the prompt, or a stronger base model before training. • Noisy, scarce, or unverified data: Bad or inconsistent examples can degrade output quality or cause overfitting

Source : www.google.com/ai-mode-thingy

In the previous worklog we saw that we had to specifically make sure that Qwen did not generate invalid characters like \frac or markdown headers. So SFT here will be really helpful in making sure that the output is generated in the format we desire. But at the same time SFT can make the model memorize the one right path to get to the answer rather than making it capable enough to explore all paths. So it can make the model prioritze memorization over search.

Trying out SFT

The first cell of the day 2 section of our colab notebook does the basic imports :

  • Installs SFT tools: trl for SFT training, peft for adding LoRA adapters (wtf is this now) and datasets for loading the JSON into training dataset
  • Made sure that none of the test puzzles get leaked into training
  • Generated 150 synthetic CoT examples (75 easy and 75 medium) recording each intermediate step before Answer: <>.
  • Saves sft_train_150.json which stores each example in chat messages format (user puzzle + assistant step by step solution).

What is LoRA

Gemini Generated Image 11xgm811xgm811xg

A basic Google search pulls up a definition from huggingface and it defines LoRA as :

LoRA is a fine-tuning technique that adapts large AI models (such as large language models or image generators) to new tasks or styles without retraining all of their weights.

So instead of training the entire model, you keep its weights frozen and train small low rank adapter matrices alongside them. The key benefits include:

  • far less memory needed in comparison to full fine tuning
  • far less compute needed in comparison to full fine tuning
  • produces small adapter files
  • no extra latency added when adapters are merged with the model

Lets dig a bit deep into the math behind it

Lets take our current Qwen 1.5B parameter model. For Qwen2.5-1.5B-Instruct in float16 :

  • Weights: ~3 GB
  • Gradients: ~3 GB
  • AdamW optimizer states: ~12 GB
  • Activations and KV cache: ~4-6 GB

Do the math, in total we need ~22-24 GB of VRAM and that's a lot.

A pre-trained LLM already has a lot of knowledge. It knows about language, how to do arithmetic operations and logical things. We want our current model to be good at a specific task - Countdown formatting for instance - thus we are not teaching it everything from scratch. We are just changing its behaviour for a few specific directions. The people behind LoRA found that during such fine tuning, the weight update ΔW\Delta W has a low intrinsic rank. So instead of updating the entire weight matrix, which is very huge, they completely froze the weights and added a tiny trainable side branch to it.

In a normal linear layer the input xx of size dd is multiplied by the weight matrix W,size(d×dW , size( d \times d)

y=Wxy = W {x}

When full fine-tuning happens, we are basically updating the entire weight matrix of the same size.

y=(W+ΔW)xy = (W + \Delta W)x

For our Qwen 1.5B parameter model, d=1536d = 1536 1536×1536=2,359,2961536 \times 1536 = \mathbf{2,359,296}

Lets do some math to understand LoRA in a bit more detail

Setup : We need to shrink the model to d=4,r=1d = 4, r = 1 Imagine a tiny layer with dimension equal to 4 instead of 1536, rank equal to 1 and α=2\alpha = 2, so that αr=21=2\frac{\alpha}{r} = \frac{2}{1} = 2

  • Input:x=[1234]Input:x = \begin{bmatrix} 1 \\ 2 \\ 3 \\ 4 \end{bmatrix}
  • Forzen base weight: W=[1000020000100002]W = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 2 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 2 \end{bmatrix} Wx=[1438]W x = \begin{bmatrix} 1 \\ 4 \\ 3 \\ 8 \end{bmatrix}
  • Trainable params: Full ΔW\Delta W 4×4=164 \times 4 = 16. LoRA needs AA (1×41 \times 4) + BB (4×14 \times 1) = 4+4=84 + 4 = \mathbf{8}

Step 0 : Before Training (B = 0)

  • A=[10−11]A = \begin{bmatrix} 1 & 0 & -1 & 1 \end{bmatrix}
  • B=[0000]B = \begin{bmatrix} 0 \\ 0 \\ 0 \\ 0 \end{bmatrix}
  1. Compress (AxA x): 1(1)+0(2)+(−1)(3)+1(4)=21(1) + 0(2) + (-1)(3) + 1(4) = \mathbf{2}
  2. Expand (B(Ax)B (A x)): [0000]⋅2=[0000]\begin{bmatrix} 0 \\ 0 \\ 0 \\ 0 \end{bmatrix} \cdot 2 = \begin{bmatrix} 0 \\ 0 \\ 0 \\ 0 \end{bmatrix}
  3. Output: y=Wx+2[0000]=Wxy = W x + 2 \begin{bmatrix} 0 \\ 0 \\ 0 \\ 0 \end{bmatrix} = W x

As we can see since B is initialized with 0 right now, the final output remains unchanged - no affect of LoRA. The base model is 100% the same it previously was.

After training, B learns a nudge, it gets updated. Suppose after training B gets update to [120−1]\begin{bmatrix} 1 \\ 2 \\ 0 \\ -1 \end{bmatrix}

Repeat the above steps once again - compress with A, expand with B and calculate the output y

  1. Since A and x are same, the output of compress step will still be 2
  2. Expand (B(Ax)B (A x)):
[120−1]⋅2=[240−2]\begin{bmatrix} 1 \\ 2 \\ 0 \\ -1 \end{bmatrix} \cdot 2 = \begin{bmatrix} 2 \\ 4 \\ 0 \\ -2 \end{bmatrix}
  1. Scale by αr=2\frac{\alpha}{r} = 2 :
2⋅[240−2]=[480−4]2 \cdot \begin{bmatrix} 2 \\ 4 \\ 0 \\ -2 \end{bmatrix} = \begin{bmatrix} 4 \\ 8 \\ 0 \\ -4 \end{bmatrix}
  1. Add to frozen Wx\text{Wx}:
y=[1438]+[480−4]=[51234]y = \begin{bmatrix} 1 \\ 4 \\ 3 \\ 8 \end{bmatrix} + \begin{bmatrix} 4 \\ 8 \\ 0 \\ -4 \end{bmatrix} = \begin{bmatrix} 5 \\ 12 \\ 3 \\ 4 \end{bmatrix}

Notice what happened, we were able to control a 4-dim output using a 1-number bottleneck ( r = 1).

Now once training finishes, WW, AA BB αr\frac{\alpha}{r} are constants, none of them depend on the input token xx.

Once training is done just do the following :

  • Multiply BB d×rd \times r by AA r×dr \times d --> produces d×dd \times d matrix
  • Scale it by αr\frac{\alpha}{r} and add it element-by-element to WW d×dd \times d
  • Save the single matrix as WmergedW_{\text{merged}} and delete AA and BB

So in very plain english if you want to summarize how LoRA fine-tuning happens, the below will help you understand it and make you remember it for the rest of your life

Let delta W (change in weights) be represented by a 4 x 4 matrix, this means that in order for us to do full fine-tuning we need to change/adjust all the 16 numbers that are present. What LoRA suggests that instead of changing all 16, we take two small matrices of a very low rank (r<<<d, let r=1 in this example). Rank of a matrix is the number of independent rows/columns that are present in a matrix. So delta W will be represented by BA where B is a 41 matrix while A is a 1*4 matrix. In a formal sense A->rd and B->dr and the total number of trainable parameters will be the total numbers present in B and A which are (rd + d*r) = 2dr, here in our example d=4 and r=1, so trainable parameters in LoRA fine-tuning becomes 8. So we have compressed our process of training 16 numbers in the ΔW\Delta W update matrix to just 8 numbers in LoRA fine-tuning.

Now coming back to our notebook experimentation, we were doing SFT using LoRA on our puzzle dataset. These are some of the configs that I had set for LoRA and SFTTrainer:

  • r=16
  • alpha=32
  • dropout=0.05
  • training epochs = 3
  • fp16 set to True

The results after SFT on evaluating on 50 test puzzles

  • pass@1=4.0% : dropped from 10%
  • pass@8=32.0% : dropped from 38%
  • format error dropped completely
  • the average response length also collapsed to just 58 characters.

Gemini Generated Image v8uziyv8uziyv8uz

Going in a bit of detail to understand what happened during SFT (Neon'ed this thing):

  1. The Cross-Entropy Trap

SFT trains the model with CE loss: given the prompt and the tokens that have been generated so far, predict the next exact token of the reference answer. CE never checks if the difference or summation between 2 numbers is actually the number that is the output.

  • It never checks if 27-3 = 14
  • It never checks if 1 was in [6,5,3]
  • The only thing it is concerned about is to ask : Does my output look like the sft_train_150.json

To illustrate the above using one of the responses generated by the model:

input = [6, 5, 3] target = 14

Answer : ((6 * 5) - 3)) - which completely wrong since 27 != 14. But to SFT the output format + Answer: ((...)) look identical to the training set that we had provided to it - so the loss keeps on going down even while the accuracy goes down.

  1. Collapse to very less output characters

In our first worklog we saw the model rambling 400-500 characters per response. Although most of that was bs but it enabled the model to explore more paths and possibilites. The model frequently caught itself ("Oops, I made a mistake, let me try another approach") and backtracked to a winning path.

From observing the outputs of the test set it is pretty clear that SFT made the model learn a fatal rule :

"Never write more than 2–3 lines (~58 chars), never doubt yourself, and immediately commit to Answer:."

When 6 * 5 = 30 overshot 14, the SFT model had no budget left to backtrack. It either forced 30 - 3 = 14 or hallucinated a fake number (27 + 1 = 28). That explains 189 wrong_value and 123 wrong_numbers out of 400 tries.

  1. What SFT did fix tho

We can't say that SFT was 100% useless. It actually did improve the way the format of the answer was structured.

  • The format_error dropped to 0 - every single completion had a clean Answer : line.
  • The invalid characters like \frac{....} that Qwen was generating a lot in our previous worklog dropped to just 2 out of the 400 tries that the model took.

So by the above we can easily conclude that :

  • SFT taught the model to generate the response in a proper fromat and strucutre and using valid characters only.
  • The pass@1 and pass@8 dropped since the fine-tning didn't care about the logic and the steps that the model took to reach the results. It was just concerned about making the structure and the format of the response as similar as the one present in its training set.