Skip to content

Menu

← All articles

DistillationAgent Systems

Distilling Multi-Step Shopping Agents Into a 4B Model

A 4-billion-parameter model can learn a multi-step shopping-search loop from a larger teacher if it trains only on teacher runs that a deterministic scorer marks as solved, and only on the assistant's own turns. In our run on ShoppingBench, a 4-bit QLoRA adapter on Qwen3.5-4B, trained on verified teacher trajectories within 9.30 GiB of GPU memory, solved a held-out query that the base model failed. One query is a demonstration, not a benchmark result.

Serving a large reasoning model for every shopping session is costly, and small models out of the box tend to stop early and skip catalog checks. In our run, the base Qwen3.5-4B stopped after two steps without a valid recommendation.

Training a compact student on every raw transcript from a larger teacher model introduces a subtle failure mode: even frontier models fail on a fraction of multi-constraint queries. If the student imitates unverified rollouts, or spends gradient capacity fitting verbose catalog dumps rather than agent decisions, small-budget fine-tuning reinforces flawed tool habits.

In this post, we build an end-to-end bounded sequence-distillation pipeline for Qwen/Qwen3.5-4B on the ShoppingBench product task. We filter teacher trajectories with the benchmark's deterministic scorer, train a 4-bit QLoRA adapter with assistant-only loss masking within a strict 9.30 GiB VRAM ceiling, and compare the base model against the distilled student inside the same live ReAct catalog loop.

Solution overview

The pipeline separates offline trajectory curation from online agent evaluation. During preparation and training, the harness scores candidate teacher rollouts against catalog ground truth, keeps only verified solved traces, masks prompt tokens, and updates a 4-bit NormalFloat QLoRA adapter on Qwen/Qwen3.5-4B.

During evaluation, both the unmodified base model and the adapted student run against a held-out product query through the same local OpenAI-compatible loopback server and the native ShoppingBench ReAct loop. Toggling the LoRA adapter on a single loaded quantized model isolates the behavioral effect of the distillation updates without runtime confounding factors.

Two flows through the distillation and benchmark harness. The blue path filters 12 teacher product trajectories with the native scorer down to 8 solved traces, masks prompt tokens, and trains a 4-bit QLoRA adapter on Qwen3.5-4B within 9.3 GiB of GPU memory. The green path runs a held-out product query through an 8-step ReAct tool loop and loopback inference server, where the base model scores 0.0 and the distilled student scores 1.0. Figure 1. The blue path filters teacher trajectories and trains the QLoRA adapter. The green path evaluates base and student arms in the live tool loop.

Three core engineering invariants keep this release reliable:

  1. Zero Data Contamination: Training problems and held-out evaluation queries are verified for zero query overlap before any trajectory is read (Qtrain∩Qeval=∅\mathcal{Q}_{\text{train}} \cap \mathcal{Q}_{\text{eval}} = \emptyset).
  2. Deterministic Scorer Filtering: The native benchmark scorer evaluates candidate teacher traces on strict rubric satisfaction, in our run rejecting 4 of 12 teacher rollouts (33%) before tokenization.
  3. Live ReAct Execution: Evaluation grades actual multi-step catalog search tool calls and constraint satisfaction rather than passive next-token perplexity.

Filter teacher trajectories with the benchmark scorer

Sequence-level knowledge distillation begins with trajectories generated by a stronger teacher agent—here, published GLM-5.3 product rollouts from the pinned sequence-distillation recipe. Rather than trusting every teacher transcript unconditionally, the preparation stage runs the benchmark's native scorer (score_rollouts.py) against the local catalog index first.

The following excerpt from prepare(run) in workflow.py shows this verification gate:

python
training, held_out = load_split(SB / "data", "product")
if {row["query"] for row in training} & {row["query"] for row in held_out}:
    raise RuntimeError("The training and held-out split overlaps.")
