Reinforcement Learning Worklog - 1
What is RL
Reinforcement learning (RL) is a machine learning method where an agent learns to make sequential decisions by interacting with an environment through trial and error, earning rewards or penalties to maximize total long-term reward
So basically you have an agent (in the context of language models - it is an LLM) and it gives some output, and depending upon the reward that it gets from the environment (some other function that keeps a check on it), it learns whether it should produce the same tokens it did for the given output or suppress the production of the same.
If you google about it (yeah same old googling about stuff and learning from it), you will come across these 4 terms:
- Agent (or Policy) - this is the LLM itself, which outputs a probability distribution over possible next tokens
- State - the input prompt along with all the tokens the LM has generated so far
- Action - choosing and outputting the next token
- Reward - a numerical value given to the generated response based on helpfulness, accuracy, or safety

Since we have the gist of the topic, let's dive into a small puzzle (ik this came out of nowhere, but trust me, this is the best way to learn about RL).
Let's take 4 random numbers and a random target that we need to achieve by combining them using these math operators - (+, -, *, /) and making sure that the intermediate results are clean integers. Also, you can use the numbers only once.
An easy example to understand will be reducing the count of numbers to just 3 (e.g., 2, 4, 6) and target = 16. The solution is very easy to calculate:
Now increasing the count to our actual puzzle count, if we have 4 numbers and target = 24, let's try out multiple ways and see if we are able to get to the required target using these numbers:
- Try A: - not equal to the target
- Try B: - hits target, but
8is not in the numbers list - Try C: - the numbers are valid and it also hits the target
Now why is the above puzzle a really good example to learn about RL?
To understand RL myself, I made sure that I picked a problem that a beginner like me can also understand and learn from. The problem doesn't require you to have great math skills. You can easily grade the answer as correct or wrong - the numbers should be in the list and the target should be hit by the math operations - that's it. Also, the answer is unambiguously true - it's either correct (reward = +1) or wrong (reward = 0) - there is no need for the answer to go through a vibe check or be in alignment with a particular preference.
Building the 50 puzzle dataset
I Neon'ed a little bit about how to generate the dataset for this mini project and this was the conclusion I arrived at:
Instead of guessing random targets (which might be impossible), we generate solution-first:
Sample 3 numbers (for 25 easy puzzles) or 4 numbers (for 25 medium puzzles) from 1..9.
Randomly combine them with +, -, *, / (only allowing / when it divides cleanly with no remainder).
Record the final integer result as target (filtering out target <= 0 or target > 100 and duplicates).
Store each puzzle as:
{
"id": 1,
"difficulty": "medium",
"numbers": [2, 3, 5, 7],
"target": 24,
"reference_solution": "(5 - 2) * 7 + 3"
}This guarantees 100% of the 50 puzzles are solvable.
Ok for now we know the puzzle and the dataset that we are trying to build here. Let's clear up some terms first that we will encounter later in our worklog.
pass@1: Fraction of the puzzles that were solved on the very first try by the modelpass@8: Fraction of puzzles solved in at least 1 of the 8 tries.
Another thing that you might be thinking is how we will score the output given by the model. Well, for that we will code a simple verify function in Python that will take the puzzle and the completion as input and give a bool (whether the output given by the model was correct or not) and a str (the reason for the answer) as the output.
Also, we will prompt the model 8 times for each puzzle (keeping the temperature set to 0.7 so that it is able to explore different reasoning paths to come to an answer) and then run the above verify function on all 8 completions and compute pass@1 and pass@8.
I used Colab notebooks for this mini project and Qwen/Qwen2.5-1.5B-Instruct as the LM.
So what we are doing here is loading the model using Hugging Face (transformers) and running 8 passes on the same prompt. Colab Notebook. Also, another thing that I came across was not to do the inference 8 times in a loop, as it will be very slow. By this I mean that a naive approach to get 8 responses for the same prompt from the model would be to use a code block like this:
outputs = []
for _ in range(8):
output = model.generate(
input_ids,
max_new_tokens=100
)
outputs.append(output)The above is sequential execution. Generation 1 happens in the first pass, followed by generation 2 in the second, and so on until the final generation and pass occur. The execution looks something like this:
- Python calls
model.generate() - GPU does the inference
- The sequence is returned
- Python receives the results
- Python again calls
model.generate() - This is repeated 8 times
The better approach is to use the batched approach: num_return_sequences=8
Instead of the above, we write:
outputs = model.generate(
input_ids,
max_new_tokens=100,
num_return_sequences=8
)Basically, now the GPU will receive a batch dimension of 8 - so instead of performing 8 separate forward passes in a loop, the GPU processes all 8 sequences together in a single batched pass, saving a lot of time.
So I ran the code cells and also did a sanity check on the first prompt to see how the results are going to look:

