Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- rl_lavida_revvideo_orig10k_4gpu_len128/temp_data/outputs-rl-...rl_lavida_revvideo_orig10k_4gpu_len128.ckpt.optimized-video_reversal_sft_train_cleaned_10k-step10.jsonAdded
- rl_lavida_revvideo_orig10k_4gpu_len128/temp_data/outputs-rl-...rl_lavida_revvideo_orig10k_4gpu_len128.ckpt.optimized-video_reversal_sft_train_cleaned_10k-step6.jsonAdded
- rl_lavida_revvideo_orig10k_4gpu_len128/temp_data/outputs-rl-...rl_lavida_revvideo_orig10k_4gpu_len128.ckpt.optimized-video_reversal_sft_train_cleaned_10k-step9.jsonAdded
- rl_lladav_video_reversal_wo_ub_reward/config.yamlAdded+102
- rl_lladav_video_reversal_wo_ub_reward/results/all_rewards.csvAdded+62
- rl_lladav_video_reversal_wo_ub_reward/results/results-eval-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train.txtAdded
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step10.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step11.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step12.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step13.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step14.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step16.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step17.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step18.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step19.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step20.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step21.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step23.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step24.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step25.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step27.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step28.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step3.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step30.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step4.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step5.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step6.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step7.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step8.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step9.txtAdded+2
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train.txtAdded
- rl_lladav_video_reversal_wo_ub_reward/results/results-rl-.data4.runqing.dLLM-RL.sft_lladav_video_reversal_3_21.ckpt.optimized-video_reversal_rl_train-step1.txtAdded+2
- train/eval_lavida_revvideo.pyAdded+390
- train/eval_llava_next_revvideo.pyAdded+325
- train/init_lladav_value_model.pyAdded+164
- train/init_mmada_v_value_model.pyAdded+162
- train/init_sdar_value_model.pyAdded+194
- train/init_trado_value_model.pyAdded+194
- train/llava/__init__.pyAdded
- train/llava/cache/Cache.pyAdded+83
- train/llava/cache/Config.pyAdded+9
- train/llava/cache/__init__.pyAdded+4
- train/llava/constants.pyAdded+12
- train/llava/conversation.pyAdded+624
- train/llava/hooks/__init__.pyAdded+6
- train/llava/hooks/cache_hook_LLaDA_V.pyAdded+619
- train/llava/hooks/fast_dllm_hook.pyAdded+507
- train/llava/mm_utils.pyAdded+396
- train/llava/model/__init__.pyAdded+11
- train/llava/model/apply_delta.pyAdded+47
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102wandb: entity: null resume: auto run_id: lzqtg4q4system: HTTP_PROXY: null HF_HOME: null env_name: /data8/runqing/miniconda/envs/dllm-rl envs_dir: /data8/runqing/miniconda/envs/dllm-rl base_dir: /data4/runqing/dLLM-RLexperiment: project: rl_lladav_video_reversal_wo_ub_reward function: train start_from_scratch: true total_step: 30 save_every: 10 eval_every: 5 current_epoch: 30 deepspeed_file: 1_node_8_gpus_deepspeed_zero2_rl num_node: 1 node_index: 0 logging_dir: rl_lladav_video_reversal_wo_ub_reward/logsmodel: pretrained_model: /data4/runqing/dLLM-RL/sft_lladav_video_reversal_3_21/ckpt/optimized optimized_name: optimized model_base: lladav vq_model_path: /data4/runqing/hf/magvitv2 image_resolution: 512dataset: train_dataset: video_reversal_rl_train data_type: video_reverse optimization_data: rl_datarollout: num_task_per_step: 128 num_response_per_task: 8 temperature: 0.8 steps: 128 max_gen_length: 128 batch_size: 1 remasking_strategy: low_confidence_dynamic target: confidence dynamic_threshold: 0.9 block_size: 32 further_horizon: 128 use_cache: truereward: answer_must_in_box: true strict_len_check: falseexecute: num_chunk: 128training: gradient_accumulation_steps: 2 batch_size_lm: 1 mixed_precision: bf16 enable_tf32: true seed: 10086 num_train_epochs: 1 max_grad_norm: 1.0 method: random_masking lower_p: 0.35 upper_p: 0.9 shrink: 8 post_num: 1 mask_times_per_sample: 2 max_gen_length: ${rollout.max_gen_length} max_prompt_len: 512 eps: 0.2 beta: 0.01 use_kl_estimator_k3: trueoptimizer: name: adamw params: learning_rate: 1.0e-06 scale_lr: false beta1: 0.9 beta2: 0.999 weight_decay: 0.0 epsilon: 1.0e-08lr_scheduler: scheduler: cosine params: learning_rate: ${optimizer.params.learning_rate} warmup_steps: 0 min_lr_scale: 1.0evaluation: if_eval: false eval_dataset: video_reversal_rl_eval data_type: video_reverse num_response_per_task: 3 temperature: 0.1 steps: 128 max_gen_length: 128 batch_size: 1 remasking_strategy: - low_confidence_static - low_confidence_dynamic target: confidence dynamic_threshold: 0.9 block_size: 32 further_horizon: 128 use_cache: trueconfig: configs/rl_lladav_video_reversal_wo_ub_reward.yaml1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162step,acc_reward,t_grpo_reward,unbiased_reward,response_length1,0.5293,0.2578,0.0000,128.00step,acc_reward,t_grpo_reward,unbiased_reward,response_length1,0.5293,0.2578,0.0000,128.002,0.5762,0.2672,0.0000,127.992,0.5762,0.2672,0.0000,127.993,0.5254,0.2625,0.0000,128.003,0.5254,0.2625,0.0000,128.004,0.5566,0.2484,0.0000,127.994,0.5566,0.2484,0.0000,127.995,0.5098,0.2344,0.0000,128.005,0.5098,0.2344,0.0000,128.006,0.6113,0.2578,0.0000,128.006,0.6113,0.2578,0.0000,128.007,0.6113,0.2578,0.0000,127.997,0.6113,0.2578,0.0000,127.998,0.5566,0.2438,0.0000,127.998,0.5566,0.2438,0.0000,127.999,0.5801,0.2250,0.0000,127.939,0.5801,0.2250,0.0000,127.9310,0.5898,0.2297,0.0000,128.0010,0.5898,0.2297,0.0000,128.0011,0.5469,0.2438,0.0000,128.0011,0.5469,0.2438,0.0000,128.0012,0.5840,0.2531,0.0000,128.0012,0.5840,0.2531,0.0000,128.0013,0.6387,0.2625,0.0000,128.0013,0.6387,0.2625,0.0000,128.0014,0.4512,0.2438,0.0000,127.9914,0.4512,0.2438,0.0000,127.9915,0.5645,0.2578,0.0000,127.9915,0.5645,0.2578,0.0000,127.9916,0.5762,0.2672,0.0000,127.9916,0.5762,0.2672,0.0000,127.9917,0.5664,0.2672,0.0000,128.0017,0.5664,0.2672,0.0000,128.0018,0.5391,0.2484,0.0000,128.0018,0.5391,0.2484,0.0000,128.0019,0.4863,0.2250,0.0000,128.0019,0.4863,0.2250,0.0000,128.0020,0.4902,0.2531,0.0000,128.0020,0.4902,0.2531,0.0000,128.0021,0.5449,0.2625,0.0000,127.9921,0.5449,0.2625,0.0000,127.9922,0.5410,0.2484,0.0000,128.0022,0.5410,0.2484,0.0000,128.0023,0.5840,0.2484,0.0000,127.9923,0.5840,0.2484,0.0000,127.9924,0.5039,0.2391,0.0000,127.9924,0.5039,0.2391,0.0000,127.9925,0.5723,0.2531,0.0000,128.0025,0.5723,0.2531,0.0000,128.0026,0.6133,0.2531,0.0000,127.9926,0.6133,0.2531,0.0000,127.9927,0.5039,0.2531,0.0000,127.9927,0.5039,0.2531,0.0000,127.9928,0.5000,0.2484,0.0000,128.0028,0.5000,0.2484,0.0000,128.0029,0.5449,0.2391,0.0000,127.9929,0.5449,0.2391,0.0000,127.9930,0.5684,0.2672,0.0000,127.9930,0.5684,0.2672,0.0000,127.9912train step: 10 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5898 avg length: 128.00train step: 10 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5898 avg length: 128.0012train step: 11 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5469 avg length: 128.00train step: 11 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5469 avg length: 128.0012train step: 12 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5840 avg length: 128.00train step: 12 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5840 avg length: 128.0012train step: 13 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.6387 avg length: 128.00train step: 13 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.6387 avg length: 128.0012train step: 14 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.4512 avg length: 127.99train step: 14 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.4512 avg length: 127.9912train step: 16 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5762 avg length: 127.99train step: 16 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5762 avg length: 127.9912train step: 17 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5664 avg length: 128.00train step: 17 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5664 avg length: 128.0012train step: 18 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5391 avg length: 128.00train step: 18 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5391 avg length: 128.0012train step: 19 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.4863 avg length: 128.00train step: 19 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.4863 avg length: 128.0012train step: 20 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.4902 avg length: 128.00train step: 20 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.4902 avg length: 128.0012train step: 21 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5449 avg length: 127.99train step: 21 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5449 avg length: 127.9912train step: 23 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5840 avg length: 127.99train step: 23 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5840 avg length: 127.9912train step: 24 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5039 avg length: 127.99train step: 24 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5039 avg length: 127.9912train step: 25 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5723 avg length: 128.00train step: 25 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5723 avg length: 128.0012train step: 27 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5039 avg length: 127.99train step: 27 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5039 avg length: 127.9912train step: 28 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5000 avg length: 128.00train step: 28 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5000 avg length: 128.0012train step: 3 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5254 avg length: 128.00train step: 3 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5254 avg length: 128.0012train step: 30 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5684 avg length: 127.99train step: 30 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5684 avg length: 127.9912train step: 4 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5566 avg length: 127.99train step: 4 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5566 avg length: 127.9912train step: 5 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5098 avg length: 128.00train step: 5 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5098 avg length: 128.0012train step: 6 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.6113 avg length: 128.00train step: 6 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.6113 avg length: 128.0012train step: 7 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.6113 avg length: 127.99train step: 7 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.6113 avg length: 127.9912train step: 8 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5566 avg length: 127.99train step: 8 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5566 avg length: 127.9912train step: 9 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5801 avg length: 127.93train step: 9 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5801 avg length: 127.9312train step: 1 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5293 avg length: 128.00train step: 1 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5293 avg length: 128.00123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390import argparseimport jsonimport mathimport osimport randomimport reimport sysfrom pathlib import Path
os.environ.setdefault("HF_HUB_OFFLINE", "1")os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")os.environ.setdefault("HF_DATASETS_OFFLINE", "1")
import torchfrom transformers import AutoConfig
try: from decord import VideoReader, cpuexcept ImportError: VideoReader = None cpu = Nonetry: import cv2except ImportError: cv2 = None
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))LAVIDA_ROOT = os.path.join(REPO_ROOT, "LaViDa")sys.path.insert(0, LAVIDA_ROOT)sys.path.insert(1, REPO_ROOT)
from llava.constants import DEFAULT_IMAGE_TOKEN, DEFAULT_IM_END_TOKEN, DEFAULT_IM_START_TOKEN, IMAGE_TOKEN_INDEXfrom llava.conversation import SeparatorStyle, conv_templatesfrom llava.mm_utils import KeywordsStoppingCriteria, tokenizer_image_tokenfrom llava.model.builder import load_pretrained_model
SYS_PROMPT = ( "Carefully watch the video and pay attention to the cause and sequence of events, " "the detail and movement of objects, and the action and pose of persons. " "Based on your observations, select the best option that accurately addresses the question.\n")QUESTION_PROMPT = "\nOnly give the best option."MCQ_PROMPT = " Please provide only the single option letter (e.g., A, B, C, D, etc.) within the <answer> </answer> tags."LETTER_RE = re.compile(r"<answer>\s*([A-Z])\s*</answer>|(?:^|[^A-Z])([A-Z])(?:[\.\)\s]|$)")
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--model-path", required=True) parser.add_argument("--dataset-json", default="/data4/runqing/dLLM-RL/data/video_reversal_sft_test.json") parser.add_argument("--output-dir", required=True) parser.add_argument("--device", default="cuda:1") parser.add_argument("--device-map", default=None) parser.add_argument("--conv-mode", default="llada") parser.add_argument("--max-samples", type=int, default=None) parser.add_argument("--start-index", type=int, default=0) parser.add_argument("--frames", type=int, default=16) parser.add_argument("--force-sample", action="store_true") parser.add_argument("--mm-spatial-pool-stride", type=int, default=4) parser.add_argument("--mm-spatial-pool-mode", default="average") parser.add_argument("--mm-newline-position", default="grid") parser.add_argument("--temperature", type=float, default=0.0) parser.add_argument("--max-new-tokens", type=int, default=12) parser.add_argument("--block-length", type=int, default=12) parser.add_argument("--step-per-block", type=int, default=4) parser.add_argument("--top-p", type=float, default=0.1) parser.add_argument("--num-beams", type=int, default=1) parser.add_argument("--use-tvcd", action="store_true") parser.add_argument("--cd-alpha", type=float, default=1.0) parser.add_argument("--cd-beta", type=float, default=0.1) parser.add_argument("--tvcd-shuffle-seed", type=int, default=42) parser.add_argument("--resume", action="store_true") return parser.parse_args()
def load_video(video_path, frames_num, force_sample): if VideoReader is not None: vr = VideoReader(video_path, ctx=cpu(0), num_threads=1) total_frame_num = len(vr) fps = max(1, round(vr.get_avg_fps())) frame_idx = [i for i in range(0, total_frame_num, fps)] if len(frame_idx) > frames_num or force_sample: frame_idx = np_linspace_int(0, total_frame_num - 1, frames_num) return vr.get_batch(frame_idx).asnumpy()
if cv2 is None: raise RuntimeError("Neither decord nor cv2 is available for video decoding.") cap = cv2.VideoCapture(video_path) total_frame_num = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) fps = cap.get(cv2.CAP_PROP_FPS) fps = max(1, round(fps if fps and fps > 0 else 1)) frame_idx = [i for i in range(0, max(total_frame_num, 1), fps)] if len(frame_idx) > frames_num or force_sample: frame_idx = np_linspace_int(0, max(total_frame_num - 1, 0), frames_num)
wanted = set(frame_idx) frames = [] idx = 0 while True: ok, frame = cap.read() if not ok: break if idx in wanted: frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) idx += 1 cap.release() if not frames: raise RuntimeError(f"Failed to decode video: {video_path}") return frames
def np_linspace_int(start, end, count): if count <= 1: return [start] step = (end - start) / (count - 1) return [int(round(start + i * step)) for i in range(count)]
def shuffle_video_tensor(video_tensor, seed): if video_tensor.ndim < 1 or video_tensor.shape[0] <= 1: return video_tensor.clone() generator = torch.Generator(device="cpu").manual_seed(int(seed)) perm = torch.randperm(video_tensor.shape[0], generator=generator) return video_tensor[perm.to(video_tensor.device)]
def build_prompt(sample): return ( SYS_PROMPT + "Question: " + sample["prompt"] + "Options: " + str(sample["options"]) + QUESTION_PROMPT + MCQ_PROMPT )
def extract_letter(text): if not text: return None match = LETTER_RE.search(text.strip().upper()) if not match: return None return match.group(1) or match.group(2)
def clean_generation_text(text): if text is None: return None text = text.lstrip("!").strip() return text
def load_samples(path, start_index, max_samples): with open(path) as f: data = json.load(f) if start_index: data = data[start_index:] if max_samples is not None: data = data[:max_samples] return data
def maybe_load_done_ids(path): done = set() if not os.path.exists(path): return done with open(path) as f: for line in f: if not line.strip(): continue try: row = json.loads(line) done.add(int(row["sample_idx"])) except Exception: continue return done
def main(): args = parse_args() print(f"[eval] args={vars(args)}", flush=True) torch.backends.cuda.matmul.allow_tf32 = True if hasattr(torch.backends, "cudnn"): torch.backends.cudnn.allow_tf32 = True
os.makedirs(args.output_dir, exist_ok=True) print(f"[eval] output_dir={args.output_dir}", flush=True) pred_path = os.path.join(args.output_dir, "predictions.jsonl") summary_path = os.path.join(args.output_dir, "summary.json")
model_name = "llava_llada" overwrite_config = { "mm_spatial_pool_mode": args.mm_spatial_pool_mode, "mm_spatial_pool_stride": args.mm_spatial_pool_stride, "mm_newline_position": args.mm_newline_position, }
cfg_pretrained = AutoConfig.from_pretrained(args.model_path) if "qwen" not in args.model_path.lower(): if hasattr(cfg_pretrained, "mm_vision_tower") and "224" in cfg_pretrained.mm_vision_tower: least_token_number = args.frames * (16 // args.mm_spatial_pool_stride) ** 2 + 1000 else: least_token_number = args.frames * (24 // args.mm_spatial_pool_stride) ** 2 + 1000 scaling_factor = math.ceil(least_token_number / 4096) if scaling_factor >= 2: if getattr(cfg_pretrained, "_name_or_path", "") and "vicuna" in cfg_pretrained._name_or_path.lower(): overwrite_config["rope_scaling"] = {"factor": float(scaling_factor), "type": "linear"} overwrite_config["max_sequence_length"] = 4096 * scaling_factor overwrite_config["tokenizer_model_max_length"] = 4096 * scaling_factor
load_device_map = args.device_map if args.device_map is not None else None print(f"[eval] loading model from {args.model_path} with device_map={load_device_map}", flush=True) tokenizer, model, image_processor, _ = load_pretrained_model( args.model_path, None, model_name, multimodal=True, device_map=load_device_map, torch_dtype="bfloat16", overwrite_config=overwrite_config, ) if args.device_map is None: device = torch.device(args.device) model = model.to(device) else: device = torch.device(args.device) model = model.eval() print("[eval] model loaded", flush=True)
if getattr(model.config, "force_sample", None) is not None: args.force_sample = bool(model.config.force_sample)
samples = load_samples(args.dataset_json, args.start_index, args.max_samples) print(f"[eval] loaded {len(samples)} samples from {args.dataset_json}", flush=True) done_ids = maybe_load_done_ids(pred_path) if args.resume else set()
total = 0 baseline_correct = 0 tvcd_correct = 0 rng = random.Random(args.tvcd_shuffle_seed)
if done_ids: with open(pred_path) as f: for line in f: if not line.strip(): continue row = json.loads(line) if row.get("baseline_correct"): baseline_correct += 1 if row.get("tvcd_correct"): tvcd_correct += 1 total += 1
with open(pred_path, "a", buffering=1) as fout: for offset, sample in enumerate(samples): sample_idx = args.start_index + offset if sample_idx in done_ids: continue print( f"[eval] sample_idx={sample_idx} reversal_type={sample.get('reversal_type')} " f"video={sample.get('video_abs_path')}", flush=True, )
prompt = build_prompt(sample) qs = prompt if model.config.mm_use_im_start_end: qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + "\n" + qs else: qs = DEFAULT_IMAGE_TOKEN + "\n" + qs
conv = conv_templates[args.conv_mode].copy() if getattr(conv, "tokenizer", None) is None: conv.tokenizer = tokenizer conv.append_message(conv.roles[0], qs) conv.append_message(conv.roles[1], None) full_prompt = conv.get_prompt()
input_ids = tokenizer_image_token(full_prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(device) if tokenizer.pad_token_id is None and "qwen" in (tokenizer.name_or_path or "").lower(): tokenizer.pad_token_id = 151643 pad_token_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id attention_mask = input_ids.ne(pad_token_id).long().to(device)
stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2 stopping_criteria = KeywordsStoppingCriteria([stop_str], tokenizer, input_ids)
frames = load_video(sample["video_abs_path"], args.frames, args.force_sample) video_tensor = image_processor.preprocess(frames, return_tensors="pt")["pixel_values"].to(device=device, dtype=torch.bfloat16) video = [video_tensor] video_cd = None if args.use_tvcd: video_cd = [shuffle_video_tensor(video_tensor, seed=rng.randint(0, 2**31 - 1))]
gen_kwargs = dict( inputs=input_ids, images=video, attention_mask=attention_mask, modalities="video", do_sample=False, temperature=args.temperature, max_new_tokens=args.max_new_tokens, block_length=args.block_length, step_per_block=args.step_per_block, top_p=args.top_p, num_beams=args.num_beams, use_cache=True, stopping_criteria=[stopping_criteria], )
with torch.inference_mode(): baseline_ids = model.generate(**gen_kwargs) baseline_text = clean_generation_text(tokenizer.batch_decode(baseline_ids, skip_special_tokens=True)[0]) print(f"[eval] sample_idx={sample_idx} baseline={baseline_text}", flush=True)
tvcd_text = None if args.use_tvcd: tvcd_ids = model.generate( **gen_kwargs, images_cd=video_cd, cd_alpha=args.cd_alpha, cd_beta=args.cd_beta, ) tvcd_text = clean_generation_text(tokenizer.batch_decode(tvcd_ids, skip_special_tokens=True)[0]) print(f"[eval] sample_idx={sample_idx} tvcd={tvcd_text}", flush=True)
gt_letter = extract_letter(sample["response"]) baseline_letter = extract_letter(baseline_text) tvcd_letter = extract_letter(tvcd_text) if tvcd_text is not None else None
baseline_hit = baseline_letter == gt_letter tvcd_hit = tvcd_letter == gt_letter if tvcd_text is not None else None
total += 1 baseline_correct += int(baseline_hit) if tvcd_hit is True: tvcd_correct += 1
row = { "sample_idx": sample_idx, "data_id": sample.get("data_id"), "reversal_type": sample.get("reversal_type"), "video_abs_path": sample.get("video_abs_path"), "gt_response": sample.get("response"), "gt_letter": gt_letter, "baseline_text": baseline_text, "baseline_letter": baseline_letter, "baseline_correct": baseline_hit, "tvcd_text": tvcd_text, "tvcd_letter": tvcd_letter, "tvcd_correct": tvcd_hit, } fout.write(json.dumps(row, ensure_ascii=False) + "\n")
if total % 10 == 0: summary = { "samples_done": total, "baseline_acc": baseline_correct / total, "tvcd_acc": (tvcd_correct / total) if args.use_tvcd else None, "model_path": args.model_path, "dataset_json": args.dataset_json, "use_tvcd": args.use_tvcd, "cd_alpha": args.cd_alpha if args.use_tvcd else None, "cd_beta": args.cd_beta if args.use_tvcd else None, } with open(summary_path, "w") as f: json.dump(summary, f, indent=2, ensure_ascii=False) print(summary, flush=True)
summary = { "samples_done": total, "baseline_acc": baseline_correct / total if total else 0.0, "tvcd_acc": (tvcd_correct / total) if args.use_tvcd and total else None, "model_path": args.model_path, "dataset_json": args.dataset_json, "use_tvcd": args.use_tvcd, "cd_alpha": args.cd_alpha if args.use_tvcd else None, "cd_beta": args.cd_beta if args.use_tvcd else None, } with open(summary_path, "w") as f: json.dump(summary, f, indent=2, ensure_ascii=False) print(json.dumps(summary, ensure_ascii=False, indent=2))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325import argparseimport jsonimport mathimport osimport randomimport reimport sys
os.environ.setdefault("HF_HUB_OFFLINE", "1")os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")os.environ.setdefault("HF_DATASETS_OFFLINE", "1")
import torchfrom transformers import AutoConfig
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))LLAVA_NEXT_ROOT = os.path.join(REPO_ROOT, "LLaVA-NeXT")sys.path.insert(0, LLAVA_NEXT_ROOT)sys.path.insert(1, REPO_ROOT)
from llava.constants import DEFAULT_IMAGE_TOKEN, IMAGE_TOKEN_INDEXfrom llava.conversation import conv_templatesfrom llava.mm_utils import tokenizer_image_token, get_model_name_from_pathfrom llava.model.builder import load_pretrained_modelfrom llava.utils import process_video_with_decordfrom train.llava_next_video.common import build_video_mcq_prompt, resolve_media_abs_path
SYS_PROMPT = ( "Carefully watch the video and pay attention to the cause and sequence of events, " "the detail and movement of objects, and the action and pose of persons. " "Based on your observations, select the best option that accurately addresses the question.\n")QUESTION_PROMPT = "\nOnly give the best option."MCQ_PROMPT = " Please provide only the single option letter (e.g., A, B, C, D, etc.) within the <answer> </answer> tags."LETTER_RE = re.compile(r"<answer>\s*([A-Z])\s*</answer>|(?:^|[^A-Z])([A-Z])(?:[\.\)\s]|$)")
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--model-path", required=True) parser.add_argument("--dataset-json", default="/data4/runqing/dLLM-RL/data/video_reversal_sft_test.json") parser.add_argument("--output-dir", required=True) parser.add_argument("--device", default="cuda:0") parser.add_argument("--conv-mode", default="vicuna_v1") parser.add_argument("--max-samples", type=int, default=None) parser.add_argument("--start-index", type=int, default=0) parser.add_argument("--frames", type=int, default=16) parser.add_argument("--force-sample", action="store_true") parser.add_argument("--mm-spatial-pool-stride", type=int, default=2) parser.add_argument("--mm-spatial-pool-mode", default="average") parser.add_argument("--mm-newline-position", default=None) parser.add_argument("--temperature", type=float, default=0.0) parser.add_argument("--max-new-tokens", type=int, default=12) parser.add_argument("--top-p", type=float, default=0.1) parser.add_argument("--num-beams", type=int, default=1) parser.add_argument("--use-tvcd", action="store_true") parser.add_argument("--cd-alpha", type=float, default=1.0) parser.add_argument("--cd-beta", type=float, default=0.1) parser.add_argument("--tvcd-shuffle-seed", type=int, default=42) parser.add_argument("--resume", action="store_true") return parser.parse_args()
def shuffle_video_tensor(video_tensor, seed): if video_tensor.ndim < 1 or video_tensor.shape[0] <= 1: return video_tensor.clone() generator = torch.Generator(device="cpu").manual_seed(int(seed)) perm = torch.randperm(video_tensor.shape[0], generator=generator) return video_tensor[perm.to(video_tensor.device)]
def load_video_inputs(video_path, image_processor, model_cfg, device): video, video_time, frame_time, num_frames_to_sample = process_video_with_decord(video_path, model_cfg) video_tensor = image_processor.preprocess(video, return_tensors="pt")["pixel_values"].to(device=device, dtype=torch.bfloat16) return [video_tensor], [video[0].size], video_time, frame_time, num_frames_to_sample
def clean_generation_text(text): if text is None: return None return text.lstrip("!").strip()
def extract_letter(text): if not text: return None match = LETTER_RE.search(text.strip().upper()) if not match: return None return match.group(1) or match.group(2)
def load_samples(path, start_index, max_samples): with open(path) as f: data = json.load(f) if start_index: data = data[start_index:] if max_samples is not None: data = data[:max_samples] return data
def maybe_load_done_ids(path): done = set() if not os.path.exists(path): return done with open(path) as f: for line in f: if not line.strip(): continue try: done.add(int(json.loads(line)["sample_idx"])) except Exception: continue return done
def extract_generated_ids(output_ids, prompt_ids): if output_ids.shape[1] > prompt_ids.shape[1]: return output_ids[:, prompt_ids.shape[1] :] return output_ids
def main(): args = parse_args() print(f"[eval] args={vars(args)}", flush=True) torch.backends.cuda.matmul.allow_tf32 = True if hasattr(torch.backends, "cudnn"): torch.backends.cudnn.allow_tf32 = True
os.makedirs(args.output_dir, exist_ok=True) pred_path = os.path.join(args.output_dir, "predictions.jsonl") summary_path = os.path.join(args.output_dir, "summary.json") print(f"[eval] output_dir={args.output_dir}", flush=True)
model_name = get_model_name_from_path(args.model_path) cfg_pretrained = AutoConfig.from_pretrained(args.model_path, local_files_only=True) overwrite_config = { "mm_spatial_pool_mode": args.mm_spatial_pool_mode, "mm_spatial_pool_stride": args.mm_spatial_pool_stride, "mm_newline_position": args.mm_newline_position or getattr(cfg_pretrained, "mm_newline_position", "grid"), } if "qwen" not in args.model_path.lower(): if hasattr(cfg_pretrained, "mm_vision_tower") and "224" in cfg_pretrained.mm_vision_tower: least_token_number = args.frames * (16 // args.mm_spatial_pool_stride) ** 2 + 1000 else: least_token_number = args.frames * (24 // args.mm_spatial_pool_stride) ** 2 + 1000 scaling_factor = math.ceil(least_token_number / 4096) if scaling_factor >= 2: if "vicuna" in str(getattr(cfg_pretrained, "_name_or_path", "")).lower(): overwrite_config["rope_scaling"] = {"factor": float(scaling_factor), "type": "linear"} overwrite_config["max_sequence_length"] = 4096 * scaling_factor overwrite_config["tokenizer_model_max_length"] = 4096 * scaling_factor
print(f"[eval] loading model from {args.model_path}", flush=True) tokenizer, model, image_processor, _ = load_pretrained_model( args.model_path, None, model_name, multimodal=True, device_map=None, torch_dtype="bfloat16", overwrite_config=overwrite_config, ) device = torch.device(args.device) model = model.to(device).eval() print("[eval] model loaded", flush=True)
if getattr(model.config, "force_sample", None) is not None: args.force_sample = bool(model.config.force_sample) if getattr(model.config, "frames_upbound", None) is not None and args.frames == 16: args.frames = int(model.config.frames_upbound) if getattr(model.config, "add_time_instruction", None) is not None: add_time_instruction = bool(model.config.add_time_instruction) else: add_time_instruction = False
samples = load_samples(args.dataset_json, args.start_index, args.max_samples) print(f"[eval] loaded {len(samples)} samples from {args.dataset_json}", flush=True) done_ids = maybe_load_done_ids(pred_path) if args.resume else set()
total = 0 baseline_correct = 0 tvcd_correct = 0 rng = random.Random(args.tvcd_shuffle_seed)
if done_ids: with open(pred_path) as f: for line in f: if not line.strip(): continue row = json.loads(line) baseline_correct += int(bool(row.get("baseline_correct"))) tvcd_correct += int(bool(row.get("tvcd_correct"))) total += 1
with open(pred_path, "a", buffering=1) as fout: for offset, sample in enumerate(samples): sample_idx = args.start_index + offset if sample_idx in done_ids: continue print(f"[eval] sample_idx={sample_idx} reversal_type={sample.get('reversal_type')} video={sample.get('video_abs_path')}", flush=True)
video_path = resolve_media_abs_path(sample, None, media_type="video") video, image_sizes, video_time, frame_time, num_frames = load_video_inputs( video_path, image_processor, model.config, device, ) video_tensor = video[0] prompt = build_video_mcq_prompt(sample)
if add_time_instruction: prompt = ( f"The video lasts for {video_time:.2f} seconds, and {num_frames} frames are uniformly sampled from it. " f"These frames are located at {frame_time}. Please answer the following questions related to this video.\n" f"{prompt}" )
qs = DEFAULT_IMAGE_TOKEN + "\n" + prompt
conv = conv_templates[args.conv_mode].copy() conv.append_message(conv.roles[0], qs) conv.append_message(conv.roles[1], None) full_prompt = conv.get_prompt()
input_ids = tokenizer_image_token(full_prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(device) pad_token_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id attention_mask = input_ids.ne(pad_token_id).long().to(device)
gen_kwargs = dict( inputs=input_ids, images=video, image_sizes=image_sizes, attention_mask=attention_mask, modalities=["video"], do_sample=False, temperature=args.temperature, max_new_tokens=args.max_new_tokens, top_p=args.top_p, num_beams=args.num_beams, use_cache=True, )
with torch.inference_mode(): baseline_ids = model.generate(**gen_kwargs) baseline_ids = extract_generated_ids(baseline_ids, input_ids) baseline_text = clean_generation_text(tokenizer.batch_decode(baseline_ids, skip_special_tokens=True)[0]) print(f"[eval] sample_idx={sample_idx} baseline={baseline_text}", flush=True)
tvcd_text = None if args.use_tvcd: video_cd = [shuffle_video_tensor(video_tensor, seed=rng.randint(0, 2**31 - 1))] tvcd_ids = model.generate( **gen_kwargs, images_cd=video_cd, image_sizes_cd=image_sizes, cd_alpha=args.cd_alpha, cd_beta=args.cd_beta, ) tvcd_ids = extract_generated_ids(tvcd_ids, input_ids) tvcd_text = clean_generation_text(tokenizer.batch_decode(tvcd_ids, skip_special_tokens=True)[0]) print(f"[eval] sample_idx={sample_idx} tvcd={tvcd_text}", flush=True)
gt_letter = extract_letter(sample["response"]) baseline_letter = extract_letter(baseline_text) tvcd_letter = extract_letter(tvcd_text) if tvcd_text is not None else None baseline_hit = baseline_letter == gt_letter tvcd_hit = tvcd_letter == gt_letter if tvcd_text is not None else None
total += 1 baseline_correct += int(baseline_hit) if tvcd_hit is True: tvcd_correct += 1
row = { "sample_idx": sample_idx, "data_id": sample.get("data_id"), "reversal_type": sample.get("reversal_type"), "video_abs_path": video_path, "gt_response": sample.get("response"), "gt_letter": gt_letter, "baseline_text": baseline_text, "baseline_letter": baseline_letter, "baseline_correct": baseline_hit, "tvcd_text": tvcd_text, "tvcd_letter": tvcd_letter, "tvcd_correct": tvcd_hit, } fout.write(json.dumps(row, ensure_ascii=False) + "\n")
if total % 10 == 0: summary = { "samples_done": total, "baseline_acc": baseline_correct / total, "tvcd_acc": (tvcd_correct / total) if args.use_tvcd else None, "model_path": args.model_path, "dataset_json": args.dataset_json, "use_tvcd": args.use_tvcd, "cd_alpha": args.cd_alpha if args.use_tvcd else None, "cd_beta": args.cd_beta if args.use_tvcd else None, } with open(summary_path, "w") as f: json.dump(summary, f, indent=2, ensure_ascii=False) print(summary, flush=True)
summary = { "samples_done": total, "baseline_acc": baseline_correct / total if total else 0.0, "tvcd_acc": (tvcd_correct / total) if args.use_tvcd and total else None, "model_path": args.model_path, "dataset_json": args.dataset_json, "use_tvcd": args.use_tvcd, "cd_alpha": args.cd_alpha if args.use_tvcd else None, "cd_beta": args.cd_beta if args.use_tvcd else None, } with open(summary_path, "w") as f: json.dump(summary, f, indent=2, ensure_ascii=False) print(json.dumps(summary, ensure_ascii=False, indent=2))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164import osimport syssys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))os.environ["TOKENIZERS_PARALLELISM"] = "true"
import jsonimport shutilimport timefrom pathlib import Path
import torchimport torch.nn as nnfrom omegaconf import OmegaConffrom transformers import AutoTokenizer, AutoConfig
from train.utils import get_configfrom models import LlavaLLaDAModelLM
def _get_hidden_size(cfg): for k in ["hidden_size", "d_model", "n_embd", "embedding_size"]: if hasattr(cfg, k): return int(getattr(cfg, k)) raise ValueError("Cannot infer hidden size from config (expected one of hidden_size/d_model/n_embd/embedding_size).")
def _get_value_model(base_llm_class, value_head_prefix="value_head"): class ValueModel(base_llm_class): def __init__(self, config: AutoConfig): try: import deepspeed zero_off = deepspeed.zero.Init(enabled=False) except Exception: from contextlib import nullcontext zero_off = nullcontext()
with zero_off: super().__init__(config)
self.value_head_prefix = value_head_prefix hs = _get_hidden_size(config) vh = nn.Linear(hs, 1, bias=False) setattr(self, value_head_prefix, vh)
def forward(self, input_ids=None, inputs_embeds=None, attention_mask=None, **kwargs): kwargs.pop("labels", None) kwargs.pop("position_ids", None) outputs = self.model( input_ids=input_ids, inputs_embeds=inputs_embeds, attention_mask=attention_mask, output_hidden_states=True, return_dict=True, ) hidden = outputs.hidden_states[-1] return getattr(self, self.value_head_prefix)(hidden).squeeze(-1) return ValueModel
def save_checkpoint(model, tokenizer, config, name, accelerator=None): from pathlib import Path import json, shutil, os, glob, importlib, inspect, time
output_dir = Path(f"../{config.experiment.project}") output_dir.mkdir(parents=True, exist_ok=True)
def _is_main(): if accelerator is not None: return accelerator.is_main_process import torch.distributed as dist return (not dist.is_available()) or (not dist.is_initialized()) or dist.get_rank() == 0
is_main = _is_main()
checkpoints_total_limit = config.experiment.get("checkpoints_total_limit", None) if is_main and checkpoints_total_limit is not None: ckpts = sorted( [d for d in output_dir.iterdir() if d.name.startswith("checkpoint")], key=lambda p: int(p.name.split("-")[1]) if "-" in p.name else -1, ) if len(ckpts) >= checkpoints_total_limit: to_remove = ckpts[: len(ckpts) - checkpoints_total_limit + 1] for p in to_remove: shutil.rmtree(p, ignore_errors=True)
save_base = output_dir / "ckpt" save_base.mkdir(exist_ok=True)
if accelerator is not None: model_to_save = accelerator.unwrap_model(model) state_dict = accelerator.get_state_dict(model) save_function = accelerator.save else: model_to_save = model state_dict = model.state_dict() save_function = None
if is_main: save_dir = save_base / name model_to_save.save_pretrained( save_dir, state_dict=state_dict, safe_serialization=True, save_function=save_function, ) tokenizer.save_pretrained(str(save_dir))
def _copy_dynamic_modules(dst_dir, model_obj, tok_obj): copied = 0 modules = set() for obj in [model_obj, getattr(model_obj, "config", None), tok_obj]: if obj is None: continue modname = getattr(obj.__class__, "__module__", None) if modname: modules.add(modname)
for modname in modules: try: mod = importlib.import_module(modname) src_file = inspect.getsourcefile(mod) if not src_file or not os.path.exists(src_file): continue base_dir = os.path.dirname(src_file) for pattern in ("modeling_*.py", "configuration_*.py", "tokenization_*.py", "processing_*.py"): for fn in glob.glob(os.path.join(base_dir, pattern)): dst = os.path.join(dst_dir, os.path.basename(fn)) if not os.path.exists(dst): shutil.copy2(fn, dst) copied += 1 except Exception: pass
_copy_dynamic_modules(str(save_dir), model_to_save, tokenizer)
metadata = {"save_time": time.strftime("%Y-%m-%d %H:%M:%S")} with (save_base / "metadata.json").open("w") as f: json.dump(metadata, f, indent=2)
if accelerator is None: import torch.distributed as dist if dist.is_available() and dist.is_initialized(): dist.barrier()
def main(): config = get_config() pretrained_model = config.model.value_base_model
value_model_class = _get_value_model(LlavaLLaDAModelLM, "value_head")
tokenizer = AutoTokenizer.from_pretrained(pretrained_model, trust_remote_code=True) value_model = value_model_class.from_pretrained(pretrained_model, trust_remote_code=True, torch_dtype="auto")
with torch.no_grad(): getattr(value_model, "value_head").weight.zero_()
save_checkpoint(value_model, tokenizer, config, config.model.optimized_value_name)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162import osimport syssys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))os.environ["TOKENIZERS_PARALLELISM"] = "true"
import jsonimport shutilimport timefrom pathlib import Path
import torchimport torch.nn as nnfrom omegaconf import OmegaConffrom transformers import AutoTokenizer, AutoConfig
from train.utils import get_configfrom models import MMadaModelLM
def _get_hidden_size(cfg): for k in ["hidden_size", "d_model", "n_embd", "embedding_size"]: if hasattr(cfg, k): return int(getattr(cfg, k)) raise ValueError("Cannot infer hidden size from config (expected one of hidden_size/d_model/n_embd/embedding_size).")
def _get_value_model(base_llm_class, value_head_prefix="value_head"): class ValueModel(base_llm_class): def __init__(self, config: AutoConfig): try: import deepspeed zero_off = deepspeed.zero.Init(enabled=False) except Exception: from contextlib import nullcontext zero_off = nullcontext()
with zero_off: super().__init__(config)
self.value_head_prefix = value_head_prefix hs = _get_hidden_size(config) vh = nn.Linear(hs, 1, bias=False) setattr(self, value_head_prefix, vh)
def forward(self, input_ids=None, attention_mask=None, **kwargs): kwargs.pop("labels", None) outputs = super().forward( input_ids=input_ids, output_hidden_states=True, return_dict=True, ) hidden = outputs.hidden_states[-1] # (B, T, H) return getattr(self, self.value_head_prefix)(hidden).squeeze(-1) # (B, T)
return ValueModel
def save_checkpoint(model, tokenizer, config, name, accelerator=None): from pathlib import Path import json, shutil, os, glob, importlib, inspect, time
# train/ 下运行,向上一级保存到 ../{project} output_dir = Path(f"../{config.experiment.project}") output_dir.mkdir(parents=True, exist_ok=True)
def _is_main(): if accelerator is not None: return accelerator.is_main_process import torch.distributed as dist return (not dist.is_available()) or (not dist.is_initialized()) or dist.get_rank() == 0
is_main = _is_main()
checkpoints_total_limit = config.experiment.get("checkpoints_total_limit", None) if is_main and checkpoints_total_limit is not None: ckpts = sorted( [d for d in output_dir.iterdir() if d.name.startswith("checkpoint")], key=lambda p: int(p.name.split("-")[1]) if "-" in p.name else -1, ) if len(ckpts) >= checkpoints_total_limit: to_remove = ckpts[: len(ckpts) - checkpoints_total_limit + 1] for p in to_remove: shutil.rmtree(p, ignore_errors=True)
save_base = output_dir / "ckpt" save_base.mkdir(exist_ok=True)
if accelerator is not None: model_to_save = accelerator.unwrap_model(model) state_dict = accelerator.get_state_dict(model) save_function = accelerator.save else: model_to_save = model state_dict = model.state_dict() save_function = None
if is_main: save_dir = save_base / name model_to_save.save_pretrained( save_dir, state_dict=state_dict, safe_serialization=True, save_function=save_function, ) tokenizer.save_pretrained(str(save_dir))
def _copy_dynamic_modules(dst_dir, model_obj, tok_obj): copied = 0 modules = set() for obj in [model_obj, getattr(model_obj, "config", None), tok_obj]: if obj is None: continue modname = getattr(obj.__class__, "__module__", None) if modname: modules.add(modname)
for modname in modules: try: mod = importlib.import_module(modname) src_file = inspect.getsourcefile(mod) if not src_file or not os.path.exists(src_file): continue base_dir = os.path.dirname(src_file) for pattern in ("modeling_*.py", "configuration_*.py", "tokenization_*.py", "processing_*.py"): for fn in glob.glob(os.path.join(base_dir, pattern)): dst = os.path.join(dst_dir, os.path.basename(fn)) if not os.path.exists(dst): shutil.copy2(fn, dst) copied += 1 except Exception: pass
_copy_dynamic_modules(str(save_dir), model_to_save, tokenizer)
metadata = {"save_time": time.strftime("%Y-%m-%d %H:%M:%S")} with (save_base / "metadata.json").open("w") as f: json.dump(metadata, f, indent=2)
if accelerator is None: import torch.distributed as dist if dist.is_available() and dist.is_initialized(): dist.barrier()
def main(): config = get_config() pretrained_model = config.model.value_base_model
value_model_class = _get_value_model(MMadaModelLM, "value_head")
tokenizer = AutoTokenizer.from_pretrained(pretrained_model, trust_remote_code=True) value_model = value_model_class.from_pretrained(pretrained_model, trust_remote_code=True, torch_dtype="auto")
with torch.no_grad(): getattr(value_model, "value_head").weight.zero_()
save_checkpoint(value_model, tokenizer, config, config.model.optimized_value_name)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194import osimport syssys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))os.environ["TOKENIZERS_PARALLELISM"] = "true"import jsonimport loggingimport mathimport shutilimport timefrom pathlib import Pathfrom typing import Optional, Tuple, Union
import numpy as npfrom PIL import Imagefrom omegaconf import OmegaConfimport wandbimport torchfrom torch.optim import AdamWimport torch.nn as nn
from transformers import AutoTokenizer, AutoConfigfrom accelerate import Acceleratorfrom accelerate.utils import DistributedType, set_seed
from transformers import AutoModelForCausalLM, AutoTokenizerfrom train.prompting_utils import UniversalPromptingfrom models.lr_schedulers import get_schedulerfrom models.logging import set_verbosity_info, set_verbosity_error
from torch.utils.data import Dataset, DataLoader
SYSTEM_PROMPT_LEN = 28
from train.utils import get_config, flatten_omega_conf, AverageMeter
try: import apex
is_apex_available = Trueexcept ImportError: is_apex_available = False
def _get_value_model(base_llm_class, value_head_prefix="value_head"): class ValueModel(base_llm_class): def __init__(self, config: AutoConfig): try: import deepspeed zero_off = deepspeed.zero.Init(enabled=False) except Exception: from contextlib import nullcontext zero_off = nullcontext()
with zero_off: super().__init__(config)
self.value_head_prefix = value_head_prefix vh = nn.Linear(config.hidden_size, 1, bias=False) setattr(self, value_head_prefix, vh)
def forward(self, input_ids=None, attention_mask=None, position_ids=None, **kwargs): outputs = self.model( input_ids, attention_mask=attention_mask, position_ids=position_ids, **kwargs ) last_hidden_states = outputs["last_hidden_state"] return getattr(self, self.value_head_prefix)(last_hidden_states).squeeze(-1)
return ValueModel
def main(): config = get_config()
pretrained_model = config.model.value_base_model
from transformers import AutoConfig from models import SDARForCausalLM value_model_class = _get_value_model(SDARForCausalLM, "value_head")
tokenizer = AutoTokenizer.from_pretrained(pretrained_model, trust_remote_code=True) value_model = value_model_class.from_pretrained(pretrained_model, trust_remote_code=True, torch_dtype="auto")
with torch.no_grad(): getattr(value_model, "value_head").weight.zero_()
save_checkpoint(value_model, tokenizer, config, config.model.optimized_value_name)
def save_checkpoint(model, tokenizer, config, name, accelerator=None): from pathlib import Path import time, json, shutil, os, glob, importlib, inspect import torch
output_dir = Path(f"../{config.experiment.project}") output_dir.mkdir(parents=True, exist_ok=True)
def _is_main(): if accelerator is not None: return accelerator.is_main_process import torch.distributed as dist return (not dist.is_available()) or (not dist.is_initialized()) or dist.get_rank() == 0
is_main = _is_main()
checkpoints_total_limit = config.experiment.get("checkpoints_total_limit", None) if is_main and checkpoints_total_limit is not None: ckpts = sorted( [d for d in output_dir.iterdir() if d.name.startswith("checkpoint")], key=lambda p: int(p.name.split("-")[1]) if "-" in p.name else -1, ) if len(ckpts) >= checkpoints_total_limit: to_remove = ckpts[: len(ckpts) - checkpoints_total_limit + 1] for p in to_remove: shutil.rmtree(p, ignore_errors=True)
save_base = output_dir / "ckpt" save_base.mkdir(exist_ok=True)
if accelerator is not None: model_to_save = accelerator.unwrap_model(model) state_dict = accelerator.get_state_dict(model) save_function = accelerator.save else: model_to_save = model state_dict = model.state_dict() save_function = None
if is_main: save_dir = save_base / name model_to_save.save_pretrained( save_dir, state_dict=state_dict, safe_serialization=True, save_function=save_function, ) tokenizer.save_pretrained(str(save_dir))
def _copy_dynamic_modules(dst_dir, model_obj, tok_obj): copied = 0 modules = set() for obj in [model_obj, getattr(model_obj, "config", None), tok_obj]: if obj is None: continue modname = getattr(obj.__class__, "__module__", None) if modname: modules.add(modname)
for modname in modules: try: mod = importlib.import_module(modname) src_file = inspect.getsourcefile(mod) if not src_file or not os.path.exists(src_file): continue base_dir = os.path.dirname(src_file) for pattern in ("modeling_*.py", "configuration_*.py", "tokenization_*.py", "processing_*.py"): for fn in glob.glob(os.path.join(base_dir, pattern)): dst = os.path.join(dst_dir, os.path.basename(fn)) if not os.path.exists(dst): shutil.copy2(fn, dst) copied += 1 except Exception as e: pass
_copy_dynamic_modules(str(save_dir), model_to_save, tokenizer)
metadata = {"save_time": time.strftime("%Y-%m-%d %H:%M:%S")} with (save_base / "metadata.json").open("w") as f: json.dump(metadata, f, indent=2)
if accelerator is None: import torch.distributed as dist if dist.is_available() and dist.is_initialized(): dist.barrier()
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194import osimport syssys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))os.environ["TOKENIZERS_PARALLELISM"] = "true"import jsonimport loggingimport mathimport shutilimport timefrom pathlib import Pathfrom typing import Optional, Tuple, Union
import numpy as npfrom PIL import Imagefrom omegaconf import OmegaConfimport wandbimport torchfrom torch.optim import AdamWimport torch.nn as nn
from transformers import AutoTokenizer, AutoConfigfrom accelerate import Acceleratorfrom accelerate.utils import DistributedType, set_seed
from transformers import AutoModelForCausalLM, AutoTokenizerfrom train.prompting_utils import UniversalPromptingfrom models.lr_schedulers import get_schedulerfrom models.logging import set_verbosity_info, set_verbosity_error
from torch.utils.data import Dataset, DataLoader
SYSTEM_PROMPT_LEN = 28
from train.utils import get_config, flatten_omega_conf, AverageMeter
try: import apex
is_apex_available = Trueexcept ImportError: is_apex_available = False
def _get_value_model(base_llm_class, value_head_prefix="value_head"): class ValueModel(base_llm_class): def __init__(self, config: AutoConfig): try: import deepspeed zero_off = deepspeed.zero.Init(enabled=False) except Exception: from contextlib import nullcontext zero_off = nullcontext()
with zero_off: super().__init__(config)
self.value_head_prefix = value_head_prefix vh = nn.Linear(config.hidden_size, 1, bias=False) setattr(self, value_head_prefix, vh)
def forward(self, input_ids=None, attention_mask=None, position_ids=None, **kwargs): outputs = self.model( input_ids, attention_mask=attention_mask, position_ids=position_ids, **kwargs ) last_hidden_states = outputs["last_hidden_state"] return getattr(self, self.value_head_prefix)(last_hidden_states).squeeze(-1)
return ValueModel
def main(): config = get_config()
pretrained_model = config.model.value_base_model
from transformers import AutoConfig from models import SDARForCausalLM value_model_class = _get_value_model(SDARForCausalLM, "value_head")
tokenizer = AutoTokenizer.from_pretrained(pretrained_model, trust_remote_code=True) value_model = value_model_class.from_pretrained(pretrained_model, trust_remote_code=True, torch_dtype="auto")
with torch.no_grad(): getattr(value_model, "value_head").weight.zero_()
save_checkpoint(value_model, tokenizer, config, config.model.optimized_value_name)
def save_checkpoint(model, tokenizer, config, name, accelerator=None): from pathlib import Path import time, json, shutil, os, glob, importlib, inspect import torch
output_dir = Path(f"../{config.experiment.project}") output_dir.mkdir(parents=True, exist_ok=True)
def _is_main(): if accelerator is not None: return accelerator.is_main_process import torch.distributed as dist return (not dist.is_available()) or (not dist.is_initialized()) or dist.get_rank() == 0
is_main = _is_main()
checkpoints_total_limit = config.experiment.get("checkpoints_total_limit", None) if is_main and checkpoints_total_limit is not None: ckpts = sorted( [d for d in output_dir.iterdir() if d.name.startswith("checkpoint")], key=lambda p: int(p.name.split("-")[1]) if "-" in p.name else -1, ) if len(ckpts) >= checkpoints_total_limit: to_remove = ckpts[: len(ckpts) - checkpoints_total_limit + 1] for p in to_remove: shutil.rmtree(p, ignore_errors=True)
save_base = output_dir / "ckpt" save_base.mkdir(exist_ok=True)
if accelerator is not None: model_to_save = accelerator.unwrap_model(model) state_dict = accelerator.get_state_dict(model) save_function = accelerator.save else: model_to_save = model state_dict = model.state_dict() save_function = None
if is_main: save_dir = save_base / name model_to_save.save_pretrained( save_dir, state_dict=state_dict, safe_serialization=True, save_function=save_function, ) tokenizer.save_pretrained(str(save_dir))
def _copy_dynamic_modules(dst_dir, model_obj, tok_obj): copied = 0 modules = set() for obj in [model_obj, getattr(model_obj, "config", None), tok_obj]: if obj is None: continue modname = getattr(obj.__class__, "__module__", None) if modname: modules.add(modname)
for modname in modules: try: mod = importlib.import_module(modname) src_file = inspect.getsourcefile(mod) if not src_file or not os.path.exists(src_file): continue base_dir = os.path.dirname(src_file) for pattern in ("modeling_*.py", "configuration_*.py", "tokenization_*.py", "processing_*.py"): for fn in glob.glob(os.path.join(base_dir, pattern)): dst = os.path.join(dst_dir, os.path.basename(fn)) if not os.path.exists(dst): shutil.copy2(fn, dst) copied += 1 except Exception as e: pass
_copy_dynamic_modules(str(save_dir), model_to_save, tokenizer)
metadata = {"save_time": time.strftime("%Y-%m-%d %H:%M:%S")} with (save_base / "metadata.json").open("w") as f: json.dump(metadata, f, indent=2)
if accelerator is None: import torch.distributed as dist if dist.is_available() and dist.is_initialized(): dist.barrier()
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283import torchfrom collections import defaultdict
class Singleton(type): _instances = {}
def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls]
class dLLMCache(metaclass=Singleton): gen_interval_steps: int prompt_interval_steps: int cfg_interval_steps: int prompt_length: int transfer_ratio: float __cache: defaultdict __step_counter: defaultdict
@classmethod def new_instance( cls, prompt_interval_steps: int = 1, gen_interval_steps: int = 1, cfg_interval_steps: int = 1, transfer_ratio: float = 0.0, ) -> "dLLMCache": ins = cls() setattr(ins, "prompt_interval_steps", prompt_interval_steps) setattr(ins, "gen_interval_steps", gen_interval_steps) setattr(ins, "cfg_interval_steps", cfg_interval_steps) setattr(ins, "transfer_ratio", transfer_ratio) ins.init() return ins
def init(self) -> None: self.__cache = defaultdict( lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(dict))) ) self.__step_counter = defaultdict(lambda: defaultdict(lambda: 0))
def reset_cache(self, prompt_length: int = 0) -> None: self.init() torch.cuda.empty_cache() self.prompt_length = prompt_length self.cache_type = "no_cfg"
def set_cache( self, layer_id: int, feature_name: str, features: torch.Tensor, cache_type: str ) -> None: self.__cache[self.cache_type][cache_type][layer_id][feature_name] = { 0: features }
def get_cache( self, layer_id: int, feature_name: str, cache_type: str ) -> torch.Tensor: output = self.__cache[self.cache_type][cache_type][layer_id][feature_name][0] return output
def update_step(self, layer_id: int) -> None: self.__step_counter[self.cache_type][layer_id] += 1
def refresh_gen(self, layer_id: int = 0) -> bool: return (self.current_step - 1) % self.gen_interval_steps == 0
def refresh_prompt(self, layer_id: int = 0) -> bool: return (self.current_step - 1) % self.prompt_interval_steps == 0
def refresh_cfg(self, layer_id: int = 0) -> bool: return ( self.current_step - 1 ) % self.cfg_interval_steps == 0 or self.current_step <= 5
@property def current_step(self) -> int: return max(list(self.__step_counter[self.cache_type].values()), default=1)
def __repr__(self): return f"USE dLLMCache"123456789from dataclasses import dataclass
@dataclassclass dLLMCacheConfig: prompt_interval_steps: int = 1 gen_interval_steps: int = 1 transfer_ratio: float = 0.0 cfg_interval_steps: int = 11234from .Cache import dLLMCachefrom .Config import dLLMCacheConfig
__all__ = ["dLLMCache", "dLLMCacheConfig"]123456789101112CONTROLLER_HEART_BEAT_EXPIRATION = 30WORKER_HEART_BEAT_INTERVAL = 15
LOGDIR = "."
# Model ConstantsIGNORE_INDEX = -100IMAGE_TOKEN_INDEX = -200DEFAULT_IMAGE_TOKEN = "<image>"DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"DEFAULT_IM_START_TOKEN = "<im_start>"DEFAULT_IM_END_TOKEN = "<im_end>"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624import dataclassesfrom enum import auto, Enumfrom typing import List, Any, Dict, Union, Tupleimport reimport base64from io import BytesIOfrom PIL import Imagefrom transformers import AutoTokenizer
class SeparatorStyle(Enum): """Different separator style."""
SINGLE = auto() TWO = auto() MPT = auto() PLAIN = auto() CHATML = auto() LLAMA_2 = auto() LLAMA_3 = auto() QWEN = auto() GEMMA = auto()
@dataclasses.dataclassclass Conversation: """A class that keeps all conversation history."""
system: str roles: List[str] messages: List[List[str]] offset: int sep_style: SeparatorStyle = SeparatorStyle.SINGLE sep: str = "###" sep2: str = None version: str = "Unknown"
tokenizer_id: str = "" tokenizer: Any = None # Stop criteria (the default one is EOS token) stop_str: Union[str, List[str]] = None # Stops generation if meeting any token in this list stop_token_ids: List[int] = None
skip_next: bool = False
def get_prompt(self): messages = self.messages if len(messages) > 0 and type(messages[0][1]) is tuple: messages = self.messages.copy() init_role, init_msg = messages[0].copy() init_msg = init_msg[0] if "mmtag" in self.version: init_msg = init_msg.replace("<image>", "").strip() messages[0] = (init_role, init_msg) messages.insert(0, (self.roles[0], "<Image><image></Image>")) messages.insert(1, (self.roles[1], "Received.")) elif not init_msg.startswith("<image>"): init_msg = init_msg.replace("<image>", "").strip() messages[0] = (init_role, "<image>\n" + init_msg) else: messages[0] = (init_role, init_msg)
if self.sep_style == SeparatorStyle.SINGLE: ret = self.system + self.sep for role, message in messages: if message: if type(message) is tuple: message, _, _ = message ret += role + ": " + message + self.sep else: ret += role + ":"
elif self.sep_style == SeparatorStyle.TWO: seps = [self.sep, self.sep2] ret = self.system + seps[0] for i, (role, message) in enumerate(messages): if message: if type(message) is tuple: message, _, _ = message ret += role + ": " + message + seps[i % 2] else: ret += role + ":"
elif self.sep_style == SeparatorStyle.CHATML: ret = "" if self.system == "" else self.system + self.sep + "\n" for role, message in messages: if message: if type(message) is tuple: message, images, _ = message message = "<image>" * len(images) + message ret += role + "\n" + message + self.sep + "\n" else: ret += role + "\n" return ret
elif self.sep_style == SeparatorStyle.LLAMA_3: if self.tokenizer is None: if self.version == "llama_v3": self.tokenizer = AutoTokenizer.from_pretrained('meta-llama/Meta-Llama-3-8B-Instruct', trust_remote_code=True) elif self.version == "llava_llada": self.tokenizer = AutoTokenizer.from_pretrained('/data4/runqing/dLLM-RL/LLaDA-V', trust_remote_code=True) else: raise ValueError("The tokenizer is not available. Make sure you have the necessary permissions.") chat_template_messages = [{"role": "system", "content": self.system}] for role, message in messages: if message: if type(message) is tuple: message, images = message message = "<image>" * len(images) + message chat_template_messages.append({"role": role, "content": message})
# print(chat_template_messages) return self.tokenizer.apply_chat_template(chat_template_messages, tokenize=False, add_generation_prompt=True) # ret = "" if self.system == "" else self.system + self.sep + "\n" # for role, message in messages: # if message: # if type(message) is tuple: # message, images = message # message = "<image>" * len(images) + message # ret += role + "\n" + message + self.sep + "\n" # else: # ret += role + "\n" # return ret
elif self.sep_style == SeparatorStyle.MPT: ret = self.system + self.sep for role, message in messages: if message: if type(message) is tuple: message, _, _ = message ret += role + message + self.sep else: ret += role
elif self.sep_style == SeparatorStyle.GEMMA: ret = "" for i, (role, message) in enumerate(messages): assert role == self.roles[i % 2], "Conversation should alternate user/assistant/user/assistant/..." if message: if type(message) is tuple: message, _, _ = message ret += role + message + self.sep else: ret += role
elif self.sep_style == SeparatorStyle.LLAMA_2: wrap_sys = lambda msg: f"<<SYS>>\n{msg}\n<</SYS>>\n\n" if len(msg) > 0 else msg wrap_inst = lambda msg: f"[INST] {msg} [/INST]" ret = ""
for i, (role, message) in enumerate(messages): if i == 0: assert message, "first message should not be none" assert role == self.roles[0], "first message should come from user" if message: if type(message) is tuple: message, _, _ = message if i == 0: message = wrap_sys(self.system) + message if i % 2 == 0: message = wrap_inst(message) ret += self.sep + message else: ret += " " + message + " " + self.sep2 else: ret += "" ret = ret.lstrip(self.sep)
elif self.sep_style == SeparatorStyle.PLAIN: seps = [self.sep, self.sep2] ret = self.system for i, (role, message) in enumerate(messages): if message: if type(message) is tuple: message, _, _ = message ret += message + seps[i % 2] else: ret += "" else: raise ValueError(f"Invalid style: {self.sep_style}")
return ret
def append_message(self, role, message): self.messages.append([role, message])
def process_image(self, image, image_process_mode, return_pil=False, image_format="PNG"): if image_process_mode == "Pad":
def expand2square(pil_img, background_color=(122, 116, 104)): width, height = pil_img.size if width == height: return pil_img elif width > height: result = Image.new(pil_img.mode, (width, width), background_color) result.paste(pil_img, (0, (width - height) // 2)) return result else: result = Image.new(pil_img.mode, (height, height), background_color) result.paste(pil_img, ((height - width) // 2, 0)) return result
image = expand2square(image) elif image_process_mode in ["Default", "Crop"]: pass elif image_process_mode == "Resize": image = image.resize((336, 336)) else: raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
if type(image) is not Image.Image: image = Image.open(image).convert("RGB")
max_hw, min_hw = max(image.size), min(image.size) aspect_ratio = max_hw / min_hw max_len, min_len = 672, 448 shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw)) longest_edge = int(shortest_edge * aspect_ratio) W, H = image.size if H > W: H, W = longest_edge, shortest_edge else: H, W = shortest_edge, longest_edge image = image.resize((W, H)) if return_pil: return image else: buffered = BytesIO() image.save(buffered, format=image_format) img_b64_str = base64.b64encode(buffered.getvalue()).decode() return img_b64_str
def get_images(self, return_pil=False, return_path=False): images = [] for i, (role, msg) in enumerate(self.messages[self.offset :]): if i % 2 == 0: if type(msg) is tuple: msg, image, image_process_mode = msg if type(image) != list: image = [image] for img in image: if not return_path and self.is_image_file(img): img = self.process_image(img, image_process_mode, return_pil=return_pil) else: images.append(img) return images
def is_image_file(self, filename): image_extensions = [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff", ".webp"] return any(filename.lower().endswith(ext) for ext in image_extensions)
def is_video_file(self, filename): video_extensions = [".mp4", ".mov", ".avi", ".mkv", ".wmv", ".flv", ".mpeg", ".mpg"] return any(filename.lower().endswith(ext) for ext in video_extensions)
def to_gradio_chatbot(self): ret = [] for i, (role, msg) in enumerate(self.messages[self.offset :]): if i % 2 == 0: if type(msg) is tuple: msg, image, image_process_mode = msg if type(image) != list: image = [image] if len(image) == 1: msg = "<image>\n" + msg.replace("<image>", "").strip() else: msg = re.sub(r"(<image>)\n(?=<image>)", r"\1 ", msg)
img_str_list = [] for img in image: if self.is_image_file(img): img_b64_str = self.process_image(img, "Default", return_pil=False, image_format="JPEG") img_str = f'<img src="data:image/jpeg;base64,{img_b64_str}" style="max-width: 256px; max-height: 256px; width: auto; height: auto; object-fit: contain;"/>' img_str_list.append(img_str) elif self.is_video_file(img): ret.append(((img,), None))
msg = msg.strip() img_place_holder = "" for img_str in img_str_list: img_place_holder += f"{img_str}\n\n"
if len(img_str_list) > 0: msg = f"{img_place_holder}\n\n{msg}"
if len(msg) > 0: ret.append([msg, None]) else: ret.append([msg, None]) else: ret[-1][-1] = msg return ret
def copy(self): return Conversation(system=self.system, roles=self.roles, messages=[[x, y] for x, y in self.messages], offset=self.offset, sep_style=self.sep_style, sep=self.sep, sep2=self.sep2, version=self.version)
def dict(self): if len(self.get_images()) > 0: return { "system": self.system, "roles": self.roles, "messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages], "offset": self.offset, "sep": self.sep, "sep2": self.sep2, } return { "system": self.system, "roles": self.roles, "messages": self.messages, "offset": self.offset, "sep": self.sep, "sep2": self.sep2, }
conv_vicuna_v0 = Conversation( system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.", roles=("Human", "Assistant"), messages=[ ["Human", "What are the key differences between renewable and non-renewable energy sources?"], [ "Assistant", "Renewable energy sources are those that can be replenished naturally in a relatively " "short amount of time, such as solar, wind, hydro, geothermal, and biomass. " "Non-renewable energy sources, on the other hand, are finite and will eventually be " "depleted, such as coal, oil, and natural gas. Here are some key differences between " "renewable and non-renewable energy sources:\n" "1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable " "energy sources are finite and will eventually run out.\n" "2. Environmental impact: Renewable energy sources have a much lower environmental impact " "than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, " "and other negative effects.\n" "3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically " "have lower operational costs than non-renewable sources.\n" "4. Reliability: Renewable energy sources are often more reliable and can be used in more remote " "locations than non-renewable sources.\n" "5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different " "situations and needs, while non-renewable sources are more rigid and inflexible.\n" "6. Sustainability: Renewable energy sources are more sustainable over the long term, while " "non-renewable sources are not, and their depletion can lead to economic and social instability.\n", ], ], offset=2, sep_style=SeparatorStyle.SINGLE, sep="###",)
conv_vicuna_v1 = Conversation( system="A chat between a curious user and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the user's questions.", roles=("USER", "ASSISTANT"), version="v1", messages=[], offset=0, sep_style=SeparatorStyle.TWO, sep=" ", sep2="</s>",)
conv_llama_2 = Conversation( system="""You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.""", roles=("USER", "ASSISTANT"), version="llama_v2", messages=[], offset=0, sep_style=SeparatorStyle.LLAMA_2, sep="<s>", sep2="</s>",)
conv_llava_llama_2 = Conversation( system="You are a helpful language and vision assistant. " "You are able to understand the visual content that the user provides, " "and assist the user with a variety of tasks using natural language.", roles=("USER", "ASSISTANT"), version="llama_v2", messages=[], offset=0, sep_style=SeparatorStyle.LLAMA_2, sep="<s>", sep2="</s>",)
def safe_load_tokenizer(tokenizer_id): try: return AutoTokenizer.from_pretrained(tokenizer_id) except Exception: return None
conv_llava_llama_3 = Conversation( system="You are a helpful language and vision assistant. " "You are able to understand the visual content that the user provides, " "and assist the user with a variety of tasks using natural language.", roles=("user", "assistant"), version="llama_v3", messages=[], offset=0, sep="<|eot_id|>", sep_style=SeparatorStyle.LLAMA_3, tokenizer_id="meta-llama/Meta-Llama-3-8B-Instruct", tokenizer=safe_load_tokenizer("/data_storage/lbw/shared/pretrained_models/Meta-Llama-3-8B-Instruct"), stop_token_ids=[128009],)
conv_mistral_instruct = Conversation( system="", roles=("USER", "ASSISTANT"), version="llama_v2", messages=[], offset=0, sep_style=SeparatorStyle.LLAMA_2, sep="", sep2="</s>",)
conv_llava_llama_2_simple = Conversation( system="Answer the questions about the visual content that the user provides.", roles=("USER", "ASSISTANT"), version="llama_v2", messages=[], offset=0, sep_style=SeparatorStyle.LLAMA_2, sep="<s>", sep2="</s>",)
conv_llava_llama_2_mmtag = Conversation( system="Answer the questions about the visual content that the user provides." "The visual content will be provided with the following format: <Image>visual content</Image>.", roles=("USER", "ASSISTANT"), version="llama_v2_mmtag", messages=[], offset=0, sep_style=SeparatorStyle.LLAMA_2, sep="<s>", sep2="</s>",)
conv_mpt = Conversation( system="""<|im_start|>systemA conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""", roles=("<|im_start|>user\n", "<|im_start|>assistant\n"), version="mpt", messages=[], offset=0, sep_style=SeparatorStyle.MPT, sep="<|im_end|>",)
conv_qwen = Conversation( system="""<|im_start|>systemYou are a helpful assistant.""", roles=("<|im_start|>user", "<|im_start|>assistant"), version="qwen", messages=[], offset=0, sep_style=SeparatorStyle.CHATML, sep="<|im_end|>",)
conv_qwen_2_5 = Conversation( system="""<|im_start|>systemYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.""", roles=("<|im_start|>user", "<|im_start|>assistant"), version="qwen", messages=[], offset=0, sep_style=SeparatorStyle.CHATML, sep="<|im_end|>",)
conv_gemma_instruct = Conversation(system="", roles=("<start_of_turn>user\n", "<start_of_turn>model\n"), version="gemma", messages=[], offset=0, sep_style=SeparatorStyle.GEMMA, sep="<end_of_turn>\n")
conv_llava_plain = Conversation( system="", roles=("", ""), messages=[], offset=0, sep_style=SeparatorStyle.PLAIN, sep="\n",)
conv_llada_plain = Conversation( system="", roles=("", ""), messages=[], version="llada_plain", offset=0, sep_style=SeparatorStyle.LLAMA_3, sep="\n",)
conv_llava_llada = Conversation( system="You are a helpful language and vision assistant. " "You are able to understand the visual content that the user provides, " "and assist the user with a variety of tasks using natural language.", roles=("user", "assistant"), version="llava_llada", messages=[], offset=0, sep="<|eot_id|>", sep_style=SeparatorStyle.LLAMA_3,)
conv_llava_v0 = Conversation( system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.", roles=("Human", "Assistant"), messages=[], offset=0, sep_style=SeparatorStyle.SINGLE, sep="###",)
conv_llava_v0_mmtag = Conversation( system="A chat between a curious user and an artificial intelligence assistant. " "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language." "The visual content will be provided with the following format: <Image>visual content</Image>.", roles=("Human", "Assistant"), messages=[], offset=0, sep_style=SeparatorStyle.SINGLE, sep="###", version="v0_mmtag",)
conv_llava_v1 = Conversation( system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.", roles=("USER", "ASSISTANT"), version="v1", messages=[], offset=0, sep_style=SeparatorStyle.TWO, sep=" ", sep2="</s>",)
conv_llava_v1_mmtag = Conversation( system="A chat between a curious user and an artificial intelligence assistant. " "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language." "The visual content will be provided with the following format: <Image>visual content</Image>.", roles=("USER", "ASSISTANT"), messages=[], offset=0, sep_style=SeparatorStyle.TWO, sep=" ", sep2="</s>", version="v1_mmtag",)
conv_mistral_orca = Conversation( system="""<|im_start|>systemYou are MistralOrca, a large language model trained by Alignment Lab AI. Write out your reasoning step-by-step to be sure you get the right answers!""", roles=("<|im_start|>user\n", "<|im_start|>assistant\n"), version="mpt", messages=[], offset=0, sep_style=SeparatorStyle.MPT, sep="<|im_end|>",)
conv_mistral_zephyr = Conversation( system="""<|system|>You are a helpful AI assistant.""", roles=("<|user|>\n", "<|assistant|>\n"), version="mpt", messages=[], offset=0, sep_style=SeparatorStyle.MPT, sep="</s>",)
conv_mistral_direct = Conversation( system="""<|im_start|>systemAnswer the questions.""", roles=("<|im_start|>user\n", "<|im_start|>assistant\n"), version="mpt", messages=[], offset=0, sep_style=SeparatorStyle.MPT, sep="<|im_end|>",)
conv_chatml_direct = Conversation( system="""<|im_start|>systemAnswer the questions.""", roles=("<|im_start|>user\n", "<|im_start|>assistant\n"), version="mpt", messages=[], offset=0, sep_style=SeparatorStyle.MPT, sep="<|im_end|>",)
default_conversation = conv_vicuna_v0conv_templates = { "default": conv_vicuna_v0, "v0": conv_vicuna_v0, "v1": conv_vicuna_v1, "vicuna_v1": conv_vicuna_v1, "llama_2": conv_llama_2, "mistral_instruct": conv_mistral_instruct, "mistral_orca": conv_mistral_orca, "mistral_zephyr": conv_mistral_zephyr, "mistral_direct": conv_mistral_direct, "plain": conv_llava_plain, "llada_plain": conv_llada_plain, "llava_llada": conv_llava_llada, "v0_plain": conv_llava_plain, "chatml_direct": conv_chatml_direct, "llava_v0": conv_llava_v0, "llava_v0_mmtag": conv_llava_v0_mmtag, "llava_v1": conv_llava_v1, "llava_v1_mmtag": conv_llava_v1_mmtag, "llava_llama_2": conv_llava_llama_2, "llava_llama_3": conv_llava_llama_3, "llava_llama_2_simple": conv_llava_llama_2_simple, "llava_llama_2_mmtag": conv_llava_llama_2_mmtag, "llava_mistral_instruct": conv_mistral_instruct, "mpt": conv_mpt, "qwen_1_5": conv_qwen, "qwen_2": conv_qwen, "qwen_2_5": conv_qwen_2_5, "gemma_instruct": conv_gemma_instruct,}
if __name__ == "__main__": print(default_conversation.get_prompt())123456from .cache_hook_LLaDA_V import register_cache_LLaDA_V
__all__ = [ "register_cache_LLaDA_V", "logout_cache_LLaDA_V",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619import torchfrom typing import Optional, Tuple, List import torch.nn as nnimport typesfrom llava.cache import dLLMCache import math
# Helper functions from the new LLADa model (need to be accessible)def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1)
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): cos = cos.unsqueeze(unsqueeze_dim) sin = sin.unsqueeze(unsqueeze_dim) q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed# --- End of imports/helpers from new LLaDA model ---
def register_cache_LLaDA_V(model: nn.Module, tf_block_module_key_name: str) -> None: """ Registers cache hooks for a LLaDA-like model. tf_block_module_key_name is typically 'model.layers' for LLaMA-style models. """ target_module_path = tf_block_module_key_name.split('.') current_module = model for part in target_module_path: current_module = getattr(current_module, part) target_module: Optional[nn.ModuleList] = current_module if target_module is None or not isinstance(target_module, nn.ModuleList): raise ValueError(f"Could not find nn.ModuleList at {tf_block_module_key_name}")
for layer_index, tf_block in enumerate(target_module): setattr(tf_block, "layer_idx", layer_index)
setattr(tf_block, "_old_forward", tf_block.forward) tf_block.forward = types.MethodType(llada_cache_hook_feature, tf_block)
setattr(tf_block.self_attn, "_old_forward_main", tf_block.self_attn.forward) tf_block.self_attn.attention_forward_for_cache = types.MethodType( llada_attention_hook_for_cache, tf_block.self_attn )
setattr(tf_block.self_attn.rotary_emb, "_old_forward", tf_block.self_attn.rotary_emb.forward) tf_block.self_attn.rotary_emb.forward = types.MethodType( llada_RoPe_forward_hook, tf_block.self_attn.rotary_emb )
def llada_attention_hook_for_cache( self, # self is LLaDAAttention instance q_in_proj: torch.Tensor, # Renamed from q to clarify it's post-projection from cache_hook k_in_proj: torch.Tensor, # Renamed from k v_in_proj: torch.Tensor, # Renamed from v attention_bias: Optional[torch.Tensor] = None, layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, use_cache: bool = False, q_index: Optional[torch.Tensor] = None, ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]: # q_in_proj, k_in_proj, v_in_proj are (Batch, SeqLen_specific_to_them, HiddenDim_model) B, q_len_current_q = q_in_proj.shape[0], q_in_proj.shape[1] # q_len_current_q is the length of the Q for this specific call q_num_heads = self.num_heads k_num_heads = self.num_key_value_heads v_num_heads = self.num_key_value_heads head_dim = self.head_dim # Reshape q, k, v to (Batch, NumHeads, SeqLen, HeadDim) q = q_in_proj.view(B, q_len_current_q, q_num_heads, head_dim).transpose(1, 2) k_seq_len_current_k = k_in_proj.shape[1] # k_seq_len_current_k is the length of K for this call (e.g., full context) v_seq_len_current_v = v_in_proj.shape[1]
k = k_in_proj.view(B, k_seq_len_current_k, k_num_heads, head_dim).transpose(1, 2) v = v_in_proj.view(B, v_seq_len_current_v, v_num_heads, head_dim).transpose(1, 2) if hasattr(self, 'rotary_emb'): # q_index passed here should be for q_in_proj q, k = self.rotary_emb(q, k, q_index=q_index)
present = None k_repeated = repeat_kv(k, self.num_key_value_groups) v_repeated = repeat_kv(v, self.num_key_value_groups)
# q is (B, q_num_heads, q_len_current_q, head_dim) # k_repeated is (B, q_num_heads, k_seq_len_current_k, head_dim) attn_weights = torch.matmul(q, k_repeated.transpose(2, 3)) / math.sqrt(self.head_dim)
if attention_bias is not None: bias_q_dim = attention_bias.shape[-2] bias_k_dim = attention_bias.shape[-1]
sliced_attention_bias = attention_bias if q_len_current_q < bias_q_dim : # Q is a segment, assume it's the latest tokens # This assumes the q segment is the last part of the full query sequence represented by the bias sliced_attention_bias = attention_bias[:, :, -q_len_current_q:, :] if k_seq_len_current_k < bias_k_dim: # K is a segment (less likely for full KV cache but possible) # This assumes K is the latest part of the full key sequence in the bias sliced_attention_bias = sliced_attention_bias[:, :, :, -k_seq_len_current_k:]
# Final check on dimensions before adding if attn_weights.shape[-2] == sliced_attention_bias.shape[-2] and \ attn_weights.shape[-1] == sliced_attention_bias.shape[-1]: attn_weights = attn_weights + sliced_attention_bias else: if sliced_attention_bias.shape[1] == 1 and attn_weights.shape[1] == self.num_heads: # Mask has 1 head dim attn_weights = attn_weights + sliced_attention_bias # Broadcast over heads elif sliced_attention_bias.shape[1] == self.num_heads: # Mask has same num heads attn_weights = attn_weights + sliced_attention_bias else: raise RuntimeError( f"Attention bias shape {sliced_attention_bias.shape} incompatible with " f"attn_weights shape {attn_weights.shape} after slicing." ) attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(q.dtype) attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training) att_output_heads = torch.matmul(attn_weights, v_repeated)
# Reshape to (B, q_len_current_q, ModelHiddenDim) att_output_heads = att_output_heads.transpose(1, 2).contiguous().view(B, q_len_current_q, q_num_heads * head_dim) output = self.o_proj(att_output_heads) return output, present
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
def llada_RoPe_forward_hook( self_rope, q_in: torch.Tensor, k_in: torch.Tensor, q_index: Optional[torch.Tensor] = None ) -> Tuple[torch.Tensor, torch.Tensor]: input_dtype = q_in.dtype q_, k_ = q_in.float(), k_in.float()
bs, _, query_len_current, head_dim_calc = q_.shape _, _, key_len_current, _ = k_.shape
max_pos_needed = key_len_current if q_index is not None: max_pos_needed = max(max_pos_needed, int(q_index.max().item()) + 1 if q_index.numel() > 0 else 0) max_pos_needed = max(max_pos_needed, query_len_current)
if max_pos_needed == 0: return q_in, k_in
dim = self_rope.dim inv_freq_to_use = self_rope.inv_freq.to(q_.device) t = torch.arange(max_pos_needed, device=q_.device, dtype=torch.float32) if hasattr(self_rope, 'scaling_factor'): t = t / self_rope.scaling_factor
freqs = torch.outer(t, inv_freq_to_use.float()) emb = torch.cat((freqs, freqs), dim=-1) pos_cos_table = emb.cos() pos_sin_table = emb.sin()
if q_index is not None: actual_q_indices = q_index[:, :query_len_current] cos_q = pos_cos_table[actual_q_indices] sin_q = pos_sin_table[actual_q_indices] q_rotated = (q_ * cos_q.unsqueeze(1)) + (rotate_half(q_) * sin_q.unsqueeze(1)) else: q_indices = torch.arange(query_len_current, device=q_.device) cos_q = pos_cos_table[q_indices].unsqueeze(0) sin_q = pos_sin_table[q_indices].unsqueeze(0) q_rotated = (q_ * cos_q.unsqueeze(1)) + (rotate_half(q_) * sin_q.unsqueeze(1))
k_indices = torch.arange(key_len_current, device=q_.device) cos_k = pos_cos_table[k_indices].unsqueeze(0) sin_k = pos_sin_table[k_indices].unsqueeze(0) k_rotated = (k_ * cos_k.unsqueeze(1)) + (rotate_half(k_) * sin_k.unsqueeze(1)) return q_rotated.type_as(q_in), k_rotated.type_as(k_in)
def refresh_index( new_features: torch.Tensor, cached_features: torch.Tensor = None, transfer_ratio: float = 0.5, layer_id: int = 0, ) -> torch.Tensor: batch_size, gen_len, d_model = new_features.shape num_replace = int(gen_len * transfer_ratio) if num_replace == 0 or gen_len == 0: return torch.empty((batch_size, 0), dtype=torch.long, device=new_features.device) if cached_features is None or cached_features.shape[1] == 0: return torch.empty((batch_size, 0), dtype=torch.long, device=new_features.device)
cos_sim = torch.nn.functional.cosine_similarity( new_features, cached_features, dim=-1 ) k_actual = min(num_replace, cos_sim.shape[1]) if k_actual == 0: return torch.empty((batch_size, 0), dtype=torch.long, device=new_features.device)
transfer_index = torch.topk(cos_sim, largest=False, k=k_actual).indices return transfer_index
def llada_cache_hook_feature( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, # This is the original mask for the full layer input position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, use_cache: Optional[bool] = False, output_attentions: Optional[bool] = False, cache_position: Optional[torch.LongTensor] = None, ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]], Optional[Tuple[torch.Tensor, ...]]]:
current_layer_idx = self.layer_idx feature_cache = dLLMCache() feature_cache.update_step(current_layer_idx) prompt_length = feature_cache.prompt_length # x_prompt and x_gen are sub-segments of hidden_states x_prompt = hidden_states[:, :prompt_length, :] x_gen = hidden_states[:, prompt_length:, :] refresh_gen = feature_cache.refresh_gen(layer_id=current_layer_idx) refresh_prompt = feature_cache.refresh_prompt(layer_id=current_layer_idx) transfer_ratio = feature_cache.transfer_ratio bs, seq_len, dim = hidden_states.shape # seq_len is the length of hidden_states input to this layer transfer = transfer_ratio > 0 and transfer_ratio <= 1 index_from_attn_transfer = None index_expanded_from_attn_transfer = None
def project(x_input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: x_normed = self.input_layernorm(x_input) q = self.self_attn.q_proj(x_normed) k = self.self_attn.k_proj(x_normed) v = self.self_attn.v_proj(x_normed) return q, k, v
# This function needs to be smarter about the attention_bias it passes. # q_tensor_origin_slice: A tuple (start_idx, length) indicating where q_tensor comes from # relative to the original hidden_states/attention_mask. def call_attention_on_qkv(q_tensor, k_tensor, v_tensor, original_full_attention_bias, q_tensor_start_idx: int, # Start index of q_tensor within the original sequence q_index: Optional[torch.Tensor] = None): q_len_for_this_call = q_tensor.shape[1] k_len_for_this_call = k_tensor.shape[1] # This K is already the full K from dLLM cache # Slice the original_full_attention_bias # original_full_attention_bias is likely (B, 1 or H, S_full_layer_input, K_full_from_dllm_or_max) # We need (B, 1 or H, q_len_for_this_call, k_len_for_this_call) sliced_bias = original_full_attention_bias if original_full_attention_bias is not None: # Slice query dimension based on q_tensor_start_idx and its length # Slice key dimension to match k_tensor's length (which is k_full from dLLM) sliced_bias = original_full_attention_bias[ :, :, q_tensor_start_idx : q_tensor_start_idx + q_len_for_this_call, :k_len_for_this_call ] # Ensure num_heads dim is compatible (1 for broadcast, or matches self.self_attn.num_heads) if sliced_bias.shape[1] != 1 and sliced_bias.shape[1] != self.self_attn.num_heads: # This might indicate an issue with mask preparation upstream if it's not 1 or num_heads # For now, assume it's (B,1,q,k) and will broadcast if num_heads > 1 in attention_hook pass
att_output, _ = self.self_attn.attention_forward_for_cache( q_tensor, k_tensor, v_tensor, attention_bias=sliced_bias, layer_past=None, use_cache=False, q_index=q_index, ) return att_output def compute_mlp(input_to_mlp: torch.Tensor) -> torch.Tensor: if input_to_mlp.shape[1] == 0: return torch.empty_like(input_to_mlp) x_norm = self.post_attention_layernorm(input_to_mlp) gate_proj_out = self.mlp.gate_proj(x_norm) up_proj_out = self.mlp.up_proj(x_norm) act_out = self.mlp.act_fn(gate_proj_out) x = act_out * up_proj_out return self.mlp.down_proj(x)
residual_pre_attn = hidden_states
if refresh_gen and refresh_prompt: q_full, k_full, v_full = project(hidden_states) feature_cache.set_cache( layer_id=current_layer_idx, feature_name="kv_cache", features={"k": k_full[:, :prompt_length, :], "v": v_full[:, :prompt_length, :]}, cache_type="prompt" ) if hidden_states.shape[1] > prompt_length: feature_cache.set_cache( layer_id=current_layer_idx, feature_name="kv_cache", features={"k": k_full[:, prompt_length:, :], "v": v_full[:, prompt_length:, :]}, cache_type="gen" ) # Q is all of hidden_states, K,V also from all of hidden_states # q_start_idx is 0 because q_full corresponds to the start of hidden_states att = call_attention_on_qkv(q_full, k_full, v_full, attention_mask, q_tensor_start_idx=0, q_index=position_ids) feature_cache.set_cache( layer_id=current_layer_idx, feature_name="attn", features=att[:, :prompt_length, :], cache_type="prompt" ) if hidden_states.shape[1] > prompt_length: feature_cache.set_cache( layer_id=current_layer_idx, feature_name="attn", features=att[:, prompt_length:, :], cache_type="gen" )
elif refresh_gen and not refresh_prompt: att_gen_part = torch.empty((bs, 0, dim), device=hidden_states.device) if x_gen.shape[1] > 0: q_gen, k_gen, v_gen = project(x_gen) feature_cache.set_cache( layer_id=current_layer_idx, feature_name="kv_cache", features={"k": k_gen, "v": v_gen}, cache_type="gen" ) kv_cache_prompt = feature_cache.get_cache( layer_id=current_layer_idx, feature_name="kv_cache", cache_type="prompt" ) k_prompt_val = kv_cache_prompt.get("k", torch.empty(bs,0,dim,device=hidden_states.device)) v_prompt_val = kv_cache_prompt.get("v", torch.empty(bs,0,dim,device=hidden_states.device))
k_full_ctx = torch.cat([k_prompt_val, k_gen], dim=1) v_full_ctx = torch.cat([v_prompt_val, v_gen], dim=1) q_gen_pos_ids = position_ids[:, prompt_length:] if position_ids is not None and position_ids.shape[1] > prompt_length else None # q_gen starts at prompt_length in the original hidden_states sequence att_gen_part = call_attention_on_qkv(q_gen, k_full_ctx, v_full_ctx, attention_mask, q_tensor_start_idx=prompt_length, q_index=q_gen_pos_ids) feature_cache.set_cache( layer_id=current_layer_idx, feature_name="attn", features=att_gen_part, cache_type="gen" ) att_prompt_cache = feature_cache.get_cache( layer_id=current_layer_idx, feature_name="attn", cache_type="prompt" ) att = torch.cat([att_prompt_cache, att_gen_part], dim=1)
elif not refresh_gen and refresh_prompt: q_prompt, k_prompt, v_prompt = project(x_prompt) feature_cache.set_cache( layer_id=current_layer_idx, feature_name="kv_cache", features={"k": k_prompt, "v": v_prompt}, cache_type="prompt" ) kv_cache_gen = feature_cache.get_cache( layer_id=current_layer_idx, feature_name="kv_cache", cache_type="gen" ) att_gen_cache = feature_cache.get_cache( layer_id=current_layer_idx, feature_name="attn", cache_type="gen" ) k_gen_current = kv_cache_gen.get("k", torch.empty(bs,0,dim, device=hidden_states.device)) v_gen_current = kv_cache_gen.get("v", torch.empty(bs,0,dim, device=hidden_states.device))
q_for_attn_segments = [q_prompt] q_idx_for_attn_segments = [position_ids[:, :prompt_length]] if position_ids is not None else [None] q_start_indices_segments = [0] # q_prompt starts at index 0 of hidden_states
if transfer and x_gen.shape[1] > 0 and k_gen_current.shape[1] > 0: _, _, v_gen_for_transfer = project(x_gen) index_from_attn_transfer = refresh_index(v_gen_for_transfer, v_gen_current, transfer_ratio, current_layer_idx) if index_from_attn_transfer.numel() > 0: index_expanded_from_attn_transfer = index_from_attn_transfer.unsqueeze(-1).expand(-1, -1, dim) x_gen_normed_selected = torch.gather(self.input_layernorm(x_gen), dim=1, index=index_expanded_from_attn_transfer) q_gen_index = self.self_attn.q_proj(x_gen_normed_selected) k_gen_index = self.self_attn.k_proj(x_gen_normed_selected) v_gen_index_part = self.self_attn.v_proj(x_gen_normed_selected)
k_gen_current = k_gen_current.scatter(dim=1, index=index_expanded_from_attn_transfer, src=k_gen_index) v_gen_current = v_gen_current.scatter(dim=1, index=index_expanded_from_attn_transfer, src=v_gen_index_part)
feature_cache.set_cache( layer_id=current_layer_idx, feature_name="kv_cache", features={"k": k_gen_current, "v": v_gen_current}, cache_type="gen" ) q_for_attn_segments.append(q_gen_index) if position_ids is not None and position_ids.shape[1] > prompt_length: gen_abs_positions_all = position_ids[:, prompt_length:] gen_abs_positions_selected = torch.gather(gen_abs_positions_all, 1, index_from_attn_transfer) q_idx_for_attn_segments.append(gen_abs_positions_selected) else: q_idx_for_attn_segments.append(None)
q_combined_for_attn = torch.cat(q_for_attn_segments, dim=1) q_idx_combined_for_rope = torch.cat(q_idx_for_attn_segments, dim=1) if all(s is not None for s in q_idx_for_attn_segments) else None
k_full_ctx = torch.cat([k_prompt, k_gen_current], dim=1) v_full_ctx = torch.cat([v_prompt, v_gen_current], dim=1) # q_combined_for_attn effectively starts at index 0 of a conceptual sequence. # Its RoPE is handled by q_idx_combined_for_rope. att_for_q_combined = call_attention_on_qkv(q_combined_for_attn, k_full_ctx, v_full_ctx, attention_mask, q_tensor_start_idx=0, # Since Q is combined and starts from effective 0 q_index=q_idx_combined_for_rope) att_prompt_new = att_for_q_combined[:, :q_prompt.shape[1], :] if transfer and index_from_attn_transfer is not None and index_from_attn_transfer.numel() > 0: att_gen_index_new = att_for_q_combined[:, q_prompt.shape[1]:, :] # Segment for transferred Qs if att_gen_cache.shape[1] > 0: att_gen_cache = att_gen_cache.scatter(dim=1, index=index_expanded_from_attn_transfer, src=att_gen_index_new) feature_cache.set_cache( layer_id=current_layer_idx, feature_name="attn", features=att_gen_cache, cache_type="gen" ) feature_cache.set_cache( layer_id=current_layer_idx, feature_name="attn", features=att_prompt_new, cache_type="prompt" ) att = torch.cat([att_prompt_new, att_gen_cache], dim=1)
else: # Not refresh gen, not refresh prompt att_prompt_cache = feature_cache.get_cache( layer_id=current_layer_idx, feature_name="attn", cache_type="prompt" ) att_gen_cache = feature_cache.get_cache( layer_id=current_layer_idx, feature_name="attn", cache_type="gen" ) kv_cache_gen = feature_cache.get_cache( layer_id=current_layer_idx, feature_name="kv_cache", cache_type="gen" ) kv_cache_prompt = feature_cache.get_cache( layer_id=current_layer_idx, feature_name="kv_cache", cache_type="prompt" ) k_gen_current = kv_cache_gen.get("k", torch.empty(bs,0,dim, device=hidden_states.device)) v_gen_current = kv_cache_gen.get("v", torch.empty(bs,0,dim, device=hidden_states.device)) k_prompt_val = kv_cache_prompt.get("k", torch.empty(bs,0,dim,device=hidden_states.device)) v_prompt_val = kv_cache_prompt.get("v", torch.empty(bs,0,dim,device=hidden_states.device)) if transfer and x_gen.shape[1] > 0 and k_gen_current.shape[1] > 0: x_gen_normed = self.input_layernorm(x_gen) v_gen_for_transfer = self.self_attn.v_proj(x_gen_normed) index_from_attn_transfer = refresh_index(v_gen_for_transfer, v_gen_current, transfer_ratio, current_layer_idx)
if index_from_attn_transfer.numel() > 0: index_expanded_from_attn_transfer = index_from_attn_transfer.unsqueeze(-1).expand(-1, -1, dim) x_gen_normed_selected = torch.gather(x_gen_normed, dim=1, index=index_expanded_from_attn_transfer) q_gen_index_only = self.self_attn.q_proj(x_gen_normed_selected) # Q only for transferred items k_gen_index = self.self_attn.k_proj(x_gen_normed_selected) v_gen_index_part = self.self_attn.v_proj(x_gen_normed_selected)
k_gen_current = k_gen_current.scatter(dim=1, index=index_expanded_from_attn_transfer, src=k_gen_index) v_gen_current = v_gen_current.scatter(dim=1, index=index_expanded_from_attn_transfer, src=v_gen_index_part) feature_cache.set_cache( layer_id=current_layer_idx, feature_name="kv_cache", features={"k": k_gen_current, "v": v_gen_current}, cache_type="gen" ) q_idx_for_transferred_rope = None if position_ids is not None and position_ids.shape[1] > prompt_length: gen_abs_positions_all = position_ids[:, prompt_length:] q_idx_for_transferred_rope = torch.gather(gen_abs_positions_all, 1, index_from_attn_transfer)
k_full_ctx = torch.cat([k_prompt_val, k_gen_current], dim=1) v_full_ctx = torch.cat([v_prompt_val, v_gen_current], dim=1)
att_gen_index_new = call_attention_on_qkv(q_gen_index_only, k_full_ctx, v_full_ctx, attention_mask, q_tensor_start_idx=prompt_length, # Approximate for mask slicing q_index=q_idx_for_transferred_rope) if att_gen_cache.shape[1] > 0: # Make sure att_gen_cache has a gen part att_gen_cache = att_gen_cache.scatter(dim=1, index=index_expanded_from_attn_transfer, src=att_gen_index_new) elif x_gen.shape[1] > 0: # If original att_gen_cache was for an empty gen part, but x_gen is not empty # Initialize att_gen_cache to be of x_gen's length before scattering att_gen_cache = torch.zeros((bs, x_gen.shape[1], dim), device=hidden_states.device, dtype=att_gen_index_new.dtype) att_gen_cache = att_gen_cache.scatter(dim=1, index=index_expanded_from_attn_transfer, src=att_gen_index_new) # Else: if x_gen.shape[1] is 0, att_gen_cache remains empty, scatter won't happen.
feature_cache.set_cache( layer_id=current_layer_idx, feature_name="attn", features=att_gen_cache, cache_type="gen" ) att = torch.cat([att_prompt_cache, att_gen_cache], dim=1)
# ... rest of the llada_cache_hook_feature (MLP part) remains the same ... hidden_states_after_attn = residual_pre_attn + att residual_pre_mlp = hidden_states_after_attn x_prompt_mlp = hidden_states_after_attn[:, :prompt_length, :] x_gen_mlp = hidden_states_after_attn[:, prompt_length:, :]
mlp_out_prompt_part = torch.empty((bs, prompt_length, dim), device=hidden_states.device, dtype=hidden_states_after_attn.dtype) mlp_out_gen_part = torch.empty((bs, x_gen_mlp.shape[1], dim), device=hidden_states.device, dtype=hidden_states_after_attn.dtype)
if refresh_gen and refresh_prompt: mlp_out_full = compute_mlp(hidden_states_after_attn) mlp_out_prompt_part = mlp_out_full[:, :prompt_length, :] if x_gen_mlp.shape[1] > 0: mlp_out_gen_part = mlp_out_full[:, prompt_length:, :] feature_cache.set_cache( current_layer_idx, "mlp", mlp_out_prompt_part, cache_type="prompt" ) if x_gen_mlp.shape[1] > 0: feature_cache.set_cache( current_layer_idx, "mlp", mlp_out_gen_part, cache_type="gen" ) if mlp_out_gen_part.shape[1] > 0: mlp_out = torch.cat([mlp_out_prompt_part, mlp_out_gen_part], dim=1) else: mlp_out = mlp_out_prompt_part
elif refresh_gen and not refresh_prompt: mlp_out_prompt_part = feature_cache.get_cache( current_layer_idx, "mlp", cache_type="prompt" ) if x_gen_mlp.shape[1] > 0: mlp_out_gen_part = compute_mlp(x_gen_mlp) feature_cache.set_cache(current_layer_idx, "mlp", mlp_out_gen_part, cache_type="gen") if mlp_out_gen_part.shape[1] > 0: mlp_out = torch.cat([mlp_out_prompt_part, mlp_out_gen_part], dim=1) else: mlp_out = mlp_out_prompt_part
elif refresh_prompt and not refresh_gen: mlp_gen_cache_data = feature_cache.get_cache(current_layer_idx, "mlp", cache_type="gen") if x_gen_mlp.shape[1] > 0: mlp_out_gen_part = mlp_gen_cache_data mlp_input_for_prompt_path = x_prompt_mlp # Use index_expanded_from_attn_transfer which was set in the attention block if transfer and index_expanded_from_attn_transfer is not None and index_expanded_from_attn_transfer.numel() > 0 and x_gen_mlp.shape[1] > 0 : x_gen_mlp_selected = torch.gather(x_gen_mlp, dim=1, index=index_expanded_from_attn_transfer) mlp_input_for_prompt_path = torch.cat([x_prompt_mlp, x_gen_mlp_selected], dim=1) mlp_out_prompt_path_processed = compute_mlp(mlp_input_for_prompt_path) mlp_out_prompt_part = mlp_out_prompt_path_processed[:, :x_prompt_mlp.shape[1], :]
if transfer and index_expanded_from_attn_transfer is not None and index_expanded_from_attn_transfer.numel() > 0 and x_gen_mlp.shape[1] > 0: mlp_gen_index_new = mlp_out_prompt_path_processed[:, x_prompt_mlp.shape[1]:, :] if mlp_out_gen_part.shape[1] > 0: # If gen part exists mlp_out_gen_part = mlp_out_gen_part.scatter(dim=1, index=index_expanded_from_attn_transfer, src=mlp_gen_index_new)
feature_cache.set_cache(current_layer_idx, "mlp", mlp_out_gen_part, cache_type="gen") feature_cache.set_cache(current_layer_idx, "mlp", mlp_out_prompt_part, cache_type="prompt") if mlp_out_gen_part.shape[1] > 0: mlp_out = torch.cat([mlp_out_prompt_part, mlp_out_gen_part], dim=1) else: mlp_out = mlp_out_prompt_part
else: mlp_out_prompt_part = feature_cache.get_cache( current_layer_idx, "mlp", cache_type="prompt" ) mlp_gen_cache_data = feature_cache.get_cache(current_layer_idx, "mlp", cache_type="gen") if x_gen_mlp.shape[1] > 0: mlp_out_gen_part = mlp_gen_cache_data
# Use index_expanded_from_attn_transfer if transfer and index_expanded_from_attn_transfer is not None and index_expanded_from_attn_transfer.numel() > 0 and x_gen_mlp.shape[1] > 0: x_gen_mlp_selected = torch.gather(x_gen_mlp, dim=1, index=index_expanded_from_attn_transfer) mlp_out_gen_index = compute_mlp(x_gen_mlp_selected) if mlp_out_gen_part.shape[1] > 0: mlp_out_gen_part = mlp_out_gen_part.scatter(dim=1, index=index_expanded_from_attn_transfer, src=mlp_out_gen_index)
feature_cache.set_cache(current_layer_idx, "mlp", mlp_out_gen_part, cache_type="gen") if mlp_out_gen_part.shape[1] > 0: mlp_out = torch.cat([mlp_out_prompt_part, mlp_out_gen_part], dim=1) else: mlp_out = mlp_out_prompt_part
final_hidden_states = residual_pre_mlp + mlp_out returned_outputs = (final_hidden_states,) if output_attentions: returned_outputs += (None,) if use_cache: returned_outputs += (None,)
return returned_outputs
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507"""Fast dLLM Cache Hook for LLaDA Model
This module contains hooks and utilities for implementing fast distributed LLM cachingin the LLaDA model architecture."""
import torchimport torch.nn as nnimport torch.nn.functional as Fimport mathfrom typing import Optional, Tuple, List, Sequence, Unionimport numpy as np
class FastDLLMGenerationHook: """ Hook class for implementing fast dLLM caching functionality in LLaDA model. This class handles both attention-level caching and generation-level optimizations. """ def __init__(self, model): self.model = model self.original_methods = {} self.is_registered = False def register_hooks(self): """Register fast dLLM hooks to the model.""" if self.is_registered: return # Store original methods self.original_methods['generate'] = self.model.generate # 新增:保存原始的generate方法 # Store original attention forwards for layer_idx, layer in enumerate(self.model.model.layers): self.original_methods[f'attention_{layer_idx}'] = layer.self_attn.forward # Replace attention forward with fast cache version layer.self_attn.forward = self._create_fast_attention_forward(layer.self_attn, layer_idx) self.model.generate = self._fast_generate # 新增:替换generate方法 self.is_registered = True def unregister_hooks(self): """Unregister fast dLLM hooks from the model.""" if not self.is_registered: return # Restore original methods self.model.generate = self.original_methods['generate'] # 新增:恢复原始的generate方法 # Restore original attention forwards for layer_idx, layer in enumerate(self.model.model.layers): layer.self_attn.forward = self.original_methods[f'attention_{layer_idx}'] self.is_registered = False def _create_fast_attention_forward(self, attention_layer, layer_idx): """Create fast attention forward method with caching support.""" def fast_attention_forward( hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, output_attentions: bool = False, use_cache: bool = False, cache_position: Optional[torch.LongTensor] = None, fast_dllm_cache: Optional[Sequence[Tuple[torch.Tensor, torch.Tensor]]] = None, **kwargs, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: # If not using fast cache or output_attentions is needed, use original method if output_attentions: return self.original_methods[f'attention_{layer_idx}']( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_value, output_attentions=output_attentions, use_cache=use_cache, cache_position=cache_position, **kwargs ) bsz, q_len, _ = hidden_states.size()
query_states = attention_layer.q_proj(hidden_states) key_states = attention_layer.k_proj(hidden_states) value_states = attention_layer.v_proj(hidden_states)
query_states = query_states.view(bsz, q_len, attention_layer.num_heads, attention_layer.head_dim).transpose(1, 2) key_states = key_states.view(bsz, q_len, attention_layer.num_key_value_heads, attention_layer.head_dim).transpose(1, 2) value_states = value_states.view(bsz, q_len, attention_layer.num_key_value_heads, attention_layer.head_dim).transpose(1, 2)
# Apply rotary position embedding with fast cache consideration cache_offset = 0 if fast_dllm_cache and len(fast_dllm_cache) > layer_idx: cache_offset = fast_dllm_cache[layer_idx][0].shape[-2] cos, sin = attention_layer.rotary_emb(value_states, position_ids + cache_offset if cache_offset > 0 else position_ids) query_states, key_states = self._apply_rotary_pos_emb(query_states, key_states, cos, sin)
# Handle past key values past_key_value = getattr(attention_layer, "past_key_value", past_key_value) if past_key_value is not None: cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} key_states, value_states = past_key_value.update(key_states, value_states, layer_idx, cache_kwargs) # Fast dLLM cache logic if fast_dllm_cache is not None: if len(fast_dllm_cache) <= layer_idx: fast_dllm_cache.append((key_states, value_states)) else: past_key, past_value = fast_dllm_cache[layer_idx] key_states = torch.cat([past_key, key_states], dim=-2) value_states = torch.cat([past_value, value_states], dim=-2)
# Repeat key-value pairs for multi-head attention key_states = self._repeat_kv(key_states, attention_layer.num_key_value_groups) value_states = self._repeat_kv(value_states, attention_layer.num_key_value_groups)
# Apply causal mask causal_mask = attention_mask if attention_mask is not None: causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
# Ensure contiguous tensors for CUDA if query_states.device.type == "cuda" and causal_mask is not None: query_states = query_states.contiguous() key_states = key_states.contiguous() value_states = value_states.contiguous()
# Scaled dot-product attention attn_output = torch.nn.functional.scaled_dot_product_attention( query_states, key_states, value_states, attn_mask=None, is_causal=False, dropout_p=attention_layer.attention_dropout if attention_layer.training else 0.0, )
attn_output = attn_output.transpose(1, 2).contiguous() attn_output = attn_output.view(bsz, q_len, attention_layer.hidden_size) attn_output = attention_layer.o_proj(attn_output)
return attn_output, None, past_key_value return fast_attention_forward @torch.no_grad() def _fast_generate( self, inputs: Optional[torch.Tensor] = None, images: Optional[torch.Tensor] = None, image_sizes: Optional[torch.Tensor] = None, modalities: Optional[List[str]] = ["image"], **kwargs, ): modalities = kwargs.pop("modalities", None) if "modalities" in kwargs and modalities is None else modalities position_ids = kwargs.pop("position_ids", None) attention_mask = kwargs.pop("attention_mask", None) if "inputs_embeds" in kwargs: raise NotImplementedError("`inputs_embeds` is not supported")
if images is not None: (inputs, position_ids, attention_mask, _, inputs_embeds, _) = self.model.prepare_inputs_labels_for_multimodal(inputs, position_ids, attention_mask, None, None, images, modalities, image_sizes=image_sizes) else: inputs_embeds = self.model.get_model().embed_tokens(inputs) output = self._fast_generate_with_embeds(inputs_embeds=inputs_embeds, **kwargs) return output @torch.no_grad() def _fast_generate_with_embeds( self, inputs_embeds, steps=128, gen_length=128, block_length=128, temperature=0.0, cfg_scale=0.0, remasking='low_confidence', mask_id=126336, tokenizer=None, stopping_criteria=None, generation_suffix=None, threshold=None, prefix_refresh_interval=32, **kwargs ): """ Fast generation with embeddings using dLLM cache optimization. This method incorporates all fast dLLM related optimizations. """ # Use mixed precision for faster computation with torch.cuda.amp.autocast(enabled=True): # Handle generation suffix suffix_embeds = None suffix_token_ids = None suffix_len = 0 if generation_suffix is not None and tokenizer is not None and len(generation_suffix) > 0: suffix_token_ids = tokenizer.encode(generation_suffix, add_special_tokens=False) suffix_token_ids = torch.tensor(suffix_token_ids, dtype=torch.long, device=inputs_embeds.device).unsqueeze(0) suffix_embeds = self.model.model.embed_tokens(suffix_token_ids) suffix_len = suffix_embeds.shape[1]
# Create input in embedding space total_length = inputs_embeds.shape[1] + gen_length + suffix_len masked_embed = self.model.model.embed_tokens(torch.tensor([mask_id]).to(inputs_embeds.device)) x_embeds = masked_embed.repeat(1, total_length, 1).to(inputs_embeds.device) x_embeds[:, :inputs_embeds.shape[1]] = inputs_embeds.clone() if suffix_embeds is not None: x_embeds[:, -suffix_len:] = suffix_embeds
# Create tracking tensor for token IDs x = torch.full((1, total_length), mask_id, dtype=torch.long, device=inputs_embeds.device) if suffix_token_ids is not None: x[:, -suffix_len:] = suffix_token_ids
# Prompt index tracking prompt_index = torch.zeros((1, total_length), dtype=torch.bool, device=inputs_embeds.device) prompt_index[:, :inputs_embeds.shape[1]] = 1
assert gen_length % block_length == 0 num_blocks = gen_length // block_length assert steps % num_blocks == 0 steps = steps // num_blocks
# Initialize stop tracking stop_position = inputs_embeds.shape[1] + gen_length found_stop_seq = False stop_tokens = [] if stopping_criteria is not None: assert tokenizer is not None, "tokenizer is required when stopping_criteria is not None" for stop_str in stopping_criteria: tokens = tokenizer.encode(stop_str, add_special_tokens=False) stop_tokens.append(tokens)
# Process each block for num_block in range(num_blocks): block_start = inputs_embeds.shape[1] + num_block * block_length block_end = inputs_embeds.shape[1] + (num_block + 1) * block_length
# Skip if stop found before current block if found_stop_seq and stop_position <= block_start: break block_embeds = x_embeds[:, block_start:block_end] block_mask_index = torch.all(torch.abs(block_embeds - masked_embed) < 1e-5, dim=2) num_transfer_tokens = self._get_num_transfer_tokens(block_mask_index, steps) i = 0
while True: if threshold is None and i >= steps: break # Check mask state mask_index = torch.all(torch.abs(x_embeds - masked_embed) < 1e-5, dim=2) if found_stop_seq: pre_stop_masks = mask_index[0, inputs_embeds.shape[1]:stop_position] if not pre_stop_masks.any(): break current_block_masks = mask_index[0, block_start:block_end] if not current_block_masks.any(): break # Handle CFG if cfg_scale > 0.0: un_embeds = x_embeds.clone() un_mask = prompt_index.unsqueeze(-1).expand_as(x_embeds) un_embeds[un_mask] = masked_embed.repeat(x_embeds.shape[0], x_embeds.shape[1], 1)[un_mask] combined_embeds = torch.cat([x_embeds, un_embeds], dim=0) outputs = self.model.model( inputs_embeds=combined_embeds, fast_dllm_cache=fast_dllm_cache ) logits = self.model.lm_head(outputs[0]).float() logits, un_logits = torch.chunk(logits, 2, dim=0) logits = un_logits + (cfg_scale + 1) * (logits - un_logits) else: if i % prefix_refresh_interval == 0: fast_dllm_cache = [] outputs = self.model.model( inputs_embeds=x_embeds, fast_dllm_cache=fast_dllm_cache ) # Slice cache to block start fast_dllm_cache = self._create_cache_slice(fast_dllm_cache, block_start) else: # Incremental forward pass outputs = self.model.model( inputs_embeds=x_embeds[:, block_start:], fast_dllm_cache=fast_dllm_cache ) logits = self.model.lm_head(outputs[0]).float()
# Filter forbidden tokens forbidden_tokens = [126081, 126080, 126346, 126347] if i % prefix_refresh_interval == 0: for token_id in forbidden_tokens: logits[:, :, token_id] = torch.where(mask_index, -float('inf'), logits[:, :, token_id]) else: for token_id in forbidden_tokens: logits[:, :, token_id] = torch.where(mask_index[:, block_start:], -float('inf'), logits[:, :, token_id])
# Get transfer indices and update if i % prefix_refresh_interval == 0: x0, transfer_index = self._get_transfer_index( logits, temperature, remasking, mask_index, x, num_transfer_tokens[:, i] if threshold is None else None, found_stop_seq, stop_position, block_end, suffix_len, threshold ) x0_embeds = self.model.model.embed_tokens(x0) x0_embeds = torch.where(mask_index.unsqueeze(-1).expand_as(x_embeds), x0_embeds, x_embeds) x_embeds[transfer_index] = x0_embeds[transfer_index] x[transfer_index] = x0[transfer_index] else: x0, transfer_index = self._get_transfer_index( logits, temperature, remasking, mask_index[:, block_start:], x[:, block_start:], num_transfer_tokens[:, i] if threshold is None else None, found_stop_seq, stop_position - block_start, block_end - block_start, suffix_len, threshold ) x0_embeds = self.model.model.embed_tokens(x0) x0_embeds = torch.where(mask_index[:, block_start:].unsqueeze(-1).expand_as(x_embeds[:, block_start:]), x0_embeds, x_embeds[:, block_start:]) x_embeds[:, block_start:][transfer_index] = x0_embeds[transfer_index] x[:, block_start:][transfer_index] = x0[transfer_index]
# Check for stop words if stopping_criteria is not None: generated_part = x[0, inputs_embeds.shape[1]:inputs_embeds.shape[1] + gen_length] for stop_seq in stop_tokens: if not isinstance(stop_seq, list): stop_seq = [stop_seq] for start_idx in range(generated_part.size(0) - len(stop_seq) + 1): if torch.all(generated_part[start_idx:start_idx + len(stop_seq)] == torch.tensor(stop_seq, device=x.device)): current_position = inputs_embeds.shape[1] + start_idx if not found_stop_seq or current_position < stop_position: stop_position = current_position found_stop_seq = True break if found_stop_seq: break i += 1
if threshold is not None: print(f'Number of steps: {i}')
# Return results if found_stop_seq: if suffix_len > 0: return torch.cat([x[:, inputs_embeds.shape[1]:stop_position], x[:, -suffix_len:]], dim=1) else: return x[:, inputs_embeds.shape[1]:stop_position] else: if suffix_len > 0: return torch.cat([x[:, inputs_embeds.shape[1]:inputs_embeds.shape[1] + gen_length], x[:, -suffix_len:]], dim=1) else: return x[:, inputs_embeds.shape[1]:inputs_embeds.shape[1] + gen_length]
@staticmethod def _apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): """Apply rotary position embedding to query and key tensors.""" cos = cos.unsqueeze(unsqueeze_dim) sin = sin.unsqueeze(unsqueeze_dim) q_embed = (q * cos) + (FastDLLMGenerationHook._rotate_half(q) * sin) k_embed = (k * cos) + (FastDLLMGenerationHook._rotate_half(k) * sin) return q_embed, k_embed
@staticmethod def _rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1)
@staticmethod def _repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """Repeat key-value pairs for multi-head attention.""" batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
def _get_transfer_index(self, logits, temperature, remasking, mask_index, x, num_transfer_tokens, found_stop_seq, stop_position, block_end, suffix_len, threshold=None): """Get transfer indices for token updates during generation.""" logits_with_noise = self._add_gumbel_noise(logits, temperature=temperature) x0 = torch.argmax(logits_with_noise, dim=-1)
if remasking == 'low_confidence': p = F.softmax(logits.to(torch.float64), dim=-1) x0_p = torch.squeeze(torch.gather(p, dim=-1, index=torch.unsqueeze(x0, -1)), -1) elif remasking == 'random': x0_p = torch.rand((x0.shape[0], x0.shape[1]), device=x0.device) else: raise NotImplementedError(remasking) # Handle stop sequences and block boundaries if found_stop_seq: x0_p[:, stop_position:] = -np.inf else: x0_p[:, block_end:] = -np.inf
# Prevent overwriting suffix if suffix_len > 0: x0_p[:, -suffix_len:] = -np.inf x0 = torch.where(mask_index, x0, x) confidence = torch.where(mask_index, x0_p, -np.inf)
transfer_index = torch.zeros_like(x0, dtype=torch.bool, device=x0.device) if threshold is not None: num_transfer_tokens = mask_index.sum(dim=1, keepdim=True)
for j in range(confidence.shape[0]): if threshold is None: top_i = num_transfer_tokens[j] else: ns = list(range(1, num_transfer_tokens[j] + 1)) es = [threshold / (n + 1) for n in ns] threshs = [1 - e for e in es] threshs[0] = -1 # at least one token is transferred sorted_confidence = torch.sort(confidence[j][mask_index[j]], dim=-1, descending=True)[0] assert len(sorted_confidence) == len(threshs) for top_i in range(len(threshs)): if sorted_confidence[top_i] < threshs[top_i]: break
if top_i == 0 or top_i == len(threshs) - 1: top_i += 1
_, select_index = torch.topk(confidence[j], k=top_i) transfer_index[j, select_index] = True
return x0, transfer_index
@staticmethod def _add_gumbel_noise(logits, temperature): """Add Gumbel noise for categorical sampling.""" if temperature == 0: return logits logits = logits.to(torch.float64) noise = torch.rand_like(logits, dtype=torch.float64) gumbel_noise = (-torch.log(noise)) ** temperature return logits.exp() / gumbel_noise
@staticmethod def _get_num_transfer_tokens(mask_index, steps): """Precompute the number of tokens to transition at each step.""" mask_num = mask_index.sum(dim=1, keepdim=True) base = mask_num // steps remainder = mask_num % steps
num_transfer_tokens = base.expand(-1, steps).clone()
if remainder.sum() > 0: indices = torch.arange(steps, device=mask_index.device) mask = indices.unsqueeze(0) < remainder num_transfer_tokens[mask] += 1
return num_transfer_tokens.to(torch.int64)
def _create_cache_slice(self, fast_dllm_cache, block_start): """Create a sliced version of fast_dllm_cache for block processing.""" new_past_key_values = [] for i in range(len(fast_dllm_cache)): new_past_key_values.append([]) for j in range(len(fast_dllm_cache[i])): new_past_key_values[i].append(fast_dllm_cache[i][j][:, :, :block_start]) return new_past_key_values
def register_fast_dllm_hook(model): """ Register fast dLLM cache hooks to the model. Args: model: The LLaDA model to register hooks to Returns: FastDLLMGenerationHook: The hook instance for management """ hook = FastDLLMGenerationHook(model) hook.register_hooks() return hook
def unregister_fast_dllm_hook(hook): """ Unregister fast dLLM cache hooks from the model. Args: hook: The FastDLLMGenerationHook instance to unregister """ hook.unregister_hooks() 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396from PIL import Imagefrom io import BytesIOimport base64import mathimport astimport reimport torchfrom transformers import StoppingCriteriafrom llava.constants import IMAGE_TOKEN_INDEXfrom llava.utils import rank0_print, process_video_with_pyav, process_video_with_decord
def resize_and_center_crop(image, shortest_edge_length): # Calculate new dimensions and resize aspect_ratio = float(image.width) / float(image.height) if aspect_ratio > 1: new_width = int(shortest_edge_length * aspect_ratio) new_height = shortest_edge_length else: new_width = shortest_edge_length new_height = int(shortest_edge_length / aspect_ratio) resized_image = image.resize((new_width, new_height), Image.ANTIALIAS)
# Calculate the position and perform the center crop left = (new_width - shortest_edge_length) / 2 top = (new_height - shortest_edge_length) / 2 right = (new_width + shortest_edge_length) / 2 bottom = (new_height + shortest_edge_length) / 2 cropped_image = resized_image.crop((left, top, right, bottom))
return cropped_image
def auto_pad_images(image, grid_params): assert isinstance(image, Image.Image), "Input should be a Pillow Image" assert len(grid_params) > 0, "Grid parameters should not be empty"
# Step 1: Calculate and find the closest aspect ratio input_width, input_height = image.size input_aspect_ratio = input_width / input_height candidate_resolutions = [(w / h, w, h) for w in grid_params for h in grid_params] closest_aspect_ratio = min(candidate_resolutions, key=lambda x: abs(input_aspect_ratio - x[0]))
candidate_resolutions = [(x[1], x[2]) for x in candidate_resolutions if abs(x[0] - closest_aspect_ratio[0]) < 1e-3]
target_resolution = min(candidate_resolutions, key=lambda res: abs(max(input_width, input_height) / max(res) - 1))
resize_width, resize_height = target_resolution if input_width > input_height: resize_height = int(resize_width / input_aspect_ratio) else: resize_width = int(resize_height * input_aspect_ratio) resized_image = image.resize((resize_width, resize_height), Image.ANTIALIAS)
# Step 5: Pad the resized image if necessary to match the target resolution pad_width = target_resolution[0] - resize_width pad_height = target_resolution[1] - resize_height padded_image = Image.new("RGB", target_resolution, color=(0, 0, 0)) padded_image.paste(resized_image, (pad_width // 2, pad_height // 2))
return padded_image
def extract_patches(image, patch_size, overlap_ratio): assert isinstance(image, Image.Image), "Input should be a Pillow Image" assert patch_size > 0, "Patch size should be greater than 0" assert 0 <= overlap_ratio < 1, "Overlap ratio should be between 0 and 1"
W, H = image.size patches = []
stride = int(patch_size * (1 - overlap_ratio))
num_patches_y = (H - patch_size) // stride + 1 num_patches_x = (W - patch_size) // stride + 1
y_start = (H - (num_patches_y - 1) * stride - patch_size) // 2 x_start = (W - (num_patches_x - 1) * stride - patch_size) // 2
for y in range(y_start, y_start + num_patches_y * stride, stride): for x in range(x_start, x_start + num_patches_x * stride, stride): patch = image.crop((x, y, x + patch_size, y + patch_size)) patches.append(patch)
return patches
def process_highres_image_crop_split(image, data_args, processor=None): crop_resolution = data_args.image_crop_resolution split_resolution = data_args.image_split_resolution if processor is None: processor = data_args.image_processor image_crop = resize_and_center_crop(image, crop_resolution) image_patches = extract_patches(image_crop, patch_size=split_resolution, overlap_ratio=0) image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches] return torch.stack(image_patches, dim=0)
def process_highres_image(image, processor, grid_pinpoints): grid_params = [int(x) for x in grid_pinpoints.split(",")] width_height = max(image.size) fit_grid_params = [x for x in grid_params if x >= width_height] if len(fit_grid_params) == 0: select_size = max(grid_params) else: select_size = min(fit_grid_params) # FIXME: always select the 448 select_size = max(grid_params) image_padded = expand2square(image, tuple(int(x * 255) for x in processor.image_mean))
# FIXME: this seems to be a bug that it always resizes instead of padding image_original_resize = image.resize((processor.size["shortest_edge"], processor.size["shortest_edge"])) image_padded = image_padded.resize((select_size, select_size)) image_patches = extract_patches(image_padded, patch_size=processor.size["shortest_edge"], overlap_ratio=0) image_patches = [image_original_resize] + image_patches image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches] return torch.stack(image_patches, dim=0)
def select_best_resolution(original_size, possible_resolutions): """ Selects the best resolution from a list of possible resolutions based on the original size.
Args: original_size (tuple): The original size of the image in the format (width, height). possible_resolutions (list): A list of possible resolutions in the format [(width1, height1), (width2, height2), ...].
Returns: tuple: The best fit resolution in the format (width, height). """ original_width, original_height = original_size best_fit = None max_effective_resolution = 0 min_wasted_resolution = float("inf")
for width, height in possible_resolutions: # Calculate the downscaled size to keep the aspect ratio scale = min(width / original_width, height / original_height) downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale)
# Calculate effective and wasted resolutions effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height) wasted_resolution = (width * height) - effective_resolution
if effective_resolution > max_effective_resolution or (effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution): max_effective_resolution = effective_resolution min_wasted_resolution = wasted_resolution best_fit = (width, height)
return best_fit
def resize_and_pad_image(image, target_resolution): """ Resize and pad an image to a target resolution while maintaining aspect ratio.
Args: image (PIL.Image.Image): The input image. target_resolution (tuple): The target resolution (width, height) of the image.
Returns: PIL.Image.Image: The resized and padded image. """ original_width, original_height = image.size target_width, target_height = target_resolution
# Determine which dimension (width or height) to fill scale_w = target_width / original_width scale_h = target_height / original_height
if scale_w < scale_h: # Width will be filled completely new_width = target_width new_height = min(math.ceil(original_height * scale_w), target_height) else: # Height will be filled completely new_height = target_height new_width = min(math.ceil(original_width * scale_h), target_width)
# Resize the image resized_image = image.resize((new_width, new_height))
# Create a new image with the target size and paste the resized image onto it new_image = Image.new("RGB", (target_width, target_height), (0, 0, 0)) paste_x = (target_width - new_width) // 2 paste_y = (target_height - new_height) // 2 new_image.paste(resized_image, (paste_x, paste_y))
return new_image
def divide_to_patches(image, patch_size): """ Divides an image into patches of a specified size.
Args: image (PIL.Image.Image): The input image. patch_size (int): The size of each patch.
Returns: list: A list of PIL.Image.Image objects representing the patches. """ patches = [] width, height = image.size for i in range(0, height, patch_size): for j in range(0, width, patch_size): box = (j, i, j + patch_size, i + patch_size) patch = image.crop(box) patches.append(patch)
return patches
def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size): """ Calculate the shape of the image patch grid after the preprocessing for images of any resolution.
Args: image_size (tuple): The size of the input image in the format (width, height). grid_pinpoints (str): A string representation of a list of possible resolutions. patch_size (int): The size of each image patch.
Returns: tuple: The shape of the image patch grid in the format (width, height). """ if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints: assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]" # Use regex to extract the range from the input string matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints) range_start = tuple(map(int, matches[0])) range_end = tuple(map(int, matches[-1])) # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1]) grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)] # Multiply all elements by patch_size grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints] if type(grid_pinpoints) is list: possible_resolutions = grid_pinpoints else: possible_resolutions = ast.literal_eval(grid_pinpoints) width, height = select_best_resolution(image_size, possible_resolutions) return width // patch_size, height // patch_size
def process_anyres_image(image, processor, grid_pinpoints): """ Process an image with variable resolutions.
Args: image (PIL.Image.Image): The input image to be processed. processor: The image processor object. grid_pinpoints (str): A string representation of a list of possible resolutions.
Returns: torch.Tensor: A tensor containing the processed image patches. """ # Convert grid_pinpoints from string to list if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints: try: patch_size = processor.size[0] except Exception as e: patch_size = processor.size["shortest_edge"] assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]" # Use regex to extract the range from the input string matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints) range_start = tuple(map(int, matches[0])) range_end = tuple(map(int, matches[-1])) # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1]) grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)] # Multiply all elements by patch_size grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
if type(grid_pinpoints) is list: possible_resolutions = grid_pinpoints else: possible_resolutions = ast.literal_eval(grid_pinpoints) best_resolution = select_best_resolution(image.size, possible_resolutions) image_padded = resize_and_pad_image(image, best_resolution)
patches = divide_to_patches(image_padded, processor.crop_size["height"])
# FIXME: this seems to be a bug that it resizes instead of pad. # but to keep it consistent with previous, i will keep it as it is # TODO: uncomment below to ablate with the padding if isinstance(processor.size, dict): shortest_edge = processor.size["shortest_edge"] else: shortest_edge = min(processor.size) image_original_resize = image.resize((shortest_edge, shortest_edge)) # image_padded_square = expand2square(image, tuple(int(x*255) for x in processor.image_mean)) # image_original_resize = image_padded_square.resize((processor.size['shortest_edge'], processor.size['shortest_edge']))
image_patches = [image_original_resize] + patches image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches] return torch.stack(image_patches, dim=0)
def load_image_from_base64(image): return Image.open(BytesIO(base64.b64decode(image)))
def expand2square(pil_img, background_color): width, height = pil_img.size if width == height: return pil_img elif width > height: result = Image.new(pil_img.mode, (width, width), background_color) result.paste(pil_img, (0, (width - height) // 2)) return result else: result = Image.new(pil_img.mode, (height, height), background_color) result.paste(pil_img, ((height - width) // 2, 0)) return result
def process_images(images, image_processor, model_cfg): image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None) new_images = [] if image_aspect_ratio == "highres": for image in images: image = process_highres_image(image, image_processor, model_cfg.image_grid_pinpoints) new_images.append(image) elif image_aspect_ratio == "anyres" or "anyres_max" in image_aspect_ratio: for image in images: image = process_anyres_image(image, image_processor, model_cfg.image_grid_pinpoints) new_images.append(image) elif image_aspect_ratio == "crop_split": for image in images: image = process_highres_image_crop_split(image, model_cfg, image_processor) new_images.append(image) elif image_aspect_ratio == "pad": for image in images: image = expand2square(image, tuple(int(x * 255) for x in image_processor.image_mean)) image = image_processor.preprocess(image, return_tensors="pt")["pixel_values"][0] new_images.append(image) else: return image_processor.preprocess(images, return_tensors="pt")["pixel_values"] if all(x.shape == new_images[0].shape for x in new_images): new_images = torch.stack(new_images, dim=0) return new_images
def tokenizer_image_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None): prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split("<image>")]
def insert_separator(X, sep): return [ele for sublist in zip(X, [sep] * len(X)) for ele in sublist][:-1]
input_ids = [] offset = 0 if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id: offset = 1 input_ids.append(prompt_chunks[0][0])
for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)): input_ids.extend(x[offset:])
if return_tensors is not None: if return_tensors == "pt": return torch.tensor(input_ids, dtype=torch.long) raise ValueError(f"Unsupported tensor type: {return_tensors}") return input_ids
def get_model_name_from_path(model_path): model_path = model_path.strip("/") model_paths = model_path.split("/") if model_paths[-1].startswith("checkpoint-"): return model_paths[-2] + "_" + model_paths[-1] else: return model_paths[-1]
class KeywordsStoppingCriteria(StoppingCriteria): def __init__(self, keywords, tokenizer, input_ids): self.keywords = keywords self.keyword_ids = [] for keyword in keywords: cur_keyword_ids = tokenizer(keyword).input_ids if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id: cur_keyword_ids = cur_keyword_ids[1:] self.keyword_ids.append(torch.tensor(cur_keyword_ids)) self.tokenizer = tokenizer self.start_len = input_ids.shape[1]
def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool: assert output_ids.shape[0] == 1, "Only support batch size 1 (yet)" # TODO offset = min(output_ids.shape[1] - self.start_len, 3) self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids] for keyword_id in self.keyword_ids: if output_ids[0, -keyword_id.shape[0] :] == keyword_id: return True outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0] for keyword in self.keywords: if keyword in outputs: return True return False1234567891011import os
AVAILABLE_MODELS = { "llava_llada": "LlavaLLaDAModelLM, LlavaLLaDAConfig",}
for model_name, model_classes in AVAILABLE_MODELS.items(): try: exec(f"from .language_model.{model_name} import {model_classes}") except Exception as e: print(f"Failed to import {model_name} from llava.language_model.{model_name}. Error: {e}")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647"""Usage:python3 -m fastchat.model.apply_delta --base ~/model_weights/llama-7b --target ~/model_weights/vicuna-7b --delta lmsys/vicuna-7b-delta"""
import argparse
import torchfrom tqdm import tqdmfrom transformers import AutoTokenizer, AutoModelForCausalLMfrom llava import LlavaLlamaForCausalLM
def apply_delta(base_model_path, target_model_path, delta_path): print("Loading base model") base = AutoModelForCausalLM.from_pretrained(base_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
print("Loading delta") delta = LlavaLlamaForCausalLM.from_pretrained(delta_path, torch_dtype=torch.float16, low_cpu_mem_usage=True) delta_tokenizer = AutoTokenizer.from_pretrained(delta_path)
print("Applying delta") for name, param in tqdm(delta.state_dict().items(), desc="Applying delta"): if name not in base.state_dict(): assert name in ["model.mm_projector.weight", "model.mm_projector.bias"], f"{name} not in base model" continue if param.data.shape == base.state_dict()[name].shape: param.data += base.state_dict()[name] else: assert name in ["model.embed_tokens.weight", "lm_head.weight"], f"{name} dimension mismatch: {param.data.shape} vs {base.state_dict()[name].shape}" bparam = base.state_dict()[name] param.data[: bparam.shape[0], : bparam.shape[1]] += bparam
print("Saving target model") delta.save_pretrained(target_model_path) delta_tokenizer.save_pretrained(target_model_path)
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--base-model-path", type=str, required=True) parser.add_argument("--target-model-path", type=str, required=True) parser.add_argument("--delta-path", type=str, required=True)
args = parser.parse_args()
apply_delta(args.base_model_path, args.target_model_path, args.delta_path)rl_lavida_revvideo_orig10k_4gpu_len128/temp_data/outputs-rl-...rl_lavida_revvideo_orig10k_4gpu_len128.ckpt.optimized-video_reversal_sft_train_cleaned_10k-step10.jsonAdded
rl_lavida_revvideo_orig10k_4gpu_len128/temp_data/outputs-rl-...rl_lavida_revvideo_orig10k_4gpu_len128.ckpt.optimized-video_reversal_sft_train_cleaned_10k-step6.jsonAdded
rl_lavida_revvideo_orig10k_4gpu_len128/temp_data/outputs-rl-...rl_lavida_revvideo_orig10k_4gpu_len128.ckpt.optimized-video_reversal_sft_train_cleaned_10k-step9.jsonAdded
rl_lladav_video_reversal_wo_ub_reward/config.yamlAdded+102
rl_lladav_video_reversal_wo_ub_reward/results/all_rewards.csvAdded+62
rl_lladav_video_reversal_wo_ub_reward/results/results-eval-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train.txtAdded
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step10.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step11.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step12.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step13.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step14.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step16.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step17.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step18.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step19.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step20.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step21.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step23.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step24.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step25.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step27.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step28.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step3.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step30.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step4.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step5.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step6.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step7.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step8.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step9.txtAdded+2
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train.txtAdded
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-.data4.runqing.dLLM-RL.sft_lladav_video_reversal_3_21.ckpt.optimized-video_reversal_rl_train-step1.txtAdded+2
train/eval_lavida_revvideo.pyAdded+390
train/eval_llava_next_revvideo.pyAdded+325
train/init_lladav_value_model.pyAdded+164
train/init_mmada_v_value_model.pyAdded+162
train/init_sdar_value_model.pyAdded+194
train/init_trado_value_model.pyAdded+194
train/llava/__init__.pyAdded
train/llava/cache/Cache.pyAdded+83
train/llava/cache/Config.pyAdded+9
train/llava/cache/__init__.pyAdded+4
train/llava/constants.pyAdded+12
train/llava/conversation.pyAdded+624
train/llava/hooks/__init__.pyAdded+6
train/llava/hooks/cache_hook_LLaDA_V.pyAdded+619
train/llava/hooks/fast_dllm_hook.pyAdded+507
train/llava/mm_utils.pyAdded+396
train/llava/model/__init__.pyAdded+11
train/llava/model/apply_delta.pyAdded+47