Add files using upload-large-folder tool
Browse files- 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/Dockerfile +76 -0
- 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/Makefile +18 -0
- 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/README.md +217 -0
- 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/__init__.py +32 -0
- 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/protocol.py +689 -0
- 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/pyproject.toml +39 -0
- 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/requirements.txt +19 -0
- 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/__init__.py +13 -0
- 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/dataset.py +235 -0
- 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/flops_counter.py +138 -0
- 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/fsdp_utils.py +140 -0
- 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/logger/__init__.py +19 -0
- 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/logger/logger.py +165 -0
- 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/model_utils.py +73 -0
- 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/py_functional.py +113 -0
- 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/seqlen_balancing.py +264 -0
- 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/tokenizer.py +51 -0
- 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/torch_dtypes.py +58 -0
- 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/torch_functional.py +340 -0
- 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/ulysses.py +298 -0
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/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
|
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/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)
|
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/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 |
+
```
|
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/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()
|
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/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}
|
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/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"
|
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/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
|
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.
|
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/dataset.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 math
|
| 16 |
+
import os
|
| 17 |
+
from collections import defaultdict
|
| 18 |
+
from io import BytesIO
|
| 19 |
+
from typing import Any, Dict, List, Optional, Union
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import torch
|
| 23 |
+
from datasets import load_dataset
|
| 24 |
+
from jinja2 import Template
|
| 25 |
+
from PIL import Image
|
| 26 |
+
from PIL.Image import Image as ImageObject
|
| 27 |
+
from PIL.Image import Image as PILImage
|
| 28 |
+
from torch.utils.data import Dataset
|
| 29 |
+
from transformers import PreTrainedTokenizer, ProcessorMixin
|
| 30 |
+
from PIL import Image, JpegImagePlugin
|
| 31 |
+
|
| 32 |
+
from ..models.transformers.qwen2_vl import get_rope_index
|
| 33 |
+
from . import torch_functional as VF
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def collate_fn(features: List[Dict[str, Any]]) -> Dict[str, Any]:
|
| 37 |
+
tensors = defaultdict(list)
|
| 38 |
+
non_tensors = defaultdict(list)
|
| 39 |
+
for feature in features:
|
| 40 |
+
for key, value in feature.items():
|
| 41 |
+
if isinstance(value, torch.Tensor):
|
| 42 |
+
tensors[key].append(value)
|
| 43 |
+
else:
|
| 44 |
+
non_tensors[key].append(value)
|
| 45 |
+
|
| 46 |
+
for key, value in tensors.items():
|
| 47 |
+
tensors[key] = torch.stack(value, dim=0)
|
| 48 |
+
|
| 49 |
+
for key, value in non_tensors.items():
|
| 50 |
+
non_tensors[key] = np.array(value, dtype=object)
|
| 51 |
+
|
| 52 |
+
return {**tensors, **non_tensors}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def process_image(image: Union[Dict[str, Any], ImageObject, str], min_pixels: int, max_pixels: int) -> ImageObject:
|
| 57 |
+
if isinstance(image, dict):
|
| 58 |
+
if 'path' in image:
|
| 59 |
+
image = Image.open(image['path']).copy()
|
| 60 |
+
else:
|
| 61 |
+
image = Image.open(BytesIO(image["bytes"]))
|
| 62 |
+
elif isinstance(image, bytes):
|
| 63 |
+
image = Image.open(BytesIO(image))
|
| 64 |
+
elif isinstance(image, list):
|
| 65 |
+
image = Image.open(image[0]).copy()
|
| 66 |
+
# image = image[0]
|
| 67 |
+
elif isinstance(image, PILImage):
|
| 68 |
+
image = image.copy()
|
| 69 |
+
else:
|
| 70 |
+
# image = image
|
| 71 |
+
raise TypeError(f'Unsupported image type: {type(image)}')
|
| 72 |
+
|
| 73 |
+
if (image.width * image.height) > max_pixels:
|
| 74 |
+
resize_factor = math.sqrt(max_pixels / (image.width * image.height))
|
| 75 |
+
width, height = int(image.width * resize_factor), int(image.height * resize_factor)
|
| 76 |
+
image = image.resize((width, height))
|
| 77 |
+
|
| 78 |
+
if (image.width * image.height) < min_pixels:
|
| 79 |
+
resize_factor = math.sqrt(min_pixels / (image.width * image.height))
|
| 80 |
+
width, height = int(image.width * resize_factor), int(image.height * resize_factor)
|
| 81 |
+
image = image.resize((width, height))
|
| 82 |
+
|
| 83 |
+
if image.mode != "RGB":
|
| 84 |
+
image = image.convert("RGB")
|
| 85 |
+
|
| 86 |
+
return image
|
| 87 |
+
|
| 88 |
+
def process_video(
|
| 89 |
+
video: str, min_pixels: Optional[int], max_pixels: Optional[int], video_fps: float, return_fps: bool = False
|
| 90 |
+
) -> Union[list[ImageObject], tuple[list[ImageObject], list[float]]]:
|
| 91 |
+
vision_info = {"video": video, "min_pixels": min_pixels, "max_pixels": max_pixels, "fps": video_fps}
|
| 92 |
+
return fetch_video(vision_info, return_video_sample_fps=return_fps)
|
| 93 |
+
|
| 94 |
+
class RLHFDataset(Dataset):
|
| 95 |
+
"""
|
| 96 |
+
We assume the dataset contains a column that contains prompts and other information
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
def __init__(
|
| 100 |
+
self,
|
| 101 |
+
data_path: str,
|
| 102 |
+
tokenizer: PreTrainedTokenizer,
|
| 103 |
+
processor: Optional[ProcessorMixin],
|
| 104 |
+
prompt_key: str = "prompt",
|
| 105 |
+
answer_key: str = "answer",
|
| 106 |
+
image_key: str = "images",
|
| 107 |
+
max_prompt_length: int = 1024,
|
| 108 |
+
truncation: str = "error",
|
| 109 |
+
format_prompt: Optional[str] = None,
|
| 110 |
+
max_pixels: Optional[int] = None,
|
| 111 |
+
min_pixels: Optional[int] = None,
|
| 112 |
+
filter_overlong_prompts: bool = False,
|
| 113 |
+
):
|
| 114 |
+
self.tokenizer = tokenizer
|
| 115 |
+
self.processor = processor
|
| 116 |
+
self.prompt_key = prompt_key
|
| 117 |
+
self.answer_key = answer_key
|
| 118 |
+
self.image_key = image_key
|
| 119 |
+
self.max_prompt_length = max_prompt_length
|
| 120 |
+
self.truncation = truncation
|
| 121 |
+
self.max_pixels = max_pixels
|
| 122 |
+
self.min_pixels = min_pixels
|
| 123 |
+
self.filter_overlong_prompts = filter_overlong_prompts
|
| 124 |
+
|
| 125 |
+
if "@" in data_path:
|
| 126 |
+
data_path, data_split = data_path.split("@")
|
| 127 |
+
else:
|
| 128 |
+
data_split = "train"
|
| 129 |
+
|
| 130 |
+
if os.path.isdir(data_path):
|
| 131 |
+
# when we use dataset builder, we should always refer to the train split
|
| 132 |
+
self.dataset = load_dataset("parquet", data_dir=data_path, split="train")
|
| 133 |
+
elif os.path.isfile(data_path):
|
| 134 |
+
self.dataset = load_dataset("parquet", data_files=data_path, split="train")
|
| 135 |
+
else:
|
| 136 |
+
# load remote dataset from huggingface hub
|
| 137 |
+
self.dataset = load_dataset(data_path, split=data_split)
|
| 138 |
+
|
| 139 |
+
self.format_prompt = None
|
| 140 |
+
if format_prompt:
|
| 141 |
+
with open(format_prompt, encoding="utf-8") as f:
|
| 142 |
+
self.format_prompt = f.read()
|
| 143 |
+
|
| 144 |
+
if self.filter_overlong_prompts:
|
| 145 |
+
self.dataset = self.dataset.filter(self._filter_overlong_prompts, desc="Filtering overlong prompts")
|
| 146 |
+
|
| 147 |
+
def _build_messages(self, example: Dict[str, Any]) -> List[Dict[str, Any]]:
|
| 148 |
+
prompt_str: str = example[self.prompt_key]
|
| 149 |
+
if self.format_prompt:
|
| 150 |
+
format_prompt = Template(self.format_prompt.strip())
|
| 151 |
+
prompt_str = format_prompt.render(content=prompt_str)
|
| 152 |
+
|
| 153 |
+
if self.image_key in example:
|
| 154 |
+
# https://huggingface.co/docs/transformers/en/tasks/image_text_to_text
|
| 155 |
+
content_list = []
|
| 156 |
+
for i, content in enumerate(prompt_str.split("<image>")):
|
| 157 |
+
if i != 0:
|
| 158 |
+
content_list.append({"type": "image"})
|
| 159 |
+
|
| 160 |
+
if content:
|
| 161 |
+
content_list.append({"type": "text", "text": content})
|
| 162 |
+
|
| 163 |
+
return [{"role": "user", "content": content_list}]
|
| 164 |
+
else:
|
| 165 |
+
return [{"role": "user", "content": prompt_str}]
|
| 166 |
+
|
| 167 |
+
def _filter_overlong_prompts(self, example: Dict[str, Any]) -> bool:
|
| 168 |
+
messages = self._build_messages(example)
|
| 169 |
+
processing_class = self.processor if self.processor is not None else self.tokenizer
|
| 170 |
+
return (
|
| 171 |
+
len(processing_class.apply_chat_template(messages, add_generation_prompt=True)) <= self.max_prompt_length
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
def __len__(self):
|
| 175 |
+
return len(self.dataset)
|
| 176 |
+
|
| 177 |
+
def __getitem__(self, index):
|
| 178 |
+
example: dict = self.dataset[index]
|
| 179 |
+
messages = self._build_messages(example)
|
| 180 |
+
|
| 181 |
+
if self.image_key in example:
|
| 182 |
+
prompt = self.processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
|
| 183 |
+
raw_image_data = example.pop(self.image_key)
|
| 184 |
+
if not isinstance(raw_image_data, (list, tuple)):
|
| 185 |
+
raw_image_data = [raw_image_data]
|
| 186 |
+
|
| 187 |
+
images = [
|
| 188 |
+
process_image(image, min_pixels=self.min_pixels, max_pixels=self.max_pixels)
|
| 189 |
+
for image in raw_image_data
|
| 190 |
+
]
|
| 191 |
+
model_inputs = self.processor(images, [prompt], add_special_tokens=False, return_tensors="pt")
|
| 192 |
+
input_ids = model_inputs.pop("input_ids")[0]
|
| 193 |
+
attention_mask = model_inputs.pop("attention_mask")[0]
|
| 194 |
+
example["multi_modal_data"] = {"image": raw_image_data}
|
| 195 |
+
else:
|
| 196 |
+
prompt = self.tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
|
| 197 |
+
model_inputs = self.tokenizer([prompt], add_special_tokens=False, return_tensors="pt")
|
| 198 |
+
input_ids = model_inputs.pop("input_ids")[0]
|
| 199 |
+
attention_mask = model_inputs.pop("attention_mask")[0]
|
| 200 |
+
|
| 201 |
+
if self.processor is not None and self.processor.image_processor.__class__.__name__ == "Qwen2VLImageProcessor":
|
| 202 |
+
# qwen2vl mrope
|
| 203 |
+
position_ids = get_rope_index(
|
| 204 |
+
self.processor,
|
| 205 |
+
input_ids=input_ids,
|
| 206 |
+
image_grid_thw=model_inputs.get("image_grid_thw"),
|
| 207 |
+
attention_mask=attention_mask,
|
| 208 |
+
) # (3, seq_length)
|
| 209 |
+
else:
|
| 210 |
+
position_ids = torch.clip(attention_mask.cumsum(dim=0) - 1, min=0, max=None) # (seq_length,)
|
| 211 |
+
|
| 212 |
+
input_ids, attention_mask, position_ids = VF.postprocess_data(
|
| 213 |
+
input_ids=input_ids,
|
| 214 |
+
attention_mask=attention_mask,
|
| 215 |
+
position_ids=position_ids,
|
| 216 |
+
max_length=self.max_prompt_length,
|
| 217 |
+
pad_token_id=self.tokenizer.pad_token_id,
|
| 218 |
+
left_pad=True,
|
| 219 |
+
truncation=self.truncation,
|
| 220 |
+
)
|
| 221 |
+
raw_prompt_ids = self.tokenizer.encode(prompt, add_special_tokens=False)
|
| 222 |
+
if len(raw_prompt_ids) > self.max_prompt_length:
|
| 223 |
+
if self.truncation == "left":
|
| 224 |
+
raw_prompt_ids = raw_prompt_ids[-self.max_prompt_length :]
|
| 225 |
+
elif self.truncation == "right":
|
| 226 |
+
raw_prompt_ids = raw_prompt_ids[: self.max_prompt_length]
|
| 227 |
+
elif self.truncation == "error":
|
| 228 |
+
raise RuntimeError(f"Prompt length {len(raw_prompt_ids)} is longer than {self.max_prompt_length}.")
|
| 229 |
+
|
| 230 |
+
example["input_ids"] = input_ids
|
| 231 |
+
example["attention_mask"] = attention_mask
|
| 232 |
+
example["position_ids"] = position_ids
|
| 233 |
+
example["raw_prompt_ids"] = raw_prompt_ids
|
| 234 |
+
example["ground_truth"] = example.pop(self.answer_key)
|
| 235 |
+
return example
|
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/flops_counter.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from typing import TYPE_CHECKING, List, Tuple
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from transformers.models.llama.configuration_llama import LlamaConfig
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
VALID_MODLE_TYPE = {"llama", "mllama", "qwen2", "qwen2_vl", "qwen2_5_vl", "qwen3"}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def get_device_flops(unit: str = "T") -> float:
|
| 28 |
+
def unit_convert(number: float, level: str):
|
| 29 |
+
units = ["B", "K", "M", "G", "T", "P"]
|
| 30 |
+
if number <= 0:
|
| 31 |
+
return number
|
| 32 |
+
|
| 33 |
+
ptr = 0
|
| 34 |
+
while ptr < len(units) and units[ptr] != level:
|
| 35 |
+
number /= 1000
|
| 36 |
+
ptr += 1
|
| 37 |
+
|
| 38 |
+
return number
|
| 39 |
+
|
| 40 |
+
device_name = torch.cuda.get_device_name()
|
| 41 |
+
flops = float("inf") # INF flops for unkown gpu type
|
| 42 |
+
if "H100" in device_name or "H800" in device_name:
|
| 43 |
+
flops = 989e12
|
| 44 |
+
elif "A100" in device_name or "A800" in device_name:
|
| 45 |
+
flops = 312e12
|
| 46 |
+
elif "L40" in device_name:
|
| 47 |
+
flops = 181.05e12
|
| 48 |
+
elif "L20" in device_name:
|
| 49 |
+
flops = 119.5e12
|
| 50 |
+
elif "H20" in device_name:
|
| 51 |
+
flops = 148e12
|
| 52 |
+
elif "910B" in device_name:
|
| 53 |
+
flops = 354e12
|
| 54 |
+
flops_unit = unit_convert(flops, unit)
|
| 55 |
+
return flops_unit
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class FlopsCounter:
|
| 59 |
+
"""
|
| 60 |
+
Used to count mfu during training loop
|
| 61 |
+
|
| 62 |
+
Example:
|
| 63 |
+
flops_counter = FlopsCounter(config)
|
| 64 |
+
flops_achieved, flops_promised = flops_counter.estimate_flops(tokens_list, delta_time)
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
def __init__(self, config: "LlamaConfig"):
|
| 68 |
+
if config.model_type not in VALID_MODLE_TYPE:
|
| 69 |
+
print(f"Only support {VALID_MODLE_TYPE}, but got {config.model_type}. MFU will always be zero.")
|
| 70 |
+
|
| 71 |
+
self.estimate_func = {
|
| 72 |
+
"mllama": self._estimate_mllama_flops,
|
| 73 |
+
"llama": self._estimate_llama_flops,
|
| 74 |
+
"qwen2": self._estimate_llama_flops,
|
| 75 |
+
"qwen2_vl": self._estimate_llama_flops,
|
| 76 |
+
"qwen2_5_vl": self._estimate_llama_flops,
|
| 77 |
+
}
|
| 78 |
+
self.config = config
|
| 79 |
+
|
| 80 |
+
def _estimate_unknown_flops(self, tokens_sum: int, batch_seqlens: List[int], delta_time: float) -> float:
|
| 81 |
+
return 0
|
| 82 |
+
|
| 83 |
+
def _estimate_llama_flops(self, tokens_sum: int, batch_seqlens: List[int], delta_time: float) -> float:
|
| 84 |
+
hidden_size = self.config.hidden_size
|
| 85 |
+
vocab_size = self.config.vocab_size
|
| 86 |
+
num_hidden_layers = self.config.num_hidden_layers
|
| 87 |
+
num_key_value_heads = self.config.num_key_value_heads
|
| 88 |
+
num_attention_heads = self.config.num_attention_heads
|
| 89 |
+
intermediate_size = self.config.intermediate_size
|
| 90 |
+
|
| 91 |
+
head_dim = hidden_size // num_attention_heads
|
| 92 |
+
q_size = num_attention_heads * head_dim
|
| 93 |
+
k_size = num_key_value_heads * head_dim
|
| 94 |
+
v_size = num_key_value_heads * head_dim
|
| 95 |
+
|
| 96 |
+
# non-attn per layer parm
|
| 97 |
+
# Qwen2/LLama use SwiGelu, gate, having up and down linear layer in mlp
|
| 98 |
+
mlp_N = hidden_size * intermediate_size * 3
|
| 99 |
+
attn_linear_N = hidden_size * (q_size + k_size + v_size + num_attention_heads * head_dim)
|
| 100 |
+
emd_and_lm_head_N = vocab_size * hidden_size * 2
|
| 101 |
+
# non-attn all_layer parm
|
| 102 |
+
dense_N = (mlp_N + attn_linear_N) * num_hidden_layers + emd_and_lm_head_N
|
| 103 |
+
# non-attn all_layer & all_token fwd & bwd flops
|
| 104 |
+
dense_N_flops = 6 * dense_N * tokens_sum
|
| 105 |
+
|
| 106 |
+
# attn all_layer & all_token fwd & bwd flops
|
| 107 |
+
seqlen_square_sum = 0
|
| 108 |
+
for seqlen in batch_seqlens:
|
| 109 |
+
seqlen_square_sum += seqlen * seqlen
|
| 110 |
+
|
| 111 |
+
attn_qkv_flops = 12 * seqlen_square_sum * head_dim * num_attention_heads * num_hidden_layers
|
| 112 |
+
|
| 113 |
+
# all_layer & all_token fwd & bwd flops
|
| 114 |
+
flops_all_token = dense_N_flops + attn_qkv_flops
|
| 115 |
+
flops_achieved = flops_all_token * (1.0 / delta_time) / 1e12
|
| 116 |
+
return flops_achieved
|
| 117 |
+
|
| 118 |
+
def _estimate_mllama_flops(self, tokens_sum: int, batch_seqlens: List[int], delta_time: float) -> float:
|
| 119 |
+
|
| 120 |
+
return 0
|
| 121 |
+
|
| 122 |
+
def estimate_flops(self, batch_seqlens: List[int], delta_time: float) -> Tuple[float, float]:
|
| 123 |
+
"""
|
| 124 |
+
Estimate the FLOPS based on the number of valid tokens in the current batch and the time taken.
|
| 125 |
+
|
| 126 |
+
Args:
|
| 127 |
+
batch_seqlens (List[int]): A list where each element represents the number of valid tokens in the current batch.
|
| 128 |
+
delta_time (float): The time taken to process the batch, in seconds.
|
| 129 |
+
|
| 130 |
+
Returns:
|
| 131 |
+
estimated_flops (float): The estimated FLOPS based on the input tokens and time.
|
| 132 |
+
promised_flops (float): The expected FLOPS of the current device.
|
| 133 |
+
"""
|
| 134 |
+
tokens_sum = sum(batch_seqlens)
|
| 135 |
+
func = self.estimate_func.get(self.config.model_type, self._estimate_unknown_flops)
|
| 136 |
+
estimated_flops = func(tokens_sum, batch_seqlens, delta_time)
|
| 137 |
+
promised_flops = get_device_flops()
|
| 138 |
+
return estimated_flops, promised_flops
|
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/fsdp_utils.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 gc
|
| 16 |
+
from collections import defaultdict
|
| 17 |
+
from functools import partial
|
| 18 |
+
from typing import Callable, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch import nn
|
| 22 |
+
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
|
| 23 |
+
from torch.distributed.fsdp._runtime_utils import _lazy_init
|
| 24 |
+
from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy
|
| 25 |
+
from torch.optim import Optimizer
|
| 26 |
+
from transformers import PreTrainedModel
|
| 27 |
+
from transformers.trainer_pt_utils import get_module_class_from_name
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def get_init_fn(model: nn.Module, device: Union[str, torch.device]) -> Callable[[nn.Module], None]:
|
| 31 |
+
param_occurrence = defaultdict(int)
|
| 32 |
+
for _, param in model.named_parameters(remove_duplicate=False):
|
| 33 |
+
param_occurrence[param] += 1
|
| 34 |
+
|
| 35 |
+
duplicated_params = {param for param in param_occurrence.keys() if param_occurrence[param] > 1}
|
| 36 |
+
materialized_params = {}
|
| 37 |
+
|
| 38 |
+
def init_fn(module: nn.Module):
|
| 39 |
+
for name, param in module.named_parameters(recurse=False):
|
| 40 |
+
if param in duplicated_params:
|
| 41 |
+
module._parameters[name] = materialized_params.setdefault(
|
| 42 |
+
param, nn.Parameter(torch.empty_like(param.data, device=device), requires_grad=param.requires_grad)
|
| 43 |
+
)
|
| 44 |
+
else:
|
| 45 |
+
module._parameters[name] = nn.Parameter(
|
| 46 |
+
torch.empty_like(param.data, device=device), requires_grad=param.requires_grad
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
return init_fn
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def get_fsdp_wrap_policy(model: PreTrainedModel):
|
| 53 |
+
"""Get FSDP wrap policy for the model.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
module: The module to get wrap policy for
|
| 57 |
+
"""
|
| 58 |
+
transformer_cls_to_wrap = set()
|
| 59 |
+
for module in model._no_split_modules:
|
| 60 |
+
transformer_cls = get_module_class_from_name(model, module)
|
| 61 |
+
if transformer_cls is None:
|
| 62 |
+
raise Exception(f"Cannot find {module} in pretrained model.")
|
| 63 |
+
else:
|
| 64 |
+
transformer_cls_to_wrap.add(transformer_cls)
|
| 65 |
+
|
| 66 |
+
return partial(transformer_auto_wrap_policy, transformer_layer_cls=transformer_cls_to_wrap)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@torch.no_grad()
|
| 70 |
+
def offload_fsdp_model(model: FSDP, empty_cache: bool = True):
|
| 71 |
+
# lazy init FSDP model
|
| 72 |
+
_lazy_init(model, model)
|
| 73 |
+
assert model._is_root, "Only support root model offloading to CPU"
|
| 74 |
+
for handle in model._all_handles:
|
| 75 |
+
if handle._offload_params:
|
| 76 |
+
continue
|
| 77 |
+
|
| 78 |
+
flat_param = handle.flat_param
|
| 79 |
+
assert (
|
| 80 |
+
flat_param.data.data_ptr() == flat_param._local_shard.data_ptr()
|
| 81 |
+
and id(flat_param.data) != id(flat_param._local_shard)
|
| 82 |
+
and flat_param.data.size() == flat_param._local_shard.size()
|
| 83 |
+
)
|
| 84 |
+
handle.flat_param_to("cpu", non_blocking=True)
|
| 85 |
+
# the following still keeps id(._local_shard) != id(.data)
|
| 86 |
+
flat_param._local_shard = flat_param.data
|
| 87 |
+
assert id(flat_param._local_shard) != id(flat_param.data)
|
| 88 |
+
|
| 89 |
+
if empty_cache:
|
| 90 |
+
torch.cuda.empty_cache()
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@torch.no_grad()
|
| 94 |
+
def load_fsdp_model(model: FSDP, empty_cache: bool = True):
|
| 95 |
+
# lazy init FSDP model
|
| 96 |
+
_lazy_init(model, model)
|
| 97 |
+
assert model._is_root, "Only support root model loading to GPU"
|
| 98 |
+
for handle in model._all_handles:
|
| 99 |
+
if handle._offload_params:
|
| 100 |
+
continue
|
| 101 |
+
|
| 102 |
+
flat_param = handle.flat_param
|
| 103 |
+
handle.flat_param_to("cuda", non_blocking=True)
|
| 104 |
+
# the following still keeps id(._local_shard) != id(.data)
|
| 105 |
+
flat_param._local_shard = flat_param.data
|
| 106 |
+
|
| 107 |
+
if empty_cache:
|
| 108 |
+
gc.collect()
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
@torch.no_grad()
|
| 112 |
+
def offload_fsdp_optimizer(optimizer: Optimizer, empty_cache: bool = True):
|
| 113 |
+
if not optimizer.state:
|
| 114 |
+
return
|
| 115 |
+
|
| 116 |
+
for param_group in optimizer.param_groups:
|
| 117 |
+
for param in param_group["params"]:
|
| 118 |
+
state = optimizer.state[param]
|
| 119 |
+
for key, value in state.items():
|
| 120 |
+
if isinstance(value, torch.Tensor):
|
| 121 |
+
state[key] = value.to("cpu", non_blocking=True)
|
| 122 |
+
|
| 123 |
+
if empty_cache:
|
| 124 |
+
torch.cuda.empty_cache()
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@torch.no_grad()
|
| 128 |
+
def load_fsdp_optimizer(optimizer: Optimizer, empty_cache: bool = True):
|
| 129 |
+
if not optimizer.state:
|
| 130 |
+
return
|
| 131 |
+
|
| 132 |
+
for param_group in optimizer.param_groups:
|
| 133 |
+
for param in param_group["params"]:
|
| 134 |
+
state = optimizer.state[param]
|
| 135 |
+
for key, value in state.items():
|
| 136 |
+
if isinstance(value, torch.Tensor):
|
| 137 |
+
state[key] = value.to("cuda", non_blocking=True)
|
| 138 |
+
|
| 139 |
+
if empty_cache:
|
| 140 |
+
gc.collect()
|
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/logger/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 16 |
+
from .logger import Tracker
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
__all__ = ["Tracker"]
|
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/logger/logger.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
A unified tracking interface that supports logging data to different backend
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
from abc import ABC, abstractmethod
|
| 20 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
|
| 24 |
+
from ..py_functional import convert_dict_to_str, flatten_dict, is_package_available, unflatten_dict
|
| 25 |
+
from .gen_logger import AggregateGenerationsLogger
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if is_package_available("mlflow"):
|
| 29 |
+
import mlflow # type: ignore
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
if is_package_available("tensorboard"):
|
| 33 |
+
from torch.utils.tensorboard import SummaryWriter
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if is_package_available("wandb"):
|
| 37 |
+
import wandb # type: ignore
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
if is_package_available("swanlab"):
|
| 41 |
+
import swanlab # type: ignore
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class Logger(ABC):
|
| 45 |
+
@abstractmethod
|
| 46 |
+
def __init__(self, config: Dict[str, Any]) -> None: ...
|
| 47 |
+
|
| 48 |
+
@abstractmethod
|
| 49 |
+
def log(self, data: Dict[str, Any], step: int) -> None: ...
|
| 50 |
+
|
| 51 |
+
def finish(self) -> None:
|
| 52 |
+
pass
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class ConsoleLogger(Logger):
|
| 56 |
+
def __init__(self, config: Dict[str, Any]) -> None:
|
| 57 |
+
print("Config\n" + convert_dict_to_str(config))
|
| 58 |
+
|
| 59 |
+
def log(self, data: Dict[str, Any], step: int) -> None:
|
| 60 |
+
print(f"Step {step}\n" + convert_dict_to_str(unflatten_dict(data)))
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class MlflowLogger(Logger):
|
| 64 |
+
def __init__(self, config: Dict[str, Any]) -> None:
|
| 65 |
+
mlflow.start_run(run_name=config["trainer"]["experiment_name"])
|
| 66 |
+
mlflow.log_params(flatten_dict(config))
|
| 67 |
+
|
| 68 |
+
def log(self, data: Dict[str, Any], step: int) -> None:
|
| 69 |
+
mlflow.log_metrics(metrics=data, step=step)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class SwanlabLogger(Logger):
|
| 73 |
+
def __init__(self, config: Dict[str, Any]) -> None:
|
| 74 |
+
swanlab_key = os.getenv("SWANLAB_API_KEY")
|
| 75 |
+
swanlab_dir = os.getenv("SWANLAB_DIR", "swanlab_log")
|
| 76 |
+
swanlab_mode = os.getenv("SWANLAB_MODE", "cloud")
|
| 77 |
+
if swanlab_key:
|
| 78 |
+
swanlab.login(swanlab_key)
|
| 79 |
+
|
| 80 |
+
swanlab.init(
|
| 81 |
+
project=config["trainer"]["project_name"],
|
| 82 |
+
experiment_name=config["trainer"]["experiment_name"],
|
| 83 |
+
config={"UPPERFRAMEWORK": "EasyR1", "FRAMEWORK": "veRL", **config},
|
| 84 |
+
logdir=swanlab_dir,
|
| 85 |
+
mode=swanlab_mode,
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
def log(self, data: Dict[str, Any], step: int) -> None:
|
| 89 |
+
swanlab.log(data=data, step=step)
|
| 90 |
+
|
| 91 |
+
def finish(self) -> None:
|
| 92 |
+
swanlab.finish()
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class TensorBoardLogger(Logger):
|
| 96 |
+
def __init__(self, config: Dict[str, Any]) -> None:
|
| 97 |
+
tensorboard_dir = os.getenv("TENSORBOARD_DIR", "tensorboard_log")
|
| 98 |
+
os.makedirs(tensorboard_dir, exist_ok=True)
|
| 99 |
+
print(f"Saving tensorboard log to {tensorboard_dir}.")
|
| 100 |
+
self.writer = SummaryWriter(tensorboard_dir)
|
| 101 |
+
config_dict = {}
|
| 102 |
+
for key, value in flatten_dict(config).items():
|
| 103 |
+
if isinstance(value, (int, float, str, bool, torch.Tensor)):
|
| 104 |
+
config_dict[key] = value
|
| 105 |
+
else:
|
| 106 |
+
config_dict[key] = str(value)
|
| 107 |
+
|
| 108 |
+
self.writer.add_hparams(hparam_dict=config_dict, metric_dict={"placeholder": 0})
|
| 109 |
+
|
| 110 |
+
def log(self, data: Dict[str, Any], step: int) -> None:
|
| 111 |
+
for key, value in data.items():
|
| 112 |
+
self.writer.add_scalar(key, value, step)
|
| 113 |
+
|
| 114 |
+
def finish(self):
|
| 115 |
+
self.writer.close()
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class WandbLogger(Logger):
|
| 119 |
+
def __init__(self, config: Dict[str, Any]) -> None:
|
| 120 |
+
wandb.init(
|
| 121 |
+
project=config["trainer"]["project_name"],
|
| 122 |
+
name=config["trainer"]["experiment_name"],
|
| 123 |
+
config=config,
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
def log(self, data: Dict[str, Any], step: int) -> None:
|
| 127 |
+
wandb.log(data=data, step=step)
|
| 128 |
+
|
| 129 |
+
def finish(self) -> None:
|
| 130 |
+
wandb.finish()
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
LOGGERS = {
|
| 134 |
+
"console": ConsoleLogger,
|
| 135 |
+
"mlflow": MlflowLogger,
|
| 136 |
+
"swanlab": SwanlabLogger,
|
| 137 |
+
"tensorboard": TensorBoardLogger,
|
| 138 |
+
"wandb": WandbLogger,
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class Tracker:
|
| 143 |
+
def __init__(self, loggers: Union[str, List[str]] = "console", config: Optional[Dict[str, Any]] = None):
|
| 144 |
+
if isinstance(loggers, str):
|
| 145 |
+
loggers = [loggers]
|
| 146 |
+
|
| 147 |
+
self.loggers: List[Logger] = []
|
| 148 |
+
for logger in loggers:
|
| 149 |
+
if logger not in LOGGERS:
|
| 150 |
+
raise ValueError(f"{logger} is not supported.")
|
| 151 |
+
|
| 152 |
+
self.loggers.append(LOGGERS[logger](config))
|
| 153 |
+
|
| 154 |
+
self.gen_logger = AggregateGenerationsLogger(loggers)
|
| 155 |
+
|
| 156 |
+
def log(self, data: Dict[str, Any], step: int) -> None:
|
| 157 |
+
for logger in self.loggers:
|
| 158 |
+
logger.log(data=data, step=step)
|
| 159 |
+
|
| 160 |
+
def log_generation(self, samples: List[Tuple[str, str, str, float]], step: int) -> None:
|
| 161 |
+
self.gen_logger.log(samples, step)
|
| 162 |
+
|
| 163 |
+
def __del__(self):
|
| 164 |
+
for logger in self.loggers:
|
| 165 |
+
logger.finish()
|
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/model_utils.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
Utilities to create common models
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from functools import lru_cache
|
| 19 |
+
from typing import Optional, Tuple
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.distributed as dist
|
| 23 |
+
from torch import nn
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@lru_cache
|
| 27 |
+
def is_rank0() -> int:
|
| 28 |
+
return (not dist.is_initialized()) or (dist.get_rank() == 0)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def print_gpu_memory_usage(prefix: str = "GPU memory usage") -> None:
|
| 32 |
+
"""Report the current GPU VRAM usage."""
|
| 33 |
+
if is_rank0():
|
| 34 |
+
free_mem, total_mem = torch.cuda.mem_get_info()
|
| 35 |
+
print(f"{prefix}: {(total_mem - free_mem) / (1024**3):.2f} GB / {total_mem / (1024**3):.2f} GB.")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _get_model_size(model: nn.Module, scale: str = "auto") -> Tuple[float, str]:
|
| 39 |
+
"""Compute the model size."""
|
| 40 |
+
n_params = sum(p.numel() for p in model.parameters())
|
| 41 |
+
|
| 42 |
+
if scale == "auto":
|
| 43 |
+
if n_params > 1e9:
|
| 44 |
+
scale = "B"
|
| 45 |
+
elif n_params > 1e6:
|
| 46 |
+
scale = "M"
|
| 47 |
+
elif n_params > 1e3:
|
| 48 |
+
scale = "K"
|
| 49 |
+
else:
|
| 50 |
+
scale = ""
|
| 51 |
+
|
| 52 |
+
if scale == "B":
|
| 53 |
+
n_params = n_params / 1e9
|
| 54 |
+
elif scale == "M":
|
| 55 |
+
n_params = n_params / 1e6
|
| 56 |
+
elif scale == "K":
|
| 57 |
+
n_params = n_params / 1e3
|
| 58 |
+
elif scale == "":
|
| 59 |
+
pass
|
| 60 |
+
else:
|
| 61 |
+
raise NotImplementedError(f"Unknown scale {scale}.")
|
| 62 |
+
|
| 63 |
+
return n_params, scale
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def print_model_size(model: nn.Module, name: Optional[str] = None) -> None:
|
| 67 |
+
"""Print the model size."""
|
| 68 |
+
if is_rank0():
|
| 69 |
+
n_params, scale = _get_model_size(model, scale="auto")
|
| 70 |
+
if name is None:
|
| 71 |
+
name = model.__class__.__name__
|
| 72 |
+
|
| 73 |
+
print(f"{name} contains {n_params:.2f}{scale} parameters.")
|
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/py_functional.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
Contain small python utility functions
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import importlib.util
|
| 19 |
+
import re
|
| 20 |
+
from contextlib import contextmanager
|
| 21 |
+
from functools import lru_cache
|
| 22 |
+
from typing import Any, Dict, List, Union
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
import yaml
|
| 26 |
+
from codetiming import Timer
|
| 27 |
+
from yaml import Dumper
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def is_sci_notation(number: float) -> bool:
|
| 31 |
+
pattern = re.compile(r"^[+-]?\d+(\.\d*)?[eE][+-]?\d+$")
|
| 32 |
+
return bool(pattern.match(str(number)))
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def float_representer(dumper: Dumper, number: Union[float, np.float32, np.float64]):
|
| 36 |
+
if is_sci_notation(number):
|
| 37 |
+
value = str(number)
|
| 38 |
+
if "." not in value and "e" in value:
|
| 39 |
+
value = value.replace("e", ".0e", 1)
|
| 40 |
+
else:
|
| 41 |
+
value = str(round(number, 3))
|
| 42 |
+
|
| 43 |
+
return dumper.represent_scalar("tag:yaml.org,2002:float", value)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
yaml.add_representer(float, float_representer)
|
| 47 |
+
yaml.add_representer(np.float32, float_representer)
|
| 48 |
+
yaml.add_representer(np.float64, float_representer)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@lru_cache
|
| 52 |
+
def is_package_available(name: str) -> bool:
|
| 53 |
+
return importlib.util.find_spec(name) is not None
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def union_two_dict(dict1: Dict[str, Any], dict2: Dict[str, Any]) -> Dict[str, Any]:
|
| 57 |
+
"""Union two dict. Will throw an error if there is an item not the same object with the same key."""
|
| 58 |
+
for key in dict2.keys():
|
| 59 |
+
if key in dict1:
|
| 60 |
+
assert dict1[key] == dict2[key], f"{key} in dict1 and dict2 are not the same object"
|
| 61 |
+
|
| 62 |
+
dict1[key] = dict2[key]
|
| 63 |
+
|
| 64 |
+
return dict1
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def append_to_dict(data: Dict[str, List[Any]], new_data: Dict[str, Any]) -> None:
|
| 68 |
+
"""Append dict to a dict of list."""
|
| 69 |
+
for key, val in new_data.items():
|
| 70 |
+
if key not in data:
|
| 71 |
+
data[key] = []
|
| 72 |
+
|
| 73 |
+
data[key].append(val)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def unflatten_dict(data: Dict[str, Any], sep: str = "/") -> Dict[str, Any]:
|
| 77 |
+
unflattened = {}
|
| 78 |
+
for key, value in data.items():
|
| 79 |
+
pieces = key.split(sep)
|
| 80 |
+
pointer = unflattened
|
| 81 |
+
for piece in pieces[:-1]:
|
| 82 |
+
if piece not in pointer:
|
| 83 |
+
pointer[piece] = {}
|
| 84 |
+
|
| 85 |
+
pointer = pointer[piece]
|
| 86 |
+
|
| 87 |
+
pointer[pieces[-1]] = value
|
| 88 |
+
|
| 89 |
+
return unflattened
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def flatten_dict(data: Dict[str, Any], parent_key: str = "", sep: str = "/") -> Dict[str, Any]:
|
| 93 |
+
flattened = {}
|
| 94 |
+
for key, value in data.items():
|
| 95 |
+
new_key = parent_key + sep + key if parent_key else key
|
| 96 |
+
if isinstance(value, dict):
|
| 97 |
+
flattened.update(flatten_dict(value, new_key, sep=sep))
|
| 98 |
+
else:
|
| 99 |
+
flattened[new_key] = value
|
| 100 |
+
|
| 101 |
+
return flattened
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def convert_dict_to_str(data: Dict[str, Any]) -> str:
|
| 105 |
+
return yaml.dump(data, indent=2)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@contextmanager
|
| 109 |
+
def timer(name: str, timing_raw: Dict[str, float]):
|
| 110 |
+
with Timer(name=name, logger=None) as timer:
|
| 111 |
+
yield
|
| 112 |
+
|
| 113 |
+
timing_raw[name] = timer.last
|
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/seqlen_balancing.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 copy
|
| 16 |
+
import heapq
|
| 17 |
+
from typing import List, Tuple
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
from tensordict import TensorDict
|
| 21 |
+
from torch import distributed as dist
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class Set:
|
| 25 |
+
def __init__(self) -> None:
|
| 26 |
+
self.sum = 0
|
| 27 |
+
self.items = []
|
| 28 |
+
|
| 29 |
+
def add(self, idx: int, val: int):
|
| 30 |
+
self.items.append((idx, val))
|
| 31 |
+
self.sum += val
|
| 32 |
+
|
| 33 |
+
def merge(self, other):
|
| 34 |
+
for idx, val in other.items:
|
| 35 |
+
self.items.append((idx, val))
|
| 36 |
+
self.sum += val
|
| 37 |
+
|
| 38 |
+
def __lt__(self, other):
|
| 39 |
+
if self.sum != other.sum:
|
| 40 |
+
return self.sum < other.sum
|
| 41 |
+
if len(self.items) != len(other.items):
|
| 42 |
+
return len(self.items) < len(other.items)
|
| 43 |
+
return self.items < other.items
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class State:
|
| 47 |
+
def __init__(self, items: List[Tuple[int, int]], k: int) -> None:
|
| 48 |
+
self.k = k
|
| 49 |
+
# sets should always be decreasing order
|
| 50 |
+
self.sets = [Set() for _ in range(k)]
|
| 51 |
+
assert len(items) in [1, k], f"{len(items)} not in [1, {k}]"
|
| 52 |
+
for i, (idx, seqlen) in enumerate(items):
|
| 53 |
+
self.sets[i].add(idx=idx, val=seqlen)
|
| 54 |
+
self.sets = sorted(self.sets, reverse=True)
|
| 55 |
+
|
| 56 |
+
def get_partitions(self):
|
| 57 |
+
partitions = []
|
| 58 |
+
for i in range(len(self.sets)):
|
| 59 |
+
cur_partition = []
|
| 60 |
+
for idx, _ in self.sets[i].items:
|
| 61 |
+
cur_partition.append(idx)
|
| 62 |
+
partitions.append(cur_partition)
|
| 63 |
+
return partitions
|
| 64 |
+
|
| 65 |
+
def merge(self, other):
|
| 66 |
+
for i in range(self.k):
|
| 67 |
+
self.sets[i].merge(other.sets[self.k - 1 - i])
|
| 68 |
+
self.sets = sorted(self.sets, reverse=True)
|
| 69 |
+
|
| 70 |
+
@property
|
| 71 |
+
def spread(self) -> int:
|
| 72 |
+
return self.sets[0].sum - self.sets[-1].sum
|
| 73 |
+
|
| 74 |
+
def __lt__(self, other):
|
| 75 |
+
# least heap, let the state with largest spread to be popped first,
|
| 76 |
+
# if the spread is the same, let the state who has the largest set
|
| 77 |
+
# to be popped first.
|
| 78 |
+
if self.spread != other.spread:
|
| 79 |
+
return self.spread > other.spread
|
| 80 |
+
return self.sets[0] > other.sets[0]
|
| 81 |
+
|
| 82 |
+
def __repr__(self) -> str:
|
| 83 |
+
repr_str = "["
|
| 84 |
+
for i in range(self.k):
|
| 85 |
+
if i > 0:
|
| 86 |
+
repr_str += ","
|
| 87 |
+
repr_str += "{"
|
| 88 |
+
for j, (_, seqlen) in enumerate(self.sets[i].items):
|
| 89 |
+
if j > 0:
|
| 90 |
+
repr_str += ","
|
| 91 |
+
repr_str += str(seqlen)
|
| 92 |
+
repr_str += "}"
|
| 93 |
+
repr_str += "]"
|
| 94 |
+
return repr_str
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def karmarkar_karp(seqlen_list: List[int], k_partitions: int, equal_size: bool):
|
| 98 |
+
# see: https://en.wikipedia.org/wiki/Largest_differencing_method
|
| 99 |
+
sorted_seqlen_list = sorted([(seqlen, i) for i, seqlen in enumerate(seqlen_list)])
|
| 100 |
+
states_pq: List[State] = []
|
| 101 |
+
if equal_size:
|
| 102 |
+
assert len(seqlen_list) % k_partitions == 0, f"{len(seqlen_list)} % {k_partitions} != 0"
|
| 103 |
+
for offset in range(0, len(sorted_seqlen_list), k_partitions):
|
| 104 |
+
items = []
|
| 105 |
+
for i in range(k_partitions):
|
| 106 |
+
seqlen, idx = sorted_seqlen_list[offset + i]
|
| 107 |
+
items.append((idx, seqlen))
|
| 108 |
+
heapq.heappush(states_pq, State(items=items, k=k_partitions))
|
| 109 |
+
else:
|
| 110 |
+
for seqlen, idx in sorted_seqlen_list:
|
| 111 |
+
heapq.heappush(states_pq, State(items=[(idx, seqlen)], k=k_partitions))
|
| 112 |
+
|
| 113 |
+
while len(states_pq) > 1:
|
| 114 |
+
state0 = heapq.heappop(states_pq)
|
| 115 |
+
state1 = heapq.heappop(states_pq)
|
| 116 |
+
# merge states
|
| 117 |
+
state0.merge(state1)
|
| 118 |
+
heapq.heappush(states_pq, state0)
|
| 119 |
+
|
| 120 |
+
final_state = states_pq[0]
|
| 121 |
+
partitions = final_state.get_partitions()
|
| 122 |
+
if equal_size:
|
| 123 |
+
for i, partition in enumerate(partitions):
|
| 124 |
+
assert len(partition) * k_partitions == len(seqlen_list), (
|
| 125 |
+
f"{len(partition)} * {k_partitions} != {len(seqlen_list)}"
|
| 126 |
+
)
|
| 127 |
+
return partitions
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def greedy_partition(seqlen_list: List[int], k_partitions: int, equal_size: bool):
|
| 131 |
+
bias = sum(seqlen_list) + 1 if equal_size else 0
|
| 132 |
+
sorted_seqlen = [(seqlen + bias, i) for i, seqlen in enumerate(seqlen_list)]
|
| 133 |
+
partitions = [[] for _ in range(k_partitions)]
|
| 134 |
+
partition_sums = [0 for _ in range(k_partitions)]
|
| 135 |
+
for seqlen, i in sorted_seqlen:
|
| 136 |
+
min_idx = None
|
| 137 |
+
for j in range(k_partitions):
|
| 138 |
+
if min_idx is None or partition_sums[j] < partition_sums[min_idx]:
|
| 139 |
+
min_idx = j
|
| 140 |
+
partitions[min_idx].append(i)
|
| 141 |
+
partition_sums[min_idx] += seqlen
|
| 142 |
+
if equal_size:
|
| 143 |
+
for i, partition in enumerate(partitions):
|
| 144 |
+
assert len(partition) * k_partitions == len(seqlen_list), (
|
| 145 |
+
f"{len(partition)} * {k_partitions} != {len(seqlen_list)}"
|
| 146 |
+
)
|
| 147 |
+
return partitions
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def get_seqlen_balanced_partitions(seqlen_list: List[int], k_partitions: int, equal_size: bool):
|
| 151 |
+
"""get order of seq lengths to make partitions balanced, this is
|
| 152 |
+
used in balacing sum of seqlength across dp ranks and microbatches
|
| 153 |
+
Parameters:
|
| 154 |
+
seqlen_list (List[int]):
|
| 155 |
+
seq lengths of each items
|
| 156 |
+
k_partitions (int):
|
| 157 |
+
resulting number of partitions
|
| 158 |
+
equal_size (bool):
|
| 159 |
+
if True, number of items in each partitions must be equal.
|
| 160 |
+
if False, only consider balancing the sum, each partition can have
|
| 161 |
+
variable number of items
|
| 162 |
+
Returns:
|
| 163 |
+
partitions (List[List[int]]):
|
| 164 |
+
return k_partitions list containing the index of items.
|
| 165 |
+
"""
|
| 166 |
+
assert len(seqlen_list) >= k_partitions, f"number of items:[{len(seqlen_list)}] < k_partitions:[{k_partitions}]"
|
| 167 |
+
|
| 168 |
+
def _check_and_sort_partitions(partitions):
|
| 169 |
+
assert len(partitions) == k_partitions, f"{len(partitions)} != {k_partitions}"
|
| 170 |
+
seen_idx = set()
|
| 171 |
+
sorted_partitions = [None] * k_partitions
|
| 172 |
+
for i, partition in enumerate(partitions):
|
| 173 |
+
assert len(partition) > 0, f"the {i}-th partition is empty"
|
| 174 |
+
for idx in partition:
|
| 175 |
+
seen_idx.add(idx)
|
| 176 |
+
sorted_partitions[i] = sorted(partition)
|
| 177 |
+
assert seen_idx == set(range(len(seqlen_list)))
|
| 178 |
+
return sorted_partitions
|
| 179 |
+
|
| 180 |
+
partitions = karmarkar_karp(seqlen_list=seqlen_list, k_partitions=k_partitions, equal_size=equal_size)
|
| 181 |
+
return _check_and_sort_partitions(partitions)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def log_seqlen_unbalance(seqlen_list: List[int], partitions: List[List[int]], prefix):
|
| 185 |
+
# add some metrics of seqlen sum on dp ranks
|
| 186 |
+
k_partition = len(partitions)
|
| 187 |
+
# assert len(seqlen_list) % k_partition == 0
|
| 188 |
+
batch_size = len(seqlen_list) // k_partition
|
| 189 |
+
min_sum_seqlen = None
|
| 190 |
+
max_sum_seqlen = None
|
| 191 |
+
total_sum_seqlen = 0
|
| 192 |
+
for offset in range(0, len(seqlen_list), batch_size):
|
| 193 |
+
cur_sum_seqlen = sum(seqlen_list[offset : offset + batch_size])
|
| 194 |
+
if min_sum_seqlen is None or cur_sum_seqlen < min_sum_seqlen:
|
| 195 |
+
min_sum_seqlen = cur_sum_seqlen
|
| 196 |
+
if max_sum_seqlen is None or cur_sum_seqlen > max_sum_seqlen:
|
| 197 |
+
max_sum_seqlen = cur_sum_seqlen
|
| 198 |
+
total_sum_seqlen += cur_sum_seqlen
|
| 199 |
+
|
| 200 |
+
balanced_sum_seqlen_list = []
|
| 201 |
+
for partition in partitions:
|
| 202 |
+
cur_sum_seqlen_balanced = sum([seqlen_list[i] for i in partition])
|
| 203 |
+
balanced_sum_seqlen_list.append(cur_sum_seqlen_balanced)
|
| 204 |
+
# print("balanced_sum_seqlen_list: ", balanced_sum_seqlen_list)
|
| 205 |
+
min_sum_seqlen_balanced = min(balanced_sum_seqlen_list)
|
| 206 |
+
max_sum_seqlen_balanced = max(balanced_sum_seqlen_list)
|
| 207 |
+
|
| 208 |
+
return {
|
| 209 |
+
f"{prefix}/min": min_sum_seqlen,
|
| 210 |
+
f"{prefix}/max": max_sum_seqlen,
|
| 211 |
+
f"{prefix}/minmax_diff": max_sum_seqlen - min_sum_seqlen,
|
| 212 |
+
f"{prefix}/balanced_min": min_sum_seqlen_balanced,
|
| 213 |
+
f"{prefix}/balanced_max": max_sum_seqlen_balanced,
|
| 214 |
+
f"{prefix}/mean": total_sum_seqlen / len(partitions),
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def ceildiv(a, b):
|
| 219 |
+
return -(a // -b)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def rearrange_micro_batches(batch: TensorDict, max_token_len, dp_group=None):
|
| 223 |
+
"""Split the batch into a list of micro_batches, where the max_token_len is smaller than max_token_len
|
| 224 |
+
and the number of valid tokens in each micro batch is well balanced.
|
| 225 |
+
"""
|
| 226 |
+
# this is per local micro_bsz
|
| 227 |
+
max_seq_len = batch["attention_mask"].shape[-1]
|
| 228 |
+
assert max_token_len >= max_seq_len, (
|
| 229 |
+
f"max_token_len must be greater than the sequence length. Got {max_token_len=} and {max_seq_len=}"
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
seq_len_effective: torch.Tensor = batch["attention_mask"].sum(dim=1)
|
| 233 |
+
total_seqlen = seq_len_effective.sum().item()
|
| 234 |
+
num_micro_batches = ceildiv(total_seqlen, max_token_len)
|
| 235 |
+
if dist.is_initialized():
|
| 236 |
+
num_micro_batches = torch.tensor([num_micro_batches], device="cuda")
|
| 237 |
+
dist.all_reduce(num_micro_batches, op=dist.ReduceOp.MAX, group=dp_group)
|
| 238 |
+
num_micro_batches = num_micro_batches.cpu().item()
|
| 239 |
+
|
| 240 |
+
seq_len_effective = seq_len_effective.tolist()
|
| 241 |
+
assert num_micro_batches <= len(seq_len_effective)
|
| 242 |
+
|
| 243 |
+
micro_bsz_idx = get_seqlen_balanced_partitions(seq_len_effective, num_micro_batches, equal_size=False)
|
| 244 |
+
|
| 245 |
+
micro_batches = []
|
| 246 |
+
|
| 247 |
+
for partition in micro_bsz_idx:
|
| 248 |
+
curr_micro_batch = []
|
| 249 |
+
for idx in partition:
|
| 250 |
+
curr_micro_batch.append(batch[idx : idx + 1])
|
| 251 |
+
curr_micro_batch = torch.cat(curr_micro_batch)
|
| 252 |
+
|
| 253 |
+
micro_batches.append(curr_micro_batch)
|
| 254 |
+
|
| 255 |
+
return micro_batches, micro_bsz_idx
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def get_reverse_idx(idx_map):
|
| 259 |
+
reverse_idx_map = copy.deepcopy(idx_map)
|
| 260 |
+
|
| 261 |
+
for i, idx in enumerate(idx_map):
|
| 262 |
+
reverse_idx_map[idx] = i
|
| 263 |
+
|
| 264 |
+
return reverse_idx_map
|
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/tokenizer.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Utils for tokenization."""
|
| 15 |
+
|
| 16 |
+
from typing import Optional
|
| 17 |
+
|
| 18 |
+
from transformers import AutoProcessor, AutoTokenizer, PreTrainedTokenizer, ProcessorMixin
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def get_tokenizer(model_path: str, override_chat_template: Optional[str] = None, **kwargs) -> PreTrainedTokenizer:
|
| 22 |
+
"""Create a huggingface pretrained tokenizer."""
|
| 23 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path, **kwargs)
|
| 24 |
+
if override_chat_template is not None:
|
| 25 |
+
tokenizer.chat_template = override_chat_template
|
| 26 |
+
|
| 27 |
+
if tokenizer.bos_token == "<bos>" and tokenizer.eos_token == "<eos>":
|
| 28 |
+
# the EOS token in gemma2 & gemma3 is ambiguious, which may worsen RL performance.
|
| 29 |
+
# https://huggingface.co/google/gemma-2-2b-it/commit/17a01657f5c87135bcdd0ec7abb4b2dece04408a
|
| 30 |
+
print("Found gemma model. Set eos_token and eos_token_id to <end_of_turn> and 107.")
|
| 31 |
+
tokenizer.eos_token = "<end_of_turn>"
|
| 32 |
+
|
| 33 |
+
if tokenizer.pad_token_id is None:
|
| 34 |
+
print("Pad token is None. Set it to eos_token.")
|
| 35 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 36 |
+
|
| 37 |
+
return tokenizer
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def get_processor(model_path: str, override_chat_template: Optional[str] = None, **kwargs) -> Optional[ProcessorMixin]:
|
| 41 |
+
"""Create a huggingface pretrained processor."""
|
| 42 |
+
processor = AutoProcessor.from_pretrained(model_path, **kwargs)
|
| 43 |
+
if override_chat_template is not None:
|
| 44 |
+
processor.chat_template = override_chat_template
|
| 45 |
+
|
| 46 |
+
# Avoid load tokenizer, see:
|
| 47 |
+
# https://github.com/huggingface/transformers/blob/v4.49.0/src/transformers/models/auto/processing_auto.py#L344
|
| 48 |
+
if processor is not None and "Processor" not in processor.__class__.__name__:
|
| 49 |
+
processor = None
|
| 50 |
+
|
| 51 |
+
return processor
|
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/torch_dtypes.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 torch
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
HALF_LIST = ["fp16", "float16"]
|
| 19 |
+
FLOAT_LIST = ["fp32", "float32"]
|
| 20 |
+
BFLOAT_LIST = ["bf16", "bfloat16"]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class PrecisionType:
|
| 24 |
+
"""Type of precision used."""
|
| 25 |
+
|
| 26 |
+
@staticmethod
|
| 27 |
+
def is_fp16(precision: str) -> bool:
|
| 28 |
+
return precision in HALF_LIST
|
| 29 |
+
|
| 30 |
+
@staticmethod
|
| 31 |
+
def is_fp32(precision: str) -> bool:
|
| 32 |
+
return precision in FLOAT_LIST
|
| 33 |
+
|
| 34 |
+
@staticmethod
|
| 35 |
+
def is_bf16(precision: str) -> bool:
|
| 36 |
+
return precision in BFLOAT_LIST
|
| 37 |
+
|
| 38 |
+
@staticmethod
|
| 39 |
+
def to_dtype(precision: str) -> torch.dtype:
|
| 40 |
+
if precision in HALF_LIST:
|
| 41 |
+
return torch.float16
|
| 42 |
+
elif precision in FLOAT_LIST:
|
| 43 |
+
return torch.float32
|
| 44 |
+
elif precision in BFLOAT_LIST:
|
| 45 |
+
return torch.bfloat16
|
| 46 |
+
else:
|
| 47 |
+
raise RuntimeError(f"Unexpected precision: {precision}")
|
| 48 |
+
|
| 49 |
+
@staticmethod
|
| 50 |
+
def to_str(precision: torch.dtype) -> str:
|
| 51 |
+
if precision == torch.float16:
|
| 52 |
+
return "float16"
|
| 53 |
+
elif precision == torch.float32:
|
| 54 |
+
return "float32"
|
| 55 |
+
elif precision == torch.bfloat16:
|
| 56 |
+
return "bfloat16"
|
| 57 |
+
else:
|
| 58 |
+
raise RuntimeError(f"Unexpected precision: {precision}")
|
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/torch_functional.py
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
# Copyright Meta Platforms, Inc. and affiliates
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Contain small torch utilities
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from typing import List, Literal, Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.distributed
|
| 23 |
+
import torch.nn.functional as F
|
| 24 |
+
from torch.optim.lr_scheduler import LambdaLR
|
| 25 |
+
|
| 26 |
+
from .torch_dtypes import PrecisionType
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
from flash_attn.ops.triton.cross_entropy import cross_entropy_loss
|
| 31 |
+
|
| 32 |
+
FLAH_ATTN_CROSS_ENTROPY_LOSS_AVAILABLE = True
|
| 33 |
+
except ImportError:
|
| 34 |
+
FLAH_ATTN_CROSS_ENTROPY_LOSS_AVAILABLE = False
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@torch.compiler.disable()
|
| 38 |
+
def log_probs_from_logits_flash_attn(logits: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
|
| 39 |
+
output = cross_entropy_loss(logits, labels, inplace_backward=True)
|
| 40 |
+
if not isinstance(output, tuple):
|
| 41 |
+
raise ValueError(
|
| 42 |
+
"please make sure flash-attn>=2.4.3 where cross_entropy_loss returns Tuple[losses, z_losses]."
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
return -output[0]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def log_probs_from_logits(logits: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
|
| 49 |
+
"""Compute log probs on the label ids given logits.
|
| 50 |
+
|
| 51 |
+
We may use torch compile to speed up computing.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
logits (torch.Tensor): logits of the model, shape (batch_size, seqlen, vocab_size)
|
| 55 |
+
labels (torch.Tensor): labels of the model, shape (batch_size, seqlen)
|
| 56 |
+
|
| 57 |
+
Returns:
|
| 58 |
+
torch.Tensor: log probs of the labels, shape (batch_size, seqlen)
|
| 59 |
+
"""
|
| 60 |
+
batch_dim = logits.shape[:-1]
|
| 61 |
+
vocab_dim = logits.shape[-1]
|
| 62 |
+
logits = logits.contiguous().view(-1, vocab_dim)
|
| 63 |
+
labels = labels.contiguous().view(-1)
|
| 64 |
+
if FLAH_ATTN_CROSS_ENTROPY_LOSS_AVAILABLE:
|
| 65 |
+
output = log_probs_from_logits_flash_attn(logits, labels)
|
| 66 |
+
else: # fall back to torch kernel, upcast logits to fp32
|
| 67 |
+
output = F.cross_entropy(logits.float(), labels, reduction="none")
|
| 68 |
+
|
| 69 |
+
return output.view(*batch_dim)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def masked_mean(values: torch.Tensor, mask: torch.Tensor, dim: int = None, eps: float = 1e-8) -> torch.Tensor:
|
| 73 |
+
"""Compute mean of tensor with a masked values."""
|
| 74 |
+
return (values * mask).sum(dim=dim) / (mask.sum(dim=dim) + eps)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def masked_var(values: torch.Tensor, mask: torch.Tensor, unbiased: bool = True) -> torch.Tensor:
|
| 78 |
+
"""Compute variance of tensor with masked values."""
|
| 79 |
+
mean = masked_mean(values, mask)
|
| 80 |
+
centered_values = values - mean
|
| 81 |
+
variance = masked_mean(centered_values**2, mask)
|
| 82 |
+
if unbiased:
|
| 83 |
+
mask_sum = mask.sum()
|
| 84 |
+
if mask_sum <= 1:
|
| 85 |
+
print("The sum of the mask is less than one, which can cause a division by zero.")
|
| 86 |
+
return variance
|
| 87 |
+
|
| 88 |
+
bessel_correction = mask_sum / (mask_sum - 1)
|
| 89 |
+
variance = variance * bessel_correction
|
| 90 |
+
|
| 91 |
+
return variance
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def masked_whiten(values: torch.Tensor, mask: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
|
| 95 |
+
"""Whiten values with masked values."""
|
| 96 |
+
mean, var = masked_mean(values, mask), masked_var(values, mask)
|
| 97 |
+
return (values - mean) * torch.rsqrt(var + eps)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def get_response_mask(
|
| 101 |
+
response_ids: torch.Tensor, eos_token_id: Union[int, List[int]] = 2, dtype: torch.dtype = torch.long
|
| 102 |
+
):
|
| 103 |
+
"""Get the mask for the response ids, the mask will be 0 after the first eos token.
|
| 104 |
+
|
| 105 |
+
eos_token_id can be int or list: 1 or [1, 2].
|
| 106 |
+
```
|
| 107 |
+
e.g. eos_token = 1
|
| 108 |
+
response_ids: [0, 0, 2, 4, 3, 5, 1, 0, 0]
|
| 109 |
+
response_mask: [1, 1, 1, 1, 1, 1, 1, 0, 0]
|
| 110 |
+
```
|
| 111 |
+
"""
|
| 112 |
+
if isinstance(eos_token_id, int):
|
| 113 |
+
eos_token_id = [eos_token_id]
|
| 114 |
+
|
| 115 |
+
response_mask = torch.zeros_like(response_ids, dtype=torch.bool)
|
| 116 |
+
for token_id in eos_token_id:
|
| 117 |
+
response_mask |= response_ids.eq(token_id)
|
| 118 |
+
|
| 119 |
+
response_mask = response_mask.long()
|
| 120 |
+
response_mask = (torch.cumsum(response_mask, dim=1) - response_mask).bool()
|
| 121 |
+
response_mask = torch.logical_not(response_mask).to(dtype)
|
| 122 |
+
return response_mask
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def pad_2d_list_to_length(
|
| 126 |
+
response: List[List[int]], pad_token_id: int, max_length: Optional[int] = None
|
| 127 |
+
) -> torch.Tensor:
|
| 128 |
+
"""Pad a 2D list (e.g. responses, log_probs) to a 2D tensor."""
|
| 129 |
+
max_response_length = max(len(sub_list) for sub_list in response)
|
| 130 |
+
if max_length is not None and max_length > max_response_length:
|
| 131 |
+
target_length = max_length
|
| 132 |
+
else:
|
| 133 |
+
target_length = max_response_length
|
| 134 |
+
|
| 135 |
+
padded_response = [tuple(sub_list) + (pad_token_id,) * (target_length - len(sub_list)) for sub_list in response]
|
| 136 |
+
tensor = torch.tensor(padded_response)
|
| 137 |
+
return tensor
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def pad_sequence_to_length(
|
| 141 |
+
tensor: torch.Tensor, max_seq_len: int, pad_token_id: int, left_pad: bool = False
|
| 142 |
+
) -> torch.Tensor:
|
| 143 |
+
"""Pad a nD tensors in the last dim to max_seq_len."""
|
| 144 |
+
if tensor.size(-1) >= max_seq_len:
|
| 145 |
+
return tensor
|
| 146 |
+
|
| 147 |
+
pad_shape = list(tensor.shape)
|
| 148 |
+
pad_shape[-1] = max_seq_len - tensor.size(-1)
|
| 149 |
+
pad_tensor = torch.full(pad_shape, fill_value=pad_token_id, dtype=tensor.dtype, device=tensor.device)
|
| 150 |
+
return torch.cat((pad_tensor, tensor), dim=-1) if left_pad else torch.cat((tensor, pad_tensor), dim=-1)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def postprocess_data(
|
| 154 |
+
input_ids: torch.Tensor,
|
| 155 |
+
attention_mask: torch.Tensor,
|
| 156 |
+
position_ids: torch.Tensor,
|
| 157 |
+
max_length: int,
|
| 158 |
+
pad_token_id: int,
|
| 159 |
+
left_pad: bool = True,
|
| 160 |
+
truncation: Literal["left", "right", "error"] = "error",
|
| 161 |
+
):
|
| 162 |
+
"""Pad or truncate data."""
|
| 163 |
+
assert truncation in ["left", "right", "error"]
|
| 164 |
+
seq_length = len(input_ids)
|
| 165 |
+
if seq_length < max_length:
|
| 166 |
+
input_ids = pad_sequence_to_length(
|
| 167 |
+
input_ids, max_seq_len=max_length, pad_token_id=pad_token_id, left_pad=left_pad
|
| 168 |
+
)
|
| 169 |
+
attention_mask = pad_sequence_to_length(
|
| 170 |
+
attention_mask, max_seq_len=max_length, pad_token_id=0, left_pad=left_pad
|
| 171 |
+
)
|
| 172 |
+
position_ids = pad_sequence_to_length(position_ids, max_seq_len=max_length, pad_token_id=0, left_pad=left_pad)
|
| 173 |
+
elif seq_length > max_length:
|
| 174 |
+
if truncation == "left": # actually, left truncation may not be reasonable
|
| 175 |
+
input_ids = input_ids[..., -max_length:]
|
| 176 |
+
attention_mask = attention_mask[..., -max_length:]
|
| 177 |
+
position_ids = position_ids[..., -max_length:]
|
| 178 |
+
elif truncation == "right":
|
| 179 |
+
input_ids = input_ids[..., :max_length]
|
| 180 |
+
attention_mask = attention_mask[..., :max_length]
|
| 181 |
+
position_ids = position_ids[..., :max_length]
|
| 182 |
+
elif truncation == "error":
|
| 183 |
+
raise RuntimeError(f"Input sequence length {seq_length} is longer than max length {max_length}.")
|
| 184 |
+
else:
|
| 185 |
+
raise NotImplementedError(f"Unknown truncation method {truncation}.")
|
| 186 |
+
|
| 187 |
+
return input_ids, attention_mask, position_ids
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def get_constant_schedule_with_warmup(
|
| 191 |
+
optimizer: torch.optim.Optimizer,
|
| 192 |
+
num_warmup_steps: int,
|
| 193 |
+
last_epoch: int = -1,
|
| 194 |
+
) -> torch.optim.lr_scheduler.LRScheduler:
|
| 195 |
+
"""Get the lr scheduler for constant lr."""
|
| 196 |
+
|
| 197 |
+
def lr_lambda(current_step: int) -> float:
|
| 198 |
+
return min(1.0, float(current_step) / float(max(1, num_warmup_steps)))
|
| 199 |
+
|
| 200 |
+
return LambdaLR(optimizer, lr_lambda, last_epoch)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
# https://github.com/meta-llama/llama-cookbook/blob/v0.0.5/src/llama_cookbook/policies/anyprecision_optimizer.py
|
| 204 |
+
class AnyPrecisionAdamW(torch.optim.Optimizer):
|
| 205 |
+
def __init__(
|
| 206 |
+
self,
|
| 207 |
+
params: List[torch.Tensor],
|
| 208 |
+
lr: float = 1e-3,
|
| 209 |
+
betas: Tuple[float, float] = (0.9, 0.999),
|
| 210 |
+
eps: float = 1e-8,
|
| 211 |
+
weight_decay: float = 0.0,
|
| 212 |
+
use_kahan_summation: bool = True,
|
| 213 |
+
momentum_dtype: str = "bfloat16",
|
| 214 |
+
variance_dtype: str = "bfloat16",
|
| 215 |
+
compensation_buffer_dtype: str = "bfloat16",
|
| 216 |
+
):
|
| 217 |
+
"""
|
| 218 |
+
AnyPrecisionAdamW: a flexible precision AdamW optimizer
|
| 219 |
+
with optional Kahan summation for high precision weight updates.
|
| 220 |
+
Allows direct control over momentum, variance and auxiliary compensation buffer dtypes.
|
| 221 |
+
Optional Kahan summation is used to offset precision reduction for the weight updates.
|
| 222 |
+
This allows full training in BFloat16 (equal or better than FP32 results in many cases)
|
| 223 |
+
due to high precision weight updates.
|
| 224 |
+
|
| 225 |
+
Args:
|
| 226 |
+
params (iterable): iterable of parameters to optimize or dicts defining parameter groups
|
| 227 |
+
lr (float, optional): learning rate (default: 1e-3)
|
| 228 |
+
betas (Tuple[float, float], optional): coefficients used for computing
|
| 229 |
+
running averages of gradient and its square (default: (0.9, 0.999))
|
| 230 |
+
eps (float, optional): term added to the denominator to improve numerical stability (default: 1e-8)
|
| 231 |
+
weight_decay (float, optional): weight decay coefficient (default: 1e-2)
|
| 232 |
+
|
| 233 |
+
# Any Precision specific
|
| 234 |
+
use_kahan_summation = creates auxiliary buffer to ensure high precision
|
| 235 |
+
model param updates (default: False)
|
| 236 |
+
momentum_dtype = dtype for momentum (default: bfloat16)
|
| 237 |
+
variance_dtype = dtype for uncentered variance (default: bfloat16)
|
| 238 |
+
compensation_buffer_dtype = dtype for Kahan summation buffer (default: bfloat16)
|
| 239 |
+
|
| 240 |
+
# Usage
|
| 241 |
+
This optimizer implements optimizer states, and Kahan summation
|
| 242 |
+
for high precision updates, all in user controlled dtypes.
|
| 243 |
+
Defaults are variance in BF16, Momentum in FP32.
|
| 244 |
+
This can be run in FSDP mixed precision, amp, or full precision,
|
| 245 |
+
depending on what training pipeline you wish to work with.
|
| 246 |
+
|
| 247 |
+
Setting to use_kahan_summation = False, and changing momentum and
|
| 248 |
+
variance dtypes to FP32, reverts this to a standard AdamW optimizer.
|
| 249 |
+
|
| 250 |
+
"""
|
| 251 |
+
defaults = {
|
| 252 |
+
"lr": lr,
|
| 253 |
+
"betas": betas,
|
| 254 |
+
"eps": eps,
|
| 255 |
+
"weight_decay": weight_decay,
|
| 256 |
+
"use_kahan_summation": use_kahan_summation,
|
| 257 |
+
"momentum_dtype": momentum_dtype,
|
| 258 |
+
"variance_dtype": variance_dtype,
|
| 259 |
+
"compensation_buffer_dtype": compensation_buffer_dtype,
|
| 260 |
+
}
|
| 261 |
+
super().__init__(params, defaults)
|
| 262 |
+
|
| 263 |
+
@torch.no_grad()
|
| 264 |
+
def step(self, closure=None):
|
| 265 |
+
"""
|
| 266 |
+
Performs a single optimization step.
|
| 267 |
+
|
| 268 |
+
Args:
|
| 269 |
+
closure (callable, optional): A closure that reevaluates the model and returns the loss.
|
| 270 |
+
"""
|
| 271 |
+
|
| 272 |
+
if closure is not None:
|
| 273 |
+
with torch.enable_grad():
|
| 274 |
+
closure()
|
| 275 |
+
|
| 276 |
+
for group in self.param_groups:
|
| 277 |
+
beta1, beta2 = group["betas"]
|
| 278 |
+
lr = group["lr"]
|
| 279 |
+
weight_decay = group["weight_decay"]
|
| 280 |
+
eps = group["eps"]
|
| 281 |
+
use_kahan_summation = group["use_kahan_summation"]
|
| 282 |
+
|
| 283 |
+
momentum_dtype = PrecisionType.to_dtype(group["momentum_dtype"])
|
| 284 |
+
variance_dtype = PrecisionType.to_dtype(group["variance_dtype"])
|
| 285 |
+
compensation_buffer_dtype = PrecisionType.to_dtype(group["compensation_buffer_dtype"])
|
| 286 |
+
for p in group["params"]:
|
| 287 |
+
assert isinstance(p, torch.Tensor) # lint
|
| 288 |
+
if p.grad is None:
|
| 289 |
+
continue
|
| 290 |
+
|
| 291 |
+
if p.grad.is_sparse:
|
| 292 |
+
raise RuntimeError("AnyPrecisionAdamW does not support sparse gradients.")
|
| 293 |
+
|
| 294 |
+
state = self.state[p]
|
| 295 |
+
# State initialization
|
| 296 |
+
if len(state) == 0:
|
| 297 |
+
state["step"] = torch.tensor(0.0)
|
| 298 |
+
|
| 299 |
+
# momentum - EMA of gradient values
|
| 300 |
+
state["exp_avg"] = torch.zeros_like(p, dtype=momentum_dtype)
|
| 301 |
+
|
| 302 |
+
# variance uncentered - EMA of squared gradient values
|
| 303 |
+
state["exp_avg_sq"] = torch.zeros_like(p, dtype=variance_dtype)
|
| 304 |
+
|
| 305 |
+
# optional Kahan summation - accumulated error tracker
|
| 306 |
+
if use_kahan_summation:
|
| 307 |
+
state["compensation"] = torch.zeros_like(p, dtype=compensation_buffer_dtype)
|
| 308 |
+
|
| 309 |
+
# Main processing
|
| 310 |
+
# update the steps for each param group update
|
| 311 |
+
state["step"] += 1
|
| 312 |
+
step = state["step"]
|
| 313 |
+
|
| 314 |
+
exp_avg = state["exp_avg"]
|
| 315 |
+
exp_avg_sq = state["exp_avg_sq"]
|
| 316 |
+
grad = p.grad
|
| 317 |
+
|
| 318 |
+
if weight_decay: # weight decay, AdamW style
|
| 319 |
+
p.data.mul_(1 - lr * weight_decay)
|
| 320 |
+
|
| 321 |
+
exp_avg.mul_(beta1).add_(grad, alpha=1 - beta1) # update momentum
|
| 322 |
+
exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2) # update uncentered variance
|
| 323 |
+
|
| 324 |
+
bias_correction1 = 1 - beta1**step # adjust using bias1
|
| 325 |
+
step_size = lr / bias_correction1
|
| 326 |
+
|
| 327 |
+
denom_correction = (1 - beta2**step) ** 0.5 # adjust using bias2 and avoids math import
|
| 328 |
+
centered_variance = (exp_avg_sq.sqrt() / denom_correction).add_(eps, alpha=1)
|
| 329 |
+
|
| 330 |
+
if use_kahan_summation: # lr update to compensation
|
| 331 |
+
compensation = state["compensation"]
|
| 332 |
+
compensation.addcdiv_(exp_avg, centered_variance, value=-step_size)
|
| 333 |
+
|
| 334 |
+
# update weights with compensation (Kahan summation)
|
| 335 |
+
# save error back to compensation for next iteration
|
| 336 |
+
temp_buffer = p.detach().clone()
|
| 337 |
+
p.data.add_(compensation)
|
| 338 |
+
compensation.add_(temp_buffer.sub_(p.data))
|
| 339 |
+
else: # usual AdamW updates
|
| 340 |
+
p.data.addcdiv_(exp_avg, centered_variance, value=-step_size)
|
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/verl/utils/ulysses.py
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
Utilities for DeepSpeed Ulysses Sequence Parallelism.
|
| 16 |
+
DeepSpeed Ulysses Paper: https://arxiv.org/abs/2309.14509
|
| 17 |
+
Inspired from: https://github.com/microsoft/DeepSpeed/blob/master/deepspeed/sequence/layer.py
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from typing import Any, Optional, Tuple
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
import torch.distributed as dist
|
| 24 |
+
from torch import Tensor
|
| 25 |
+
from torch.distributed import ProcessGroup
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
_ULYSSES_SEQUENCE_PARALLEL_GROUP = None
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def set_ulysses_sequence_parallel_group(group: dist.ProcessGroup):
|
| 32 |
+
"""
|
| 33 |
+
Set ulysses sequence parallel process group.
|
| 34 |
+
"""
|
| 35 |
+
global _ULYSSES_SEQUENCE_PARALLEL_GROUP
|
| 36 |
+
_ULYSSES_SEQUENCE_PARALLEL_GROUP = group
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def get_ulysses_sequence_parallel_group() -> Optional[dist.ProcessGroup]:
|
| 40 |
+
"""
|
| 41 |
+
Get ulysses sequence parallel process group.
|
| 42 |
+
"""
|
| 43 |
+
global _ULYSSES_SEQUENCE_PARALLEL_GROUP
|
| 44 |
+
return _ULYSSES_SEQUENCE_PARALLEL_GROUP
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def get_ulysses_sequence_parallel_world_size(group: ProcessGroup = None) -> int:
|
| 48 |
+
"""
|
| 49 |
+
Get ulysses sequence parallel world size.
|
| 50 |
+
"""
|
| 51 |
+
group = get_ulysses_sequence_parallel_group() if group is None else group
|
| 52 |
+
return dist.get_world_size(group) if group else 1
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def get_ulysses_sequence_parallel_rank(group: ProcessGroup = None) -> int:
|
| 56 |
+
"""
|
| 57 |
+
Get ulysses sequence parallel rank.
|
| 58 |
+
"""
|
| 59 |
+
group = get_ulysses_sequence_parallel_group() if group is None else group
|
| 60 |
+
return dist.get_rank(group) if group else 0
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def gather_seq_scatter_heads(
|
| 64 |
+
x: Tensor,
|
| 65 |
+
seq_dim: int,
|
| 66 |
+
head_dim: int,
|
| 67 |
+
unpadded_dim_size: int = 0,
|
| 68 |
+
group: ProcessGroup = None,
|
| 69 |
+
) -> Tensor:
|
| 70 |
+
"""
|
| 71 |
+
A func to sync embedding input with alltoall in sequence parallel
|
| 72 |
+
gather sequence dimension and scatter head dim:
|
| 73 |
+
e.g. seq_dim: 1, head_dim: 2
|
| 74 |
+
[bsz, seq/n, h, ...] -> [bsz, seq, h/n, ...]
|
| 75 |
+
"""
|
| 76 |
+
group = get_ulysses_sequence_parallel_group() if group is None else group
|
| 77 |
+
if not group:
|
| 78 |
+
return x
|
| 79 |
+
sp_world = get_ulysses_sequence_parallel_world_size(group)
|
| 80 |
+
x = SeqAllToAll.apply(group, x, head_dim, seq_dim)
|
| 81 |
+
if unpadded_dim_size and unpadded_dim_size % sp_world != 0:
|
| 82 |
+
padding_size = x.size(seq_dim) - unpadded_dim_size
|
| 83 |
+
x = _unpad_tensor(x, seq_dim, padding_size)
|
| 84 |
+
return x
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def gather_heads_scatter_seq(x: Tensor, head_dim: int, seq_dim: int, group: ProcessGroup = None) -> Tensor:
|
| 88 |
+
"""
|
| 89 |
+
A func to sync attention result with alltoall in sequence parallel
|
| 90 |
+
gather head dimension and scatter seq dim:
|
| 91 |
+
e.g. seq_dim: 1, head_dim: 2
|
| 92 |
+
[bsz, seq, h/n, ...] -> [bsz, seq/n, h, ...]
|
| 93 |
+
"""
|
| 94 |
+
group = get_ulysses_sequence_parallel_group() if group is None else group
|
| 95 |
+
if not group:
|
| 96 |
+
return x
|
| 97 |
+
dim_size = x.size(seq_dim)
|
| 98 |
+
sp_world = get_ulysses_sequence_parallel_world_size(group)
|
| 99 |
+
if dim_size % sp_world != 0:
|
| 100 |
+
padding_size = sp_world - (dim_size % sp_world)
|
| 101 |
+
x = _pad_tensor(x, seq_dim, padding_size)
|
| 102 |
+
return SeqAllToAll.apply(group, x, seq_dim, head_dim, False)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _pad_tensor(x: Tensor, dim: int, padding_size: int) -> Tensor:
|
| 106 |
+
shape = list(x.shape)
|
| 107 |
+
shape[dim] = padding_size
|
| 108 |
+
pad = torch.zeros(shape, dtype=x.dtype, device=x.device)
|
| 109 |
+
return torch.cat([x, pad], dim=dim)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def _unpad_tensor(x: Tensor, dim: int, padding_size: int) -> Tensor:
|
| 113 |
+
slc = [slice(None)] * len(x.shape)
|
| 114 |
+
slc[dim] = slice(0, -padding_size)
|
| 115 |
+
return x[slc]
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def slice_input_tensor(x: Tensor, dim: int, padding: bool = True, group: ProcessGroup = None) -> Tensor:
|
| 119 |
+
group = get_ulysses_sequence_parallel_group() if group is None else group
|
| 120 |
+
sp_world_size = dist.get_world_size(group)
|
| 121 |
+
sp_rank = get_ulysses_sequence_parallel_rank()
|
| 122 |
+
dim_size = x.size(dim)
|
| 123 |
+
# pad before slice
|
| 124 |
+
if padding and dim_size % sp_world_size:
|
| 125 |
+
padding_size = sp_world_size - (dim_size % sp_world_size)
|
| 126 |
+
x = _pad_tensor(x, dim, padding_size)
|
| 127 |
+
# slice the input tensor
|
| 128 |
+
parts = x.size(dim) // sp_world_size
|
| 129 |
+
slc = [slice(None)] * len(x.shape)
|
| 130 |
+
slc[dim] = slice(sp_rank * parts, (sp_rank + 1) * parts)
|
| 131 |
+
return x[slc].contiguous()
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def all_to_all_tensor(
|
| 135 |
+
local_input: Tensor,
|
| 136 |
+
scatter_dim: int,
|
| 137 |
+
gather_dim: int,
|
| 138 |
+
group: Optional[dist.ProcessGroup] = None,
|
| 139 |
+
async_op: bool = False,
|
| 140 |
+
):
|
| 141 |
+
group = get_ulysses_sequence_parallel_group() if group is None else group
|
| 142 |
+
seq_world_size = dist.get_world_size(group)
|
| 143 |
+
input_list = [t.contiguous() for t in torch.tensor_split(local_input, seq_world_size, scatter_dim)]
|
| 144 |
+
output_list = [torch.empty_like(input_list[0]) for _ in range(seq_world_size)]
|
| 145 |
+
comm = dist.all_to_all(output_list, input_list, group=group, async_op=async_op)
|
| 146 |
+
if async_op:
|
| 147 |
+
|
| 148 |
+
def wait():
|
| 149 |
+
comm.wait()
|
| 150 |
+
return torch.cat(output_list, dim=gather_dim).contiguous()
|
| 151 |
+
|
| 152 |
+
return wait
|
| 153 |
+
return torch.cat(output_list, dim=gather_dim).contiguous()
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def all_gather_tensor(local_tensor: Tensor, group: Optional[dist.ProcessGroup] = None, async_op: bool = False):
|
| 157 |
+
group = get_ulysses_sequence_parallel_group() if group is None else group
|
| 158 |
+
sp_world_size = dist.get_world_size(group=group)
|
| 159 |
+
output_shape = list(local_tensor.shape)
|
| 160 |
+
output_shape[0] = output_shape[0] * sp_world_size
|
| 161 |
+
output = torch.empty(output_shape, dtype=local_tensor.dtype, device=local_tensor.device)
|
| 162 |
+
dist.all_gather_into_tensor(output, local_tensor, group=group, async_op=async_op)
|
| 163 |
+
return output
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class SeqAllToAll(torch.autograd.Function):
|
| 167 |
+
@staticmethod
|
| 168 |
+
def forward(
|
| 169 |
+
ctx: Any,
|
| 170 |
+
group: dist.ProcessGroup,
|
| 171 |
+
local_input: Tensor,
|
| 172 |
+
scatter_dim: int,
|
| 173 |
+
gather_dim: int,
|
| 174 |
+
async_op: bool = False,
|
| 175 |
+
) -> Tensor:
|
| 176 |
+
ctx.group = group
|
| 177 |
+
ctx.scatter_dim = scatter_dim
|
| 178 |
+
ctx.gather_dim = gather_dim
|
| 179 |
+
ctx.async_op = async_op
|
| 180 |
+
return all_to_all_tensor(local_input, scatter_dim, gather_dim, group, async_op)
|
| 181 |
+
|
| 182 |
+
@staticmethod
|
| 183 |
+
def backward(ctx: Any, *grad_output: Tensor) -> Tuple[None, Tensor, None, None]:
|
| 184 |
+
if ctx.async_op:
|
| 185 |
+
input_t = torch.cat(grad_output[1:], dim=ctx.gather_dim).contiguous()
|
| 186 |
+
else:
|
| 187 |
+
input_t = grad_output[0]
|
| 188 |
+
return (
|
| 189 |
+
None,
|
| 190 |
+
all_to_all_tensor(input_t, ctx.gather_dim, ctx.scatter_dim, ctx.group, False),
|
| 191 |
+
None,
|
| 192 |
+
None,
|
| 193 |
+
None,
|
| 194 |
+
None,
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class Gather(torch.autograd.Function):
|
| 199 |
+
@staticmethod
|
| 200 |
+
def forward(
|
| 201 |
+
ctx: Any,
|
| 202 |
+
group: dist.ProcessGroup,
|
| 203 |
+
local_tensor: Tensor,
|
| 204 |
+
gather_dim: int,
|
| 205 |
+
grad_scaler: bool = True,
|
| 206 |
+
async_op=False,
|
| 207 |
+
) -> Tensor:
|
| 208 |
+
ctx.group = group
|
| 209 |
+
ctx.gather_dim = gather_dim
|
| 210 |
+
ctx.grad_scaler = grad_scaler
|
| 211 |
+
ctx.async_op = async_op
|
| 212 |
+
|
| 213 |
+
sp_world_size = dist.get_world_size(group=group)
|
| 214 |
+
ctx.sp_world_size = sp_world_size
|
| 215 |
+
|
| 216 |
+
sp_rank = dist.get_rank(group=group)
|
| 217 |
+
ctx.sp_rank = sp_rank
|
| 218 |
+
|
| 219 |
+
local_shape = list(local_tensor.size())
|
| 220 |
+
split_size = local_shape[0]
|
| 221 |
+
part_size = local_shape[gather_dim] # store original size
|
| 222 |
+
ctx.part_size = part_size
|
| 223 |
+
|
| 224 |
+
output = all_gather_tensor(local_tensor, group, async_op)
|
| 225 |
+
return torch.cat(output.split(split_size, dim=0), dim=gather_dim)
|
| 226 |
+
|
| 227 |
+
@staticmethod
|
| 228 |
+
def backward(ctx: Any, grad_output: Tensor) -> Any:
|
| 229 |
+
if ctx.grad_scaler:
|
| 230 |
+
grad_output = grad_output * ctx.sp_world_size
|
| 231 |
+
return (
|
| 232 |
+
None,
|
| 233 |
+
grad_output.split(ctx.part_size, dim=ctx.gather_dim)[ctx.sp_rank].contiguous(),
|
| 234 |
+
None,
|
| 235 |
+
None,
|
| 236 |
+
None,
|
| 237 |
+
None,
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def gather_outputs_and_unpad(
|
| 242 |
+
x: Tensor,
|
| 243 |
+
gather_dim: int,
|
| 244 |
+
unpad_dim: int = None,
|
| 245 |
+
padding_size: int = 0,
|
| 246 |
+
grad_scaler: bool = True,
|
| 247 |
+
group: Optional[dist.ProcessGroup] = None,
|
| 248 |
+
):
|
| 249 |
+
group = get_ulysses_sequence_parallel_group() if group is None else group
|
| 250 |
+
# sp_size = get_ulysses_sequence_parallel_world_size()
|
| 251 |
+
if group is None:
|
| 252 |
+
return x
|
| 253 |
+
x = Gather.apply(group, x, gather_dim, grad_scaler)
|
| 254 |
+
if unpad_dim is not None:
|
| 255 |
+
assert isinstance(padding_size, int), "padding size is not given or is not an integer"
|
| 256 |
+
if padding_size == 0:
|
| 257 |
+
return x
|
| 258 |
+
x = _unpad_tensor(x, unpad_dim, padding_size)
|
| 259 |
+
return x
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def ulysses_pad_and_slice_inputs(
|
| 263 |
+
input_ids_rmpad: torch.Tensor, position_ids_rmpad: Optional[torch.Tensor] = None, sp_size: int = 1
|
| 264 |
+
):
|
| 265 |
+
"""
|
| 266 |
+
Pad and slice input_ids to be divisible by sp_size
|
| 267 |
+
Pad position_ids to be divisible by sp_size.
|
| 268 |
+
|
| 269 |
+
Note both input_ids_rmpad and position_ids_rmpad will be padded,
|
| 270 |
+
but only input_ids will be sliced.
|
| 271 |
+
|
| 272 |
+
The is the utility of pre-forward for ulysses sequence parallelism
|
| 273 |
+
|
| 274 |
+
Args:
|
| 275 |
+
input_ids_rmpad: shape of [bsz, seqlen]
|
| 276 |
+
position_ids_rmpad: shape of [bsz, seqlen], where bsz must be 1
|
| 277 |
+
sp_size (int): ulysses sequence parallelism size
|
| 278 |
+
|
| 279 |
+
Returns:
|
| 280 |
+
torch.Tensor: padded and sliced input_ids
|
| 281 |
+
torch.Tensor: padded and sliced position_ids
|
| 282 |
+
int: pad size
|
| 283 |
+
"""
|
| 284 |
+
if position_ids_rmpad is not None:
|
| 285 |
+
assert position_ids_rmpad.size(0) == 1
|
| 286 |
+
assert input_ids_rmpad.size(1) == position_ids_rmpad.size(1)
|
| 287 |
+
if sp_size <= 1:
|
| 288 |
+
return input_ids_rmpad, position_ids_rmpad, 0
|
| 289 |
+
_, total_seq_len = input_ids_rmpad.shape
|
| 290 |
+
pad_size = (sp_size - total_seq_len % sp_size) % sp_size
|
| 291 |
+
if pad_size > 0:
|
| 292 |
+
input_ids_rmpad = torch.nn.functional.pad(input_ids_rmpad, (0, pad_size), value=0)
|
| 293 |
+
if position_ids_rmpad is not None:
|
| 294 |
+
pad_pos_ids = torch.arange(pad_size, device=position_ids_rmpad.device).unsqueeze(0)
|
| 295 |
+
position_ids_rmpad = torch.cat((position_ids_rmpad, pad_pos_ids), dim=-1)
|
| 296 |
+
# we don't need to slice position ids
|
| 297 |
+
input_ids_rmpad = slice_input_tensor(input_ids_rmpad, dim=1, padding=False)
|
| 298 |
+
return input_ids_rmpad, position_ids_rmpad, pad_size
|