Skip to content

Add Qwen3 (4B) GRPO tool use and tool calling SFT notebooks - #395

Merged
danielhanchen merged 7 commits into
mainfrom
qwen3-tool-use-notebooks
Oct 11, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
qwen3-tool-use-notebooks

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 10, 2026 •

Copy link
Copy Markdown
Member

Two Qwen3 (4B) notebooks for agent training.

  • Qwen3_(4B)-GRPO-Tool_Use.ipynb: Qwen3-4B-Instruct-2507, fast_inference=True, LoRA, GRPOTrainer(tools=[add, subtract, multiply]) with max_tool_calling_iterations, generated word problems, rewards for the correct answer and clean tool use, and an agent loop with the trained LoRA. Named Tool_Use so update_all_notebooks.py keeps the GRPO + vLLM install cell.
  • Qwen3_(4B)-Tool_Calling.ipynb: SFT warm-up on multi-turn tool calls from NousResearch/hermes-function-calling-v1 (Apache-2.0) converted to messages + tools, qwen3-instruct template, train_on_responses_only (tool calls and replies trained, tool results masked), then an agent loop with a tool the model has not seen.

Install

The GRPO tool-use notebook gets its own install override: TRL tool calling needs trl >= 0.26 and transformers >= 5, while vllm 0.11.2 / 0.15.1 require transformers < 5. It installs transformers 5.15.1 + trl 1.13.0, vllm 0.19.1 off T4, and no vLLM on T4 (fast_inference follows whether vllm is installed; inference falls back to model.generate). The SFT notebook keeps the default install.

Colab runs (3 steps)

Tier Notebook Result
L4 GRPO tool use (vLLM 0.19.1) tools/call_frequency 2, failure 0 every step; "Answer: 36484" (correct) after training
T4 GRPO tool use (no vLLM) same: 2 calls per rollout, 0 failures, correct answer
T4 Tool calling SFT (default install) loss 0.658 -> 0.414 -> 0.306; two correct get_stock_price calls at inference

Needs unslothai/unsloth#13202 released (TRL rejects Unsloth's Qwen3 template for tools without it) and unslothai/unsloth-zoo#1650 (checkpoint save with tools). The GRPO Colab runs above installed both branches on top of the normal install.

Fixes unslothai/unsloth#3528: a tool-calling GRPO notebook with multi-turn tool use. The same Unsloth change (#13202) also makes TRL's environment_factory (the OpenEnv-style interface) work with Unsloth models and fast_inference=True.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-11T03:52:04.390658Z 643c938 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen danielhanchen self-assigned this Oct 10, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: feb5486abc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +552 to +553
"1. Teach a model to call tools with SFT first. [Tool calling SFT notebook](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_(4B)-Tool_Calling.ipynb)\n",
"2. Reinforcement learning with tools. [GRPO tool use notebook](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_(4B)-GRPO-Tool_Use.ipynb)\n",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Generate the public notebook artifacts before linking them

These links target the new notebooks under nb/, but a repo-wide tree search of this commit finds both names only under original_template/; the corresponding nb/ notebooks, python_scripts/ mirrors, and README entries were not committed. Because the templates still contain placeholder installation cells, they are not usable substitutes, and both newly advertised Colab links will return 404. Run update_all_notebooks.py --to_main_repo and commit its generated outputs.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 654bd72: ran update_all_notebooks.py (and --amd) and committed the generated nb/ notebooks, python_scripts and the four README rows for these two notebooks only.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 10, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: feb5486abc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +225 to +226
" args = SFTConfig(\n",
" dataset_text_field = \"text\",\n",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Set the intended sequence limit in SFTConfig

For conversations longer than 1,024 tokens—which is plausible here because each sample includes tool schemas, tool results, and multiple turns—this configuration silently truncates the sequence from the right: SFTConfig.max_length defaults to 1,024, and the max_seq_length = 4096 passed to FastLanguageModel.from_pretrained does not override that trainer setting. Consequently, later tool calls and final assistant replies can be omitted from training despite the notebook claiming to support 4,096-token conversations; pass the intended limit as max_length in this SFTConfig.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unsloth's SFTTrainer treats SFTConfig's default max_length as unset and uses model.max_seq_length (4096 here) instead; only an explicit max_length narrows it (unsloth/models/rl.py, _unsloth_explicit_max_length). So rows are not cut at 1024.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 10, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 654bd72b67

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