problems = run / "train-product.jsonl"
write_jsonl(training, problems)
rollout = run / "teacher-product.jsonl"
with gzip.open(ROOT / TRACE, "rb") as source, rollout.open("wb") as dest:
    dest.writelines(islice(source, 12))
scores = run / "teacher-scores.json"
result = subprocess.run(
    [str(PYTHON), str(ROOT / "scripts/score_rollouts.py"), "--task", "product",
     "--rollouts", str(rollout), "--problems", str(problems), "--per-query", str(scores)],
    cwd=SB, env=_env(), capture_output=True, text=True, timeout=900,
)
solved = {q for q, score in json.loads(scores.read_text()).items() if score["solved"]}
return sft_rows(rollout, solved, include_reasoning=True), held_out[0], len(solved)

The split check confirms that no held-out evaluation query appears in the training pool. Next, the harness scores the first 12 teacher product trajectories. In our run, four rollouts failed either constraint coverage or tool formatting rubrics, leaving 8 solved rollouts (66.7% pass rate). The first seven of our twelve scored rollouts:

Rollout #Scorer StatusRecommendedExact Gold IDQuery Intent
0SOLVEDTrueTrueSingle-pack chili powder priced above 375
1REJECTEDTrueFalseToner from psph beauty costing over 98
2SOLVEDTrueTrueHeavy-duty stainless steel gate roller
3SOLVEDTrueTrueSilver nail remover in nail care
4SOLVEDTrueFalseKids t-shirt in color 04, size 110
5REJECTEDTrueFalseBlack ABS pipe fitting, 125mm size
6REJECTEDTrueFalseVktech motion sensor for security system

The preparation step discards the 4 failed rollouts and exports only verified trajectories for supervised fine-tuning.

Using deterministic Python logic over LLM-as-a-judge provides three critical advantages in production: it executes in milliseconds without API cost, enforces exact schema compliance against catalog databases, and eliminates evaluator drift.

Train on assistant turns within a bounded context

In our solved trajectories, user prompts and tool observations made up 73–88% of each training sequence (table below). Standard causal language modeling computes cross-entropy loss over every token in the sequence, forcing the student model to spend parameter capacity memorizing large product descriptions returned by the catalog search tool.

To focus training exclusively on agent decisions, the training step masks out all prompt and observation tokens, computing loss purely on assistant turns (reasoning traces <think>...</think> and tool invocation blocks):

L(θ)=−1∣Tassistant∣∑t∈Tassistantlog⁡Pθ(xt∣x<t)\mathcal{L}(\theta) = - \frac{1}{|\mathcal{T}_{\text{assistant}}|} \quad\sum_{t \in \mathcal{T}_{\text{assistant}}} \log P_\theta(x_t \mid x_{<t})

where every token xt∈Tprompt∪Tobservationx_t \in \mathcal{T}_{\text{prompt}} \cup \mathcal{T}_{\text{observation}} is assigned label −100-100, excluding it from backpropagation.

The token breakdown across solved trajectories illustrates why masking is indispensable:

Step #Prompt (-100 Masked)Assistant TargetTotal SequenceSupervised Decision %
Step 11,042 tokens384 tokens1,426 tokens26.9%
Step 21,038 tokens142 tokens1,180 tokens12.0%
Step 31,046 tokens218 tokens1,264 tokens17.2%
Step 41,051 tokens264 tokens1,315 tokens20.1%

In our four training examples, 73–88% of tokens are prompt or catalog output. Without masking, most of the loss would come from reproducing that text rather than from the agent's decisions.

The training step quantizes Qwen/Qwen3.5-4B into 4-bit NormalFloat weights using BitsAndBytesConfig and attaches a low-rank adapter (r=16, lora_alpha=32, targeting all linear projection layers). The training loop in workflow.py sets up assistant loss masking:

