diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..de48edc897787c7f47c9cfde840ce7763560b0b2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,170 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/latest/usage/project/#working-with-version-control +.pdm.toml +.pdm-python +.pdm-build/ + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +output +tf-logs +tmp/ +scripts_tmp/ +logs/*.log + +testing.ipynb \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a8f4b39fc0cc691c1b9c13153879211f17c2b130 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e588cfc61fcc1d83cabca8116e165dbb7b72a64f --- /dev/null +++ b/README.md @@ -0,0 +1,755 @@ +# Fine-tuning Qwen-VL Series + +This repository contains a script for training [Qwen2-VL](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct), [Qwen2.5-VL](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct) +and [Qwen3-VL](https://huggingface.co/Qwen/Qwen3-VL-4B-Thinking) with only using HuggingFace and [Liger-Kernel](https://github.com/linkedin/Liger-Kernel). + +## Other projects + +**[[Phi3-Vision Finetuning]](https://github.com/2U1/Phi3-Vision-Finetune)**
+**[[Llama3.2-Vision Finetuning]](https://github.com/2U1/Llama3.2-Vision-Ft)**
+**[[Molmo Finetune]](https://github.com/2U1/Molmo-Finetune)**
+**[[Pixtral Finetune]](https://github.com/2U1/Pixtral-Finetune)**
+**[[SmolVLM Finetune]](https://github.com/2U1/SmolVLM-Finetune)**
+**[[Gemma3 Finetune]](https://github.com/2U1/Gemma3-Finetune)** + +## Update + +- [2025/11/28] 🔥**Supports video training with DPO and GRPO.** +- [2025/11/27] 🔥**Supports Qwen3-VL-MoE** +- [2025/11/26] Update support for liger-kernel in Qwen3-VL. +- [2025/10/16] 🔥**Supports Qwen3-VL(non-moe)** +- [2025/08/21] Add option for using 2-layer mlp for classification. +- [2025/08/21] Add option for unfreeze only few layers for llm and vision tower. +- [2025/08/08] 🔥Monkey patch Qwen2.5-VL's window attention and forward for using less memory and speedups. +- [2025/07/25] Updated Classification training script for experimental feature. +- [2025/05/29] 🔥Supports GRPO training. +- [2025/04/16] 🔥Supports DPO training. +- [2025/03/04] Add Option for using liger kernel. +- [2025/02/18] 🔥Supports mixed-modality dataset with zero3. +- [2025/02/05] Fixed code for properly use image. +- [2025/02/03] Support Liger-kernel for Qwen2.5-VL. +- [2025/02/03] 🔥Supports Qwen2.5-VL. +- [2025/01/24] Add option for using DoRA. +- [2025/01/24] Fix error in LoRA training. +- [2025/01/18] 🔥Supports mixed-modality data. +- [2024/09/12] 🔥Now the model is trained using [Liger-Kernel](https://github.com/linkedin/Liger-Kernel). +- [2024/09/11] Supports setting different learning rates to projector and vision model. +- [2024/09/11] 🔥Supports multi-image and video training. + +## Table of Contents + +- [Fine-tuning Qwen-VL Series](#fine-tuning-qwen-vl-series) + - [Other projects](#other-projects) + - [Update](#update) + - [Table of Contents](#table-of-contents) + - [Supported Features](#supported-features) + - [Docker](#docker) + - [Installation](#installation) + - [Environments](#environments) + - [Using `requirements.txt`](#using-requirementstxt) + - [Using `environment.yaml`](#using-environmentyaml) + - [Dataset Preparation](#dataset-preparation) + - [Supervised Fine Tuning](#supervised-fine-tuning) + - [Full Finetuning](#full-finetuning) + - [Finetune with LoRA](#finetune-with-lora) + - [Train with video dataset](#train-with-video-dataset) + - [Image Resolution for vram usage](#image-resolution-for-vram-usage) + - [Merge LoRA Weights](#merge-lora-weights) + - [Evaluation during Training](#evaluation-during-training) + - [Step 1: Prepare Evaluation Dataset](#step-1-prepare-evaluation-dataset) + - [Step 2: Define compute\_metrics Function](#step-2-define-compute_metrics-function) + - [Step 3: Modify Training Script](#step-3-modify-training-script) + - [Step 4: Add Evaluation Arguments](#step-4-add-evaluation-arguments) + - [DPO Finetuning](#dpo-finetuning) + - [GRPO Finetuning](#grpo-finetuning) + - [Prerequisites](#prerequisites) + - [Classification Finetuning](#classification-finetuning) + - [⚠️This is an experimental feature.](#️this-is-an-experimental-feature) + - [Experimental Features](#experimental-features) + - [Inference](#inference) + - [Gradio Infernce (WebUI)](#gradio-infernce-webui) + - [Issue for libcudnn error](#issue-for-libcudnn-error) + - [TODO](#todo) + - [Known Issues](#known-issues) + - [License](#license) + - [Citation](#citation) + - [Acknowledgement](#acknowledgement) + +## Supported Features + +- Deepspeed +- LoRA/QLoRA +- Full-finetuning +- Enable finetuning `vision_model` while using LoRA +- Unfreeze only top-k layer +- Disable/enable Flash Attention 2 +- Multi-image and video training +- Training optimized with liger kernel +- Mixed-modality dataset +- Direct Preference Optimization (DPO) +- Group Relative Policy Optimization (GRPO) + +## Docker + +To simplfy the setting process for training, you could use the provided pre-build environments.
+The settings are done in the conda env named `train`.

+You could find more information about the image [here](https://hub.docker.com/repository/docker/john119/vlm/general). + +``` +docker pull john119/vlm +docker run --gpus all -it -v /host/path:/docker/path --name vlm --ipc=host john119/vlm /bin/bash +``` + +## Installation + +### Environments + +- Ubuntu 22.04 +- Nvidia-Driver 550.120 +- Cuda version 12.8 + +Install the required packages using `environment.yaml`. + +### Using `requirements.txt` + +```bash +pip install -r requirements.txt -f https://download.pytorch.org/whl/cu128 +pip install qwen-vl-utils +pip install flash-attn --no-build-isolation +``` + +### Using `environment.yaml` + +```bash +conda env create -f environment.yaml +conda activate train +pip install qwen-vl-utils +pip install flash-attn --no-build-isolation +``` + +**Note:** You should install flash-attn after installing the other packages. + +## Dataset Preparation + +The script requires a dataset formatted according to the LLaVA specification. The dataset should be a JSON file where each entry contains information about conversations and images. Ensure that the image paths in the dataset match the provided `--image_folder`.
+ +**When using a multi-image dataset, the image tokens should all be ``, and the image file names should have been in a list.**

+**Please see the example below and follow format your data.** + +
+Example for single image dataset + +```json +[ + { + "id": "000000033471", + "image": "000000033471.jpg", + "conversations": [ + { + "from": "human", + "value": "\nWhat are the colors of the bus in the image?" + }, + { + "from": "gpt", + "value": "The bus in the image is white and red." + }, + { + "from": "human", + "value": "What feature can be seen on the back of the bus?" + }, + { + "from": "gpt", + "value": "The back of the bus features an advertisement." + }, + { + "from": "human", + "value": "Is the bus driving down the street or pulled off to the side?" + }, + { + "from": "gpt", + "value": "The bus is driving down the street, which is crowded with people and other vehicles." + } + ] + } + ... +] +``` + +
+ +
+Example for multi image dataset + +```json +[ + { + "id": "000000033471", + "image": ["000000033471.jpg", "000000033472.jpg"], + "conversations": [ + { + "from": "human", + "value": "\n\nIs the perspective of the camera differnt?" + }, + { + "from": "gpt", + "value": "Yes, It the perspective of the camera is different." + } + ] + } + ... +] +``` + +
+ +
+Example for video dataset + +```json +[ + { + "id": "sample1", + "video": "sample1.mp4", + "conversations": [ + { + "from": "human", + "value": "
+ +
+Example for DPO dataet + +```json +[ + { + "id": "e4cd017f-3854-4019-9cc1-9dacacb5d424", + "image": "example_0_0.png", + "prompt": "\nDescribe the key features of the image in great detail.", + "chosen": "The image features a modern, multi-colored train parked on a train track, occupying a significant portion of the scene. The train has a unique and striking design, with red, white, and blue colors, as well as yellow accents. It appears to be a high-speed train, indicating its advanced engineering and potential for fast travel.\n\nThe train is situated next to a platform, suggesting that it may be at a train station. The overall scene conveys a sense of transportation and modern technology, with the vibrant and sleek train as the main subject.", + "rejected": "The image features a modern, colorful train parked on a set of train tracks. The train has a striking design, with red, white, and blue colors as well as yellow accents. It appears to be a high-speed train, ready for departure.\n\nThe train spans a significant portion of the image, from the left to the right side. The train tracks can be seen clearly beneath the train, emphasizing its position on the railway line. The overall scene gives off an impression of a contemporary and efficient mode of transportation." + }, + { + "id": "5e19e647-e5d3-4bcf-82e9-d262570743ae", + "image": "example_1_0.png", + "prompt": "\nIs this bus in the USA?", + "chosen": "Yes, based on the image, it can be assumed that this bus is in the USA. The location of the bus cannot be accurately determined.", + "rejected": "No, it's not in the USA. The image does not provide specific information on where the bus is located. However, we can say that it's not in the United States." + } + ... +] +``` + +
+ +
+Example for GRPO dataset + +```json +[ + { + "id": "06bc8a17-bb1c-4007-8c08-92c41e2628b2", + "image": "image_2.jpg", + "conversations": [ + { + "from": "human", + "value": "\nBased on the image, which geometric method is used to determine the bearing angle, and why is it the most appropriate choice?" + }, + { + "from": "gpt", + "value": "Let's analyze the image step-by-step. The image shows a right-angled triangle with points B, C, and A. The angle at point B is a right angle, indicating that trigonometric functions can be applied. To find the bearing angle, we need to relate the sides of the triangle. The tangent function is suitable here because it relates the opposite side (BC) to the adjacent side (AB) in a right-angled triangle. By using the tangent function, we can calculate the angle at point A, which is the bearing angle. Therefore, the most appropriate geometric method is the use of trigonometric functions.\n\nA" + } + ] + } + ... +] +``` + +
+ +

+ +Adding the new domain-specific data on top of the general data from open-source data will enhance downstream capabilities while retaining the foundational skills. Of course, you can also choose to fine-tune solely on the new data based on your requirements. + +## Supervised Fine Tuning + +⚠️**For Qwen3-VL models, using liger-kernel with full fine-tuning is awfully slow. I recommend turning off liger-kernel or use zero2 with full-finetuning.**

+ +**Note:** Deepspeed zero2 is faster than zero3, however it consumes more memory. Also, most of the time zero2 is more stable than zero3.

+**Tip:** You could use `adamw_bnb_8bit` for optimizer to save memory. + +To run the training script, use the following command: + +### Full Finetuning + +**Note:** If you want to use `unfreeze_topk_llm` or `unfreeze_topk_vision` you should set `-freeze_llm` or `--freeze_vision_tower` to `true`. + +```bash +bash scripts/finetune.sh +``` + +### Finetune with LoRA + +**Note:** Liger-kernel won't work with QLoRA. You need to disable to use QLoRA.
+If you want to train only the language model with LoRA and perform full training for the vision model: + +```bash +bash scripts/finetune_lora.sh +``` + +If you want to train both the language model and the vision model with LoRA: + +```bash +bash scripts/finetune_lora_vision.sh +``` + +**IMPORTANT:** If you want to tune the `embed_token` with LoRA, You need to tune `lm_head` together. + +
+Training arguments + +- `--deepspeed` (str): Path to DeepSpeed config file (default: "scripts/zero2.json"). +- `--data_path` (str): Path to the LLaVA formatted training data (a JSON file). **(Required)** +- `--image_folder` (str): Path to the images folder as referenced in the LLaVA formatted training data. **(Required)** +- `--model_id` (str): Path to the Qwen2-VL model. **(Required)** +- `--use_liger` (bool): Option for using liger kernel to save memory. +- `--output_dir` (str): Output directory for model checkpoints +- `--num_train_epochs` (int): Number of training epochs (default: 1). +- `--per_device_train_batch_size` (int): Training batch size per GPU per forwarding step. +- `--gradient_accumulation_steps` (int): Gradient accumulation steps (default: 4). +- `--freeze_vision_tower` (bool): Option to freeze vision_model (default: False). +- `--freeze_llm` (bool): Option to freeze LLM (default: False). +- `--freeze_merger` (bool): Option to tune projector (default: False). +- `--num_lora_modules` (int): Number of target modules to add LoRA (-1 means all layers). +- `--vision_lr` (float): Learning rate for vision_model. +- `--merger_lr` (float): Learning rate for merger(projector). +- `--learning_rate` (float): Learning rate for language module. +- `--bf16` (bool): Option for using bfloat16. +- `--fp16` (bool): Option for using fp16. +- `--image_min_pixels` (int): Option for minimum input tokens for image. +- `--image_max_pixles` (int): Option for maximum maxmimum tokens for image. +- `--video_min_pixels` (int): Option for minimum input tokens for video. +- `--video_max_pixles` (int): Option for maximum maxmimum tokens for video. +- `--image_resized_width` (int): Option for setting the width of the input image. +- `--image_resized_height` (int): Option for setting the height of the input image. +- `--video_resized_width` (int): Option for setting the width of the input video. +- `--video_resized_height` (int): Option for setting the height of the input video. +- `--fps` (float): Frames per second for video data. +- `--nframes` (int): Number of frames for video data. +- `--unfreeze_topk_llm` (int): Number of top layers to unfreeze in the language model. +- `--unfreeze_topk_vision` (int): Number of top layers to unfreeze in the vision model. +- `--lora_enable` (bool): Option for using LoRA. +- `--vision_lora` (bool): Option for including `vision_tower` in LoRA module. `lora_enable` should be `True` to use this option. +- `--use_dora` (bool): Option for using DoRA instead of LoRA. `lora_enable` should be `True` to use this option. +- `--lora_namespan_exclude` (str): Exclude modules with namespans to add LoRA. +- `--max_seq_length` (int): Maximum sequence length (default: 32K). +- `--bits` (int): Quantization bits (default: 16). +- `--disable_flash_attn2` (bool): Disable Flash Attention 2. +- `--report_to` (str): Reporting tool (choices: 'tensorboard', 'wandb', 'none') (default: 'tensorboard'). +- `--logging_dir` (str): Logging directory (default: "./tf-logs"). +- `--lora_rank` (int): LoRA rank (default: 128). +- `--lora_alpha` (int): LoRA alpha (default: 256). +- `--lora_dropout` (float): LoRA dropout (default: 0.05). +- `--logging_steps` (int): Logging steps (default: 1). +- `--dataloader_num_workers` (int): Number of data loader workers (default: 4). + +**Note:** The learning rate of `vision_model` should be 10x ~ 5x smaller than the `language_model`. + +
+ +### Train with video dataset + +You can train the model using a video dataset. You can set LoRA configs and use for LoRA too.
+**Note:** You could not set `fps` and `nframes` at the same time. + +```bash +bash scripts/finetune_video.sh +``` + +**Note:** When training with video, it just as multi-image so you should adjust the `max_pixels` for maximum resolution and `fps` based on the available VRAM. + +If you run out of vram, you can use [zero3_offload](./scripts/zero3_offload.json) instead of [zero3](./scripts/zero3_offload.json).
+You could use [zero2_offload](./scripts/zero2_offload.json) for a bit faster training. + +#### Image Resolution for vram usage + +The model supprots a wide range of resolution inputs. By default, it uses the native resolution for input. +For better performance using native or higer pixel numbers are recommended, however it takes too much memory and computation time for large images. So you could adjust the pixel numbers for it. +The model splits the image into `token * 28 * 28` so you could just change the the token_num part in the script.

+⚠️**For Qwen3-VL models, it should be `token * 32 * 32`.**

+For example: + +``` +--image_min_pixels $((256 * 28 * 28)) +--image_max_pixels $((1280 * 28 * 28)) +--video_min_pixels $((128 * 28 * 28)) +--video_max_pixels $((768 * 28 * 28)) +``` + +Besides you could directly set the image/video height and width to control over the memory. + +``` +--image_resized_width 448 +--image_resized_height 448 +--video_resized_width 448 +--video_resized_height 448 +``` + +These values will be rounded to the nearest multiple of 28. + +#### Merge LoRA Weights + +``` +bash scripts/merge_lora.sh +``` + +**Note:** Remember to replace the paths in `finetune.sh` or `finetune_lora.sh` with your specific paths. (Also in `merge_lora.sh` when using LoRA.) + +### Evaluation during Training + +You can run generation-based evaluation during training by providing an evaluation dataset and a custom `compute_metrics` function. This allows you to monitor metrics like accuracy, BLEU, or any custom metric based on the model's generated text outputs. + +#### Step 1: Prepare Evaluation Dataset + +The evaluation dataset uses the same format as the training dataset. Place your evaluation data JSON file and specify the path using `--eval_path`. + +```json +[ + { + "id": "eval_001", + "image": "test_image.jpg", + "conversations": [ + { + "from": "human", + "value": "\nWhat is shown in this image?" + }, + { + "from": "gpt", + "value": "A cat sitting on a couch." + } + ] + } +] +``` + +#### Step 2: Define compute_metrics Function + +Create a custom `compute_metrics` function in your training script. The function receives a `GenerativeEvalPrediction` object containing: + +- `predictions`: List of generated text strings from the model +- `references`: List of ground truth answer strings + +```python +from src.trainer import GenerativeEvalPrediction + +def compute_metrics(eval_pred: GenerativeEvalPrediction): + predictions = eval_pred.predictions + references = eval_pred.references + + # Example: Exact match accuracy + correct = sum( + 1 for p, r in zip(predictions, references) + if p.strip().lower() == r.strip().lower() + ) + accuracy = correct / len(predictions) if predictions else 0 + + return {"accuracy": accuracy} +``` + +#### Step 3: Modify Training Script + +Update your training script (`src/train/train_sft.py`) to pass `compute_metrics` to the trainer: + +```python +from src.trainer import QwenSFTTrainer, GenerativeEvalPrediction + +def compute_metrics(eval_pred: GenerativeEvalPrediction): + predictions = eval_pred.predictions + references = eval_pred.references + correct = sum(1 for p, r in zip(predictions, references) if p.strip() == r.strip()) + return {"accuracy": correct / len(predictions)} + +# ... (model and data setup code) + +trainer = QwenSFTTrainer( + model=model, + processing_class=processor, + args=training_args, + compute_metrics=compute_metrics, # Add this line + **data_module +) +``` + +#### Step 4: Add Evaluation Arguments + +Add these arguments to your training script: + +```bash + --eval_path /path/to/eval.json \ + --eval_strategy steps \ + --eval_steps 500 \ + --per_device_eval_batch_size 1 \ + --generation_max_new_tokens 256 \ + --prediction_loss_only False \ + # ... other arguments +``` + +
+Evaluation Arguments + +- `--eval_path` (str): Path to the evaluation data JSON file. +- `--eval_strategy` (str): Evaluation strategy - "steps" or "epoch" (default: "no"). +- `--eval_steps` (int): Number of steps between evaluations (when eval_strategy="steps"). +- `--per_device_eval_batch_size` (int): Batch size for evaluation (default: 8). +- `--generation_max_new_tokens` (int): Maximum new tokens to generate during evaluation (default: 512). +- `--prediction_loss_only` (bool): Set to False to enable generation-based evaluation (default: True). + +
+ +
+Example: Custom Metrics with Multiple Scores + +```python +from src.trainer import GenerativeEvalPrediction +import re + +def compute_metrics(eval_pred: GenerativeEvalPrediction): + predictions = eval_pred.predictions + references = eval_pred.references + + # Exact match + exact_matches = sum( + 1 for p, r in zip(predictions, references) + if p.strip().lower() == r.strip().lower() + ) + + # Contains match (reference appears in prediction) + contains_matches = sum( + 1 for p, r in zip(predictions, references) + if r.strip().lower() in p.strip().lower() + ) + + n = len(predictions) + return { + "exact_match": exact_matches / n if n > 0 else 0, + "contains_match": contains_matches / n if n > 0 else 0, + } +``` + +
+ +**Note:** Generation-based evaluation is slower than loss-only evaluation because it runs `model.generate()` for each sample. Consider using a smaller evaluation dataset or less frequent evaluation steps. + +## DPO Finetuning + +You can train the model using Direct Preference Optimization (DPO).
+The process is quite similar to Supervised Fine-Tuning (SFT), and you can also apply LoRA during DPO training just like in SFT. + +```bash +bash scripts/finetune_dpo.sh +``` + +Most of the training arugments are same as SFT, but few other arguments are added for DPO training. + +
+Training arguments + +- `--dpo_loss` (str): Loss type for dpo. (default: 'sigmoid') +- `--precompute_ref_log_probs` (bool): Wheter to precompute the reference log probs (default: False) +- `--beta` (float): The beta value for DPO (default: 0.1) + +
+ +## GRPO Finetuning + +You can traing the model using Group Relative Policy Optimization (GRPO)
+The process is quite similar to Supervised Fine-Tuning (SFT), and you can also apply LoRA during GRPO training just like in SFT.
+
+ +### Prerequisites + +| What | Where | Notes | +| ------------------------- | --------------------------- | ------------------------------------------------------------------------------------------- | +| **Reward functions** | `src/train/reward_funcs.py` | Add any function that ends with `_reward`. The training script picks them up automatically. | +| **Custom system prompts** | `src/constants.py` | Append your own prompt strings here. | + +You could start training using this script.
+Before training, **Please check the dataset format once more.** The format is a bit different from other training methods. + +```bash +bash scripts/finetune_grpo.sh +``` + +Most of the training arugments are same as SFT, but few other arguments are added for GRPO training. + +
+Training arguments + +- `--temperature` (float): Generation config (default: 0.9) +- `--top_p` (float): Generation config (default: 1.0) +- `--top_k` (int): Generation config (default: 50) +- `--min_p` (float): Generation config (default: None) +- `--repetition_penalty` (float): Generation config (default: 1.0) +- `--max_completion_length` (int): Max length for the completion (default: 256) +- `--max_prompt_length` (int): Max length for the prompt (default: 512) +- `--beta` (float): KL Coefficient. (default: 0.04) + +
+ +## Classification Finetuning + +### ⚠️This is an experimental feature. + +The [model](src/model/modeling_cls.py) is tailored for classification tasks, such as other SequenceClassification models. + +For the classification task, you need to prepare the dataset in a specific format. The dataset should be a JSON file where each entry contains an image and its corresponding label. The labels should be integers starting from 0.
+You can set the text in the filed `prompt` to provide a questions and options for the classification task. Also if your dataset dose not contain the `prompt` field, the script will automatically use the `USER_MESSAGE` from the [cls_dataset.py](src/dataset/cls_dataset.py).
+ +**Please see the example below for the dataset format.**
+ +
+Example for Classification Dataset + +```json +[ + { + "id": "06bc8a17-bb1c-4007-8c08-92c41e2628b2", + "image": "image_2.jpg", + "prompt": "Question: What is in the image? \n Options: \n 1. A train \n 2. A bus \n 3. A car \n 4. A bicycle", + "label": "3", + } + ... +] +``` + +**Note:** You should set the `CLASS_2_ID` variable in the [cls_dataset.py](src/dataset/cls_dataset.py). + +
+ +
+ +The dataset can contain **single/multi-image or video data**, and the model will be trained to classify the images/videos based on the provided labels.
+ +For now, you can select loss from one of the following: + +- `cross_entropy` +- `focal_loss` +- `class_balanced_cross_entropy` +- `class_balanced_focal_loss` + +Also you can set early stopping patience and threshold for the training. +For example, you can set `--early_stopping_patience 5` and `--early_stopping_threshold 0.01` to stop the training if the validation loss does not improve for 5 epochs with a threshold of 0.01. + +Most of the training arugments are same as SFT, but few other arguments are added for classification training.

+ +**Tip:** In models like the Qwen family, which have strong context embeddings, even a shallow nonlinearity (a 1-layer MLP) can often improve separability in the tail. This works by introducing a bit of curvature that a purely linear head cannot provide. + +
+Training arguments + +- `--loss_type` (str): Loss type for classification (default: 'cross_entropy'). +- `--focal_alpha` (str): Focal Loss alpha value. If None use CrossEntropyLoss. ex '1.0,7.5' (default: None). +- `--focal_gamma` (float): Focal Loss gamma value. (default: 0.0) +- `--num_labels` (int): Number of labels for classification +- `--class_balanced_beta` (float): Class Balanced beta value. (default: 0.999) +- `--early_stopping_patience` (int): Early stopping patience (default: 0) +- `--early_stopping_threshold` (float): Early stopping threshold (default: 0.01) +- `--mlp_head_dim` (int): Dimension of the MLP head (default: 0) +- `--mlp_head_dropout` (float): Dropout rate for the MLP head (default: 0.0) + +
+ +You can run the training script using the following command: + +```bash +bash scripts/finetune_cls.sh +``` + +#### Experimental Features + +- Sampler for the dataset. The trainer scripts supports the sampler for the dataset. You could make your own sampler with inherting `DistributedSampler`. + +## Inference + +**Note:** You should use the merged weight when trained with LoRA. + +### Gradio Infernce (WebUI) + +1. Install gradio + +``` +pip install gradio +``` + +2. Launch app + +``` +python -m src.serve.app \ + --model-path /path/to/merged/weight +``` + +You can launch gradio based demo with this command. This can also set some other generation configs like `repetition_penalty`, `temperature` etc. + +## Issue for libcudnn error + +``` +Could not load library libcudnn_cnn_train.so.8. Error: /usr/local/cuda-12.1/lib/libcudnn_cnn_train.so.8: undefined symbol: _ZN5cudnn3cnn34layerNormFwd_execute_internal_implERKNS_7backend11VariantPackEP11CUstream_stRNS0_18LayerNormFwdParamsERKNS1_20NormForwardOperationEmb, version libcudnn_cnn_infer.so.8 +``` + +You could run `unset LD_LIBRARY_PATH` for this error. +You could see this [issue](https://github.com/andimarafioti/florence2-finetuning/issues/2) + +## TODO + +- [x] Support for video data +- [x] Add demo for multi-image and video +- [x] Handle mixed-modality data in dataset and collator +- [x] Support Qwen2.5-VL +- [x] Monkey-patch liger-kernel for Qwen2.5-VL +- [x] Update the code base to the latest transformers. +- [x] Add DPO +- [x] Add GRPO +- [x] Support Qwen3-VL(non-moe) +- [x] Support Qwen3-VL-Moe + +## Known Issues + +- [libcudnn issue](#issue-for-libcudnn-error) + +## License + +This project is licensed under the Apache-2.0 License. See the [LICENSE](LICENSE) file for details. + +## Citation + +If you find this repository useful in your project, please consider giving a :star: and citing: + +```bibtex +@misc{Qwen2-VL-Finetuning, + author = {Yuwon Lee}, + title = {Qwen2-VL-Finetune}, + year = {2024}, + publisher = {GitHub}, + url = {https://github.com/2U1/Qwen2-VL-Finetune} +} +``` + +## Acknowledgement + +This project is based on + +- [LLaVA-NeXT](https://github.com/LLaVA-VL/LLaVA-NeXT): An amazing open-source project of LMM. +- [Mipha](https://github.com/zhuyiche/llava-phi): Open-source projcet of SMM with amazing capabilites. +- [Qwen2-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct): Awesome pretrained MLLM based on Qwen2. +- [Liger-Kernel](https://github.com/linkedin/Liger-Kernel): Collection of Tirton kernels designed specifically for LLM training. +- [VLM-R1](https://github.com/om-ai-lab/VLM-R1): Open-source project of Reinforcement Learning with VLMs. diff --git a/environment.yaml b/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..13a5a930f4abd86d37ffee501601423b346ddc8a --- /dev/null +++ b/environment.yaml @@ -0,0 +1,175 @@ +name: train +channels: + - conda-forge +dependencies: + - _libgcc_mutex=0.1=conda_forge + - _openmp_mutex=4.5=2_gnu + - asttokens=3.0.0=pyhd8ed1ab_1 + - bzip2=1.0.8=h4bc722e_7 + - ca-certificates=2025.4.26=hbd8a1cb_0 + - comm=0.2.2=pyhd8ed1ab_1 + - debugpy=1.8.14=py311hfdbb021_0 + - decorator=5.2.1=pyhd8ed1ab_0 + - exceptiongroup=1.2.2=pyhd8ed1ab_1 + - executing=2.2.0=pyhd8ed1ab_0 + - importlib-metadata=8.6.1=pyha770c72_0 + - ipykernel=6.29.5=pyh3099207_0 + - ipython=9.2.0=pyhfb0248b_0 + - ipython_pygments_lexers=1.1.1=pyhd8ed1ab_0 + - jedi=0.19.2=pyhd8ed1ab_1 + - jupyter_client=8.6.3=pyhd8ed1ab_1 + - jupyter_core=5.7.2=pyh31011fe_1 + - keyutils=1.6.1=h166bdaf_0 + - krb5=1.21.3=h659f571_0 + - ld_impl_linux-64=2.43=h712a8e2_4 + - libedit=3.1.20250104=pl5321h7949ede_0 + - libexpat=2.7.0=h5888daf_0 + - libffi=3.4.6=h2dba641_1 + - libgcc=14.2.0=h767d61c_2 + - libgcc-ng=14.2.0=h69a702a_2 + - libgomp=14.2.0=h767d61c_2 + - liblzma=5.8.1=hb9d3cd8_0 + - libnsl=2.0.1=hd590300_0 + - libsodium=1.0.20=h4ab18f5_0 + - libsqlite=3.49.1=hee588c1_2 + - libstdcxx=14.2.0=h8f9b012_2 + - libstdcxx-ng=14.2.0=h4852527_2 + - libuuid=2.38.1=h0b41bf4_0 + - libxcrypt=4.4.36=hd590300_1 + - libzlib=1.3.1=hb9d3cd8_2 + - matplotlib-inline=0.1.7=pyhd8ed1ab_1 + - ncurses=6.5=h2d0b736_3 + - nest-asyncio=1.6.0=pyhd8ed1ab_1 + - openssl=3.5.0=h7b32b05_0 + - packaging=25.0=pyh29332c3_1 + - parso=0.8.4=pyhd8ed1ab_1 + - pexpect=4.9.0=pyhd8ed1ab_1 + - pickleshare=0.7.5=pyhd8ed1ab_1004 + - pip=25.1=pyh8b19718_0 + - platformdirs=4.3.7=pyh29332c3_0 + - prompt-toolkit=3.0.51=pyha770c72_0 + - psutil=7.0.0=py311h9ecbd09_0 + - ptyprocess=0.7.0=pyhd8ed1ab_1 + - pure_eval=0.2.3=pyhd8ed1ab_1 + - pygments=2.19.1=pyhd8ed1ab_0 + - python=3.11.12=h9e4cc4f_0_cpython + - python-dateutil=2.9.0.post0=pyhff2d567_1 + - python_abi=3.11=7_cp311 + - pyzmq=26.4.0=py311h7deb3e3_0 + - readline=8.2=h8c095d6_2 + - setuptools=79.0.1=pyhff2d567_0 + - six=1.17.0=pyhd8ed1ab_0 + - stack_data=0.6.3=pyhd8ed1ab_1 + - tk=8.6.13=noxft_h4845f30_101 + - tornado=6.4.2=py311h9ecbd09_0 + - traitlets=5.14.3=pyhd8ed1ab_1 + - typing_extensions=4.13.2=pyh29332c3_0 + - wcwidth=0.2.13=pyhd8ed1ab_1 + - wheel=0.45.1=pyhd8ed1ab_1 + - zeromq=4.3.5=h3b0a872_7 + - zipp=3.21.0=pyhd8ed1ab_1 + - pip: + - accelerate==1.10.1 + - aiohappyeyeballs==2.6.1 + - aiohttp==3.11.18 + - aiosignal==1.3.2 + - annotated-types==0.7.0 + - attrs==25.3.0 + - av==14.3.0 + - bitsandbytes==0.45.5 + - certifi==2025.4.26 + - charset-normalizer==3.4.1 + - click==8.1.8 + - contourpy==1.3.3 + - cycler==0.12.1 + - datasets==3.5.1 + - decord==0.6.0 + - deepspeed==0.17.5 + - dill==0.3.8 + - docker-pycreds==0.4.0 + - einops==0.8.1 + - filelock==3.13.1 + - fonttools==4.59.2 + - frozenlist==1.6.0 + - fsspec==2024.6.1 + - gitdb==4.0.12 + - gitpython==3.1.44 + - hf-xet==1.1.9 + - hjson==3.1.0 + - huggingface-hub==0.34.4 + - idna==3.10 + - ipywidgets==8.1.6 + - jinja2==3.1.4 + - joblib==1.5.2 + - jupyterlab-widgets==3.0.14 + - kiwisolver==1.4.9 + - liger-kernel==0.6.4 + - markdown-it-py==3.0.0 + - markupsafe==2.1.5 + - matplotlib==3.10.6 + - mdurl==0.1.2 + - mpmath==1.3.0 + - msgpack==1.1.0 + - multidict==6.4.3 + - multiprocess==0.70.16 + - networkx==3.3 + - ninja==1.11.1.4 + - numpy==2.1.2 + - nvidia-cublas-cu12==12.8.4.1 + - nvidia-cuda-cupti-cu12==12.8.90 + - nvidia-cuda-nvrtc-cu12==12.8.93 + - nvidia-cuda-runtime-cu12==12.8.90 + - nvidia-cudnn-cu12==9.10.2.21 + - nvidia-cufft-cu12==11.3.3.83 + - nvidia-cufile-cu12==1.13.1.3 + - nvidia-curand-cu12==10.3.9.90 + - nvidia-cusolver-cu12==11.7.3.90 + - nvidia-cusparse-cu12==12.5.8.93 + - nvidia-cusparselt-cu12==0.7.1 + - nvidia-ml-py==12.570.86 + - nvidia-nccl-cu12==2.27.3 + - nvidia-nvjitlink-cu12==12.8.93 + - nvidia-nvtx-cu12==12.8.90 + - opencv-python==4.11.0.86 + - pandas==2.2.3 + - peft==0.15.2 + - pillow==11.3.0 + - pillow-simd==9.5.0.post2 + - propcache==0.3.1 + - protobuf==6.30.2 + - py-cpuinfo==9.0.0 + - pyarrow==20.0.0 + - pydantic==2.11.3 + - pydantic-core==2.33.1 + - pyparsing==3.2.3 + - pytz==2025.2 + - pyyaml==6.0.2 + - regex==2024.11.6 + - requests==2.32.3 + - rich==14.0.0 + - safetensors==0.6.2 + - scikit-learn==1.7.2 + - scipy==1.16.2 + - sentry-sdk==2.27.0 + - setproctitle==1.3.5 + - smmap==5.0.2 + - sympy==1.13.3 + - tabulate==0.9.0 + - tensorboardx==2.6.2.2 + - threadpoolctl==3.6.0 + - tokenizers==0.22.0 + - torch==2.8.0 + - torchaudio==2.8.0 + - torchvision==0.23.0 + - tqdm==4.67.1 + - transformers==4.57.1 + - triton==3.4.0 + - trl==0.25.0 + - typing-inspection==0.4.0 + - tzdata==2025.2 + - ujson==5.10.0 + - urllib3==2.4.0 + - wandb==0.19.10 + - widgetsnbextension==4.0.14 + - xxhash==3.5.0 + - yarl==1.20.0 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..b38114fe17e13c0a8062e46c9fd019b36f2d9aa2 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,140 @@ +accelerate==1.10.1 +aiohappyeyeballs==2.6.1 +aiohttp==3.11.18 +aiosignal==1.3.2 +annotated-types==0.7.0 +asttokens==3.0.0 +attrs==25.3.0 +av==14.3.0 +bitsandbytes==0.45.5 +certifi==2025.4.26 +charset-normalizer==3.4.1 +click==8.1.8 +comm==0.2.2 +contourpy==1.3.3 +cycler==0.12.1 +datasets==3.5.1 +debugpy==1.8.14 +decorator==5.2.1 +decord==0.6.0 +deepspeed==0.17.5 +dill==0.3.8 +docker-pycreds==0.4.0 +einops==0.8.1 +exceptiongroup==1.2.2 +executing==2.2.0 +filelock==3.13.1 +fonttools==4.59.2 +frozenlist==1.6.0 +fsspec==2024.6.1 +gitdb==4.0.12 +GitPython==3.1.44 +hf-xet==1.1.9 +hjson==3.1.0 +huggingface-hub==0.34.4 +idna==3.10 +importlib_metadata==8.6.1 +ipykernel==6.29.5 +ipython==9.2.0 +ipython_pygments_lexers==1.1.1 +ipywidgets==8.1.6 +jedi==0.19.2 +Jinja2==3.1.4 +joblib==1.5.2 +jupyter_client==8.6.3 +jupyter_core==5.7.2 +jupyterlab_widgets==3.0.14 +kiwisolver==1.4.9 +liger_kernel==0.6.4 +markdown-it-py==3.0.0 +MarkupSafe==2.1.5 +matplotlib==3.10.6 +matplotlib-inline==0.1.7 +mdurl==0.1.2 +mpmath==1.3.0 +msgpack==1.1.0 +multidict==6.4.3 +multiprocess==0.70.16 +nest_asyncio==1.6.0 +networkx==3.3 +ninja==1.11.1.4 +numpy==2.1.2 +nvidia-cublas-cu12==12.8.4.1 +nvidia-cuda-cupti-cu12==12.8.90 +nvidia-cuda-nvrtc-cu12==12.8.93 +nvidia-cuda-runtime-cu12==12.8.90 +nvidia-cudnn-cu12==9.10.2.21 +nvidia-cufft-cu12==11.3.3.83 +nvidia-cufile-cu12==1.13.1.3 +nvidia-curand-cu12==10.3.9.90 +nvidia-cusolver-cu12==11.7.3.90 +nvidia-cusparse-cu12==12.5.8.93 +nvidia-cusparselt-cu12==0.7.1 +nvidia-ml-py==12.570.86 +nvidia-nccl-cu12==2.27.3 +nvidia-nvjitlink-cu12==12.8.93 +nvidia-nvtx-cu12==12.8.90 +opencv-python==4.11.0.86 +packaging==25.0 +pandas==2.2.3 +parso==0.8.4 +peft==0.15.2 +pexpect==4.9.0 +pickleshare==0.7.5 +pillow==11.3.0 +pip==25.1 +platformdirs==4.3.7 +prompt_toolkit==3.0.51 +propcache==0.3.1 +protobuf==6.30.2 +psutil==7.0.0 +ptyprocess==0.7.0 +pure_eval==0.2.3 +py-cpuinfo==9.0.0 +pyarrow==20.0.0 +pydantic==2.11.3 +pydantic_core==2.33.1 +Pygments==2.19.1 +pyparsing==3.2.3 +python-dateutil==2.9.0.post0 +pytz==2025.2 +PyYAML==6.0.2 +pyzmq==26.4.0 +regex==2024.11.6 +requests==2.32.3 +rich==14.0.0 +safetensors==0.6.2 +scikit-learn==1.7.2 +scipy==1.16.2 +sentry-sdk==2.27.0 +setproctitle==1.3.5 +setuptools==79.0.1 +six==1.17.0 +smmap==5.0.2 +stack_data==0.6.3 +sympy==1.13.3 +tabulate==0.9.0 +tensorboardX==2.6.2.2 +threadpoolctl==3.6.0 +tokenizers==0.22.0 +torch==2.8.0 +torchaudio==2.8.0 +torchvision==0.23.0 +tornado==6.4.2 +tqdm==4.67.1 +traitlets==5.14.3 +transformers==4.57.1 +triton==3.4.0 +trl==0.25.0 +typing_extensions==4.13.2 +typing-inspection==0.4.0 +tzdata==2025.2 +ujson==5.10.0 +urllib3==2.4.0 +wandb==0.19.10 +wcwidth==0.2.13 +wheel==0.45.1 +widgetsnbextension==4.0.14 +xxhash==3.5.0 +yarl==1.20.0 +zipp==3.21.0 \ No newline at end of file diff --git a/scripts/finetune.sh b/scripts/finetune.sh new file mode 100644 index 0000000000000000000000000000000000000000..183210a3ea910b7c4c1834741e65003ea81f7200 --- /dev/null +++ b/scripts/finetune.sh @@ -0,0 +1,52 @@ +#!/bin/bash + +# MODEL_NAME="Qwen/Qwen2-VL-7B-Instruct" +# MODEL_NAME="Qwen/Qwen2-VL-2B-Instruct" +# MODEL_NAME="Qwen/Qwen2.5-VL-3B-Instruct" +# MODEL_NAME="Qwen/Qwen2.5-VL-7B-Instruct" + +MODEL_NAME="Qwen/Qwen3-VL-4B-Instruct" + +GLOBAL_BATCH_SIZE=128 +BATCH_PER_DEVICE=4 +NUM_DEVICES=8 +GRAD_ACCUM_STEPS=$((GLOBAL_BATCH_SIZE / (BATCH_PER_DEVICE * NUM_DEVICES))) + +export PYTHONPATH=src:$PYTHONPATH + +# If you want to set the min pixels and max pixels for Qwen3-VL, You should set as (N * 32 * 32) + +deepspeed src/train/train_sft.py \ + --use_liger_kernel True \ + --deepspeed scripts/zero3_offload.json \ + --model_id $MODEL_NAME \ + --data_path /path/to/your/training/data.json \ + --image_folder /path/to/your/image/folder \ + --remove_unused_columns False \ + --freeze_vision_tower False \ + --freeze_llm False \ + --freeze_merger False \ + --bf16 True \ + --fp16 False \ + --disable_flash_attn2 False \ + --output_dir output/test_fft \ + --num_train_epochs 1 \ + --per_device_train_batch_size $BATCH_PER_DEVICE \ + --gradient_accumulation_steps $GRAD_ACCUM_STEPS \ + --image_min_pixels $((512 * 28 * 28)) \ + --image_max_pixels $((1280 * 28 * 28)) \ + --learning_rate 1e-5 \ + --merger_lr 1e-5 \ + --vision_lr 2e-6 \ + --weight_decay 0.1 \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --gradient_checkpointing True \ + --report_to tensorboard \ + --lazy_preprocess True \ + --save_strategy "steps" \ + --save_steps 200 \ + --save_total_limit 10 \ + --dataloader_num_workers 4 \ No newline at end of file diff --git a/scripts/finetune_cls.sh b/scripts/finetune_cls.sh new file mode 100644 index 0000000000000000000000000000000000000000..648eb5fb8758784d2462a4b10d929ced64db9ef8 --- /dev/null +++ b/scripts/finetune_cls.sh @@ -0,0 +1,48 @@ +#!/bin/bash + +# MODEL_NAME="Qwen/Qwen2-VL-7B-Instruct" +# MODEL_NAME="Qwen/Qwen2-VL-2B-Instruct" +MODEL_NAME="Qwen/Qwen2.5-VL-3B-Instruct" + +# loss_type should be one of "cross_entropy", "focal_loss", "class_balanced_cross_entropy", or "class_balanced_focal_loss". + +export PYTHONPATH=src:$PYTHONPATH + +deepspeed src/train/train_cls.py \ + --deepspeed scripts/zero3.json \ + --model_id $MODEL_NAME \ + --data_path /path/to/your/training/data.json \ + --image_folder /path/to/your/image/folder \ + --eval_path /path/to/your/training/data.json \ + --eval_image_folder /path/to/your/image/folder \ + --freeze_llm True \ + --freeze_vision_tower False \ + --freeze_merger False \ + --bf16 True \ + --fp16 False \ + --loss_type "cross_entropy" \ + --num_labels 2 \ + --disable_flash_attn2 False \ + --output_dir output/qwen_cls \ + --num_train_epochs 3 \ + --per_device_train_batch_size 4 \ + --gradient_accumulation_steps 4 \ + --learning_rate 3e-5 \ + --head_lr 4e-5 \ + --vision_lr 6e-6 \ + --merger_lr 2e-5 \ + --weight_decay 0.02 \ + --warmup_ratio 0.05 \ + --max_grad_norm 1.0 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --eval_strategy "epoch" \ + --load_best_model_at_end True \ + --metric_for_best_model "eval_f1" \ + --greater_is_better True \ + --gradient_checkpointing True \ + --report_to tensorboard \ + --lazy_preprocess True \ + --save_strategy "epoch" \ + --dataloader_num_workers 4 \ No newline at end of file diff --git a/scripts/finetune_dpo.sh b/scripts/finetune_dpo.sh new file mode 100644 index 0000000000000000000000000000000000000000..c121bea8381d0cd775be249e048c18ba78ea4740 --- /dev/null +++ b/scripts/finetune_dpo.sh @@ -0,0 +1,51 @@ +#!/bin/bash + +# MODEL_NAME="Qwen/Qwen2-VL-7B-Instruct" +# MODEL_NAME="Qwen/Qwen2-VL-2B-Instruct" +MODEL_NAME="Qwen/Qwen2.5-VL-3B-Instruct" +# MODEL_NAME="Qwen/Qwen2.5-VL-7B-Instruct" + +GLOBAL_BATCH_SIZE=128 +BATCH_PER_DEVICE=4 +NUM_DEVICES=8 +GRAD_ACCUM_STEPS=$((GLOBAL_BATCH_SIZE / (BATCH_PER_DEVICE * NUM_DEVICES))) + +export PYTHONPATH=src:$PYTHONPATH + +deepspeed src/train/train_dpo.py \ + --dpo_loss "sigmoid" \ + --precompute_ref_log_probs False \ + --beta 0.1 \ + --use_liger_loss True \ + --deepspeed scripts/zero3_offload.json \ + --model_id $MODEL_NAME \ + --data_path /path/to/your/training/data.json \ + --image_folder /path/to/your/image/folder \ + --remove_unused_columns False \ + --freeze_vision_tower False \ + --freeze_llm False \ + --freeze_merger False \ + --bf16 True \ + --fp16 False \ + --disable_flash_attn2 False \ + --output_dir output/test_dpo \ + --num_train_epochs 1 \ + --per_device_train_batch_size $BATCH_PER_DEVICE \ + --gradient_accumulation_steps $GRAD_ACCUM_STEPS \ + --image_min_pixels $((512 * 28 * 28)) \ + --image_max_pixels $((1280 * 28 * 28)) \ + --learning_rate 1e-5 \ + --merger_lr 1e-5 \ + --vision_lr 2e-6 \ + --weight_decay 0.1 \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --gradient_checkpointing True \ + --report_to tensorboard \ + --lazy_preprocess True \ + --save_strategy "steps" \ + --save_steps 200 \ + --save_total_limit 10 \ + --dataloader_num_workers 4 \ No newline at end of file diff --git a/scripts/finetune_grpo.sh b/scripts/finetune_grpo.sh new file mode 100644 index 0000000000000000000000000000000000000000..cda832314928e217551d91761ef2221a60f0edf0 --- /dev/null +++ b/scripts/finetune_grpo.sh @@ -0,0 +1,42 @@ +#!/bin/bash + +# MODEL_NAME="Qwen/Qwen2-VL-7B-Instruct" +# MODEL_NAME="Qwen/Qwen2-VL-2B-Instruct" +MODEL_NAME="Qwen/Qwen2.5-VL-3B-Instruct" + +export PYTHONPATH=src:$PYTHONPATH + +deepspeed src/train/train_grpo.py \ + --deepspeed scripts/zero3.json \ + --use_liger_loss True \ + --model_id $MODEL_NAME \ + --data_path /path/to/your/training/data.json \ + --image_folder /path/to/your/image/folder \ + --freeze_vision_tower False \ + --freeze_llm True \ + --freeze_merger False \ + --bf16 True \ + --fp16 False \ + --disable_flash_attn2 False \ + --output_dir output/test_grpo \ + --num_train_epochs 1 \ + --num_generations 2 \ + --per_device_train_batch_size 1 \ + --gradient_accumulation_steps 1 \ + --max_completion_length 256 \ + --max_prompt_length 512 \ + --image_min_pixels $((128 * 28 * 28)) \ + --image_max_pixels $((256 * 28 * 28)) \ + --learning_rate 5e-6 \ + --remove_unused_columns False \ + --weight_decay 0.1 \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --gradient_checkpointing True \ + --report_to tensorboard \ + --lazy_preprocess True \ + --save_strategy "epoch" \ + --save_total_limit 10 \ + --dataloader_num_workers 4 \ No newline at end of file diff --git a/scripts/finetune_lora.sh b/scripts/finetune_lora.sh new file mode 100644 index 0000000000000000000000000000000000000000..cbb04486f8d206fc8fdfadf3cd5f206194b48ee2 --- /dev/null +++ b/scripts/finetune_lora.sh @@ -0,0 +1,61 @@ +#!/bin/bash + +# MODEL_NAME="Qwen/Qwen2-VL-7B-Instruct" +# MODEL_NAME="Qwen/Qwen2-VL-2B-Instruct" +# MODEL_NAME="Qwen/Qwen2.5-VL-3B-Instruct" +# MODEL_NAME="Qwen/Qwen2.5-VL-7B-Instruct" + +MODEL_NAME="/DATA/disk1/cdp/hf_models/Qwen3-VL-8B-Instruct" + +export PYTHONPATH=src:$PYTHONPATH + +GLOBAL_BATCH_SIZE=128 +BATCH_PER_DEVICE=4 +NUM_DEVICES=8 +GRAD_ACCUM_STEPS=$((GLOBAL_BATCH_SIZE / (BATCH_PER_DEVICE * NUM_DEVICES))) + +# If you want to tune the `embed_token` with LoRA, You need to tune `lm_head` together + +# If you want to set the min pixels and max pixels for Qwen3-VL, You should set as (N * 32 * 32) + +deepspeed src/train/train_sft.py \ + --use_liger_kernel False \ + --lora_enable True \ + --use_dora False \ + --lora_namespan_exclude "['lm_head', 'embed_tokens']" \ + --lora_rank 32 \ + --lora_alpha 64 \ + --lora_dropout 0.05 \ + --num_lora_modules -1 \ + --deepspeed scripts/zero3.json \ + --model_id $MODEL_NAME \ + --data_path /DATA/disk1/cdp/hxa/dataset/dataset_merged_en_formatted.json \ + --image_folder /DATA/disk1/cdp/hxa/dataset \ + --remove_unused_columns False \ + --freeze_vision_tower False \ + --freeze_llm True \ + --freeze_merger False \ + --bf16 True \ + --fp16 False \ + --disable_flash_attn2 False \ + --output_dir output/testing_lora_multi_qa_8b \ + --num_train_epochs 8 \ + --per_device_train_batch_size $BATCH_PER_DEVICE \ + --gradient_accumulation_steps $GRAD_ACCUM_STEPS \ + --image_min_pixels $((256 * 28 * 28)) \ + --image_max_pixels $((1280 * 28 * 28)) \ + --learning_rate 1e-4 \ + --merger_lr 1e-5 \ + --vision_lr 2e-6 \ + --weight_decay 0.1 \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --gradient_checkpointing True \ + --report_to tensorboard \ + --lazy_preprocess True \ + --save_strategy "steps" \ + --save_steps 100 \ + --save_total_limit 50 \ + --dataloader_num_workers 4 \ No newline at end of file diff --git a/scripts/finetune_lora_1.sh b/scripts/finetune_lora_1.sh new file mode 100644 index 0000000000000000000000000000000000000000..321c8ff8a27b18309d3fd8d5f1f394e0a08363f6 --- /dev/null +++ b/scripts/finetune_lora_1.sh @@ -0,0 +1,61 @@ +#!/bin/bash + +# MODEL_NAME="Qwen/Qwen2-VL-7B-Instruct" +# MODEL_NAME="Qwen/Qwen2-VL-2B-Instruct" +# MODEL_NAME="Qwen/Qwen2.5-VL-3B-Instruct" +# MODEL_NAME="Qwen/Qwen2.5-VL-7B-Instruct" + +MODEL_NAME="/DATA/disk1/cdp/hf_models/Qwen3-VL-4B-Instruct" + +export PYTHONPATH=src:$PYTHONPATH + +GLOBAL_BATCH_SIZE=128 +BATCH_PER_DEVICE=4 +NUM_DEVICES=8 +GRAD_ACCUM_STEPS=$((GLOBAL_BATCH_SIZE / (BATCH_PER_DEVICE * NUM_DEVICES))) + +# If you want to tune the `embed_token` with LoRA, You need to tune `lm_head` together + +# If you want to set the min pixels and max pixels for Qwen3-VL, You should set as (N * 32 * 32) + +deepspeed src/train/train_sft.py \ + --use_liger_kernel False \ + --lora_enable True \ + --use_dora False \ + --lora_namespan_exclude "['lm_head', 'embed_tokens']" \ + --lora_rank 32 \ + --lora_alpha 64 \ + --lora_dropout 0.05 \ + --num_lora_modules -1 \ + --deepspeed scripts/zero3.json \ + --model_id $MODEL_NAME \ + --data_path /DATA/disk1/cdp/hxa/dataset/dataset_merged_en_en_choice_formatted.json \ + --image_folder /DATA/disk1/cdp/hxa/dataset \ + --remove_unused_columns False \ + --freeze_vision_tower False \ + --freeze_llm True \ + --freeze_merger False \ + --bf16 True \ + --fp16 False \ + --disable_flash_attn2 False \ + --output_dir output/testing_lora_en_choice \ + --num_train_epochs 8 \ + --per_device_train_batch_size $BATCH_PER_DEVICE \ + --gradient_accumulation_steps $GRAD_ACCUM_STEPS \ + --image_min_pixels $((256 * 28 * 28)) \ + --image_max_pixels $((1280 * 28 * 28)) \ + --learning_rate 1e-4 \ + --merger_lr 1e-5 \ + --vision_lr 2e-6 \ + --weight_decay 0.1 \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --gradient_checkpointing True \ + --report_to tensorboard \ + --lazy_preprocess True \ + --save_strategy "steps" \ + --save_steps 100 \ + --save_total_limit 50 \ + --dataloader_num_workers 4 \ No newline at end of file diff --git a/scripts/finetune_lora_2.sh b/scripts/finetune_lora_2.sh new file mode 100644 index 0000000000000000000000000000000000000000..dbaf96ce001822588300b7ed4c52846550036b6f --- /dev/null +++ b/scripts/finetune_lora_2.sh @@ -0,0 +1,61 @@ +#!/bin/bash + +# MODEL_NAME="Qwen/Qwen2-VL-7B-Instruct" +# MODEL_NAME="Qwen/Qwen2-VL-2B-Instruct" +# MODEL_NAME="Qwen/Qwen2.5-VL-3B-Instruct" +# MODEL_NAME="Qwen/Qwen2.5-VL-7B-Instruct" + +MODEL_NAME="/DATA/disk1/cdp/hf_models/Qwen3-VL-4B-Instruct" + +export PYTHONPATH=src:$PYTHONPATH + +GLOBAL_BATCH_SIZE=128 +BATCH_PER_DEVICE=4 +NUM_DEVICES=8 +GRAD_ACCUM_STEPS=$((GLOBAL_BATCH_SIZE / (BATCH_PER_DEVICE * NUM_DEVICES))) + +# If you want to tune the `embed_token` with LoRA, You need to tune `lm_head` together + +# If you want to set the min pixels and max pixels for Qwen3-VL, You should set as (N * 32 * 32) + +deepspeed src/train/train_sft.py \ + --use_liger_kernel False \ + --lora_enable True \ + --use_dora False \ + --lora_namespan_exclude "['lm_head', 'embed_tokens']" \ + --lora_rank 32 \ + --lora_alpha 64 \ + --lora_dropout 0.05 \ + --num_lora_modules -1 \ + --deepspeed scripts/zero3.json \ + --model_id $MODEL_NAME \ + --data_path /DATA/disk1/cdp/hxa/dataset/dataset_merged_en_choice_formatted.json \ + --image_folder /DATA/disk1/cdp/hxa/dataset \ + --remove_unused_columns False \ + --freeze_vision_tower False \ + --freeze_llm True \ + --freeze_merger False \ + --bf16 True \ + --fp16 False \ + --disable_flash_attn2 False \ + --output_dir output/testing_lora_multi_choice \ + --num_train_epochs 8 \ + --per_device_train_batch_size $BATCH_PER_DEVICE \ + --gradient_accumulation_steps $GRAD_ACCUM_STEPS \ + --image_min_pixels $((256 * 28 * 28)) \ + --image_max_pixels $((1280 * 28 * 28)) \ + --learning_rate 1e-4 \ + --merger_lr 1e-5 \ + --vision_lr 2e-6 \ + --weight_decay 0.1 \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --gradient_checkpointing True \ + --report_to tensorboard \ + --lazy_preprocess True \ + --save_strategy "steps" \ + --save_steps 100 \ + --save_total_limit 50 \ + --dataloader_num_workers 4 \ No newline at end of file diff --git a/scripts/finetune_lora_vision.sh b/scripts/finetune_lora_vision.sh new file mode 100644 index 0000000000000000000000000000000000000000..c50cefb366d7ca161ee802a14f930c8b9b9d3ec4 --- /dev/null +++ b/scripts/finetune_lora_vision.sh @@ -0,0 +1,60 @@ +#!/bin/bash + + +# MODEL_NAME="Qwen/Qwen2-VL-7B-Instruct" +# MODEL_NAME="Qwen/Qwen2-VL-2B-Instruct" +MODEL_NAME="Qwen/Qwen2.5-VL-3B-Instruct" +# MODEL_NAME="Qwen/Qwen2.5-VL-7B-Instruct" + +export PYTHONPATH=src:$PYTHONPATH + +GLOBAL_BATCH_SIZE=128 +BATCH_PER_DEVICE=4 +NUM_DEVICES=8 +GRAD_ACCUM_STEPS=$((GLOBAL_BATCH_SIZE / (BATCH_PER_DEVICE * NUM_DEVICES))) + +# If you want to tune the `embed_token` with LoRA, You need to tune `lm_head` together +# You should freeze the the merger also, becuase the merger is included in the vision_tower. + +# Please set the gradient_checkpointing to False when you are using LoRA with vision models. + +deepspeed src/train/train_sft.py \ + --use_liger_kernel True \ + --lora_enable True \ + --vision_lora True \ + --use_dora False \ + --lora_namespan_exclude "['lm_head', 'embed_tokens']" \ + --lora_rank 32 \ + --lora_alpha 64 \ + --lora_dropout 0.05 \ + --num_lora_modules -1 \ + --deepspeed scripts/zero3.json \ + --model_id $MODEL_NAME \ + --data_path /path/to/your/training/data.json \ + --image_folder /path/to/your/image/folder \ + --remove_unused_columns False \ + --freeze_vision_tower True \ + --freeze_llm True \ + --freeze_merger True \ + --bf16 True \ + --fp16 False \ + --disable_flash_attn2 False \ + --output_dir output/lora_vision_test \ + --num_train_epochs 1 \ + --per_device_train_batch_size $BATCH_PER_DEVICE \ + --gradient_accumulation_steps $GRAD_ACCUM_STEPS \ + --image_min_pixels $((256 * 28 * 28)) \ + --image_max_pixels $((1280 * 28 * 28)) \ + --learning_rate 2e-4 \ + --weight_decay 0.1 \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --gradient_checkpointing False \ + --report_to tensorboard \ + --lazy_preprocess True \ + --save_strategy "steps" \ + --save_steps 200 \ + --save_total_limit 10 \ + --dataloader_num_workers 4 \ No newline at end of file diff --git a/scripts/finetune_video.sh b/scripts/finetune_video.sh new file mode 100644 index 0000000000000000000000000000000000000000..00026da2d3bcb09022653a0fe10101759505f66a --- /dev/null +++ b/scripts/finetune_video.sh @@ -0,0 +1,53 @@ +#!/bin/bash + +# MODEL_NAME="Qwen/Qwen2-VL-7B-Instruct" +# MODEL_NAME="Qwen/Qwen2-VL-2B-Instruct" +# MODEL_NAME="Qwen/Qwen2.5-VL-3B-Instruct" +# MODEL_NAME="Qwen/Qwen2.5-VL-7B-Instruct" + +MODEL_NAME="Qwen/Qwen3-VL-4B-Instruct" + +export PYTHONPATH=src:$PYTHONPATH + +GLOBAL_BATCH_SIZE=128 +BATCH_PER_DEVICE=4 +NUM_DEVICES=8 +GRAD_ACCUM_STEPS=$((GLOBAL_BATCH_SIZE / (BATCH_PER_DEVICE * NUM_DEVICES))) + +# If your dataset is mixed with images and videos, you need to use zero2. +# If you want to set the min pixels and max pixels for Qwen3-VL, You should set as (N * 32 * 32) + +deepspeed src/train/train_sft.py \ + --use_liger_kernel True \ + --deepspeed scripts/zero3_offload.json \ + --model_id $MODEL_NAME \ + --data_path /path/to/your/training/data.json \ + --image_folder /path/to/your/image/folder \ + --remove_unused_columns False \ + --freeze_vision_tower False \ + --freeze_llm False \ + --freeze_merger False \ + --bf16 True \ + --fp16 False \ + --disable_flash_attn2 False \ + --output_dir output/test_train \ + --num_train_epochs 1 \ + --per_device_train_batch_size $BATCH_PER_DEVICE \ + --gradient_accumulation_steps $GRAD_ACCUM_STEPS \ + --video_max_pixels $((360 * 420)) \ + --fps 1.0 \ + --learning_rate 1e-5 \ + --merger_lr 1e-5 \ + --vision_lr 2e-6 \ + --weight_decay 0.1 \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --gradient_checkpointing True \ + --report_to tensorboard \ + --lazy_preprocess True \ + --save_strategy "steps" \ + --save_steps 1 \ + --save_total_limit 10 \ + --dataloader_num_workers 4 \ No newline at end of file diff --git a/scripts/merge_lora.sh b/scripts/merge_lora.sh new file mode 100644 index 0000000000000000000000000000000000000000..2f9037550fdb5cc39b9ee200e7aede04b29e4a9f --- /dev/null +++ b/scripts/merge_lora.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +MODEL_NAME="Qwen/Qwen2-VL-7B-Instruct" +# MODEL_NAME="Qwen/Qwen2-VL-2B-Instruct" + +export PYTHONPATH=src:$PYTHONPATH + +python src/merge_lora_weights.py \ + --model-path /home/workspace/Qwen2-VL-Finetune/output/testing_lora \ + --model-base $MODEL_NAME \ + --save-model-path /home/workspace/Qwen2-VL-Finetune/output/merge_test \ + --safe-serialization \ No newline at end of file diff --git a/scripts/zero2.json b/scripts/zero2.json new file mode 100644 index 0000000000000000000000000000000000000000..3b6e03d7a7b07fa1958feaab5d504b299a8365fc --- /dev/null +++ b/scripts/zero2.json @@ -0,0 +1,23 @@ +{ + "fp16": { + "enabled": "auto", + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "bf16": { + "enabled": "auto" + }, + "train_micro_batch_size_per_gpu": "auto", + "train_batch_size": "auto", + "gradient_accumulation_steps": "auto", + "zero_optimization": { + "stage": 2, + "overlap_comm": true, + "contiguous_gradients": true, + "sub_group_size": 1e9, + "reduce_bucket_size": "auto" + } +} diff --git a/scripts/zero2_offload.json b/scripts/zero2_offload.json new file mode 100644 index 0000000000000000000000000000000000000000..b8154c8973e3be86296631d787ad9f14dd14a1ed --- /dev/null +++ b/scripts/zero2_offload.json @@ -0,0 +1,31 @@ +{ + "fp16": { + "enabled": "auto", + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "bf16": { + "enabled": "auto" + }, + "train_micro_batch_size_per_gpu": "auto", + "train_batch_size": "auto", + "gradient_accumulation_steps": "auto", + "zero_optimization": { + "stage": 2, + "offload_optimizer": { + "device": "cpu", + "pin_memory": true + }, + "offload_param": { + "device": "cpu", + "pin_memory": true + }, + "overlap_comm": true, + "contiguous_gradients": true, + "sub_group_size": 1e9, + "reduce_bucket_size": "auto" + } +} diff --git a/scripts/zero3.json b/scripts/zero3.json new file mode 100644 index 0000000000000000000000000000000000000000..56cc7ea481cd3a272d5a14d3b0d2333c153fa5a9 --- /dev/null +++ b/scripts/zero3.json @@ -0,0 +1,28 @@ +{ + "fp16": { + "enabled": "auto", + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "bf16": { + "enabled": "auto" + }, + "train_micro_batch_size_per_gpu": "auto", + "train_batch_size": "auto", + "gradient_accumulation_steps": "auto", + "zero_optimization": { + "stage": 3, + "overlap_comm": true, + "contiguous_gradients": true, + "sub_group_size": 1e9, + "reduce_bucket_size": "auto", + "stage3_prefetch_bucket_size": "auto", + "stage3_param_persistence_threshold": "auto", + "stage3_max_live_parameters": 1e9, + "stage3_max_reuse_distance": 1e9, + "stage3_gather_16bit_weights_on_model_save": true + } +} diff --git a/scripts/zero3_offload.json b/scripts/zero3_offload.json new file mode 100644 index 0000000000000000000000000000000000000000..145c82b537a1becb75f5fb8ece0a4679972eb9c8 --- /dev/null +++ b/scripts/zero3_offload.json @@ -0,0 +1,48 @@ +{ + "fp16": { + "enabled": "auto", + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "bf16": { + "enabled": "auto" + }, + "optimizer": { + "type": "AdamW", + "params": { + "lr": "auto", + "betas": "auto", + "eps": "auto", + "weight_decay": "auto" + } + }, + "zero_optimization": { + "stage": 3, + "offload_optimizer": { + "device": "cpu", + "pin_memory": true + }, + "offload_param": { + "device": "cpu", + "pin_memory": true + }, + "overlap_comm": true, + "contiguous_gradients": true, + "sub_group_size": 1e9, + "reduce_bucket_size": "auto", + "stage3_prefetch_bucket_size": "auto", + "stage3_param_persistence_threshold": "auto", + "stage3_max_live_parameters": 1e9, + "stage3_max_reuse_distance": 1e9, + "gather_16bit_weights_on_model_save": true + }, + "gradient_accumulation_steps": "auto", + "gradient_clipping": "auto", + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "steps_per_print": 1e5, + "wall_clock_breakdown": false +} diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/constants.py b/src/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..0fe0b16715f5c8f3d694fabe8272179f58b81523 --- /dev/null +++ b/src/constants.py @@ -0,0 +1,14 @@ +IGNORE_INDEX = -100 + +DEFAULT_IM_START_TOKEN = "<|im_start|>" +DEFAULT_IM_END_TOKEN = "<|im_end|>" +DEFAULT_IMAGE_TOKEN = "<|image_pad|>" +DEFAULT_VIDEO_TOKEN = "<|video_pad|>" +LLAVA_IMAGE_TOKEN = "" +LLAVA_VIDEO_TOKEN = "