Understanding the model's response
The numbers were just 3 - so it was an easy problem and the answer was very easy to get - - and yet the model failed to get it right.
Even though we clearly prompted the model to think briefly, it directly jumped to Answer:. On observing Try 1 to Try 5 and Try 7, you can clearly see that the model is not doing any intermediate steps and tries to guess the equation in a single shot. Also, in Try 2 you can clearly see it wrote , when in fact it is 23 - the model is hallucinating.
By this, it's very clear that the model is skipping directly to the answer, so I made some tweaks to the prompt first to see if giving a better prompt to the model improved its thinking and accuracy or not.
Minor prompt tweaks
The new prompt that was used (v2) to make sure that the model doesn't jump straight to the answer, and instead tries out different paths instead of blind guessing:
def format_prompt(puzzle):
nums_str = ", ".join(map(str, puzzle["numbers"]))
user_msg = (
f"Solve this Countdown puzzle using ONLY the numbers [{nums_str}] "
f"(each at most once) and +, -, *, / to reach {puzzle['target']}.\n"
f"Show your step-by-step calculations first and double-check your arithmetic.\n"
f"Then, on the very last line, write ONLY: Answer: <expression>\n"
f"(Use standard * and /, no LaTeX, and do NOT include '= {puzzle['target']}' after the expression.)"
)
messages = [{"role": "user", "content": user_msg}]
return tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
)Also, I increased max_new_tokens to 300 so that the model has more space to show its intermediate steps.
It was run on the same puzzle[0] as a sanity check and the results are in my Colab notebook. Some interesting observations are as follows:
- v2 actually tried taking different paths to reach the answer instead of blind guessing
- It wrote long markdown headers, which exhausted the 300-token budget
- Neon'ed a little bit about it and learned that a 1.5B-parameter model has a strong bias toward multiplying the numbers (based on the results we got) rather than simply trying out adding the individual numbers first
- Qwen also has a
\boxed{.....}habit, where it ignoredAnswer:and used its SFT-trained LaTeX habit: .
Final fixes to the prompt before final run
max_new_tokensset to 450_extract_expressionupdated to also catch\boxed{...}as a fallback ifAnswer:is missing
Building the referee: the verify() function
At the start of the worklog we came across 4 terms:
- Agent -> the LLM itself
- State -> the prompt + generated tokens
- Action -> each generated token is the action of the agent (LLM)
- Reward -> this comes from the environment
In our mini experiment, verify() is the environment - no human, no second neural network doing a check, just a strict, deterministic 5-gate funnel to make sure that only if the response passes through all 5 gates will it earn a +1 reward. If it doesn't, we not only give it a reward of 0, but also return why it failed. Giving out the reason is important because it tells you what to fix:
- If the model fails at Gate 1 ->
format_error, our prompt or parser is broken and needs fixing - If the model fails at Gate 4 ->
wrong_numbers, the model is cheating or hallucinating - If the model fails at Gate 5 ->
wrong_value, the model gets the rules, it just used bad math to get to the final target number
Breaking down each gate
- Gate 1: Extraction
The model writes a bunch of reasoning text, and somewhere at the end it puts the final expression.
We search for all
Answer: ...lines and take the last one (matches[-1]).If
Answer:is missing, we fall back to\boxed{...}because Qwen loves its LaTeX habit.Then we normalize the string: strip
\(\)$, convert\times→*,\div→/, and drop anything after=(so6 + 5 + 3 = 14becomes just6 + 5 + 3).Gate 2: Character Whitelist
Before we ever try to evaluate the extracted string as math, we check: re.fullmatch(r"[0-9+\-*/().\s]+", expr). Why? Two reasons:
Safety: Never pass raw LLM text into Python's
eval().Clarity: If the model wrote words like
"Answer: cannot be solved", this catches it cleanly asinvalid_charsinstead of crashing.Gate 3: Safe Math Parsing
Instead of eval(), we use Python's ast (Abstract Syntax Tree) module. ast.parse("((6 - 5) * 3)", mode="eval") turns the string into a tiny tree of pure math operations (Add, Sub, Mult, Div, Constant).
We walk the tree recursively and compute the value.
If the model wrote broken parentheses like
(6 + 5or divided by zero(6 / (3 - 3)), this gate catches it and labels itsyntax_error.Gate 4: The Inventory Check (
Counter)
This is the rule-enforcement gate: did the model only use the numbers we gave it, and each at most once?
Why can't we just use a Python set? Suppose puzzle["numbers"] = [6, 5, 3] and the model outputs 6 + 6 + 2.
- A
setcheck wouldn't notice that6was used twice. - Instead, I use
collections.Counter(a multiset), which counts how many times each number appears:
used_counts = Counter(used_nums) # {6: 2, 2: 1}
allowed_counts = Counter(puzzle["numbers"]) # {6: 1, 5: 1, 3: 1}If used_counts - allowed_counts is non-empty, the model either invented a number (2) or reused a number too many times (6). Gate 4 immediately rejects it with wrong_numbers.
- Gate 5: Target Equality
Finally, we check if the computed value equals puzzle["target"]. We use abs(value - puzzle["target"]) > 1e-6 instead of == because division in Python produces floats (e.g., 6 / 3 = 2.0, or (1 / 3) * 3 can have tiny floating-point rounding noise).
- If it misses, return
(False, "wrong_value: got 22, expected 14"). - If it hits, return
(True, "correct")→ Reward = +1
Measuring the gap: run_diagnostic(puzzles) function
Once the verify() function is ready, we use run_diagnostic(puzzles) to answer one important question:
Does the 1.5B-parameter model already have the ability to solve the Countdown puzzle? Is the knowledge already present inside its weights?
So what actually happens inside run_diagnostic:
Sample 8 paths per puzzle For each of the 50 puzzles, we call
generate_k_passes(..., k=8, temperature=0.7, max_new_tokens=450). That gives us50 × 8 = 400completions total, wheretemperature=0.7forces the model to explore 8 slightly different reasoning paths per puzzle.Grade every path We pass all 8 completions through
verify(puzzle, completion). Each puzzle now has a list of 8(passed, reason)pairs—for example:[False, False, False, False, True, False, False, False].Compute the Two Key Metrics (
pass@1vs.pass@8)
From those 8 boolean flags per puzzle, we compute:
pass@1 (Try #1 only): Didpassed_flags[0]equalTrue? Averaged across 50 puzzles, this tells us how often the model gets it right on its very first shot.pass@1 (Avg of 8 tries):sum(passed_flags) / 8, averaged across 50 puzzles. Because Try #1 alone can be noisy with only 50 puzzles, averaging across all 8 tries gives a smoother estimate of single-attempt accuracy.pass@8: Didany(passed_flags)equalTrue? This tells us what fraction of puzzles the model can solve at least once when given 8 shots.
After Neon'ing a little bit I came across this:
The difference
pass@8 - pass@1is the "RLVR Juice" for our mini experiment:
- If
pass@1 = 20%andpass@8 = 60%, there is a+40%gap of capability already sitting inside the model that RLVR can surface.- If
pass@8 = 0%, RLVR has nothing to reinforce—you've hit the wall and need SFT (or a stronger model) first.
- Count Failure Reasons Across All 400 Completions
We tally the tag before the : in every reason string (correct, wrong_value, wrong_numbers, format_error, syntax_error). This gives us a crystal-clear X-ray of the model's weaknesses.
- Auto-Extract the 3 "RLVR Juice" Examples
Finally, we filter results with one line:
not r["attempts"][0]["passed"] and any(a["passed"] for a in r["attempts"][1:])The above will pull the exact puzzles where Try #1 failed (False), yet a later try succeeded (True).
The results we got
The Numbers (Qwen2.5-1.5B-Instruct, k=8, temp=0.7):
pass@1(Try #1 only): 6/50 (12%) (5/50 = 10% after removing a verifier edge-case bug on Puzzle #43)- Easy puzzles: 4/25 (16%)
- Medium puzzles: 2/25 (8%) (1/25 = 4% without Puzzle #43)
pass@8(Any of 8 tries): 20/50 (40%) (19/50 = 38% without Puzzle #43)- Easy puzzles: 11/25 (44%)
- Medium puzzles: 9/25 (36%) (8/25 = 32% without Puzzle #43)
The RLVR juice we talked about above (Neon talked about it tbh) - (pass@8 - pass@1) = +28 percentage points
What this proves:
Qwen2.5-1.5B-Instructis not at the 0% wall. It already knows how to solve ~38% of these Countdown puzzles; it just only hits ~10% on Try #1. That 28-point gap is the exact room RLVR has to promote winning reasoning paths up to Try #1.