{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "x_wPZgziQKXy" }, "source": [ "To run this, press \"*Runtime*\" and press \"*Run all*\" on a **free** Tesla T4 Google Colab instance!\n", "
\n", "\n", "This notebook is an **ASFT / ASFT+ demo** (Anchored Supervised Fine-Tuning).\n", "\n", "Credits:\n", "- ASFT paper & reference implementation: https://github.com/zhuchichi56/ASFT\n", "- ASFT+ (this optimized Unsloth integration + extra speed/perf optimizations): Hasan Can Solakoğlu X/Twitter @HCSolakoglu\n", "\n", "To install Unsloth your local device, follow [our guide](https://docs.unsloth.ai/get-started/install-and-update). This notebook is licensed [LGPL-3.0](https://github.com/unslothai/notebooks?tab=LGPL-3.0-1-ov-file#readme).\n", "\n", "You will learn how to do [data prep](#Data), how to [train](#Train), how to [run the model](#Inference), & [how to save it](#Save)\n" ] }, { "cell_type": "markdown", "metadata": { "id": "t-ahwuyvQKXz" }, "source": [ "### News" ] }, { "cell_type": "markdown", "metadata": { "id": "TiJUkQ5MQKX0" }, "source": [ "\n", "Introducing FP8 precision training for faster RL inference. [Read Blog](https://docs.unsloth.ai/new/fp8-reinforcement-learning).\n", "\n", "Unsloth's [Docker image](https://hub.docker.com/r/unsloth/unsloth) is here! Start training with no setup & environment issues. [Read our Guide](https://docs.unsloth.ai/new/how-to-train-llms-with-unsloth-and-docker).\n", "\n", "[gpt-oss RL](https://docs.unsloth.ai/new/gpt-oss-reinforcement-learning) is now supported with the fastest inference & lowest VRAM. Try our [new notebook](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/gpt-oss-(20B)-GRPO.ipynb) which creates kernels!\n", "\n", "Introducing [Vision](https://docs.unsloth.ai/new/vision-reinforcement-learning-vlm-rl) and [Standby](https://docs.unsloth.ai/basics/memory-efficient-rl) for RL! Train Qwen, Gemma etc. VLMs with GSPO - even faster with less VRAM.\n", "\n", "Visit our docs for all our [model uploads](https://docs.unsloth.ai/get-started/all-our-models) and [notebooks](https://docs.unsloth.ai/get-started/unsloth-notebooks).\n" ] }, { "cell_type": "markdown", "metadata": { "id": "vXSL0oj6QKX0" }, "source": [ "### Installation" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "krAQhz2yQKX0" }, "outputs": [], "source": [ "%%capture\n", "import os, re\n", "\n", "IN_COLAB = \"COLAB_\" in \"\".join(os.environ.keys())\n", "\n", "if not IN_COLAB:\n", " # ASFT demo: if you're running this notebook from the Unsloth repo/branch,\n", " # an editable install is the most reliable way to ensure ASFTTrainer is present.\n", " if os.path.exists(\"pyproject.toml\"):\n", " %pip install -e \".[cu126-torch290]\"\n", " else:\n", " %pip install -U unsloth\n", "else:\n", " # Do this only in Colab notebooks! Otherwise use pip install unsloth / pip install -e .\n", " import torch; v = re.match(r\"[0-9]{1,}\\.[0-9]{1,}\", str(torch.__version__)).group(0)\n", " xformers = \"xformers==\" + (\"0.0.33.post1\" if v==\"2.9\" else \"0.0.32.post2\" if v==\"2.8\" else \"0.0.29.post3\")\n", " %pip install --no-deps bitsandbytes accelerate {xformers} peft trl triton cut_cross_entropy unsloth_zoo\n", " %pip install sentencepiece protobuf \"datasets==4.3.0\" \"huggingface_hub>=0.34.0\" hf_transfer\n", " %pip install --no-deps unsloth\n", "\n", "%pip install transformers==4.56.2\n", "%pip install --no-deps trl==0.22.2" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# In Colab, clone the ASFT branch of Unsloth for ASFTTrainer\n", "!git clone -b asft-plus https://github.com/hcsolakoglu/unsloth.git\n", "%cd unsloth" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!pip install -e \".[cu126-torch290]\"" ] }, { "cell_type": "markdown", "metadata": { "id": "S68-v0avQKX1" }, "source": [ "### Unsloth" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 300, "referenced_widgets": [ "6e3c281f112b4a86af7a3ef95933d221", "92395f250a154006923aaf9ea0a9c30b", "f84bfc5390054ec687c157c4d68199a6", "4228734651ca45e19fc7bda79817f9b3", "4613edbbec6846edb5b1677c25d542b6", "d032fe2ba5d647d99026fdade758c0cd", "e9971d220fe24552a1e9aa299765cfb9", "2be29a4553ad4dfea8a9bc620c81a3ae", "94cbb87829d1486899e2ff6325c2ecdf", "f878c2e00bc240c7b0333cce950080e1", "6b908368de51428585552dfef6a83088", "ac5eacaaee8346c080e54ea7a52648a4", "7981edf408d54d41bbeac42da7492c6b", "2b848e5a85bc42bc87945fd9ed5db038", "e88c33f37d6849e0b1a6b41254104cb9", "33843107b93647b28985bfc37ea781ca", "76e5410e286a4a5abd6c213a38aa38bb", "ae7e90a811f94e75997d6a9ed1be8596", "bb9f3379310d4b04be694996f3137b28", "75082ba15db445df907f5612976590ae", "89934c4f26834f15b9889ec36fee3b65", "e887160635cb4803b9f33845df615ec6", "1c7bc5fdb7dd4c39af8d4c2c504ec3ed", "843a27e619534ea8914f9d36386c364b", "8f5adc70fbf248f2811527f620553be5", "4ffb4b2f015046fb94c1115ed0397a20", "5a232ed040f94633a2a374031284c1f6", "2006be31c09349738e221295bb84939f", "07055fc12b0841aaa5317f8252b5d347", "1eb90e686e214122ae763b1b79ae321d", "7a935956348e47c68fbdf05ddf4752f3", "8653acb618ad4e76bbf1daa00ea71238", "e3c3bd9c4c124b0a8c88c83c1fc747d3", "1bd75ddaf57c4438a4e2c3070b9cef65", "a3a3ef6d6337403cabea8b23f7c3021b", "c2ea0a3f01f34ffa8c94ab9b5098e9da", "68ea1d7cb8274a639b3fb5326f4218c3", "39fef7b257614a0595f39355fa226b69", "d125995cc0934239a01ba01b78529f21", "634ae4c6cfe04673b1cdc9c9cac4cbf9", "d7f92e8332374313bee87ccd427446a4", "36799fbcd90d43128620ff98225a825d", "5310346dd579424fa676b8e8e64790e7", "0c1835f404db4846bb13b5da8d8f4447", "29c5b713f07043dda51820523e5c8ff3", "d7375f0f048841b29a20601c122666e8", "f433ced9bfcd4a57ba691d3c1caeed08", "da8ffc70820a48f5a12c6d4b5967015b", "1a6db9aea6a64ae3aaef51d6265b35b2", "331f516c7a76456d801bc2a2feb228aa", "9be9074028da42d39d044a78393a861f", "51cd9026b1664819a67712996ca97bd5", "ea55293415ca48a4be97c2e1e4769122", "8ea52b105a7e44978caca33c0e7e815b", "3662f1445ef34a50b462e601ed31bb69" ] }, "id": "QmUBVEnvCDJv", "outputId": "0a47b925-663d-4543-9c61-994a6302f3c5" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "🦥 Unsloth: Will patch your computer to enable 2x faster free finetuning.\n", "==((====))== Unsloth 2024.8: Fast Llama patching. Transformers = 4.44.2.\n", " \\\\ /| GPU: Tesla T4. Max memory: 14.748 GB. Platform = Linux.\n", "O^O/ \\_/ \\ Pytorch: 2.4.0+cu121. CUDA = 7.5. CUDA Toolkit = 12.1.\n", "\\ / Bfloat16 = FALSE. FA [Xformers = 0.0.27.post2. FA2 = False]\n", " \"-____-\" Free Apache license: http://github.com/unslothai/unsloth\n", "Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored!\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "6e3c281f112b4a86af7a3ef95933d221", "version_major": 2, "version_minor": 0 }, "text/plain": [ "model.safetensors: 0%| | 0.00/5.70G [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "ac5eacaaee8346c080e54ea7a52648a4", "version_major": 2, "version_minor": 0 }, "text/plain": [ "generation_config.json: 0%| | 0.00/230 [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "1c7bc5fdb7dd4c39af8d4c2c504ec3ed", "version_major": 2, "version_minor": 0 }, "text/plain": [ "tokenizer_config.json: 0%| | 0.00/50.6k [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "1bd75ddaf57c4438a4e2c3070b9cef65", "version_major": 2, "version_minor": 0 }, "text/plain": [ "tokenizer.json: 0%| | 0.00/9.09M [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "29c5b713f07043dda51820523e5c8ff3", "version_major": 2, "version_minor": 0 }, "text/plain": [ "special_tokens_map.json: 0%| | 0.00/345 [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from unsloth import FastLanguageModel\n", "import torch\n", "max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!\n", "dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+\n", "load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.\n", "\n", "# 4bit pre quantized models we support for 4x faster downloading + no OOMs.\n", "fourbit_models = [\n", " \"unsloth/Meta-Llama-3.1-8B-bnb-4bit\", # Llama-3.1 15 trillion tokens model 2x faster!\n", " \"unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit\",\n", " \"unsloth/Meta-Llama-3.1-70B-bnb-4bit\",\n", " \"unsloth/Meta-Llama-3.1-405B-bnb-4bit\", # We also uploaded 4bit for 405b!\n", " \"unsloth/Mistral-Nemo-Base-2407-bnb-4bit\", # New Mistral 12b 2x faster!\n", " \"unsloth/Mistral-Nemo-Instruct-2407-bnb-4bit\",\n", " \"unsloth/mistral-7b-v0.3-bnb-4bit\", # Mistral v3 2x faster!\n", " \"unsloth/mistral-7b-instruct-v0.3-bnb-4bit\",\n", " \"unsloth/Phi-3.5-mini-instruct\", # Phi-3.5 2x faster!\n", " \"unsloth/Phi-3-medium-4k-instruct\",\n", " \"unsloth/gemma-2-9b-bnb-4bit\",\n", " \"unsloth/gemma-2-27b-bnb-4bit\", # Gemma 2x faster!\n", "] # More models at https://huggingface.co/unsloth\n", "\n", "model, tokenizer = FastLanguageModel.from_pretrained(\n", " model_name = \"unsloth/Meta-Llama-3.1-8B\",\n", " max_seq_length = max_seq_length,\n", " dtype = dtype,\n", " load_in_4bit = load_in_4bit,\n", " # token = \"hf_...\", # use one if using gated models like meta-llama/Llama-2-7b-hf\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "SXd9bTZd1aaL" }, "source": [ "We now add LoRA adapters so we only need to update 1 to 10% of all parameters!" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "6bZsfBuZDeCL", "outputId": "3e2a4618-6aa0-4f1c-d3a0-0ec45eb33237" }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Unsloth 2024.8 patched 32 layers with 32 QKV layers, 32 O layers and 32 MLP layers.\n" ] } ], "source": [ "model = FastLanguageModel.get_peft_model(\n", " model,\n", " r = 16, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128\n", " target_modules = [\"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\",\n", " \"gate_proj\", \"up_proj\", \"down_proj\",],\n", " lora_alpha = 16,\n", " lora_dropout = 0, # Supports any, but = 0 is optimized\n", " bias = \"none\", # Supports any, but = \"none\" is optimized\n", " # [NEW] \"unsloth\" uses 30% less VRAM, fits 2x larger batch sizes!\n", " use_gradient_checkpointing = \"unsloth\", # True or \"unsloth\" for very long context\n", " random_state = 3407,\n", " use_rslora = False, # We support rank stabilized LoRA\n", " loftq_config = None, # And LoftQ\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "vITh0KVJ10qX" }, "source": [ "\n", "### Data Prep\n", "We now use the Alpaca dataset from [yahma](https://huggingface.co/datasets/yahma/alpaca-cleaned), which is a filtered version of 52K of the original [Alpaca dataset](https://crfm.stanford.edu/2023/03/13/alpaca.html). You can replace this code section with your own data prep.\n", "\n", "**[NOTE]** To train only on completions (ignoring the user's input) read TRL's docs [here](https://huggingface.co/docs/trl/sft_trainer#train-on-completions-only).\n", "\n", "**[NOTE]** Remember to add the **EOS_TOKEN** to the tokenized output!! Otherwise you'll get infinite generations!\n", "\n", "If you want to use the `llama-3` template for ShareGPT datasets, try our conversational [notebook](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Llama3_(8B)-Alpaca.ipynb)\n", "\n", "For text completions like novel writing, try this [notebook](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Mistral_(7B)-Text_Completion.ipynb)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 145, "referenced_widgets": [ "5e8825fb770b41529f2129113cebc4a9", "0a9dc233674e4096b7a988a5e4ebaf84", "374fa9beda4042e1bf9a9b13de6e6674", "e6533d3c91fd4359bc84ffd8e59af5a3", "f9b01aebcbdc48a585b7942b0ee60a2d", "d4b3770433bc41818372b7aed243fb31", "19bcefcc1d874840ae9a9ca983e474b6", "4011ce9370d74fad857ec8e1e99d314f", "41f5fed060ad4c8d87b24602b720ef04", "88fcd51819b5483c9ab22df7ef89ab64", "e6ffac074f1b476ba2ade11b37732af3", "98a6716e7438429ea322adb3e3264f91", "68c686291b50430faeef0de7840e2c4b", "953625aa1e824f8a8d203197b316b302", "f899a815142542219bde22ff792fb60c", "51ca174d26e94b5cb1e895aa3c770655", "f4519637bb43400a80ce83505101e8a5", "805676b197c94f5aa45956daa354640b", "ce9fcc5eff1f460d80b703a4ca32dad1", "3fef797403d14440afe599a3bf06b626", "4e7cb8e988114ed4b6fe09ff9f682dff", "a14bc1c2130842568a5fde6698731e5f", "85cc6f24cba54563acb5598f54fed7b9", "80a72037771e4da9be989eefabbc8e76", "ba68b274c50b44ec9e02642378d271a6", "f84d2fe4f1c24a34948755abf1f32b7f", "86511967834f4484a5ec4af387b7d7a9", "c97c40c2bf2a41a8ae1c75e0a9c8ebff", "484e507f14424f2b9173595b985f4101", "68a32b398e1c490393e01befdc260785", "04cc963133d242779572d2e847fa3d65", "94730f13e92a4c9aac35c2cfb21fc48c", "620c0de28ec74f71a021a2be96dccf3a", "6e1aff64771c402ab070f650562fa4c9", "0078f897f2174217a307d95d4f9bd775", "ecdeaab4f8c94d6dade63bb06857c969", "735b85f0a0e9411cac4d704a504fcfc1", "8e992e60416145a8b6eed744287ca0fb", "8c195b5809604905b5e404baa30e8449", "2247efac4283489bbd228330344388ab", "e93d063faf984cc4aa51462418d9b57e", "9d45b9a5de3e4cba9ac35ad2cb187f51", "e99423a1ed3f4f72886b39368468b7c1", "5f174718e5974a7cab024d113f662513" ] }, "id": "LjY75GoYUCB8", "outputId": "80d6c3b9-28c2-4ebf-9c57-6a0b77ce82b1" }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "5e8825fb770b41529f2129113cebc4a9", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Downloading readme: 0%| | 0.00/11.6k [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "98a6716e7438429ea322adb3e3264f91", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Downloading data: 0%| | 0.00/44.3M [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "85cc6f24cba54563acb5598f54fed7b9", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Generating train split: 0%| | 0/51760 [00:00, ? examples/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "6e1aff64771c402ab070f650562fa4c9", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Map: 0%| | 0/51760 [00:00, ? examples/s]" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "alpaca_prompt = \"\"\"Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.\n", "\n", "### Instruction:\n", "{}\n", "\n", "### Input:\n", "{}\n", "\n", "### Response:\n", "{}\"\"\"\n", "\n", "EOS_TOKEN = tokenizer.eos_token # Must add EOS_TOKEN\n", "def formatting_prompts_func(examples):\n", " instructions = examples[\"instruction\"]\n", " inputs = examples[\"input\"]\n", " outputs = examples[\"output\"]\n", " texts = []\n", " for instruction, input, output in zip(instructions, inputs, outputs):\n", " # Must add EOS_TOKEN, otherwise your generation will go on forever!\n", " text = alpaca_prompt.format(instruction, input, output) + EOS_TOKEN\n", " texts.append(text)\n", " return { \"text\" : texts, }\n", "\n", "from datasets import load_dataset\n", "dataset = load_dataset(\"yahma/alpaca-cleaned\", split = \"train\")\n", "dataset = dataset.map(formatting_prompts_func, batched = True,)" ] }, { "cell_type": "markdown", "metadata": { "id": "idAEIeSQ3xdS" }, "source": [ "\n", "### Train the model (ASFT / ASFT+ demo)\n", "This demo notebook uses **Unsloth `ASFTTrainer`** (Anchored Supervised Fine-Tuning) instead of the standard `SFTTrainer`.\n", "\n", "ASFT in a nutshell:\n", "- Uses **DFT weights** (based on token probabilities / confidence) to reweight token-level CE loss.\n", "- Adds lightweight **KL anchoring** to stay close to a reference distribution (stability).\n", "- Supports **streaming** to chunk the reference forward pass and reduce peak VRAM.\n", "\n", "**ASFT+** in this repo refers to the same ASFT objective with extra engineering work (performance + VRAM optimizations) on top.\n", "\n", "Note: `max_steps` is kept small for a quick demo. For a full run, set `max_steps=None` and use `num_train_epochs=1` (or similar)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Recommended ASFT defaults (optimized)\n", "- `asft_mode=\"asft\"` + `kl_weight=0.05`: a solid starting point (stable, not overly restrictive).\n", "- `reference_policy=\"disable_adapter\"`: avoids keeping a separate frozen reference copy in most PEFT setups.\n", "- `ASFTStreamingConfig(mode=\"auto\")`: tries seq_kv_cache first, falls back to batch micro to reduce peak VRAM.\n", "\n", "For quick comparisons, try: `asft_mode=\"sft\"` or `asft_mode=\"dft\"` (KL off)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 67, "referenced_widgets": [ "3719bf6f9c6a4c6fbef93c5328c11a07", "03f492b4b56f4d8e80e9395a65058b1b", "39d9ef9fb35f47119f319f48eb222070", "3d7cfb33ceaf417e851ac4393c65148b", "ece66fa2f128456fa2a82b8a28d1211c", "9695a640b0ff4e91af495bb59548e4b6", "d4bd5559d4134d64a943d57972c6ef39", "fbae6e599d1644f39e5d86efa0f9f997", "00d425bca350451da6400f9f05c4a659", "6a27d9ad4f064586a87636b10455d15b", "77f4367616964a01a8c42416f5f4c147" ] }, "id": "95_Nn-89DhsL", "outputId": "29798478-b975-42d3-b32b-020a805cac35" }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "3719bf6f9c6a4c6fbef93c5328c11a07", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Map (num_proc=2): 0%| | 0/51760 [00:00, ? examples/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stderr", "output_type": "stream", "text": [ "max_steps is given, it will override any value given in num_train_epochs\n" ] } ], "source": [ "from trl import SFTConfig\n", "\n", "try:\n", " from unsloth.trainer import ASFTTrainer, ASFTStreamingConfig\n", "except Exception as e:\n", " raise ImportError(\n", " \"ASFTTrainer not found. For this ASFT demo notebook, install Unsloth from this repo/branch: \"\n", " \"(local) `pip install -e .` or (Colab) use the relevant git installation.\"\n", " ) from e\n", "\n", "# --- ASFT settings (optimized defaults for demo) ---\n", "asft_mode = \"asft\" # \"sft\" | \"dft\" | \"sft+kl\" | \"asft\"\n", "kl_weight = 0.05 # KL strength (for \"sft+kl\" and \"asft\")\n", "reference_policy = \"disable_adapter\" # \"disable_adapter\" | \"frozen_copy\"\n", "\n", "# Reference forward streaming to reduce VRAM peak\n", "asft_streaming = ASFTStreamingConfig(\n", " mode = \"auto\",\n", " # ref_microbatch_size = 1, # Set manually if desired; None picks automatically\n", " # seq_chunk_size = 256, # Adjust for long sequences if needed\n", " force_fp32_kl = True,\n", ")\n", "\n", "trainer = ASFTTrainer(\n", " model = model,\n", " tokenizer = tokenizer,\n", " train_dataset = dataset,\n", " dataset_text_field = \"text\",\n", " max_seq_length = max_seq_length,\n", " packing = True, # Try True for speed on short sequences.\n", " asft_enabled = True,\n", " asft_mode = asft_mode,\n", " kl_weight = kl_weight,\n", " reference_policy = reference_policy,\n", " asft_streaming = asft_streaming,\n", " args = SFTConfig(\n", " per_device_train_batch_size = 2,\n", " gradient_accumulation_steps = 4,\n", " warmup_steps = 5,\n", " # num_train_epochs = 1, # Enable for full training.\n", " max_steps = 60,\n", " learning_rate = 2e-4,\n", " logging_steps = 1,\n", " optim = \"adamw_8bit\",\n", " weight_decay = 0.001,\n", " lr_scheduler_type = \"linear\",\n", " seed = 3407,\n", " output_dir = \"outputs\",\n", " report_to = \"none\", # TrackIO/WandB etc.\n", " ),\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Quick sanity check: confirm ASFT is enabled and configured\n", "print(\"ASFT enabled:\", getattr(trainer, \"asft_enabled\", None))\n", "print(\"ASFT mode:\", getattr(trainer, \"asft_mode\", None))\n", "print(\"KL weight:\", getattr(trainer, \"kl_weight\", None))\n", "print(\"Reference policy:\", getattr(trainer, \"reference_policy\", None))\n", "streaming = getattr(trainer, \"asft_streaming\", None)\n", "if streaming is not None:\n", " print(\"Streaming mode:\", getattr(streaming, \"mode\", None))\n", " print(\"Streaming strategy:\", getattr(streaming, \"ref_strategy\", None))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "colab": { "base_uri": "https://localhost:8080/" }, "id": "2ejIt2xSNKKp", "outputId": "d397dd48-304c-4f42-ecbc-d5c9ce14989c" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "GPU = Tesla T4. Max memory = 14.748 GB.\n", "5.984 GB of memory reserved.\n" ] } ], "source": [ "# @title Show current memory stats\n", "gpu_stats = torch.cuda.get_device_properties(0)\n", "start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)\n", "max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)\n", "print(f\"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.\")\n", "print(f\"{start_gpu_memory} GB of memory reserved.\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 1000 }, "id": "yqxqAZ7KJ4oL", "outputId": "76534fb4-5f9a-4da4-9740-fcff4583fd1c" }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "==((====))== Unsloth - 2x faster free finetuning | Num GPUs = 1\n", " \\\\ /| Num examples = 51,760 | Num Epochs = 1\n", "O^O/ \\_/ \\ Batch size per device = 2 | Gradient Accumulation steps = 4\n", "\\ / Total batch size = 8 | Total steps = 60\n", " \"-____-\" Number of trainable parameters = 41,943,040\n" ] }, { "data": { "text/html": [ "\n", "| Step | \n", "Training Loss | \n", "
|---|---|
| 1 | \n", "1.817600 | \n", "
| 2 | \n", "2.304200 | \n", "
| 3 | \n", "1.689300 | \n", "
| 4 | \n", "1.938200 | \n", "
| 5 | \n", "1.656900 | \n", "
| 6 | \n", "1.621900 | \n", "
| 7 | \n", "1.187100 | \n", "
| 8 | \n", "1.264200 | \n", "
| 9 | \n", "1.101200 | \n", "
| 10 | \n", "1.189500 | \n", "
| 11 | \n", "0.930800 | \n", "
| 12 | \n", "0.959400 | \n", "
| 13 | \n", "0.929400 | \n", "
| 14 | \n", "1.048700 | \n", "
| 15 | \n", "0.892800 | \n", "
| 16 | \n", "0.901400 | \n", "
| 17 | \n", "1.009100 | \n", "
| 18 | \n", "1.256100 | \n", "
| 19 | \n", "1.016500 | \n", "
| 20 | \n", "0.882600 | \n", "
| 21 | \n", "0.940500 | \n", "
| 22 | \n", "1.018500 | \n", "
| 23 | \n", "0.897200 | \n", "
| 24 | \n", "0.991900 | \n", "
| 25 | \n", "1.072000 | \n", "
| 26 | \n", "1.022900 | \n", "
| 27 | \n", "1.044900 | \n", "
| 28 | \n", "0.877800 | \n", "
| 29 | \n", "0.843800 | \n", "
| 30 | \n", "0.887500 | \n", "
| 31 | \n", "0.853400 | \n", "
| 32 | \n", "0.866000 | \n", "
| 33 | \n", "0.983200 | \n", "
| 34 | \n", "0.852200 | \n", "
| 35 | \n", "0.961200 | \n", "
| 36 | \n", "0.856700 | \n", "
| 37 | \n", "0.872300 | \n", "
| 38 | \n", "0.751100 | \n", "
| 39 | \n", "1.081400 | \n", "
| 40 | \n", "1.174400 | \n", "
| 41 | \n", "0.893400 | \n", "
| 42 | \n", "0.977500 | \n", "
| 43 | \n", "0.957100 | \n", "
| 44 | \n", "0.908100 | \n", "
| 45 | \n", "0.915000 | \n", "
| 46 | \n", "0.973400 | \n", "
| 47 | \n", "0.870900 | \n", "
| 48 | \n", "1.196500 | \n", "
| 49 | \n", "0.907500 | \n", "
| 50 | \n", "1.031300 | \n", "
| 51 | \n", "1.015900 | \n", "
| 52 | \n", "0.907900 | \n", "
| 53 | \n", "0.977000 | \n", "
| 54 | \n", "1.154300 | \n", "
| 55 | \n", "0.778000 | \n", "
| 56 | \n", "1.013300 | \n", "
| 57 | \n", "0.886800 | \n", "
| 58 | \n", "0.827500 | \n", "
| 59 | \n", "0.852300 | \n", "
| 60 | \n", "0.896600 | \n", "
"
],
"text/plain": [
"
\n",
"
\n",
"
\n",
"\n",
" Join Discord if you need help + ⭐️ Star us on Github ⭐️\n",
"\n",
" This notebook and all Unsloth notebooks are licensed [LGPL-3.0](https://github.com/unslothai/notebooks?tab=LGPL-3.0-1-ov-file#readme).\n",
"