{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d07125c3-86a1-4f71-965b-dccee2cdae6b",
   "metadata": {},
   "source": [
    "#### 下载训练数据 train.jsonl"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "37edbdc6-f0ce-40e1-babb-154208bb48fe",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "!curl -f -o train.jsonl \"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250610/azvmpb/train_with_system.jsonl\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ed981d1e-2891-497d-8cc2-ca6daf862528",
   "metadata": {
    "ExecutionIndicator": {
     "show": true
    },
    "tags": []
   },
   "source": [
    "#### 执行微调命令"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4f8601f8-d0c4-46b4-9e73-d00c27a3c2e0",
   "metadata": {
    "ExecutionIndicator": {
     "show": true
    },
    "scrolled": true,
    "tags": []
   },
   "outputs": [],
   "source": [
    "!CUDA_VISIBLE_DEVICES=0 \\\n",
    "swift sft \\\n",
    "    --model Qwen/Qwen3-0.6B \\\n",
    "    --train_type lora \\\n",
    "    --dataset 'train.jsonl' \\\n",
    "    --torch_dtype float32 \\\n",
    "    --num_train_epochs 1 \\\n",
    "    --per_device_train_batch_size 1 \\\n",
    "    --per_device_eval_batch_size 1 \\\n",
    "    --learning_rate 1e-4 \\\n",
    "    --lora_rank 8 \\\n",
    "    --lora_alpha 32 \\\n",
    "    --target_modules all-linear \\\n",
    "    --gradient_accumulation_steps 16 \\\n",
    "    --save_steps 5 \\\n",
    "    --save_total_limit 2 \\\n",
    "    --logging_steps 5 \\\n",
    "    --max_length 2048 \\\n",
    "    --output_dir output \\\n",
    "    --warmup_ratio 0.05 \\\n",
    "    --dataloader_num_workers 4"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c24f671b-3a16-413f-bb68-dc75e84d8268",
   "metadata": {
    "tags": []
   },
   "source": [
    "#### 查看train_loss曲线和eval_loss曲线"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "76fa899a-e51d-4463-852f-b80a1d7982a7",
   "metadata": {
    "ExecutionIndicator": {
     "show": false
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import matplotlib.pyplot as plt\n",
    "from PIL import Image\n",
    "\n",
    "\n",
    "def find_images(directory, filenames=(\"train_loss.png\", \"eval_loss.png\")):\n",
    "    image_paths = {name: None for name in filenames}\n",
    "\n",
    "    # 递归查找指定文件\n",
    "    for root, _, files in os.walk(directory):\n",
    "        for filename in files:\n",
    "            if filename in filenames:\n",
    "                image_paths[filename] = os.path.join(root, filename)\n",
    "\n",
    "    return image_paths\n",
    "\n",
    "\n",
    "def plot_images(image_paths):\n",
    "    plt.figure(figsize=(10, 5))\n",
    "\n",
    "    for i, (label, path) in enumerate(image_paths.items(), start=1):\n",
    "        if path:\n",
    "            img = Image.open(path)\n",
    "            plt.subplot(1, 2, i)\n",
    "            plt.imshow(img)\n",
    "            plt.title(label)\n",
    "            plt.axis('off')  # 不显示坐标轴\n",
    "\n",
    "    plt.tight_layout()\n",
    "    plt.show()\n",
    "\n",
    "\n",
    "# 指定输出目录，图像在output/v*-*****-***/images下\n",
    "output_directory = \"output\"  # 不用修改，如果有多个images时可以手动指定\n",
    "# 找到图像文件\n",
    "images = find_images(output_directory)\n",
    "# 绘制图像\n",
    "plot_images(images)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "65b600df-40be-4fc0-b627-4d1bb7157d17",
   "metadata": {},
   "source": [
    "#### 合并LoRA和原始模型参数，\n",
    "##### 注意将命令中`/mnt/workspace/output/v*-*********-*****/checkpoint-**`替换为上面输出的best_model_checkpoint路径。执行成功后会输出合并LoRA参数后的模型路径"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bdd51f53-36f1-4e06-8491-3e3873ca7b6c",
   "metadata": {
    "ExecutionIndicator": {
     "show": true
    },
    "scrolled": true,
    "tags": []
   },
   "outputs": [],
   "source": [
    "!swift export \\\n",
    "    --adapters /mnt/workspace/output/v*-*********-*****/checkpoint-** \\\n",
    "    --merge_lora true"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bf8d21d5-bd0d-418c-8bb0-75b7053efc69",
   "metadata": {},
   "source": [
    "#### 将微调后的模型文件复制到OSS中持久化保存\n",
    "##### 注意将命令中`/mnt/workspace/output/v*-*********-*****/checkpoint-**-merged`替换为上面输出的合并LoRA参数后的模型路径\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "678131d3-620e-47d2-b83b-d0109020bc87",
   "metadata": {
    "ExecutionIndicator": {
     "show": false
    },
    "execution": {
     "iopub.execute_input": "2025-06-20T08:13:42.277793Z",
     "iopub.status.busy": "2025-06-20T08:13:42.277356Z",
     "iopub.status.idle": "2025-06-20T08:13:49.467324Z",
     "shell.execute_reply": "2025-06-20T08:13:49.466509Z",
     "shell.execute_reply.started": "2025-06-20T08:13:42.277757Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "!cp -r /mnt/workspace/output/v*-*********-*****/checkpoint-**-merged /mnt/data/qwen3_best_checkpoint"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4ce2a591-6fc9-4a29-8b90-290c04ba749b",
   "metadata": {},
   "source": [
    "#### 下载验证模型准确率的代码脚本evaluate_model.py"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a888c180-8872-4783-ae13-4161f7959d2e",
   "metadata": {
    "ExecutionIndicator": {
     "show": true
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "!curl -f -o evaluate_model.py \"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250619/ayyuze/evalute_model.py\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c9b7ad9d-5baf-477e-875f-bb8f5e1aa25b",
   "metadata": {},
   "source": [
    "#### 启动模型服务\n",
    "##### 注意将命令中`/mnt/workspace/output/v*-*********-*****/checkpoint-**-merged`替换为上面输出的合并LoRA参数后的模型路径"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "04a90586-00ae-42cc-bfd6-f9ef029d0821",
   "metadata": {
    "ExecutionIndicator": {
     "show": false
    },
    "execution": {
     "iopub.status.idle": "2025-06-20T09:35:52.378559Z",
     "shell.execute_reply": "2025-06-20T09:35:52.377555Z",
     "shell.execute_reply.started": "2025-06-20T09:35:36.797503Z"
    },
    "scrolled": true,
    "tags": []
   },
   "outputs": [],
   "source": [
    "!CUDA_VISIBLE_DEVICES=0 \\\n",
    "swift deploy \\\n",
    "    --model /mnt/workspace/output/v*-*********-*****/checkpoint-**-merged \\\n",
    "    --infer_backend vllm \\\n",
    "    --max_new_tokens 2048 \\\n",
    "    --max_model_len 10000 \\\n",
    "    --served_model_name Qwen3-0.6B"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "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.11.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
