{ "cells": [ { "cell_type": "markdown", "id": "1d06b16b", "metadata": {}, "source": [ "# Gemma 4 E4B-it — function-calling SFT (LoRA + full fine-tuning)\n", "\n", "This notebook fine-tunes `unsloth/gemma-4-E4B-it` on WMS agent trajectories (multi-turn conversations with tool calls).\n", "It targets **Azure `Standard_NC40ads_H100_v5`** (1× H100 NVL 94 GB, 320 GB RAM, 128 GB OS disk) and **32k–64k context**.\n", "\n", "The training mode is selected by a single variable, `TRAIN_MODE`:\n", "\n", "| | `lora` | `full` |\n", "|---|---|---|\n", "| What is trained | LoRA adapters (r=64) on every linear layer of the *language* model | all language-model weights except frozen groups (vision/audio towers, per-layer embeddings, token embeddings) |\n", "| Optimizer | `adamw_8bit` | `adamw_8bit` (classic fp32 AdamW needs ~95 GB for states alone and does not fit) |\n", "| Learning rate | 1e-4 | 1e-5 |\n", "| Expected GPU memory at 64k | ~35–50 GB | ~50–65 GB |\n", "\n", "## How to use it\n", "1. **Smoke test first.** Keep `N_SAMPLES = 100` (the default) and run all cells. The whole pipeline then runs on a small random subset in a few minutes: download, analysis, tokenization, training, evaluation and saving.\n", "2. Check the outputs of section 3 (chat-template check and loss-mask preview) and the memory probe in section 5.\n", "3. For the real run, set `N_SAMPLES = None` (full dataset) and run again.\n", "\n", "Sections 1–3 need **no GPU**: download, data analysis, normalization, tokenization and masking. Training starts in section 4.\n", "\n", "## Data: what the training file contains\n", "These figures come from an analysis of the first 50 MB (625 trajectories) of the 2.12 GB file, so the full file holds roughly 26k trajectories. Section 2 recomputes everything on whatever you load.\n", "\n", "**Rows and messages**\n", "- **One JSONL row per trajectory.** Each row has `messages`, `tools`, `metadata`, `prompt_id`, plus generator bookkeeping: `prompt_variant_type`, `source_intent_id`, `original_user_prompt`, `deployment_context`, `argument_source_map`, flags such as `needs_clarification`, `no_results_returned`, ...\n", "- **`messages`** go `system` → `user` → (`assistant` with `tool_calls` → `tool`)×N → `assistant` (final markdown answer).\n", "- **The system prompt ends with a \"Deployment Context\" block.** It holds the default warehouse and short-reason code. The model has to learn to use these defaults when the user omits them (`implicit_defaults`, ~92% of rows) and to let explicit user values override them.\n", "- **Reasoning is inline.** Every assistant turn starts with a `…` block inside `content`; there is no separate field. With `REASONING_MODE=\"native\"` it is moved into Gemma 4's native thinking channel. Leaving it inline breaks masking, because the template rewrites earlier tool-call turns.\n", "- **`tool_calls[].function.arguments` is a JSON string.** HF chat templates expect a `dict`, so `normalize_example` parses it.\n", "- **`tool` messages** carry `is_error` and `status`; `content` is a JSON string.\n", "\n", "**Tools**\n", "- **34 tools, identical in every row:** 28 `get_*`, 5 write tools (`allocate_inventory`, `allocate_wave`, `process_cancel_pick`, `assign_pick_group`, `update_shipment_line`) and the new composite tool `resolve_self_remediation_yard`.\n", "- **Only 2 tools are ever called in the analysed part:** `get_short_shipment_lines` (in almost every row) and `get_shipments` (~60% of rows). The other 32 tools are context only. The model will learn *not* to call them, but not *how* to call them.\n", "\n", "**Variants and length**\n", "- **Edge cases are rare:** clarification without any tool call (~0.5%), empty tool results (~1.5%), explicit warehouse/reason overrides (~6%).\n", "- **Answer-leaking hints** (`Expected tool sequence`) are no longer present in user prompts.\n", "- **Length:** a typical trajectory is **~17k tokens** with the Gemma 4 tokenizer, and the tool schemas take most of it. The longest one in the sample is ~1.5× the median, so `MAX_SEQ_LEN=32768` should keep essentially everything. Section 3 shows the exact distribution.\n", "\n", "### Things to keep in mind\n", "1. **Narrow tool coverage.** Training on this file teaches a 1–2-call shorts workflow very well, but nothing about the other tools.\n", "2. **Low share of trained tokens.** Only a small share of tokens (reasoning, calls, answers) goes into the loss; the rest is fixed context. Training speed is dominated by the ~15k-token prefix.\n", "3. **`dataset_split` is mostly missing** (set on ~30% of rows, always `train`), so the eval split is produced by the stratified-by-intent fallback." ] }, { "cell_type": "markdown", "id": "8f7ec0a2", "metadata": {}, "source": [ "## 0. Install\n", "Use a **separate environment**. Gemma 4 needs recent `transformers`, while the repo's SFT environment (Nemotron) is pinned to `transformers<5`; the Azure ML default kernels are too old as well.\n", "\n", "On an Azure ML compute instance, create the kernel once in a terminal, then select **gemma4** in the kernel picker:\n", "```bash\n", "conda create -y -n gemma4 -c conda-forge --override-channels python=3.12 && conda run -n gemma4 pip install ipykernel && conda run -n gemma4 python -m ipykernel install --user --name gemma4 --display-name gemma4\n", "```" ] }, { "cell_type": "code", "execution_count": 5, "id": "603b445e", "metadata": {}, "outputs": [], "source": [ "# %pip (not !pip) installs into the Python of the CURRENT kernel. !pip can hit a different interpreter, which is\n", "# exactly how \"unsloth is not available\" happens even after installing it.\n", "# Run this in the dedicated Gemma 4 kernel, NOT in the Azure ML default kernel (jupyter_env / Python 3.10 / azureml_py*).\n", "# After it finishes, restart the kernel (Kernel -> Restart) so the new packages are picked up.\n", "\n", "\n", "\n", "# import sys\n", "# print(\"kernel python:\", sys.executable, sys.version.split()[0])\n", "# %pip install -q -U \"unsloth\" \"unsloth_zoo\"\n", "# %pip install -q -U \"transformers\" \"trl\" \"datasets\" \"accelerate\" \"bitsandbytes\" \"pandas\" \"matplotlib\"\n", "# # Dataset download: direct Azure Blob access + Azure ML datastore access (azureml-fsspec)\n", "# %pip install -q -U \"azure-storage-blob\" \"azure-identity\" \"azureml-fsspec\"\n", "# %pip install -q six azure-ai-ml\n", "# %pip install -q azure-storage-file-share # Azure Files upload (section 1.1 also installs it if missing)\n" ] }, { "cell_type": "markdown", "id": "88c36afa", "metadata": {}, "source": [ "## 1. Configuration\n", "All settings are in this one cell. The rest of the notebook only reads them." ] }, { "cell_type": "code", "execution_count": 1, "id": "eabc081d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "🦥 Unsloth: Will patch your computer to enable 2x faster free finetuning.\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/anaconda/envs/gemma4/lib/python3.12/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n", " from .autonotebook import tqdm as notebook_tqdm\n", "W1105 12:56:10.890000 721523 site-packages/torch/utils/_pytree.py:630] is an Enum subclass and is now natively supported by torch.compile as an opaque value type. Calling register_constant() on Enum subclasses is deprecated and will be an error in a future release.\n", "W1105 12:56:10.912000 721523 site-packages/torch/utils/_pytree.py:630] is an Enum subclass and is now natively supported by torch.compile as an opaque value type. Calling register_constant() on Enum subclasses is deprecated and will be an error in a future release.\n", "/anaconda/envs/gemma4/lib/python3.12/site-packages/transformers/configuration_utils.py:723: FutureWarning: `rope_scaling` is deprecated and will be removed in a future version. Set `rope_parameters` instead, with `rope_type` and `rope_theta` included.\n", " warnings.warn(\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Unsloth: xformers is installed but cannot load with torch 2.14.1+cu130 (it was built for 2.10.0+cu128), so PyTorch attention is used instead.\n", "To install a matching xformers, run `unsloth install-kernels xformers`, or `pip uninstall xformers` to hide this. UNSLOTH_ENABLE_LOGGING=1 shows the full error.\n", "🦥 Unsloth Zoo will now patch everything to make training faster!\n", "TRAIN_MODE=lora MAX_SEQ_LEN=32768 N_SAMPLES=None\n", "WORK_ROOT=/mnt/sft (free: 54 GB) OUTPUT_DIR=/mnt/sft/sft_outputs/gemma-4-E4B-it-fc-lora-20261105-125617\n", "RUN_NAME=gemma-4-E4B-it-fc-lora-20261105-125617 persist -> https://f0e5421a9fe2c4b71ad30f7.file.core.windows.net/pvc-5f71c3c3-be4d-4309-bbfa-dd48f339250c/gemma-4-E4B-it-fc-lora-20261105-125617\n", "[warn] ~57 GB of local disk is needed for checkpoints + final model, only 54 GB free\n" ] } ], "source": [ "import os, json, re, random, math, hashlib, inspect\n", "from pathlib import Path\n", "from collections import Counter, defaultdict\n", "from urllib.parse import urlsplit\n", "\n", "# `unsloth` must be imported BEFORE `transformers`: it monkey-patches model classes (fused cross-entropy,\n", "# gradient-checkpointing offload, attention kernels) at import time.\n", "# On a machine without a GPU the import fails. Sections 1-3 (data only) still work in that case.\n", "try:\n", " import unsloth # noqa: F401\n", " from unsloth import FastModel\n", " UNSLOTH_OK = True\n", "except Exception as e:\n", " print(f\"[warn] unsloth is not available ({type(e).__name__}: {e}). Data analysis works, training does not.\")\n", " UNSLOTH_OK = False\n", "\n", "import pandas as pd\n", "\n", "# ======================= RUN SIZE (smoke test vs. full run) =======================\n", "# Number of trajectories to use from the training file.\n", "# * an int (e.g. 100) -> random, seeded subset. Use this first to check that the whole pipeline works end-to-end.\n", "# * None -> the whole dataset (real training run).\n", "# With a small N_SAMPLES the notebook also shrinks gradient accumulation and the logging/eval/save intervals\n", "# so that you actually see several optimizer steps, an evaluation and a checkpoint (see \"smoke-test overrides\" below).\n", "N_SAMPLES = None\n", "N_EVAL_SAMPLES = None # cap on eval trajectories (None = keep the whole eval split)\n", "# The training file is large. In smoke-test mode (N_SAMPLES set) only the BEGINNING of the blob is streamed:\n", "# the first N_SAMPLES * STREAM_OVERSAMPLE rows are downloaded, and N_SAMPLES are then sampled from them at random.\n", "# Oversampling partly compensates for files that are sorted (e.g. by intent). For a fully representative\n", "# sample, or for the real run (N_SAMPLES=None), the whole file is downloaded.\n", "STREAM_OVERSAMPLE = 5\n", "\n", "# ======================= MODEL / MODE =======================\n", "TRAIN_MODE = \"lora\" # \"lora\" | \"full\"\n", "MODEL_NAME = \"unsloth/gemma-4-E4B-it\"\n", "MAX_SEQ_LEN = 32768 # 32768 or 65536. Longer trajectories are DROPPED, not truncated:\n", " # truncation would cut off the final answer, the most important target.\n", "SEED = 3407\n", "\n", "# ======================= DATA LOCATION =======================\n", "# DATA_URL can be an Azure Blob HTTPS URL (downloaded once into LOCAL_DATA_DIR and cached) or a local path.\n", "DATA_URL = (\"https://wmsoperatorcus2666761940.blob.core.windows.net/\"\n", " \"azureml-blobstore-d1ed4f78-081d-4c32-a452-9b0059bc858c/UI/2026-10-12_142204_UTC/\"\n", " \"sft.train.007.prompt_variants.with_as005_wrapper.with_edge_cases.sample_one_seed10.\"\n", " \"global_tools.implicit90_other10.stateful_reasoning.jsonl\")\n", "EVAL_URL = None # separate eval file (URL or path). None -> split eval from the train file.\n", "# Three forms are accepted for DATA_URL / EVAL_URL:\n", "# 1. https://.blob.core.windows.net// direct Blob access (needs a SAS, key or RBAC role)\n", "# 2. azureml://subscriptions//resourcegroups//workspaces//datastores//paths/\n", "# Azure ML datastore access: uses the credential STORED IN THE DATASTORE, so your identity needs only\n", "# workspace access (e.g. AzureML Data Scientist), not the \"Storage Blob Data Reader\" role on the account.\n", "# Studio shows this URI on the data asset page (\"Data sources\" / \"Copy URI\").\n", "# 3. a local path\n", "# DATA_ACCESS=\"auto\": an https URL whose container is \"azureml-blobstore-\" is the workspace's default\n", "# datastore. It is rewritten to form 2 (datastore AML_DATASTORE) whenever the workspace is known (AML_* below or\n", "# the compute instance's environment). \"blob\" forces direct Blob access, \"datastore\" forces the datastore route.\n", "DATA_ACCESS = \"auto\"\n", "AML_DATASTORE = \"workspaceblobstore\" # default blob datastore of every Azure ML workspace\n", "AML_SUBSCRIPTION = os.environ.get(\"AML_SUBSCRIPTION_ID\") # None -> read from the environment / config.json\n", "AML_RESOURCE_GROUP = os.environ.get(\"AML_RESOURCE_GROUP\")\n", "AML_WORKSPACE = os.environ.get(\"AML_WORKSPACE_NAME\")\n", "# Working directory for the dataset cache and checkpoints. It should be on the large local NVMe temp disk (/mnt):\n", "# the OS disk is only 128 GB and ~/cloudfiles (Azure ML Notebooks share) is a slow network drive.\n", "# /mnt is wiped when the VM / compute instance is stopped or deallocated, so copy final models elsewhere.\n", "# On an Azure ML compute instance /mnt is owned by root and the notebook runs as `azureuser`; pick_work_root()\n", "# below then creates /mnt/sft with passwordless sudo (available there by default) and hands it to the current user.\n", "# Override with the env var SFT_WORK_ROOT or by setting WORK_ROOT explicitly.\n", "WORK_ROOT = os.environ.get(\"SFT_WORK_ROOT\") # None -> auto\n", "\n", "\n", "def _writable(p: Path) -> bool:\n", " try:\n", " p.mkdir(parents=True, exist_ok=True)\n", " probe = p / \".write_probe\"\n", " probe.write_text(\"ok\"); probe.unlink()\n", " return True\n", " except OSError:\n", " return False\n", "\n", "\n", "def pick_work_root(preferred=None) -> Path:\n", " import getpass, shutil, subprocess\n", " if preferred:\n", " p = Path(preferred)\n", " assert _writable(p), f\"WORK_ROOT={p} is not writable\"\n", " return p\n", " nvme = Path(\"/mnt/sft\")\n", " if _writable(nvme):\n", " return nvme\n", " # /mnt exists but is root-owned (Azure ML compute instance): try passwordless sudo once (-n = never prompt).\n", " if Path(\"/mnt\").is_dir() and shutil.which(\"sudo\"):\n", " user = getpass.getuser()\n", " r = subprocess.run([\"sudo\", \"-n\", \"sh\", \"-c\", f\"mkdir -p {nvme} && chown {user} {nvme}\"],\n", " capture_output=True, text=True)\n", " if r.returncode == 0 and _writable(nvme):\n", " print(f\"created {nvme} with sudo and gave it to user '{user}'\")\n", " return nvme\n", " print(f\"[warn] cannot create {nvme} (sudo: {r.stderr.strip() or 'failed'}). \"\n", " f\"Fix manually in a terminal: sudo mkdir -p {nvme} && sudo chown $USER {nvme}\")\n", " fallback = Path.home() / \"sft_work\"\n", " print(f\"[warn] falling back to {fallback} on the OS disk - mind the free space (checkpoints are large)\")\n", " assert _writable(fallback), f\"{fallback} is not writable either\"\n", " return fallback\n", "\n", "\n", "WORK_ROOT = pick_work_root(WORK_ROOT)\n", "LOCAL_DATA_DIR = str(WORK_ROOT / \"data\")\n", "# ======================= RUN NAME =======================\n", "# Every run gets its own name: -fc--[-smoke], e.g. gemma-4-E4B-it-fc-lora-20261105-132616.\n", "# It is used both for the local OUTPUT_DIR and for the folder on the persistent share.\n", "# To continue writing into an earlier run's folder, set RUN_ID to that run's id (or the env var SFT_RUN_ID).\n", "from datetime import datetime\n", "RUN_ID = os.environ.get(\"SFT_RUN_ID\") or datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n", "RUN_NAME = f\"{MODEL_NAME.split('/')[-1]}-fc-{TRAIN_MODE}-{RUN_ID}\"\n", "OUTPUT_DIR = str(WORK_ROOT / \"sft_outputs\" / RUN_NAME) # local, fast NVMe; wiped when the instance stops\n", "\n", "# ======================= PERSISTENT STORAGE (Azure Files) =======================\n", "# Training writes to the fast local disk (OUTPUT_DIR); the results are then uploaded to this Azure Files share\n", "# as //final/... (and /checkpoint-N/ if PERSIST_CHECKPOINTS).\n", "# Writing checkpoints straight to a network share would slow every save and risks half-written checkpoints.\n", "# None -> keep everything local only. Credentials: see section 1.1.\n", "PERSIST_URL = \"https://f0e5421a9fe2c4b71ad30f7.file.core.windows.net/pvc-5f71c3c3-be4d-4309-bbfa-dd48f339250c/\"\n", "# Upload every checkpoint right after it is saved. Training waits for the upload: seconds for a LoRA checkpoint\n", "# (~1-2 GB), a few minutes for a full-FT one (~25 GB). Old checkpoints are NOT deleted on the share.\n", "PERSIST_CHECKPOINTS = True\n", "PERSIST_CREDENTIAL_FILE = Path.home() / \".sft_share_credential\" # optional: a SAS token or account key, chmod 600\n", "\n", "# ======================= DATA PROCESSING =======================\n", "EVAL_FRACTION = 0.05 # share of each intent held out for eval (only if no EVAL_URL / dataset_split)\n", "MIN_HARD_VR_SCORE = None # e.g. 1.0 keeps only trajectories that passed the hard verifier\n", "STRIP_ROUTING_HINTS = False # True -> remove \"Routing hint / Hard-verifier hint / Expected tool sequence\" lines\n", "# Assistant reasoning. In this dataset every assistant turn starts with an inline \"...\" block\n", "# inside `content` (there is no separate reasoning field). Options:\n", "# \"native\" -> move the text into the message's `reasoning` field. The Gemma 4 template then renders it in\n", "# its NATIVE thinking format (<|channel>thought ... ), i.e. exactly what the model produces\n", "# at inference with thinking enabled. Recommended.\n", "# \"drop\" -> delete the blocks; train on tool calls / answers only.\n", "# \"inline\" -> leave \"\" as plain text in content. NOT recommended: the Gemma 4 template rewrites the content\n", "# of earlier tool-call turns, so turns 2+ cannot be masked and most rows are dropped.\n", "REASONING_MODE = \"native\"\n", "REASONING_SOURCE_KEYS = (\"reasoning_content\", \"reasoning\", \"thinking\", \"thought\") # separate fields, if a file has them\n", "REASONING_TEMPLATE_KEY = \"reasoning\" # field the Gemma 4 template reads\n", "# Kwargs for apply_chat_template. Thinking is enabled only when reasoning is trained: with enable_thinking=True the\n", "# template opens a thought block in every generation prompt, which would not match data without reasoning.\n", "# Use the SAME enable_thinking setting at inference (vLLM: chat_template_kwargs={\"enable_thinking\": ...}).\n", "CHAT_TEMPLATE_KWARGS = {\"enable_thinking\": REASONING_MODE == \"native\"}\n", "NUM_PROC = 8 # worker processes for tokenization\n", "\n", "# ======================= LoRA =======================\n", "# r=64 with alpha=r gives the adapters enough capacity for a narrow but strict output format (tool JSON).\n", "# Unsloth's kernels are optimized for dropout = 0.\n", "LORA_R, LORA_ALPHA, LORA_DROPOUT = 64, 64, 0.0\n", "\n", "# ======================= FULL FT =======================\n", "# Parameters whose names match these regexes are frozen in full FT:\n", "# * vision / audio towers: the data is text-only, so training them only costs memory;\n", "# * per-layer embeddings (~2.8B params): the largest memory consumer, with little benefit for function calling.\n", "FULL_FT_FREEZE_PATTERNS = [r\"vision\", r\"audio\", r\"embed_tokens_per_layer\"]\n", "FULL_FT_FREEZE_EMBEDDINGS = True # also freeze embed_tokens (tied with lm_head, 262k x hidden). Saves\n", " # ~10 GB of grads/optimizer state and protects the huge vocabulary.\n", "\n", "# ======================= OPTIMIZATION =======================\n", "# Effective batch = per_device_batch (1) x gradient_accumulation_steps. Long sequences force batch=1.\n", "# 16 trajectories per optimizer step keeps the gradient noise reasonable.\n", "HP = {\n", " \"lora\": dict(learning_rate=1e-4, num_train_epochs=2, gradient_accumulation_steps=16,\n", " warmup_ratio=0.03, weight_decay=0.01, optim=\"adamw_8bit\"),\n", " \"full\": dict(learning_rate=1e-5, num_train_epochs=1, gradient_accumulation_steps=16,\n", " warmup_ratio=0.03, weight_decay=0.01, optim=\"adamw_8bit\"),\n", "}[TRAIN_MODE]\n", "LOGGING_STEPS, EVAL_STEPS, SAVE_STEPS = 5, 250, 500\n", "# A full-FT checkpoint is ~25 GB (bf16 weights + 8-bit Adam state); /mnt has only ~57 GB free on this VM,\n", "# so two of them plus the final model would not fit. LoRA checkpoints are small.\n", "SAVE_TOTAL_LIMIT = 20 if TRAIN_MODE == \"lora\" else 1\n", "REPORT_TO = \"none\" # \"mlflow\" / \"tensorboard\" / \"wandb\"\n", "MAX_STEPS = -1 # >0 hard-caps optimizer steps (overrides epochs)\n", "N_GEN_EVAL_DIALOGS = 20 # trajectories used for the generation-based tool-call check (section 7)\n", "\n", "# ---- smoke-test overrides ----\n", "# With only ~100 samples, the full-run settings above would give ~6 optimizer steps and never reach an\n", "# eval/save step. Shrink everything so a small run still exercises logging, evaluation and checkpointing.\n", "if N_SAMPLES is not None:\n", " HP[\"gradient_accumulation_steps\"] = min(HP[\"gradient_accumulation_steps\"], 4)\n", " _steps = max(1, math.ceil(N_SAMPLES * (1 - EVAL_FRACTION) / HP[\"gradient_accumulation_steps\"]) * HP[\"num_train_epochs\"])\n", " LOGGING_STEPS = 1\n", " EVAL_STEPS = SAVE_STEPS = max(1, _steps // 2)\n", " N_GEN_EVAL_DIALOGS = min(N_GEN_EVAL_DIALOGS, 5)\n", " RUN_NAME += f\"-smoke{N_SAMPLES}\"\n", " OUTPUT_DIR += f\"-smoke{N_SAMPLES}\"\n", " print(f\"[smoke test] N_SAMPLES={N_SAMPLES}: grad_accum={HP['gradient_accumulation_steps']}, \"\n", " f\"~{_steps} optimizer steps, eval/save every {EVAL_STEPS} steps\")\n", "\n", "# Tool names starting with these prefixes are state-changing (\"write\") tools. Used only for reporting.\n", "WRITE_TOOL_PREFIXES = (\"allocate_\", \"process_\", \"assign_\", \"update_\")\n", "\n", "random.seed(SEED)\n", "Path(OUTPUT_DIR).mkdir(parents=True, exist_ok=True)\n", "Path(LOCAL_DATA_DIR).mkdir(parents=True, exist_ok=True)\n", "import shutil as _sh\n", "print(f\"TRAIN_MODE={TRAIN_MODE} MAX_SEQ_LEN={MAX_SEQ_LEN} N_SAMPLES={N_SAMPLES}\")\n", "_free_gb = _sh.disk_usage(WORK_ROOT).free / 2**30\n", "print(f\"WORK_ROOT={WORK_ROOT} (free: {_free_gb:.0f} GB) OUTPUT_DIR={OUTPUT_DIR}\")\n", "print(f\"RUN_NAME={RUN_NAME} persist -> {PERSIST_URL.rstrip('/') + '/' + RUN_NAME if PERSIST_URL else 'local only'}\")\n", "# Rough local disk need: checkpoints kept at once + final model (LoRA: adapter + merged bf16 copy).\n", "_need_gb = (SAVE_TOTAL_LIMIT * 2 + 17) if TRAIN_MODE == \"lora\" else (SAVE_TOTAL_LIMIT * 25 + 17)\n", "if _free_gb < _need_gb:\n", " print(f\"[warn] ~{_need_gb} GB of local disk is needed for checkpoints + final model, only {_free_gb:.0f} GB free\")" ] }, { "cell_type": "markdown", "id": "531aa632", "metadata": {}, "source": [ "### 1.1 Persistent storage: Azure Files share\n", "The local working disk (`/mnt`) is wiped when the compute instance stops. After training, the notebook uploads the final model and every checkpoint right after it is saved to the Azure Files share in `PERSIST_URL`:\n", "```\n", "//final/adapter/ LoRA adapter\n", "//final/merged_16bit/ merged bf16 model (LoRA) / the model itself (full FT: directly in final/)\n", "//final/run_summary.json\n", "//checkpoint-N/ every checkpoint, uploaded right after it is saved\n", "```\n", "Files that already exist on the share with the same size are skipped, so a failed upload can simply be re-run.\n", "\n", "**Credentials** are tried in this order (the cell below checks write access **before** training, so a missing permission does not surface only after hours of training):\n", "1. a SAS token in `PERSIST_URL` itself (`...?sv=...&sig=...`) or in the env var `AZURE_FILES_SAS_TOKEN`;\n", "2. the file `PERSIST_CREDENTIAL_FILE` (`~/.sft_share_credential`) with either a SAS token or the account key. Keep secrets out of the notebook: create it in a terminal with `nano ~/.sft_share_credential && chmod 600 ~/.sft_share_credential`;\n", "3. an account key from `AZURE_FILES_ACCOUNT_KEY`, or `AZURE_STORAGE_ACCOUNT_NAME` + `AZURE_STORAGE_ACCOUNT_KEY` / `AZURE_STORAGE_CONNECTION_STRING` when they name this account;\n", "4. `DefaultAzureCredential` (managed identity / `az login`). For Azure Files over REST this needs the role **Storage File Data Privileged Contributor** on the storage account; the usual Blob roles do not apply.\n", "\n", "The share name `pvc-...` suggests it is an AKS persistent volume. The serving side can then read the model from the same volume." ] }, { "cell_type": "code", "execution_count": 2, "id": "152e1563", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "share is writable: https://f0e5421a9fe2c4b71ad30f7.file.core.windows.net/pvc-5f71c3c3-be4d-4309-bbfa-dd48f339250c/gemma-4-E4B-it-fc-lora-20261105-125617/\n" ] } ], "source": [ "try:\n", " import azure.storage.fileshare # noqa: F401\n", "except ImportError: # installed into the CURRENT kernel's Python\n", " import subprocess, sys\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"azure-storage-file-share\"])\n", "\n", "\n", "def _file_share_credential(account: str):\n", " # Credential for the share's storage account (order: see the markdown above). Returns None for a SAS in the URL.\n", " sas = os.environ.get(\"AZURE_FILES_SAS_TOKEN\")\n", " if not sas and PERSIST_CREDENTIAL_FILE and Path(PERSIST_CREDENTIAL_FILE).expanduser().is_file():\n", " secret = Path(PERSIST_CREDENTIAL_FILE).expanduser().read_text().strip()\n", " if \"sig=\" in secret:\n", " sas = secret\n", " elif secret:\n", " from azure.core.credentials import AzureNamedKeyCredential\n", " return AzureNamedKeyCredential(account, secret)\n", " if sas:\n", " return sas.lstrip(\"?\")\n", " key = os.environ.get(\"AZURE_FILES_ACCOUNT_KEY\")\n", " if not key and os.environ.get(\"AZURE_STORAGE_ACCOUNT_NAME\") == account:\n", " key = os.environ.get(\"AZURE_STORAGE_ACCOUNT_KEY\")\n", " conn = dict(p.split(\"=\", 1) for p in os.environ.get(\"AZURE_STORAGE_CONNECTION_STRING\", \"\").split(\";\") if \"=\" in p)\n", " if not key and conn.get(\"AccountName\") == account:\n", " key = conn.get(\"AccountKey\")\n", " if key:\n", " from azure.core.credentials import AzureNamedKeyCredential\n", " return AzureNamedKeyCredential(account, key)\n", " from azure.identity import DefaultAzureCredential\n", " return DefaultAzureCredential()\n", "\n", "\n", "def _share():\n", " # (ShareClient, base path inside the share) for PERSIST_URL = https://.file.core.windows.net/[/]\n", " from azure.storage.fileshare import ShareClient\n", " parsed = urlsplit(PERSIST_URL)\n", " account = parsed.netloc.split(\".\")[0]\n", " share_name, _, base = parsed.path.strip(\"/\").partition(\"/\")\n", " assert parsed.netloc.endswith(\".file.core.windows.net\") and share_name, f\"not an Azure Files URL: {PERSIST_URL}\"\n", " credential = parsed.query or _file_share_credential(account)\n", " # OAuth (token) access to Azure Files REST requires token_intent=\"backup\"; keys and SAS must not pass it.\n", " extra = {\"token_intent\": \"backup\"} if hasattr(credential, \"get_token\") else {}\n", " client = ShareClient(account_url=f\"https://{parsed.netloc}\", share_name=share_name, credential=credential, **extra)\n", " return client, base.strip(\"/\")\n", "\n", "\n", "def _ensure_dirs(share, path: str, made: set):\n", " # Azure Files has real directories: create every level of `path` (no-op for existing ones).\n", " from azure.core.exceptions import ResourceExistsError\n", " cur = \"\"\n", " for part in [p for p in path.split(\"/\") if p]:\n", " cur = f\"{cur}/{part}\" if cur else part\n", " if cur in made:\n", " continue\n", " try:\n", " share.get_directory_client(cur).create_directory()\n", " except ResourceExistsError:\n", " pass\n", " made.add(cur)\n", "\n", "\n", "def upload_dir_to_share(local_dir, remote_subdir: str) -> str:\n", " # Upload every file under local_dir to //..., skipping files already there with the\n", " # same size. Returns the remote URL of the folder.\n", " from azure.core.exceptions import ResourceNotFoundError\n", " share, base = _share()\n", " root = \"/\".join(p for p in (base, remote_subdir.strip(\"/\")) if p)\n", " files = sorted(f for f in Path(local_dir).rglob(\"*\") if f.is_file())\n", " made, sent, skipped = set(), 0, 0\n", " for f in files:\n", " remote = f\"{root}/{f.relative_to(local_dir).as_posix()}\"\n", " _ensure_dirs(share, remote.rsplit(\"/\", 1)[0], made)\n", " fc = share.get_file_client(remote)\n", " size = f.stat().st_size\n", " try:\n", " if fc.get_file_properties().size == size:\n", " skipped += 1\n", " continue\n", " except ResourceNotFoundError:\n", " pass\n", " with open(f, \"rb\") as h:\n", " fc.upload_file(h, length=size, max_concurrency=8)\n", " sent += size\n", " url = f\"{PERSIST_URL.split('?')[0].rstrip('/')}/{remote_subdir.strip('/')}\"\n", " print(f\"uploaded {len(files) - skipped} files ({sent/2**30:.2f} GB), skipped {skipped} unchanged -> {url}\")\n", " return url\n", "\n", "\n", "def check_share_access():\n", " # Write + delete a probe file in / so missing permissions show up now, not after training.\n", " share, base = _share()\n", " probe_dir = \"/\".join(p for p in (base, RUN_NAME) if p)\n", " _ensure_dirs(share, probe_dir, set())\n", " probe = share.get_file_client(f\"{probe_dir}/.write_probe\")\n", " probe.upload_file(b\"ok\")\n", " probe.delete_file()\n", " print(f\"share is writable: {PERSIST_URL.split('?')[0].rstrip('/')}/{RUN_NAME}/\")\n", "\n", "\n", "if PERSIST_URL:\n", " check_share_access()\n", "else:\n", " print(\"PERSIST_URL is None: results stay only in\", OUTPUT_DIR)" ] }, { "cell_type": "markdown", "id": "80d7773f", "metadata": {}, "source": [ "## 2. Download and analyse the data\n", "### 2.1 Download from Azure Blob Storage\n", "- **Full run (`N_SAMPLES=None`):** the whole file is downloaded once and cached in `LOCAL_DATA_DIR`. It is re-downloaded only if the size of the local copy differs from the blob.\n", "- **Smoke test (`N_SAMPLES` set):** only the first `N_SAMPLES * STREAM_OVERSAMPLE` rows are streamed from the blob in 8 MiB range requests. Downloading stops as soon as enough complete lines have arrived, and the result is cached as `.head.jsonl`. A multi-GB file therefore costs only a few MB for a pipeline check.\n", "\n", "Authentication is tried in this order:\n", "1. **SAS token**, either in the URL itself (`...jsonl?sv=...`) or in the env var `AZURE_STORAGE_SAS_TOKEN`.\n", "2. **Account key** from `AZURE_STORAGE_ACCOUNT_KEY` (with `AZURE_STORAGE_ACCOUNT_NAME`) or `AZURE_STORAGE_CONNECTION_STRING`. This is the same convention the repo uses in `forge_common/artifact_refs.py`.\n", "3. **`DefaultAzureCredential`**: the VM's managed identity, `az login`, env-var service principal, and so on. The identity needs the **Storage Blob Data Reader** role on the storage account. If `az login` fails because of conditional access, run `az login --scope https://storage.azure.com/.default`.\n", "\n", "**Azure ML datastore route (recommended on an Azure ML compute instance).** Without that role, `DefaultAzureCredential` fails with `AuthorizationPermissionMismatch`. The dataset lives in the workspace's default datastore (container `azureml-blobstore-`), so the notebook reads it through `azureml-fsspec` instead. This uses the key stored in the datastore and needs only workspace permissions. With `DATA_ACCESS=\"auto\"`, an `azureml-blobstore-*` URL is routed this way automatically once the workspace (subscription, resource group, name) is known. The workspace is read from `AML_*`, the compute-instance environment, or `config.json`." ] }, { "cell_type": "code", "execution_count": 3, "id": "d3b4d7ad", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "reading via Azure ML datastore: wms-operator-cus/datastores/workspaceblobstore/paths/UI/2026-10-12_142204_UTC/sft.train.007.prompt_variants.with_as005_wrapper.with_edge_cases.sample_one_seed10.global_tools.implicit90_other10.stateful_reasoning.jsonl\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "[opentelemetry.metrics._internal|WARNING]Overriding of current MeterProvider is not allowed\n", "[opentelemetry.trace|WARNING]Overriding of current TracerProvider is not allowed\n", "[opentelemetry._logs._internal|WARNING]Overriding of current LoggerProvider is not allowed\n", "[opentelemetry.instrumentation.instrumentor|WARNING]Attempting to instrument while already instrumented\n", "[opentelemetry.instrumentation.instrumentor|WARNING]Attempting to instrument while already instrumented\n", "[opentelemetry.instrumentation.instrumentor|WARNING]Attempting to instrument while already instrumented\n", "[opentelemetry.instrumentation.instrumentor|WARNING]Attempting to instrument while already instrumented\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "downloading 2023.2 MiB -> /mnt/sft/data/sft.train.007.prompt_variants.with_as005_wrapper.with_edge_cases.sample_one_seed10.global_tools.implicit90_other10.stateful_reasoning.jsonl\n" ] } ], "source": [ "def _storage_credential(account: str):\n", " # Pick a credential for the storage account (see the markdown above for the order).\n", " sas = os.environ.get(\"AZURE_STORAGE_SAS_TOKEN\")\n", " if sas:\n", " return sas.lstrip(\"?\")\n", " key = None\n", " if os.environ.get(\"AZURE_STORAGE_ACCOUNT_NAME\") == account:\n", " key = os.environ.get(\"AZURE_STORAGE_ACCOUNT_KEY\")\n", " conn = dict(p.split(\"=\", 1) for p in os.environ.get(\"AZURE_STORAGE_CONNECTION_STRING\", \"\").split(\";\") if \"=\" in p)\n", " if conn.get(\"AccountName\") == account:\n", " key = key or conn.get(\"AccountKey\")\n", " if key:\n", " from azure.core.credentials import AzureNamedKeyCredential\n", " return AzureNamedKeyCredential(account, key)\n", " from azure.identity import DefaultAzureCredential\n", " return DefaultAzureCredential()\n", "\n", "\n", "def _stream_head(blob, remote_size: int, local: Path, max_rows: int, chunk_bytes: int = 8 * 2**20) -> Path:\n", " # Download only the first `max_rows` complete JSONL lines using ranged reads.\n", " tmp = local.with_name(local.name + \".part\")\n", " rows, offset, carry = 0, 0, b\"\"\n", " with open(tmp, \"wb\") as f:\n", " while rows < max_rows and offset < remote_size:\n", " length = min(chunk_bytes, remote_size - offset)\n", " data = carry + blob.download_blob(offset=offset, length=length).readall()\n", " offset += length\n", " lines = data.split(b\"\\n\")\n", " # Mid-file, the last piece is usually a half-received line: keep it and prepend it to the next chunk.\n", " # At end of file it is the final line (or empty if the file ends with a newline).\n", " carry = lines.pop() if offset < remote_size else b\"\"\n", " for line in lines:\n", " if rows >= max_rows:\n", " break\n", " if line.strip():\n", " f.write(line + b\"\\n\")\n", " rows += 1\n", " tmp.replace(local)\n", " print(f\"streamed {rows} rows ({offset/2**20:.1f} MiB of {remote_size/2**20:.1f} MiB) -> {local}\")\n", " return local\n", "\n", "\n", "def _aml_workspace():\n", " # (subscription, resource_group, workspace) of the current Azure ML workspace, or None if unknown.\n", " # Order: explicit AML_* config -> env vars of Azure ML jobs / compute instances -> config.json.\n", " sub = AML_SUBSCRIPTION or os.environ.get(\"AZUREML_ARM_SUBSCRIPTION\")\n", " rg = AML_RESOURCE_GROUP or os.environ.get(\"AZUREML_ARM_RESOURCEGROUP\") or os.environ.get(\"CI_RESOURCE_GROUP\")\n", " ws = AML_WORKSPACE or os.environ.get(\"AZUREML_ARM_WORKSPACE_NAME\") or os.environ.get(\"CI_WORKSPACE\")\n", " if not (sub and rg and ws):\n", " # Compute instances and `az ml` / Studio downloads provide a config.json with all three values.\n", " for cfg in [Path.cwd(), *Path.cwd().parents, Path.home() / \".azureml\", Path(\"/\")]:\n", " for f in (cfg / \"config.json\", cfg / \".azureml\" / \"config.json\"):\n", " try:\n", " c = json.loads(f.read_text())\n", " except (OSError, ValueError):\n", " continue\n", " if isinstance(c, dict) and c.get(\"subscription_id\"):\n", " sub = sub or c.get(\"subscription_id\")\n", " rg = rg or c.get(\"resource_group\")\n", " ws = ws or c.get(\"workspace_name\")\n", " break\n", " if sub and rg and ws:\n", " break\n", " return (sub, rg, ws) if (sub and rg and ws) else None\n", "\n", "\n", "def _to_datastore_uri(url: str):\n", " # https://.blob.core.windows.net/azureml-blobstore-/ -> azureml://.../datastores//paths/\n", " parsed = urlsplit(url)\n", " container, _, path = parsed.path.lstrip(\"/\").partition(\"/\")\n", " if DATA_ACCESS == \"blob\" or parsed.query or not container.startswith(\"azureml-blobstore-\"):\n", " return None\n", " ws = _aml_workspace()\n", " if ws is None:\n", " if DATA_ACCESS == \"datastore\":\n", " raise RuntimeError(\"DATA_ACCESS='datastore' but the workspace is unknown: set AML_SUBSCRIPTION, \"\n", " \"AML_RESOURCE_GROUP and AML_WORKSPACE (Studio: top-right workspace menu)\")\n", " return None\n", " sub, rg, name = ws\n", " return (f\"azureml://subscriptions/{sub}/resourcegroups/{rg}/workspaces/{name}\"\n", " f\"/datastores/{AML_DATASTORE}/paths/{path}\")\n", "\n", "\n", "class _DatastoreBlob:\n", " # Wraps a file in an Azure ML datastore (azureml-fsspec) behind the two BlobClient calls used here, so\n", " # _stream_head and the full download work unchanged for both access routes.\n", " def __init__(self, uri: str):\n", " from azureml.fsspec import AzureMachineLearningFileSystem\n", " root, sep, self.path = uri.partition(\"/paths/\")\n", " assert sep and self.path, f\"expected .../datastores//paths/, got {uri}\"\n", " self.fs = AzureMachineLearningFileSystem(root + \"/paths/\")\n", " self.size = self.fs.size(self.path)\n", "\n", " def download_blob(self, offset: int = 0, length: int | None = None, max_concurrency: int = 1):\n", " fs, path, size = self.fs, self.path, self.size\n", "\n", " class _Download:\n", " def readall(self):\n", " with fs.open(path, \"rb\") as f:\n", " f.seek(offset)\n", " return f.read(size - offset if length is None else length)\n", "\n", " def readinto(self, out):\n", " with fs.open(path, \"rb\", block_size=64 * 2**20) as f:\n", " f.seek(offset)\n", " while chunk := f.read(64 * 2**20):\n", " out.write(chunk)\n", " return _Download()\n", "\n", "\n", "def fetch_dataset(url_or_path: str, local_dir: str, max_rows: int | None = None) -> Path:\n", " # Return a local path for `url_or_path`, downloading it from Azure Blob / an Azure ML datastore if remote.\n", " # max_rows=None downloads the whole file; an int streams only that many rows from the beginning.\n", " if not url_or_path.startswith((\"https://\", \"azureml://\")):\n", " p = Path(url_or_path)\n", " assert p.is_file(), f\"local file not found: {p}\"\n", " return p # local file: it is read fully and subsampled in memory\n", "\n", " uri = url_or_path if url_or_path.startswith(\"azureml://\") else (_to_datastore_uri(url_or_path) or url_or_path)\n", " name = Path(urlsplit(uri).path).name\n", " if uri.startswith(\"azureml://\"):\n", " print(f\"reading via Azure ML datastore: {uri.split('/workspaces/')[-1]}\")\n", " blob = _DatastoreBlob(uri)\n", " remote_size = blob.size\n", " else:\n", " from azure.core.exceptions import HttpResponseError\n", " from azure.storage.blob import BlobClient\n", " parsed = urlsplit(uri)\n", " account = parsed.netloc.split(\".\")[0]\n", " # A SAS token already embedded in the URL is enough; do not pass a second credential.\n", " credential = None if parsed.query else _storage_credential(account)\n", " blob = BlobClient.from_blob_url(uri, credential=credential)\n", " try:\n", " remote_size = blob.get_blob_properties().size\n", " except HttpResponseError as e:\n", " if getattr(e, \"error_code\", None) in (\"AuthorizationPermissionMismatch\", \"AuthorizationFailure\"):\n", " raise PermissionError(\n", " \"Your identity cannot read this blob directly (it lacks 'Storage Blob Data Reader'). Options: \"\n", " \"(a) set AML_SUBSCRIPTION / AML_RESOURCE_GROUP / AML_WORKSPACE so the Azure ML datastore route \"\n", " \"is used, or put the azureml:// URI from Studio into DATA_URL; (b) set AZURE_STORAGE_SAS_TOKEN; \"\n", " \"(c) ask an admin for the role.\") from e\n", " raise\n", "\n", " if max_rows is not None:\n", " local = Path(local_dir) / f\"{Path(name).stem}.head{max_rows}.jsonl\"\n", " if local.is_file():\n", " print(f\"cached head: {local}\")\n", " return local\n", " return _stream_head(blob, remote_size, local, max_rows)\n", "\n", " local = Path(local_dir) / name\n", " if local.is_file() and local.stat().st_size == remote_size:\n", " print(f\"cached: {local} ({remote_size/2**20:.1f} MiB)\")\n", " return local\n", "\n", " # Download into a .part file and rename at the end, so an interrupted download never looks complete.\n", " tmp = local.with_name(local.name + \".part\")\n", " print(f\"downloading {remote_size/2**20:.1f} MiB -> {local}\")\n", " with open(tmp, \"wb\") as f:\n", " blob.download_blob(max_concurrency=8).readinto(f)\n", " tmp.replace(local)\n", " return local\n", "\n", "\n", "DATA_PATH = fetch_dataset(DATA_URL, LOCAL_DATA_DIR,\n", " max_rows=N_SAMPLES * STREAM_OVERSAMPLE if N_SAMPLES else None)\n", "EVAL_PATH = (fetch_dataset(EVAL_URL, LOCAL_DATA_DIR,\n", " max_rows=N_EVAL_SAMPLES * STREAM_OVERSAMPLE if N_EVAL_SAMPLES else None)\n", " if EVAL_URL else None)" ] }, { "cell_type": "markdown", "id": "9a5e671f", "metadata": {}, "source": [ "### 2.2 Load and (optionally) subsample" ] }, { "cell_type": "code", "execution_count": 4, "id": "151cf99e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "/mnt/sft/data/sft.train.007.prompt_variants.with_as005_wrapper.with_edge_cases.sample_one_seed10.global_tools.implicit90_other10.stateful_reasoning.jsonl: 25721 rows, broken JSON lines: 0\n" ] } ], "source": [ "def load_jsonl(path):\n", " # Read a JSONL file. Broken lines are counted and skipped instead of failing the whole run.\n", " rows, bad = [], 0\n", " with open(path, encoding=\"utf-8\") as f:\n", " for line in f:\n", " line = line.strip()\n", " if not line:\n", " continue\n", " try:\n", " rows.append(json.loads(line))\n", " except json.JSONDecodeError:\n", " bad += 1\n", " print(f\"{path}: {len(rows)} rows, broken JSON lines: {bad}\")\n", " return rows\n", "\n", "\n", "def subsample(rows, n, name):\n", " # Seeded random subset. Random rather than \"first n\" because files are often sorted by intent,\n", " # and the first n rows would then cover only one or two scenarios.\n", " if n is None or n >= len(rows):\n", " return rows\n", " out = random.Random(SEED).sample(rows, n)\n", " print(f\"[{name}] using a random subset of {n} / {len(rows)} rows (N_SAMPLES)\")\n", " return out\n", "\n", "\n", "raw_train = subsample(load_jsonl(DATA_PATH), N_SAMPLES, \"train\")\n", "raw_eval = subsample(load_jsonl(EVAL_PATH), N_EVAL_SAMPLES, \"eval\") if EVAL_PATH else None" ] }, { "cell_type": "markdown", "id": "f1b52d8e", "metadata": {}, "source": [ "### 2.3 Dataset analysis\n", "This cell answers the following questions about the data:\n", "- **Tools:** how many there are, whether every row has the same tool set, read vs. write tools, and which tools are never called.\n", "- **Calls:** which tool sequences occur and how many calls each trajectory has.\n", "- **Arguments:** how often calls omit \"required\" arguments or pass arguments that are not in the schema.\n", "- **Leakage:** how many prompts contain answer hints.\n", "- **Message fields:** which fields messages actually carry, for example reasoning." ] }, { "cell_type": "code", "execution_count": 5, "id": "38c8e88c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "================ train: 25721 trajectories ================\n", "Top-level keys: {'messages': 25721, 'metadata': 25721, 'prompt_id': 25721, 'tools': 25721, 'prompt_variant_type': 25721, 'source_dataset': 25721, 'source_intent_id': 25721, 'source_prompt_id': 25721, 'original_user_prompt': 25721, 'deployment_context': 25721, 'argument_source_map': 25721, 'uses_system_default_warehouse': 25721, 'uses_system_default_reason_code': 25721, 'user_overrides_warehouse': 25721, 'user_overrides_reason_code': 25721, 'requires_wave_number': 25721, 'wave_number_source': 25721, 'needs_clarification': 25721, 'no_tool_call_expected': 25721, 'no_results_returned': 25721, 'tool_catalog_strategy': 25721, 'tool_catalog_tool_count': 25721, 'variant_sampling_strategy': 25721, 'source_tool_arguments': 129, 'agent_runs_summary': 2271, 'api_sequence': 2271, 'attempt': 2271, 'closed_loop_status': 2271, 'complexity': 2271, 'coverage_slot': 2271, 'difficulty': 2271, 'domain': 2271, 'duration_s': 2271, 'experiment_metadata': 2271, 'generated_at': 2271, 'intent_id': 2271, 'max_turns': 2271, 'model': 2271, 'original_prompt': 2271, 'output': 2271, 'persona': 2271, 'prompt_category': 2271, 'scenario_name': 2271, 'sequence': 2271, 'skill_hint_prompt': 2271, 'source': 2271, 'source_refs': 2271, 'source_spec': 2271, 'trajectory_id': 2271, 'vr': 2271, 'workflow_endpoint': 2271, 'source_trace_format': 2271, 'retry_feedback': 1756}\n", "\n", "Message keys per role:\n", " system {'content': 25721, 'role': 25721}\n", " user {'content': 25721, 'role': 25721}\n", " assistant {'content': 65049, 'role': 65049, 'tool_calls': 64432}\n", " tool {'content': 39328, 'is_error': 39328, 'name': 39328, 'role': 39328, 'status': 39328, 'tool_call_id': 39328}\n", "\n", "Tools per row: {34: 25721} rows WITHOUT tools: 0\n", "Distinct tool sets: 1 (1 = every row has exactly the same tools)\n", "Distinct tools overall: 34 -> read: 29, write: 5\n", "Write tools: ['allocate_inventory', 'allocate_wave', 'assign_pick_group', 'process_cancel_pick', 'update_shipment_line']\n", "\n", "Tool calls: 39328; per trajectory avg 1.53, min/max 0/2\n", "Parallel batches (>1 tool_call in one assistant turn): 0\n", "Tool responses with an error: 0\n", "Invalid JSON in arguments: 0\n", "Trajectories without a final text answer: 0\n", "Assistant turns with reasoning: 65049 / 65049\n", "Prompts with 'Expected tool sequence' hint: 0 (0%)\n", "\n", "Tools NEVER called in this data (31) - the model will not learn to use them: ['allocate_inventory', 'allocate_wave', 'assign_pick_group', 'get_available_pickable_inventory', 'get_customers', 'get_held_inventory', 'get_inventory', 'get_inventory_item_quantities', 'get_inventory_statuses', 'get_inventory_summarized_by_location', 'get_invoice_trucks', 'get_location_status', 'get_locations', 'get_order', 'get_order_line', 'get_order_line_details', 'get_order_lines', 'get_order_types', 'get_orders', 'get_parts', 'get_pick_work', 'get_pick_work_details', 'get_picks', 'get_shipment_lines', 'get_short_reasons', 'get_uom_quantities_for_detail', 'get_uom_quantities_for_load', 'get_uom_quantities_for_sub', 'get_yard_locations_and_trailers', 'process_cancel_pick', 'update_shipment_line']\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
toolcallskind
0get_short_shipment_lines23333read
1get_shipments13736read
2resolve_self_remediation_yard2259read
\n", "
" ], "text/plain": [ " tool calls kind\n", "0 get_short_shipment_lines 23333 read\n", "1 get_shipments 13736 read\n", "2 resolve_self_remediation_yard 2259 read" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
tool sequencetrajectories
0get_short_shipment_lines -> get_shipments13736
1get_short_shipment_lines9597
2resolve_self_remediation_yard2259
3129
\n", "
" ], "text/plain": [ " tool sequence trajectories\n", "0 get_short_shipment_lines -> get_shipments 13736\n", "1 get_short_shipment_lines 9597\n", "2 resolve_self_remediation_yard 2259\n", "3 129" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
intenttrajectories
0AS-0012345
1AS-0082345
2AS-0062345
3AS-0022345
4AS-0102345
5AS-0042345
6AS-0092345
7AS-0112345
8AS-0072345
9AS-0032345
10AS-0052271
\n", "
" ], "text/plain": [ " intent trajectories\n", "0 AS-001 2345\n", "1 AS-008 2345\n", "2 AS-006 2345\n", "3 AS-002 2345\n", "4 AS-010 2345\n", "5 AS-004 2345\n", "6 AS-009 2345\n", "7 AS-011 2345\n", "8 AS-007 2345\n", "9 AS-003 2345\n", "10 AS-005 2271" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
prompt_variant_typetrajectories
0implicit_defaults23149
1explicit_override_reason489
2explicit_override_warehouse489
3original_explicit489
4no_results_after_first_tool488
5explicit_override_both488
6no_defaults_clarification129
\n", "
" ], "text/plain": [ " prompt_variant_type trajectories\n", "0 implicit_defaults 23149\n", "1 explicit_override_reason 489\n", "2 explicit_override_warehouse 489\n", "3 original_explicit 489\n", "4 no_results_after_first_tool 488\n", "5 explicit_override_both 488\n", "6 no_defaults_clarification 129" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "variant flags (rows with True): {'needs_clarification': 129, 'no_tool_call_expected': 129, 'no_results_returned': 488, 'uses_system_default_warehouse': 24126, 'uses_system_default_reason_code': 24126, 'requires_wave_number': 2345}\n", "'required' arguments omitted by calls (top 15 of 3):\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
tool.argcount
0get_short_shipment_lines.customer_number23333
1get_short_shipment_lines.order_number23333
2get_short_shipment_lines.wave_number21000
\n", "
" ], "text/plain": [ " tool.arg count\n", "0 get_short_shipment_lines.customer_number 23333\n", "1 get_short_shipment_lines.order_number 23333\n", "2 get_short_shipment_lines.wave_number 21000" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "def parse_args(raw):\n", " # `arguments` is a JSON string in this dataset. Returns (dict | None, ok).\n", " if isinstance(raw, dict):\n", " return raw, True\n", " if raw is None or raw == \"\":\n", " return {}, True\n", " try:\n", " v = json.loads(raw)\n", " return (v if isinstance(v, dict) else {\"_value\": v}), isinstance(v, dict)\n", " except json.JSONDecodeError:\n", " return None, False\n", "\n", "\n", "def tools_signature(tools):\n", " # Short hash of a tool list. Equal hashes mean identical tool sets (names, descriptions and schemas).\n", " return hashlib.md5(json.dumps(tools, sort_keys=True).encode()).hexdigest()[:10]\n", "\n", "\n", "THINK_RE = re.compile(r\"^\\s*(.*?)\\s*\", re.S)\n", "\n", "\n", "def split_reasoning(m):\n", " # Return (reasoning | None, content_without_reasoning) for an assistant message.\n", " # Looks for a separate reasoning field first, then for a leading inline ... block.\n", " content = m.get(\"content\") or \"\"\n", " for k in REASONING_SOURCE_KEYS:\n", " v = m.get(k)\n", " if isinstance(v, str) and v.strip():\n", " return v.strip(), content\n", " mt = THINK_RE.match(content)\n", " if mt:\n", " return mt.group(1).strip(), content[mt.end():]\n", " return None, content\n", "\n", "\n", "def get_reasoning(m):\n", " return split_reasoning(m)[0]\n", "\n", "\n", "def row_intent(r):\n", " # Intent used for stratified splitting / reporting. This file has it at the top level (`source_intent_id`);\n", " # older exports keep it in metadata.\n", " meta = r.get(\"metadata\") or {}\n", " return r.get(\"source_intent_id\") or meta.get(\"as_intent\") or meta.get(\"intent_id\") or \"?\"\n", "\n", "\n", "VARIANT_FLAGS = (\"needs_clarification\", \"no_tool_call_expected\", \"no_results_returned\",\n", " \"uses_system_default_warehouse\", \"uses_system_default_reason_code\", \"requires_wave_number\")\n", "\n", "\n", "def analyze(rows, title=\"dataset\"):\n", " print(f\"\\n================ {title}: {len(rows)} trajectories ================\")\n", " print(\"Top-level keys:\", dict(Counter(k for r in rows for k in r)))\n", "\n", " # ---------- which fields do messages carry, per role? (reveals reasoning fields, extra metadata, ...) ----------\n", " keys_by_role = defaultdict(Counter)\n", " for r in rows:\n", " for m in r.get(\"messages\") or []:\n", " for k in m:\n", " keys_by_role[m.get(\"role\")][k] += 1\n", " print(\"\\nMessage keys per role:\")\n", " for role, c in keys_by_role.items():\n", " print(f\" {role:<9} {dict(c)}\")\n", "\n", " # ---------- tools ----------\n", " rows_without_tools = sum(1 for r in rows if not r.get(\"tools\"))\n", " n_tools = Counter(len(r.get(\"tools\") or []) for r in rows)\n", " sigs = Counter(tools_signature(r.get(\"tools\") or []) for r in rows if r.get(\"tools\"))\n", " all_tools = {}\n", " for r in rows:\n", " for t in r.get(\"tools\") or []:\n", " all_tools.setdefault(t[\"function\"][\"name\"], t[\"function\"])\n", " write_tools = sorted(n for n in all_tools if n.startswith(WRITE_TOOL_PREFIXES))\n", " read_tools = sorted(n for n in all_tools if n not in write_tools)\n", " print(f\"\\nTools per row: {dict(n_tools)} rows WITHOUT tools: {rows_without_tools}\")\n", " print(f\"Distinct tool sets: {len(sigs)} (1 = every row has exactly the same tools)\")\n", " print(f\"Distinct tools overall: {len(all_tools)} -> read: {len(read_tools)}, write: {len(write_tools)}\")\n", " print(\"Write tools:\", write_tools)\n", "\n", " # Rows without their own `tools` are validated against the most common tool set (same fallback as training uses).\n", " _by_sig = {tools_signature(r[\"tools\"]): r[\"tools\"] for r in rows if r.get(\"tools\")}\n", " fallback_tools = _by_sig[sigs.most_common(1)[0][0]] if sigs else []\n", "\n", " # ---------- calls / arguments / quality ----------\n", " call_counter, seq_counter, intents = Counter(), Counter(), Counter()\n", " calls_per_ex, parallel_batches = [], 0\n", " bad_args, unknown_args, omitted_required, total_calls = 0, Counter(), Counter(), 0\n", " tool_errors, no_final, hint_rows, reasoning_turns, assistant_turns = 0, 0, 0, 0, 0\n", " for r in rows:\n", " msgs = r.get(\"messages\") or []\n", " schema = {t[\"function\"][\"name\"]: t[\"function\"].get(\"parameters\", {}) for t in r.get(\"tools\") or fallback_tools}\n", " seq = []\n", " for m in msgs:\n", " if m[\"role\"] == \"user\" and \"Expected tool sequence\" in (m.get(\"content\") or \"\"):\n", " hint_rows += 1\n", " if m[\"role\"] == \"tool\" and (m.get(\"is_error\") or str(m.get(\"status\", \"ok\")).lower() not in (\"ok\", \"success\")):\n", " tool_errors += 1\n", " if m[\"role\"] != \"assistant\":\n", " continue\n", " assistant_turns += 1\n", " reasoning_turns += get_reasoning(m) is not None\n", " tcs = m.get(\"tool_calls\") or []\n", " parallel_batches += len(tcs) > 1\n", " for tc in tcs:\n", " total_calls += 1\n", " name = tc[\"function\"][\"name\"]\n", " seq.append(name)\n", " call_counter[name] += 1\n", " args, ok = parse_args(tc[\"function\"].get(\"arguments\"))\n", " if not ok:\n", " bad_args += 1\n", " continue\n", " props = schema.get(name, {}).get(\"properties\", {})\n", " req = schema.get(name, {}).get(\"required\", [])\n", " for a in set(args) - set(props):\n", " unknown_args[f\"{name}.{a}\"] += 1\n", " for a in set(req) - set(args):\n", " omitted_required[f\"{name}.{a}\"] += 1\n", " seq_counter[\" -> \".join(seq)] += 1\n", " calls_per_ex.append(len(seq))\n", " last = msgs[-1] if msgs else {}\n", " if not (last.get(\"role\") == \"assistant\" and (last.get(\"content\") or \"\").strip() and not last.get(\"tool_calls\")):\n", " no_final += 1\n", " intents[row_intent(r)] += 1\n", "\n", " n = max(len(rows), 1)\n", " print(f\"\\nTool calls: {total_calls}; per trajectory avg {sum(calls_per_ex)/n:.2f}, \"\n", " f\"min/max {min(calls_per_ex, default=0)}/{max(calls_per_ex, default=0)}\")\n", " print(f\"Parallel batches (>1 tool_call in one assistant turn): {parallel_batches}\")\n", " print(f\"Tool responses with an error: {tool_errors}\")\n", " print(f\"Invalid JSON in arguments: {bad_args}\")\n", " print(f\"Trajectories without a final text answer: {no_final}\")\n", " print(f\"Assistant turns with reasoning: {reasoning_turns} / {assistant_turns}\")\n", " print(f\"Prompts with 'Expected tool sequence' hint: {hint_rows} ({hint_rows/n:.0%})\")\n", " never_called = sorted(set(all_tools) - set(call_counter))\n", " print(f\"\\nTools NEVER called in this data ({len(never_called)}) - the model will not learn to use them: {never_called}\")\n", "\n", " display(pd.DataFrame(call_counter.most_common(), columns=[\"tool\", \"calls\"]).assign(\n", " kind=lambda d: d.tool.map(lambda x: \"write\" if x.startswith(WRITE_TOOL_PREFIXES) else \"read\")))\n", " display(pd.DataFrame(seq_counter.most_common(15), columns=[\"tool sequence\", \"trajectories\"]))\n", " display(pd.DataFrame(intents.most_common(), columns=[\"intent\", \"trajectories\"]))\n", " # Prompt-variant bookkeeping written by the data generator (implicit defaults, overrides, clarification, ...).\n", " variants = Counter(str(r.get(\"prompt_variant_type\")) for r in rows if \"prompt_variant_type\" in r)\n", " if variants:\n", " display(pd.DataFrame(variants.most_common(), columns=[\"prompt_variant_type\", \"trajectories\"]))\n", " print(\"variant flags (rows with True):\",\n", " {f: sum(bool(r.get(f)) for r in rows) for f in VARIANT_FLAGS if any(f in r for r in rows)})\n", " if unknown_args:\n", " print(\"WARNING: arguments that do NOT exist in the tool schema (hallucinations in the data):\")\n", " display(pd.DataFrame(unknown_args.most_common(20), columns=[\"tool.arg\", \"count\"]))\n", " if omitted_required:\n", " print(f\"'required' arguments omitted by calls (top 15 of {len(omitted_required)}):\")\n", " display(pd.DataFrame(omitted_required.most_common(15), columns=[\"tool.arg\", \"count\"]))\n", " return {\"all_tools\": all_tools, \"call_counter\": call_counter, \"tool_sets\": sigs}\n", "\n", "\n", "train_stats = analyze(raw_train, \"train\")\n", "if raw_eval:\n", " analyze(raw_eval, \"eval\")" ] }, { "cell_type": "markdown", "id": "d90640ec", "metadata": {}, "source": [ "## 3. Normalize, tokenize and mask\n", "- **Normalize:** the raw rows are converted into the standard HF `messages` + `tools` format that the Gemma 4 chat template understands.\n", "- **Render:** each conversation is rendered with the model's **own** chat template, the same one vLLM / `generate` use at inference. This keeps training and serving formats identical.\n", "- **Mask:** the loss is computed **only on assistant turns** (tool calls, reasoning, final answer). The system prompt, tool schemas, user prompt and tool outputs are context only (label `-100`). Without this, ~90% of the gradient would go into memorizing the tool schemas and the tool outputs." ] }, { "cell_type": "code", "execution_count": 6, "id": "e6b5eaf9", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "normalized: 25721, dropped: 0\n" ] } ], "source": [ "HINT_LINE_PATTERNS = [r\"^\\s*Routing hint:\", r\"^\\s*Hard-verifier hint:\", r\"^\\s*For staged retrieval,\", r\"^\\s*Expected tool sequence:\"]\n", "\n", "# Fallback for rows without their own `tools` (the file name says \"global_tools\"): use the most common\n", "# tool set of the dataset. The analysis above prints how many rows this affects.\n", "_tool_sets = {}\n", "for _r in raw_train:\n", " if _r.get(\"tools\"):\n", " _tool_sets.setdefault(tools_signature(_r[\"tools\"]), _r[\"tools\"])\n", "GLOBAL_TOOLS = _tool_sets[train_stats[\"tool_sets\"].most_common(1)[0][0]] if train_stats[\"tool_sets\"] else []\n", "\n", "\n", "def strip_hints(text):\n", " lines = [l for l in text.split(\"\\n\") if not any(re.match(p, l) for p in HINT_LINE_PATTERNS)]\n", " return \"\\n\".join(lines).strip()\n", "\n", "\n", "def normalize_example(row):\n", " # Convert one raw row into {messages_json, tools_json, ...}. Returns None if the row is unusable.\n", " msgs = []\n", " for m in row.get(\"messages\") or []:\n", " role = m.get(\"role\")\n", " if role == \"system\":\n", " msgs.append({\"role\": \"system\", \"content\": m.get(\"content\") or \"\"})\n", " elif role == \"user\":\n", " c = m.get(\"content\") or \"\"\n", " msgs.append({\"role\": \"user\", \"content\": strip_hints(c) if STRIP_ROUTING_HINTS else c})\n", " elif role == \"assistant\":\n", " if REASONING_MODE == \"inline\":\n", " out = {\"role\": \"assistant\", \"content\": m.get(\"content\") or \"\"}\n", " else:\n", " reasoning, content = split_reasoning(m)\n", " out = {\"role\": \"assistant\", \"content\": content}\n", " if reasoning and REASONING_MODE == \"native\":\n", " out[REASONING_TEMPLATE_KEY] = reasoning\n", " tcs = []\n", " for tc in m.get(\"tool_calls\") or []:\n", " args, ok = parse_args(tc[\"function\"].get(\"arguments\"))\n", " if not ok: # a call with broken JSON would teach the model to emit broken JSON -> drop the row\n", " return None\n", " tcs.append({\"id\": tc.get(\"id\"), \"type\": \"function\",\n", " \"function\": {\"name\": tc[\"function\"][\"name\"], \"arguments\": args}})\n", " if tcs:\n", " out[\"tool_calls\"] = tcs\n", " msgs.append(out)\n", " elif role == \"tool\":\n", " # Keep the tool output as a string. `is_error` / `status` are dataset bookkeeping and the\n", " # template does not know them, so they are dropped.\n", " c = m.get(\"content\")\n", " msgs.append({\"role\": \"tool\", \"name\": m.get(\"name\"), \"tool_call_id\": m.get(\"tool_call_id\"),\n", " \"content\": c if isinstance(c, str) else json.dumps(c, ensure_ascii=False)})\n", " if not any(m[\"role\"] == \"assistant\" for m in msgs):\n", " return None\n", " meta = row.get(\"metadata\") or {}\n", " return {\n", " \"prompt_id\": row.get(\"prompt_id\") or meta.get(\"original_id\") or \"\",\n", " \"intent\": row_intent(row),\n", " \"split\": meta.get(\"dataset_split\") or \"\",\n", " \"hard_vr_score\": meta.get(\"hard_vr_score\"),\n", " # Arrow (HF datasets) cannot hold arbitrarily nested, heterogeneous JSON (tool schemas differ per tool),\n", " # so messages/tools are stored as JSON strings and parsed back when needed.\n", " \"messages_json\": json.dumps(msgs, ensure_ascii=False),\n", " \"tools_json\": json.dumps(row.get(\"tools\") or GLOBAL_TOOLS, ensure_ascii=False),\n", " }\n", "\n", "\n", "def normalize_all(rows):\n", " out, dropped = [], 0\n", " for r in rows:\n", " if MIN_HARD_VR_SCORE is not None:\n", " s = (r.get(\"metadata\") or {}).get(\"hard_vr_score\")\n", " if s is None or s < MIN_HARD_VR_SCORE:\n", " dropped += 1\n", " continue\n", " n = normalize_example(r)\n", " if n is None:\n", " dropped += 1\n", " else:\n", " out.append(n)\n", " print(f\"normalized: {len(out)}, dropped: {dropped}\")\n", " return out\n", "\n", "\n", "norm_train = normalize_all(raw_train)\n", "norm_eval = normalize_all(raw_eval) if raw_eval else None" ] }, { "cell_type": "markdown", "id": "30ebde15", "metadata": {}, "source": [ "### 3.1 Tokenizer and chat-template check\n", "Only the tokenizer is loaded here, no model weights, so this works without a GPU.\n", "\n", "The check confirms that the template **actually renders** the tool schemas, the tool calls with their arguments, the tool outputs and the reasoning. Some templates silently drop fields they do not know about. Read the printed text once to see what Gemma 4's tool-call markup looks like." ] }, { "cell_type": "code", "execution_count": 7, "id": "fde12aa8", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "vocab: 262144 | pad: | eos: \n", "{'tool schema in prompt': True, 'tool_call name': True, 'tool_call argument': True, 'tool response': True, 'reasoning (last turn)': True}\n", "<|turn>system\n", "<|think|>\n", "# Role and Identity\n", "\n", "You are the WMS Shorts Management Specialist sub-agent. You diagnose warehouse shorts and related allocation, inventory, shipment, order, picking, inbound, yard, location, customer, and item questions using direct WMS API access.\n", "\n", "Your output is a presentation-ready factual handoff to the parent orchestrator. Format it so the orchestrator can preserve it as the final user response without reformatting.\n", "\n", "\n", "## Tool Contract\n", "\n", "- Before any warehouse operation or WMS data-tool call, read the applicable task skills.\n", "- Select the most specific named WMS tool for the task, for example `get_short_shipment_lines`, `get_inventory`, `get_pick_work`, `allocate_wave`, or `process_cancel_pick`.\n", "- Use each tool's LLM-facing argument names exactly as defined in its schema, for example `warehouse_id`, `order_number`, `item_number`, `ship_id`, and `shipment_line_id`.\n", "- Retrieve enough data for the orchestrator to answer the user's request without inventing facts. Include raw IDs, display/link fields returned by tools, quantities, dates, reason/status descriptions, and any joined context needed for grouping or sorting.\n", "\n", "# Behaviour Rules\n", "\n", "1. Always prefer calling a tool over making assumptions about warehouse data.\n", "2. Never fabricate inventory data, location names, customer names, order IDs, or WMS statuses.\n", "3. If a tool call fails, inspect the error, adjust parameters and retry once. If the second attempt fails, explain the failure clearly withou \n", ".....\n", " level context with ship_id=TRN-SHIP-01285-01|TRN-SHIP-01285-04|TRN-SHIP-01285-03|TRN-SHIP-01285-02|TRN-SHIP-01285-05, warehouse=TRN-WH-1285. This supports grouping, status, customer impact, dates, and exact final ranking. Previous evidence: tool returned 5 records\n", "<|tool_call>call:get_shipments{limit:50,offset:0,ship_id:<|\"|>TRN-SHIP-01285-01|TRN-SHIP-01285-04|TRN-SHIP-01285-03|TRN-SHIP-01285-02|TRN-SHIP-01285-05<|\"|>,warehouse_id:<|\"|>TRN-WH-1285<|\"|>}<|tool_response>response:get_shipments{value:<|\"|>{\"records\":[{\"shipment_id\":\"TRN-SHIP-01285-05\",\"warehouse_id\":\"TRN-WH-1285\",\"client_id\":null,\"early_ship_date\":null,\"late_ship_date\":\"12:00 AM 01.01.2028 UTC\",\"shipment_status\":\"DERIVED_FROM_SHORT_SHIPMENT_LINES\"},{\"shipment_id\":\"TRN-SHIP-01285-01\",\"warehouse_id\":\"TRN-WH-1285\",\"client_id\":null,\"early_ship_date\":null,\"late_ship_date\":\"12:00 AM 22.02.2028 UTC\",\"shipment_status\":\"OPEN\"},{\"shipment_id\":\"TRN-SHIP-01285-02\",\"warehouse_id\":\"TRN-WH-1285\",\"client_id\":null,\"early_ship_date\":null,\"late_ship_date\":\"03:00 AM 23.03.2028 UTC\",\"shipment_status\":\"OPEN\"},{\"shipment_id\":\"TRN-SHIP-01285-03\",\"warehouse_id\":\"TRN-WH-1285\",\"client_id\":null,\"early_ship_date\":null,\"late_ship_date\":\"06:00 AM 24.04.2028 UTC\",\"shipment_status\":\"OPEN\"},{\"shipment_id\":\"TRN-SHIP-01285-04\",\"warehouse_id\":\"TRN-WH-1285\",\"client_id\":null,\"early_ship_date\":null,\"late_ship_date\":\"09:00 AM 25.05.2028 UTC\",\"shipment_status\":\"OPEN\"}],\"info\":\"Total size of data is 5 rows, returned rows from 1 to 5, rows left 0.\"}<|\"|>}<|channel>thought\n", "The required evidence has been gathered from the completed tool calls. Now answer from tool results only. Preserve exact counts, quantities, filters, requested top-k or sorting, and mention exclusions or mismatched rows when relevant. Last evidence: tool returned 5 records\n", "Returned confirmed NOAVINV short shipment lines with due-time context joined from shipment headers. Scope: warehouse `TRN-WH-1285`, wave `TRN-WAVE-01285`, short reason `NOAVINV`, offset `0`, limit `50`. Confirmed NOAVINV rows included: 4.\n", "\n", "| Due Time | Shipment | Shipment Line | Customer | Item | Short Qty | Order | Wave | Reason | Shipment Status |\n", "| --- | --- | --- | --- | --- | ---: | --- | --- | --- | --- |\n", "| 12:00 AM 22.02.2028 UTC | TRN-SHIP-01285-01 | TRN-SL-01285-01 | TRN-CUST-1285-1 | TRN-PART-1285-A | 42 | TRN-ORD-01285-01 | TRN-WAVE-01285 | NOAVINV (No Available Inventory) | OPEN |\n", "| 03:00 AM 23.03.2028 UTC | TRN-SHIP-01285-02 | TRN-SL-01285-02 | TRN-CUST-1285-2 | TRN-PART-1285-B | 8 | TRN-ORD-01285-02 | TRN-WAVE-01285 | NOAVINV (No Available Inventory) | OPEN |\n", "| 06:00 AM 24.04.2028 UTC | TRN-SHIP-01285-03 | TRN-SL-01285-03 | TRN-CUST-1285-3 | TRN-PART-1285-C | 21 | TRN-ORD-01285-03 | TRN-WAVE-01285 | NOAVINV (No Available Inventory) | OPEN |\n", "| 09:00 AM 25.05.2028 UTC | TRN-SHIP-01285-04 | TRN-SL-01285-04 | TRN-CUST-1285-4 | TRN-PART-1285-A | 34 | TRN-ORD-01285-04 | TRN-WAVE-01285 | NOAVINV (No Available Inventory) | OPEN |\n", "\n" ] } ], "source": [ "from transformers import AutoTokenizer\n", "\n", "tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)\n", "assert tokenizer.is_fast, \"a fast tokenizer is required (offset_mapping is used for masking)\"\n", "assert tokenizer.chat_template, \"the tokenizer has no chat_template\"\n", "if tokenizer.pad_token_id is None:\n", " tokenizer.pad_token = tokenizer.eos_token\n", "print(\"vocab:\", len(tokenizer), \"| pad:\", tokenizer.pad_token, \"| eos:\", tokenizer.eos_token)\n", "\n", "\n", "def render(messages, tools, add_generation_prompt=False):\n", " # Single place where text is produced from messages: used for training, masking and generation-eval.\n", " return tokenizer.apply_chat_template(messages, tools=tools or None, tokenize=False,\n", " add_generation_prompt=add_generation_prompt, **CHAT_TEMPLATE_KWARGS)\n", "\n", "\n", "_ex = norm_train[0]\n", "_msgs, _tools = json.loads(_ex[\"messages_json\"]), json.loads(_ex[\"tools_json\"])\n", "_txt = render(_msgs, _tools)\n", "_first_call = next((m for m in _msgs if m.get(\"tool_calls\")), None)\n", "_tool_msg = next((m for m in _msgs if m[\"role\"] == \"tool\"), None)\n", "_reason_msg = next((m for m in _msgs if m.get(REASONING_TEMPLATE_KEY)), None)\n", "checks = {\n", " \"tool schema in prompt\": (not _tools) or _tools[0][\"function\"][\"name\"] in _txt,\n", " \"tool_call name\": (_first_call is None) or _first_call[\"tool_calls\"][0][\"function\"][\"name\"] in _txt,\n", " \"tool_call argument\": (_first_call is None) or str(next(iter(_first_call[\"tool_calls\"][0][\"function\"][\"arguments\"].values()), \"\")) in _txt,\n", " \"tool response\": (_tool_msg is None) or (_tool_msg[\"content\"][:40] in _txt),\n", " # Reasoning of earlier turns may legitimately be stripped by the template; check the LAST reasoning turn.\n", " \"reasoning (last turn)\": (_reason_msg is None) or any(\n", " m.get(REASONING_TEMPLATE_KEY, \"\")[:40] in _txt for m in _msgs[::-1] if m.get(REASONING_TEMPLATE_KEY)),\n", "}\n", "print(checks)\n", "assert all(checks.values()), (\"The chat template did not render part of the data. Inspect the text below; for reasoning, \"\n", " \"try another REASONING_TEMPLATE_KEY or REASONING_MODE='drop'.\")\n", "print(_txt[:1500], \"\\n.....\\n\", _txt[-3000:])" ] }, { "cell_type": "markdown", "id": "d005275d", "metadata": {}, "source": [ "### 3.2 Build `input_ids` / `labels`\n", "**How the assistant spans are found.** For every assistant turn *i* the code renders:\n", "- `messages[:i]` with `add_generation_prompt=True`, which gives the text right before the model starts talking;\n", "- `messages[:i+1]`, which gives the text up to the end of that turn.\n", "\n", "The characters between the two are that turn's target. They include the end-of-turn token, so the model learns when to stop. Character spans are then mapped to tokens via `offset_mapping`.\n", "\n", "Why this approach: it does **not** hard-code any template tokens, so it keeps working if the template changes.\n", "\n", "**Status values per row:**\n", "- `ok` — the spans were found normally.\n", "- `fallback_prefix` — the generation prompt adds something absent from the full render (for example an empty thinking block). The role header is then trained too, which is harmless.\n", "- `prefix_mismatch` — the template rewrites earlier turns (typically by stripping reasoning from past turns). Such rows are dropped. If there are many of them, use `REASONING_MODE=\"drop\"`." ] }, { "cell_type": "code", "execution_count": 8, "id": "047fdeb0", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "system prompt: ~1640 tokens; 34 tool schemas: ~12947 tokens\n", "status: ok | tokens: 17220 | trainable: 1016\n", "> TRAIN: '<|channel>thought\\nStart by retrieving short shipment lines using warehouse=TRN-WH-1285, wave=TRN-WAVE-01285, short_reason=NOAVINV. This establishes the affected shipment lines, items, customers, quantities, and IDs needed for any later lookup.\\n<|tool_call>call:get_short_shipment_lines{limit:50,offset:0,short_reason_code:<|\"|>NOAVINV<|\"|>,warehouse_id:<|\"|>TRN-WH-1285<|\"|>,wave_number:<|\"|>TRN-WAVE-01285<|\"|>}<|tool_response>'\n", "> TRAIN: 'Use shipment IDs from the short-line result to fetch shipment-level context with ship_id=TRN-SHIP-01285-01|TRN-SHIP-01285-04|TRN-SHIP-01285-03|TRN-SHIP-01285-02|TRN-SHIP-01285-05, warehouse=TRN-WH-1285. This supports grouping, status, customer impact, dates, and exact final ranking. Previous evidence: tool returned 5 records\\n<|tool_call>call:get_shipments{limit:50,offset:0,ship_id:<|\"|>TRN-SHIP-01285-01|TRN-SHIP-01285-04|TRN-SHIP-01285-03|TRN-SHIP-01285-02|TRN-SHIP-01285-05<|\"|>,warehouse_id:<|\"|>TRN-WH-1285<|\"|>}<|tool_response>'\n", "> TRAIN: 'The required evidence has been gathered from the completed tool calls. Now answer from tool results only. Preserve exact counts, quantities, filters, requested top-k or sorting, and mention exclusions or mismatched rows when relevant. Last evidence: tool returned 5 records\\nReturned confirmed NOAVINV short shipment lines with due-time context joined from shipment headers. Scope: warehouse `TRN-WH-1285`, wave `TRN-WAVE-01285`, short reason `NOAVINV`, offset `0`, limit `50`. Confirmed NOAVINV rows included: 4.\\n\\n| Due Time | Shipment | Shipment Line | Customer | Item | Short Qty | Or\n" ] } ], "source": [ "def _common_prefix_len(a, b):\n", " n = min(len(a), len(b))\n", " i = 0\n", " while i < n and a[i] == b[i]:\n", " i += 1\n", " return i\n", "\n", "\n", "def build_features(ex):\n", " msgs, tools = json.loads(ex[\"messages_json\"]), json.loads(ex[\"tools_json\"])\n", " empty = {\"input_ids\": [], \"labels\": [], \"n_tokens\": 0, \"n_trainable\": 0}\n", " full = render(msgs, tools)\n", " spans, status = [], \"ok\"\n", " for i, m in enumerate(msgs):\n", " if m[\"role\"] != \"assistant\":\n", " continue\n", " prefix = render(msgs[:i], tools, add_generation_prompt=True)\n", " if not full.startswith(prefix):\n", " prefix = render(msgs[:i], tools, add_generation_prompt=False)\n", " status = \"fallback_prefix\"\n", " if not full.startswith(prefix):\n", " return {**empty, \"status\": \"prefix_mismatch\"}\n", " upto = render(msgs[: i + 1], tools)\n", " # A template may render the LAST message slightly differently (e.g. without a trailing newline),\n", " # so the end of the span is the longest common prefix of `upto` and `full`.\n", " end = _common_prefix_len(upto, full)\n", " if end <= len(prefix):\n", " return {**empty, \"status\": \"empty_span\"}\n", " spans.append((len(prefix), end))\n", "\n", " # add_special_tokens=False: the rendered text already contains ; adding another would double it.\n", " enc = tokenizer(full, add_special_tokens=False, return_offsets_mapping=True)\n", " ids, offs = enc[\"input_ids\"], enc[\"offset_mapping\"]\n", " labels = [-100] * len(ids)\n", " j = 0\n", " for k, (s, e) in enumerate(offs):\n", " while j < len(spans) and s >= spans[j][1]:\n", " j += 1\n", " if j == len(spans):\n", " break\n", " a, b = spans[j]\n", " if e > s and s >= a and e <= b: # token lies fully inside an assistant span\n", " labels[k] = ids[k]\n", " return {\"input_ids\": ids, \"labels\": labels, \"n_tokens\": len(ids),\n", " \"n_trainable\": sum(l != -100 for l in labels), \"status\": status}\n", "\n", "\n", "# How much of every sequence is fixed overhead (system prompt + tool schemas)?\n", "_sys = [m for m in _msgs if m[\"role\"] == \"system\"][:1]\n", "_t_sys_tools = len(tokenizer(render(_sys, _tools), add_special_tokens=False)[\"input_ids\"])\n", "_t_sys = len(tokenizer(render(_sys, None), add_special_tokens=False)[\"input_ids\"])\n", "print(f\"system prompt: ~{_t_sys} tokens; {len(_tools)} tool schemas: ~{_t_sys_tools - _t_sys} tokens\")\n", "\n", "# Visual mask check: print every contiguous trained chunk of the first example.\n", "# You should see ONLY assistant output (reasoning / tool calls / final answer), never tool results or the user prompt.\n", "_f = build_features(norm_train[0])\n", "print(\"status:\", _f[\"status\"], \"| tokens:\", _f[\"n_tokens\"], \"| trainable:\", _f[\"n_trainable\"])\n", "_chunks, _cur = [], []\n", "for t, l in zip(_f[\"input_ids\"], _f[\"labels\"]):\n", " if l == -100:\n", " if _cur:\n", " _chunks.append(_cur); _cur = []\n", " else:\n", " _cur.append(t)\n", "if _cur:\n", " _chunks.append(_cur)\n", "for c in _chunks:\n", " print(\"> TRAIN:\", repr(tokenizer.decode(c))[:600])" ] }, { "cell_type": "code", "execution_count": 9, "id": "d988a76e", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "tokenize train (num_proc=8): 14%|█▎ | 3518/25721 [01:00<02:56, 125.78 examples/s][azure.monitor.opentelemetry.exporter.export._base|WARNING]Retrying due to server response error: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response')).\n", "tokenize train (num_proc=8): 100%|██████████| 25721/25721 [04:37<00:00, 92.82 examples/s] \n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "[train] status: {'ok': 25721}\n", "\n", "Sequence length (tokens):\n" ] }, { "data": { "text/plain": [ "count 25721.0\n", "mean 17351.0\n", "std 2351.0\n", "min 14671.0\n", "50% 16733.0\n", "90% 21185.0\n", "95% 23018.0\n", "99% 28024.0\n", "max 32016.0\n", "dtype: float64" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "Share of tokens that contribute to the loss: 4.6%\n", " > 16384: 17039 trajectories (66.2%)\n", " > 32768: 0 trajectories (0.0%)\n", " > 65536: 0 trajectories (0.0%)\n" ] }, { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAABDEAAAFOCAYAAACfRoY+AAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjExLjIsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvgI3uAAAAAAlwSFlzAAAPYQAAD2EBqD+naQAAe7dJREFUeJzt3XdUFNfbB/AvUpYiIKCCBcSGYgNRsPeOJXZs2DWxxBpj1Pw0xiSaxESNBRWNihqxorHFGHtBRSX2FgtgjSK9LAL3/YOXieMusAsLuPL9nDPn7N55Zvbe2YWZffbeOwZCCAEiIiIiIiIiovdcscKuABERERERERGRJpjEICIiIiIiIiK9wCQGEREREREREekFJjGIiIiIiIiISC8wiUFEREREREREeoFJDCIiIiIiIiLSC0xiEBEREREREZFeYBKDiIiIiIiIiPQCkxgfoK1bt2LHjh2FXQ16y/3797F48WL8+++/hV2VQhMfH48lS5bg2bNnBfJ6J06cwLJlywrktajo+u2333DmzJnCrgZRkXX37l0sXrwYkZGRhfL6T58+xeLFi/Hw4UON4mNiYgr9eqCwj5kuXLhwAevXry/Q17x27RoWL16M2NjYAn1dyp6fnx+OHz9e2NWgAmYghBCFXQn6z44dO5CWlgYfH59c76Nhw4YwNTXlH7QW7t69iwMHDmDgwIEoVaqUzve/e/du9OjRAyE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HBASlBoEkNERERaePMGWLgw4/FXXxVqVXShfv36qF+/fp5jDAwMMHjwYAwePDhPMURERJT/tJ7YMyIiAr1790anTp1Qt25dzJs3D/369ZPWGxgYoGHDhmjcuDEqVaqEOXPmoFmzZnjz5g0AICkpCc+fP4eTk5Nsv05OTnjw4IHGMeoolUrExsbKFiIiIiIiIiL6MGg9sae1tTX69euH6OhoCCGwfPlydO/eHZUqVQIAjB07FjY2NlK8j48PXF1dsXr1aowbNw5KpRIAYG5uLttv8eLFkZycDAAaxagzf/58zJ07V9smEREREREREZEe0LonhpWVFXr37o2RI0fiwIEDKFGihCxx8HYCA8joPeHh4SHd7qx48eIwNDREVFSULC4yMlKaQVyTGHV4T3YiIiIiIiKiD5fWPTHeVqxYMbi4uCA8PDzbuJiYGGlODCMjI7i6uuLq1auymKtXr6JOnToax6ijUCigUChy0xQiIiIiIiIies9p1RNj48aNSE9Pl57fv38fhw8fRvPmzaWygIAApKWlSc8DAwNx7do1fPTRR1LZoEGDsG3bNjx+/BgAcOPGDRw8eBCDBg3SKoaIiIiIiIiIig6temJcvXoVs2fPhouLC5KSknDx4kX07dsXX3zxhRRz8+ZNVK5cGdWqVcOrV69w584dfP/99+jWrZsUM3nyZJw9exZubm5wd3dHSEgI+vfvL7tVmSYxRERERERERFR0aJXE+PHHH/HFF18gNDQUxsbGqFatGhwcHGQxCxYswLRp0xAaGgpzc3PUqFFDZR4LExMT7NmzB1euXEF4eDiqVKkCV1dXrWOIiIhIC2ZmwPXr/z2Ojy/c+hARERFpSes5Mezs7NC2bds8xwCAm5sb3Nzc8hxDREREGihWDKhZs7BrQURERJRrWt+dhIiIiIiIiIioMOTp7iRERESkR1JSgO++y3g8c2bh1oWIiIgoF5jEICIiKirevAHmzs14PG1a4daFiIiIKBc4nISIiIiIiIiI9AKTGERERERERESkF5jEICIiIiIiIiK9wCQGEREREREREekFJjGIiIiIiIiISC8wiUFEREREREREeoG3WCUiIioqTE2BCxf+e5yQULj1IcqB8xf7s1z3aEH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GIiIiIiIiISC8wiUFEREREREREeoFJDCIiIiIiIiLSC0xiEBEREREREZFe4C1WiYiIigqFAti27b/HiYmFWx8iIiIiLTGJQUREVFQYGQF9+hR2LYiIiIhyjcNJiIiIiIiIiEgvsCcGERFRUZGaCgQFZTzu0aNw60JERESUC0xiEBERFRVKJdC3b8bj+PjCrQsRERFRLjCJQURERHopPT0dZ86cwe3bt+Hg4IDWrVvDwsJCFuPn5welUikra9y4Mby8vGRlERER+OuvvwAAbdu2haOjo8rraRJDRERE+YtzYhAREZHe+fvvv1G7dm3MmjULFy5cwLx581ClShVcunRJFjdjxgz89ddfePTokbTExMTIYoKCglCtWjXs2rVLehyUOexGixgiIiLKf+yJQURERHrH2NgYQUFBcHFxkcp69OiBTz75BCEhIbLYoUOHonfv3mr3k5CQgJEjR+Lzzz/HV199BQD48ssvMWrUKHTo0AHm5uYaxRAREVHBYE8MIiIi0js1a9aUJTAAoFWrVrhz545KbHBwMFauXImDBw8iISFBtu7IkSN4/fo1Pv74Y6lszJgxiIyMxJEjRzSOISIiooLBJAYRERF9EHbv3o369evLyooVK4bLly8jJCQEU6ZMgaurq6ynxs2bN2FtbY0yZcpIZeXKlYOlpSVu3rypccy7lEolYmNjZQsRERHlHYeTEBERkd5bsGABzp49izNnzsjK//zzTymxkZqair59+2LAgAG4e/cuDAwMEBcXhxIlSqjsz8bGBnFxcQCgUcy75s+fj7lz5+atUURERKRCq54Yly9fho+PDxwcHGBnZ4eOHTsiNDRUFvPNN9/AwMBAtqg78QcEBMDFxQUKhQK1atXC3r17cxVDREREGjIxAdaty1hMTAq7NjqzatUqzJkzB1u3bkW9evVk697umWFkZIQJEybgn3/+wcOHDwEA5ubmahMRsbGx0lwXmsS8a8aMGYiJiZGWiIiIXLePiIiI/qNVEmP27Nno3bs3rly5gtu3b8PR0RFt2rTBkydPZHENGjSAEEJaoqOjZev/+OMPjBgxAl9++SWeP3+O4cOHo2fPnrIZxTWJISIiIi0YGwNDh2YsxsaFXRud8Pf3x4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ERERERERUdGhVRJj3rx5iI+PR/PmzWFgYCAtX331lRQzadIkfPvtt3B0dESTJk2QmJiI8+fPo1q1alJMx44dsXbtWsybNw8ODg5Yu3Ytdu7ciXr16mkVQ0RERERERERFh1YTeyYnJ+cY06RJExzKvH1bNgYPHozBgwfnOYaIiIiIiIiIioY83WKViIiI9IiJCbBs2X+Pk5IKtz5EREREWmISg4iIqKgwNgbGjfvvOZMYREREpGdydYtVIiIiIiIiIqKCxp4YRERERUVaGnDqVMbjLO4yRqQvnL/YX9hVICKiQsAkBhERUVGRnAy0apXxOD6+cOtCRERElAscTkJEREREREREeoE9MYiIiIgoX3HoBxER6Qp7YhARERERERGRXmASg4iIiIiIiIj0ApMYRERERERERKQXmMQgIiIiIiIiIr3AiT2JiIiKCmNj4Icf/nuclla49SEiIiLSEpMYRERERYWJCTBt2n/Pk5MLry5EREREucDhJERERERERESkF9gTg4iIqKhISwMuX8547OFRuHUhIiIiygUmMYiIiIqK5GTAyyvjcXx84daFiIiIKBc4nISIiIiIiIiI9AKTGERERKR3kpKS8Msvv8DNzQ2mpqaoUKECZs6cieR3Jit99eoVfHx8YGFhAQsLC/j4+ODVq1f5EkNERET5j0kMIiIi0jsHDx7EgwcPsHHjRsTExGDbtm0ICAjApEmTZHE+Pj4ICwvDrVu3cPPmTTx8+BA+Pj75EkNERET5j3NiEBERkd7p2bMnevbsKT1v0KABJk6ciO+//x4rV64EAISGhuLo0aM4e/YsnJycAAA//fQTmjdvjr///hvu7u46iyEiIqKCwZ4YRERE9EF48eIFrK2tpednz56FQqFAw4YNpbImTZrAxMQEZ8+e1WkMERERFQytemKkpaVh165dOHHiBN68eQNPT08MGTIExsbGsriIiAj4+fkhLCwMVatWxfjx41GyZMl8iSEiIiK6ceMG/Pz88NVXX0llL168gJ2dHQwMDKSyYsWKoWTJknjx4oVOY96lVCqhVCql57GxsTppJxERUVGnVU+MJk2aYMeOHahevTrc3d2xcOFCtGjRAikpKVLMo0eP4OHhgVu3bqFly5Y4deoU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8NRpUoVuLq6yuJ1FUNERERERERERYdWSYwePXpoHOvm5gY3N7cCiSEiIiIiIiKiD1+u7k5CREREesjYGPjss/8eq+ldSURERPQ+YxKDiIioqDAxAX788b/nycmFVxciIiKiXNDq7iRERERERERERIWFPTGIiIiKivR0IDw847GTU+HWhYiIiCgXmMQgIiIqKpKSgIoVMx7HxxduXYiIiIhygcNJiIiIiIiIiEgvMIlBRERERERERHqBSQwiIiIiIiIi0gtMYhARERERERGRXmASg4iIiIiIiIj0ApMYRERERERERKQXeItVIiKiosLICBg79r/HaWmFWx8iIiIiLTGJQUREVFQoFMDy5f89VyoLry5EREREucDhJERERERERESkF9gTg4iIqKgQAnj1KuNxyZKFWxciIiKiXGASg4iIqKhITARKl854HB9fuHUhIiIiygUOJyEiIiIiIiIivcCeGERERKS3rl27hk2bNgEAvv/+e5X1U6ZMQWJioqzso48+QqdOnWRlp06dwr59+wAAXbp0QbNmzVT2pUkMERER5S/2xCAiIiK91LFjRwwYMACXLl3Chg0b1Mb8+uuvEELA3d1dWuzt7WUxS5YsQfv27ZGeng4hBNq3b48lS5ZoHUNERET5jz0xSGPOX+zPct2jBZ0LsCZERETAN998g/r162PhwoW4fv16lnHt2rVD79691a57/fo1ZsyYgUWLFuGTTz4BADg5OeHzzz+Hr68vbG1tNYohIiKigpGrnhh37txBYGAgwsLCVNbdvHkTgYGBsmXXrl1q93P58mUEBQVle+GhSQwREREVPfXr19cobseOHZg0aRIWLVqkcu1y+PBhJCcno1+/flLZwIEDkZycjL/++kvjGCIiIioYWiUxLl68iDZt2qBr167o378/Tp06pRKza9cujB8/Hrt375aW/fvlv+ArlUp06dIFHTp0wMqVK9G0aVMMGTIE6enpWsUQERERZcfKygo2NjYoV64cjh49iho1auD333+X1t+7dw82NjYoUaKEVGZjYwNra2v8888/Gse8S6lUIjY2VrYQERFR3mk1nCQmJgYzZsxAmzZtUKxY1vmPKlWqIDAwMMv1ixYtQkhICK5cuYKyZcvi1q1bqFevHlq3bo0hQ4Zo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yS6skxosXL3Ds2DHp+blz52BkZITKlSvD09MTANCzZ0/UrVsXdevWxatXr7B8+XLUqVMHH3/8sbTd7NmzUb9+fXTv3h3e3t7YunUrFAoFJk+erFUMERERERERERUdWk3s+fLlS+zevRu7d++Gj48PXr16hd27dyM0NFSKOXHiBDw9PXHp0iW8fPkSCxcuxJkzZ2BhYSHFODk5ITQ0FO7u7jh37hzatm2LkJAQ2USemsQQERERERERUdGhVU+MWrVqITAwMNsYExMTDBs2DMOGDcs2rly5cpg3b16eY4iIiIiIiIioaND5LVaJiIiIiIiIiPJDgdydhIiIiN4DhoZA797/PU5LK9z6EBEREWmJSQwiIqKiwtQU2L79v+cpKYVXFyIiIqJc4HASIiIiIiIiItILTGIQERERERERkV7gcBIiIqKiIiEBKF4843F8fOHWhT44zl/sL+wq5El29X+0oHMB1oSIiLLDnhhEREREREREpBeYxCAiIiIiIiIivcAkBhERERERERHpBc6JQTrBcaRERERERESU39gTg4iIiIiIiIj0ApMYRERERERERKQXOJyEiIioqDA0BLy9/3uclla49SEiIiLSEpMYRERERYWpKbD/rTmMUlIKry5EREREucDhJERERERERESkF5jEICIiIiIiIiK9wCQGERFRUZGQAFhYZCwJCYVdGyIiIiKtcU4MIiKioiQxsbBrQERERJRr7IlBREREei08PBx37tzJNiYiIgIREREFEkNERET5h0kMIiIi0ks7duxAy5YtUb16dbRo0UJtzN27d+Hm5oaaNWuiVq1acHNzw927d/MlhoiIiPIfkxhERESkl44cOYI5c+bg66+/Vrs+PT0dvXr1QqVKlfD69Wu8evUKzs7O6NWrF9LT03UaQ0RERAVDqyRGQkIC/P394eHhAQMDA2zatEltXEBAAFxcXKBQKFCrVi3s3bs332KIiIioaPLz80OrVq2yXH/mzBlcv34d8+bNg5GREYyNjTF37lxcv34dZ8+e1WkMERERFQytkhjr1q3D+fPn4e/vn2XMH3/8gREjRuDLL7/E8+fPMXz4cPTs2ROXLl3SeQwRERFRVi5dugRzc3PUqlVLKnN3d4eZmZl0PaGrGCIiIioYW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V65cwerVqwFASjJkXlBkKl68OJKTkzWOUWf+/PmwtraWFkdHR521i4iIiPTPu9cSHTp0QFJSEu7cuQMAsLGxQWRkpMp2kZGRsLGx0TjmXTNmzEBMTIy0RERE5LUpREREhHxIYrx7MndycoKHhwdCQkIAZCQiDA0NERUVJYuLjIxEiRIlNI5RhxcMRERElJ2XL18CyBimCgB169ZFQkIC7t69K8XcunULiYmJqFu3rsYx71IoFLCyspItRERElHcFcnPzmJgYGBoaAgCMjIzg6uqKq1evymKuXr2KOnXqaByjDi8YiIiIspGUBHh6ZixJSYVdm3x36tQpnD59Wnr+8uVLzJkzB+7u7nBxcQEANG/eHJUrV8a3334rxX377beoXLkymjVrpnEMERERFQydJzECAgJkE3kGBgbi2rVr+Oijj6SyQYMGYdu2bXj8+DEA4MaNGzh48CAGDRqkVQwRERFpIT0duHgxY0lPL+za5Lvy5cvj66+/hqOjI+rXrw9nZ2fY2toiKChIijEyMsK2bdtw/PhxVKhQAU5OTjh16hS2b98OIyMjjWOIiIioYOj8zHvz5k1UrlwZ1apVw6tXr3Dnzh18//33stusTp48GWfPnoWbmxvc3d0REhKC/v37w9fXV6sYIiIioqxUrFgRf/75J54/f46IiAg4OzujVKlSKnEeHh64f/++1AO0Tp06KskJTWLeN5xwkoiIPkQ6P/suWLAA06ZNQ2hoKMzNzVGjRg2VeSxMTEywZ88eXLlyBeHh4ahSpQpcXV21jtEn2V1IEBERUf5xcHCAg4NDtjFGRkbw8PDIc4y+4HUJERHpq3z5CcHOzg5t27bNMc7NzQ1ubm55jiEiIiIiIiKiD1+BTOxJRERERERERJRXTGIQERERERERkV54v2ekIiIiIt0qWbKwa0BERESUa0xiEJHOcUZ8oveUhQXw8uV/z2NjC68uRERERLnA4SREREREREREpBfYE4OIssQeFURERERE9D5hEoOIiKioSEoCOnXKeHzwYOHWhagI4I8BRES6xyQG0QeCF0pElKP0dODEif8eExEREekZzolBRERERERERHqBPTEo37GHQOF7n96D96kuRERERESkX9gTg4iIiIiIiIj0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lStXIjw8HNWqVcOYMWNUJvTSJIbyX1BQEA4cOIBixYqhe/fu6NSpU2FXqcDt27cPmzZtUikfPnw42rdvLz2/evUq1q9fj9evX6N+/foYNWqUNM+FrmP0RXBwMJYsWaJ23dKlS1GqVCnp+V9//YWdO3ciJSUF7du3h4+Pj8o2uorRJxcvXsSuXbvw4sULlC9fHr1795buGpJJCIFNmzbh2LFjMDMzg4+PD5o3b54vMfosKCgIf/31F5YvXy4rT0xMxMqVK3HlyhWULl0aI0eORLVq1fIlRp+kpqbit99+w9mzZ2FmZob69eujX79+MDQ0lMU9f/4cfn5+ePjwISpXroyxY8fK/rZ1GfO+KNJJDCIiIiIiIiLSH5zYk4iIiIiIiIj0ApMYRERERERERKQXmMQgIiIiIiIiIr3AJAYRERERERER6QUmMYiIiIiIiIhILzCJQURERERERER6gUkMIiIiIiIiItILTGIQERERERERkV5gEoOIiIiIiIiI9AKTGERERERERESkF5jEICIiIiIiIiK9wCQGEREREREREemF/wMACDatFyoOcwAAAABJRU5ErkJggg==", "text/plain": [ "
" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from datasets import Dataset\n", "\n", "\n", "def tokenize_split(norm_rows, name):\n", " ds = Dataset.from_list(norm_rows)\n", " ds = ds.map(build_features, num_proc=min(NUM_PROC, max(1, len(norm_rows) // 50)), desc=f\"tokenize {name}\")\n", " st = Counter(ds[\"status\"])\n", " print(f\"[{name}] status: {dict(st)}\")\n", " if st.get(\"prefix_mismatch\", 0) or st.get(\"empty_span\", 0):\n", " print(\" WARNING: some rows could not be masked and will be dropped (see 3.2)\")\n", " return ds\n", "\n", "\n", "tok_train = tokenize_split(norm_train, \"train\")\n", "tok_eval = tokenize_split(norm_eval, \"eval\") if norm_eval else None\n", "\n", "lens = pd.Series(tok_train[\"n_tokens\"])\n", "trn = pd.Series(tok_train[\"n_trainable\"])\n", "print(\"\\nSequence length (tokens):\"); display(lens.describe(percentiles=[.5, .9, .95, .99]).round(0))\n", "print(f\"Share of tokens that contribute to the loss: {trn.sum() / max(lens.sum(), 1):.1%}\")\n", "for L in (16384, 32768, 65536):\n", " print(f\" > {L:>6}: {(lens > L).sum():>6} trajectories ({(lens > L).mean():.1%})\")\n", "\n", "import matplotlib.pyplot as plt\n", "fig, ax = plt.subplots(1, 2, figsize=(13, 3.5))\n", "ax[0].hist(lens, bins=60); ax[0].axvline(MAX_SEQ_LEN, color=\"r\", ls=\"--\"); ax[0].set_title(\"tokens per trajectory (red = MAX_SEQ_LEN)\")\n", "ax[1].hist(trn, bins=60); ax[1].set_title(\"trained (assistant) tokens per trajectory\")\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "51a9b8d9", "metadata": {}, "source": [ "### 3.3 Filter and split\n", "- **Filter:** rows longer than `MAX_SEQ_LEN` or without any trainable token are dropped.\n", "- **Eval split**, by priority:\n", " 1. a separate `EVAL_URL`;\n", " 2. `metadata.dataset_split` equal to `eval` / `validation` / `test`;\n", " 3. a seeded split **stratified by intent**, so every scenario is represented in eval." ] }, { "cell_type": "code", "execution_count": 10, "id": "b067a0c2", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[train] kept 25721 of 25721 (dropped: longer than MAX_SEQ_LEN=32768 or unmaskable)\n", "train: 24437 eval: 1284\n", "trained tokens per epoch: 19,676,515 | total tokens per epoch: 424,029,462\n" ] } ], "source": [ "def finalize(ds, name):\n", " before = len(ds)\n", " keep = [i for i, (s, n, t) in enumerate(zip(ds[\"status\"], ds[\"n_tokens\"], ds[\"n_trainable\"]))\n", " if s in (\"ok\", \"fallback_prefix\") and 0 < n <= MAX_SEQ_LEN and t > 0]\n", " ds = ds.select(keep)\n", " print(f\"[{name}] kept {len(ds)} of {before} (dropped: longer than MAX_SEQ_LEN={MAX_SEQ_LEN} or unmaskable)\")\n", " return ds\n", "\n", "\n", "tok_train = finalize(tok_train, \"train\")\n", "EVAL_SPLITS = (\"eval\", \"validation\", \"val\", \"test\")\n", "\n", "if tok_eval is not None:\n", " tok_eval = finalize(tok_eval, \"eval\")\n", "elif any(s in EVAL_SPLITS for s in tok_train[\"split\"]):\n", " is_eval = [s in EVAL_SPLITS for s in tok_train[\"split\"]]\n", " tok_eval = tok_train.select([i for i, e in enumerate(is_eval) if e])\n", " tok_train = tok_train.select([i for i, e in enumerate(is_eval) if not e])\n", "else:\n", " by_intent = defaultdict(list)\n", " for i, it in enumerate(tok_train[\"intent\"]):\n", " by_intent[it].append(i)\n", " rng = random.Random(SEED)\n", " eval_idx = []\n", " for it, idx in by_intent.items():\n", " rng.shuffle(idx)\n", " eval_idx += idx[: max(1, round(len(idx) * EVAL_FRACTION))] if len(idx) > 1 else []\n", " eval_set = set(eval_idx)\n", " tok_eval = tok_train.select(sorted(eval_set))\n", " tok_train = tok_train.select([i for i in range(len(tok_train)) if i not in eval_set])\n", "\n", "if N_EVAL_SAMPLES is not None and len(tok_eval) > N_EVAL_SAMPLES:\n", " tok_eval = tok_eval.select(range(N_EVAL_SAMPLES))\n", "assert len(tok_train) > 0 and len(tok_eval) > 0, \"empty train or eval split - increase N_SAMPLES\"\n", "\n", "# The Trainer only needs input_ids/labels. The metadata columns stay in tok_train/tok_eval for section 7.\n", "KEEP = [\"input_ids\", \"labels\"]\n", "train_ds = tok_train.remove_columns([c for c in tok_train.column_names if c not in KEEP])\n", "eval_ds = tok_eval.remove_columns([c for c in tok_eval.column_names if c not in KEEP])\n", "print(f\"train: {len(train_ds)} eval: {len(eval_ds)}\")\n", "print(f\"trained tokens per epoch: {sum(tok_train['n_trainable']):,} | total tokens per epoch: {sum(tok_train['n_tokens']):,}\")" ] }, { "cell_type": "markdown", "id": "7229381a", "metadata": {}, "source": [ "## 4. Model\n", "The model is loaded in **bf16**. At this size, 4-bit QLoRA would only cost accuracy, and 94 GB is enough.\n", "\n", "- **`lora`:** adapters are attached to the attention and MLP projections of the language model. The vision and audio towers stay untouched.\n", "- **`full`:** all weights are trainable except the frozen groups from the config.\n", "\n", "`use_gradient_checkpointing=\"unsloth\"` keeps only one activation per layer and offloads it to CPU RAM, then recomputes the rest in backward. This is what makes 32–64k context fit on one GPU." ] }, { "cell_type": "code", "execution_count": 11, "id": "73acb335", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "==((====))== Unsloth 2026.11.2: Fast Gemma4 patching. Transformers: 5.22.1.\n", " \\\\ /| NVIDIA H100 NVL. Num GPUs = 1. Max memory: 93.085 GB. Platform: Linux.\n", "O^O/ \\_/ \\ Torch: 2.14.1+cu130. CUDA: 9.0. CUDA Toolkit: 13.0. Triton: 3.8.0\n", "\\ / Bfloat16 = TRUE. FA [Xformers = None. FA2 = False]\n", " \"-____-\" Free license: http://github.com/unslothai/unsloth\n", "Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored!\n", "Unsloth: QLoRA and full finetuning all not selected. Switching to 16bit LoRA.\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading weights: 100%|██████████| 2076/2076 [00:01<00:00, 1051.09it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Unsloth: compiling each transformer block as one region (Gemma4TextDecoderLayer).\n", "attention implementation: sdpa\n", "trainable parameters: 139.5M of 8,080.6M (1.73%)\n" ] } ], "source": [ "import torch\n", "assert UNSLOTH_OK and torch.cuda.is_available(), \"a GPU and unsloth are required from here on\"\n", "\n", "# FastModel handles multimodal checkpoints such as Gemma 4. It returns (model, processor);\n", "# the text tokenizer loaded above is used for training, the processor is saved with the model for serving.\n", "model, processor = FastModel.from_pretrained(\n", " model_name=MODEL_NAME,\n", " max_seq_length=MAX_SEQ_LEN,\n", " dtype=torch.bfloat16,\n", " load_in_4bit=False,\n", " load_in_8bit=False,\n", " full_finetuning=(TRAIN_MODE == \"full\"),\n", " use_gradient_checkpointing=\"unsloth\",\n", ")\n", "\n", "\n", "def _attn_impl(m):\n", " cfg = m.config\n", " return getattr(cfg, \"_attn_implementation\", None) or getattr(getattr(cfg, \"text_config\", cfg), \"_attn_implementation\", None)\n", "\n", "\n", "print(\"attention implementation:\", _attn_impl(model))\n", "if _attn_impl(model) == \"eager\":\n", " # eager attention materializes the T x T score matrix: ~68 GB per layer at 64k -> guaranteed OOM.\n", " print(\"WARNING: eager attention at 32-64k = O(T^2) memory -> OOM. sdpa / flash_attention_2 is required.\")\n", "\n", "if TRAIN_MODE == \"lora\":\n", " model = FastModel.get_peft_model(\n", " model,\n", " finetune_vision_layers=False, # text-only data\n", " finetune_language_layers=True,\n", " finetune_attention_modules=True, # q/k/v/o\n", " finetune_mlp_modules=True, # gate/up/down\n", " r=LORA_R, lora_alpha=LORA_ALPHA, lora_dropout=LORA_DROPOUT, bias=\"none\",\n", " random_state=SEED,\n", " use_gradient_checkpointing=\"unsloth\",\n", " )\n", "else:\n", " pats = [re.compile(p) for p in FULL_FT_FREEZE_PATTERNS]\n", " frozen = Counter()\n", " for n, p in model.named_parameters():\n", " if any(r.search(n) for r in pats) or (FULL_FT_FREEZE_EMBEDDINGS and re.search(r\"embed_tokens\\.|lm_head\", n)):\n", " p.requires_grad_(False)\n", " frozen[\".\".join(n.split(\".\")[:3])] += p.numel()\n", " # Check this list: it shows exactly which parameter groups got frozen.\n", " print(\"frozen groups:\", {k: f\"{v/1e6:.0f}M\" for k, v in frozen.most_common()})\n", "\n", "trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", "total = sum(p.numel() for p in model.parameters())\n", "print(f\"trainable parameters: {trainable/1e6:,.1f}M of {total/1e6:,.1f}M ({trainable/total:.2%})\")" ] }, { "cell_type": "code", "execution_count": 12, "id": "44f43895", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "forward accepts token_type_ids: False\n" ] } ], "source": [ "def _forward_params(m):\n", " base = m.get_base_model() if hasattr(m, \"get_base_model\") else m\n", " return set(inspect.signature(base.forward).parameters)\n", "\n", "\n", "# Multimodal Gemma checkpoints require `token_type_ids` in training mode (0 = text token).\n", "NEEDS_TOKEN_TYPE_IDS = \"token_type_ids\" in _forward_params(model)\n", "print(\"forward accepts token_type_ids:\", NEEDS_TOKEN_TYPE_IDS)\n", "\n", "\n", "class CausalCollator:\n", " # Right-pads a batch. Labels are already shifted inside the model, so labels == input_ids except\n", " # masked positions (-100). With batch size 1 there is no padding at all.\n", " def __init__(self, pad_id):\n", " self.pad_id = pad_id\n", "\n", " def __call__(self, feats):\n", " L = max(len(f[\"input_ids\"]) for f in feats)\n", " ids = torch.full((len(feats), L), self.pad_id, dtype=torch.long)\n", " lab = torch.full((len(feats), L), -100, dtype=torch.long)\n", " att = torch.zeros((len(feats), L), dtype=torch.long)\n", " for i, f in enumerate(feats):\n", " n = len(f[\"input_ids\"])\n", " ids[i, :n] = torch.tensor(f[\"input_ids\"])\n", " lab[i, :n] = torch.tensor(f[\"labels\"])\n", " att[i, :n] = 1\n", " batch = {\"input_ids\": ids, \"labels\": lab, \"attention_mask\": att}\n", " if NEEDS_TOKEN_TYPE_IDS:\n", " batch[\"token_type_ids\"] = torch.zeros_like(ids)\n", " return batch\n", "\n", "\n", "collator = CausalCollator(tokenizer.pad_token_id)" ] }, { "cell_type": "markdown", "id": "e900deb9", "metadata": {}, "source": [ "## 5. Memory probe on the longest example\n", "This runs one forward + backward pass on the longest training trajectory, which is the worst case for activation memory.\n", "\n", "Optimizer states are **not** included: they are allocated lazily at the first optimizer step. For full FT, add roughly 2 bytes per trainable parameter for 8-bit Adam (~10 GB).\n", "\n", "If this cell OOMs, use a lower `MAX_SEQ_LEN`, or switch to `TRAIN_MODE=\"lora\"`." ] }, { "cell_type": "code", "execution_count": 13, "id": "0b870288", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "longest training example: 32016 tokens\n", "peak: 35.6 GB of 93.1 GB -> headroom 57.5 GB\n" ] } ], "source": [ "longest = max(range(len(train_ds)), key=lambda i: len(train_ds[i][\"input_ids\"]))\n", "print(\"longest training example:\", len(train_ds[longest][\"input_ids\"]), \"tokens\")\n", "\n", "torch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats()\n", "model.train()\n", "batch = {k: v.to(model.device) for k, v in collator([train_ds[longest]]).items()}\n", "out = model(**batch)\n", "out.loss.backward()\n", "model.zero_grad(set_to_none=True) # discard these gradients; this was only a probe\n", "del out, batch\n", "peak = torch.cuda.max_memory_allocated() / 2**30\n", "total_gb = torch.cuda.get_device_properties(0).total_memory / 2**30\n", "print(f\"peak: {peak:.1f} GB of {total_gb:.1f} GB -> headroom {total_gb - peak:.1f} GB\")\n", "torch.cuda.empty_cache()" ] }, { "cell_type": "markdown", "id": "976448b9", "metadata": {}, "source": [ "## 6. Training\n", "A plain `transformers.Trainer` is used on the pre-tokenized data. The masking is already done, so no SFT-specific data handling is needed. Unsloth's patches (fused loss, gradient-checkpointing offload) live inside the model, so they apply here as well." ] }, { "cell_type": "code", "execution_count": 14, "id": "e8f936de", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "optimizer steps per epoch: 1528\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "==((====))== Unsloth - 2x faster free finetuning | Num GPUs used = 1\n", " \\\\ /| Num examples = 24,437 | Num Epochs = 2 | Total steps = 3,056\n", "O^O/ \\_/ \\ Batch size per device = 1 | Gradient accumulation steps = 16\n", "\\ / Data Parallel GPUs = 1 | Total batch size (1 x 16 x 1) = 16\n", " \"-____-\" Trainable parameters = 139,526,144 of 8,080,626,976 (1.73% trained)\n", "[azure.monitor.opentelemetry.exporter.export._base|WARNING]Retrying due to server response error: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response')).\n" ] }, { "data": { "text/html": [ "\n", "
\n", " \n", " \n", " [ 28/3056 1:09:17 < 134:28:51, 0.01 it/s, Epoch 0.02/2]\n", "
\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
StepTraining LossValidation Loss

" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stderr", "output_type": "stream", "text": [ "[opentelemetry.attributes|WARNING]Invalid type `` for attribute value. Expected one of bool, str, None, bytes, int, float or a Mapping or Sequence of those types. Value's __str__ method will be called if it exists, otherwise the value will be replaced with None.\n" ] }, { "ename": "KeyboardInterrupt", "evalue": "", "output_type": "error", "traceback": [ "\u001b[31m---------------------------------------------------------------------------\u001b[39m", "\u001b[31mKeyboardInterrupt\u001b[39m Traceback (most recent call last)", "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[14]\u001b[39m\u001b[32m, line 46\u001b[39m\n\u001b[32m 42\u001b[39m callbacks=[PersistCheckpoints()] \u001b[38;5;28;01mif\u001b[39;00m PERSIST_URL \u001b[38;5;28;01mand\u001b[39;00m PERSIST_CHECKPOINTS \u001b[38;5;28;01melse\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m)\n\u001b[32m 43\u001b[39m \n\u001b[32m 44\u001b[39m print(f\"optimizer steps per epoch: {math.ceil(len(train_ds) / HP[\u001b[33m'gradient_accumulation_steps'\u001b[39m])}\")\n\u001b[32m 45\u001b[39m torch.cuda.reset_peak_memory_stats()\n\u001b[32m---> \u001b[39m\u001b[32m46\u001b[39m train_result = trainer.train()\n\u001b[32m 47\u001b[39m print(train_result.metrics)\n\u001b[32m 48\u001b[39m print(f\"peak GPU memory during training: {torch.cuda.max_memory_allocated()/\u001b[32m2\u001b[39m**\u001b[32m30\u001b[39m:.1f} GB\")\n", "\u001b[36mFile \u001b[39m\u001b[32m/anaconda/envs/gemma4/lib/python3.12/site-packages/unsloth_zoo/fast_grad_params.py:220\u001b[39m, in \u001b[36m_wrap_trainer..wrapped\u001b[39m\u001b[34m(self, *args, **kwargs)\u001b[39m\n\u001b[32m 217\u001b[39m \u001b[38;5;129m@functools\u001b[39m.wraps(train)\n\u001b[32m 218\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mwrapped\u001b[39m(\u001b[38;5;28mself\u001b[39m, *args, **kwargs):\n\u001b[32m 219\u001b[39m bump() \u001b[38;5;66;03m# every train() rebuilds the tuples once\u001b[39;00m\n\u001b[32m--> \u001b[39m\u001b[32m220\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[30;43mtrain\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43mself\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43margs\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43mkwargs\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n", "\u001b[36mFile \u001b[39m\u001b[32m/anaconda/envs/gemma4/lib/python3.12/site-packages/unsloth/models/_gc_train_scope.py:80\u001b[39m, in \u001b[36mpatch_trainer_train_gc_scope..train\u001b[39m\u001b[34m(self, *args, **kwargs)\u001b[39m\n\u001b[32m 77\u001b[39m \u001b[38;5;129m@functools\u001b[39m.wraps(original_train)\n\u001b[32m 78\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mtrain\u001b[39m(\u001b[38;5;28mself\u001b[39m, *args, **kwargs):\n\u001b[32m 79\u001b[39m \u001b[38;5;28;01mwith\u001b[39;00m unsloth_gc_train_scope():\n\u001b[32m---> \u001b[39m\u001b[32m80\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[30;43moriginal_train\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43mself\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43margs\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43mkwargs\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n", "\u001b[36mFile \u001b[39m\u001b[32m/anaconda/envs/gemma4/lib/python3.12/site-packages/transformers/trainer.py:1559\u001b[39m, in \u001b[36mTrainer.train\u001b[39m\u001b[34m(self, resume_from_checkpoint, trial, ignore_keys_for_eval)\u001b[39m\n\u001b[32m 1557\u001b[39m ctx = suppress_progress_bars() \u001b[38;5;28;01mif\u001b[39;00m args.push_to_hub \u001b[38;5;28;01melse\u001b[39;00m contextlib.nullcontext()\n\u001b[32m 1558\u001b[39m \u001b[38;5;28;01mwith\u001b[39;00m ctx:\n\u001b[32m-> \u001b[39m\u001b[32m1559\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[30;43minner_training_loop\u001b[39;49m\u001b[30;43m(\u001b[39;49m\n\u001b[32m 1560\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43margs\u001b[39;49m\u001b[30;43m=\u001b[39;49m\u001b[30;43margs\u001b[39;49m\u001b[30;43m,\u001b[39;49m\n\u001b[32m 1561\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43mresume_from_checkpoint\u001b[39;49m\u001b[30;43m=\u001b[39;49m\u001b[30;43mresume_from_checkpoint\u001b[39;49m\u001b[30;43m,\u001b[39;49m\n\u001b[32m 1562\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43mtrial\u001b[39;49m\u001b[30;43m=\u001b[39;49m\u001b[30;43mtrial\u001b[39;49m\u001b[30;43m,\u001b[39;49m\n\u001b[32m 1563\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43mignore_keys_for_eval\u001b[39;49m\u001b[30;43m=\u001b[39;49m\u001b[30;43mignore_keys_for_eval\u001b[39;49m\u001b[30;43m,\u001b[39;49m\n\u001b[32m 1564\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43m)\u001b[39;49m\n", "\u001b[36mFile \u001b[39m\u001b[32m:83\u001b[39m, in \u001b[36m_fast_inner_training_loop\u001b[39m\u001b[34m(self, batch_size, args, resume_from_checkpoint, trial, ignore_keys_for_eval)\u001b[39m\n", "\u001b[36mFile \u001b[39m\u001b[32m/anaconda/envs/gemma4/lib/python3.12/site-packages/transformers/trainer.py:1889\u001b[39m, in \u001b[36mTrainer._run_epoch\u001b[39m\u001b[34m(self, model, epoch, train_dataloader, steps_in_epoch, num_update_steps_per_epoch, trial, ignore_keys_for_eval, start_time, resume_from_checkpoint, epochs_trained, steps_trained_in_current_epoch)\u001b[39m\n\u001b[32m 1887\u001b[39m sync_context = functools.partial(\u001b[38;5;28mself\u001b[39m.accelerator.no_sync, model=model)\n\u001b[32m 1888\u001b[39m \u001b[38;5;28;01mwith\u001b[39;00m sync_context():\n\u001b[32m-> \u001b[39m\u001b[32m1889\u001b[39m tr_loss_step = \u001b[30;43mself\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43mtraining_step\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43mmodel\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43minputs\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43mnum_items_in_batch\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n\u001b[32m 1891\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m (\n\u001b[32m 1892\u001b[39m \u001b[38;5;28mself\u001b[39m.args.logging_nan_inf_filter\n\u001b[32m 1893\u001b[39m \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m is_torch_xla_available()\n\u001b[32m 1894\u001b[39m \u001b[38;5;129;01mand\u001b[39;00m (torch.isnan(tr_loss_step) \u001b[38;5;129;01mor\u001b[39;00m torch.isinf(tr_loss_step))\n\u001b[32m 1895\u001b[39m ):\n\u001b[32m 1896\u001b[39m \u001b[38;5;66;03m# if loss is nan or inf simply add the average of previous logged losses\u001b[39;00m\n\u001b[32m 1897\u001b[39m \u001b[38;5;28mself\u001b[39m._tr_loss += \u001b[38;5;28mself\u001b[39m._tr_loss / (\u001b[32m1\u001b[39m + \u001b[38;5;28mself\u001b[39m.state.global_step - \u001b[38;5;28mself\u001b[39m._globalstep_last_logged)\n", "\u001b[36mFile \u001b[39m\u001b[32m/anaconda/envs/gemma4/lib/python3.12/site-packages/unsloth/models/_utils.py:6385\u001b[39m, in \u001b[36mpatch_gradient_accumulation_fix.._unsloth_training_step_settling_fallbacks\u001b[39m\u001b[34m(self, *args, **kwargs)\u001b[39m\n\u001b[32m 6381\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m 6382\u001b[39m _apply_pending_eager_fallbacks()\n\u001b[32m 6383\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m Exception:\n\u001b[32m 6384\u001b[39m \u001b[38;5;28;01mpass\u001b[39;00m\n\u001b[32m-> \u001b[39m\u001b[32m6385\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m _training_step_before_settle(self, *args, **kwargs)\n", "\u001b[36mFile \u001b[39m\u001b[32m:76\u001b[39m, in \u001b[36m_unsloth_training_step\u001b[39m\u001b[34m(***failed resolving arguments***)\u001b[39m\n", "\u001b[36mFile \u001b[39m\u001b[32m/anaconda/envs/gemma4/lib/python3.12/site-packages/accelerate/accelerator.py:2861\u001b[39m, in \u001b[36mAccelerator.backward\u001b[39m\u001b[34m(self, loss, **kwargs)\u001b[39m\n\u001b[32m 2859\u001b[39m \u001b[38;5;28mself\u001b[39m.lomo_backward(loss, learning_rate)\n\u001b[32m 2860\u001b[39m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[32m-> \u001b[39m\u001b[32m2861\u001b[39m \u001b[30;43mloss\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43mbackward\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43mkwargs\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n", "\u001b[36mFile \u001b[39m\u001b[32m/anaconda/envs/gemma4/lib/python3.12/site-packages/torch/_tensor.py:623\u001b[39m, in \u001b[36mTensor.backward\u001b[39m\u001b[34m(self, gradient, retain_graph, create_graph, inputs)\u001b[39m\n\u001b[32m 613\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m has_torch_function_unary(\u001b[38;5;28mself\u001b[39m):\n\u001b[32m 614\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m handle_torch_function(\n\u001b[32m 615\u001b[39m Tensor.backward,\n\u001b[32m 616\u001b[39m (\u001b[38;5;28mself\u001b[39m,),\n\u001b[32m (...)\u001b[39m\u001b[32m 621\u001b[39m inputs=inputs,\n\u001b[32m 622\u001b[39m )\n\u001b[32m--> \u001b[39m\u001b[32m623\u001b[39m \u001b[30;43mtorch\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43mautograd\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43mbackward\u001b[39;49m\u001b[30;43m(\u001b[39;49m\n\u001b[32m 624\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43mself\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43mgradient\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43mretain_graph\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43mcreate_graph\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43minputs\u001b[39;49m\u001b[30;43m=\u001b[39;49m\u001b[30;43minputs\u001b[39;49m\n\u001b[32m 625\u001b[39m \u001b[30;43m\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n", "\u001b[36mFile \u001b[39m\u001b[32m/anaconda/envs/gemma4/lib/python3.12/site-packages/torch/autograd/__init__.py:395\u001b[39m, in \u001b[36mbackward\u001b[39m\u001b[34m(tensors, grad_tensors, retain_graph, create_graph, grad_variables, inputs)\u001b[39m\n\u001b[32m 390\u001b[39m retain_graph = create_graph\n\u001b[32m 392\u001b[39m \u001b[38;5;66;03m# The reason we repeat the same comment below is that\u001b[39;00m\n\u001b[32m 393\u001b[39m \u001b[38;5;66;03m# some Python versions print out the first line of a multi-line function\u001b[39;00m\n\u001b[32m 394\u001b[39m \u001b[38;5;66;03m# calls in the traceback and some print out the last line\u001b[39;00m\n\u001b[32m--> \u001b[39m\u001b[32m395\u001b[39m \u001b[30;43m_engine_run_backward\u001b[39;49m\u001b[30;43m(\u001b[39;49m\n\u001b[32m 396\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43mtensors\u001b[39;49m\u001b[30;43m,\u001b[39;49m\n\u001b[32m 397\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43mgrad_tensors_\u001b[39;49m\u001b[30;43m,\u001b[39;49m\n\u001b[32m 398\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43mretain_graph\u001b[39;49m\u001b[30;43m,\u001b[39;49m\n\u001b[32m 399\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43mcreate_graph\u001b[39;49m\u001b[30;43m,\u001b[39;49m\n\u001b[32m 400\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43minputs_tuple\u001b[39;49m\u001b[30;43m,\u001b[39;49m\n\u001b[32m 401\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43mallow_unreachable\u001b[39;49m\u001b[30;43m=\u001b[39;49m\u001b[30;43;01mTrue\u001b[39;49;00m\u001b[30;43m,\u001b[39;49m\n\u001b[32m 402\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43maccumulate_grad\u001b[39;49m\u001b[30;43m=\u001b[39;49m\u001b[30;43;01mTrue\u001b[39;49;00m\u001b[30;43m,\u001b[39;49m\n\u001b[32m 403\u001b[39m \u001b[30;43m\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n", "\u001b[36mFile \u001b[39m\u001b[32m/anaconda/envs/gemma4/lib/python3.12/site-packages/torch/autograd/graph.py:1072\u001b[39m, in \u001b[36m_engine_run_backward\u001b[39m\u001b[34m(t_outputs, *args, **kwargs)\u001b[39m\n\u001b[32m 1069\u001b[39m torch._C._stash_obj_in_tls(\u001b[33m\"\u001b[39m\u001b[33mcontext\u001b[39m\u001b[33m\"\u001b[39m, contextvars.copy_context())\n\u001b[32m 1071\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m-> \u001b[39m\u001b[32m1072\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[30;43mVariable\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43m_execution_engine\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43mrun_backward\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43;03m# Calls into the C++ engine to run the backward pass\u001b[39;49;00m\n\u001b[32m 1073\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43mt_outputs\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43margs\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43mkwargs\u001b[39;49m\n\u001b[32m 1074\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43m)\u001b[39;49m \u001b[38;5;66;03m# Calls into the C++ engine to run the backward pass\u001b[39;00m\n\u001b[32m 1075\u001b[39m \u001b[38;5;28;01mfinally\u001b[39;00m:\n\u001b[32m 1076\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m attach_logging_hooks:\n", "\u001b[31mKeyboardInterrupt\u001b[39m: " ] }, { "ename": "KeyboardInterrupt", "evalue": "", "output_type": "error", "traceback": [ "\u001b[31m---------------------------------------------------------------------------\u001b[39m", "\u001b[31mKeyboardInterrupt\u001b[39m Traceback (most recent call last)", "\u001b[36mFile \u001b[39m\u001b[32m/anaconda/envs/gemma4/lib/python3.12/inspect.py:999\u001b[39m, in \u001b[36mgetmodule\u001b[39m\u001b[34m(object, _filename)\u001b[39m\n\u001b[32m 997\u001b[39m \u001b[38;5;66;03m# Try the cache again with the absolute file name\u001b[39;00m\n\u001b[32m 998\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m--> \u001b[39m\u001b[32m999\u001b[39m file = \u001b[30;43mgetabsfile\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43mobject\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43m_filename\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n\u001b[32m 1000\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m (\u001b[38;5;167;01mTypeError\u001b[39;00m, \u001b[38;5;167;01mFileNotFoundError\u001b[39;00m):\n\u001b[32m 1001\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m\n", "\u001b[36mFile \u001b[39m\u001b[32m/anaconda/envs/gemma4/lib/python3.12/inspect.py:982\u001b[39m, in \u001b[36mgetabsfile\u001b[39m\u001b[34m(object, _filename)\u001b[39m\n\u001b[32m 977\u001b[39m \u001b[38;5;250m\u001b[39m\u001b[33;03m\"\"\"Return an absolute path to the source or compiled file for an object.\u001b[39;00m\n\u001b[32m 978\u001b[39m \n\u001b[32m 979\u001b[39m \u001b[33;03mThe idea is for each object to have a unique origin, so this routine\u001b[39;00m\n\u001b[32m 980\u001b[39m \u001b[33;03mnormalizes the result as much as possible.\"\"\"\u001b[39;00m\n\u001b[32m 981\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m _filename \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[32m--> \u001b[39m\u001b[32m982\u001b[39m _filename = \u001b[30;43mgetsourcefile\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43mobject\u001b[39;49m\u001b[30;43m)\u001b[39;49m \u001b[38;5;129;01mor\u001b[39;00m getfile(\u001b[38;5;28mobject\u001b[39m)\n\u001b[32m 983\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m os.path.normcase(os.path.abspath(_filename))\n", "\u001b[36mFile \u001b[39m\u001b[32m/anaconda/envs/gemma4/lib/python3.12/inspect.py:970\u001b[39m, in \u001b[36mgetsourcefile\u001b[39m\u001b[34m(object)\u001b[39m\n\u001b[32m 968\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m filename\n\u001b[32m 969\u001b[39m \u001b[38;5;66;03m# only return a non-existent filename if the module has a PEP 302 loader\u001b[39;00m\n\u001b[32m--> \u001b[39m\u001b[32m970\u001b[39m module = \u001b[30;43mgetmodule\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43mobject\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43mfilename\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n\u001b[32m 971\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mgetattr\u001b[39m(module, \u001b[33m'\u001b[39m\u001b[33m__loader__\u001b[39m\u001b[33m'\u001b[39m, \u001b[38;5;28;01mNone\u001b[39;00m) \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[32m 972\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m filename\n", "\u001b[36mFile \u001b[39m\u001b[32m/anaconda/envs/gemma4/lib/python3.12/inspect.py:1007\u001b[39m, in \u001b[36mgetmodule\u001b[39m\u001b[34m(object, _filename)\u001b[39m\n\u001b[32m 1004\u001b[39m \u001b[38;5;66;03m# Update the filename to module name cache and check yet again\u001b[39;00m\n\u001b[32m 1005\u001b[39m \u001b[38;5;66;03m# Copy sys.modules in order to cope with changes while iterating\u001b[39;00m\n\u001b[32m 1006\u001b[39m \u001b[38;5;28;01mfor\u001b[39;00m modname, module \u001b[38;5;129;01min\u001b[39;00m sys.modules.copy().items():\n\u001b[32m-> \u001b[39m\u001b[32m1007\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m ismodule(module) \u001b[38;5;129;01mand\u001b[39;00m \u001b[30;43mhasattr\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43mmodule\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43m'\u001b[39;49m\u001b[30;43m__file__\u001b[39;49m\u001b[30;43m'\u001b[39;49m\u001b[30;43m)\u001b[39;49m:\n\u001b[32m 1008\u001b[39m f = module.\u001b[34m__file__\u001b[39m\n\u001b[32m 1009\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m f == _filesbymodname.get(modname, \u001b[38;5;28;01mNone\u001b[39;00m):\n\u001b[32m 1010\u001b[39m \u001b[38;5;66;03m# Have already mapped this module, so skip it\u001b[39;00m\n", "\u001b[31mKeyboardInterrupt\u001b[39m: " ] } ], "source": [ "from transformers import Trainer, TrainingArguments, TrainerCallback\n", "\n", "\n", "class PersistCheckpoints(TrainerCallback):\n", " # Uploads each checkpoint to the share right after the Trainer saved it. on_save runs after the old checkpoints\n", " # were rotated out (save_total_limit), so the folder is complete and stable. A failed upload only warns:\n", " # the checkpoint is still on the local disk, and training must not die because of the network.\n", " def on_save(self, args, state, control, **kwargs):\n", " ckpt = Path(args.output_dir) / f\"checkpoint-{state.global_step}\"\n", " if state.is_world_process_zero and ckpt.is_dir():\n", " try:\n", " upload_dir_to_share(ckpt, f\"{RUN_NAME}/{ckpt.name}\")\n", " except Exception as e:\n", " print(f\"[warn] checkpoint upload failed, training continues: {type(e).__name__}: {e}\")\n", "\n", "args = TrainingArguments(\n", " output_dir=OUTPUT_DIR,\n", " per_device_train_batch_size=1, # one 32-64k trajectory per forward pass\n", " per_device_eval_batch_size=1,\n", " gradient_accumulation_steps=HP[\"gradient_accumulation_steps\"],\n", " num_train_epochs=HP[\"num_train_epochs\"],\n", " max_steps=MAX_STEPS,\n", " learning_rate=HP[\"learning_rate\"],\n", " lr_scheduler_type=\"cosine\",\n", " warmup_steps=HP[\"warmup_ratio\"], # transformers 5: warmup_ratio was removed; a float in [0, 1) is a ratio\n", " weight_decay=HP[\"weight_decay\"],\n", " optim=HP[\"optim\"],\n", " max_grad_norm=1.0,\n", " bf16=True,\n", " gradient_checkpointing=False, # already enabled by Unsloth; enabling it here too would double-wrap it\n", " logging_steps=LOGGING_STEPS,\n", " eval_strategy=\"steps\", eval_steps=EVAL_STEPS,\n", " save_strategy=\"steps\", save_steps=SAVE_STEPS, save_total_limit=SAVE_TOTAL_LIMIT,\n", " prediction_loss_only=True, # never gather eval logits: T x 262k vocab = tens of GB per example\n", " remove_unused_columns=False,\n", " dataloader_num_workers=2,\n", " report_to=REPORT_TO,\n", " seed=SEED,\n", ")\n", "\n", "trainer = Trainer(model=model, args=args, train_dataset=train_ds, eval_dataset=eval_ds, data_collator=collator,\n", " callbacks=[PersistCheckpoints()] if PERSIST_URL and PERSIST_CHECKPOINTS else None)\n", "\n", "print(f\"optimizer steps per epoch: {math.ceil(len(train_ds) / HP['gradient_accumulation_steps'])}\")\n", "torch.cuda.reset_peak_memory_stats()\n", "train_result = trainer.train()\n", "print(train_result.metrics)\n", "print(f\"peak GPU memory during training: {torch.cuda.max_memory_allocated()/2**30:.1f} GB\")" ] }, { "cell_type": "code", "execution_count": null, "id": "8c546b78", "metadata": {}, "outputs": [], "source": [ "# Eval loss on held-out trajectories. It is computed on assistant tokens only, like the training loss.\n", "metrics = trainer.evaluate()\n", "metrics[\"eval_ppl\"] = math.exp(metrics[\"eval_loss\"]) if metrics.get(\"eval_loss\", 99) < 20 else float(\"inf\")\n", "print(metrics)" ] }, { "cell_type": "markdown", "id": "447c66c2", "metadata": {}, "source": [ "## 7. Generation check: does the model call the right tools?\n", "Loss alone does not tell you whether the model behaves correctly. This check takes every assistant turn of a few eval trajectories, gives the model the **reference** history up to that turn (teacher forcing) and lets it generate greedily. It then compares the result with the reference:\n", "- **tool-call turns:** the set of tool names in the generated text must equal the reference set;\n", "- **final turns:** the generated text must contain **no** tool names.\n", "\n", "The tool names are searched as plain text. This works for any tool-call markup, but it does **not** validate the arguments. For a proper evaluation use the repo's evaluator / verifiable rewards on the saved model." ] }, { "cell_type": "code", "execution_count": null, "id": "2f6cc10d", "metadata": {}, "outputs": [], "source": [ "ALL_TOOL_NAMES = sorted(train_stats[\"all_tools\"])\n", "# Word-boundary-like regex: `get_order` must not match inside `get_order_lines`.\n", "_name_re = {n: re.compile(rf\"(? (the runtime then injects the tool result)\n", "# and a normal turn with . Without the first one, generate() would hallucinate a tool response.\n", "STOP_IDS = sorted({tokenizer.eos_token_id, *[tokenizer.convert_tokens_to_ids(t) for t in (\"\", \"<|tool_response>\")\n", " if tokenizer.convert_tokens_to_ids(t) != tokenizer.unk_token_id]})\n", "print(\"stop token ids:\", STOP_IDS)\n", "\n", "FastModel.for_inference(model)\n", "rows = []\n", "for ex in tok_eval.select(range(min(N_GEN_EVAL_DIALOGS, len(tok_eval)))):\n", " msgs, tools = json.loads(ex[\"messages_json\"]), json.loads(ex[\"tools_json\"])\n", " for i, m in enumerate(msgs):\n", " if m[\"role\"] != \"assistant\":\n", " continue\n", " expected = {tc[\"function\"][\"name\"] for tc in m.get(\"tool_calls\") or []}\n", " prompt = render(msgs[:i], tools, add_generation_prompt=True)\n", " enc = tokenizer(prompt, add_special_tokens=False, return_tensors=\"pt\").to(model.device)\n", " with torch.no_grad():\n", " gen = model.generate(**enc, max_new_tokens=1024 if expected else 2048, do_sample=False,\n", " eos_token_id=STOP_IDS, pad_token_id=tokenizer.pad_token_id)\n", " text = tokenizer.decode(gen[0, enc[\"input_ids\"].shape[1]:], skip_special_tokens=False)\n", " got = tools_in(text)\n", " rows.append({\"prompt_id\": ex[\"prompt_id\"], \"turn\": i, \"kind\": \"tool_call\" if expected else \"final\",\n", " \"expected\": sorted(expected), \"got\": sorted(got), \"match\": got == expected, \"sample\": text[:300]})\n", "\n", "res = pd.DataFrame(rows)\n", "display(res.groupby(\"kind\")[\"match\"].agg([\"mean\", \"count\"]))\n", "display(res[~res.match].head(20))\n", "FastModel.for_training(model)" ] }, { "cell_type": "markdown", "id": "18d80a1b", "metadata": {}, "source": [ "## 8. Save\n", "- **LoRA:** the notebook saves the adapter (small) **and** a merged bf16 model (~16 GB). The merged model can be served directly with vLLM, without peft.\n", "- **Full FT:** the notebook saves the full model.\n", "\n", "`run_summary.json` stores the config and the metrics, so you can tell runs apart later.\n", "\n", "If `PERSIST_URL` is set, `final/` is then uploaded to `//final/` (section 1.1). Re-running this cell after a failed upload only sends the missing files." ] }, { "cell_type": "code", "execution_count": null, "id": "f504c118", "metadata": {}, "outputs": [], "source": [ "final_dir = Path(OUTPUT_DIR) / \"final\"\n", "if TRAIN_MODE == \"lora\":\n", " model.save_pretrained(final_dir / \"adapter\")\n", " processor.save_pretrained(final_dir / \"adapter\")\n", " model.save_pretrained_merged(str(final_dir / \"merged_16bit\"), processor, save_method=\"merged_16bit\")\n", "else:\n", " model.save_pretrained(final_dir)\n", " processor.save_pretrained(final_dir)\n", "\n", "json.dump({\"train\": train_result.metrics, \"eval\": metrics,\n", " \"generation_check\": res.groupby(\"kind\")[\"match\"].mean().to_dict(),\n", " \"config\": {\"TRAIN_MODE\": TRAIN_MODE, \"MODEL_NAME\": MODEL_NAME, \"MAX_SEQ_LEN\": MAX_SEQ_LEN, \"HP\": HP,\n", " \"RUN_NAME\": RUN_NAME, \"PERSIST_URL\": PERSIST_URL and PERSIST_URL.split(\"?\")[0],\n", " \"DATA_URL\": DATA_URL, \"N_SAMPLES\": N_SAMPLES, \"n_train\": len(train_ds), \"n_eval\": len(eval_ds),\n", " \"STRIP_ROUTING_HINTS\": STRIP_ROUTING_HINTS, \"REASONING_MODE\": REASONING_MODE,\n", " \"MIN_HARD_VR_SCORE\": MIN_HARD_VR_SCORE, \"LORA\": [LORA_R, LORA_ALPHA, LORA_DROPOUT]}},\n", " open(final_dir / \"run_summary.json\", \"w\"), indent=2, default=str)\n", "print(\"saved to\", final_dir)\n", "\n", "# Copy the final model to the persistent share (the local /mnt copy disappears when the instance stops).\n", "if PERSIST_URL:\n", " FINAL_URL = upload_dir_to_share(final_dir, f\"{RUN_NAME}/final\")" ] }, { "cell_type": "code", "execution_count": 15, "id": "77022b68-9a59-42b6-8110-16e75651c729", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "with attention_mask 17000 tok: 9.25 s/fwd+bwd -> 1,837 tok/s\n", "without attention_mask 17000 tok: 9.30 s/fwd+bwd -> 1,828 tok/s\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "USDT:2026-11-05 14:22:16 721523:721523 SyncActivityProfilerHandler.cpp:39] profiler_start\n", "USDT:2026-11-05 14:22:25 721523:721523 SyncActivityProfilerHandler.cpp:46] profiler_stop\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "---------------------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ \n", " Name Self CPU % Self CPU CPU total % CPU total CPU time avg Self CUDA Self CUDA % CUDA total CUDA time avg # of Calls \n", "---------------------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ \n", " autograd::engine::evaluate_function: CompiledFunctionBackward 0.01% 1.434ms 25.55% 4.005s 91.023ms 0.000us 0.00% 7.768s 176.544ms 44 \n", " CompiledFunctionBackward 0.23% 35.979ms 25.53% 4.003s 90.979ms 0.000us 0.00% 7.767s 176.531ms 44 \n", " aten::_scaled_dot_product_efficient_attention_backward 0.01% 946.659us 2.57% 402.958ms 11.513ms 0.000us 0.00% 5.450s 155.708ms 35 \n", " aten::_efficient_attention_backward 0.01% 948.665us 2.56% 401.529ms 11.472ms 5.448s 58.75% 5.450s 155.708ms 35 \n", "fmha_cutlassB_bf16_aligned_128x64_k65536_sm80(PyTorchMemEffAttentio... 0.00% 0.000us 0.00% 0.000us 0.000us 5.448s 58.75% 5.448s 155.652ms 35 \n", "## Call CompiledFxGraph f7enr2rdjww4ecs62khdzk5tthhy5ikpnoe7g5bp42a... 0.11% 17.408ms 7.21% 1.131s 59.508ms 0.000us 0.00% 3.173s 167.002ms 19 \n", " CompiledFunction 0.21% 32.166ms 11.42% 1.791s 20.822ms 0.000us 0.00% 2.778s 32.297ms 86 \n", "## Call CompiledFxGraph fzgnxyyuhw5m4rfpzmqdqwor6p5fmu444uvo2s76mj6... 0.07% 10.445ms 8.44% 1.324s 88.235ms 0.000us 0.00% 2.403s 160.201ms 15 \n", " aten::_scaled_dot_product_efficient_attention 0.01% 811.732us 1.82% 284.932ms 4.070ms 0.000us 0.00% 1.709s 24.413ms 70 \n", " aten::_efficient_attention_forward 0.01% 1.184ms 1.81% 283.651ms 4.052ms 1.709s 18.43% 1.709s 24.413ms 70 \n", "fmha_cutlassF_bf16_aligned_32x128_gmem_sm80(PyTorchMemEffAttention:... 0.00% 0.000us 0.00% 0.000us 0.000us 1.709s 18.43% 1.709s 24.411ms 70 \n", " Torch-Compiled Region: 2/12 0.02% 3.168ms 3.56% 557.759ms 14.678ms 0.000us 0.00% 1.275s 33.544ms 38 \n", "## Call CompiledFxGraph f2rudne2ch3ovntmr6fvd5pkv6lnyczxe7estk7kaly... 0.20% 31.236ms 3.43% 537.353ms 14.141ms 0.000us 0.00% 1.275s 33.544ms 38 \n", " Torch-Compiled Region: 2/16 0.01% 2.124ms 4.10% 643.132ms 21.438ms 0.000us 0.00% 1.026s 34.215ms 30 \n", "## Call CompiledFxGraph fmn66qylwr5lqwicbswmvnulki7nv5ocbdhl7o3ccxy... 0.14% 22.031ms 4.02% 630.627ms 21.021ms 0.000us 0.00% 1.026s 34.215ms 30 \n", "---------------------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ \n", "Self CPU time total: 15.677s\n", "Self CUDA time total: 9.274s\n", "\n" ] } ], "source": [ "import time, torch\n", "from torch.profiler import profile, ProfilerActivity\n", "\n", "model.train()\n", "idx = min(range(len(train_ds)), key=lambda i: abs(len(train_ds[i][\"input_ids\"]) - 17000)) # typical length\n", "base = {k: v.to(model.device) for k, v in collator([train_ds[idx]]).items()}\n", "n = base[\"input_ids\"].shape[1]\n", "\n", "def bench(batch, label, iters=3):\n", " def step():\n", " out = model(**batch); out.loss.backward(); model.zero_grad(set_to_none=True)\n", " step(); torch.cuda.synchronize() # warm-up (compilation)\n", " t = time.time()\n", " for _ in range(iters):\n", " step()\n", " torch.cuda.synchronize()\n", " dt = (time.time() - t) / iters\n", " print(f\"{label:28s} {n} tok: {dt:5.2f} s/fwd+bwd -> {n/dt:7,.0f} tok/s\")\n", " return step\n", "\n", "bench(base, \"with attention_mask\")\n", "step = bench({k: v for k, v in base.items() if k != \"attention_mask\"}, \"without attention_mask\")\n", "\n", "with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof:\n", " step(); torch.cuda.synchronize()\n", "print(prof.key_averages().table(sort_by=\"device_time_total\", row_limit=15, max_name_column_width=70))" ] }, { "cell_type": "code", "execution_count": 17, "id": "9cc00f7c-0512-4184-8b64-b6ddbb0a7748", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "==((====))== Unsloth 2026.11.2: Fast Gemma4 patching. Transformers: 5.22.1.\n", " \\\\ /| NVIDIA H100 NVL. Num GPUs = 1. Max memory: 93.085 GB. Platform: Linux.\n", "O^O/ \\_/ \\ Torch: 2.14.1+cu130. CUDA: 9.0. CUDA Toolkit: 13.0. Triton: 3.8.0\n", "\\ / Bfloat16 = TRUE. FA [Xformers = None. FA2 = False]\n", " \"-____-\" Free license: http://github.com/unslothai/unsloth\n", "Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored!\n", "Unsloth: QLoRA and full finetuning all not selected. Switching to 16bit LoRA.\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading weights: 100%|██████████| 2076/2076 [00:01<00:00, 1054.58it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "text attention: flex_attention | audio: eager\n", "Unsloth: Gemma4TextDecoderLayer block compile failed (LoweringException: TypeError: unsupported operand type(s) for &: 'FloorDiv' and 'Add'); retrying with flex_attention outside the block.\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Traceback (most recent call last):\n", " File \"/tmp/ipykernel_721523/4134936975.py\", line 17, in bench_impl\n", " step(); torch.cuda.synchronize() # warm-up (flex compiles its kernels on the first call)\n", " ^^^^^^\n", " File \"/tmp/ipykernel_721523/4134936975.py\", line 15, in step\n", " out = m(**base); out.loss.backward(); m.zero_grad(set_to_none=True)\n", " ^^^^^^^^^^^^^^^^^^^\n", " File \"/anaconda/envs/gemma4/lib/python3.12/site-packages/torch/_tensor.py\", line 623, in backward\n", " torch.autograd.backward(\n", "torch.utils.checkpoint.CheckpointError: torch.utils.checkpoint: A different number of tensors was saved during the original forward and recomputation.\n", "Number of tensors saved during forward: 80\n", "Number of tensors saved during recomputation: 77.\n", "\n", "Tip: To see a more detailed error message, either pass `debug=True` to\n", "`torch.utils.checkpoint.checkpoint(...)` or wrap the code block\n", "with `with torch.utils.checkpoint.set_checkpoint_debug_enabled(True):` to\n", "enable checkpoint‑debug mode globally.\n", "\n", "If this error occurs under torch.compile with automatic_dynamic_shapes enabled,\n", "it may be because the recomputation selected a different compiled graph than the\n", "forward pass (e.g., a dynamic graph instead of the original static graph).\n", "To fix this, either:\n", " - Use torch._dynamo.mark_dynamic() to explicitly mark varying dimensions as\n", " dynamic upfront, avoiding the static-to-dynamic transition.\n", " - Call torch._C._dynamo.eval_frame._set_lru_cache(False) to disable LRU cache\n", " reordering, which can change which graph is checked first between forward\n", " and recompute.\n", "See https://github.com/pytorch/pytorch/issues/166926 for more details and\n", "workaround examples.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "flex_attention FAILED: CheckpointError: torch.utils.checkpoint: A different number of tensors was saved during the original forward and recomputation.\n", "Number of tensors saved during forward: 80\n", "Number of tensors saved during recomputation: 77.\n", "\n", "Tip: To see a more detailed error message, either pass `debug=True` to\n", "`torch.utils.checkpoint.checkpoint(...)` or wrap the code block\n", "with `with torch.utils.checkpoint.set_checkpoint_debug_enabled(True):` to\n", "enable checkpoint‑debug mode globally.\n", "\n", "If this error occurs under torch.compile with automatic_dynamic_shapes enabled,\n", "it may be because the recomputation selected a different compiled graph than the\n", "forward pass (e.g., a dynamic graph instead of the original static graph).\n", "To fix this, either:\n", " - Use torch._dynamo.mark_dynamic() to explicitly mark varying dimensions as\n", " dynamic\n" ] } ], "source": [ "def bench_impl(text_impl, iters=3):\n", " m, _ = FastModel.from_pretrained(model_name=MODEL_NAME, max_seq_length=MAX_SEQ_LEN, dtype=torch.bfloat16,\n", " load_in_4bit=False, use_gradient_checkpointing=\"unsloth\")\n", " # Per-submodel attention: only the text model gets the new implementation; audio stays eager (its only option).\n", " m.set_attn_implementation({\"\": text_impl, \"text_config\": text_impl,\n", " \"vision_config\": \"sdpa\", \"audio_config\": \"eager\"})\n", " print(\"text attention:\", m.config.text_config._attn_implementation,\n", " \"| audio:\", getattr(m.config.audio_config, \"_attn_implementation\", None))\n", " m = FastModel.get_peft_model(m, finetune_vision_layers=False, finetune_language_layers=True,\n", " finetune_attention_modules=True, finetune_mlp_modules=True,\n", " r=LORA_R, lora_alpha=LORA_ALPHA, lora_dropout=0.0, bias=\"none\",\n", " random_state=SEED, use_gradient_checkpointing=\"unsloth\")\n", " m.train()\n", " def step():\n", " out = m(**base); out.loss.backward(); m.zero_grad(set_to_none=True)\n", " try:\n", " step(); torch.cuda.synchronize() # warm-up (flex compiles its kernels on the first call)\n", " torch.cuda.reset_peak_memory_stats()\n", " t = time.time()\n", " for _ in range(iters):\n", " step()\n", " torch.cuda.synchronize()\n", " dt = (time.time() - t) / iters\n", " n = base[\"input_ids\"].shape[1]\n", " print(f\"{text_impl:15s} {n} tok: {dt:5.2f} s -> {n/dt:7,.0f} tok/s, peak {torch.cuda.max_memory_allocated()/2**30:.1f} GB\")\n", " except Exception as e:\n", " import traceback; traceback.print_exc(limit=3)\n", " print(f\"{text_impl} FAILED: {type(e).__name__}: {str(e)[:800]}\")\n", " del m; gc.collect(); torch.cuda.empty_cache()\n", "\n", "bench_impl(\"flex_attention\")" ] } ], "metadata": { "accelerator": "GPU", "kernelspec": { "display_name": "gemma4", "language": "python", "name": "gemma4" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.16" } }, "nbformat": 4, "nbformat_minor": 5 }