LongVU icon indicating copy to clipboard operation
LongVU copied to clipboard

Did you ever encounter issues with `Trainer`'s `_save_checkpoint` and FSDP?

Open geomlyd opened this issue 2 years ago • 14 comments

This may be system-dependent and a bit of a long shot, but I'm having some issues running training. All goes seemingly well until _save_checkpoint is called (if it matters, I'm running a toy training session with a dataset of 10 samples), at which point I receive some kind of pytorch synchronization error (originating from a gather op) that indicates that e.g. rank 0's optimizer state has a large number of parameters (presumably, as many as the backbone's) but rank 1's is empty.

I'm using srun on a machine with 4 A40s. Did you ever encounter anything similar?

geomlyd avatar Nov 15 '24 09:11 geomlyd

We did not encounter this problem by running on H100s or A100s.

xiaoqian-shen avatar Nov 17 '24 10:11 xiaoqian-shen

I met the same issue, have you ever solved it? @geomlyd

IceFlameWorm avatar Dec 02 '24 08:12 IceFlameWorm

Hello @IceFlameWorm, not exactly: I never managed to get FSDP to run properly. What I did instead, and what seems to work so far, is I switched to using deepspeed. I did this by removing all FSDP-related arguments from the launching script, and by adding the --deepspeed $my_deepspeed_cfg_file argument that is passed on to the base class of HuggingFace's trainer. In case it's helpful, I will also upload here the .json config I used for deepspeed.

Note that I say seems to work because a) I've been able to run some training experiments that did what I expected, but my aim so far was not to reproduce the paper's results, and so I can't confirm that everything runs exactly as it should b) I've noticed that at the very end of training, if there's been a checkpoint resumption in between, the program crashes with some sort of triton-related error message. Nevertheless, this seems to happen after the model has been saved to the disk, and so it doesn't seem to have serious negative effects. zero2.json

geomlyd avatar Dec 02 '24 09:12 geomlyd

Thanks for your reply @geomlyd. I also noticed that although the training script crashes in the end, some checkpoint files do be saved. I tried to load the model from these files to run the quick inference code, but I met the following error: ValueError: Trying to set a tensor of shape torch.Size([143251328]) in "weight" (which has shape torch.Size([152064, 3584])), this looks incorrect. Do you have any solutions or suggestions? Thank you in advance.

IceFlameWorm avatar Dec 02 '24 09:12 IceFlameWorm

@xiaoqian-shen We both still havn't solve this issue yet, could you share your dev enviroment settings?

IceFlameWorm avatar Dec 02 '24 09:12 IceFlameWorm

From my experience, your best bet is probably trying to use deepspeed, inference worked fine for me after training with it (and also whenever I ran inference with the published pretrained checkpoints without any training).

geomlyd avatar Dec 02 '24 09:12 geomlyd

All right, maybe your advice is now the only one solution for me.

IceFlameWorm avatar Dec 02 '24 09:12 IceFlameWorm

@xiaoqian-shen Hi, although some error occurred at line 1109, trainer.train() , in train.py after finishing a finetune, some files still be saved like the following: screenshot-20241203-112530

But when I tried to load this finetuned model using the quick inference code, the following errors were thrown out:

