保留正文与补采附件。源页面当前未重新核验;具体限制见交付清单。
We value your privacy
We use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking "Accept All", you consent to our use of cookies.
Customise Reject All Accept All
Customise Consent Preferences
We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.
The cookies that are categorised as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more
NecessaryAlways Active
Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.
Cookie BCTempID
Duration 10 minutes
Description No description available.
Cookie __cf_bm
Duration 1 hour
Description This cookie, set by Cloudflare, is used to support Cloudflare Bot Management.
Cookie AWSALBCORS
Duration 7 days
Description Amazon Web Services set this cookie for load balancing.
Cookie _cfuvid
Duration session
Description Cloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services
Cookie li_gc
Duration 6 months
Description Linkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.
Cookie __hssrc
Duration session
Description This cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.
Cookie __hssc
Duration 1 hour
Description HubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.
Cookie wpEmojiSettingsSupports
Duration session
Description WordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.
Cookie BCSessionID
Duration 1 year 1 month 4 days
Description Blueconic sets this cookie as a unique identifier for the BlueConic profile.
Cookie _octo
Duration 1 year
Description No description available.
Cookie logged_in
Duration 1 year
Description No description available.
Cookie __Secure-YEC
Duration past
Description YouTube sets this cookie to stores the user's video player preferences using embedded YouTube video
Cookie __eoi
Duration 6 months
Description Description is currently not available.
Cookie AWSALBTGCORS
Duration 7 days
Description No description available.
Cookie login-status-p
Duration past
Description Description is currently not available.
Cookie AWSALBTG
Duration 7 days
Description No description available.
Cookie csrf_token
Duration session
Description No description available.
Cookie token_v2
Duration 1 day
Description Description is currently not available.
Cookie D
Duration 1 year
Description Description is currently not available.
Cookie PHPSESSID
Duration session
Description This cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.
Cookie VISITOR_PRIVACY_METADATA
Duration 6 months
Description YouTube sets this cookie to store the user's cookie consent state for the current domain.
Cookie cookietest
Duration session
Description The cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.
Cookie __Host-airtable-session
Duration 1 year
Description This cookie is used to enable us to integrate the services of Airtable.
Cookie __Host-airtable-session.sig
Duration 1 year
Description This cookie is used to enable us to integrate the services of Airtable.
Cookie m
Duration 1 year 1 month 4 days
Description Stripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.
Cookie BIGipServer*
Duration session
Description Marketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user.
Cookie __cfruid
Duration session
Description Cloudflare sets this cookie to identify trusted web traffic.
Cookie _GRECAPTCHA
Duration 6 months
Description Google Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.
Cookie __Secure-YNID
Duration 6 months
Description Google cookie used to protect user security and prevent fraud, especially during the login process.
Cookie cookieyes-consent
Duration 1 year
Description CookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.
Functional Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.
Cookie lidc
Duration 1 day
Description LinkedIn sets the lidc cookie to facilitate data center selection.
Cookie brw
Duration 1 year
Description No description available.
Cookie brwConsent
Duration 5 minutes
Description Description is currently not available.
Cookie WMF-Uniq
Duration 1 year
Description Description is currently not available.
Cookie loom_anon_comment
Duration 1 year
Description No description available.
Cookie loom_referral_video
Duration session
Description Description is currently not available.
Cookie VISITOR_INFO1_LIVE
Duration 6 months
Description A cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.
Cookie yt-remote-connected-devices
Duration Never Expires
Description YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.
Cookie ytidb::LAST_RESULT_ENTRY_KEY
Duration Never Expires
Description The cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.
Cookie yt-remote-device-id
Duration Never Expires
Description YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.
Cookie yt-remote-session-name
Duration session
Description The yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.
Cookie yt-remote-fast-check-period
Duration session
Description The yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.
Cookie yt-remote-session-app
Duration session
Description The yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.
Cookie yt-remote-cast-available
Duration session
Description The yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.
Cookie yt-remote-cast-installed
Duration session
Description The yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.
Cookie cp_session
Duration 3 months
Description Codepen sets this cookie for Help systems found in the website.
Cookie loid
Duration 1 year 1 month 4 days
Description This cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.
Analytics Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.
Cookie __hstc
Duration 6 months
Description Hubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).
Cookie hubspotutk
Duration 6 months
Description HubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.
Cookie _ga
Duration 1 year 1 month 4 days
Description Google Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.
Cookie ga*
Duration 1 year 1 month 4 days
Description Google Analytics sets this cookie to store and count page views.
Cookie __Host-psifi.analyticsTrace
Duration 6 hours
Description Description is currently not available.
Cookie __Host-psifi.analyticsTraceV2
Duration 6 hours
Description Description is currently not available.
Cookie _gh_sess
Duration session
Description GitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.
Cookie YSC
Duration session
Description YSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.
Cookie ajs_anonymous_id
Duration 1 year
Description This cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.
Cookie vuid
Duration 1 year 1 month 4 days
Description Vimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website.
Performance Performance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Cookie AWSALB
Duration 7 days
Description AWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.
Cookie acq
Duration past
Description Description is currently not available.
Cookie acq.sig
Duration past
Description Description is currently not available.
Cookie ptc
Duration 2 years
Description No description available.
Advertisement Advertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.
Cookie muc_ads
Duration 1 year 1 month 4 days
Description Twitter sets this cookie to collect user behaviour and interaction data to optimize the website.
Cookie guest_id_marketing
Duration 1 year 1 month 4 days
Description Twitter sets this cookie to identify and track the website visitor.
Cookie guest_id_ads
Duration 1 year 1 month 4 days
Description Twitter sets this cookie to identify and track the website visitor.
Cookie personalization_id
Duration 1 year 1 month 4 days
Description Twitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.
Cookie guest_id
Duration 1 year 1 month 4 days
Description Twitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.
Cookie bcookie
Duration 1 year
Description LinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.
Cookie __Secure-ROLLOUT_TOKEN
Duration 6 months
Description YouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.
Cookie yt.innertube::nextId
Duration Never Expires
Description YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.
Cookie yt.innertube::requests
Duration Never Expires
Description YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.
Cookie session_tracker
Duration session
Description This cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.
Cookie edgebucket
Duration session
Description Reddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.
Cookie did
Duration 1 year
Description Arbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.
Uncategorised Other uncategorised cookies are those that are being analysed and have not been classified into a category as yet. No cookies to display. Reject All Save My Preferences Accept All Toggle SearchToggle Mobile Navigation Publish AI, ML & data-science insights to a global community of data professionals. Sign inSubmit an Article LatestEditor's PicksNewsletterShipAI
Write For TDS LinkedInXToggle Search Large Language Models
A visual tour and from-scratch guide to train GRPO reasoning models in PyTorch
Avishek Biswas
July 8, 202520 min read
Reasoning models are currently in fashion. DeepSeek-R1, Gemini-2.5-Pro, OpenAI's O-series models, Anthropic's Claude, Magistral, and Qwen3 — there is a new one every month. When you ask these models a question, they go into a chain of thought before generating an answer.
A simple demonstration of what reasoning looks like. When asked a question, the Language Model (LM) generates a chain of thought first, followed by the answer. (Illustration by the Author)
I recently asked myself the question, "Hmm... I wonder if I should write a Reinforcement Learning loop from scratch that teaches this 'thinking' behaviour to really small models — like only 135 million parameters ". It should be easy, right?
Well, it wasn't.
**Small models simply do not have the world knowledge that large models do. This makes < 1B parameter model lack the "common sense" to easily reason through complex logical tasks. Therefore, you cannot just rely on compute to train them to reason. **
You need additional tricks up your sleeve. In this article, I won't just cover tricks though. I will cover the major ideas behind training reasoning behaviours into language models, share some simple code snippets, and some practical tips to fine-tune Small Language Models (SLMs) with RL. Learn this step by step with the interactive AI Engineer roadmap. This article is divided into 5 sections:
Unless otherwise mentioned, all images used in this article are illustrations produced by the author. At the end of this article, I will link to the 50-minute companion YouTube video of this article. If you have any queries, that video likely has the answers/clarification you need. You can also reach out to me on X (@neural_avb ).
Before diving into specific challenges with Small models, let's first introduce some terms. Group Relative Policy Optimization, or GRPO, is a (rather new) Reinforcement Learning (RL) technique that researchers are using to fine-tune Large Language Models (LLMs) on logical and analytical tasks. Since its inception, a new term has been circulating in the LLM research space: RLVR , or R einforcement L earning with V erifiable R ewards. To understand what makes RLVR unique, it's helpful to contrast it with the most common application of RL in language models: RLHF (R einforcement L earning with H uman F eedback). In RLHF, an RL module is trained to maximize scores from a separate reward model, which acts as a proxy for human preferences. This reward model is trained on a dataset where humans have ranked or rated different model responses.
In other words, RLHF is trained so LLMs can output responses that are more aligned with human preferences. It tries to make models follow instructions more closely. RLVR tries to solve a different problem. RLVR teaches a model to be verifiably correct, often by learning to generate it's own chain of thought. Where RLHF had a subjective reward model, RLVR uses an objective verifier. The core idea is to provide rewards based on whether an answer is demonstrably correct, not on a prediction of what a human might prefer.
An illustration of how RLVR works (Illustrated by the Author) This is exactly why this system is called 'RL with verifiable rewards '. Not every question's answer can be verified easily. Especially open-ended questions like "What iPhone should I buy? " or "Where should I go to college?". Some use cases, however, do fit easily in the "verifiable rewards" paradigm, like math, logical tasks, and code-writing, to name a few. In the
reasoning-gymsection below, we will look into how exactly these tasks can be simulated and how the rewards can be generated. But before that, you might ask: well where does "reasoning" fit into all of this? We will train the LLM to generate arbitrarily long chain of thought reasoning texts before generating the final answer. We instruct the model to wrap its thinking process in<think>tags and its final conclusion in<answer>tags. The full language model response will look something like this: markup
<think>User has asked me to count the number of r's in strawberry.Let's do a cumulative count.s=0, t=0, r=1, a=0, w=0, b=0, e=0, r=2, r=3, y=4It seems there are 3 r's in strawberry. I notice that there is an r in straw and 2 r's in berry.Since 1+2=3 I am more confident there are 3 r's</think><answer>3</answer>
This structure allows us to easily extract just the final answer and check if it's correct. The verifier is a single source of truth, and can be a simple piece of code that (literally) counts alphabets. python
def count_alphabets(word, letter):
return sum([1 for l in word if l == letter])
reward = 1 if (lm_answer == count_alphabets("strawberry", "r") else -1
We will keep a record of the model's experiences — its responses and the corresponding rewards received from the verifier. The RL algorithm will then train to promote behaviours that increase the likelihood of correct final answers.
By consistently rewarding correct answers and good formatting, we would increase the likelihood of reasoning tokens that lead to correct answers. Get this: we don't needto directly evaluate the intermediate reasoning tokens. By simply rewarding the final answer, we will indirectly elicit reasoning steps into the LLM's chain of thought that lead to correct answers!
Source: Some exercepts from the DeepSeek-R1 paper (License: Free)
I am going to skip the usual Reinforcement Learning 101 intro here, I expect most of you who read this far to understand the basics of RL. There is an agent who observes states from the environment and takes an action — the environment rewards the agent depending on how good the action was — the agent stores these experiences and trains to take better actions in the future that lead to higher rewards. RL 101 class dismissed. But how do we transfer the RL paradigm to language? Let's talk about our algorithm of choice — G roup R elative P olicy O ptimization to understand how. GRPO works in two iteratively self-repeating phases — an experience collection phase where the Language Model (LM) accumulates experiences in the environment with its current weights. And a training phase where it uses the collected memories to update its weights to improve. After training, it once again goes into an experience collection step with the updated weights.
Let's dissect each step in the experience collection phase now.
Step 1: The environment is a black box that generates questions about logical or math tasks. We will discuss this in an upcoming section with the reasoning-gym library.
Step 2: We tokenize the input questions into a sequence of integer tokens.
Sample questions, tokenized them, forward pass through LM, and generate multiple responses for each question! (Illustrated by the Author)
The Environment acts as the verifier and assigns a reward to the agent. (Illustrated by the Author)
Advantages define how favourable a specific response is relative to other responses to the same question
(Illustrated by the Author)
Saving experiences in the buffer! (Illustrated by the Author)
After the end of the experience collection phase, our goal is to enter the training phase. Here, we will learn from the reward patterns the LLM observed and use RL to improve its weights. Here is how that works:
GRPO operates in 2 repeating phases — collect experiences, train on experiences, repeat. (Illustrated by the Author)
Let me explain the PPO Loss in an intuitive step-by-step fashion. The PPO Loss looks like this.
The PPO Loss Function. Let me break it down for you. (Illustration by the Author)
Here, pi_old is the old-policy neural network that we used during the data collection phase.
π is the current policy neural network we are training. Since the weights of π change after each gradient update, π and π_old do not remain the same during the training phase — hence the distinction.
G is the number of generated responses for a single question. |o_i| is the length of the i-th response in the group. Therefore, those summation and normalization operation computes a mean over all the tokens over all responses. What does it compute the mean of? Well it is π/π_old * A_{it}. What does that mean?
The simplest way to assign an advantage to each token is by copying the advantage of the entire response (Illustrated by the Author)
A_it is the advantage of the t-th token in the i-th response. Remember when we calculated the advantage of each response in Step 5 during experience collection? The easiest way to assign an advantage to each token is by simply duplicating the same advantage to each token — this means we are saying that every token is equally responsible for generating the correct answer.
Lastly, what is π(o_it | q, o_i < t)? It means what is the probability of the t-th token in the i-th response? Meaning, how likely was that token when it was generated?
The importance sampling ratio reweights the advantages between the current updating policy and the old exploration policy.
The clipping term ensures that the updates to the network do not become too large and the weights do not move too far away from the old policy. This adds more stability to the training process by keeping the model updates close to "a trust region" from the data-collection policy.
The PPO objective broken down into individual components. (Illustrated by the Author)
When we are maximizing the PPO objective, we are effectively asking the LLM to increasethe log-probability of the tokens that led to a high advantage, while decreasingthe log-probability of tokens that had a low advantage. In other words: make tokens that generate good advantages more likely and tokens that generate low advantages less likely.
Let's forget about the clipping term and the π_old for now, and let's just see what maximizing 𝜋(𝑜_i) * A_i means. To remind you, this part of the equation simply means, "the product of the probability of the i-th token (o_i) and the advantage of the i-th token (A_i)
Let's say for a question, the LLM generated these two sequences: "A B C" and "D E F", and it got an advantage of +1 for the former and -1 for the latter*. Let's say we have the log probabilities for each of the 3 tokens as shown below.
A_it by the current logprobs pi. Now really think about what it means to maximize the mean of that product matrix.
A toy example to show what it means to maximize the product of the probability of a token with it's advantage (Illustrated by the Author)
Remember we can only change the probabilities coming out of the LLM. The advantages come from the environment and are therefore treated as constants. Increasing this expected score would therefore mean increasing the probability of tokens with a positive advantage, and decreasing the value of the negative advantage example.
To increase the mean of the product tensor, we must increase each value in the tensor, so we must increase the probs of positive advantage-tokens, and decrease the probs of negative-advantage tokens.
A comparison of how RL fine-tuning affects log-probs of tokens after training (Illustration by the Author)
In the next section, let's take a look at the reasoning-gym library and understand how we could sample tasks.So, to do RL, we first need tasks. A common way to do this is by using an existing dataset of math problems, like the GSM-8K dataset. In this article, let's look at a different case — generating tasks procedurally with a Python library called reasoning-gym.
For my experiments, I used two tasks: syllogism and propositional logic. reasoning-gym contains a host of different repositories of varying difficulty.
A syllogism task is a type of logical puzzle designed to test deductive reasoning. Basically, we will provide the LLM with two premises and ask if the conclusion is correct or not. The propositional logic task is a symbolic reasoning task where the LLM is provided tasks with symbols and asked to generate the conclusion. Unlike syllogism, this is not a YES/NO classification response — they have to generate the correct conclusion directly. This makes this task considerably harder.
Example of the Syllogism Task (Footage of my RL-trained model)
Before we begin coding, I guess it is customary to specify what I mean by "small" models.
The jury is still out on what qualifies as a "small" model (some say <14B, some say <7B), but for my YouTube video, I picked even smaller models: SmolLM-135M-Instruct, SmolLM-360M-Instruct, and Qwen3-0.6B. These are ~135M, ~360M, and ~600M models, respectively.
Let's see how to set up the basic training loop. First, we can use Huggingface's transformers library to load in a model we want to train, let's say the little 135M param model SmolLM-135M-Instruct.
To generate some propositional logic tasks, for example, you just call this reasoning_gym.create_dataset function as shown below.
python
import re
from reasoning_gym import create_dataset, get_score_answer_fn
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
model_name = "HuggingfaceTB/SmolLM-135M-Instruct"
# load model from huggingface
lm = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.bfloat16)
tokenizer = AutoTokenizer.from_pretrained(model_name)
# This sets all models as trainable
for param in lm.parameters():
param.requires_grad = True
# In my experiments, I used a LORA adapter (more on this later)
# specify name of the env
environment_name = "propositional_logic"
# In practice, you should wrap this with a torch dataloader
# to sample a minibatch of questions
dataset = create_dataset(
environment_name, seed=42, size=DATA_SIZE
)
for d in dataset:
question = d["question"] # Accessing the question
# We will use this later to verify if answer is correct
validation_object = d["metadata"]["source_dataset"]
score_fn = get_score_answer_fn(validation_object)
To generate reasoning data, we want the LM to generate thinking, followed by the response. Below is the system prompt we will be using. python
system_prompt = """A conversation between User and Assistant. The user asks a question, and the Assistant solves it.
The assistant first thinks about the reasoning process in the mind and then provides the user
with the answer. The reasoning process and answer are enclosed within <think> </think> and
<answer> </answer> tags, respectively, i.e., <think> reasoning process here </think>
<answer> answer here </answer>.
Do not generate new code. Do not write python code.
You may also be given examples by the user telling you the expected response format.
Follow the format of the examples, but solve the specific problem asked by the user, not the examples.
Very important - Remember again, your output format should be:
<think> reasoning process here </think>
<answer> answer here </answer>
Your response will be scored by extracting the substring between the <answer>...</answer> tags.
It is critical to follow the above format.
feature_extraction_utilsling to follow the response format will result in a penalty.
"""
To generate answers, we first tokenize the system prompt and the question as shown below. python
# Create messages structure
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": question}, # Obtained from reasoning-gym
]
# Create tokenized representation
inputs = tokenizer.apply_chat_template(
messages,
tokenize=True,
return_tensors="pt",
add_generation_prompt=True
)
Then we pass it through the LM — generate multiple responses using the num_return_sequences parameter, and detokenize it back to get a string response. No gradients are calculated during this stage.
python
generated_response = lm.generate(
input_ids=inputs["input_ids"],
attention_mask=inputs["attention_mask"],
max_new_tokens=max_new_tokens, # The max number of tokens to generate
do_sample=True, # Probabilistic sampling
top_p=0.95, # Nucleus sampling
num_return_sequences=G, # Number of sequences per question
temperature=1, # Increase randomness
eos_token_id=eos_token_id,
pad_token_id=eos_token_id,
)
We also write the extract_answer function, which uses regular expressions to extract answers between the answer tags.
python
def extract_answer(response):
answer = re.search(r"<answer>(.*?)</answer>", response, re.DOTALL)
if answer is not None:
return answer.group(1).strip()
else:
return ""
Finally, we use the score function we got previously to generate a reward depending on whether the LM's response was correct. To calculate rewards, we add a format reward and a correction reward. The correction reward comes from the environment, and the format reward is awarded if the model correctly generates the <think> ... </think> and <answer> ... </answer> tags.
The advantages are calculated by standardizing across each group.
python
# Response is an array of string of length [B*G]
# B is the number of questions, G is the number of responses per question
correctness_reward = score_fn(response, validation_object)
format_reward = calculate_format_reward(response)
# Total reward is a weighted sum of correctness and formatting rewards
reward = correctness_reward * 0.85 + format_reward * 0.15
# Convert rewards from [B*G, 1] -> [B, G]
rewards = rewards.reshape(B, G)
# Calculate advantages
advantages = (rewards - np.mean(rewards, axis=1, keepdims=True)) / (
np.std(rewards, axis=1, keepdims=True) + 1e-8
)
advantages = advantages.reshape(-1, 1)
Store the (old) log probs, advantages, responses, and response masks in a memory buffer. python
# A function that returns the log prob of each selected token
log_probs = calculate_log_probs(lm, generated_response)
buffer.extend([{
"full_response": generated_response[i],
"response_mask": response_mask[i], # A binary mask to denote which tokens in generated response are AI generated, 0 for system prompt and questions
"old_log_probs": log_probs[i],
"advantages": advantages[i]
} for i in range(len(generated_response))])
After multiple experience collection step, once the buffer is full, we initiate our training loop. Here, we sample minibatches from our experience, calculate the log probs, compute loss, and backdrop. python
# full_response, response_mask, old_log_probs, advantages <--- Buffer
# Recompute the new log_probs. Notice no torch.no_grad(), so gradients WILL BE USED here.
logits = llm(input_ids=full_response).logits
# Extract log probs from the logits
# Does log_softmax over the vocabulary and extracts the log-prob of each selected token
log_probs = calculate_log_probs(
logits,
full_responses
)
# Calculate the clipped surrogate loss
reasoning_loss = calculate_ppo_loss(
log_probs, # Trainable
old_log_probs, # Obtained from exploration, not trainable
advantages, # Obtained from environment, not trainable
response_mask # Obtained from exploration, not trainable
)
# Optimizaiton steps
accelerator.backward(reasoning_loss)
optimizer.step()
optimizer.zero_grad()
You can use additional entropy losses here, or minimize KLD with your reference model as suggested in the original Deepseek-R1 paper, but future papers have concluded that these leash the training process and not a requirement.
Technically, we can try to run a big RL training right now and hope that the small models can pull through and conquer our tasks. However, the probability of that is incredibly low.
There is one big problem — our small models are not appropriately trained to generate formatted outputs or perform well on these tasks. Off the box, their responses do have some logical flow to them, thanks to the pretraining or instruction tuning from their original developers, but they are not good enough for our target task.
Comparing the outputs of a small model with a Large LM (Illustration by Author)
Think about it — RL trains by collecting experiences and updating the policy to maximize the good experiences. But if most of the experiences are completely bad and the model receives 0 rewards, it has no way to optimize, because it gets no signal to improve at all. So the recommended approach is to first teach the model the behavior you want to train using supervised fine-tuning. Here is a simple script:
python
client = openai.AsyncClient()
ENVIRONMENT = "propositional_logic"
model = "gpt-4.1-mini"
semaphore = asyncio.Semaphore(50)
num_datapoints = 200
system_prompt = (
system_prompt
+ """You will also be provided the real answer. Your thinking should eventually result in producing the real answer."""
)
dataloader = create_dataset(name=ENVIRONMENT, size=num_datapoints)
@backoff.on_exception(backoff.expo, openai.RateLimitError)
async def generate_response(item):
async with semaphore:
messages = [
{"role": "system", "content": system_prompt},
{
"role": "user",
"content": f"""
Question: {item['question']}
Metadata: {item['metadata']}
Answer: {item['answer']}
""",
},
]
response = await client.chat.completions.create(messages=messages, model=model)
return {
"question": item["question"],
"metadata": item["metadata"],
"answer": item["answer"],
"response": response.choices[0].message.content,
}
async def main():
responses = await asyncio.gather(*[generate_response(item) for item in dataloader])
fname = f"responses_{ENVIRONMENT}_{model}.json"
json.dump(responses, open(fname, "w"), indent=4)
print(f"Saved responses to {fname}")
if __name__ == "__main__":
asyncio.run(main())
To generate the fine-tuning dataset, I first generated the thinking and answer tags with a small LLM-like GPT-4.1-mini. Doing this is incredibly simple — we sample 200 or so examples for each task, call the OpenAI API to generate a response, and save it on disk. During SFT, we load the base model we want to train, attach a trainable LORA adapter ,and do parameter-efficient fine-tuning. Here are the LORA configurations I used. python
lora:
r: 32
lora_alpha: 64
lora_dropout: 0
target_modules: ["q_proj", "v_proj", "k_proj", "o_proj",
"up_proj", "down_proj", "gate_proj"]
LORA allows the training process to be more memory efficient and also reduces the risk of corrupting the original model. You can find the details of parameter-efficient supervised fine-tuning in my YouTube video right here. Please accept cookies to access this content I trained a LORA adapter on 200 examples of syllogism data with the smallest language model I could find — the HuggingfaceTB/SmolLM-135M-Instruct, and it got us an accuracy of 46%. Roughly, this means that we generate a correct answer 46% of the time. More importantly, we often get the formatting right, so our regex can safely extract answers from the responses more often than not.
temperature, top_p, and num_return_sequences parameters in the generate().Here is my YouTube video that explains everything in this blog post more pictorially and provides a hands-on tutorial on how to code such a thing.
Please accept cookies to access this content
On the supervised-fine-tuned SmolLM-135M on the syllogism task, we got a bump to 60%! You can see the reward curve here — the healthy standard deviation of the rewards shows that we were indeed getting diverse responses throughout, which is a healthy thing if we want to train with RL.
Rewards curve of the Syllogism task on SmolLM-135M after SFT (Illustration by Author)
Here is a set of hyperparameters that worked well for me.
yaml
config:
name: "path/to/sft_model"
max_new_tokens: 300 # reasoning + answer token budget
exploration_batchsize: 8 # number of questions per batch during rollout
G: 6 # num responses per group
temperature: 0.7
batch_size: 16 # minibatch size during training
gradient_accumulation_steps: 12
learning_rate: 0.000001 # Advisable to keep this low, like 1e-6 or 1e-7
top_p: 0.95
buffer_size: 500
I also repeated this experiment with larger models — the SmolLM-360M-Instruct and the Qwen3-0.6B model. In the latter, I was able to get accuracies up to 81% which is awesome! We got a 20% additive bump on average in the syllogism task!
In the propositional logic task, which in my opinion is a harder reasoning task, I also saw similar gains across all small models! I am sure that with more instruction tuning and RL fine-tuning, possibly on multiple tasks at once, we can raise the intelligence of these models a lot higher. Training on a single task can generate quick results which is what I wanted for this Youtube video, but it can also act as a bottleneck for the model's overall intelligence.
Let's end this article with a GIF of the small models outputting reasoning data and solving tasks. Enjoy, and stay magnificent!
SmolLM-135M after training on Propositional Logic Tasks (Source: Author)
Author's YouTube channel : https://www.youtube.com/@avb_fj
Author's Patreon : www.patreon.com/NeuralBreakdownwithAVB
Author's Twitter (X) account : https://x.com/neural_avb
Deepseek Math: https://arxiv.org/pdf/2402.03300
DeepSeek R1: https://arxiv.org/abs/2501.12948
DAPO: https://arxiv.org/abs/2503.14476
Critical Perspectives on R1: https://arxiv.org/abs/2503.20783
Reasoning Gym Library: github.com/open-thought/reasoning-gym
A good place to read about Reasoning: https://github.com/willccbb/verifiers
A great place to study code: https://github.com/huggingface/trl/blob/main/trl/trainer/grpo_trainer.py
All articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more. Register for freeSign in to your account
Written By
See all from Avishek Biswas Deep DivesDeep LearningHuggingfacePytorchReinforcement Learning Share This Article
Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program. Write for TDS
Large Language Models It's both fast and cost-effective Thuwarakesh Murallie September 4, 20247 min read
Deep Learning Train your models with GPU instances on the AWS cloud. NVS Yashwanth October 1, 202010 min read
Deep Learning A method developed at Intel and Johns Hopkins to improve LSTM performance Michael Berk August 11, 20218 min read
Reinforcement Learning Build a Custom 3D Environment for Reinforcement Learning Mauro Di Pietro November 13, 202514 min read
Large Language Models How to build a usage-reinforced memory decay engine for AI agent memory that outperforms naive recency-window pruning on long-running, multi-session tasks — with a deterministic, zero-dependency Python implementation you can verify yourself. Emmimal P Alexander July 24, 202621 min read
Machine Learning Why 1-shot RLVR might be the breakthrough we've been waiting for Derrick Mwiti April 30, 20254 min read
Large Language Models A fast and effective approach to generating fluent sentences from given keywords using public pre-trained models. Sergey Vilov July 19, 20249 min read
Deep Learning Pragmatism versus (over-)planning Pascal Janetzky January 3, 20253 min read
Deep Learning Is the quest of the perfect activation function accessible? Kevin Berlemont, PhD September 22, 20227 min read
Your home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals. Subscribe to Our NewsletterWrite For TDS•About•Advertise•Privacy Policy•Terms of Use © Insight Media Group, LLC 2026•The New Stack•roadmap.sh•Creator Network
Close