" gradient_accumulation_steps = 1, # Increase to 4 for smoother training\n",
" num_generations = 4, # Decrease if out of memory\n",
" max_completion_length = 1024,\n",
" max_tool_calling_iterations = 6, # At most 6 rounds of tool calls per rollout\n",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Install a TRL release that supports tool calling

In a fresh Colab/Kaggle run, the installation cell pins trl==0.22.2, but that release's GRPOConfig has no max_tool_calling_iterations field and GRPOTrainer.__init__ has no tools parameter. Consequently this notebook cannot construct the advertised multi-turn trainer—depending on Unsloth's compatibility wrapper, these arguments either raise TypeError or are discarded, but the tool loop is unavailable either way. Pin a TRL/Transformers combination that exposes both APIs instead.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b4034e4: this notebook gets its own install override in update_all_notebooks.py: transformers 5.15.1 + trl 1.13.0, vllm 0.19.1 off T4 (vllm 0.11.2 / 0.15.1 require transformers < 5), and no vLLM on T4 (fast_inference follows whether vllm is installed). Ran on Colab L4 (vLLM) and T4 (no vLLM): 2 tool calls per rollout, 0 failures, correct answer after training.

Comment on lines +291 to +293
" errors = sum('\"error\"' in str(message.get(\"content\", \"\")) for message in results)\n",
" score = 0.5 if results else -0.5 # Encourage calling the calculator\n",
" score -= 0.5 * errors # Penalize malformed tool calls\n",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Detect tool failures before awarding the bonus