Traceback (most recent call last):
  File "/data/home/agent_ln/projects/LongVU/infer.py", line 20, in <module>
    tokenizer, model, image_processor, context_len = load_pretrained_model(
  File "/data/home/agent_ln/projects/LongVU/longvu/builder.py", line 159, in load_pretrained_model
    model = CambrianQwenForCausalLM.from_pretrained(
  File "/data/home/agent_ln/miniconda3/envs/longvu/lib/python3.10/site-packages/transformers/modeling_utils.py", line 3838, in from_pretrained
    ) = cls._load_pretrained_model(
  File "/data/home/agent_ln/miniconda3/envs/longvu/lib/python3.10/site-packages/transformers/modeling_utils.py", line 4298, in _load_pretrained_model
    new_error_msgs, offload_index, state_dict_index = _load_state_dict_into_meta_model(
  File "/data/home/agent_ln/miniconda3/envs/longvu/lib/python3.10/site-packages/transformers/modeling_utils.py", line 895, in _load_state_dict_into_meta_model
    set_module_tensor_to_device(model, param_name, param_device, **set_module_kwargs)
  File "/data/home/agent_ln/miniconda3/envs/longvu/lib/python3.10/site-packages/accelerate/utils/modeling.py", line 373, in set_module_tensor_to_device
    raise ValueError(
ValueError: Trying to set a tensor of shape torch.Size([143251328]) in "weight" (which has shape torch.Size([152064, 3584])), this looks incorrect.

IceFlameWorm avatar Dec 03 '24 03:12 IceFlameWorm

Hi, @IceFlameWorm

It seems that you are loading the FSDP checkpoint. Remove this file and the checkpoint should be successfully loaded for inference.

xiaoqian-shen avatar Dec 05 '24 11:12 xiaoqian-shen

Hi, @IceFlameWorm

It seems that you are loading the FSDP checkpoint. Remove this file and the checkpoint should be successfully loaded for inference.

I removed those safetensor files and renamed pytorch_model_fsdp.bin as pytorch_model.bin, then the inference seemed ok. Is it a right way? @xiaoqian-shen

IceFlameWorm avatar Dec 09 '24 03:12 IceFlameWorm

根据我的经验,最好的选择可能是尝试使用 deepspeed,在用它训练之后,推理对我来说效果很好(并且每当我在没有任何训练的情况下使用已发布的预训练检查点进行推理时也是如此)。

I recently encountered the problem of FSDP and want to switch to deepspeed. I would like to ask you for help. Can you provide the relevant code? Thank you very much!

orzgugu avatar Dec 09 '24 12:12 orzgugu

Hello @orzgugu , I don't think I had to make changes to the code itself. See my comment above: you should remove all fsdp-related arguments provided to train.py, and you should instead use --deepspeed $my_deepspeed_cfg_file with the deepspeed json config I uploaded above (other configurations may work as well).

However, unrelated to FSDP or deepspeed, I made some changes to the code that saves/loads checkpoints, since my cluster environment has time limits on submitted jobs. I got these from some changes I had previously found necessary for making VideoLlaVa's codebase resume training properly. Note that I'm not sure whether things would work just as well without them, I just thought it would be better to do this as a precaution and so far everything has worked. I can't directly upload .py files here, so I link to a repo I've made containing just these files.

geomlyd avatar Dec 18 '24 10:12 geomlyd

@xiaoqian-shen Meet the same problem with H800. Is there an official solution available for this issue?

jzhzhang avatar Jan 10 '25 04:01 jzhzhang

Hello, After following the aforementioned steps for deleting files, when executing “train_video_qwen.sh”.I still encountered problems.

I encountered the error :

mat1 and mat2 shapes cannot be multiplied (1152x2688 and 256x3584)

when executing “train_image_qwen.sh”.The following errors occurred, but the model file was still retained.

CollectiveFingerPrint
(SequenceNumber=57835, OpType=ALLGATHER, TensorShape=[0], TensorDtypes=Float, 
TensorDeviceTypes=TensorOptions(dtype=float (default), device=cuda,
layout=Strided (default), requires_grad=false (default), 
pinned_memory=false (default), memory_format=(nullopt))). 
Collectives differ in the following aspects: 
Tensor Tensor shapes: 544997376vs 0

The dataset I used was provided by GitHub.I made the modification in the code. If the image file cannot be found, it will be skipped.The video dataset I'm using is shenxq/VideoChat2. Could it be that the dataset I downloaded is incorrect?

However, the model files were retained. I deleted the safetensor files as described above, but the image model files cannot be used to infer videos. Then, when I executed “train_video_qwen.sh”, the following errors occurred:

0%|                                                                                                                                                                                                                 | 0/165311 [00:00<?, ?it/s]Video file not found, skipping: /data/zm_doc/datasets_MLLM/VideoChat2/gifs/tumblr_nodpeypt1E1tqwtb6o1_500.gif
WARNING: tokenization mismatch: 85 vs. 87. (ignored)
Video file not found, skipping: /data/zm_doc/datasets_MLLM/VideoChat2/11558840
WARNING: tokenization mismatch: 80 vs. 81. (ignored)
Video file not found, skipping: /data/zm_doc/datasets_MLLM/VideoChat2/Street_View_Indoor/video3_00350_00360.mp4
WARNING: tokenization mismatch: 75 vs. 76. (ignored)
Video file not found, skipping: /data/zm_doc/datasets_MLLM/VideoChat2/didemo/44012166@N05_4174564176_52c774f2ab.mp4
WARNING: tokenization mismatch: 74 vs. 76. (ignored)
Video file not found, skipping: /data/zm_doc/datasets_MLLM/VideoChat2/11592197
Video file not found, skipping: /data/zm_doc/datasets_MLLM/VideoChat2/1010400251
WARNING: tokenization mismatch: 56 vs. 57. (ignored)
Video file not found, skipping: /data/zm_doc/datasets_MLLM/VideoChat2/didemo/7964800@N03_6072995822_212c640508.mp4
WARNING: tokenization mismatch: 64 vs. 65. (ignored)
Video file not found, skipping: /data/zm_doc/datasets_MLLM/VideoChat2/HXshtf_6lmI
WARNING: tokenization mismatch: 71 vs. 73. (ignored)
WARNING: tokenization mismatch: 79 vs. 80. (ignored)
Traceback (most recent call last):
 File "/workspace/LongVU/longvu/train.py", line 1141, in <module>
    train()
  File "/workspace/LongVU/longvu/train.py", line 1129, in train
    trainer.train()
  File "/opt/conda/envs/longvu/lib/python3.10/site-packages/transformers/trainer.py", line 1932, in train
    return inner_training_loop(
  File "/opt/conda/envs/longvu/lib/python3.10/site-packages/transformers/trainer.py", line 2268, in _inner_training_loop
    tr_loss_step = self.training_step(model, inputs)
  File "/opt/conda/envs/longvu/lib/python3.10/site-packages/transformers/trainer.py", line 3307, in training_step
    loss = self.compute_loss(model, inputs)
 File "/workspace/LongVU/longvu/cambrian_arch.py", line 1033, in prepare_inputs_labels_for_multimodal
 ) = self.prepare_inputs_labels_for_multimodal(
 image_features = self.get_model().mm_projector(image_features).to(dtype)
 File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
 File "/workspace/LongVU/longvu/cambrian_arch.py", line 1033, in prepare_inputs_labels_for_multimodal
 return self._call_impl(*args, **kwargs)
 File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
 return forward_call(*args, **kwargs)
 File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/linear.py", line 114, in forward
 image_features = self.get_model().mm_projector(image_features).to(dtype)
 File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
 return self._call_impl(*args, **kwargs)
 File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
 return forward_call(*args, **kwargs)
 File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/linear.py", line 114, in forward
 return F.linear(input, self.weight, self.bias)
RuntimeError: mat1 and mat2 shapes cannot be multiplied (1152x2688 and 256x3584)
return F.linear(input, self.weight, self.bias)
RuntimeError: mat1 and mat2 shapes cannot be multiplied (1152x2688 and 256x3584)

train_image_qwen.sh

PREV_STAGE_CHECKPOINT="/workspace/LongVU/checkpoints/cambrian_qwen/checkpoint-500"
PATH_TO_JSON="/data/zm_doc/datasets_MLLM/VideoChat2/train_video_data.json"
PATH_TO_FOLDER="/data/zm_doc/datasets_MLLM/VideoChat2/"
VERSION="qwen"

CUDA_LAUNCH_BLOCKING=1 TORCH_DISTRIBUTED_DEBUG=DETAIL PYTHONPATH=/workspace/LongVU   torchrun --nproc_per_node=2 --nnodes=1 \
longvu/train.py \
--output_dir "/tmp/longvu/" \
--input_model_filename $PREV_STAGE_CHECKPOINT \
--output_model_filename "./checkpoints/cambrian_vl_qwen/" \
--data_path $PATH_TO_JSON \
--image_folder $PATH_TO_FOLDER \
--model_max_length 8192 \
--fp16 False \
--bf16 True \
--log_on_each_node False \
--logging_dir /tmp/llava/test/ \
--num_train_epochs 1 \
--per_device_train_batch_size 2 \
--per_device_eval_batch_size 2 \
--gradient_accumulation_steps 1 \
--save_steps 30 \
--eval_steps 30 \
--logging_steps 10 \
--evaluation_strategy "no" \
--save_strategy "steps" \
#--report_to "tensorboard" \
--save_total_limit 1 \
--learning_rate 5e-6 \
--weight_decay 0. \
--warmup_ratio 0.03 \
--lr_scheduler_type "cosine" \
--tf32 False \
--version $VERSION \
--mm_vision_select_layer "-2" \
--mm_use_im_start_end False \
--mm_use_im_patch_token False \
--image_aspect_ratio pad \
--group_by_modality_length True \
--dataloader_num_workers 0 \
--lazy_preprocess False \
--tune_mm_mlp_adapter False \
--freeze_mm_mlp_adapter False \
--freeze_backbone False \
--fsdp "full_shard auto_wrap" \
--fsdp_transformer_layer_cls_to_wrap 'Qwen2DecoderLayer' \
--gradient_checkpointing True \
--mm_projector_type sva \
--image_token_len 144 \
--query_num_list "[144]" \
--resume True \
--lowres_token 8 \
--video_fps 1 \
--highres True \
--drop_threshold 0.8 \

meng8407 avatar Sep 23 '25 10:09 meng8407