python
quantization = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_use_double_quant=True,
    bnb_4bit_compute_dtype=torch.bfloat16,
)
base = AutoModelForCausalLM.from_pretrained(
    model_name,
    quantization_config=quantization,
    device_map="auto",
    torch_dtype=torch.bfloat16,
)
model = get_peft_model(base, LoraConfig(
    r=16, lora_alpha=32,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
    lora_dropout=0.05, bias="none", task_type="CAUSAL_LM"
))
trainer = SFTTrainer(
    model=model,
    train_dataset=dataset,
    args=SFTConfig(
        dataset_text_field="text",
        max_seq_length=2048,
        per_device_train_batch_size=1,
        gradient_accumulation_steps=4,
        learning_rate=2e-4,
        warmup_steps=2,
        optim="paged_adamw_8bit",
        fp16=False,
        bf16=True,
    ),
    data_collator=DataCollatorForCompletionOnlyLM(
        response_template="<|im_start|>assistant\n",
        tokenizer=tokenizer,
    ),
)

By passing response_template="<|im_start|>assistant\n" to DataCollatorForCompletionOnlyLM, labels preceding the assistant turn are set to -100, ignoring them during backpropagation. The collator also strips duplicate leading <think> tokens so generated thoughts align cleanly with inference time.

In our run the adapter trained 1,474,560 of 2,418,622,464 parameters (0.0610%). We ran only four updates of one example each, so the step losses (0.8264, 0.8013, 0.8838, 0.9406) show no trend: this is a smoke test of the pipeline, not a converged training run. Peak allocated GPU memory was 9.30 GiB, which fits on a 24 GB GPU such as an Nvidia L4 or RTX 4090.

Evaluate base and student in the same ReAct tool loop

A low training loss does not guarantee that an agent can navigate multi-step tool loops on unseen queries. To evaluate true functional capability, evaluate(run, case, adapter) boots the local ShoppingBench catalog search service, starts an in-process OpenAI-compatible /v1/chat/completions loopback server, and executes the native react_loop on a held-out product query:

"B20 cast bronze crash cymbal hybrid ghost"

Both evaluation arms run on the identical quantized base weights in memory. For the base arm, inference runs inside model.disable_adapter(); for the student arm, the trained QLoRA adapter is active:

python
with torch.inference_mode(), (model.disable_adapter() if mode == "base" else nullcontext()):
    output = model.generate(**encoded, max_new_tokens=512, do_sample=False)
content = tokenizer.decode(output[0, length:], skip_special_tokens=True)

Trace comparison on held-out evaluation query

The contrast between the base model and the distilled student is stark when inspecting the actual multi-turn rollouts:

text
=== BASE ARM TRAJECTORY (2 steps — FAILED) ===
Step 1: [tool_call: find_product]
        <tool_call>[{"name": "find_product", "parameters": {"q": "B20 cast bronze crash cymbal hybrid ghost", "page": 1}}]</tool_call>
        Observation: [Returned 5 products with IDs and metadata]
Step 2: [hallucinated response — early termination]
        <response>Both products match your request for B20 cast bronze crash cymbals with a hybrid ghost finish: 1. Arborea Ghost...</response>
        Scorer Result: Recommend: 0.0, Exact ID: 0.0, ASR: 0.0 (FAILED)

=== DISTILLED STUDENT ARM TRAJECTORY (4 steps — SOLVED) ===
Step 1: [tool_call: find_product]
        <tool_call>[{"name": "find_product", "parameters": {"q": "B20 cast bronze crash cymbal hybrid ghost", "page": 1}}]</tool_call>
Step 2: [tool_call: view_product_information]
        <tool_call>[{"name": "view_product_information", "parameters": {"product_ids": "684368150,591486855"}}]</tool_call>
Step 3: [tool_call: recommend_product]
        <tool_call>[{"name": "recommend_product", "parameters": {"product_ids": "684368150,591486855"}}]</tool_call>
Step 4: [tool_call: terminate]
        <tool_call>[{"name": "terminate", "parameters": {"status": "success"}}]</tool_call>
        Scorer Result: Recommend: 1.0, Exact ID: 0.0, ASR: 1.0 (PASSED)