When a compatible TRL version executes a failing or unknown tool, its tool loop stores the result as str({"error": ...}), producing content such as {'error': '...'} with single quotes (upstream implementation). Searching only for the double-quoted substring "error" therefore always misses these failures, so an invalid tool call receives the same +0.5 bonus as a successful calculator call rather than the documented penalty; inspect the parsed/result structure or match TRL's actual representation.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b4034e4: the reward now checks for both quotings, startswith(("{'error'", '{"error"')).

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b4034e4dcd

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread nb/Qwen3_(4B)-GRPO-Tool_Use.ipynb Outdated
"execution_count": null,
"metadata": {},
"outputs": [],
"source": "#@title Colab Extra Install { display-mode: \"form\" }\n%%capture\nimport os\n!pip install --upgrade -qqq uv\nif \"COLAB_\" not in \"\".join(os.environ.keys()):\n # If you're not in Colab, just use pip install!\n !pip install unsloth vllm\nelse:\n try: import numpy, PIL; _numpy = f'numpy=={numpy.__version__}'; _pil = f'pillow=={PIL.__version__}'\n except: _numpy = \"numpy\"; _pil = \"pillow\"\n try: import subprocess; is_t4 = \"Tesla T4\" in str(subprocess.check_output([\"nvidia-smi\"]))\n except: is_t4 = False\n _triton = 'triton'\n if is_t4:\n # Keep the machine's torch: upgrading it can pull a CUDA build the driver cannot load\n try:\n import importlib.metadata as _md\n _torch, _tv = (f'{_p}=={_md.version(_p).split(\"+\")[0]}' for _p in ('torch', 'torchvision'))\n except Exception:\n _torch, _tv = 'torch', 'torchvision'\n !uv pip install -qqq {_numpy} {_pil} {_torch} {_tv} bitsandbytes xformers unsloth\n else:\n !uv pip install -qqq --upgrade vllm==0.19.1 {_numpy} {_pil} torchvision bitsandbytes xformers unsloth\n !uv pip install -qqq {_triton}\n try:\n import importlib.metadata as _md; _torch_v = tuple(int(_p) for _p in _md.version(\"torch\").split(\"+\")[0].split(\".\")[:2])\n except Exception:\n _torch_v = ()\n # torchao 0.18.0 imports torch.nn.functional.ScalingType, added in torch 2.10; peft >= 0.19 needs the 0.16.0 floor.\n _torchao = \"torchao>=0.16.0\" if _torch_v >= (2, 10) else \"torchao>=0.16.0,<0.18.0\"\n !uv pip install -qqq --no-deps --upgrade \"{_torchao}\"\n!uv pip install transformers==5.15.1 \"datasets>=4.7.0,<5.0.0\"\n!uv pip install --no-deps trl==1.13.0"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Install the Unsloth fixes used by the successful runs

On a fresh Colab or Kaggle run, this cell installs only the published unsloth/unsloth_zoo packages, but the commit notes that its successful GRPO runs manually overlaid unsloth#13202 and unsloth-zoo#1650 and that both fixes are still required. Without the first fix, GRPOTrainer(..., tools=...) rejects the Qwen3 template during construction; without the second, the configured checkpoint save at step 100 fails. Pin/install those fixes in the generated installation cell, or wait until releases containing them are available before advertising the notebook as runnable.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, this is a merge-order dependency rather than something to pin into the install cell (the cells install released packages). Marked as draft until an Unsloth release ships unslothai/unsloth#13202 and unslothai/unsloth-zoo#1650; the description lists both.

@danielhanchen
danielhanchen marked this pull request as ready for review October 11, 2026 03:49
@danielhanchen
danielhanchen merged commit 0313a67 into main Oct 11, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for security reviews. Please try again later.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 643c938ffb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread update_all_notebooks.py
Comment on lines +851 to +854
installation_amd_extras_grpo_tool_use = installation_amd_extras_grpo + """\
!uv pip install --system -qqq vllm "transformers==5.15.1" "datasets>=4.7.0,<5.0.0"
!uv pip install --system -qqq --no-deps "trl==1.13.0"
"""

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Apply the required Unsloth fixes to AMD installs

When the generated AMD GRPO notebook is run, its base cell installs the released unsloth[amd] and unsloth_zoo[amd], while this AMD-specific override upgrades only vLLM, Transformers, and TRL. The new TOOL_USE_UNSLOTH_MAIN overlay—explicitly required for the TRL chat-template fallback and tokenizer checkpoint-save fix—is applied only by _tool_use_installation, so the AMD notebook still uses packages that fail during trainer construction or checkpoint saving. Append equivalent main-branch AMD installs here before advertising the generated AMD artifact as runnable.

Useful? React with 👍 / 👎.

Penguinjanator pushed a commit to Penguinjanator/notebooks that referenced this pull request Oct 16, 2026
…nslothai#402)

unsloth==2026.10.5 carries everything the forced-reinstall cell existed for
(unslothai/unsloth#11440, unsloth-zoo#1310, the reentrant pin, and the chunked
JSD wiring from unslothai/unsloth#12136), checked against the installed wheel
rather than the tags, so the cell now only drags users off a release onto main.

Removing it exposes a hole: the shared install says a bare `pip install unsloth`,
which pip treats as satisfied by ANY installed version. Measured: with 2026.9.7
present, `pip install unsloth` left 2026.9.7 in place, and that release has no
chunked loss. Both install variants now pass --upgrade with a minimum, Kaggle's
included, and the notebook checks the capability before training.

The check probes RL_FUNCTIONS["gkd_trainer"] rather than a version, because
replace_common rewrites every YYYY.M.D literal in a cell to 2026.2.1, which 2026.9.7
satisfies; a version assert shipped defanged. It imports unsloth before
unsloth_zoo, which refuses to import until UNSLOTH_IS_PRESENT is set. And it runs
after the config and UNSLOTH_COMPILE_DISABLE cells, because
unsloth_zoo/temporary_patches/common.py:43 freezes that flag at import, so an
earlier unsloth import silently lost the gemma-4 workaround.

The memory claim is also no longer true. Measured at the settings this notebook
ships, with UNSLOTH_GKD_CHUNKED=0 as the dense control:

  dense    9.94 GiB peak, loss 0.375788, 49.3 s
  chunked  3.03 GiB peak, loss 0.375766, 63.5 s

3.3x off the peak for the same loss to 2.2e-05, at about 30% more time at batch 1;
level at batch 2, and faster on gemma-4 at batch 2 (11.1 s vs 14.8 s) while
dropping 51.34 GiB to 23.63 GiB. The qwen3 table row is re-measured on a free
single Colab T4 (loss 0.367, 392/392 adapters, 3.36 GB, verified from the executed
notebook) and the table says which rows predate the chunked loss.

Rebased onto current main: the earlier branch was 25 commits behind and would have
reverted four workflow files Dependabot had updated, which is also why only CodeQL
ran on it. molab was removed from the repo meanwhile (unslothai#394), so that artefact is
gone rather than regenerated.

Verified: gemma-4 frozen compile-disable True, the guard raises AssertionError on
2026.9.7 with UNSLOTH_IS_PRESENT unset, and the notebook runs end to end at loss
0.370, 392/392 adapters, 3.28 GB. The suite's 18 failures are on the Qwen3 (4B)
tool-use notebooks from unslothai#395 and reproduce unchanged on clean main.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Openenv with tool calling notebook unsloth ?

1 participant