{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[],"dockerImageVersionId":28755,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# 1. Di chuyển về thư mục làm việc gốc và dọn dẹp dự án cũ nếu có\n%cd /kaggle/working\n!rm -rf ViTGaL\n\n# 2. Clone mã nguồn mới sạch sẽ từ GitHub\n!git clone https://github.com/PXThanhLam/ViTGaL.git\n%cd ViTGaL\n\n# 3. Cài đặt các thư viện Deep Learning cốt lõi\n!pip install -q timm scikit-learn tqdm\n\n# 4. Cài đặt pydegensac (bản đã build sẵn để tránh lỗi compile trên Kaggle)\n!pip install -q pydegensac\n\n# 5. Cài đặt bổ sung thư viện nền qudida và hạ cấp albumentations an toàn\n!pip install -q qudida\n!pip install -q --no-deps albumentations==1.3.1","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-03T06:54:41.744393Z","iopub.execute_input":"2026-06-03T06:54:41.744750Z","iopub.status.idle":"2026-06-03T06:54:57.742435Z","shell.execute_reply.started":"2026-06-03T06:54:41.744719Z","shell.execute_reply":"2026-06-03T06:54:57.741782Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\n# Đảm bảo đứng đúng thư mục dự án\nif os.path.basename(os.getcwd()) != \"ViTGaL\":\n    %cd /kaggle/working/ViTGaL\n\n# Đọc file cấu trúc mô hình gốc\nwith open(\"xcit_retrieval.py\", \"r\") as f:\n    code = f.read()\n\n# Định nghĩa hàm vá lỗi nâng cao: loại bỏ toàn bộ các biến cấu hình tự động của timm mới\npatch_code = \"\"\"\n# Bổ sung bản vá lỗi tương thích timm (Xóa sạch các cấu hình hệ thống tự động sinh ra)\ndef xcit_retrievalv2_small_12_p16_patched(*args, **kwargs):\n    timm_keys = ['pretrained_cfg', 'pretrained_cfg_overlay', 'cache_dir', 'model_cfg']\n    for key in timm_keys:\n        if key in kwargs:\n            del kwargs[key]\n    return XCiTRetrievalv2(\n        img_size=224,\n        patch_size=16,\n        embed_dim=384,\n        depth=12,\n        num_heads=8,\n        eta=1e-5,\n        tokens_norm=True,\n        **kwargs\n    )\n\"\"\"\n\n# Tiến hành chèn bản vá toàn diện vào file\nif \"xcit_retrievalv2_small_12_p16_patched\" not in code:\n    code += patch_code\n    code = code.replace(\n        \"def xcit_retrievalv2_small_12_p16(pretrained=False, **kwargs):\",\n        \"def xcit_retrievalv2_small_12_p16(pretrained=False, **kwargs):\\n    return xcit_retrievalv2_small_12_p16_patched(**kwargs)\"\n    )\n    print(\"-> THÀNH CÔNG: Đã cấu hình bộ lọc bóc tách sạch sẽ các tham số hệ thống dư thừa của timm!\")\nelse:\n    print(\"-> File xcit_retrieval.py đã được vá từ trước.\")\n\nwith open(\"xcit_retrieval.py\", \"w\") as f:\n    f.write(code)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-03T06:54:57.744075Z","iopub.execute_input":"2026-06-03T06:54:57.744396Z","iopub.status.idle":"2026-06-03T06:54:57.754029Z","shell.execute_reply.started":"2026-06-03T06:54:57.744366Z","shell.execute_reply":"2026-06-03T06:54:57.753372Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 1. Sửa lỗi cứng đường dẫn trong file script tạo split gốc của tác giả\n!sed -i \"s|args.data_path + '/train_split.txt'|'train_split.txt'|g\" create_train_split.py\n!sed -i \"s|args.data_path + '/test_split.txt'|'test_split.txt'|g\" create_train_split.py\n\n# 2. Tiến hành chạy tạo file text phân chia dữ liệu hình ảnh gốc toàn bộ cuộc thi\n!python create_train_split.py \\\n    --data_path /kaggle/input/competitions/landmark-retrieval-2021","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-03T06:54:57.754926Z","iopub.execute_input":"2026-06-03T06:54:57.755211Z","iopub.status.idle":"2026-06-03T06:55:08.264961Z","shell.execute_reply.started":"2026-06-03T06:54:57.755179Z","shell.execute_reply":"2026-06-03T06:55:08.263443Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ================= CONFIG SỐ LƯỢNG ẢNH MONG MUỐN =================\n# Nếu muốn chạy TOÀN BỘ hơn 1.2 triệu ảnh -> Hãy đặt: MAX_TRAIN_IMAGES = None\n# Nếu muốn chạy TEST NHANH (ví dụ: 10000 ảnh) -> Hãy đặt: MAX_TRAIN_IMAGES = 10000\n\nMAX_TRAIN_IMAGES = 10000  # <--- BẠN THAY ĐỔI CẤU HÌNH TẠI ĐÂY\n\n# =================================================================\n\nimport os\n\nif MAX_TRAIN_IMAGES is None:\n    # Sao chép nguyên bản toàn bộ danh sách ảnh gốc để train\n    !cp train_split.txt final_train_split.txt\n    !cp test_split.txt final_test_split.txt\n    print(f\"-> ĐANG CHỌN: Huấn luyện trên TOÀN BỘ bộ dữ liệu gốc.\")\nelse:\n    # Trích xuất số lượng dòng cụ thể theo ý bạn để debug siêu tốc\n    # Tính toán tỷ lệ tập test bằng khoảng 20% tập train tương ứng\n    max_test_images = max(100, int(MAX_TRAIN_IMAGES * 0.2))\n    \n    os.system(f\"head -n {MAX_TRAIN_IMAGES} train_split.txt > final_train_split.txt\")\n    os.system(f\"head -n {max_test_images} test_split.txt > final_test_split.txt\")\n    print(f\"-> ĐANG CHỌN: Huấn luyện nhanh với tối đa {MAX_TRAIN_IMAGES} ảnh.\")\n\n# Kiểm tra tổng số ảnh thực tế sẽ đưa vào mô hình chính\nprint(\"\\n--- Số lượng mẫu dữ liệu đầu vào cuối cùng ---\")\n!wc -l final_train_split.txt\n!wc -l final_test_split.txt","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-03T06:55:08.266289Z","iopub.execute_input":"2026-06-03T06:55:08.266793Z","iopub.status.idle":"2026-06-03T06:55:08.516036Z","shell.execute_reply.started":"2026-06-03T06:55:08.266733Z","shell.execute_reply":"2026-06-03T06:55:08.515129Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import argparse\nimport pathlib\nimport torch\n\n# Tạo sẵn các cấu trúc thư mục lưu đầu ra mô hình\n!mkdir -p checkpoints/debug\n!mkdir -p checkpoints/vitgal\n!mkdir -p checkpoints/vitgal_ae\n\n# Cấp quyền cho Notebook load các class cấu hình hệ thống\ntorch.serialization.add_safe_globals([argparse.Namespace, pathlib.PosixPath])\n\n# Đọc và tiến hành vá bảo mật PyTorch 2.6+ trực tiếp vào file main.py\nwith open(\"main.py\", \"r\") as f:\n    main_code = f.read()\n\nsecurity_patch = \"\"\"\nimport argparse\nimport pathlib\nimport torch\ntry:\n    torch.serialization.add_safe_globals([argparse.Namespace, pathlib.PosixPath])\nexcept Exception:\n    pass\n\"\"\"\n\nif \"add_safe_globals\" not in main_code:\n    main_code = main_code.replace(\"import torch\", \"import torch\" + security_patch, 1)\n    print(\"-> THÀNH CÔNG: Đã vá lỗi UnpicklingError trực tiếp vào file main.py!\")\nelse:\n    print(\"-> File main.py đã được cấu hình an toàn từ trước.\")\n\nwith open(\"main.py\", \"w\") as f:\n    f.write(main_code)\n\n# Kiểm tra thử đường dẫn tệp weights pretrain\nprint(\"\\nĐang kiểm tra nạp thử file weights pretrain...\")\nckpt = torch.load(\n    \"/kaggle/input/datasets/vuongtuanminh/pretrain-dataset-vitgal/xcit_small_12_p16_224.pth\",\n    map_location=\"cpu\"\n)\nprint(\"-> Xác thực thành công file weights dạng:\", type(ckpt))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-03T06:55:08.517992Z","iopub.execute_input":"2026-06-03T06:55:08.518803Z","iopub.status.idle":"2026-06-03T06:55:18.536536Z","shell.execute_reply.started":"2026-06-03T06:55:08.518764Z","shell.execute_reply":"2026-06-03T06:55:18.535748Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\n\nprint(\"CUDA Available:\", torch.cuda.is_available())\nif torch.cuda.is_available():\n    print(\"GPU Device Name:\", torch.cuda.get_device_name(0))\nelse:\n    print(\"⚠️ CẢNH BÁO: Hãy chắc chắn bạn đã kích hoạt GPU trong mục Settings (bên phải màn hình Kaggle)!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-03T06:55:18.537769Z","iopub.execute_input":"2026-06-03T06:55:18.538221Z","iopub.status.idle":"2026-06-03T06:55:18.841917Z","shell.execute_reply.started":"2026-06-03T06:55:18.538194Z","shell.execute_reply":"2026-06-03T06:55:18.841028Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\n# 1. Ép hệ thống ẩn các cảnh báo không cần thiết để logs hiển thị sạch sẽ\nos.environ[\"PYTHONWARNINGS\"] = \"ignore::FutureWarning\"\n\n# 2. Gọi lệnh thực thi huấn luyện mô hình chính\n!python main.py \\\n    --model xcit_retrievalv2_small_12_p16 \\\n    --pretrained /kaggle/input/datasets/vuongtuanminh/pretrain-dataset-vitgal/xcit_small_12_p16_224.pth \\\n    --data-path /kaggle/input/competitions/landmark-retrieval-2021 \\\n    --train_split /kaggle/working/ViTGaL/final_train_split.txt \\\n    --val_split /kaggle/working/ViTGaL/final_test_split.txt \\\n    --batch-size 32 \\\n    --epochs 1 \\\n    --num_workers 2 \\\n    --output_dir checkpoints/debug","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-03T06:55:18.843001Z","iopub.execute_input":"2026-06-03T06:55:18.843298Z","iopub.status.idle":"2026-06-03T07:03:45.561382Z","shell.execute_reply.started":"2026-06-03T06:55:18.843275Z","shell.execute_reply":"2026-06-03T07:03:45.560501Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!find checkpoints/debug -name \"*.pth\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-03T07:03:45.562785Z","iopub.execute_input":"2026-06-03T07:03:45.563151Z","iopub.status.idle":"2026-06-03T07:03:45.703533Z","shell.execute_reply.started":"2026-06-03T07:03:45.563120Z","shell.execute_reply":"2026-06-03T07:03:45.702780Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python main_reduction_ae.py --help","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-03T07:04:19.597748Z","iopub.execute_input":"2026-06-03T07:04:19.598199Z","iopub.status.idle":"2026-06-03T07:04:26.257795Z","shell.execute_reply.started":"2026-06-03T07:04:19.598164Z","shell.execute_reply":"2026-06-03T07:04:26.257009Z"}},"outputs":[],"execution_count":null}]}