{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [] }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "7llavzX0Jlbm", "outputId": "710c2728-5e5b-4958-91a9-2321aa30488f" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Requirement already satisfied: torch in /usr/local/lib/python3.12/dist-packages (2.11.0+cpu)\n", "Requirement already satisfied: torchvision in /usr/local/lib/python3.12/dist-packages (0.26.0+cpu)\n", "Collecting onnx\n", " Downloading onnx-1.22.0-cp312-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.metadata (8.5 kB)\n", "Collecting onnxruntime\n", " Downloading onnxruntime-1.27.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.metadata (5.4 kB)\n", "Requirement already satisfied: filelock in /usr/local/lib/python3.12/dist-packages (from torch) (3.29.3)\n", "Requirement already satisfied: typing-extensions>=4.10.0 in /usr/local/lib/python3.12/dist-packages (from torch) (4.15.0)\n", "Requirement already satisfied: setuptools<82 in /usr/local/lib/python3.12/dist-packages (from torch) (75.2.0)\n", "Requirement already satisfied: sympy>=1.13.3 in /usr/local/lib/python3.12/dist-packages (from torch) (1.14.0)\n", "Requirement already satisfied: networkx>=2.5.1 in /usr/local/lib/python3.12/dist-packages (from torch) (3.6.1)\n", "Requirement already satisfied: jinja2 in /usr/local/lib/python3.12/dist-packages (from torch) (3.1.6)\n", "Requirement already satisfied: fsspec>=0.8.5 in /usr/local/lib/python3.12/dist-packages (from torch) (2025.3.0)\n", "Requirement already satisfied: numpy in /usr/local/lib/python3.12/dist-packages (from torchvision) (2.0.2)\n", "Requirement already satisfied: pillow!=8.3.*,>=5.3.0 in /usr/local/lib/python3.12/dist-packages (from torchvision) (11.3.0)\n", "Requirement already satisfied: protobuf>=4.25.1 in /usr/local/lib/python3.12/dist-packages (from onnx) (5.29.6)\n", "Requirement already satisfied: ml_dtypes>=0.5.4 in /usr/local/lib/python3.12/dist-packages (from onnx) (0.5.4)\n", "Requirement already satisfied: flatbuffers in /usr/local/lib/python3.12/dist-packages (from onnxruntime) (25.12.19)\n", "Requirement already satisfied: packaging in /usr/local/lib/python3.12/dist-packages (from onnxruntime) (26.2)\n", "Requirement already satisfied: mpmath<1.4,>=1.1.0 in /usr/local/lib/python3.12/dist-packages (from sympy>=1.13.3->torch) (1.3.0)\n", "Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.12/dist-packages (from jinja2->torch) (3.0.3)\n", "Downloading onnx-1.22.0-cp312-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (19.1 MB)\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m19.1/19.1 MB\u001b[0m \u001b[31m45.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[?25hDownloading onnxruntime-1.27.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (18.7 MB)\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m18.7/18.7 MB\u001b[0m \u001b[31m43.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[?25hInstalling collected packages: onnxruntime, onnx\n", "Successfully installed onnx-1.22.0 onnxruntime-1.27.0\n" ] } ], "source": [ "!pip install torch torchvision onnx onnxruntime" ] }, { "cell_type": "code", "source": [ "!pip install onnxconverter-common onnxscript" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "4O_nji0GKIIF", "outputId": "6e998cd2-45a1-4c08-c964-2dccd1943c89" }, "execution_count": 4, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Requirement already satisfied: onnxconverter-common in /usr/local/lib/python3.12/dist-packages (1.16.0)\n", "Collecting onnxscript\n", " Downloading onnxscript-0.7.1-py3-none-any.whl.metadata (13 kB)\n", "Requirement already satisfied: numpy in /usr/local/lib/python3.12/dist-packages (from onnxconverter-common) (2.0.2)\n", "Requirement already satisfied: onnx in /usr/local/lib/python3.12/dist-packages (from onnxconverter-common) (1.22.0)\n", "Requirement already satisfied: packaging in /usr/local/lib/python3.12/dist-packages (from onnxconverter-common) (26.2)\n", "Requirement already satisfied: protobuf>=3.20.2 in /usr/local/lib/python3.12/dist-packages (from onnxconverter-common) (5.29.6)\n", "Requirement already satisfied: ml_dtypes in /usr/local/lib/python3.12/dist-packages (from onnxscript) (0.5.4)\n", "Collecting onnx_ir<2,>=0.1.16 (from onnxscript)\n", " Downloading onnx_ir-0.2.1-py3-none-any.whl.metadata (3.3 kB)\n", "Requirement already satisfied: typing_extensions>=4.10 in /usr/local/lib/python3.12/dist-packages (from onnxscript) (4.15.0)\n", "Requirement already satisfied: sympy>=1.13 in /usr/local/lib/python3.12/dist-packages (from onnx_ir<2,>=0.1.16->onnxscript) (1.14.0)\n", "Requirement already satisfied: mpmath<1.4,>=1.1.0 in /usr/local/lib/python3.12/dist-packages (from sympy>=1.13->onnx_ir<2,>=0.1.16->onnxscript) (1.3.0)\n", "Downloading onnxscript-0.7.1-py3-none-any.whl (721 kB)\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m722.0/722.0 kB\u001b[0m \u001b[31m3.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[?25hDownloading onnx_ir-0.2.1-py3-none-any.whl (166 kB)\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m166.8/166.8 kB\u001b[0m \u001b[31m9.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[?25hInstalling collected packages: onnx_ir, onnxscript\n", "Successfully installed onnx_ir-0.2.1 onnxscript-0.7.1\n" ] } ] }, { "cell_type": "code", "source": [ "pip install git+https://github.com/ChaoningZhang/MobileSAM.git" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "RfskpLtIKg5r", "outputId": "0c1c4821-0821-4637-8c2d-641b1918e5dd" }, "execution_count": 6, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Collecting git+https://github.com/ChaoningZhang/MobileSAM.git\n", " Cloning https://github.com/ChaoningZhang/MobileSAM.git to /tmp/pip-req-build-ubuj4910\n", " Running command git clone --filter=blob:none --quiet https://github.com/ChaoningZhang/MobileSAM.git /tmp/pip-req-build-ubuj4910\n", " Resolved https://github.com/ChaoningZhang/MobileSAM.git to commit f706ad9c4eb7f219c00d9050e46328518ffb65d2\n", " Preparing metadata (setup.py) ... \u001b[?25l\u001b[?25hdone\n", "Building wheels for collected packages: mobile_sam\n", " Building wheel for mobile_sam (setup.py) ... \u001b[?25l\u001b[?25hdone\n", " Created wheel for mobile_sam: filename=mobile_sam-1.0-py3-none-any.whl size=42431 sha256=08b3049a387c3369ea339d70fcf39d47453ed8dc570e28c0056bb3e00a4a415f\n", " Stored in directory: /tmp/pip-ephem-wheel-cache-s9bnvwnr/wheels/5f/88/d6/5c0b5d4d64a06e19190d50269d8725c8aeadb128c966801af5\n", "Successfully built mobile_sam\n", "Installing collected packages: mobile_sam\n", "Successfully installed mobile_sam-1.0\n" ] } ] }, { "cell_type": "code", "source": [ "import os\n", "import sys\n", "import subprocess\n", "\n", "# 1. Tự động kiểm tra và cài đặt thư viện cấu trúc mạng mobile-sam\n", "try:\n", " from mobile_sam import sam_model_registry\n", "except ImportError:\n", " print(\"📥 Không tìm thấy thư viện mobile-sam. Đang tiến hành cài đặt từ GitHub...\")\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"git+https://github.com/ChaoningZhang/MobileSAM.git\"])\n", " from mobile_sam import sam_model_registry\n", "\n", "try:\n", " from onnxconverter_common import float16\n", "except ImportError:\n", " print(\"📥 Đang cài đặt onnxconverter-common...\")\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"onnxconverter-common\"])\n", " from onnxconverter_common import float16\n", "\n", "import torch\n", "import onnx\n", "\n", "# 2. Khai báo các đường dẫn file\n", "pth_path = \"tinysam.pth\"\n", "onnx_fp32_path = \"tinysam_fp32.onnx\"\n", "onnx_fp16_path = \"tinysam_fp16.onnx\"\n", "\n", "# 3. Khởi tạo cấu trúc mô hình và nạp trọng số chuẩn\n", "print(\"\\n🔄 Đang dựng cấu trúc mạng TinySAM (ViT-Tiny)...\")\n", "sam = sam_model_registry[\"vit_t\"]()\n", "\n", "print(f\"📦 Đang nạp trọng số từ file: {pth_path}\")\n", "checkpoint = torch.load(pth_path, map_location=\"cpu\")\n", "\n", "# Khắc phục lỗi bằng cách đưa dict vào cấu trúc mạng NN.Module\n", "sam.load_state_dict(checkpoint)\n", "\n", "# Tách riêng phần Image Encoder (Trọng tâm xử lý nặng nhất để đưa lên Android)\n", "image_encoder = sam.image_encoder\n", "image_encoder.eval()\n", "print(\"✅ Đã chuẩn bị xong mô hình dạng torch.nn.Module!\")\n", "\n", "# 4. Xuất sang ONNX FP32\n", "print(\"\\n📦 Bước 1: Đang export sang ONNX FP32...\")\n", "dummy_input = torch.randn(1, 3, 1024, 1024)\n", "\n", "# Ép PyTorch dùng bộ export cũ (Legacy/TorchScript) để tránh lỗi tương thích của Python 3.12\n", "with torch.no_grad():\n", " torch.onnx.export(\n", " image_encoder,\n", " dummy_input,\n", " onnx_fp32_path,\n", " export_params=True,\n", " opset_version=17, # Opset tối ưu ổn định cho thiết bị di động\n", " do_constant_folding=True,\n", " input_names=['images'],\n", " output_names=['embeddings'],\n", " # Dòng dưới vô cùng quan trọng để bỏ qua lỗi cơ chế kiểm tra đồ thị mới của PyTorch 2.x\n", " operator_export_type=torch.onnx.OperatorExportTypes.ONNX_FALLTHROUGH\n", " )\n", "print(f\"✅ Đã xuất file thành công: {onnx_fp32_path}\")\n", "\n", "# 5. Lượng tử hóa sang FP16\n", "print(\"\\n⚡ Bước 2: Đang lượng tử hóa (Quantize) xuống FP16...\")\n", "onnx_model = onnx.load(onnx_fp32_path)\n", "model_fp16 = float16.convert_float_to_float16(onnx_model)\n", "onnx.save(model_fp16, onnx_fp16_path)\n", "\n", "print(f\"\\n🎉 HOÀN THÀNH XUẤT SẮC! File {onnx_fp16_path} (~20MB) đã sẵn sàng chạy trên Android.\")" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "fyEyrIudJmTx", "outputId": "dedc7641-e8e1-44ba-b64d-699bedca157e" }, "execution_count": 7, "outputs": [ { "output_type": "stream", "name": "stderr", "text": [ "/usr/local/lib/python3.12/dist-packages/timm/models/layers/__init__.py:49: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers\n", " warnings.warn(f\"Importing from {__name__} is deprecated, please import via timm.layers\", FutureWarning)\n", "/usr/local/lib/python3.12/dist-packages/timm/models/registry.py:4: FutureWarning: Importing from timm.models.registry is deprecated, please import via timm.models\n", " warnings.warn(f\"Importing from {__name__} is deprecated, please import via timm.models\", FutureWarning)\n", "/usr/local/lib/python3.12/dist-packages/mobile_sam/modeling/tiny_vit_sam.py:656: UserWarning: Overwriting tiny_vit_5m_224 in registry with mobile_sam.modeling.tiny_vit_sam.tiny_vit_5m_224. This is because the name being registered conflicts with an existing name. Please check if this is not expected.\n", " return register_model(fn_wrapper)\n", "/usr/local/lib/python3.12/dist-packages/mobile_sam/modeling/tiny_vit_sam.py:656: UserWarning: Overwriting tiny_vit_11m_224 in registry with mobile_sam.modeling.tiny_vit_sam.tiny_vit_11m_224. This is because the name being registered conflicts with an existing name. Please check if this is not expected.\n", " return register_model(fn_wrapper)\n", "/usr/local/lib/python3.12/dist-packages/mobile_sam/modeling/tiny_vit_sam.py:656: UserWarning: Overwriting tiny_vit_21m_224 in registry with mobile_sam.modeling.tiny_vit_sam.tiny_vit_21m_224. This is because the name being registered conflicts with an existing name. Please check if this is not expected.\n", " return register_model(fn_wrapper)\n", "/usr/local/lib/python3.12/dist-packages/mobile_sam/modeling/tiny_vit_sam.py:656: UserWarning: Overwriting tiny_vit_21m_384 in registry with mobile_sam.modeling.tiny_vit_sam.tiny_vit_21m_384. This is because the name being registered conflicts with an existing name. Please check if this is not expected.\n", " return register_model(fn_wrapper)\n", "/usr/local/lib/python3.12/dist-packages/mobile_sam/modeling/tiny_vit_sam.py:656: UserWarning: Overwriting tiny_vit_21m_512 in registry with mobile_sam.modeling.tiny_vit_sam.tiny_vit_21m_512. This is because the name being registered conflicts with an existing name. Please check if this is not expected.\n", " return register_model(fn_wrapper)\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ "\n", "🔄 Đang dựng cấu trúc mạng TinySAM (ViT-Tiny)...\n", "📦 Đang nạp trọng số từ file: tinysam.pth\n", "✅ Đã chuẩn bị xong mô hình dạng torch.nn.Module!\n", "\n", "📦 Bước 1: Đang export sang ONNX FP32...\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "W0630 10:56:46.888000 12264 torch/onnx/_internal/exporter/_compat.py:133] Setting ONNX exporter to use operator set version 18 because the requested opset_version 17 is a lower version than we have implementations for. Automatic version conversion will be performed, which may not be successful at converting to the requested version. If version conversion is unsuccessful, the opset version of the exported model will be kept at 18. Please consider setting opset_version >=18 to leverage latest ONNX features\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ "[torch.onnx] Obtain model graph for `TinyViT([...]` with `torch.export.export(..., strict=False)`...\n", "[torch.onnx] Obtain model graph for `TinyViT([...]` with `torch.export.export(..., strict=False)`... ✅\n", "[torch.onnx] Run decompositions...\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "/usr/lib/python3.12/copyreg.py:99: FutureWarning: `isinstance(treespec, LeafSpec)` is deprecated, use `isinstance(treespec, TreeSpec) and treespec.is_leaf()` instead.\n", " return cls.__new__(cls, *args)\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ "[torch.onnx] Run decompositions... ✅\n", "[torch.onnx] Translate the graph into ONNX...\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "WARNING:onnxscript.version_converter:The model version conversion is not supported by the onnxscript version converter and fallback is enabled. The model will be converted using the onnx C API (target version: 17).\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ "[torch.onnx] Translate the graph into ONNX... ✅\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "WARNING:onnxscript.version_converter:Failed to convert the model to the target version 17 using the ONNX C API. The model was not modified\n", "Traceback (most recent call last):\n", " File \"/usr/local/lib/python3.12/dist-packages/onnxscript/version_converter/__init__.py\", line 137, in call\n", " converted_proto = _c_api_utils.call_onnx_api(\n", " ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", " File \"/usr/local/lib/python3.12/dist-packages/onnxscript/version_converter/_c_api_utils.py\", line 65, in call_onnx_api\n", " result = func(proto)\n", " ^^^^^^^^^^^\n", " File \"/usr/local/lib/python3.12/dist-packages/onnxscript/version_converter/__init__.py\", line 132, in _partial_convert_version\n", " return onnx.version_converter.convert_version(\n", " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", " File \"/usr/local/lib/python3.12/dist-packages/onnx/version_converter.py\", line 39, in convert_version\n", " converted_model_str = C.convert_version(model_str, target_version)\n", " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", "RuntimeError: /project/onnx/version_converter/BaseConverter.h:64: adapter_lookup: Assertion `false` failed: No Adapter To Version $17 for Pad\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ "[torch.onnx] Optimize the ONNX graph...\n", "[torch.onnx] Optimize the ONNX graph... ✅\n", "✅ Đã xuất file thành công: tinysam_fp32.onnx\n", "\n", "⚡ Bước 2: Đang lượng tử hóa (Quantize) xuống FP16...\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:52: UserWarning: the float32 number 2.96924464182613e-11 will be truncated to 1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:70: UserWarning: the float32 number -5.084482834760706e-10 will be truncated to -1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:52: UserWarning: the float32 number 4.369391959357927e-09 will be truncated to 1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:70: UserWarning: the float32 number -4.202550252241366e-10 will be truncated to -1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:52: UserWarning: the float32 number 4.5062709119747524e-08 will be truncated to 1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:70: UserWarning: the float32 number -1.5576400613781516e-08 will be truncated to -1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:52: UserWarning: the float32 number 9.58783725156509e-13 will be truncated to 1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:70: UserWarning: the float32 number -1.5560433150318964e-11 will be truncated to -1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:52: UserWarning: the float32 number 2.677064958600539e-10 will be truncated to 1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:70: UserWarning: the float32 number -1.0865126576220518e-09 will be truncated to -1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:52: UserWarning: the float32 number 5.222516641367747e-09 will be truncated to 1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:70: UserWarning: the float32 number -5.568366212571618e-09 will be truncated to -1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:52: UserWarning: the float32 number 3.997479680606375e-09 will be truncated to 1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:70: UserWarning: the float32 number -2.3033279727968647e-09 will be truncated to -1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:52: UserWarning: the float32 number 1.3769063667012915e-09 will be truncated to 1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:70: UserWarning: the float32 number -8.361915604382375e-10 will be truncated to -1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:52: UserWarning: the float32 number 8.9231697586456e-09 will be truncated to 1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:70: UserWarning: the float32 number -6.136954500135516e-09 will be truncated to -1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:52: UserWarning: the float32 number 4.350866777969031e-09 will be truncated to 1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:70: UserWarning: the float32 number -1.86040320926395e-08 will be truncated to -1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:52: UserWarning: the float32 number 2.692952527638681e-10 will be truncated to 1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:70: UserWarning: the float32 number -8.705120652097165e-11 will be truncated to -1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:52: UserWarning: the float32 number 2.597781434410251e-10 will be truncated to 1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:70: UserWarning: the float32 number -1.5402988606805224e-10 will be truncated to -1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:70: UserWarning: the float32 number -4.5255553970946494e-08 will be truncated to -1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:52: UserWarning: the float32 number 8.497573844579165e-08 will be truncated to 1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:52: UserWarning: the float32 number 4.558812882748953e-09 will be truncated to 1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:70: UserWarning: the float32 number -5.925561152864134e-10 will be truncated to -1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:52: UserWarning: the float32 number 9.544110923798144e-08 will be truncated to 1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:52: UserWarning: the float32 number 2.3779847448807123e-12 will be truncated to 1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:70: UserWarning: the float32 number -8.287774980186846e-12 will be truncated to -1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:52: UserWarning: the float32 number 4.042161450001913e-08 will be truncated to 1e-07\n", " warnings.warn(\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ "\n", "🎉 HOÀN THÀNH XUẤT SẮC! File tinysam_fp16.onnx (~20MB) đã sẵn sàng chạy trên Android.\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:70: UserWarning: the float32 number -2.4764778672192733e-08 will be truncated to -1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:70: UserWarning: the float32 number -5.992093576878688e-08 will be truncated to -1e-07\n", " warnings.warn(\n", "/usr/local/lib/python3.12/dist-packages/onnxconverter_common/float16.py:70: UserWarning: the float32 number -9.47832106135138e-08 will be truncated to -1e-07\n", " warnings.warn(\n" ] } ] }, { "cell_type": "code", "source": [ "!pip install onnx2torch" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "7A-LrQv7LvMe", "outputId": "cd6dc452-aa56-4da1-e774-9ad89fb0e296" }, "execution_count": 8, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Collecting onnx2torch\n", " Downloading onnx2torch-1.5.15-py3-none-any.whl.metadata (23 kB)\n", "Requirement already satisfied: numpy>=1.16.4 in /usr/local/lib/python3.12/dist-packages (from onnx2torch) (2.0.2)\n", "Requirement already satisfied: onnx>=1.9.0 in /usr/local/lib/python3.12/dist-packages (from onnx2torch) (1.22.0)\n", "Requirement already satisfied: torch>=1.8.0 in /usr/local/lib/python3.12/dist-packages (from onnx2torch) (2.11.0+cpu)\n", "Requirement already satisfied: torchvision>=0.9.0 in /usr/local/lib/python3.12/dist-packages (from onnx2torch) (0.26.0+cpu)\n", "Requirement already satisfied: protobuf>=4.25.1 in /usr/local/lib/python3.12/dist-packages (from onnx>=1.9.0->onnx2torch) (5.29.6)\n", "Requirement already satisfied: typing_extensions>=4.15.0 in /usr/local/lib/python3.12/dist-packages (from onnx>=1.9.0->onnx2torch) (4.15.0)\n", "Requirement already satisfied: ml_dtypes>=0.5.4 in /usr/local/lib/python3.12/dist-packages (from onnx>=1.9.0->onnx2torch) (0.5.4)\n", "Requirement already satisfied: filelock in /usr/local/lib/python3.12/dist-packages (from torch>=1.8.0->onnx2torch) (3.29.3)\n", "Requirement already satisfied: setuptools<82 in /usr/local/lib/python3.12/dist-packages (from torch>=1.8.0->onnx2torch) (75.2.0)\n", "Requirement already satisfied: sympy>=1.13.3 in /usr/local/lib/python3.12/dist-packages (from torch>=1.8.0->onnx2torch) (1.14.0)\n", "Requirement already satisfied: networkx>=2.5.1 in /usr/local/lib/python3.12/dist-packages (from torch>=1.8.0->onnx2torch) (3.6.1)\n", "Requirement already satisfied: jinja2 in /usr/local/lib/python3.12/dist-packages (from torch>=1.8.0->onnx2torch) (3.1.6)\n", "Requirement already satisfied: fsspec>=0.8.5 in /usr/local/lib/python3.12/dist-packages (from torch>=1.8.0->onnx2torch) (2025.3.0)\n", "Requirement already satisfied: pillow!=8.3.*,>=5.3.0 in /usr/local/lib/python3.12/dist-packages (from torchvision>=0.9.0->onnx2torch) (11.3.0)\n", "Requirement already satisfied: mpmath<1.4,>=1.1.0 in /usr/local/lib/python3.12/dist-packages (from sympy>=1.13.3->torch>=1.8.0->onnx2torch) (1.3.0)\n", "Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.12/dist-packages (from jinja2->torch>=1.8.0->onnx2torch) (3.0.3)\n", "Downloading onnx2torch-1.5.15-py3-none-any.whl (80 kB)\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m81.0/81.0 kB\u001b[0m \u001b[31m1.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[?25hInstalling collected packages: onnx2torch\n", "Successfully installed onnx2torch-1.5.15\n" ] } ] }, { "cell_type": "code", "source": [ "import torch\n", "import onnx\n", "from onnx2torch import convert\n", "\n", "# 1. Khai báo đường dẫn file\n", "onnx_path = \"tinysam_fp16.onnx\"\n", "pt_path = \"tinysam_fp16.pt\"\n", "\n", "print(f\"🔄 Đang đọc và convert file ONNX: {onnx_path}...\")\n", "\n", "# 2. Thực hiện chuyển đổi cấu trúc đồ thị mạng từ ONNX sang PyTorch\n", "try:\n", " # convert() sẽ tự động map các node ONNX sang nn.Module của PyTorch\n", " torch_model = convert(onnx_path)\n", "\n", " # Đảm bảo toàn bộ model được đưa về chế độ Evaluation\n", " torch_model.eval()\n", "\n", " # Ép kiểu các tham số về nửa chính xác (Half Precision - FP16)\n", " # để đồng bộ với file ONNX FP16 ban đầu\n", " torch_model = torch_model.half()\n", "\n", " print(\"✅ Đã chuyển đổi cấu trúc mạng sang PyTorch thành công!\")\n", "except Exception as e:\n", " print(f\"❌ Lỗi trong quá trình dịch ONNX sang PyTorch: {e}\")\n", " exit()\n", "\n", "# 3. Kiểm tra thử với dữ liệu giả lập (Dummy Input kiểu Half/FP16)\n", "print(\"🧪 Đang chạy thử nghiệm (Inference Test) để kiểm tra mô hình...\")\n", "try:\n", " # Dữ liệu đầu vào phải ở định dạng .half() (FP16) để khớp với mô hình\n", " dummy_input = torch.randn(1, 3, 1024, 1024).half()\n", "\n", " with torch.no_grad():\n", " output = torch_model(dummy_input)\n", " print(\"✅ Chạy thử thành công! Mô hình phản hồi dữ liệu chính xác.\")\n", "except Exception as e:\n", " print(f\"⚠️ Cảnh báo chạy thử: {e}\")\n", " print(\"💡 Mẹo: Một số toán tử ONNX đặc thù khi chuyển về PyTorch có thể đòi hỏi input chuẩn logic.\")\n", "\n", "# 4. Lưu mô hình thành file .pt\n", "print(f\"💾 Đang lưu mô hình sang file PyTorch: {pt_path}...\")\n", "\n", "# Lưu ý: Nên lưu cả cấu trúc mạng (Tránh lỗi như lần trước)\n", "torch.save(torch_model, pt_path)\n", "\n", "print(f\"🎉 HOÀN THÀNH! Bạn đã thu được file {pt_path} (~20MB) ở định dạng PyTorch FP16.\")" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 456 }, "id": "zGmZPunYLw00", "outputId": "7ec29cdb-a966-4359-a407-51ef84fb5219" }, "execution_count": 9, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "🔄 Đang đọc và convert file ONNX: tinysam_fp16.onnx...\n", "❌ Lỗi trong quá trình dịch ONNX sang PyTorch: \"allowzero=1\" is not implemented\n", "🧪 Đang chạy thử nghiệm (Inference Test) để kiểm tra mô hình...\n", "⚠️ Cảnh báo chạy thử: name 'torch_model' is not defined\n", "💡 Mẹo: Một số toán tử ONNX đặc thù khi chuyển về PyTorch có thể đòi hỏi input chuẩn logic.\n", "💾 Đang lưu mô hình sang file PyTorch: tinysam_fp16.pt...\n" ] }, { "output_type": "error", "ename": "NameError", "evalue": "name 'torch_model' is not defined", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/tmp/ipykernel_12264/2269699233.py\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 43\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 44\u001b[0m \u001b[0;31m# Lưu ý: Nên lưu cả cấu trúc mạng (Tránh lỗi như lần trước)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 45\u001b[0;31m \u001b[0mtorch\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msave\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtorch_model\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mpt_path\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 46\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 47\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34mf\"🎉 HOÀN THÀNH! Bạn đã thu được file {pt_path} (~20MB) ở định dạng PyTorch FP16.\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mNameError\u001b[0m: name 'torch_model' is not defined" ] } ] }, { "cell_type": "code", "source": [ "import os\n", "import sys\n", "import subprocess\n", "\n", "# 1. Tự động kiểm tra và cài đặt thư viện mobile-sam nếu thiếu\n", "try:\n", " from mobile_sam import sam_model_registry\n", "except ImportError:\n", " print(\"📥 Đang cài đặt thư viện cấu trúc mạng mobile-sam...\")\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"git+https://github.com/ChaoningZhang/MobileSAM.git\"])\n", " from mobile_sam import sam_model_registry\n", "\n", "import torch\n", "\n", "# 2. Khai báo đường dẫn\n", "pth_path = \"tinysam.pth\"\n", "pt_fp16_path = \"tinysam_fp16.pt\"\n", "\n", "print(\"🔄 Đang dựng cấu trúc mạng TinySAM...\")\n", "sam = sam_model_registry[\"vit_t\"]()\n", "\n", "print(f\"📦 Đang nạp trọng số gốc từ: {pth_path}\")\n", "checkpoint = torch.load(pth_path, map_location=\"cpu\")\n", "sam.load_state_dict(checkpoint)\n", "\n", "# Tách riêng phần nặng nhất Image Encoder\n", "image_encoder = sam.image_encoder\n", "image_encoder.eval()\n", "\n", "# 3. Lượng tử hóa trực tiếp bằng PyTorch sang FP16\n", "print(\"⚡ Đang ép kiểu toàn bộ trọng số mô hình về FP16 (Half Precision)...\")\n", "image_encoder = image_encoder.half()\n", "\n", "# 4. Kiểm tra thử nghiệm tính toán\n", "print(\"🧪 Chạy thử nghiệm với dữ liệu giả lập kiểu FP16...\")\n", "try:\n", " # Dummy input dạng .half() để khớp với mô hình FP16\n", " dummy_input = torch.randn(1, 3, 1024, 1024).half()\n", " with torch.no_grad():\n", " output = image_encoder(dummy_input)\n", " print(\"✅ Mô hình FP16 hoạt động hoàn hảo trên PyTorch!\")\n", "except Exception as e:\n", " print(f\"❌ Lỗi chạy thử: {e}\")\n", "\n", "# 5. Lưu mô hình nguyên vẹn cấu trúc mạng\n", "print(f\"💾 Đang lưu mô hình sang: {pt_fp16_path}...\")\n", "torch.save(image_encoder, pt_fp16_path)\n", "\n", "print(f\"🎉 HOÀN THÀNH! Bạn đã có file {pt_fp16_path} (~20MB) thuần PyTorch dạng FP16.\")" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "5-fFxStTL-6R", "outputId": "87e4ca25-3c7e-4318-9f70-a51ac646d40d" }, "execution_count": 1, "outputs": [ { "output_type": "stream", "name": "stderr", "text": [ "/usr/local/lib/python3.12/dist-packages/timm/models/layers/__init__.py:49: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers\n", " warnings.warn(f\"Importing from {__name__} is deprecated, please import via timm.layers\", FutureWarning)\n", "/usr/local/lib/python3.12/dist-packages/timm/models/registry.py:4: FutureWarning: Importing from timm.models.registry is deprecated, please import via timm.models\n", " warnings.warn(f\"Importing from {__name__} is deprecated, please import via timm.models\", FutureWarning)\n", "/usr/local/lib/python3.12/dist-packages/mobile_sam/modeling/tiny_vit_sam.py:656: UserWarning: Overwriting tiny_vit_5m_224 in registry with mobile_sam.modeling.tiny_vit_sam.tiny_vit_5m_224. This is because the name being registered conflicts with an existing name. Please check if this is not expected.\n", " return register_model(fn_wrapper)\n", "/usr/local/lib/python3.12/dist-packages/mobile_sam/modeling/tiny_vit_sam.py:656: UserWarning: Overwriting tiny_vit_11m_224 in registry with mobile_sam.modeling.tiny_vit_sam.tiny_vit_11m_224. This is because the name being registered conflicts with an existing name. Please check if this is not expected.\n", " return register_model(fn_wrapper)\n", "/usr/local/lib/python3.12/dist-packages/mobile_sam/modeling/tiny_vit_sam.py:656: UserWarning: Overwriting tiny_vit_21m_224 in registry with mobile_sam.modeling.tiny_vit_sam.tiny_vit_21m_224. This is because the name being registered conflicts with an existing name. Please check if this is not expected.\n", " return register_model(fn_wrapper)\n", "/usr/local/lib/python3.12/dist-packages/mobile_sam/modeling/tiny_vit_sam.py:656: UserWarning: Overwriting tiny_vit_21m_384 in registry with mobile_sam.modeling.tiny_vit_sam.tiny_vit_21m_384. This is because the name being registered conflicts with an existing name. Please check if this is not expected.\n", " return register_model(fn_wrapper)\n", "/usr/local/lib/python3.12/dist-packages/mobile_sam/modeling/tiny_vit_sam.py:656: UserWarning: Overwriting tiny_vit_21m_512 in registry with mobile_sam.modeling.tiny_vit_sam.tiny_vit_21m_512. This is because the name being registered conflicts with an existing name. Please check if this is not expected.\n", " return register_model(fn_wrapper)\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ "🔄 Đang dựng cấu trúc mạng TinySAM...\n", "📦 Đang nạp trọng số gốc từ: tinysam.pth\n", "⚡ Đang ép kiểu toàn bộ trọng số mô hình về FP16 (Half Precision)...\n", "🧪 Chạy thử nghiệm với dữ liệu giả lập kiểu FP16...\n", "✅ Mô hình FP16 hoạt động hoàn hảo trên PyTorch!\n", "💾 Đang lưu mô hình sang: tinysam_fp16.pt...\n", "🎉 HOÀN THÀNH! Bạn đã có file tinysam_fp16.pt (~20MB) thuần PyTorch dạng FP16.\n" ] } ] }, { "cell_type": "code", "source": [ "import torch\n", "\n", "# 1. Thêm tham số weights_only=False để bỏ qua bộ lọc bảo mật đối với file do chính bạn tạo ra\n", "print(\"🔄 Đang nạp lại file tinysam_fp16.pt...\")\n", "model_object = torch.load(\"tinysam_fp16.pt\", map_location=\"cpu\", weights_only=False)\n", "\n", "# 2. Trích xuất duy nhất dictionary chứa các trọng số (weights)\n", "print(\"📦 Đang trích xuất trọng số và cấu trúc lại tên layer...\")\n", "state_dict_raw = model_object.state_dict()\n", "\n", "# Thêm tiền tố 'image_encoder.' vào trước mỗi layer để khớp hoàn toàn với cấu trúc\n", "# mà file build_sam.py của TinySAM gốc yêu cầu\n", "correct_state_dict = {}\n", "for k, v in state_dict_raw.items():\n", " if not k.startswith(\"image_encoder.\"):\n", " correct_state_dict[f\"image_encoder.{k}\"] = v\n", " else:\n", " correct_state_dict[k] = v\n", "\n", "# 3. Lưu lại ở dạng định dạng OrderedDict (Trọng số thuần túy)\n", "# Khi lưu dạng này, bất kỳ phiên bản PyTorch nào (kể cả weights_only=True) đều sẽ nạp được mượt mà\n", "output_path = \"tinysam_fp16_fixed.pt\"\n", "torch.save(correct_state_dict, output_path)\n", "\n", "print(f\"🎉 THÀNH CÔNG RỰC RỠ! Đã tạo xong file: {output_path}\")\n", "print(\"💡 Bây giờ bạn hãy tải file này lên Hugging Face Space, lỗi UnpicklingError sẽ biến mất hoàn toàn.\")" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "kDpikQftN3Sf", "outputId": "c9e59582-7282-4d93-8a4e-e6c46c68be92" }, "execution_count": 4, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "🔄 Đang nạp lại file tinysam_fp16.pt...\n", "📦 Đang trích xuất trọng số và cấu trúc lại tên layer...\n", "🎉 THÀNH CÔNG RỰC RỠ! Đã tạo xong file: tinysam_fp16_fixed.pt\n", "💡 Bây giờ bạn hãy tải file này lên Hugging Face Space, lỗi UnpicklingError sẽ biến mất hoàn toàn.\n" ] } ] }, { "cell_type": "code", "source": [ "import torch\n", "\n", "# 1. Khai báo đường dẫn file\n", "file_goc_fp32 = \"tinysam.pth\" # File gốc tải từ HF (40.7 MB)\n", "file_cua_ban_fp16 = \"tinysam_fp16.pt\" # File Object FP16 bạn tạo từ các bước trước\n", "\n", "print(\"🔄 Đang nạp các file trọng số...\")\n", "checkpoint_goc = torch.load(file_goc_fp32, map_location=\"cpu\", weights_only=False)\n", "model_fp16_obj = torch.load(file_cua_ban_fp16, map_location=\"cpu\", weights_only=False)\n", "\n", "# Lấy state_dict của phần Image Encoder FP16 từ mô hình của bạn\n", "encoder_fp16_dict = model_fp16_obj.state_dict()\n", "\n", "# 2. Tạo một bản dict mới để trộn dữ liệu\n", "final_state_dict = {}\n", "\n", "print(\"📦 Đang tiến hành trộn và ép kiểu các layer...\")\n", "\n", "# Duyệt qua toàn bộ file gốc để giữ lại các layer Prompt và Mask Decoder\n", "for key, value in checkpoint_goc.items():\n", " if key.startswith(\"image_encoder.\"):\n", " # Lấy layer tương ứng từ bản FP16 của bạn (bỏ hoặc thêm tiền tố cho khớp)\n", " sub_key = key.replace(\"image_encoder.\", \"\")\n", " if sub_key in encoder_fp16_dict:\n", " final_state_dict[key] = encoder_fp16_dict[sub_key].half()\n", " else:\n", " final_state_dict[key] = encoder_fp16_dict[key].half() if key in encoder_fp16_dict else value.half()\n", " else:\n", " # Giữ nguyên Prompt Encoder và Mask Decoder nhưng ép sang .half() (FP16) để đồng bộ dung lượng nhẹ\n", " final_state_dict[key] = value.half()\n", "\n", "# 3. Lưu file checkpoint hoàn chỉnh\n", "output_path = \"tinysam_fp16_full.pt\"\n", "torch.save(final_state_dict, output_path)\n", "\n", "print(f\"🎉 THÀNH CÔNG! Đã tạo xong file: {output_path}\")\n", "print(\"💡 File này chứa đầy đủ tất cả các Key và đã được tối ưu FP16. Hãy up file này lên Space của bạn.\")" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "rmLvScfrPH8S", "outputId": "035355d9-b8bc-4105-eb0d-9670411b6be1" }, "execution_count": 6, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "🔄 Đang nạp các file trọng số...\n", "📦 Đang tiến hành trộn và ép kiểu các layer...\n", "🎉 THÀNH CÔNG! Đã tạo xong file: tinysam_fp16_full.pt\n", "💡 File này chứa đầy đủ tất cả các Key và đã được tối ưu FP16. Hãy up file này lên Space của bạn.\n" ] } ] }, { "cell_type": "code", "source": [ "import torch\n", "import os\n", "\n", "# 1. Khai báo đường dẫn file\n", "file_goc_fp32 = \"tinysam.pth\"\n", "output_path = \"tinysam_int8_full.pt\"\n", "\n", "if not os.path.exists(file_goc_fp32):\n", " print(f\"❌ Lỗi: Không tìm thấy file gốc {file_goc_fp32} để xử lý.\")\n", " exit()\n", "\n", "print(\"🔄 Bước 1: Đang nạp mô hình gốc và chuẩn bị cấu trúc mạng...\")\n", "# Để lượng tử hóa INT8 chuẩn trong PyTorch, ta cần dựng cấu trúc nn.Module trước\n", "try:\n", " from mobile_sam import sam_model_registry\n", " sam = sam_model_registry[\"vit_t\"]()\n", "\n", " checkpoint_goc = torch.load(file_goc_fp32, map_location=\"cpu\", weights_only=False)\n", " sam.load_state_dict(checkpoint_goc)\n", " sam.eval()\n", " print(\"✅ Đã nạp cấu trúc mạng TinySAM.\")\n", "except ImportError:\n", " print(\"❌ Lỗi: Cần cài đặt thư viện mobile-sam để chạy cấu trúc mạng.\")\n", " exit()\n", "\n", "print(\"\\n⚡ Bước 2: Tiến hành lượng tử hóa 8-bit (INT8) cho các layer tính toán nặng...\")\n", "# Áp dụng lượng tử hóa động cho các lớp tuyến tính (Linear/nn.Linear) và các lớp tuần tự (LSTM/GRU nếu có)\n", "# Đối với ViT (Vision Transformer) trong TinySAM, các layer Linear chiếm phần lớn tính toán và dung lượng\n", "sam_int8 = torch.quantization.quantize_dynamic(\n", " sam,\n", " {torch.nn.Linear}, # Chỉ định các lớp áp dụng 8-bit\n", " dtype=torch.qint8 # Kiểu dữ liệu đích là số nguyên 8-bit\n", ")\n", "\n", "print(\"\\n📦 Bước 3: Trích xuất state_dict và đồng bộ hóa cho Space...\")\n", "# Trích xuất trọng số sau khi đã tối ưu 8-bit\n", "state_dict_int8 = sam_int8.state_dict()\n", "\n", "# Một số thành phần như Convolution (nn.Conv2d) không hỗ trợ lượng tử hóa động trực tiếp trong PyTorch CPU cơ bản,\n", "# vì vậy chúng sẽ được giữ nguyên hoặc tự động ép sang dạng phù hợp nhất để tránh lỗi \"Missing key\".\n", "# Đảm bảo toàn bộ các key gốc (bao gồm cả prompt_encoder và mask_decoder) đều có mặt.\n", "\n", "# 4. Lưu checkpoint\n", "torch.save(state_dict_int8, output_path)\n", "\n", "print(\"\\n\" + \"=\"*50)\n", "print(f\"🎉 HOÀN THÀNH XUẤT SẮC! File của bạn: {output_path}\")\n", "print(f\"📊 Kích thước ước tính: ~12MB (Giảm ~70% dung lượng so với bản 40MB gốc)\")\n", "print(\"💡 Mẹo: Bản INT8 này cực kỳ tiết kiệm RAM và CPU trên Hugging Face Space.\")\n", "print(\"=\"*50)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "qTKDtDTdQ8-1", "outputId": "a4afcde3-c556-44e2-e269-ff28e29deba9" }, "execution_count": 8, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "🔄 Bước 1: Đang nạp mô hình gốc và chuẩn bị cấu trúc mạng...\n", "✅ Đã nạp cấu trúc mạng TinySAM.\n", "\n", "⚡ Bước 2: Tiến hành lượng tử hóa 8-bit (INT8) cho các layer tính toán nặng...\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "/tmp/ipykernel_14696/1910624650.py:29: DeprecationWarning: torch.ao.quantization is deprecated and will be removed in 2.10. \n", "For migrations of users: \n", "1. Eager mode quantization (torch.ao.quantization.quantize, torch.ao.quantization.quantize_dynamic), please migrate to use torchao eager mode quantize_ API instead \n", "2. FX graph mode quantization (torch.ao.quantization.quantize_fx.prepare_fx,torch.ao.quantization.quantize_fx.convert_fx, please migrate to use torchao pt2e quantization API instead (prepare_pt2e, convert_pt2e) \n", "3. pt2e quantization has been migrated to torchao (https://github.com/pytorch/ao/tree/main/torchao/quantization/pt2e) \n", "see https://github.com/pytorch/ao/issues/2259 for more details\n", " sam_int8 = torch.quantization.quantize_dynamic(\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ "\n", "📦 Bước 3: Trích xuất state_dict và đồng bộ hóa cho Space...\n", "\n", "==================================================\n", "🎉 HOÀN THÀNH XUẤT SẮC! File của bạn: tinysam_int8_full.pt\n", "📊 Kích thước ước tính: ~12MB (Giảm ~70% dung lượng so với bản 40MB gốc)\n", "💡 Mẹo: Bản INT8 này cực kỳ tiết kiệm RAM và CPU trên Hugging Face Space.\n", "==================================================\n" ] } ] }, { "cell_type": "code", "source": [ "from google.colab import files\n", "\n", "# Kích hoạt trình duyệt tự động tải file về máy\n", "files.download('/content/tinysam_int8_full.pt')" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 17 }, "id": "vOX768CiMmdr", "outputId": "ba5d394b-324b-4ea8-af0c-88600d5cf321" }, "execution_count": 10, "outputs": [ { "output_type": "display_data", "data": { "text/plain": [ "" ], "application/javascript": [ "\n", " async function download(id, filename, size) {\n", " if (!google.colab.kernel.accessAllowed) {\n", " return;\n", " }\n", " const div = document.createElement('div');\n", " const label = document.createElement('label');\n", " label.textContent = `Downloading \"${filename}\": `;\n", " div.appendChild(label);\n", " const progress = document.createElement('progress');\n", " progress.max = size;\n", " div.appendChild(progress);\n", " document.body.appendChild(div);\n", "\n", " const buffers = [];\n", " let downloaded = 0;\n", "\n", " const channel = await google.colab.kernel.comms.open(id);\n", " // Send a message to notify the kernel that we're ready.\n", " channel.send({})\n", "\n", " for await (const message of channel.messages) {\n", " // Send a message to notify the kernel that we're ready.\n", " channel.send({})\n", " if (message.buffers) {\n", " for (const buffer of message.buffers) {\n", " buffers.push(buffer);\n", " downloaded += buffer.byteLength;\n", " progress.value = downloaded;\n", " }\n", " }\n", " }\n", " const blob = new Blob(buffers, {type: 'application/binary'});\n", " const a = document.createElement('a');\n", " a.href = window.URL.createObjectURL(blob);\n", " a.download = filename;\n", " div.appendChild(a);\n", " a.click();\n", " div.remove();\n", " }\n", " " ] }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ "" ], "application/javascript": [ "download(\"download_dd84ddc6-c9cb-409c-a89e-a6ff8ff9b5d6\", \"tinysam_int8_full.pt\", 13864563)" ] }, "metadata": {} } ] }, { "cell_type": "code", "source": [ "import torch\n", "import urllib.request\n", "import os\n", "\n", "url = \"https://huggingface.co/datasets/Supbatomic/mian/resolve/main/migan_512_places2.pt\"\n", "filename = \"migan_512_places2.pt\"\n", "\n", "# 1. Tải file từ link bạn gửi\n", "if not os.path.exists(filename):\n", " print(\"📥 Đang tải file migan_512_places2.pt từ Hugging Face...\")\n", " opener = urllib.request.build_opener()\n", " opener.addheaders = [('User-Agent', 'Mozilla/5.0')]\n", " urllib.request.install_opener(opener)\n", " urllib.request.urlretrieve(url, filename)\n", " print(\"✅ Tải file hoàn tất!\")\n", "else:\n", " print(\"📦 File đã có sẵn trong thư mục.\")\n", "\n", "# 2. Đọc dung lượng thực tế\n", "size_mb = os.path.getsize(filename) / (1024 * 1024)\n", "print(f\"📊 Dung lượng file: {size_mb:.2f} MB\")\n", "\n", "# 3. Kiểm tra mức lượng tử (Data type) của các trọng số bên trong\n", "print(\"🔍 Đang bóc tách và kiểm tra kiểu dữ liệu...\")\n", "checkpoint = torch.load(filename, map_location=\"cpu\", weights_only=False)\n", "\n", "dtype = \"Không xác định\"\n", "# Trường hợp file là state_dict (Dictionary)\n", "if isinstance(checkpoint, dict):\n", " # Nếu dict bị bọc bởi một key cha như 'state_dict' hoặc 'model'\n", " if 'state_dict' in checkpoint:\n", " checkpoint = checkpoint['state_dict']\n", " elif 'model' in checkpoint:\n", " checkpoint = checkpoint['model']\n", "\n", " for k, v in checkpoint.items():\n", " if isinstance(v, torch.Tensor):\n", " dtype = v.dtype\n", " break\n", "# Trường hợp file lưu cả Object Module mạng\n", "elif isinstance(checkpoint, torch.nn.Module):\n", " dtype = next(checkpoint.parameters()).dtype\n", "\n", "print(\"-\" * 50)\n", "print(f\"🎉 KẾT QUẢ KIỂM TRA MỨC LƯỢNG TỬ: {dtype}\")\n", "print(\"-\" * 50)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "wyDaxk1gTNgy", "outputId": "1e3a642b-1ccc-45c4-ded2-04f41bae8314" }, "execution_count": 13, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "📥 Đang tải file migan_512_places2.pt từ Hugging Face...\n", "✅ Tải file hoàn tất!\n", "📊 Dung lượng file: 28.18 MB\n", "🔍 Đang bóc tách và kiểm tra kiểu dữ liệu...\n", "--------------------------------------------------\n", "🎉 KẾT QUẢ KIỂM TRA MỨC LƯỢNG TỬ: torch.float32\n", "--------------------------------------------------\n" ] } ] }, { "cell_type": "code", "source": [ "import torch\n", "import os\n", "\n", "input_file = \"migan_512_places2.pt\"\n", "output_file = \"migan_512_places2_fp16.pt\"\n", "\n", "print(\"🔄 Đang nạp mô hình FP32...\")\n", "# Nạp file checkpoint gốc (tắt weights_only nếu mô hình chứa cấu trúc class tùy biến)\n", "checkpoint = torch.load(input_file, map_location=\"cpu\", weights_only=False)\n", "\n", "print(\"⚡ Đang tiến hành lượng tử hóa sang FP16 (Half Precision)...\")\n", "\n", "if isinstance(checkpoint, dict):\n", " # Trường hợp file là một state_dict (Dictionary chứa trọng số)\n", " # Ta duyệt qua từng layer để ép kiểu các Tensor số thực về dạng .half()\n", " checkpoint_fp16 = {}\n", " for key, value in checkpoint.items():\n", " if isinstance(value, torch.Tensor) and value.is_floating_point():\n", " checkpoint_fp16[key] = value.half()\n", " else:\n", " checkpoint_fp16[key] = value # Giữ nguyên nếu là biến số nguyên hoặc cấu hình khác\n", "else:\n", " # Trường hợp file lưu nguyên Object Module (nn.Module)\n", " checkpoint_fp16 = checkpoint.half()\n", "\n", "print(f\"💾 Đang lưu mô hình mới sang file: {output_file}...\")\n", "torch.save(checkpoint_fp16, output_file)\n", "\n", "# Kiểm tra lại dung lượng sau khi nén\n", "size_old = os.path.getsize(input_file) / (1024 * 1024)\n", "size_new = os.path.getsize(output_file) / (1024 * 1024)\n", "\n", "print(\"\\n\" + \"=\"*50)\n", "print(f\"🎉 CONVERT THÀNH CÔNG!\")\n", "print(f\"📊 Dung lượng bản gốc (FP32): {size_old:.2f} MB\")\n", "print(f\"📉 Dung lượng bản mới (FP16): {size_new:.2f} MB (Giảm ~50%)\")\n", "print(f\"💡 File '{output_file}' đã sẵn sàng để bạn deploy lên Mobile hoặc Hugging Face Space!\")\n", "print(\"=\"*50)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "eXXpo8QTTrXn", "outputId": "9296bc24-eda2-421f-eb05-c58aea5719ba" }, "execution_count": 15, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "🔄 Đang nạp mô hình FP32...\n", "⚡ Đang tiến hành lượng tử hóa sang FP16 (Half Precision)...\n", "💾 Đang lưu mô hình mới sang file: migan_512_places2_fp16.pt...\n", "\n", "==================================================\n", "🎉 CONVERT THÀNH CÔNG!\n", "📊 Dung lượng bản gốc (FP32): 28.18 MB\n", "📉 Dung lượng bản mới (FP16): 14.12 MB (Giảm ~50%)\n", "💡 File 'migan_512_places2_fp16.pt' đã sẵn sàng để bạn deploy lên Mobile hoặc Hugging Face Space!\n", "==================================================\n" ] } ] }, { "cell_type": "code", "source": [ "import torch\n", "import os\n", "\n", "input_file = \"migan_512_places2.pt\"\n", "output_file = \"migan_512_places2_int8_real.pt\"\n", "\n", "print(\"🔄 Đang nạp mô hình FP32...\")\n", "checkpoint = torch.load(input_file, map_location=\"cpu\", weights_only=False)\n", "\n", "# Nếu state_dict bị bọc bởi key cha như 'state_dict' hay 'model', ta đi sâu vào trong\n", "is_wrapped = False\n", "wrapper_key = None\n", "if isinstance(checkpoint, dict):\n", " for k in ['state_dict', 'model', 'generator']:\n", " if k in checkpoint:\n", " is_wrapped = True\n", " wrapper_key = k\n", " working_dict = checkpoint[k]\n", " break\n", " if not is_wrapped:\n", " working_dict = checkpoint\n", "\n", "print(\"⚡ Đang nén chặt và ép kiểu lưu trữ sang torch.int8...\")\n", "checkpoint_int8 = {}\n", "quant_meta = {} # Lưu lại thông tin scale để đồng bộ khi giải nén lúc chạy\n", "\n", "for key, value in working_dict.items():\n", " if isinstance(value, torch.Tensor) and value.is_floating_point() and value.numel() > 0:\n", " min_val, max_val = value.min().item(), value.max().item()\n", " if min_val != max_val:\n", " scale = (max_val - min_val) / 255.0\n", " zero_point = int(-min_val / scale) - 128\n", "\n", " # Ép chặt về kiểu dữ liệu int8 để giải phóng bộ nhớ file\n", " q_tensor = torch.round(value / scale) + zero_point\n", " q_tensor = torch.clamp(q_tensor, -128, 127).to(torch.int8)\n", "\n", " checkpoint_int8[key] = q_tensor\n", " quant_meta[key] = {'scale': scale, 'zero_point': zero_point}\n", " else:\n", " checkpoint_int8[key] = value\n", " else:\n", " checkpoint_int8[key] = value\n", "\n", "# Đóng gói lại đúng cấu trúc ban đầu\n", "final_save = {wrapper_key: checkpoint_int8, 'quant_meta': quant_meta} if is_wrapped else {'state_dict': checkpoint_int8, 'quant_meta': quant_meta}\n", "\n", "print(f\"💾 Đang lưu file nén thực tế: {output_file}...\")\n", "torch.save(final_save, output_file)\n", "\n", "size_old = os.path.getsize(input_file) / (1024 * 1024)\n", "size_new = os.path.getsize(output_file) / (1024 * 1024)\n", "\n", "print(\"\\n\" + \"=\"*50)\n", "print(f\"🎉 ĐÃ FIX THÀNH CÔNG!\")\n", "print(f\"📊 Dung lượng bản gốc (FP32): {size_old:.2f} MB\")\n", "print(f\"📉 Dung lượng bản mới thực tế (INT8): {size_new:.2f} MB\")\n", "print(f\"ℹ️ File đã giảm về mức ~7MB thành công!\")\n", "print(\"=\"*50)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "_pU3HjqIT66a", "outputId": "ce473b93-f89b-42eb-eb96-62dd69d14b4d" }, "execution_count": 18, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "🔄 Đang nạp mô hình FP32...\n", "⚡ Đang nén chặt và ép kiểu lưu trữ sang torch.int8...\n", "💾 Đang lưu file nén thực tế: migan_512_places2_int8_real.pt...\n", "\n", "==================================================\n", "🎉 ĐÃ FIX THÀNH CÔNG!\n", "📊 Dung lượng bản gốc (FP32): 28.18 MB\n", "📉 Dung lượng bản mới thực tế (INT8): 7.09 MB\n", "ℹ️ File đã giảm về mức ~7MB thành công!\n", "==================================================\n" ] } ] }, { "cell_type": "code", "source": [ "from google.colab import files\n", "\n", "# Kích hoạt trình duyệt tự động tải file về máy\n", "files.download('/content/migan_512_places2_int8_real.pt')" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 17 }, "id": "Q5i0d2rtTxXG", "outputId": "68b2b46c-371d-4eba-e5e8-b1e276652dcf" }, "execution_count": 19, "outputs": [ { "output_type": "display_data", "data": { "text/plain": [ "" ], "application/javascript": [ "\n", " async function download(id, filename, size) {\n", " if (!google.colab.kernel.accessAllowed) {\n", " return;\n", " }\n", " const div = document.createElement('div');\n", " const label = document.createElement('label');\n", " label.textContent = `Downloading \"${filename}\": `;\n", " div.appendChild(label);\n", " const progress = document.createElement('progress');\n", " progress.max = size;\n", " div.appendChild(progress);\n", " document.body.appendChild(div);\n", "\n", " const buffers = [];\n", " let downloaded = 0;\n", "\n", " const channel = await google.colab.kernel.comms.open(id);\n", " // Send a message to notify the kernel that we're ready.\n", " channel.send({})\n", "\n", " for await (const message of channel.messages) {\n", " // Send a message to notify the kernel that we're ready.\n", " channel.send({})\n", " if (message.buffers) {\n", " for (const buffer of message.buffers) {\n", " buffers.push(buffer);\n", " downloaded += buffer.byteLength;\n", " progress.value = downloaded;\n", " }\n", " }\n", " }\n", " const blob = new Blob(buffers, {type: 'application/binary'});\n", " const a = document.createElement('a');\n", " a.href = window.URL.createObjectURL(blob);\n", " a.download = filename;\n", " div.appendChild(a);\n", " a.click();\n", " div.remove();\n", " }\n", " " ] }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ "" ], "application/javascript": [ "download(\"download_632dff16-198d-42ea-9eee-49a5f5d6c3bf\", \"migan_512_places2_int8_real.pt\", 7437097)" ] }, "metadata": {} } ] } ] }