The unmodified base model terminated prematurely after 2 steps without inspecting product attributes or issuing a valid recommendation tool call (recommend: 0.0, asr: 0.0). In contrast, the distilled student ran 4 tool-loop steps, read the product details before recommending, and passed the scorer's task check (recommend: 1.0, asr: 1.0), although its recommendation was not the exact gold product (exact_id: 0.0).

Our recorded results on the one held-out query:

Evaluation armActive weightsTool loop stepsRecommendExact gold IDTask success (asr)Wall-clock time
Base Qwen3.5-4BFrozen 4-bit base20.00.00.0 (failed)174 s
Distilled student4-bit base + scored LoRA41.00.01.0 (passed)259 s

On this query the student solved a task the base model failed, using two more tool steps and about 1.5 times the wall-clock time on our GPU. A real comparison needs the full held-out set and several seeds; that is the next run.

Key takeaways for production deployments

  1. Filter teacher runs before training: A student that imitates failed teacher runs learns their shortcuts. Scoring teacher traces with the benchmark's own programmatic scorer before training keeps only runs that actually solved the task.
  2. Mask non-assistant tokens in ReAct loops: In our trajectories, prompt and observation tokens were 73–88% of each sequence. Assistant-only loss masking keeps training focused on the agent's decisions.
  3. In-process adapter toggling guarantees honest evaluation: By disabling and enabling LoRA adapters on the same loaded model weights, base and student arms can be compared under identical memory, CUDA context, and tokenization environments.
  4. Small adapters forget less: We updated 0.061% of parameters (1.47M) with QLoRA. Research comparing LoRA with full fine-tuning found that LoRA learns less but forgets less, which suits a narrow skill such as a catalog tool loop.

Try it yourself

The complete runnable companion package is published in recohut/agent-kit.

To run the pipeline locally:

bash
git clone https://github.com/recohut/agent-kit.git
cd agent-kit/examples/shopping-agent-sequence-distillation
pip install -r requirements.txt
jupyter lab main.ipynb

Follow the setup instructions in README.md to initialize the environment and pinned ShoppingBench index. The companion notebook main.ipynb executes trajectory scoring, 4-bit QLoRA training, and side-by-side base versus student evaluation, writing training.json and evaluation.json into the run directory.

Inspect teacher-scores.json after the preparation cell to see which 8 of the 12 teacher traces passed verification, then compare the rollout logs generated for base and student to observe how the distilled adapter transforms a failed 2-step search into a 4-step solved catalog recommendation.

Frequently asked questions

Why use QLoRA instead of full fine-tuning for distillation?

Full fine-tuning with Adam in mixed precision keeps about 16 bytes per parameter for weights, gradients and optimizer states (ZeRO), so a 4B model needs on the order of 64 GB before activations. In our run, 4-bit QLoRA with paged 8-bit AdamW peaked at 9.30 GiB on one GPU while training 1.47M parameters (0.061%).

Why mask tool observations out of the loss?

In agent workflows, tool outputs (search results, database queries) are dynamic environment observations, not agent reasoning. Training on observations forces the model to memorize transient product listings. Masking them out forces the model to learn policy transitions: when to search, when to view product details, and when to terminate.

Can this technique generalize to other multi-step agent tools?

Yes. The pattern of (1) deterministic rubric filtering of teacher traces, (2) prompt and observation loss masking, and (3) in-process adapter-toggled evaluation applies directly to SQL querying, API orchestrators, and technical customer support agents.

More on fine-tuning

Why Standard A/B Tests Break on AI AgentsAgent SystemsThe Inference Stack Playbook: Six Levers That Decide What Serving an LLM CostsAgent SystemsAll fine-tuning articles →

Start here

The lantern is on. Bring us the task.

Tell us where work slows down and what a good result looks like. A finished specification is not needed.