Add files using upload-large-folder tool
Browse files- benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--H0012--2d_none--0000_000.png +3 -0
- benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0010--2d_none--0000_000.png +3 -0
- benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0012--2d_none--0000_000.png +3 -0
- benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0033--2d_none--0000_000.png +3 -0
- benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0094--2d_none--0000_000.png +3 -0
- benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0006--2d_none--0000_000.png +3 -0
- benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0016--2d_none--0000_000.png +3 -0
- benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0036--2d_none--0000_000.png +3 -0
- benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0125--2d_none--0000_000.png +3 -0
- benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0327--2d_none--0000_000.png +3 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/format_prompt/math_format.jinja +1 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/format_prompt/r1v_format.jinja +1 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/Dockerfile +76 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/Makefile +18 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/README.md +217 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/__init__.py +32 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/init +1 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/protocol.py +689 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/pyproject.toml +39 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/requirements.txt +19 -0
benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--H0012--2d_none--0000_000.png
ADDED
|
Git LFS Details
|
benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0010--2d_none--0000_000.png
ADDED
|
Git LFS Details
|
benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0012--2d_none--0000_000.png
ADDED
|
Git LFS Details
|
benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0033--2d_none--0000_000.png
ADDED
|
Git LFS Details
|
benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0094--2d_none--0000_000.png
ADDED
|
Git LFS Details
|
benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0006--2d_none--0000_000.png
ADDED
|
Git LFS Details
|
benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0016--2d_none--0000_000.png
ADDED
|
Git LFS Details
|
benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0036--2d_none--0000_000.png
ADDED
|
Git LFS Details
|
benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0125--2d_none--0000_000.png
ADDED
|
Git LFS Details
|
benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0327--2d_none--0000_000.png
ADDED
|
Git LFS Details
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/format_prompt/math_format.jinja
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{{ content | trim }} You FIRST think about the reasoning process as an internal monologue and then provide the final answer. The reasoning process MUST BE enclosed within <think> </think> tags. The final answer MUST BE put in \boxed{}.
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/format_prompt/r1v_format.jinja
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{{ content | trim }} A conversation between User and Assistant. The user asks a question, and the Assistant solves it. The assistant first thinks about the reasoning process in the mind and then provides the user with the answer. The reasoning process and answer are enclosed within <think> </think> and <answer> </answer> tags, respectively, i.e., <think> reasoning process here </think><answer> answer here </answer>
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/Dockerfile
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Start from the NVIDIA official image (ubuntu-22.04 + cuda-12.6 + python-3.10)
|
| 2 |
+
# https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-24-08.html
|
| 3 |
+
FROM nvcr.io/nvidia/pytorch:24.08-py3
|
| 4 |
+
|
| 5 |
+
# Define environments
|
| 6 |
+
ENV MAX_JOBS=32
|
| 7 |
+
ENV VLLM_WORKER_MULTIPROC_METHOD=spawn
|
| 8 |
+
ENV DEBIAN_FRONTEND=noninteractive
|
| 9 |
+
ENV NODE_OPTIONS=""
|
| 10 |
+
ENV PIP_ROOT_USER_ACTION=ignore
|
| 11 |
+
ENV HF_HUB_ENABLE_HF_TRANSFER="1"
|
| 12 |
+
|
| 13 |
+
# Define installation arguments
|
| 14 |
+
ARG APT_SOURCE=https://mirrors.tuna.tsinghua.edu.cn/ubuntu/
|
| 15 |
+
ARG PIP_INDEX=https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple
|
| 16 |
+
|
| 17 |
+
# Set apt source
|
| 18 |
+
RUN cp /etc/apt/sources.list /etc/apt/sources.list.bak && \
|
| 19 |
+
{ \
|
| 20 |
+
echo "deb ${APT_SOURCE} jammy main restricted universe multiverse"; \
|
| 21 |
+
echo "deb ${APT_SOURCE} jammy-updates main restricted universe multiverse"; \
|
| 22 |
+
echo "deb ${APT_SOURCE} jammy-backports main restricted universe multiverse"; \
|
| 23 |
+
echo "deb ${APT_SOURCE} jammy-security main restricted universe multiverse"; \
|
| 24 |
+
} > /etc/apt/sources.list
|
| 25 |
+
|
| 26 |
+
# Install systemctl
|
| 27 |
+
RUN apt-get update && \
|
| 28 |
+
apt-get install -y -o Dpkg::Options::="--force-confdef" systemd && \
|
| 29 |
+
apt-get clean
|
| 30 |
+
|
| 31 |
+
# Install tini
|
| 32 |
+
RUN apt-get update && \
|
| 33 |
+
apt-get install -y tini && \
|
| 34 |
+
apt-get clean
|
| 35 |
+
|
| 36 |
+
# Change pip source
|
| 37 |
+
RUN pip config set global.index-url "${PIP_INDEX}" && \
|
| 38 |
+
pip config set global.extra-index-url "${PIP_INDEX}" && \
|
| 39 |
+
python -m pip install --upgrade pip
|
| 40 |
+
|
| 41 |
+
# Uninstall nv-pytorch fork
|
| 42 |
+
RUN pip uninstall -y torch torchvision torchaudio \
|
| 43 |
+
pytorch-quantization pytorch-triton torch-tensorrt \
|
| 44 |
+
transformer_engine flash_attn apex megatron-core \
|
| 45 |
+
xgboost opencv grpcio
|
| 46 |
+
|
| 47 |
+
# Fix cv2
|
| 48 |
+
RUN rm -rf /usr/local/lib/python3.10/dist-packages/cv2
|
| 49 |
+
|
| 50 |
+
# Install torch-2.6.0+cu124 + vllm-0.8.4
|
| 51 |
+
# torch-2.6.0+cu124: cxx11abi=False
|
| 52 |
+
# torch-2.6.0+cu126: cxx11abi=True
|
| 53 |
+
# see https://github.com/flashinfer-ai/flashinfer/issues/911
|
| 54 |
+
RUN pip install --no-cache-dir "vllm==0.8.4" "torch==2.6.0" "torchvision==0.21.0" "torchaudio==2.6.0" tensordict torchdata \
|
| 55 |
+
"transformers[hf_xet]>=4.51.0" accelerate datasets peft hf-transfer \
|
| 56 |
+
"numpy<2.0.0" "pyarrow>=15.0.0" pandas \
|
| 57 |
+
ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb liger-kernel mathruler \
|
| 58 |
+
pytest yapf py-spy pyext pre-commit ruff
|
| 59 |
+
|
| 60 |
+
# Install flash-attn-2.7.4.post1 (cxx11abi=False)
|
| 61 |
+
RUN wget -nv https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.4.post1/flash_attn-2.7.4.post1+cu12torch2.6cxx11abiFALSE-cp310-cp310-linux_x86_64.whl && \
|
| 62 |
+
pip install --no-cache-dir flash_attn-2.7.4.post1+cu12torch2.6cxx11abiFALSE-cp310-cp310-linux_x86_64.whl
|
| 63 |
+
|
| 64 |
+
# Install flashinfer-0.2.2.post1+cu124 (cxx11abi=False)
|
| 65 |
+
# vllm-0.8.3 does not support flashinfer>=0.2.3
|
| 66 |
+
# see https://github.com/vllm-project/vllm/pull/15777
|
| 67 |
+
RUN wget -nv https://github.com/flashinfer-ai/flashinfer/releases/download/v0.2.2.post1/flashinfer_python-0.2.2.post1+cu124torch2.6-cp38-abi3-linux_x86_64.whl && \
|
| 68 |
+
pip install --no-cache-dir flashinfer_python-0.2.2.post1+cu124torch2.6-cp38-abi3-linux_x86_64.whl
|
| 69 |
+
|
| 70 |
+
# Fix packages
|
| 71 |
+
RUN pip uninstall -y pynvml nvidia-ml-py && \
|
| 72 |
+
pip install --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1"
|
| 73 |
+
|
| 74 |
+
# Reset pip config
|
| 75 |
+
RUN pip config unset global.index-url && \
|
| 76 |
+
pip config unset global.extra-index-url
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/Makefile
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.PHONY: build commit quality style
|
| 2 |
+
|
| 3 |
+
check_dirs := examples scripts verl setup.py
|
| 4 |
+
|
| 5 |
+
build:
|
| 6 |
+
python3 setup.py sdist bdist_wheel
|
| 7 |
+
|
| 8 |
+
commit:
|
| 9 |
+
pre-commit install
|
| 10 |
+
pre-commit run --all-files
|
| 11 |
+
|
| 12 |
+
quality:
|
| 13 |
+
ruff check $(check_dirs)
|
| 14 |
+
ruff format --check $(check_dirs)
|
| 15 |
+
|
| 16 |
+
style:
|
| 17 |
+
ruff check $(check_dirs) --fix
|
| 18 |
+
ruff format $(check_dirs)
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/README.md
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# EasyR1: An Efficient, Scalable, Multi-Modality RL Training Framework
|
| 2 |
+
|
| 3 |
+
[](https://github.com/hiyouga/EasyR1/stargazers)
|
| 4 |
+
[](https://twitter.com/llamafactory_ai)
|
| 5 |
+
|
| 6 |
+
This project is a clean fork of the original [veRL](https://github.com/volcengine/verl) project to support vision language models, we thank all the authors for providing such a high-performance RL training framework.
|
| 7 |
+
|
| 8 |
+
EasyR1 is efficient and scalable due to the design of **[HybirdEngine](https://arxiv.org/abs/2409.19256)** and the latest release of **[vLLM](https://github.com/vllm-project/vllm)**'s SPMD mode.
|
| 9 |
+
|
| 10 |
+
## Features
|
| 11 |
+
|
| 12 |
+
- Supported models
|
| 13 |
+
- Llama3/Qwen2/Qwen2.5/Qwen3 language models
|
| 14 |
+
- Qwen2/Qwen2.5-VL vision language models
|
| 15 |
+
- DeepSeek-R1 distill models
|
| 16 |
+
|
| 17 |
+
- Supported algorithms
|
| 18 |
+
- GRPO
|
| 19 |
+
- Reinforce++
|
| 20 |
+
- ReMax
|
| 21 |
+
- RLOO
|
| 22 |
+
|
| 23 |
+
- Supported datasets
|
| 24 |
+
- Any text, vision-text dataset in a [specific format](#custom-dataset)
|
| 25 |
+
|
| 26 |
+
- Supported tricks
|
| 27 |
+
- Padding-free training
|
| 28 |
+
- Resuming from checkpoint
|
| 29 |
+
- Wandb & SwanLab & Mlflow & Tensorboard tracking
|
| 30 |
+
|
| 31 |
+
## Requirements
|
| 32 |
+
|
| 33 |
+
### Software Requirements
|
| 34 |
+
|
| 35 |
+
- Python 3.9+
|
| 36 |
+
- transformers>=4.51.0
|
| 37 |
+
- flash-attn>=2.4.3
|
| 38 |
+
- vllm>=0.8.3
|
| 39 |
+
|
| 40 |
+
We provide a [Dockerfile](./Dockerfile) to easily build environments.
|
| 41 |
+
|
| 42 |
+
We recommend using the [pre-built docker image](https://hub.docker.com/r/hiyouga/verl) in EasyR1.
|
| 43 |
+
|
| 44 |
+
```bash
|
| 45 |
+
docker pull hiyouga/verl:ngc-th2.6.0-cu126-vllm0.8.4-flashinfer0.2.2-cxx11abi0
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
### Hardware Requirements
|
| 49 |
+
|
| 50 |
+
\* *estimated*
|
| 51 |
+
|
| 52 |
+
| Method | Bits | 1.5B | 3B | 7B | 32B |
|
| 53 |
+
| ------------------------ | ---- | ------ | ------ | ------ | ------- |
|
| 54 |
+
| GRPO Full Fine-Tuning | AMP | 2*24GB | 4*40GB | 8*40GB | 16*80GB |
|
| 55 |
+
| GRPO Full Fine-Tuning | BF16 | 1*24GB | 1*40GB | 4*40GB | 8*80GB |
|
| 56 |
+
|
| 57 |
+
> [!NOTE]
|
| 58 |
+
> Use `worker.actor.fsdp.torch_dtype=bf16` and `worker.actor.optim.strategy=adamw_bf16` to enable bf16 training.
|
| 59 |
+
>
|
| 60 |
+
> We are working hard to reduce the VRAM in RL training, LoRA support will be integrated in next updates.
|
| 61 |
+
|
| 62 |
+
## Tutorial: Run Qwen2.5-VL GRPO on [Geometry3K](https://huggingface.co/datasets/hiyouga/geometry3k) Dataset in Just 3 Steps
|
| 63 |
+
|
| 64 |
+

|
| 65 |
+
|
| 66 |
+
### Installation
|
| 67 |
+
|
| 68 |
+
```bash
|
| 69 |
+
git clone https://github.com/hiyouga/EasyR1.git
|
| 70 |
+
cd EasyR1
|
| 71 |
+
pip install -e .
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
### GRPO Training
|
| 75 |
+
|
| 76 |
+
```bash
|
| 77 |
+
bash examples/qwen2_5_vl_7b_geo3k_grpo.sh
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
### Merge Checkpoint in Hugging Face Format
|
| 81 |
+
|
| 82 |
+
```bash
|
| 83 |
+
python3 scripts/model_merger.py --local_dir checkpoints/easy_r1/exp_name/global_step_1/actor
|
| 84 |
+
```
|
| 85 |
+
|
| 86 |
+
> [!TIP]
|
| 87 |
+
> If you encounter issues with connecting to Hugging Face, consider using `export HF_ENDPOINT=https://hf-mirror.com`.
|
| 88 |
+
>
|
| 89 |
+
> If you want to use SwanLab logger, consider using `bash examples/qwen2_5_vl_7b_geo3k_swanlab.sh`.
|
| 90 |
+
|
| 91 |
+
## Custom Dataset
|
| 92 |
+
|
| 93 |
+
Please refer to the example datasets to prepare your own dataset.
|
| 94 |
+
|
| 95 |
+
- Text dataset: https://huggingface.co/datasets/hiyouga/math12k
|
| 96 |
+
- Image-text dataset: https://huggingface.co/datasets/hiyouga/geometry3k
|
| 97 |
+
- Multi-image-text dataset: https://huggingface.co/datasets/hiyouga/journeybench-multi-image-vqa
|
| 98 |
+
|
| 99 |
+
## How to Understand GRPO in EasyR1
|
| 100 |
+
|
| 101 |
+

|
| 102 |
+
|
| 103 |
+
- To learn about the GRPO algorithm, you can refer to [Hugging Face's blog](https://huggingface.co/docs/trl/v0.16.1/en/grpo_trainer).
|
| 104 |
+
|
| 105 |
+
## How to Run 70B+ Model in Multi-node Environment
|
| 106 |
+
|
| 107 |
+
1. Start the Ray head node.
|
| 108 |
+
|
| 109 |
+
```bash
|
| 110 |
+
ray start --head --port=6379 --dashboard-host=0.0.0.0
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
2. Start the Ray worker node and connect to the head node.
|
| 114 |
+
|
| 115 |
+
```bash
|
| 116 |
+
ray start --address=<head_node_ip>:6379
|
| 117 |
+
```
|
| 118 |
+
|
| 119 |
+
3. Check the Ray resource pool.
|
| 120 |
+
|
| 121 |
+
```bash
|
| 122 |
+
ray status
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
4. Run training script on the Ray head node only.
|
| 126 |
+
|
| 127 |
+
```bash
|
| 128 |
+
bash examples/qwen2_5_vl_7b_geo3k_grpo.sh
|
| 129 |
+
```
|
| 130 |
+
|
| 131 |
+
See the **[veRL's official doc](https://verl.readthedocs.io/en/latest/start/multinode.html)** for more details about multi-node training and Ray debugger.
|
| 132 |
+
|
| 133 |
+
## Other Baselines
|
| 134 |
+
|
| 135 |
+
We also reproduced the following two baselines of the [R1-V](https://github.com/deep-agent/R1-V) project.
|
| 136 |
+
- [CLEVR-70k-Counting](examples/baselines/qwen2_5_vl_3b_clevr.sh): Train the Qwen2.5-VL-3B-Instruct model on counting problem.
|
| 137 |
+
- [GeoQA-8k](examples/baselines/qwen2_5_vl_3b_geoqa8k.sh): Train the Qwen2.5-VL-3B-Instruct model on GeoQA problem.
|
| 138 |
+
|
| 139 |
+
## Performance Baselines
|
| 140 |
+
|
| 141 |
+
See [baselines.md](assets/baselines.md).
|
| 142 |
+
|
| 143 |
+
## Awesome Work using EasyR1
|
| 144 |
+
|
| 145 |
+
- **MMR1**: Advancing the Frontiers of Multimodal Reasoning. [![[code]](https://img.shields.io/github/stars/LengSicong/MMR1)](https://github.com/LengSicong/MMR1)
|
| 146 |
+
- **Vision-R1**: Incentivizing Reasoning Capability in Multimodal Large Language Models. [![[code]](https://img.shields.io/github/stars/Osilly/Vision-R1)](https://github.com/Osilly/Vision-R1) [![[arxiv]](https://img.shields.io/badge/arxiv-2503.06749-blue)](https://arxiv.org/abs/2503.06749)
|
| 147 |
+
- **Seg-Zero**: Reasoning-Chain Guided Segmentation via Cognitive Reinforcement. [![[code]](https://img.shields.io/github/stars/dvlab-research/Seg-Zero)](https://github.com/dvlab-research/Seg-Zero) [![[arxiv]](https://img.shields.io/badge/arxiv-2503.06520-blue)](https://arxiv.org/abs/2503.06520)
|
| 148 |
+
- **MetaSpatial**: Reinforcing 3D Spatial Reasoning in VLMs for the Metaverse. [![[code]](https://img.shields.io/github/stars/PzySeere/MetaSpatial)](https://github.com/PzySeere/MetaSpatial) [![[arxiv]](https://img.shields.io/badge/arxiv-2503.18470-blue)](https://arxiv.org/abs/2503.18470)
|
| 149 |
+
- **Temporal-R1**: Envolving Temporal Reasoning Capability into LMMs via Temporal Consistent Reward. [![[code]](https://img.shields.io/github/stars/appletea233/Temporal-R1)](https://github.com/appletea233/Temporal-R1)
|
| 150 |
+
- **NoisyRollout**: Reinforcing Visual Reasoning with Data Augmentation. [![[code]](https://img.shields.io/github/stars/John-AI-Lab/NoisyRollout)](https://github.com/John-AI-Lab/NoisyRollout) [![[arxiv]](https://img.shields.io/badge/arxiv-2504.13055-blue)](https://arxiv.org/pdf/2504.13055)
|
| 151 |
+
- **GUI-R1**: A Generalist R1-Style Vision-Language Action Model For GUI Agents. [![[code]](https://img.shields.io/github/stars/ritzz-ai/GUI-R1)](https://github.com/ritzz-ai/GUI-R1) [![[arxiv]](https://img.shields.io/badge/arxiv-2504.10458-blue)](https://arxiv.org/abs/2504.10458)
|
| 152 |
+
- **R1-Track**: Direct Application of MLLMs to Visual Object Tracking via Reinforcement Learning. [![[code]](https://img.shields.io/github/stars/Wangbiao2/R1-Track)](https://github.com/Wangbiao2/R1-Track)
|
| 153 |
+
- **VisionReasoner**: Unified Visual Perception and Reasoning via Reinforcement Learning. [![[code]](https://img.shields.io/github/stars/dvlab-research/VisionReasoner)](https://github.com/dvlab-research/VisionReasoner) [![[arxiv]](https://img.shields.io/badge/arxiv-2505.12081-blue)](https://arxiv.org/abs/2505.12081)
|
| 154 |
+
- **MM-UPT**: Unsupervised Post-Training for Multi-Modal LLM Reasoning via GRPO. [![[code]](https://img.shields.io/github/stars/waltonfuture/MM-UPT)](https://github.com/waltonfuture/MM-UPT) [![[arxiv]](https://img.shields.io/badge/arxiv-2505.22453-blue)](https://arxiv.org/pdf/2505.22453)
|
| 155 |
+
- **RL-with-Cold-Start**: Advancing Multimodal Reasoning via Reinforcement Learning with Cold Start. [![[code]](https://img.shields.io/github/stars/waltonfuture/RL-with-Cold-Start)](https://github.com/waltonfuture/RL-with-Cold-Start) [![[arxiv]](https://img.shields.io/badge/arxiv-2505.22334-blue)](https://arxiv.org/pdf/2505.22334)
|
| 156 |
+
- **ViGoRL**: Grounded Reinforcement Learning for Visual Reasoning. [![[code]](https://img.shields.io/github/stars/Gabesarch/grounded-rl)](https://github.com/Gabesarch/grounded-rl) [![[arxiv]](https://img.shields.io/badge/arxiv-2505.22334-blue)](https://arxiv.org/abs/2505.23678)
|
| 157 |
+
- **Revisual-R1**: Advancing Multimodal Reasoning: From Optimized Cold Start to Staged Reinforcement Learning. [![[code]](https://img.shields.io/github/stars/CSfufu/Revisual-R1)](https://github.com/CSfufu/Revisual-R1) [![[arxiv]](https://img.shields.io/badge/arxiv-2506.04207-blue)](https://arxiv.org/abs/2506.04207)
|
| 158 |
+
- **SophiaVL-R1**: Reinforcing MLLMs Reasoning with Thinking Reward. [![[code]](https://img.shields.io/github/stars/kxfan2002/SophiaVL-R1)](https://github.com/kxfan2002/SophiaVL-R1) [![[arxiv]](https://img.shields.io/badge/arxiv-2505.17018-blue)](https://arxiv.org/abs/2505.17018)
|
| 159 |
+
|
| 160 |
+
## TODO
|
| 161 |
+
|
| 162 |
+
- Support LoRA (high priority).
|
| 163 |
+
- Support ulysses parallelism for VLMs (middle priority).
|
| 164 |
+
- Support more VLM architectures.
|
| 165 |
+
|
| 166 |
+
> [!NOTE]
|
| 167 |
+
> We will not provide scripts for supervised fine-tuning and inference in this project. If you have such requirements, we recommend using [LLaMA-Factory](https://github.com/hiyouga/LLaMA-Factory).
|
| 168 |
+
|
| 169 |
+
### Known bugs
|
| 170 |
+
|
| 171 |
+
These features are temporarily disabled for now, we plan to fix them one-by-one in the future updates.
|
| 172 |
+
|
| 173 |
+
- Vision language models are not compatible with ulysses parallelism yet.
|
| 174 |
+
|
| 175 |
+
## Discussion Group
|
| 176 |
+
|
| 177 |
+
👋 Join our [WeChat group](assets/wechat.jpg).
|
| 178 |
+
|
| 179 |
+
## FAQs
|
| 180 |
+
|
| 181 |
+
> ValueError: Image features and image tokens do not match: tokens: 8192, features 9800
|
| 182 |
+
|
| 183 |
+
Increase the `data.max_prompt_length` or reduce the `data.max_pixels`.
|
| 184 |
+
|
| 185 |
+
> RuntimeError: CUDA Error: out of memory at /workspace/csrc/cumem_allocator.cpp:62
|
| 186 |
+
|
| 187 |
+
Reduce the `worker.rollout.gpu_memory_utilization` and enable `worker.actor.offload.offload_params`.
|
| 188 |
+
|
| 189 |
+
> RuntimeError: 0 active drivers ([]). There should only be one.
|
| 190 |
+
|
| 191 |
+
Uninstall `deepspeed` from the current python environment.
|
| 192 |
+
|
| 193 |
+
## Citation
|
| 194 |
+
|
| 195 |
+
Core contributors: [Yaowei Zheng](https://github.com/hiyouga), [Junting Lu](https://github.com/AL-377), [Shenzhi Wang](https://github.com/Shenzhi-Wang), [Zhangchi Feng](https://github.com/BUAADreamer), [Dongdong Kuang](https://github.com/Kuangdd01) and Yuwen Xiong
|
| 196 |
+
|
| 197 |
+
We also thank Guangming Sheng and Chi Zhang for helpful discussions.
|
| 198 |
+
|
| 199 |
+
```bibtex
|
| 200 |
+
@misc{zheng2025easyr1,
|
| 201 |
+
title = {EasyR1: An Efficient, Scalable, Multi-Modality RL Training Framework},
|
| 202 |
+
author = {Yaowei Zheng, Junting Lu, Shenzhi Wang, Zhangchi Feng, Dongdong Kuang, Yuwen Xiong},
|
| 203 |
+
howpublished = {\url{https://github.com/hiyouga/EasyR1}},
|
| 204 |
+
year = {2025}
|
| 205 |
+
}
|
| 206 |
+
```
|
| 207 |
+
|
| 208 |
+
We recommend to also cite the original work.
|
| 209 |
+
|
| 210 |
+
```bibtex
|
| 211 |
+
@article{sheng2024hybridflow,
|
| 212 |
+
title = {HybridFlow: A Flexible and Efficient RLHF Framework},
|
| 213 |
+
author = {Guangming Sheng and Chi Zhang and Zilingfeng Ye and Xibin Wu and Wang Zhang and Ru Zhang and Yanghua Peng and Haibin Lin and Chuan Wu},
|
| 214 |
+
year = {2024},
|
| 215 |
+
journal = {arXiv preprint arXiv: 2409.19256}
|
| 216 |
+
}
|
| 217 |
+
```
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/__init__.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
|
| 17 |
+
from .utils.py_functional import is_package_available
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if is_package_available("modelscope"):
|
| 21 |
+
from modelscope.utils.hf_util import patch_hub # type: ignore
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
__version__ = "0.3.1.dev0"
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if os.getenv("USE_MODELSCOPE_HUB", "0").lower() in ["true", "y", "1"]:
|
| 28 |
+
# Patch hub to download models from modelscope to speed up.
|
| 29 |
+
if not is_package_available("modelscope"):
|
| 30 |
+
raise ImportError("You are using the modelscope hub, please install modelscope by `pip install modelscope`.")
|
| 31 |
+
|
| 32 |
+
patch_hub()
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/init
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/protocol.py
ADDED
|
@@ -0,0 +1,689 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""
|
| 15 |
+
Implement base data transfer protocol between any two functions, modules.
|
| 16 |
+
We can subclass Protocol to define more detailed batch info with specific keys
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import copy
|
| 20 |
+
import io
|
| 21 |
+
import pickle
|
| 22 |
+
from collections import defaultdict
|
| 23 |
+
from dataclasses import dataclass, field
|
| 24 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
import ray
|
| 28 |
+
import torch
|
| 29 |
+
from numpy.typing import NDArray
|
| 30 |
+
from tensordict import TensorDict
|
| 31 |
+
from torch.distributed import ProcessGroup
|
| 32 |
+
from torch.utils.data import DataLoader
|
| 33 |
+
|
| 34 |
+
from .utils.py_functional import union_two_dict
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
import tensordict
|
| 39 |
+
|
| 40 |
+
tensordict.set_lazy_legacy(False).set()
|
| 41 |
+
except Exception:
|
| 42 |
+
pass
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
__all__ = ["DataProto", "union_tensor_dict"]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def pad_dataproto_to_divisor(data: "DataProto", size_divisor: int) -> Tuple["DataProto", int]:
|
| 49 |
+
"""Pad a DataProto to size divisible by size_divisor
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
data (DataProto): the unpadded DataProto
|
| 53 |
+
size_divisor (int): size divisor
|
| 54 |
+
|
| 55 |
+
Returns:
|
| 56 |
+
data (DataProto): the padded DataProto
|
| 57 |
+
pad_size (int)
|
| 58 |
+
"""
|
| 59 |
+
assert isinstance(data, DataProto), "data must be a DataProto"
|
| 60 |
+
if len(data) % size_divisor != 0:
|
| 61 |
+
pad_size = size_divisor - len(data) % size_divisor
|
| 62 |
+
padding_protos = []
|
| 63 |
+
remaining_pad = pad_size
|
| 64 |
+
while remaining_pad > 0:
|
| 65 |
+
take_size = min(remaining_pad, len(data))
|
| 66 |
+
padding_protos.append(data[:take_size])
|
| 67 |
+
remaining_pad -= take_size
|
| 68 |
+
|
| 69 |
+
data_padded = DataProto.concat([data] + padding_protos)
|
| 70 |
+
else:
|
| 71 |
+
pad_size = 0
|
| 72 |
+
data_padded = data
|
| 73 |
+
|
| 74 |
+
return data_padded, pad_size
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def unpad_dataproto(data: "DataProto", pad_size: int) -> "DataProto":
|
| 78 |
+
if pad_size != 0:
|
| 79 |
+
data = data[:-pad_size]
|
| 80 |
+
|
| 81 |
+
return data
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def union_tensor_dict(tensor_dict1: TensorDict, tensor_dict2: TensorDict) -> TensorDict:
|
| 85 |
+
"""Union two tensordicts."""
|
| 86 |
+
if tensor_dict1.batch_size != tensor_dict2.batch_size:
|
| 87 |
+
raise ValueError(
|
| 88 |
+
f"Two tensor dict must have identical batch size. Got {tensor_dict1.batch_size} and {tensor_dict2.batch_size}"
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
for key in tensor_dict2.keys():
|
| 92 |
+
if key in tensor_dict1 and not torch.equal(tensor_dict1[key], tensor_dict2[key]):
|
| 93 |
+
raise ValueError(f"Key already exists: {key}.")
|
| 94 |
+
|
| 95 |
+
tensor_dict1[key] = tensor_dict2[key]
|
| 96 |
+
|
| 97 |
+
return tensor_dict1
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def union_numpy_dict(tensor_dict1: Dict[str, NDArray], tensor_dict2: Dict[str, NDArray]) -> Dict[str, NDArray]:
|
| 101 |
+
for key in tensor_dict2.keys():
|
| 102 |
+
if key in tensor_dict1:
|
| 103 |
+
assert isinstance(tensor_dict2[key], np.ndarray)
|
| 104 |
+
assert isinstance(tensor_dict1[key], np.ndarray)
|
| 105 |
+
if not np.all(tensor_dict1[key] == tensor_dict2[key]):
|
| 106 |
+
raise ValueError(f"Key already exists: {key}.")
|
| 107 |
+
|
| 108 |
+
tensor_dict1[key] = tensor_dict2[key]
|
| 109 |
+
|
| 110 |
+
return tensor_dict1
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def batch_collate(features: List[Dict[str, Any]]) -> Dict[str, List[Any]]:
|
| 114 |
+
if len(features) == 0:
|
| 115 |
+
return {}
|
| 116 |
+
|
| 117 |
+
batch_features = defaultdict(list)
|
| 118 |
+
for feature in features:
|
| 119 |
+
for key, value in feature.items():
|
| 120 |
+
batch_features[key].append(value)
|
| 121 |
+
|
| 122 |
+
return batch_features
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def fold_batch_dim(data: "DataProto", new_batch_size: int):
|
| 126 |
+
"""
|
| 127 |
+
Fold a batch dim from [bsz, xxx] into [new_bsz, bsz // new_bsz, xxx]
|
| 128 |
+
"""
|
| 129 |
+
batch_size = data.batch.batch_size[0]
|
| 130 |
+
|
| 131 |
+
assert batch_size % new_batch_size == 0
|
| 132 |
+
|
| 133 |
+
tensor: TensorDict = data.batch
|
| 134 |
+
non_tensor = data.non_tensor_batch
|
| 135 |
+
|
| 136 |
+
tensor = tensor.view(new_batch_size, -1)
|
| 137 |
+
tensor.auto_batch_size_(batch_dims=1)
|
| 138 |
+
|
| 139 |
+
for key, value in non_tensor.items():
|
| 140 |
+
non_tensor[key] = np.reshape(value, newshape=(new_batch_size, -1, *value.shape[1:]))
|
| 141 |
+
|
| 142 |
+
return DataProto(batch=tensor, non_tensor_batch=non_tensor, meta_info=data.meta_info)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def collate_fn(data_items: list["DataProtoItem"]):
|
| 146 |
+
batch = []
|
| 147 |
+
non_tensor_batch = []
|
| 148 |
+
for data in data_items:
|
| 149 |
+
batch.append(data.batch)
|
| 150 |
+
non_tensor_batch.append(data.non_tensor_batch)
|
| 151 |
+
|
| 152 |
+
batch = torch.stack(batch).contiguous()
|
| 153 |
+
non_tensor_batch = batch_collate(non_tensor_batch)
|
| 154 |
+
non_tensor_batch = {key: np.array(value, dtype=object) for key, value in non_tensor_batch.items()}
|
| 155 |
+
return DataProto(batch=batch, non_tensor_batch=non_tensor_batch)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
@dataclass
|
| 159 |
+
class DataProtoItem:
|
| 160 |
+
batch: Optional[TensorDict] = None
|
| 161 |
+
non_tensor_batch: Dict[str, NDArray] = field(default_factory=dict)
|
| 162 |
+
meta_info: Dict[str, Any] = field(default_factory=dict)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
@dataclass
|
| 166 |
+
class DataProto:
|
| 167 |
+
"""
|
| 168 |
+
A DataProto is a data structure that aims to provide a standard protocol for data exchange between functions.
|
| 169 |
+
It contains a batch (TensorDict) and a meta_info (Dict). The batch is a TensorDict https://pytorch.org/tensordict/.
|
| 170 |
+
TensorDict allows you to manipulate a dictionary of Tensors like a single Tensor. Ideally, the tensors with the
|
| 171 |
+
same batch size should be put inside batch.
|
| 172 |
+
"""
|
| 173 |
+
|
| 174 |
+
batch: Optional[TensorDict] = None
|
| 175 |
+
non_tensor_batch: Dict[str, NDArray] = field(default_factory=dict)
|
| 176 |
+
meta_info: Dict[str, Any] = field(default_factory=dict)
|
| 177 |
+
|
| 178 |
+
def __post_init__(self):
|
| 179 |
+
self.check_consistency() # perform necessary checking
|
| 180 |
+
|
| 181 |
+
def __len__(self) -> int:
|
| 182 |
+
if self.batch is not None:
|
| 183 |
+
return self.batch.batch_size[0]
|
| 184 |
+
elif self.non_tensor_batch is not None and len(self.non_tensor_batch) > 0:
|
| 185 |
+
pivot_key = list(self.non_tensor_batch.keys())[0]
|
| 186 |
+
return self.non_tensor_batch[pivot_key].shape[0]
|
| 187 |
+
else:
|
| 188 |
+
return 0
|
| 189 |
+
|
| 190 |
+
def __getitem__(self, item: Union[int, slice]) -> Union["DataProto", "DataProtoItem"]:
|
| 191 |
+
tensor_data = self.batch[item]
|
| 192 |
+
non_tensor_data = {key: value[item] for key, value in self.non_tensor_batch.items()}
|
| 193 |
+
return_type = DataProto if isinstance(item, slice) else DataProtoItem
|
| 194 |
+
return return_type(batch=tensor_data, non_tensor_batch=non_tensor_data, meta_info=self.meta_info)
|
| 195 |
+
|
| 196 |
+
def __getstate__(self) -> Tuple[bytes, Dict[str, NDArray], Dict[str, Any]]:
|
| 197 |
+
buffer = io.BytesIO()
|
| 198 |
+
if self.batch is not None:
|
| 199 |
+
self.batch: TensorDict = self.batch.contiguous()
|
| 200 |
+
self.batch: TensorDict = self.batch.consolidate()
|
| 201 |
+
|
| 202 |
+
torch.save(self.batch, buffer)
|
| 203 |
+
buffer_bytes = buffer.getvalue()
|
| 204 |
+
return buffer_bytes, self.non_tensor_batch, self.meta_info
|
| 205 |
+
|
| 206 |
+
def __setstate__(self, data: Tuple[bytes, Dict[str, NDArray], Dict[str, Any]]) -> None:
|
| 207 |
+
batch_deserialized_bytes, non_tensor_batch, meta_info = data
|
| 208 |
+
batch_deserialized = io.BytesIO(batch_deserialized_bytes)
|
| 209 |
+
batch = torch.load(batch_deserialized, weights_only=False, map_location="cpu")
|
| 210 |
+
self.batch = batch
|
| 211 |
+
self.non_tensor_batch = non_tensor_batch
|
| 212 |
+
self.meta_info = meta_info
|
| 213 |
+
|
| 214 |
+
def save_to_disk(self, filepath: str) -> None:
|
| 215 |
+
with open(filepath, "wb") as f:
|
| 216 |
+
pickle.dump(self, f)
|
| 217 |
+
|
| 218 |
+
@staticmethod
|
| 219 |
+
def load_from_disk(filepath: str) -> "DataProto":
|
| 220 |
+
with open(filepath, "rb") as f:
|
| 221 |
+
data = pickle.load(f)
|
| 222 |
+
return data
|
| 223 |
+
|
| 224 |
+
def print_size(self, prefix: str = "") -> None:
|
| 225 |
+
size_of_tensordict = 0
|
| 226 |
+
if self.batch is not None:
|
| 227 |
+
for tensor in self.batch.values():
|
| 228 |
+
if isinstance(tensor, torch.Tensor):
|
| 229 |
+
size_of_tensordict += tensor.element_size() * tensor.numel()
|
| 230 |
+
|
| 231 |
+
size_of_numpy_array = 0
|
| 232 |
+
for value in self.non_tensor_batch.values():
|
| 233 |
+
size_of_numpy_array += value.nbytes
|
| 234 |
+
|
| 235 |
+
size_of_numpy_array /= 1024**3
|
| 236 |
+
size_of_tensordict /= 1024**3
|
| 237 |
+
|
| 238 |
+
message = f"Size of tensordict: {size_of_tensordict} GB, size of non_tensor_batch: {size_of_numpy_array} GB."
|
| 239 |
+
print({prefix}, {message})
|
| 240 |
+
|
| 241 |
+
def check_consistency(self):
|
| 242 |
+
"""Check the consistency of the DataProto. Mainly for batch and non_tensor_batch
|
| 243 |
+
We expose this function as a public one so that user can call themselves directly
|
| 244 |
+
"""
|
| 245 |
+
if self.batch is not None:
|
| 246 |
+
assert len(self.batch.batch_size) == 1, "only support num_batch_dims=1"
|
| 247 |
+
|
| 248 |
+
if self.batch is not None and len(self.non_tensor_batch) != 0:
|
| 249 |
+
# TODO: we can actually lift this restriction if needed
|
| 250 |
+
assert len(self.batch.batch_size) == 1, "only support num_batch_dims=1 when non_tensor_batch is not empty."
|
| 251 |
+
|
| 252 |
+
batch_size = self.batch.batch_size[0]
|
| 253 |
+
for key, value in self.non_tensor_batch.items():
|
| 254 |
+
assert len(value) == batch_size, f"key {key} length {len(value)} is not equal to bsz {batch_size}."
|
| 255 |
+
|
| 256 |
+
@classmethod
|
| 257 |
+
def from_single_dict(
|
| 258 |
+
cls,
|
| 259 |
+
data: Dict[str, Union[torch.Tensor, NDArray]],
|
| 260 |
+
meta_info: Optional[Dict[str, Any]] = None,
|
| 261 |
+
) -> "DataProto":
|
| 262 |
+
tensors, non_tensors = {}, {}
|
| 263 |
+
for key, value in data.items():
|
| 264 |
+
if isinstance(value, torch.Tensor):
|
| 265 |
+
tensors[key] = value
|
| 266 |
+
elif isinstance(value, np.ndarray):
|
| 267 |
+
non_tensors[key] = value
|
| 268 |
+
else:
|
| 269 |
+
raise ValueError(f"Unsupported type in data {type(value)}")
|
| 270 |
+
|
| 271 |
+
return DataProto.from_dict(tensors=tensors, non_tensors=non_tensors, meta_info=meta_info)
|
| 272 |
+
|
| 273 |
+
@classmethod
|
| 274 |
+
def from_dict(
|
| 275 |
+
cls,
|
| 276 |
+
tensors: Dict[str, torch.Tensor],
|
| 277 |
+
non_tensors: Dict[str, NDArray] = None,
|
| 278 |
+
meta_info: Optional[Dict[str, Any]] = None,
|
| 279 |
+
num_batch_dims: int = 1,
|
| 280 |
+
) -> "DataProto":
|
| 281 |
+
"""Create a DataProto from a dict of tensors. This assumes that
|
| 282 |
+
1. All the tensor in tensors have the same dim0
|
| 283 |
+
2. Only dim0 is the batch dim
|
| 284 |
+
"""
|
| 285 |
+
assert len(tensors) > 0, "tensors must not be empty"
|
| 286 |
+
assert num_batch_dims > 0, "num_batch_dims must be greater than zero"
|
| 287 |
+
if non_tensors is not None:
|
| 288 |
+
assert num_batch_dims == 1, "only support num_batch_dims=1 when non_tensors is not None."
|
| 289 |
+
|
| 290 |
+
meta_info = meta_info or {}
|
| 291 |
+
non_tensors = non_tensors or {}
|
| 292 |
+
assert isinstance(non_tensors, dict), "non_tensors should be a dictionary."
|
| 293 |
+
|
| 294 |
+
# get and check batch size
|
| 295 |
+
batch_size = None
|
| 296 |
+
pivot_key = None
|
| 297 |
+
for key, tensor in tensors.items():
|
| 298 |
+
if batch_size is None:
|
| 299 |
+
batch_size = tensor.shape[:num_batch_dims]
|
| 300 |
+
pivot_key = key
|
| 301 |
+
else:
|
| 302 |
+
current_batch = tensor.shape[:num_batch_dims]
|
| 303 |
+
assert batch_size == current_batch, (
|
| 304 |
+
f"Not all the tensor in tensors have the same batch size with batch_dims={num_batch_dims}. "
|
| 305 |
+
f"Got {pivot_key} has {batch_size}, {key} has {current_batch}"
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
tensor_dict = TensorDict(source=tensors, batch_size=batch_size)
|
| 309 |
+
return cls(batch=tensor_dict, non_tensor_batch=non_tensors, meta_info=meta_info)
|
| 310 |
+
|
| 311 |
+
def to(self, device: torch.device) -> "DataProto":
|
| 312 |
+
"""move the batch to device
|
| 313 |
+
|
| 314 |
+
Args:
|
| 315 |
+
device (torch.device, str): torch device
|
| 316 |
+
|
| 317 |
+
Returns:
|
| 318 |
+
DataProto: the current DataProto
|
| 319 |
+
|
| 320 |
+
"""
|
| 321 |
+
if self.batch is not None:
|
| 322 |
+
self.batch = self.batch.to(device)
|
| 323 |
+
|
| 324 |
+
return self
|
| 325 |
+
|
| 326 |
+
def select(
|
| 327 |
+
self,
|
| 328 |
+
batch_keys: Optional[List[str]] = None,
|
| 329 |
+
non_tensor_batch_keys: Optional[List[str]] = None,
|
| 330 |
+
meta_info_keys: Optional[List[str]] = None,
|
| 331 |
+
deepcopy: bool = False,
|
| 332 |
+
) -> "DataProto":
|
| 333 |
+
"""Select a subset of the DataProto via batch_keys and meta_info_keys
|
| 334 |
+
|
| 335 |
+
Args:
|
| 336 |
+
batch_keys (list, optional): a list of strings indicating the keys in batch to select
|
| 337 |
+
meta_info_keys (list, optional): a list of keys indicating the meta info to select
|
| 338 |
+
|
| 339 |
+
Returns:
|
| 340 |
+
DataProto: the DataProto with the selected batch_keys and meta_info_keys
|
| 341 |
+
"""
|
| 342 |
+
# TODO (zhangchi.usc1992) whether to copy
|
| 343 |
+
if batch_keys is not None:
|
| 344 |
+
batch_keys = tuple(batch_keys)
|
| 345 |
+
sub_batch = self.batch.select(*batch_keys)
|
| 346 |
+
else:
|
| 347 |
+
sub_batch = self.batch
|
| 348 |
+
|
| 349 |
+
if non_tensor_batch_keys is not None:
|
| 350 |
+
non_tensor_batch = {k: v for k, v in self.non_tensor_batch.items() if k in non_tensor_batch_keys}
|
| 351 |
+
else:
|
| 352 |
+
non_tensor_batch = self.non_tensor_batch
|
| 353 |
+
|
| 354 |
+
if deepcopy:
|
| 355 |
+
non_tensor_batch = copy.deepcopy(non_tensor_batch)
|
| 356 |
+
|
| 357 |
+
if meta_info_keys is not None:
|
| 358 |
+
sub_meta_info = {k: v for k, v in self.meta_info.items() if k in meta_info_keys}
|
| 359 |
+
else:
|
| 360 |
+
sub_meta_info = self.meta_info
|
| 361 |
+
|
| 362 |
+
if deepcopy:
|
| 363 |
+
sub_meta_info = copy.deepcopy(sub_meta_info)
|
| 364 |
+
|
| 365 |
+
return DataProto(batch=sub_batch, non_tensor_batch=non_tensor_batch, meta_info=sub_meta_info)
|
| 366 |
+
|
| 367 |
+
def pop(
|
| 368 |
+
self,
|
| 369 |
+
batch_keys: Optional[List[str]] = None,
|
| 370 |
+
non_tensor_batch_keys: Optional[List[str]] = None,
|
| 371 |
+
meta_info_keys: Optional[List[str]] = None,
|
| 372 |
+
) -> "DataProto":
|
| 373 |
+
"""Pop a subset of the DataProto via `batch_keys` and `meta_info_keys`
|
| 374 |
+
|
| 375 |
+
Args:
|
| 376 |
+
batch_keys (list, optional): a list of strings indicating the keys in batch to pop
|
| 377 |
+
meta_info_keys (list, optional): a list of keys indicating the meta info to pop
|
| 378 |
+
|
| 379 |
+
Returns:
|
| 380 |
+
DataProto: the DataProto with the poped batch_keys and meta_info_keys
|
| 381 |
+
"""
|
| 382 |
+
assert batch_keys is not None
|
| 383 |
+
non_tensor_batch_keys = non_tensor_batch_keys or []
|
| 384 |
+
meta_info_keys = meta_info_keys or []
|
| 385 |
+
|
| 386 |
+
tensors = {}
|
| 387 |
+
for key in batch_keys:
|
| 388 |
+
tensors[key] = self.batch.pop(key)
|
| 389 |
+
|
| 390 |
+
non_tensors = {}
|
| 391 |
+
for key in non_tensor_batch_keys:
|
| 392 |
+
non_tensors[key] = self.non_tensor_batch.pop(key)
|
| 393 |
+
|
| 394 |
+
meta_info = {}
|
| 395 |
+
for key in meta_info_keys:
|
| 396 |
+
meta_info[key] = self.meta_info.pop(key)
|
| 397 |
+
|
| 398 |
+
return DataProto.from_dict(tensors=tensors, non_tensors=non_tensors, meta_info=meta_info)
|
| 399 |
+
|
| 400 |
+
def rename(
|
| 401 |
+
self, old_keys: Optional[Union[str, List[str]]] = None, new_keys: Optional[Union[str, List[str]]] = None
|
| 402 |
+
) -> "DataProto":
|
| 403 |
+
"""
|
| 404 |
+
Note that this function only rename the key in the batch
|
| 405 |
+
"""
|
| 406 |
+
|
| 407 |
+
def validate_input(keys):
|
| 408 |
+
if keys is not None:
|
| 409 |
+
if isinstance(keys, str):
|
| 410 |
+
keys = [keys]
|
| 411 |
+
elif isinstance(keys, list):
|
| 412 |
+
pass
|
| 413 |
+
else:
|
| 414 |
+
raise TypeError(f"keys must be a list or a string, but got {type(keys)}")
|
| 415 |
+
return keys
|
| 416 |
+
|
| 417 |
+
old_keys = validate_input(old_keys)
|
| 418 |
+
new_keys = validate_input(new_keys)
|
| 419 |
+
|
| 420 |
+
if len(new_keys) != len(old_keys):
|
| 421 |
+
raise ValueError(
|
| 422 |
+
f"new_keys and old_keys must have the same length, but got {len(new_keys)} and {len(old_keys)}"
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
self.batch.rename_key_(tuple(old_keys), tuple(new_keys))
|
| 426 |
+
|
| 427 |
+
return self
|
| 428 |
+
|
| 429 |
+
def union(self, other: "DataProto") -> "DataProto":
|
| 430 |
+
"""Union with another DataProto. Union batch and meta_info separately.
|
| 431 |
+
Throw an error if
|
| 432 |
+
- there are conflict keys in batch and they are not equal
|
| 433 |
+
- the batch size of two data batch is not the same
|
| 434 |
+
- there are conflict keys in meta_info and they are not the same.
|
| 435 |
+
|
| 436 |
+
Args:
|
| 437 |
+
other (DataProto): another DataProto to union
|
| 438 |
+
|
| 439 |
+
Returns:
|
| 440 |
+
DataProto: the DataProto after union
|
| 441 |
+
"""
|
| 442 |
+
self.batch = union_tensor_dict(self.batch, other.batch)
|
| 443 |
+
self.non_tensor_batch = union_numpy_dict(self.non_tensor_batch, other.non_tensor_batch)
|
| 444 |
+
self.meta_info = union_two_dict(self.meta_info, other.meta_info)
|
| 445 |
+
return self
|
| 446 |
+
|
| 447 |
+
def make_iterator(
|
| 448 |
+
self, mini_batch_size: int, epochs: int, seed: int = None, dataloader_kwargs: Dict[str, Any] = None
|
| 449 |
+
):
|
| 450 |
+
"""Make an iterator from the DataProto. This is built upon that TensorDict can be used as a normal Pytorch
|
| 451 |
+
dataset. See https://pytorch.org/tensordict/tutorials/data_fashion for more details.
|
| 452 |
+
|
| 453 |
+
Args:
|
| 454 |
+
mini_batch_size (int): mini-batch size when iterating the dataset. We require that
|
| 455 |
+
``batch.batch_size[0] % mini_batch_size == 0``
|
| 456 |
+
epochs (int): number of epochs when iterating the dataset.
|
| 457 |
+
dataloader_kwargs: internally, it returns a DataLoader over the batch.
|
| 458 |
+
The dataloader_kwargs is the kwargs passed to the DataLoader
|
| 459 |
+
|
| 460 |
+
Returns:
|
| 461 |
+
Iterator: an iterator that yields a mini-batch data at a time. The total number of iteration steps is
|
| 462 |
+
``self.batch.batch_size * epochs // mini_batch_size``
|
| 463 |
+
"""
|
| 464 |
+
assert self.batch.batch_size[0] % mini_batch_size == 0, f"{self.batch.batch_size[0]} % {mini_batch_size} != 0"
|
| 465 |
+
# we can directly create a dataloader from TensorDict
|
| 466 |
+
if dataloader_kwargs is None:
|
| 467 |
+
dataloader_kwargs = {}
|
| 468 |
+
|
| 469 |
+
if seed is not None:
|
| 470 |
+
generator = torch.Generator()
|
| 471 |
+
generator.manual_seed(seed)
|
| 472 |
+
else:
|
| 473 |
+
generator = None
|
| 474 |
+
|
| 475 |
+
assert isinstance(dataloader_kwargs, Dict)
|
| 476 |
+
train_dataloader = DataLoader(
|
| 477 |
+
dataset=self, batch_size=mini_batch_size, collate_fn=collate_fn, generator=generator, **dataloader_kwargs
|
| 478 |
+
)
|
| 479 |
+
|
| 480 |
+
def get_data():
|
| 481 |
+
for _ in range(epochs):
|
| 482 |
+
for d in train_dataloader:
|
| 483 |
+
d.meta_info = self.meta_info
|
| 484 |
+
yield d
|
| 485 |
+
|
| 486 |
+
return iter(get_data())
|
| 487 |
+
|
| 488 |
+
def chunk(self, chunks: int) -> List["DataProto"]:
|
| 489 |
+
"""Split the batch among dim=0 into chunks. The meta_info is passed to each DataProto after split.
|
| 490 |
+
|
| 491 |
+
Args:
|
| 492 |
+
chunks (int): the number of chunks to split on dim=0
|
| 493 |
+
|
| 494 |
+
Returns:
|
| 495 |
+
List[DataProto]: a list of DataProto after splitting
|
| 496 |
+
"""
|
| 497 |
+
assert len(self) % chunks == 0, (
|
| 498 |
+
f"only support equal chunk. Got size of DataProto {len(self)} and chunk {chunks}."
|
| 499 |
+
)
|
| 500 |
+
if self.batch is not None:
|
| 501 |
+
batch_lst = self.batch.chunk(chunks=chunks, dim=0)
|
| 502 |
+
else:
|
| 503 |
+
batch_lst = [None for _ in range(chunks)]
|
| 504 |
+
|
| 505 |
+
non_tensor_batch_lst = [{} for _ in range(chunks)]
|
| 506 |
+
for key, value in self.non_tensor_batch.items():
|
| 507 |
+
assert isinstance(value, np.ndarray)
|
| 508 |
+
non_tensor_lst = np.array_split(value, chunks)
|
| 509 |
+
assert len(non_tensor_lst) == chunks
|
| 510 |
+
for i in range(chunks):
|
| 511 |
+
non_tensor_batch_lst[i][key] = non_tensor_lst[i]
|
| 512 |
+
|
| 513 |
+
output = []
|
| 514 |
+
for i in range(chunks):
|
| 515 |
+
output.append(
|
| 516 |
+
DataProto(batch=batch_lst[i], non_tensor_batch=non_tensor_batch_lst[i], meta_info=self.meta_info)
|
| 517 |
+
)
|
| 518 |
+
|
| 519 |
+
return output
|
| 520 |
+
|
| 521 |
+
def split(self, split_size: int) -> List["DataProto"]:
|
| 522 |
+
chunks = len(self) // split_size
|
| 523 |
+
return self.chunk(chunks)
|
| 524 |
+
|
| 525 |
+
@staticmethod
|
| 526 |
+
def concat(data: List["DataProto"]) -> "DataProto":
|
| 527 |
+
"""Concat a list of DataProto. The batch is concatenated among dim=0.
|
| 528 |
+
The meta_info is assumed to be identical and will use the first one.
|
| 529 |
+
|
| 530 |
+
Args:
|
| 531 |
+
data (List[DataProto]): list of DataProto
|
| 532 |
+
|
| 533 |
+
Returns:
|
| 534 |
+
DataProto: concatenated DataProto
|
| 535 |
+
"""
|
| 536 |
+
batch_lst = [batch.batch for batch in data]
|
| 537 |
+
if batch_lst[0] is not None:
|
| 538 |
+
new_batch = torch.cat(batch_lst, dim=0)
|
| 539 |
+
else:
|
| 540 |
+
new_batch = None
|
| 541 |
+
|
| 542 |
+
non_tensor_batch = batch_collate([d.non_tensor_batch for d in data])
|
| 543 |
+
for key, value in non_tensor_batch.items():
|
| 544 |
+
non_tensor_batch[key] = np.concatenate(value, axis=0)
|
| 545 |
+
|
| 546 |
+
return DataProto(batch=new_batch, non_tensor_batch=non_tensor_batch, meta_info=data[0].meta_info)
|
| 547 |
+
|
| 548 |
+
def reorder(self, indices: torch.Tensor) -> None:
|
| 549 |
+
"""
|
| 550 |
+
Note that this operation is in-place
|
| 551 |
+
"""
|
| 552 |
+
indices_np = indices.detach().numpy()
|
| 553 |
+
self.batch = self.batch[indices]
|
| 554 |
+
self.non_tensor_batch = {key: value[indices_np] for key, value in self.non_tensor_batch.items()}
|
| 555 |
+
|
| 556 |
+
def repeat(self, repeat_times: int = 2, interleave: bool = True) -> "DataProto":
|
| 557 |
+
"""
|
| 558 |
+
Repeat the batch data a specified number of times.
|
| 559 |
+
|
| 560 |
+
Args:
|
| 561 |
+
repeat_times (int): Number of times to repeat the data.
|
| 562 |
+
interleave (bool): Whether to interleave the repeated data.
|
| 563 |
+
|
| 564 |
+
Returns:
|
| 565 |
+
DataProto: A new DataProto with repeated data.
|
| 566 |
+
"""
|
| 567 |
+
if self.batch is not None:
|
| 568 |
+
if interleave:
|
| 569 |
+
# Interleave the data
|
| 570 |
+
repeated_tensors = {
|
| 571 |
+
key: tensor.repeat_interleave(repeat_times, dim=0) for key, tensor in self.batch.items()
|
| 572 |
+
}
|
| 573 |
+
else:
|
| 574 |
+
# Stack the data
|
| 575 |
+
repeated_tensors = {
|
| 576 |
+
key: tensor.unsqueeze(0).expand(repeat_times, *tensor.shape).reshape(-1, *tensor.shape[1:])
|
| 577 |
+
for key, tensor in self.batch.items()
|
| 578 |
+
}
|
| 579 |
+
|
| 580 |
+
repeated_batch = TensorDict(
|
| 581 |
+
source=repeated_tensors,
|
| 582 |
+
batch_size=(self.batch.batch_size[0] * repeat_times,),
|
| 583 |
+
)
|
| 584 |
+
else:
|
| 585 |
+
repeated_batch = None
|
| 586 |
+
|
| 587 |
+
repeated_non_tensor_batch = {}
|
| 588 |
+
for key, value in self.non_tensor_batch.items():
|
| 589 |
+
if interleave:
|
| 590 |
+
repeated_non_tensor_batch[key] = np.repeat(value, repeat_times, axis=0)
|
| 591 |
+
else:
|
| 592 |
+
repeated_non_tensor_batch[key] = np.tile(value, (repeat_times,) + (1,) * (value.ndim - 1))
|
| 593 |
+
|
| 594 |
+
return DataProto(
|
| 595 |
+
batch=repeated_batch,
|
| 596 |
+
non_tensor_batch=repeated_non_tensor_batch,
|
| 597 |
+
meta_info=self.meta_info,
|
| 598 |
+
)
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
@dataclass
|
| 602 |
+
class DataProtoFuture:
|
| 603 |
+
"""
|
| 604 |
+
DataProtoFuture aims to eliminate actual data fetching on driver. By doing so, the driver doesn't have to wait
|
| 605 |
+
for data so that asynchronous execution becomes possible.
|
| 606 |
+
DataProtoFuture contains a list of futures from another WorkerGroup of size world_size.
|
| 607 |
+
- collect_fn is a Callable that reduces the list of futures to a DataProto
|
| 608 |
+
- dispatch_fn is a Callable that partitions the DataProto into a list of DataProto of size world_size and then select
|
| 609 |
+
|
| 610 |
+
Potential issue: we can optimize dispatch_fn(collect_fn) such that only needed data is fetched on destination
|
| 611 |
+
- DataProtoFuture only supports directly passing from the output of a method to another input. You can't perform any
|
| 612 |
+
operation on the DataProtoFuture in driver.
|
| 613 |
+
"""
|
| 614 |
+
|
| 615 |
+
collect_fn: Callable
|
| 616 |
+
futures: List[ray.ObjectRef]
|
| 617 |
+
dispatch_fn: Callable = None
|
| 618 |
+
|
| 619 |
+
@staticmethod
|
| 620 |
+
def concat(data: List[ray.ObjectRef]) -> "DataProtoFuture":
|
| 621 |
+
output = DataProtoFuture(collect_fn=DataProto.concat, futures=data)
|
| 622 |
+
return output
|
| 623 |
+
|
| 624 |
+
def chunk(self, chunks: int) -> List["DataProtoFuture"]:
|
| 625 |
+
from functools import partial
|
| 626 |
+
|
| 627 |
+
arg_future_lst = []
|
| 628 |
+
for i in range(chunks):
|
| 629 |
+
# note that we can't directly pass i and chunks
|
| 630 |
+
def dispatch_fn(x, i, chunks):
|
| 631 |
+
return x.chunk(chunks=chunks)[i]
|
| 632 |
+
|
| 633 |
+
arg_future = DataProtoFuture(
|
| 634 |
+
collect_fn=self.collect_fn, dispatch_fn=partial(dispatch_fn, i=i, chunks=chunks), futures=self.futures
|
| 635 |
+
)
|
| 636 |
+
arg_future_lst.append(arg_future)
|
| 637 |
+
return arg_future_lst
|
| 638 |
+
|
| 639 |
+
def get(self):
|
| 640 |
+
outputs = ray.get(self.futures) # dp_size.
|
| 641 |
+
for output in outputs:
|
| 642 |
+
assert isinstance(output, DataProto)
|
| 643 |
+
|
| 644 |
+
outputs = self.collect_fn(outputs) # select dp, concat
|
| 645 |
+
if self.dispatch_fn is not None:
|
| 646 |
+
outputs = self.dispatch_fn(outputs) # split in batch dim, select using dp
|
| 647 |
+
|
| 648 |
+
return outputs
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
def allgather_dict_tensors(
|
| 652 |
+
tensors: Union[Dict[str, torch.Tensor], TensorDict], size: int, group: ProcessGroup, dim: int = 0
|
| 653 |
+
) -> Union[Dict[str, torch.Tensor], TensorDict]:
|
| 654 |
+
"""
|
| 655 |
+
TODO: optimize this.
|
| 656 |
+
- We can use async ops
|
| 657 |
+
- We can use only one allgather
|
| 658 |
+
"""
|
| 659 |
+
if isinstance(tensors, TensorDict):
|
| 660 |
+
is_tensor_dict = True
|
| 661 |
+
tensors_as_dict = tensors.to_dict()
|
| 662 |
+
else:
|
| 663 |
+
tensors_as_dict = tensors
|
| 664 |
+
is_tensor_dict = False
|
| 665 |
+
|
| 666 |
+
output = {}
|
| 667 |
+
sorted_keys = sorted(tensors_as_dict.keys())
|
| 668 |
+
for key in sorted_keys:
|
| 669 |
+
value = tensors_as_dict[key]
|
| 670 |
+
output[key] = [torch.empty_like(value) for _ in range(size)]
|
| 671 |
+
torch.distributed.all_gather(output[key], value, group=group, async_op=False)
|
| 672 |
+
output[key] = torch.cat(output[key], dim=dim)
|
| 673 |
+
|
| 674 |
+
if is_tensor_dict:
|
| 675 |
+
output = TensorDict(source=output, batch_size=tensors.batch_size[0] * size)
|
| 676 |
+
|
| 677 |
+
return output
|
| 678 |
+
|
| 679 |
+
|
| 680 |
+
def all_gather_data_proto(data: DataProto, size: int, group: ProcessGroup) -> None:
|
| 681 |
+
# Note that this is an inplace operator just like torch.distributed.all_gather
|
| 682 |
+
prev_device = data.batch.device
|
| 683 |
+
data.batch = data.batch.cuda(device=torch.cuda.current_device())
|
| 684 |
+
data.batch = allgather_dict_tensors(data.batch.contiguous(), size=size, group=group, dim=0)
|
| 685 |
+
data.batch = data.batch.to(prev_device)
|
| 686 |
+
# all gather non_tensor_batch
|
| 687 |
+
all_non_tensor_batch = [None for _ in range(size)]
|
| 688 |
+
torch.distributed.all_gather_object(all_non_tensor_batch, data.non_tensor_batch, group=group)
|
| 689 |
+
data.non_tensor_batch = {k: np.concatenate([d[k] for d in all_non_tensor_batch]) for k in data.non_tensor_batch}
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/pyproject.toml
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["setuptools>=61.0"]
|
| 3 |
+
build-backend = "setuptools.build_meta"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "verl"
|
| 7 |
+
dynamic = [
|
| 8 |
+
"version",
|
| 9 |
+
"dependencies",
|
| 10 |
+
"optional-dependencies",
|
| 11 |
+
"requires-python",
|
| 12 |
+
"authors",
|
| 13 |
+
"description",
|
| 14 |
+
"readme",
|
| 15 |
+
"license"
|
| 16 |
+
]
|
| 17 |
+
|
| 18 |
+
[tool.ruff]
|
| 19 |
+
target-version = "py39"
|
| 20 |
+
line-length = 119
|
| 21 |
+
indent-width = 4
|
| 22 |
+
|
| 23 |
+
[tool.ruff.lint]
|
| 24 |
+
ignore = ["C901", "E501", "E741", "W605", "C408"]
|
| 25 |
+
select = ["C", "E", "F", "I", "W", "RUF022"]
|
| 26 |
+
|
| 27 |
+
[tool.ruff.lint.per-file-ignores]
|
| 28 |
+
"__init__.py" = ["E402", "F401", "F403", "F811"]
|
| 29 |
+
|
| 30 |
+
[tool.ruff.lint.isort]
|
| 31 |
+
lines-after-imports = 2
|
| 32 |
+
known-first-party = ["verl"]
|
| 33 |
+
known-third-party = ["torch", "transformers", "wandb"]
|
| 34 |
+
|
| 35 |
+
[tool.ruff.format]
|
| 36 |
+
quote-style = "double"
|
| 37 |
+
indent-style = "space"
|
| 38 |
+
skip-magic-trailing-comma = false
|
| 39 |
+
line-ending = "auto"
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/requirements.txt
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
accelerate
|
| 2 |
+
codetiming
|
| 3 |
+
datasets
|
| 4 |
+
liger-kernel
|
| 5 |
+
mathruler
|
| 6 |
+
numpy
|
| 7 |
+
omegaconf
|
| 8 |
+
pandas
|
| 9 |
+
peft
|
| 10 |
+
pillow
|
| 11 |
+
pyarrow>=15.0.0
|
| 12 |
+
pylatexenc
|
| 13 |
+
qwen-vl-utils
|
| 14 |
+
ray[default]
|
| 15 |
+
tensordict
|
| 16 |
+
torchdata
|
| 17 |
+
transformers>=4.51.0
|
| 18 |
+
vllm>=0.7.3
|
| 19 |
+
wandb
|