Qwen3-1.7B-Distillation-Coding

Qwen3-1.7B distilled on-policy from Qwen3-8B as a coding agent, with TRL's DistillationTrainer and environment_factory.

The student solves MBPP problems in a live Python session from OpenEnv's coding environment. It has one tool, run_python(code), and the session keeps what it defines between calls, so over several turns it writes the function, runs it, reads the error, fixes it and tests it again. The teacher scores every token the student wrote, with the whole episode so far as context, interpreter output included.

On the 500 problems of the MBPP test split, it passes 51.4% of the test cases, up from 43.6% for the base model. The teacher passes 68.2%.

How it was trained

On-policy distillation trains the student on the teacher's per-token distribution over the student's own samples. Here a sample is a whole episode:

  1. Each episode gets its own CodingSession instance, created by environment_factory. reset() opens a fresh Python session, and the class's public method run_python becomes the student's tool.
  2. The student generates a turn, calls the tool, gets the interpreter's output, and goes on. The episode ends when the student answers without calling the tool, after 6 tool calls, or when the episode reaches 4096 tokens.
  3. The teacher is run on the exact tokens of the episode. The loss compares the two distributions on the tokens the student wrote. The tool results are context only and are masked out of the loss. In this run they were about 79% of the episode's tokens, mostly tracebacks.
  4. Distillation needs no reward. CodingSession.get_reward() runs the MBPP tests in the session the student leaves behind, and its value is only logged, never trained on.
Setting Value
Training data MBPP full train split (374 problems)
Steps 100 (about 9 passes over the problems)
Episodes per step 32 (8 per device x 4 gradient accumulation steps)
Learning rate 1e-5, linear decay
max_completion_length 4096, the budget for the whole episode (every model turn plus every tool result)
max_tool_calling_iterations 6
Thinking Off (enable_thinking=False)
Hardware 1x A100 80GB, student, teacher and vLLM colocated, about 80 minutes

Over training, the distillation loss went from 0.169 (steps 1-10) to 0.100 (steps 91-100), and the logged share of MBPP train tests passed from 0.55 to 0.62. The curves and the logged episodes are on Trackio.

Evaluation

The 500 problems of the MBPP full test split, with the training prompt, tool, turn limit and episode budget. Temperature 0.7, top-p 0.8, top-k 20, two episodes per problem with different seeds. "Test cases passed" is the share of MBPP's test cases that pass in the session the model leaves behind, "Problems solved" the share of problems where all of them pass.

Model Test cases passed (seed 0, seed 1) Problems solved (seed 0, seed 1) Tool calls per episode
Qwen3-1.7B 43.6% (42.9, 44.3) 36.7% (36.2, 37.2) 3.0
Qwen3-1.7B-Distillation-Coding 51.4% (50.9, 51.9) 44.3% (44.0, 44.6) 2.2
Qwen3-8B (teacher) 68.2% (68.1, 68.3) 61.0% (60.6, 61.4) 1.8

The student closes about a third of the gap to the teacher, on problems it never trained on. One teacher episode per seed lost its connection to the environment server and counts as failed.

Reproduce

The training script, the evaluation script and a README are in the TRL example examples/distillation_coding_env, added in huggingface/trl#8453. On Hugging Face Jobs:

hf jobs uv run --flavor a100-large --timeout 2h --secrets HF_TOKEN \
    examples/distillation_coding_env/distillation_coding_env.py --push-to-hub

hf jobs uv run --flavor a100-large --timeout 90m \
    examples/distillation_coding_env/evaluate.py --model <you>/Qwen3-1.7B-Distillation-Coding

The scripts start the coding environment server locally, in its own process and without the tokens of the main process, since it runs code written by the model.

Use it

The model expects the training setup: the run_python tool in the chat template, thinking off, and an interpreter that answers its tool calls. The evaluation script above runs that loop. To look at a first turn:

from transformers import AutoModelForCausalLM, AutoTokenizer


def run_python(code: str) -> str:
    """
    Run Python code in the session and return its output.

    Args:
        code: The Python code to run.

    Returns:
        The standard output and standard error of the code.
    """


model_id = "sergiopaniego/Qwen3-1.7B-Distillation-Coding"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="auto", device_map="auto")

prompt = """Write a Python function for the task below. Use the `run_python` tool to define the function and to test \
it: the session keeps what you define between calls. When the function works, reply with a one-line summary.

Task: Write a function to find the minimum of two numbers.
Your function must pass this test:
assert minimum(1,2) == 1"""
inputs = tokenizer.apply_chat_template(
    [{"role": "user", "content": prompt}],
    tools=[run_python],
    enable_thinking=False,
    add_generation_prompt=True,
    return_tensors="pt",
    return_dict=True,
).to(model.device)
output = model.generate(**inputs, max_new_tokens=512, do_sample=True, temperature=0.7, top_p=0.8, top_k=20)
print(tokenizer.decode(output[0][inputs["input_ids"].shape[1] :]))

Intended use and limitations

This is an example model, to show on-policy distillation of a tool-using agent in an environment. It was trained and evaluated on one benchmark only: short, MBPP-style Python functions, written and tested with a Python interpreter. It is not a general coding assistant, and the run is short (100 steps on 374 problems). Its scores outside MBPP, and without the tool loop it was trained with, were not measured. Code it writes should be run in a sandbox, as the environment server does here.

Framework versions

  • TRL: 1.19.0.dev0
  • Transformers: 5.23.0
  • Pytorch: 2.13.0
  • Datasets: 5.2.0
  • Tokenizers: 0.23.3

Citations

Cite Distillation as:

@inproceedings{agarwal2024on-policy,
    title        = {{On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes}},
    author       = {Rishabh Agarwal and Nino Vieillard and Yongchao Zhou and Piotr Stanczyk and Sabela Ramos Garea and Matthieu Geist and Olivier Bachem},
    year         = 2024,
    booktitle    = {The Twelfth International Conference on Learning Representations, {ICLR} 2024, Vienna, Austria, May 7-11, 2024},
    publisher    = {OpenReview.net},
    url          = {https://openreview.net/forum?id=3zKtaqxLhW},
}

Cite TRL as:

@software{vonwerra2020trl,
  title   = {{TRL: Transformers Reinforcement Learning}},
  author  = {von Werra, Leandro and Belkada, Younes and Tunstall, Lewis and Beeching, Edward and Thrush, Tristan and Lambert, Nathan and Huang, Shengyi and Rasul, Kashif and Gallouรฉdec, Quentin and Dirhoussi, Amine and Villanova del Moral, Albert and Paniego Blanco, Sergio},
  license = {Apache-2.0},
  url     = {https://github.com/huggingface/trl},
  year    = {2020}
}
Downloads last month
332
Safetensors
Model size
2B params
Tensor type
BF16
ยท
Inference Providers NEW
This model isn't deployed by any Inference Provider. ๐Ÿ™‹ Ask for provider support

Model tree for sergiopaniego/Qwen3-1.7B-Distillation-Coding

Finetuned
Qwen/Qwen3-1.7B
Finetuned
(1,445)
this model

Dataset used to train sergiopaniego/Qwen3-1.7B-Distillation-Coding